diff --git a/architecture-baseline.json b/architecture-baseline.json index 48077af5..1f6d9e60 100644 --- a/architecture-baseline.json +++ b/architecture-baseline.json @@ -6,13 +6,12 @@ ], "oversize": { "control-plane/examples/cp_replay.rs": 946, - "control-plane/src/config/impl_config.rs": 520, + "control-plane/src/config/impl_config/impl_config_2_2.rs": 436, "control-plane/src/ggml_bridge/tests.rs": 1286, "control-plane/src/gguf_f32_stream/tests.rs": 909, "control-plane/src/main.rs": 1156, "control-plane/src/prepare_preview/tests.rs": 808, "control-plane/src/prometheus.rs": 441, - "control-plane/src/responses.rs": 2780, "control-plane/src/responses/tests.rs": 2961, "control-plane/src/service_install.rs": 436, "control-plane/src/vision.rs": 402, @@ -30,56 +29,29 @@ "crates/cpu-worker/tests/serve_loop.rs": 477, "crates/cuda-driver/src/api.rs": 423, "crates/cuda-driver/src/closed_kernels/tests.rs": 405, - "crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels.rs": 421, "crates/cuda-driver/src/experimental.rs": 407, - "crates/cuda-driver/src/experimental_gpu/impl_experimental.rs": 577, "crates/cuda-driver/src/ffi.rs": 1897, - "crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix.rs": 539, - "crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix.rs": 401, "crates/cuda-driver/src/gdn_native_batch.rs": 557, - "crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix.rs": 690, - "crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice.rs": 736, - "crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread.rs": 495, - "crates/cuda-driver/src/gr_native_batch/impl_grnativebatch.rs": 524, + "crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2_2.rs": 618, "crates/cuda-driver/src/lib.rs": 3508, - "crates/cuda-driver/src/mapped_expert_bank/impl_mappedexpertbank.rs": 515, - "crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer.rs": 594, - "crates/cuda-driver/src/mmq_original_ring/impl_ring.rs": 634, - "crates/cuda-driver/src/mmq_resident/impl_mmqworkspace.rs": 549, "crates/cuda-driver/src/mmq_resident_gpu.rs": 517, "crates/cuda-driver/src/moe_prefill_batch.rs": 476, - "crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix.rs": 652, - "crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter.rs": 492, - "crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2.rs": 918, - "crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_3.rs": 545, + "crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2/impl_originalmtpfullforward.rs": 621, "crates/cuda-driver/src/mtp_original_full_symbols.rs": 445, - "crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8.rs": 930, "crates/cuda-driver/src/mtp_original_int8_ffi.rs": 543, - "crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill.rs": 1180, - "crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill.rs": 1285, + "crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_4.rs": 676, + "crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_4.rs": 622, "crates/cuda-driver/src/native_head.rs": 533, - "crates/cuda-driver/src/native_head/impl_originalnativeheadrows.rs": 479, - "crates/cuda-driver/src/native_parity/impl_nativeparity.rs": 428, - "crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice.rs": 1257, - "crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache.rs": 864, - "crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource.rs": 844, "crates/cuda-driver/src/original_gpu_schedule_ffi.rs": 454, - "crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice.rs": 474, - "crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor.rs": 447, "crates/cuda-driver/src/original_mtp_rt/tests.rs": 435, - "crates/cuda-driver/src/original_sampler/impl_originalsampler.rs": 678, "crates/cuda-driver/src/original_verify_window_gr/tests.rs": 506, "crates/cuda-driver/src/original_verify_window_moe/tests.rs": 720, "crates/cuda-driver/src/original_verify_window_planner/tests.rs": 411, "crates/cuda-driver/src/original_verify_window_qsa/tests.rs": 652, "crates/cuda-driver/src/ple_batch_ffi.rs": 625, - "crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue.rs": 446, "crates/cuda-driver/src/prefill_stage_gdn_gpu.rs": 420, - "crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv.rs": 480, "crates/cuda-driver/src/qwen_dispatch.rs": 2003, - "crates/cuda-driver/src/qwen_dispatch/impl_context.rs": 1423, "crates/cuda-driver/src/qwen_ffi.rs": 1696, - "crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace.rs": 483, "crates/cuda-driver/src/sm86_table.rs": 933, "crates/cuda-driver/tests/mock_driver.rs": 1560, "crates/cuda-driver/tests/original_serve_preflight_probe.rs": 784, @@ -111,12 +83,10 @@ "crates/gptoss/tests/synthetic_model.rs": 922, "crates/igpu/src/lib.rs": 1386, "crates/igpu/src/shaders.rs": 440, - "crates/leleka-memory/src/governor/impl_governor.rs": 739, "crates/leleka-memory/src/lock.rs": 432, "crates/leleka-runtime/src/backend.rs": 3770, "crates/leleka-runtime/src/backend_original_serve.rs": 1115, "crates/leleka-runtime/src/conversation/cache/tests.rs": 407, - "crates/leleka-runtime/src/conversation/manager/impl_conversationmanager.rs": 413, "crates/leleka-runtime/src/conversation/manager_tests.rs": 1129, "crates/leleka-runtime/src/conversation/snapshot_tests.rs": 1596, "crates/leleka-runtime/src/gpu_proofs/backend_original_serve_memory_smoke.rs": 851, @@ -125,34 +95,17 @@ "crates/leleka-runtime/src/gpu_proofs/native_down_candidate_only.rs": 1648, "crates/leleka-runtime/src/gpu_proofs/native_down_public_pair.rs": 540, "crates/leleka-runtime/src/model_binding/qwen4exp_kar_ple.rs": 1026, - "crates/leleka-runtime/src/model_binding/qwen4exp_moe_expert/impl_modelbinding.rs": 405, "crates/leleka-runtime/src/model_binding/qwen4exp_mtp.rs": 1124, - "crates/leleka-runtime/src/prefix_cache/store/impl_prefixstore.rs": 563, "crates/leleka-runtime/src/prefix_cache/store/tests.rs": 582, - "crates/leleka-runtime/src/qwen_forward/cache_profile_fill/impl_moeweightcache.rs": 411, - "crates/leleka-runtime/src/qwen_forward/dense_weight_cache/impl_denseweightcache.rs": 1482, - "crates/leleka-runtime/src/qwen_forward/executor/impl_qwenforward.rs": 512, - "crates/leleka-runtime/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor.rs": 478, - "crates/leleka-runtime/src/qwen_forward/executor_prefill_chunk/impl_qwenforward.rs": 1266, + "crates/leleka-runtime/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3.rs": 980, "crates/leleka-runtime/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn.rs": 466, - "crates/leleka-runtime/src/qwen_forward/gdn_chain/impl_chain.rs": 770, - "crates/leleka-runtime/src/qwen_forward/gdn_chunk_device/impl_gdnchunkdevice.rs": 538, - "crates/leleka-runtime/src/qwen_forward/gdn_state_mirror/impl_gdnstatemirror.rs": 450, "crates/leleka-runtime/src/qwen_forward/gr.rs": 1036, "crates/leleka-runtime/src/qwen_forward/kar_ple_cache.rs": 730, - "crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache.rs": 2047, - "crates/leleka-runtime/src/qwen_forward/mtp_decode/impl_mtpdecoder.rs": 617, "crates/leleka-runtime/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn.rs": 454, "crates/leleka-runtime/src/qwen_forward/original_serve_engine/tests.rs": 668, - "crates/leleka-runtime/src/qwen_forward/original_serve_prefix/impl_prefixserve.rs": 417, "crates/leleka-runtime/src/qwen_forward/original_serve_prefix/tests.rs": 674, - "crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack.rs": 1239, "crates/leleka-runtime/src/qwen_forward/original_spec_controller/tests.rs": 813, - "crates/leleka-runtime/src/qwen_forward/output/impl_outputstage.rs": 503, - "crates/leleka-runtime/src/qwen_forward/session/impl_qwensteptxn.rs": 445, "crates/leleka-runtime/src/qwen_forward/session/tests.rs": 538, - "crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn.rs": 1991, - "crates/leleka-runtime/src/qwen_forward/session_chunk_verify/impl_qwenchunktxn.rs": 584, "crates/model-format/src/gguf.rs": 1099, "crates/model-format/src/ple_reader/tests.rs": 750, "crates/model-format/src/qwen4exp.rs": 625, diff --git a/control-plane/src/config/impl_config.rs b/control-plane/src/config/impl_config.rs index 7c14a269..93f6ef16 100644 --- a/control-plane/src/config/impl_config.rs +++ b/control-plane/src/config/impl_config.rs @@ -3,518 +3,6 @@ #[allow(unused_imports)] use super::*; -impl Config { - pub fn load() -> Result> { - Self::load_with_path(None) - } - - /// An explicit CLI config path takes precedence over STRATA_CONFIG. - pub fn load_with_path(path: Option<&Path>) -> Result> { - let config_path = path - .map(|p| p.as_os_str().to_owned()) - .or_else(|| env::var_os("STRATA_CONFIG")) - .map(PathBuf::from); - let file = match &config_path { - Some(path) => serde_json::from_str::(&fs::read_to_string(path)?)?, - None => FileConfig::default(), - }; - - crate::asset_bundle::validate(&file.assets)?; - if let Some(native) = &file.native_model { - native.validate(&file.assets)?; - } - let bind: SocketAddr = optional_env("STRATA_BIND")? - .or(file.bind) - .unwrap_or_else(|| "127.0.0.1:8081".to_owned()) - .parse()?; - - let max_in_flight_requests = optional_env("STRATA_MAX_IN_FLIGHT_REQUESTS")? - .map(|value| value.parse::()) - .transpose()? - .or(file.max_in_flight_requests) - .unwrap_or(crate::lifecycle::DEFAULT_MAX_IN_FLIGHT_REQUESTS); - crate::lifecycle::validate_capacity(max_in_flight_requests)?; - - let prompt_date = optional_env("STRATA_PROMPT_DATE")? - .or(file.prompt_date) - .map(|text| crate::responses::PromptDate::parse(&text)) - .transpose()? - .unwrap_or(crate::responses::PromptDate::Utc); - - let queue_timeout_s = optional_env("STRATA_QUEUE_TIMEOUT_S")? - .map(|value| value.parse::()) - .transpose()? - .or(file.queue_timeout_s); - if queue_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) { - return Err("queue_timeout_s must be between 1 and 86400 when configured".into()); - } - - let shutdown_grace_s = optional_env("STRATA_SHUTDOWN_GRACE_S")? - .map(|value| value.parse::()) - .transpose()? - .or(file.shutdown_grace_s) - .unwrap_or(0); - if shutdown_grace_s > 20 { - return Err("shutdown_grace_s must be between 0 and 20".into()); - } - - let executable = env::var_os("STRATA_ENGINE_EXE").or_else(|| { - file.engine - .as_ref() - .map(|engine| OsString::from(&engine.executable)) - }); - let args_override = optional_env("STRATA_ENGINE_ARGS_JSON")? - .map(|value| serde_json::from_str::>(&value)) - .transpose()?; - let timeout_override = optional_env("STRATA_STARTUP_TIMEOUT_S")? - .map(|value| value.parse::()) - .transpose()?; - let configured_args = file.engine.as_ref().map(|engine| engine.args.clone()); - let args = args_override.or(configured_args).unwrap_or_default(); - let startup_timeout_s = timeout_override - .or_else(|| { - file.engine - .as_ref() - .and_then(|engine| engine.startup_timeout_s) - }) - .unwrap_or(600); - - if !(1..=3600).contains(&startup_timeout_s) { - return Err("startup_timeout_s must be between 1 and 3600".into()); - } - let max_restarts = optional_env("STRATA_MAX_WORKER_RESTARTS")? - .map(|value| value.parse::()) - .transpose()? - .or_else(|| file.engine.as_ref().and_then(|engine| engine.max_restarts)) - .unwrap_or(3); - if max_restarts > 3 { - return Err("max_restarts must be between 0 and 3".into()); - } - let generation_timeout_s = optional_env("STRATA_GENERATION_TIMEOUT_S")? - .map(|value| value.parse::()) - .transpose()? - .or_else(|| { - file.engine - .as_ref() - .and_then(|engine| engine.generation_timeout_s) - }); - if generation_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) { - return Err("generation_timeout_s must be between 1 and 86400".into()); - } - let engine_file = file.engine.as_ref(); - let mut args = args; - if let Some(vector) = engine_file.and_then(|engine| engine.control_vector.as_ref()) { - if args - .iter() - .any(|arg| arg.starts_with("--control-vector") || arg.starts_with("--cvec-")) - { - return Err("control_vector owns the --control-vector*/--cvec-* arguments; remove them from engine args".into()); - } - args.extend(vector.engine_args()?); - } - let stall_timeout_s = engine_file.and_then(|engine| engine.stall_timeout_s); - if stall_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) { - return Err("stall_timeout_s must be between 1 and 86400".into()); - } - let idle_unload_s = engine_file.and_then(|engine| engine.idle_unload_s); - if idle_unload_s.is_some_and(|seconds| !seconds.is_finite() || seconds < 0.0) { - return Err("idle_unload_s must be a non-negative number".into()); - } - let worker = match executable { - Some(executable) if !executable.is_empty() => Some(WorkerConfig { - executable, - cuda_memory: None, - args, - startup_timeout: Duration::from_secs(startup_timeout_s), - generation_timeout: generation_timeout_s.map(Duration::from_secs), - max_restarts, - lazy: engine_file.is_some_and(|engine| engine.lazy_load), - stall_timeout: stall_timeout_s.map(Duration::from_secs), - before_load: engine_file.and_then(|engine| engine.before_load.clone()), - min_free_vram_mib: engine_file - .and_then(|engine| engine.min_free_vram_mib) - .unwrap_or(0), - vision: None, - }), - Some(_) => return Err("engine executable cannot be empty".into()), - None if !args.is_empty() => return Err("engine args require an executable".into()), - None => None, - }; - let extra = file - .engine - .as_ref() - .map(|engine| engine.extra_workers.as_slice()) - .unwrap_or_default(); - if !extra.is_empty() { - if file.runtime.is_some() { - return Err("extra_workers and runtime are mutually exclusive: the pool feeds stdio engine children, a runtime block serves in front of one leleka-inference".into()); - } - if engine_file.is_some_and(|engine| { - engine.lazy_load || engine.idle_unload_s.is_some_and(|seconds| seconds > 0.0) - }) { - return Err("extra_workers cannot be combined with lazy_load or idle_unload_s: the pool dispatcher does not load or unload workers on demand".into()); - } - if file.vision.is_some() { - return Err("extra_workers cannot be combined with vision: images are read by the single supervised worker".into()); - } - } - if extra.len() > 7 { - return Err("at most 7 extra_workers".into()); - } - let mut extra_workers = Vec::with_capacity(extra.len()); - for entry in extra { - let Some(main) = worker.as_ref() else { - return Err("extra_workers require an engine executable".into()); - }; - if entry.executable.is_empty() { - return Err("an extra worker executable cannot be empty".into()); - } - extra_workers.push(WorkerConfig { - executable: OsString::from(&entry.executable), - cuda_memory: None, - args: entry.args.clone(), - startup_timeout: main.startup_timeout, - generation_timeout: main.generation_timeout, - max_restarts: main.max_restarts, - lazy: false, - stall_timeout: main.stall_timeout, - before_load: None, - min_free_vram_mib: 0, - vision: None, - }); - } - let mut tokenizer_dir = env::var_os("STRATA_TOKENIZER_DIR") - .map(PathBuf::from) - .or_else(|| { - file.engine - .as_ref() - .and_then(|engine| engine.tokenizer_dir.clone()) - }); - if let Some(native) = &file.native_model { - let worker = worker - .as_ref() - .ok_or("native_model requires an engine executable")?; - if tokenizer_dir.is_some() - || worker.args.iter().any(|arg| { - ["--pack", "--native", "--gguf"] - .iter() - .any(|key| arg == key || arg.starts_with(&format!("{key}="))) - }) - { - return Err("native_model owns pack/source/tokenizer settings; remove conflicting overrides".into()); - } - tokenizer_dir = Some(native.output.join("tokenizer")); - } - if file.runtime.is_some() { - if worker.is_some() { - return Err("runtime and engine are mutually exclusive: the API serves in front of either a stdio engine child or a running leleka-inference".into()); - } - if file.native_model.is_some() - || file.mtp_pack.is_some() - || file.vision.is_some() - || file.gpu_requirement.is_some() - || file.cuda_memory.is_some() - || file.engine_probe - { - return Err("runtime cannot be combined with native_model, mtp_pack, vision, gpu_requirement, cuda_memory or engine_probe: the runtime process owns the model and the GPU".into()); - } - } - let runtime = file - .runtime - .map(crate::runtime_config::FileRuntime::resolve) - .transpose()?; - if let Some(runtime) = &runtime { - tokenizer_dir.get_or_insert_with(|| runtime.tokenizer_dir.clone()); - } - if worker.is_none() && runtime.is_none() && tokenizer_dir.is_some() { - return Err("tokenizer_dir requires an engine executable".into()); - } - let gptoss_gguf = env::var_os("STRATA_GPTOSS_GGUF") - .map(PathBuf::from) - .or_else(|| { - file.engine - .as_ref() - .and_then(|engine| engine.gptoss_gguf.clone()) - }); - if gptoss_gguf.is_some() && file.vision.is_some() { - return Err("vision is not available for the gpt-oss family (gptoss_gguf)".into()); - } - if gptoss_gguf.is_some() && (worker.is_none() || tokenizer_dir.is_some()) { - return Err( - "gptoss_gguf requires an engine executable and excludes tokenizer_dir".into(), - ); - } - if worker.is_none() && file.gpu_requirement.is_some() { - return Err("gpu_requirement requires an engine executable".into()); - } - if let Some(policy) = file.cuda_memory { - policy.validate()?; - if file.gpu_requirement.is_none() { - return Err("cuda_memory requires an explicit gpu_requirement".into()); - } - } - if worker.is_none() && file.engine_probe { - return Err("engine_probe requires an engine executable".into()); - } - if let Some(mtp) = &file.mtp_pack { - let worker = worker - .as_ref() - .ok_or("mtp_pack requires an engine executable")?; - if !file.assets.iter().any(|asset| &asset.directory == mtp) { - return Err("mtp_pack must exactly match a pinned assets bundle directory".into()); - } - if mtp.to_str().is_none() - || worker - .args - .iter() - .any(|arg| arg == "--mtp" || arg.starts_with("--mtp=")) - { - return Err( - "mtp_pack requires UTF-8 path and owns --mtp; remove conflicting engine args" - .into(), - ); - } - } - let model = optional_env("STRATA_MODEL_ID")?.or(file.model); - if model.as_ref().is_some_and(|id| { - id.is_empty() - || id.len() > 180 - || !id - .bytes() - .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.')) - }) { - return Err( - "model ID requires 1..180 ASCII letters, digits, dots, hyphens or underscores" - .into(), - ); - } - let api_key = env::var_os("STRATA_API_KEY_FILE") - .map(PathBuf::from) - .or(file.api_key_file) - .map(|path| crate::auth::ApiKey::from_file(&path).map(std::sync::Arc::new)) - .transpose()?; - let response_history_dir = env::var_os("STRATA_RESPONSE_HISTORY_DIR") - .map(PathBuf::from) - .or(file.response_history_dir); - if response_history_dir.as_ref().is_some_and(|p| { - !p.is_absolute() - || p.file_name().is_none() - || p.components() - .any(|c| matches!(c, std::path::Component::ParentDir)) - }) { - return Err( - "response_history_dir must be an absolute non-root path without '..'".into(), - ); - } - let aliases = match &file.aliases { - None => Vec::new(), - Some(value) => leleka_serving_policy::shared::normalize_aliases( - value, - model.as_deref().unwrap_or(""), - ) - .map_err(|message| format!("config {message}"))?, - }; - if aliases.iter().any(|alias| { - alias.len() > 180 - || !alias - .bytes() - .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.')) - }) { - return Err( - "aliases require 1..180 ASCII letters, digits, dots, hyphens or underscores".into(), - ); - } - let cors_origins = leleka_serving_policy::cors::origins_of( - file.cors_origins - .as_ref() - .unwrap_or(&serde_json::Value::Null), - "cors_origins", - true, - )?; - let trusted_origins = leleka_serving_policy::cors::origins_of( - file.trusted_origins - .as_ref() - .unwrap_or(&serde_json::Value::Null), - "trusted_origins", - false, - )?; - let sampling = leleka_serving_policy::shared::sampling_defaults_from_config( - file.sampling.as_ref().unwrap_or(&serde_json::Value::Null), - )?; - for ignored in &sampling.ignored { - crate::elog!("config sampling.{ignored}: unknown key, ignored"); - } - if let Some(value) = &file.reasoning_budget_tokens { - leleka_serving_policy::reasoning::parse_budget(None, Some(value)) - .map_err(|message| format!("config {message}"))?; - } - let shared_settings_file = file.shared_settings_file.clone().or_else(|| { - config_path - .as_deref() - .map(crate::settings::default_shared_path) - }); - let mut mcp_servers = std::collections::BTreeMap::new(); - let null = serde_json::Value::Null; - mcp_servers.extend(crate::mcp::servers_from( - file.mcp_servers.as_ref().unwrap_or(&null), - "config mcp_servers", - )?); - mcp_servers.extend(crate::mcp::servers_from( - file.mcp_servers_desktop.as_ref().unwrap_or(&null), - "config mcpServers", - )?); - if let Some(path) = &file.mcp_config_file { - // Claude Desktop's format; a name in both takes this file's entry. - let location = format!("mcp_config_file {}", path.display()); - let text = std::fs::read_to_string(path) - .map_err(|error| format!("[strata] {location}: {error}"))?; - let data: serde_json::Value = serde_json::from_str(text.trim_start_matches('\u{feff}')) - .map_err(|error| format!("[strata] {location}: {error}"))?; - let block = data - .get("mcpServers") - .or_else(|| data.get("mcp_servers")) - .ok_or_else(|| { - format!("[strata] {location}: expected {{\"mcpServers\": {{...}}}}") - })?; - mcp_servers.extend(crate::mcp::servers_from(block, &location)?); - } - let mcp_settings = crate::mcp::settings_from(file.mcp.as_ref().unwrap_or(&null))?; - if let Some(vision) = &file.vision { - vision.validate()?; - if worker.is_none() { - return Err("vision requires an engine executable".into()); - } - if worker.as_ref().is_some_and(|worker| worker.lazy) { - return Err("lazy loading is text-only; disable vision in the config".into()); - } - } - Ok(Self { - vision: file.vision, - mcp_servers, - mcp_settings, - aliases, - cors_origins, - trusted_origins, - api_monitor: file.api_monitor == Some(true), - tool_call_recovery: match optional_env("STRATA_TOOL_CALL_RECOVERY")?.as_deref() { - Some("1" | "true") => true, - Some("0" | "false") => false, - Some(other) => { - return Err(format!( - "STRATA_TOOL_CALL_RECOVERY must be 1, true, 0 or false, not {other:?}" - ) - .into()); - } - None => file.tool_call_recovery == Some(true), - }, - sampling, - reasoning_budget_tokens: file.reasoning_budget_tokens, - shared_settings_file, - idle_unload: idle_unload_s - .filter(|seconds| *seconds > 0.0) - .map(Duration::from_secs_f64), - mtp_pack: file.mtp_pack, - response_history_dir, - assets: file.assets, - native_model: file.native_model, - gpu_requirement: file.gpu_requirement, - cuda_memory: file.cuda_memory, - host_checked: false, - engine_probe: file.engine_probe, - shutdown_grace: Duration::from_secs(shutdown_grace_s), - queue_timeout: queue_timeout_s.map(Duration::from_secs), - max_in_flight_requests, - api_key, - bind, - model, - worker, - runtime, - extra_workers, - prompt_date, - tokenizer_dir, - gptoss_gguf, - }) - } - - /// Complete acquisition/preparation before the listener or worker starts. - pub async fn provision(&mut self) -> Result<(), Box> { - self.check_host().await?; - self.prepare_assets().await - } - - /// Prepare a switch target while the previous runtime still owns GPU memory. - /// Serving must subsequently perform full host admission; never mark it checked here. - pub async fn prepare_for_switch(&mut self) -> Result<(), Box> { - if let Some(requirement) = self.gpu_requirement { - crate::doctor::check(requirement).await?; - } - self.prepare_assets().await - } - - pub(super) async fn prepare_assets(&mut self) -> Result<(), Box> { - if self.engine_probe { - let worker = self - .worker - .as_ref() - .ok_or("engine_probe requires an engine executable")?; - crate::engine_probe::check(&worker.executable).await?; - } - // Parse all manifests before any acquisition, including the source model. - if let Some(native) = &self.native_model { - crate::model::Manifest::load(&native.manifest).await?; - } - crate::asset_bundle::provision(&self.assets).await?; - if let Some(mtp) = self.mtp_pack.clone() { - let checked = mtp.clone(); - tokio::task::spawn_blocking(move || crate::mtp_pack::check(&checked)).await??; - self.worker - .as_mut() - .ok_or("mtp_pack requires worker")? - .args - .extend([ - "--mtp".to_owned(), - mtp.to_str().ok_or("MTP path must be UTF-8")?.to_owned(), - ]); - } - if let Some(native) = &self.native_model { - let primary = native.ensure().await?; - let output = native.output.to_str().ok_or("pack path must be UTF-8")?; - let source = primary.to_str().ok_or("source path must be UTF-8")?; - self.worker - .as_mut() - .ok_or("native_model requires worker")? - .args - .extend([ - "--pack".to_owned(), - output.to_owned(), - "--native".to_owned(), - source.to_owned(), - ]); - } - Ok(()) - } - - /// Point-in-time driver policy check; never creates a CUDA context. - pub async fn check_host(&mut self) -> Result<(), Box> { - if let Some(requirement) = self.gpu_requirement - && !self.host_checked - { - crate::doctor::check(requirement).await?; - if let Some(policy) = self.cuda_memory { - let selected = policy.select().await?; - crate::elog!( - "cuda_memory: selected {} for declared {} + {} MiB; allocation is not reserved", - selected.uuid, - policy.required_mib, - policy.reserve_mib - ); - self.worker - .as_mut() - .ok_or("cuda_memory requires worker")? - .cuda_memory = Some(selected); - } - self.host_checked = true; - } - Ok(()) - } -} +mod impl_config_2; +mod impl_config_2_2; +mod impl_config_3; diff --git a/control-plane/src/config/impl_config/impl_config_2.rs b/control-plane/src/config/impl_config/impl_config_2.rs new file mode 100644 index 00000000..8ac84f3d --- /dev/null +++ b/control-plane/src/config/impl_config/impl_config_2.rs @@ -0,0 +1,10 @@ +//! Moved out of the parent module by STRA-338: impl Config. + +#[allow(unused_imports)] +use super::*; + +impl Config { + pub fn load() -> Result> { + Self::load_with_path(None) + } +} diff --git a/control-plane/src/config/impl_config/impl_config_2_2.rs b/control-plane/src/config/impl_config/impl_config_2_2.rs new file mode 100644 index 00000000..6011904a --- /dev/null +++ b/control-plane/src/config/impl_config/impl_config_2_2.rs @@ -0,0 +1,434 @@ +//! Moved out of the parent module by STRA-338: impl Config (2). + +#[allow(unused_imports)] +use super::*; + +impl Config { + /// An explicit CLI config path takes precedence over STRATA_CONFIG. + pub fn load_with_path(path: Option<&Path>) -> Result> { + let config_path = path + .map(|p| p.as_os_str().to_owned()) + .or_else(|| env::var_os("STRATA_CONFIG")) + .map(PathBuf::from); + let file = match &config_path { + Some(path) => serde_json::from_str::(&fs::read_to_string(path)?)?, + None => FileConfig::default(), + }; + + crate::asset_bundle::validate(&file.assets)?; + if let Some(native) = &file.native_model { + native.validate(&file.assets)?; + } + let bind: SocketAddr = optional_env("STRATA_BIND")? + .or(file.bind) + .unwrap_or_else(|| "127.0.0.1:8081".to_owned()) + .parse()?; + + let max_in_flight_requests = optional_env("STRATA_MAX_IN_FLIGHT_REQUESTS")? + .map(|value| value.parse::()) + .transpose()? + .or(file.max_in_flight_requests) + .unwrap_or(crate::lifecycle::DEFAULT_MAX_IN_FLIGHT_REQUESTS); + crate::lifecycle::validate_capacity(max_in_flight_requests)?; + + let prompt_date = optional_env("STRATA_PROMPT_DATE")? + .or(file.prompt_date) + .map(|text| crate::responses::PromptDate::parse(&text)) + .transpose()? + .unwrap_or(crate::responses::PromptDate::Utc); + + let queue_timeout_s = optional_env("STRATA_QUEUE_TIMEOUT_S")? + .map(|value| value.parse::()) + .transpose()? + .or(file.queue_timeout_s); + if queue_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) { + return Err("queue_timeout_s must be between 1 and 86400 when configured".into()); + } + + let shutdown_grace_s = optional_env("STRATA_SHUTDOWN_GRACE_S")? + .map(|value| value.parse::()) + .transpose()? + .or(file.shutdown_grace_s) + .unwrap_or(0); + if shutdown_grace_s > 20 { + return Err("shutdown_grace_s must be between 0 and 20".into()); + } + + let executable = env::var_os("STRATA_ENGINE_EXE").or_else(|| { + file.engine + .as_ref() + .map(|engine| OsString::from(&engine.executable)) + }); + let args_override = optional_env("STRATA_ENGINE_ARGS_JSON")? + .map(|value| serde_json::from_str::>(&value)) + .transpose()?; + let timeout_override = optional_env("STRATA_STARTUP_TIMEOUT_S")? + .map(|value| value.parse::()) + .transpose()?; + let configured_args = file.engine.as_ref().map(|engine| engine.args.clone()); + let args = args_override.or(configured_args).unwrap_or_default(); + let startup_timeout_s = timeout_override + .or_else(|| { + file.engine + .as_ref() + .and_then(|engine| engine.startup_timeout_s) + }) + .unwrap_or(600); + + if !(1..=3600).contains(&startup_timeout_s) { + return Err("startup_timeout_s must be between 1 and 3600".into()); + } + let max_restarts = optional_env("STRATA_MAX_WORKER_RESTARTS")? + .map(|value| value.parse::()) + .transpose()? + .or_else(|| file.engine.as_ref().and_then(|engine| engine.max_restarts)) + .unwrap_or(3); + if max_restarts > 3 { + return Err("max_restarts must be between 0 and 3".into()); + } + let generation_timeout_s = optional_env("STRATA_GENERATION_TIMEOUT_S")? + .map(|value| value.parse::()) + .transpose()? + .or_else(|| { + file.engine + .as_ref() + .and_then(|engine| engine.generation_timeout_s) + }); + if generation_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) { + return Err("generation_timeout_s must be between 1 and 86400".into()); + } + let engine_file = file.engine.as_ref(); + let mut args = args; + if let Some(vector) = engine_file.and_then(|engine| engine.control_vector.as_ref()) { + if args + .iter() + .any(|arg| arg.starts_with("--control-vector") || arg.starts_with("--cvec-")) + { + return Err("control_vector owns the --control-vector*/--cvec-* arguments; remove them from engine args".into()); + } + args.extend(vector.engine_args()?); + } + let stall_timeout_s = engine_file.and_then(|engine| engine.stall_timeout_s); + if stall_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) { + return Err("stall_timeout_s must be between 1 and 86400".into()); + } + let idle_unload_s = engine_file.and_then(|engine| engine.idle_unload_s); + if idle_unload_s.is_some_and(|seconds| !seconds.is_finite() || seconds < 0.0) { + return Err("idle_unload_s must be a non-negative number".into()); + } + let worker = match executable { + Some(executable) if !executable.is_empty() => Some(WorkerConfig { + executable, + cuda_memory: None, + args, + startup_timeout: Duration::from_secs(startup_timeout_s), + generation_timeout: generation_timeout_s.map(Duration::from_secs), + max_restarts, + lazy: engine_file.is_some_and(|engine| engine.lazy_load), + stall_timeout: stall_timeout_s.map(Duration::from_secs), + before_load: engine_file.and_then(|engine| engine.before_load.clone()), + min_free_vram_mib: engine_file + .and_then(|engine| engine.min_free_vram_mib) + .unwrap_or(0), + vision: None, + }), + Some(_) => return Err("engine executable cannot be empty".into()), + None if !args.is_empty() => return Err("engine args require an executable".into()), + None => None, + }; + let extra = file + .engine + .as_ref() + .map(|engine| engine.extra_workers.as_slice()) + .unwrap_or_default(); + if !extra.is_empty() { + if file.runtime.is_some() { + return Err("extra_workers and runtime are mutually exclusive: the pool feeds stdio engine children, a runtime block serves in front of one leleka-inference".into()); + } + if engine_file.is_some_and(|engine| { + engine.lazy_load || engine.idle_unload_s.is_some_and(|seconds| seconds > 0.0) + }) { + return Err("extra_workers cannot be combined with lazy_load or idle_unload_s: the pool dispatcher does not load or unload workers on demand".into()); + } + if file.vision.is_some() { + return Err("extra_workers cannot be combined with vision: images are read by the single supervised worker".into()); + } + } + if extra.len() > 7 { + return Err("at most 7 extra_workers".into()); + } + let mut extra_workers = Vec::with_capacity(extra.len()); + for entry in extra { + let Some(main) = worker.as_ref() else { + return Err("extra_workers require an engine executable".into()); + }; + if entry.executable.is_empty() { + return Err("an extra worker executable cannot be empty".into()); + } + extra_workers.push(WorkerConfig { + executable: OsString::from(&entry.executable), + cuda_memory: None, + args: entry.args.clone(), + startup_timeout: main.startup_timeout, + generation_timeout: main.generation_timeout, + max_restarts: main.max_restarts, + lazy: false, + stall_timeout: main.stall_timeout, + before_load: None, + min_free_vram_mib: 0, + vision: None, + }); + } + let mut tokenizer_dir = env::var_os("STRATA_TOKENIZER_DIR") + .map(PathBuf::from) + .or_else(|| { + file.engine + .as_ref() + .and_then(|engine| engine.tokenizer_dir.clone()) + }); + if let Some(native) = &file.native_model { + let worker = worker + .as_ref() + .ok_or("native_model requires an engine executable")?; + if tokenizer_dir.is_some() + || worker.args.iter().any(|arg| { + ["--pack", "--native", "--gguf"] + .iter() + .any(|key| arg == key || arg.starts_with(&format!("{key}="))) + }) + { + return Err("native_model owns pack/source/tokenizer settings; remove conflicting overrides".into()); + } + tokenizer_dir = Some(native.output.join("tokenizer")); + } + if file.runtime.is_some() { + if worker.is_some() { + return Err("runtime and engine are mutually exclusive: the API serves in front of either a stdio engine child or a running leleka-inference".into()); + } + if file.native_model.is_some() + || file.mtp_pack.is_some() + || file.vision.is_some() + || file.gpu_requirement.is_some() + || file.cuda_memory.is_some() + || file.engine_probe + { + return Err("runtime cannot be combined with native_model, mtp_pack, vision, gpu_requirement, cuda_memory or engine_probe: the runtime process owns the model and the GPU".into()); + } + } + let runtime = file + .runtime + .map(crate::runtime_config::FileRuntime::resolve) + .transpose()?; + if let Some(runtime) = &runtime { + tokenizer_dir.get_or_insert_with(|| runtime.tokenizer_dir.clone()); + } + if worker.is_none() && runtime.is_none() && tokenizer_dir.is_some() { + return Err("tokenizer_dir requires an engine executable".into()); + } + let gptoss_gguf = env::var_os("STRATA_GPTOSS_GGUF") + .map(PathBuf::from) + .or_else(|| { + file.engine + .as_ref() + .and_then(|engine| engine.gptoss_gguf.clone()) + }); + if gptoss_gguf.is_some() && file.vision.is_some() { + return Err("vision is not available for the gpt-oss family (gptoss_gguf)".into()); + } + if gptoss_gguf.is_some() && (worker.is_none() || tokenizer_dir.is_some()) { + return Err( + "gptoss_gguf requires an engine executable and excludes tokenizer_dir".into(), + ); + } + if worker.is_none() && file.gpu_requirement.is_some() { + return Err("gpu_requirement requires an engine executable".into()); + } + if let Some(policy) = file.cuda_memory { + policy.validate()?; + if file.gpu_requirement.is_none() { + return Err("cuda_memory requires an explicit gpu_requirement".into()); + } + } + if worker.is_none() && file.engine_probe { + return Err("engine_probe requires an engine executable".into()); + } + if let Some(mtp) = &file.mtp_pack { + let worker = worker + .as_ref() + .ok_or("mtp_pack requires an engine executable")?; + if !file.assets.iter().any(|asset| &asset.directory == mtp) { + return Err("mtp_pack must exactly match a pinned assets bundle directory".into()); + } + if mtp.to_str().is_none() + || worker + .args + .iter() + .any(|arg| arg == "--mtp" || arg.starts_with("--mtp=")) + { + return Err( + "mtp_pack requires UTF-8 path and owns --mtp; remove conflicting engine args" + .into(), + ); + } + } + let model = optional_env("STRATA_MODEL_ID")?.or(file.model); + if model.as_ref().is_some_and(|id| { + id.is_empty() + || id.len() > 180 + || !id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.')) + }) { + return Err( + "model ID requires 1..180 ASCII letters, digits, dots, hyphens or underscores" + .into(), + ); + } + let api_key = env::var_os("STRATA_API_KEY_FILE") + .map(PathBuf::from) + .or(file.api_key_file) + .map(|path| crate::auth::ApiKey::from_file(&path).map(std::sync::Arc::new)) + .transpose()?; + let response_history_dir = env::var_os("STRATA_RESPONSE_HISTORY_DIR") + .map(PathBuf::from) + .or(file.response_history_dir); + if response_history_dir.as_ref().is_some_and(|p| { + !p.is_absolute() + || p.file_name().is_none() + || p.components() + .any(|c| matches!(c, std::path::Component::ParentDir)) + }) { + return Err( + "response_history_dir must be an absolute non-root path without '..'".into(), + ); + } + let aliases = match &file.aliases { + None => Vec::new(), + Some(value) => leleka_serving_policy::shared::normalize_aliases( + value, + model.as_deref().unwrap_or(""), + ) + .map_err(|message| format!("config {message}"))?, + }; + if aliases.iter().any(|alias| { + alias.len() > 180 + || !alias + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.')) + }) { + return Err( + "aliases require 1..180 ASCII letters, digits, dots, hyphens or underscores".into(), + ); + } + let cors_origins = leleka_serving_policy::cors::origins_of( + file.cors_origins + .as_ref() + .unwrap_or(&serde_json::Value::Null), + "cors_origins", + true, + )?; + let trusted_origins = leleka_serving_policy::cors::origins_of( + file.trusted_origins + .as_ref() + .unwrap_or(&serde_json::Value::Null), + "trusted_origins", + false, + )?; + let sampling = leleka_serving_policy::shared::sampling_defaults_from_config( + file.sampling.as_ref().unwrap_or(&serde_json::Value::Null), + )?; + for ignored in &sampling.ignored { + crate::elog!("config sampling.{ignored}: unknown key, ignored"); + } + if let Some(value) = &file.reasoning_budget_tokens { + leleka_serving_policy::reasoning::parse_budget(None, Some(value)) + .map_err(|message| format!("config {message}"))?; + } + let shared_settings_file = file.shared_settings_file.clone().or_else(|| { + config_path + .as_deref() + .map(crate::settings::default_shared_path) + }); + let mut mcp_servers = std::collections::BTreeMap::new(); + let null = serde_json::Value::Null; + mcp_servers.extend(crate::mcp::servers_from( + file.mcp_servers.as_ref().unwrap_or(&null), + "config mcp_servers", + )?); + mcp_servers.extend(crate::mcp::servers_from( + file.mcp_servers_desktop.as_ref().unwrap_or(&null), + "config mcpServers", + )?); + if let Some(path) = &file.mcp_config_file { + // Claude Desktop's format; a name in both takes this file's entry. + let location = format!("mcp_config_file {}", path.display()); + let text = std::fs::read_to_string(path) + .map_err(|error| format!("[strata] {location}: {error}"))?; + let data: serde_json::Value = serde_json::from_str(text.trim_start_matches('\u{feff}')) + .map_err(|error| format!("[strata] {location}: {error}"))?; + let block = data + .get("mcpServers") + .or_else(|| data.get("mcp_servers")) + .ok_or_else(|| { + format!("[strata] {location}: expected {{\"mcpServers\": {{...}}}}") + })?; + mcp_servers.extend(crate::mcp::servers_from(block, &location)?); + } + let mcp_settings = crate::mcp::settings_from(file.mcp.as_ref().unwrap_or(&null))?; + if let Some(vision) = &file.vision { + vision.validate()?; + if worker.is_none() { + return Err("vision requires an engine executable".into()); + } + if worker.as_ref().is_some_and(|worker| worker.lazy) { + return Err("lazy loading is text-only; disable vision in the config".into()); + } + } + Ok(Self { + vision: file.vision, + mcp_servers, + mcp_settings, + aliases, + cors_origins, + trusted_origins, + api_monitor: file.api_monitor == Some(true), + tool_call_recovery: match optional_env("STRATA_TOOL_CALL_RECOVERY")?.as_deref() { + Some("1" | "true") => true, + Some("0" | "false") => false, + Some(other) => { + return Err(format!( + "STRATA_TOOL_CALL_RECOVERY must be 1, true, 0 or false, not {other:?}" + ) + .into()); + } + None => file.tool_call_recovery == Some(true), + }, + sampling, + reasoning_budget_tokens: file.reasoning_budget_tokens, + shared_settings_file, + idle_unload: idle_unload_s + .filter(|seconds| *seconds > 0.0) + .map(Duration::from_secs_f64), + mtp_pack: file.mtp_pack, + response_history_dir, + assets: file.assets, + native_model: file.native_model, + gpu_requirement: file.gpu_requirement, + cuda_memory: file.cuda_memory, + host_checked: false, + engine_probe: file.engine_probe, + shutdown_grace: Duration::from_secs(shutdown_grace_s), + queue_timeout: queue_timeout_s.map(Duration::from_secs), + max_in_flight_requests, + api_key, + bind, + model, + worker, + runtime, + extra_workers, + prompt_date, + tokenizer_dir, + gptoss_gguf, + }) + } +} diff --git a/control-plane/src/config/impl_config/impl_config_3.rs b/control-plane/src/config/impl_config/impl_config_3.rs new file mode 100644 index 00000000..3d1efb56 --- /dev/null +++ b/control-plane/src/config/impl_config/impl_config_3.rs @@ -0,0 +1,90 @@ +//! Moved out of the parent module by STRA-338: impl Config (3). + +#[allow(unused_imports)] +use super::*; + +impl Config { + /// Complete acquisition/preparation before the listener or worker starts. + pub async fn provision(&mut self) -> Result<(), Box> { + self.check_host().await?; + self.prepare_assets().await + } + + /// Prepare a switch target while the previous runtime still owns GPU memory. + /// Serving must subsequently perform full host admission; never mark it checked here. + pub async fn prepare_for_switch(&mut self) -> Result<(), Box> { + if let Some(requirement) = self.gpu_requirement { + crate::doctor::check(requirement).await?; + } + self.prepare_assets().await + } + + pub(in super::super) async fn prepare_assets( + &mut self, + ) -> Result<(), Box> { + if self.engine_probe { + let worker = self + .worker + .as_ref() + .ok_or("engine_probe requires an engine executable")?; + crate::engine_probe::check(&worker.executable).await?; + } + // Parse all manifests before any acquisition, including the source model. + if let Some(native) = &self.native_model { + crate::model::Manifest::load(&native.manifest).await?; + } + crate::asset_bundle::provision(&self.assets).await?; + if let Some(mtp) = self.mtp_pack.clone() { + let checked = mtp.clone(); + tokio::task::spawn_blocking(move || crate::mtp_pack::check(&checked)).await??; + self.worker + .as_mut() + .ok_or("mtp_pack requires worker")? + .args + .extend([ + "--mtp".to_owned(), + mtp.to_str().ok_or("MTP path must be UTF-8")?.to_owned(), + ]); + } + if let Some(native) = &self.native_model { + let primary = native.ensure().await?; + let output = native.output.to_str().ok_or("pack path must be UTF-8")?; + let source = primary.to_str().ok_or("source path must be UTF-8")?; + self.worker + .as_mut() + .ok_or("native_model requires worker")? + .args + .extend([ + "--pack".to_owned(), + output.to_owned(), + "--native".to_owned(), + source.to_owned(), + ]); + } + Ok(()) + } + + /// Point-in-time driver policy check; never creates a CUDA context. + pub async fn check_host(&mut self) -> Result<(), Box> { + if let Some(requirement) = self.gpu_requirement + && !self.host_checked + { + crate::doctor::check(requirement).await?; + if let Some(policy) = self.cuda_memory { + let selected = policy.select().await?; + crate::elog!( + "cuda_memory: selected {} for declared {} + {} MiB; allocation is not reserved", + selected.uuid, + policy.required_mib, + policy.reserve_mib + ); + self.worker + .as_mut() + .ok_or("cuda_memory requires worker")? + .cuda_memory = Some(selected); + } + self.host_checked = true; + } + Ok(()) + } +} diff --git a/control-plane/src/responses.rs b/control-plane/src/responses.rs index 57f2daf2..c5b33b21 100644 --- a/control-plane/src/responses.rs +++ b/control-plane/src/responses.rs @@ -39,19 +39,6 @@ static NEXT_RESPONSE_ID: AtomicU64 = AtomicU64::new(0); static TOOL_CALL_RECOVERY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); -/// Turn the experimental recovery of drifted tool-call forms on or off for the rest of the process. -pub fn set_tool_call_recovery(on: bool) { - TOOL_CALL_RECOVERY.store(on, Ordering::Relaxed); -} - -/// How tool calls are read: `natural_stop` as the generation ended, recovery as configured. -fn tool_options(natural_stop: bool) -> tool_output::Options { - tool_output::Options { - natural_stop, - recovery: TOOL_CALL_RECOVERY.load(Ordering::Relaxed), - } -} - mod harmony_prompt; pub use harmony_prompt::{PromptDate, set_prompt_date}; const MAX_STORED_RESPONSES: usize = 64; @@ -75,261 +62,6 @@ struct StoredResponse { bytes: usize, } -impl ResponseHistory { - /// Call before worker acquisition/start. Payloads are never included in errors. - pub fn open(directory: Option<&std::path::Path>) -> Result { - let Some(directory) = directory else { - return Ok(Self::default()); - }; - let store = Arc::new(crate::history_store::Store::open(directory)?); - let mut history = Self::default(); - if let Some(bytes) = store.read()? { - #[derive(Deserialize)] - #[serde(deny_unknown_fields)] - struct Snapshot { - schema: u32, - sha256: String, - entries: Vec, - } - let snapshot: Snapshot = - serde_json::from_slice(&bytes).map_err(|_| "invalid history snapshot")?; - if snapshot.schema != 1 || snapshot.entries.len() > MAX_STORED_RESPONSES { - return Err("unsupported history snapshot schema or entry count"); - } - use sha2::Digest; - let encoded = - serde_json::to_vec(&snapshot.entries).map_err(|_| "invalid history snapshot")?; - if hex::encode(sha2::Sha256::digest(&encoded)) != snapshot.sha256 { - return Err("history snapshot checksum mismatch"); - } - drop(encoded); - for entry in snapshot.entries { - let id = entry.response["id"] - .as_str() - .ok_or("invalid stored response ID")?; - if !id.starts_with("resp_") - || id.len() > 180 - || !id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') - || entry.model.is_empty() - || entry.model.len() > 180 - || entry.input_len > entry.transcript.len() - || entry.response["object"] != "response" - || !matches!( - entry.response["status"].as_str(), - Some("completed" | "incomplete") - ) - { - return Err("invalid stored response metadata"); - } - let input = Value::Array(entry.transcript[..entry.input_len].to_vec()); - if !input.as_array().unwrap().iter().all(Value::is_object) { - return Err("invalid stored response input"); - } - // Rebuild and compare, never trust persisted size or transcript bounds. - let count = history.entries.len(); - history.insert(id, &entry.model, &input, &entry.response)?; - let rebuilt = &history.entries[id]; - if history.entries.len() != count + 1 - || rebuilt.bytes != entry.bytes - || rebuilt.transcript != entry.transcript - { - return Err("inconsistent or oversized history snapshot"); - } - } - } - history.store = Some(store); - Ok(history) - } - - fn persist(&self) -> Result<(), &'static str> { - if let Some(store) = &self.store { - #[derive(Serialize)] - struct Snapshot<'a> { - schema: u32, - sha256: String, - entries: Vec<&'a StoredResponse>, - } - use sha2::Digest; - let entries: Vec<_> = self - .order - .iter() - .map(|id| self.entries[id].as_ref()) - .collect(); - let encoded = - serde_json::to_vec(&entries).map_err(|_| "cannot encode history snapshot")?; - let sha256 = hex::encode(sha2::Sha256::digest(&encoded)); - drop(encoded); - let snapshot = Snapshot { - schema: 1, - sha256, - entries, - }; - let bytes = - serde_json::to_vec(&snapshot).map_err(|_| "cannot encode history snapshot")?; - store.write(&bytes)?; - } - Ok(()) - } - - fn get(&self, id: &str, model: &str) -> Option<&[Value]> { - let response = self.entries.get(id)?; - (response.model == model).then_some(response.transcript.as_slice()) - } - - fn insert( - &mut self, - id: &str, - model: &str, - input: &Value, - response: &Value, - ) -> Result<(), &'static str> { - if self.store.is_none() { - return self.insert_with_limit(id, model, input, response, MAX_HISTORY_BYTES); - } - let mut candidate = self.clone(); - candidate.insert_with_limit(id, model, input, response, MAX_HISTORY_BYTES)?; - candidate.persist()?; - *self = candidate; - Ok(()) - } - - fn insert_with_limit( - &mut self, - id: &str, - model: &str, - input: &Value, - response: &Value, - limit: usize, - ) -> Result<(), &'static str> { - if response["id"] != id || response["model"] != model { - return Err("stored response identity mismatch"); - } - let mut transcript = Vec::new(); - append_input(&mut transcript, input); - let input_len = transcript.len(); - if let Some(items) = response["output"].as_array() { - transcript.extend(items.iter().cloned()); - } - let bytes = serde_json::to_vec(&transcript) - .map_err(|_| "response transcript cannot be serialized")? - .len() - .checked_add( - serde_json::to_vec(response) - .map_err(|_| "response cannot be serialized")? - .len(), - ) - .ok_or("response storage size overflow")?; - if bytes > limit { - return Err("response and transcript exceed the in-memory history limit"); - } - if self.entries.contains_key(id) { - return Err("response ID already exists in history"); - } - while self.entries.len() >= MAX_STORED_RESPONSES || self.bytes.saturating_add(bytes) > limit - { - let Some(oldest) = self.order.pop_front() else { - break; - }; - if let Some(removed) = self.entries.remove(&oldest) { - self.bytes -= removed.bytes; - } - } - self.bytes += bytes; - self.order.push_back(id.to_owned()); - self.entries.insert( - id.to_owned(), - Arc::new(StoredResponse { - model: model.to_owned(), - transcript, - input_len, - response: response.clone(), - bytes, - }), - ); - Ok(()) - } - - fn delete_committed(&mut self, id: &str) -> Result { - let mut candidate = self.clone(); - if !candidate.remove(id) { - return Ok(false); - } - candidate.persist()?; - *self = candidate; - Ok(true) - } - - fn remove(&mut self, id: &str) -> bool { - let Some(removed) = self.entries.remove(id) else { - return false; - }; - self.bytes -= removed.bytes; - self.order.retain(|entry| entry != id); - true - } -} - -async fn store_response( - history: &Arc>, - id: &str, - model: &str, - input: &Value, - response: &Value, -) -> Result<(), &'static str> { - let mut guard = history.clone().write_owned().await; - if guard.store.is_none() { - return guard.insert(id, model, input, response); - } - let (id, model, input, response) = ( - id.to_owned(), - model.to_owned(), - input.clone(), - response.clone(), - ); - tokio::task::spawn_blocking(move || guard.insert(&id, &model, &input, &response)) - .await - .map_err(|_| "history storage task failed")? -} - -fn resource_not_found() -> Response { - api_error( - StatusCode::NOT_FOUND, - "invalid_request_error", - "response_not_found", - Some("response_id"), - "the stored response is unavailable", - ) -} - -fn resource_query_error(query: Option) -> Option { - query.filter(|value| !value.is_empty()).map(|_| { - api_error( - StatusCode::BAD_REQUEST, - "invalid_request_error", - "unsupported_query", - None, - "stored response query options and stream resumption are not supported", - ) - }) -} - -pub async fn retrieve( - State(state): State, - Path(id): Path, - RawQuery(query): RawQuery, -) -> Response { - if let Some(error) = resource_query_error(query) { - return error; - } - let history = state.response_history.read().await; - let Some(entry) = history.entries.get(&id) else { - return resource_not_found(); - }; - let response = entry.response.clone(); - drop(history); - Json(response).into_response() -} - #[derive(Default, Deserialize)] #[serde(deny_unknown_fields)] struct InputItemsQuery { @@ -338,169 +70,6 @@ struct InputItemsQuery { order: Option, } -impl InputItemsQuery { - fn parse(query: Option<&str>) -> Result { - let uri = format!("/?{}", query.unwrap_or("")) - .parse::() - .map_err(|_| "invalid input-items query")?; - let Query(options) = Query::::try_from_uri(&uri) - .map_err(|_| "only single after, limit and order query parameters are supported")?; - if options.limit.is_some_and(|n| !(1..=100).contains(&n)) - || options - .order - .as_deref() - .is_some_and(|s| s != "asc" && s != "desc") - || options - .after - .as_ref() - .is_some_and(|s| s.is_empty() || s.len() > 256) - { - return Err("limit must be 1..100, order asc|desc and after a nonempty item ID"); - } - Ok(options) - } -} - -impl StoredResponse { - fn input_page(&self, id: &str, options: &InputItemsQuery) -> Result { - let descending = options.order.as_deref().unwrap_or("desc") == "desc"; - let prefix = format!("input_{id}_"); - let start = match options.after.as_deref() { - None => 0, - Some(cursor) => { - let index = cursor - .strip_prefix(&prefix) - .and_then(|s| s.parse::().ok()) - .filter(|i| *i < self.input_len && format!("{prefix}{i}") == cursor) - .ok_or("after does not identify an input item of this response")?; - if descending { - self.input_len - index - } else { - index + 1 - } - } - }; - let limit = options.limit.unwrap_or(20); - let count = self.input_len.saturating_sub(start).min(limit); - let mut data = Vec::with_capacity(count); - for position in start..start + count { - let index = if descending { - self.input_len - 1 - position - } else { - position - }; - // Project rather than mutate the transcript used for prompt replay. - // IDs identify occurrences in this response, so repeated client IDs - // cannot make a pagination cursor ambiguous. call_id stays intact. - let mut item = self.transcript[index].clone(); - item.as_object_mut() - .ok_or("stored input item is not an object")? - .insert("id".into(), json!(format!("{prefix}{index}"))); - if item.get("role").is_some() - && (item.get("type").is_none() || item["type"] == "message") - { - item["type"] = json!("message"); - if let Some(text) = item["content"].as_str() { - item["content"] = if item["role"] == "assistant" { - json!([{"type":"output_text","text":text,"annotations":[]}]) - } else { - json!([{"type":"input_text","text":text}]) - }; - } - let assistant = item["role"] == "assistant"; - if let Some(parts) = item["content"].as_array_mut() { - for part in parts { - if part["type"] == "input_text" || part["type"] == "output_text" { - part["type"] = json!(if assistant { - "output_text" - } else { - "input_text" - }); - if assistant && part.get("annotations").is_none() { - part["annotations"] = json!([]); - } - } - } - } - if item.get("status").is_none() { - item["status"] = json!("completed"); - } - } - data.push(item); - } - Ok( - json!({"object":"list", "first_id":data.first().map(|item| &item["id"]), - "last_id":data.last().map(|item| &item["id"]), - "has_more":self.input_len.saturating_sub(start) > count,"data":data}), - ) - } -} - -pub async fn input_items( - State(state): State, - Path(id): Path, - RawQuery(query): RawQuery, -) -> Response { - let invalid = |message| { - api_error( - StatusCode::BAD_REQUEST, - "invalid_request_error", - "invalid_input_items_query", - None, - message, - ) - }; - let options = match InputItemsQuery::parse(query.as_deref()) { - Ok(options) => options, - Err(message) => return invalid(message), - }; - let history = state.response_history.read().await; - let Some(entry) = history.entries.get(&id) else { - return resource_not_found(); - }; - let page = entry.input_page(&id, &options); - drop(history); - match page { - Ok(page) => Json(page).into_response(), - Err(message) => invalid(message), - } -} - -pub async fn delete( - State(state): State, - Path(id): Path, - RawQuery(query): RawQuery, -) -> Response { - if let Some(error) = resource_query_error(query) { - return error; - } - let mut guard = state.response_history.clone().write_owned().await; - let target = id.clone(); - let result = tokio::task::spawn_blocking(move || guard.delete_committed(&target)).await; - match result { - Ok(Ok(true)) => (), - Ok(Ok(false)) => return resource_not_found(), - _ => { - return api_error( - StatusCode::INSUFFICIENT_STORAGE, - "server_error", - "response_storage_failed", - None, - "cannot commit response deletion; inspect storage and restart", - ); - } - } - Json(json!({"id":id,"object":"response.deleted","deleted":true})).into_response() -} - -fn append_input(transcript: &mut Vec, input: &Value) { - if let Some(items) = input.as_array() { - transcript.extend(items.iter().cloned()); - } else if let Some(text) = input.as_str() { - transcript.push(json!({"role":"user","content":text})); - } -} - #[derive(Clone, Deserialize)] #[serde(deny_unknown_fields)] pub struct CreateRequest { @@ -568,351 +137,9 @@ pub enum TextFormat { }, } -impl CreateRequest { - /// The request's sampling fields as the Original's serving layer reads them. - pub fn sampling(&self) -> leleka_sampler_ref::RequestSampling { - leleka_sampler_ref::RequestSampling { - temperature: self.temperature, - top_p: self.top_p, - top_k: self.top_k, - min_p: self.min_p, - repetition_penalty: self.repetition_penalty, - frequency_penalty: self.frequency_penalty, - presence_penalty: self.presence_penalty, - penalty_last_n: self.penalty_last_n, - seed: self.seed, - } - } - - /// Fill what the request left out from the server defaults: the config's `sampling` block, - /// then the shared Chat settings (`{**config, **shared}`, request fields win, an explicit - /// `temperature: 0` stays greedy), the shared `max_tokens`, and the shared reasoning effort. - pub fn apply_defaults(&mut self, settings: &crate::settings::Settings) { - let merged = settings.merged(); - let shared = settings.shared(); - let effective = - leleka_sampler_ref::RequestSampling::overlay(&merged.sampling, &self.sampling()); - self.temperature = effective.temperature; - self.top_p = effective.top_p; - self.top_k = effective.top_k; - self.min_p = effective.min_p; - self.repetition_penalty = effective.repetition_penalty; - self.frequency_penalty = effective.frequency_penalty; - self.presence_penalty = effective.presence_penalty; - self.penalty_last_n = effective.penalty_last_n; - self.seed = effective.seed; - self.experimental_speed_projection = self - .experimental_speed_projection - .or(merged.experimental_speed_projection); - if self.max_output_tokens.is_none() - && let Some(limit) = shared.max_tokens - { - self.max_output_tokens = Some(limit.min(u64::from(u32::MAX)) as u32); - } - if self.reasoning.is_none() - && let Some(effort) = &shared.reasoning_effort - { - self.reasoning = Some(json!({"effort": effort})); - } - } - - fn forced_tool(&self) -> Option<&str> { - self.tool_choice - .as_ref() - .filter(|choice| choice["type"] == "function" || choice["type"] == "custom")? - .get("name")? - .as_str() - } - - fn allowed_tools(&self) -> Option<&Vec> { - self.tool_choice - .as_ref() - .filter(|choice| choice["type"] == "allowed_tools")? - .get("tools")? - .as_array() - } - - fn declared_selector(&self, choice: &Value) -> bool { - choice.as_object().is_some_and(|fields| fields.len() == 2) - && (choice["type"] == "function" || choice["type"] == "custom") - && choice["name"].is_string() - && self - .tools - .iter() - .any(|tool| tool["type"] == choice["type"] && tool["name"] == choice["name"]) - } - - fn validate_tool_name(&self, name: &str) -> Result<(), String> { - if self.forced_tool().is_some_and(|forced| forced != name) { - return Err("generated tool does not match forced tool choice".into()); - } - if self - .allowed_tools() - .is_some_and(|allowed| !allowed.iter().any(|tool| tool["name"] == name)) - { - return Err("generated tool is not in allowed_tools".into()); - } - Ok(()) - } - - fn tools_required(&self) -> bool { - self.tool_choice.as_ref().is_some_and(|choice| { - choice == "required" - || (choice["type"] == "allowed_tools" && choice["mode"] == "required") - }) || self.forced_tool().is_some() - } - - fn tools_disabled(&self) -> bool { - self.tool_choice - .as_ref() - .is_some_and(|choice| choice == "none") - } - - fn validate_tool_count(&self, count: usize) -> Result<(), String> { - if self.tools_disabled() && count > 0 { - return Err("tool_choice none forbids tool calls".into()); - } - if self.parallel_tool_calls == Some(false) && count > 1 { - return Err("parallel_tool_calls false permits at most one tool call".into()); - } - if self.forced_tool().is_some() && count > 1 { - return Err("forced tool choice permits exactly one tool call".into()); - } - Ok(()) - } - - pub fn validate(&self) -> Result<(), (&'static str, &'static str)> { - if self.model.trim().is_empty() { - return Err(("model", "model must be a nonempty string")); - } - if !self.input.is_string() && !self.input.is_array() { - return Err(("input", "input must be a string or an array")); - } - if self.input.as_str().is_some_and(str::is_empty) - || self.input.as_array().is_some_and(Vec::is_empty) - { - return Err(("input", "input cannot be empty")); - } - if self.max_output_tokens == Some(0) { - return Err(("max_output_tokens", "max_output_tokens must be positive")); - } - crate::sampling::validate(&self.sampling())?; - if let Some(tune) = &self.strata_tune { - crate::sampling::validate_tune(tune)?; - } - if leleka_serving_policy::reasoning::parse_budget( - self.reasoning_budget_tokens.as_ref(), - None, - ) - .is_err() - { - return Err(( - "reasoning_budget_tokens", - "reasoning_budget_tokens must be a whole number of tokens (0: no budget)", - )); - } - if let Some(TextOptions { - format: TextFormat::JsonSchema { name, schema, .. }, - .. - }) = &self.text - && (name.is_empty() || schema.get("type").and_then(Value::as_str) != Some("object")) - { - return Err(( - "text.format", - "json_schema needs a name and a root schema of type object", - )); - } - if let Some(TextOptions { - format: TextFormat::JsonSchema { schema, .. }, - .. - }) = &self.text - { - if reject_remote_refs(schema).is_err() { - return Err(( - "text.format", - "schema cannot use external $ref/$dynamicRef/$recursiveRef", - )); - } - if jsonschema::validator_for(schema).is_err() { - return Err(("text.format", "json_schema needs a valid local schema")); - } - } - reasoning_effort(self)?; - if self - .service_tier - .as_deref() - .is_some_and(|tier| !matches!(tier, "auto" | "default" | "flex" | "priority" | "scale")) - { - return Err(("service_tier", "unsupported service tier")); - } - if self - .text - .as_ref() - .and_then(|text| text.verbosity.as_deref()) - .is_some_and(|level| !matches!(level, "low" | "medium" | "high")) - { - return Err(("text.verbosity", "use low, medium or high")); - } - if self.user.as_ref().is_some_and(|user| user.len() > 512) { - return Err(("user", "user exceeds 512 bytes")); - } - if self - .include - .iter() - .any(|field| field != "reasoning.encrypted_content") - { - return Err(("include", "unsupported optional response field")); - } - if self - .prompt_cache_key - .as_ref() - .is_some_and(|key| key.len() > 512) - { - return Err(("prompt_cache_key", "cache key exceeds 512 bytes")); - } - let catalog = Catalog::new(&self.tools).map_err(|message| ("tools", message))?; - if self.tools_required() && catalog.flat.is_empty() { - return Err(( - "tool_choice", - "required tool choice needs at least one callable tool", - )); - } - if let Some(choice) = &self.tool_choice - && (choice["type"] == "function" || choice["type"] == "custom") - && !self.declared_selector(choice) - { - return Err(( - "tool_choice", - "forced tool needs only type and the name of a declared top-level tool of the same type", - )); - } - if let Some(choice) = &self.tool_choice - && choice["type"] == "allowed_tools" - { - let allowed = self - .allowed_tools() - .ok_or(("tool_choice", "allowed_tools needs a tools array"))?; - if choice.as_object().is_none_or(|fields| fields.len() != 3) - || (choice["mode"] != "auto" && choice["mode"] != "required") - || (choice["mode"] == "required" && allowed.is_empty()) - { - return Err(( - "tool_choice", - "allowed_tools needs only type, mode auto|required and tools; required needs at least one tool", - )); - } - let mut seen = HashSet::new(); - for selector in allowed { - if !self.declared_selector(selector) || !seen.insert(selector["name"].as_str()) { - return Err(( - "tool_choice", - "allowed_tools needs unique declared top-level function/custom type and name selectors", - )); - } - } - } - let mut names = HashSet::new(); - for tool in &catalog.flat { - let Some(name) = tool.get("name").and_then(Value::as_str) else { - return Err(("tools", "only named function tools are supported")); - }; - if tool.get("type").and_then(Value::as_str) != Some("function") - || name.is_empty() - || name.len() > 64 - || !name - .bytes() - .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-') - || !names.insert(name) - { - return Err(( - "tools", - "function names must be unique ASCII letters, digits, hyphens or underscores (up to 64 bytes)", - )); - } - if let Some(parameters) = tool.get("parameters") - && !tool_schema_accepted(parameters) - { - return Err(( - "tools", - "function parameters need a local, valid object schema", - )); - } - } - Ok(()) - } -} - /// `Json` with the body read and parse timed as the stage `http_body_json`; same rejections. pub struct TracedJson(pub Json); -impl axum::extract::FromRequest for TracedJson { - type Rejection = JsonRejection; - - async fn from_request( - request: axum::extract::Request, - state: &S, - ) -> Result { - let _span = crate::stage_trace::span("http_body_json"); - Json::::from_request(request, state).await.map(Self) - } -} - -fn parse_request( - state: &AppState, - body: Result, JsonRejection>, -) -> Result> { - let Json(body) = match body { - Ok(body) => body, - Err(error) => { - return Err(Box::new(api_error( - error.status(), - "invalid_request_error", - "invalid_json", - None, - &error.to_string(), - ))); - } - }; - let decode = crate::stage_trace::span("request_decode"); - let request: CreateRequest = match serde_json::from_value(body) { - Ok(request) => request, - Err(error) => { - return Err(Box::new(api_error( - StatusCode::BAD_REQUEST, - "invalid_request_error", - "invalid_request", - None, - &error.to_string(), - ))); - } - }; - drop(decode); - let validated = crate::stage_trace::time("request_validate", || request.validate()); - if let Err((param, message)) = validated { - return Err(Box::new(api_error( - StatusCode::BAD_REQUEST, - "invalid_request_error", - "invalid_request", - Some(param), - message, - ))); - } - if state - .model - .as_ref() - .is_some_and(|model| model != &request.model && !state.aliases.contains(&request.model)) - { - return Err(Box::new(api_error( - StatusCode::NOT_FOUND, - "invalid_request_error", - "model_not_found", - Some("model"), - "the requested model is not served by this runtime", - ))); - } - Ok(request) -} - /// A request's prompt as the engine reads it: token ids (every image already expanded to its rows) and, with /// pictures, the embeddings file `GENI` takes. struct Prepared { @@ -927,986 +154,21 @@ struct Prepared { const IMAGE_PAD: &str = "<|image_pad|>"; const VISION_START: &str = "<|vision_start|>"; -fn vision_error(error: crate::vision::VisionError) -> Box { - Box::new(match error { - crate::vision::VisionError::Invalid(message) => api_error( - StatusCode::BAD_REQUEST, - "invalid_request_error", - "invalid_image", - Some("input"), - &message, - ), - crate::vision::VisionError::Failed(message) => api_error( - StatusCode::SERVICE_UNAVAILABLE, - "server_error", - "vision_encoder_failed", - None, - &message, - ), - }) -} - -/// `Service.prepare`'s image branch: encode the pictures (in turn with the engine), then turn each -/// `<|image_pad|>` the template wrote for one into one pad per image token. -async fn expand_images( - state: &AppState, - tokenizer: &Tokenizer, - ids: Vec, - images: &[String], -) -> Result> { - let Some(vision) = &state.vision else { - return Err(Box::new(api_error( - StatusCode::BAD_REQUEST, - "invalid_request_error", - "images_unsupported", - Some("input"), - "this server was started without the vision encoder (run setup again and choose 'vision'), so it cannot read images", - ))); - }; - let first = |text: &str, special: bool| { - tokenizer - .encode(text, special) - .map_err(|e| e.to_string()) - .and_then(|ids| { - ids.first() - .copied() - .ok_or_else(|| format!("{text} has no token")) - }) - }; - let internal = |message: String| { - Box::new(api_error( - StatusCode::INTERNAL_SERVER_ERROR, - "server_error", - "tokenization_failed", - None, - &message, - )) - }; - let pad = first(IMAGE_PAD, true).map_err(internal)?; - let start = first(VISION_START, true).map_err(internal)?; - let literal = tokenizer - .encode(IMAGE_PAD, false) - .map_err(|e| internal(e.to_string()))?; - // Encode only while the engine is idle: the engine and the image encoder are separate processes that must - // not run on the GPU at the same time. - let encoded = { - let _turn = vision.gate.lock().await; - let mut encoded = Vec::with_capacity(images.len()); - for source in images { - encoded.push(vision.encode(source).await.map_err(vision_error)?); - } - encoded - }; - let counts: Vec = encoded.iter().map(|image| image.tokens).collect(); - let token_ids = - leleka_serving_policy::vision::expand_image_pads(&ids, pad, start, &literal, &counts) - .map_err(|message| { - Box::new(api_error( - StatusCode::BAD_REQUEST, - "invalid_request_error", - "invalid_prompt", - Some("input"), - &message, - )) - })?; - let (path, keep) = vision.combine(&encoded).await.map_err(vision_error)?; - Ok(Prepared { - token_ids, - prompt_text: None, - embeddings: Some(path.to_string_lossy().into_owned()), - keep, - }) -} - -// Both endpoints must encode the same expanded transcript and chat template. `encode_images: false` (the token -// counters) leaves one pad per picture, as the Python server's count does: nothing is sent to the encoder. -async fn prepare_input_tokens( - state: &AppState, - request: &mut CreateRequest, - tokenizer: Arc, - encode_images: bool, -) -> Result> { - if let Some(previous) = &request.previous_response_id { - let history = state.response_history.read().await; - let Some(saved) = history.get(previous, &request.model) else { - return Err(Box::new(api_error( - StatusCode::NOT_FOUND, - "invalid_request_error", - "response_not_found", - Some("previous_response_id"), - "the previous response is unavailable or belongs to a different model", - ))); - }; - let mut transcript = saved.to_vec(); - append_input(&mut transcript, &request.input); - request.input = Value::Array(transcript); - } - // The Qwen path renders through the chat template with the control-token marks and may carry pictures; the - // Harmony renderer of gpt-oss has no pictures. - let rendered = crate::stage_trace::time("render", || match tokenizer.family() { - Family::Qwen35 => { - let qwen = tokenizer - .qwen() - .ok_or_else(|| "the Qwen family needs the Qwen tokenizer".to_owned())?; - render_request(request, qwen.marks()) - } - Family::GptOss => harmony_prompt::render(request).map(|prompt| (prompt, Vec::new())), - }); - let (prompt, images) = match rendered { - Ok(rendered) => rendered, - Err(message) => { - return Err(Box::new(api_error( - StatusCode::BAD_REQUEST, - "invalid_request_error", - "invalid_prompt", - Some("input"), - &message, - ))); - } - }; - let tokenizer_for_encode = tokenizer.clone(); - let tokenize_span = crate::stage_trace::span("tokenize"); - let (token_ids, prompt) = match tokio::task::spawn_blocking(move || { - // The one tokenization of a prompt, for generation and for counting: the template's own markers are special - // tokens, the control-token text inside the messages (marked by `render_request`) is ordinary text. - tokenizer_for_encode - .encode_prompt(&prompt) - .map(|ids| (ids, prompt)) - }) - .await - { - Ok(Ok(encoded)) => encoded, - Ok(Err(message)) => { - return Err(Box::new(api_error( - StatusCode::BAD_REQUEST, - "invalid_request_error", - "tokenization_failed", - Some("input"), - &message, - ))); - } - Err(error) => { - return Err(Box::new(api_error( - StatusCode::INTERNAL_SERVER_ERROR, - "server_error", - "tokenization_failed", - None, - &error.to_string(), - ))); - } - }; - drop(tokenize_span); - if images.is_empty() || !encode_images { - return Ok(Prepared { - token_ids, - prompt_text: Some(Arc::from(prompt)), - embeddings: None, - keep: Default::default(), - }); - } - let Some(qwen) = tokenizer.qwen() else { - return Err(Box::new(api_error( - StatusCode::BAD_REQUEST, - "invalid_request_error", - "images_unsupported", - Some("input"), - "this model family cannot read images", - ))); - }; - expand_images(state, qwen, token_ids, &images).await -} - -pub async fn count_input_tokens( - State(state): State, - body: Result, JsonRejection>, -) -> Response { - let mut request = match parse_request(&state, body) { - Ok(request) => request, - Err(error) => return *error, - }; - if let Err((param, message)) = validate_live_subset(&request) { - return api_error( - StatusCode::NOT_IMPLEMENTED, - "invalid_request_error", - "unsupported_live_feature", - Some(param), - message, - ); - } - let Some(tokenizer) = &state.tokenizer else { - return api_error( - StatusCode::NOT_IMPLEMENTED, - "server_error", - "inference_adapter_missing", - None, - "configure tokenizer_dir to enable input token counting", - ); - }; - match prepare_input_tokens(&state, &mut request, tokenizer.clone(), false).await { - Ok(prepared) => Json( - json!({"object": "response.input_tokens", "input_tokens": prepared.token_ids.len()}), - ) - .into_response(), - Err(error) => *error, - } -} - -/// Every failed generation leaves one line in the log (the message is the one the client gets: no prompt or output text). -/// With `STRATA_DEBUG_FAILED_OUTPUT=1` the generated text of a failed streaming tool turn is logged too: operator debugging -/// only, because it is model output. -fn log_generation_failure(message: &str) { - crate::elog!("generation failed: {message}"); -} - -fn debug_failed_output() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("STRATA_DEBUG_FAILED_OUTPUT").is_some_and(|v| v == "1")) -} - /// The engines refuse a request unless `prompt + max_new + 8 <= context`. const CONTEXT_MARGIN_TOKENS: usize = 8; -fn queue_error(error: crate::queue::Error) -> Response { - match error { - crate::queue::Error::Expired => api_error( - StatusCode::GATEWAY_TIMEOUT, - "server_error", - "queue_timeout", - None, - "request exceeded the configured queue deadline before worker claim; generation was not started", - ), - crate::queue::Error::Closed => api_error( - StatusCode::SERVICE_UNAVAILABLE, - "server_error", - "worker_not_ready", - None, - "the Strata worker command queue closed before request claim", - ), - } -} - -/// The `/v1/responses` route: [`create`] with the body read and parse timed. -pub async fn create_route( - state: State, - body: Result, -) -> Response { - create(state, body.map(|traced| traced.0)).await -} - -pub async fn create( - State(state): State, - body: Result, JsonRejection>, -) -> Response { - let mut request = match parse_request(&state, body) { - Ok(request) => request, - Err(error) => return *error, - }; - if let Err(response) = crate::server_api::ensure_loaded(&state).await { - return *response; - } - if state.worker.read().await.state != WorkerState::Ready { - return api_error( - StatusCode::SERVICE_UNAVAILABLE, - "server_error", - "worker_not_ready", - None, - "the Strata worker is not ready", - ); - } - // The engine's memory governor says the host is at its hard floor: refuse now, with Retry-After, instead of queueing - // work that would push it into swap or the OOM killer (`docs/memory-safety.md`). - if let Some(closed) = state.memory.closed() { - return crate::memory_view::refusal_response(closed.retry_after_secs, &closed.reason); - } - let (Some(tokenizer), Some(generation)) = (&state.tokenizer, &state.generation) else { - return api_error( - StatusCode::NOT_IMPLEMENTED, - "server_error", - "inference_adapter_missing", - None, - "configure tokenizer_dir to enable the text inference preview", - ); - }; - if let Err((param, message)) = validate_live_subset(&request) { - return api_error( - StatusCode::NOT_IMPLEMENTED, - "invalid_request_error", - "unsupported_live_feature", - Some(param), - message, - ); - } - if tokenizer.family() == Family::GptOss { - // The gpt-oss CPU worker's `GEN` line takes temperature, top_p and seed only. An explicit request for a - // sampler it does not have is a client error; defaults from the config or the shared settings are dropped. - if let Some(param) = unsupported_gptoss_sampling(&request.sampling()) { - return api_error( - StatusCode::BAD_REQUEST, - "invalid_request_error", - "unsupported_parameter", - Some(param), - "the gpt-oss family supports temperature, top_p and seed only", - ); - } - } - request.apply_defaults(&state.settings); - if tokenizer.family() == Family::GptOss { - request.top_k = None; - request.min_p = None; - request.repetition_penalty = None; - request.frequency_penalty = None; - request.presence_penalty = None; - request.penalty_last_n = None; - } - let Prepared { - token_ids, - prompt_text, - embeddings, - keep, - } = match prepare_input_tokens(&state, &mut request, tokenizer.clone(), true).await { - Ok(prepared) => prepared, - Err(error) => return *error, - }; - let (max_context, output_cap, text_level_engine) = { - let worker = state.worker.read().await; - ( - worker.max_context, - worker.output_cap.unwrap_or(u32::MAX), - worker.text_level_engine, - ) - }; - // The worker refuses `prompt + max_new + 8 > context` and an output budget above the runtime's cap, but only after the - // request was queued, as a 502. These are client errors: answer them here, as 400, before anything is queued. - let prompt_tokens = token_ids.len(); - let remaining = max_context - .map(|context| { - context - .saturating_sub(prompt_tokens) - .saturating_sub(CONTEXT_MARGIN_TOKENS) - .min(u32::MAX as usize) as u32 - }) - .unwrap_or(32768); - if let Some(context) = max_context - && (remaining == 0 - || request - .max_output_tokens - .is_some_and(|new| u64::from(new) > u64::from(remaining))) - { - return api_error( - StatusCode::BAD_REQUEST, - "invalid_request_error", - "context_length_exceeded", - Some("input"), - &format!( - "the prompt has {prompt_tokens} tokens and the output budget is {}; the model's context is {context} tokens (prompt + output budget + {CONTEXT_MARGIN_TOKENS} tokens of margin must fit)", - request - .max_output_tokens - .map_or_else(|| "unset".to_owned(), |n| n.to_string()), - ), - ); - } - if request - .max_output_tokens - .is_some_and(|new| new > output_cap) - { - return api_error( - StatusCode::BAD_REQUEST, - "invalid_request_error", - "invalid_output_limit", - Some("max_output_tokens"), - &format!( - "max_output_tokens {} exceeds the runtime's limit of {output_cap}", - request.max_output_tokens.unwrap_or_default() - ), - ); - } - let generate = Generate { - token_ids, - max_new: request - .max_output_tokens - .unwrap_or(32768.min(remaining).min(output_cap).max(1)), - sampling: request.sampling(), - tune: request.strata_tune.map(Into::into), - cvec: request.experimental_speed_projection, - embeddings, - keep, - reasoning: reasoning_plan(&request, &state, tokenizer), - prompt_text, - obs: { - let obs = crate::request_log::ObsHandle::current(); - obs.set_stream(request.stream); - obs - }, - }; - if text_level_engine { - // What the text-level engine contract cannot carry is the client's error to hear about now, not a 502 after queueing. - let unsupported = if generate.reasoning.is_some() { - Some(( - "reasoning_budget_tokens", - "reasoning_budget_tokens needs token-level continuation, which the text-level engine contract does not provide", - )) - } else if generate.tune.is_some() { - Some(( - "strata_tune", - "strata_tune is an engine-process setting and is not part of the engine contract", - )) - } else if generate.cvec.is_some() { - Some(( - "experimental_speed_projection", - "experimental_speed_projection (control vectors) is not part of the engine contract", - )) - } else { - None - }; - if let Some((param, message)) = unsupported { - return api_error( - StatusCode::BAD_REQUEST, - "invalid_request_error", - "unsupported_request_field", - Some(param), - message, - ); - } - // The text contract carries sampling as thousandths / millionths; anything finer cannot be served as asked. - if let Err(error) = leleka_serving_policy::fixed::to_fixed_point(&generate.sampling) { - return api_error( - StatusCode::BAD_REQUEST, - "invalid_request_error", - "invalid_sampling_precision", - None, - &format!("sampling: {error}"), - ); - } - } - if request.stream { - let (events, received) = mpsc::channel(16); - let enqueue_span = crate::stage_trace::span("enqueue"); - let enqueued = crate::queue::enqueue( - generation, - GenerationCommand { - queue: None, - activity: Some(state.lifecycle.generation()), - request: generate, - result: GenerationResult::Streaming(events), - }, - state.queue_timeout, - ) - .await; - drop(enqueue_span); - if let Err(error) = enqueued { - return queue_error(error); - } - return stream_live_text( - request, - tokenizer.clone(), - received, - Some(state.response_history.clone()), - ); - } - let (result, received) = oneshot::channel(); - let command = GenerationCommand { - queue: None, - activity: Some(state.lifecycle.generation()), - request: generate, - result: GenerationResult::Buffered(result), - }; - if let Err(error) = crate::queue::enqueue(generation, command, state.queue_timeout).await { - return queue_error(error); - } - let events = match received.await { - Ok(Ok(events)) => events, - Ok(Err(message)) => { - if let Some(retry_after) = crate::memory_view::parse_refusal(&message) { - return crate::memory_view::refusal_response(retry_after, &message); - } - log_generation_failure(&message); - return api_error( - StatusCode::BAD_GATEWAY, - "server_error", - "generation_failed", - None, - &message, - ); - } - Err(_) => { - return api_error( - StatusCode::SERVICE_UNAVAILABLE, - "server_error", - "worker_not_ready", - None, - "the Strata worker stopped before completing the request", - ); - } - }; - let Some(Event::Done(done)) = events.last() else { - return api_error( - StatusCode::BAD_GATEWAY, - "server_error", - "missing_terminal_event", - None, - "the Strata worker did not report DONE", - ); - }; - if done.finish == Finish::Cancel { - return api_error( - StatusCode::BAD_GATEWAY, - "server_error", - "unsupported_finish", - None, - "the text inference preview requires a stop finish", - ); - } - let output_ids = events - .iter() - .filter_map(|event| match event { - Event::Token(id) => Some(*id), - _ => None, - }) - .collect::>(); - let terminal = tokenizer.terminal_ids(); - let output_ids = output_ids - .split(|id| terminal.contains(id)) - .next() - .unwrap_or(&[]) - .to_vec(); - let tokenizer_for_decode = tokenizer.clone(); - let thinking = reasoning_enabled(&request, tokenizer.family()); - let finish = done.finish; - let flat_tools = flat_tools(&request); - let output = match tokio::task::spawn_blocking(move || { - decode_generation_with( - tokenizer_for_decode.as_ref(), - &output_ids, - thinking, - finish, - &flat_tools, - ) - }) - .await - { - Ok(Ok(text)) => text, - Ok(Err(message)) => { - return api_error( - StatusCode::BAD_GATEWAY, - "server_error", - "detokenization_failed", - None, - &message, - ); - } - Err(error) => { - return api_error( - StatusCode::INTERNAL_SERVER_ERROR, - "server_error", - "detokenization_failed", - None, - &error.to_string(), - ); - } - }; - let now = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default(); - let id = format!( - "resp_{:x}_{:x}", - now.as_nanos(), - NEXT_RESPONSE_ID.fetch_add(1, Ordering::Relaxed) - ); - let debug_copy = debug_failed_output().then(|| { - format!( - "reasoning={:?} answer={:?}", - output.reasoning.as_ref().map(|(text, _)| text), - output.answer - ) - }); - let (items, reasoning_tokens) = - match decoded_items(&request, output, &id, finish != Finish::Length) { - Ok(items) => items, - Err(message) => { - log_generation_failure(&message); - if let Some(text) = &debug_copy { - crate::elog!("failed output (STRATA_DEBUG_FAILED_OUTPUT): {text:?}"); - } - return api_error( - StatusCode::BAD_GATEWAY, - "server_error", - "tool_call_parse_failed", - None, - &message, - ); - } - }; - let usage = Usage { - input_tokens: done.prompt_tokens, - output_tokens: done.generated, - // Counted from the ids that were decoded; a text-level engine reports its own total, which - // this count must never exceed (equal on the stdio wire, where each id is one T line). - reasoning_tokens: reasoning_tokens.min(done.generated), - cached_tokens: done.reused.unwrap_or(0), - }; - match ResponseTrace::build_with_terminal( - &request, - &items, - usage, - &id, - now.as_secs(), - now.as_secs(), - done.finish == Finish::Length, - ) { - Ok(trace) => { - if request.store != Some(false) - && let Err(message) = store_response( - &state.response_history, - &id, - &request.model, - &request.input, - &trace.response, - ) - .await - { - return api_error( - StatusCode::INSUFFICIENT_STORAGE, - "server_error", - "response_storage_failed", - None, - message, - ); - } - Json(trace.response).into_response() - } - Err(message) => api_error( - StatusCode::BAD_GATEWAY, - "server_error", - "response_assembly_failed", - None, - &message, - ), - } -} - -#[cfg(test)] -fn parse_output_items( - request: &CreateRequest, - output: String, - id: &str, -) -> Result, String> { - parse_output_items_after(request, output, id, false) -} - -/// `natural_stop`: the generation ended by itself and not at the token limit, so a call that ends the text on `` is whole. -fn parse_output_items_after( - request: &CreateRequest, - output: String, - id: &str, - natural_stop: bool, -) -> Result, String> { - if request.tools.is_empty() { - return Ok(vec![OutputItem::Text { - deltas: vec![output], - }]); - } - let catalog = Catalog::new(&request.tools)?; - let parsed = tool_output::parse_with(&output, &catalog.flat, tool_options(natural_stop))?; - log_tool_notes(&parsed.notes); - let mut items = parsed - .segments - .into_iter() - .enumerate() - .map(|(index, segment)| match segment { - Segment::Text(text) => OutputItem::Text { deltas: vec![text] }, - Segment::Call { name, arguments } => OutputItem::FunctionCall { - name, - call_id: format!("call_{}_{}", &id[5..], index), - argument_deltas: vec![arguments.to_string()], - }, - }) - .collect::>(); - if items.is_empty() { - items.push(OutputItem::Text { - deltas: vec![String::new()], - }); - } - Ok(items) -} - -/// The request's tool declarations in the form the parser reads; none when the request declares no tools. -fn flat_tools(request: &CreateRequest) -> Vec { - Catalog::new(&request.tools) - .map(|catalog| catalog.flat) - .unwrap_or_default() -} - -/// A tool call that was accepted although the template form was not followed is never silent: it is logged here. -fn log_tool_notes(notes: &tool_output::Notes) { - if !notes.is_empty() { - crate::elog!("tool call accepted beyond the template form ({notes})"); - } -} - -fn reasoning_effort(request: &CreateRequest) -> Result { - let Some(value) = &request.reasoning else { - return Ok(Effort::XHigh); - }; - let fields = value - .as_object() - .ok_or(("reasoning", "reasoning must be an object"))?; - if fields - .keys() - .any(|key| !matches!(key.as_str(), "effort" | "summary")) - { - return Err(("reasoning", "only effort and summary are supported")); - } - if fields - .get("summary") - .is_some_and(|value| !value.is_null() && value != "auto" && value != "none") - { - return Err(( - "reasoning.summary", - "only auto, none or null is supported; this runtime returns raw reasoning content with an empty summary", - )); - } - match fields.get("effort") { - None | Some(Value::Null) => Ok(Effort::XHigh), - Some(Value::String(effort)) => match effort.as_str() { - "none" => Ok(Effort::None), - // The template has no "minimal"; the closest instruction it has is the brief one. - "minimal" | "low" => Ok(Effort::Low), - "medium" => Ok(Effort::Medium), - "high" => Ok(Effort::High), - "xhigh" => Ok(Effort::XHigh), - _ => Err(( - "reasoning.effort", - "use none, minimal, low, medium, high or xhigh", - )), - }, - _ => Err(("reasoning.effort", "effort must be a string or null")), - } -} - -/// Whether the output starts inside a reasoning block that ends with ``. gpt-oss always reasons. -fn reasoning_enabled(request: &CreateRequest, family: Family) -> bool { - family == Family::GptOss || reasoning_effort(request).is_ok_and(|effort| effort != Effort::None) -} - struct DecodedGeneration { answer: String, reasoning: Option<(String, bool)>, reasoning_tokens: u64, } -#[cfg(test)] -fn decode_generation( - tokenizer: &dyn TextCodec, - ids: &[u32], - reasoning: bool, - finish: Finish, -) -> Result { - decode_generation_with(tokenizer, ids, reasoning, finish, &[]) -} - -/// `tools`: the flat declarations of the request, to tell a call the reasoning ends on from one it only quotes. -fn decode_generation_with( - tokenizer: &dyn TextCodec, - ids: &[u32], - reasoning: bool, - finish: Finish, - tools: &[Value], -) -> Result { - let bytes = decode_all(tokenizer, ids)?; - if !reasoning { - return Ok(DecodedGeneration { - answer: String::from_utf8_lossy(&bytes).into_owned(), - reasoning: None, - reasoning_tokens: 0, - }); - } - let marker = b""; - let boundary = bytes.windows(marker.len()).position(|part| part == marker); - let Some(boundary) = boundary else { - if finish != Finish::Length { - // The model stopped by itself without closing its reasoning. If the text ends on whole tool calls of declared - // tools, the reasoning is what comes before them and they are the answer; otherwise the turn is malformed. - // (The calls were already streamed as reasoning text; the reasoning item here ends before them.) - let text = String::from_utf8_lossy(&bytes); - if let Some(at) = tool_output::calls_at_end(&text, tools, tool_options(true)) { - crate::elog!( - "tool call accepted beyond the template form (written inside the reasoning, no )" - ); - let mut consumed = 0; - let mut reasoning_tokens = 0; - let mut decoder = tokenizer.decoder(); - for id in ids { - if consumed >= at { - break; - } - consumed += decoder.push(*id)?.len(); - reasoning_tokens += 1; - } - return Ok(DecodedGeneration { - answer: text[at..].to_owned(), - reasoning: Some((text[..at].to_owned(), true)), - reasoning_tokens, - }); - } - return Err("reasoning ended without ".into()); - } - return Ok(DecodedGeneration { - answer: String::new(), - reasoning: Some((String::from_utf8_lossy(&bytes).into_owned(), false)), - reasoning_tokens: ids.len() as u64, - }); - }; - let mut consumed = 0; - let mut reasoning_tokens = 0; - let mut decoder = tokenizer.decoder(); - for id in ids { - consumed += decoder.push(*id)?.len(); - reasoning_tokens += 1; - if consumed >= boundary + marker.len() { - break; - } - } - Ok(DecodedGeneration { - answer: String::from_utf8_lossy(&bytes[boundary + marker.len()..]) - .trim_start_matches('\n') - .to_owned(), - reasoning: Some(( - String::from_utf8_lossy(&bytes[..boundary]).into_owned(), - true, - )), - reasoning_tokens, - }) -} - -fn decoded_items( - request: &CreateRequest, - decoded: DecodedGeneration, - id: &str, - natural_stop: bool, -) -> Result<(Vec, u64), String> { - let mut items = Vec::new(); - let mut reasoning_incomplete = false; - if let Some((text, complete)) = decoded.reasoning { - items.push(OutputItem::Reasoning { - deltas: vec![text], - complete, - }); - reasoning_incomplete = !complete; - } - if !reasoning_incomplete { - items.extend(parse_output_items_after( - request, - decoded.answer, - id, - natural_stop, - )?); - } - Ok((items, decoded.reasoning_tokens)) -} - #[derive(Default)] struct ReasoningStream { pending: Vec, ended: bool, } -impl ReasoningStream { - fn push(&mut self, bytes: &[u8]) -> String { - if self.ended { - return String::new(); - } - self.pending.extend_from_slice(bytes); - let marker = b""; - if let Some(at) = self - .pending - .windows(marker.len()) - .position(|part| part == marker) - { - let text = String::from_utf8_lossy(&self.pending[..at]).into_owned(); - self.pending.clear(); - self.ended = true; - return text; - } - let keep = (1..marker.len()) - .rev() - .find(|n| self.pending.ends_with(&marker[..*n])) - .unwrap_or(0); - let tail = self.pending.split_off(self.pending.len() - keep); - let text = drain_utf8(&mut self.pending, false); - self.pending.extend_from_slice(&tail); - text - } - - fn finish(&mut self) -> String { - drain_utf8(&mut self.pending, true) - } -} - -/// The first sampler the request sets that the gpt-oss worker's `GEN` line cannot carry. -fn unsupported_gptoss_sampling( - sampling: &leleka_sampler_ref::RequestSampling, -) -> Option<&'static str> { - if sampling.top_k.is_some() { - Some("top_k") - } else if sampling.min_p.is_some() { - Some("min_p") - } else if sampling.repetition_penalty.is_some_and(|v| v != 1.0) { - Some("repetition_penalty") - } else if sampling.frequency_penalty.is_some_and(|v| v != 0.0) { - Some("frequency_penalty") - } else if sampling.presence_penalty.is_some_and(|v| v != 0.0) { - Some("presence_penalty") - } else { - None - } -} - -/// The reasoning-budget wrap-up for this request, if thinking is on and a budget is set (the -/// request's `reasoning_budget_tokens`, else the config's). -fn reasoning_plan( - request: &CreateRequest, - state: &AppState, - codec: &Arc, -) -> Option { - // The wrap-up and the byte accounting are the Qwen path's; the Harmony family has no reasoning budget. - let tokenizer = codec.qwen()?; - if !reasoning_enabled(request, codec.family()) { - return None; - } - let budget = leleka_serving_policy::reasoning::parse_budget( - request.reasoning_budget_tokens.as_ref(), - state.settings.reasoning_budget_default(), - ) - .ok()??; - let wrap_up = tokenizer - .encode(leleka_serving_policy::reasoning::WRAP_UP, true) - .ok()?; - let stop_ids = ["<|im_end|>", "<|endoftext|>"] - .into_iter() - .filter_map(|name| tokenizer.special_id(name)) - .collect(); - let bytes_of = tokenizer.clone(); - Some(crate::wire::ReasoningPlan { - budget, - wrap_up, - stop_ids, - token_bytes: Arc::new(move |id| bytes_of.decode_bytes(&[id]).unwrap_or_default()), - }) -} - -fn is_structured(request: &CreateRequest) -> bool { - request - .text - .as_ref() - .is_some_and(|text| !matches!(text.format, TextFormat::Text)) -} - -/// The prompt text, for tests and callers that do not read pictures. -#[cfg(test)] -fn render_request_prompt(request: &CreateRequest) -> Result { - render_request(request, &tests::test_marks()).map(|(prompt, _)| prompt) -} - /// One message of the request while the prompt is assembled. struct Owned { role: Role, @@ -1916,466 +178,9 @@ struct Owned { parts: Option>, } -impl Owned { - fn new(role: Role, content: String, reasoning: Option) -> Self { - Self { - role, - content, - reasoning, - parts: None, - } - } -} - -/// Every string of a JSON value (keys too) through [`LiteralMarks::mark`]: a tool's description and parameter schema. -fn mark_json(marks: &LiteralMarks, value: &Value) -> Value { - match value { - Value::String(text) => Value::String(marks.mark(text).into_owned()), - Value::Array(items) => { - Value::Array(items.iter().map(|item| mark_json(marks, item)).collect()) - } - Value::Object(fields) => Value::Object( - fields - .iter() - .map(|(key, item)| (marks.mark(key).into_owned(), mark_json(marks, item))) - .collect(), - ), - other => other.clone(), - } -} - -/// The rendered prompt and the sources of its pictures, in prompt order. -/// -/// Control-token text inside a message is text: every string that comes from the client (instructions, message text, reasoning, -/// tool-call arguments, tool outputs, tool descriptions and schemas) goes through [`LiteralMarks::mark`] before the template -/// runs, and the tokenizer encodes the marks as ordinary text ([`Tokenizer::encode_marked`]). The markers this function and the -/// template write themselves (``, ``, the template's turn and `` markers) stay literal. -fn render_request( - request: &CreateRequest, - marks: &LiteralMarks, -) -> Result<(String, Vec), String> { - let mark = |text: &str| marks.mark(text).into_owned(); - let mut owned = Vec::::new(); - if let Some(instructions) = &request.instructions { - owned.push(Owned::new(Role::System, mark(instructions), None)); - } - if let Some(name) = request.forced_tool() { - let kind = if request - .tool_choice - .as_ref() - .is_some_and(|choice| choice["type"] == "custom") - { - "custom tool" - } else { - "function" - }; - owned.push(Owned::new( - Role::System, - mark(&format!( - "Call exactly one {kind} in this response: {name}. Do not call any other tool." - )), - None, - )); - } else if request.tools_required() { - owned.push(Owned::new( - Role::System, - "Call at least one tool in this response.".to_owned(), - None, - )); - } - if let Some(allowed) = request.allowed_tools() { - owned.push(Owned::new(Role::System, if allowed.is_empty() { - "Do not call any tools in this response.".to_owned() - } else { - mark(&format!("Only these tools may be called in this response: {}. Do not call any other tool.", serde_json::to_string(allowed).expect("selector serialization"))) - }, None)); - } - if request.parallel_tool_calls == Some(false) - && !request.tools_disabled() - && !request.tools.is_empty() - { - owned.push(Owned::new( - Role::System, - "Use at most one tool call in this response.".to_owned(), - None, - )); - } - if let Some(options) = &request.text { - let instruction = match &options.format { - TextFormat::Text => None, - TextFormat::JsonObject => Some("Return exactly one JSON object as your final text response. Do not add Markdown fences or commentary.".to_owned()), - TextFormat::JsonSchema { schema, .. } => Some(format!("Return exactly one JSON object matching this JSON Schema as your final text response. Do not add Markdown fences or commentary.\nJSON Schema: {schema}")), - }; - if let Some(mut instruction) = instruction { - if !request.tools_disabled() && !request.tools.is_empty() { - instruction.push_str(" Function calls still use the tool-call format; this JSON requirement applies to your final text answer after any necessary tool results."); - } - owned.push(Owned::new(Role::System, mark(&instruction), None)); - } - } - if let Some(input) = request.input.as_str() { - owned.push(Owned::new(Role::User, mark(input), None)); - } else { - let items = request - .input - .as_array() - .ok_or("input must be a string or array")?; - let mut calls = Vec::<(String, String)>::new(); - let mut outputs = Vec::<(String, String)>::new(); - let mut custom_calls = HashSet::::new(); - let mut reasoning = None::; - for item in items { - let kind = item - .get("type") - .and_then(Value::as_str) - .unwrap_or("message"); - match kind { - "reasoning" => { - if reasoning.is_some() || !calls.is_empty() { - return Err( - "reasoning must precede its assistant message or tool calls".into() - ); - } - if item.get("encrypted_content").is_some_and(|v| !v.is_null()) { - return Err("encrypted reasoning replay is not supported".into()); - } - let parts = item - .get("content") - .and_then(Value::as_array) - .ok_or("reasoning replay requires raw reasoning_text content")?; - let mut text = String::new(); - for part in parts { - if part.get("type").and_then(Value::as_str) != Some("reasoning_text") { - return Err("reasoning replay requires reasoning_text parts".into()); - } - text.push_str( - part.get("text") - .and_then(Value::as_str) - .ok_or("reasoning_text needs text")?, - ); - } - reasoning = Some(mark(&text)); - } - "message" => { - if !calls.is_empty() { - return Err( - "every replayed function call needs an output before the next message" - .into(), - ); - } - let role = match item.get("role").and_then(Value::as_str) { - Some("system") => Role::System, - Some("developer") => Role::Developer, - Some("user") => Role::User, - Some("assistant") => Role::Assistant, - _ => return Err("unsupported input message role".into()), - }; - let mut pictures: Option> = None; - let content = match item.get("content") { - Some(Value::String(text)) => mark(text), - Some(Value::Array(parts)) => { - let mut text = String::new(); - let mut listed = Vec::new(); - for part in parts { - match part.get("type").and_then(Value::as_str) { - Some("input_text" | "output_text") => { - let piece = mark( - part.get("text") - .and_then(Value::as_str) - .ok_or("text part needs text")?, - ); - text.push_str(&piece); - listed.push(Part::Text(piece)); - } - Some("input_image") => { - listed.push(Part::Image( - leleka_serving_policy::vision::image_source(part), - )); - } - _ => { - return Err( - "only text and image content parts are supported" - .into(), - ); - } - } - } - if listed.iter().any(|part| matches!(part, Part::Image(_))) { - match role { - Role::User => pictures = Some(listed), - Role::System | Role::Developer => { - return Err("System message cannot contain images.".into()); - } - Role::Assistant => { - return Err( - "images are only supported in user messages".into() - ); - } - } - } - text - } - _ => return Err("input message needs text content".into()), - }; - if role != Role::Assistant - && let Some(thought) = reasoning.take() - { - owned.push(Owned::new(Role::Assistant, String::new(), Some(thought))); - } - if role == Role::Assistant - && let Some(Owned { - role: Role::Assistant, - content: previous, - reasoning: thought, - parts: None, - }) = owned.last_mut() - { - if !previous.is_empty() && !content.is_empty() { - previous.push('\n'); - } - previous.push_str(&content); - if let Some(next) = reasoning.take() { - let current = thought.get_or_insert_with(String::new); - current.push_str(&next); - } - } else { - let mut message = Owned::new(role, content, reasoning.take()); - message.parts = pictures; - owned.push(message); - } - } - "function_call" | "custom_tool_call" => { - if !outputs.is_empty() { - return Err("new function calls cannot interrupt tool outputs".into()); - } - let call_id = item - .get("call_id") - .and_then(Value::as_str) - .ok_or("function call needs call_id")?; - let name = item - .get("name") - .and_then(Value::as_str) - .ok_or("function call needs name")?; - let namespace = match item.get("namespace") { - None | Some(Value::Null) => None, - Some(Value::String(value)) => Some(value.as_str()), - _ => return Err("function namespace must be a string".into()), - }; - let name = crate::response_tools::alias(name, namespace)?; - if call_id.is_empty() - || name.is_empty() - || !name.bytes().all(|byte| { - byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-' - }) - || calls.iter().any(|(id, _)| id == call_id) - { - return Err("function call has an invalid or duplicate identity".into()); - } - let custom = kind == "custom_tool_call"; - let arguments: Value = if custom { - if item.get("arguments").is_some() { - return Err("custom tool call uses input, not arguments".into()); - } - custom_calls.insert(call_id.to_owned()); - json!({"input":item["input"].as_str().ok_or("custom tool call needs text input")?}) - } else { - if item.get("input").is_some() { - return Err("function call uses arguments, not input".into()); - } - let arguments = item["arguments"] - .as_str() - .ok_or("function call needs JSON arguments")?; - serde_json::from_str(arguments) - .map_err(|_| "function call arguments are not JSON")? - }; - let properties = arguments - .as_object() - .ok_or("function call arguments must be an object")?; - let mut markup = format!("\n\n"); - for (parameter, value) in properties { - if parameter.is_empty() - || !parameter.bytes().all(|byte| { - byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-' - }) - { - return Err("function argument name cannot be rendered safely".into()); - } - markup.push_str("\n"); - if let Some(text) = value.as_str() { - markup.push_str(&mark(text)); - } else { - markup.push_str(&mark(&value.to_string())); - } - markup.push_str("\n\n"); - } - markup.push_str("\n"); - calls.push((call_id.to_owned(), markup)); - } - "function_call_output" | "custom_tool_call_output" => { - let call_id = item - .get("call_id") - .and_then(Value::as_str) - .ok_or("tool output needs call_id")?; - if custom_calls.contains(call_id) != (kind == "custom_tool_call_output") { - return Err("tool output kind must match its preceding call".into()); - } - let output = match item.get("output") { - Some(Value::String(text)) => mark(text), - Some(Value::Array(parts)) => parts - .iter() - .map(|part| { - if part["type"] != "input_text" { - return Err( - "tool output supports only input_text content parts", - ); - } - part["text"].as_str().ok_or("tool output part needs text") - }) - .collect::, _>>()? - .into_iter() - .map(mark) - .collect::>() - .join("\n"), - _ => return Err("tool output needs text or input_text parts".into()), - }; - if !calls.iter().any(|(id, _)| id == call_id) - || outputs.iter().any(|(id, _)| id == call_id) - { - return Err( - "tool output must match one preceding unresolved call_id".into() - ); - } - outputs.push((call_id.to_owned(), output.to_owned())); - if outputs.len() == calls.len() { - let call_text = calls - .iter() - .map(|(_, markup)| markup.as_str()) - .collect::>() - .join("\n"); - // Qwen's tool_response blocks carry no call_id. Restore - // call order so parallel results cannot change identity. - let output_text = calls - .iter() - .map(|(call_id, _)| { - let (_, value) = outputs - .iter() - .find(|(id, _)| id == call_id) - .expect("all distinct call IDs have an output"); - format!("\n{value}\n") - }) - .collect::>() - .join("\n"); - if let Some(Owned { - role: Role::Assistant, - content, - reasoning: thought, - parts: None, - }) = owned.last_mut() - { - content.truncate(content.trim_end().len()); - if !content.is_empty() { - content.push_str("\n\n"); - } - content.push_str(&call_text); - if let Some(next) = reasoning.take() { - thought.get_or_insert_with(String::new).push_str(&next); - } - } else { - owned.push(Owned::new(Role::Assistant, call_text, reasoning.take())); - } - owned.push(Owned::new(Role::User, output_text, None)); - calls.clear(); - outputs.clear(); - custom_calls.clear(); - } - } - _ => return Err("unsupported Responses input item".into()), - } - } - if !calls.is_empty() { - return Err("replayed function calls need all tool outputs".into()); - } - if reasoning.is_some() { - return Err( - "reasoning replay needs a following assistant message, tool call, or user turn" - .into(), - ); - } - } - // The pinned Qwen template only accepts leading instruction messages. - // Keep all instruction text and its order/authority; never demote a late - // developer instruction (including approval criteria) into user content. - owned.sort_by_key(|o| !matches!(o.role, Role::System | Role::Developer)); - let messages = owned - .iter() - .map(|o| Message { - role: o.role, - content: &o.content, - reasoning: o.reasoning.as_deref(), - parts: o.parts.as_deref(), - }) - .collect::>(); - let catalog = Catalog::new(&request.tools)?; - let flat: Vec = if request.tools_disabled() { - Vec::new() - } else { - catalog - .flat - .iter() - .map(|tool| mark_json(marks, tool)) - .collect() - }; - let _template = crate::stage_trace::span("render_template"); - prompt::render_with_images( - &messages, - reasoning_effort(request).map_err(|(_, message)| message.to_owned())?, - &flat, - ) -} - mod stream; use stream::*; -fn validate_live_subset(request: &CreateRequest) -> Result<(), (&'static str, &'static str)> { - if request.tool_choice.as_ref().is_some_and(|choice| { - choice != "auto" - && choice != "none" - && choice != "required" - && choice["type"] != "function" - && choice["type"] != "custom" - && choice["type"] != "allowed_tools" - }) { - return Err(( - "tool_choice", - "only auto, none, required, allowed_tools and forced top-level function/custom choices are connected", - )); - } - if request - .truncation - .as_deref() - .is_some_and(|value| value != "disabled") - { - return Err(("truncation", "automatic truncation is not connected yet")); - } - Ok(()) -} - -fn api_error( - status: StatusCode, - kind: &'static str, - code: &'static str, - param: Option<&'static str>, - message: &str, -) -> Response { - ( - status, - Json(json!({"error": {"message": message, "type": kind, "param": param, "code": code}})), - ) - .into_response() -} - #[derive(Clone, Deserialize)] #[serde(tag = "type", rename_all = "snake_case")] pub enum OutputItem { @@ -2407,374 +212,107 @@ pub struct ResponseTrace { pub events: Vec, } -impl ResponseTrace { - pub fn build( - request: &CreateRequest, - items: &[OutputItem], - usage: Usage, - id: &str, - created_at: u64, - completed_at: u64, - ) -> Result { - Self::build_with_terminal(request, items, usage, id, created_at, completed_at, false) - } - - fn build_with_terminal( - request: &CreateRequest, - items: &[OutputItem], - usage: Usage, - id: &str, - created_at: u64, - completed_at: u64, - incomplete: bool, - ) -> Result { - request - .validate() - .map_err(|(param, message)| format!("{param}: {message}"))?; - let mut call_count = 0; - for item in items { - if let OutputItem::FunctionCall { name, .. } = item { - call_count += 1; - request.validate_tool_name(name)?; - } - } - request.validate_tool_count(call_count)?; - if !incomplete && request.tools_required() && call_count == 0 { - return Err("required tool choice produced no tool call".into()); - } - if items.is_empty() { - return Err("a completed response needs an output item".to_owned()); - } - if !id.starts_with("resp_") - || id.len() <= 5 - || !id[5..] - .bytes() - .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-') - || completed_at < created_at - { - return Err("invalid response identity or timestamps".to_owned()); - } - if usage.cached_tokens > usage.input_tokens || usage.reasoning_tokens > usage.output_tokens - { - return Err("usage detail counters exceed their parent count".to_owned()); - } - let text = request - .text - .as_ref() - .map(serde_json::to_value) - .transpose() - .map_err(|error| error.to_string())? - .unwrap_or_else(|| json!({"format": {"type": "text"}})); - let mut response = json!({ - "id": id, - "object": "response", - "created_at": created_at, - "status": "in_progress", - "error": null, - "incomplete_details": null, - "instructions": request.instructions, - "max_output_tokens": request.max_output_tokens, - "model": request.model, - "output": [], - "parallel_tool_calls": request.parallel_tool_calls.unwrap_or(true), - "previous_response_id": request.previous_response_id, - "reasoning": request.reasoning.clone().unwrap_or_else(|| json!({"effort": null, "summary": null})), - "store": request.store.unwrap_or(true), - "temperature": request.temperature.unwrap_or(0.0), - "text": text, - "tool_choice": request.tool_choice.clone().unwrap_or_else(|| json!("auto")), - "tools": request.tools, - "top_p": request.top_p.unwrap_or(1.0), - "truncation": request.truncation.as_deref().unwrap_or("disabled"), - "usage": null, - "user": null, - "metadata": request.metadata.clone().unwrap_or_default(), - }); - let mut emitter = Emitter::default(); - emitter.push("response.created", json!({"response": response})); - emitter.push("response.in_progress", json!({"response": response})); - - let mut output = Vec::with_capacity(items.len()); - let mut all_text = String::new(); - let mut has_text = false; - let mut call_ids = HashSet::new(); - let catalog = Catalog::new(&request.tools)?; - let allowed_tools: HashSet<&str> = catalog - .flat - .iter() - .filter_map(|tool| tool.get("name").and_then(Value::as_str)) - .collect(); - for (index, item) in items.iter().enumerate() { - match item { - OutputItem::Reasoning { deltas, complete } => { - if !complete && !incomplete { - return Err("unfinished reasoning needs an incomplete response".into()); - } - let item_id = format!("rs_{}_{}", &id[5..], index); - let pending = json!({"id":item_id,"type":"reasoning","status":"in_progress","summary":[],"content":[]}); - emitter.push( - "response.output_item.added", - json!({"response_id":id,"output_index":index,"item":pending}), - ); - emitter.push("response.content_part.added", json!({"response_id":id,"item_id":item_id,"output_index":index,"content_index":0,"part":{"type":"reasoning_text","text":""}})); - let whole = deltas.concat(); - for delta in deltas { - emitter.push("response.reasoning_text.delta", json!({"response_id":id,"item_id":item_id,"output_index":index,"content_index":0,"delta":delta})); - } - emitter.push("response.reasoning_text.done", json!({"response_id":id,"item_id":item_id,"output_index":index,"content_index":0,"text":whole})); - let part = json!({"type":"reasoning_text","text":whole}); - emitter.push("response.content_part.done", json!({"response_id":id,"item_id":item_id,"output_index":index,"content_index":0,"part":part})); - let done = json!({"id":item_id,"type":"reasoning","status":if *complete {"completed"} else {"incomplete"},"summary":[],"content":[part]}); - emitter.push( - "response.output_item.done", - json!({"response_id":id,"output_index":index,"item":done}), - ); - output.push(done); - } - OutputItem::Text { deltas } => { - has_text = true; - let item_id = format!("msg_{}_{}", &id[5..], index); - let mut whole = String::new(); - let pending = json!({"id": item_id, "type": "message", "status": "in_progress", "role": "assistant", "content": []}); - emitter.push( - "response.output_item.added", - json!({"response_id": id, "output_index": index, "item": pending}), - ); - emitter.push("response.content_part.added", json!({"response_id": id, "item_id": item_id, "output_index": index, "content_index": 0, "part": text_part("")})); - for delta in deltas { - whole.push_str(delta); - emitter.push("response.output_text.delta", json!({"response_id": id, "item_id": item_id, "output_index": index, "content_index": 0, "delta": delta, "logprobs": []})); - } - all_text.push_str(&whole); - emitter.push("response.output_text.done", json!({"response_id": id, "item_id": item_id, "output_index": index, "content_index": 0, "text": whole, "logprobs": []})); - emitter.push("response.content_part.done", json!({"response_id": id, "item_id": item_id, "output_index": index, "content_index": 0, "part": text_part(&whole)})); - let item_status = if incomplete { - "incomplete" - } else { - "completed" - }; - let done = json!({"id": item_id, "type": "message", "status": item_status, "role": "assistant", "content": [text_part(&whole)]}); - emitter.push( - "response.output_item.done", - json!({"response_id": id, "output_index": index, "item": done}), - ); - output.push(done); - } - OutputItem::FunctionCall { - name, - call_id, - argument_deltas, - } => { - if name.is_empty() || call_id.is_empty() { - return Err("function calls need a name and call_id".to_owned()); - } - if !allowed_tools.contains(name.as_str()) { - return Err(format!("function call names an undeclared tool: {name}")); - } - if !call_ids.insert(call_id) { - return Err("function call_id must be unique".to_owned()); - } - let custom = catalog.is_custom(name); - let prefix = if custom { "ctc" } else { "fc" }; - let item_id = format!("{prefix}_{}_{}", &id[5..], index); - let arguments = argument_deltas.concat(); - let parsed_arguments: Value = serde_json::from_str(&arguments) - .map_err(|_| "function call arguments must be a JSON object")?; - if !parsed_arguments.is_object() { - return Err("function call arguments must be a JSON object".to_owned()); - } - if let Some(schema) = catalog - .flat - .iter() - .find(|tool| tool.get("name").and_then(Value::as_str) == Some(name)) - .and_then(|tool| tool.get("parameters")) - { - reject_remote_refs(schema)?; - let validator = jsonschema::validator_for(schema).map_err(|error| { - format!("invalid function parameter schema: {error}") - })?; - validator.validate(&parsed_arguments).map_err(|error| { - format!("function call arguments violate schema: {error}") - })?; - } - let mut done = json!({"id": item_id, "type": "function_call", "status": "completed", "call_id": call_id, "name": name, "arguments": arguments}); - catalog.restore(&mut done)?; - let field = if custom { "input" } else { "arguments" }; - let (delta_event, done_event) = crate::response_tools::input_events(custom); - let mut pending = done.clone(); - pending["status"] = json!("in_progress"); - pending[field] = json!(""); - emitter.push( - "response.output_item.added", - json!({"response_id":id,"output_index":index,"item":pending}), - ); - let deltas = if custom { - vec![done["input"].as_str().expect("restored input").to_owned()] - } else { - argument_deltas.clone() - }; - for delta in deltas { - emitter.push(delta_event, json!({"response_id":id,"item_id":item_id,"output_index":index,"delta":delta})); - } - emitter.push(done_event, json!({"response_id":id,"item_id":item_id,"output_index":index,field:done[field]})); - emitter.push( - "response.output_item.done", - json!({"response_id": id, "output_index": index, "item": done}), - ); - output.push(done); - } - } - } - - if has_text && !incomplete { - validate_text_format(request, &all_text)?; - } - let total_tokens = usage - .input_tokens - .checked_add(usage.output_tokens) - .ok_or("total token count overflows u64")?; - - response["status"] = json!(if incomplete { - "incomplete" - } else { - "completed" - }); - if incomplete { - response["incomplete_details"] = json!({"reason": "max_output_tokens"}); - } else { - response["completed_at"] = json!(completed_at); - } - response["output"] = json!(output); - response["usage"] = json!({ - "input_tokens": usage.input_tokens, - "input_tokens_details": {"cached_tokens": usage.cached_tokens}, - "output_tokens": usage.output_tokens, - "output_tokens_details": {"reasoning_tokens": usage.reasoning_tokens}, - "total_tokens": total_tokens, - }); - emitter.push( - if incomplete { - "response.incomplete" - } else { - "response.completed" - }, - json!({"response": response}), - ); - Ok(Self { - response, - events: emitter.events, - }) - } - - pub fn sse_frames(&self) -> Vec { - self.events - .iter() - .map(|event| { - format!( - "event: {}\ndata: {}\n\n", - event["type"].as_str().unwrap_or("error"), - event - ) - }) - .collect() - } -} - -fn validate_text_format(request: &CreateRequest, text: &str) -> Result<(), String> { - let Some(options) = &request.text else { - return Ok(()); - }; - match &options.format { - TextFormat::Text => Ok(()), - TextFormat::JsonObject => { - if serde_json::from_str::(text).is_ok_and(|value| value.is_object()) { - Ok(()) - } else { - Err("text.format requires a JSON object".to_owned()) - } - } - TextFormat::JsonSchema { schema, .. } => { - reject_remote_refs(schema)?; - let validator = jsonschema::validator_for(schema) - .map_err(|error| format!("invalid text.format schema: {error}"))?; - let value: Value = serde_json::from_str(text) - .map_err(|error| format!("text.format output is not JSON: {error}"))?; - validator - .validate(&value) - .map_err(|error| format!("text.format output violates schema: {error}")) - } - } -} - -/// Whether a tool's `parameters` is a local, valid object schema. The answer depends on the schema alone, and a coding agent -/// sends the same dozen tool schemas with every request (validated three times per request), so it is remembered by the -/// schema's compact text instead of compiling a validator each time. -fn tool_schema_accepted(parameters: &Value) -> bool { - use std::sync::{Mutex, OnceLock}; - static MEMO: OnceLock>> = OnceLock::new(); - let key = parameters.to_string(); - let memo = MEMO.get_or_init(Default::default); - if let Some(known) = memo.lock().ok().and_then(|memo| memo.get(&key).copied()) { - return known; - } - let accepted = parameters.get("type").and_then(Value::as_str) == Some("object") - && reject_remote_refs(parameters).is_ok() - && jsonschema::validator_for(parameters).is_ok(); - if let Ok(mut memo) = memo.lock() { - if memo.len() >= 512 { - memo.clear(); - } - memo.insert(key, accepted); - } - accepted -} - -fn reject_remote_refs(value: &Value) -> Result<(), String> { - match value { - Value::Object(fields) => { - for key in ["$ref", "$dynamicRef", "$recursiveRef"] { - if fields - .get(key) - .and_then(Value::as_str) - .is_some_and(|reference| !reference.starts_with('#')) - { - return Err(format!("text.format schema cannot use external {key}")); - } - } - for child in fields.values() { - reject_remote_refs(child)?; - } - } - Value::Array(values) => { - for child in values { - reject_remote_refs(child)?; - } - } - _ => {} - } - Ok(()) -} - -fn text_part(text: &str) -> Value { - json!({"type": "output_text", "text": text, "annotations": [], "logprobs": []}) -} - #[derive(Default)] struct Emitter { events: Vec, } -impl Emitter { - fn push(&mut self, kind: &'static str, fields: Value) { - let mut fields = fields - .as_object() - .cloned() - .expect("event fields are an object"); - fields.insert("type".to_owned(), json!(kind)); - fields.insert("sequence_number".to_owned(), json!(self.events.len())); - self.events.push(Value::Object(fields)); - } -} - #[cfg(test)] mod tests; + +mod set_tool_call_recovery_fn; +#[allow(unused_imports)] +use set_tool_call_recovery_fn::resource_not_found; +#[allow(unused_imports)] +pub use set_tool_call_recovery_fn::set_tool_call_recovery; +#[allow(unused_imports)] +use set_tool_call_recovery_fn::store_response; +#[allow(unused_imports)] +use set_tool_call_recovery_fn::tool_options; +mod resource_query_error_fn; +#[allow(unused_imports)] +use resource_query_error_fn::append_input; +#[allow(unused_imports)] +pub use resource_query_error_fn::delete; +#[allow(unused_imports)] +pub use resource_query_error_fn::input_items; +#[allow(unused_imports)] +use resource_query_error_fn::resource_query_error; +#[allow(unused_imports)] +pub use resource_query_error_fn::retrieve; +mod impl_createrequest; +mod impl_createrequest_2; +#[allow(unused_imports)] +use impl_createrequest_2::parse_request; +mod vision_error_fn; +#[allow(unused_imports)] +pub use vision_error_fn::count_input_tokens; +#[allow(unused_imports)] +use vision_error_fn::debug_failed_output; +#[allow(unused_imports)] +use vision_error_fn::expand_images; +#[allow(unused_imports)] +use vision_error_fn::log_generation_failure; +#[allow(unused_imports)] +use vision_error_fn::prepare_input_tokens; +#[allow(unused_imports)] +use vision_error_fn::vision_error; +mod queue_error_fn; +#[allow(unused_imports)] +pub use queue_error_fn::create_route; +#[allow(unused_imports)] +use queue_error_fn::queue_error; +mod create_fn; +#[allow(unused_imports)] +pub use create_fn::create; +mod parse_output_items_fn; +#[cfg(test)] +#[allow(unused_imports)] +use parse_output_items_fn::decode_generation; +#[allow(unused_imports)] +use parse_output_items_fn::decode_generation_with; +#[allow(unused_imports)] +use parse_output_items_fn::decoded_items; +#[allow(unused_imports)] +use parse_output_items_fn::flat_tools; +#[allow(unused_imports)] +use parse_output_items_fn::log_tool_notes; +#[cfg(test)] +#[allow(unused_imports)] +use parse_output_items_fn::parse_output_items; +#[allow(unused_imports)] +use parse_output_items_fn::parse_output_items_after; +#[allow(unused_imports)] +use parse_output_items_fn::reasoning_effort; +#[allow(unused_imports)] +use parse_output_items_fn::reasoning_enabled; +mod impl_reasoningstream; +#[allow(unused_imports)] +use impl_reasoningstream::is_structured; +#[allow(unused_imports)] +use impl_reasoningstream::mark_json; +#[allow(unused_imports)] +use impl_reasoningstream::reasoning_plan; +#[cfg(test)] +#[allow(unused_imports)] +use impl_reasoningstream::render_request_prompt; +#[allow(unused_imports)] +use impl_reasoningstream::unsupported_gptoss_sampling; +mod render_request_fn; +#[allow(unused_imports)] +use render_request_fn::render_request; +mod validate_live_subset_fn; +#[allow(unused_imports)] +use validate_live_subset_fn::api_error; +#[allow(unused_imports)] +use validate_live_subset_fn::validate_live_subset; +mod impl_responsetrace_2; +mod impl_responsetrace_3; +#[allow(unused_imports)] +use impl_responsetrace_3::reject_remote_refs; +#[allow(unused_imports)] +use impl_responsetrace_3::text_part; +#[allow(unused_imports)] +use impl_responsetrace_3::tool_schema_accepted; +#[allow(unused_imports)] +use impl_responsetrace_3::validate_text_format; diff --git a/control-plane/src/responses/create_fn.rs b/control-plane/src/responses/create_fn.rs new file mode 100644 index 00000000..43a78136 --- /dev/null +++ b/control-plane/src/responses/create_fn.rs @@ -0,0 +1,395 @@ +//! Moved out of the parent module by STRA-338: fn create. + +#[allow(unused_imports)] +use super::*; + +pub async fn create( + State(state): State, + body: Result, JsonRejection>, +) -> Response { + let mut request = match parse_request(&state, body) { + Ok(request) => request, + Err(error) => return *error, + }; + if let Err(response) = crate::server_api::ensure_loaded(&state).await { + return *response; + } + if state.worker.read().await.state != WorkerState::Ready { + return api_error( + StatusCode::SERVICE_UNAVAILABLE, + "server_error", + "worker_not_ready", + None, + "the Strata worker is not ready", + ); + } + // The engine's memory governor says the host is at its hard floor: refuse now, with Retry-After, instead of queueing + // work that would push it into swap or the OOM killer (`docs/memory-safety.md`). + if let Some(closed) = state.memory.closed() { + return crate::memory_view::refusal_response(closed.retry_after_secs, &closed.reason); + } + let (Some(tokenizer), Some(generation)) = (&state.tokenizer, &state.generation) else { + return api_error( + StatusCode::NOT_IMPLEMENTED, + "server_error", + "inference_adapter_missing", + None, + "configure tokenizer_dir to enable the text inference preview", + ); + }; + if let Err((param, message)) = validate_live_subset(&request) { + return api_error( + StatusCode::NOT_IMPLEMENTED, + "invalid_request_error", + "unsupported_live_feature", + Some(param), + message, + ); + } + if tokenizer.family() == Family::GptOss { + // The gpt-oss CPU worker's `GEN` line takes temperature, top_p and seed only. An explicit request for a + // sampler it does not have is a client error; defaults from the config or the shared settings are dropped. + if let Some(param) = unsupported_gptoss_sampling(&request.sampling()) { + return api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "unsupported_parameter", + Some(param), + "the gpt-oss family supports temperature, top_p and seed only", + ); + } + } + request.apply_defaults(&state.settings); + if tokenizer.family() == Family::GptOss { + request.top_k = None; + request.min_p = None; + request.repetition_penalty = None; + request.frequency_penalty = None; + request.presence_penalty = None; + request.penalty_last_n = None; + } + let Prepared { + token_ids, + prompt_text, + embeddings, + keep, + } = match prepare_input_tokens(&state, &mut request, tokenizer.clone(), true).await { + Ok(prepared) => prepared, + Err(error) => return *error, + }; + let (max_context, output_cap, text_level_engine) = { + let worker = state.worker.read().await; + ( + worker.max_context, + worker.output_cap.unwrap_or(u32::MAX), + worker.text_level_engine, + ) + }; + // The worker refuses `prompt + max_new + 8 > context` and an output budget above the runtime's cap, but only after the + // request was queued, as a 502. These are client errors: answer them here, as 400, before anything is queued. + let prompt_tokens = token_ids.len(); + let remaining = max_context + .map(|context| { + context + .saturating_sub(prompt_tokens) + .saturating_sub(CONTEXT_MARGIN_TOKENS) + .min(u32::MAX as usize) as u32 + }) + .unwrap_or(32768); + if let Some(context) = max_context + && (remaining == 0 + || request + .max_output_tokens + .is_some_and(|new| u64::from(new) > u64::from(remaining))) + { + return api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "context_length_exceeded", + Some("input"), + &format!( + "the prompt has {prompt_tokens} tokens and the output budget is {}; the model's context is {context} tokens (prompt + output budget + {CONTEXT_MARGIN_TOKENS} tokens of margin must fit)", + request + .max_output_tokens + .map_or_else(|| "unset".to_owned(), |n| n.to_string()), + ), + ); + } + if request + .max_output_tokens + .is_some_and(|new| new > output_cap) + { + return api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "invalid_output_limit", + Some("max_output_tokens"), + &format!( + "max_output_tokens {} exceeds the runtime's limit of {output_cap}", + request.max_output_tokens.unwrap_or_default() + ), + ); + } + let generate = Generate { + token_ids, + max_new: request + .max_output_tokens + .unwrap_or(32768.min(remaining).min(output_cap).max(1)), + sampling: request.sampling(), + tune: request.strata_tune.map(Into::into), + cvec: request.experimental_speed_projection, + embeddings, + keep, + reasoning: reasoning_plan(&request, &state, tokenizer), + prompt_text, + obs: { + let obs = crate::request_log::ObsHandle::current(); + obs.set_stream(request.stream); + obs + }, + }; + if text_level_engine { + // What the text-level engine contract cannot carry is the client's error to hear about now, not a 502 after queueing. + let unsupported = if generate.reasoning.is_some() { + Some(( + "reasoning_budget_tokens", + "reasoning_budget_tokens needs token-level continuation, which the text-level engine contract does not provide", + )) + } else if generate.tune.is_some() { + Some(( + "strata_tune", + "strata_tune is an engine-process setting and is not part of the engine contract", + )) + } else if generate.cvec.is_some() { + Some(( + "experimental_speed_projection", + "experimental_speed_projection (control vectors) is not part of the engine contract", + )) + } else { + None + }; + if let Some((param, message)) = unsupported { + return api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "unsupported_request_field", + Some(param), + message, + ); + } + // The text contract carries sampling as thousandths / millionths; anything finer cannot be served as asked. + if let Err(error) = leleka_serving_policy::fixed::to_fixed_point(&generate.sampling) { + return api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "invalid_sampling_precision", + None, + &format!("sampling: {error}"), + ); + } + } + if request.stream { + let (events, received) = mpsc::channel(16); + let enqueue_span = crate::stage_trace::span("enqueue"); + let enqueued = crate::queue::enqueue( + generation, + GenerationCommand { + queue: None, + activity: Some(state.lifecycle.generation()), + request: generate, + result: GenerationResult::Streaming(events), + }, + state.queue_timeout, + ) + .await; + drop(enqueue_span); + if let Err(error) = enqueued { + return queue_error(error); + } + return stream_live_text( + request, + tokenizer.clone(), + received, + Some(state.response_history.clone()), + ); + } + let (result, received) = oneshot::channel(); + let command = GenerationCommand { + queue: None, + activity: Some(state.lifecycle.generation()), + request: generate, + result: GenerationResult::Buffered(result), + }; + if let Err(error) = crate::queue::enqueue(generation, command, state.queue_timeout).await { + return queue_error(error); + } + let events = match received.await { + Ok(Ok(events)) => events, + Ok(Err(message)) => { + if let Some(retry_after) = crate::memory_view::parse_refusal(&message) { + return crate::memory_view::refusal_response(retry_after, &message); + } + log_generation_failure(&message); + return api_error( + StatusCode::BAD_GATEWAY, + "server_error", + "generation_failed", + None, + &message, + ); + } + Err(_) => { + return api_error( + StatusCode::SERVICE_UNAVAILABLE, + "server_error", + "worker_not_ready", + None, + "the Strata worker stopped before completing the request", + ); + } + }; + let Some(Event::Done(done)) = events.last() else { + return api_error( + StatusCode::BAD_GATEWAY, + "server_error", + "missing_terminal_event", + None, + "the Strata worker did not report DONE", + ); + }; + if done.finish == Finish::Cancel { + return api_error( + StatusCode::BAD_GATEWAY, + "server_error", + "unsupported_finish", + None, + "the text inference preview requires a stop finish", + ); + } + let output_ids = events + .iter() + .filter_map(|event| match event { + Event::Token(id) => Some(*id), + _ => None, + }) + .collect::>(); + let terminal = tokenizer.terminal_ids(); + let output_ids = output_ids + .split(|id| terminal.contains(id)) + .next() + .unwrap_or(&[]) + .to_vec(); + let tokenizer_for_decode = tokenizer.clone(); + let thinking = reasoning_enabled(&request, tokenizer.family()); + let finish = done.finish; + let flat_tools = flat_tools(&request); + let output = match tokio::task::spawn_blocking(move || { + decode_generation_with( + tokenizer_for_decode.as_ref(), + &output_ids, + thinking, + finish, + &flat_tools, + ) + }) + .await + { + Ok(Ok(text)) => text, + Ok(Err(message)) => { + return api_error( + StatusCode::BAD_GATEWAY, + "server_error", + "detokenization_failed", + None, + &message, + ); + } + Err(error) => { + return api_error( + StatusCode::INTERNAL_SERVER_ERROR, + "server_error", + "detokenization_failed", + None, + &error.to_string(), + ); + } + }; + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default(); + let id = format!( + "resp_{:x}_{:x}", + now.as_nanos(), + NEXT_RESPONSE_ID.fetch_add(1, Ordering::Relaxed) + ); + let debug_copy = debug_failed_output().then(|| { + format!( + "reasoning={:?} answer={:?}", + output.reasoning.as_ref().map(|(text, _)| text), + output.answer + ) + }); + let (items, reasoning_tokens) = + match decoded_items(&request, output, &id, finish != Finish::Length) { + Ok(items) => items, + Err(message) => { + log_generation_failure(&message); + if let Some(text) = &debug_copy { + crate::elog!("failed output (STRATA_DEBUG_FAILED_OUTPUT): {text:?}"); + } + return api_error( + StatusCode::BAD_GATEWAY, + "server_error", + "tool_call_parse_failed", + None, + &message, + ); + } + }; + let usage = Usage { + input_tokens: done.prompt_tokens, + output_tokens: done.generated, + // Counted from the ids that were decoded; a text-level engine reports its own total, which + // this count must never exceed (equal on the stdio wire, where each id is one T line). + reasoning_tokens: reasoning_tokens.min(done.generated), + cached_tokens: done.reused.unwrap_or(0), + }; + match ResponseTrace::build_with_terminal( + &request, + &items, + usage, + &id, + now.as_secs(), + now.as_secs(), + done.finish == Finish::Length, + ) { + Ok(trace) => { + if request.store != Some(false) + && let Err(message) = store_response( + &state.response_history, + &id, + &request.model, + &request.input, + &trace.response, + ) + .await + { + return api_error( + StatusCode::INSUFFICIENT_STORAGE, + "server_error", + "response_storage_failed", + None, + message, + ); + } + Json(trace.response).into_response() + } + Err(message) => api_error( + StatusCode::BAD_GATEWAY, + "server_error", + "response_assembly_failed", + None, + &message, + ), + } +} diff --git a/control-plane/src/responses/impl_createrequest.rs b/control-plane/src/responses/impl_createrequest.rs new file mode 100644 index 00000000..5713c8d1 --- /dev/null +++ b/control-plane/src/responses/impl_createrequest.rs @@ -0,0 +1,118 @@ +//! Moved out of the parent module by STRA-338: impl CreateRequest. + +#[allow(unused_imports)] +use super::*; + +impl CreateRequest { + /// The request's sampling fields as the Original's serving layer reads them. + pub fn sampling(&self) -> leleka_sampler_ref::RequestSampling { + leleka_sampler_ref::RequestSampling { + temperature: self.temperature, + top_p: self.top_p, + top_k: self.top_k, + min_p: self.min_p, + repetition_penalty: self.repetition_penalty, + frequency_penalty: self.frequency_penalty, + presence_penalty: self.presence_penalty, + penalty_last_n: self.penalty_last_n, + seed: self.seed, + } + } + + /// Fill what the request left out from the server defaults: the config's `sampling` block, + /// then the shared Chat settings (`{**config, **shared}`, request fields win, an explicit + /// `temperature: 0` stays greedy), the shared `max_tokens`, and the shared reasoning effort. + pub fn apply_defaults(&mut self, settings: &crate::settings::Settings) { + let merged = settings.merged(); + let shared = settings.shared(); + let effective = + leleka_sampler_ref::RequestSampling::overlay(&merged.sampling, &self.sampling()); + self.temperature = effective.temperature; + self.top_p = effective.top_p; + self.top_k = effective.top_k; + self.min_p = effective.min_p; + self.repetition_penalty = effective.repetition_penalty; + self.frequency_penalty = effective.frequency_penalty; + self.presence_penalty = effective.presence_penalty; + self.penalty_last_n = effective.penalty_last_n; + self.seed = effective.seed; + self.experimental_speed_projection = self + .experimental_speed_projection + .or(merged.experimental_speed_projection); + if self.max_output_tokens.is_none() + && let Some(limit) = shared.max_tokens + { + self.max_output_tokens = Some(limit.min(u64::from(u32::MAX)) as u32); + } + if self.reasoning.is_none() + && let Some(effort) = &shared.reasoning_effort + { + self.reasoning = Some(json!({"effort": effort})); + } + } + + pub(super) fn forced_tool(&self) -> Option<&str> { + self.tool_choice + .as_ref() + .filter(|choice| choice["type"] == "function" || choice["type"] == "custom")? + .get("name")? + .as_str() + } + + pub(super) fn allowed_tools(&self) -> Option<&Vec> { + self.tool_choice + .as_ref() + .filter(|choice| choice["type"] == "allowed_tools")? + .get("tools")? + .as_array() + } + + pub(super) fn declared_selector(&self, choice: &Value) -> bool { + choice.as_object().is_some_and(|fields| fields.len() == 2) + && (choice["type"] == "function" || choice["type"] == "custom") + && choice["name"].is_string() + && self + .tools + .iter() + .any(|tool| tool["type"] == choice["type"] && tool["name"] == choice["name"]) + } + + pub(super) fn validate_tool_name(&self, name: &str) -> Result<(), String> { + if self.forced_tool().is_some_and(|forced| forced != name) { + return Err("generated tool does not match forced tool choice".into()); + } + if self + .allowed_tools() + .is_some_and(|allowed| !allowed.iter().any(|tool| tool["name"] == name)) + { + return Err("generated tool is not in allowed_tools".into()); + } + Ok(()) + } + + pub(super) fn tools_required(&self) -> bool { + self.tool_choice.as_ref().is_some_and(|choice| { + choice == "required" + || (choice["type"] == "allowed_tools" && choice["mode"] == "required") + }) || self.forced_tool().is_some() + } + + pub(super) fn tools_disabled(&self) -> bool { + self.tool_choice + .as_ref() + .is_some_and(|choice| choice == "none") + } + + pub(super) fn validate_tool_count(&self, count: usize) -> Result<(), String> { + if self.tools_disabled() && count > 0 { + return Err("tool_choice none forbids tool calls".into()); + } + if self.parallel_tool_calls == Some(false) && count > 1 { + return Err("parallel_tool_calls false permits at most one tool call".into()); + } + if self.forced_tool().is_some() && count > 1 { + return Err("forced tool choice permits exactly one tool call".into()); + } + Ok(()) + } +} diff --git a/control-plane/src/responses/impl_createrequest_2.rs b/control-plane/src/responses/impl_createrequest_2.rs new file mode 100644 index 00000000..f9ca3450 --- /dev/null +++ b/control-plane/src/responses/impl_createrequest_2.rs @@ -0,0 +1,234 @@ +//! Moved out of the parent module by STRA-338: impl CreateRequest (2), impl axum_extract_FromRequest, fn parse_request. + +#[allow(unused_imports)] +use super::*; + +impl CreateRequest { + pub fn validate(&self) -> Result<(), (&'static str, &'static str)> { + if self.model.trim().is_empty() { + return Err(("model", "model must be a nonempty string")); + } + if !self.input.is_string() && !self.input.is_array() { + return Err(("input", "input must be a string or an array")); + } + if self.input.as_str().is_some_and(str::is_empty) + || self.input.as_array().is_some_and(Vec::is_empty) + { + return Err(("input", "input cannot be empty")); + } + if self.max_output_tokens == Some(0) { + return Err(("max_output_tokens", "max_output_tokens must be positive")); + } + crate::sampling::validate(&self.sampling())?; + if let Some(tune) = &self.strata_tune { + crate::sampling::validate_tune(tune)?; + } + if leleka_serving_policy::reasoning::parse_budget( + self.reasoning_budget_tokens.as_ref(), + None, + ) + .is_err() + { + return Err(( + "reasoning_budget_tokens", + "reasoning_budget_tokens must be a whole number of tokens (0: no budget)", + )); + } + if let Some(TextOptions { + format: TextFormat::JsonSchema { name, schema, .. }, + .. + }) = &self.text + && (name.is_empty() || schema.get("type").and_then(Value::as_str) != Some("object")) + { + return Err(( + "text.format", + "json_schema needs a name and a root schema of type object", + )); + } + if let Some(TextOptions { + format: TextFormat::JsonSchema { schema, .. }, + .. + }) = &self.text + { + if reject_remote_refs(schema).is_err() { + return Err(( + "text.format", + "schema cannot use external $ref/$dynamicRef/$recursiveRef", + )); + } + if jsonschema::validator_for(schema).is_err() { + return Err(("text.format", "json_schema needs a valid local schema")); + } + } + reasoning_effort(self)?; + if self + .service_tier + .as_deref() + .is_some_and(|tier| !matches!(tier, "auto" | "default" | "flex" | "priority" | "scale")) + { + return Err(("service_tier", "unsupported service tier")); + } + if self + .text + .as_ref() + .and_then(|text| text.verbosity.as_deref()) + .is_some_and(|level| !matches!(level, "low" | "medium" | "high")) + { + return Err(("text.verbosity", "use low, medium or high")); + } + if self.user.as_ref().is_some_and(|user| user.len() > 512) { + return Err(("user", "user exceeds 512 bytes")); + } + if self + .include + .iter() + .any(|field| field != "reasoning.encrypted_content") + { + return Err(("include", "unsupported optional response field")); + } + if self + .prompt_cache_key + .as_ref() + .is_some_and(|key| key.len() > 512) + { + return Err(("prompt_cache_key", "cache key exceeds 512 bytes")); + } + let catalog = Catalog::new(&self.tools).map_err(|message| ("tools", message))?; + if self.tools_required() && catalog.flat.is_empty() { + return Err(( + "tool_choice", + "required tool choice needs at least one callable tool", + )); + } + if let Some(choice) = &self.tool_choice + && (choice["type"] == "function" || choice["type"] == "custom") + && !self.declared_selector(choice) + { + return Err(( + "tool_choice", + "forced tool needs only type and the name of a declared top-level tool of the same type", + )); + } + if let Some(choice) = &self.tool_choice + && choice["type"] == "allowed_tools" + { + let allowed = self + .allowed_tools() + .ok_or(("tool_choice", "allowed_tools needs a tools array"))?; + if choice.as_object().is_none_or(|fields| fields.len() != 3) + || (choice["mode"] != "auto" && choice["mode"] != "required") + || (choice["mode"] == "required" && allowed.is_empty()) + { + return Err(( + "tool_choice", + "allowed_tools needs only type, mode auto|required and tools; required needs at least one tool", + )); + } + let mut seen = HashSet::new(); + for selector in allowed { + if !self.declared_selector(selector) || !seen.insert(selector["name"].as_str()) { + return Err(( + "tool_choice", + "allowed_tools needs unique declared top-level function/custom type and name selectors", + )); + } + } + } + let mut names = HashSet::new(); + for tool in &catalog.flat { + let Some(name) = tool.get("name").and_then(Value::as_str) else { + return Err(("tools", "only named function tools are supported")); + }; + if tool.get("type").and_then(Value::as_str) != Some("function") + || name.is_empty() + || name.len() > 64 + || !name + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-') + || !names.insert(name) + { + return Err(( + "tools", + "function names must be unique ASCII letters, digits, hyphens or underscores (up to 64 bytes)", + )); + } + if let Some(parameters) = tool.get("parameters") + && !tool_schema_accepted(parameters) + { + return Err(( + "tools", + "function parameters need a local, valid object schema", + )); + } + } + Ok(()) + } +} + +impl axum::extract::FromRequest for TracedJson { + type Rejection = JsonRejection; + + async fn from_request( + request: axum::extract::Request, + state: &S, + ) -> Result { + let _span = crate::stage_trace::span("http_body_json"); + Json::::from_request(request, state).await.map(Self) + } +} + +pub(super) fn parse_request( + state: &AppState, + body: Result, JsonRejection>, +) -> Result> { + let Json(body) = match body { + Ok(body) => body, + Err(error) => { + return Err(Box::new(api_error( + error.status(), + "invalid_request_error", + "invalid_json", + None, + &error.to_string(), + ))); + } + }; + let decode = crate::stage_trace::span("request_decode"); + let request: CreateRequest = match serde_json::from_value(body) { + Ok(request) => request, + Err(error) => { + return Err(Box::new(api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "invalid_request", + None, + &error.to_string(), + ))); + } + }; + drop(decode); + let validated = crate::stage_trace::time("request_validate", || request.validate()); + if let Err((param, message)) = validated { + return Err(Box::new(api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "invalid_request", + Some(param), + message, + ))); + } + if state + .model + .as_ref() + .is_some_and(|model| model != &request.model && !state.aliases.contains(&request.model)) + { + return Err(Box::new(api_error( + StatusCode::NOT_FOUND, + "invalid_request_error", + "model_not_found", + Some("model"), + "the requested model is not served by this runtime", + ))); + } + Ok(request) +} diff --git a/control-plane/src/responses/impl_reasoningstream.rs b/control-plane/src/responses/impl_reasoningstream.rs new file mode 100644 index 00000000..50faf245 --- /dev/null +++ b/control-plane/src/responses/impl_reasoningstream.rs @@ -0,0 +1,129 @@ +//! Moved out of the parent module by STRA-338: impl ReasoningStream, fn unsupported_gptoss_sampling, fn reasoning_plan, fn is_structured, fn render_request_prompt, impl Owned .... + +#[allow(unused_imports)] +use super::*; + +impl ReasoningStream { + pub(super) fn push(&mut self, bytes: &[u8]) -> String { + if self.ended { + return String::new(); + } + self.pending.extend_from_slice(bytes); + let marker = b""; + if let Some(at) = self + .pending + .windows(marker.len()) + .position(|part| part == marker) + { + let text = String::from_utf8_lossy(&self.pending[..at]).into_owned(); + self.pending.clear(); + self.ended = true; + return text; + } + let keep = (1..marker.len()) + .rev() + .find(|n| self.pending.ends_with(&marker[..*n])) + .unwrap_or(0); + let tail = self.pending.split_off(self.pending.len() - keep); + let text = drain_utf8(&mut self.pending, false); + self.pending.extend_from_slice(&tail); + text + } + + pub(super) fn finish(&mut self) -> String { + drain_utf8(&mut self.pending, true) + } +} + +/// The first sampler the request sets that the gpt-oss worker's `GEN` line cannot carry. +pub(super) fn unsupported_gptoss_sampling( + sampling: &leleka_sampler_ref::RequestSampling, +) -> Option<&'static str> { + if sampling.top_k.is_some() { + Some("top_k") + } else if sampling.min_p.is_some() { + Some("min_p") + } else if sampling.repetition_penalty.is_some_and(|v| v != 1.0) { + Some("repetition_penalty") + } else if sampling.frequency_penalty.is_some_and(|v| v != 0.0) { + Some("frequency_penalty") + } else if sampling.presence_penalty.is_some_and(|v| v != 0.0) { + Some("presence_penalty") + } else { + None + } +} + +/// The reasoning-budget wrap-up for this request, if thinking is on and a budget is set (the +/// request's `reasoning_budget_tokens`, else the config's). +pub(super) fn reasoning_plan( + request: &CreateRequest, + state: &AppState, + codec: &Arc, +) -> Option { + // The wrap-up and the byte accounting are the Qwen path's; the Harmony family has no reasoning budget. + let tokenizer = codec.qwen()?; + if !reasoning_enabled(request, codec.family()) { + return None; + } + let budget = leleka_serving_policy::reasoning::parse_budget( + request.reasoning_budget_tokens.as_ref(), + state.settings.reasoning_budget_default(), + ) + .ok()??; + let wrap_up = tokenizer + .encode(leleka_serving_policy::reasoning::WRAP_UP, true) + .ok()?; + let stop_ids = ["<|im_end|>", "<|endoftext|>"] + .into_iter() + .filter_map(|name| tokenizer.special_id(name)) + .collect(); + let bytes_of = tokenizer.clone(); + Some(crate::wire::ReasoningPlan { + budget, + wrap_up, + stop_ids, + token_bytes: Arc::new(move |id| bytes_of.decode_bytes(&[id]).unwrap_or_default()), + }) +} + +pub(super) fn is_structured(request: &CreateRequest) -> bool { + request + .text + .as_ref() + .is_some_and(|text| !matches!(text.format, TextFormat::Text)) +} + +/// The prompt text, for tests and callers that do not read pictures. +#[cfg(test)] +pub(super) fn render_request_prompt(request: &CreateRequest) -> Result { + render_request(request, &tests::test_marks()).map(|(prompt, _)| prompt) +} + +impl Owned { + pub(super) fn new(role: Role, content: String, reasoning: Option) -> Self { + Self { + role, + content, + reasoning, + parts: None, + } + } +} + +/// Every string of a JSON value (keys too) through [`LiteralMarks::mark`]: a tool's description and parameter schema. +pub(super) fn mark_json(marks: &LiteralMarks, value: &Value) -> Value { + match value { + Value::String(text) => Value::String(marks.mark(text).into_owned()), + Value::Array(items) => { + Value::Array(items.iter().map(|item| mark_json(marks, item)).collect()) + } + Value::Object(fields) => Value::Object( + fields + .iter() + .map(|(key, item)| (marks.mark(key).into_owned(), mark_json(marks, item))) + .collect(), + ), + other => other.clone(), + } +} diff --git a/control-plane/src/responses/impl_responsetrace_2.rs b/control-plane/src/responses/impl_responsetrace_2.rs new file mode 100644 index 00000000..94b34b89 --- /dev/null +++ b/control-plane/src/responses/impl_responsetrace_2.rs @@ -0,0 +1,253 @@ +//! Moved out of the parent module by STRA-338: impl ResponseTrace (2). + +#[allow(unused_imports)] +use super::*; + +impl ResponseTrace { + pub(super) fn build_with_terminal( + request: &CreateRequest, + items: &[OutputItem], + usage: Usage, + id: &str, + created_at: u64, + completed_at: u64, + incomplete: bool, + ) -> Result { + request + .validate() + .map_err(|(param, message)| format!("{param}: {message}"))?; + let mut call_count = 0; + for item in items { + if let OutputItem::FunctionCall { name, .. } = item { + call_count += 1; + request.validate_tool_name(name)?; + } + } + request.validate_tool_count(call_count)?; + if !incomplete && request.tools_required() && call_count == 0 { + return Err("required tool choice produced no tool call".into()); + } + if items.is_empty() { + return Err("a completed response needs an output item".to_owned()); + } + if !id.starts_with("resp_") + || id.len() <= 5 + || !id[5..] + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-') + || completed_at < created_at + { + return Err("invalid response identity or timestamps".to_owned()); + } + if usage.cached_tokens > usage.input_tokens || usage.reasoning_tokens > usage.output_tokens + { + return Err("usage detail counters exceed their parent count".to_owned()); + } + let text = request + .text + .as_ref() + .map(serde_json::to_value) + .transpose() + .map_err(|error| error.to_string())? + .unwrap_or_else(|| json!({"format": {"type": "text"}})); + let mut response = json!({ + "id": id, + "object": "response", + "created_at": created_at, + "status": "in_progress", + "error": null, + "incomplete_details": null, + "instructions": request.instructions, + "max_output_tokens": request.max_output_tokens, + "model": request.model, + "output": [], + "parallel_tool_calls": request.parallel_tool_calls.unwrap_or(true), + "previous_response_id": request.previous_response_id, + "reasoning": request.reasoning.clone().unwrap_or_else(|| json!({"effort": null, "summary": null})), + "store": request.store.unwrap_or(true), + "temperature": request.temperature.unwrap_or(0.0), + "text": text, + "tool_choice": request.tool_choice.clone().unwrap_or_else(|| json!("auto")), + "tools": request.tools, + "top_p": request.top_p.unwrap_or(1.0), + "truncation": request.truncation.as_deref().unwrap_or("disabled"), + "usage": null, + "user": null, + "metadata": request.metadata.clone().unwrap_or_default(), + }); + let mut emitter = Emitter::default(); + emitter.push("response.created", json!({"response": response})); + emitter.push("response.in_progress", json!({"response": response})); + + let mut output = Vec::with_capacity(items.len()); + let mut all_text = String::new(); + let mut has_text = false; + let mut call_ids = HashSet::new(); + let catalog = Catalog::new(&request.tools)?; + let allowed_tools: HashSet<&str> = catalog + .flat + .iter() + .filter_map(|tool| tool.get("name").and_then(Value::as_str)) + .collect(); + for (index, item) in items.iter().enumerate() { + match item { + OutputItem::Reasoning { deltas, complete } => { + if !complete && !incomplete { + return Err("unfinished reasoning needs an incomplete response".into()); + } + let item_id = format!("rs_{}_{}", &id[5..], index); + let pending = json!({"id":item_id,"type":"reasoning","status":"in_progress","summary":[],"content":[]}); + emitter.push( + "response.output_item.added", + json!({"response_id":id,"output_index":index,"item":pending}), + ); + emitter.push("response.content_part.added", json!({"response_id":id,"item_id":item_id,"output_index":index,"content_index":0,"part":{"type":"reasoning_text","text":""}})); + let whole = deltas.concat(); + for delta in deltas { + emitter.push("response.reasoning_text.delta", json!({"response_id":id,"item_id":item_id,"output_index":index,"content_index":0,"delta":delta})); + } + emitter.push("response.reasoning_text.done", json!({"response_id":id,"item_id":item_id,"output_index":index,"content_index":0,"text":whole})); + let part = json!({"type":"reasoning_text","text":whole}); + emitter.push("response.content_part.done", json!({"response_id":id,"item_id":item_id,"output_index":index,"content_index":0,"part":part})); + let done = json!({"id":item_id,"type":"reasoning","status":if *complete {"completed"} else {"incomplete"},"summary":[],"content":[part]}); + emitter.push( + "response.output_item.done", + json!({"response_id":id,"output_index":index,"item":done}), + ); + output.push(done); + } + OutputItem::Text { deltas } => { + has_text = true; + let item_id = format!("msg_{}_{}", &id[5..], index); + let mut whole = String::new(); + let pending = json!({"id": item_id, "type": "message", "status": "in_progress", "role": "assistant", "content": []}); + emitter.push( + "response.output_item.added", + json!({"response_id": id, "output_index": index, "item": pending}), + ); + emitter.push("response.content_part.added", json!({"response_id": id, "item_id": item_id, "output_index": index, "content_index": 0, "part": text_part("")})); + for delta in deltas { + whole.push_str(delta); + emitter.push("response.output_text.delta", json!({"response_id": id, "item_id": item_id, "output_index": index, "content_index": 0, "delta": delta, "logprobs": []})); + } + all_text.push_str(&whole); + emitter.push("response.output_text.done", json!({"response_id": id, "item_id": item_id, "output_index": index, "content_index": 0, "text": whole, "logprobs": []})); + emitter.push("response.content_part.done", json!({"response_id": id, "item_id": item_id, "output_index": index, "content_index": 0, "part": text_part(&whole)})); + let item_status = if incomplete { + "incomplete" + } else { + "completed" + }; + let done = json!({"id": item_id, "type": "message", "status": item_status, "role": "assistant", "content": [text_part(&whole)]}); + emitter.push( + "response.output_item.done", + json!({"response_id": id, "output_index": index, "item": done}), + ); + output.push(done); + } + OutputItem::FunctionCall { + name, + call_id, + argument_deltas, + } => { + if name.is_empty() || call_id.is_empty() { + return Err("function calls need a name and call_id".to_owned()); + } + if !allowed_tools.contains(name.as_str()) { + return Err(format!("function call names an undeclared tool: {name}")); + } + if !call_ids.insert(call_id) { + return Err("function call_id must be unique".to_owned()); + } + let custom = catalog.is_custom(name); + let prefix = if custom { "ctc" } else { "fc" }; + let item_id = format!("{prefix}_{}_{}", &id[5..], index); + let arguments = argument_deltas.concat(); + let parsed_arguments: Value = serde_json::from_str(&arguments) + .map_err(|_| "function call arguments must be a JSON object")?; + if !parsed_arguments.is_object() { + return Err("function call arguments must be a JSON object".to_owned()); + } + if let Some(schema) = catalog + .flat + .iter() + .find(|tool| tool.get("name").and_then(Value::as_str) == Some(name)) + .and_then(|tool| tool.get("parameters")) + { + reject_remote_refs(schema)?; + let validator = jsonschema::validator_for(schema).map_err(|error| { + format!("invalid function parameter schema: {error}") + })?; + validator.validate(&parsed_arguments).map_err(|error| { + format!("function call arguments violate schema: {error}") + })?; + } + let mut done = json!({"id": item_id, "type": "function_call", "status": "completed", "call_id": call_id, "name": name, "arguments": arguments}); + catalog.restore(&mut done)?; + let field = if custom { "input" } else { "arguments" }; + let (delta_event, done_event) = crate::response_tools::input_events(custom); + let mut pending = done.clone(); + pending["status"] = json!("in_progress"); + pending[field] = json!(""); + emitter.push( + "response.output_item.added", + json!({"response_id":id,"output_index":index,"item":pending}), + ); + let deltas = if custom { + vec![done["input"].as_str().expect("restored input").to_owned()] + } else { + argument_deltas.clone() + }; + for delta in deltas { + emitter.push(delta_event, json!({"response_id":id,"item_id":item_id,"output_index":index,"delta":delta})); + } + emitter.push(done_event, json!({"response_id":id,"item_id":item_id,"output_index":index,field:done[field]})); + emitter.push( + "response.output_item.done", + json!({"response_id": id, "output_index": index, "item": done}), + ); + output.push(done); + } + } + } + + if has_text && !incomplete { + validate_text_format(request, &all_text)?; + } + let total_tokens = usage + .input_tokens + .checked_add(usage.output_tokens) + .ok_or("total token count overflows u64")?; + + response["status"] = json!(if incomplete { + "incomplete" + } else { + "completed" + }); + if incomplete { + response["incomplete_details"] = json!({"reason": "max_output_tokens"}); + } else { + response["completed_at"] = json!(completed_at); + } + response["output"] = json!(output); + response["usage"] = json!({ + "input_tokens": usage.input_tokens, + "input_tokens_details": {"cached_tokens": usage.cached_tokens}, + "output_tokens": usage.output_tokens, + "output_tokens_details": {"reasoning_tokens": usage.reasoning_tokens}, + "total_tokens": total_tokens, + }); + emitter.push( + if incomplete { + "response.incomplete" + } else { + "response.completed" + }, + json!({"response": response}), + ); + Ok(Self { + response, + events: emitter.events, + }) + } +} diff --git a/control-plane/src/responses/impl_responsetrace_3.rs b/control-plane/src/responses/impl_responsetrace_3.rs new file mode 100644 index 00000000..38dc1e35 --- /dev/null +++ b/control-plane/src/responses/impl_responsetrace_3.rs @@ -0,0 +1,110 @@ +//! Moved out of the parent module by STRA-338: impl ResponseTrace (3), fn validate_text_format, fn tool_schema_accepted, fn reject_remote_refs, fn text_part, impl Emitter. + +#[allow(unused_imports)] +use super::*; + +impl ResponseTrace { + pub fn sse_frames(&self) -> Vec { + self.events + .iter() + .map(|event| { + format!( + "event: {}\ndata: {}\n\n", + event["type"].as_str().unwrap_or("error"), + event + ) + }) + .collect() + } +} + +pub(super) fn validate_text_format(request: &CreateRequest, text: &str) -> Result<(), String> { + let Some(options) = &request.text else { + return Ok(()); + }; + match &options.format { + TextFormat::Text => Ok(()), + TextFormat::JsonObject => { + if serde_json::from_str::(text).is_ok_and(|value| value.is_object()) { + Ok(()) + } else { + Err("text.format requires a JSON object".to_owned()) + } + } + TextFormat::JsonSchema { schema, .. } => { + reject_remote_refs(schema)?; + let validator = jsonschema::validator_for(schema) + .map_err(|error| format!("invalid text.format schema: {error}"))?; + let value: Value = serde_json::from_str(text) + .map_err(|error| format!("text.format output is not JSON: {error}"))?; + validator + .validate(&value) + .map_err(|error| format!("text.format output violates schema: {error}")) + } + } +} + +/// Whether a tool's `parameters` is a local, valid object schema. The answer depends on the schema alone, and a coding agent +/// sends the same dozen tool schemas with every request (validated three times per request), so it is remembered by the +/// schema's compact text instead of compiling a validator each time. +pub(super) fn tool_schema_accepted(parameters: &Value) -> bool { + use std::sync::{Mutex, OnceLock}; + static MEMO: OnceLock>> = OnceLock::new(); + let key = parameters.to_string(); + let memo = MEMO.get_or_init(Default::default); + if let Some(known) = memo.lock().ok().and_then(|memo| memo.get(&key).copied()) { + return known; + } + let accepted = parameters.get("type").and_then(Value::as_str) == Some("object") + && reject_remote_refs(parameters).is_ok() + && jsonschema::validator_for(parameters).is_ok(); + if let Ok(mut memo) = memo.lock() { + if memo.len() >= 512 { + memo.clear(); + } + memo.insert(key, accepted); + } + accepted +} + +pub(super) fn reject_remote_refs(value: &Value) -> Result<(), String> { + match value { + Value::Object(fields) => { + for key in ["$ref", "$dynamicRef", "$recursiveRef"] { + if fields + .get(key) + .and_then(Value::as_str) + .is_some_and(|reference| !reference.starts_with('#')) + { + return Err(format!("text.format schema cannot use external {key}")); + } + } + for child in fields.values() { + reject_remote_refs(child)?; + } + } + Value::Array(values) => { + for child in values { + reject_remote_refs(child)?; + } + } + _ => {} + } + Ok(()) +} + +pub(super) fn text_part(text: &str) -> Value { + json!({"type": "output_text", "text": text, "annotations": [], "logprobs": []}) +} + +impl Emitter { + pub(super) fn push(&mut self, kind: &'static str, fields: Value) { + let mut fields = fields + .as_object() + .cloned() + .expect("event fields are an object"); + fields.insert("type".to_owned(), json!(kind)); + fields.insert("sequence_number".to_owned(), json!(self.events.len())); + self.events.push(Value::Object(fields)); + } +} diff --git a/control-plane/src/responses/parse_output_items_fn.rs b/control-plane/src/responses/parse_output_items_fn.rs new file mode 100644 index 00000000..aec93993 --- /dev/null +++ b/control-plane/src/responses/parse_output_items_fn.rs @@ -0,0 +1,220 @@ +//! Moved out of the parent module by STRA-338: fn parse_output_items, fn parse_output_items_after, fn flat_tools, fn log_tool_notes, fn reasoning_effort, fn reasoning_enabled .... + +#[allow(unused_imports)] +use super::*; + +#[cfg(test)] +pub(super) fn parse_output_items( + request: &CreateRequest, + output: String, + id: &str, +) -> Result, String> { + parse_output_items_after(request, output, id, false) +} + +/// `natural_stop`: the generation ended by itself and not at the token limit, so a call that ends the text on `` is whole. +pub(super) fn parse_output_items_after( + request: &CreateRequest, + output: String, + id: &str, + natural_stop: bool, +) -> Result, String> { + if request.tools.is_empty() { + return Ok(vec![OutputItem::Text { + deltas: vec![output], + }]); + } + let catalog = Catalog::new(&request.tools)?; + let parsed = tool_output::parse_with(&output, &catalog.flat, tool_options(natural_stop))?; + log_tool_notes(&parsed.notes); + let mut items = parsed + .segments + .into_iter() + .enumerate() + .map(|(index, segment)| match segment { + Segment::Text(text) => OutputItem::Text { deltas: vec![text] }, + Segment::Call { name, arguments } => OutputItem::FunctionCall { + name, + call_id: format!("call_{}_{}", &id[5..], index), + argument_deltas: vec![arguments.to_string()], + }, + }) + .collect::>(); + if items.is_empty() { + items.push(OutputItem::Text { + deltas: vec![String::new()], + }); + } + Ok(items) +} + +/// The request's tool declarations in the form the parser reads; none when the request declares no tools. +pub(super) fn flat_tools(request: &CreateRequest) -> Vec { + Catalog::new(&request.tools) + .map(|catalog| catalog.flat) + .unwrap_or_default() +} + +/// A tool call that was accepted although the template form was not followed is never silent: it is logged here. +pub(super) fn log_tool_notes(notes: &tool_output::Notes) { + if !notes.is_empty() { + crate::elog!("tool call accepted beyond the template form ({notes})"); + } +} + +pub(super) fn reasoning_effort( + request: &CreateRequest, +) -> Result { + let Some(value) = &request.reasoning else { + return Ok(Effort::XHigh); + }; + let fields = value + .as_object() + .ok_or(("reasoning", "reasoning must be an object"))?; + if fields + .keys() + .any(|key| !matches!(key.as_str(), "effort" | "summary")) + { + return Err(("reasoning", "only effort and summary are supported")); + } + if fields + .get("summary") + .is_some_and(|value| !value.is_null() && value != "auto" && value != "none") + { + return Err(( + "reasoning.summary", + "only auto, none or null is supported; this runtime returns raw reasoning content with an empty summary", + )); + } + match fields.get("effort") { + None | Some(Value::Null) => Ok(Effort::XHigh), + Some(Value::String(effort)) => match effort.as_str() { + "none" => Ok(Effort::None), + // The template has no "minimal"; the closest instruction it has is the brief one. + "minimal" | "low" => Ok(Effort::Low), + "medium" => Ok(Effort::Medium), + "high" => Ok(Effort::High), + "xhigh" => Ok(Effort::XHigh), + _ => Err(( + "reasoning.effort", + "use none, minimal, low, medium, high or xhigh", + )), + }, + _ => Err(("reasoning.effort", "effort must be a string or null")), + } +} + +/// Whether the output starts inside a reasoning block that ends with ``. gpt-oss always reasons. +pub(super) fn reasoning_enabled(request: &CreateRequest, family: Family) -> bool { + family == Family::GptOss || reasoning_effort(request).is_ok_and(|effort| effort != Effort::None) +} + +#[cfg(test)] +pub(super) fn decode_generation( + tokenizer: &dyn TextCodec, + ids: &[u32], + reasoning: bool, + finish: Finish, +) -> Result { + decode_generation_with(tokenizer, ids, reasoning, finish, &[]) +} + +/// `tools`: the flat declarations of the request, to tell a call the reasoning ends on from one it only quotes. +pub(super) fn decode_generation_with( + tokenizer: &dyn TextCodec, + ids: &[u32], + reasoning: bool, + finish: Finish, + tools: &[Value], +) -> Result { + let bytes = decode_all(tokenizer, ids)?; + if !reasoning { + return Ok(DecodedGeneration { + answer: String::from_utf8_lossy(&bytes).into_owned(), + reasoning: None, + reasoning_tokens: 0, + }); + } + let marker = b""; + let boundary = bytes.windows(marker.len()).position(|part| part == marker); + let Some(boundary) = boundary else { + if finish != Finish::Length { + // The model stopped by itself without closing its reasoning. If the text ends on whole tool calls of declared + // tools, the reasoning is what comes before them and they are the answer; otherwise the turn is malformed. + // (The calls were already streamed as reasoning text; the reasoning item here ends before them.) + let text = String::from_utf8_lossy(&bytes); + if let Some(at) = tool_output::calls_at_end(&text, tools, tool_options(true)) { + crate::elog!( + "tool call accepted beyond the template form (written inside the reasoning, no )" + ); + let mut consumed = 0; + let mut reasoning_tokens = 0; + let mut decoder = tokenizer.decoder(); + for id in ids { + if consumed >= at { + break; + } + consumed += decoder.push(*id)?.len(); + reasoning_tokens += 1; + } + return Ok(DecodedGeneration { + answer: text[at..].to_owned(), + reasoning: Some((text[..at].to_owned(), true)), + reasoning_tokens, + }); + } + return Err("reasoning ended without ".into()); + } + return Ok(DecodedGeneration { + answer: String::new(), + reasoning: Some((String::from_utf8_lossy(&bytes).into_owned(), false)), + reasoning_tokens: ids.len() as u64, + }); + }; + let mut consumed = 0; + let mut reasoning_tokens = 0; + let mut decoder = tokenizer.decoder(); + for id in ids { + consumed += decoder.push(*id)?.len(); + reasoning_tokens += 1; + if consumed >= boundary + marker.len() { + break; + } + } + Ok(DecodedGeneration { + answer: String::from_utf8_lossy(&bytes[boundary + marker.len()..]) + .trim_start_matches('\n') + .to_owned(), + reasoning: Some(( + String::from_utf8_lossy(&bytes[..boundary]).into_owned(), + true, + )), + reasoning_tokens, + }) +} + +pub(super) fn decoded_items( + request: &CreateRequest, + decoded: DecodedGeneration, + id: &str, + natural_stop: bool, +) -> Result<(Vec, u64), String> { + let mut items = Vec::new(); + let mut reasoning_incomplete = false; + if let Some((text, complete)) = decoded.reasoning { + items.push(OutputItem::Reasoning { + deltas: vec![text], + complete, + }); + reasoning_incomplete = !complete; + } + if !reasoning_incomplete { + items.extend(parse_output_items_after( + request, + decoded.answer, + id, + natural_stop, + )?); + } + Ok((items, decoded.reasoning_tokens)) +} diff --git a/control-plane/src/responses/queue_error_fn.rs b/control-plane/src/responses/queue_error_fn.rs new file mode 100644 index 00000000..e20def2c --- /dev/null +++ b/control-plane/src/responses/queue_error_fn.rs @@ -0,0 +1,31 @@ +//! Moved out of the parent module by STRA-338: fn queue_error, fn create_route. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn queue_error(error: crate::queue::Error) -> Response { + match error { + crate::queue::Error::Expired => api_error( + StatusCode::GATEWAY_TIMEOUT, + "server_error", + "queue_timeout", + None, + "request exceeded the configured queue deadline before worker claim; generation was not started", + ), + crate::queue::Error::Closed => api_error( + StatusCode::SERVICE_UNAVAILABLE, + "server_error", + "worker_not_ready", + None, + "the Strata worker command queue closed before request claim", + ), + } +} + +/// The `/v1/responses` route: [`create`] with the body read and parse timed. +pub async fn create_route( + state: State, + body: Result, +) -> Response { + create(state, body.map(|traced| traced.0)).await +} diff --git a/control-plane/src/responses/render_request_fn.rs b/control-plane/src/responses/render_request_fn.rs new file mode 100644 index 00000000..3ac78b0c --- /dev/null +++ b/control-plane/src/responses/render_request_fn.rs @@ -0,0 +1,395 @@ +//! Moved out of the parent module by STRA-338: fn render_request. + +#[allow(unused_imports)] +use super::*; + +/// The rendered prompt and the sources of its pictures, in prompt order. +/// +/// Control-token text inside a message is text: every string that comes from the client (instructions, message text, reasoning, +/// tool-call arguments, tool outputs, tool descriptions and schemas) goes through [`LiteralMarks::mark`] before the template +/// runs, and the tokenizer encodes the marks as ordinary text ([`Tokenizer::encode_marked`]). The markers this function and the +/// template write themselves (``, ``, the template's turn and `` markers) stay literal. +pub(super) fn render_request( + request: &CreateRequest, + marks: &LiteralMarks, +) -> Result<(String, Vec), String> { + let mark = |text: &str| marks.mark(text).into_owned(); + let mut owned = Vec::::new(); + if let Some(instructions) = &request.instructions { + owned.push(Owned::new(Role::System, mark(instructions), None)); + } + if let Some(name) = request.forced_tool() { + let kind = if request + .tool_choice + .as_ref() + .is_some_and(|choice| choice["type"] == "custom") + { + "custom tool" + } else { + "function" + }; + owned.push(Owned::new( + Role::System, + mark(&format!( + "Call exactly one {kind} in this response: {name}. Do not call any other tool." + )), + None, + )); + } else if request.tools_required() { + owned.push(Owned::new( + Role::System, + "Call at least one tool in this response.".to_owned(), + None, + )); + } + if let Some(allowed) = request.allowed_tools() { + owned.push(Owned::new(Role::System, if allowed.is_empty() { + "Do not call any tools in this response.".to_owned() + } else { + mark(&format!("Only these tools may be called in this response: {}. Do not call any other tool.", serde_json::to_string(allowed).expect("selector serialization"))) + }, None)); + } + if request.parallel_tool_calls == Some(false) + && !request.tools_disabled() + && !request.tools.is_empty() + { + owned.push(Owned::new( + Role::System, + "Use at most one tool call in this response.".to_owned(), + None, + )); + } + if let Some(options) = &request.text { + let instruction = match &options.format { + TextFormat::Text => None, + TextFormat::JsonObject => Some("Return exactly one JSON object as your final text response. Do not add Markdown fences or commentary.".to_owned()), + TextFormat::JsonSchema { schema, .. } => Some(format!("Return exactly one JSON object matching this JSON Schema as your final text response. Do not add Markdown fences or commentary.\nJSON Schema: {schema}")), + }; + if let Some(mut instruction) = instruction { + if !request.tools_disabled() && !request.tools.is_empty() { + instruction.push_str(" Function calls still use the tool-call format; this JSON requirement applies to your final text answer after any necessary tool results."); + } + owned.push(Owned::new(Role::System, mark(&instruction), None)); + } + } + if let Some(input) = request.input.as_str() { + owned.push(Owned::new(Role::User, mark(input), None)); + } else { + let items = request + .input + .as_array() + .ok_or("input must be a string or array")?; + let mut calls = Vec::<(String, String)>::new(); + let mut outputs = Vec::<(String, String)>::new(); + let mut custom_calls = HashSet::::new(); + let mut reasoning = None::; + for item in items { + let kind = item + .get("type") + .and_then(Value::as_str) + .unwrap_or("message"); + match kind { + "reasoning" => { + if reasoning.is_some() || !calls.is_empty() { + return Err( + "reasoning must precede its assistant message or tool calls".into() + ); + } + if item.get("encrypted_content").is_some_and(|v| !v.is_null()) { + return Err("encrypted reasoning replay is not supported".into()); + } + let parts = item + .get("content") + .and_then(Value::as_array) + .ok_or("reasoning replay requires raw reasoning_text content")?; + let mut text = String::new(); + for part in parts { + if part.get("type").and_then(Value::as_str) != Some("reasoning_text") { + return Err("reasoning replay requires reasoning_text parts".into()); + } + text.push_str( + part.get("text") + .and_then(Value::as_str) + .ok_or("reasoning_text needs text")?, + ); + } + reasoning = Some(mark(&text)); + } + "message" => { + if !calls.is_empty() { + return Err( + "every replayed function call needs an output before the next message" + .into(), + ); + } + let role = match item.get("role").and_then(Value::as_str) { + Some("system") => Role::System, + Some("developer") => Role::Developer, + Some("user") => Role::User, + Some("assistant") => Role::Assistant, + _ => return Err("unsupported input message role".into()), + }; + let mut pictures: Option> = None; + let content = match item.get("content") { + Some(Value::String(text)) => mark(text), + Some(Value::Array(parts)) => { + let mut text = String::new(); + let mut listed = Vec::new(); + for part in parts { + match part.get("type").and_then(Value::as_str) { + Some("input_text" | "output_text") => { + let piece = mark( + part.get("text") + .and_then(Value::as_str) + .ok_or("text part needs text")?, + ); + text.push_str(&piece); + listed.push(Part::Text(piece)); + } + Some("input_image") => { + listed.push(Part::Image( + leleka_serving_policy::vision::image_source(part), + )); + } + _ => { + return Err( + "only text and image content parts are supported" + .into(), + ); + } + } + } + if listed.iter().any(|part| matches!(part, Part::Image(_))) { + match role { + Role::User => pictures = Some(listed), + Role::System | Role::Developer => { + return Err("System message cannot contain images.".into()); + } + Role::Assistant => { + return Err( + "images are only supported in user messages".into() + ); + } + } + } + text + } + _ => return Err("input message needs text content".into()), + }; + if role != Role::Assistant + && let Some(thought) = reasoning.take() + { + owned.push(Owned::new(Role::Assistant, String::new(), Some(thought))); + } + if role == Role::Assistant + && let Some(Owned { + role: Role::Assistant, + content: previous, + reasoning: thought, + parts: None, + }) = owned.last_mut() + { + if !previous.is_empty() && !content.is_empty() { + previous.push('\n'); + } + previous.push_str(&content); + if let Some(next) = reasoning.take() { + let current = thought.get_or_insert_with(String::new); + current.push_str(&next); + } + } else { + let mut message = Owned::new(role, content, reasoning.take()); + message.parts = pictures; + owned.push(message); + } + } + "function_call" | "custom_tool_call" => { + if !outputs.is_empty() { + return Err("new function calls cannot interrupt tool outputs".into()); + } + let call_id = item + .get("call_id") + .and_then(Value::as_str) + .ok_or("function call needs call_id")?; + let name = item + .get("name") + .and_then(Value::as_str) + .ok_or("function call needs name")?; + let namespace = match item.get("namespace") { + None | Some(Value::Null) => None, + Some(Value::String(value)) => Some(value.as_str()), + _ => return Err("function namespace must be a string".into()), + }; + let name = crate::response_tools::alias(name, namespace)?; + if call_id.is_empty() + || name.is_empty() + || !name.bytes().all(|byte| { + byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-' + }) + || calls.iter().any(|(id, _)| id == call_id) + { + return Err("function call has an invalid or duplicate identity".into()); + } + let custom = kind == "custom_tool_call"; + let arguments: Value = if custom { + if item.get("arguments").is_some() { + return Err("custom tool call uses input, not arguments".into()); + } + custom_calls.insert(call_id.to_owned()); + json!({"input":item["input"].as_str().ok_or("custom tool call needs text input")?}) + } else { + if item.get("input").is_some() { + return Err("function call uses arguments, not input".into()); + } + let arguments = item["arguments"] + .as_str() + .ok_or("function call needs JSON arguments")?; + serde_json::from_str(arguments) + .map_err(|_| "function call arguments are not JSON")? + }; + let properties = arguments + .as_object() + .ok_or("function call arguments must be an object")?; + let mut markup = format!("\n\n"); + for (parameter, value) in properties { + if parameter.is_empty() + || !parameter.bytes().all(|byte| { + byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-' + }) + { + return Err("function argument name cannot be rendered safely".into()); + } + markup.push_str("\n"); + if let Some(text) = value.as_str() { + markup.push_str(&mark(text)); + } else { + markup.push_str(&mark(&value.to_string())); + } + markup.push_str("\n\n"); + } + markup.push_str("\n"); + calls.push((call_id.to_owned(), markup)); + } + "function_call_output" | "custom_tool_call_output" => { + let call_id = item + .get("call_id") + .and_then(Value::as_str) + .ok_or("tool output needs call_id")?; + if custom_calls.contains(call_id) != (kind == "custom_tool_call_output") { + return Err("tool output kind must match its preceding call".into()); + } + let output = match item.get("output") { + Some(Value::String(text)) => mark(text), + Some(Value::Array(parts)) => parts + .iter() + .map(|part| { + if part["type"] != "input_text" { + return Err( + "tool output supports only input_text content parts", + ); + } + part["text"].as_str().ok_or("tool output part needs text") + }) + .collect::, _>>()? + .into_iter() + .map(mark) + .collect::>() + .join("\n"), + _ => return Err("tool output needs text or input_text parts".into()), + }; + if !calls.iter().any(|(id, _)| id == call_id) + || outputs.iter().any(|(id, _)| id == call_id) + { + return Err( + "tool output must match one preceding unresolved call_id".into() + ); + } + outputs.push((call_id.to_owned(), output.to_owned())); + if outputs.len() == calls.len() { + let call_text = calls + .iter() + .map(|(_, markup)| markup.as_str()) + .collect::>() + .join("\n"); + // Qwen's tool_response blocks carry no call_id. Restore + // call order so parallel results cannot change identity. + let output_text = calls + .iter() + .map(|(call_id, _)| { + let (_, value) = outputs + .iter() + .find(|(id, _)| id == call_id) + .expect("all distinct call IDs have an output"); + format!("\n{value}\n") + }) + .collect::>() + .join("\n"); + if let Some(Owned { + role: Role::Assistant, + content, + reasoning: thought, + parts: None, + }) = owned.last_mut() + { + content.truncate(content.trim_end().len()); + if !content.is_empty() { + content.push_str("\n\n"); + } + content.push_str(&call_text); + if let Some(next) = reasoning.take() { + thought.get_or_insert_with(String::new).push_str(&next); + } + } else { + owned.push(Owned::new(Role::Assistant, call_text, reasoning.take())); + } + owned.push(Owned::new(Role::User, output_text, None)); + calls.clear(); + outputs.clear(); + custom_calls.clear(); + } + } + _ => return Err("unsupported Responses input item".into()), + } + } + if !calls.is_empty() { + return Err("replayed function calls need all tool outputs".into()); + } + if reasoning.is_some() { + return Err( + "reasoning replay needs a following assistant message, tool call, or user turn" + .into(), + ); + } + } + // The pinned Qwen template only accepts leading instruction messages. + // Keep all instruction text and its order/authority; never demote a late + // developer instruction (including approval criteria) into user content. + owned.sort_by_key(|o| !matches!(o.role, Role::System | Role::Developer)); + let messages = owned + .iter() + .map(|o| Message { + role: o.role, + content: &o.content, + reasoning: o.reasoning.as_deref(), + parts: o.parts.as_deref(), + }) + .collect::>(); + let catalog = Catalog::new(&request.tools)?; + let flat: Vec = if request.tools_disabled() { + Vec::new() + } else { + catalog + .flat + .iter() + .map(|tool| mark_json(marks, tool)) + .collect() + }; + let _template = crate::stage_trace::span("render_template"); + prompt::render_with_images( + &messages, + reasoning_effort(request).map_err(|(_, message)| message.to_owned())?, + &flat, + ) +} diff --git a/control-plane/src/responses/resource_query_error_fn.rs b/control-plane/src/responses/resource_query_error_fn.rs new file mode 100644 index 00000000..bf1f930f --- /dev/null +++ b/control-plane/src/responses/resource_query_error_fn.rs @@ -0,0 +1,200 @@ +//! Moved out of the parent module by STRA-338: fn resource_query_error, fn retrieve, impl InputItemsQuery, impl StoredResponse, fn input_items, fn delete .... + +#[allow(unused_imports)] +use super::*; + +pub(super) fn resource_query_error(query: Option) -> Option { + query.filter(|value| !value.is_empty()).map(|_| { + api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "unsupported_query", + None, + "stored response query options and stream resumption are not supported", + ) + }) +} + +pub async fn retrieve( + State(state): State, + Path(id): Path, + RawQuery(query): RawQuery, +) -> Response { + if let Some(error) = resource_query_error(query) { + return error; + } + let history = state.response_history.read().await; + let Some(entry) = history.entries.get(&id) else { + return resource_not_found(); + }; + let response = entry.response.clone(); + drop(history); + Json(response).into_response() +} + +impl InputItemsQuery { + pub(super) fn parse(query: Option<&str>) -> Result { + let uri = format!("/?{}", query.unwrap_or("")) + .parse::() + .map_err(|_| "invalid input-items query")?; + let Query(options) = Query::::try_from_uri(&uri) + .map_err(|_| "only single after, limit and order query parameters are supported")?; + if options.limit.is_some_and(|n| !(1..=100).contains(&n)) + || options + .order + .as_deref() + .is_some_and(|s| s != "asc" && s != "desc") + || options + .after + .as_ref() + .is_some_and(|s| s.is_empty() || s.len() > 256) + { + return Err("limit must be 1..100, order asc|desc and after a nonempty item ID"); + } + Ok(options) + } +} + +impl StoredResponse { + pub(super) fn input_page( + &self, + id: &str, + options: &InputItemsQuery, + ) -> Result { + let descending = options.order.as_deref().unwrap_or("desc") == "desc"; + let prefix = format!("input_{id}_"); + let start = match options.after.as_deref() { + None => 0, + Some(cursor) => { + let index = cursor + .strip_prefix(&prefix) + .and_then(|s| s.parse::().ok()) + .filter(|i| *i < self.input_len && format!("{prefix}{i}") == cursor) + .ok_or("after does not identify an input item of this response")?; + if descending { + self.input_len - index + } else { + index + 1 + } + } + }; + let limit = options.limit.unwrap_or(20); + let count = self.input_len.saturating_sub(start).min(limit); + let mut data = Vec::with_capacity(count); + for position in start..start + count { + let index = if descending { + self.input_len - 1 - position + } else { + position + }; + // Project rather than mutate the transcript used for prompt replay. + // IDs identify occurrences in this response, so repeated client IDs + // cannot make a pagination cursor ambiguous. call_id stays intact. + let mut item = self.transcript[index].clone(); + item.as_object_mut() + .ok_or("stored input item is not an object")? + .insert("id".into(), json!(format!("{prefix}{index}"))); + if item.get("role").is_some() + && (item.get("type").is_none() || item["type"] == "message") + { + item["type"] = json!("message"); + if let Some(text) = item["content"].as_str() { + item["content"] = if item["role"] == "assistant" { + json!([{"type":"output_text","text":text,"annotations":[]}]) + } else { + json!([{"type":"input_text","text":text}]) + }; + } + let assistant = item["role"] == "assistant"; + if let Some(parts) = item["content"].as_array_mut() { + for part in parts { + if part["type"] == "input_text" || part["type"] == "output_text" { + part["type"] = json!(if assistant { + "output_text" + } else { + "input_text" + }); + if assistant && part.get("annotations").is_none() { + part["annotations"] = json!([]); + } + } + } + } + if item.get("status").is_none() { + item["status"] = json!("completed"); + } + } + data.push(item); + } + Ok( + json!({"object":"list", "first_id":data.first().map(|item| &item["id"]), + "last_id":data.last().map(|item| &item["id"]), + "has_more":self.input_len.saturating_sub(start) > count,"data":data}), + ) + } +} + +pub async fn input_items( + State(state): State, + Path(id): Path, + RawQuery(query): RawQuery, +) -> Response { + let invalid = |message| { + api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "invalid_input_items_query", + None, + message, + ) + }; + let options = match InputItemsQuery::parse(query.as_deref()) { + Ok(options) => options, + Err(message) => return invalid(message), + }; + let history = state.response_history.read().await; + let Some(entry) = history.entries.get(&id) else { + return resource_not_found(); + }; + let page = entry.input_page(&id, &options); + drop(history); + match page { + Ok(page) => Json(page).into_response(), + Err(message) => invalid(message), + } +} + +pub async fn delete( + State(state): State, + Path(id): Path, + RawQuery(query): RawQuery, +) -> Response { + if let Some(error) = resource_query_error(query) { + return error; + } + let mut guard = state.response_history.clone().write_owned().await; + let target = id.clone(); + let result = tokio::task::spawn_blocking(move || guard.delete_committed(&target)).await; + match result { + Ok(Ok(true)) => (), + Ok(Ok(false)) => return resource_not_found(), + _ => { + return api_error( + StatusCode::INSUFFICIENT_STORAGE, + "server_error", + "response_storage_failed", + None, + "cannot commit response deletion; inspect storage and restart", + ); + } + } + Json(json!({"id":id,"object":"response.deleted","deleted":true})).into_response() +} + +pub(super) fn append_input(transcript: &mut Vec, input: &Value) { + if let Some(items) = input.as_array() { + transcript.extend(items.iter().cloned()); + } else if let Some(text) = input.as_str() { + transcript.push(json!({"role":"user","content":text})); + } +} diff --git a/control-plane/src/responses/set_tool_call_recovery_fn.rs b/control-plane/src/responses/set_tool_call_recovery_fn.rs new file mode 100644 index 00000000..9518d173 --- /dev/null +++ b/control-plane/src/responses/set_tool_call_recovery_fn.rs @@ -0,0 +1,243 @@ +//! Moved out of the parent module by STRA-338: fn set_tool_call_recovery, fn tool_options, impl ResponseHistory, fn store_response, fn resource_not_found. + +#[allow(unused_imports)] +use super::*; + +/// Turn the experimental recovery of drifted tool-call forms on or off for the rest of the process. +pub fn set_tool_call_recovery(on: bool) { + TOOL_CALL_RECOVERY.store(on, Ordering::Relaxed); +} + +/// How tool calls are read: `natural_stop` as the generation ended, recovery as configured. +pub(super) fn tool_options(natural_stop: bool) -> tool_output::Options { + tool_output::Options { + natural_stop, + recovery: TOOL_CALL_RECOVERY.load(Ordering::Relaxed), + } +} + +impl ResponseHistory { + /// Call before worker acquisition/start. Payloads are never included in errors. + pub fn open(directory: Option<&std::path::Path>) -> Result { + let Some(directory) = directory else { + return Ok(Self::default()); + }; + let store = Arc::new(crate::history_store::Store::open(directory)?); + let mut history = Self::default(); + if let Some(bytes) = store.read()? { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Snapshot { + schema: u32, + sha256: String, + entries: Vec, + } + let snapshot: Snapshot = + serde_json::from_slice(&bytes).map_err(|_| "invalid history snapshot")?; + if snapshot.schema != 1 || snapshot.entries.len() > MAX_STORED_RESPONSES { + return Err("unsupported history snapshot schema or entry count"); + } + use sha2::Digest; + let encoded = + serde_json::to_vec(&snapshot.entries).map_err(|_| "invalid history snapshot")?; + if hex::encode(sha2::Sha256::digest(&encoded)) != snapshot.sha256 { + return Err("history snapshot checksum mismatch"); + } + drop(encoded); + for entry in snapshot.entries { + let id = entry.response["id"] + .as_str() + .ok_or("invalid stored response ID")?; + if !id.starts_with("resp_") + || id.len() > 180 + || !id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') + || entry.model.is_empty() + || entry.model.len() > 180 + || entry.input_len > entry.transcript.len() + || entry.response["object"] != "response" + || !matches!( + entry.response["status"].as_str(), + Some("completed" | "incomplete") + ) + { + return Err("invalid stored response metadata"); + } + let input = Value::Array(entry.transcript[..entry.input_len].to_vec()); + if !input.as_array().unwrap().iter().all(Value::is_object) { + return Err("invalid stored response input"); + } + // Rebuild and compare, never trust persisted size or transcript bounds. + let count = history.entries.len(); + history.insert(id, &entry.model, &input, &entry.response)?; + let rebuilt = &history.entries[id]; + if history.entries.len() != count + 1 + || rebuilt.bytes != entry.bytes + || rebuilt.transcript != entry.transcript + { + return Err("inconsistent or oversized history snapshot"); + } + } + } + history.store = Some(store); + Ok(history) + } + + pub(super) fn persist(&self) -> Result<(), &'static str> { + if let Some(store) = &self.store { + #[derive(Serialize)] + struct Snapshot<'a> { + schema: u32, + sha256: String, + entries: Vec<&'a StoredResponse>, + } + use sha2::Digest; + let entries: Vec<_> = self + .order + .iter() + .map(|id| self.entries[id].as_ref()) + .collect(); + let encoded = + serde_json::to_vec(&entries).map_err(|_| "cannot encode history snapshot")?; + let sha256 = hex::encode(sha2::Sha256::digest(&encoded)); + drop(encoded); + let snapshot = Snapshot { + schema: 1, + sha256, + entries, + }; + let bytes = + serde_json::to_vec(&snapshot).map_err(|_| "cannot encode history snapshot")?; + store.write(&bytes)?; + } + Ok(()) + } + + pub(super) fn get(&self, id: &str, model: &str) -> Option<&[Value]> { + let response = self.entries.get(id)?; + (response.model == model).then_some(response.transcript.as_slice()) + } + + pub(super) fn insert( + &mut self, + id: &str, + model: &str, + input: &Value, + response: &Value, + ) -> Result<(), &'static str> { + if self.store.is_none() { + return self.insert_with_limit(id, model, input, response, MAX_HISTORY_BYTES); + } + let mut candidate = self.clone(); + candidate.insert_with_limit(id, model, input, response, MAX_HISTORY_BYTES)?; + candidate.persist()?; + *self = candidate; + Ok(()) + } + + pub(super) fn insert_with_limit( + &mut self, + id: &str, + model: &str, + input: &Value, + response: &Value, + limit: usize, + ) -> Result<(), &'static str> { + if response["id"] != id || response["model"] != model { + return Err("stored response identity mismatch"); + } + let mut transcript = Vec::new(); + append_input(&mut transcript, input); + let input_len = transcript.len(); + if let Some(items) = response["output"].as_array() { + transcript.extend(items.iter().cloned()); + } + let bytes = serde_json::to_vec(&transcript) + .map_err(|_| "response transcript cannot be serialized")? + .len() + .checked_add( + serde_json::to_vec(response) + .map_err(|_| "response cannot be serialized")? + .len(), + ) + .ok_or("response storage size overflow")?; + if bytes > limit { + return Err("response and transcript exceed the in-memory history limit"); + } + if self.entries.contains_key(id) { + return Err("response ID already exists in history"); + } + while self.entries.len() >= MAX_STORED_RESPONSES || self.bytes.saturating_add(bytes) > limit + { + let Some(oldest) = self.order.pop_front() else { + break; + }; + if let Some(removed) = self.entries.remove(&oldest) { + self.bytes -= removed.bytes; + } + } + self.bytes += bytes; + self.order.push_back(id.to_owned()); + self.entries.insert( + id.to_owned(), + Arc::new(StoredResponse { + model: model.to_owned(), + transcript, + input_len, + response: response.clone(), + bytes, + }), + ); + Ok(()) + } + + pub(super) fn delete_committed(&mut self, id: &str) -> Result { + let mut candidate = self.clone(); + if !candidate.remove(id) { + return Ok(false); + } + candidate.persist()?; + *self = candidate; + Ok(true) + } + + pub(super) fn remove(&mut self, id: &str) -> bool { + let Some(removed) = self.entries.remove(id) else { + return false; + }; + self.bytes -= removed.bytes; + self.order.retain(|entry| entry != id); + true + } +} + +pub(super) async fn store_response( + history: &Arc>, + id: &str, + model: &str, + input: &Value, + response: &Value, +) -> Result<(), &'static str> { + let mut guard = history.clone().write_owned().await; + if guard.store.is_none() { + return guard.insert(id, model, input, response); + } + let (id, model, input, response) = ( + id.to_owned(), + model.to_owned(), + input.clone(), + response.clone(), + ); + tokio::task::spawn_blocking(move || guard.insert(&id, &model, &input, &response)) + .await + .map_err(|_| "history storage task failed")? +} + +pub(super) fn resource_not_found() -> Response { + api_error( + StatusCode::NOT_FOUND, + "invalid_request_error", + "response_not_found", + Some("response_id"), + "the stored response is unavailable", + ) +} diff --git a/control-plane/src/responses/validate_live_subset_fn.rs b/control-plane/src/responses/validate_live_subset_fn.rs new file mode 100644 index 00000000..da2eed12 --- /dev/null +++ b/control-plane/src/responses/validate_live_subset_fn.rs @@ -0,0 +1,57 @@ +//! Moved out of the parent module by STRA-338: fn validate_live_subset, fn api_error, impl ResponseTrace. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn validate_live_subset( + request: &CreateRequest, +) -> Result<(), (&'static str, &'static str)> { + if request.tool_choice.as_ref().is_some_and(|choice| { + choice != "auto" + && choice != "none" + && choice != "required" + && choice["type"] != "function" + && choice["type"] != "custom" + && choice["type"] != "allowed_tools" + }) { + return Err(( + "tool_choice", + "only auto, none, required, allowed_tools and forced top-level function/custom choices are connected", + )); + } + if request + .truncation + .as_deref() + .is_some_and(|value| value != "disabled") + { + return Err(("truncation", "automatic truncation is not connected yet")); + } + Ok(()) +} + +pub(super) fn api_error( + status: StatusCode, + kind: &'static str, + code: &'static str, + param: Option<&'static str>, + message: &str, +) -> Response { + ( + status, + Json(json!({"error": {"message": message, "type": kind, "param": param, "code": code}})), + ) + .into_response() +} + +impl ResponseTrace { + pub fn build( + request: &CreateRequest, + items: &[OutputItem], + usage: Usage, + id: &str, + created_at: u64, + completed_at: u64, + ) -> Result { + Self::build_with_terminal(request, items, usage, id, created_at, completed_at, false) + } +} diff --git a/control-plane/src/responses/vision_error_fn.rs b/control-plane/src/responses/vision_error_fn.rs new file mode 100644 index 00000000..d1c66f68 --- /dev/null +++ b/control-plane/src/responses/vision_error_fn.rs @@ -0,0 +1,240 @@ +//! Moved out of the parent module by STRA-338: fn vision_error, fn expand_images, fn prepare_input_tokens, fn count_input_tokens, fn log_generation_failure, fn debug_failed_output. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn vision_error(error: crate::vision::VisionError) -> Box { + Box::new(match error { + crate::vision::VisionError::Invalid(message) => api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "invalid_image", + Some("input"), + &message, + ), + crate::vision::VisionError::Failed(message) => api_error( + StatusCode::SERVICE_UNAVAILABLE, + "server_error", + "vision_encoder_failed", + None, + &message, + ), + }) +} + +/// `Service.prepare`'s image branch: encode the pictures (in turn with the engine), then turn each +/// `<|image_pad|>` the template wrote for one into one pad per image token. +pub(super) async fn expand_images( + state: &AppState, + tokenizer: &Tokenizer, + ids: Vec, + images: &[String], +) -> Result> { + let Some(vision) = &state.vision else { + return Err(Box::new(api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "images_unsupported", + Some("input"), + "this server was started without the vision encoder (run setup again and choose 'vision'), so it cannot read images", + ))); + }; + let first = |text: &str, special: bool| { + tokenizer + .encode(text, special) + .map_err(|e| e.to_string()) + .and_then(|ids| { + ids.first() + .copied() + .ok_or_else(|| format!("{text} has no token")) + }) + }; + let internal = |message: String| { + Box::new(api_error( + StatusCode::INTERNAL_SERVER_ERROR, + "server_error", + "tokenization_failed", + None, + &message, + )) + }; + let pad = first(IMAGE_PAD, true).map_err(internal)?; + let start = first(VISION_START, true).map_err(internal)?; + let literal = tokenizer + .encode(IMAGE_PAD, false) + .map_err(|e| internal(e.to_string()))?; + // Encode only while the engine is idle: the engine and the image encoder are separate processes that must + // not run on the GPU at the same time. + let encoded = { + let _turn = vision.gate.lock().await; + let mut encoded = Vec::with_capacity(images.len()); + for source in images { + encoded.push(vision.encode(source).await.map_err(vision_error)?); + } + encoded + }; + let counts: Vec = encoded.iter().map(|image| image.tokens).collect(); + let token_ids = + leleka_serving_policy::vision::expand_image_pads(&ids, pad, start, &literal, &counts) + .map_err(|message| { + Box::new(api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "invalid_prompt", + Some("input"), + &message, + )) + })?; + let (path, keep) = vision.combine(&encoded).await.map_err(vision_error)?; + Ok(Prepared { + token_ids, + prompt_text: None, + embeddings: Some(path.to_string_lossy().into_owned()), + keep, + }) +} + +// Both endpoints must encode the same expanded transcript and chat template. `encode_images: false` (the token +// counters) leaves one pad per picture, as the Python server's count does: nothing is sent to the encoder. +pub(super) async fn prepare_input_tokens( + state: &AppState, + request: &mut CreateRequest, + tokenizer: Arc, + encode_images: bool, +) -> Result> { + if let Some(previous) = &request.previous_response_id { + let history = state.response_history.read().await; + let Some(saved) = history.get(previous, &request.model) else { + return Err(Box::new(api_error( + StatusCode::NOT_FOUND, + "invalid_request_error", + "response_not_found", + Some("previous_response_id"), + "the previous response is unavailable or belongs to a different model", + ))); + }; + let mut transcript = saved.to_vec(); + append_input(&mut transcript, &request.input); + request.input = Value::Array(transcript); + } + // The Qwen path renders through the chat template with the control-token marks and may carry pictures; the + // Harmony renderer of gpt-oss has no pictures. + let rendered = crate::stage_trace::time("render", || match tokenizer.family() { + Family::Qwen35 => { + let qwen = tokenizer + .qwen() + .ok_or_else(|| "the Qwen family needs the Qwen tokenizer".to_owned())?; + render_request(request, qwen.marks()) + } + Family::GptOss => harmony_prompt::render(request).map(|prompt| (prompt, Vec::new())), + }); + let (prompt, images) = match rendered { + Ok(rendered) => rendered, + Err(message) => { + return Err(Box::new(api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "invalid_prompt", + Some("input"), + &message, + ))); + } + }; + let tokenizer_for_encode = tokenizer.clone(); + let tokenize_span = crate::stage_trace::span("tokenize"); + let (token_ids, prompt) = match tokio::task::spawn_blocking(move || { + // The one tokenization of a prompt, for generation and for counting: the template's own markers are special + // tokens, the control-token text inside the messages (marked by `render_request`) is ordinary text. + tokenizer_for_encode + .encode_prompt(&prompt) + .map(|ids| (ids, prompt)) + }) + .await + { + Ok(Ok(encoded)) => encoded, + Ok(Err(message)) => { + return Err(Box::new(api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "tokenization_failed", + Some("input"), + &message, + ))); + } + Err(error) => { + return Err(Box::new(api_error( + StatusCode::INTERNAL_SERVER_ERROR, + "server_error", + "tokenization_failed", + None, + &error.to_string(), + ))); + } + }; + drop(tokenize_span); + if images.is_empty() || !encode_images { + return Ok(Prepared { + token_ids, + prompt_text: Some(Arc::from(prompt)), + embeddings: None, + keep: Default::default(), + }); + } + let Some(qwen) = tokenizer.qwen() else { + return Err(Box::new(api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "images_unsupported", + Some("input"), + "this model family cannot read images", + ))); + }; + expand_images(state, qwen, token_ids, &images).await +} + +pub async fn count_input_tokens( + State(state): State, + body: Result, JsonRejection>, +) -> Response { + let mut request = match parse_request(&state, body) { + Ok(request) => request, + Err(error) => return *error, + }; + if let Err((param, message)) = validate_live_subset(&request) { + return api_error( + StatusCode::NOT_IMPLEMENTED, + "invalid_request_error", + "unsupported_live_feature", + Some(param), + message, + ); + } + let Some(tokenizer) = &state.tokenizer else { + return api_error( + StatusCode::NOT_IMPLEMENTED, + "server_error", + "inference_adapter_missing", + None, + "configure tokenizer_dir to enable input token counting", + ); + }; + match prepare_input_tokens(&state, &mut request, tokenizer.clone(), false).await { + Ok(prepared) => Json( + json!({"object": "response.input_tokens", "input_tokens": prepared.token_ids.len()}), + ) + .into_response(), + Err(error) => *error, + } +} + +/// Every failed generation leaves one line in the log (the message is the one the client gets: no prompt or output text). +/// With `STRATA_DEBUG_FAILED_OUTPUT=1` the generated text of a failed streaming tool turn is logged too: operator debugging +/// only, because it is model output. +pub(super) fn log_generation_failure(message: &str) { + crate::elog!("generation failed: {message}"); +} + +pub(super) fn debug_failed_output() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("STRATA_DEBUG_FAILED_OUTPUT").is_some_and(|v| v == "1")) +} diff --git a/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels.rs b/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels.rs index 8befca52..b2636300 100644 --- a/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels.rs +++ b/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels.rs @@ -3,419 +3,5 @@ #[allow(unused_imports)] use super::*; - -impl<'c> ClosedKernels<'c> { - /// Pin gate, then load the module and resolve every entry; nothing is kept unless all of them resolve. - pub fn open(context: &'c Context<'c>, program: Program) -> Result { - admit(program)?; - if context.poisoned.get() || context.handle.is_none() { - return Err(Error::ContextPoisoned.into()); - } - let api = &context.driver.api; - let guard = context.enter()?; - let module = match api.load_kar_levels_module(program.ptx()) { - Ok(module) => module, - Err(error) => return Err(failure(error, guard.finish())), - }; - let mut functions = Vec::with_capacity(program.entries().len()); - let mut resolved: DriverResult<()> = Ok(()); - for entry in program.entries() { - match api.kar_levels_function(module, entry.name) { - Ok(function) => functions.push(function), - Err(error) => { - resolved = Err(error); - break; - } - } - } - match resolved { - Ok(()) => { - guard.finish()?; - Ok(Self { - context, - program, - module, - functions, - }) - } - Err(error) => { - let cleanup = api.unload(module); - if cleanup.is_err() { - context.poisoned.set(true); - std::mem::forget(Rc::clone(api)); - } - let primary = - combine::<()>(Err(error), cleanup).expect_err("resolution failure is primary"); - Err(failure(primary, guard.finish())) - } - } - } - - /// Unload the module. A program that is dropped instead is unloaded with its context. - pub fn close(self) -> Result<()> { - let context = self.context; - if context.poisoned.get() || context.handle.is_none() { - return Err(Error::ContextPoisoned.into()); - } - let guard = context.enter()?; - let unload = context.driver.api.unload(self.module); - if unload.is_err() { - context.poisoned.set(true); - std::mem::forget(Rc::clone(&context.driver.api)); - } - combine(unload, guard.finish()).map_err(Into::into) - } - - pub(super) fn expect(&self, program: Program) -> Result<()> { - if self.program != program { - return invalid("this facade call belongs to a different closed program"); - } - Ok(()) - } - - /// Check the slots against the entry, admit the operands, and build the argument table. - pub(super) fn build( - &self, - entry: usize, - grid: [u32; 3], - block: [u32; 3], - shared: u32, - slots: &[Slot], - operands: &[Operand<'_, '_>], - ) -> Result { - let spec = &self.program.entries()[entry]; - if !conforms(spec, slots) { - return invalid("closed launch arguments differ from the entry's fixed signature"); - } - if block.contains(&0) - || grid.contains(&0) - || block.iter().map(|b| u64::from(*b)).product::() > 1024 - { - return invalid("closed launch geometry is empty or exceeds 1024 threads per block"); - } - let context = self.context; - if context.poisoned.get() { - return Err(Error::ContextPoisoned.into()); - } - let mut args = Vec::with_capacity(slots.len()); - let mut admitted = Vec::new(); - for slot in slots { - match *slot { - Slot::Ptr(role) => { - let mut found = operands.iter().filter(|o| o.role == role); - let (Some(operand), None) = (found.next(), found.next()) else { - return invalid("closed launch needs exactly one buffer per pointer role"); - }; - if !std::ptr::eq(context, operand.buffer.context) { - return Err(Error::ContextMismatch.into()); - } - let handle = operand.buffer.handle.ok_or(Error::ContextPoisoned)?; - let min = usize::try_from(operand.min) - .or_else(|_| invalid("closed buffer size exceeds usize"))?; - if min == 0 || operand.buffer.bytes < min { - return invalid("closed buffer is smaller than the geometry requires"); - } - handle.validate_projection_extent(operand.buffer.bytes, 16)?; - admitted.push(Admitted { - handle, - bytes: operand.buffer.bytes, - writes: operand.writes, - }); - let at = handle.experimental_offset(operand.offset)?; - args.push(ffi::KarArgument::Scalar64(at.qwen_address())); - } - Slot::Null => args.push(ffi::KarArgument::Scalar64(0)), - Slot::I32(value) => args.push(ffi::KarArgument::Scalar(value as u32)), - Slot::I64(value) => args.push(ffi::KarArgument::Scalar64(value as u64)), - Slot::F32(value) => args.push(ffi::KarArgument::Scalar(value.to_bits())), - } - } - for (i, a) in admitted.iter().enumerate() { - for b in &admitted[i + 1..] { - if (a.writes || b.writes) && a.handle.overlaps(a.bytes, b.handle, b.bytes) { - return Err(Error::OutputAliasesInput.into()); - } - } - } - Ok(Launch { - function: self.functions[entry], - grid, - block, - shared, - args: ffi::KarLevelsArgs::new(&args)?, - }) - } - - /// Launch in order and drain with exactly one synchronize. - pub(super) fn run(&self, mut launches: Vec) -> Result<()> { - let context = self.context; - if context.poisoned.get() { - return Err(Error::ContextPoisoned.into()); - } - let guard = context.enter()?; - let mut launch = Ok(()); - for l in &mut launches { - launch = context.driver.api.launch_closed( - l.function, - l.grid, - l.block, - l.shared, - &mut l.args, - ); - if launch.is_err() { - break; - } - } - context - .complete_launch(launch, launches, guard) - .map_err(Into::into) - } - - // --------------------------------------------------------------------------- short FlashAttention - - /// `native_flash_attn_short_step`: one query, Q 24x256 f32, K/V 2x256 f16 cells (`capacity` of them each), device - /// `step` record `{pos, n_kv, n_bid, width}`, optional additive f16 mask of 256 logits. `out` is 24x256 f32 and - /// `status` one i32 (0 = success, 1 = the step record is not a valid short step: `out` is then NaN). Launch - /// geometry is the Original's `<<<24, dim3(32, 4)>>>`; the argument admission is `native_flash_attn::admit` - /// verbatim (`idx_top_k` is the QSA index's top-k, which the Original also checks). - #[allow(clippy::too_many_arguments)] // closed ABI operands - pub fn native_flash_attn_short( - &self, - q: &DeviceBuffer<'_>, - k: &DeviceBuffer<'_>, - v: &DeviceBuffer<'_>, - step: &DeviceBuffer<'_>, - mask: Option<&DeviceBuffer<'_>>, - capacity: i64, - idx_top_k: i64, - max_context: i32, - out: &mut DeviceBuffer<'_>, - status: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.expect(Program::NativeFlashAttn)?; - let bytes = flash_bytes(capacity)?; - let address = |b: &DeviceBuffer<'_>| -> Result { - let handle = b.handle.ok_or(Error::ContextPoisoned)?; - usize::try_from(handle.qwen_address()) - .or_else(|_| invalid("device address exceeds usize")) - }; - let launch = flash::admit(&flash::Arguments { - n_head: flash::HEADS as i64, - n_head_kv: flash::KV_HEADS as i64, - head_dim: flash::HEAD_DIM as i64, - idx_block: 4, - idx_top_k, - capacity, - max_context, - stream_present: true, - q: address(q)?, - k: address(k)?, - v: address(v)?, - step: address(step)?, - output: address(out)?, - status: address(status)?, - mask: mask.map(address).transpose()?, - }) - .map_err(|e| ExperimentalError::Invalid(e.message()))?; - let mut operands = vec![ - Operand { - role: Role::Q, - buffer: q, - min: bytes.q, - offset: 0, - writes: false, - }, - Operand { - role: Role::K, - buffer: k, - min: bytes.kv, - offset: 0, - writes: false, - }, - Operand { - role: Role::V, - buffer: v, - min: bytes.kv, - offset: 0, - writes: false, - }, - Operand { - role: Role::Step, - buffer: step, - min: bytes.step, - offset: 0, - writes: false, - }, - Operand { - role: Role::Out, - buffer: out, - min: bytes.out, - offset: 0, - writes: true, - }, - Operand { - role: Role::Status, - buffer: status, - min: bytes.status, - offset: 0, - writes: true, - }, - ]; - if let Some(mask) = mask { - operands.push(Operand { - role: Role::Mask, - buffer: mask, - min: bytes.mask, - offset: 0, - writes: false, - }); - } - let slots = flash_slots(max_context, mask.is_some()); - let launch = self.build( - FLASH_SHORT, - launch.grid, - launch.block, - launch.dynamic_shared, - &slots, - &operands, - )?; - self.run(vec![launch]) - } - - // ------------------------------------------------------------------------------- poison fill - - /// The constructor loop of `DeviceArena` with `poison = true`: fill the buffer with the quiet-NaN pattern - /// `0x7fc00000`, in slices of at most `0x7FFFFFFF` blocks of 256 threads, under one drain. - pub fn poison_f32(&self, buffer: &mut DeviceBuffer<'_>) -> Result<()> { - self.expect(Program::DevicePoison)?; - let plan = - device_arena::poison_launches(buffer.bytes as u64, device_arena::POISON_MAX_BLOCKS); - if plan.is_empty() { - return invalid("poison needs at least one float"); - } - let mut launches = Vec::with_capacity(plan.len()); - for slice in plan { - let operands = [Operand { - role: Role::Poison, - buffer, - min: buffer.bytes as u64, - offset: slice.float_offset * 4, - writes: true, - }]; - let grid = [ - u32::try_from(slice.blocks) - .or_else(|_| invalid("poison slice exceeds the grid"))?, - 1, - 1, - ]; - launches.push(self.build( - POISON_F32, - grid, - [device_arena::POISON_THREADS as u32, 1, 1], - 0, - &poison_slots(slice.n_floats)?, - &operands, - )?); - } - self.run(launches) - } - - // -------------------------------------------------------------------------------- S-form GEMVs - - /// Launch a planned S-form GEMV (`plan_s_gemv*` of `s_gemv_legacy`) over admitted operands: fp16, `block_q8_K` or - /// `block_q8_0` activation `x` (as the plan's kernel reads it), the packed `codes`, `scales` and (when the form has - /// one) `offset`, and `y` of `n_out` floats. - #[allow(clippy::too_many_arguments)] // closed ABI operands - pub fn s_gemv( - &self, - plan: &Plan, - form: &SForm, - n_in: i64, - n_out: i64, - x: &DeviceBuffer<'_>, - codes: &DeviceBuffer<'_>, - scales: &DeviceBuffer<'_>, - offset: Option<&DeviceBuffer<'_>>, - y: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.expect(Program::SGemvLegacy)?; - let bytes = s_operand_bytes(plan.kernel, form, n_in, n_out)?; - if bytes.offset.is_some() != offset.is_some() { - return invalid("the S-form has an offset exactly when an offset buffer is passed"); - } - let mut operands = vec![ - Operand { - role: Role::X, - buffer: x, - min: bytes.x, - offset: 0, - writes: false, - }, - Operand { - role: Role::Codes, - buffer: codes, - min: bytes.codes, - offset: 0, - writes: false, - }, - Operand { - role: Role::Scales, - buffer: scales, - min: bytes.scales, - offset: 0, - writes: false, - }, - Operand { - role: Role::Y, - buffer: y, - min: bytes.y, - offset: 0, - writes: true, - }, - ]; - if let (Some(buffer), Some(min)) = (offset, bytes.offset) { - operands.push(Operand { - role: Role::Offset, - buffer, - min, - offset: 0, - writes: false, - }); - } - let slots = s_gemv_slots(plan, form, n_in, n_out, offset.is_some()); - let launch = self.build( - s_gemv_entry_index(plan.kernel), - plan.launch.grid, - plan.launch.block, - plan.launch.dynamic_shared, - &slots, - &operands, - )?; - self.run(vec![launch]) - } - - /// The S2 kernels (`plan_s2_gemv*`): the 2-bit, group-64 form without offsets. - #[allow(clippy::too_many_arguments)] // closed ABI operands - pub fn s2_gemv( - &self, - plan: &Plan, - n_in: i64, - n_out: i64, - x: &DeviceBuffer<'_>, - codes: &DeviceBuffer<'_>, - scales: &DeviceBuffer<'_>, - y: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.s_gemv( - plan, - &SForm::default(), - n_in, - n_out, - x, - codes, - scales, - None, - y, - ) - } -} +mod impl_closedkernels_2; +mod impl_closedkernels_2_2; diff --git a/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2.rs b/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2.rs new file mode 100644 index 00000000..dfcd6688 --- /dev/null +++ b/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2.rs @@ -0,0 +1,174 @@ +//! Moved out of the parent module by STRA-338: impl ClosedKernels. + +#[allow(unused_imports)] +use super::*; + + + +impl<'c> ClosedKernels<'c> { + /// Pin gate, then load the module and resolve every entry; nothing is kept unless all of them resolve. + pub fn open(context: &'c Context<'c>, program: Program) -> Result { + admit(program)?; + if context.poisoned.get() || context.handle.is_none() { + return Err(Error::ContextPoisoned.into()); + } + let api = &context.driver.api; + let guard = context.enter()?; + let module = match api.load_kar_levels_module(program.ptx()) { + Ok(module) => module, + Err(error) => return Err(failure(error, guard.finish())), + }; + let mut functions = Vec::with_capacity(program.entries().len()); + let mut resolved: DriverResult<()> = Ok(()); + for entry in program.entries() { + match api.kar_levels_function(module, entry.name) { + Ok(function) => functions.push(function), + Err(error) => { + resolved = Err(error); + break; + } + } + } + match resolved { + Ok(()) => { + guard.finish()?; + Ok(Self { + context, + program, + module, + functions, + }) + } + Err(error) => { + let cleanup = api.unload(module); + if cleanup.is_err() { + context.poisoned.set(true); + std::mem::forget(Rc::clone(api)); + } + let primary = + combine::<()>(Err(error), cleanup).expect_err("resolution failure is primary"); + Err(failure(primary, guard.finish())) + } + } + } + + /// Unload the module. A program that is dropped instead is unloaded with its context. + pub fn close(self) -> Result<()> { + let context = self.context; + if context.poisoned.get() || context.handle.is_none() { + return Err(Error::ContextPoisoned.into()); + } + let guard = context.enter()?; + let unload = context.driver.api.unload(self.module); + if unload.is_err() { + context.poisoned.set(true); + std::mem::forget(Rc::clone(&context.driver.api)); + } + combine(unload, guard.finish()).map_err(Into::into) + } + + pub(in super::super) fn expect(&self, program: Program) -> Result<()> { + if self.program != program { + return invalid("this facade call belongs to a different closed program"); + } + Ok(()) + } + + /// Check the slots against the entry, admit the operands, and build the argument table. + pub(in super::super) fn build( + &self, + entry: usize, + grid: [u32; 3], + block: [u32; 3], + shared: u32, + slots: &[Slot], + operands: &[Operand<'_, '_>], + ) -> Result { + let spec = &self.program.entries()[entry]; + if !conforms(spec, slots) { + return invalid("closed launch arguments differ from the entry's fixed signature"); + } + if block.contains(&0) + || grid.contains(&0) + || block.iter().map(|b| u64::from(*b)).product::() > 1024 + { + return invalid("closed launch geometry is empty or exceeds 1024 threads per block"); + } + let context = self.context; + if context.poisoned.get() { + return Err(Error::ContextPoisoned.into()); + } + let mut args = Vec::with_capacity(slots.len()); + let mut admitted = Vec::new(); + for slot in slots { + match *slot { + Slot::Ptr(role) => { + let mut found = operands.iter().filter(|o| o.role == role); + let (Some(operand), None) = (found.next(), found.next()) else { + return invalid("closed launch needs exactly one buffer per pointer role"); + }; + if !std::ptr::eq(context, operand.buffer.context) { + return Err(Error::ContextMismatch.into()); + } + let handle = operand.buffer.handle.ok_or(Error::ContextPoisoned)?; + let min = usize::try_from(operand.min) + .or_else(|_| invalid("closed buffer size exceeds usize"))?; + if min == 0 || operand.buffer.bytes < min { + return invalid("closed buffer is smaller than the geometry requires"); + } + handle.validate_projection_extent(operand.buffer.bytes, 16)?; + admitted.push(Admitted { + handle, + bytes: operand.buffer.bytes, + writes: operand.writes, + }); + let at = handle.experimental_offset(operand.offset)?; + args.push(ffi::KarArgument::Scalar64(at.qwen_address())); + } + Slot::Null => args.push(ffi::KarArgument::Scalar64(0)), + Slot::I32(value) => args.push(ffi::KarArgument::Scalar(value as u32)), + Slot::I64(value) => args.push(ffi::KarArgument::Scalar64(value as u64)), + Slot::F32(value) => args.push(ffi::KarArgument::Scalar(value.to_bits())), + } + } + for (i, a) in admitted.iter().enumerate() { + for b in &admitted[i + 1..] { + if (a.writes || b.writes) && a.handle.overlaps(a.bytes, b.handle, b.bytes) { + return Err(Error::OutputAliasesInput.into()); + } + } + } + Ok(Launch { + function: self.functions[entry], + grid, + block, + shared, + args: ffi::KarLevelsArgs::new(&args)?, + }) + } + + /// Launch in order and drain with exactly one synchronize. + pub(in super::super) fn run(&self, mut launches: Vec) -> Result<()> { + let context = self.context; + if context.poisoned.get() { + return Err(Error::ContextPoisoned.into()); + } + let guard = context.enter()?; + let mut launch = Ok(()); + for l in &mut launches { + launch = context.driver.api.launch_closed( + l.function, + l.grid, + l.block, + l.shared, + &mut l.args, + ); + if launch.is_err() { + break; + } + } + context + .complete_launch(launch, launches, guard) + .map_err(Into::into) + } +} diff --git a/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2_2.rs b/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2_2.rs new file mode 100644 index 00000000..9a87045b --- /dev/null +++ b/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2_2.rs @@ -0,0 +1,257 @@ +//! Moved out of the parent module by STRA-338: impl ClosedKernels (2). + +#[allow(unused_imports)] +use super::*; + + + +impl<'c> ClosedKernels<'c> { + + // --------------------------------------------------------------------------- short FlashAttention + + /// `native_flash_attn_short_step`: one query, Q 24x256 f32, K/V 2x256 f16 cells (`capacity` of them each), device + /// `step` record `{pos, n_kv, n_bid, width}`, optional additive f16 mask of 256 logits. `out` is 24x256 f32 and + /// `status` one i32 (0 = success, 1 = the step record is not a valid short step: `out` is then NaN). Launch + /// geometry is the Original's `<<<24, dim3(32, 4)>>>`; the argument admission is `native_flash_attn::admit` + /// verbatim (`idx_top_k` is the QSA index's top-k, which the Original also checks). + #[allow(clippy::too_many_arguments)] // closed ABI operands + pub fn native_flash_attn_short( + &self, + q: &DeviceBuffer<'_>, + k: &DeviceBuffer<'_>, + v: &DeviceBuffer<'_>, + step: &DeviceBuffer<'_>, + mask: Option<&DeviceBuffer<'_>>, + capacity: i64, + idx_top_k: i64, + max_context: i32, + out: &mut DeviceBuffer<'_>, + status: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.expect(Program::NativeFlashAttn)?; + let bytes = flash_bytes(capacity)?; + let address = |b: &DeviceBuffer<'_>| -> Result { + let handle = b.handle.ok_or(Error::ContextPoisoned)?; + usize::try_from(handle.qwen_address()) + .or_else(|_| invalid("device address exceeds usize")) + }; + let launch = flash::admit(&flash::Arguments { + n_head: flash::HEADS as i64, + n_head_kv: flash::KV_HEADS as i64, + head_dim: flash::HEAD_DIM as i64, + idx_block: 4, + idx_top_k, + capacity, + max_context, + stream_present: true, + q: address(q)?, + k: address(k)?, + v: address(v)?, + step: address(step)?, + output: address(out)?, + status: address(status)?, + mask: mask.map(address).transpose()?, + }) + .map_err(|e| ExperimentalError::Invalid(e.message()))?; + let mut operands = vec![ + Operand { + role: Role::Q, + buffer: q, + min: bytes.q, + offset: 0, + writes: false, + }, + Operand { + role: Role::K, + buffer: k, + min: bytes.kv, + offset: 0, + writes: false, + }, + Operand { + role: Role::V, + buffer: v, + min: bytes.kv, + offset: 0, + writes: false, + }, + Operand { + role: Role::Step, + buffer: step, + min: bytes.step, + offset: 0, + writes: false, + }, + Operand { + role: Role::Out, + buffer: out, + min: bytes.out, + offset: 0, + writes: true, + }, + Operand { + role: Role::Status, + buffer: status, + min: bytes.status, + offset: 0, + writes: true, + }, + ]; + if let Some(mask) = mask { + operands.push(Operand { + role: Role::Mask, + buffer: mask, + min: bytes.mask, + offset: 0, + writes: false, + }); + } + let slots = flash_slots(max_context, mask.is_some()); + let launch = self.build( + FLASH_SHORT, + launch.grid, + launch.block, + launch.dynamic_shared, + &slots, + &operands, + )?; + self.run(vec![launch]) + } + + // ------------------------------------------------------------------------------- poison fill + + /// The constructor loop of `DeviceArena` with `poison = true`: fill the buffer with the quiet-NaN pattern + /// `0x7fc00000`, in slices of at most `0x7FFFFFFF` blocks of 256 threads, under one drain. + pub fn poison_f32(&self, buffer: &mut DeviceBuffer<'_>) -> Result<()> { + self.expect(Program::DevicePoison)?; + let plan = + device_arena::poison_launches(buffer.bytes as u64, device_arena::POISON_MAX_BLOCKS); + if plan.is_empty() { + return invalid("poison needs at least one float"); + } + let mut launches = Vec::with_capacity(plan.len()); + for slice in plan { + let operands = [Operand { + role: Role::Poison, + buffer, + min: buffer.bytes as u64, + offset: slice.float_offset * 4, + writes: true, + }]; + let grid = [ + u32::try_from(slice.blocks) + .or_else(|_| invalid("poison slice exceeds the grid"))?, + 1, + 1, + ]; + launches.push(self.build( + POISON_F32, + grid, + [device_arena::POISON_THREADS as u32, 1, 1], + 0, + &poison_slots(slice.n_floats)?, + &operands, + )?); + } + self.run(launches) + } + + // -------------------------------------------------------------------------------- S-form GEMVs + + /// Launch a planned S-form GEMV (`plan_s_gemv*` of `s_gemv_legacy`) over admitted operands: fp16, `block_q8_K` or + /// `block_q8_0` activation `x` (as the plan's kernel reads it), the packed `codes`, `scales` and (when the form has + /// one) `offset`, and `y` of `n_out` floats. + #[allow(clippy::too_many_arguments)] // closed ABI operands + pub fn s_gemv( + &self, + plan: &Plan, + form: &SForm, + n_in: i64, + n_out: i64, + x: &DeviceBuffer<'_>, + codes: &DeviceBuffer<'_>, + scales: &DeviceBuffer<'_>, + offset: Option<&DeviceBuffer<'_>>, + y: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.expect(Program::SGemvLegacy)?; + let bytes = s_operand_bytes(plan.kernel, form, n_in, n_out)?; + if bytes.offset.is_some() != offset.is_some() { + return invalid("the S-form has an offset exactly when an offset buffer is passed"); + } + let mut operands = vec![ + Operand { + role: Role::X, + buffer: x, + min: bytes.x, + offset: 0, + writes: false, + }, + Operand { + role: Role::Codes, + buffer: codes, + min: bytes.codes, + offset: 0, + writes: false, + }, + Operand { + role: Role::Scales, + buffer: scales, + min: bytes.scales, + offset: 0, + writes: false, + }, + Operand { + role: Role::Y, + buffer: y, + min: bytes.y, + offset: 0, + writes: true, + }, + ]; + if let (Some(buffer), Some(min)) = (offset, bytes.offset) { + operands.push(Operand { + role: Role::Offset, + buffer, + min, + offset: 0, + writes: false, + }); + } + let slots = s_gemv_slots(plan, form, n_in, n_out, offset.is_some()); + let launch = self.build( + s_gemv_entry_index(plan.kernel), + plan.launch.grid, + plan.launch.block, + plan.launch.dynamic_shared, + &slots, + &operands, + )?; + self.run(vec![launch]) + } + + /// The S2 kernels (`plan_s2_gemv*`): the 2-bit, group-64 form without offsets. + #[allow(clippy::too_many_arguments)] // closed ABI operands + pub fn s2_gemv( + &self, + plan: &Plan, + n_in: i64, + n_out: i64, + x: &DeviceBuffer<'_>, + codes: &DeviceBuffer<'_>, + scales: &DeviceBuffer<'_>, + y: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.s_gemv( + plan, + &SForm::default(), + n_in, + n_out, + x, + codes, + scales, + None, + y, + ) + } +} diff --git a/crates/cuda-driver/src/experimental_gpu/impl_experimental.rs b/crates/cuda-driver/src/experimental_gpu/impl_experimental.rs index b6a0356b..10c5d624 100644 --- a/crates/cuda-driver/src/experimental_gpu/impl_experimental.rs +++ b/crates/cuda-driver/src/experimental_gpu/impl_experimental.rs @@ -3,575 +3,6 @@ #[allow(unused_imports)] use super::*; - -impl<'c> Experimental<'c> { - /// Load (once) and return the cached program. Fails closed with `NotEnabled` / `Unpinned`. - pub fn open(context: &'c Context<'c>, program: Program, opt_in: &OptIn) -> Result { - let loaded = context.experimental_program(program, opt_in)?; - Ok(Self { - context, - program, - loaded, - }) - } - - /// The module is owned by the context and unloaded by `Context::close`. - pub fn close(self) -> Result<()> { - Ok(()) - } - - pub(super) fn expect(&self, program: Program) -> Result<()> { - if self.program != program { - return invalid("this facade call belongs to a different experimental program"); - } - Ok(()) - } - - pub(super) fn call(&self, entry: usize) -> Call<'_, 'c> { - Call { - gpu: self, - entry, - args: Vec::new(), - kinds: Vec::new(), - admitted: Vec::new(), - } - } - - /// Launch every entry in order and drain with exactly one synchronize. - pub(super) fn run(&self, mut launches: Vec) -> Result<()> { - let context = self.context; - if context.poisoned.get() { - return Err(Error::ContextPoisoned.into()); - } - let guard = context.enter()?; - let mut launch = Ok(()); - for l in &mut launches { - launch = context - .driver - .api - .launch_kar_levels(l.function, l.grid, l.block, &mut l.args); - if launch.is_err() { - break; - } - } - context - .complete_launch(launch, launches, guard) - .map_err(Into::into) - } - - // ------------------------------------------------------------------------------------- FWHT-256 - - /// `fwht256_cuda`: orthonormal Walsh-Hadamard transform of `rows` rows of 256 floats (scale 1/16; the - /// transform is its own inverse). `src` and `dst` must not overlap. - pub fn fwht256( - &self, - src: &DeviceBuffer<'_>, - dst: &mut DeviceBuffer<'_>, - rows: u64, - ) -> Result<()> { - self.expect(Program::KvQ4)?; - let grid = experimental::fwht_grid(rows)?; - let bytes = experimental::fwht_bytes(rows); - let launch = self - .call(FWHT256) - .ro(src, bytes)? - .rw(dst, bytes)? - .i64(i64_of(rows)?) - .finish(grid)?; - self.run(vec![launch]) - } - - // ------------------------------------------------------------------------------------ Q4_0 pool - - /// `kv_append_q4_step`: quantize one new cell (position and page table from the device `step` record) into - /// the Q4_0 pools. Host write-through is off (null mapped pointers). - #[allow(clippy::too_many_arguments)] // closed ABI operands - pub fn q4_append_step( - &self, - p: &Paged, - k_q4: &mut DeviceBuffer<'_>, - v_q4: &mut DeviceBuffer<'_>, - table: &DeviceBuffer<'_>, - step: &DeviceBuffer<'_>, - kcur: &DeviceBuffer<'_>, - vcur: &DeviceBuffer<'_>, - ) -> Result<()> { - self.expect(Program::KvQ4)?; - let grid = experimental::q4_step_grid(&p.shape)?; - let cell = p.shape.kv_heads as u64 * p.shape.head_dim as u64 * 4; - let launch = self - .call(Q4_APPEND_STEP) - .rw(k_q4, p.shape.q4_bytes(p.pages))? - .rw(v_q4, p.shape.q4_bytes(p.pages))? - .ro(table, p.table_entries * 4)? - .ro(step, STEP_BYTES)? - .ro(kcur, cell)? - .ro(vcur, cell)? - .i32(p.shape.kv_heads as i32) - .i32(p.shape.head_dim as i32) - .i32(p.shape.page_size as i32) - .null() - .null() - .finish(grid)?; - self.run(vec![launch]) - } - - /// `kv_append_q4` (prefill): `tokens` cells starting at `pos0`; K and V are `[token][kv_head][head_dim]`. - /// Two launches (`is_v` 0 then 1) under one drain, as the Original does. - #[allow(clippy::too_many_arguments)] // closed ABI operands - pub fn q4_append_batch( - &self, - p: &Paged, - k_q4: &mut DeviceBuffer<'_>, - v_q4: &mut DeviceBuffer<'_>, - table: &DeviceBuffer<'_>, - pos0: i64, - tokens: u64, - k: &DeviceBuffer<'_>, - v: &DeviceBuffer<'_>, - ) -> Result<()> { - self.expect(Program::KvQ4)?; - if pos0 < 0 { - return invalid("q4 append: negative start position"); - } - let grid = experimental::q4_batch_grid(tokens, &p.shape)?; - let rows = tokens * p.shape.kv_heads as u64 * p.shape.head_dim as u64 * 4; - let mut launches = Vec::new(); - for is_v in 0..2 { - launches.push( - self.call(Q4_APPEND_BATCH) - .rw(k_q4, p.shape.q4_bytes(p.pages))? - .rw(v_q4, p.shape.q4_bytes(p.pages))? - .ro(table, p.table_entries * 4)? - .i64(pos0) - .ro(k, rows)? - .ro(v, rows)? - .i32(p.shape.kv_heads as i32) - .i32(p.shape.head_dim as i32) - .i32(p.shape.page_size as i32) - .i32(is_v) - .null() - .null() - .null() - .null() - .finish(grid)?, - ); - } - self.run(launches) - } - - /// `kv_gather_q4_step`: dequantize the selected cells (device `ids`) into fp16 `[id][kv_head][head_dim]`. - #[allow(clippy::too_many_arguments)] // closed ABI operands - pub fn q4_gather_step( - &self, - p: &Paged, - k_q4: &DeviceBuffer<'_>, - v_q4: &DeviceBuffer<'_>, - table: &DeviceBuffer<'_>, - ids: &DeviceBuffer<'_>, - step: &DeviceBuffer<'_>, - max_ids: u64, - k_scratch: &mut DeviceBuffer<'_>, - v_scratch: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.expect(Program::KvQ4)?; - let grid = experimental::q4_gather_grid(max_ids, &p.shape)?; - let scratch = p.shape.gather_scratch_bytes(max_ids); - let launch = self - .call(Q4_GATHER_STEP) - .ro(k_q4, p.shape.q4_bytes(p.pages))? - .ro(v_q4, p.shape.q4_bytes(p.pages))? - .ro(table, p.table_entries * 4)? - .ro(ids, max_ids * 4)? - .ro(step, STEP_BYTES)? - .i32(p.shape.kv_heads as i32) - .i32(p.shape.head_dim as i32) - .i32(p.shape.page_size as i32) - .rw(k_scratch, scratch)? - .rw(v_scratch, scratch)? - .finish(grid)?; - self.run(vec![launch]) - } - - // ------------------------------------------------------------------------------------ INT8 pool - - /// `kv_append_q8_step`. With `keys == None` the cache is V-only (keyless): no K codes, scales or K input. - #[allow(clippy::too_many_arguments)] // closed ABI operands - pub fn q8_append_step( - &self, - p: &Paged, - keys: Option<( - &mut DeviceBuffer<'_>, - &mut DeviceBuffer<'_>, - &DeviceBuffer<'_>, - )>, - v_q: &mut DeviceBuffer<'_>, - v_scale: &mut DeviceBuffer<'_>, - table: &DeviceBuffer<'_>, - step: &DeviceBuffer<'_>, - vcur: &DeviceBuffer<'_>, - ) -> Result<()> { - self.expect(Program::KvQ8)?; - let grid = experimental::q8_step_grid(&p.shape, keys.is_some())?; - let codes = p.shape.q8_code_bytes(p.pages); - let scales = p.shape.q8_scale_bytes(p.pages); - let cell = p.shape.kv_heads as u64 * p.shape.head_dim as u64 * 4; - let mut c = self.call(Q8_APPEND_STEP); - match keys { - Some((k_q, k_scale, kcur)) => { - c = c.rw(k_q, codes)?.rw(v_q, codes)?.rw(k_scale, scales)?; - c = c - .rw(v_scale, scales)? - .ro(table, p.table_entries * 4)? - .ro(step, STEP_BYTES)?; - c = c.ro(kcur, cell)?; - } - None => { - c = c.null().rw(v_q, codes)?.null().rw(v_scale, scales)?; - c = c - .ro(table, p.table_entries * 4)? - .ro(step, STEP_BYTES)? - .null(); - } - } - let launch = c - .ro(vcur, cell)? - .i32(p.shape.kv_heads as i32) - .i32(p.shape.head_dim as i32) - .i32(p.shape.page_size as i32) - .null() - .null() - .null() - .null() - .finish(grid)?; - self.run(vec![launch]) - } - - /// `kv_gather_q8_step`: dequantize the selected cells into fp16 scratch (K and V of the same pool). - #[allow(clippy::too_many_arguments)] // closed ABI operands - pub fn q8_gather_step( - &self, - p: &Paged, - k_q: &DeviceBuffer<'_>, - v_q: &DeviceBuffer<'_>, - k_scale: &DeviceBuffer<'_>, - v_scale: &DeviceBuffer<'_>, - table: &DeviceBuffer<'_>, - ids: &DeviceBuffer<'_>, - step: &DeviceBuffer<'_>, - max_ids: u64, - k_scratch: &mut DeviceBuffer<'_>, - v_scratch: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.expect(Program::KvQ8)?; - let grid = experimental::q8_gather_grid(max_ids, &p.shape)?; - let codes = p.shape.q8_code_bytes(p.pages); - let scales = p.shape.q8_scale_bytes(p.pages); - let scratch = p.shape.gather_scratch_bytes(max_ids); - let launch = self - .call(Q8_GATHER_STEP) - .ro(k_q, codes)? - .ro(v_q, codes)? - .ro(k_scale, scales)? - .ro(v_scale, scales)? - .ro(table, p.table_entries * 4)? - .ro(ids, max_ids * 4)? - .ro(step, STEP_BYTES)? - .i32(p.shape.kv_heads as i32) - .i32(p.shape.head_dim as i32) - .i32(p.shape.page_size as i32) - .rw(k_scratch, scratch)? - .rw(v_scratch, scratch)? - .finish(grid)?; - self.run(vec![launch]) - } - - // --------------------------------------------------------------------------------- KV streaming - - /// `kv_stream_reset`: every block non-resident, every slot free, clock state zero. - pub fn stream_reset( - &self, - map: &mut StreamMap<'_, '_>, - n_blocks: u64, - n_slots: u64, - ) -> Result<()> { - self.expect(Program::KvStream)?; - let launch = map - .bind(self.call(STREAM_RESET), n_blocks, n_slots, false)? - .i64(i64_of(n_blocks)?) - .i64(i64_of(n_slots)?) - .finish(experimental::STREAM_RESET_GRID)?; - self.run(vec![launch]) - } - - /// `kv_stream_resolve` followed by `copy_kernel`: map this call's block ids to slots (CLOCK), then copy the - /// missed blocks from the host-tier arrays into the slot arrays, under one drain. `host` and `slots` hold - /// the streamed format's arrays in the order of `stream_runs`. - #[allow(clippy::too_many_arguments)] // closed ABI operands - pub fn stream_resolve( - &self, - map: &mut StreamMap<'_, '_>, - format: StreamFormat, - shape: &KvShape, - n_blocks: u64, - n_slots: u64, - ids: &DeviceBuffer<'_>, - steps: &DeviceBuffer<'_>, - n_q: u64, - cap: u64, - host: &[&DeviceBuffer<'_>], - slots: &mut [&mut DeviceBuffer<'_>], - ) -> Result<()> { - self.expect(Program::KvStream)?; - experimental::check_stream_resolve(shape, n_slots, n_q, cap)?; - let runs = stream_runs(&shape.as_qsa(), format); - if host.len() != runs.len() || slots.len() != runs.len() || runs.len() > 4 { - return invalid("kv_stream: host/slot array counts differ from the format's runs"); - } - let resolve = map - .bind(self.call(STREAM_RESOLVE), n_blocks, n_slots, true)? - .i64(i64_of(n_slots)?) - .ro(ids, n_q * cap * 4)? - .ro(steps, n_q * STEP_BYTES)? - .i32(i32_of(n_q)?) - .i32(i32_of(cap)?) - .i32(shape.page_size as i32) - .finish(experimental::STREAM_RESOLVE_GRID)?; - let mut copy = self - .call(STREAM_COPY) - .rw(&*map.ctl, CTL_INTS as u64 * 4)? - .rw(&*map.miss_block, n_slots * 4)? - .rw(&*map.miss_slot, n_slots * 4)?; - for i in 0..4 { - copy = match (host.get(i), runs.get(i)) { - (Some(h), Some(run)) => copy.ro(h, n_blocks * run.1)?, - _ => copy.null(), - }; - } - for i in 0..4 { - copy = match (slots.get(i), runs.get(i)) { - (Some(s), Some(run)) => copy.rw(s, n_slots * run.1)?, - _ => copy.null(), - }; - } - for i in 0..4 { - copy = copy.i32(runs.get(i).map_or(0, |r| r.1 as i32)); - } - let copy = copy - .i32(runs.len() as i32) - .finish(experimental::STREAM_COPY_GRID)?; - self.run(vec![resolve, copy]) - } - - /// `kv_ring_table`: the ring layout's fixed block -> slot table (`block % n_slots`). - pub fn ring_table( - &self, - table: &mut DeviceBuffer<'_>, - n_blocks: u64, - n_slots: u64, - ) -> Result<()> { - self.expect(Program::KvStream)?; - if n_blocks == 0 || n_slots == 0 { - return invalid("kv ring: empty table"); - } - let launch = self - .call(RING_TABLE) - .rw(table, n_blocks * 4)? - .i64(i64_of(n_blocks)?) - .i64(i64_of(n_slots)?) - .finish(experimental::RING_TABLE_GRID)?; - self.run(vec![launch]) - } - - /// `leleka_kv_copy_u4`: grid-stride copy of `n_u4` 16-byte units (stands in for `cudaMemcpyAsync` in - /// `kv_ring_restore` / `kv_stage_from_host`; `src` and `dst` must not overlap). - pub fn copy_u4( - &self, - src: &DeviceBuffer<'_>, - dst: &mut DeviceBuffer<'_>, - n_u4: u64, - ) -> Result<()> { - self.expect(Program::KvStream)?; - let grid = experimental::copy_u4_grid(n_u4)?; - let launch = self - .call(COPY_U4) - .ro(src, n_u4 * 16)? - .rw(dst, n_u4 * 16)? - .i64(i64_of(n_u4)?) - .finish(grid)?; - self.run(vec![launch]) - } - - // ------------------------------------------------------------------------------------- keyless - - /// `keyless_route_query`: rotate each head's query through its routing matrix (`[heads][256][256]` f32) - /// in place; `q` is `[token][head][256]`. - pub fn keyless_route_query( - &self, - q: &mut DeviceBuffer<'_>, - matrices: &DeviceBuffer<'_>, - tokens: u64, - heads: u64, - ) -> Result<()> { - self.expect(Program::Keyless)?; - let grid = experimental::keyless_grid(tokens, heads)?; - let launch = self - .call(KEYLESS_ROUTE) - .rw(q, tokens * heads * 256 * 4)? - .ro(matrices, experimental::keyless_matrices_bytes(heads))? - .i32(i32_of(heads)?) - .finish(grid)?; - self.run(vec![launch]) - } - - // --------------------------------------------------------------------------------------- cvec - - /// `cvec_apply` on `tokens` residual rows of `hc` streams of `n_embd`: `mode` 0 projects the direction out, - /// 1 adds it; an optional pending FFN write `(bo, bo_ld, inj, inj_ld)` is folded in first. - #[allow(clippy::too_many_arguments)] // closed ABI operands - pub fn cvec_apply( - &self, - r: &mut DeviceBuffer<'_>, - dir: &DeviceBuffer<'_>, - s_l: &DeviceBuffer<'_>, - on: &DeviceBuffer<'_>, - mode: leleka_experimental_ref::cvec::CvecMode, - layer: u64, - n_layers: u64, - n_embd: u64, - hc: u64, - tokens: u64, - r_ld: u64, - pending: Option<(&DeviceBuffer<'_>, u64, &DeviceBuffer<'_>, u64)>, - ) -> Result<()> { - self.expect(Program::Cvec)?; - let grid = experimental::cvec_grid(hc, tokens, n_embd)?; - if layer >= n_layers || r_ld < hc * n_embd { - return invalid("control vector: layer or row stride out of range"); - } - let rows = |ld: u64, width: u64| (tokens - 1) * ld + width; - let mut c = self - .call(CVEC_APPLY) - .rw(r, rows(r_ld, hc * n_embd) * 4)? - .ro(dir, n_layers * n_embd * 4)? - .ro(s_l, n_layers * 4)? - .ro(on, 4)? - .i32(mode as i32) - .i64(i64_of(layer)?) - .i32(i32_of(n_embd)?) - .i32(i32_of(hc)?) - .i64(i64_of(r_ld)?); - match pending { - Some((bo, bo_ld, inj, inj_ld)) => { - if bo_ld < n_embd || inj_ld < hc { - return invalid("control vector: pending-write strides are too small"); - } - c = c.ro(bo, rows(bo_ld, n_embd) * 4)?.i64(i64_of(bo_ld)?); - c = c.ro(inj, rows(inj_ld, hc) * 4)?.i64(i64_of(inj_ld)?); - } - None => c = c.null().i64(0).null().i64(0), - } - let launch = c.i32(i32::from(pending.is_some())).finish(grid)?; - self.run(vec![launch]) - } - - // ------------------------------------------------------------------------------------ attention - - /// `qsa_decode_attn_batch` for the experimental KV modes: the chunk kernel of `pools`' mode, then the merge, - /// under one drain. `scratch` holds `n_q * attn_scratch_floats(cap)` floats; the three partial buffers are - /// carved from it exactly as the Original's wrapper does. - #[allow(clippy::too_many_arguments)] // closed ABI operands - pub fn attend( - &self, - p: &Paged, - pools: &AttnPools<'_, '_>, - q: &DeviceBuffer<'_>, - table: &DeviceBuffer<'_>, - ids: &DeviceBuffer<'_>, - steps: &DeviceBuffer<'_>, - cap: u64, - n_q: u64, - scratch: &mut DeviceBuffer<'_>, - out: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.expect(Program::QsaAttn)?; - let chunk_grid = experimental::attn_chunk_grid(cap, &p.shape, n_q)?; - let merge_grid = experimental::attn_merge_grid(&p.shape, n_q)?; - let n_chunks = chunk_grid[0] as u64; - let n_head = p.shape.n_head() as u64; - let stride = experimental::attn_scratch_floats(cap, &p.shape); - let m_offset = n_chunks * n_head * attn::HD as u64 * 4; - let l_offset = m_offset + n_chunks * n_head * 4; - let q_bytes = n_q * n_head * attn::HD as u64 * 4; - let (kv, ps) = (p.shape.kv_heads as i32, p.shape.page_size as i32); - let table_bytes = p.table_entries * 4; - let mut chunk = match pools { - AttnPools::Q4 { k_q4, v_q4 } => self - .call(ATTN_CHUNK_M2) - .ro(q, q_bytes)? - .ro(k_q4, p.shape.q4_bytes(p.pages))? - .ro(v_q4, p.shape.q4_bytes(p.pages))? - .ro(table, table_bytes)? - .ro(ids, n_q * cap * 4)? - .ro(steps, n_q * STEP_BYTES)? - .i32(kv) - .i32(ps), - AttnPools::K8V4 { k_q, k_scale, v_q4 } => self - .call(ATTN_CHUNK_M3) - .ro(q, q_bytes)? - .ro(k_q, p.shape.q8_code_bytes(p.pages))? - .ro(k_scale, p.shape.q8_scale_bytes(p.pages))? - .ro(v_q4, p.shape.q4_bytes(p.pages))? - .ro(table, table_bytes)? - .ro(ids, n_q * cap * 4)? - .ro(steps, n_q * STEP_BYTES)? - .i32(kv) - .i32(ps), - AttnPools::Keyless { - v_q, - v_scale, - cos, - sin, - mrope, - } => { - let n_rot = leleka_experimental_ref::keyless::N_ROT as u64; - let c = self - .call(ATTN_CHUNK_M4) - .ro(q, q_bytes)? - .ro(v_q, p.shape.q8_code_bytes(p.pages))? - .ro(v_scale, p.shape.q8_scale_bytes(p.pages))? - .ro(table, table_bytes)? - .ro(cos, 4)? - .ro(sin, 4)?; - let c = match mrope { - Some(m) => c.ro(m, 4)?, - None => c.null(), - }; - c.i32(n_rot as i32) - .ro(ids, n_q * cap * 4)? - .ro(steps, n_q * STEP_BYTES)? - .i32(kv) - .i32(ps) - } - }; - let scratch_bytes = n_q * stride * 4; - chunk = chunk - .rw_at(scratch, scratch_bytes, 0)? - .rw_at(scratch, scratch_bytes, m_offset)? - .rw_at(scratch, scratch_bytes, l_offset)? - .i32(i32_of(n_chunks)?) - .i32(i32_of(cap)?) - .i64(i64_of(stride)?); - let chunk = chunk.finish(chunk_grid)?; - let merge = self - .call(ATTN_MERGE) - .ro_at(scratch, scratch_bytes, 0)? - .ro_at(scratch, scratch_bytes, m_offset)? - .ro_at(scratch, scratch_bytes, l_offset)? - .i32(i32_of(n_chunks)?) - .rw(out, q_bytes)? - .i64(i64_of(stride)?) - .finish(merge_grid)?; - self.run(vec![chunk, merge]) - } -} +mod impl_experimental_2; +mod impl_experimental_2_2; +mod impl_experimental_3; diff --git a/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_2.rs b/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_2.rs new file mode 100644 index 00000000..58ecebed --- /dev/null +++ b/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_2.rs @@ -0,0 +1,250 @@ +//! Moved out of the parent module by STRA-338: impl Experimental. + +#[allow(unused_imports)] +use super::*; + + + +impl<'c> Experimental<'c> { + /// Load (once) and return the cached program. Fails closed with `NotEnabled` / `Unpinned`. + pub fn open(context: &'c Context<'c>, program: Program, opt_in: &OptIn) -> Result { + let loaded = context.experimental_program(program, opt_in)?; + Ok(Self { + context, + program, + loaded, + }) + } + + /// The module is owned by the context and unloaded by `Context::close`. + pub fn close(self) -> Result<()> { + Ok(()) + } + + pub(in super::super) fn expect(&self, program: Program) -> Result<()> { + if self.program != program { + return invalid("this facade call belongs to a different experimental program"); + } + Ok(()) + } + + pub(in super::super) fn call(&self, entry: usize) -> Call<'_, 'c> { + Call { + gpu: self, + entry, + args: Vec::new(), + kinds: Vec::new(), + admitted: Vec::new(), + } + } + + /// Launch every entry in order and drain with exactly one synchronize. + pub(in super::super) fn run(&self, mut launches: Vec) -> Result<()> { + let context = self.context; + if context.poisoned.get() { + return Err(Error::ContextPoisoned.into()); + } + let guard = context.enter()?; + let mut launch = Ok(()); + for l in &mut launches { + launch = context + .driver + .api + .launch_kar_levels(l.function, l.grid, l.block, &mut l.args); + if launch.is_err() { + break; + } + } + context + .complete_launch(launch, launches, guard) + .map_err(Into::into) + } + + // ------------------------------------------------------------------------------------- FWHT-256 + + /// `fwht256_cuda`: orthonormal Walsh-Hadamard transform of `rows` rows of 256 floats (scale 1/16; the + /// transform is its own inverse). `src` and `dst` must not overlap. + pub fn fwht256( + &self, + src: &DeviceBuffer<'_>, + dst: &mut DeviceBuffer<'_>, + rows: u64, + ) -> Result<()> { + self.expect(Program::KvQ4)?; + let grid = experimental::fwht_grid(rows)?; + let bytes = experimental::fwht_bytes(rows); + let launch = self + .call(FWHT256) + .ro(src, bytes)? + .rw(dst, bytes)? + .i64(i64_of(rows)?) + .finish(grid)?; + self.run(vec![launch]) + } + + // ------------------------------------------------------------------------------------ Q4_0 pool + + /// `kv_append_q4_step`: quantize one new cell (position and page table from the device `step` record) into + /// the Q4_0 pools. Host write-through is off (null mapped pointers). + #[allow(clippy::too_many_arguments)] // closed ABI operands + pub fn q4_append_step( + &self, + p: &Paged, + k_q4: &mut DeviceBuffer<'_>, + v_q4: &mut DeviceBuffer<'_>, + table: &DeviceBuffer<'_>, + step: &DeviceBuffer<'_>, + kcur: &DeviceBuffer<'_>, + vcur: &DeviceBuffer<'_>, + ) -> Result<()> { + self.expect(Program::KvQ4)?; + let grid = experimental::q4_step_grid(&p.shape)?; + let cell = p.shape.kv_heads as u64 * p.shape.head_dim as u64 * 4; + let launch = self + .call(Q4_APPEND_STEP) + .rw(k_q4, p.shape.q4_bytes(p.pages))? + .rw(v_q4, p.shape.q4_bytes(p.pages))? + .ro(table, p.table_entries * 4)? + .ro(step, STEP_BYTES)? + .ro(kcur, cell)? + .ro(vcur, cell)? + .i32(p.shape.kv_heads as i32) + .i32(p.shape.head_dim as i32) + .i32(p.shape.page_size as i32) + .null() + .null() + .finish(grid)?; + self.run(vec![launch]) + } + + /// `kv_append_q4` (prefill): `tokens` cells starting at `pos0`; K and V are `[token][kv_head][head_dim]`. + /// Two launches (`is_v` 0 then 1) under one drain, as the Original does. + #[allow(clippy::too_many_arguments)] // closed ABI operands + pub fn q4_append_batch( + &self, + p: &Paged, + k_q4: &mut DeviceBuffer<'_>, + v_q4: &mut DeviceBuffer<'_>, + table: &DeviceBuffer<'_>, + pos0: i64, + tokens: u64, + k: &DeviceBuffer<'_>, + v: &DeviceBuffer<'_>, + ) -> Result<()> { + self.expect(Program::KvQ4)?; + if pos0 < 0 { + return invalid("q4 append: negative start position"); + } + let grid = experimental::q4_batch_grid(tokens, &p.shape)?; + let rows = tokens * p.shape.kv_heads as u64 * p.shape.head_dim as u64 * 4; + let mut launches = Vec::new(); + for is_v in 0..2 { + launches.push( + self.call(Q4_APPEND_BATCH) + .rw(k_q4, p.shape.q4_bytes(p.pages))? + .rw(v_q4, p.shape.q4_bytes(p.pages))? + .ro(table, p.table_entries * 4)? + .i64(pos0) + .ro(k, rows)? + .ro(v, rows)? + .i32(p.shape.kv_heads as i32) + .i32(p.shape.head_dim as i32) + .i32(p.shape.page_size as i32) + .i32(is_v) + .null() + .null() + .null() + .null() + .finish(grid)?, + ); + } + self.run(launches) + } + + /// `kv_gather_q4_step`: dequantize the selected cells (device `ids`) into fp16 `[id][kv_head][head_dim]`. + #[allow(clippy::too_many_arguments)] // closed ABI operands + pub fn q4_gather_step( + &self, + p: &Paged, + k_q4: &DeviceBuffer<'_>, + v_q4: &DeviceBuffer<'_>, + table: &DeviceBuffer<'_>, + ids: &DeviceBuffer<'_>, + step: &DeviceBuffer<'_>, + max_ids: u64, + k_scratch: &mut DeviceBuffer<'_>, + v_scratch: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.expect(Program::KvQ4)?; + let grid = experimental::q4_gather_grid(max_ids, &p.shape)?; + let scratch = p.shape.gather_scratch_bytes(max_ids); + let launch = self + .call(Q4_GATHER_STEP) + .ro(k_q4, p.shape.q4_bytes(p.pages))? + .ro(v_q4, p.shape.q4_bytes(p.pages))? + .ro(table, p.table_entries * 4)? + .ro(ids, max_ids * 4)? + .ro(step, STEP_BYTES)? + .i32(p.shape.kv_heads as i32) + .i32(p.shape.head_dim as i32) + .i32(p.shape.page_size as i32) + .rw(k_scratch, scratch)? + .rw(v_scratch, scratch)? + .finish(grid)?; + self.run(vec![launch]) + } + + // ------------------------------------------------------------------------------------ INT8 pool + + /// `kv_append_q8_step`. With `keys == None` the cache is V-only (keyless): no K codes, scales or K input. + #[allow(clippy::too_many_arguments)] // closed ABI operands + pub fn q8_append_step( + &self, + p: &Paged, + keys: Option<( + &mut DeviceBuffer<'_>, + &mut DeviceBuffer<'_>, + &DeviceBuffer<'_>, + )>, + v_q: &mut DeviceBuffer<'_>, + v_scale: &mut DeviceBuffer<'_>, + table: &DeviceBuffer<'_>, + step: &DeviceBuffer<'_>, + vcur: &DeviceBuffer<'_>, + ) -> Result<()> { + self.expect(Program::KvQ8)?; + let grid = experimental::q8_step_grid(&p.shape, keys.is_some())?; + let codes = p.shape.q8_code_bytes(p.pages); + let scales = p.shape.q8_scale_bytes(p.pages); + let cell = p.shape.kv_heads as u64 * p.shape.head_dim as u64 * 4; + let mut c = self.call(Q8_APPEND_STEP); + match keys { + Some((k_q, k_scale, kcur)) => { + c = c.rw(k_q, codes)?.rw(v_q, codes)?.rw(k_scale, scales)?; + c = c + .rw(v_scale, scales)? + .ro(table, p.table_entries * 4)? + .ro(step, STEP_BYTES)?; + c = c.ro(kcur, cell)?; + } + None => { + c = c.null().rw(v_q, codes)?.null().rw(v_scale, scales)?; + c = c + .ro(table, p.table_entries * 4)? + .ro(step, STEP_BYTES)? + .null(); + } + } + let launch = c + .ro(vcur, cell)? + .i32(p.shape.kv_heads as i32) + .i32(p.shape.head_dim as i32) + .i32(p.shape.page_size as i32) + .null() + .null() + .null() + .null() + .finish(grid)?; + self.run(vec![launch]) + } +} diff --git a/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_2_2.rs b/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_2_2.rs new file mode 100644 index 00000000..aa28868a --- /dev/null +++ b/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_2_2.rs @@ -0,0 +1,237 @@ +//! Moved out of the parent module by STRA-338: impl Experimental (2). + +#[allow(unused_imports)] +use super::*; + + + +impl<'c> Experimental<'c> { + + /// `kv_gather_q8_step`: dequantize the selected cells into fp16 scratch (K and V of the same pool). + #[allow(clippy::too_many_arguments)] // closed ABI operands + pub fn q8_gather_step( + &self, + p: &Paged, + k_q: &DeviceBuffer<'_>, + v_q: &DeviceBuffer<'_>, + k_scale: &DeviceBuffer<'_>, + v_scale: &DeviceBuffer<'_>, + table: &DeviceBuffer<'_>, + ids: &DeviceBuffer<'_>, + step: &DeviceBuffer<'_>, + max_ids: u64, + k_scratch: &mut DeviceBuffer<'_>, + v_scratch: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.expect(Program::KvQ8)?; + let grid = experimental::q8_gather_grid(max_ids, &p.shape)?; + let codes = p.shape.q8_code_bytes(p.pages); + let scales = p.shape.q8_scale_bytes(p.pages); + let scratch = p.shape.gather_scratch_bytes(max_ids); + let launch = self + .call(Q8_GATHER_STEP) + .ro(k_q, codes)? + .ro(v_q, codes)? + .ro(k_scale, scales)? + .ro(v_scale, scales)? + .ro(table, p.table_entries * 4)? + .ro(ids, max_ids * 4)? + .ro(step, STEP_BYTES)? + .i32(p.shape.kv_heads as i32) + .i32(p.shape.head_dim as i32) + .i32(p.shape.page_size as i32) + .rw(k_scratch, scratch)? + .rw(v_scratch, scratch)? + .finish(grid)?; + self.run(vec![launch]) + } + + // --------------------------------------------------------------------------------- KV streaming + + /// `kv_stream_reset`: every block non-resident, every slot free, clock state zero. + pub fn stream_reset( + &self, + map: &mut StreamMap<'_, '_>, + n_blocks: u64, + n_slots: u64, + ) -> Result<()> { + self.expect(Program::KvStream)?; + let launch = map + .bind(self.call(STREAM_RESET), n_blocks, n_slots, false)? + .i64(i64_of(n_blocks)?) + .i64(i64_of(n_slots)?) + .finish(experimental::STREAM_RESET_GRID)?; + self.run(vec![launch]) + } + + /// `kv_stream_resolve` followed by `copy_kernel`: map this call's block ids to slots (CLOCK), then copy the + /// missed blocks from the host-tier arrays into the slot arrays, under one drain. `host` and `slots` hold + /// the streamed format's arrays in the order of `stream_runs`. + #[allow(clippy::too_many_arguments)] // closed ABI operands + pub fn stream_resolve( + &self, + map: &mut StreamMap<'_, '_>, + format: StreamFormat, + shape: &KvShape, + n_blocks: u64, + n_slots: u64, + ids: &DeviceBuffer<'_>, + steps: &DeviceBuffer<'_>, + n_q: u64, + cap: u64, + host: &[&DeviceBuffer<'_>], + slots: &mut [&mut DeviceBuffer<'_>], + ) -> Result<()> { + self.expect(Program::KvStream)?; + experimental::check_stream_resolve(shape, n_slots, n_q, cap)?; + let runs = stream_runs(&shape.as_qsa(), format); + if host.len() != runs.len() || slots.len() != runs.len() || runs.len() > 4 { + return invalid("kv_stream: host/slot array counts differ from the format's runs"); + } + let resolve = map + .bind(self.call(STREAM_RESOLVE), n_blocks, n_slots, true)? + .i64(i64_of(n_slots)?) + .ro(ids, n_q * cap * 4)? + .ro(steps, n_q * STEP_BYTES)? + .i32(i32_of(n_q)?) + .i32(i32_of(cap)?) + .i32(shape.page_size as i32) + .finish(experimental::STREAM_RESOLVE_GRID)?; + let mut copy = self + .call(STREAM_COPY) + .rw(&*map.ctl, CTL_INTS as u64 * 4)? + .rw(&*map.miss_block, n_slots * 4)? + .rw(&*map.miss_slot, n_slots * 4)?; + for i in 0..4 { + copy = match (host.get(i), runs.get(i)) { + (Some(h), Some(run)) => copy.ro(h, n_blocks * run.1)?, + _ => copy.null(), + }; + } + for i in 0..4 { + copy = match (slots.get(i), runs.get(i)) { + (Some(s), Some(run)) => copy.rw(s, n_slots * run.1)?, + _ => copy.null(), + }; + } + for i in 0..4 { + copy = copy.i32(runs.get(i).map_or(0, |r| r.1 as i32)); + } + let copy = copy + .i32(runs.len() as i32) + .finish(experimental::STREAM_COPY_GRID)?; + self.run(vec![resolve, copy]) + } + + /// `kv_ring_table`: the ring layout's fixed block -> slot table (`block % n_slots`). + pub fn ring_table( + &self, + table: &mut DeviceBuffer<'_>, + n_blocks: u64, + n_slots: u64, + ) -> Result<()> { + self.expect(Program::KvStream)?; + if n_blocks == 0 || n_slots == 0 { + return invalid("kv ring: empty table"); + } + let launch = self + .call(RING_TABLE) + .rw(table, n_blocks * 4)? + .i64(i64_of(n_blocks)?) + .i64(i64_of(n_slots)?) + .finish(experimental::RING_TABLE_GRID)?; + self.run(vec![launch]) + } + + /// `leleka_kv_copy_u4`: grid-stride copy of `n_u4` 16-byte units (stands in for `cudaMemcpyAsync` in + /// `kv_ring_restore` / `kv_stage_from_host`; `src` and `dst` must not overlap). + pub fn copy_u4( + &self, + src: &DeviceBuffer<'_>, + dst: &mut DeviceBuffer<'_>, + n_u4: u64, + ) -> Result<()> { + self.expect(Program::KvStream)?; + let grid = experimental::copy_u4_grid(n_u4)?; + let launch = self + .call(COPY_U4) + .ro(src, n_u4 * 16)? + .rw(dst, n_u4 * 16)? + .i64(i64_of(n_u4)?) + .finish(grid)?; + self.run(vec![launch]) + } + + // ------------------------------------------------------------------------------------- keyless + + /// `keyless_route_query`: rotate each head's query through its routing matrix (`[heads][256][256]` f32) + /// in place; `q` is `[token][head][256]`. + pub fn keyless_route_query( + &self, + q: &mut DeviceBuffer<'_>, + matrices: &DeviceBuffer<'_>, + tokens: u64, + heads: u64, + ) -> Result<()> { + self.expect(Program::Keyless)?; + let grid = experimental::keyless_grid(tokens, heads)?; + let launch = self + .call(KEYLESS_ROUTE) + .rw(q, tokens * heads * 256 * 4)? + .ro(matrices, experimental::keyless_matrices_bytes(heads))? + .i32(i32_of(heads)?) + .finish(grid)?; + self.run(vec![launch]) + } + + // --------------------------------------------------------------------------------------- cvec + + /// `cvec_apply` on `tokens` residual rows of `hc` streams of `n_embd`: `mode` 0 projects the direction out, + /// 1 adds it; an optional pending FFN write `(bo, bo_ld, inj, inj_ld)` is folded in first. + #[allow(clippy::too_many_arguments)] // closed ABI operands + pub fn cvec_apply( + &self, + r: &mut DeviceBuffer<'_>, + dir: &DeviceBuffer<'_>, + s_l: &DeviceBuffer<'_>, + on: &DeviceBuffer<'_>, + mode: leleka_experimental_ref::cvec::CvecMode, + layer: u64, + n_layers: u64, + n_embd: u64, + hc: u64, + tokens: u64, + r_ld: u64, + pending: Option<(&DeviceBuffer<'_>, u64, &DeviceBuffer<'_>, u64)>, + ) -> Result<()> { + self.expect(Program::Cvec)?; + let grid = experimental::cvec_grid(hc, tokens, n_embd)?; + if layer >= n_layers || r_ld < hc * n_embd { + return invalid("control vector: layer or row stride out of range"); + } + let rows = |ld: u64, width: u64| (tokens - 1) * ld + width; + let mut c = self + .call(CVEC_APPLY) + .rw(r, rows(r_ld, hc * n_embd) * 4)? + .ro(dir, n_layers * n_embd * 4)? + .ro(s_l, n_layers * 4)? + .ro(on, 4)? + .i32(mode as i32) + .i64(i64_of(layer)?) + .i32(i32_of(n_embd)?) + .i32(i32_of(hc)?) + .i64(i64_of(r_ld)?); + match pending { + Some((bo, bo_ld, inj, inj_ld)) => { + if bo_ld < n_embd || inj_ld < hc { + return invalid("control vector: pending-write strides are too small"); + } + c = c.ro(bo, rows(bo_ld, n_embd) * 4)?.i64(i64_of(bo_ld)?); + c = c.ro(inj, rows(inj_ld, hc) * 4)?.i64(i64_of(inj_ld)?); + } + None => c = c.null().i64(0).null().i64(0), + } + let launch = c.i32(i32::from(pending.is_some())).finish(grid)?; + self.run(vec![launch]) + } +} diff --git a/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_3.rs b/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_3.rs new file mode 100644 index 00000000..d1d259dd --- /dev/null +++ b/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_3.rs @@ -0,0 +1,109 @@ +//! Moved out of the parent module by STRA-338: impl Experimental (3). + +#[allow(unused_imports)] +use super::*; + + + +impl<'c> Experimental<'c> { + + // ------------------------------------------------------------------------------------ attention + + /// `qsa_decode_attn_batch` for the experimental KV modes: the chunk kernel of `pools`' mode, then the merge, + /// under one drain. `scratch` holds `n_q * attn_scratch_floats(cap)` floats; the three partial buffers are + /// carved from it exactly as the Original's wrapper does. + #[allow(clippy::too_many_arguments)] // closed ABI operands + pub fn attend( + &self, + p: &Paged, + pools: &AttnPools<'_, '_>, + q: &DeviceBuffer<'_>, + table: &DeviceBuffer<'_>, + ids: &DeviceBuffer<'_>, + steps: &DeviceBuffer<'_>, + cap: u64, + n_q: u64, + scratch: &mut DeviceBuffer<'_>, + out: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.expect(Program::QsaAttn)?; + let chunk_grid = experimental::attn_chunk_grid(cap, &p.shape, n_q)?; + let merge_grid = experimental::attn_merge_grid(&p.shape, n_q)?; + let n_chunks = chunk_grid[0] as u64; + let n_head = p.shape.n_head() as u64; + let stride = experimental::attn_scratch_floats(cap, &p.shape); + let m_offset = n_chunks * n_head * attn::HD as u64 * 4; + let l_offset = m_offset + n_chunks * n_head * 4; + let q_bytes = n_q * n_head * attn::HD as u64 * 4; + let (kv, ps) = (p.shape.kv_heads as i32, p.shape.page_size as i32); + let table_bytes = p.table_entries * 4; + let mut chunk = match pools { + AttnPools::Q4 { k_q4, v_q4 } => self + .call(ATTN_CHUNK_M2) + .ro(q, q_bytes)? + .ro(k_q4, p.shape.q4_bytes(p.pages))? + .ro(v_q4, p.shape.q4_bytes(p.pages))? + .ro(table, table_bytes)? + .ro(ids, n_q * cap * 4)? + .ro(steps, n_q * STEP_BYTES)? + .i32(kv) + .i32(ps), + AttnPools::K8V4 { k_q, k_scale, v_q4 } => self + .call(ATTN_CHUNK_M3) + .ro(q, q_bytes)? + .ro(k_q, p.shape.q8_code_bytes(p.pages))? + .ro(k_scale, p.shape.q8_scale_bytes(p.pages))? + .ro(v_q4, p.shape.q4_bytes(p.pages))? + .ro(table, table_bytes)? + .ro(ids, n_q * cap * 4)? + .ro(steps, n_q * STEP_BYTES)? + .i32(kv) + .i32(ps), + AttnPools::Keyless { + v_q, + v_scale, + cos, + sin, + mrope, + } => { + let n_rot = leleka_experimental_ref::keyless::N_ROT as u64; + let c = self + .call(ATTN_CHUNK_M4) + .ro(q, q_bytes)? + .ro(v_q, p.shape.q8_code_bytes(p.pages))? + .ro(v_scale, p.shape.q8_scale_bytes(p.pages))? + .ro(table, table_bytes)? + .ro(cos, 4)? + .ro(sin, 4)?; + let c = match mrope { + Some(m) => c.ro(m, 4)?, + None => c.null(), + }; + c.i32(n_rot as i32) + .ro(ids, n_q * cap * 4)? + .ro(steps, n_q * STEP_BYTES)? + .i32(kv) + .i32(ps) + } + }; + let scratch_bytes = n_q * stride * 4; + chunk = chunk + .rw_at(scratch, scratch_bytes, 0)? + .rw_at(scratch, scratch_bytes, m_offset)? + .rw_at(scratch, scratch_bytes, l_offset)? + .i32(i32_of(n_chunks)?) + .i32(i32_of(cap)?) + .i64(i64_of(stride)?); + let chunk = chunk.finish(chunk_grid)?; + let merge = self + .call(ATTN_MERGE) + .ro_at(scratch, scratch_bytes, 0)? + .ro_at(scratch, scratch_bytes, m_offset)? + .ro_at(scratch, scratch_bytes, l_offset)? + .i32(i32_of(n_chunks)?) + .rw(out, q_bytes)? + .i64(i64_of(stride)?) + .finish(merge_grid)?; + self.run(vec![chunk, merge]) + } +} diff --git a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix.rs b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix.rs index 5fb77413..1c85432b 100644 --- a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix.rs +++ b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix.rs @@ -3,537 +3,9 @@ #[allow(unused_imports)] use super::*; - -impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> { - pub(super) fn ready(&self, step: Step) -> Result<()> { - if let Some(error) = &self.refusal { - return Err(error.clone()); - } - if self.step != step { - return Err(Error::InvalidQwenShape); - } - self.queue.status_handle()?; - Ok(()) - } - pub(super) fn latch(&mut self, result: Result<()>) -> Result<()> { - if let Err(error) = &result { - self.refusal.get_or_insert_with(|| error.clone()); - } - result - } - pub(super) fn handle_of(&self, buffer: &DeviceBuffer<'_>, bytes: usize) -> Result { - if !std::ptr::eq(self.queue.context, buffer.context) { - return Err(Error::ContextMismatch); - } - if buffer.bytes != bytes { - return Err(Error::InvalidQwenShape); - } - let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; - handle.validate_projection_extent(bytes, 4)?; - let status = self.queue.status_handle()?; - if handle.overlaps(bytes, status, STATUS_BYTES) { - return Err(Error::OutputAliasesInput); - } - Ok(handle) - } - /// Require the caller's buffer to be the very allocation a previous stage - /// of this one program produced or scanned; the order is the data flow. - pub(super) fn same(&self, expected: Option, buffer: &DeviceBuffer<'_>) -> Result<()> { - match (expected, buffer.handle) { - (Some(a), Some(b)) if a == b => Ok(()), - _ => Err(Error::InvalidQwenShape), - } - } - pub(super) fn push_stage( - &mut self, - kernel: usize, - buffers: &[&'lease DeviceBuffer<'lease>], - epsilon: f32, - ) -> Result<()> { - let operation = OPS[kernel]; - let queue = &*self.queue; - let (_, layout, handles) = admission( - queue.context, - buffers, - Admission { - operation, - layout: Ok(operation.layout()), - asset: qwen_ffi::asset(operation), - epsilon, - in_place: false, - }, - )?; - let function = queue.kernels.as_ref().ok_or(Error::ContextPoisoned)?.qwen[kernel]; - self.commands.push(Command::Qwen( - function, - operation, - Box::new(Arguments::with_layout(operation, layout, handles, epsilon)), - )); - self.held.extend_from_slice(buffers); - Ok(()) - } - pub(super) fn push_scan( - &mut self, - stage: GdnQueueStage, - buffer: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { - let source = self.handle_of(buffer, stage.words() * 4)?; - self.push_scan_range(stage, source, buffer) - } - // `held` keeps the whole owner borrowed; `source` may be a fixed subspan of it. - pub(super) fn push_scan_range( - &mut self, - stage: GdnQueueStage, - source: ffi::BufferHandle, - owner: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { - if self.checks != stage.slot() { - return Err(Error::InvalidQwenShape); - } - let words = stage.words(); - let queue = &*self.queue; - let status = queue - .status_handle()? - .checked_subspan(STATUS_BYTES, stage.slot() * 4, 4)?; - let function = queue.kernels.as_ref().ok_or(Error::ContextPoisoned)?.finite; - self.commands.push(Command::Guard( - function, - words as u32, - ffi::MmqResidentArguments::finite(source, status, 0, words as u32, 0), - )); - self.held.push(owner); - self.checks = stage.slot() + 1; - Ok(()) - } - - /// Row `row` of a retained batched QKV projection output, scanned as the - /// first stage of the program. `columns` is the actual whole - /// `tokens x 10,240` F32 owner of one batched projection; the fixed - /// 40,960 B row range is derived here (never caller supplied) exactly as the - /// recurrence derives its Q/K/V ranges from completed whole producers. - pub fn scan_qkv_columns( - &mut self, - columns: &'lease DeviceBuffer<'lease>, - row: usize, - ) -> Result<()> { - let result = (|| { - self.ready(Step::Alpha)?; - if self.checks != 0 || self.columns.is_some() { - return Err(Error::InvalidQwenShape); - } - let offset = column_row_offset(columns.bytes, row)?; - let whole = self.handle_of(columns, columns.bytes)?; - let range = whole.checked_subspan(columns.bytes, offset, QKV_BYTES)?; - range.validate_projection_extent(QKV_BYTES, 4)?; - self.push_scan_range(GdnQueueStage::Qkv, range, columns)?; - self.columns = Some((whole, row, range)); - Ok(()) - })(); - self.latch(result) - } - /// Device-only projection output of the Alpha role (48 words). - pub fn scan_alpha(&mut self, alpha: &'lease DeviceBuffer<'lease>) -> Result<()> { - let result = (|| { - self.ready(Step::Alpha)?; - let handle = self.handle_of(alpha, 192)?; - // Host-imported QKV was already finite-checked by its producer; - // its slot stays at the reset zero. - self.checks = self.checks.max(GdnQueueStage::Qkv.slot() + 1); - self.push_scan(GdnQueueStage::Alpha, alpha)?; - self.alpha = Some(handle); - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - /// Device-only projection output of the raw Beta role (48 words). - pub fn scan_beta_raw(&mut self, beta_raw: &'lease DeviceBuffer<'lease>) -> Result<()> { - let result = (|| { - self.ready(Step::BetaRaw)?; - let handle = self.handle_of(beta_raw, 192)?; - self.push_scan(GdnQueueStage::BetaRaw, beta_raw)?; - self.beta_raw = Some(handle); - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - /// Original convolution, then the raw, next-history and H scans in the - /// legacy readback order. - pub fn conv_silu( - &mut self, - history: &'lease DeviceBuffer<'lease>, - qkv: &'lease DeviceBuffer<'lease>, - weights: &'lease DeviceBuffer<'lease>, - next_history: &'lease DeviceBuffer<'lease>, - raw: &'lease DeviceBuffer<'lease>, - h: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { - let result = (|| { - self.ready(Step::Conv)?; - if self.columns.is_some() { - return Err(Error::InvalidQwenShape); - } - self.push_stage(CONV, &[history, qkv, weights, next_history, raw, h], 0.0)?; - self.push_scan(GdnQueueStage::ConvRaw, raw)?; - self.push_scan(GdnQueueStage::NextHistory, next_history)?; - self.push_scan(GdnQueueStage::ConvH, h)?; - self.next_history = next_history.handle; - self.h = h.handle; - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - /// The same convolution over the retained, already scanned QKV row. The - /// whole batched owner is admitted first; only the fixed row range is - /// derived from it. - #[allow(clippy::too_many_arguments)] // Six fixed source-defined owners and the row. - pub fn conv_silu_columns( - &mut self, - history: &'lease DeviceBuffer<'lease>, - columns: &'lease DeviceBuffer<'lease>, - row: usize, - weights: &'lease DeviceBuffer<'lease>, - next_history: &'lease DeviceBuffer<'lease>, - raw: &'lease DeviceBuffer<'lease>, - h: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { - let result = (|| { - self.ready(Step::Conv)?; - let (whole, scanned_row, range) = self.columns.ok_or(Error::InvalidQwenShape)?; - if scanned_row != row || columns.handle != Some(whole) { - return Err(Error::InvalidQwenShape); - } - let original = Operation::GdnConv.layout(); - let mut layout = original; - layout.bytes[1] = columns.bytes; - let queue = &*self.queue; - let (_, _, owners) = admission( - queue.context, - &[history, columns, weights, next_history, raw, h], - Admission { - operation: Operation::GdnConv, - layout: Ok(layout), - asset: qwen_ffi::asset(Operation::GdnConv), - epsilon: 0.0, - in_place: false, - }, - )?; - let mut handles = owners; - handles[1] = range; - ranges_layout(Operation::GdnConv, original, handles, original.bytes, false)?; - let function = queue.kernels.as_ref().ok_or(Error::ContextPoisoned)?.qwen[CONV]; - self.commands.push(Command::Qwen( - function, - Operation::GdnConv, - Box::new(Arguments::with_layout( - Operation::GdnConv, - original, - handles, - 0.0, - )), - )); - self.held - .extend_from_slice(&[history, columns, weights, next_history, raw, h]); - self.push_scan(GdnQueueStage::ConvRaw, raw)?; - self.push_scan(GdnQueueStage::NextHistory, next_history)?; - self.push_scan(GdnQueueStage::ConvH, h)?; - self.next_history = next_history.handle; - self.h = h.handle; - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - /// Original Q/K L2 kernel into the whole 10,240-word slot; the scan covers - /// the initialized tail too, as the scalar chain's full readback did. - pub fn qk_l2( - &mut self, - h: &'lease DeviceBuffer<'lease>, - qk: &'lease DeviceBuffer<'lease>, - epsilon: f32, - ) -> Result<()> { - let result = (|| { - self.ready(Step::Qk)?; - self.same(self.h, h)?; - self.push_stage(QK, &[h, qk], epsilon)?; - self.push_scan(GdnQueueStage::Qk, qk)?; - self.qk = qk.handle; - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - pub fn beta_sigmoid( - &mut self, - beta_raw: &'lease DeviceBuffer<'lease>, - sigmoid: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { - let result = (|| { - self.ready(Step::Sigmoid)?; - self.same(self.beta_raw, beta_raw)?; - self.push_stage(BETA, &[beta_raw, sigmoid], 0.0)?; - self.push_scan(GdnQueueStage::Sigmoid, sigmoid)?; - self.sigmoid = sigmoid.handle; - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - pub fn gate_softplus( - &mut self, - alpha: &'lease DeviceBuffer<'lease>, - dt: &'lease DeviceBuffer<'lease>, - a: &'lease DeviceBuffer<'lease>, - gate: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { - let result = (|| { - self.ready(Step::Gate)?; - self.same(self.alpha, alpha)?; - self.push_stage(GATE, &[alpha, dt, a, gate], 0.0)?; - self.push_scan(GdnQueueStage::Gate, gate)?; - self.gate = gate.handle; - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - /// The unchanged recurrence over fixed Q/K/V ranges of the completed whole - /// producers, exactly as `gdn_step_from_products_f32` admits them, then - /// the full next-state scan and the readout scan. The queue's own finite - /// function scans the next state; `GdnStateFiniteGuard` is not involved. - #[allow(clippy::too_many_arguments)] // Seven fixed source-defined owners. - pub fn recurrence( - &mut self, - state: &'lease DeviceBuffer<'lease>, - qk: &'lease DeviceBuffer<'lease>, - h: &'lease DeviceBuffer<'lease>, - gate: &'lease DeviceBuffer<'lease>, - beta: &'lease DeviceBuffer<'lease>, - next_state: &'lease DeviceBuffer<'lease>, - readout: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { - let result = (|| { - self.ready(Step::Recurrence)?; - self.same(self.qk, qk)?; - self.same(self.h, h)?; - self.same(self.gate, gate)?; - self.same(self.sigmoid, beta)?; - let original = Operation::GdnStep.layout(); - // Admit the WHOLE real allocations, including aliases outside the - // consumed ranges, before deriving any private pointer operands. - let mut whole = original; - whole.bytes = [ - STATE_BYTES, - QK_BYTES, - QK_BYTES, - 192, - 192, - STATE_BYTES, - 24_576, - 0, - 0, - ]; - whole.align = [4; 9]; - whole.count = 7; - whole.outputs = 0b110_0000; - let queue = &*self.queue; - let (_, _, owners) = admission( - queue.context, - &[state, qk, h, gate, beta, next_state, readout], - Admission { - operation: Operation::GdnStep, - layout: Ok(whole), - asset: qwen_ffi::asset(Operation::GdnStep), - epsilon: 0.0, - in_place: false, - }, - )?; - let status = queue.status_handle()?; - for owner in &owners[..7] { - if owner.overlaps(1, status, STATUS_BYTES) { - return Err(Error::OutputAliasesInput); - } - } - let q = owners[1].checked_subspan(QK_BYTES, 0, 8192)?; - let k = owners[1].checked_subspan(QK_BYTES, 8192, 8192)?; - let v = owners[2].checked_subspan(QK_BYTES, 16_384, 24_576)?; - let handles = [ - owners[0], q, k, v, owners[3], owners[4], owners[5], owners[6], owners[0], - ]; - ranges_layout(Operation::GdnStep, original, handles, original.bytes, false)?; - let function = queue.kernels.as_ref().ok_or(Error::ContextPoisoned)?.qwen[STEP]; - self.commands.push(Command::Qwen( - function, - Operation::GdnStep, - Box::new(Arguments::with_layout( - Operation::GdnStep, - original, - handles, - 0.0, - )), - )); - self.held - .extend_from_slice(&[state, qk, h, gate, beta, next_state, readout]); - // Earliest full-state refusal precedes the readout, as before. - self.push_scan(GdnQueueStage::NextState, next_state)?; - self.push_scan(GdnQueueStage::Readout, readout)?; - self.readout = readout.handle; - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - /// Device-only projection output of the Z role (6,144 words). - pub fn scan_z(&mut self, z: &'lease DeviceBuffer<'lease>) -> Result<()> { - let result = (|| { - self.ready(Step::Z)?; - self.push_scan(GdnQueueStage::Z, z)?; - self.z = z.handle; - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - pub fn out_norm( - &mut self, - readout: &'lease DeviceBuffer<'lease>, - z: &'lease DeviceBuffer<'lease>, - gamma: &'lease DeviceBuffer<'lease>, - normalized: &'lease DeviceBuffer<'lease>, - epsilon: f32, - ) -> Result<()> { - let result = (|| { - self.ready(Step::OutNorm)?; - self.same(self.readout, readout)?; - self.same(self.z, z)?; - self.push_stage(OUT_NORM, &[readout, z, gamma, normalized], epsilon)?; - self.push_scan(GdnQueueStage::Normalized, normalized)?; - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - /// Select the already produced next-history owner for the single bounded - /// D2H performed inside the final drain. No other range is exposed. - pub fn fetch_next_history(&mut self, next_history: &'lease DeviceBuffer<'lease>) -> Result<()> { - let result = (|| { - if self.fetch.is_some() { - return Err(Error::InvalidQwenShape); - } - self.same(self.next_history, next_history)?; - let handle = self.handle_of(next_history, HISTORY_BYTES)?; - self.held.push(next_history); - self.fetch = Some(handle); - Ok(()) - })(); - self.latch(result) - } - - /// Drain the complete admitted prefix once. Earlier numerical refusal beats - /// a later admission error; an admission error with a clean prefix is the - /// returned error. No usable history is returned on numerical refusal. - pub fn finish(mut self) -> Result { - let complete = self.step == Step::Done && self.fetch.is_some(); - if !complete && self.refusal.is_none() { - self.refusal = Some(Error::InvalidQwenShape); - } - let drained = self.drain(complete)?; - if drained.refusal.is_none() - && let Some(error) = drained.deferred - { - return Err(error); - } - Ok(GdnRowCompletion { - refusal: drained.refusal, - next_history: if drained.refusal.is_none() { - drained.next_history - } else { - None - }, - }) - } - - pub(super) fn drain(mut self, fetch: bool) -> Result { - let status = self.queue.status_handle()?; - let mut statuses = staging(STATUS_BYTES)?; - let write_fetch = fetch && self.refusal.is_none(); - let mut fetched = staging(if write_fetch { HISTORY_BYTES } else { 0 })?; - if !self.commands.is_empty() { - let zero = self - .queue - .kernels - .as_ref() - .ok_or(Error::ContextPoisoned)? - .zero; - let mut reset = ffi::MmqResidentArguments::zero(status, SLOTS as u32); - let context = self.queue.context; - let guard = context.enter().inspect_err(|_| { - self.queue.failed = true; - context.poisoned.set(true); - })?; - let mut operation = - context - .driver - .api - .launch_mmq_resident(zero, SLOTS as u32, &mut reset); - for command in &mut self.commands { - if operation.is_err() { - break; - } - operation = command.launch(context); - } - if operation.is_ok() { - operation = context.driver.api.copy_to(status, &mut statuses); - } - if operation.is_ok() && write_fetch { - let source = self.fetch.ok_or(Error::InvalidQwenShape)?; - operation = context.driver.api.copy_to(source, &mut fetched); - } - let sync = context.driver.api.synchronize(); - let pop = guard.finish(); - if operation.is_err() || sync.is_err() || pop.is_err() { - self.queue.failed = true; - context.poisoned.set(true); - } - if sync.is_err() || pop.is_err() { - // Completion is uncertain: retain every actual argument/staging - // owner and every borrowed buffer; Context poison forbids reuse. - std::mem::forget((reset, self.commands, self.held, statuses, fetched)); - return combine(combine(operation, sync), pop) - .map(|()| unreachable!("uncertain GDN row drain")); - } - combine(combine(operation, sync), pop)?; - } - let (_, refusal) = match decode_statuses(&statuses, self.checks) { - Ok(decoded) => decoded, - Err(error) => { - self.queue.failed = true; - self.queue.context.poisoned.set(true); - return Err(error); - } - }; - let next_history = if write_fetch && refusal.is_none() { - let mut values = Vec::new(); - values - .try_reserve_exact(HISTORY_BYTES / 4) - .map_err(|_| Error::HostAllocation)?; - values.extend( - fetched - .as_chunks::<4>() - .0 - .iter() - .map(|word| f32::from_le_bytes(*word)), - ); - Some(values.into_boxed_slice()) - } else { - None - }; - Ok(Drained { - refusal, - deferred: self.refusal, - next_history, - }) - } -} +#[path = "impl_gdnrowprefix/impl_gdnrowprefix_2.rs"] +mod impl_gdnrowprefix_2; +#[path = "impl_gdnrowprefix/impl_gdnrowprefix_2_2.rs"] +mod impl_gdnrowprefix_2_2; +#[path = "impl_gdnrowprefix/impl_gdnrowprefix_3.rs"] +mod impl_gdnrowprefix_3; diff --git a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_2.rs b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_2.rs new file mode 100644 index 00000000..e656466d --- /dev/null +++ b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_2.rs @@ -0,0 +1,250 @@ +//! Moved out of the parent module by STRA-338: impl GdnRowPrefix. + +#[allow(unused_imports)] +use super::*; + + + +impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> { + pub(in super::super) fn ready(&self, step: Step) -> Result<()> { + if let Some(error) = &self.refusal { + return Err(error.clone()); + } + if self.step != step { + return Err(Error::InvalidQwenShape); + } + self.queue.status_handle()?; + Ok(()) + } + pub(in super::super) fn latch(&mut self, result: Result<()>) -> Result<()> { + if let Err(error) = &result { + self.refusal.get_or_insert_with(|| error.clone()); + } + result + } + pub(in super::super) fn handle_of(&self, buffer: &DeviceBuffer<'_>, bytes: usize) -> Result { + if !std::ptr::eq(self.queue.context, buffer.context) { + return Err(Error::ContextMismatch); + } + if buffer.bytes != bytes { + return Err(Error::InvalidQwenShape); + } + let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; + handle.validate_projection_extent(bytes, 4)?; + let status = self.queue.status_handle()?; + if handle.overlaps(bytes, status, STATUS_BYTES) { + return Err(Error::OutputAliasesInput); + } + Ok(handle) + } + /// Require the caller's buffer to be the very allocation a previous stage + /// of this one program produced or scanned; the order is the data flow. + pub(in super::super) fn same(&self, expected: Option, buffer: &DeviceBuffer<'_>) -> Result<()> { + match (expected, buffer.handle) { + (Some(a), Some(b)) if a == b => Ok(()), + _ => Err(Error::InvalidQwenShape), + } + } + pub(in super::super) fn push_stage( + &mut self, + kernel: usize, + buffers: &[&'lease DeviceBuffer<'lease>], + epsilon: f32, + ) -> Result<()> { + let operation = OPS[kernel]; + let queue = &*self.queue; + let (_, layout, handles) = admission( + queue.context, + buffers, + Admission { + operation, + layout: Ok(operation.layout()), + asset: qwen_ffi::asset(operation), + epsilon, + in_place: false, + }, + )?; + let function = queue.kernels.as_ref().ok_or(Error::ContextPoisoned)?.qwen[kernel]; + self.commands.push(Command::Qwen( + function, + operation, + Box::new(Arguments::with_layout(operation, layout, handles, epsilon)), + )); + self.held.extend_from_slice(buffers); + Ok(()) + } + pub(in super::super) fn push_scan( + &mut self, + stage: GdnQueueStage, + buffer: &'lease DeviceBuffer<'lease>, + ) -> Result<()> { + let source = self.handle_of(buffer, stage.words() * 4)?; + self.push_scan_range(stage, source, buffer) + } + // `held` keeps the whole owner borrowed; `source` may be a fixed subspan of it. + pub(in super::super) fn push_scan_range( + &mut self, + stage: GdnQueueStage, + source: ffi::BufferHandle, + owner: &'lease DeviceBuffer<'lease>, + ) -> Result<()> { + if self.checks != stage.slot() { + return Err(Error::InvalidQwenShape); + } + let words = stage.words(); + let queue = &*self.queue; + let status = queue + .status_handle()? + .checked_subspan(STATUS_BYTES, stage.slot() * 4, 4)?; + let function = queue.kernels.as_ref().ok_or(Error::ContextPoisoned)?.finite; + self.commands.push(Command::Guard( + function, + words as u32, + ffi::MmqResidentArguments::finite(source, status, 0, words as u32, 0), + )); + self.held.push(owner); + self.checks = stage.slot() + 1; + Ok(()) + } + + /// Row `row` of a retained batched QKV projection output, scanned as the + /// first stage of the program. `columns` is the actual whole + /// `tokens x 10,240` F32 owner of one batched projection; the fixed + /// 40,960 B row range is derived here (never caller supplied) exactly as the + /// recurrence derives its Q/K/V ranges from completed whole producers. + pub fn scan_qkv_columns( + &mut self, + columns: &'lease DeviceBuffer<'lease>, + row: usize, + ) -> Result<()> { + let result = (|| { + self.ready(Step::Alpha)?; + if self.checks != 0 || self.columns.is_some() { + return Err(Error::InvalidQwenShape); + } + let offset = column_row_offset(columns.bytes, row)?; + let whole = self.handle_of(columns, columns.bytes)?; + let range = whole.checked_subspan(columns.bytes, offset, QKV_BYTES)?; + range.validate_projection_extent(QKV_BYTES, 4)?; + self.push_scan_range(GdnQueueStage::Qkv, range, columns)?; + self.columns = Some((whole, row, range)); + Ok(()) + })(); + self.latch(result) + } + /// Device-only projection output of the Alpha role (48 words). + pub fn scan_alpha(&mut self, alpha: &'lease DeviceBuffer<'lease>) -> Result<()> { + let result = (|| { + self.ready(Step::Alpha)?; + let handle = self.handle_of(alpha, 192)?; + // Host-imported QKV was already finite-checked by its producer; + // its slot stays at the reset zero. + self.checks = self.checks.max(GdnQueueStage::Qkv.slot() + 1); + self.push_scan(GdnQueueStage::Alpha, alpha)?; + self.alpha = Some(handle); + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } + /// Device-only projection output of the raw Beta role (48 words). + pub fn scan_beta_raw(&mut self, beta_raw: &'lease DeviceBuffer<'lease>) -> Result<()> { + let result = (|| { + self.ready(Step::BetaRaw)?; + let handle = self.handle_of(beta_raw, 192)?; + self.push_scan(GdnQueueStage::BetaRaw, beta_raw)?; + self.beta_raw = Some(handle); + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } + /// Original convolution, then the raw, next-history and H scans in the + /// legacy readback order. + pub fn conv_silu( + &mut self, + history: &'lease DeviceBuffer<'lease>, + qkv: &'lease DeviceBuffer<'lease>, + weights: &'lease DeviceBuffer<'lease>, + next_history: &'lease DeviceBuffer<'lease>, + raw: &'lease DeviceBuffer<'lease>, + h: &'lease DeviceBuffer<'lease>, + ) -> Result<()> { + let result = (|| { + self.ready(Step::Conv)?; + if self.columns.is_some() { + return Err(Error::InvalidQwenShape); + } + self.push_stage(CONV, &[history, qkv, weights, next_history, raw, h], 0.0)?; + self.push_scan(GdnQueueStage::ConvRaw, raw)?; + self.push_scan(GdnQueueStage::NextHistory, next_history)?; + self.push_scan(GdnQueueStage::ConvH, h)?; + self.next_history = next_history.handle; + self.h = h.handle; + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } + /// The same convolution over the retained, already scanned QKV row. The + /// whole batched owner is admitted first; only the fixed row range is + /// derived from it. + #[allow(clippy::too_many_arguments)] // Six fixed source-defined owners and the row. + pub fn conv_silu_columns( + &mut self, + history: &'lease DeviceBuffer<'lease>, + columns: &'lease DeviceBuffer<'lease>, + row: usize, + weights: &'lease DeviceBuffer<'lease>, + next_history: &'lease DeviceBuffer<'lease>, + raw: &'lease DeviceBuffer<'lease>, + h: &'lease DeviceBuffer<'lease>, + ) -> Result<()> { + let result = (|| { + self.ready(Step::Conv)?; + let (whole, scanned_row, range) = self.columns.ok_or(Error::InvalidQwenShape)?; + if scanned_row != row || columns.handle != Some(whole) { + return Err(Error::InvalidQwenShape); + } + let original = Operation::GdnConv.layout(); + let mut layout = original; + layout.bytes[1] = columns.bytes; + let queue = &*self.queue; + let (_, _, owners) = admission( + queue.context, + &[history, columns, weights, next_history, raw, h], + Admission { + operation: Operation::GdnConv, + layout: Ok(layout), + asset: qwen_ffi::asset(Operation::GdnConv), + epsilon: 0.0, + in_place: false, + }, + )?; + let mut handles = owners; + handles[1] = range; + ranges_layout(Operation::GdnConv, original, handles, original.bytes, false)?; + let function = queue.kernels.as_ref().ok_or(Error::ContextPoisoned)?.qwen[CONV]; + self.commands.push(Command::Qwen( + function, + Operation::GdnConv, + Box::new(Arguments::with_layout( + Operation::GdnConv, + original, + handles, + 0.0, + )), + )); + self.held + .extend_from_slice(&[history, columns, weights, next_history, raw, h]); + self.push_scan(GdnQueueStage::ConvRaw, raw)?; + self.push_scan(GdnQueueStage::NextHistory, next_history)?; + self.push_scan(GdnQueueStage::ConvH, h)?; + self.next_history = next_history.handle; + self.h = h.handle; + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } +} diff --git a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_2_2.rs b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_2_2.rs new file mode 100644 index 00000000..9d422009 --- /dev/null +++ b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_2_2.rs @@ -0,0 +1,217 @@ +//! Moved out of the parent module by STRA-338: impl GdnRowPrefix (2). + +#[allow(unused_imports)] +use super::*; + + + +impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> { + /// Original Q/K L2 kernel into the whole 10,240-word slot; the scan covers + /// the initialized tail too, as the scalar chain's full readback did. + pub fn qk_l2( + &mut self, + h: &'lease DeviceBuffer<'lease>, + qk: &'lease DeviceBuffer<'lease>, + epsilon: f32, + ) -> Result<()> { + let result = (|| { + self.ready(Step::Qk)?; + self.same(self.h, h)?; + self.push_stage(QK, &[h, qk], epsilon)?; + self.push_scan(GdnQueueStage::Qk, qk)?; + self.qk = qk.handle; + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } + pub fn beta_sigmoid( + &mut self, + beta_raw: &'lease DeviceBuffer<'lease>, + sigmoid: &'lease DeviceBuffer<'lease>, + ) -> Result<()> { + let result = (|| { + self.ready(Step::Sigmoid)?; + self.same(self.beta_raw, beta_raw)?; + self.push_stage(BETA, &[beta_raw, sigmoid], 0.0)?; + self.push_scan(GdnQueueStage::Sigmoid, sigmoid)?; + self.sigmoid = sigmoid.handle; + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } + pub fn gate_softplus( + &mut self, + alpha: &'lease DeviceBuffer<'lease>, + dt: &'lease DeviceBuffer<'lease>, + a: &'lease DeviceBuffer<'lease>, + gate: &'lease DeviceBuffer<'lease>, + ) -> Result<()> { + let result = (|| { + self.ready(Step::Gate)?; + self.same(self.alpha, alpha)?; + self.push_stage(GATE, &[alpha, dt, a, gate], 0.0)?; + self.push_scan(GdnQueueStage::Gate, gate)?; + self.gate = gate.handle; + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } + /// The unchanged recurrence over fixed Q/K/V ranges of the completed whole + /// producers, exactly as `gdn_step_from_products_f32` admits them, then + /// the full next-state scan and the readout scan. The queue's own finite + /// function scans the next state; `GdnStateFiniteGuard` is not involved. + #[allow(clippy::too_many_arguments)] // Seven fixed source-defined owners. + pub fn recurrence( + &mut self, + state: &'lease DeviceBuffer<'lease>, + qk: &'lease DeviceBuffer<'lease>, + h: &'lease DeviceBuffer<'lease>, + gate: &'lease DeviceBuffer<'lease>, + beta: &'lease DeviceBuffer<'lease>, + next_state: &'lease DeviceBuffer<'lease>, + readout: &'lease DeviceBuffer<'lease>, + ) -> Result<()> { + let result = (|| { + self.ready(Step::Recurrence)?; + self.same(self.qk, qk)?; + self.same(self.h, h)?; + self.same(self.gate, gate)?; + self.same(self.sigmoid, beta)?; + let original = Operation::GdnStep.layout(); + // Admit the WHOLE real allocations, including aliases outside the + // consumed ranges, before deriving any private pointer operands. + let mut whole = original; + whole.bytes = [ + STATE_BYTES, + QK_BYTES, + QK_BYTES, + 192, + 192, + STATE_BYTES, + 24_576, + 0, + 0, + ]; + whole.align = [4; 9]; + whole.count = 7; + whole.outputs = 0b110_0000; + let queue = &*self.queue; + let (_, _, owners) = admission( + queue.context, + &[state, qk, h, gate, beta, next_state, readout], + Admission { + operation: Operation::GdnStep, + layout: Ok(whole), + asset: qwen_ffi::asset(Operation::GdnStep), + epsilon: 0.0, + in_place: false, + }, + )?; + let status = queue.status_handle()?; + for owner in &owners[..7] { + if owner.overlaps(1, status, STATUS_BYTES) { + return Err(Error::OutputAliasesInput); + } + } + let q = owners[1].checked_subspan(QK_BYTES, 0, 8192)?; + let k = owners[1].checked_subspan(QK_BYTES, 8192, 8192)?; + let v = owners[2].checked_subspan(QK_BYTES, 16_384, 24_576)?; + let handles = [ + owners[0], q, k, v, owners[3], owners[4], owners[5], owners[6], owners[0], + ]; + ranges_layout(Operation::GdnStep, original, handles, original.bytes, false)?; + let function = queue.kernels.as_ref().ok_or(Error::ContextPoisoned)?.qwen[STEP]; + self.commands.push(Command::Qwen( + function, + Operation::GdnStep, + Box::new(Arguments::with_layout( + Operation::GdnStep, + original, + handles, + 0.0, + )), + )); + self.held + .extend_from_slice(&[state, qk, h, gate, beta, next_state, readout]); + // Earliest full-state refusal precedes the readout, as before. + self.push_scan(GdnQueueStage::NextState, next_state)?; + self.push_scan(GdnQueueStage::Readout, readout)?; + self.readout = readout.handle; + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } + /// Device-only projection output of the Z role (6,144 words). + pub fn scan_z(&mut self, z: &'lease DeviceBuffer<'lease>) -> Result<()> { + let result = (|| { + self.ready(Step::Z)?; + self.push_scan(GdnQueueStage::Z, z)?; + self.z = z.handle; + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } + pub fn out_norm( + &mut self, + readout: &'lease DeviceBuffer<'lease>, + z: &'lease DeviceBuffer<'lease>, + gamma: &'lease DeviceBuffer<'lease>, + normalized: &'lease DeviceBuffer<'lease>, + epsilon: f32, + ) -> Result<()> { + let result = (|| { + self.ready(Step::OutNorm)?; + self.same(self.readout, readout)?; + self.same(self.z, z)?; + self.push_stage(OUT_NORM, &[readout, z, gamma, normalized], epsilon)?; + self.push_scan(GdnQueueStage::Normalized, normalized)?; + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } + /// Select the already produced next-history owner for the single bounded + /// D2H performed inside the final drain. No other range is exposed. + pub fn fetch_next_history(&mut self, next_history: &'lease DeviceBuffer<'lease>) -> Result<()> { + let result = (|| { + if self.fetch.is_some() { + return Err(Error::InvalidQwenShape); + } + self.same(self.next_history, next_history)?; + let handle = self.handle_of(next_history, HISTORY_BYTES)?; + self.held.push(next_history); + self.fetch = Some(handle); + Ok(()) + })(); + self.latch(result) + } + + /// Drain the complete admitted prefix once. Earlier numerical refusal beats + /// a later admission error; an admission error with a clean prefix is the + /// returned error. No usable history is returned on numerical refusal. + pub fn finish(mut self) -> Result { + let complete = self.step == Step::Done && self.fetch.is_some(); + if !complete && self.refusal.is_none() { + self.refusal = Some(Error::InvalidQwenShape); + } + let drained = self.drain(complete)?; + if drained.refusal.is_none() + && let Some(error) = drained.deferred + { + return Err(error); + } + Ok(GdnRowCompletion { + refusal: drained.refusal, + next_history: if drained.refusal.is_none() { + drained.next_history + } else { + None + }, + }) + } +} diff --git a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_3.rs b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_3.rs new file mode 100644 index 00000000..5d2ee4e8 --- /dev/null +++ b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_3.rs @@ -0,0 +1,91 @@ +//! Moved out of the parent module by STRA-338: impl GdnRowPrefix (3). + +#[allow(unused_imports)] +use super::*; + + + +impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> { + + pub(in super::super) fn drain(mut self, fetch: bool) -> Result { + let status = self.queue.status_handle()?; + let mut statuses = staging(STATUS_BYTES)?; + let write_fetch = fetch && self.refusal.is_none(); + let mut fetched = staging(if write_fetch { HISTORY_BYTES } else { 0 })?; + if !self.commands.is_empty() { + let zero = self + .queue + .kernels + .as_ref() + .ok_or(Error::ContextPoisoned)? + .zero; + let mut reset = ffi::MmqResidentArguments::zero(status, SLOTS as u32); + let context = self.queue.context; + let guard = context.enter().inspect_err(|_| { + self.queue.failed = true; + context.poisoned.set(true); + })?; + let mut operation = + context + .driver + .api + .launch_mmq_resident(zero, SLOTS as u32, &mut reset); + for command in &mut self.commands { + if operation.is_err() { + break; + } + operation = command.launch(context); + } + if operation.is_ok() { + operation = context.driver.api.copy_to(status, &mut statuses); + } + if operation.is_ok() && write_fetch { + let source = self.fetch.ok_or(Error::InvalidQwenShape)?; + operation = context.driver.api.copy_to(source, &mut fetched); + } + let sync = context.driver.api.synchronize(); + let pop = guard.finish(); + if operation.is_err() || sync.is_err() || pop.is_err() { + self.queue.failed = true; + context.poisoned.set(true); + } + if sync.is_err() || pop.is_err() { + // Completion is uncertain: retain every actual argument/staging + // owner and every borrowed buffer; Context poison forbids reuse. + std::mem::forget((reset, self.commands, self.held, statuses, fetched)); + return combine(combine(operation, sync), pop) + .map(|()| unreachable!("uncertain GDN row drain")); + } + combine(combine(operation, sync), pop)?; + } + let (_, refusal) = match decode_statuses(&statuses, self.checks) { + Ok(decoded) => decoded, + Err(error) => { + self.queue.failed = true; + self.queue.context.poisoned.set(true); + return Err(error); + } + }; + let next_history = if write_fetch && refusal.is_none() { + let mut values = Vec::new(); + values + .try_reserve_exact(HISTORY_BYTES / 4) + .map_err(|_| Error::HostAllocation)?; + values.extend( + fetched + .as_chunks::<4>() + .0 + .iter() + .map(|word| f32::from_le_bytes(*word)), + ); + Some(values.into_boxed_slice()) + } else { + None + }; + Ok(Drained { + refusal, + deferred: self.refusal, + next_history, + }) + } +} diff --git a/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix.rs b/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix.rs index 90154958..358ae628 100644 --- a/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix.rs +++ b/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix.rs @@ -3,399 +3,7 @@ #[allow(unused_imports)] use super::*; - -impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> { - pub(super) fn ready(&self, step: Step) -> Result<()> { - if let Some(error) = &self.refusal { - return Err(error.clone()); - } - if self.step != step { - return Err(Error::InvalidQwenShape); - } - self.batch.status_handle()?; - Ok(()) - } - pub(super) fn latch(&mut self, result: Result<()>) -> Result<()> { - if let Err(error) = &result { - self.refusal.get_or_insert_with(|| error.clone()); - } - result - } - /// Admit one caller buffer under `role` with an exact size. - pub(super) fn bind( - &mut self, - role: Role, - buffer: &'lease DeviceBuffer<'lease>, - bytes: usize, - ) -> Result { - if !std::ptr::eq(self.batch.context, buffer.context) { - return Err(Error::ContextMismatch); - } - if bytes == 0 || buffer.bytes != bytes { - return Err(Error::InvalidQwenShape); - } - let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; - handle.validate_projection_extent(buffer.bytes, 4)?; - let status = self.batch.status_handle()?; - if handle.overlaps(buffer.bytes, status, STATUS_BYTES) { - return Err(Error::OutputAliasesInput); - } - self.bindings.bind(role, handle, buffer.bytes)?; - if !self.held.iter().any(|held| std::ptr::eq(*held, buffer)) { - self.held.push(buffer); - } - Ok(handle) - } - pub(super) fn push( - &mut self, - kernel: FusedKernel, - geometry: ([u32; 3], [u32; 3]), - args: &[ffi::KernelArg], - ) -> Result<()> { - let function = self - .batch - .functions - .as_ref() - .ok_or(Error::ContextPoisoned)?[kernel.index()]; - self.commands.push(Command { - function, - grid: geometry.0, - block: geometry.1, - args: ffi::GdnPrefillArguments::new(args)?, - }); - Ok(()) - } - pub(super) fn status_word(&self, stage: GdnFusedStage) -> Result { - self.batch - .status_handle()? - .checked_subspan(STATUS_BYTES, stage.slot() * 4, 4) - } - /// Complete finite scan of the whole buffer bound to `role`, into the stage's own status word. Stages are - /// scanned strictly in program order. - pub(super) fn scan(&mut self, stage: GdnFusedStage, role: Role) -> Result<()> { - if self.checks != stage.slot() { - return Err(Error::InvalidQwenShape); - } - let (handle, bytes) = self.bindings.get(role)?; - if bytes != stage.bytes() { - return Err(Error::InvalidQwenShape); - } - let elements = stage.elements(); - let status = self.status_word(stage)?; - self.push( - FusedKernel::FiniteF32, - linear(elements)?, - &[ - ffi::KernelArg::Pointer(handle), - ffi::KernelArg::Pointer(status), - ffi::KernelArg::U32(u32::try_from(elements).map_err(|_| Error::InvalidQwenShape)?), - ], - )?; - self.checks = stage.slot() + 1; - Ok(()) - } - pub(super) fn handle(&self, role: Role) -> Result { - Ok(self.bindings.get(role)?.0) - } - - /// Admit the program inputs and scan them first: the projected QKV `[10240]` and Z `[6144]` (device-resident, - /// not yet finite-checked by their producer). - pub fn scan_inputs( - &mut self, - qkv: &'lease DeviceBuffer<'lease>, - z: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { - let result = (|| { - self.ready(Step::Inputs)?; - self.bind(Role::Qkv, qkv, GdnFusedStage::Qkv.bytes())?; - self.bind(Role::Z, z, GdnFusedStage::Z.bytes())?; - self.scan(GdnFusedStage::Qkv, Role::Qkv)?; - self.scan(GdnFusedStage::Z, Role::Z)?; - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - /// Seed the in-place candidate state. `Some(resident)`: the bit-exact device copy of the resident mirror (a - /// key hit). `None`: the caller has already uploaded the canonical host prior into `next_state` (a miss). - pub fn seed_state( - &mut self, - resident: Option<&'lease DeviceBuffer<'lease>>, - next_state: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { - let result = (|| { - self.ready(Step::Seed)?; - let next = self.bind(Role::NextState, next_state, GDN_FUSED_T1_STATE_BYTES)?; - if let Some(resident) = resident { - let source = self.bind(Role::Resident, resident, GDN_FUSED_T1_STATE_BYTES)?; - self.push( - FusedKernel::CopyF32, - linear(STATE_WORDS)?, - &[ - ffi::KernelArg::Pointer(source), - ffi::KernelArg::Pointer(next), - ffi::KernelArg::U32( - u32::try_from(STATE_WORDS).map_err(|_| Error::InvalidQwenShape)?, - ), - ], - )?; - } - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - /// `fused_gdn_conv_l2`: `next_history` holds the canonical prior history (uploaded by the caller) and is updated in - /// place; `h` receives conv + SiLU + the L2 norms of the first 32 heads. Scans `next_history` then `h`. - pub fn conv_l2( - &mut self, - next_history: &'lease DeviceBuffer<'lease>, - conv_weights: &'lease DeviceBuffer<'lease>, - h: &'lease DeviceBuffer<'lease>, - epsilon: f32, - ) -> Result<()> { - let result = (|| { - self.ready(Step::Conv)?; - let qkv = self.handle(Role::Qkv)?; - let hist = self.bind( - Role::NextHistory, - next_history, - GdnFusedStage::NextHistory.bytes(), - )?; - let w = self.bind(Role::ConvW, conv_weights, 4 * C * F32)?; - let h_handle = self.bind(Role::H, h, GdnFusedStage::H.bytes())?; - self.push( - FusedKernel::ConvL2, - ([(C / S) as u32, 1, 1], [S as u32, 1, 1]), - &[ - ffi::KernelArg::Pointer(hist), - ffi::KernelArg::Pointer(qkv), - ffi::KernelArg::Pointer(w), - ffi::KernelArg::Pointer(h_handle), - ffi::KernelArg::F32(epsilon), - ], - )?; - self.scan(GdnFusedStage::NextHistory, Role::NextHistory)?; - self.scan(GdnFusedStage::H, Role::H)?; - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - /// `fused_gdn_ab`: gate = softplus(alpha . x + dt) * ssm_a, beta = sigmoid(beta . x). `w_alpha` / `w_beta` are - /// the exact BF16 `[48][2560]` matrices, `mixed` the exact f32 `[2560]` activation. - #[allow(clippy::too_many_arguments)] // The Original call has the same operand list. - pub fn ab( - &mut self, - mixed: &'lease DeviceBuffer<'lease>, - w_alpha: &'lease DeviceBuffer<'lease>, - w_beta: &'lease DeviceBuffer<'lease>, - dt: &'lease DeviceBuffer<'lease>, - ssm_a: &'lease DeviceBuffer<'lease>, - gate: &'lease DeviceBuffer<'lease>, - beta: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { - let result = (|| { - self.ready(Step::Ab)?; - let x = self.bind(Role::Mixed, mixed, N_EMBD * F32)?; - let wa = self.bind(Role::WAlpha, w_alpha, HV * N_EMBD * F16)?; - let wb = self.bind(Role::WBeta, w_beta, HV * N_EMBD * F16)?; - let dt_h = self.bind(Role::Dt, dt, HV * F32)?; - let a_h = self.bind(Role::A, ssm_a, HV * F32)?; - let gate_h = self.bind(Role::Gate, gate, GdnFusedStage::Gate.bytes())?; - let beta_h = self.bind(Role::Beta, beta, GdnFusedStage::Beta.bytes())?; - if self.checks != GdnFusedStage::RawAlpha.slot() { - return Err(Error::InvalidQwenShape); - } - // Two adjacent private words receive only integer classifications of the original raw accumulators. - let raw_status = self.batch.status_handle()?.checked_subspan( - STATUS_BYTES, - GdnFusedStage::RawAlpha.slot() * F32, - 2 * F32, - )?; - self.push( - FusedKernel::Ab, - ([((2 * HV + 7) / 8) as u32, 1, 1], [256, 1, 1]), - &[ - ffi::KernelArg::Pointer(x), - ffi::KernelArg::Pointer(wa), - ffi::KernelArg::Pointer(wb), - ffi::KernelArg::Pointer(dt_h), - ffi::KernelArg::Pointer(a_h), - ffi::KernelArg::Pointer(gate_h), - ffi::KernelArg::Pointer(beta_h), - ffi::KernelArg::Pointer(raw_status), - ], - )?; - self.checks = GdnFusedStage::RawBeta.slot() + 1; - self.scan(GdnFusedStage::Gate, Role::Gate)?; - self.scan(GdnFusedStage::Beta, Role::Beta)?; - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - /// `fused_gdn_step_norm`: the in-place state update, readout and per-head norm / ssm_norm / sigmoid(z) gate. - /// `gamma` is the f32 `[128]` ssm_norm weight; `y` receives the f32 `[6144]` normalized readout. Scans `y` then - /// the whole updated state. - pub fn step_norm( - &mut self, - gamma: &'lease DeviceBuffer<'lease>, - y: &'lease DeviceBuffer<'lease>, - epsilon: f32, - ) -> Result<()> { - let result = (|| { - self.ready(Step::Norm)?; - let state = self.handle(Role::NextState)?; - let h = self.handle(Role::H)?; - let gate = self.handle(Role::Gate)?; - let beta = self.handle(Role::Beta)?; - let z = self.handle(Role::Z)?; - let gamma_h = self.bind(Role::Gamma, gamma, S * F32)?; - let y_h = self.bind(Role::Y, y, GdnFusedStage::Y.bytes())?; - self.push( - FusedKernel::StepNorm, - ([HV as u32, 1, 1], [S as u32, 4, 1]), - &[ - ffi::KernelArg::Pointer(state), - ffi::KernelArg::Pointer(h), - ffi::KernelArg::Pointer(gate), - ffi::KernelArg::Pointer(beta), - ffi::KernelArg::Pointer(z), - ffi::KernelArg::Pointer(gamma_h), - ffi::KernelArg::F32(epsilon), - ffi::KernelArg::Pointer(y_h), - ], - )?; - self.scan(GdnFusedStage::Y, Role::Y)?; - self.scan(GdnFusedStage::State, Role::NextState)?; - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - /// Ask for the candidate state and history on the host after a clean complete drain. - pub fn fetch_candidate(&mut self) -> Result<()> { - let result = (|| { - self.ready(Step::Fetch)?; - let state = self.handle(Role::NextState)?; - let history = self.handle(Role::NextHistory)?; - self.fetch = Some((state, history)); - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - - /// Drain the complete admitted prefix once. Earlier numerical refusal beats a later admission error; an - /// admission error with a clean prefix is the returned error. No candidate is returned on numerical refusal. - pub fn finish(mut self) -> Result { - let complete = self.step == Step::Done && self.fetch.is_some(); - if !complete && self.refusal.is_none() { - self.refusal = Some(Error::InvalidQwenShape); - } - let drained = self.drain(complete)?; - if drained.refusal.is_none() - && let Some(error) = drained.deferred - { - return Err(error); - } - Ok(GdnFusedCompletion { - refusal: drained.refusal, - fetched: if drained.refusal.is_none() { - drained.fetched - } else { - None - }, - }) - } - - pub(super) fn drain(mut self, fetch: bool) -> Result { - let status = self.batch.status_handle()?; - let mut statuses = staging(STATUS_BYTES)?; - let write_fetch = fetch && self.refusal.is_none(); - let mut fetched_state = staging(if write_fetch { - GDN_FUSED_T1_STATE_BYTES - } else { - 0 - })?; - let mut fetched_history = staging(if write_fetch { HISTORY_WORDS * F32 } else { 0 })?; - if self.commands.len() > 1 { - let context = self.batch.context; - let guard = context.enter().inspect_err(|_| { - self.batch.failed = true; - context.poisoned.set(true); - })?; - // The caller's inputs may have arrived by synchronous pageable H2D (candidate history/state seeds), which - // can return after host staging only: one real context synchronization precedes the first launch. - let stream = GdnStream::default_stream(); - let mut operation = context.driver.api.synchronize(); - if operation.is_ok() { - for command in &mut self.commands { - operation = context.driver.api.launch_gdn_native( - command.function, - stream, - command.grid, - command.block, - &mut command.args, - ); - if operation.is_err() { - break; - } - } - } - // Every kernel ran on the default stream; the D2H below is ordered after them by this completion fence. - let sync = context.driver.api.synchronize(); - if operation.is_ok() && sync.is_ok() { - operation = context.driver.api.copy_to(status, &mut statuses); - } - if operation.is_ok() && sync.is_ok() && write_fetch { - let (state, history) = self.fetch.ok_or(Error::InvalidQwenShape)?; - operation = context.driver.api.copy_to(state, &mut fetched_state); - if operation.is_ok() { - operation = context.driver.api.copy_to(history, &mut fetched_history); - } - } - let pop = guard.finish(); - if operation.is_err() || sync.is_err() || pop.is_err() { - self.batch.failed = true; - context.poisoned.set(true); - } - if sync.is_err() || pop.is_err() { - // Completion is uncertain: retain every actual argument/staging owner. The borrowed buffers are kept alive - // by the poisoned context (it refuses to enter, so their frees leak instead of racing the device). - std::mem::forget(( - self.commands, - self.held, - statuses, - fetched_state, - fetched_history, - )); - return combine(combine(operation, sync), pop) - .map(|()| unreachable!("uncertain fused GDN T1 drain")); - } - combine(combine(operation, sync), pop)?; - } - let refusal = match decode_statuses(&statuses, self.checks) { - Ok(refusal) => refusal, - Err(error) => { - self.batch.failed = true; - self.batch.context.poisoned.set(true); - return Err(error); - } - }; - let fetched = if write_fetch && refusal.is_none() { - Some(( - words::(&fetched_state, f32::from_le_bytes)?, - words::(&fetched_history, f32::from_le_bytes)?, - )) - } else { - None - }; - Ok(Drained { - refusal, - deferred: self.refusal, - fetched, - }) - } -} +#[path = "impl_gdnfusedprefix/impl_gdnfusedprefix_2.rs"] +mod impl_gdnfusedprefix_2; +#[path = "impl_gdnfusedprefix/impl_gdnfusedprefix_2_2.rs"] +mod impl_gdnfusedprefix_2_2; diff --git a/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2.rs b/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2.rs new file mode 100644 index 00000000..61bb21c5 --- /dev/null +++ b/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2.rs @@ -0,0 +1,239 @@ +//! Moved out of the parent module by STRA-338: impl GdnFusedPrefix. + +#[allow(unused_imports)] +use super::*; + + + +impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> { + pub(in super::super) fn ready(&self, step: Step) -> Result<()> { + if let Some(error) = &self.refusal { + return Err(error.clone()); + } + if self.step != step { + return Err(Error::InvalidQwenShape); + } + self.batch.status_handle()?; + Ok(()) + } + pub(in super::super) fn latch(&mut self, result: Result<()>) -> Result<()> { + if let Err(error) = &result { + self.refusal.get_or_insert_with(|| error.clone()); + } + result + } + /// Admit one caller buffer under `role` with an exact size. + pub(in super::super) fn bind( + &mut self, + role: Role, + buffer: &'lease DeviceBuffer<'lease>, + bytes: usize, + ) -> Result { + if !std::ptr::eq(self.batch.context, buffer.context) { + return Err(Error::ContextMismatch); + } + if bytes == 0 || buffer.bytes != bytes { + return Err(Error::InvalidQwenShape); + } + let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; + handle.validate_projection_extent(buffer.bytes, 4)?; + let status = self.batch.status_handle()?; + if handle.overlaps(buffer.bytes, status, STATUS_BYTES) { + return Err(Error::OutputAliasesInput); + } + self.bindings.bind(role, handle, buffer.bytes)?; + if !self.held.iter().any(|held| std::ptr::eq(*held, buffer)) { + self.held.push(buffer); + } + Ok(handle) + } + pub(in super::super) fn push( + &mut self, + kernel: FusedKernel, + geometry: ([u32; 3], [u32; 3]), + args: &[ffi::KernelArg], + ) -> Result<()> { + let function = self + .batch + .functions + .as_ref() + .ok_or(Error::ContextPoisoned)?[kernel.index()]; + self.commands.push(Command { + function, + grid: geometry.0, + block: geometry.1, + args: ffi::GdnPrefillArguments::new(args)?, + }); + Ok(()) + } + pub(in super::super) fn status_word(&self, stage: GdnFusedStage) -> Result { + self.batch + .status_handle()? + .checked_subspan(STATUS_BYTES, stage.slot() * 4, 4) + } + /// Complete finite scan of the whole buffer bound to `role`, into the stage's own status word. Stages are + /// scanned strictly in program order. + pub(in super::super) fn scan(&mut self, stage: GdnFusedStage, role: Role) -> Result<()> { + if self.checks != stage.slot() { + return Err(Error::InvalidQwenShape); + } + let (handle, bytes) = self.bindings.get(role)?; + if bytes != stage.bytes() { + return Err(Error::InvalidQwenShape); + } + let elements = stage.elements(); + let status = self.status_word(stage)?; + self.push( + FusedKernel::FiniteF32, + linear(elements)?, + &[ + ffi::KernelArg::Pointer(handle), + ffi::KernelArg::Pointer(status), + ffi::KernelArg::U32(u32::try_from(elements).map_err(|_| Error::InvalidQwenShape)?), + ], + )?; + self.checks = stage.slot() + 1; + Ok(()) + } + pub(in super::super) fn handle(&self, role: Role) -> Result { + Ok(self.bindings.get(role)?.0) + } + + /// Admit the program inputs and scan them first: the projected QKV `[10240]` and Z `[6144]` (device-resident, + /// not yet finite-checked by their producer). + pub fn scan_inputs( + &mut self, + qkv: &'lease DeviceBuffer<'lease>, + z: &'lease DeviceBuffer<'lease>, + ) -> Result<()> { + let result = (|| { + self.ready(Step::Inputs)?; + self.bind(Role::Qkv, qkv, GdnFusedStage::Qkv.bytes())?; + self.bind(Role::Z, z, GdnFusedStage::Z.bytes())?; + self.scan(GdnFusedStage::Qkv, Role::Qkv)?; + self.scan(GdnFusedStage::Z, Role::Z)?; + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } + /// Seed the in-place candidate state. `Some(resident)`: the bit-exact device copy of the resident mirror (a + /// key hit). `None`: the caller has already uploaded the canonical host prior into `next_state` (a miss). + pub fn seed_state( + &mut self, + resident: Option<&'lease DeviceBuffer<'lease>>, + next_state: &'lease DeviceBuffer<'lease>, + ) -> Result<()> { + let result = (|| { + self.ready(Step::Seed)?; + let next = self.bind(Role::NextState, next_state, GDN_FUSED_T1_STATE_BYTES)?; + if let Some(resident) = resident { + let source = self.bind(Role::Resident, resident, GDN_FUSED_T1_STATE_BYTES)?; + self.push( + FusedKernel::CopyF32, + linear(STATE_WORDS)?, + &[ + ffi::KernelArg::Pointer(source), + ffi::KernelArg::Pointer(next), + ffi::KernelArg::U32( + u32::try_from(STATE_WORDS).map_err(|_| Error::InvalidQwenShape)?, + ), + ], + )?; + } + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } + /// `fused_gdn_conv_l2`: `next_history` holds the canonical prior history (uploaded by the caller) and is updated in + /// place; `h` receives conv + SiLU + the L2 norms of the first 32 heads. Scans `next_history` then `h`. + pub fn conv_l2( + &mut self, + next_history: &'lease DeviceBuffer<'lease>, + conv_weights: &'lease DeviceBuffer<'lease>, + h: &'lease DeviceBuffer<'lease>, + epsilon: f32, + ) -> Result<()> { + let result = (|| { + self.ready(Step::Conv)?; + let qkv = self.handle(Role::Qkv)?; + let hist = self.bind( + Role::NextHistory, + next_history, + GdnFusedStage::NextHistory.bytes(), + )?; + let w = self.bind(Role::ConvW, conv_weights, 4 * C * F32)?; + let h_handle = self.bind(Role::H, h, GdnFusedStage::H.bytes())?; + self.push( + FusedKernel::ConvL2, + ([(C / S) as u32, 1, 1], [S as u32, 1, 1]), + &[ + ffi::KernelArg::Pointer(hist), + ffi::KernelArg::Pointer(qkv), + ffi::KernelArg::Pointer(w), + ffi::KernelArg::Pointer(h_handle), + ffi::KernelArg::F32(epsilon), + ], + )?; + self.scan(GdnFusedStage::NextHistory, Role::NextHistory)?; + self.scan(GdnFusedStage::H, Role::H)?; + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } + /// `fused_gdn_ab`: gate = softplus(alpha . x + dt) * ssm_a, beta = sigmoid(beta . x). `w_alpha` / `w_beta` are + /// the exact BF16 `[48][2560]` matrices, `mixed` the exact f32 `[2560]` activation. + #[allow(clippy::too_many_arguments)] // The Original call has the same operand list. + pub fn ab( + &mut self, + mixed: &'lease DeviceBuffer<'lease>, + w_alpha: &'lease DeviceBuffer<'lease>, + w_beta: &'lease DeviceBuffer<'lease>, + dt: &'lease DeviceBuffer<'lease>, + ssm_a: &'lease DeviceBuffer<'lease>, + gate: &'lease DeviceBuffer<'lease>, + beta: &'lease DeviceBuffer<'lease>, + ) -> Result<()> { + let result = (|| { + self.ready(Step::Ab)?; + let x = self.bind(Role::Mixed, mixed, N_EMBD * F32)?; + let wa = self.bind(Role::WAlpha, w_alpha, HV * N_EMBD * F16)?; + let wb = self.bind(Role::WBeta, w_beta, HV * N_EMBD * F16)?; + let dt_h = self.bind(Role::Dt, dt, HV * F32)?; + let a_h = self.bind(Role::A, ssm_a, HV * F32)?; + let gate_h = self.bind(Role::Gate, gate, GdnFusedStage::Gate.bytes())?; + let beta_h = self.bind(Role::Beta, beta, GdnFusedStage::Beta.bytes())?; + if self.checks != GdnFusedStage::RawAlpha.slot() { + return Err(Error::InvalidQwenShape); + } + // Two adjacent private words receive only integer classifications of the original raw accumulators. + let raw_status = self.batch.status_handle()?.checked_subspan( + STATUS_BYTES, + GdnFusedStage::RawAlpha.slot() * F32, + 2 * F32, + )?; + self.push( + FusedKernel::Ab, + ([((2 * HV + 7) / 8) as u32, 1, 1], [256, 1, 1]), + &[ + ffi::KernelArg::Pointer(x), + ffi::KernelArg::Pointer(wa), + ffi::KernelArg::Pointer(wb), + ffi::KernelArg::Pointer(dt_h), + ffi::KernelArg::Pointer(a_h), + ffi::KernelArg::Pointer(gate_h), + ffi::KernelArg::Pointer(beta_h), + ffi::KernelArg::Pointer(raw_status), + ], + )?; + self.checks = GdnFusedStage::RawBeta.slot() + 1; + self.scan(GdnFusedStage::Gate, Role::Gate)?; + self.scan(GdnFusedStage::Beta, Role::Beta)?; + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } +} diff --git a/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2_2.rs b/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2_2.rs new file mode 100644 index 00000000..1f55628d --- /dev/null +++ b/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2_2.rs @@ -0,0 +1,172 @@ +//! Moved out of the parent module by STRA-338: impl GdnFusedPrefix (2). + +#[allow(unused_imports)] +use super::*; + + + +impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> { + /// `fused_gdn_step_norm`: the in-place state update, readout and per-head norm / ssm_norm / sigmoid(z) gate. + /// `gamma` is the f32 `[128]` ssm_norm weight; `y` receives the f32 `[6144]` normalized readout. Scans `y` then + /// the whole updated state. + pub fn step_norm( + &mut self, + gamma: &'lease DeviceBuffer<'lease>, + y: &'lease DeviceBuffer<'lease>, + epsilon: f32, + ) -> Result<()> { + let result = (|| { + self.ready(Step::Norm)?; + let state = self.handle(Role::NextState)?; + let h = self.handle(Role::H)?; + let gate = self.handle(Role::Gate)?; + let beta = self.handle(Role::Beta)?; + let z = self.handle(Role::Z)?; + let gamma_h = self.bind(Role::Gamma, gamma, S * F32)?; + let y_h = self.bind(Role::Y, y, GdnFusedStage::Y.bytes())?; + self.push( + FusedKernel::StepNorm, + ([HV as u32, 1, 1], [S as u32, 4, 1]), + &[ + ffi::KernelArg::Pointer(state), + ffi::KernelArg::Pointer(h), + ffi::KernelArg::Pointer(gate), + ffi::KernelArg::Pointer(beta), + ffi::KernelArg::Pointer(z), + ffi::KernelArg::Pointer(gamma_h), + ffi::KernelArg::F32(epsilon), + ffi::KernelArg::Pointer(y_h), + ], + )?; + self.scan(GdnFusedStage::Y, Role::Y)?; + self.scan(GdnFusedStage::State, Role::NextState)?; + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } + /// Ask for the candidate state and history on the host after a clean complete drain. + pub fn fetch_candidate(&mut self) -> Result<()> { + let result = (|| { + self.ready(Step::Fetch)?; + let state = self.handle(Role::NextState)?; + let history = self.handle(Role::NextHistory)?; + self.fetch = Some((state, history)); + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } + + /// Drain the complete admitted prefix once. Earlier numerical refusal beats a later admission error; an + /// admission error with a clean prefix is the returned error. No candidate is returned on numerical refusal. + pub fn finish(mut self) -> Result { + let complete = self.step == Step::Done && self.fetch.is_some(); + if !complete && self.refusal.is_none() { + self.refusal = Some(Error::InvalidQwenShape); + } + let drained = self.drain(complete)?; + if drained.refusal.is_none() + && let Some(error) = drained.deferred + { + return Err(error); + } + Ok(GdnFusedCompletion { + refusal: drained.refusal, + fetched: if drained.refusal.is_none() { + drained.fetched + } else { + None + }, + }) + } + + pub(in super::super) fn drain(mut self, fetch: bool) -> Result { + let status = self.batch.status_handle()?; + let mut statuses = staging(STATUS_BYTES)?; + let write_fetch = fetch && self.refusal.is_none(); + let mut fetched_state = staging(if write_fetch { + GDN_FUSED_T1_STATE_BYTES + } else { + 0 + })?; + let mut fetched_history = staging(if write_fetch { HISTORY_WORDS * F32 } else { 0 })?; + if self.commands.len() > 1 { + let context = self.batch.context; + let guard = context.enter().inspect_err(|_| { + self.batch.failed = true; + context.poisoned.set(true); + })?; + // The caller's inputs may have arrived by synchronous pageable H2D (candidate history/state seeds), which + // can return after host staging only: one real context synchronization precedes the first launch. + let stream = GdnStream::default_stream(); + let mut operation = context.driver.api.synchronize(); + if operation.is_ok() { + for command in &mut self.commands { + operation = context.driver.api.launch_gdn_native( + command.function, + stream, + command.grid, + command.block, + &mut command.args, + ); + if operation.is_err() { + break; + } + } + } + // Every kernel ran on the default stream; the D2H below is ordered after them by this completion fence. + let sync = context.driver.api.synchronize(); + if operation.is_ok() && sync.is_ok() { + operation = context.driver.api.copy_to(status, &mut statuses); + } + if operation.is_ok() && sync.is_ok() && write_fetch { + let (state, history) = self.fetch.ok_or(Error::InvalidQwenShape)?; + operation = context.driver.api.copy_to(state, &mut fetched_state); + if operation.is_ok() { + operation = context.driver.api.copy_to(history, &mut fetched_history); + } + } + let pop = guard.finish(); + if operation.is_err() || sync.is_err() || pop.is_err() { + self.batch.failed = true; + context.poisoned.set(true); + } + if sync.is_err() || pop.is_err() { + // Completion is uncertain: retain every actual argument/staging owner. The borrowed buffers are kept alive + // by the poisoned context (it refuses to enter, so their frees leak instead of racing the device). + std::mem::forget(( + self.commands, + self.held, + statuses, + fetched_state, + fetched_history, + )); + return combine(combine(operation, sync), pop) + .map(|()| unreachable!("uncertain fused GDN T1 drain")); + } + combine(combine(operation, sync), pop)?; + } + let refusal = match decode_statuses(&statuses, self.checks) { + Ok(refusal) => refusal, + Err(error) => { + self.batch.failed = true; + self.batch.context.poisoned.set(true); + return Err(error); + } + }; + let fetched = if write_fetch && refusal.is_none() { + Some(( + words::(&fetched_state, f32::from_le_bytes)?, + words::(&fetched_history, f32::from_le_bytes)?, + )) + } else { + None + }; + Ok(Drained { + refusal, + deferred: self.refusal, + fetched, + }) + } +} diff --git a/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix.rs b/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix.rs index fcbdd575..30af7baf 100644 --- a/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix.rs +++ b/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix.rs @@ -3,688 +3,9 @@ #[allow(unused_imports)] use super::*; - -impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { - pub fn tokens(&self) -> usize { - self.tokens - } - pub(super) fn ready(&self, step: Step) -> Result<()> { - if let Some(error) = &self.refusal { - return Err(error.clone()); - } - if self.step != step { - return Err(Error::InvalidQwenShape); - } - self.batch.status_handle()?; - Ok(()) - } - pub(super) fn latch(&mut self, result: Result<()>) -> Result<()> { - if let Err(error) = &result { - self.refusal.get_or_insert_with(|| error.clone()); - } - result - } - pub(super) fn function(&self, kernel: Kernel) -> Result { - Ok(self - .batch - .functions - .as_ref() - .ok_or(Error::ContextPoisoned)? - .get(kernel)) - } - /// Admit one caller buffer under `role`. `bytes` is the exact size unless - /// `at_least`, in which case the whole allocation is bound. - pub(super) fn bind( - &mut self, - role: Role, - buffer: &'lease DeviceBuffer<'lease>, - bytes: usize, - at_least: bool, - ) -> Result { - if !std::ptr::eq(self.batch.context, buffer.context) { - return Err(Error::ContextMismatch); - } - if bytes == 0 || (at_least && buffer.bytes < bytes) || (!at_least && buffer.bytes != bytes) - { - return Err(Error::InvalidQwenShape); - } - let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; - handle.validate_projection_extent(buffer.bytes, 4)?; - let status = self.batch.status_handle()?; - if handle.overlaps(buffer.bytes, status, STATUS_BYTES) { - return Err(Error::OutputAliasesInput); - } - self.bindings.bind(role, handle, buffer.bytes)?; - if !self.held.iter().any(|held| std::ptr::eq(*held, buffer)) { - self.held.push(buffer); - } - Ok(handle) - } - pub(super) fn push_kernel( - &mut self, - kernel: Kernel, - geometry: ([u32; 3], [u32; 3]), - args: &[ffi::KernelArg], - ) -> Result<()> { - let function = self.function(kernel)?; - self.commands.push(Command::Kernel { - function, - stream: self.stream, - grid: geometry.0, - block: geometry.1, - args: ffi::GdnPrefillArguments::new(args)?, - }); - Ok(()) - } - /// Complete finite scan of the whole buffer bound to `role`, into the - /// stage's own status word. Stages are scanned strictly in program order. - pub(super) fn scan(&mut self, stage: GdnBatchStage, role: Role) -> Result<()> { - if self.checks != stage.slot() { - return Err(Error::InvalidQwenShape); - } - let (handle, bytes) = self.bindings.get(role)?; - let elements = stage.elements(self.tokens); - if bytes != stage.bytes(self.tokens) { - return Err(Error::InvalidQwenShape); - } - let status = - self.batch - .status_handle()? - .checked_subspan(STATUS_BYTES, stage.slot() * 4, 4)?; - let kernel = if stage.is_half() { - Kernel::FiniteF16 - } else { - Kernel::FiniteF32 - }; - self.push_kernel( - kernel, - linear(elements)?, - &[ - ffi::KernelArg::Pointer(handle), - ffi::KernelArg::Pointer(status), - ffi::KernelArg::U32(u32::try_from(elements).map_err(|_| Error::InvalidQwenShape)?), - ], - )?; - self.checks = stage.slot() + 1; - Ok(()) - } - /// The status word of a stage whose witness a kernel writes itself. - pub(super) fn witness_word(&mut self, stage: GdnBatchStage) -> Result { - if self.checks != stage.slot() || stage != GdnBatchStage::StateSteps { - return Err(Error::InvalidQwenShape); - } - let word = - self.batch - .status_handle()? - .checked_subspan(STATUS_BYTES, stage.slot() * 4, 4)?; - self.checks = stage.slot() + 1; - Ok(word) - } - pub(super) fn handle(&self, role: Role) -> Result { - Ok(self.bindings.get(role)?.0) - } - pub(super) fn buffer_ref(&self, role: Role) -> Result<&'lease DeviceBuffer<'lease>> { - let handle = self.handle(role)?; - self.held - .iter() - .copied() - .find(|buffer| buffer.handle == Some(handle)) - .ok_or(Error::InvalidQwenShape) - } - - // ---------------------------------------------------------------- images - /// Original tail of `gr_mix_kernel`: the FP16 image, the BF16 hi image and - /// (when `mixed_bf_lo` is given) the BF16 lo image of an f32 `mixed` - /// `[tokens][2560]`, then the FP16 image scan. For a producer that already - /// delivers the three images use [`Self::images_supplied`]. - pub fn pack_mixed( - &mut self, - mixed: &'lease DeviceBuffer<'lease>, - mixed_h: &'lease DeviceBuffer<'lease>, - mixed_bf: &'lease DeviceBuffer<'lease>, - mixed_bf_lo: Option<&'lease DeviceBuffer<'lease>>, - ) -> Result<()> { - let result = (|| { - self.ready(Step::Images)?; - let t = self.tokens; - let source = self.bind(Role::Mixed, mixed, t * N * F32, false)?; - let h = self.bind(Role::MixedH, mixed_h, t * N * F16, false)?; - let bf = self.bind(Role::MixedBf, mixed_bf, t * N * F16, false)?; - let lo = match mixed_bf_lo { - Some(buffer) => ffi::KernelArg::Pointer(self.bind( - Role::MixedBfLo, - buffer, - t * N * F16, - false, - )?), - None => ffi::KernelArg::NullPointer, - }; - self.push_kernel( - Kernel::MixedPack, - linear(t * N)?, - &[ - ffi::KernelArg::Pointer(source), - ffi::KernelArg::Pointer(h), - ffi::KernelArg::Pointer(bf), - lo, - ffi::KernelArg::I64(t as i64), - ], - )?; - self.scan(GdnBatchStage::MixedH, Role::MixedH)?; - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - /// The three images were produced by the caller's own (original) gr_mix. - pub fn images_supplied( - &mut self, - mixed_h: &'lease DeviceBuffer<'lease>, - mixed_bf: &'lease DeviceBuffer<'lease>, - mixed_bf_lo: Option<&'lease DeviceBuffer<'lease>>, - ) -> Result<()> { - let result = (|| { - self.ready(Step::Images)?; - let t = self.tokens; - self.bind(Role::MixedH, mixed_h, t * N * F16, false)?; - self.bind(Role::MixedBf, mixed_bf, t * N * F16, false)?; - if let Some(buffer) = mixed_bf_lo { - self.bind(Role::MixedBfLo, buffer, t * N * F16, false)?; - } - self.scan(GdnBatchStage::MixedH, Role::MixedH)?; - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - - // ---------------------------------------------------------------- projections - #[allow(clippy::too_many_arguments)] // The fixed operands of one native projection. - pub(super) fn project_native( - &mut self, - format: GdnNativeFormat, - weights: (Role, &'lease DeviceBuffer<'lease>), - scratch: &'lease DeviceBuffer<'lease>, - activation: Role, - output: (Role, &'lease DeviceBuffer<'lease>), - rows: usize, - depth: usize, - output_bytes: usize, - ) -> Result<()> { - let t = self.tokens; - let matrix = format.matrix_bytes(rows, depth)?; - let half_bytes = rows * depth * F16; - let blocks = self.bind(weights.0, weights.1, matrix, false)?; - let scratch_handle = self.bind(Role::Scratch, scratch, half_bytes, true)?; - self.bind(output.0, output.1, output_bytes, false)?; - // The dequantized weights: one thread per 32-value group, 256 per block. - let groups_per_row = depth / 32; - let groups = rows * groups_per_row; - self.push_kernel( - format.kernel(), - linear(groups)?, - &[ - ffi::KernelArg::Pointer(blocks), - ffi::KernelArg::I64((depth / format.block().0 * format.block().1) as i64), - ffi::KernelArg::I64(0), - ffi::KernelArg::I64(rows as i64), - ffi::KernelArg::I64(groups_per_row as i64), - ffi::KernelArg::Pointer(scratch_handle), - ], - )?; - let x = self.buffer_ref(activation)?; - self.commands.push(Command::Gemm { - gemm: self.gemm, - bf16: false, - x, - w: scratch, - y: output.1, - shape: GemmShape { - tokens: t, - rows, - depth, - ldy: rows, - y_offset: 0, - beta: 0.0, - }, - }); - Ok(()) - } - /// Native `attn_qkv` projection: dequantize to FP16, `Y[T,10240] = X . W^T` - /// with `X` = the FP16 image of `mixed`; then the QKV scan. - pub fn project_qkv( - &mut self, - format: GdnNativeFormat, - weights: &'lease DeviceBuffer<'lease>, - scratch: &'lease DeviceBuffer<'lease>, - qkv: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { - let result = (|| { - self.ready(Step::Qkv)?; - let bytes = self.tokens * C * F32; - self.project_native( - format, - (Role::QkvW, weights), - scratch, - Role::MixedH, - (Role::Qkv, qkv), - C, - N, - bytes, - )?; - self.scan(GdnBatchStage::Qkv, Role::Qkv)?; - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - /// Native `attn_gate` (Z) projection, `Y[T,6144]`; then the Z scan. - pub fn project_z( - &mut self, - format: GdnNativeFormat, - weights: &'lease DeviceBuffer<'lease>, - scratch: &'lease DeviceBuffer<'lease>, - z: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { - let result = (|| { - self.ready(Step::Z)?; - let bytes = self.tokens * ZV * F32; - self.project_native( - format, - (Role::ZW, weights), - scratch, - Role::MixedH, - (Role::Z, z), - ZV, - N, - bytes, - )?; - self.scan(GdnBatchStage::Z, Role::Z)?; - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - /// BF16 `ssm_alpha` then `ssm_beta` into the interleaved `ab` `[T][96]` - /// (`alpha` at column 0, raw `beta` at column 48), each as the original - /// does: the hi image with `beta = 0`, then, when the lo image was given, - /// the lo image accumulated with `beta = 1`. Then the Ab scan. - pub fn project_alpha_beta( - &mut self, - alpha_weights: &'lease DeviceBuffer<'lease>, - beta_weights: &'lease DeviceBuffer<'lease>, - ab: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { - let result = (|| { - self.ready(Step::Ab)?; - let t = self.tokens; - self.bind(Role::AlphaW, alpha_weights, HV * N * F16, false)?; - self.bind(Role::BetaW, beta_weights, HV * N * F16, false)?; - self.bind(Role::Ab, ab, t * 2 * HV * F32, false)?; - let x = self.buffer_ref(Role::MixedBf)?; - let lo = self.buffer_ref(Role::MixedBfLo).ok(); - for (weights, y_offset) in [(alpha_weights, 0), (beta_weights, HV)] { - let shape = |beta| GemmShape { - tokens: t, - rows: HV, - depth: N, - ldy: 2 * HV, - y_offset, - beta, - }; - self.commands.push(Command::Gemm { - gemm: self.gemm, - bf16: true, - x, - w: weights, - y: ab, - shape: shape(0.0), - }); - if let Some(lo) = lo { - self.commands.push(Command::Gemm { - gemm: self.gemm, - bf16: true, - x: lo, - w: weights, - y: ab, - shape: shape(1.0), - }); - } - } - self.scan(GdnBatchStage::Ab, Role::Ab)?; - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - - // ---------------------------------------------------------------- GDN kernels - /// `gdn_gates`: `gate` and sigmoid `beta` `[T][48]` from `ab`; two scans. - pub fn gates( - &mut self, - dt: &'lease DeviceBuffer<'lease>, - ssm_a: &'lease DeviceBuffer<'lease>, - gate: &'lease DeviceBuffer<'lease>, - beta: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { - let result = (|| { - self.ready(Step::Gates)?; - let t = self.tokens; - let ab = self.handle(Role::Ab)?; - let dt_h = self.bind(Role::Dt, dt, HV * F32, false)?; - let a_h = self.bind(Role::SsmA, ssm_a, HV * F32, false)?; - let gate_h = self.bind(Role::Gate, gate, t * HV * F32, false)?; - let beta_h = self.bind(Role::Beta, beta, t * HV * F32, false)?; - self.push_kernel( - Kernel::Gates, - linear(t * HV)?, - &[ - ffi::KernelArg::Pointer(ab), - ffi::KernelArg::Pointer(dt_h), - ffi::KernelArg::Pointer(a_h), - ffi::KernelArg::Pointer(gate_h), - ffi::KernelArg::Pointer(beta_h), - ffi::KernelArg::I64(t as i64), - ], - )?; - self.scan(GdnBatchStage::Gate, Role::Gate)?; - self.scan(GdnBatchStage::Beta, Role::Beta)?; - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - /// `gdn_conv`: the 4-tap causal convolution + SiLU over the chunk into `h` - /// `[T][10240]`, and the history after the chunk into `next_history` - /// (`history` stays untouched). Chunks of at most 64 rows use the serial - /// walk, longer ones the tiled kernel plus the history kernel, exactly as - /// the original launcher selects. - pub fn conv( - &mut self, - history: &'lease DeviceBuffer<'lease>, - conv_weights: &'lease DeviceBuffer<'lease>, - next_history: &'lease DeviceBuffer<'lease>, - h: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { - let result = (|| { - self.ready(Step::Conv)?; - let t = self.tokens; - let qkv = self.handle(Role::Qkv)?; - let hist = self.bind(Role::History, history, HISTORY_WORDS * F32, false)?; - let w = self.bind(Role::ConvW, conv_weights, C * 4 * F32, false)?; - let next = self.bind(Role::NextHistory, next_history, HISTORY_WORDS * F32, false)?; - let h_h = self.bind(Role::H, h, t * C * F32, false)?; - let t_arg = ffi::KernelArg::I64(t as i64); - if t <= CONV_TILE { - self.push_kernel( - Kernel::Conv, - ([(C / 128) as u32, 1, 1], [128, 1, 1]), - &[ - ffi::KernelArg::Pointer(hist), - ffi::KernelArg::Pointer(next), - ffi::KernelArg::Pointer(qkv), - ffi::KernelArg::Pointer(w), - ffi::KernelArg::Pointer(h_h), - t_arg, - ], - )?; - } else { - self.push_kernel( - Kernel::ConvTiled, - ( - [(C / 128) as u32, t.div_ceil(CONV_TILE) as u32, 1], - [128, 1, 1], - ), - &[ - ffi::KernelArg::Pointer(hist), - ffi::KernelArg::Pointer(qkv), - ffi::KernelArg::Pointer(w), - ffi::KernelArg::Pointer(h_h), - t_arg, - ], - )?; - self.push_kernel( - Kernel::ConvHist, - ([(C / 128) as u32, 1, 1], [128, 1, 1]), - &[ - ffi::KernelArg::Pointer(next), - ffi::KernelArg::Pointer(hist), - ffi::KernelArg::Pointer(qkv), - t_arg, - ], - )?; - } - self.scan(GdnBatchStage::ConvH, Role::H)?; - self.scan(GdnBatchStage::NextHistory, Role::NextHistory)?; - self.fetch = Some(next); - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - /// `gdn_l2`: in-place L2 normalization of the 32 Q/K heads of every row of - /// `h` (the original's `rsqrtf(ss + eps)` with `eps = 1e-6`); then the scan. - pub fn l2(&mut self) -> Result<()> { - let result = (|| { - self.ready(Step::L2)?; - let h = self.handle(Role::H)?; - self.push_kernel( - Kernel::L2, - ([32, self.tokens as u32, 1], [128, 1, 1]), - &[ - ffi::KernelArg::Pointer(h), - ffi::KernelArg::F32(GDN_BATCH_EPSILON), - ], - )?; - self.scan(GdnBatchStage::Qk, Role::H)?; - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - /// `gdn_rec_cols_pipe`: the whole-chunk recurrence. `state_in` is the - /// immutable prior state `[128][48][128]`, `state_out` the separate final - /// state; `y` receives the un-normalized readout `oc` `[T][6144]`. Then the - /// per-step state witness (written by the kernel) and then the NextState and - /// Readout scans (earliest refusal first). - pub fn recurrence( - &mut self, - state_in: &'lease DeviceBuffer<'lease>, - state_out: &'lease DeviceBuffer<'lease>, - y: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { - let result = (|| { - self.ready(Step::Recurrence)?; - let t = self.tokens; - let h = self.handle(Role::H)?; - let gate = self.handle(Role::Gate)?; - let beta = self.handle(Role::Beta)?; - let s_in = self.bind(Role::StateIn, state_in, STATE_WORDS * F32, false)?; - let s_out = self.bind(Role::StateOut, state_out, STATE_WORDS * F32, false)?; - let y_h = self.bind(Role::Y, y, t * ZV * F32, false)?; - let witness = self.witness_word(GdnBatchStage::StateSteps)?; - self.push_kernel( - Kernel::RecColsPipe, - ([(HV * (S / 32)) as u32, 1, 1], [32, 4, 1]), - &[ - ffi::KernelArg::Pointer(s_in), - ffi::KernelArg::Pointer(s_out), - ffi::KernelArg::Pointer(h), - ffi::KernelArg::Pointer(gate), - ffi::KernelArg::Pointer(beta), - ffi::KernelArg::Pointer(y_h), - ffi::KernelArg::I64(t as i64), - ffi::KernelArg::Pointer(witness), - ], - )?; - self.scan(GdnBatchStage::NextState, Role::StateOut)?; - self.scan(GdnBatchStage::Readout, Role::Y)?; - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - /// `gdn_out_norm`: in place on `y` (f32) plus the half image `y16` - /// (`hf(v)`), gated by `z`; then the Y and Y16 scans. - pub fn out_norm( - &mut self, - gamma: &'lease DeviceBuffer<'lease>, - y16: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { - let result = (|| { - self.ready(Step::OutNorm)?; - let t = self.tokens; - let z = self.handle(Role::Z)?; - let y = self.handle(Role::Y)?; - let gamma_h = self.bind(Role::Gamma, gamma, S * F32, false)?; - let y16_h = self.bind(Role::Y16, y16, t * ZV * F16, false)?; - self.push_kernel( - Kernel::OutNorm, - ([t as u32, HV as u32, 1], [128, 1, 1]), - &[ - ffi::KernelArg::Pointer(z), - ffi::KernelArg::Pointer(gamma_h), - ffi::KernelArg::F32(GDN_BATCH_EPSILON), - ffi::KernelArg::Pointer(y), - ffi::KernelArg::Pointer(y16_h), - ], - )?; - self.scan(GdnBatchStage::Y, Role::Y)?; - self.scan(GdnBatchStage::Y16, Role::Y16)?; - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - /// Native `ssm_out` projection from the FP16 `y16`: `Y[T,2560] = y16 . W^T` - /// into `bo`; then the Bo scan. - pub fn project_out( - &mut self, - format: GdnNativeFormat, - weights: &'lease DeviceBuffer<'lease>, - scratch: &'lease DeviceBuffer<'lease>, - bo: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { - let result = (|| { - self.ready(Step::Out)?; - let bytes = self.tokens * N * F32; - self.project_native( - format, - (Role::OutW, weights), - scratch, - Role::Y16, - (Role::Bo, bo), - N, - ZV, - bytes, - )?; - self.scan(GdnBatchStage::Bo, Role::Bo)?; - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - - /// Drain the complete admitted prefix once. Earlier numerical refusal beats - /// a later admission error; an admission error with a clean prefix is the - /// returned error. No usable history is returned on numerical refusal. - pub fn finish(mut self) -> Result { - let complete = self.step == Step::Done && self.fetch.is_some(); - if !complete && self.refusal.is_none() { - self.refusal = Some(Error::InvalidQwenShape); - } - let drained = self.drain(complete)?; - if drained.refusal.is_none() - && let Some(error) = drained.deferred - { - return Err(error); - } - Ok(GdnBatchCompletion { - refusal: drained.refusal, - next_history: if drained.refusal.is_none() { - drained.next_history - } else { - None - }, - }) - } - - pub(super) fn drain(mut self, fetch: bool) -> Result { - let status = self.batch.status_handle()?; - let mut statuses = staging(STATUS_BYTES)?; - let write_fetch = fetch && self.refusal.is_none(); - let mut fetched = staging(if write_fetch { HISTORY_WORDS * F32 } else { 0 })?; - if self.commands.len() > 1 { - let context = self.batch.context; - let guard = context.enter().inspect_err(|_| { - self.batch.failed = true; - context.poisoned.set(true); - })?; - // The caller's inputs arrived by synchronous pageable H2D, which may - // return after host staging only. The program runs on the adapter's - // dedicated NON-BLOCKING stream, which the legacy default stream does - // not order against: one real context synchronization separates them. - let mut operation = context.driver.api.synchronize(); - if operation.is_ok() { - for command in &mut self.commands { - operation = command.launch(context); - if operation.is_err() { - break; - } - } - } - // Every program kernel and GEMM is on the non-blocking stream: the - // D2H below is only ordered after them by this completion fence. - let sync = context.driver.api.synchronize(); - if operation.is_ok() && sync.is_ok() { - operation = context.driver.api.copy_to(status, &mut statuses); - } - if operation.is_ok() && sync.is_ok() && write_fetch { - let source = self.fetch.ok_or(Error::InvalidQwenShape)?; - operation = context.driver.api.copy_to(source, &mut fetched); - } - let pop = guard.finish(); - if operation.is_err() || sync.is_err() || pop.is_err() { - self.batch.failed = true; - context.poisoned.set(true); - } - if sync.is_err() || pop.is_err() { - // Completion is uncertain: retain every actual argument/staging - // owner and every borrowed buffer; Context poison forbids reuse. - std::mem::forget((self.commands, self.held, statuses, fetched)); - return combine(combine(operation, sync), pop) - .map(|()| unreachable!("uncertain GDN batch drain")); - } - combine(combine(operation, sync), pop)?; - } - let refusal = match decode_statuses(&statuses, self.checks) { - Ok(refusal) => refusal, - Err(error) => { - self.batch.failed = true; - self.batch.context.poisoned.set(true); - return Err(error); - } - }; - let next_history = if write_fetch && refusal.is_none() { - let mut values = Vec::new(); - values - .try_reserve_exact(HISTORY_WORDS) - .map_err(|_| Error::HostAllocation)?; - values.extend( - fetched - .as_chunks::<4>() - .0 - .iter() - .map(|word| f32::from_le_bytes(*word)), - ); - Some(values.into_boxed_slice()) - } else { - None - }; - Ok(Drained { - refusal, - deferred: self.refusal, - next_history, - }) - } -} +#[path = "impl_gdnbatchprefix/impl_gdnbatchprefix_2.rs"] +mod impl_gdnbatchprefix_2; +#[path = "impl_gdnbatchprefix/impl_gdnbatchprefix_2_2.rs"] +mod impl_gdnbatchprefix_2_2; +#[path = "impl_gdnbatchprefix/impl_gdnbatchprefix_3.rs"] +mod impl_gdnbatchprefix_3; diff --git a/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_2.rs b/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_2.rs new file mode 100644 index 00000000..9473fb6d --- /dev/null +++ b/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_2.rs @@ -0,0 +1,254 @@ +//! Moved out of the parent module by STRA-338: impl GdnBatchPrefix. + +#[allow(unused_imports)] +use super::*; + + + +impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { + pub fn tokens(&self) -> usize { + self.tokens + } + pub(in super::super) fn ready(&self, step: Step) -> Result<()> { + if let Some(error) = &self.refusal { + return Err(error.clone()); + } + if self.step != step { + return Err(Error::InvalidQwenShape); + } + self.batch.status_handle()?; + Ok(()) + } + pub(in super::super) fn latch(&mut self, result: Result<()>) -> Result<()> { + if let Err(error) = &result { + self.refusal.get_or_insert_with(|| error.clone()); + } + result + } + pub(in super::super) fn function(&self, kernel: Kernel) -> Result { + Ok(self + .batch + .functions + .as_ref() + .ok_or(Error::ContextPoisoned)? + .get(kernel)) + } + /// Admit one caller buffer under `role`. `bytes` is the exact size unless + /// `at_least`, in which case the whole allocation is bound. + pub(in super::super) fn bind( + &mut self, + role: Role, + buffer: &'lease DeviceBuffer<'lease>, + bytes: usize, + at_least: bool, + ) -> Result { + if !std::ptr::eq(self.batch.context, buffer.context) { + return Err(Error::ContextMismatch); + } + if bytes == 0 || (at_least && buffer.bytes < bytes) || (!at_least && buffer.bytes != bytes) + { + return Err(Error::InvalidQwenShape); + } + let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; + handle.validate_projection_extent(buffer.bytes, 4)?; + let status = self.batch.status_handle()?; + if handle.overlaps(buffer.bytes, status, STATUS_BYTES) { + return Err(Error::OutputAliasesInput); + } + self.bindings.bind(role, handle, buffer.bytes)?; + if !self.held.iter().any(|held| std::ptr::eq(*held, buffer)) { + self.held.push(buffer); + } + Ok(handle) + } + pub(in super::super) fn push_kernel( + &mut self, + kernel: Kernel, + geometry: ([u32; 3], [u32; 3]), + args: &[ffi::KernelArg], + ) -> Result<()> { + let function = self.function(kernel)?; + self.commands.push(Command::Kernel { + function, + stream: self.stream, + grid: geometry.0, + block: geometry.1, + args: ffi::GdnPrefillArguments::new(args)?, + }); + Ok(()) + } + /// Complete finite scan of the whole buffer bound to `role`, into the + /// stage's own status word. Stages are scanned strictly in program order. + pub(in super::super) fn scan(&mut self, stage: GdnBatchStage, role: Role) -> Result<()> { + if self.checks != stage.slot() { + return Err(Error::InvalidQwenShape); + } + let (handle, bytes) = self.bindings.get(role)?; + let elements = stage.elements(self.tokens); + if bytes != stage.bytes(self.tokens) { + return Err(Error::InvalidQwenShape); + } + let status = + self.batch + .status_handle()? + .checked_subspan(STATUS_BYTES, stage.slot() * 4, 4)?; + let kernel = if stage.is_half() { + Kernel::FiniteF16 + } else { + Kernel::FiniteF32 + }; + self.push_kernel( + kernel, + linear(elements)?, + &[ + ffi::KernelArg::Pointer(handle), + ffi::KernelArg::Pointer(status), + ffi::KernelArg::U32(u32::try_from(elements).map_err(|_| Error::InvalidQwenShape)?), + ], + )?; + self.checks = stage.slot() + 1; + Ok(()) + } + /// The status word of a stage whose witness a kernel writes itself. + pub(in super::super) fn witness_word(&mut self, stage: GdnBatchStage) -> Result { + if self.checks != stage.slot() || stage != GdnBatchStage::StateSteps { + return Err(Error::InvalidQwenShape); + } + let word = + self.batch + .status_handle()? + .checked_subspan(STATUS_BYTES, stage.slot() * 4, 4)?; + self.checks = stage.slot() + 1; + Ok(word) + } + pub(in super::super) fn handle(&self, role: Role) -> Result { + Ok(self.bindings.get(role)?.0) + } + pub(in super::super) fn buffer_ref(&self, role: Role) -> Result<&'lease DeviceBuffer<'lease>> { + let handle = self.handle(role)?; + self.held + .iter() + .copied() + .find(|buffer| buffer.handle == Some(handle)) + .ok_or(Error::InvalidQwenShape) + } + + // ---------------------------------------------------------------- images + /// Original tail of `gr_mix_kernel`: the FP16 image, the BF16 hi image and + /// (when `mixed_bf_lo` is given) the BF16 lo image of an f32 `mixed` + /// `[tokens][2560]`, then the FP16 image scan. For a producer that already + /// delivers the three images use [`Self::images_supplied`]. + pub fn pack_mixed( + &mut self, + mixed: &'lease DeviceBuffer<'lease>, + mixed_h: &'lease DeviceBuffer<'lease>, + mixed_bf: &'lease DeviceBuffer<'lease>, + mixed_bf_lo: Option<&'lease DeviceBuffer<'lease>>, + ) -> Result<()> { + let result = (|| { + self.ready(Step::Images)?; + let t = self.tokens; + let source = self.bind(Role::Mixed, mixed, t * N * F32, false)?; + let h = self.bind(Role::MixedH, mixed_h, t * N * F16, false)?; + let bf = self.bind(Role::MixedBf, mixed_bf, t * N * F16, false)?; + let lo = match mixed_bf_lo { + Some(buffer) => ffi::KernelArg::Pointer(self.bind( + Role::MixedBfLo, + buffer, + t * N * F16, + false, + )?), + None => ffi::KernelArg::NullPointer, + }; + self.push_kernel( + Kernel::MixedPack, + linear(t * N)?, + &[ + ffi::KernelArg::Pointer(source), + ffi::KernelArg::Pointer(h), + ffi::KernelArg::Pointer(bf), + lo, + ffi::KernelArg::I64(t as i64), + ], + )?; + self.scan(GdnBatchStage::MixedH, Role::MixedH)?; + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } + /// The three images were produced by the caller's own (original) gr_mix. + pub fn images_supplied( + &mut self, + mixed_h: &'lease DeviceBuffer<'lease>, + mixed_bf: &'lease DeviceBuffer<'lease>, + mixed_bf_lo: Option<&'lease DeviceBuffer<'lease>>, + ) -> Result<()> { + let result = (|| { + self.ready(Step::Images)?; + let t = self.tokens; + self.bind(Role::MixedH, mixed_h, t * N * F16, false)?; + self.bind(Role::MixedBf, mixed_bf, t * N * F16, false)?; + if let Some(buffer) = mixed_bf_lo { + self.bind(Role::MixedBfLo, buffer, t * N * F16, false)?; + } + self.scan(GdnBatchStage::MixedH, Role::MixedH)?; + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } + + // ---------------------------------------------------------------- projections + #[allow(clippy::too_many_arguments)] // The fixed operands of one native projection. + pub(in super::super) fn project_native( + &mut self, + format: GdnNativeFormat, + weights: (Role, &'lease DeviceBuffer<'lease>), + scratch: &'lease DeviceBuffer<'lease>, + activation: Role, + output: (Role, &'lease DeviceBuffer<'lease>), + rows: usize, + depth: usize, + output_bytes: usize, + ) -> Result<()> { + let t = self.tokens; + let matrix = format.matrix_bytes(rows, depth)?; + let half_bytes = rows * depth * F16; + let blocks = self.bind(weights.0, weights.1, matrix, false)?; + let scratch_handle = self.bind(Role::Scratch, scratch, half_bytes, true)?; + self.bind(output.0, output.1, output_bytes, false)?; + // The dequantized weights: one thread per 32-value group, 256 per block. + let groups_per_row = depth / 32; + let groups = rows * groups_per_row; + self.push_kernel( + format.kernel(), + linear(groups)?, + &[ + ffi::KernelArg::Pointer(blocks), + ffi::KernelArg::I64((depth / format.block().0 * format.block().1) as i64), + ffi::KernelArg::I64(0), + ffi::KernelArg::I64(rows as i64), + ffi::KernelArg::I64(groups_per_row as i64), + ffi::KernelArg::Pointer(scratch_handle), + ], + )?; + let x = self.buffer_ref(activation)?; + self.commands.push(Command::Gemm { + gemm: self.gemm, + bf16: false, + x, + w: scratch, + y: output.1, + shape: GemmShape { + tokens: t, + rows, + depth, + ldy: rows, + y_offset: 0, + beta: 0.0, + }, + }); + Ok(()) + } +} diff --git a/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_2_2.rs b/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_2_2.rs new file mode 100644 index 00000000..08c97fbd --- /dev/null +++ b/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_2_2.rs @@ -0,0 +1,241 @@ +//! Moved out of the parent module by STRA-338: impl GdnBatchPrefix (2). + +#[allow(unused_imports)] +use super::*; + + + +impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { + /// Native `attn_qkv` projection: dequantize to FP16, `Y[T,10240] = X . W^T` + /// with `X` = the FP16 image of `mixed`; then the QKV scan. + pub fn project_qkv( + &mut self, + format: GdnNativeFormat, + weights: &'lease DeviceBuffer<'lease>, + scratch: &'lease DeviceBuffer<'lease>, + qkv: &'lease DeviceBuffer<'lease>, + ) -> Result<()> { + let result = (|| { + self.ready(Step::Qkv)?; + let bytes = self.tokens * C * F32; + self.project_native( + format, + (Role::QkvW, weights), + scratch, + Role::MixedH, + (Role::Qkv, qkv), + C, + N, + bytes, + )?; + self.scan(GdnBatchStage::Qkv, Role::Qkv)?; + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } + /// Native `attn_gate` (Z) projection, `Y[T,6144]`; then the Z scan. + pub fn project_z( + &mut self, + format: GdnNativeFormat, + weights: &'lease DeviceBuffer<'lease>, + scratch: &'lease DeviceBuffer<'lease>, + z: &'lease DeviceBuffer<'lease>, + ) -> Result<()> { + let result = (|| { + self.ready(Step::Z)?; + let bytes = self.tokens * ZV * F32; + self.project_native( + format, + (Role::ZW, weights), + scratch, + Role::MixedH, + (Role::Z, z), + ZV, + N, + bytes, + )?; + self.scan(GdnBatchStage::Z, Role::Z)?; + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } + /// BF16 `ssm_alpha` then `ssm_beta` into the interleaved `ab` `[T][96]` + /// (`alpha` at column 0, raw `beta` at column 48), each as the original + /// does: the hi image with `beta = 0`, then, when the lo image was given, + /// the lo image accumulated with `beta = 1`. Then the Ab scan. + pub fn project_alpha_beta( + &mut self, + alpha_weights: &'lease DeviceBuffer<'lease>, + beta_weights: &'lease DeviceBuffer<'lease>, + ab: &'lease DeviceBuffer<'lease>, + ) -> Result<()> { + let result = (|| { + self.ready(Step::Ab)?; + let t = self.tokens; + self.bind(Role::AlphaW, alpha_weights, HV * N * F16, false)?; + self.bind(Role::BetaW, beta_weights, HV * N * F16, false)?; + self.bind(Role::Ab, ab, t * 2 * HV * F32, false)?; + let x = self.buffer_ref(Role::MixedBf)?; + let lo = self.buffer_ref(Role::MixedBfLo).ok(); + for (weights, y_offset) in [(alpha_weights, 0), (beta_weights, HV)] { + let shape = |beta| GemmShape { + tokens: t, + rows: HV, + depth: N, + ldy: 2 * HV, + y_offset, + beta, + }; + self.commands.push(Command::Gemm { + gemm: self.gemm, + bf16: true, + x, + w: weights, + y: ab, + shape: shape(0.0), + }); + if let Some(lo) = lo { + self.commands.push(Command::Gemm { + gemm: self.gemm, + bf16: true, + x: lo, + w: weights, + y: ab, + shape: shape(1.0), + }); + } + } + self.scan(GdnBatchStage::Ab, Role::Ab)?; + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } + + // ---------------------------------------------------------------- GDN kernels + /// `gdn_gates`: `gate` and sigmoid `beta` `[T][48]` from `ab`; two scans. + pub fn gates( + &mut self, + dt: &'lease DeviceBuffer<'lease>, + ssm_a: &'lease DeviceBuffer<'lease>, + gate: &'lease DeviceBuffer<'lease>, + beta: &'lease DeviceBuffer<'lease>, + ) -> Result<()> { + let result = (|| { + self.ready(Step::Gates)?; + let t = self.tokens; + let ab = self.handle(Role::Ab)?; + let dt_h = self.bind(Role::Dt, dt, HV * F32, false)?; + let a_h = self.bind(Role::SsmA, ssm_a, HV * F32, false)?; + let gate_h = self.bind(Role::Gate, gate, t * HV * F32, false)?; + let beta_h = self.bind(Role::Beta, beta, t * HV * F32, false)?; + self.push_kernel( + Kernel::Gates, + linear(t * HV)?, + &[ + ffi::KernelArg::Pointer(ab), + ffi::KernelArg::Pointer(dt_h), + ffi::KernelArg::Pointer(a_h), + ffi::KernelArg::Pointer(gate_h), + ffi::KernelArg::Pointer(beta_h), + ffi::KernelArg::I64(t as i64), + ], + )?; + self.scan(GdnBatchStage::Gate, Role::Gate)?; + self.scan(GdnBatchStage::Beta, Role::Beta)?; + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } + /// `gdn_conv`: the 4-tap causal convolution + SiLU over the chunk into `h` + /// `[T][10240]`, and the history after the chunk into `next_history` + /// (`history` stays untouched). Chunks of at most 64 rows use the serial + /// walk, longer ones the tiled kernel plus the history kernel, exactly as + /// the original launcher selects. + pub fn conv( + &mut self, + history: &'lease DeviceBuffer<'lease>, + conv_weights: &'lease DeviceBuffer<'lease>, + next_history: &'lease DeviceBuffer<'lease>, + h: &'lease DeviceBuffer<'lease>, + ) -> Result<()> { + let result = (|| { + self.ready(Step::Conv)?; + let t = self.tokens; + let qkv = self.handle(Role::Qkv)?; + let hist = self.bind(Role::History, history, HISTORY_WORDS * F32, false)?; + let w = self.bind(Role::ConvW, conv_weights, C * 4 * F32, false)?; + let next = self.bind(Role::NextHistory, next_history, HISTORY_WORDS * F32, false)?; + let h_h = self.bind(Role::H, h, t * C * F32, false)?; + let t_arg = ffi::KernelArg::I64(t as i64); + if t <= CONV_TILE { + self.push_kernel( + Kernel::Conv, + ([(C / 128) as u32, 1, 1], [128, 1, 1]), + &[ + ffi::KernelArg::Pointer(hist), + ffi::KernelArg::Pointer(next), + ffi::KernelArg::Pointer(qkv), + ffi::KernelArg::Pointer(w), + ffi::KernelArg::Pointer(h_h), + t_arg, + ], + )?; + } else { + self.push_kernel( + Kernel::ConvTiled, + ( + [(C / 128) as u32, t.div_ceil(CONV_TILE) as u32, 1], + [128, 1, 1], + ), + &[ + ffi::KernelArg::Pointer(hist), + ffi::KernelArg::Pointer(qkv), + ffi::KernelArg::Pointer(w), + ffi::KernelArg::Pointer(h_h), + t_arg, + ], + )?; + self.push_kernel( + Kernel::ConvHist, + ([(C / 128) as u32, 1, 1], [128, 1, 1]), + &[ + ffi::KernelArg::Pointer(next), + ffi::KernelArg::Pointer(hist), + ffi::KernelArg::Pointer(qkv), + t_arg, + ], + )?; + } + self.scan(GdnBatchStage::ConvH, Role::H)?; + self.scan(GdnBatchStage::NextHistory, Role::NextHistory)?; + self.fetch = Some(next); + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } + /// `gdn_l2`: in-place L2 normalization of the 32 Q/K heads of every row of + /// `h` (the original's `rsqrtf(ss + eps)` with `eps = 1e-6`); then the scan. + pub fn l2(&mut self) -> Result<()> { + let result = (|| { + self.ready(Step::L2)?; + let h = self.handle(Role::H)?; + self.push_kernel( + Kernel::L2, + ([32, self.tokens as u32, 1], [128, 1, 1]), + &[ + ffi::KernelArg::Pointer(h), + ffi::KernelArg::F32(GDN_BATCH_EPSILON), + ], + )?; + self.scan(GdnBatchStage::Qk, Role::H)?; + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } +} diff --git a/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_3.rs b/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_3.rs new file mode 100644 index 00000000..e5d5ee22 --- /dev/null +++ b/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_3.rs @@ -0,0 +1,214 @@ +//! Moved out of the parent module by STRA-338: impl GdnBatchPrefix (3). + +#[allow(unused_imports)] +use super::*; + + + +impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { + /// `gdn_rec_cols_pipe`: the whole-chunk recurrence. `state_in` is the + /// immutable prior state `[128][48][128]`, `state_out` the separate final + /// state; `y` receives the un-normalized readout `oc` `[T][6144]`. Then the + /// per-step state witness (written by the kernel) and then the NextState and + /// Readout scans (earliest refusal first). + pub fn recurrence( + &mut self, + state_in: &'lease DeviceBuffer<'lease>, + state_out: &'lease DeviceBuffer<'lease>, + y: &'lease DeviceBuffer<'lease>, + ) -> Result<()> { + let result = (|| { + self.ready(Step::Recurrence)?; + let t = self.tokens; + let h = self.handle(Role::H)?; + let gate = self.handle(Role::Gate)?; + let beta = self.handle(Role::Beta)?; + let s_in = self.bind(Role::StateIn, state_in, STATE_WORDS * F32, false)?; + let s_out = self.bind(Role::StateOut, state_out, STATE_WORDS * F32, false)?; + let y_h = self.bind(Role::Y, y, t * ZV * F32, false)?; + let witness = self.witness_word(GdnBatchStage::StateSteps)?; + self.push_kernel( + Kernel::RecColsPipe, + ([(HV * (S / 32)) as u32, 1, 1], [32, 4, 1]), + &[ + ffi::KernelArg::Pointer(s_in), + ffi::KernelArg::Pointer(s_out), + ffi::KernelArg::Pointer(h), + ffi::KernelArg::Pointer(gate), + ffi::KernelArg::Pointer(beta), + ffi::KernelArg::Pointer(y_h), + ffi::KernelArg::I64(t as i64), + ffi::KernelArg::Pointer(witness), + ], + )?; + self.scan(GdnBatchStage::NextState, Role::StateOut)?; + self.scan(GdnBatchStage::Readout, Role::Y)?; + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } + /// `gdn_out_norm`: in place on `y` (f32) plus the half image `y16` + /// (`hf(v)`), gated by `z`; then the Y and Y16 scans. + pub fn out_norm( + &mut self, + gamma: &'lease DeviceBuffer<'lease>, + y16: &'lease DeviceBuffer<'lease>, + ) -> Result<()> { + let result = (|| { + self.ready(Step::OutNorm)?; + let t = self.tokens; + let z = self.handle(Role::Z)?; + let y = self.handle(Role::Y)?; + let gamma_h = self.bind(Role::Gamma, gamma, S * F32, false)?; + let y16_h = self.bind(Role::Y16, y16, t * ZV * F16, false)?; + self.push_kernel( + Kernel::OutNorm, + ([t as u32, HV as u32, 1], [128, 1, 1]), + &[ + ffi::KernelArg::Pointer(z), + ffi::KernelArg::Pointer(gamma_h), + ffi::KernelArg::F32(GDN_BATCH_EPSILON), + ffi::KernelArg::Pointer(y), + ffi::KernelArg::Pointer(y16_h), + ], + )?; + self.scan(GdnBatchStage::Y, Role::Y)?; + self.scan(GdnBatchStage::Y16, Role::Y16)?; + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } + /// Native `ssm_out` projection from the FP16 `y16`: `Y[T,2560] = y16 . W^T` + /// into `bo`; then the Bo scan. + pub fn project_out( + &mut self, + format: GdnNativeFormat, + weights: &'lease DeviceBuffer<'lease>, + scratch: &'lease DeviceBuffer<'lease>, + bo: &'lease DeviceBuffer<'lease>, + ) -> Result<()> { + let result = (|| { + self.ready(Step::Out)?; + let bytes = self.tokens * N * F32; + self.project_native( + format, + (Role::OutW, weights), + scratch, + Role::Y16, + (Role::Bo, bo), + N, + ZV, + bytes, + )?; + self.scan(GdnBatchStage::Bo, Role::Bo)?; + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } + + /// Drain the complete admitted prefix once. Earlier numerical refusal beats + /// a later admission error; an admission error with a clean prefix is the + /// returned error. No usable history is returned on numerical refusal. + pub fn finish(mut self) -> Result { + let complete = self.step == Step::Done && self.fetch.is_some(); + if !complete && self.refusal.is_none() { + self.refusal = Some(Error::InvalidQwenShape); + } + let drained = self.drain(complete)?; + if drained.refusal.is_none() + && let Some(error) = drained.deferred + { + return Err(error); + } + Ok(GdnBatchCompletion { + refusal: drained.refusal, + next_history: if drained.refusal.is_none() { + drained.next_history + } else { + None + }, + }) + } + + pub(in super::super) fn drain(mut self, fetch: bool) -> Result { + let status = self.batch.status_handle()?; + let mut statuses = staging(STATUS_BYTES)?; + let write_fetch = fetch && self.refusal.is_none(); + let mut fetched = staging(if write_fetch { HISTORY_WORDS * F32 } else { 0 })?; + if self.commands.len() > 1 { + let context = self.batch.context; + let guard = context.enter().inspect_err(|_| { + self.batch.failed = true; + context.poisoned.set(true); + })?; + // The caller's inputs arrived by synchronous pageable H2D, which may + // return after host staging only. The program runs on the adapter's + // dedicated NON-BLOCKING stream, which the legacy default stream does + // not order against: one real context synchronization separates them. + let mut operation = context.driver.api.synchronize(); + if operation.is_ok() { + for command in &mut self.commands { + operation = command.launch(context); + if operation.is_err() { + break; + } + } + } + // Every program kernel and GEMM is on the non-blocking stream: the + // D2H below is only ordered after them by this completion fence. + let sync = context.driver.api.synchronize(); + if operation.is_ok() && sync.is_ok() { + operation = context.driver.api.copy_to(status, &mut statuses); + } + if operation.is_ok() && sync.is_ok() && write_fetch { + let source = self.fetch.ok_or(Error::InvalidQwenShape)?; + operation = context.driver.api.copy_to(source, &mut fetched); + } + let pop = guard.finish(); + if operation.is_err() || sync.is_err() || pop.is_err() { + self.batch.failed = true; + context.poisoned.set(true); + } + if sync.is_err() || pop.is_err() { + // Completion is uncertain: retain every actual argument/staging + // owner and every borrowed buffer; Context poison forbids reuse. + std::mem::forget((self.commands, self.held, statuses, fetched)); + return combine(combine(operation, sync), pop) + .map(|()| unreachable!("uncertain GDN batch drain")); + } + combine(combine(operation, sync), pop)?; + } + let refusal = match decode_statuses(&statuses, self.checks) { + Ok(refusal) => refusal, + Err(error) => { + self.batch.failed = true; + self.batch.context.poisoned.set(true); + return Err(error); + } + }; + let next_history = if write_fetch && refusal.is_none() { + let mut values = Vec::new(); + values + .try_reserve_exact(HISTORY_WORDS) + .map_err(|_| Error::HostAllocation)?; + values.extend( + fetched + .as_chunks::<4>() + .0 + .iter() + .map(|word| f32::from_le_bytes(*word)), + ); + Some(values.into_boxed_slice()) + } else { + None + }; + Ok(Drained { + refusal, + deferred: self.refusal, + next_history, + }) + } +} diff --git a/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice.rs b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice.rs index 54a0fdaa..3a1c7522 100644 --- a/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice.rs +++ b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice.rs @@ -3,734 +3,9 @@ #[allow(unused_imports)] use super::*; -impl<'ctx> OriginalGdnPromptDevice<'ctx> { - pub fn device_bytes(capacity: usize) -> Result { - if !(1..=8192).contains(&capacity) { - return Err(Error::InvalidQwenShape); - } - Ok(SCRATCH + 2 * HISTORY + STATUS_BYTES) - } - pub(super) fn new( - context: &'ctx Context<'ctx>, - capacity: usize, - profile: crate::GrNativeProfile, - ) -> Result { - let required = Self::device_bytes(capacity)? - .checked_add(RESERVE) - .ok_or(Error::BudgetExceeded)?; - if context.is_poisoned() { - return Err(Error::ContextPoisoned); - } - if context - .allocated_bytes() - .checked_add(required) - .is_none_or(|x| x > context.budget_bytes()) - || context.memory_info()?.0 < required - { - return Err(Error::BudgetExceeded); - } - let mut owner = Self { - context, - capacity, - profile, - batch: None, - scratch: None, - history: [None, None], - stage: None, - failed: false, - }; - let operation = (|| -> Result<()> { - owner.batch = Some(context.gdn_prefill_batch_for_prompt(capacity)?); - owner.scratch = Some(context.allocate(SCRATCH)?); - for slot in &mut owner.history { - *slot = Some(context.allocate(HISTORY)?) - } - if context.memory_info()?.0 < RESERVE { - return Err(Error::BudgetExceeded); - } - Ok(()) - })(); - if let Err(e) = operation { - let _ = owner.close(); - return Err(e); - } - Ok(owner) - } - pub fn is_failed(&self) -> bool { - self.failed - || self.context.is_poisoned() - || self.batch.as_ref().is_none_or(GdnPrefillBatch::is_failed) - } - pub fn allocated_bytes(&self) -> usize { - self.batch - .as_ref() - .map_or(0, GdnPrefillBatch::allocated_bytes) - + self.scratch.as_ref().map_or(0, DeviceBuffer::len) - + self - .history - .iter() - .flatten() - .map(DeviceBuffer::len) - .sum::() - } - /// Consumes the actual affine GR read. `state` is untouched prior; only - /// `next_state` is written. Runtime alone may adopt it after this clean drain. - #[allow(clippy::too_many_arguments)] - pub fn produce<'arena, 'loan>( - &mut self, - read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, - weights: OriginalGdnPromptWeights<'_, 'ctx>, - state: &DeviceBuffer<'ctx>, - next_state: &DeviceBuffer<'ctx>, - history: &[f32], - ) -> Result<(OriginalDeviceBlock<'arena, 'loan, 'ctx>, Box<[f32]>)> { - let lease = read.lease(); - let t = read.rows(); - if self.is_failed() || lease.is_failed() { - return Err(Error::ContextPoisoned); - } - if !read.context_matches(self.context) { - return Err(Error::ContextMismatch); - } - if !(1..=self.capacity).contains(&t) || history.len() != HISTORY_WORDS { - return Err(Error::InvalidQwenShape); - } - if history.iter().any(|x| !x.is_finite()) { - return Err(Error::NonFiniteMmqOutput("GDN prior history")); - } - workspace.validate_context(self.context)?; - let batch = self.batch.as_ref().ok_or(Error::ContextPoisoned)?; - let status = batch.status_handle()?; - let mut bindings = Bindings::new(); - let mut buffer = - |role: Role, b: &DeviceBuffer<'_>, bytes: usize| -> Result { - if !std::ptr::eq(b.context, self.context) { - return Err(Error::ContextMismatch); - } - if b.len() != bytes { - return Err(Error::InvalidQwenShape); - } - let h = b.handle.ok_or(Error::ContextPoisoned)?; - h.validate_projection_extent(bytes, 4)?; - workspace.reject_alias(h, bytes)?; - if h.overlaps(bytes, status, STATUS_BYTES) { - return Err(Error::OutputAliasesInput); - } - bindings.bind(role, h, bytes)?; - Ok(h) - }; - let scratch = buffer( - Role::Scratch, - self.scratch.as_ref().ok_or(Error::ContextPoisoned)?, - SCRATCH, - )?; - let hin = buffer( - Role::History, - self.history[0].as_ref().ok_or(Error::ContextPoisoned)?, - HISTORY, - )?; - let hout = buffer( - Role::NextHistory, - self.history[1].as_ref().ok_or(Error::ContextPoisoned)?, - HISTORY, - )?; - let sin = buffer(Role::StateIn, state, STATE_WORDS * 4)?; - let sout = buffer(Role::StateOut, next_state, STATE_WORDS * 4)?; - let mut w = [sin; 5]; - for (i, role, n, k) in [ - (0, Role::QkvW, C, N), - (1, Role::ZW, ZV, N), - (2, Role::OutW, N, ZV), - (3, Role::AlphaW, HV, N), - (4, Role::BetaW, HV, N), - ] { - let bytes = if i < 3 { - weights.formats[i].matrix_bytes(n, k)? - } else { - n * k * 2 - }; - w[i] = buffer(role, weights.matrices[i], bytes)?; - } - let mut a = [sin; 4]; - for (i, role, n) in [ - (0, Role::ConvW, C * 4 * 4), - (1, Role::Dt, HV * 4), - (2, Role::SsmA, HV * 4), - (3, Role::Gamma, S * 4), - ] { - a[i] = buffer(role, weights.aux[i], n)?; - } - drop(buffer); - let mut carved = |role: Role, - phase: Option<(&str, usize)>, - common: Option<(OriginalPromptSpan, usize)>| - -> Result { - let (h, capacity, bytes) = if let Some((name, width)) = phase { - let (h, n) = lease.span(PrefillPhase::Gdn, name)?; - (h, n, t * width) - } else { - let (r, width) = common.ok_or(Error::InvalidQwenShape)?; - let (h, n) = lease.common_span(r)?; - (h, n, t * width) - }; - let h = h.checked_subspan(capacity, 0, bytes)?; - h.validate_projection_extent(bytes, 2)?; - workspace.reject_alias(h, bytes)?; - if h.overlaps(bytes, status, STATUS_BYTES) { - return Err(Error::OutputAliasesInput); - } - bindings.bind(role, h, bytes)?; - Ok(h) - }; - let mixed = carved( - Role::MixedH, - None, - Some((OriginalPromptSpan::MixedHalf, 5120)), - )?; - let high = carved( - Role::MixedBf, - None, - Some((OriginalPromptSpan::MixedHigh, 5120)), - )?; - let lower = if self.profile == crate::GrNativeProfile::HighAndLow { - Some(carved( - Role::MixedBfLo, - None, - Some((OriginalPromptSpan::MixedLow, 5120)), - )?) - } else { - None - }; - let qkv = carved(Role::Qkv, Some(("qkv", C * 4)), None)?; - let z = carved(Role::Z, Some(("z", ZV * 4)), None)?; - let ab = carved(Role::Ab, Some(("ab", HV * 8)), None)?; - let gate = carved(Role::Gate, Some(("gate", HV * 4)), None)?; - let beta = carved(Role::Beta, Some(("beta", HV * 4)), None)?; - let h = carved(Role::H, Some(("hbuf", C * 4)), None)?; - let y = carved(Role::Y, Some(("y", ZV * 4)), None)?; - let yh = carved(Role::Y16, Some(("y_h", ZV * 2)), None)?; - let bo = carved(Role::Bo, None, Some((OriginalPromptSpan::Block, N * 4)))?; - drop(carved); - // Every owner/alias/shape admission above precedes the first write. - let mut commands = Vec::new(); - commands - .try_reserve_exact(48) - .map_err(|_| Error::HostAllocation)?; - let funcs = batch.functions.as_ref().ok_or(Error::ContextPoisoned)?; - let mut push = |kernel: Kernel, - geometry: ([u32; 3], [u32; 3]), - args: &[ffi::KernelArg]| - -> Result<()> { - commands.push(DeviceCommand::Kernel { - function: funcs.get(kernel), - grid: geometry.0, - block: geometry.1, - args: ffi::GdnPrefillArguments::new(args)?, - }); - Ok(()) - }; - push( - Kernel::Zero, - linear(SLOTS)?, - &[ - ffi::KernelArg::Pointer(status), - ffi::KernelArg::U32(SLOTS as u32), - ], - )?; - drop(push); - let add_kernel = |commands: &mut Vec, - kernel: Kernel, - geometry: ([u32; 3], [u32; 3]), - args: &[ffi::KernelArg]| - -> Result<()> { - commands.push(DeviceCommand::Kernel { - function: funcs.get(kernel), - grid: geometry.0, - block: geometry.1, - args: ffi::GdnPrefillArguments::new(args)?, - }); - Ok(()) - }; - let scan = |commands: &mut Vec, - stage: GdnBatchStage, - data: ffi::BufferHandle| - -> Result<()> { - let word = status.checked_subspan(STATUS_BYTES, stage.slot() * 4, 4)?; - add_kernel( - commands, - if stage.is_half() { - Kernel::FiniteF16 - } else { - Kernel::FiniteF32 - }, - linear(stage.elements(t))?, - &[ - ffi::KernelArg::Pointer(data), - ffi::KernelArg::Pointer(word), - ffi::KernelArg::U32(stage.elements(t) as u32), - ], - ) - }; - let fast_dequant = crate::prefill_stage::fast_dequant(); - let native = |commands: &mut Vec, - format: GdnNativeFormat, - input, - weight, - output, - n: usize, - k: usize| - -> Result<()> { - if fast_dequant { - let total = n * k; - commands.push(DeviceCommand::Stage { - index: crate::prefill_stage::DEQUANT_FIRST - + match format { - GdnNativeFormat::Q8_0 => 0, - GdnNativeFormat::Q4K => 1, - GdnNativeFormat::Q5K => 2, - GdnNativeFormat::Q6K => 3, - GdnNativeFormat::Iq4Nl => 4, - GdnNativeFormat::Iq4Xs => 5, - }, - grid: u32::try_from(total.div_ceil(256)).map_err(|_| Error::InvalidQwenShape)?, - block: 256, - args: KernelArguments::new(vec![ - A::Address(weight), - A::I64((k / format.block().0 * format.block().1) as i64), - A::I64(total as i64), - A::I64((k / 32) as i64), - A::Address(scratch), - ]), - }); - } else { - add_kernel( - commands, - format.kernel(), - linear(n * (k / 32))?, - &[ - ffi::KernelArg::Pointer(weight), - ffi::KernelArg::I64((k / format.block().0 * format.block().1) as i64), - ffi::KernelArg::I64(0), - ffi::KernelArg::I64(n as i64), - ffi::KernelArg::I64((k / 32) as i64), - ffi::KernelArg::Pointer(scratch), - ], - )?; - } - commands.push(DeviceCommand::Gemm { - bf16: false, - x: input, - w: scratch, - y: output, - n: n as i32, - k: k as i32, - ldy: n as i32, - offset: 0, - beta: 0., - }); - Ok(()) - }; - scan(&mut commands, GdnBatchStage::MixedH, mixed)?; - // t > 64 with fused guards: the guards of qkv, the convolution output, the normalised q/k, z, the readout, y and its - // FP16 image ride on the kernels that read or write those tensors (same status words) - let fused = crate::prefill_stage::fused_scans() && t > 64; - let word = |stage: GdnBatchStage| status.checked_subspan(STATUS_BYTES, stage.slot() * 4, 4); - native(&mut commands, weights.formats[0], mixed, w[0], qkv, C, N)?; - if !fused { - scan(&mut commands, GdnBatchStage::Qkv, qkv)?; - } - native(&mut commands, weights.formats[1], mixed, w[1], z, ZV, N)?; - if !fused { - scan(&mut commands, GdnBatchStage::Z, z)?; - } - for (i, offset) in [(3, 0), (4, HV)] { - commands.push(DeviceCommand::Gemm { - bf16: true, - x: high, - w: w[i], - y: ab, - n: HV as i32, - k: N as i32, - ldy: 96, - offset, - beta: 0., - }); - if let Some(lo) = lower { - commands.push(DeviceCommand::Gemm { - bf16: true, - x: lo, - w: w[i], - y: ab, - n: HV as i32, - k: N as i32, - ldy: 96, - offset, - beta: 1., - }) - } - } - scan(&mut commands, GdnBatchStage::Ab, ab)?; - add_kernel( - &mut commands, - Kernel::Gates, - linear(t * HV)?, - &[ - ffi::KernelArg::Pointer(ab), - ffi::KernelArg::Pointer(a[1]), - ffi::KernelArg::Pointer(a[2]), - ffi::KernelArg::Pointer(gate), - ffi::KernelArg::Pointer(beta), - ffi::KernelArg::I64(t as i64), - ], - )?; - scan(&mut commands, GdnBatchStage::Gate, gate)?; - scan(&mut commands, GdnBatchStage::Beta, beta)?; - if t <= 64 { - add_kernel( - &mut commands, - Kernel::Conv, - ([80, 1, 1], [128, 1, 1]), - &[ - ffi::KernelArg::Pointer(hin), - ffi::KernelArg::Pointer(hout), - ffi::KernelArg::Pointer(qkv), - ffi::KernelArg::Pointer(a[0]), - ffi::KernelArg::Pointer(h), - ffi::KernelArg::I64(t as i64), - ], - )? - } else { - if fused { - commands.push(DeviceCommand::Stage { - index: crate::prefill_stage::GDN_CONV_TILED, - grid: 40 * t.div_ceil(64) as u32, - block: 256, - args: KernelArguments::new(vec![ - A::Address(hin), - A::Address(qkv), - A::Address(a[0]), - A::Address(h), - A::I64(t as i64), - A::Address(word(GdnBatchStage::Qkv)?), - A::Address(word(GdnBatchStage::ConvH)?), - ]), - }); - } else { - add_kernel( - &mut commands, - Kernel::ConvTiled, - ([80, t.div_ceil(64) as u32, 1], [128, 1, 1]), - &[ - ffi::KernelArg::Pointer(hin), - ffi::KernelArg::Pointer(qkv), - ffi::KernelArg::Pointer(a[0]), - ffi::KernelArg::Pointer(h), - ffi::KernelArg::I64(t as i64), - ], - )?; - } - add_kernel( - &mut commands, - Kernel::ConvHist, - ([80, 1, 1], [128, 1, 1]), - &[ - ffi::KernelArg::Pointer(hout), - ffi::KernelArg::Pointer(hin), - ffi::KernelArg::Pointer(qkv), - ffi::KernelArg::I64(t as i64), - ], - )?; - } - if !fused { - scan(&mut commands, GdnBatchStage::ConvH, h)?; - } - scan(&mut commands, GdnBatchStage::NextHistory, hout)?; - if fused { - commands.push(DeviceCommand::Stage { - index: crate::prefill_stage::GDN_L2, - grid: (32 * t).div_ceil(2) as u32, - block: 256, - args: KernelArguments::new(vec![ - A::Address(h), - A::F32(GDN_BATCH_EPSILON), - A::I64(t as i64), - A::Address(word(GdnBatchStage::Qk)?), - ]), - }); - } else { - add_kernel( - &mut commands, - Kernel::L2, - ([32, t as u32, 1], [128, 1, 1]), - &[ - ffi::KernelArg::Pointer(h), - ffi::KernelArg::F32(GDN_BATCH_EPSILON), - ], - )?; - scan(&mut commands, GdnBatchStage::Qk, h)?; - } - let witness = - status.checked_subspan(STATUS_BYTES, GdnBatchStage::StateSteps.slot() * 4, 4)?; - if crate::prefill_stage::fast_rec() || crate::prefill_stage::gdn_kh_usable(self.context) { - let kh = !crate::prefill_stage::fast_rec(); - commands.push(DeviceCommand::Stage { - index: if kh { crate::prefill_stage::GDN_REC_KH } else { crate::prefill_stage::GDN_REC }, - grid: if kh { 64 } else { 192 }, - block: 128, - args: KernelArguments::new(vec![ - A::Address(sin), - A::Address(sout), - A::Address(h), - A::Address(gate), - A::Address(beta), - A::Address(y), - A::I64(t as i64), - A::Address(witness), - ]), - }); - } else { - add_kernel( - &mut commands, - Kernel::RecColsPipe, - ([192, 1, 1], [32, 4, 1]), - &[ - ffi::KernelArg::Pointer(sin), - ffi::KernelArg::Pointer(sout), - ffi::KernelArg::Pointer(h), - ffi::KernelArg::Pointer(gate), - ffi::KernelArg::Pointer(beta), - ffi::KernelArg::Pointer(y), - ffi::KernelArg::I64(t as i64), - ffi::KernelArg::Pointer(witness), - ], - )?; - } - scan(&mut commands, GdnBatchStage::NextState, sout)?; - if fused { - commands.push(DeviceCommand::Stage { - index: if crate::prefill_stage::gdn_nostore() { crate::prefill_stage::GDN_OUT_NORM_Y16 } else { crate::prefill_stage::GDN_OUT_NORM }, - grid: (48 * t).div_ceil(2) as u32, - block: 256, - args: KernelArguments::new(vec![ - A::Address(z), - A::Address(a[3]), - A::F32(GDN_BATCH_EPSILON), - A::Address(y), - A::Address(yh), - A::I64(t as i64), - A::Address(word(GdnBatchStage::Z)?), - A::Address(word(GdnBatchStage::Readout)?), - A::Address(word(GdnBatchStage::Y)?), - A::Address(word(GdnBatchStage::Y16)?), - ]), - }); - } else { - scan(&mut commands, GdnBatchStage::Readout, y)?; - add_kernel( - &mut commands, - Kernel::OutNorm, - ([t as u32, 48, 1], [128, 1, 1]), - &[ - ffi::KernelArg::Pointer(z), - ffi::KernelArg::Pointer(a[3]), - ffi::KernelArg::F32(GDN_BATCH_EPSILON), - ffi::KernelArg::Pointer(y), - ffi::KernelArg::Pointer(yh), - ], - )?; - scan(&mut commands, GdnBatchStage::Y, y)?; - scan(&mut commands, GdnBatchStage::Y16, yh)?; - } - native(&mut commands, weights.formats[2], yh, w[2], bo, N, ZV)?; - scan(&mut commands, GdnBatchStage::Bo, bo)?; - let mut history_bytes = staging(HISTORY)?; - for (x, b) in history.iter().zip(history_bytes.as_chunks_mut::<4>().0) { - b.copy_from_slice(&x.to_le_bytes()) - } - let mut flags = staging(STATUS_BYTES)?; - let mut final_history = staging(HISTORY)?; - let mut values = Vec::new(); - values - .try_reserve_exact(HISTORY_WORDS) - .map_err(|_| Error::HostAllocation)?; - let context = self.context; - let blas = workspace.blas()?; - let guard = match context.enter() { - Ok(g) => g, - Err(e) => { - self.failed = true; - context.poison(); - context.retain_driver(); - return Err(e); - } - }; - if self.stage.is_none() { - match KernelModule::load(crate::prefill_stage::PTX, crate::prefill_stage::ENTRIES) { - Ok(m) => self.stage = Some(m), - Err(e) => { - let pop = guard.finish(); - self.failed = true; - return combine(Err(e), pop).map(|()| unreachable!("stage module")); - } - } - } - let timed = crate::command_profile::enabled(); - let started = std::time::Instant::now(); - let mut operation = context - .driver - .api - .copy_from(hin, &history_bytes) - .and_then(|()| context.driver.api.synchronize()); - if timed { - crate::command_profile::add("gdn", 0, "history upload", started.elapsed()); - } - for (index, cmd) in commands.iter_mut().enumerate() { - if operation.is_err() { - break; - } - let started = std::time::Instant::now(); - let label = match cmd { DeviceCommand::Kernel { .. } => "kernel", DeviceCommand::Gemm { .. } => "gemm", DeviceCommand::Stage { .. } => "stage" }; - operation = match cmd { - DeviceCommand::Kernel { - function, - grid, - block, - args, - } => context.driver.api.launch_gdn_native( - *function, - GdnStream::from_raw(blas.stream()), - *grid, - *block, - args, - ), - DeviceCommand::Gemm { - bf16, - x, - w, - y, - n, - k, - ldy, - offset, - beta, - } => blas.gemm_gdn(*bf16, *x, *w, *y, t as i32, *n, *k, *ldy, *offset, beta), - DeviceCommand::Stage { - index, - grid, - block, - args, - } => match self.stage.as_ref() { - Some(module) => module.launch(*index, *grid, *block, blas.stream(), args), - None => Err(Error::ContextPoisoned), - }, - }; - if timed && operation.is_ok() { - operation = blas.synchronize(); - crate::command_profile::add("gdn", index + 1, label, started.elapsed()); - } - } - let started = std::time::Instant::now(); - let sync = blas.synchronize(); - if operation.is_ok() && sync.is_ok() { - operation = context - .driver - .api - .copy_to(status, &mut flags) - .and_then(|()| context.driver.api.copy_to(hout, &mut final_history)) - } - let all = context.driver.api.synchronize(); - if timed { - crate::command_profile::add("gdn", 999, "drain+readback", started.elapsed()); - } - let pop = guard.finish(); - let result = combine(combine(combine(operation, sync), all), pop); - if result.is_err() { - // A failed drain has no trustworthy completion boundary. Retain the - // command and host buffers before returning, so none can be freed - // while driver work may still reference them. - self.failed = true; - context.poison(); - context.retain_driver(); - std::mem::forget((commands, history_bytes, flags, final_history)); - workspace.mark_failed(); - return result.map(|()| unreachable!("failed GDN drain")); - } - let refusal = match decode_statuses(&flags, SLOTS) { - Ok(r) => r, - Err(e) => { - self.failed = true; - context.poison(); - context.retain_driver(); - return Err(e); - } - }; - if let Some(stage) = refusal { - return Err(Error::NonFiniteMmqOutput(match stage { - GdnBatchStage::Bo => "GDN block", - _ => "GDN prompt stage", - })); - } - values.extend( - final_history - .as_chunks::<4>() - .0 - .iter() - .map(|x| f32::from_le_bytes(*x)), - ); - if values.iter().any(|x| !x.is_finite()) { - return Err(Error::NonFiniteMmqOutput("GDN final history")); - } - Ok((read.from_completed_block(), values.into_boxed_slice())) - } - pub fn close(mut self) -> Result<()> { - self.close_inner() - } - pub(super) fn close_inner(&mut self) -> Result<()> { - self.failed = true; - let mut result = Ok(()); - for b in self - .history - .iter_mut() - .filter_map(Option::take) - .chain(self.scratch.take()) - { - let r = if self.context.is_poisoned() { - std::mem::forget(b); - Err(Error::ContextPoisoned) - } else { - b.release() - }; - result = combine(result, r); - } - if let Some(m) = self.stage.take() { - let r = if self.context.is_poisoned() { - std::mem::forget(m); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(g) => combine(m.close(), g.finish()), - Err(e) => { - std::mem::forget(m); - Err(e) - } - } - }; - result = combine(result, r); - } - if let Some(b) = self.batch.take() { - let r = if self.context.is_poisoned() { - std::mem::forget(b); - Err(Error::ContextPoisoned) - } else { - b.close() - }; - result = combine(result, r); - } - if result.is_err() { - self.context.poison(); - self.context.retain_driver() - } - result - } -} +#[path = "impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2.rs"] +mod impl_originalgdnpromptdevice_2; +#[path = "impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2_2.rs"] +mod impl_originalgdnpromptdevice_2_2; +#[path = "impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_3.rs"] +mod impl_originalgdnpromptdevice_3; diff --git a/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2.rs b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2.rs new file mode 100644 index 00000000..89ffc428 --- /dev/null +++ b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2.rs @@ -0,0 +1,77 @@ +//! Moved out of the parent module by STRA-338: impl OriginalGdnPromptDevice. + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalGdnPromptDevice<'ctx> { + pub fn device_bytes(capacity: usize) -> Result { + if !(1..=8192).contains(&capacity) { + return Err(Error::InvalidQwenShape); + } + Ok(SCRATCH + 2 * HISTORY + STATUS_BYTES) + } + pub(in super::super) fn new( + context: &'ctx Context<'ctx>, + capacity: usize, + profile: crate::GrNativeProfile, + ) -> Result { + let required = Self::device_bytes(capacity)? + .checked_add(RESERVE) + .ok_or(Error::BudgetExceeded)?; + if context.is_poisoned() { + return Err(Error::ContextPoisoned); + } + if context + .allocated_bytes() + .checked_add(required) + .is_none_or(|x| x > context.budget_bytes()) + || context.memory_info()?.0 < required + { + return Err(Error::BudgetExceeded); + } + let mut owner = Self { + context, + capacity, + profile, + batch: None, + scratch: None, + history: [None, None], + stage: None, + failed: false, + }; + let operation = (|| -> Result<()> { + owner.batch = Some(context.gdn_prefill_batch_for_prompt(capacity)?); + owner.scratch = Some(context.allocate(SCRATCH)?); + for slot in &mut owner.history { + *slot = Some(context.allocate(HISTORY)?) + } + if context.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + Ok(()) + })(); + if let Err(e) = operation { + let _ = owner.close(); + return Err(e); + } + Ok(owner) + } + pub fn is_failed(&self) -> bool { + self.failed + || self.context.is_poisoned() + || self.batch.as_ref().is_none_or(GdnPrefillBatch::is_failed) + } + pub fn allocated_bytes(&self) -> usize { + self.batch + .as_ref() + .map_or(0, GdnPrefillBatch::allocated_bytes) + + self.scratch.as_ref().map_or(0, DeviceBuffer::len) + + self + .history + .iter() + .flatten() + .map(DeviceBuffer::len) + .sum::() + } +} diff --git a/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2_2.rs b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2_2.rs new file mode 100644 index 00000000..61bad2b9 --- /dev/null +++ b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2_2.rs @@ -0,0 +1,618 @@ +//! Moved out of the parent module by STRA-338: impl OriginalGdnPromptDevice (2). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalGdnPromptDevice<'ctx> { + /// Consumes the actual affine GR read. `state` is untouched prior; only + /// `next_state` is written. Runtime alone may adopt it after this clean drain. + #[allow(clippy::too_many_arguments)] + pub fn produce<'arena, 'loan>( + &mut self, + read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + weights: OriginalGdnPromptWeights<'_, 'ctx>, + state: &DeviceBuffer<'ctx>, + next_state: &DeviceBuffer<'ctx>, + history: &[f32], + ) -> Result<(OriginalDeviceBlock<'arena, 'loan, 'ctx>, Box<[f32]>)> { + let lease = read.lease(); + let t = read.rows(); + if self.is_failed() || lease.is_failed() { + return Err(Error::ContextPoisoned); + } + if !read.context_matches(self.context) { + return Err(Error::ContextMismatch); + } + if !(1..=self.capacity).contains(&t) || history.len() != HISTORY_WORDS { + return Err(Error::InvalidQwenShape); + } + if history.iter().any(|x| !x.is_finite()) { + return Err(Error::NonFiniteMmqOutput("GDN prior history")); + } + workspace.validate_context(self.context)?; + let batch = self.batch.as_ref().ok_or(Error::ContextPoisoned)?; + let status = batch.status_handle()?; + let mut bindings = Bindings::new(); + let mut buffer = + |role: Role, b: &DeviceBuffer<'_>, bytes: usize| -> Result { + if !std::ptr::eq(b.context, self.context) { + return Err(Error::ContextMismatch); + } + if b.len() != bytes { + return Err(Error::InvalidQwenShape); + } + let h = b.handle.ok_or(Error::ContextPoisoned)?; + h.validate_projection_extent(bytes, 4)?; + workspace.reject_alias(h, bytes)?; + if h.overlaps(bytes, status, STATUS_BYTES) { + return Err(Error::OutputAliasesInput); + } + bindings.bind(role, h, bytes)?; + Ok(h) + }; + let scratch = buffer( + Role::Scratch, + self.scratch.as_ref().ok_or(Error::ContextPoisoned)?, + SCRATCH, + )?; + let hin = buffer( + Role::History, + self.history[0].as_ref().ok_or(Error::ContextPoisoned)?, + HISTORY, + )?; + let hout = buffer( + Role::NextHistory, + self.history[1].as_ref().ok_or(Error::ContextPoisoned)?, + HISTORY, + )?; + let sin = buffer(Role::StateIn, state, STATE_WORDS * 4)?; + let sout = buffer(Role::StateOut, next_state, STATE_WORDS * 4)?; + let mut w = [sin; 5]; + for (i, role, n, k) in [ + (0, Role::QkvW, C, N), + (1, Role::ZW, ZV, N), + (2, Role::OutW, N, ZV), + (3, Role::AlphaW, HV, N), + (4, Role::BetaW, HV, N), + ] { + let bytes = if i < 3 { + weights.formats[i].matrix_bytes(n, k)? + } else { + n * k * 2 + }; + w[i] = buffer(role, weights.matrices[i], bytes)?; + } + let mut a = [sin; 4]; + for (i, role, n) in [ + (0, Role::ConvW, C * 4 * 4), + (1, Role::Dt, HV * 4), + (2, Role::SsmA, HV * 4), + (3, Role::Gamma, S * 4), + ] { + a[i] = buffer(role, weights.aux[i], n)?; + } + drop(buffer); + let mut carved = |role: Role, + phase: Option<(&str, usize)>, + common: Option<(OriginalPromptSpan, usize)>| + -> Result { + let (h, capacity, bytes) = if let Some((name, width)) = phase { + let (h, n) = lease.span(PrefillPhase::Gdn, name)?; + (h, n, t * width) + } else { + let (r, width) = common.ok_or(Error::InvalidQwenShape)?; + let (h, n) = lease.common_span(r)?; + (h, n, t * width) + }; + let h = h.checked_subspan(capacity, 0, bytes)?; + h.validate_projection_extent(bytes, 2)?; + workspace.reject_alias(h, bytes)?; + if h.overlaps(bytes, status, STATUS_BYTES) { + return Err(Error::OutputAliasesInput); + } + bindings.bind(role, h, bytes)?; + Ok(h) + }; + let mixed = carved( + Role::MixedH, + None, + Some((OriginalPromptSpan::MixedHalf, 5120)), + )?; + let high = carved( + Role::MixedBf, + None, + Some((OriginalPromptSpan::MixedHigh, 5120)), + )?; + let lower = if self.profile == crate::GrNativeProfile::HighAndLow { + Some(carved( + Role::MixedBfLo, + None, + Some((OriginalPromptSpan::MixedLow, 5120)), + )?) + } else { + None + }; + let qkv = carved(Role::Qkv, Some(("qkv", C * 4)), None)?; + let z = carved(Role::Z, Some(("z", ZV * 4)), None)?; + let ab = carved(Role::Ab, Some(("ab", HV * 8)), None)?; + let gate = carved(Role::Gate, Some(("gate", HV * 4)), None)?; + let beta = carved(Role::Beta, Some(("beta", HV * 4)), None)?; + let h = carved(Role::H, Some(("hbuf", C * 4)), None)?; + let y = carved(Role::Y, Some(("y", ZV * 4)), None)?; + let yh = carved(Role::Y16, Some(("y_h", ZV * 2)), None)?; + let bo = carved(Role::Bo, None, Some((OriginalPromptSpan::Block, N * 4)))?; + drop(carved); + // Every owner/alias/shape admission above precedes the first write. + let mut commands = Vec::new(); + commands + .try_reserve_exact(48) + .map_err(|_| Error::HostAllocation)?; + let funcs = batch.functions.as_ref().ok_or(Error::ContextPoisoned)?; + let mut push = |kernel: Kernel, + geometry: ([u32; 3], [u32; 3]), + args: &[ffi::KernelArg]| + -> Result<()> { + commands.push(DeviceCommand::Kernel { + function: funcs.get(kernel), + grid: geometry.0, + block: geometry.1, + args: ffi::GdnPrefillArguments::new(args)?, + }); + Ok(()) + }; + push( + Kernel::Zero, + linear(SLOTS)?, + &[ + ffi::KernelArg::Pointer(status), + ffi::KernelArg::U32(SLOTS as u32), + ], + )?; + drop(push); + let add_kernel = |commands: &mut Vec, + kernel: Kernel, + geometry: ([u32; 3], [u32; 3]), + args: &[ffi::KernelArg]| + -> Result<()> { + commands.push(DeviceCommand::Kernel { + function: funcs.get(kernel), + grid: geometry.0, + block: geometry.1, + args: ffi::GdnPrefillArguments::new(args)?, + }); + Ok(()) + }; + let scan = |commands: &mut Vec, + stage: GdnBatchStage, + data: ffi::BufferHandle| + -> Result<()> { + let word = status.checked_subspan(STATUS_BYTES, stage.slot() * 4, 4)?; + add_kernel( + commands, + if stage.is_half() { + Kernel::FiniteF16 + } else { + Kernel::FiniteF32 + }, + linear(stage.elements(t))?, + &[ + ffi::KernelArg::Pointer(data), + ffi::KernelArg::Pointer(word), + ffi::KernelArg::U32(stage.elements(t) as u32), + ], + ) + }; + let fast_dequant = crate::prefill_stage::fast_dequant(); + let native = |commands: &mut Vec, + format: GdnNativeFormat, + input, + weight, + output, + n: usize, + k: usize| + -> Result<()> { + if fast_dequant { + let total = n * k; + commands.push(DeviceCommand::Stage { + index: crate::prefill_stage::DEQUANT_FIRST + + match format { + GdnNativeFormat::Q8_0 => 0, + GdnNativeFormat::Q4K => 1, + GdnNativeFormat::Q5K => 2, + GdnNativeFormat::Q6K => 3, + GdnNativeFormat::Iq4Nl => 4, + GdnNativeFormat::Iq4Xs => 5, + }, + grid: u32::try_from(total.div_ceil(256)).map_err(|_| Error::InvalidQwenShape)?, + block: 256, + args: KernelArguments::new(vec![ + A::Address(weight), + A::I64((k / format.block().0 * format.block().1) as i64), + A::I64(total as i64), + A::I64((k / 32) as i64), + A::Address(scratch), + ]), + }); + } else { + add_kernel( + commands, + format.kernel(), + linear(n * (k / 32))?, + &[ + ffi::KernelArg::Pointer(weight), + ffi::KernelArg::I64((k / format.block().0 * format.block().1) as i64), + ffi::KernelArg::I64(0), + ffi::KernelArg::I64(n as i64), + ffi::KernelArg::I64((k / 32) as i64), + ffi::KernelArg::Pointer(scratch), + ], + )?; + } + commands.push(DeviceCommand::Gemm { + bf16: false, + x: input, + w: scratch, + y: output, + n: n as i32, + k: k as i32, + ldy: n as i32, + offset: 0, + beta: 0., + }); + Ok(()) + }; + scan(&mut commands, GdnBatchStage::MixedH, mixed)?; + // t > 64 with fused guards: the guards of qkv, the convolution output, the normalised q/k, z, the readout, y and its + // FP16 image ride on the kernels that read or write those tensors (same status words) + let fused = crate::prefill_stage::fused_scans() && t > 64; + let word = |stage: GdnBatchStage| status.checked_subspan(STATUS_BYTES, stage.slot() * 4, 4); + native(&mut commands, weights.formats[0], mixed, w[0], qkv, C, N)?; + if !fused { + scan(&mut commands, GdnBatchStage::Qkv, qkv)?; + } + native(&mut commands, weights.formats[1], mixed, w[1], z, ZV, N)?; + if !fused { + scan(&mut commands, GdnBatchStage::Z, z)?; + } + for (i, offset) in [(3, 0), (4, HV)] { + commands.push(DeviceCommand::Gemm { + bf16: true, + x: high, + w: w[i], + y: ab, + n: HV as i32, + k: N as i32, + ldy: 96, + offset, + beta: 0., + }); + if let Some(lo) = lower { + commands.push(DeviceCommand::Gemm { + bf16: true, + x: lo, + w: w[i], + y: ab, + n: HV as i32, + k: N as i32, + ldy: 96, + offset, + beta: 1., + }) + } + } + scan(&mut commands, GdnBatchStage::Ab, ab)?; + add_kernel( + &mut commands, + Kernel::Gates, + linear(t * HV)?, + &[ + ffi::KernelArg::Pointer(ab), + ffi::KernelArg::Pointer(a[1]), + ffi::KernelArg::Pointer(a[2]), + ffi::KernelArg::Pointer(gate), + ffi::KernelArg::Pointer(beta), + ffi::KernelArg::I64(t as i64), + ], + )?; + scan(&mut commands, GdnBatchStage::Gate, gate)?; + scan(&mut commands, GdnBatchStage::Beta, beta)?; + if t <= 64 { + add_kernel( + &mut commands, + Kernel::Conv, + ([80, 1, 1], [128, 1, 1]), + &[ + ffi::KernelArg::Pointer(hin), + ffi::KernelArg::Pointer(hout), + ffi::KernelArg::Pointer(qkv), + ffi::KernelArg::Pointer(a[0]), + ffi::KernelArg::Pointer(h), + ffi::KernelArg::I64(t as i64), + ], + )? + } else { + if fused { + commands.push(DeviceCommand::Stage { + index: crate::prefill_stage::GDN_CONV_TILED, + grid: 40 * t.div_ceil(64) as u32, + block: 256, + args: KernelArguments::new(vec![ + A::Address(hin), + A::Address(qkv), + A::Address(a[0]), + A::Address(h), + A::I64(t as i64), + A::Address(word(GdnBatchStage::Qkv)?), + A::Address(word(GdnBatchStage::ConvH)?), + ]), + }); + } else { + add_kernel( + &mut commands, + Kernel::ConvTiled, + ([80, t.div_ceil(64) as u32, 1], [128, 1, 1]), + &[ + ffi::KernelArg::Pointer(hin), + ffi::KernelArg::Pointer(qkv), + ffi::KernelArg::Pointer(a[0]), + ffi::KernelArg::Pointer(h), + ffi::KernelArg::I64(t as i64), + ], + )?; + } + add_kernel( + &mut commands, + Kernel::ConvHist, + ([80, 1, 1], [128, 1, 1]), + &[ + ffi::KernelArg::Pointer(hout), + ffi::KernelArg::Pointer(hin), + ffi::KernelArg::Pointer(qkv), + ffi::KernelArg::I64(t as i64), + ], + )?; + } + if !fused { + scan(&mut commands, GdnBatchStage::ConvH, h)?; + } + scan(&mut commands, GdnBatchStage::NextHistory, hout)?; + if fused { + commands.push(DeviceCommand::Stage { + index: crate::prefill_stage::GDN_L2, + grid: (32 * t).div_ceil(2) as u32, + block: 256, + args: KernelArguments::new(vec![ + A::Address(h), + A::F32(GDN_BATCH_EPSILON), + A::I64(t as i64), + A::Address(word(GdnBatchStage::Qk)?), + ]), + }); + } else { + add_kernel( + &mut commands, + Kernel::L2, + ([32, t as u32, 1], [128, 1, 1]), + &[ + ffi::KernelArg::Pointer(h), + ffi::KernelArg::F32(GDN_BATCH_EPSILON), + ], + )?; + scan(&mut commands, GdnBatchStage::Qk, h)?; + } + let witness = + status.checked_subspan(STATUS_BYTES, GdnBatchStage::StateSteps.slot() * 4, 4)?; + if crate::prefill_stage::fast_rec() || crate::prefill_stage::gdn_kh_usable(self.context) { + let kh = !crate::prefill_stage::fast_rec(); + commands.push(DeviceCommand::Stage { + index: if kh { crate::prefill_stage::GDN_REC_KH } else { crate::prefill_stage::GDN_REC }, + grid: if kh { 64 } else { 192 }, + block: 128, + args: KernelArguments::new(vec![ + A::Address(sin), + A::Address(sout), + A::Address(h), + A::Address(gate), + A::Address(beta), + A::Address(y), + A::I64(t as i64), + A::Address(witness), + ]), + }); + } else { + add_kernel( + &mut commands, + Kernel::RecColsPipe, + ([192, 1, 1], [32, 4, 1]), + &[ + ffi::KernelArg::Pointer(sin), + ffi::KernelArg::Pointer(sout), + ffi::KernelArg::Pointer(h), + ffi::KernelArg::Pointer(gate), + ffi::KernelArg::Pointer(beta), + ffi::KernelArg::Pointer(y), + ffi::KernelArg::I64(t as i64), + ffi::KernelArg::Pointer(witness), + ], + )?; + } + scan(&mut commands, GdnBatchStage::NextState, sout)?; + if fused { + commands.push(DeviceCommand::Stage { + index: if crate::prefill_stage::gdn_nostore() { crate::prefill_stage::GDN_OUT_NORM_Y16 } else { crate::prefill_stage::GDN_OUT_NORM }, + grid: (48 * t).div_ceil(2) as u32, + block: 256, + args: KernelArguments::new(vec![ + A::Address(z), + A::Address(a[3]), + A::F32(GDN_BATCH_EPSILON), + A::Address(y), + A::Address(yh), + A::I64(t as i64), + A::Address(word(GdnBatchStage::Z)?), + A::Address(word(GdnBatchStage::Readout)?), + A::Address(word(GdnBatchStage::Y)?), + A::Address(word(GdnBatchStage::Y16)?), + ]), + }); + } else { + scan(&mut commands, GdnBatchStage::Readout, y)?; + add_kernel( + &mut commands, + Kernel::OutNorm, + ([t as u32, 48, 1], [128, 1, 1]), + &[ + ffi::KernelArg::Pointer(z), + ffi::KernelArg::Pointer(a[3]), + ffi::KernelArg::F32(GDN_BATCH_EPSILON), + ffi::KernelArg::Pointer(y), + ffi::KernelArg::Pointer(yh), + ], + )?; + scan(&mut commands, GdnBatchStage::Y, y)?; + scan(&mut commands, GdnBatchStage::Y16, yh)?; + } + native(&mut commands, weights.formats[2], yh, w[2], bo, N, ZV)?; + scan(&mut commands, GdnBatchStage::Bo, bo)?; + let mut history_bytes = staging(HISTORY)?; + for (x, b) in history.iter().zip(history_bytes.as_chunks_mut::<4>().0) { + b.copy_from_slice(&x.to_le_bytes()) + } + let mut flags = staging(STATUS_BYTES)?; + let mut final_history = staging(HISTORY)?; + let mut values = Vec::new(); + values + .try_reserve_exact(HISTORY_WORDS) + .map_err(|_| Error::HostAllocation)?; + let context = self.context; + let blas = workspace.blas()?; + let guard = match context.enter() { + Ok(g) => g, + Err(e) => { + self.failed = true; + context.poison(); + context.retain_driver(); + return Err(e); + } + }; + if self.stage.is_none() { + match KernelModule::load(crate::prefill_stage::PTX, crate::prefill_stage::ENTRIES) { + Ok(m) => self.stage = Some(m), + Err(e) => { + let pop = guard.finish(); + self.failed = true; + return combine(Err(e), pop).map(|()| unreachable!("stage module")); + } + } + } + let timed = crate::command_profile::enabled(); + let started = std::time::Instant::now(); + let mut operation = context + .driver + .api + .copy_from(hin, &history_bytes) + .and_then(|()| context.driver.api.synchronize()); + if timed { + crate::command_profile::add("gdn", 0, "history upload", started.elapsed()); + } + for (index, cmd) in commands.iter_mut().enumerate() { + if operation.is_err() { + break; + } + let started = std::time::Instant::now(); + let label = match cmd { DeviceCommand::Kernel { .. } => "kernel", DeviceCommand::Gemm { .. } => "gemm", DeviceCommand::Stage { .. } => "stage" }; + operation = match cmd { + DeviceCommand::Kernel { + function, + grid, + block, + args, + } => context.driver.api.launch_gdn_native( + *function, + GdnStream::from_raw(blas.stream()), + *grid, + *block, + args, + ), + DeviceCommand::Gemm { + bf16, + x, + w, + y, + n, + k, + ldy, + offset, + beta, + } => blas.gemm_gdn(*bf16, *x, *w, *y, t as i32, *n, *k, *ldy, *offset, beta), + DeviceCommand::Stage { + index, + grid, + block, + args, + } => match self.stage.as_ref() { + Some(module) => module.launch(*index, *grid, *block, blas.stream(), args), + None => Err(Error::ContextPoisoned), + }, + }; + if timed && operation.is_ok() { + operation = blas.synchronize(); + crate::command_profile::add("gdn", index + 1, label, started.elapsed()); + } + } + let started = std::time::Instant::now(); + let sync = blas.synchronize(); + if operation.is_ok() && sync.is_ok() { + operation = context + .driver + .api + .copy_to(status, &mut flags) + .and_then(|()| context.driver.api.copy_to(hout, &mut final_history)) + } + let all = context.driver.api.synchronize(); + if timed { + crate::command_profile::add("gdn", 999, "drain+readback", started.elapsed()); + } + let pop = guard.finish(); + let result = combine(combine(combine(operation, sync), all), pop); + if result.is_err() { + // A failed drain has no trustworthy completion boundary. Retain the + // command and host buffers before returning, so none can be freed + // while driver work may still reference them. + self.failed = true; + context.poison(); + context.retain_driver(); + std::mem::forget((commands, history_bytes, flags, final_history)); + workspace.mark_failed(); + return result.map(|()| unreachable!("failed GDN drain")); + } + let refusal = match decode_statuses(&flags, SLOTS) { + Ok(r) => r, + Err(e) => { + self.failed = true; + context.poison(); + context.retain_driver(); + return Err(e); + } + }; + if let Some(stage) = refusal { + return Err(Error::NonFiniteMmqOutput(match stage { + GdnBatchStage::Bo => "GDN block", + _ => "GDN prompt stage", + })); + } + values.extend( + final_history + .as_chunks::<4>() + .0 + .iter() + .map(|x| f32::from_le_bytes(*x)), + ); + if values.iter().any(|x| !x.is_finite()) { + return Err(Error::NonFiniteMmqOutput("GDN final history")); + } + Ok((read.from_completed_block(), values.into_boxed_slice())) + } +} diff --git a/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_3.rs b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_3.rs new file mode 100644 index 00000000..83624a70 --- /dev/null +++ b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_3.rs @@ -0,0 +1,58 @@ +//! Moved out of the parent module by STRA-338: impl OriginalGdnPromptDevice (3). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalGdnPromptDevice<'ctx> { + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + pub(in super::super) fn close_inner(&mut self) -> Result<()> { + self.failed = true; + let mut result = Ok(()); + for b in self + .history + .iter_mut() + .filter_map(Option::take) + .chain(self.scratch.take()) + { + let r = if self.context.is_poisoned() { + std::mem::forget(b); + Err(Error::ContextPoisoned) + } else { + b.release() + }; + result = combine(result, r); + } + if let Some(m) = self.stage.take() { + let r = if self.context.is_poisoned() { + std::mem::forget(m); + Err(Error::ContextPoisoned) + } else { + match self.context.enter() { + Ok(g) => combine(m.close(), g.finish()), + Err(e) => { + std::mem::forget(m); + Err(e) + } + } + }; + result = combine(result, r); + } + if let Some(b) = self.batch.take() { + let r = if self.context.is_poisoned() { + std::mem::forget(b); + Err(Error::ContextPoisoned) + } else { + b.close() + }; + result = combine(result, r); + } + if result.is_err() { + self.context.poison(); + self.context.retain_driver() + } + result + } +} diff --git a/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread.rs b/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread.rs index 60d27873..810f0317 100644 --- a/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread.rs +++ b/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread.rs @@ -3,493 +3,9 @@ #[allow(unused_imports)] use super::*; -impl<'ctx> GrMicrobatchRead<'ctx> { - pub(super) fn new(context: &'ctx Context<'ctx>, tokens: usize, streams: &[f32]) -> Result { - checked_row(tokens, 0, 40960)?; - if streams.len() != tokens * 10240 { - return Err(Error::InvalidQwenShape); - } - if streams.iter().any(|x| !x.is_finite()) { - return Err(Error::InvalidDriverValue("GR micro input finite")); - } - if context.is_poisoned() { - return Err(Error::ContextPoisoned); - } - let required = SIZES.iter().try_fold(RESERVE, |sum, n| { - sum.checked_add(n * tokens).ok_or(Error::BudgetExceeded) - })?; - if context - .allocated_bytes() - .checked_add(required) - .is_none_or(|n| n > context.budget_bytes()) - || context.memory_info()?.0 < required - { - return Err(Error::BudgetExceeded); - } - let staging = encode(streams)?; - let mut owner = Self { - context, - tokens, - buffers: std::array::from_fn(|_| None), - finite_module: None, - finite: None, - phase: 0, - failed: false, - }; - let result = (|| { - for (slot, size) in SIZES.into_iter().enumerate() { - owner.buffers[slot] = Some(context.allocate(size * tokens)?); - } - let guard = context.enter()?; - let load = (|| { - let module = context.driver.api.load_mmq_resident()?; - owner.finite_module = Some(module); - owner.finite = Some(context.driver.api.mmq_resident_function(module, 1)?); - Ok(()) - })(); - let pop = guard.finish(); - if pop.is_err() { - context.poison(); - context.retain_driver(); - } - combine(load, pop)?; - if context.memory_info()?.0 < RESERVE { - return Err(Error::BudgetExceeded); - } - owner.buffers[0] - .as_mut() - .ok_or(Error::ContextPoisoned)? - .copy_from_owned(staging)?; - Ok(()) - })(); - if let Err(primary) = result { - return combine(Err(primary), owner.close()); - } - Ok(owner) - } - pub fn tokens(&self) -> usize { - self.tokens - } - pub fn allocated_bytes(&self) -> usize { - self.buffers.iter().flatten().map(DeviceBuffer::len).sum() - } - pub fn is_failed(&self) -> bool { - self.failed || self.context.is_poisoned() - } - pub(super) fn buffer(&self, slot: usize) -> Result<&DeviceBuffer<'ctx>> { - if self.is_failed() { - return Err(Error::ContextPoisoned); - } - self.buffers - .get(slot) - .and_then(Option::as_ref) - .ok_or(Error::ContextPoisoned) - } - pub(super) fn handle(&self, slot: usize, row: usize) -> Result { - let buffer = self.buffer(slot)?; - let (whole, offset) = checked_row(self.tokens, row, SIZES[slot])?; - if !std::ptr::eq(self.context, buffer.context) { - return Err(Error::ContextMismatch); - } - if buffer.len() != whole { - return Err(Error::InvalidQwenShape); - } - buffer - .handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(whole, offset, SIZES[slot]) - } - pub(super) fn validate(&self, weights: &[&DeviceBuffer<'_>]) -> Result<()> { - if self.is_failed() || self.finite_module.is_none() || self.finite.is_none() { - return Err(Error::ContextPoisoned); - } - for (i, buffer) in self.buffers.iter().enumerate() { - let buffer = buffer.as_ref().ok_or(Error::ContextPoisoned)?; - self.handle(i, self.tokens - 1)?; - let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; - for prior in self.buffers[..i].iter().flatten() { - if handle.overlaps( - buffer.bytes, - prior.handle.ok_or(Error::ContextPoisoned)?, - prior.bytes, - ) { - return Err(Error::OutputAliasesInput); - } - } - for weight in weights { - if !std::ptr::eq(self.context, weight.context) { - return Err(Error::ContextMismatch); - } - if handle.overlaps( - buffer.bytes, - weight.handle.ok_or(Error::ContextPoisoned)?, - weight.bytes, - ) { - return Err(Error::OutputAliasesInput); - } - } - } - Ok(()) - } - pub(super) fn row_arguments( - &self, - row: usize, - weights: [&DeviceBuffer<'_>; 4], - epsilon: f32, - ) -> Result<[Arguments; 6]> { - if !epsilon.is_finite() || epsilon < 0.0 { - return Err(Error::InvalidQwenShape); - } - let sizes = [40960, 6553600, 6553600, 81920]; - let mut w = [self.handle(0, row)?; 4]; - for (i, weight) in weights.iter().enumerate() { - if weight.len() != sizes[i] { - return Err(Error::InvalidQwenShape); - } - w[i] = weight.handle.ok_or(Error::ContextPoisoned)?; - } - let mut h = [self.handle(0, row)?; 8]; - for (i, handle) in h.iter_mut().enumerate() { - *handle = self.handle(i, row)?; - } - let sets: [&[ffi::BufferHandle]; 6] = [ - &[h[0], w[0], h[1]], - &[w[1], h[1], h[2]], - &[h[2], h[3]], - &[w[2], h[3], h[4]], - &[h[1], h[4], h[5], h[6]], - &[w[3], h[1], h[7]], - ]; - let mut prepared = Vec::new(); - prepared - .try_reserve_exact(6) - .map_err(|_| Error::HostAllocation)?; - for (operation, set) in OPS.into_iter().zip(sets) { - let asset = qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?; - asset.validate(operation)?; - let layout = operation.layout(); - let mut handles = [set[0]; 9]; - handles[..set.len()].copy_from_slice(set); - ranges_layout(operation, layout, handles, layout.bytes, false)?; - prepared.push(Arguments::with_layout(operation, layout, handles, epsilon)); - } - prepared.try_into().map_err(|_| Error::InvalidQwenShape) - } - // Seven separate actual status words per row preserve complete ordered - // Norm/Down/Silu/Up/products/mixed/inject refusal arbitration. The reused - // integer finite kernel sets bit0 only and scans every actual F32 word. - pub fn read(&mut self, weights: [&DeviceBuffer<'_>; 4], epsilon: f32) -> Result { - if self.phase != 0 { - return Err(Error::InvalidQwenShape); - } - self.validate(&weights)?; - let mut arguments = Vec::new(); - arguments - .try_reserve_exact(self.tokens) - .map_err(|_| Error::HostAllocation)?; - let mut scans = Vec::new(); - scans - .try_reserve_exact(self.tokens * 7) - .map_err(|_| Error::HostAllocation)?; - for row in 0..self.tokens { - arguments.push(self.row_arguments(row, weights, epsilon)?); - for (stage, slot) in [1, 2, 3, 4, 5, 6, 7].into_iter().enumerate() { - let status = self.handle(10, row)?.checked_subspan(32, stage * 4, 4)?; - scans.push(ffi::MmqResidentArguments::finite( - self.handle(slot, row)?, - status, - 0, - (SIZES[slot] / 4) as u32, - 0, - )); - } - } - let zero = vec![0u8; 32 * self.tokens]; - let mut readback = vec![0u8; 32 * self.tokens]; - let guard = self.context.enter()?; - let kernels = (|| { - let mut result = Vec::new(); - result - .try_reserve_exact(6) - .map_err(|_| Error::HostAllocation)?; - for operation in OPS { - result.push(registered( - self.context, - &self.context.qwen_kernels, - qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?, - )?); - } - Ok(result) - })(); - let kernels = match kernels { - Ok(kernels) => kernels, - Err(error) => { - let pop = guard.finish(); - if pop.is_err() { - self.failed = true; - self.context.poison(); - self.context.retain_driver(); - } - return combine(Err(error), pop); - } - }; - let status = self.buffer(10)?.handle.ok_or(Error::ContextPoisoned)?; - let finite = self.finite.ok_or(Error::ContextPoisoned)?; - let mut commands = self.context.driver.api.copy_from(status, &zero); - let initialized = commands.is_ok(); - let mut completed_scans = 0usize; - for (row, row_args) in arguments.iter_mut().enumerate() { - for stage in 0..6 { - if commands.is_err() { - break; - } - commands = self.context.driver.api.launch_qwen( - kernels[stage].function, - OPS[stage], - &mut row_args[stage], - ); - if commands.is_ok() { - let scan_stage = if stage == 5 { 6 } else { stage }; - let words = SIZES[[1, 2, 3, 4, 5, 7][stage]] / 4; - commands = self.context.driver.api.launch_mmq_resident( - finite, - words as u32, - &mut scans[row * 7 + scan_stage], - ); - if commands.is_ok() { - completed_scans += 1; - } - } - if stage == 4 && commands.is_ok() { - commands = self.context.driver.api.launch_mmq_resident( - finite, - 2560, - &mut scans[row * 7 + 5], - ); - if commands.is_ok() { - completed_scans += 1; - } - } - } - if commands.is_err() { - break; - } - } - let read_status = if initialized { - self.context.driver.api.copy_to(status, &mut readback) - } else { - Ok(()) - }; - let status_read = initialized && read_status.is_ok(); - let commands = combine(commands, read_status); - let sync = self.context.driver.api.synchronize(); - let pop = guard.finish(); - if commands.is_err() || sync.is_err() || pop.is_err() { - self.failed = true; - } - if sync.is_err() || pop.is_err() { - self.context.poison(); - self.context.retain_driver(); - std::mem::forget((arguments, scans, zero, readback)); - } else { - // A later enqueue failure cannot replace an earlier completed - // numeric refusal. Only actually enqueued scans, successful - // status readback and confirmed sync/pop authorize this ordering. - if status_read { - let mut scan_index = 0usize; - for row in readback.chunks_exact(32) { - for (stage, bytes) in row.chunks_exact(4).take(7).enumerate() { - if scan_index >= completed_scans { - break; - } - scan_index += 1; - let flag = u32::from_le_bytes( - bytes.try_into().map_err(|_| Error::InvalidQwenShape)?, - ); - if flag & !1 != 0 { - self.failed = true; - return Err(Error::InvalidDriverValue("GR micro finite status")); - } - if flag != 0 { - return Err(Error::NonFiniteMmqOutput(STAGES[stage])); - } - } - } - } - combine(combine(commands, sync), pop)?; - let mixed = decode(self.buffer(6)?)?; - let inject = decode(self.buffer(7)?)?; - self.phase = 1; - return Ok(GrMicroValues { mixed, inject }); - } - combine(combine(commands, sync), pop) - .map(|()| unreachable!("uncertain completion is an error")) - } - /// Original residual write consumes retained real input and injection banks. - /// Blocks are the only new upload. Completed candidate is retained as the - /// next input bank, while canonical host values remain truthful. - pub fn inject(&mut self, blocks: &[f32]) -> Result> { - if self.phase != 1 { - return Err(Error::InvalidQwenShape); - } - self.validate(&[])?; - if blocks.len() != self.tokens * 2560 { - return Err(Error::InvalidQwenShape); - } - if blocks.iter().any(|x| !x.is_finite()) { - return Err(Error::InvalidDriverValue("GR micro block finite")); - } - let staging = encode(blocks)?; - let mut arguments = Vec::new(); - let mut scans = Vec::new(); - arguments - .try_reserve_exact(self.tokens) - .map_err(|_| Error::HostAllocation)?; - scans - .try_reserve_exact(self.tokens) - .map_err(|_| Error::HostAllocation)?; - let operation = Operation::InjectResidual; - let asset = qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?; - asset.validate(operation)?; - for row in 0..self.tokens { - let layout = operation.layout(); - let mut handles = [self.handle(0, row)?; 9]; - for (i, slot) in [0, 8, 7, 9].into_iter().enumerate() { - handles[i] = self.handle(slot, row)?; - } - ranges_layout(operation, layout, handles, layout.bytes, false)?; - arguments.push(Arguments::with_layout(operation, layout, handles, 0.)); - scans.push(ffi::MmqResidentArguments::finite( - handles[3], - self.handle(10, row)?.checked_subspan(32, 28, 4)?, - 0, - 10240, - 0, - )); - } - let zero = vec![0u8; 32 * self.tokens]; - let mut readback = vec![0u8; 32 * self.tokens]; - let status = self.buffer(10)?.handle.ok_or(Error::ContextPoisoned)?; - let block = self.buffer(8)?.handle.ok_or(Error::ContextPoisoned)?; - let guard = self.context.enter()?; - let kernel = match registered(self.context, &self.context.qwen_kernels, asset) { - Ok(kernel) => kernel, - Err(error) => { - let pop = guard.finish(); - if pop.is_err() { - self.failed = true; - self.context.poison(); - self.context.retain_driver(); - } - return combine(Err(error), pop); - } - }; - let mut commands = self.context.driver.api.copy_from(block, &staging); - if commands.is_ok() { - commands = self.context.driver.api.copy_from(status, &zero); - } - let initialized = commands.is_ok(); - let mut completed_scans = 0usize; - for (args, scan) in arguments.iter_mut().zip(scans.iter_mut()) { - if commands.is_err() { - break; - } - commands = self - .context - .driver - .api - .launch_qwen(kernel.function, operation, args); - if commands.is_ok() { - commands = self.context.driver.api.launch_mmq_resident( - self.finite.ok_or(Error::ContextPoisoned)?, - 10240, - scan, - ); - } - if commands.is_ok() { - completed_scans += 1; - } - } - let read_status = if initialized { - self.context.driver.api.copy_to(status, &mut readback) - } else { - Ok(()) - }; - let status_read = initialized && read_status.is_ok(); - let commands = combine(commands, read_status); - let sync = self.context.driver.api.synchronize(); - let pop = guard.finish(); - if commands.is_err() || sync.is_err() || pop.is_err() { - self.failed = true; - } - if sync.is_err() || pop.is_err() { - self.context.poison(); - self.context.retain_driver(); - std::mem::forget((arguments, scans, staging, zero, readback)); - return combine(combine(commands, sync), pop) - .map(|()| unreachable!("uncertain completion")); - } - if status_read { - for row in readback.chunks_exact(32).take(completed_scans) { - let flag = u32::from_le_bytes( - row[28..32] - .try_into() - .map_err(|_| Error::InvalidQwenShape)?, - ); - if flag & !1 != 0 { - self.failed = true; - return Err(Error::InvalidDriverValue("GR micro candidate status")); - } - if flag != 0 { - return Err(Error::NonFiniteMmqOutput("GR inject candidate")); - } - } - } - combine(combine(commands, sync), pop)?; - let values = decode(self.buffer(9)?)?; - self.buffers.swap(0, 9); - self.phase = 0; - Ok(values) - } - pub fn close(mut self) -> Result<()> { - self.close_inner() - } - pub(super) fn close_inner(&mut self) -> Result<()> { - self.failed = true; - let mut result = Ok(()); - for slot in self.buffers.iter_mut().rev() { - if let Some(buffer) = slot.take() { - let release = if self.context.is_poisoned() { - std::mem::forget(buffer); - self.context.retain_driver(); - Err(Error::ContextPoisoned) - } else { - buffer.release() - }; - if release.is_err() { - self.context.poison(); - self.context.retain_driver(); - } - result = combine(result, release); - } - } - self.finite = None; - if let Some(module) = self.finite_module.take() { - let release = if self.context.is_poisoned() { - self.context.retain_driver(); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(guard) => combine(self.context.driver.api.unload(module), guard.finish()), - Err(error) => Err(error), - } - }; - if release.is_err() { - self.context.poison(); - self.context.retain_driver(); - } - result = combine(result, release); - } - result - } -} +#[path = "impl_grmicrobatchread/impl_grmicrobatchread_2.rs"] +mod impl_grmicrobatchread_2; +#[path = "impl_grmicrobatchread/impl_grmicrobatchread_2_2.rs"] +mod impl_grmicrobatchread_2_2; +#[path = "impl_grmicrobatchread/impl_grmicrobatchread_3.rs"] +mod impl_grmicrobatchread_3; diff --git a/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/impl_grmicrobatchread_2.rs b/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/impl_grmicrobatchread_2.rs new file mode 100644 index 00000000..b4d073b4 --- /dev/null +++ b/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/impl_grmicrobatchread_2.rs @@ -0,0 +1,179 @@ +//! Moved out of the parent module by STRA-338: impl GrMicrobatchRead. + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> GrMicrobatchRead<'ctx> { + pub(in super::super) fn new(context: &'ctx Context<'ctx>, tokens: usize, streams: &[f32]) -> Result { + checked_row(tokens, 0, 40960)?; + if streams.len() != tokens * 10240 { + return Err(Error::InvalidQwenShape); + } + if streams.iter().any(|x| !x.is_finite()) { + return Err(Error::InvalidDriverValue("GR micro input finite")); + } + if context.is_poisoned() { + return Err(Error::ContextPoisoned); + } + let required = SIZES.iter().try_fold(RESERVE, |sum, n| { + sum.checked_add(n * tokens).ok_or(Error::BudgetExceeded) + })?; + if context + .allocated_bytes() + .checked_add(required) + .is_none_or(|n| n > context.budget_bytes()) + || context.memory_info()?.0 < required + { + return Err(Error::BudgetExceeded); + } + let staging = encode(streams)?; + let mut owner = Self { + context, + tokens, + buffers: std::array::from_fn(|_| None), + finite_module: None, + finite: None, + phase: 0, + failed: false, + }; + let result = (|| { + for (slot, size) in SIZES.into_iter().enumerate() { + owner.buffers[slot] = Some(context.allocate(size * tokens)?); + } + let guard = context.enter()?; + let load = (|| { + let module = context.driver.api.load_mmq_resident()?; + owner.finite_module = Some(module); + owner.finite = Some(context.driver.api.mmq_resident_function(module, 1)?); + Ok(()) + })(); + let pop = guard.finish(); + if pop.is_err() { + context.poison(); + context.retain_driver(); + } + combine(load, pop)?; + if context.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + owner.buffers[0] + .as_mut() + .ok_or(Error::ContextPoisoned)? + .copy_from_owned(staging)?; + Ok(()) + })(); + if let Err(primary) = result { + return combine(Err(primary), owner.close()); + } + Ok(owner) + } + pub fn tokens(&self) -> usize { + self.tokens + } + pub fn allocated_bytes(&self) -> usize { + self.buffers.iter().flatten().map(DeviceBuffer::len).sum() + } + pub fn is_failed(&self) -> bool { + self.failed || self.context.is_poisoned() + } + pub(in super::super) fn buffer(&self, slot: usize) -> Result<&DeviceBuffer<'ctx>> { + if self.is_failed() { + return Err(Error::ContextPoisoned); + } + self.buffers + .get(slot) + .and_then(Option::as_ref) + .ok_or(Error::ContextPoisoned) + } + pub(in super::super) fn handle(&self, slot: usize, row: usize) -> Result { + let buffer = self.buffer(slot)?; + let (whole, offset) = checked_row(self.tokens, row, SIZES[slot])?; + if !std::ptr::eq(self.context, buffer.context) { + return Err(Error::ContextMismatch); + } + if buffer.len() != whole { + return Err(Error::InvalidQwenShape); + } + buffer + .handle + .ok_or(Error::ContextPoisoned)? + .checked_subspan(whole, offset, SIZES[slot]) + } + pub(in super::super) fn validate(&self, weights: &[&DeviceBuffer<'_>]) -> Result<()> { + if self.is_failed() || self.finite_module.is_none() || self.finite.is_none() { + return Err(Error::ContextPoisoned); + } + for (i, buffer) in self.buffers.iter().enumerate() { + let buffer = buffer.as_ref().ok_or(Error::ContextPoisoned)?; + self.handle(i, self.tokens - 1)?; + let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; + for prior in self.buffers[..i].iter().flatten() { + if handle.overlaps( + buffer.bytes, + prior.handle.ok_or(Error::ContextPoisoned)?, + prior.bytes, + ) { + return Err(Error::OutputAliasesInput); + } + } + for weight in weights { + if !std::ptr::eq(self.context, weight.context) { + return Err(Error::ContextMismatch); + } + if handle.overlaps( + buffer.bytes, + weight.handle.ok_or(Error::ContextPoisoned)?, + weight.bytes, + ) { + return Err(Error::OutputAliasesInput); + } + } + } + Ok(()) + } + pub(in super::super) fn row_arguments( + &self, + row: usize, + weights: [&DeviceBuffer<'_>; 4], + epsilon: f32, + ) -> Result<[Arguments; 6]> { + if !epsilon.is_finite() || epsilon < 0.0 { + return Err(Error::InvalidQwenShape); + } + let sizes = [40960, 6553600, 6553600, 81920]; + let mut w = [self.handle(0, row)?; 4]; + for (i, weight) in weights.iter().enumerate() { + if weight.len() != sizes[i] { + return Err(Error::InvalidQwenShape); + } + w[i] = weight.handle.ok_or(Error::ContextPoisoned)?; + } + let mut h = [self.handle(0, row)?; 8]; + for (i, handle) in h.iter_mut().enumerate() { + *handle = self.handle(i, row)?; + } + let sets: [&[ffi::BufferHandle]; 6] = [ + &[h[0], w[0], h[1]], + &[w[1], h[1], h[2]], + &[h[2], h[3]], + &[w[2], h[3], h[4]], + &[h[1], h[4], h[5], h[6]], + &[w[3], h[1], h[7]], + ]; + let mut prepared = Vec::new(); + prepared + .try_reserve_exact(6) + .map_err(|_| Error::HostAllocation)?; + for (operation, set) in OPS.into_iter().zip(sets) { + let asset = qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?; + asset.validate(operation)?; + let layout = operation.layout(); + let mut handles = [set[0]; 9]; + handles[..set.len()].copy_from_slice(set); + ranges_layout(operation, layout, handles, layout.bytes, false)?; + prepared.push(Arguments::with_layout(operation, layout, handles, epsilon)); + } + prepared.try_into().map_err(|_| Error::InvalidQwenShape) + } +} diff --git a/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/impl_grmicrobatchread_2_2.rs b/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/impl_grmicrobatchread_2_2.rs new file mode 100644 index 00000000..c5ee2948 --- /dev/null +++ b/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/impl_grmicrobatchread_2_2.rs @@ -0,0 +1,158 @@ +//! Moved out of the parent module by STRA-338: impl GrMicrobatchRead (2). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> GrMicrobatchRead<'ctx> { + // Seven separate actual status words per row preserve complete ordered + // Norm/Down/Silu/Up/products/mixed/inject refusal arbitration. The reused + // integer finite kernel sets bit0 only and scans every actual F32 word. + pub fn read(&mut self, weights: [&DeviceBuffer<'_>; 4], epsilon: f32) -> Result { + if self.phase != 0 { + return Err(Error::InvalidQwenShape); + } + self.validate(&weights)?; + let mut arguments = Vec::new(); + arguments + .try_reserve_exact(self.tokens) + .map_err(|_| Error::HostAllocation)?; + let mut scans = Vec::new(); + scans + .try_reserve_exact(self.tokens * 7) + .map_err(|_| Error::HostAllocation)?; + for row in 0..self.tokens { + arguments.push(self.row_arguments(row, weights, epsilon)?); + for (stage, slot) in [1, 2, 3, 4, 5, 6, 7].into_iter().enumerate() { + let status = self.handle(10, row)?.checked_subspan(32, stage * 4, 4)?; + scans.push(ffi::MmqResidentArguments::finite( + self.handle(slot, row)?, + status, + 0, + (SIZES[slot] / 4) as u32, + 0, + )); + } + } + let zero = vec![0u8; 32 * self.tokens]; + let mut readback = vec![0u8; 32 * self.tokens]; + let guard = self.context.enter()?; + let kernels = (|| { + let mut result = Vec::new(); + result + .try_reserve_exact(6) + .map_err(|_| Error::HostAllocation)?; + for operation in OPS { + result.push(registered( + self.context, + &self.context.qwen_kernels, + qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?, + )?); + } + Ok(result) + })(); + let kernels = match kernels { + Ok(kernels) => kernels, + Err(error) => { + let pop = guard.finish(); + if pop.is_err() { + self.failed = true; + self.context.poison(); + self.context.retain_driver(); + } + return combine(Err(error), pop); + } + }; + let status = self.buffer(10)?.handle.ok_or(Error::ContextPoisoned)?; + let finite = self.finite.ok_or(Error::ContextPoisoned)?; + let mut commands = self.context.driver.api.copy_from(status, &zero); + let initialized = commands.is_ok(); + let mut completed_scans = 0usize; + for (row, row_args) in arguments.iter_mut().enumerate() { + for stage in 0..6 { + if commands.is_err() { + break; + } + commands = self.context.driver.api.launch_qwen( + kernels[stage].function, + OPS[stage], + &mut row_args[stage], + ); + if commands.is_ok() { + let scan_stage = if stage == 5 { 6 } else { stage }; + let words = SIZES[[1, 2, 3, 4, 5, 7][stage]] / 4; + commands = self.context.driver.api.launch_mmq_resident( + finite, + words as u32, + &mut scans[row * 7 + scan_stage], + ); + if commands.is_ok() { + completed_scans += 1; + } + } + if stage == 4 && commands.is_ok() { + commands = self.context.driver.api.launch_mmq_resident( + finite, + 2560, + &mut scans[row * 7 + 5], + ); + if commands.is_ok() { + completed_scans += 1; + } + } + } + if commands.is_err() { + break; + } + } + let read_status = if initialized { + self.context.driver.api.copy_to(status, &mut readback) + } else { + Ok(()) + }; + let status_read = initialized && read_status.is_ok(); + let commands = combine(commands, read_status); + let sync = self.context.driver.api.synchronize(); + let pop = guard.finish(); + if commands.is_err() || sync.is_err() || pop.is_err() { + self.failed = true; + } + if sync.is_err() || pop.is_err() { + self.context.poison(); + self.context.retain_driver(); + std::mem::forget((arguments, scans, zero, readback)); + } else { + // A later enqueue failure cannot replace an earlier completed + // numeric refusal. Only actually enqueued scans, successful + // status readback and confirmed sync/pop authorize this ordering. + if status_read { + let mut scan_index = 0usize; + for row in readback.chunks_exact(32) { + for (stage, bytes) in row.chunks_exact(4).take(7).enumerate() { + if scan_index >= completed_scans { + break; + } + scan_index += 1; + let flag = u32::from_le_bytes( + bytes.try_into().map_err(|_| Error::InvalidQwenShape)?, + ); + if flag & !1 != 0 { + self.failed = true; + return Err(Error::InvalidDriverValue("GR micro finite status")); + } + if flag != 0 { + return Err(Error::NonFiniteMmqOutput(STAGES[stage])); + } + } + } + } + combine(combine(commands, sync), pop)?; + let mixed = decode(self.buffer(6)?)?; + let inject = decode(self.buffer(7)?)?; + self.phase = 1; + return Ok(GrMicroValues { mixed, inject }); + } + combine(combine(commands, sync), pop) + .map(|()| unreachable!("uncertain completion is an error")) + } +} diff --git a/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/impl_grmicrobatchread_3.rs b/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/impl_grmicrobatchread_3.rs new file mode 100644 index 00000000..d00c0e86 --- /dev/null +++ b/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/impl_grmicrobatchread_3.rs @@ -0,0 +1,175 @@ +//! Moved out of the parent module by STRA-338: impl GrMicrobatchRead (3). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> GrMicrobatchRead<'ctx> { + /// Original residual write consumes retained real input and injection banks. + /// Blocks are the only new upload. Completed candidate is retained as the + /// next input bank, while canonical host values remain truthful. + pub fn inject(&mut self, blocks: &[f32]) -> Result> { + if self.phase != 1 { + return Err(Error::InvalidQwenShape); + } + self.validate(&[])?; + if blocks.len() != self.tokens * 2560 { + return Err(Error::InvalidQwenShape); + } + if blocks.iter().any(|x| !x.is_finite()) { + return Err(Error::InvalidDriverValue("GR micro block finite")); + } + let staging = encode(blocks)?; + let mut arguments = Vec::new(); + let mut scans = Vec::new(); + arguments + .try_reserve_exact(self.tokens) + .map_err(|_| Error::HostAllocation)?; + scans + .try_reserve_exact(self.tokens) + .map_err(|_| Error::HostAllocation)?; + let operation = Operation::InjectResidual; + let asset = qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?; + asset.validate(operation)?; + for row in 0..self.tokens { + let layout = operation.layout(); + let mut handles = [self.handle(0, row)?; 9]; + for (i, slot) in [0, 8, 7, 9].into_iter().enumerate() { + handles[i] = self.handle(slot, row)?; + } + ranges_layout(operation, layout, handles, layout.bytes, false)?; + arguments.push(Arguments::with_layout(operation, layout, handles, 0.)); + scans.push(ffi::MmqResidentArguments::finite( + handles[3], + self.handle(10, row)?.checked_subspan(32, 28, 4)?, + 0, + 10240, + 0, + )); + } + let zero = vec![0u8; 32 * self.tokens]; + let mut readback = vec![0u8; 32 * self.tokens]; + let status = self.buffer(10)?.handle.ok_or(Error::ContextPoisoned)?; + let block = self.buffer(8)?.handle.ok_or(Error::ContextPoisoned)?; + let guard = self.context.enter()?; + let kernel = match registered(self.context, &self.context.qwen_kernels, asset) { + Ok(kernel) => kernel, + Err(error) => { + let pop = guard.finish(); + if pop.is_err() { + self.failed = true; + self.context.poison(); + self.context.retain_driver(); + } + return combine(Err(error), pop); + } + }; + let mut commands = self.context.driver.api.copy_from(block, &staging); + if commands.is_ok() { + commands = self.context.driver.api.copy_from(status, &zero); + } + let initialized = commands.is_ok(); + let mut completed_scans = 0usize; + for (args, scan) in arguments.iter_mut().zip(scans.iter_mut()) { + if commands.is_err() { + break; + } + commands = self + .context + .driver + .api + .launch_qwen(kernel.function, operation, args); + if commands.is_ok() { + commands = self.context.driver.api.launch_mmq_resident( + self.finite.ok_or(Error::ContextPoisoned)?, + 10240, + scan, + ); + } + if commands.is_ok() { + completed_scans += 1; + } + } + let read_status = if initialized { + self.context.driver.api.copy_to(status, &mut readback) + } else { + Ok(()) + }; + let status_read = initialized && read_status.is_ok(); + let commands = combine(commands, read_status); + let sync = self.context.driver.api.synchronize(); + let pop = guard.finish(); + if commands.is_err() || sync.is_err() || pop.is_err() { + self.failed = true; + } + if sync.is_err() || pop.is_err() { + self.context.poison(); + self.context.retain_driver(); + std::mem::forget((arguments, scans, staging, zero, readback)); + return combine(combine(commands, sync), pop) + .map(|()| unreachable!("uncertain completion")); + } + if status_read { + for row in readback.chunks_exact(32).take(completed_scans) { + let flag = u32::from_le_bytes( + row[28..32] + .try_into() + .map_err(|_| Error::InvalidQwenShape)?, + ); + if flag & !1 != 0 { + self.failed = true; + return Err(Error::InvalidDriverValue("GR micro candidate status")); + } + if flag != 0 { + return Err(Error::NonFiniteMmqOutput("GR inject candidate")); + } + } + } + combine(combine(commands, sync), pop)?; + let values = decode(self.buffer(9)?)?; + self.buffers.swap(0, 9); + self.phase = 0; + Ok(values) + } + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + pub(in super::super) fn close_inner(&mut self) -> Result<()> { + self.failed = true; + let mut result = Ok(()); + for slot in self.buffers.iter_mut().rev() { + if let Some(buffer) = slot.take() { + let release = if self.context.is_poisoned() { + std::mem::forget(buffer); + self.context.retain_driver(); + Err(Error::ContextPoisoned) + } else { + buffer.release() + }; + if release.is_err() { + self.context.poison(); + self.context.retain_driver(); + } + result = combine(result, release); + } + } + self.finite = None; + if let Some(module) = self.finite_module.take() { + let release = if self.context.is_poisoned() { + self.context.retain_driver(); + Err(Error::ContextPoisoned) + } else { + match self.context.enter() { + Ok(guard) => combine(self.context.driver.api.unload(module), guard.finish()), + Err(error) => Err(error), + } + }; + if release.is_err() { + self.context.poison(); + self.context.retain_driver(); + } + result = combine(result, release); + } + result + } +} diff --git a/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch.rs b/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch.rs index d95d91ac..782ce8a6 100644 --- a/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch.rs +++ b/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch.rs @@ -3,522 +3,9 @@ #[allow(unused_imports)] use super::*; -impl<'ctx> GrNativeBatch<'ctx> { - pub fn prompt_device_bytes(tokens: usize) -> Result { - if !(1..=8192).contains(&tokens) { - return Err(Error::InvalidQwenShape); - } - BYTES.iter().try_fold(0usize, |sum, n| { - sum.checked_add(n * tokens).ok_or(Error::BudgetExceeded) - }) - } - pub(super) fn new( - context: &'ctx Context<'ctx>, - tokens: usize, - streams: &[f32], - profile: GrNativeProfile, - ) -> Result { - Self::new_bounded(context, tokens, streams, profile, 64) - } - pub(super) fn new_bounded( - context: &'ctx Context<'ctx>, - tokens: usize, - streams: &[f32], - profile: GrNativeProfile, - limit: usize, - ) -> Result { - if !(1..=limit).contains(&tokens) || streams.len() != tokens * 10240 { - return Err(Error::InvalidQwenShape); - } - if streams.iter().any(|x| !x.is_finite()) { - return Err(Error::InvalidDriverValue("GR micro input finite")); - } - // Explicit unsealed source-only placeholder is never a CUDA producer. - if PTX.starts_with(b"// UNSEALED") { - return Err(Error::InvalidDriverValue("GR native asset unsealed")); - } - if context.is_poisoned() { - return Err(Error::ContextPoisoned); - } - let bank = BYTES.iter().try_fold(0usize, |n, x| { - n.checked_add(x * tokens).ok_or(Error::BudgetExceeded) - })?; - let required = bank.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; - if context - .allocated_bytes() - .checked_add(required) - .is_none_or(|n| n > context.budget_bytes()) - || context.memory_info()?.0 < required - { - return Err(Error::BudgetExceeded); - } - let mut owner = Self { - context, - tokens, - profile, - buffers: std::array::from_fn(|_| None), - module: None, - scalars: Some(Box::new([1., 0., 1.])), - phase: 0, - failed: false, - }; - let attempted = (|| { - for (i, n) in BYTES.into_iter().enumerate() { - owner.buffers[i] = Some(context.allocate(n * tokens)?); - } - let guard = context.enter()?; - let loaded = (|| { - owner.module = Some(KernelModule::load(PTX, ENTRIES)?); - Ok(()) - })(); - let pop = guard.finish(); - if pop.is_err() { - context.poison(); - context.retain_driver(); - } - combine(loaded, pop)?; - if context.memory_info()?.0 < RESERVE { - return Err(Error::BudgetExceeded); - } - owner.buffers[0] - .as_mut() - .ok_or(Error::ContextPoisoned)? - .copy_from_owned(encode(streams)?)?; - Ok(()) - })(); - if let Err(primary) = attempted { - let _ = owner.close(); - return Err(primary); - } - Ok(owner) - } - pub fn is_failed(&self) -> bool { - self.failed || self.context.is_poisoned() - } - pub fn allocated_bytes(&self) -> usize { - self.buffers.iter().flatten().map(DeviceBuffer::len).sum() - } - pub(super) fn buffer(&self, i: usize) -> Result<&DeviceBuffer<'ctx>> { - if self.is_failed() { - return Err(Error::ContextPoisoned); - } - self.buffers - .get(i) - .and_then(Option::as_ref) - .ok_or(Error::ContextPoisoned) - } - pub(super) fn handle(&self, i: usize) -> Result { - let b = self.buffer(i)?; - let bytes = BYTES.get(i).ok_or(Error::InvalidQwenShape)? * self.tokens; - if !std::ptr::eq(self.context, b.context) { - return Err(Error::ContextMismatch); - } - if b.len() != bytes { - return Err(Error::InvalidQwenShape); - } - let handle = b.handle.ok_or(Error::ContextPoisoned)?; - handle.validate_projection_extent(bytes, 256)?; - Ok(handle) - } - pub(super) fn validate(&self, weights: &[&DeviceBuffer<'_>]) -> Result<()> { - if self.is_failed() { - return Err(Error::ContextPoisoned); - } - for (i, b) in self.buffers.iter().enumerate() { - let b = b.as_ref().ok_or(Error::ContextPoisoned)?; - let h = self.handle(i)?; - for prior in self.buffers[..i].iter().flatten() { - if h.overlaps( - b.bytes, - prior.handle.ok_or(Error::ContextPoisoned)?, - prior.bytes, - ) { - return Err(Error::OutputAliasesInput); - } - } - for w in weights { - if !std::ptr::eq(self.context, w.context) { - return Err(Error::ContextMismatch); - } - if h.overlaps(b.bytes, w.handle.ok_or(Error::ContextPoisoned)?, w.bytes) { - return Err(Error::OutputAliasesInput); - } - } - } - Ok(()) - } - pub(super) fn low(&self, slot: usize) -> Result { - if self.profile == GrNativeProfile::HighOnly { - Ok(A::NullAddress) - } else { - Ok(A::Address(self.handle(slot)?)) - } - } - pub(super) fn args(values: Vec) -> KernelArguments { - KernelArguments::new(values) - } - pub(super) fn scan(&self, slot: usize, width: usize, stage: u32) -> Result { - Ok(Self::args(vec![ - A::Address(self.handle(slot)?), - A::Address(self.handle(14)?), - A::I64(width as i64), - A::I64(self.tokens as i64), - A::U32(stage), - ])) - } - pub(super) fn launch( - &self, - blas: &Blas, - index: usize, - count: usize, - args: &mut KernelArguments, - ) -> Result<()> { - let module = self.module.as_ref().ok_or(Error::ContextPoisoned)?; - let stream = blas.stream(); - module.launch(index, count.div_ceil(256) as u32, 256, stream, args) - } - #[allow(clippy::too_many_arguments)] // Fixed Original GEMM roles and owned alpha/beta ABI. - pub(super) fn gemm( - &self, - blas: &Blas, - input: usize, - low: usize, - weight: ffi::BufferHandle, - output: usize, - n: i32, - k: i32, - alpha: &f32, - beta0: &f32, - beta1: &f32, - ) -> Result<()> { - blas.gemm_bf16( - self.handle(input)?, - weight, - self.handle(output)?, - self.tokens as i32, - n, - k, - alpha, - beta0, - )?; - if self.profile == GrNativeProfile::HighAndLow { - blas.gemm_bf16( - self.handle(low)?, - weight, - self.handle(output)?, - self.tokens as i32, - n, - k, - alpha, - beta1, - )?; - } - Ok(()) - } - #[allow(clippy::too_many_arguments)] // One complete retained command/drain ownership set. - pub(super) fn finish( - &mut self, - blas: &Blas, - commands: Result<()>, - eligible: [bool; 8], - mut zero: Vec, - mut arguments: Vec, - mut readback: Vec, - guard: CurrentGuard<'_, 'ctx>, - ) -> Result<()> { - let sync = blas.synchronize(); - let status = if sync.is_ok() { - self.buffers[14] - .as_ref() - .and_then(|buffer| buffer.handle) - .ok_or(Error::ContextPoisoned) - .and_then(|handle| self.context.driver.api.copy_to(handle, &mut readback)) - } else { - Ok(()) - }; - let pop = guard.finish(); - if commands.is_err() || sync.is_err() || status.is_err() || pop.is_err() { - self.failed = true; - self.context.poison(); - self.context.retain_driver(); - } - if sync.is_err() || status.is_err() || pop.is_err() { - self.context.poison(); - self.context.retain_driver(); - std::mem::forget((arguments, zero, readback)); - return combine(combine(combine(commands, sync), status), pop); - } - if commands.is_err() { - // A failed upload/fence may still own host staging; conservatively - // retain every command operand even when vendor drain succeeded. - std::mem::forget(std::mem::take(&mut arguments)); - std::mem::forget(std::mem::take(&mut zero)); - } - if status.is_ok() { - for stage in [0usize, 1, 2, 3, 6, 4, 5, 7] { - if !eligible[stage] { - continue; - } - for row in readback.chunks_exact(32) { - let flag = u32::from_le_bytes( - row[stage * 4..stage * 4 + 4] - .try_into() - .map_err(|_| Error::InvalidQwenShape)?, - ); - if flag & !1 != 0 { - self.failed = true; - return Err(Error::InvalidDriverValue("GR native unknown finite status")); - } - if flag != 0 { - return Err(Error::NonFiniteMmqOutput(if stage == 7 { - "GR native candidate" - } else { - STAGES[stage] - })); - } - } - } - } - // Owned host ABI/staging cannot die before actual stream drain+pop. - arguments.clear(); - zero.clear(); - combine(combine(combine(commands, sync), status), pop) - } - pub fn read( - &mut self, - weights: [&DeviceBuffer<'_>; 4], - epsilon: f32, - workspace: &mut NativeBatchWorkspace<'ctx>, - ) -> Result { - if self.phase != 0 || !epsilon.is_finite() || epsilon < 0.0 { - return Err(Error::InvalidQwenShape); - } - workspace.validate_context(self.context)?; - self.validate(&weights)?; - for (i, buffer) in self.buffers.iter().flatten().enumerate() { - workspace.reject_alias(self.handle(i)?, buffer.bytes)?; - } - let blas = workspace.blas()?; - let mut w = [self.handle(0)?; 4]; - for (i, size) in [40960, 6553600, 6553600, 81920].into_iter().enumerate() { - if weights[i].len() != size { - return Err(Error::InvalidQwenShape); - } - w[i] = weights[i].handle.ok_or(Error::ContextPoisoned)?; - w[i].validate_projection_extent(size, if i == 0 { 4 } else { 2 })?; - workspace.reject_alias(w[i], size)?; - } - let t = self.tokens as i64; - let flags = self.handle(14)?; - let mut args = vec![ - Self::args(vec![ - A::Address(self.handle(0)?), - A::Address(w[0]), - A::F32(epsilon), - A::Address(self.handle(1)?), - A::Address(self.handle(2)?), - self.low(3)?, - ]), - Self::args(vec![ - A::Address(self.handle(0)?), - A::Address(self.handle(1)?), - A::Address(w[0]), - A::Address(flags), - A::I64(t), - ]), - self.scan(4, 320, 1)?, - Self::args(vec![ - A::Address(self.handle(4)?), - A::Address(self.handle(5)?), - self.low(6)?, - A::I64(t * 320), - ]), - Self::args(vec![ - A::Address(self.handle(4)?), - A::Address(flags), - A::I64(t), - ]), - self.scan(7, 10240, 3)?, - self.scan(12, 4, 6)?, - Self::args(vec![ - A::Address(self.handle(0)?), - A::Address(self.handle(1)?), - A::Address(w[0]), - A::Address(self.handle(7)?), - A::Address(self.handle(8)?), - A::Address(self.handle(9)?), - A::I64(t), - A::Address(self.handle(11)?), - self.low(10)?, - ]), - Self::args(vec![ - A::Address(self.handle(0)?), - A::Address(self.handle(1)?), - A::Address(w[0]), - A::Address(self.handle(7)?), - A::Address(flags), - A::I64(t), - ]), - self.scan(8, 2560, 5)?, - ]; - let scalars = self.scalars.as_ref().ok_or(Error::ContextPoisoned)?; - let alpha = &scalars[0]; - let beta0 = &scalars[1]; - let beta1 = &scalars[2]; - let zero = vec![0u8; 32 * self.tokens]; - let readback = vec![0u8; 32 * self.tokens]; - let context = self.context; - let guard = context.enter()?; - let mut eligible = [false; 8]; - let commands = (|| { - self.context.driver.api.copy_from(flags, &zero)?; - // The private vendor stream is NON_BLOCKING: drain all actual - // legacy uploads/reset before any stream consumer is enqueued. - self.context.driver.api.synchronize()?; - // Original gr_norm_rs block topology T*HC blocks, 256 threads. - self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch( - 0, - (self.tokens * 4) as u32, - 256, - blas.stream(), - &mut args[0], - )?; - self.launch(blas, 5, self.tokens * 10240, &mut args[1])?; - eligible[0] = true; - self.gemm(blas, 2, 3, w[1], 4, 320, 10240, alpha, beta0, beta1)?; - self.launch(blas, 4, self.tokens * 320, &mut args[2])?; - eligible[1] = true; - self.launch(blas, 1, self.tokens * 320, &mut args[3])?; - self.launch(blas, 6, self.tokens * 320, &mut args[4])?; - eligible[2] = true; - self.gemm(blas, 5, 6, w[2], 7, 10240, 320, alpha, beta0, beta1)?; - self.launch(blas, 4, self.tokens * 10240, &mut args[5])?; - eligible[3] = true; - // Literal Original executes inject GEMM BEFORE gr_mix_r. - self.gemm(blas, 2, 3, w[3], 12, 4, 10240, alpha, beta0, beta1)?; - self.launch(blas, 4, self.tokens * 4, &mut args[6])?; - eligible[6] = true; - self.launch(blas, 2, self.tokens * 2560, &mut args[7])?; - self.launch(blas, 7, self.tokens * 10240, &mut args[8])?; - eligible[4] = true; - self.launch(blas, 4, self.tokens * 2560, &mut args[9])?; - eligible[5] = true; - Ok(()) - })(); - self.finish(blas, commands, eligible, zero, args, readback, guard)?; - let mixed = decode(self.buffer(8)?)?; - let inject = decode(self.buffer(12)?)?; - self.phase = 1; - Ok(super::super::gr_batch_read::GrMicroValues { mixed, inject }) - } - pub fn inject( - &mut self, - blocks: &[f32], - workspace: &mut NativeBatchWorkspace<'ctx>, - ) -> Result> { - if self.phase != 1 { - return Err(Error::InvalidQwenShape); - } - workspace.validate_context(self.context)?; - self.validate(&[])?; - for (i, buffer) in self.buffers.iter().flatten().enumerate() { - workspace.reject_alias(self.handle(i)?, buffer.bytes)?; - } - let blas = workspace.blas()?; - if blocks.len() != self.tokens * 2560 { - return Err(Error::InvalidQwenShape); - } - if blocks.iter().any(|x| !x.is_finite()) { - return Err(Error::InvalidDriverValue("GR micro block finite")); - } - self.buffers[13] - .as_mut() - .ok_or(Error::ContextPoisoned)? - .copy_from_owned(encode(blocks)?)?; - let flags = self.handle(14)?; - let mut args = vec![ - Self::args(vec![ - A::Address(self.handle(0)?), - A::Address(self.handle(13)?), - A::Address(self.handle(12)?), - A::I64(4), - A::I64(self.tokens as i64), - ]), - self.scan(0, 10240, 7)?, - ]; - let zero = vec![0u8; 32 * self.tokens]; - let readback = vec![0u8; 32 * self.tokens]; - let context = self.context; - let guard = context.enter()?; - let mut eligible = [false; 8]; - let commands = (|| { - self.context.driver.api.copy_from(flags, &zero)?; - // The private vendor stream is NON_BLOCKING: drain all actual - // legacy uploads/reset before any stream consumer is enqueued. - self.context.driver.api.synchronize()?; - self.launch(blas, 3, self.tokens * 10240, &mut args[0])?; - self.launch(blas, 4, self.tokens * 10240, &mut args[1])?; - eligible[7] = true; - Ok(()) - })(); - // Original writes the real R bank in place. Any attempted failure - // retires this bank phase; no retry can add the same block twice. - // Mere completed numerical refusal does not poison the Context. - self.phase = 2; - self.finish(blas, commands, eligible, zero, args, readback, guard)?; - let values = decode(self.buffer(0)?)?; - self.phase = 0; - Ok(values) - } - pub fn close(mut self) -> Result<()> { - self.close_inner() - } - pub(super) fn close_inner(&mut self) -> Result<()> { - self.failed = true; - let mut result = Ok(()); - // Every returned operation drained this model's borrowed stream. - // Unknown completion already poisoned Context and retains ALL operands. - if let Some(module) = self.module.take() { - let closed = if self.context.is_poisoned() { - std::mem::forget(module); - self.context.retain_driver(); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(guard) => combine(module.close(), guard.finish()), - Err(error) => { - std::mem::forget(module); - Err(error) - } - } - }; - if closed.is_err() { - self.context.poison(); - self.context.retain_driver(); - } - result = combine(result, closed); - } - if let Some(scalars) = self.scalars.take() { - if self.context.is_poisoned() { - std::mem::forget(scalars); - } - } - for slot in self.buffers.iter_mut().rev() { - if let Some(buffer) = slot.take() { - let closed = if self.context.is_poisoned() { - std::mem::forget(buffer); - self.context.retain_driver(); - Err(Error::ContextPoisoned) - } else { - buffer.release() - }; - if closed.is_err() { - self.context.poison(); - self.context.retain_driver(); - } - result = combine(result, closed); - } - } - result - } -} +#[path = "impl_grnativebatch/impl_grnativebatch_2.rs"] +mod impl_grnativebatch_2; +#[path = "impl_grnativebatch/impl_grnativebatch_2_2.rs"] +mod impl_grnativebatch_2_2; +#[path = "impl_grnativebatch/impl_grnativebatch_3.rs"] +mod impl_grnativebatch_3; diff --git a/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/impl_grnativebatch_2.rs b/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/impl_grnativebatch_2.rs new file mode 100644 index 00000000..85748a79 --- /dev/null +++ b/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/impl_grnativebatch_2.rs @@ -0,0 +1,219 @@ +//! Moved out of the parent module by STRA-338: impl GrNativeBatch. + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> GrNativeBatch<'ctx> { + pub fn prompt_device_bytes(tokens: usize) -> Result { + if !(1..=8192).contains(&tokens) { + return Err(Error::InvalidQwenShape); + } + BYTES.iter().try_fold(0usize, |sum, n| { + sum.checked_add(n * tokens).ok_or(Error::BudgetExceeded) + }) + } + pub(in super::super) fn new( + context: &'ctx Context<'ctx>, + tokens: usize, + streams: &[f32], + profile: GrNativeProfile, + ) -> Result { + Self::new_bounded(context, tokens, streams, profile, 64) + } + pub(in super::super) fn new_bounded( + context: &'ctx Context<'ctx>, + tokens: usize, + streams: &[f32], + profile: GrNativeProfile, + limit: usize, + ) -> Result { + if !(1..=limit).contains(&tokens) || streams.len() != tokens * 10240 { + return Err(Error::InvalidQwenShape); + } + if streams.iter().any(|x| !x.is_finite()) { + return Err(Error::InvalidDriverValue("GR micro input finite")); + } + // Explicit unsealed source-only placeholder is never a CUDA producer. + if PTX.starts_with(b"// UNSEALED") { + return Err(Error::InvalidDriverValue("GR native asset unsealed")); + } + if context.is_poisoned() { + return Err(Error::ContextPoisoned); + } + let bank = BYTES.iter().try_fold(0usize, |n, x| { + n.checked_add(x * tokens).ok_or(Error::BudgetExceeded) + })?; + let required = bank.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; + if context + .allocated_bytes() + .checked_add(required) + .is_none_or(|n| n > context.budget_bytes()) + || context.memory_info()?.0 < required + { + return Err(Error::BudgetExceeded); + } + let mut owner = Self { + context, + tokens, + profile, + buffers: std::array::from_fn(|_| None), + module: None, + scalars: Some(Box::new([1., 0., 1.])), + phase: 0, + failed: false, + }; + let attempted = (|| { + for (i, n) in BYTES.into_iter().enumerate() { + owner.buffers[i] = Some(context.allocate(n * tokens)?); + } + let guard = context.enter()?; + let loaded = (|| { + owner.module = Some(KernelModule::load(PTX, ENTRIES)?); + Ok(()) + })(); + let pop = guard.finish(); + if pop.is_err() { + context.poison(); + context.retain_driver(); + } + combine(loaded, pop)?; + if context.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + owner.buffers[0] + .as_mut() + .ok_or(Error::ContextPoisoned)? + .copy_from_owned(encode(streams)?)?; + Ok(()) + })(); + if let Err(primary) = attempted { + let _ = owner.close(); + return Err(primary); + } + Ok(owner) + } + pub fn is_failed(&self) -> bool { + self.failed || self.context.is_poisoned() + } + pub fn allocated_bytes(&self) -> usize { + self.buffers.iter().flatten().map(DeviceBuffer::len).sum() + } + pub(in super::super) fn buffer(&self, i: usize) -> Result<&DeviceBuffer<'ctx>> { + if self.is_failed() { + return Err(Error::ContextPoisoned); + } + self.buffers + .get(i) + .and_then(Option::as_ref) + .ok_or(Error::ContextPoisoned) + } + pub(in super::super) fn handle(&self, i: usize) -> Result { + let b = self.buffer(i)?; + let bytes = BYTES.get(i).ok_or(Error::InvalidQwenShape)? * self.tokens; + if !std::ptr::eq(self.context, b.context) { + return Err(Error::ContextMismatch); + } + if b.len() != bytes { + return Err(Error::InvalidQwenShape); + } + let handle = b.handle.ok_or(Error::ContextPoisoned)?; + handle.validate_projection_extent(bytes, 256)?; + Ok(handle) + } + pub(in super::super) fn validate(&self, weights: &[&DeviceBuffer<'_>]) -> Result<()> { + if self.is_failed() { + return Err(Error::ContextPoisoned); + } + for (i, b) in self.buffers.iter().enumerate() { + let b = b.as_ref().ok_or(Error::ContextPoisoned)?; + let h = self.handle(i)?; + for prior in self.buffers[..i].iter().flatten() { + if h.overlaps( + b.bytes, + prior.handle.ok_or(Error::ContextPoisoned)?, + prior.bytes, + ) { + return Err(Error::OutputAliasesInput); + } + } + for w in weights { + if !std::ptr::eq(self.context, w.context) { + return Err(Error::ContextMismatch); + } + if h.overlaps(b.bytes, w.handle.ok_or(Error::ContextPoisoned)?, w.bytes) { + return Err(Error::OutputAliasesInput); + } + } + } + Ok(()) + } + pub(in super::super) fn low(&self, slot: usize) -> Result { + if self.profile == GrNativeProfile::HighOnly { + Ok(A::NullAddress) + } else { + Ok(A::Address(self.handle(slot)?)) + } + } + pub(in super::super) fn args(values: Vec) -> KernelArguments { + KernelArguments::new(values) + } + pub(in super::super) fn scan(&self, slot: usize, width: usize, stage: u32) -> Result { + Ok(Self::args(vec![ + A::Address(self.handle(slot)?), + A::Address(self.handle(14)?), + A::I64(width as i64), + A::I64(self.tokens as i64), + A::U32(stage), + ])) + } + pub(in super::super) fn launch( + &self, + blas: &Blas, + index: usize, + count: usize, + args: &mut KernelArguments, + ) -> Result<()> { + let module = self.module.as_ref().ok_or(Error::ContextPoisoned)?; + let stream = blas.stream(); + module.launch(index, count.div_ceil(256) as u32, 256, stream, args) + } + #[allow(clippy::too_many_arguments)] // Fixed Original GEMM roles and owned alpha/beta ABI. + pub(in super::super) fn gemm( + &self, + blas: &Blas, + input: usize, + low: usize, + weight: ffi::BufferHandle, + output: usize, + n: i32, + k: i32, + alpha: &f32, + beta0: &f32, + beta1: &f32, + ) -> Result<()> { + blas.gemm_bf16( + self.handle(input)?, + weight, + self.handle(output)?, + self.tokens as i32, + n, + k, + alpha, + beta0, + )?; + if self.profile == GrNativeProfile::HighAndLow { + blas.gemm_bf16( + self.handle(low)?, + weight, + self.handle(output)?, + self.tokens as i32, + n, + k, + alpha, + beta1, + )?; + } + Ok(()) + } +} diff --git a/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/impl_grnativebatch_2_2.rs b/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/impl_grnativebatch_2_2.rs new file mode 100644 index 00000000..d21f6537 --- /dev/null +++ b/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/impl_grnativebatch_2_2.rs @@ -0,0 +1,204 @@ +//! Moved out of the parent module by STRA-338: impl GrNativeBatch (2). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> GrNativeBatch<'ctx> { + #[allow(clippy::too_many_arguments)] // One complete retained command/drain ownership set. + pub(in super::super) fn finish( + &mut self, + blas: &Blas, + commands: Result<()>, + eligible: [bool; 8], + mut zero: Vec, + mut arguments: Vec, + mut readback: Vec, + guard: CurrentGuard<'_, 'ctx>, + ) -> Result<()> { + let sync = blas.synchronize(); + let status = if sync.is_ok() { + self.buffers[14] + .as_ref() + .and_then(|buffer| buffer.handle) + .ok_or(Error::ContextPoisoned) + .and_then(|handle| self.context.driver.api.copy_to(handle, &mut readback)) + } else { + Ok(()) + }; + let pop = guard.finish(); + if commands.is_err() || sync.is_err() || status.is_err() || pop.is_err() { + self.failed = true; + self.context.poison(); + self.context.retain_driver(); + } + if sync.is_err() || status.is_err() || pop.is_err() { + self.context.poison(); + self.context.retain_driver(); + std::mem::forget((arguments, zero, readback)); + return combine(combine(combine(commands, sync), status), pop); + } + if commands.is_err() { + // A failed upload/fence may still own host staging; conservatively + // retain every command operand even when vendor drain succeeded. + std::mem::forget(std::mem::take(&mut arguments)); + std::mem::forget(std::mem::take(&mut zero)); + } + if status.is_ok() { + for stage in [0usize, 1, 2, 3, 6, 4, 5, 7] { + if !eligible[stage] { + continue; + } + for row in readback.chunks_exact(32) { + let flag = u32::from_le_bytes( + row[stage * 4..stage * 4 + 4] + .try_into() + .map_err(|_| Error::InvalidQwenShape)?, + ); + if flag & !1 != 0 { + self.failed = true; + return Err(Error::InvalidDriverValue("GR native unknown finite status")); + } + if flag != 0 { + return Err(Error::NonFiniteMmqOutput(if stage == 7 { + "GR native candidate" + } else { + STAGES[stage] + })); + } + } + } + } + // Owned host ABI/staging cannot die before actual stream drain+pop. + arguments.clear(); + zero.clear(); + combine(combine(combine(commands, sync), status), pop) + } + pub fn read( + &mut self, + weights: [&DeviceBuffer<'_>; 4], + epsilon: f32, + workspace: &mut NativeBatchWorkspace<'ctx>, + ) -> Result { + if self.phase != 0 || !epsilon.is_finite() || epsilon < 0.0 { + return Err(Error::InvalidQwenShape); + } + workspace.validate_context(self.context)?; + self.validate(&weights)?; + for (i, buffer) in self.buffers.iter().flatten().enumerate() { + workspace.reject_alias(self.handle(i)?, buffer.bytes)?; + } + let blas = workspace.blas()?; + let mut w = [self.handle(0)?; 4]; + for (i, size) in [40960, 6553600, 6553600, 81920].into_iter().enumerate() { + if weights[i].len() != size { + return Err(Error::InvalidQwenShape); + } + w[i] = weights[i].handle.ok_or(Error::ContextPoisoned)?; + w[i].validate_projection_extent(size, if i == 0 { 4 } else { 2 })?; + workspace.reject_alias(w[i], size)?; + } + let t = self.tokens as i64; + let flags = self.handle(14)?; + let mut args = vec![ + Self::args(vec![ + A::Address(self.handle(0)?), + A::Address(w[0]), + A::F32(epsilon), + A::Address(self.handle(1)?), + A::Address(self.handle(2)?), + self.low(3)?, + ]), + Self::args(vec![ + A::Address(self.handle(0)?), + A::Address(self.handle(1)?), + A::Address(w[0]), + A::Address(flags), + A::I64(t), + ]), + self.scan(4, 320, 1)?, + Self::args(vec![ + A::Address(self.handle(4)?), + A::Address(self.handle(5)?), + self.low(6)?, + A::I64(t * 320), + ]), + Self::args(vec![ + A::Address(self.handle(4)?), + A::Address(flags), + A::I64(t), + ]), + self.scan(7, 10240, 3)?, + self.scan(12, 4, 6)?, + Self::args(vec![ + A::Address(self.handle(0)?), + A::Address(self.handle(1)?), + A::Address(w[0]), + A::Address(self.handle(7)?), + A::Address(self.handle(8)?), + A::Address(self.handle(9)?), + A::I64(t), + A::Address(self.handle(11)?), + self.low(10)?, + ]), + Self::args(vec![ + A::Address(self.handle(0)?), + A::Address(self.handle(1)?), + A::Address(w[0]), + A::Address(self.handle(7)?), + A::Address(flags), + A::I64(t), + ]), + self.scan(8, 2560, 5)?, + ]; + let scalars = self.scalars.as_ref().ok_or(Error::ContextPoisoned)?; + let alpha = &scalars[0]; + let beta0 = &scalars[1]; + let beta1 = &scalars[2]; + let zero = vec![0u8; 32 * self.tokens]; + let readback = vec![0u8; 32 * self.tokens]; + let context = self.context; + let guard = context.enter()?; + let mut eligible = [false; 8]; + let commands = (|| { + self.context.driver.api.copy_from(flags, &zero)?; + // The private vendor stream is NON_BLOCKING: drain all actual + // legacy uploads/reset before any stream consumer is enqueued. + self.context.driver.api.synchronize()?; + // Original gr_norm_rs block topology T*HC blocks, 256 threads. + self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch( + 0, + (self.tokens * 4) as u32, + 256, + blas.stream(), + &mut args[0], + )?; + self.launch(blas, 5, self.tokens * 10240, &mut args[1])?; + eligible[0] = true; + self.gemm(blas, 2, 3, w[1], 4, 320, 10240, alpha, beta0, beta1)?; + self.launch(blas, 4, self.tokens * 320, &mut args[2])?; + eligible[1] = true; + self.launch(blas, 1, self.tokens * 320, &mut args[3])?; + self.launch(blas, 6, self.tokens * 320, &mut args[4])?; + eligible[2] = true; + self.gemm(blas, 5, 6, w[2], 7, 10240, 320, alpha, beta0, beta1)?; + self.launch(blas, 4, self.tokens * 10240, &mut args[5])?; + eligible[3] = true; + // Literal Original executes inject GEMM BEFORE gr_mix_r. + self.gemm(blas, 2, 3, w[3], 12, 4, 10240, alpha, beta0, beta1)?; + self.launch(blas, 4, self.tokens * 4, &mut args[6])?; + eligible[6] = true; + self.launch(blas, 2, self.tokens * 2560, &mut args[7])?; + self.launch(blas, 7, self.tokens * 10240, &mut args[8])?; + eligible[4] = true; + self.launch(blas, 4, self.tokens * 2560, &mut args[9])?; + eligible[5] = true; + Ok(()) + })(); + self.finish(blas, commands, eligible, zero, args, readback, guard)?; + let mixed = decode(self.buffer(8)?)?; + let inject = decode(self.buffer(12)?)?; + self.phase = 1; + Ok(super::super::super::gr_batch_read::GrMicroValues { mixed, inject }) + } +} diff --git a/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/impl_grnativebatch_3.rs b/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/impl_grnativebatch_3.rs new file mode 100644 index 00000000..b53af944 --- /dev/null +++ b/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/impl_grnativebatch_3.rs @@ -0,0 +1,118 @@ +//! Moved out of the parent module by STRA-338: impl GrNativeBatch (3). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> GrNativeBatch<'ctx> { + pub fn inject( + &mut self, + blocks: &[f32], + workspace: &mut NativeBatchWorkspace<'ctx>, + ) -> Result> { + if self.phase != 1 { + return Err(Error::InvalidQwenShape); + } + workspace.validate_context(self.context)?; + self.validate(&[])?; + for (i, buffer) in self.buffers.iter().flatten().enumerate() { + workspace.reject_alias(self.handle(i)?, buffer.bytes)?; + } + let blas = workspace.blas()?; + if blocks.len() != self.tokens * 2560 { + return Err(Error::InvalidQwenShape); + } + if blocks.iter().any(|x| !x.is_finite()) { + return Err(Error::InvalidDriverValue("GR micro block finite")); + } + self.buffers[13] + .as_mut() + .ok_or(Error::ContextPoisoned)? + .copy_from_owned(encode(blocks)?)?; + let flags = self.handle(14)?; + let mut args = vec![ + Self::args(vec![ + A::Address(self.handle(0)?), + A::Address(self.handle(13)?), + A::Address(self.handle(12)?), + A::I64(4), + A::I64(self.tokens as i64), + ]), + self.scan(0, 10240, 7)?, + ]; + let zero = vec![0u8; 32 * self.tokens]; + let readback = vec![0u8; 32 * self.tokens]; + let context = self.context; + let guard = context.enter()?; + let mut eligible = [false; 8]; + let commands = (|| { + self.context.driver.api.copy_from(flags, &zero)?; + // The private vendor stream is NON_BLOCKING: drain all actual + // legacy uploads/reset before any stream consumer is enqueued. + self.context.driver.api.synchronize()?; + self.launch(blas, 3, self.tokens * 10240, &mut args[0])?; + self.launch(blas, 4, self.tokens * 10240, &mut args[1])?; + eligible[7] = true; + Ok(()) + })(); + // Original writes the real R bank in place. Any attempted failure + // retires this bank phase; no retry can add the same block twice. + // Mere completed numerical refusal does not poison the Context. + self.phase = 2; + self.finish(blas, commands, eligible, zero, args, readback, guard)?; + let values = decode(self.buffer(0)?)?; + self.phase = 0; + Ok(values) + } + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + pub(in super::super) fn close_inner(&mut self) -> Result<()> { + self.failed = true; + let mut result = Ok(()); + // Every returned operation drained this model's borrowed stream. + // Unknown completion already poisoned Context and retains ALL operands. + if let Some(module) = self.module.take() { + let closed = if self.context.is_poisoned() { + std::mem::forget(module); + self.context.retain_driver(); + Err(Error::ContextPoisoned) + } else { + match self.context.enter() { + Ok(guard) => combine(module.close(), guard.finish()), + Err(error) => { + std::mem::forget(module); + Err(error) + } + } + }; + if closed.is_err() { + self.context.poison(); + self.context.retain_driver(); + } + result = combine(result, closed); + } + if let Some(scalars) = self.scalars.take() { + if self.context.is_poisoned() { + std::mem::forget(scalars); + } + } + for slot in self.buffers.iter_mut().rev() { + if let Some(buffer) = slot.take() { + let closed = if self.context.is_poisoned() { + std::mem::forget(buffer); + self.context.retain_driver(); + Err(Error::ContextPoisoned) + } else { + buffer.release() + }; + if closed.is_err() { + self.context.poison(); + self.context.retain_driver(); + } + result = combine(result, closed); + } + } + result + } +} diff --git a/crates/cuda-driver/src/mapped_expert_bank/impl_mappedexpertbank.rs b/crates/cuda-driver/src/mapped_expert_bank/impl_mappedexpertbank.rs index 8ac5ae52..397cbdd0 100644 --- a/crates/cuda-driver/src/mapped_expert_bank/impl_mappedexpertbank.rs +++ b/crates/cuda-driver/src/mapped_expert_bank/impl_mappedexpertbank.rs @@ -3,513 +3,6 @@ #[allow(unused_imports)] use super::*; -impl<'ctx> MappedExpertBank<'ctx> { - pub(crate) fn cache_context_matches(&self, context: &Context<'_>) -> bool { - !self.closed && std::ptr::eq(self.context, context) - } - /// Validate the retained registered owner before the literal queued H2D - /// cache fill. The device alias is deliberately not exported to runtime. - pub(crate) fn cache_source(&self, span: &ResidentExpertBankSpan) -> Result<&[u8]> { - self.check(span)?; - let layer = match span.role() { - TensorRole::Layer { layer, .. } => layer, - _ => return Err(Error::InvalidSize), - }; - let role = match span.role() { - TensorRole::Layer { role, .. } => role, - _ => return Err(Error::InvalidSize), - }; - let n = usize::from(layer) * 3 - + match role { - LayerRole::FfnGateExperts => 0, - LayerRole::FfnUpExperts => 1, - LayerRole::FfnDownExperts => 2, - _ => return Err(Error::InvalidSize), - }; - let bank = self.banks.get(n).ok_or(Error::InvalidSize)?; - let end = span - .offset() - .checked_add(span.bytes().len()) - .ok_or(Error::InvalidSize)?; - bank.member - .bytes() - .get(span.offset()..end) - .ok_or(Error::InvalidSize) - } - /// The 4 KiB-aligned superset of `cache_source(span)` inside the same registered tensor and the offset of the span in it - /// (claude/ledger): the DMA engine reads host memory ~15 % faster from page-aligned runs (the expert pieces start at - /// `expert * piece_bytes`, i.e. at arbitrary offsets; job 907/9051 and the CUPTI ledger: 36-40 GB/s unaligned, 47-50 aligned). - /// The superset is clamped to the tensor (a registered range), so it never reads outside the bank. - pub(crate) fn cache_source_aligned(&self, span: &ResidentExpertBankSpan) -> Result<(&[u8], usize)> { - let exact = self.cache_source(span)?; - let layer = match span.role() { - TensorRole::Layer { layer, .. } => layer, - _ => return Err(Error::InvalidSize), - }; - let role = match span.role() { - TensorRole::Layer { role, .. } => role, - _ => return Err(Error::InvalidSize), - }; - let n = usize::from(layer) * 3 - + match role { - LayerRole::FfnGateExperts => 0, - LayerRole::FfnUpExperts => 1, - LayerRole::FfnDownExperts => 2, - _ => return Err(Error::InvalidSize), - }; - let member = self.banks.get(n).ok_or(Error::InvalidSize)?.member.bytes(); - let base = member.as_ptr() as usize; - let (start, end) = (exact.as_ptr() as usize, exact.as_ptr() as usize + exact.len()); - let a = (start & !(PAGE - 1)).max(base); - let b = ((end + PAGE - 1) & !(PAGE - 1)).min(base + member.len()); - if a > start || b < end { - return Err(Error::InvalidSize); - } - Ok((&member[a - base..b - base], start - a)) - } - pub(crate) fn retained_span_handle( - &self, - span: &ResidentExpertBankSpan, - ) -> Result { - crate::ffi::BufferHandle::registered_bank_alias(self.alias(span)?, span.bytes().len()) - } - pub fn page_overhead_bytes(&self) -> usize { - self.page_charge - } - pub fn source_bytes(&self) -> u64 { - self.lease.source_bytes() - } - pub fn metadata_bytes(&self) -> usize { - size_of::() - + 2 * size_of::() - + self.banks.capacity() * size_of::() - } - /// The gate/up/down host ranges (address, length) of `expert` of `layer`: the members hold 512 equal - /// per-expert extents in id order (the same extents `cache_source` returns for that expert's spans). - pub(crate) fn expert_pieces(&self, layer: u8, expert: u32) -> Result<[(usize, usize); 3]> { - if self.closed || self.context.is_poisoned() { - return Err(Error::ContextPoisoned); - } - if layer >= 48 || expert >= 512 { - return Err(Error::InvalidSize); - } - let mut pieces = [(0usize, 0usize); 3]; - for (role, piece) in pieces.iter_mut().enumerate() { - let bytes = self.banks[usize::from(layer) * 3 + role].member.bytes(); - if !bytes.len().is_multiple_of(512) { - return Err(Error::InvalidSize); - } - let each = bytes.len() / 512; - *piece = (bytes.as_ptr() as usize + expert as usize * each, each); - } - Ok(pieces) - } - /// `expert_pieces` as 4 KiB-aligned supersets clamped to the member: (address, length, lead) where `lead` is the offset of the - /// exact piece inside the superset (claude/ledger; the stream issuer copies the superset and reads the piece at `lead`). - pub(crate) fn expert_pieces_aligned(&self, layer: u8, expert: u32) -> Result<[(usize, usize, usize); 3]> { - let exact = self.expert_pieces(layer, expert)?; - let mut out = [(0usize, 0usize, 0usize); 3]; - for (role, piece) in out.iter_mut().enumerate() { - let member = self.banks[usize::from(layer) * 3 + role].member.bytes(); - let base = member.as_ptr() as usize; - let (start, end) = (exact[role].0, exact[role].0 + exact[role].1); - let a = (start & !(PAGE - 1)).max(base); - let b = ((end + PAGE - 1) & !(PAGE - 1)).min(base + member.len()); - *piece = (a, b - a, start - a); - } - Ok(out) - } - /// True for the low-RAM source: pageable file-mapped banks, no device aliases (see the field). - pub fn pageable(&self) -> bool { - self.pageable - } - - /// The low-RAM resident budget (generate.cpp `--resident-budget-gib` / `--resident-experts`, - /// `FileExpertSource::pin_cache_complement`): keep the experts `ranked` (hottest first, the caller leaves out - /// the ones the VRAM cache holds) resident in RAM, page-locked, while their gate/up/down bytes fit - /// `budget_bytes`. The Original copies them into a page-locked arena; here the bank's own file pages are - /// page-locked in place (read-only registration), which reads them in once and keeps them out of the OS's - /// reclaim, and makes their copies DMA. Answers are unchanged: the bytes are the same file pages. Only for - /// a pageable bank, once. Returns (experts held, bytes registered including page rounding). - pub fn pin_resident(&self, ranked: &[(u8, u32)], budget_bytes: u64) -> Result<(usize, u64)> { - if !self.pageable || self.closed || self.context.is_poisoned() { - return Err(Error::UnsupportedQwenOperation); - } - if !self.resident.borrow().is_empty() { - return Err(Error::InvalidSize); - } - let page = api::page_size()?; - let mut ranges: Vec<(usize, usize)> = Vec::new(); - let mut used = 0u64; - let mut held = 0usize; - for &(layer, expert) in ranked { - if layer >= 48 || expert >= 512 { - return Err(Error::InvalidSize); - } - let spans: Vec<(usize, usize)> = (0..3) - .map(|role| { - let bytes = self.banks[usize::from(layer) * 3 + role].member.bytes(); - let each = bytes.len() / 512; - (bytes.as_ptr() as usize + expert as usize * each, each) - }) - .collect(); - let need: u64 = spans.iter().map(|&(_, n)| n as u64).sum(); - if used + need > budget_bytes { - continue; - } - used += need; - held += 1; - ranges.extend(spans); - } - // page-round each span inside its own mapping, then merge overlapping/adjacent ranges per mapping - let mut rounded: Vec<(usize, usize)> = Vec::new(); - for &(start, len) in &ranges { - let bank = self - .banks - .iter() - .map(|b| b.member.bytes()) - .find(|b| { - let s = b.as_ptr() as usize; - start >= s && start + len <= s + b.len() - }) - .ok_or(Error::InvalidSize)?; - let lo = (bank.as_ptr() as usize) & !(page - 1); - let hi = (bank.as_ptr() as usize + bank.len()).next_multiple_of(page); - let a = (start & !(page - 1)).max(lo); - let b = (start + len).next_multiple_of(page).min(hi); - rounded.push((a, b)); - } - rounded.sort_unstable(); - let mut merged: Vec<(usize, usize)> = Vec::new(); - for (a, b) in rounded { - match merged.last_mut() { - // only merge inside one mapping: distinct mappings are distinct VMAs (never contiguous by - // assumption), so an overlap or touch can only be the same tensor's pages - Some(last) if a <= last.1 && self.same_mapping(last.0, b - 1) => last.1 = last.1.max(b), - _ => merged.push((a, b)), - } - } - let api = self.api.as_ref().ok_or(Error::ContextPoisoned)?; - let guard = self.context.enter()?; - let mut registered = 0u64; - let mut result = Ok(()); - for &(a, b) in &merged { - match api.register_read_only(a, b - a) { - Ok(()) => { - self.resident.borrow_mut().push((a, b - a)); - registered += (b - a) as u64; - } - Err(e) => { - result = Err(e); - break; - } - } - } - let result = combine(result, guard.finish()); - if let Err(primary) = result { - // leave nothing half-built: the copies still work from pageable memory - let guard = self.context.enter()?; - let mut cleanup = Ok(()); - for (start, _) in std::mem::take(&mut *self.resident.borrow_mut()) { - cleanup = combine(cleanup, api.unregister_at(start)); - } - return combine(Err(primary), combine(cleanup, guard.finish())); - } - Ok((held, registered)) - } - pub(super) fn same_mapping(&self, a: usize, b: usize) -> bool { - let page = api::page_size().unwrap_or(4096); - self.banks.iter().map(|x| x.member.bytes()).any(|x| { - let lo = (x.as_ptr() as usize) & !(page - 1); - let hi = (x.as_ptr() as usize + x.len()).next_multiple_of(page); - a >= lo && b < hi - }) - } - /// `bytes` (a `cache_source` slice) cut at every boundary of a `pin_resident` range, as (offset, length) - /// pieces: one H2D copy must not start in registered pages and run into unregistered ones (the driver - /// refuses it with CUDA_ERROR_INVALID_VALUE), so copy sites issue one copy per piece. One piece when nothing - /// is page-locked. - pub(crate) fn copy_pieces(&self, bytes: &[u8]) -> Vec<(usize, usize)> { - let resident = self.resident.borrow(); - let start = bytes.as_ptr() as usize; - let end = start + bytes.len(); - let mut cuts = vec![start, end]; - for &(a, n) in resident.iter() { - for c in [a, a + n] { - if c > start && c < end { - cuts.push(c); - } - } - } - cuts.sort_unstable(); - cuts.dedup(); - cuts.windows(2).map(|w| (w[0] - start, w[1] - w[0])).collect() - } - /// Whether the prompt path copies this expert through its pinned host staging (`HostStage` of the copy - /// ring, prefill.cpp's `Stager`): a pageable bank whose gate/up/down bytes are not all inside page-locked - /// `pin_resident` ranges. Those bytes are copied by helper threads into page-locked buffers, which also check - /// every block scale finite there, then DMA'd; the rest are DMA'd from the bank in place. - pub fn host_staged(&self, spans: &[ResidentExpertBankSpan; 3]) -> bool { - self.pageable && !spans.iter().all(|span| self.page_locked(span.bytes())) - } - pub(super) fn page_locked(&self, bytes: &[u8]) -> bool { - let start = bytes.as_ptr() as usize; - let end = start + bytes.len(); - self.resident.borrow().iter().any(|&(a, n)| start >= a && end <= a + n) - } - /// Which experts have all three pieces (gate, up, down) inside `pin_resident` ranges, indexed `layer * 512 + expert`: their copies - /// are DMA out of page-locked memory and never make the calling thread stage pageable pages. Empty for a registered - /// (non-pageable) bank, where every expert qualifies. - pub fn locked_experts(&self) -> Vec { - if !self.pageable { - return Vec::new(); - } - let mut ranges: Vec<(usize, usize)> = self.resident.borrow().clone(); - ranges.sort_unstable(); - let mut locked = vec![false; 48 * 512]; - for layer in 0..48u8 { - for expert in 0..512u32 { - locked[usize::from(layer) * 512 + expert as usize] = self - .expert_pieces(layer, expert) - .is_ok_and(|pieces| pieces.iter().all(|&(start, len)| range_covered(&ranges, start, len))); - } - } - locked - } - /// Bytes page-locked by `pin_resident`. - pub fn resident_bytes(&self) -> u64 { - self.resident.borrow().iter().map(|&(_, n)| n as u64).sum() - } - /// The device alias of a registered span for the verify window's PCIe copy kernel (`publish_gpu_plan`, pcie - /// mode 2): refused for pageable banks. The caller keeps the bank retained until the window's fence. - pub(crate) fn pcie_alias(&self, span: &ResidentExpertBankSpan) -> Result { - self.alias(span) - } - /// The device alias of a registered span: refused for pageable banks. - pub(super) fn alias(&self, span: &ResidentExpertBankSpan) -> Result { - let n = self.check(span)?; - if self.pageable { - return Err(Error::UnsupportedQwenOperation); - } - self.banks[n] - .alias - .checked_add(span.offset() as u64) - .ok_or(Error::InvalidSize) - } - /// Every check of a span against its retained bank except the device alias; returns the bank index. - pub(super) fn check(&self, span: &ResidentExpertBankSpan) -> Result { - if self.closed || self.context.is_poisoned() { - return Err(Error::ContextPoisoned); - } - let n = match span.role() { - TensorRole::Layer { layer, role } if layer < 48 => { - usize::from(layer) * 3 - + match role { - LayerRole::FfnGateExperts => 0, - LayerRole::FfnUpExperts => 1, - LayerRole::FfnDownExperts => 2, - _ => return Err(Error::InvalidSize), - } - } - _ => return Err(Error::InvalidSize), - }; - let bank = &self.banks[n]; - if (!bank.registered && !self.pageable) - || !span.belongs_to(&bank.member) - || span.bytes().is_empty() - || span - .offset() - .checked_add(span.bytes().len()) - .is_none_or(|n| n > bank.member.bytes().len()) - || !span.offset().is_multiple_of(16) - || !span.bytes().len().is_multiple_of(16) - { - return Err(Error::InvalidSize); - } - Ok(n) - } - pub fn eligible(&self, spans: &[ResidentExpertBankSpan; 3]) -> bool { - let layer = match spans[0].role() { - TensorRole::Layer { layer, .. } => layer, - _ => return false, - }; - spans.iter().enumerate().all(|(n, span)| { - let role = match n { - 0 => LayerRole::FfnGateExperts, - 1 => LayerRole::FfnUpExperts, - _ => LayerRole::FfnDownExperts, - }; - span.role() == TensorRole::Layer { layer, role } - && span.expert() == spans[0].expert() - && self.check(span).is_ok() - }) - } - pub fn copy_triplet( - self: &Rc, - spans: [ResidentExpertBankSpan; 3], - destinations: [DeviceBuffer<'ctx>; 3], - mut scratch: MappedExpertCopyScratch<'ctx>, - ) -> Result> { - let admitted = (|| { - if self.context.is_poisoned() { - return Err(Error::ContextPoisoned); - } - if !self.eligible(&spans) { - return Err(Error::InvalidSize); - } - if !std::ptr::eq(scratch.context, self.context) - || scratch.tables.len() != 6 - || scratch.arguments.len() != 3 - { - return Err(Error::ContextMismatch); - } - for (n, (span, destination)) in spans.iter().zip(&destinations).enumerate() { - self.alias(span)?; - if !std::ptr::eq(destination.context, self.context) { - return Err(Error::ContextMismatch); - } - if destination.bytes != span.bytes().len() { - return Err(Error::ShapeMismatch { - expected: span.bytes().len(), - actual: destination.bytes, - }); - } - let handle = destination.handle.ok_or(Error::ContextPoisoned)?; - handle.validate_extent(destination.bytes)?; - for prior in &destinations[..n] { - if handle.overlaps( - destination.bytes, - prior.handle.ok_or(Error::ContextPoisoned)?, - prior.bytes, - ) { - return Err(Error::OutputAliasesInput); - } - } - } - Ok(()) - })(); - if let Err(primary) = admitted { - return Err(primary); - } - // Exact fixed table/count owners per role. These completed tiny uploads - // precede the original byte kernels; no detached expert staging exists. - for (n, span) in spans.iter().enumerate() { - scratch.tables[n * 2].copy_from(&self.alias(span)?.to_le_bytes())?; - scratch.tables[n * 2 + 1].copy_from(&1i32.to_le_bytes())?; - } - let tables = std::mem::take(&mut scratch.tables); - let arguments = std::mem::take(&mut scratch.arguments); - let mut pending = PendingMappedExpertCopy { - bank: Some(Rc::clone(self)), - spans: Some(spans), - destinations: Some(destinations), - tables, - arguments, - stream: None, - event: None, - attempted: false, - recorded: false, - complete: false, - }; - let guard = self.context.enter()?; - let launched = (|| { - let api = self.api.as_ref().ok_or(Error::ContextPoisoned)?; - pending.stream = Some(api.stream()?); - pending.event = Some(api.event()?); - for n in 0..3 { - let actual = pending.destinations.as_ref().expect("owned triplet"); - pending.attempted = true; - pending.arguments[n] = api::MappedCopyArguments { - source: pending.tables[n * 2] - .handle - .ok_or(Error::ContextPoisoned)? - .qwen_address(), - count: pending.tables[n * 2 + 1] - .handle - .ok_or(Error::ContextPoisoned)? - .qwen_address(), - destination: actual[n] - .handle - .ok_or(Error::ContextPoisoned)? - .qwen_address(), - words: (actual[n].bytes / 16) as i64, - }; - api.copy_kernel( - &mut pending.arguments[n], - pending.stream.expect("actual stream"), - )?; - } - api.record( - pending.event.expect("actual event"), - pending.stream.expect("actual stream"), - )?; - pending.recorded = true; - Ok(()) - })(); - match combine(launched, guard.finish()) { - Ok(()) => Ok(pending), - Err(primary) => { - if pending.attempted || self.context.is_poisoned() { - pending.retain_uncertain(); - } else { - let _ = pending.cleanup(); - } - Err(primary) - } - } - } - pub(super) fn close_inner(&mut self) -> Result<()> { - if self.closed { - return Ok(()); - } - if self.context.is_poisoned() { - self.retain_uncertain(); - return Err(Error::ContextPoisoned); - } - let guard = self.context.enter()?; - let mut result = Ok(()); - if let Some(api) = &self.api { - for (start, _) in std::mem::take(&mut *self.resident.borrow_mut()) { - result = combine(result, api.unregister_at(start)); - } - for bank in &mut self.banks { - if bank.registered { - let unregister = api.unregister_bank(bank.member.bytes()); - if unregister.is_ok() { - bank.registered = false; - } - result = combine(result, unregister); - } - } - } - result = combine(result, guard.finish()); - if result.is_err() { - self.context.poisoned.set(true); - self.retain_uncertain(); - return result; - } - if let Some(api) = &mut self.api { - let guard = self.context.enter()?; - result = combine(api.close(), guard.finish()); - } - if result.is_err() { - self.context.poisoned.set(true); - self.retain_uncertain(); - return result; - } - self.closed = true; - Ok(()) - } - pub(super) fn retain_uncertain(&mut self) { - self.context.poisoned.set(true); - if let Some(api) = self.api.take() { - std::mem::forget(api); - } - std::mem::forget(std::mem::take(&mut self.banks)); - // Banks retain the identical original Rc catalog bytes. - self.closed = true; - } - pub fn close(mut self) -> Result<()> { - self.close_inner() - } -} +mod impl_mappedexpertbank_2; +mod impl_mappedexpertbank_2_2; +mod impl_mappedexpertbank_3; diff --git a/crates/cuda-driver/src/mapped_expert_bank/impl_mappedexpertbank/impl_mappedexpertbank_2.rs b/crates/cuda-driver/src/mapped_expert_bank/impl_mappedexpertbank/impl_mappedexpertbank_2.rs new file mode 100644 index 00000000..4ba7ac01 --- /dev/null +++ b/crates/cuda-driver/src/mapped_expert_bank/impl_mappedexpertbank/impl_mappedexpertbank_2.rs @@ -0,0 +1,256 @@ +//! Moved out of the parent module by STRA-338: impl MappedExpertBank. + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> MappedExpertBank<'ctx> { + pub(crate) fn cache_context_matches(&self, context: &Context<'_>) -> bool { + !self.closed && std::ptr::eq(self.context, context) + } + /// Validate the retained registered owner before the literal queued H2D + /// cache fill. The device alias is deliberately not exported to runtime. + pub(crate) fn cache_source(&self, span: &ResidentExpertBankSpan) -> Result<&[u8]> { + self.check(span)?; + let layer = match span.role() { + TensorRole::Layer { layer, .. } => layer, + _ => return Err(Error::InvalidSize), + }; + let role = match span.role() { + TensorRole::Layer { role, .. } => role, + _ => return Err(Error::InvalidSize), + }; + let n = usize::from(layer) * 3 + + match role { + LayerRole::FfnGateExperts => 0, + LayerRole::FfnUpExperts => 1, + LayerRole::FfnDownExperts => 2, + _ => return Err(Error::InvalidSize), + }; + let bank = self.banks.get(n).ok_or(Error::InvalidSize)?; + let end = span + .offset() + .checked_add(span.bytes().len()) + .ok_or(Error::InvalidSize)?; + bank.member + .bytes() + .get(span.offset()..end) + .ok_or(Error::InvalidSize) + } + /// The 4 KiB-aligned superset of `cache_source(span)` inside the same registered tensor and the offset of the span in it + /// (claude/ledger): the DMA engine reads host memory ~15 % faster from page-aligned runs (the expert pieces start at + /// `expert * piece_bytes`, i.e. at arbitrary offsets; job 907/9051 and the CUPTI ledger: 36-40 GB/s unaligned, 47-50 aligned). + /// The superset is clamped to the tensor (a registered range), so it never reads outside the bank. + pub(crate) fn cache_source_aligned(&self, span: &ResidentExpertBankSpan) -> Result<(&[u8], usize)> { + let exact = self.cache_source(span)?; + let layer = match span.role() { + TensorRole::Layer { layer, .. } => layer, + _ => return Err(Error::InvalidSize), + }; + let role = match span.role() { + TensorRole::Layer { role, .. } => role, + _ => return Err(Error::InvalidSize), + }; + let n = usize::from(layer) * 3 + + match role { + LayerRole::FfnGateExperts => 0, + LayerRole::FfnUpExperts => 1, + LayerRole::FfnDownExperts => 2, + _ => return Err(Error::InvalidSize), + }; + let member = self.banks.get(n).ok_or(Error::InvalidSize)?.member.bytes(); + let base = member.as_ptr() as usize; + let (start, end) = (exact.as_ptr() as usize, exact.as_ptr() as usize + exact.len()); + let a = (start & !(PAGE - 1)).max(base); + let b = ((end + PAGE - 1) & !(PAGE - 1)).min(base + member.len()); + if a > start || b < end { + return Err(Error::InvalidSize); + } + Ok((&member[a - base..b - base], start - a)) + } + pub(crate) fn retained_span_handle( + &self, + span: &ResidentExpertBankSpan, + ) -> Result { + crate::ffi::BufferHandle::registered_bank_alias(self.alias(span)?, span.bytes().len()) + } + pub fn page_overhead_bytes(&self) -> usize { + self.page_charge + } + pub fn source_bytes(&self) -> u64 { + self.lease.source_bytes() + } + pub fn metadata_bytes(&self) -> usize { + size_of::() + + 2 * size_of::() + + self.banks.capacity() * size_of::() + } + /// The gate/up/down host ranges (address, length) of `expert` of `layer`: the members hold 512 equal + /// per-expert extents in id order (the same extents `cache_source` returns for that expert's spans). + pub(crate) fn expert_pieces(&self, layer: u8, expert: u32) -> Result<[(usize, usize); 3]> { + if self.closed || self.context.is_poisoned() { + return Err(Error::ContextPoisoned); + } + if layer >= 48 || expert >= 512 { + return Err(Error::InvalidSize); + } + let mut pieces = [(0usize, 0usize); 3]; + for (role, piece) in pieces.iter_mut().enumerate() { + let bytes = self.banks[usize::from(layer) * 3 + role].member.bytes(); + if !bytes.len().is_multiple_of(512) { + return Err(Error::InvalidSize); + } + let each = bytes.len() / 512; + *piece = (bytes.as_ptr() as usize + expert as usize * each, each); + } + Ok(pieces) + } + /// `expert_pieces` as 4 KiB-aligned supersets clamped to the member: (address, length, lead) where `lead` is the offset of the + /// exact piece inside the superset (claude/ledger; the stream issuer copies the superset and reads the piece at `lead`). + pub(crate) fn expert_pieces_aligned(&self, layer: u8, expert: u32) -> Result<[(usize, usize, usize); 3]> { + let exact = self.expert_pieces(layer, expert)?; + let mut out = [(0usize, 0usize, 0usize); 3]; + for (role, piece) in out.iter_mut().enumerate() { + let member = self.banks[usize::from(layer) * 3 + role].member.bytes(); + let base = member.as_ptr() as usize; + let (start, end) = (exact[role].0, exact[role].0 + exact[role].1); + let a = (start & !(PAGE - 1)).max(base); + let b = ((end + PAGE - 1) & !(PAGE - 1)).min(base + member.len()); + *piece = (a, b - a, start - a); + } + Ok(out) + } + /// True for the low-RAM source: pageable file-mapped banks, no device aliases (see the field). + pub fn pageable(&self) -> bool { + self.pageable + } + + /// The low-RAM resident budget (generate.cpp `--resident-budget-gib` / `--resident-experts`, + /// `FileExpertSource::pin_cache_complement`): keep the experts `ranked` (hottest first, the caller leaves out + /// the ones the VRAM cache holds) resident in RAM, page-locked, while their gate/up/down bytes fit + /// `budget_bytes`. The Original copies them into a page-locked arena; here the bank's own file pages are + /// page-locked in place (read-only registration), which reads them in once and keeps them out of the OS's + /// reclaim, and makes their copies DMA. Answers are unchanged: the bytes are the same file pages. Only for + /// a pageable bank, once. Returns (experts held, bytes registered including page rounding). + pub fn pin_resident(&self, ranked: &[(u8, u32)], budget_bytes: u64) -> Result<(usize, u64)> { + if !self.pageable || self.closed || self.context.is_poisoned() { + return Err(Error::UnsupportedQwenOperation); + } + if !self.resident.borrow().is_empty() { + return Err(Error::InvalidSize); + } + let page = api::page_size()?; + let mut ranges: Vec<(usize, usize)> = Vec::new(); + let mut used = 0u64; + let mut held = 0usize; + for &(layer, expert) in ranked { + if layer >= 48 || expert >= 512 { + return Err(Error::InvalidSize); + } + let spans: Vec<(usize, usize)> = (0..3) + .map(|role| { + let bytes = self.banks[usize::from(layer) * 3 + role].member.bytes(); + let each = bytes.len() / 512; + (bytes.as_ptr() as usize + expert as usize * each, each) + }) + .collect(); + let need: u64 = spans.iter().map(|&(_, n)| n as u64).sum(); + if used + need > budget_bytes { + continue; + } + used += need; + held += 1; + ranges.extend(spans); + } + // page-round each span inside its own mapping, then merge overlapping/adjacent ranges per mapping + let mut rounded: Vec<(usize, usize)> = Vec::new(); + for &(start, len) in &ranges { + let bank = self + .banks + .iter() + .map(|b| b.member.bytes()) + .find(|b| { + let s = b.as_ptr() as usize; + start >= s && start + len <= s + b.len() + }) + .ok_or(Error::InvalidSize)?; + let lo = (bank.as_ptr() as usize) & !(page - 1); + let hi = (bank.as_ptr() as usize + bank.len()).next_multiple_of(page); + let a = (start & !(page - 1)).max(lo); + let b = (start + len).next_multiple_of(page).min(hi); + rounded.push((a, b)); + } + rounded.sort_unstable(); + let mut merged: Vec<(usize, usize)> = Vec::new(); + for (a, b) in rounded { + match merged.last_mut() { + // only merge inside one mapping: distinct mappings are distinct VMAs (never contiguous by + // assumption), so an overlap or touch can only be the same tensor's pages + Some(last) if a <= last.1 && self.same_mapping(last.0, b - 1) => last.1 = last.1.max(b), + _ => merged.push((a, b)), + } + } + let api = self.api.as_ref().ok_or(Error::ContextPoisoned)?; + let guard = self.context.enter()?; + let mut registered = 0u64; + let mut result = Ok(()); + for &(a, b) in &merged { + match api.register_read_only(a, b - a) { + Ok(()) => { + self.resident.borrow_mut().push((a, b - a)); + registered += (b - a) as u64; + } + Err(e) => { + result = Err(e); + break; + } + } + } + let result = combine(result, guard.finish()); + if let Err(primary) = result { + // leave nothing half-built: the copies still work from pageable memory + let guard = self.context.enter()?; + let mut cleanup = Ok(()); + for (start, _) in std::mem::take(&mut *self.resident.borrow_mut()) { + cleanup = combine(cleanup, api.unregister_at(start)); + } + return combine(Err(primary), combine(cleanup, guard.finish())); + } + Ok((held, registered)) + } + pub(in super::super) fn same_mapping(&self, a: usize, b: usize) -> bool { + let page = api::page_size().unwrap_or(4096); + self.banks.iter().map(|x| x.member.bytes()).any(|x| { + let lo = (x.as_ptr() as usize) & !(page - 1); + let hi = (x.as_ptr() as usize + x.len()).next_multiple_of(page); + a >= lo && b < hi + }) + } + /// `bytes` (a `cache_source` slice) cut at every boundary of a `pin_resident` range, as (offset, length) + /// pieces: one H2D copy must not start in registered pages and run into unregistered ones (the driver + /// refuses it with CUDA_ERROR_INVALID_VALUE), so copy sites issue one copy per piece. One piece when nothing + /// is page-locked. + pub(crate) fn copy_pieces(&self, bytes: &[u8]) -> Vec<(usize, usize)> { + let resident = self.resident.borrow(); + let start = bytes.as_ptr() as usize; + let end = start + bytes.len(); + let mut cuts = vec![start, end]; + for &(a, n) in resident.iter() { + for c in [a, a + n] { + if c > start && c < end { + cuts.push(c); + } + } + } + cuts.sort_unstable(); + cuts.dedup(); + cuts.windows(2).map(|w| (w[0] - start, w[1] - w[0])).collect() + } + /// Whether the prompt path copies this expert through its pinned host staging (`HostStage` of the copy + /// ring, prefill.cpp's `Stager`): a pageable bank whose gate/up/down bytes are not all inside page-locked + /// `pin_resident` ranges. Those bytes are copied by helper threads into page-locked buffers, which also check + /// every block scale finite there, then DMA'd; the rest are DMA'd from the bank in place. + pub fn host_staged(&self, spans: &[ResidentExpertBankSpan; 3]) -> bool { + self.pageable && !spans.iter().all(|span| self.page_locked(span.bytes())) + } +} diff --git a/crates/cuda-driver/src/mapped_expert_bank/impl_mappedexpertbank/impl_mappedexpertbank_2_2.rs b/crates/cuda-driver/src/mapped_expert_bank/impl_mappedexpertbank/impl_mappedexpertbank_2_2.rs new file mode 100644 index 00000000..7d66a977 --- /dev/null +++ b/crates/cuda-driver/src/mapped_expert_bank/impl_mappedexpertbank/impl_mappedexpertbank_2_2.rs @@ -0,0 +1,256 @@ +//! Moved out of the parent module by STRA-338: impl MappedExpertBank (2). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> MappedExpertBank<'ctx> { + pub(in super::super) fn page_locked(&self, bytes: &[u8]) -> bool { + let start = bytes.as_ptr() as usize; + let end = start + bytes.len(); + self.resident.borrow().iter().any(|&(a, n)| start >= a && end <= a + n) + } + /// Which experts have all three pieces (gate, up, down) inside `pin_resident` ranges, indexed `layer * 512 + expert`: their copies + /// are DMA out of page-locked memory and never make the calling thread stage pageable pages. Empty for a registered + /// (non-pageable) bank, where every expert qualifies. + pub fn locked_experts(&self) -> Vec { + if !self.pageable { + return Vec::new(); + } + let mut ranges: Vec<(usize, usize)> = self.resident.borrow().clone(); + ranges.sort_unstable(); + let mut locked = vec![false; 48 * 512]; + for layer in 0..48u8 { + for expert in 0..512u32 { + locked[usize::from(layer) * 512 + expert as usize] = self + .expert_pieces(layer, expert) + .is_ok_and(|pieces| pieces.iter().all(|&(start, len)| range_covered(&ranges, start, len))); + } + } + locked + } + /// Bytes page-locked by `pin_resident`. + pub fn resident_bytes(&self) -> u64 { + self.resident.borrow().iter().map(|&(_, n)| n as u64).sum() + } + /// The device alias of a registered span for the verify window's PCIe copy kernel (`publish_gpu_plan`, pcie + /// mode 2): refused for pageable banks. The caller keeps the bank retained until the window's fence. + pub(crate) fn pcie_alias(&self, span: &ResidentExpertBankSpan) -> Result { + self.alias(span) + } + /// The device alias of a registered span: refused for pageable banks. + pub(in super::super) fn alias(&self, span: &ResidentExpertBankSpan) -> Result { + let n = self.check(span)?; + if self.pageable { + return Err(Error::UnsupportedQwenOperation); + } + self.banks[n] + .alias + .checked_add(span.offset() as u64) + .ok_or(Error::InvalidSize) + } + /// Every check of a span against its retained bank except the device alias; returns the bank index. + pub(in super::super) fn check(&self, span: &ResidentExpertBankSpan) -> Result { + if self.closed || self.context.is_poisoned() { + return Err(Error::ContextPoisoned); + } + let n = match span.role() { + TensorRole::Layer { layer, role } if layer < 48 => { + usize::from(layer) * 3 + + match role { + LayerRole::FfnGateExperts => 0, + LayerRole::FfnUpExperts => 1, + LayerRole::FfnDownExperts => 2, + _ => return Err(Error::InvalidSize), + } + } + _ => return Err(Error::InvalidSize), + }; + let bank = &self.banks[n]; + if (!bank.registered && !self.pageable) + || !span.belongs_to(&bank.member) + || span.bytes().is_empty() + || span + .offset() + .checked_add(span.bytes().len()) + .is_none_or(|n| n > bank.member.bytes().len()) + || !span.offset().is_multiple_of(16) + || !span.bytes().len().is_multiple_of(16) + { + return Err(Error::InvalidSize); + } + Ok(n) + } + pub fn eligible(&self, spans: &[ResidentExpertBankSpan; 3]) -> bool { + let layer = match spans[0].role() { + TensorRole::Layer { layer, .. } => layer, + _ => return false, + }; + spans.iter().enumerate().all(|(n, span)| { + let role = match n { + 0 => LayerRole::FfnGateExperts, + 1 => LayerRole::FfnUpExperts, + _ => LayerRole::FfnDownExperts, + }; + span.role() == TensorRole::Layer { layer, role } + && span.expert() == spans[0].expert() + && self.check(span).is_ok() + }) + } + pub fn copy_triplet( + self: &Rc, + spans: [ResidentExpertBankSpan; 3], + destinations: [DeviceBuffer<'ctx>; 3], + mut scratch: MappedExpertCopyScratch<'ctx>, + ) -> Result> { + let admitted = (|| { + if self.context.is_poisoned() { + return Err(Error::ContextPoisoned); + } + if !self.eligible(&spans) { + return Err(Error::InvalidSize); + } + if !std::ptr::eq(scratch.context, self.context) + || scratch.tables.len() != 6 + || scratch.arguments.len() != 3 + { + return Err(Error::ContextMismatch); + } + for (n, (span, destination)) in spans.iter().zip(&destinations).enumerate() { + self.alias(span)?; + if !std::ptr::eq(destination.context, self.context) { + return Err(Error::ContextMismatch); + } + if destination.bytes != span.bytes().len() { + return Err(Error::ShapeMismatch { + expected: span.bytes().len(), + actual: destination.bytes, + }); + } + let handle = destination.handle.ok_or(Error::ContextPoisoned)?; + handle.validate_extent(destination.bytes)?; + for prior in &destinations[..n] { + if handle.overlaps( + destination.bytes, + prior.handle.ok_or(Error::ContextPoisoned)?, + prior.bytes, + ) { + return Err(Error::OutputAliasesInput); + } + } + } + Ok(()) + })(); + if let Err(primary) = admitted { + return Err(primary); + } + // Exact fixed table/count owners per role. These completed tiny uploads + // precede the original byte kernels; no detached expert staging exists. + for (n, span) in spans.iter().enumerate() { + scratch.tables[n * 2].copy_from(&self.alias(span)?.to_le_bytes())?; + scratch.tables[n * 2 + 1].copy_from(&1i32.to_le_bytes())?; + } + let tables = std::mem::take(&mut scratch.tables); + let arguments = std::mem::take(&mut scratch.arguments); + let mut pending = PendingMappedExpertCopy { + bank: Some(Rc::clone(self)), + spans: Some(spans), + destinations: Some(destinations), + tables, + arguments, + stream: None, + event: None, + attempted: false, + recorded: false, + complete: false, + }; + let guard = self.context.enter()?; + let launched = (|| { + let api = self.api.as_ref().ok_or(Error::ContextPoisoned)?; + pending.stream = Some(api.stream()?); + pending.event = Some(api.event()?); + for n in 0..3 { + let actual = pending.destinations.as_ref().expect("owned triplet"); + pending.attempted = true; + pending.arguments[n] = api::MappedCopyArguments { + source: pending.tables[n * 2] + .handle + .ok_or(Error::ContextPoisoned)? + .qwen_address(), + count: pending.tables[n * 2 + 1] + .handle + .ok_or(Error::ContextPoisoned)? + .qwen_address(), + destination: actual[n] + .handle + .ok_or(Error::ContextPoisoned)? + .qwen_address(), + words: (actual[n].bytes / 16) as i64, + }; + api.copy_kernel( + &mut pending.arguments[n], + pending.stream.expect("actual stream"), + )?; + } + api.record( + pending.event.expect("actual event"), + pending.stream.expect("actual stream"), + )?; + pending.recorded = true; + Ok(()) + })(); + match combine(launched, guard.finish()) { + Ok(()) => Ok(pending), + Err(primary) => { + if pending.attempted || self.context.is_poisoned() { + pending.retain_uncertain(); + } else { + let _ = pending.cleanup(); + } + Err(primary) + } + } + } + pub(in super::super) fn close_inner(&mut self) -> Result<()> { + if self.closed { + return Ok(()); + } + if self.context.is_poisoned() { + self.retain_uncertain(); + return Err(Error::ContextPoisoned); + } + let guard = self.context.enter()?; + let mut result = Ok(()); + if let Some(api) = &self.api { + for (start, _) in std::mem::take(&mut *self.resident.borrow_mut()) { + result = combine(result, api.unregister_at(start)); + } + for bank in &mut self.banks { + if bank.registered { + let unregister = api.unregister_bank(bank.member.bytes()); + if unregister.is_ok() { + bank.registered = false; + } + result = combine(result, unregister); + } + } + } + result = combine(result, guard.finish()); + if result.is_err() { + self.context.poisoned.set(true); + self.retain_uncertain(); + return result; + } + if let Some(api) = &mut self.api { + let guard = self.context.enter()?; + result = combine(api.close(), guard.finish()); + } + if result.is_err() { + self.context.poisoned.set(true); + self.retain_uncertain(); + return result; + } + self.closed = true; + Ok(()) + } +} diff --git a/crates/cuda-driver/src/mapped_expert_bank/impl_mappedexpertbank/impl_mappedexpertbank_3.rs b/crates/cuda-driver/src/mapped_expert_bank/impl_mappedexpertbank/impl_mappedexpertbank_3.rs new file mode 100644 index 00000000..01c6693e --- /dev/null +++ b/crates/cuda-driver/src/mapped_expert_bank/impl_mappedexpertbank/impl_mappedexpertbank_3.rs @@ -0,0 +1,20 @@ +//! Moved out of the parent module by STRA-338: impl MappedExpertBank (3). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> MappedExpertBank<'ctx> { + pub(in super::super) fn retain_uncertain(&mut self) { + self.context.poisoned.set(true); + if let Some(api) = self.api.take() { + std::mem::forget(api); + } + std::mem::forget(std::mem::take(&mut self.banks)); + // Banks retain the identical original Rc catalog bytes. + self.closed = true; + } + pub fn close(mut self) -> Result<()> { + self.close_inner() + } +} diff --git a/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer.rs b/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer.rs index 6666ecf2..7584beb5 100644 --- a/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer.rs +++ b/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer.rs @@ -3,592 +3,9 @@ #[allow(unused_imports)] use super::*; -impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { - pub(super) fn bank(&self) -> Result<&OriginalGroupBank<'ctx>> { - self.workspace.check()?; - self.workspace - .original_group - .as_ref() - .ok_or(Error::UnsupportedProjection) - } - pub(super) fn span(&self, index: usize) -> Result<(ffi::BufferHandle, usize)> { - let b = self.bank()?; - if index != TMP { - if let Some(arena) = self.arena { - return arena.span(index); - } - } - let owner = b.buffer(index)?; - Ok((owner.handle.ok_or(Error::ContextPoisoned)?, owner.bytes)) - } - pub(super) fn handle( - &self, - index: usize, - offset: usize, - bytes: usize, - align: u64, - ) -> Result { - let (h, n) = self.span(index)?; - let group = if self.arena.is_some() && matches!(index, H | D) { - (self.bounds[self.next] as usize) - .checked_mul(if index == H { 640 * 4 } else { 2560 * 4 }) - .ok_or(Error::InvalidProjectionShape)? - } else { - 0 - }; - let h = h.checked_subspan( - n, - group - .checked_add(offset) - .ok_or(Error::InvalidProjectionShape)?, - bytes, - )?; - h.validate_projection_extent(bytes, align)?; - Ok(h) - } - pub(super) fn reject_arena_alias(&self, h: ffi::BufferHandle, bytes: usize) -> Result<()> { - if let Some(arena) = self.arena { - for index in 0..TMP { - let (a, n) = arena.span(index)?; - if h.overlaps(bytes, a, n) { - return Err(Error::OutputAliasesInput); - } - } - } - Ok(()) - } - pub(super) fn finite( - &self, - commands: Vec, - source: ffi::BufferHandle, - amount: usize, - q8: bool, - label: &'static str, - ) -> Result<()> { - let w = &*self.workspace; - let status = w.handle(STATUS, 4, 4)?; - let tail = if q8 { 128 * 144 } else { 0 }; - let mut cmds = commands; - if cmds.len() > 3 { - return Err(Error::InvalidProjectionShape); - } - cmds.push(w.zero_command(STATUS, 4)?); - cmds.push(QueuedCommand::OriginalHelper( - w.kernel(1)?, - ((if q8 { amount * 144 + tail } else { amount * 4 }) / 4) as u32, - ffi::MmqResidentArguments::finite( - source, - status, - u32::from(q8), - amount as u32, - tail as u32, - ), - )); - match w.run_queued(cmds, Some(status))? { - 0 => Ok(()), - 1 | 3 if q8 => Err(Error::InvalidQ8Activation), - 2 if q8 => Err(Error::InvalidDriverValue("Original grouped Q8 tail")), - 1 => Err(Error::NonFiniteMmqOutput(label)), - _ => Err(Error::InvalidDriverValue("Original grouped finite status")), - } - } - pub(super) fn quantize( - &self, - input: usize, - packed: usize, - tokens: u32, - columns: u32, - ids: Option, - ) -> Result<()> { - let b = self.bank()?; - let f = if columns == 2560 { - MmqFormat::Iq3XxsGateUp - } else { - MmqFormat::Iq4NlDown - }; - let l = layout(f, if columns == 2560 { 1280 } else { 2560 }, tokens, 64)?; - let ih = self.handle( - input, - 0, - if ids.is_some() { - b.capacity as usize * 10240 - } else { - l.input - }, - 16, - )?; - let qh = self.handle(packed, 0, l.packed, 16)?; - let mut cmds = commands()?; - cmds.push(QueuedCommand::OriginalHelper( - self.workspace.kernel(0)?, - (l.packed / 4) as u32, - ffi::MmqResidentArguments::zero(qh, (l.packed / 4) as u32), - )); - let id_handle = ids - .map(|i| self.handle(i, 0, tokens as usize * 4, 4)) - .transpose()?; - let args = ffi::MmqQuantArguments::original_indexed(ih, id_handle, qh, l); - cmds.push(QueuedCommand::Quantize( - self.workspace - .experiment - .as_ref() - .ok_or(Error::ContextPoisoned)? - .quantizer - .ok_or(Error::ContextPoisoned)?, - l, - args, - )); - self.finite(cmds, qh, l.payload / 144, true, "Q8") - } - pub(super) fn quantize_device_mixed(&self, input: ffi::BufferHandle) -> Result<()> { - let b = self.bank()?; - let l = layout(MmqFormat::Iq3XxsGateUp, 1280, self.total, 64)?; - let qh = self.handle(XQ, 0, l.packed, 16)?; - let ids = self.handle(ROW_IDS, 0, self.total as usize * 4, 4)?; - let mut cmds = commands()?; - cmds.push(QueuedCommand::OriginalHelper( - self.workspace.kernel(0)?, - (l.packed / 4) as u32, - ffi::MmqResidentArguments::zero(qh, (l.packed / 4) as u32), - )); - cmds.push(QueuedCommand::Quantize( - self.workspace - .experiment - .as_ref() - .ok_or(Error::ContextPoisoned)? - .quantizer - .ok_or(Error::ContextPoisoned)?, - l, - ffi::MmqQuantArguments::original_indexed(input, Some(ids), qh, l), - )); - self.finite(cmds, qh, l.payload / 144, true, "Q8") - } - pub fn stage_expert( - &mut self, - formats: [MmqFormat; 3], - raw: [&DeviceBuffer<'_>; 3], - ) -> Result<()> { - let n = (self.counts.len() - self.next).min(16); - if self.completed || self.staged >= n { - return Err(Error::InvalidProjectionShape); - } - if formats[0] != formats[1] - || !FORMATS[..5].contains(&formats[0]) - || !FORMATS[5..].contains(&formats[2]) - || self.formats.is_some_and(|f| f != formats) - { - return Err(Error::UnsupportedProjection); - } - let b = self.bank()?; - let gu = formats[0].layout(1)?; - let down = formats[2].layout(1)?; - let wh = self.handle(WG, self.staged * gu.raw_weight * 2, gu.raw_weight * 2, 4)?; - let dh = self.handle(WD, self.staged * down.raw_weight, down.raw_weight, 4)?; - let mut handles = [None; 3]; - for (i, source) in raw.into_iter().enumerate() { - let expected = if i < 2 { - gu.raw_weight - } else { - down.raw_weight - }; - let alignment = if formats[i] == MmqFormat::Iq4XsGateUp { - 4 - } else { - 2 - }; - if source.bytes != expected { - return Err(Error::InvalidProjectionShape); - } - if !std::ptr::eq(b.context, source.context) { - return Err(Error::ContextMismatch); - } - let h = source.handle.ok_or(Error::ContextPoisoned)?; - h.validate_projection_extent(expected, alignment)?; - for prior in raw.iter().take(i) { - if h.overlaps( - expected, - prior.handle.ok_or(Error::ContextPoisoned)?, - prior.bytes, - ) { - return Err(Error::OutputAliasesInput); - } - } - for owner in b - .buffers - .iter() - .chain(self.workspace.buffers.iter()) - .flatten() - { - if h.overlaps( - expected, - owner.handle.ok_or(Error::ContextPoisoned)?, - owner.bytes, - ) { - return Err(Error::OutputAliasesInput); - } - } - self.reject_arena_alias(h, expected)?; - handles[i] = Some(h); - } - let raw = [ - handles[0].ok_or(Error::ContextPoisoned)?, - handles[1].ok_or(Error::ContextPoisoned)?, - handles[2].ok_or(Error::ContextPoisoned)?, - ]; - self.stage_raw(formats, raw) - } - - pub(super) fn stage_raw(&mut self, formats: [MmqFormat; 3], raw: [ffi::BufferHandle; 3]) -> Result<()> { - let n = (self.counts.len() - self.next).min(16); - if self.completed || self.staged >= n { - return Err(Error::InvalidProjectionShape); - } - if formats[0] != formats[1] - || !FORMATS[..5].contains(&formats[0]) - || !FORMATS[5..].contains(&formats[2]) - || self.formats.is_some_and(|f| f != formats) - { - return Err(Error::UnsupportedProjection); - } - let b = self.bank()?; - let gu = formats[0].layout(1)?; - let down = formats[2].layout(1)?; - let wh = self.handle(WG, self.staged * gu.raw_weight * 2, gu.raw_weight * 2, 4)?; - let dh = self.handle(WD, self.staged * down.raw_weight, down.raw_weight, 4)?; - for (i, h) in raw.iter().enumerate() { - let amount = if i < 2 { - gu.raw_weight - } else { - down.raw_weight - }; - h.validate_projection_extent(amount, 16)?; - for (j, prior) in raw.iter().take(i).enumerate() { - let prior_amount = if j < 2 { - gu.raw_weight - } else { - down.raw_weight - }; - if h.overlaps(amount, *prior, prior_amount) { - return Err(Error::OutputAliasesInput); - } - } - for owner in b - .buffers - .iter() - .chain(self.workspace.buffers.iter()) - .flatten() - { - if h.overlaps( - amount, - owner.handle.ok_or(Error::ContextPoisoned)?, - owner.bytes, - ) { - return Err(Error::OutputAliasesInput); - } - } - } - for (i, h) in raw.iter().enumerate() { - self.reject_arena_alias( - *h, - if i < 2 { - gu.raw_weight - } else { - down.raw_weight - }, - )?; - } - // All admitted formats have real 16-byte-aligned lengths/owners. This is - // exactly Original gather_native's copy16 branch, not three host-staged copies. - wh.validate_projection_extent(gu.raw_weight * 2, 16)?; - dh.validate_projection_extent(down.raw_weight, 16)?; - for (h, bytes) in [ - (raw[0], gu.raw_weight), - (raw[1], gu.raw_weight), - (raw[2], down.raw_weight), - ] { - h.validate_projection_extent(bytes, 16)?; - } - let mut commands = commands()?; - commands.push(QueuedCommand::OriginalGather( - b.gather.ok_or(Error::ContextPoisoned)?, - ((gu.raw_weight * 2 + down.raw_weight) / 16) as u32, - ffi::MmqOriginalGatherArguments::new(raw, wh, dh, gu.raw_weight, down.raw_weight), - )); - self.workspace.run_queued(commands, None)?; - self.formats = Some(formats); - self.staged += 1; - Ok(()) - } - /// Gather actual registered immutable source slices. No raw address or - /// fabricated DeviceBuffer can be supplied by the runtime caller. - pub fn stage_expert_retained( - &mut self, - formats: [MmqFormat; 3], - bank: &crate::MappedExpertBank<'ctx>, - spans: &[leleka_model_format::qwen4exp::ResidentExpertBankSpan; 3], - ) -> Result<()> { - if !bank.cache_context_matches(self.workspace.context) || !bank.eligible(spans) { - return Err(Error::ContextMismatch); - } - let gu = formats[0].layout(1)?; - let down = formats[2].layout(1)?; - for (i, span) in spans.iter().enumerate() { - if span.raw_kind() != kind(formats[i]) - || span.bytes().len() - != if i < 2 { - gu.raw_weight - } else { - down.raw_weight - } - { - return Err(Error::InvalidProjectionShape); - } - } - let handles = [ - bank.retained_span_handle(&spans[0])?, - bank.retained_span_handle(&spans[1])?, - bank.retained_span_handle(&spans[2])?, - ]; - // stage_raw performs an actual full gather drain before releasing this bank borrow. - self.stage_raw(formats, handles) - } - /// Only a completed real cache prefix inside this affine prompt arena is - /// eligible. Lent/scratch bytes remain misses; the cache owner cannot refill - /// them while the prompt rows hold its allocation's mutable tail loan. - pub fn stage_expert_from_prompt_cache( - &mut self, - read: &crate::OriginalDeviceGrRead<'_, '_, 'ctx>, - layer: usize, - expert: usize, - formats: [MmqFormat; 3], - ) -> Result { - if !read.context_matches(self.workspace.context) { - return Err(Error::ContextMismatch); - } - let Some((blob, extent)) = read.lease().cache_expert_span(layer, expert)? else { - return Ok(false); - }; - let gu = formats[0].layout(1)?; - let down = formats[2].layout(1)?; - let amount = gu - .raw_weight - .checked_mul(2) - .and_then(|n| n.checked_add(down.raw_weight)) - .ok_or(Error::InvalidProjectionShape)?; - if amount > extent { - return Err(Error::InvalidProjectionShape); - } - self.stage_raw( - formats, - [ - blob.checked_subspan(extent, 0, gu.raw_weight)?, - blob.checked_subspan(extent, gu.raw_weight, gu.raw_weight)?, - blob.checked_subspan(extent, gu.raw_weight * 2, down.raw_weight)?, - ], - )?; - Ok(true) - } - - pub(super) fn project( - &self, - format: MmqFormat, - weights: usize, - packed: usize, - out: usize, - down: bool, - width: u32, - ) -> Result<()> { - let b = self.bank()?; - let experts = self.staged as u32; - let nr = self.bounds[self.next + self.staged] - self.bounds[self.next]; - let rows = if down { 2560 } else { 1280 }; - let tokens = if down { nr } else { self.total }; - let l = layout(format, rows, tokens, width)?; - let fi = format_index(format)?; - let ti = WIDTHS - .iter() - .position(|j| *j == width) - .ok_or(Error::UnsupportedProjection)?; - let f = b.functions[fi][ti].ok_or(Error::UnsupportedProjection)?; - let fix = b.fixups[fi][ti].ok_or(Error::UnsupportedProjection)?; - let maxr = self.counts[self.next..self.next + self.staged] - .iter() - .copied() - .max() - .ok_or(Error::InvalidProjectionShape)?; - let ntx = maxr.div_ceil(width); - let tiles = (rows / 128) - .checked_mul(ntx) - .and_then(|n| n.checked_mul(experts)) - .ok_or(Error::InvalidProjectionShape)?; - if tiles - .checked_mul(l.columns / l.qk) - .is_none_or(|n| n >= 1 << 30) - { - return Err(Error::InvalidProjectionShape); - } - let sms = self - .workspace - .experiment - .as_ref() - .ok_or(Error::ContextPoisoned)? - .sms; - let efficiency = 100 * tiles / (sms * tiles.div_ceil(sms)); - let grid = if efficiency >= 90 || crate::arch_ptx::stream_k_off() { tiles } else { sms }; - let needs_fix = !tiles.is_multiple_of(grid); - let wh = self.handle(weights, 0, l.raw_weight * experts as usize + 4096, 4)?; - let ph = self.handle(packed, 0, l.packed, 16)?; - let oh = self.handle(out, 0, l.output, 4)?; - let ids = self.handle(IDENTITY, 0, tokens as usize * 4, 4)?; - let offset = if down { - self.counts.len() + 1 + (self.next / 16) * 17 - } else { - self.next - }; - let bounds = self.handle(BOUNDS, offset * 4, (experts as usize + 1) * 4, 4)?; - let tmp = if needs_fix { - Some(self.handle(TMP, 0, grid as usize * width as usize * 128 * 4, 4)?) - } else { - None - }; - let mut cmds = commands()?; - cmds.push(QueuedCommand::Project( - f, - l, - grid, - ffi::MmqArguments::original_group( - wh, ph, ids, bounds, oh, tmp, l, experts, maxr, width, - ), - )); - if let Some(tmp) = tmp { - cmds.push(QueuedCommand::Fixup( - fix, - grid, - ffi::MmqFixupArguments::original_group( - ids, bounds, oh, tmp, l, experts, maxr, width, - ), - )); - } - let source = if down { - oh - } else { - self.handle( - out, - self.bounds[self.next] as usize * 1280 * 4, - nr as usize * 1280 * 4, - 4, - )? - }; - if down { - self.finite(cmds, source, nr as usize * 2560, false, "Down") - } else { - // Same complete exponent scan with separate role bits. Gate outranks Up - // after the one successful GU/fixup drain, without introducing a D2H failure - // during numerical arbitration. All nr*1280 real words are inspected. - let status = self.workspace.handle(STATUS, 4, 4)?; - cmds.push(self.workspace.zero_command(STATUS, 4)?); - cmds.push(QueuedCommand::OriginalHelper( - b.gu_finite.ok_or(Error::ContextPoisoned)?, - nr * 1280, - ffi::MmqResidentArguments::finite(source, status, 0, nr * 1280, 0), - )); - match self.workspace.run_queued(cmds, Some(status))? { - 0 => Ok(()), - 1 | 3 => Err(Error::NonFiniteMmqOutput("Gate")), - 2 => Err(Error::NonFiniteMmqOutput("Up")), - _ => Err(Error::InvalidDriverValue("Original GU finite witness")), - } - } - } - pub(super) fn width(&self, format: MmqFormat) -> Result { - let maxr = self.counts[self.next..self.next + self.staged] - .iter() - .copied() - .max() - .ok_or(Error::InvalidProjectionShape)?; - let i = format_index(format)?; - let b = self.bank()?; - let mut best = None; - let mut tiles = u32::MAX; - for (j, width) in WIDTHS.into_iter().enumerate() { - if tiles <= 1 { - break; - } - if b.functions[i][j].is_none() { - continue; - } - let n = maxr.div_ceil(width); - if n < tiles { - best = Some(width); - tiles = n; - } - } - best.ok_or(Error::UnsupportedProjection) - } - pub fn run_group<'a>(&'a mut self) -> Result> { - if self.completed - || self.staged == 0 - || self.staged != (self.counts.len() - self.next).min(16) - { - return Err(Error::InvalidProjectionShape); - } - let formats = self.formats.ok_or(Error::InvalidProjectionShape)?; - let nr = self.bounds[self.next + self.staged] - self.bounds[self.next]; - let b = self.bank()?; - let mut zeros = commands()?; - for (index, bytes) in [ - (WG, formats[0].layout(1)?.raw_weight * 2 * self.staged), - (WD, formats[2].layout(1)?.raw_weight * self.staged), - ] { - let h = self.handle(index, bytes, 4096, 4)?; - zeros.push(QueuedCommand::OriginalHelper( - self.workspace.kernel(0)?, - 1024, - ffi::MmqResidentArguments::zero(h, 1024), - )); - } - self.workspace.run_queued(zeros, None)?; - self.project(formats[0], WG, XQ, GU, false, self.width(formats[0])?)?; - let b = self.bank()?; - let gu = self.handle( - GU, - self.bounds[self.next] as usize * 1280 * 4, - nr as usize * 1280 * 4, - 4, - )?; - let h = self.handle(H, 0, nr as usize * 640 * 4, 4)?; - let mut cmds = commands()?; - cmds.push(QueuedCommand::OriginalSwiglu( - b.swiglu.ok_or(Error::ContextPoisoned)?, - nr, - ffi::MmqOriginalSwigluArguments::new(gu, h, nr), - )); - self.finite(cmds, h, nr as usize * 640, false, "SwiGLU")?; - self.quantize(H, HQ, nr, 640, None)?; - self.project(formats[2], WD, HQ, D, true, self.width(formats[2])?)?; - self.completed = true; - Ok(OriginalMmqOutput { layer: self }) - } - pub fn finish_group(&mut self) -> Result<()> { - if !self.completed - || self.staged != (self.counts.len() - self.next).min(16) - || self.staged == 0 - { - return Err(Error::InvalidProjectionShape); - } - // Called only after the affine output loan drops. Numerical outputs cannot - // survive the next staged group through an external ready handle. - self.next += self.staged; - self.staged = 0; - self.formats = None; - self.completed = false; - Ok(()) - } - pub fn finish(self) -> Result<()> { - if self.next != self.counts.len() || self.staged != 0 { - Err(Error::InvalidProjectionShape) - } else { - Ok(()) - } - } -} +#[path = "impl_originalmmqlayer/impl_originalmmqlayer_2.rs"] +mod impl_originalmmqlayer_2; +#[path = "impl_originalmmqlayer/impl_originalmmqlayer_2_2.rs"] +mod impl_originalmmqlayer_2_2; +#[path = "impl_originalmmqlayer/impl_originalmmqlayer_3.rs"] +mod impl_originalmmqlayer_3; diff --git a/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/impl_originalmmqlayer_2.rs b/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/impl_originalmmqlayer_2.rs new file mode 100644 index 00000000..e51d746e --- /dev/null +++ b/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/impl_originalmmqlayer_2.rs @@ -0,0 +1,241 @@ +//! Moved out of the parent module by STRA-338: impl OriginalMmqLayer. + +#[allow(unused_imports)] +use super::*; + + +impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { + pub(in super::super) fn bank(&self) -> Result<&OriginalGroupBank<'ctx>> { + self.workspace.check()?; + self.workspace + .original_group + .as_ref() + .ok_or(Error::UnsupportedProjection) + } + pub(in super::super) fn span(&self, index: usize) -> Result<(ffi::BufferHandle, usize)> { + let b = self.bank()?; + if index != TMP { + if let Some(arena) = self.arena { + return arena.span(index); + } + } + let owner = b.buffer(index)?; + Ok((owner.handle.ok_or(Error::ContextPoisoned)?, owner.bytes)) + } + pub(in super::super) fn handle( + &self, + index: usize, + offset: usize, + bytes: usize, + align: u64, + ) -> Result { + let (h, n) = self.span(index)?; + let group = if self.arena.is_some() && matches!(index, H | D) { + (self.bounds[self.next] as usize) + .checked_mul(if index == H { 640 * 4 } else { 2560 * 4 }) + .ok_or(Error::InvalidProjectionShape)? + } else { + 0 + }; + let h = h.checked_subspan( + n, + group + .checked_add(offset) + .ok_or(Error::InvalidProjectionShape)?, + bytes, + )?; + h.validate_projection_extent(bytes, align)?; + Ok(h) + } + pub(in super::super) fn reject_arena_alias(&self, h: ffi::BufferHandle, bytes: usize) -> Result<()> { + if let Some(arena) = self.arena { + for index in 0..TMP { + let (a, n) = arena.span(index)?; + if h.overlaps(bytes, a, n) { + return Err(Error::OutputAliasesInput); + } + } + } + Ok(()) + } + pub(in super::super) fn finite( + &self, + commands: Vec, + source: ffi::BufferHandle, + amount: usize, + q8: bool, + label: &'static str, + ) -> Result<()> { + let w = &*self.workspace; + let status = w.handle(STATUS, 4, 4)?; + let tail = if q8 { 128 * 144 } else { 0 }; + let mut cmds = commands; + if cmds.len() > 3 { + return Err(Error::InvalidProjectionShape); + } + cmds.push(w.zero_command(STATUS, 4)?); + cmds.push(QueuedCommand::OriginalHelper( + w.kernel(1)?, + ((if q8 { amount * 144 + tail } else { amount * 4 }) / 4) as u32, + ffi::MmqResidentArguments::finite( + source, + status, + u32::from(q8), + amount as u32, + tail as u32, + ), + )); + match w.run_queued(cmds, Some(status))? { + 0 => Ok(()), + 1 | 3 if q8 => Err(Error::InvalidQ8Activation), + 2 if q8 => Err(Error::InvalidDriverValue("Original grouped Q8 tail")), + 1 => Err(Error::NonFiniteMmqOutput(label)), + _ => Err(Error::InvalidDriverValue("Original grouped finite status")), + } + } + pub(in super::super) fn quantize( + &self, + input: usize, + packed: usize, + tokens: u32, + columns: u32, + ids: Option, + ) -> Result<()> { + let b = self.bank()?; + let f = if columns == 2560 { + MmqFormat::Iq3XxsGateUp + } else { + MmqFormat::Iq4NlDown + }; + let l = layout(f, if columns == 2560 { 1280 } else { 2560 }, tokens, 64)?; + let ih = self.handle( + input, + 0, + if ids.is_some() { + b.capacity as usize * 10240 + } else { + l.input + }, + 16, + )?; + let qh = self.handle(packed, 0, l.packed, 16)?; + let mut cmds = commands()?; + cmds.push(QueuedCommand::OriginalHelper( + self.workspace.kernel(0)?, + (l.packed / 4) as u32, + ffi::MmqResidentArguments::zero(qh, (l.packed / 4) as u32), + )); + let id_handle = ids + .map(|i| self.handle(i, 0, tokens as usize * 4, 4)) + .transpose()?; + let args = ffi::MmqQuantArguments::original_indexed(ih, id_handle, qh, l); + cmds.push(QueuedCommand::Quantize( + self.workspace + .experiment + .as_ref() + .ok_or(Error::ContextPoisoned)? + .quantizer + .ok_or(Error::ContextPoisoned)?, + l, + args, + )); + self.finite(cmds, qh, l.payload / 144, true, "Q8") + } + pub(in super::super) fn quantize_device_mixed(&self, input: ffi::BufferHandle) -> Result<()> { + let b = self.bank()?; + let l = layout(MmqFormat::Iq3XxsGateUp, 1280, self.total, 64)?; + let qh = self.handle(XQ, 0, l.packed, 16)?; + let ids = self.handle(ROW_IDS, 0, self.total as usize * 4, 4)?; + let mut cmds = commands()?; + cmds.push(QueuedCommand::OriginalHelper( + self.workspace.kernel(0)?, + (l.packed / 4) as u32, + ffi::MmqResidentArguments::zero(qh, (l.packed / 4) as u32), + )); + cmds.push(QueuedCommand::Quantize( + self.workspace + .experiment + .as_ref() + .ok_or(Error::ContextPoisoned)? + .quantizer + .ok_or(Error::ContextPoisoned)?, + l, + ffi::MmqQuantArguments::original_indexed(input, Some(ids), qh, l), + )); + self.finite(cmds, qh, l.payload / 144, true, "Q8") + } + pub fn stage_expert( + &mut self, + formats: [MmqFormat; 3], + raw: [&DeviceBuffer<'_>; 3], + ) -> Result<()> { + let n = (self.counts.len() - self.next).min(16); + if self.completed || self.staged >= n { + return Err(Error::InvalidProjectionShape); + } + if formats[0] != formats[1] + || !FORMATS[..5].contains(&formats[0]) + || !FORMATS[5..].contains(&formats[2]) + || self.formats.is_some_and(|f| f != formats) + { + return Err(Error::UnsupportedProjection); + } + let b = self.bank()?; + let gu = formats[0].layout(1)?; + let down = formats[2].layout(1)?; + let wh = self.handle(WG, self.staged * gu.raw_weight * 2, gu.raw_weight * 2, 4)?; + let dh = self.handle(WD, self.staged * down.raw_weight, down.raw_weight, 4)?; + let mut handles = [None; 3]; + for (i, source) in raw.into_iter().enumerate() { + let expected = if i < 2 { + gu.raw_weight + } else { + down.raw_weight + }; + let alignment = if formats[i] == MmqFormat::Iq4XsGateUp { + 4 + } else { + 2 + }; + if source.bytes != expected { + return Err(Error::InvalidProjectionShape); + } + if !std::ptr::eq(b.context, source.context) { + return Err(Error::ContextMismatch); + } + let h = source.handle.ok_or(Error::ContextPoisoned)?; + h.validate_projection_extent(expected, alignment)?; + for prior in raw.iter().take(i) { + if h.overlaps( + expected, + prior.handle.ok_or(Error::ContextPoisoned)?, + prior.bytes, + ) { + return Err(Error::OutputAliasesInput); + } + } + for owner in b + .buffers + .iter() + .chain(self.workspace.buffers.iter()) + .flatten() + { + if h.overlaps( + expected, + owner.handle.ok_or(Error::ContextPoisoned)?, + owner.bytes, + ) { + return Err(Error::OutputAliasesInput); + } + } + self.reject_arena_alias(h, expected)?; + handles[i] = Some(h); + } + let raw = [ + handles[0].ok_or(Error::ContextPoisoned)?, + handles[1].ok_or(Error::ContextPoisoned)?, + handles[2].ok_or(Error::ContextPoisoned)?, + ]; + self.stage_raw(formats, raw) + } +} diff --git a/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/impl_originalmmqlayer_2_2.rs b/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/impl_originalmmqlayer_2_2.rs new file mode 100644 index 00000000..58d4e2d5 --- /dev/null +++ b/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/impl_originalmmqlayer_2_2.rs @@ -0,0 +1,159 @@ +//! Moved out of the parent module by STRA-338: impl OriginalMmqLayer (2). + +#[allow(unused_imports)] +use super::*; + + +impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { + + pub(in super::super) fn stage_raw(&mut self, formats: [MmqFormat; 3], raw: [ffi::BufferHandle; 3]) -> Result<()> { + let n = (self.counts.len() - self.next).min(16); + if self.completed || self.staged >= n { + return Err(Error::InvalidProjectionShape); + } + if formats[0] != formats[1] + || !FORMATS[..5].contains(&formats[0]) + || !FORMATS[5..].contains(&formats[2]) + || self.formats.is_some_and(|f| f != formats) + { + return Err(Error::UnsupportedProjection); + } + let b = self.bank()?; + let gu = formats[0].layout(1)?; + let down = formats[2].layout(1)?; + let wh = self.handle(WG, self.staged * gu.raw_weight * 2, gu.raw_weight * 2, 4)?; + let dh = self.handle(WD, self.staged * down.raw_weight, down.raw_weight, 4)?; + for (i, h) in raw.iter().enumerate() { + let amount = if i < 2 { + gu.raw_weight + } else { + down.raw_weight + }; + h.validate_projection_extent(amount, 16)?; + for (j, prior) in raw.iter().take(i).enumerate() { + let prior_amount = if j < 2 { + gu.raw_weight + } else { + down.raw_weight + }; + if h.overlaps(amount, *prior, prior_amount) { + return Err(Error::OutputAliasesInput); + } + } + for owner in b + .buffers + .iter() + .chain(self.workspace.buffers.iter()) + .flatten() + { + if h.overlaps( + amount, + owner.handle.ok_or(Error::ContextPoisoned)?, + owner.bytes, + ) { + return Err(Error::OutputAliasesInput); + } + } + } + for (i, h) in raw.iter().enumerate() { + self.reject_arena_alias( + *h, + if i < 2 { + gu.raw_weight + } else { + down.raw_weight + }, + )?; + } + // All admitted formats have real 16-byte-aligned lengths/owners. This is + // exactly Original gather_native's copy16 branch, not three host-staged copies. + wh.validate_projection_extent(gu.raw_weight * 2, 16)?; + dh.validate_projection_extent(down.raw_weight, 16)?; + for (h, bytes) in [ + (raw[0], gu.raw_weight), + (raw[1], gu.raw_weight), + (raw[2], down.raw_weight), + ] { + h.validate_projection_extent(bytes, 16)?; + } + let mut commands = commands()?; + commands.push(QueuedCommand::OriginalGather( + b.gather.ok_or(Error::ContextPoisoned)?, + ((gu.raw_weight * 2 + down.raw_weight) / 16) as u32, + ffi::MmqOriginalGatherArguments::new(raw, wh, dh, gu.raw_weight, down.raw_weight), + )); + self.workspace.run_queued(commands, None)?; + self.formats = Some(formats); + self.staged += 1; + Ok(()) + } + /// Gather actual registered immutable source slices. No raw address or + /// fabricated DeviceBuffer can be supplied by the runtime caller. + pub fn stage_expert_retained( + &mut self, + formats: [MmqFormat; 3], + bank: &crate::MappedExpertBank<'ctx>, + spans: &[leleka_model_format::qwen4exp::ResidentExpertBankSpan; 3], + ) -> Result<()> { + if !bank.cache_context_matches(self.workspace.context) || !bank.eligible(spans) { + return Err(Error::ContextMismatch); + } + let gu = formats[0].layout(1)?; + let down = formats[2].layout(1)?; + for (i, span) in spans.iter().enumerate() { + if span.raw_kind() != kind(formats[i]) + || span.bytes().len() + != if i < 2 { + gu.raw_weight + } else { + down.raw_weight + } + { + return Err(Error::InvalidProjectionShape); + } + } + let handles = [ + bank.retained_span_handle(&spans[0])?, + bank.retained_span_handle(&spans[1])?, + bank.retained_span_handle(&spans[2])?, + ]; + // stage_raw performs an actual full gather drain before releasing this bank borrow. + self.stage_raw(formats, handles) + } + /// Only a completed real cache prefix inside this affine prompt arena is + /// eligible. Lent/scratch bytes remain misses; the cache owner cannot refill + /// them while the prompt rows hold its allocation's mutable tail loan. + pub fn stage_expert_from_prompt_cache( + &mut self, + read: &crate::OriginalDeviceGrRead<'_, '_, 'ctx>, + layer: usize, + expert: usize, + formats: [MmqFormat; 3], + ) -> Result { + if !read.context_matches(self.workspace.context) { + return Err(Error::ContextMismatch); + } + let Some((blob, extent)) = read.lease().cache_expert_span(layer, expert)? else { + return Ok(false); + }; + let gu = formats[0].layout(1)?; + let down = formats[2].layout(1)?; + let amount = gu + .raw_weight + .checked_mul(2) + .and_then(|n| n.checked_add(down.raw_weight)) + .ok_or(Error::InvalidProjectionShape)?; + if amount > extent { + return Err(Error::InvalidProjectionShape); + } + self.stage_raw( + formats, + [ + blob.checked_subspan(extent, 0, gu.raw_weight)?, + blob.checked_subspan(extent, gu.raw_weight, gu.raw_weight)?, + blob.checked_subspan(extent, gu.raw_weight * 2, down.raw_weight)?, + ], + )?; + Ok(true) + } +} diff --git a/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/impl_originalmmqlayer_3.rs b/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/impl_originalmmqlayer_3.rs new file mode 100644 index 00000000..c4fe98fd --- /dev/null +++ b/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/impl_originalmmqlayer_3.rs @@ -0,0 +1,211 @@ +//! Moved out of the parent module by STRA-338: impl OriginalMmqLayer (3). + +#[allow(unused_imports)] +use super::*; + + +impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { + + pub(in super::super) fn project( + &self, + format: MmqFormat, + weights: usize, + packed: usize, + out: usize, + down: bool, + width: u32, + ) -> Result<()> { + let b = self.bank()?; + let experts = self.staged as u32; + let nr = self.bounds[self.next + self.staged] - self.bounds[self.next]; + let rows = if down { 2560 } else { 1280 }; + let tokens = if down { nr } else { self.total }; + let l = layout(format, rows, tokens, width)?; + let fi = format_index(format)?; + let ti = WIDTHS + .iter() + .position(|j| *j == width) + .ok_or(Error::UnsupportedProjection)?; + let f = b.functions[fi][ti].ok_or(Error::UnsupportedProjection)?; + let fix = b.fixups[fi][ti].ok_or(Error::UnsupportedProjection)?; + let maxr = self.counts[self.next..self.next + self.staged] + .iter() + .copied() + .max() + .ok_or(Error::InvalidProjectionShape)?; + let ntx = maxr.div_ceil(width); + let tiles = (rows / 128) + .checked_mul(ntx) + .and_then(|n| n.checked_mul(experts)) + .ok_or(Error::InvalidProjectionShape)?; + if tiles + .checked_mul(l.columns / l.qk) + .is_none_or(|n| n >= 1 << 30) + { + return Err(Error::InvalidProjectionShape); + } + let sms = self + .workspace + .experiment + .as_ref() + .ok_or(Error::ContextPoisoned)? + .sms; + let efficiency = 100 * tiles / (sms * tiles.div_ceil(sms)); + let grid = if efficiency >= 90 || crate::arch_ptx::stream_k_off() { tiles } else { sms }; + let needs_fix = !tiles.is_multiple_of(grid); + let wh = self.handle(weights, 0, l.raw_weight * experts as usize + 4096, 4)?; + let ph = self.handle(packed, 0, l.packed, 16)?; + let oh = self.handle(out, 0, l.output, 4)?; + let ids = self.handle(IDENTITY, 0, tokens as usize * 4, 4)?; + let offset = if down { + self.counts.len() + 1 + (self.next / 16) * 17 + } else { + self.next + }; + let bounds = self.handle(BOUNDS, offset * 4, (experts as usize + 1) * 4, 4)?; + let tmp = if needs_fix { + Some(self.handle(TMP, 0, grid as usize * width as usize * 128 * 4, 4)?) + } else { + None + }; + let mut cmds = commands()?; + cmds.push(QueuedCommand::Project( + f, + l, + grid, + ffi::MmqArguments::original_group( + wh, ph, ids, bounds, oh, tmp, l, experts, maxr, width, + ), + )); + if let Some(tmp) = tmp { + cmds.push(QueuedCommand::Fixup( + fix, + grid, + ffi::MmqFixupArguments::original_group( + ids, bounds, oh, tmp, l, experts, maxr, width, + ), + )); + } + let source = if down { + oh + } else { + self.handle( + out, + self.bounds[self.next] as usize * 1280 * 4, + nr as usize * 1280 * 4, + 4, + )? + }; + if down { + self.finite(cmds, source, nr as usize * 2560, false, "Down") + } else { + // Same complete exponent scan with separate role bits. Gate outranks Up + // after the one successful GU/fixup drain, without introducing a D2H failure + // during numerical arbitration. All nr*1280 real words are inspected. + let status = self.workspace.handle(STATUS, 4, 4)?; + cmds.push(self.workspace.zero_command(STATUS, 4)?); + cmds.push(QueuedCommand::OriginalHelper( + b.gu_finite.ok_or(Error::ContextPoisoned)?, + nr * 1280, + ffi::MmqResidentArguments::finite(source, status, 0, nr * 1280, 0), + )); + match self.workspace.run_queued(cmds, Some(status))? { + 0 => Ok(()), + 1 | 3 => Err(Error::NonFiniteMmqOutput("Gate")), + 2 => Err(Error::NonFiniteMmqOutput("Up")), + _ => Err(Error::InvalidDriverValue("Original GU finite witness")), + } + } + } + pub(in super::super) fn width(&self, format: MmqFormat) -> Result { + let maxr = self.counts[self.next..self.next + self.staged] + .iter() + .copied() + .max() + .ok_or(Error::InvalidProjectionShape)?; + let i = format_index(format)?; + let b = self.bank()?; + let mut best = None; + let mut tiles = u32::MAX; + for (j, width) in WIDTHS.into_iter().enumerate() { + if tiles <= 1 { + break; + } + if b.functions[i][j].is_none() { + continue; + } + let n = maxr.div_ceil(width); + if n < tiles { + best = Some(width); + tiles = n; + } + } + best.ok_or(Error::UnsupportedProjection) + } + pub fn run_group<'a>(&'a mut self) -> Result> { + if self.completed + || self.staged == 0 + || self.staged != (self.counts.len() - self.next).min(16) + { + return Err(Error::InvalidProjectionShape); + } + let formats = self.formats.ok_or(Error::InvalidProjectionShape)?; + let nr = self.bounds[self.next + self.staged] - self.bounds[self.next]; + let b = self.bank()?; + let mut zeros = commands()?; + for (index, bytes) in [ + (WG, formats[0].layout(1)?.raw_weight * 2 * self.staged), + (WD, formats[2].layout(1)?.raw_weight * self.staged), + ] { + let h = self.handle(index, bytes, 4096, 4)?; + zeros.push(QueuedCommand::OriginalHelper( + self.workspace.kernel(0)?, + 1024, + ffi::MmqResidentArguments::zero(h, 1024), + )); + } + self.workspace.run_queued(zeros, None)?; + self.project(formats[0], WG, XQ, GU, false, self.width(formats[0])?)?; + let b = self.bank()?; + let gu = self.handle( + GU, + self.bounds[self.next] as usize * 1280 * 4, + nr as usize * 1280 * 4, + 4, + )?; + let h = self.handle(H, 0, nr as usize * 640 * 4, 4)?; + let mut cmds = commands()?; + cmds.push(QueuedCommand::OriginalSwiglu( + b.swiglu.ok_or(Error::ContextPoisoned)?, + nr, + ffi::MmqOriginalSwigluArguments::new(gu, h, nr), + )); + self.finite(cmds, h, nr as usize * 640, false, "SwiGLU")?; + self.quantize(H, HQ, nr, 640, None)?; + self.project(formats[2], WD, HQ, D, true, self.width(formats[2])?)?; + self.completed = true; + Ok(OriginalMmqOutput { layer: self }) + } + pub fn finish_group(&mut self) -> Result<()> { + if !self.completed + || self.staged != (self.counts.len() - self.next).min(16) + || self.staged == 0 + { + return Err(Error::InvalidProjectionShape); + } + // Called only after the affine output loan drops. Numerical outputs cannot + // survive the next staged group through an external ready handle. + self.next += self.staged; + self.staged = 0; + self.formats = None; + self.completed = false; + Ok(()) + } + pub fn finish(self) -> Result<()> { + if self.next != self.counts.len() || self.staged != 0 { + Err(Error::InvalidProjectionShape) + } else { + Ok(()) + } + } +} diff --git a/crates/cuda-driver/src/mmq_original_ring/impl_ring.rs b/crates/cuda-driver/src/mmq_original_ring/impl_ring.rs index 1fa81139..db1f0144 100644 --- a/crates/cuda-driver/src/mmq_original_ring/impl_ring.rs +++ b/crates/cuda-driver/src/mmq_original_ring/impl_ring.rs @@ -3,632 +3,9 @@ #[allow(unused_imports)] use super::*; -impl<'read, 'ctx> Ring<'read, 'ctx> { - pub(in super::super) fn new( - context: &'ctx Context<'ctx>, - read: &'read crate::OriginalDeviceGrRead<'_, '_, 'ctx>, - layer: usize, - schedule: &'read mut OriginalMmqCopySchedule<'ctx>, - bank: Rc>, - formats: [MmqFormat; 3], - spans: &'read [[ResidentExpertBankSpan; 3]], - groups: usize, - ) -> Result { - if !read.context_matches(context) - || !bank.cache_context_matches(context) - || layer >= 48 - || spans.is_empty() - || spans.len() > 512 - || groups != spans.len().div_ceil(16) - || formats[0] != formats[1] - || !FORMATS[..5].contains(&formats[0]) - || !FORMATS[5..].contains(&formats[2]) - { - return Err(Error::InvalidProjectionShape); - } - let gu = formats[0].layout(1)?.raw_weight; - let down = formats[2].layout(1)?.raw_weight; - let blob = gu - .checked_mul(2) - .and_then(|n| n.checked_add(down)) - .ok_or(Error::InvalidSize)?; - let admitted: &dyn RingArena = read; - let count = admitted.stage_slots()?; - schedule.validate_context(context)?; - if schedule.ring_slots() != count { - return Err(Error::InvalidProjectionShape); - } - let mut owner = Self { - context, - read, - bank: Some(bank), - schedule, - slots: Vec::new(), - sources: Vec::new(), - commands: Vec::new(), - status: None, - flags: Vec::new(), - stage_next: 0, - staging: false, - streamed: false, - layer: layer as u8, - stage_done: 0, - submitted: false, - drained: false, - closed: false, - }; - let result = (|| { - owner - .slots - .try_reserve_exact(count) - .map_err(|_| Error::HostAllocation)?; - owner - .sources - .try_reserve_exact(spans.len()) - .map_err(|_| Error::HostAllocation)?; - owner - .commands - .try_reserve_exact(COMMAND_CAP) - .map_err(|_| Error::HostAllocation)?; - owner - .flags - .try_reserve_exact(groups * 16) - .map_err(|_| Error::HostAllocation)?; - owner.flags.resize(groups * 16, 0); - // Includes actual fixed ABI storage conservatively (<=512B each), - // plus actual vector capacities; no second unbounded launch list. - if owner - .metadata_bytes()? - .checked_add(owner.schedule.metadata_bytes()?) - .and_then(|n| n.checked_add(owner.schedule.host_metadata_outside)) - .is_none_or(|n| n > 16 * 1024 * 1024) - { - return Err(Error::BudgetExceeded); - } - for index in 0..count { - let (h, n) = admitted.stage_span(index)?; - if n < blob { - return Err(Error::InvalidSize); - } - h.validate_projection_extent(n, 256)?; - for slot in &owner.slots { - if h.overlaps(n, slot.span, slot.bytes) { - return Err(Error::OutputAliasesInput); - } - } - for role in 0..TMP { - let (a, n) = GroupArena::span(read, role)?; - if h.overlaps(blob, a, n) { - return Err(Error::OutputAliasesInput); - } - } - owner.slots.push(Slot { - span: h, - bytes: n, - live: false, - gathered: false, - }); - } - let bank = owner.bank.as_ref().ok_or(Error::ContextPoisoned)?; - for (i, spans) in spans.iter().enumerate() { - if !bank.eligible(spans) - || !matches!(spans[0].role(),TensorRole::Layer{layer:l,..} if usize::from(l)==layer) - || i > 0 && spans[0].expert() <= owner.sources[i - 1].spans[0].expert() - { - return Err(Error::InvalidProjectionShape); - } - for (role, span) in spans.iter().enumerate() { - let actual = bank.cache_source(span)?; - if span.raw_kind() != kind(formats[role]) - || actual.len() != if role < 2 { gu } else { down } - { - return Err(Error::InvalidProjectionShape); - } - } - let resident = admitted - .cache_span(layer, spans[0].expert() as usize)? - .map(|(h, n)| { - if n < blob { - return Err(Error::InvalidSize); - } - Ok([ - h.checked_subspan(n, 0, gu)?, - h.checked_subspan(n, gu, gu)?, - h.checked_subspan(n, gu * 2, down)?, - ]) - }) - .transpose()?; - owner.sources.push(Source { - spans, - resident, - slot: None, - job: None, - entry: None, - dest: None, - }); - } - // With an active chunk stream for this layer, every non-resident expert is the stream's entry. - if let Some(stream) = owner.schedule.stream.as_ref() { - if stream.next_layer_is(layer as u8) { - for source in &mut owner.sources { - if source.resident.is_some() { - continue; - } - let entry = stream - .entry(layer as u8, source.spans[0].expert()) - .ok_or(Error::InvalidProjectionShape)?; - // the stream copies exactly the bytes this span names - if !stream.entry_matches(entry, [ - bank.cache_source(&source.spans[0])?, - bank.cache_source(&source.spans[1])?, - bank.cache_source(&source.spans[2])?, - ]) { - return Err(Error::InvalidProjectionShape); - } - source.entry = Some(entry); - } - owner.streamed = true; - } else { - return Err(Error::InvalidProjectionShape); - } - } - // Experts not page-locked (a pageable bank) are copied by the host stager's helpers into page-locked - // buffers, in launch order, ahead of their DMAs. - let mut jobs = Vec::new(); - for source in &mut owner.sources { - if source.resident.is_none() && source.entry.is_none() && bank.host_staged(source.spans) { - let mut pieces = [(0usize, 0usize, 0u32); 3]; - for (role, span) in source.spans.iter().enumerate() { - let bytes = bank.cache_source(span)?; - pieces[role] = (bytes.as_ptr() as usize, bytes.len(), span.raw_kind()); - } - source.job = Some(jobs.len()); - jobs.push(Job { pieces, priority: 0 }); - } - } - if !jobs.is_empty() { - let priority = host_stage::layer_priority(layer, jobs.len().saturating_mul(blob)); - for job in &mut jobs { - job.priority = priority; - } - } - let charge = groups * 16; - let required = charge - .checked_add(128 * 1024 * 1024) - .ok_or(Error::BudgetExceeded)?; - if context - .allocated_bytes() - .checked_add(required) - .is_none_or(|n| n > context.budget) - || context.memory_info()?.0 < required - { - return Err(Error::BudgetExceeded); - } - owner.status = match owner.schedule.status_pool.take() { - Some((bytes, buffer)) if bytes >= charge => Some(buffer), - Some((_, other)) => { - other.release()?; - Some(context.allocate(charge.max(512))?) - } - None => Some(context.allocate(charge.max(512))?), - }; - // The old input quantization/metadata upload used default stream. - // Admit that dependency once before starting nonblocking producers. - context.synchronize()?; - if !jobs.is_empty() { - let pageable = owner.bank.as_ref().ok_or(Error::ContextPoisoned)?.pageable(); - let schedule = &mut *owner.schedule; - if schedule.host.as_ref().is_some_and(|h| h.buffer_bytes() < blob) { - // a larger blob than the buffers: every earlier DMA from them was drained with its layer - let mut old = schedule.host.take().ok_or(Error::ContextPoisoned)?; - old.close()?; - for event in schedule.host_events.drain(..) { - event.close()?; - } - } - if schedule.host.is_none() { - let guard = context.enter()?; - let created = HostStage::new(blob, pageable); - let pop = guard.finish(); - let host = match (created, pop) { - (Ok(host), Ok(())) => host, - (Err(e), _) | (Ok(_), Err(e)) => return Err(e), - }; - for _ in 0..host.ring() { - schedule.host_events.push(context.original_gpu_event(OriginalEventKind::Completion)?); - } - schedule.host = Some(host); - } - schedule.host.as_mut().ok_or(Error::ContextPoisoned)?.start(jobs)?; - owner.staging = true; - } - Ok(()) - })(); - if let Err(primary) = result { - return combine(Err(primary), owner.close_inner()); - } - Ok(owner) - } - pub(in super::super) fn metadata_bytes(&self) -> Result { - self.slots - .capacity() - .checked_mul(std::mem::size_of::()) - .and_then(|n| n.checked_add(self.sources.capacity() * std::mem::size_of::())) - .and_then(|n| { - n.checked_add(self.commands.capacity() * (std::mem::size_of::() + 512)) - }) - .and_then(|n| n.checked_add(self.flags.capacity() + std::mem::size_of::())) - .ok_or(Error::BudgetExceeded) - } - pub(in super::super) fn enqueue(&mut self, command: Command) -> Result<()> { - if self.closed - || self.commands.len() == COMMAND_CAP - || !self.read.matches_context(self.context) - { - return Err(Error::InvalidProjectionShape); - } - self.commands.push(command); - self.submitted = true; - self.drained = false; - let api = self.schedule.api.as_ref().ok_or(Error::ContextPoisoned)?; - let command = self.commands.last_mut().ok_or(Error::ContextPoisoned)?; - let queued = self - .schedule - .compute - .as_mut() - .ok_or(Error::ContextPoisoned)? - .with_enqueue(|stream| api.enqueue(command, stream)); - if queued.is_ok() && serialize_ring(Drain::Commands) { - return self.schedule.compute.as_ref().ok_or(Error::ContextPoisoned)?.synchronize(); - } - queued - } - pub(in super::super) fn flag(&self, group: usize, stage: usize) -> Result { - if stage >= 4 { - return Err(Error::InvalidProjectionShape); - } - let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?; - b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan( - b.bytes, - group - .checked_mul(16) - .and_then(|n| n.checked_add(stage * 4)) - .ok_or(Error::InvalidSize)?, - 4, - ) - } - pub(in super::super) fn stage_one(&mut self, index: usize, formats: [MmqFormat; 3]) -> Result<()> { - let source = self - .sources - .get(index) - .ok_or(Error::InvalidProjectionShape)?; - if source.resident.is_some() || source.entry.is_some() { - return Ok(()); - } - if source.slot.is_some() { - return Err(Error::InvalidProjectionShape); - } - let sl = self.stage_next; - let next = (sl + 1) % self.slots.len(); - let slot = &mut self.slots[sl]; - let events = &mut self.schedule.events[sl]; - let copy = self.schedule.copy.as_mut().ok_or(Error::ContextPoisoned)?; - if slot.live { - if !slot.gathered { - return Err(Error::InvalidProjectionShape); - } - // Re-recorded copied and used events have the same real source - // streams; the copy stream waits the previous gather before reuse. - events - .used - .as_mut() - .ok_or(Error::ContextPoisoned)? - .wait_on(copy)?; - } - let bank = self.bank.as_ref().ok_or(Error::ContextPoisoned)?; - let api = self.schedule.api.as_ref().ok_or(Error::ContextPoisoned)?; - let gu = formats[0].layout(1)?.raw_weight; - let down = formats[2].layout(1)?.raw_weight; - let mut new_dest: Option<[usize; 3]> = None; - if skip_expert_dma() { - // EXPERIMENTAL diagnostic only (wrong outputs): no expert bytes move; the slot keeps whatever blob it - // held, so the ring's compute runs alone. Measures the grouped MMQ cost without the PCIe stream. - } else if let Some(j) = source.job { - // prefill.cpp stage_one, unpinned: the stager's page-locked copy (waits only if it is behind), then DMA - let blob = gu * 2 + down; - let host = self.schedule.host.as_mut().ok_or(Error::ContextPoisoned)?; - let host_events = &mut self.schedule.host_events; - let ring = host.ring(); - let issued = host.issued_count(); - let done = &mut self.stage_done; - let staged = host.wait(j, blob, || { - while *done < issued && host_events[*done % ring].query()? { - *done += 1; - } - Ok(*done) - })?; - let destination = slot.span.checked_subspan(slot.bytes, 0, blob)?; - self.submitted = true; - self.drained = false; - copy.with_enqueue(|stream| api.copy_registered(destination, staged, stream))?; - host_events[j % ring].record(copy)?; - host.issued(j); - } else { - // page-aligned supersets, side by side in the slot at page offsets (registered banks; falls back when they do not fit) - let aligned = if !bank.pageable() && crate::mapped_expert_bank::aligned_copy_enabled() { - let mut parts: [(&[u8], usize, usize); 3] = [(&[], 0, 0); 3]; - let mut off = 0usize; - for (i, part) in parts.iter_mut().enumerate() { - let (superset, lead) = bank.cache_source_aligned(&source.spans[i])?; - *part = (superset, lead, off); - off += superset.len().div_ceil(4096) * 4096; - } - (off <= slot.bytes).then_some(parts) - } else { - None - }; - if let Some(parts) = aligned { - self.submitted = true; - self.drained = false; - copy.with_enqueue(|stream| { - for (superset, _, off) in parts { - api.copy_registered(slot.span.checked_subspan(slot.bytes, off, superset.len())?, superset, stream)?; - } - Ok(()) - })?; - new_dest = Some([parts[0].2 + parts[0].1, parts[1].2 + parts[1].1, parts[2].2 + parts[2].1]); - } else { - let sources = [ - bank.cache_source(&source.spans[0])?, - bank.cache_source(&source.spans[1])?, - bank.cache_source(&source.spans[2])?, - ]; - let destinations = [ - slot.span.checked_subspan(slot.bytes, 0, gu)?, - slot.span.checked_subspan(slot.bytes, gu, gu)?, - slot.span.checked_subspan(slot.bytes, gu * 2, down)?, - ]; - self.submitted = true; - self.drained = false; - copy.with_enqueue(|stream| { - // Physical role-major bank layout requires three H2Ds. Same source - // bytes and literal blob G/U/D layout; no decode/conversion/copy tmp. - for (destination, source) in destinations.into_iter().zip(sources) { - // one copy per registered/unregistered piece (`MappedExpertBank::copy_pieces`) - for (offset, bytes) in bank.copy_pieces(source) { - api.copy_registered( - destination.checked_subspan(source.len(), offset, bytes)?, - &source[offset..offset + bytes], - stream, - )?; - } - } - Ok(()) - })?; - } - } - events - .copied - .as_mut() - .ok_or(Error::ContextPoisoned)? - .record(copy)?; - if serialize_ring(Drain::Copies) { - copy.synchronize()?; - } - slot.live = true; - slot.gathered = false; - self.sources[index].slot = Some(sl); - self.sources[index].dest = new_dest; - self.stage_next = next; - Ok(()) - } - pub(in super::super) fn gather( - &mut self, - index: usize, - formats: [MmqFormat; 3], - f: ffi::FunctionHandle, - gate_up: ffi::BufferHandle, - down_out: ffi::BufferHandle, - ) -> Result<()> { - let source = self - .sources - .get(index) - .ok_or(Error::InvalidProjectionShape)?; - let gu = formats[0].layout(1)?.raw_weight; - let down = formats[2].layout(1)?.raw_weight; - let sl = source.slot; - let entry = source.entry; - let dest = source.dest; - let raw = if let Some(raw) = source.resident { - raw - } else if let Some(k) = entry { - // the chunk stream's copy of entry k (the compute stream waits for it) - let schedule = &mut *self.schedule; - let stream = schedule.stream.as_mut().ok_or(Error::ContextPoisoned)?; - let at = stream.entry_at(k)?; - let (span, bytes) = schedule - .compute - .as_mut() - .ok_or(Error::ContextPoisoned)? - .with_enqueue(|s| stream.acquire(k, s))?; - [ - span.checked_subspan(bytes, at[0], gu)?, - span.checked_subspan(bytes, at[1], gu)?, - span.checked_subspan(bytes, at[2], down)?, - ] - } else { - let sl = sl.ok_or(Error::InvalidProjectionShape)?; - let slot = &mut self.slots[sl]; - let events = &mut self.schedule.events[sl]; - if !slot.live || slot.gathered { - return Err(Error::InvalidProjectionShape); - } - events - .copied - .as_mut() - .ok_or(Error::ContextPoisoned)? - .wait_on( - self.schedule - .compute - .as_ref() - .ok_or(Error::ContextPoisoned)?, - )?; - let at = dest.unwrap_or([0, gu, gu * 2]); - [ - slot.span.checked_subspan(slot.bytes, at[0], gu)?, - slot.span.checked_subspan(slot.bytes, at[1], gu)?, - slot.span.checked_subspan(slot.bytes, at[2], down)?, - ] - }; - // Destination checks are closed to actual group-bank ranges. All source - // buffers/arena slots were pre-admitted, and are held by this owner. - gate_up.validate_projection_extent(gu * 2, 16)?; - down_out.validate_projection_extent(down, 16)?; - if gate_up.overlaps(gu * 2, down_out, down) { - return Err(Error::OutputAliasesInput); - } - for (i, h) in raw.iter().enumerate() { - let n = if i < 2 { gu } else { down }; - if h.overlaps(n, gate_up, gu * 2) || h.overlaps(n, down_out, down) { - return Err(Error::OutputAliasesInput); - } - } - self.enqueue(Command::Gather( - f, - ((gu * 2 + down) / 16) as u32, - ffi::MmqOriginalGatherArguments::new(raw, gate_up, down_out, gu, down), - ))?; - if let Some(k) = entry { - let schedule = &mut *self.schedule; - let stream = schedule.stream.as_mut().ok_or(Error::ContextPoisoned)?; - schedule - .compute - .as_mut() - .ok_or(Error::ContextPoisoned)? - .with_enqueue(|s| stream.consumed(k, s))?; - } - if let Some(sl) = sl { - let slot = &mut self.slots[sl]; - let events = &mut self.schedule.events[sl]; - events.used.as_mut().ok_or(Error::ContextPoisoned)?.record( - self.schedule - .compute - .as_ref() - .ok_or(Error::ContextPoisoned)?, - )?; - slot.gathered = true; - } - Ok(()) - } - /// Every status is copied only after BOTH real streams drain. Numeric - /// refusal remains stage/group ordered; later transport failure is primary. - pub(in super::super) fn finish_statuses(&mut self) -> Result<&[u8]> { - if self.streamed { - // release the layer's unrouted stream entries (in order) and hand the stream to the next layer - let layer = self.layer; - let schedule = &mut *self.schedule; - let stream = schedule.stream.as_mut().ok_or(Error::ContextPoisoned)?; - schedule - .compute - .as_mut() - .ok_or(Error::ContextPoisoned)? - .with_enqueue(|s| stream.finish_layer(layer, s))?; - self.streamed = false; - } - self.drain()?; - let status = self.status.as_ref().ok_or(Error::ContextPoisoned)?; - let guard = self.context.enter()?; - let copy = self.context.driver.api.copy_to( - status.handle.ok_or(Error::ContextPoisoned)?, - &mut self.flags, - ); - let sync = self.context.driver.api.synchronize(); - let pop = guard.finish(); - if copy.is_err() || sync.is_err() || pop.is_err() { - self.context.poison(); - self.context.retain_driver(); - } - combine(combine(copy, sync), pop)?; - Ok(&self.flags) - } - pub(super) fn drain(&mut self) -> Result<()> { - if self.drained { - return Ok(()); - } - // Do not short-circuit the second producer on a first drain failure. - // With the chunk's expert stream active the copy stream carries the NEXT layers' copies: this layer's own - // were waited for on the compute stream (the `copied` events) and its gathers are drained below. - let copy = if self.schedule.stream.is_some() { - Ok(()) - } else { - self.schedule.copy.as_ref().map_or(Ok(()), OriginalGpuStream::synchronize) - }; - let compute = self - .schedule - .compute - .as_ref() - .map_or(Ok(()), OriginalGpuStream::synchronize); - let result = combine(copy, compute); - self.drained = result.is_ok(); - if result.is_err() { - self.schedule.failed = true; - } - result - } - pub(in super::super) fn close(mut self) -> Result<()> { - self.close_inner() - } - pub(super) fn close_inner(&mut self) -> Result<()> { - if self.closed { - return Ok(()); - } - self.closed = true; - if self.streamed { - // a layer that did not finish leaves the stream unusable: stop its issuer now (the owner ends it) - if let Some(stream) = self.schedule.stream.as_mut() { - let _ = stream.stop(); - } - self.streamed = false; - } - // no stager helper reads the bank after this - if self.staging { - if let Some(host) = self.schedule.host.as_mut() { - host.finish(); - } - self.staging = false; - } - let mut result = if self.submitted { self.drain() } else { Ok(()) }; - if self.context.is_poisoned() || result.is_err() { - self.context.poison(); - self.context.retain_driver(); - // Retain actual registered-bank lease and all actual command ABI, - // not merely a charge/ready bit. Context retains arena VRAM itself. - if let Some(bank) = self.bank.take() { - std::mem::forget(bank); - } - self.schedule.failed = true; - if let Some(api) = self.schedule.api.take() { - std::mem::forget(api); - } - std::mem::forget(std::mem::take(&mut self.sources)); - std::mem::forget(std::mem::take(&mut self.commands)); - std::mem::forget(std::mem::take(&mut self.flags)); - } else { - self.commands.clear(); - self.sources.clear(); - self.bank.take(); - } - if let Some(status) = self.status.take() { - if result.is_ok() && self.drained && !self.context.is_poisoned() && !self.schedule.closed { - // kept for the next layer (the words are zeroed on the device before each group's use) - let charge = status.bytes; - if let Some((_, old)) = self.schedule.status_pool.replace((charge, status)) { - result = combine(result, old.release()); - } - } else { - result = combine(result, status.release()); - } - } - result - } -} +#[path = "impl_ring/impl_ring_2.rs"] +mod impl_ring_2; +#[path = "impl_ring/impl_ring_2_2.rs"] +mod impl_ring_2_2; +#[path = "impl_ring/impl_ring_3.rs"] +mod impl_ring_3; diff --git a/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_2.rs b/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_2.rs new file mode 100644 index 00000000..c2aca818 --- /dev/null +++ b/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_2.rs @@ -0,0 +1,253 @@ +//! Moved out of the parent module by STRA-338: impl Ring. + +#[allow(unused_imports)] +use super::*; + + +impl<'read, 'ctx> Ring<'read, 'ctx> { + pub(in super::super::super) fn new( + context: &'ctx Context<'ctx>, + read: &'read crate::OriginalDeviceGrRead<'_, '_, 'ctx>, + layer: usize, + schedule: &'read mut OriginalMmqCopySchedule<'ctx>, + bank: Rc>, + formats: [MmqFormat; 3], + spans: &'read [[ResidentExpertBankSpan; 3]], + groups: usize, + ) -> Result { + if !read.context_matches(context) + || !bank.cache_context_matches(context) + || layer >= 48 + || spans.is_empty() + || spans.len() > 512 + || groups != spans.len().div_ceil(16) + || formats[0] != formats[1] + || !FORMATS[..5].contains(&formats[0]) + || !FORMATS[5..].contains(&formats[2]) + { + return Err(Error::InvalidProjectionShape); + } + let gu = formats[0].layout(1)?.raw_weight; + let down = formats[2].layout(1)?.raw_weight; + let blob = gu + .checked_mul(2) + .and_then(|n| n.checked_add(down)) + .ok_or(Error::InvalidSize)?; + let admitted: &dyn RingArena = read; + let count = admitted.stage_slots()?; + schedule.validate_context(context)?; + if schedule.ring_slots() != count { + return Err(Error::InvalidProjectionShape); + } + let mut owner = Self { + context, + read, + bank: Some(bank), + schedule, + slots: Vec::new(), + sources: Vec::new(), + commands: Vec::new(), + status: None, + flags: Vec::new(), + stage_next: 0, + staging: false, + streamed: false, + layer: layer as u8, + stage_done: 0, + submitted: false, + drained: false, + closed: false, + }; + let result = (|| { + owner + .slots + .try_reserve_exact(count) + .map_err(|_| Error::HostAllocation)?; + owner + .sources + .try_reserve_exact(spans.len()) + .map_err(|_| Error::HostAllocation)?; + owner + .commands + .try_reserve_exact(COMMAND_CAP) + .map_err(|_| Error::HostAllocation)?; + owner + .flags + .try_reserve_exact(groups * 16) + .map_err(|_| Error::HostAllocation)?; + owner.flags.resize(groups * 16, 0); + // Includes actual fixed ABI storage conservatively (<=512B each), + // plus actual vector capacities; no second unbounded launch list. + if owner + .metadata_bytes()? + .checked_add(owner.schedule.metadata_bytes()?) + .and_then(|n| n.checked_add(owner.schedule.host_metadata_outside)) + .is_none_or(|n| n > 16 * 1024 * 1024) + { + return Err(Error::BudgetExceeded); + } + for index in 0..count { + let (h, n) = admitted.stage_span(index)?; + if n < blob { + return Err(Error::InvalidSize); + } + h.validate_projection_extent(n, 256)?; + for slot in &owner.slots { + if h.overlaps(n, slot.span, slot.bytes) { + return Err(Error::OutputAliasesInput); + } + } + for role in 0..TMP { + let (a, n) = GroupArena::span(read, role)?; + if h.overlaps(blob, a, n) { + return Err(Error::OutputAliasesInput); + } + } + owner.slots.push(Slot { + span: h, + bytes: n, + live: false, + gathered: false, + }); + } + let bank = owner.bank.as_ref().ok_or(Error::ContextPoisoned)?; + for (i, spans) in spans.iter().enumerate() { + if !bank.eligible(spans) + || !matches!(spans[0].role(),TensorRole::Layer{layer:l,..} if usize::from(l)==layer) + || i > 0 && spans[0].expert() <= owner.sources[i - 1].spans[0].expert() + { + return Err(Error::InvalidProjectionShape); + } + for (role, span) in spans.iter().enumerate() { + let actual = bank.cache_source(span)?; + if span.raw_kind() != kind(formats[role]) + || actual.len() != if role < 2 { gu } else { down } + { + return Err(Error::InvalidProjectionShape); + } + } + let resident = admitted + .cache_span(layer, spans[0].expert() as usize)? + .map(|(h, n)| { + if n < blob { + return Err(Error::InvalidSize); + } + Ok([ + h.checked_subspan(n, 0, gu)?, + h.checked_subspan(n, gu, gu)?, + h.checked_subspan(n, gu * 2, down)?, + ]) + }) + .transpose()?; + owner.sources.push(Source { + spans, + resident, + slot: None, + job: None, + entry: None, + dest: None, + }); + } + // With an active chunk stream for this layer, every non-resident expert is the stream's entry. + if let Some(stream) = owner.schedule.stream.as_ref() { + if stream.next_layer_is(layer as u8) { + for source in &mut owner.sources { + if source.resident.is_some() { + continue; + } + let entry = stream + .entry(layer as u8, source.spans[0].expert()) + .ok_or(Error::InvalidProjectionShape)?; + // the stream copies exactly the bytes this span names + if !stream.entry_matches(entry, [ + bank.cache_source(&source.spans[0])?, + bank.cache_source(&source.spans[1])?, + bank.cache_source(&source.spans[2])?, + ]) { + return Err(Error::InvalidProjectionShape); + } + source.entry = Some(entry); + } + owner.streamed = true; + } else { + return Err(Error::InvalidProjectionShape); + } + } + // Experts not page-locked (a pageable bank) are copied by the host stager's helpers into page-locked + // buffers, in launch order, ahead of their DMAs. + let mut jobs = Vec::new(); + for source in &mut owner.sources { + if source.resident.is_none() && source.entry.is_none() && bank.host_staged(source.spans) { + let mut pieces = [(0usize, 0usize, 0u32); 3]; + for (role, span) in source.spans.iter().enumerate() { + let bytes = bank.cache_source(span)?; + pieces[role] = (bytes.as_ptr() as usize, bytes.len(), span.raw_kind()); + } + source.job = Some(jobs.len()); + jobs.push(Job { pieces, priority: 0 }); + } + } + if !jobs.is_empty() { + let priority = host_stage::layer_priority(layer, jobs.len().saturating_mul(blob)); + for job in &mut jobs { + job.priority = priority; + } + } + let charge = groups * 16; + let required = charge + .checked_add(128 * 1024 * 1024) + .ok_or(Error::BudgetExceeded)?; + if context + .allocated_bytes() + .checked_add(required) + .is_none_or(|n| n > context.budget) + || context.memory_info()?.0 < required + { + return Err(Error::BudgetExceeded); + } + owner.status = match owner.schedule.status_pool.take() { + Some((bytes, buffer)) if bytes >= charge => Some(buffer), + Some((_, other)) => { + other.release()?; + Some(context.allocate(charge.max(512))?) + } + None => Some(context.allocate(charge.max(512))?), + }; + // The old input quantization/metadata upload used default stream. + // Admit that dependency once before starting nonblocking producers. + context.synchronize()?; + if !jobs.is_empty() { + let pageable = owner.bank.as_ref().ok_or(Error::ContextPoisoned)?.pageable(); + let schedule = &mut *owner.schedule; + if schedule.host.as_ref().is_some_and(|h| h.buffer_bytes() < blob) { + // a larger blob than the buffers: every earlier DMA from them was drained with its layer + let mut old = schedule.host.take().ok_or(Error::ContextPoisoned)?; + old.close()?; + for event in schedule.host_events.drain(..) { + event.close()?; + } + } + if schedule.host.is_none() { + let guard = context.enter()?; + let created = HostStage::new(blob, pageable); + let pop = guard.finish(); + let host = match (created, pop) { + (Ok(host), Ok(())) => host, + (Err(e), _) | (Ok(_), Err(e)) => return Err(e), + }; + for _ in 0..host.ring() { + schedule.host_events.push(context.original_gpu_event(OriginalEventKind::Completion)?); + } + schedule.host = Some(host); + } + schedule.host.as_mut().ok_or(Error::ContextPoisoned)?.start(jobs)?; + owner.staging = true; + } + Ok(()) + })(); + if let Err(primary) = result { + return combine(Err(primary), owner.close_inner()); + } + Ok(owner) + } +} diff --git a/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_2_2.rs b/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_2_2.rs new file mode 100644 index 00000000..34b23f31 --- /dev/null +++ b/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_2_2.rs @@ -0,0 +1,181 @@ +//! Moved out of the parent module by STRA-338: impl Ring (2). + +#[allow(unused_imports)] +use super::*; + + +impl<'read, 'ctx> Ring<'read, 'ctx> { + pub(in super::super::super) fn metadata_bytes(&self) -> Result { + self.slots + .capacity() + .checked_mul(std::mem::size_of::()) + .and_then(|n| n.checked_add(self.sources.capacity() * std::mem::size_of::())) + .and_then(|n| { + n.checked_add(self.commands.capacity() * (std::mem::size_of::() + 512)) + }) + .and_then(|n| n.checked_add(self.flags.capacity() + std::mem::size_of::())) + .ok_or(Error::BudgetExceeded) + } + pub(in super::super::super) fn enqueue(&mut self, command: Command) -> Result<()> { + if self.closed + || self.commands.len() == COMMAND_CAP + || !self.read.matches_context(self.context) + { + return Err(Error::InvalidProjectionShape); + } + self.commands.push(command); + self.submitted = true; + self.drained = false; + let api = self.schedule.api.as_ref().ok_or(Error::ContextPoisoned)?; + let command = self.commands.last_mut().ok_or(Error::ContextPoisoned)?; + let queued = self + .schedule + .compute + .as_mut() + .ok_or(Error::ContextPoisoned)? + .with_enqueue(|stream| api.enqueue(command, stream)); + if queued.is_ok() && serialize_ring(Drain::Commands) { + return self.schedule.compute.as_ref().ok_or(Error::ContextPoisoned)?.synchronize(); + } + queued + } + pub(in super::super::super) fn flag(&self, group: usize, stage: usize) -> Result { + if stage >= 4 { + return Err(Error::InvalidProjectionShape); + } + let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?; + b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan( + b.bytes, + group + .checked_mul(16) + .and_then(|n| n.checked_add(stage * 4)) + .ok_or(Error::InvalidSize)?, + 4, + ) + } + pub(in super::super::super) fn stage_one(&mut self, index: usize, formats: [MmqFormat; 3]) -> Result<()> { + let source = self + .sources + .get(index) + .ok_or(Error::InvalidProjectionShape)?; + if source.resident.is_some() || source.entry.is_some() { + return Ok(()); + } + if source.slot.is_some() { + return Err(Error::InvalidProjectionShape); + } + let sl = self.stage_next; + let next = (sl + 1) % self.slots.len(); + let slot = &mut self.slots[sl]; + let events = &mut self.schedule.events[sl]; + let copy = self.schedule.copy.as_mut().ok_or(Error::ContextPoisoned)?; + if slot.live { + if !slot.gathered { + return Err(Error::InvalidProjectionShape); + } + // Re-recorded copied and used events have the same real source + // streams; the copy stream waits the previous gather before reuse. + events + .used + .as_mut() + .ok_or(Error::ContextPoisoned)? + .wait_on(copy)?; + } + let bank = self.bank.as_ref().ok_or(Error::ContextPoisoned)?; + let api = self.schedule.api.as_ref().ok_or(Error::ContextPoisoned)?; + let gu = formats[0].layout(1)?.raw_weight; + let down = formats[2].layout(1)?.raw_weight; + let mut new_dest: Option<[usize; 3]> = None; + if skip_expert_dma() { + // EXPERIMENTAL diagnostic only (wrong outputs): no expert bytes move; the slot keeps whatever blob it + // held, so the ring's compute runs alone. Measures the grouped MMQ cost without the PCIe stream. + } else if let Some(j) = source.job { + // prefill.cpp stage_one, unpinned: the stager's page-locked copy (waits only if it is behind), then DMA + let blob = gu * 2 + down; + let host = self.schedule.host.as_mut().ok_or(Error::ContextPoisoned)?; + let host_events = &mut self.schedule.host_events; + let ring = host.ring(); + let issued = host.issued_count(); + let done = &mut self.stage_done; + let staged = host.wait(j, blob, || { + while *done < issued && host_events[*done % ring].query()? { + *done += 1; + } + Ok(*done) + })?; + let destination = slot.span.checked_subspan(slot.bytes, 0, blob)?; + self.submitted = true; + self.drained = false; + copy.with_enqueue(|stream| api.copy_registered(destination, staged, stream))?; + host_events[j % ring].record(copy)?; + host.issued(j); + } else { + // page-aligned supersets, side by side in the slot at page offsets (registered banks; falls back when they do not fit) + let aligned = if !bank.pageable() && crate::mapped_expert_bank::aligned_copy_enabled() { + let mut parts: [(&[u8], usize, usize); 3] = [(&[], 0, 0); 3]; + let mut off = 0usize; + for (i, part) in parts.iter_mut().enumerate() { + let (superset, lead) = bank.cache_source_aligned(&source.spans[i])?; + *part = (superset, lead, off); + off += superset.len().div_ceil(4096) * 4096; + } + (off <= slot.bytes).then_some(parts) + } else { + None + }; + if let Some(parts) = aligned { + self.submitted = true; + self.drained = false; + copy.with_enqueue(|stream| { + for (superset, _, off) in parts { + api.copy_registered(slot.span.checked_subspan(slot.bytes, off, superset.len())?, superset, stream)?; + } + Ok(()) + })?; + new_dest = Some([parts[0].2 + parts[0].1, parts[1].2 + parts[1].1, parts[2].2 + parts[2].1]); + } else { + let sources = [ + bank.cache_source(&source.spans[0])?, + bank.cache_source(&source.spans[1])?, + bank.cache_source(&source.spans[2])?, + ]; + let destinations = [ + slot.span.checked_subspan(slot.bytes, 0, gu)?, + slot.span.checked_subspan(slot.bytes, gu, gu)?, + slot.span.checked_subspan(slot.bytes, gu * 2, down)?, + ]; + self.submitted = true; + self.drained = false; + copy.with_enqueue(|stream| { + // Physical role-major bank layout requires three H2Ds. Same source + // bytes and literal blob G/U/D layout; no decode/conversion/copy tmp. + for (destination, source) in destinations.into_iter().zip(sources) { + // one copy per registered/unregistered piece (`MappedExpertBank::copy_pieces`) + for (offset, bytes) in bank.copy_pieces(source) { + api.copy_registered( + destination.checked_subspan(source.len(), offset, bytes)?, + &source[offset..offset + bytes], + stream, + )?; + } + } + Ok(()) + })?; + } + } + events + .copied + .as_mut() + .ok_or(Error::ContextPoisoned)? + .record(copy)?; + if serialize_ring(Drain::Copies) { + copy.synchronize()?; + } + slot.live = true; + slot.gathered = false; + self.sources[index].slot = Some(sl); + self.sources[index].dest = new_dest; + self.stage_next = next; + Ok(()) + } +} diff --git a/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_3.rs b/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_3.rs new file mode 100644 index 00000000..abc01a75 --- /dev/null +++ b/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_3.rs @@ -0,0 +1,217 @@ +//! Moved out of the parent module by STRA-338: impl Ring (3). + +#[allow(unused_imports)] +use super::*; + + +impl<'read, 'ctx> Ring<'read, 'ctx> { + pub(in super::super::super) fn gather( + &mut self, + index: usize, + formats: [MmqFormat; 3], + f: ffi::FunctionHandle, + gate_up: ffi::BufferHandle, + down_out: ffi::BufferHandle, + ) -> Result<()> { + let source = self + .sources + .get(index) + .ok_or(Error::InvalidProjectionShape)?; + let gu = formats[0].layout(1)?.raw_weight; + let down = formats[2].layout(1)?.raw_weight; + let sl = source.slot; + let entry = source.entry; + let dest = source.dest; + let raw = if let Some(raw) = source.resident { + raw + } else if let Some(k) = entry { + // the chunk stream's copy of entry k (the compute stream waits for it) + let schedule = &mut *self.schedule; + let stream = schedule.stream.as_mut().ok_or(Error::ContextPoisoned)?; + let at = stream.entry_at(k)?; + let (span, bytes) = schedule + .compute + .as_mut() + .ok_or(Error::ContextPoisoned)? + .with_enqueue(|s| stream.acquire(k, s))?; + [ + span.checked_subspan(bytes, at[0], gu)?, + span.checked_subspan(bytes, at[1], gu)?, + span.checked_subspan(bytes, at[2], down)?, + ] + } else { + let sl = sl.ok_or(Error::InvalidProjectionShape)?; + let slot = &mut self.slots[sl]; + let events = &mut self.schedule.events[sl]; + if !slot.live || slot.gathered { + return Err(Error::InvalidProjectionShape); + } + events + .copied + .as_mut() + .ok_or(Error::ContextPoisoned)? + .wait_on( + self.schedule + .compute + .as_ref() + .ok_or(Error::ContextPoisoned)?, + )?; + let at = dest.unwrap_or([0, gu, gu * 2]); + [ + slot.span.checked_subspan(slot.bytes, at[0], gu)?, + slot.span.checked_subspan(slot.bytes, at[1], gu)?, + slot.span.checked_subspan(slot.bytes, at[2], down)?, + ] + }; + // Destination checks are closed to actual group-bank ranges. All source + // buffers/arena slots were pre-admitted, and are held by this owner. + gate_up.validate_projection_extent(gu * 2, 16)?; + down_out.validate_projection_extent(down, 16)?; + if gate_up.overlaps(gu * 2, down_out, down) { + return Err(Error::OutputAliasesInput); + } + for (i, h) in raw.iter().enumerate() { + let n = if i < 2 { gu } else { down }; + if h.overlaps(n, gate_up, gu * 2) || h.overlaps(n, down_out, down) { + return Err(Error::OutputAliasesInput); + } + } + self.enqueue(Command::Gather( + f, + ((gu * 2 + down) / 16) as u32, + ffi::MmqOriginalGatherArguments::new(raw, gate_up, down_out, gu, down), + ))?; + if let Some(k) = entry { + let schedule = &mut *self.schedule; + let stream = schedule.stream.as_mut().ok_or(Error::ContextPoisoned)?; + schedule + .compute + .as_mut() + .ok_or(Error::ContextPoisoned)? + .with_enqueue(|s| stream.consumed(k, s))?; + } + if let Some(sl) = sl { + let slot = &mut self.slots[sl]; + let events = &mut self.schedule.events[sl]; + events.used.as_mut().ok_or(Error::ContextPoisoned)?.record( + self.schedule + .compute + .as_ref() + .ok_or(Error::ContextPoisoned)?, + )?; + slot.gathered = true; + } + Ok(()) + } + /// Every status is copied only after BOTH real streams drain. Numeric + /// refusal remains stage/group ordered; later transport failure is primary. + pub(in super::super::super) fn finish_statuses(&mut self) -> Result<&[u8]> { + if self.streamed { + // release the layer's unrouted stream entries (in order) and hand the stream to the next layer + let layer = self.layer; + let schedule = &mut *self.schedule; + let stream = schedule.stream.as_mut().ok_or(Error::ContextPoisoned)?; + schedule + .compute + .as_mut() + .ok_or(Error::ContextPoisoned)? + .with_enqueue(|s| stream.finish_layer(layer, s))?; + self.streamed = false; + } + self.drain()?; + let status = self.status.as_ref().ok_or(Error::ContextPoisoned)?; + let guard = self.context.enter()?; + let copy = self.context.driver.api.copy_to( + status.handle.ok_or(Error::ContextPoisoned)?, + &mut self.flags, + ); + let sync = self.context.driver.api.synchronize(); + let pop = guard.finish(); + if copy.is_err() || sync.is_err() || pop.is_err() { + self.context.poison(); + self.context.retain_driver(); + } + combine(combine(copy, sync), pop)?; + Ok(&self.flags) + } + pub(in super::super) fn drain(&mut self) -> Result<()> { + if self.drained { + return Ok(()); + } + // Do not short-circuit the second producer on a first drain failure. + // With the chunk's expert stream active the copy stream carries the NEXT layers' copies: this layer's own + // were waited for on the compute stream (the `copied` events) and its gathers are drained below. + let copy = if self.schedule.stream.is_some() { + Ok(()) + } else { + self.schedule.copy.as_ref().map_or(Ok(()), OriginalGpuStream::synchronize) + }; + let compute = self + .schedule + .compute + .as_ref() + .map_or(Ok(()), OriginalGpuStream::synchronize); + let result = combine(copy, compute); + self.drained = result.is_ok(); + if result.is_err() { + self.schedule.failed = true; + } + result + } + pub(in super::super::super) fn close(mut self) -> Result<()> { + self.close_inner() + } + pub(in super::super) fn close_inner(&mut self) -> Result<()> { + if self.closed { + return Ok(()); + } + self.closed = true; + if self.streamed { + // a layer that did not finish leaves the stream unusable: stop its issuer now (the owner ends it) + if let Some(stream) = self.schedule.stream.as_mut() { + let _ = stream.stop(); + } + self.streamed = false; + } + // no stager helper reads the bank after this + if self.staging { + if let Some(host) = self.schedule.host.as_mut() { + host.finish(); + } + self.staging = false; + } + let mut result = if self.submitted { self.drain() } else { Ok(()) }; + if self.context.is_poisoned() || result.is_err() { + self.context.poison(); + self.context.retain_driver(); + // Retain actual registered-bank lease and all actual command ABI, + // not merely a charge/ready bit. Context retains arena VRAM itself. + if let Some(bank) = self.bank.take() { + std::mem::forget(bank); + } + self.schedule.failed = true; + if let Some(api) = self.schedule.api.take() { + std::mem::forget(api); + } + std::mem::forget(std::mem::take(&mut self.sources)); + std::mem::forget(std::mem::take(&mut self.commands)); + std::mem::forget(std::mem::take(&mut self.flags)); + } else { + self.commands.clear(); + self.sources.clear(); + self.bank.take(); + } + if let Some(status) = self.status.take() { + if result.is_ok() && self.drained && !self.context.is_poisoned() && !self.schedule.closed { + // kept for the next layer (the words are zeroed on the device before each group's use) + let charge = status.bytes; + if let Some((_, old)) = self.schedule.status_pool.replace((charge, status)) { + result = combine(result, old.release()); + } + } else { + result = combine(result, status.release()); + } + } + result + } +} diff --git a/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace.rs b/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace.rs index 3897c191..46367ef9 100644 --- a/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace.rs +++ b/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace.rs @@ -3,547 +3,9 @@ #[allow(unused_imports)] use super::*; -impl<'ctx> MmqWorkspace<'ctx> { - pub(super) fn new( - context: &'ctx Context<'ctx>, - native_policy: bool, - integer_policy: bool, - ) -> Result { - if integer_policy { - if context.is_poisoned() || context.handle.is_none() { - return Err(Error::ContextPoisoned); - } - // Refuse before allocating any module/buffer until compiled artifact is sealed. - native_integer::asset()?; - if !native_policy { - return Err(Error::UnsupportedProjection); - } - } - let experiment = context.mmq_experiment()?; - let scratch = (experiment.sms as usize) - .checked_mul(64 * 128 * 4) - .ok_or(Error::BudgetExceeded)?; - let sizes = [ - 655360, 193536, 193536, 163840, 163840, 163840, 82944, 655360, scratch, 256, 4, - ]; - let charge = sizes.iter().try_fold( - if native_policy { - native_activation::CHARGE - + if integer_policy { - native_integer::CHARGE - } else { - 0 - } - } else { - 0 - }, - |a, b| a.checked_add(*b).ok_or(Error::BudgetExceeded), - )?; - if context - .allocated_bytes() - .checked_add(charge) - .is_none_or(|n| n > context.budget) - { - return combine(Err(Error::BudgetExceeded), experiment.close()); - } - let mut owner = Self { - experiment: Some(experiment), - context, - helper: None, - functions: None, - buffers: std::array::from_fn(|_| None), - failed: false, - native_activation: None, - native_integer: None, - original_group: None, - }; - let result = (|| { - if native_policy { - owner.native_activation = Some(native_activation::NativeActivation::new(context)?); - } - if integer_policy { - owner.native_integer = Some(native_integer::NativeInteger::new(context)?); - } - let guard = context.enter()?; - let loaded = (|| { - let m = context.driver.api.load_mmq_resident()?; - owner.helper = Some(m); - let mut fs = Vec::new(); - fs.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?; - for k in 0..3 { - fs.push(context.driver.api.mmq_resident_function(m, k)?); - } - owner.functions = Some(fs.try_into().map_err(|_| Error::InvalidProjectionShape)?); - Ok(()) - })(); - combine(loaded, guard.finish())?; - for (i, size) in sizes.into_iter().enumerate() { - owner.buffers[i] = Some(context.allocate(size)?); - } - Ok(()) - })(); - if let Err(e) = result { - return combine(Err(e), owner.close()); - } - Ok(owner) - } - pub fn allocated_bytes(&self) -> usize { - self.buffers - .iter() - .flatten() - .map(|b| b.bytes) - .sum::() - + self - .original_group - .as_ref() - .map_or(0, |b| b.allocated_bytes()) - + self - .native_activation - .as_ref() - .map_or(0, |_| native_activation::CHARGE) - + self - .native_integer - .as_ref() - .map_or(0, |_| native_integer::CHARGE) - } - pub(super) fn check(&self) -> Result<()> { - if self.failed - || self.context.is_poisoned() - || self.context.handle.is_none() - || self.functions.is_none() - || self.experiment.is_none() - || self.buffers.iter().any(Option::is_none) - { - return Err(Error::ContextPoisoned); - } - if let Some(integer) = &self.native_integer { - integer.check()?; - let native = self - .native_activation - .as_ref() - .ok_or(Error::UnsupportedProjection)? - .buffer()?; - if integer.overlaps(native.handle.ok_or(Error::ContextPoisoned)?, native.bytes)? { - return Err(Error::OutputAliasesInput); - } - } - if let Some(native) = &self.native_activation { - native.check()?; - } - Ok(()) - } - pub(super) fn buffer(&self, index: usize) -> Result<&DeviceBuffer<'ctx>> { - self.check()?; - self.buffers[index].as_ref().ok_or(Error::ContextPoisoned) - } - pub(super) fn handle(&self, index: usize, bytes: usize, alignment: u64) -> Result { - let b = self.buffer(index)?; - if bytes == 0 || bytes > b.bytes { - return Err(Error::InvalidProjectionShape); - } - if !std::ptr::eq(self.context, b.context) { - return Err(Error::ContextMismatch); - } - let h = b.handle.ok_or(Error::ContextPoisoned)?; - h.validate_projection_extent(b.bytes, alignment)?; - Ok(h) - } - pub(super) fn kernel(&self, kind: usize) -> Result { - self.check()?; - self.functions - .ok_or(Error::ContextPoisoned) - .map(|f| f[kind]) - } - pub(super) fn fail(&mut self, r: Result) -> Result { - if r.is_err() { - self.failed = true; - } - r - } - pub(super) fn zero_command(&self, index: usize, bytes: usize) -> Result { - if !bytes.is_multiple_of(4) { - return Err(Error::InvalidProjectionShape); - } - let h = self.handle(index, bytes, 4)?; - Ok(QueuedCommand::Helper( - self.kernel(0)?, - (bytes / 4) as u32, - ffi::MmqResidentArguments::zero(h, (bytes / 4) as u32), - )) - } - #[cfg(test)] - pub(super) fn zero(&self, index: usize, bytes: usize) -> Result<()> { - let mut commands = commands()?; - commands.push(self.zero_command(index, bytes)?); - self.run_queued(commands, None).map(|_| ()) - } - pub(super) fn run_queued( - &self, - mut commands: Vec, - status: Option, - ) -> Result { - self.check()?; - if commands.is_empty() || commands.len() > 5 { - return Err(Error::InvalidProjectionShape); - } - // Owned host destination, never a borrowed stack slice given to CUDA. - // Even a failed copy can describe prior work and must retain its storage. - let mut staging = bytes(4)?; - let guard = self.context.enter()?; - let mut operation = Ok(()); - for command in &mut commands { - operation = command.launch(self.context); - if operation.is_err() { - break; - } - } - if operation.is_ok() - && let Some(status) = status - { - operation = self.context.driver.api.copy_to(status, &mut staging); - } - if operation.is_err() { - self.context.poisoned.set(true); - } - // Identical primary/sync/pop precedence to Context::complete_launch. - // No argument or status owner can drop before all attempted work ends. - let sync = self.context.driver.api.synchronize(); - let pop = guard.finish(); - if sync.is_err() || pop.is_err() { - self.context.poisoned.set(true); - std::mem::forget((commands, staging)); - return combine(combine(operation, sync), pop).map(|_| 0); - } - combine(combine(operation, sync), pop)?; - Ok(u32::from_le_bytes(staging.as_chunks::<4>().0[0])) - } - pub(super) fn finish_finite( - &self, - mut commands: Vec, - index: usize, - amount: usize, - q8: bool, - ) -> Result<()> { - let tail = if q8 { 9216 } else { 0 }; - let bytes = if q8 { - amount.checked_mul(144).and_then(|n| n.checked_add(tail)) - } else { - amount.checked_mul(4) - } - .ok_or(Error::InvalidProjectionShape)?; - let source = self.handle(index, bytes, 4)?; - let status = self.handle(STATUS, 4, 4)?; - if source.overlaps(self.buffer(index)?.bytes, status, 4) { - return Err(Error::OutputAliasesInput); - } - // All validation and owner construction precede the first launch. - if commands.len() > 3 { - return Err(Error::InvalidProjectionShape); - } - commands.push(self.zero_command(STATUS, 4)?); - commands.push(QueuedCommand::Helper( - self.kernel(1)?, - (bytes / 4) as u32, - ffi::MmqResidentArguments::finite( - source, - status, - u32::from(q8), - amount as u32, - tail as u32, - ), - )); - match self.run_queued(commands, Some(status))? { - 0 => Ok(()), - 1 | 3 if q8 => Err(Error::InvalidQ8Activation), - 2 if q8 => Err(Error::InvalidDriverValue("MMQ dirty Q8 tail")), - 1 if !q8 => Err(Error::NonFiniteMmqOutput(match index { - GATE => "Gate", - UP => "Up", - HIDDEN => "SwiGLU", - DOWN => "Down", - _ => "unknown", - })), - _ => Err(Error::InvalidDriverValue("MMQ finite witness")), - } - } - #[cfg(test)] - pub(super) fn finite(&self, index: usize, amount: usize, q8: bool) -> Result<()> { - self.finish_finite(commands()?, index, amount, q8) - } - pub(super) fn quantize(&self, input: usize, packed: usize, l: Layout) -> Result<()> { - self.quantize_with_operator(input, packed, l, false) - } - pub(super) fn quantize_with_operator( - &self, - input: usize, - packed: usize, - l: Layout, - original: bool, - ) -> Result<()> { - if !original && self.native_activation.is_some() { - return self.quantize_native(input, packed, l); - } - let ih = self.handle(input, l.input, 16)?; - let qh = self.handle(packed, l.packed, 16)?; - if ih.overlaps(self.buffer(input)?.bytes, qh, self.buffer(packed)?.bytes) { - return Err(Error::OutputAliasesInput); - } - let e = self.experiment.as_ref().ok_or(Error::ContextPoisoned)?; - e.check()?; - let mut commands = commands()?; - commands.push(self.zero_command(packed, l.packed)?); - commands.push(QueuedCommand::Quantize( - e.quantizer.ok_or(Error::ContextPoisoned)?, - l, - ffi::MmqQuantArguments::new(ih, qh, l), - )); - self.finish_finite(commands, packed, l.payload / 144, true) - } - - pub(super) fn quantize_native(&self, input: usize, packed: usize, l: Layout) -> Result<()> { - self.check()?; - let ih = self.handle(input, l.input, 16)?; - let qh = self.handle(packed, l.packed, 16)?; - let sh = self.handle(STATUS, 4, 4)?; - let sources = [ - (ih, self.buffer(input)?.bytes), - (qh, self.buffer(packed)?.bytes), - (sh, 4), - ]; - for i in 0..sources.len() { - for j in i + 1..sources.len() { - if sources[i] - .0 - .overlaps(sources[i].1, sources[j].0, sources[j].1) - { - return Err(Error::OutputAliasesInput); - } - } - } - let n = self - .native_activation - .as_ref() - .ok_or(Error::InvalidProjectionShape)?; - let nh = n.buffer()?.handle.ok_or(Error::ContextPoisoned)?; - for b in self.buffers.iter().flatten() { - if nh.overlaps( - native_activation::CHARGE, - b.handle.ok_or(Error::ContextPoisoned)?, - b.bytes, - ) { - return Err(Error::OutputAliasesInput); - } - } - let mut cmds = commands()?; - cmds.push(self.zero_command(STATUS, 4)?); - n.append(&mut cmds, ih, qh, sh, l)?; - // Preserve native status bits: never zero between native quantize and proof. - cmds.push(QueuedCommand::Helper( - self.kernel(1)?, - (l.packed / 4) as u32, - ffi::MmqResidentArguments::finite(qh, sh, 1, (l.payload / 144) as u32, 9216), - )); - match self.run_queued(cmds, Some(sh))? { - 0 => Ok(()), - _ => Err(Error::InvalidQ8Activation), - } - } - - pub(super) fn project( - &self, - weights: &MmqWeights<'_>, - packed: usize, - out: usize, - tokens: u32, - ) -> Result<()> { - self.project_with_operator(weights, packed, out, tokens, false) - } - pub(super) fn project_with_operator( - &self, - weights: &MmqWeights<'_>, - packed: usize, - out: usize, - tokens: u32, - original: bool, - ) -> Result<()> { - self.check()?; - let l = weights - .format - .adaptive_layout(tokens, MmqProfile::OriginalAdaptive)?; - let w = weights.native_buffer()?; - if !std::ptr::eq(self.context, weights.context) { - return Err(Error::ContextMismatch); - } - let wh = w.handle.ok_or(Error::ContextPoisoned)?; - wh.validate_projection_extent(w.bytes, 2)?; - let ph = self.handle(packed, l.packed, 16)?; - let oh = self.handle(out, l.output, 4)?; - for (h, n) in [ - (ph, self.buffer(packed)?.bytes), - (oh, self.buffer(out)?.bytes), - ] { - if wh.overlaps(w.bytes, h, n) { - return Err(Error::OutputAliasesInput); - } - } - if ph.overlaps(self.buffer(packed)?.bytes, oh, self.buffer(out)?.bytes) { - return Err(Error::OutputAliasesInput); - } - if let Some(integer) = &self.native_integer - && !original - { - if matches!(weights.format, MmqFormat::Iq2SGateUp) { - return Err(Error::UnsupportedProjection); - } - if matches!(weights.format, MmqFormat::Iq3XxsGateUp) { - if self.native_activation.is_none() || packed != GROUP || !matches!(out, GATE | UP) - { - return Err(Error::UnsupportedProjection); - } - for b in self.buffers.iter().flatten() { - if integer.overlaps(b.handle.ok_or(Error::ContextPoisoned)?, b.bytes)? { - return Err(Error::OutputAliasesInput); - } - } - let mut queued = commands()?; - integer.append(&mut queued, wh, ph, oh, l)?; - return self.finish_finite(queued, out, l.output / 4, false); - } - } - let e = self.experiment.as_ref().ok_or(Error::ContextPoisoned)?; - e.check()?; - let tiles = l.rows / 128; - let efficiency = 100 * tiles / (e.sms * tiles.div_ceil(e.sms)); - let grid = if efficiency >= 90 || crate::arch_ptx::stream_k_off() { tiles } else { e.sms }; - let fixup = !tiles.is_multiple_of(grid); - let temp = if fixup { - let n = grid as usize * l.tile.width() as usize * 128 * 4; - let th = self.handle(SCRATCH, n, 4)?; - for (h, b) in [ - (wh, w.bytes), - (ph, self.buffer(packed)?.bytes), - (oh, self.buffer(out)?.bytes), - ] { - if th.overlaps(self.buffer(SCRATCH)?.bytes, h, b) { - return Err(Error::OutputAliasesInput); - } - } - Some(th) - } else { - None - }; - let mut commands = commands()?; - if fixup { - commands.push( - self.zero_command(SCRATCH, grid as usize * l.tile.width() as usize * 128 * 4)?, - ); - } - let f = e.function(weights.format, l.tile, false)?; - commands.push(QueuedCommand::Project( - f, - l, - grid, - ffi::MmqArguments::new(wh, ph, oh, temp, l), - )); - if let Some(th) = temp { - let f = e.function(weights.format, l.tile, true)?; - commands.push(QueuedCommand::Fixup( - f, - grid, - ffi::MmqFixupArguments::new(oh, th, l), - )); - } - self.finish_finite(commands, out, l.output / 4, false) - } - pub fn prepare_gate_up_chunk<'lease>( - &'lease mut self, - values: &[f32], - tokens: u32, - ) -> Result> { - self.prepare_gate_up_chunk_with_operator(values, tokens, false) - } - /// Mint an affine Original-prompt activation using the actual D4 quantizer, - /// independently of this workspace's optional native integer operators. - pub fn prepare_original_gate_up_chunk<'lease>( - &'lease mut self, - values: &[f32], - tokens: u32, - ) -> Result> { - self.check()?; - let e = self.experiment.as_ref().ok_or(Error::ContextPoisoned)?; - if e.original_functions.is_none() || e.original_fixups.is_none() { - return Err(Error::UnsupportedProjection); - } - self.prepare_gate_up_chunk_with_operator(values, tokens, true) - } - pub(super) fn prepare_gate_up_chunk_with_operator<'lease>( - &'lease mut self, - values: &[f32], - tokens: u32, - original: bool, - ) -> Result> { - self.check()?; - let l = MmqFormat::Iq3XxsGateUp.layout(tokens)?; - if values.len() != l.input / 4 || values.iter().any(|x| !x.is_finite()) { - return Err(Error::InvalidQ8Activation); - } - let mut b = bytes(l.input)?; - for (v, d) in values.iter().zip(b.as_chunks_mut::<4>().0) { - *d = v.to_le_bytes(); - } - let r = (|| { - let dst = self.buffers[INPUT].as_mut().ok_or(Error::ContextPoisoned)?; - // Only the complete current source prefix is read by the closed quantizer. - dst.copy_from_range(0, &b)?; - self.quantize_with_operator(INPUT, CHUNK, l, original) - })(); - if matches!( - &r, - Err(Error::Driver { .. }) | Err(Error::Multiple { .. }) | Err(Error::UnexpectedContext) - ) { - self.context.poisoned.set(true); - } - self.fail(r)?; - Ok(MmqChunkActivation { - workspace: self, - tokens, - original, - }) - } - pub fn close(mut self) -> Result<()> { - self.close_inner() - } - pub(super) fn close_inner(&mut self) -> Result<()> { - self.failed = true; - self.functions = None; - let mut r = self.original_group.take().map_or(Ok(()), |n| n.close()); - r = combine(r, self.native_integer.take().map_or(Ok(()), |n| n.close())); - r = combine( - r, - self.native_activation.take().map_or(Ok(()), |n| n.close()), - ); - for b in &mut self.buffers { - if let Some(b) = b.take() { - let step = b.release(); - if step.is_err() { - self.context.poisoned.set(true); - } - r = combine(r, step); - } - } - if let Some(m) = self.helper.take() { - let step = match self.context.enter() { - Ok(g) => combine(self.context.driver.api.unload(m), g.finish()), - Err(e) => Err(e), - }; - if step.is_err() { - self.context.poisoned.set(true); - } - r = combine(r, step); - } - if let Some(e) = self.experiment.take() { - r = combine(r, e.close()); - } - r - } -} +#[path = "impl_mmqworkspace/impl_mmqworkspace_2.rs"] +mod impl_mmqworkspace_2; +#[path = "impl_mmqworkspace/impl_mmqworkspace_2_2.rs"] +mod impl_mmqworkspace_2_2; +#[path = "impl_mmqworkspace/impl_mmqworkspace_3.rs"] +mod impl_mmqworkspace_3; diff --git a/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace/impl_mmqworkspace_2.rs b/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace/impl_mmqworkspace_2.rs new file mode 100644 index 00000000..2269bd4e --- /dev/null +++ b/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace/impl_mmqworkspace_2.rs @@ -0,0 +1,221 @@ +//! Moved out of the parent module by STRA-338: impl MmqWorkspace. + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> MmqWorkspace<'ctx> { + pub(in super::super) fn new( + context: &'ctx Context<'ctx>, + native_policy: bool, + integer_policy: bool, + ) -> Result { + if integer_policy { + if context.is_poisoned() || context.handle.is_none() { + return Err(Error::ContextPoisoned); + } + // Refuse before allocating any module/buffer until compiled artifact is sealed. + native_integer::asset()?; + if !native_policy { + return Err(Error::UnsupportedProjection); + } + } + let experiment = context.mmq_experiment()?; + let scratch = (experiment.sms as usize) + .checked_mul(64 * 128 * 4) + .ok_or(Error::BudgetExceeded)?; + let sizes = [ + 655360, 193536, 193536, 163840, 163840, 163840, 82944, 655360, scratch, 256, 4, + ]; + let charge = sizes.iter().try_fold( + if native_policy { + native_activation::CHARGE + + if integer_policy { + native_integer::CHARGE + } else { + 0 + } + } else { + 0 + }, + |a, b| a.checked_add(*b).ok_or(Error::BudgetExceeded), + )?; + if context + .allocated_bytes() + .checked_add(charge) + .is_none_or(|n| n > context.budget) + { + return combine(Err(Error::BudgetExceeded), experiment.close()); + } + let mut owner = Self { + experiment: Some(experiment), + context, + helper: None, + functions: None, + buffers: std::array::from_fn(|_| None), + failed: false, + native_activation: None, + native_integer: None, + original_group: None, + }; + let result = (|| { + if native_policy { + owner.native_activation = Some(native_activation::NativeActivation::new(context)?); + } + if integer_policy { + owner.native_integer = Some(native_integer::NativeInteger::new(context)?); + } + let guard = context.enter()?; + let loaded = (|| { + let m = context.driver.api.load_mmq_resident()?; + owner.helper = Some(m); + let mut fs = Vec::new(); + fs.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?; + for k in 0..3 { + fs.push(context.driver.api.mmq_resident_function(m, k)?); + } + owner.functions = Some(fs.try_into().map_err(|_| Error::InvalidProjectionShape)?); + Ok(()) + })(); + combine(loaded, guard.finish())?; + for (i, size) in sizes.into_iter().enumerate() { + owner.buffers[i] = Some(context.allocate(size)?); + } + Ok(()) + })(); + if let Err(e) = result { + return combine(Err(e), owner.close()); + } + Ok(owner) + } + pub fn allocated_bytes(&self) -> usize { + self.buffers + .iter() + .flatten() + .map(|b| b.bytes) + .sum::() + + self + .original_group + .as_ref() + .map_or(0, |b| b.allocated_bytes()) + + self + .native_activation + .as_ref() + .map_or(0, |_| native_activation::CHARGE) + + self + .native_integer + .as_ref() + .map_or(0, |_| native_integer::CHARGE) + } + pub(in super::super) fn check(&self) -> Result<()> { + if self.failed + || self.context.is_poisoned() + || self.context.handle.is_none() + || self.functions.is_none() + || self.experiment.is_none() + || self.buffers.iter().any(Option::is_none) + { + return Err(Error::ContextPoisoned); + } + if let Some(integer) = &self.native_integer { + integer.check()?; + let native = self + .native_activation + .as_ref() + .ok_or(Error::UnsupportedProjection)? + .buffer()?; + if integer.overlaps(native.handle.ok_or(Error::ContextPoisoned)?, native.bytes)? { + return Err(Error::OutputAliasesInput); + } + } + if let Some(native) = &self.native_activation { + native.check()?; + } + Ok(()) + } + pub(in super::super) fn buffer(&self, index: usize) -> Result<&DeviceBuffer<'ctx>> { + self.check()?; + self.buffers[index].as_ref().ok_or(Error::ContextPoisoned) + } + pub(in super::super) fn handle(&self, index: usize, bytes: usize, alignment: u64) -> Result { + let b = self.buffer(index)?; + if bytes == 0 || bytes > b.bytes { + return Err(Error::InvalidProjectionShape); + } + if !std::ptr::eq(self.context, b.context) { + return Err(Error::ContextMismatch); + } + let h = b.handle.ok_or(Error::ContextPoisoned)?; + h.validate_projection_extent(b.bytes, alignment)?; + Ok(h) + } + pub(in super::super) fn kernel(&self, kind: usize) -> Result { + self.check()?; + self.functions + .ok_or(Error::ContextPoisoned) + .map(|f| f[kind]) + } + pub(in super::super) fn fail(&mut self, r: Result) -> Result { + if r.is_err() { + self.failed = true; + } + r + } + pub(in super::super) fn zero_command(&self, index: usize, bytes: usize) -> Result { + if !bytes.is_multiple_of(4) { + return Err(Error::InvalidProjectionShape); + } + let h = self.handle(index, bytes, 4)?; + Ok(QueuedCommand::Helper( + self.kernel(0)?, + (bytes / 4) as u32, + ffi::MmqResidentArguments::zero(h, (bytes / 4) as u32), + )) + } + #[cfg(test)] + pub(in super::super) fn zero(&self, index: usize, bytes: usize) -> Result<()> { + let mut commands = commands()?; + commands.push(self.zero_command(index, bytes)?); + self.run_queued(commands, None).map(|_| ()) + } + pub(in super::super) fn run_queued( + &self, + mut commands: Vec, + status: Option, + ) -> Result { + self.check()?; + if commands.is_empty() || commands.len() > 5 { + return Err(Error::InvalidProjectionShape); + } + // Owned host destination, never a borrowed stack slice given to CUDA. + // Even a failed copy can describe prior work and must retain its storage. + let mut staging = bytes(4)?; + let guard = self.context.enter()?; + let mut operation = Ok(()); + for command in &mut commands { + operation = command.launch(self.context); + if operation.is_err() { + break; + } + } + if operation.is_ok() + && let Some(status) = status + { + operation = self.context.driver.api.copy_to(status, &mut staging); + } + if operation.is_err() { + self.context.poisoned.set(true); + } + // Identical primary/sync/pop precedence to Context::complete_launch. + // No argument or status owner can drop before all attempted work ends. + let sync = self.context.driver.api.synchronize(); + let pop = guard.finish(); + if sync.is_err() || pop.is_err() { + self.context.poisoned.set(true); + std::mem::forget((commands, staging)); + return combine(combine(operation, sync), pop).map(|_| 0); + } + combine(combine(operation, sync), pop)?; + Ok(u32::from_le_bytes(staging.as_chunks::<4>().0[0])) + } +} diff --git a/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace/impl_mmqworkspace_2_2.rs b/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace/impl_mmqworkspace_2_2.rs new file mode 100644 index 00000000..1ad6455a --- /dev/null +++ b/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace/impl_mmqworkspace_2_2.rs @@ -0,0 +1,253 @@ +//! Moved out of the parent module by STRA-338: impl MmqWorkspace (2). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> MmqWorkspace<'ctx> { + pub(in super::super) fn finish_finite( + &self, + mut commands: Vec, + index: usize, + amount: usize, + q8: bool, + ) -> Result<()> { + let tail = if q8 { 9216 } else { 0 }; + let bytes = if q8 { + amount.checked_mul(144).and_then(|n| n.checked_add(tail)) + } else { + amount.checked_mul(4) + } + .ok_or(Error::InvalidProjectionShape)?; + let source = self.handle(index, bytes, 4)?; + let status = self.handle(STATUS, 4, 4)?; + if source.overlaps(self.buffer(index)?.bytes, status, 4) { + return Err(Error::OutputAliasesInput); + } + // All validation and owner construction precede the first launch. + if commands.len() > 3 { + return Err(Error::InvalidProjectionShape); + } + commands.push(self.zero_command(STATUS, 4)?); + commands.push(QueuedCommand::Helper( + self.kernel(1)?, + (bytes / 4) as u32, + ffi::MmqResidentArguments::finite( + source, + status, + u32::from(q8), + amount as u32, + tail as u32, + ), + )); + match self.run_queued(commands, Some(status))? { + 0 => Ok(()), + 1 | 3 if q8 => Err(Error::InvalidQ8Activation), + 2 if q8 => Err(Error::InvalidDriverValue("MMQ dirty Q8 tail")), + 1 if !q8 => Err(Error::NonFiniteMmqOutput(match index { + GATE => "Gate", + UP => "Up", + HIDDEN => "SwiGLU", + DOWN => "Down", + _ => "unknown", + })), + _ => Err(Error::InvalidDriverValue("MMQ finite witness")), + } + } + #[cfg(test)] + pub(in super::super) fn finite(&self, index: usize, amount: usize, q8: bool) -> Result<()> { + self.finish_finite(commands()?, index, amount, q8) + } + pub(in super::super) fn quantize(&self, input: usize, packed: usize, l: Layout) -> Result<()> { + self.quantize_with_operator(input, packed, l, false) + } + pub(in super::super) fn quantize_with_operator( + &self, + input: usize, + packed: usize, + l: Layout, + original: bool, + ) -> Result<()> { + if !original && self.native_activation.is_some() { + return self.quantize_native(input, packed, l); + } + let ih = self.handle(input, l.input, 16)?; + let qh = self.handle(packed, l.packed, 16)?; + if ih.overlaps(self.buffer(input)?.bytes, qh, self.buffer(packed)?.bytes) { + return Err(Error::OutputAliasesInput); + } + let e = self.experiment.as_ref().ok_or(Error::ContextPoisoned)?; + e.check()?; + let mut commands = commands()?; + commands.push(self.zero_command(packed, l.packed)?); + commands.push(QueuedCommand::Quantize( + e.quantizer.ok_or(Error::ContextPoisoned)?, + l, + ffi::MmqQuantArguments::new(ih, qh, l), + )); + self.finish_finite(commands, packed, l.payload / 144, true) + } + + pub(in super::super) fn quantize_native(&self, input: usize, packed: usize, l: Layout) -> Result<()> { + self.check()?; + let ih = self.handle(input, l.input, 16)?; + let qh = self.handle(packed, l.packed, 16)?; + let sh = self.handle(STATUS, 4, 4)?; + let sources = [ + (ih, self.buffer(input)?.bytes), + (qh, self.buffer(packed)?.bytes), + (sh, 4), + ]; + for i in 0..sources.len() { + for j in i + 1..sources.len() { + if sources[i] + .0 + .overlaps(sources[i].1, sources[j].0, sources[j].1) + { + return Err(Error::OutputAliasesInput); + } + } + } + let n = self + .native_activation + .as_ref() + .ok_or(Error::InvalidProjectionShape)?; + let nh = n.buffer()?.handle.ok_or(Error::ContextPoisoned)?; + for b in self.buffers.iter().flatten() { + if nh.overlaps( + native_activation::CHARGE, + b.handle.ok_or(Error::ContextPoisoned)?, + b.bytes, + ) { + return Err(Error::OutputAliasesInput); + } + } + let mut cmds = commands()?; + cmds.push(self.zero_command(STATUS, 4)?); + n.append(&mut cmds, ih, qh, sh, l)?; + // Preserve native status bits: never zero between native quantize and proof. + cmds.push(QueuedCommand::Helper( + self.kernel(1)?, + (l.packed / 4) as u32, + ffi::MmqResidentArguments::finite(qh, sh, 1, (l.payload / 144) as u32, 9216), + )); + match self.run_queued(cmds, Some(sh))? { + 0 => Ok(()), + _ => Err(Error::InvalidQ8Activation), + } + } + + pub(in super::super) fn project( + &self, + weights: &MmqWeights<'_>, + packed: usize, + out: usize, + tokens: u32, + ) -> Result<()> { + self.project_with_operator(weights, packed, out, tokens, false) + } + pub(in super::super) fn project_with_operator( + &self, + weights: &MmqWeights<'_>, + packed: usize, + out: usize, + tokens: u32, + original: bool, + ) -> Result<()> { + self.check()?; + let l = weights + .format + .adaptive_layout(tokens, MmqProfile::OriginalAdaptive)?; + let w = weights.native_buffer()?; + if !std::ptr::eq(self.context, weights.context) { + return Err(Error::ContextMismatch); + } + let wh = w.handle.ok_or(Error::ContextPoisoned)?; + wh.validate_projection_extent(w.bytes, 2)?; + let ph = self.handle(packed, l.packed, 16)?; + let oh = self.handle(out, l.output, 4)?; + for (h, n) in [ + (ph, self.buffer(packed)?.bytes), + (oh, self.buffer(out)?.bytes), + ] { + if wh.overlaps(w.bytes, h, n) { + return Err(Error::OutputAliasesInput); + } + } + if ph.overlaps(self.buffer(packed)?.bytes, oh, self.buffer(out)?.bytes) { + return Err(Error::OutputAliasesInput); + } + if let Some(integer) = &self.native_integer + && !original + { + if matches!(weights.format, MmqFormat::Iq2SGateUp) { + return Err(Error::UnsupportedProjection); + } + if matches!(weights.format, MmqFormat::Iq3XxsGateUp) { + if self.native_activation.is_none() || packed != GROUP || !matches!(out, GATE | UP) + { + return Err(Error::UnsupportedProjection); + } + for b in self.buffers.iter().flatten() { + if integer.overlaps(b.handle.ok_or(Error::ContextPoisoned)?, b.bytes)? { + return Err(Error::OutputAliasesInput); + } + } + let mut queued = commands()?; + integer.append(&mut queued, wh, ph, oh, l)?; + return self.finish_finite(queued, out, l.output / 4, false); + } + } + let e = self.experiment.as_ref().ok_or(Error::ContextPoisoned)?; + e.check()?; + let tiles = l.rows / 128; + let efficiency = 100 * tiles / (e.sms * tiles.div_ceil(e.sms)); + let grid = if efficiency >= 90 || crate::arch_ptx::stream_k_off() { tiles } else { e.sms }; + let fixup = !tiles.is_multiple_of(grid); + let temp = if fixup { + let n = grid as usize * l.tile.width() as usize * 128 * 4; + let th = self.handle(SCRATCH, n, 4)?; + for (h, b) in [ + (wh, w.bytes), + (ph, self.buffer(packed)?.bytes), + (oh, self.buffer(out)?.bytes), + ] { + if th.overlaps(self.buffer(SCRATCH)?.bytes, h, b) { + return Err(Error::OutputAliasesInput); + } + } + Some(th) + } else { + None + }; + let mut commands = commands()?; + if fixup { + commands.push( + self.zero_command(SCRATCH, grid as usize * l.tile.width() as usize * 128 * 4)?, + ); + } + let f = e.function(weights.format, l.tile, false)?; + commands.push(QueuedCommand::Project( + f, + l, + grid, + ffi::MmqArguments::new(wh, ph, oh, temp, l), + )); + if let Some(th) = temp { + let f = e.function(weights.format, l.tile, true)?; + commands.push(QueuedCommand::Fixup( + f, + grid, + ffi::MmqFixupArguments::new(oh, th, l), + )); + } + self.finish_finite(commands, out, l.output / 4, false) + } + pub fn prepare_gate_up_chunk<'lease>( + &'lease mut self, + values: &[f32], + tokens: u32, + ) -> Result> { + self.prepare_gate_up_chunk_with_operator(values, tokens, false) + } +} diff --git a/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace/impl_mmqworkspace_3.rs b/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace/impl_mmqworkspace_3.rs new file mode 100644 index 00000000..4a3124d7 --- /dev/null +++ b/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace/impl_mmqworkspace_3.rs @@ -0,0 +1,92 @@ +//! Moved out of the parent module by STRA-338: impl MmqWorkspace (3). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> MmqWorkspace<'ctx> { + /// Mint an affine Original-prompt activation using the actual D4 quantizer, + /// independently of this workspace's optional native integer operators. + pub fn prepare_original_gate_up_chunk<'lease>( + &'lease mut self, + values: &[f32], + tokens: u32, + ) -> Result> { + self.check()?; + let e = self.experiment.as_ref().ok_or(Error::ContextPoisoned)?; + if e.original_functions.is_none() || e.original_fixups.is_none() { + return Err(Error::UnsupportedProjection); + } + self.prepare_gate_up_chunk_with_operator(values, tokens, true) + } + pub(in super::super) fn prepare_gate_up_chunk_with_operator<'lease>( + &'lease mut self, + values: &[f32], + tokens: u32, + original: bool, + ) -> Result> { + self.check()?; + let l = MmqFormat::Iq3XxsGateUp.layout(tokens)?; + if values.len() != l.input / 4 || values.iter().any(|x| !x.is_finite()) { + return Err(Error::InvalidQ8Activation); + } + let mut b = bytes(l.input)?; + for (v, d) in values.iter().zip(b.as_chunks_mut::<4>().0) { + *d = v.to_le_bytes(); + } + let r = (|| { + let dst = self.buffers[INPUT].as_mut().ok_or(Error::ContextPoisoned)?; + // Only the complete current source prefix is read by the closed quantizer. + dst.copy_from_range(0, &b)?; + self.quantize_with_operator(INPUT, CHUNK, l, original) + })(); + if matches!( + &r, + Err(Error::Driver { .. }) | Err(Error::Multiple { .. }) | Err(Error::UnexpectedContext) + ) { + self.context.poisoned.set(true); + } + self.fail(r)?; + Ok(MmqChunkActivation { + workspace: self, + tokens, + original, + }) + } + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + pub(in super::super) fn close_inner(&mut self) -> Result<()> { + self.failed = true; + self.functions = None; + let mut r = self.original_group.take().map_or(Ok(()), |n| n.close()); + r = combine(r, self.native_integer.take().map_or(Ok(()), |n| n.close())); + r = combine( + r, + self.native_activation.take().map_or(Ok(()), |n| n.close()), + ); + for b in &mut self.buffers { + if let Some(b) = b.take() { + let step = b.release(); + if step.is_err() { + self.context.poisoned.set(true); + } + r = combine(r, step); + } + } + if let Some(m) = self.helper.take() { + let step = match self.context.enter() { + Ok(g) => combine(self.context.driver.api.unload(m), g.finish()), + Err(e) => Err(e), + }; + if step.is_err() { + self.context.poisoned.set(true); + } + r = combine(r, step); + } + if let Some(e) = self.experiment.take() { + r = combine(r, e.close()); + } + r + } +} diff --git a/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix.rs b/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix.rs index f535f4d5..7e8f6d69 100644 --- a/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix.rs +++ b/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix.rs @@ -3,650 +3,9 @@ #[allow(unused_imports)] use super::*; - -impl<'lease, 'ctx> MoeBatchPrefix<'lease, 'ctx> { - pub fn tokens(&self) -> usize { - self.tokens - } - pub(super) fn ready(&self, step: Step) -> Result<()> { - if let Some(error) = &self.refusal { - return Err(error.clone()); - } - if self.step != step { - return Err(Error::InvalidQwenShape); - } - self.batch.status_handle()?; - Ok(()) - } - pub(super) fn latch(&mut self, result: Result<()>) -> Result<()> { - if let Err(error) = &result { - self.refusal.get_or_insert_with(|| error.clone()); - } - result - } - pub(super) fn moe_function(&self, kernel: MoeKernel) -> Result { - Ok(self - .batch - .functions - .as_ref() - .ok_or(Error::ContextPoisoned)? - .moe[kernel.index()]) - } - /// Admit one caller buffer under `role`. `bytes` is the exact size unless `at_least`, in which case the whole - /// allocation is bound. - pub(super) fn bind( - &mut self, - role: Role, - buffer: &'lease DeviceBuffer<'lease>, - bytes: usize, - at_least: bool, - ) -> Result { - if !std::ptr::eq(self.batch.context, buffer.context) { - return Err(Error::ContextMismatch); - } - if bytes == 0 || (at_least && buffer.bytes < bytes) || (!at_least && buffer.bytes != bytes) - { - return Err(Error::InvalidQwenShape); - } - let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; - handle.validate_projection_extent(buffer.bytes, 4)?; - let status = self.batch.status_handle()?; - if handle.overlaps(buffer.bytes, status, STATUS_BYTES) { - return Err(Error::OutputAliasesInput); - } - self.bindings.bind(role, handle, buffer.bytes)?; - if !self.held.iter().any(|held| std::ptr::eq(*held, buffer)) { - self.held.push(buffer); - } - Ok(handle) - } - pub(super) fn push_kernel( - &mut self, - kernel: MoeKernel, - geometry: ([u32; 3], [u32; 3]), - args: &[ffi::KernelArg], - ) -> Result<()> { - let function = self.moe_function(kernel)?; - self.push_function(function, geometry, args) - } - pub(super) fn push_function( - &mut self, - function: ffi::FunctionHandle, - geometry: ([u32; 3], [u32; 3]), - args: &[ffi::KernelArg], - ) -> Result<()> { - self.commands.push(Command::Kernel { - function, - stream: self.stream, - grid: geometry.0, - block: geometry.1, - args: ffi::GdnPrefillArguments::new(args)?, - }); - Ok(()) - } - pub(super) fn status_word(&self, stage: MoeBatchStage) -> Result { - self.batch - .status_handle()? - .checked_subspan(STATUS_BYTES, stage.slot() * 4, 4) - } - /// Complete finite scan of the whole buffer bound to `role`, into the stage's own status word. Stages are - /// scanned strictly in program order. - pub(super) fn scan(&mut self, stage: MoeBatchStage, role: Role) -> Result<()> { - if self.checks != stage.slot() { - return Err(Error::InvalidQwenShape); - } - let (handle, bytes) = self.bindings.get(role)?; - let elements = stage.elements(self.tokens); - if bytes != stage.bytes(self.tokens) { - return Err(Error::InvalidQwenShape); - } - let status = self.status_word(stage)?; - let kernel = if stage.is_half() { - MoeKernel::FiniteF16 - } else { - MoeKernel::FiniteF32 - }; - self.push_kernel( - kernel, - linear(elements)?, - &[ - ffi::KernelArg::Pointer(handle), - ffi::KernelArg::Pointer(status), - ffi::KernelArg::U32(u32::try_from(elements).map_err(|_| Error::InvalidQwenShape)?), - ], - )?; - self.checks = stage.slot() + 1; - Ok(()) - } - pub(super) fn handle(&self, role: Role) -> Result { - Ok(self.bindings.get(role)?.0) - } - pub(super) fn buffer_ref(&self, role: Role) -> Result<&'lease DeviceBuffer<'lease>> { - let handle = self.handle(role)?; - self.held - .iter() - .copied() - .find(|buffer| buffer.handle == Some(handle)) - .ok_or(Error::InvalidQwenShape) - } - - // ---------------------------------------------------------------- images - /// Original tail of `gr_mix_kernel`: the FP16 image, the BF16 hi image and (when given) the BF16 lo image of an - /// f32 `mixed` `[tokens][2560]`, then the FP16 image scan. - pub fn pack_mixed( - &mut self, - mixed: &'lease DeviceBuffer<'lease>, - mixed_h: &'lease DeviceBuffer<'lease>, - mixed_bf: &'lease DeviceBuffer<'lease>, - mixed_bf_lo: Option<&'lease DeviceBuffer<'lease>>, - ) -> Result<()> { - let result = (|| { - self.ready(Step::Images)?; - let t = self.tokens; - let source = self.bind(Role::Mixed, mixed, t * N * F32, false)?; - let h = self.bind(Role::MixedH, mixed_h, t * N * F16, false)?; - let bf = self.bind(Role::MixedBf, mixed_bf, t * N * F16, false)?; - let lo = match mixed_bf_lo { - Some(buffer) => ffi::KernelArg::Pointer(self.bind( - Role::MixedBfLo, - buffer, - t * N * F16, - false, - )?), - None => ffi::KernelArg::NullPointer, - }; - self.push_kernel( - MoeKernel::MixedPack, - linear(t * N)?, - &[ - ffi::KernelArg::Pointer(source), - ffi::KernelArg::Pointer(h), - ffi::KernelArg::Pointer(bf), - lo, - ffi::KernelArg::I64(t as i64), - ], - )?; - self.scan(MoeBatchStage::MixedH, Role::MixedH)?; - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - - // ---------------------------------------------------------------- router - /// BF16 router over the whole window: `logits[t][512] = mixed_bf . W^T` (hi pass with `beta = 0`, then the lo - /// pass accumulated with `beta = 1` when the lo image was given), the logits scan, the verbatim `route_kernel` - /// into `ids` / `weights` `[t][10]`, and the weights scan. `router_w` is the exact BF16 `[512][2560]` matrix. - pub fn route( - &mut self, - router_w: &'lease DeviceBuffer<'lease>, - logits: &'lease DeviceBuffer<'lease>, - ids: &'lease DeviceBuffer<'lease>, - weights: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { - let result = (|| { - self.ready(Step::Router)?; - let t = self.tokens; - self.bind(Role::RouterW, router_w, EXPERTS * N * F16, false)?; - let logits_h = self.bind(Role::Logits, logits, t * EXPERTS * F32, false)?; - let ids_h = self.bind(Role::Ids, ids, t * SELECTED * F32, false)?; - let weights_h = self.bind(Role::Weights, weights, t * SELECTED * F32, false)?; - let x = self.buffer_ref(Role::MixedBf)?; - let lo = self.buffer_ref(Role::MixedBfLo).ok(); - let shape = |beta| GemmShape { - tokens: t, - rows: EXPERTS, - depth: N, - ldy: EXPERTS, - y_offset: 0, - beta, - }; - self.commands.push(Command::Gemm { - gemm: self.gemm, - bf16: true, - x, - w: router_w, - y: logits, - shape: shape(0.0), - }); - if let Some(lo) = lo { - self.commands.push(Command::Gemm { - gemm: self.gemm, - bf16: true, - x: lo, - w: router_w, - y: logits, - shape: shape(1.0), - }); - } - self.scan(MoeBatchStage::Logits, Role::Logits)?; - self.push_kernel( - MoeKernel::Route, - ([t.div_ceil(8) as u32, 1, 1], [256, 1, 1]), - &[ - ffi::KernelArg::Pointer(logits_h), - ffi::KernelArg::Pointer(ids_h), - ffi::KernelArg::Pointer(weights_h), - ffi::KernelArg::I64(t as i64), - ], - )?; - self.scan(MoeBatchStage::RouteWeights, Role::Weights)?; - self.fetch = Some((ids_h, weights_h)); - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - - // ---------------------------------------------------------------- shared expert - /// Dequantize the exact GGUF matrix to FP16 scratch (one thread per 32-value group) and enqueue - /// `Y[t][rows] = X . W^T` through the adapter. - #[allow(clippy::too_many_arguments)] // The fixed operands of one native projection. - pub(super) fn project_native( - &mut self, - format: GdnNativeFormat, - weights: (Role, &'lease DeviceBuffer<'lease>), - scratch: &'lease DeviceBuffer<'lease>, - activation: Role, - output: (Role, &'lease DeviceBuffer<'lease>), - rows: usize, - depth: usize, - output_bytes: usize, - ) -> Result<()> { - let t = self.tokens; - let matrix = format.matrix_bytes(rows, depth)?; - let half_bytes = rows * depth * F16; - let blocks = self.bind(weights.0, weights.1, matrix, false)?; - let scratch_handle = self.bind(Role::Scratch, scratch, half_bytes, true)?; - self.bind(output.0, output.1, output_bytes, false)?; - let groups_per_row = depth / 32; - let function = self - .batch - .functions - .as_ref() - .ok_or(Error::ContextPoisoned)? - .dequant[format_index(format)]; - self.push_function( - function, - linear(rows * groups_per_row)?, - &[ - ffi::KernelArg::Pointer(blocks), - ffi::KernelArg::I64(format.matrix_bytes(1, depth)? as i64), - ffi::KernelArg::I64(0), - ffi::KernelArg::I64(rows as i64), - ffi::KernelArg::I64(groups_per_row as i64), - ffi::KernelArg::Pointer(scratch_handle), - ], - )?; - let x = self.buffer_ref(activation)?; - self.commands.push(Command::Gemm { - gemm: self.gemm, - bf16: false, - x, - w: scratch, - y: output.1, - shape: GemmShape { - tokens: t, - rows, - depth, - ldy: rows, - y_offset: 0, - beta: 0.0, - }, - }); - Ok(()) - } - /// `ffn_gate_shexp`: native dequant + FP16 GEMM from `mixed_h` into `sgate[t][640]`; then its scan. - pub fn shared_gate( - &mut self, - format: GdnNativeFormat, - weights: &'lease DeviceBuffer<'lease>, - scratch: &'lease DeviceBuffer<'lease>, - sgate: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { - let result = (|| { - self.ready(Step::Gate)?; - let bytes = self.tokens * FF * F32; - self.project_native( - format, - (Role::GateW, weights), - scratch, - Role::MixedH, - (Role::SGate, sgate), - FF, - N, - bytes, - )?; - self.scan(MoeBatchStage::SGate, Role::SGate)?; - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - /// `ffn_up_shexp`: the same into `sup[t][640]`; then its scan. - pub fn shared_up( - &mut self, - format: GdnNativeFormat, - weights: &'lease DeviceBuffer<'lease>, - scratch: &'lease DeviceBuffer<'lease>, - sup: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { - let result = (|| { - self.ready(Step::Up)?; - let bytes = self.tokens * FF * F32; - self.project_native( - format, - (Role::UpW, weights), - scratch, - Role::MixedH, - (Role::SUp, sup), - FF, - N, - bytes, - )?; - self.scan(MoeBatchStage::SUp, Role::SUp)?; - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - /// `swiglu_pair`: `H[t][640] = hf_sat(silu(sgate) * sup)` as FP16; then its scan. - pub fn swiglu(&mut self, sh_h: &'lease DeviceBuffer<'lease>) -> Result<()> { - let result = (|| { - self.ready(Step::Swiglu)?; - let t = self.tokens; - let gate = self.handle(Role::SGate)?; - let up = self.handle(Role::SUp)?; - let h = self.bind(Role::ShH, sh_h, t * FF * F16, false)?; - self.push_kernel( - MoeKernel::SwigluPair, - linear(t * FF)?, - &[ - ffi::KernelArg::Pointer(gate), - ffi::KernelArg::Pointer(up), - ffi::KernelArg::Pointer(h), - ffi::KernelArg::I64(t as i64), - ], - )?; - self.scan(MoeBatchStage::ShH, Role::ShH)?; - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - /// `ffn_down_shexp`: native dequant + FP16 GEMM from the FP16 H into `shared[t][2560]`; then its scan. - pub fn shared_down( - &mut self, - format: GdnNativeFormat, - weights: &'lease DeviceBuffer<'lease>, - scratch: &'lease DeviceBuffer<'lease>, - shared: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { - let result = (|| { - self.ready(Step::Down)?; - let bytes = self.tokens * N * F32; - self.project_native( - format, - (Role::DownW, weights), - scratch, - Role::ShH, - (Role::Shared, shared), - N, - FF, - bytes, - )?; - self.scan(MoeBatchStage::Shared, Role::Shared)?; - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - /// Shared scalar gate: BF16 `sg[t] = mixed_bf . wgi` with `N = 1` (hi pass `beta = 0`, then the lo pass with - /// `beta = 1` when given); then its scan. `scalar_w` is the exact BF16 `[2560]` vector. - pub fn shared_scalar( - &mut self, - scalar_w: &'lease DeviceBuffer<'lease>, - sg: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { - let result = (|| { - self.ready(Step::Scalar)?; - let t = self.tokens; - self.bind(Role::ScalarW, scalar_w, N * F16, false)?; - self.bind(Role::Sg, sg, t * F32, false)?; - let x = self.buffer_ref(Role::MixedBf)?; - let lo = self.buffer_ref(Role::MixedBfLo).ok(); - let shape = |beta| GemmShape { - tokens: t, - rows: 1, - depth: N, - ldy: 1, - y_offset: 0, - beta, - }; - self.commands.push(Command::Gemm { - gemm: self.gemm, - bf16: true, - x, - w: scalar_w, - y: sg, - shape: shape(0.0), - }); - if let Some(lo) = lo { - self.commands.push(Command::Gemm { - gemm: self.gemm, - bf16: true, - x: lo, - w: scalar_w, - y: sg, - shape: shape(1.0), - }); - } - self.scan(MoeBatchStage::Sg, Role::Sg)?; - self.step = self.step.next(); - Ok(()) - })(); - self.latch(result) - } - - // ---------------------------------------------------------------- combine (optional) - /// `moe_combine`: `bo[t][d] = sum_k fmaf(w[t][k], Dm[slot[t][k]][d]) + shared[t][d] * sigmoid(sg[t])`. `dm` is - /// the exact `[10 * t][2560]` f32 routed-down matrix, `slot` the HOST row map `[t][10]`: it must be a permutation - /// of `0..10 * t` (the original's expert-sorted slot assignment) and is checked here, then copied into the - /// owner's private device map, so the combine can never read outside `dm`. `bo` is the output. Optional: a window - /// may finish without it. - pub fn combine( - &mut self, - dm: &'lease DeviceBuffer<'lease>, - slot: &[i32], - bo: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { - let result = if self.combine_only { - Err(Error::InvalidQwenShape) - } else { - self.combine_body(dm, slot, bo) - }; - self.latch(result) - } - /// The combine-only program's single step (`begin_combine`): the same `moe_combine` over the caller-lent - /// products of a drained window. `route_weights` is the exact `[t][10]` f32 route-weight buffer, `shared` the - /// exact `[t][2560]` f32 shared output and `sg` the exact `[t]` f32 scalar-gate logits. - pub fn combine_from( - &mut self, - route_weights: &'lease DeviceBuffer<'lease>, - shared: &'lease DeviceBuffer<'lease>, - sg: &'lease DeviceBuffer<'lease>, - dm: &'lease DeviceBuffer<'lease>, - slot: &[i32], - bo: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { - let result = (|| { - if !self.combine_only { - return Err(Error::InvalidQwenShape); - } - self.ready(Step::Combine)?; - let t = self.tokens; - self.bind(Role::Weights, route_weights, t * SELECTED * F32, false)?; - self.bind(Role::Shared, shared, t * N * F32, false)?; - self.bind(Role::Sg, sg, t * F32, false)?; - self.combine_body(dm, slot, bo) - })(); - self.latch(result) - } - pub(super) fn combine_body( - &mut self, - dm: &'lease DeviceBuffer<'lease>, - slot: &[i32], - bo: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { - self.ready(Step::Combine)?; - let t = self.tokens; - check_slot_map(slot, t)?; - let w = self.handle(Role::Weights)?; - let shared = self.handle(Role::Shared)?; - let sg = self.handle(Role::Sg)?; - let dm_h = self.bind(Role::Dm, dm, t * SELECTED * N * F32, false)?; - let bo_h = self.bind(Role::Bo, bo, t * N * F32, false)?; - let private = self.batch.slots.as_mut().ok_or(Error::ContextPoisoned)?; - let slot_h = private.handle.ok_or(Error::ContextPoisoned)?; - let mut bytes = Vec::new(); - bytes - .try_reserve_exact(slot.len() * F32) - .map_err(|_| Error::HostAllocation)?; - bytes.extend(slot.iter().flat_map(|v| v.to_le_bytes())); - private.copy_from_range(0, &bytes)?; - self.bindings.bind(Role::Slot, slot_h, SLOT_BYTES)?; - self.push_kernel( - MoeKernel::Combine, - linear(t * N)?, - &[ - ffi::KernelArg::Pointer(dm_h), - ffi::KernelArg::Pointer(slot_h), - ffi::KernelArg::Pointer(w), - ffi::KernelArg::Pointer(shared), - ffi::KernelArg::Pointer(sg), - ffi::KernelArg::Pointer(bo_h), - ffi::KernelArg::I64(t as i64), - ], - )?; - self.scan(MoeBatchStage::Bo, Role::Bo)?; - self.step = self.step.next(); - Ok(()) - } - - /// Drain the complete admitted prefix once. Earlier numerical refusal beats a later admission error; an - /// admission error with a clean prefix is the returned error. No route is returned on numerical refusal. - pub fn finish(mut self) -> Result { - // `Combine` is optional: a window that ran through the scalar gate is complete. - // The combine-only program is complete exactly when its single combine step ran, and fetches no route. - let complete = if self.combine_only { - self.step == Step::Done - } else { - matches!(self.step, Step::Combine | Step::Done) && self.fetch.is_some() - }; - if !complete && self.refusal.is_none() { - self.refusal = Some(Error::InvalidQwenShape); - } - let fetch = complete && !self.combine_only; - let drained = self.drain(fetch)?; - if drained.refusal.is_none() - && let Some(error) = drained.deferred - { - return Err(error); - } - Ok(MoeBatchCompletion { - refusal: drained.refusal, - route: if drained.refusal.is_none() { - drained.route - } else { - None - }, - }) - } - - pub(super) fn drain(mut self, fetch: bool) -> Result { - let status = self.batch.status_handle()?; - let mut statuses = staging(STATUS_BYTES)?; - let write_fetch = fetch && self.refusal.is_none(); - let route_bytes = self.tokens * SELECTED * F32; - let mut fetched_ids = staging(if write_fetch { route_bytes } else { 0 })?; - let mut fetched_weights = staging(if write_fetch { route_bytes } else { 0 })?; - if self.commands.len() > 1 { - let context = self.batch.context; - let guard = context.enter().inspect_err(|_| { - self.batch.failed = true; - context.poisoned.set(true); - })?; - // The caller's inputs arrived by synchronous pageable H2D, which may return after host staging only. The - // program runs on the adapter's dedicated NON-BLOCKING stream, which the legacy default stream does not - // order against: one real context synchronization separates them. - let mut operation = context.driver.api.synchronize(); - if operation.is_ok() { - for command in &mut self.commands { - operation = command.launch(context); - if operation.is_err() { - break; - } - } - } - // Every program kernel and GEMM is on the non-blocking stream: the D2H below is only ordered after them - // by this completion fence. - let sync = context.driver.api.synchronize(); - if operation.is_ok() && sync.is_ok() { - operation = context.driver.api.copy_to(status, &mut statuses); - } - if operation.is_ok() && sync.is_ok() && write_fetch { - let (ids, weights) = self.fetch.ok_or(Error::InvalidQwenShape)?; - operation = context.driver.api.copy_to(ids, &mut fetched_ids); - if operation.is_ok() { - operation = context.driver.api.copy_to(weights, &mut fetched_weights); - } - } - let pop = guard.finish(); - if operation.is_err() || sync.is_err() || pop.is_err() { - self.batch.failed = true; - context.poisoned.set(true); - } - if sync.is_err() || pop.is_err() { - // Completion is uncertain: retain every actual argument/staging owner and every borrowed buffer. - std::mem::forget(( - self.commands, - self.held, - statuses, - fetched_ids, - fetched_weights, - )); - return combine(combine(operation, sync), pop) - .map(|()| unreachable!("uncertain MoE batch drain")); - } - combine(combine(operation, sync), pop)?; - } - let refusal = match decode_statuses(&statuses, self.checks) { - Ok(refusal) => refusal, - Err(error) => { - self.batch.failed = true; - self.batch.context.poisoned.set(true); - return Err(error); - } - }; - let route = if write_fetch && refusal.is_none() { - let ids = words::(&fetched_ids, i32::from_le_bytes)?; - let weights = words::(&fetched_weights, f32::from_le_bytes)?; - // The scans cover the weights; the ids are integers and must be real experts. - if ids.iter().any(|id| !(0..EXPERTS as i32).contains(id)) { - self.batch.failed = true; - self.batch.context.poisoned.set(true); - return Err(Error::InvalidDriverValue( - "MoE route id outside the expert range", - )); - } - Some(MoeRouteBatch { ids, weights }) - } else { - None - }; - Ok(Drained { - refusal, - deferred: self.refusal, - route, - }) - } -} +#[path = "impl_moebatchprefix/impl_moebatchprefix_2.rs"] +mod impl_moebatchprefix_2; +#[path = "impl_moebatchprefix/impl_moebatchprefix_2_2.rs"] +mod impl_moebatchprefix_2_2; +#[path = "impl_moebatchprefix/impl_moebatchprefix_3.rs"] +mod impl_moebatchprefix_3; diff --git a/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/impl_moebatchprefix_2.rs b/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/impl_moebatchprefix_2.rs new file mode 100644 index 00000000..bb51ea59 --- /dev/null +++ b/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/impl_moebatchprefix_2.rs @@ -0,0 +1,241 @@ +//! Moved out of the parent module by STRA-338: impl MoeBatchPrefix. + +#[allow(unused_imports)] +use super::*; + + + +impl<'lease, 'ctx> MoeBatchPrefix<'lease, 'ctx> { + pub fn tokens(&self) -> usize { + self.tokens + } + pub(in super::super) fn ready(&self, step: Step) -> Result<()> { + if let Some(error) = &self.refusal { + return Err(error.clone()); + } + if self.step != step { + return Err(Error::InvalidQwenShape); + } + self.batch.status_handle()?; + Ok(()) + } + pub(in super::super) fn latch(&mut self, result: Result<()>) -> Result<()> { + if let Err(error) = &result { + self.refusal.get_or_insert_with(|| error.clone()); + } + result + } + pub(in super::super) fn moe_function(&self, kernel: MoeKernel) -> Result { + Ok(self + .batch + .functions + .as_ref() + .ok_or(Error::ContextPoisoned)? + .moe[kernel.index()]) + } + /// Admit one caller buffer under `role`. `bytes` is the exact size unless `at_least`, in which case the whole + /// allocation is bound. + pub(in super::super) fn bind( + &mut self, + role: Role, + buffer: &'lease DeviceBuffer<'lease>, + bytes: usize, + at_least: bool, + ) -> Result { + if !std::ptr::eq(self.batch.context, buffer.context) { + return Err(Error::ContextMismatch); + } + if bytes == 0 || (at_least && buffer.bytes < bytes) || (!at_least && buffer.bytes != bytes) + { + return Err(Error::InvalidQwenShape); + } + let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; + handle.validate_projection_extent(buffer.bytes, 4)?; + let status = self.batch.status_handle()?; + if handle.overlaps(buffer.bytes, status, STATUS_BYTES) { + return Err(Error::OutputAliasesInput); + } + self.bindings.bind(role, handle, buffer.bytes)?; + if !self.held.iter().any(|held| std::ptr::eq(*held, buffer)) { + self.held.push(buffer); + } + Ok(handle) + } + pub(in super::super) fn push_kernel( + &mut self, + kernel: MoeKernel, + geometry: ([u32; 3], [u32; 3]), + args: &[ffi::KernelArg], + ) -> Result<()> { + let function = self.moe_function(kernel)?; + self.push_function(function, geometry, args) + } + pub(in super::super) fn push_function( + &mut self, + function: ffi::FunctionHandle, + geometry: ([u32; 3], [u32; 3]), + args: &[ffi::KernelArg], + ) -> Result<()> { + self.commands.push(Command::Kernel { + function, + stream: self.stream, + grid: geometry.0, + block: geometry.1, + args: ffi::GdnPrefillArguments::new(args)?, + }); + Ok(()) + } + pub(in super::super) fn status_word(&self, stage: MoeBatchStage) -> Result { + self.batch + .status_handle()? + .checked_subspan(STATUS_BYTES, stage.slot() * 4, 4) + } + /// Complete finite scan of the whole buffer bound to `role`, into the stage's own status word. Stages are + /// scanned strictly in program order. + pub(in super::super) fn scan(&mut self, stage: MoeBatchStage, role: Role) -> Result<()> { + if self.checks != stage.slot() { + return Err(Error::InvalidQwenShape); + } + let (handle, bytes) = self.bindings.get(role)?; + let elements = stage.elements(self.tokens); + if bytes != stage.bytes(self.tokens) { + return Err(Error::InvalidQwenShape); + } + let status = self.status_word(stage)?; + let kernel = if stage.is_half() { + MoeKernel::FiniteF16 + } else { + MoeKernel::FiniteF32 + }; + self.push_kernel( + kernel, + linear(elements)?, + &[ + ffi::KernelArg::Pointer(handle), + ffi::KernelArg::Pointer(status), + ffi::KernelArg::U32(u32::try_from(elements).map_err(|_| Error::InvalidQwenShape)?), + ], + )?; + self.checks = stage.slot() + 1; + Ok(()) + } + pub(in super::super) fn handle(&self, role: Role) -> Result { + Ok(self.bindings.get(role)?.0) + } + pub(in super::super) fn buffer_ref(&self, role: Role) -> Result<&'lease DeviceBuffer<'lease>> { + let handle = self.handle(role)?; + self.held + .iter() + .copied() + .find(|buffer| buffer.handle == Some(handle)) + .ok_or(Error::InvalidQwenShape) + } + + // ---------------------------------------------------------------- images + /// Original tail of `gr_mix_kernel`: the FP16 image, the BF16 hi image and (when given) the BF16 lo image of an + /// f32 `mixed` `[tokens][2560]`, then the FP16 image scan. + pub fn pack_mixed( + &mut self, + mixed: &'lease DeviceBuffer<'lease>, + mixed_h: &'lease DeviceBuffer<'lease>, + mixed_bf: &'lease DeviceBuffer<'lease>, + mixed_bf_lo: Option<&'lease DeviceBuffer<'lease>>, + ) -> Result<()> { + let result = (|| { + self.ready(Step::Images)?; + let t = self.tokens; + let source = self.bind(Role::Mixed, mixed, t * N * F32, false)?; + let h = self.bind(Role::MixedH, mixed_h, t * N * F16, false)?; + let bf = self.bind(Role::MixedBf, mixed_bf, t * N * F16, false)?; + let lo = match mixed_bf_lo { + Some(buffer) => ffi::KernelArg::Pointer(self.bind( + Role::MixedBfLo, + buffer, + t * N * F16, + false, + )?), + None => ffi::KernelArg::NullPointer, + }; + self.push_kernel( + MoeKernel::MixedPack, + linear(t * N)?, + &[ + ffi::KernelArg::Pointer(source), + ffi::KernelArg::Pointer(h), + ffi::KernelArg::Pointer(bf), + lo, + ffi::KernelArg::I64(t as i64), + ], + )?; + self.scan(MoeBatchStage::MixedH, Role::MixedH)?; + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } + + // ---------------------------------------------------------------- router + /// BF16 router over the whole window: `logits[t][512] = mixed_bf . W^T` (hi pass with `beta = 0`, then the lo + /// pass accumulated with `beta = 1` when the lo image was given), the logits scan, the verbatim `route_kernel` + /// into `ids` / `weights` `[t][10]`, and the weights scan. `router_w` is the exact BF16 `[512][2560]` matrix. + pub fn route( + &mut self, + router_w: &'lease DeviceBuffer<'lease>, + logits: &'lease DeviceBuffer<'lease>, + ids: &'lease DeviceBuffer<'lease>, + weights: &'lease DeviceBuffer<'lease>, + ) -> Result<()> { + let result = (|| { + self.ready(Step::Router)?; + let t = self.tokens; + self.bind(Role::RouterW, router_w, EXPERTS * N * F16, false)?; + let logits_h = self.bind(Role::Logits, logits, t * EXPERTS * F32, false)?; + let ids_h = self.bind(Role::Ids, ids, t * SELECTED * F32, false)?; + let weights_h = self.bind(Role::Weights, weights, t * SELECTED * F32, false)?; + let x = self.buffer_ref(Role::MixedBf)?; + let lo = self.buffer_ref(Role::MixedBfLo).ok(); + let shape = |beta| GemmShape { + tokens: t, + rows: EXPERTS, + depth: N, + ldy: EXPERTS, + y_offset: 0, + beta, + }; + self.commands.push(Command::Gemm { + gemm: self.gemm, + bf16: true, + x, + w: router_w, + y: logits, + shape: shape(0.0), + }); + if let Some(lo) = lo { + self.commands.push(Command::Gemm { + gemm: self.gemm, + bf16: true, + x: lo, + w: router_w, + y: logits, + shape: shape(1.0), + }); + } + self.scan(MoeBatchStage::Logits, Role::Logits)?; + self.push_kernel( + MoeKernel::Route, + ([t.div_ceil(8) as u32, 1, 1], [256, 1, 1]), + &[ + ffi::KernelArg::Pointer(logits_h), + ffi::KernelArg::Pointer(ids_h), + ffi::KernelArg::Pointer(weights_h), + ffi::KernelArg::I64(t as i64), + ], + )?; + self.scan(MoeBatchStage::RouteWeights, Role::Weights)?; + self.fetch = Some((ids_h, weights_h)); + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } +} diff --git a/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/impl_moebatchprefix_2_2.rs b/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/impl_moebatchprefix_2_2.rs new file mode 100644 index 00000000..420c123c --- /dev/null +++ b/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/impl_moebatchprefix_2_2.rs @@ -0,0 +1,239 @@ +//! Moved out of the parent module by STRA-338: impl MoeBatchPrefix (2). + +#[allow(unused_imports)] +use super::*; + + + +impl<'lease, 'ctx> MoeBatchPrefix<'lease, 'ctx> { + + // ---------------------------------------------------------------- shared expert + /// Dequantize the exact GGUF matrix to FP16 scratch (one thread per 32-value group) and enqueue + /// `Y[t][rows] = X . W^T` through the adapter. + #[allow(clippy::too_many_arguments)] // The fixed operands of one native projection. + pub(in super::super) fn project_native( + &mut self, + format: GdnNativeFormat, + weights: (Role, &'lease DeviceBuffer<'lease>), + scratch: &'lease DeviceBuffer<'lease>, + activation: Role, + output: (Role, &'lease DeviceBuffer<'lease>), + rows: usize, + depth: usize, + output_bytes: usize, + ) -> Result<()> { + let t = self.tokens; + let matrix = format.matrix_bytes(rows, depth)?; + let half_bytes = rows * depth * F16; + let blocks = self.bind(weights.0, weights.1, matrix, false)?; + let scratch_handle = self.bind(Role::Scratch, scratch, half_bytes, true)?; + self.bind(output.0, output.1, output_bytes, false)?; + let groups_per_row = depth / 32; + let function = self + .batch + .functions + .as_ref() + .ok_or(Error::ContextPoisoned)? + .dequant[format_index(format)]; + self.push_function( + function, + linear(rows * groups_per_row)?, + &[ + ffi::KernelArg::Pointer(blocks), + ffi::KernelArg::I64(format.matrix_bytes(1, depth)? as i64), + ffi::KernelArg::I64(0), + ffi::KernelArg::I64(rows as i64), + ffi::KernelArg::I64(groups_per_row as i64), + ffi::KernelArg::Pointer(scratch_handle), + ], + )?; + let x = self.buffer_ref(activation)?; + self.commands.push(Command::Gemm { + gemm: self.gemm, + bf16: false, + x, + w: scratch, + y: output.1, + shape: GemmShape { + tokens: t, + rows, + depth, + ldy: rows, + y_offset: 0, + beta: 0.0, + }, + }); + Ok(()) + } + /// `ffn_gate_shexp`: native dequant + FP16 GEMM from `mixed_h` into `sgate[t][640]`; then its scan. + pub fn shared_gate( + &mut self, + format: GdnNativeFormat, + weights: &'lease DeviceBuffer<'lease>, + scratch: &'lease DeviceBuffer<'lease>, + sgate: &'lease DeviceBuffer<'lease>, + ) -> Result<()> { + let result = (|| { + self.ready(Step::Gate)?; + let bytes = self.tokens * FF * F32; + self.project_native( + format, + (Role::GateW, weights), + scratch, + Role::MixedH, + (Role::SGate, sgate), + FF, + N, + bytes, + )?; + self.scan(MoeBatchStage::SGate, Role::SGate)?; + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } + /// `ffn_up_shexp`: the same into `sup[t][640]`; then its scan. + pub fn shared_up( + &mut self, + format: GdnNativeFormat, + weights: &'lease DeviceBuffer<'lease>, + scratch: &'lease DeviceBuffer<'lease>, + sup: &'lease DeviceBuffer<'lease>, + ) -> Result<()> { + let result = (|| { + self.ready(Step::Up)?; + let bytes = self.tokens * FF * F32; + self.project_native( + format, + (Role::UpW, weights), + scratch, + Role::MixedH, + (Role::SUp, sup), + FF, + N, + bytes, + )?; + self.scan(MoeBatchStage::SUp, Role::SUp)?; + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } + /// `swiglu_pair`: `H[t][640] = hf_sat(silu(sgate) * sup)` as FP16; then its scan. + pub fn swiglu(&mut self, sh_h: &'lease DeviceBuffer<'lease>) -> Result<()> { + let result = (|| { + self.ready(Step::Swiglu)?; + let t = self.tokens; + let gate = self.handle(Role::SGate)?; + let up = self.handle(Role::SUp)?; + let h = self.bind(Role::ShH, sh_h, t * FF * F16, false)?; + self.push_kernel( + MoeKernel::SwigluPair, + linear(t * FF)?, + &[ + ffi::KernelArg::Pointer(gate), + ffi::KernelArg::Pointer(up), + ffi::KernelArg::Pointer(h), + ffi::KernelArg::I64(t as i64), + ], + )?; + self.scan(MoeBatchStage::ShH, Role::ShH)?; + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } + /// `ffn_down_shexp`: native dequant + FP16 GEMM from the FP16 H into `shared[t][2560]`; then its scan. + pub fn shared_down( + &mut self, + format: GdnNativeFormat, + weights: &'lease DeviceBuffer<'lease>, + scratch: &'lease DeviceBuffer<'lease>, + shared: &'lease DeviceBuffer<'lease>, + ) -> Result<()> { + let result = (|| { + self.ready(Step::Down)?; + let bytes = self.tokens * N * F32; + self.project_native( + format, + (Role::DownW, weights), + scratch, + Role::ShH, + (Role::Shared, shared), + N, + FF, + bytes, + )?; + self.scan(MoeBatchStage::Shared, Role::Shared)?; + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } + /// Shared scalar gate: BF16 `sg[t] = mixed_bf . wgi` with `N = 1` (hi pass `beta = 0`, then the lo pass with + /// `beta = 1` when given); then its scan. `scalar_w` is the exact BF16 `[2560]` vector. + pub fn shared_scalar( + &mut self, + scalar_w: &'lease DeviceBuffer<'lease>, + sg: &'lease DeviceBuffer<'lease>, + ) -> Result<()> { + let result = (|| { + self.ready(Step::Scalar)?; + let t = self.tokens; + self.bind(Role::ScalarW, scalar_w, N * F16, false)?; + self.bind(Role::Sg, sg, t * F32, false)?; + let x = self.buffer_ref(Role::MixedBf)?; + let lo = self.buffer_ref(Role::MixedBfLo).ok(); + let shape = |beta| GemmShape { + tokens: t, + rows: 1, + depth: N, + ldy: 1, + y_offset: 0, + beta, + }; + self.commands.push(Command::Gemm { + gemm: self.gemm, + bf16: true, + x, + w: scalar_w, + y: sg, + shape: shape(0.0), + }); + if let Some(lo) = lo { + self.commands.push(Command::Gemm { + gemm: self.gemm, + bf16: true, + x: lo, + w: scalar_w, + y: sg, + shape: shape(1.0), + }); + } + self.scan(MoeBatchStage::Sg, Role::Sg)?; + self.step = self.step.next(); + Ok(()) + })(); + self.latch(result) + } + + // ---------------------------------------------------------------- combine (optional) + /// `moe_combine`: `bo[t][d] = sum_k fmaf(w[t][k], Dm[slot[t][k]][d]) + shared[t][d] * sigmoid(sg[t])`. `dm` is + /// the exact `[10 * t][2560]` f32 routed-down matrix, `slot` the HOST row map `[t][10]`: it must be a permutation + /// of `0..10 * t` (the original's expert-sorted slot assignment) and is checked here, then copied into the + /// owner's private device map, so the combine can never read outside `dm`. `bo` is the output. Optional: a window + /// may finish without it. + pub fn combine( + &mut self, + dm: &'lease DeviceBuffer<'lease>, + slot: &[i32], + bo: &'lease DeviceBuffer<'lease>, + ) -> Result<()> { + let result = if self.combine_only { + Err(Error::InvalidQwenShape) + } else { + self.combine_body(dm, slot, bo) + }; + self.latch(result) + } +} diff --git a/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/impl_moebatchprefix_3.rs b/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/impl_moebatchprefix_3.rs new file mode 100644 index 00000000..a25da431 --- /dev/null +++ b/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/impl_moebatchprefix_3.rs @@ -0,0 +1,191 @@ +//! Moved out of the parent module by STRA-338: impl MoeBatchPrefix (3). + +#[allow(unused_imports)] +use super::*; + + + +impl<'lease, 'ctx> MoeBatchPrefix<'lease, 'ctx> { + /// The combine-only program's single step (`begin_combine`): the same `moe_combine` over the caller-lent + /// products of a drained window. `route_weights` is the exact `[t][10]` f32 route-weight buffer, `shared` the + /// exact `[t][2560]` f32 shared output and `sg` the exact `[t]` f32 scalar-gate logits. + pub fn combine_from( + &mut self, + route_weights: &'lease DeviceBuffer<'lease>, + shared: &'lease DeviceBuffer<'lease>, + sg: &'lease DeviceBuffer<'lease>, + dm: &'lease DeviceBuffer<'lease>, + slot: &[i32], + bo: &'lease DeviceBuffer<'lease>, + ) -> Result<()> { + let result = (|| { + if !self.combine_only { + return Err(Error::InvalidQwenShape); + } + self.ready(Step::Combine)?; + let t = self.tokens; + self.bind(Role::Weights, route_weights, t * SELECTED * F32, false)?; + self.bind(Role::Shared, shared, t * N * F32, false)?; + self.bind(Role::Sg, sg, t * F32, false)?; + self.combine_body(dm, slot, bo) + })(); + self.latch(result) + } + pub(in super::super) fn combine_body( + &mut self, + dm: &'lease DeviceBuffer<'lease>, + slot: &[i32], + bo: &'lease DeviceBuffer<'lease>, + ) -> Result<()> { + self.ready(Step::Combine)?; + let t = self.tokens; + check_slot_map(slot, t)?; + let w = self.handle(Role::Weights)?; + let shared = self.handle(Role::Shared)?; + let sg = self.handle(Role::Sg)?; + let dm_h = self.bind(Role::Dm, dm, t * SELECTED * N * F32, false)?; + let bo_h = self.bind(Role::Bo, bo, t * N * F32, false)?; + let private = self.batch.slots.as_mut().ok_or(Error::ContextPoisoned)?; + let slot_h = private.handle.ok_or(Error::ContextPoisoned)?; + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(slot.len() * F32) + .map_err(|_| Error::HostAllocation)?; + bytes.extend(slot.iter().flat_map(|v| v.to_le_bytes())); + private.copy_from_range(0, &bytes)?; + self.bindings.bind(Role::Slot, slot_h, SLOT_BYTES)?; + self.push_kernel( + MoeKernel::Combine, + linear(t * N)?, + &[ + ffi::KernelArg::Pointer(dm_h), + ffi::KernelArg::Pointer(slot_h), + ffi::KernelArg::Pointer(w), + ffi::KernelArg::Pointer(shared), + ffi::KernelArg::Pointer(sg), + ffi::KernelArg::Pointer(bo_h), + ffi::KernelArg::I64(t as i64), + ], + )?; + self.scan(MoeBatchStage::Bo, Role::Bo)?; + self.step = self.step.next(); + Ok(()) + } + + /// Drain the complete admitted prefix once. Earlier numerical refusal beats a later admission error; an + /// admission error with a clean prefix is the returned error. No route is returned on numerical refusal. + pub fn finish(mut self) -> Result { + // `Combine` is optional: a window that ran through the scalar gate is complete. + // The combine-only program is complete exactly when its single combine step ran, and fetches no route. + let complete = if self.combine_only { + self.step == Step::Done + } else { + matches!(self.step, Step::Combine | Step::Done) && self.fetch.is_some() + }; + if !complete && self.refusal.is_none() { + self.refusal = Some(Error::InvalidQwenShape); + } + let fetch = complete && !self.combine_only; + let drained = self.drain(fetch)?; + if drained.refusal.is_none() + && let Some(error) = drained.deferred + { + return Err(error); + } + Ok(MoeBatchCompletion { + refusal: drained.refusal, + route: if drained.refusal.is_none() { + drained.route + } else { + None + }, + }) + } + + pub(in super::super) fn drain(mut self, fetch: bool) -> Result { + let status = self.batch.status_handle()?; + let mut statuses = staging(STATUS_BYTES)?; + let write_fetch = fetch && self.refusal.is_none(); + let route_bytes = self.tokens * SELECTED * F32; + let mut fetched_ids = staging(if write_fetch { route_bytes } else { 0 })?; + let mut fetched_weights = staging(if write_fetch { route_bytes } else { 0 })?; + if self.commands.len() > 1 { + let context = self.batch.context; + let guard = context.enter().inspect_err(|_| { + self.batch.failed = true; + context.poisoned.set(true); + })?; + // The caller's inputs arrived by synchronous pageable H2D, which may return after host staging only. The + // program runs on the adapter's dedicated NON-BLOCKING stream, which the legacy default stream does not + // order against: one real context synchronization separates them. + let mut operation = context.driver.api.synchronize(); + if operation.is_ok() { + for command in &mut self.commands { + operation = command.launch(context); + if operation.is_err() { + break; + } + } + } + // Every program kernel and GEMM is on the non-blocking stream: the D2H below is only ordered after them + // by this completion fence. + let sync = context.driver.api.synchronize(); + if operation.is_ok() && sync.is_ok() { + operation = context.driver.api.copy_to(status, &mut statuses); + } + if operation.is_ok() && sync.is_ok() && write_fetch { + let (ids, weights) = self.fetch.ok_or(Error::InvalidQwenShape)?; + operation = context.driver.api.copy_to(ids, &mut fetched_ids); + if operation.is_ok() { + operation = context.driver.api.copy_to(weights, &mut fetched_weights); + } + } + let pop = guard.finish(); + if operation.is_err() || sync.is_err() || pop.is_err() { + self.batch.failed = true; + context.poisoned.set(true); + } + if sync.is_err() || pop.is_err() { + // Completion is uncertain: retain every actual argument/staging owner and every borrowed buffer. + std::mem::forget(( + self.commands, + self.held, + statuses, + fetched_ids, + fetched_weights, + )); + return combine(combine(operation, sync), pop) + .map(|()| unreachable!("uncertain MoE batch drain")); + } + combine(combine(operation, sync), pop)?; + } + let refusal = match decode_statuses(&statuses, self.checks) { + Ok(refusal) => refusal, + Err(error) => { + self.batch.failed = true; + self.batch.context.poisoned.set(true); + return Err(error); + } + }; + let route = if write_fetch && refusal.is_none() { + let ids = words::(&fetched_ids, i32::from_le_bytes)?; + let weights = words::(&fetched_weights, f32::from_le_bytes)?; + // The scans cover the weights; the ids are integers and must be real experts. + if ids.iter().any(|id| !(0..EXPERTS as i32).contains(id)) { + self.batch.failed = true; + self.batch.context.poisoned.set(true); + return Err(Error::InvalidDriverValue( + "MoE route id outside the expert range", + )); + } + Some(MoeRouteBatch { ids, weights }) + } else { + None + }; + Ok(Drained { + refusal, + deferred: self.refusal, + route, + }) + } +} diff --git a/crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter.rs b/crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter.rs index 0df475c1..59203c6c 100644 --- a/crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter.rs +++ b/crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter.rs @@ -3,490 +3,9 @@ #[allow(unused_imports)] use super::*; -impl<'ctx> OriginalMtpDrafter<'ctx> { - pub fn new( - full: OriginalMtpFullForward<'ctx>, - mut scalar: OriginalMtpScalarPrefill<'ctx>, - ) -> Result { - full.validate_context(scalar.context)?; - scalar.validate()?; - if full.inner.max_t != scalar.max_t || scalar.has_pending { - return Err(Error::InvalidQwenShape); - } - let c = scalar.context; - let max_t = scalar.max_t; - let stream = scalar.stream.take().ok_or(Error::ContextPoisoned)?; - let mut result = Self { - full: Some(full), - scalar: Some(scalar), - graphs: None, - stream: Some(stream), - context: c, - failed: false, - max_t, - graph_metadata: 0, - direct_window_mode: None, - ring_owner: None, - policy_key: None, - in_flight: None, - }; - let op = (|| { - result.graphs = Some(OriginalGraphRegistry::new( - c, - 2 * (max_t + max_t.saturating_sub(2)), - )?); - Ok(()) - })(); - if let Err(primary) = op { - return combine(Err(primary), result.close_inner()); - } - Ok(result) - } - pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { - if !std::ptr::eq(self.context, c) { - return Err(Error::ContextMismatch); - } - if self.failed || c.is_poisoned() { - return Err(Error::ContextPoisoned); - } - self.full - .as_ref() - .ok_or(Error::ContextPoisoned)? - .validate_context(c)?; - validate_scalar_prefix(self.scalar.as_ref().ok_or(Error::ContextPoisoned)?)?; - self.stream - .as_ref() - .ok_or(Error::ContextPoisoned)? - .validate_context(c) - } - pub fn metadata_bytes(&self) -> Result { - Ok(std::mem::size_of::() - + self - .graphs - .as_ref() - .ok_or(Error::ContextPoisoned)? - .metadata_bytes() - + self.graph_metadata) - } - pub fn is_failed(&self) -> bool { - self.failed || self.context.is_poisoned() - } - /// Original source does not clamp min_p or turn max_drafts==0 into no work: - /// draft0 always runs; continuation uses the literal comparison below. - #[allow(clippy::too_many_arguments)] - pub fn draft( - &mut self, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - window: OriginalVerifyWindow<'ctx>, - selection: NativeHeadSelection, - a: usize, - max_drafts: i32, - min_p: f32, - policy: &OriginalMtpFullPolicy, - coupled: Option<(SamplerParams, &[i32; 4096])>, - ) -> Result> { - self.draft_inner( - ring, prior, window, selection, a, max_drafts, min_p, policy, coupled, None, false, - ) - } - #[allow(clippy::too_many_arguments)] - pub fn draft_first( - &mut self, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - window: OriginalVerifyWindow<'ctx>, - selection: NativeHeadSelection, - rows: usize, - max_drafts: i32, - min_p: f32, - policy: &OriginalMtpFullPolicy, - coupled: Option<(SamplerParams, &[i32; 4096])>, - ) -> Result> { - self.draft_inner( - ring, - prior, - window, - selection, - 0, - max_drafts, - min_p, - policy, - coupled, - Some(rows), - false, - ) - } - #[allow(clippy::too_many_arguments)] - pub(super) fn launch_inner( - &mut self, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - window: OriginalVerifyWindow<'ctx>, - selection: NativeHeadSelection, - a: usize, - max_drafts: i32, - min_p: f32, - policy: &OriginalMtpFullPolicy, - coupled: Option<(SamplerParams, &[i32; 4096])>, - first_rows: Option, - direct_window: bool, - after: Option<&mut OriginalGpuEvent<'ctx>>, - ) -> Result<()> { - if self.in_flight.is_some() { - return Err(Error::InvalidQwenShape); - } - self.validate_context(self.context)?; - policy.validate_selected()?; - ring.validate_snapshot(prior)?; - window.validate_context(self.context)?; - window.validate_selection(&selection)?; - let rows = first_rows.unwrap_or(window.rows()); - let first = window.first_position(); - if first_rows.is_some() && window.rows() != 1 { - return Err(Error::InvalidQwenShape); - } - if rows == 0 - || rows > self.max_t - || a >= rows - || first > prior.0.end - || first - .checked_add(rows.max(a + 1)) - .is_none_or(|n| n > MTP_ORIGINAL_MAX_CELLS) - { - return Err(Error::InvalidQwenShape); - } - if self - .direct_window_mode - .is_some_and(|old| old != direct_window) - { - return Err(Error::InvalidQwenShape); - } - self.direct_window_mode = Some(direct_window); - let owner = prior.owner_id(); - let policy_key = policy.capture_key(); - if self - .ring_owner - .as_ref() - .is_some_and(|old| !old.same_owner(&owner)) - || self.policy_key.is_some_and(|old| old != policy_key) - { - return Err(Error::InvalidQwenShape); - } - self.ring_owner = Some(owner); - self.policy_key = Some(policy_key); - let cp = coupled.is_some(); - if cp - && !self - .full - .as_ref() - .ok_or(Error::ContextPoisoned)? - .inner - .coupled - { - return Err(Error::InvalidQwenShape); - } - let window = Rc::new(window); - let mut selection = Some(selection); - if first_rows.is_some() { - let full = self.full.as_ref().ok_or(Error::ContextPoisoned)?; - if direct_window { - full.stage_first_residual_direct( - Rc::clone(&window), - selection.take().ok_or(Error::InvalidQwenShape)?, - rows, - )?; - } else { - full.stage_first_residual( - Rc::clone(&window), - selection.take().ok_or(Error::InvalidQwenShape)?, - rows, - )?; - } - } - let pol = policy.for_capture(0, cp); - let key = OriginalGraphKey::MtpRound { - rows: rows as u8, - coupled: cp, - }; - let full = self.full.as_ref().ok_or(Error::ContextPoisoned)?; - let scalar = self.scalar.as_ref().ok_or(Error::ContextPoisoned)?; - let graphs = self.graphs.as_mut().ok_or(Error::ContextPoisoned)?; - let stream = self.stream.as_mut().ok_or(Error::ContextPoisoned)?; - let span_record = crate::host_profile::span("mtp.launch_record"); - let first_capture = graphs.find_mut(key)?.is_none(); - let graph = graphs.record( - key, - stream, - || { - if direct_window { - full.prepare_round_from_verifier_rows( - scalar, - ring, - Rc::clone(&window), - rows, - first_rows.is_some(), - &pol, - ) - } else { - full.prepare_round(scalar, ring, rows, &pol) - } - }, - |c, r| r.capture(c), - )?; - drop(span_record); - if first_capture { - self.graph_metadata = self - .graph_metadata - .checked_add(graph.mtp_resource_metadata()?) - .ok_or(Error::BudgetExceeded)?; - if crate::host_profile::enabled() { - eprintln!("DBG mtp round graph rows {rows} (coupled {cp}): {:?} nodes", graph.nodes()); - } - } - let _span_stage = crate::host_profile::span("mtp.launch_stage_enqueue"); - // generate.cpp enqueues the draft on the commit's stream: here the draft stream waits the verifier's - // commit event before its first command, so the GPU orders them without a host wait. - if let Some(event) = after { - event.wait_on(stream)?; - } - // Literal capture happens before h_tok/h_step/h_pos/h_row writes. Its real - // mapped residual staging retains the completed verifier window before DMA. - if first_rows.is_some() { - graph.mtp_stage_first_after_capture()?; - } else { - graph.mtp_stage_window( - stream, - Rc::clone(&window), - selection.take().ok_or(Error::InvalidQwenShape)?, - a, - )?; - } - if let Some((params, history)) = coupled { - graph.mtp_stage_sampling(params, history)?; - } - let generation = ring.begin_original_graph_mutation(prior)?; - if let Err(error) = graph.enqueue(stream) { - if self.context.is_poisoned() { - self.failed = true; - } - return Err(error); - } - self.in_flight = Some(InFlightDraft { - window, - key, - generation, - a, - rows, - first, - max_drafts, - min_p, - coupled: cp, - policy_key, - }); - Ok(()) - } - - /// Read back the first graph of the draft `launch_inner` enqueued, run the chain and close the ring mutation: - /// the second half of `draft_from_verifier`, over the same ring and prior. - pub(super) fn finish_inner( - &mut self, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - policy: &OriginalMtpFullPolicy, - ) -> Result> { - let InFlightDraft { window, key, generation, a, rows, first, max_drafts, min_p, coupled: cp, policy_key } = - self.in_flight.take().ok_or(Error::InvalidQwenShape)?; - self.validate_context(self.context)?; - policy.validate_selected()?; - ring.validate_snapshot(prior)?; - if policy.capture_key() != policy_key - || self.ring_owner.as_ref().is_none_or(|old| !old.same_owner(&prior.owner_id())) - { - return Err(Error::InvalidQwenShape); - } - let full = self.full.as_ref().ok_or(Error::ContextPoisoned)?; - let scalar = self.scalar.as_ref().ok_or(Error::ContextPoisoned)?; - let graphs = self.graphs.as_mut().ok_or(Error::ContextPoisoned)?; - let stream = self.stream.as_mut().ok_or(Error::ContextPoisoned)?; - let graph = graphs.find_mut(key)?.ok_or(Error::InvalidQwenShape)?; - let mut ids = [0i32; 8]; - let mut probabilities = [0f32; 8]; - let mut count; - let span_first = crate::host_profile::span("mtp.finish_first_step"); - let first_result = graph.mtp_finish_step(stream); - drop(span_first); - let output = match first_result { - Ok(o) => o, - Err(error) => { - if self.context.is_poisoned() { - self.failed = true; - } - return Err(error); - } - }; - ids[0] = output.token; - probabilities[0] = output.probability; - count = 1; - // draft j writes the cell first + a + j, and the ring ends at MTP_ORIGINAL_MAX_CELLS (upstream `max_steps`) - let limit = crate::original_mtp_actor::chain_end_within_cells( - (self.max_t as i32 - 1).min(max_drafts), - first.saturating_add(a), - MTP_ORIGINAL_MAX_CELLS, - ); - let mut j = 1usize; - while (j as i32) < limit && probabilities[j - 1] >= min_p { - let _span_chain = crate::host_profile::span("mtp.chain_step"); - let key = OriginalGraphKey::MtpStep { - step: j as u8, - coupled: cp, - }; - let pol = policy.for_capture(j, cp); - let first_capture = graphs.find_mut(key)?.is_none(); - let graph = graphs.record( - key, - stream, - || full.prepare_step(scalar, ring, j, &pol), - |c, r| r.capture(c), - )?; - if first_capture { - self.graph_metadata = self - .graph_metadata - .checked_add(graph.mtp_resource_metadata()?) - .ok_or(Error::BudgetExceeded)?; - if crate::host_profile::enabled() { - eprintln!("DBG mtp chain-step graph {j} (coupled {cp}): {:?} nodes", graph.nodes()); - } - } - graph.mtp_stage_chain()?; - // LELEKA_SERVE_PROFILE: the GPU time of the step's graph (events around the launch), next to its wall time - let mut timing = if crate::host_profile::enabled() { - match ( - self.context.original_gpu_event(crate::OriginalEventKind::Timing), - self.context.original_gpu_event(crate::OriginalEventKind::Timing), - ) { - (Ok(a), Ok(b)) => Some((a, b)), - _ => None, - } - } else { - None - }; - if let Some((a, _)) = timing.as_mut() { - let _ = a.record(stream); - } - let step_result = graph - .enqueue(stream) - .and_then(|_| { - if let Some((_, b)) = timing.as_mut() { - let _ = b.record(stream); - } - graph.mtp_finish_step(stream) - }); - if let Some((a, b)) = timing.as_ref() { - if let Ok(ms) = a.elapsed_ms(b) { - crate::host_profile::add("gpu.mtp_chain_step", f64::from(ms)); - } - } - let output = match step_result { - Ok(o) => o, - Err(error) => { - if self.context.is_poisoned() { - self.failed = true; - } - return Err(error); - } - }; - ids[j] = output.token; - probabilities[j] = output.probability; - count += 1; - j += 1; - } - window.validate_context(self.context)?; - let end = first - .checked_add(rows.max(a + count)) - .ok_or(Error::InvalidSize)?; - let _span_ring = crate::host_profile::span("mtp.finish_ring"); - let snapshot = ring.finish_original_graph_mutation(prior, first, end, generation)?; - Ok(CompletedOriginalMtpDraft { - snapshot, - generation, - window, - ids, - probabilities, - count, - first, - accepted_row: a, - }) - } - /// End of a verifier's life (the serve stack assembles a NEW verifier bank per request). The cached round programs of the - /// direct mode captured the OLD bank's final-R span and keep its completed window alive, and the tail owner keeps the last - /// staged window: that blocks `OriginalVerifyBank::close` (the bank is still shared) and makes the next request's first - /// draft refuse (`stage_round`: the new bank's R is another address). Drain the draft stream, drop the cached programs and - /// the staged window and forget the direct mode, so the next request captures against its own bank. The ring, the scalar - /// prefix and the weights are untouched. - pub fn release_verifier_bindings(&mut self) -> Result<()> { - self.validate_context(self.context)?; - self.stream.as_ref().ok_or(Error::ContextPoisoned)?.synchronize()?; - // a launched draft that was never finished is drained with the stream; its ring mutation stays open - self.in_flight = None; - let cleared = self.graphs.as_mut().ok_or(Error::ContextPoisoned)?.clear(); - self.graph_metadata = 0; - self.direct_window_mode = None; - let source = self.full.as_ref().ok_or(Error::ContextPoisoned)?.release_staged_source(); - if cleared.is_err() || source.is_err() { - self.failed = true; - } - combine(cleared, source) - } - /// The scalar (non-MMQ) draft K/V prefill of a short prompt, run on THIS drafter's own scalar owner. The ring of the shared - /// layout is paired with that owner's main arena (`validate_original_main`): a standalone `original_mtp_scalar_prefill` - /// owns another scratch bank and is refused with InvalidQwenShape. `Drafter::new` moved the owner's stream into the drafter, - /// so it is lent back for the call (the Original's `mtp.prefill` runs on the drafter's `cs_`). - #[allow(clippy::too_many_arguments)] - pub fn record_scalar_prefill<'arena, 'loan>( - &mut self, - residual: &mut crate::OriginalDeviceResidual<'arena, 'loan, 'ctx>, - workspace: &mut crate::NativeBatchWorkspace<'ctx>, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - tokens: &[i32], - cell0: usize, - first_needed: usize, - retained: Rc>, - policy: &OriginalMtpScalarPolicy, - cancelled: impl FnMut() -> bool, - ) -> Result { - self.validate_context(self.context)?; - let stream = self.stream.take().ok_or(Error::ContextPoisoned)?; - let scalar = self.scalar.as_mut().ok_or(Error::ContextPoisoned)?; - scalar.stream = Some(stream); - let result = scalar.record( - residual, workspace, ring, prior, tokens, cell0, first_needed, retained, policy, cancelled, - ); - self.stream = scalar.stream.take(); - if self.stream.is_none() || result.is_err() && self.context.is_poisoned() { - self.failed = true; - } - result - } - pub fn close(mut self) -> Result<()> { - self.close_inner() - } - pub(super) fn close_inner(&mut self) -> Result<()> { - self.failed = true; - let graphs = self - .graphs - .take() - .map_or(Ok(()), OriginalGraphRegistry::close); - let scalar = self - .scalar - .take() - .map_or(Ok(()), OriginalMtpScalarPrefill::close); - let stream = self.stream.take().map_or(Ok(()), OriginalGpuStream::close); - let full = self - .full - .take() - .map_or(Ok(()), OriginalMtpFullForward::close); - combine(combine(combine(graphs, scalar), stream), full) - } -} +#[path = "impl_originalmtpdrafter/impl_originalmtpdrafter_2.rs"] +mod impl_originalmtpdrafter_2; +#[path = "impl_originalmtpdrafter/impl_originalmtpdrafter_2_2.rs"] +mod impl_originalmtpdrafter_2_2; +#[path = "impl_originalmtpdrafter/impl_originalmtpdrafter_3.rs"] +mod impl_originalmtpdrafter_3; diff --git a/crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter/impl_originalmtpdrafter_2.rs b/crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter/impl_originalmtpdrafter_2.rs new file mode 100644 index 00000000..757aaa9f --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter/impl_originalmtpdrafter_2.rs @@ -0,0 +1,121 @@ +//! Moved out of the parent module by STRA-338: impl OriginalMtpDrafter. + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalMtpDrafter<'ctx> { + pub fn new( + full: OriginalMtpFullForward<'ctx>, + mut scalar: OriginalMtpScalarPrefill<'ctx>, + ) -> Result { + full.validate_context(scalar.context)?; + scalar.validate()?; + if full.inner.max_t != scalar.max_t || scalar.has_pending { + return Err(Error::InvalidQwenShape); + } + let c = scalar.context; + let max_t = scalar.max_t; + let stream = scalar.stream.take().ok_or(Error::ContextPoisoned)?; + let mut result = Self { + full: Some(full), + scalar: Some(scalar), + graphs: None, + stream: Some(stream), + context: c, + failed: false, + max_t, + graph_metadata: 0, + direct_window_mode: None, + ring_owner: None, + policy_key: None, + in_flight: None, + }; + let op = (|| { + result.graphs = Some(OriginalGraphRegistry::new( + c, + 2 * (max_t + max_t.saturating_sub(2)), + )?); + Ok(()) + })(); + if let Err(primary) = op { + return combine(Err(primary), result.close_inner()); + } + Ok(result) + } + pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { + if !std::ptr::eq(self.context, c) { + return Err(Error::ContextMismatch); + } + if self.failed || c.is_poisoned() { + return Err(Error::ContextPoisoned); + } + self.full + .as_ref() + .ok_or(Error::ContextPoisoned)? + .validate_context(c)?; + validate_scalar_prefix(self.scalar.as_ref().ok_or(Error::ContextPoisoned)?)?; + self.stream + .as_ref() + .ok_or(Error::ContextPoisoned)? + .validate_context(c) + } + pub fn metadata_bytes(&self) -> Result { + Ok(std::mem::size_of::() + + self + .graphs + .as_ref() + .ok_or(Error::ContextPoisoned)? + .metadata_bytes() + + self.graph_metadata) + } + pub fn is_failed(&self) -> bool { + self.failed || self.context.is_poisoned() + } + /// Original source does not clamp min_p or turn max_drafts==0 into no work: + /// draft0 always runs; continuation uses the literal comparison below. + #[allow(clippy::too_many_arguments)] + pub fn draft( + &mut self, + ring: &mut MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + window: OriginalVerifyWindow<'ctx>, + selection: NativeHeadSelection, + a: usize, + max_drafts: i32, + min_p: f32, + policy: &OriginalMtpFullPolicy, + coupled: Option<(SamplerParams, &[i32; 4096])>, + ) -> Result> { + self.draft_inner( + ring, prior, window, selection, a, max_drafts, min_p, policy, coupled, None, false, + ) + } + #[allow(clippy::too_many_arguments)] + pub fn draft_first( + &mut self, + ring: &mut MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + window: OriginalVerifyWindow<'ctx>, + selection: NativeHeadSelection, + rows: usize, + max_drafts: i32, + min_p: f32, + policy: &OriginalMtpFullPolicy, + coupled: Option<(SamplerParams, &[i32; 4096])>, + ) -> Result> { + self.draft_inner( + ring, + prior, + window, + selection, + 0, + max_drafts, + min_p, + policy, + coupled, + Some(rows), + false, + ) + } +} diff --git a/crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter/impl_originalmtpdrafter_2_2.rs b/crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter/impl_originalmtpdrafter_2_2.rs new file mode 100644 index 00000000..1ee995d7 --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter/impl_originalmtpdrafter_2_2.rs @@ -0,0 +1,177 @@ +//! Moved out of the parent module by STRA-338: impl OriginalMtpDrafter (2). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalMtpDrafter<'ctx> { + #[allow(clippy::too_many_arguments)] + pub(in super::super) fn launch_inner( + &mut self, + ring: &mut MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + window: OriginalVerifyWindow<'ctx>, + selection: NativeHeadSelection, + a: usize, + max_drafts: i32, + min_p: f32, + policy: &OriginalMtpFullPolicy, + coupled: Option<(SamplerParams, &[i32; 4096])>, + first_rows: Option, + direct_window: bool, + after: Option<&mut OriginalGpuEvent<'ctx>>, + ) -> Result<()> { + if self.in_flight.is_some() { + return Err(Error::InvalidQwenShape); + } + self.validate_context(self.context)?; + policy.validate_selected()?; + ring.validate_snapshot(prior)?; + window.validate_context(self.context)?; + window.validate_selection(&selection)?; + let rows = first_rows.unwrap_or(window.rows()); + let first = window.first_position(); + if first_rows.is_some() && window.rows() != 1 { + return Err(Error::InvalidQwenShape); + } + if rows == 0 + || rows > self.max_t + || a >= rows + || first > prior.0.end + || first + .checked_add(rows.max(a + 1)) + .is_none_or(|n| n > MTP_ORIGINAL_MAX_CELLS) + { + return Err(Error::InvalidQwenShape); + } + if self + .direct_window_mode + .is_some_and(|old| old != direct_window) + { + return Err(Error::InvalidQwenShape); + } + self.direct_window_mode = Some(direct_window); + let owner = prior.owner_id(); + let policy_key = policy.capture_key(); + if self + .ring_owner + .as_ref() + .is_some_and(|old| !old.same_owner(&owner)) + || self.policy_key.is_some_and(|old| old != policy_key) + { + return Err(Error::InvalidQwenShape); + } + self.ring_owner = Some(owner); + self.policy_key = Some(policy_key); + let cp = coupled.is_some(); + if cp + && !self + .full + .as_ref() + .ok_or(Error::ContextPoisoned)? + .inner + .coupled + { + return Err(Error::InvalidQwenShape); + } + let window = Rc::new(window); + let mut selection = Some(selection); + if first_rows.is_some() { + let full = self.full.as_ref().ok_or(Error::ContextPoisoned)?; + if direct_window { + full.stage_first_residual_direct( + Rc::clone(&window), + selection.take().ok_or(Error::InvalidQwenShape)?, + rows, + )?; + } else { + full.stage_first_residual( + Rc::clone(&window), + selection.take().ok_or(Error::InvalidQwenShape)?, + rows, + )?; + } + } + let pol = policy.for_capture(0, cp); + let key = OriginalGraphKey::MtpRound { + rows: rows as u8, + coupled: cp, + }; + let full = self.full.as_ref().ok_or(Error::ContextPoisoned)?; + let scalar = self.scalar.as_ref().ok_or(Error::ContextPoisoned)?; + let graphs = self.graphs.as_mut().ok_or(Error::ContextPoisoned)?; + let stream = self.stream.as_mut().ok_or(Error::ContextPoisoned)?; + let span_record = crate::host_profile::span("mtp.launch_record"); + let first_capture = graphs.find_mut(key)?.is_none(); + let graph = graphs.record( + key, + stream, + || { + if direct_window { + full.prepare_round_from_verifier_rows( + scalar, + ring, + Rc::clone(&window), + rows, + first_rows.is_some(), + &pol, + ) + } else { + full.prepare_round(scalar, ring, rows, &pol) + } + }, + |c, r| r.capture(c), + )?; + drop(span_record); + if first_capture { + self.graph_metadata = self + .graph_metadata + .checked_add(graph.mtp_resource_metadata()?) + .ok_or(Error::BudgetExceeded)?; + if crate::host_profile::enabled() { + eprintln!("DBG mtp round graph rows {rows} (coupled {cp}): {:?} nodes", graph.nodes()); + } + } + let _span_stage = crate::host_profile::span("mtp.launch_stage_enqueue"); + // generate.cpp enqueues the draft on the commit's stream: here the draft stream waits the verifier's + // commit event before its first command, so the GPU orders them without a host wait. + if let Some(event) = after { + event.wait_on(stream)?; + } + // Literal capture happens before h_tok/h_step/h_pos/h_row writes. Its real + // mapped residual staging retains the completed verifier window before DMA. + if first_rows.is_some() { + graph.mtp_stage_first_after_capture()?; + } else { + graph.mtp_stage_window( + stream, + Rc::clone(&window), + selection.take().ok_or(Error::InvalidQwenShape)?, + a, + )?; + } + if let Some((params, history)) = coupled { + graph.mtp_stage_sampling(params, history)?; + } + let generation = ring.begin_original_graph_mutation(prior)?; + if let Err(error) = graph.enqueue(stream) { + if self.context.is_poisoned() { + self.failed = true; + } + return Err(error); + } + self.in_flight = Some(InFlightDraft { + window, + key, + generation, + a, + rows, + first, + max_drafts, + min_p, + coupled: cp, + policy_key, + }); + Ok(()) + } +} diff --git a/crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter/impl_originalmtpdrafter_3.rs b/crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter/impl_originalmtpdrafter_3.rs new file mode 100644 index 00000000..6684b137 --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter/impl_originalmtpdrafter_3.rs @@ -0,0 +1,211 @@ +//! Moved out of the parent module by STRA-338: impl OriginalMtpDrafter (3). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalMtpDrafter<'ctx> { + + /// Read back the first graph of the draft `launch_inner` enqueued, run the chain and close the ring mutation: + /// the second half of `draft_from_verifier`, over the same ring and prior. + pub(in super::super) fn finish_inner( + &mut self, + ring: &mut MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + policy: &OriginalMtpFullPolicy, + ) -> Result> { + let InFlightDraft { window, key, generation, a, rows, first, max_drafts, min_p, coupled: cp, policy_key } = + self.in_flight.take().ok_or(Error::InvalidQwenShape)?; + self.validate_context(self.context)?; + policy.validate_selected()?; + ring.validate_snapshot(prior)?; + if policy.capture_key() != policy_key + || self.ring_owner.as_ref().is_none_or(|old| !old.same_owner(&prior.owner_id())) + { + return Err(Error::InvalidQwenShape); + } + let full = self.full.as_ref().ok_or(Error::ContextPoisoned)?; + let scalar = self.scalar.as_ref().ok_or(Error::ContextPoisoned)?; + let graphs = self.graphs.as_mut().ok_or(Error::ContextPoisoned)?; + let stream = self.stream.as_mut().ok_or(Error::ContextPoisoned)?; + let graph = graphs.find_mut(key)?.ok_or(Error::InvalidQwenShape)?; + let mut ids = [0i32; 8]; + let mut probabilities = [0f32; 8]; + let mut count; + let span_first = crate::host_profile::span("mtp.finish_first_step"); + let first_result = graph.mtp_finish_step(stream); + drop(span_first); + let output = match first_result { + Ok(o) => o, + Err(error) => { + if self.context.is_poisoned() { + self.failed = true; + } + return Err(error); + } + }; + ids[0] = output.token; + probabilities[0] = output.probability; + count = 1; + // draft j writes the cell first + a + j, and the ring ends at MTP_ORIGINAL_MAX_CELLS (upstream `max_steps`) + let limit = crate::original_mtp_actor::chain_end_within_cells( + (self.max_t as i32 - 1).min(max_drafts), + first.saturating_add(a), + MTP_ORIGINAL_MAX_CELLS, + ); + let mut j = 1usize; + while (j as i32) < limit && probabilities[j - 1] >= min_p { + let _span_chain = crate::host_profile::span("mtp.chain_step"); + let key = OriginalGraphKey::MtpStep { + step: j as u8, + coupled: cp, + }; + let pol = policy.for_capture(j, cp); + let first_capture = graphs.find_mut(key)?.is_none(); + let graph = graphs.record( + key, + stream, + || full.prepare_step(scalar, ring, j, &pol), + |c, r| r.capture(c), + )?; + if first_capture { + self.graph_metadata = self + .graph_metadata + .checked_add(graph.mtp_resource_metadata()?) + .ok_or(Error::BudgetExceeded)?; + if crate::host_profile::enabled() { + eprintln!("DBG mtp chain-step graph {j} (coupled {cp}): {:?} nodes", graph.nodes()); + } + } + graph.mtp_stage_chain()?; + // LELEKA_SERVE_PROFILE: the GPU time of the step's graph (events around the launch), next to its wall time + let mut timing = if crate::host_profile::enabled() { + match ( + self.context.original_gpu_event(crate::OriginalEventKind::Timing), + self.context.original_gpu_event(crate::OriginalEventKind::Timing), + ) { + (Ok(a), Ok(b)) => Some((a, b)), + _ => None, + } + } else { + None + }; + if let Some((a, _)) = timing.as_mut() { + let _ = a.record(stream); + } + let step_result = graph + .enqueue(stream) + .and_then(|_| { + if let Some((_, b)) = timing.as_mut() { + let _ = b.record(stream); + } + graph.mtp_finish_step(stream) + }); + if let Some((a, b)) = timing.as_ref() { + if let Ok(ms) = a.elapsed_ms(b) { + crate::host_profile::add("gpu.mtp_chain_step", f64::from(ms)); + } + } + let output = match step_result { + Ok(o) => o, + Err(error) => { + if self.context.is_poisoned() { + self.failed = true; + } + return Err(error); + } + }; + ids[j] = output.token; + probabilities[j] = output.probability; + count += 1; + j += 1; + } + window.validate_context(self.context)?; + let end = first + .checked_add(rows.max(a + count)) + .ok_or(Error::InvalidSize)?; + let _span_ring = crate::host_profile::span("mtp.finish_ring"); + let snapshot = ring.finish_original_graph_mutation(prior, first, end, generation)?; + Ok(CompletedOriginalMtpDraft { + snapshot, + generation, + window, + ids, + probabilities, + count, + first, + accepted_row: a, + }) + } + /// End of a verifier's life (the serve stack assembles a NEW verifier bank per request). The cached round programs of the + /// direct mode captured the OLD bank's final-R span and keep its completed window alive, and the tail owner keeps the last + /// staged window: that blocks `OriginalVerifyBank::close` (the bank is still shared) and makes the next request's first + /// draft refuse (`stage_round`: the new bank's R is another address). Drain the draft stream, drop the cached programs and + /// the staged window and forget the direct mode, so the next request captures against its own bank. The ring, the scalar + /// prefix and the weights are untouched. + pub fn release_verifier_bindings(&mut self) -> Result<()> { + self.validate_context(self.context)?; + self.stream.as_ref().ok_or(Error::ContextPoisoned)?.synchronize()?; + // a launched draft that was never finished is drained with the stream; its ring mutation stays open + self.in_flight = None; + let cleared = self.graphs.as_mut().ok_or(Error::ContextPoisoned)?.clear(); + self.graph_metadata = 0; + self.direct_window_mode = None; + let source = self.full.as_ref().ok_or(Error::ContextPoisoned)?.release_staged_source(); + if cleared.is_err() || source.is_err() { + self.failed = true; + } + combine(cleared, source) + } + /// The scalar (non-MMQ) draft K/V prefill of a short prompt, run on THIS drafter's own scalar owner. The ring of the shared + /// layout is paired with that owner's main arena (`validate_original_main`): a standalone `original_mtp_scalar_prefill` + /// owns another scratch bank and is refused with InvalidQwenShape. `Drafter::new` moved the owner's stream into the drafter, + /// so it is lent back for the call (the Original's `mtp.prefill` runs on the drafter's `cs_`). + #[allow(clippy::too_many_arguments)] + pub fn record_scalar_prefill<'arena, 'loan>( + &mut self, + residual: &mut crate::OriginalDeviceResidual<'arena, 'loan, 'ctx>, + workspace: &mut crate::NativeBatchWorkspace<'ctx>, + ring: &mut MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + tokens: &[i32], + cell0: usize, + first_needed: usize, + retained: Rc>, + policy: &OriginalMtpScalarPolicy, + cancelled: impl FnMut() -> bool, + ) -> Result { + self.validate_context(self.context)?; + let stream = self.stream.take().ok_or(Error::ContextPoisoned)?; + let scalar = self.scalar.as_mut().ok_or(Error::ContextPoisoned)?; + scalar.stream = Some(stream); + let result = scalar.record( + residual, workspace, ring, prior, tokens, cell0, first_needed, retained, policy, cancelled, + ); + self.stream = scalar.stream.take(); + if self.stream.is_none() || result.is_err() && self.context.is_poisoned() { + self.failed = true; + } + result + } + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + pub(in super::super) fn close_inner(&mut self) -> Result<()> { + self.failed = true; + let graphs = self + .graphs + .take() + .map_or(Ok(()), OriginalGraphRegistry::close); + let scalar = self + .scalar + .take() + .map_or(Ok(()), OriginalMtpScalarPrefill::close); + let stream = self.stream.take().map_or(Ok(()), OriginalGpuStream::close); + let full = self + .full + .take() + .map_or(Ok(()), OriginalMtpFullForward::close); + combine(combine(combine(graphs, scalar), stream), full) + } +} diff --git a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2.rs b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2.rs index 739a4509..f210fb9b 100644 --- a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2.rs +++ b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2.rs @@ -3,916 +3,9 @@ #[allow(unused_imports)] use super::*; -impl OriginalMtpFullForward<'_> { - pub(super) fn plan( - &self, - p: &ForwardPrefix<'_, '_>, - policy: &OriginalMtpFullPolicy, - ) -> Result> { - self.inner.validate(p.scalar.context)?; - validate_scalar_prefix(p.scalar)?; - p.ring.validate_context(p.scalar.context)?; - if policy.legacy_router_mode > 2 { - return Err(Error::InvalidProjectionShape); - } - let o = &self.inner; - let w = &o.weights; - let wa = |i: usize| -> Result { - Ok(w.roles[i] - .handle - .ok_or(Error::ContextPoisoned)? - .qwen_address()) - }; - let a = |i| o.address(i); - let mut v = Vec::new(); - v.try_reserve_exact(110) - .map_err(|_| Error::HostAllocation)?; - // Prefix quantized mixed remains live: Q uses same Q8 image as K and V. - // Original Q split is 24 distinct width256 rows, equivalent to its 2D D2D. - let qfull = a(0)?; - let qcur = a(1)?; - let attn = a(2)?; - let gated = a(3)?; - let bo = a(4)?; - // Native Q8_0 body is shared with prefix's literal MMVQ module; its command - // is retained in ForwardProgram, not submitted through an old default API. - // Slot0 below is a full native MMVQ asset; explicit input/output geometry. - let qweight = wa(0)?; - let qentry = fixed_entry(13, "head_n8_s0")?; - push( - &mut v, - 13, - qentry, - [12288, 1, 1], - [32, 4, 1], - 0, - vec![ - F::U64(qweight), - F::U64(p.q), - F::U64(qfull), - F::I32(2560), - F::I32(12288), - ], - )?; - self.finite_tail(&mut v, qfull, 12288, 0)?; - // Copy commands remain distinct byte transports (24 literal rows); their - // execution is interleaved in ForwardProgram immediately before Q norm. - let norm_entry = 0; - push( - &mut v, - 16, - norm_entry, - [24, 1, 1], - [256, 1, 1], - 0, - vec![ - F::U64(qcur), - F::U64(wa(1)?), - F::U64(qcur), - F::I32(256), - F::F32(1e-6), - ], - )?; - self.finite_tail(&mut v, qcur, 6144, 1)?; - let kv = &policy.kv; - if kv.disabled - || kv.hybrid - || kv.rotated - || kv.q4 - || kv.alternate_f16 - || kv.mode != 0 - || kv.rope_table_enabled - || kv.multimodal_positions - { - return Err(Error::UnsupportedQwenOperation); - } - push( - &mut v, - 16, - 1, - [4, 24, 1], - [32, 1, 1], - 0, - vec![ - F::U64(qcur), - F::U64(qcur), - F::I32(24), - F::I32(256), - F::I32(64), - F::F32(kv.theta_scale), - F::F32(kv.freq_scale), - F::F32(kv.corr_low), - F::F32(kv.corr_high), - F::F32(kv.ext_factor), - F::F32(kv.mscale), - F::U64(p.pos), - F::U64(0), - F::Words3([0; 3]), - ], - )?; - self.finite_tail(&mut v, qcur, 6144, 2)?; - // Original window_ids on actual private step, followed by same INT8 decode - // chunk and merge entries. Ring owns pools/table/ident/scratch throughout. - // window command uses ring's actual KV module in the captured program. - let (pa, pm, pl, ident) = o.attention(p.ring)?; - let chain_mtp = crate::original_verify::chain::flags().mtp; - // the Original's chunk kernel in both modes (the load-hoisted variant measured no faster); only the merge changes - let daily = daily_mtp(); - push( - &mut v, - if daily { symbols::DAILY_ASSET } else { 19 }, - if daily { symbols::DAILY_CHUNK } else { 0 }, - [CHUNKS as u32, 2, 1], - [256, 1, 1], - 0, - vec![ - F::U64(qcur), - F::U64(p.ring.address(0)?), - F::U64(p.ring.address(1)?), - F::U64(p.ring.address(2)?), - F::U64(p.ring.address(3)?), - F::U64(p.ring.address(4)?), - F::U64(ident), - F::U64(p.step), - F::I32(2), - F::I32(4), - F::F32(1.0 / 16.0), - F::U64(pa), - F::U64(pm), - F::U64(pl), - F::I32(CHUNKS as i32), - F::I32(32768), - F::I64(SCRATCH_FLOATS as i64), - ], - )?; - let mut merge_args = vec![ - F::U64(pa), - F::U64(pm), - F::U64(pl), - F::I32(CHUNKS as i32), - F::U64(attn), - F::I64(SCRATCH_FLOATS as i64), - ]; - if daily { - // merge_v2 takes the step words after n_chunks: (acc, m, l, n_chunks, steps, attn, stride) - merge_args = vec![ - F::U64(pa), - F::U64(pm), - F::U64(pl), - F::I32(CHUNKS as i32), - F::U64(p.step), - F::U64(attn), - F::I64(SCRATCH_FLOATS as i64), - ]; - } else if chain_mtp { - merge_args.push(F::U64(p.step)); // the row's step words: n_ids bounds the merge to the chunks that hold cells - } - push( - &mut v, - if daily { symbols::DAILY_ASSET } else if chain_mtp { symbols::CHAIN_ASSET } else { 19 }, - if daily { symbols::DAILY_MERGE_V2 } else if chain_mtp { symbols::CHAIN_QSA_MERGE_N } else { 1 }, - [24, 1, 1], - [256, 1, 1], - 0, - merge_args, - )?; - self.finite_tail(&mut v, attn, 6144, 3)?; - push( - &mut v, - 11, - 0, - [24, 1, 1], - [256, 1, 1], - 0, - vec![ - F::U64(attn), - F::U64(qfull), - F::U64(gated), - F::I32(24), - F::I32(256), - ], - )?; - self.finite_tail(&mut v, gated, 6144, 4)?; - self.quant(&mut v, gated, p.q, 6144)?; - self.q8_tail(&mut v, p.q, 6144, 5)?; - self.mmvq(&mut v, wa(2)?, p.q, bo, 6144, 2560)?; - self.finite_tail(&mut v, bo, 2560, 6)?; - self.mlp_gr(&mut v, p, bo, policy)?; - self.finite_tail(&mut v, p.r, 10240, 7)?; - self.finite_tail( - &mut v, - p.scalar.address(7, p.scalar.max_t * 40960)?, - 10240, - 8, - )?; - self.finite_tail(&mut v, p.scalar.address(8, p.scalar.max_t * 1280)?, 320, 9)?; - self.finite_tail(&mut v, a(20)?, 4, 10)?; - self.finite_tail(&mut v, p.mixed, 2560, 11)?; - let router = a(5)?; - self.mmvf(&mut v, p.mixed, wa(7)?, router, 2560, 512)?; - self.finite_tail(&mut v, router, 512, 12)?; - if policy.native_router { - push( - &mut v, - 3, - 0, - [1, 1, 1], - [32, 8, 1], - 0, - vec![F::U64(router), F::U64(a(7)?), F::U64(a(6)?)], - )?; - } else { - push( - &mut v, - 4, - policy.legacy_router_mode as usize, - [1, 1, 1], - [512, 1, 1], - (512 + 512 * 8 + 512 * 4) as u32, - vec![ - F::U64(router), - F::I32(1), - F::I32(512), - F::I32(10), - F::U64(a(7)?), - F::U64(a(6)?), - ], - )?; - } - self.finite_tail(&mut v, a(6)?, 10, 13)?; - let expert = w - .experts - .handle - .ok_or(Error::ContextPoisoned)? - .qwen_address(); - push( - &mut v, - 0, - 0, - [1, 1, 1], - [128, 1, 1], - 0, - vec![ - F::U64(a(7)?), - F::I32(10), - F::I32(10), - F::U64(expert), - F::I64(1382400), - F::U64(a(12)?), - F::U64(a(13)?), - F::U64(a(14)?), - F::U64(a(8)?), - F::U64(a(10)?), - ], - )?; - push( - &mut v, - 1, - 0, - [1, 1, 1], - [128, 1, 1], - 0, - vec![F::U64(p.mixed), F::U64(a(15)?), F::U64(a(16)?), F::I64(80)], - )?; - let s2 = a(17)?; - let hiddenq = s2 + 51200; - let hscale = hiddenq + 6816; - push( - &mut v, - 0, - if policy.old_grouped_s2 { 1 } else { 2 }, - [40, 10, 1], - [256, 1, 1], - 0, - vec![ - F::U64(a(12)?), - F::U64(a(13)?), - F::U64(a(14)?), - F::U64(a(10)?), - F::U64(a(15)?), - F::U64(a(16)?), - F::U64(s2), - F::I32(10), - ], - )?; - self.finite_tail(&mut v, s2, 12800, 14)?; - push( - &mut v, - 0, - 3, - [6400usize.div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![F::U64(s2), F::I64(6400)], - )?; - self.finite_tail(&mut v, s2, 6400, 15)?; - push( - &mut v, - 1, - 0, - [200usize.div_ceil(128) as u32, 1, 1], - [128, 1, 1], - 0, - vec![F::U64(s2), F::U64(hiddenq), F::U64(hscale), F::I64(200)], - )?; - push( - &mut v, - 0, - if policy.old_grouped_s2 { 4 } else { 5 }, - [40, 10, 1], - [256, 1, 1], - 0, - vec![ - F::U64(a(12)?), - F::U64(a(13)?), - F::U64(a(14)?), - F::U64(a(8)?), - F::U64(hiddenq), - F::U64(hscale), - F::U64(a(9)?), - ], - )?; - self.finite_tail(&mut v, a(9)?, 25600, 16)?; - // Shared projection consumes original mixed, not its unconditional BF16 image. - push( - &mut v, - 10, - 0, - [10, 1, 1], - [256, 1, 1], - 0, - vec![F::U64(p.mixed), F::U64(a(23)?), F::I64(2560)], - )?; - self.quant(&mut v, p.mixed, p.q, 2560)?; - self.q8_tail(&mut v, p.q, 2560, 17)?; - self.mmvq(&mut v, wa(8)?, p.q, a(18)?, 2560, 640)?; - self.mmvq(&mut v, wa(9)?, p.q, a(19)?, 2560, 640)?; - self.finite_tail(&mut v, a(18)?, 640, 18)?; - self.finite_tail(&mut v, a(19)?, 640, 19)?; - push( - &mut v, - 2, - 0, - [5, 1, 1], - [128, 1, 1], - 0, - vec![F::U64(a(18)?), F::U64(a(19)?), F::U64(a(18)?), F::I32(640)], - )?; - self.finite_tail(&mut v, a(18)?, 640, 20)?; - self.quant(&mut v, a(18)?, p.q, 640)?; - self.q8_tail(&mut v, p.q, 640, 21)?; - self.mmvq(&mut v, wa(10)?, p.q, a(11)?, 640, 2560)?; - self.finite_tail(&mut v, a(11)?, 2560, 22)?; - if policy.native_shared_scalar { - self.mmvf(&mut v, p.mixed, wa(11)?, a(22)?, 2560, 1)?; - push(&mut v, 2, 2, [1, 1, 1], [1, 1, 1], 0, vec![F::U64(a(22)?)])?; - } else { - push( - &mut v, - 2, - 1, - [1, 1, 1], - [256, 1, 1], - 0, - vec![ - F::U64(a(23)?), - F::U64(wa(11)?), - F::U64(a(22)?), - F::I32(2560), - ], - )?; - } - self.finite_tail(&mut v, a(22)?, 1, 23)?; - push( - &mut v, - 2, - 3, - [20, 1, 1], - [128, 1, 1], - 0, - vec![F::U64(a(11)?), F::U64(a(22)?), F::I32(2560)], - )?; - self.finite_tail(&mut v, a(11)?, 2560, 24)?; - let mut combine_args = vec![ - F::U64(a(9)?), - F::U64(a(6)?), - F::U64(a(11)?), - F::U64(o.combined()?), - ]; - if policy.native_combine { - combine_args.extend([F::I64(2560), F::I32(10)]); - } else { - combine_args.extend([F::I32(2560), F::I32(10), F::I32(1)]); - } - push( - &mut v, - if policy.native_combine { 5 } else { 2 }, - if policy.native_combine { 0 } else { 4 }, - [if policy.native_combine { 10 } else { 20 }, 1, 1], - [if policy.native_combine { 256 } else { 128 }, 1, 1], - 0, - combine_args, - )?; - self.finite_tail(&mut v, o.combined()?, 2560, 25)?; - if policy.native_final_gr { - push( - &mut v, - 8, - 2, - [40, 1, 1], - [256, 1, 1], - 0, - vec![ - F::U64(p.r), - F::U64(o.combined()?), - F::U64(a(20)?), - F::U64(p.r), - F::I32(2560), - F::I32(4), - F::F32(0.25), - ], - )?; - } else { - push( - &mut v, - 9, - 0, - [40, 1, 1], - [256, 1, 1], - 16, - vec![ - F::U64(p.r), - F::U64(o.combined()?), - F::U64(a(20)?), - F::I32(2560), - F::I32(4), - F::U64(p.r), - ], - )?; - } - self.finite_tail(&mut v, p.r, 10240, 26)?; - self.final_gr(&mut v, p, policy)?; - self.finite_tail(&mut v, a(24)?, 2560, 27)?; - self.quant(&mut v, a(24)?, p.q, 2560)?; - self.q8_tail(&mut v, p.q, 2560, 28)?; - let (name, grid, block, iq) = - head_dispatch::head_dispatch(w.head_kind, 2560, w.vocab, 1, w.dispatch)?; - let asset = if iq { 14 } else { 13 }; - let index = fixed_entry(asset, name)?; - let mut args = vec![F::U64( - w.head.handle.ok_or(Error::ContextPoisoned)?.qwen_address(), - )]; - if iq { - args.push(F::U64( - crate::native_head_row_bytes(w.head_kind, 2560)? as u64 - )); - } - args.extend([ - F::U64(p.q), - F::U64(o.logits()?), - F::I32(2560), - F::I32(w.vocab as i32), - ]); - if iq { - args.push(F::I32(1)); - } - push(&mut v, asset, index, grid, block, 0, args)?; - self.finite_tail(&mut v, o.logits()?, w.vocab, 29)?; - if let Some(j) = policy.coupled_j { - if !o.coupled || j >= 8 { - return Err(Error::InvalidQwenShape); - } - let blocks = w.vocab.div_ceil(4096); - let kpart = w.vocab.min(64); - let sub = w - .subset - .as_ref() - .map(|(f, _)| { - f.handle - .ok_or(Error::ContextPoisoned) - .map(|h| h.qwen_address()) - }) - .transpose()? - .unwrap_or(0); - let inv = w - .subset - .as_ref() - .map(|(_, i)| { - i.handle - .ok_or(Error::ContextPoisoned) - .map(|h| h.qwen_address()) - }) - .transpose()? - .unwrap_or(0); - push( - &mut v, - 20, - 2, - [1, 1, 1], - [1024, 1, 1], - (w.vocab.div_ceil(32) * 4) as u32, - vec![ - F::U64(o.logits()?), - F::I32(w.vocab as i32), - F::U64(inv), - F::I32(w.id_vocab as i32), - F::U64(a(28)?), - F::U64(a(29)?), - F::I32(4096), - F::I32(j as i32), - ], - )?; - push( - &mut v, - 20, - 0, - [blocks as u32, 1, 1], - [128, 1, 1], - 0, - vec![ - F::U64(o.logits()?), - F::I32(w.vocab as i32), - F::U64(0), - F::I32(0), - F::Params(SamplerParams::default()), - F::I32(kpart as i32), - F::I32(blocks as i32), - F::U64(a(30)?), - ], - )?; - push( - &mut v, - 20, - 3, - [1, 1, 1], - [32, 1, 1], - 0, - vec![ - F::U64(a(30)?), - F::I32(blocks as i32), - F::I32(w.vocab as i32), - F::I32(kpart as i32), - F::U64(a(28)?), - F::U64(p.step), - F::U64(sub), - F::U64(a(29)?), - F::I32(4096), - F::I32(j as i32), - F::U64(o.address(34)?), - F::U64(o.address(35)?), - ], - )?; - } else { - let mut greedy = SamplerParams::default(); - greedy.greedy = true; - greedy.temperature = 0.0; - let chain_head = crate::original_verify::chain::flags().head; - push( - &mut v, - if chain_head { symbols::CHAIN_ASSET } else { 15 }, - if chain_head { symbols::CHAIN_SAMPLER_GREEDY } else { 0 }, - [1, 1, 1], - [1024, 1, 1], - 0, - vec![ - F::U64(o.logits()?), - F::I32(w.vocab as i32), - F::U64(0), - F::I32(0), - F::Params(greedy), - F::I32(0), - F::I32(0), - F::U64(o.address(34)?), - ], - )?; - push( - &mut v, - if chain_head { symbols::CHAIN_ASSET } else { 12 }, - if chain_head { symbols::CHAIN_ROW_TOP_PROB } else { 0 }, - [1, 1, 1], - [1024, 1, 1], - 0, - vec![ - F::U64(o.logits()?), - F::I32(w.vocab as i32), - F::U64(o.address(34)?), - F::U64(o.address(35)?), - ], - )?; - if let Some((forward, _)) = &w.subset { - push( - &mut v, - 12, - 1, - [1, 1, 1], - [64, 1, 1], - 0, - vec![ - F::U64(o.address(34)?), - F::U64(forward.handle.ok_or(Error::ContextPoisoned)?.qwen_address()), - F::I32(1), - ], - )?; - } - } - Ok(v) - } - pub(super) fn finite_tail(&self, v: &mut Vec, x: u64, n: usize, slot: usize) -> Result<()> { - if slot >= TAIL_FLAGS || n == 0 || n > i32::MAX as usize { - return Err(Error::InvalidSize); - } - push( - v, - 18, - 0, - [n.div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - F::U64(x), - F::I32(n as i32), - F::U64(self.inner.address(27)? + (slot * 4) as u64), - ], - ) - } - pub(super) fn q8_tail(&self, v: &mut Vec, x: u64, n: usize, slot: usize) -> Result<()> { - if slot >= TAIL_FLAGS || n == 0 || n % 32 != 0 { - return Err(Error::InvalidSize); - } - push( - v, - 18, - 1, - [(n / 32).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - F::U64(x), - F::I32((n / 32) as i32), - F::U64(self.inner.address(27)? + (slot * 4) as u64), - ], - ) - } - pub(super) fn quant(&self, v: &mut Vec, x: u64, q: u64, n: usize) -> Result<()> { - push( - v, - 13, - fixed_entry(13, "head_quant")?, - [n.div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![F::U64(x), F::U64(q), F::I32(n as i32)], - ) - } - pub(super) fn mmvq( - &self, - v: &mut Vec, - w: u64, - q: u64, - y: u64, - n: usize, - out: usize, - ) -> Result<()> { - let (name, grid, block, _) = - head_dispatch::head_dispatch(8, n, out, 1, NativeHeadDispatch::default())?; - push( - v, - 13, - fixed_entry(13, name)?, - grid, - block, - 0, - vec![ - F::U64(w), - F::U64(q), - F::U64(y), - F::I32(n as i32), - F::I32(out as i32), - ], - ) - } - pub(super) fn mmvf( - &self, - v: &mut Vec, - x: u64, - w: u64, - y: u64, - n: usize, - out: usize, - ) -> Result<()> { - let b = mmvf_block(n); - push( - v, - 6, - (b / 32 - 1) as usize, - [out as u32, 1, 1], - [b, 1, 1], - 0, - vec![F::U64(x), F::U64(w), F::U64(y), F::I32(n as i32)], - ) - } - pub(super) fn mlp_gr( - &self, - v: &mut Vec, - p: &ForwardPrefix<'_, '_>, - bo: u64, - policy: &OriginalMtpFullPolicy, - ) -> Result<()> { - let w = &self.inner.weights.roles; - let wa = |i: usize| { - w[i].handle - .ok_or(Error::ContextPoisoned) - .map(|h| h.qwen_address()) - }; - let s = p.scalar; - let xn = s.address(7, s.max_t * 40960)?; - let mut words = Box::new([0u64; 114]); - let a = &mut words[..14]; - a[0] = p.r; - a[1] = p.r; - a[2] = 1; - a[3] = bo; - a[4] = p.inj; - a[5] = wa(3)?; - a[6] = wa(4)?; - a[7] = wa(5)?; - a[8] = wa(6)?; - a[9] = u64::from(1e-6f32.to_bits()); - a[10] = s.address(8, s.max_t * 1280)?; - a[11] = s.address(9, s.max_t * 16)?; - a[12] = self.inner.address(20)?; - a[13] = p.mixed; - words[112] = xn; - words[113] = 1; - let args = words; - // Actual same GR module as prefix, stable by-value arguments. ForwardProgram - // carries this separate scalar-module command (no reloaded module/math). - - let make = || F::GrMulti(args.clone()); - push( - v, - 17, - if policy.gr == OriginalMtpGrVariant::Plain { - 0 - } else { - 1 - }, - [ - 1, - if policy.gr == OriginalMtpGrVariant::Plain { - 1 - } else { - 4 - }, - 1, - ], - [256, 1, 1], - 0, - vec![make()], - )?; - let bytes = if policy.gr == OriginalMtpGrVariant::Staged { - 10240 - } else { - s.plain_tile * 4 - }; - if s.shared_limit < bytes { - return Err(Error::InvalidProjectionShape); - } - push( - v, - 17, - if policy.gr == OriginalMtpGrVariant::Staged { - 2 - } else if s.plain_tile == 1280 { - 4 - } else { - 5 - }, - [41, 1, 1], - [256, 1, 1], - bytes as u32, - vec![make()], - )?; - push(v, 17, 3, [160, 1, 1], [256, 1, 1], 0, vec![make()]) - } - pub(super) fn final_gr( - &self, - v: &mut Vec, - p: &ForwardPrefix<'_, '_>, - policy: &OriginalMtpFullPolicy, - ) -> Result<()> { - let a = |i| self.inner.address(i); - let w = &self.inner.weights.roles; - let wa = |i: usize| { - w[i].handle - .ok_or(Error::ContextPoisoned) - .map(|h| h.qwen_address()) - }; - let xn = p.scalar.address(7, p.scalar.max_t * 40960)?; - let lo = p.scalar.address(8, p.scalar.max_t * 1280)?; - if policy.native_final_gr { - push( - v, - 7, - 0, - [4, 1, 1], - [1024, 1, 1], - 0, - vec![ - F::U64(p.r), - F::U64(wa(12)?), - F::U64(xn), - F::I32(2560), - F::F32(1e-6), - ], - )?; - self.mmvf(v, xn, wa(13)?, lo, 10240, 320)?; - push( - v, - 8, - 0, - [2, 1, 1], - [256, 1, 1], - 0, - vec![F::U64(lo), F::I32(320), F::F32(0.25)], - )?; - self.mmvf(v, lo, wa(14)?, a(25)?, 320, 10240)?; - push( - v, - 8, - 1, - [10, 1, 1], - [256, 1, 1], - 0, - vec![ - F::U64(xn), - F::U64(a(25)?), - F::U64(a(24)?), - F::I32(2560), - F::I32(4), - F::F32(0.25), - ], - )?; - } else { - let fp = policy.fp32_final_gr; - push( - v, - 9, - if fp { 1 } else { 2 }, - [4, 1, 1], - [256, 1, 1], - 0, - vec![ - F::U64(p.r), - F::U64(wa(12)?), - F::F32(1e-6), - F::I32(2560), - F::U64(xn), - F::U64(a(25)?), - ], - )?; - push( - v, - 9, - if fp { 3 } else { 4 }, - [320, 1, 1], - [256, 1, 1], - 0, - vec![ - F::U64(if fp { xn } else { a(25)? }), - F::U64(wa(13)?), - F::I32(10240), - F::I32(320), - F::I32(4), - F::U64(if fp { lo } else { a(26)? }), - ], - )?; - push( - v, - 9, - if fp { 5 } else { 6 }, - [1280, 1, 1], - [256, 1, 1], - 0, - vec![ - F::U64(if fp { lo } else { a(26)? }), - F::U64(wa(14)?), - F::U64(xn), - F::I32(10240), - F::I32(320), - F::U64(a(25)?), - ], - )?; - push( - v, - 9, - 7, - [10, 1, 1], - [256, 1, 1], - 0, - vec![F::U64(a(25)?), F::I32(2560), F::I32(4), F::U64(a(24)?)], - )?; - } - Ok(()) - } -} +#[path = "impl_originalmtpfullforward_2/impl_originalmtpfullforward.rs"] +mod impl_originalmtpfullforward; +#[path = "impl_originalmtpfullforward_2/impl_originalmtpfullforward_2_2.rs"] +mod impl_originalmtpfullforward_2_2; +#[path = "impl_originalmtpfullforward_2/impl_originalmtpfullforward_3.rs"] +mod impl_originalmtpfullforward_3; diff --git a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2/impl_originalmtpfullforward.rs b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2/impl_originalmtpfullforward.rs new file mode 100644 index 00000000..a4ec884e --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2/impl_originalmtpfullforward.rs @@ -0,0 +1,621 @@ +//! Moved out of the parent module by STRA-338: impl OriginalMtpFullForward. + +#[allow(unused_imports)] +use super::*; + + +impl OriginalMtpFullForward<'_> { + pub(in super::super) fn plan( + &self, + p: &ForwardPrefix<'_, '_>, + policy: &OriginalMtpFullPolicy, + ) -> Result> { + self.inner.validate(p.scalar.context)?; + validate_scalar_prefix(p.scalar)?; + p.ring.validate_context(p.scalar.context)?; + if policy.legacy_router_mode > 2 { + return Err(Error::InvalidProjectionShape); + } + let o = &self.inner; + let w = &o.weights; + let wa = |i: usize| -> Result { + Ok(w.roles[i] + .handle + .ok_or(Error::ContextPoisoned)? + .qwen_address()) + }; + let a = |i| o.address(i); + let mut v = Vec::new(); + v.try_reserve_exact(110) + .map_err(|_| Error::HostAllocation)?; + // Prefix quantized mixed remains live: Q uses same Q8 image as K and V. + // Original Q split is 24 distinct width256 rows, equivalent to its 2D D2D. + let qfull = a(0)?; + let qcur = a(1)?; + let attn = a(2)?; + let gated = a(3)?; + let bo = a(4)?; + // Native Q8_0 body is shared with prefix's literal MMVQ module; its command + // is retained in ForwardProgram, not submitted through an old default API. + // Slot0 below is a full native MMVQ asset; explicit input/output geometry. + let qweight = wa(0)?; + let qentry = fixed_entry(13, "head_n8_s0")?; + push( + &mut v, + 13, + qentry, + [12288, 1, 1], + [32, 4, 1], + 0, + vec![ + F::U64(qweight), + F::U64(p.q), + F::U64(qfull), + F::I32(2560), + F::I32(12288), + ], + )?; + self.finite_tail(&mut v, qfull, 12288, 0)?; + // Copy commands remain distinct byte transports (24 literal rows); their + // execution is interleaved in ForwardProgram immediately before Q norm. + let norm_entry = 0; + push( + &mut v, + 16, + norm_entry, + [24, 1, 1], + [256, 1, 1], + 0, + vec![ + F::U64(qcur), + F::U64(wa(1)?), + F::U64(qcur), + F::I32(256), + F::F32(1e-6), + ], + )?; + self.finite_tail(&mut v, qcur, 6144, 1)?; + let kv = &policy.kv; + if kv.disabled + || kv.hybrid + || kv.rotated + || kv.q4 + || kv.alternate_f16 + || kv.mode != 0 + || kv.rope_table_enabled + || kv.multimodal_positions + { + return Err(Error::UnsupportedQwenOperation); + } + push( + &mut v, + 16, + 1, + [4, 24, 1], + [32, 1, 1], + 0, + vec![ + F::U64(qcur), + F::U64(qcur), + F::I32(24), + F::I32(256), + F::I32(64), + F::F32(kv.theta_scale), + F::F32(kv.freq_scale), + F::F32(kv.corr_low), + F::F32(kv.corr_high), + F::F32(kv.ext_factor), + F::F32(kv.mscale), + F::U64(p.pos), + F::U64(0), + F::Words3([0; 3]), + ], + )?; + self.finite_tail(&mut v, qcur, 6144, 2)?; + // Original window_ids on actual private step, followed by same INT8 decode + // chunk and merge entries. Ring owns pools/table/ident/scratch throughout. + // window command uses ring's actual KV module in the captured program. + let (pa, pm, pl, ident) = o.attention(p.ring)?; + let chain_mtp = crate::original_verify::chain::flags().mtp; + // the Original's chunk kernel in both modes (the load-hoisted variant measured no faster); only the merge changes + let daily = daily_mtp(); + push( + &mut v, + if daily { symbols::DAILY_ASSET } else { 19 }, + if daily { symbols::DAILY_CHUNK } else { 0 }, + [CHUNKS as u32, 2, 1], + [256, 1, 1], + 0, + vec![ + F::U64(qcur), + F::U64(p.ring.address(0)?), + F::U64(p.ring.address(1)?), + F::U64(p.ring.address(2)?), + F::U64(p.ring.address(3)?), + F::U64(p.ring.address(4)?), + F::U64(ident), + F::U64(p.step), + F::I32(2), + F::I32(4), + F::F32(1.0 / 16.0), + F::U64(pa), + F::U64(pm), + F::U64(pl), + F::I32(CHUNKS as i32), + F::I32(32768), + F::I64(SCRATCH_FLOATS as i64), + ], + )?; + let mut merge_args = vec![ + F::U64(pa), + F::U64(pm), + F::U64(pl), + F::I32(CHUNKS as i32), + F::U64(attn), + F::I64(SCRATCH_FLOATS as i64), + ]; + if daily { + // merge_v2 takes the step words after n_chunks: (acc, m, l, n_chunks, steps, attn, stride) + merge_args = vec![ + F::U64(pa), + F::U64(pm), + F::U64(pl), + F::I32(CHUNKS as i32), + F::U64(p.step), + F::U64(attn), + F::I64(SCRATCH_FLOATS as i64), + ]; + } else if chain_mtp { + merge_args.push(F::U64(p.step)); // the row's step words: n_ids bounds the merge to the chunks that hold cells + } + push( + &mut v, + if daily { symbols::DAILY_ASSET } else if chain_mtp { symbols::CHAIN_ASSET } else { 19 }, + if daily { symbols::DAILY_MERGE_V2 } else if chain_mtp { symbols::CHAIN_QSA_MERGE_N } else { 1 }, + [24, 1, 1], + [256, 1, 1], + 0, + merge_args, + )?; + self.finite_tail(&mut v, attn, 6144, 3)?; + push( + &mut v, + 11, + 0, + [24, 1, 1], + [256, 1, 1], + 0, + vec![ + F::U64(attn), + F::U64(qfull), + F::U64(gated), + F::I32(24), + F::I32(256), + ], + )?; + self.finite_tail(&mut v, gated, 6144, 4)?; + self.quant(&mut v, gated, p.q, 6144)?; + self.q8_tail(&mut v, p.q, 6144, 5)?; + self.mmvq(&mut v, wa(2)?, p.q, bo, 6144, 2560)?; + self.finite_tail(&mut v, bo, 2560, 6)?; + self.mlp_gr(&mut v, p, bo, policy)?; + self.finite_tail(&mut v, p.r, 10240, 7)?; + self.finite_tail( + &mut v, + p.scalar.address(7, p.scalar.max_t * 40960)?, + 10240, + 8, + )?; + self.finite_tail(&mut v, p.scalar.address(8, p.scalar.max_t * 1280)?, 320, 9)?; + self.finite_tail(&mut v, a(20)?, 4, 10)?; + self.finite_tail(&mut v, p.mixed, 2560, 11)?; + let router = a(5)?; + self.mmvf(&mut v, p.mixed, wa(7)?, router, 2560, 512)?; + self.finite_tail(&mut v, router, 512, 12)?; + if policy.native_router { + push( + &mut v, + 3, + 0, + [1, 1, 1], + [32, 8, 1], + 0, + vec![F::U64(router), F::U64(a(7)?), F::U64(a(6)?)], + )?; + } else { + push( + &mut v, + 4, + policy.legacy_router_mode as usize, + [1, 1, 1], + [512, 1, 1], + (512 + 512 * 8 + 512 * 4) as u32, + vec![ + F::U64(router), + F::I32(1), + F::I32(512), + F::I32(10), + F::U64(a(7)?), + F::U64(a(6)?), + ], + )?; + } + self.finite_tail(&mut v, a(6)?, 10, 13)?; + let expert = w + .experts + .handle + .ok_or(Error::ContextPoisoned)? + .qwen_address(); + push( + &mut v, + 0, + 0, + [1, 1, 1], + [128, 1, 1], + 0, + vec![ + F::U64(a(7)?), + F::I32(10), + F::I32(10), + F::U64(expert), + F::I64(1382400), + F::U64(a(12)?), + F::U64(a(13)?), + F::U64(a(14)?), + F::U64(a(8)?), + F::U64(a(10)?), + ], + )?; + push( + &mut v, + 1, + 0, + [1, 1, 1], + [128, 1, 1], + 0, + vec![F::U64(p.mixed), F::U64(a(15)?), F::U64(a(16)?), F::I64(80)], + )?; + let s2 = a(17)?; + let hiddenq = s2 + 51200; + let hscale = hiddenq + 6816; + push( + &mut v, + 0, + if policy.old_grouped_s2 { 1 } else { 2 }, + [40, 10, 1], + [256, 1, 1], + 0, + vec![ + F::U64(a(12)?), + F::U64(a(13)?), + F::U64(a(14)?), + F::U64(a(10)?), + F::U64(a(15)?), + F::U64(a(16)?), + F::U64(s2), + F::I32(10), + ], + )?; + self.finite_tail(&mut v, s2, 12800, 14)?; + push( + &mut v, + 0, + 3, + [6400usize.div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![F::U64(s2), F::I64(6400)], + )?; + self.finite_tail(&mut v, s2, 6400, 15)?; + push( + &mut v, + 1, + 0, + [200usize.div_ceil(128) as u32, 1, 1], + [128, 1, 1], + 0, + vec![F::U64(s2), F::U64(hiddenq), F::U64(hscale), F::I64(200)], + )?; + push( + &mut v, + 0, + if policy.old_grouped_s2 { 4 } else { 5 }, + [40, 10, 1], + [256, 1, 1], + 0, + vec![ + F::U64(a(12)?), + F::U64(a(13)?), + F::U64(a(14)?), + F::U64(a(8)?), + F::U64(hiddenq), + F::U64(hscale), + F::U64(a(9)?), + ], + )?; + self.finite_tail(&mut v, a(9)?, 25600, 16)?; + // Shared projection consumes original mixed, not its unconditional BF16 image. + push( + &mut v, + 10, + 0, + [10, 1, 1], + [256, 1, 1], + 0, + vec![F::U64(p.mixed), F::U64(a(23)?), F::I64(2560)], + )?; + self.quant(&mut v, p.mixed, p.q, 2560)?; + self.q8_tail(&mut v, p.q, 2560, 17)?; + self.mmvq(&mut v, wa(8)?, p.q, a(18)?, 2560, 640)?; + self.mmvq(&mut v, wa(9)?, p.q, a(19)?, 2560, 640)?; + self.finite_tail(&mut v, a(18)?, 640, 18)?; + self.finite_tail(&mut v, a(19)?, 640, 19)?; + push( + &mut v, + 2, + 0, + [5, 1, 1], + [128, 1, 1], + 0, + vec![F::U64(a(18)?), F::U64(a(19)?), F::U64(a(18)?), F::I32(640)], + )?; + self.finite_tail(&mut v, a(18)?, 640, 20)?; + self.quant(&mut v, a(18)?, p.q, 640)?; + self.q8_tail(&mut v, p.q, 640, 21)?; + self.mmvq(&mut v, wa(10)?, p.q, a(11)?, 640, 2560)?; + self.finite_tail(&mut v, a(11)?, 2560, 22)?; + if policy.native_shared_scalar { + self.mmvf(&mut v, p.mixed, wa(11)?, a(22)?, 2560, 1)?; + push(&mut v, 2, 2, [1, 1, 1], [1, 1, 1], 0, vec![F::U64(a(22)?)])?; + } else { + push( + &mut v, + 2, + 1, + [1, 1, 1], + [256, 1, 1], + 0, + vec![ + F::U64(a(23)?), + F::U64(wa(11)?), + F::U64(a(22)?), + F::I32(2560), + ], + )?; + } + self.finite_tail(&mut v, a(22)?, 1, 23)?; + push( + &mut v, + 2, + 3, + [20, 1, 1], + [128, 1, 1], + 0, + vec![F::U64(a(11)?), F::U64(a(22)?), F::I32(2560)], + )?; + self.finite_tail(&mut v, a(11)?, 2560, 24)?; + let mut combine_args = vec![ + F::U64(a(9)?), + F::U64(a(6)?), + F::U64(a(11)?), + F::U64(o.combined()?), + ]; + if policy.native_combine { + combine_args.extend([F::I64(2560), F::I32(10)]); + } else { + combine_args.extend([F::I32(2560), F::I32(10), F::I32(1)]); + } + push( + &mut v, + if policy.native_combine { 5 } else { 2 }, + if policy.native_combine { 0 } else { 4 }, + [if policy.native_combine { 10 } else { 20 }, 1, 1], + [if policy.native_combine { 256 } else { 128 }, 1, 1], + 0, + combine_args, + )?; + self.finite_tail(&mut v, o.combined()?, 2560, 25)?; + if policy.native_final_gr { + push( + &mut v, + 8, + 2, + [40, 1, 1], + [256, 1, 1], + 0, + vec![ + F::U64(p.r), + F::U64(o.combined()?), + F::U64(a(20)?), + F::U64(p.r), + F::I32(2560), + F::I32(4), + F::F32(0.25), + ], + )?; + } else { + push( + &mut v, + 9, + 0, + [40, 1, 1], + [256, 1, 1], + 16, + vec![ + F::U64(p.r), + F::U64(o.combined()?), + F::U64(a(20)?), + F::I32(2560), + F::I32(4), + F::U64(p.r), + ], + )?; + } + self.finite_tail(&mut v, p.r, 10240, 26)?; + self.final_gr(&mut v, p, policy)?; + self.finite_tail(&mut v, a(24)?, 2560, 27)?; + self.quant(&mut v, a(24)?, p.q, 2560)?; + self.q8_tail(&mut v, p.q, 2560, 28)?; + let (name, grid, block, iq) = + head_dispatch::head_dispatch(w.head_kind, 2560, w.vocab, 1, w.dispatch)?; + let asset = if iq { 14 } else { 13 }; + let index = fixed_entry(asset, name)?; + let mut args = vec![F::U64( + w.head.handle.ok_or(Error::ContextPoisoned)?.qwen_address(), + )]; + if iq { + args.push(F::U64( + crate::native_head_row_bytes(w.head_kind, 2560)? as u64 + )); + } + args.extend([ + F::U64(p.q), + F::U64(o.logits()?), + F::I32(2560), + F::I32(w.vocab as i32), + ]); + if iq { + args.push(F::I32(1)); + } + push(&mut v, asset, index, grid, block, 0, args)?; + self.finite_tail(&mut v, o.logits()?, w.vocab, 29)?; + if let Some(j) = policy.coupled_j { + if !o.coupled || j >= 8 { + return Err(Error::InvalidQwenShape); + } + let blocks = w.vocab.div_ceil(4096); + let kpart = w.vocab.min(64); + let sub = w + .subset + .as_ref() + .map(|(f, _)| { + f.handle + .ok_or(Error::ContextPoisoned) + .map(|h| h.qwen_address()) + }) + .transpose()? + .unwrap_or(0); + let inv = w + .subset + .as_ref() + .map(|(_, i)| { + i.handle + .ok_or(Error::ContextPoisoned) + .map(|h| h.qwen_address()) + }) + .transpose()? + .unwrap_or(0); + push( + &mut v, + 20, + 2, + [1, 1, 1], + [1024, 1, 1], + (w.vocab.div_ceil(32) * 4) as u32, + vec![ + F::U64(o.logits()?), + F::I32(w.vocab as i32), + F::U64(inv), + F::I32(w.id_vocab as i32), + F::U64(a(28)?), + F::U64(a(29)?), + F::I32(4096), + F::I32(j as i32), + ], + )?; + push( + &mut v, + 20, + 0, + [blocks as u32, 1, 1], + [128, 1, 1], + 0, + vec![ + F::U64(o.logits()?), + F::I32(w.vocab as i32), + F::U64(0), + F::I32(0), + F::Params(SamplerParams::default()), + F::I32(kpart as i32), + F::I32(blocks as i32), + F::U64(a(30)?), + ], + )?; + push( + &mut v, + 20, + 3, + [1, 1, 1], + [32, 1, 1], + 0, + vec![ + F::U64(a(30)?), + F::I32(blocks as i32), + F::I32(w.vocab as i32), + F::I32(kpart as i32), + F::U64(a(28)?), + F::U64(p.step), + F::U64(sub), + F::U64(a(29)?), + F::I32(4096), + F::I32(j as i32), + F::U64(o.address(34)?), + F::U64(o.address(35)?), + ], + )?; + } else { + let mut greedy = SamplerParams::default(); + greedy.greedy = true; + greedy.temperature = 0.0; + let chain_head = crate::original_verify::chain::flags().head; + push( + &mut v, + if chain_head { symbols::CHAIN_ASSET } else { 15 }, + if chain_head { symbols::CHAIN_SAMPLER_GREEDY } else { 0 }, + [1, 1, 1], + [1024, 1, 1], + 0, + vec![ + F::U64(o.logits()?), + F::I32(w.vocab as i32), + F::U64(0), + F::I32(0), + F::Params(greedy), + F::I32(0), + F::I32(0), + F::U64(o.address(34)?), + ], + )?; + push( + &mut v, + if chain_head { symbols::CHAIN_ASSET } else { 12 }, + if chain_head { symbols::CHAIN_ROW_TOP_PROB } else { 0 }, + [1, 1, 1], + [1024, 1, 1], + 0, + vec![ + F::U64(o.logits()?), + F::I32(w.vocab as i32), + F::U64(o.address(34)?), + F::U64(o.address(35)?), + ], + )?; + if let Some((forward, _)) = &w.subset { + push( + &mut v, + 12, + 1, + [1, 1, 1], + [64, 1, 1], + 0, + vec![ + F::U64(o.address(34)?), + F::U64(forward.handle.ok_or(Error::ContextPoisoned)?.qwen_address()), + F::I32(1), + ], + )?; + } + } + Ok(v) + } +} diff --git a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2/impl_originalmtpfullforward_2_2.rs b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2/impl_originalmtpfullforward_2_2.rs new file mode 100644 index 00000000..c971b43d --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2/impl_originalmtpfullforward_2_2.rs @@ -0,0 +1,186 @@ +//! Moved out of the parent module by STRA-338: impl OriginalMtpFullForward (2). + +#[allow(unused_imports)] +use super::*; + + +impl OriginalMtpFullForward<'_> { + pub(in super::super) fn finite_tail(&self, v: &mut Vec, x: u64, n: usize, slot: usize) -> Result<()> { + if slot >= TAIL_FLAGS || n == 0 || n > i32::MAX as usize { + return Err(Error::InvalidSize); + } + push( + v, + 18, + 0, + [n.div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + F::U64(x), + F::I32(n as i32), + F::U64(self.inner.address(27)? + (slot * 4) as u64), + ], + ) + } + pub(in super::super) fn q8_tail(&self, v: &mut Vec, x: u64, n: usize, slot: usize) -> Result<()> { + if slot >= TAIL_FLAGS || n == 0 || n % 32 != 0 { + return Err(Error::InvalidSize); + } + push( + v, + 18, + 1, + [(n / 32).div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + F::U64(x), + F::I32((n / 32) as i32), + F::U64(self.inner.address(27)? + (slot * 4) as u64), + ], + ) + } + pub(in super::super) fn quant(&self, v: &mut Vec, x: u64, q: u64, n: usize) -> Result<()> { + push( + v, + 13, + fixed_entry(13, "head_quant")?, + [n.div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![F::U64(x), F::U64(q), F::I32(n as i32)], + ) + } + pub(in super::super) fn mmvq( + &self, + v: &mut Vec, + w: u64, + q: u64, + y: u64, + n: usize, + out: usize, + ) -> Result<()> { + let (name, grid, block, _) = + head_dispatch::head_dispatch(8, n, out, 1, NativeHeadDispatch::default())?; + push( + v, + 13, + fixed_entry(13, name)?, + grid, + block, + 0, + vec![ + F::U64(w), + F::U64(q), + F::U64(y), + F::I32(n as i32), + F::I32(out as i32), + ], + ) + } + pub(in super::super) fn mmvf( + &self, + v: &mut Vec, + x: u64, + w: u64, + y: u64, + n: usize, + out: usize, + ) -> Result<()> { + let b = mmvf_block(n); + push( + v, + 6, + (b / 32 - 1) as usize, + [out as u32, 1, 1], + [b, 1, 1], + 0, + vec![F::U64(x), F::U64(w), F::U64(y), F::I32(n as i32)], + ) + } + pub(in super::super) fn mlp_gr( + &self, + v: &mut Vec, + p: &ForwardPrefix<'_, '_>, + bo: u64, + policy: &OriginalMtpFullPolicy, + ) -> Result<()> { + let w = &self.inner.weights.roles; + let wa = |i: usize| { + w[i].handle + .ok_or(Error::ContextPoisoned) + .map(|h| h.qwen_address()) + }; + let s = p.scalar; + let xn = s.address(7, s.max_t * 40960)?; + let mut words = Box::new([0u64; 114]); + let a = &mut words[..14]; + a[0] = p.r; + a[1] = p.r; + a[2] = 1; + a[3] = bo; + a[4] = p.inj; + a[5] = wa(3)?; + a[6] = wa(4)?; + a[7] = wa(5)?; + a[8] = wa(6)?; + a[9] = u64::from(1e-6f32.to_bits()); + a[10] = s.address(8, s.max_t * 1280)?; + a[11] = s.address(9, s.max_t * 16)?; + a[12] = self.inner.address(20)?; + a[13] = p.mixed; + words[112] = xn; + words[113] = 1; + let args = words; + // Actual same GR module as prefix, stable by-value arguments. ForwardProgram + // carries this separate scalar-module command (no reloaded module/math). + + let make = || F::GrMulti(args.clone()); + push( + v, + 17, + if policy.gr == OriginalMtpGrVariant::Plain { + 0 + } else { + 1 + }, + [ + 1, + if policy.gr == OriginalMtpGrVariant::Plain { + 1 + } else { + 4 + }, + 1, + ], + [256, 1, 1], + 0, + vec![make()], + )?; + let bytes = if policy.gr == OriginalMtpGrVariant::Staged { + 10240 + } else { + s.plain_tile * 4 + }; + if s.shared_limit < bytes { + return Err(Error::InvalidProjectionShape); + } + push( + v, + 17, + if policy.gr == OriginalMtpGrVariant::Staged { + 2 + } else if s.plain_tile == 1280 { + 4 + } else { + 5 + }, + [41, 1, 1], + [256, 1, 1], + bytes as u32, + vec![make()], + )?; + push(v, 17, 3, [160, 1, 1], [256, 1, 1], 0, vec![make()]) + } +} diff --git a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2/impl_originalmtpfullforward_3.rs b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2/impl_originalmtpfullforward_3.rs new file mode 100644 index 00000000..05ac92da --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2/impl_originalmtpfullforward_3.rs @@ -0,0 +1,128 @@ +//! Moved out of the parent module by STRA-338: impl OriginalMtpFullForward (3). + +#[allow(unused_imports)] +use super::*; + + +impl OriginalMtpFullForward<'_> { + pub(in super::super) fn final_gr( + &self, + v: &mut Vec, + p: &ForwardPrefix<'_, '_>, + policy: &OriginalMtpFullPolicy, + ) -> Result<()> { + let a = |i| self.inner.address(i); + let w = &self.inner.weights.roles; + let wa = |i: usize| { + w[i].handle + .ok_or(Error::ContextPoisoned) + .map(|h| h.qwen_address()) + }; + let xn = p.scalar.address(7, p.scalar.max_t * 40960)?; + let lo = p.scalar.address(8, p.scalar.max_t * 1280)?; + if policy.native_final_gr { + push( + v, + 7, + 0, + [4, 1, 1], + [1024, 1, 1], + 0, + vec![ + F::U64(p.r), + F::U64(wa(12)?), + F::U64(xn), + F::I32(2560), + F::F32(1e-6), + ], + )?; + self.mmvf(v, xn, wa(13)?, lo, 10240, 320)?; + push( + v, + 8, + 0, + [2, 1, 1], + [256, 1, 1], + 0, + vec![F::U64(lo), F::I32(320), F::F32(0.25)], + )?; + self.mmvf(v, lo, wa(14)?, a(25)?, 320, 10240)?; + push( + v, + 8, + 1, + [10, 1, 1], + [256, 1, 1], + 0, + vec![ + F::U64(xn), + F::U64(a(25)?), + F::U64(a(24)?), + F::I32(2560), + F::I32(4), + F::F32(0.25), + ], + )?; + } else { + let fp = policy.fp32_final_gr; + push( + v, + 9, + if fp { 1 } else { 2 }, + [4, 1, 1], + [256, 1, 1], + 0, + vec![ + F::U64(p.r), + F::U64(wa(12)?), + F::F32(1e-6), + F::I32(2560), + F::U64(xn), + F::U64(a(25)?), + ], + )?; + push( + v, + 9, + if fp { 3 } else { 4 }, + [320, 1, 1], + [256, 1, 1], + 0, + vec![ + F::U64(if fp { xn } else { a(25)? }), + F::U64(wa(13)?), + F::I32(10240), + F::I32(320), + F::I32(4), + F::U64(if fp { lo } else { a(26)? }), + ], + )?; + push( + v, + 9, + if fp { 5 } else { 6 }, + [1280, 1, 1], + [256, 1, 1], + 0, + vec![ + F::U64(if fp { lo } else { a(26)? }), + F::U64(wa(14)?), + F::U64(xn), + F::I32(10240), + F::I32(320), + F::U64(a(25)?), + ], + )?; + push( + v, + 9, + 7, + [10, 1, 1], + [256, 1, 1], + 0, + vec![F::U64(a(25)?), F::I32(2560), F::I32(4), F::U64(a(24)?)], + )?; + } + Ok(()) + } +} diff --git a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_3.rs b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_3.rs index ff656816..61b646a8 100644 --- a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_3.rs +++ b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_3.rs @@ -3,543 +3,7 @@ #[allow(unused_imports)] use super::*; -impl<'ctx> OriginalMtpFullForward<'ctx> { - /// Builds the literal full=true T1 prefix with genuine retained model roles. - /// The resulting graph resource owns all scratch, records, weights and ring; - /// this method neither launches nor declares any input/output complete. - pub(super) fn prefix_commands( - &self, - scalar: &OriginalMtpScalarPrefill<'ctx>, - ring: &MtpOriginalInt8<'ctx>, - policy: &OriginalMtpFullPolicy, - t: usize, - step_row: usize, - ) -> Result<(Vec, Option>)> { - self.validate_context(scalar.context)?; - validate_scalar_prefix(scalar)?; - ring.validate_context(scalar.context)?; - policy.validate_selected()?; - if scalar.has_pending { - return Err(Error::InvalidQwenShape); - } - if self.inner.original_layout.is_some() && !self.inner.shares_original(scalar) { - return Err(Error::InvalidQwenShape); - } - let retained = Rc::clone(&self.inner.weights.prefix); - retained.validate_context(scalar.context)?; - let weights = &retained.roles; - let embedding = match &retained.embedding { - PrefixEmbedding::Device { bank } => Some(bank.loans(scalar.context)?.1), - PrefixEmbedding::Native(_) => None, - }; - let wr = weights.each_ref().map(|b| Rc::as_ref(b)); - let extents = [ - 10240, - 2560 * 80 * 34, - 40960, - 2560 * 80 * 34, - 40960, - 320 * 10240 * 2, - 10240 * 320 * 2, - 512 * 80 * 34, - 512 * 80 * 34, - 1024, - 4 * 10240 * 2, - ]; - ring.validate_original_main(scalar.scratch.as_ref().ok_or(Error::ContextPoisoned)?)?; - let eh = scalar - .scratch - .as_ref() - .ok_or(Error::ContextPoisoned)? - .handle - .ok_or(Error::ContextPoisoned)?; - let mut wh = [eh; 11]; - for i in 0..11 { - checked(scalar.context, wr[i], extents[i])?; - wh[i] = wr[i].handle.ok_or(Error::ContextPoisoned)?; - } - for b in wr.into_iter().chain(embedding.as_ref().map(|e| e.table)) { - ring.reject_state_alias(b)?; - let h = b.handle.ok_or(Error::ContextPoisoned)?; - for output in [&scalar.scratch, &scalar.status, &scalar.records] - .into_iter() - .flatten() - { - if h.overlaps( - b.bytes, - output.handle.ok_or(Error::ContextPoisoned)?, - output.bytes, - ) { - return Err(Error::OutputAliasesInput); - } - } - for output in ring.buffers()?.iter().flatten() { - if h.overlaps( - b.bytes, - output.handle.ok_or(Error::ContextPoisoned)?, - output.bytes, - ) { - return Err(Error::OutputAliasesInput); - } - } - } - if t == 0 - || t > self.inner.max_t - || t > scalar.max_t - || t > ring.max_t - // Window ring (mtp.cpp: ring = window + 4 * max_t + 64 cells, 4 per - // slot) or the Original fully-resident retry (one slot per page). - || (ring.slots != (MTP_ORIGINAL_WINDOW + 4 * ring.max_t + 64).div_ceil(4) - && ring.slots != MTP_ORIGINAL_MAX_CELLS / 4) - || step_row - .checked_add(t) - .is_none_or(|n| n > 2 * self.inner.max_t) - { - return Err(Error::InvalidQwenShape); - } - let kv = &policy.kv; - let group = 0usize; - let prefix_policy = OriginalMtpScalarPolicy { - gr: policy.gr, - per_group_sync: false, - kv: DraftKvPolicy { - disabled: kv.disabled, - hybrid: kv.hybrid, - rotated: kv.rotated, - q4: kv.q4, - alternate_f16: kv.alternate_f16, - mode: kv.mode, - rope_table_enabled: kv.rope_table_enabled, - multimodal_positions: kv.multimodal_positions, - theta_scale: kv.theta_scale, - freq_scale: kv.freq_scale, - corr_low: kv.corr_low, - corr_high: kv.corr_high, - ext_factor: kv.ext_factor, - mscale: kv.mscale, - }, - }; - let rin = scalar.address(0, t * 40960)?; - let emb = scalar.address(2, t * 10240)?; - let en = scalar.address(3, t * 10240)?; - let e2 = scalar.address(4, t * 10240)?; - let hn = scalar.address(5, t * 40960)?; - let h2 = scalar.address(6, t * 40960)?; - let r = scalar.address(1, t * 40960)?; - let mixed = scalar.address(11, t * 10240)?; - let tok = scalar.address(12, t * 4)?; - let step = self.inner.address(31)? + (step_row * 16) as u64; - let pos = self.inner.address(32)? + (step_row * 96) as u64; - let policy = &prefix_policy; - let mut cmds = Vec::new(); - cmds.try_reserve_exact(128) - .map_err(|_| Error::HostAllocation)?; - OriginalMtpScalarPrefill::kernel( - &mut cmds, - 0, - 11, - [1, 1, 1], - [256, 1, 1], - 0, - vec![Arg::U64(scalar.flag(0, 0)?), Arg::I32(16)], - )?; - let mut native_embedding = None; - if let PrefixEmbedding::Native(e) = &retained.embedding { - let scratch = scalar.scratch.as_ref().ok_or(Error::ContextPoisoned)?; - let h = scratch.handle.ok_or(Error::ContextPoisoned)?; - native_embedding = Some(e.gather_plan( - scalar.context, - h.checked_subspan(scratch.bytes, scalar.layout.offsets[12], t * 4)?, - h.checked_subspan(scratch.bytes, scalar.layout.offsets[2], t * 10240)?, - t, - )?); - } - if let Some(embedding) = embedding { - let eh = embedding.table.handle.ok_or(Error::ContextPoisoned)?; - match embedding.kind { - EmbeddingKind::Native { - kind, row_bytes, .. - } => OriginalMtpScalarPrefill::kernel( - &mut cmds, - 1, - 0, - [10, t as u32, 1], - [32, 1, 1], - 0, - vec![ - Arg::I32(kind), - Arg::U64(eh.qwen_address()), - Arg::U64(row_bytes as u64), - Arg::U64(tok), - Arg::I64(2560), - Arg::U64(emb), - ], - )?, - EmbeddingKind::Compressed { - bits, - bias, - group, - codes, - scales, - offsets, - .. - } => OriginalMtpScalarPrefill::kernel( - &mut cmds, - 0, - 5, - [10, t as u32, 1], - [256, 1, 1], - 0, - vec![ - Arg::U64(eh.qwen_address()), - Arg::U64(eh.qwen_address() + codes as u64), - Arg::U64(if offsets { - eh.qwen_address() + (codes + scales) as u64 - } else { - 0 - }), - Arg::U64(tok), - Arg::I64(2560), - Arg::I32(bits), - Arg::I32(bias), - Arg::I32(group as i32), - Arg::U64((2560 / (8 / bits)) as u64), - Arg::U64((2560 / group) as u64), - Arg::U64(emb), - ], - )?, - } - } - scalar.finite(&mut cmds, emb, t * 2560, group, 0)?; - OriginalMtpScalarPrefill::kernel( - &mut cmds, - 3, - 0, - [t as u32, 1, 1], - [1024, 1, 1], - 0, - vec![ - Arg::U64(emb), - Arg::U64(wh[0].qwen_address()), - Arg::U64(en), - Arg::I32(2560), - Arg::F32(1e-6), - ], - )?; - scalar.finite(&mut cmds, en, t * 2560, group, 1)?; - let q = scalar.address(15, 8 * 80 * 36)?; - OriginalMtpScalarPrefill::quant(&mut cmds, en, q, t)?; - scalar.q8_guard(&mut cmds, q, t, group, 2)?; - OriginalMtpScalarPrefill::project(&mut cmds, wh[1].qwen_address(), q, e2, t, 2560)?; - scalar.finite(&mut cmds, e2, t * 2560, group, 2)?; - OriginalMtpScalarPrefill::kernel( - &mut cmds, - 3, - 0, - [t as u32, 1, 1], - [1024, 1, 1], - 0, - vec![ - Arg::U64(rin), - Arg::U64(wh[2].qwen_address()), - Arg::U64(hn), - Arg::I32(10240), - Arg::F32(1e-6), - ], - )?; - scalar.finite(&mut cmds, hn, t * 10240, group, 3)?; - for hc in (0..t * 4).step_by(8) { - let cols = 8.min(t * 4 - hc); - OriginalMtpScalarPrefill::quant(&mut cmds, hn + (hc * 10240) as u64, q, cols)?; - scalar.q8_guard(&mut cmds, q, cols, group, 4)?; - OriginalMtpScalarPrefill::project( - &mut cmds, - wh[3].qwen_address(), - q, - h2 + (hc * 10240) as u64, - cols, - 2560, - )?; - } - scalar.finite(&mut cmds, h2, t * 10240, group, 4)?; - OriginalMtpScalarPrefill::kernel( - &mut cmds, - 0, - 4, - [40, t as u32, 1], - [256, 1, 1], - 0, - vec![ - Arg::U64(h2), - Arg::U64(e2), - Arg::U64(r), - Arg::I64(2560), - Arg::I32(4), - ], - )?; - scalar.finite(&mut cmds, r, t * 10240, group, 5)?; - scalar.gr(&mut cmds, t, &wh, policy)?; - scalar.finite(&mut cmds, scalar.address(9, t * 16)?, t * 4, group, 6)?; - scalar.finite( - &mut cmds, - scalar.address(7, t * 40960)?, - t * 10240, - group, - 6, - )?; - scalar.finite(&mut cmds, scalar.address(8, t * 1280)?, t * 320, group, 7)?; - scalar.finite(&mut cmds, scalar.address(10, t * 16)?, t * 4, group, 7)?; - scalar.finite(&mut cmds, mixed, t * 2560, group, 8)?; - OriginalMtpScalarPrefill::quant(&mut cmds, mixed, q, t)?; - scalar.q8_guard(&mut cmds, q, t, group, 9)?; - let (kc, vc) = scalar.current_kv(ring)?; - OriginalMtpScalarPrefill::project(&mut cmds, wh[7].qwen_address(), q, kc, t, 512)?; - scalar.finite(&mut cmds, kc, t * 512, group, 10)?; - OriginalMtpScalarPrefill::project(&mut cmds, wh[8].qwen_address(), q, vc, t, 512)?; - scalar.finite(&mut cmds, vc, t * 512, group, 11)?; - for row in 0..t { - let k = kc + (row * 2048) as u64; - OriginalMtpScalarPrefill::kernel( - &mut cmds, - 2, - 9, - [2, 1, 1], - [256, 1, 1], - 0, - vec![ - Arg::U64(k), - Arg::U64(wh[9].qwen_address()), - Arg::U64(k), - Arg::I32(256), - Arg::F32(1e-6), - ], - )?; - scalar.finite(&mut cmds, k, 512, group, 12)?; - OriginalMtpScalarPrefill::kernel( - &mut cmds, - 3, - 1, - [4, 2, 1], - [32, 1, 1], - 0, - vec![ - Arg::U64(k), - Arg::U64(k), - Arg::I32(2), - Arg::I32(256), - Arg::I32(64), - Arg::F32(kv.theta_scale), - Arg::F32(kv.freq_scale), - Arg::F32(kv.corr_low), - Arg::F32(kv.corr_high), - Arg::F32(kv.ext_factor), - Arg::F32(kv.mscale), - Arg::U64(pos + (row * 96) as u64), - Arg::U64(0), - Arg::Words3([0; 3]), - ], - )?; - scalar.finite(&mut cmds, k, 512, group, 13)?; - let mut host = [0u64; 8]; - host[2..6].copy_from_slice(&ring.host_addresses()?); - // Literal step append kernel and actual private step record, not batched prompt arithmetic. - OriginalMtpScalarPrefill::kernel( - &mut cmds, - 5, - 0, - [2, 4, 2], - [64, 1, 1], - 0, - vec![ - Arg::U64(ring.address(0)?), - Arg::U64(ring.address(1)?), - Arg::U64(ring.address(2)?), - Arg::U64(ring.address(3)?), - Arg::U64(ring.address(4)?), - Arg::U64(step + (row * 16) as u64), - Arg::U64(k), - Arg::U64(vc + (row * 2048) as u64), - Arg::I32(2), - Arg::I32(256), - Arg::I32(4), - Arg::U64(host[2]), - Arg::U64(host[3]), - Arg::U64(host[4]), - Arg::U64(host[5]), - ], - )?; - } - OriginalMtpScalarPrefill::kernel( - &mut cmds, - 3, - 3, - [64, 1, 1], - [256, 1, 1], - 0, - vec![ - Arg::U64(ring.address(2)?), - Arg::U64(ring.address(3)?), - Arg::U64(ring.address(4)?), - Arg::U64(step), - Arg::I32(t as i32), - Arg::U64(scalar.flag(0, 14)?), - ], - )?; - Ok((cmds, native_embedding)) - } - - // Called ONLY at scalar capture preparation, immediately after the genuine - // prefix plan builder has emitted its real current step append commands. - pub(in super::super) fn program( - &self, - scalar: &OriginalMtpScalarPrefill<'ctx>, - ring: &MtpOriginalInt8<'ctx>, - prefix: Vec, - policy: &OriginalMtpFullPolicy, - native_embedding: Option>, - step_row: usize, - ) -> Result> { - validate_scalar_prefix(scalar)?; - ring.validate_context(self.inner.context)?; - self.validate_context(scalar.context)?; - let scratch = self.inner.scratch.as_ref().ok_or(Error::ContextPoisoned)?; - ring.reject_state_alias(scratch)?; - let sh = scratch.handle.ok_or(Error::ContextPoisoned)?; - for b in self - .inner - .weights - .prefix - .roles - .iter() - .chain(self.inner.weights.roles.iter()) - .chain([&self.inner.weights.experts, &self.inner.weights.head]) - .chain([ - scalar.scratch.as_ref().ok_or(Error::ContextPoisoned)?, - scalar.status.as_ref().ok_or(Error::ContextPoisoned)?, - scalar.records.as_ref().ok_or(Error::ContextPoisoned)?, - ]) - { - if sh.overlaps( - scratch.bytes, - b.handle.ok_or(Error::ContextPoisoned)?, - b.bytes, - ) { - let genuine_shared = self.inner.shares_original(scalar) - && Rc::ptr_eq(b, scalar.scratch.as_ref().ok_or(Error::ContextPoisoned)?); - if !genuine_shared { - return Err(Error::OutputAliasesInput); - } - } - } - if self.inner.original_layout.is_some() && !self.inner.shares_original(scalar) { - return Err(Error::InvalidQwenShape); - } - for extra in self.inner.extras.iter().flatten() { - ring.reject_state_alias(extra)?; - let h = extra.handle.ok_or(Error::ContextPoisoned)?; - for b in self - .inner - .weights - .prefix - .roles - .iter() - .chain(self.inner.weights.roles.iter()) - .chain([&self.inner.weights.experts, &self.inner.weights.head]) - .chain([ - scalar.scratch.as_ref().ok_or(Error::ContextPoisoned)?, - scalar.status.as_ref().ok_or(Error::ContextPoisoned)?, - scalar.records.as_ref().ok_or(Error::ContextPoisoned)?, - ]) - { - ring.reject_state_alias(b)?; - if h.overlaps( - extra.bytes, - b.handle.ok_or(Error::ContextPoisoned)?, - b.bytes, - ) { - return Err(Error::OutputAliasesInput); - } - } - for b in ring.buffers()?.iter().flatten() { - if h.overlaps( - extra.bytes, - b.handle.ok_or(Error::ContextPoisoned)?, - b.bytes, - ) { - return Err(Error::OutputAliasesInput); - } - } - } - for b in ring.buffers()?.iter().flatten() { - if sh.overlaps( - scratch.bytes, - b.handle.ok_or(Error::ContextPoisoned)?, - b.bytes, - ) { - return Err(Error::OutputAliasesInput); - } - } - let p = ForwardPrefix { - scalar, - ring, - step: self.inner.address(31)? + (step_row * 16) as u64, - pos: self.inner.address(32)? + (step_row * 96) as u64, - q: scalar.address(15, 8 * 80 * 36)?, - r: scalar.address(1, 40960)?, - mixed: scalar.address(11, 10240)?, - inj: scalar.address(10, 16)?, - }; - let commands = self.plan(&p, policy)?; - let mut modules = Vec::new(); - modules - .try_reserve_exact(6) - .map_err(|_| Error::HostAllocation)?; - for m in &scalar.modules { - modules.push(Rc::clone(m.as_ref().ok_or(Error::ContextPoisoned)?)); - } - let window = abi::Arguments::new(vec![ - abi::Arg::U64(p.step), - abi::Arg::I32(32768), - abi::Arg::U64(self.inner.attention(ring)?.3), - abi::Arg::I64(32768), - ])?; - let coupled_stage = if policy.coupled_j == Some(0) { - let base = self.inner.max_t * 236 + 384; - Some(FA::new(vec![ - F::U64(self.inner.mapped_address(base, 64)?), - F::U64(self.inner.mapped_address(base + 64, 4096 * 4)?), - F::U64(self.inner.address(28)?), - F::U64(self.inner.address(29)?), - F::I32(4096), - ])?) - } else { - None - }; - Ok(OriginalMtpForwardProgram { - context: scalar.context, - prefix_modules: modules.try_into().map_err(|_| Error::InvalidSize)?, - prefix_scratch: Rc::clone(scalar.scratch.as_ref().ok_or(Error::ContextPoisoned)?), - prefix_status: Rc::clone(scalar.status.as_ref().ok_or(Error::ContextPoisoned)?), - prefix_records: Rc::clone(scalar.records.as_ref().ok_or(Error::ContextPoisoned)?), - prefix_mapped: Rc::clone(&scalar.mapped), - ring: ring.retain_physical_resources()?, - tail: Rc::clone(&self.inner), - prefix, - tail_commands: commands, - split: Box::new(full_abi::Copy2D::q_split( - self.inner.address(0)?, - self.inner.address(1)?, - )), - window, - tail_reset: Arguments::new(vec![ - Arg::U64(self.inner.address(27)?), - Arg::I32(TAIL_FLAGS as i32), - ])?, - native_embedding, - coupled_stage, - residual_offset: scalar.layout.offsets[1], - input_address: scalar.address(0, 40960)?, - token_address: scalar.address(12, 4)?, - }) - } -} +#[path = "impl_originalmtpfullforward_3/impl_originalmtpfullforward.rs"] +mod impl_originalmtpfullforward; +#[path = "impl_originalmtpfullforward_3/impl_originalmtpfullforward_2.rs"] +mod impl_originalmtpfullforward_2; diff --git a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_3/impl_originalmtpfullforward.rs b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_3/impl_originalmtpfullforward.rs new file mode 100644 index 00000000..5c163b1e --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_3/impl_originalmtpfullforward.rs @@ -0,0 +1,391 @@ +//! Moved out of the parent module by STRA-338: impl OriginalMtpFullForward. + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalMtpFullForward<'ctx> { + /// Builds the literal full=true T1 prefix with genuine retained model roles. + /// The resulting graph resource owns all scratch, records, weights and ring; + /// this method neither launches nor declares any input/output complete. + pub(in super::super) fn prefix_commands( + &self, + scalar: &OriginalMtpScalarPrefill<'ctx>, + ring: &MtpOriginalInt8<'ctx>, + policy: &OriginalMtpFullPolicy, + t: usize, + step_row: usize, + ) -> Result<(Vec, Option>)> { + self.validate_context(scalar.context)?; + validate_scalar_prefix(scalar)?; + ring.validate_context(scalar.context)?; + policy.validate_selected()?; + if scalar.has_pending { + return Err(Error::InvalidQwenShape); + } + if self.inner.original_layout.is_some() && !self.inner.shares_original(scalar) { + return Err(Error::InvalidQwenShape); + } + let retained = Rc::clone(&self.inner.weights.prefix); + retained.validate_context(scalar.context)?; + let weights = &retained.roles; + let embedding = match &retained.embedding { + PrefixEmbedding::Device { bank } => Some(bank.loans(scalar.context)?.1), + PrefixEmbedding::Native(_) => None, + }; + let wr = weights.each_ref().map(|b| Rc::as_ref(b)); + let extents = [ + 10240, + 2560 * 80 * 34, + 40960, + 2560 * 80 * 34, + 40960, + 320 * 10240 * 2, + 10240 * 320 * 2, + 512 * 80 * 34, + 512 * 80 * 34, + 1024, + 4 * 10240 * 2, + ]; + ring.validate_original_main(scalar.scratch.as_ref().ok_or(Error::ContextPoisoned)?)?; + let eh = scalar + .scratch + .as_ref() + .ok_or(Error::ContextPoisoned)? + .handle + .ok_or(Error::ContextPoisoned)?; + let mut wh = [eh; 11]; + for i in 0..11 { + checked(scalar.context, wr[i], extents[i])?; + wh[i] = wr[i].handle.ok_or(Error::ContextPoisoned)?; + } + for b in wr.into_iter().chain(embedding.as_ref().map(|e| e.table)) { + ring.reject_state_alias(b)?; + let h = b.handle.ok_or(Error::ContextPoisoned)?; + for output in [&scalar.scratch, &scalar.status, &scalar.records] + .into_iter() + .flatten() + { + if h.overlaps( + b.bytes, + output.handle.ok_or(Error::ContextPoisoned)?, + output.bytes, + ) { + return Err(Error::OutputAliasesInput); + } + } + for output in ring.buffers()?.iter().flatten() { + if h.overlaps( + b.bytes, + output.handle.ok_or(Error::ContextPoisoned)?, + output.bytes, + ) { + return Err(Error::OutputAliasesInput); + } + } + } + if t == 0 + || t > self.inner.max_t + || t > scalar.max_t + || t > ring.max_t + // Window ring (mtp.cpp: ring = window + 4 * max_t + 64 cells, 4 per + // slot) or the Original fully-resident retry (one slot per page). + || (ring.slots != (MTP_ORIGINAL_WINDOW + 4 * ring.max_t + 64).div_ceil(4) + && ring.slots != MTP_ORIGINAL_MAX_CELLS / 4) + || step_row + .checked_add(t) + .is_none_or(|n| n > 2 * self.inner.max_t) + { + return Err(Error::InvalidQwenShape); + } + let kv = &policy.kv; + let group = 0usize; + let prefix_policy = OriginalMtpScalarPolicy { + gr: policy.gr, + per_group_sync: false, + kv: DraftKvPolicy { + disabled: kv.disabled, + hybrid: kv.hybrid, + rotated: kv.rotated, + q4: kv.q4, + alternate_f16: kv.alternate_f16, + mode: kv.mode, + rope_table_enabled: kv.rope_table_enabled, + multimodal_positions: kv.multimodal_positions, + theta_scale: kv.theta_scale, + freq_scale: kv.freq_scale, + corr_low: kv.corr_low, + corr_high: kv.corr_high, + ext_factor: kv.ext_factor, + mscale: kv.mscale, + }, + }; + let rin = scalar.address(0, t * 40960)?; + let emb = scalar.address(2, t * 10240)?; + let en = scalar.address(3, t * 10240)?; + let e2 = scalar.address(4, t * 10240)?; + let hn = scalar.address(5, t * 40960)?; + let h2 = scalar.address(6, t * 40960)?; + let r = scalar.address(1, t * 40960)?; + let mixed = scalar.address(11, t * 10240)?; + let tok = scalar.address(12, t * 4)?; + let step = self.inner.address(31)? + (step_row * 16) as u64; + let pos = self.inner.address(32)? + (step_row * 96) as u64; + let policy = &prefix_policy; + let mut cmds = Vec::new(); + cmds.try_reserve_exact(128) + .map_err(|_| Error::HostAllocation)?; + OriginalMtpScalarPrefill::kernel( + &mut cmds, + 0, + 11, + [1, 1, 1], + [256, 1, 1], + 0, + vec![Arg::U64(scalar.flag(0, 0)?), Arg::I32(16)], + )?; + let mut native_embedding = None; + if let PrefixEmbedding::Native(e) = &retained.embedding { + let scratch = scalar.scratch.as_ref().ok_or(Error::ContextPoisoned)?; + let h = scratch.handle.ok_or(Error::ContextPoisoned)?; + native_embedding = Some(e.gather_plan( + scalar.context, + h.checked_subspan(scratch.bytes, scalar.layout.offsets[12], t * 4)?, + h.checked_subspan(scratch.bytes, scalar.layout.offsets[2], t * 10240)?, + t, + )?); + } + if let Some(embedding) = embedding { + let eh = embedding.table.handle.ok_or(Error::ContextPoisoned)?; + match embedding.kind { + EmbeddingKind::Native { + kind, row_bytes, .. + } => OriginalMtpScalarPrefill::kernel( + &mut cmds, + 1, + 0, + [10, t as u32, 1], + [32, 1, 1], + 0, + vec![ + Arg::I32(kind), + Arg::U64(eh.qwen_address()), + Arg::U64(row_bytes as u64), + Arg::U64(tok), + Arg::I64(2560), + Arg::U64(emb), + ], + )?, + EmbeddingKind::Compressed { + bits, + bias, + group, + codes, + scales, + offsets, + .. + } => OriginalMtpScalarPrefill::kernel( + &mut cmds, + 0, + 5, + [10, t as u32, 1], + [256, 1, 1], + 0, + vec![ + Arg::U64(eh.qwen_address()), + Arg::U64(eh.qwen_address() + codes as u64), + Arg::U64(if offsets { + eh.qwen_address() + (codes + scales) as u64 + } else { + 0 + }), + Arg::U64(tok), + Arg::I64(2560), + Arg::I32(bits), + Arg::I32(bias), + Arg::I32(group as i32), + Arg::U64((2560 / (8 / bits)) as u64), + Arg::U64((2560 / group) as u64), + Arg::U64(emb), + ], + )?, + } + } + scalar.finite(&mut cmds, emb, t * 2560, group, 0)?; + OriginalMtpScalarPrefill::kernel( + &mut cmds, + 3, + 0, + [t as u32, 1, 1], + [1024, 1, 1], + 0, + vec![ + Arg::U64(emb), + Arg::U64(wh[0].qwen_address()), + Arg::U64(en), + Arg::I32(2560), + Arg::F32(1e-6), + ], + )?; + scalar.finite(&mut cmds, en, t * 2560, group, 1)?; + let q = scalar.address(15, 8 * 80 * 36)?; + OriginalMtpScalarPrefill::quant(&mut cmds, en, q, t)?; + scalar.q8_guard(&mut cmds, q, t, group, 2)?; + OriginalMtpScalarPrefill::project(&mut cmds, wh[1].qwen_address(), q, e2, t, 2560)?; + scalar.finite(&mut cmds, e2, t * 2560, group, 2)?; + OriginalMtpScalarPrefill::kernel( + &mut cmds, + 3, + 0, + [t as u32, 1, 1], + [1024, 1, 1], + 0, + vec![ + Arg::U64(rin), + Arg::U64(wh[2].qwen_address()), + Arg::U64(hn), + Arg::I32(10240), + Arg::F32(1e-6), + ], + )?; + scalar.finite(&mut cmds, hn, t * 10240, group, 3)?; + for hc in (0..t * 4).step_by(8) { + let cols = 8.min(t * 4 - hc); + OriginalMtpScalarPrefill::quant(&mut cmds, hn + (hc * 10240) as u64, q, cols)?; + scalar.q8_guard(&mut cmds, q, cols, group, 4)?; + OriginalMtpScalarPrefill::project( + &mut cmds, + wh[3].qwen_address(), + q, + h2 + (hc * 10240) as u64, + cols, + 2560, + )?; + } + scalar.finite(&mut cmds, h2, t * 10240, group, 4)?; + OriginalMtpScalarPrefill::kernel( + &mut cmds, + 0, + 4, + [40, t as u32, 1], + [256, 1, 1], + 0, + vec![ + Arg::U64(h2), + Arg::U64(e2), + Arg::U64(r), + Arg::I64(2560), + Arg::I32(4), + ], + )?; + scalar.finite(&mut cmds, r, t * 10240, group, 5)?; + scalar.gr(&mut cmds, t, &wh, policy)?; + scalar.finite(&mut cmds, scalar.address(9, t * 16)?, t * 4, group, 6)?; + scalar.finite( + &mut cmds, + scalar.address(7, t * 40960)?, + t * 10240, + group, + 6, + )?; + scalar.finite(&mut cmds, scalar.address(8, t * 1280)?, t * 320, group, 7)?; + scalar.finite(&mut cmds, scalar.address(10, t * 16)?, t * 4, group, 7)?; + scalar.finite(&mut cmds, mixed, t * 2560, group, 8)?; + OriginalMtpScalarPrefill::quant(&mut cmds, mixed, q, t)?; + scalar.q8_guard(&mut cmds, q, t, group, 9)?; + let (kc, vc) = scalar.current_kv(ring)?; + OriginalMtpScalarPrefill::project(&mut cmds, wh[7].qwen_address(), q, kc, t, 512)?; + scalar.finite(&mut cmds, kc, t * 512, group, 10)?; + OriginalMtpScalarPrefill::project(&mut cmds, wh[8].qwen_address(), q, vc, t, 512)?; + scalar.finite(&mut cmds, vc, t * 512, group, 11)?; + for row in 0..t { + let k = kc + (row * 2048) as u64; + OriginalMtpScalarPrefill::kernel( + &mut cmds, + 2, + 9, + [2, 1, 1], + [256, 1, 1], + 0, + vec![ + Arg::U64(k), + Arg::U64(wh[9].qwen_address()), + Arg::U64(k), + Arg::I32(256), + Arg::F32(1e-6), + ], + )?; + scalar.finite(&mut cmds, k, 512, group, 12)?; + OriginalMtpScalarPrefill::kernel( + &mut cmds, + 3, + 1, + [4, 2, 1], + [32, 1, 1], + 0, + vec![ + Arg::U64(k), + Arg::U64(k), + Arg::I32(2), + Arg::I32(256), + Arg::I32(64), + Arg::F32(kv.theta_scale), + Arg::F32(kv.freq_scale), + Arg::F32(kv.corr_low), + Arg::F32(kv.corr_high), + Arg::F32(kv.ext_factor), + Arg::F32(kv.mscale), + Arg::U64(pos + (row * 96) as u64), + Arg::U64(0), + Arg::Words3([0; 3]), + ], + )?; + scalar.finite(&mut cmds, k, 512, group, 13)?; + let mut host = [0u64; 8]; + host[2..6].copy_from_slice(&ring.host_addresses()?); + // Literal step append kernel and actual private step record, not batched prompt arithmetic. + OriginalMtpScalarPrefill::kernel( + &mut cmds, + 5, + 0, + [2, 4, 2], + [64, 1, 1], + 0, + vec![ + Arg::U64(ring.address(0)?), + Arg::U64(ring.address(1)?), + Arg::U64(ring.address(2)?), + Arg::U64(ring.address(3)?), + Arg::U64(ring.address(4)?), + Arg::U64(step + (row * 16) as u64), + Arg::U64(k), + Arg::U64(vc + (row * 2048) as u64), + Arg::I32(2), + Arg::I32(256), + Arg::I32(4), + Arg::U64(host[2]), + Arg::U64(host[3]), + Arg::U64(host[4]), + Arg::U64(host[5]), + ], + )?; + } + OriginalMtpScalarPrefill::kernel( + &mut cmds, + 3, + 3, + [64, 1, 1], + [256, 1, 1], + 0, + vec![ + Arg::U64(ring.address(2)?), + Arg::U64(ring.address(3)?), + Arg::U64(ring.address(4)?), + Arg::U64(step), + Arg::I32(t as i32), + Arg::U64(scalar.flag(0, 14)?), + ], + )?; + Ok((cmds, native_embedding)) + } +} diff --git a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_3/impl_originalmtpfullforward_2.rs b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_3/impl_originalmtpfullforward_2.rs new file mode 100644 index 00000000..5243c6a9 --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_3/impl_originalmtpfullforward_2.rs @@ -0,0 +1,163 @@ +//! Moved out of the parent module by STRA-338: impl OriginalMtpFullForward (2). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalMtpFullForward<'ctx> { + + // Called ONLY at scalar capture preparation, immediately after the genuine + // prefix plan builder has emitted its real current step append commands. + pub(in super::super::super) fn program( + &self, + scalar: &OriginalMtpScalarPrefill<'ctx>, + ring: &MtpOriginalInt8<'ctx>, + prefix: Vec, + policy: &OriginalMtpFullPolicy, + native_embedding: Option>, + step_row: usize, + ) -> Result> { + validate_scalar_prefix(scalar)?; + ring.validate_context(self.inner.context)?; + self.validate_context(scalar.context)?; + let scratch = self.inner.scratch.as_ref().ok_or(Error::ContextPoisoned)?; + ring.reject_state_alias(scratch)?; + let sh = scratch.handle.ok_or(Error::ContextPoisoned)?; + for b in self + .inner + .weights + .prefix + .roles + .iter() + .chain(self.inner.weights.roles.iter()) + .chain([&self.inner.weights.experts, &self.inner.weights.head]) + .chain([ + scalar.scratch.as_ref().ok_or(Error::ContextPoisoned)?, + scalar.status.as_ref().ok_or(Error::ContextPoisoned)?, + scalar.records.as_ref().ok_or(Error::ContextPoisoned)?, + ]) + { + if sh.overlaps( + scratch.bytes, + b.handle.ok_or(Error::ContextPoisoned)?, + b.bytes, + ) { + let genuine_shared = self.inner.shares_original(scalar) + && Rc::ptr_eq(b, scalar.scratch.as_ref().ok_or(Error::ContextPoisoned)?); + if !genuine_shared { + return Err(Error::OutputAliasesInput); + } + } + } + if self.inner.original_layout.is_some() && !self.inner.shares_original(scalar) { + return Err(Error::InvalidQwenShape); + } + for extra in self.inner.extras.iter().flatten() { + ring.reject_state_alias(extra)?; + let h = extra.handle.ok_or(Error::ContextPoisoned)?; + for b in self + .inner + .weights + .prefix + .roles + .iter() + .chain(self.inner.weights.roles.iter()) + .chain([&self.inner.weights.experts, &self.inner.weights.head]) + .chain([ + scalar.scratch.as_ref().ok_or(Error::ContextPoisoned)?, + scalar.status.as_ref().ok_or(Error::ContextPoisoned)?, + scalar.records.as_ref().ok_or(Error::ContextPoisoned)?, + ]) + { + ring.reject_state_alias(b)?; + if h.overlaps( + extra.bytes, + b.handle.ok_or(Error::ContextPoisoned)?, + b.bytes, + ) { + return Err(Error::OutputAliasesInput); + } + } + for b in ring.buffers()?.iter().flatten() { + if h.overlaps( + extra.bytes, + b.handle.ok_or(Error::ContextPoisoned)?, + b.bytes, + ) { + return Err(Error::OutputAliasesInput); + } + } + } + for b in ring.buffers()?.iter().flatten() { + if sh.overlaps( + scratch.bytes, + b.handle.ok_or(Error::ContextPoisoned)?, + b.bytes, + ) { + return Err(Error::OutputAliasesInput); + } + } + let p = ForwardPrefix { + scalar, + ring, + step: self.inner.address(31)? + (step_row * 16) as u64, + pos: self.inner.address(32)? + (step_row * 96) as u64, + q: scalar.address(15, 8 * 80 * 36)?, + r: scalar.address(1, 40960)?, + mixed: scalar.address(11, 10240)?, + inj: scalar.address(10, 16)?, + }; + let commands = self.plan(&p, policy)?; + let mut modules = Vec::new(); + modules + .try_reserve_exact(6) + .map_err(|_| Error::HostAllocation)?; + for m in &scalar.modules { + modules.push(Rc::clone(m.as_ref().ok_or(Error::ContextPoisoned)?)); + } + let window = abi::Arguments::new(vec![ + abi::Arg::U64(p.step), + abi::Arg::I32(32768), + abi::Arg::U64(self.inner.attention(ring)?.3), + abi::Arg::I64(32768), + ])?; + let coupled_stage = if policy.coupled_j == Some(0) { + let base = self.inner.max_t * 236 + 384; + Some(FA::new(vec![ + F::U64(self.inner.mapped_address(base, 64)?), + F::U64(self.inner.mapped_address(base + 64, 4096 * 4)?), + F::U64(self.inner.address(28)?), + F::U64(self.inner.address(29)?), + F::I32(4096), + ])?) + } else { + None + }; + Ok(OriginalMtpForwardProgram { + context: scalar.context, + prefix_modules: modules.try_into().map_err(|_| Error::InvalidSize)?, + prefix_scratch: Rc::clone(scalar.scratch.as_ref().ok_or(Error::ContextPoisoned)?), + prefix_status: Rc::clone(scalar.status.as_ref().ok_or(Error::ContextPoisoned)?), + prefix_records: Rc::clone(scalar.records.as_ref().ok_or(Error::ContextPoisoned)?), + prefix_mapped: Rc::clone(&scalar.mapped), + ring: ring.retain_physical_resources()?, + tail: Rc::clone(&self.inner), + prefix, + tail_commands: commands, + split: Box::new(full_abi::Copy2D::q_split( + self.inner.address(0)?, + self.inner.address(1)?, + )), + window, + tail_reset: Arguments::new(vec![ + Arg::U64(self.inner.address(27)?), + Arg::I32(TAIL_FLAGS as i32), + ])?, + native_embedding, + coupled_stage, + residual_offset: scalar.layout.offsets[1], + input_address: scalar.address(0, 40960)?, + token_address: scalar.address(12, 4)?, + }) + } +} diff --git a/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8.rs b/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8.rs index a76aaf4e..1f980272 100644 --- a/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8.rs +++ b/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8.rs @@ -3,928 +3,13 @@ #[allow(unused_imports)] use super::*; -impl<'ctx> MtpOriginalInt8<'ctx> { - pub fn planned_device_bytes(max_t: usize) -> Result { - Ok(layout(max_t)?.1.into_iter().sum()) - } - pub fn pinned_host_bytes() -> usize { - MTP_ORIGINAL_PINNED_HOST_BYTES - } - pub fn max_snapshot_payload_bytes() -> usize { - MTP_ORIGINAL_SNAPSHOT_PAYLOAD_BYTES - } - pub fn max_snapshot_metadata_bytes() -> usize { - std::mem::size_of::() - + std::mem::size_of::() - + 8 * std::mem::size_of::() - + 65536 - * (std::mem::size_of::>() - + std::mem::size_of::() - + 2 * std::mem::size_of::()) - } - pub(super) fn new(c: &'ctx Context<'ctx>, max_t: usize) -> Result { - let (slots, sizes) = layout(max_t)?; - if c.is_poisoned() || c.handle.is_none() { - return Err(Error::ContextPoisoned); - } - // Refuse placeholders before any host or device owner allocation. - for ptx in [ - include_bytes!("../mtp_original_tail.ptx").as_slice(), - include_bytes!("../mtp_original_kv.ptx").as_slice(), - ] { - if ptx.windows(8).any(|w| w == b"UNSEALED") { - return Err(Error::UnsupportedQwenOperation); - } - } - let needed = sizes - .into_iter() - .sum::() - .checked_add(RESERVE) - .ok_or(Error::BudgetExceeded)?; - if c.allocated_bytes() - .checked_add(needed) - .is_none_or(|n| n > c.budget) - || c.memory_info()?.0 < needed - { - return Err(Error::BudgetExceeded); - } - let origin = Rc::new(Origin); - let physical = Rc::new(PhysicalRing { - context: c, - origin: origin.clone(), - sizes, - buffers: std::array::from_fn(|_| None), - modules: std::array::from_fn(|_| None), - mapped: RefCell::new(None), - selected: None, - failed: Cell::new(false), - active: Cell::new(true), - }); - let mut o = Self { - context: c, - origin, - max_t, - slots, - sizes, - physical: Some(physical), - current: None, - failed: false, - generation: 0, - }; - let operation = (|| { - let guard = c.enter().inspect_err(|_| { - c.poison(); - c.retain_driver(); - })?; - let load = (|| { - o.physical_mut()?.modules[0] = Some(Module::load( - include_bytes!("../mtp_original_tail.ptx"), - TAIL_ENTRIES, - )?); - o.physical_mut()?.modules[1] = Some(Module::load( - include_bytes!("../mtp_original_kv.ptx"), - KV_ENTRIES, - )?); - o.physical_mut()?.modules[2] = Some(Module::load( - include_bytes!("../qsa_native_decode.ptx"), - ATTN_ENTRIES, - )?); - *o.physical_mut()?.mapped.get_mut() = Some(MappedOwner::new()?); - if o.physical()? - .mapped - .borrow() - .as_ref() - .is_none_or(|m| m.bytes() != MTP_ORIGINAL_PINNED_HOST_BYTES) - { - return Err(Error::InvalidSize); - } - Ok(()) - })(); - let pop = guard.finish(); - if pop.is_err() { - o.poison(); - } - combine(load, pop)?; - for (i, n) in sizes.into_iter().enumerate() { - o.physical_mut()?.buffers[i] = Some(c.allocate(n)?); - } - // Real initialized pools; no reader ever names an unwritten logical cell. - for i in 0..4 { - o.copy_from_physical(i, &zero_bytes(sizes[i])?)?; - } - let mut table = zero_bytes(65536 * 4)?; - for (p, b) in table.chunks_exact_mut(4).enumerate() { - b.copy_from_slice(&((p % slots) as i32).to_le_bytes()); - } - o.copy_from_physical(4, &table)?; - if c.memory_info()?.0 < RESERVE { - return Err(Error::BudgetExceeded); - } - Ok(()) - })(); - if let Err(e) = operation { - return combine(Err(e), o.close()); - } - Ok(o) - } - pub(super) fn physical(&self) -> Result<&PhysicalRing<'ctx>> { - self.physical.as_deref().ok_or(Error::ContextPoisoned) - } - pub(super) fn physical_mut(&mut self) -> Result<&mut PhysicalRing<'ctx>> { - Rc::get_mut(self.physical.as_mut().ok_or(Error::ContextPoisoned)?) - .ok_or(Error::InvalidQwenShape) - } - pub(super) fn buffer(&self, i: usize) -> Result<&DeviceBuffer<'ctx>> { - self.physical()? - .buffers - .get(i) - .and_then(Option::as_ref) - .ok_or(Error::ContextPoisoned) - } - pub(super) fn buffers(&self) -> Result<&[Option>; 15]> { - Ok(&self.physical()?.buffers) - } - pub(super) fn mapped(&self) -> Result> { - Ref::filter_map( - self.physical()? - .mapped - .try_borrow() - .map_err(|_| Error::InvalidQwenShape)?, - Option::as_ref, - ) - .map_err(|_| Error::ContextPoisoned) - } - pub(super) fn mapped_mut(&self) -> Result> { - RefMut::filter_map( - self.physical()? - .mapped - .try_borrow_mut() - .map_err(|_| Error::InvalidQwenShape)?, - Option::as_mut, - ) - .map_err(|_| Error::ContextPoisoned) - } - pub(super) fn copy_from_physical(&self, i: usize, input: &[u8]) -> Result<()> { - if let Some(s) = &self.physical()?.selected { - if s.provides(i) { - return s.copy_from(i, 0, input); - } - } - let b = self.buffer(i)?; - let mut staging = b.staging(input.len())?; - staging.copy_from_slice(input); - b.copy_staged(staging, false).map(|_| ()) - } - pub(crate) fn retain_physical_resources(&self) -> Result> { - self.validate()?; - Ok(MtpOriginalRingResources { - physical: Rc::clone(self.physical.as_ref().ok_or(Error::ContextPoisoned)?), - }) - } - pub fn physical_metadata_bytes() -> usize { - std::mem::size_of::>() + 2 * std::mem::size_of::() - } - - pub(super) fn address(&self, i: usize) -> Result { - if let Some(s) = &self.physical()?.selected { - if s.provides(i) { - return Ok(s.span(i, 0, self.sizes[i])?.qwen_address()); - } - } - checked(self.context, self.buffer(i)?, self.sizes[i]) - } - pub(super) fn sub(&self, i: usize, o: usize, n: usize) -> Result { - if let Some(s) = &self.physical()?.selected { - if s.provides(i) { - return Ok(s.span(i, o, n)?.qwen_address()); - } - } - Ok(self - .buffer(i)? - .handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(self.sizes[i], o, n)? - .qwen_address()) - } - pub fn allocated_bytes(&self) -> usize { - self.physical.as_ref().map_or(0, |p| { - p.buffers.iter().flatten().map(|b| b.bytes).sum::() - + p.selected.as_ref().map_or(0, |s| s.unique_bytes()) - }) - } - pub fn is_failed(&self) -> bool { - self.failed - || self.context.is_poisoned() - || self.context.handle.is_none() - || self - .physical - .as_ref() - .is_none_or(|p| p.failed.get() || !p.active.get()) - } - pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { - if !std::ptr::eq(c, self.context) { - return Err(Error::ContextMismatch); - } - self.validate() - } - pub(super) fn validate(&self) -> Result<()> { - if self.is_failed() { - return Err(Error::ContextPoisoned); - } - self.physical()?.validate_context(self.context)?; - for i in 0..15 { - if self - .physical()? - .selected - .as_ref() - .is_some_and(|s| s.provides(i)) - { - continue; - } - let b = self.buffer(i)?; - checked(self.context, b, self.sizes[i])?; - if let Some(s) = &self.physical()?.selected { - s.reject_state_alias(b)?; - s.reject_main_alias(b)?; - } - for j in 0..i { - if self - .physical()? - .selected - .as_ref() - .is_some_and(|s| s.provides(j)) - { - continue; - } - let other = self.buffer(j)?; - if b.handle.ok_or(Error::ContextPoisoned)?.overlaps( - b.bytes, - other.handle.ok_or(Error::ContextPoisoned)?, - other.bytes, - ) { - return Err(Error::OutputAliasesInput); - } - } - } - if self.context.allocated_bytes() > self.context.budget { - return Err(Error::BudgetExceeded); - } - Ok(()) - } - pub(super) fn external( - &self, - w: &NativeBatchWorkspace<'ctx>, - b: &DeviceBuffer<'_>, - n: usize, - ) -> Result { - let addr = checked(self.context, b, n)?; - self.reject_state_alias(b)?; - if self - .physical()? - .mapped - .try_borrow() - .map_err(|_| Error::InvalidQwenShape)? - .is_some() - { - let mapped = self.mapped()?; - let ma = mapped.address(0, MTP_ORIGINAL_PINNED_HOST_BYTES)?; - if addr < ma + MTP_ORIGINAL_PINNED_HOST_BYTES as u64 && ma < addr + n as u64 { - return Err(Error::OutputAliasesInput); - } - } - if let Some(s) = &self.physical()?.selected { - s.reject_main_alias(b)?; - } - let h = b.handle.ok_or(Error::ContextPoisoned)?; - w.reject_alias(h, n)?; - for own in self.buffers()?.iter().flatten() { - if h.overlaps(n, own.handle.ok_or(Error::ContextPoisoned)?, own.bytes) { - return Err(Error::OutputAliasesInput); - } - } - Ok(addr) - } - pub fn empty_snapshot(&self) -> Result { - self.validate()?; - Ok(MtpInt8Snapshot(Rc::new(Snapshot { - origin: self.origin.clone(), - pages: Pages::empty(), - end: 0, - checked: std::cell::Cell::new(true), - }))) - } - pub fn validate_snapshot(&self, s: &MtpInt8Snapshot) -> Result<()> { - self.validate()?; - if !Rc::ptr_eq(&self.origin, &s.0.origin) - || s.0.end > MTP_ORIGINAL_MAX_CELLS - || s.0.pages.len() < s.0.end.div_ceil(4) - { - return Err(Error::InvalidQwenShape); - } - if s.0.checked.get() && snapshot_memo() { - return Ok(()); - } - for p in s.0.pages.iter().take(s.0.end.div_ceil(4)) { - for (i, n) in PAGE_BYTES.into_iter().enumerate() { - if p.runs[i].len() != n { - return Err(Error::InvalidSize); - } - } - } - s.0.checked.set(true); - Ok(()) - } - pub(super) fn poison(&mut self) { - self.failed = true; - self.current = None; - if let Some(p) = &self.physical { - p.failed.set(true); - } - self.context.poison(); - self.context.retain_driver(); - } - pub(super) fn execute( - &mut self, - w: &mut NativeBatchWorkspace<'ctx>, - mut commands: Vec, - ) -> Result<()> { - self.validate()?; - w.validate_context(self.context)?; - let blas = w.blas()?; - let stream = blas.stream(); - let modules = &self.physical()?.modules; - let g = match self.context.enter() { - Ok(g) => g, - Err(e) => { - self.poison(); - w.mark_failed(); - return Err(e); - } - }; - // Inputs may be produced on Original default stream. This confirmed dependency - // precedes the model-owned nonblocking stream, never a guessed ready flag. - let mut op = self.context.driver.api.synchronize(); - if op.is_ok() { - for command in &mut commands { - let result = match command { - Command::Kernel { - asset, - index, - grid, - block, - args, - } => modules[*asset] - .as_ref() - .map_or(Err(Error::ContextPoisoned), |m| { - m.launch(*index, *grid, *block, 0, stream, args) - }), - Command::Copy { dst, src, bytes } => modules[1] - .as_ref() - .map_or(Err(Error::ContextPoisoned), |m| { - m.copy(*dst, *src, *bytes, stream) - }), - }; - if let Err(e) = result { - op = Err(e); - break; - } - } - } - let sync = blas.synchronize(); - let pop = g.finish(); - let uncertain = sync.is_err() || pop.is_err(); - if uncertain { - std::mem::forget(commands); - } - if op.is_err() || uncertain { - self.poison(); - w.mark_failed(); - } - combine(combine(op, sync), pop) - } - pub(super) fn push( - commands: &mut Vec, - asset: usize, - index: usize, - grid: [u32; 3], - block: [u32; 3], - values: Vec, - ) -> Result<()> { - commands.try_reserve(1).map_err(|_| Error::HostAllocation)?; - commands.push(Command::Kernel { - asset, - index, - grid, - block, - args: Arguments::new(values)?, - }); - Ok(()) - } - pub(super) fn finite(&self, commands: &mut Vec, a: u64, n: usize, status: usize) -> Result<()> { - Self::push( - commands, - 0, - 11, - [64, 1, 1], - [256, 1, 1], - vec![ - Arg::U64(a), - Arg::I32(n as i32), - Arg::U64(self.sub(10, status * 4, 4)?), - ], - ) - } - pub(super) fn flags(&mut self) -> Result<[u32; STATUS_WORDS]> { - let b = self.buffer(10)?.copy_to_owned(STATUS_WORDS * 4)?; - let mut s = [0; STATUS_WORDS]; - for (i, v) in b.chunks_exact(4).enumerate() { - s[i] = u32::from_le_bytes(v.try_into().map_err(|_| Error::InvalidSize)?); - if s[i] > 1 { - self.poison(); - return Err(Error::InvalidDriverValue("MTP finite flags")); - } - } - Ok(s) - } - /// Restore real immutable host pages, then exact Original modulo ring blocks. - /// The current witness is invalidated BEFORE any write; valid-end guards prevent - /// O(1) future-backing pages from incorrectly skipping rematerialization. - pub fn restore( - &mut self, - w: &mut NativeBatchWorkspace<'ctx>, - s: &MtpInt8Snapshot, - ) -> Result<()> { - self.validate_snapshot(s)?; - w.validate_context(self.context)?; - self.generation = self - .generation - .checked_add(1) - .ok_or(Error::InvalidQwenShape)?; - if self - .current - .as_ref() - .is_some_and(|old| Rc::ptr_eq(&old.0, &s.0)) - { - return Ok(()); - } - let previous = self.current.take(); - if self.fully_resident()? { - // Canonical snapshots remain genuine; restore overwritten accepted pages - // to the same identity cells before publishing the restored witness. - for (p, page) in s.0.pages.iter().take(s.0.end.div_ceil(4)).enumerate() { - if previous.as_ref().is_some_and(|old| { - p < old.0.end.div_ceil(4) - && old.0.pages.get(p).is_some_and(|x| Rc::ptr_eq(x, page)) - }) { - continue; - } - let state = self - .physical()? - .selected - .as_ref() - .ok_or(Error::ContextPoisoned)?; - for (i, n) in PAGE_BYTES.into_iter().enumerate() { - state.copy_from(i, p * n, &page.runs[i])?; - } - } - self.current = Some(s.clone()); - return Ok(()); - } - let mut mapped = self.mapped_mut()?; - for (p, page) in s.0.pages.iter().take(s.0.end.div_ceil(4)).enumerate() { - if previous.as_ref().is_some_and(|old| { - p < old.0.end.div_ceil(4) && old.0.pages.get(p).is_some_and(|x| Rc::ptr_eq(x, page)) - }) { - continue; - } - for (i, n) in PAGE_BYTES.into_iter().enumerate() { - mapped.write(HOST_OFFSETS[i] + p * n, &page.runs[i])?; - } - } - drop(mapped); - let b1 = s.0.end.div_ceil(4); - let b0 = b1.saturating_sub(self.slots); - let mut commands = Vec::new(); - commands - .try_reserve_exact(8) - .map_err(|_| Error::HostAllocation)?; - let mut b = b0; - while b < b1 { - let slot = b % self.slots; - let run = (b1 - b).min(self.slots - slot); - for (i, n) in PAGE_BYTES.into_iter().enumerate() { - commands.push(Command::Copy { - dst: self.sub(i, slot * n, run * n)?, - src: self.mapped()?.address(HOST_OFFSETS[i] + b * n, run * n)?, - bytes: run * n, - }); - } - b += run; - } - if !commands.is_empty() { - self.execute(w, commands)?; - } - self.current = Some(s.clone()); - Ok(()) - } - /// Exact attention tail of record_forward(false). Real input+GR has already - /// produced this opaque mixed owner; no full MLP/head work is performed here. - pub fn record_kv_only<'loan, 'buffers, 'weights>( - &'loan mut self, - w: &mut NativeBatchWorkspace<'ctx>, - prior: &MtpInt8Snapshot, - input: &'loan MtpOriginalMixed<'loan, 'buffers>, - weights: [&'loan DeviceBuffer<'weights>; 3], - ) -> Result> { - self.validate_snapshot(prior)?; - w.validate_context(self.context)?; - rows_range(input.first, input.rows, self.max_t)?; - if input.first > prior.0.end { - return Err(Error::InvalidQwenShape); - } - let mixed = self.external(w, input.mixed, input.rows * 10240)?; - let wk = self.external(w, weights[0], 512 * 80 * 34)?; - let wv = self.external(w, weights[1], 512 * 80 * 34)?; - let gamma = self.external(w, weights[2], 256 * 4)?; - let spans = [ - ( - input.mixed.handle.ok_or(Error::ContextPoisoned)?, - input.mixed.bytes, - ), - ( - weights[0].handle.ok_or(Error::ContextPoisoned)?, - weights[0].bytes, - ), - ( - weights[1].handle.ok_or(Error::ContextPoisoned)?, - weights[1].bytes, - ), - ( - weights[2].handle.ok_or(Error::ContextPoisoned)?, - weights[2].bytes, - ), - ]; - for (i, (a, an)) in spans.iter().enumerate() { - for (b, bn) in spans.iter().take(i) { - let exact = a.qwen_address() == b.qwen_address() && an == bn; - if !exact && a.overlaps(*an, *b, *bn) { - return Err(Error::OutputAliasesInput); - } - } - } - let generation = self - .generation - .checked_add(1) - .ok_or(Error::InvalidQwenShape)?; - let end = input.first + input.rows; - let n_pages = end.div_ceil(4); - let first_page = input.first / 4; - // All new host ownership is fallibly allocated before the first command. - let mut pages = Vec::new(); - pages - .try_reserve_exact(n_pages) - .map_err(|_| Error::HostAllocation)?; - for page in prior.0.pages.iter().take(first_page) { - pages.push(page.clone()); - } - let mut changed = Vec::new(); - changed - .try_reserve_exact(n_pages - first_page) - .map_err(|_| Error::HostAllocation)?; - for p in first_page..n_pages { - let mut runs: [Vec; 4] = std::array::from_fn(|_| Vec::new()); - for (i, n) in PAGE_BYTES.into_iter().enumerate() { - runs[i] = zero_bytes(n)?; - if let Some(old) = prior.0.pages.get(p) { - runs[i].copy_from_slice(&old.runs[i]); - } - } - changed.push(runs); - } - let mut pos = zero_bytes(self.sizes[8])?; - let mut steps = zero_bytes(self.sizes[9])?; - for t in 0..input.rows { - let p = input.first + t; - for h in 0..24 { - pos[(t * 24 + h) * 4..(t * 24 + h + 1) * 4] - .copy_from_slice(&(p as i32).to_le_bytes()); - } - for (i, v) in [p, p + 1, (p + 1) / 4, p + 1].into_iter().enumerate() { - steps[(t * 4 + i) * 4..(t * 4 + i + 1) * 4] - .copy_from_slice(&(v as i32).to_le_bytes()); - } - } - // The real mixed producer supplies the rewind position. Restoring the - // longer prior's ring would keep future blocks after a shorter replay. - // This private prefix is bounded by that genuine prior, never caller-minted. - let replay_prior = if input.first == prior.0.end { - prior.clone() - } else { - MtpInt8Snapshot(Rc::new(Snapshot { - origin: prior.0.origin.clone(), - pages: prior.0.pages.clone(), - end: input.first, - checked: std::cell::Cell::new(prior.0.checked.get()), - })) - }; - self.restore(w, &replay_prior)?; - self.copy_from_physical(8, &pos)?; - self.copy_from_physical(9, &steps)?; - self.copy_from_physical(10, &[0; STATUS_WORDS * 4])?; - let mut commands = Vec::new(); - commands - .try_reserve_exact(32 + input.rows * 5) - .map_err(|_| Error::HostAllocation)?; - self.finite(&mut commands, mixed, input.rows * 2560, 0)?; - Self::push( - &mut commands, - 0, - 0, - [(input.rows * 2560).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - vec![ - Arg::U64(mixed), - Arg::U64(self.address(5)?), - Arg::I32((input.rows * 2560) as i32), - ], - )?; - Self::push( - &mut commands, - 0, - 12, - [64, 1, 1], - [256, 1, 1], - vec![ - Arg::U64(self.address(5)?), - Arg::I32((input.rows * 80) as i32), - Arg::U64(self.sub(10, 4, 4)?), - ], - )?; - for (weight, out, status) in [(wk, 6, 2), (wv, 7, 3)] { - Self::push( - &mut commands, - 0, - input.rows, - [512, 1, 1], - [32, 4, 1], - vec![ - Arg::U64(weight), - Arg::U64(self.address(5)?), - Arg::U64(self.address(out)?), - Arg::I32(2560), - Arg::I32(512), - ], - )?; - self.finite(&mut commands, self.address(out)?, input.rows * 512, status)?; - } - for t in 0..input.rows { - let k = self.sub(6, t * 2048, 2048)?; - Self::push( - &mut commands, - 0, - 9, - [2, 1, 1], - [256, 1, 1], - vec![ - Arg::U64(k), - Arg::U64(gamma), - Arg::U64(k), - Arg::I32(256), - Arg::F32(1.0e-6), - ], - )?; - self.finite(&mut commands, k, 512, 4 + 2 * t)?; - Self::push( - &mut commands, - 0, - 10, - [1, 2, 1], - [128, 1, 1], - vec![ - Arg::U64(k), - Arg::U64(k), - Arg::I32(2), - Arg::I32(256), - Arg::F32(crate::qsa_index_ffi::theta()), - Arg::U64(self.sub(8, t * 96, 8)?), - ], - )?; - self.finite(&mut commands, k, 512, 5 + 2 * t)?; - } - // First failed upstream full scan/quant wins. No host/ring write before - // successful numeric admission of all real K/V rows. - self.execute(w, commands)?; - let flags = self.flags()?; - for (i, v) in flags.iter().enumerate().take(4 + 2 * input.rows) { - if *v != 0 { - return Err(if i == 1 { - Error::InvalidQ8Activation - } else { - Error::NonFiniteMmqOutput("mtp-kv-only") - }); - } - } - let mut append = Vec::new(); - append - .try_reserve_exact(input.rows * 2) - .map_err(|_| Error::HostAllocation)?; - let host = self.host_addresses()?; - for t in 0..input.rows { - Self::push( - &mut append, - 1, - 0, - [2, 4, 2], - [64, 1, 1], - vec![ - Arg::U64(self.address(0)?), - Arg::U64(self.address(1)?), - Arg::U64(self.address(2)?), - Arg::U64(self.address(3)?), - Arg::U64(self.address(4)?), - Arg::U64(self.sub(9, t * 16, 16)?), - Arg::U64(self.sub(6, t * 2048, 2048)?), - Arg::U64(self.sub(7, t * 2048, 2048)?), - Arg::I32(2), - Arg::I32(256), - Arg::I32(4), - Arg::U64(host[0]), - Arg::U64(host[1]), - Arg::U64(host[2]), - Arg::U64(host[3]), - ], - )?; - } - Self::push( - &mut append, - 1, - 3, - [64, 1, 1], - [256, 1, 1], - vec![ - Arg::U64(self.address(2)?), - Arg::U64(self.address(3)?), - Arg::I32((self.slots * 32) as i32), - Arg::U64(self.sub(10, (4 + 2 * self.max_t) * 4, 4)?), - ], - )?; - self.current = None; // source pages and resident ring mutate only after invalidation - self.execute(w, append)?; - if self.flags()?[4 + 2 * self.max_t] != 0 { - return Err(Error::NonFiniteMmqOutput("mtp-int8-scale")); - } - for (p, runs) in changed.iter_mut().enumerate() { - self.read_encoded_page(p + first_page, runs)?; - } - for runs in changed { - pages.push(Rc::new(Page { - runs: runs.map(Vec::into_boxed_slice), - })); - } - let snapshot = MtpInt8Snapshot(Rc::new(Snapshot { - origin: self.origin.clone(), - pages: Pages::from_vec(pages), - end, - checked: std::cell::Cell::new(false), - })); - self.current = Some(snapshot.clone()); - self.generation = generation; - Ok(CompletedMtpKvReplay { - owner: self, - snapshot, - _mixed: input, - _weights: weights, - first: input.first, - rows: input.rows, - }) - } - /// Literal Original dense-window INT8 split-K attention. No selected index, - /// clock resolver, prompt MMA or F16 intermediate pool stands in for the ring. - pub fn attend<'loan, 'buffers>( - &'loan mut self, - w: &mut NativeBatchWorkspace<'ctx>, - snapshot: &'loan MtpInt8Snapshot, - position: usize, - query: &'loan MtpOriginalQuery<'loan, 'buffers>, - ) -> Result> { - self.validate_snapshot(snapshot)?; - w.validate_context(self.context)?; - if position >= snapshot.0.end { - return Err(Error::InvalidQwenShape); - } - // Snapshot may contain the whole verified suffix. Its ring's extra4*S+64 - // cells cover every legal earlier query in that same completed replay. - let b1 = snapshot.0.end.div_ceil(4); - let oldest = (position + 1).saturating_sub(MTP_ORIGINAL_WINDOW); - if oldest / 4 < b1.saturating_sub(self.slots) { - return Err(Error::InvalidQwenShape); - } - let q = self.external(w, query.query, 24576)?; - self.restore(w, snapshot)?; - self.copy_from_physical(10, &[0; STATUS_WORDS * 4])?; - let mut steps = [0u8; 16]; - for (i, v) in [position, position + 1, (position + 1) / 4, position + 1] - .into_iter() - .enumerate() - { - steps[i * 4..i * 4 + 4].copy_from_slice(&(v as i32).to_le_bytes()); - } - self.copy_from_physical(14, &steps)?; - let mut admission = Vec::new(); - self.finite(&mut admission, q, 6144, 0)?; - self.execute(w, admission)?; - if self.flags()?[0] != 0 { - return Err(Error::NonFiniteMmqOutput("mtp-query")); - } - let mut commands = Vec::new(); - commands - .try_reserve_exact(4) - .map_err(|_| Error::HostAllocation)?; - Self::push( - &mut commands, - 1, - 2, - [8, 1, 1], - [256, 1, 1], - vec![ - Arg::U64(self.address(14)?), - Arg::I32(32768), - Arg::U64(self.address(13)?), - Arg::I64(32768), - ], - )?; - let pa = self.address(12)?; - let pm = self.sub(12, CHUNKS * 24 * 256 * 4, CHUNKS * 24 * 4)?; - let pl = self.sub(12, CHUNKS * 24 * 257 * 4, CHUNKS * 24 * 4)?; - Self::push( - &mut commands, - 2, - 1, - [CHUNKS as u32, 2, 1], - [256, 1, 1], - vec![ - Arg::U64(q), - Arg::U64(self.address(0)?), - Arg::U64(self.address(1)?), - Arg::U64(self.address(2)?), - Arg::U64(self.address(3)?), - Arg::U64(self.address(4)?), - Arg::U64(self.address(13)?), - Arg::U64(self.address(14)?), - Arg::I32(2), - Arg::I32(4), - Arg::F32(1.0 / 16.0), - Arg::U64(pa), - Arg::U64(pm), - Arg::U64(pl), - Arg::I32(CHUNKS as i32), - Arg::I32(32768), - Arg::I64(SCRATCH_FLOATS as i64), - ], - )?; - Self::push( - &mut commands, - 2, - 2, - [24, 1, 1], - [256, 1, 1], - vec![ - Arg::U64(pa), - Arg::U64(pm), - Arg::U64(pl), - Arg::I32(CHUNKS as i32), - Arg::U64(self.address(11)?), - Arg::I64(SCRATCH_FLOATS as i64), - ], - )?; - self.finite(&mut commands, self.address(11)?, 6144, 1)?; - self.execute(w, commands)?; - if self.flags()?[1] != 0 { - return Err(Error::NonFiniteMmqOutput("mtp-int8-attention")); - } - Ok(CompletedMtpAttention { - owner: self, - _snapshot: snapshot, - _query: query, - }) - } - pub fn close(mut self) -> Result<()> { - self.close_inner() - } - pub(super) fn close_inner(&mut self) -> Result<()> { - self.failed = true; - self.current = None; - let Some(mut physical) = self.physical.take() else { - return Ok(()); - }; - physical.active.set(false); - // Explicit close requires graph retirement first. Dropping this logical - // ring never frees allocations retained by a real graph resource token. - if Rc::strong_count(&physical) != 1 { - return Err(Error::InvalidQwenShape); - } - Rc::get_mut(&mut physical) - .ok_or(Error::InvalidQwenShape)? - .close_inner() - } -} +#[path = "impl_mtporiginalint8/impl_mtporiginalint8_2.rs"] +mod impl_mtporiginalint8_2; +#[path = "impl_mtporiginalint8/impl_mtporiginalint8_2_2.rs"] +mod impl_mtporiginalint8_2_2; +#[path = "impl_mtporiginalint8/impl_mtporiginalint8_3.rs"] +mod impl_mtporiginalint8_3; +#[path = "impl_mtporiginalint8/impl_mtporiginalint8_4.rs"] +mod impl_mtporiginalint8_4; +#[path = "impl_mtporiginalint8/impl_mtporiginalint8_5.rs"] +mod impl_mtporiginalint8_5; diff --git a/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_2.rs b/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_2.rs new file mode 100644 index 00000000..7512e7e8 --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_2.rs @@ -0,0 +1,231 @@ +//! Moved out of the parent module by STRA-338: impl MtpOriginalInt8. + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> MtpOriginalInt8<'ctx> { + pub fn planned_device_bytes(max_t: usize) -> Result { + Ok(layout(max_t)?.1.into_iter().sum()) + } + pub fn pinned_host_bytes() -> usize { + MTP_ORIGINAL_PINNED_HOST_BYTES + } + pub fn max_snapshot_payload_bytes() -> usize { + MTP_ORIGINAL_SNAPSHOT_PAYLOAD_BYTES + } + pub fn max_snapshot_metadata_bytes() -> usize { + std::mem::size_of::() + + std::mem::size_of::() + + 8 * std::mem::size_of::() + + 65536 + * (std::mem::size_of::>() + + std::mem::size_of::() + + 2 * std::mem::size_of::()) + } + pub(in super::super) fn new(c: &'ctx Context<'ctx>, max_t: usize) -> Result { + let (slots, sizes) = layout(max_t)?; + if c.is_poisoned() || c.handle.is_none() { + return Err(Error::ContextPoisoned); + } + // Refuse placeholders before any host or device owner allocation. + for ptx in [ + include_bytes!("../../mtp_original_tail.ptx").as_slice(), + include_bytes!("../../mtp_original_kv.ptx").as_slice(), + ] { + if ptx.windows(8).any(|w| w == b"UNSEALED") { + return Err(Error::UnsupportedQwenOperation); + } + } + let needed = sizes + .into_iter() + .sum::() + .checked_add(RESERVE) + .ok_or(Error::BudgetExceeded)?; + if c.allocated_bytes() + .checked_add(needed) + .is_none_or(|n| n > c.budget) + || c.memory_info()?.0 < needed + { + return Err(Error::BudgetExceeded); + } + let origin = Rc::new(Origin); + let physical = Rc::new(PhysicalRing { + context: c, + origin: origin.clone(), + sizes, + buffers: std::array::from_fn(|_| None), + modules: std::array::from_fn(|_| None), + mapped: RefCell::new(None), + selected: None, + failed: Cell::new(false), + active: Cell::new(true), + }); + let mut o = Self { + context: c, + origin, + max_t, + slots, + sizes, + physical: Some(physical), + current: None, + failed: false, + generation: 0, + }; + let operation = (|| { + let guard = c.enter().inspect_err(|_| { + c.poison(); + c.retain_driver(); + })?; + let load = (|| { + o.physical_mut()?.modules[0] = Some(Module::load( + include_bytes!("../../mtp_original_tail.ptx"), + TAIL_ENTRIES, + )?); + o.physical_mut()?.modules[1] = Some(Module::load( + include_bytes!("../../mtp_original_kv.ptx"), + KV_ENTRIES, + )?); + o.physical_mut()?.modules[2] = Some(Module::load( + include_bytes!("../../qsa_native_decode.ptx"), + ATTN_ENTRIES, + )?); + *o.physical_mut()?.mapped.get_mut() = Some(MappedOwner::new()?); + if o.physical()? + .mapped + .borrow() + .as_ref() + .is_none_or(|m| m.bytes() != MTP_ORIGINAL_PINNED_HOST_BYTES) + { + return Err(Error::InvalidSize); + } + Ok(()) + })(); + let pop = guard.finish(); + if pop.is_err() { + o.poison(); + } + combine(load, pop)?; + for (i, n) in sizes.into_iter().enumerate() { + o.physical_mut()?.buffers[i] = Some(c.allocate(n)?); + } + // Real initialized pools; no reader ever names an unwritten logical cell. + for i in 0..4 { + o.copy_from_physical(i, &zero_bytes(sizes[i])?)?; + } + let mut table = zero_bytes(65536 * 4)?; + for (p, b) in table.chunks_exact_mut(4).enumerate() { + b.copy_from_slice(&((p % slots) as i32).to_le_bytes()); + } + o.copy_from_physical(4, &table)?; + if c.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + Ok(()) + })(); + if let Err(e) = operation { + return combine(Err(e), o.close()); + } + Ok(o) + } + pub(in super::super) fn physical(&self) -> Result<&PhysicalRing<'ctx>> { + self.physical.as_deref().ok_or(Error::ContextPoisoned) + } + pub(in super::super) fn physical_mut(&mut self) -> Result<&mut PhysicalRing<'ctx>> { + Rc::get_mut(self.physical.as_mut().ok_or(Error::ContextPoisoned)?) + .ok_or(Error::InvalidQwenShape) + } + pub(in super::super) fn buffer(&self, i: usize) -> Result<&DeviceBuffer<'ctx>> { + self.physical()? + .buffers + .get(i) + .and_then(Option::as_ref) + .ok_or(Error::ContextPoisoned) + } + pub(in super::super) fn buffers(&self) -> Result<&[Option>; 15]> { + Ok(&self.physical()?.buffers) + } + pub(in super::super) fn mapped(&self) -> Result> { + Ref::filter_map( + self.physical()? + .mapped + .try_borrow() + .map_err(|_| Error::InvalidQwenShape)?, + Option::as_ref, + ) + .map_err(|_| Error::ContextPoisoned) + } + pub(in super::super) fn mapped_mut(&self) -> Result> { + RefMut::filter_map( + self.physical()? + .mapped + .try_borrow_mut() + .map_err(|_| Error::InvalidQwenShape)?, + Option::as_mut, + ) + .map_err(|_| Error::ContextPoisoned) + } + pub(in super::super) fn copy_from_physical(&self, i: usize, input: &[u8]) -> Result<()> { + if let Some(s) = &self.physical()?.selected { + if s.provides(i) { + return s.copy_from(i, 0, input); + } + } + let b = self.buffer(i)?; + let mut staging = b.staging(input.len())?; + staging.copy_from_slice(input); + b.copy_staged(staging, false).map(|_| ()) + } + pub(crate) fn retain_physical_resources(&self) -> Result> { + self.validate()?; + Ok(MtpOriginalRingResources { + physical: Rc::clone(self.physical.as_ref().ok_or(Error::ContextPoisoned)?), + }) + } + pub fn physical_metadata_bytes() -> usize { + std::mem::size_of::>() + 2 * std::mem::size_of::() + } + + pub(in super::super) fn address(&self, i: usize) -> Result { + if let Some(s) = &self.physical()?.selected { + if s.provides(i) { + return Ok(s.span(i, 0, self.sizes[i])?.qwen_address()); + } + } + checked(self.context, self.buffer(i)?, self.sizes[i]) + } + pub(in super::super) fn sub(&self, i: usize, o: usize, n: usize) -> Result { + if let Some(s) = &self.physical()?.selected { + if s.provides(i) { + return Ok(s.span(i, o, n)?.qwen_address()); + } + } + Ok(self + .buffer(i)? + .handle + .ok_or(Error::ContextPoisoned)? + .checked_subspan(self.sizes[i], o, n)? + .qwen_address()) + } + pub fn allocated_bytes(&self) -> usize { + self.physical.as_ref().map_or(0, |p| { + p.buffers.iter().flatten().map(|b| b.bytes).sum::() + + p.selected.as_ref().map_or(0, |s| s.unique_bytes()) + }) + } + pub fn is_failed(&self) -> bool { + self.failed + || self.context.is_poisoned() + || self.context.handle.is_none() + || self + .physical + .as_ref() + .is_none_or(|p| p.failed.get() || !p.active.get()) + } + pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { + if !std::ptr::eq(c, self.context) { + return Err(Error::ContextMismatch); + } + self.validate() + } +} diff --git a/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_2_2.rs b/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_2_2.rs new file mode 100644 index 00000000..4bb0b4ac --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_2_2.rs @@ -0,0 +1,227 @@ +//! Moved out of the parent module by STRA-338: impl MtpOriginalInt8 (2). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> MtpOriginalInt8<'ctx> { + pub(in super::super) fn validate(&self) -> Result<()> { + if self.is_failed() { + return Err(Error::ContextPoisoned); + } + self.physical()?.validate_context(self.context)?; + for i in 0..15 { + if self + .physical()? + .selected + .as_ref() + .is_some_and(|s| s.provides(i)) + { + continue; + } + let b = self.buffer(i)?; + checked(self.context, b, self.sizes[i])?; + if let Some(s) = &self.physical()?.selected { + s.reject_state_alias(b)?; + s.reject_main_alias(b)?; + } + for j in 0..i { + if self + .physical()? + .selected + .as_ref() + .is_some_and(|s| s.provides(j)) + { + continue; + } + let other = self.buffer(j)?; + if b.handle.ok_or(Error::ContextPoisoned)?.overlaps( + b.bytes, + other.handle.ok_or(Error::ContextPoisoned)?, + other.bytes, + ) { + return Err(Error::OutputAliasesInput); + } + } + } + if self.context.allocated_bytes() > self.context.budget { + return Err(Error::BudgetExceeded); + } + Ok(()) + } + pub(in super::super) fn external( + &self, + w: &NativeBatchWorkspace<'ctx>, + b: &DeviceBuffer<'_>, + n: usize, + ) -> Result { + let addr = checked(self.context, b, n)?; + self.reject_state_alias(b)?; + if self + .physical()? + .mapped + .try_borrow() + .map_err(|_| Error::InvalidQwenShape)? + .is_some() + { + let mapped = self.mapped()?; + let ma = mapped.address(0, MTP_ORIGINAL_PINNED_HOST_BYTES)?; + if addr < ma + MTP_ORIGINAL_PINNED_HOST_BYTES as u64 && ma < addr + n as u64 { + return Err(Error::OutputAliasesInput); + } + } + if let Some(s) = &self.physical()?.selected { + s.reject_main_alias(b)?; + } + let h = b.handle.ok_or(Error::ContextPoisoned)?; + w.reject_alias(h, n)?; + for own in self.buffers()?.iter().flatten() { + if h.overlaps(n, own.handle.ok_or(Error::ContextPoisoned)?, own.bytes) { + return Err(Error::OutputAliasesInput); + } + } + Ok(addr) + } + pub fn empty_snapshot(&self) -> Result { + self.validate()?; + Ok(MtpInt8Snapshot(Rc::new(Snapshot { + origin: self.origin.clone(), + pages: Pages::empty(), + end: 0, + checked: std::cell::Cell::new(true), + }))) + } + pub fn validate_snapshot(&self, s: &MtpInt8Snapshot) -> Result<()> { + self.validate()?; + if !Rc::ptr_eq(&self.origin, &s.0.origin) + || s.0.end > MTP_ORIGINAL_MAX_CELLS + || s.0.pages.len() < s.0.end.div_ceil(4) + { + return Err(Error::InvalidQwenShape); + } + if s.0.checked.get() && snapshot_memo() { + return Ok(()); + } + for p in s.0.pages.iter().take(s.0.end.div_ceil(4)) { + for (i, n) in PAGE_BYTES.into_iter().enumerate() { + if p.runs[i].len() != n { + return Err(Error::InvalidSize); + } + } + } + s.0.checked.set(true); + Ok(()) + } + pub(in super::super) fn poison(&mut self) { + self.failed = true; + self.current = None; + if let Some(p) = &self.physical { + p.failed.set(true); + } + self.context.poison(); + self.context.retain_driver(); + } + pub(in super::super) fn execute( + &mut self, + w: &mut NativeBatchWorkspace<'ctx>, + mut commands: Vec, + ) -> Result<()> { + self.validate()?; + w.validate_context(self.context)?; + let blas = w.blas()?; + let stream = blas.stream(); + let modules = &self.physical()?.modules; + let g = match self.context.enter() { + Ok(g) => g, + Err(e) => { + self.poison(); + w.mark_failed(); + return Err(e); + } + }; + // Inputs may be produced on Original default stream. This confirmed dependency + // precedes the model-owned nonblocking stream, never a guessed ready flag. + let mut op = self.context.driver.api.synchronize(); + if op.is_ok() { + for command in &mut commands { + let result = match command { + Command::Kernel { + asset, + index, + grid, + block, + args, + } => modules[*asset] + .as_ref() + .map_or(Err(Error::ContextPoisoned), |m| { + m.launch(*index, *grid, *block, 0, stream, args) + }), + Command::Copy { dst, src, bytes } => modules[1] + .as_ref() + .map_or(Err(Error::ContextPoisoned), |m| { + m.copy(*dst, *src, *bytes, stream) + }), + }; + if let Err(e) = result { + op = Err(e); + break; + } + } + } + let sync = blas.synchronize(); + let pop = g.finish(); + let uncertain = sync.is_err() || pop.is_err(); + if uncertain { + std::mem::forget(commands); + } + if op.is_err() || uncertain { + self.poison(); + w.mark_failed(); + } + combine(combine(op, sync), pop) + } + pub(in super::super) fn push( + commands: &mut Vec, + asset: usize, + index: usize, + grid: [u32; 3], + block: [u32; 3], + values: Vec, + ) -> Result<()> { + commands.try_reserve(1).map_err(|_| Error::HostAllocation)?; + commands.push(Command::Kernel { + asset, + index, + grid, + block, + args: Arguments::new(values)?, + }); + Ok(()) + } + pub(in super::super) fn finite(&self, commands: &mut Vec, a: u64, n: usize, status: usize) -> Result<()> { + Self::push( + commands, + 0, + 11, + [64, 1, 1], + [256, 1, 1], + vec![ + Arg::U64(a), + Arg::I32(n as i32), + Arg::U64(self.sub(10, status * 4, 4)?), + ], + ) + } + pub(in super::super) fn flags(&mut self) -> Result<[u32; STATUS_WORDS]> { + let b = self.buffer(10)?.copy_to_owned(STATUS_WORDS * 4)?; + let mut s = [0; STATUS_WORDS]; + for (i, v) in b.chunks_exact(4).enumerate() { + s[i] = u32::from_le_bytes(v.try_into().map_err(|_| Error::InvalidSize)?); + if s[i] > 1 { + self.poison(); + return Err(Error::InvalidDriverValue("MTP finite flags")); + } + } + Ok(s) + } +} diff --git a/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_3.rs b/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_3.rs new file mode 100644 index 00000000..df3abf9b --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_3.rs @@ -0,0 +1,89 @@ +//! Moved out of the parent module by STRA-338: impl MtpOriginalInt8 (3). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> MtpOriginalInt8<'ctx> { + /// Restore real immutable host pages, then exact Original modulo ring blocks. + /// The current witness is invalidated BEFORE any write; valid-end guards prevent + /// O(1) future-backing pages from incorrectly skipping rematerialization. + pub fn restore( + &mut self, + w: &mut NativeBatchWorkspace<'ctx>, + s: &MtpInt8Snapshot, + ) -> Result<()> { + self.validate_snapshot(s)?; + w.validate_context(self.context)?; + self.generation = self + .generation + .checked_add(1) + .ok_or(Error::InvalidQwenShape)?; + if self + .current + .as_ref() + .is_some_and(|old| Rc::ptr_eq(&old.0, &s.0)) + { + return Ok(()); + } + let previous = self.current.take(); + if self.fully_resident()? { + // Canonical snapshots remain genuine; restore overwritten accepted pages + // to the same identity cells before publishing the restored witness. + for (p, page) in s.0.pages.iter().take(s.0.end.div_ceil(4)).enumerate() { + if previous.as_ref().is_some_and(|old| { + p < old.0.end.div_ceil(4) + && old.0.pages.get(p).is_some_and(|x| Rc::ptr_eq(x, page)) + }) { + continue; + } + let state = self + .physical()? + .selected + .as_ref() + .ok_or(Error::ContextPoisoned)?; + for (i, n) in PAGE_BYTES.into_iter().enumerate() { + state.copy_from(i, p * n, &page.runs[i])?; + } + } + self.current = Some(s.clone()); + return Ok(()); + } + let mut mapped = self.mapped_mut()?; + for (p, page) in s.0.pages.iter().take(s.0.end.div_ceil(4)).enumerate() { + if previous.as_ref().is_some_and(|old| { + p < old.0.end.div_ceil(4) && old.0.pages.get(p).is_some_and(|x| Rc::ptr_eq(x, page)) + }) { + continue; + } + for (i, n) in PAGE_BYTES.into_iter().enumerate() { + mapped.write(HOST_OFFSETS[i] + p * n, &page.runs[i])?; + } + } + drop(mapped); + let b1 = s.0.end.div_ceil(4); + let b0 = b1.saturating_sub(self.slots); + let mut commands = Vec::new(); + commands + .try_reserve_exact(8) + .map_err(|_| Error::HostAllocation)?; + let mut b = b0; + while b < b1 { + let slot = b % self.slots; + let run = (b1 - b).min(self.slots - slot); + for (i, n) in PAGE_BYTES.into_iter().enumerate() { + commands.push(Command::Copy { + dst: self.sub(i, slot * n, run * n)?, + src: self.mapped()?.address(HOST_OFFSETS[i] + b * n, run * n)?, + bytes: run * n, + }); + } + b += run; + } + if !commands.is_empty() { + self.execute(w, commands)?; + } + self.current = Some(s.clone()); + Ok(()) + } +} diff --git a/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_4.rs b/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_4.rs new file mode 100644 index 00000000..32cd067b --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_4.rs @@ -0,0 +1,279 @@ +//! Moved out of the parent module by STRA-338: impl MtpOriginalInt8 (4). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> MtpOriginalInt8<'ctx> { + /// Exact attention tail of record_forward(false). Real input+GR has already + /// produced this opaque mixed owner; no full MLP/head work is performed here. + pub fn record_kv_only<'loan, 'buffers, 'weights>( + &'loan mut self, + w: &mut NativeBatchWorkspace<'ctx>, + prior: &MtpInt8Snapshot, + input: &'loan MtpOriginalMixed<'loan, 'buffers>, + weights: [&'loan DeviceBuffer<'weights>; 3], + ) -> Result> { + self.validate_snapshot(prior)?; + w.validate_context(self.context)?; + rows_range(input.first, input.rows, self.max_t)?; + if input.first > prior.0.end { + return Err(Error::InvalidQwenShape); + } + let mixed = self.external(w, input.mixed, input.rows * 10240)?; + let wk = self.external(w, weights[0], 512 * 80 * 34)?; + let wv = self.external(w, weights[1], 512 * 80 * 34)?; + let gamma = self.external(w, weights[2], 256 * 4)?; + let spans = [ + ( + input.mixed.handle.ok_or(Error::ContextPoisoned)?, + input.mixed.bytes, + ), + ( + weights[0].handle.ok_or(Error::ContextPoisoned)?, + weights[0].bytes, + ), + ( + weights[1].handle.ok_or(Error::ContextPoisoned)?, + weights[1].bytes, + ), + ( + weights[2].handle.ok_or(Error::ContextPoisoned)?, + weights[2].bytes, + ), + ]; + for (i, (a, an)) in spans.iter().enumerate() { + for (b, bn) in spans.iter().take(i) { + let exact = a.qwen_address() == b.qwen_address() && an == bn; + if !exact && a.overlaps(*an, *b, *bn) { + return Err(Error::OutputAliasesInput); + } + } + } + let generation = self + .generation + .checked_add(1) + .ok_or(Error::InvalidQwenShape)?; + let end = input.first + input.rows; + let n_pages = end.div_ceil(4); + let first_page = input.first / 4; + // All new host ownership is fallibly allocated before the first command. + let mut pages = Vec::new(); + pages + .try_reserve_exact(n_pages) + .map_err(|_| Error::HostAllocation)?; + for page in prior.0.pages.iter().take(first_page) { + pages.push(page.clone()); + } + let mut changed = Vec::new(); + changed + .try_reserve_exact(n_pages - first_page) + .map_err(|_| Error::HostAllocation)?; + for p in first_page..n_pages { + let mut runs: [Vec; 4] = std::array::from_fn(|_| Vec::new()); + for (i, n) in PAGE_BYTES.into_iter().enumerate() { + runs[i] = zero_bytes(n)?; + if let Some(old) = prior.0.pages.get(p) { + runs[i].copy_from_slice(&old.runs[i]); + } + } + changed.push(runs); + } + let mut pos = zero_bytes(self.sizes[8])?; + let mut steps = zero_bytes(self.sizes[9])?; + for t in 0..input.rows { + let p = input.first + t; + for h in 0..24 { + pos[(t * 24 + h) * 4..(t * 24 + h + 1) * 4] + .copy_from_slice(&(p as i32).to_le_bytes()); + } + for (i, v) in [p, p + 1, (p + 1) / 4, p + 1].into_iter().enumerate() { + steps[(t * 4 + i) * 4..(t * 4 + i + 1) * 4] + .copy_from_slice(&(v as i32).to_le_bytes()); + } + } + // The real mixed producer supplies the rewind position. Restoring the + // longer prior's ring would keep future blocks after a shorter replay. + // This private prefix is bounded by that genuine prior, never caller-minted. + let replay_prior = if input.first == prior.0.end { + prior.clone() + } else { + MtpInt8Snapshot(Rc::new(Snapshot { + origin: prior.0.origin.clone(), + pages: prior.0.pages.clone(), + end: input.first, + checked: std::cell::Cell::new(prior.0.checked.get()), + })) + }; + self.restore(w, &replay_prior)?; + self.copy_from_physical(8, &pos)?; + self.copy_from_physical(9, &steps)?; + self.copy_from_physical(10, &[0; STATUS_WORDS * 4])?; + let mut commands = Vec::new(); + commands + .try_reserve_exact(32 + input.rows * 5) + .map_err(|_| Error::HostAllocation)?; + self.finite(&mut commands, mixed, input.rows * 2560, 0)?; + Self::push( + &mut commands, + 0, + 0, + [(input.rows * 2560).div_ceil(256) as u32, 1, 1], + [256, 1, 1], + vec![ + Arg::U64(mixed), + Arg::U64(self.address(5)?), + Arg::I32((input.rows * 2560) as i32), + ], + )?; + Self::push( + &mut commands, + 0, + 12, + [64, 1, 1], + [256, 1, 1], + vec![ + Arg::U64(self.address(5)?), + Arg::I32((input.rows * 80) as i32), + Arg::U64(self.sub(10, 4, 4)?), + ], + )?; + for (weight, out, status) in [(wk, 6, 2), (wv, 7, 3)] { + Self::push( + &mut commands, + 0, + input.rows, + [512, 1, 1], + [32, 4, 1], + vec![ + Arg::U64(weight), + Arg::U64(self.address(5)?), + Arg::U64(self.address(out)?), + Arg::I32(2560), + Arg::I32(512), + ], + )?; + self.finite(&mut commands, self.address(out)?, input.rows * 512, status)?; + } + for t in 0..input.rows { + let k = self.sub(6, t * 2048, 2048)?; + Self::push( + &mut commands, + 0, + 9, + [2, 1, 1], + [256, 1, 1], + vec![ + Arg::U64(k), + Arg::U64(gamma), + Arg::U64(k), + Arg::I32(256), + Arg::F32(1.0e-6), + ], + )?; + self.finite(&mut commands, k, 512, 4 + 2 * t)?; + Self::push( + &mut commands, + 0, + 10, + [1, 2, 1], + [128, 1, 1], + vec![ + Arg::U64(k), + Arg::U64(k), + Arg::I32(2), + Arg::I32(256), + Arg::F32(crate::qsa_index_ffi::theta()), + Arg::U64(self.sub(8, t * 96, 8)?), + ], + )?; + self.finite(&mut commands, k, 512, 5 + 2 * t)?; + } + // First failed upstream full scan/quant wins. No host/ring write before + // successful numeric admission of all real K/V rows. + self.execute(w, commands)?; + let flags = self.flags()?; + for (i, v) in flags.iter().enumerate().take(4 + 2 * input.rows) { + if *v != 0 { + return Err(if i == 1 { + Error::InvalidQ8Activation + } else { + Error::NonFiniteMmqOutput("mtp-kv-only") + }); + } + } + let mut append = Vec::new(); + append + .try_reserve_exact(input.rows * 2) + .map_err(|_| Error::HostAllocation)?; + let host = self.host_addresses()?; + for t in 0..input.rows { + Self::push( + &mut append, + 1, + 0, + [2, 4, 2], + [64, 1, 1], + vec![ + Arg::U64(self.address(0)?), + Arg::U64(self.address(1)?), + Arg::U64(self.address(2)?), + Arg::U64(self.address(3)?), + Arg::U64(self.address(4)?), + Arg::U64(self.sub(9, t * 16, 16)?), + Arg::U64(self.sub(6, t * 2048, 2048)?), + Arg::U64(self.sub(7, t * 2048, 2048)?), + Arg::I32(2), + Arg::I32(256), + Arg::I32(4), + Arg::U64(host[0]), + Arg::U64(host[1]), + Arg::U64(host[2]), + Arg::U64(host[3]), + ], + )?; + } + Self::push( + &mut append, + 1, + 3, + [64, 1, 1], + [256, 1, 1], + vec![ + Arg::U64(self.address(2)?), + Arg::U64(self.address(3)?), + Arg::I32((self.slots * 32) as i32), + Arg::U64(self.sub(10, (4 + 2 * self.max_t) * 4, 4)?), + ], + )?; + self.current = None; // source pages and resident ring mutate only after invalidation + self.execute(w, append)?; + if self.flags()?[4 + 2 * self.max_t] != 0 { + return Err(Error::NonFiniteMmqOutput("mtp-int8-scale")); + } + for (p, runs) in changed.iter_mut().enumerate() { + self.read_encoded_page(p + first_page, runs)?; + } + for runs in changed { + pages.push(Rc::new(Page { + runs: runs.map(Vec::into_boxed_slice), + })); + } + let snapshot = MtpInt8Snapshot(Rc::new(Snapshot { + origin: self.origin.clone(), + pages: Pages::from_vec(pages), + end, + checked: std::cell::Cell::new(false), + })); + self.current = Some(snapshot.clone()); + self.generation = generation; + Ok(CompletedMtpKvReplay { + owner: self, + snapshot, + _mixed: input, + _weights: weights, + first: input.first, + rows: input.rows, + }) + } +} diff --git a/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_5.rs b/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_5.rs new file mode 100644 index 00000000..e135fee0 --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_5.rs @@ -0,0 +1,137 @@ +//! Moved out of the parent module by STRA-338: impl MtpOriginalInt8 (5). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> MtpOriginalInt8<'ctx> { + /// Literal Original dense-window INT8 split-K attention. No selected index, + /// clock resolver, prompt MMA or F16 intermediate pool stands in for the ring. + pub fn attend<'loan, 'buffers>( + &'loan mut self, + w: &mut NativeBatchWorkspace<'ctx>, + snapshot: &'loan MtpInt8Snapshot, + position: usize, + query: &'loan MtpOriginalQuery<'loan, 'buffers>, + ) -> Result> { + self.validate_snapshot(snapshot)?; + w.validate_context(self.context)?; + if position >= snapshot.0.end { + return Err(Error::InvalidQwenShape); + } + // Snapshot may contain the whole verified suffix. Its ring's extra4*S+64 + // cells cover every legal earlier query in that same completed replay. + let b1 = snapshot.0.end.div_ceil(4); + let oldest = (position + 1).saturating_sub(MTP_ORIGINAL_WINDOW); + if oldest / 4 < b1.saturating_sub(self.slots) { + return Err(Error::InvalidQwenShape); + } + let q = self.external(w, query.query, 24576)?; + self.restore(w, snapshot)?; + self.copy_from_physical(10, &[0; STATUS_WORDS * 4])?; + let mut steps = [0u8; 16]; + for (i, v) in [position, position + 1, (position + 1) / 4, position + 1] + .into_iter() + .enumerate() + { + steps[i * 4..i * 4 + 4].copy_from_slice(&(v as i32).to_le_bytes()); + } + self.copy_from_physical(14, &steps)?; + let mut admission = Vec::new(); + self.finite(&mut admission, q, 6144, 0)?; + self.execute(w, admission)?; + if self.flags()?[0] != 0 { + return Err(Error::NonFiniteMmqOutput("mtp-query")); + } + let mut commands = Vec::new(); + commands + .try_reserve_exact(4) + .map_err(|_| Error::HostAllocation)?; + Self::push( + &mut commands, + 1, + 2, + [8, 1, 1], + [256, 1, 1], + vec![ + Arg::U64(self.address(14)?), + Arg::I32(32768), + Arg::U64(self.address(13)?), + Arg::I64(32768), + ], + )?; + let pa = self.address(12)?; + let pm = self.sub(12, CHUNKS * 24 * 256 * 4, CHUNKS * 24 * 4)?; + let pl = self.sub(12, CHUNKS * 24 * 257 * 4, CHUNKS * 24 * 4)?; + Self::push( + &mut commands, + 2, + 1, + [CHUNKS as u32, 2, 1], + [256, 1, 1], + vec![ + Arg::U64(q), + Arg::U64(self.address(0)?), + Arg::U64(self.address(1)?), + Arg::U64(self.address(2)?), + Arg::U64(self.address(3)?), + Arg::U64(self.address(4)?), + Arg::U64(self.address(13)?), + Arg::U64(self.address(14)?), + Arg::I32(2), + Arg::I32(4), + Arg::F32(1.0 / 16.0), + Arg::U64(pa), + Arg::U64(pm), + Arg::U64(pl), + Arg::I32(CHUNKS as i32), + Arg::I32(32768), + Arg::I64(SCRATCH_FLOATS as i64), + ], + )?; + Self::push( + &mut commands, + 2, + 2, + [24, 1, 1], + [256, 1, 1], + vec![ + Arg::U64(pa), + Arg::U64(pm), + Arg::U64(pl), + Arg::I32(CHUNKS as i32), + Arg::U64(self.address(11)?), + Arg::I64(SCRATCH_FLOATS as i64), + ], + )?; + self.finite(&mut commands, self.address(11)?, 6144, 1)?; + self.execute(w, commands)?; + if self.flags()?[1] != 0 { + return Err(Error::NonFiniteMmqOutput("mtp-int8-attention")); + } + Ok(CompletedMtpAttention { + owner: self, + _snapshot: snapshot, + _query: query, + }) + } + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + pub(in super::super) fn close_inner(&mut self) -> Result<()> { + self.failed = true; + self.current = None; + let Some(mut physical) = self.physical.take() else { + return Ok(()); + }; + physical.active.set(false); + // Explicit close requires graph retirement first. Dropping this logical + // ring never frees allocations retained by a real graph resource token. + if Rc::strong_count(&physical) != 1 { + return Err(Error::InvalidQwenShape); + } + Rc::get_mut(&mut physical) + .ok_or(Error::InvalidQwenShape)? + .close_inner() + } +} diff --git a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill.rs b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill.rs index d5137678..71d8ebfa 100644 --- a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill.rs +++ b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill.rs @@ -3,1178 +3,13 @@ #[allow(unused_imports)] use super::*; -impl<'ctx> OriginalMtpPrefill<'ctx> { - pub(super) fn new(context: &'ctx Context<'ctx>) -> Result { - let assets = [ - include_bytes!("../mtp_original_prefill.ptx").as_slice(), - include_bytes!("../mtp_original_prefill_embedding.ptx").as_slice(), - include_bytes!("../mtp_original_prefill_quant.ptx").as_slice(), - include_bytes!("../mtp_original_prefill_mmq.ptx").as_slice(), - include_bytes!("../mtp_original_prefill_fixup.ptx").as_slice(), - ]; - if assets - .iter() - .any(|a| a.windows(8).any(|w| w == b"UNSEALED")) - { - return Err(Error::UnsupportedQwenOperation); - } - let mut owner = Self { - context, - modules: std::array::from_fn(|_| None), - status: None, - tmp: None, - sms: 0, - shared_limit: 0, - failed: false, - }; - let result = (|| { - let g = context.enter()?; - let load = (|| { - owner.modules[0] = Some(Mod::load(assets[0], ENTRIES)?); - owner.modules[1] = Some(Mod::load(assets[1], &[c"mtp_prefill_native_embedding"])?); - owner.modules[2] = Some(Mod::load(assets[2], &[c"mtp_prefill_q8"])?); - owner.modules[3] = Some(Mod::load(assets[3], symbols::PROJECT)?); - owner.modules[4] = Some(Mod::load(assets[4], symbols::FIXUP)?); - let (sms, limit) = owner.module(0)?.info()?; - crate::arch_ptx::latch_stream_k_policy(); - owner.sms = sms; - owner.shared_limit = limit; - Ok(()) - })(); - let pop = g.finish(); - if pop.is_err() - || load.as_ref().is_err_and(|e| { - matches!(e, Error::Driver { .. } | Error::InvalidDriverValue(_)) - }) - { - owner.poison(); - } - combine(load, pop)?; - let charge = owner - .sms - .checked_mul(128 * 128 * 4) - .and_then(|n| n.checked_add(FLAG_WORDS * 4)) - .ok_or(Error::BudgetExceeded)?; - let required = charge - .checked_add(RESERVE_BYTES) - .ok_or(Error::BudgetExceeded)?; - if context - .allocated_bytes() - .checked_add(required) - .is_none_or(|n| n > context.budget_bytes()) - || context.memory_info()?.0 < required - { - return Err(Error::BudgetExceeded); - } - owner.status = Some(context.allocate(FLAG_WORDS * 4)?); - owner.tmp = Some(context.allocate(charge - FLAG_WORDS * 4)?); - Ok(()) - })(); - if let Err(e) = result { - return combine(Err(e), owner.close()); - } - Ok(owner) - } - pub fn allocated_bytes(&self) -> usize { - self.status.as_ref().map_or(0, DeviceBuffer::len) - + self.tmp.as_ref().map_or(0, DeviceBuffer::len) - } - pub fn is_failed(&self) -> bool { - self.failed || self.context.is_poisoned() - } - pub(super) fn poison(&mut self) { - self.failed = true; - self.context.poison(); - self.context.retain_driver(); - } - pub(super) fn module(&self, i: usize) -> Result<&Mod> { - self.modules - .get(i) - .and_then(Option::as_ref) - .ok_or(Error::ContextPoisoned) - } - pub(super) fn status(&self, i: usize) -> Result { - let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?; - b.handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(b.bytes, i * 4, 4) - } - pub(super) fn kernel( - cmds: &mut Vec, - asset: usize, - index: usize, - grid: [u32; 3], - block: [u32; 3], - shared: u32, - args: Vec, - ) -> Result<()> { - cmds.try_reserve(1).map_err(|_| Error::HostAllocation)?; - cmds.push(Cmd::Kernel { - asset, - index, - grid, - block, - shared, - args: Args::new(args)?, - }); - Ok(()) - } - pub(super) fn finite(&self, cmds: &mut Vec, data: u64, words: usize, stage: usize) -> Result<()> { - Self::kernel( - cmds, - 0, - 8, - [(words.div_ceil(256)) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(data), - A::I32(words as i32), - A::U64(self.status(stage)?.qwen_address()), - ], - ) - } - pub(super) fn weight( - &self, - rows: &OriginalPromptRows<'_, '_, '_>, - w: &NativeBatchWorkspace<'_>, - b: &DeviceBuffer<'_>, - bytes: usize, - ) -> Result { - if b.bytes != bytes || !std::ptr::eq(b.context, self.context) { - return Err(Error::InvalidProjectionShape); - } - let h = b.handle.ok_or(Error::ContextPoisoned)?; - h.validate_projection_extent(bytes, 2)?; - w.reject_alias(h, bytes)?; - let (region, n) = rows.draft_kv_region()?; - let (r, rn) = rows.common_span(OriginalPromptSpan::R)?; - for (a, len) in [ - (region, n), - (r, rn), - ( - self.status - .as_ref() - .ok_or(Error::ContextPoisoned)? - .handle - .ok_or(Error::ContextPoisoned)?, - FLAG_WORDS * 4, - ), - ( - self.tmp - .as_ref() - .ok_or(Error::ContextPoisoned)? - .handle - .ok_or(Error::ContextPoisoned)?, - self.sms * 128 * 128 * 4, - ), - ] { - if h.overlaps(bytes, a, len) { - return Err(Error::OutputAliasesInput); - } - } - Ok(h) - } - #[allow(clippy::too_many_arguments)] - pub(super) fn project( - &self, - cmds: &mut Vec, - r: &Region, - x: u64, - w: u64, - y: u64, - rows: usize, - out: usize, - bound_slot: usize, - stage: usize, - ) -> Result<()> { - if rows == 0 || rows > r.b * 4 || !matches!(out, 512 | 2560) { - return Err(Error::InvalidProjectionShape); - } - let mut best = None; - let mut ntx = usize::MAX; - for (i, j) in WIDTHS.into_iter().enumerate() { - if ntx <= 1 { - break; - } - let shared = 128 * 76 * 4 + j * 4 + (j * 144).div_ceil(1024) * 1024; - if shared > self.shared_limit as usize { - continue; - } - if rows.div_ceil(j) < ntx { - best = Some((i, j, shared)); - ntx = rows.div_ceil(j); - } - } - let (index, j, shared) = best.ok_or(Error::UnsupportedProjection)?; - let tiles = (out / 128) * ntx; - let efficiency = 100 * tiles / (self.sms * tiles.div_ceil(self.sms)); - let grid = if efficiency >= 90 || crate::arch_ptx::stream_k_off() { tiles } else { self.sms }; - let fix = !tiles.is_multiple_of(grid); - if tiles.checked_mul(80).is_none_or(|n| n >= 1 << 30) { - return Err(Error::InvalidProjectionShape); - } - let xq = r.address(17, q8_bytes(rows)?)?; - let ids = r.address(18, rows * 4)?; - let bound = r - .handle(19, 16)? - .checked_subspan(16, bound_slot * 8, 8)? - .qwen_address(); - Self::kernel( - cmds, - 2, - 0, - [rows as u32, 5, 1], - [128, 1, 1], - 0, - vec![ - A::U64(x), - A::U64(0), - A::U64(xq), - A::I64(2560), - A::I64(2560), - A::I64((rows * 2560) as i64), - A::I64((rows * 2560) as i64), - A::I64(2560), - A::I32(rows as i32), - A::I32(1), - A::I32(1), - ], - )?; - // Original D4 data includes a fixed128-block tail. Initialize that exact - // tail before a literal vendor kernel can speculatively load it. - Self::kernel( - cmds, - 0, - 11, - [72, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(xq + (rows * 20 * 144) as u64), - A::I32((128 * 144) as i32), - ], - )?; - Self::kernel( - cmds, - 0, - 16, - [(rows * 20).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(xq), - A::I32((rows * 20) as i32), - A::U64(self.status(stage)?.qwen_address()), - ], - )?; - let tmp = if fix { - self.tmp - .as_ref() - .ok_or(Error::ContextPoisoned)? - .handle - .ok_or(Error::ContextPoisoned)? - .qwen_address() - } else { - 0 - }; - let fd = fastdiv; - Self::kernel( - cmds, - 3, - index, - [grid as u32, 1, 1], - [32, 8, 1], - shared as u32, - vec![ - A::U64(w), - A::U64(xq), - A::U64(ids), - A::U64(bound), - A::U64(y), - A::U64(tmp), - A::U64(0), - A::U3(fd(80)), - A::I32(out as i32), - A::I32(rows as i32), - A::I32(80), - A::I32(rows as i32), - A::I32(out as i32), - A::U3(fd(1)), - A::U3(fd(1)), - A::I32((out * 80) as i32), - A::I32(0), - A::I32(0), - A::U3(fd(1)), - A::U3(fd(1)), - A::I32(0), - A::I32(0), - A::I32(0), - A::U3(fd(ntx as u32)), - ], - )?; - if fix { - Self::kernel( - cmds, - 4, - index, - [grid as u32, 4, 1], - [32, 4, 1], - 0, - vec![ - A::U64(ids), - A::U64(bound), - A::U64(y), - A::U64(tmp), - A::U3(fd(80)), - A::I32(out as i32), - A::I32(rows as i32), - A::I32(out as i32), - A::U3(fd(1)), - A::I32(0), - A::U3(fd(1)), - A::I32(0), - A::U3(fd(ntx as u32)), - ], - )?; - } - Ok(()) - } - pub(super) fn run( - &mut self, - rows: &mut OriginalPromptRows<'_, '_, '_>, - w: &mut NativeBatchWorkspace<'ctx>, - mut cmds: Vec, - staging: Vec<(BufferHandle, Vec)>, - ) -> Result<()> { - let mut readback = zero_bytes(FLAG_WORDS * 4)?; - let zero = zero_bytes(FLAG_WORDS * 4)?; - let status = self - .status - .as_ref() - .ok_or(Error::ContextPoisoned)? - .handle - .ok_or(Error::ContextPoisoned)?; - status.validate_projection_extent(FLAG_WORDS * 4, 4)?; - for i in 0..5 { - self.module(i)?; - } - let blas = w.blas()?; - let g = match self.context.enter() { - Ok(g) => g, - Err(e) => { - self.poison(); - rows.mark_failed(); - w.mark_failed(); - return Err(e); - } - }; - let mut operation = self.context.driver.api.copy_from(status, &zero); - if operation.is_ok() { - for (dst, bytes) in &staging { - if let Err(e) = self.context.driver.api.copy_from(*dst, bytes) { - operation = Err(e); - break; - } - } - } - if operation.is_ok() { - operation = self.context.driver.api.synchronize(); - } - if operation.is_ok() { - for c in &mut cmds { - let r = match c { - Cmd::Kernel { - asset, - index, - grid, - block, - shared, - args, - } => self.modules[*asset] - .as_ref() - .map_or(Err(Error::ContextPoisoned), |m| { - m.launch(*index, *grid, *block, *shared, blas.stream(), args) - }), - Cmd::Copy { dst, src, bytes } => self.modules[0] - .as_ref() - .map_or(Err(Error::ContextPoisoned), |m| { - m.copy(*dst, *src, *bytes, blas.stream()) - }), - Cmd::Gemm { - x, - w, - y, - rows, - n, - k, - alpha, - beta, - } => blas.gemm_bf16(*x, *w, *y, *rows, *n, *k, alpha, beta), - }; - if let Err(e) = r { - operation = Err(e); - break; - } - } - } - let stream = blas.synchronize(); - if operation.is_ok() && stream.is_ok() { - operation = self.context.driver.api.copy_to(status, &mut readback); - } - let device = self.context.driver.api.synchronize(); - let pop = g.finish(); - if operation.is_err() || stream.is_err() || device.is_err() || pop.is_err() { - self.poison(); - rows.mark_failed(); - w.mark_failed(); - } - if stream.is_err() || device.is_err() || pop.is_err() { - std::mem::forget((cmds, staging, zero, readback)); - self.context.retain_driver(); - return combine(combine(combine(operation, stream), device), pop); - } - combine(combine(combine(operation, stream), device), pop)?; - for word in readback.chunks_exact(4) { - if u32::from_le_bytes(word.try_into().map_err(|_| Error::InvalidSize)?) > 1 { - self.poison(); - return Err(Error::InvalidDriverValue("draft prefill status")); - } - } - for (stage, word) in readback.chunks_exact(4).enumerate() { - if u32::from_le_bytes(word.try_into().map_err(|_| Error::InvalidSize)?) != 0 { - return Err(Error::NonFiniteMmqOutput(match stage { - 0 => "MTP embedding", - 1 => "MTP embedding norm", - 2 => "MTP FC embedding", - 3 => "MTP hidden norm", - 4 => "MTP FC hidden", - 5 => "MTP broadcast", - 6 => "MTP GR normalized", - 7 => "MTP GR down", - 8 => "MTP GR SiLU", - 9 => "MTP GR up", - 10 => "MTP GR mixed", - 11 => "MTP K", - 12 => "MTP V", - 13 => "MTP K norm", - 14 => "MTP K Rope", - _ => "MTP INT8 encoded", - })); - } - } - Ok(()) - } - #[allow(clippy::too_many_arguments)] - pub fn record<'arena, 'loan>( - &mut self, - residual: &mut OriginalDeviceResidual<'arena, 'loan, 'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - tokens: &[i32], - cell0: usize, - first_needed: usize, - weights: OriginalMtpPrefillWeights<'_, '_>, - embedding: OriginalMtpEmbedding<'_, '_>, - policy: &DraftKvPolicy, - mut cancelled: impl FnMut() -> bool, - ) -> Result { - if policy.disabled { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::Disabled)); - } - if tokens.is_empty() { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::Empty)); - } - if policy.mode != 0 || policy.hybrid || policy.rotated || policy.q4 { - return Ok(DraftKvOutcome::Fallback( - DraftKvFallback::UnsupportedStorage, - )); - } - if policy.alternate_f16 { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::AlternateF16)); - } - if policy.rope_table_enabled || policy.multimodal_positions { - return Ok(DraftKvOutcome::Fallback( - DraftKvFallback::UnsupportedRopeTable, - )); - } - if [ - policy.theta_scale, - policy.freq_scale, - policy.corr_low, - policy.corr_high, - policy.ext_factor, - policy.mscale, - ] - .iter() - .any(|x| !x.is_finite()) - || policy.theta_scale <= 0.0 - || policy.freq_scale <= 0.0 - || policy.mscale <= 0.0 - { - return Err(Error::InvalidProjectionShape); - } - ring.validate_snapshot(prior)?; - workspace.validate_context(self.context)?; - ring.validate_context(self.context)?; - if self.is_failed() - || !residual.context_matches(self.context) - || tokens.len() != residual.rows() - || tokens.len() > 8192 - || cell0 - .checked_add(tokens.len()) - .is_none_or(|n| n > MTP_ORIGINAL_MAX_CELLS) - { - return Err(Error::InvalidProjectionShape); - } - if tokens - .iter() - .any(|t| *t < 0 || *t as usize >= embedding.vocab()) - { - return Err(Error::InvalidProjectionShape); - } - let r0 = first_needed.saturating_sub(cell0); - if r0 >= tokens.len() { - return Ok(DraftKvOutcome::Skipped); - } - let rows = residual.lease_mut(); - let (region, region_bytes) = rows.draft_kv_region()?; - let Some(r) = Region::new(region, region_bytes, tokens.len(), r0)? else { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::RegionTooSmall)); - }; - crate::bringup_trace!("DBG prefill.record: region ok b={} tokens={} r0={r0}", r.b, tokens.len()); - if !WIDTHS.into_iter().any(|j| { - 128 * 76 * 4 + j * 4 + (j * 144).div_ceil(1024) * 1024 <= self.shared_limit as usize - }) { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::NoQ8Tile)); - } - let weight_refs = [ - weights.embedding_norm, - weights.embedding_fc, - weights.hidden_norm, - weights.hidden_fc, - weights.gr_norm, - weights.gr_down, - weights.gr_up, - weights.key, - weights.value, - weights.key_norm, - ]; - let extents = [ - 10240, - 2560 * 80 * 34, - 40960, - 2560 * 80 * 34, - 40960, - 320 * 10240 * 2, - 10240 * 320 * 2, - 512 * 80 * 34, - 512 * 80 * 34, - 1024, - ]; - let mut wh = [region; 10]; - for i in 0..10 { - wh[i] = self.weight(rows, workspace, weight_refs[i], extents[i]).map_err(|e| { crate::bringup_trace!("DBG prefill.record: weight {i} err {e:?}"); e })?; - } - crate::bringup_trace!("DBG prefill.record: 10 weights staged"); - let eh = self.weight(rows, workspace, embedding.table, embedding.table.bytes).map_err(|e| { crate::bringup_trace!("DBG prefill.record: embedding table err {e:?}"); e })?; - crate::bringup_trace!("DBG prefill.record: embedding table staged"); - for (i, a) in weight_refs.iter().enumerate() { - for b in weight_refs.iter().take(i) { - let ah = a.handle.ok_or_else(|| { crate::bringup_trace!("DBG prefill.record: weight_ref a.handle is None (i={i})"); Error::ContextPoisoned })?; - let bh = b.handle.ok_or_else(|| { crate::bringup_trace!("DBG prefill.record: weight_ref b.handle is None (i={i})"); Error::ContextPoisoned })?; - if ah.overlaps(a.bytes, bh, b.bytes) - && !(ah.qwen_address() == bh.qwen_address() && a.bytes == b.bytes) - { - return Err(Error::OutputAliasesInput); - } - } - } - for b in weight_refs { - let h = b.handle.ok_or_else(|| { crate::bringup_trace!("DBG prefill.record: weight b.handle is None (embedding overlap)"); Error::ContextPoisoned })?; - if eh.overlaps(embedding.table.bytes, h, b.bytes) - && !(eh.qwen_address() == h.qwen_address() && embedding.table.bytes == b.bytes) - { - return Err(Error::OutputAliasesInput); - } - } - // Actual input residual lies outside the region being overwritten. - let (rh, rbytes) = rows.common_span(OriginalPromptSpan::R).map_err(|e| { crate::bringup_trace!("DBG prefill.record: common_span(R) err {e:?}"); e })?; - crate::bringup_trace!("DBG prefill.record: weights vs embedding overlap ok, R span ok"); - if rh.overlaps(rbytes, region, region_bytes) { - return Err(Error::OutputAliasesInput); - } - // The serve ring is built from prepared spans of the drafter's shared region, so buffers 0..5 are not - // separately owned DeviceBuffers; compare by address (ring.address works for both layouts). - for i in 0..5 { - let hv = ring.address(i)?; - let n = ring.sizes[i]; - let ov = |o: u64, on: usize| hv < o.saturating_add(on as u64) && o < hv.saturating_add(n as u64); - if ov(region.qwen_address(), region_bytes) - || ov(rh.qwen_address(), rbytes) - || wh.iter().zip(extents).any(|(w, n2)| ov(w.qwen_address(), n2)) - || ov(eh.qwen_address(), embedding.table.bytes) - { - return Err(Error::OutputAliasesInput); - } - } - crate::bringup_trace!("DBG prefill.record: overlap checks ok"); - let generation = ring - .generation - .checked_add(1) - .ok_or(Error::InvalidQwenShape)?; - let end = cell0 + tokens.len(); - let first = cell0 + r0; - let first_page = first / 4; - let page_count = end.div_ceil(4); - let mut pages = Vec::new(); - pages - .try_reserve_exact(page_count) - .map_err(|_| Error::HostAllocation)?; - let mut changed = Vec::new(); - changed - .try_reserve_exact(page_count - first_page) - .map_err(|_| Error::HostAllocation)?; - for p in 0..page_count { - if p < first_page { - if let Some(page) = prior.0.pages.get(p) { - pages.push(page.clone()); - continue; - } - } - let mut runs: [Vec; 4] = std::array::from_fn(|_| Vec::new()); - for (i, n) in PAGE_BYTES.into_iter().enumerate() { - runs[i] = zero_bytes(n)?; - } - if p < first_page { - pages.push(Rc::new(Page { - runs: runs.map(Vec::into_boxed_slice), - })); - } else { - changed.push(runs); - } - } - if cancelled() { - return Ok(DraftKvOutcome::Cancelled); - } - // Genuine idle dependency before this stream can mutate the real drafter KV. - crate::bringup_trace!("DBG prefill.record: pages ready, ring.execute(idle)"); - ring.execute(workspace, Vec::new()).map_err(|e| { crate::bringup_trace!("DBG prefill.record: ring.execute err {e:?}"); e })?; // genuine global + shared drafter stream idle, even identical snapshot - ring.restore(workspace, prior).map_err(|e| { crate::bringup_trace!("DBG prefill.record: ring.restore err {e:?}"); e })?; - crate::bringup_trace!("DBG prefill.record: ring restored"); - ring.current = None; - for b0 in (r0..tokens.len()).step_by(r.b) { - let nb = r.b.min(tokens.len() - b0); - let c0 = cell0 + b0; - crate::bringup_trace!("DBG prefill.record: block b0={b0} nb={nb} c0={c0}"); - if cancelled() { - return Ok(DraftKvOutcome::Cancelled); - } - let mut commands = Vec::new(); - commands - .try_reserve_exact(80) - .map_err(|_| Error::HostAllocation)?; - let mut tk = zero_bytes(nb * 4)?; - for (dst, t) in tk.chunks_exact_mut(4).zip(&tokens[b0..b0 + nb]) { - dst.copy_from_slice(&t.to_le_bytes()); - } - let mut bounds = zero_bytes(16)?; - for (dst, v) in bounds - .chunks_exact_mut(4) - .zip([0, nb as i32, 0, (nb * 4) as i32]) - { - dst.copy_from_slice(&v.to_le_bytes()); - } - Self::kernel( - &mut commands, - 0, - 9, - [(nb * 4).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![A::U64(r.address(18, nb * 16)?), A::I32((nb * 4) as i32)], - )?; - let emb = r.address(0, nb * 10240)?; - let tok = r.address(16, nb * 4)?; - match embedding.kind { - EmbeddingKind::Native { - kind, row_bytes, .. - } => Self::kernel( - &mut commands, - 1, - 0, - [10, nb as u32, 1], - [32, 1, 1], - 0, - vec![ - A::I32(kind), - A::U64(eh.qwen_address()), - A::U64(row_bytes as u64), - A::U64(tok), - A::I64(2560), - A::U64(emb), - ], - )?, - EmbeddingKind::Compressed { - bits, - bias, - group, - codes, - scales, - offsets, - .. - } => Self::kernel( - &mut commands, - 0, - 5, - [10, nb as u32, 1], - [256, 1, 1], - 0, - vec![ - A::U64(eh.qwen_address()), - A::U64(eh.qwen_address() + codes as u64), - A::U64(if offsets { - eh.qwen_address() + (codes + scales) as u64 - } else { - 0 - }), - A::U64(tok), - A::I64(2560), - A::I32(bits), - A::I32(bias), - A::I32(group as i32), - A::U64((2560 / (8 / bits)) as u64), - A::U64((2560 / group) as u64), - A::U64(emb), - ], - )?, - } - self.finite(&mut commands, emb, nb * 2560, 0)?; - Self::kernel( - &mut commands, - 0, - 0, - [nb as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(emb), - A::U64(wh[0].qwen_address()), - A::I64(2560), - A::I64(2560), - A::F32(1e-6), - ], - )?; - self.finite(&mut commands, emb, nb * 2560, 1)?; - let e2 = r.address(1, nb * 10240)?; - self.project( - &mut commands, - &r, - emb, - wh[1].qwen_address(), - e2, - nb, - 2560, - 0, - 2, - )?; - self.finite(&mut commands, e2, nb * 2560, 2)?; - let hn = r.address(3, nb * 40960)?; - let h2 = r.address(4, nb * 40960)?; - commands.push(Cmd::Copy { - dst: hn, - src: rh - .checked_subspan(rbytes, b0 * 40960, nb * 40960)? - .qwen_address(), - bytes: nb * 40960, - }); - Self::kernel( - &mut commands, - 0, - 0, - [nb as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(hn), - A::U64(wh[2].qwen_address()), - A::I64(10240), - A::I64(10240), - A::F32(1e-6), - ], - )?; - self.finite(&mut commands, hn, nb * 10240, 3)?; - self.project( - &mut commands, - &r, - hn, - wh[3].qwen_address(), - h2, - nb * 4, - 2560, - 1, - 4, - )?; - self.finite(&mut commands, h2, nb * 10240, 4)?; - let rm = r.address(5, nb * 40960)?; - let gated = r.address(6, nb * 40960)?; - let xn = r.address(8, nb * 20480)?; - let lo = r.address(9, nb * 1280)?; - let lo16 = r.address(10, nb * 640)?; - let grs = r.address(11, nb * 16)?; - let mixed = r.address(12, nb * 10240)?; - let mixedh = r.address(13, nb * 5120)?; - Self::kernel( - &mut commands, - 0, - 4, - [40, nb as u32, 1], - [256, 1, 1], - 0, - vec![A::U64(h2), A::U64(e2), A::U64(rm), A::I64(2560), A::I32(4)], - )?; - self.finite(&mut commands, rm, nb * 10240, 5)?; - Self::kernel( - &mut commands, - 0, - 1, - [(nb * 4) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(rm), - A::U64(wh[4].qwen_address()), - A::F32(1e-6), - A::U64(grs), - A::U64(xn), - A::U64(0), - ], - )?; - self.finite(&mut commands, grs, nb * 4, 6)?; - Self::kernel( - &mut commands, - 0, - 12, - [(nb * 10240).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(rm), - A::U64(grs), - A::U64(wh[4].qwen_address()), - A::U64(self.status(6)?.qwen_address()), - A::I64(nb as i64), - ], - )?; - Self::kernel( - &mut commands, - 0, - 14, - [(nb * 10240).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(xn), - A::I32((nb * 10240) as i32), - A::U64(self.status(6)?.qwen_address()), - ], - )?; - commands.push(Cmd::Gemm { - x: r.handle(8, nb * 20480)?, - w: wh[5], - y: r.handle(9, nb * 1280)?, - rows: nb as i32, - n: 320, - k: 10240, - alpha: 1.0, - beta: 0.0, - }); - self.finite(&mut commands, lo, nb * 320, 7)?; - Self::kernel( - &mut commands, - 0, - 2, - [(nb * 320).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(lo), - A::U64(lo16), - A::U64(0), - A::I64((nb * 320) as i64), - ], - )?; - Self::kernel( - &mut commands, - 0, - 13, - [(nb * 320).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(lo), - A::U64(self.status(8)?.qwen_address()), - A::I64(nb as i64), - ], - )?; - Self::kernel( - &mut commands, - 0, - 14, - [(nb * 320).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(lo16), - A::I32((nb * 320) as i32), - A::U64(self.status(8)?.qwen_address()), - ], - )?; - commands.push(Cmd::Gemm { - x: r.handle(10, nb * 640)?, - w: wh[6], - y: r.handle(6, nb * 40960)?, - rows: nb as i32, - n: 10240, - k: 320, - alpha: 1.0, - beta: 0.0, - }); - self.finite(&mut commands, gated, nb * 10240, 9)?; - Self::kernel( - &mut commands, - 0, - 3, - [(nb * 2560).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(rm), - A::U64(grs), - A::U64(wh[4].qwen_address()), - A::U64(gated), - A::U64(mixed), - A::U64(0), - A::I64(nb as i64), - A::U64(mixedh), - A::U64(0), - ], - )?; - Self::kernel( - &mut commands, - 0, - 15, - [(nb * 10240).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(rm), - A::U64(grs), - A::U64(wh[4].qwen_address()), - A::U64(gated), - A::U64(self.status(10)?.qwen_address()), - A::I64(nb as i64), - ], - )?; - self.finite(&mut commands, mixed, nb * 2560, 10)?; - let kc = r.address(14, nb * 2048)?; - let vc = r.address(15, nb * 2048)?; - self.project( - &mut commands, - &r, - mixed, - wh[7].qwen_address(), - kc, - nb, - 512, - 0, - 11, - )?; - self.finite(&mut commands, kc, nb * 512, 11)?; - self.project( - &mut commands, - &r, - mixed, - wh[8].qwen_address(), - vc, - nb, - 512, - 0, - 12, - )?; - self.finite(&mut commands, vc, nb * 512, 12)?; - Self::kernel( - &mut commands, - 0, - 0, - [(nb * 2) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(kc), - A::U64(wh[9].qwen_address()), - A::I64(256), - A::I64(256), - A::F32(1e-6), - ], - )?; - self.finite(&mut commands, kc, nb * 512, 13)?; - Self::kernel( - &mut commands, - 0, - 6, - [(nb * 2) as u32, 1, 1], - [32, 1, 1], - 0, - vec![ - A::U64(kc), - A::I64(2), - A::I64(256), - A::I64(512), - A::I64(c0 as i64), - A::F32(policy.theta_scale), - A::F32(policy.freq_scale), - A::F32(policy.corr_low), - A::F32(policy.corr_high), - A::F32(policy.ext_factor), - A::F32(policy.mscale), - A::U64(0), - A::Words3([0; 3]), - ], - )?; - self.finite(&mut commands, kc, nb * 512, 14)?; - self.run( - rows, - workspace, - commands, - vec![(r.handle(16, nb * 4)?, tk), (r.handle(19, 16)?, bounds)], - )?; - if cancelled() { - return Ok(DraftKvOutcome::Cancelled); - } - let mapped = ring.mapped()?; - let mut host = [0u64; 8]; - for (i, n) in HOST_RUNS.into_iter().enumerate() { - host[i + 2] = mapped.address(HOST_OFFSETS[i], n)?; - } - let mut append = Vec::new(); - append - .try_reserve_exact(2) - .map_err(|_| Error::HostAllocation)?; - Self::kernel( - &mut append, - 0, - 7, - [nb as u32, 2, 8], - [64, 1, 1], - 0, - vec![ - A::U64(kc), - A::U64(vc), - A::I64(c0 as i64), - A::U64(ring.address(4)?), - A::I64(4), - A::U64(0), - A::U64(0), - A::U64(ring.address(0)?), - A::U64(ring.address(1)?), - A::U64(ring.address(2)?), - A::U64(ring.address(3)?), - A::Words8(host), - A::Words8([0; 8]), - ], - )?; - Self::kernel( - &mut append, - 0, - 10, - [64, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(ring.address(2)?), - A::U64(ring.address(3)?), - A::U64(ring.address(4)?), - A::I64(c0 as i64), - A::I32(nb as i32), - A::U64(self.status(15)?.qwen_address()), - ], - )?; - self.run(rows, workspace, append, Vec::new())?; - if cancelled() { - return Ok(DraftKvOutcome::Cancelled); - } - } - let mapped = ring.mapped()?; - for (p, runs) in changed.iter_mut().enumerate() { - for (i, n) in PAGE_BYTES.into_iter().enumerate() { - mapped.read_into(HOST_OFFSETS[i] + (first_page + p) * n, &mut runs[i])?; - } - } - drop(mapped); - for runs in changed { - pages.push(Rc::new(Page { - runs: runs.map(Vec::into_boxed_slice), - })); - } - let snapshot = MtpInt8Snapshot(Rc::new(Snapshot { - origin: ring.origin.clone(), - pages: Pages::from_vec(pages), - end, - checked: std::cell::Cell::new(false), - })); - ring.current = Some(snapshot.clone()); - ring.generation = generation; - Ok(DraftKvOutcome::Completed(CompletedDraftKv { - snapshot, - first_materialized: first, - end, - generation, - })) - } - pub fn close(mut self) -> Result<()> { - self.close_inner() - } - pub(super) fn close_inner(&mut self) -> Result<()> { - self.failed = true; - let mut first = Ok(()); - for module in &mut self.modules { - if let Some(m) = module.take() { - let r = if self.context.is_poisoned() { - std::mem::forget(m); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(g) => combine(m.close(), g.finish()), - Err(e) => { - self.context.poison(); - std::mem::forget(m); - Err(e) - } - } - }; - if r.is_err() { - self.context.poison(); - self.context.retain_driver(); - } - first = combine(first, r); - } - } - for b in [&mut self.status, &mut self.tmp] { - if let Some(b) = b.take() { - let r = if self.context.is_poisoned() { - std::mem::forget(b); - Err(Error::ContextPoisoned) - } else { - b.release() - }; - first = combine(first, r); - } - } - if self.context.is_poisoned() { - self.context.retain_driver(); - } - first - } -} +#[path = "impl_originalmtpprefill/impl_originalmtpprefill_2.rs"] +mod impl_originalmtpprefill_2; +#[path = "impl_originalmtpprefill/impl_originalmtpprefill_2_2.rs"] +mod impl_originalmtpprefill_2_2; +#[path = "impl_originalmtpprefill/impl_originalmtpprefill_3.rs"] +mod impl_originalmtpprefill_3; +#[path = "impl_originalmtpprefill/impl_originalmtpprefill_4.rs"] +mod impl_originalmtpprefill_4; +#[path = "impl_originalmtpprefill/impl_originalmtpprefill_5.rs"] +mod impl_originalmtpprefill_5; diff --git a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_2.rs b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_2.rs new file mode 100644 index 00000000..ee96b281 --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_2.rs @@ -0,0 +1,179 @@ +//! Moved out of the parent module by STRA-338: impl OriginalMtpPrefill. + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalMtpPrefill<'ctx> { + pub(in super::super) fn new(context: &'ctx Context<'ctx>) -> Result { + let assets = [ + include_bytes!("../../mtp_original_prefill.ptx").as_slice(), + include_bytes!("../../mtp_original_prefill_embedding.ptx").as_slice(), + include_bytes!("../../mtp_original_prefill_quant.ptx").as_slice(), + include_bytes!("../../mtp_original_prefill_mmq.ptx").as_slice(), + include_bytes!("../../mtp_original_prefill_fixup.ptx").as_slice(), + ]; + if assets + .iter() + .any(|a| a.windows(8).any(|w| w == b"UNSEALED")) + { + return Err(Error::UnsupportedQwenOperation); + } + let mut owner = Self { + context, + modules: std::array::from_fn(|_| None), + status: None, + tmp: None, + sms: 0, + shared_limit: 0, + failed: false, + }; + let result = (|| { + let g = context.enter()?; + let load = (|| { + owner.modules[0] = Some(Mod::load(assets[0], ENTRIES)?); + owner.modules[1] = Some(Mod::load(assets[1], &[c"mtp_prefill_native_embedding"])?); + owner.modules[2] = Some(Mod::load(assets[2], &[c"mtp_prefill_q8"])?); + owner.modules[3] = Some(Mod::load(assets[3], symbols::PROJECT)?); + owner.modules[4] = Some(Mod::load(assets[4], symbols::FIXUP)?); + let (sms, limit) = owner.module(0)?.info()?; + crate::arch_ptx::latch_stream_k_policy(); + owner.sms = sms; + owner.shared_limit = limit; + Ok(()) + })(); + let pop = g.finish(); + if pop.is_err() + || load.as_ref().is_err_and(|e| { + matches!(e, Error::Driver { .. } | Error::InvalidDriverValue(_)) + }) + { + owner.poison(); + } + combine(load, pop)?; + let charge = owner + .sms + .checked_mul(128 * 128 * 4) + .and_then(|n| n.checked_add(FLAG_WORDS * 4)) + .ok_or(Error::BudgetExceeded)?; + let required = charge + .checked_add(RESERVE_BYTES) + .ok_or(Error::BudgetExceeded)?; + if context + .allocated_bytes() + .checked_add(required) + .is_none_or(|n| n > context.budget_bytes()) + || context.memory_info()?.0 < required + { + return Err(Error::BudgetExceeded); + } + owner.status = Some(context.allocate(FLAG_WORDS * 4)?); + owner.tmp = Some(context.allocate(charge - FLAG_WORDS * 4)?); + Ok(()) + })(); + if let Err(e) = result { + return combine(Err(e), owner.close()); + } + Ok(owner) + } + pub fn allocated_bytes(&self) -> usize { + self.status.as_ref().map_or(0, DeviceBuffer::len) + + self.tmp.as_ref().map_or(0, DeviceBuffer::len) + } + pub fn is_failed(&self) -> bool { + self.failed || self.context.is_poisoned() + } + pub(in super::super) fn poison(&mut self) { + self.failed = true; + self.context.poison(); + self.context.retain_driver(); + } + pub(in super::super) fn module(&self, i: usize) -> Result<&Mod> { + self.modules + .get(i) + .and_then(Option::as_ref) + .ok_or(Error::ContextPoisoned) + } + pub(in super::super) fn status(&self, i: usize) -> Result { + let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?; + b.handle + .ok_or(Error::ContextPoisoned)? + .checked_subspan(b.bytes, i * 4, 4) + } + pub(in super::super) fn kernel( + cmds: &mut Vec, + asset: usize, + index: usize, + grid: [u32; 3], + block: [u32; 3], + shared: u32, + args: Vec, + ) -> Result<()> { + cmds.try_reserve(1).map_err(|_| Error::HostAllocation)?; + cmds.push(Cmd::Kernel { + asset, + index, + grid, + block, + shared, + args: Args::new(args)?, + }); + Ok(()) + } + pub(in super::super) fn finite(&self, cmds: &mut Vec, data: u64, words: usize, stage: usize) -> Result<()> { + Self::kernel( + cmds, + 0, + 8, + [(words.div_ceil(256)) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(data), + A::I32(words as i32), + A::U64(self.status(stage)?.qwen_address()), + ], + ) + } + pub(in super::super) fn weight( + &self, + rows: &OriginalPromptRows<'_, '_, '_>, + w: &NativeBatchWorkspace<'_>, + b: &DeviceBuffer<'_>, + bytes: usize, + ) -> Result { + if b.bytes != bytes || !std::ptr::eq(b.context, self.context) { + return Err(Error::InvalidProjectionShape); + } + let h = b.handle.ok_or(Error::ContextPoisoned)?; + h.validate_projection_extent(bytes, 2)?; + w.reject_alias(h, bytes)?; + let (region, n) = rows.draft_kv_region()?; + let (r, rn) = rows.common_span(OriginalPromptSpan::R)?; + for (a, len) in [ + (region, n), + (r, rn), + ( + self.status + .as_ref() + .ok_or(Error::ContextPoisoned)? + .handle + .ok_or(Error::ContextPoisoned)?, + FLAG_WORDS * 4, + ), + ( + self.tmp + .as_ref() + .ok_or(Error::ContextPoisoned)? + .handle + .ok_or(Error::ContextPoisoned)?, + self.sms * 128 * 128 * 4, + ), + ] { + if h.overlaps(bytes, a, len) { + return Err(Error::OutputAliasesInput); + } + } + Ok(h) + } +} diff --git a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_2_2.rs b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_2_2.rs new file mode 100644 index 00000000..5c17093a --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_2_2.rs @@ -0,0 +1,173 @@ +//! Moved out of the parent module by STRA-338: impl OriginalMtpPrefill (2). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalMtpPrefill<'ctx> { + #[allow(clippy::too_many_arguments)] + pub(in super::super) fn project( + &self, + cmds: &mut Vec, + r: &Region, + x: u64, + w: u64, + y: u64, + rows: usize, + out: usize, + bound_slot: usize, + stage: usize, + ) -> Result<()> { + if rows == 0 || rows > r.b * 4 || !matches!(out, 512 | 2560) { + return Err(Error::InvalidProjectionShape); + } + let mut best = None; + let mut ntx = usize::MAX; + for (i, j) in WIDTHS.into_iter().enumerate() { + if ntx <= 1 { + break; + } + let shared = 128 * 76 * 4 + j * 4 + (j * 144).div_ceil(1024) * 1024; + if shared > self.shared_limit as usize { + continue; + } + if rows.div_ceil(j) < ntx { + best = Some((i, j, shared)); + ntx = rows.div_ceil(j); + } + } + let (index, j, shared) = best.ok_or(Error::UnsupportedProjection)?; + let tiles = (out / 128) * ntx; + let efficiency = 100 * tiles / (self.sms * tiles.div_ceil(self.sms)); + let grid = if efficiency >= 90 || crate::arch_ptx::stream_k_off() { tiles } else { self.sms }; + let fix = !tiles.is_multiple_of(grid); + if tiles.checked_mul(80).is_none_or(|n| n >= 1 << 30) { + return Err(Error::InvalidProjectionShape); + } + let xq = r.address(17, q8_bytes(rows)?)?; + let ids = r.address(18, rows * 4)?; + let bound = r + .handle(19, 16)? + .checked_subspan(16, bound_slot * 8, 8)? + .qwen_address(); + Self::kernel( + cmds, + 2, + 0, + [rows as u32, 5, 1], + [128, 1, 1], + 0, + vec![ + A::U64(x), + A::U64(0), + A::U64(xq), + A::I64(2560), + A::I64(2560), + A::I64((rows * 2560) as i64), + A::I64((rows * 2560) as i64), + A::I64(2560), + A::I32(rows as i32), + A::I32(1), + A::I32(1), + ], + )?; + // Original D4 data includes a fixed128-block tail. Initialize that exact + // tail before a literal vendor kernel can speculatively load it. + Self::kernel( + cmds, + 0, + 11, + [72, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(xq + (rows * 20 * 144) as u64), + A::I32((128 * 144) as i32), + ], + )?; + Self::kernel( + cmds, + 0, + 16, + [(rows * 20).div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(xq), + A::I32((rows * 20) as i32), + A::U64(self.status(stage)?.qwen_address()), + ], + )?; + let tmp = if fix { + self.tmp + .as_ref() + .ok_or(Error::ContextPoisoned)? + .handle + .ok_or(Error::ContextPoisoned)? + .qwen_address() + } else { + 0 + }; + let fd = fastdiv; + Self::kernel( + cmds, + 3, + index, + [grid as u32, 1, 1], + [32, 8, 1], + shared as u32, + vec![ + A::U64(w), + A::U64(xq), + A::U64(ids), + A::U64(bound), + A::U64(y), + A::U64(tmp), + A::U64(0), + A::U3(fd(80)), + A::I32(out as i32), + A::I32(rows as i32), + A::I32(80), + A::I32(rows as i32), + A::I32(out as i32), + A::U3(fd(1)), + A::U3(fd(1)), + A::I32((out * 80) as i32), + A::I32(0), + A::I32(0), + A::U3(fd(1)), + A::U3(fd(1)), + A::I32(0), + A::I32(0), + A::I32(0), + A::U3(fd(ntx as u32)), + ], + )?; + if fix { + Self::kernel( + cmds, + 4, + index, + [grid as u32, 4, 1], + [32, 4, 1], + 0, + vec![ + A::U64(ids), + A::U64(bound), + A::U64(y), + A::U64(tmp), + A::U3(fd(80)), + A::I32(out as i32), + A::I32(rows as i32), + A::I32(out as i32), + A::U3(fd(1)), + A::I32(0), + A::U3(fd(1)), + A::I32(0), + A::U3(fd(ntx as u32)), + ], + )?; + } + Ok(()) + } +} diff --git a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_3.rs b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_3.rs new file mode 100644 index 00000000..3c762cae --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_3.rs @@ -0,0 +1,133 @@ +//! Moved out of the parent module by STRA-338: impl OriginalMtpPrefill (3). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalMtpPrefill<'ctx> { + pub(in super::super) fn run( + &mut self, + rows: &mut OriginalPromptRows<'_, '_, '_>, + w: &mut NativeBatchWorkspace<'ctx>, + mut cmds: Vec, + staging: Vec<(BufferHandle, Vec)>, + ) -> Result<()> { + let mut readback = zero_bytes(FLAG_WORDS * 4)?; + let zero = zero_bytes(FLAG_WORDS * 4)?; + let status = self + .status + .as_ref() + .ok_or(Error::ContextPoisoned)? + .handle + .ok_or(Error::ContextPoisoned)?; + status.validate_projection_extent(FLAG_WORDS * 4, 4)?; + for i in 0..5 { + self.module(i)?; + } + let blas = w.blas()?; + let g = match self.context.enter() { + Ok(g) => g, + Err(e) => { + self.poison(); + rows.mark_failed(); + w.mark_failed(); + return Err(e); + } + }; + let mut operation = self.context.driver.api.copy_from(status, &zero); + if operation.is_ok() { + for (dst, bytes) in &staging { + if let Err(e) = self.context.driver.api.copy_from(*dst, bytes) { + operation = Err(e); + break; + } + } + } + if operation.is_ok() { + operation = self.context.driver.api.synchronize(); + } + if operation.is_ok() { + for c in &mut cmds { + let r = match c { + Cmd::Kernel { + asset, + index, + grid, + block, + shared, + args, + } => self.modules[*asset] + .as_ref() + .map_or(Err(Error::ContextPoisoned), |m| { + m.launch(*index, *grid, *block, *shared, blas.stream(), args) + }), + Cmd::Copy { dst, src, bytes } => self.modules[0] + .as_ref() + .map_or(Err(Error::ContextPoisoned), |m| { + m.copy(*dst, *src, *bytes, blas.stream()) + }), + Cmd::Gemm { + x, + w, + y, + rows, + n, + k, + alpha, + beta, + } => blas.gemm_bf16(*x, *w, *y, *rows, *n, *k, alpha, beta), + }; + if let Err(e) = r { + operation = Err(e); + break; + } + } + } + let stream = blas.synchronize(); + if operation.is_ok() && stream.is_ok() { + operation = self.context.driver.api.copy_to(status, &mut readback); + } + let device = self.context.driver.api.synchronize(); + let pop = g.finish(); + if operation.is_err() || stream.is_err() || device.is_err() || pop.is_err() { + self.poison(); + rows.mark_failed(); + w.mark_failed(); + } + if stream.is_err() || device.is_err() || pop.is_err() { + std::mem::forget((cmds, staging, zero, readback)); + self.context.retain_driver(); + return combine(combine(combine(operation, stream), device), pop); + } + combine(combine(combine(operation, stream), device), pop)?; + for word in readback.chunks_exact(4) { + if u32::from_le_bytes(word.try_into().map_err(|_| Error::InvalidSize)?) > 1 { + self.poison(); + return Err(Error::InvalidDriverValue("draft prefill status")); + } + } + for (stage, word) in readback.chunks_exact(4).enumerate() { + if u32::from_le_bytes(word.try_into().map_err(|_| Error::InvalidSize)?) != 0 { + return Err(Error::NonFiniteMmqOutput(match stage { + 0 => "MTP embedding", + 1 => "MTP embedding norm", + 2 => "MTP FC embedding", + 3 => "MTP hidden norm", + 4 => "MTP FC hidden", + 5 => "MTP broadcast", + 6 => "MTP GR normalized", + 7 => "MTP GR down", + 8 => "MTP GR SiLU", + 9 => "MTP GR up", + 10 => "MTP GR mixed", + 11 => "MTP K", + 12 => "MTP V", + 13 => "MTP K norm", + 14 => "MTP K Rope", + _ => "MTP INT8 encoded", + })); + } + } + Ok(()) + } +} diff --git a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_4.rs b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_4.rs new file mode 100644 index 00000000..7902b937 --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_4.rs @@ -0,0 +1,676 @@ +//! Moved out of the parent module by STRA-338: impl OriginalMtpPrefill (4). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalMtpPrefill<'ctx> { + #[allow(clippy::too_many_arguments)] + pub fn record<'arena, 'loan>( + &mut self, + residual: &mut OriginalDeviceResidual<'arena, 'loan, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + ring: &mut MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + tokens: &[i32], + cell0: usize, + first_needed: usize, + weights: OriginalMtpPrefillWeights<'_, '_>, + embedding: OriginalMtpEmbedding<'_, '_>, + policy: &DraftKvPolicy, + mut cancelled: impl FnMut() -> bool, + ) -> Result { + if policy.disabled { + return Ok(DraftKvOutcome::Fallback(DraftKvFallback::Disabled)); + } + if tokens.is_empty() { + return Ok(DraftKvOutcome::Fallback(DraftKvFallback::Empty)); + } + if policy.mode != 0 || policy.hybrid || policy.rotated || policy.q4 { + return Ok(DraftKvOutcome::Fallback( + DraftKvFallback::UnsupportedStorage, + )); + } + if policy.alternate_f16 { + return Ok(DraftKvOutcome::Fallback(DraftKvFallback::AlternateF16)); + } + if policy.rope_table_enabled || policy.multimodal_positions { + return Ok(DraftKvOutcome::Fallback( + DraftKvFallback::UnsupportedRopeTable, + )); + } + if [ + policy.theta_scale, + policy.freq_scale, + policy.corr_low, + policy.corr_high, + policy.ext_factor, + policy.mscale, + ] + .iter() + .any(|x| !x.is_finite()) + || policy.theta_scale <= 0.0 + || policy.freq_scale <= 0.0 + || policy.mscale <= 0.0 + { + return Err(Error::InvalidProjectionShape); + } + ring.validate_snapshot(prior)?; + workspace.validate_context(self.context)?; + ring.validate_context(self.context)?; + if self.is_failed() + || !residual.context_matches(self.context) + || tokens.len() != residual.rows() + || tokens.len() > 8192 + || cell0 + .checked_add(tokens.len()) + .is_none_or(|n| n > MTP_ORIGINAL_MAX_CELLS) + { + return Err(Error::InvalidProjectionShape); + } + if tokens + .iter() + .any(|t| *t < 0 || *t as usize >= embedding.vocab()) + { + return Err(Error::InvalidProjectionShape); + } + let r0 = first_needed.saturating_sub(cell0); + if r0 >= tokens.len() { + return Ok(DraftKvOutcome::Skipped); + } + let rows = residual.lease_mut(); + let (region, region_bytes) = rows.draft_kv_region()?; + let Some(r) = Region::new(region, region_bytes, tokens.len(), r0)? else { + return Ok(DraftKvOutcome::Fallback(DraftKvFallback::RegionTooSmall)); + }; + crate::bringup_trace!("DBG prefill.record: region ok b={} tokens={} r0={r0}", r.b, tokens.len()); + if !WIDTHS.into_iter().any(|j| { + 128 * 76 * 4 + j * 4 + (j * 144).div_ceil(1024) * 1024 <= self.shared_limit as usize + }) { + return Ok(DraftKvOutcome::Fallback(DraftKvFallback::NoQ8Tile)); + } + let weight_refs = [ + weights.embedding_norm, + weights.embedding_fc, + weights.hidden_norm, + weights.hidden_fc, + weights.gr_norm, + weights.gr_down, + weights.gr_up, + weights.key, + weights.value, + weights.key_norm, + ]; + let extents = [ + 10240, + 2560 * 80 * 34, + 40960, + 2560 * 80 * 34, + 40960, + 320 * 10240 * 2, + 10240 * 320 * 2, + 512 * 80 * 34, + 512 * 80 * 34, + 1024, + ]; + let mut wh = [region; 10]; + for i in 0..10 { + wh[i] = self.weight(rows, workspace, weight_refs[i], extents[i]).map_err(|e| { crate::bringup_trace!("DBG prefill.record: weight {i} err {e:?}"); e })?; + } + crate::bringup_trace!("DBG prefill.record: 10 weights staged"); + let eh = self.weight(rows, workspace, embedding.table, embedding.table.bytes).map_err(|e| { crate::bringup_trace!("DBG prefill.record: embedding table err {e:?}"); e })?; + crate::bringup_trace!("DBG prefill.record: embedding table staged"); + for (i, a) in weight_refs.iter().enumerate() { + for b in weight_refs.iter().take(i) { + let ah = a.handle.ok_or_else(|| { crate::bringup_trace!("DBG prefill.record: weight_ref a.handle is None (i={i})"); Error::ContextPoisoned })?; + let bh = b.handle.ok_or_else(|| { crate::bringup_trace!("DBG prefill.record: weight_ref b.handle is None (i={i})"); Error::ContextPoisoned })?; + if ah.overlaps(a.bytes, bh, b.bytes) + && !(ah.qwen_address() == bh.qwen_address() && a.bytes == b.bytes) + { + return Err(Error::OutputAliasesInput); + } + } + } + for b in weight_refs { + let h = b.handle.ok_or_else(|| { crate::bringup_trace!("DBG prefill.record: weight b.handle is None (embedding overlap)"); Error::ContextPoisoned })?; + if eh.overlaps(embedding.table.bytes, h, b.bytes) + && !(eh.qwen_address() == h.qwen_address() && embedding.table.bytes == b.bytes) + { + return Err(Error::OutputAliasesInput); + } + } + // Actual input residual lies outside the region being overwritten. + let (rh, rbytes) = rows.common_span(OriginalPromptSpan::R).map_err(|e| { crate::bringup_trace!("DBG prefill.record: common_span(R) err {e:?}"); e })?; + crate::bringup_trace!("DBG prefill.record: weights vs embedding overlap ok, R span ok"); + if rh.overlaps(rbytes, region, region_bytes) { + return Err(Error::OutputAliasesInput); + } + // The serve ring is built from prepared spans of the drafter's shared region, so buffers 0..5 are not + // separately owned DeviceBuffers; compare by address (ring.address works for both layouts). + for i in 0..5 { + let hv = ring.address(i)?; + let n = ring.sizes[i]; + let ov = |o: u64, on: usize| hv < o.saturating_add(on as u64) && o < hv.saturating_add(n as u64); + if ov(region.qwen_address(), region_bytes) + || ov(rh.qwen_address(), rbytes) + || wh.iter().zip(extents).any(|(w, n2)| ov(w.qwen_address(), n2)) + || ov(eh.qwen_address(), embedding.table.bytes) + { + return Err(Error::OutputAliasesInput); + } + } + crate::bringup_trace!("DBG prefill.record: overlap checks ok"); + let generation = ring + .generation + .checked_add(1) + .ok_or(Error::InvalidQwenShape)?; + let end = cell0 + tokens.len(); + let first = cell0 + r0; + let first_page = first / 4; + let page_count = end.div_ceil(4); + let mut pages = Vec::new(); + pages + .try_reserve_exact(page_count) + .map_err(|_| Error::HostAllocation)?; + let mut changed = Vec::new(); + changed + .try_reserve_exact(page_count - first_page) + .map_err(|_| Error::HostAllocation)?; + for p in 0..page_count { + if p < first_page { + if let Some(page) = prior.0.pages.get(p) { + pages.push(page.clone()); + continue; + } + } + let mut runs: [Vec; 4] = std::array::from_fn(|_| Vec::new()); + for (i, n) in PAGE_BYTES.into_iter().enumerate() { + runs[i] = zero_bytes(n)?; + } + if p < first_page { + pages.push(Rc::new(Page { + runs: runs.map(Vec::into_boxed_slice), + })); + } else { + changed.push(runs); + } + } + if cancelled() { + return Ok(DraftKvOutcome::Cancelled); + } + // Genuine idle dependency before this stream can mutate the real drafter KV. + crate::bringup_trace!("DBG prefill.record: pages ready, ring.execute(idle)"); + ring.execute(workspace, Vec::new()).map_err(|e| { crate::bringup_trace!("DBG prefill.record: ring.execute err {e:?}"); e })?; // genuine global + shared drafter stream idle, even identical snapshot + ring.restore(workspace, prior).map_err(|e| { crate::bringup_trace!("DBG prefill.record: ring.restore err {e:?}"); e })?; + crate::bringup_trace!("DBG prefill.record: ring restored"); + ring.current = None; + for b0 in (r0..tokens.len()).step_by(r.b) { + let nb = r.b.min(tokens.len() - b0); + let c0 = cell0 + b0; + crate::bringup_trace!("DBG prefill.record: block b0={b0} nb={nb} c0={c0}"); + if cancelled() { + return Ok(DraftKvOutcome::Cancelled); + } + let mut commands = Vec::new(); + commands + .try_reserve_exact(80) + .map_err(|_| Error::HostAllocation)?; + let mut tk = zero_bytes(nb * 4)?; + for (dst, t) in tk.chunks_exact_mut(4).zip(&tokens[b0..b0 + nb]) { + dst.copy_from_slice(&t.to_le_bytes()); + } + let mut bounds = zero_bytes(16)?; + for (dst, v) in bounds + .chunks_exact_mut(4) + .zip([0, nb as i32, 0, (nb * 4) as i32]) + { + dst.copy_from_slice(&v.to_le_bytes()); + } + Self::kernel( + &mut commands, + 0, + 9, + [(nb * 4).div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![A::U64(r.address(18, nb * 16)?), A::I32((nb * 4) as i32)], + )?; + let emb = r.address(0, nb * 10240)?; + let tok = r.address(16, nb * 4)?; + match embedding.kind { + EmbeddingKind::Native { + kind, row_bytes, .. + } => Self::kernel( + &mut commands, + 1, + 0, + [10, nb as u32, 1], + [32, 1, 1], + 0, + vec![ + A::I32(kind), + A::U64(eh.qwen_address()), + A::U64(row_bytes as u64), + A::U64(tok), + A::I64(2560), + A::U64(emb), + ], + )?, + EmbeddingKind::Compressed { + bits, + bias, + group, + codes, + scales, + offsets, + .. + } => Self::kernel( + &mut commands, + 0, + 5, + [10, nb as u32, 1], + [256, 1, 1], + 0, + vec![ + A::U64(eh.qwen_address()), + A::U64(eh.qwen_address() + codes as u64), + A::U64(if offsets { + eh.qwen_address() + (codes + scales) as u64 + } else { + 0 + }), + A::U64(tok), + A::I64(2560), + A::I32(bits), + A::I32(bias), + A::I32(group as i32), + A::U64((2560 / (8 / bits)) as u64), + A::U64((2560 / group) as u64), + A::U64(emb), + ], + )?, + } + self.finite(&mut commands, emb, nb * 2560, 0)?; + Self::kernel( + &mut commands, + 0, + 0, + [nb as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(emb), + A::U64(wh[0].qwen_address()), + A::I64(2560), + A::I64(2560), + A::F32(1e-6), + ], + )?; + self.finite(&mut commands, emb, nb * 2560, 1)?; + let e2 = r.address(1, nb * 10240)?; + self.project( + &mut commands, + &r, + emb, + wh[1].qwen_address(), + e2, + nb, + 2560, + 0, + 2, + )?; + self.finite(&mut commands, e2, nb * 2560, 2)?; + let hn = r.address(3, nb * 40960)?; + let h2 = r.address(4, nb * 40960)?; + commands.push(Cmd::Copy { + dst: hn, + src: rh + .checked_subspan(rbytes, b0 * 40960, nb * 40960)? + .qwen_address(), + bytes: nb * 40960, + }); + Self::kernel( + &mut commands, + 0, + 0, + [nb as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(hn), + A::U64(wh[2].qwen_address()), + A::I64(10240), + A::I64(10240), + A::F32(1e-6), + ], + )?; + self.finite(&mut commands, hn, nb * 10240, 3)?; + self.project( + &mut commands, + &r, + hn, + wh[3].qwen_address(), + h2, + nb * 4, + 2560, + 1, + 4, + )?; + self.finite(&mut commands, h2, nb * 10240, 4)?; + let rm = r.address(5, nb * 40960)?; + let gated = r.address(6, nb * 40960)?; + let xn = r.address(8, nb * 20480)?; + let lo = r.address(9, nb * 1280)?; + let lo16 = r.address(10, nb * 640)?; + let grs = r.address(11, nb * 16)?; + let mixed = r.address(12, nb * 10240)?; + let mixedh = r.address(13, nb * 5120)?; + Self::kernel( + &mut commands, + 0, + 4, + [40, nb as u32, 1], + [256, 1, 1], + 0, + vec![A::U64(h2), A::U64(e2), A::U64(rm), A::I64(2560), A::I32(4)], + )?; + self.finite(&mut commands, rm, nb * 10240, 5)?; + Self::kernel( + &mut commands, + 0, + 1, + [(nb * 4) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(rm), + A::U64(wh[4].qwen_address()), + A::F32(1e-6), + A::U64(grs), + A::U64(xn), + A::U64(0), + ], + )?; + self.finite(&mut commands, grs, nb * 4, 6)?; + Self::kernel( + &mut commands, + 0, + 12, + [(nb * 10240).div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(rm), + A::U64(grs), + A::U64(wh[4].qwen_address()), + A::U64(self.status(6)?.qwen_address()), + A::I64(nb as i64), + ], + )?; + Self::kernel( + &mut commands, + 0, + 14, + [(nb * 10240).div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(xn), + A::I32((nb * 10240) as i32), + A::U64(self.status(6)?.qwen_address()), + ], + )?; + commands.push(Cmd::Gemm { + x: r.handle(8, nb * 20480)?, + w: wh[5], + y: r.handle(9, nb * 1280)?, + rows: nb as i32, + n: 320, + k: 10240, + alpha: 1.0, + beta: 0.0, + }); + self.finite(&mut commands, lo, nb * 320, 7)?; + Self::kernel( + &mut commands, + 0, + 2, + [(nb * 320).div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(lo), + A::U64(lo16), + A::U64(0), + A::I64((nb * 320) as i64), + ], + )?; + Self::kernel( + &mut commands, + 0, + 13, + [(nb * 320).div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(lo), + A::U64(self.status(8)?.qwen_address()), + A::I64(nb as i64), + ], + )?; + Self::kernel( + &mut commands, + 0, + 14, + [(nb * 320).div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(lo16), + A::I32((nb * 320) as i32), + A::U64(self.status(8)?.qwen_address()), + ], + )?; + commands.push(Cmd::Gemm { + x: r.handle(10, nb * 640)?, + w: wh[6], + y: r.handle(6, nb * 40960)?, + rows: nb as i32, + n: 10240, + k: 320, + alpha: 1.0, + beta: 0.0, + }); + self.finite(&mut commands, gated, nb * 10240, 9)?; + Self::kernel( + &mut commands, + 0, + 3, + [(nb * 2560).div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(rm), + A::U64(grs), + A::U64(wh[4].qwen_address()), + A::U64(gated), + A::U64(mixed), + A::U64(0), + A::I64(nb as i64), + A::U64(mixedh), + A::U64(0), + ], + )?; + Self::kernel( + &mut commands, + 0, + 15, + [(nb * 10240).div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(rm), + A::U64(grs), + A::U64(wh[4].qwen_address()), + A::U64(gated), + A::U64(self.status(10)?.qwen_address()), + A::I64(nb as i64), + ], + )?; + self.finite(&mut commands, mixed, nb * 2560, 10)?; + let kc = r.address(14, nb * 2048)?; + let vc = r.address(15, nb * 2048)?; + self.project( + &mut commands, + &r, + mixed, + wh[7].qwen_address(), + kc, + nb, + 512, + 0, + 11, + )?; + self.finite(&mut commands, kc, nb * 512, 11)?; + self.project( + &mut commands, + &r, + mixed, + wh[8].qwen_address(), + vc, + nb, + 512, + 0, + 12, + )?; + self.finite(&mut commands, vc, nb * 512, 12)?; + Self::kernel( + &mut commands, + 0, + 0, + [(nb * 2) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(kc), + A::U64(wh[9].qwen_address()), + A::I64(256), + A::I64(256), + A::F32(1e-6), + ], + )?; + self.finite(&mut commands, kc, nb * 512, 13)?; + Self::kernel( + &mut commands, + 0, + 6, + [(nb * 2) as u32, 1, 1], + [32, 1, 1], + 0, + vec![ + A::U64(kc), + A::I64(2), + A::I64(256), + A::I64(512), + A::I64(c0 as i64), + A::F32(policy.theta_scale), + A::F32(policy.freq_scale), + A::F32(policy.corr_low), + A::F32(policy.corr_high), + A::F32(policy.ext_factor), + A::F32(policy.mscale), + A::U64(0), + A::Words3([0; 3]), + ], + )?; + self.finite(&mut commands, kc, nb * 512, 14)?; + self.run( + rows, + workspace, + commands, + vec![(r.handle(16, nb * 4)?, tk), (r.handle(19, 16)?, bounds)], + )?; + if cancelled() { + return Ok(DraftKvOutcome::Cancelled); + } + let mapped = ring.mapped()?; + let mut host = [0u64; 8]; + for (i, n) in HOST_RUNS.into_iter().enumerate() { + host[i + 2] = mapped.address(HOST_OFFSETS[i], n)?; + } + let mut append = Vec::new(); + append + .try_reserve_exact(2) + .map_err(|_| Error::HostAllocation)?; + Self::kernel( + &mut append, + 0, + 7, + [nb as u32, 2, 8], + [64, 1, 1], + 0, + vec![ + A::U64(kc), + A::U64(vc), + A::I64(c0 as i64), + A::U64(ring.address(4)?), + A::I64(4), + A::U64(0), + A::U64(0), + A::U64(ring.address(0)?), + A::U64(ring.address(1)?), + A::U64(ring.address(2)?), + A::U64(ring.address(3)?), + A::Words8(host), + A::Words8([0; 8]), + ], + )?; + Self::kernel( + &mut append, + 0, + 10, + [64, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(ring.address(2)?), + A::U64(ring.address(3)?), + A::U64(ring.address(4)?), + A::I64(c0 as i64), + A::I32(nb as i32), + A::U64(self.status(15)?.qwen_address()), + ], + )?; + self.run(rows, workspace, append, Vec::new())?; + if cancelled() { + return Ok(DraftKvOutcome::Cancelled); + } + } + let mapped = ring.mapped()?; + for (p, runs) in changed.iter_mut().enumerate() { + for (i, n) in PAGE_BYTES.into_iter().enumerate() { + mapped.read_into(HOST_OFFSETS[i] + (first_page + p) * n, &mut runs[i])?; + } + } + drop(mapped); + for runs in changed { + pages.push(Rc::new(Page { + runs: runs.map(Vec::into_boxed_slice), + })); + } + let snapshot = MtpInt8Snapshot(Rc::new(Snapshot { + origin: ring.origin.clone(), + pages: Pages::from_vec(pages), + end, + checked: std::cell::Cell::new(false), + })); + ring.current = Some(snapshot.clone()); + ring.generation = generation; + Ok(DraftKvOutcome::Completed(CompletedDraftKv { + snapshot, + first_materialized: first, + end, + generation, + })) + } +} diff --git a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_5.rs b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_5.rs new file mode 100644 index 00000000..5cc48f6d --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_5.rs @@ -0,0 +1,52 @@ +//! Moved out of the parent module by STRA-338: impl OriginalMtpPrefill (5). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalMtpPrefill<'ctx> { + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + pub(in super::super) fn close_inner(&mut self) -> Result<()> { + self.failed = true; + let mut first = Ok(()); + for module in &mut self.modules { + if let Some(m) = module.take() { + let r = if self.context.is_poisoned() { + std::mem::forget(m); + Err(Error::ContextPoisoned) + } else { + match self.context.enter() { + Ok(g) => combine(m.close(), g.finish()), + Err(e) => { + self.context.poison(); + std::mem::forget(m); + Err(e) + } + } + }; + if r.is_err() { + self.context.poison(); + self.context.retain_driver(); + } + first = combine(first, r); + } + } + for b in [&mut self.status, &mut self.tmp] { + if let Some(b) = b.take() { + let r = if self.context.is_poisoned() { + std::mem::forget(b); + Err(Error::ContextPoisoned) + } else { + b.release() + }; + first = combine(first, r); + } + } + if self.context.is_poisoned() { + self.context.retain_driver(); + } + first + } +} diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill.rs index d3a083c9..eccd7ebf 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill.rs @@ -3,1283 +3,13 @@ #[allow(unused_imports)] use super::*; -impl<'ctx> OriginalMtpScalarPrefill<'ctx> { - pub(super) fn assets_ready() -> Result<()> { - let assets = [ - include_bytes!("../mtp_original_prefill.ptx").as_slice(), - include_bytes!("../mtp_original_prefill_embedding.ptx").as_slice(), - include_bytes!("../mtp_original_tail.ptx").as_slice(), - include_bytes!("../mtp_original_scalar_norm.ptx").as_slice(), - include_bytes!("../mtp_original_scalar_gr.ptx").as_slice(), - include_bytes!("../mtp_original_kv.ptx").as_slice(), - ]; - if assets - .iter() - .any(|p| p.windows(8).any(|w| w == b"UNSEALED")) - { - Err(Error::UnsupportedQwenOperation) - } else { - Ok(()) - } - } - pub fn planned_device_bytes(max_t: usize, prompt_cap: usize) -> Result { - if !(1..=MAX_PROMPT).contains(&prompt_cap) { - return Err(Error::InvalidQwenShape); - } - Scratch::new(max_t)? - .bytes - .checked_add(prompt_cap.checked_mul(29 * 4).ok_or(Error::InvalidSize)?) - .and_then(|n| n.checked_add((prompt_cap.div_ceil(max_t) + 1) * SCALAR_FLAGS * 4)) - .ok_or(Error::InvalidSize) - } - pub fn planned_host_bytes(max_t: usize, prompt_cap: usize) -> Result { - Self::planned_device_bytes(max_t, prompt_cap)?; - let timeline = (prompt_cap.div_ceil(max_t) + 1) * SCALAR_FLAGS * 4; - // New per-call immutable host snapshot may include absent pruned-prefix pages; - // charge its real worst-case payload+catalog separately from the existing - // physical mapped ring. Cached graph metadata is bounded per actual T/key. - let snapshot = MTP_ORIGINAL_MAX_CELLS - .div_ceil(4) - .checked_mul(4224 + 128) - .ok_or(Error::BudgetExceeded)?; - (2 * max_t) - .checked_mul(512 * 1024) - .and_then(|n| { - n.checked_add(prompt_cap * 29 * 4 + max_t * 29 * 4 + 2 * timeline + 64 * 1024) - }) - .and_then(|n| n.checked_add(snapshot)) - .ok_or(Error::BudgetExceeded) - } - pub fn host_metadata_bytes(&self) -> usize { - self.graphs - .as_ref() - .map_or(0, OriginalGraphRegistry::metadata_bytes) - + self.graph_metadata_bytes - + std::mem::size_of::() - + self.pending_host.capacity() * std::mem::size_of::>() - } - pub fn pinned_host_bytes(&self) -> usize { - if self.original_layout.is_some() { - self.max_t * 236 + 384 - } else { - self.max_t * 29 * 4 - } - } - pub(super) fn new(c: &'ctx Context<'ctx>, max_t: usize, prompt_cap: usize) -> Result { - Self::new_internal(c, max_t, prompt_cap, None) - } - pub(super) fn new_internal( - c: &'ctx Context<'ctx>, - max_t: usize, - prompt_cap: usize, - exact: Option>, - ) -> Result { - let legacy_charge = Self::planned_device_bytes(max_t, prompt_cap)?; - let charge = if exact.is_some() { - legacy_charge - .checked_sub(Scratch::new(max_t)?.bytes) - .ok_or(Error::InvalidSize)? - } else { - legacy_charge - }; - if let Some(e) = &exact { - if e.layout.t != max_t { - return Err(Error::InvalidQwenShape); - } - checked(c, &e.bank, e.layout.bytes)?; - } - let assets = [ - include_bytes!("../mtp_original_prefill.ptx").as_slice(), - include_bytes!("../mtp_original_prefill_embedding.ptx").as_slice(), - include_bytes!("../mtp_original_tail.ptx").as_slice(), - include_bytes!("../mtp_original_scalar_norm.ptx").as_slice(), - include_bytes!("../mtp_original_scalar_gr.ptx").as_slice(), - include_bytes!("../mtp_original_kv.ptx").as_slice(), - ]; - if assets - .iter() - .any(|p| p.windows(8).any(|w| w == b"UNSEALED")) - { - return Err(Error::UnsupportedQwenOperation); - } - let required = charge - .checked_add(RESERVE_BYTES) - .ok_or(Error::BudgetExceeded)?; - if c.is_poisoned() || c.handle.is_none() { - return Err(Error::ContextPoisoned); - } - if c.allocated_bytes() - .checked_add(required) - .is_none_or(|n| n > c.budget_bytes()) - || c.memory_info()?.0 < required - { - return Err(Error::BudgetExceeded); - } - let mut o = Self { - context: c, - max_t, - prompt_cap, - modules: std::array::from_fn(|_| None), - scratch: None, - records: None, - status: None, - layout: match &exact { - Some(e) => e.layout.scalar(), - None => Scratch::new(max_t)?, - }, - original_layout: exact.as_ref().map(|e| e.layout.clone()), - shared_limit: 0, - plain_tile: 0, - stream: None, - failed: false, - graphs: None, - mapped: Rc::new(RefCell::new(None)), - retained: None, - ring_id: None, - policy_key: None, - pending_host: Vec::new(), - graph_metadata_bytes: 0, - has_pending: false, - }; - let operation = (|| { - let g = c.enter().inspect_err(|_| { - c.poison(); - c.retain_driver(); - })?; - let load = (|| { - o.modules[0] = Some(Rc::new(Module::load(assets[0], ENTRIES)?)); - o.modules[1] = Some(Rc::new(Module::load( - assets[1], - &[c"mtp_prefill_native_embedding"], - )?)); - o.modules[2] = Some(Rc::new(Module::load(assets[2], TAIL_ENTRIES)?)); - o.modules[3] = Some(Rc::new(Module::load( - assets[3], - &[ - c"mtp_scalar_norm1024", - c"mtp_scalar_rope", - c"mtp_scalar_copy_i32", - c"mtp_scalar_encoded", - ], - )?)); - o.modules[4] = Some(Rc::new(Module::load(assets[4], GR_ENTRIES)?)); - o.modules[5] = Some(Rc::new(Module::load(assets[5], KV_ENTRIES)?)); - let (shared, tile) = o.module(4)?.configure_gr()?; - o.shared_limit = shared; - o.plain_tile = tile; - Ok(()) - })(); - let pop = g.finish(); - if load.is_err() || pop.is_err() { - o.poison(); - } - combine(load, pop)?; - o.scratch = Some(match &exact { - Some(e) => Rc::clone(&e.bank), - None => Rc::new(c.allocate(o.layout.bytes)?), - }); - o.records = Some(Rc::new(c.allocate(prompt_cap * 29 * 4)?)); - o.status = Some(Rc::new( - c.allocate((prompt_cap.div_ceil(max_t) + 1) * SCALAR_FLAGS * 4)?, - )); - o.stream = Some(c.original_gpu_stream(OriginalStreamKind::NonBlocking)?); - let g = c.enter().inspect_err(|_| { - c.poison(); - c.retain_driver(); - })?; - let allocation = match &exact { - Some(e) => Ok(mapped_records::MappedOwner::original( - max_t, - Rc::clone(&e.mapped), - )), - None => mapped_records::MappedOwner::new(max_t), - }; - let pop = g.finish(); - if pop.is_err() { - o.poison(); - let original = match allocation { - Ok(owner) => { - std::mem::forget(owner); - Ok(()) - } - Err(e) => Err(e), - }; - return combine(original, pop); - } - if allocation.is_err() { - o.poison(); - } - *o.mapped.borrow_mut() = Some(allocation?); - o.graphs = Some(OriginalGraphRegistry::new(c, 2 * max_t)?); - o.pending_host - .try_reserve_exact(2) - .map_err(|_| Error::HostAllocation)?; - if c.memory_info()?.0 < RESERVE_BYTES { - return Err(Error::BudgetExceeded); - } - Ok(()) - })(); - if let Err(e) = operation { - return combine(Err(e), o.close()); - } - Ok(o) - } - pub fn allocated_bytes(&self) -> usize { - [&self.scratch, &self.records, &self.status] - .into_iter() - .map(|s| s.as_ref().map_or(0, |b| b.len())) - .sum() - } - pub fn is_failed(&self) -> bool { - self.failed || self.context.is_poisoned() - } - pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { - if !std::ptr::eq(c, self.context) { - return Err(Error::ContextMismatch); - } - self.validate() - } - pub(super) fn validate(&self) -> Result<()> { - if self.is_failed() - || self.modules.iter().any(Option::is_none) - || self - .stream - .as_ref() - .is_none_or(OriginalGpuStream::is_failed) - { - return Err(Error::ContextPoisoned); - } - for (b, n) in [ - (&self.scratch, self.layout.bytes), - (&self.records, self.prompt_cap * 29 * 4), - ( - &self.status, - (self.prompt_cap.div_ceil(self.max_t) + 1) * SCALAR_FLAGS * 4, - ), - ] { - let b = b.as_ref().ok_or(Error::ContextPoisoned)?; - checked(self.context, b, n)?; - } - Ok(()) - } - pub(super) fn poison(&mut self) { - self.failed = true; - self.context.poison(); - self.context.retain_driver(); - } - pub(super) fn module(&self, i: usize) -> Result<&Module> { - self.modules - .get(i) - .and_then(Option::as_ref) - .map(Rc::as_ref) - .ok_or(Error::ContextPoisoned) - } - pub(super) fn scratch(&self, i: usize, n: usize) -> Result { - let b = self.scratch.as_ref().ok_or(Error::ContextPoisoned)?; - if n == 0 || n > self.layout.sizes[i] { - return Err(Error::InvalidSize); - } - b.handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(b.bytes, self.layout.offsets[i], n) - } - pub(super) fn address(&self, i: usize, n: usize) -> Result { - Ok(self.scratch(i, n)?.qwen_address()) - } - pub(super) fn current_kv(&self, ring: &MtpOriginalInt8<'ctx>) -> Result<(u64, u64)> { - match &self.original_layout { - Some(l) => { - let b = self.scratch.as_ref().ok_or(Error::ContextPoisoned)?; - Ok(( - l.span(b, 22, 0, self.max_t * 2048)?.qwen_address(), - l.span(b, 23, 0, self.max_t * 2048)?.qwen_address(), - )) - } - None => Ok((ring.address(6)?, ring.address(7)?)), - } - } - pub(super) fn flag(&self, group: usize, stage: usize) -> Result { - let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?; - if stage >= SCALAR_FLAGS { - return Err(Error::InvalidSize); - } - Ok(b.handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(b.bytes, (group * SCALAR_FLAGS + stage) * 4, 4)? - .qwen_address()) - } - #[allow(clippy::too_many_arguments)] - pub(super) fn kernel( - cmds: &mut Vec, - asset: usize, - index: usize, - grid: [u32; 3], - block: [u32; 3], - shared: u32, - args: Vec, - ) -> Result<()> { - cmds.try_reserve(1).map_err(|_| Error::HostAllocation)?; - cmds.push(ScalarCommand::Kernel { - asset, - index, - grid, - block, - shared, - args: Arguments::new(args)?, - }); - Ok(()) - } - pub(super) fn finite( - &self, - cmds: &mut Vec, - data: u64, - n: usize, - _g: usize, - s: usize, - ) -> Result<()> { - Self::kernel( - cmds, - 2, - 11, - [n.div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - Arg::U64(data), - Arg::I32(n as i32), - Arg::U64(self.flag(0, s)?), - ], - ) - } - pub(super) fn q8_guard( - &self, - cmds: &mut Vec, - q: u64, - rows: usize, - _g: usize, - s: usize, - ) -> Result<()> { - Self::kernel( - cmds, - 2, - 12, - [(rows * 80).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - Arg::U64(q), - Arg::I32((rows * 80) as i32), - Arg::U64(self.flag(0, s)?), - ], - ) - } - pub(super) fn quant(cmds: &mut Vec, x: u64, q: u64, rows: usize) -> Result<()> { - Self::kernel( - cmds, - 2, - 0, - [(rows * 2560).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![Arg::U64(x), Arg::U64(q), Arg::I32((rows * 2560) as i32)], - ) - } - pub(super) fn project( - cmds: &mut Vec, - w: u64, - q: u64, - y: u64, - rows: usize, - out: usize, - ) -> Result<()> { - if !(1..=8).contains(&rows) || !matches!(out, 512 | 2560) { - return Err(Error::InvalidProjectionShape); - } - Self::kernel( - cmds, - 2, - rows, - [out as u32, 1, 1], - [32, 4, 1], - 0, - vec![ - Arg::U64(w), - Arg::U64(q), - Arg::U64(y), - Arg::I32(2560), - Arg::I32(out as i32), - ], - ) - } - pub(super) fn external( - &self, - rows: &OriginalPromptRows<'_, '_, '_>, - w: &NativeBatchWorkspace<'_>, - ring: &MtpOriginalInt8<'_>, - b: &DeviceBuffer<'_>, - n: usize, - ) -> Result { - checked(self.context, b, n)?; - let h = b.handle.ok_or(Error::ContextPoisoned)?; - w.reject_alias(h, n)?; - let (r, rn) = rows.common_span(OriginalPromptSpan::R)?; - if h.overlaps(n, r, rn) { - return Err(Error::OutputAliasesInput); - } - for own in [&self.scratch, &self.records, &self.status] - .into_iter() - .flatten() - { - if h.overlaps(n, own.handle.ok_or(Error::ContextPoisoned)?, own.bytes) { - return Err(Error::OutputAliasesInput); - } - } - for own in ring.buffers()?.iter().flatten() { - if h.overlaps(n, own.handle.ok_or(Error::ContextPoisoned)?, own.bytes) { - return Err(Error::OutputAliasesInput); - } - } - ring.reject_state_alias(b)?; - if !ring.fully_resident()? { - let mapped = ring.mapped()?; - let host = mapped.address(0, MTP_ORIGINAL_PINNED_HOST_BYTES)?; - if h.qwen_address() < host + MTP_ORIGINAL_PINNED_HOST_BYTES as u64 - && host < h.qwen_address() + n as u64 - { - return Err(Error::OutputAliasesInput); - } - } - Ok(h) - } - // Exact FusedGrArgs/GrMulti by-value ABI (static assertions in source asset). - #[allow(clippy::too_many_arguments)] - pub(super) fn gr_args(&self, start: usize, t: usize, wh: &[BufferHandle; 11], xn: u64) -> Result { - let mut words = Box::new([0u64; 114]); - for i in 0..t { - let row = start + i; - let a = &mut words[i * 14..i * 14 + 14]; - a[0] = self.address(1, self.max_t * 40960)? + (row * 40960) as u64; - a[1] = a[0]; - a[2] = 0; // apply=false, exact null previous writers - a[5] = wh[4].qwen_address(); - a[6] = wh[5].qwen_address(); - a[7] = wh[6].qwen_address(); - a[8] = wh[10].qwen_address(); - a[9] = u64::from(1e-6f32.to_bits()); - a[10] = self.address(8, self.max_t * 1280)? + (row * 1280) as u64; - a[11] = self.address(9, self.max_t * 16)? + (row * 16) as u64; - a[12] = self.address(10, self.max_t * 16)? + (row * 16) as u64; - a[13] = self.address(11, self.max_t * 10240)? + (row * 10240) as u64; - } - words[112] = xn; - words[113] = t as u64; - Ok(Arg::GrMulti(words)) - } - pub(super) fn gr( - &self, - cmds: &mut Vec, - t: usize, - wh: &[BufferHandle; 11], - policy: &OriginalMtpScalarPolicy, - ) -> Result<()> { - let xn = self.address(7, t * 40960)?; - Self::kernel( - cmds, - 4, - if policy.gr == OriginalMtpGrVariant::Plain { - 0 - } else { - 1 - }, - [ - t as u32, - if policy.gr == OriginalMtpGrVariant::Plain { - 1 - } else { - 4 - }, - 1, - ], - [256, 1, 1], - 0, - vec![self.gr_args(0, t, wh, xn)?], - )?; - let per_token = if policy.gr == OriginalMtpGrVariant::Staged { - 2 * 1280 * 4 - } else { - self.plain_tile * 4 - }; - let capacity = (self.shared_limit / per_token).clamp(1, 8); - for c in (0..t).step_by(capacity) { - let ct = capacity.min(t - c); - Self::kernel( - cmds, - 4, - if policy.gr == OriginalMtpGrVariant::Staged { - 2 - } else if self.plain_tile == 1280 { - 4 - } else { - 5 - }, - [41, 1, 1], - [256, 1, 1], - (ct * per_token) as u32, - vec![self.gr_args(c, ct, wh, xn + (c * 40960) as u64)?], - )?; - } - Self::kernel( - cmds, - 4, - 3, - [160, 1, 1], - [256, 1, 1], - 0, - vec![self.gr_args(0, t, wh, xn)?], - ) - } - #[allow(clippy::too_many_arguments)] - pub fn record<'arena, 'loan>( - &mut self, - residual: &mut OriginalDeviceResidual<'arena, 'loan, 'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - tokens: &[i32], - cell0: usize, - first_needed: usize, - retained: Rc>, - policy: &OriginalMtpScalarPolicy, - cancelled: impl FnMut() -> bool, - ) -> Result { - let result = self.record_impl( - residual, - workspace, - ring, - prior, - tokens, - cell0, - first_needed, - retained, - policy, - cancelled, - ); - if self.has_pending { - let drained = self.drain_graphs(residual.lease_mut(), workspace); - return combine(result, drained); - } - result - } - /// Literal cached device-input or mapped-input per-T graph scheduling. - /// Unsupported storage/math branches return explicit fallback, never completion. - #[allow(clippy::too_many_arguments)] - pub(super) fn record_impl<'arena, 'loan>( - &mut self, - residual: &mut OriginalDeviceResidual<'arena, 'loan, 'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - tokens: &[i32], - cell0: usize, - first_needed: usize, - retained: Rc>, - policy: &OriginalMtpScalarPolicy, - mut cancelled: impl FnMut() -> bool, - ) -> Result { - let kv = &policy.kv; - if kv.disabled { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::Disabled)); - } - if tokens.is_empty() { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::Empty)); - } - if kv.mode != 0 || kv.hybrid || kv.rotated || kv.q4 { - return Ok(DraftKvOutcome::Fallback( - DraftKvFallback::UnsupportedStorage, - )); - } - if kv.alternate_f16 { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::AlternateF16)); - } - if kv.rope_table_enabled || kv.multimodal_positions { - return Ok(DraftKvOutcome::Fallback( - DraftKvFallback::UnsupportedRopeTable, - )); - } - if [ - kv.theta_scale, - kv.freq_scale, - kv.corr_low, - kv.corr_high, - kv.ext_factor, - kv.mscale, - ] - .iter() - .any(|x| !x.is_finite()) - || kv.theta_scale <= 0.0 - || kv.freq_scale <= 0.0 - || kv.mscale <= 0.0 - { - return Err(Error::InvalidProjectionShape); - } - let (weights, embedding) = retained.loans(self.context)?; - self.validate()?; - ring.validate_original_main(self.scratch.as_ref().ok_or(Error::ContextPoisoned)?)?; - ring.validate_snapshot(prior)?; - workspace.validate_context(self.context)?; - ring.validate_context(self.context)?; - if !residual.context_matches(self.context) - || tokens.len() != residual.rows() - || tokens.len() > self.prompt_cap - || cell0 - .checked_add(tokens.len()) - .is_none_or(|n| n > MTP_ORIGINAL_MAX_CELLS) - || ring.max_t < self.max_t - { - return Err(Error::InvalidProjectionShape); - } - if tokens - .iter() - .any(|t| *t < 0 || *t as usize >= embedding.vocab()) - { - return Err(Error::InvalidProjectionShape); - } - // Original skips WHOLE groups whose end<=first_needed, not individual rows. - let first_group = (0..tokens.len()) - .step_by(self.max_t) - .find(|c| cell0 + *c + self.max_t.min(tokens.len() - *c) > first_needed); - let Some(first_group) = first_group else { - return Ok(DraftKvOutcome::Skipped); - }; - let first = cell0 + first_group; - let end = cell0 + tokens.len(); - let rows = residual.lease_mut(); - let (rh, rbytes) = rows.common_span(OriginalPromptSpan::R)?; - for own in [&self.scratch, &self.records, &self.status] - .into_iter() - .flatten() - { - if rh.overlaps(rbytes, own.handle.ok_or(Error::ContextPoisoned)?, own.bytes) { - return Err(Error::OutputAliasesInput); - } - } - for own in [&self.scratch, &self.records, &self.status] - .into_iter() - .flatten() - { - ring.reject_state_alias(own)?; - let h = own.handle.ok_or(Error::ContextPoisoned)?; - workspace.reject_alias(h, own.bytes)?; - for other in ring.buffers()?.iter().flatten() { - if h.overlaps( - own.bytes, - other.handle.ok_or(Error::ContextPoisoned)?, - other.bytes, - ) { - return Err(Error::OutputAliasesInput); - } - } - } - let wr = [ - weights.input.embedding_norm, - weights.input.embedding_fc, - weights.input.hidden_norm, - weights.input.hidden_fc, - weights.input.gr_norm, - weights.input.gr_down, - weights.input.gr_up, - weights.input.key, - weights.input.value, - weights.input.key_norm, - weights.gr_inject, - ]; - let extents = [ - 10240, - 2560 * 80 * 34, - 40960, - 2560 * 80 * 34, - 40960, - 320 * 10240 * 2, - 10240 * 320 * 2, - 512 * 80 * 34, - 512 * 80 * 34, - 1024, - 4 * 10240 * 2, - ]; - let mut wh = [rh; 11]; - for i in 0..11 { - wh[i] = self.external(rows, workspace, ring, wr[i], extents[i])?; - } - let eh = self.external( - rows, - workspace, - ring, - embedding.table, - embedding.table.bytes, - )?; - for i in 0..wr.len() { - for j in 0..i { - if wh[i].overlaps(extents[i], wh[j], extents[j]) - && !(wh[i].qwen_address() == wh[j].qwen_address() && extents[i] == extents[j]) - { - return Err(Error::OutputAliasesInput); - } - } - } - let key = [ - policy.gr as u32, - policy.per_group_sync as u32, - kv.theta_scale.to_bits(), - kv.freq_scale.to_bits(), - kv.corr_low.to_bits(), - kv.corr_high.to_bits(), - kv.ext_factor.to_bits(), - kv.mscale.to_bits(), - 0, - ]; - if self - .retained - .as_ref() - .is_some_and(|old| !Rc::ptr_eq(old, &retained)) - || self - .ring_id - .as_ref() - .is_some_and(|id| !id.same_owner(&prior.owner_id())) - || self.policy_key.is_some_and(|old| old != key) - { - return Err(Error::InvalidProjectionShape); - } - self.retained = Some(retained.clone()); - self.ring_id = Some(prior.owner_id()); - self.policy_key = Some(key); - let generation = ring - .generation - .checked_add(1) - .ok_or(Error::InvalidQwenShape)?; - let first_page = first / 4; - let count = end.div_ceil(4); - let mut pages = Vec::new(); - pages - .try_reserve_exact(count) - .map_err(|_| Error::HostAllocation)?; - let mut changed = Vec::new(); - changed - .try_reserve_exact(count - first_page) - .map_err(|_| Error::HostAllocation)?; - for p in 0..count { - if p < first_page { - if let Some(old) = prior.0.pages.get(p) { - pages.push(old.clone()); - continue; - } - } - let mut runs: [Vec; 4] = std::array::from_fn(|_| Vec::new()); - for (i, n) in PAGE_BYTES.into_iter().enumerate() { - runs[i] = zero_bytes(n)?; - } - if p < first_page { - pages.push(Rc::new(Page { - runs: runs.map(Vec::into_boxed_slice), - })); - } else { - changed.push(runs); - } - } - // Literal prefill records [tokens n][steps4*n][positions24*n], one upload. - let mut rec = zero_bytes(tokens.len() * 29 * 4)?; - let n = tokens.len(); - for (i, token) in tokens.iter().enumerate() { - let cell = cell0 + i; - rec[i * 4..i * 4 + 4].copy_from_slice(&token.to_le_bytes()); - for (j, v) in [cell, cell + 1, (cell + 1) / 4, cell + 1] - .into_iter() - .enumerate() - { - let off = (n + i * 4 + j) * 4; - rec[off..off + 4].copy_from_slice(&(v as i32).to_le_bytes()); - } - for h in 0..24 { - let off = (n * 5 + i * 24 + h) * 4; - rec[off..off + 4].copy_from_slice(&(cell as i32).to_le_bytes()); - } - } - let rb = self.records.as_ref().ok_or(Error::ContextPoisoned)?; - let rec_h = - rb.handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(rb.bytes, 0, rec.len())?; - let mut staging = vec![(rec_h, rec)]; - let mut cmds = Vec::new(); - cmds.try_reserve(128).map_err(|_| Error::HostAllocation)?; - if cancelled() { - return Ok(DraftKvOutcome::Cancelled); - } - ring.execute(workspace, Vec::new())?; - ring.restore(workspace, prior)?; - ring.current = None; - if !policy.per_group_sync { - self.upload_records(&mut staging)?; - } else { - self.upload_records(&mut Vec::new())?; - } - staging.clear(); - for (group, c) in (0..n).step_by(self.max_t).enumerate() { - let t = self.max_t.min(n - c); - if cell0 + c + t <= first_needed { - continue; - } - let rin = self.address(0, t * 40960)?; - let emb = self.address(2, t * 10240)?; - let en = self.address(3, t * 10240)?; - let e2 = self.address(4, t * 10240)?; - let hn = self.address(5, t * 40960)?; - let h2 = self.address(6, t * 40960)?; - let r = self.address(1, t * 40960)?; - let mixed = self.address(11, t * 10240)?; - let tok = self.address(12, t * 4)?; - let step = self.address(13, t * 16)?; - let pos = self.address(14, t * 96)?; - let mut copies = [ - (tok, rec_h.qwen_address() + (c * 4) as u64, t * 4), - ( - step, - rec_h.qwen_address() + ((n + c * 4) * 4) as u64, - t * 16, - ), - ( - pos, - rec_h.qwen_address() + ((n * 5 + c * 24) * 4) as u64, - t * 96, - ), - ( - rin, - rh.checked_subspan(rbytes, c * 40960, t * 40960)? - .qwen_address(), - t * 40960, - ), - ] - .map(|(dst, src, bytes)| ScalarCommand::Copy { dst, src, bytes }); - let needs_capture = self - .graphs - .as_mut() - .ok_or(Error::ContextPoisoned)? - .find_mut(OriginalGraphKey::MtpPrefill { - rows: t as u8, - device_inputs: !policy.per_group_sync, - })? - .is_none(); - if needs_capture { - // Captured per-T forward owns fixed whole scratch/status and stable arguments. - Self::kernel( - &mut cmds, - 0, - 11, - [1, 1, 1], - [256, 1, 1], - 0, - vec![Arg::U64(self.flag(0, 0)?), Arg::I32(64)], - )?; - if policy.per_group_sync { - let mapped = self - .mapped - .try_borrow() - .map_err(|_| Error::InvalidQwenShape)?; - let m = mapped.as_ref().ok_or(Error::ContextPoisoned)?; - for (dst, offset, count) in [ - (tok, 0, t), - (step, self.max_t * 4, t * 4), - (pos, self.max_t * 20, t * 24), - ] { - Self::kernel( - &mut cmds, - 3, - 2, - [1, 1, 1], - [128, 1, 1], - 0, - vec![ - Arg::U64(dst), - Arg::U64(m.address(offset, count * 4)?), - Arg::I32(count as i32), - ], - )?; - } - } - match embedding.kind { - EmbeddingKind::Native { - kind, row_bytes, .. - } => Self::kernel( - &mut cmds, - 1, - 0, - [10, t as u32, 1], - [32, 1, 1], - 0, - vec![ - Arg::I32(kind), - Arg::U64(eh.qwen_address()), - Arg::U64(row_bytes as u64), - Arg::U64(tok), - Arg::I64(2560), - Arg::U64(emb), - ], - )?, - EmbeddingKind::Compressed { - bits, - bias, - group, - codes, - scales, - offsets, - .. - } => Self::kernel( - &mut cmds, - 0, - 5, - [10, t as u32, 1], - [256, 1, 1], - 0, - vec![ - Arg::U64(eh.qwen_address()), - Arg::U64(eh.qwen_address() + codes as u64), - Arg::U64(if offsets { - eh.qwen_address() + (codes + scales) as u64 - } else { - 0 - }), - Arg::U64(tok), - Arg::I64(2560), - Arg::I32(bits), - Arg::I32(bias), - Arg::I32(group as i32), - Arg::U64((2560 / (8 / bits)) as u64), - Arg::U64((2560 / group) as u64), - Arg::U64(emb), - ], - )?, - } - self.finite(&mut cmds, emb, t * 2560, group, 0)?; - Self::kernel( - &mut cmds, - 3, - 0, - [t as u32, 1, 1], - [1024, 1, 1], - 0, - vec![ - Arg::U64(emb), - Arg::U64(wh[0].qwen_address()), - Arg::U64(en), - Arg::I32(2560), - Arg::F32(1e-6), - ], - )?; - self.finite(&mut cmds, en, t * 2560, group, 1)?; - let q = self.address(15, 8 * 80 * 36)?; - Self::quant(&mut cmds, en, q, t)?; - self.q8_guard(&mut cmds, q, t, group, 2)?; - Self::project(&mut cmds, wh[1].qwen_address(), q, e2, t, 2560)?; - self.finite(&mut cmds, e2, t * 2560, group, 2)?; - Self::kernel( - &mut cmds, - 3, - 0, - [t as u32, 1, 1], - [1024, 1, 1], - 0, - vec![ - Arg::U64(rin), - Arg::U64(wh[2].qwen_address()), - Arg::U64(hn), - Arg::I32(10240), - Arg::F32(1e-6), - ], - )?; - self.finite(&mut cmds, hn, t * 10240, group, 3)?; - for hc in (0..t * 4).step_by(8) { - let cols = 8.min(t * 4 - hc); - Self::quant(&mut cmds, hn + (hc * 10240) as u64, q, cols)?; - self.q8_guard(&mut cmds, q, cols, group, 4)?; - Self::project( - &mut cmds, - wh[3].qwen_address(), - q, - h2 + (hc * 10240) as u64, - cols, - 2560, - )?; - } - self.finite(&mut cmds, h2, t * 10240, group, 4)?; - Self::kernel( - &mut cmds, - 0, - 4, - [40, t as u32, 1], - [256, 1, 1], - 0, - vec![ - Arg::U64(h2), - Arg::U64(e2), - Arg::U64(r), - Arg::I64(2560), - Arg::I32(4), - ], - )?; - self.finite(&mut cmds, r, t * 10240, group, 5)?; - self.gr(&mut cmds, t, &wh, policy)?; - self.finite(&mut cmds, self.address(9, t * 16)?, t * 4, group, 6)?; - self.finite(&mut cmds, self.address(7, t * 40960)?, t * 10240, group, 6)?; - self.finite(&mut cmds, self.address(8, t * 1280)?, t * 320, group, 7)?; - self.finite(&mut cmds, self.address(10, t * 16)?, t * 4, group, 7)?; - self.finite(&mut cmds, mixed, t * 2560, group, 8)?; - Self::quant(&mut cmds, mixed, q, t)?; - self.q8_guard(&mut cmds, q, t, group, 9)?; - let (kc, vc) = self.current_kv(ring)?; - Self::project(&mut cmds, wh[7].qwen_address(), q, kc, t, 512)?; - self.finite(&mut cmds, kc, t * 512, group, 10)?; - Self::project(&mut cmds, wh[8].qwen_address(), q, vc, t, 512)?; - self.finite(&mut cmds, vc, t * 512, group, 11)?; - for row in 0..t { - let k = kc + (row * 2048) as u64; - Self::kernel( - &mut cmds, - 2, - 9, - [2, 1, 1], - [256, 1, 1], - 0, - vec![ - Arg::U64(k), - Arg::U64(wh[9].qwen_address()), - Arg::U64(k), - Arg::I32(256), - Arg::F32(1e-6), - ], - )?; - self.finite(&mut cmds, k, 512, group, 12)?; - Self::kernel( - &mut cmds, - 3, - 1, - [4, 2, 1], - [32, 1, 1], - 0, - vec![ - Arg::U64(k), - Arg::U64(k), - Arg::I32(2), - Arg::I32(256), - Arg::I32(64), - Arg::F32(kv.theta_scale), - Arg::F32(kv.freq_scale), - Arg::F32(kv.corr_low), - Arg::F32(kv.corr_high), - Arg::F32(kv.ext_factor), - Arg::F32(kv.mscale), - Arg::U64(pos + (row * 96) as u64), - Arg::U64(0), - Arg::Words3([0; 3]), - ], - )?; - self.finite(&mut cmds, k, 512, group, 13)?; - let mut host = [0u64; 8]; - host[2..6].copy_from_slice(&ring.host_addresses()?); - // Literal step append kernel and actual private step record, not batched prompt arithmetic. - Self::kernel( - &mut cmds, - 5, - 0, - [2, 4, 2], - [64, 1, 1], - 0, - vec![ - Arg::U64(ring.address(0)?), - Arg::U64(ring.address(1)?), - Arg::U64(ring.address(2)?), - Arg::U64(ring.address(3)?), - Arg::U64(ring.address(4)?), - Arg::U64(step + (row * 16) as u64), - Arg::U64(k), - Arg::U64(vc + (row * 2048) as u64), - Arg::I32(2), - Arg::I32(256), - Arg::I32(4), - Arg::U64(host[2]), - Arg::U64(host[3]), - Arg::U64(host[4]), - Arg::U64(host[5]), - ], - )?; - } - Self::kernel( - &mut cmds, - 3, - 3, - [64, 1, 1], - [256, 1, 1], - 0, - vec![ - Arg::U64(ring.address(2)?), - Arg::U64(ring.address(3)?), - Arg::U64(ring.address(4)?), - Arg::U64(step), - Arg::I32(t as i32), - Arg::U64(self.flag(0, 14)?), - ], - )?; - } - if cancelled() { - self.drain_graphs(rows, workspace)?; - return Ok(DraftKvOutcome::Cancelled); - } - if let Err(primary) = self.enqueue_group( - t, - group, - policy.per_group_sync, - &retained, - ring, - &mut cmds, - if policy.per_group_sync { - &mut copies[3..] - } else { - &mut copies[..] - }, - &tokens[c..c + t], - cell0 + c, - ) { - let drained = self.drain_graphs(rows, workspace); - return combine(Err(primary), drained); - } - cmds.clear(); - if policy.per_group_sync { - self.drain_graphs(rows, workspace)?; - } - } - if !policy.per_group_sync { - self.drain_graphs(rows, workspace)?; - } - if cancelled() { - return Ok(DraftKvOutcome::Cancelled); - } - for (p, runs) in changed.iter_mut().enumerate() { - ring.read_encoded_page(first_page + p, runs)?; - } - for runs in changed { - pages.push(Rc::new(Page { - runs: runs.map(Vec::into_boxed_slice), - })); - } - let snapshot = MtpInt8Snapshot(Rc::new(Snapshot { - origin: ring.origin.clone(), - pages: Pages::from_vec(pages), - end, - checked: std::cell::Cell::new(false), - })); - ring.current = Some(snapshot.clone()); - ring.generation = generation; - Ok(DraftKvOutcome::Completed(CompletedDraftKv { - snapshot, - first_materialized: first, - end, - generation, - })) - } - pub fn close(mut self) -> Result<()> { - self.close_inner() - } - pub(super) fn close_inner(&mut self) -> Result<()> { - self.failed = true; - let mut primary = Ok(()); - if let Some(graphs) = self.graphs.take() { - primary = combine(primary, graphs.close()); - } - if let Some(stream) = self.stream.take() { - let r = stream.close(); - if r.is_err() { - self.context.poison(); - self.context.retain_driver(); - } - primary = combine(primary, r); - } - for module in &mut self.modules { - if let Some(m) = module.take() { - let r = if self.context.is_poisoned() { - std::mem::forget(m); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(g) => combine( - Rc::try_unwrap(m) - .map_err(|_| Error::InvalidQwenShape) - .and_then(Module::close), - g.finish(), - ), - Err(e) => { - self.context.poison(); - std::mem::forget(m); - Err(e) - } - } - }; - if r.is_err() { - self.context.poison(); - self.context.retain_driver(); - } - primary = combine(primary, r); - } - } - for b in [&mut self.scratch, &mut self.records, &mut self.status] { - if let Some(b) = b.take() { - primary = combine( - primary, - if self.context.is_poisoned() { - std::mem::forget(b); - Err(Error::ContextPoisoned) - } else { - match Rc::try_unwrap(b) { - Ok(b) => b.release(), - Err(b) => { - if self.original_layout.is_some() { - drop(b); - Ok(()) - } else { - Err(Error::InvalidQwenShape) - } - } - } - }, - ); - } - } - if let Some(mut m) = self.mapped.borrow_mut().take() { - let result = if self.context.is_poisoned() { - std::mem::forget(m); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(g) => combine(m.close(), g.finish()), - Err(e) => { - self.context.poison(); - std::mem::forget(m); - Err(e) - } - } - }; - if result.is_err() { - self.context.poison(); - self.context.retain_driver(); - } - primary = combine(primary, result); - } - self.retained = None; - if self.context.is_poisoned() { - std::mem::forget(std::mem::take(&mut self.pending_host)); - } else { - self.pending_host.clear(); - } - if self.context.is_poisoned() { - self.context.retain_driver(); - } - primary - } -} +#[path = "impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_2.rs"] +mod impl_originalmtpscalarprefill_2; +#[path = "impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_2_2.rs"] +mod impl_originalmtpscalarprefill_2_2; +#[path = "impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_3.rs"] +mod impl_originalmtpscalarprefill_3; +#[path = "impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_4.rs"] +mod impl_originalmtpscalarprefill_4; +#[path = "impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_5.rs"] +mod impl_originalmtpscalarprefill_5; diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_2.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_2.rs new file mode 100644 index 00000000..e79e3357 --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_2.rs @@ -0,0 +1,243 @@ +//! Moved out of the parent module by STRA-338: impl OriginalMtpScalarPrefill. + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalMtpScalarPrefill<'ctx> { + pub(in super::super) fn assets_ready() -> Result<()> { + let assets = [ + include_bytes!("../../mtp_original_prefill.ptx").as_slice(), + include_bytes!("../../mtp_original_prefill_embedding.ptx").as_slice(), + include_bytes!("../../mtp_original_tail.ptx").as_slice(), + include_bytes!("../../mtp_original_scalar_norm.ptx").as_slice(), + include_bytes!("../../mtp_original_scalar_gr.ptx").as_slice(), + include_bytes!("../../mtp_original_kv.ptx").as_slice(), + ]; + if assets + .iter() + .any(|p| p.windows(8).any(|w| w == b"UNSEALED")) + { + Err(Error::UnsupportedQwenOperation) + } else { + Ok(()) + } + } + pub fn planned_device_bytes(max_t: usize, prompt_cap: usize) -> Result { + if !(1..=MAX_PROMPT).contains(&prompt_cap) { + return Err(Error::InvalidQwenShape); + } + Scratch::new(max_t)? + .bytes + .checked_add(prompt_cap.checked_mul(29 * 4).ok_or(Error::InvalidSize)?) + .and_then(|n| n.checked_add((prompt_cap.div_ceil(max_t) + 1) * SCALAR_FLAGS * 4)) + .ok_or(Error::InvalidSize) + } + pub fn planned_host_bytes(max_t: usize, prompt_cap: usize) -> Result { + Self::planned_device_bytes(max_t, prompt_cap)?; + let timeline = (prompt_cap.div_ceil(max_t) + 1) * SCALAR_FLAGS * 4; + // New per-call immutable host snapshot may include absent pruned-prefix pages; + // charge its real worst-case payload+catalog separately from the existing + // physical mapped ring. Cached graph metadata is bounded per actual T/key. + let snapshot = MTP_ORIGINAL_MAX_CELLS + .div_ceil(4) + .checked_mul(4224 + 128) + .ok_or(Error::BudgetExceeded)?; + (2 * max_t) + .checked_mul(512 * 1024) + .and_then(|n| { + n.checked_add(prompt_cap * 29 * 4 + max_t * 29 * 4 + 2 * timeline + 64 * 1024) + }) + .and_then(|n| n.checked_add(snapshot)) + .ok_or(Error::BudgetExceeded) + } + pub fn host_metadata_bytes(&self) -> usize { + self.graphs + .as_ref() + .map_or(0, OriginalGraphRegistry::metadata_bytes) + + self.graph_metadata_bytes + + std::mem::size_of::() + + self.pending_host.capacity() * std::mem::size_of::>() + } + pub fn pinned_host_bytes(&self) -> usize { + if self.original_layout.is_some() { + self.max_t * 236 + 384 + } else { + self.max_t * 29 * 4 + } + } + pub(in super::super) fn new(c: &'ctx Context<'ctx>, max_t: usize, prompt_cap: usize) -> Result { + Self::new_internal(c, max_t, prompt_cap, None) + } + pub(in super::super) fn new_internal( + c: &'ctx Context<'ctx>, + max_t: usize, + prompt_cap: usize, + exact: Option>, + ) -> Result { + let legacy_charge = Self::planned_device_bytes(max_t, prompt_cap)?; + let charge = if exact.is_some() { + legacy_charge + .checked_sub(Scratch::new(max_t)?.bytes) + .ok_or(Error::InvalidSize)? + } else { + legacy_charge + }; + if let Some(e) = &exact { + if e.layout.t != max_t { + return Err(Error::InvalidQwenShape); + } + checked(c, &e.bank, e.layout.bytes)?; + } + let assets = [ + include_bytes!("../../mtp_original_prefill.ptx").as_slice(), + include_bytes!("../../mtp_original_prefill_embedding.ptx").as_slice(), + include_bytes!("../../mtp_original_tail.ptx").as_slice(), + include_bytes!("../../mtp_original_scalar_norm.ptx").as_slice(), + include_bytes!("../../mtp_original_scalar_gr.ptx").as_slice(), + include_bytes!("../../mtp_original_kv.ptx").as_slice(), + ]; + if assets + .iter() + .any(|p| p.windows(8).any(|w| w == b"UNSEALED")) + { + return Err(Error::UnsupportedQwenOperation); + } + let required = charge + .checked_add(RESERVE_BYTES) + .ok_or(Error::BudgetExceeded)?; + if c.is_poisoned() || c.handle.is_none() { + return Err(Error::ContextPoisoned); + } + if c.allocated_bytes() + .checked_add(required) + .is_none_or(|n| n > c.budget_bytes()) + || c.memory_info()?.0 < required + { + return Err(Error::BudgetExceeded); + } + let mut o = Self { + context: c, + max_t, + prompt_cap, + modules: std::array::from_fn(|_| None), + scratch: None, + records: None, + status: None, + layout: match &exact { + Some(e) => e.layout.scalar(), + None => Scratch::new(max_t)?, + }, + original_layout: exact.as_ref().map(|e| e.layout.clone()), + shared_limit: 0, + plain_tile: 0, + stream: None, + failed: false, + graphs: None, + mapped: Rc::new(RefCell::new(None)), + retained: None, + ring_id: None, + policy_key: None, + pending_host: Vec::new(), + graph_metadata_bytes: 0, + has_pending: false, + }; + let operation = (|| { + let g = c.enter().inspect_err(|_| { + c.poison(); + c.retain_driver(); + })?; + let load = (|| { + o.modules[0] = Some(Rc::new(Module::load(assets[0], ENTRIES)?)); + o.modules[1] = Some(Rc::new(Module::load( + assets[1], + &[c"mtp_prefill_native_embedding"], + )?)); + o.modules[2] = Some(Rc::new(Module::load(assets[2], TAIL_ENTRIES)?)); + o.modules[3] = Some(Rc::new(Module::load( + assets[3], + &[ + c"mtp_scalar_norm1024", + c"mtp_scalar_rope", + c"mtp_scalar_copy_i32", + c"mtp_scalar_encoded", + ], + )?)); + o.modules[4] = Some(Rc::new(Module::load(assets[4], GR_ENTRIES)?)); + o.modules[5] = Some(Rc::new(Module::load(assets[5], KV_ENTRIES)?)); + let (shared, tile) = o.module(4)?.configure_gr()?; + o.shared_limit = shared; + o.plain_tile = tile; + Ok(()) + })(); + let pop = g.finish(); + if load.is_err() || pop.is_err() { + o.poison(); + } + combine(load, pop)?; + o.scratch = Some(match &exact { + Some(e) => Rc::clone(&e.bank), + None => Rc::new(c.allocate(o.layout.bytes)?), + }); + o.records = Some(Rc::new(c.allocate(prompt_cap * 29 * 4)?)); + o.status = Some(Rc::new( + c.allocate((prompt_cap.div_ceil(max_t) + 1) * SCALAR_FLAGS * 4)?, + )); + o.stream = Some(c.original_gpu_stream(OriginalStreamKind::NonBlocking)?); + let g = c.enter().inspect_err(|_| { + c.poison(); + c.retain_driver(); + })?; + let allocation = match &exact { + Some(e) => Ok(mapped_records::MappedOwner::original( + max_t, + Rc::clone(&e.mapped), + )), + None => mapped_records::MappedOwner::new(max_t), + }; + let pop = g.finish(); + if pop.is_err() { + o.poison(); + let original = match allocation { + Ok(owner) => { + std::mem::forget(owner); + Ok(()) + } + Err(e) => Err(e), + }; + return combine(original, pop); + } + if allocation.is_err() { + o.poison(); + } + *o.mapped.borrow_mut() = Some(allocation?); + o.graphs = Some(OriginalGraphRegistry::new(c, 2 * max_t)?); + o.pending_host + .try_reserve_exact(2) + .map_err(|_| Error::HostAllocation)?; + if c.memory_info()?.0 < RESERVE_BYTES { + return Err(Error::BudgetExceeded); + } + Ok(()) + })(); + if let Err(e) = operation { + return combine(Err(e), o.close()); + } + Ok(o) + } + pub fn allocated_bytes(&self) -> usize { + [&self.scratch, &self.records, &self.status] + .into_iter() + .map(|s| s.as_ref().map_or(0, |b| b.len())) + .sum() + } + pub fn is_failed(&self) -> bool { + self.failed || self.context.is_poisoned() + } + pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { + if !std::ptr::eq(c, self.context) { + return Err(Error::ContextMismatch); + } + self.validate() + } +} diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_2_2.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_2_2.rs new file mode 100644 index 00000000..f7c29b7a --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_2_2.rs @@ -0,0 +1,244 @@ +//! Moved out of the parent module by STRA-338: impl OriginalMtpScalarPrefill (2). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalMtpScalarPrefill<'ctx> { + pub(in super::super) fn validate(&self) -> Result<()> { + if self.is_failed() + || self.modules.iter().any(Option::is_none) + || self + .stream + .as_ref() + .is_none_or(OriginalGpuStream::is_failed) + { + return Err(Error::ContextPoisoned); + } + for (b, n) in [ + (&self.scratch, self.layout.bytes), + (&self.records, self.prompt_cap * 29 * 4), + ( + &self.status, + (self.prompt_cap.div_ceil(self.max_t) + 1) * SCALAR_FLAGS * 4, + ), + ] { + let b = b.as_ref().ok_or(Error::ContextPoisoned)?; + checked(self.context, b, n)?; + } + Ok(()) + } + pub(in super::super) fn poison(&mut self) { + self.failed = true; + self.context.poison(); + self.context.retain_driver(); + } + pub(in super::super) fn module(&self, i: usize) -> Result<&Module> { + self.modules + .get(i) + .and_then(Option::as_ref) + .map(Rc::as_ref) + .ok_or(Error::ContextPoisoned) + } + pub(in super::super) fn scratch(&self, i: usize, n: usize) -> Result { + let b = self.scratch.as_ref().ok_or(Error::ContextPoisoned)?; + if n == 0 || n > self.layout.sizes[i] { + return Err(Error::InvalidSize); + } + b.handle + .ok_or(Error::ContextPoisoned)? + .checked_subspan(b.bytes, self.layout.offsets[i], n) + } + pub(in super::super) fn address(&self, i: usize, n: usize) -> Result { + Ok(self.scratch(i, n)?.qwen_address()) + } + pub(in super::super) fn current_kv(&self, ring: &MtpOriginalInt8<'ctx>) -> Result<(u64, u64)> { + match &self.original_layout { + Some(l) => { + let b = self.scratch.as_ref().ok_or(Error::ContextPoisoned)?; + Ok(( + l.span(b, 22, 0, self.max_t * 2048)?.qwen_address(), + l.span(b, 23, 0, self.max_t * 2048)?.qwen_address(), + )) + } + None => Ok((ring.address(6)?, ring.address(7)?)), + } + } + pub(in super::super) fn flag(&self, group: usize, stage: usize) -> Result { + let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?; + if stage >= SCALAR_FLAGS { + return Err(Error::InvalidSize); + } + Ok(b.handle + .ok_or(Error::ContextPoisoned)? + .checked_subspan(b.bytes, (group * SCALAR_FLAGS + stage) * 4, 4)? + .qwen_address()) + } + #[allow(clippy::too_many_arguments)] + pub(in super::super) fn kernel( + cmds: &mut Vec, + asset: usize, + index: usize, + grid: [u32; 3], + block: [u32; 3], + shared: u32, + args: Vec, + ) -> Result<()> { + cmds.try_reserve(1).map_err(|_| Error::HostAllocation)?; + cmds.push(ScalarCommand::Kernel { + asset, + index, + grid, + block, + shared, + args: Arguments::new(args)?, + }); + Ok(()) + } + pub(in super::super) fn finite( + &self, + cmds: &mut Vec, + data: u64, + n: usize, + _g: usize, + s: usize, + ) -> Result<()> { + Self::kernel( + cmds, + 2, + 11, + [n.div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + Arg::U64(data), + Arg::I32(n as i32), + Arg::U64(self.flag(0, s)?), + ], + ) + } + pub(in super::super) fn q8_guard( + &self, + cmds: &mut Vec, + q: u64, + rows: usize, + _g: usize, + s: usize, + ) -> Result<()> { + Self::kernel( + cmds, + 2, + 12, + [(rows * 80).div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + Arg::U64(q), + Arg::I32((rows * 80) as i32), + Arg::U64(self.flag(0, s)?), + ], + ) + } + pub(in super::super) fn quant(cmds: &mut Vec, x: u64, q: u64, rows: usize) -> Result<()> { + Self::kernel( + cmds, + 2, + 0, + [(rows * 2560).div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![Arg::U64(x), Arg::U64(q), Arg::I32((rows * 2560) as i32)], + ) + } + pub(in super::super) fn project( + cmds: &mut Vec, + w: u64, + q: u64, + y: u64, + rows: usize, + out: usize, + ) -> Result<()> { + if !(1..=8).contains(&rows) || !matches!(out, 512 | 2560) { + return Err(Error::InvalidProjectionShape); + } + Self::kernel( + cmds, + 2, + rows, + [out as u32, 1, 1], + [32, 4, 1], + 0, + vec![ + Arg::U64(w), + Arg::U64(q), + Arg::U64(y), + Arg::I32(2560), + Arg::I32(out as i32), + ], + ) + } + pub(in super::super) fn external( + &self, + rows: &OriginalPromptRows<'_, '_, '_>, + w: &NativeBatchWorkspace<'_>, + ring: &MtpOriginalInt8<'_>, + b: &DeviceBuffer<'_>, + n: usize, + ) -> Result { + checked(self.context, b, n)?; + let h = b.handle.ok_or(Error::ContextPoisoned)?; + w.reject_alias(h, n)?; + let (r, rn) = rows.common_span(OriginalPromptSpan::R)?; + if h.overlaps(n, r, rn) { + return Err(Error::OutputAliasesInput); + } + for own in [&self.scratch, &self.records, &self.status] + .into_iter() + .flatten() + { + if h.overlaps(n, own.handle.ok_or(Error::ContextPoisoned)?, own.bytes) { + return Err(Error::OutputAliasesInput); + } + } + for own in ring.buffers()?.iter().flatten() { + if h.overlaps(n, own.handle.ok_or(Error::ContextPoisoned)?, own.bytes) { + return Err(Error::OutputAliasesInput); + } + } + ring.reject_state_alias(b)?; + if !ring.fully_resident()? { + let mapped = ring.mapped()?; + let host = mapped.address(0, MTP_ORIGINAL_PINNED_HOST_BYTES)?; + if h.qwen_address() < host + MTP_ORIGINAL_PINNED_HOST_BYTES as u64 + && host < h.qwen_address() + n as u64 + { + return Err(Error::OutputAliasesInput); + } + } + Ok(h) + } + // Exact FusedGrArgs/GrMulti by-value ABI (static assertions in source asset). + #[allow(clippy::too_many_arguments)] + pub(in super::super) fn gr_args(&self, start: usize, t: usize, wh: &[BufferHandle; 11], xn: u64) -> Result { + let mut words = Box::new([0u64; 114]); + for i in 0..t { + let row = start + i; + let a = &mut words[i * 14..i * 14 + 14]; + a[0] = self.address(1, self.max_t * 40960)? + (row * 40960) as u64; + a[1] = a[0]; + a[2] = 0; // apply=false, exact null previous writers + a[5] = wh[4].qwen_address(); + a[6] = wh[5].qwen_address(); + a[7] = wh[6].qwen_address(); + a[8] = wh[10].qwen_address(); + a[9] = u64::from(1e-6f32.to_bits()); + a[10] = self.address(8, self.max_t * 1280)? + (row * 1280) as u64; + a[11] = self.address(9, self.max_t * 16)? + (row * 16) as u64; + a[12] = self.address(10, self.max_t * 16)? + (row * 16) as u64; + a[13] = self.address(11, self.max_t * 10240)? + (row * 10240) as u64; + } + words[112] = xn; + words[113] = t as u64; + Ok(Arg::GrMulti(words)) + } +} diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_3.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_3.rs new file mode 100644 index 00000000..90a7705e --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_3.rs @@ -0,0 +1,103 @@ +//! Moved out of the parent module by STRA-338: impl OriginalMtpScalarPrefill (3). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalMtpScalarPrefill<'ctx> { + pub(in super::super) fn gr( + &self, + cmds: &mut Vec, + t: usize, + wh: &[BufferHandle; 11], + policy: &OriginalMtpScalarPolicy, + ) -> Result<()> { + let xn = self.address(7, t * 40960)?; + Self::kernel( + cmds, + 4, + if policy.gr == OriginalMtpGrVariant::Plain { + 0 + } else { + 1 + }, + [ + t as u32, + if policy.gr == OriginalMtpGrVariant::Plain { + 1 + } else { + 4 + }, + 1, + ], + [256, 1, 1], + 0, + vec![self.gr_args(0, t, wh, xn)?], + )?; + let per_token = if policy.gr == OriginalMtpGrVariant::Staged { + 2 * 1280 * 4 + } else { + self.plain_tile * 4 + }; + let capacity = (self.shared_limit / per_token).clamp(1, 8); + for c in (0..t).step_by(capacity) { + let ct = capacity.min(t - c); + Self::kernel( + cmds, + 4, + if policy.gr == OriginalMtpGrVariant::Staged { + 2 + } else if self.plain_tile == 1280 { + 4 + } else { + 5 + }, + [41, 1, 1], + [256, 1, 1], + (ct * per_token) as u32, + vec![self.gr_args(c, ct, wh, xn + (c * 40960) as u64)?], + )?; + } + Self::kernel( + cmds, + 4, + 3, + [160, 1, 1], + [256, 1, 1], + 0, + vec![self.gr_args(0, t, wh, xn)?], + ) + } + #[allow(clippy::too_many_arguments)] + pub fn record<'arena, 'loan>( + &mut self, + residual: &mut OriginalDeviceResidual<'arena, 'loan, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + ring: &mut MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + tokens: &[i32], + cell0: usize, + first_needed: usize, + retained: Rc>, + policy: &OriginalMtpScalarPolicy, + cancelled: impl FnMut() -> bool, + ) -> Result { + let result = self.record_impl( + residual, + workspace, + ring, + prior, + tokens, + cell0, + first_needed, + retained, + policy, + cancelled, + ); + if self.has_pending { + let drained = self.drain_graphs(residual.lease_mut(), workspace); + return combine(result, drained); + } + result + } +} diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_4.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_4.rs new file mode 100644 index 00000000..12b8eeb6 --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_4.rs @@ -0,0 +1,622 @@ +//! Moved out of the parent module by STRA-338: impl OriginalMtpScalarPrefill (4). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalMtpScalarPrefill<'ctx> { + /// Literal cached device-input or mapped-input per-T graph scheduling. + /// Unsupported storage/math branches return explicit fallback, never completion. + #[allow(clippy::too_many_arguments)] + pub(in super::super) fn record_impl<'arena, 'loan>( + &mut self, + residual: &mut OriginalDeviceResidual<'arena, 'loan, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + ring: &mut MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + tokens: &[i32], + cell0: usize, + first_needed: usize, + retained: Rc>, + policy: &OriginalMtpScalarPolicy, + mut cancelled: impl FnMut() -> bool, + ) -> Result { + let kv = &policy.kv; + if kv.disabled { + return Ok(DraftKvOutcome::Fallback(DraftKvFallback::Disabled)); + } + if tokens.is_empty() { + return Ok(DraftKvOutcome::Fallback(DraftKvFallback::Empty)); + } + if kv.mode != 0 || kv.hybrid || kv.rotated || kv.q4 { + return Ok(DraftKvOutcome::Fallback( + DraftKvFallback::UnsupportedStorage, + )); + } + if kv.alternate_f16 { + return Ok(DraftKvOutcome::Fallback(DraftKvFallback::AlternateF16)); + } + if kv.rope_table_enabled || kv.multimodal_positions { + return Ok(DraftKvOutcome::Fallback( + DraftKvFallback::UnsupportedRopeTable, + )); + } + if [ + kv.theta_scale, + kv.freq_scale, + kv.corr_low, + kv.corr_high, + kv.ext_factor, + kv.mscale, + ] + .iter() + .any(|x| !x.is_finite()) + || kv.theta_scale <= 0.0 + || kv.freq_scale <= 0.0 + || kv.mscale <= 0.0 + { + return Err(Error::InvalidProjectionShape); + } + let (weights, embedding) = retained.loans(self.context)?; + self.validate()?; + ring.validate_original_main(self.scratch.as_ref().ok_or(Error::ContextPoisoned)?)?; + ring.validate_snapshot(prior)?; + workspace.validate_context(self.context)?; + ring.validate_context(self.context)?; + if !residual.context_matches(self.context) + || tokens.len() != residual.rows() + || tokens.len() > self.prompt_cap + || cell0 + .checked_add(tokens.len()) + .is_none_or(|n| n > MTP_ORIGINAL_MAX_CELLS) + || ring.max_t < self.max_t + { + return Err(Error::InvalidProjectionShape); + } + if tokens + .iter() + .any(|t| *t < 0 || *t as usize >= embedding.vocab()) + { + return Err(Error::InvalidProjectionShape); + } + // Original skips WHOLE groups whose end<=first_needed, not individual rows. + let first_group = (0..tokens.len()) + .step_by(self.max_t) + .find(|c| cell0 + *c + self.max_t.min(tokens.len() - *c) > first_needed); + let Some(first_group) = first_group else { + return Ok(DraftKvOutcome::Skipped); + }; + let first = cell0 + first_group; + let end = cell0 + tokens.len(); + let rows = residual.lease_mut(); + let (rh, rbytes) = rows.common_span(OriginalPromptSpan::R)?; + for own in [&self.scratch, &self.records, &self.status] + .into_iter() + .flatten() + { + if rh.overlaps(rbytes, own.handle.ok_or(Error::ContextPoisoned)?, own.bytes) { + return Err(Error::OutputAliasesInput); + } + } + for own in [&self.scratch, &self.records, &self.status] + .into_iter() + .flatten() + { + ring.reject_state_alias(own)?; + let h = own.handle.ok_or(Error::ContextPoisoned)?; + workspace.reject_alias(h, own.bytes)?; + for other in ring.buffers()?.iter().flatten() { + if h.overlaps( + own.bytes, + other.handle.ok_or(Error::ContextPoisoned)?, + other.bytes, + ) { + return Err(Error::OutputAliasesInput); + } + } + } + let wr = [ + weights.input.embedding_norm, + weights.input.embedding_fc, + weights.input.hidden_norm, + weights.input.hidden_fc, + weights.input.gr_norm, + weights.input.gr_down, + weights.input.gr_up, + weights.input.key, + weights.input.value, + weights.input.key_norm, + weights.gr_inject, + ]; + let extents = [ + 10240, + 2560 * 80 * 34, + 40960, + 2560 * 80 * 34, + 40960, + 320 * 10240 * 2, + 10240 * 320 * 2, + 512 * 80 * 34, + 512 * 80 * 34, + 1024, + 4 * 10240 * 2, + ]; + let mut wh = [rh; 11]; + for i in 0..11 { + wh[i] = self.external(rows, workspace, ring, wr[i], extents[i])?; + } + let eh = self.external( + rows, + workspace, + ring, + embedding.table, + embedding.table.bytes, + )?; + for i in 0..wr.len() { + for j in 0..i { + if wh[i].overlaps(extents[i], wh[j], extents[j]) + && !(wh[i].qwen_address() == wh[j].qwen_address() && extents[i] == extents[j]) + { + return Err(Error::OutputAliasesInput); + } + } + } + let key = [ + policy.gr as u32, + policy.per_group_sync as u32, + kv.theta_scale.to_bits(), + kv.freq_scale.to_bits(), + kv.corr_low.to_bits(), + kv.corr_high.to_bits(), + kv.ext_factor.to_bits(), + kv.mscale.to_bits(), + 0, + ]; + if self + .retained + .as_ref() + .is_some_and(|old| !Rc::ptr_eq(old, &retained)) + || self + .ring_id + .as_ref() + .is_some_and(|id| !id.same_owner(&prior.owner_id())) + || self.policy_key.is_some_and(|old| old != key) + { + return Err(Error::InvalidProjectionShape); + } + self.retained = Some(retained.clone()); + self.ring_id = Some(prior.owner_id()); + self.policy_key = Some(key); + let generation = ring + .generation + .checked_add(1) + .ok_or(Error::InvalidQwenShape)?; + let first_page = first / 4; + let count = end.div_ceil(4); + let mut pages = Vec::new(); + pages + .try_reserve_exact(count) + .map_err(|_| Error::HostAllocation)?; + let mut changed = Vec::new(); + changed + .try_reserve_exact(count - first_page) + .map_err(|_| Error::HostAllocation)?; + for p in 0..count { + if p < first_page { + if let Some(old) = prior.0.pages.get(p) { + pages.push(old.clone()); + continue; + } + } + let mut runs: [Vec; 4] = std::array::from_fn(|_| Vec::new()); + for (i, n) in PAGE_BYTES.into_iter().enumerate() { + runs[i] = zero_bytes(n)?; + } + if p < first_page { + pages.push(Rc::new(Page { + runs: runs.map(Vec::into_boxed_slice), + })); + } else { + changed.push(runs); + } + } + // Literal prefill records [tokens n][steps4*n][positions24*n], one upload. + let mut rec = zero_bytes(tokens.len() * 29 * 4)?; + let n = tokens.len(); + for (i, token) in tokens.iter().enumerate() { + let cell = cell0 + i; + rec[i * 4..i * 4 + 4].copy_from_slice(&token.to_le_bytes()); + for (j, v) in [cell, cell + 1, (cell + 1) / 4, cell + 1] + .into_iter() + .enumerate() + { + let off = (n + i * 4 + j) * 4; + rec[off..off + 4].copy_from_slice(&(v as i32).to_le_bytes()); + } + for h in 0..24 { + let off = (n * 5 + i * 24 + h) * 4; + rec[off..off + 4].copy_from_slice(&(cell as i32).to_le_bytes()); + } + } + let rb = self.records.as_ref().ok_or(Error::ContextPoisoned)?; + let rec_h = + rb.handle + .ok_or(Error::ContextPoisoned)? + .checked_subspan(rb.bytes, 0, rec.len())?; + let mut staging = vec![(rec_h, rec)]; + let mut cmds = Vec::new(); + cmds.try_reserve(128).map_err(|_| Error::HostAllocation)?; + if cancelled() { + return Ok(DraftKvOutcome::Cancelled); + } + ring.execute(workspace, Vec::new())?; + ring.restore(workspace, prior)?; + ring.current = None; + if !policy.per_group_sync { + self.upload_records(&mut staging)?; + } else { + self.upload_records(&mut Vec::new())?; + } + staging.clear(); + for (group, c) in (0..n).step_by(self.max_t).enumerate() { + let t = self.max_t.min(n - c); + if cell0 + c + t <= first_needed { + continue; + } + let rin = self.address(0, t * 40960)?; + let emb = self.address(2, t * 10240)?; + let en = self.address(3, t * 10240)?; + let e2 = self.address(4, t * 10240)?; + let hn = self.address(5, t * 40960)?; + let h2 = self.address(6, t * 40960)?; + let r = self.address(1, t * 40960)?; + let mixed = self.address(11, t * 10240)?; + let tok = self.address(12, t * 4)?; + let step = self.address(13, t * 16)?; + let pos = self.address(14, t * 96)?; + let mut copies = [ + (tok, rec_h.qwen_address() + (c * 4) as u64, t * 4), + ( + step, + rec_h.qwen_address() + ((n + c * 4) * 4) as u64, + t * 16, + ), + ( + pos, + rec_h.qwen_address() + ((n * 5 + c * 24) * 4) as u64, + t * 96, + ), + ( + rin, + rh.checked_subspan(rbytes, c * 40960, t * 40960)? + .qwen_address(), + t * 40960, + ), + ] + .map(|(dst, src, bytes)| ScalarCommand::Copy { dst, src, bytes }); + let needs_capture = self + .graphs + .as_mut() + .ok_or(Error::ContextPoisoned)? + .find_mut(OriginalGraphKey::MtpPrefill { + rows: t as u8, + device_inputs: !policy.per_group_sync, + })? + .is_none(); + if needs_capture { + // Captured per-T forward owns fixed whole scratch/status and stable arguments. + Self::kernel( + &mut cmds, + 0, + 11, + [1, 1, 1], + [256, 1, 1], + 0, + vec![Arg::U64(self.flag(0, 0)?), Arg::I32(64)], + )?; + if policy.per_group_sync { + let mapped = self + .mapped + .try_borrow() + .map_err(|_| Error::InvalidQwenShape)?; + let m = mapped.as_ref().ok_or(Error::ContextPoisoned)?; + for (dst, offset, count) in [ + (tok, 0, t), + (step, self.max_t * 4, t * 4), + (pos, self.max_t * 20, t * 24), + ] { + Self::kernel( + &mut cmds, + 3, + 2, + [1, 1, 1], + [128, 1, 1], + 0, + vec![ + Arg::U64(dst), + Arg::U64(m.address(offset, count * 4)?), + Arg::I32(count as i32), + ], + )?; + } + } + match embedding.kind { + EmbeddingKind::Native { + kind, row_bytes, .. + } => Self::kernel( + &mut cmds, + 1, + 0, + [10, t as u32, 1], + [32, 1, 1], + 0, + vec![ + Arg::I32(kind), + Arg::U64(eh.qwen_address()), + Arg::U64(row_bytes as u64), + Arg::U64(tok), + Arg::I64(2560), + Arg::U64(emb), + ], + )?, + EmbeddingKind::Compressed { + bits, + bias, + group, + codes, + scales, + offsets, + .. + } => Self::kernel( + &mut cmds, + 0, + 5, + [10, t as u32, 1], + [256, 1, 1], + 0, + vec![ + Arg::U64(eh.qwen_address()), + Arg::U64(eh.qwen_address() + codes as u64), + Arg::U64(if offsets { + eh.qwen_address() + (codes + scales) as u64 + } else { + 0 + }), + Arg::U64(tok), + Arg::I64(2560), + Arg::I32(bits), + Arg::I32(bias), + Arg::I32(group as i32), + Arg::U64((2560 / (8 / bits)) as u64), + Arg::U64((2560 / group) as u64), + Arg::U64(emb), + ], + )?, + } + self.finite(&mut cmds, emb, t * 2560, group, 0)?; + Self::kernel( + &mut cmds, + 3, + 0, + [t as u32, 1, 1], + [1024, 1, 1], + 0, + vec![ + Arg::U64(emb), + Arg::U64(wh[0].qwen_address()), + Arg::U64(en), + Arg::I32(2560), + Arg::F32(1e-6), + ], + )?; + self.finite(&mut cmds, en, t * 2560, group, 1)?; + let q = self.address(15, 8 * 80 * 36)?; + Self::quant(&mut cmds, en, q, t)?; + self.q8_guard(&mut cmds, q, t, group, 2)?; + Self::project(&mut cmds, wh[1].qwen_address(), q, e2, t, 2560)?; + self.finite(&mut cmds, e2, t * 2560, group, 2)?; + Self::kernel( + &mut cmds, + 3, + 0, + [t as u32, 1, 1], + [1024, 1, 1], + 0, + vec![ + Arg::U64(rin), + Arg::U64(wh[2].qwen_address()), + Arg::U64(hn), + Arg::I32(10240), + Arg::F32(1e-6), + ], + )?; + self.finite(&mut cmds, hn, t * 10240, group, 3)?; + for hc in (0..t * 4).step_by(8) { + let cols = 8.min(t * 4 - hc); + Self::quant(&mut cmds, hn + (hc * 10240) as u64, q, cols)?; + self.q8_guard(&mut cmds, q, cols, group, 4)?; + Self::project( + &mut cmds, + wh[3].qwen_address(), + q, + h2 + (hc * 10240) as u64, + cols, + 2560, + )?; + } + self.finite(&mut cmds, h2, t * 10240, group, 4)?; + Self::kernel( + &mut cmds, + 0, + 4, + [40, t as u32, 1], + [256, 1, 1], + 0, + vec![ + Arg::U64(h2), + Arg::U64(e2), + Arg::U64(r), + Arg::I64(2560), + Arg::I32(4), + ], + )?; + self.finite(&mut cmds, r, t * 10240, group, 5)?; + self.gr(&mut cmds, t, &wh, policy)?; + self.finite(&mut cmds, self.address(9, t * 16)?, t * 4, group, 6)?; + self.finite(&mut cmds, self.address(7, t * 40960)?, t * 10240, group, 6)?; + self.finite(&mut cmds, self.address(8, t * 1280)?, t * 320, group, 7)?; + self.finite(&mut cmds, self.address(10, t * 16)?, t * 4, group, 7)?; + self.finite(&mut cmds, mixed, t * 2560, group, 8)?; + Self::quant(&mut cmds, mixed, q, t)?; + self.q8_guard(&mut cmds, q, t, group, 9)?; + let (kc, vc) = self.current_kv(ring)?; + Self::project(&mut cmds, wh[7].qwen_address(), q, kc, t, 512)?; + self.finite(&mut cmds, kc, t * 512, group, 10)?; + Self::project(&mut cmds, wh[8].qwen_address(), q, vc, t, 512)?; + self.finite(&mut cmds, vc, t * 512, group, 11)?; + for row in 0..t { + let k = kc + (row * 2048) as u64; + Self::kernel( + &mut cmds, + 2, + 9, + [2, 1, 1], + [256, 1, 1], + 0, + vec![ + Arg::U64(k), + Arg::U64(wh[9].qwen_address()), + Arg::U64(k), + Arg::I32(256), + Arg::F32(1e-6), + ], + )?; + self.finite(&mut cmds, k, 512, group, 12)?; + Self::kernel( + &mut cmds, + 3, + 1, + [4, 2, 1], + [32, 1, 1], + 0, + vec![ + Arg::U64(k), + Arg::U64(k), + Arg::I32(2), + Arg::I32(256), + Arg::I32(64), + Arg::F32(kv.theta_scale), + Arg::F32(kv.freq_scale), + Arg::F32(kv.corr_low), + Arg::F32(kv.corr_high), + Arg::F32(kv.ext_factor), + Arg::F32(kv.mscale), + Arg::U64(pos + (row * 96) as u64), + Arg::U64(0), + Arg::Words3([0; 3]), + ], + )?; + self.finite(&mut cmds, k, 512, group, 13)?; + let mut host = [0u64; 8]; + host[2..6].copy_from_slice(&ring.host_addresses()?); + // Literal step append kernel and actual private step record, not batched prompt arithmetic. + Self::kernel( + &mut cmds, + 5, + 0, + [2, 4, 2], + [64, 1, 1], + 0, + vec![ + Arg::U64(ring.address(0)?), + Arg::U64(ring.address(1)?), + Arg::U64(ring.address(2)?), + Arg::U64(ring.address(3)?), + Arg::U64(ring.address(4)?), + Arg::U64(step + (row * 16) as u64), + Arg::U64(k), + Arg::U64(vc + (row * 2048) as u64), + Arg::I32(2), + Arg::I32(256), + Arg::I32(4), + Arg::U64(host[2]), + Arg::U64(host[3]), + Arg::U64(host[4]), + Arg::U64(host[5]), + ], + )?; + } + Self::kernel( + &mut cmds, + 3, + 3, + [64, 1, 1], + [256, 1, 1], + 0, + vec![ + Arg::U64(ring.address(2)?), + Arg::U64(ring.address(3)?), + Arg::U64(ring.address(4)?), + Arg::U64(step), + Arg::I32(t as i32), + Arg::U64(self.flag(0, 14)?), + ], + )?; + } + if cancelled() { + self.drain_graphs(rows, workspace)?; + return Ok(DraftKvOutcome::Cancelled); + } + if let Err(primary) = self.enqueue_group( + t, + group, + policy.per_group_sync, + &retained, + ring, + &mut cmds, + if policy.per_group_sync { + &mut copies[3..] + } else { + &mut copies[..] + }, + &tokens[c..c + t], + cell0 + c, + ) { + let drained = self.drain_graphs(rows, workspace); + return combine(Err(primary), drained); + } + cmds.clear(); + if policy.per_group_sync { + self.drain_graphs(rows, workspace)?; + } + } + if !policy.per_group_sync { + self.drain_graphs(rows, workspace)?; + } + if cancelled() { + return Ok(DraftKvOutcome::Cancelled); + } + for (p, runs) in changed.iter_mut().enumerate() { + ring.read_encoded_page(first_page + p, runs)?; + } + for runs in changed { + pages.push(Rc::new(Page { + runs: runs.map(Vec::into_boxed_slice), + })); + } + let snapshot = MtpInt8Snapshot(Rc::new(Snapshot { + origin: ring.origin.clone(), + pages: Pages::from_vec(pages), + end, + checked: std::cell::Cell::new(false), + })); + ring.current = Some(snapshot.clone()); + ring.generation = generation; + Ok(DraftKvOutcome::Completed(CompletedDraftKv { + snapshot, + first_materialized: first, + end, + generation, + })) + } +} diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_5.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_5.rs new file mode 100644 index 00000000..cb9b5466 --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_5.rs @@ -0,0 +1,106 @@ +//! Moved out of the parent module by STRA-338: impl OriginalMtpScalarPrefill (5). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalMtpScalarPrefill<'ctx> { + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + pub(in super::super) fn close_inner(&mut self) -> Result<()> { + self.failed = true; + let mut primary = Ok(()); + if let Some(graphs) = self.graphs.take() { + primary = combine(primary, graphs.close()); + } + if let Some(stream) = self.stream.take() { + let r = stream.close(); + if r.is_err() { + self.context.poison(); + self.context.retain_driver(); + } + primary = combine(primary, r); + } + for module in &mut self.modules { + if let Some(m) = module.take() { + let r = if self.context.is_poisoned() { + std::mem::forget(m); + Err(Error::ContextPoisoned) + } else { + match self.context.enter() { + Ok(g) => combine( + Rc::try_unwrap(m) + .map_err(|_| Error::InvalidQwenShape) + .and_then(Module::close), + g.finish(), + ), + Err(e) => { + self.context.poison(); + std::mem::forget(m); + Err(e) + } + } + }; + if r.is_err() { + self.context.poison(); + self.context.retain_driver(); + } + primary = combine(primary, r); + } + } + for b in [&mut self.scratch, &mut self.records, &mut self.status] { + if let Some(b) = b.take() { + primary = combine( + primary, + if self.context.is_poisoned() { + std::mem::forget(b); + Err(Error::ContextPoisoned) + } else { + match Rc::try_unwrap(b) { + Ok(b) => b.release(), + Err(b) => { + if self.original_layout.is_some() { + drop(b); + Ok(()) + } else { + Err(Error::InvalidQwenShape) + } + } + } + }, + ); + } + } + if let Some(mut m) = self.mapped.borrow_mut().take() { + let result = if self.context.is_poisoned() { + std::mem::forget(m); + Err(Error::ContextPoisoned) + } else { + match self.context.enter() { + Ok(g) => combine(m.close(), g.finish()), + Err(e) => { + self.context.poison(); + std::mem::forget(m); + Err(e) + } + } + }; + if result.is_err() { + self.context.poison(); + self.context.retain_driver(); + } + primary = combine(primary, result); + } + self.retained = None; + if self.context.is_poisoned() { + std::mem::forget(std::mem::take(&mut self.pending_host)); + } else { + self.pending_host.clear(); + } + if self.context.is_poisoned() { + self.context.retain_driver(); + } + primary + } +} diff --git a/crates/cuda-driver/src/native_head/impl_originalnativeheadrows.rs b/crates/cuda-driver/src/native_head/impl_originalnativeheadrows.rs index 7f5213bf..4c529e80 100644 --- a/crates/cuda-driver/src/native_head/impl_originalnativeheadrows.rs +++ b/crates/cuda-driver/src/native_head/impl_originalnativeheadrows.rs @@ -3,477 +3,5 @@ #[allow(unused_imports)] use super::*; -impl<'ctx> OriginalNativeHeadRows<'ctx> { - pub(super) fn new(head: Rc>, t: usize) -> Result { - if !(1..=8).contains(&t) { - return Err(Error::InvalidQwenShape); - } - head.validate(head.context)?; - let charge = t - .checked_mul(head.n * 4 + head.n / 32 * 36 + head.vocab * 4) - .ok_or(Error::InvalidSize)?; - admission(head.context, charge)?; - let mut owner = Self { - head, - mixed: None, - q8: None, - logits: None, - mapped: None, - commands: RefCell::new(Vec::new()), - t, - failed: Cell::new(false), - }; - let op = (|| { - owner.mixed = Some(owner.head.context.allocate(t * owner.head.n * 4)?); - owner.q8 = Some(owner.head.context.allocate(t * owner.head.n / 32 * 36)?); - owner.logits = Some(owner.head.context.allocate(t * owner.head.vocab * 4)?); - let guard = owner.head.context.enter()?; - let mapped = MappedAllocation::new(t * 4); - let pop = guard.finish(); - if pop.is_err() { - owner.head.context.poison(); - owner.head.context.retain_driver(); - } - owner.mapped = Some(combine(mapped, pop)?); - Ok(()) - })(); - if let Err(primary) = op { - return combine(Err(primary), owner.close_inner()); - } - Ok(owner) - } - pub fn rows(&self) -> usize { - self.t - } - pub(crate) fn belongs_to(&self, head: &OriginalNativeHead<'ctx>) -> bool { - Rc::ptr_eq(&self.head, &head.inner) - } - pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { - self.head.validate(c)?; - if self.failed.get() - || self.mixed.is_none() - || self.q8.is_none() - || self.logits.is_none() - || self.mapped.is_none() - { - Err(Error::ContextPoisoned) - } else { - Ok(()) - } - } - /// The actual producer fills this whole destination; no host readiness is minted. - pub fn mixed_mut(&mut self) -> Result<&mut DeviceBuffer<'ctx>> { - self.validate_context(self.head.context)?; - self.mixed.as_mut().ok_or(Error::ContextPoisoned) - } - pub(super) fn buffer<'a>(&'a self, b: &'a Option>) -> Result<&'a DeviceBuffer<'ctx>> { - b.as_ref().ok_or(Error::ContextPoisoned) - } - pub(super) fn output_address(&self) -> Result { - self.mapped - .as_ref() - .ok_or(Error::ContextPoisoned)? - .address(0, self.t * 4) - } - pub(super) fn projection(&self) -> Result> { - self.validate_context(self.head.context)?; - projection_commands( - &self.head, - self.buffer(&self.mixed)?, - self.buffer(&self.q8)?, - self.buffer(&self.logits)?, - self.t, - ) - } - pub(super) fn greedy(&self) -> Result { - let mut p = SamplerParams::default(); - p.greedy = true; - p.temperature = 0.0; - Command::new( - greedy_entry(), - [self.t as u32, 1, 1], - [1024, 1, 1], - 0, - vec![ - Arg::Address(address(self.buffer(&self.logits)?)?), - Arg::I32(self.head.vocab as i32), - Arg::Address(0), - Arg::I32(0), - Arg::Params(p), - Arg::I32(0), - Arg::I32(0), - Arg::Address(self.output_address()?), - ], - ) - } - pub(super) fn prepare_commands(&self, commands: &[Command]) -> Result<()> { - self.commands - .borrow_mut() - .try_reserve_exact(commands.len()) - .map_err(|_| Error::HostAllocation)?; - let k = self.head.kernels.as_ref().ok_or(Error::ContextPoisoned)?; - for c in commands { - k.module(c.name)?.admit(c)?; - } - Ok(()) - } - pub(super) fn submit(&self, stream: usize, mut commands: Vec) -> Result<()> { - if stream == 0 { - return Err(Error::InvalidQwenShape); - } - let k = self.head.kernels.as_ref().ok_or(Error::ContextPoisoned)?; - let mut op = Ok(()); - for c in &mut commands { - if op.is_ok() { - op = k.module(c.name)?.launch(stream, c); - } - } - self.commands.borrow_mut().extend(commands); - if op.as_ref().err().is_some_and(transport) { - self.failed.set(true); - self.head.failed.set(true); - self.head.context.poison(); - } - op - } - /// Exact captured Verifier tail: one quantize ALL T, native MMVQ ALL T, greedy. - pub fn capture_head_greedy(&mut self, capture: &mut OriginalCapture<'_, 'ctx>) -> Result<()> { - capture.validate_context(self.head.context)?; - let mut c = self.projection()?; - c.push(self.greedy()?); - self.prepare_commands(&c)?; - self.submit(capture.stream_handle(self.head.context)?, c) - } - pub fn enqueue_head_greedy<'a>( - &'a mut self, - stream: &'a mut OriginalGpuStream<'ctx>, - ) -> Result> { - stream.validate_context(self.head.context)?; - let mut c = self.projection()?; - c.push(self.greedy()?); - self.prepare_commands(&c)?; - let op = stream.with_enqueue(|h| self.submit(h, c)); - if let Err(primary) = op { - return combine(Err(primary), stream.synchronize()); - } - Ok(NativeHeadFlight { - rows: self, - stream, - active: true, - }) - } - // Called ONLY by the genuine graph bridge after an actual launched graph drain, - // or by NativeHeadFlight after its same-stream wait. No caller completion flag. - pub(crate) fn finish_same_stream( - &mut self, - stream: &mut OriginalGpuStream<'ctx>, - sampling: NativeHeadSampling<'_, 'ctx>, - ) -> Result { - let NativeHeadSampling { - position: pos0, - params, - history, - history_len, - path, - enabled: head_sampling, - } = sampling; - self.validate_context(self.head.context)?; - stream.validate_context(self.head.context)?; - params.validate()?; - if history_len > i32::MAX as usize { - return Err(Error::InvalidSize); - } - if pos0.checked_add(self.t as u64 - 1).is_none() { - return Err(Error::InvalidSize); - } - self.commands.borrow_mut().clear(); - if head_sampling && ((!params.greedy && params.temperature > 0.0) || history.is_some()) { - let mut p = params; - p.counter = pos0; - // Original sampler ignores the history pointer entirely with penalties off. - // An empty optional history must not create a zero-byte admission failure. - let (history, history_len) = if p.penalty_last_n > 0 { - let h = history.ok_or(Error::InvalidQwenShape)?; - if history_len == 0 { - return Err(Error::InvalidQwenShape); - } - admit_history_prefix( - self.head.context, - h, - self.t - .checked_mul(history_len) - .and_then(|n| n.checked_mul(4)) - .ok_or(Error::InvalidSize)?, - )?; - disjoint(h, self.buffer(&self.mixed)?)?; - disjoint(h, self.buffer(&self.q8)?)?; - disjoint(h, self.buffer(&self.logits)?)?; - (Some(h), history_len) - } else { - (None, 0) - }; - let mut commands = self.sample_commands( - p, - history, - history_len, - path, - stream.native_head_stream_key()?, - )?; - self.prepare_commands(&commands)?; - let span_sample = crate::host_profile::span("head.sample_sync"); - let operation = stream.with_enqueue(|h| self.submit(h, std::mem::take(&mut commands))); - let sync = stream.synchronize(); - drop(span_sample); - combine(operation, sync)?; - self.commands.borrow_mut().clear(); - } - let _span_ids = crate::host_profile::span("head.read_ids"); - let ids = self - .mapped - .as_ref() - .ok_or(Error::ContextPoisoned)? - .read_i32(self.t)?; - if ids - .iter() - .any(|&id| id < 0 || id as usize >= self.head.vocab) - { - return Err(Error::InvalidDriverValue("Original NativeHead sampled id")); - } - Ok(NativeHeadSelection { - ids, - position: pos0, - vocabulary: self.head.vocab, - }) - } - pub(super) fn sample_commands( - &self, - p: SamplerParams, - history: Option<&DeviceBuffer<'ctx>>, - history_len: usize, - path: SamplerPath, - stream_key: usize, - ) -> Result> { - let history = history.map(address).transpose()?.unwrap_or(0); - let logits = address(self.buffer(&self.logits)?)?; - let output = self.output_address()?; - let v = self.head.vocab as i32; - let t = self.t as i32; - let shared = if history != 0 && history_len > 0 && p.penalty_last_n > 0 { - self.head.vocab.div_ceil(32) * 4 - } else { - 0 - }; - let mut c = Vec::new(); - c.try_reserve_exact(2).map_err(|_| Error::HostAllocation)?; - if p.greedy || p.temperature <= 0.0 { - c.push(Command::new( - greedy_entry(), - [self.t as u32, 1, 1], - [1024, 1, 1], - shared.try_into().map_err(|_| Error::InvalidSize)?, - vec![ - Arg::Address(logits), - Arg::I32(v), - Arg::Address(history), - Arg::I32(history_len.try_into().map_err(|_| Error::InvalidSize)?), - Arg::Params(p), - Arg::I32(p.penalty_last_n), - Arg::I32(p.penalty_last_n), - Arg::Address(output), - ], - )?); - } else if path == SamplerPath::Old { - c.push(Command::new( - "sampler_kernel", - [self.t as u32, 1, 1], - [1024, 1, 1], - shared as u32, - vec![ - Arg::Address(logits), - Arg::I32(v), - Arg::I32(t), - Arg::Address(history), - Arg::I32(history_len as i32), - Arg::Params(p), - Arg::Address(output), - ], - )?); - } else { - let blocks = self.head.vocab.div_ceil(4096); - let scratch = if path == SamplerPath::Split && blocks <= 64 { - self.split_scratch(stream_key, 16 * blocks * 64)? - } else { - None - }; - if let Some(scratch) = scratch { - let k = if p.top_k > 0 && p.top_k < 64 { - p.top_k - } else { - 64 - } - .min(v); - c.push(cmd( - "sampler_split_part_kernel", - [blocks as u32, self.t as u32, 1], - [128, 1, 1], - vec![ - Arg::Address(logits), - Arg::I32(v), - Arg::Address(history), - Arg::I32(history_len as i32), - Arg::Params(p), - Arg::I32(k), - Arg::I32(blocks as i32), - Arg::Address(scratch), - ], - )?); - c.push(cmd( - "sampler_split_merge_kernel", - [self.t as u32, 1, 1], - [32, 1, 1], - vec![ - Arg::Address(scratch), - Arg::I32(blocks as i32), - Arg::I32(v), - Arg::Params(p), - Arg::I32(k), - Arg::Address(output), - ], - )?); - } else { - c.push(Command::new( - "sampler_one_block_kernel", - [self.t as u32, 1, 1], - [1024, 1, 1], - shared as u32, - vec![ - Arg::Address(logits), - Arg::I32(v), - Arg::Address(history), - Arg::I32(history_len as i32), - Arg::Params(p), - Arg::Address(output), - ], - )?); - } - } - Ok(c) - } - pub(super) fn split_scratch(&self, stream_key: usize, entries: usize) -> Result> { - const CAP: usize = 64 * 64 * 64; - if entries == 0 || entries > CAP { - return Ok(None); - } - // Same per-(device, actual stream) lifetime as Original. All fixed-T banks - // share this model owner; streams never share a scratch buffer. - let mut slots = self - .head - .sampling - .try_borrow_mut() - .map_err(|_| Error::InvalidQwenShape)?; - let at = match slots.iter().position(|slot| slot.stream == stream_key) { - Some(at) => at, - None => { - slots - .try_reserve_exact(1) - .map_err(|_| Error::HostAllocation)?; - slots.push(SamplingScratch { - stream: stream_key, - buffer: None, - entries: 0, - failed: 0, - retired: Vec::new(), - }); - slots.len() - 1 - } - }; - let slot = &mut slots[at]; - if slot.entries >= entries { - return slot.buffer.as_ref().map(address).transpose(); - } - if slot.failed != 0 && entries >= slot.failed { - return Ok(None); - } - slot.retired - .try_reserve_exact(1) - .map_err(|_| Error::HostAllocation)?; - let want = (2 * slot.entries).min(CAP).max(entries); - for n in [want, entries] { - // Admission refusal is the original allocation-failure fallback; do not - // swallow a physical-query/Context failure as an allocation shortage. - if let Err(e) = admission(self.head.context, n * 8) { - if matches!(e, Error::BudgetExceeded) { - continue; - } - return Err(e); - } - match self.head.context.allocate(n * 8) { - Ok(b) => { - if let Some(old) = slot.buffer.replace(b) { - slot.retired.push(old); - } - slot.entries = n; - return slot.buffer.as_ref().map(address).transpose(); - } - Err(Error::BudgetExceeded) - | Err(Error::Driver { - operation: "cuMemAlloc_v2", - code: 2, - }) => {} - Err(e) => return Err(e), - } - } - slot.failed = entries; - Ok(None) - } - /// Actual ALL-row logits, only after caller's genuine graph/flight completion. - pub(crate) fn completed_logits(&self) -> Result<&DeviceBuffer<'ctx>> { - self.validate_context(self.head.context)?; - self.buffer(&self.logits) - } - pub fn close(mut self) -> Result<()> { - self.close_inner() - } - pub(super) fn close_inner(&mut self) -> Result<()> { - if self.mixed.is_none() - && self.q8.is_none() - && self.logits.is_none() - && self.mapped.is_none() - { - return Ok(()); - } - self.failed.set(true); - let context = self.head.context; - let sync = context.synchronize(); - if sync.is_err() || context.is_poisoned() { - context.poison(); - context.retain_driver(); - for b in [self.mixed.take(), self.q8.take(), self.logits.take()] - .into_iter() - .flatten() - { - std::mem::forget(b); - } - if let Some(m) = self.mapped.take() { - std::mem::forget(m); - } - std::mem::forget(std::mem::take(self.commands.get_mut())); - return combine(sync, Err(Error::ContextPoisoned)); - } - self.commands.get_mut().clear(); - let mut result = Ok(()); - for b in [self.mixed.take(), self.q8.take(), self.logits.take()] - .into_iter() - .flatten() - { - result = combine(result, b.release()); - } - let guard = context.enter()?; - let mapped = self.mapped.take().map_or(Ok(()), |mut m| m.close()); - let pop = guard.finish(); - if mapped.is_err() || pop.is_err() { - context.poison(); - } - combine(combine(result, mapped), pop) - } -} +mod impl_originalnativeheadrows_2; +mod impl_originalnativeheadrows_2_2; diff --git a/crates/cuda-driver/src/native_head/impl_originalnativeheadrows/impl_originalnativeheadrows_2.rs b/crates/cuda-driver/src/native_head/impl_originalnativeheadrows/impl_originalnativeheadrows_2.rs new file mode 100644 index 00000000..4e07ebda --- /dev/null +++ b/crates/cuda-driver/src/native_head/impl_originalnativeheadrows/impl_originalnativeheadrows_2.rs @@ -0,0 +1,249 @@ +//! Moved out of the parent module by STRA-338: impl OriginalNativeHeadRows. + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalNativeHeadRows<'ctx> { + pub(in super::super) fn new(head: Rc>, t: usize) -> Result { + if !(1..=8).contains(&t) { + return Err(Error::InvalidQwenShape); + } + head.validate(head.context)?; + let charge = t + .checked_mul(head.n * 4 + head.n / 32 * 36 + head.vocab * 4) + .ok_or(Error::InvalidSize)?; + admission(head.context, charge)?; + let mut owner = Self { + head, + mixed: None, + q8: None, + logits: None, + mapped: None, + commands: RefCell::new(Vec::new()), + t, + failed: Cell::new(false), + }; + let op = (|| { + owner.mixed = Some(owner.head.context.allocate(t * owner.head.n * 4)?); + owner.q8 = Some(owner.head.context.allocate(t * owner.head.n / 32 * 36)?); + owner.logits = Some(owner.head.context.allocate(t * owner.head.vocab * 4)?); + let guard = owner.head.context.enter()?; + let mapped = MappedAllocation::new(t * 4); + let pop = guard.finish(); + if pop.is_err() { + owner.head.context.poison(); + owner.head.context.retain_driver(); + } + owner.mapped = Some(combine(mapped, pop)?); + Ok(()) + })(); + if let Err(primary) = op { + return combine(Err(primary), owner.close_inner()); + } + Ok(owner) + } + pub fn rows(&self) -> usize { + self.t + } + pub(crate) fn belongs_to(&self, head: &OriginalNativeHead<'ctx>) -> bool { + Rc::ptr_eq(&self.head, &head.inner) + } + pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { + self.head.validate(c)?; + if self.failed.get() + || self.mixed.is_none() + || self.q8.is_none() + || self.logits.is_none() + || self.mapped.is_none() + { + Err(Error::ContextPoisoned) + } else { + Ok(()) + } + } + /// The actual producer fills this whole destination; no host readiness is minted. + pub fn mixed_mut(&mut self) -> Result<&mut DeviceBuffer<'ctx>> { + self.validate_context(self.head.context)?; + self.mixed.as_mut().ok_or(Error::ContextPoisoned) + } + pub(in super::super) fn buffer<'a>(&'a self, b: &'a Option>) -> Result<&'a DeviceBuffer<'ctx>> { + b.as_ref().ok_or(Error::ContextPoisoned) + } + pub(in super::super) fn output_address(&self) -> Result { + self.mapped + .as_ref() + .ok_or(Error::ContextPoisoned)? + .address(0, self.t * 4) + } + pub(in super::super) fn projection(&self) -> Result> { + self.validate_context(self.head.context)?; + projection_commands( + &self.head, + self.buffer(&self.mixed)?, + self.buffer(&self.q8)?, + self.buffer(&self.logits)?, + self.t, + ) + } + pub(in super::super) fn greedy(&self) -> Result { + let mut p = SamplerParams::default(); + p.greedy = true; + p.temperature = 0.0; + Command::new( + greedy_entry(), + [self.t as u32, 1, 1], + [1024, 1, 1], + 0, + vec![ + Arg::Address(address(self.buffer(&self.logits)?)?), + Arg::I32(self.head.vocab as i32), + Arg::Address(0), + Arg::I32(0), + Arg::Params(p), + Arg::I32(0), + Arg::I32(0), + Arg::Address(self.output_address()?), + ], + ) + } + pub(in super::super) fn prepare_commands(&self, commands: &[Command]) -> Result<()> { + self.commands + .borrow_mut() + .try_reserve_exact(commands.len()) + .map_err(|_| Error::HostAllocation)?; + let k = self.head.kernels.as_ref().ok_or(Error::ContextPoisoned)?; + for c in commands { + k.module(c.name)?.admit(c)?; + } + Ok(()) + } + pub(in super::super) fn submit(&self, stream: usize, mut commands: Vec) -> Result<()> { + if stream == 0 { + return Err(Error::InvalidQwenShape); + } + let k = self.head.kernels.as_ref().ok_or(Error::ContextPoisoned)?; + let mut op = Ok(()); + for c in &mut commands { + if op.is_ok() { + op = k.module(c.name)?.launch(stream, c); + } + } + self.commands.borrow_mut().extend(commands); + if op.as_ref().err().is_some_and(transport) { + self.failed.set(true); + self.head.failed.set(true); + self.head.context.poison(); + } + op + } + /// Exact captured Verifier tail: one quantize ALL T, native MMVQ ALL T, greedy. + pub fn capture_head_greedy(&mut self, capture: &mut OriginalCapture<'_, 'ctx>) -> Result<()> { + capture.validate_context(self.head.context)?; + let mut c = self.projection()?; + c.push(self.greedy()?); + self.prepare_commands(&c)?; + self.submit(capture.stream_handle(self.head.context)?, c) + } + pub fn enqueue_head_greedy<'a>( + &'a mut self, + stream: &'a mut OriginalGpuStream<'ctx>, + ) -> Result> { + stream.validate_context(self.head.context)?; + let mut c = self.projection()?; + c.push(self.greedy()?); + self.prepare_commands(&c)?; + let op = stream.with_enqueue(|h| self.submit(h, c)); + if let Err(primary) = op { + return combine(Err(primary), stream.synchronize()); + } + Ok(NativeHeadFlight { + rows: self, + stream, + active: true, + }) + } + // Called ONLY by the genuine graph bridge after an actual launched graph drain, + // or by NativeHeadFlight after its same-stream wait. No caller completion flag. + pub(crate) fn finish_same_stream( + &mut self, + stream: &mut OriginalGpuStream<'ctx>, + sampling: NativeHeadSampling<'_, 'ctx>, + ) -> Result { + let NativeHeadSampling { + position: pos0, + params, + history, + history_len, + path, + enabled: head_sampling, + } = sampling; + self.validate_context(self.head.context)?; + stream.validate_context(self.head.context)?; + params.validate()?; + if history_len > i32::MAX as usize { + return Err(Error::InvalidSize); + } + if pos0.checked_add(self.t as u64 - 1).is_none() { + return Err(Error::InvalidSize); + } + self.commands.borrow_mut().clear(); + if head_sampling && ((!params.greedy && params.temperature > 0.0) || history.is_some()) { + let mut p = params; + p.counter = pos0; + // Original sampler ignores the history pointer entirely with penalties off. + // An empty optional history must not create a zero-byte admission failure. + let (history, history_len) = if p.penalty_last_n > 0 { + let h = history.ok_or(Error::InvalidQwenShape)?; + if history_len == 0 { + return Err(Error::InvalidQwenShape); + } + admit_history_prefix( + self.head.context, + h, + self.t + .checked_mul(history_len) + .and_then(|n| n.checked_mul(4)) + .ok_or(Error::InvalidSize)?, + )?; + disjoint(h, self.buffer(&self.mixed)?)?; + disjoint(h, self.buffer(&self.q8)?)?; + disjoint(h, self.buffer(&self.logits)?)?; + (Some(h), history_len) + } else { + (None, 0) + }; + let mut commands = self.sample_commands( + p, + history, + history_len, + path, + stream.native_head_stream_key()?, + )?; + self.prepare_commands(&commands)?; + let span_sample = crate::host_profile::span("head.sample_sync"); + let operation = stream.with_enqueue(|h| self.submit(h, std::mem::take(&mut commands))); + let sync = stream.synchronize(); + drop(span_sample); + combine(operation, sync)?; + self.commands.borrow_mut().clear(); + } + let _span_ids = crate::host_profile::span("head.read_ids"); + let ids = self + .mapped + .as_ref() + .ok_or(Error::ContextPoisoned)? + .read_i32(self.t)?; + if ids + .iter() + .any(|&id| id < 0 || id as usize >= self.head.vocab) + { + return Err(Error::InvalidDriverValue("Original NativeHead sampled id")); + } + Ok(NativeHeadSelection { + ids, + position: pos0, + vocabulary: self.head.vocab, + }) + } +} diff --git a/crates/cuda-driver/src/native_head/impl_originalnativeheadrows/impl_originalnativeheadrows_2_2.rs b/crates/cuda-driver/src/native_head/impl_originalnativeheadrows/impl_originalnativeheadrows_2_2.rs new file mode 100644 index 00000000..096ddc73 --- /dev/null +++ b/crates/cuda-driver/src/native_head/impl_originalnativeheadrows/impl_originalnativeheadrows_2_2.rs @@ -0,0 +1,239 @@ +//! Moved out of the parent module by STRA-338: impl OriginalNativeHeadRows (2). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalNativeHeadRows<'ctx> { + pub(in super::super) fn sample_commands( + &self, + p: SamplerParams, + history: Option<&DeviceBuffer<'ctx>>, + history_len: usize, + path: SamplerPath, + stream_key: usize, + ) -> Result> { + let history = history.map(address).transpose()?.unwrap_or(0); + let logits = address(self.buffer(&self.logits)?)?; + let output = self.output_address()?; + let v = self.head.vocab as i32; + let t = self.t as i32; + let shared = if history != 0 && history_len > 0 && p.penalty_last_n > 0 { + self.head.vocab.div_ceil(32) * 4 + } else { + 0 + }; + let mut c = Vec::new(); + c.try_reserve_exact(2).map_err(|_| Error::HostAllocation)?; + if p.greedy || p.temperature <= 0.0 { + c.push(Command::new( + greedy_entry(), + [self.t as u32, 1, 1], + [1024, 1, 1], + shared.try_into().map_err(|_| Error::InvalidSize)?, + vec![ + Arg::Address(logits), + Arg::I32(v), + Arg::Address(history), + Arg::I32(history_len.try_into().map_err(|_| Error::InvalidSize)?), + Arg::Params(p), + Arg::I32(p.penalty_last_n), + Arg::I32(p.penalty_last_n), + Arg::Address(output), + ], + )?); + } else if path == SamplerPath::Old { + c.push(Command::new( + "sampler_kernel", + [self.t as u32, 1, 1], + [1024, 1, 1], + shared as u32, + vec![ + Arg::Address(logits), + Arg::I32(v), + Arg::I32(t), + Arg::Address(history), + Arg::I32(history_len as i32), + Arg::Params(p), + Arg::Address(output), + ], + )?); + } else { + let blocks = self.head.vocab.div_ceil(4096); + let scratch = if path == SamplerPath::Split && blocks <= 64 { + self.split_scratch(stream_key, 16 * blocks * 64)? + } else { + None + }; + if let Some(scratch) = scratch { + let k = if p.top_k > 0 && p.top_k < 64 { + p.top_k + } else { + 64 + } + .min(v); + c.push(cmd( + "sampler_split_part_kernel", + [blocks as u32, self.t as u32, 1], + [128, 1, 1], + vec![ + Arg::Address(logits), + Arg::I32(v), + Arg::Address(history), + Arg::I32(history_len as i32), + Arg::Params(p), + Arg::I32(k), + Arg::I32(blocks as i32), + Arg::Address(scratch), + ], + )?); + c.push(cmd( + "sampler_split_merge_kernel", + [self.t as u32, 1, 1], + [32, 1, 1], + vec![ + Arg::Address(scratch), + Arg::I32(blocks as i32), + Arg::I32(v), + Arg::Params(p), + Arg::I32(k), + Arg::Address(output), + ], + )?); + } else { + c.push(Command::new( + "sampler_one_block_kernel", + [self.t as u32, 1, 1], + [1024, 1, 1], + shared as u32, + vec![ + Arg::Address(logits), + Arg::I32(v), + Arg::Address(history), + Arg::I32(history_len as i32), + Arg::Params(p), + Arg::Address(output), + ], + )?); + } + } + Ok(c) + } + pub(in super::super) fn split_scratch(&self, stream_key: usize, entries: usize) -> Result> { + const CAP: usize = 64 * 64 * 64; + if entries == 0 || entries > CAP { + return Ok(None); + } + // Same per-(device, actual stream) lifetime as Original. All fixed-T banks + // share this model owner; streams never share a scratch buffer. + let mut slots = self + .head + .sampling + .try_borrow_mut() + .map_err(|_| Error::InvalidQwenShape)?; + let at = match slots.iter().position(|slot| slot.stream == stream_key) { + Some(at) => at, + None => { + slots + .try_reserve_exact(1) + .map_err(|_| Error::HostAllocation)?; + slots.push(SamplingScratch { + stream: stream_key, + buffer: None, + entries: 0, + failed: 0, + retired: Vec::new(), + }); + slots.len() - 1 + } + }; + let slot = &mut slots[at]; + if slot.entries >= entries { + return slot.buffer.as_ref().map(address).transpose(); + } + if slot.failed != 0 && entries >= slot.failed { + return Ok(None); + } + slot.retired + .try_reserve_exact(1) + .map_err(|_| Error::HostAllocation)?; + let want = (2 * slot.entries).min(CAP).max(entries); + for n in [want, entries] { + // Admission refusal is the original allocation-failure fallback; do not + // swallow a physical-query/Context failure as an allocation shortage. + if let Err(e) = admission(self.head.context, n * 8) { + if matches!(e, Error::BudgetExceeded) { + continue; + } + return Err(e); + } + match self.head.context.allocate(n * 8) { + Ok(b) => { + if let Some(old) = slot.buffer.replace(b) { + slot.retired.push(old); + } + slot.entries = n; + return slot.buffer.as_ref().map(address).transpose(); + } + Err(Error::BudgetExceeded) + | Err(Error::Driver { + operation: "cuMemAlloc_v2", + code: 2, + }) => {} + Err(e) => return Err(e), + } + } + slot.failed = entries; + Ok(None) + } + /// Actual ALL-row logits, only after caller's genuine graph/flight completion. + pub(crate) fn completed_logits(&self) -> Result<&DeviceBuffer<'ctx>> { + self.validate_context(self.head.context)?; + self.buffer(&self.logits) + } + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + pub(in super::super) fn close_inner(&mut self) -> Result<()> { + if self.mixed.is_none() + && self.q8.is_none() + && self.logits.is_none() + && self.mapped.is_none() + { + return Ok(()); + } + self.failed.set(true); + let context = self.head.context; + let sync = context.synchronize(); + if sync.is_err() || context.is_poisoned() { + context.poison(); + context.retain_driver(); + for b in [self.mixed.take(), self.q8.take(), self.logits.take()] + .into_iter() + .flatten() + { + std::mem::forget(b); + } + if let Some(m) = self.mapped.take() { + std::mem::forget(m); + } + std::mem::forget(std::mem::take(self.commands.get_mut())); + return combine(sync, Err(Error::ContextPoisoned)); + } + self.commands.get_mut().clear(); + let mut result = Ok(()); + for b in [self.mixed.take(), self.q8.take(), self.logits.take()] + .into_iter() + .flatten() + { + result = combine(result, b.release()); + } + let guard = context.enter()?; + let mapped = self.mapped.take().map_or(Ok(()), |mut m| m.close()); + let pop = guard.finish(); + if mapped.is_err() || pop.is_err() { + context.poison(); + } + combine(combine(result, mapped), pop) + } +} diff --git a/crates/cuda-driver/src/native_parity/impl_nativeparity.rs b/crates/cuda-driver/src/native_parity/impl_nativeparity.rs index ad5c0b70..74667c1e 100644 --- a/crates/cuda-driver/src/native_parity/impl_nativeparity.rs +++ b/crates/cuda-driver/src/native_parity/impl_nativeparity.rs @@ -3,426 +3,5 @@ #[allow(unused_imports)] use super::*; -impl<'ctx> NativeParity<'ctx> { - pub(super) fn new(context: &'ctx Context<'ctx>) -> BenchResult { - let ptx = sealed_ptx().ok_or("Original parity asset is unsealed")?; - let guard = message(context.enter())?; - let api = message(Api::load())?; - let stream = match message(api.create()) { - Ok(s) => s, - Err(e) => return first(Err(e), message(guard.finish())), - }; - let module = match message(api.module(ptx)) { - Ok(m) => m, - Err(e) => { - let cleanup = message(api.destroy(stream)); - return first(first(Err(e), cleanup), message(guard.finish())); - } - }; - let mut state = State { - context, - api: Some(api), - stream: Cell::new(Some(stream)), - module: Cell::new(Some(module)), - pending: Cell::new(false), - failed: Cell::new(false), - active: Cell::new(false), - commands: RefCell::new(Vec::new()), - staging: RefCell::new(Vec::new()), - entries: Vec::new(), - }; - let admit = (|| { - state - .entries - .try_reserve_exact(ENTRIES.len()) - .map_err(|_| "parity function allocation")?; - for &name in ENTRIES { - let c = CString::new(name).map_err(|_| "parity entry NUL")?; - state.entries.push(( - name, - message(state.api.as_ref().ok_or("parity ABI")?.function(module, &c))?, - )); - } - Ok(()) - })(); - let pop = message(guard.finish()); - if pop.is_err() { - state.uncertain(); - } - first(admit, pop)?; - let old = std::env::var_os("STRATA_OLD_IQ_MMVQ").is_some_and(|x| { - #[cfg(unix)] - use std::os::unix::ffi::OsStrExt; - #[cfg(unix)] - let b = x.as_bytes(); - #[cfg(not(unix))] - let b = x.as_encoded_bytes(); - !b.is_empty() && b[0] != b'0' - }); - Ok(Self { - state: Rc::new(state), - old, - }) - } - pub(super) fn idle(&self) -> BenchResult<()> { - self.state.healthy()?; - if self.state.active.get() { - Err("Original parity expert still owned".into()) - } else { - Ok(()) - } - } - pub(super) fn expert(&self, e: &NativeParityExpert<'ctx>) -> BenchResult<()> { - self.state.healthy()?; - if !Rc::ptr_eq(&self.state, &e.state) || e.buffers.len() != 10 { - Err("foreign Original parity expert".into()) - } else { - Ok(()) - } - } - pub fn old_kernels(&self) -> bool { - self.old - } - pub fn set_old_kernels(&mut self, old: bool) { - self.old = old; - } - pub fn prepare_expert( - &mut self, - gu: i32, - down: i32, - blob: &[u8], - input: &[f32], - ) -> BenchResult> { - self.idle()?; - let l = layout(gu, down)?; - if blob.len() != l.bytes as usize || input.len() != NT * H { - return Err("Original parity expert extent".into()); - } - let mut e = NativeParityExpert { - state: self.state.clone(), - layout: l, - buffers: Vec::new(), - diagnostic: RefCell::new(Vec::new()), - enqueued: Cell::new(false), - }; - self.state.active.set(true); - let prepare = (|| { - e.buffers - .try_reserve_exact(10) - .map_err(|_| "parity expert directory")?; - for n in [ - blob.len(), - NT * H * 4, - NT * (H / 32) * 36, - 25344, - NT * H * 4, - 8, - 8, - 4, - NT * 4, - NT * 4, - ] { - e.buffers.push(message(self.state.context.allocate(n))?); - } - self.state.upload(&e.buffers[0], blob)?; - self.state.upload(&e.buffers[1], &bytes_f32(input)?)?; - self.state.upload( - &e.buffers[5], - &address(&e.buffers[0], 0, blob.len())?.to_le_bytes(), - )?; - self.state - .upload(&e.buffers[6], &bytes_i32(&[0, NT as i32])?)?; - self.state.upload(&e.buffers[7], &1i32.to_le_bytes())?; - self.state.upload(&e.buffers[8], &bytes_i32(&[0, 1, 2])?)?; - self.state.upload(&e.buffers[9], &bytes_i32(&[0, 1, 2])?)?; - self.state.enqueue(vec![command( - "parity_quant", - [30, 1, 1], - [256, 1, 1], - vec![ - Arg::Address(address(&e.buffers[1], 0, NT * H * 4)?), - Arg::Address(address(&e.buffers[2], 0, NT * (H / 32) * 36)?), - Arg::I64((NT * H) as i64), - ], - )?]) - })(); - if let Err(err) = prepare { - return first(Err(err), e.release()); - } - Ok(e) - } - pub fn enqueue_expert(&mut self, e: &mut NativeParityExpert<'ctx>) -> BenchResult<()> { - self.expert(e)?; - if e.enqueued.get() { - return Err("download required before another Original expert launch".into()); - } - let b = &e.buffers; - let l = e.layout; - let gate = address(&b[3], 0, 7680)?; - let up = address(&b[3], 7680, 7680)?; - let hidden = address(&b[3], 15360, 7680)?; - let hq = address(&b[3], 23040, 2160)?; - let gu = gu_entry(l.gu, !self.old && split(l.gu))?; - let down = down_entry(l.down, !self.old && split(l.down))?; - let args = || -> BenchResult> { - Ok(vec![ - Arg::Address(address(&b[5], 0, 8)?), - Arg::Address(address(&b[6], 0, 8)?), - Arg::Address(address(&b[7], 0, 4)?), - ]) - }; - let mut g = args()?; - g.extend([ - Arg::Address(address(&b[9], 0, 12)?), - Arg::Address(address(&b[2], 0, 8640)?), - Arg::Layout(l), - Arg::Address(gate), - Arg::Address(up), - ]); - let mut d = args()?; - d.extend([ - Arg::Address(address(&b[8], 0, 12)?), - Arg::Address(hq), - Arg::Layout(l), - Arg::Address(address(&b[4], 0, NT * H * 4)?), - ]); - let cmds = vec![ - command(gu, [160, 1, 1], [256, 1, 1], g)?, - command( - "parity_swiglu", - [8, 1, 1], - [256, 1, 1], - vec![ - Arg::Address(gate), - Arg::Address(up), - Arg::Address(hidden), - Arg::I64(1920), - ], - )?, - command( - "parity_quant", - [8, 1, 1], - [256, 1, 1], - vec![Arg::Address(hidden), Arg::Address(hq), Arg::I64(1920)], - )?, - command(down, [320, 1, 1], [256, 1, 1], d)?, - ]; - self.state.enqueue(cmds)?; - e.enqueued.set(true); - Ok(()) - } - pub fn download_expert(&mut self, e: &mut NativeParityExpert<'ctx>) -> BenchResult> { - self.expert(e)?; - if !e.enqueued.get() { - return Err("Original expert was not enqueued".into()); - } - self.state.drain()?; - let v = floats(read(&self.state, &e.buffers[4], NT * H * 4)?)?; - e.enqueued.set(false); - Ok(v) - } - pub fn dequantize_expert_role( - &mut self, - e: &NativeParityExpert<'ctx>, - role: usize, - ) -> BenchResult<(Vec, Vec)> { - self.expert(e)?; - if role >= 3 || e.enqueued.get() { - return Err("Original dequant role or pending expert".into()); - } - e.diagnostics()?; - let diag = e.diagnostic.borrow(); - let (ty, off, nbytes) = match role { - 0 => (e.layout.gu, 0, e.layout.up as usize), - 1 => (e.layout.gu, e.layout.up as usize, e.layout.up as usize), - _ => ( - e.layout.down, - e.layout.d as usize, - e.layout.bytes as usize - e.layout.d as usize, - ), - }; - let a = address(&e.buffers[0], off, nbytes)?; - self.state.enqueue(vec![ - command( - "parity_dequant_f32", - [6400, 1, 1], - [32, 1, 1], - vec![ - Arg::I32(ty), - Arg::Address(a), - Arg::Address(address(&diag[0], 0, H * FF * 4)?), - ], - )?, - command( - "parity_dequant_f16", - [6400, 1, 1], - [32, 1, 1], - vec![ - Arg::I32(ty), - Arg::Address(a), - Arg::Address(address(&diag[1], 0, H * FF * 2)?), - ], - )?, - ])?; - self.state.drain()?; - let f = floats(read(&self.state, &diag[0], H * FF * 4)?)?; - let raw = read(&self.state, &diag[1], H * FF * 2)?; - let mut h = Vec::new(); - h.try_reserve_exact(H * FF) - .map_err(|_| "half readback allocation")?; - for v in raw.chunks_exact(2) { - h.push(u16::from_le_bytes([v[0], v[1]])); - } - Ok((f, h)) - } - pub fn embed_expert_gate( - &mut self, - e: &NativeParityExpert<'ctx>, - rows: &[i32], - ) -> BenchResult> { - self.expert(e)?; - if rows.len() != FF - || rows - .iter() - .enumerate() - .any(|(i, &r)| r != (FF - 1 - i) as i32) - || e.enqueued.get() - { - return Err("Original gate embedding token extent/order".into()); - } - e.diagnostics()?; - let diag = e.diagnostic.borrow(); - self.state.enqueue(vec![command( - "parity_embed", - [10, FF as u32, 1], - [32, 1, 1], - vec![ - Arg::I32(e.layout.gu), - Arg::Address(address(&e.buffers[0], 0, e.layout.up as usize)?), - Arg::U64(e.layout.gu_row), - Arg::Address(address(&diag[2], 0, FF * 4)?), - Arg::I64(H as i64), - Arg::Address(address(&diag[0], 0, H * FF * 4)?), - ], - )?])?; - self.state.drain()?; - floats(read(&self.state, &diag[0], H * FF * 4)?) - } - pub fn release_expert(&mut self, e: NativeParityExpert<'ctx>) -> BenchResult<()> { - if !Rc::ptr_eq(&self.state, &e.state) { - return Err("foreign Original expert release".into()); - } - e.release() - } - pub fn q5_one_min( - &mut self, - weights: &[u8], - input: &[f32], - ) -> BenchResult<(Vec, Vec)> { - self.idle()?; - if weights.len() != 64 * 20 * 24 || input.len() != 640 { - return Err("Original Q5_1 extent".into()); - } - let mut owned = Temporary::new(self.state.clone())?; - let result = (|| { - for n in [weights.len(), 640 * 4, 720, 64 * 4] { - owned.buffers.push(message(self.state.context.allocate(n))?); - } - let b = &owned.buffers; - self.state.upload(&b[0], weights)?; - self.state.upload(&b[1], &bytes_f32(input)?)?; - self.state.enqueue(vec![ - command( - "parity_quant", - [3, 1, 1], - [256, 1, 1], - vec![ - Arg::Address(address(&b[1], 0, 2560)?), - Arg::Address(address(&b[2], 0, 720)?), - Arg::I64(640), - ], - )?, - command( - "parity_mmvq_7", - [16, 1, 1], - [32, 4, 1], - vec![ - Arg::Address(address(&b[0], 0, weights.len())?), - Arg::U64(480), - Arg::Address(address(&b[2], 0, 720)?), - Arg::Address(address(&b[3], 0, 256)?), - Arg::I32(640), - Arg::I32(64), - Arg::I32(1), - ], - )?, - ])?; - self.state.drain()?; - Ok(( - floats(read(&self.state, &b[3], 256)?)?, - read(&self.state, &b[2], 720)?, - )) - })(); - first(result, owned.release()) - } - pub fn bf16_embedding( - &mut self, - table: &[u16], - ids: &[i32], - ) -> BenchResult<(Vec, Vec)> { - self.idle()?; - if table.len() != 61 * H || ids.len() != 97 || ids.iter().any(|&i| !(0..61).contains(&i)) { - return Err("Original BF16 embedding extent".into()); - } - let mut owned = Temporary::new(self.state.clone())?; - let result = (|| { - for n in [61 * H * 2, 97 * 4, 97 * H * 4] { - owned.buffers.push(message(self.state.context.allocate(n))?); - } - let b = &owned.buffers; - let mut raw = Vec::new(); - raw.try_reserve_exact(table.len() * 2) - .map_err(|_| "BF16 staging allocation")?; - for h in table { - raw.extend_from_slice(&h.to_le_bytes()); - } - self.state.upload(&b[0], &raw)?; - self.state.upload(&b[1], &bytes_i32(ids)?)?; - self.state.enqueue(vec![command( - "parity_embed", - [10, 97, 1], - [32, 1, 1], - vec![ - Arg::I32(30), - Arg::Address(address(&b[0], 0, 61 * H * 2)?), - Arg::U64((H * 2) as u64), - Arg::Address(address(&b[1], 0, 97 * 4)?), - Arg::I64(H as i64), - Arg::Address(address(&b[2], 0, 97 * H * 4)?), - ], - )?])?; - self.state.drain()?; - let gather = floats(read(&self.state, &b[2], 97 * H * 4)?)?; - self.state.enqueue(vec![command( - "parity_dequant_f32", - [610, 1, 1], - [32, 1, 1], - vec![ - Arg::I32(30), - Arg::Address(address(&b[0], 0, 61 * H * 2)?), - Arg::Address(address(&b[2], 0, 61 * H * 4)?), - ], - )?])?; - self.state.drain()?; - Ok((gather, floats(read(&self.state, &b[2], 61 * H * 4)?)?)) - })(); - first(result, owned.release()) - } - pub fn close(self) -> BenchResult<()> { - if Rc::strong_count(&self.state) != 1 { - return Err("Original parity expert still owned at close".into()); - } - let mut s = Rc::try_unwrap(self.state).map_err(|_| "parity owner shared")?; - s.close() - } -} +mod impl_nativeparity_2; +mod impl_nativeparity_2_2; diff --git a/crates/cuda-driver/src/native_parity/impl_nativeparity/impl_nativeparity_2.rs b/crates/cuda-driver/src/native_parity/impl_nativeparity/impl_nativeparity_2.rs new file mode 100644 index 00000000..0af6435e --- /dev/null +++ b/crates/cuda-driver/src/native_parity/impl_nativeparity/impl_nativeparity_2.rs @@ -0,0 +1,225 @@ +//! Moved out of the parent module by STRA-338: impl NativeParity. + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> NativeParity<'ctx> { + pub(in super::super) fn new(context: &'ctx Context<'ctx>) -> BenchResult { + let ptx = sealed_ptx().ok_or("Original parity asset is unsealed")?; + let guard = message(context.enter())?; + let api = message(Api::load())?; + let stream = match message(api.create()) { + Ok(s) => s, + Err(e) => return first(Err(e), message(guard.finish())), + }; + let module = match message(api.module(ptx)) { + Ok(m) => m, + Err(e) => { + let cleanup = message(api.destroy(stream)); + return first(first(Err(e), cleanup), message(guard.finish())); + } + }; + let mut state = State { + context, + api: Some(api), + stream: Cell::new(Some(stream)), + module: Cell::new(Some(module)), + pending: Cell::new(false), + failed: Cell::new(false), + active: Cell::new(false), + commands: RefCell::new(Vec::new()), + staging: RefCell::new(Vec::new()), + entries: Vec::new(), + }; + let admit = (|| { + state + .entries + .try_reserve_exact(ENTRIES.len()) + .map_err(|_| "parity function allocation")?; + for &name in ENTRIES { + let c = CString::new(name).map_err(|_| "parity entry NUL")?; + state.entries.push(( + name, + message(state.api.as_ref().ok_or("parity ABI")?.function(module, &c))?, + )); + } + Ok(()) + })(); + let pop = message(guard.finish()); + if pop.is_err() { + state.uncertain(); + } + first(admit, pop)?; + let old = std::env::var_os("STRATA_OLD_IQ_MMVQ").is_some_and(|x| { + #[cfg(unix)] + use std::os::unix::ffi::OsStrExt; + #[cfg(unix)] + let b = x.as_bytes(); + #[cfg(not(unix))] + let b = x.as_encoded_bytes(); + !b.is_empty() && b[0] != b'0' + }); + Ok(Self { + state: Rc::new(state), + old, + }) + } + pub(in super::super) fn idle(&self) -> BenchResult<()> { + self.state.healthy()?; + if self.state.active.get() { + Err("Original parity expert still owned".into()) + } else { + Ok(()) + } + } + pub(in super::super) fn expert(&self, e: &NativeParityExpert<'ctx>) -> BenchResult<()> { + self.state.healthy()?; + if !Rc::ptr_eq(&self.state, &e.state) || e.buffers.len() != 10 { + Err("foreign Original parity expert".into()) + } else { + Ok(()) + } + } + pub fn old_kernels(&self) -> bool { + self.old + } + pub fn set_old_kernels(&mut self, old: bool) { + self.old = old; + } + pub fn prepare_expert( + &mut self, + gu: i32, + down: i32, + blob: &[u8], + input: &[f32], + ) -> BenchResult> { + self.idle()?; + let l = layout(gu, down)?; + if blob.len() != l.bytes as usize || input.len() != NT * H { + return Err("Original parity expert extent".into()); + } + let mut e = NativeParityExpert { + state: self.state.clone(), + layout: l, + buffers: Vec::new(), + diagnostic: RefCell::new(Vec::new()), + enqueued: Cell::new(false), + }; + self.state.active.set(true); + let prepare = (|| { + e.buffers + .try_reserve_exact(10) + .map_err(|_| "parity expert directory")?; + for n in [ + blob.len(), + NT * H * 4, + NT * (H / 32) * 36, + 25344, + NT * H * 4, + 8, + 8, + 4, + NT * 4, + NT * 4, + ] { + e.buffers.push(message(self.state.context.allocate(n))?); + } + self.state.upload(&e.buffers[0], blob)?; + self.state.upload(&e.buffers[1], &bytes_f32(input)?)?; + self.state.upload( + &e.buffers[5], + &address(&e.buffers[0], 0, blob.len())?.to_le_bytes(), + )?; + self.state + .upload(&e.buffers[6], &bytes_i32(&[0, NT as i32])?)?; + self.state.upload(&e.buffers[7], &1i32.to_le_bytes())?; + self.state.upload(&e.buffers[8], &bytes_i32(&[0, 1, 2])?)?; + self.state.upload(&e.buffers[9], &bytes_i32(&[0, 1, 2])?)?; + self.state.enqueue(vec![command( + "parity_quant", + [30, 1, 1], + [256, 1, 1], + vec![ + Arg::Address(address(&e.buffers[1], 0, NT * H * 4)?), + Arg::Address(address(&e.buffers[2], 0, NT * (H / 32) * 36)?), + Arg::I64((NT * H) as i64), + ], + )?]) + })(); + if let Err(err) = prepare { + return first(Err(err), e.release()); + } + Ok(e) + } + pub fn enqueue_expert(&mut self, e: &mut NativeParityExpert<'ctx>) -> BenchResult<()> { + self.expert(e)?; + if e.enqueued.get() { + return Err("download required before another Original expert launch".into()); + } + let b = &e.buffers; + let l = e.layout; + let gate = address(&b[3], 0, 7680)?; + let up = address(&b[3], 7680, 7680)?; + let hidden = address(&b[3], 15360, 7680)?; + let hq = address(&b[3], 23040, 2160)?; + let gu = gu_entry(l.gu, !self.old && split(l.gu))?; + let down = down_entry(l.down, !self.old && split(l.down))?; + let args = || -> BenchResult> { + Ok(vec![ + Arg::Address(address(&b[5], 0, 8)?), + Arg::Address(address(&b[6], 0, 8)?), + Arg::Address(address(&b[7], 0, 4)?), + ]) + }; + let mut g = args()?; + g.extend([ + Arg::Address(address(&b[9], 0, 12)?), + Arg::Address(address(&b[2], 0, 8640)?), + Arg::Layout(l), + Arg::Address(gate), + Arg::Address(up), + ]); + let mut d = args()?; + d.extend([ + Arg::Address(address(&b[8], 0, 12)?), + Arg::Address(hq), + Arg::Layout(l), + Arg::Address(address(&b[4], 0, NT * H * 4)?), + ]); + let cmds = vec![ + command(gu, [160, 1, 1], [256, 1, 1], g)?, + command( + "parity_swiglu", + [8, 1, 1], + [256, 1, 1], + vec![ + Arg::Address(gate), + Arg::Address(up), + Arg::Address(hidden), + Arg::I64(1920), + ], + )?, + command( + "parity_quant", + [8, 1, 1], + [256, 1, 1], + vec![Arg::Address(hidden), Arg::Address(hq), Arg::I64(1920)], + )?, + command(down, [320, 1, 1], [256, 1, 1], d)?, + ]; + self.state.enqueue(cmds)?; + e.enqueued.set(true); + Ok(()) + } + pub fn download_expert(&mut self, e: &mut NativeParityExpert<'ctx>) -> BenchResult> { + self.expert(e)?; + if !e.enqueued.get() { + return Err("Original expert was not enqueued".into()); + } + self.state.drain()?; + let v = floats(read(&self.state, &e.buffers[4], NT * H * 4)?)?; + e.enqueued.set(false); + Ok(v) + } +} diff --git a/crates/cuda-driver/src/native_parity/impl_nativeparity/impl_nativeparity_2_2.rs b/crates/cuda-driver/src/native_parity/impl_nativeparity/impl_nativeparity_2_2.rs new file mode 100644 index 00000000..88f41401 --- /dev/null +++ b/crates/cuda-driver/src/native_parity/impl_nativeparity/impl_nativeparity_2_2.rs @@ -0,0 +1,212 @@ +//! Moved out of the parent module by STRA-338: impl NativeParity (2). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> NativeParity<'ctx> { + pub fn dequantize_expert_role( + &mut self, + e: &NativeParityExpert<'ctx>, + role: usize, + ) -> BenchResult<(Vec, Vec)> { + self.expert(e)?; + if role >= 3 || e.enqueued.get() { + return Err("Original dequant role or pending expert".into()); + } + e.diagnostics()?; + let diag = e.diagnostic.borrow(); + let (ty, off, nbytes) = match role { + 0 => (e.layout.gu, 0, e.layout.up as usize), + 1 => (e.layout.gu, e.layout.up as usize, e.layout.up as usize), + _ => ( + e.layout.down, + e.layout.d as usize, + e.layout.bytes as usize - e.layout.d as usize, + ), + }; + let a = address(&e.buffers[0], off, nbytes)?; + self.state.enqueue(vec![ + command( + "parity_dequant_f32", + [6400, 1, 1], + [32, 1, 1], + vec![ + Arg::I32(ty), + Arg::Address(a), + Arg::Address(address(&diag[0], 0, H * FF * 4)?), + ], + )?, + command( + "parity_dequant_f16", + [6400, 1, 1], + [32, 1, 1], + vec![ + Arg::I32(ty), + Arg::Address(a), + Arg::Address(address(&diag[1], 0, H * FF * 2)?), + ], + )?, + ])?; + self.state.drain()?; + let f = floats(read(&self.state, &diag[0], H * FF * 4)?)?; + let raw = read(&self.state, &diag[1], H * FF * 2)?; + let mut h = Vec::new(); + h.try_reserve_exact(H * FF) + .map_err(|_| "half readback allocation")?; + for v in raw.chunks_exact(2) { + h.push(u16::from_le_bytes([v[0], v[1]])); + } + Ok((f, h)) + } + pub fn embed_expert_gate( + &mut self, + e: &NativeParityExpert<'ctx>, + rows: &[i32], + ) -> BenchResult> { + self.expert(e)?; + if rows.len() != FF + || rows + .iter() + .enumerate() + .any(|(i, &r)| r != (FF - 1 - i) as i32) + || e.enqueued.get() + { + return Err("Original gate embedding token extent/order".into()); + } + e.diagnostics()?; + let diag = e.diagnostic.borrow(); + self.state.enqueue(vec![command( + "parity_embed", + [10, FF as u32, 1], + [32, 1, 1], + vec![ + Arg::I32(e.layout.gu), + Arg::Address(address(&e.buffers[0], 0, e.layout.up as usize)?), + Arg::U64(e.layout.gu_row), + Arg::Address(address(&diag[2], 0, FF * 4)?), + Arg::I64(H as i64), + Arg::Address(address(&diag[0], 0, H * FF * 4)?), + ], + )?])?; + self.state.drain()?; + floats(read(&self.state, &diag[0], H * FF * 4)?) + } + pub fn release_expert(&mut self, e: NativeParityExpert<'ctx>) -> BenchResult<()> { + if !Rc::ptr_eq(&self.state, &e.state) { + return Err("foreign Original expert release".into()); + } + e.release() + } + pub fn q5_one_min( + &mut self, + weights: &[u8], + input: &[f32], + ) -> BenchResult<(Vec, Vec)> { + self.idle()?; + if weights.len() != 64 * 20 * 24 || input.len() != 640 { + return Err("Original Q5_1 extent".into()); + } + let mut owned = Temporary::new(self.state.clone())?; + let result = (|| { + for n in [weights.len(), 640 * 4, 720, 64 * 4] { + owned.buffers.push(message(self.state.context.allocate(n))?); + } + let b = &owned.buffers; + self.state.upload(&b[0], weights)?; + self.state.upload(&b[1], &bytes_f32(input)?)?; + self.state.enqueue(vec![ + command( + "parity_quant", + [3, 1, 1], + [256, 1, 1], + vec![ + Arg::Address(address(&b[1], 0, 2560)?), + Arg::Address(address(&b[2], 0, 720)?), + Arg::I64(640), + ], + )?, + command( + "parity_mmvq_7", + [16, 1, 1], + [32, 4, 1], + vec![ + Arg::Address(address(&b[0], 0, weights.len())?), + Arg::U64(480), + Arg::Address(address(&b[2], 0, 720)?), + Arg::Address(address(&b[3], 0, 256)?), + Arg::I32(640), + Arg::I32(64), + Arg::I32(1), + ], + )?, + ])?; + self.state.drain()?; + Ok(( + floats(read(&self.state, &b[3], 256)?)?, + read(&self.state, &b[2], 720)?, + )) + })(); + first(result, owned.release()) + } + pub fn bf16_embedding( + &mut self, + table: &[u16], + ids: &[i32], + ) -> BenchResult<(Vec, Vec)> { + self.idle()?; + if table.len() != 61 * H || ids.len() != 97 || ids.iter().any(|&i| !(0..61).contains(&i)) { + return Err("Original BF16 embedding extent".into()); + } + let mut owned = Temporary::new(self.state.clone())?; + let result = (|| { + for n in [61 * H * 2, 97 * 4, 97 * H * 4] { + owned.buffers.push(message(self.state.context.allocate(n))?); + } + let b = &owned.buffers; + let mut raw = Vec::new(); + raw.try_reserve_exact(table.len() * 2) + .map_err(|_| "BF16 staging allocation")?; + for h in table { + raw.extend_from_slice(&h.to_le_bytes()); + } + self.state.upload(&b[0], &raw)?; + self.state.upload(&b[1], &bytes_i32(ids)?)?; + self.state.enqueue(vec![command( + "parity_embed", + [10, 97, 1], + [32, 1, 1], + vec![ + Arg::I32(30), + Arg::Address(address(&b[0], 0, 61 * H * 2)?), + Arg::U64((H * 2) as u64), + Arg::Address(address(&b[1], 0, 97 * 4)?), + Arg::I64(H as i64), + Arg::Address(address(&b[2], 0, 97 * H * 4)?), + ], + )?])?; + self.state.drain()?; + let gather = floats(read(&self.state, &b[2], 97 * H * 4)?)?; + self.state.enqueue(vec![command( + "parity_dequant_f32", + [610, 1, 1], + [32, 1, 1], + vec![ + Arg::I32(30), + Arg::Address(address(&b[0], 0, 61 * H * 2)?), + Arg::Address(address(&b[2], 0, 61 * H * 4)?), + ], + )?])?; + self.state.drain()?; + Ok((gather, floats(read(&self.state, &b[2], 61 * H * 4)?)?)) + })(); + first(result, owned.release()) + } + pub fn close(self) -> BenchResult<()> { + if Rc::strong_count(&self.state) != 1 { + return Err("Original parity expert still owned at close".into()); + } + let mut s = Rc::try_unwrap(self.state).map_err(|_| "parity owner shared")?; + s.close() + } +} diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice.rs index 19c9a50e..537f45e7 100644 --- a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice.rs +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice.rs @@ -3,1255 +3,10 @@ #[allow(unused_imports)] use super::*; - -impl<'ctx> OriginalPromptDevice<'ctx> { - pub fn device_bytes(capacity: usize) -> Result { - if !(1..=8192).contains(&capacity) { - return Err(Error::InvalidQwenShape); - } - capacity.checked_mul(40).ok_or(Error::BudgetExceeded) - } - pub(super) fn new( - context: &'ctx Context<'ctx>, - capacity: usize, - mode: PleBf16Mode, - profile: GrNativeProfile, - ) -> Result { - let count = Self::device_bytes(capacity)?; - // Separate new precise PLE arithmetic asset must be genuinely sealed. - if PLE_PTX.len() < 2 - || PLE_PTX.last() != Some(&0) - || PLE_PTX[..PLE_PTX.len() - 1].contains(&0) - || crate::qwen_ffi::sha256(&PLE_PTX[..PLE_PTX.len() - 1]) != PLE_SHA - || GR_PTX.len() < 2 - || GR_PTX.last() != Some(&0) - || GR_PTX[..GR_PTX.len() - 1].contains(&0) - || crate::qwen_ffi::sha256(&GR_PTX[..GR_PTX.len() - 1]) != GR_SHA - || crate::prefill_stage::admit().is_err() - { - return Err(Error::UnsupportedQwenOperation); - } - if context.is_poisoned() { - return Err(Error::ContextPoisoned); - } - let required = count.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; - if context - .allocated_bytes() - .checked_add(required) - .is_none_or(|x| x > context.budget_bytes()) - || context.memory_info()?.0 < required - { - return Err(Error::BudgetExceeded); - } - let mut owner = Self { - context, - capacity, - mode, - profile, - status: None, - pack: None, - ple: None, - gr: None, - stage: None, - stage_scratch: None, - profile_tag: "prompt", - failed: false, - }; - let operation = (|| -> Result<()> { - owner.status = Some(context.allocate(count)?); - let guard = match context.enter() { - Ok(g) => g, - Err(e) => { - context.poison(); - context.retain_driver(); - return Err(e); - } - }; - let load = (|| -> Result<()> { - owner.pack = Some(KernelModule::load(PACK_PTX, &[c"ple_pack"])?); - owner.ple = Some(KernelModule::load(PLE_PTX, PLE_ENTRIES)?); - owner.gr = Some(KernelModule::load(GR_PTX, GR_ENTRIES)?); - owner.stage = Some(KernelModule::load( - crate::prefill_stage::PTX, - crate::prefill_stage::ENTRIES, - )?); - Ok(()) - })(); - let pop = guard.finish(); - if pop.is_err() { - context.poison(); - context.retain_driver() - } - combine(load, pop)?; - if context.memory_info()?.0 < RESERVE { - return Err(Error::BudgetExceeded); - } - Ok(()) - })(); - if let Err(e) = operation { - let _ = owner.close(); - return Err(e); - } - Ok(owner) - } - pub fn allocated_bytes(&self) -> usize { - self.status.as_ref().map_or(0, DeviceBuffer::len) - } - pub fn is_failed(&self) -> bool { - self.failed || self.context.is_poisoned() - } - pub(super) fn status(&self) -> Result { - if self.is_failed() { - return Err(Error::ContextPoisoned); - } - let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?; - if b.len() != self.capacity * 40 || !std::ptr::eq(b.context, self.context) { - return Err(Error::InvalidQwenShape); - } - let h = b.handle.ok_or(Error::ContextPoisoned)?; - h.validate_projection_extent(b.len(), 4)?; - Ok(h) - } - pub(super) fn validate( - &self, - rows: &OriginalPromptRows<'_, '_, '_>, - workspace: &NativeBatchWorkspace<'_>, - ) -> Result<()> { - if self.is_failed() || rows.is_failed() { - return Err(Error::ContextPoisoned); - } - if !std::ptr::eq(self.context, rows.context()) { - return Err(Error::ContextMismatch); - } - if rows.rows() > self.capacity { - return Err(Error::InvalidQwenShape); - } - workspace.validate_context(self.context)?; - workspace.reject_alias(self.status()?, self.capacity * 40)?; - // All whole common spans used by this owner must be actual disjoint - // arena spans, not fresh handles minted from addresses. - for role in [ - S::R, - S::PleEmbedding, - S::GrRS, - S::XHigh, - S::Lo, - S::LoHigh, - S::Gated, - S::Mixed, - S::MixedHigh, - S::MixedHalf, - S::Inject, - S::Block, - ] { - let (h, n) = rows.common_span(role)?; - workspace.reject_alias(h, n)?; - if h.overlaps(n, self.status()?, self.capacity * 40) { - return Err(Error::OutputAliasesInput); - } - } - for enabled_roles in [ - ( - self.profile == GrNativeProfile::HighAndLow, - [S::XLow, S::LoLow], - ), - ( - self.profile == GrNativeProfile::HighAndLow, - [S::MixedLow, S::MixedLow], - ), - ] { - if enabled_roles.0 { - for role in enabled_roles.1 { - let (h, n) = rows.common_span(role)?; - workspace.reject_alias(h, n)?; - if h.overlaps(n, self.status()?, self.capacity * 40) { - return Err(Error::OutputAliasesInput); - } - } - } - } - Ok(()) - } - pub(super) fn span(rows: &OriginalPromptRows<'_, '_, '_>, role: S, width: usize) -> Result { - let (h, n) = rows.common_span(role)?; - h.checked_subspan( - n, - 0, - rows.rows().checked_mul(width).ok_or(Error::InvalidSize)?, - ) - } - pub(super) fn weight( - &self, - rows: &OriginalPromptRows<'_, '_, '_>, - workspace: &NativeBatchWorkspace<'_>, - b: &DeviceBuffer<'_>, - size: usize, - alignment: u64, - ) -> Result { - if !std::ptr::eq(self.context, b.context) { - return Err(Error::ContextMismatch); - } - if b.bytes != size { - return Err(Error::InvalidQwenShape); - } - let h = b.handle.ok_or(Error::ContextPoisoned)?; - h.validate_projection_extent(size, alignment)?; - workspace.reject_alias(h, size)?; - if h.overlaps(size, self.status()?, self.capacity * 40) { - return Err(Error::OutputAliasesInput); - } - for role in [ - S::R, - S::PleEmbedding, - S::GrRS, - S::XHigh, - S::Lo, - S::LoHigh, - S::Gated, - S::Mixed, - S::MixedHigh, - S::MixedHalf, - S::Inject, - S::Block, - ] { - let (a, n) = rows.common_span(role)?; - if h.overlaps(size, a, n) { - return Err(Error::OutputAliasesInput); - } - } - if self.profile == GrNativeProfile::HighAndLow { - for role in [S::XLow, S::LoLow, S::MixedLow] { - let (a, n) = rows.common_span(role)?; - if h.overlaps(size, a, n) { - return Err(Error::OutputAliasesInput); - } - } - } - Ok(h) - } - /// Initial authentic prompt staging only. Later phases never download R. - pub fn initialize<'arena, 'loan>( - &mut self, - lease: OriginalPromptRows<'arena, 'loan, 'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, - streams: &[f32], - embedding: &[f32], - ) -> Result> { - self.validate(&lease, workspace)?; - let t = lease.rows(); - if streams.len() != t * 10240 || embedding.len() != t * 2560 { - return Err(Error::InvalidQwenShape); - } - if streams.iter().chain(embedding).any(|x| !x.is_finite()) { - return Err(Error::NonFiniteMmqOutput("Original prompt input")); - } - let s = encode(streams)?; - let e = encode(embedding)?; - self.upload_initial(lease, workspace, s, e) - } - /// `initialize` over the rows in place: each row's 10240 residual-stream values and 2560 PLE embedding - /// values, in row order. The same finite refusal and the same device bytes, staged in one pass per buffer - /// instead of a caller concatenation, a finite scan and a byte conversion. - pub fn initialize_rows<'arena, 'loan>( - &mut self, - lease: OriginalPromptRows<'arena, 'loan, 'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, - rows: &[(&[f32], &[f32])], - ) -> Result> { - self.validate(&lease, workspace)?; - let t = lease.rows(); - if rows.len() != t || rows.iter().any(|(s, e)| s.len() != 10240 || e.len() != 2560) { - return Err(Error::InvalidQwenShape); - } - let mut s = Vec::new(); - s.try_reserve_exact(t * 10240 * 4).map_err(|_| Error::HostAllocation)?; - let mut e = Vec::new(); - e.try_reserve_exact(t * 2560 * 4).map_err(|_| Error::HostAllocation)?; - let mut finite = true; - for (streams, embedding) in rows { - for x in streams.iter() { - finite &= x.is_finite(); - s.extend_from_slice(&x.to_le_bytes()); - } - for x in embedding.iter() { - finite &= x.is_finite(); - e.extend_from_slice(&x.to_le_bytes()); - } - } - if !finite { - return Err(Error::NonFiniteMmqOutput("Original prompt input")); - } - self.upload_initial(lease, workspace, s, e) - } - pub(super) fn upload_initial<'arena, 'loan>( - &mut self, - mut lease: OriginalPromptRows<'arena, 'loan, 'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, - s: Vec, - e: Vec, - ) -> Result> { - let rh = Self::span(&lease, S::R, 40960)?; - let eh = Self::span(&lease, S::PleEmbedding, 10240)?; - let guard = match self.context.enter() { - Ok(g) => g, - Err(err) => { - lease.mark_failed(); - workspace.mark_failed(); - self.context.retain_driver(); - return Err(err); - } - }; - let op = self - .context - .driver - .api - .copy_from(rh, &s) - .and_then(|()| self.context.driver.api.copy_from(eh, &e)); - let sync = self.context.driver.api.synchronize(); - let pop = guard.finish(); - if op.is_err() || sync.is_err() || pop.is_err() { - self.failed = true; - lease.mark_failed(); - workspace.mark_failed() - } - if sync.is_err() || pop.is_err() { - std::mem::forget((s, e)); - self.context.retain_driver() - } - combine(combine(op, sync), pop)?; - Ok(OriginalDeviceResidual { lease }) - } - // Own every actual ABI argument until the vendor stream and readback drain. - pub(super) fn run( - &mut self, - lease: &mut OriginalPromptRows<'_, '_, '_>, - workspace: &mut NativeBatchWorkspace<'ctx>, - mut commands: Vec, - t: usize, - stride: usize, - order: &[usize], - labels: &[&'static str], - ) -> Result<()> { - let status = self.status()?; - let zero = bytes(t * stride * 4)?; - let mut readback = bytes(t * stride * 4)?; - let blas = workspace.blas()?; - let guard = match self.context.enter() { - Ok(g) => g, - Err(e) => { - self.failed = true; - lease.mark_failed(); - self.context.retain_driver(); - return Err(e); - } - }; - // LELEKA_PREFILL_DEFER_GUARDS (experimental, deferred_status.rs): the status words are zeroed and read back on the stream and - // looked at later (ring full, or before results leave the device); PLE (stride 10) and the profiling mode stay immediate. - let defer = crate::deferred_status::enabled() && stride != 10 && !crate::command_profile::enabled(); - let status_bytes = t * stride * 4; - let mut op = if defer { - crate::deferred_status::begin(self.context, status, status_bytes, blas.stream(), self.capacity * 40) - } else { - self.context.driver.api.copy_from(status, &zero) - }; - if op.is_ok() && !defer { - op = self.context.driver.api.synchronize() - } - // LELEKA_PREFILL_PROFILE_SYNC: each command drained on its own and charged to (tag, position) - let timed = crate::command_profile::enabled(); - for (position, cmd) in commands.iter_mut().enumerate() { - if op.is_err() { - break; - } - let started = std::time::Instant::now(); - let mut label = "gemm"; - op = match cmd { - C::Kernel { - family, - index, - grid, - block, - args, - } => { - let module = match family { - 0 => self.pack.as_ref(), - 1 => self.ple.as_ref(), - 3 => self.stage.as_ref(), - _ => self.gr.as_ref(), - } - .ok_or(Error::ContextPoisoned)?; - if timed { - let entries = match family { - 1 => PLE_ENTRIES, - 3 => crate::prefill_stage::ENTRIES, - _ => GR_ENTRIES, - }; - label = entries.get(*index).and_then(|e| e.to_str().ok()).unwrap_or("kernel"); - } - module.launch(*index, *grid, *block, blas.stream(), args) - } - C::Gemm { - input, - weight, - output, - t, - n, - k, - alpha, - beta, - } => blas.gemm_bf16(*input, *weight, *output, *t, *n, *k, alpha, beta), - }; - if timed && op.is_ok() { - op = blas.synchronize(); - crate::command_profile::add(self.profile_tag, position + 1, label, started.elapsed()); - } - } - if defer { - // no host wait: the words and the cross-stream ordering are queued on the stream (deferred_status.rs) - let queued = if op.is_ok() { - crate::deferred_status::finish(self.context, status, status_bytes, blas.stream(), stride, order, labels) - } else { - op - }; - let pop = guard.finish(); - if queued.is_err() || pop.is_err() { - self.failed = true; - lease.mark_failed(); - workspace.mark_failed(); - std::mem::forget((commands, zero, readback)); - self.context.retain_driver(); - return combine(queued, pop); - } - // cuLaunchKernel copies its parameter values at the call and cuBLAS (host pointer mode) reads alpha/beta at the - // call, so the argument vectors need not outlive the enqueue (the immediate path keeps them until its drain - // as a conservative audit rule; the failure path above still leaks them) - drop(commands); - return Ok(()); - } - let sync = blas.synchronize(); - if op.is_ok() && sync.is_ok() { - op = self.context.driver.api.copy_to(status, &mut readback) - } - let all = self.context.driver.api.synchronize(); - let pop = guard.finish(); - if op.is_err() || sync.is_err() || all.is_err() || pop.is_err() { - self.failed = true; - lease.mark_failed(); - workspace.mark_failed() - } - if sync.is_err() || all.is_err() || pop.is_err() { - std::mem::forget((commands, zero, readback)); - self.context.retain_driver(); - return combine(combine(combine(op, sync), all), pop); - } - combine(combine(combine(op, sync), all), pop)?; - // Unknown status is never a usable finite product, including a later word after an earlier numerical flag. All actual - // kernels write 0/1. The evaluation is shared with the deferred path (deferred_status::evaluate). - if let Err(e) = crate::deferred_status::evaluate(&readback, stride, order, labels) { - if matches!(e, Error::InvalidDriverValue(_)) { - self.failed = true; - lease.mark_failed(); - self.context.retain_driver(); - } - return Err(e); - } - Ok(()) - } - pub fn apply_ple<'arena, 'loan>( - &mut self, - mut residual: OriginalDeviceResidual<'arena, 'loan, 'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, - weights: PleClosedWeights<'_, '_>, - history: &mut OriginalPleHistory<'ctx>, - ) -> Result> { - self.profile_tag = "ple"; - let lease = &mut residual.lease; - self.validate(lease, workspace)?; - if history.failed || !std::ptr::eq(history.context, self.context) { - return Err(Error::ContextMismatch); - } - let hb = history.buffer.as_ref().ok_or(Error::ContextPoisoned)?; - if hb.len() != 368640 { - return Err(Error::InvalidQwenShape); - } - let hist = hb.handle.ok_or(Error::ContextPoisoned)?; - hist.validate_projection_extent(368640, 4)?; - workspace.reject_alias(hist, 368640)?; - let key = self.weight(lease, workspace, weights.key, 52428800, 2)?; - let value = self.weight(lease, workspace, weights.value, 13107200, 2)?; - let mut aux = [key; 4]; - for (i, w) in weights.aux.iter().enumerate() { - aux[i] = self.weight( - lease, - workspace, - w, - if i == 3 { 81920 } else { 40960 }, - if i == 3 { 2 } else { 4 }, - )?; - } - let sb = lease.ple_subbatch_capacity()?; - let total = lease.rows(); - for first in (0..total).step_by(sb) { - let t = sb.min(total - first); - let rh = Self::span(lease, S::R, 40960)?.checked_subspan( - total * 40960, - first * 40960, - t * 40960, - )?; - let eh = Self::span(lease, S::PleEmbedding, 10240)?.checked_subspan( - total * 10240, - first * 10240, - t * 10240, - )?; - let get = |role: P| -> Result { - let (h, n) = lease.ple_span(role, t)?; - workspace.reject_alias(h, n)?; - if h.overlaps(n, hist, 368640) || h.overlaps(n, self.status()?, self.capacity * 40) - { - return Err(Error::OutputAliasesInput); - } - for (w, wn) in [ - (key, 52428800), - (value, 13107200), - (aux[0], 40960), - (aux[1], 40960), - (aux[2], 40960), - (aux[3], 81920), - ] { - if h.overlaps(n, w, wn) { - return Err(Error::OutputAliasesInput); - } - } - Ok(h) - }; - let kh = get(P::Key)?; - let qn = get(P::Qn)?; - let gated = get(P::Gated)?; - let val = get(P::Value)?; - let gate = get(P::Gate)?; - let packed = get(P::PackedEmbedding)?; - let low = if self.mode == PleBf16Mode::HighAndLow { - Some(get(P::PackedEmbeddingLow)?) - } else { - None - }; - for (h, n) in [ - (rh, t * 40960), - (eh, t * 10240), - (self.status()?, self.capacity * 40), - ] { - if h.overlaps(n, hist, 368640) { - return Err(Error::OutputAliasesInput); - } - } - for (w, n) in [ - (key, 52428800), - (value, 13107200), - (aux[0], 40960), - (aux[1], 40960), - (aux[2], 40960), - (aux[3], 81920), - ] { - if w.overlaps(n, hist, 368640) { - return Err(Error::OutputAliasesInput); - } - } - let flags = self.status()?; - let mut v = Vec::new(); - v.try_reserve_exact(28).map_err(|_| Error::HostAllocation)?; - // Candidate history is source bytes, never a caller finite witness. - scan_ple(&mut v, hist, flags, 92160, 1, 8); - kernel( - &mut v, - 0, - 0, - (t * 2560).div_ceil(256), - 256, - vec![ - A::Address(eh), - A::Address(packed), - low.map_or(A::NullAddress, A::Address), - A::I64((t * 2560) as i64), - ], - ); - for (out, n, w, role) in [(kh, 10240, key, 0), (val, 2560, value, 1)] { - v.push(C::Gemm { - input: packed, - weight: w, - output: out, - t: t as i32, - n, - k: 2560, - alpha: 1., - beta: 0., - }); - if let Some(l) = low { - v.push(C::Gemm { - input: l, - weight: w, - output: out, - t: t as i32, - n, - k: 2560, - alpha: 1., - beta: 1., - }) - } - scan_ple(&mut v, out, flags, n as usize, t, role); - } - // Literal native_ple_postops_batch reuses Key and Qn in place. - kernel( - &mut v, - 1, - 0, - t * 4, - 1024, - vec![A::Address(kh), A::Address(aux[0]), A::Address(kh)], - ); - scan_ple(&mut v, kh, flags, 10240, t, 2); - kernel( - &mut v, - 1, - 0, - t * 4, - 1024, - vec![A::Address(rh), A::Address(aux[1]), A::Address(qn)], - ); - scan_ple(&mut v, qn, flags, 10240, t, 3); - kernel( - &mut v, - 1, - 1, - t * 4, - 512, - vec![ - A::Address(kh), - A::Address(qn), - A::Address(gate), - A::F32(1. / 2560.0f32.sqrt()), - ], - ); - scan_ple(&mut v, gate, flags, 4, t, 4); - kernel( - &mut v, - 1, - 2, - t * 40, - 256, - vec![ - A::Address(val), - A::Address(gate), - A::Address(gated), - A::I32(t as i32), - ], - ); - scan_ple(&mut v, gated, flags, 10240, t, 5); - kernel( - &mut v, - 1, - 0, - t * 4, - 1024, - vec![A::Address(gated), A::Address(aux[2]), A::Address(qn)], - ); - scan_ple(&mut v, qn, flags, 10240, t, 6); - kernel( - &mut v, - 1, - 3, - t * 40, - 256, - vec![ - A::Address(hist), - A::Address(qn), - A::Address(aux[3]), - A::Address(rh), - A::Address(gated), - A::Address(flags), - A::I32(t as i32), - ], - ); - kernel( - &mut v, - 1, - 4, - 40, - 256, - vec![A::Address(hist), A::Address(qn), A::I32(t as i32)], - ); - scan_ple(&mut v, hist, flags, 92160, 1, 8); - scan_ple(&mut v, rh, flags, 10240, t, 9); - if let Err(e) = self.run( - lease, - workspace, - v, - t, - 10, - &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], - &[ - "PLE key", - "PLE value", - "PLE key norm", - "PLE query norm", - "PLE gate", - "PLE gated", - "PLE normalized", - "PLE conv", - "PLE history", - "PLE streams", - ], - ) { - history.failed = true; - return Err(e); - } - } - Ok(residual) - } - pub fn read_gr<'arena, 'loan>( - &mut self, - residual: OriginalDeviceResidual<'arena, 'loan, 'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, - weights: [&DeviceBuffer<'_>; 4], - epsilon: f32, - ) -> Result> { - self.read_gr_impl(residual, workspace, weights, epsilon, false) - } - pub fn read_gr_normed<'weight, 'arena, 'loan>( - &mut self, - normed: OriginalDeviceNormedResidual<'weight, 'arena, 'loan, 'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, - weights: [&DeviceBuffer<'_>; 4], - epsilon: f32, - ) -> Result> { - if !std::ptr::eq(normed.gamma, weights[0]) || normed.epsilon.to_bits() != epsilon.to_bits() - { - return Err(Error::InvalidQwenShape); - } - self.read_gr_impl(normed.residual, workspace, weights, epsilon, true) - } - pub(super) fn read_gr_impl<'arena, 'loan>( - &mut self, - mut residual: OriginalDeviceResidual<'arena, 'loan, 'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, - weights: [&DeviceBuffer<'_>; 4], - epsilon: f32, - normed: bool, - ) -> Result> { - self.profile_tag = if normed { "readn" } else { "read" }; - let lease = &mut residual.lease; - self.validate(lease, workspace)?; - if !epsilon.is_finite() || epsilon < 0. { - return Err(Error::InvalidQwenShape); - } - let t = lease.rows(); - let mut h = [self.status()?; 15]; - for (i, r, n) in [ - (0, S::R, 40960), - (1, S::GrRS, 16), - (2, S::XHigh, 20480), - (4, S::Lo, 1280), - (5, S::LoHigh, 640), - (7, S::Gated, 40960), - (8, S::Mixed, 10240), - (9, S::MixedHigh, 5120), - (11, S::MixedHalf, 5120), - (12, S::Inject, 16), - (13, S::Block, 10240), - ] { - h[i] = Self::span(lease, r, n)?; - } - if self.profile == GrNativeProfile::HighAndLow { - for (i, r, n) in [ - (3, S::XLow, 20480), - (6, S::LoLow, 640), - (10, S::MixedLow, 5120), - ] { - h[i] = Self::span(lease, r, n)?; - } - } - let mut w = [h[0]; 4]; - for (i, n) in [40960, 6553600, 6553600, 81920].into_iter().enumerate() { - w[i] = self.weight(lease, workspace, weights[i], n, if i == 0 { 4 } else { 2 })?; - } - let low = |i| { - if self.profile == GrNativeProfile::HighAndLow { - A::Address(h[i]) - } else { - A::NullAddress - } - }; - let flags = self.status()?; - let mut v = Vec::new(); - v.try_reserve_exact(20).map_err(|_| Error::HostAllocation)?; - let fused = fused_scans(); - if fused { - // the norm guard rides on the norm kernel; a normed read follows `inject_gr_fused`, which already guarded - // this very norm (same R, rs and gamma), so nothing is left to scan - if !normed { - kernel( - &mut v, - 3, - 3, - t * 4, - 256, - vec![ - A::Address(h[0]), - A::Address(w[0]), - A::F32(epsilon), - A::Address(h[1]), - A::Address(h[2]), - low(3), - A::Address(flags), - ], - ); - } - } else { - if !normed { - kernel( - &mut v, - 2, - 0, - t * 4, - 256, - vec![ - A::Address(h[0]), - A::Address(w[0]), - A::F32(epsilon), - A::Address(h[1]), - A::Address(h[2]), - low(3), - ], - ); - } - kernel( - &mut v, - 2, - 5, - (t * 10240).div_ceil(256), - 256, - vec![ - A::Address(h[0]), - A::Address(h[1]), - A::Address(w[0]), - A::Address(flags), - A::I64(t as i64), - ], - ); - } - let gemm = |v: &mut Vec, input, lo, weight, out, n, k| { - v.push(C::Gemm { - input: h[input], - weight, - output: h[out], - t: t as i32, - n, - k, - alpha: 1., - beta: 0., - }); - if self.profile == GrNativeProfile::HighAndLow { - v.push(C::Gemm { - input: h[lo], - weight, - output: h[out], - t: t as i32, - n, - k, - alpha: 1., - beta: 1., - }) - } - }; - gemm(&mut v, 2, 3, w[1], 4, 320, 10240); - scan_gr(&mut v, h[4], flags, 320, t, 1); - kernel( - &mut v, - 2, - 1, - (t * 320).div_ceil(256), - 256, - vec![ - A::Address(h[4]), - A::Address(h[5]), - low(6), - A::I64((t * 320) as i64), - ], - ); - kernel( - &mut v, - 2, - 6, - (t * 320).div_ceil(256), - 256, - vec![A::Address(h[4]), A::Address(flags), A::I64(t as i64)], - ); - gemm(&mut v, 5, 6, w[2], 7, 10240, 320); - if !fused { - scan_gr(&mut v, h[7], flags, 10240, t, 3); - } - // Original injection GEMM precedes mixed production. - gemm(&mut v, 2, 3, w[3], 12, 4, 10240); - scan_gr(&mut v, h[12], flags, 4, t, 6); - if fused { - // mix + the guards of the gated tensor (3), the products (4) and the mixed row (5) - kernel( - &mut v, - 3, - 4, - (t * 2560).div_ceil(256), - 256, - vec![ - A::Address(h[0]), - A::Address(h[1]), - A::Address(w[0]), - A::Address(h[7]), - A::Address(h[8]), - A::Address(h[9]), - A::I64(t as i64), - A::Address(h[11]), - low(10), - A::Address(flags), - ], - ); - } else { - kernel( - &mut v, - 2, - 2, - (t * 2560).div_ceil(256), - 256, - vec![ - A::Address(h[0]), - A::Address(h[1]), - A::Address(w[0]), - A::Address(h[7]), - A::Address(h[8]), - A::Address(h[9]), - A::I64(t as i64), - A::Address(h[11]), - low(10), - ], - ); - kernel( - &mut v, - 2, - 7, - (t * 10240).div_ceil(256), - 256, - vec![ - A::Address(h[0]), - A::Address(h[1]), - A::Address(w[0]), - A::Address(h[7]), - A::Address(flags), - A::I64(t as i64), - ], - ); - scan_gr(&mut v, h[8], flags, 2560, t, 5); - } - self.run( - lease, - workspace, - v, - t, - 8, - &[0, 1, 2, 3, 6, 4, 5], - &[ - "GR native norm", - "GR native down", - "GR native silu", - "GR native up", - "GR native products", - "GR native mixed", - "GR native inject", - "GR native candidate", - ], - )?; - Ok(OriginalDeviceGrRead { - lease: residual.lease, - }) - } - /// A completed real attention/MoE producer moved the read lease into Block. - /// Recheck its full actual Block before the Original ascending R write. - pub fn inject_gr<'arena, 'loan>( - &mut self, - mut block: OriginalDeviceBlock<'arena, 'loan, 'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, - ) -> Result> { - self.profile_tag = "injectchk"; - let lease = &mut block.read.lease; - self.validate(lease, workspace)?; - let t = lease.rows(); - let flags = self.status()?; - let r = Self::span(lease, S::R, 40960)?; - let b = Self::span(lease, S::Block, 10240)?; - let inj = Self::span(lease, S::Inject, 16)?; - // Prewrite full Block scan/drain rejects numerical errors before R is - // modified. No host floats are treated as a device-completion witness. - let mut check = Vec::new(); - check - .try_reserve_exact(1) - .map_err(|_| Error::HostAllocation)?; - scan_gr(&mut check, b, flags, 2560, t, 7); - self.run( - lease, - workspace, - check, - t, - 8, - &[7], - &[ - "unused", - "unused", - "unused", - "unused", - "unused", - "unused", - "unused", - "GR native block", - ], - )?; - self.profile_tag = "inject"; - let mut v = Vec::new(); - v.try_reserve_exact(2).map_err(|_| Error::HostAllocation)?; - if fused_scans() { - kernel( - &mut v, - 3, - 6, - (t * 10240).div_ceil(256), - 256, - vec![ - A::Address(r), - A::Address(b), - A::Address(inj), - A::I64(4), - A::I64(t as i64), - A::Address(flags), - ], - ); - } else { - kernel( - &mut v, - 2, - 3, - (t * 10240).div_ceil(256), - 256, - vec![ - A::Address(r), - A::Address(b), - A::Address(inj), - A::I64(4), - A::I64(t as i64), - ], - ); - scan_gr(&mut v, r, flags, 10240, t, 7); - } - self.run( - lease, - workspace, - v, - t, - 8, - &[7], - &[ - "unused", - "unused", - "unused", - "unused", - "unused", - "unused", - "unused", - "GR native candidate", - ], - )?; - Ok(OriginalDeviceResidual { - lease: block.read.lease, - }) - } - pub fn inject_gr_fused<'weight, 'arena, 'loan>( - &mut self, - mut block: OriginalDeviceBlock<'arena, 'loan, 'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, - gamma: &'weight DeviceBuffer<'ctx>, - epsilon: f32, - ) -> Result> { - self.profile_tag = "injectchk"; - let lease = &mut block.read.lease; - self.validate(lease, workspace)?; - if !epsilon.is_finite() || epsilon < 0. { - return Err(Error::InvalidQwenShape); - } - let w = self.weight(lease, workspace, gamma, 40960, 4)?; - let t = lease.rows(); - let flags = self.status()?; - let r = Self::span(lease, S::R, 40960)?; - let b = Self::span(lease, S::Block, 10240)?; - let inj = Self::span(lease, S::Inject, 16)?; - let rs = Self::span(lease, S::GrRS, 16)?; - let high = Self::span(lease, S::XHigh, 20480)?; - let low = if self.profile == GrNativeProfile::HighAndLow { - A::Address(Self::span(lease, S::XLow, 20480)?) - } else { - A::NullAddress - }; - let mut check = Vec::new(); - check - .try_reserve_exact(1) - .map_err(|_| Error::HostAllocation)?; - scan_gr(&mut check, b, flags, 2560, t, 7); - self.run( - lease, - workspace, - check, - t, - 8, - &[7], - &[ - "unused", - "unused", - "unused", - "unused", - "unused", - "unused", - "unused", - "GR native block", - ], - )?; - self.profile_tag = "injectf"; - let mut v = Vec::new(); - v.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?; - if fused_scans() { - // write + the guards of R after the write (7) and of the next half's norm (0) - kernel( - &mut v, - 3, - 5, - t * 4, - 256, - vec![ - A::Address(r), - A::Address(b), - A::Address(inj), - A::I64(4), - A::Address(w), - A::F32(epsilon), - A::Address(rs), - A::Address(high), - low, - A::Address(flags), - ], - ); - } else { - kernel( - &mut v, - 2, - 8, - t * 4, - 256, - vec![ - A::Address(r), - A::Address(b), - A::Address(inj), - A::I64(4), - A::Address(w), - A::F32(epsilon), - A::Address(rs), - A::Address(high), - low, - ], - ); - scan_gr(&mut v, r, flags, 10240, t, 7); - kernel( - &mut v, - 2, - 5, - (t * 10240).div_ceil(256), - 256, - vec![ - A::Address(r), - A::Address(rs), - A::Address(w), - A::Address(flags), - A::I64(t as i64), - ], - ); - } - self.run( - lease, - workspace, - v, - t, - 8, - &[7, 0], - &[ - "GR native next norm", - "unused", - "unused", - "unused", - "unused", - "unused", - "unused", - "GR native candidate", - ], - )?; - Ok(OriginalDeviceNormedResidual { - residual: OriginalDeviceResidual { - lease: block.read.lease, - }, - gamma, - epsilon, - }) - } - pub fn close(mut self) -> Result<()> { - self.close_inner() - } - pub(super) fn close_inner(&mut self) -> Result<()> { - self.failed = true; - let mut result = Ok(()); - for m in [ - self.pack.take(), - self.ple.take(), - self.gr.take(), - self.stage.take(), - ] - .into_iter() - .flatten() - { - let r = if self.context.is_poisoned() { - std::mem::forget(m); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(g) => combine(m.close(), g.finish()), - Err(e) => { - std::mem::forget(m); - Err(e) - } - } - }; - if r.is_err() { - self.context.poison(); - self.context.retain_driver() - } - result = combine(result, r); - } - for b in [self.status.take(), self.stage_scratch.take()] - .into_iter() - .flatten() - { - let r = if self.context.is_poisoned() { - std::mem::forget(b); - Err(Error::ContextPoisoned) - } else { - b.release() - }; - if r.is_err() { - self.context.poison(); - self.context.retain_driver() - } - result = combine(result, r) - } - result - } -} +mod impl_originalpromptdevice_2; +mod impl_originalpromptdevice_2_2; +mod impl_originalpromptdevice_3; +mod impl_originalpromptdevice_4; +mod impl_originalpromptdevice_5; +mod impl_originalpromptdevice_6; +mod impl_originalpromptdevice_7; diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_2.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_2.rs new file mode 100644 index 00000000..bca7d624 --- /dev/null +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_2.rs @@ -0,0 +1,253 @@ +//! Moved out of the parent module by STRA-338: impl OriginalPromptDevice. + +#[allow(unused_imports)] +use super::*; + + + +impl<'ctx> OriginalPromptDevice<'ctx> { + pub fn device_bytes(capacity: usize) -> Result { + if !(1..=8192).contains(&capacity) { + return Err(Error::InvalidQwenShape); + } + capacity.checked_mul(40).ok_or(Error::BudgetExceeded) + } + pub(in super::super) fn new( + context: &'ctx Context<'ctx>, + capacity: usize, + mode: PleBf16Mode, + profile: GrNativeProfile, + ) -> Result { + let count = Self::device_bytes(capacity)?; + // Separate new precise PLE arithmetic asset must be genuinely sealed. + if PLE_PTX.len() < 2 + || PLE_PTX.last() != Some(&0) + || PLE_PTX[..PLE_PTX.len() - 1].contains(&0) + || crate::qwen_ffi::sha256(&PLE_PTX[..PLE_PTX.len() - 1]) != PLE_SHA + || GR_PTX.len() < 2 + || GR_PTX.last() != Some(&0) + || GR_PTX[..GR_PTX.len() - 1].contains(&0) + || crate::qwen_ffi::sha256(&GR_PTX[..GR_PTX.len() - 1]) != GR_SHA + || crate::prefill_stage::admit().is_err() + { + return Err(Error::UnsupportedQwenOperation); + } + if context.is_poisoned() { + return Err(Error::ContextPoisoned); + } + let required = count.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; + if context + .allocated_bytes() + .checked_add(required) + .is_none_or(|x| x > context.budget_bytes()) + || context.memory_info()?.0 < required + { + return Err(Error::BudgetExceeded); + } + let mut owner = Self { + context, + capacity, + mode, + profile, + status: None, + pack: None, + ple: None, + gr: None, + stage: None, + stage_scratch: None, + profile_tag: "prompt", + failed: false, + }; + let operation = (|| -> Result<()> { + owner.status = Some(context.allocate(count)?); + let guard = match context.enter() { + Ok(g) => g, + Err(e) => { + context.poison(); + context.retain_driver(); + return Err(e); + } + }; + let load = (|| -> Result<()> { + owner.pack = Some(KernelModule::load(PACK_PTX, &[c"ple_pack"])?); + owner.ple = Some(KernelModule::load(PLE_PTX, PLE_ENTRIES)?); + owner.gr = Some(KernelModule::load(GR_PTX, GR_ENTRIES)?); + owner.stage = Some(KernelModule::load( + crate::prefill_stage::PTX, + crate::prefill_stage::ENTRIES, + )?); + Ok(()) + })(); + let pop = guard.finish(); + if pop.is_err() { + context.poison(); + context.retain_driver() + } + combine(load, pop)?; + if context.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + Ok(()) + })(); + if let Err(e) = operation { + let _ = owner.close(); + return Err(e); + } + Ok(owner) + } + pub fn allocated_bytes(&self) -> usize { + self.status.as_ref().map_or(0, DeviceBuffer::len) + } + pub fn is_failed(&self) -> bool { + self.failed || self.context.is_poisoned() + } + pub(in super::super) fn status(&self) -> Result { + if self.is_failed() { + return Err(Error::ContextPoisoned); + } + let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?; + if b.len() != self.capacity * 40 || !std::ptr::eq(b.context, self.context) { + return Err(Error::InvalidQwenShape); + } + let h = b.handle.ok_or(Error::ContextPoisoned)?; + h.validate_projection_extent(b.len(), 4)?; + Ok(h) + } + pub(in super::super) fn validate( + &self, + rows: &OriginalPromptRows<'_, '_, '_>, + workspace: &NativeBatchWorkspace<'_>, + ) -> Result<()> { + if self.is_failed() || rows.is_failed() { + return Err(Error::ContextPoisoned); + } + if !std::ptr::eq(self.context, rows.context()) { + return Err(Error::ContextMismatch); + } + if rows.rows() > self.capacity { + return Err(Error::InvalidQwenShape); + } + workspace.validate_context(self.context)?; + workspace.reject_alias(self.status()?, self.capacity * 40)?; + // All whole common spans used by this owner must be actual disjoint + // arena spans, not fresh handles minted from addresses. + for role in [ + S::R, + S::PleEmbedding, + S::GrRS, + S::XHigh, + S::Lo, + S::LoHigh, + S::Gated, + S::Mixed, + S::MixedHigh, + S::MixedHalf, + S::Inject, + S::Block, + ] { + let (h, n) = rows.common_span(role)?; + workspace.reject_alias(h, n)?; + if h.overlaps(n, self.status()?, self.capacity * 40) { + return Err(Error::OutputAliasesInput); + } + } + for enabled_roles in [ + ( + self.profile == GrNativeProfile::HighAndLow, + [S::XLow, S::LoLow], + ), + ( + self.profile == GrNativeProfile::HighAndLow, + [S::MixedLow, S::MixedLow], + ), + ] { + if enabled_roles.0 { + for role in enabled_roles.1 { + let (h, n) = rows.common_span(role)?; + workspace.reject_alias(h, n)?; + if h.overlaps(n, self.status()?, self.capacity * 40) { + return Err(Error::OutputAliasesInput); + } + } + } + } + Ok(()) + } + pub(in super::super) fn span(rows: &OriginalPromptRows<'_, '_, '_>, role: S, width: usize) -> Result { + let (h, n) = rows.common_span(role)?; + h.checked_subspan( + n, + 0, + rows.rows().checked_mul(width).ok_or(Error::InvalidSize)?, + ) + } + pub(in super::super) fn weight( + &self, + rows: &OriginalPromptRows<'_, '_, '_>, + workspace: &NativeBatchWorkspace<'_>, + b: &DeviceBuffer<'_>, + size: usize, + alignment: u64, + ) -> Result { + if !std::ptr::eq(self.context, b.context) { + return Err(Error::ContextMismatch); + } + if b.bytes != size { + return Err(Error::InvalidQwenShape); + } + let h = b.handle.ok_or(Error::ContextPoisoned)?; + h.validate_projection_extent(size, alignment)?; + workspace.reject_alias(h, size)?; + if h.overlaps(size, self.status()?, self.capacity * 40) { + return Err(Error::OutputAliasesInput); + } + for role in [ + S::R, + S::PleEmbedding, + S::GrRS, + S::XHigh, + S::Lo, + S::LoHigh, + S::Gated, + S::Mixed, + S::MixedHigh, + S::MixedHalf, + S::Inject, + S::Block, + ] { + let (a, n) = rows.common_span(role)?; + if h.overlaps(size, a, n) { + return Err(Error::OutputAliasesInput); + } + } + if self.profile == GrNativeProfile::HighAndLow { + for role in [S::XLow, S::LoLow, S::MixedLow] { + let (a, n) = rows.common_span(role)?; + if h.overlaps(size, a, n) { + return Err(Error::OutputAliasesInput); + } + } + } + Ok(h) + } + /// Initial authentic prompt staging only. Later phases never download R. + pub fn initialize<'arena, 'loan>( + &mut self, + lease: OriginalPromptRows<'arena, 'loan, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + streams: &[f32], + embedding: &[f32], + ) -> Result> { + self.validate(&lease, workspace)?; + let t = lease.rows(); + if streams.len() != t * 10240 || embedding.len() != t * 2560 { + return Err(Error::InvalidQwenShape); + } + if streams.iter().chain(embedding).any(|x| !x.is_finite()) { + return Err(Error::NonFiniteMmqOutput("Original prompt input")); + } + let s = encode(streams)?; + let e = encode(embedding)?; + self.upload_initial(lease, workspace, s, e) + } +} diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_2_2.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_2_2.rs new file mode 100644 index 00000000..8e886454 --- /dev/null +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_2_2.rs @@ -0,0 +1,217 @@ +//! Moved out of the parent module by STRA-338: impl OriginalPromptDevice (2). + +#[allow(unused_imports)] +use super::*; + + + +impl<'ctx> OriginalPromptDevice<'ctx> { + /// `initialize` over the rows in place: each row's 10240 residual-stream values and 2560 PLE embedding + /// values, in row order. The same finite refusal and the same device bytes, staged in one pass per buffer + /// instead of a caller concatenation, a finite scan and a byte conversion. + pub fn initialize_rows<'arena, 'loan>( + &mut self, + lease: OriginalPromptRows<'arena, 'loan, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + rows: &[(&[f32], &[f32])], + ) -> Result> { + self.validate(&lease, workspace)?; + let t = lease.rows(); + if rows.len() != t || rows.iter().any(|(s, e)| s.len() != 10240 || e.len() != 2560) { + return Err(Error::InvalidQwenShape); + } + let mut s = Vec::new(); + s.try_reserve_exact(t * 10240 * 4).map_err(|_| Error::HostAllocation)?; + let mut e = Vec::new(); + e.try_reserve_exact(t * 2560 * 4).map_err(|_| Error::HostAllocation)?; + let mut finite = true; + for (streams, embedding) in rows { + for x in streams.iter() { + finite &= x.is_finite(); + s.extend_from_slice(&x.to_le_bytes()); + } + for x in embedding.iter() { + finite &= x.is_finite(); + e.extend_from_slice(&x.to_le_bytes()); + } + } + if !finite { + return Err(Error::NonFiniteMmqOutput("Original prompt input")); + } + self.upload_initial(lease, workspace, s, e) + } + pub(in super::super) fn upload_initial<'arena, 'loan>( + &mut self, + mut lease: OriginalPromptRows<'arena, 'loan, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + s: Vec, + e: Vec, + ) -> Result> { + let rh = Self::span(&lease, S::R, 40960)?; + let eh = Self::span(&lease, S::PleEmbedding, 10240)?; + let guard = match self.context.enter() { + Ok(g) => g, + Err(err) => { + lease.mark_failed(); + workspace.mark_failed(); + self.context.retain_driver(); + return Err(err); + } + }; + let op = self + .context + .driver + .api + .copy_from(rh, &s) + .and_then(|()| self.context.driver.api.copy_from(eh, &e)); + let sync = self.context.driver.api.synchronize(); + let pop = guard.finish(); + if op.is_err() || sync.is_err() || pop.is_err() { + self.failed = true; + lease.mark_failed(); + workspace.mark_failed() + } + if sync.is_err() || pop.is_err() { + std::mem::forget((s, e)); + self.context.retain_driver() + } + combine(combine(op, sync), pop)?; + Ok(OriginalDeviceResidual { lease }) + } + // Own every actual ABI argument until the vendor stream and readback drain. + pub(in super::super) fn run( + &mut self, + lease: &mut OriginalPromptRows<'_, '_, '_>, + workspace: &mut NativeBatchWorkspace<'ctx>, + mut commands: Vec, + t: usize, + stride: usize, + order: &[usize], + labels: &[&'static str], + ) -> Result<()> { + let status = self.status()?; + let zero = bytes(t * stride * 4)?; + let mut readback = bytes(t * stride * 4)?; + let blas = workspace.blas()?; + let guard = match self.context.enter() { + Ok(g) => g, + Err(e) => { + self.failed = true; + lease.mark_failed(); + self.context.retain_driver(); + return Err(e); + } + }; + // LELEKA_PREFILL_DEFER_GUARDS (experimental, deferred_status.rs): the status words are zeroed and read back on the stream and + // looked at later (ring full, or before results leave the device); PLE (stride 10) and the profiling mode stay immediate. + let defer = crate::deferred_status::enabled() && stride != 10 && !crate::command_profile::enabled(); + let status_bytes = t * stride * 4; + let mut op = if defer { + crate::deferred_status::begin(self.context, status, status_bytes, blas.stream(), self.capacity * 40) + } else { + self.context.driver.api.copy_from(status, &zero) + }; + if op.is_ok() && !defer { + op = self.context.driver.api.synchronize() + } + // LELEKA_PREFILL_PROFILE_SYNC: each command drained on its own and charged to (tag, position) + let timed = crate::command_profile::enabled(); + for (position, cmd) in commands.iter_mut().enumerate() { + if op.is_err() { + break; + } + let started = std::time::Instant::now(); + let mut label = "gemm"; + op = match cmd { + C::Kernel { + family, + index, + grid, + block, + args, + } => { + let module = match family { + 0 => self.pack.as_ref(), + 1 => self.ple.as_ref(), + 3 => self.stage.as_ref(), + _ => self.gr.as_ref(), + } + .ok_or(Error::ContextPoisoned)?; + if timed { + let entries = match family { + 1 => PLE_ENTRIES, + 3 => crate::prefill_stage::ENTRIES, + _ => GR_ENTRIES, + }; + label = entries.get(*index).and_then(|e| e.to_str().ok()).unwrap_or("kernel"); + } + module.launch(*index, *grid, *block, blas.stream(), args) + } + C::Gemm { + input, + weight, + output, + t, + n, + k, + alpha, + beta, + } => blas.gemm_bf16(*input, *weight, *output, *t, *n, *k, alpha, beta), + }; + if timed && op.is_ok() { + op = blas.synchronize(); + crate::command_profile::add(self.profile_tag, position + 1, label, started.elapsed()); + } + } + if defer { + // no host wait: the words and the cross-stream ordering are queued on the stream (deferred_status.rs) + let queued = if op.is_ok() { + crate::deferred_status::finish(self.context, status, status_bytes, blas.stream(), stride, order, labels) + } else { + op + }; + let pop = guard.finish(); + if queued.is_err() || pop.is_err() { + self.failed = true; + lease.mark_failed(); + workspace.mark_failed(); + std::mem::forget((commands, zero, readback)); + self.context.retain_driver(); + return combine(queued, pop); + } + // cuLaunchKernel copies its parameter values at the call and cuBLAS (host pointer mode) reads alpha/beta at the + // call, so the argument vectors need not outlive the enqueue (the immediate path keeps them until its drain + // as a conservative audit rule; the failure path above still leaks them) + drop(commands); + return Ok(()); + } + let sync = blas.synchronize(); + if op.is_ok() && sync.is_ok() { + op = self.context.driver.api.copy_to(status, &mut readback) + } + let all = self.context.driver.api.synchronize(); + let pop = guard.finish(); + if op.is_err() || sync.is_err() || all.is_err() || pop.is_err() { + self.failed = true; + lease.mark_failed(); + workspace.mark_failed() + } + if sync.is_err() || all.is_err() || pop.is_err() { + std::mem::forget((commands, zero, readback)); + self.context.retain_driver(); + return combine(combine(combine(op, sync), all), pop); + } + combine(combine(combine(op, sync), all), pop)?; + // Unknown status is never a usable finite product, including a later word after an earlier numerical flag. All actual + // kernels write 0/1. The evaluation is shared with the deferred path (deferred_status::evaluate). + if let Err(e) = crate::deferred_status::evaluate(&readback, stride, order, labels) { + if matches!(e, Error::InvalidDriverValue(_)) { + self.failed = true; + lease.mark_failed(); + self.context.retain_driver(); + } + return Err(e); + } + Ok(()) + } +} diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_3.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_3.rs new file mode 100644 index 00000000..bf22a617 --- /dev/null +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_3.rs @@ -0,0 +1,259 @@ +//! Moved out of the parent module by STRA-338: impl OriginalPromptDevice (3). + +#[allow(unused_imports)] +use super::*; + + + +impl<'ctx> OriginalPromptDevice<'ctx> { + pub fn apply_ple<'arena, 'loan>( + &mut self, + mut residual: OriginalDeviceResidual<'arena, 'loan, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + weights: PleClosedWeights<'_, '_>, + history: &mut OriginalPleHistory<'ctx>, + ) -> Result> { + self.profile_tag = "ple"; + let lease = &mut residual.lease; + self.validate(lease, workspace)?; + if history.failed || !std::ptr::eq(history.context, self.context) { + return Err(Error::ContextMismatch); + } + let hb = history.buffer.as_ref().ok_or(Error::ContextPoisoned)?; + if hb.len() != 368640 { + return Err(Error::InvalidQwenShape); + } + let hist = hb.handle.ok_or(Error::ContextPoisoned)?; + hist.validate_projection_extent(368640, 4)?; + workspace.reject_alias(hist, 368640)?; + let key = self.weight(lease, workspace, weights.key, 52428800, 2)?; + let value = self.weight(lease, workspace, weights.value, 13107200, 2)?; + let mut aux = [key; 4]; + for (i, w) in weights.aux.iter().enumerate() { + aux[i] = self.weight( + lease, + workspace, + w, + if i == 3 { 81920 } else { 40960 }, + if i == 3 { 2 } else { 4 }, + )?; + } + let sb = lease.ple_subbatch_capacity()?; + let total = lease.rows(); + for first in (0..total).step_by(sb) { + let t = sb.min(total - first); + let rh = Self::span(lease, S::R, 40960)?.checked_subspan( + total * 40960, + first * 40960, + t * 40960, + )?; + let eh = Self::span(lease, S::PleEmbedding, 10240)?.checked_subspan( + total * 10240, + first * 10240, + t * 10240, + )?; + let get = |role: P| -> Result { + let (h, n) = lease.ple_span(role, t)?; + workspace.reject_alias(h, n)?; + if h.overlaps(n, hist, 368640) || h.overlaps(n, self.status()?, self.capacity * 40) + { + return Err(Error::OutputAliasesInput); + } + for (w, wn) in [ + (key, 52428800), + (value, 13107200), + (aux[0], 40960), + (aux[1], 40960), + (aux[2], 40960), + (aux[3], 81920), + ] { + if h.overlaps(n, w, wn) { + return Err(Error::OutputAliasesInput); + } + } + Ok(h) + }; + let kh = get(P::Key)?; + let qn = get(P::Qn)?; + let gated = get(P::Gated)?; + let val = get(P::Value)?; + let gate = get(P::Gate)?; + let packed = get(P::PackedEmbedding)?; + let low = if self.mode == PleBf16Mode::HighAndLow { + Some(get(P::PackedEmbeddingLow)?) + } else { + None + }; + for (h, n) in [ + (rh, t * 40960), + (eh, t * 10240), + (self.status()?, self.capacity * 40), + ] { + if h.overlaps(n, hist, 368640) { + return Err(Error::OutputAliasesInput); + } + } + for (w, n) in [ + (key, 52428800), + (value, 13107200), + (aux[0], 40960), + (aux[1], 40960), + (aux[2], 40960), + (aux[3], 81920), + ] { + if w.overlaps(n, hist, 368640) { + return Err(Error::OutputAliasesInput); + } + } + let flags = self.status()?; + let mut v = Vec::new(); + v.try_reserve_exact(28).map_err(|_| Error::HostAllocation)?; + // Candidate history is source bytes, never a caller finite witness. + scan_ple(&mut v, hist, flags, 92160, 1, 8); + kernel( + &mut v, + 0, + 0, + (t * 2560).div_ceil(256), + 256, + vec![ + A::Address(eh), + A::Address(packed), + low.map_or(A::NullAddress, A::Address), + A::I64((t * 2560) as i64), + ], + ); + for (out, n, w, role) in [(kh, 10240, key, 0), (val, 2560, value, 1)] { + v.push(C::Gemm { + input: packed, + weight: w, + output: out, + t: t as i32, + n, + k: 2560, + alpha: 1., + beta: 0., + }); + if let Some(l) = low { + v.push(C::Gemm { + input: l, + weight: w, + output: out, + t: t as i32, + n, + k: 2560, + alpha: 1., + beta: 1., + }) + } + scan_ple(&mut v, out, flags, n as usize, t, role); + } + // Literal native_ple_postops_batch reuses Key and Qn in place. + kernel( + &mut v, + 1, + 0, + t * 4, + 1024, + vec![A::Address(kh), A::Address(aux[0]), A::Address(kh)], + ); + scan_ple(&mut v, kh, flags, 10240, t, 2); + kernel( + &mut v, + 1, + 0, + t * 4, + 1024, + vec![A::Address(rh), A::Address(aux[1]), A::Address(qn)], + ); + scan_ple(&mut v, qn, flags, 10240, t, 3); + kernel( + &mut v, + 1, + 1, + t * 4, + 512, + vec![ + A::Address(kh), + A::Address(qn), + A::Address(gate), + A::F32(1. / 2560.0f32.sqrt()), + ], + ); + scan_ple(&mut v, gate, flags, 4, t, 4); + kernel( + &mut v, + 1, + 2, + t * 40, + 256, + vec![ + A::Address(val), + A::Address(gate), + A::Address(gated), + A::I32(t as i32), + ], + ); + scan_ple(&mut v, gated, flags, 10240, t, 5); + kernel( + &mut v, + 1, + 0, + t * 4, + 1024, + vec![A::Address(gated), A::Address(aux[2]), A::Address(qn)], + ); + scan_ple(&mut v, qn, flags, 10240, t, 6); + kernel( + &mut v, + 1, + 3, + t * 40, + 256, + vec![ + A::Address(hist), + A::Address(qn), + A::Address(aux[3]), + A::Address(rh), + A::Address(gated), + A::Address(flags), + A::I32(t as i32), + ], + ); + kernel( + &mut v, + 1, + 4, + 40, + 256, + vec![A::Address(hist), A::Address(qn), A::I32(t as i32)], + ); + scan_ple(&mut v, hist, flags, 92160, 1, 8); + scan_ple(&mut v, rh, flags, 10240, t, 9); + if let Err(e) = self.run( + lease, + workspace, + v, + t, + 10, + &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + &[ + "PLE key", + "PLE value", + "PLE key norm", + "PLE query norm", + "PLE gate", + "PLE gated", + "PLE normalized", + "PLE conv", + "PLE history", + "PLE streams", + ], + ) { + history.failed = true; + return Err(e); + } + } + Ok(residual) + } +} diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_4.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_4.rs new file mode 100644 index 00000000..dac6ead7 --- /dev/null +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_4.rs @@ -0,0 +1,31 @@ +//! Moved out of the parent module by STRA-338: impl OriginalPromptDevice (4). + +#[allow(unused_imports)] +use super::*; + + + +impl<'ctx> OriginalPromptDevice<'ctx> { + pub fn read_gr<'arena, 'loan>( + &mut self, + residual: OriginalDeviceResidual<'arena, 'loan, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + weights: [&DeviceBuffer<'_>; 4], + epsilon: f32, + ) -> Result> { + self.read_gr_impl(residual, workspace, weights, epsilon, false) + } + pub fn read_gr_normed<'weight, 'arena, 'loan>( + &mut self, + normed: OriginalDeviceNormedResidual<'weight, 'arena, 'loan, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + weights: [&DeviceBuffer<'_>; 4], + epsilon: f32, + ) -> Result> { + if !std::ptr::eq(normed.gamma, weights[0]) || normed.epsilon.to_bits() != epsilon.to_bits() + { + return Err(Error::InvalidQwenShape); + } + self.read_gr_impl(normed.residual, workspace, weights, epsilon, true) + } +} diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_5.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_5.rs new file mode 100644 index 00000000..31bbe2dd --- /dev/null +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_5.rs @@ -0,0 +1,251 @@ +//! Moved out of the parent module by STRA-338: impl OriginalPromptDevice (5). + +#[allow(unused_imports)] +use super::*; + + + +impl<'ctx> OriginalPromptDevice<'ctx> { + pub(in super::super) fn read_gr_impl<'arena, 'loan>( + &mut self, + mut residual: OriginalDeviceResidual<'arena, 'loan, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + weights: [&DeviceBuffer<'_>; 4], + epsilon: f32, + normed: bool, + ) -> Result> { + self.profile_tag = if normed { "readn" } else { "read" }; + let lease = &mut residual.lease; + self.validate(lease, workspace)?; + if !epsilon.is_finite() || epsilon < 0. { + return Err(Error::InvalidQwenShape); + } + let t = lease.rows(); + let mut h = [self.status()?; 15]; + for (i, r, n) in [ + (0, S::R, 40960), + (1, S::GrRS, 16), + (2, S::XHigh, 20480), + (4, S::Lo, 1280), + (5, S::LoHigh, 640), + (7, S::Gated, 40960), + (8, S::Mixed, 10240), + (9, S::MixedHigh, 5120), + (11, S::MixedHalf, 5120), + (12, S::Inject, 16), + (13, S::Block, 10240), + ] { + h[i] = Self::span(lease, r, n)?; + } + if self.profile == GrNativeProfile::HighAndLow { + for (i, r, n) in [ + (3, S::XLow, 20480), + (6, S::LoLow, 640), + (10, S::MixedLow, 5120), + ] { + h[i] = Self::span(lease, r, n)?; + } + } + let mut w = [h[0]; 4]; + for (i, n) in [40960, 6553600, 6553600, 81920].into_iter().enumerate() { + w[i] = self.weight(lease, workspace, weights[i], n, if i == 0 { 4 } else { 2 })?; + } + let low = |i| { + if self.profile == GrNativeProfile::HighAndLow { + A::Address(h[i]) + } else { + A::NullAddress + } + }; + let flags = self.status()?; + let mut v = Vec::new(); + v.try_reserve_exact(20).map_err(|_| Error::HostAllocation)?; + let fused = fused_scans(); + if fused { + // the norm guard rides on the norm kernel; a normed read follows `inject_gr_fused`, which already guarded + // this very norm (same R, rs and gamma), so nothing is left to scan + if !normed { + kernel( + &mut v, + 3, + 3, + t * 4, + 256, + vec![ + A::Address(h[0]), + A::Address(w[0]), + A::F32(epsilon), + A::Address(h[1]), + A::Address(h[2]), + low(3), + A::Address(flags), + ], + ); + } + } else { + if !normed { + kernel( + &mut v, + 2, + 0, + t * 4, + 256, + vec![ + A::Address(h[0]), + A::Address(w[0]), + A::F32(epsilon), + A::Address(h[1]), + A::Address(h[2]), + low(3), + ], + ); + } + kernel( + &mut v, + 2, + 5, + (t * 10240).div_ceil(256), + 256, + vec![ + A::Address(h[0]), + A::Address(h[1]), + A::Address(w[0]), + A::Address(flags), + A::I64(t as i64), + ], + ); + } + let gemm = |v: &mut Vec, input, lo, weight, out, n, k| { + v.push(C::Gemm { + input: h[input], + weight, + output: h[out], + t: t as i32, + n, + k, + alpha: 1., + beta: 0., + }); + if self.profile == GrNativeProfile::HighAndLow { + v.push(C::Gemm { + input: h[lo], + weight, + output: h[out], + t: t as i32, + n, + k, + alpha: 1., + beta: 1., + }) + } + }; + gemm(&mut v, 2, 3, w[1], 4, 320, 10240); + scan_gr(&mut v, h[4], flags, 320, t, 1); + kernel( + &mut v, + 2, + 1, + (t * 320).div_ceil(256), + 256, + vec![ + A::Address(h[4]), + A::Address(h[5]), + low(6), + A::I64((t * 320) as i64), + ], + ); + kernel( + &mut v, + 2, + 6, + (t * 320).div_ceil(256), + 256, + vec![A::Address(h[4]), A::Address(flags), A::I64(t as i64)], + ); + gemm(&mut v, 5, 6, w[2], 7, 10240, 320); + if !fused { + scan_gr(&mut v, h[7], flags, 10240, t, 3); + } + // Original injection GEMM precedes mixed production. + gemm(&mut v, 2, 3, w[3], 12, 4, 10240); + scan_gr(&mut v, h[12], flags, 4, t, 6); + if fused { + // mix + the guards of the gated tensor (3), the products (4) and the mixed row (5) + kernel( + &mut v, + 3, + 4, + (t * 2560).div_ceil(256), + 256, + vec![ + A::Address(h[0]), + A::Address(h[1]), + A::Address(w[0]), + A::Address(h[7]), + A::Address(h[8]), + A::Address(h[9]), + A::I64(t as i64), + A::Address(h[11]), + low(10), + A::Address(flags), + ], + ); + } else { + kernel( + &mut v, + 2, + 2, + (t * 2560).div_ceil(256), + 256, + vec![ + A::Address(h[0]), + A::Address(h[1]), + A::Address(w[0]), + A::Address(h[7]), + A::Address(h[8]), + A::Address(h[9]), + A::I64(t as i64), + A::Address(h[11]), + low(10), + ], + ); + kernel( + &mut v, + 2, + 7, + (t * 10240).div_ceil(256), + 256, + vec![ + A::Address(h[0]), + A::Address(h[1]), + A::Address(w[0]), + A::Address(h[7]), + A::Address(flags), + A::I64(t as i64), + ], + ); + scan_gr(&mut v, h[8], flags, 2560, t, 5); + } + self.run( + lease, + workspace, + v, + t, + 8, + &[0, 1, 2, 3, 6, 4, 5], + &[ + "GR native norm", + "GR native down", + "GR native silu", + "GR native up", + "GR native products", + "GR native mixed", + "GR native inject", + "GR native candidate", + ], + )?; + Ok(OriginalDeviceGrRead { + lease: residual.lease, + }) + } +} diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_6.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_6.rs new file mode 100644 index 00000000..e1a52482 --- /dev/null +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_6.rs @@ -0,0 +1,244 @@ +//! Moved out of the parent module by STRA-338: impl OriginalPromptDevice (6). + +#[allow(unused_imports)] +use super::*; + + + +impl<'ctx> OriginalPromptDevice<'ctx> { + /// A completed real attention/MoE producer moved the read lease into Block. + /// Recheck its full actual Block before the Original ascending R write. + pub fn inject_gr<'arena, 'loan>( + &mut self, + mut block: OriginalDeviceBlock<'arena, 'loan, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + ) -> Result> { + self.profile_tag = "injectchk"; + let lease = &mut block.read.lease; + self.validate(lease, workspace)?; + let t = lease.rows(); + let flags = self.status()?; + let r = Self::span(lease, S::R, 40960)?; + let b = Self::span(lease, S::Block, 10240)?; + let inj = Self::span(lease, S::Inject, 16)?; + // Prewrite full Block scan/drain rejects numerical errors before R is + // modified. No host floats are treated as a device-completion witness. + let mut check = Vec::new(); + check + .try_reserve_exact(1) + .map_err(|_| Error::HostAllocation)?; + scan_gr(&mut check, b, flags, 2560, t, 7); + self.run( + lease, + workspace, + check, + t, + 8, + &[7], + &[ + "unused", + "unused", + "unused", + "unused", + "unused", + "unused", + "unused", + "GR native block", + ], + )?; + self.profile_tag = "inject"; + let mut v = Vec::new(); + v.try_reserve_exact(2).map_err(|_| Error::HostAllocation)?; + if fused_scans() { + kernel( + &mut v, + 3, + 6, + (t * 10240).div_ceil(256), + 256, + vec![ + A::Address(r), + A::Address(b), + A::Address(inj), + A::I64(4), + A::I64(t as i64), + A::Address(flags), + ], + ); + } else { + kernel( + &mut v, + 2, + 3, + (t * 10240).div_ceil(256), + 256, + vec![ + A::Address(r), + A::Address(b), + A::Address(inj), + A::I64(4), + A::I64(t as i64), + ], + ); + scan_gr(&mut v, r, flags, 10240, t, 7); + } + self.run( + lease, + workspace, + v, + t, + 8, + &[7], + &[ + "unused", + "unused", + "unused", + "unused", + "unused", + "unused", + "unused", + "GR native candidate", + ], + )?; + Ok(OriginalDeviceResidual { + lease: block.read.lease, + }) + } + pub fn inject_gr_fused<'weight, 'arena, 'loan>( + &mut self, + mut block: OriginalDeviceBlock<'arena, 'loan, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + gamma: &'weight DeviceBuffer<'ctx>, + epsilon: f32, + ) -> Result> { + self.profile_tag = "injectchk"; + let lease = &mut block.read.lease; + self.validate(lease, workspace)?; + if !epsilon.is_finite() || epsilon < 0. { + return Err(Error::InvalidQwenShape); + } + let w = self.weight(lease, workspace, gamma, 40960, 4)?; + let t = lease.rows(); + let flags = self.status()?; + let r = Self::span(lease, S::R, 40960)?; + let b = Self::span(lease, S::Block, 10240)?; + let inj = Self::span(lease, S::Inject, 16)?; + let rs = Self::span(lease, S::GrRS, 16)?; + let high = Self::span(lease, S::XHigh, 20480)?; + let low = if self.profile == GrNativeProfile::HighAndLow { + A::Address(Self::span(lease, S::XLow, 20480)?) + } else { + A::NullAddress + }; + let mut check = Vec::new(); + check + .try_reserve_exact(1) + .map_err(|_| Error::HostAllocation)?; + scan_gr(&mut check, b, flags, 2560, t, 7); + self.run( + lease, + workspace, + check, + t, + 8, + &[7], + &[ + "unused", + "unused", + "unused", + "unused", + "unused", + "unused", + "unused", + "GR native block", + ], + )?; + self.profile_tag = "injectf"; + let mut v = Vec::new(); + v.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?; + if fused_scans() { + // write + the guards of R after the write (7) and of the next half's norm (0) + kernel( + &mut v, + 3, + 5, + t * 4, + 256, + vec![ + A::Address(r), + A::Address(b), + A::Address(inj), + A::I64(4), + A::Address(w), + A::F32(epsilon), + A::Address(rs), + A::Address(high), + low, + A::Address(flags), + ], + ); + } else { + kernel( + &mut v, + 2, + 8, + t * 4, + 256, + vec![ + A::Address(r), + A::Address(b), + A::Address(inj), + A::I64(4), + A::Address(w), + A::F32(epsilon), + A::Address(rs), + A::Address(high), + low, + ], + ); + scan_gr(&mut v, r, flags, 10240, t, 7); + kernel( + &mut v, + 2, + 5, + (t * 10240).div_ceil(256), + 256, + vec![ + A::Address(r), + A::Address(rs), + A::Address(w), + A::Address(flags), + A::I64(t as i64), + ], + ); + } + self.run( + lease, + workspace, + v, + t, + 8, + &[7, 0], + &[ + "GR native next norm", + "unused", + "unused", + "unused", + "unused", + "unused", + "unused", + "GR native candidate", + ], + )?; + Ok(OriginalDeviceNormedResidual { + residual: OriginalDeviceResidual { + lease: block.read.lease, + }, + gamma, + epsilon, + }) + } + pub fn close(mut self) -> Result<()> { + self.close_inner() + } +} diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_7.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_7.rs new file mode 100644 index 00000000..b92541b6 --- /dev/null +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_7.rs @@ -0,0 +1,57 @@ +//! Moved out of the parent module by STRA-338: impl OriginalPromptDevice (7). + +#[allow(unused_imports)] +use super::*; + + + +impl<'ctx> OriginalPromptDevice<'ctx> { + pub(in super::super) fn close_inner(&mut self) -> Result<()> { + self.failed = true; + let mut result = Ok(()); + for m in [ + self.pack.take(), + self.ple.take(), + self.gr.take(), + self.stage.take(), + ] + .into_iter() + .flatten() + { + let r = if self.context.is_poisoned() { + std::mem::forget(m); + Err(Error::ContextPoisoned) + } else { + match self.context.enter() { + Ok(g) => combine(m.close(), g.finish()), + Err(e) => { + std::mem::forget(m); + Err(e) + } + } + }; + if r.is_err() { + self.context.poison(); + self.context.retain_driver() + } + result = combine(result, r); + } + for b in [self.status.take(), self.stage_scratch.take()] + .into_iter() + .flatten() + { + let r = if self.context.is_poisoned() { + std::mem::forget(b); + Err(Error::ContextPoisoned) + } else { + b.release() + }; + if r.is_err() { + self.context.poison(); + self.context.retain_driver() + } + result = combine(result, r) + } + result + } +} diff --git a/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache.rs b/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache.rs index 88b25dd4..185e650a 100644 --- a/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache.rs +++ b/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache.rs @@ -3,862 +3,7 @@ #[allow(unused_imports)] use super::*; - -impl<'ctx> OriginalExpertCache<'ctx> { - pub(crate) fn validate_file_source_context(&self, c: &Context<'_>) -> Result<()> { - self.ensure_live()?; - if !std::ptr::eq(c, self.context) { - return Err(Error::ContextMismatch); - } - Ok(()) - } - pub(crate) fn completed_file_source_member( - &self, - c: &Context<'_>, - layer: usize, - expert: usize, - digest: [u8; 32], - ) -> Result> { - self.validate_file_source_context(c)?; - if self.file_source_digest != Some(digest) { - return Err(Error::InvalidSize); - } - let Some(slot) = self.owners.iter().position(|p| *p == Some((layer, expert))) else { - return Ok(None); - }; - if self.states.get(slot) != Some(&State::Filled) { - return Ok(None); - } - self.slot_handle(slot).map(Some) - } - - pub(super) fn open(context: &'ctx Context<'ctx>, table: OriginalExpertSlots) -> Result { - if context.is_poisoned() { - return Err(Error::ContextPoisoned); - } - let bytes = table.bytes(); - // Literal Original free-VRAM check before the one contiguous cudaMalloc. - if context.memory_info()?.0 < bytes - || context - .allocated_bytes() - .checked_add(bytes) - .is_none_or(|n| n > context.budget_bytes()) - { - return Err(Error::BudgetExceeded); - } - let mut states = Vec::new(); - let mut owners = Vec::new(); - states - .try_reserve_exact(table.slots()) - .map_err(|_| Error::HostAllocation)?; - owners - .try_reserve_exact(table.slots()) - .map_err(|_| Error::HostAllocation)?; - states.resize(table.slots(), State::Empty); - owners.resize(table.slots(), None); - let mut cache = Self { - context, - buffer: Some(context.allocate(bytes)?), - table, - api: None, - states, - owners, - pending: Vec::new(), - file_source_digest: None, - fills: 0, - attempted: false, - failed: false, - swap_stream: None, - fill_stream: None, - swap_event: None, - swapping: Vec::new(), - swap_sources: Vec::new(), - swap_armed: false, - swaps: 0, - }; - let guard = context.enter()?; - let operation = (|| { - cache.api = Some(api::AsyncApi::load()?); - let handle = cache - .buffer - .as_ref() - .ok_or(Error::ContextPoisoned)? - .handle - .ok_or(Error::ContextPoisoned)?; - handle.validate_extent(bytes)?; - cache.attempted = true; - cache - .api - .as_ref() - .ok_or(Error::ContextPoisoned)? - .zero(handle.qwen_address(), bytes)?; - Ok(()) - })(); - let result = combine(operation, guard.finish()); - if let Err(primary) = result { - if cache.attempted { - cache.poison(); - } - return combine(Err(primary), cache.close_inner()); - } - Ok(cache) - } - pub fn slots(&self) -> usize { - self.table.slots() - } - pub fn bytes(&self) -> usize { - self.table.bytes() - } - pub fn resident(&self) -> usize { - self.table.resident() - } - pub fn fills(&self) -> u64 { - self.fills - } - /// Original auto's second memset, device fence, then actual free reading. - /// Initial open's memset stays queued on the default stream until a real - /// fill/close/auto fence; no extra success fence is inserted at open. - pub fn zero_written_free_info(&mut self) -> Result { - self.ensure_live()?; - if self.states.iter().any(|s| *s != State::Empty) || !self.pending.is_empty() { - return Err(Error::InvalidSize); - } - let guard = self.context.enter()?; - let result = (|| { - let b = self.buffer.as_ref().ok_or(Error::ContextPoisoned)?; - self.attempted = true; - self.api.as_ref().ok_or(Error::ContextPoisoned)?.zero( - b.handle.ok_or(Error::ContextPoisoned)?.qwen_address(), - b.bytes, - )?; - self.context.driver.api.synchronize()?; - self.attempted = false; - Ok(()) - })(); - let result = combine(result, guard.finish()); - if result.is_err() { - self.poison(); - return result.map(|_| 0); - } - self.context.memory_info().map(|(free, _)| free) - } - pub fn set_per_layer_admission(&mut self, enabled: bool) { - self.table.set_per_layer_admission(enabled); - } - pub fn per_layer_admission(&self) -> bool { - self.table.per_layer_admission() - } - pub fn slot_of(&self, layer: usize, expert: usize) -> i32 { - self.table.slot_of(layer, expert) - } - /// The verify window's residency test (`host_res[l * n_expert + e] >= 0`): the slot holding the expert, - /// only once its bytes were genuinely copied and fenced. A lent, queued or swapped-out slot is a miss. - pub fn resident_slot(&self, layer: usize, expert: usize) -> Option { - let slot = usize::try_from(self.table.slot_of(layer, expert)).ok()?; - (self.states.get(slot) == Some(&State::Filled) - && self.owners.get(slot).copied().flatten() == Some((layer, expert))) - .then_some(slot) - } - /// The (layer, expert) a slot was admitted for (or swapped to). - pub fn slot_owner(&self, slot: usize) -> Option<(usize, usize)> { - self.owners.get(slot).copied().flatten() - } - /// Per-layer slot range `[lo, hi)` of `--expert-cache-per-layer` (R4.2g). - pub fn layer_slot_range(&self, layer: usize) -> (usize, usize) { - self.table.layer_slot_range(layer) - } - /// Adaptive swaps issued since open. - pub fn swaps(&self) -> u64 { - self.swaps - } - /// generate.cpp `adapt` (one swap): the slot of `out` (resident, same layer) is given to the expert of - /// `spans` and its bytes are copied on the adaptive tier's own stream. `out` is a miss from now on and - /// the new expert becomes resident only when `poll_swaps` sees the batch's event complete. - pub fn swap_slot_queued( - &mut self, - slot: usize, - bank: Rc>, - spans: [ResidentExpertBankSpan; 3], - ) -> Result<()> { - self.ensure_live()?; - if self.file_source_digest.is_some() || !bank.cache_context_matches(self.context) || !bank.eligible(&spans) { - return Err(Error::InvalidSize); - } - let layer = match spans[0].role() { - TensorRole::Layer { layer, .. } => usize::from(layer), - _ => return Err(Error::InvalidSize), - }; - let to = (layer, spans[0].expert() as usize); - let from = self.owners.get(slot).copied().flatten().ok_or(Error::InvalidSize)?; - if !matches!(self.states.get(slot), Some(State::Filled) | Some(State::NeedsRefill)) || self.swap_armed { - return Err(Error::InvalidSize); - } - let (handle, capacity) = self.slot_handle(slot)?; - let mut total = 0usize; - for span in &spans { - bank.cache_source(span)?; - total = total.checked_add(span.bytes().len()).ok_or(Error::InvalidSize)?; - } - if total > capacity { - return Err(Error::ShapeMismatch { expected: capacity, actual: total }); - } - self.swapping.try_reserve(1).map_err(|_| Error::HostAllocation)?; - self.swap_sources.try_reserve(1).map_err(|_| Error::HostAllocation)?; - self.table.reassign(slot, from, to)?; - self.owners[slot] = Some(to); - // From here the slot holds neither expert until the copy is fenced. - self.states[slot] = State::NeedsRefill; - self.swap_sources.push(RetainedFill::Mapped { bank, spans }); - let guard = self.context.enter()?; - let operation = (|| { - let api = self.api.as_ref().ok_or(Error::ContextPoisoned)?; - if self.swap_stream.is_none() { - self.swap_stream = Some(api.create_stream()?); - } - let stream = self.swap_stream.ok_or(Error::ContextPoisoned)?; - let RetainedFill::Mapped { bank, spans } = self.swap_sources.last().ok_or(Error::ContextPoisoned)? else { - return Err(Error::InvalidSize); - }; - let mut offset = 0usize; - for span in spans { - let source = bank.cache_source(span)?; - for (at, bytes) in bank.copy_pieces(source) { - let destination = handle.checked_subspan(capacity, offset + at, bytes)?; - api.copy(destination.qwen_address(), &source[at..at + bytes], stream)?; - } - offset += source.len(); - } - Ok(()) - })(); - let result = combine(operation, guard.finish()); - if result.is_err() { - self.poison(); - return result; - } - self.states[slot] = State::Queued; - self.swapping.push(slot); - self.swaps = self.swaps.checked_add(1).ok_or(Error::InvalidSize)?; - self.fills = self.fills.checked_add(1).ok_or(Error::InvalidSize)?; - Ok(()) - } - /// `cudaEventRecord(adapt_ev, adapt_stream)` after a batch of swaps; nothing to do without swaps. - pub fn arm_swaps(&mut self) -> Result<()> { - self.ensure_live()?; - if self.swapping.is_empty() || self.swap_armed { - return Ok(()); - } - let guard = self.context.enter()?; - let operation = (|| { - let api = self.api.as_ref().ok_or(Error::ContextPoisoned)?; - if self.swap_event.is_none() { - self.swap_event = Some(api.create_event()?); - } - api.record(self.swap_event.ok_or(Error::ContextPoisoned)?, self.swap_stream.ok_or(Error::ContextPoisoned)?) - })(); - let result = combine(operation, guard.finish()); - if result.is_err() { - self.poison(); - return result; - } - self.swap_armed = true; - Ok(()) - } - /// True while swaps are queued and not yet published (`!pending.empty()`). - pub fn swaps_pending(&self) -> bool { - !self.swapping.is_empty() - } - /// generate.cpp `apply_pending(false)`: when the batch's event has completed, every swapped slot becomes - /// resident (`host_res[in] = slot`) and its sources are released. NOT_READY publishes nothing. - pub fn poll_swaps(&mut self) -> Result { - self.ensure_live()?; - if self.swapping.is_empty() { - return Ok(true); - } - if !self.swap_armed { - return Ok(false); - } - let guard = self.context.enter()?; - let query = self - .api - .as_ref() - .ok_or(Error::ContextPoisoned) - .and_then(|api| api.query(self.swap_event.ok_or(Error::ContextPoisoned)?)); - match combine(query, guard.finish()) { - Err(error) => { - self.poison(); - Err(error) - } - Ok(false) => Ok(false), - Ok(true) => { - self.complete_swaps(); - Ok(true) - } - } - } - pub(super) fn complete_swaps(&mut self) { - for &slot in &self.swapping { - if self.states[slot] == State::Queued { - self.states[slot] = State::Filled; - } - } - self.swapping.clear(); - self.swap_sources.clear(); - self.swap_armed = false; - } - /// generate.cpp `apply_pending(true)`: wait for the swaps in flight, then publish them. - pub fn wait_swaps(&mut self) -> Result<()> { - self.ensure_live()?; - if self.swapping.is_empty() { - return Ok(()); - } - let guard = self.context.enter()?; - let wait = self - .api - .as_ref() - .ok_or(Error::ContextPoisoned) - .and_then(|api| api.synchronize_stream(self.swap_stream.ok_or(Error::ContextPoisoned)?)); - let result = combine(wait, guard.finish()); - if result.is_err() { - self.poison(); - return result; - } - self.complete_swaps(); - Ok(()) - } - /// Model-free probes only (feature `expert-tier-probe`): fill an admitted slot from caller bytes with a - /// blocking copy. Production fills come from the registered model bank or the pinned file source only. - #[cfg(any(test, feature = "expert-tier-probe"))] - pub fn probe_fill_slot(&mut self, slot: usize, bytes: &[u8]) -> Result<()> { - self.ensure_live()?; - if self.owners.get(slot).copied().flatten().is_none() || !self.pending.is_empty() || !self.swapping.is_empty() { - return Err(Error::InvalidSize); - } - let (handle, capacity) = self.slot_handle(slot)?; - if bytes.is_empty() || bytes.len() > capacity { - return Err(Error::InvalidSize); - } - let handle = handle.checked_subspan(capacity, 0, bytes.len())?; - let guard = self.context.enter()?; - let copy = self.context.driver.api.copy_from(handle, bytes); - let result = combine(copy, guard.finish()); - if result.is_err() { - self.poison(); - return result; - } - self.states[slot] = State::Filled; - self.fills = self.fills.checked_add(1).ok_or(Error::InvalidSize)?; - Ok(()) - } - pub fn admit(&mut self, layer: usize, expert: usize) -> Result { - self.ensure_live()?; - let slot = self.table.admit(layer, expert); - if slot >= 0 { - self.owners[slot as usize] = Some((layer, expert)); - } - Ok(slot) - } - pub(super) fn ensure_live(&self) -> Result<()> { - if self.failed || self.context.is_poisoned() || self.buffer.is_none() { - Err(Error::ContextPoisoned) - } else { - Ok(()) - } - } - pub(super) fn slot_handle(&self, slot: usize) -> Result<(ffi::BufferHandle, usize)> { - self.ensure_live()?; - let (offset, bytes) = self.table.slot_span(slot)?; - let b = self.buffer.as_ref().ok_or(Error::ContextPoisoned)?; - Ok(( - b.handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(b.bytes, offset, bytes)?, - bytes, - )) - } - /// Same encoded gate/up/down layout as Original native_expert::Format. - /// Three immutable registered role slices replace the contiguous host blob; - /// destination bytes and ordering are identical, with no assembled clone. - pub fn fill_slot_queued( - &mut self, - slot: usize, - bank: Rc>, - spans: [ResidentExpertBankSpan; 3], - ) -> Result<()> { - self.fill_slot_queued_on(slot, bank, spans, false) - } - /// `fill_slot_queued` on the cache's own non-blocking stream: other users of the default stream (small synchronous - /// uploads of the decode phase) do not wait behind the copies. `sync_queued` is still the fence. - pub fn fill_slot_queued_async( - &mut self, - slot: usize, - bank: Rc>, - spans: [ResidentExpertBankSpan; 3], - ) -> Result<()> { - self.fill_slot_queued_on(slot, bank, spans, true) - } - pub(super) fn fill_slot_queued_on( - &mut self, - slot: usize, - bank: Rc>, - spans: [ResidentExpertBankSpan; 3], - own_stream: bool, - ) -> Result<()> { - self.ensure_live()?; - if self.file_source_digest.is_some() { - return Err(Error::InvalidSize); - } - if !bank.cache_context_matches(self.context) { - return Err(Error::ContextMismatch); - } - if !bank.eligible(&spans) { - return Err(Error::InvalidSize); - } - let layer = match spans[0].role() { - TensorRole::Layer { layer, .. } => usize::from(layer), - _ => return Err(Error::InvalidSize), - }; - if self.owners.get(slot).copied().flatten() != Some((layer, spans[0].expert() as usize)) { - return Err(Error::InvalidSize); - } - if self.states.get(slot) == Some(&State::Queued) { - return Err(Error::InvalidSize); - } - let (handle, capacity) = self.slot_handle(slot)?; - let mut total = 0usize; - for span in &spans { - bank.cache_source(span)?; - total = total - .checked_add(span.bytes().len()) - .ok_or(Error::InvalidSize)?; - } - if total > capacity { - return Err(Error::ShapeMismatch { - expected: capacity, - actual: total, - }); - } - self.pending - .try_reserve(1) - .map_err(|_| Error::HostAllocation)?; - let next_fills = self.fills.checked_add(1).ok_or(Error::InvalidSize)?; - // Retain the real Arc/Rc-backed registered source BEFORE any enqueue. - self.pending.push(RetainedFill::Mapped { bank, spans }); - let guard = self.context.enter()?; - let operation = (|| { - let RetainedFill::Mapped { bank, spans } = - self.pending.last().ok_or(Error::ContextPoisoned)? - else { - return Err(Error::InvalidSize); - }; - let stream = if own_stream { - if self.fill_stream.is_none() { - self.fill_stream = Some(self.api.as_ref().ok_or(Error::ContextPoisoned)?.create_stream()?); - } - self.fill_stream.ok_or(Error::ContextPoisoned)? - } else { - api::Stream(0) - }; - let mut offset = 0usize; - for span in spans { - let source = bank.cache_source(span)?; - for (at, bytes) in bank.copy_pieces(source) { - let destination = handle.checked_subspan(capacity, offset + at, bytes)?; - self.attempted = true; - self.api.as_ref().ok_or(Error::ContextPoisoned)?.copy( - destination.qwen_address(), - &source[at..at + bytes], - stream, - )?; - } - offset += source.len(); - } - Ok(()) - })(); - let result = combine(operation, guard.finish()); - if result.is_err() { - self.poison(); - return result; - } - self.states[slot] = State::Queued; - self.fills = next_fills; - Ok(()) - } - /// Original contiguous G/U/D startup/refill: one actual H2D on the default - /// stream. The authentic assembled source and its admitted FD/context stay - /// owned by this cache until the batch fence. A table admission is not a hit. - pub fn fill_file_slot_queued( - &mut self, - slot: usize, - blob: crate::OriginalFileExpertBlob<'ctx>, - ) -> Result<()> { - self.ensure_live()?; - blob.validate_context(self.context)?; - let digest = blob.source_digest(); - if self.file_source_digest.is_some_and(|bound| bound != digest) - || self.file_source_digest.is_none() && self.states.iter().any(|s| *s != State::Empty) - || self - .pending - .iter() - .any(|fill| matches!(fill, RetainedFill::Mapped { .. })) - { - return Err(Error::InvalidSize); - } - if self.owners.get(slot).copied().flatten() - != Some((usize::from(blob.layer()), blob.expert() as usize)) - || self.states.get(slot) == Some(&State::Queued) - { - return Err(Error::InvalidSize); - } - let (handle, capacity) = self.slot_handle(slot)?; - if blob.bytes().len() > capacity { - return Err(Error::ShapeMismatch { - expected: capacity, - actual: blob.bytes().len(), - }); - } - self.pending - .try_reserve(1) - .map_err(|_| Error::HostAllocation)?; - let next_fills = self.fills.checked_add(1).ok_or(Error::InvalidSize)?; - self.pending.push(RetainedFill::File(blob)); - self.file_source_digest = Some(digest); - let guard = self.context.enter()?; - let copy = (|| { - let RetainedFill::File(blob) = self.pending.last().ok_or(Error::ContextPoisoned)? - else { - return Err(Error::InvalidSize); - }; - blob.validate_context(self.context)?; - self.attempted = true; - self.api.as_ref().ok_or(Error::ContextPoisoned)?.copy( - handle.qwen_address(), - blob.bytes(), - api::Stream(0), - ) - })(); - let result = combine(copy, guard.finish()); - if result.is_err() { - self.poison(); - return result; - } - self.states[slot] = State::Queued; - self.fills = next_fills; - Ok(()) - } - /// Actual retained host charge for pending owned file assemblies, so the - /// caller subtracts it before assembling the next expert in a startup batch. - pub fn pending_file_host_bytes(&self) -> Result { - self.ensure_live()?; - let metadata = self - .pending - .capacity() - .checked_mul(std::mem::size_of::>()) - .ok_or(Error::BudgetExceeded)?; - self.pending - .iter() - .try_fold(metadata, |n, fill| match fill { - RetainedFill::File(blob) => n - .checked_add(blob.bytes().len()) - .and_then(|n| n.checked_add(blob.retained_metadata_bytes())) - .ok_or(Error::BudgetExceeded), - RetainedFill::Mapped { .. } => Ok(n), - }) - } - /// Startup uses Original's blocking cudaMemcpy semantics, rather than - /// substituting a queued batch. The same owned blob survives uncertain DMA. - pub fn fill_file_slot_blocking( - &mut self, - slot: usize, - blob: crate::OriginalFileExpertBlob<'ctx>, - ) -> Result<()> { - self.ensure_live()?; - blob.validate_context(self.context)?; - if !self.pending.is_empty() { - return Err(Error::InvalidSize); - } - let digest = blob.source_digest(); - if self.file_source_digest.is_some_and(|bound| bound != digest) - || self.file_source_digest.is_none() && self.states.iter().any(|s| *s != State::Empty) - || self.owners.get(slot).copied().flatten() - != Some((usize::from(blob.layer()), blob.expert() as usize)) - { - return Err(Error::InvalidSize); - } - let (handle, capacity) = self.slot_handle(slot)?; - let count = blob.bytes().len(); - let handle = handle.checked_subspan(capacity, 0, count)?; - self.pending - .try_reserve(1) - .map_err(|_| Error::HostAllocation)?; - let next_fills = self.fills.checked_add(1).ok_or(Error::InvalidSize)?; - self.pending.push(RetainedFill::File(blob)); - self.file_source_digest = Some(digest); - let guard = self.context.enter()?; - self.attempted = true; - let copy = (|| { - let RetainedFill::File(blob) = self.pending.last().ok_or(Error::ContextPoisoned)? - else { - return Err(Error::InvalidSize); - }; - blob.validate_context(self.context)?; - self.context.driver.api.copy_from(handle, blob.bytes()) - })(); - let result = combine(copy, guard.finish()); - if result.is_err() { - self.poison(); - return result; - } - self.states[slot] = State::Filled; - self.fills = next_fills; - self.attempted = false; - self.pending.clear(); - Ok(()) - } - pub fn verify_file_slot( - &mut self, - slot: usize, - blob: &crate::OriginalFileExpertBlob<'ctx>, - ) -> Result<()> { - self.sync_queued()?; - blob.validate_context(self.context)?; - if self.file_source_digest != Some(blob.source_digest()) - || self.owners.get(slot).copied().flatten() - != Some((usize::from(blob.layer()), blob.expert() as usize)) - || self.states.get(slot) != Some(&State::Filled) - { - return Err(Error::InvalidSize); - } - let (handle, capacity) = self.slot_handle(slot)?; - let count = blob.bytes().len(); - let handle = handle.checked_subspan(capacity, 0, count)?; - let mut got = Vec::new(); - got.try_reserve_exact(count) - .map_err(|_| Error::HostAllocation)?; - got.resize(count, 0); - let guard = self.context.enter()?; - let copy = self.context.driver.api.copy_to(handle, &mut got); - let sync = self.context.driver.api.synchronize(); - if sync.is_err() { - self.poison(); - std::mem::forget(got); - return combine(combine(copy, sync), guard.finish()); - } - combine(combine(copy, sync), guard.finish())?; - if got.as_slice() != blob.bytes() { - self.states[slot] = State::NeedsRefill; - return Err(Error::InvalidDriverValue( - "Original expert cache source byte mismatch", - )); - } - Ok(()) - } - /// Exactly one default-stream fence for all preceding startup/refill copies. - /// NOT_READY/transport errors never publish the table as usable GPU weights. - pub fn sync_queued(&mut self) -> Result<()> { - self.wait_swaps()?; - self.ensure_live()?; - if !self.attempted { - return Ok(()); - } - let guard = self.context.enter()?; - let wait = self - .api - .as_ref() - .ok_or(Error::ContextPoisoned)? - .synchronize_stream(api::Stream(0)); - let wait = match (wait, self.fill_stream, self.api.as_ref()) { - (Ok(()), Some(stream), Some(api)) => api.synchronize_stream(stream), - (wait, _, _) => wait, - }; - let result = combine(wait, guard.finish()); - if result.is_err() { - self.poison(); - return result; - } - for state in &mut self.states { - if *state == State::Queued { - *state = State::Filled; - } - } - self.attempted = false; - self.pending.clear(); - Ok(()) - } - pub fn fill_slot_blocking( - &mut self, - slot: usize, - bank: Rc>, - spans: [ResidentExpertBankSpan; 3], - ) -> Result<()> { - self.fill_slot_queued(slot, bank, spans)?; - self.sync_queued() - } - /// Actual startup byte audit against the same retained source. Neither - /// finite values nor successful allocation substitutes for this readback. - pub fn verify_slot( - &mut self, - slot: usize, - bank: &MappedExpertBank<'ctx>, - spans: &[ResidentExpertBankSpan; 3], - ) -> Result<()> { - self.sync_queued()?; - if !bank.cache_context_matches(self.context) || !bank.eligible(spans) { - return Err(Error::ContextMismatch); - } - let layer = match spans[0].role() { - TensorRole::Layer { layer, .. } => usize::from(layer), - _ => return Err(Error::InvalidSize), - }; - if self.owners.get(slot).copied().flatten() != Some((layer, spans[0].expert() as usize)) - || self.states.get(slot) != Some(&State::Filled) - { - return Err(Error::InvalidSize); - } - let count = spans.iter().try_fold(0usize, |n, s| { - n.checked_add(s.bytes().len()).ok_or(Error::InvalidSize) - })?; - let (handle, capacity) = self.slot_handle(slot)?; - let handle = handle.checked_subspan(capacity, 0, count)?; - let mut got = Vec::new(); - got.try_reserve_exact(count) - .map_err(|_| Error::HostAllocation)?; - got.resize(count, 0); - let guard = self.context.enter()?; - let copy = self.context.driver.api.copy_to(handle, &mut got); - let sync = self.context.driver.api.synchronize(); - if sync.is_err() { - self.poison(); - std::mem::forget(got); - return combine(combine(copy, sync), guard.finish()); - } - combine(combine(copy, sync), guard.finish())?; - let mut offset = 0; - for span in spans { - let source = bank.cache_source(span)?; - if got[offset..offset + source.len()] != *source { - self.states[slot] = State::NeedsRefill; - return Err(Error::InvalidDriverValue( - "Original expert cache source byte mismatch", - )); - } - offset += source.len(); - } - Ok(()) - } - /// Private consumers receive checked nonowning handles only after genuine - /// completion. No synthetic DeviceBuffer is minted for a slot subspan. - pub(crate) fn completed_slot(&self, slot: usize) -> Result<(ffi::BufferHandle, usize)> { - if self.states.get(slot) != Some(&State::Filled) { - return Err(Error::InvalidSize); - } - self.slot_handle(slot) - } - pub fn choose_loan( - &self, - requested: usize, - auto: bool, - auto_max: usize, - context: usize, - lend_percent: usize, - needed: impl FnMut(usize) -> Result, - ) -> Result> { - self.ensure_live()?; - self.table - .choose_loan(requested, auto, auto_max, context, lend_percent, needed) - } - /// generate.cpp `part_slots`: the slots from the end of the cache that hold `bytes_needed`. - pub fn lend_slots(&self, bytes_needed: usize) -> Result { - self.ensure_live()?; - self.table.lend_slots(bytes_needed) - } - /// Holding this owner excludes every cache refill/use through &mut self. - /// Overwritten residents remain NeedsRefill after the loan ends until their - /// real original bytes have been copied and fenced again. - pub fn lend_prefill_tail<'loan>( - &'loan mut self, - slots: usize, - options: PrefillLayoutOptions, - ) -> Result> { - if crate::arch_ptx::chunk_drain() { - self.context.synchronize()?; - } - self.sync_queued()?; - let (offset, bytes) = self.table.loan_span(slots)?; - if options.carve()?.source_bytes_needed > bytes { - return Err(Error::BudgetExceeded); - } - let first = self.table.slots() - slots; - for state in &mut self.states[first..] { - if *state == State::Filled { - *state = State::NeedsRefill; - } - } - let prefix = OriginalCachePrefix { - table: &self.table, - states: &self.states[..first], - }; - OriginalPrefillArena::from_cache_tail( - self.buffer.as_mut().ok_or(Error::ContextPoisoned)?, - offset, - bytes, - options, - prefix, - ) - } - pub fn needs_refill(&self, slot: usize) -> Result> { - self.ensure_live()?; - let state = self.states.get(slot).ok_or(Error::InvalidSize)?; - Ok(if *state == State::NeedsRefill { - self.owners[slot] - } else { - None - }) - } - pub(super) fn poison(&mut self) { - self.failed = true; - self.context.poison(); - self.context.retain_driver(); - } - pub fn close(mut self) -> Result<()> { - self.close_inner() - } - pub(super) fn close_inner(&mut self) -> Result<()> { - if self.buffer.is_none() { - return Ok(()); - } - let drain = self.sync_queued(); - if drain.is_err() || self.context.is_poisoned() { - self.poison(); - std::mem::forget(std::mem::take(&mut self.pending)); - std::mem::forget(std::mem::take(&mut self.swap_sources)); - if let Some(buffer) = self.buffer.take() { - std::mem::forget(buffer); - } - if let Some(api) = self.api.take() { - std::mem::forget(api); - } - return drain.and(Err(Error::ContextPoisoned)); - } - self.failed = true; - self.pending.clear(); - let mut released = Ok(()); - if self.swap_event.is_some() || self.swap_stream.is_some() || self.fill_stream.is_some() { - let guard = self.context.enter()?; - if let Some(api) = self.api.as_ref() { - if let Some(event) = self.swap_event.take() { - released = combine(released, api.destroy_event(event)); - } - if let Some(stream) = self.fill_stream.take() { - released = combine(released, api.destroy_stream(stream)); - } - if let Some(stream) = self.swap_stream.take() { - released = combine(released, api.destroy_stream(stream)); - } - } - released = combine(released, guard.finish()); - } - let released = combine(released, self.buffer.take().ok_or(Error::ContextPoisoned)?.release()); - self.api.take(); - released - } -} +mod impl_originalexpertcache_2; +mod impl_originalexpertcache_2_2; +mod impl_originalexpertcache_3; +mod impl_originalexpertcache_4; diff --git a/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_2.rs b/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_2.rs new file mode 100644 index 00000000..45e35014 --- /dev/null +++ b/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_2.rs @@ -0,0 +1,245 @@ +//! Moved out of the parent module by STRA-338: impl OriginalExpertCache. + +#[allow(unused_imports)] +use super::*; + + + +impl<'ctx> OriginalExpertCache<'ctx> { + pub(crate) fn validate_file_source_context(&self, c: &Context<'_>) -> Result<()> { + self.ensure_live()?; + if !std::ptr::eq(c, self.context) { + return Err(Error::ContextMismatch); + } + Ok(()) + } + pub(crate) fn completed_file_source_member( + &self, + c: &Context<'_>, + layer: usize, + expert: usize, + digest: [u8; 32], + ) -> Result> { + self.validate_file_source_context(c)?; + if self.file_source_digest != Some(digest) { + return Err(Error::InvalidSize); + } + let Some(slot) = self.owners.iter().position(|p| *p == Some((layer, expert))) else { + return Ok(None); + }; + if self.states.get(slot) != Some(&State::Filled) { + return Ok(None); + } + self.slot_handle(slot).map(Some) + } + + pub(in super::super) fn open(context: &'ctx Context<'ctx>, table: OriginalExpertSlots) -> Result { + if context.is_poisoned() { + return Err(Error::ContextPoisoned); + } + let bytes = table.bytes(); + // Literal Original free-VRAM check before the one contiguous cudaMalloc. + if context.memory_info()?.0 < bytes + || context + .allocated_bytes() + .checked_add(bytes) + .is_none_or(|n| n > context.budget_bytes()) + { + return Err(Error::BudgetExceeded); + } + let mut states = Vec::new(); + let mut owners = Vec::new(); + states + .try_reserve_exact(table.slots()) + .map_err(|_| Error::HostAllocation)?; + owners + .try_reserve_exact(table.slots()) + .map_err(|_| Error::HostAllocation)?; + states.resize(table.slots(), State::Empty); + owners.resize(table.slots(), None); + let mut cache = Self { + context, + buffer: Some(context.allocate(bytes)?), + table, + api: None, + states, + owners, + pending: Vec::new(), + file_source_digest: None, + fills: 0, + attempted: false, + failed: false, + swap_stream: None, + fill_stream: None, + swap_event: None, + swapping: Vec::new(), + swap_sources: Vec::new(), + swap_armed: false, + swaps: 0, + }; + let guard = context.enter()?; + let operation = (|| { + cache.api = Some(api::AsyncApi::load()?); + let handle = cache + .buffer + .as_ref() + .ok_or(Error::ContextPoisoned)? + .handle + .ok_or(Error::ContextPoisoned)?; + handle.validate_extent(bytes)?; + cache.attempted = true; + cache + .api + .as_ref() + .ok_or(Error::ContextPoisoned)? + .zero(handle.qwen_address(), bytes)?; + Ok(()) + })(); + let result = combine(operation, guard.finish()); + if let Err(primary) = result { + if cache.attempted { + cache.poison(); + } + return combine(Err(primary), cache.close_inner()); + } + Ok(cache) + } + pub fn slots(&self) -> usize { + self.table.slots() + } + pub fn bytes(&self) -> usize { + self.table.bytes() + } + pub fn resident(&self) -> usize { + self.table.resident() + } + pub fn fills(&self) -> u64 { + self.fills + } + /// Original auto's second memset, device fence, then actual free reading. + /// Initial open's memset stays queued on the default stream until a real + /// fill/close/auto fence; no extra success fence is inserted at open. + pub fn zero_written_free_info(&mut self) -> Result { + self.ensure_live()?; + if self.states.iter().any(|s| *s != State::Empty) || !self.pending.is_empty() { + return Err(Error::InvalidSize); + } + let guard = self.context.enter()?; + let result = (|| { + let b = self.buffer.as_ref().ok_or(Error::ContextPoisoned)?; + self.attempted = true; + self.api.as_ref().ok_or(Error::ContextPoisoned)?.zero( + b.handle.ok_or(Error::ContextPoisoned)?.qwen_address(), + b.bytes, + )?; + self.context.driver.api.synchronize()?; + self.attempted = false; + Ok(()) + })(); + let result = combine(result, guard.finish()); + if result.is_err() { + self.poison(); + return result.map(|_| 0); + } + self.context.memory_info().map(|(free, _)| free) + } + pub fn set_per_layer_admission(&mut self, enabled: bool) { + self.table.set_per_layer_admission(enabled); + } + pub fn per_layer_admission(&self) -> bool { + self.table.per_layer_admission() + } + pub fn slot_of(&self, layer: usize, expert: usize) -> i32 { + self.table.slot_of(layer, expert) + } + /// The verify window's residency test (`host_res[l * n_expert + e] >= 0`): the slot holding the expert, + /// only once its bytes were genuinely copied and fenced. A lent, queued or swapped-out slot is a miss. + pub fn resident_slot(&self, layer: usize, expert: usize) -> Option { + let slot = usize::try_from(self.table.slot_of(layer, expert)).ok()?; + (self.states.get(slot) == Some(&State::Filled) + && self.owners.get(slot).copied().flatten() == Some((layer, expert))) + .then_some(slot) + } + /// The (layer, expert) a slot was admitted for (or swapped to). + pub fn slot_owner(&self, slot: usize) -> Option<(usize, usize)> { + self.owners.get(slot).copied().flatten() + } + /// Per-layer slot range `[lo, hi)` of `--expert-cache-per-layer` (R4.2g). + pub fn layer_slot_range(&self, layer: usize) -> (usize, usize) { + self.table.layer_slot_range(layer) + } + /// Adaptive swaps issued since open. + pub fn swaps(&self) -> u64 { + self.swaps + } + /// generate.cpp `adapt` (one swap): the slot of `out` (resident, same layer) is given to the expert of + /// `spans` and its bytes are copied on the adaptive tier's own stream. `out` is a miss from now on and + /// the new expert becomes resident only when `poll_swaps` sees the batch's event complete. + pub fn swap_slot_queued( + &mut self, + slot: usize, + bank: Rc>, + spans: [ResidentExpertBankSpan; 3], + ) -> Result<()> { + self.ensure_live()?; + if self.file_source_digest.is_some() || !bank.cache_context_matches(self.context) || !bank.eligible(&spans) { + return Err(Error::InvalidSize); + } + let layer = match spans[0].role() { + TensorRole::Layer { layer, .. } => usize::from(layer), + _ => return Err(Error::InvalidSize), + }; + let to = (layer, spans[0].expert() as usize); + let from = self.owners.get(slot).copied().flatten().ok_or(Error::InvalidSize)?; + if !matches!(self.states.get(slot), Some(State::Filled) | Some(State::NeedsRefill)) || self.swap_armed { + return Err(Error::InvalidSize); + } + let (handle, capacity) = self.slot_handle(slot)?; + let mut total = 0usize; + for span in &spans { + bank.cache_source(span)?; + total = total.checked_add(span.bytes().len()).ok_or(Error::InvalidSize)?; + } + if total > capacity { + return Err(Error::ShapeMismatch { expected: capacity, actual: total }); + } + self.swapping.try_reserve(1).map_err(|_| Error::HostAllocation)?; + self.swap_sources.try_reserve(1).map_err(|_| Error::HostAllocation)?; + self.table.reassign(slot, from, to)?; + self.owners[slot] = Some(to); + // From here the slot holds neither expert until the copy is fenced. + self.states[slot] = State::NeedsRefill; + self.swap_sources.push(RetainedFill::Mapped { bank, spans }); + let guard = self.context.enter()?; + let operation = (|| { + let api = self.api.as_ref().ok_or(Error::ContextPoisoned)?; + if self.swap_stream.is_none() { + self.swap_stream = Some(api.create_stream()?); + } + let stream = self.swap_stream.ok_or(Error::ContextPoisoned)?; + let RetainedFill::Mapped { bank, spans } = self.swap_sources.last().ok_or(Error::ContextPoisoned)? else { + return Err(Error::InvalidSize); + }; + let mut offset = 0usize; + for span in spans { + let source = bank.cache_source(span)?; + for (at, bytes) in bank.copy_pieces(source) { + let destination = handle.checked_subspan(capacity, offset + at, bytes)?; + api.copy(destination.qwen_address(), &source[at..at + bytes], stream)?; + } + offset += source.len(); + } + Ok(()) + })(); + let result = combine(operation, guard.finish()); + if result.is_err() { + self.poison(); + return result; + } + self.states[slot] = State::Queued; + self.swapping.push(slot); + self.swaps = self.swaps.checked_add(1).ok_or(Error::InvalidSize)?; + self.fills = self.fills.checked_add(1).ok_or(Error::InvalidSize)?; + Ok(()) + } +} diff --git a/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_2_2.rs b/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_2_2.rs new file mode 100644 index 00000000..58f0eb8c --- /dev/null +++ b/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_2_2.rs @@ -0,0 +1,251 @@ +//! Moved out of the parent module by STRA-338: impl OriginalExpertCache (2). + +#[allow(unused_imports)] +use super::*; + + + +impl<'ctx> OriginalExpertCache<'ctx> { + /// `cudaEventRecord(adapt_ev, adapt_stream)` after a batch of swaps; nothing to do without swaps. + pub fn arm_swaps(&mut self) -> Result<()> { + self.ensure_live()?; + if self.swapping.is_empty() || self.swap_armed { + return Ok(()); + } + let guard = self.context.enter()?; + let operation = (|| { + let api = self.api.as_ref().ok_or(Error::ContextPoisoned)?; + if self.swap_event.is_none() { + self.swap_event = Some(api.create_event()?); + } + api.record(self.swap_event.ok_or(Error::ContextPoisoned)?, self.swap_stream.ok_or(Error::ContextPoisoned)?) + })(); + let result = combine(operation, guard.finish()); + if result.is_err() { + self.poison(); + return result; + } + self.swap_armed = true; + Ok(()) + } + /// True while swaps are queued and not yet published (`!pending.empty()`). + pub fn swaps_pending(&self) -> bool { + !self.swapping.is_empty() + } + /// generate.cpp `apply_pending(false)`: when the batch's event has completed, every swapped slot becomes + /// resident (`host_res[in] = slot`) and its sources are released. NOT_READY publishes nothing. + pub fn poll_swaps(&mut self) -> Result { + self.ensure_live()?; + if self.swapping.is_empty() { + return Ok(true); + } + if !self.swap_armed { + return Ok(false); + } + let guard = self.context.enter()?; + let query = self + .api + .as_ref() + .ok_or(Error::ContextPoisoned) + .and_then(|api| api.query(self.swap_event.ok_or(Error::ContextPoisoned)?)); + match combine(query, guard.finish()) { + Err(error) => { + self.poison(); + Err(error) + } + Ok(false) => Ok(false), + Ok(true) => { + self.complete_swaps(); + Ok(true) + } + } + } + pub(in super::super) fn complete_swaps(&mut self) { + for &slot in &self.swapping { + if self.states[slot] == State::Queued { + self.states[slot] = State::Filled; + } + } + self.swapping.clear(); + self.swap_sources.clear(); + self.swap_armed = false; + } + /// generate.cpp `apply_pending(true)`: wait for the swaps in flight, then publish them. + pub fn wait_swaps(&mut self) -> Result<()> { + self.ensure_live()?; + if self.swapping.is_empty() { + return Ok(()); + } + let guard = self.context.enter()?; + let wait = self + .api + .as_ref() + .ok_or(Error::ContextPoisoned) + .and_then(|api| api.synchronize_stream(self.swap_stream.ok_or(Error::ContextPoisoned)?)); + let result = combine(wait, guard.finish()); + if result.is_err() { + self.poison(); + return result; + } + self.complete_swaps(); + Ok(()) + } + /// Model-free probes only (feature `expert-tier-probe`): fill an admitted slot from caller bytes with a + /// blocking copy. Production fills come from the registered model bank or the pinned file source only. + #[cfg(any(test, feature = "expert-tier-probe"))] + pub fn probe_fill_slot(&mut self, slot: usize, bytes: &[u8]) -> Result<()> { + self.ensure_live()?; + if self.owners.get(slot).copied().flatten().is_none() || !self.pending.is_empty() || !self.swapping.is_empty() { + return Err(Error::InvalidSize); + } + let (handle, capacity) = self.slot_handle(slot)?; + if bytes.is_empty() || bytes.len() > capacity { + return Err(Error::InvalidSize); + } + let handle = handle.checked_subspan(capacity, 0, bytes.len())?; + let guard = self.context.enter()?; + let copy = self.context.driver.api.copy_from(handle, bytes); + let result = combine(copy, guard.finish()); + if result.is_err() { + self.poison(); + return result; + } + self.states[slot] = State::Filled; + self.fills = self.fills.checked_add(1).ok_or(Error::InvalidSize)?; + Ok(()) + } + pub fn admit(&mut self, layer: usize, expert: usize) -> Result { + self.ensure_live()?; + let slot = self.table.admit(layer, expert); + if slot >= 0 { + self.owners[slot as usize] = Some((layer, expert)); + } + Ok(slot) + } + pub(in super::super) fn ensure_live(&self) -> Result<()> { + if self.failed || self.context.is_poisoned() || self.buffer.is_none() { + Err(Error::ContextPoisoned) + } else { + Ok(()) + } + } + pub(in super::super) fn slot_handle(&self, slot: usize) -> Result<(ffi::BufferHandle, usize)> { + self.ensure_live()?; + let (offset, bytes) = self.table.slot_span(slot)?; + let b = self.buffer.as_ref().ok_or(Error::ContextPoisoned)?; + Ok(( + b.handle + .ok_or(Error::ContextPoisoned)? + .checked_subspan(b.bytes, offset, bytes)?, + bytes, + )) + } + /// Same encoded gate/up/down layout as Original native_expert::Format. + /// Three immutable registered role slices replace the contiguous host blob; + /// destination bytes and ordering are identical, with no assembled clone. + pub fn fill_slot_queued( + &mut self, + slot: usize, + bank: Rc>, + spans: [ResidentExpertBankSpan; 3], + ) -> Result<()> { + self.fill_slot_queued_on(slot, bank, spans, false) + } + /// `fill_slot_queued` on the cache's own non-blocking stream: other users of the default stream (small synchronous + /// uploads of the decode phase) do not wait behind the copies. `sync_queued` is still the fence. + pub fn fill_slot_queued_async( + &mut self, + slot: usize, + bank: Rc>, + spans: [ResidentExpertBankSpan; 3], + ) -> Result<()> { + self.fill_slot_queued_on(slot, bank, spans, true) + } + pub(in super::super) fn fill_slot_queued_on( + &mut self, + slot: usize, + bank: Rc>, + spans: [ResidentExpertBankSpan; 3], + own_stream: bool, + ) -> Result<()> { + self.ensure_live()?; + if self.file_source_digest.is_some() { + return Err(Error::InvalidSize); + } + if !bank.cache_context_matches(self.context) { + return Err(Error::ContextMismatch); + } + if !bank.eligible(&spans) { + return Err(Error::InvalidSize); + } + let layer = match spans[0].role() { + TensorRole::Layer { layer, .. } => usize::from(layer), + _ => return Err(Error::InvalidSize), + }; + if self.owners.get(slot).copied().flatten() != Some((layer, spans[0].expert() as usize)) { + return Err(Error::InvalidSize); + } + if self.states.get(slot) == Some(&State::Queued) { + return Err(Error::InvalidSize); + } + let (handle, capacity) = self.slot_handle(slot)?; + let mut total = 0usize; + for span in &spans { + bank.cache_source(span)?; + total = total + .checked_add(span.bytes().len()) + .ok_or(Error::InvalidSize)?; + } + if total > capacity { + return Err(Error::ShapeMismatch { + expected: capacity, + actual: total, + }); + } + self.pending + .try_reserve(1) + .map_err(|_| Error::HostAllocation)?; + let next_fills = self.fills.checked_add(1).ok_or(Error::InvalidSize)?; + // Retain the real Arc/Rc-backed registered source BEFORE any enqueue. + self.pending.push(RetainedFill::Mapped { bank, spans }); + let guard = self.context.enter()?; + let operation = (|| { + let RetainedFill::Mapped { bank, spans } = + self.pending.last().ok_or(Error::ContextPoisoned)? + else { + return Err(Error::InvalidSize); + }; + let stream = if own_stream { + if self.fill_stream.is_none() { + self.fill_stream = Some(self.api.as_ref().ok_or(Error::ContextPoisoned)?.create_stream()?); + } + self.fill_stream.ok_or(Error::ContextPoisoned)? + } else { + api::Stream(0) + }; + let mut offset = 0usize; + for span in spans { + let source = bank.cache_source(span)?; + for (at, bytes) in bank.copy_pieces(source) { + let destination = handle.checked_subspan(capacity, offset + at, bytes)?; + self.attempted = true; + self.api.as_ref().ok_or(Error::ContextPoisoned)?.copy( + destination.qwen_address(), + &source[at..at + bytes], + stream, + )?; + } + offset += source.len(); + } + Ok(()) + })(); + let result = combine(operation, guard.finish()); + if result.is_err() { + self.poison(); + return result; + } + self.states[slot] = State::Queued; + self.fills = next_fills; + Ok(()) + } +} diff --git a/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_3.rs b/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_3.rs new file mode 100644 index 00000000..c90edad4 --- /dev/null +++ b/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_3.rs @@ -0,0 +1,219 @@ +//! Moved out of the parent module by STRA-338: impl OriginalExpertCache (3). + +#[allow(unused_imports)] +use super::*; + + + +impl<'ctx> OriginalExpertCache<'ctx> { + /// Original contiguous G/U/D startup/refill: one actual H2D on the default + /// stream. The authentic assembled source and its admitted FD/context stay + /// owned by this cache until the batch fence. A table admission is not a hit. + pub fn fill_file_slot_queued( + &mut self, + slot: usize, + blob: crate::OriginalFileExpertBlob<'ctx>, + ) -> Result<()> { + self.ensure_live()?; + blob.validate_context(self.context)?; + let digest = blob.source_digest(); + if self.file_source_digest.is_some_and(|bound| bound != digest) + || self.file_source_digest.is_none() && self.states.iter().any(|s| *s != State::Empty) + || self + .pending + .iter() + .any(|fill| matches!(fill, RetainedFill::Mapped { .. })) + { + return Err(Error::InvalidSize); + } + if self.owners.get(slot).copied().flatten() + != Some((usize::from(blob.layer()), blob.expert() as usize)) + || self.states.get(slot) == Some(&State::Queued) + { + return Err(Error::InvalidSize); + } + let (handle, capacity) = self.slot_handle(slot)?; + if blob.bytes().len() > capacity { + return Err(Error::ShapeMismatch { + expected: capacity, + actual: blob.bytes().len(), + }); + } + self.pending + .try_reserve(1) + .map_err(|_| Error::HostAllocation)?; + let next_fills = self.fills.checked_add(1).ok_or(Error::InvalidSize)?; + self.pending.push(RetainedFill::File(blob)); + self.file_source_digest = Some(digest); + let guard = self.context.enter()?; + let copy = (|| { + let RetainedFill::File(blob) = self.pending.last().ok_or(Error::ContextPoisoned)? + else { + return Err(Error::InvalidSize); + }; + blob.validate_context(self.context)?; + self.attempted = true; + self.api.as_ref().ok_or(Error::ContextPoisoned)?.copy( + handle.qwen_address(), + blob.bytes(), + api::Stream(0), + ) + })(); + let result = combine(copy, guard.finish()); + if result.is_err() { + self.poison(); + return result; + } + self.states[slot] = State::Queued; + self.fills = next_fills; + Ok(()) + } + /// Actual retained host charge for pending owned file assemblies, so the + /// caller subtracts it before assembling the next expert in a startup batch. + pub fn pending_file_host_bytes(&self) -> Result { + self.ensure_live()?; + let metadata = self + .pending + .capacity() + .checked_mul(std::mem::size_of::>()) + .ok_or(Error::BudgetExceeded)?; + self.pending + .iter() + .try_fold(metadata, |n, fill| match fill { + RetainedFill::File(blob) => n + .checked_add(blob.bytes().len()) + .and_then(|n| n.checked_add(blob.retained_metadata_bytes())) + .ok_or(Error::BudgetExceeded), + RetainedFill::Mapped { .. } => Ok(n), + }) + } + /// Startup uses Original's blocking cudaMemcpy semantics, rather than + /// substituting a queued batch. The same owned blob survives uncertain DMA. + pub fn fill_file_slot_blocking( + &mut self, + slot: usize, + blob: crate::OriginalFileExpertBlob<'ctx>, + ) -> Result<()> { + self.ensure_live()?; + blob.validate_context(self.context)?; + if !self.pending.is_empty() { + return Err(Error::InvalidSize); + } + let digest = blob.source_digest(); + if self.file_source_digest.is_some_and(|bound| bound != digest) + || self.file_source_digest.is_none() && self.states.iter().any(|s| *s != State::Empty) + || self.owners.get(slot).copied().flatten() + != Some((usize::from(blob.layer()), blob.expert() as usize)) + { + return Err(Error::InvalidSize); + } + let (handle, capacity) = self.slot_handle(slot)?; + let count = blob.bytes().len(); + let handle = handle.checked_subspan(capacity, 0, count)?; + self.pending + .try_reserve(1) + .map_err(|_| Error::HostAllocation)?; + let next_fills = self.fills.checked_add(1).ok_or(Error::InvalidSize)?; + self.pending.push(RetainedFill::File(blob)); + self.file_source_digest = Some(digest); + let guard = self.context.enter()?; + self.attempted = true; + let copy = (|| { + let RetainedFill::File(blob) = self.pending.last().ok_or(Error::ContextPoisoned)? + else { + return Err(Error::InvalidSize); + }; + blob.validate_context(self.context)?; + self.context.driver.api.copy_from(handle, blob.bytes()) + })(); + let result = combine(copy, guard.finish()); + if result.is_err() { + self.poison(); + return result; + } + self.states[slot] = State::Filled; + self.fills = next_fills; + self.attempted = false; + self.pending.clear(); + Ok(()) + } + pub fn verify_file_slot( + &mut self, + slot: usize, + blob: &crate::OriginalFileExpertBlob<'ctx>, + ) -> Result<()> { + self.sync_queued()?; + blob.validate_context(self.context)?; + if self.file_source_digest != Some(blob.source_digest()) + || self.owners.get(slot).copied().flatten() + != Some((usize::from(blob.layer()), blob.expert() as usize)) + || self.states.get(slot) != Some(&State::Filled) + { + return Err(Error::InvalidSize); + } + let (handle, capacity) = self.slot_handle(slot)?; + let count = blob.bytes().len(); + let handle = handle.checked_subspan(capacity, 0, count)?; + let mut got = Vec::new(); + got.try_reserve_exact(count) + .map_err(|_| Error::HostAllocation)?; + got.resize(count, 0); + let guard = self.context.enter()?; + let copy = self.context.driver.api.copy_to(handle, &mut got); + let sync = self.context.driver.api.synchronize(); + if sync.is_err() { + self.poison(); + std::mem::forget(got); + return combine(combine(copy, sync), guard.finish()); + } + combine(combine(copy, sync), guard.finish())?; + if got.as_slice() != blob.bytes() { + self.states[slot] = State::NeedsRefill; + return Err(Error::InvalidDriverValue( + "Original expert cache source byte mismatch", + )); + } + Ok(()) + } + /// Exactly one default-stream fence for all preceding startup/refill copies. + /// NOT_READY/transport errors never publish the table as usable GPU weights. + pub fn sync_queued(&mut self) -> Result<()> { + self.wait_swaps()?; + self.ensure_live()?; + if !self.attempted { + return Ok(()); + } + let guard = self.context.enter()?; + let wait = self + .api + .as_ref() + .ok_or(Error::ContextPoisoned)? + .synchronize_stream(api::Stream(0)); + let wait = match (wait, self.fill_stream, self.api.as_ref()) { + (Ok(()), Some(stream), Some(api)) => api.synchronize_stream(stream), + (wait, _, _) => wait, + }; + let result = combine(wait, guard.finish()); + if result.is_err() { + self.poison(); + return result; + } + for state in &mut self.states { + if *state == State::Queued { + *state = State::Filled; + } + } + self.attempted = false; + self.pending.clear(); + Ok(()) + } + pub fn fill_slot_blocking( + &mut self, + slot: usize, + bank: Rc>, + spans: [ResidentExpertBankSpan; 3], + ) -> Result<()> { + self.fill_slot_queued(slot, bank, spans)?; + self.sync_queued() + } +} diff --git a/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_4.rs b/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_4.rs new file mode 100644 index 00000000..efd423b0 --- /dev/null +++ b/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_4.rs @@ -0,0 +1,177 @@ +//! Moved out of the parent module by STRA-338: impl OriginalExpertCache (4). + +#[allow(unused_imports)] +use super::*; + + + +impl<'ctx> OriginalExpertCache<'ctx> { + /// Actual startup byte audit against the same retained source. Neither + /// finite values nor successful allocation substitutes for this readback. + pub fn verify_slot( + &mut self, + slot: usize, + bank: &MappedExpertBank<'ctx>, + spans: &[ResidentExpertBankSpan; 3], + ) -> Result<()> { + self.sync_queued()?; + if !bank.cache_context_matches(self.context) || !bank.eligible(spans) { + return Err(Error::ContextMismatch); + } + let layer = match spans[0].role() { + TensorRole::Layer { layer, .. } => usize::from(layer), + _ => return Err(Error::InvalidSize), + }; + if self.owners.get(slot).copied().flatten() != Some((layer, spans[0].expert() as usize)) + || self.states.get(slot) != Some(&State::Filled) + { + return Err(Error::InvalidSize); + } + let count = spans.iter().try_fold(0usize, |n, s| { + n.checked_add(s.bytes().len()).ok_or(Error::InvalidSize) + })?; + let (handle, capacity) = self.slot_handle(slot)?; + let handle = handle.checked_subspan(capacity, 0, count)?; + let mut got = Vec::new(); + got.try_reserve_exact(count) + .map_err(|_| Error::HostAllocation)?; + got.resize(count, 0); + let guard = self.context.enter()?; + let copy = self.context.driver.api.copy_to(handle, &mut got); + let sync = self.context.driver.api.synchronize(); + if sync.is_err() { + self.poison(); + std::mem::forget(got); + return combine(combine(copy, sync), guard.finish()); + } + combine(combine(copy, sync), guard.finish())?; + let mut offset = 0; + for span in spans { + let source = bank.cache_source(span)?; + if got[offset..offset + source.len()] != *source { + self.states[slot] = State::NeedsRefill; + return Err(Error::InvalidDriverValue( + "Original expert cache source byte mismatch", + )); + } + offset += source.len(); + } + Ok(()) + } + /// Private consumers receive checked nonowning handles only after genuine + /// completion. No synthetic DeviceBuffer is minted for a slot subspan. + pub(crate) fn completed_slot(&self, slot: usize) -> Result<(ffi::BufferHandle, usize)> { + if self.states.get(slot) != Some(&State::Filled) { + return Err(Error::InvalidSize); + } + self.slot_handle(slot) + } + pub fn choose_loan( + &self, + requested: usize, + auto: bool, + auto_max: usize, + context: usize, + lend_percent: usize, + needed: impl FnMut(usize) -> Result, + ) -> Result> { + self.ensure_live()?; + self.table + .choose_loan(requested, auto, auto_max, context, lend_percent, needed) + } + /// generate.cpp `part_slots`: the slots from the end of the cache that hold `bytes_needed`. + pub fn lend_slots(&self, bytes_needed: usize) -> Result { + self.ensure_live()?; + self.table.lend_slots(bytes_needed) + } + /// Holding this owner excludes every cache refill/use through &mut self. + /// Overwritten residents remain NeedsRefill after the loan ends until their + /// real original bytes have been copied and fenced again. + pub fn lend_prefill_tail<'loan>( + &'loan mut self, + slots: usize, + options: PrefillLayoutOptions, + ) -> Result> { + if crate::arch_ptx::chunk_drain() { + self.context.synchronize()?; + } + self.sync_queued()?; + let (offset, bytes) = self.table.loan_span(slots)?; + if options.carve()?.source_bytes_needed > bytes { + return Err(Error::BudgetExceeded); + } + let first = self.table.slots() - slots; + for state in &mut self.states[first..] { + if *state == State::Filled { + *state = State::NeedsRefill; + } + } + let prefix = OriginalCachePrefix { + table: &self.table, + states: &self.states[..first], + }; + OriginalPrefillArena::from_cache_tail( + self.buffer.as_mut().ok_or(Error::ContextPoisoned)?, + offset, + bytes, + options, + prefix, + ) + } + pub fn needs_refill(&self, slot: usize) -> Result> { + self.ensure_live()?; + let state = self.states.get(slot).ok_or(Error::InvalidSize)?; + Ok(if *state == State::NeedsRefill { + self.owners[slot] + } else { + None + }) + } + pub(in super::super) fn poison(&mut self) { + self.failed = true; + self.context.poison(); + self.context.retain_driver(); + } + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + pub(in super::super) fn close_inner(&mut self) -> Result<()> { + if self.buffer.is_none() { + return Ok(()); + } + let drain = self.sync_queued(); + if drain.is_err() || self.context.is_poisoned() { + self.poison(); + std::mem::forget(std::mem::take(&mut self.pending)); + std::mem::forget(std::mem::take(&mut self.swap_sources)); + if let Some(buffer) = self.buffer.take() { + std::mem::forget(buffer); + } + if let Some(api) = self.api.take() { + std::mem::forget(api); + } + return drain.and(Err(Error::ContextPoisoned)); + } + self.failed = true; + self.pending.clear(); + let mut released = Ok(()); + if self.swap_event.is_some() || self.swap_stream.is_some() || self.fill_stream.is_some() { + let guard = self.context.enter()?; + if let Some(api) = self.api.as_ref() { + if let Some(event) = self.swap_event.take() { + released = combine(released, api.destroy_event(event)); + } + if let Some(stream) = self.fill_stream.take() { + released = combine(released, api.destroy_stream(stream)); + } + if let Some(stream) = self.swap_stream.take() { + released = combine(released, api.destroy_stream(stream)); + } + } + released = combine(released, guard.finish()); + } + let released = combine(released, self.buffer.take().ok_or(Error::ContextPoisoned)?.release()); + self.api.take(); + released + } +} diff --git a/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource.rs b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource.rs index 4fa5323f..2104a6b0 100644 --- a/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource.rs +++ b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource.rs @@ -3,842 +3,7 @@ #[allow(unused_imports)] use super::*; -impl<'ctx> OriginalFileExpertSource<'ctx> { - pub(super) fn live(&self) -> Result<()> { - if self.closed || self.failed || self.context.is_poisoned() { - return Err(Error::ContextPoisoned); - } - self.metadata_bytes()?; - self.lease - .validate_current() - .map_err(|_| Error::InvalidSize) - } - pub(crate) fn validate_context(&self, c: &Context<'_>) -> Result<()> { - self.live()?; - if !std::ptr::eq(c, self.context) { - return Err(Error::UnexpectedContext); - } - Ok(()) - } - pub(super) fn parts(&self, l: usize, e: usize) -> Result<[&[u8]; 3]> { - key(l, e)?; - let mut p = [&[][..]; 3]; - for (i, r) in [ - LayerRole::FfnGateExperts, - LayerRole::FfnUpExperts, - LayerRole::FfnDownExperts, - ] - .into_iter() - .enumerate() - { - let m = self - .lease - .member(l as u8, r) - .map_err(|_| Error::InvalidSize)?; - let first = m - .absolute_start() - .checked_add( - (e as u64) - .checked_mul(m.expert_bytes() as u64) - .ok_or(Error::InvalidSize)?, - ) - .ok_or(Error::InvalidSize)?; - p[i] = self - .map - .as_ref() - .ok_or(Error::ContextPoisoned)? - .part(first, m.expert_bytes())?; - } - Ok(p) - } - pub fn source_digest(&self) -> [u8; 32] { - self.lease.digest() - } - pub fn counters(&self) -> OriginalFileSourceCounters { - self.counts.get() - } - pub fn resident_bytes(&self) -> usize { - self.arena.as_ref().map_or(0, abi::Arena::bytes) - } - pub fn pinned_bytes(&self) -> usize { - self.arena.as_ref().map_or(0, abi::Arena::pin_limit) - } - pub fn locked_bytes(&self) -> usize { - self.arena.as_ref().map_or(0, abi::Arena::locked) - } - pub fn resident_lent_slots(&self) -> usize { - self.lent_slots - } - pub fn complement_ready(&self) -> bool { - self.ready - } - pub fn has_resident(&self, l: usize, e: usize) -> bool { - key(l, e) - .ok() - .and_then(|i| self.offsets.get(i)) - .is_some_and(|o| *o != NONE) - } - pub fn transient(&self, l: usize, e: usize) -> bool { - key(l, e).is_ok_and(|i| { - !self.has_resident(l, e) && self.overrides.get(i).copied().unwrap_or(NONE) == NONE - }) - } - pub fn pcie_layer(&self, l: usize) -> bool { - l < LAYERS && self.ready && self.pinned_bytes() > 0 - } - pub fn set_fetch_threads(&mut self, n: i32) { - self.fetch_threads = n.max(1) as usize; - } - pub fn begin_layer(&mut self, l: usize) -> Result<()> { - self.live()?; - if self.last_layer != Some(l) { - self.epoch = self.epoch.wrapping_add(1); - self.last_layer = Some(l); - } - Ok(()) - } - pub fn metadata_bytes(&self) -> Result { - // HashMap physical bucket bound (power-of-two group buckets, <=2x capacity), - // plus complete source directory and all actual Vec capacities. - let buckets = self - .stage_of - .capacity() - .checked_next_power_of_two() - .and_then(|n| n.checked_mul(2)) - .ok_or(Error::BudgetExceeded)?; - let n = self - .lease - .metadata_bytes() - .checked_add(size_of::()) - .and_then(|n| { - n.checked_add( - (self.offsets.capacity() + self.overrides.capacity()) * size_of::() - + self.warm_stamp.capacity() * size_of::() - + self.stage.capacity() * size_of::() - + self.staged.capacity() * size_of::(), - ) - }) - .and_then(|n| n.checked_add(buckets * (size_of::<(usize, usize)>() + 1) + 16)) - .ok_or(Error::BudgetExceeded)?; - if n > META_CAP { - return Err(Error::BudgetExceeded); - } - Ok(n) - } - pub fn charged_source_bytes(&self) -> Result { - self.charged_bytes() - } - pub(super) fn charged_bytes(&self) -> Result { - self.resident_bytes() - .checked_add(self.exchange.as_ref().map_or(0, abi::Arena::bytes)) - .and_then(|n| n.checked_add(self.stage.len().checked_mul(self.maximum)?)) - .and_then(|n| n.checked_add(self.metadata_bytes().ok()?)) - .ok_or(Error::BudgetExceeded) - } - pub(super) fn admit_extra(&self, n: usize) -> Result<()> { - if self - .charged_bytes()? - .checked_add(n) - .is_none_or(|n| n > SOURCE_CAP) - || available_memory()? < n.checked_add(8 * GIB).ok_or(Error::BudgetExceeded)? - { - return Err(Error::BudgetExceeded); - } - Ok(()) - } - /// Genuine original primary cache membership, complete fill and Context fence, - /// not caller-provided booleans. Additional/rank lists retain Original validation. - pub fn build_cache_complement( - &mut self, - cache: &OriginalExpertCache<'ctx>, - options: OriginalResidentOptions, - additional: &[(i32, i32)], - rank: Option<&[(i32, i32)]>, - ) -> Result<()> { - self.live()?; - if self.ready { - return Err(Error::InvalidSize); - } - cache.validate_file_source_context(self.context)?; - if cache.fills() != cache.resident() as u64 { - return Err(Error::InvalidSize); - } - self.context.synchronize().inspect_err(|_| { - self.failed = true; - self.context.poison(); - self.context.retain_driver(); - })?; - let mut primary = Vec::new(); - let mut slot_bytes = vec_filled(cache.slots(), 0usize)?; - for l in 0..LAYERS { - for e in 0..EXPERTS { - let s = cache.slot_of(l, e); - if s >= 0 { - let s = s as usize; - if s >= cache.slots() { - return Err(Error::InvalidSize); - } - primary.try_reserve(1).map_err(|_| Error::HostAllocation)?; - primary.push((l as i32, e as i32, s)); - slot_bytes[s] = self.layer_bytes[l]; - } - } - } - let (mut offsets, mut bytes) = self.plan(&primary, additional)?; - let mut lend = options - .lend_from_slot - .filter(|s| *s < cache.slots() && additional.is_empty()); - let physical = available_memory()?; - let room = physical.saturating_sub(options.headroom_bytes); - let mut budget = options.budget_bytes; - if budget > 0 { - if budget > (room as u64) { - budget = room.saturating_sub(256 << 20) as u64; - } - let mut ranked = vec_filled(N, NONE)?; - let mut at = 0usize; - let mut held = 0; - if let Some(rank) = rank { - for &(l, e) in rank { - if l < 0 || e < 0 { - continue; - } - let Ok(i) = key(l as usize, e as usize) else { - continue; - }; - if offsets[i] == NONE || ranked[i] != NONE { - continue; - } - let b = self.layer_bytes[l as usize]; - if (b as u64) > budget.saturating_sub(at as u64) { - continue; - } - ranked[i] = at; - at = at.checked_add(b).ok_or(Error::InvalidSize)?; - held += 1; - } - } - if options.budget_bytes == u64::MAX && held == 0 { - return Err(Error::BudgetExceeded); - } - offsets = ranked; - bytes = at; - lend = None; - } - if bytes > room { - return Err(Error::BudgetExceeded); - } - let mut keep_from = cache.slots(); - if let Some(first) = lend { - let mut b = bytes; - while keep_from > first { - let n = slot_bytes[keep_from - 1]; - if n > room - b { - break; - } - b += n; - keep_from -= 1; - } - if keep_from < cache.slots() { - let mut core = Vec::new(); - core.try_reserve_exact(primary.len()) - .map_err(|_| Error::HostAllocation)?; - core.extend(primary.iter().copied().filter(|p| p.2 < keep_from)); - (offsets, bytes) = self.plan(&core, additional)?; - } - } - let stack = abi::worker_stack_bytes()?; - let prospective_meta = self - .metadata_bytes()? - .checked_add( - offsets.capacity() * size_of::() - + 2 * primary.capacity() * size_of::<(i32, i32, usize)>() - + slot_bytes.capacity() * size_of::() - + N * (size_of::() + size_of::() + size_of::()) - + LAYERS * size_of::>() - + 5 * size_of::>(), - ) - .ok_or(Error::BudgetExceeded)?; - if prospective_meta > META_CAP - || bytes - .checked_add(prospective_meta) - .is_none_or(|n| n > SOURCE_CAP) - || bytes - .checked_add(5 * stack) - .and_then(|n| n.checked_add(prospective_meta)) - .and_then(|n| n.checked_add(options.headroom_bytes)) - .is_none_or(|n| n > physical) - { - return Err(Error::BudgetExceeded); - } - let guard = self.context.enter().inspect_err(|_| { - self.failed = true; - self.context.poison(); - self.context.retain_driver(); - })?; - let api = self.api.as_ref().ok_or(Error::ContextPoisoned)?; - let mut arena = match api.allocate(bytes, options.pin) { - Ok(a) => a, - Err(primary) => { - let pop = guard.finish(); - if matches!(primary, Error::Driver { .. }) || pop.is_err() { - self.failed = true; - self.context.poison(); - self.context.retain_driver(); - } - return combine(Err(primary), pop); - } - }; - let prepare = (|| { - if options.pin && arena.pin_limit() == 0 { - if budget > 0 && options.partial_pin { - let step = 2 * GIB; - let mut want = bytes.min(options.partial_pin_cap); - while want >= step { - let mut cut = want; - for (i, &off) in offsets.iter().enumerate() { - if off != NONE - && off < want - && off - .checked_add(self.layer_bytes[i / EXPERTS]) - .is_some_and(|end| end > want) - { - cut = off; - break; - } - } - if cut == 0 { - break; - } - if api.register_prefix(&mut arena, cut)? { - break; - } - want = if want > step { want - step } else { 0 }; - } - } - arena.lock_remainder(); - } - // Closed raw records derived only from retained mapped source and actual arena. - // Six Original layer workers; one actor participates. No Context/Rc is sent. - let mut per_layer = Vec::new(); - per_layer - .try_reserve_exact(LAYERS) - .map_err(|_| Error::HostAllocation)?; - for l in 0..LAYERS { - let mut jobs = Vec::new(); - jobs.try_reserve_exact(EXPERTS) - .map_err(|_| Error::HostAllocation)?; - for e in 0..EXPERTS { - let off = offsets[l * EXPERTS + e]; - if off != NONE { - jobs.push(arena.write(off, self.parts(l, e)?)?); - } - } - per_layer.push(jobs); - } - let next = AtomicUsize::new(0); - let first = Mutex::new(None); - let work = || loop { - let l = next.fetch_add(1, Ordering::Relaxed); - if l >= LAYERS { - break; - } - if first.lock().is_ok_and(|e| e.is_some()) { - break; - } - for j in &per_layer[l] { - if let Err(e) = j.run() { - if let Ok(mut f) = first.lock() { - if f.is_none() { - *f = Some(e); - } - } - break; - } - } - }; - thread::scope(|s| { - let mut workers = Vec::new(); - workers - .try_reserve_exact(5) - .map_err(|_| Error::HostAllocation)?; - for _ in 0..5 { - workers.push( - thread::Builder::new() - .stack_size(stack) - .spawn_scoped(s, work) - .map_err(|_| Error::HostAllocation)?, - ); - } - work(); - for w in workers { - if w.join().is_err() { - return Err(Error::HostAllocation); - } - } - Ok(()) - })?; - if let Some(e) = first.into_inner().map_err(|_| Error::HostAllocation)? { - return Err(e); - } - self.lease - .validate_current() - .map_err(|_| Error::InvalidSize)?; - Ok(()) - })(); - let pop = guard.finish(); - if pop.is_err() { - self.failed = true; - self.context.poison(); - self.context.retain_driver(); - std::mem::forget(arena); - return combine(prepare, pop); - } - if let Err(primary) = prepare { - let g = match self.context.enter() { - Ok(g) => g, - Err(e) => { - self.failed = true; - self.context.poison(); - self.context.retain_driver(); - std::mem::forget(arena); - return combine::<()>(Err(primary), Err(e)); - } - }; - let cleanup = combine(api.close(&mut arena), g.finish()); - if cleanup.is_err() { - self.failed = true; - self.context.poison(); - self.context.retain_driver(); - std::mem::forget(arena); - } - return combine(Err(primary), cleanup); - } - self.arena = Some(arena); - self.offsets = offsets; - self.ready = true; - self.lent_slots = if lend.is_some() { - cache.slots() - keep_from - } else { - 0 - }; - Ok(()) - } - pub(super) fn plan( - &self, - primary: &[(i32, i32, usize)], - additional: &[(i32, i32)], - ) -> Result<(Vec, usize)> { - let mut omit = vec_filled(N, 0u8)?; - for &(l, e, _) in primary { - let i = key(l as usize, e as usize)?; - if omit[i] & 1 != 0 { - return Err(Error::InvalidSize); - } - omit[i] |= 1; - } - for &(l, e) in additional { - if l < 0 || e < 0 { - return Err(Error::InvalidSize); - } - let i = key(l as usize, e as usize)?; - if omit[i] != 0 { - return Err(Error::InvalidSize); - } - omit[i] |= 2; - } - let mut offsets = vec_filled(N, NONE)?; - let mut bytes = 0usize; - for l in 0..LAYERS { - if self.layer_bytes[l] == 0 { - return Err(Error::InvalidSize); - } - for e in 0..EXPERTS { - let i = l * EXPERTS + e; - if omit[i] == 0 { - offsets[i] = bytes; - bytes = bytes - .checked_add(self.layer_bytes[l]) - .ok_or(Error::InvalidSize)?; - } - } - } - Ok((offsets, bytes)) - } - pub(super) fn claim_stage(&mut self, k: usize) -> Result<(usize, bool)> { - self.seq = self.seq.wrapping_add(1); - let seq = self.seq; - if let Some(&v) = self.stage_of.get(&k) { - let s = &mut self.stage[v]; - s.epoch = self.epoch; - s.used = seq; - return Ok((v, false)); - } - let victim = self - .stage - .iter() - .enumerate() - .filter(|(_, s)| { - !s.busy - && (s.epoch.wrapping_add(3) <= self.epoch || s.used.wrapping_add(256) <= seq) - }) - .min_by_key(|(_, s)| s.used) - .map(|(i, _)| i); - self.stage_of - .try_reserve(1) - .map_err(|_| Error::HostAllocation)?; - let v = if let Some(v) = victim { - self.stage_of.remove(&self.stage[v].key); - v - } else { - self.admit_extra(self.maximum + size_of::())?; - self.stage - .try_reserve(1) - .map_err(|_| Error::HostAllocation)?; - let mut data = Vec::new(); - data.try_reserve_exact(self.maximum) - .map_err(|_| Error::HostAllocation)?; - data.resize(self.maximum, 0); - let v = self.stage.len(); - self.stage.push(Stage { - data: data.into_boxed_slice(), - key: NONE, - epoch: 0, - used: 0, - busy: false, - }); - v - }; - self.metadata_bytes()?; - let s = &mut self.stage[v]; - s.key = k; - s.epoch = self.epoch; - s.used = seq; - s.busy = true; - self.stage_of.insert(k, v); - Ok((v, true)) - } - pub(super) fn fill_stage(&mut self, v: usize, k: usize) -> Result<()> { - let t = Instant::now(); - let operation = (|| { - let parts = self.parts(k / EXPERTS, k % EXPERTS)?; - // Source slices and destination are disjoint fields; capture private records - // before the mutable stage borrow to avoid re-borrowing the artifact owner. - let owned = parts.map(|p| (p.as_ptr() as usize, p.len())); - let stage = &mut self.stage[v]; - abi::copy_parts_to(owned, &mut stage.data)?; - self.lease - .validate_current() - .map_err(|_| Error::InvalidSize) - })(); - let mut c = self.counts.get(); - c.file_us = c.file_us.wrapping_add(t.elapsed().as_micros() as u64); - if operation.is_ok() { - c.file_read_bytes = c - .file_read_bytes - .wrapping_add(self.layer_bytes[k / EXPERTS] as u64); - c.file_blob_bytes = c - .file_blob_bytes - .wrapping_add(self.layer_bytes[k / EXPERTS] as u64); - } - self.counts.set(c); - self.stage[v].busy = false; - if operation.is_err() { - self.stage_of.remove(&k); - self.stage[v].key = NONE; - } - operation - } - pub fn prepare_blob(&mut self, l: usize, e: usize) -> Result<()> { - self.live()?; - let k = key(l, e)?; - if self.has_resident(l, e) || self.overrides.get(k).copied().unwrap_or(NONE) != NONE { - return Ok(()); - } - let (v, fill) = self.claim_stage(k)?; - if fill { - self.fill_stage(v, k)?; - } else if self.stage[v].busy { - return Err(Error::InvalidSize); - } - Ok(()) - } - pub fn blob(&self, l: usize, e: usize) -> Result> { - self.live()?; - let k = key(l, e)?; - let off = self.offsets.get(k).copied().unwrap_or(NONE); - let n = self.layer_bytes[l]; - let (bytes, alias) = if off != NONE { - let a = self.arena.as_ref().ok_or(Error::InvalidSize)?; - (a.part(off, n)?, a.alias(off, n)?) - } else if let Some(q) = self.overrides.get(k).copied().filter(|q| *q != NONE) { - ( - self.exchange - .as_ref() - .ok_or(Error::InvalidSize)? - .part(q * self.maximum, n)?, - None, - ) - } else { - let v = *self.stage_of.get(&k).ok_or(Error::InvalidSize)?; - let s = &self.stage[v]; - if s.busy || s.key != k { - return Err(Error::InvalidSize); - } - (&s.data[..n], None) - }; - let mut c = self.counts.get(); - if off != NONE { - c.ram_reads = c.ram_reads.wrapping_add(1); - } else if self.ready && self.overrides.get(k).copied().unwrap_or(NONE) == NONE { - c.file_reads = c.file_reads.wrapping_add(1); - } - c.reads = c.reads.wrapping_add(1); - self.counts.set(c); - Ok(OriginalFileSourceBlob { - source: self, - layer: l, - expert: e, - bytes, - alias, - }) - } - pub fn copy_blob(&self, l: usize, e: usize, out: &mut [u8]) -> Result<()> { - self.live()?; - let k = key(l, e)?; - let n = self.layer_bytes[l]; - if out.len() != n { - return Err(Error::InvalidSize); - } - let off = self.offsets.get(k).copied().unwrap_or(NONE); - if off != NONE { - out.copy_from_slice( - self.arena - .as_ref() - .ok_or(Error::InvalidSize)? - .part(off, n)?, - ); - return Ok(()); - } - if let Some(q) = self.overrides.get(k).copied().filter(|q| *q != NONE) { - out.copy_from_slice( - self.exchange - .as_ref() - .ok_or(Error::InvalidSize)? - .part(q * self.maximum, n)?, - ); - return Ok(()); - } - let t = Instant::now(); - let result = abi::Copy::into_slice(self.parts(l, e)?, out)?.run(); - let mut c = self.counts.get(); - c.file_us = c.file_us.wrapping_add(t.elapsed().as_micros() as u64); - if result.is_ok() { - c.file_read_bytes = c.file_read_bytes.wrapping_add(n as u64); - } - self.counts.set(c); - result?; - self.lease - .validate_current() - .map_err(|_| Error::InvalidSize) - } - pub fn warm(&mut self, l: usize, experts: &[i64]) -> Result<()> { - self.live()?; - if l >= LAYERS { - return Ok(()); - } - for &e in experts { - if e < 0 || e >= EXPERTS as i64 || self.has_resident(l, e as usize) { - continue; - } - let k = l * EXPERTS + e as usize; - self.warm_stamp[k] = (self.epoch.wrapping_add(1)) as u32; - let mut c = self.counts.get(); - c.warmed = c.warmed.wrapping_add(1); - self.counts.set(c); - abi::warm(self.parts(l, e as usize)?); - } - Ok(()) - } - pub fn prefetch(&mut self, l: usize, experts: &[i64]) -> Result<()> { - let result = self.prefetch_impl(l, experts); - if result.is_err() { - for s in &mut self.stage { - if s.busy { - self.stage_of.remove(&s.key); - s.key = NONE; - s.busy = false; - } - } - } - result - } - pub(super) fn prefetch_impl(&mut self, l: usize, experts: &[i64]) -> Result<()> { - self.live()?; - if l >= LAYERS || experts.is_empty() { - return Ok(()); - } - let mut todo = Vec::new(); - todo.try_reserve_exact(experts.len().min(N)) - .map_err(|_| Error::HostAllocation)?; - for &e in experts { - if e < 0 || e >= EXPERTS as i64 { - continue; - } - let k = l * EXPERTS + e as usize; - if self.has_resident(l, e as usize) - || self.overrides.get(k).copied().unwrap_or(NONE) != NONE - { - continue; - } - let (v, fill) = self.claim_stage(k)?; - if fill { - todo.push((v, k)); - let stamp = self.warm_stamp[k]; - if stamp != 0 && (stamp as u64).wrapping_add(3) >= self.epoch.wrapping_add(1) { - let mut c = self.counts.get(); - c.warm_hits = c.warm_hits.wrapping_add(1); - self.counts.set(c); - } - } - } - if todo.is_empty() { - return Ok(()); - } - let mut jobs = Vec::new(); - jobs.try_reserve_exact(todo.len()) - .map_err(|_| Error::HostAllocation)?; - for &(v, k) in &todo { - let raw = self - .parts(l, k % EXPERTS)? - .map(|p| (p.as_ptr() as usize, p.len())); - jobs.push(abi::copy_parts_record(raw, &mut self.stage[v].data)?); - } - let next = AtomicUsize::new(0); - let mut result: Vec, u64)>>> = Vec::new(); - result - .try_reserve_exact(todo.len()) - .map_err(|_| Error::HostAllocation)?; - result.resize_with(todo.len(), || Mutex::new(None)); - let work = || loop { - let i = next.fetch_add(1, Ordering::Relaxed); - if i >= jobs.len() { - break; - } - let t = Instant::now(); - let r = jobs[i].run(); - if let Ok(mut out) = result[i].lock() { - *out = Some((r, t.elapsed().as_micros() as u64)); - } - }; - let nt = jobs.len().min(self.fetch_threads); - let stack = abi::worker_stack_bytes()?; - self.admit_extra( - nt.saturating_sub(1) - .checked_mul(stack) - .ok_or(Error::BudgetExceeded)?, - )?; - let spawned = thread::scope(|s| { - let mut workers = Vec::new(); - workers - .try_reserve_exact(nt.saturating_sub(1)) - .map_err(|_| Error::HostAllocation)?; - for _ in 1..nt { - workers.push( - thread::Builder::new() - .stack_size(stack) - .spawn_scoped(s, work) - .map_err(|_| Error::HostAllocation)?, - ); - } - work(); - for w in workers { - if w.join().is_err() { - return Err(Error::HostAllocation); - } - } - Ok(()) - }); - let source = self - .lease - .validate_current() - .map_err(|_| Error::InvalidSize); - let mut first = None; - for (i, &(v, k)) in todo.iter().enumerate() { - let completed = result[i].lock().ok().and_then(|mut r| r.take()); - let ok = completed.as_ref().is_some_and(|(r, _)| r.is_ok()) && source.is_ok(); - let mut c = self.counts.get(); - if let Some((r, us)) = completed { - c.file_us = c.file_us.wrapping_add(us); - if r.is_ok() && source.is_ok() { - c.file_read_bytes = c.file_read_bytes.wrapping_add(self.layer_bytes[l] as u64); - c.file_blob_bytes = c.file_blob_bytes.wrapping_add(self.layer_bytes[l] as u64); - } else if first.is_none() { - first = r.err().or(Some(Error::InvalidSize)); - } - } else if first.is_none() { - first = Some(Error::HostAllocation); - } - self.counts.set(c); - self.stage[v].busy = false; - if !ok { - self.stage_of.remove(&k); - self.stage[v].key = NONE; - } - } - combine(combine(spawned, source), first.map_or(Ok(()), Err)) - } - pub fn close(mut self) -> Result<()> { - self.close_inner() - } - pub(super) fn close_inner(&mut self) -> Result<()> { - if self.closed { - return Ok(()); - } - self.closed = true; - if self.context.is_poisoned() { - self.retain(); - return Err(Error::ContextPoisoned); - } - let guard = match self.context.enter() { - Ok(g) => g, - Err(e) => { - self.context.poison(); - self.context.retain_driver(); - self.retain(); - return Err(e); - } - }; - let operation = (|| { - self.context.synchronize()?; - let api = self.api.as_ref().ok_or(Error::ContextPoisoned)?; - let x = self.exchange.as_mut().map_or(Ok(()), |a| api.close(a)); - let a = self.arena.as_mut().map_or(Ok(()), |a| api.close(a)); - combine(x, a) - })(); - let result = combine(operation, guard.finish()); - if result.is_err() { - self.context.poison(); - self.context.retain_driver(); - self.retain(); - } - result - } - pub(super) fn retain(&mut self) { - if let Some(a) = self.arena.take() { - std::mem::forget(a); - } - if let Some(a) = self.exchange.take() { - std::mem::forget(a); - } - if let Some(a) = self.api.take() { - std::mem::forget(a); - } - if let Some(m) = self.map.take() { - std::mem::forget(m); - } - std::mem::forget(self.lease.clone()); - let stage = std::mem::take(&mut self.stage); - std::mem::forget(stage); /* actual uncertain source storage is retained, not just its address */ - } -} +mod impl_originalfileexpertsource_2; +mod impl_originalfileexpertsource_2_2; +mod impl_originalfileexpertsource_3; +mod impl_originalfileexpertsource_4; diff --git a/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_2.rs b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_2.rs new file mode 100644 index 00000000..f237e845 --- /dev/null +++ b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_2.rs @@ -0,0 +1,150 @@ +//! Moved out of the parent module by STRA-338: impl OriginalFileExpertSource. + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalFileExpertSource<'ctx> { + pub(in super::super) fn live(&self) -> Result<()> { + if self.closed || self.failed || self.context.is_poisoned() { + return Err(Error::ContextPoisoned); + } + self.metadata_bytes()?; + self.lease + .validate_current() + .map_err(|_| Error::InvalidSize) + } + pub(crate) fn validate_context(&self, c: &Context<'_>) -> Result<()> { + self.live()?; + if !std::ptr::eq(c, self.context) { + return Err(Error::UnexpectedContext); + } + Ok(()) + } + pub(in super::super) fn parts(&self, l: usize, e: usize) -> Result<[&[u8]; 3]> { + key(l, e)?; + let mut p = [&[][..]; 3]; + for (i, r) in [ + LayerRole::FfnGateExperts, + LayerRole::FfnUpExperts, + LayerRole::FfnDownExperts, + ] + .into_iter() + .enumerate() + { + let m = self + .lease + .member(l as u8, r) + .map_err(|_| Error::InvalidSize)?; + let first = m + .absolute_start() + .checked_add( + (e as u64) + .checked_mul(m.expert_bytes() as u64) + .ok_or(Error::InvalidSize)?, + ) + .ok_or(Error::InvalidSize)?; + p[i] = self + .map + .as_ref() + .ok_or(Error::ContextPoisoned)? + .part(first, m.expert_bytes())?; + } + Ok(p) + } + pub fn source_digest(&self) -> [u8; 32] { + self.lease.digest() + } + pub fn counters(&self) -> OriginalFileSourceCounters { + self.counts.get() + } + pub fn resident_bytes(&self) -> usize { + self.arena.as_ref().map_or(0, abi::Arena::bytes) + } + pub fn pinned_bytes(&self) -> usize { + self.arena.as_ref().map_or(0, abi::Arena::pin_limit) + } + pub fn locked_bytes(&self) -> usize { + self.arena.as_ref().map_or(0, abi::Arena::locked) + } + pub fn resident_lent_slots(&self) -> usize { + self.lent_slots + } + pub fn complement_ready(&self) -> bool { + self.ready + } + pub fn has_resident(&self, l: usize, e: usize) -> bool { + key(l, e) + .ok() + .and_then(|i| self.offsets.get(i)) + .is_some_and(|o| *o != NONE) + } + pub fn transient(&self, l: usize, e: usize) -> bool { + key(l, e).is_ok_and(|i| { + !self.has_resident(l, e) && self.overrides.get(i).copied().unwrap_or(NONE) == NONE + }) + } + pub fn pcie_layer(&self, l: usize) -> bool { + l < LAYERS && self.ready && self.pinned_bytes() > 0 + } + pub fn set_fetch_threads(&mut self, n: i32) { + self.fetch_threads = n.max(1) as usize; + } + pub fn begin_layer(&mut self, l: usize) -> Result<()> { + self.live()?; + if self.last_layer != Some(l) { + self.epoch = self.epoch.wrapping_add(1); + self.last_layer = Some(l); + } + Ok(()) + } + pub fn metadata_bytes(&self) -> Result { + // HashMap physical bucket bound (power-of-two group buckets, <=2x capacity), + // plus complete source directory and all actual Vec capacities. + let buckets = self + .stage_of + .capacity() + .checked_next_power_of_two() + .and_then(|n| n.checked_mul(2)) + .ok_or(Error::BudgetExceeded)?; + let n = self + .lease + .metadata_bytes() + .checked_add(size_of::()) + .and_then(|n| { + n.checked_add( + (self.offsets.capacity() + self.overrides.capacity()) * size_of::() + + self.warm_stamp.capacity() * size_of::() + + self.stage.capacity() * size_of::() + + self.staged.capacity() * size_of::(), + ) + }) + .and_then(|n| n.checked_add(buckets * (size_of::<(usize, usize)>() + 1) + 16)) + .ok_or(Error::BudgetExceeded)?; + if n > META_CAP { + return Err(Error::BudgetExceeded); + } + Ok(n) + } + pub fn charged_source_bytes(&self) -> Result { + self.charged_bytes() + } + pub(in super::super) fn charged_bytes(&self) -> Result { + self.resident_bytes() + .checked_add(self.exchange.as_ref().map_or(0, abi::Arena::bytes)) + .and_then(|n| n.checked_add(self.stage.len().checked_mul(self.maximum)?)) + .and_then(|n| n.checked_add(self.metadata_bytes().ok()?)) + .ok_or(Error::BudgetExceeded) + } + pub(in super::super) fn admit_extra(&self, n: usize) -> Result<()> { + if self + .charged_bytes()? + .checked_add(n) + .is_none_or(|n| n > SOURCE_CAP) + || available_memory()? < n.checked_add(8 * GIB).ok_or(Error::BudgetExceeded)? + { + return Err(Error::BudgetExceeded); + } + Ok(()) + } +} diff --git a/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_2_2.rs b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_2_2.rs new file mode 100644 index 00000000..f703a50e --- /dev/null +++ b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_2_2.rs @@ -0,0 +1,286 @@ +//! Moved out of the parent module by STRA-338: impl OriginalFileExpertSource (2). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalFileExpertSource<'ctx> { + /// Genuine original primary cache membership, complete fill and Context fence, + /// not caller-provided booleans. Additional/rank lists retain Original validation. + pub fn build_cache_complement( + &mut self, + cache: &OriginalExpertCache<'ctx>, + options: OriginalResidentOptions, + additional: &[(i32, i32)], + rank: Option<&[(i32, i32)]>, + ) -> Result<()> { + self.live()?; + if self.ready { + return Err(Error::InvalidSize); + } + cache.validate_file_source_context(self.context)?; + if cache.fills() != cache.resident() as u64 { + return Err(Error::InvalidSize); + } + self.context.synchronize().inspect_err(|_| { + self.failed = true; + self.context.poison(); + self.context.retain_driver(); + })?; + let mut primary = Vec::new(); + let mut slot_bytes = vec_filled(cache.slots(), 0usize)?; + for l in 0..LAYERS { + for e in 0..EXPERTS { + let s = cache.slot_of(l, e); + if s >= 0 { + let s = s as usize; + if s >= cache.slots() { + return Err(Error::InvalidSize); + } + primary.try_reserve(1).map_err(|_| Error::HostAllocation)?; + primary.push((l as i32, e as i32, s)); + slot_bytes[s] = self.layer_bytes[l]; + } + } + } + let (mut offsets, mut bytes) = self.plan(&primary, additional)?; + let mut lend = options + .lend_from_slot + .filter(|s| *s < cache.slots() && additional.is_empty()); + let physical = available_memory()?; + let room = physical.saturating_sub(options.headroom_bytes); + let mut budget = options.budget_bytes; + if budget > 0 { + if budget > (room as u64) { + budget = room.saturating_sub(256 << 20) as u64; + } + let mut ranked = vec_filled(N, NONE)?; + let mut at = 0usize; + let mut held = 0; + if let Some(rank) = rank { + for &(l, e) in rank { + if l < 0 || e < 0 { + continue; + } + let Ok(i) = key(l as usize, e as usize) else { + continue; + }; + if offsets[i] == NONE || ranked[i] != NONE { + continue; + } + let b = self.layer_bytes[l as usize]; + if (b as u64) > budget.saturating_sub(at as u64) { + continue; + } + ranked[i] = at; + at = at.checked_add(b).ok_or(Error::InvalidSize)?; + held += 1; + } + } + if options.budget_bytes == u64::MAX && held == 0 { + return Err(Error::BudgetExceeded); + } + offsets = ranked; + bytes = at; + lend = None; + } + if bytes > room { + return Err(Error::BudgetExceeded); + } + let mut keep_from = cache.slots(); + if let Some(first) = lend { + let mut b = bytes; + while keep_from > first { + let n = slot_bytes[keep_from - 1]; + if n > room - b { + break; + } + b += n; + keep_from -= 1; + } + if keep_from < cache.slots() { + let mut core = Vec::new(); + core.try_reserve_exact(primary.len()) + .map_err(|_| Error::HostAllocation)?; + core.extend(primary.iter().copied().filter(|p| p.2 < keep_from)); + (offsets, bytes) = self.plan(&core, additional)?; + } + } + let stack = abi::worker_stack_bytes()?; + let prospective_meta = self + .metadata_bytes()? + .checked_add( + offsets.capacity() * size_of::() + + 2 * primary.capacity() * size_of::<(i32, i32, usize)>() + + slot_bytes.capacity() * size_of::() + + N * (size_of::() + size_of::() + size_of::()) + + LAYERS * size_of::>() + + 5 * size_of::>(), + ) + .ok_or(Error::BudgetExceeded)?; + if prospective_meta > META_CAP + || bytes + .checked_add(prospective_meta) + .is_none_or(|n| n > SOURCE_CAP) + || bytes + .checked_add(5 * stack) + .and_then(|n| n.checked_add(prospective_meta)) + .and_then(|n| n.checked_add(options.headroom_bytes)) + .is_none_or(|n| n > physical) + { + return Err(Error::BudgetExceeded); + } + let guard = self.context.enter().inspect_err(|_| { + self.failed = true; + self.context.poison(); + self.context.retain_driver(); + })?; + let api = self.api.as_ref().ok_or(Error::ContextPoisoned)?; + let mut arena = match api.allocate(bytes, options.pin) { + Ok(a) => a, + Err(primary) => { + let pop = guard.finish(); + if matches!(primary, Error::Driver { .. }) || pop.is_err() { + self.failed = true; + self.context.poison(); + self.context.retain_driver(); + } + return combine(Err(primary), pop); + } + }; + let prepare = (|| { + if options.pin && arena.pin_limit() == 0 { + if budget > 0 && options.partial_pin { + let step = 2 * GIB; + let mut want = bytes.min(options.partial_pin_cap); + while want >= step { + let mut cut = want; + for (i, &off) in offsets.iter().enumerate() { + if off != NONE + && off < want + && off + .checked_add(self.layer_bytes[i / EXPERTS]) + .is_some_and(|end| end > want) + { + cut = off; + break; + } + } + if cut == 0 { + break; + } + if api.register_prefix(&mut arena, cut)? { + break; + } + want = if want > step { want - step } else { 0 }; + } + } + arena.lock_remainder(); + } + // Closed raw records derived only from retained mapped source and actual arena. + // Six Original layer workers; one actor participates. No Context/Rc is sent. + let mut per_layer = Vec::new(); + per_layer + .try_reserve_exact(LAYERS) + .map_err(|_| Error::HostAllocation)?; + for l in 0..LAYERS { + let mut jobs = Vec::new(); + jobs.try_reserve_exact(EXPERTS) + .map_err(|_| Error::HostAllocation)?; + for e in 0..EXPERTS { + let off = offsets[l * EXPERTS + e]; + if off != NONE { + jobs.push(arena.write(off, self.parts(l, e)?)?); + } + } + per_layer.push(jobs); + } + let next = AtomicUsize::new(0); + let first = Mutex::new(None); + let work = || loop { + let l = next.fetch_add(1, Ordering::Relaxed); + if l >= LAYERS { + break; + } + if first.lock().is_ok_and(|e| e.is_some()) { + break; + } + for j in &per_layer[l] { + if let Err(e) = j.run() { + if let Ok(mut f) = first.lock() { + if f.is_none() { + *f = Some(e); + } + } + break; + } + } + }; + thread::scope(|s| { + let mut workers = Vec::new(); + workers + .try_reserve_exact(5) + .map_err(|_| Error::HostAllocation)?; + for _ in 0..5 { + workers.push( + thread::Builder::new() + .stack_size(stack) + .spawn_scoped(s, work) + .map_err(|_| Error::HostAllocation)?, + ); + } + work(); + for w in workers { + if w.join().is_err() { + return Err(Error::HostAllocation); + } + } + Ok(()) + })?; + if let Some(e) = first.into_inner().map_err(|_| Error::HostAllocation)? { + return Err(e); + } + self.lease + .validate_current() + .map_err(|_| Error::InvalidSize)?; + Ok(()) + })(); + let pop = guard.finish(); + if pop.is_err() { + self.failed = true; + self.context.poison(); + self.context.retain_driver(); + std::mem::forget(arena); + return combine(prepare, pop); + } + if let Err(primary) = prepare { + let g = match self.context.enter() { + Ok(g) => g, + Err(e) => { + self.failed = true; + self.context.poison(); + self.context.retain_driver(); + std::mem::forget(arena); + return combine::<()>(Err(primary), Err(e)); + } + }; + let cleanup = combine(api.close(&mut arena), g.finish()); + if cleanup.is_err() { + self.failed = true; + self.context.poison(); + self.context.retain_driver(); + std::mem::forget(arena); + } + return combine(Err(primary), cleanup); + } + self.arena = Some(arena); + self.offsets = offsets; + self.ready = true; + self.lent_slots = if lend.is_some() { + cache.slots() - keep_from + } else { + 0 + }; + Ok(()) + } +} diff --git a/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_3.rs b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_3.rs new file mode 100644 index 00000000..771b31d9 --- /dev/null +++ b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_3.rs @@ -0,0 +1,257 @@ +//! Moved out of the parent module by STRA-338: impl OriginalFileExpertSource (3). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalFileExpertSource<'ctx> { + pub(in super::super) fn plan( + &self, + primary: &[(i32, i32, usize)], + additional: &[(i32, i32)], + ) -> Result<(Vec, usize)> { + let mut omit = vec_filled(N, 0u8)?; + for &(l, e, _) in primary { + let i = key(l as usize, e as usize)?; + if omit[i] & 1 != 0 { + return Err(Error::InvalidSize); + } + omit[i] |= 1; + } + for &(l, e) in additional { + if l < 0 || e < 0 { + return Err(Error::InvalidSize); + } + let i = key(l as usize, e as usize)?; + if omit[i] != 0 { + return Err(Error::InvalidSize); + } + omit[i] |= 2; + } + let mut offsets = vec_filled(N, NONE)?; + let mut bytes = 0usize; + for l in 0..LAYERS { + if self.layer_bytes[l] == 0 { + return Err(Error::InvalidSize); + } + for e in 0..EXPERTS { + let i = l * EXPERTS + e; + if omit[i] == 0 { + offsets[i] = bytes; + bytes = bytes + .checked_add(self.layer_bytes[l]) + .ok_or(Error::InvalidSize)?; + } + } + } + Ok((offsets, bytes)) + } + pub(in super::super) fn claim_stage(&mut self, k: usize) -> Result<(usize, bool)> { + self.seq = self.seq.wrapping_add(1); + let seq = self.seq; + if let Some(&v) = self.stage_of.get(&k) { + let s = &mut self.stage[v]; + s.epoch = self.epoch; + s.used = seq; + return Ok((v, false)); + } + let victim = self + .stage + .iter() + .enumerate() + .filter(|(_, s)| { + !s.busy + && (s.epoch.wrapping_add(3) <= self.epoch || s.used.wrapping_add(256) <= seq) + }) + .min_by_key(|(_, s)| s.used) + .map(|(i, _)| i); + self.stage_of + .try_reserve(1) + .map_err(|_| Error::HostAllocation)?; + let v = if let Some(v) = victim { + self.stage_of.remove(&self.stage[v].key); + v + } else { + self.admit_extra(self.maximum + size_of::())?; + self.stage + .try_reserve(1) + .map_err(|_| Error::HostAllocation)?; + let mut data = Vec::new(); + data.try_reserve_exact(self.maximum) + .map_err(|_| Error::HostAllocation)?; + data.resize(self.maximum, 0); + let v = self.stage.len(); + self.stage.push(Stage { + data: data.into_boxed_slice(), + key: NONE, + epoch: 0, + used: 0, + busy: false, + }); + v + }; + self.metadata_bytes()?; + let s = &mut self.stage[v]; + s.key = k; + s.epoch = self.epoch; + s.used = seq; + s.busy = true; + self.stage_of.insert(k, v); + Ok((v, true)) + } + pub(in super::super) fn fill_stage(&mut self, v: usize, k: usize) -> Result<()> { + let t = Instant::now(); + let operation = (|| { + let parts = self.parts(k / EXPERTS, k % EXPERTS)?; + // Source slices and destination are disjoint fields; capture private records + // before the mutable stage borrow to avoid re-borrowing the artifact owner. + let owned = parts.map(|p| (p.as_ptr() as usize, p.len())); + let stage = &mut self.stage[v]; + abi::copy_parts_to(owned, &mut stage.data)?; + self.lease + .validate_current() + .map_err(|_| Error::InvalidSize) + })(); + let mut c = self.counts.get(); + c.file_us = c.file_us.wrapping_add(t.elapsed().as_micros() as u64); + if operation.is_ok() { + c.file_read_bytes = c + .file_read_bytes + .wrapping_add(self.layer_bytes[k / EXPERTS] as u64); + c.file_blob_bytes = c + .file_blob_bytes + .wrapping_add(self.layer_bytes[k / EXPERTS] as u64); + } + self.counts.set(c); + self.stage[v].busy = false; + if operation.is_err() { + self.stage_of.remove(&k); + self.stage[v].key = NONE; + } + operation + } + pub fn prepare_blob(&mut self, l: usize, e: usize) -> Result<()> { + self.live()?; + let k = key(l, e)?; + if self.has_resident(l, e) || self.overrides.get(k).copied().unwrap_or(NONE) != NONE { + return Ok(()); + } + let (v, fill) = self.claim_stage(k)?; + if fill { + self.fill_stage(v, k)?; + } else if self.stage[v].busy { + return Err(Error::InvalidSize); + } + Ok(()) + } + pub fn blob(&self, l: usize, e: usize) -> Result> { + self.live()?; + let k = key(l, e)?; + let off = self.offsets.get(k).copied().unwrap_or(NONE); + let n = self.layer_bytes[l]; + let (bytes, alias) = if off != NONE { + let a = self.arena.as_ref().ok_or(Error::InvalidSize)?; + (a.part(off, n)?, a.alias(off, n)?) + } else if let Some(q) = self.overrides.get(k).copied().filter(|q| *q != NONE) { + ( + self.exchange + .as_ref() + .ok_or(Error::InvalidSize)? + .part(q * self.maximum, n)?, + None, + ) + } else { + let v = *self.stage_of.get(&k).ok_or(Error::InvalidSize)?; + let s = &self.stage[v]; + if s.busy || s.key != k { + return Err(Error::InvalidSize); + } + (&s.data[..n], None) + }; + let mut c = self.counts.get(); + if off != NONE { + c.ram_reads = c.ram_reads.wrapping_add(1); + } else if self.ready && self.overrides.get(k).copied().unwrap_or(NONE) == NONE { + c.file_reads = c.file_reads.wrapping_add(1); + } + c.reads = c.reads.wrapping_add(1); + self.counts.set(c); + Ok(OriginalFileSourceBlob { + source: self, + layer: l, + expert: e, + bytes, + alias, + }) + } + pub fn copy_blob(&self, l: usize, e: usize, out: &mut [u8]) -> Result<()> { + self.live()?; + let k = key(l, e)?; + let n = self.layer_bytes[l]; + if out.len() != n { + return Err(Error::InvalidSize); + } + let off = self.offsets.get(k).copied().unwrap_or(NONE); + if off != NONE { + out.copy_from_slice( + self.arena + .as_ref() + .ok_or(Error::InvalidSize)? + .part(off, n)?, + ); + return Ok(()); + } + if let Some(q) = self.overrides.get(k).copied().filter(|q| *q != NONE) { + out.copy_from_slice( + self.exchange + .as_ref() + .ok_or(Error::InvalidSize)? + .part(q * self.maximum, n)?, + ); + return Ok(()); + } + let t = Instant::now(); + let result = abi::Copy::into_slice(self.parts(l, e)?, out)?.run(); + let mut c = self.counts.get(); + c.file_us = c.file_us.wrapping_add(t.elapsed().as_micros() as u64); + if result.is_ok() { + c.file_read_bytes = c.file_read_bytes.wrapping_add(n as u64); + } + self.counts.set(c); + result?; + self.lease + .validate_current() + .map_err(|_| Error::InvalidSize) + } + pub fn warm(&mut self, l: usize, experts: &[i64]) -> Result<()> { + self.live()?; + if l >= LAYERS { + return Ok(()); + } + for &e in experts { + if e < 0 || e >= EXPERTS as i64 || self.has_resident(l, e as usize) { + continue; + } + let k = l * EXPERTS + e as usize; + self.warm_stamp[k] = (self.epoch.wrapping_add(1)) as u32; + let mut c = self.counts.get(); + c.warmed = c.warmed.wrapping_add(1); + self.counts.set(c); + abi::warm(self.parts(l, e as usize)?); + } + Ok(()) + } + pub fn prefetch(&mut self, l: usize, experts: &[i64]) -> Result<()> { + let result = self.prefetch_impl(l, experts); + if result.is_err() { + for s in &mut self.stage { + if s.busy { + self.stage_of.remove(&s.key); + s.key = NONE; + s.busy = false; + } + } + } + result + } +} diff --git a/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_4.rs b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_4.rs new file mode 100644 index 00000000..62ffece4 --- /dev/null +++ b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_4.rs @@ -0,0 +1,176 @@ +//! Moved out of the parent module by STRA-338: impl OriginalFileExpertSource (4). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalFileExpertSource<'ctx> { + pub(in super::super) fn prefetch_impl(&mut self, l: usize, experts: &[i64]) -> Result<()> { + self.live()?; + if l >= LAYERS || experts.is_empty() { + return Ok(()); + } + let mut todo = Vec::new(); + todo.try_reserve_exact(experts.len().min(N)) + .map_err(|_| Error::HostAllocation)?; + for &e in experts { + if e < 0 || e >= EXPERTS as i64 { + continue; + } + let k = l * EXPERTS + e as usize; + if self.has_resident(l, e as usize) + || self.overrides.get(k).copied().unwrap_or(NONE) != NONE + { + continue; + } + let (v, fill) = self.claim_stage(k)?; + if fill { + todo.push((v, k)); + let stamp = self.warm_stamp[k]; + if stamp != 0 && (stamp as u64).wrapping_add(3) >= self.epoch.wrapping_add(1) { + let mut c = self.counts.get(); + c.warm_hits = c.warm_hits.wrapping_add(1); + self.counts.set(c); + } + } + } + if todo.is_empty() { + return Ok(()); + } + let mut jobs = Vec::new(); + jobs.try_reserve_exact(todo.len()) + .map_err(|_| Error::HostAllocation)?; + for &(v, k) in &todo { + let raw = self + .parts(l, k % EXPERTS)? + .map(|p| (p.as_ptr() as usize, p.len())); + jobs.push(abi::copy_parts_record(raw, &mut self.stage[v].data)?); + } + let next = AtomicUsize::new(0); + let mut result: Vec, u64)>>> = Vec::new(); + result + .try_reserve_exact(todo.len()) + .map_err(|_| Error::HostAllocation)?; + result.resize_with(todo.len(), || Mutex::new(None)); + let work = || loop { + let i = next.fetch_add(1, Ordering::Relaxed); + if i >= jobs.len() { + break; + } + let t = Instant::now(); + let r = jobs[i].run(); + if let Ok(mut out) = result[i].lock() { + *out = Some((r, t.elapsed().as_micros() as u64)); + } + }; + let nt = jobs.len().min(self.fetch_threads); + let stack = abi::worker_stack_bytes()?; + self.admit_extra( + nt.saturating_sub(1) + .checked_mul(stack) + .ok_or(Error::BudgetExceeded)?, + )?; + let spawned = thread::scope(|s| { + let mut workers = Vec::new(); + workers + .try_reserve_exact(nt.saturating_sub(1)) + .map_err(|_| Error::HostAllocation)?; + for _ in 1..nt { + workers.push( + thread::Builder::new() + .stack_size(stack) + .spawn_scoped(s, work) + .map_err(|_| Error::HostAllocation)?, + ); + } + work(); + for w in workers { + if w.join().is_err() { + return Err(Error::HostAllocation); + } + } + Ok(()) + }); + let source = self + .lease + .validate_current() + .map_err(|_| Error::InvalidSize); + let mut first = None; + for (i, &(v, k)) in todo.iter().enumerate() { + let completed = result[i].lock().ok().and_then(|mut r| r.take()); + let ok = completed.as_ref().is_some_and(|(r, _)| r.is_ok()) && source.is_ok(); + let mut c = self.counts.get(); + if let Some((r, us)) = completed { + c.file_us = c.file_us.wrapping_add(us); + if r.is_ok() && source.is_ok() { + c.file_read_bytes = c.file_read_bytes.wrapping_add(self.layer_bytes[l] as u64); + c.file_blob_bytes = c.file_blob_bytes.wrapping_add(self.layer_bytes[l] as u64); + } else if first.is_none() { + first = r.err().or(Some(Error::InvalidSize)); + } + } else if first.is_none() { + first = Some(Error::HostAllocation); + } + self.counts.set(c); + self.stage[v].busy = false; + if !ok { + self.stage_of.remove(&k); + self.stage[v].key = NONE; + } + } + combine(combine(spawned, source), first.map_or(Ok(()), Err)) + } + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + pub(in super::super) fn close_inner(&mut self) -> Result<()> { + if self.closed { + return Ok(()); + } + self.closed = true; + if self.context.is_poisoned() { + self.retain(); + return Err(Error::ContextPoisoned); + } + let guard = match self.context.enter() { + Ok(g) => g, + Err(e) => { + self.context.poison(); + self.context.retain_driver(); + self.retain(); + return Err(e); + } + }; + let operation = (|| { + self.context.synchronize()?; + let api = self.api.as_ref().ok_or(Error::ContextPoisoned)?; + let x = self.exchange.as_mut().map_or(Ok(()), |a| api.close(a)); + let a = self.arena.as_mut().map_or(Ok(()), |a| api.close(a)); + combine(x, a) + })(); + let result = combine(operation, guard.finish()); + if result.is_err() { + self.context.poison(); + self.context.retain_driver(); + self.retain(); + } + result + } + pub(in super::super) fn retain(&mut self) { + if let Some(a) = self.arena.take() { + std::mem::forget(a); + } + if let Some(a) = self.exchange.take() { + std::mem::forget(a); + } + if let Some(a) = self.api.take() { + std::mem::forget(a); + } + if let Some(m) = self.map.take() { + std::mem::forget(m); + } + std::mem::forget(self.lease.clone()); + let stage = std::mem::take(&mut self.stage); + std::mem::forget(stage); /* actual uncertain source storage is retained, not just its address */ + } +} diff --git a/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice.rs b/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice.rs index a246de3f..787888c2 100644 --- a/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice.rs +++ b/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice.rs @@ -3,472 +3,6 @@ #[allow(unused_imports)] use super::*; -impl<'ctx> OriginalMoePromptDevice<'ctx> { - pub(super) fn new(context: &'ctx Context<'ctx>, capacity: usize) -> Result { - if !(1..=8192).contains(&capacity) { - return Err(Error::InvalidQwenShape); - } - let moe = crate::qwen_dispatch::moe_prefill_batch::prefill_asset()?; - let dq = crate::qwen_dispatch::gdn_native_batch::dequant_asset()?; - let wanted = SCRATCH + STATUS + RESERVE; - if context.is_poisoned() { - return Err(Error::ContextPoisoned); - } - if context - .allocated_bytes() - .checked_add(wanted) - .is_none_or(|n| n > context.budget_bytes()) - || context.memory_info()?.0 < wanted - { - return Err(Error::BudgetExceeded); - } - let mut owner = Self { - context, - capacity, - status: None, - scratch: None, - moe: None, - dequant: None, - failed: false, - }; - let operation = (|| { - owner.status = Some(context.allocate(STATUS)?); - owner.scratch = Some(context.allocate(SCRATCH)?); - let guard = context.enter()?; - let load = (|| { - owner.moe = Some(KernelModule::load(moe, MOE_ENTRIES)?); - owner.dequant = Some(KernelModule::load(dq, DQ_ENTRIES)?); - Ok(()) - })(); - combine(load, guard.finish()) - })(); - if let Err(primary) = operation { - return combine(Err(primary), owner.close_inner()); - } - Ok(owner) - } - pub fn allocated_bytes(&self) -> usize { - self.status.as_ref().map_or(0, DeviceBuffer::len) - + self.scratch.as_ref().map_or(0, DeviceBuffer::len) - } - pub(super) fn handle(&self, buffer: &Option>, amount: usize) -> Result { - if self.failed || self.context.is_poisoned() { - return Err(Error::ContextPoisoned); - } - let b = buffer.as_ref().ok_or(Error::ContextPoisoned)?; - if b.bytes < amount || !std::ptr::eq(b.context, self.context) { - return Err(Error::InvalidQwenShape); - } - b.handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(b.bytes, 0, amount) - } - pub(super) fn weight( - &self, - rows: &OriginalPromptRows<'_, '_, '_>, - workspace: &NativeBatchWorkspace<'_>, - buffer: &DeviceBuffer<'_>, - amount: usize, - ) -> Result { - if buffer.bytes != amount { - return Err(Error::ShapeMismatch { - expected: amount, - actual: buffer.bytes, - }); - } - if !std::ptr::eq(buffer.context, self.context) { - return Err(Error::ContextMismatch); - } - let h = buffer.handle.ok_or(Error::ContextPoisoned)?; - h.validate_projection_extent(amount, 2)?; - workspace.reject_alias(h, amount)?; - for b in [&self.status, &self.scratch].into_iter().flatten() { - if h.overlaps(amount, b.handle.ok_or(Error::ContextPoisoned)?, b.bytes) { - return Err(Error::OutputAliasesInput); - } - } - // Every MoE scratch role can alias another phase; actual source weights - // are separate whole owners and must overlap none of this phase's spans. - for name in [ - "logits", "w", "ids", "slot_dev", "src_dev", "GU", "Dm", "sgate", "sup", "sh_h", - "shared", "sg", - ] { - let (a, n) = rows.span(PrefillPhase::Moe, name)?; - if h.overlaps(amount, a, n) { - return Err(Error::OutputAliasesInput); - } - } - for role in [S::R, S::Mixed, S::MixedHigh, S::MixedHalf, S::Block] { - let (a, n) = rows.common_span(role)?; - if h.overlaps(amount, a, n) { - return Err(Error::OutputAliasesInput); - } - } - Ok(h) - } - pub(super) fn scan( - &self, - commands: &mut Vec, - source: BufferHandle, - elements: usize, - half: bool, - slot: usize, - ) -> Result<()> { - let status = self - .handle(&self.status, STATUS)? - .checked_subspan(STATUS, slot * 4, 4)?; - kernel( - commands, - false, - if half { 2 } else { 1 }, - elements, - vec![ - A::Address(source), - A::Address(status), - A::U32(u32::try_from(elements).map_err(|_| Error::InvalidQwenShape)?), - ], - ) - } - pub(super) fn run( - &mut self, - workspace: &mut NativeBatchWorkspace<'ctx>, - mut commands: Vec, - labels: &[&'static str], - ) -> Result<()> { - workspace.validate_context(self.context)?; - let status = self.handle(&self.status, STATUS)?; - let zero = blank(STATUS)?; - let mut got = blank(STATUS)?; - let blas = workspace.blas()?; - let guard = self.context.enter()?; - let mut operation = self.context.driver.api.copy_from(status, &zero); - if operation.is_ok() { - operation = self.context.driver.api.synchronize(); - } - for command in &mut commands { - if operation.is_err() { - break; - } - operation = match command { - Command::Kernel { - dequant, - index, - grid, - args, - } => { - let module = if *dequant { &self.dequant } else { &self.moe }; - module.as_ref().ok_or(Error::ContextPoisoned)?.launch( - *index, - *grid, - 256, - blas.stream(), - args, - ) - } - Command::Gemm { - bf16, - input, - weight, - output, - t, - n, - k, - beta, - } => { - if *bf16 { - blas.gemm_bf16(*input, *weight, *output, *t, *n, *k, &1.0, beta) - } else { - blas.gemm_f16(*input, *weight, *output, *t, *n, *k, &1.0, beta) - } - } - }; - } - let wait = blas.synchronize(); - if operation.is_ok() && wait.is_ok() { - operation = self.context.driver.api.copy_to(status, &mut got); - } - let all = self.context.driver.api.synchronize(); - let pop = guard.finish(); - if operation.is_err() || wait.is_err() || all.is_err() || pop.is_err() { - self.failed = true; - self.context.poison(); - workspace.mark_failed(); - } - if wait.is_err() || all.is_err() || pop.is_err() { - std::mem::forget((commands, zero, got)); - self.context.retain_driver(); - return combine(combine(combine(operation, wait), all), pop); - } - combine(combine(combine(operation, wait), all), pop)?; - for word in got.as_chunks::<4>().0 { - if u32::from_le_bytes(*word) > 1 { - self.failed = true; - self.context.poison(); - return Err(Error::InvalidDriverValue("Original MoE status")); - } - } - for (slot, label) in labels.iter().enumerate() { - if u32::from_le_bytes( - got[slot * 4..slot * 4 + 4] - .try_into() - .map_err(|_| Error::InvalidSize)?, - ) != 0 - { - return Err(Error::NonFiniteMmqOutput(label)); - } - } - Ok(()) - } - /// Weights are the actual router, shared scalar gate, shared gate/up/down. - /// Runtime authenticates their binding/role; driver admits their whole owners. - pub fn prepare<'program, 'arena, 'loan>( - &'program mut self, - read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, - weights: [&DeviceBuffer<'_>; 5], - formats: [GdnNativeFormat; 3], - low: bool, - ) -> Result> { - if !read.context_matches(self.context) || read.rows() == 0 || read.rows() > self.capacity { - return Err(Error::ContextMismatch); - } - let rows = read.lease(); - let t = rows.rows(); - workspace.validate_context(self.context)?; - let high = common(rows, S::MixedHigh, 5120)?; - let half = common(rows, S::MixedHalf, 5120)?; - let low_image = if low { - Some(common(rows, S::MixedLow, 5120)?) - } else { - None - }; - let logits = phase(rows, "logits", 512 * 4)?; - let ids = phase(rows, "ids", 10 * 4)?; - let w = phase(rows, "w", 10 * 4)?; - let gate = phase(rows, "sgate", 640 * 4)?; - let up = phase(rows, "sup", 640 * 4)?; - let h = phase(rows, "sh_h", 640 * 2)?; - let shared = phase(rows, "shared", 2560 * 4)?; - let sg = phase(rows, "sg", 4)?; - let router = self.weight(rows, workspace, weights[0], 512 * 2560 * 2)?; - let scalar = self.weight(rows, workspace, weights[1], 2560 * 2)?; - let dims = [(640, 2560), (640, 2560), (2560, 640)]; - let mut native = Vec::new(); - native - .try_reserve_exact(3) - .map_err(|_| Error::HostAllocation)?; - for (index, (n, k)) in dims.iter().copied().enumerate() { - native.push(self.weight( - rows, - workspace, - weights[index + 2], - formats[index].matrix_bytes(n, k)?, - )?); - } - let scratch = self.handle(&self.scratch, SCRATCH)?; - let mut commands = Vec::new(); - commands - .try_reserve_exact(32) - .map_err(|_| Error::HostAllocation)?; - self.scan(&mut commands, half, t * 2560, true, 0)?; - gemm(&mut commands, true, high, router, logits, t, 512, 2560, 0.0)?; - if let Some(lo) = low_image { - gemm(&mut commands, true, lo, router, logits, t, 512, 2560, 1.0)?; - } - self.scan(&mut commands, logits, t * 512, false, 1)?; - // route_kernel<16>: one warp/token, eight token rows per256-thread CTA. - commands.push(Command::Kernel { - dequant: false, - index: 4, - grid: t.div_ceil(8) as u32, - args: KernelArguments::new(vec![ - A::Address(logits), - A::Address(ids), - A::Address(w), - A::I64(t as i64), - ]), - }); - self.scan(&mut commands, w, t * 10, false, 2)?; - for index in 0..3 { - let (n, k) = dims[index]; - let destination = [gate, up, shared][index]; - kernel( - &mut commands, - true, - dequant_index(formats[index]), - n * (k / 32), - vec![ - A::Address(native[index]), - A::I64(formats[index].matrix_bytes(1, k)? as i64), - A::I64(0), - A::I64(n as i64), - A::I64((k / 32) as i64), - A::Address(scratch), - ], - )?; - gemm( - &mut commands, - false, - if index == 2 { h } else { half }, - scratch, - destination, - t, - n, - k, - 0.0, - )?; - self.scan(&mut commands, destination, t * n, false, [3, 4, 6][index])?; - if index == 1 { - kernel( - &mut commands, - false, - 5, - t * 640, - vec![ - A::Address(gate), - A::Address(up), - A::Address(h), - A::I64(t as i64), - ], - )?; - self.scan(&mut commands, h, t * 640, true, 5)?; - } - } - gemm(&mut commands, true, high, scalar, sg, t, 1, 2560, 0.0)?; - if let Some(lo) = low_image { - gemm(&mut commands, true, lo, scalar, sg, t, 1, 2560, 1.0)?; - } - self.scan(&mut commands, sg, t, false, 7)?; - self.run( - workspace, - commands, - &[ - "MixedH", - "router", - "route weights", - "shared Gate", - "shared Up", - "shared SwiGLU", - "shared Down", - "shared scalar", - ], - )?; - let mut raw = blank(t * 10 * 4)?; - let guard = self.context.enter()?; - let copy = self.context.driver.api.copy_to(ids, &mut raw); - let wait = self.context.driver.api.synchronize(); - let pop = guard.finish(); - if wait.is_err() || pop.is_err() { - std::mem::forget(raw); - self.failed = true; - self.context.poison(); - return combine(combine(copy, wait), pop).map(|()| unreachable!()); - } - combine(combine(copy, wait), pop)?; - let mut counts = [0u32; 512]; - for row in raw.chunks_exact(40) { - let mut seen = [0u64; 8]; - for word in row.as_chunks::<4>().0 { - let id = i32::from_le_bytes(*word); - if !(0..512).contains(&id) { - return Err(Error::InvalidDriverValue("Original routed ID")); - } - let id = id as usize; - let bit = 1u64 << (id % 64); - if seen[id / 64] & bit != 0 { - return Err(Error::InvalidDriverValue("Original duplicate routed ID")); - } - seen[id / 64] |= bit; - counts[id] += 1; - } - } - let mut offsets = [0usize; 513]; - for expert in 0..512 { - offsets[expert + 1] = offsets[expert] + counts[expert] as usize; - } - let mut cursor = offsets; - let mut source_rows = Vec::new(); - source_rows - .try_reserve_exact(t * 10) - .map_err(|_| Error::HostAllocation)?; - source_rows.resize(t * 10, 0); - let mut slot_map = Vec::new(); - slot_map - .try_reserve_exact(t * 10) - .map_err(|_| Error::HostAllocation)?; - for (i, word) in raw.as_chunks::<4>().0.iter().enumerate() { - let id = i32::from_le_bytes(*word) as usize; - let p = cursor[id]; - cursor[id] += 1; - slot_map.push(p as i32); - source_rows[p] = (i / 10) as u32; - } - let mut order = Vec::new(); - let mut actual_counts = Vec::new(); - order - .try_reserve_exact(512) - .map_err(|_| Error::HostAllocation)?; - actual_counts - .try_reserve_exact(512) - .map_err(|_| Error::HostAllocation)?; - for (id, count) in counts.iter().copied().enumerate() { - if count > 0 { - order.push(id as u32); - actual_counts.push(count); - } - } - Ok(OriginalMoePromptLayer { - program: self, - read, - order, - counts: actual_counts, - source_rows, - slot_map, - slot_uploaded: false, - completed_experts: 0, - }) - } - pub fn close(mut self) -> Result<()> { - self.close_inner() - } - pub(super) fn close_inner(&mut self) -> Result<()> { - if self.status.is_none() - && self.scratch.is_none() - && self.moe.is_none() - && self.dequant.is_none() - { - return Ok(()); - } - if self.context.is_poisoned() { - if let Some(v) = self.status.take() { - std::mem::forget(v); - } - if let Some(v) = self.scratch.take() { - std::mem::forget(v); - } - if let Some(v) = self.moe.take() { - std::mem::forget(v); - } - if let Some(v) = self.dequant.take() { - std::mem::forget(v); - } - self.context.retain_driver(); - return Err(Error::ContextPoisoned); - } - let guard = self.context.enter()?; - let mut result = Ok(()); - for module in [&mut self.moe, &mut self.dequant] { - if let Some(module) = module.take() { - result = combine(result, module.close()); - } - } - result = combine(result, guard.finish()); - for buffer in [&mut self.status, &mut self.scratch] { - if let Some(buffer) = buffer.take() { - result = combine(result, buffer.release()); - } - } - self.failed = true; - result - } -} +mod impl_originalmoepromptdevice_2; +mod impl_originalmoepromptdevice_2_2; +mod impl_originalmoepromptdevice_3; diff --git a/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice/impl_originalmoepromptdevice_2.rs b/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice/impl_originalmoepromptdevice_2.rs new file mode 100644 index 00000000..053ed653 --- /dev/null +++ b/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice/impl_originalmoepromptdevice_2.rs @@ -0,0 +1,223 @@ +//! Moved out of the parent module by STRA-338: impl OriginalMoePromptDevice. + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalMoePromptDevice<'ctx> { + pub(in super::super) fn new(context: &'ctx Context<'ctx>, capacity: usize) -> Result { + if !(1..=8192).contains(&capacity) { + return Err(Error::InvalidQwenShape); + } + let moe = crate::qwen_dispatch::moe_prefill_batch::prefill_asset()?; + let dq = crate::qwen_dispatch::gdn_native_batch::dequant_asset()?; + let wanted = SCRATCH + STATUS + RESERVE; + if context.is_poisoned() { + return Err(Error::ContextPoisoned); + } + if context + .allocated_bytes() + .checked_add(wanted) + .is_none_or(|n| n > context.budget_bytes()) + || context.memory_info()?.0 < wanted + { + return Err(Error::BudgetExceeded); + } + let mut owner = Self { + context, + capacity, + status: None, + scratch: None, + moe: None, + dequant: None, + failed: false, + }; + let operation = (|| { + owner.status = Some(context.allocate(STATUS)?); + owner.scratch = Some(context.allocate(SCRATCH)?); + let guard = context.enter()?; + let load = (|| { + owner.moe = Some(KernelModule::load(moe, MOE_ENTRIES)?); + owner.dequant = Some(KernelModule::load(dq, DQ_ENTRIES)?); + Ok(()) + })(); + combine(load, guard.finish()) + })(); + if let Err(primary) = operation { + return combine(Err(primary), owner.close_inner()); + } + Ok(owner) + } + pub fn allocated_bytes(&self) -> usize { + self.status.as_ref().map_or(0, DeviceBuffer::len) + + self.scratch.as_ref().map_or(0, DeviceBuffer::len) + } + pub(in super::super) fn handle(&self, buffer: &Option>, amount: usize) -> Result { + if self.failed || self.context.is_poisoned() { + return Err(Error::ContextPoisoned); + } + let b = buffer.as_ref().ok_or(Error::ContextPoisoned)?; + if b.bytes < amount || !std::ptr::eq(b.context, self.context) { + return Err(Error::InvalidQwenShape); + } + b.handle + .ok_or(Error::ContextPoisoned)? + .checked_subspan(b.bytes, 0, amount) + } + pub(in super::super) fn weight( + &self, + rows: &OriginalPromptRows<'_, '_, '_>, + workspace: &NativeBatchWorkspace<'_>, + buffer: &DeviceBuffer<'_>, + amount: usize, + ) -> Result { + if buffer.bytes != amount { + return Err(Error::ShapeMismatch { + expected: amount, + actual: buffer.bytes, + }); + } + if !std::ptr::eq(buffer.context, self.context) { + return Err(Error::ContextMismatch); + } + let h = buffer.handle.ok_or(Error::ContextPoisoned)?; + h.validate_projection_extent(amount, 2)?; + workspace.reject_alias(h, amount)?; + for b in [&self.status, &self.scratch].into_iter().flatten() { + if h.overlaps(amount, b.handle.ok_or(Error::ContextPoisoned)?, b.bytes) { + return Err(Error::OutputAliasesInput); + } + } + // Every MoE scratch role can alias another phase; actual source weights + // are separate whole owners and must overlap none of this phase's spans. + for name in [ + "logits", "w", "ids", "slot_dev", "src_dev", "GU", "Dm", "sgate", "sup", "sh_h", + "shared", "sg", + ] { + let (a, n) = rows.span(PrefillPhase::Moe, name)?; + if h.overlaps(amount, a, n) { + return Err(Error::OutputAliasesInput); + } + } + for role in [S::R, S::Mixed, S::MixedHigh, S::MixedHalf, S::Block] { + let (a, n) = rows.common_span(role)?; + if h.overlaps(amount, a, n) { + return Err(Error::OutputAliasesInput); + } + } + Ok(h) + } + pub(in super::super) fn scan( + &self, + commands: &mut Vec, + source: BufferHandle, + elements: usize, + half: bool, + slot: usize, + ) -> Result<()> { + let status = self + .handle(&self.status, STATUS)? + .checked_subspan(STATUS, slot * 4, 4)?; + kernel( + commands, + false, + if half { 2 } else { 1 }, + elements, + vec![ + A::Address(source), + A::Address(status), + A::U32(u32::try_from(elements).map_err(|_| Error::InvalidQwenShape)?), + ], + ) + } + pub(in super::super) fn run( + &mut self, + workspace: &mut NativeBatchWorkspace<'ctx>, + mut commands: Vec, + labels: &[&'static str], + ) -> Result<()> { + workspace.validate_context(self.context)?; + let status = self.handle(&self.status, STATUS)?; + let zero = blank(STATUS)?; + let mut got = blank(STATUS)?; + let blas = workspace.blas()?; + let guard = self.context.enter()?; + let mut operation = self.context.driver.api.copy_from(status, &zero); + if operation.is_ok() { + operation = self.context.driver.api.synchronize(); + } + for command in &mut commands { + if operation.is_err() { + break; + } + operation = match command { + Command::Kernel { + dequant, + index, + grid, + args, + } => { + let module = if *dequant { &self.dequant } else { &self.moe }; + module.as_ref().ok_or(Error::ContextPoisoned)?.launch( + *index, + *grid, + 256, + blas.stream(), + args, + ) + } + Command::Gemm { + bf16, + input, + weight, + output, + t, + n, + k, + beta, + } => { + if *bf16 { + blas.gemm_bf16(*input, *weight, *output, *t, *n, *k, &1.0, beta) + } else { + blas.gemm_f16(*input, *weight, *output, *t, *n, *k, &1.0, beta) + } + } + }; + } + let wait = blas.synchronize(); + if operation.is_ok() && wait.is_ok() { + operation = self.context.driver.api.copy_to(status, &mut got); + } + let all = self.context.driver.api.synchronize(); + let pop = guard.finish(); + if operation.is_err() || wait.is_err() || all.is_err() || pop.is_err() { + self.failed = true; + self.context.poison(); + workspace.mark_failed(); + } + if wait.is_err() || all.is_err() || pop.is_err() { + std::mem::forget((commands, zero, got)); + self.context.retain_driver(); + return combine(combine(combine(operation, wait), all), pop); + } + combine(combine(combine(operation, wait), all), pop)?; + for word in got.as_chunks::<4>().0 { + if u32::from_le_bytes(*word) > 1 { + self.failed = true; + self.context.poison(); + return Err(Error::InvalidDriverValue("Original MoE status")); + } + } + for (slot, label) in labels.iter().enumerate() { + if u32::from_le_bytes( + got[slot * 4..slot * 4 + 4] + .try_into() + .map_err(|_| Error::InvalidSize)?, + ) != 0 + { + return Err(Error::NonFiniteMmqOutput(label)); + } + } + Ok(()) + } +} diff --git a/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice/impl_originalmoepromptdevice_2_2.rs b/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice/impl_originalmoepromptdevice_2_2.rs new file mode 100644 index 00000000..281d449a --- /dev/null +++ b/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice/impl_originalmoepromptdevice_2_2.rs @@ -0,0 +1,220 @@ +//! Moved out of the parent module by STRA-338: impl OriginalMoePromptDevice (2). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalMoePromptDevice<'ctx> { + /// Weights are the actual router, shared scalar gate, shared gate/up/down. + /// Runtime authenticates their binding/role; driver admits their whole owners. + pub fn prepare<'program, 'arena, 'loan>( + &'program mut self, + read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + weights: [&DeviceBuffer<'_>; 5], + formats: [GdnNativeFormat; 3], + low: bool, + ) -> Result> { + if !read.context_matches(self.context) || read.rows() == 0 || read.rows() > self.capacity { + return Err(Error::ContextMismatch); + } + let rows = read.lease(); + let t = rows.rows(); + workspace.validate_context(self.context)?; + let high = common(rows, S::MixedHigh, 5120)?; + let half = common(rows, S::MixedHalf, 5120)?; + let low_image = if low { + Some(common(rows, S::MixedLow, 5120)?) + } else { + None + }; + let logits = phase(rows, "logits", 512 * 4)?; + let ids = phase(rows, "ids", 10 * 4)?; + let w = phase(rows, "w", 10 * 4)?; + let gate = phase(rows, "sgate", 640 * 4)?; + let up = phase(rows, "sup", 640 * 4)?; + let h = phase(rows, "sh_h", 640 * 2)?; + let shared = phase(rows, "shared", 2560 * 4)?; + let sg = phase(rows, "sg", 4)?; + let router = self.weight(rows, workspace, weights[0], 512 * 2560 * 2)?; + let scalar = self.weight(rows, workspace, weights[1], 2560 * 2)?; + let dims = [(640, 2560), (640, 2560), (2560, 640)]; + let mut native = Vec::new(); + native + .try_reserve_exact(3) + .map_err(|_| Error::HostAllocation)?; + for (index, (n, k)) in dims.iter().copied().enumerate() { + native.push(self.weight( + rows, + workspace, + weights[index + 2], + formats[index].matrix_bytes(n, k)?, + )?); + } + let scratch = self.handle(&self.scratch, SCRATCH)?; + let mut commands = Vec::new(); + commands + .try_reserve_exact(32) + .map_err(|_| Error::HostAllocation)?; + self.scan(&mut commands, half, t * 2560, true, 0)?; + gemm(&mut commands, true, high, router, logits, t, 512, 2560, 0.0)?; + if let Some(lo) = low_image { + gemm(&mut commands, true, lo, router, logits, t, 512, 2560, 1.0)?; + } + self.scan(&mut commands, logits, t * 512, false, 1)?; + // route_kernel<16>: one warp/token, eight token rows per256-thread CTA. + commands.push(Command::Kernel { + dequant: false, + index: 4, + grid: t.div_ceil(8) as u32, + args: KernelArguments::new(vec![ + A::Address(logits), + A::Address(ids), + A::Address(w), + A::I64(t as i64), + ]), + }); + self.scan(&mut commands, w, t * 10, false, 2)?; + for index in 0..3 { + let (n, k) = dims[index]; + let destination = [gate, up, shared][index]; + kernel( + &mut commands, + true, + dequant_index(formats[index]), + n * (k / 32), + vec![ + A::Address(native[index]), + A::I64(formats[index].matrix_bytes(1, k)? as i64), + A::I64(0), + A::I64(n as i64), + A::I64((k / 32) as i64), + A::Address(scratch), + ], + )?; + gemm( + &mut commands, + false, + if index == 2 { h } else { half }, + scratch, + destination, + t, + n, + k, + 0.0, + )?; + self.scan(&mut commands, destination, t * n, false, [3, 4, 6][index])?; + if index == 1 { + kernel( + &mut commands, + false, + 5, + t * 640, + vec![ + A::Address(gate), + A::Address(up), + A::Address(h), + A::I64(t as i64), + ], + )?; + self.scan(&mut commands, h, t * 640, true, 5)?; + } + } + gemm(&mut commands, true, high, scalar, sg, t, 1, 2560, 0.0)?; + if let Some(lo) = low_image { + gemm(&mut commands, true, lo, scalar, sg, t, 1, 2560, 1.0)?; + } + self.scan(&mut commands, sg, t, false, 7)?; + self.run( + workspace, + commands, + &[ + "MixedH", + "router", + "route weights", + "shared Gate", + "shared Up", + "shared SwiGLU", + "shared Down", + "shared scalar", + ], + )?; + let mut raw = blank(t * 10 * 4)?; + let guard = self.context.enter()?; + let copy = self.context.driver.api.copy_to(ids, &mut raw); + let wait = self.context.driver.api.synchronize(); + let pop = guard.finish(); + if wait.is_err() || pop.is_err() { + std::mem::forget(raw); + self.failed = true; + self.context.poison(); + return combine(combine(copy, wait), pop).map(|()| unreachable!()); + } + combine(combine(copy, wait), pop)?; + let mut counts = [0u32; 512]; + for row in raw.chunks_exact(40) { + let mut seen = [0u64; 8]; + for word in row.as_chunks::<4>().0 { + let id = i32::from_le_bytes(*word); + if !(0..512).contains(&id) { + return Err(Error::InvalidDriverValue("Original routed ID")); + } + let id = id as usize; + let bit = 1u64 << (id % 64); + if seen[id / 64] & bit != 0 { + return Err(Error::InvalidDriverValue("Original duplicate routed ID")); + } + seen[id / 64] |= bit; + counts[id] += 1; + } + } + let mut offsets = [0usize; 513]; + for expert in 0..512 { + offsets[expert + 1] = offsets[expert] + counts[expert] as usize; + } + let mut cursor = offsets; + let mut source_rows = Vec::new(); + source_rows + .try_reserve_exact(t * 10) + .map_err(|_| Error::HostAllocation)?; + source_rows.resize(t * 10, 0); + let mut slot_map = Vec::new(); + slot_map + .try_reserve_exact(t * 10) + .map_err(|_| Error::HostAllocation)?; + for (i, word) in raw.as_chunks::<4>().0.iter().enumerate() { + let id = i32::from_le_bytes(*word) as usize; + let p = cursor[id]; + cursor[id] += 1; + slot_map.push(p as i32); + source_rows[p] = (i / 10) as u32; + } + let mut order = Vec::new(); + let mut actual_counts = Vec::new(); + order + .try_reserve_exact(512) + .map_err(|_| Error::HostAllocation)?; + actual_counts + .try_reserve_exact(512) + .map_err(|_| Error::HostAllocation)?; + for (id, count) in counts.iter().copied().enumerate() { + if count > 0 { + order.push(id as u32); + actual_counts.push(count); + } + } + Ok(OriginalMoePromptLayer { + program: self, + read, + order, + counts: actual_counts, + source_rows, + slot_map, + slot_uploaded: false, + completed_experts: 0, + }) + } + pub fn close(mut self) -> Result<()> { + self.close_inner() + } +} diff --git a/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice/impl_originalmoepromptdevice_3.rs b/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice/impl_originalmoepromptdevice_3.rs new file mode 100644 index 00000000..62fbfe04 --- /dev/null +++ b/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice/impl_originalmoepromptdevice_3.rs @@ -0,0 +1,48 @@ +//! Moved out of the parent module by STRA-338: impl OriginalMoePromptDevice (3). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalMoePromptDevice<'ctx> { + pub(in super::super) fn close_inner(&mut self) -> Result<()> { + if self.status.is_none() + && self.scratch.is_none() + && self.moe.is_none() + && self.dequant.is_none() + { + return Ok(()); + } + if self.context.is_poisoned() { + if let Some(v) = self.status.take() { + std::mem::forget(v); + } + if let Some(v) = self.scratch.take() { + std::mem::forget(v); + } + if let Some(v) = self.moe.take() { + std::mem::forget(v); + } + if let Some(v) = self.dequant.take() { + std::mem::forget(v); + } + self.context.retain_driver(); + return Err(Error::ContextPoisoned); + } + let guard = self.context.enter()?; + let mut result = Ok(()); + for module in [&mut self.moe, &mut self.dequant] { + if let Some(module) = module.take() { + result = combine(result, module.close()); + } + } + result = combine(result, guard.finish()); + for buffer in [&mut self.status, &mut self.scratch] { + if let Some(buffer) = buffer.take() { + result = combine(result, buffer.release()); + } + } + self.failed = true; + result + } +} diff --git a/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor.rs b/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor.rs index 65428ea5..442dc9ec 100644 --- a/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor.rs +++ b/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor.rs @@ -3,445 +3,7 @@ #[allow(unused_imports)] use super::*; - -impl<'ctx> OriginalMtpActor<'ctx> { - /// End of `MtpDrafter::load` + `bind`: take ownership of the assembled - /// drafter and verify, against the owners themselves, every fact the plan - /// and the evidence claim. `ring` is only inspected (it stays with the - /// draft session). On refusal the drafter is closed before returning. - pub fn adopt( - context: &'ctx Context<'ctx>, - plan: OriginalMtpLoadPlan, - drafter: OriginalMtpDrafter<'ctx>, - ring: &MtpOriginalInt8<'ctx>, - weights: Rc>, - evidence: OriginalMtpLoadEvidence, - ) -> std::result::Result { - let mut drafter = drafter; - match Self::admit(context, &plan, &mut drafter, ring, &weights, evidence) { - Ok((kv, disposition, coupled)) => Ok(Self { - drafter: Some(drafter), - weights, - context, - settings: DraftSettings::default(), - kv, - coupled: Box::new(coupled), - disposition, - device: evidence.device, - vram: evidence.vram_bytes, - draft_vocabulary: evidence.draft_vocabulary, - plan, - }), - Err(failure) => { - let _ = drafter.close(); - Err(failure) - } - } - } - - pub(super) fn admit( - context: &'ctx Context<'ctx>, - plan: &OriginalMtpLoadPlan, - drafter: &mut OriginalMtpDrafter<'ctx>, - ring: &MtpOriginalInt8<'ctx>, - weights: &OriginalMtpRetainedFullWeights<'ctx>, - evidence: OriginalMtpLoadEvidence, - ) -> std::result::Result<(KvPlan, SetupDisposition, CoupledDraftHost), OriginalMtpLoadFailure> - { - let capture = *plan.capture(); - drafter.validate_context(context).map_err(inconsistent)?; - ring.validate_context(context).map_err(inconsistent)?; - weights.validate_context(context).map_err(inconsistent)?; - if drafter.loaded_max_t().map_err(inconsistent)? as u64 != capture.max_t { - return Err(mismatch("max_t differs from the loaded drafter")); - } - // `cudaGetDevice` at load: capture, context and ledger must agree. - if context.device_ordinal() != capture.device || evidence.device != capture.device { - return Err(mismatch( - "the drafter's device differs from the captured one", - )); - } - if weights.id_vocabulary() as u64 != capture.vocabulary { - return Err(mismatch("the draft vocabulary differs from output.weight")); - } - // Both directions: a bound subset must be the loaded draft head and - // the loaded draft head must be the bound subset. - if weights.subset_rows() != evidence.draft_vocabulary { - return Err(mismatch("the draft head differs from the retained weights")); - } - // The retained state's ACTUAL mode, not a configured one: window ring - // as planned, or the Original fully-resident retry. - let kv = plan - .admit_ring(ring.fully_resident().map_err(inconsistent)?) - .map_err(|e| OriginalMtpLoadFailure::new(e.message(), None))?; - - // coupled setup: preference -> plan -> literal disposition -> layout - let subset = weights.subset_rows(); - let mut preference = CoupledPreference::from_observed_env(None); - preference.set(capture.coupled_requested); - let disposition = setup_disposition(&preference, capture.vocabulary as usize, subset); - let planned = plan - .coupled(subset.map(|n| n as u64)) - .map_err(|e| OriginalMtpLoadFailure::new(e.message(), None))?; - let expected = match planned { - CoupledPlan::Off => SetupDisposition::Disabled, - CoupledPlan::ArgmaxVocabularyTooWide => SetupDisposition::ArgmaxFallback, - CoupledPlan::Allocate { .. } => SetupDisposition::NeedsActualDeviceSetup, - }; - let layout_coupled = drafter.loaded_coupled().map_err(inconsistent)?; - if disposition != expected - || layout_coupled != (disposition == SetupDisposition::NeedsActualDeviceSetup) - { - return Err(mismatch( - "the coupled resources do not match the setup plan", - )); - } - let mut host = CoupledDraftHost::unselected(); - if disposition == SetupDisposition::NeedsActualDeviceSetup { - // setup_coupled ends with cudaDeviceSynchronize before coupled_ok. - context.synchronize().map_err(|e| { - OriginalMtpLoadFailure::new( - "mtp: coupled setup: device synchronize failed", - Some(e), - ) - })?; - let receipt = CoupledSetupReceipt::after_setup(disposition, layout_coupled, true) - .ok_or_else(|| mismatch("the coupled setup receipt was not issued"))?; - host.arm(receipt); - } - Ok((kv, disposition, host)) - } - - /// `device()`. - pub fn device(&self) -> i32 { - self.device - } - /// `vram_bytes()`: the context ledger across load and bind. - pub fn vram_bytes(&self) -> u64 { - self.vram - } - /// The admitted draft-state plan (window ring, or the resident retry). - pub fn kv_plan(&self) -> &KvPlan { - &self.kv - } - pub fn load_plan(&self) -> &OriginalMtpLoadPlan { - &self.plan - } - pub fn draft_vocabulary(&self) -> Option { - self.draft_vocabulary - } - pub fn max_t(&self) -> u64 { - self.plan.capture().max_t - } - pub fn settings(&self) -> &DraftSettings { - &self.settings - } - pub fn set_prompt_len(&mut self, n: i64) { - self.settings.set_prompt_len(n); - } - pub fn set_max_drafts(&mut self, k: i32) { - self.settings.set_max_drafts(k); - } - /// `first_needed()` over the ADMITTED effective window. - pub fn first_needed(&self) -> std::result::Result { - self.settings.first_needed(self.kv.effective_window as i64) - } - pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { - if !std::ptr::eq(c, self.context) { - return Err(Error::ContextMismatch); - } - self.weights.validate_context(c)?; - self.drafter - .as_ref() - .ok_or(Error::ContextPoisoned)? - .validate_context(c) - } - pub fn is_failed(&self) -> bool { - self.drafter - .as_ref() - .is_none_or(OriginalMtpDrafter::is_failed) - } - /// stderr line of `load`, for the operator log. - pub fn load_report(&self) -> String { - let bank = self.plan.weight_bank(); - let mib = |n: u64| n as f64 / 1_048_576.0; - let mut line = format!( - "strata mtp: draft layer loaded, {:.0} MiB of VRAM (experts {:.0}, dense {:.0})", - mib(self.vram), - mib(bank.expert_device_bytes), - mib(bank.dense_file_bytes) - ); - if let Some(n) = self.draft_vocabulary { - line.push_str(&format!("; draft head over {n} tokens")); - } - match self.disposition { - SetupDisposition::NeedsActualDeviceSetup => { - line.push_str("; coupled draft sampling on") - } - SetupDisposition::ArgmaxFallback => { - line.push_str("; coupled sampler too wide, argmax drafts") - } - SetupDisposition::Disabled => {} - } - line - } - - /// `idle()`: synchronize the capture stream (`cs_`) and nothing else. - pub fn idle(&mut self) -> Result<()> { - self.drafter - .as_mut() - .ok_or(Error::ContextPoisoned)? - .idle_public() - } - - /// Scalar draft K/V prefill on the actor's own scalar owner (short prompts; see `OriginalMtpDrafter::record_scalar_prefill`). - #[allow(clippy::too_many_arguments)] - pub fn record_scalar_prefill<'arena, 'loan>( - &mut self, - residual: &mut crate::OriginalDeviceResidual<'arena, 'loan, 'ctx>, - workspace: &mut crate::NativeBatchWorkspace<'ctx>, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - tokens: &[i32], - cell0: usize, - first_needed: usize, - retained: Rc>, - policy: &crate::OriginalMtpScalarPolicy, - cancelled: impl FnMut() -> bool, - ) -> Result { - self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.record_scalar_prefill( - residual, workspace, ring, prior, tokens, cell0, first_needed, retained, policy, cancelled, - ) - } - - /// Release everything the drafter bound to the verifier bank of the request that just ended (see - /// `OriginalMtpDrafter::release_verifier_bindings`). Call it before the verifier is closed. - pub fn release_verifier_bindings(&mut self) -> Result<()> { - self.drafter - .as_mut() - .ok_or(Error::ContextPoisoned)? - .release_verifier_bindings() - } - - /// `kv_restore(upto)`: refill the draft ring's window for a sequence that - /// continues at `upto` from the host pages `prior` authenticates. A no-op - /// when the ring is fully resident, exactly as in Original. - pub fn kv_restore( - &mut self, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - upto: i64, - ) -> Result<()> { - self.drafter - .as_mut() - .ok_or(Error::ContextPoisoned)? - .resume_public_kv(ring, prior, upto) - } - - /// `coupled()`. - pub fn coupled(&self) -> bool { - self.coupled.is_active() - } - /// `set_draft_sampling`: a no-op unless coupled setup succeeded. - pub fn set_draft_sampling(&mut self, params: &SamplerParams) { - self.coupled.set_draft_sampling(params); - } - /// `set_draft_history`: `tail` is what the session holds after the commit, - /// `next` the window's pick at the last accepted row. - pub fn set_draft_history(&mut self, tail: &[i32], next: i32) -> Result<()> { - self.coupled - .set_draft_history(tail, next) - .map_err(|_| Error::InvalidQwenShape) - } - - pub(super) fn staged_coupled(&self) -> Option<(SamplerParams, Box<[i32; 4096]>)> { - self.coupled - .staged_host_values() - .map(|(p, h)| (*p, Box::new(*h))) - } - - /// `draft(T, tokens, p, a, drafts, ...)` over a completed verifier window. - /// `max_drafts` and the coupled request come from this actor's settings. - #[allow(clippy::too_many_arguments)] - pub fn draft_from_verifier( - &mut self, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - window: OriginalVerifyWindow<'ctx>, - selection: NativeHeadSelection, - accepted_row: usize, - min_probability: f32, - policy: &OriginalMtpFullPolicy, - ) -> Result> { - let staged = self.staged_coupled(); - let coupled = staged.as_ref().map(|(p, h)| (*p, &**h)); - let max_drafts = self.settings.max_drafts(); - self.drafter - .as_mut() - .ok_or(Error::ContextPoisoned)? - .draft_from_verifier( - ring, - prior, - window, - selection, - accepted_row, - max_drafts, - min_probability, - policy, - coupled, - ) - } - - /// `draft_from_verifier` split around the host's work (`OriginalMtpDrafter::launch_from_verifier`); `after` is the - /// verifier's pending commit event. - #[allow(clippy::too_many_arguments)] - pub fn launch_draft_from_verifier( - &mut self, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - window: OriginalVerifyWindow<'ctx>, - selection: NativeHeadSelection, - accepted_row: usize, - min_probability: f32, - policy: &OriginalMtpFullPolicy, - after: Option<&mut crate::OriginalGpuEvent<'ctx>>, - ) -> Result<()> { - let staged = self.staged_coupled(); - let coupled = staged.as_ref().map(|(p, h)| (*p, &**h)); - let max_drafts = self.settings.max_drafts(); - self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.launch_from_verifier( - ring, - prior, - window, - selection, - accepted_row, - max_drafts, - min_probability, - policy, - coupled, - after, - ) - } - /// The read-back half of `launch_draft_from_verifier`. - pub fn finish_draft_from_verifier( - &mut self, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - policy: &OriginalMtpFullPolicy, - ) -> Result> { - self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.finish_from_verifier(ring, prior, policy) - } - - /// `draft_first(T, R_row, token, cell, ...)`: the Original repeat-row path. - #[allow(clippy::too_many_arguments)] - pub fn draft_first_from_verifier( - &mut self, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - window: OriginalVerifyWindow<'ctx>, - selection: NativeHeadSelection, - rows: usize, - min_probability: f32, - policy: &OriginalMtpFullPolicy, - ) -> Result> { - let staged = self.staged_coupled(); - let coupled = staged.as_ref().map(|(p, h)| (*p, &**h)); - let max_drafts = self.settings.max_drafts(); - self.drafter - .as_mut() - .ok_or(Error::ContextPoisoned)? - .draft_first_from_verifier( - ring, - prior, - window, - selection, - rows, - max_drafts, - min_probability, - policy, - coupled, - ) - } - - /// Public array form of `draft` (`drafts`/`probs` out-arguments). - #[allow(clippy::too_many_arguments)] - pub fn draft( - &mut self, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - window: OriginalVerifyWindow<'ctx>, - selection: NativeHeadSelection, - accepted_row: usize, - min_probability: f32, - policy: &OriginalMtpFullPolicy, - drafts: &mut [i32], - probabilities: Option<&mut [f32]>, - ) -> Result> { - let staged = self.staged_coupled(); - let coupled = staged.as_ref().map(|(p, h)| (*p, &**h)); - let settings = self.settings; - self.drafter - .as_mut() - .ok_or(Error::ContextPoisoned)? - .draft_public( - ring, - prior, - window, - selection, - accepted_row, - &settings, - min_probability, - policy, - coupled, - drafts, - probabilities, - ) - } - - /// Public array form of `draft_first`. - #[allow(clippy::too_many_arguments)] - pub fn draft_first( - &mut self, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - window: OriginalVerifyWindow<'ctx>, - selection: NativeHeadSelection, - rows: usize, - min_probability: f32, - policy: &OriginalMtpFullPolicy, - drafts: &mut [i32], - probabilities: Option<&mut [f32]>, - ) -> Result> { - let staged = self.staged_coupled(); - let coupled = staged.as_ref().map(|(p, h)| (*p, &**h)); - let settings = self.settings; - self.drafter - .as_mut() - .ok_or(Error::ContextPoisoned)? - .draft_first_public( - ring, - prior, - window, - selection, - rows, - &settings, - min_probability, - policy, - coupled, - drafts, - probabilities, - ) - } - - /// `~MtpDrafter()`: stream drain, graphs and owners via the drafter's - /// closure order, then the retained weights (dropped last). - pub fn close(mut self) -> Result<()> { - self.close_inner() - } - pub(super) fn close_inner(&mut self) -> Result<()> { - self.coupled.close(); - self.drafter - .take() - .map_or(Ok(()), OriginalMtpDrafter::close) - } -} +#[path = "impl_originalmtpactor/impl_originalmtpactor_2.rs"] +mod impl_originalmtpactor_2; +#[path = "impl_originalmtpactor/impl_originalmtpactor_2_2.rs"] +mod impl_originalmtpactor_2_2; diff --git a/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor/impl_originalmtpactor_2.rs b/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor/impl_originalmtpactor_2.rs new file mode 100644 index 00000000..a4a0095f --- /dev/null +++ b/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor/impl_originalmtpactor_2.rs @@ -0,0 +1,257 @@ +//! Moved out of the parent module by STRA-338: impl OriginalMtpActor. + +#[allow(unused_imports)] +use super::*; + + + +impl<'ctx> OriginalMtpActor<'ctx> { + /// End of `MtpDrafter::load` + `bind`: take ownership of the assembled + /// drafter and verify, against the owners themselves, every fact the plan + /// and the evidence claim. `ring` is only inspected (it stays with the + /// draft session). On refusal the drafter is closed before returning. + pub fn adopt( + context: &'ctx Context<'ctx>, + plan: OriginalMtpLoadPlan, + drafter: OriginalMtpDrafter<'ctx>, + ring: &MtpOriginalInt8<'ctx>, + weights: Rc>, + evidence: OriginalMtpLoadEvidence, + ) -> std::result::Result { + let mut drafter = drafter; + match Self::admit(context, &plan, &mut drafter, ring, &weights, evidence) { + Ok((kv, disposition, coupled)) => Ok(Self { + drafter: Some(drafter), + weights, + context, + settings: DraftSettings::default(), + kv, + coupled: Box::new(coupled), + disposition, + device: evidence.device, + vram: evidence.vram_bytes, + draft_vocabulary: evidence.draft_vocabulary, + plan, + }), + Err(failure) => { + let _ = drafter.close(); + Err(failure) + } + } + } + + pub(in super::super) fn admit( + context: &'ctx Context<'ctx>, + plan: &OriginalMtpLoadPlan, + drafter: &mut OriginalMtpDrafter<'ctx>, + ring: &MtpOriginalInt8<'ctx>, + weights: &OriginalMtpRetainedFullWeights<'ctx>, + evidence: OriginalMtpLoadEvidence, + ) -> std::result::Result<(KvPlan, SetupDisposition, CoupledDraftHost), OriginalMtpLoadFailure> + { + let capture = *plan.capture(); + drafter.validate_context(context).map_err(inconsistent)?; + ring.validate_context(context).map_err(inconsistent)?; + weights.validate_context(context).map_err(inconsistent)?; + if drafter.loaded_max_t().map_err(inconsistent)? as u64 != capture.max_t { + return Err(mismatch("max_t differs from the loaded drafter")); + } + // `cudaGetDevice` at load: capture, context and ledger must agree. + if context.device_ordinal() != capture.device || evidence.device != capture.device { + return Err(mismatch( + "the drafter's device differs from the captured one", + )); + } + if weights.id_vocabulary() as u64 != capture.vocabulary { + return Err(mismatch("the draft vocabulary differs from output.weight")); + } + // Both directions: a bound subset must be the loaded draft head and + // the loaded draft head must be the bound subset. + if weights.subset_rows() != evidence.draft_vocabulary { + return Err(mismatch("the draft head differs from the retained weights")); + } + // The retained state's ACTUAL mode, not a configured one: window ring + // as planned, or the Original fully-resident retry. + let kv = plan + .admit_ring(ring.fully_resident().map_err(inconsistent)?) + .map_err(|e| OriginalMtpLoadFailure::new(e.message(), None))?; + + // coupled setup: preference -> plan -> literal disposition -> layout + let subset = weights.subset_rows(); + let mut preference = CoupledPreference::from_observed_env(None); + preference.set(capture.coupled_requested); + let disposition = setup_disposition(&preference, capture.vocabulary as usize, subset); + let planned = plan + .coupled(subset.map(|n| n as u64)) + .map_err(|e| OriginalMtpLoadFailure::new(e.message(), None))?; + let expected = match planned { + CoupledPlan::Off => SetupDisposition::Disabled, + CoupledPlan::ArgmaxVocabularyTooWide => SetupDisposition::ArgmaxFallback, + CoupledPlan::Allocate { .. } => SetupDisposition::NeedsActualDeviceSetup, + }; + let layout_coupled = drafter.loaded_coupled().map_err(inconsistent)?; + if disposition != expected + || layout_coupled != (disposition == SetupDisposition::NeedsActualDeviceSetup) + { + return Err(mismatch( + "the coupled resources do not match the setup plan", + )); + } + let mut host = CoupledDraftHost::unselected(); + if disposition == SetupDisposition::NeedsActualDeviceSetup { + // setup_coupled ends with cudaDeviceSynchronize before coupled_ok. + context.synchronize().map_err(|e| { + OriginalMtpLoadFailure::new( + "mtp: coupled setup: device synchronize failed", + Some(e), + ) + })?; + let receipt = CoupledSetupReceipt::after_setup(disposition, layout_coupled, true) + .ok_or_else(|| mismatch("the coupled setup receipt was not issued"))?; + host.arm(receipt); + } + Ok((kv, disposition, host)) + } + + /// `device()`. + pub fn device(&self) -> i32 { + self.device + } + /// `vram_bytes()`: the context ledger across load and bind. + pub fn vram_bytes(&self) -> u64 { + self.vram + } + /// The admitted draft-state plan (window ring, or the resident retry). + pub fn kv_plan(&self) -> &KvPlan { + &self.kv + } + pub fn load_plan(&self) -> &OriginalMtpLoadPlan { + &self.plan + } + pub fn draft_vocabulary(&self) -> Option { + self.draft_vocabulary + } + pub fn max_t(&self) -> u64 { + self.plan.capture().max_t + } + pub fn settings(&self) -> &DraftSettings { + &self.settings + } + pub fn set_prompt_len(&mut self, n: i64) { + self.settings.set_prompt_len(n); + } + pub fn set_max_drafts(&mut self, k: i32) { + self.settings.set_max_drafts(k); + } + /// `first_needed()` over the ADMITTED effective window. + pub fn first_needed(&self) -> std::result::Result { + self.settings.first_needed(self.kv.effective_window as i64) + } + pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { + if !std::ptr::eq(c, self.context) { + return Err(Error::ContextMismatch); + } + self.weights.validate_context(c)?; + self.drafter + .as_ref() + .ok_or(Error::ContextPoisoned)? + .validate_context(c) + } + pub fn is_failed(&self) -> bool { + self.drafter + .as_ref() + .is_none_or(OriginalMtpDrafter::is_failed) + } + /// stderr line of `load`, for the operator log. + pub fn load_report(&self) -> String { + let bank = self.plan.weight_bank(); + let mib = |n: u64| n as f64 / 1_048_576.0; + let mut line = format!( + "strata mtp: draft layer loaded, {:.0} MiB of VRAM (experts {:.0}, dense {:.0})", + mib(self.vram), + mib(bank.expert_device_bytes), + mib(bank.dense_file_bytes) + ); + if let Some(n) = self.draft_vocabulary { + line.push_str(&format!("; draft head over {n} tokens")); + } + match self.disposition { + SetupDisposition::NeedsActualDeviceSetup => { + line.push_str("; coupled draft sampling on") + } + SetupDisposition::ArgmaxFallback => { + line.push_str("; coupled sampler too wide, argmax drafts") + } + SetupDisposition::Disabled => {} + } + line + } + + /// `idle()`: synchronize the capture stream (`cs_`) and nothing else. + pub fn idle(&mut self) -> Result<()> { + self.drafter + .as_mut() + .ok_or(Error::ContextPoisoned)? + .idle_public() + } + + /// Scalar draft K/V prefill on the actor's own scalar owner (short prompts; see `OriginalMtpDrafter::record_scalar_prefill`). + #[allow(clippy::too_many_arguments)] + pub fn record_scalar_prefill<'arena, 'loan>( + &mut self, + residual: &mut crate::OriginalDeviceResidual<'arena, 'loan, 'ctx>, + workspace: &mut crate::NativeBatchWorkspace<'ctx>, + ring: &mut MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + tokens: &[i32], + cell0: usize, + first_needed: usize, + retained: Rc>, + policy: &crate::OriginalMtpScalarPolicy, + cancelled: impl FnMut() -> bool, + ) -> Result { + self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.record_scalar_prefill( + residual, workspace, ring, prior, tokens, cell0, first_needed, retained, policy, cancelled, + ) + } + + /// Release everything the drafter bound to the verifier bank of the request that just ended (see + /// `OriginalMtpDrafter::release_verifier_bindings`). Call it before the verifier is closed. + pub fn release_verifier_bindings(&mut self) -> Result<()> { + self.drafter + .as_mut() + .ok_or(Error::ContextPoisoned)? + .release_verifier_bindings() + } + + /// `kv_restore(upto)`: refill the draft ring's window for a sequence that + /// continues at `upto` from the host pages `prior` authenticates. A no-op + /// when the ring is fully resident, exactly as in Original. + pub fn kv_restore( + &mut self, + ring: &mut MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + upto: i64, + ) -> Result<()> { + self.drafter + .as_mut() + .ok_or(Error::ContextPoisoned)? + .resume_public_kv(ring, prior, upto) + } + + /// `coupled()`. + pub fn coupled(&self) -> bool { + self.coupled.is_active() + } + /// `set_draft_sampling`: a no-op unless coupled setup succeeded. + pub fn set_draft_sampling(&mut self, params: &SamplerParams) { + self.coupled.set_draft_sampling(params); + } + /// `set_draft_history`: `tail` is what the session holds after the commit, + /// `next` the window's pick at the last accepted row. + pub fn set_draft_history(&mut self, tail: &[i32], next: i32) -> Result<()> { + self.coupled + .set_draft_history(tail, next) + .map_err(|_| Error::InvalidQwenShape) + } +} diff --git a/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor/impl_originalmtpactor_2_2.rs b/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor/impl_originalmtpactor_2_2.rs new file mode 100644 index 00000000..a7b63789 --- /dev/null +++ b/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor/impl_originalmtpactor_2_2.rs @@ -0,0 +1,200 @@ +//! Moved out of the parent module by STRA-338: impl OriginalMtpActor (2). + +#[allow(unused_imports)] +use super::*; + + + +impl<'ctx> OriginalMtpActor<'ctx> { + + pub(in super::super) fn staged_coupled(&self) -> Option<(SamplerParams, Box<[i32; 4096]>)> { + self.coupled + .staged_host_values() + .map(|(p, h)| (*p, Box::new(*h))) + } + + /// `draft(T, tokens, p, a, drafts, ...)` over a completed verifier window. + /// `max_drafts` and the coupled request come from this actor's settings. + #[allow(clippy::too_many_arguments)] + pub fn draft_from_verifier( + &mut self, + ring: &mut MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + window: OriginalVerifyWindow<'ctx>, + selection: NativeHeadSelection, + accepted_row: usize, + min_probability: f32, + policy: &OriginalMtpFullPolicy, + ) -> Result> { + let staged = self.staged_coupled(); + let coupled = staged.as_ref().map(|(p, h)| (*p, &**h)); + let max_drafts = self.settings.max_drafts(); + self.drafter + .as_mut() + .ok_or(Error::ContextPoisoned)? + .draft_from_verifier( + ring, + prior, + window, + selection, + accepted_row, + max_drafts, + min_probability, + policy, + coupled, + ) + } + + /// `draft_from_verifier` split around the host's work (`OriginalMtpDrafter::launch_from_verifier`); `after` is the + /// verifier's pending commit event. + #[allow(clippy::too_many_arguments)] + pub fn launch_draft_from_verifier( + &mut self, + ring: &mut MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + window: OriginalVerifyWindow<'ctx>, + selection: NativeHeadSelection, + accepted_row: usize, + min_probability: f32, + policy: &OriginalMtpFullPolicy, + after: Option<&mut crate::OriginalGpuEvent<'ctx>>, + ) -> Result<()> { + let staged = self.staged_coupled(); + let coupled = staged.as_ref().map(|(p, h)| (*p, &**h)); + let max_drafts = self.settings.max_drafts(); + self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.launch_from_verifier( + ring, + prior, + window, + selection, + accepted_row, + max_drafts, + min_probability, + policy, + coupled, + after, + ) + } + /// The read-back half of `launch_draft_from_verifier`. + pub fn finish_draft_from_verifier( + &mut self, + ring: &mut MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + policy: &OriginalMtpFullPolicy, + ) -> Result> { + self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.finish_from_verifier(ring, prior, policy) + } + + /// `draft_first(T, R_row, token, cell, ...)`: the Original repeat-row path. + #[allow(clippy::too_many_arguments)] + pub fn draft_first_from_verifier( + &mut self, + ring: &mut MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + window: OriginalVerifyWindow<'ctx>, + selection: NativeHeadSelection, + rows: usize, + min_probability: f32, + policy: &OriginalMtpFullPolicy, + ) -> Result> { + let staged = self.staged_coupled(); + let coupled = staged.as_ref().map(|(p, h)| (*p, &**h)); + let max_drafts = self.settings.max_drafts(); + self.drafter + .as_mut() + .ok_or(Error::ContextPoisoned)? + .draft_first_from_verifier( + ring, + prior, + window, + selection, + rows, + max_drafts, + min_probability, + policy, + coupled, + ) + } + + /// Public array form of `draft` (`drafts`/`probs` out-arguments). + #[allow(clippy::too_many_arguments)] + pub fn draft( + &mut self, + ring: &mut MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + window: OriginalVerifyWindow<'ctx>, + selection: NativeHeadSelection, + accepted_row: usize, + min_probability: f32, + policy: &OriginalMtpFullPolicy, + drafts: &mut [i32], + probabilities: Option<&mut [f32]>, + ) -> Result> { + let staged = self.staged_coupled(); + let coupled = staged.as_ref().map(|(p, h)| (*p, &**h)); + let settings = self.settings; + self.drafter + .as_mut() + .ok_or(Error::ContextPoisoned)? + .draft_public( + ring, + prior, + window, + selection, + accepted_row, + &settings, + min_probability, + policy, + coupled, + drafts, + probabilities, + ) + } + + /// Public array form of `draft_first`. + #[allow(clippy::too_many_arguments)] + pub fn draft_first( + &mut self, + ring: &mut MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + window: OriginalVerifyWindow<'ctx>, + selection: NativeHeadSelection, + rows: usize, + min_probability: f32, + policy: &OriginalMtpFullPolicy, + drafts: &mut [i32], + probabilities: Option<&mut [f32]>, + ) -> Result> { + let staged = self.staged_coupled(); + let coupled = staged.as_ref().map(|(p, h)| (*p, &**h)); + let settings = self.settings; + self.drafter + .as_mut() + .ok_or(Error::ContextPoisoned)? + .draft_first_public( + ring, + prior, + window, + selection, + rows, + &settings, + min_probability, + policy, + coupled, + drafts, + probabilities, + ) + } + + /// `~MtpDrafter()`: stream drain, graphs and owners via the drafter's + /// closure order, then the retained weights (dropped last). + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + pub(in super::super) fn close_inner(&mut self) -> Result<()> { + self.coupled.close(); + self.drafter + .take() + .map_or(Ok(()), OriginalMtpDrafter::close) + } +} diff --git a/crates/cuda-driver/src/original_sampler/impl_originalsampler.rs b/crates/cuda-driver/src/original_sampler/impl_originalsampler.rs index 0237720c..43adc32d 100644 --- a/crates/cuda-driver/src/original_sampler/impl_originalsampler.rs +++ b/crates/cuda-driver/src/original_sampler/impl_originalsampler.rs @@ -3,676 +3,7 @@ #[allow(unused_imports)] use super::*; -impl<'ctx> OriginalSampler<'ctx> { - pub(super) fn new( - context: &'ctx Context<'ctx>, - rows: usize, - vocab: usize, - history: usize, - ) -> Result { - if !(1..=64).contains(&rows) || !(1..=262144).contains(&vocab) || history > HIST { - return Err(Error::InvalidQwenShape); - } - let ptx = asset().ok_or(Error::UnsupportedQwenOperation)?; - let sizes = [ - 0, - rows * history.max(1) * 4, - rows * 4, - 64, - (HIST + DRAFTS) * 4, - 4, - 4, - vocab * 4, - vocab * 4, - ]; - let charge = sizes - .iter() - .try_fold(0usize, |a, b| a.checked_add(*b)) - .ok_or(Error::InvalidSize)?; - let required = charge.checked_add(RESERVE).ok_or(Error::InvalidSize)?; - if context - .allocated_bytes() - .checked_add(required) - .is_none_or(|n| n > context.budget) - || context.memory_info()?.0 < required - { - return Err(Error::BudgetExceeded); - } - let mut owner = Self { - context, - module: None, - mapped: None, - buffers: std::array::from_fn(|_| None), - rows, - vocab, - history, - subset: None, - next_draft: None, - failed: false, - scratch_entries: 0, - scratch_failed: 0, - retired: Vec::new(), - }; - let operation = (|| { - for (slot, bytes) in owner.buffers.iter_mut().zip(sizes) { - if bytes > 0 { - *slot = Some(context.allocate(bytes)?); - } - } - let guard = context.enter()?; - let load: Result<()> = (|| { - owner.module = Some(KernelModule::load(ptx, ENTRIES)?); - owner.mapped = Some(MappedAllocation::new()?); - Ok(()) - })(); - let pop = guard.finish(); - if load.is_err() || pop.is_err() { - context.poisoned.set(true); - } - combine(load, pop)?; - if context.memory_info()?.0 < RESERVE { - return Err(Error::BudgetExceeded); - } - Ok(()) - })(); - if let Err(primary) = operation { - return combine(Err(primary), owner.close()); - } - Ok(owner) - } - pub fn allocated_bytes(&self) -> usize { - self.buffers - .iter() - .flatten() - .chain(self.retired.iter()) - .map(DeviceBuffer::len) - .sum() - } - pub fn host_bytes(&self) -> usize { - self.mapped.as_ref().map_or(0, MappedAllocation::bytes) - } - pub fn is_failed(&self) -> bool { - self.failed || self.context.is_poisoned() - } - pub fn validate_context(&self, context: &Context<'_>) -> Result<()> { - if !std::ptr::eq(context, self.context) { - return Err(Error::ContextMismatch); - } - if self.is_failed() || self.module.is_none() || self.mapped.is_none() { - return Err(Error::ContextPoisoned); - } - Ok(()) - } - pub(super) fn buffer(&self, i: usize) -> Result<&DeviceBuffer<'ctx>> { - self.buffers - .get(i) - .and_then(Option::as_ref) - .ok_or(Error::ContextPoisoned) - } - pub(super) fn address(&self, i: usize) -> Result { - Ok(self - .buffer(i)? - .handle - .ok_or(Error::ContextPoisoned)? - .qwen_address()) - } - pub(super) fn admit(&self, buffer: &DeviceBuffer<'_>, bytes: usize) -> Result<()> { - self.validate_context(self.context)?; - if !std::ptr::eq(buffer.context, self.context) { - return Err(Error::ContextMismatch); - } - if buffer.bytes != bytes { - return Err(Error::ShapeMismatch { - expected: bytes, - actual: buffer.bytes, - }); - } - let h = buffer.handle.ok_or(Error::ContextPoisoned)?; - h.validate_projection_extent(bytes, 4)?; - for b in self.buffers.iter().flatten().chain(self.retired.iter()) { - let o = b.handle.ok_or(Error::ContextPoisoned)?; - if h.overlaps(bytes, o, b.bytes) { - return Err(Error::OutputAliasesInput); - } - } - Ok(()) - } - // Original per-stream scratch growth, doubling/retirement/failure memory. - // This exclusive actor owner is the stream slot; previously handed addresses - // remain owned until teardown, even though each public call already drains. - pub(super) fn split_scratch(&mut self, entries: usize) -> Result { - const CAP: usize = 64 * 64 * 64; - if entries == 0 || entries > CAP { - return Err(Error::InvalidQwenShape); - } - if self.scratch_entries >= entries { - return Ok(true); - } - if self.scratch_failed != 0 && entries >= self.scratch_failed { - return Ok(false); - } - self.retired - .try_reserve(1) - .map_err(|_| Error::HostAllocation)?; - let want = (self.scratch_entries * 2).min(CAP).max(entries); - for n in [want, entries] { - let bytes = n * 8; - let required = bytes + RESERVE; - if self - .context - .allocated_bytes() - .checked_add(required) - .is_none_or(|v| v > self.context.budget) - || self.context.memory_info()?.0 < required - { - continue; - } - match self.context.allocate(bytes) { - Ok(buffer) => { - if let Some(old) = self.buffers[0].replace(buffer) { - self.retired.push(old); - } - self.scratch_entries = n; - return Ok(true); - } - Err(Error::BudgetExceeded) - | Err(Error::Driver { - operation: "cuMemAlloc_v2", - code: 2, - }) => {} - Err(error) => { - self.failed = true; - return Err(error); - } - } - } - self.scratch_failed = entries; - Ok(false) - } - pub(super) fn upload(&mut self, i: usize, bytes: &[u8]) -> Result<()> { - let r = self.buffers[i] - .as_mut() - .ok_or(Error::ContextPoisoned)? - .copy_from(bytes); - if r.is_err() { - self.failed = true; - } - r - } - pub(super) fn run( - &mut self, - commands: &mut [Launch], - read_ids: bool, - prob: bool, - ) -> Result<(Vec, [u8; 4])> { - self.validate_context(self.context)?; - let mut ids = Vec::new(); - if read_ids { - ids.try_reserve_exact(self.rows * 4) - .map_err(|_| Error::HostAllocation)?; - ids.resize(self.rows * 4, 0); - } - let mut probability = Vec::new(); - if prob { - probability - .try_reserve_exact(4) - .map_err(|_| Error::HostAllocation)?; - probability.resize(4, 0); - } - let guard = self.context.enter()?; - let mut operation = Ok(()); - for command in commands { - if operation.is_ok() { - operation = self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch( - command.entry, - command.grid, - command.block, - command.shared, - &mut command.args, - ); - } - } - if operation.is_ok() && read_ids { - operation = self.context.driver.api.copy_to( - self.buffer(2)?.handle.ok_or(Error::ContextPoisoned)?, - &mut ids, - ); - } - if operation.is_ok() && prob { - operation = self.context.driver.api.copy_to( - self.buffer(5)?.handle.ok_or(Error::ContextPoisoned)?, - &mut probability, - ); - } - let sync = self.context.driver.api.synchronize(); - let pop = guard.finish(); - if operation.is_err() || sync.is_err() || pop.is_err() { - self.failed = true; - self.context.poisoned.set(true); - } - if sync.is_err() || pop.is_err() { - std::mem::forget((ids, probability)); - return combine(combine(operation, sync), pop).map(|()| (Vec::new(), [0; 4])); - } - combine(combine(operation, sync), pop)?; - Ok(( - ids, - if prob { - probability.try_into().expect("four bytes") - } else { - [0; 4] - }, - )) - } - /// One actual verify window. Histories are actual row-specific IDs from the - /// caller's consumed tail/window, not a capability or inferred accepted prefix. - pub fn sample( - &mut self, - logits: &DeviceBuffer<'_>, - rows: usize, - histories: &[i32], - params: SamplerParams, - path: SamplerPath, - captured: bool, - ) -> Result> { - params.validate()?; - if rows == 0 - || rows > self.rows - || histories.len() != rows * self.history - || params.counter.checked_add(rows as u64 - 1).is_none() - { - return Err(Error::InvalidQwenShape); - } - if params.penalty_last_n > 0 && self.history == 0 { - return Err(Error::InvalidQwenShape); - } - self.admit(logits, rows * self.vocab * 4)?; - let split = path == SamplerPath::Split - && !captured - && !params.greedy - && params.temperature > 0.0 - && self.split_scratch(rows.max(16) * self.vocab.div_ceil(4096) * 64)?; - let mut h = Vec::new(); - h.try_reserve_exact(self.rows * self.history.max(1) * 4) - .map_err(|_| Error::HostAllocation)?; - for id in histories { - h.extend_from_slice(&id.to_le_bytes()); - } - h.resize(self.rows * self.history.max(1) * 4, 0xff); - self.upload(1, &h)?; - let source = logits.handle.ok_or(Error::ContextPoisoned)?.qwen_address(); - let history = if self.history > 0 { - Arg::Address(self.address(1)?) - } else { - Arg::NullAddress - }; - let output = self.address(2)?; - let nv = self.vocab as i32; - let nt = rows as i32; - let shared = if params.penalty_last_n > 0 { - self.vocab.div_ceil(32) as u32 * 4 - } else { - 0 - }; - let mut commands = Vec::new(); - commands - .try_reserve_exact(2) - .map_err(|_| Error::HostAllocation)?; - if params.greedy || params.temperature <= 0.0 { - commands.push(Launch::new( - 0, - [rows as u32, 1], - 1024, - shared, - vec![ - Arg::Address(source), - Arg::I32(nv), - history, - Arg::I32(self.history as i32), - Arg::Params(params), - Arg::I32(params.penalty_last_n), - Arg::I32(params.penalty_last_n), - Arg::Address(output), - ], - )); - } else if path == SamplerPath::Old { - commands.push(Launch::new( - 1, - [rows as u32, 1], - 1024, - shared, - vec![ - Arg::Address(source), - Arg::I32(nv), - Arg::I32(nt), - history, - Arg::I32(self.history as i32), - Arg::Params(params), - Arg::Address(output), - ], - )); - } else if split { - let k = (if params.top_k > 0 && params.top_k < 64 { - params.top_k - } else { - 64 - }) - .min(nv); - let blocks = self.vocab.div_ceil(4096) as i32; - commands.push(Launch::new( - 3, - [blocks as u32, rows as u32], - 128, - 0, - vec![ - Arg::Address(source), - Arg::I32(nv), - history, - Arg::I32(self.history as i32), - Arg::Params(params), - Arg::I32(k), - Arg::I32(blocks), - Arg::Address(self.address(0)?), - ], - )); - commands.push(Launch::new( - 4, - [rows as u32, 1], - 32, - 0, - vec![ - Arg::Address(self.address(0)?), - Arg::I32(blocks), - Arg::I32(nv), - Arg::Params(params), - Arg::I32(k), - Arg::Address(output), - ], - )); - } else { - commands.push(Launch::new( - 2, - [rows as u32, 1], - 1024, - shared, - vec![ - Arg::Address(source), - Arg::I32(nv), - history, - Arg::I32(self.history as i32), - Arg::Params(params), - Arg::Address(output), - ], - )); - } - let result = self.run(&mut commands, true, false); - if self.context.is_poisoned() { - std::mem::forget(commands); - } - let (bytes, _) = result?; - let mut ids = Vec::new(); - ids.try_reserve_exact(rows) - .map_err(|_| Error::HostAllocation)?; - for b in bytes[..rows * 4].chunks_exact(4) { - let id = i32::from_le_bytes(b.try_into().expect("word")); - if id < 0 || id >= nv { - self.failed = true; - return Err(Error::InvalidDriverValue("Original sampler token")); - } - ids.push(id); - } - Ok(ids.into_boxed_slice()) - } - /// Install the actual draft-head vocabulary once. Empty means whole vocabulary. - /// Literal `MtpDrafter::setup_coupled`: `sub_to_id` is the draft head's raw `dvocab_` array - /// (every entry as stored); `id_to_sub` maps a token id to its FIRST subset index, ignoring - /// entries outside `[0, n_vocab)` and later duplicates - neither is an error in the Original. - pub fn set_subset(&mut self, subset: &[i32]) -> Result<()> { - self.validate_context(self.context)?; - if self.next_draft.is_some() || subset.len() > self.vocab { - return Err(Error::InvalidQwenShape); - } - let mut forward = Vec::new(); - forward - .try_reserve_exact(self.vocab) - .map_err(|_| Error::HostAllocation)?; - forward.resize(self.vocab, -1i32); - forward[..subset.len()].copy_from_slice(subset); - let inverse = crate::original_mtp_coupled::subset_inverse(self.vocab, subset) - .map_err(|_| Error::InvalidQwenShape)?; - for (slot, values) in [(7, forward), (8, inverse)] { - let mut bytes = Vec::new(); - bytes - .try_reserve_exact(self.vocab * 4) - .map_err(|_| Error::HostAllocation)?; - for v in values { - bytes.extend_from_slice(&v.to_le_bytes()); - } - self.upload(slot, &bytes)?; - } - self.subset = (!subset.is_empty()).then_some(subset.len()); - Ok(()) - } - /// Actual mapped parameter/history staging, original coupled_stage kernel. - /// `base` is the full 4096-slot authentic caller history, -1 padded in front. - pub fn stage_coupled_round(&mut self, params: SamplerParams, base: &[i32; HIST]) -> Result<()> { - self.validate_context(self.context)?; - params.validate()?; - let mut bytes = Vec::new(); - bytes - .try_reserve_exact(HIST * 4) - .map_err(|_| Error::HostAllocation)?; - for v in base { - bytes.extend_from_slice(&v.to_le_bytes()); - } - let guard = self.context.enter()?; - let mapped = self.mapped.as_mut().ok_or(Error::ContextPoisoned)?; - let operation = (|| { - mapped.write(0, ¶ms.bytes())?; - mapped.write(64, &bytes)?; - Ok(()) - })(); - let pop = guard.finish(); - if operation.is_err() || pop.is_err() { - self.failed = true; - self.context.poisoned.set(true); - } - combine(operation, pop)?; - let mapped = self.mapped.as_ref().ok_or(Error::ContextPoisoned)?; - let mut commands = [Launch::new( - 5, - [1, 1], - 256, - 0, - vec![ - Arg::Address(mapped.address(0, 64)?), - Arg::Address(mapped.address(64, HIST * 4)?), - Arg::Address(self.address(3)?), - Arg::Address(self.address(4)?), - Arg::I32(HIST as i32), - ], - )]; - let result = self.run(&mut commands, false, false); - if self.context.is_poisoned() { - std::mem::forget(commands); - } - result?; - self.next_draft = Some(0); - Ok(()) - } - /// Actual single draft logits, genuine caller's cell, successive j in one round. - /// Literal penalties -> widest split -> coupled merge writes the real ring. - pub fn sample_coupled( - &mut self, - logits: &mut DeviceBuffer<'_>, - cell: i32, - j: usize, - ) -> Result<(i32, f32)> { - // cell -1 is `draft_first` for a window at p = 0 (counter 0); see coupled_draft_counter. - if cell < -1 || j >= DRAFTS || self.next_draft != Some(j) { - return Err(Error::InvalidQwenShape); - } - let nv = self.subset.unwrap_or(self.vocab); - self.admit(logits, nv * 4)?; - if !self.split_scratch(nv.div_ceil(4096) * 64)? { - return Err(Error::BudgetExceeded); - } - self.upload(6, &cell.to_le_bytes())?; - let blocks = nv.div_ceil(4096) as i32; - let kpart = nv.min(64) as i32; - let sub = if self.subset.is_some() { - Arg::Address(self.address(7)?) - } else { - Arg::NullAddress - }; - let inverse = if self.subset.is_some() { - Arg::Address(self.address(8)?) - } else { - Arg::NullAddress - }; - let l = logits.handle.ok_or(Error::ContextPoisoned)?.qwen_address(); - let mut commands = [ - Launch::new( - 6, - [1, 1], - 1024, - nv.div_ceil(32) as u32 * 4, - vec![ - Arg::Address(l), - Arg::I32(nv as i32), - inverse, - Arg::I32(self.vocab as i32), - Arg::Address(self.address(3)?), - Arg::Address(self.address(4)?), - Arg::I32(HIST as i32), - Arg::I32(j as i32), - ], - ), - Launch::new( - 3, - [blocks as u32, 1], - 128, - 0, - vec![ - Arg::Address(l), - Arg::I32(nv as i32), - Arg::NullAddress, - Arg::I32(0), - Arg::Params(SamplerParams::default()), - Arg::I32(kpart), - Arg::I32(blocks), - Arg::Address(self.address(0)?), - ], - ), - Launch::new( - 7, - [1, 1], - 32, - 0, - vec![ - Arg::Address(self.address(0)?), - Arg::I32(blocks), - Arg::I32(nv as i32), - Arg::I32(kpart), - Arg::Address(self.address(3)?), - Arg::Address(self.address(6)?), - sub, - Arg::Address(self.address(4)?), - Arg::I32(HIST as i32), - Arg::I32(j as i32), - Arg::Address(self.address(2)?), - Arg::Address(self.address(5)?), - ], - ), - ]; - let result = self.run(&mut commands, true, true); - if self.context.is_poisoned() { - std::mem::forget(commands); - } - let (ids, p) = result?; - let id = i32::from_le_bytes(ids[..4].try_into().expect("word")); - let probability = f32::from_le_bytes(p); - if id < 0 - || id as usize >= self.vocab - || !probability.is_finite() - || !(0.0..=1.0).contains(&probability) - { - self.failed = true; - return Err(Error::InvalidDriverValue("Original coupled pick")); - } - self.next_draft = Some(j + 1); - Ok((id, probability)) - } - pub fn finish_coupled_round(&mut self) { - self.next_draft = None; - } - pub fn close(mut self) -> Result<()> { - self.close_inner() - } - pub(super) fn close_inner(&mut self) -> Result<()> { - if self.module.is_none() - && self.mapped.is_none() - && self.buffers.iter().all(Option::is_none) - && self.retired.is_empty() - { - return Ok(()); - } - self.failed = true; - self.next_draft = None; - let mut result = Ok(()); - for buffer in self.retired.drain(..) { - let r = if self.context.is_poisoned() { - std::mem::forget(buffer); - Err(Error::ContextPoisoned) - } else { - buffer.release() - }; - if r.is_err() { - self.context.poisoned.set(true); - } - result = combine(result, r); - } - for slot in &mut self.buffers { - if let Some(buffer) = slot.take() { - let r = if self.context.is_poisoned() { - std::mem::forget(buffer); - Err(Error::ContextPoisoned) - } else { - buffer.release() - }; - if r.is_err() { - self.context.poisoned.set(true); - } - result = combine(result, r); - } - } - if self.context.is_poisoned() { - if let Some(module) = self.module.take() { - std::mem::forget(module); - } - if let Some(mapped) = self.mapped.take() { - std::mem::forget(mapped); - } - return combine(result, Err(Error::ContextPoisoned)); - } - let guard = match self.context.enter() { - Ok(g) => g, - Err(e) => { - if let Some(m) = self.module.take() { - std::mem::forget(m); - } - if let Some(m) = self.mapped.take() { - std::mem::forget(m); - } - return combine(result, Err(e)); - } - }; - let module = self.module.take().map_or(Ok(()), KernelModule::close); - let mapped = self.mapped.take().map_or(Ok(()), |mut m| m.close()); - let pop = guard.finish(); - if module.is_err() || mapped.is_err() || pop.is_err() { - self.context.poisoned.set(true); - } - combine(combine(combine(result, module), mapped), pop) - } -} +mod impl_originalsampler_2; +mod impl_originalsampler_2_2; +mod impl_originalsampler_3; +mod impl_originalsampler_4; diff --git a/crates/cuda-driver/src/original_sampler/impl_originalsampler/impl_originalsampler_2.rs b/crates/cuda-driver/src/original_sampler/impl_originalsampler/impl_originalsampler_2.rs new file mode 100644 index 00000000..76855b4c --- /dev/null +++ b/crates/cuda-driver/src/original_sampler/impl_originalsampler/impl_originalsampler_2.rs @@ -0,0 +1,203 @@ +//! Moved out of the parent module by STRA-338: impl OriginalSampler. + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalSampler<'ctx> { + pub(in super::super) fn new( + context: &'ctx Context<'ctx>, + rows: usize, + vocab: usize, + history: usize, + ) -> Result { + if !(1..=64).contains(&rows) || !(1..=262144).contains(&vocab) || history > HIST { + return Err(Error::InvalidQwenShape); + } + let ptx = asset().ok_or(Error::UnsupportedQwenOperation)?; + let sizes = [ + 0, + rows * history.max(1) * 4, + rows * 4, + 64, + (HIST + DRAFTS) * 4, + 4, + 4, + vocab * 4, + vocab * 4, + ]; + let charge = sizes + .iter() + .try_fold(0usize, |a, b| a.checked_add(*b)) + .ok_or(Error::InvalidSize)?; + let required = charge.checked_add(RESERVE).ok_or(Error::InvalidSize)?; + if context + .allocated_bytes() + .checked_add(required) + .is_none_or(|n| n > context.budget) + || context.memory_info()?.0 < required + { + return Err(Error::BudgetExceeded); + } + let mut owner = Self { + context, + module: None, + mapped: None, + buffers: std::array::from_fn(|_| None), + rows, + vocab, + history, + subset: None, + next_draft: None, + failed: false, + scratch_entries: 0, + scratch_failed: 0, + retired: Vec::new(), + }; + let operation = (|| { + for (slot, bytes) in owner.buffers.iter_mut().zip(sizes) { + if bytes > 0 { + *slot = Some(context.allocate(bytes)?); + } + } + let guard = context.enter()?; + let load: Result<()> = (|| { + owner.module = Some(KernelModule::load(ptx, ENTRIES)?); + owner.mapped = Some(MappedAllocation::new()?); + Ok(()) + })(); + let pop = guard.finish(); + if load.is_err() || pop.is_err() { + context.poisoned.set(true); + } + combine(load, pop)?; + if context.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + Ok(()) + })(); + if let Err(primary) = operation { + return combine(Err(primary), owner.close()); + } + Ok(owner) + } + pub fn allocated_bytes(&self) -> usize { + self.buffers + .iter() + .flatten() + .chain(self.retired.iter()) + .map(DeviceBuffer::len) + .sum() + } + pub fn host_bytes(&self) -> usize { + self.mapped.as_ref().map_or(0, MappedAllocation::bytes) + } + pub fn is_failed(&self) -> bool { + self.failed || self.context.is_poisoned() + } + pub fn validate_context(&self, context: &Context<'_>) -> Result<()> { + if !std::ptr::eq(context, self.context) { + return Err(Error::ContextMismatch); + } + if self.is_failed() || self.module.is_none() || self.mapped.is_none() { + return Err(Error::ContextPoisoned); + } + Ok(()) + } + pub(in super::super) fn buffer(&self, i: usize) -> Result<&DeviceBuffer<'ctx>> { + self.buffers + .get(i) + .and_then(Option::as_ref) + .ok_or(Error::ContextPoisoned) + } + pub(in super::super) fn address(&self, i: usize) -> Result { + Ok(self + .buffer(i)? + .handle + .ok_or(Error::ContextPoisoned)? + .qwen_address()) + } + pub(in super::super) fn admit(&self, buffer: &DeviceBuffer<'_>, bytes: usize) -> Result<()> { + self.validate_context(self.context)?; + if !std::ptr::eq(buffer.context, self.context) { + return Err(Error::ContextMismatch); + } + if buffer.bytes != bytes { + return Err(Error::ShapeMismatch { + expected: bytes, + actual: buffer.bytes, + }); + } + let h = buffer.handle.ok_or(Error::ContextPoisoned)?; + h.validate_projection_extent(bytes, 4)?; + for b in self.buffers.iter().flatten().chain(self.retired.iter()) { + let o = b.handle.ok_or(Error::ContextPoisoned)?; + if h.overlaps(bytes, o, b.bytes) { + return Err(Error::OutputAliasesInput); + } + } + Ok(()) + } + // Original per-stream scratch growth, doubling/retirement/failure memory. + // This exclusive actor owner is the stream slot; previously handed addresses + // remain owned until teardown, even though each public call already drains. + pub(in super::super) fn split_scratch(&mut self, entries: usize) -> Result { + const CAP: usize = 64 * 64 * 64; + if entries == 0 || entries > CAP { + return Err(Error::InvalidQwenShape); + } + if self.scratch_entries >= entries { + return Ok(true); + } + if self.scratch_failed != 0 && entries >= self.scratch_failed { + return Ok(false); + } + self.retired + .try_reserve(1) + .map_err(|_| Error::HostAllocation)?; + let want = (self.scratch_entries * 2).min(CAP).max(entries); + for n in [want, entries] { + let bytes = n * 8; + let required = bytes + RESERVE; + if self + .context + .allocated_bytes() + .checked_add(required) + .is_none_or(|v| v > self.context.budget) + || self.context.memory_info()?.0 < required + { + continue; + } + match self.context.allocate(bytes) { + Ok(buffer) => { + if let Some(old) = self.buffers[0].replace(buffer) { + self.retired.push(old); + } + self.scratch_entries = n; + return Ok(true); + } + Err(Error::BudgetExceeded) + | Err(Error::Driver { + operation: "cuMemAlloc_v2", + code: 2, + }) => {} + Err(error) => { + self.failed = true; + return Err(error); + } + } + } + self.scratch_failed = entries; + Ok(false) + } + pub(in super::super) fn upload(&mut self, i: usize, bytes: &[u8]) -> Result<()> { + let r = self.buffers[i] + .as_mut() + .ok_or(Error::ContextPoisoned)? + .copy_from(bytes); + if r.is_err() { + self.failed = true; + } + r + } +} diff --git a/crates/cuda-driver/src/original_sampler/impl_originalsampler/impl_originalsampler_2_2.rs b/crates/cuda-driver/src/original_sampler/impl_originalsampler/impl_originalsampler_2_2.rs new file mode 100644 index 00000000..71c20984 --- /dev/null +++ b/crates/cuda-driver/src/original_sampler/impl_originalsampler/impl_originalsampler_2_2.rs @@ -0,0 +1,232 @@ +//! Moved out of the parent module by STRA-338: impl OriginalSampler (2). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalSampler<'ctx> { + pub(in super::super) fn run( + &mut self, + commands: &mut [Launch], + read_ids: bool, + prob: bool, + ) -> Result<(Vec, [u8; 4])> { + self.validate_context(self.context)?; + let mut ids = Vec::new(); + if read_ids { + ids.try_reserve_exact(self.rows * 4) + .map_err(|_| Error::HostAllocation)?; + ids.resize(self.rows * 4, 0); + } + let mut probability = Vec::new(); + if prob { + probability + .try_reserve_exact(4) + .map_err(|_| Error::HostAllocation)?; + probability.resize(4, 0); + } + let guard = self.context.enter()?; + let mut operation = Ok(()); + for command in commands { + if operation.is_ok() { + operation = self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch( + command.entry, + command.grid, + command.block, + command.shared, + &mut command.args, + ); + } + } + if operation.is_ok() && read_ids { + operation = self.context.driver.api.copy_to( + self.buffer(2)?.handle.ok_or(Error::ContextPoisoned)?, + &mut ids, + ); + } + if operation.is_ok() && prob { + operation = self.context.driver.api.copy_to( + self.buffer(5)?.handle.ok_or(Error::ContextPoisoned)?, + &mut probability, + ); + } + let sync = self.context.driver.api.synchronize(); + let pop = guard.finish(); + if operation.is_err() || sync.is_err() || pop.is_err() { + self.failed = true; + self.context.poisoned.set(true); + } + if sync.is_err() || pop.is_err() { + std::mem::forget((ids, probability)); + return combine(combine(operation, sync), pop).map(|()| (Vec::new(), [0; 4])); + } + combine(combine(operation, sync), pop)?; + Ok(( + ids, + if prob { + probability.try_into().expect("four bytes") + } else { + [0; 4] + }, + )) + } + /// One actual verify window. Histories are actual row-specific IDs from the + /// caller's consumed tail/window, not a capability or inferred accepted prefix. + pub fn sample( + &mut self, + logits: &DeviceBuffer<'_>, + rows: usize, + histories: &[i32], + params: SamplerParams, + path: SamplerPath, + captured: bool, + ) -> Result> { + params.validate()?; + if rows == 0 + || rows > self.rows + || histories.len() != rows * self.history + || params.counter.checked_add(rows as u64 - 1).is_none() + { + return Err(Error::InvalidQwenShape); + } + if params.penalty_last_n > 0 && self.history == 0 { + return Err(Error::InvalidQwenShape); + } + self.admit(logits, rows * self.vocab * 4)?; + let split = path == SamplerPath::Split + && !captured + && !params.greedy + && params.temperature > 0.0 + && self.split_scratch(rows.max(16) * self.vocab.div_ceil(4096) * 64)?; + let mut h = Vec::new(); + h.try_reserve_exact(self.rows * self.history.max(1) * 4) + .map_err(|_| Error::HostAllocation)?; + for id in histories { + h.extend_from_slice(&id.to_le_bytes()); + } + h.resize(self.rows * self.history.max(1) * 4, 0xff); + self.upload(1, &h)?; + let source = logits.handle.ok_or(Error::ContextPoisoned)?.qwen_address(); + let history = if self.history > 0 { + Arg::Address(self.address(1)?) + } else { + Arg::NullAddress + }; + let output = self.address(2)?; + let nv = self.vocab as i32; + let nt = rows as i32; + let shared = if params.penalty_last_n > 0 { + self.vocab.div_ceil(32) as u32 * 4 + } else { + 0 + }; + let mut commands = Vec::new(); + commands + .try_reserve_exact(2) + .map_err(|_| Error::HostAllocation)?; + if params.greedy || params.temperature <= 0.0 { + commands.push(Launch::new( + 0, + [rows as u32, 1], + 1024, + shared, + vec![ + Arg::Address(source), + Arg::I32(nv), + history, + Arg::I32(self.history as i32), + Arg::Params(params), + Arg::I32(params.penalty_last_n), + Arg::I32(params.penalty_last_n), + Arg::Address(output), + ], + )); + } else if path == SamplerPath::Old { + commands.push(Launch::new( + 1, + [rows as u32, 1], + 1024, + shared, + vec![ + Arg::Address(source), + Arg::I32(nv), + Arg::I32(nt), + history, + Arg::I32(self.history as i32), + Arg::Params(params), + Arg::Address(output), + ], + )); + } else if split { + let k = (if params.top_k > 0 && params.top_k < 64 { + params.top_k + } else { + 64 + }) + .min(nv); + let blocks = self.vocab.div_ceil(4096) as i32; + commands.push(Launch::new( + 3, + [blocks as u32, rows as u32], + 128, + 0, + vec![ + Arg::Address(source), + Arg::I32(nv), + history, + Arg::I32(self.history as i32), + Arg::Params(params), + Arg::I32(k), + Arg::I32(blocks), + Arg::Address(self.address(0)?), + ], + )); + commands.push(Launch::new( + 4, + [rows as u32, 1], + 32, + 0, + vec![ + Arg::Address(self.address(0)?), + Arg::I32(blocks), + Arg::I32(nv), + Arg::Params(params), + Arg::I32(k), + Arg::Address(output), + ], + )); + } else { + commands.push(Launch::new( + 2, + [rows as u32, 1], + 1024, + shared, + vec![ + Arg::Address(source), + Arg::I32(nv), + history, + Arg::I32(self.history as i32), + Arg::Params(params), + Arg::Address(output), + ], + )); + } + let result = self.run(&mut commands, true, false); + if self.context.is_poisoned() { + std::mem::forget(commands); + } + let (bytes, _) = result?; + let mut ids = Vec::new(); + ids.try_reserve_exact(rows) + .map_err(|_| Error::HostAllocation)?; + for b in bytes[..rows * 4].chunks_exact(4) { + let id = i32::from_le_bytes(b.try_into().expect("word")); + if id < 0 || id >= nv { + self.failed = true; + return Err(Error::InvalidDriverValue("Original sampler token")); + } + ids.push(id); + } + Ok(ids.into_boxed_slice()) + } +} diff --git a/crates/cuda-driver/src/original_sampler/impl_originalsampler/impl_originalsampler_3.rs b/crates/cuda-driver/src/original_sampler/impl_originalsampler/impl_originalsampler_3.rs new file mode 100644 index 00000000..a25b5422 --- /dev/null +++ b/crates/cuda-driver/src/original_sampler/impl_originalsampler/impl_originalsampler_3.rs @@ -0,0 +1,194 @@ +//! Moved out of the parent module by STRA-338: impl OriginalSampler (3). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalSampler<'ctx> { + /// Install the actual draft-head vocabulary once. Empty means whole vocabulary. + /// Literal `MtpDrafter::setup_coupled`: `sub_to_id` is the draft head's raw `dvocab_` array + /// (every entry as stored); `id_to_sub` maps a token id to its FIRST subset index, ignoring + /// entries outside `[0, n_vocab)` and later duplicates - neither is an error in the Original. + pub fn set_subset(&mut self, subset: &[i32]) -> Result<()> { + self.validate_context(self.context)?; + if self.next_draft.is_some() || subset.len() > self.vocab { + return Err(Error::InvalidQwenShape); + } + let mut forward = Vec::new(); + forward + .try_reserve_exact(self.vocab) + .map_err(|_| Error::HostAllocation)?; + forward.resize(self.vocab, -1i32); + forward[..subset.len()].copy_from_slice(subset); + let inverse = crate::original_mtp_coupled::subset_inverse(self.vocab, subset) + .map_err(|_| Error::InvalidQwenShape)?; + for (slot, values) in [(7, forward), (8, inverse)] { + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(self.vocab * 4) + .map_err(|_| Error::HostAllocation)?; + for v in values { + bytes.extend_from_slice(&v.to_le_bytes()); + } + self.upload(slot, &bytes)?; + } + self.subset = (!subset.is_empty()).then_some(subset.len()); + Ok(()) + } + /// Actual mapped parameter/history staging, original coupled_stage kernel. + /// `base` is the full 4096-slot authentic caller history, -1 padded in front. + pub fn stage_coupled_round(&mut self, params: SamplerParams, base: &[i32; HIST]) -> Result<()> { + self.validate_context(self.context)?; + params.validate()?; + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(HIST * 4) + .map_err(|_| Error::HostAllocation)?; + for v in base { + bytes.extend_from_slice(&v.to_le_bytes()); + } + let guard = self.context.enter()?; + let mapped = self.mapped.as_mut().ok_or(Error::ContextPoisoned)?; + let operation = (|| { + mapped.write(0, ¶ms.bytes())?; + mapped.write(64, &bytes)?; + Ok(()) + })(); + let pop = guard.finish(); + if operation.is_err() || pop.is_err() { + self.failed = true; + self.context.poisoned.set(true); + } + combine(operation, pop)?; + let mapped = self.mapped.as_ref().ok_or(Error::ContextPoisoned)?; + let mut commands = [Launch::new( + 5, + [1, 1], + 256, + 0, + vec![ + Arg::Address(mapped.address(0, 64)?), + Arg::Address(mapped.address(64, HIST * 4)?), + Arg::Address(self.address(3)?), + Arg::Address(self.address(4)?), + Arg::I32(HIST as i32), + ], + )]; + let result = self.run(&mut commands, false, false); + if self.context.is_poisoned() { + std::mem::forget(commands); + } + result?; + self.next_draft = Some(0); + Ok(()) + } + /// Actual single draft logits, genuine caller's cell, successive j in one round. + /// Literal penalties -> widest split -> coupled merge writes the real ring. + pub fn sample_coupled( + &mut self, + logits: &mut DeviceBuffer<'_>, + cell: i32, + j: usize, + ) -> Result<(i32, f32)> { + // cell -1 is `draft_first` for a window at p = 0 (counter 0); see coupled_draft_counter. + if cell < -1 || j >= DRAFTS || self.next_draft != Some(j) { + return Err(Error::InvalidQwenShape); + } + let nv = self.subset.unwrap_or(self.vocab); + self.admit(logits, nv * 4)?; + if !self.split_scratch(nv.div_ceil(4096) * 64)? { + return Err(Error::BudgetExceeded); + } + self.upload(6, &cell.to_le_bytes())?; + let blocks = nv.div_ceil(4096) as i32; + let kpart = nv.min(64) as i32; + let sub = if self.subset.is_some() { + Arg::Address(self.address(7)?) + } else { + Arg::NullAddress + }; + let inverse = if self.subset.is_some() { + Arg::Address(self.address(8)?) + } else { + Arg::NullAddress + }; + let l = logits.handle.ok_or(Error::ContextPoisoned)?.qwen_address(); + let mut commands = [ + Launch::new( + 6, + [1, 1], + 1024, + nv.div_ceil(32) as u32 * 4, + vec![ + Arg::Address(l), + Arg::I32(nv as i32), + inverse, + Arg::I32(self.vocab as i32), + Arg::Address(self.address(3)?), + Arg::Address(self.address(4)?), + Arg::I32(HIST as i32), + Arg::I32(j as i32), + ], + ), + Launch::new( + 3, + [blocks as u32, 1], + 128, + 0, + vec![ + Arg::Address(l), + Arg::I32(nv as i32), + Arg::NullAddress, + Arg::I32(0), + Arg::Params(SamplerParams::default()), + Arg::I32(kpart), + Arg::I32(blocks), + Arg::Address(self.address(0)?), + ], + ), + Launch::new( + 7, + [1, 1], + 32, + 0, + vec![ + Arg::Address(self.address(0)?), + Arg::I32(blocks), + Arg::I32(nv as i32), + Arg::I32(kpart), + Arg::Address(self.address(3)?), + Arg::Address(self.address(6)?), + sub, + Arg::Address(self.address(4)?), + Arg::I32(HIST as i32), + Arg::I32(j as i32), + Arg::Address(self.address(2)?), + Arg::Address(self.address(5)?), + ], + ), + ]; + let result = self.run(&mut commands, true, true); + if self.context.is_poisoned() { + std::mem::forget(commands); + } + let (ids, p) = result?; + let id = i32::from_le_bytes(ids[..4].try_into().expect("word")); + let probability = f32::from_le_bytes(p); + if id < 0 + || id as usize >= self.vocab + || !probability.is_finite() + || !(0.0..=1.0).contains(&probability) + { + self.failed = true; + return Err(Error::InvalidDriverValue("Original coupled pick")); + } + self.next_draft = Some(j + 1); + Ok((id, probability)) + } + pub fn finish_coupled_round(&mut self) { + self.next_draft = None; + } + pub fn close(mut self) -> Result<()> { + self.close_inner() + } +} diff --git a/crates/cuda-driver/src/original_sampler/impl_originalsampler/impl_originalsampler_4.rs b/crates/cuda-driver/src/original_sampler/impl_originalsampler/impl_originalsampler_4.rs new file mode 100644 index 00000000..5b287656 --- /dev/null +++ b/crates/cuda-driver/src/original_sampler/impl_originalsampler/impl_originalsampler_4.rs @@ -0,0 +1,74 @@ +//! Moved out of the parent module by STRA-338: impl OriginalSampler (4). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalSampler<'ctx> { + pub(in super::super) fn close_inner(&mut self) -> Result<()> { + if self.module.is_none() + && self.mapped.is_none() + && self.buffers.iter().all(Option::is_none) + && self.retired.is_empty() + { + return Ok(()); + } + self.failed = true; + self.next_draft = None; + let mut result = Ok(()); + for buffer in self.retired.drain(..) { + let r = if self.context.is_poisoned() { + std::mem::forget(buffer); + Err(Error::ContextPoisoned) + } else { + buffer.release() + }; + if r.is_err() { + self.context.poisoned.set(true); + } + result = combine(result, r); + } + for slot in &mut self.buffers { + if let Some(buffer) = slot.take() { + let r = if self.context.is_poisoned() { + std::mem::forget(buffer); + Err(Error::ContextPoisoned) + } else { + buffer.release() + }; + if r.is_err() { + self.context.poisoned.set(true); + } + result = combine(result, r); + } + } + if self.context.is_poisoned() { + if let Some(module) = self.module.take() { + std::mem::forget(module); + } + if let Some(mapped) = self.mapped.take() { + std::mem::forget(mapped); + } + return combine(result, Err(Error::ContextPoisoned)); + } + let guard = match self.context.enter() { + Ok(g) => g, + Err(e) => { + if let Some(m) = self.module.take() { + std::mem::forget(m); + } + if let Some(m) = self.mapped.take() { + std::mem::forget(m); + } + return combine(result, Err(e)); + } + }; + let module = self.module.take().map_or(Ok(()), KernelModule::close); + let mapped = self.mapped.take().map_or(Ok(()), |mut m| m.close()); + let pop = guard.finish(); + if module.is_err() || mapped.is_err() || pop.is_err() { + self.context.poisoned.set(true); + } + combine(combine(combine(result, module), mapped), pop) + } +} diff --git a/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue.rs b/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue.rs index 9752e0b3..1c44f8a6 100644 --- a/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue.rs +++ b/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue.rs @@ -3,444 +3,6 @@ #[allow(unused_imports)] use super::*; -impl<'ctx> PleBatchQueue<'ctx> { - pub(super) fn new(context: &'ctx Context<'ctx>, mode: PleBf16Mode) -> Result { - Self::new_capacity(context,mode,64) - } - pub(super) fn new_capacity(context:&'ctx Context<'ctx>,mode:PleBf16Mode,capacity:usize)->Result { - if !(1..=8192).contains(&capacity) {return Err(Error::InvalidQwenShape);} - let mut sizes=SIZES; for (i,size) in sizes.iter_mut().enumerate() {if i!=2 {*size=(*size/64).checked_mul(capacity).ok_or(Error::BudgetExceeded)?;}} - let ptx = assets()?; // explicit pending refusal before any allocation/module. - if context.is_poisoned() || context.handle.is_none() { - return Err(Error::ContextPoisoned); - } - let required = sizes.iter().try_fold(0usize,|sum,n|sum.checked_add(*n).ok_or(Error::BudgetExceeded))? - .checked_add(RESERVE) - .ok_or(Error::BudgetExceeded)?; - if context - .allocated_bytes() - .checked_add(required) - .is_none_or(|n| n > context.budget) - || context.memory_info()?.0 < required - { - return Err(Error::BudgetExceeded); - } - let mut owner = Self { - capacity, sizes, context, - buffers: std::array::from_fn(|_| None), - pack_module: None, - module: None, - mode, - failed: false, - }; - let operation = (|| { - for (i, bytes) in sizes.into_iter().enumerate() { - owner.buffers[i] = Some(context.allocate(bytes)?); - } - let guard = context.enter()?; - let load = (|| { - owner.pack_module = Some(KernelModule::load(ptx[0], &PACK_ENTRIES)?); - owner.module = Some(KernelModule::load(ptx[1], &ENTRIES)?); - Ok(()) - })(); - let pop = guard.finish(); - if pop.is_err() { - context.poisoned.set(true); - } - combine(load, pop)?; - owner.handles()?; - if context.memory_info()?.0 < RESERVE { - return Err(Error::BudgetExceeded); - } - Ok(()) - })(); - if let Err(error) = operation { - return combine(Err(error), owner.close()); - } - Ok(owner) - } - pub fn prompt_device_bytes(capacity:usize)->Result { - if !(1..=8192).contains(&capacity) {return Err(Error::InvalidQwenShape);} - Ok(368640+(PLE_BATCH_QUEUE_BYTES-368640)/64*capacity) - } - pub fn capacity(&self)->usize {self.capacity} - pub fn allocated_bytes(&self) -> usize { - self.buffers.iter().flatten().map(DeviceBuffer::len).sum() - } - pub fn is_failed(&self) -> bool { - self.failed || self.context.is_poisoned() || self.context.handle.is_none() - } - pub fn validate_context(&self, context: &Context<'_>) -> Result<()> { - if !std::ptr::eq(context, self.context) { - return Err(Error::ContextMismatch); - } - self.handles().map(|_| ()) - } - pub(super) fn buffer(&self, i: usize) -> Result<&DeviceBuffer<'ctx>> { - self.buffers[i].as_ref().ok_or(Error::ContextPoisoned) - } - pub(super) fn handles(&self) -> Result<[BufferHandle; 15]> { - if self.is_failed() || self.module.is_none() || self.pack_module.is_none() { - return Err(Error::ContextPoisoned); - } - let first = self.buffer(0)?.handle.ok_or(Error::ContextPoisoned)?; - let mut handles = [first; 15]; - for (i, bytes) in self.sizes.into_iter().enumerate() { - let b = self.buffer(i)?; - if !std::ptr::eq(b.context, self.context) { - return Err(Error::ContextMismatch); - } - if b.bytes != bytes { - return Err(Error::InvalidQwenShape); - } - let h = b.handle.ok_or(Error::ContextPoisoned)?; - h.validate_projection_extent(bytes, 4)?; - for (j, other) in handles.iter().take(i).enumerate() { - if h.overlaps(bytes, *other, self.sizes[j]) { - return Err(Error::OutputAliasesInput); - } - } - handles[i] = h; - } - if self.context.allocated_bytes() > self.context.budget { - return Err(Error::BudgetExceeded); - } - Ok(handles) - } - pub(super) fn weight(&self, w: &DeviceBuffer<'_>, bytes: usize, alignment: u64) -> Result { - if !std::ptr::eq(w.context, self.context) { - return Err(Error::ContextMismatch); - } - if w.bytes != bytes { - return Err(Error::InvalidQwenShape); - } - let h = w.handle.ok_or(Error::ContextPoisoned)?; - h.validate_projection_extent(bytes, alignment)?; - for (owned, count) in self.handles()?.into_iter().zip(self.sizes) { - if h.overlaps(bytes, owned, count) { - return Err(Error::OutputAliasesInput); - } - } - Ok(h) - } - /// Literal original batch profile, explicit hi-only or hi+low; no automatic - /// equivalence to the old F32 MMVF reduction is asserted. Actual binding, - /// row/position/history provenance must be supplied by the runtime caller. - pub fn compose<'loan>( - &'loan mut self, - workspace: &mut NativeBatchWorkspace<'_>, - weights: PleClosedWeights<'_, '_>, - embedding: &[f32], - streams: &[f32], - history: &[f32], - ) -> Result> { - workspace.validate_context(self.context)?; - let h = self.handles()?; - for (handle, bytes) in h.into_iter().zip(self.sizes) { - workspace.reject_alias(handle, bytes)?; - } - if !embedding.len().is_multiple_of(2560) { - return Err(Error::InvalidQwenShape); - } - let rows = embedding.len() / 2560; - if !(1..=self.capacity).contains(&rows) || streams.len() != rows * 10240 || history.len() != 92160 { - return Err(Error::InvalidQwenShape); - } - if embedding - .iter() - .chain(streams) - .chain(history) - .any(|v| !v.is_finite()) - { - return Err(Error::InvalidDriverValue("PLE batch source finite")); - } - let key = self.weight(weights.key, 52428800, 2)?; - let value = self.weight(weights.value, 13107200, 2)?; - let mut aux = [h[0]; 4]; - for (i, w) in weights.aux.iter().enumerate() { - aux[i] = self.weight( - w, - if i == 3 { 81920 } else { 40960 }, - if i == 3 { 2 } else { 4 }, - )?; - } - for (weight, bytes) in [ - (key, 52428800), - (value, 13107200), - (aux[0], 40960), - (aux[1], 40960), - (aux[2], 40960), - (aux[3], 81920), - ] { - workspace.reject_alias(weight, bytes)?; - } - let t = rows as i32; - let mut commands = Vec::new(); - commands - .try_reserve_exact(24) - .map_err(|_| Error::HostAllocation)?; - let pack_low = if self.mode == PleBf16Mode::HighAndLow { - A::Address(h[13]) - } else { - A::NullAddress - }; - push( - &mut commands, - 0, - (rows * 2560).div_ceil(256) as u32, - 256, - vec![ - A::Address(h[0]), - A::Address(h[12]), - pack_low, - A::I64(i64::from(t) * 2560), - ], - ); - for (out, n, w) in [(3, 10240, key), (4, 2560, value)] { - commands.push(Command::Gemm { - input: h[12], - weight: w, - output: h[out], - rows: t, - n, - alpha: 1.0, - beta: 0.0, - }); - if self.mode == PleBf16Mode::HighAndLow { - commands.push(Command::Gemm { - input: h[13], - weight: w, - output: h[out], - rows: t, - n, - alpha: 1.0, - beta: 1.0, - }); - } - scan( - &mut commands, - h[out], - h[14], - n, - t, - if out == 3 { 0 } else { 1 }, - ); - } - push( - &mut commands, - 1, - (rows * 4) as u32, - 1024, - vec![A::Address(h[3]), A::Address(aux[0]), A::Address(h[5])], - ); - scan(&mut commands, h[5], h[14], 10240, t, 2); - push( - &mut commands, - 1, - (rows * 4) as u32, - 1024, - vec![A::Address(h[1]), A::Address(aux[1]), A::Address(h[6])], - ); - scan(&mut commands, h[6], h[14], 10240, t, 3); - push( - &mut commands, - 2, - (rows * 4) as u32, - 512, - vec![ - A::Address(h[5]), - A::Address(h[6]), - A::Address(h[7]), - A::F32(1.0 / 2560.0f32.sqrt()), - ], - ); - scan(&mut commands, h[7], h[14], 4, t, 4); - push( - &mut commands, - 3, - (rows * 40) as u32, - 256, - vec![ - A::Address(h[4]), - A::Address(h[7]), - A::Address(h[8]), - A::I32(t), - ], - ); - scan(&mut commands, h[8], h[14], 10240, t, 5); - push( - &mut commands, - 1, - (rows * 4) as u32, - 1024, - vec![A::Address(h[8]), A::Address(aux[2]), A::Address(h[9])], - ); - scan(&mut commands, h[9], h[14], 10240, t, 6); - push( - &mut commands, - 4, - (rows * 40) as u32, - 256, - vec![ - A::Address(h[2]), - A::Address(h[9]), - A::Address(aux[3]), - A::Address(h[1]), - A::Address(h[8]), - A::Address(h[10]), - A::I32(t), - ], - ); - scan(&mut commands, h[10], h[14], 10240, t, 7); - push( - &mut commands, - 6, - (rows * 360) as u32, - 256, - vec![ - A::Address(h[2]), - A::Address(h[9]), - A::Address(h[11]), - A::I32(t), - ], - ); - scan(&mut commands, h[11], h[14], 92160, t, 8); - push( - &mut commands, - 5, - 40, - 256, - vec![A::Address(h[2]), A::Address(h[9]), A::I32(t)], - ); - scan(&mut commands, h[1], h[14], 10240, t, 9); - let e = float_staging(embedding)?; - let s = float_staging(streams)?; - let p = float_staging(history)?; - let zero = staging(rows * 40)?; - let mut statuses = staging(rows * 40)?; - let mut flags = Vec::new(); - flags - .try_reserve_exact(rows * 10) - .map_err(|_| Error::HostAllocation)?; - flags.resize(rows * 10, 0); - let context = self.context; - let guard = context.enter()?; - let mut operation = context.driver.api.copy_from(h[0], &e); - if operation.is_ok() { - operation = context.driver.api.copy_from(h[1], &s); - } - if operation.is_ok() { - operation = context.driver.api.copy_from(h[2], &p); - } - if operation.is_ok() { - operation = context.driver.api.copy_from(h[14], &zero); - } - // Synchronous pageable H2D may return after staging before device DMA. - // The private NON_BLOCKING vendor stream has no implicit default-stream - // dependency: prove completion of real source uploads before enqueuing. - if operation.is_ok() { - operation = context.driver.api.synchronize(); - } - let blas = workspace.blas()?; - let module = self.module.as_ref().ok_or(Error::ContextPoisoned)?; - let pack = self.pack_module.as_ref().ok_or(Error::ContextPoisoned)?; - for command in &mut commands { - if operation.is_err() { - break; - } - operation = command.launch(blas, pack, module); - } - let sync = blas.synchronize(); - if operation.is_ok() && sync.is_ok() { - operation = context.driver.api.copy_to(h[14], &mut statuses); - } - let all = context.driver.api.synchronize(); - let pop = guard.finish(); - if operation.is_err() || sync.is_err() || all.is_err() || pop.is_err() { - self.failed = true; - workspace.mark_failed(); - } - if sync.is_err() || all.is_err() || pop.is_err() { - std::mem::forget((commands, e, s, p, zero, statuses, flags, weights)); - context.retain_driver(); - return combine(combine(combine(operation, sync), all), pop) - .map(|()| unreachable!("uncertain PLE batch drain")); - } - combine(combine(combine(operation, sync), all), pop)?; - for (flag, bytes) in flags.iter_mut().zip(statuses.as_chunks::<4>().0) { - *flag = u32::from_le_bytes(*bytes); - if *flag > 1 { - self.failed = true; - context.poisoned.set(true); - return Err(Error::InvalidDriverValue("PLE batch finite status")); - } - } - Ok(PleBatchCompletion { - owner: self, - rows, - next: 0, - flags: flags.into_boxed_slice(), - }) - } - pub fn close(mut self) -> Result<()> { - self.close_inner() - } - pub(super) fn close_inner(&mut self) -> Result<()> { - self.failed = true; - let mut result = Ok(()); - // No queued commands survive a successful compose. A poisoned owner - // retains vendor/kernel/whole banks and the Driver instead of freeing. - let guard = if self.context.is_poisoned() { - None - } else { - match self.context.enter() { - Ok(g) => Some(g), - Err(e) => { - self.context.poisoned.set(true); - result = Err(e); - None - } - } - }; - for module in [self.pack_module.take(), self.module.take()] - .into_iter() - .flatten() - { - let close = if self.context.is_poisoned() { - std::mem::forget(module); - Err(Error::ContextPoisoned) - } else { - module.close() - }; - if close.is_err() { - self.context.poisoned.set(true); - } - result = combine(result, close); - } - if let Some(g) = guard { - let pop = g.finish(); - if pop.is_err() { - self.context.poisoned.set(true); - } - result = combine(result, pop); - } - for slot in &mut self.buffers { - if let Some(b) = slot.take() { - let close = if self.context.is_poisoned() { - std::mem::forget(b); - Err(Error::ContextPoisoned) - } else { - b.release() - }; - if close.is_err() { - self.context.poisoned.set(true); - } - result = combine(result, close); - } - } - if self.context.is_poisoned() { - self.context.retain_driver(); - } - result - } -} +mod impl_plebatchqueue_2; +mod impl_plebatchqueue_2_2; +mod impl_plebatchqueue_3; diff --git a/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_2.rs b/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_2.rs new file mode 100644 index 00000000..f5e2d617 --- /dev/null +++ b/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_2.rs @@ -0,0 +1,127 @@ +//! Moved out of the parent module by STRA-338: impl PleBatchQueue. + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> PleBatchQueue<'ctx> { + pub(in super::super) fn new(context: &'ctx Context<'ctx>, mode: PleBf16Mode) -> Result { + Self::new_capacity(context,mode,64) + } + pub(in super::super) fn new_capacity(context:&'ctx Context<'ctx>,mode:PleBf16Mode,capacity:usize)->Result { + if !(1..=8192).contains(&capacity) {return Err(Error::InvalidQwenShape);} + let mut sizes=SIZES; for (i,size) in sizes.iter_mut().enumerate() {if i!=2 {*size=(*size/64).checked_mul(capacity).ok_or(Error::BudgetExceeded)?;}} + let ptx = assets()?; // explicit pending refusal before any allocation/module. + if context.is_poisoned() || context.handle.is_none() { + return Err(Error::ContextPoisoned); + } + let required = sizes.iter().try_fold(0usize,|sum,n|sum.checked_add(*n).ok_or(Error::BudgetExceeded))? + .checked_add(RESERVE) + .ok_or(Error::BudgetExceeded)?; + if context + .allocated_bytes() + .checked_add(required) + .is_none_or(|n| n > context.budget) + || context.memory_info()?.0 < required + { + return Err(Error::BudgetExceeded); + } + let mut owner = Self { + capacity, sizes, context, + buffers: std::array::from_fn(|_| None), + pack_module: None, + module: None, + mode, + failed: false, + }; + let operation = (|| { + for (i, bytes) in sizes.into_iter().enumerate() { + owner.buffers[i] = Some(context.allocate(bytes)?); + } + let guard = context.enter()?; + let load = (|| { + owner.pack_module = Some(KernelModule::load(ptx[0], &PACK_ENTRIES)?); + owner.module = Some(KernelModule::load(ptx[1], &ENTRIES)?); + Ok(()) + })(); + let pop = guard.finish(); + if pop.is_err() { + context.poisoned.set(true); + } + combine(load, pop)?; + owner.handles()?; + if context.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + Ok(()) + })(); + if let Err(error) = operation { + return combine(Err(error), owner.close()); + } + Ok(owner) + } + pub fn prompt_device_bytes(capacity:usize)->Result { + if !(1..=8192).contains(&capacity) {return Err(Error::InvalidQwenShape);} + Ok(368640+(PLE_BATCH_QUEUE_BYTES-368640)/64*capacity) + } + pub fn capacity(&self)->usize {self.capacity} + pub fn allocated_bytes(&self) -> usize { + self.buffers.iter().flatten().map(DeviceBuffer::len).sum() + } + pub fn is_failed(&self) -> bool { + self.failed || self.context.is_poisoned() || self.context.handle.is_none() + } + pub fn validate_context(&self, context: &Context<'_>) -> Result<()> { + if !std::ptr::eq(context, self.context) { + return Err(Error::ContextMismatch); + } + self.handles().map(|_| ()) + } + pub(in super::super) fn buffer(&self, i: usize) -> Result<&DeviceBuffer<'ctx>> { + self.buffers[i].as_ref().ok_or(Error::ContextPoisoned) + } + pub(in super::super) fn handles(&self) -> Result<[BufferHandle; 15]> { + if self.is_failed() || self.module.is_none() || self.pack_module.is_none() { + return Err(Error::ContextPoisoned); + } + let first = self.buffer(0)?.handle.ok_or(Error::ContextPoisoned)?; + let mut handles = [first; 15]; + for (i, bytes) in self.sizes.into_iter().enumerate() { + let b = self.buffer(i)?; + if !std::ptr::eq(b.context, self.context) { + return Err(Error::ContextMismatch); + } + if b.bytes != bytes { + return Err(Error::InvalidQwenShape); + } + let h = b.handle.ok_or(Error::ContextPoisoned)?; + h.validate_projection_extent(bytes, 4)?; + for (j, other) in handles.iter().take(i).enumerate() { + if h.overlaps(bytes, *other, self.sizes[j]) { + return Err(Error::OutputAliasesInput); + } + } + handles[i] = h; + } + if self.context.allocated_bytes() > self.context.budget { + return Err(Error::BudgetExceeded); + } + Ok(handles) + } + pub(in super::super) fn weight(&self, w: &DeviceBuffer<'_>, bytes: usize, alignment: u64) -> Result { + if !std::ptr::eq(w.context, self.context) { + return Err(Error::ContextMismatch); + } + if w.bytes != bytes { + return Err(Error::InvalidQwenShape); + } + let h = w.handle.ok_or(Error::ContextPoisoned)?; + h.validate_projection_extent(bytes, alignment)?; + for (owned, count) in self.handles()?.into_iter().zip(self.sizes) { + if h.overlaps(bytes, owned, count) { + return Err(Error::OutputAliasesInput); + } + } + Ok(h) + } +} diff --git a/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_2_2.rs b/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_2_2.rs new file mode 100644 index 00000000..859f910e --- /dev/null +++ b/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_2_2.rs @@ -0,0 +1,267 @@ +//! Moved out of the parent module by STRA-338: impl PleBatchQueue (2). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> PleBatchQueue<'ctx> { + /// Literal original batch profile, explicit hi-only or hi+low; no automatic + /// equivalence to the old F32 MMVF reduction is asserted. Actual binding, + /// row/position/history provenance must be supplied by the runtime caller. + pub fn compose<'loan>( + &'loan mut self, + workspace: &mut NativeBatchWorkspace<'_>, + weights: PleClosedWeights<'_, '_>, + embedding: &[f32], + streams: &[f32], + history: &[f32], + ) -> Result> { + workspace.validate_context(self.context)?; + let h = self.handles()?; + for (handle, bytes) in h.into_iter().zip(self.sizes) { + workspace.reject_alias(handle, bytes)?; + } + if !embedding.len().is_multiple_of(2560) { + return Err(Error::InvalidQwenShape); + } + let rows = embedding.len() / 2560; + if !(1..=self.capacity).contains(&rows) || streams.len() != rows * 10240 || history.len() != 92160 { + return Err(Error::InvalidQwenShape); + } + if embedding + .iter() + .chain(streams) + .chain(history) + .any(|v| !v.is_finite()) + { + return Err(Error::InvalidDriverValue("PLE batch source finite")); + } + let key = self.weight(weights.key, 52428800, 2)?; + let value = self.weight(weights.value, 13107200, 2)?; + let mut aux = [h[0]; 4]; + for (i, w) in weights.aux.iter().enumerate() { + aux[i] = self.weight( + w, + if i == 3 { 81920 } else { 40960 }, + if i == 3 { 2 } else { 4 }, + )?; + } + for (weight, bytes) in [ + (key, 52428800), + (value, 13107200), + (aux[0], 40960), + (aux[1], 40960), + (aux[2], 40960), + (aux[3], 81920), + ] { + workspace.reject_alias(weight, bytes)?; + } + let t = rows as i32; + let mut commands = Vec::new(); + commands + .try_reserve_exact(24) + .map_err(|_| Error::HostAllocation)?; + let pack_low = if self.mode == PleBf16Mode::HighAndLow { + A::Address(h[13]) + } else { + A::NullAddress + }; + push( + &mut commands, + 0, + (rows * 2560).div_ceil(256) as u32, + 256, + vec![ + A::Address(h[0]), + A::Address(h[12]), + pack_low, + A::I64(i64::from(t) * 2560), + ], + ); + for (out, n, w) in [(3, 10240, key), (4, 2560, value)] { + commands.push(Command::Gemm { + input: h[12], + weight: w, + output: h[out], + rows: t, + n, + alpha: 1.0, + beta: 0.0, + }); + if self.mode == PleBf16Mode::HighAndLow { + commands.push(Command::Gemm { + input: h[13], + weight: w, + output: h[out], + rows: t, + n, + alpha: 1.0, + beta: 1.0, + }); + } + scan( + &mut commands, + h[out], + h[14], + n, + t, + if out == 3 { 0 } else { 1 }, + ); + } + push( + &mut commands, + 1, + (rows * 4) as u32, + 1024, + vec![A::Address(h[3]), A::Address(aux[0]), A::Address(h[5])], + ); + scan(&mut commands, h[5], h[14], 10240, t, 2); + push( + &mut commands, + 1, + (rows * 4) as u32, + 1024, + vec![A::Address(h[1]), A::Address(aux[1]), A::Address(h[6])], + ); + scan(&mut commands, h[6], h[14], 10240, t, 3); + push( + &mut commands, + 2, + (rows * 4) as u32, + 512, + vec![ + A::Address(h[5]), + A::Address(h[6]), + A::Address(h[7]), + A::F32(1.0 / 2560.0f32.sqrt()), + ], + ); + scan(&mut commands, h[7], h[14], 4, t, 4); + push( + &mut commands, + 3, + (rows * 40) as u32, + 256, + vec![ + A::Address(h[4]), + A::Address(h[7]), + A::Address(h[8]), + A::I32(t), + ], + ); + scan(&mut commands, h[8], h[14], 10240, t, 5); + push( + &mut commands, + 1, + (rows * 4) as u32, + 1024, + vec![A::Address(h[8]), A::Address(aux[2]), A::Address(h[9])], + ); + scan(&mut commands, h[9], h[14], 10240, t, 6); + push( + &mut commands, + 4, + (rows * 40) as u32, + 256, + vec![ + A::Address(h[2]), + A::Address(h[9]), + A::Address(aux[3]), + A::Address(h[1]), + A::Address(h[8]), + A::Address(h[10]), + A::I32(t), + ], + ); + scan(&mut commands, h[10], h[14], 10240, t, 7); + push( + &mut commands, + 6, + (rows * 360) as u32, + 256, + vec![ + A::Address(h[2]), + A::Address(h[9]), + A::Address(h[11]), + A::I32(t), + ], + ); + scan(&mut commands, h[11], h[14], 92160, t, 8); + push( + &mut commands, + 5, + 40, + 256, + vec![A::Address(h[2]), A::Address(h[9]), A::I32(t)], + ); + scan(&mut commands, h[1], h[14], 10240, t, 9); + let e = float_staging(embedding)?; + let s = float_staging(streams)?; + let p = float_staging(history)?; + let zero = staging(rows * 40)?; + let mut statuses = staging(rows * 40)?; + let mut flags = Vec::new(); + flags + .try_reserve_exact(rows * 10) + .map_err(|_| Error::HostAllocation)?; + flags.resize(rows * 10, 0); + let context = self.context; + let guard = context.enter()?; + let mut operation = context.driver.api.copy_from(h[0], &e); + if operation.is_ok() { + operation = context.driver.api.copy_from(h[1], &s); + } + if operation.is_ok() { + operation = context.driver.api.copy_from(h[2], &p); + } + if operation.is_ok() { + operation = context.driver.api.copy_from(h[14], &zero); + } + // Synchronous pageable H2D may return after staging before device DMA. + // The private NON_BLOCKING vendor stream has no implicit default-stream + // dependency: prove completion of real source uploads before enqueuing. + if operation.is_ok() { + operation = context.driver.api.synchronize(); + } + let blas = workspace.blas()?; + let module = self.module.as_ref().ok_or(Error::ContextPoisoned)?; + let pack = self.pack_module.as_ref().ok_or(Error::ContextPoisoned)?; + for command in &mut commands { + if operation.is_err() { + break; + } + operation = command.launch(blas, pack, module); + } + let sync = blas.synchronize(); + if operation.is_ok() && sync.is_ok() { + operation = context.driver.api.copy_to(h[14], &mut statuses); + } + let all = context.driver.api.synchronize(); + let pop = guard.finish(); + if operation.is_err() || sync.is_err() || all.is_err() || pop.is_err() { + self.failed = true; + workspace.mark_failed(); + } + if sync.is_err() || all.is_err() || pop.is_err() { + std::mem::forget((commands, e, s, p, zero, statuses, flags, weights)); + context.retain_driver(); + return combine(combine(combine(operation, sync), all), pop) + .map(|()| unreachable!("uncertain PLE batch drain")); + } + combine(combine(combine(operation, sync), all), pop)?; + for (flag, bytes) in flags.iter_mut().zip(statuses.as_chunks::<4>().0) { + *flag = u32::from_le_bytes(*bytes); + if *flag > 1 { + self.failed = true; + context.poisoned.set(true); + return Err(Error::InvalidDriverValue("PLE batch finite status")); + } + } + Ok(PleBatchCompletion { + owner: self, + rows, + next: 0, + flags: flags.into_boxed_slice(), + }) + } +} diff --git a/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_3.rs b/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_3.rs new file mode 100644 index 00000000..4abe4da7 --- /dev/null +++ b/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_3.rs @@ -0,0 +1,69 @@ +//! Moved out of the parent module by STRA-338: impl PleBatchQueue (3). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> PleBatchQueue<'ctx> { + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + pub(in super::super) fn close_inner(&mut self) -> Result<()> { + self.failed = true; + let mut result = Ok(()); + // No queued commands survive a successful compose. A poisoned owner + // retains vendor/kernel/whole banks and the Driver instead of freeing. + let guard = if self.context.is_poisoned() { + None + } else { + match self.context.enter() { + Ok(g) => Some(g), + Err(e) => { + self.context.poisoned.set(true); + result = Err(e); + None + } + } + }; + for module in [self.pack_module.take(), self.module.take()] + .into_iter() + .flatten() + { + let close = if self.context.is_poisoned() { + std::mem::forget(module); + Err(Error::ContextPoisoned) + } else { + module.close() + }; + if close.is_err() { + self.context.poisoned.set(true); + } + result = combine(result, close); + } + if let Some(g) = guard { + let pop = g.finish(); + if pop.is_err() { + self.context.poisoned.set(true); + } + result = combine(result, pop); + } + for slot in &mut self.buffers { + if let Some(b) = slot.take() { + let close = if self.context.is_poisoned() { + std::mem::forget(b); + Err(Error::ContextPoisoned) + } else { + b.release() + }; + if close.is_err() { + self.context.poisoned.set(true); + } + result = combine(result, close); + } + } + if self.context.is_poisoned() { + self.context.retain_driver(); + } + result + } +} diff --git a/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv.rs b/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv.rs index 8aaa9b25..90ec889d 100644 --- a/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv.rs +++ b/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv.rs @@ -3,478 +3,5 @@ #[allow(unused_imports)] use super::*; -impl<'ctx> QsaPromptKv<'ctx> { - pub(super) fn new(c: &'ctx Context<'ctx>) -> Result { - let slots = crate::serving_context::kv_resident_pages()?; - admit( - c, - geometry() - .resident_bytes_with(slots, Resolver::map_bytes(slots)?) - .map_err(|_| Error::BudgetExceeded)?, - )?; - let mut o = Self { - context: c, - origin: Rc::new(Origin), - pools: Pools::empty(), - current: None, - mapped_current: None, - mapped: None, - resolver: None, - slots, - failed: false, - }; - let r = (|| { - // Asset fails closed before host allocation. Root charges mapped AND immutable - // snapshot payload as separate actual host owners, never transient-cap credit. - o.resolver = Some(Resolver::new(c, slots)?); - #[cfg(windows)] - let available = libc::physical_memory() - .and_then(|(_, available)| usize::try_from(available).ok()) - .ok_or(Error::HostAllocation)?; - #[cfg(unix)] - let text = - std::fs::read_to_string("/proc/meminfo").map_err(|_| Error::HostAllocation)?; - #[cfg(unix)] - let available = text - .lines() - .find_map(|line| { - line.strip_prefix("MemAvailable:")? - .split_whitespace() - .next()? - .parse::() - .ok() - }) - .and_then(|n| n.checked_mul(1024)) - .ok_or(Error::HostAllocation)?; - let mapped_host = geometry() - .mapped_host_bytes() - .map_err(|_| Error::HostAllocation)?; - if available < mapped_host + 8 * 1024 * 1024 * 1024 { - return Err(Error::HostAllocation); - } - let g = c.enter()?; - let mapped = MappedAllocation::new(); - let pop = g.finish(); - match mapped { - Ok(m) => { - o.mapped = Some(m); - if let Err(e) = pop { - c.poisoned.set(true); - return Err(e); - } - } - Err(e) => { - if pop.is_err() { - c.poisoned.set(true); - } - return combine(Err(e), pop); - } - } - o.pools.allocate(c, resident_runs(slots)?)?; - if c.memory_info()?.0 < RESERVE { - return Err(Error::BudgetExceeded); - } - Ok(()) - })(); - if let Err(e) = r { - return combine(Err(e), o.close()); - } - Ok(o) - } - pub fn empty_snapshot(&self) -> Result { - self.validate()?; - Ok(QsaKvSnapshot(Rc::new(Snapshot { - origin: self.origin.clone(), - pages: Rc::new(Box::new([])), - end: 0, - }))) - } - pub fn owner_id(&self) -> QsaKvOwnerId { - QsaKvOwnerId(self.origin.clone()) - } - pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { - if !std::ptr::eq(c, self.context) { - return Err(Error::ContextMismatch); - } - self.validate() - } - pub fn allocated_bytes(&self) -> usize { - self.pools.bytes() + self.resolver.as_ref().map_or(0, Resolver::bytes) - } - /// Resident pages (VRAM slots) of this owner. - pub fn resident_pages(&self) -> usize { - self.slots - } - pub fn pinned_host_bytes(&self) -> usize { - self.mapped.as_ref().map_or(0, MappedAllocation::bytes) - } - pub fn is_failed(&self) -> bool { - self.failed || self.context.is_poisoned() - } - pub fn validate(&self) -> Result<()> { - if self.is_failed() { - return Err(Error::ContextPoisoned); - } - self.pools.validate(self.context, resident_runs(self.slots)?)?; - self.resolver - .as_ref() - .ok_or(Error::ContextPoisoned)? - .validate()?; - if self.mapped.is_none() { - return Err(Error::ContextPoisoned); - } - Ok(()) - } - pub fn validate_snapshot(&self, s: &QsaKvSnapshot) -> Result<()> { - self.validate()?; - if !Rc::ptr_eq(&s.0.origin, &self.origin) - || s.0.end > geometry().cells() - || s.0.pages.len() < s.0.end.div_ceil(4) - || s.0.pages.len() > geometry().pages() - { - return Err(Error::InvalidQwenShape); - } - for p in s.0.pages.iter().take(s.0.end.div_ceil(4)) { - for (b, n) in p.bytes.iter().zip(PAGE) { - if b.len() != n { - return Err(Error::InvalidSize); - } - } - } - Ok(()) - } - pub(super) fn host_addresses(&self) -> Result<[u64; 4]> { - let m = self.mapped.as_ref().ok_or(Error::ContextPoisoned)?; - let (offsets, runs) = (offsets()?, stage_runs()?); - Ok([ - m.address(offsets[0], runs[0])?, - m.address(offsets[1], runs[1])?, - m.address(offsets[2], runs[2])?, - m.address(offsets[3], runs[3])?, - ]) - } - pub(super) fn restore(&mut self, w: &mut NativeBatchWorkspace<'ctx>, s: &QsaKvSnapshot) -> Result<()> { - self.validate_snapshot(s)?; - w.validate_context(self.context)?; - if self.current.as_ref().is_some_and(|x| Rc::ptr_eq(x, &s.0)) - && self - .mapped_current - .as_ref() - .is_some_and(|x| Rc::ptr_eq(x, &s.0)) - { - return Ok(()); - } - // No CPU host write may race an actual previous stream use. All successful public - // operations drain; this fence additionally enforces the materialization dependency. - self.context.synchronize()?; - let previous = self.mapped_current.take(); - self.current = None; - let m = self.mapped.as_mut().ok_or(Error::ContextPoisoned)?; - let offsets = offsets()?; - for (p, page) in s.0.pages.iter().take(s.0.end.div_ceil(4)).enumerate() { - if previous.as_ref().is_some_and(|old| { - Rc::ptr_eq(&old.origin, &s.0.origin) - && p < old.end.div_ceil(4) - && old.pages.get(p).is_some_and(|q| Rc::ptr_eq(q, page)) - }) { - continue; - } - for i in 0..4 { - m.write(offsets[i] + p * PAGE[i], &page.bytes[i])?; - } - } - self.resolver - .as_mut() - .ok_or(Error::ContextPoisoned)? - .reset(w, self.pools.table()?)?; - self.mapped_current = Some(s.0.clone()); - self.current = Some(s.0.clone()); - Ok(()) - } - pub(crate) fn resolved_addresses( - &mut self, - w: &mut NativeBatchWorkspace<'ctx>, - s: &QsaKvSnapshot, - ids: &DeviceBuffer<'_>, - steps: &DeviceBuffer<'_>, - t: usize, - ) -> Result<([u64; 4], u64, usize)> { - self.validate_snapshot(s)?; - if !(1..=3).contains(&t) { - return Err(Error::InvalidQwenShape); - } - let ids = checked(self.context, ids, t * 2051 * 4)?; - let steps = checked(self.context, steps, t * 16)?; - self.restore(w, s)?; - let host = self.host_addresses()?; - let resident = self.pools.addresses()?; - let table = self.pools.table()?; - self.resolver - .as_mut() - .ok_or(Error::ContextPoisoned)? - .resolve(w, table, ids, steps, t, host, resident)?; - Ok((resident, table, s.0.end)) - } - pub(crate) fn reject_alias(&self, b: &DeviceBuffer<'_>) -> Result<()> { - for own in self - .pools - .buffers - .iter() - .flatten() - .chain(self.pools.table.iter()) - { - if own.handle.ok_or(Error::ContextPoisoned)?.overlaps( - own.bytes, - b.handle.ok_or(Error::ContextPoisoned)?, - b.bytes, - ) { - return Err(Error::OutputAliasesInput); - } - } - self.resolver - .as_ref() - .ok_or(Error::ContextPoisoned)? - .reject_alias(b) - } - /// Inputs are the genuine full F32 normalized/RoPE K,V outputs, not half cells. - /// Successful result is privately minted after quantization/scales/full completion. - pub fn append( - &mut self, - workspace: &mut NativeBatchWorkspace<'ctx>, - stage: &mut QsaPromptStage<'ctx>, - prior: &QsaKvSnapshot, - inputs: &QsaKvInputs<'_, '_>, - ) -> Result { - self.append_bounded(workspace,stage,prior,inputs,64) - } - pub fn append_for_prompt(&mut self,workspace:&mut NativeBatchWorkspace<'ctx>,stage:&mut QsaPromptStage<'ctx>,prior:&QsaKvSnapshot,inputs:&QsaKvInputs<'_, '_>)->Result { - self.append_bounded(workspace,stage,prior,inputs,8192) - } - pub(super) fn append_bounded(&mut self,workspace:&mut NativeBatchWorkspace<'ctx>,stage:&mut QsaPromptStage<'ctx>,prior:&QsaKvSnapshot,inputs:&QsaKvInputs<'_, '_>,limit:usize)->Result { - let QsaKvInputs { keys, values, t } = inputs; - let (keys, values, t) = (*keys, *values, *t); - self.validate_snapshot(prior)?; - stage.validate(self.context)?; - workspace.validate_context(self.context)?; - if !(1..=limit).contains(&t) - || prior - .0 - .end - .checked_add(t) - .is_none_or(|n| n > geometry().cells()) - { - return Err(Error::InvalidQwenShape); - } - let end = prior.0.end + t; - let k = checked(self.context, keys, t * 512 * 4)?; - let v = checked(self.context, values, t * 512 * 4)?; - if keys.handle.ok_or(Error::ContextPoisoned)?.overlaps( - keys.bytes, - values.handle.ok_or(Error::ContextPoisoned)?, - values.bytes, - ) { - return Err(Error::OutputAliasesInput); - } - for p in self - .pools - .buffers - .iter() - .chain(stage.pools.buffers.iter()) - .flatten() - .chain(stage.status.iter()) - { - for b in [keys, values] { - if p.handle.ok_or(Error::ContextPoisoned)?.overlaps( - p.bytes, - b.handle.ok_or(Error::ContextPoisoned)?, - b.bytes, - ) { - return Err(Error::OutputAliasesInput); - } - } - } - workspace.reject_alias(keys.handle.ok_or(Error::ContextPoisoned)?, keys.bytes)?; - workspace.reject_alias(values.handle.ok_or(Error::ContextPoisoned)?, values.bytes)?; - // Reserve snapshot metadata and completed page storage BEFORE device writes. - let mut pages = Vec::new(); - pages - .try_reserve_exact(end.div_ceil(4)) - .map_err(|_| Error::HostAllocation)?; - pages.extend(prior.0.pages[..prior.0.end.div_ceil(4)].iter().cloned()); - let first = prior.0.end / 4; - let mut completed = Vec::new(); - completed - .try_reserve_exact(17) - .map_err(|_| Error::HostAllocation)?; - for _ in first..end.div_ceil(4) { - let mut a = Vec::new(); - a.try_reserve_exact(4).map_err(|_| Error::HostAllocation)?; - for n in PAGE { - let mut b = Vec::new(); - b.try_reserve_exact(n).map_err(|_| Error::HostAllocation)?; - b.resize(n, 0); - a.push(b); - } - completed.push(a); - } - stage.restore(self, prior)?; - self.restore(workspace, prior)?; - // Initialize new host-page tails; no uninitialized bytes enter canonical snapshots. - for p in prior.0.end.div_ceil(4)..end.div_ceil(4) { - for i in 0..4 { - stage.pools.buffers[i] - .as_mut() - .ok_or(Error::ContextPoisoned)? - .copy_from_range(p * PAGE[i], &completed[p - first][i])?; - } - } - let status = stage.status.as_mut().ok_or(Error::ContextPoisoned)?; - status.copy_from(&[0; 4])?; - let sa = checked(self.context, status, 4)?; - let rp = self.pools.addresses()?; - let sp = stage.pools.addresses()?; - let hp = self.host_addresses()?; - let guard = Arguments::new(vec![ - Arg::U64(k), - Arg::U64(v), - Arg::I32((t * 512) as i32), - Arg::U64(sa), - ])?; - stage.run( - workspace, - 0, - [(t * 512).div_ceil(256) as u32, 1, 1], - 256, - guard, - )?; - if stage.flags()? != 0 { - return Err(Error::InvalidQ8Activation); - } - let args = Arguments::new(vec![ - Arg::U64(k), - Arg::U64(v), - Arg::I64(prior.0.end as i64), - Arg::U64(self.pools.table()?), - Arg::I64(4), - Arg::U64(rp[0]), - Arg::U64(rp[1]), - Arg::U64(rp[2]), - Arg::U64(rp[3]), - Arg::U64(sp[0]), - Arg::U64(sp[1]), - Arg::U64(sp[2]), - Arg::U64(sp[3]), - Arg::U64(hp[0]), - Arg::U64(hp[1]), - Arg::U64(hp[2]), - Arg::U64(hp[3]), - ])?; - let scales = Arguments::new(vec![ - Arg::U64(sp[2]), - Arg::U64(sp[3]), - Arg::I32(prior.0.end as i32), - Arg::I32(end as i32), - Arg::U64(sa), - ])?; - stage.current = None; - self.current = None; - self.mapped_current = None; - stage.run(workspace, 1, [t as u32, 2, 8], 64, args)?; - stage.run(workspace, 2, [1, 1, 1], 256, scales)?; - if stage.flags()? != 0 { - return Err(Error::InvalidQ8Activation); - } - for (p, bufs) in (first..end.div_ceil(4)).zip(completed.iter_mut()) { - for (i, b) in bufs.iter_mut().enumerate() { - let pool = stage.pools.buffers[i] - .as_ref() - .ok_or(Error::ContextPoisoned)?; - read_range(pool, p * PAGE[i], b)?; - } - } - for (p, bufs) in (first..end.div_ceil(4)).zip(completed) { - let mut it = bufs.into_iter(); - let page = Rc::new(Page { - bytes: [ - it.next().ok_or(Error::InvalidSize)?.into_boxed_slice(), - it.next().ok_or(Error::InvalidSize)?.into_boxed_slice(), - it.next().ok_or(Error::InvalidSize)?.into_boxed_slice(), - it.next().ok_or(Error::InvalidSize)?.into_boxed_slice(), - ], - }); - if p < pages.len() { - pages[p] = page; - } else { - pages.push(page); - } - } - let result = QsaKvSnapshot(Rc::new(Snapshot { - origin: self.origin.clone(), - pages: Rc::new(pages.into_boxed_slice()), - end, - })); - stage.current = Some(result.0.clone()); - self.current = Some(result.0.clone()); - self.mapped_current = Some(result.0.clone()); - Ok(CompletedQsaKvAppend { - final_snapshot: result, - first: prior.0.end, - rows: t, - }) - } - pub fn close(mut self) -> Result<()> { - self.close_inner() - } - pub(super) fn close_inner(&mut self) -> Result<()> { - self.failed = true; - self.current = None; - self.mapped_current = None; - let mut r = Ok(()); - if let Some(o) = self.resolver.take() { - r = combine(r, o.close()); - } - if let Some(mut m) = self.mapped.take() { - // Closing while failed Context cannot prove DMA complete: retain actual pinned - // host allocation/library just as actual device owners are retained on poison. - if self.context.is_poisoned() { - std::mem::forget(m); - r = combine(r, Err(Error::ContextPoisoned)); - } else { - match self.context.enter() { - Ok(g) => { - let sync = self.context.driver.api.synchronize(); - let pop = g.finish(); - let safe = sync.is_ok() && pop.is_ok(); - r = combine(r, combine(sync, pop)); - if safe { - // Re-enter the exact Context only after drain AND pop proved - // completion. No uncertain launch input is freed by this cleanup. - match self.context.enter() { - Ok(g) => { - let free = m.close(); - let pop = g.finish(); - if free.is_err() || pop.is_err() { - self.context.poisoned.set(true); - } - r = combine(r, combine(free, pop)); - } - Err(e) => { - std::mem::forget(m); - r = combine(r, Err(e)); - } - } - } else { - self.context.poisoned.set(true); - std::mem::forget(m); - } - } - Err(e) => { - std::mem::forget(m); - r = combine(r, Err(e)); - } - } - } - } - combine(r, self.pools.close()) - } -} +mod impl_qsapromptkv_2; +mod impl_qsapromptkv_2_2; diff --git a/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv/impl_qsapromptkv_2.rs b/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv/impl_qsapromptkv_2.rs new file mode 100644 index 00000000..0c834230 --- /dev/null +++ b/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv/impl_qsapromptkv_2.rs @@ -0,0 +1,254 @@ +//! Moved out of the parent module by STRA-338: impl QsaPromptKv. + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> QsaPromptKv<'ctx> { + pub(in super::super) fn new(c: &'ctx Context<'ctx>) -> Result { + let slots = crate::serving_context::kv_resident_pages()?; + admit( + c, + geometry() + .resident_bytes_with(slots, Resolver::map_bytes(slots)?) + .map_err(|_| Error::BudgetExceeded)?, + )?; + let mut o = Self { + context: c, + origin: Rc::new(Origin), + pools: Pools::empty(), + current: None, + mapped_current: None, + mapped: None, + resolver: None, + slots, + failed: false, + }; + let r = (|| { + // Asset fails closed before host allocation. Root charges mapped AND immutable + // snapshot payload as separate actual host owners, never transient-cap credit. + o.resolver = Some(Resolver::new(c, slots)?); + #[cfg(windows)] + let available = libc::physical_memory() + .and_then(|(_, available)| usize::try_from(available).ok()) + .ok_or(Error::HostAllocation)?; + #[cfg(unix)] + let text = + std::fs::read_to_string("/proc/meminfo").map_err(|_| Error::HostAllocation)?; + #[cfg(unix)] + let available = text + .lines() + .find_map(|line| { + line.strip_prefix("MemAvailable:")? + .split_whitespace() + .next()? + .parse::() + .ok() + }) + .and_then(|n| n.checked_mul(1024)) + .ok_or(Error::HostAllocation)?; + let mapped_host = geometry() + .mapped_host_bytes() + .map_err(|_| Error::HostAllocation)?; + if available < mapped_host + 8 * 1024 * 1024 * 1024 { + return Err(Error::HostAllocation); + } + let g = c.enter()?; + let mapped = MappedAllocation::new(); + let pop = g.finish(); + match mapped { + Ok(m) => { + o.mapped = Some(m); + if let Err(e) = pop { + c.poisoned.set(true); + return Err(e); + } + } + Err(e) => { + if pop.is_err() { + c.poisoned.set(true); + } + return combine(Err(e), pop); + } + } + o.pools.allocate(c, resident_runs(slots)?)?; + if c.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + Ok(()) + })(); + if let Err(e) = r { + return combine(Err(e), o.close()); + } + Ok(o) + } + pub fn empty_snapshot(&self) -> Result { + self.validate()?; + Ok(QsaKvSnapshot(Rc::new(Snapshot { + origin: self.origin.clone(), + pages: Rc::new(Box::new([])), + end: 0, + }))) + } + pub fn owner_id(&self) -> QsaKvOwnerId { + QsaKvOwnerId(self.origin.clone()) + } + pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { + if !std::ptr::eq(c, self.context) { + return Err(Error::ContextMismatch); + } + self.validate() + } + pub fn allocated_bytes(&self) -> usize { + self.pools.bytes() + self.resolver.as_ref().map_or(0, Resolver::bytes) + } + /// Resident pages (VRAM slots) of this owner. + pub fn resident_pages(&self) -> usize { + self.slots + } + pub fn pinned_host_bytes(&self) -> usize { + self.mapped.as_ref().map_or(0, MappedAllocation::bytes) + } + pub fn is_failed(&self) -> bool { + self.failed || self.context.is_poisoned() + } + pub fn validate(&self) -> Result<()> { + if self.is_failed() { + return Err(Error::ContextPoisoned); + } + self.pools.validate(self.context, resident_runs(self.slots)?)?; + self.resolver + .as_ref() + .ok_or(Error::ContextPoisoned)? + .validate()?; + if self.mapped.is_none() { + return Err(Error::ContextPoisoned); + } + Ok(()) + } + pub fn validate_snapshot(&self, s: &QsaKvSnapshot) -> Result<()> { + self.validate()?; + if !Rc::ptr_eq(&s.0.origin, &self.origin) + || s.0.end > geometry().cells() + || s.0.pages.len() < s.0.end.div_ceil(4) + || s.0.pages.len() > geometry().pages() + { + return Err(Error::InvalidQwenShape); + } + for p in s.0.pages.iter().take(s.0.end.div_ceil(4)) { + for (b, n) in p.bytes.iter().zip(PAGE) { + if b.len() != n { + return Err(Error::InvalidSize); + } + } + } + Ok(()) + } + pub(in super::super) fn host_addresses(&self) -> Result<[u64; 4]> { + let m = self.mapped.as_ref().ok_or(Error::ContextPoisoned)?; + let (offsets, runs) = (offsets()?, stage_runs()?); + Ok([ + m.address(offsets[0], runs[0])?, + m.address(offsets[1], runs[1])?, + m.address(offsets[2], runs[2])?, + m.address(offsets[3], runs[3])?, + ]) + } + pub(in super::super) fn restore(&mut self, w: &mut NativeBatchWorkspace<'ctx>, s: &QsaKvSnapshot) -> Result<()> { + self.validate_snapshot(s)?; + w.validate_context(self.context)?; + if self.current.as_ref().is_some_and(|x| Rc::ptr_eq(x, &s.0)) + && self + .mapped_current + .as_ref() + .is_some_and(|x| Rc::ptr_eq(x, &s.0)) + { + return Ok(()); + } + // No CPU host write may race an actual previous stream use. All successful public + // operations drain; this fence additionally enforces the materialization dependency. + self.context.synchronize()?; + let previous = self.mapped_current.take(); + self.current = None; + let m = self.mapped.as_mut().ok_or(Error::ContextPoisoned)?; + let offsets = offsets()?; + for (p, page) in s.0.pages.iter().take(s.0.end.div_ceil(4)).enumerate() { + if previous.as_ref().is_some_and(|old| { + Rc::ptr_eq(&old.origin, &s.0.origin) + && p < old.end.div_ceil(4) + && old.pages.get(p).is_some_and(|q| Rc::ptr_eq(q, page)) + }) { + continue; + } + for i in 0..4 { + m.write(offsets[i] + p * PAGE[i], &page.bytes[i])?; + } + } + self.resolver + .as_mut() + .ok_or(Error::ContextPoisoned)? + .reset(w, self.pools.table()?)?; + self.mapped_current = Some(s.0.clone()); + self.current = Some(s.0.clone()); + Ok(()) + } + pub(crate) fn resolved_addresses( + &mut self, + w: &mut NativeBatchWorkspace<'ctx>, + s: &QsaKvSnapshot, + ids: &DeviceBuffer<'_>, + steps: &DeviceBuffer<'_>, + t: usize, + ) -> Result<([u64; 4], u64, usize)> { + self.validate_snapshot(s)?; + if !(1..=3).contains(&t) { + return Err(Error::InvalidQwenShape); + } + let ids = checked(self.context, ids, t * 2051 * 4)?; + let steps = checked(self.context, steps, t * 16)?; + self.restore(w, s)?; + let host = self.host_addresses()?; + let resident = self.pools.addresses()?; + let table = self.pools.table()?; + self.resolver + .as_mut() + .ok_or(Error::ContextPoisoned)? + .resolve(w, table, ids, steps, t, host, resident)?; + Ok((resident, table, s.0.end)) + } + pub(crate) fn reject_alias(&self, b: &DeviceBuffer<'_>) -> Result<()> { + for own in self + .pools + .buffers + .iter() + .flatten() + .chain(self.pools.table.iter()) + { + if own.handle.ok_or(Error::ContextPoisoned)?.overlaps( + own.bytes, + b.handle.ok_or(Error::ContextPoisoned)?, + b.bytes, + ) { + return Err(Error::OutputAliasesInput); + } + } + self.resolver + .as_ref() + .ok_or(Error::ContextPoisoned)? + .reject_alias(b) + } + /// Inputs are the genuine full F32 normalized/RoPE K,V outputs, not half cells. + /// Successful result is privately minted after quantization/scales/full completion. + pub fn append( + &mut self, + workspace: &mut NativeBatchWorkspace<'ctx>, + stage: &mut QsaPromptStage<'ctx>, + prior: &QsaKvSnapshot, + inputs: &QsaKvInputs<'_, '_>, + ) -> Result { + self.append_bounded(workspace,stage,prior,inputs,64) + } + pub fn append_for_prompt(&mut self,workspace:&mut NativeBatchWorkspace<'ctx>,stage:&mut QsaPromptStage<'ctx>,prior:&QsaKvSnapshot,inputs:&QsaKvInputs<'_, '_>)->Result { + self.append_bounded(workspace,stage,prior,inputs,8192) + } +} diff --git a/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv/impl_qsapromptkv_2_2.rs b/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv/impl_qsapromptkv_2_2.rs new file mode 100644 index 00000000..f5306c5d --- /dev/null +++ b/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv/impl_qsapromptkv_2_2.rs @@ -0,0 +1,235 @@ +//! Moved out of the parent module by STRA-338: impl QsaPromptKv (2). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> QsaPromptKv<'ctx> { + pub(in super::super) fn append_bounded(&mut self,workspace:&mut NativeBatchWorkspace<'ctx>,stage:&mut QsaPromptStage<'ctx>,prior:&QsaKvSnapshot,inputs:&QsaKvInputs<'_, '_>,limit:usize)->Result { + let QsaKvInputs { keys, values, t } = inputs; + let (keys, values, t) = (*keys, *values, *t); + self.validate_snapshot(prior)?; + stage.validate(self.context)?; + workspace.validate_context(self.context)?; + if !(1..=limit).contains(&t) + || prior + .0 + .end + .checked_add(t) + .is_none_or(|n| n > geometry().cells()) + { + return Err(Error::InvalidQwenShape); + } + let end = prior.0.end + t; + let k = checked(self.context, keys, t * 512 * 4)?; + let v = checked(self.context, values, t * 512 * 4)?; + if keys.handle.ok_or(Error::ContextPoisoned)?.overlaps( + keys.bytes, + values.handle.ok_or(Error::ContextPoisoned)?, + values.bytes, + ) { + return Err(Error::OutputAliasesInput); + } + for p in self + .pools + .buffers + .iter() + .chain(stage.pools.buffers.iter()) + .flatten() + .chain(stage.status.iter()) + { + for b in [keys, values] { + if p.handle.ok_or(Error::ContextPoisoned)?.overlaps( + p.bytes, + b.handle.ok_or(Error::ContextPoisoned)?, + b.bytes, + ) { + return Err(Error::OutputAliasesInput); + } + } + } + workspace.reject_alias(keys.handle.ok_or(Error::ContextPoisoned)?, keys.bytes)?; + workspace.reject_alias(values.handle.ok_or(Error::ContextPoisoned)?, values.bytes)?; + // Reserve snapshot metadata and completed page storage BEFORE device writes. + let mut pages = Vec::new(); + pages + .try_reserve_exact(end.div_ceil(4)) + .map_err(|_| Error::HostAllocation)?; + pages.extend(prior.0.pages[..prior.0.end.div_ceil(4)].iter().cloned()); + let first = prior.0.end / 4; + let mut completed = Vec::new(); + completed + .try_reserve_exact(17) + .map_err(|_| Error::HostAllocation)?; + for _ in first..end.div_ceil(4) { + let mut a = Vec::new(); + a.try_reserve_exact(4).map_err(|_| Error::HostAllocation)?; + for n in PAGE { + let mut b = Vec::new(); + b.try_reserve_exact(n).map_err(|_| Error::HostAllocation)?; + b.resize(n, 0); + a.push(b); + } + completed.push(a); + } + stage.restore(self, prior)?; + self.restore(workspace, prior)?; + // Initialize new host-page tails; no uninitialized bytes enter canonical snapshots. + for p in prior.0.end.div_ceil(4)..end.div_ceil(4) { + for i in 0..4 { + stage.pools.buffers[i] + .as_mut() + .ok_or(Error::ContextPoisoned)? + .copy_from_range(p * PAGE[i], &completed[p - first][i])?; + } + } + let status = stage.status.as_mut().ok_or(Error::ContextPoisoned)?; + status.copy_from(&[0; 4])?; + let sa = checked(self.context, status, 4)?; + let rp = self.pools.addresses()?; + let sp = stage.pools.addresses()?; + let hp = self.host_addresses()?; + let guard = Arguments::new(vec![ + Arg::U64(k), + Arg::U64(v), + Arg::I32((t * 512) as i32), + Arg::U64(sa), + ])?; + stage.run( + workspace, + 0, + [(t * 512).div_ceil(256) as u32, 1, 1], + 256, + guard, + )?; + if stage.flags()? != 0 { + return Err(Error::InvalidQ8Activation); + } + let args = Arguments::new(vec![ + Arg::U64(k), + Arg::U64(v), + Arg::I64(prior.0.end as i64), + Arg::U64(self.pools.table()?), + Arg::I64(4), + Arg::U64(rp[0]), + Arg::U64(rp[1]), + Arg::U64(rp[2]), + Arg::U64(rp[3]), + Arg::U64(sp[0]), + Arg::U64(sp[1]), + Arg::U64(sp[2]), + Arg::U64(sp[3]), + Arg::U64(hp[0]), + Arg::U64(hp[1]), + Arg::U64(hp[2]), + Arg::U64(hp[3]), + ])?; + let scales = Arguments::new(vec![ + Arg::U64(sp[2]), + Arg::U64(sp[3]), + Arg::I32(prior.0.end as i32), + Arg::I32(end as i32), + Arg::U64(sa), + ])?; + stage.current = None; + self.current = None; + self.mapped_current = None; + stage.run(workspace, 1, [t as u32, 2, 8], 64, args)?; + stage.run(workspace, 2, [1, 1, 1], 256, scales)?; + if stage.flags()? != 0 { + return Err(Error::InvalidQ8Activation); + } + for (p, bufs) in (first..end.div_ceil(4)).zip(completed.iter_mut()) { + for (i, b) in bufs.iter_mut().enumerate() { + let pool = stage.pools.buffers[i] + .as_ref() + .ok_or(Error::ContextPoisoned)?; + read_range(pool, p * PAGE[i], b)?; + } + } + for (p, bufs) in (first..end.div_ceil(4)).zip(completed) { + let mut it = bufs.into_iter(); + let page = Rc::new(Page { + bytes: [ + it.next().ok_or(Error::InvalidSize)?.into_boxed_slice(), + it.next().ok_or(Error::InvalidSize)?.into_boxed_slice(), + it.next().ok_or(Error::InvalidSize)?.into_boxed_slice(), + it.next().ok_or(Error::InvalidSize)?.into_boxed_slice(), + ], + }); + if p < pages.len() { + pages[p] = page; + } else { + pages.push(page); + } + } + let result = QsaKvSnapshot(Rc::new(Snapshot { + origin: self.origin.clone(), + pages: Rc::new(pages.into_boxed_slice()), + end, + })); + stage.current = Some(result.0.clone()); + self.current = Some(result.0.clone()); + self.mapped_current = Some(result.0.clone()); + Ok(CompletedQsaKvAppend { + final_snapshot: result, + first: prior.0.end, + rows: t, + }) + } + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + pub(in super::super) fn close_inner(&mut self) -> Result<()> { + self.failed = true; + self.current = None; + self.mapped_current = None; + let mut r = Ok(()); + if let Some(o) = self.resolver.take() { + r = combine(r, o.close()); + } + if let Some(mut m) = self.mapped.take() { + // Closing while failed Context cannot prove DMA complete: retain actual pinned + // host allocation/library just as actual device owners are retained on poison. + if self.context.is_poisoned() { + std::mem::forget(m); + r = combine(r, Err(Error::ContextPoisoned)); + } else { + match self.context.enter() { + Ok(g) => { + let sync = self.context.driver.api.synchronize(); + let pop = g.finish(); + let safe = sync.is_ok() && pop.is_ok(); + r = combine(r, combine(sync, pop)); + if safe { + // Re-enter the exact Context only after drain AND pop proved + // completion. No uncertain launch input is freed by this cleanup. + match self.context.enter() { + Ok(g) => { + let free = m.close(); + let pop = g.finish(); + if free.is_err() || pop.is_err() { + self.context.poisoned.set(true); + } + r = combine(r, combine(free, pop)); + } + Err(e) => { + std::mem::forget(m); + r = combine(r, Err(e)); + } + } + } else { + self.context.poisoned.set(true); + std::mem::forget(m); + } + } + Err(e) => { + std::mem::forget(m); + r = combine(r, Err(e)); + } + } + } + } + combine(r, self.pools.close()) + } +} diff --git a/crates/cuda-driver/src/qwen_dispatch/impl_context.rs b/crates/cuda-driver/src/qwen_dispatch/impl_context.rs index 4d82f992..eb118e6f 100644 --- a/crates/cuda-driver/src/qwen_dispatch/impl_context.rs +++ b/crates/cuda-driver/src/qwen_dispatch/impl_context.rs @@ -3,1421 +3,17 @@ #[allow(unused_imports)] use super::*; - -impl Context<'_> { - /// Source-defined fixed 2560-value embedding RMS normalization. The - /// producer validates finite semantic output after completed dispatch. - #[allow(clippy::too_many_arguments)] // Fixed source ABI operands, not caller selected geometry. - pub fn mtp_gr_attention_down( - &self, - r: &DeviceBuffer<'_>, - norm: &DeviceBuffer<'_>, - down: &DeviceBuffer<'_>, - inject: &DeviceBuffer<'_>, - lo: &mut DeviceBuffer<'_>, - rs: &mut DeviceBuffer<'_>, - injout: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call( - Operation::MtpGrAttentionDown, - &[r, norm, down, inject, lo, rs, injout], - 0.0, - false, - ) - } - - #[allow(clippy::too_many_arguments)] // Fixed source ABI operands, not caller selected geometry. - pub fn mtp_gr_attention_up( - &self, - r: &DeviceBuffer<'_>, - norm: &DeviceBuffer<'_>, - up: &DeviceBuffer<'_>, - lo: &DeviceBuffer<'_>, - rs: &DeviceBuffer<'_>, - mixed: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call( - Operation::MtpGrAttentionUp, - &[r, norm, up, lo, rs, mixed], - 0.0, - false, - ) - } - - #[allow(clippy::too_many_arguments)] // Fixed source ABI operands, not caller selected geometry. - pub fn mtp_gr_mlp_down( - &self, - r: &DeviceBuffer<'_>, - bo: &DeviceBuffer<'_>, - inj: &DeviceBuffer<'_>, - norm: &DeviceBuffer<'_>, - down: &DeviceBuffer<'_>, - inject: &DeviceBuffer<'_>, - lo: &mut DeviceBuffer<'_>, - rs: &mut DeviceBuffer<'_>, - injout: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call( - Operation::MtpGrMlpDown, - &[r, bo, inj, norm, down, inject, lo, rs, injout], - 0.0, - false, - ) - } - - #[allow(clippy::too_many_arguments)] // Fixed source ABI operands, not caller selected geometry. - pub fn mtp_gr_mlp_up( - &self, - r: &DeviceBuffer<'_>, - bo: &DeviceBuffer<'_>, - inj: &DeviceBuffer<'_>, - norm: &DeviceBuffer<'_>, - up: &DeviceBuffer<'_>, - lo: &DeviceBuffer<'_>, - rs: &DeviceBuffer<'_>, - rout: &mut DeviceBuffer<'_>, - mixed: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call( - Operation::MtpGrMlpUp, - &[r, bo, inj, norm, up, lo, rs, rout, mixed], - 0.0, - false, - ) - } - - #[allow(clippy::too_many_arguments)] // Fixed source ABI operands, not caller selected geometry. - pub fn mtp_quantize_scaled_2560( - &self, - input: &DeviceBuffer<'_>, - q: &mut DeviceBuffer<'_>, - scales: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call(Operation::MtpQuant2560, &[input, q, scales], 0.0, false) - } - - #[allow(clippy::too_many_arguments)] // Fixed source ABI operands, not caller selected geometry. - pub fn mtp_quantize_scaled_640( - &self, - input: &DeviceBuffer<'_>, - q: &mut DeviceBuffer<'_>, - scales: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call(Operation::MtpQuant640, &[input, q, scales], 0.0, false) - } - - #[allow(clippy::too_many_arguments)] // Fixed source ABI operands, not caller selected geometry. - pub fn mtp_s2_gate_up_tile( - &self, - codes: &DeviceBuffer<'_>, - halfscales: &DeviceBuffer<'_>, - q: &DeviceBuffer<'_>, - xscales: &DeviceBuffer<'_>, - out: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call( - Operation::MtpS2GateUp, - &[codes, halfscales, q, xscales, out], - 0.0, - false, - ) - } - - #[allow(clippy::too_many_arguments)] // Fixed source ABI operands, not caller selected geometry. - pub fn mtp_s2_down_tile( - &self, - codes: &DeviceBuffer<'_>, - halfscales: &DeviceBuffer<'_>, - q: &DeviceBuffer<'_>, - xscales: &DeviceBuffer<'_>, - out: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call( - Operation::MtpS2Down, - &[codes, halfscales, q, xscales, out], - 0.0, - false, - ) - } - - /// Original512-expert S2 bank; exactly640 gate then640 up results. - /// No row/plane slices or caller geometry are exposed. - pub fn mtp_s2_gate_up_full( - &self, - bank: &DeviceBuffer<'_>, - expert: u32, - q: &DeviceBuffer<'_>, - xscales: &DeviceBuffer<'_>, - out: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.mtp_s2_full_call(Operation::MtpS2GateUpFull, bank, expert, q, xscales, out) - } - - /// Original512-expert S2 bank; exactly2560 down results. - pub fn mtp_s2_down_full( - &self, - bank: &DeviceBuffer<'_>, - expert: u32, - q: &DeviceBuffer<'_>, - xscales: &DeviceBuffer<'_>, - out: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.mtp_s2_full_call(Operation::MtpS2DownFull, bank, expert, q, xscales, out) - } - - #[allow(clippy::too_many_arguments)] // Two closed source ABIs, no caller geometry. - pub(super) fn mtp_s2_full_call( - &self, - operation: Operation, - bank: &DeviceBuffer<'_>, - expert: u32, - q: &DeviceBuffer<'_>, - xscales: &DeviceBuffer<'_>, - out: &mut DeviceBuffer<'_>, - ) -> Result<()> { - let layout = qwen_ffi::mtp_s2_full_layout(operation, expert)?; - let (asset, layout, handles) = admission( - self, - &[bank, q, xscales, out], - Admission { - operation, - layout: Ok(layout), - asset: qwen_ffi::asset(operation), - epsilon: 0.0, - in_place: false, - }, - )?; - execute( - self, - &self.qwen_kernels, - asset, - Arguments::with_layout(operation, layout, handles, 0.0), - ) - } - - #[allow(clippy::too_many_arguments)] // Fixed source ABI operands, not caller selected geometry. - pub fn mtp_swiglu_640( - &self, - gateup: &DeviceBuffer<'_>, - out: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call(Operation::MtpS2Swiglu, &[gateup, out], 0.0, false) - } - pub fn mtp_embedding_norm_f32( - &self, - input: &DeviceBuffer<'_>, - gamma: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call( - Operation::MtpEmbeddingNorm, - &[input, gamma, output], - 0.0, - false, - ) - } - /// Normalize all four hidden streams together over exactly 10240 values. - pub fn mtp_hidden_norm_f32( - &self, - input: &DeviceBuffer<'_>, - gamma: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call( - Operation::MtpHiddenNorm, - &[input, gamma, output], - 0.0, - false, - ) - } - /// Add the normalized embedding independently to each hidden stream. - pub fn mtp_broadcast_f32( - &self, - hidden: &DeviceBuffer<'_>, - embedding: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call( - Operation::MtpBroadcast, - &[hidden, embedding, output], - 0.0, - false, - ) - } - - /// Closed causal dense MTP attention, FP16 cell-major K/V in ascending - /// window order. Position determines width; scratch and launch dimensions - /// are internal. Completion is distinct from producer finite publication. - pub fn mtp_dense_attend_f16( - &self, - query: &DeviceBuffer<'_>, - keys: &DeviceBuffer<'_>, - values: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - position: u32, - ) -> Result<()> { - let chunk_layout = qwen_ffi::mtp_dense_layout(Operation::MtpDenseChunk, position)?; - let merge_layout = qwen_ffi::mtp_dense_layout(Operation::MtpDenseMerge, position)?; - let chunk_asset = - qwen_ffi::asset(Operation::MtpDenseChunk).ok_or(Error::UnsupportedQwenOperation)?; - let merge_asset = - qwen_ffi::asset(Operation::MtpDenseMerge).ok_or(Error::UnsupportedQwenOperation)?; - chunk_asset.validate(Operation::MtpDenseChunk)?; - merge_asset.validate(Operation::MtpDenseMerge)?; - if self.poisoned() { - return Err(Error::ContextPoisoned); - } - let inputs = [query, keys, values, &*output]; - let expected = [ - chunk_layout.bytes[0], - chunk_layout.bytes[1], - chunk_layout.bytes[2], - merge_layout.bytes[3], - ]; - for (i, buffer) in inputs.iter().enumerate() { - if !std::ptr::eq(self, buffer.context) { - return Err(Error::ContextMismatch); - } - if buffer.bytes != expected[i] { - return Err(Error::InvalidQwenShape); - } - let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; - handle - .validate_projection_extent(expected[i], if i < 3 { 16 } else { 4 }) - .map_err(|_| Error::InvalidQwenShape)?; - for other in inputs.iter().take(i) { - if handle.overlaps( - buffer.bytes, - other.handle.ok_or(Error::ContextPoisoned)?, - other.bytes, - ) { - return Err(Error::OutputAliasesInput); - } - } - } - let scratch = chunk_layout.bytes[3..6] - .iter() - .try_fold(256usize, |sum, size| sum.checked_add(*size)) - .ok_or(Error::InvalidQwenShape)?; - if self - .allocated - .get() - .checked_add(scratch) - .is_none_or(|n| n > self.budget) - { - return Err(Error::BudgetExceeded); - } - // Every allocation is retained by an owner through both synchronized - // launches. Existing failed-free charges/poison policy remain active. - let [acc, max, sum, padding] = owned_mtp_scratch( - self, - [ - chunk_layout.bytes[3], - chunk_layout.bytes[4], - chunk_layout.bytes[5], - 256, - ], - )?; - let result = (|| { - let (chunk, cl, ch) = admission( - self, - &[query, keys, values, &acc, &max, &sum], - Admission { - operation: Operation::MtpDenseChunk, - layout: Ok(chunk_layout), - asset: Some(chunk_asset), - epsilon: 0.0, - in_place: false, - }, - )?; - let (merge, ml, mh) = admission( - self, - &[&acc, &max, &sum, output], - Admission { - operation: Operation::MtpDenseMerge, - layout: Ok(merge_layout), - asset: Some(merge_asset), - epsilon: 0.0, - in_place: false, - }, - )?; - prepare_pair(self, &self.qwen_kernels, [chunk, merge]) - .and_then(|()| { - execute( - self, - &self.qwen_kernels, - chunk, - Arguments::with_layout(Operation::MtpDenseChunk, cl, ch, 0.0), - ) - }) - .and_then(|()| { - execute( - self, - &self.qwen_kernels, - merge, - Arguments::with_layout(Operation::MtpDenseMerge, ml, mh, 0.0), - ) - }) - })(); - let result = combine(result, acc.release()); - let result = combine(result, max.release()); - let result = combine(result, sum.release()); - combine(result, padding.release()) - } - - // Private transport-only adapter; original public attention remains exact. - pub(in super::super) fn mtp_dense_attend_ring_f16( - &self, - query: &DeviceBuffer<'_>, - keys: &DeviceBuffer<'_>, - values: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - position: u32, - offset: usize, - ) -> Result<()> { - let chunk_layout = qwen_ffi::mtp_dense_layout(Operation::MtpDenseChunk, position)?; - let merge_layout = qwen_ffi::mtp_dense_layout(Operation::MtpDenseMerge, position)?; - let chunk_asset = - qwen_ffi::asset(Operation::MtpDenseChunk).ok_or(Error::UnsupportedQwenOperation)?; - let merge_asset = - qwen_ffi::asset(Operation::MtpDenseMerge).ok_or(Error::UnsupportedQwenOperation)?; - chunk_asset.validate(Operation::MtpDenseChunk)?; - merge_asset.validate(Operation::MtpDenseMerge)?; - if self.poisoned() { - return Err(Error::ContextPoisoned); - } - // Full allocations are owned by the opaque ring. Only checked active - // chronological spans enter the unchanged chunk/merge ABI. - let inputs = [query, keys, values, &*output]; - let expected = [ - chunk_layout.bytes[0], - super::super::mtp_dense_kv::HALF_RING_BYTES, - super::super::mtp_dense_kv::HALF_RING_BYTES, - merge_layout.bytes[3], - ]; - let mut active = [query.handle.ok_or(Error::ContextPoisoned)?; 4]; - for (i, buffer) in inputs.iter().enumerate() { - if !std::ptr::eq(self, buffer.context) { - return Err(Error::ContextMismatch); - } - if buffer.bytes != expected[i] { - return Err(Error::InvalidQwenShape); - } - let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; - handle.validate_projection_extent(expected[i], if i < 3 { 16 } else { 4 })?; - for other in inputs.iter().take(i) { - if handle.overlaps( - buffer.bytes, - other.handle.ok_or(Error::ContextPoisoned)?, - other.bytes, - ) { - return Err(Error::OutputAliasesInput); - } - } - active[i] = if i == 1 || i == 2 { - handle.checked_subspan(buffer.bytes, offset, chunk_layout.bytes[i])? - } else { - handle - }; - } - let scratch = chunk_layout.bytes[3..6] - .iter() - .try_fold(256usize, |sum, size| sum.checked_add(*size)) - .ok_or(Error::InvalidQwenShape)?; - if self - .allocated - .get() - .checked_add(scratch) - .is_none_or(|n| n > self.budget) - { - return Err(Error::BudgetExceeded); - } - // Every allocation is retained by an owner through both synchronized - // launches. Existing failed-free charges/poison policy remain active. - let [acc, max, sum, padding] = owned_mtp_scratch( - self, - [ - chunk_layout.bytes[3], - chunk_layout.bytes[4], - chunk_layout.bytes[5], - 256, - ], - )?; - let result = (|| { - let chunk = chunk_asset; - let cl = chunk_layout; - let mut ch = [active[0]; 9]; - ch[..6].copy_from_slice(&[ - active[0], - active[1], - active[2], - acc.handle.ok_or(Error::ContextPoisoned)?, - max.handle.ok_or(Error::ContextPoisoned)?, - sum.handle.ok_or(Error::ContextPoisoned)?, - ]); - ranges_layout(Operation::MtpDenseChunk, cl, ch, cl.bytes, false)?; - let (merge, ml, mh) = admission( - self, - &[&acc, &max, &sum, output], - Admission { - operation: Operation::MtpDenseMerge, - layout: Ok(merge_layout), - asset: Some(merge_asset), - epsilon: 0.0, - in_place: false, - }, - )?; - prepare_pair(self, &self.qwen_kernels, [chunk, merge]) - .and_then(|()| { - execute( - self, - &self.qwen_kernels, - chunk, - Arguments::with_layout(Operation::MtpDenseChunk, cl, ch, 0.0), - ) - }) - .and_then(|()| { - execute( - self, - &self.qwen_kernels, - merge, - Arguments::with_layout(Operation::MtpDenseMerge, ml, mh, 0.0), - ) - }) - })(); - let result = combine(result, acc.release()); - let result = combine(result, max.release()); - let result = combine(result, sum.release()); - combine(result, padding.release()) - } - - pub(super) fn kar_ple_call( - &self, - operation: Operation, - buffers: &[&DeviceBuffer<'_>], - value: u32, - ) -> Result<()> { - let (asset, layout, handles) = admission( - self, - buffers, - Admission { - operation, - layout: qwen_ffi::kar_ple_layout(operation, value), - asset: qwen_ffi::asset(operation), - epsilon: 0.0, - in_place: false, - }, - )?; - execute( - self, - &self.qwen_kernels, - asset, - Arguments::with_layout(operation, layout, handles, 0.0), - ) - } - - /// Fixed experimental PLE row-cache scatter. Missing qualification refuses - /// before native mutation. Zero misses must skip this call. - pub fn kar_ple_scatter( - &self, - cache: &mut DeviceBuffer<'_>, - updates: &DeviceBuffer<'_>, - count: u32, - ) -> Result<()> { - self.kar_ple_call(Operation::KarPleScatter, &[cache, updates], count) - } - - /// Decode exactly sixteen fixed L2 PLE rows. Partition count is derived - /// from the exact four-FP16 book extent; the producer validates row data. - pub fn kar_ple_decode( - &self, - cache: &DeviceBuffer<'_>, - slots: &DeviceBuffer<'_>, - books: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - if !books.bytes.is_multiple_of(8) { - return Err(Error::InvalidQwenShape); - } - let parts = u32::try_from(books.bytes / 8).map_err(|_| Error::InvalidQwenShape)?; - self.kar_ple_call( - Operation::KarPleDecode, - &[cache, slots, books, output], - parts, - ) - } - - pub(super) fn qsa_call( - &self, - operation: Operation, - buffers: &[&DeviceBuffer<'_>], - value: u32, - ) -> Result<()> { - // These four fixed kernels bake the identity RoPE (a private theta word, no scaling arguments); the - // committed assets cannot rotate a scaled context, so a scaled serving context must never reach them. - if matches!( - operation, - Operation::QsaRopeQ - | Operation::QsaRopeK - | Operation::QsaRopeIndexQ - | Operation::QsaIndexAppend - ) && crate::serving_context::serving_context().rope_is_scaled() - { - return Err(Error::UnsupportedQwenOperation); - } - let (asset, layout, handles) = admission( - self, - buffers, - Admission { - operation, - layout: qwen_ffi::qsa_layout(operation, value), - asset: qwen_ffi::asset(operation), - epsilon: 0.0, - in_place: false, - }, - )?; - execute( - self, - &self.qwen_kernels, - asset, - Arguments::with_layout(operation, layout, handles, 0.0), - ) - } - - /// Closed QSA split q gate; unqualified assets refuse before mutation. - pub fn qsa_split_q_gate( - &self, - full: &DeviceBuffer<'_>, - query: &mut DeviceBuffer<'_>, - gate: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call(Operation::QsaSplit, &[full, query, gate], 0.0, false) - } - - /// Closed QSA norm q; unqualified assets refuse before mutation. - pub fn qsa_norm_q( - &self, - input: &DeviceBuffer<'_>, - gamma: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call(Operation::QsaNormQ, &[input, gamma, output], 0.0, false) - } - - /// Closed QSA norm k; unqualified assets refuse before mutation. - pub fn qsa_norm_k( - &self, - input: &DeviceBuffer<'_>, - gamma: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call(Operation::QsaNormK, &[input, gamma, output], 0.0, false) - } - - /// Closed QSA norm index q; unqualified assets refuse before mutation. - pub fn qsa_norm_index_q( - &self, - input: &DeviceBuffer<'_>, - gamma: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call( - Operation::QsaNormIndexQ, - &[input, gamma, output], - 0.0, - false, - ) - } - - /// Closed QSA rope q; unqualified assets refuse before mutation. - pub fn qsa_rope_q( - &self, - input: &DeviceBuffer<'_>, - position: u32, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qsa_call(Operation::QsaRopeQ, &[input, output], position) - } - - /// Closed QSA rope k; unqualified assets refuse before mutation. - pub fn qsa_rope_k( - &self, - input: &DeviceBuffer<'_>, - position: u32, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qsa_call(Operation::QsaRopeK, &[input, output], position) - } - - /// Closed QSA rope index q; unqualified assets refuse before mutation. - pub fn qsa_rope_index_q( - &self, - input: &DeviceBuffer<'_>, - position: u32, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qsa_call(Operation::QsaRopeIndexQ, &[input, output], position) - } - - /// Closed QSA index append; unqualified assets refuse before mutation. - pub fn qsa_index_append( - &self, - raw: &DeviceBuffer<'_>, - gamma: &DeviceBuffer<'_>, - prior: &DeviceBuffer<'_>, - next: &mut DeviceBuffer<'_>, - position: u32, - ) -> Result<()> { - self.qsa_call( - Operation::QsaIndexAppend, - &[raw, gamma, prior, next], - position, - ) - } - - /// Closed QSA pack kv; unqualified assets refuse before mutation. - pub fn qsa_pack_kv( - &self, - key: &DeviceBuffer<'_>, - value: &DeviceBuffer<'_>, - packed_key: &mut DeviceBuffer<'_>, - packed_value: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call( - Operation::QsaPackKv, - &[key, value, packed_key, packed_value], - 0.0, - false, - ) - } - - /// Closed QSA block scores; unqualified assets refuse before mutation. - pub fn qsa_block_scores( - &self, - pooled: &DeviceBuffer<'_>, - dead: &DeviceBuffer<'_>, - index_query: &DeviceBuffer<'_>, - scores: &mut DeviceBuffer<'_>, - position: u32, - ) -> Result<()> { - self.qsa_call( - Operation::QsaBlockScores, - &[pooled, dead, index_query, scores], - position, - ) - } - - /// Score only the exact initialized prefix of a bounded pooled-key owner. - /// The original operation admission still checks shapes, context, aliases, - /// qualification and budget. The scoped view never owns or frees memory. - pub fn qsa_block_scores_prefix( - &self, - pooled: &DeviceBuffer<'_>, - dead: &DeviceBuffer<'_>, - index_query: &DeviceBuffer<'_>, - scores: &mut DeviceBuffer<'_>, - position: u32, - ) -> Result<()> { - let layout = qwen_ffi::qsa_layout(Operation::QsaBlockScores, position)?; - let bytes = layout.bytes[0]; - if bytes == 0 || bytes > pooled.bytes { - return Err(Error::InvalidQwenShape); - } - let view = std::mem::ManuallyDrop::new(DeviceBuffer { - context: pooled.context, - handle: pooled.handle, - bytes, - _thread: std::marker::PhantomData, - borrowed: false, - }); - self.qsa_block_scores(&view, dead, index_query, scores, position) - } - - /// Closed QSA block topk; unqualified assets refuse before mutation. - pub fn qsa_block_topk( - &self, - scores: &DeviceBuffer<'_>, - ids: &mut DeviceBuffer<'_>, - position: u32, - ) -> Result<()> { - self.qsa_call(Operation::QsaBlockTopk, &[scores, ids], position) - } - - /// Closed QSA attend; unqualified assets refuse before mutation. - pub fn qsa_attend( - &self, - query: &DeviceBuffer<'_>, - packed_key: &DeviceBuffer<'_>, - packed_value: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - width: u32, - ) -> Result<()> { - self.qsa_call( - Operation::QsaAttend, - &[query, packed_key, packed_value, output], - width, - ) - } - - /// Closed QSA gate f32; unqualified assets refuse before mutation. - pub fn qsa_gate_f32( - &self, - attention: &DeviceBuffer<'_>, - gate: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call(Operation::QsaGate, &[attention, gate, output], 0.0, false) - } - - /// Native quantized-expert SwiGLU on two fixed 640-value F32 vectors. - pub fn moe_swiglu_f32( - &self, - gate: &DeviceBuffer<'_>, - up: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call(Operation::MoeSwiglu, &[gate, up, output], 0.0, false) - } - - /// Original BF16-rounded activation and DOUBLE shared scalar reduction. - pub fn moe_shared_scalar_f32_bf16( - &self, - input: &DeviceBuffer<'_>, - weights: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call( - Operation::MoeSharedScalar, - &[input, weights, output], - 0.0, - false, - ) - } - - /// Scale one shared 2560-value vector by its completed scalar gate. - pub fn moe_shared_scale_f32( - &self, - input: &DeviceBuffer<'_>, - scalar: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call( - Operation::MoeSharedScale, - &[input, scalar, output], - 0.0, - false, - ) - } - - /// Original ordered DOUBLE reduction of ten routed outputs plus shared. - /// All buffers store F32; only the fixed kernel's accumulator is F64. - pub fn moe_combine_f64( - &self, - parts: &DeviceBuffer<'_>, - weights: &DeviceBuffer<'_>, - shared: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call( - Operation::MoeCombine, - &[parts, weights, shared, output], - 0.0, - false, - ) - } - - /// Fixed PLE value projection: BF16-rounded activation, source double sum. - pub fn ple_value_bf16_f32( - &self, - embedding: &DeviceBuffer<'_>, - weights: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call( - Operation::PleValue, - &[embedding, weights, output], - 0.0, - false, - ) - } - - /// Complete fixed PLE Value projection; forty CTAs preserve each serial row sum. - pub fn ple_value_full_bf16_f32( - &self, - embedding: &DeviceBuffer<'_>, - weights: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call( - Operation::PleValueFull, - &[embedding, weights, output], - 0.0, - false, - ) - } - - /// Four PLE streams with the source's ordinary CUDA normalization profile. - pub fn ple_grouped_norm_f32( - &self, - input: &DeviceBuffer<'_>, - gamma: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call(Operation::PleNorm, &[input, gamma, output], 0.0, false) - } - - pub fn ple_signed_gate_f32( - &self, - key: &DeviceBuffer<'_>, - query: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call(Operation::PleGate, &[key, query, output], 0.0, false) - } - - pub fn ple_broadcast_f32( - &self, - value: &DeviceBuffer<'_>, - gate: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call(Operation::PleBroadcast, &[value, gate, output], 0.0, false) - } - - /// Nine row-fastest history entries per channel; candidate outputs disjoint. - pub fn ple_conv_history_f32( - &self, - prior: &DeviceBuffer<'_>, - normalized: &DeviceBuffer<'_>, - weights: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - next: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call( - Operation::PleConv, - &[prior, normalized, weights, output, next], - 0.0, - false, - ) - } - - pub fn ple_residual_f32( - &self, - residual: &DeviceBuffer<'_>, - gated: &DeviceBuffer<'_>, - convolution: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call( - Operation::PleResidual, - &[residual, gated, convolution, output], - 0.0, - false, - ) - } - - /// Fixed decomposed GDN convolution over10240 channels and three prior taps. - pub fn gdn_conv_silu_f32( - &self, - history: &DeviceBuffer<'_>, - input: &DeviceBuffer<'_>, - weights: &DeviceBuffer<'_>, - next_history: &mut DeviceBuffer<'_>, - raw: &mut DeviceBuffer<'_>, - h: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call( - Operation::GdnConv, - &[history, input, weights, next_history, raw, h], - 0.0, - false, - ) - } - /// Normalizes32 Q/K rows. Only the first4096 F32 values are written. - pub fn gdn_qk_l2_f32( - &self, - h: &DeviceBuffer<'_>, - normalized: &mut DeviceBuffer<'_>, - epsilon: f32, - ) -> Result<()> { - self.qwen_call(Operation::GdnQk, &[h, normalized], epsilon, false) - } - pub fn gdn_beta_sigmoid_f32( - &self, - beta: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call(Operation::GdnBeta, &[beta, output], 0.0, false) - } - pub fn gdn_gate_softplus_f32( - &self, - alpha: &DeviceBuffer<'_>, - dt: &DeviceBuffer<'_>, - a: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call(Operation::GdnGate, &[alpha, dt, a, output], 0.0, false) - } - /// Fixed state[(row*48+head)*128+column]; outputs are disjoint candidates. - #[allow(clippy::too_many_arguments)] // Eight distinct source-defined pointer operands. - pub fn gdn_step_f32( - &self, - state: &DeviceBuffer<'_>, - q: &DeviceBuffer<'_>, - k: &DeviceBuffer<'_>, - v: &DeviceBuffer<'_>, - gate: &DeviceBuffer<'_>, - beta: &DeviceBuffer<'_>, - next_state: &mut DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call( - Operation::GdnStep, - &[state, q, k, v, gate, beta, next_state, output], - 0.0, - false, - ) - } - /// The unchanged recurrence consumes fixed Q/K/V ranges of completed - /// producer allocations. No general buffer view or range is exposed. - #[allow(clippy::too_many_arguments)] // Seven fixed source-defined owners. - pub fn gdn_step_from_products_f32( - &self, - state: &DeviceBuffer<'_>, - qk: &DeviceBuffer<'_>, - h: &DeviceBuffer<'_>, - gate: &DeviceBuffer<'_>, - beta: &DeviceBuffer<'_>, - next_state: &mut DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - let original = Operation::GdnStep.layout(); - // Admit the WHOLE real allocations, including aliases outside the - // consumed ranges, before deriving any private pointer operands. - let mut whole = original; - whole.bytes = [3145728, 40960, 40960, 192, 192, 3145728, 24576, 0, 0]; - whole.align = [4; 9]; - whole.count = 7; - whole.outputs = 0b1100000; - let (asset, _, owners) = admission( - self, - &[state, qk, h, gate, beta, next_state, output], - Admission { - operation: Operation::GdnStep, - layout: Ok(whole), - asset: qwen_ffi::asset(Operation::GdnStep), - epsilon: 0.0, - in_place: false, - }, - )?; - let q = owners[1].checked_subspan(40960, 0, 8192)?; - let k = owners[1].checked_subspan(40960, 8192, 8192)?; - let v = owners[2].checked_subspan(40960, 16384, 24576)?; - let handles = [ - owners[0], q, k, v, owners[3], owners[4], owners[5], owners[6], owners[0], - ]; - ranges_layout(Operation::GdnStep, original, handles, original.bytes, false)?; - // Same asset, eight-operand ABI, geometry and completed execution as - // the original separate-input method. Runtime retains full finite - // producer checks and authenticated row ownership before this call. - execute( - self, - &self.qwen_kernels, - asset, - Arguments::with_layout(Operation::GdnStep, original, handles, 0.0), - ) - } - pub fn gdn_out_norm_f32( - &self, - input: &DeviceBuffer<'_>, - z: &DeviceBuffer<'_>, - gamma: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - epsilon: f32, - ) -> Result<()> { - self.qwen_call( - Operation::GdnOutNorm, - &[input, z, gamma, output], - epsilon, - false, - ) - } - /// One fixed512-expert/top10 router. Exact whole buffers are logits2048B, - /// IDs40B and weights40B; each is aligned4 and owned by this Context. - /// The typed producer validates finite logits before upload and validates - /// IDs/weights after readback. Driver success attests completion only. - pub fn qwen_route_top10( - &self, - logits: &DeviceBuffer<'_>, - ids: &mut DeviceBuffer<'_>, - weights: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call(Operation::RouteTop10, &[logits, ids, weights], 0.0, false) - } - /// BF16 weights × unchanged F32 vector, using the native adaptive MMVF - /// schedule. All raw weight/activation bit patterns remain admissible. - /// The output is publishable only after a successful completed return. - pub fn bf16_f32( - &self, - weights: &DeviceBuffer<'_>, - activation: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - shape: crate::Bf16ProjectionShape, - ) -> Result<()> { - let (asset, layout, handles) = admission( - self, - &[weights, activation, output], - Admission { - operation: Operation::Bf16, - layout: qwen_ffi::bf16_layout(shape.rows, shape.columns), - asset: qwen_ffi::asset(Operation::Bf16), - epsilon: 0.0, - in_place: false, - }, - ) - .map_err(|error| { - if error == Error::InvalidQwenShape { - Error::InvalidBf16ProjectionShape - } else { - error - } - })?; - let arguments = Arguments::with_layout(Operation::Bf16, layout, handles, 0.0); - execute(self, &self.qwen_kernels, asset, arguments) - } - pub(super) fn qwen_call( - &self, - operation: Operation, - buffers: &[&DeviceBuffer<'_>], - epsilon: f32, - in_place: bool, - ) -> Result<()> { - let (asset, layout, handles) = admission( - self, - buffers, - Admission { - operation, - layout: Ok(operation.layout()), - asset: qwen_ffi::asset(operation), - epsilon, - in_place, - }, - )?; - execute( - self, - &self.qwen_kernels, - asset, - Arguments::with_layout(operation, layout, handles, epsilon), - ) - } - pub(in super::super) fn unload_qwen_kernels(&self) -> Result<()> { - unload(self, &self.qwen_kernels) - } - - /// Complete one fixed layer GR read using the original five kernels and - /// original finite mask. Bit i denotes nonfinite values at stage i; the - /// caller uses the first set bit before publishing a stage result. This - /// opt-in composite has one final completion fence, never a pending result - /// or generic asynchronous capability. The old per-launch methods remain. - #[allow(clippy::too_many_arguments)] // Exact closed five-operation operand set. - pub fn gr_read_chain_queued( - &self, - residual: &DeviceBuffer<'_>, - gamma: &DeviceBuffer<'_>, - down_weights: &DeviceBuffer<'_>, - up_weights: &DeviceBuffer<'_>, - epsilon: f32, - xn: &mut DeviceBuffer<'_>, - down: &mut DeviceBuffer<'_>, - activated: &mut DeviceBuffer<'_>, - gates: &mut DeviceBuffer<'_>, - products: &mut DeviceBuffer<'_>, - mixed: &mut DeviceBuffer<'_>, - ) -> Result { - let inputs = [residual, gamma, down_weights, up_weights]; - let outputs = [&*xn, &*down, &*activated, &*gates, &*products, &*mixed]; - // Original per-operation layout, asset, Context and native index - // checks, all completed before any registration/allocation/mutation. - let admitted = [ - admission( - self, - &[residual, gamma, &*xn], - Admission { - operation: Operation::Norm, - layout: Ok(Operation::Norm.layout()), - asset: qwen_ffi::asset(Operation::Norm), - epsilon, - in_place: false, - }, - )?, - admission( - self, - &[down_weights, &*xn, &*down], - Admission { - operation: Operation::Down, - layout: Ok(Operation::Down.layout()), - asset: qwen_ffi::asset(Operation::Down), - epsilon, - in_place: false, - }, - )?, - admission( - self, - &[&*down, &*activated], - Admission { - operation: Operation::DownSilu, - layout: Ok(Operation::DownSilu.layout()), - asset: qwen_ffi::asset(Operation::DownSilu), - epsilon, - in_place: false, - }, - )?, - admission( - self, - &[up_weights, &*activated, &*gates], - Admission { - operation: Operation::Up, - layout: Ok(Operation::Up.layout()), - asset: qwen_ffi::asset(Operation::Up), - epsilon, - in_place: false, - }, - )?, - admission( - self, - &[&*xn, &*gates, &*products, &*mixed], - Admission { - operation: Operation::LayerGate, - layout: Ok(Operation::LayerGate.layout()), - asset: qwen_ffi::asset(Operation::LayerGate), - epsilon, - in_place: false, - }, - )?, - ]; - // Per-stage alias checks alone cannot see future weights or another - // stage output. Refuse every cross-stage alias before the first write. - for (i, output) in outputs.iter().enumerate() { - let handle = output.handle.ok_or(Error::ContextPoisoned)?; - for input in inputs { - if handle.overlaps( - output.bytes, - input.handle.ok_or(Error::ContextPoisoned)?, - input.bytes, - ) { - return Err(Error::OutputAliasesInput); - } - } - for prior in &outputs[..i] { - if handle.overlaps( - output.bytes, - prior.handle.ok_or(Error::ContextPoisoned)?, - prior.bytes, - ) { - return Err(Error::OutputAliasesInput); - } - } - } - if self - .allocated - .get() - .checked_add(4) - .ok_or(Error::InvalidQwenShape)? - > self.budget - { - return Err(Error::BudgetExceeded); - } - #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver")))] - { - return Err(Error::UnsupportedPlatform); - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] - { - let assets = std::array::from_fn(|i| admitted[i].0); - let kernels = prepare_gr_read_set(self, assets)?; - let status = self.allocate(4)?; - let result = (|| { - let status_handle = status.handle.ok_or(Error::ContextPoisoned)?; - let mut arguments: [Arguments; 5] = std::array::from_fn(|i| { - let (asset, layout, handles) = admitted[i]; - Arguments::with_layout(asset.operation, layout, handles, epsilon) - }); - let handles = [ - xn.handle.ok_or(Error::ContextPoisoned)?, - down.handle.ok_or(Error::ContextPoisoned)?, - activated.handle.ok_or(Error::ContextPoisoned)?, - gates.handle.ok_or(Error::ContextPoisoned)?, - products.handle.ok_or(Error::ContextPoisoned)?, - status_handle, - ]; - let mut finite_arguments = ffi::GrReadGuardArguments::new(handles); - // Owned host buffers outlive all attempted commands; never - // pass stack/borrowed readback storage to an uncertain driver. - let zero = vec![0u8; 4]; - let mut readback = vec![0u8; 4]; - let guard = self.enter()?; - let mut commands = self.driver.api.copy_from(status_handle, &zero); - for (i, argument) in arguments.iter_mut().enumerate() { - if commands.is_err() { - break; - } - commands = self.driver.api.launch_qwen( - kernels[i].function, - assets[i].operation, - argument, - ); - } - if commands.is_ok() { - commands = self - .driver - .api - .launch_gr_read_guard(kernels[5].function, &mut finite_arguments); - } - if commands.is_ok() { - commands = self.driver.api.copy_to(status_handle, &mut readback); - } - // Fence ALL attempted same-stream commands even on a failed - // enqueue. Launch/copy -> sync -> restore retains precedence. - let sync = self.driver.api.synchronize(); - if sync.is_err() { - self.poison(); - self.retain_driver(); - } - let pop = guard.finish(); - if sync.is_err() || pop.is_err() { - std::mem::forget((arguments, finite_arguments, zero, readback)); - return combine(combine(commands, sync), pop).map(|()| 0); - } - combine(combine(commands, sync), pop)?; - let mask = u32::from_le_bytes( - readback - .as_slice() - .try_into() - .map_err(|_| Error::InvalidQwenShape)?, - ); - if mask & !31 != 0 { - return Err(Error::InvalidDriverValue("GR finite witness")); - } - Ok(mask) - })(); - combine(result, status.release()) - } - } - - /// BF16[320,10240] weights × unchanged F32[10240] -> F32[320]. - /// The fixed asset must have a separate numerical qualification receipt. - pub fn gr_down_projection_bf16_f32( - &self, - weights: &DeviceBuffer<'_>, - activation: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call(Operation::Down, &[weights, activation, output], 0.0, false) - } - /// BF16[10240,320] weights × unchanged F32[320] -> F32[10240]. - pub fn gr_up_projection_bf16_f32( - &self, - weights: &DeviceBuffer<'_>, - activation: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call(Operation::Up, &[weights, activation, output], 0.0, false) - } - /// BF16[4,10240] weights × unchanged F32[10240] -> F32[4]. - pub fn gr_inject_projection_bf16_f32( - &self, - weights: &DeviceBuffer<'_>, - activation: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call( - Operation::InjectProjection, - &[weights, activation, output], - 0.0, - false, - ) - } - /// Weighted RMS over four streams of2560 F32 elements. Epsilon is finite - /// and nonnegative (including -0.0), matching the native launch refusal. - /// Outputs publish only after completion and restoration. - pub fn gr_norm_f32( - &self, - residual: &DeviceBuffer<'_>, - gamma: &DeviceBuffer<'_>, - epsilon: f32, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call(Operation::Norm, &[residual, gamma, output], epsilon, false) - } - /// Fixed source-ordered division byHC=4 followed by SiLU on320 F32 values. - pub fn gr_down_silu_hc_f32( - &self, - down: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call(Operation::DownSilu, &[down, output], 0.0, false) - } - /// Layer GR: separate products and ascending stream fused accumulation. - /// xn/gates/products are F32[4,2560], mixed is F32[2560]. - pub fn gr_gate_mean_layer_fused_f32( - &self, - xn: &DeviceBuffer<'_>, - gates: &DeviceBuffer<'_>, - products: &mut DeviceBuffer<'_>, - mixed: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call( - Operation::LayerGate, - &[xn, gates, products, mixed], - 0.0, - false, - ) - } - /// Final GR: the qualified unfused product/add order, without injection. - /// xn/gates/products are F32[4,2560], mixed is F32[2560]. - pub fn gr_gate_mean_final_unfused_f32( - &self, - xn: &DeviceBuffer<'_>, - gates: &DeviceBuffer<'_>, - products: &mut DeviceBuffer<'_>, - mixed: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call( - Operation::FinalGate, - &[xn, gates, products, mixed], - 0.0, - false, - ) - } - /// Inject shared block_out[2560] with four scalar inject values into a - /// separate residual[4,2560] output. All values/storage are F32. - pub fn gr_inject_residual_f32( - &self, - residual: &DeviceBuffer<'_>, - block_out: &DeviceBuffer<'_>, - inject: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call( - Operation::InjectResidual, - &[residual, block_out, inject, output], - 0.0, - false, - ) - } - /// Same-element in-place variant of the exact same fixed injection slot. - /// The mutable buffer is both R and R_out; no partial alias is admitted. - pub fn gr_inject_residual_in_place_f32( - &self, - residual: &mut DeviceBuffer<'_>, - block_out: &DeviceBuffer<'_>, - inject: &DeviceBuffer<'_>, - ) -> Result<()> { - self.qwen_call( - Operation::InjectResidual, - &[residual, block_out, inject, residual], - 0.0, - true, - ) - } -} +#[path = "impl_context/impl_context_2.rs"] +mod impl_context_2; +#[path = "impl_context/impl_context_2_2.rs"] +mod impl_context_2_2; +#[path = "impl_context/impl_context_3.rs"] +mod impl_context_3; +#[path = "impl_context/impl_context_4.rs"] +mod impl_context_4; +#[path = "impl_context/impl_context_5.rs"] +mod impl_context_5; +#[path = "impl_context/impl_context_6.rs"] +mod impl_context_6; +#[path = "impl_context/impl_context_7.rs"] +mod impl_context_7; diff --git a/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_2.rs b/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_2.rs new file mode 100644 index 00000000..172a7464 --- /dev/null +++ b/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_2.rs @@ -0,0 +1,248 @@ +//! Moved out of the parent module by STRA-338: impl Context. + +#[allow(unused_imports)] +use super::*; + + + +impl Context<'_> { + /// Source-defined fixed 2560-value embedding RMS normalization. The + /// producer validates finite semantic output after completed dispatch. + #[allow(clippy::too_many_arguments)] // Fixed source ABI operands, not caller selected geometry. + pub fn mtp_gr_attention_down( + &self, + r: &DeviceBuffer<'_>, + norm: &DeviceBuffer<'_>, + down: &DeviceBuffer<'_>, + inject: &DeviceBuffer<'_>, + lo: &mut DeviceBuffer<'_>, + rs: &mut DeviceBuffer<'_>, + injout: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call( + Operation::MtpGrAttentionDown, + &[r, norm, down, inject, lo, rs, injout], + 0.0, + false, + ) + } + + #[allow(clippy::too_many_arguments)] // Fixed source ABI operands, not caller selected geometry. + pub fn mtp_gr_attention_up( + &self, + r: &DeviceBuffer<'_>, + norm: &DeviceBuffer<'_>, + up: &DeviceBuffer<'_>, + lo: &DeviceBuffer<'_>, + rs: &DeviceBuffer<'_>, + mixed: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call( + Operation::MtpGrAttentionUp, + &[r, norm, up, lo, rs, mixed], + 0.0, + false, + ) + } + + #[allow(clippy::too_many_arguments)] // Fixed source ABI operands, not caller selected geometry. + pub fn mtp_gr_mlp_down( + &self, + r: &DeviceBuffer<'_>, + bo: &DeviceBuffer<'_>, + inj: &DeviceBuffer<'_>, + norm: &DeviceBuffer<'_>, + down: &DeviceBuffer<'_>, + inject: &DeviceBuffer<'_>, + lo: &mut DeviceBuffer<'_>, + rs: &mut DeviceBuffer<'_>, + injout: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call( + Operation::MtpGrMlpDown, + &[r, bo, inj, norm, down, inject, lo, rs, injout], + 0.0, + false, + ) + } + + #[allow(clippy::too_many_arguments)] // Fixed source ABI operands, not caller selected geometry. + pub fn mtp_gr_mlp_up( + &self, + r: &DeviceBuffer<'_>, + bo: &DeviceBuffer<'_>, + inj: &DeviceBuffer<'_>, + norm: &DeviceBuffer<'_>, + up: &DeviceBuffer<'_>, + lo: &DeviceBuffer<'_>, + rs: &DeviceBuffer<'_>, + rout: &mut DeviceBuffer<'_>, + mixed: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call( + Operation::MtpGrMlpUp, + &[r, bo, inj, norm, up, lo, rs, rout, mixed], + 0.0, + false, + ) + } + + #[allow(clippy::too_many_arguments)] // Fixed source ABI operands, not caller selected geometry. + pub fn mtp_quantize_scaled_2560( + &self, + input: &DeviceBuffer<'_>, + q: &mut DeviceBuffer<'_>, + scales: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call(Operation::MtpQuant2560, &[input, q, scales], 0.0, false) + } + + #[allow(clippy::too_many_arguments)] // Fixed source ABI operands, not caller selected geometry. + pub fn mtp_quantize_scaled_640( + &self, + input: &DeviceBuffer<'_>, + q: &mut DeviceBuffer<'_>, + scales: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call(Operation::MtpQuant640, &[input, q, scales], 0.0, false) + } + + #[allow(clippy::too_many_arguments)] // Fixed source ABI operands, not caller selected geometry. + pub fn mtp_s2_gate_up_tile( + &self, + codes: &DeviceBuffer<'_>, + halfscales: &DeviceBuffer<'_>, + q: &DeviceBuffer<'_>, + xscales: &DeviceBuffer<'_>, + out: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call( + Operation::MtpS2GateUp, + &[codes, halfscales, q, xscales, out], + 0.0, + false, + ) + } + + #[allow(clippy::too_many_arguments)] // Fixed source ABI operands, not caller selected geometry. + pub fn mtp_s2_down_tile( + &self, + codes: &DeviceBuffer<'_>, + halfscales: &DeviceBuffer<'_>, + q: &DeviceBuffer<'_>, + xscales: &DeviceBuffer<'_>, + out: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call( + Operation::MtpS2Down, + &[codes, halfscales, q, xscales, out], + 0.0, + false, + ) + } + + /// Original512-expert S2 bank; exactly640 gate then640 up results. + /// No row/plane slices or caller geometry are exposed. + pub fn mtp_s2_gate_up_full( + &self, + bank: &DeviceBuffer<'_>, + expert: u32, + q: &DeviceBuffer<'_>, + xscales: &DeviceBuffer<'_>, + out: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.mtp_s2_full_call(Operation::MtpS2GateUpFull, bank, expert, q, xscales, out) + } + + /// Original512-expert S2 bank; exactly2560 down results. + pub fn mtp_s2_down_full( + &self, + bank: &DeviceBuffer<'_>, + expert: u32, + q: &DeviceBuffer<'_>, + xscales: &DeviceBuffer<'_>, + out: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.mtp_s2_full_call(Operation::MtpS2DownFull, bank, expert, q, xscales, out) + } + + #[allow(clippy::too_many_arguments)] // Two closed source ABIs, no caller geometry. + pub(in super::super) fn mtp_s2_full_call( + &self, + operation: Operation, + bank: &DeviceBuffer<'_>, + expert: u32, + q: &DeviceBuffer<'_>, + xscales: &DeviceBuffer<'_>, + out: &mut DeviceBuffer<'_>, + ) -> Result<()> { + let layout = qwen_ffi::mtp_s2_full_layout(operation, expert)?; + let (asset, layout, handles) = admission( + self, + &[bank, q, xscales, out], + Admission { + operation, + layout: Ok(layout), + asset: qwen_ffi::asset(operation), + epsilon: 0.0, + in_place: false, + }, + )?; + execute( + self, + &self.qwen_kernels, + asset, + Arguments::with_layout(operation, layout, handles, 0.0), + ) + } + + #[allow(clippy::too_many_arguments)] // Fixed source ABI operands, not caller selected geometry. + pub fn mtp_swiglu_640( + &self, + gateup: &DeviceBuffer<'_>, + out: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call(Operation::MtpS2Swiglu, &[gateup, out], 0.0, false) + } + pub fn mtp_embedding_norm_f32( + &self, + input: &DeviceBuffer<'_>, + gamma: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call( + Operation::MtpEmbeddingNorm, + &[input, gamma, output], + 0.0, + false, + ) + } + /// Normalize all four hidden streams together over exactly 10240 values. + pub fn mtp_hidden_norm_f32( + &self, + input: &DeviceBuffer<'_>, + gamma: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call( + Operation::MtpHiddenNorm, + &[input, gamma, output], + 0.0, + false, + ) + } + /// Add the normalized embedding independently to each hidden stream. + pub fn mtp_broadcast_f32( + &self, + hidden: &DeviceBuffer<'_>, + embedding: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call( + Operation::MtpBroadcast, + &[hidden, embedding, output], + 0.0, + false, + ) + } +} diff --git a/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_2_2.rs b/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_2_2.rs new file mode 100644 index 00000000..e20c0f42 --- /dev/null +++ b/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_2_2.rs @@ -0,0 +1,255 @@ +//! Moved out of the parent module by STRA-338: impl Context (2). + +#[allow(unused_imports)] +use super::*; + + + +impl Context<'_> { + + /// Closed causal dense MTP attention, FP16 cell-major K/V in ascending + /// window order. Position determines width; scratch and launch dimensions + /// are internal. Completion is distinct from producer finite publication. + pub fn mtp_dense_attend_f16( + &self, + query: &DeviceBuffer<'_>, + keys: &DeviceBuffer<'_>, + values: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + position: u32, + ) -> Result<()> { + let chunk_layout = qwen_ffi::mtp_dense_layout(Operation::MtpDenseChunk, position)?; + let merge_layout = qwen_ffi::mtp_dense_layout(Operation::MtpDenseMerge, position)?; + let chunk_asset = + qwen_ffi::asset(Operation::MtpDenseChunk).ok_or(Error::UnsupportedQwenOperation)?; + let merge_asset = + qwen_ffi::asset(Operation::MtpDenseMerge).ok_or(Error::UnsupportedQwenOperation)?; + chunk_asset.validate(Operation::MtpDenseChunk)?; + merge_asset.validate(Operation::MtpDenseMerge)?; + if self.poisoned() { + return Err(Error::ContextPoisoned); + } + let inputs = [query, keys, values, &*output]; + let expected = [ + chunk_layout.bytes[0], + chunk_layout.bytes[1], + chunk_layout.bytes[2], + merge_layout.bytes[3], + ]; + for (i, buffer) in inputs.iter().enumerate() { + if !std::ptr::eq(self, buffer.context) { + return Err(Error::ContextMismatch); + } + if buffer.bytes != expected[i] { + return Err(Error::InvalidQwenShape); + } + let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; + handle + .validate_projection_extent(expected[i], if i < 3 { 16 } else { 4 }) + .map_err(|_| Error::InvalidQwenShape)?; + for other in inputs.iter().take(i) { + if handle.overlaps( + buffer.bytes, + other.handle.ok_or(Error::ContextPoisoned)?, + other.bytes, + ) { + return Err(Error::OutputAliasesInput); + } + } + } + let scratch = chunk_layout.bytes[3..6] + .iter() + .try_fold(256usize, |sum, size| sum.checked_add(*size)) + .ok_or(Error::InvalidQwenShape)?; + if self + .allocated + .get() + .checked_add(scratch) + .is_none_or(|n| n > self.budget) + { + return Err(Error::BudgetExceeded); + } + // Every allocation is retained by an owner through both synchronized + // launches. Existing failed-free charges/poison policy remain active. + let [acc, max, sum, padding] = owned_mtp_scratch( + self, + [ + chunk_layout.bytes[3], + chunk_layout.bytes[4], + chunk_layout.bytes[5], + 256, + ], + )?; + let result = (|| { + let (chunk, cl, ch) = admission( + self, + &[query, keys, values, &acc, &max, &sum], + Admission { + operation: Operation::MtpDenseChunk, + layout: Ok(chunk_layout), + asset: Some(chunk_asset), + epsilon: 0.0, + in_place: false, + }, + )?; + let (merge, ml, mh) = admission( + self, + &[&acc, &max, &sum, output], + Admission { + operation: Operation::MtpDenseMerge, + layout: Ok(merge_layout), + asset: Some(merge_asset), + epsilon: 0.0, + in_place: false, + }, + )?; + prepare_pair(self, &self.qwen_kernels, [chunk, merge]) + .and_then(|()| { + execute( + self, + &self.qwen_kernels, + chunk, + Arguments::with_layout(Operation::MtpDenseChunk, cl, ch, 0.0), + ) + }) + .and_then(|()| { + execute( + self, + &self.qwen_kernels, + merge, + Arguments::with_layout(Operation::MtpDenseMerge, ml, mh, 0.0), + ) + }) + })(); + let result = combine(result, acc.release()); + let result = combine(result, max.release()); + let result = combine(result, sum.release()); + combine(result, padding.release()) + } + + // Private transport-only adapter; original public attention remains exact. + pub(in super::super::super) fn mtp_dense_attend_ring_f16( + &self, + query: &DeviceBuffer<'_>, + keys: &DeviceBuffer<'_>, + values: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + position: u32, + offset: usize, + ) -> Result<()> { + let chunk_layout = qwen_ffi::mtp_dense_layout(Operation::MtpDenseChunk, position)?; + let merge_layout = qwen_ffi::mtp_dense_layout(Operation::MtpDenseMerge, position)?; + let chunk_asset = + qwen_ffi::asset(Operation::MtpDenseChunk).ok_or(Error::UnsupportedQwenOperation)?; + let merge_asset = + qwen_ffi::asset(Operation::MtpDenseMerge).ok_or(Error::UnsupportedQwenOperation)?; + chunk_asset.validate(Operation::MtpDenseChunk)?; + merge_asset.validate(Operation::MtpDenseMerge)?; + if self.poisoned() { + return Err(Error::ContextPoisoned); + } + // Full allocations are owned by the opaque ring. Only checked active + // chronological spans enter the unchanged chunk/merge ABI. + let inputs = [query, keys, values, &*output]; + let expected = [ + chunk_layout.bytes[0], + super::super::super::mtp_dense_kv::HALF_RING_BYTES, + super::super::super::mtp_dense_kv::HALF_RING_BYTES, + merge_layout.bytes[3], + ]; + let mut active = [query.handle.ok_or(Error::ContextPoisoned)?; 4]; + for (i, buffer) in inputs.iter().enumerate() { + if !std::ptr::eq(self, buffer.context) { + return Err(Error::ContextMismatch); + } + if buffer.bytes != expected[i] { + return Err(Error::InvalidQwenShape); + } + let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; + handle.validate_projection_extent(expected[i], if i < 3 { 16 } else { 4 })?; + for other in inputs.iter().take(i) { + if handle.overlaps( + buffer.bytes, + other.handle.ok_or(Error::ContextPoisoned)?, + other.bytes, + ) { + return Err(Error::OutputAliasesInput); + } + } + active[i] = if i == 1 || i == 2 { + handle.checked_subspan(buffer.bytes, offset, chunk_layout.bytes[i])? + } else { + handle + }; + } + let scratch = chunk_layout.bytes[3..6] + .iter() + .try_fold(256usize, |sum, size| sum.checked_add(*size)) + .ok_or(Error::InvalidQwenShape)?; + if self + .allocated + .get() + .checked_add(scratch) + .is_none_or(|n| n > self.budget) + { + return Err(Error::BudgetExceeded); + } + // Every allocation is retained by an owner through both synchronized + // launches. Existing failed-free charges/poison policy remain active. + let [acc, max, sum, padding] = owned_mtp_scratch( + self, + [ + chunk_layout.bytes[3], + chunk_layout.bytes[4], + chunk_layout.bytes[5], + 256, + ], + )?; + let result = (|| { + let chunk = chunk_asset; + let cl = chunk_layout; + let mut ch = [active[0]; 9]; + ch[..6].copy_from_slice(&[ + active[0], + active[1], + active[2], + acc.handle.ok_or(Error::ContextPoisoned)?, + max.handle.ok_or(Error::ContextPoisoned)?, + sum.handle.ok_or(Error::ContextPoisoned)?, + ]); + ranges_layout(Operation::MtpDenseChunk, cl, ch, cl.bytes, false)?; + let (merge, ml, mh) = admission( + self, + &[&acc, &max, &sum, output], + Admission { + operation: Operation::MtpDenseMerge, + layout: Ok(merge_layout), + asset: Some(merge_asset), + epsilon: 0.0, + in_place: false, + }, + )?; + prepare_pair(self, &self.qwen_kernels, [chunk, merge]) + .and_then(|()| { + execute( + self, + &self.qwen_kernels, + chunk, + Arguments::with_layout(Operation::MtpDenseChunk, cl, ch, 0.0), + ) + }) + .and_then(|()| { + execute( + self, + &self.qwen_kernels, + merge, + Arguments::with_layout(Operation::MtpDenseMerge, ml, mh, 0.0), + ) + }) + })(); + let result = combine(result, acc.release()); + let result = combine(result, max.release()); + let result = combine(result, sum.release()); + combine(result, padding.release()) + } +} diff --git a/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_3.rs b/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_3.rs new file mode 100644 index 00000000..96f17612 --- /dev/null +++ b/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_3.rs @@ -0,0 +1,251 @@ +//! Moved out of the parent module by STRA-338: impl Context (3). + +#[allow(unused_imports)] +use super::*; + + + +impl Context<'_> { + + pub(in super::super) fn kar_ple_call( + &self, + operation: Operation, + buffers: &[&DeviceBuffer<'_>], + value: u32, + ) -> Result<()> { + let (asset, layout, handles) = admission( + self, + buffers, + Admission { + operation, + layout: qwen_ffi::kar_ple_layout(operation, value), + asset: qwen_ffi::asset(operation), + epsilon: 0.0, + in_place: false, + }, + )?; + execute( + self, + &self.qwen_kernels, + asset, + Arguments::with_layout(operation, layout, handles, 0.0), + ) + } + + /// Fixed experimental PLE row-cache scatter. Missing qualification refuses + /// before native mutation. Zero misses must skip this call. + pub fn kar_ple_scatter( + &self, + cache: &mut DeviceBuffer<'_>, + updates: &DeviceBuffer<'_>, + count: u32, + ) -> Result<()> { + self.kar_ple_call(Operation::KarPleScatter, &[cache, updates], count) + } + + /// Decode exactly sixteen fixed L2 PLE rows. Partition count is derived + /// from the exact four-FP16 book extent; the producer validates row data. + pub fn kar_ple_decode( + &self, + cache: &DeviceBuffer<'_>, + slots: &DeviceBuffer<'_>, + books: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + if !books.bytes.is_multiple_of(8) { + return Err(Error::InvalidQwenShape); + } + let parts = u32::try_from(books.bytes / 8).map_err(|_| Error::InvalidQwenShape)?; + self.kar_ple_call( + Operation::KarPleDecode, + &[cache, slots, books, output], + parts, + ) + } + + pub(in super::super) fn qsa_call( + &self, + operation: Operation, + buffers: &[&DeviceBuffer<'_>], + value: u32, + ) -> Result<()> { + // These four fixed kernels bake the identity RoPE (a private theta word, no scaling arguments); the + // committed assets cannot rotate a scaled context, so a scaled serving context must never reach them. + if matches!( + operation, + Operation::QsaRopeQ + | Operation::QsaRopeK + | Operation::QsaRopeIndexQ + | Operation::QsaIndexAppend + ) && crate::serving_context::serving_context().rope_is_scaled() + { + return Err(Error::UnsupportedQwenOperation); + } + let (asset, layout, handles) = admission( + self, + buffers, + Admission { + operation, + layout: qwen_ffi::qsa_layout(operation, value), + asset: qwen_ffi::asset(operation), + epsilon: 0.0, + in_place: false, + }, + )?; + execute( + self, + &self.qwen_kernels, + asset, + Arguments::with_layout(operation, layout, handles, 0.0), + ) + } + + /// Closed QSA split q gate; unqualified assets refuse before mutation. + pub fn qsa_split_q_gate( + &self, + full: &DeviceBuffer<'_>, + query: &mut DeviceBuffer<'_>, + gate: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call(Operation::QsaSplit, &[full, query, gate], 0.0, false) + } + + /// Closed QSA norm q; unqualified assets refuse before mutation. + pub fn qsa_norm_q( + &self, + input: &DeviceBuffer<'_>, + gamma: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call(Operation::QsaNormQ, &[input, gamma, output], 0.0, false) + } + + /// Closed QSA norm k; unqualified assets refuse before mutation. + pub fn qsa_norm_k( + &self, + input: &DeviceBuffer<'_>, + gamma: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call(Operation::QsaNormK, &[input, gamma, output], 0.0, false) + } + + /// Closed QSA norm index q; unqualified assets refuse before mutation. + pub fn qsa_norm_index_q( + &self, + input: &DeviceBuffer<'_>, + gamma: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call( + Operation::QsaNormIndexQ, + &[input, gamma, output], + 0.0, + false, + ) + } + + /// Closed QSA rope q; unqualified assets refuse before mutation. + pub fn qsa_rope_q( + &self, + input: &DeviceBuffer<'_>, + position: u32, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qsa_call(Operation::QsaRopeQ, &[input, output], position) + } + + /// Closed QSA rope k; unqualified assets refuse before mutation. + pub fn qsa_rope_k( + &self, + input: &DeviceBuffer<'_>, + position: u32, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qsa_call(Operation::QsaRopeK, &[input, output], position) + } + + /// Closed QSA rope index q; unqualified assets refuse before mutation. + pub fn qsa_rope_index_q( + &self, + input: &DeviceBuffer<'_>, + position: u32, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qsa_call(Operation::QsaRopeIndexQ, &[input, output], position) + } + + /// Closed QSA index append; unqualified assets refuse before mutation. + pub fn qsa_index_append( + &self, + raw: &DeviceBuffer<'_>, + gamma: &DeviceBuffer<'_>, + prior: &DeviceBuffer<'_>, + next: &mut DeviceBuffer<'_>, + position: u32, + ) -> Result<()> { + self.qsa_call( + Operation::QsaIndexAppend, + &[raw, gamma, prior, next], + position, + ) + } + + /// Closed QSA pack kv; unqualified assets refuse before mutation. + pub fn qsa_pack_kv( + &self, + key: &DeviceBuffer<'_>, + value: &DeviceBuffer<'_>, + packed_key: &mut DeviceBuffer<'_>, + packed_value: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call( + Operation::QsaPackKv, + &[key, value, packed_key, packed_value], + 0.0, + false, + ) + } + + /// Closed QSA block scores; unqualified assets refuse before mutation. + pub fn qsa_block_scores( + &self, + pooled: &DeviceBuffer<'_>, + dead: &DeviceBuffer<'_>, + index_query: &DeviceBuffer<'_>, + scores: &mut DeviceBuffer<'_>, + position: u32, + ) -> Result<()> { + self.qsa_call( + Operation::QsaBlockScores, + &[pooled, dead, index_query, scores], + position, + ) + } + + /// Score only the exact initialized prefix of a bounded pooled-key owner. + /// The original operation admission still checks shapes, context, aliases, + /// qualification and budget. The scoped view never owns or frees memory. + pub fn qsa_block_scores_prefix( + &self, + pooled: &DeviceBuffer<'_>, + dead: &DeviceBuffer<'_>, + index_query: &DeviceBuffer<'_>, + scores: &mut DeviceBuffer<'_>, + position: u32, + ) -> Result<()> { + let layout = qwen_ffi::qsa_layout(Operation::QsaBlockScores, position)?; + let bytes = layout.bytes[0]; + if bytes == 0 || bytes > pooled.bytes { + return Err(Error::InvalidQwenShape); + } + let view = std::mem::ManuallyDrop::new(DeviceBuffer { + context: pooled.context, + handle: pooled.handle, + bytes, + _thread: std::marker::PhantomData, + borrowed: false, + }); + self.qsa_block_scores(&view, dead, index_query, scores, position) + } +} diff --git a/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_4.rs b/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_4.rs new file mode 100644 index 00000000..4182557f --- /dev/null +++ b/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_4.rs @@ -0,0 +1,255 @@ +//! Moved out of the parent module by STRA-338: impl Context (4). + +#[allow(unused_imports)] +use super::*; + + + +impl Context<'_> { + + /// Closed QSA block topk; unqualified assets refuse before mutation. + pub fn qsa_block_topk( + &self, + scores: &DeviceBuffer<'_>, + ids: &mut DeviceBuffer<'_>, + position: u32, + ) -> Result<()> { + self.qsa_call(Operation::QsaBlockTopk, &[scores, ids], position) + } + + /// Closed QSA attend; unqualified assets refuse before mutation. + pub fn qsa_attend( + &self, + query: &DeviceBuffer<'_>, + packed_key: &DeviceBuffer<'_>, + packed_value: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + width: u32, + ) -> Result<()> { + self.qsa_call( + Operation::QsaAttend, + &[query, packed_key, packed_value, output], + width, + ) + } + + /// Closed QSA gate f32; unqualified assets refuse before mutation. + pub fn qsa_gate_f32( + &self, + attention: &DeviceBuffer<'_>, + gate: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call(Operation::QsaGate, &[attention, gate, output], 0.0, false) + } + + /// Native quantized-expert SwiGLU on two fixed 640-value F32 vectors. + pub fn moe_swiglu_f32( + &self, + gate: &DeviceBuffer<'_>, + up: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call(Operation::MoeSwiglu, &[gate, up, output], 0.0, false) + } + + /// Original BF16-rounded activation and DOUBLE shared scalar reduction. + pub fn moe_shared_scalar_f32_bf16( + &self, + input: &DeviceBuffer<'_>, + weights: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call( + Operation::MoeSharedScalar, + &[input, weights, output], + 0.0, + false, + ) + } + + /// Scale one shared 2560-value vector by its completed scalar gate. + pub fn moe_shared_scale_f32( + &self, + input: &DeviceBuffer<'_>, + scalar: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call( + Operation::MoeSharedScale, + &[input, scalar, output], + 0.0, + false, + ) + } + + /// Original ordered DOUBLE reduction of ten routed outputs plus shared. + /// All buffers store F32; only the fixed kernel's accumulator is F64. + pub fn moe_combine_f64( + &self, + parts: &DeviceBuffer<'_>, + weights: &DeviceBuffer<'_>, + shared: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call( + Operation::MoeCombine, + &[parts, weights, shared, output], + 0.0, + false, + ) + } + + /// Fixed PLE value projection: BF16-rounded activation, source double sum. + pub fn ple_value_bf16_f32( + &self, + embedding: &DeviceBuffer<'_>, + weights: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call( + Operation::PleValue, + &[embedding, weights, output], + 0.0, + false, + ) + } + + /// Complete fixed PLE Value projection; forty CTAs preserve each serial row sum. + pub fn ple_value_full_bf16_f32( + &self, + embedding: &DeviceBuffer<'_>, + weights: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call( + Operation::PleValueFull, + &[embedding, weights, output], + 0.0, + false, + ) + } + + /// Four PLE streams with the source's ordinary CUDA normalization profile. + pub fn ple_grouped_norm_f32( + &self, + input: &DeviceBuffer<'_>, + gamma: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call(Operation::PleNorm, &[input, gamma, output], 0.0, false) + } + + pub fn ple_signed_gate_f32( + &self, + key: &DeviceBuffer<'_>, + query: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call(Operation::PleGate, &[key, query, output], 0.0, false) + } + + pub fn ple_broadcast_f32( + &self, + value: &DeviceBuffer<'_>, + gate: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call(Operation::PleBroadcast, &[value, gate, output], 0.0, false) + } + + /// Nine row-fastest history entries per channel; candidate outputs disjoint. + pub fn ple_conv_history_f32( + &self, + prior: &DeviceBuffer<'_>, + normalized: &DeviceBuffer<'_>, + weights: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + next: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call( + Operation::PleConv, + &[prior, normalized, weights, output, next], + 0.0, + false, + ) + } + + pub fn ple_residual_f32( + &self, + residual: &DeviceBuffer<'_>, + gated: &DeviceBuffer<'_>, + convolution: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call( + Operation::PleResidual, + &[residual, gated, convolution, output], + 0.0, + false, + ) + } + + /// Fixed decomposed GDN convolution over10240 channels and three prior taps. + pub fn gdn_conv_silu_f32( + &self, + history: &DeviceBuffer<'_>, + input: &DeviceBuffer<'_>, + weights: &DeviceBuffer<'_>, + next_history: &mut DeviceBuffer<'_>, + raw: &mut DeviceBuffer<'_>, + h: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call( + Operation::GdnConv, + &[history, input, weights, next_history, raw, h], + 0.0, + false, + ) + } + /// Normalizes32 Q/K rows. Only the first4096 F32 values are written. + pub fn gdn_qk_l2_f32( + &self, + h: &DeviceBuffer<'_>, + normalized: &mut DeviceBuffer<'_>, + epsilon: f32, + ) -> Result<()> { + self.qwen_call(Operation::GdnQk, &[h, normalized], epsilon, false) + } + pub fn gdn_beta_sigmoid_f32( + &self, + beta: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call(Operation::GdnBeta, &[beta, output], 0.0, false) + } + pub fn gdn_gate_softplus_f32( + &self, + alpha: &DeviceBuffer<'_>, + dt: &DeviceBuffer<'_>, + a: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call(Operation::GdnGate, &[alpha, dt, a, output], 0.0, false) + } + /// Fixed state[(row*48+head)*128+column]; outputs are disjoint candidates. + #[allow(clippy::too_many_arguments)] // Eight distinct source-defined pointer operands. + pub fn gdn_step_f32( + &self, + state: &DeviceBuffer<'_>, + q: &DeviceBuffer<'_>, + k: &DeviceBuffer<'_>, + v: &DeviceBuffer<'_>, + gate: &DeviceBuffer<'_>, + beta: &DeviceBuffer<'_>, + next_state: &mut DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call( + Operation::GdnStep, + &[state, q, k, v, gate, beta, next_state, output], + 0.0, + false, + ) + } +} diff --git a/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_5.rs b/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_5.rs new file mode 100644 index 00000000..57f2eb01 --- /dev/null +++ b/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_5.rs @@ -0,0 +1,144 @@ +//! Moved out of the parent module by STRA-338: impl Context (5). + +#[allow(unused_imports)] +use super::*; + + + +impl Context<'_> { + /// The unchanged recurrence consumes fixed Q/K/V ranges of completed + /// producer allocations. No general buffer view or range is exposed. + #[allow(clippy::too_many_arguments)] // Seven fixed source-defined owners. + pub fn gdn_step_from_products_f32( + &self, + state: &DeviceBuffer<'_>, + qk: &DeviceBuffer<'_>, + h: &DeviceBuffer<'_>, + gate: &DeviceBuffer<'_>, + beta: &DeviceBuffer<'_>, + next_state: &mut DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + let original = Operation::GdnStep.layout(); + // Admit the WHOLE real allocations, including aliases outside the + // consumed ranges, before deriving any private pointer operands. + let mut whole = original; + whole.bytes = [3145728, 40960, 40960, 192, 192, 3145728, 24576, 0, 0]; + whole.align = [4; 9]; + whole.count = 7; + whole.outputs = 0b1100000; + let (asset, _, owners) = admission( + self, + &[state, qk, h, gate, beta, next_state, output], + Admission { + operation: Operation::GdnStep, + layout: Ok(whole), + asset: qwen_ffi::asset(Operation::GdnStep), + epsilon: 0.0, + in_place: false, + }, + )?; + let q = owners[1].checked_subspan(40960, 0, 8192)?; + let k = owners[1].checked_subspan(40960, 8192, 8192)?; + let v = owners[2].checked_subspan(40960, 16384, 24576)?; + let handles = [ + owners[0], q, k, v, owners[3], owners[4], owners[5], owners[6], owners[0], + ]; + ranges_layout(Operation::GdnStep, original, handles, original.bytes, false)?; + // Same asset, eight-operand ABI, geometry and completed execution as + // the original separate-input method. Runtime retains full finite + // producer checks and authenticated row ownership before this call. + execute( + self, + &self.qwen_kernels, + asset, + Arguments::with_layout(Operation::GdnStep, original, handles, 0.0), + ) + } + pub fn gdn_out_norm_f32( + &self, + input: &DeviceBuffer<'_>, + z: &DeviceBuffer<'_>, + gamma: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + epsilon: f32, + ) -> Result<()> { + self.qwen_call( + Operation::GdnOutNorm, + &[input, z, gamma, output], + epsilon, + false, + ) + } + /// One fixed512-expert/top10 router. Exact whole buffers are logits2048B, + /// IDs40B and weights40B; each is aligned4 and owned by this Context. + /// The typed producer validates finite logits before upload and validates + /// IDs/weights after readback. Driver success attests completion only. + pub fn qwen_route_top10( + &self, + logits: &DeviceBuffer<'_>, + ids: &mut DeviceBuffer<'_>, + weights: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call(Operation::RouteTop10, &[logits, ids, weights], 0.0, false) + } + /// BF16 weights × unchanged F32 vector, using the native adaptive MMVF + /// schedule. All raw weight/activation bit patterns remain admissible. + /// The output is publishable only after a successful completed return. + pub fn bf16_f32( + &self, + weights: &DeviceBuffer<'_>, + activation: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + shape: crate::Bf16ProjectionShape, + ) -> Result<()> { + let (asset, layout, handles) = admission( + self, + &[weights, activation, output], + Admission { + operation: Operation::Bf16, + layout: qwen_ffi::bf16_layout(shape.rows, shape.columns), + asset: qwen_ffi::asset(Operation::Bf16), + epsilon: 0.0, + in_place: false, + }, + ) + .map_err(|error| { + if error == Error::InvalidQwenShape { + Error::InvalidBf16ProjectionShape + } else { + error + } + })?; + let arguments = Arguments::with_layout(Operation::Bf16, layout, handles, 0.0); + execute(self, &self.qwen_kernels, asset, arguments) + } + pub(in super::super) fn qwen_call( + &self, + operation: Operation, + buffers: &[&DeviceBuffer<'_>], + epsilon: f32, + in_place: bool, + ) -> Result<()> { + let (asset, layout, handles) = admission( + self, + buffers, + Admission { + operation, + layout: Ok(operation.layout()), + asset: qwen_ffi::asset(operation), + epsilon, + in_place, + }, + )?; + execute( + self, + &self.qwen_kernels, + asset, + Arguments::with_layout(operation, layout, handles, epsilon), + ) + } + pub(in super::super::super) fn unload_qwen_kernels(&self) -> Result<()> { + unload(self, &self.qwen_kernels) + } +} diff --git a/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_6.rs b/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_6.rs new file mode 100644 index 00000000..c7483580 --- /dev/null +++ b/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_6.rs @@ -0,0 +1,253 @@ +//! Moved out of the parent module by STRA-338: impl Context (6). + +#[allow(unused_imports)] +use super::*; + + + +impl Context<'_> { + + /// Complete one fixed layer GR read using the original five kernels and + /// original finite mask. Bit i denotes nonfinite values at stage i; the + /// caller uses the first set bit before publishing a stage result. This + /// opt-in composite has one final completion fence, never a pending result + /// or generic asynchronous capability. The old per-launch methods remain. + #[allow(clippy::too_many_arguments)] // Exact closed five-operation operand set. + pub fn gr_read_chain_queued( + &self, + residual: &DeviceBuffer<'_>, + gamma: &DeviceBuffer<'_>, + down_weights: &DeviceBuffer<'_>, + up_weights: &DeviceBuffer<'_>, + epsilon: f32, + xn: &mut DeviceBuffer<'_>, + down: &mut DeviceBuffer<'_>, + activated: &mut DeviceBuffer<'_>, + gates: &mut DeviceBuffer<'_>, + products: &mut DeviceBuffer<'_>, + mixed: &mut DeviceBuffer<'_>, + ) -> Result { + let inputs = [residual, gamma, down_weights, up_weights]; + let outputs = [&*xn, &*down, &*activated, &*gates, &*products, &*mixed]; + // Original per-operation layout, asset, Context and native index + // checks, all completed before any registration/allocation/mutation. + let admitted = [ + admission( + self, + &[residual, gamma, &*xn], + Admission { + operation: Operation::Norm, + layout: Ok(Operation::Norm.layout()), + asset: qwen_ffi::asset(Operation::Norm), + epsilon, + in_place: false, + }, + )?, + admission( + self, + &[down_weights, &*xn, &*down], + Admission { + operation: Operation::Down, + layout: Ok(Operation::Down.layout()), + asset: qwen_ffi::asset(Operation::Down), + epsilon, + in_place: false, + }, + )?, + admission( + self, + &[&*down, &*activated], + Admission { + operation: Operation::DownSilu, + layout: Ok(Operation::DownSilu.layout()), + asset: qwen_ffi::asset(Operation::DownSilu), + epsilon, + in_place: false, + }, + )?, + admission( + self, + &[up_weights, &*activated, &*gates], + Admission { + operation: Operation::Up, + layout: Ok(Operation::Up.layout()), + asset: qwen_ffi::asset(Operation::Up), + epsilon, + in_place: false, + }, + )?, + admission( + self, + &[&*xn, &*gates, &*products, &*mixed], + Admission { + operation: Operation::LayerGate, + layout: Ok(Operation::LayerGate.layout()), + asset: qwen_ffi::asset(Operation::LayerGate), + epsilon, + in_place: false, + }, + )?, + ]; + // Per-stage alias checks alone cannot see future weights or another + // stage output. Refuse every cross-stage alias before the first write. + for (i, output) in outputs.iter().enumerate() { + let handle = output.handle.ok_or(Error::ContextPoisoned)?; + for input in inputs { + if handle.overlaps( + output.bytes, + input.handle.ok_or(Error::ContextPoisoned)?, + input.bytes, + ) { + return Err(Error::OutputAliasesInput); + } + } + for prior in &outputs[..i] { + if handle.overlaps( + output.bytes, + prior.handle.ok_or(Error::ContextPoisoned)?, + prior.bytes, + ) { + return Err(Error::OutputAliasesInput); + } + } + } + if self + .allocated + .get() + .checked_add(4) + .ok_or(Error::InvalidQwenShape)? + > self.budget + { + return Err(Error::BudgetExceeded); + } + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver")))] + { + return Err(Error::UnsupportedPlatform); + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] + { + let assets = std::array::from_fn(|i| admitted[i].0); + let kernels = prepare_gr_read_set(self, assets)?; + let status = self.allocate(4)?; + let result = (|| { + let status_handle = status.handle.ok_or(Error::ContextPoisoned)?; + let mut arguments: [Arguments; 5] = std::array::from_fn(|i| { + let (asset, layout, handles) = admitted[i]; + Arguments::with_layout(asset.operation, layout, handles, epsilon) + }); + let handles = [ + xn.handle.ok_or(Error::ContextPoisoned)?, + down.handle.ok_or(Error::ContextPoisoned)?, + activated.handle.ok_or(Error::ContextPoisoned)?, + gates.handle.ok_or(Error::ContextPoisoned)?, + products.handle.ok_or(Error::ContextPoisoned)?, + status_handle, + ]; + let mut finite_arguments = ffi::GrReadGuardArguments::new(handles); + // Owned host buffers outlive all attempted commands; never + // pass stack/borrowed readback storage to an uncertain driver. + let zero = vec![0u8; 4]; + let mut readback = vec![0u8; 4]; + let guard = self.enter()?; + let mut commands = self.driver.api.copy_from(status_handle, &zero); + for (i, argument) in arguments.iter_mut().enumerate() { + if commands.is_err() { + break; + } + commands = self.driver.api.launch_qwen( + kernels[i].function, + assets[i].operation, + argument, + ); + } + if commands.is_ok() { + commands = self + .driver + .api + .launch_gr_read_guard(kernels[5].function, &mut finite_arguments); + } + if commands.is_ok() { + commands = self.driver.api.copy_to(status_handle, &mut readback); + } + // Fence ALL attempted same-stream commands even on a failed + // enqueue. Launch/copy -> sync -> restore retains precedence. + let sync = self.driver.api.synchronize(); + if sync.is_err() { + self.poison(); + self.retain_driver(); + } + let pop = guard.finish(); + if sync.is_err() || pop.is_err() { + std::mem::forget((arguments, finite_arguments, zero, readback)); + return combine(combine(commands, sync), pop).map(|()| 0); + } + combine(combine(commands, sync), pop)?; + let mask = u32::from_le_bytes( + readback + .as_slice() + .try_into() + .map_err(|_| Error::InvalidQwenShape)?, + ); + if mask & !31 != 0 { + return Err(Error::InvalidDriverValue("GR finite witness")); + } + Ok(mask) + })(); + combine(result, status.release()) + } + } + + /// BF16[320,10240] weights × unchanged F32[10240] -> F32[320]. + /// The fixed asset must have a separate numerical qualification receipt. + pub fn gr_down_projection_bf16_f32( + &self, + weights: &DeviceBuffer<'_>, + activation: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call(Operation::Down, &[weights, activation, output], 0.0, false) + } + /// BF16[10240,320] weights × unchanged F32[320] -> F32[10240]. + pub fn gr_up_projection_bf16_f32( + &self, + weights: &DeviceBuffer<'_>, + activation: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call(Operation::Up, &[weights, activation, output], 0.0, false) + } + /// BF16[4,10240] weights × unchanged F32[10240] -> F32[4]. + pub fn gr_inject_projection_bf16_f32( + &self, + weights: &DeviceBuffer<'_>, + activation: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call( + Operation::InjectProjection, + &[weights, activation, output], + 0.0, + false, + ) + } + /// Weighted RMS over four streams of2560 F32 elements. Epsilon is finite + /// and nonnegative (including -0.0), matching the native launch refusal. + /// Outputs publish only after completion and restoration. + pub fn gr_norm_f32( + &self, + residual: &DeviceBuffer<'_>, + gamma: &DeviceBuffer<'_>, + epsilon: f32, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call(Operation::Norm, &[residual, gamma, output], epsilon, false) + } + /// Fixed source-ordered division byHC=4 followed by SiLU on320 F32 values. + pub fn gr_down_silu_hc_f32( + &self, + down: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call(Operation::DownSilu, &[down, output], 0.0, false) + } +} diff --git a/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_7.rs b/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_7.rs new file mode 100644 index 00000000..46d3ff45 --- /dev/null +++ b/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_7.rs @@ -0,0 +1,72 @@ +//! Moved out of the parent module by STRA-338: impl Context (7). + +#[allow(unused_imports)] +use super::*; + + + +impl Context<'_> { + /// Layer GR: separate products and ascending stream fused accumulation. + /// xn/gates/products are F32[4,2560], mixed is F32[2560]. + pub fn gr_gate_mean_layer_fused_f32( + &self, + xn: &DeviceBuffer<'_>, + gates: &DeviceBuffer<'_>, + products: &mut DeviceBuffer<'_>, + mixed: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call( + Operation::LayerGate, + &[xn, gates, products, mixed], + 0.0, + false, + ) + } + /// Final GR: the qualified unfused product/add order, without injection. + /// xn/gates/products are F32[4,2560], mixed is F32[2560]. + pub fn gr_gate_mean_final_unfused_f32( + &self, + xn: &DeviceBuffer<'_>, + gates: &DeviceBuffer<'_>, + products: &mut DeviceBuffer<'_>, + mixed: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call( + Operation::FinalGate, + &[xn, gates, products, mixed], + 0.0, + false, + ) + } + /// Inject shared block_out[2560] with four scalar inject values into a + /// separate residual[4,2560] output. All values/storage are F32. + pub fn gr_inject_residual_f32( + &self, + residual: &DeviceBuffer<'_>, + block_out: &DeviceBuffer<'_>, + inject: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call( + Operation::InjectResidual, + &[residual, block_out, inject, output], + 0.0, + false, + ) + } + /// Same-element in-place variant of the exact same fixed injection slot. + /// The mutable buffer is both R and R_out; no partial alias is admitted. + pub fn gr_inject_residual_in_place_f32( + &self, + residual: &mut DeviceBuffer<'_>, + block_out: &DeviceBuffer<'_>, + inject: &DeviceBuffer<'_>, + ) -> Result<()> { + self.qwen_call( + Operation::InjectResidual, + &[residual, block_out, inject, residual], + 0.0, + true, + ) + } +} diff --git a/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace.rs b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace.rs index 0cbd0a9c..1562d4c0 100644 --- a/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace.rs +++ b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace.rs @@ -3,481 +3,9 @@ #[allow(unused_imports)] use super::*; -impl<'ctx> SharedExpertWorkspace<'ctx> { - pub(super) fn new(context: &'ctx Context<'ctx>) -> Result { - if context.is_poisoned() || context.handle.is_none() { - return Err(Error::ContextPoisoned); - } - for operation in OPERATIONS { - qwen_ffi::asset(operation) - .ok_or(Error::UnsupportedQwenOperation)? - .validate(operation)?; - } - let required = TOTAL.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; - if context - .allocated_bytes() - .checked_add(required) - .is_none_or(|n| n > context.budget) - || context.memory_info()?.0 < required - { - return Err(Error::BudgetExceeded); - } - let mut owner = Self { - context, - buffers: std::array::from_fn(|_| None), - module: None, - kernels: None, - generation: 0, - failed: false, - }; - let result = (|| { - for (i, size) in SIZES.into_iter().enumerate() { - owner.buffers[i] = Some(context.allocate(size)?); - } - let guard = context.enter()?; - let load = (|| { - let common = |format| -> Result { - let kind = ProjectionKind::Dense(format); - let (quant, project) = context.common_kernels(kind)?; - Ok(Pair { - quant, - project, - style: ProjectionStyle::Common(kind), - }) - }; - let q4 = common(DenseFormat::Q4_K)?; - let q5 = context.q5_kernels()?; - let q6 = context.q6_kernels()?; - let xs = common(DenseFormat::IQ4_XS)?; - let gu = [ - q4, - Pair { - quant: q5.quantize, - project: q5.project, - style: ProjectionStyle::Q5, - }, - Pair { - quant: q6.quantize, - project: q6.project, - style: ProjectionStyle::Q6, - }, - xs, - ]; - let down = [common(DenseFormat::Q8_0)?, common(DenseFormat::IQ4_NL)?]; - let mut qwen = [None; 4]; - for (i, operation) in OPERATIONS.into_iter().enumerate() { - let asset = - qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?; - qwen[i] = Some(registered(context, &context.qwen_kernels, asset)?.function); - } - let module = context.driver.api.load_mmq_resident()?; - owner.module = Some(module); - let finite = [ - context.driver.api.mmq_resident_function(module, 0)?, - context.driver.api.mmq_resident_function(module, 1)?, - ]; - Ok(Kernels { - gu, - down, - qwen: qwen.map(|x| x.expect("four closed entries resolved")), - guard: finite, - }) - })(); - let pop = guard.finish(); - if pop.is_err() { - context.poisoned.set(true); - } - owner.kernels = Some(combine(load, pop)?); - // Real module residency is implicit CUDA memory. Preserve the actual free reserve too. - if context.memory_info()?.0 < RESERVE { - return Err(Error::BudgetExceeded); - } - owner.handles()?; - Ok(()) - })(); - if let Err(error) = result { - return combine(Err(error), owner.close()); - } - Ok(owner) - } - pub fn allocated_bytes(&self) -> usize { - self.buffers.iter().flatten().map(|b| b.bytes).sum() - } - pub fn is_failed(&self) -> bool { - self.failed || self.context.is_poisoned() - } - pub(super) fn buffer(&self, i: usize) -> Result<&DeviceBuffer<'ctx>> { - self.buffers[i].as_ref().ok_or(Error::ContextPoisoned) - } - pub(super) fn handles(&self) -> Result<[ffi::BufferHandle; 11]> { - if self.is_failed() || self.context.handle.is_none() { - return Err(Error::ContextPoisoned); - } - let first = self.buffer(0)?.handle.ok_or(Error::ContextPoisoned)?; - let mut handles = [first; 11]; - for i in 0..11 { - let buffer = self.buffer(i)?; - if !std::ptr::eq(self.context, buffer.context) { - return Err(Error::ContextMismatch); - } - if buffer.bytes != SIZES[i] { - return Err(Error::InvalidQwenShape); - } - handles[i] = buffer.handle.ok_or(Error::ContextPoisoned)?; - handles[i].validate_projection_extent(SIZES[i], 4)?; - for j in 0..i { - if handles[i].overlaps(SIZES[i], handles[j], SIZES[j]) { - return Err(Error::OutputAliasesInput); - } - } - } - Ok(handles) - } - pub(super) fn inputs( - &self, - activation: &DeviceBuffer<'_>, - weights: &SharedExpertWeights<'_, '_>, - packed: &DeviceBuffer<'_>, - owned: [ffi::BufferHandle; 11], - ) -> Result<[ffi::BufferHandle; 6]> { - let buffers = [ - activation, - weights.gate, - weights.up, - weights.down, - weights.scalar, - packed, - ]; - let sizes = [ - 10240, - weights.gu_kind[0].weight_bytes(), - weights.gu_kind[1].weight_bytes(), - weights.down_kind.weight_bytes(), - 5120, - 102400, - ]; - let mut handles = [owned[0]; 6]; - for (i, buffer) in buffers.into_iter().enumerate() { - if !std::ptr::eq(self.context, buffer.context) { - return Err(Error::ContextMismatch); - } - if buffer.bytes != sizes[i] { - return Err(Error::InvalidQwenShape); - } - handles[i] = buffer.handle.ok_or(Error::ContextPoisoned)?; - handles[i].validate_projection_extent(sizes[i], if i == 4 { 2 } else { 4 })?; - for (j, h) in owned.into_iter().enumerate() { - if handles[i].overlaps(sizes[i], h, SIZES[j]) { - return Err(Error::OutputAliasesInput); - } - } - // Immutable inputs may share an owner as in the original per-role APIs. - // Every output/scratch/status/route owner must be disjoint from all inputs. - } - if self.context.allocated_bytes() > self.context.budget { - return Err(Error::BudgetExceeded); - } - Ok(handles) - } - - /// Bounded completed queue, never a general asynchronous/operator API. - /// Numeric flags are arbitrated in the original producer order after the final drain. - pub fn compose<'lease>( - &'lease mut self, - activation: &'lease DeviceBuffer<'lease>, - weights: SharedExpertWeights<'lease, 'lease>, - packed: &'lease DeviceBuffer<'lease>, - route_weights: &[f32; 10], - ) -> Result> { - let handles = self.handles()?; - let inputs = self.inputs(activation, &weights, packed, handles)?; - let generation = self - .generation - .checked_add(1) - .ok_or(Error::InvalidQwenShape)?; - let kernels = self.kernels.as_ref().ok_or(Error::ContextPoisoned)?; - let mut route = staging(40)?; - for (value, out) in route_weights.iter().zip(route.as_chunks_mut::<4>().0) { - out.copy_from_slice(&value.to_le_bytes()); - } - let mut status_staging = staging(48)?; - let mut scalar_staging = staging(4)?; - let mut final_staging = staging(10240)?; - let mut values = Vec::new(); - values - .try_reserve_exact(2560) - .map_err(|_| Error::HostAllocation)?; - values.resize(2560, 0.0); - let mut commands = Vec::new(); - commands - .try_reserve_exact(20) - .map_err(|_| Error::HostAllocation)?; - commands.push(Command::Guard( - kernels.guard[0], - 12, - ffi::MmqResidentArguments::zero(handles[9], 12), - )); - let statuses = status_spans(handles[9])?; - append_projection( - &mut commands, - kernels.gu[weights.gu_kind[0].index()], - [inputs[1], inputs[0], handles[0]], - handles[7], - statuses[0], - 640, - 2560, - )?; - append_finite( - &mut commands, - kernels.guard[1], - handles[0], - statuses[1], - 640, - ); - append_projection( - &mut commands, - kernels.gu[weights.gu_kind[1].index()], - [inputs[2], inputs[0], handles[1]], - handles[7], - statuses[2], - 640, - 2560, - )?; - append_finite( - &mut commands, - kernels.guard[1], - handles[1], - statuses[3], - 640, - ); - self.append_qwen( - &mut commands, - kernels.qwen[0], - Operation::MoeSwiglu, - &[self.buffer(0)?, self.buffer(1)?, self.buffer(2)?], - )?; - append_finite( - &mut commands, - kernels.guard[1], - handles[2], - statuses[4], - 640, - ); - append_projection( - &mut commands, - kernels.down[weights.down_kind.index()], - [inputs[3], handles[2], handles[3]], - handles[8], - statuses[5], - 2560, - 640, - )?; - append_finite( - &mut commands, - kernels.guard[1], - handles[3], - statuses[6], - 2560, - ); - self.append_qwen( - &mut commands, - kernels.qwen[1], - Operation::MoeSharedScalar, - &[activation, weights.scalar, self.buffer(4)?], - )?; - append_finite(&mut commands, kernels.guard[1], handles[4], statuses[7], 1); - self.append_qwen( - &mut commands, - kernels.qwen[2], - Operation::MoeSharedScale, - &[self.buffer(3)?, self.buffer(4)?, self.buffer(5)?], - )?; - append_finite( - &mut commands, - kernels.guard[1], - handles[5], - statuses[8], - 2560, - ); - append_finite( - &mut commands, - kernels.guard[1], - inputs[5], - statuses[9], - 25600, - ); - append_finite( - &mut commands, - kernels.guard[1], - handles[10], - statuses[10], - 10, - ); - self.append_qwen( - &mut commands, - kernels.qwen[3], - Operation::MoeCombine, - &[packed, self.buffer(10)?, self.buffer(5)?, self.buffer(6)?], - )?; - append_finite( - &mut commands, - kernels.guard[1], - handles[6], - statuses[11], - 2560, - ); - // All exact shapes/ranges/aliases/assets and owned staging precede the first write. - let guard = match self.context.enter() { - Ok(guard) => guard, - Err(error) => { - self.failed = true; - self.context.poisoned.set(true); - return Err(error); - } - }; - let mut operation = self.context.driver.api.copy_from(handles[10], &route); - for command in &mut commands { - if operation.is_err() { - break; - } - operation = command.launch(self.context); - } - // These are blocking cuMemcpyDtoH calls, in one final drain phase, not async DMA. - if operation.is_ok() { - operation = self - .context - .driver - .api - .copy_to(handles[9], &mut status_staging); - } - if operation.is_ok() { - operation = self - .context - .driver - .api - .copy_to(handles[4], &mut scalar_staging); - } - if operation.is_ok() { - operation = self - .context - .driver - .api - .copy_to(handles[6], &mut final_staging); - } - let sync = self.context.driver.api.synchronize(); - let pop = guard.finish(); - if operation.is_err() || sync.is_err() || pop.is_err() { - self.failed = true; - self.context.poisoned.set(true); - } - if sync.is_err() || pop.is_err() { - std::mem::forget(( - commands, - route, - status_staging, - scalar_staging, - final_staging, - values, - )); - return combine(combine(operation, sync), pop).map(|()| unreachable!("failed drain")); - } - combine(combine(operation, sync), pop)?; - let mut result = [0u32; 12]; - for (out, bytes) in result.iter_mut().zip(status_staging.as_chunks::<4>().0) { - *out = u32::from_le_bytes(*bytes); - } - if result.iter().enumerate().any(|(i, status)| { - let permitted = if matches!(i, 0 | 2 | 5) { 3 } else { 1 }; - status & !permitted != 0 - }) { - self.failed = true; - self.context.poisoned.set(true); - return Err(Error::InvalidDriverValue("shared-tail numeric witness")); - } - let scalar = f32::from_le_bytes(scalar_staging.as_chunks::<4>().0[0]); - let refusal = first_refusal(result, scalar); - for (value, bytes) in values.iter_mut().zip(final_staging.as_chunks::<4>().0) { - *value = f32::from_le_bytes(*bytes); - } - self.generation = generation; - Ok(SharedTailCompletion { - workspace: self, - _weights: weights, - _activation: activation, - _packed: packed, - statuses: result, - scalar, - refusal, - values: values.into_boxed_slice(), - generation, - }) - } - pub(super) fn append_qwen( - &self, - commands: &mut Vec, - function: ffi::FunctionHandle, - operation: Operation, - buffers: &[&DeviceBuffer<'_>], - ) -> Result<()> { - let (_, layout, handles) = admission( - self.context, - buffers, - Admission { - operation, - layout: Ok(operation.layout()), - asset: qwen_ffi::asset(operation), - epsilon: 0.0, - in_place: false, - }, - )?; - commands.push(Command::Qwen( - function, - operation, - Box::new(Arguments::with_layout(operation, layout, handles, 0.0)), - )); - Ok(()) - } - pub fn close(mut self) -> Result<()> { - self.close_inner() - } - pub(super) fn close_inner(&mut self) -> Result<()> { - self.failed = true; - self.kernels = None; - let mut result = Ok(()); - for buffer in &mut self.buffers { - if let Some(buffer) = buffer.take() { - let release = if self.context.is_poisoned() { - std::mem::forget(buffer); - Err(Error::ContextPoisoned) - } else { - buffer.release() - }; - if release.is_err() { - self.context.poisoned.set(true); - } - result = combine(result, release); - } - } - if let Some(module) = self.module.take() { - let release = if self.context.is_poisoned() { - self.context.retain_driver(); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(guard) => { - let unload = self.context.driver.api.unload(module); - let pop = guard.finish(); - combine(unload, pop) - } - Err(error) => Err(error), - } - }; - if release.is_err() { - self.context.poisoned.set(true); - self.context.retain_driver(); - } - result = combine(result, release); - } - result - } -} +#[path = "impl_sharedexpertworkspace/impl_sharedexpertworkspace_2.rs"] +mod impl_sharedexpertworkspace_2; +#[path = "impl_sharedexpertworkspace/impl_sharedexpertworkspace_2_2.rs"] +mod impl_sharedexpertworkspace_2_2; +#[path = "impl_sharedexpertworkspace/impl_sharedexpertworkspace_3.rs"] +mod impl_sharedexpertworkspace_3; diff --git a/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_2.rs b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_2.rs new file mode 100644 index 00000000..6608e86e --- /dev/null +++ b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_2.rs @@ -0,0 +1,183 @@ +//! Moved out of the parent module by STRA-338: impl SharedExpertWorkspace. + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> SharedExpertWorkspace<'ctx> { + pub(in super::super) fn new(context: &'ctx Context<'ctx>) -> Result { + if context.is_poisoned() || context.handle.is_none() { + return Err(Error::ContextPoisoned); + } + for operation in OPERATIONS { + qwen_ffi::asset(operation) + .ok_or(Error::UnsupportedQwenOperation)? + .validate(operation)?; + } + let required = TOTAL.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; + if context + .allocated_bytes() + .checked_add(required) + .is_none_or(|n| n > context.budget) + || context.memory_info()?.0 < required + { + return Err(Error::BudgetExceeded); + } + let mut owner = Self { + context, + buffers: std::array::from_fn(|_| None), + module: None, + kernels: None, + generation: 0, + failed: false, + }; + let result = (|| { + for (i, size) in SIZES.into_iter().enumerate() { + owner.buffers[i] = Some(context.allocate(size)?); + } + let guard = context.enter()?; + let load = (|| { + let common = |format| -> Result { + let kind = ProjectionKind::Dense(format); + let (quant, project) = context.common_kernels(kind)?; + Ok(Pair { + quant, + project, + style: ProjectionStyle::Common(kind), + }) + }; + let q4 = common(DenseFormat::Q4_K)?; + let q5 = context.q5_kernels()?; + let q6 = context.q6_kernels()?; + let xs = common(DenseFormat::IQ4_XS)?; + let gu = [ + q4, + Pair { + quant: q5.quantize, + project: q5.project, + style: ProjectionStyle::Q5, + }, + Pair { + quant: q6.quantize, + project: q6.project, + style: ProjectionStyle::Q6, + }, + xs, + ]; + let down = [common(DenseFormat::Q8_0)?, common(DenseFormat::IQ4_NL)?]; + let mut qwen = [None; 4]; + for (i, operation) in OPERATIONS.into_iter().enumerate() { + let asset = + qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?; + qwen[i] = Some(registered(context, &context.qwen_kernels, asset)?.function); + } + let module = context.driver.api.load_mmq_resident()?; + owner.module = Some(module); + let finite = [ + context.driver.api.mmq_resident_function(module, 0)?, + context.driver.api.mmq_resident_function(module, 1)?, + ]; + Ok(Kernels { + gu, + down, + qwen: qwen.map(|x| x.expect("four closed entries resolved")), + guard: finite, + }) + })(); + let pop = guard.finish(); + if pop.is_err() { + context.poisoned.set(true); + } + owner.kernels = Some(combine(load, pop)?); + // Real module residency is implicit CUDA memory. Preserve the actual free reserve too. + if context.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + owner.handles()?; + Ok(()) + })(); + if let Err(error) = result { + return combine(Err(error), owner.close()); + } + Ok(owner) + } + pub fn allocated_bytes(&self) -> usize { + self.buffers.iter().flatten().map(|b| b.bytes).sum() + } + pub fn is_failed(&self) -> bool { + self.failed || self.context.is_poisoned() + } + pub(in super::super) fn buffer(&self, i: usize) -> Result<&DeviceBuffer<'ctx>> { + self.buffers[i].as_ref().ok_or(Error::ContextPoisoned) + } + pub(in super::super) fn handles(&self) -> Result<[ffi::BufferHandle; 11]> { + if self.is_failed() || self.context.handle.is_none() { + return Err(Error::ContextPoisoned); + } + let first = self.buffer(0)?.handle.ok_or(Error::ContextPoisoned)?; + let mut handles = [first; 11]; + for i in 0..11 { + let buffer = self.buffer(i)?; + if !std::ptr::eq(self.context, buffer.context) { + return Err(Error::ContextMismatch); + } + if buffer.bytes != SIZES[i] { + return Err(Error::InvalidQwenShape); + } + handles[i] = buffer.handle.ok_or(Error::ContextPoisoned)?; + handles[i].validate_projection_extent(SIZES[i], 4)?; + for j in 0..i { + if handles[i].overlaps(SIZES[i], handles[j], SIZES[j]) { + return Err(Error::OutputAliasesInput); + } + } + } + Ok(handles) + } + pub(in super::super) fn inputs( + &self, + activation: &DeviceBuffer<'_>, + weights: &SharedExpertWeights<'_, '_>, + packed: &DeviceBuffer<'_>, + owned: [ffi::BufferHandle; 11], + ) -> Result<[ffi::BufferHandle; 6]> { + let buffers = [ + activation, + weights.gate, + weights.up, + weights.down, + weights.scalar, + packed, + ]; + let sizes = [ + 10240, + weights.gu_kind[0].weight_bytes(), + weights.gu_kind[1].weight_bytes(), + weights.down_kind.weight_bytes(), + 5120, + 102400, + ]; + let mut handles = [owned[0]; 6]; + for (i, buffer) in buffers.into_iter().enumerate() { + if !std::ptr::eq(self.context, buffer.context) { + return Err(Error::ContextMismatch); + } + if buffer.bytes != sizes[i] { + return Err(Error::InvalidQwenShape); + } + handles[i] = buffer.handle.ok_or(Error::ContextPoisoned)?; + handles[i].validate_projection_extent(sizes[i], if i == 4 { 2 } else { 4 })?; + for (j, h) in owned.into_iter().enumerate() { + if handles[i].overlaps(sizes[i], h, SIZES[j]) { + return Err(Error::OutputAliasesInput); + } + } + // Immutable inputs may share an owner as in the original per-role APIs. + // Every output/scratch/status/route owner must be disjoint from all inputs. + } + if self.context.allocated_bytes() > self.context.budget { + return Err(Error::BudgetExceeded); + } + Ok(handles) + } +} diff --git a/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_2_2.rs b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_2_2.rs new file mode 100644 index 00000000..03330c9c --- /dev/null +++ b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_2_2.rs @@ -0,0 +1,241 @@ +//! Moved out of the parent module by STRA-338: impl SharedExpertWorkspace (2). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> SharedExpertWorkspace<'ctx> { + + /// Bounded completed queue, never a general asynchronous/operator API. + /// Numeric flags are arbitrated in the original producer order after the final drain. + pub fn compose<'lease>( + &'lease mut self, + activation: &'lease DeviceBuffer<'lease>, + weights: SharedExpertWeights<'lease, 'lease>, + packed: &'lease DeviceBuffer<'lease>, + route_weights: &[f32; 10], + ) -> Result> { + let handles = self.handles()?; + let inputs = self.inputs(activation, &weights, packed, handles)?; + let generation = self + .generation + .checked_add(1) + .ok_or(Error::InvalidQwenShape)?; + let kernels = self.kernels.as_ref().ok_or(Error::ContextPoisoned)?; + let mut route = staging(40)?; + for (value, out) in route_weights.iter().zip(route.as_chunks_mut::<4>().0) { + out.copy_from_slice(&value.to_le_bytes()); + } + let mut status_staging = staging(48)?; + let mut scalar_staging = staging(4)?; + let mut final_staging = staging(10240)?; + let mut values = Vec::new(); + values + .try_reserve_exact(2560) + .map_err(|_| Error::HostAllocation)?; + values.resize(2560, 0.0); + let mut commands = Vec::new(); + commands + .try_reserve_exact(20) + .map_err(|_| Error::HostAllocation)?; + commands.push(Command::Guard( + kernels.guard[0], + 12, + ffi::MmqResidentArguments::zero(handles[9], 12), + )); + let statuses = status_spans(handles[9])?; + append_projection( + &mut commands, + kernels.gu[weights.gu_kind[0].index()], + [inputs[1], inputs[0], handles[0]], + handles[7], + statuses[0], + 640, + 2560, + )?; + append_finite( + &mut commands, + kernels.guard[1], + handles[0], + statuses[1], + 640, + ); + append_projection( + &mut commands, + kernels.gu[weights.gu_kind[1].index()], + [inputs[2], inputs[0], handles[1]], + handles[7], + statuses[2], + 640, + 2560, + )?; + append_finite( + &mut commands, + kernels.guard[1], + handles[1], + statuses[3], + 640, + ); + self.append_qwen( + &mut commands, + kernels.qwen[0], + Operation::MoeSwiglu, + &[self.buffer(0)?, self.buffer(1)?, self.buffer(2)?], + )?; + append_finite( + &mut commands, + kernels.guard[1], + handles[2], + statuses[4], + 640, + ); + append_projection( + &mut commands, + kernels.down[weights.down_kind.index()], + [inputs[3], handles[2], handles[3]], + handles[8], + statuses[5], + 2560, + 640, + )?; + append_finite( + &mut commands, + kernels.guard[1], + handles[3], + statuses[6], + 2560, + ); + self.append_qwen( + &mut commands, + kernels.qwen[1], + Operation::MoeSharedScalar, + &[activation, weights.scalar, self.buffer(4)?], + )?; + append_finite(&mut commands, kernels.guard[1], handles[4], statuses[7], 1); + self.append_qwen( + &mut commands, + kernels.qwen[2], + Operation::MoeSharedScale, + &[self.buffer(3)?, self.buffer(4)?, self.buffer(5)?], + )?; + append_finite( + &mut commands, + kernels.guard[1], + handles[5], + statuses[8], + 2560, + ); + append_finite( + &mut commands, + kernels.guard[1], + inputs[5], + statuses[9], + 25600, + ); + append_finite( + &mut commands, + kernels.guard[1], + handles[10], + statuses[10], + 10, + ); + self.append_qwen( + &mut commands, + kernels.qwen[3], + Operation::MoeCombine, + &[packed, self.buffer(10)?, self.buffer(5)?, self.buffer(6)?], + )?; + append_finite( + &mut commands, + kernels.guard[1], + handles[6], + statuses[11], + 2560, + ); + // All exact shapes/ranges/aliases/assets and owned staging precede the first write. + let guard = match self.context.enter() { + Ok(guard) => guard, + Err(error) => { + self.failed = true; + self.context.poisoned.set(true); + return Err(error); + } + }; + let mut operation = self.context.driver.api.copy_from(handles[10], &route); + for command in &mut commands { + if operation.is_err() { + break; + } + operation = command.launch(self.context); + } + // These are blocking cuMemcpyDtoH calls, in one final drain phase, not async DMA. + if operation.is_ok() { + operation = self + .context + .driver + .api + .copy_to(handles[9], &mut status_staging); + } + if operation.is_ok() { + operation = self + .context + .driver + .api + .copy_to(handles[4], &mut scalar_staging); + } + if operation.is_ok() { + operation = self + .context + .driver + .api + .copy_to(handles[6], &mut final_staging); + } + let sync = self.context.driver.api.synchronize(); + let pop = guard.finish(); + if operation.is_err() || sync.is_err() || pop.is_err() { + self.failed = true; + self.context.poisoned.set(true); + } + if sync.is_err() || pop.is_err() { + std::mem::forget(( + commands, + route, + status_staging, + scalar_staging, + final_staging, + values, + )); + return combine(combine(operation, sync), pop).map(|()| unreachable!("failed drain")); + } + combine(combine(operation, sync), pop)?; + let mut result = [0u32; 12]; + for (out, bytes) in result.iter_mut().zip(status_staging.as_chunks::<4>().0) { + *out = u32::from_le_bytes(*bytes); + } + if result.iter().enumerate().any(|(i, status)| { + let permitted = if matches!(i, 0 | 2 | 5) { 3 } else { 1 }; + status & !permitted != 0 + }) { + self.failed = true; + self.context.poisoned.set(true); + return Err(Error::InvalidDriverValue("shared-tail numeric witness")); + } + let scalar = f32::from_le_bytes(scalar_staging.as_chunks::<4>().0[0]); + let refusal = first_refusal(result, scalar); + for (value, bytes) in values.iter_mut().zip(final_staging.as_chunks::<4>().0) { + *value = f32::from_le_bytes(*bytes); + } + self.generation = generation; + Ok(SharedTailCompletion { + workspace: self, + _weights: weights, + _activation: activation, + _packed: packed, + statuses: result, + scalar, + refusal, + values: values.into_boxed_slice(), + generation, + }) + } +} diff --git a/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_3.rs b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_3.rs new file mode 100644 index 00000000..b18315d2 --- /dev/null +++ b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_3.rs @@ -0,0 +1,76 @@ +//! Moved out of the parent module by STRA-338: impl SharedExpertWorkspace (3). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> SharedExpertWorkspace<'ctx> { + pub(in super::super) fn append_qwen( + &self, + commands: &mut Vec, + function: ffi::FunctionHandle, + operation: Operation, + buffers: &[&DeviceBuffer<'_>], + ) -> Result<()> { + let (_, layout, handles) = admission( + self.context, + buffers, + Admission { + operation, + layout: Ok(operation.layout()), + asset: qwen_ffi::asset(operation), + epsilon: 0.0, + in_place: false, + }, + )?; + commands.push(Command::Qwen( + function, + operation, + Box::new(Arguments::with_layout(operation, layout, handles, 0.0)), + )); + Ok(()) + } + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + pub(in super::super) fn close_inner(&mut self) -> Result<()> { + self.failed = true; + self.kernels = None; + let mut result = Ok(()); + for buffer in &mut self.buffers { + if let Some(buffer) = buffer.take() { + let release = if self.context.is_poisoned() { + std::mem::forget(buffer); + Err(Error::ContextPoisoned) + } else { + buffer.release() + }; + if release.is_err() { + self.context.poisoned.set(true); + } + result = combine(result, release); + } + } + if let Some(module) = self.module.take() { + let release = if self.context.is_poisoned() { + self.context.retain_driver(); + Err(Error::ContextPoisoned) + } else { + match self.context.enter() { + Ok(guard) => { + let unload = self.context.driver.api.unload(module); + let pop = guard.finish(); + combine(unload, pop) + } + Err(error) => Err(error), + } + }; + if release.is_err() { + self.context.poisoned.set(true); + self.context.retain_driver(); + } + result = combine(result, release); + } + result + } +} diff --git a/crates/leleka-memory/src/governor/impl_governor.rs b/crates/leleka-memory/src/governor/impl_governor.rs index a277946d..4307ee54 100644 --- a/crates/leleka-memory/src/governor/impl_governor.rs +++ b/crates/leleka-memory/src/governor/impl_governor.rs @@ -3,737 +3,7 @@ #[allow(unused_imports)] use super::*; - -impl Governor { - pub fn new(cfg: GovernorConfig, src: Arc) -> Self { - let policy0 = cfg.policy; - let monitor = Monitor::new(policy0); - Self { - inner: Arc::new(Inner { - cfg, - src, - epoch: Instant::now(), - plan: Mutex::new(None), - monitor: Mutex::new(monitor), - policy: Mutex::new(policy0), - level: AtomicU8::new(Level::Normal as u8), - reason: Mutex::new("startup".into()), - available: AtomicU64::new(NONE), - sampled_at_ms: AtomicU64::new(0), - prefix_planned: AtomicU64::new(0), - prefix_target: AtomicU64::new(NONE), - prefix_used: AtomicU64::new(0), - last_shed_ms: AtomicU64::new(0), - last_trim_ms: AtomicU64::new(NONE), - last_trim_log_ms: AtomicU64::new(0), - trims: AtomicU64::new(0), - since_ms: AtomicU64::new(0), - transitions: Mutex::new(VecDeque::new()), - counters: Counters::default(), - ledger: Ledger::new(), - vram: Mutex::new(None), - post_load: Mutex::new(None), - #[cfg(all(target_os = "linux", target_pointer_width = "64"))] - guarded: Mutex::new(None), - stop: AtomicBool::new(false), - }), - } - } - - /// A governor over the real `/proc`. - pub fn real(cfg: GovernorConfig) -> Self { - Self::new(cfg, Arc::new(RealProc)) - } - - /// Make this the process-wide governor (the first install wins; later ones are returned unchanged). - pub fn install(self) -> &'static Governor { - GLOBAL.get_or_init(|| self) - } - pub fn global() -> Option<&'static Governor> { - GLOBAL.get() - } - - /// Replace the pressure floors at run time (diagnostics and the shed tests: move the thresholds next to the memory - /// the host has now, so the whole shed path runs without ever approaching the real limit). `hard < soft` is required. - pub fn set_floors(&self, soft_floor: u64, hard_floor: u64) -> Result<(), String> { - if hard_floor >= soft_floor { - return Err(format!("hard floor {hard_floor} must be below the soft floor {soft_floor}")); - } - let mut policy = lock(&self.inner.policy); - policy.soft_floor = soft_floor; - policy.hard_floor = hard_floor; - lock(&self.inner.monitor).set_policy(*policy); - drop(policy); - self.log(&format!("floors set to soft {} MiB / hard {} MiB", soft_floor >> 20, hard_floor >> 20)); - Ok(()) - } - - pub fn config(&self) -> &GovernorConfig { - &self.inner.cfg - } - pub fn policy(&self) -> Policy { - *lock(&self.inner.policy) - } - pub fn inventory(&self) -> &'static Inventory { - Inventory::global() - } - pub fn ledger(&self) -> &Ledger { - &self.inner.ledger - } - pub fn source(&self) -> &(dyn ProcSource + Send + Sync) { - &*self.inner.src - } - pub fn probe(&self) -> HostFacts { - HostFacts::probe(&*self.inner.src) - } - pub fn census(&self) -> Census { - Census::take(&*self.inner.src) - } - pub(super) fn now_ms(&self) -> u64 { - self.inner.epoch.elapsed().as_millis() as u64 - } - pub fn log(&self, text: &str) { - if self.inner.cfg.log { - // Structured and rate limited like every other line; the lab scripts' bare form under LELEKA_LOG_LEGACY=1. - if leleka_obs::settings().legacy { - leleka_obs::legacy_line(&format!("leleka-memory: {text}")); - } else { - leleka_obs::emit_msg(leleka_obs::Level::Info, "memory", "leleka-memory:governor", text); - } - } - } - - // ---- plan ------------------------------------------------------------------------------------------------- - - /// Plan the budget (or refuse), log the plan, register the expected size of every fixed item in the inventory and keep - /// the plan for the report. - pub fn startup(&self, input: &crate::plan::PlanInput) -> Result { - let plan = match crate::plan::plan(input) { - Ok(plan) => plan, - Err(refusal) => { - self.log(&format!("REFUSING TO START: {refusal}")); - return Err(refusal); - } - }; - let inv = self.inventory(); - for item in &plan.fixed { - inv.set( - crate::inventory::Entry::new("planned", &item.name, item.space, crate::inventory::When::Startup, &item.formula) - .expected(item.bytes) - .swappable(false), - ); - } - self.log(&format!( - "budget: available {} - fixed {} - memfd to create {} = {} after the fixed footprint; floors soft {} / hard {}; elastic {}: resident complement {}, prefix cache {}, conversation checkpoints {} ({}){}", - plan.available_before.map_or("unknown".into(), gib), - gib(plan.fixed_bytes), - gib(plan.kar_to_create), - plan.available_after_fixed.map_or("unknown".into(), gib), - gib(plan.soft_floor), - gib(plan.hard_floor), - gib(plan.elastic), - gib(plan.resident_complement_bytes), - gib(plan.prefix_bytes), - plan.conversation_checkpoints, - gib(plan.conversation_bytes), - if plan.blind { "; BLIND: no memory telemetry, caches off" } else { "" } - )); - for note in &plan.notes { - self.log(&format!("note: {note}")); - } - self.set_plan(plan.clone()); - Ok(plan) - } - - /// The device check once the device is visible (`cuMemGetInfo`): refuse or note, and keep the numbers for the report. - pub fn check_vram(&self, vram: crate::plan::VramFacts, budget: u64, fixed_estimate: Option) -> Result<(), Refusal> { - match crate::plan::check_vram(&self.policy(), vram, budget, fixed_estimate) { - Ok((plan, note)) => { - if let Some(note) = note { - self.log(&format!("note: {note}")); - } - *lock(&self.inner.vram) = Some(plan); - Ok(()) - } - Err(refusal) => { - self.log(&format!("REFUSING TO START: {refusal}")); - Err(refusal) - } - } - } - - /// Compare the plan's prediction with what the host really has after the stack opened, log the error when it matters and keep it for the - /// report (`plan_check`). Returns `actual - predicted` in bytes (negative: the footprint was bigger than planned). - pub fn note_post_load(&self, actual_available: Option) -> Option { - let predicted = lock(&self.inner.plan).as_ref().and_then(|p| p.available_after_fixed)?; - let actual = actual_available?; - *lock(&self.inner.post_load) = Some((predicted, actual)); - let error = i128::from(actual) - i128::from(predicted); - let error = i64::try_from(error).unwrap_or(if error < 0 { i64::MIN } else { i64::MAX }); - if error.unsigned_abs() > 512 * MIB { - self.log(&format!( - "WARNING: the startup plan predicted {} available after the fixed footprint, the host has {} after the stack opened ({:+} MiB): the footprint constants are off, caches are sized from the measured value", - gib(predicted), - gib(actual), - error >> 20 - )); - } - Some(error) - } - - pub fn set_plan(&self, plan: Plan) { - self.inner.prefix_planned.store(plan.prefix_bytes, Ordering::Release); - *lock(&self.inner.plan) = Some(plan); - } - pub fn plan(&self) -> Option { - lock(&self.inner.plan).clone() - } - /// The prefix budget decided at stack open (after the fixed items are resident); the shed target is relative to it. - pub fn set_prefix_budget(&self, bytes: u64) { - self.inner.prefix_planned.store(bytes, Ordering::Release); - } - - // ---- level ------------------------------------------------------------------------------------------------ - - pub fn level(&self) -> Level { - Level::from_u8(self.inner.level.load(Ordering::Acquire)) - } - - /// The caller's own sample when the sampler thread has not delivered one for five intervals (it died, or was never started): - /// a stuck `reject` must not outlive the thread that would have lifted it, so the owner thread drives the monitor itself. - pub(super) fn ensure_fresh(&self) { - let interval = self.inner.cfg.sample_interval_ms.max(50); - let now = self.now_ms(); - let last = self.inner.sampled_at_ms.load(Ordering::Acquire); - if now.saturating_sub(last) > interval.saturating_mul(5) && self.inner.counters.samples.load(Ordering::Relaxed) > 0 { - self.sample_at(now); - } - } - /// A fresh reading of the effective available memory (one probe of a dozen small files). - pub fn available_now(&self) -> Option { - self.probe().effective_available() - } - /// The last sampled value (at most one sample interval old); `None` before the first sample or when unknown. - pub fn available_cached(&self) -> Option { - match self.inner.available.load(Ordering::Acquire) { - NONE => None, - v => Some(v), - } - } - - /// Take a sample now and apply it. Returns the transition, if any. - pub fn sample_now(&self) -> Option { - self.sample_at(self.now_ms()) - } - - pub fn sample_at(&self, at_ms: u64) -> Option { - let facts = self.relieve_working_set(self.probe()); - let sample = Sample { - at_ms, - available: facts.effective_available(), - psi: facts.psi, - events: facts.cgroup.as_ref().and_then(|c| c.events), - pswpout: facts.pswpout, - }; - self.inner.counters.samples.fetch_add(1, Ordering::Relaxed); - self.inner.available.store(sample.available.unwrap_or(NONE), Ordering::Release); - self.inner.sampled_at_ms.store(at_ms, Ordering::Release); - let transition = lock(&self.inner.monitor).update(&sample); - if let Some(t) = &transition { - self.inner.level.store(t.to as u8, Ordering::Release); - self.inner.since_ms.store(at_ms, Ordering::Release); - *lock(&self.inner.reason) = t.reason.0.clone(); - self.inner.counters.level_changes.fetch_add(1, Ordering::Relaxed); - let mut q = lock(&self.inner.transitions); - if q.len() >= 32 { - q.pop_front(); - } - q.push_back(TransitionRecord { at_ms, from: t.from, to: t.to, reason: t.reason.0.clone() }); - drop(q); - self.log(&format!("memory pressure {} -> {}: {}", t.from.as_str(), t.to.as_str(), t.reason.0)); - } - transition - } - - // ---- admission and shedding ------------------------------------------------------------------------------- - - /// May this request start? Context first (a request that can never fit is a 400, not a retry), then the pressure level, - /// then whether its own transient memory would take the host below the hard floor. - pub fn admit(&self, shape: &RequestShape) -> Admission { - let c = &self.inner.counters; - let needed = shape.prompt_tokens.saturating_add(shape.max_new_tokens).saturating_add(8); - if needed > shape.max_context { - c.rejected_context.fetch_add(1, Ordering::Relaxed); - return Admission::Refuse(Refuse { - status: 400, - code: "context_length_exceeded", - message: format!( - "the request needs {needed} tokens (prompt {} + up to {} new + 8) but the pinned K/V image holds {} tokens", - shape.prompt_tokens, shape.max_new_tokens, shape.max_context - ), - retry_after_secs: 0, - }); - } - self.ensure_fresh(); - let level = self.level(); - let retry = lock(&self.inner.monitor).retry_after_secs().max(1); - if level == Level::Reject { - c.rejected_pressure.fetch_add(1, Ordering::Relaxed); - return Admission::Refuse(Refuse { - status: 503, - code: "memory_pressure", - message: format!("host memory is under pressure ({}); retry shortly", lock(&self.inner.reason)), - retry_after_secs: retry, - }); - } - // the transient of one request (checkpoint / node state / import staging) must not take the host below the hard floor - let transient = self.policy().reserve / 4; - if let Some(available) = self.available_now() - && available.saturating_sub(transient) < self.policy().hard_floor { - c.rejected_pressure.fetch_add(1, Ordering::Relaxed); - return Admission::Refuse(Refuse { - status: 503, - code: "memory_pressure", - message: format!( - "{} available is within {} of the hard floor {}; retry shortly", - gib(available), - gib(transient), - gib(self.policy().hard_floor) - ), - retry_after_secs: retry, - }); - } - c.admitted.fetch_add(1, Ordering::Relaxed); - Admission::Admit - } - - /// Windows keeps touched mapped pages in the working set, where they count as used. When the host reads below the soft floor, hand them back to - /// the standby list (at most every 250 ms) and read the host again, so that a dip caused only by trimmable mapped pages never reaches the monitor: - /// a shed evicts prefix-cache blocks, and live runs showed it firing every few seconds at the floor (laptop 256k session, 2026-10-26: 113 blocks - /// evicted, the fourth turn re-read 223k tokens in 32 minutes). - pub(super) fn relieve_working_set(&self, facts: HostFacts) -> HostFacts { - self.relieve_working_set_below(facts, self.policy().soft_floor) - } - - /// The available memory after handing the engine's trimmable working-set pages back, for a cache owner that needs `needed` bytes of it - /// (a prefix-cache checkpoint must leave the admit floor free: a reading of 8.9 GiB against a floor of 9.2 GiB refused a 0.2 GiB checkpoint - /// that the very next trim would have admitted, because the periodic trim only runs below the soft floor). At most one trim per 250 ms. - pub fn available_after_relief(&self, needed: u64) -> Option { - let facts = self.probe(); - self.relieve_working_set_below(facts, needed).effective_available() - } - - pub(super) fn relieve_working_set_below(&self, facts: HostFacts, threshold: u64) -> HostFacts { - if !cfg!(windows) { - return facts; - } - // A/B inside one engine (bring-up): no trim while the file named by LELEKA_NO_TRIM_FILE exists - static NO_TRIM_FILE: OnceLock> = OnceLock::new(); - if NO_TRIM_FILE.get_or_init(|| std::env::var_os("LELEKA_NO_TRIM_FILE").map(std::path::PathBuf::from)).as_ref().is_some_and(|f| f.exists()) { - return facts; - } - let Some(available) = facts.effective_available() else { return facts }; - if available >= threshold { - return facts; - } - let now = self.now_ms(); - let last = self.inner.last_trim_ms.load(Ordering::Acquire); - if last != NONE && now.saturating_sub(last) < WORKING_SET_TRIM_EVERY.as_millis() as u64 { - return facts; - } - self.inner.last_trim_ms.store(now, Ordering::Release); - if !crate::winproc::trim_working_set() { - return facts; - } - let after = self.probe(); - let trims = self.inner.trims.fetch_add(1, Ordering::Relaxed) + 1; - if trims == 1 || now.saturating_sub(self.inner.last_trim_log_ms.load(Ordering::Relaxed)) >= 10_000 { - self.inner.last_trim_log_ms.store(now, Ordering::Relaxed); - self.log(&format!( - "working set trimmed (#{trims}): available {} -> {} MiB", - available >> 20, - after.effective_available().unwrap_or(0) >> 20 - )); - } - after - } - - /// What the cache owners must do at this level. The prefix target steps down by a quarter per second while shedding. - pub fn directive(&self, prefix_used: u64) -> ShedDirective { - self.ensure_fresh(); - let level = self.level(); - let planned = self.inner.prefix_planned.load(Ordering::Acquire); - self.inner.prefix_used.store(prefix_used, Ordering::Release); - match level { - Level::Normal => { - self.inner.prefix_target.store(NONE, Ordering::Release); - ShedDirective { level, prefix_budget: None, drop_conversation: false } - } - Level::Shed => { - let now = self.now_ms(); - let last = self.inner.last_shed_ms.load(Ordering::Acquire); - let current = self.inner.prefix_target.load(Ordering::Acquire); - let target = if current == NONE || now.saturating_sub(last) >= 1000 { - let base = if current == NONE { prefix_used.min(planned) } else { current.min(prefix_used) }; - let next = base / 4 * 3; - self.inner.prefix_target.store(next, Ordering::Release); - self.inner.last_shed_ms.store(now, Ordering::Release); - self.inner.counters.shed_steps.fetch_add(1, Ordering::Relaxed); - next - } else { - current - }; - ShedDirective { level, prefix_budget: Some(target), drop_conversation: true } - } - Level::Reject => { - self.inner.prefix_target.store(0, Ordering::Release); - ShedDirective { level, prefix_budget: Some(0), drop_conversation: true } - } - } - } - - pub fn note_prefix_used(&self, bytes: u64) { - self.inner.prefix_used.store(bytes, Ordering::Release); - } - pub fn note_evicted(&self, bytes: u64) { - self.inner.counters.evicted_bytes.fetch_add(bytes, Ordering::Relaxed); - } - - // ---- the sealed memfd --------------------------------------------------------------------------------------- - - /// Map the sealed archive, lock it when the limits allow, and keep the mapping for the residency guard. - #[cfg(all(target_os = "linux", target_pointer_width = "64"))] - pub fn guard_archive(&self, fd: std::os::fd::BorrowedFd<'_>, len: u64) -> Result { - self.guard_archive_extents(fd, len, None) - } - - /// [`Self::guard_archive`] for a sparse memfd: `extents` are the `(offset, len)` ranges that hold data, everything else of the - /// `len`-byte descriptor is a hole. Only the extents are locked and healed (locking or populating a hole allocates zero - /// pages for it, which would turn the sparse copy back into the full archive), the lock limit is judged against their - /// size, and the report says so. `None` is the whole archive. - #[cfg(all(target_os = "linux", target_pointer_width = "64"))] - pub fn guard_archive_extents(&self, fd: std::os::fd::BorrowedFd<'_>, len: u64, extents: Option<&[crate::lock::Span]>) -> Result { - let started = Instant::now(); - let facts = self.probe(); - let mode = self.inner.cfg.lock_mode; - if let Some(spans) = extents - && let Err(why) = crate::lock::check_spans(spans, len) - { - return Err(Refusal { code: "memlock", message: format!("the sparse archive extents are invalid: {why}"), numbers: vec![("archive".to_owned(), len)], advice: vec![] }); - } - // the bytes that are resident and have to be locked - let resident = extents.map_or(len, crate::lock::spans_bytes); - let extent_bytes = extents.map(crate::lock::spans_bytes); - let decision = plan_lock(mode, resident, facts.memlock, &facts.status); - // Map a private READ-ONLY reopen of the descriptor, never the descriptor itself: a write-sealed memfd refuses a shared - // mapping that could become writable (EPERM on kernels up to 5.15 when the description is read-write), and a read-only - // description can never become writable, so the mapping is allowed everywhere and is immutable by construction. - let readonly = { - use std::os::fd::AsRawFd; - std::fs::OpenOptions::new().read(true).open(format!("/proc/self/fd/{}", fd.as_raw_fd())) - }; - let mapped = match &readonly { - Ok(file) => { - use std::os::fd::AsFd as _; - crate::lock::FdMapping::map_readonly(file.as_fd(), usize::try_from(len).unwrap_or(usize::MAX)) - } - Err(e) => Err(std::io::Error::new(e.kind(), format!("cannot reopen the descriptor read-only: {e}"))), - }; - let mut mapping = match mapped { - Ok(m) => m, - Err(e) => { - let report = LockReport { - mode, - decision, - outcome: LockOutcome::NotAttempted { why: format!("mmap of the archive failed: {e}") }, - mapping_bytes: 0, - extent_bytes, - memlock_soft: facts.memlock.map(|m| m.0), - memlock_hard: facts.memlock.map(|m| m.1), - millis: started.elapsed().as_secs_f64() * 1e3, - }; - self.log(&format!("WARNING: cannot map the sealed KAR memfd for the residency guard: {e}")); - if mode == LockMode::Require { - return Err(Refusal { code: "memlock", message: format!("mmap of the archive failed: {e}"), numbers: vec![], advice: vec![] }); - } - return Ok(report); - } - }; - let outcome = match &decision { - LockDecision::Off => LockOutcome::NotAttempted { why: "LELEKA_MEMORY_LOCK=off".into() }, - LockDecision::Insufficient { need, soft, hard, advice } => { - let why = format!( - "RLIMIT_MEMLOCK soft {} MiB / hard {} MiB cannot cover {} MiB", - soft >> 20, - if *hard == u64::MAX { "unlimited".into() } else { (hard >> 20).to_string() }, - need >> 20 - ); - self.log(&format!("WARNING: the sealed KAR memfd ({}) stays swappable: {why}. To keep it resident: {}", gib(resident), advice.join(" | "))); - LockOutcome::NotAttempted { why } - } - LockDecision::Attempt { raise_soft_to } => { - if let Some(to) = raise_soft_to - && let Err(e) = crate::lock::raise_memlock_soft(*to) { - self.log(&format!("WARNING: could not raise the soft RLIMIT_MEMLOCK to {} MiB: {e}", to >> 20)); - } - let policy = self.policy(); - let swapped = self.mapping_swapped(&mapping).unwrap_or(0); - let src = self.inner.src.clone(); - let allow = |n: u64| { - // a swapped-out chunk is read back into RAM: keep the hard floor + reserve - let need = if swapped > 0 { n } else { 0 }; - HostFacts::probe(&*src).effective_available().is_none_or(|a| a.saturating_sub(need) >= policy.hard_floor + policy.reserve) - }; - let outcome = match extents { - Some(spans) => mapping.lock_ranges(spans, GIB, allow), - None => mapping.lock(GIB, allow), - }; - match &outcome { - LockOutcome::Locked { bytes } => self.log(&format!("sealed KAR memfd locked in RAM: {} (mlock, never swapped)", gib(*bytes))), - LockOutcome::Partial { locked, why, .. } => self.log(&format!("WARNING: sealed KAR memfd lock stopped at {} of {}: {why}", gib(*locked), gib(len))), - LockOutcome::NotAttempted { why } => self.log(&format!("sealed KAR memfd lock not attempted: {why}")), - } - outcome - } - }; - let report = LockReport { - mode, - decision: decision.clone(), - outcome: outcome.clone(), - mapping_bytes: len, - extent_bytes, - memlock_soft: facts.memlock.map(|m| m.0), - memlock_hard: facts.memlock.map(|m| m.1), - millis: started.elapsed().as_secs_f64() * 1e3, - }; - if mode == LockMode::Require && !matches!(outcome, LockOutcome::Locked { .. }) { - let (numbers, advice) = match &decision { - LockDecision::Insufficient { need, soft, hard, advice } => ( - vec![("needed to lock".to_owned(), *need), ("RLIMIT_MEMLOCK soft".to_owned(), *soft), ("RLIMIT_MEMLOCK hard".to_owned(), *hard)], - advice.clone(), - ), - _ => (vec![("archive".to_owned(), resident)], vec![]), - }; - return Err(Refusal { code: "memlock", message: format!("LELEKA_MEMORY_LOCK=require but the sealed KAR memfd could not be locked ({outcome:?})"), numbers, advice }); - } - *lock(&self.inner.guarded) = Some(Guarded { mapping, report: report.clone(), extents: extents.map(<[_]>::to_vec), cursor: 0, last_swapped: 0, warned_swapped: 0, last_check: None, last: None }); - Ok(report) - } - - #[cfg(all(target_os = "linux", target_pointer_width = "64"))] - pub(super) fn mapping_swapped(&self, mapping: &crate::lock::FdMapping) -> Option { - let text = self.inner.src.read("/proc/self/smaps").ok()?; - residency_from_smaps(&text, mapping.start(), mapping.len()).map(|r| r.swapped_bytes) - } - - /// Read the swap state of the archive mapping; warn when pages are swapped; pull them back when allowed. - /// Returns the swapped bytes found (0 when no mapping is guarded). - #[cfg(all(target_os = "linux", target_pointer_width = "64"))] - pub fn residency_tick(&self) -> u64 { - let policy = self.policy(); - let mut slot = lock(&self.inner.guarded); - let Some(g) = slot.as_mut() else { return 0 }; - let started = Instant::now(); - let Some(text) = self.inner.src.read("/proc/self/smaps").ok() else { return 0 }; - let Some(r) = residency_from_smaps(&text, g.mapping.start(), g.mapping.len()) else { return 0 }; - let read_ms = started.elapsed().as_secs_f64() * 1e3; - g.last = Some(r); - g.last_check = Some(Instant::now()); - g.last_swapped = r.swapped_bytes; - if r.swapped_bytes >= 64 * MIB && r.swapped_bytes.abs_diff(g.warned_swapped) >= 64 * MIB { - g.warned_swapped = r.swapped_bytes; - self.log(&format!( - "WARNING: {} MiB of the sealed KAR memfd are swapped out ({} of {} resident, locked {} MiB; smaps read {read_ms:.0} ms): PLE reads fault from swap until they are pulled back{}", - r.swapped_bytes >> 20, - gib(r.rss_bytes), - gib(r.mapping_bytes), - r.locked_bytes >> 20, - if self.inner.cfg.heal { "; healing" } else { "" } - )); - } else if r.swapped_bytes < 64 * MIB { - g.warned_swapped = 0; - } - if self.inner.cfg.heal && r.swapped_bytes >= 16 * MIB && self.level() == Level::Normal { - let budget = self.inner.cfg.heal_bytes_per_tick.min(r.swapped_bytes.max(GIB)); - let ok = HostFacts::probe(&*self.inner.src) - .effective_available() - .is_some_and(|a| a.saturating_sub(budget.min(r.swapped_bytes)) >= policy.soft_floor + policy.reserve); - if ok { - let mut done = 0; - match g.extents.clone() { - // a sparse archive: walk the concatenation of the extents, never a hole - Some(spans) => { - let total = crate::lock::spans_bytes(&spans); - while done < budget && done < total { - if g.cursor >= total { - g.cursor = 0; - } - let want = (256 * MIB).min(budget - done); - let Some((offset, piece)) = crate::lock::compact_piece(&spans, g.cursor, want) else { break }; - // whole pages; the last page of the last extent may be partial and is rounded up by the kernel - let n = if g.cursor + piece == total || piece < 4096 { piece } else { piece / 4096 * 4096 }; - if g.mapping.populate(offset, n).is_err() { - break; - } - g.cursor += n; - done += n; - } - } - None => { - let total = g.mapping.len(); - while done < budget && done < total { - if g.cursor >= total { - g.cursor = 0; - } - let n = (256 * MIB).min(total - g.cursor).min(budget - done) / 4096 * 4096; - if n == 0 { - break; - } - if g.mapping.populate(g.cursor, n).is_err() { - break; - } - g.cursor += n; - done += n; - } - } - } - self.inner.counters.heal_bytes.fetch_add(done, Ordering::Relaxed); - self.inner.counters.heal_runs.fetch_add(1, Ordering::Relaxed); - } - } - r.swapped_bytes - } - - #[cfg(not(all(target_os = "linux", target_pointer_width = "64")))] - pub fn residency_tick(&self) -> u64 { - 0 - } - - // ---- report ----------------------------------------------------------------------------------------------- - - pub fn report(&self) -> serde_json::Value { - let facts = self.probe(); - let monitor = lock(&self.inner.monitor); - let policy = self.policy(); - let level = self.level(); - let c = &self.inner.counters; - let planned = self.inner.prefix_planned.load(Ordering::Acquire); - let target = self.inner.prefix_target.load(Ordering::Acquire); - #[cfg(all(target_os = "linux", target_pointer_width = "64"))] - let archive = lock(&self.inner.guarded).as_ref().map(|g| json!({"lock": g.report, "residency": g.last, "heal": {"cursor": g.cursor}})); - #[cfg(not(all(target_os = "linux", target_pointer_width = "64")))] - let archive: Option = None; - json!({ - "version": 1, - "uptime_ms": self.now_ms(), - "gate": { - "level": level.as_str(), - "since_ms": self.inner.since_ms.load(Ordering::Acquire), - "reason": &*lock(&self.inner.reason), - "retry_after_secs": if level == Level::Normal { 0 } else { monitor.retry_after_secs() }, - "available_bytes": self.available_cached(), - "soft_floor_bytes": policy.soft_floor, - "hard_floor_bytes": policy.hard_floor, - }, - "policy": policy, - "config": {"sample_interval_ms": self.inner.cfg.sample_interval_ms, "lock_mode": self.inner.cfg.lock_mode, "heal": self.inner.cfg.heal}, - "plan": self.plan(), - "host": { - "mem_total": facts.meminfo.mem_total, - "mem_available": facts.meminfo.mem_available, - "effective_available": facts.effective_available(), - "swap_total": facts.meminfo.swap_total, - "swap_free": facts.meminfo.swap_free, - "shmem": facts.meminfo.shmem, - "mlocked": facts.meminfo.mlocked, - "cgroup": facts.cgroup, - "psi": facts.psi, - "memlock": facts.memlock, - "wsl": facts.wsl, - "kernel": facts.kernel, - }, - "process": { - "rss": facts.status.vm_rss, "swap": facts.status.vm_swap, "pinned": facts.status.vm_pin, "locked": facts.status.vm_lck, - "threads": facts.status.threads, "fds": facts.open_fds, - }, - "observed": monitor.observed, - "caches": { - "prefix": {"planned_bytes": planned, "shed_target_bytes": if target == NONE { serde_json::Value::Null } else { json!(target) }, "used_bytes": self.inner.prefix_used.load(Ordering::Acquire)}, - }, - "counters": { - "admitted": c.admitted.load(Ordering::Relaxed), - "rejected_memory_pressure": c.rejected_pressure.load(Ordering::Relaxed), - "rejected_context": c.rejected_context.load(Ordering::Relaxed), - "shed_steps": c.shed_steps.load(Ordering::Relaxed), - "evicted_bytes": c.evicted_bytes.load(Ordering::Relaxed), - "samples": c.samples.load(Ordering::Relaxed), - "level_changes": c.level_changes.load(Ordering::Relaxed), - "heal_bytes": c.heal_bytes.load(Ordering::Relaxed), - "heal_runs": c.heal_runs.load(Ordering::Relaxed), - }, - "archive": archive, - "inventory": self.inventory().to_json(), - "ledger": self.inner.ledger.to_json(), - "vram": &*lock(&self.inner.vram), - "plan_check": lock(&self.inner.post_load).map(|(p, a)| json!({"predicted_available_after_fixed": p, "actual_available_after_open": a, "error_bytes": i128::from(a) - i128::from(p)})), - "transitions": &*lock(&self.inner.transitions), - }) - } - - /// Render the report into the cell [`published_report`] reads. - pub fn publish(&self) { - if let Ok(text) = serde_json::to_string(&self.report()) { - *PUBLISHED.lock().unwrap_or_else(|p| p.into_inner()) = Some(text); - } - } - - // ---- sampler ----------------------------------------------------------------------------------------------- - - /// Start the sampler thread (pressure level and report, every interval) and the residency-guard thread (the smaps read of - /// the memfd mapping costs up to a second for 55 GB, which must not delay a pressure sample). Both stop when the guard is - /// dropped. - pub fn spawn_sampler(&self) -> SamplerGuard { - fn nap(inner: &Inner, total: Duration) { - let mut slept = Duration::ZERO; - while slept < total && !inner.stop.load(Ordering::Acquire) { - let step = Duration::from_millis(50).min(total - slept); - std::thread::sleep(step); - slept += step; - } - } - self.inner.stop.store(false, Ordering::Release); - let me = self.clone(); - let sampler = std::thread::Builder::new() - .name("leleka-memory".into()) - .spawn(move || { - let interval = Duration::from_millis(me.inner.cfg.sample_interval_ms); - while !me.inner.stop.load(Ordering::Acquire) { - // a panic in one round (a malformed /proc read, a poisoned state) must not end the thread that lifts a pressure level - let round = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - me.sample_now(); - me.publish(); - })); - if round.is_err() { - me.log("WARNING: the memory sampler round panicked; continuing"); - } - nap(&me.inner, interval); - } - }) - .ok(); - let me = self.clone(); - let guard = std::thread::Builder::new() - .name("leleka-memory-guard".into()) - .spawn(move || { - let every = Duration::from_millis(me.inner.cfg.residency_every_ms); - while !me.inner.stop.load(Ordering::Acquire) { - let round = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| me.residency_tick())); - if round.is_err() { - me.log("WARNING: the memfd residency round panicked; continuing"); - } - nap(&me.inner, every); - } - }) - .ok(); - SamplerGuard { inner: self.inner.clone(), handles: sampler.into_iter().chain(guard).collect() } - } -} +mod impl_governor_2; +mod impl_governor_2_2; +mod impl_governor_3; +mod impl_governor_4; diff --git a/crates/leleka-memory/src/governor/impl_governor/impl_governor_2.rs b/crates/leleka-memory/src/governor/impl_governor/impl_governor_2.rs new file mode 100644 index 00000000..2ba38b9f --- /dev/null +++ b/crates/leleka-memory/src/governor/impl_governor/impl_governor_2.rs @@ -0,0 +1,258 @@ +//! Moved out of the parent module by STRA-338: impl Governor. + +#[allow(unused_imports)] +use super::*; + + + +impl Governor { + pub fn new(cfg: GovernorConfig, src: Arc) -> Self { + let policy0 = cfg.policy; + let monitor = Monitor::new(policy0); + Self { + inner: Arc::new(Inner { + cfg, + src, + epoch: Instant::now(), + plan: Mutex::new(None), + monitor: Mutex::new(monitor), + policy: Mutex::new(policy0), + level: AtomicU8::new(Level::Normal as u8), + reason: Mutex::new("startup".into()), + available: AtomicU64::new(NONE), + sampled_at_ms: AtomicU64::new(0), + prefix_planned: AtomicU64::new(0), + prefix_target: AtomicU64::new(NONE), + prefix_used: AtomicU64::new(0), + last_shed_ms: AtomicU64::new(0), + last_trim_ms: AtomicU64::new(NONE), + last_trim_log_ms: AtomicU64::new(0), + trims: AtomicU64::new(0), + since_ms: AtomicU64::new(0), + transitions: Mutex::new(VecDeque::new()), + counters: Counters::default(), + ledger: Ledger::new(), + vram: Mutex::new(None), + post_load: Mutex::new(None), + #[cfg(all(target_os = "linux", target_pointer_width = "64"))] + guarded: Mutex::new(None), + stop: AtomicBool::new(false), + }), + } + } + + /// A governor over the real `/proc`. + pub fn real(cfg: GovernorConfig) -> Self { + Self::new(cfg, Arc::new(RealProc)) + } + + /// Make this the process-wide governor (the first install wins; later ones are returned unchanged). + pub fn install(self) -> &'static Governor { + GLOBAL.get_or_init(|| self) + } + pub fn global() -> Option<&'static Governor> { + GLOBAL.get() + } + + /// Replace the pressure floors at run time (diagnostics and the shed tests: move the thresholds next to the memory + /// the host has now, so the whole shed path runs without ever approaching the real limit). `hard < soft` is required. + pub fn set_floors(&self, soft_floor: u64, hard_floor: u64) -> Result<(), String> { + if hard_floor >= soft_floor { + return Err(format!("hard floor {hard_floor} must be below the soft floor {soft_floor}")); + } + let mut policy = lock(&self.inner.policy); + policy.soft_floor = soft_floor; + policy.hard_floor = hard_floor; + lock(&self.inner.monitor).set_policy(*policy); + drop(policy); + self.log(&format!("floors set to soft {} MiB / hard {} MiB", soft_floor >> 20, hard_floor >> 20)); + Ok(()) + } + + pub fn config(&self) -> &GovernorConfig { + &self.inner.cfg + } + pub fn policy(&self) -> Policy { + *lock(&self.inner.policy) + } + pub fn inventory(&self) -> &'static Inventory { + Inventory::global() + } + pub fn ledger(&self) -> &Ledger { + &self.inner.ledger + } + pub fn source(&self) -> &(dyn ProcSource + Send + Sync) { + &*self.inner.src + } + pub fn probe(&self) -> HostFacts { + HostFacts::probe(&*self.inner.src) + } + pub fn census(&self) -> Census { + Census::take(&*self.inner.src) + } + pub(in super::super) fn now_ms(&self) -> u64 { + self.inner.epoch.elapsed().as_millis() as u64 + } + pub fn log(&self, text: &str) { + if self.inner.cfg.log { + // Structured and rate limited like every other line; the lab scripts' bare form under LELEKA_LOG_LEGACY=1. + if leleka_obs::settings().legacy { + leleka_obs::legacy_line(&format!("leleka-memory: {text}")); + } else { + leleka_obs::emit_msg(leleka_obs::Level::Info, "memory", "leleka-memory:governor", text); + } + } + } + + // ---- plan ------------------------------------------------------------------------------------------------- + + /// Plan the budget (or refuse), log the plan, register the expected size of every fixed item in the inventory and keep + /// the plan for the report. + pub fn startup(&self, input: &crate::plan::PlanInput) -> Result { + let plan = match crate::plan::plan(input) { + Ok(plan) => plan, + Err(refusal) => { + self.log(&format!("REFUSING TO START: {refusal}")); + return Err(refusal); + } + }; + let inv = self.inventory(); + for item in &plan.fixed { + inv.set( + crate::inventory::Entry::new("planned", &item.name, item.space, crate::inventory::When::Startup, &item.formula) + .expected(item.bytes) + .swappable(false), + ); + } + self.log(&format!( + "budget: available {} - fixed {} - memfd to create {} = {} after the fixed footprint; floors soft {} / hard {}; elastic {}: resident complement {}, prefix cache {}, conversation checkpoints {} ({}){}", + plan.available_before.map_or("unknown".into(), gib), + gib(plan.fixed_bytes), + gib(plan.kar_to_create), + plan.available_after_fixed.map_or("unknown".into(), gib), + gib(plan.soft_floor), + gib(plan.hard_floor), + gib(plan.elastic), + gib(plan.resident_complement_bytes), + gib(plan.prefix_bytes), + plan.conversation_checkpoints, + gib(plan.conversation_bytes), + if plan.blind { "; BLIND: no memory telemetry, caches off" } else { "" } + )); + for note in &plan.notes { + self.log(&format!("note: {note}")); + } + self.set_plan(plan.clone()); + Ok(plan) + } + + /// The device check once the device is visible (`cuMemGetInfo`): refuse or note, and keep the numbers for the report. + pub fn check_vram(&self, vram: crate::plan::VramFacts, budget: u64, fixed_estimate: Option) -> Result<(), Refusal> { + match crate::plan::check_vram(&self.policy(), vram, budget, fixed_estimate) { + Ok((plan, note)) => { + if let Some(note) = note { + self.log(&format!("note: {note}")); + } + *lock(&self.inner.vram) = Some(plan); + Ok(()) + } + Err(refusal) => { + self.log(&format!("REFUSING TO START: {refusal}")); + Err(refusal) + } + } + } + + /// Compare the plan's prediction with what the host really has after the stack opened, log the error when it matters and keep it for the + /// report (`plan_check`). Returns `actual - predicted` in bytes (negative: the footprint was bigger than planned). + pub fn note_post_load(&self, actual_available: Option) -> Option { + let predicted = lock(&self.inner.plan).as_ref().and_then(|p| p.available_after_fixed)?; + let actual = actual_available?; + *lock(&self.inner.post_load) = Some((predicted, actual)); + let error = i128::from(actual) - i128::from(predicted); + let error = i64::try_from(error).unwrap_or(if error < 0 { i64::MIN } else { i64::MAX }); + if error.unsigned_abs() > 512 * MIB { + self.log(&format!( + "WARNING: the startup plan predicted {} available after the fixed footprint, the host has {} after the stack opened ({:+} MiB): the footprint constants are off, caches are sized from the measured value", + gib(predicted), + gib(actual), + error >> 20 + )); + } + Some(error) + } + + pub fn set_plan(&self, plan: Plan) { + self.inner.prefix_planned.store(plan.prefix_bytes, Ordering::Release); + *lock(&self.inner.plan) = Some(plan); + } + pub fn plan(&self) -> Option { + lock(&self.inner.plan).clone() + } + /// The prefix budget decided at stack open (after the fixed items are resident); the shed target is relative to it. + pub fn set_prefix_budget(&self, bytes: u64) { + self.inner.prefix_planned.store(bytes, Ordering::Release); + } + + // ---- level ------------------------------------------------------------------------------------------------ + + pub fn level(&self) -> Level { + Level::from_u8(self.inner.level.load(Ordering::Acquire)) + } + + /// The caller's own sample when the sampler thread has not delivered one for five intervals (it died, or was never started): + /// a stuck `reject` must not outlive the thread that would have lifted it, so the owner thread drives the monitor itself. + pub(in super::super) fn ensure_fresh(&self) { + let interval = self.inner.cfg.sample_interval_ms.max(50); + let now = self.now_ms(); + let last = self.inner.sampled_at_ms.load(Ordering::Acquire); + if now.saturating_sub(last) > interval.saturating_mul(5) && self.inner.counters.samples.load(Ordering::Relaxed) > 0 { + self.sample_at(now); + } + } + /// A fresh reading of the effective available memory (one probe of a dozen small files). + pub fn available_now(&self) -> Option { + self.probe().effective_available() + } + /// The last sampled value (at most one sample interval old); `None` before the first sample or when unknown. + pub fn available_cached(&self) -> Option { + match self.inner.available.load(Ordering::Acquire) { + NONE => None, + v => Some(v), + } + } + + /// Take a sample now and apply it. Returns the transition, if any. + pub fn sample_now(&self) -> Option { + self.sample_at(self.now_ms()) + } + + pub fn sample_at(&self, at_ms: u64) -> Option { + let facts = self.relieve_working_set(self.probe()); + let sample = Sample { + at_ms, + available: facts.effective_available(), + psi: facts.psi, + events: facts.cgroup.as_ref().and_then(|c| c.events), + pswpout: facts.pswpout, + }; + self.inner.counters.samples.fetch_add(1, Ordering::Relaxed); + self.inner.available.store(sample.available.unwrap_or(NONE), Ordering::Release); + self.inner.sampled_at_ms.store(at_ms, Ordering::Release); + let transition = lock(&self.inner.monitor).update(&sample); + if let Some(t) = &transition { + self.inner.level.store(t.to as u8, Ordering::Release); + self.inner.since_ms.store(at_ms, Ordering::Release); + *lock(&self.inner.reason) = t.reason.0.clone(); + self.inner.counters.level_changes.fetch_add(1, Ordering::Relaxed); + let mut q = lock(&self.inner.transitions); + if q.len() >= 32 { + q.pop_front(); + } + q.push_back(TransitionRecord { at_ms, from: t.from, to: t.to, reason: t.reason.0.clone() }); + drop(q); + self.log(&format!("memory pressure {} -> {}: {}", t.from.as_str(), t.to.as_str(), t.reason.0)); + } + transition + } +} diff --git a/crates/leleka-memory/src/governor/impl_governor/impl_governor_2_2.rs b/crates/leleka-memory/src/governor/impl_governor/impl_governor_2_2.rs new file mode 100644 index 00000000..cbf917b7 --- /dev/null +++ b/crates/leleka-memory/src/governor/impl_governor/impl_governor_2_2.rs @@ -0,0 +1,161 @@ +//! Moved out of the parent module by STRA-338: impl Governor (2). + +#[allow(unused_imports)] +use super::*; + + + +impl Governor { + + // ---- admission and shedding ------------------------------------------------------------------------------- + + /// May this request start? Context first (a request that can never fit is a 400, not a retry), then the pressure level, + /// then whether its own transient memory would take the host below the hard floor. + pub fn admit(&self, shape: &RequestShape) -> Admission { + let c = &self.inner.counters; + let needed = shape.prompt_tokens.saturating_add(shape.max_new_tokens).saturating_add(8); + if needed > shape.max_context { + c.rejected_context.fetch_add(1, Ordering::Relaxed); + return Admission::Refuse(Refuse { + status: 400, + code: "context_length_exceeded", + message: format!( + "the request needs {needed} tokens (prompt {} + up to {} new + 8) but the pinned K/V image holds {} tokens", + shape.prompt_tokens, shape.max_new_tokens, shape.max_context + ), + retry_after_secs: 0, + }); + } + self.ensure_fresh(); + let level = self.level(); + let retry = lock(&self.inner.monitor).retry_after_secs().max(1); + if level == Level::Reject { + c.rejected_pressure.fetch_add(1, Ordering::Relaxed); + return Admission::Refuse(Refuse { + status: 503, + code: "memory_pressure", + message: format!("host memory is under pressure ({}); retry shortly", lock(&self.inner.reason)), + retry_after_secs: retry, + }); + } + // the transient of one request (checkpoint / node state / import staging) must not take the host below the hard floor + let transient = self.policy().reserve / 4; + if let Some(available) = self.available_now() + && available.saturating_sub(transient) < self.policy().hard_floor { + c.rejected_pressure.fetch_add(1, Ordering::Relaxed); + return Admission::Refuse(Refuse { + status: 503, + code: "memory_pressure", + message: format!( + "{} available is within {} of the hard floor {}; retry shortly", + gib(available), + gib(transient), + gib(self.policy().hard_floor) + ), + retry_after_secs: retry, + }); + } + c.admitted.fetch_add(1, Ordering::Relaxed); + Admission::Admit + } + + /// Windows keeps touched mapped pages in the working set, where they count as used. When the host reads below the soft floor, hand them back to + /// the standby list (at most every 250 ms) and read the host again, so that a dip caused only by trimmable mapped pages never reaches the monitor: + /// a shed evicts prefix-cache blocks, and live runs showed it firing every few seconds at the floor (laptop 256k session, 2026-10-26: 113 blocks + /// evicted, the fourth turn re-read 223k tokens in 32 minutes). + pub(in super::super) fn relieve_working_set(&self, facts: HostFacts) -> HostFacts { + self.relieve_working_set_below(facts, self.policy().soft_floor) + } + + /// The available memory after handing the engine's trimmable working-set pages back, for a cache owner that needs `needed` bytes of it + /// (a prefix-cache checkpoint must leave the admit floor free: a reading of 8.9 GiB against a floor of 9.2 GiB refused a 0.2 GiB checkpoint + /// that the very next trim would have admitted, because the periodic trim only runs below the soft floor). At most one trim per 250 ms. + pub fn available_after_relief(&self, needed: u64) -> Option { + let facts = self.probe(); + self.relieve_working_set_below(facts, needed).effective_available() + } + + pub(in super::super) fn relieve_working_set_below(&self, facts: HostFacts, threshold: u64) -> HostFacts { + if !cfg!(windows) { + return facts; + } + // A/B inside one engine (bring-up): no trim while the file named by LELEKA_NO_TRIM_FILE exists + static NO_TRIM_FILE: OnceLock> = OnceLock::new(); + if NO_TRIM_FILE.get_or_init(|| std::env::var_os("LELEKA_NO_TRIM_FILE").map(std::path::PathBuf::from)).as_ref().is_some_and(|f| f.exists()) { + return facts; + } + let Some(available) = facts.effective_available() else { return facts }; + if available >= threshold { + return facts; + } + let now = self.now_ms(); + let last = self.inner.last_trim_ms.load(Ordering::Acquire); + if last != NONE && now.saturating_sub(last) < WORKING_SET_TRIM_EVERY.as_millis() as u64 { + return facts; + } + self.inner.last_trim_ms.store(now, Ordering::Release); + if !crate::winproc::trim_working_set() { + return facts; + } + let after = self.probe(); + let trims = self.inner.trims.fetch_add(1, Ordering::Relaxed) + 1; + if trims == 1 || now.saturating_sub(self.inner.last_trim_log_ms.load(Ordering::Relaxed)) >= 10_000 { + self.inner.last_trim_log_ms.store(now, Ordering::Relaxed); + self.log(&format!( + "working set trimmed (#{trims}): available {} -> {} MiB", + available >> 20, + after.effective_available().unwrap_or(0) >> 20 + )); + } + after + } + + /// What the cache owners must do at this level. The prefix target steps down by a quarter per second while shedding. + pub fn directive(&self, prefix_used: u64) -> ShedDirective { + self.ensure_fresh(); + let level = self.level(); + let planned = self.inner.prefix_planned.load(Ordering::Acquire); + self.inner.prefix_used.store(prefix_used, Ordering::Release); + match level { + Level::Normal => { + self.inner.prefix_target.store(NONE, Ordering::Release); + ShedDirective { level, prefix_budget: None, drop_conversation: false } + } + Level::Shed => { + let now = self.now_ms(); + let last = self.inner.last_shed_ms.load(Ordering::Acquire); + let current = self.inner.prefix_target.load(Ordering::Acquire); + let target = if current == NONE || now.saturating_sub(last) >= 1000 { + let base = if current == NONE { prefix_used.min(planned) } else { current.min(prefix_used) }; + let next = base / 4 * 3; + self.inner.prefix_target.store(next, Ordering::Release); + self.inner.last_shed_ms.store(now, Ordering::Release); + self.inner.counters.shed_steps.fetch_add(1, Ordering::Relaxed); + next + } else { + current + }; + ShedDirective { level, prefix_budget: Some(target), drop_conversation: true } + } + Level::Reject => { + self.inner.prefix_target.store(0, Ordering::Release); + ShedDirective { level, prefix_budget: Some(0), drop_conversation: true } + } + } + } + + pub fn note_prefix_used(&self, bytes: u64) { + self.inner.prefix_used.store(bytes, Ordering::Release); + } + pub fn note_evicted(&self, bytes: u64) { + self.inner.counters.evicted_bytes.fetch_add(bytes, Ordering::Relaxed); + } + + // ---- the sealed memfd --------------------------------------------------------------------------------------- + + /// Map the sealed archive, lock it when the limits allow, and keep the mapping for the residency guard. + #[cfg(all(target_os = "linux", target_pointer_width = "64"))] + pub fn guard_archive(&self, fd: std::os::fd::BorrowedFd<'_>, len: u64) -> Result { + self.guard_archive_extents(fd, len, None) + } +} diff --git a/crates/leleka-memory/src/governor/impl_governor/impl_governor_3.rs b/crates/leleka-memory/src/governor/impl_governor/impl_governor_3.rs new file mode 100644 index 00000000..c6d2e0a0 --- /dev/null +++ b/crates/leleka-memory/src/governor/impl_governor/impl_governor_3.rs @@ -0,0 +1,211 @@ +//! Moved out of the parent module by STRA-338: impl Governor (3). + +#[allow(unused_imports)] +use super::*; + + + +impl Governor { + + /// [`Self::guard_archive`] for a sparse memfd: `extents` are the `(offset, len)` ranges that hold data, everything else of the + /// `len`-byte descriptor is a hole. Only the extents are locked and healed (locking or populating a hole allocates zero + /// pages for it, which would turn the sparse copy back into the full archive), the lock limit is judged against their + /// size, and the report says so. `None` is the whole archive. + #[cfg(all(target_os = "linux", target_pointer_width = "64"))] + pub fn guard_archive_extents(&self, fd: std::os::fd::BorrowedFd<'_>, len: u64, extents: Option<&[crate::lock::Span]>) -> Result { + let started = Instant::now(); + let facts = self.probe(); + let mode = self.inner.cfg.lock_mode; + if let Some(spans) = extents + && let Err(why) = crate::lock::check_spans(spans, len) + { + return Err(Refusal { code: "memlock", message: format!("the sparse archive extents are invalid: {why}"), numbers: vec![("archive".to_owned(), len)], advice: vec![] }); + } + // the bytes that are resident and have to be locked + let resident = extents.map_or(len, crate::lock::spans_bytes); + let extent_bytes = extents.map(crate::lock::spans_bytes); + let decision = plan_lock(mode, resident, facts.memlock, &facts.status); + // Map a private READ-ONLY reopen of the descriptor, never the descriptor itself: a write-sealed memfd refuses a shared + // mapping that could become writable (EPERM on kernels up to 5.15 when the description is read-write), and a read-only + // description can never become writable, so the mapping is allowed everywhere and is immutable by construction. + let readonly = { + use std::os::fd::AsRawFd; + std::fs::OpenOptions::new().read(true).open(format!("/proc/self/fd/{}", fd.as_raw_fd())) + }; + let mapped = match &readonly { + Ok(file) => { + use std::os::fd::AsFd as _; + crate::lock::FdMapping::map_readonly(file.as_fd(), usize::try_from(len).unwrap_or(usize::MAX)) + } + Err(e) => Err(std::io::Error::new(e.kind(), format!("cannot reopen the descriptor read-only: {e}"))), + }; + let mut mapping = match mapped { + Ok(m) => m, + Err(e) => { + let report = LockReport { + mode, + decision, + outcome: LockOutcome::NotAttempted { why: format!("mmap of the archive failed: {e}") }, + mapping_bytes: 0, + extent_bytes, + memlock_soft: facts.memlock.map(|m| m.0), + memlock_hard: facts.memlock.map(|m| m.1), + millis: started.elapsed().as_secs_f64() * 1e3, + }; + self.log(&format!("WARNING: cannot map the sealed KAR memfd for the residency guard: {e}")); + if mode == LockMode::Require { + return Err(Refusal { code: "memlock", message: format!("mmap of the archive failed: {e}"), numbers: vec![], advice: vec![] }); + } + return Ok(report); + } + }; + let outcome = match &decision { + LockDecision::Off => LockOutcome::NotAttempted { why: "LELEKA_MEMORY_LOCK=off".into() }, + LockDecision::Insufficient { need, soft, hard, advice } => { + let why = format!( + "RLIMIT_MEMLOCK soft {} MiB / hard {} MiB cannot cover {} MiB", + soft >> 20, + if *hard == u64::MAX { "unlimited".into() } else { (hard >> 20).to_string() }, + need >> 20 + ); + self.log(&format!("WARNING: the sealed KAR memfd ({}) stays swappable: {why}. To keep it resident: {}", gib(resident), advice.join(" | "))); + LockOutcome::NotAttempted { why } + } + LockDecision::Attempt { raise_soft_to } => { + if let Some(to) = raise_soft_to + && let Err(e) = crate::lock::raise_memlock_soft(*to) { + self.log(&format!("WARNING: could not raise the soft RLIMIT_MEMLOCK to {} MiB: {e}", to >> 20)); + } + let policy = self.policy(); + let swapped = self.mapping_swapped(&mapping).unwrap_or(0); + let src = self.inner.src.clone(); + let allow = |n: u64| { + // a swapped-out chunk is read back into RAM: keep the hard floor + reserve + let need = if swapped > 0 { n } else { 0 }; + HostFacts::probe(&*src).effective_available().is_none_or(|a| a.saturating_sub(need) >= policy.hard_floor + policy.reserve) + }; + let outcome = match extents { + Some(spans) => mapping.lock_ranges(spans, GIB, allow), + None => mapping.lock(GIB, allow), + }; + match &outcome { + LockOutcome::Locked { bytes } => self.log(&format!("sealed KAR memfd locked in RAM: {} (mlock, never swapped)", gib(*bytes))), + LockOutcome::Partial { locked, why, .. } => self.log(&format!("WARNING: sealed KAR memfd lock stopped at {} of {}: {why}", gib(*locked), gib(len))), + LockOutcome::NotAttempted { why } => self.log(&format!("sealed KAR memfd lock not attempted: {why}")), + } + outcome + } + }; + let report = LockReport { + mode, + decision: decision.clone(), + outcome: outcome.clone(), + mapping_bytes: len, + extent_bytes, + memlock_soft: facts.memlock.map(|m| m.0), + memlock_hard: facts.memlock.map(|m| m.1), + millis: started.elapsed().as_secs_f64() * 1e3, + }; + if mode == LockMode::Require && !matches!(outcome, LockOutcome::Locked { .. }) { + let (numbers, advice) = match &decision { + LockDecision::Insufficient { need, soft, hard, advice } => ( + vec![("needed to lock".to_owned(), *need), ("RLIMIT_MEMLOCK soft".to_owned(), *soft), ("RLIMIT_MEMLOCK hard".to_owned(), *hard)], + advice.clone(), + ), + _ => (vec![("archive".to_owned(), resident)], vec![]), + }; + return Err(Refusal { code: "memlock", message: format!("LELEKA_MEMORY_LOCK=require but the sealed KAR memfd could not be locked ({outcome:?})"), numbers, advice }); + } + *lock(&self.inner.guarded) = Some(Guarded { mapping, report: report.clone(), extents: extents.map(<[_]>::to_vec), cursor: 0, last_swapped: 0, warned_swapped: 0, last_check: None, last: None }); + Ok(report) + } + + #[cfg(all(target_os = "linux", target_pointer_width = "64"))] + pub(in super::super) fn mapping_swapped(&self, mapping: &crate::lock::FdMapping) -> Option { + let text = self.inner.src.read("/proc/self/smaps").ok()?; + residency_from_smaps(&text, mapping.start(), mapping.len()).map(|r| r.swapped_bytes) + } + + /// Read the swap state of the archive mapping; warn when pages are swapped; pull them back when allowed. + /// Returns the swapped bytes found (0 when no mapping is guarded). + #[cfg(all(target_os = "linux", target_pointer_width = "64"))] + pub fn residency_tick(&self) -> u64 { + let policy = self.policy(); + let mut slot = lock(&self.inner.guarded); + let Some(g) = slot.as_mut() else { return 0 }; + let started = Instant::now(); + let Some(text) = self.inner.src.read("/proc/self/smaps").ok() else { return 0 }; + let Some(r) = residency_from_smaps(&text, g.mapping.start(), g.mapping.len()) else { return 0 }; + let read_ms = started.elapsed().as_secs_f64() * 1e3; + g.last = Some(r); + g.last_check = Some(Instant::now()); + g.last_swapped = r.swapped_bytes; + if r.swapped_bytes >= 64 * MIB && r.swapped_bytes.abs_diff(g.warned_swapped) >= 64 * MIB { + g.warned_swapped = r.swapped_bytes; + self.log(&format!( + "WARNING: {} MiB of the sealed KAR memfd are swapped out ({} of {} resident, locked {} MiB; smaps read {read_ms:.0} ms): PLE reads fault from swap until they are pulled back{}", + r.swapped_bytes >> 20, + gib(r.rss_bytes), + gib(r.mapping_bytes), + r.locked_bytes >> 20, + if self.inner.cfg.heal { "; healing" } else { "" } + )); + } else if r.swapped_bytes < 64 * MIB { + g.warned_swapped = 0; + } + if self.inner.cfg.heal && r.swapped_bytes >= 16 * MIB && self.level() == Level::Normal { + let budget = self.inner.cfg.heal_bytes_per_tick.min(r.swapped_bytes.max(GIB)); + let ok = HostFacts::probe(&*self.inner.src) + .effective_available() + .is_some_and(|a| a.saturating_sub(budget.min(r.swapped_bytes)) >= policy.soft_floor + policy.reserve); + if ok { + let mut done = 0; + match g.extents.clone() { + // a sparse archive: walk the concatenation of the extents, never a hole + Some(spans) => { + let total = crate::lock::spans_bytes(&spans); + while done < budget && done < total { + if g.cursor >= total { + g.cursor = 0; + } + let want = (256 * MIB).min(budget - done); + let Some((offset, piece)) = crate::lock::compact_piece(&spans, g.cursor, want) else { break }; + // whole pages; the last page of the last extent may be partial and is rounded up by the kernel + let n = if g.cursor + piece == total || piece < 4096 { piece } else { piece / 4096 * 4096 }; + if g.mapping.populate(offset, n).is_err() { + break; + } + g.cursor += n; + done += n; + } + } + None => { + let total = g.mapping.len(); + while done < budget && done < total { + if g.cursor >= total { + g.cursor = 0; + } + let n = (256 * MIB).min(total - g.cursor).min(budget - done) / 4096 * 4096; + if n == 0 { + break; + } + if g.mapping.populate(g.cursor, n).is_err() { + break; + } + g.cursor += n; + done += n; + } + } + } + self.inner.counters.heal_bytes.fetch_add(done, Ordering::Relaxed); + self.inner.counters.heal_runs.fetch_add(1, Ordering::Relaxed); + } + } + r.swapped_bytes + } + + #[cfg(not(all(target_os = "linux", target_pointer_width = "64")))] + pub fn residency_tick(&self) -> u64 { + 0 + } +} diff --git a/crates/leleka-memory/src/governor/impl_governor/impl_governor_4.rs b/crates/leleka-memory/src/governor/impl_governor/impl_governor_4.rs new file mode 100644 index 00000000..d52d6374 --- /dev/null +++ b/crates/leleka-memory/src/governor/impl_governor/impl_governor_4.rs @@ -0,0 +1,137 @@ +//! Moved out of the parent module by STRA-338: impl Governor (4). + +#[allow(unused_imports)] +use super::*; + + + +impl Governor { + + // ---- report ----------------------------------------------------------------------------------------------- + + pub fn report(&self) -> serde_json::Value { + let facts = self.probe(); + let monitor = lock(&self.inner.monitor); + let policy = self.policy(); + let level = self.level(); + let c = &self.inner.counters; + let planned = self.inner.prefix_planned.load(Ordering::Acquire); + let target = self.inner.prefix_target.load(Ordering::Acquire); + #[cfg(all(target_os = "linux", target_pointer_width = "64"))] + let archive = lock(&self.inner.guarded).as_ref().map(|g| json!({"lock": g.report, "residency": g.last, "heal": {"cursor": g.cursor}})); + #[cfg(not(all(target_os = "linux", target_pointer_width = "64")))] + let archive: Option = None; + json!({ + "version": 1, + "uptime_ms": self.now_ms(), + "gate": { + "level": level.as_str(), + "since_ms": self.inner.since_ms.load(Ordering::Acquire), + "reason": &*lock(&self.inner.reason), + "retry_after_secs": if level == Level::Normal { 0 } else { monitor.retry_after_secs() }, + "available_bytes": self.available_cached(), + "soft_floor_bytes": policy.soft_floor, + "hard_floor_bytes": policy.hard_floor, + }, + "policy": policy, + "config": {"sample_interval_ms": self.inner.cfg.sample_interval_ms, "lock_mode": self.inner.cfg.lock_mode, "heal": self.inner.cfg.heal}, + "plan": self.plan(), + "host": { + "mem_total": facts.meminfo.mem_total, + "mem_available": facts.meminfo.mem_available, + "effective_available": facts.effective_available(), + "swap_total": facts.meminfo.swap_total, + "swap_free": facts.meminfo.swap_free, + "shmem": facts.meminfo.shmem, + "mlocked": facts.meminfo.mlocked, + "cgroup": facts.cgroup, + "psi": facts.psi, + "memlock": facts.memlock, + "wsl": facts.wsl, + "kernel": facts.kernel, + }, + "process": { + "rss": facts.status.vm_rss, "swap": facts.status.vm_swap, "pinned": facts.status.vm_pin, "locked": facts.status.vm_lck, + "threads": facts.status.threads, "fds": facts.open_fds, + }, + "observed": monitor.observed, + "caches": { + "prefix": {"planned_bytes": planned, "shed_target_bytes": if target == NONE { serde_json::Value::Null } else { json!(target) }, "used_bytes": self.inner.prefix_used.load(Ordering::Acquire)}, + }, + "counters": { + "admitted": c.admitted.load(Ordering::Relaxed), + "rejected_memory_pressure": c.rejected_pressure.load(Ordering::Relaxed), + "rejected_context": c.rejected_context.load(Ordering::Relaxed), + "shed_steps": c.shed_steps.load(Ordering::Relaxed), + "evicted_bytes": c.evicted_bytes.load(Ordering::Relaxed), + "samples": c.samples.load(Ordering::Relaxed), + "level_changes": c.level_changes.load(Ordering::Relaxed), + "heal_bytes": c.heal_bytes.load(Ordering::Relaxed), + "heal_runs": c.heal_runs.load(Ordering::Relaxed), + }, + "archive": archive, + "inventory": self.inventory().to_json(), + "ledger": self.inner.ledger.to_json(), + "vram": &*lock(&self.inner.vram), + "plan_check": lock(&self.inner.post_load).map(|(p, a)| json!({"predicted_available_after_fixed": p, "actual_available_after_open": a, "error_bytes": i128::from(a) - i128::from(p)})), + "transitions": &*lock(&self.inner.transitions), + }) + } + + /// Render the report into the cell [`published_report`] reads. + pub fn publish(&self) { + if let Ok(text) = serde_json::to_string(&self.report()) { + *PUBLISHED.lock().unwrap_or_else(|p| p.into_inner()) = Some(text); + } + } + + // ---- sampler ----------------------------------------------------------------------------------------------- + + /// Start the sampler thread (pressure level and report, every interval) and the residency-guard thread (the smaps read of + /// the memfd mapping costs up to a second for 55 GB, which must not delay a pressure sample). Both stop when the guard is + /// dropped. + pub fn spawn_sampler(&self) -> SamplerGuard { + fn nap(inner: &Inner, total: Duration) { + let mut slept = Duration::ZERO; + while slept < total && !inner.stop.load(Ordering::Acquire) { + let step = Duration::from_millis(50).min(total - slept); + std::thread::sleep(step); + slept += step; + } + } + self.inner.stop.store(false, Ordering::Release); + let me = self.clone(); + let sampler = std::thread::Builder::new() + .name("leleka-memory".into()) + .spawn(move || { + let interval = Duration::from_millis(me.inner.cfg.sample_interval_ms); + while !me.inner.stop.load(Ordering::Acquire) { + // a panic in one round (a malformed /proc read, a poisoned state) must not end the thread that lifts a pressure level + let round = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + me.sample_now(); + me.publish(); + })); + if round.is_err() { + me.log("WARNING: the memory sampler round panicked; continuing"); + } + nap(&me.inner, interval); + } + }) + .ok(); + let me = self.clone(); + let guard = std::thread::Builder::new() + .name("leleka-memory-guard".into()) + .spawn(move || { + let every = Duration::from_millis(me.inner.cfg.residency_every_ms); + while !me.inner.stop.load(Ordering::Acquire) { + let round = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| me.residency_tick())); + if round.is_err() { + me.log("WARNING: the memfd residency round panicked; continuing"); + } + nap(&me.inner, every); + } + }) + .ok(); + SamplerGuard { inner: self.inner.clone(), handles: sampler.into_iter().chain(guard).collect() } + } +} diff --git a/crates/leleka-runtime/src/conversation/manager/impl_conversationmanager.rs b/crates/leleka-runtime/src/conversation/manager/impl_conversationmanager.rs index 0c78603b..83e42823 100644 --- a/crates/leleka-runtime/src/conversation/manager/impl_conversationmanager.rs +++ b/crates/leleka-runtime/src/conversation/manager/impl_conversationmanager.rs @@ -3,411 +3,5 @@ #[allow(unused_imports)] use super::*; - -impl ConversationManager { - pub fn new(options: ConversationOptions) -> Self { - let budget = if options.prompt_cache > 0 { - options.conversation_cache_bytes - } else { - 0 - }; - let cache = ConversationCache::new(budget, options.conversation_cache_slots); - Self { - options, - live: Vec::new(), - live_imgs: Vec::new(), - live_ok: false, - checks: Vec::new(), - check_clock: 0, - cvec_cached: true, - cache, - pp_next_check: 0, - events: Vec::new(), - } - } - - pub fn options(&self) -> &ConversationOptions { - &self.options - } - pub fn live(&self) -> &[i32] { - &self.live - } - pub fn live_ok(&self) -> bool { - self.live_ok - } - pub fn checkpoints(&self) -> &[ConversationCheckpoint] { - &self.checks - } - pub fn cvec_cached(&self) -> bool { - self.cvec_cached - } - pub fn cache(&self) -> &ConversationCache { - &self.cache - } - /// The checkpoints' LRU clock. - pub fn check_clock(&self) -> u64 { - self.check_clock - } - /// Next prompt position at which a periodic checkpoint is due. - pub fn next_periodic_checkpoint(&self) -> i64 { - self.pp_next_check - } - /// Operator-facing log lines produced since the last call. - pub fn take_events(&mut self) -> Vec { - std::mem::take(&mut self.events) - } - - /// Drop everything that refers to the device's state (after an unload, - /// a reset or a fatal device error). - pub fn invalidate(&mut self) { - self.live.clear(); - self.live_imgs.clear(); - self.live_ok = false; - self.checks.clear(); - self.cache = ConversationCache::new(self.cache.budget(), self.cache.slots()); - self.pp_next_check = 0; - } - - /// Save only on a switch/rewind, not on each continuing request. `held` is - /// an incoming image that is still alive during the exchange. Anything - /// recoverable (nothing to park, no room, no RAM, allocation failure) - /// skips parking and returns `Ok`; a device failure is fatal. - pub(super) fn park_current(&mut self, engine: &mut dyn SessionEngine, held: usize) -> ConvResult<()> { - if !self.cache.enabled() || !self.live_ok || self.live.is_empty() { - return Ok(()); - } - let view = ConversationView { - ids: &self.live, - images: &self.live_imgs, - checkpoints: &self.checks, - cvec: self.cvec_cached, - }; - let mut reuse = self.cache.take_reuse(); - let fresh_estimate = match engine.snapshot_bytes(&view) { - Ok(n) => n, - Err(e) => { - self.events - .push(format!("conversation cache: skip parking ({e})")); - return Ok(()); - } - }; - let mut estimate = fresh_estimate; - if !reuse.kv.is_empty() { - match engine.snapshot_capture_bytes(&reuse, &view) { - Ok(n) => estimate = n, - Err(_) => { - reuse = ConversationKvReuse::default(); - estimate = fresh_estimate; - } - } - } - // A park carrying its own retained K/V replaces memory the cache - // already held, so capacity is make_room's call: the with-reuse - // estimate must stay uncapped, because put() charges that same true - // size and a capped figure would under-evict and overfill the budget. - // #342: before make_room evicts oldest-first, the copies of this - // conversation a turn back go. - let keys: Vec> = self - .checks - .iter() - .map(|c| CheckpointKey { - ids: &c.ids, - imgs: &c.imgs, - }) - .collect(); - let dropped = - self.cache - .drop_superseded(&self.live, &self.live_imgs, &keys, self.cvec_cached); - if dropped != 0 { - self.events.push(format!( - "conversation cache: dropped {dropped} superseded cop{} of this conversation; parked={}", - if dropped == 1 { "y" } else { "ies" }, - self.cache.size() - )); - } - if !self.cache.make_room(estimate, held) { - self.events.push(format!( - "conversation cache: skip parking (snapshot {} MiB exceeds available budget)", - estimate >> 20 - )); - return Ok(()); - } - let floor = self.options.conversation_cache_min_free_bytes; - let additional = estimate.saturating_sub(reuse.bytes()); - if !memory_admit(engine.available_memory(), additional as u64, floor) { - self.events.push(format!( - "conversation cache: skip parking (physical RAM admission; need {} MiB plus {} MiB floor, or telemetry unavailable)", - additional >> 20, - floor >> 20 - )); - return Ok(()); - } - let mut reused_bytes = 0usize; - let image = match engine.snapshot_save(&view, reuse, &mut reused_bytes) { - Ok(image) => image, - Err(e) if is_allocation(&e) => { - // The active state has not been touched: continue with normal - // prompt processing rather than killing a serving process. - self.events - .push("conversation cache: allocation failed; skip parking".into()); - return Ok(()); - } - Err(e) => return Err(e), - }; - if !memory_admit(engine.available_memory(), 0, floor) { - self.events.push( - "conversation cache: skip parking (physical RAM floor after capture, or telemetry unavailable)".into(), - ); - return Ok(()); - } - let snapshot_bytes = image.bytes(); - let tokens = self.live.len(); - let stored = self.cache.put(image, held).is_ok(); - self.events.push(format!( - "conversation cache: {} {tokens} tokens; parked={} bytes={} evictions={} snapshot_bytes={snapshot_bytes} reused_kv_bytes={reused_bytes}", - if stored { "parked" } else { "skipped" }, - self.cache.size(), - self.cache.bytes(), - self.cache.evictions(), - )); - Ok(()) - } - - /// Decide where `ids` starts reading and put the device in that state: - /// continue the live session, restore a checkpoint, restore a parked - /// conversation (parking the outgoing one first), or start empty. Any - /// error is fatal for the request and the device state is then undefined. - pub fn begin_request( - &mut self, - engine: &mut dyn SessionEngine, - ids: &[i32], - req_imgs: &[ConversationImageKey], - want_cvec: bool, - ) -> ConvResult { - let prompt_cache = self.options.prompt_cache > 0; - let mut resume = 0usize; - let mut from_live = false; - if prompt_cache && want_cvec == self.cvec_cached { - if self.live_ok && starts_with(&self.live, &self.live_imgs, ids, req_imgs) { - resume = self.live.len(); - from_live = true; - } - for c in &self.checks { - if c.ids.len() > resume && starts_with(&c.ids, &c.imgs, ids, req_imgs) { - resume = c.ids.len(); - from_live = false; - } - } - } - let parked = self.cache.best(ids, req_imgs, want_cvec); - let mut incoming = if parked.tokens as usize > resume { - self.cache.take(parked.index) - } else { - None - }; - // Reject the entire image before parking/overwriting the outgoing - // state. Invalid entries can safely fall back to the existing prefix. - if let Some(image) = &incoming - && let Err(e) = engine.snapshot_validate(image) - { - self.events.push(format!( - "conversation cache: discard invalid snapshot ({e})" - )); - incoming = None; - } - // Preserve the outgoing branch before any checkpoint rewind, reset or - // incoming restore overwrites the positional state it requires. - if !from_live || incoming.is_some() { - let held = incoming.as_ref().map_or(0, SavedConversation::bytes); - self.park_current(engine, held)?; - } - let mut restored = None; - if let Some(mut image) = incoming { - match engine.snapshot_restore(&image) { - RestoreOutcome::Restored => {} - // Already prevalidated: a failure here is fatal, never - // permission to decode from a partially restored session. - RestoreOutcome::Invalid(e) | RestoreOutcome::TransferFailed(e) => { - return Err(ConvError(format!("restoring parked conversation: {e}"))); - } - } - self.live = std::mem::take(&mut image.live.ids); - self.live_imgs = std::mem::take(&mut image.live.imgs); - self.checks = std::mem::take(&mut image.checkpoints); - self.cvec_cached = image.cvec; - resume = parked.tokens as usize; - from_live = parked.live; - restored = Some((resume, from_live)); - if self.options.incremental_capture { - self.cache - .retain(std::mem::take(&mut image.kv), self.live.len() as i64); - } - self.events.push(format!( - "conversation cache: restored {resume} tokens ({}); parked={} bytes={}", - if from_live { "live" } else { "checkpoint" }, - self.cache.size(), - self.cache.bytes() - )); - } - if want_cvec != self.cvec_cached { - self.live_ok = false; - self.checks.clear(); - self.cvec_cached = want_cvec; - } - engine.set_steering(want_cvec); - // This request rewrites every cell from `resume` on, so a checkpoint - // past it (or not on this prompt's path) no longer has its cells; the - // ones kept are prefixes of both the old tokens and the new. - self.checks - .retain(|c| c.ids.len() <= resume && starts_with(&c.ids, &c.imgs, ids, req_imgs)); - self.live_ok = false; // until this request has finished, the session is in between - let mut reread_to = None; - if resume == 0 { - engine.zero_session()?; - self.checks.clear(); - } else if !from_live { - let Some(index) = self.checks.iter().rposition(|k| k.ids.len() == resume) else { - return Err(ConvError( - "restoring a conversation checkpoint failed".into(), - )); - }; - self.check_clock += 1; - self.checks[index].used = self.check_clock; - if self.options.reread_checkpoints { - // THE CHECK OF THE CHECKPOINT: read its tokens again from - // position 0 instead of restoring it; with the expert set - // fixed the answer must match the restored one token for token. - engine.zero_session()?; - reread_to = Some(resume); - self.events.push(format!( - "STRATA_CKPT_REREAD: reading {resume} tokens again instead of restoring" - )); - } else { - let c = &self.checks[index]; - if !c.stage_parts.is_empty() || engine.checkpoint_restore(c).is_err() { - return Err(ConvError( - "restoring a conversation checkpoint failed".into(), - )); - } - } - } - // KV streaming: the drafter's ring may hold cells past `resume` from a - // longer turn; the main layers' host copies and slots are always - // current (every writer writes both), so they need nothing. - if resume > 0 && reread_to.is_none() { - engine.restore_draft(resume)?; - } - let read_from = if reread_to.is_some() { 0 } else { resume }; - self.cache.limit_reuse(read_from as i64); - self.pp_next_check = if reread_to.is_some() { - i64::MAX - } else { - resume as i64 + self.options.prompt_cache_every - }; - Ok(RequestStart { - resume, - from_live, - restored, - reread_to, - read_from, - }) - } - - /// A checkpoint of the state after `ids[..position]`. `Ok` also when - /// checkpoints are off. An existing checkpoint at the position just - /// becomes the most recently used. - pub fn checkpoint_at( - &mut self, - engine: &mut dyn SessionEngine, - ids: &[i32], - req_imgs: &[ConversationImageKey], - position: usize, - ) -> ConvResult<()> { - if self.options.prompt_cache <= 0 || position < 1 { - return Ok(()); - } - if position > ids.len() { - return Err(ConvError( - "conversation checkpoint beyond the prompt".into(), - )); - } - if let Some(existing) = self.checks.iter_mut().find(|c| c.ids.len() == position) { - self.check_clock += 1; - existing.used = self.check_clock; - return Ok(()); - } - let mut c = ConversationCheckpoint { - ids: ids[..position].to_vec(), - imgs: images_below(req_imgs, position), - ..ConversationCheckpoint::default() - }; - engine.synchronize()?; - engine.checkpoint_save(&mut c)?; - self.check_clock += 1; - c.used = self.check_clock; - self.checks.push(c); - while self.checks.len() as i64 > self.options.prompt_cache { - let stamps: Vec = self.checks.iter().map(|k| k.used).collect(); - let victim = eviction_victim(&stamps, self.options.prompt_cache); - self.checks.remove(victim); - } - Ok(()) - } - - /// A batched prompt chunk finished and the prompt is read up to `done`: - /// take the periodic checkpoint when it is due. - pub fn chunk_done( - &mut self, - engine: &mut dyn SessionEngine, - ids: &[i32], - req_imgs: &[ConversationImageKey], - done: usize, - ) -> ConvResult<()> { - if self.options.prompt_cache_every > 0 && done as i64 >= self.pp_next_check { - self.checkpoint_at(engine, ids, req_imgs, done) - .map_err(|_| ConvError("saving a conversation checkpoint failed".into()))?; - self.pp_next_check = done as i64 + self.options.prompt_cache_every; - } - Ok(()) - } - - /// Bookkeeping after the caller executed one [`PromptAction`] of the - /// request's prompt plan: the periodic checkpoint after a batched chunk, - /// and the turn/root checkpoint when the action ends its segment. - // Used by the Original-path prompt driver (the plan type is crate-private). - #[allow(dead_code)] - pub(crate) fn after_prompt_action( - &mut self, - engine: &mut dyn SessionEngine, - ids: &[i32], - req_imgs: &[ConversationImageKey], - action: &PromptAction, - ) -> ConvResult<()> { - let end = action.first + action.count; - if matches!(action.path, PromptPath::Batched { .. }) { - self.chunk_done(engine, ids, req_imgs, end)?; - } - if action.checkpoint_after { - self.checkpoint_at(engine, ids, req_imgs, end) - .map_err(|_| ConvError("saving a conversation checkpoint failed".into()))?; - } - Ok(()) - } - - /// The request is over. `consumed` is what the session now holds: the - /// prompt read so far, then every committed token. A request stopped - /// while reading the prompt leaves the session between two chunks, with - /// nothing to continue from (the checkpoints taken meanwhile are good). - pub fn finish_request( - &mut self, - consumed: Vec, - req_imgs: &[ConversationImageKey], - cancelled: bool, - ) { - if !cancelled { - self.live_imgs = images_below(req_imgs, consumed.len()); - self.live = consumed; - self.live_ok = self.options.prompt_cache > 0; - } - } -} +mod impl_conversationmanager_2; +mod impl_conversationmanager_2_2; diff --git a/crates/leleka-runtime/src/conversation/manager/impl_conversationmanager/impl_conversationmanager_2.rs b/crates/leleka-runtime/src/conversation/manager/impl_conversationmanager/impl_conversationmanager_2.rs new file mode 100644 index 00000000..158570ae --- /dev/null +++ b/crates/leleka-runtime/src/conversation/manager/impl_conversationmanager/impl_conversationmanager_2.rs @@ -0,0 +1,176 @@ +//! Moved out of the parent module by STRA-338: impl ConversationManager. + +#[allow(unused_imports)] +use super::*; + + + +impl ConversationManager { + pub fn new(options: ConversationOptions) -> Self { + let budget = if options.prompt_cache > 0 { + options.conversation_cache_bytes + } else { + 0 + }; + let cache = ConversationCache::new(budget, options.conversation_cache_slots); + Self { + options, + live: Vec::new(), + live_imgs: Vec::new(), + live_ok: false, + checks: Vec::new(), + check_clock: 0, + cvec_cached: true, + cache, + pp_next_check: 0, + events: Vec::new(), + } + } + + pub fn options(&self) -> &ConversationOptions { + &self.options + } + pub fn live(&self) -> &[i32] { + &self.live + } + pub fn live_ok(&self) -> bool { + self.live_ok + } + pub fn checkpoints(&self) -> &[ConversationCheckpoint] { + &self.checks + } + pub fn cvec_cached(&self) -> bool { + self.cvec_cached + } + pub fn cache(&self) -> &ConversationCache { + &self.cache + } + /// The checkpoints' LRU clock. + pub fn check_clock(&self) -> u64 { + self.check_clock + } + /// Next prompt position at which a periodic checkpoint is due. + pub fn next_periodic_checkpoint(&self) -> i64 { + self.pp_next_check + } + /// Operator-facing log lines produced since the last call. + pub fn take_events(&mut self) -> Vec { + std::mem::take(&mut self.events) + } + + /// Drop everything that refers to the device's state (after an unload, + /// a reset or a fatal device error). + pub fn invalidate(&mut self) { + self.live.clear(); + self.live_imgs.clear(); + self.live_ok = false; + self.checks.clear(); + self.cache = ConversationCache::new(self.cache.budget(), self.cache.slots()); + self.pp_next_check = 0; + } + + /// Save only on a switch/rewind, not on each continuing request. `held` is + /// an incoming image that is still alive during the exchange. Anything + /// recoverable (nothing to park, no room, no RAM, allocation failure) + /// skips parking and returns `Ok`; a device failure is fatal. + pub(in super::super) fn park_current(&mut self, engine: &mut dyn SessionEngine, held: usize) -> ConvResult<()> { + if !self.cache.enabled() || !self.live_ok || self.live.is_empty() { + return Ok(()); + } + let view = ConversationView { + ids: &self.live, + images: &self.live_imgs, + checkpoints: &self.checks, + cvec: self.cvec_cached, + }; + let mut reuse = self.cache.take_reuse(); + let fresh_estimate = match engine.snapshot_bytes(&view) { + Ok(n) => n, + Err(e) => { + self.events + .push(format!("conversation cache: skip parking ({e})")); + return Ok(()); + } + }; + let mut estimate = fresh_estimate; + if !reuse.kv.is_empty() { + match engine.snapshot_capture_bytes(&reuse, &view) { + Ok(n) => estimate = n, + Err(_) => { + reuse = ConversationKvReuse::default(); + estimate = fresh_estimate; + } + } + } + // A park carrying its own retained K/V replaces memory the cache + // already held, so capacity is make_room's call: the with-reuse + // estimate must stay uncapped, because put() charges that same true + // size and a capped figure would under-evict and overfill the budget. + // #342: before make_room evicts oldest-first, the copies of this + // conversation a turn back go. + let keys: Vec> = self + .checks + .iter() + .map(|c| CheckpointKey { + ids: &c.ids, + imgs: &c.imgs, + }) + .collect(); + let dropped = + self.cache + .drop_superseded(&self.live, &self.live_imgs, &keys, self.cvec_cached); + if dropped != 0 { + self.events.push(format!( + "conversation cache: dropped {dropped} superseded cop{} of this conversation; parked={}", + if dropped == 1 { "y" } else { "ies" }, + self.cache.size() + )); + } + if !self.cache.make_room(estimate, held) { + self.events.push(format!( + "conversation cache: skip parking (snapshot {} MiB exceeds available budget)", + estimate >> 20 + )); + return Ok(()); + } + let floor = self.options.conversation_cache_min_free_bytes; + let additional = estimate.saturating_sub(reuse.bytes()); + if !memory_admit(engine.available_memory(), additional as u64, floor) { + self.events.push(format!( + "conversation cache: skip parking (physical RAM admission; need {} MiB plus {} MiB floor, or telemetry unavailable)", + additional >> 20, + floor >> 20 + )); + return Ok(()); + } + let mut reused_bytes = 0usize; + let image = match engine.snapshot_save(&view, reuse, &mut reused_bytes) { + Ok(image) => image, + Err(e) if is_allocation(&e) => { + // The active state has not been touched: continue with normal + // prompt processing rather than killing a serving process. + self.events + .push("conversation cache: allocation failed; skip parking".into()); + return Ok(()); + } + Err(e) => return Err(e), + }; + if !memory_admit(engine.available_memory(), 0, floor) { + self.events.push( + "conversation cache: skip parking (physical RAM floor after capture, or telemetry unavailable)".into(), + ); + return Ok(()); + } + let snapshot_bytes = image.bytes(); + let tokens = self.live.len(); + let stored = self.cache.put(image, held).is_ok(); + self.events.push(format!( + "conversation cache: {} {tokens} tokens; parked={} bytes={} evictions={} snapshot_bytes={snapshot_bytes} reused_kv_bytes={reused_bytes}", + if stored { "parked" } else { "skipped" }, + self.cache.size(), + self.cache.bytes(), + self.cache.evictions(), + )); + Ok(()) + } +} diff --git a/crates/leleka-runtime/src/conversation/manager/impl_conversationmanager/impl_conversationmanager_2_2.rs b/crates/leleka-runtime/src/conversation/manager/impl_conversationmanager/impl_conversationmanager_2_2.rs new file mode 100644 index 00000000..ba2b1b82 --- /dev/null +++ b/crates/leleka-runtime/src/conversation/manager/impl_conversationmanager/impl_conversationmanager_2_2.rs @@ -0,0 +1,247 @@ +//! Moved out of the parent module by STRA-338: impl ConversationManager (2). + +#[allow(unused_imports)] +use super::*; + + + +impl ConversationManager { + + /// Decide where `ids` starts reading and put the device in that state: + /// continue the live session, restore a checkpoint, restore a parked + /// conversation (parking the outgoing one first), or start empty. Any + /// error is fatal for the request and the device state is then undefined. + pub fn begin_request( + &mut self, + engine: &mut dyn SessionEngine, + ids: &[i32], + req_imgs: &[ConversationImageKey], + want_cvec: bool, + ) -> ConvResult { + let prompt_cache = self.options.prompt_cache > 0; + let mut resume = 0usize; + let mut from_live = false; + if prompt_cache && want_cvec == self.cvec_cached { + if self.live_ok && starts_with(&self.live, &self.live_imgs, ids, req_imgs) { + resume = self.live.len(); + from_live = true; + } + for c in &self.checks { + if c.ids.len() > resume && starts_with(&c.ids, &c.imgs, ids, req_imgs) { + resume = c.ids.len(); + from_live = false; + } + } + } + let parked = self.cache.best(ids, req_imgs, want_cvec); + let mut incoming = if parked.tokens as usize > resume { + self.cache.take(parked.index) + } else { + None + }; + // Reject the entire image before parking/overwriting the outgoing + // state. Invalid entries can safely fall back to the existing prefix. + if let Some(image) = &incoming + && let Err(e) = engine.snapshot_validate(image) + { + self.events.push(format!( + "conversation cache: discard invalid snapshot ({e})" + )); + incoming = None; + } + // Preserve the outgoing branch before any checkpoint rewind, reset or + // incoming restore overwrites the positional state it requires. + if !from_live || incoming.is_some() { + let held = incoming.as_ref().map_or(0, SavedConversation::bytes); + self.park_current(engine, held)?; + } + let mut restored = None; + if let Some(mut image) = incoming { + match engine.snapshot_restore(&image) { + RestoreOutcome::Restored => {} + // Already prevalidated: a failure here is fatal, never + // permission to decode from a partially restored session. + RestoreOutcome::Invalid(e) | RestoreOutcome::TransferFailed(e) => { + return Err(ConvError(format!("restoring parked conversation: {e}"))); + } + } + self.live = std::mem::take(&mut image.live.ids); + self.live_imgs = std::mem::take(&mut image.live.imgs); + self.checks = std::mem::take(&mut image.checkpoints); + self.cvec_cached = image.cvec; + resume = parked.tokens as usize; + from_live = parked.live; + restored = Some((resume, from_live)); + if self.options.incremental_capture { + self.cache + .retain(std::mem::take(&mut image.kv), self.live.len() as i64); + } + self.events.push(format!( + "conversation cache: restored {resume} tokens ({}); parked={} bytes={}", + if from_live { "live" } else { "checkpoint" }, + self.cache.size(), + self.cache.bytes() + )); + } + if want_cvec != self.cvec_cached { + self.live_ok = false; + self.checks.clear(); + self.cvec_cached = want_cvec; + } + engine.set_steering(want_cvec); + // This request rewrites every cell from `resume` on, so a checkpoint + // past it (or not on this prompt's path) no longer has its cells; the + // ones kept are prefixes of both the old tokens and the new. + self.checks + .retain(|c| c.ids.len() <= resume && starts_with(&c.ids, &c.imgs, ids, req_imgs)); + self.live_ok = false; // until this request has finished, the session is in between + let mut reread_to = None; + if resume == 0 { + engine.zero_session()?; + self.checks.clear(); + } else if !from_live { + let Some(index) = self.checks.iter().rposition(|k| k.ids.len() == resume) else { + return Err(ConvError( + "restoring a conversation checkpoint failed".into(), + )); + }; + self.check_clock += 1; + self.checks[index].used = self.check_clock; + if self.options.reread_checkpoints { + // THE CHECK OF THE CHECKPOINT: read its tokens again from + // position 0 instead of restoring it; with the expert set + // fixed the answer must match the restored one token for token. + engine.zero_session()?; + reread_to = Some(resume); + self.events.push(format!( + "STRATA_CKPT_REREAD: reading {resume} tokens again instead of restoring" + )); + } else { + let c = &self.checks[index]; + if !c.stage_parts.is_empty() || engine.checkpoint_restore(c).is_err() { + return Err(ConvError( + "restoring a conversation checkpoint failed".into(), + )); + } + } + } + // KV streaming: the drafter's ring may hold cells past `resume` from a + // longer turn; the main layers' host copies and slots are always + // current (every writer writes both), so they need nothing. + if resume > 0 && reread_to.is_none() { + engine.restore_draft(resume)?; + } + let read_from = if reread_to.is_some() { 0 } else { resume }; + self.cache.limit_reuse(read_from as i64); + self.pp_next_check = if reread_to.is_some() { + i64::MAX + } else { + resume as i64 + self.options.prompt_cache_every + }; + Ok(RequestStart { + resume, + from_live, + restored, + reread_to, + read_from, + }) + } + + /// A checkpoint of the state after `ids[..position]`. `Ok` also when + /// checkpoints are off. An existing checkpoint at the position just + /// becomes the most recently used. + pub fn checkpoint_at( + &mut self, + engine: &mut dyn SessionEngine, + ids: &[i32], + req_imgs: &[ConversationImageKey], + position: usize, + ) -> ConvResult<()> { + if self.options.prompt_cache <= 0 || position < 1 { + return Ok(()); + } + if position > ids.len() { + return Err(ConvError( + "conversation checkpoint beyond the prompt".into(), + )); + } + if let Some(existing) = self.checks.iter_mut().find(|c| c.ids.len() == position) { + self.check_clock += 1; + existing.used = self.check_clock; + return Ok(()); + } + let mut c = ConversationCheckpoint { + ids: ids[..position].to_vec(), + imgs: images_below(req_imgs, position), + ..ConversationCheckpoint::default() + }; + engine.synchronize()?; + engine.checkpoint_save(&mut c)?; + self.check_clock += 1; + c.used = self.check_clock; + self.checks.push(c); + while self.checks.len() as i64 > self.options.prompt_cache { + let stamps: Vec = self.checks.iter().map(|k| k.used).collect(); + let victim = eviction_victim(&stamps, self.options.prompt_cache); + self.checks.remove(victim); + } + Ok(()) + } + + /// A batched prompt chunk finished and the prompt is read up to `done`: + /// take the periodic checkpoint when it is due. + pub fn chunk_done( + &mut self, + engine: &mut dyn SessionEngine, + ids: &[i32], + req_imgs: &[ConversationImageKey], + done: usize, + ) -> ConvResult<()> { + if self.options.prompt_cache_every > 0 && done as i64 >= self.pp_next_check { + self.checkpoint_at(engine, ids, req_imgs, done) + .map_err(|_| ConvError("saving a conversation checkpoint failed".into()))?; + self.pp_next_check = done as i64 + self.options.prompt_cache_every; + } + Ok(()) + } + + /// Bookkeeping after the caller executed one [`PromptAction`] of the + /// request's prompt plan: the periodic checkpoint after a batched chunk, + /// and the turn/root checkpoint when the action ends its segment. + // Used by the Original-path prompt driver (the plan type is crate-private). + #[allow(dead_code)] + pub(crate) fn after_prompt_action( + &mut self, + engine: &mut dyn SessionEngine, + ids: &[i32], + req_imgs: &[ConversationImageKey], + action: &PromptAction, + ) -> ConvResult<()> { + let end = action.first + action.count; + if matches!(action.path, PromptPath::Batched { .. }) { + self.chunk_done(engine, ids, req_imgs, end)?; + } + if action.checkpoint_after { + self.checkpoint_at(engine, ids, req_imgs, end) + .map_err(|_| ConvError("saving a conversation checkpoint failed".into()))?; + } + Ok(()) + } + + /// The request is over. `consumed` is what the session now holds: the + /// prompt read so far, then every committed token. A request stopped + /// while reading the prompt leaves the session between two chunks, with + /// nothing to continue from (the checkpoints taken meanwhile are good). + pub fn finish_request( + &mut self, + consumed: Vec, + req_imgs: &[ConversationImageKey], + cancelled: bool, + ) { + if !cancelled { + self.live_imgs = images_below(req_imgs, consumed.len()); + self.live = consumed; + self.live_ok = self.options.prompt_cache > 0; + } + } +} diff --git a/crates/leleka-runtime/src/model_binding/qwen4exp_moe_expert/impl_modelbinding.rs b/crates/leleka-runtime/src/model_binding/qwen4exp_moe_expert/impl_modelbinding.rs index c494d713..e78488e8 100644 --- a/crates/leleka-runtime/src/model_binding/qwen4exp_moe_expert/impl_modelbinding.rs +++ b/crates/leleka-runtime/src/model_binding/qwen4exp_moe_expert/impl_modelbinding.rs @@ -3,403 +3,7 @@ #[allow(unused_imports)] use super::*; -impl ModelBinding { - pub(crate) fn moe_expert_weights( - &self, - layer: u32, - selected: [u32; SELECTED], - ) -> InputResult { - validate_selected(&selected)?; - if layer >= self.layer_count() { - return Err(E::Range); - } - let layer_index = u8::try_from(layer).map_err(|_| E::Range)?; - let artifact = self.artifact.try_borrow_mut().map_err(|_| E::Busy)?; - let t = artifact.topology(); - if t.embedding_length() != N as u32 - || t.expert_count() != EXPERTS as u32 - || t.expert_used_count() != SELECTED as u32 - || t.expert_feed_forward_length() != FF as u32 - || t.expert_shared_feed_forward_length() != FF as u32 - { - return Err(E::Metadata); - } - let make = |role: LayerRole, routed: bool, down: bool| -> InputResult { - let role = TensorRole::Layer { - layer: layer_index, - role, - }; - let tensor = artifact.tensor(role).map_err(|_| E::Geometry)?; - if tensor.shard() != 0 { - return Err(E::Geometry); - } - let (kind, row_bytes) = descriptor( - tensor.kind(), - tensor.dimensions(), - tensor.byte_length(), - routed, - down, - )?; - let (columns, rows) = if down { (FF, N) } else { (N, FF) }; - Ok(Matrix { - role, - kind, - raw_kind: tensor.kind(), - columns, - rows, - row_bytes, - }) - }; - let routed = [ - make(LayerRole::FfnGateExperts, true, false)?, - make(LayerRole::FfnUpExperts, true, false)?, - make(LayerRole::FfnDownExperts, true, true)?, - ]; - let shared = [ - make(LayerRole::FfnGateShared, false, false)?, - make(LayerRole::FfnUpShared, false, false)?, - make(LayerRole::FfnDownShared, false, true)?, - ]; - let role = TensorRole::Layer { - layer: layer_index, - role: LayerRole::FfnGateInpShared, - }; - let tensor = artifact.tensor(role).map_err(|_| E::Geometry)?; - if tensor.kind() != 30 - || tensor.shard() != 0 - || tensor.dimensions() != [N as u64] - || tensor.byte_length() != (N * 2) as u64 - { - return Err(E::Geometry); - } - Ok(MoeExpertWeights { - binding: self.identity(), - layer, - selected, - routed, - shared, - }) - } - /// Actual bound tensor/expert address; no synthetic selected-route object. - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(crate) fn moe_preload_descriptor( - &self, - layer: u32, - expert: u32, - role: MoeMatrixRole, - ) -> InputResult { - if layer >= self.layer_count() || expert >= EXPERTS as u32 { - return Err(E::Range); - } - let tensor_role = TensorRole::Layer { - layer: u8::try_from(layer).map_err(|_| E::Range)?, - role: match role { - MoeMatrixRole::Gate => LayerRole::FfnGateExperts, - MoeMatrixRole::Up => LayerRole::FfnUpExperts, - MoeMatrixRole::Down => LayerRole::FfnDownExperts, - }, - }; - let mut artifact = self.artifact.try_borrow_mut().map_err(|_| E::Busy)?; - let t = artifact.topology(); - if self.layer_count() != 48 - || t.embedding_length() != N as u32 - || t.expert_count() != EXPERTS as u32 - || t.expert_used_count() != SELECTED as u32 - || t.expert_feed_forward_length() != FF as u32 - || t.expert_shared_feed_forward_length() != FF as u32 - { - return Err(E::Metadata); - } - let tensor = artifact.tensor(tensor_role).map_err(|_| E::Geometry)?; - if tensor.shard() != 0 { - return Err(E::Geometry); - } - let (_, row_bytes) = descriptor( - tensor.kind(), - tensor.dimensions(), - tensor.byte_length(), - true, - role == MoeMatrixRole::Down, - )?; - let (columns, rows) = if role == MoeMatrixRole::Down { - (FF, N) - } else { - (N, FF) - }; - let key = MoeWeightDescriptor { - layer, - expert: Some(expert), - role: index(role) as u8, - raw_kind: tensor.kind(), - columns, - rows, - bytes: rows.checked_mul(row_bytes).ok_or(E::Geometry)?, - }; - artifact - .validate_tensor_source(tensor_role) - .map_err(|_| E::Read)?; - Ok(key) - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(crate) fn moe_preload_block(&self, key: MoeWeightDescriptor) -> InputResult> { - let role = match key.role { - 0 => MoeMatrixRole::Gate, - 1 => MoeMatrixRole::Up, - 2 => MoeMatrixRole::Down, - _ => return Err(E::Range), - }; - let expert = key.expert.ok_or(E::Range)?; - if self.moe_preload_descriptor(key.layer, expert, role)? != key { - return Err(E::Geometry); - } - let tensor_role = TensorRole::Layer { - layer: u8::try_from(key.layer).map_err(|_| E::Range)?, - role: match role { - MoeMatrixRole::Gate => LayerRole::FfnGateExperts, - MoeMatrixRole::Up => LayerRole::FfnUpExperts, - MoeMatrixRole::Down => LayerRole::FfnDownExperts, - }, - }; - let row_bytes = key.bytes.checked_div(key.rows).ok_or(E::Geometry)?; - let mut bytes = Vec::new(); - bytes - .try_reserve_exact(key.bytes) - .map_err(|_| E::Allocation)?; - bytes.resize(key.bytes, 0); - let mut artifact = self.artifact.try_borrow_mut().map_err(|_| E::Busy)?; - let bytes = artifact - .read_expert_rows_owned(tensor_role, u64::from(expert), 0, key.rows as u64, - bytes.into_boxed_slice()) - .map_err(|_| E::Read)?; - if bytes.len() != key.bytes { - return Err(E::Read); - } - for row in bytes.chunks_exact(row_bytes) { - if matches!(key.raw_kind, 18 | 21 | 22 | 23 | 20 | 42) { - encoded_finite::validate_row(key.raw_kind, row, key.columns)?; - } else { - let _finite = super::super::decode::row(key.raw_kind, row, key.columns)?; - } - } - Ok(bytes) - } - pub(crate) fn moe_weight_descriptor( - &self, - weights: &MoeExpertWeights, - selection: MoeExpertSelection, - role: MoeMatrixRole, - ) -> InputResult { - if !weights.matches(&self.identity(), weights.layer) { - return Err(E::Metadata); - } - let matrix = weights.matrix(selection, role)?; - let expert = match selection { - MoeExpertSelection::Routed { slot } => Some(weights.selected[slot]), - MoeExpertSelection::Shared => None, - }; - let mut artifact = self.artifact.try_borrow_mut().map_err(|_| E::Busy)?; - let tensor = artifact.tensor(matrix.role).map_err(|_| E::Geometry)?; - let checked = descriptor( - tensor.kind(), - tensor.dimensions(), - tensor.byte_length(), - expert.is_some(), - role == MoeMatrixRole::Down, - )?; - if tensor.shard() != 0 - || tensor.kind() != matrix.raw_kind - || checked != (matrix.kind, matrix.row_bytes) - { - return Err(E::Geometry); - } - artifact - .validate_tensor_source(matrix.role) - .map_err(|_| E::Read)?; - Ok(MoeWeightDescriptor { - layer: weights.layer, - expert, - role: index(role) as u8, - raw_kind: matrix.raw_kind, - columns: matrix.columns, - rows: matrix.rows, - bytes: matrix - .rows - .checked_mul(matrix.row_bytes) - .ok_or(E::Geometry)?, - }) - } - pub(crate) fn moe_shared_scalar_descriptor( - &self, - weights: &MoeExpertWeights, - ) -> InputResult { - if !weights.matches(&self.identity(), weights.layer) { - return Err(E::Metadata); - } - let role = TensorRole::Layer { - layer: u8::try_from(weights.layer).map_err(|_| E::Range)?, - role: LayerRole::FfnGateInpShared, - }; - let mut artifact = self.artifact.try_borrow_mut().map_err(|_| E::Busy)?; - let tensor = artifact.tensor(role).map_err(|_| E::Geometry)?; - if tensor.shard() != 0 - || tensor.kind() != 30 - || tensor.dimensions() != [N as u64] - || tensor.byte_length() != (N * 2) as u64 - { - return Err(E::Geometry); - } - artifact.validate_tensor_source(role).map_err(|_| E::Read)?; - Ok(MoeWeightDescriptor { - layer: weights.layer, - expert: None, - role: 3, - raw_kind: 30, - columns: N, - rows: 1, - bytes: N * 2, - }) - } - pub(crate) fn moe_shared_scalar(&self, weights: &MoeExpertWeights) -> InputResult> { - self.moe_shared_scalar_descriptor(weights)?; - let role = TensorRole::Layer { - layer: u8::try_from(weights.layer).map_err(|_| E::Range)?, - role: LayerRole::FfnGateInpShared, - }; - let mut artifact = self.artifact.try_borrow_mut().map_err(|_| E::Busy)?; - // The rank-one row-zero provider retains the original indexed owner. - let mut scalar = Vec::new(); - scalar.try_reserve_exact(N * 2).map_err(|_| E::Allocation)?; - artifact - .stream_row(role, 0, |chunk| { - if scalar - .len() - .checked_add(chunk.len()) - .is_none_or(|v| v > N * 2) - { - return Err(std::io::ErrorKind::InvalidData.into()); - } - scalar.extend_from_slice(chunk); - Ok(()) - }) - .map_err(|_| E::Read)?; - if scalar.len() != N * 2 { - return Err(E::Read); - } - if scalar - .as_chunks::<2>() - .0 - .iter() - .any(|word| u16::from_le_bytes(*word) & 0x7f80 == 0x7f80) - { - return Err(E::NonFinite); - } - Ok(scalar.into_boxed_slice()) - } - pub(crate) fn moe_expert_block( - &self, - weights: &MoeExpertWeights, - selection: MoeExpertSelection, - role: MoeMatrixRole, - first: usize, - count: usize, - ) -> InputResult { - if !weights.matches(&self.identity(), weights.layer) { - return Err(E::Metadata); - } - let matrix = weights.matrix(selection, role)?; - validate_range(first, count, matrix.rows)?; - let expert = match selection { - MoeExpertSelection::Routed { slot } => Some(weights.selected[slot]), - MoeExpertSelection::Shared => None, - }; - let mut artifact = self.artifact.try_borrow_mut().map_err(|_| E::Busy)?; - let tensor = artifact.tensor(matrix.role).map_err(|_| E::Geometry)?; - let checked = descriptor( - tensor.kind(), - tensor.dimensions(), - tensor.byte_length(), - expert.is_some(), - role == MoeMatrixRole::Down, - )?; - if tensor.shard() != 0 - || tensor.kind() != matrix.raw_kind - || checked != (matrix.kind, matrix.row_bytes) - { - return Err(E::Geometry); - } - let limit = count.checked_mul(matrix.row_bytes).ok_or(E::Geometry)?; - let mut bytes = Vec::new(); - bytes.try_reserve_exact(limit).map_err(|_| E::Allocation)?; - if let Some(id) = expert.filter(|_| artifact.resident_expert_source_report().is_some()) { - // Immutable bank bytes supply the genuine selected source span. - // The same final owner, full finite loop and later H2D still apply. - bytes.resize(limit, 0); - let bytes = artifact - .read_expert_rows_owned( - matrix.role, - u64::from(id), - first as u64, - count as u64, - bytes.into_boxed_slice(), - ) - .map_err(|_| E::Read)?; - if bytes.len() != limit { - return Err(E::Read); - } - for row in bytes.chunks_exact(matrix.row_bytes) { - if matches!(matrix.raw_kind, 18 | 21 | 22 | 23 | 20 | 42) { - encoded_finite::validate_row(matrix.raw_kind, row, matrix.columns)?; - } else { - let _finite = super::super::decode::row(matrix.raw_kind, row, matrix.columns)?; - } - } - return Ok(MoeExpertBlock { - kind: matrix.kind, - columns: matrix.columns, - rows: count, - bytes, - }); - } - // The retained owner streams one bounded tile or complete matrix. Chunks may - // cross row boundaries; decoder admission still checks each exact row. - let consume = |chunk: &[u8]| { - if bytes - .len() - .checked_add(chunk.len()) - .is_none_or(|v| v > limit) - { - return Err(std::io::ErrorKind::InvalidData.into()); - } - bytes.extend_from_slice(chunk); - Ok(()) - }; - match expert { - Some(id) => artifact.stream_expert_rows( - matrix.role, - u64::from(id), - first as u64, - count as u64, - consume, - ), - None => artifact.stream_rows(matrix.role, first as u64, count as u64, consume), - } - .map_err(|_| E::Read)?; - if bytes.len() != limit { - return Err(E::Read); - } - for row in bytes.chunks_exact(matrix.row_bytes) { - if expert.is_some() && matches!(matrix.raw_kind, 18 | 21 | 22 | 23 | 20 | 42) { - encoded_finite::validate_row(matrix.raw_kind, row, matrix.columns)?; - } else { - // Unproven formats and shared matrices retain decoder admission. - let _finite = super::super::decode::row(matrix.raw_kind, row, matrix.columns)?; - } - } - Ok(MoeExpertBlock { - kind: matrix.kind, - columns: matrix.columns, - rows: count, - bytes: bytes.into_boxed_slice(), - }) - } -} +#[path = "impl_modelbinding/impl_modelbinding_2.rs"] +mod impl_modelbinding_2; +#[path = "impl_modelbinding/impl_modelbinding_2_2.rs"] +mod impl_modelbinding_2_2; diff --git a/crates/leleka-runtime/src/model_binding/qwen4exp_moe_expert/impl_modelbinding/impl_modelbinding_2.rs b/crates/leleka-runtime/src/model_binding/qwen4exp_moe_expert/impl_modelbinding/impl_modelbinding_2.rs new file mode 100644 index 00000000..7df2398a --- /dev/null +++ b/crates/leleka-runtime/src/model_binding/qwen4exp_moe_expert/impl_modelbinding/impl_modelbinding_2.rs @@ -0,0 +1,232 @@ +//! Moved out of the parent module by STRA-338: impl ModelBinding. + +#[allow(unused_imports)] +use super::*; + + +impl ModelBinding { + pub(crate) fn moe_expert_weights( + &self, + layer: u32, + selected: [u32; SELECTED], + ) -> InputResult { + validate_selected(&selected)?; + if layer >= self.layer_count() { + return Err(E::Range); + } + let layer_index = u8::try_from(layer).map_err(|_| E::Range)?; + let artifact = self.artifact.try_borrow_mut().map_err(|_| E::Busy)?; + let t = artifact.topology(); + if t.embedding_length() != N as u32 + || t.expert_count() != EXPERTS as u32 + || t.expert_used_count() != SELECTED as u32 + || t.expert_feed_forward_length() != FF as u32 + || t.expert_shared_feed_forward_length() != FF as u32 + { + return Err(E::Metadata); + } + let make = |role: LayerRole, routed: bool, down: bool| -> InputResult { + let role = TensorRole::Layer { + layer: layer_index, + role, + }; + let tensor = artifact.tensor(role).map_err(|_| E::Geometry)?; + if tensor.shard() != 0 { + return Err(E::Geometry); + } + let (kind, row_bytes) = descriptor( + tensor.kind(), + tensor.dimensions(), + tensor.byte_length(), + routed, + down, + )?; + let (columns, rows) = if down { (FF, N) } else { (N, FF) }; + Ok(Matrix { + role, + kind, + raw_kind: tensor.kind(), + columns, + rows, + row_bytes, + }) + }; + let routed = [ + make(LayerRole::FfnGateExperts, true, false)?, + make(LayerRole::FfnUpExperts, true, false)?, + make(LayerRole::FfnDownExperts, true, true)?, + ]; + let shared = [ + make(LayerRole::FfnGateShared, false, false)?, + make(LayerRole::FfnUpShared, false, false)?, + make(LayerRole::FfnDownShared, false, true)?, + ]; + let role = TensorRole::Layer { + layer: layer_index, + role: LayerRole::FfnGateInpShared, + }; + let tensor = artifact.tensor(role).map_err(|_| E::Geometry)?; + if tensor.kind() != 30 + || tensor.shard() != 0 + || tensor.dimensions() != [N as u64] + || tensor.byte_length() != (N * 2) as u64 + { + return Err(E::Geometry); + } + Ok(MoeExpertWeights { + binding: self.identity(), + layer, + selected, + routed, + shared, + }) + } + /// Actual bound tensor/expert address; no synthetic selected-route object. + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(crate) fn moe_preload_descriptor( + &self, + layer: u32, + expert: u32, + role: MoeMatrixRole, + ) -> InputResult { + if layer >= self.layer_count() || expert >= EXPERTS as u32 { + return Err(E::Range); + } + let tensor_role = TensorRole::Layer { + layer: u8::try_from(layer).map_err(|_| E::Range)?, + role: match role { + MoeMatrixRole::Gate => LayerRole::FfnGateExperts, + MoeMatrixRole::Up => LayerRole::FfnUpExperts, + MoeMatrixRole::Down => LayerRole::FfnDownExperts, + }, + }; + let mut artifact = self.artifact.try_borrow_mut().map_err(|_| E::Busy)?; + let t = artifact.topology(); + if self.layer_count() != 48 + || t.embedding_length() != N as u32 + || t.expert_count() != EXPERTS as u32 + || t.expert_used_count() != SELECTED as u32 + || t.expert_feed_forward_length() != FF as u32 + || t.expert_shared_feed_forward_length() != FF as u32 + { + return Err(E::Metadata); + } + let tensor = artifact.tensor(tensor_role).map_err(|_| E::Geometry)?; + if tensor.shard() != 0 { + return Err(E::Geometry); + } + let (_, row_bytes) = descriptor( + tensor.kind(), + tensor.dimensions(), + tensor.byte_length(), + true, + role == MoeMatrixRole::Down, + )?; + let (columns, rows) = if role == MoeMatrixRole::Down { + (FF, N) + } else { + (N, FF) + }; + let key = MoeWeightDescriptor { + layer, + expert: Some(expert), + role: index(role) as u8, + raw_kind: tensor.kind(), + columns, + rows, + bytes: rows.checked_mul(row_bytes).ok_or(E::Geometry)?, + }; + artifact + .validate_tensor_source(tensor_role) + .map_err(|_| E::Read)?; + Ok(key) + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(crate) fn moe_preload_block(&self, key: MoeWeightDescriptor) -> InputResult> { + let role = match key.role { + 0 => MoeMatrixRole::Gate, + 1 => MoeMatrixRole::Up, + 2 => MoeMatrixRole::Down, + _ => return Err(E::Range), + }; + let expert = key.expert.ok_or(E::Range)?; + if self.moe_preload_descriptor(key.layer, expert, role)? != key { + return Err(E::Geometry); + } + let tensor_role = TensorRole::Layer { + layer: u8::try_from(key.layer).map_err(|_| E::Range)?, + role: match role { + MoeMatrixRole::Gate => LayerRole::FfnGateExperts, + MoeMatrixRole::Up => LayerRole::FfnUpExperts, + MoeMatrixRole::Down => LayerRole::FfnDownExperts, + }, + }; + let row_bytes = key.bytes.checked_div(key.rows).ok_or(E::Geometry)?; + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(key.bytes) + .map_err(|_| E::Allocation)?; + bytes.resize(key.bytes, 0); + let mut artifact = self.artifact.try_borrow_mut().map_err(|_| E::Busy)?; + let bytes = artifact + .read_expert_rows_owned(tensor_role, u64::from(expert), 0, key.rows as u64, + bytes.into_boxed_slice()) + .map_err(|_| E::Read)?; + if bytes.len() != key.bytes { + return Err(E::Read); + } + for row in bytes.chunks_exact(row_bytes) { + if matches!(key.raw_kind, 18 | 21 | 22 | 23 | 20 | 42) { + encoded_finite::validate_row(key.raw_kind, row, key.columns)?; + } else { + let _finite = super::super::super::decode::row(key.raw_kind, row, key.columns)?; + } + } + Ok(bytes) + } + pub(crate) fn moe_weight_descriptor( + &self, + weights: &MoeExpertWeights, + selection: MoeExpertSelection, + role: MoeMatrixRole, + ) -> InputResult { + if !weights.matches(&self.identity(), weights.layer) { + return Err(E::Metadata); + } + let matrix = weights.matrix(selection, role)?; + let expert = match selection { + MoeExpertSelection::Routed { slot } => Some(weights.selected[slot]), + MoeExpertSelection::Shared => None, + }; + let mut artifact = self.artifact.try_borrow_mut().map_err(|_| E::Busy)?; + let tensor = artifact.tensor(matrix.role).map_err(|_| E::Geometry)?; + let checked = descriptor( + tensor.kind(), + tensor.dimensions(), + tensor.byte_length(), + expert.is_some(), + role == MoeMatrixRole::Down, + )?; + if tensor.shard() != 0 + || tensor.kind() != matrix.raw_kind + || checked != (matrix.kind, matrix.row_bytes) + { + return Err(E::Geometry); + } + artifact + .validate_tensor_source(matrix.role) + .map_err(|_| E::Read)?; + Ok(MoeWeightDescriptor { + layer: weights.layer, + expert, + role: index(role) as u8, + raw_kind: matrix.raw_kind, + columns: matrix.columns, + rows: matrix.rows, + bytes: matrix + .rows + .checked_mul(matrix.row_bytes) + .ok_or(E::Geometry)?, + }) + } +} diff --git a/crates/leleka-runtime/src/model_binding/qwen4exp_moe_expert/impl_modelbinding/impl_modelbinding_2_2.rs b/crates/leleka-runtime/src/model_binding/qwen4exp_moe_expert/impl_modelbinding/impl_modelbinding_2_2.rs new file mode 100644 index 00000000..96e44a54 --- /dev/null +++ b/crates/leleka-runtime/src/model_binding/qwen4exp_moe_expert/impl_modelbinding/impl_modelbinding_2_2.rs @@ -0,0 +1,182 @@ +//! Moved out of the parent module by STRA-338: impl ModelBinding (2). + +#[allow(unused_imports)] +use super::*; + + +impl ModelBinding { + pub(crate) fn moe_shared_scalar_descriptor( + &self, + weights: &MoeExpertWeights, + ) -> InputResult { + if !weights.matches(&self.identity(), weights.layer) { + return Err(E::Metadata); + } + let role = TensorRole::Layer { + layer: u8::try_from(weights.layer).map_err(|_| E::Range)?, + role: LayerRole::FfnGateInpShared, + }; + let mut artifact = self.artifact.try_borrow_mut().map_err(|_| E::Busy)?; + let tensor = artifact.tensor(role).map_err(|_| E::Geometry)?; + if tensor.shard() != 0 + || tensor.kind() != 30 + || tensor.dimensions() != [N as u64] + || tensor.byte_length() != (N * 2) as u64 + { + return Err(E::Geometry); + } + artifact.validate_tensor_source(role).map_err(|_| E::Read)?; + Ok(MoeWeightDescriptor { + layer: weights.layer, + expert: None, + role: 3, + raw_kind: 30, + columns: N, + rows: 1, + bytes: N * 2, + }) + } + pub(crate) fn moe_shared_scalar(&self, weights: &MoeExpertWeights) -> InputResult> { + self.moe_shared_scalar_descriptor(weights)?; + let role = TensorRole::Layer { + layer: u8::try_from(weights.layer).map_err(|_| E::Range)?, + role: LayerRole::FfnGateInpShared, + }; + let mut artifact = self.artifact.try_borrow_mut().map_err(|_| E::Busy)?; + // The rank-one row-zero provider retains the original indexed owner. + let mut scalar = Vec::new(); + scalar.try_reserve_exact(N * 2).map_err(|_| E::Allocation)?; + artifact + .stream_row(role, 0, |chunk| { + if scalar + .len() + .checked_add(chunk.len()) + .is_none_or(|v| v > N * 2) + { + return Err(std::io::ErrorKind::InvalidData.into()); + } + scalar.extend_from_slice(chunk); + Ok(()) + }) + .map_err(|_| E::Read)?; + if scalar.len() != N * 2 { + return Err(E::Read); + } + if scalar + .as_chunks::<2>() + .0 + .iter() + .any(|word| u16::from_le_bytes(*word) & 0x7f80 == 0x7f80) + { + return Err(E::NonFinite); + } + Ok(scalar.into_boxed_slice()) + } + pub(crate) fn moe_expert_block( + &self, + weights: &MoeExpertWeights, + selection: MoeExpertSelection, + role: MoeMatrixRole, + first: usize, + count: usize, + ) -> InputResult { + if !weights.matches(&self.identity(), weights.layer) { + return Err(E::Metadata); + } + let matrix = weights.matrix(selection, role)?; + validate_range(first, count, matrix.rows)?; + let expert = match selection { + MoeExpertSelection::Routed { slot } => Some(weights.selected[slot]), + MoeExpertSelection::Shared => None, + }; + let mut artifact = self.artifact.try_borrow_mut().map_err(|_| E::Busy)?; + let tensor = artifact.tensor(matrix.role).map_err(|_| E::Geometry)?; + let checked = descriptor( + tensor.kind(), + tensor.dimensions(), + tensor.byte_length(), + expert.is_some(), + role == MoeMatrixRole::Down, + )?; + if tensor.shard() != 0 + || tensor.kind() != matrix.raw_kind + || checked != (matrix.kind, matrix.row_bytes) + { + return Err(E::Geometry); + } + let limit = count.checked_mul(matrix.row_bytes).ok_or(E::Geometry)?; + let mut bytes = Vec::new(); + bytes.try_reserve_exact(limit).map_err(|_| E::Allocation)?; + if let Some(id) = expert.filter(|_| artifact.resident_expert_source_report().is_some()) { + // Immutable bank bytes supply the genuine selected source span. + // The same final owner, full finite loop and later H2D still apply. + bytes.resize(limit, 0); + let bytes = artifact + .read_expert_rows_owned( + matrix.role, + u64::from(id), + first as u64, + count as u64, + bytes.into_boxed_slice(), + ) + .map_err(|_| E::Read)?; + if bytes.len() != limit { + return Err(E::Read); + } + for row in bytes.chunks_exact(matrix.row_bytes) { + if matches!(matrix.raw_kind, 18 | 21 | 22 | 23 | 20 | 42) { + encoded_finite::validate_row(matrix.raw_kind, row, matrix.columns)?; + } else { + let _finite = super::super::super::decode::row(matrix.raw_kind, row, matrix.columns)?; + } + } + return Ok(MoeExpertBlock { + kind: matrix.kind, + columns: matrix.columns, + rows: count, + bytes, + }); + } + // The retained owner streams one bounded tile or complete matrix. Chunks may + // cross row boundaries; decoder admission still checks each exact row. + let consume = |chunk: &[u8]| { + if bytes + .len() + .checked_add(chunk.len()) + .is_none_or(|v| v > limit) + { + return Err(std::io::ErrorKind::InvalidData.into()); + } + bytes.extend_from_slice(chunk); + Ok(()) + }; + match expert { + Some(id) => artifact.stream_expert_rows( + matrix.role, + u64::from(id), + first as u64, + count as u64, + consume, + ), + None => artifact.stream_rows(matrix.role, first as u64, count as u64, consume), + } + .map_err(|_| E::Read)?; + if bytes.len() != limit { + return Err(E::Read); + } + for row in bytes.chunks_exact(matrix.row_bytes) { + if expert.is_some() && matches!(matrix.raw_kind, 18 | 21 | 22 | 23 | 20 | 42) { + encoded_finite::validate_row(matrix.raw_kind, row, matrix.columns)?; + } else { + // Unproven formats and shared matrices retain decoder admission. + let _finite = super::super::super::decode::row(matrix.raw_kind, row, matrix.columns)?; + } + } + Ok(MoeExpertBlock { + kind: matrix.kind, + columns: matrix.columns, + rows: count, + bytes: bytes.into_boxed_slice(), + }) + } +} diff --git a/crates/leleka-runtime/src/prefix_cache/store/impl_prefixstore.rs b/crates/leleka-runtime/src/prefix_cache/store/impl_prefixstore.rs index d50860d6..49c19d72 100644 --- a/crates/leleka-runtime/src/prefix_cache/store/impl_prefixstore.rs +++ b/crates/leleka-runtime/src/prefix_cache/store/impl_prefixstore.rs @@ -3,561 +3,6 @@ #[allow(unused_imports)] use super::*; - -impl PrefixStore { - pub fn new(cfg: StoreConfig) -> Self { - assert!(cfg.block_tokens > 0 && cfg.block_tokens % 4 == 0, "block_tokens must be a positive multiple of the 4-cell page"); - Self { cfg, blocks: HashMap::new(), nodes: HashMap::new(), tails: HashMap::new(), clock: 0, now_ms: 0, node_bytes: 0, block_bytes: 0, stats: Stats::default(), orphans: HashSet::new() } - } - pub fn config(&self) -> &StoreConfig { - &self.cfg - } - pub fn stats(&self) -> &Stats { - &self.stats - } - pub fn bytes(&self) -> usize { - self.node_bytes + self.block_bytes - } - pub fn node_bytes(&self) -> usize { - self.node_bytes - } - pub fn block_bytes(&self) -> usize { - self.block_bytes - } - pub fn node_count(&self) -> usize { - self.nodes.len() - } - pub fn block_count(&self) -> usize { - self.blocks.len() - } - pub fn clock(&self) -> u64 { - self.clock - } - - /// A new request begins: ages every prior and hit mass by one tick. - pub fn tick(&mut self, prompt_tokens: usize) { - self.clock += 1; - self.stats.requests += 1; - self.stats.prompt_tokens += prompt_tokens as u64; - } - - /// `tick` with the wall time of the request, in milliseconds on any monotonic scale. - pub fn tick_at(&mut self, prompt_tokens: usize, now_ms: u64) { - self.now_ms = self.now_ms.max(now_ms); - self.tick(prompt_tokens); - } - - /// Advance the wall time without a request (the idle sweep). - pub fn set_now(&mut self, now_ms: u64) { - self.now_ms = self.now_ms.max(now_ms); - } - - /// Drop every node unused for longer than the retention time; returns how many went (their blocks with them). - pub fn expire(&mut self) -> usize { - let limit = self.cfg.policy.retention_ms; - if limit == 0 { - return 0; - } - let now = self.now_ms; - let stale: Vec = self.nodes.iter().filter(|(_, node)| now.saturating_sub(node.last_used_ms) > limit).map(|(key, _)| *key).collect(); - for key in &stale { - self.evict(*key); - } - self.stats.expired += stale.len() as u64; - stale.len() - } - - /// How much of its value a node keeps at its age: 1 when just used, `recency_floor` at the retention limit. - pub(super) fn recency(&self, node: &Node) -> f64 { - let p = &self.cfg.policy; - if p.retention_ms == 0 { - return 1.0; - } - let age = self.now_ms.saturating_sub(node.last_used_ms) as f64 / p.retention_ms as f64; - 1.0 - (1.0 - p.recency_floor) * age.min(1.0) - } - - pub fn contains_node(&self, key: u64) -> bool { - self.nodes.contains_key(&key) - } - pub fn node_payload(&self, key: u64) -> Option<&N> { - self.nodes.get(&key).map(|n| &n.payload) - } - /// Tokens the node covers. - pub fn node_tokens(&self, key: u64) -> Option { - self.nodes.get(&key).map(|n| self.tokens_of(n)) - } - pub(super) fn tokens_of(&self, node: &Node) -> usize { - node.path.len() * self.cfg.block_tokens + node.tail.as_ref().map_or(0, |t| t.tokens.len()) - } - /// The tail of a request-end node: its cells, where they start and how many tokens they cover. - pub fn tail_of(&self, key: u64) -> Option<(&B, usize, usize)> { - let node = self.nodes.get(&key)?; - let tail = node.tail.as_ref()?; - Some((&tail.payload, node.path.len() * self.cfg.block_tokens, tail.tokens.len())) - } - /// The payloads of the node's blocks from block `from_block` on, with their block indices. - pub fn blocks_from(&self, key: u64, from_block: usize) -> Option> { - let node = self.nodes.get(&key)?; - let mut out = Vec::with_capacity(node.path.len().saturating_sub(from_block)); - for (j, h) in node.path.iter().enumerate().skip(from_block) { - out.push((j, &self.blocks.get(h)?.payload)); - } - Some(out) - } - - /// The deepest node that is a prefix of `tokens` and covers at most `limit` tokens. The blocks are compared - /// token for token, so a hash collision cannot produce a hit. - pub fn longest_match(&self, tokens: &[i32], limit: usize) -> Option { - let g = self.cfg.block_tokens; - let mut prev = CHAIN_SEED; - let mut best = None; - for (j, block) in tokens.chunks_exact(g).enumerate() { - let end = (j + 1) * g; - if end > limit { - break; - } - let h = chain_step(prev, block); - match self.blocks.get(&h) { - Some(b) if *b.tokens == *block => {} - _ => break, - } - prev = h; - if self.nodes.contains_key(&h) { - best = Some(Match { key: h, tokens: end }); - } - // request-end checkpoints that extend this block (the longest whose tokens are the prompt's next ones) - if let Some(keys) = self.tails.get(&h) { - for key in keys { - let Some(tail) = self.nodes.get(key).and_then(|n| n.tail.as_ref()) else { continue }; - let upto = end + tail.tokens.len(); - if upto <= limit && best.is_none_or(|b| upto > b.tokens) && tokens.get(end..upto).is_some_and(|t| t == &*tail.tokens) { - best = Some(Match { key: *key, tokens: upto }); - } - } - } - } - best - } - - /// The deepest node among `chain` (chain values of a prompt's blocks, from [`super::hash::chain`]): the tokens - /// of a cached prefix of that prompt, 0 when none. Hash-only (the router's query): it cannot see collisions. - pub fn prefix_match(&self, chain: &[u64]) -> usize { - chain.iter().rposition(|h| self.nodes.contains_key(h)).map_or(0, |j| (j + 1) * self.cfg.block_tokens) - } - - /// Every node as `(key, tokens)`, deepest first. - pub fn heads(&self) -> Vec<(u64, usize)> { - let mut heads: Vec<(u64, usize)> = - self.nodes.iter().filter(|(_, n)| n.tail.is_none()).map(|(k, n)| (*k, n.path.len() * self.cfg.block_tokens)).collect(); - heads.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0))); - heads - } - - /// The heads ranked by value (best first), for a summary that has to leave some out. - pub fn heads_by_value(&self) -> Vec<(u64, usize)> { - let mut scored = self.scores(&HashSet::new(), &HashSet::new()); - scored.sort_by(|a, b| b.score.total_cmp(&a.score).then(a.key.cmp(&b.key))); - scored - .iter() - .filter(|s| self.nodes[&s.key].tail.is_none()) - .map(|s| (s.key, self.nodes[&s.key].path.len() * self.cfg.block_tokens)) - .collect() - } - - pub fn record_miss(&mut self) { - self.stats.misses += 1; - } - - /// Whether the node has descendants, i.e. whether histories fork below it: a system prompt shared by several - /// sessions, or a rewritten history. (A session's own frontier has none.) - pub fn is_branch_point(&self, key: u64) -> bool { - let Some(node) = self.nodes.get(&key) else { return false }; - if node.tail.is_some() { - return false; - } - let at = node.path.len() - 1; - self.nodes.values().any(|other| other.path.len() > node.path.len() && other.path[at] == key) - } - - /// A request resumed from `m`. A hit on a branch point counts as evidence of sharing, a hit on a frontier as - /// the session's own continuation (see [`PolicyParams`]). - pub fn record_hit(&mut self, m: &Match) { - let branch = self.is_branch_point(m.key); - self.record_hit_as(m, branch); - } - - /// `record_hit` with the sharing verdict given by the caller. - pub fn record_hit_as(&mut self, m: &Match, shared: bool) { - let weight = if shared { self.cfg.policy.shared_weight } else { self.cfg.policy.continuation_weight }; - let clock = self.clock; - let half_life = self.cfg.policy.half_life; - if let Some(node) = self.nodes.get_mut(&m.key) { - node.hit_mass = decayed(node.hit_mass, clock - node.hit_stamp, half_life) + weight; - node.hit_stamp = clock; - node.touched = clock; - node.last_used_ms = self.now_ms; - node.hits += 1; - node.shared_hits += u64::from(shared); - self.stats.hits += 1; - self.stats.shared_hits += u64::from(shared); - self.stats.reused_tokens += m.tokens as u64; - } - } - - pub(super) fn probability(&self, node: &Node, children: u32) -> f64 { - let p = &self.cfg.policy; - let prior = if children == 0 && node.frontier { p.frontier_prior } else { 1.0 - (1.0 - p.interior_prior).powi(1 + children as i32) }; - let base = prior * decayed(1.0, self.clock - node.touched, p.half_life); - let mass = decayed(node.hit_mass, self.clock - node.hit_stamp, p.half_life); - (1.0 - (1.0 - base) * (-p.hit_gain * mass).exp()) * self.recency(node) - } - - /// Value of every node not in `removed`: expected tokens saved per byte its eviction frees. A node's saving is - /// measured against its nearest SURVIVING ancestor, so thinning a chain makes what is left worth more. - /// `protect`: blocks that stay whatever happens (the path of an entry being admitted). - pub(super) fn scores(&self, removed: &HashSet, protect: &HashSet) -> Vec { - let g = self.cfg.block_tokens; - let mut cover: HashMap = HashMap::new(); - for key in removed { - if let Some(node) = self.nodes.get(key) { - for h in node.path.iter() { - *cover.entry(*h).or_default() += 1; - } - } - } - let mut ancestor: HashMap = HashMap::with_capacity(self.nodes.len()); - let mut children: HashMap = HashMap::new(); - for (key, node) in &self.nodes { - if removed.contains(key) { - continue; - } - let mut depth = 0; - // a tail node's nearest ancestor may be the grid node at the end of its own path - let upto = if node.tail.is_some() { node.path.len() } else { node.path.len() - 1 }; - for i in (0..upto).rev() { - let h = node.path[i]; - if self.nodes.contains_key(&h) && !removed.contains(&h) { - depth = (i + 1) * g; - *children.entry(h).or_default() += 1; - break; - } - } - ancestor.insert(*key, depth); - } - let mut out = Vec::with_capacity(ancestor.len()); - for (key, node) in &self.nodes { - let Some(&anc) = ancestor.get(key) else { continue }; - let mut freed = node.bytes; - for h in node.path.iter() { - let block = &self.blocks[h]; - if block.refs.saturating_sub(cover.get(h).copied().unwrap_or(0)) == 1 && !protect.contains(h) { - freed += block.bytes; - } - } - let marginal = (self.tokens_of(node) - anc) as f64; - let p = self.probability(node, children.get(key).copied().unwrap_or(0)); - out.push(Scored { key: *key, score: p * marginal / freed.max(1) as f64, value: p * marginal, freed }); - } - out - } - - /// Decide whether a node for `tokens` (a whole number of blocks) is worth its bytes, making room if so. - /// `est_state` / `est_block`: the sizes the payloads are expected to have. Evictions made here are final even if - /// the caller then fails to build the payloads. - pub fn consider(&mut self, tokens: &[i32], frontier: bool, est_state: usize, est_block: usize) -> Consider { - let g = self.cfg.block_tokens; - assert!(!tokens.is_empty() && tokens.len() % g == 0, "a node covers whole blocks"); - self.consider_at(tokens, frontier, est_state, est_block) - } - - /// `consider` for a checkpoint at the END OF A REQUEST: `tokens` is a whole number of blocks (at least one) plus a tail of - /// 1..block_tokens tokens. The tail's cells are charged as the same share of a block. - pub fn consider_tail(&mut self, tokens: &[i32], frontier: bool, est_state: usize, est_block: usize) -> Consider { - let g = self.cfg.block_tokens; - assert!(tokens.len() > g && tokens.len() % g != 0, "a tail node extends at least one whole block by a partial one"); - self.consider_at(tokens, frontier, est_state, est_block) - } - - pub(super) fn consider_at(&mut self, tokens: &[i32], frontier: bool, est_state: usize, est_block: usize) -> Consider { - let g = self.cfg.block_tokens; - let tail_len = tokens.len() % g; - self.release_orphans(); - let mut path = Vec::with_capacity(tokens.len() / g); - let mut missing = Vec::new(); - let mut prev = CHAIN_SEED; - for (j, block) in tokens.chunks_exact(g).enumerate() { - let h = chain_step(prev, block); - match self.blocks.get(&h) { - Some(b) if *b.tokens != *block => { - self.stats.rejected += 1; - return Consider::Rejected(Reject::Collision); - } - Some(_) => {} - None => missing.push(j), - } - path.push(h); - prev = h; - } - let key = if tail_len == 0 { prev } else { chain_step(prev, &tokens[tokens.len() - tail_len..]) }; - if let Some(node) = self.nodes.get_mut(&key) { - node.touched = self.clock; - node.last_used_ms = self.now_ms; - self.stats.already_cached += 1; - return Consider::Exists; - } - let need = est_state + missing.len() * est_block + (est_block as u128 * tail_len as u128 / g as u128) as usize; - if need > self.cfg.budget_bytes { - self.stats.rejected += 1; - return Consider::Rejected(Reject::TooLarge); - } - let protect: HashSet = path.iter().copied().collect(); - let mut removed: Vec = Vec::new(); - let mut removed_set: HashSet = HashSet::new(); - let mut freed_total = 0usize; - let mut lost = 0.0f64; - let mut need_slot = self.nodes.len() >= self.cfg.max_nodes; - let free = self.cfg.budget_bytes.saturating_sub(self.bytes()); - while need > free + freed_total || need_slot { - let victim = self - .scores(&removed_set, &protect) - .into_iter() - .min_by(|a, b| a.score.total_cmp(&b.score).then(a.key.cmp(&b.key))); - let Some(victim) = victim else { - self.stats.rejected += 1; - return Consider::Rejected(Reject::NoRoom); - }; - // What the candidate would be worth once this victim is gone (a victim that is its own ancestor raises its - // saving) against everything given up so far: take victims while the sacrifice stays smaller than the gain. - let mut after = removed_set.clone(); - after.insert(victim.key); - if lost + victim.value >= self.candidate_value(&path, tail_len, frontier, &after) { - self.stats.rejected += 1; - return Consider::Rejected(Reject::NotWorth); - } - lost += victim.value; - freed_total += victim.freed; - removed_set.insert(victim.key); - removed.push(victim.key); - need_slot = false; - } - for key in removed { - self.evict_keeping(key, &protect); - } - Consider::Admit(Candidate { key, path, tail_len, missing, frontier }) - } - - /// Expected tokens saved by a node at the end of `path` (against its nearest surviving ancestor). - pub(super) fn candidate_value(&self, path: &[u64], tail_len: usize, frontier: bool, removed: &HashSet) -> f64 { - let g = self.cfg.block_tokens; - let upto = if tail_len > 0 { path.len() } else { path.len() - 1 }; - let anc = (0..upto) - .rev() - .find(|&i| self.nodes.contains_key(&path[i]) && !removed.contains(&path[i])) - .map_or(0, |i| (i + 1) * g); - let marginal = (path.len() * g + tail_len - anc) as f64; - let p = if frontier { self.cfg.policy.frontier_prior } else { self.cfg.policy.interior_prior }; - p * marginal - } - - /// Insert an admitted candidate. `tokens` are the same tokens that were considered; `blocks` hold exactly the - /// candidate's missing blocks. The real sizes may differ from the estimates: the budget is enforced again and the - /// new node may be the entry that goes. - pub fn commit(&mut self, candidate: Candidate, tokens: &[i32], state: N, blocks: Vec<(usize, B)>) -> Result<(), Reject> { - if candidate.tail_len != 0 { - return Err(Reject::Mismatch); - } - self.insert(candidate, tokens, state, blocks, None, None) - } - - /// `commit` of a tail node: `tail` holds the cells of the tokens after the last full block. Tail nodes of the same history that - /// end earlier (a token-wise prefix of this one) are superseded: the next request of the session starts from this one. - pub fn commit_tail(&mut self, candidate: Candidate, tokens: &[i32], state: N, blocks: Vec<(usize, B)>, tail: B) -> Result<(), Reject> { - self.commit_tail_keeping(candidate, tokens, state, blocks, tail, None) - } - - /// `commit_tail` that leaves the tail node ending at `keep_end` tokens standing. The decode-end checkpoint of a request extends - /// the same request's prompt-end checkpoint; when the client resends the history without the reply's reasoning, the next prompt - /// shares only the prompt part, so the prompt-end node must survive (the next request's own tails supersede it as usual). - pub fn commit_tail_keeping(&mut self, candidate: Candidate, tokens: &[i32], state: N, blocks: Vec<(usize, B)>, tail: B, keep_end: Option) -> Result<(), Reject> { - if candidate.tail_len == 0 { - return Err(Reject::Mismatch); - } - self.insert(candidate, tokens, state, blocks, Some(tail), keep_end) - } - - pub(super) fn insert(&mut self, candidate: Candidate, tokens: &[i32], state: N, blocks: Vec<(usize, B)>, tail: Option, keep_end: Option) -> Result<(), Reject> { - let g = self.cfg.block_tokens; - if tokens.len() != candidate.path.len() * g + candidate.tail_len - || blocks.len() != candidate.missing.len() - || blocks.iter().zip(&candidate.missing).any(|((j, _), m)| j != m) - || candidate.missing.iter().any(|j| self.blocks.contains_key(&candidate.path[*j])) - || self.nodes.contains_key(&candidate.key) - { - return Err(Reject::Mismatch); - } - for (j, payload) in blocks { - let bytes = payload.byte_size(); - self.block_bytes += bytes; - self.blocks.insert(candidate.path[j], Block { tokens: tokens[j * g..(j + 1) * g].into(), payload, bytes, refs: 0 }); - } - for h in &candidate.path { - self.orphans.remove(h); - match self.blocks.get_mut(h) { - Some(block) => block.refs += 1, - // a present block vanished between consider and commit: impossible while the caller is single-threaded - None => return Err(Reject::Mismatch), - } - } - let superseded = if candidate.tail_len > 0 { self.superseded_tails(&candidate.path, tokens, keep_end) } else { Vec::new() }; - let tail = tail.map(|payload| Tail { tokens: tokens[tokens.len() - candidate.tail_len..].into(), payload }); - let bytes = state.byte_size() + tail.as_ref().map_or(0, |t| t.payload.byte_size()); - self.node_bytes += bytes; - if tail.is_some() { - self.tails.entry(*candidate.path.last().expect("a tail extends a block")).or_default().push(candidate.key); - } - self.nodes.insert( - candidate.key, - Node { - path: candidate.path.into_boxed_slice(), - tail, - payload: state, - bytes, - touched: self.clock, - last_used_ms: self.now_ms, - hit_mass: 0.0, - hit_stamp: self.clock, - hits: 0, - shared_hits: 0, - frontier: candidate.frontier, - }, - ); - self.stats.admitted += 1; - for old in superseded { - self.evict(old); - } - self.enforce_budget(candidate.key); - Ok(()) - } - - /// Tail nodes whose tokens are a strict prefix of `tokens` (the history this tail node continues). - pub(super) fn superseded_tails(&self, path: &[u64], tokens: &[i32], keep_end: Option) -> Vec { - let g = self.cfg.block_tokens; - let mut out = Vec::new(); - for (j, parent) in path.iter().enumerate() { - let start = (j + 1) * g; - for key in self.tails.get(parent).into_iter().flatten() { - let Some(tail) = self.nodes.get(key).and_then(|n| n.tail.as_ref()) else { continue }; - let end = start + tail.tokens.len(); - if end < tokens.len() && Some(end) != keep_end && tokens[start..end] == *tail.tokens { - out.push(*key); - } - } - } - out - } - - pub(super) fn enforce_budget(&mut self, fresh: u64) { - while self.bytes() > self.cfg.budget_bytes || self.nodes.len() > self.cfg.max_nodes { - let victim = self - .scores(&HashSet::new(), &HashSet::new()) - .into_iter() - .min_by(|a, b| a.score.total_cmp(&b.score).then(a.key.cmp(&b.key))); - let Some(victim) = victim else { break }; - if victim.key == fresh { - self.stats.rejected_after_build += 1; - } - self.evict(victim.key); - } - } - - /// The caller could not build the payloads of an admitted candidate. - pub fn abort(&mut self, candidate: Candidate) { - drop(candidate); - self.release_orphans(); - } - - pub(super) fn release_orphans(&mut self) { - for h in std::mem::take(&mut self.orphans) { - if self.blocks.get(&h).is_some_and(|b| b.refs == 0) { - if let Some(block) = self.blocks.remove(&h) { - self.block_bytes -= block.bytes; - } - } - } - } - - /// Remove a node and every block only it covered. - pub(super) fn evict(&mut self, key: u64) { - self.evict_keeping(key, &HashSet::new()); - } - - /// `evict`, except that blocks in `keep` stay (as orphans) when this was their last node. - pub(super) fn evict_keeping(&mut self, key: u64, keep: &HashSet) { - let Some(node) = self.nodes.remove(&key) else { return }; - self.node_bytes -= node.bytes; - self.stats.evicted += 1; - if node.tail.is_some() { - if let Some(parent) = node.path.last() { - if let Some(list) = self.tails.get_mut(parent) { - list.retain(|k| *k != key); - if list.is_empty() { - self.tails.remove(parent); - } - } - } - } - for h in node.path.iter() { - let gone = match self.blocks.get_mut(h) { - Some(block) => { - block.refs -= 1; - block.refs == 0 - } - None => false, - }; - if gone && keep.contains(h) { - self.orphans.insert(*h); - } else if gone { - if let Some(block) = self.blocks.remove(h) { - self.block_bytes -= block.bytes; - } - } - } - } - - /// Drop everything (the device state the payloads were taken from is gone or suspect). - pub fn clear(&mut self) { - self.orphans.clear(); - self.blocks.clear(); - self.nodes.clear(); - self.tails.clear(); - self.node_bytes = 0; - self.block_bytes = 0; - } - - /// Change the budget (e.g. the operator or the memory guard); evicts down to it. - pub fn set_budget(&mut self, bytes: usize) { - self.cfg.budget_bytes = bytes; - self.enforce_budget(0); - } - - #[cfg(test)] - pub(crate) fn check_invariants(&self) { - let mut refs: HashMap = HashMap::new(); - let mut node_bytes = 0; - for node in self.nodes.values() { - node_bytes += node.bytes; - for h in node.path.iter() { - assert!(self.blocks.contains_key(h), "a node's block is missing"); - *refs.entry(*h).or_default() += 1; - } - } - let mut block_bytes = 0; - for (h, b) in &self.blocks { - assert_eq!(refs.get(h).copied().unwrap_or(0), b.refs, "refcount of a block"); - assert!(b.refs > 0 || self.orphans.contains(h), "an unreferenced block is kept"); - block_bytes += b.bytes; - } - assert_eq!((node_bytes, block_bytes), (self.node_bytes, self.block_bytes)); - } -} +mod impl_prefixstore_2; +mod impl_prefixstore_2_2; +mod impl_prefixstore_3; diff --git a/crates/leleka-runtime/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_2.rs b/crates/leleka-runtime/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_2.rs new file mode 100644 index 00000000..246df499 --- /dev/null +++ b/crates/leleka-runtime/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_2.rs @@ -0,0 +1,216 @@ +//! Moved out of the parent module by STRA-338: impl PrefixStore. + +#[allow(unused_imports)] +use super::*; + + + +impl PrefixStore { + pub fn new(cfg: StoreConfig) -> Self { + assert!(cfg.block_tokens > 0 && cfg.block_tokens % 4 == 0, "block_tokens must be a positive multiple of the 4-cell page"); + Self { cfg, blocks: HashMap::new(), nodes: HashMap::new(), tails: HashMap::new(), clock: 0, now_ms: 0, node_bytes: 0, block_bytes: 0, stats: Stats::default(), orphans: HashSet::new() } + } + pub fn config(&self) -> &StoreConfig { + &self.cfg + } + pub fn stats(&self) -> &Stats { + &self.stats + } + pub fn bytes(&self) -> usize { + self.node_bytes + self.block_bytes + } + pub fn node_bytes(&self) -> usize { + self.node_bytes + } + pub fn block_bytes(&self) -> usize { + self.block_bytes + } + pub fn node_count(&self) -> usize { + self.nodes.len() + } + pub fn block_count(&self) -> usize { + self.blocks.len() + } + pub fn clock(&self) -> u64 { + self.clock + } + + /// A new request begins: ages every prior and hit mass by one tick. + pub fn tick(&mut self, prompt_tokens: usize) { + self.clock += 1; + self.stats.requests += 1; + self.stats.prompt_tokens += prompt_tokens as u64; + } + + /// `tick` with the wall time of the request, in milliseconds on any monotonic scale. + pub fn tick_at(&mut self, prompt_tokens: usize, now_ms: u64) { + self.now_ms = self.now_ms.max(now_ms); + self.tick(prompt_tokens); + } + + /// Advance the wall time without a request (the idle sweep). + pub fn set_now(&mut self, now_ms: u64) { + self.now_ms = self.now_ms.max(now_ms); + } + + /// Drop every node unused for longer than the retention time; returns how many went (their blocks with them). + pub fn expire(&mut self) -> usize { + let limit = self.cfg.policy.retention_ms; + if limit == 0 { + return 0; + } + let now = self.now_ms; + let stale: Vec = self.nodes.iter().filter(|(_, node)| now.saturating_sub(node.last_used_ms) > limit).map(|(key, _)| *key).collect(); + for key in &stale { + self.evict(*key); + } + self.stats.expired += stale.len() as u64; + stale.len() + } + + /// How much of its value a node keeps at its age: 1 when just used, `recency_floor` at the retention limit. + pub(in super::super) fn recency(&self, node: &Node) -> f64 { + let p = &self.cfg.policy; + if p.retention_ms == 0 { + return 1.0; + } + let age = self.now_ms.saturating_sub(node.last_used_ms) as f64 / p.retention_ms as f64; + 1.0 - (1.0 - p.recency_floor) * age.min(1.0) + } + + pub fn contains_node(&self, key: u64) -> bool { + self.nodes.contains_key(&key) + } + pub fn node_payload(&self, key: u64) -> Option<&N> { + self.nodes.get(&key).map(|n| &n.payload) + } + /// Tokens the node covers. + pub fn node_tokens(&self, key: u64) -> Option { + self.nodes.get(&key).map(|n| self.tokens_of(n)) + } + pub(in super::super) fn tokens_of(&self, node: &Node) -> usize { + node.path.len() * self.cfg.block_tokens + node.tail.as_ref().map_or(0, |t| t.tokens.len()) + } + /// The tail of a request-end node: its cells, where they start and how many tokens they cover. + pub fn tail_of(&self, key: u64) -> Option<(&B, usize, usize)> { + let node = self.nodes.get(&key)?; + let tail = node.tail.as_ref()?; + Some((&tail.payload, node.path.len() * self.cfg.block_tokens, tail.tokens.len())) + } + /// The payloads of the node's blocks from block `from_block` on, with their block indices. + pub fn blocks_from(&self, key: u64, from_block: usize) -> Option> { + let node = self.nodes.get(&key)?; + let mut out = Vec::with_capacity(node.path.len().saturating_sub(from_block)); + for (j, h) in node.path.iter().enumerate().skip(from_block) { + out.push((j, &self.blocks.get(h)?.payload)); + } + Some(out) + } + + /// The deepest node that is a prefix of `tokens` and covers at most `limit` tokens. The blocks are compared + /// token for token, so a hash collision cannot produce a hit. + pub fn longest_match(&self, tokens: &[i32], limit: usize) -> Option { + let g = self.cfg.block_tokens; + let mut prev = CHAIN_SEED; + let mut best = None; + for (j, block) in tokens.chunks_exact(g).enumerate() { + let end = (j + 1) * g; + if end > limit { + break; + } + let h = chain_step(prev, block); + match self.blocks.get(&h) { + Some(b) if *b.tokens == *block => {} + _ => break, + } + prev = h; + if self.nodes.contains_key(&h) { + best = Some(Match { key: h, tokens: end }); + } + // request-end checkpoints that extend this block (the longest whose tokens are the prompt's next ones) + if let Some(keys) = self.tails.get(&h) { + for key in keys { + let Some(tail) = self.nodes.get(key).and_then(|n| n.tail.as_ref()) else { continue }; + let upto = end + tail.tokens.len(); + if upto <= limit && best.is_none_or(|b| upto > b.tokens) && tokens.get(end..upto).is_some_and(|t| t == &*tail.tokens) { + best = Some(Match { key: *key, tokens: upto }); + } + } + } + } + best + } + + /// The deepest node among `chain` (chain values of a prompt's blocks, from [`super::hash::chain`]): the tokens + /// of a cached prefix of that prompt, 0 when none. Hash-only (the router's query): it cannot see collisions. + pub fn prefix_match(&self, chain: &[u64]) -> usize { + chain.iter().rposition(|h| self.nodes.contains_key(h)).map_or(0, |j| (j + 1) * self.cfg.block_tokens) + } + + /// Every node as `(key, tokens)`, deepest first. + pub fn heads(&self) -> Vec<(u64, usize)> { + let mut heads: Vec<(u64, usize)> = + self.nodes.iter().filter(|(_, n)| n.tail.is_none()).map(|(k, n)| (*k, n.path.len() * self.cfg.block_tokens)).collect(); + heads.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0))); + heads + } + + /// The heads ranked by value (best first), for a summary that has to leave some out. + pub fn heads_by_value(&self) -> Vec<(u64, usize)> { + let mut scored = self.scores(&HashSet::new(), &HashSet::new()); + scored.sort_by(|a, b| b.score.total_cmp(&a.score).then(a.key.cmp(&b.key))); + scored + .iter() + .filter(|s| self.nodes[&s.key].tail.is_none()) + .map(|s| (s.key, self.nodes[&s.key].path.len() * self.cfg.block_tokens)) + .collect() + } + + pub fn record_miss(&mut self) { + self.stats.misses += 1; + } + + /// Whether the node has descendants, i.e. whether histories fork below it: a system prompt shared by several + /// sessions, or a rewritten history. (A session's own frontier has none.) + pub fn is_branch_point(&self, key: u64) -> bool { + let Some(node) = self.nodes.get(&key) else { return false }; + if node.tail.is_some() { + return false; + } + let at = node.path.len() - 1; + self.nodes.values().any(|other| other.path.len() > node.path.len() && other.path[at] == key) + } + + /// A request resumed from `m`. A hit on a branch point counts as evidence of sharing, a hit on a frontier as + /// the session's own continuation (see [`PolicyParams`]). + pub fn record_hit(&mut self, m: &Match) { + let branch = self.is_branch_point(m.key); + self.record_hit_as(m, branch); + } + + /// `record_hit` with the sharing verdict given by the caller. + pub fn record_hit_as(&mut self, m: &Match, shared: bool) { + let weight = if shared { self.cfg.policy.shared_weight } else { self.cfg.policy.continuation_weight }; + let clock = self.clock; + let half_life = self.cfg.policy.half_life; + if let Some(node) = self.nodes.get_mut(&m.key) { + node.hit_mass = decayed(node.hit_mass, clock - node.hit_stamp, half_life) + weight; + node.hit_stamp = clock; + node.touched = clock; + node.last_used_ms = self.now_ms; + node.hits += 1; + node.shared_hits += u64::from(shared); + self.stats.hits += 1; + self.stats.shared_hits += u64::from(shared); + self.stats.reused_tokens += m.tokens as u64; + } + } + + pub(in super::super) fn probability(&self, node: &Node, children: u32) -> f64 { + let p = &self.cfg.policy; + let prior = if children == 0 && node.frontier { p.frontier_prior } else { 1.0 - (1.0 - p.interior_prior).powi(1 + children as i32) }; + let base = prior * decayed(1.0, self.clock - node.touched, p.half_life); + let mass = decayed(node.hit_mass, self.clock - node.hit_stamp, p.half_life); + (1.0 - (1.0 - base) * (-p.hit_gain * mass).exp()) * self.recency(node) + } +} diff --git a/crates/leleka-runtime/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_2_2.rs b/crates/leleka-runtime/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_2_2.rs new file mode 100644 index 00000000..c9f011e8 --- /dev/null +++ b/crates/leleka-runtime/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_2_2.rs @@ -0,0 +1,253 @@ +//! Moved out of the parent module by STRA-338: impl PrefixStore (2). + +#[allow(unused_imports)] +use super::*; + + + +impl PrefixStore { + + /// Value of every node not in `removed`: expected tokens saved per byte its eviction frees. A node's saving is + /// measured against its nearest SURVIVING ancestor, so thinning a chain makes what is left worth more. + /// `protect`: blocks that stay whatever happens (the path of an entry being admitted). + pub(in super::super) fn scores(&self, removed: &HashSet, protect: &HashSet) -> Vec { + let g = self.cfg.block_tokens; + let mut cover: HashMap = HashMap::new(); + for key in removed { + if let Some(node) = self.nodes.get(key) { + for h in node.path.iter() { + *cover.entry(*h).or_default() += 1; + } + } + } + let mut ancestor: HashMap = HashMap::with_capacity(self.nodes.len()); + let mut children: HashMap = HashMap::new(); + for (key, node) in &self.nodes { + if removed.contains(key) { + continue; + } + let mut depth = 0; + // a tail node's nearest ancestor may be the grid node at the end of its own path + let upto = if node.tail.is_some() { node.path.len() } else { node.path.len() - 1 }; + for i in (0..upto).rev() { + let h = node.path[i]; + if self.nodes.contains_key(&h) && !removed.contains(&h) { + depth = (i + 1) * g; + *children.entry(h).or_default() += 1; + break; + } + } + ancestor.insert(*key, depth); + } + let mut out = Vec::with_capacity(ancestor.len()); + for (key, node) in &self.nodes { + let Some(&anc) = ancestor.get(key) else { continue }; + let mut freed = node.bytes; + for h in node.path.iter() { + let block = &self.blocks[h]; + if block.refs.saturating_sub(cover.get(h).copied().unwrap_or(0)) == 1 && !protect.contains(h) { + freed += block.bytes; + } + } + let marginal = (self.tokens_of(node) - anc) as f64; + let p = self.probability(node, children.get(key).copied().unwrap_or(0)); + out.push(Scored { key: *key, score: p * marginal / freed.max(1) as f64, value: p * marginal, freed }); + } + out + } + + /// Decide whether a node for `tokens` (a whole number of blocks) is worth its bytes, making room if so. + /// `est_state` / `est_block`: the sizes the payloads are expected to have. Evictions made here are final even if + /// the caller then fails to build the payloads. + pub fn consider(&mut self, tokens: &[i32], frontier: bool, est_state: usize, est_block: usize) -> Consider { + let g = self.cfg.block_tokens; + assert!(!tokens.is_empty() && tokens.len() % g == 0, "a node covers whole blocks"); + self.consider_at(tokens, frontier, est_state, est_block) + } + + /// `consider` for a checkpoint at the END OF A REQUEST: `tokens` is a whole number of blocks (at least one) plus a tail of + /// 1..block_tokens tokens. The tail's cells are charged as the same share of a block. + pub fn consider_tail(&mut self, tokens: &[i32], frontier: bool, est_state: usize, est_block: usize) -> Consider { + let g = self.cfg.block_tokens; + assert!(tokens.len() > g && tokens.len() % g != 0, "a tail node extends at least one whole block by a partial one"); + self.consider_at(tokens, frontier, est_state, est_block) + } + + pub(in super::super) fn consider_at(&mut self, tokens: &[i32], frontier: bool, est_state: usize, est_block: usize) -> Consider { + let g = self.cfg.block_tokens; + let tail_len = tokens.len() % g; + self.release_orphans(); + let mut path = Vec::with_capacity(tokens.len() / g); + let mut missing = Vec::new(); + let mut prev = CHAIN_SEED; + for (j, block) in tokens.chunks_exact(g).enumerate() { + let h = chain_step(prev, block); + match self.blocks.get(&h) { + Some(b) if *b.tokens != *block => { + self.stats.rejected += 1; + return Consider::Rejected(Reject::Collision); + } + Some(_) => {} + None => missing.push(j), + } + path.push(h); + prev = h; + } + let key = if tail_len == 0 { prev } else { chain_step(prev, &tokens[tokens.len() - tail_len..]) }; + if let Some(node) = self.nodes.get_mut(&key) { + node.touched = self.clock; + node.last_used_ms = self.now_ms; + self.stats.already_cached += 1; + return Consider::Exists; + } + let need = est_state + missing.len() * est_block + (est_block as u128 * tail_len as u128 / g as u128) as usize; + if need > self.cfg.budget_bytes { + self.stats.rejected += 1; + return Consider::Rejected(Reject::TooLarge); + } + let protect: HashSet = path.iter().copied().collect(); + let mut removed: Vec = Vec::new(); + let mut removed_set: HashSet = HashSet::new(); + let mut freed_total = 0usize; + let mut lost = 0.0f64; + let mut need_slot = self.nodes.len() >= self.cfg.max_nodes; + let free = self.cfg.budget_bytes.saturating_sub(self.bytes()); + while need > free + freed_total || need_slot { + let victim = self + .scores(&removed_set, &protect) + .into_iter() + .min_by(|a, b| a.score.total_cmp(&b.score).then(a.key.cmp(&b.key))); + let Some(victim) = victim else { + self.stats.rejected += 1; + return Consider::Rejected(Reject::NoRoom); + }; + // What the candidate would be worth once this victim is gone (a victim that is its own ancestor raises its + // saving) against everything given up so far: take victims while the sacrifice stays smaller than the gain. + let mut after = removed_set.clone(); + after.insert(victim.key); + if lost + victim.value >= self.candidate_value(&path, tail_len, frontier, &after) { + self.stats.rejected += 1; + return Consider::Rejected(Reject::NotWorth); + } + lost += victim.value; + freed_total += victim.freed; + removed_set.insert(victim.key); + removed.push(victim.key); + need_slot = false; + } + for key in removed { + self.evict_keeping(key, &protect); + } + Consider::Admit(Candidate { key, path, tail_len, missing, frontier }) + } + + /// Expected tokens saved by a node at the end of `path` (against its nearest surviving ancestor). + pub(in super::super) fn candidate_value(&self, path: &[u64], tail_len: usize, frontier: bool, removed: &HashSet) -> f64 { + let g = self.cfg.block_tokens; + let upto = if tail_len > 0 { path.len() } else { path.len() - 1 }; + let anc = (0..upto) + .rev() + .find(|&i| self.nodes.contains_key(&path[i]) && !removed.contains(&path[i])) + .map_or(0, |i| (i + 1) * g); + let marginal = (path.len() * g + tail_len - anc) as f64; + let p = if frontier { self.cfg.policy.frontier_prior } else { self.cfg.policy.interior_prior }; + p * marginal + } + + /// Insert an admitted candidate. `tokens` are the same tokens that were considered; `blocks` hold exactly the + /// candidate's missing blocks. The real sizes may differ from the estimates: the budget is enforced again and the + /// new node may be the entry that goes. + pub fn commit(&mut self, candidate: Candidate, tokens: &[i32], state: N, blocks: Vec<(usize, B)>) -> Result<(), Reject> { + if candidate.tail_len != 0 { + return Err(Reject::Mismatch); + } + self.insert(candidate, tokens, state, blocks, None, None) + } + + /// `commit` of a tail node: `tail` holds the cells of the tokens after the last full block. Tail nodes of the same history that + /// end earlier (a token-wise prefix of this one) are superseded: the next request of the session starts from this one. + pub fn commit_tail(&mut self, candidate: Candidate, tokens: &[i32], state: N, blocks: Vec<(usize, B)>, tail: B) -> Result<(), Reject> { + self.commit_tail_keeping(candidate, tokens, state, blocks, tail, None) + } + + /// `commit_tail` that leaves the tail node ending at `keep_end` tokens standing. The decode-end checkpoint of a request extends + /// the same request's prompt-end checkpoint; when the client resends the history without the reply's reasoning, the next prompt + /// shares only the prompt part, so the prompt-end node must survive (the next request's own tails supersede it as usual). + pub fn commit_tail_keeping(&mut self, candidate: Candidate, tokens: &[i32], state: N, blocks: Vec<(usize, B)>, tail: B, keep_end: Option) -> Result<(), Reject> { + if candidate.tail_len == 0 { + return Err(Reject::Mismatch); + } + self.insert(candidate, tokens, state, blocks, Some(tail), keep_end) + } + + pub(in super::super) fn insert(&mut self, candidate: Candidate, tokens: &[i32], state: N, blocks: Vec<(usize, B)>, tail: Option, keep_end: Option) -> Result<(), Reject> { + let g = self.cfg.block_tokens; + if tokens.len() != candidate.path.len() * g + candidate.tail_len + || blocks.len() != candidate.missing.len() + || blocks.iter().zip(&candidate.missing).any(|((j, _), m)| j != m) + || candidate.missing.iter().any(|j| self.blocks.contains_key(&candidate.path[*j])) + || self.nodes.contains_key(&candidate.key) + { + return Err(Reject::Mismatch); + } + for (j, payload) in blocks { + let bytes = payload.byte_size(); + self.block_bytes += bytes; + self.blocks.insert(candidate.path[j], Block { tokens: tokens[j * g..(j + 1) * g].into(), payload, bytes, refs: 0 }); + } + for h in &candidate.path { + self.orphans.remove(h); + match self.blocks.get_mut(h) { + Some(block) => block.refs += 1, + // a present block vanished between consider and commit: impossible while the caller is single-threaded + None => return Err(Reject::Mismatch), + } + } + let superseded = if candidate.tail_len > 0 { self.superseded_tails(&candidate.path, tokens, keep_end) } else { Vec::new() }; + let tail = tail.map(|payload| Tail { tokens: tokens[tokens.len() - candidate.tail_len..].into(), payload }); + let bytes = state.byte_size() + tail.as_ref().map_or(0, |t| t.payload.byte_size()); + self.node_bytes += bytes; + if tail.is_some() { + self.tails.entry(*candidate.path.last().expect("a tail extends a block")).or_default().push(candidate.key); + } + self.nodes.insert( + candidate.key, + Node { + path: candidate.path.into_boxed_slice(), + tail, + payload: state, + bytes, + touched: self.clock, + last_used_ms: self.now_ms, + hit_mass: 0.0, + hit_stamp: self.clock, + hits: 0, + shared_hits: 0, + frontier: candidate.frontier, + }, + ); + self.stats.admitted += 1; + for old in superseded { + self.evict(old); + } + self.enforce_budget(candidate.key); + Ok(()) + } + + /// Tail nodes whose tokens are a strict prefix of `tokens` (the history this tail node continues). + pub(in super::super) fn superseded_tails(&self, path: &[u64], tokens: &[i32], keep_end: Option) -> Vec { + let g = self.cfg.block_tokens; + let mut out = Vec::new(); + for (j, parent) in path.iter().enumerate() { + let start = (j + 1) * g; + for key in self.tails.get(parent).into_iter().flatten() { + let Some(tail) = self.nodes.get(key).and_then(|n| n.tail.as_ref()) else { continue }; + let end = start + tail.tokens.len(); + if end < tokens.len() && Some(end) != keep_end && tokens[start..end] == *tail.tokens { + out.push(*key); + } + } + } + out + } +} diff --git a/crates/leleka-runtime/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_3.rs b/crates/leleka-runtime/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_3.rs new file mode 100644 index 00000000..e61a68d3 --- /dev/null +++ b/crates/leleka-runtime/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_3.rs @@ -0,0 +1,113 @@ +//! Moved out of the parent module by STRA-338: impl PrefixStore (3). + +#[allow(unused_imports)] +use super::*; + + + +impl PrefixStore { + + pub(in super::super) fn enforce_budget(&mut self, fresh: u64) { + while self.bytes() > self.cfg.budget_bytes || self.nodes.len() > self.cfg.max_nodes { + let victim = self + .scores(&HashSet::new(), &HashSet::new()) + .into_iter() + .min_by(|a, b| a.score.total_cmp(&b.score).then(a.key.cmp(&b.key))); + let Some(victim) = victim else { break }; + if victim.key == fresh { + self.stats.rejected_after_build += 1; + } + self.evict(victim.key); + } + } + + /// The caller could not build the payloads of an admitted candidate. + pub fn abort(&mut self, candidate: Candidate) { + drop(candidate); + self.release_orphans(); + } + + pub(in super::super) fn release_orphans(&mut self) { + for h in std::mem::take(&mut self.orphans) { + if self.blocks.get(&h).is_some_and(|b| b.refs == 0) { + if let Some(block) = self.blocks.remove(&h) { + self.block_bytes -= block.bytes; + } + } + } + } + + /// Remove a node and every block only it covered. + pub(in super::super) fn evict(&mut self, key: u64) { + self.evict_keeping(key, &HashSet::new()); + } + + /// `evict`, except that blocks in `keep` stay (as orphans) when this was their last node. + pub(in super::super) fn evict_keeping(&mut self, key: u64, keep: &HashSet) { + let Some(node) = self.nodes.remove(&key) else { return }; + self.node_bytes -= node.bytes; + self.stats.evicted += 1; + if node.tail.is_some() { + if let Some(parent) = node.path.last() { + if let Some(list) = self.tails.get_mut(parent) { + list.retain(|k| *k != key); + if list.is_empty() { + self.tails.remove(parent); + } + } + } + } + for h in node.path.iter() { + let gone = match self.blocks.get_mut(h) { + Some(block) => { + block.refs -= 1; + block.refs == 0 + } + None => false, + }; + if gone && keep.contains(h) { + self.orphans.insert(*h); + } else if gone { + if let Some(block) = self.blocks.remove(h) { + self.block_bytes -= block.bytes; + } + } + } + } + + /// Drop everything (the device state the payloads were taken from is gone or suspect). + pub fn clear(&mut self) { + self.orphans.clear(); + self.blocks.clear(); + self.nodes.clear(); + self.tails.clear(); + self.node_bytes = 0; + self.block_bytes = 0; + } + + /// Change the budget (e.g. the operator or the memory guard); evicts down to it. + pub fn set_budget(&mut self, bytes: usize) { + self.cfg.budget_bytes = bytes; + self.enforce_budget(0); + } + + #[cfg(test)] + pub(crate) fn check_invariants(&self) { + let mut refs: HashMap = HashMap::new(); + let mut node_bytes = 0; + for node in self.nodes.values() { + node_bytes += node.bytes; + for h in node.path.iter() { + assert!(self.blocks.contains_key(h), "a node's block is missing"); + *refs.entry(*h).or_default() += 1; + } + } + let mut block_bytes = 0; + for (h, b) in &self.blocks { + assert_eq!(refs.get(h).copied().unwrap_or(0), b.refs, "refcount of a block"); + assert!(b.refs > 0 || self.orphans.contains(h), "an unreferenced block is kept"); + block_bytes += b.bytes; + } + assert_eq!((node_bytes, block_bytes), (self.node_bytes, self.block_bytes)); + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/cache_profile_fill/impl_moeweightcache.rs b/crates/leleka-runtime/src/qwen_forward/cache_profile_fill/impl_moeweightcache.rs index 1e3e099a..d674b250 100644 --- a/crates/leleka-runtime/src/qwen_forward/cache_profile_fill/impl_moeweightcache.rs +++ b/crates/leleka-runtime/src/qwen_forward/cache_profile_fill/impl_moeweightcache.rs @@ -3,409 +3,7 @@ #[allow(unused_imports)] use super::*; - -impl<'ctx> MoeWeightCache<'ctx> { - /// Private candidate only. The caller creates all eager Dense owners first. - pub(crate) fn new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile( - binding: &ModelBinding, - context: &'ctx Context<'ctx>, - bytes: &[u8], - ) -> Result { - Self::profile_with_mtp_input(binding, context, bytes, false) - } - /// Explicit new candidate only; all prior constructors create no input queue. - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(crate) fn new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile_mtp_input( - binding: &ModelBinding, - context: &'ctx Context<'ctx>, - bytes: &[u8], - ) -> Result { - Self::profile_with_mtp_input(binding, context, bytes, true) - } - pub(super) fn profile_with_mtp_input( - binding: &ModelBinding, - context: &'ctx Context<'ctx>, - bytes: &[u8], - with_mtp_input: bool, - ) -> Result { - Self::profile_with_mtp_input_and_spill_floor(binding, context, bytes, with_mtp_input, 0) - } - // Only the separately named experimental factory supplies a nonzero floor. - // Old constructors preserve their original complete-prefix policy via zero. - pub(in super::super) fn profile_with_mtp_input_and_spill_floor( - binding: &ModelBinding, - context: &'ctx Context<'ctx>, - bytes: &[u8], - with_mtp_input: bool, - reusable_spill_floor: usize, - ) -> Result { - let profile = RankedProfile::parse(bytes, PROFILE_SHA)?; - let mut cache = - Self::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_lru(binding, context)?; - let operation = (|| { - cache.validate(binding, context)?; - if with_mtp_input { - cache.admit_mtp_input_workspace(binding)?; - } - // These are genuine bound tensor descriptors, not chosen routes. - let mut layer_keys = Vec::new(); - layer_keys - .try_reserve_exact(48) - .map_err(|_| Error::InputAllocation)?; - let mut charges = [[0usize; 3]; 48]; - for (layer, charge) in charges.iter_mut().enumerate() { - let keys = [ - binding - .moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Gate) - .map_err(binding_error)?, - binding - .moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Up) - .map_err(binding_error)?, - binding - .moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Down) - .map_err(binding_error)?, - ]; - for (n, key) in keys.iter().enumerate() { - charge[n] = cache.weight_layout(*key)?.map_or(key.bytes, |(_, n)| n); - } - layer_keys.push(keys); - } - let (free, _) = context.memory_info().map_err(driver_error)?; - // Max simultaneously live original native micro64 allocation set; - // this exceeds the resident-MMQ packet peak. Weight triplet is separate. - // PrefixPlan subtracts this additive floor from main, typed and - // physical capacity. Its published spill_reserve is also rechecked - // by every unchanged preload_pinned_triplet before real uploads. - let window_spill = profile_window_spill_with_floor(reusable_spill_floor)?; - let plan = PrefixPlan::new( - &profile, - &charges, - ProfileLimits { - main_cap: MAIN_LIMIT, - allocated: context.allocated_bytes(), - device_budget: context.budget_bytes(), - physical_free: free, - working_reserve: WORKING_RESERVE, - window_spill, - }, - )?; - let metadata_base = profile - .metadata_bytes() - .checked_add(plan.metadata_bytes()) - .and_then(|n| n.checked_add(bytes.len())) - .and_then(|n| n.checked_add(std::mem::size_of::())) - .and_then(|n| { - n.checked_add( - layer_keys.capacity() * std::mem::size_of::<[MoeWeightDescriptor; 3]>(), - ) - }) - .and_then(|n| n.checked_add(cache.lru.as_ref()?.metadata_bytes().ok()?)) - .ok_or(Error::Overflow)?; - let count = plan.prefix.checked_mul(3).ok_or(Error::Overflow)?; - // One weight map, allocated before publishing any owner. A 2^15 - // request fits every real complete prefix allowed by the 24GiB - // cap (smallest admitted triplet is >1.5MB). Actual capacity is - // rechecked rather than assumed, and bounds all later spill inserts. - cache - .main - .try_reserve(count.max(1 << 15)) - .map_err(|_| Error::InputAllocation)?; - let main_slot_limit = cache.main.capacity(); - // Current pinned Rust std HashMap uses 7/8 load factor. 4/3 of - // reported capacity conservatively covers buckets, plus controls - // and the extra SIMD control group. This includes real owner tuples. - let buckets = main_slot_limit - .checked_mul(4) - .and_then(|n| n.checked_add(2)) - .map(|n| n / 3) - .ok_or(Error::Overflow)?; - let map_bytes = buckets - .checked_mul(std::mem::size_of::<(MoeWeightDescriptor, Entry<'ctx>)>() + 1) - .and_then(|n| { - n.checked_add( - 16 + std::mem::size_of::>>(), - ) - }) - .ok_or(Error::Overflow)?; - let metadata_bytes = metadata_base - .checked_add(map_bytes) - .ok_or(Error::Overflow)?; - if metadata_bytes > HOST_CAP || count > main_slot_limit { - return Err(Error::InputAllocation); - } - let expected_bytes = plan.charged_bytes; - cache.pinned = Some(PinnedPool { - plan, - loaded_matrices: 0, - shared: None, - #[cfg(test)] - metadata_bytes, - main_slot_limit, - #[cfg(test)] - fixed_resident_upload_bytes: cache.counters.upload_bytes, - #[cfg(test)] - fixed_resident_read_bytes: cache.counters.read_bytes, - pinned_hits: 0, - spill_hits: 0, - spill_misses: 0, - preload_read_bytes: 0, - preload_upload_bytes: 0, - }); - let prefix = cache - .pinned - .as_ref() - .ok_or(Error::IdentityMismatch)? - .plan - .prefix; - for &(layer, expert) in &profile.ordered_pairs()[..prefix] { - // Re-admit each actual expert source before reading any matrix. - let keys = [ - binding - .moe_preload_descriptor( - u32::from(layer), - u32::from(expert), - MoeMatrixRole::Gate, - ) - .map_err(binding_error)?, - binding - .moe_preload_descriptor( - u32::from(layer), - u32::from(expert), - MoeMatrixRole::Up, - ) - .map_err(binding_error)?, - binding - .moe_preload_descriptor( - u32::from(layer), - u32::from(expert), - MoeMatrixRole::Down, - ) - .map_err(binding_error)?, - ]; - let mut topology_keys = layer_keys[usize::from(layer)]; - for key in &mut topology_keys { - key.expert = Some(u32::from(expert)); - } - if keys != topology_keys { - return Err(Error::IdentityMismatch); - } - cache.preload_pinned_triplet(binding, keys)?; - } - if cache.main_bytes != expected_bytes - || cache.spill_len()? != 0 - || cache - .pinned - .as_ref() - .is_none_or(|pool| pool.loaded_matrices != count) - { - return Err(Error::IdentityMismatch); - } - cache.validate(binding, context) - })(); - if let Err(primary) = operation { - let _ = cache.close(); - return Err(primary); - } - Ok(cache) - } - pub(super) fn preload_pinned_triplet( - &mut self, - binding: &ModelBinding, - keys: [MoeWeightDescriptor; 3], - ) -> Result<()> { - if keys - .iter() - .any(|key| !self.is_pinned(*key) || self.main.contains_key(key)) - { - return Err(Error::IdentityMismatch); - } - let layouts = [ - self.weight_layout(keys[0])?, - self.weight_layout(keys[1])?, - self.weight_layout(keys[2])?, - ]; - let charges = - std::array::from_fn::<_, 3, _>(|i| layouts[i].map_or(keys[i].bytes, |(_, n)| n)); - let extra = charges - .iter() - .try_fold(0usize, |n, v| n.checked_add(*v)) - .ok_or(Error::Overflow)?; - let spill = self - .pinned - .as_ref() - .ok_or(Error::IdentityMismatch)? - .plan - .spill_reserve; - // Requery real physical room for each upload, leaving the complete spill - // allowance and working reserve intact. No eviction of already pinned owners. - let (free, _) = self.context.memory_info().map_err(driver_error)?; - let required = extra - .checked_add(spill) - .and_then(|n| n.checked_add(WORKING_RESERVE)) - .ok_or(Error::Overflow)?; - if required > free - || self - .context - .allocated_bytes() - .checked_add(required) - .is_none_or(|n| n > self.context.budget_bytes()) - || self - .main_bytes - .checked_add(extra) - .and_then(|n| n.checked_add(spill)) - .is_none_or(|n| n > MAIN_LIMIT) - { - return Err(Error::InputAllocation); - } - let next_bytes = self.main_bytes.checked_add(extra).ok_or(Error::Overflow)?; - let next_age = self.age.checked_add(3).ok_or(Error::Overflow)?; - let next_loaded = self - .pinned - .as_ref() - .ok_or(Error::IdentityMismatch)? - .loaded_matrices - .checked_add(3) - .ok_or(Error::Overflow)?; - let raw = [ - binding.moe_preload_block(keys[0]).map_err(binding_error)?, - binding.moe_preload_block(keys[1]).map_err(binding_error)?, - binding.moe_preload_block(keys[2]).map_err(binding_error)?, - ]; - let read_bytes = raw - .iter() - .try_fold(0usize, |n, b| n.checked_add(b.len())) - .ok_or(Error::Overflow)?; - let mut owned: [Option>; 3] = std::array::from_fn(|_| None); - let operation: Result<()> = (|| { - if let [Some((gate, _)), Some((up, _)), Some((down, _))] = layouts { - let owners = if self.original_prompt_mmq { - self.context.mmq_original_weight_triplet( - [gate, up, down], [&raw[0], &raw[1], &raw[2]]) - } else { - self.context.mmq_weight_triplet( - [gate, up, down], [&raw[0], &raw[1], &raw[2]]) - }.map_err(driver_error)?; - if owners - .iter() - .zip(charges) - .any(|(owner, charge)| owner.allocated_bytes() != charge) - { - for owner in owners.into_iter().rev() { - if owner.close().is_err() { - self.failed.set(true); - } - } - return Err(Error::IdentityMismatch); - } - for (i, owner) in owners.into_iter().enumerate() { - owned[i] = Some(EncodedWeight::Dual([gate, up, down][i], owner)); - } - } else { - for i in 0..3 { - if raw[i].len() != keys[i].bytes { - return Err(Error::InvalidDimension); - } - let weight = if let Some((format, expected)) = layouts[i] { - let owner = self - .context - .mmq_weights(format, &raw[i]) - .map_err(driver_error)?; - if owner.allocated_bytes() != expected { - if owner.close().is_err() { - self.failed.set(true); - } - return Err(Error::IdentityMismatch); - } - EncodedWeight::Dual(format, owner) - } else { - // Original upload includes the same full encoded bytes. - EncodedWeight::Raw(self.upload(&raw[i])?) - }; - owned[i] = Some(weight); - } - } - Ok(()) - })(); - if let Err(primary) = operation { - for owner in owned.into_iter().rev().flatten() { - if owner.close().is_err() { - self.failed.set(true); - } - } - if self.context.is_poisoned() { - self.failed.set(true); - } - return Err(primary); - } - // Capacity, complete ownership, byte/age/count arithmetic checked above. - // No fallible work or allocation follows the first triplet insertion. - for (i, owner) in owned.into_iter().enumerate() { - self.main.insert( - keys[i], - Entry { - weight: owner.unwrap(), - charged_bytes: charges[i], - age: self.age + i as u64 + 1, - }, - ); - } - self.main_bytes = next_bytes; - self.age = next_age; - self.counters.misses = self.counters.misses.saturating_add(3); - let pool = self.pinned.as_mut().unwrap(); - pool.loaded_matrices = next_loaded; - pool.preload_read_bytes = pool.preload_read_bytes.saturating_add(read_bytes as u64); - pool.preload_upload_bytes = pool.preload_upload_bytes.saturating_add(extra as u64); - // Raw uploads already update source/upload counters; Dual uploads do not. - for i in 0..3 { - if layouts[i].is_some() { - self.counters.read_bytes = - self.counters.read_bytes.saturating_add(raw[i].len() as u64); - self.counters.upload_bytes = - self.counters.upload_bytes.saturating_add(charges[i] as u64); - } - } - for (key, charge) in keys.into_iter().zip(charges) { - self.note_permanent_fill(key, key.bytes, charge); - } - Ok(()) - } - #[cfg(test)] - pub(crate) fn test_profile_witness(&self) -> Result { - let pool = self.pinned.as_ref().ok_or(Error::IdentityMismatch)?; - if pool.loaded_matrices != pool.plan.prefix * 3 { - return Err(Error::IdentityMismatch); - } - Ok(ProfileWitness { - main_slot_limit: pool.main_slot_limit, - fixed_resident_upload_bytes: pool.fixed_resident_upload_bytes, - spill_bytes: self - .main_bytes - .checked_sub(pool.plan.charged_bytes) - .and_then(|n| n.checked_sub(pool.shared.as_ref().map_or(0, |shared| shared.bytes))) - .ok_or(Error::IdentityMismatch)?, - post_preload_read_bytes: self - .counters - .read_bytes - .checked_sub(pool.fixed_resident_read_bytes) - .and_then(|n| n.checked_sub(pool.preload_read_bytes)) - .ok_or(Error::IdentityMismatch)?, - post_preload_upload_bytes: self - .counters - .upload_bytes - .checked_sub(pool.fixed_resident_upload_bytes) - .and_then(|n| n.checked_sub(pool.preload_upload_bytes)) - .ok_or(Error::IdentityMismatch)?, - prefix: pool.plan.prefix, - pinned_bytes: pool.plan.charged_bytes, - spill_reserve: pool.plan.spill_reserve, - largest_triplet: pool.plan.largest_triplet, - metadata_bytes: pool.metadata_bytes, - pinned_hits: pool.pinned_hits, - spill_hits: pool.spill_hits, - spill_misses: pool.spill_misses, - preload_read_bytes: pool.preload_read_bytes, - preload_upload_bytes: self.profile_preload_upload_bytes(), - }) - } -} +#[path = "impl_moeweightcache/impl_moeweightcache_2.rs"] +mod impl_moeweightcache_2; +#[path = "impl_moeweightcache/impl_moeweightcache_2_2.rs"] +mod impl_moeweightcache_2_2; diff --git a/crates/leleka-runtime/src/qwen_forward/cache_profile_fill/impl_moeweightcache/impl_moeweightcache_2.rs b/crates/leleka-runtime/src/qwen_forward/cache_profile_fill/impl_moeweightcache/impl_moeweightcache_2.rs new file mode 100644 index 00000000..4aa25bb6 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/cache_profile_fill/impl_moeweightcache/impl_moeweightcache_2.rs @@ -0,0 +1,212 @@ +//! Moved out of the parent module by STRA-338: impl MoeWeightCache. + +#[allow(unused_imports)] +use super::*; + + + +impl<'ctx> MoeWeightCache<'ctx> { + /// Private candidate only. The caller creates all eager Dense owners first. + pub(crate) fn new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + bytes: &[u8], + ) -> Result { + Self::profile_with_mtp_input(binding, context, bytes, false) + } + /// Explicit new candidate only; all prior constructors create no input queue. + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(crate) fn new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile_mtp_input( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + bytes: &[u8], + ) -> Result { + Self::profile_with_mtp_input(binding, context, bytes, true) + } + pub(in super::super) fn profile_with_mtp_input( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + bytes: &[u8], + with_mtp_input: bool, + ) -> Result { + Self::profile_with_mtp_input_and_spill_floor(binding, context, bytes, with_mtp_input, 0) + } + // Only the separately named experimental factory supplies a nonzero floor. + // Old constructors preserve their original complete-prefix policy via zero. + pub(in super::super::super) fn profile_with_mtp_input_and_spill_floor( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + bytes: &[u8], + with_mtp_input: bool, + reusable_spill_floor: usize, + ) -> Result { + let profile = RankedProfile::parse(bytes, PROFILE_SHA)?; + let mut cache = + Self::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_lru(binding, context)?; + let operation = (|| { + cache.validate(binding, context)?; + if with_mtp_input { + cache.admit_mtp_input_workspace(binding)?; + } + // These are genuine bound tensor descriptors, not chosen routes. + let mut layer_keys = Vec::new(); + layer_keys + .try_reserve_exact(48) + .map_err(|_| Error::InputAllocation)?; + let mut charges = [[0usize; 3]; 48]; + for (layer, charge) in charges.iter_mut().enumerate() { + let keys = [ + binding + .moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Gate) + .map_err(binding_error)?, + binding + .moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Up) + .map_err(binding_error)?, + binding + .moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Down) + .map_err(binding_error)?, + ]; + for (n, key) in keys.iter().enumerate() { + charge[n] = cache.weight_layout(*key)?.map_or(key.bytes, |(_, n)| n); + } + layer_keys.push(keys); + } + let (free, _) = context.memory_info().map_err(driver_error)?; + // Max simultaneously live original native micro64 allocation set; + // this exceeds the resident-MMQ packet peak. Weight triplet is separate. + // PrefixPlan subtracts this additive floor from main, typed and + // physical capacity. Its published spill_reserve is also rechecked + // by every unchanged preload_pinned_triplet before real uploads. + let window_spill = profile_window_spill_with_floor(reusable_spill_floor)?; + let plan = PrefixPlan::new( + &profile, + &charges, + ProfileLimits { + main_cap: MAIN_LIMIT, + allocated: context.allocated_bytes(), + device_budget: context.budget_bytes(), + physical_free: free, + working_reserve: WORKING_RESERVE, + window_spill, + }, + )?; + let metadata_base = profile + .metadata_bytes() + .checked_add(plan.metadata_bytes()) + .and_then(|n| n.checked_add(bytes.len())) + .and_then(|n| n.checked_add(std::mem::size_of::())) + .and_then(|n| { + n.checked_add( + layer_keys.capacity() * std::mem::size_of::<[MoeWeightDescriptor; 3]>(), + ) + }) + .and_then(|n| n.checked_add(cache.lru.as_ref()?.metadata_bytes().ok()?)) + .ok_or(Error::Overflow)?; + let count = plan.prefix.checked_mul(3).ok_or(Error::Overflow)?; + // One weight map, allocated before publishing any owner. A 2^15 + // request fits every real complete prefix allowed by the 24GiB + // cap (smallest admitted triplet is >1.5MB). Actual capacity is + // rechecked rather than assumed, and bounds all later spill inserts. + cache + .main + .try_reserve(count.max(1 << 15)) + .map_err(|_| Error::InputAllocation)?; + let main_slot_limit = cache.main.capacity(); + // Current pinned Rust std HashMap uses 7/8 load factor. 4/3 of + // reported capacity conservatively covers buckets, plus controls + // and the extra SIMD control group. This includes real owner tuples. + let buckets = main_slot_limit + .checked_mul(4) + .and_then(|n| n.checked_add(2)) + .map(|n| n / 3) + .ok_or(Error::Overflow)?; + let map_bytes = buckets + .checked_mul(std::mem::size_of::<(MoeWeightDescriptor, Entry<'ctx>)>() + 1) + .and_then(|n| { + n.checked_add( + 16 + std::mem::size_of::>>(), + ) + }) + .ok_or(Error::Overflow)?; + let metadata_bytes = metadata_base + .checked_add(map_bytes) + .ok_or(Error::Overflow)?; + if metadata_bytes > HOST_CAP || count > main_slot_limit { + return Err(Error::InputAllocation); + } + let expected_bytes = plan.charged_bytes; + cache.pinned = Some(PinnedPool { + plan, + loaded_matrices: 0, + shared: None, + #[cfg(test)] + metadata_bytes, + main_slot_limit, + #[cfg(test)] + fixed_resident_upload_bytes: cache.counters.upload_bytes, + #[cfg(test)] + fixed_resident_read_bytes: cache.counters.read_bytes, + pinned_hits: 0, + spill_hits: 0, + spill_misses: 0, + preload_read_bytes: 0, + preload_upload_bytes: 0, + }); + let prefix = cache + .pinned + .as_ref() + .ok_or(Error::IdentityMismatch)? + .plan + .prefix; + for &(layer, expert) in &profile.ordered_pairs()[..prefix] { + // Re-admit each actual expert source before reading any matrix. + let keys = [ + binding + .moe_preload_descriptor( + u32::from(layer), + u32::from(expert), + MoeMatrixRole::Gate, + ) + .map_err(binding_error)?, + binding + .moe_preload_descriptor( + u32::from(layer), + u32::from(expert), + MoeMatrixRole::Up, + ) + .map_err(binding_error)?, + binding + .moe_preload_descriptor( + u32::from(layer), + u32::from(expert), + MoeMatrixRole::Down, + ) + .map_err(binding_error)?, + ]; + let mut topology_keys = layer_keys[usize::from(layer)]; + for key in &mut topology_keys { + key.expert = Some(u32::from(expert)); + } + if keys != topology_keys { + return Err(Error::IdentityMismatch); + } + cache.preload_pinned_triplet(binding, keys)?; + } + if cache.main_bytes != expected_bytes + || cache.spill_len()? != 0 + || cache + .pinned + .as_ref() + .is_none_or(|pool| pool.loaded_matrices != count) + { + return Err(Error::IdentityMismatch); + } + cache.validate(binding, context) + })(); + if let Err(primary) = operation { + let _ = cache.close(); + return Err(primary); + } + Ok(cache) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/cache_profile_fill/impl_moeweightcache/impl_moeweightcache_2_2.rs b/crates/leleka-runtime/src/qwen_forward/cache_profile_fill/impl_moeweightcache/impl_moeweightcache_2_2.rs new file mode 100644 index 00000000..82c64aa0 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/cache_profile_fill/impl_moeweightcache/impl_moeweightcache_2_2.rs @@ -0,0 +1,209 @@ +//! Moved out of the parent module by STRA-338: impl MoeWeightCache (2). + +#[allow(unused_imports)] +use super::*; + + + +impl<'ctx> MoeWeightCache<'ctx> { + pub(in super::super) fn preload_pinned_triplet( + &mut self, + binding: &ModelBinding, + keys: [MoeWeightDescriptor; 3], + ) -> Result<()> { + if keys + .iter() + .any(|key| !self.is_pinned(*key) || self.main.contains_key(key)) + { + return Err(Error::IdentityMismatch); + } + let layouts = [ + self.weight_layout(keys[0])?, + self.weight_layout(keys[1])?, + self.weight_layout(keys[2])?, + ]; + let charges = + std::array::from_fn::<_, 3, _>(|i| layouts[i].map_or(keys[i].bytes, |(_, n)| n)); + let extra = charges + .iter() + .try_fold(0usize, |n, v| n.checked_add(*v)) + .ok_or(Error::Overflow)?; + let spill = self + .pinned + .as_ref() + .ok_or(Error::IdentityMismatch)? + .plan + .spill_reserve; + // Requery real physical room for each upload, leaving the complete spill + // allowance and working reserve intact. No eviction of already pinned owners. + let (free, _) = self.context.memory_info().map_err(driver_error)?; + let required = extra + .checked_add(spill) + .and_then(|n| n.checked_add(WORKING_RESERVE)) + .ok_or(Error::Overflow)?; + if required > free + || self + .context + .allocated_bytes() + .checked_add(required) + .is_none_or(|n| n > self.context.budget_bytes()) + || self + .main_bytes + .checked_add(extra) + .and_then(|n| n.checked_add(spill)) + .is_none_or(|n| n > MAIN_LIMIT) + { + return Err(Error::InputAllocation); + } + let next_bytes = self.main_bytes.checked_add(extra).ok_or(Error::Overflow)?; + let next_age = self.age.checked_add(3).ok_or(Error::Overflow)?; + let next_loaded = self + .pinned + .as_ref() + .ok_or(Error::IdentityMismatch)? + .loaded_matrices + .checked_add(3) + .ok_or(Error::Overflow)?; + let raw = [ + binding.moe_preload_block(keys[0]).map_err(binding_error)?, + binding.moe_preload_block(keys[1]).map_err(binding_error)?, + binding.moe_preload_block(keys[2]).map_err(binding_error)?, + ]; + let read_bytes = raw + .iter() + .try_fold(0usize, |n, b| n.checked_add(b.len())) + .ok_or(Error::Overflow)?; + let mut owned: [Option>; 3] = std::array::from_fn(|_| None); + let operation: Result<()> = (|| { + if let [Some((gate, _)), Some((up, _)), Some((down, _))] = layouts { + let owners = if self.original_prompt_mmq { + self.context.mmq_original_weight_triplet( + [gate, up, down], [&raw[0], &raw[1], &raw[2]]) + } else { + self.context.mmq_weight_triplet( + [gate, up, down], [&raw[0], &raw[1], &raw[2]]) + }.map_err(driver_error)?; + if owners + .iter() + .zip(charges) + .any(|(owner, charge)| owner.allocated_bytes() != charge) + { + for owner in owners.into_iter().rev() { + if owner.close().is_err() { + self.failed.set(true); + } + } + return Err(Error::IdentityMismatch); + } + for (i, owner) in owners.into_iter().enumerate() { + owned[i] = Some(EncodedWeight::Dual([gate, up, down][i], owner)); + } + } else { + for i in 0..3 { + if raw[i].len() != keys[i].bytes { + return Err(Error::InvalidDimension); + } + let weight = if let Some((format, expected)) = layouts[i] { + let owner = self + .context + .mmq_weights(format, &raw[i]) + .map_err(driver_error)?; + if owner.allocated_bytes() != expected { + if owner.close().is_err() { + self.failed.set(true); + } + return Err(Error::IdentityMismatch); + } + EncodedWeight::Dual(format, owner) + } else { + // Original upload includes the same full encoded bytes. + EncodedWeight::Raw(self.upload(&raw[i])?) + }; + owned[i] = Some(weight); + } + } + Ok(()) + })(); + if let Err(primary) = operation { + for owner in owned.into_iter().rev().flatten() { + if owner.close().is_err() { + self.failed.set(true); + } + } + if self.context.is_poisoned() { + self.failed.set(true); + } + return Err(primary); + } + // Capacity, complete ownership, byte/age/count arithmetic checked above. + // No fallible work or allocation follows the first triplet insertion. + for (i, owner) in owned.into_iter().enumerate() { + self.main.insert( + keys[i], + Entry { + weight: owner.unwrap(), + charged_bytes: charges[i], + age: self.age + i as u64 + 1, + }, + ); + } + self.main_bytes = next_bytes; + self.age = next_age; + self.counters.misses = self.counters.misses.saturating_add(3); + let pool = self.pinned.as_mut().unwrap(); + pool.loaded_matrices = next_loaded; + pool.preload_read_bytes = pool.preload_read_bytes.saturating_add(read_bytes as u64); + pool.preload_upload_bytes = pool.preload_upload_bytes.saturating_add(extra as u64); + // Raw uploads already update source/upload counters; Dual uploads do not. + for i in 0..3 { + if layouts[i].is_some() { + self.counters.read_bytes = + self.counters.read_bytes.saturating_add(raw[i].len() as u64); + self.counters.upload_bytes = + self.counters.upload_bytes.saturating_add(charges[i] as u64); + } + } + for (key, charge) in keys.into_iter().zip(charges) { + self.note_permanent_fill(key, key.bytes, charge); + } + Ok(()) + } + #[cfg(test)] + pub(crate) fn test_profile_witness(&self) -> Result { + let pool = self.pinned.as_ref().ok_or(Error::IdentityMismatch)?; + if pool.loaded_matrices != pool.plan.prefix * 3 { + return Err(Error::IdentityMismatch); + } + Ok(ProfileWitness { + main_slot_limit: pool.main_slot_limit, + fixed_resident_upload_bytes: pool.fixed_resident_upload_bytes, + spill_bytes: self + .main_bytes + .checked_sub(pool.plan.charged_bytes) + .and_then(|n| n.checked_sub(pool.shared.as_ref().map_or(0, |shared| shared.bytes))) + .ok_or(Error::IdentityMismatch)?, + post_preload_read_bytes: self + .counters + .read_bytes + .checked_sub(pool.fixed_resident_read_bytes) + .and_then(|n| n.checked_sub(pool.preload_read_bytes)) + .ok_or(Error::IdentityMismatch)?, + post_preload_upload_bytes: self + .counters + .upload_bytes + .checked_sub(pool.fixed_resident_upload_bytes) + .and_then(|n| n.checked_sub(pool.preload_upload_bytes)) + .ok_or(Error::IdentityMismatch)?, + prefix: pool.plan.prefix, + pinned_bytes: pool.plan.charged_bytes, + spill_reserve: pool.plan.spill_reserve, + largest_triplet: pool.plan.largest_triplet, + metadata_bytes: pool.metadata_bytes, + pinned_hits: pool.pinned_hits, + spill_hits: pool.spill_hits, + spill_misses: pool.spill_misses, + preload_read_bytes: pool.preload_read_bytes, + preload_upload_bytes: self.profile_preload_upload_bytes(), + }) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/dense_weight_cache/impl_denseweightcache.rs b/crates/leleka-runtime/src/qwen_forward/dense_weight_cache/impl_denseweightcache.rs index 3ef42257..28d9cffa 100644 --- a/crates/leleka-runtime/src/qwen_forward/dense_weight_cache/impl_denseweightcache.rs +++ b/crates/leleka-runtime/src/qwen_forward/dense_weight_cache/impl_denseweightcache.rs @@ -3,1480 +3,10 @@ #[allow(unused_imports)] use super::*; -impl<'ctx> DenseWeightCache<'ctx> { - pub(crate) fn new(binding: &ModelBinding, context: &'ctx Context<'ctx>) -> Result { - Self::new_with_selected(binding, context, false) - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(crate) fn new_qsa_selected( - binding: &ModelBinding, - context: &'ctx Context<'ctx>, - ) -> Result { - Self::new_with_selected(binding, context, true) - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(crate) fn new_qsa_selected_router( - binding: &ModelBinding, - context: &'ctx Context<'ctx>, - ) -> Result { - let mut result = Self::new_qsa_selected(binding, context)?; - match RouterScratch::new( - result.binding.clone(), - context, - result.mirror_failed.clone(), - ) { - Ok(slot) => result.router_scratch = Some(RefCell::new(slot)), - Err(primary) => { - let _ = result.close(); - return Err(primary); - } - } - result.gdn_four_borrow = true; - Ok(result) - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(crate) fn new_qsa_selected_router_gr_batch( - binding: &ModelBinding, - context: &'ctx Context<'ctx>, - ) -> Result { - let mut result = Self::new_qsa_selected_router(binding, context)?; - match context.gr_batch_inject_workspace() { - Ok(slot) => result.gr_batch_workspace = Some(RefCell::new(slot)), - Err(error) => { - let primary = driver_error(error); - let _ = result.close(); - return Err(primary); - } - } - Ok(result) - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(crate) fn new_qsa_selected_router_gr_batch_qk( - binding: &ModelBinding, - context: &'ctx Context<'ctx>, - ) -> Result { - let mut result = Self::new_qsa_selected_router_gr_batch(binding, context)?; - match QkScratch::new( - result.binding.clone(), - context, - result.mirror_failed.clone(), - ) { - Ok(slot) => result.gdn_qk_workspace = Some(Rc::new(slot)), - Err(primary) => { - let _ = result.close(); - return Err(primary); - } - } - // Caller creates its real PrefixPlan/preload only AFTER this factory. - Ok(result) - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(crate) fn new_qsa_selected_router_gr_batch_qk_attention( - binding: &ModelBinding, - context: &'ctx Context<'ctx>, - ) -> Result { - Self::new_attention_capacity(binding,context,64) - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(super) fn new_attention_capacity(binding:&ModelBinding,context:&'ctx Context<'ctx>,capacity:usize)->Result { - if !(1..=8192).contains(&capacity) {return Err(Error::InvalidDimension);} - let mut result = Self::new_qsa_selected_router_gr_batch_qk(binding, context)?; - result.native_prompt_capacity=capacity; - match QsaAttentionScratch::new_experimental(binding, context, result.mirror_failed.clone()) - { - Ok(slot) => { - if slot.allocated_bytes() != super::super::qsa_attention::attention_scratch::SCRATCH_BYTES - { - let _ = slot.close(); - let _ = result.close(); - return Err(Error::InvalidDimension); - } - result.qsa_attention_workspace = Some(RefCell::new(slot)); - } - Err(primary) => { - let _ = result.close(); - return Err(primary); - } - } - // This selected actor eagerly owns the actual PLE queue before any - // expert cache budget is admitted. Default actors retain their path. - match context.ple_closed_queue() { - Ok(queue) => result.ple_queue = Some(RefCell::new(queue)), - Err(error) => { - let primary = driver_error(error); - let _ = result.close(); - return Err(primary); - } - } - // Literal prefill GEMM has one model-lifetime vendor handle, stream and - // actual 32 MiB workspace. Each producer releases its exclusive loan - // after completion; a row bank never carries it across attention. - match context.native_batch_workspace() { - Ok(workspace) => result.native_batch_workspace = Some(RefCell::new(workspace)), - Err(error) => { - let primary = driver_error(error); - let _ = result.close(); - return Err(primary); - } - } - // Original selected mode17 profile has STRATA_PREFILL_BF16X2 absent. - // HighOnly is explicit. Hi+Lo is a separately qualified load profile. - match if capacity==64 {context.ple_batch_queue(leleka_cuda_driver::PleBf16Mode::HighOnly)}else{context.ple_batch_queue_for_prompt(leleka_cuda_driver::PleBf16Mode::HighOnly,capacity)} { - Ok(queue) => result.ple_batch_queue = Some(RefCell::new(queue)), - Err(error) => { - let primary = driver_error(error); - let _ = result.close(); - return Err(primary); - } - } - match if capacity==64 {super::super::gdn::prefill_batch::GdnBatchResources::new(context,super::super::gdn::prefill_batch::Bf16Profile::HighOnly)}else{super::super::gdn::prefill_batch::GdnBatchResources::new_for_prompt(context,super::super::gdn::prefill_batch::Bf16Profile::HighOnly,capacity)} { - Ok(resources) => result.gdn_batch_resources = Some(RefCell::new(resources)), - Err(primary) => { - let _ = result.close(); - return Err(primary); - } - } - match if capacity==64 {context.qsa_native_batch_workspace(leleka_cuda_driver::QsaNativePacking::HighOnly)}else{context.qsa_native_batch_workspace_for_prompt(leleka_cuda_driver::QsaNativePacking::HighOnly,capacity)} { - Ok(owner) => result.qsa_native_workspace = Some(RefCell::new(owner)), - Err(error) => { - let primary = driver_error(error); - let _ = result.close(); - return Err(primary); - } - } - match if capacity==64 {super::super::qsa_native_resources::NativeQsaResources::new(context,result.mirror_failed.clone())}else{super::super::qsa_native_resources::NativeQsaResources::new_for_prompt(context,result.mirror_failed.clone(),capacity)} { - Ok(owner) => result.native_qsa = Some(RefCell::new(owner)), - Err(primary) => { - let _ = result.close(); - return Err(primary); - } - } - // The selected native target and verification journal share one actual - // closed fused program owner, charged before any routed PrefixPlan. - match context.gdn_fused_t1() { - Ok(owner) => result.native_gdn_fused = Some(Rc::new(RefCell::new(owner))), - Err(error) => { - let primary = driver_error(error); - let _ = result.close(); - return Err(primary); - } - } - // Actual scratch, mapped/canonical KV ledger and exact64 banks are eager before routed PrefixPlan. - Ok(result) - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in super::super) fn native_qsa( - &self, - binding: &ModelBinding, - context: &Context<'_>, - ) -> Result>> { - self.retained_context(binding, context)?; - let resource = self.native_qsa.as_ref().ok_or(Error::IdentityMismatch)?; - let owner = resource - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch)?; - owner.validate(context)?; - Ok(owner) - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in super::super) fn has_native_qsa(&self) -> bool { - self.native_qsa.is_some() - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in crate::qwen_forward) fn native_gdn_fused( - &self, - binding: &ModelBinding, - context: &Context<'_>, - ) -> Result>>> { - self.retained_context(binding, context)?; - let owner = self.native_gdn_fused.as_ref().ok_or(Error::IdentityMismatch)?; - if owner.try_borrow().map_err(|_| Error::IdentityMismatch)?.is_failed() { - self.mirror_failed.set(true); - return Err(Error::CudaExecution); - } - Ok(owner.clone()) - } - pub(in super::super) fn qsa_attention_workspace(&self) -> Option<&RefCell>> { - self.qsa_attention_workspace.as_ref() - } - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(crate) fn test_retained_scratch_witness(&self) -> Result<(usize, u64)> { - let qk = self - .gdn_qk_workspace - .as_ref() - .ok_or(Error::IdentityMismatch)? - .test_slot_bytes()?; - let qsa = self - .qsa_attention_workspace - .as_ref() - .ok_or(Error::IdentityMismatch)? - .try_borrow() - .map_err(|_| Error::IdentityMismatch)?; - Ok(( - qk.checked_add(qsa.allocated_bytes()) - .ok_or(Error::Overflow)?, - qsa.completed_rows(), - )) - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(crate) fn new_qsa_selected_router_gr_batch_qk_attention_mtp_journal( - binding: &ModelBinding, - context: &'ctx Context<'ctx>, - ) -> Result { - let mut cache = Self::new_qsa_selected_router_gr_batch_qk_attention(binding, context)?; - match super::super::gdn::verification::Workspace::new( - cache.binding.clone(), - context, - cache.mirror_failed.clone(), - ) { - Ok(workspace) => cache.gdn_verification = Some(Rc::new(RefCell::new(workspace))), - Err(primary) => { - let _ = cache.close(); - return Err(primary); - } - } - Ok(cache) - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(crate) fn new_original_prompt_capacity(binding:&ModelBinding,context:&'ctx Context<'ctx>,capacity:usize)->Result { - if !(1..=8192).contains(&capacity){return Err(Error::InvalidDimension);} - // Actual weights and scalar/decode state remain model-lifetime owners. - // Prompt payloads live in the Original aliased arena, so this factory - // never allocates the legacy capacity-sized PLE/GDN/QSA row banks. - let mut cache=startup_step("new_with_selected",Self::new_with_selected(binding,context,false))?; - cache.native_prompt_capacity=capacity; - let loaded=(||->Result<()>{ - cache.native_batch_workspace=Some(RefCell::new(startup_step("native_batch_workspace",context.native_batch_workspace()).map_err(driver_error)?)); - cache.ple_queue=Some(RefCell::new(startup_step("ple_closed_queue",context.ple_closed_queue()).map_err(driver_error)?)); - cache.native_gdn_fused=Some(Rc::new(RefCell::new(startup_step("gdn_fused_t1",context.gdn_fused_t1()).map_err(driver_error)?))); - cache.gdn_verification=Some(Rc::new(RefCell::new(startup_step("gdn verification workspace",super::super::gdn::verification::Workspace::new( - cache.binding.clone(),context,cache.mirror_failed.clone()))?))); - cache.gdn_qk_workspace=Some(Rc::new(startup_step("gdn qk scratch",QkScratch::new(cache.binding.clone(),context,cache.mirror_failed.clone()))?)); - cache.router_scratch=Some(RefCell::new(startup_step("router scratch",RouterScratch::new(cache.binding.clone(),context,cache.mirror_failed.clone()))?)); - cache.gr_batch_workspace=Some(RefCell::new(startup_step("gr_batch_inject_workspace",context.gr_batch_inject_workspace()).map_err(driver_error)?)); - cache.gdn_four_borrow=true; - startup_step("validate",cache.validate(binding)) - })(); - if loaded.is_ok() && let Some(slabs) = cache.slabs.as_ref() { - let stats = slabs.stats(); - eprintln!( - "leleka-serve dense weights: {} buffers; {} slabs of {} MiB hold {} of them ({:.1} MiB), {} buffers above {} MiB keep their own allocation ({:.1} MiB driver-estimated)", - cache.buffers.len(), stats.slabs, SlabPolicy::DENSE.slab_bytes >> 20, stats.carved, stats.carved_bytes as f64 / 1048576.0, - stats.direct, SlabPolicy::DENSE.direct_above >> 20, stats.direct_bytes as f64 / 1048576.0, - ); - } - match loaded{Ok(())=>Ok(cache),Err(primary)=>{let _=cache.close();Err(primary)}} - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in crate::qwen_forward) fn native_prompt_capacity(&self,binding:&ModelBinding,context:&Context<'_>)->Result { - self.retained_context(binding,context)?; - if self.native_batch_workspace.is_none()||!(1..=8192).contains(&self.native_prompt_capacity) {return Err(Error::IdentityMismatch);} - Ok(self.native_prompt_capacity) - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in crate::qwen_forward) fn native_prompt_transient_device_bytes(&self,binding:&ModelBinding,context:&Context<'_>)->Result { - let capacity=self.native_prompt_capacity(binding,context)?; - let gr=leleka_cuda_driver::GrNativeBatch::prompt_device_bytes(capacity).map_err(driver_error)?; - let qsa=leleka_cuda_driver::QsaPromptIndexWorkspace::prompt_output_bytes(capacity).map_err(driver_error)?; - gr.checked_add(qsa).ok_or(Error::Overflow) - } - /// An idle GDN next-state finite guard of this cache's Context, or a new one. - pub(in crate::qwen_forward) fn take_gdn_guard( - &self, - binding: &ModelBinding, - context: &Context<'_>, - ) -> Result> { - let context = self.retained_context(binding, context)?; - let idle = self.gdn_guards.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.pop(); - match idle { - Some(guard) if !guard.is_failed() => Ok(guard), - Some(guard) => { - let _ = guard.close(); - context.gdn_state_finite_guard().map_err(driver_error) - } - None => context.gdn_state_finite_guard().map_err(driver_error), - } - } - /// A 3.1 MB GDN state buffer: an idle pooled one when `LELEKA_PREFILL_GDN_POOL` is on, else a fresh allocation. Contents are never assumed. - pub(in crate::qwen_forward) fn take_gdn_scratch(&self, context: &'ctx Context<'ctx>, bytes: usize) -> Result> { - if super::super::gdn::pool_enabled() { - let idle = self.gdn_scratch.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.pop(); - if let Some(buffer) = idle { - if buffer.len() == bytes { - return Ok(buffer); - } - buffer.release().map_err(driver_error)?; - } - } - context.allocate(bytes).map_err(driver_error) - } - /// Give a GDN state buffer back: pooled (at most 4) when the switch is on, else released as before. - pub(in crate::qwen_forward) fn return_gdn_scratch(&self, buffer: DeviceBuffer<'ctx>) -> Result<()> { - if super::super::gdn::pool_enabled() { - let mut idle = self.gdn_scratch.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; - if idle.len() < 4 { - idle.push(buffer); - return Ok(()); - } - } - buffer.release().map_err(driver_error) - } - /// Give a guard back after a clean use; a failed one is closed instead. - pub(in crate::qwen_forward) fn return_gdn_guard( - &self, - guard: leleka_cuda_driver::GdnStateFiniteGuard<'ctx>, - ) -> Result<()> { - if guard.is_failed() { - return guard.close().map_err(driver_error); - } - let mut idle = self.gdn_guards.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; - if idle.len() >= 4 { - drop(idle); - return guard.close().map_err(driver_error); - } - idle.push(guard); - Ok(()) - } - pub(in crate::qwen_forward) fn has_gdn_verification_workspace(&self) -> bool { - self.gdn_verification.is_some() - } - pub(in crate::qwen_forward) fn gdn_verification_workspace( - &self, - binding: &ModelBinding, - context: &Context<'_>, - ) -> Result>> { - self.retained_context(binding, context)?; - if self.mirror_failed.get() { - return Err(Error::CudaExecution); - } - Ok(self.gdn_verification.clone()) - } - pub(super) fn new_with_selected( - binding: &ModelBinding, - context: &'ctx Context<'ctx>, - selected: bool, - ) -> Result { - let n = usize::try_from(binding.layer_count()).map_err(|_| Error::Overflow)?; - if n != 48 { - return Err(Error::InvalidDimension); - } - let mut result = Self { - modules: None, - binding: binding.identity(), - owner: Rc::new(()), - context, - buffers: Vec::new(), - slabs: Some(SlabAllocator::new(context, dense_slab_policy()).map_err(driver_error)?), - gdn: Vec::new(), - gdn_mirrors: Vec::new(), - mirror_failed: Rc::new(Cell::new(false)), - gdn_four_borrow: false, - gdn_input: None, - gdn_qk_workspace: None, - qsa_attention_workspace: None, - gdn_verification: None, - gdn_guards: RefCell::new(Vec::new()), - gdn_scratch: RefCell::new(Vec::new()), - gr_scratch: None, - qsa_input: None, - qsa_keys: None, - qsa_selected: None, - router_scratch: None, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - gr_batch_workspace: None, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - ple_queue: None, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - native_prompt_capacity: 64, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - native_batch_workspace: None, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - ple_batch_queue: None, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - gdn_batch_resources: None, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - qsa_native_workspace: None, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - native_qsa: None, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - native_gdn_fused: None, - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - gr_batch_completed: Cell::new(0), - qsa: Vec::new(), - gr: Vec::new(), - router: Vec::new(), - ple: None, - counters: Cell::new(DenseCacheCounters::default()), - }; - result.modules = Some(super::super::chunk_modules::ChunkModules::new( - context, - result.mirror_failed.clone(), - )); - let loaded = (|| -> Result<()> { - // Optional fixed byte workspace is eagerly charged before lazy MoE growth. - if selected { - result.qsa_selected = Some(RefCell::new(QsaSelectedCache::new( - result.binding.clone(), - context, - result.mirror_failed.clone(), - )?)); - } - result.qsa_keys = Some(RefCell::new(QsaIndexKeyCache::new( - result.binding.clone(), - context, - result.mirror_failed.clone(), - )?)); - result.qsa_input = Some(RefCell::new(QsaInputScratch::new( - result.binding.clone(), - context, - result.mirror_failed.clone(), - )?)); - // Fixed activation scratch is charged before any lazy MoE growth. - result.gdn_input = Some(RefCell::new(GdnInputScratch::new( - result.binding.clone(), - context, - result.mirror_failed.clone(), - )?)); - result.gr_scratch = Some(RefCell::new(GrScratch::new( - binding, - context, - result.mirror_failed.clone(), - )?)); - result - .gdn - .try_reserve_exact(n) - .map_err(|_| Error::InputAllocation)?; - result - .gdn_mirrors - .try_reserve_exact(n) - .map_err(|_| Error::InputAllocation)?; - result - .qsa - .try_reserve_exact(n) - .map_err(|_| Error::InputAllocation)?; - result - .gr - .try_reserve_exact(n * 2 + 1) - .map_err(|_| Error::InputAllocation)?; - result - .router - .try_reserve_exact(n) - .map_err(|_| Error::InputAllocation)?; - for layer in binding.ordered_layers() { - let id = layer.index(); - let gdn = if layer.kind() == BoundLayerKind::Gdn { - let weights = Rc::new(binding.gdn_weights(id).map_err(binding_error)?); - let mut matrices = [(0, GdnMatrixKind::Bf16); 5]; - for (i, role) in [ - GdnMatrixRole::Qkv, - GdnMatrixRole::Z, - GdnMatrixRole::Alpha, - GdnMatrixRole::Beta, - GdnMatrixRole::Out, - ] - .into_iter() - .enumerate() - { - let block = binding - .gdn_matrix_block(&weights, role, 0, weights.shape(role).1) - .map_err(binding_error)?; - matrices[i] = ( - result.add( - block.bytes(), - weights.source_bytes(role).map_err(binding_error)?, - )?, - block.kind(), - ); - } - let aux = [ - result.add_f32(weights.conv())?, - result.add_f32(weights.dt())?, - result.add_f32(weights.a())?, - result.add_f32(weights.norm())?, - ]; - Some(GdnResident { - owner: result.owner.clone(), - weights, - matrices, - aux, - }) - } else { - None - }; - let qsa = if layer.kind() == BoundLayerKind::Qsa { - let weights = Rc::new(binding.qsa_weights(id).map_err(binding_error)?); - let mut matrices = [(0, QsaMatrixKind::Bf16); 6]; - for (i, role) in [ - QsaMatrixRole::Q, - QsaMatrixRole::K, - QsaMatrixRole::V, - QsaMatrixRole::IndexQ, - QsaMatrixRole::IndexK, - QsaMatrixRole::Out, - ] - .into_iter() - .enumerate() - { - let block = binding - .qsa_matrix_block(&weights, role, 0, weights.shape(role).1) - .map_err(binding_error)?; - matrices[i] = ( - result.add( - block.bytes(), - weights.source_bytes(role).map_err(binding_error)?, - )?, - block.kind(), - ); - } - let norms = [ - result.add_f32(weights.q_norm())?, - result.add_f32(weights.k_norm())?, - result.add_f32(weights.index_q_norm())?, - result.add_f32(weights.index_k_norm())?, - ]; - Some(QsaResident { - owner: result.owner.clone(), - weights, - matrices, - norms, - }) - } else { - None - }; - let mirror = gdn - .as_ref() - .map(|_| { - GdnStateMirror::new( - result.binding.clone(), - id, - context, - result.mirror_failed.clone(), - ) - }) - .transpose()? - .map(RefCell::new); - result.gdn.push(gdn); - result.gdn_mirrors.push(mirror); - result.qsa.push(qsa); - for role in [GrRole::Attention(id), GrRole::Ffn(id)] { - result.add_gr(binding, role)?; - } - let weights = binding.moe_route_weights(id).map_err(binding_error)?; - let block = binding - .moe_route_matrix_block(&weights, 0, 512) - .map_err(binding_error)?; - let index = result.add(block.bytes(), block.bytes().len())?; - result.router.push(index); - } - result.add_gr(binding, GrRole::Final)?; - result.add_ple(binding)?; - let mirror_count = result - .gdn_mirrors - .iter() - .filter(|entry| entry.is_some()) - .count(); - if mirror_count.checked_mul(786432 * 4) != Some(ALL_MIRROR_BYTES) { - return Err(Error::InvalidDimension); - } - result.validate(binding)?; - Ok(()) - })(); - match loaded { - Ok(()) => Ok(result), - Err(primary) => { - // A failed eager load publishes no cache. Explicitly attempt - // every owned release, preserving the original load refusal. - let _ = result.close(); - Err(primary) - } - } - } - pub(super) fn add(&mut self, bytes: &[u8], source_bytes: usize) -> Result { - if self - .context - .allocated_bytes() - .checked_add(bytes.len()) - .and_then(|n| n.checked_add(RESERVE)) - .is_none_or(|n| n > self.context.budget_bytes()) - { - return Err(Error::InputAllocation); - } - self.buffers - .try_reserve(1) - .map_err(|_| Error::InputAllocation)?; - let mut b = self.slabs.as_mut().ok_or(Error::IdentityMismatch)?.allocate(bytes.len()).map_err(driver_error)?; - if let Err(error) = b.copy_from(bytes) { - let primary = driver_error(error); - let _ = b.release(); - return Err(primary); - } - let index = self.buffers.len(); - self.buffers.push(b); - let mut c = self.counters.get(); - c.matrices = c.matrices.checked_add(1).ok_or(Error::Overflow)?; - c.read_bytes = c - .read_bytes - .checked_add(source_bytes as u64) - .ok_or(Error::Overflow)?; - c.upload_bytes = c - .upload_bytes - .checked_add(bytes.len() as u64) - .ok_or(Error::Overflow)?; - self.counters.set(c); - Ok(index) - } - pub(super) fn add_f32(&mut self, values: &[f32]) -> Result { - let mut bytes = Vec::new(); - bytes - .try_reserve_exact(values.len().checked_mul(4).ok_or(Error::Overflow)?) - .map_err(|_| Error::InputAllocation)?; - for v in values { - if !v.is_finite() { - return Err(Error::NonFinite); - } - bytes.extend_from_slice(&v.to_le_bytes()); - } - self.add(&bytes, bytes.len()) - } - pub(super) fn add_bf16(&mut self, values: &[u16], source_bytes: usize) -> Result { - let mut bytes = Vec::new(); - bytes - .try_reserve_exact(values.len().checked_mul(2).ok_or(Error::Overflow)?) - .map_err(|_| Error::InputAllocation)?; - for v in values { - if !f32::from_bits(u32::from(*v) << 16).is_finite() { - return Err(Error::NonFinite); - } - bytes.extend_from_slice(&v.to_le_bytes()); - } - self.add(&bytes, source_bytes) - } - pub(super) fn add_gr(&mut self, binding: &ModelBinding, role: GrRole) -> Result<()> { - let weights = Rc::new(binding.gr_weights(role).map_err(binding_error)?); - let source_bytes = binding.gr_source_bytes(role).map_err(binding_error)?; - let buffers = [ - Some(self.add_f32(weights.norm())?), - Some(self.add_bf16(weights.down(), source_bytes[1])?), - Some(self.add_bf16(weights.up(), source_bytes[2])?), - weights - .inject() - .map(|v| self.add_bf16(v, source_bytes[3])) - .transpose()?, - ]; - self.gr.push(GrResident { - owner: self.owner.clone(), - weights, - buffers, - }); - Ok(()) - } - pub(super) fn add_ple(&mut self, binding: &ModelBinding) -> Result<()> { - let weights = Rc::new(binding.ple_weights().map_err(binding_error)?); - // Key retains one complete immutable matrix with the same total byte - // charge as its former 160 tiles; per-row projection math is unchanged. - let key_matrix = binding - .ple_matrix_full(&weights, PleMatrixRole::Key) - .map_err(binding_error)?; - if key_matrix.rows() != 10240 || key_matrix.bytes().len() != 52_428_800 { - return Err(Error::InvalidDimension); - } - let key = self.add(key_matrix.bytes(), key_matrix.bytes().len())?; - drop(key_matrix); - // Value retains one whole immutable matrix; forty CTAs keep the original row arithmetic. - let value_matrix = binding - .ple_matrix_full(&weights, PleMatrixRole::Value) - .map_err(binding_error)?; - if value_matrix.rows() != 2560 || value_matrix.bytes().len() != 2560 * 2560 * 2 { - return Err(Error::InvalidDimension); - } - let value = self.add(value_matrix.bytes(), value_matrix.bytes().len())?; - drop(value_matrix); - let mut conv = Vec::new(); - conv.try_reserve_exact(weights.conv().len() * 2) - .map_err(|_| Error::InputAllocation)?; - for v in weights.conv() { - if !leleka_quant_core::f16_bits_to_f32(*v).is_finite() { - return Err(Error::NonFinite); - } - conv.extend_from_slice(&v.to_le_bytes()); - } - let aux = [ - self.add_f32(weights.norm_key())?, - self.add_f32(weights.norm_query())?, - self.add_f32(weights.norm_conv())?, - self.add(&conv, conv.len())?, - ]; - self.ple = Some(PleResident { - owner: self.owner.clone(), - weights, - key, - value, - aux, - }); - Ok(()) - } - pub(in super::super) fn validate(&self, binding: &ModelBinding) -> Result<()> { - self.check(binding)?; - binding.validate_dense_sources().map_err(binding_error)?; - binding.validate_ple_sources().map_err(binding_error) - } - pub(super) fn check(&self, binding: &ModelBinding) -> Result<()> { - if !self.binding.matches(&binding.identity()) { - return Err(Error::IdentityMismatch); - } - if self.mirror_failed.get() { - #[cfg(test)] - eprintln!( - "PUBLIC CUDA stage=dense-cache-fence shared_failed=true context_poisoned={} allocated={} budget={}", - self.context.is_poisoned(), - self.context.allocated_bytes(), - self.context.budget_bytes() - ); - return Err(Error::CudaExecution); - } - Ok(()) - } - pub(in super::super) fn retained_context( - &self, - binding: &ModelBinding, - context: &Context<'_>, - ) -> Result<&'ctx Context<'ctx>> { - self.check(binding)?; - if !std::ptr::eq(self.context, context) { - return Err(Error::IdentityMismatch); - } - Ok(self.context) - } - pub(in super::super) fn router_scratch<'loan>( - &'loan self, - binding: &ModelBinding, - context: &Context<'_>, - source: &'loan super::super::gr::ResidualReady, - ) -> Result>> { - self.retained_context(binding, context)?; - let Some(slot) = &self.router_scratch else { - return Ok(None); - }; - // This matrix is an actual immutable buffer created by this cache on - // the retained Context for this bound layer; no external view is used. - let matrix = self.router(binding, source.identity().layer().get())?; - let slot = slot.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; - RouterScratch::lease(slot, &self.binding, context, source, matrix).map(Some) - } - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(crate) fn test_router_witness(&self) -> Result { - self.router_scratch - .as_ref() - .ok_or(Error::IdentityMismatch)? - .try_borrow() - .map(|slot| slot.completed()) - .map_err(|_| Error::IdentityMismatch) - } - pub(in super::super) fn gr_scratch( - &self, - binding: &ModelBinding, - context: &Context<'_>, - ) -> Result>> { - self.retained_context(binding, context)?; - self.gr_scratch - .as_ref() - .ok_or(Error::IdentityMismatch)? - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch) - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in super::super) fn gr_batch_workspace( - &self, - binding: &ModelBinding, - context: &Context<'_>, - ) -> Result>>> { - let Some(slot) = &self.gr_batch_workspace else { - return Ok(None); - }; - self.retained_context(binding, context)?; - slot.try_borrow_mut() - .map(Some) - .map_err(|_| Error::IdentityMismatch) - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in super::super) fn ple_queue( - &self, - binding: &ModelBinding, - context: &Context<'_>, - ) -> Result>>> { - self.retained_context(binding, context)?; - self.ple_queue - .as_ref() - .map(|queue| queue.try_borrow_mut().map_err(|_| Error::IdentityMismatch)) - .transpose() - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in super::super) fn native_batch_workspace( - &self, - binding: &ModelBinding, - context: &Context<'_>, - ) -> Result>>> { - self.retained_context(binding, context)?; - self.native_batch_workspace - .as_ref() - .map(|slot| slot.try_borrow_mut().map_err(|_| Error::IdentityMismatch)) - .transpose() - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in super::super) fn ple_batch_queue( - &self, - binding: &ModelBinding, - context: &Context<'_>, - ) -> Result>>> { - self.retained_context(binding, context)?; - self.ple_batch_queue - .as_ref() - .map(|slot| slot.try_borrow_mut().map_err(|_| Error::IdentityMismatch)) - .transpose() - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in super::super) fn gdn_batch_resources( - &self, - binding: &ModelBinding, - context: &Context<'_>, - ) -> Result>>> { - self.retained_context(binding, context)?; - if self.mirror_failed.get() { - return Err(Error::CudaExecution); - } - self.gdn_batch_resources - .as_ref() - .map(|slot| slot.try_borrow_mut().map_err(|_| Error::IdentityMismatch)) - .transpose() - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in super::super) fn qsa_native_workspace( - &self, - binding: &ModelBinding, - context: &Context<'_>, - ) -> Result>>> { - self.retained_context(binding, context)?; - if self.mirror_failed.get() { - return Err(Error::CudaExecution); - } - self.qsa_native_workspace - .as_ref() - .map(|slot| slot.try_borrow_mut().map_err(|_| Error::IdentityMismatch)) - .transpose() - } - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in super::super) fn test_record_gr_batch_completed( - &self, - binding: &ModelBinding, - context: &Context<'_>, - ) -> Result<()> { - self.retained_context(binding, context)?; - if self.gr_batch_workspace.is_none() { - return Err(Error::IdentityMismatch); - } - let count = self - .gr_batch_completed - .get() - .checked_add(1) - .ok_or(Error::Overflow)?; - self.gr_batch_completed.set(count); - Ok(()) - } - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(crate) fn test_gr_batch_completions(&self) -> u64 { - self.gr_batch_completed.get() - } - pub(in super::super) fn has_gdn_qk_workspace(&self) -> bool { - self.gdn_qk_workspace.is_some() - } - pub(in super::super) fn gdn_qk_workspace( - &self, - binding: &ModelBinding, - context: &Context<'_>, - identity: super::super::contract::TokenLayer, - ) -> Result>> { - self.retained_context(binding, context)?; - let resident = self - .gdn - .get(identity.layer().get() as usize) - .and_then(Option::as_ref) - .ok_or(Error::InvalidLayer)?; - if !Rc::ptr_eq(&self.owner, &resident.owner) - || resident.weights.layer() != identity.layer().get() - || identity.layer().get() % 4 == 3 - { - return Err(Error::IdentityMismatch); - } - self.gdn_qk_workspace.clone().ok_or(Error::IdentityMismatch) - } - pub(in super::super) fn gdn_four_borrow( - &self, - binding: &ModelBinding, - context: &Context<'_>, - ) -> Result { - self.retained_context(binding, context)?; - Ok(self.gdn_four_borrow) - } - pub(in super::super) fn transport_failure_flag( - &self, - binding: &ModelBinding, - context: &Context<'_>, - ) -> Result>> { - self.retained_context(binding, context)?; - Ok(self.mirror_failed.clone()) - } - pub(in super::super) fn qsa_input<'slot, 'source>( - &'slot self, - binding: &ModelBinding, - layer: u32, - context: &Context<'_>, - source: &'source [f32], - ) -> Result> { - self.retained_context(binding, context)?; - let resident = self - .qsa - .get(layer as usize) - .and_then(Option::as_ref) - .ok_or(Error::InvalidLayer)?; - if !Rc::ptr_eq(&self.owner, &resident.owner) || resident.weights.layer() != layer { - return Err(Error::IdentityMismatch); - } - let slot = self - .qsa_input - .as_ref() - .ok_or(Error::IdentityMismatch)? - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch)?; - QsaInputScratch::lease(slot, &self.binding, context, layer, source) - } - pub(in super::super) fn has_qsa_selected(&self) -> bool { - self.qsa_selected.is_some() - } - pub(in super::super) fn qsa_selected( - &self, - binding: &ModelBinding, - layer: u32, - context: &Context<'_>, - ) -> Result>>> { - self.retained_context(binding, context)?; - let resident = self - .qsa - .get(layer as usize) - .and_then(Option::as_ref) - .ok_or(Error::InvalidLayer)?; - if !Rc::ptr_eq(&self.owner, &resident.owner) || resident.weights.layer() != layer { - return Err(Error::IdentityMismatch); - } - self.qsa_selected - .as_ref() - .map(|slot| slot.try_borrow_mut().map_err(|_| Error::IdentityMismatch)) - .transpose() - } - pub(in super::super) fn qsa_select( - &self, - binding: &ModelBinding, - context: &Context<'_>, - candidate: &QsaPrior, - iq: &[f32], - position: u32, - ) -> Result> { - self.retained_context(binding, context)?; - self.qsa_keys - .as_ref() - .ok_or(Error::IdentityMismatch)? - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch)? - .select(&self.binding, context, candidate, iq, position) - } - pub(in super::super) fn gdn_input<'slot, 'source>( - &'slot self, - binding: &ModelBinding, - layer: u32, - context: &Context<'_>, - source: &'source [f32], - ) -> Result> { - self.retained_context(binding, context)?; - let resident = self - .gdn - .get(layer as usize) - .and_then(Option::as_ref) - .ok_or(Error::InvalidLayer)?; - if !Rc::ptr_eq(&self.owner, &resident.owner) || resident.weights.layer() != layer { - return Err(Error::IdentityMismatch); - } - let slot = self - .gdn_input - .as_ref() - .ok_or(Error::IdentityMismatch)? - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch)?; - GdnInputScratch::lease(slot, &self.binding, context, layer, source) - } - pub(super) fn hit(&self) -> Result<()> { - let mut c = self.counters.get(); - c.hits = c.hits.checked_add(1).ok_or(Error::Overflow)?; - self.counters.set(c); - Ok(()) - } - pub(in super::super) fn gdn(&self, binding: &ModelBinding, layer: u32) -> Result<&GdnResident> { - self.check(binding)?; - self.hit()?; - self.gdn - .get(layer as usize) - .and_then(Option::as_ref) - .ok_or(Error::InvalidLayer) - } - pub(in super::super) fn gdn_mirror( - &self, - binding: &ModelBinding, - layer: u32, - context: &Context<'_>, - ) -> Result>> { - self.check(binding)?; - if !std::ptr::eq(self.context, context) { - return Err(Error::IdentityMismatch); - } - let resident = self - .gdn - .get(layer as usize) - .and_then(Option::as_ref) - .ok_or(Error::InvalidLayer)?; - if !Rc::ptr_eq(&self.owner, &resident.owner) || resident.weights.layer() != layer { - return Err(Error::IdentityMismatch); - } - self.gdn_mirrors - .get(layer as usize) - .and_then(Option::as_ref) - .ok_or(Error::InvalidLayer)? - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch) - } - pub(in super::super) fn qsa(&self, binding: &ModelBinding, layer: u32) -> Result<&QsaResident> { - self.check(binding)?; - self.hit()?; - self.qsa - .get(layer as usize) - .and_then(Option::as_ref) - .ok_or(Error::InvalidLayer) - } - pub(in super::super) fn gr(&self, binding: &ModelBinding, role: GrRole) -> Result<&GrResident> { - self.check(binding)?; - self.hit()?; - let index = match role { - GrRole::Attention(l) if l < 48 => l as usize * 2, - GrRole::Ffn(l) if l < 48 => l as usize * 2 + 1, - GrRole::Final => 96, - _ => return Err(Error::InvalidLayer), - }; - self.gr.get(index).ok_or(Error::InvalidLayer) - } - pub(in super::super) fn router(&self, binding: &ModelBinding, layer: u32) -> Result<&DeviceBuffer<'ctx>> { - self.check(binding)?; - self.hit()?; - let i = *self.router.get(layer as usize).ok_or(Error::InvalidLayer)?; - self.buffer(i) - } - pub(super) fn buffer(&self, index: usize) -> Result<&DeviceBuffer<'ctx>> { - self.buffers.get(index).map(|slice| &**slice).ok_or(Error::IdentityMismatch) - } - pub(in super::super) fn ple( - &self, - binding: &ModelBinding, - context: &Context<'_>, - ) -> Result<&PleResident> { - self.check(binding)?; - if !std::ptr::eq(self.context, context) { - return Err(Error::IdentityMismatch); - } - binding.validate_ple_sources().map_err(binding_error)?; - let entry = self.ple.as_ref().ok_or(Error::IdentityMismatch)?; - if !Rc::ptr_eq(&self.owner, &entry.owner) || !entry.weights.matches(&binding.identity()) { - return Err(Error::IdentityMismatch); - } - self.hit()?; - Ok(entry) - } - pub(in super::super) fn ple_key(&self, entry: &PleResident) -> Result<&DeviceBuffer<'ctx>> { - if !Rc::ptr_eq(&self.owner, &entry.owner) { - return Err(Error::IdentityMismatch); - } - let matrix = self.buffer(entry.key)?; - if matrix.len() != 52_428_800 { - return Err(Error::InvalidDimension); - } - Ok(matrix) - } - pub(in super::super) fn ple_value(&self, entry: &PleResident) -> Result<&DeviceBuffer<'ctx>> { - if !Rc::ptr_eq(&self.owner, &entry.owner) { - return Err(Error::IdentityMismatch); - } - let matrix = self.buffer(entry.value)?; - if matrix.len() != 13_107_200 { - return Err(Error::InvalidDimension); - } - Ok(matrix) - } - // The genuine legacy diagnostic helper cannot borrow a subrange from the - // complete resident matrix. Refuse rather than manufacture a buffer view. - pub(in super::super) fn ple_value_tile( - &self, - entry: &PleResident, - first: usize, - ) -> Result<&DeviceBuffer<'ctx>> { - if !Rc::ptr_eq(&self.owner, &entry.owner) || !first.is_multiple_of(64) { - return Err(Error::IdentityMismatch); - } - if first >= 2560 { - return Err(Error::InvalidDimension); - } - Err(Error::Unsupported(super::super::contract::Stage::Input)) - } - pub(in super::super) fn ple_aux(&self, entry: &PleResident) -> Result<[&DeviceBuffer<'ctx>; 4]> { - if !Rc::ptr_eq(&self.owner, &entry.owner) { - return Err(Error::IdentityMismatch); - } - Ok([ - self.buffer(entry.aux[0])?, - self.buffer(entry.aux[1])?, - self.buffer(entry.aux[2])?, - self.buffer(entry.aux[3])?, - ]) - } - pub(in super::super) fn gdn_matrix( - &self, - entry: &GdnResident, - role: GdnMatrixRole, - ) -> Result<(&DeviceBuffer<'ctx>, GdnMatrixKind)> { - if !Rc::ptr_eq(&self.owner, &entry.owner) { - return Err(Error::IdentityMismatch); - } - let i = match role { - GdnMatrixRole::Qkv => 0, - GdnMatrixRole::Z => 1, - GdnMatrixRole::Alpha => 2, - GdnMatrixRole::Beta => 3, - GdnMatrixRole::Out => 4, - }; - let (index, kind) = entry.matrices[i]; - Ok((self.buffer(index)?, kind)) - } - pub(in super::super) fn gdn_aux(&self, entry: &GdnResident) -> Result<[&DeviceBuffer<'ctx>; 4]> { - if !Rc::ptr_eq(&self.owner, &entry.owner) { - return Err(Error::IdentityMismatch); - } - Ok([ - self.buffer(entry.aux[0])?, - self.buffer(entry.aux[1])?, - self.buffer(entry.aux[2])?, - self.buffer(entry.aux[3])?, - ]) - } - /// Ordered, retained operands for the native verifier's thirty-six GDN - /// layers. These are the cache's actual allocations: no host-side weight - /// conversion or subrange projection is permitted at this boundary. - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in super::super) fn original_verify_gdn_weights<'a>( - &'a self, - binding: &ModelBinding, - ) -> Result<[OriginalVerifyGdnWeights<'a, 'ctx>; 36]> { - self.check(binding)?; - let mut retained = Vec::new(); - retained - .try_reserve_exact(36) - .map_err(|_| Error::InputAllocation)?; - for layer in binding.ordered_layers() { - if layer.kind() != BoundLayerKind::Gdn { - continue; - } - let resident = self.gdn(binding, layer.index())?; - let (alpha, alpha_kind) = self.gdn_matrix(resident, GdnMatrixRole::Alpha)?; - let (beta, beta_kind) = self.gdn_matrix(resident, GdnMatrixRole::Beta)?; - if alpha_kind != GdnMatrixKind::Bf16 || beta_kind != GdnMatrixKind::Bf16 { - return Err(Error::Unsupported(super::super::contract::Stage::Gdn)); - } - let aux = self.gdn_aux(resident)?; - retained.push(OriginalVerifyGdnWeights { - conv: aux[0], - alpha, - beta, - dt: aux[1], - a: aux[2], - norm: aux[3], - }); - } - retained.try_into().map_err(|_| Error::InvalidDimension) - } - /// The twelve QSA layers' indexer K norm gamma (128 F32 each), in layer order: the verifier's - /// indexer append re-normalizes each raw index key with exactly these cache allocations. - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in super::super) fn original_verify_qsa_gamma<'a>( - &'a self, - binding: &ModelBinding, - ) -> Result<[&'a DeviceBuffer<'ctx>; 12]> { - self.check(binding)?; - let mut gamma = Vec::new(); - gamma.try_reserve_exact(12).map_err(|_| Error::InputAllocation)?; - for layer in binding.ordered_layers() { - if layer.kind() != BoundLayerKind::Qsa { - continue; - } - let resident = self.qsa(binding, layer.index())?; - // norms: [q, k, index q, index k] - gamma.push(self.qsa_norms(resident)?[3]); - } - gamma.try_into().map_err(|_| Error::InvalidDimension) - } - /// The native-format (GGUF block) MMVQ projection matrices of the 36 GDN and 12 QSA - /// layers for the literal Verifier window: the cache's own allocations, borrowed. - /// A matrix the cache holds as BF16 has no native MMVQ owner and is refused. - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in super::super) fn original_verify_projections<'a>( - &'a self, - binding: &ModelBinding, - geometry: &OriginalVerifyGeometry, - ) -> Result> { - self.check(binding)?; - let gdn_type = |kind: GdnMatrixKind| -> Result { - match kind { - GdnMatrixKind::Q8_0 => Ok(8), - GdnMatrixKind::Q4K => Ok(12), - GdnMatrixKind::Q5K => Ok(13), - GdnMatrixKind::Q6K => Ok(14), - GdnMatrixKind::Iq4Nl => Ok(20), - GdnMatrixKind::Iq4Xs => Ok(23), - GdnMatrixKind::Bf16 => Err(Error::Unsupported(super::super::contract::Stage::Gdn)), - } - }; - let qsa_type = |kind: QsaMatrixKind| -> Result { - match kind { - QsaMatrixKind::Q4K => Ok(12), - QsaMatrixKind::Q5K => Ok(13), - QsaMatrixKind::Q6K => Ok(14), - QsaMatrixKind::Iq4Xs => Ok(23), - QsaMatrixKind::Bf16 => Err(Error::Unsupported(super::super::contract::Stage::QsaAttention)), - } - }; - let mut gdn = Vec::new(); - let mut qsa = Vec::new(); - gdn.try_reserve_exact(36).map_err(|_| Error::InputAllocation)?; - qsa.try_reserve_exact(12).map_err(|_| Error::InputAllocation)?; - for layer in binding.ordered_layers() { - match layer.kind() { - BoundLayerKind::Gdn => { - let resident = self.gdn(binding, layer.index())?; - let mut matrix = |role| -> Result> { - let (buffer, kind) = self.gdn_matrix(resident, role)?; - Ok(OriginalVerifyNativeMatrix { kind: gdn_type(kind)?, buffer }) - }; - gdn.push(OriginalVerifyGdnProjections { - qkv: matrix(GdnMatrixRole::Qkv)?, - gate: matrix(GdnMatrixRole::Z)?, - out: matrix(GdnMatrixRole::Out)?, - }); - } - BoundLayerKind::Qsa => { - let resident = self.qsa(binding, layer.index())?; - let mut matrix = |role| -> Result> { - let (buffer, kind) = self.qsa_matrix(resident, role)?; - Ok(OriginalVerifyNativeMatrix { kind: qsa_type(kind)?, buffer }) - }; - qsa.push(OriginalVerifyQsaProjections { - k: matrix(QsaMatrixRole::K)?, - v: matrix(QsaMatrixRole::V)?, - q: matrix(QsaMatrixRole::Q)?, - out: matrix(QsaMatrixRole::Out)?, - }); - } - } - } - OriginalVerifyProjBinding::new(self.context, geometry, gdn, qsa).map_err(driver_error) - } - pub(in super::super) fn qsa_matrix( - &self, - entry: &QsaResident, - role: QsaMatrixRole, - ) -> Result<(&DeviceBuffer<'ctx>, QsaMatrixKind)> { - if !Rc::ptr_eq(&self.owner, &entry.owner) { - return Err(Error::IdentityMismatch); - } - let i = match role { - QsaMatrixRole::Q => 0, - QsaMatrixRole::K => 1, - QsaMatrixRole::V => 2, - QsaMatrixRole::IndexQ => 3, - QsaMatrixRole::IndexK => 4, - QsaMatrixRole::Out => 5, - }; - let (index, kind) = entry.matrices[i]; - Ok((self.buffer(index)?, kind)) - } - pub(in super::super) fn qsa_norms(&self, entry: &QsaResident) -> Result<[&DeviceBuffer<'ctx>; 4]> { - if !Rc::ptr_eq(&self.owner, &entry.owner) { - return Err(Error::IdentityMismatch); - } - Ok([ - self.buffer(entry.norms[0])?, - self.buffer(entry.norms[1])?, - self.buffer(entry.norms[2])?, - self.buffer(entry.norms[3])?, - ]) - } - pub(in super::super) fn gr_buffers( - &self, - entry: &GrResident, - ) -> Result<[Option<&DeviceBuffer<'ctx>>; 4]> { - if !Rc::ptr_eq(&self.owner, &entry.owner) { - return Err(Error::IdentityMismatch); - } - Ok([ - entry.buffers[0].map(|i| self.buffer(i)).transpose()?, - entry.buffers[1].map(|i| self.buffer(i)).transpose()?, - entry.buffers[2].map(|i| self.buffer(i)).transpose()?, - entry.buffers[3].map(|i| self.buffer(i)).transpose()?, - ]) - } - pub(crate) fn counters(&self) -> DenseCacheCounters { - self.counters.get() - } - pub(in super::super) fn chunk_modules( - &self, - binding: &ModelBinding, - context: &Context<'_>, - ) -> Result<&super::super::chunk_modules::ChunkModules<'ctx>> { - self.retained_context(binding, context)?; - self.modules.as_ref().ok_or(Error::IdentityMismatch) - } - pub(crate) fn close(self) -> Result<()> { - let mut error = self.mirror_failed.get().then_some(Error::CudaExecution); - for guard in self.gdn_guards.take() { - if let Err(e) = guard.close() { - error.get_or_insert(driver_error(e)); - } - } - for buffer in self.gdn_scratch.take() { - if let Err(e) = buffer.release() { - error.get_or_insert(driver_error(e)); - } - } - if let Some(modules) = self.modules - && let Err(e) = modules.close() - { - error.get_or_insert(e); - } - if let Some(selected) = self.qsa_selected - && let Err(e) = selected.into_inner().close() - { - error.get_or_insert(e); - } - if let Some(keys) = self.qsa_keys - && let Err(e) = keys.into_inner().close() - { - error.get_or_insert(e); - } - if let Some(slot) = self.gdn_verification { - let result = Rc::try_unwrap(slot) - .map_err(|_| Error::IdentityMismatch) - .and_then(|slot| slot.into_inner().close()); - if let Err(failure) = result { - error.get_or_insert(failure); - } - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if let Some(owner) = self.native_gdn_fused { - let result = Rc::try_unwrap(owner) - .map_err(|_| Error::IdentityMismatch) - .and_then(|owner| owner.into_inner().close().map_err(driver_error)); - if let Err(failure) = result { - error.get_or_insert(failure); - } - } - if let Some(slot) = self.qsa_attention_workspace - && let Err(e) = slot.into_inner().close() - { - error.get_or_insert(e); - } - if let Some(slot) = self.qsa_input - && let Err(e) = slot.into_inner().close() - { - error.get_or_insert(e); - } - if let Some(slot) = self.gdn_qk_workspace - && let Err(e) = QkScratch::close(slot) - { - error.get_or_insert(e); - } - if let Some(slot) = self.gdn_input - && let Err(e) = slot.into_inner().close() - { - error.get_or_insert(e); - } - if let Some(slot) = self.gr_scratch - && let Err(e) = slot.into_inner().close() - { - error.get_or_insert(e); - } - if let Some(slot) = self.router_scratch - && let Err(e) = slot.into_inner().close() - { - error.get_or_insert(e); - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if let Some(slot) = self.gr_batch_workspace - && let Err(e) = slot.into_inner().close() - { - error.get_or_insert(driver_error(e)); - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if let Some(queue) = self.ple_queue - && let Err(e) = queue.into_inner().close() - { - error.get_or_insert(driver_error(e)); - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if let Some(queue) = self.ple_batch_queue - && let Err(e) = queue.into_inner().close() - { - error.get_or_insert(driver_error(e)); - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if let Some(resources) = self.gdn_batch_resources - && let Err(e) = resources.into_inner().close() - { - error.get_or_insert(e); - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if let Some(owner) = self.native_qsa - && let Err(e) = owner.into_inner().close() - { - error.get_or_insert(e); - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if let Some(owner) = self.qsa_native_workspace - && let Err(e) = owner.into_inner().close() - { - error.get_or_insert(driver_error(e)); - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if let Some(workspace) = self.native_batch_workspace - && let Err(e) = workspace.into_inner().close() - { - error.get_or_insert(driver_error(e)); - } - for mirror in self.gdn_mirrors.into_iter().flatten() { - if let Err(e) = mirror.into_inner().close() { - error.get_or_insert(e); - } - } - for b in self.buffers { - if let Err(e) = b.release() { - error.get_or_insert(driver_error(e)); - } - } - if let Some(slabs) = self.slabs - && let Err(e) = slabs.release() - { - error.get_or_insert(driver_error(e)); - } - error.map_or(Ok(()), Err) - } -} +mod impl_denseweightcache_2; +mod impl_denseweightcache_2_2; +mod impl_denseweightcache_3; +mod impl_denseweightcache_4; +mod impl_denseweightcache_5; +mod impl_denseweightcache_6; +mod impl_denseweightcache_7; diff --git a/crates/leleka-runtime/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_2.rs b/crates/leleka-runtime/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_2.rs new file mode 100644 index 00000000..61b2e492 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_2.rs @@ -0,0 +1,241 @@ +//! Moved out of the parent module by STRA-338: impl DenseWeightCache. + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> DenseWeightCache<'ctx> { + pub(crate) fn new(binding: &ModelBinding, context: &'ctx Context<'ctx>) -> Result { + Self::new_with_selected(binding, context, false) + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(crate) fn new_qsa_selected( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + ) -> Result { + Self::new_with_selected(binding, context, true) + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(crate) fn new_qsa_selected_router( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + ) -> Result { + let mut result = Self::new_qsa_selected(binding, context)?; + match RouterScratch::new( + result.binding.clone(), + context, + result.mirror_failed.clone(), + ) { + Ok(slot) => result.router_scratch = Some(RefCell::new(slot)), + Err(primary) => { + let _ = result.close(); + return Err(primary); + } + } + result.gdn_four_borrow = true; + Ok(result) + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(crate) fn new_qsa_selected_router_gr_batch( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + ) -> Result { + let mut result = Self::new_qsa_selected_router(binding, context)?; + match context.gr_batch_inject_workspace() { + Ok(slot) => result.gr_batch_workspace = Some(RefCell::new(slot)), + Err(error) => { + let primary = driver_error(error); + let _ = result.close(); + return Err(primary); + } + } + Ok(result) + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(crate) fn new_qsa_selected_router_gr_batch_qk( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + ) -> Result { + let mut result = Self::new_qsa_selected_router_gr_batch(binding, context)?; + match QkScratch::new( + result.binding.clone(), + context, + result.mirror_failed.clone(), + ) { + Ok(slot) => result.gdn_qk_workspace = Some(Rc::new(slot)), + Err(primary) => { + let _ = result.close(); + return Err(primary); + } + } + // Caller creates its real PrefixPlan/preload only AFTER this factory. + Ok(result) + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(crate) fn new_qsa_selected_router_gr_batch_qk_attention( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + ) -> Result { + Self::new_attention_capacity(binding,context,64) + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in super::super) fn new_attention_capacity(binding:&ModelBinding,context:&'ctx Context<'ctx>,capacity:usize)->Result { + if !(1..=8192).contains(&capacity) {return Err(Error::InvalidDimension);} + let mut result = Self::new_qsa_selected_router_gr_batch_qk(binding, context)?; + result.native_prompt_capacity=capacity; + match QsaAttentionScratch::new_experimental(binding, context, result.mirror_failed.clone()) + { + Ok(slot) => { + if slot.allocated_bytes() != super::super::super::qsa_attention::attention_scratch::SCRATCH_BYTES + { + let _ = slot.close(); + let _ = result.close(); + return Err(Error::InvalidDimension); + } + result.qsa_attention_workspace = Some(RefCell::new(slot)); + } + Err(primary) => { + let _ = result.close(); + return Err(primary); + } + } + // This selected actor eagerly owns the actual PLE queue before any + // expert cache budget is admitted. Default actors retain their path. + match context.ple_closed_queue() { + Ok(queue) => result.ple_queue = Some(RefCell::new(queue)), + Err(error) => { + let primary = driver_error(error); + let _ = result.close(); + return Err(primary); + } + } + // Literal prefill GEMM has one model-lifetime vendor handle, stream and + // actual 32 MiB workspace. Each producer releases its exclusive loan + // after completion; a row bank never carries it across attention. + match context.native_batch_workspace() { + Ok(workspace) => result.native_batch_workspace = Some(RefCell::new(workspace)), + Err(error) => { + let primary = driver_error(error); + let _ = result.close(); + return Err(primary); + } + } + // Original selected mode17 profile has STRATA_PREFILL_BF16X2 absent. + // HighOnly is explicit. Hi+Lo is a separately qualified load profile. + match if capacity==64 {context.ple_batch_queue(leleka_cuda_driver::PleBf16Mode::HighOnly)}else{context.ple_batch_queue_for_prompt(leleka_cuda_driver::PleBf16Mode::HighOnly,capacity)} { + Ok(queue) => result.ple_batch_queue = Some(RefCell::new(queue)), + Err(error) => { + let primary = driver_error(error); + let _ = result.close(); + return Err(primary); + } + } + match if capacity==64 {super::super::super::gdn::prefill_batch::GdnBatchResources::new(context,super::super::super::gdn::prefill_batch::Bf16Profile::HighOnly)}else{super::super::super::gdn::prefill_batch::GdnBatchResources::new_for_prompt(context,super::super::super::gdn::prefill_batch::Bf16Profile::HighOnly,capacity)} { + Ok(resources) => result.gdn_batch_resources = Some(RefCell::new(resources)), + Err(primary) => { + let _ = result.close(); + return Err(primary); + } + } + match if capacity==64 {context.qsa_native_batch_workspace(leleka_cuda_driver::QsaNativePacking::HighOnly)}else{context.qsa_native_batch_workspace_for_prompt(leleka_cuda_driver::QsaNativePacking::HighOnly,capacity)} { + Ok(owner) => result.qsa_native_workspace = Some(RefCell::new(owner)), + Err(error) => { + let primary = driver_error(error); + let _ = result.close(); + return Err(primary); + } + } + match if capacity==64 {super::super::super::qsa_native_resources::NativeQsaResources::new(context,result.mirror_failed.clone())}else{super::super::super::qsa_native_resources::NativeQsaResources::new_for_prompt(context,result.mirror_failed.clone(),capacity)} { + Ok(owner) => result.native_qsa = Some(RefCell::new(owner)), + Err(primary) => { + let _ = result.close(); + return Err(primary); + } + } + // The selected native target and verification journal share one actual + // closed fused program owner, charged before any routed PrefixPlan. + match context.gdn_fused_t1() { + Ok(owner) => result.native_gdn_fused = Some(Rc::new(RefCell::new(owner))), + Err(error) => { + let primary = driver_error(error); + let _ = result.close(); + return Err(primary); + } + } + // Actual scratch, mapped/canonical KV ledger and exact64 banks are eager before routed PrefixPlan. + Ok(result) + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in super::super::super) fn native_qsa( + &self, + binding: &ModelBinding, + context: &Context<'_>, + ) -> Result>> { + self.retained_context(binding, context)?; + let resource = self.native_qsa.as_ref().ok_or(Error::IdentityMismatch)?; + let owner = resource + .try_borrow_mut() + .map_err(|_| Error::IdentityMismatch)?; + owner.validate(context)?; + Ok(owner) + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in super::super::super) fn has_native_qsa(&self) -> bool { + self.native_qsa.is_some() + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in crate::qwen_forward) fn native_gdn_fused( + &self, + binding: &ModelBinding, + context: &Context<'_>, + ) -> Result>>> { + self.retained_context(binding, context)?; + let owner = self.native_gdn_fused.as_ref().ok_or(Error::IdentityMismatch)?; + if owner.try_borrow().map_err(|_| Error::IdentityMismatch)?.is_failed() { + self.mirror_failed.set(true); + return Err(Error::CudaExecution); + } + Ok(owner.clone()) + } + pub(in super::super::super) fn qsa_attention_workspace(&self) -> Option<&RefCell>> { + self.qsa_attention_workspace.as_ref() + } + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(crate) fn test_retained_scratch_witness(&self) -> Result<(usize, u64)> { + let qk = self + .gdn_qk_workspace + .as_ref() + .ok_or(Error::IdentityMismatch)? + .test_slot_bytes()?; + let qsa = self + .qsa_attention_workspace + .as_ref() + .ok_or(Error::IdentityMismatch)? + .try_borrow() + .map_err(|_| Error::IdentityMismatch)?; + Ok(( + qk.checked_add(qsa.allocated_bytes()) + .ok_or(Error::Overflow)?, + qsa.completed_rows(), + )) + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(crate) fn new_qsa_selected_router_gr_batch_qk_attention_mtp_journal( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + ) -> Result { + let mut cache = Self::new_qsa_selected_router_gr_batch_qk_attention(binding, context)?; + match super::super::super::gdn::verification::Workspace::new( + cache.binding.clone(), + context, + cache.mirror_failed.clone(), + ) { + Ok(workspace) => cache.gdn_verification = Some(Rc::new(RefCell::new(workspace))), + Err(primary) => { + let _ = cache.close(); + return Err(primary); + } + } + Ok(cache) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_2_2.rs b/crates/leleka-runtime/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_2_2.rs new file mode 100644 index 00000000..b131f930 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_2_2.rs @@ -0,0 +1,122 @@ +//! Moved out of the parent module by STRA-338: impl DenseWeightCache (2). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> DenseWeightCache<'ctx> { + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(crate) fn new_original_prompt_capacity(binding:&ModelBinding,context:&'ctx Context<'ctx>,capacity:usize)->Result { + if !(1..=8192).contains(&capacity){return Err(Error::InvalidDimension);} + // Actual weights and scalar/decode state remain model-lifetime owners. + // Prompt payloads live in the Original aliased arena, so this factory + // never allocates the legacy capacity-sized PLE/GDN/QSA row banks. + let mut cache=startup_step("new_with_selected",Self::new_with_selected(binding,context,false))?; + cache.native_prompt_capacity=capacity; + let loaded=(||->Result<()>{ + cache.native_batch_workspace=Some(RefCell::new(startup_step("native_batch_workspace",context.native_batch_workspace()).map_err(driver_error)?)); + cache.ple_queue=Some(RefCell::new(startup_step("ple_closed_queue",context.ple_closed_queue()).map_err(driver_error)?)); + cache.native_gdn_fused=Some(Rc::new(RefCell::new(startup_step("gdn_fused_t1",context.gdn_fused_t1()).map_err(driver_error)?))); + cache.gdn_verification=Some(Rc::new(RefCell::new(startup_step("gdn verification workspace",super::super::super::gdn::verification::Workspace::new( + cache.binding.clone(),context,cache.mirror_failed.clone()))?))); + cache.gdn_qk_workspace=Some(Rc::new(startup_step("gdn qk scratch",QkScratch::new(cache.binding.clone(),context,cache.mirror_failed.clone()))?)); + cache.router_scratch=Some(RefCell::new(startup_step("router scratch",RouterScratch::new(cache.binding.clone(),context,cache.mirror_failed.clone()))?)); + cache.gr_batch_workspace=Some(RefCell::new(startup_step("gr_batch_inject_workspace",context.gr_batch_inject_workspace()).map_err(driver_error)?)); + cache.gdn_four_borrow=true; + startup_step("validate",cache.validate(binding)) + })(); + if loaded.is_ok() && let Some(slabs) = cache.slabs.as_ref() { + let stats = slabs.stats(); + eprintln!( + "leleka-serve dense weights: {} buffers; {} slabs of {} MiB hold {} of them ({:.1} MiB), {} buffers above {} MiB keep their own allocation ({:.1} MiB driver-estimated)", + cache.buffers.len(), stats.slabs, SlabPolicy::DENSE.slab_bytes >> 20, stats.carved, stats.carved_bytes as f64 / 1048576.0, + stats.direct, SlabPolicy::DENSE.direct_above >> 20, stats.direct_bytes as f64 / 1048576.0, + ); + } + match loaded{Ok(())=>Ok(cache),Err(primary)=>{let _=cache.close();Err(primary)}} + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in crate::qwen_forward) fn native_prompt_capacity(&self,binding:&ModelBinding,context:&Context<'_>)->Result { + self.retained_context(binding,context)?; + if self.native_batch_workspace.is_none()||!(1..=8192).contains(&self.native_prompt_capacity) {return Err(Error::IdentityMismatch);} + Ok(self.native_prompt_capacity) + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in crate::qwen_forward) fn native_prompt_transient_device_bytes(&self,binding:&ModelBinding,context:&Context<'_>)->Result { + let capacity=self.native_prompt_capacity(binding,context)?; + let gr=leleka_cuda_driver::GrNativeBatch::prompt_device_bytes(capacity).map_err(driver_error)?; + let qsa=leleka_cuda_driver::QsaPromptIndexWorkspace::prompt_output_bytes(capacity).map_err(driver_error)?; + gr.checked_add(qsa).ok_or(Error::Overflow) + } + /// An idle GDN next-state finite guard of this cache's Context, or a new one. + pub(in crate::qwen_forward) fn take_gdn_guard( + &self, + binding: &ModelBinding, + context: &Context<'_>, + ) -> Result> { + let context = self.retained_context(binding, context)?; + let idle = self.gdn_guards.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.pop(); + match idle { + Some(guard) if !guard.is_failed() => Ok(guard), + Some(guard) => { + let _ = guard.close(); + context.gdn_state_finite_guard().map_err(driver_error) + } + None => context.gdn_state_finite_guard().map_err(driver_error), + } + } + /// A 3.1 MB GDN state buffer: an idle pooled one when `LELEKA_PREFILL_GDN_POOL` is on, else a fresh allocation. Contents are never assumed. + pub(in crate::qwen_forward) fn take_gdn_scratch(&self, context: &'ctx Context<'ctx>, bytes: usize) -> Result> { + if super::super::super::gdn::pool_enabled() { + let idle = self.gdn_scratch.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.pop(); + if let Some(buffer) = idle { + if buffer.len() == bytes { + return Ok(buffer); + } + buffer.release().map_err(driver_error)?; + } + } + context.allocate(bytes).map_err(driver_error) + } + /// Give a GDN state buffer back: pooled (at most 4) when the switch is on, else released as before. + pub(in crate::qwen_forward) fn return_gdn_scratch(&self, buffer: DeviceBuffer<'ctx>) -> Result<()> { + if super::super::super::gdn::pool_enabled() { + let mut idle = self.gdn_scratch.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; + if idle.len() < 4 { + idle.push(buffer); + return Ok(()); + } + } + buffer.release().map_err(driver_error) + } + /// Give a guard back after a clean use; a failed one is closed instead. + pub(in crate::qwen_forward) fn return_gdn_guard( + &self, + guard: leleka_cuda_driver::GdnStateFiniteGuard<'ctx>, + ) -> Result<()> { + if guard.is_failed() { + return guard.close().map_err(driver_error); + } + let mut idle = self.gdn_guards.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; + if idle.len() >= 4 { + drop(idle); + return guard.close().map_err(driver_error); + } + idle.push(guard); + Ok(()) + } + pub(in crate::qwen_forward) fn has_gdn_verification_workspace(&self) -> bool { + self.gdn_verification.is_some() + } + pub(in crate::qwen_forward) fn gdn_verification_workspace( + &self, + binding: &ModelBinding, + context: &Context<'_>, + ) -> Result>> { + self.retained_context(binding, context)?; + if self.mirror_failed.get() { + return Err(Error::CudaExecution); + } + Ok(self.gdn_verification.clone()) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_3.rs b/crates/leleka-runtime/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_3.rs new file mode 100644 index 00000000..44420f84 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_3.rs @@ -0,0 +1,248 @@ +//! Moved out of the parent module by STRA-338: impl DenseWeightCache (3). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> DenseWeightCache<'ctx> { + pub(in super::super) fn new_with_selected( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + selected: bool, + ) -> Result { + let n = usize::try_from(binding.layer_count()).map_err(|_| Error::Overflow)?; + if n != 48 { + return Err(Error::InvalidDimension); + } + let mut result = Self { + modules: None, + binding: binding.identity(), + owner: Rc::new(()), + context, + buffers: Vec::new(), + slabs: Some(SlabAllocator::new(context, dense_slab_policy()).map_err(driver_error)?), + gdn: Vec::new(), + gdn_mirrors: Vec::new(), + mirror_failed: Rc::new(Cell::new(false)), + gdn_four_borrow: false, + gdn_input: None, + gdn_qk_workspace: None, + qsa_attention_workspace: None, + gdn_verification: None, + gdn_guards: RefCell::new(Vec::new()), + gdn_scratch: RefCell::new(Vec::new()), + gr_scratch: None, + qsa_input: None, + qsa_keys: None, + qsa_selected: None, + router_scratch: None, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + gr_batch_workspace: None, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + ple_queue: None, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + native_prompt_capacity: 64, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + native_batch_workspace: None, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + ple_batch_queue: None, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + gdn_batch_resources: None, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + qsa_native_workspace: None, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + native_qsa: None, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + native_gdn_fused: None, + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + gr_batch_completed: Cell::new(0), + qsa: Vec::new(), + gr: Vec::new(), + router: Vec::new(), + ple: None, + counters: Cell::new(DenseCacheCounters::default()), + }; + result.modules = Some(super::super::super::chunk_modules::ChunkModules::new( + context, + result.mirror_failed.clone(), + )); + let loaded = (|| -> Result<()> { + // Optional fixed byte workspace is eagerly charged before lazy MoE growth. + if selected { + result.qsa_selected = Some(RefCell::new(QsaSelectedCache::new( + result.binding.clone(), + context, + result.mirror_failed.clone(), + )?)); + } + result.qsa_keys = Some(RefCell::new(QsaIndexKeyCache::new( + result.binding.clone(), + context, + result.mirror_failed.clone(), + )?)); + result.qsa_input = Some(RefCell::new(QsaInputScratch::new( + result.binding.clone(), + context, + result.mirror_failed.clone(), + )?)); + // Fixed activation scratch is charged before any lazy MoE growth. + result.gdn_input = Some(RefCell::new(GdnInputScratch::new( + result.binding.clone(), + context, + result.mirror_failed.clone(), + )?)); + result.gr_scratch = Some(RefCell::new(GrScratch::new( + binding, + context, + result.mirror_failed.clone(), + )?)); + result + .gdn + .try_reserve_exact(n) + .map_err(|_| Error::InputAllocation)?; + result + .gdn_mirrors + .try_reserve_exact(n) + .map_err(|_| Error::InputAllocation)?; + result + .qsa + .try_reserve_exact(n) + .map_err(|_| Error::InputAllocation)?; + result + .gr + .try_reserve_exact(n * 2 + 1) + .map_err(|_| Error::InputAllocation)?; + result + .router + .try_reserve_exact(n) + .map_err(|_| Error::InputAllocation)?; + for layer in binding.ordered_layers() { + let id = layer.index(); + let gdn = if layer.kind() == BoundLayerKind::Gdn { + let weights = Rc::new(binding.gdn_weights(id).map_err(binding_error)?); + let mut matrices = [(0, GdnMatrixKind::Bf16); 5]; + for (i, role) in [ + GdnMatrixRole::Qkv, + GdnMatrixRole::Z, + GdnMatrixRole::Alpha, + GdnMatrixRole::Beta, + GdnMatrixRole::Out, + ] + .into_iter() + .enumerate() + { + let block = binding + .gdn_matrix_block(&weights, role, 0, weights.shape(role).1) + .map_err(binding_error)?; + matrices[i] = ( + result.add( + block.bytes(), + weights.source_bytes(role).map_err(binding_error)?, + )?, + block.kind(), + ); + } + let aux = [ + result.add_f32(weights.conv())?, + result.add_f32(weights.dt())?, + result.add_f32(weights.a())?, + result.add_f32(weights.norm())?, + ]; + Some(GdnResident { + owner: result.owner.clone(), + weights, + matrices, + aux, + }) + } else { + None + }; + let qsa = if layer.kind() == BoundLayerKind::Qsa { + let weights = Rc::new(binding.qsa_weights(id).map_err(binding_error)?); + let mut matrices = [(0, QsaMatrixKind::Bf16); 6]; + for (i, role) in [ + QsaMatrixRole::Q, + QsaMatrixRole::K, + QsaMatrixRole::V, + QsaMatrixRole::IndexQ, + QsaMatrixRole::IndexK, + QsaMatrixRole::Out, + ] + .into_iter() + .enumerate() + { + let block = binding + .qsa_matrix_block(&weights, role, 0, weights.shape(role).1) + .map_err(binding_error)?; + matrices[i] = ( + result.add( + block.bytes(), + weights.source_bytes(role).map_err(binding_error)?, + )?, + block.kind(), + ); + } + let norms = [ + result.add_f32(weights.q_norm())?, + result.add_f32(weights.k_norm())?, + result.add_f32(weights.index_q_norm())?, + result.add_f32(weights.index_k_norm())?, + ]; + Some(QsaResident { + owner: result.owner.clone(), + weights, + matrices, + norms, + }) + } else { + None + }; + let mirror = gdn + .as_ref() + .map(|_| { + GdnStateMirror::new( + result.binding.clone(), + id, + context, + result.mirror_failed.clone(), + ) + }) + .transpose()? + .map(RefCell::new); + result.gdn.push(gdn); + result.gdn_mirrors.push(mirror); + result.qsa.push(qsa); + for role in [GrRole::Attention(id), GrRole::Ffn(id)] { + result.add_gr(binding, role)?; + } + let weights = binding.moe_route_weights(id).map_err(binding_error)?; + let block = binding + .moe_route_matrix_block(&weights, 0, 512) + .map_err(binding_error)?; + let index = result.add(block.bytes(), block.bytes().len())?; + result.router.push(index); + } + result.add_gr(binding, GrRole::Final)?; + result.add_ple(binding)?; + let mirror_count = result + .gdn_mirrors + .iter() + .filter(|entry| entry.is_some()) + .count(); + if mirror_count.checked_mul(786432 * 4) != Some(ALL_MIRROR_BYTES) { + return Err(Error::InvalidDimension); + } + result.validate(binding)?; + Ok(()) + })(); + match loaded { + Ok(()) => Ok(result), + Err(primary) => { + // A failed eager load publishes no cache. Explicitly attempt + // every owned release, preserving the original load refusal. + let _ = result.close(); + Err(primary) + } + } + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_4.rs b/crates/leleka-runtime/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_4.rs new file mode 100644 index 00000000..64937ea5 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_4.rs @@ -0,0 +1,251 @@ +//! Moved out of the parent module by STRA-338: impl DenseWeightCache (4). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> DenseWeightCache<'ctx> { + pub(in super::super) fn add(&mut self, bytes: &[u8], source_bytes: usize) -> Result { + if self + .context + .allocated_bytes() + .checked_add(bytes.len()) + .and_then(|n| n.checked_add(RESERVE)) + .is_none_or(|n| n > self.context.budget_bytes()) + { + return Err(Error::InputAllocation); + } + self.buffers + .try_reserve(1) + .map_err(|_| Error::InputAllocation)?; + let mut b = self.slabs.as_mut().ok_or(Error::IdentityMismatch)?.allocate(bytes.len()).map_err(driver_error)?; + if let Err(error) = b.copy_from(bytes) { + let primary = driver_error(error); + let _ = b.release(); + return Err(primary); + } + let index = self.buffers.len(); + self.buffers.push(b); + let mut c = self.counters.get(); + c.matrices = c.matrices.checked_add(1).ok_or(Error::Overflow)?; + c.read_bytes = c + .read_bytes + .checked_add(source_bytes as u64) + .ok_or(Error::Overflow)?; + c.upload_bytes = c + .upload_bytes + .checked_add(bytes.len() as u64) + .ok_or(Error::Overflow)?; + self.counters.set(c); + Ok(index) + } + pub(in super::super) fn add_f32(&mut self, values: &[f32]) -> Result { + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(values.len().checked_mul(4).ok_or(Error::Overflow)?) + .map_err(|_| Error::InputAllocation)?; + for v in values { + if !v.is_finite() { + return Err(Error::NonFinite); + } + bytes.extend_from_slice(&v.to_le_bytes()); + } + self.add(&bytes, bytes.len()) + } + pub(in super::super) fn add_bf16(&mut self, values: &[u16], source_bytes: usize) -> Result { + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(values.len().checked_mul(2).ok_or(Error::Overflow)?) + .map_err(|_| Error::InputAllocation)?; + for v in values { + if !f32::from_bits(u32::from(*v) << 16).is_finite() { + return Err(Error::NonFinite); + } + bytes.extend_from_slice(&v.to_le_bytes()); + } + self.add(&bytes, source_bytes) + } + pub(in super::super) fn add_gr(&mut self, binding: &ModelBinding, role: GrRole) -> Result<()> { + let weights = Rc::new(binding.gr_weights(role).map_err(binding_error)?); + let source_bytes = binding.gr_source_bytes(role).map_err(binding_error)?; + let buffers = [ + Some(self.add_f32(weights.norm())?), + Some(self.add_bf16(weights.down(), source_bytes[1])?), + Some(self.add_bf16(weights.up(), source_bytes[2])?), + weights + .inject() + .map(|v| self.add_bf16(v, source_bytes[3])) + .transpose()?, + ]; + self.gr.push(GrResident { + owner: self.owner.clone(), + weights, + buffers, + }); + Ok(()) + } + pub(in super::super) fn add_ple(&mut self, binding: &ModelBinding) -> Result<()> { + let weights = Rc::new(binding.ple_weights().map_err(binding_error)?); + // Key retains one complete immutable matrix with the same total byte + // charge as its former 160 tiles; per-row projection math is unchanged. + let key_matrix = binding + .ple_matrix_full(&weights, PleMatrixRole::Key) + .map_err(binding_error)?; + if key_matrix.rows() != 10240 || key_matrix.bytes().len() != 52_428_800 { + return Err(Error::InvalidDimension); + } + let key = self.add(key_matrix.bytes(), key_matrix.bytes().len())?; + drop(key_matrix); + // Value retains one whole immutable matrix; forty CTAs keep the original row arithmetic. + let value_matrix = binding + .ple_matrix_full(&weights, PleMatrixRole::Value) + .map_err(binding_error)?; + if value_matrix.rows() != 2560 || value_matrix.bytes().len() != 2560 * 2560 * 2 { + return Err(Error::InvalidDimension); + } + let value = self.add(value_matrix.bytes(), value_matrix.bytes().len())?; + drop(value_matrix); + let mut conv = Vec::new(); + conv.try_reserve_exact(weights.conv().len() * 2) + .map_err(|_| Error::InputAllocation)?; + for v in weights.conv() { + if !leleka_quant_core::f16_bits_to_f32(*v).is_finite() { + return Err(Error::NonFinite); + } + conv.extend_from_slice(&v.to_le_bytes()); + } + let aux = [ + self.add_f32(weights.norm_key())?, + self.add_f32(weights.norm_query())?, + self.add_f32(weights.norm_conv())?, + self.add(&conv, conv.len())?, + ]; + self.ple = Some(PleResident { + owner: self.owner.clone(), + weights, + key, + value, + aux, + }); + Ok(()) + } + pub(in super::super::super) fn validate(&self, binding: &ModelBinding) -> Result<()> { + self.check(binding)?; + binding.validate_dense_sources().map_err(binding_error)?; + binding.validate_ple_sources().map_err(binding_error) + } + pub(in super::super) fn check(&self, binding: &ModelBinding) -> Result<()> { + if !self.binding.matches(&binding.identity()) { + return Err(Error::IdentityMismatch); + } + if self.mirror_failed.get() { + #[cfg(test)] + eprintln!( + "PUBLIC CUDA stage=dense-cache-fence shared_failed=true context_poisoned={} allocated={} budget={}", + self.context.is_poisoned(), + self.context.allocated_bytes(), + self.context.budget_bytes() + ); + return Err(Error::CudaExecution); + } + Ok(()) + } + pub(in super::super::super) fn retained_context( + &self, + binding: &ModelBinding, + context: &Context<'_>, + ) -> Result<&'ctx Context<'ctx>> { + self.check(binding)?; + if !std::ptr::eq(self.context, context) { + return Err(Error::IdentityMismatch); + } + Ok(self.context) + } + pub(in super::super::super) fn router_scratch<'loan>( + &'loan self, + binding: &ModelBinding, + context: &Context<'_>, + source: &'loan super::super::super::gr::ResidualReady, + ) -> Result>> { + self.retained_context(binding, context)?; + let Some(slot) = &self.router_scratch else { + return Ok(None); + }; + // This matrix is an actual immutable buffer created by this cache on + // the retained Context for this bound layer; no external view is used. + let matrix = self.router(binding, source.identity().layer().get())?; + let slot = slot.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; + RouterScratch::lease(slot, &self.binding, context, source, matrix).map(Some) + } + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(crate) fn test_router_witness(&self) -> Result { + self.router_scratch + .as_ref() + .ok_or(Error::IdentityMismatch)? + .try_borrow() + .map(|slot| slot.completed()) + .map_err(|_| Error::IdentityMismatch) + } + pub(in super::super::super) fn gr_scratch( + &self, + binding: &ModelBinding, + context: &Context<'_>, + ) -> Result>> { + self.retained_context(binding, context)?; + self.gr_scratch + .as_ref() + .ok_or(Error::IdentityMismatch)? + .try_borrow_mut() + .map_err(|_| Error::IdentityMismatch) + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in super::super::super) fn gr_batch_workspace( + &self, + binding: &ModelBinding, + context: &Context<'_>, + ) -> Result>>> { + let Some(slot) = &self.gr_batch_workspace else { + return Ok(None); + }; + self.retained_context(binding, context)?; + slot.try_borrow_mut() + .map(Some) + .map_err(|_| Error::IdentityMismatch) + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in super::super::super) fn ple_queue( + &self, + binding: &ModelBinding, + context: &Context<'_>, + ) -> Result>>> { + self.retained_context(binding, context)?; + self.ple_queue + .as_ref() + .map(|queue| queue.try_borrow_mut().map_err(|_| Error::IdentityMismatch)) + .transpose() + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in super::super::super) fn native_batch_workspace( + &self, + binding: &ModelBinding, + context: &Context<'_>, + ) -> Result>>> { + self.retained_context(binding, context)?; + self.native_batch_workspace + .as_ref() + .map(|slot| slot.try_borrow_mut().map_err(|_| Error::IdentityMismatch)) + .transpose() + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in super::super::super) fn ple_batch_queue( + &self, + binding: &ModelBinding, + context: &Context<'_>, + ) -> Result>>> { + self.retained_context(binding, context)?; + self.ple_batch_queue + .as_ref() + .map(|slot| slot.try_borrow_mut().map_err(|_| Error::IdentityMismatch)) + .transpose() + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_5.rs b/crates/leleka-runtime/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_5.rs new file mode 100644 index 00000000..646866d7 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_5.rs @@ -0,0 +1,253 @@ +//! Moved out of the parent module by STRA-338: impl DenseWeightCache (5). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> DenseWeightCache<'ctx> { + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in super::super::super) fn gdn_batch_resources( + &self, + binding: &ModelBinding, + context: &Context<'_>, + ) -> Result>>> { + self.retained_context(binding, context)?; + if self.mirror_failed.get() { + return Err(Error::CudaExecution); + } + self.gdn_batch_resources + .as_ref() + .map(|slot| slot.try_borrow_mut().map_err(|_| Error::IdentityMismatch)) + .transpose() + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in super::super::super) fn qsa_native_workspace( + &self, + binding: &ModelBinding, + context: &Context<'_>, + ) -> Result>>> { + self.retained_context(binding, context)?; + if self.mirror_failed.get() { + return Err(Error::CudaExecution); + } + self.qsa_native_workspace + .as_ref() + .map(|slot| slot.try_borrow_mut().map_err(|_| Error::IdentityMismatch)) + .transpose() + } + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in super::super::super) fn test_record_gr_batch_completed( + &self, + binding: &ModelBinding, + context: &Context<'_>, + ) -> Result<()> { + self.retained_context(binding, context)?; + if self.gr_batch_workspace.is_none() { + return Err(Error::IdentityMismatch); + } + let count = self + .gr_batch_completed + .get() + .checked_add(1) + .ok_or(Error::Overflow)?; + self.gr_batch_completed.set(count); + Ok(()) + } + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(crate) fn test_gr_batch_completions(&self) -> u64 { + self.gr_batch_completed.get() + } + pub(in super::super::super) fn has_gdn_qk_workspace(&self) -> bool { + self.gdn_qk_workspace.is_some() + } + pub(in super::super::super) fn gdn_qk_workspace( + &self, + binding: &ModelBinding, + context: &Context<'_>, + identity: super::super::super::contract::TokenLayer, + ) -> Result>> { + self.retained_context(binding, context)?; + let resident = self + .gdn + .get(identity.layer().get() as usize) + .and_then(Option::as_ref) + .ok_or(Error::InvalidLayer)?; + if !Rc::ptr_eq(&self.owner, &resident.owner) + || resident.weights.layer() != identity.layer().get() + || identity.layer().get() % 4 == 3 + { + return Err(Error::IdentityMismatch); + } + self.gdn_qk_workspace.clone().ok_or(Error::IdentityMismatch) + } + pub(in super::super::super) fn gdn_four_borrow( + &self, + binding: &ModelBinding, + context: &Context<'_>, + ) -> Result { + self.retained_context(binding, context)?; + Ok(self.gdn_four_borrow) + } + pub(in super::super::super) fn transport_failure_flag( + &self, + binding: &ModelBinding, + context: &Context<'_>, + ) -> Result>> { + self.retained_context(binding, context)?; + Ok(self.mirror_failed.clone()) + } + pub(in super::super::super) fn qsa_input<'slot, 'source>( + &'slot self, + binding: &ModelBinding, + layer: u32, + context: &Context<'_>, + source: &'source [f32], + ) -> Result> { + self.retained_context(binding, context)?; + let resident = self + .qsa + .get(layer as usize) + .and_then(Option::as_ref) + .ok_or(Error::InvalidLayer)?; + if !Rc::ptr_eq(&self.owner, &resident.owner) || resident.weights.layer() != layer { + return Err(Error::IdentityMismatch); + } + let slot = self + .qsa_input + .as_ref() + .ok_or(Error::IdentityMismatch)? + .try_borrow_mut() + .map_err(|_| Error::IdentityMismatch)?; + QsaInputScratch::lease(slot, &self.binding, context, layer, source) + } + pub(in super::super::super) fn has_qsa_selected(&self) -> bool { + self.qsa_selected.is_some() + } + pub(in super::super::super) fn qsa_selected( + &self, + binding: &ModelBinding, + layer: u32, + context: &Context<'_>, + ) -> Result>>> { + self.retained_context(binding, context)?; + let resident = self + .qsa + .get(layer as usize) + .and_then(Option::as_ref) + .ok_or(Error::InvalidLayer)?; + if !Rc::ptr_eq(&self.owner, &resident.owner) || resident.weights.layer() != layer { + return Err(Error::IdentityMismatch); + } + self.qsa_selected + .as_ref() + .map(|slot| slot.try_borrow_mut().map_err(|_| Error::IdentityMismatch)) + .transpose() + } + pub(in super::super::super) fn qsa_select( + &self, + binding: &ModelBinding, + context: &Context<'_>, + candidate: &QsaPrior, + iq: &[f32], + position: u32, + ) -> Result> { + self.retained_context(binding, context)?; + self.qsa_keys + .as_ref() + .ok_or(Error::IdentityMismatch)? + .try_borrow_mut() + .map_err(|_| Error::IdentityMismatch)? + .select(&self.binding, context, candidate, iq, position) + } + pub(in super::super::super) fn gdn_input<'slot, 'source>( + &'slot self, + binding: &ModelBinding, + layer: u32, + context: &Context<'_>, + source: &'source [f32], + ) -> Result> { + self.retained_context(binding, context)?; + let resident = self + .gdn + .get(layer as usize) + .and_then(Option::as_ref) + .ok_or(Error::InvalidLayer)?; + if !Rc::ptr_eq(&self.owner, &resident.owner) || resident.weights.layer() != layer { + return Err(Error::IdentityMismatch); + } + let slot = self + .gdn_input + .as_ref() + .ok_or(Error::IdentityMismatch)? + .try_borrow_mut() + .map_err(|_| Error::IdentityMismatch)?; + GdnInputScratch::lease(slot, &self.binding, context, layer, source) + } + pub(in super::super) fn hit(&self) -> Result<()> { + let mut c = self.counters.get(); + c.hits = c.hits.checked_add(1).ok_or(Error::Overflow)?; + self.counters.set(c); + Ok(()) + } + pub(in super::super::super) fn gdn(&self, binding: &ModelBinding, layer: u32) -> Result<&GdnResident> { + self.check(binding)?; + self.hit()?; + self.gdn + .get(layer as usize) + .and_then(Option::as_ref) + .ok_or(Error::InvalidLayer) + } + pub(in super::super::super) fn gdn_mirror( + &self, + binding: &ModelBinding, + layer: u32, + context: &Context<'_>, + ) -> Result>> { + self.check(binding)?; + if !std::ptr::eq(self.context, context) { + return Err(Error::IdentityMismatch); + } + let resident = self + .gdn + .get(layer as usize) + .and_then(Option::as_ref) + .ok_or(Error::InvalidLayer)?; + if !Rc::ptr_eq(&self.owner, &resident.owner) || resident.weights.layer() != layer { + return Err(Error::IdentityMismatch); + } + self.gdn_mirrors + .get(layer as usize) + .and_then(Option::as_ref) + .ok_or(Error::InvalidLayer)? + .try_borrow_mut() + .map_err(|_| Error::IdentityMismatch) + } + pub(in super::super::super) fn qsa(&self, binding: &ModelBinding, layer: u32) -> Result<&QsaResident> { + self.check(binding)?; + self.hit()?; + self.qsa + .get(layer as usize) + .and_then(Option::as_ref) + .ok_or(Error::InvalidLayer) + } + pub(in super::super::super) fn gr(&self, binding: &ModelBinding, role: GrRole) -> Result<&GrResident> { + self.check(binding)?; + self.hit()?; + let index = match role { + GrRole::Attention(l) if l < 48 => l as usize * 2, + GrRole::Ffn(l) if l < 48 => l as usize * 2 + 1, + GrRole::Final => 96, + _ => return Err(Error::InvalidLayer), + }; + self.gr.get(index).ok_or(Error::InvalidLayer) + } + pub(in super::super::super) fn router(&self, binding: &ModelBinding, layer: u32) -> Result<&DeviceBuffer<'ctx>> { + self.check(binding)?; + self.hit()?; + let i = *self.router.get(layer as usize).ok_or(Error::InvalidLayer)?; + self.buffer(i) + } + pub(in super::super) fn buffer(&self, index: usize) -> Result<&DeviceBuffer<'ctx>> { + self.buffers.get(index).map(|slice| &**slice).ok_or(Error::IdentityMismatch) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_6.rs b/crates/leleka-runtime/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_6.rs new file mode 100644 index 00000000..63b4ded2 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_6.rs @@ -0,0 +1,250 @@ +//! Moved out of the parent module by STRA-338: impl DenseWeightCache (6). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> DenseWeightCache<'ctx> { + pub(in super::super::super) fn ple( + &self, + binding: &ModelBinding, + context: &Context<'_>, + ) -> Result<&PleResident> { + self.check(binding)?; + if !std::ptr::eq(self.context, context) { + return Err(Error::IdentityMismatch); + } + binding.validate_ple_sources().map_err(binding_error)?; + let entry = self.ple.as_ref().ok_or(Error::IdentityMismatch)?; + if !Rc::ptr_eq(&self.owner, &entry.owner) || !entry.weights.matches(&binding.identity()) { + return Err(Error::IdentityMismatch); + } + self.hit()?; + Ok(entry) + } + pub(in super::super::super) fn ple_key(&self, entry: &PleResident) -> Result<&DeviceBuffer<'ctx>> { + if !Rc::ptr_eq(&self.owner, &entry.owner) { + return Err(Error::IdentityMismatch); + } + let matrix = self.buffer(entry.key)?; + if matrix.len() != 52_428_800 { + return Err(Error::InvalidDimension); + } + Ok(matrix) + } + pub(in super::super::super) fn ple_value(&self, entry: &PleResident) -> Result<&DeviceBuffer<'ctx>> { + if !Rc::ptr_eq(&self.owner, &entry.owner) { + return Err(Error::IdentityMismatch); + } + let matrix = self.buffer(entry.value)?; + if matrix.len() != 13_107_200 { + return Err(Error::InvalidDimension); + } + Ok(matrix) + } + // The genuine legacy diagnostic helper cannot borrow a subrange from the + // complete resident matrix. Refuse rather than manufacture a buffer view. + pub(in super::super::super) fn ple_value_tile( + &self, + entry: &PleResident, + first: usize, + ) -> Result<&DeviceBuffer<'ctx>> { + if !Rc::ptr_eq(&self.owner, &entry.owner) || !first.is_multiple_of(64) { + return Err(Error::IdentityMismatch); + } + if first >= 2560 { + return Err(Error::InvalidDimension); + } + Err(Error::Unsupported(super::super::super::contract::Stage::Input)) + } + pub(in super::super::super) fn ple_aux(&self, entry: &PleResident) -> Result<[&DeviceBuffer<'ctx>; 4]> { + if !Rc::ptr_eq(&self.owner, &entry.owner) { + return Err(Error::IdentityMismatch); + } + Ok([ + self.buffer(entry.aux[0])?, + self.buffer(entry.aux[1])?, + self.buffer(entry.aux[2])?, + self.buffer(entry.aux[3])?, + ]) + } + pub(in super::super::super) fn gdn_matrix( + &self, + entry: &GdnResident, + role: GdnMatrixRole, + ) -> Result<(&DeviceBuffer<'ctx>, GdnMatrixKind)> { + if !Rc::ptr_eq(&self.owner, &entry.owner) { + return Err(Error::IdentityMismatch); + } + let i = match role { + GdnMatrixRole::Qkv => 0, + GdnMatrixRole::Z => 1, + GdnMatrixRole::Alpha => 2, + GdnMatrixRole::Beta => 3, + GdnMatrixRole::Out => 4, + }; + let (index, kind) = entry.matrices[i]; + Ok((self.buffer(index)?, kind)) + } + pub(in super::super::super) fn gdn_aux(&self, entry: &GdnResident) -> Result<[&DeviceBuffer<'ctx>; 4]> { + if !Rc::ptr_eq(&self.owner, &entry.owner) { + return Err(Error::IdentityMismatch); + } + Ok([ + self.buffer(entry.aux[0])?, + self.buffer(entry.aux[1])?, + self.buffer(entry.aux[2])?, + self.buffer(entry.aux[3])?, + ]) + } + /// Ordered, retained operands for the native verifier's thirty-six GDN + /// layers. These are the cache's actual allocations: no host-side weight + /// conversion or subrange projection is permitted at this boundary. + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in super::super::super) fn original_verify_gdn_weights<'a>( + &'a self, + binding: &ModelBinding, + ) -> Result<[OriginalVerifyGdnWeights<'a, 'ctx>; 36]> { + self.check(binding)?; + let mut retained = Vec::new(); + retained + .try_reserve_exact(36) + .map_err(|_| Error::InputAllocation)?; + for layer in binding.ordered_layers() { + if layer.kind() != BoundLayerKind::Gdn { + continue; + } + let resident = self.gdn(binding, layer.index())?; + let (alpha, alpha_kind) = self.gdn_matrix(resident, GdnMatrixRole::Alpha)?; + let (beta, beta_kind) = self.gdn_matrix(resident, GdnMatrixRole::Beta)?; + if alpha_kind != GdnMatrixKind::Bf16 || beta_kind != GdnMatrixKind::Bf16 { + return Err(Error::Unsupported(super::super::super::contract::Stage::Gdn)); + } + let aux = self.gdn_aux(resident)?; + retained.push(OriginalVerifyGdnWeights { + conv: aux[0], + alpha, + beta, + dt: aux[1], + a: aux[2], + norm: aux[3], + }); + } + retained.try_into().map_err(|_| Error::InvalidDimension) + } + /// The twelve QSA layers' indexer K norm gamma (128 F32 each), in layer order: the verifier's + /// indexer append re-normalizes each raw index key with exactly these cache allocations. + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in super::super::super) fn original_verify_qsa_gamma<'a>( + &'a self, + binding: &ModelBinding, + ) -> Result<[&'a DeviceBuffer<'ctx>; 12]> { + self.check(binding)?; + let mut gamma = Vec::new(); + gamma.try_reserve_exact(12).map_err(|_| Error::InputAllocation)?; + for layer in binding.ordered_layers() { + if layer.kind() != BoundLayerKind::Qsa { + continue; + } + let resident = self.qsa(binding, layer.index())?; + // norms: [q, k, index q, index k] + gamma.push(self.qsa_norms(resident)?[3]); + } + gamma.try_into().map_err(|_| Error::InvalidDimension) + } + /// The native-format (GGUF block) MMVQ projection matrices of the 36 GDN and 12 QSA + /// layers for the literal Verifier window: the cache's own allocations, borrowed. + /// A matrix the cache holds as BF16 has no native MMVQ owner and is refused. + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in super::super::super) fn original_verify_projections<'a>( + &'a self, + binding: &ModelBinding, + geometry: &OriginalVerifyGeometry, + ) -> Result> { + self.check(binding)?; + let gdn_type = |kind: GdnMatrixKind| -> Result { + match kind { + GdnMatrixKind::Q8_0 => Ok(8), + GdnMatrixKind::Q4K => Ok(12), + GdnMatrixKind::Q5K => Ok(13), + GdnMatrixKind::Q6K => Ok(14), + GdnMatrixKind::Iq4Nl => Ok(20), + GdnMatrixKind::Iq4Xs => Ok(23), + GdnMatrixKind::Bf16 => Err(Error::Unsupported(super::super::super::contract::Stage::Gdn)), + } + }; + let qsa_type = |kind: QsaMatrixKind| -> Result { + match kind { + QsaMatrixKind::Q4K => Ok(12), + QsaMatrixKind::Q5K => Ok(13), + QsaMatrixKind::Q6K => Ok(14), + QsaMatrixKind::Iq4Xs => Ok(23), + QsaMatrixKind::Bf16 => Err(Error::Unsupported(super::super::super::contract::Stage::QsaAttention)), + } + }; + let mut gdn = Vec::new(); + let mut qsa = Vec::new(); + gdn.try_reserve_exact(36).map_err(|_| Error::InputAllocation)?; + qsa.try_reserve_exact(12).map_err(|_| Error::InputAllocation)?; + for layer in binding.ordered_layers() { + match layer.kind() { + BoundLayerKind::Gdn => { + let resident = self.gdn(binding, layer.index())?; + let mut matrix = |role| -> Result> { + let (buffer, kind) = self.gdn_matrix(resident, role)?; + Ok(OriginalVerifyNativeMatrix { kind: gdn_type(kind)?, buffer }) + }; + gdn.push(OriginalVerifyGdnProjections { + qkv: matrix(GdnMatrixRole::Qkv)?, + gate: matrix(GdnMatrixRole::Z)?, + out: matrix(GdnMatrixRole::Out)?, + }); + } + BoundLayerKind::Qsa => { + let resident = self.qsa(binding, layer.index())?; + let mut matrix = |role| -> Result> { + let (buffer, kind) = self.qsa_matrix(resident, role)?; + Ok(OriginalVerifyNativeMatrix { kind: qsa_type(kind)?, buffer }) + }; + qsa.push(OriginalVerifyQsaProjections { + k: matrix(QsaMatrixRole::K)?, + v: matrix(QsaMatrixRole::V)?, + q: matrix(QsaMatrixRole::Q)?, + out: matrix(QsaMatrixRole::Out)?, + }); + } + } + } + OriginalVerifyProjBinding::new(self.context, geometry, gdn, qsa).map_err(driver_error) + } + pub(in super::super::super) fn qsa_matrix( + &self, + entry: &QsaResident, + role: QsaMatrixRole, + ) -> Result<(&DeviceBuffer<'ctx>, QsaMatrixKind)> { + if !Rc::ptr_eq(&self.owner, &entry.owner) { + return Err(Error::IdentityMismatch); + } + let i = match role { + QsaMatrixRole::Q => 0, + QsaMatrixRole::K => 1, + QsaMatrixRole::V => 2, + QsaMatrixRole::IndexQ => 3, + QsaMatrixRole::IndexK => 4, + QsaMatrixRole::Out => 5, + }; + let (index, kind) = entry.matrices[i]; + Ok((self.buffer(index)?, kind)) + } + pub(in super::super::super) fn qsa_norms(&self, entry: &QsaResident) -> Result<[&DeviceBuffer<'ctx>; 4]> { + if !Rc::ptr_eq(&self.owner, &entry.owner) { + return Err(Error::IdentityMismatch); + } + Ok([ + self.buffer(entry.norms[0])?, + self.buffer(entry.norms[1])?, + self.buffer(entry.norms[2])?, + self.buffer(entry.norms[3])?, + ]) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_7.rs b/crates/leleka-runtime/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_7.rs new file mode 100644 index 00000000..2547fb3f --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_7.rs @@ -0,0 +1,166 @@ +//! Moved out of the parent module by STRA-338: impl DenseWeightCache (7). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> DenseWeightCache<'ctx> { + pub(in super::super::super) fn gr_buffers( + &self, + entry: &GrResident, + ) -> Result<[Option<&DeviceBuffer<'ctx>>; 4]> { + if !Rc::ptr_eq(&self.owner, &entry.owner) { + return Err(Error::IdentityMismatch); + } + Ok([ + entry.buffers[0].map(|i| self.buffer(i)).transpose()?, + entry.buffers[1].map(|i| self.buffer(i)).transpose()?, + entry.buffers[2].map(|i| self.buffer(i)).transpose()?, + entry.buffers[3].map(|i| self.buffer(i)).transpose()?, + ]) + } + pub(crate) fn counters(&self) -> DenseCacheCounters { + self.counters.get() + } + pub(in super::super::super) fn chunk_modules( + &self, + binding: &ModelBinding, + context: &Context<'_>, + ) -> Result<&super::super::super::chunk_modules::ChunkModules<'ctx>> { + self.retained_context(binding, context)?; + self.modules.as_ref().ok_or(Error::IdentityMismatch) + } + pub(crate) fn close(self) -> Result<()> { + let mut error = self.mirror_failed.get().then_some(Error::CudaExecution); + for guard in self.gdn_guards.take() { + if let Err(e) = guard.close() { + error.get_or_insert(driver_error(e)); + } + } + for buffer in self.gdn_scratch.take() { + if let Err(e) = buffer.release() { + error.get_or_insert(driver_error(e)); + } + } + if let Some(modules) = self.modules + && let Err(e) = modules.close() + { + error.get_or_insert(e); + } + if let Some(selected) = self.qsa_selected + && let Err(e) = selected.into_inner().close() + { + error.get_or_insert(e); + } + if let Some(keys) = self.qsa_keys + && let Err(e) = keys.into_inner().close() + { + error.get_or_insert(e); + } + if let Some(slot) = self.gdn_verification { + let result = Rc::try_unwrap(slot) + .map_err(|_| Error::IdentityMismatch) + .and_then(|slot| slot.into_inner().close()); + if let Err(failure) = result { + error.get_or_insert(failure); + } + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(owner) = self.native_gdn_fused { + let result = Rc::try_unwrap(owner) + .map_err(|_| Error::IdentityMismatch) + .and_then(|owner| owner.into_inner().close().map_err(driver_error)); + if let Err(failure) = result { + error.get_or_insert(failure); + } + } + if let Some(slot) = self.qsa_attention_workspace + && let Err(e) = slot.into_inner().close() + { + error.get_or_insert(e); + } + if let Some(slot) = self.qsa_input + && let Err(e) = slot.into_inner().close() + { + error.get_or_insert(e); + } + if let Some(slot) = self.gdn_qk_workspace + && let Err(e) = QkScratch::close(slot) + { + error.get_or_insert(e); + } + if let Some(slot) = self.gdn_input + && let Err(e) = slot.into_inner().close() + { + error.get_or_insert(e); + } + if let Some(slot) = self.gr_scratch + && let Err(e) = slot.into_inner().close() + { + error.get_or_insert(e); + } + if let Some(slot) = self.router_scratch + && let Err(e) = slot.into_inner().close() + { + error.get_or_insert(e); + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(slot) = self.gr_batch_workspace + && let Err(e) = slot.into_inner().close() + { + error.get_or_insert(driver_error(e)); + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(queue) = self.ple_queue + && let Err(e) = queue.into_inner().close() + { + error.get_or_insert(driver_error(e)); + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(queue) = self.ple_batch_queue + && let Err(e) = queue.into_inner().close() + { + error.get_or_insert(driver_error(e)); + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(resources) = self.gdn_batch_resources + && let Err(e) = resources.into_inner().close() + { + error.get_or_insert(e); + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(owner) = self.native_qsa + && let Err(e) = owner.into_inner().close() + { + error.get_or_insert(e); + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(owner) = self.qsa_native_workspace + && let Err(e) = owner.into_inner().close() + { + error.get_or_insert(driver_error(e)); + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(workspace) = self.native_batch_workspace + && let Err(e) = workspace.into_inner().close() + { + error.get_or_insert(driver_error(e)); + } + for mirror in self.gdn_mirrors.into_iter().flatten() { + if let Err(e) = mirror.into_inner().close() { + error.get_or_insert(e); + } + } + for b in self.buffers { + if let Err(e) = b.release() { + error.get_or_insert(driver_error(e)); + } + } + if let Some(slabs) = self.slabs + && let Err(e) = slabs.release() + { + error.get_or_insert(driver_error(e)); + } + error.map_or(Ok(()), Err) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/executor/impl_qwenforward.rs b/crates/leleka-runtime/src/qwen_forward/executor/impl_qwenforward.rs index b5cb332d..1e13d656 100644 --- a/crates/leleka-runtime/src/qwen_forward/executor/impl_qwenforward.rs +++ b/crates/leleka-runtime/src/qwen_forward/executor/impl_qwenforward.rs @@ -3,510 +3,9 @@ #[allow(unused_imports)] use super::*; - -impl QwenForward { - pub(crate) fn step( - binding: &ModelBinding, - token: TokenId, - pos: Position, - session: &mut QwenSession<'_>, - ) -> Result { - Self::step_inner(binding, token, pos, session, None, None) - } - - /// Complete-forward entry retains the loaded output head across tokens. - /// Unsupported stages abort the same transaction without state publication. - pub(crate) fn step_with_output( - binding: &ModelBinding, - token: TokenId, - pos: Position, - session: &mut QwenSession<'_>, - output: &OutputStage<'_, '_>, - ) -> Result { - Self::step_inner(binding, token, pos, session, Some(output), None) - } - - /// Explicit loaded KAR provider. Cache lifetime is borrowed from the - /// caller's stable owner-thread Context; it is never self-referential. - pub(crate) fn step_with_kar_ple_output( - binding: &ModelBinding, - token: TokenId, - pos: Position, - session: &mut QwenSession<'_>, - output: &OutputStage<'_, '_>, - cache: &mut KarPleCache<'_>, - ) -> Result { - Self::step_inner(binding, token, pos, session, Some(output), Some(cache)) - } - - pub(super) fn step_inner( - binding: &ModelBinding, - token: TokenId, - pos: Position, - session: &mut QwenSession<'_>, - output: Option<&OutputStage<'_, '_>>, - kar_cache: Option<&mut KarPleCache<'_>>, - ) -> Result { - Self::step_core( - binding, token, pos, session, output, kar_cache, None, None, false, false, - ) - .and_then(|(predicted, _)| predicted.ok_or(Error::IdentityMismatch)) - } - - /// Retain the pre-output four-stream residual only for explicit MTP use. - /// Native/KAR callers above keep their original allocation and math path. - pub(crate) fn step_for_mtp( - binding: &ModelBinding, - token: TokenId, - pos: Position, - session: &mut QwenSession<'_>, - output: &OutputStage<'_, '_>, - kar_cache: Option<&mut KarPleCache<'_>>, - ) -> Result { - Self::step_for_mtp_cached(binding, token, pos, session, output, kar_cache, None, None) - } - #[allow(clippy::too_many_arguments)] - pub(crate) fn step_cached( - binding: &ModelBinding, - token: TokenId, - pos: Position, - session: &mut QwenSession<'_>, - output: &OutputStage<'_, '_>, - kar_cache: Option<&mut KarPleCache<'_>>, - moe_cache: &mut MoeWeightCache<'_>, - dense_cache: &DenseWeightCache<'_>, - ) -> Result { - Self::step_core( - binding, - token, - pos, - session, - Some(output), - kar_cache, - Some(moe_cache), - Some(dense_cache), - false, - false, - ) - .and_then(|(token, _)| token.ok_or(Error::IdentityMismatch)) - } - #[allow(clippy::too_many_arguments)] - pub(crate) fn step_for_mtp_cached( - binding: &ModelBinding, - token: TokenId, - pos: Position, - session: &mut QwenSession<'_>, - output: &OutputStage<'_, '_>, - kar_cache: Option<&mut KarPleCache<'_>>, - moe_cache: Option<&mut MoeWeightCache<'_>>, - dense_cache: Option<&DenseWeightCache<'_>>, - ) -> Result { - let (predicted, streams) = Self::step_core( - binding, - token, - pos, - session, - Some(output), - kar_cache, - moe_cache, - dense_cache, - true, - false, - )?; - Ok(TargetStepProduct { - binding: binding.identity(), - token, - position: pos, - predicted: predicted.ok_or(Error::IdentityMismatch)?, - streams: streams.ok_or(Error::IdentityMismatch)?, - origin: session.target_origin()?, - }) - } - - #[allow(clippy::too_many_arguments)] - pub(crate) fn prefill_for_mtp_cached( - binding: &ModelBinding, - token: TokenId, - pos: Position, - session: &mut QwenSession<'_>, - output: &OutputStage<'_, '_>, - kar_cache: Option<&mut KarPleCache<'_>>, - moe_cache: &mut MoeWeightCache<'_>, - dense_cache: &DenseWeightCache<'_>, - ) -> Result { - let (predicted, streams) = Self::step_core( - binding, - token, - pos, - session, - Some(output), - kar_cache, - Some(moe_cache), - Some(dense_cache), - true, - true, - )?; - if predicted.is_some() { - return Err(Error::IdentityMismatch); - } - Ok(PrefillStepProduct { - binding: binding.identity(), - token, - position: pos, - streams: streams.ok_or(Error::IdentityMismatch)?, - origin: session.target_origin()?, - }) - } - - #[allow(clippy::too_many_arguments)] - pub(super) fn step_core( - binding: &ModelBinding, - token: TokenId, - pos: Position, - session: &mut QwenSession<'_>, - output: Option<&OutputStage<'_, '_>>, - kar_cache: Option<&mut KarPleCache<'_>>, - mut moe_cache: Option<&mut MoeWeightCache<'_>>, - dense_cache: Option<&DenseWeightCache<'_>>, - capture_mtp: bool, - prefill_only: bool, - ) -> Result { - let mut streams = None; - let predicted = session.transact_completion(token, pos, &binding.identity(), |txn| { - // Validate the complete producer-bound descriptor sequence before - // touching any model rows or invoking a stage. - let layer_bound = validate_layer_plan(binding)?; - if let Some(cache) = dense_cache { - cache.validate(binding)?; - } - if let Some(cache) = moe_cache.as_deref_mut() { - let context = txn.cuda_context()?; - if dense_cache - .map(|dense| dense.gdn_four_borrow(binding, context)) - .transpose()? - .unwrap_or(false) - { - cache.reserve_mmq_transient(binding, context, super::super::gdn::FOUR_BORROW_BYTES)?; - } else { - cache.prepare_step(binding, txn.cuda_context()?)?; - } - } - - // A forward without its output head can never publish, so refuse - // before reading any row or running any layer. Everything above - // keeps its precedence; nothing has been staged yet. - let output = output.ok_or(Error::Unsupported(Stage::Output))?; - - let input = diagnose( - ForwardPhase::Input, - 0, - pos, - match (binding.kar_ple_binding(), kar_cache) { - (None, None) => InputStage::consume(binding, token, pos, txn), - (Some(_), Some(cache)) => { - InputStage::consume_kar(binding, cache, token, pos, txn) - } - // Never interpret a missing or wrong loaded provider as a - // request to switch modes or fall back to the native rows. - _ => Err(Error::IdentityMismatch), - }, - )?; - - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if super::super::oracle_capture::enabled() { - super::super::oracle_capture::stage_f32(-1, "input_residual", input.streams().values())?; - super::super::oracle_capture::stage_f32( - -1, - "embedding", - input - .streams() - .values() - .get(..2560) - .ok_or(Error::InvalidDimension)?, - )?; - } - txn.stage_input(input)?; - - let mut previous = None; - for descriptor in binding.ordered_layers() { - #[cfg(test)] - eprintln!("integration: starting layer {}", descriptor.index()); - let layer = LayerId::new(u64::from(descriptor.index()), layer_bound)?; - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if super::super::oracle_capture::enabled() { - super::super::oracle_capture::begin(pos.get(), layer.get() as i32)?; - } - - let mut residual = diagnose( - ForwardPhase::ReadAttention, - layer.get(), - pos, - read_layer_attention(binding, layer, previous.as_ref(), txn, dense_cache), - )?; - - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if super::super::oracle_capture::enabled() { - super::super::oracle_capture::stage_current( - "gr_attention_mixed", - residual.ready().mixed(), - )?; - super::super::oracle_capture::stage_current( - "gr_attention_inject", - residual.ready().oracle_inject(), - )?; - } - let injected_result = (|| { - let injected = match descriptor.kind() { - BoundLayerKind::Gdn => { - let prior = txn.gdn_prior(layer)?; - let mut attention = diagnose( - ForwardPhase::Gdn, - layer.get(), - pos, - GdnStage::step( - binding, - layer, - residual.ready(), - &prior, - txn, - dense_cache, - ), - )?; - attention.validate_origin(&binding.identity())?; - attention.identity().validate(token, pos, layer)?; - let pending = attention.take_pending()?; - txn.stage_gdn(&prior, pending)?; - - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if super::super::oracle_capture::enabled() { - super::super::oracle_capture::stage_current( - "attention_output", - attention.output(), - )?; - } - diagnose( - ForwardPhase::GrAttentionInject, - layer.get(), - pos, - GrStage::inject( - binding, - &mut residual, - attention.output(), - attention.identity(), - txn, - ), - )? - } - BoundLayerKind::Qsa => { - let attention = { - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let native = dense_cache - .filter(|cache| cache.has_native_qsa()) - .map(|cache| { - diagnose( - ForwardPhase::QsaAttention, - layer.get(), - pos, - QsaAttentionStage::decode_native( - binding, - layer, - residual.ready(), - txn, - cache, - ), - ) - }) - .transpose()?; - #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] - let native = None; - if let Some(completed) = native { - completed - } else { - let prior = txn.qsa_prior(layer)?; - let mut prepared = diagnose( - ForwardPhase::QsaIndex, - layer.get(), - pos, - QsaIndexStage::prepare( - binding, - layer, - residual.ready(), - pos, - &prior, - txn, - dense_cache, - ), - )?; - prepared.validate_origin(&binding.identity(), layer)?; - prepared.identity().validate(token, pos, layer)?; - let pending = prepared.take_pending()?; - txn.stage_qsa(&prior, pending)?; - let attention = diagnose( - ForwardPhase::QsaAttention, - layer.get(), - pos, - QsaAttentionStage::decode_with_scratch( - binding, - layer, - prepared, - txn, - dense_cache, - dense_cache.and_then( - DenseWeightCache::qsa_attention_workspace, - ), - ), - )?; - attention - } - }; - attention.validate_origin(&binding.identity(), layer)?; - attention.identity().validate(token, pos, layer)?; - - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if super::super::oracle_capture::enabled() { - super::super::oracle_capture::stage_current( - "attention_output", - attention.output(), - )?; - } - diagnose( - ForwardPhase::GrAttentionInject, - layer.get(), - pos, - GrStage::inject( - binding, - &mut residual, - attention.output(), - attention.identity(), - txn, - ), - )? - } - }; - Ok(injected) - })(); - let injected = residual.finish(injected_result)?; - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if super::super::oracle_capture::enabled() { - super::super::oracle_capture::stage_current( - "residual_after_attention", - injected.streams(), - )?; - } - - let mut ffn = diagnose( - ForwardPhase::GrFfn, - layer.get(), - pos, - GrStage::read_ffn(binding, layer, &injected, txn, dense_cache), - )?; - - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if super::super::oracle_capture::enabled() { - super::super::oracle_capture::stage_current("gr_ffn_mixed", ffn.ready().mixed())?; - super::super::oracle_capture::stage_current( - "gr_ffn_inject", - ffn.ready().oracle_inject(), - )?; - } - let completed_result = (|| { - let route = diagnose( - ForwardPhase::MoeRoute, - layer.get(), - pos, - MoeRouteStage::route_from_ffn( - binding, - layer, - ffn.ready(), - txn, - dense_cache, - ), - )?; - - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if super::super::oracle_capture::enabled() { - let ids = - std::array::from_fn::<_, 10, _>(|i| route.experts()[i].get() as i32); - let weights = std::array::from_fn::<_, 10, _>(|i| route.weights()[i].get()); - super::super::oracle_capture::stage_i32(layer.get() as i32, "router_ids", &ids)?; - super::super::oracle_capture::stage_current("router_weights", &weights)?; - } - let experts = diagnose( - ForwardPhase::MoeExpert, - layer.get(), - pos, - MoeExpertStage::execute( - binding, - layer, - route, - ffn.ready(), - txn, - moe_cache.as_deref_mut(), - ), - )?; - experts.validate_origin(&binding.identity())?; - experts.identity().validate(token, pos, layer)?; - - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if super::super::oracle_capture::enabled() { - super::super::oracle_capture::stage_current("combined_output", experts.output())?; - } - let completed = diagnose( - ForwardPhase::GrFfnInject, - layer.get(), - pos, - GrStage::inject( - binding, - &mut ffn, - experts.output(), - experts.identity(), - txn, - ), - )?; - Ok(completed) - })(); - let completed = ffn.finish(completed_result)?; - - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if super::super::oracle_capture::enabled() { - super::super::oracle_capture::stage_current( - "residual_after_moe", - completed.streams(), - )?; - } - txn.mark_layer_complete(&completed)?; - previous = Some(completed); - } - let final_residual = previous.as_ref().ok_or(Error::InvalidDimension)?; - let predicted = if prefill_only { - txn.finish_prefill(final_residual)?; - None - } else { - let logits = diagnose( - ForwardPhase::Output, - binding.layer_count().saturating_sub(1), - pos, - output.logits_cached(binding, final_residual, txn, dense_cache), - )?; - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - output.test_reset_replay_capture(&logits)?; - Some(txn.finish_forward(logits)?) - }; - if capture_mtp { - let mut owned = Vec::new(); - owned - .try_reserve_exact(10240) - .map_err(|_| Error::InputAllocation)?; - owned.extend_from_slice(final_residual.streams()); - streams = Some(owned.into_boxed_slice()); - } - Ok(predicted) - })?; - // A failed commit never exposes the local candidate to a draft caller. - Ok((predicted, streams)) - } - - pub(crate) fn reset(session: &mut QwenSession<'_>) -> Result<()> { - session.reset() - } -} +#[path = "impl_qwenforward/impl_qwenforward_2.rs"] +mod impl_qwenforward_2; +#[path = "impl_qwenforward/impl_qwenforward_2_2.rs"] +mod impl_qwenforward_2_2; +#[path = "impl_qwenforward/impl_qwenforward_3.rs"] +mod impl_qwenforward_3; diff --git a/crates/leleka-runtime/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_2.rs b/crates/leleka-runtime/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_2.rs new file mode 100644 index 00000000..7d5cd4a0 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_2.rs @@ -0,0 +1,161 @@ +//! Moved out of the parent module by STRA-338: impl QwenForward. + +#[allow(unused_imports)] +use super::*; + + + +impl QwenForward { + pub(crate) fn step( + binding: &ModelBinding, + token: TokenId, + pos: Position, + session: &mut QwenSession<'_>, + ) -> Result { + Self::step_inner(binding, token, pos, session, None, None) + } + + /// Complete-forward entry retains the loaded output head across tokens. + /// Unsupported stages abort the same transaction without state publication. + pub(crate) fn step_with_output( + binding: &ModelBinding, + token: TokenId, + pos: Position, + session: &mut QwenSession<'_>, + output: &OutputStage<'_, '_>, + ) -> Result { + Self::step_inner(binding, token, pos, session, Some(output), None) + } + + /// Explicit loaded KAR provider. Cache lifetime is borrowed from the + /// caller's stable owner-thread Context; it is never self-referential. + pub(crate) fn step_with_kar_ple_output( + binding: &ModelBinding, + token: TokenId, + pos: Position, + session: &mut QwenSession<'_>, + output: &OutputStage<'_, '_>, + cache: &mut KarPleCache<'_>, + ) -> Result { + Self::step_inner(binding, token, pos, session, Some(output), Some(cache)) + } + + pub(in super::super) fn step_inner( + binding: &ModelBinding, + token: TokenId, + pos: Position, + session: &mut QwenSession<'_>, + output: Option<&OutputStage<'_, '_>>, + kar_cache: Option<&mut KarPleCache<'_>>, + ) -> Result { + Self::step_core( + binding, token, pos, session, output, kar_cache, None, None, false, false, + ) + .and_then(|(predicted, _)| predicted.ok_or(Error::IdentityMismatch)) + } + + /// Retain the pre-output four-stream residual only for explicit MTP use. + /// Native/KAR callers above keep their original allocation and math path. + pub(crate) fn step_for_mtp( + binding: &ModelBinding, + token: TokenId, + pos: Position, + session: &mut QwenSession<'_>, + output: &OutputStage<'_, '_>, + kar_cache: Option<&mut KarPleCache<'_>>, + ) -> Result { + Self::step_for_mtp_cached(binding, token, pos, session, output, kar_cache, None, None) + } + #[allow(clippy::too_many_arguments)] + pub(crate) fn step_cached( + binding: &ModelBinding, + token: TokenId, + pos: Position, + session: &mut QwenSession<'_>, + output: &OutputStage<'_, '_>, + kar_cache: Option<&mut KarPleCache<'_>>, + moe_cache: &mut MoeWeightCache<'_>, + dense_cache: &DenseWeightCache<'_>, + ) -> Result { + Self::step_core( + binding, + token, + pos, + session, + Some(output), + kar_cache, + Some(moe_cache), + Some(dense_cache), + false, + false, + ) + .and_then(|(token, _)| token.ok_or(Error::IdentityMismatch)) + } + #[allow(clippy::too_many_arguments)] + pub(crate) fn step_for_mtp_cached( + binding: &ModelBinding, + token: TokenId, + pos: Position, + session: &mut QwenSession<'_>, + output: &OutputStage<'_, '_>, + kar_cache: Option<&mut KarPleCache<'_>>, + moe_cache: Option<&mut MoeWeightCache<'_>>, + dense_cache: Option<&DenseWeightCache<'_>>, + ) -> Result { + let (predicted, streams) = Self::step_core( + binding, + token, + pos, + session, + Some(output), + kar_cache, + moe_cache, + dense_cache, + true, + false, + )?; + Ok(TargetStepProduct { + binding: binding.identity(), + token, + position: pos, + predicted: predicted.ok_or(Error::IdentityMismatch)?, + streams: streams.ok_or(Error::IdentityMismatch)?, + origin: session.target_origin()?, + }) + } + + #[allow(clippy::too_many_arguments)] + pub(crate) fn prefill_for_mtp_cached( + binding: &ModelBinding, + token: TokenId, + pos: Position, + session: &mut QwenSession<'_>, + output: &OutputStage<'_, '_>, + kar_cache: Option<&mut KarPleCache<'_>>, + moe_cache: &mut MoeWeightCache<'_>, + dense_cache: &DenseWeightCache<'_>, + ) -> Result { + let (predicted, streams) = Self::step_core( + binding, + token, + pos, + session, + Some(output), + kar_cache, + Some(moe_cache), + Some(dense_cache), + true, + true, + )?; + if predicted.is_some() { + return Err(Error::IdentityMismatch); + } + Ok(PrefillStepProduct { + binding: binding.identity(), + token, + position: pos, + streams: streams.ok_or(Error::IdentityMismatch)?, + origin: session.target_origin()?, + }) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_2_2.rs b/crates/leleka-runtime/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_2_2.rs new file mode 100644 index 00000000..d5168ac0 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_2_2.rs @@ -0,0 +1,357 @@ +//! Moved out of the parent module by STRA-338: impl QwenForward (2). + +#[allow(unused_imports)] +use super::*; + + + +impl QwenForward { + + #[allow(clippy::too_many_arguments)] + pub(in super::super) fn step_core( + binding: &ModelBinding, + token: TokenId, + pos: Position, + session: &mut QwenSession<'_>, + output: Option<&OutputStage<'_, '_>>, + kar_cache: Option<&mut KarPleCache<'_>>, + mut moe_cache: Option<&mut MoeWeightCache<'_>>, + dense_cache: Option<&DenseWeightCache<'_>>, + capture_mtp: bool, + prefill_only: bool, + ) -> Result { + let mut streams = None; + let predicted = session.transact_completion(token, pos, &binding.identity(), |txn| { + // Validate the complete producer-bound descriptor sequence before + // touching any model rows or invoking a stage. + let layer_bound = validate_layer_plan(binding)?; + if let Some(cache) = dense_cache { + cache.validate(binding)?; + } + if let Some(cache) = moe_cache.as_deref_mut() { + let context = txn.cuda_context()?; + if dense_cache + .map(|dense| dense.gdn_four_borrow(binding, context)) + .transpose()? + .unwrap_or(false) + { + cache.reserve_mmq_transient(binding, context, super::super::super::gdn::FOUR_BORROW_BYTES)?; + } else { + cache.prepare_step(binding, txn.cuda_context()?)?; + } + } + + // A forward without its output head can never publish, so refuse + // before reading any row or running any layer. Everything above + // keeps its precedence; nothing has been staged yet. + let output = output.ok_or(Error::Unsupported(Stage::Output))?; + + let input = diagnose( + ForwardPhase::Input, + 0, + pos, + match (binding.kar_ple_binding(), kar_cache) { + (None, None) => InputStage::consume(binding, token, pos, txn), + (Some(_), Some(cache)) => { + InputStage::consume_kar(binding, cache, token, pos, txn) + } + // Never interpret a missing or wrong loaded provider as a + // request to switch modes or fall back to the native rows. + _ => Err(Error::IdentityMismatch), + }, + )?; + + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if super::super::super::oracle_capture::enabled() { + super::super::super::oracle_capture::stage_f32(-1, "input_residual", input.streams().values())?; + super::super::super::oracle_capture::stage_f32( + -1, + "embedding", + input + .streams() + .values() + .get(..2560) + .ok_or(Error::InvalidDimension)?, + )?; + } + txn.stage_input(input)?; + + let mut previous = None; + for descriptor in binding.ordered_layers() { + #[cfg(test)] + eprintln!("integration: starting layer {}", descriptor.index()); + let layer = LayerId::new(u64::from(descriptor.index()), layer_bound)?; + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if super::super::super::oracle_capture::enabled() { + super::super::super::oracle_capture::begin(pos.get(), layer.get() as i32)?; + } + + let mut residual = diagnose( + ForwardPhase::ReadAttention, + layer.get(), + pos, + read_layer_attention(binding, layer, previous.as_ref(), txn, dense_cache), + )?; + + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if super::super::super::oracle_capture::enabled() { + super::super::super::oracle_capture::stage_current( + "gr_attention_mixed", + residual.ready().mixed(), + )?; + super::super::super::oracle_capture::stage_current( + "gr_attention_inject", + residual.ready().oracle_inject(), + )?; + } + let injected_result = (|| { + let injected = match descriptor.kind() { + BoundLayerKind::Gdn => { + let prior = txn.gdn_prior(layer)?; + let mut attention = diagnose( + ForwardPhase::Gdn, + layer.get(), + pos, + GdnStage::step( + binding, + layer, + residual.ready(), + &prior, + txn, + dense_cache, + ), + )?; + attention.validate_origin(&binding.identity())?; + attention.identity().validate(token, pos, layer)?; + let pending = attention.take_pending()?; + txn.stage_gdn(&prior, pending)?; + + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if super::super::super::oracle_capture::enabled() { + super::super::super::oracle_capture::stage_current( + "attention_output", + attention.output(), + )?; + } + diagnose( + ForwardPhase::GrAttentionInject, + layer.get(), + pos, + GrStage::inject( + binding, + &mut residual, + attention.output(), + attention.identity(), + txn, + ), + )? + } + BoundLayerKind::Qsa => { + let attention = { + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + let native = dense_cache + .filter(|cache| cache.has_native_qsa()) + .map(|cache| { + diagnose( + ForwardPhase::QsaAttention, + layer.get(), + pos, + QsaAttentionStage::decode_native( + binding, + layer, + residual.ready(), + txn, + cache, + ), + ) + }) + .transpose()?; + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] + let native = None; + if let Some(completed) = native { + completed + } else { + let prior = txn.qsa_prior(layer)?; + let mut prepared = diagnose( + ForwardPhase::QsaIndex, + layer.get(), + pos, + QsaIndexStage::prepare( + binding, + layer, + residual.ready(), + pos, + &prior, + txn, + dense_cache, + ), + )?; + prepared.validate_origin(&binding.identity(), layer)?; + prepared.identity().validate(token, pos, layer)?; + let pending = prepared.take_pending()?; + txn.stage_qsa(&prior, pending)?; + let attention = diagnose( + ForwardPhase::QsaAttention, + layer.get(), + pos, + QsaAttentionStage::decode_with_scratch( + binding, + layer, + prepared, + txn, + dense_cache, + dense_cache.and_then( + DenseWeightCache::qsa_attention_workspace, + ), + ), + )?; + attention + } + }; + attention.validate_origin(&binding.identity(), layer)?; + attention.identity().validate(token, pos, layer)?; + + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if super::super::super::oracle_capture::enabled() { + super::super::super::oracle_capture::stage_current( + "attention_output", + attention.output(), + )?; + } + diagnose( + ForwardPhase::GrAttentionInject, + layer.get(), + pos, + GrStage::inject( + binding, + &mut residual, + attention.output(), + attention.identity(), + txn, + ), + )? + } + }; + Ok(injected) + })(); + let injected = residual.finish(injected_result)?; + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if super::super::super::oracle_capture::enabled() { + super::super::super::oracle_capture::stage_current( + "residual_after_attention", + injected.streams(), + )?; + } + + let mut ffn = diagnose( + ForwardPhase::GrFfn, + layer.get(), + pos, + GrStage::read_ffn(binding, layer, &injected, txn, dense_cache), + )?; + + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if super::super::super::oracle_capture::enabled() { + super::super::super::oracle_capture::stage_current("gr_ffn_mixed", ffn.ready().mixed())?; + super::super::super::oracle_capture::stage_current( + "gr_ffn_inject", + ffn.ready().oracle_inject(), + )?; + } + let completed_result = (|| { + let route = diagnose( + ForwardPhase::MoeRoute, + layer.get(), + pos, + MoeRouteStage::route_from_ffn( + binding, + layer, + ffn.ready(), + txn, + dense_cache, + ), + )?; + + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if super::super::super::oracle_capture::enabled() { + let ids = + std::array::from_fn::<_, 10, _>(|i| route.experts()[i].get() as i32); + let weights = std::array::from_fn::<_, 10, _>(|i| route.weights()[i].get()); + super::super::super::oracle_capture::stage_i32(layer.get() as i32, "router_ids", &ids)?; + super::super::super::oracle_capture::stage_current("router_weights", &weights)?; + } + let experts = diagnose( + ForwardPhase::MoeExpert, + layer.get(), + pos, + MoeExpertStage::execute( + binding, + layer, + route, + ffn.ready(), + txn, + moe_cache.as_deref_mut(), + ), + )?; + experts.validate_origin(&binding.identity())?; + experts.identity().validate(token, pos, layer)?; + + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if super::super::super::oracle_capture::enabled() { + super::super::super::oracle_capture::stage_current("combined_output", experts.output())?; + } + let completed = diagnose( + ForwardPhase::GrFfnInject, + layer.get(), + pos, + GrStage::inject( + binding, + &mut ffn, + experts.output(), + experts.identity(), + txn, + ), + )?; + Ok(completed) + })(); + let completed = ffn.finish(completed_result)?; + + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if super::super::super::oracle_capture::enabled() { + super::super::super::oracle_capture::stage_current( + "residual_after_moe", + completed.streams(), + )?; + } + txn.mark_layer_complete(&completed)?; + previous = Some(completed); + } + let final_residual = previous.as_ref().ok_or(Error::InvalidDimension)?; + let predicted = if prefill_only { + txn.finish_prefill(final_residual)?; + None + } else { + let logits = diagnose( + ForwardPhase::Output, + binding.layer_count().saturating_sub(1), + pos, + output.logits_cached(binding, final_residual, txn, dense_cache), + )?; + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + output.test_reset_replay_capture(&logits)?; + Some(txn.finish_forward(logits)?) + }; + if capture_mtp { + let mut owned = Vec::new(); + owned + .try_reserve_exact(10240) + .map_err(|_| Error::InputAllocation)?; + owned.extend_from_slice(final_residual.streams()); + streams = Some(owned.into_boxed_slice()); + } + Ok(predicted) + })?; + // A failed commit never exposes the local candidate to a draft caller. + Ok((predicted, streams)) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_3.rs b/crates/leleka-runtime/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_3.rs new file mode 100644 index 00000000..e42ecb91 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_3.rs @@ -0,0 +1,13 @@ +//! Moved out of the parent module by STRA-338: impl QwenForward (3). + +#[allow(unused_imports)] +use super::*; + + + +impl QwenForward { + + pub(crate) fn reset(session: &mut QwenSession<'_>) -> Result<()> { + session.reset() + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor.rs b/crates/leleka-runtime/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor.rs index 8c8b8f51..bae13aca 100644 --- a/crates/leleka-runtime/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor.rs +++ b/crates/leleka-runtime/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor.rs @@ -3,476 +3,9 @@ #[allow(unused_imports)] use super::*; -impl<'ctx> OriginalPromptExecutor<'ctx>{ - /// Eager model/session owners precede expert prefix planning. The twelve - /// resident checkpoints are installed together only after all producers exist. - pub(in crate::qwen_forward) fn new(binding:&ModelBinding,dense:&DenseWeightCache<'ctx>, - session:&mut QwenSession<'ctx>,context:&'ctx Context<'ctx>,moe:&MoeWeightCache<'ctx>, - embedding:&OriginalPromptEmbedding<'ctx>,capacity:usize,max_t:usize,fused:bool, - )->Result{ - // Pinned-pack source: the MoE cache already holds and charged the roles. - let retained=moe.retain_original_mtp_weights(binding,context)?; - Self::new_with_mtp_weights(binding,dense,session,context,retained,embedding,capacity,max_t,fused) - } - /// Same construction over any retained MTP role bank (the pinned pack, or - /// the Original-literal RT directory bank of `select_rt_mtp`). - #[allow(clippy::too_many_arguments)] - pub(in crate::qwen_forward) fn new_with_mtp_weights(binding:&ModelBinding,dense:&DenseWeightCache<'ctx>, - session:&mut QwenSession<'ctx>,context:&'ctx Context<'ctx>,retained:RetainedOriginalMtpWeights<'ctx>, - embedding:&OriginalPromptEmbedding<'ctx>,capacity:usize,max_t:usize,fused:bool, - )->Result{ - if binding.layer_count()!=48||!(1..=8192).contains(&capacity)||!(1..=8).contains(&max_t) - ||dense.native_prompt_capacity(binding,context)?!=capacity - ||!std::ptr::eq(context,session.mtp_context()?){return Err(Error::IdentityMismatch);} - let mut owner=Self{context,binding:binding.identity(),capacity,fused,prompt:None,gdn:None,qsa:None, - transport:None,attention:None,mtp_prefill:None,mtp_scalar:None,mtp_scalar_weights:None, - mtp_weights:None,mtp_full:None,max_t,layers:std::array::from_fn(|_|None),failed:false}; - let result=(||{ - owner.prompt=Some(context.original_prompt_device(capacity,PleBf16Mode::HighOnly,GrNativeProfile::HighOnly).map_err(driver_error)?); - owner.gdn=Some(context.original_gdn_prompt_device(capacity,GrNativeProfile::HighOnly).map_err(driver_error)?); - owner.qsa=Some(context.original_qsa_resident_prompt_device(capacity,QsaNativePacking::HighOnly).map_err(driver_error)?); - owner.transport=Some(context.original_qsa_resident_transport().map_err(driver_error)?); - owner.attention=Some(context.original_qsa_resident_attention(capacity).map_err(driver_error)?); - owner.mtp_prefill=Some(context.original_mtp_prefill().map_err(driver_error)?); - owner.mtp_scalar_weights=Some(retained.scalar_prefill_weights(binding,context,embedding)?); - owner.mtp_weights=Some(retained); - owner.mtp_scalar=Some(context.original_mtp_scalar_prefill(max_t,capacity).map_err(driver_error)?); - let mut workspace=dense.native_batch_workspace(binding,context)?.ok_or(Error::IdentityMismatch)?; - for layer in binding.ordered_layers(){if layer.kind()==BoundLayerKind::Qsa{ - let id=LayerId::new(layer.index()as u64,Dimension::new(48)?)?; - let empty=session.original_qsa_seed(binding,id)?; - let index=context.original_qsa_resident_index().map_err(driver_error)?; - let kv=context.qsa_prompt_kv().map_err(driver_error)?.into_original_mapped_journal().map_err(driver_error)?; - owner.layers[layer.index()as usize]=Some(ResidentQsaLayer::new(binding,dense,session,&empty,index,kv,&mut workspace)?); - }} - drop(workspace); - let priors=std::array::from_fn(|slot|owner.layers[slot].as_ref().map(ResidentQsaLayer::current)); - session.install_original_qsa_seed_set(binding,priors)?;Ok(()) - })(); - if let Err(primary)=result{let _=owner.close_inner();return Err(primary);} - Ok(owner) - } - /// The immutable MTP roles this executor retains (the RT bank's on the product path). - pub(in crate::qwen_forward) fn retained_mtp_weights(&self)->Option<&RetainedOriginalMtpWeights<'ctx>>{self.mtp_weights.as_ref()} - /// Joins the source-created full MTP graph owner to this exact prompt - /// executor. The draft session is validated against the same target - /// session before it leaves the assembly, so callers cannot pair a full - /// graph with a separately allocated MTP ring. - pub(in crate::qwen_forward) fn install_full_mtp(&mut self,binding:&ModelBinding, - session:&QwenSession<'ctx>,assembly:OriginalMtpFullAssembly<'ctx>)->Result>{ - if self.failed||self.context.is_poisoned()||!self.binding.matches(&binding.identity()) - ||!std::ptr::eq(self.context,session.mtp_context()?)||self.mtp_full.is_some(){return Err(Error::IdentityMismatch);} - assembly.draft.checkpoint(binding,session)?; - assembly.owner.validate(binding,self.context,self.max_t)?; - self.mtp_full=Some(assembly.owner); - Ok(assembly.draft) - } - /// Source-level MTP selection, the `--mtp DIR` branch of generate.cpp - /// (`mtp.load` ... `mtp.bind`): load the RT directory banks (dense.txt, - /// dense.bin, experts.bin, nine-name check), build the prompt executor over - /// those exact retained roles, then bind the native head (optional - /// draft_vocab subset), the shared scalar/full/ring layout, the coupled - /// setup and the actor, and install the matching draft session. - /// - /// Returns both owners; the draft session is the sole mutator of the - /// ring, the executor holds the actor. Any failure releases everything - /// built so far through the owners' own closure order. - #[allow(clippy::too_many_arguments)] - pub(in crate::qwen_forward) fn select_rt_mtp(binding:&ModelBinding,dense:&DenseWeightCache<'ctx>, - session:&mut QwenSession<'ctx>,context:&'ctx Context<'ctx>,embedding:&OriginalPromptEmbedding<'ctx>, - output:&OriginalNativeOutput<'ctx>,rt_directory:&std::path::Path,capacity:usize,fused:bool, - request:&OriginalMtpRequest)->std::result::Result<(Self,OriginalDraftSession<'ctx>),OriginalMtpLoadError>{ - if !(1..=8).contains(&request.max_t)||request.prompt_capacity!=capacity||binding.layer_count()!=48{ - return Err(Error::IdentityMismatch.into());} - let bank=context.original_mtp_rt_bank(rt_directory,binding.expert_count() as usize)?; - let retained=RetainedOriginalMtpWeights::from_rt_bank(binding,context,&bank)?; - // The bank object is only a loader receipt: every allocation it holds is - // shared with (or retained alongside) `retained`. - drop(bank); - let mut executor=Self::new_with_mtp_weights(binding,dense,session,context,retained.clone(),embedding, - capacity,request.max_t,fused)?; - let assembly=OriginalMtpFullOwner::assemble_rt(binding,session,context,&retained,embedding,output,request,rt_directory)?; - let draft=executor.install_full_mtp(binding,session,assembly)?; - Ok((executor,draft)) - } - /// The loaded `MtpDrafter` of this executor. The caller still borrows the - /// ring through the draft session (`with_pending_ring`, - /// `with_mtp_transition_ring`), which keeps SessionState as the sole mutable - /// authority for its snapshot. - pub(in crate::qwen_forward) fn mtp_actor(&mut self,binding:&ModelBinding) - ->Result<&mut leleka_cuda_driver::OriginalMtpActor<'ctx>>{ - let(context,max_t)=(self.context,self.max_t); - self.mtp_full.as_mut().ok_or(Error::IdentityMismatch)?.actor_mut(binding,context,max_t) - } - /// generate.cpp `mtp.set_prompt_len(n)`. - pub(in crate::qwen_forward) fn set_mtp_prompt_len(&mut self,binding:&ModelBinding,n:i64)->Result<()> { - self.mtp_actor(binding)?.set_prompt_len(n);Ok(()) - } - /// generate.cpp `mtp.set_max_drafts(S_mtp - 1)`. - pub(in crate::qwen_forward) fn set_mtp_max_drafts(&mut self,binding:&ModelBinding,k:i32)->Result<()> { - self.mtp_actor(binding)?.set_max_drafts(k);Ok(()) - } - /// `MtpDrafter::idle()`: drain its own capture stream, nothing else. - pub(in crate::qwen_forward) fn mtp_idle(&mut self,binding:&ModelBinding)->Result<()> { - self.mtp_actor(binding)?.idle().map_err(driver_error) - } - /// End of a request's verifier: release what the MTP drafter bound to that verifier's bank (its cached round programs read the - /// bank's final-R span and its tail keeps the last staged window), so the bank can close and the next request's first draft - /// captures against its own bank. See `OriginalMtpActor::release_verifier_bindings`. - pub(in crate::qwen_forward) fn mtp_release_verifier(&mut self,binding:&ModelBinding)->Result<()> { - self.mtp_actor(binding)?.release_verifier_bindings().map_err(driver_error) - } - /// `MtpDrafter::device()`. - pub(in crate::qwen_forward) fn mtp_device(&mut self,binding:&ModelBinding)->Result { - Ok(self.mtp_actor(binding)?.device()) - } - /// generate.cpp `if (resume > 0 && reread_to <= 0) mtp.kv_restore(resume)` - /// on the retained ring of the CURRENT, already restored target branch. - pub(in crate::qwen_forward) fn mtp_kv_restore(&mut self,binding:&ModelBinding, - session:&QwenSession<'ctx>,draft:&mut OriginalDraftSession<'ctx>,upto:i64)->Result<()> { - let origin=session.target_origin()?; - let actor=self.mtp_actor(binding)?; - draft.with_mtp_current_ring(binding,session,&origin,|ring,prior|actor.kv_restore(ring,prior,upto).map_err(driver_error)) - } - /// One-way handoff of the twelve resident QSA layers (index image + mapped K/V) to the native - /// verifier for a decode phase. All twelve are validated before any is moved, so a refusal leaves the - /// executor whole. While the owners are out the executor cannot run a prompt transaction; `adopt_qsa_owners` - /// takes the very same physical owners back. - #[allow(clippy::type_complexity)] - pub(in crate::qwen_forward) fn take_qsa_owners(&mut self)->Result<[Option<(leleka_cuda_driver::OriginalQsaResidentIndex<'ctx>, - leleka_cuda_driver::OriginalQsaMappedJournal<'ctx>)>;48]>{ - if self.failed||self.context.is_poisoned(){return Err(Error::CudaExecution);} - for layer in self.layers.iter().flatten(){layer.check_handoff()?;} - if self.layers.iter().flatten().count()!=12{return Err(Error::IdentityMismatch);} - let mut owners:[Option<(leleka_cuda_driver::OriginalQsaResidentIndex<'ctx>,leleka_cuda_driver::OriginalQsaMappedJournal<'ctx>)>;48]= - std::array::from_fn(|_|None); - for(slot,layer)in self.layers.iter_mut().enumerate(){if let Some(layer)=layer.take(){ - // the session keeps the lineage prior; only the physical owners travel - let(index,kv,_prior)=layer.into_verifier_owners()?;owners[slot]=Some((index,kv)); - }} - Ok(owners) - } - /// The reverse of `take_qsa_owners`, after the verifier closed and its journal returned the owners. - /// Each layer is rebuilt at the session's current lineage witness and its physical image rolled back to - /// it (a no-op copy when the last window committed; the repair when a window was abandoned). The - /// roll-back mints a fresh witness object per layer for the SAME lineage, so the session adopts those - /// objects before the layers can be used again (a layer and the session must name one witness). - #[allow(clippy::type_complexity)] - pub(in crate::qwen_forward) fn adopt_qsa_owners(&mut self,binding:&ModelBinding,dense:&DenseWeightCache<'ctx>, - session:&mut QwenSession<'ctx>,owners:[Option<(leleka_cuda_driver::OriginalQsaResidentIndex<'ctx>, - leleka_cuda_driver::OriginalQsaMappedJournal<'ctx>)>;48])->Result<()>{ - if self.failed||self.context.is_poisoned()||self.layers.iter().any(Option::is_some){return Err(Error::IdentityMismatch);} - let witnesses=session.original_qsa_witnesses()?; - let context=dense.retained_context(binding,session.mtp_context()?)?; - let mut workspace=dense.native_batch_workspace(binding,context)?.ok_or(Error::IdentityMismatch)?; - let mut first=None; - for(slot,owner)in owners.into_iter().enumerate(){if let Some((index,kv))=owner{ - let rebuilt=witnesses[slot].clone().ok_or(Error::IdentityMismatch).and_then(|prior| - ResidentQsaLayer::from_verifier_owners(binding,dense,session,index,kv,prior,&mut workspace)); - match rebuilt{Ok(layer)=>self.layers[slot]=Some(layer),Err(error)=>{first.get_or_insert(error);}} - }} - drop(workspace); - if let Some(error)=first{self.failed=true;return Err(error);} - let current:[Option>;48]=std::array::from_fn(|slot|self.layers[slot].as_ref().map(ResidentQsaLayer::current)); - let adopted=session.adopt_original_qsa_witnesses(current); - if adopted.is_err(){self.failed=true;} - adopted - } - /// The session's Original checkpoint (position, predecessors, PLE/GDN priors and the twelve resident QSA - /// witnesses). Refused while the recurrent priors lag a verified-window publication. - pub(in crate::qwen_forward) fn checkpoint_session(&mut self,binding:&ModelBinding, - session:&mut QwenSession<'ctx>)->Result>{ - if self.failed||self.context.is_poisoned(){return Err(Error::CudaExecution);} - if self.layers.iter().flatten().count()!=12{return Err(Error::IdentityMismatch);} - session.original_checkpoint(binding) - } - /// Prefix cache: park the point the session stands at (see `ParkedSession`). - pub(in crate::qwen_forward) fn park_session(&mut self,binding:&ModelBinding, - session:&mut QwenSession<'ctx>)->Result{ - if self.failed||self.context.is_poisoned(){return Err(Error::CudaExecution);} - if self.layers.iter().flatten().count()!=12{return Err(Error::IdentityMismatch);} - session.park_original(binding,&self.layers) - } - /// Prefix cache: the cells `first..first + tokens` of the twelve layers as plain bytes. - pub(in crate::qwen_forward) fn park_block(&self,session:&QwenSession<'ctx>,first:usize,tokens:usize)->Result{ - if self.failed||self.context.is_poisoned(){return Err(Error::CudaExecution);} - if self.layers.iter().flatten().count()!=12{return Err(Error::IdentityMismatch);} - session.park_block(&self.layers,first,tokens) - } - /// Prefix cache: make the session and the twelve layers stand at `parked`, writing `blocks`. A failure poisons - /// the executor, as for `restore_session`. - pub(in crate::qwen_forward) fn import_session(&mut self,binding:&ModelBinding,dense:&DenseWeightCache<'ctx>, - session:&mut QwenSession<'ctx>,parked:&ParkedSession,blocks:&[&ParkedBlock])->Result<()>{ - if self.failed||self.context.is_poisoned(){return Err(Error::CudaExecution);} - let imported=session.import_parked(binding,dense,&mut self.layers,parked,blocks); - if imported.is_err(){self.failed=true;} - imported - } - /// Roll the session AND the twelve physical resident layers back to `checkpoint` (a request reset to the - /// empty prompt, or an abandoned prompt transaction). A failure poisons the executor. - pub(in crate::qwen_forward) fn restore_session(&mut self,binding:&ModelBinding,dense:&DenseWeightCache<'ctx>, - session:&mut QwenSession<'ctx>,checkpoint:&OriginalSessionCheckpoint<'ctx>)->Result<()>{ - if self.failed||self.context.is_poisoned(){return Err(Error::CudaExecution);} - let restored=session.restore_original_checkpoint(binding,dense,&mut self.layers,checkpoint); - if restored.is_err(){self.failed=true;} - restored - } - /// Whether the twelve resident layers are home (a prompt transaction can run). - pub(in crate::qwen_forward) fn qsa_owners_home(&self)->bool{self.layers.iter().flatten().count()==12} - pub(super) fn validate(&self,binding:&ModelBinding,dense:&DenseWeightCache<'ctx>,session:&QwenSession<'ctx>)->Result<()> { - if self.failed||self.context.is_poisoned(){return Err(Error::CudaExecution);} - if !self.binding.matches(&binding.identity())||!std::ptr::eq(self.context,session.mtp_context()?) - ||dense.native_prompt_capacity(binding,self.context)?!=self.capacity{return Err(Error::IdentityMismatch);} - dense.validate(binding)?;Ok(()) - } - /// No target position is advanced here. Every read is actual GR arithmetic; - /// recurrent/KV/PLE seals belong to the same still-private source transaction. - #[allow(clippy::too_many_arguments)] - pub(in crate::qwen_forward) fn forward<'session,'program,'loan>( - &'program mut self,binding:&'program ModelBinding,dense:&'program DenseWeightCache<'ctx>, - session:&'session mut QwenSession<'ctx>,source:&std::rc::Rc,count:usize, - mut kar:Option<&mut KarPleCache<'ctx>>,moe:&mut MoeWeightCache<'ctx>, - arena:&mut OriginalPrefillArena<'loan,'ctx>, - draft:&'program mut OriginalDraftSession<'ctx>,embedding:&OriginalPromptEmbedding<'ctx>, - policy:&OriginalMtpScalarPolicy,mut cancelled:impl FnMut()->bool, - )->Result>{ - self.validate(binding,dense,session)?; - let first_position=session.target_origin()?.next_position(); - let tokens=source.window(binding,first_position,count)?; - crate::bringup_trace!("DBG[{:.0}s] forward: tokens={} self.capacity={} arena.capacity={} count={count}",crate::qwen_forward::original_serve_stack::dbg_el(),tokens.len(),self.capacity,arena.capacity()); - let _launch_sync=leleka_cuda_driver::PromptSyncTrace::enter(); - if tokens.is_empty()||tokens.len()>self.capacity||arena.capacity()!=self.capacity{return Err(Error::InvalidDimension);} - let checkpoint=session.original_checkpoint(binding)?; - let draft_checkpoint=draft.checkpoint(binding,session)?; - let mut txn=OriginalPromptTxn::begin(session,binding,source,count)?; - let profile_context=self.context; - let drain=Some(profile_context as &dyn prof::Drain); - let operation=(||{ - // The last prompt seed belongs to Original Verifier. Every row - // admitted here must have its authentic next token in the source. - txn.known_prompt_next()?.ok_or(Error::IdentityMismatch)?; - let input_span=prof::span(PStage::Input,None); - // KAR inputs are staged chunk-wide: embeddings broadcast and PLE rows decoded on the device - // (LELEKA_PREFILL_STAGED_INPUT=0: the per-token host path, the A/B arm). - let mut staged_input=None;let mut staged_ple=None;let mut first_predecessors:Option<[i32;2]>=None; - if binding.kar_ple_binding().is_some()&&staged_input_enabled(){ - let mut staged=StagedInput::default(); - for &token in tokens{ - txn.stage_input(|step|{let pos=step.position(); - if first_predecessors.is_none(){first_predecessors=Some(step.input_predecessors()?);} - match kar.as_deref(){ - Some(cache)=>InputStage::consume_kar_deferred(binding,cache,token,pos,step,&mut staged), - None=>Err(Error::IdentityMismatch), - } - })?; - } - let cache=kar.as_deref_mut().ok_or(Error::IdentityMismatch)?; - let kar_binding=binding.kar_ple_binding().ok_or(Error::IdentityMismatch)?; - let _ple_span=prof::span(PStage::InputPle,None); - staged_ple=Some(cache.stage_batch(kar_binding,staged.ple_rows())?); - staged_input=Some(staged); - }else{ - for &token in tokens{ - txn.stage_input(|step|{let pos=step.position(); - match (binding.kar_ple_binding(),kar.as_deref_mut()){ - (None,None)=>InputStage::consume(binding,token,pos,step), - (Some(_),Some(cache))=>InputStage::consume_kar(binding,cache,token,pos,step), - _=>Err(Error::IdentityMismatch), - } - })?; - } - } - drop(input_span); - let init_span=prof::span(PStage::Initialize,drain); - let mut sources=Vec::new();sources.try_reserve_exact(tokens.len()).map_err(|_|Error::InputAllocation)?; - let sources_span=prof::span(PStage::InitSources,None); - for local in 0..tokens.len(){sources.push(PromptDeviceSource::from_original(binding,self.context,&txn,local)?);} - drop(sources_span); - let upload_span=prof::span(PStage::InitUpload,drain); - let prompt=self.prompt.as_mut().ok_or(Error::IdentityMismatch)?; - let lease=arena.begin_rows(tokens.len()).map_err(driver_error)?; - let rows=match (staged_input.as_ref(),staged_ple){ - (Some(input),Some(ple))=>{ - let cache=kar.as_deref_mut().ok_or(Error::IdentityMismatch)?; - let result={ - let (ple_cache,ple_books)=cache.device_parts(); - let stage=PromptInputStage{embedding_rows:input.embedding_rows(),embedding_index:input.embedding_index(), - ple_cache,ple_books,ple_updates:ple.updates(),ple_slots:ple.slots()}; - PromptDeviceRows::initialize(binding,dense,self.context,prompt,lease,sources,Some(stage)) - }; - match result{ - Ok(rows)=>{cache.commit(ple);rows}, - // the device may already hold part of the scatter: the cache is not trusted again - Err(error)=>{cache.invalidate();return Err(error);}, - } - }, - _=>PromptDeviceRows::initialize(binding,dense,self.context,prompt,lease,sources,None)?, - }; - drop(upload_span);drop(init_span); - // The PLE packets of the next chunk are read from the archive on a thread of their own while this chunk computes - // (they are a function of the tokens and the archive only); `stage_batch` of that chunk takes them from there. - if let (Some(cache),Some(kar_binding),Some(mut before))=(kar.as_deref_mut(),binding.kar_ple_binding(),first_predecessors){ - let next_first=first_position+tokens.len() as u64; - let want=self.capacity.min(source.len().saturating_sub(next_first as usize)); - if want>0{ - if let Ok(next)=source.window(binding,next_first,want){ - for &token in tokens{before=[before[1],token.get() as i32];} - if let Ok(rows)=InputStage::ple_rows_ahead(binding,before,next){cache.read_ahead(kar_binding,&rows);} - } - } - } - let mut carrier=Carrier::Plain(rows); - for layer in binding.ordered_layers(){ - let index=layer.index();let role=super::super::super::gr::GrRole::Attention(index); - crate::bringup_trace!("DBG[{:.0}s] forward layer {index} {:?} begin",crate::qwen_forward::original_serve_stack::dbg_el(),layer.kind()); - if index==1{ - let Carrier::Plain(mut rows)=carrier else{return Err(Error::IdentityMismatch);}; - {let _span=prof::span(PStage::Validate,None);rows.validate_original_rows(binding,dense)?;} - let _span=prof::span(PStage::Ple,drain); - let prior=txn.ple_prior()?; - let mut history=InputStage::prepare_original_prompt_history(binding,dense,self.context,&txn)?; - rows=rows.apply_ple(binding,dense,prompt,&mut history)?; - InputStage::finish_original_prompt_history(binding,&txn,&prior,history)?; - // The completed PLE operation changes the real row state. - // Its output must pass fresh current-row validation. - carrier=Carrier::Plain(rows); - } - let mut read=match carrier{ - Carrier::Plain(mut rows)=>{ - {let _span=prof::span(PStage::Validate,None);rows.validate_original_rows(binding,dense)?;} - let _span=prof::span(PStage::AttnRead,drain); - rows.read(binding,dense,prompt,role)? - }, - Carrier::Normed(mut rows)=>{ - {let _span=prof::span(PStage::Validate,None);rows.validate_original_rows(binding,dense)?;} - let _span=prof::span(PStage::AttnRead,drain); - rows.read(binding,dense,prompt)? - }, - }; - crate::bringup_trace!("DBG[{:.0}s] L{index} attn-read ok",crate::qwen_forward::original_serve_stack::dbg_el()); - {let _span=prof::span(PStage::Validate,None);read.validate_original_rows(binding,dense)?;} - let mixer_span=prof::span(match layer.kind(){BoundLayerKind::Gdn=>PStage::Gdn,BoundLayerKind::Qsa=>PStage::Qsa},drain); - let mut ffn=if self.fused { - let rows=match layer.kind(){ - BoundLayerKind::Gdn=>read.complete_original_gdn_normed(binding,dense,&txn,prompt,self.gdn.as_mut().ok_or(Error::IdentityMismatch)?)?, - BoundLayerKind::Qsa=>read.complete_original_qsa_normed(binding,dense,&txn,prompt,self.layers[index as usize].as_mut().ok_or(Error::IdentityMismatch)?, - self.qsa.as_mut().ok_or(Error::IdentityMismatch)?,self.transport.as_mut().ok_or(Error::IdentityMismatch)?,self.attention.as_mut().ok_or(Error::IdentityMismatch)?)?, - };Carrier::Normed(rows) - }else{ - let rows=match layer.kind(){ - BoundLayerKind::Gdn=>read.complete_original_gdn(binding,dense,&txn,prompt,self.gdn.as_mut().ok_or(Error::IdentityMismatch)?)?, - BoundLayerKind::Qsa=>read.complete_original_qsa(binding,dense,&txn,prompt,self.layers[index as usize].as_mut().ok_or(Error::IdentityMismatch)?, - self.qsa.as_mut().ok_or(Error::IdentityMismatch)?,self.transport.as_mut().ok_or(Error::IdentityMismatch)?,self.attention.as_mut().ok_or(Error::IdentityMismatch)?)?, - };Carrier::Plain(rows) - }; - drop(mixer_span); - crate::bringup_trace!("DBG[{:.0}s] L{index} mixer ok",crate::qwen_forward::original_serve_stack::dbg_el()); - {let _span=prof::span(PStage::Validate,None);match &mut ffn{ - Carrier::Plain(rows)=>{rows.validate_original_rows(binding,dense)?;}, - Carrier::Normed(rows)=>{rows.validate_original_rows(binding,dense)?;}, - };} - crate::bringup_trace!("DBG[{:.0}s] L{index} ffn-validate ok",crate::qwen_forward::original_serve_stack::dbg_el()); - let ffn_span=prof::span(PStage::FfnRead,drain); - let mut read=match ffn{ - Carrier::Plain(rows)=>rows.read(binding,dense,prompt,super::super::super::gr::GrRole::Ffn(index))?, - Carrier::Normed(rows)=>rows.read(binding,dense,prompt)?, - }; - drop(ffn_span); - {let _span=prof::span(PStage::Validate,None);read.validate_original_rows(binding,dense)?;} - let moe_span=prof::span(PStage::Moe,drain); - // Literal fused GR norm is prohibited across PLE and final head. - carrier=if self.fused&&index!=0&&index!=47{ - Carrier::Normed(read.complete_original_moe_normed(binding,dense,moe,prompt)?) - }else{Carrier::Plain(read.complete_original_moe(binding,dense,moe,prompt)?)}; - drop(moe_span); - crate::bringup_trace!("DBG[{:.0}s] L{index} moe ok",crate::qwen_forward::original_serve_stack::dbg_el()); - } - let Carrier::Plain(mut rows)=carrier else{return Err(Error::IdentityMismatch);}; - // the chunk's expert stream (if any) ended with the last MoE layer; never carried past the layers - moe.end_prompt_stream()?; - let final_span=prof::span(PStage::Final,drain); - crate::bringup_trace!("DBG[{:.0}s] forward: all layers ok, final row",crate::qwen_forward::original_serve_stack::dbg_el()); - let final_row=rows.preview_conditioning(binding,dense,&txn).map_err(|e|{crate::bringup_trace!("DBG[{:.0}s] preview_conditioning err {e:?}",crate::qwen_forward::original_serve_stack::dbg_el());e})?; - crate::bringup_trace!("DBG[{:.0}s] final_row ok",crate::qwen_forward::original_serve_stack::dbg_el()); - // Bring-up gate (LELEKA_TRACE_PREFILL_R=1): FNV-1a of the bits of every row of the chunk's final residual R - // (all four streams), for bit-exact A/B comparison of prefill variants. Slow (one drain per row); off by default. - if std::env::var_os("LELEKA_TRACE_PREFILL_R").is_some(){ - let first=txn.start_position();let count=txn.len(); - let hash=rows.with_final_residual(binding,dense,&txn,&final_row,|residual|{ - let mut hash=0xcbf29ce484222325u64;let mut rows_hash=Vec::with_capacity(count); - for index in 0..count{ - let row=residual.read_prompt_row(index).map_err(driver_error)?; - let mut row_hash=0xcbf29ce484222325u64; - for value in row.iter(){for byte in value.to_le_bytes(){row_hash^=u64::from(byte);row_hash=row_hash.wrapping_mul(0x100000001b3);}} - hash^=row_hash;hash=hash.wrapping_mul(0x100000001b3);rows_hash.push(row_hash); - } - Ok((hash,rows_hash)) - })?; - eprintln!("PREFILL-R first={first} rows={count} fnv1a64={:016x} first_row={:016x} last_row={:016x}",hash.0,hash.1[0],hash.1[count-1]); - } - let sample=OriginalPromptSample::conditioning(binding,&final_row,&txn).map_err(|e|{crate::bringup_trace!("DBG[{:.0}s] sample conditioning err {e:?}",crate::qwen_forward::original_serve_stack::dbg_el());e})?; - crate::bringup_trace!("DBG[{:.0}s] sample ok",crate::qwen_forward::original_serve_stack::dbg_el()); - drop(final_span); - let draft_span=prof::span(PStage::DraftKv,drain); - let producer=self.mtp_prefill.as_mut().ok_or(Error::IdentityMismatch)?; - // The scalar (short prompt) fallback must run on the drafter's OWN scalar owner: the ring of the shared layout is paired - // with that owner's main arena, a standalone owner is refused with InvalidQwenShape. - let (context,max_t)=(self.context,self.max_t); - let scalar=self.mtp_full.as_mut().ok_or(Error::IdentityMismatch)?.actor_mut(binding,context,max_t)?; - let scalar_weights=std::rc::Rc::clone(self.mtp_scalar_weights.as_ref().ok_or(Error::IdentityMismatch)?); - let retained_mtp=self.mtp_weights.clone().ok_or(Error::IdentityMismatch)?; - let draft_kv=draft.with_pending_ring(binding,&txn,|ring,prior,first_needed|{ - crate::bringup_trace!("DBG[{:.0}s] draft ring open first_needed={first_needed:?}",crate::qwen_forward::original_serve_stack::dbg_el()); - let mut workspace=dense.native_batch_workspace(binding,self.context)?.ok_or(Error::IdentityMismatch)?; - let outcome=rows.record_original_draft_kv(binding,dense,moe,&txn,&final_row,sample.next(), - producer,&mut workspace,ring,prior,embedding.borrow(binding,self.context)?,first_needed,&policy.kv,&mut cancelled)?; - crate::bringup_trace!("DBG[{:.0}s] record_original_draft_kv -> {}",crate::qwen_forward::original_serve_stack::dbg_el(),match &outcome{OriginalPromptDraftOutcome::Completed(_)=>"Completed",OriginalPromptDraftOutcome::Fallback(reason)=>{crate::bringup_trace!("DBG fallback reason: {reason:?}");"Fallback"},OriginalPromptDraftOutcome::Skipped=>"Skipped",OriginalPromptDraftOutcome::Cancelled=>"Cancelled"}); - let outcome=match outcome{ - OriginalPromptDraftOutcome::Fallback(_)=>rows.record_original_scalar_draft_kv( - binding,dense,&retained_mtp,&txn,&final_row,sample.next(),scalar,&mut workspace,ring,prior, - scalar_weights,first_needed,policy,&mut cancelled)?, - other=>other, - }; - crate::bringup_trace!("DBG[{:.0}s] after scalar fallback -> {}",crate::qwen_forward::original_serve_stack::dbg_el(),match &outcome{OriginalPromptDraftOutcome::Completed(_)=>"Completed",OriginalPromptDraftOutcome::Fallback(_)=>"Fallback",OriginalPromptDraftOutcome::Skipped=>"Skipped",OriginalPromptDraftOutcome::Cancelled=>"Cancelled"}); - match outcome{ - OriginalPromptDraftOutcome::Completed(completed)=>Ok(completed), - // Optional unported storage and actual no-materialization - // need separate genuine outcomes; refusal advances neither. - OriginalPromptDraftOutcome::Fallback(_)|OriginalPromptDraftOutcome::Skipped| - OriginalPromptDraftOutcome::Cancelled=>Err(Error::Unsupported(Stage::Session)), - } - }).map_err(|e|{crate::bringup_trace!("DBG[{:.0}s] with_pending_ring err {e:?}",crate::qwen_forward::original_serve_stack::dbg_el());e})?; - crate::bringup_trace!("DBG[{:.0}s] forward: draft kv ok",crate::qwen_forward::original_serve_stack::dbg_el()); - drop(draft_span); - if cancelled(){return Err(Error::Unsupported(Stage::Session));} - let _span=prof::span(PStage::FinishPreview,drain); - rows.finish_after_preview(binding,dense,&txn,&final_row).map_err(|e|{crate::bringup_trace!("DBG[{:.0}s] finish_after_preview err {e:?}",crate::qwen_forward::original_serve_stack::dbg_el());e})?; - Ok((final_row,sample,draft_kv)) - })(); - match operation{ - Err(primary)=>{ - crate::bringup_trace!("DBG[{:.0}s] forward operation failed: {primary:?}",crate::qwen_forward::original_serve_stack::dbg_el()); - // stop the chunk's expert stream before the transaction rolls back - if moe.end_prompt_stream().is_err(){self.failed=true;} - let cleanup=txn.abort_with_draft(binding,dense,&mut self.layers,&checkpoint,draft,&draft_checkpoint); - if cleanup.is_err()||self.context.is_poisoned(){self.failed=true;} - Err(primary) - }, - Ok((completed,sample,draft_kv))=>Ok(OriginalPromptPending{txn:Some(txn),binding,dense,layers:&mut self.layers, - failed:&mut self.failed,checkpoint,completed,sample,draft_kv,draft,draft_checkpoint}), - } - } - pub(in crate::qwen_forward) fn close(mut self)->Result<()>{self.close_inner()} - pub(super) fn close_inner(&mut self)->Result<()>{ - let mut first=None; - macro_rules! retire {($v:expr)=>{if let Some(owner)=$v.take(){if let Err(e)=owner.close().map_err(driver_error){first.get_or_insert(e);}}};} - retire!(self.prompt);retire!(self.gdn);retire!(self.qsa);retire!(self.transport);retire!(self.attention); - retire!(self.mtp_prefill); - retire!(self.mtp_scalar); - self.mtp_scalar_weights.take(); - self.mtp_weights.take(); - if let Some(owner)=self.mtp_full.take(){if let Err(error)=owner.close(){first.get_or_insert(error);}} - for slot in &mut self.layers{if let Some(layer)=slot.take(){if let Err(e)=layer.close(){first.get_or_insert(e);}}} - self.failed=true;first.map_or(Ok(()),Err) - } -} +#[path = "impl_originalpromptexecutor/impl_originalpromptexecutor_2.rs"] +mod impl_originalpromptexecutor_2; +#[path = "impl_originalpromptexecutor/impl_originalpromptexecutor_2_2.rs"] +mod impl_originalpromptexecutor_2_2; +#[path = "impl_originalpromptexecutor/impl_originalpromptexecutor_3.rs"] +mod impl_originalpromptexecutor_3; diff --git a/crates/leleka-runtime/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2.rs b/crates/leleka-runtime/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2.rs new file mode 100644 index 00000000..5dbb8ee8 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2.rs @@ -0,0 +1,229 @@ +//! Moved out of the parent module by STRA-338: impl OriginalPromptExecutor. + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalPromptExecutor<'ctx>{ + /// Eager model/session owners precede expert prefix planning. The twelve + /// resident checkpoints are installed together only after all producers exist. + pub(in crate::qwen_forward) fn new(binding:&ModelBinding,dense:&DenseWeightCache<'ctx>, + session:&mut QwenSession<'ctx>,context:&'ctx Context<'ctx>,moe:&MoeWeightCache<'ctx>, + embedding:&OriginalPromptEmbedding<'ctx>,capacity:usize,max_t:usize,fused:bool, + )->Result{ + // Pinned-pack source: the MoE cache already holds and charged the roles. + let retained=moe.retain_original_mtp_weights(binding,context)?; + Self::new_with_mtp_weights(binding,dense,session,context,retained,embedding,capacity,max_t,fused) + } + /// Same construction over any retained MTP role bank (the pinned pack, or + /// the Original-literal RT directory bank of `select_rt_mtp`). + #[allow(clippy::too_many_arguments)] + pub(in crate::qwen_forward) fn new_with_mtp_weights(binding:&ModelBinding,dense:&DenseWeightCache<'ctx>, + session:&mut QwenSession<'ctx>,context:&'ctx Context<'ctx>,retained:RetainedOriginalMtpWeights<'ctx>, + embedding:&OriginalPromptEmbedding<'ctx>,capacity:usize,max_t:usize,fused:bool, + )->Result{ + if binding.layer_count()!=48||!(1..=8192).contains(&capacity)||!(1..=8).contains(&max_t) + ||dense.native_prompt_capacity(binding,context)?!=capacity + ||!std::ptr::eq(context,session.mtp_context()?){return Err(Error::IdentityMismatch);} + let mut owner=Self{context,binding:binding.identity(),capacity,fused,prompt:None,gdn:None,qsa:None, + transport:None,attention:None,mtp_prefill:None,mtp_scalar:None,mtp_scalar_weights:None, + mtp_weights:None,mtp_full:None,max_t,layers:std::array::from_fn(|_|None),failed:false}; + let result=(||{ + owner.prompt=Some(context.original_prompt_device(capacity,PleBf16Mode::HighOnly,GrNativeProfile::HighOnly).map_err(driver_error)?); + owner.gdn=Some(context.original_gdn_prompt_device(capacity,GrNativeProfile::HighOnly).map_err(driver_error)?); + owner.qsa=Some(context.original_qsa_resident_prompt_device(capacity,QsaNativePacking::HighOnly).map_err(driver_error)?); + owner.transport=Some(context.original_qsa_resident_transport().map_err(driver_error)?); + owner.attention=Some(context.original_qsa_resident_attention(capacity).map_err(driver_error)?); + owner.mtp_prefill=Some(context.original_mtp_prefill().map_err(driver_error)?); + owner.mtp_scalar_weights=Some(retained.scalar_prefill_weights(binding,context,embedding)?); + owner.mtp_weights=Some(retained); + owner.mtp_scalar=Some(context.original_mtp_scalar_prefill(max_t,capacity).map_err(driver_error)?); + let mut workspace=dense.native_batch_workspace(binding,context)?.ok_or(Error::IdentityMismatch)?; + for layer in binding.ordered_layers(){if layer.kind()==BoundLayerKind::Qsa{ + let id=LayerId::new(layer.index()as u64,Dimension::new(48)?)?; + let empty=session.original_qsa_seed(binding,id)?; + let index=context.original_qsa_resident_index().map_err(driver_error)?; + let kv=context.qsa_prompt_kv().map_err(driver_error)?.into_original_mapped_journal().map_err(driver_error)?; + owner.layers[layer.index()as usize]=Some(ResidentQsaLayer::new(binding,dense,session,&empty,index,kv,&mut workspace)?); + }} + drop(workspace); + let priors=std::array::from_fn(|slot|owner.layers[slot].as_ref().map(ResidentQsaLayer::current)); + session.install_original_qsa_seed_set(binding,priors)?;Ok(()) + })(); + if let Err(primary)=result{let _=owner.close_inner();return Err(primary);} + Ok(owner) + } + /// The immutable MTP roles this executor retains (the RT bank's on the product path). + pub(in crate::qwen_forward) fn retained_mtp_weights(&self)->Option<&RetainedOriginalMtpWeights<'ctx>>{self.mtp_weights.as_ref()} + /// Joins the source-created full MTP graph owner to this exact prompt + /// executor. The draft session is validated against the same target + /// session before it leaves the assembly, so callers cannot pair a full + /// graph with a separately allocated MTP ring. + pub(in crate::qwen_forward) fn install_full_mtp(&mut self,binding:&ModelBinding, + session:&QwenSession<'ctx>,assembly:OriginalMtpFullAssembly<'ctx>)->Result>{ + if self.failed||self.context.is_poisoned()||!self.binding.matches(&binding.identity()) + ||!std::ptr::eq(self.context,session.mtp_context()?)||self.mtp_full.is_some(){return Err(Error::IdentityMismatch);} + assembly.draft.checkpoint(binding,session)?; + assembly.owner.validate(binding,self.context,self.max_t)?; + self.mtp_full=Some(assembly.owner); + Ok(assembly.draft) + } + /// Source-level MTP selection, the `--mtp DIR` branch of generate.cpp + /// (`mtp.load` ... `mtp.bind`): load the RT directory banks (dense.txt, + /// dense.bin, experts.bin, nine-name check), build the prompt executor over + /// those exact retained roles, then bind the native head (optional + /// draft_vocab subset), the shared scalar/full/ring layout, the coupled + /// setup and the actor, and install the matching draft session. + /// + /// Returns both owners; the draft session is the sole mutator of the + /// ring, the executor holds the actor. Any failure releases everything + /// built so far through the owners' own closure order. + #[allow(clippy::too_many_arguments)] + pub(in crate::qwen_forward) fn select_rt_mtp(binding:&ModelBinding,dense:&DenseWeightCache<'ctx>, + session:&mut QwenSession<'ctx>,context:&'ctx Context<'ctx>,embedding:&OriginalPromptEmbedding<'ctx>, + output:&OriginalNativeOutput<'ctx>,rt_directory:&std::path::Path,capacity:usize,fused:bool, + request:&OriginalMtpRequest)->std::result::Result<(Self,OriginalDraftSession<'ctx>),OriginalMtpLoadError>{ + if !(1..=8).contains(&request.max_t)||request.prompt_capacity!=capacity||binding.layer_count()!=48{ + return Err(Error::IdentityMismatch.into());} + let bank=context.original_mtp_rt_bank(rt_directory,binding.expert_count() as usize)?; + let retained=RetainedOriginalMtpWeights::from_rt_bank(binding,context,&bank)?; + // The bank object is only a loader receipt: every allocation it holds is + // shared with (or retained alongside) `retained`. + drop(bank); + let mut executor=Self::new_with_mtp_weights(binding,dense,session,context,retained.clone(),embedding, + capacity,request.max_t,fused)?; + let assembly=OriginalMtpFullOwner::assemble_rt(binding,session,context,&retained,embedding,output,request,rt_directory)?; + let draft=executor.install_full_mtp(binding,session,assembly)?; + Ok((executor,draft)) + } + /// The loaded `MtpDrafter` of this executor. The caller still borrows the + /// ring through the draft session (`with_pending_ring`, + /// `with_mtp_transition_ring`), which keeps SessionState as the sole mutable + /// authority for its snapshot. + pub(in crate::qwen_forward) fn mtp_actor(&mut self,binding:&ModelBinding) + ->Result<&mut leleka_cuda_driver::OriginalMtpActor<'ctx>>{ + let(context,max_t)=(self.context,self.max_t); + self.mtp_full.as_mut().ok_or(Error::IdentityMismatch)?.actor_mut(binding,context,max_t) + } + /// generate.cpp `mtp.set_prompt_len(n)`. + pub(in crate::qwen_forward) fn set_mtp_prompt_len(&mut self,binding:&ModelBinding,n:i64)->Result<()> { + self.mtp_actor(binding)?.set_prompt_len(n);Ok(()) + } + /// generate.cpp `mtp.set_max_drafts(S_mtp - 1)`. + pub(in crate::qwen_forward) fn set_mtp_max_drafts(&mut self,binding:&ModelBinding,k:i32)->Result<()> { + self.mtp_actor(binding)?.set_max_drafts(k);Ok(()) + } + /// `MtpDrafter::idle()`: drain its own capture stream, nothing else. + pub(in crate::qwen_forward) fn mtp_idle(&mut self,binding:&ModelBinding)->Result<()> { + self.mtp_actor(binding)?.idle().map_err(driver_error) + } + /// End of a request's verifier: release what the MTP drafter bound to that verifier's bank (its cached round programs read the + /// bank's final-R span and its tail keeps the last staged window), so the bank can close and the next request's first draft + /// captures against its own bank. See `OriginalMtpActor::release_verifier_bindings`. + pub(in crate::qwen_forward) fn mtp_release_verifier(&mut self,binding:&ModelBinding)->Result<()> { + self.mtp_actor(binding)?.release_verifier_bindings().map_err(driver_error) + } + /// `MtpDrafter::device()`. + pub(in crate::qwen_forward) fn mtp_device(&mut self,binding:&ModelBinding)->Result { + Ok(self.mtp_actor(binding)?.device()) + } + /// generate.cpp `if (resume > 0 && reread_to <= 0) mtp.kv_restore(resume)` + /// on the retained ring of the CURRENT, already restored target branch. + pub(in crate::qwen_forward) fn mtp_kv_restore(&mut self,binding:&ModelBinding, + session:&QwenSession<'ctx>,draft:&mut OriginalDraftSession<'ctx>,upto:i64)->Result<()> { + let origin=session.target_origin()?; + let actor=self.mtp_actor(binding)?; + draft.with_mtp_current_ring(binding,session,&origin,|ring,prior|actor.kv_restore(ring,prior,upto).map_err(driver_error)) + } + /// One-way handoff of the twelve resident QSA layers (index image + mapped K/V) to the native + /// verifier for a decode phase. All twelve are validated before any is moved, so a refusal leaves the + /// executor whole. While the owners are out the executor cannot run a prompt transaction; `adopt_qsa_owners` + /// takes the very same physical owners back. + #[allow(clippy::type_complexity)] + pub(in crate::qwen_forward) fn take_qsa_owners(&mut self)->Result<[Option<(leleka_cuda_driver::OriginalQsaResidentIndex<'ctx>, + leleka_cuda_driver::OriginalQsaMappedJournal<'ctx>)>;48]>{ + if self.failed||self.context.is_poisoned(){return Err(Error::CudaExecution);} + for layer in self.layers.iter().flatten(){layer.check_handoff()?;} + if self.layers.iter().flatten().count()!=12{return Err(Error::IdentityMismatch);} + let mut owners:[Option<(leleka_cuda_driver::OriginalQsaResidentIndex<'ctx>,leleka_cuda_driver::OriginalQsaMappedJournal<'ctx>)>;48]= + std::array::from_fn(|_|None); + for(slot,layer)in self.layers.iter_mut().enumerate(){if let Some(layer)=layer.take(){ + // the session keeps the lineage prior; only the physical owners travel + let(index,kv,_prior)=layer.into_verifier_owners()?;owners[slot]=Some((index,kv)); + }} + Ok(owners) + } + /// The reverse of `take_qsa_owners`, after the verifier closed and its journal returned the owners. + /// Each layer is rebuilt at the session's current lineage witness and its physical image rolled back to + /// it (a no-op copy when the last window committed; the repair when a window was abandoned). The + /// roll-back mints a fresh witness object per layer for the SAME lineage, so the session adopts those + /// objects before the layers can be used again (a layer and the session must name one witness). + #[allow(clippy::type_complexity)] + pub(in crate::qwen_forward) fn adopt_qsa_owners(&mut self,binding:&ModelBinding,dense:&DenseWeightCache<'ctx>, + session:&mut QwenSession<'ctx>,owners:[Option<(leleka_cuda_driver::OriginalQsaResidentIndex<'ctx>, + leleka_cuda_driver::OriginalQsaMappedJournal<'ctx>)>;48])->Result<()>{ + if self.failed||self.context.is_poisoned()||self.layers.iter().any(Option::is_some){return Err(Error::IdentityMismatch);} + let witnesses=session.original_qsa_witnesses()?; + let context=dense.retained_context(binding,session.mtp_context()?)?; + let mut workspace=dense.native_batch_workspace(binding,context)?.ok_or(Error::IdentityMismatch)?; + let mut first=None; + for(slot,owner)in owners.into_iter().enumerate(){if let Some((index,kv))=owner{ + let rebuilt=witnesses[slot].clone().ok_or(Error::IdentityMismatch).and_then(|prior| + ResidentQsaLayer::from_verifier_owners(binding,dense,session,index,kv,prior,&mut workspace)); + match rebuilt{Ok(layer)=>self.layers[slot]=Some(layer),Err(error)=>{first.get_or_insert(error);}} + }} + drop(workspace); + if let Some(error)=first{self.failed=true;return Err(error);} + let current:[Option>;48]=std::array::from_fn(|slot|self.layers[slot].as_ref().map(ResidentQsaLayer::current)); + let adopted=session.adopt_original_qsa_witnesses(current); + if adopted.is_err(){self.failed=true;} + adopted + } + /// The session's Original checkpoint (position, predecessors, PLE/GDN priors and the twelve resident QSA + /// witnesses). Refused while the recurrent priors lag a verified-window publication. + pub(in crate::qwen_forward) fn checkpoint_session(&mut self,binding:&ModelBinding, + session:&mut QwenSession<'ctx>)->Result>{ + if self.failed||self.context.is_poisoned(){return Err(Error::CudaExecution);} + if self.layers.iter().flatten().count()!=12{return Err(Error::IdentityMismatch);} + session.original_checkpoint(binding) + } + /// Prefix cache: park the point the session stands at (see `ParkedSession`). + pub(in crate::qwen_forward) fn park_session(&mut self,binding:&ModelBinding, + session:&mut QwenSession<'ctx>)->Result{ + if self.failed||self.context.is_poisoned(){return Err(Error::CudaExecution);} + if self.layers.iter().flatten().count()!=12{return Err(Error::IdentityMismatch);} + session.park_original(binding,&self.layers) + } + /// Prefix cache: the cells `first..first + tokens` of the twelve layers as plain bytes. + pub(in crate::qwen_forward) fn park_block(&self,session:&QwenSession<'ctx>,first:usize,tokens:usize)->Result{ + if self.failed||self.context.is_poisoned(){return Err(Error::CudaExecution);} + if self.layers.iter().flatten().count()!=12{return Err(Error::IdentityMismatch);} + session.park_block(&self.layers,first,tokens) + } + /// Prefix cache: make the session and the twelve layers stand at `parked`, writing `blocks`. A failure poisons + /// the executor, as for `restore_session`. + pub(in crate::qwen_forward) fn import_session(&mut self,binding:&ModelBinding,dense:&DenseWeightCache<'ctx>, + session:&mut QwenSession<'ctx>,parked:&ParkedSession,blocks:&[&ParkedBlock])->Result<()>{ + if self.failed||self.context.is_poisoned(){return Err(Error::CudaExecution);} + let imported=session.import_parked(binding,dense,&mut self.layers,parked,blocks); + if imported.is_err(){self.failed=true;} + imported + } + /// Roll the session AND the twelve physical resident layers back to `checkpoint` (a request reset to the + /// empty prompt, or an abandoned prompt transaction). A failure poisons the executor. + pub(in crate::qwen_forward) fn restore_session(&mut self,binding:&ModelBinding,dense:&DenseWeightCache<'ctx>, + session:&mut QwenSession<'ctx>,checkpoint:&OriginalSessionCheckpoint<'ctx>)->Result<()>{ + if self.failed||self.context.is_poisoned(){return Err(Error::CudaExecution);} + let restored=session.restore_original_checkpoint(binding,dense,&mut self.layers,checkpoint); + if restored.is_err(){self.failed=true;} + restored + } + /// Whether the twelve resident layers are home (a prompt transaction can run). + pub(in crate::qwen_forward) fn qsa_owners_home(&self)->bool{self.layers.iter().flatten().count()==12} + pub(in super::super) fn validate(&self,binding:&ModelBinding,dense:&DenseWeightCache<'ctx>,session:&QwenSession<'ctx>)->Result<()> { + if self.failed||self.context.is_poisoned(){return Err(Error::CudaExecution);} + if !self.binding.matches(&binding.identity())||!std::ptr::eq(self.context,session.mtp_context()?) + ||dense.native_prompt_capacity(binding,self.context)?!=self.capacity{return Err(Error::IdentityMismatch);} + dense.validate(binding)?;Ok(()) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2.rs b/crates/leleka-runtime/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2.rs new file mode 100644 index 00000000..4ae5f58b --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2.rs @@ -0,0 +1,246 @@ +//! Moved out of the parent module by STRA-338: impl OriginalPromptExecutor (2). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalPromptExecutor<'ctx>{ + /// No target position is advanced here. Every read is actual GR arithmetic; + /// recurrent/KV/PLE seals belong to the same still-private source transaction. + #[allow(clippy::too_many_arguments)] + pub(in crate::qwen_forward) fn forward<'session,'program,'loan>( + &'program mut self,binding:&'program ModelBinding,dense:&'program DenseWeightCache<'ctx>, + session:&'session mut QwenSession<'ctx>,source:&std::rc::Rc,count:usize, + mut kar:Option<&mut KarPleCache<'ctx>>,moe:&mut MoeWeightCache<'ctx>, + arena:&mut OriginalPrefillArena<'loan,'ctx>, + draft:&'program mut OriginalDraftSession<'ctx>,embedding:&OriginalPromptEmbedding<'ctx>, + policy:&OriginalMtpScalarPolicy,mut cancelled:impl FnMut()->bool, + )->Result>{ + self.validate(binding,dense,session)?; + let first_position=session.target_origin()?.next_position(); + let tokens=source.window(binding,first_position,count)?; + crate::bringup_trace!("DBG[{:.0}s] forward: tokens={} self.capacity={} arena.capacity={} count={count}",crate::qwen_forward::original_serve_stack::dbg_el(),tokens.len(),self.capacity,arena.capacity()); + let _launch_sync=leleka_cuda_driver::PromptSyncTrace::enter(); + if tokens.is_empty()||tokens.len()>self.capacity||arena.capacity()!=self.capacity{return Err(Error::InvalidDimension);} + let checkpoint=session.original_checkpoint(binding)?; + let draft_checkpoint=draft.checkpoint(binding,session)?; + let mut txn=OriginalPromptTxn::begin(session,binding,source,count)?; + let profile_context=self.context; + let drain=Some(profile_context as &dyn prof::Drain); + let operation=(||{ + // The last prompt seed belongs to Original Verifier. Every row + // admitted here must have its authentic next token in the source. + txn.known_prompt_next()?.ok_or(Error::IdentityMismatch)?; + let input_span=prof::span(PStage::Input,None); + // KAR inputs are staged chunk-wide: embeddings broadcast and PLE rows decoded on the device + // (LELEKA_PREFILL_STAGED_INPUT=0: the per-token host path, the A/B arm). + let mut staged_input=None;let mut staged_ple=None;let mut first_predecessors:Option<[i32;2]>=None; + if binding.kar_ple_binding().is_some()&&staged_input_enabled(){ + let mut staged=StagedInput::default(); + for &token in tokens{ + txn.stage_input(|step|{let pos=step.position(); + if first_predecessors.is_none(){first_predecessors=Some(step.input_predecessors()?);} + match kar.as_deref(){ + Some(cache)=>InputStage::consume_kar_deferred(binding,cache,token,pos,step,&mut staged), + None=>Err(Error::IdentityMismatch), + } + })?; + } + let cache=kar.as_deref_mut().ok_or(Error::IdentityMismatch)?; + let kar_binding=binding.kar_ple_binding().ok_or(Error::IdentityMismatch)?; + let _ple_span=prof::span(PStage::InputPle,None); + staged_ple=Some(cache.stage_batch(kar_binding,staged.ple_rows())?); + staged_input=Some(staged); + }else{ + for &token in tokens{ + txn.stage_input(|step|{let pos=step.position(); + match (binding.kar_ple_binding(),kar.as_deref_mut()){ + (None,None)=>InputStage::consume(binding,token,pos,step), + (Some(_),Some(cache))=>InputStage::consume_kar(binding,cache,token,pos,step), + _=>Err(Error::IdentityMismatch), + } + })?; + } + } + drop(input_span); + let init_span=prof::span(PStage::Initialize,drain); + let mut sources=Vec::new();sources.try_reserve_exact(tokens.len()).map_err(|_|Error::InputAllocation)?; + let sources_span=prof::span(PStage::InitSources,None); + for local in 0..tokens.len(){sources.push(PromptDeviceSource::from_original(binding,self.context,&txn,local)?);} + drop(sources_span); + let upload_span=prof::span(PStage::InitUpload,drain); + let prompt=self.prompt.as_mut().ok_or(Error::IdentityMismatch)?; + let lease=arena.begin_rows(tokens.len()).map_err(driver_error)?; + let rows=match (staged_input.as_ref(),staged_ple){ + (Some(input),Some(ple))=>{ + let cache=kar.as_deref_mut().ok_or(Error::IdentityMismatch)?; + let result={ + let (ple_cache,ple_books)=cache.device_parts(); + let stage=PromptInputStage{embedding_rows:input.embedding_rows(),embedding_index:input.embedding_index(), + ple_cache,ple_books,ple_updates:ple.updates(),ple_slots:ple.slots()}; + PromptDeviceRows::initialize(binding,dense,self.context,prompt,lease,sources,Some(stage)) + }; + match result{ + Ok(rows)=>{cache.commit(ple);rows}, + // the device may already hold part of the scatter: the cache is not trusted again + Err(error)=>{cache.invalidate();return Err(error);}, + } + }, + _=>PromptDeviceRows::initialize(binding,dense,self.context,prompt,lease,sources,None)?, + }; + drop(upload_span);drop(init_span); + // The PLE packets of the next chunk are read from the archive on a thread of their own while this chunk computes + // (they are a function of the tokens and the archive only); `stage_batch` of that chunk takes them from there. + if let (Some(cache),Some(kar_binding),Some(mut before))=(kar.as_deref_mut(),binding.kar_ple_binding(),first_predecessors){ + let next_first=first_position+tokens.len() as u64; + let want=self.capacity.min(source.len().saturating_sub(next_first as usize)); + if want>0{ + if let Ok(next)=source.window(binding,next_first,want){ + for &token in tokens{before=[before[1],token.get() as i32];} + if let Ok(rows)=InputStage::ple_rows_ahead(binding,before,next){cache.read_ahead(kar_binding,&rows);} + } + } + } + let mut carrier=Carrier::Plain(rows); + for layer in binding.ordered_layers(){ + let index=layer.index();let role=super::super::super::super::gr::GrRole::Attention(index); + crate::bringup_trace!("DBG[{:.0}s] forward layer {index} {:?} begin",crate::qwen_forward::original_serve_stack::dbg_el(),layer.kind()); + if index==1{ + let Carrier::Plain(mut rows)=carrier else{return Err(Error::IdentityMismatch);}; + {let _span=prof::span(PStage::Validate,None);rows.validate_original_rows(binding,dense)?;} + let _span=prof::span(PStage::Ple,drain); + let prior=txn.ple_prior()?; + let mut history=InputStage::prepare_original_prompt_history(binding,dense,self.context,&txn)?; + rows=rows.apply_ple(binding,dense,prompt,&mut history)?; + InputStage::finish_original_prompt_history(binding,&txn,&prior,history)?; + // The completed PLE operation changes the real row state. + // Its output must pass fresh current-row validation. + carrier=Carrier::Plain(rows); + } + let mut read=match carrier{ + Carrier::Plain(mut rows)=>{ + {let _span=prof::span(PStage::Validate,None);rows.validate_original_rows(binding,dense)?;} + let _span=prof::span(PStage::AttnRead,drain); + rows.read(binding,dense,prompt,role)? + }, + Carrier::Normed(mut rows)=>{ + {let _span=prof::span(PStage::Validate,None);rows.validate_original_rows(binding,dense)?;} + let _span=prof::span(PStage::AttnRead,drain); + rows.read(binding,dense,prompt)? + }, + }; + crate::bringup_trace!("DBG[{:.0}s] L{index} attn-read ok",crate::qwen_forward::original_serve_stack::dbg_el()); + {let _span=prof::span(PStage::Validate,None);read.validate_original_rows(binding,dense)?;} + let mixer_span=prof::span(match layer.kind(){BoundLayerKind::Gdn=>PStage::Gdn,BoundLayerKind::Qsa=>PStage::Qsa},drain); + let mut ffn=if self.fused { + let rows=match layer.kind(){ + BoundLayerKind::Gdn=>read.complete_original_gdn_normed(binding,dense,&txn,prompt,self.gdn.as_mut().ok_or(Error::IdentityMismatch)?)?, + BoundLayerKind::Qsa=>read.complete_original_qsa_normed(binding,dense,&txn,prompt,self.layers[index as usize].as_mut().ok_or(Error::IdentityMismatch)?, + self.qsa.as_mut().ok_or(Error::IdentityMismatch)?,self.transport.as_mut().ok_or(Error::IdentityMismatch)?,self.attention.as_mut().ok_or(Error::IdentityMismatch)?)?, + };Carrier::Normed(rows) + }else{ + let rows=match layer.kind(){ + BoundLayerKind::Gdn=>read.complete_original_gdn(binding,dense,&txn,prompt,self.gdn.as_mut().ok_or(Error::IdentityMismatch)?)?, + BoundLayerKind::Qsa=>read.complete_original_qsa(binding,dense,&txn,prompt,self.layers[index as usize].as_mut().ok_or(Error::IdentityMismatch)?, + self.qsa.as_mut().ok_or(Error::IdentityMismatch)?,self.transport.as_mut().ok_or(Error::IdentityMismatch)?,self.attention.as_mut().ok_or(Error::IdentityMismatch)?)?, + };Carrier::Plain(rows) + }; + drop(mixer_span); + crate::bringup_trace!("DBG[{:.0}s] L{index} mixer ok",crate::qwen_forward::original_serve_stack::dbg_el()); + {let _span=prof::span(PStage::Validate,None);match &mut ffn{ + Carrier::Plain(rows)=>{rows.validate_original_rows(binding,dense)?;}, + Carrier::Normed(rows)=>{rows.validate_original_rows(binding,dense)?;}, + };} + crate::bringup_trace!("DBG[{:.0}s] L{index} ffn-validate ok",crate::qwen_forward::original_serve_stack::dbg_el()); + let ffn_span=prof::span(PStage::FfnRead,drain); + let mut read=match ffn{ + Carrier::Plain(rows)=>rows.read(binding,dense,prompt,super::super::super::super::gr::GrRole::Ffn(index))?, + Carrier::Normed(rows)=>rows.read(binding,dense,prompt)?, + }; + drop(ffn_span); + {let _span=prof::span(PStage::Validate,None);read.validate_original_rows(binding,dense)?;} + let moe_span=prof::span(PStage::Moe,drain); + // Literal fused GR norm is prohibited across PLE and final head. + carrier=if self.fused&&index!=0&&index!=47{ + Carrier::Normed(read.complete_original_moe_normed(binding,dense,moe,prompt)?) + }else{Carrier::Plain(read.complete_original_moe(binding,dense,moe,prompt)?)}; + drop(moe_span); + crate::bringup_trace!("DBG[{:.0}s] L{index} moe ok",crate::qwen_forward::original_serve_stack::dbg_el()); + } + let Carrier::Plain(mut rows)=carrier else{return Err(Error::IdentityMismatch);}; + // the chunk's expert stream (if any) ended with the last MoE layer; never carried past the layers + moe.end_prompt_stream()?; + let final_span=prof::span(PStage::Final,drain); + crate::bringup_trace!("DBG[{:.0}s] forward: all layers ok, final row",crate::qwen_forward::original_serve_stack::dbg_el()); + let final_row=rows.preview_conditioning(binding,dense,&txn).map_err(|e|{crate::bringup_trace!("DBG[{:.0}s] preview_conditioning err {e:?}",crate::qwen_forward::original_serve_stack::dbg_el());e})?; + crate::bringup_trace!("DBG[{:.0}s] final_row ok",crate::qwen_forward::original_serve_stack::dbg_el()); + // Bring-up gate (LELEKA_TRACE_PREFILL_R=1): FNV-1a of the bits of every row of the chunk's final residual R + // (all four streams), for bit-exact A/B comparison of prefill variants. Slow (one drain per row); off by default. + if std::env::var_os("LELEKA_TRACE_PREFILL_R").is_some(){ + let first=txn.start_position();let count=txn.len(); + let hash=rows.with_final_residual(binding,dense,&txn,&final_row,|residual|{ + let mut hash=0xcbf29ce484222325u64;let mut rows_hash=Vec::with_capacity(count); + for index in 0..count{ + let row=residual.read_prompt_row(index).map_err(driver_error)?; + let mut row_hash=0xcbf29ce484222325u64; + for value in row.iter(){for byte in value.to_le_bytes(){row_hash^=u64::from(byte);row_hash=row_hash.wrapping_mul(0x100000001b3);}} + hash^=row_hash;hash=hash.wrapping_mul(0x100000001b3);rows_hash.push(row_hash); + } + Ok((hash,rows_hash)) + })?; + eprintln!("PREFILL-R first={first} rows={count} fnv1a64={:016x} first_row={:016x} last_row={:016x}",hash.0,hash.1[0],hash.1[count-1]); + } + let sample=OriginalPromptSample::conditioning(binding,&final_row,&txn).map_err(|e|{crate::bringup_trace!("DBG[{:.0}s] sample conditioning err {e:?}",crate::qwen_forward::original_serve_stack::dbg_el());e})?; + crate::bringup_trace!("DBG[{:.0}s] sample ok",crate::qwen_forward::original_serve_stack::dbg_el()); + drop(final_span); + let draft_span=prof::span(PStage::DraftKv,drain); + let producer=self.mtp_prefill.as_mut().ok_or(Error::IdentityMismatch)?; + // The scalar (short prompt) fallback must run on the drafter's OWN scalar owner: the ring of the shared layout is paired + // with that owner's main arena, a standalone owner is refused with InvalidQwenShape. + let (context,max_t)=(self.context,self.max_t); + let scalar=self.mtp_full.as_mut().ok_or(Error::IdentityMismatch)?.actor_mut(binding,context,max_t)?; + let scalar_weights=std::rc::Rc::clone(self.mtp_scalar_weights.as_ref().ok_or(Error::IdentityMismatch)?); + let retained_mtp=self.mtp_weights.clone().ok_or(Error::IdentityMismatch)?; + let draft_kv=draft.with_pending_ring(binding,&txn,|ring,prior,first_needed|{ + crate::bringup_trace!("DBG[{:.0}s] draft ring open first_needed={first_needed:?}",crate::qwen_forward::original_serve_stack::dbg_el()); + let mut workspace=dense.native_batch_workspace(binding,self.context)?.ok_or(Error::IdentityMismatch)?; + let outcome=rows.record_original_draft_kv(binding,dense,moe,&txn,&final_row,sample.next(), + producer,&mut workspace,ring,prior,embedding.borrow(binding,self.context)?,first_needed,&policy.kv,&mut cancelled)?; + crate::bringup_trace!("DBG[{:.0}s] record_original_draft_kv -> {}",crate::qwen_forward::original_serve_stack::dbg_el(),match &outcome{OriginalPromptDraftOutcome::Completed(_)=>"Completed",OriginalPromptDraftOutcome::Fallback(reason)=>{crate::bringup_trace!("DBG fallback reason: {reason:?}");"Fallback"},OriginalPromptDraftOutcome::Skipped=>"Skipped",OriginalPromptDraftOutcome::Cancelled=>"Cancelled"}); + let outcome=match outcome{ + OriginalPromptDraftOutcome::Fallback(_)=>rows.record_original_scalar_draft_kv( + binding,dense,&retained_mtp,&txn,&final_row,sample.next(),scalar,&mut workspace,ring,prior, + scalar_weights,first_needed,policy,&mut cancelled)?, + other=>other, + }; + crate::bringup_trace!("DBG[{:.0}s] after scalar fallback -> {}",crate::qwen_forward::original_serve_stack::dbg_el(),match &outcome{OriginalPromptDraftOutcome::Completed(_)=>"Completed",OriginalPromptDraftOutcome::Fallback(_)=>"Fallback",OriginalPromptDraftOutcome::Skipped=>"Skipped",OriginalPromptDraftOutcome::Cancelled=>"Cancelled"}); + match outcome{ + OriginalPromptDraftOutcome::Completed(completed)=>Ok(completed), + // Optional unported storage and actual no-materialization + // need separate genuine outcomes; refusal advances neither. + OriginalPromptDraftOutcome::Fallback(_)|OriginalPromptDraftOutcome::Skipped| + OriginalPromptDraftOutcome::Cancelled=>Err(Error::Unsupported(Stage::Session)), + } + }).map_err(|e|{crate::bringup_trace!("DBG[{:.0}s] with_pending_ring err {e:?}",crate::qwen_forward::original_serve_stack::dbg_el());e})?; + crate::bringup_trace!("DBG[{:.0}s] forward: draft kv ok",crate::qwen_forward::original_serve_stack::dbg_el()); + drop(draft_span); + if cancelled(){return Err(Error::Unsupported(Stage::Session));} + let _span=prof::span(PStage::FinishPreview,drain); + rows.finish_after_preview(binding,dense,&txn,&final_row).map_err(|e|{crate::bringup_trace!("DBG[{:.0}s] finish_after_preview err {e:?}",crate::qwen_forward::original_serve_stack::dbg_el());e})?; + Ok((final_row,sample,draft_kv)) + })(); + match operation{ + Err(primary)=>{ + crate::bringup_trace!("DBG[{:.0}s] forward operation failed: {primary:?}",crate::qwen_forward::original_serve_stack::dbg_el()); + // stop the chunk's expert stream before the transaction rolls back + if moe.end_prompt_stream().is_err(){self.failed=true;} + let cleanup=txn.abort_with_draft(binding,dense,&mut self.layers,&checkpoint,draft,&draft_checkpoint); + if cleanup.is_err()||self.context.is_poisoned(){self.failed=true;} + Err(primary) + }, + Ok((completed,sample,draft_kv))=>Ok(OriginalPromptPending{txn:Some(txn),binding,dense,layers:&mut self.layers, + failed:&mut self.failed,checkpoint,completed,sample,draft_kv,draft,draft_checkpoint}), + } + } + pub(in crate::qwen_forward) fn close(mut self)->Result<()>{self.close_inner()} +} diff --git a/crates/leleka-runtime/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_3.rs b/crates/leleka-runtime/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_3.rs new file mode 100644 index 00000000..4c89860d --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_3.rs @@ -0,0 +1,20 @@ +//! Moved out of the parent module by STRA-338: impl OriginalPromptExecutor (3). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> OriginalPromptExecutor<'ctx>{ + pub(in super::super) fn close_inner(&mut self)->Result<()>{ + let mut first=None; + macro_rules! retire {($v:expr)=>{if let Some(owner)=$v.take(){if let Err(e)=owner.close().map_err(driver_error){first.get_or_insert(e);}}};} + retire!(self.prompt);retire!(self.gdn);retire!(self.qsa);retire!(self.transport);retire!(self.attention); + retire!(self.mtp_prefill); + retire!(self.mtp_scalar); + self.mtp_scalar_weights.take(); + self.mtp_weights.take(); + if let Some(owner)=self.mtp_full.take(){if let Err(error)=owner.close(){first.get_or_insert(error);}} + for slot in &mut self.layers{if let Some(layer)=slot.take(){if let Err(e)=layer.close(){first.get_or_insert(e);}}} + self.failed=true;first.map_or(Ok(()),Err) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/executor_prefill_chunk/impl_qwenforward.rs b/crates/leleka-runtime/src/qwen_forward/executor_prefill_chunk/impl_qwenforward.rs index 4e86cb87..1e13d656 100644 --- a/crates/leleka-runtime/src/qwen_forward/executor_prefill_chunk/impl_qwenforward.rs +++ b/crates/leleka-runtime/src/qwen_forward/executor_prefill_chunk/impl_qwenforward.rs @@ -3,1264 +3,9 @@ #[allow(unused_imports)] use super::*; - -impl QwenForward { - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(crate) fn test_chunk_on_loaded<'driver>( - binding: &ModelBinding, - session: &mut QwenSession<'driver>, - output: &OutputStage<'_, '_>, - kar: &mut KarPleCache<'_>, - moe: &mut MoeWeightCache<'driver>, - dense: &DenseWeightCache<'_>, - ) { - check_chunk_on_loaded(binding, session, output, kar, moe, dense); - } - - #[allow(clippy::too_many_arguments)] - pub(crate) fn prefill_chunk_mmq_joint<'driver>( - binding: &ModelBinding, - tokens: &[TokenId], - known_next: Option, - session: &mut QwenSession<'driver>, - draft: &mut crate::qwen_forward::mtp_decode::MtpDecoder, - output: &OutputStage<'_, '_>, - kar_cache: Option<&mut KarPleCache<'_>>, - moe_cache: &mut MoeWeightCache<'driver>, - dense_cache: &DenseWeightCache<'_>, - host_remaining: usize, - mut cancelled: impl FnMut() -> bool, - ) -> Result> { - let mut txn = Self::prepare_prefill_chunk_with_policy( - binding, - tokens, - known_next, - session, - output, - kar_cache, - moe_cache, - dense_cache, - host_remaining, - &mut cancelled, - ChunkMoePolicy::ExperimentalResidentMmq, - )?; - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - let ready = draft.stage_prefill_chunk(binding, &mut txn, moe_cache, &mut cancelled)?; - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - Ok(txn.publish_joint(ready)?.into_target_product()) - } - #[allow(clippy::too_many_arguments)] - pub(crate) fn prefill_chunk_cached_joint<'driver>( - binding: &ModelBinding, - tokens: &[TokenId], - known_next: Option, - session: &mut QwenSession<'driver>, - draft: &mut super::super::super::mtp_decode::MtpDecoder, - output: &OutputStage<'_, '_>, - kar_cache: Option<&mut KarPleCache<'_>>, - moe_cache: &mut MoeWeightCache<'driver>, - dense_cache: &DenseWeightCache<'_>, - host_remaining: usize, - mut cancelled: impl FnMut() -> bool, - ) -> Result> { - let mut txn = Self::prepare_prefill_chunk_cached( - binding, - tokens, - known_next, - session, - output, - kar_cache, - moe_cache, - dense_cache, - host_remaining, - &mut cancelled, - )?; - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - let ready: super::super::super::mtp_decode::ReadyMtpChunk<'_, '_> = - draft.stage_prefill_chunk(binding, &mut txn, moe_cache, &mut cancelled)?; - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - Ok(txn.publish_joint(ready)?.into_target_product()) - } - - #[allow(clippy::too_many_arguments)] - pub(in crate::qwen_forward) fn prepare_prefill_chunk_cached<'session, 'driver>( - binding: &ModelBinding, - tokens: &[TokenId], - known_next: Option, - session: &'session mut QwenSession<'driver>, - output: &OutputStage<'_, '_>, - kar_cache: Option<&mut KarPleCache<'_>>, - moe_cache: &mut MoeWeightCache<'driver>, - dense_cache: &DenseWeightCache<'_>, - host_remaining: usize, - cancelled: impl FnMut() -> bool, - ) -> Result> { - Self::prepare_prefill_chunk_with_policy( - binding, - tokens, - known_next, - session, - output, - kar_cache, - moe_cache, - dense_cache, - host_remaining, - cancelled, - ChunkMoePolicy::Native, - ) - } - /// Explicit private outer256 experiment. Only the original native MoE - /// arithmetic is selected here; existing normal serving stays outer64. - #[allow(clippy::too_many_arguments)] - pub(in crate::qwen_forward) fn prefill_chunk_windowed256_joint<'driver>( - binding: &ModelBinding, - tokens: &[TokenId], - known_next: Option, - session: &mut QwenSession<'driver>, - draft: &mut super::super::super::mtp_decode::MtpDecoder, - output: &OutputStage<'_, '_>, - kar_cache: Option<&mut KarPleCache<'_>>, - moe_cache: &mut MoeWeightCache<'driver>, - dense_cache: &DenseWeightCache<'_>, - host_remaining: usize, - mut cancelled: impl FnMut() -> bool, - ) -> Result> { - let mut txn = Self::prepare_prefill_chunk_with_policy_windowed( - binding, - tokens, - known_next, - session, - output, - kar_cache, - moe_cache, - dense_cache, - host_remaining.min(512 * 1024 * 1024), - &mut cancelled, - ChunkMoePolicy::Native, - true, - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - None, - )?; - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - // Every actual outer row has completed all48 target layers. Only now - // warm the one private draft branch and publish target+draft together. - let ready = draft.stage_prefill_chunk(binding, &mut txn, moe_cache, &mut cancelled)?; - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - Ok(txn.publish_joint(ready)?.into_target_product()) - } - - /// Explicit private outer256 with retainedGR transport; Native MoE - /// arithmetic stays unchanged and normal serving stays outer64. - #[allow(clippy::too_many_arguments)] - pub(crate) fn prefill_chunk_windowed256_retained_gr_joint<'driver>( - binding: &ModelBinding, - tokens: &[TokenId], - known_next: Option, - session: &mut QwenSession<'driver>, - draft: &mut super::super::super::mtp_decode::MtpDecoder, - output: &OutputStage<'_, '_>, - kar_cache: Option<&mut KarPleCache<'_>>, - moe_cache: &mut MoeWeightCache<'driver>, - dense_cache: &DenseWeightCache<'_>, - host_remaining: usize, - mut cancelled: impl FnMut() -> bool, - ) -> Result> { - let mut txn = Self::prepare_prefill_chunk_with_policy_windowed( - binding, - tokens, - known_next, - session, - output, - kar_cache, - moe_cache, - dense_cache, - host_remaining.min(512 * 1024 * 1024), - &mut cancelled, - ChunkMoePolicy::ExperimentalRetainedGr, - true, - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - None, - )?; - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - // Every actual outer row has completed all48 target layers. Only now - // warm the one private draft branch and publish target+draft together. - let ready = draft.stage_prefill_chunk(binding, &mut txn, moe_cache, &mut cancelled)?; - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - Ok(txn.publish_joint(ready)?.into_target_product()) - } - - /// Explicit private composition using the owned IntegerIQ3 cache. Each - /// outer256 layer uses <=64-row windows and existing retained GR transport; - /// unsupported GU selects native whole-layer execution before any MMQ launch. - #[allow(clippy::too_many_arguments)] - pub(crate) fn prefill_chunk_native_integer_iq3_windowed256_retained_gr_joint<'driver>( - binding: &ModelBinding, - tokens: &[TokenId], - known_next: Option, - session: &mut QwenSession<'driver>, - draft: &mut super::super::super::mtp_decode::MtpDecoder, - output: &OutputStage<'_, '_>, - kar_cache: Option<&mut KarPleCache<'_>>, - moe_cache: &mut MoeWeightCache<'driver>, - dense_cache: &DenseWeightCache<'_>, - host_remaining: usize, - mut cancelled: impl FnMut() -> bool, - ) -> Result> { - if !moe_cache.requires_iq3_mmq_admission() { - return Err(Error::IdentityMismatch); - } - #[cfg(test)] - let allocation_context = moe_cache.mmq_context(binding, session.mtp_context()?)?; - let mut txn = Self::prepare_prefill_chunk_with_policy_windowed( - binding, - tokens, - known_next, - session, - output, - kar_cache, - moe_cache, - dense_cache, - host_remaining.min(512 * 1024 * 1024), - &mut cancelled, - ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr, - true, - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - None, - ).inspect_err(|_error| { - #[cfg(test)] - eprintln!("PUBLIC candidate allocation stage=prepare-target-chunk rows={} allocated={} budget={} error={_error:?}", tokens.len(), allocation_context.allocated_bytes(), allocation_context.budget_bytes()); - })?; - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - // Every actual outer row has completed all48 target layers. Only now - // warm the one private draft branch and publish target+draft together. - let ready = draft.stage_owned_prefill_chunk(binding, &mut txn, moe_cache, &mut cancelled).inspect_err(|_error| { - #[cfg(test)] - eprintln!("PUBLIC candidate allocation stage=warm-draft-chunk rows={} allocated={} budget={} error={_error:?}", tokens.len(), allocation_context.allocated_bytes(), allocation_context.budget_bytes()); - })?; - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - Ok(txn.publish_joint(ready)?.into_target_product()) - } - - #[allow(clippy::too_many_arguments)] - pub(super) fn prepare_prefill_chunk_with_policy<'session, 'driver>( - binding: &ModelBinding, - tokens: &[TokenId], - known_next: Option, - session: &'session mut QwenSession<'driver>, - output: &OutputStage<'_, '_>, - kar_cache: Option<&mut KarPleCache<'_>>, - moe_cache: &mut MoeWeightCache<'driver>, - dense_cache: &DenseWeightCache<'_>, - host_remaining: usize, - cancelled: impl FnMut() -> bool, - policy: ChunkMoePolicy, - ) -> Result> { - Self::prepare_prefill_chunk_with_policy_windowed( - binding, - tokens, - known_next, - session, - output, - kar_cache, - moe_cache, - dense_cache, - host_remaining, - cancelled, - policy, - false, - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - None, - ) - } - - #[allow(clippy::too_many_arguments)] - pub(super) fn prepare_prefill_chunk_with_policy_windowed<'session, 'driver>( - binding: &ModelBinding, - tokens: &[TokenId], - known_next: Option, - session: &'session mut QwenSession<'driver>, - output: &OutputStage<'_, '_>, - mut kar_cache: Option<&mut KarPleCache<'_>>, - moe_cache: &mut MoeWeightCache<'driver>, - dense_cache: &DenseWeightCache<'_>, - host_remaining: usize, - mut cancelled: impl FnMut() -> bool, - policy: ChunkMoePolicy, - windowed: bool, - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] boundary: Option< - window_numeric::BoundaryPlan, - >, - ) -> Result> { - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let host_remaining = if moe_cache.uses_strata_adaptive_experts() { - // Independent actual CPU wave and ephemeral staging coexist. - // Both are inside the unchanged 512MiB request admission. - host_remaining - .checked_sub((48 + 16) * 1024 * 1024) - .ok_or(Error::InputAllocation)? - } else { - host_remaining - }; - let layer_bound = validate_layer_plan(binding)?; - if layer_bound.get() != 48 { - return Err(Error::Unsupported(Stage::Executor)); - } - chunk_diagnostic( - "dense-cache-validate", - None, - 0, - tokens.len(), - dense_cache.validate(binding), - )?; - // Immutable weights and eagerly reserved scratch are charged before - // chunk admission. The existing 128MiB transient reserve is preserved. - let context = chunk_diagnostic( - "target-context", - None, - 0, - tokens.len(), - session.mtp_context(), - )?; - // Revalidate the genuine actor Context and retain its cache lifetime, - // independent of the upcoming mutable session transaction borrow. - let context = moe_cache.mmq_context(binding, context)?; - chunk_diagnostic( - "moe-prepare-step", - None, - 0, - tokens.len(), - moe_cache.prepare_step(binding, context), - )?; - if !matches!( - policy, - ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr - ) && dense_cache.gdn_four_borrow(binding, context)? - { - // Retained full QK/H/Gate/Beta are additional to the unchanged - // typed+physical128MiB reserve, before any row/input/weight loan. - moe_cache.reserve_mmq_transient( - binding, - context, - super::super::super::gdn::FOUR_BORROW_BYTES, - )?; - } - // Only the existing explicit experimental windowed256 policy opts in. - let recurrence_context = if windowed - && matches!( - policy, - ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr - ) { - Some(dense_cache.retained_context(binding, context)?) - } else { - None - }; - let verification_context = if matches!(policy, ChunkMoePolicy::ExperimentalMtpVerification) - && dense_cache.has_gdn_verification_workspace() - { - Some(dense_cache.retained_context(binding, context)?) - } else { - None - }; - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let micro_gr = matches!( - policy, - ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr - | ChunkMoePolicy::ExperimentalMtpVerification - ); - #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] - let micro_gr = false; - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let host_remaining = if matches!( - policy, - ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr - ) { - host_remaining - .min(512 * 1024 * 1024) - .checked_sub(QwenChunkTxn::native_prefill_host_charge(tokens.len())?) - .ok_or(Error::InputAllocation)? - } else { - host_remaining - }; - let mut chunk = chunk_diagnostic( - "chunk-begin", - None, - 0, - tokens.len(), - if matches!(policy, ChunkMoePolicy::ExperimentalMtpVerification) { - if !windowed || known_next.is_some() { - return Err(Error::IdentityMismatch); - } - QwenChunkTxn::begin_mtp_verification(session, binding, tokens, host_remaining) - } else if windowed { - QwenChunkTxn::begin_windowed256( - session, - binding, - tokens, - known_next, - host_remaining, - ) - } else { - QwenChunkTxn::begin(session, binding, tokens, known_next, host_remaining) - }, - )?; - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if matches!(boundary, Some(window_numeric::BoundaryPlan::FullMicro2)) { - chunk.test_use_micro2()?; - } - if verification_context.is_some() { - chunk.enable_device_gdn_verification(binding, dense_cache, host_remaining)?; - } - let verification_lease = if verification_context.is_some() { - chunk.device_gdn_lease()? - } else { - None - }; - let mut previous = Vec::new(); - previous - .try_reserve_exact(chunk.len()) - .map_err(|_| Error::InputAllocation)?; - previous.resize_with(chunk.len(), || None); - for index in 0..chunk.len() { - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - let (token, pos) = chunk.row_ids(index)?; - chunk_diagnostic( - "input", - None, - index, - 1, - chunk.input(index, |txn| { - match (binding.kar_ple_binding(), kar_cache.as_deref_mut()) { - (None, None) => InputStage::consume(binding, token, pos, txn), - (Some(_), Some(cache)) => { - InputStage::consume_kar(binding, cache, token, pos, txn) - } - _ => Err(Error::IdentityMismatch), - } - }), - )?; - } - // Genuine outer-layer/inner-row order. At a causal layer each row - // consumes only the rolling state through its own position. - for descriptor in binding.ordered_layers() { - let layer = LayerId::new(u64::from(descriptor.index()), layer_bound)?; - let mut gdn_device = if descriptor.kind() == BoundLayerKind::Gdn { - if let (Some(context), Some(lease)) = - (verification_context, verification_lease.as_ref()) - { - let start = chunk.begin_gdn_chunk(layer)?; - Some( - super::super::super::gdn::chunk_device::GdnChunkDevice::new_verification( - binding, - context, - dense_cache, - start, - lease.clone(), - )?, - ) - } else if let Some(context) = recurrence_context { - // Both actual state owners/status coexist with the eager - // prompt bank. No scalar four-input chain is loaned here. - // Recheck after every intervening routed cache growth. - let live_gdn = super::super::super::gdn::chunk_device::CHUNK_DEVICE_CHARGE; - moe_cache.reserve_mmq_transient(binding, context, live_gdn)?; - let start = chunk.begin_gdn_chunk(layer)?; - let mut owner = super::super::super::gdn::chunk_device::GdnChunkDevice::new( - binding, - context, - dense_cache, - start, - )?; - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if micro_gr - && !matches!( - policy, - ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr - ) - && dense_cache.has_gdn_qk_workspace() - { - owner.enable_row_queue()?; - } - Some(owner) - } else { - None - } - } else { - None - }; - // Complete all actual outer rows of this layer, releasing each - // bounded window before the next. Kernel geometry remains<=64. - let stride = if windowed { 64 } else { chunk.len() }; - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let stride = if matches!(boundary, Some(window_numeric::BoundaryPlan::FullMicro2)) { - 2 - } else { - stride - }; - for first in (0..chunk.len()).step_by(stride) { - let window = if windowed { - Some(chunk.open_micro_window(layer)?) - } else { - None - }; - let count = chunk.micro_len()?; - let end = first.checked_add(count).ok_or(Error::Overflow)?; - if end > chunk.len() || chunk.micro_row_index(0)? != first { - return Err(Error::IdentityMismatch); - } - let mut attention = Vec::new(); - attention - .try_reserve_exact(count) - .map_err(|_| Error::InputAllocation)?; - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let mut gr_micro_bank = None; - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let mut ple_micro = if matches!( - policy, - ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr - ) && layer.get() == 1 - { - let (prior, inputs) = chunk.prepare_ple_micro_inputs(layer, |index, txn| { - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - InputStage::prepare_ple_micro_input( - binding, - previous[index].as_ref().ok_or(Error::IdentityMismatch)?, - txn, - ) - })?; - Some(InputStage::apply_ple_micro_cached( - binding, - context, - prior, - inputs, - dense_cache, - )?) - } else { - None - }; - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if micro_gr { - let retained_bytes = count.checked_mul(227888).ok_or(Error::Overflow)?; - moe_cache.reserve_mmq_transient(binding, context, retained_bytes)?; - #[cfg(test)] - let closed_end = chunk.test_window_journal().last().map(|(_, _, end)| *end); - attention = chunk_diagnostic( - "attention-micro-read", - Some(layer.get()), - first, - count, - chunk.read_attention_micro( - layer, - |index, txn| { - #[cfg(test)] - if let Some(window_numeric::BoundaryPlan::CancelFirstLayerAt193 { - observed, - cancelled: latch, - }) = &boundary - && layer.get() == 0 - && index == 193 - { - if txn.position().get() != 193 { - return Err(Error::IdentityMismatch); - } - observed.set(Some(( - index, - closed_end.ok_or(Error::IdentityMismatch)?, - ))); - latch.set(true); - } - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - prepare_layer_attention_micro( - binding, - layer, - previous[index].as_ref(), - txn, - dense_cache, - ple_micro.as_mut(), - ) - }, - |inputs| { - let completed = if matches!( - policy, - ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr - ) { - GrStage::read_micro_attention_native( - binding, - context, - inputs, - dense_cache, - )? - } else { - GrStage::read_micro_attention( - binding, - context, - inputs, - dense_cache, - )? - }; - let (bank, rows) = completed.into_parts(); - gr_micro_bank = Some(bank); - Ok(rows) - }, - ), - )?; - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if let Some(batch) = ple_micro.take() - && !batch.is_consumed() - { - return Err(Error::IdentityMismatch); - } - if !micro_gr { - for (local, prior) in previous[first..end].iter().enumerate() { - let index = chunk.micro_row_index(local)?; - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if let Some(window_numeric::BoundaryPlan::CancelFirstLayerAt193 { - observed, - cancelled: latch, - }) = &boundary - && layer.get() == 0 - && index == 193 - { - let (_, position) = chunk.row_ids(index)?; - if position.get() != 193 { - return Err(Error::IdentityMismatch); - } - let closed_end = - chunk.test_window_journal().last().map(|(_, _, end)| *end); - observed.set(Some((index, closed_end.ok_or(Error::IdentityMismatch)?))); - // Set only at the genuine global row. The unchanged - // cancellation callback/fence below performs refusal. - latch.set(true); - } - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - attention.push(chunk_diagnostic( - "attention-read", - Some(layer.get()), - index, - 1, - chunk.read_attention_column(index, layer, |txn| { - let read = read_layer_attention( - binding, - layer, - prior.as_ref(), - txn, - Some(dense_cache), - )?; - GrStage::detach_attention(binding, read, txn) - }), - )?); - } - } - let native_prompt = matches!( - policy, - ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr - ); - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let native_decode_qsa = - dense_cache.has_native_qsa() && descriptor.kind() == BoundLayerKind::Qsa; - #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] - let native_decode_qsa = false; - let mut projected = if native_prompt || native_decode_qsa { - // Literal prompt projections are native GEMM chains; - // the scalar Q6 column program is not also executed. - (0..count).map(|_| Vec::new()).collect() - } else { - chunk_diagnostic( - "q6-columns", - Some(layer.get()), - first, - count, - prepare_q6_layer_columns( - binding, - dense_cache, - &chunk, - layer, - descriptor.kind(), - &attention, - micro_gr && gdn_device.is_some() && verification_context.is_none(), - ), - )? - }; - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let mut native_moe = None; - let mut ffn_rows = Vec::new(); - ffn_rows - .try_reserve_exact(count) - .map_err(|_| Error::InputAllocation)?; - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if let Some(bank) = gr_micro_bank { - for slot in &mut previous[first..end] { - let _ = slot.take(); - } - let prepared_micro = prepare_micro_ffn_rows( - binding, - layer, - descriptor.kind(), - &mut chunk, - &attention, - &mut projected, - bank, - gdn_device.as_mut(), - dense_cache, - moe_cache, - native_prompt, - &mut cancelled, - )?; - ffn_rows = prepared_micro.0; - native_moe = prepared_micro.1; - } - if !micro_gr { - for (local, previous_slot) in previous[first..end].iter_mut().enumerate() { - let index = chunk.micro_row_index(local)?; - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - let (token, pos) = chunk.row_ids(index)?; - let _ = previous_slot.take(); - let prepared = chunk_diagnostic( - "causal-attention-ffn", - Some(layer.get()), - index, - 1, - if let Some(owner) = gdn_device.as_mut() { - chunk.prepare_attention_ffn_device_gdn( - index, - layer, - &attention[local], - |txn, residual, row| { - let attention = diagnose( - ForwardPhase::Gdn, - layer.get(), - pos, - GdnStage::step_chunk_selected( - binding, - layer, - residual.ready(), - txn, - dense_cache, - owner, - row, - projected[local].first_mut(), - ), - )?; - attention.validate_origin(&binding.identity())?; - attention.identity().validate(token, pos, layer)?; - let ffn = read_chunk_attention_ffn( - binding, - residual, - attention.output(), - attention.identity(), - txn, - dense_cache, - true, - )?; - let route = diagnose( - ForwardPhase::MoeRoute, - layer.get(), - pos, - MoeRouteStage::route_from_ffn( - binding, - layer, - ffn.ready(), - txn, - Some(dense_cache), - ), - )?; - let prepared = MoeExpertStage::prepare_chunk_row( - binding, layer, ffn, route, txn, - )?; - Ok((prepared, attention.into_edge())) - }, - ) - } else { - chunk.prepare_attention_ffn( - index, - layer, - &attention[local], - |txn, residual| { - let ffn = if matches!( - policy, - ChunkMoePolicy::ExperimentalRetainedGr - | ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr - | ChunkMoePolicy::ExperimentalMtpVerification - ) { - let ffn_result: Result> = - (|| { - let ffn = match descriptor.kind() { - BoundLayerKind::Gdn => { - let prior = txn.gdn_prior(layer)?; - let mut attention = diagnose( - ForwardPhase::Gdn, - layer.get(), - pos, - if let Some(projection) = - projected[local].first_mut() - { - GdnStage::step_projected( - binding, - layer, - residual.ready(), - &prior, - txn, - dense_cache, - projection, - ) - } else { - GdnStage::step( - binding, - layer, - residual.ready(), - &prior, - txn, - Some(dense_cache), - ) - }, - )?; - attention - .validate_origin(&binding.identity())?; - attention - .identity() - .validate(token, pos, layer)?; - let pending = attention.take_pending()?; - txn.stage_gdn(&prior, pending)?; - read_chunk_attention_ffn( - binding, - residual, - attention.output(), - attention.identity(), - txn, - dense_cache, - true, - )? - } - BoundLayerKind::Qsa => { - let attention = { - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - let native = dense_cache.has_native_qsa().then_some(dense_cache).map(|cache| - diagnose(ForwardPhase::QsaAttention,layer.get(),pos, - QsaAttentionStage::decode_native(binding,layer,residual.ready(),txn,cache))).transpose()?; - #[cfg(not(all(any(target_os="linux",target_os="windows"),target_arch="x86_64")))] - let native = None; - if let Some(completed)=native { completed } else { - let prior = txn.qsa_prior(layer)?; - let mut prepared = diagnose( - ForwardPhase::QsaIndex, - layer.get(), - pos, - QsaIndexStage::prepare_projected( - binding, - layer, - residual.ready(), - pos, - &prior, - txn, - dense_cache, - &mut projected[local], - ), - )?; - prepared.validate_origin( - &binding.identity(), - layer, - )?; - prepared - .identity() - .validate(token, pos, layer)?; - let pending = prepared.take_pending()?; - txn.stage_qsa(&prior, pending)?; - let attention = diagnose( - ForwardPhase::QsaAttention, - layer.get(), - pos, - QsaAttentionStage::decode_with_scratch( - binding, - layer, - prepared, - txn, - Some(dense_cache), - dense_cache.qsa_attention_workspace(), - ), - )?; - attention - } - }; - attention.validate_origin( - &binding.identity(), - layer, - )?; - attention - .identity() - .validate(token, pos, layer)?; - read_chunk_attention_ffn( - binding, - residual, - attention.output(), - attention.identity(), - txn, - dense_cache, - true, - )? - } - }; - Ok(ffn) - })(); - ffn_result? - } else { - let injected_result = (|| { - let injected = match descriptor.kind() { - BoundLayerKind::Gdn => { - let prior = txn.gdn_prior(layer)?; - let mut attention = diagnose( - ForwardPhase::Gdn, - layer.get(), - pos, - if let Some(projection) = - projected[local].first_mut() - { - GdnStage::step_projected( - binding, - layer, - residual.ready(), - &prior, - txn, - dense_cache, - projection, - ) - } else { - GdnStage::step( - binding, - layer, - residual.ready(), - &prior, - txn, - Some(dense_cache), - ) - }, - )?; - attention - .validate_origin(&binding.identity())?; - attention - .identity() - .validate(token, pos, layer)?; - let pending = attention.take_pending()?; - txn.stage_gdn(&prior, pending)?; - diagnose( - ForwardPhase::GrAttentionInject, - layer.get(), - pos, - GrStage::inject_detached( - binding, - residual, - attention.output(), - attention.identity(), - txn, - ), - )? - } - BoundLayerKind::Qsa => { - let attention = { - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - let native = dense_cache.has_native_qsa().then_some(dense_cache).map(|cache| - diagnose(ForwardPhase::QsaAttention,layer.get(),pos, - QsaAttentionStage::decode_native(binding,layer,residual.ready(),txn,cache))).transpose()?; - #[cfg(not(all(any(target_os="linux",target_os="windows"),target_arch="x86_64")))] - let native = None; - if let Some(completed)=native { completed } else { - let prior = txn.qsa_prior(layer)?; - let mut prepared = diagnose( - ForwardPhase::QsaIndex, - layer.get(), - pos, - QsaIndexStage::prepare_projected( - binding, - layer, - residual.ready(), - pos, - &prior, - txn, - dense_cache, - &mut projected[local], - ), - )?; - prepared.validate_origin( - &binding.identity(), - layer, - )?; - prepared - .identity() - .validate(token, pos, layer)?; - let pending = prepared.take_pending()?; - txn.stage_qsa(&prior, pending)?; - let attention = diagnose( - ForwardPhase::QsaAttention, - layer.get(), - pos, - QsaAttentionStage::decode_with_scratch( - binding, - layer, - prepared, - txn, - Some(dense_cache), - dense_cache.qsa_attention_workspace(), - ), - )?; - attention - } - }; - attention.validate_origin( - &binding.identity(), - layer, - )?; - attention - .identity() - .validate(token, pos, layer)?; - diagnose( - ForwardPhase::GrAttentionInject, - layer.get(), - pos, - GrStage::inject_detached( - binding, - residual, - attention.output(), - attention.identity(), - txn, - ), - )? - } - }; - Ok(injected) - })( - ); - let injected = residual.finish(injected_result)?; - diagnose( - ForwardPhase::GrFfn, - layer.get(), - pos, - GrStage::read_ffn( - binding, - layer, - &injected, - txn, - Some(dense_cache), - ), - )? - }; - (|| { - let route = diagnose( - ForwardPhase::MoeRoute, - layer.get(), - pos, - MoeRouteStage::route_from_ffn( - binding, - layer, - ffn.ready(), - txn, - Some(dense_cache), - ), - )?; - MoeExpertStage::prepare_chunk_row( - binding, layer, ffn, route, txn, - ) - })() - }, - ) - }, - )?; - ffn_rows.push(prepared); - } - } - drop(projected); - drop(attention); - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if matches!(policy, ChunkMoePolicy::Layer0Diagnostic) { - if layer.get() != 0 { - return Err(Error::IdentityMismatch); - } - MoeExpertStage::test_layer0_same_rows( - binding, layer, &ffn_rows, &mut chunk, moe_cache, - )?; - // Actual unpublished chunk drops here, before FFN injection/MTP/head. - return Err(Error::Unsupported(Stage::Executor)); - } - let experts = chunk_diagnostic("moe-experts", Some(layer.get()), first, count, { - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let native_result = if native_prompt { - Some(MoeExpertStage::execute_chunk_mmq_native_prompt( - binding, - layer, - &ffn_rows, - &mut chunk, - moe_cache, - &mut cancelled, - native_moe.as_mut().ok_or(Error::IdentityMismatch)?, - dense_cache, - )) - } else { - None - }; - #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] - let native_result: Option< - Result>, - > = None; - if let Some(result) = native_result { - result - } else { - match policy { - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - ChunkMoePolicy::Layer0Diagnostic => { - return Err(Error::IdentityMismatch); - } - ChunkMoePolicy::Native | ChunkMoePolicy::ExperimentalRetainedGr => { - MoeExpertStage::execute_chunk( - binding, - layer, - &ffn_rows, - &mut chunk, - moe_cache, - &mut cancelled, - ) - } - ChunkMoePolicy::ExperimentalResidentMmq - | ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr - | ChunkMoePolicy::ExperimentalMtpVerification => { - MoeExpertStage::execute_chunk_mmq( - binding, - layer, - &ffn_rows, - &mut chunk, - moe_cache, - &mut cancelled, - ) - } - } - } - }); - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let cleanup = native_moe - .take() - .map_or(Ok(()), |products| products.release()); - #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] - let cleanup = Ok(()); - if cleanup.is_err() { - moe_cache.note_transport_failure(); - } - let experts = experts.and_then(|values| cleanup.map(|()| values))?; - if experts.len() != ffn_rows.len() { - return Err(Error::IdentityMismatch); - } - let mut batch_rows = Vec::new(); - let mut proofs = Vec::new(); - batch_rows - .try_reserve_exact(ffn_rows.len()) - .map_err(|_| Error::InputAllocation)?; - proofs - .try_reserve_exact(ffn_rows.len()) - .map_err(|_| Error::InputAllocation)?; - for (local, (row, expert)) in ffn_rows.into_iter().zip(experts).enumerate() { - let index = chunk.micro_row_index(local)?; - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - let (prepared, proof) = - chunk.prepare_ffn_injection(index, layer, row, binding, expert)?; - batch_rows.push(prepared); - proofs.push(proof); - } - // Actual single CUDA launch over tightly packed token columns, - // then only genuine finite FFN producers complete the rows. - let completed = chunk_diagnostic( - "gr-ffn-batch-inject", - Some(layer.get()), - first, - count, - chunk.batch_outputs(|context| { - GrStage::inject_batch(binding, context, batch_rows, dense_cache) - }), - )?; - if completed.len() != proofs.len() { - return Err(Error::IdentityMismatch); - } - for ((slot, proof), residual) in - previous[first..end].iter_mut().zip(proofs).zip(completed) - { - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - *slot = Some(chunk.complete_layer_batch(proof, residual)?); - } - // All temporaries/projection borrows were consumed or dropped. - // Consuming this actual capability is the sole window transition. - if let Some(window) = window { - chunk.close_micro_window(window)?; - } - } - // The last real micro capability has closed and all actual FFN - // rows completed. Only now materialize/adopt the canonical boundary. - if let Some(owner) = gdn_device.take() { - chunk.finish_gdn_chunk(owner, binding, dense_cache)?; - } - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if matches!(boundary, Some(window_numeric::BoundaryPlan::FirstLayer)) - && layer.get() == 0 - { - chunk.test_observe_first_layer(&previous)?; - return Ok(chunk); // Deliberately unfinished: cannot warm or publish. - } - } - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if verification_lease.is_some() { - chunk.materialize_device_gdn_observer(binding, dense_cache, &mut cancelled)?; - } - let mut execute_head = |txn: &mut QwenStepTxn<'_, 'driver>, residual: &InjectedResidual| { - if matches!(policy, ChunkMoePolicy::ExperimentalMtpVerification) && cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - let logits = chunk_diagnostic( - "output-head", - None, - 0, - 1, - output.logits_cached(binding, residual, txn, Some(dense_cache)), - )?; - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - output.test_reset_replay_capture(&logits)?; - txn.finish_forward(logits) - }; - if matches!(policy, ChunkMoePolicy::ExperimentalMtpVerification) { - chunk.finish_mtp_verification(&previous, &mut execute_head)?; - } else { - chunk.finish(&previous, execute_head)?; - } - Ok(chunk) - } -} +#[path = "impl_qwenforward/impl_qwenforward_2.rs"] +mod impl_qwenforward_2; +#[path = "impl_qwenforward/impl_qwenforward_2_2.rs"] +mod impl_qwenforward_2_2; +#[path = "impl_qwenforward/impl_qwenforward_3.rs"] +mod impl_qwenforward_3; diff --git a/crates/leleka-runtime/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_2.rs b/crates/leleka-runtime/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_2.rs new file mode 100644 index 00000000..8c93c38f --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_2.rs @@ -0,0 +1,208 @@ +//! Moved out of the parent module by STRA-338: impl QwenForward. + +#[allow(unused_imports)] +use super::*; + + + +impl QwenForward { + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(crate) fn test_chunk_on_loaded<'driver>( + binding: &ModelBinding, + session: &mut QwenSession<'driver>, + output: &OutputStage<'_, '_>, + kar: &mut KarPleCache<'_>, + moe: &mut MoeWeightCache<'driver>, + dense: &DenseWeightCache<'_>, + ) { + check_chunk_on_loaded(binding, session, output, kar, moe, dense); + } + + #[allow(clippy::too_many_arguments)] + pub(crate) fn prefill_chunk_mmq_joint<'driver>( + binding: &ModelBinding, + tokens: &[TokenId], + known_next: Option, + session: &mut QwenSession<'driver>, + draft: &mut crate::qwen_forward::mtp_decode::MtpDecoder, + output: &OutputStage<'_, '_>, + kar_cache: Option<&mut KarPleCache<'_>>, + moe_cache: &mut MoeWeightCache<'driver>, + dense_cache: &DenseWeightCache<'_>, + host_remaining: usize, + mut cancelled: impl FnMut() -> bool, + ) -> Result> { + let mut txn = Self::prepare_prefill_chunk_with_policy( + binding, + tokens, + known_next, + session, + output, + kar_cache, + moe_cache, + dense_cache, + host_remaining, + &mut cancelled, + ChunkMoePolicy::ExperimentalResidentMmq, + )?; + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + let ready = draft.stage_prefill_chunk(binding, &mut txn, moe_cache, &mut cancelled)?; + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + Ok(txn.publish_joint(ready)?.into_target_product()) + } + #[allow(clippy::too_many_arguments)] + pub(crate) fn prefill_chunk_cached_joint<'driver>( + binding: &ModelBinding, + tokens: &[TokenId], + known_next: Option, + session: &mut QwenSession<'driver>, + draft: &mut super::super::super::super::mtp_decode::MtpDecoder, + output: &OutputStage<'_, '_>, + kar_cache: Option<&mut KarPleCache<'_>>, + moe_cache: &mut MoeWeightCache<'driver>, + dense_cache: &DenseWeightCache<'_>, + host_remaining: usize, + mut cancelled: impl FnMut() -> bool, + ) -> Result> { + let mut txn = Self::prepare_prefill_chunk_cached( + binding, + tokens, + known_next, + session, + output, + kar_cache, + moe_cache, + dense_cache, + host_remaining, + &mut cancelled, + )?; + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + let ready: super::super::super::super::mtp_decode::ReadyMtpChunk<'_, '_> = + draft.stage_prefill_chunk(binding, &mut txn, moe_cache, &mut cancelled)?; + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + Ok(txn.publish_joint(ready)?.into_target_product()) + } + + #[allow(clippy::too_many_arguments)] + pub(in crate::qwen_forward) fn prepare_prefill_chunk_cached<'session, 'driver>( + binding: &ModelBinding, + tokens: &[TokenId], + known_next: Option, + session: &'session mut QwenSession<'driver>, + output: &OutputStage<'_, '_>, + kar_cache: Option<&mut KarPleCache<'_>>, + moe_cache: &mut MoeWeightCache<'driver>, + dense_cache: &DenseWeightCache<'_>, + host_remaining: usize, + cancelled: impl FnMut() -> bool, + ) -> Result> { + Self::prepare_prefill_chunk_with_policy( + binding, + tokens, + known_next, + session, + output, + kar_cache, + moe_cache, + dense_cache, + host_remaining, + cancelled, + ChunkMoePolicy::Native, + ) + } + /// Explicit private outer256 experiment. Only the original native MoE + /// arithmetic is selected here; existing normal serving stays outer64. + #[allow(clippy::too_many_arguments)] + pub(in crate::qwen_forward) fn prefill_chunk_windowed256_joint<'driver>( + binding: &ModelBinding, + tokens: &[TokenId], + known_next: Option, + session: &mut QwenSession<'driver>, + draft: &mut super::super::super::super::mtp_decode::MtpDecoder, + output: &OutputStage<'_, '_>, + kar_cache: Option<&mut KarPleCache<'_>>, + moe_cache: &mut MoeWeightCache<'driver>, + dense_cache: &DenseWeightCache<'_>, + host_remaining: usize, + mut cancelled: impl FnMut() -> bool, + ) -> Result> { + let mut txn = Self::prepare_prefill_chunk_with_policy_windowed( + binding, + tokens, + known_next, + session, + output, + kar_cache, + moe_cache, + dense_cache, + host_remaining.min(512 * 1024 * 1024), + &mut cancelled, + ChunkMoePolicy::Native, + true, + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + None, + )?; + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + // Every actual outer row has completed all48 target layers. Only now + // warm the one private draft branch and publish target+draft together. + let ready = draft.stage_prefill_chunk(binding, &mut txn, moe_cache, &mut cancelled)?; + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + Ok(txn.publish_joint(ready)?.into_target_product()) + } + + /// Explicit private outer256 with retainedGR transport; Native MoE + /// arithmetic stays unchanged and normal serving stays outer64. + #[allow(clippy::too_many_arguments)] + pub(crate) fn prefill_chunk_windowed256_retained_gr_joint<'driver>( + binding: &ModelBinding, + tokens: &[TokenId], + known_next: Option, + session: &mut QwenSession<'driver>, + draft: &mut super::super::super::super::mtp_decode::MtpDecoder, + output: &OutputStage<'_, '_>, + kar_cache: Option<&mut KarPleCache<'_>>, + moe_cache: &mut MoeWeightCache<'driver>, + dense_cache: &DenseWeightCache<'_>, + host_remaining: usize, + mut cancelled: impl FnMut() -> bool, + ) -> Result> { + let mut txn = Self::prepare_prefill_chunk_with_policy_windowed( + binding, + tokens, + known_next, + session, + output, + kar_cache, + moe_cache, + dense_cache, + host_remaining.min(512 * 1024 * 1024), + &mut cancelled, + ChunkMoePolicy::ExperimentalRetainedGr, + true, + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + None, + )?; + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + // Every actual outer row has completed all48 target layers. Only now + // warm the one private draft branch and publish target+draft together. + let ready = draft.stage_prefill_chunk(binding, &mut txn, moe_cache, &mut cancelled)?; + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + Ok(txn.publish_joint(ready)?.into_target_product()) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_2_2.rs b/crates/leleka-runtime/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_2_2.rs new file mode 100644 index 00000000..639599d2 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_2_2.rs @@ -0,0 +1,97 @@ +//! Moved out of the parent module by STRA-338: impl QwenForward (2). + +#[allow(unused_imports)] +use super::*; + + + +impl QwenForward { + + /// Explicit private composition using the owned IntegerIQ3 cache. Each + /// outer256 layer uses <=64-row windows and existing retained GR transport; + /// unsupported GU selects native whole-layer execution before any MMQ launch. + #[allow(clippy::too_many_arguments)] + pub(crate) fn prefill_chunk_native_integer_iq3_windowed256_retained_gr_joint<'driver>( + binding: &ModelBinding, + tokens: &[TokenId], + known_next: Option, + session: &mut QwenSession<'driver>, + draft: &mut super::super::super::super::mtp_decode::MtpDecoder, + output: &OutputStage<'_, '_>, + kar_cache: Option<&mut KarPleCache<'_>>, + moe_cache: &mut MoeWeightCache<'driver>, + dense_cache: &DenseWeightCache<'_>, + host_remaining: usize, + mut cancelled: impl FnMut() -> bool, + ) -> Result> { + if !moe_cache.requires_iq3_mmq_admission() { + return Err(Error::IdentityMismatch); + } + #[cfg(test)] + let allocation_context = moe_cache.mmq_context(binding, session.mtp_context()?)?; + let mut txn = Self::prepare_prefill_chunk_with_policy_windowed( + binding, + tokens, + known_next, + session, + output, + kar_cache, + moe_cache, + dense_cache, + host_remaining.min(512 * 1024 * 1024), + &mut cancelled, + ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr, + true, + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + None, + ).inspect_err(|_error| { + #[cfg(test)] + eprintln!("PUBLIC candidate allocation stage=prepare-target-chunk rows={} allocated={} budget={} error={_error:?}", tokens.len(), allocation_context.allocated_bytes(), allocation_context.budget_bytes()); + })?; + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + // Every actual outer row has completed all48 target layers. Only now + // warm the one private draft branch and publish target+draft together. + let ready = draft.stage_owned_prefill_chunk(binding, &mut txn, moe_cache, &mut cancelled).inspect_err(|_error| { + #[cfg(test)] + eprintln!("PUBLIC candidate allocation stage=warm-draft-chunk rows={} allocated={} budget={} error={_error:?}", tokens.len(), allocation_context.allocated_bytes(), allocation_context.budget_bytes()); + })?; + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + Ok(txn.publish_joint(ready)?.into_target_product()) + } + + #[allow(clippy::too_many_arguments)] + pub(in super::super) fn prepare_prefill_chunk_with_policy<'session, 'driver>( + binding: &ModelBinding, + tokens: &[TokenId], + known_next: Option, + session: &'session mut QwenSession<'driver>, + output: &OutputStage<'_, '_>, + kar_cache: Option<&mut KarPleCache<'_>>, + moe_cache: &mut MoeWeightCache<'driver>, + dense_cache: &DenseWeightCache<'_>, + host_remaining: usize, + cancelled: impl FnMut() -> bool, + policy: ChunkMoePolicy, + ) -> Result> { + Self::prepare_prefill_chunk_with_policy_windowed( + binding, + tokens, + known_next, + session, + output, + kar_cache, + moe_cache, + dense_cache, + host_remaining, + cancelled, + policy, + false, + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + None, + ) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3.rs b/crates/leleka-runtime/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3.rs new file mode 100644 index 00000000..181871bd --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3.rs @@ -0,0 +1,980 @@ +//! Moved out of the parent module by STRA-338: impl QwenForward (3). + +#[allow(unused_imports)] +use super::*; + + + +impl QwenForward { + + #[allow(clippy::too_many_arguments)] + pub(in super::super) fn prepare_prefill_chunk_with_policy_windowed<'session, 'driver>( + binding: &ModelBinding, + tokens: &[TokenId], + known_next: Option, + session: &'session mut QwenSession<'driver>, + output: &OutputStage<'_, '_>, + mut kar_cache: Option<&mut KarPleCache<'_>>, + moe_cache: &mut MoeWeightCache<'driver>, + dense_cache: &DenseWeightCache<'_>, + host_remaining: usize, + mut cancelled: impl FnMut() -> bool, + policy: ChunkMoePolicy, + windowed: bool, + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] boundary: Option< + window_numeric::BoundaryPlan, + >, + ) -> Result> { + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + let host_remaining = if moe_cache.uses_strata_adaptive_experts() { + // Independent actual CPU wave and ephemeral staging coexist. + // Both are inside the unchanged 512MiB request admission. + host_remaining + .checked_sub((48 + 16) * 1024 * 1024) + .ok_or(Error::InputAllocation)? + } else { + host_remaining + }; + let layer_bound = validate_layer_plan(binding)?; + if layer_bound.get() != 48 { + return Err(Error::Unsupported(Stage::Executor)); + } + chunk_diagnostic( + "dense-cache-validate", + None, + 0, + tokens.len(), + dense_cache.validate(binding), + )?; + // Immutable weights and eagerly reserved scratch are charged before + // chunk admission. The existing 128MiB transient reserve is preserved. + let context = chunk_diagnostic( + "target-context", + None, + 0, + tokens.len(), + session.mtp_context(), + )?; + // Revalidate the genuine actor Context and retain its cache lifetime, + // independent of the upcoming mutable session transaction borrow. + let context = moe_cache.mmq_context(binding, context)?; + chunk_diagnostic( + "moe-prepare-step", + None, + 0, + tokens.len(), + moe_cache.prepare_step(binding, context), + )?; + if !matches!( + policy, + ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr + ) && dense_cache.gdn_four_borrow(binding, context)? + { + // Retained full QK/H/Gate/Beta are additional to the unchanged + // typed+physical128MiB reserve, before any row/input/weight loan. + moe_cache.reserve_mmq_transient( + binding, + context, + super::super::super::super::gdn::FOUR_BORROW_BYTES, + )?; + } + // Only the existing explicit experimental windowed256 policy opts in. + let recurrence_context = if windowed + && matches!( + policy, + ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr + ) { + Some(dense_cache.retained_context(binding, context)?) + } else { + None + }; + let verification_context = if matches!(policy, ChunkMoePolicy::ExperimentalMtpVerification) + && dense_cache.has_gdn_verification_workspace() + { + Some(dense_cache.retained_context(binding, context)?) + } else { + None + }; + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + let micro_gr = matches!( + policy, + ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr + | ChunkMoePolicy::ExperimentalMtpVerification + ); + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] + let micro_gr = false; + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + let host_remaining = if matches!( + policy, + ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr + ) { + host_remaining + .min(512 * 1024 * 1024) + .checked_sub(QwenChunkTxn::native_prefill_host_charge(tokens.len())?) + .ok_or(Error::InputAllocation)? + } else { + host_remaining + }; + let mut chunk = chunk_diagnostic( + "chunk-begin", + None, + 0, + tokens.len(), + if matches!(policy, ChunkMoePolicy::ExperimentalMtpVerification) { + if !windowed || known_next.is_some() { + return Err(Error::IdentityMismatch); + } + QwenChunkTxn::begin_mtp_verification(session, binding, tokens, host_remaining) + } else if windowed { + QwenChunkTxn::begin_windowed256( + session, + binding, + tokens, + known_next, + host_remaining, + ) + } else { + QwenChunkTxn::begin(session, binding, tokens, known_next, host_remaining) + }, + )?; + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if matches!(boundary, Some(window_numeric::BoundaryPlan::FullMicro2)) { + chunk.test_use_micro2()?; + } + if verification_context.is_some() { + chunk.enable_device_gdn_verification(binding, dense_cache, host_remaining)?; + } + let verification_lease = if verification_context.is_some() { + chunk.device_gdn_lease()? + } else { + None + }; + let mut previous = Vec::new(); + previous + .try_reserve_exact(chunk.len()) + .map_err(|_| Error::InputAllocation)?; + previous.resize_with(chunk.len(), || None); + for index in 0..chunk.len() { + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + let (token, pos) = chunk.row_ids(index)?; + chunk_diagnostic( + "input", + None, + index, + 1, + chunk.input(index, |txn| { + match (binding.kar_ple_binding(), kar_cache.as_deref_mut()) { + (None, None) => InputStage::consume(binding, token, pos, txn), + (Some(_), Some(cache)) => { + InputStage::consume_kar(binding, cache, token, pos, txn) + } + _ => Err(Error::IdentityMismatch), + } + }), + )?; + } + // Genuine outer-layer/inner-row order. At a causal layer each row + // consumes only the rolling state through its own position. + for descriptor in binding.ordered_layers() { + let layer = LayerId::new(u64::from(descriptor.index()), layer_bound)?; + let mut gdn_device = if descriptor.kind() == BoundLayerKind::Gdn { + if let (Some(context), Some(lease)) = + (verification_context, verification_lease.as_ref()) + { + let start = chunk.begin_gdn_chunk(layer)?; + Some( + super::super::super::super::gdn::chunk_device::GdnChunkDevice::new_verification( + binding, + context, + dense_cache, + start, + lease.clone(), + )?, + ) + } else if let Some(context) = recurrence_context { + // Both actual state owners/status coexist with the eager + // prompt bank. No scalar four-input chain is loaned here. + // Recheck after every intervening routed cache growth. + let live_gdn = super::super::super::super::gdn::chunk_device::CHUNK_DEVICE_CHARGE; + moe_cache.reserve_mmq_transient(binding, context, live_gdn)?; + let start = chunk.begin_gdn_chunk(layer)?; + let mut owner = super::super::super::super::gdn::chunk_device::GdnChunkDevice::new( + binding, + context, + dense_cache, + start, + )?; + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if micro_gr + && !matches!( + policy, + ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr + ) + && dense_cache.has_gdn_qk_workspace() + { + owner.enable_row_queue()?; + } + Some(owner) + } else { + None + } + } else { + None + }; + // Complete all actual outer rows of this layer, releasing each + // bounded window before the next. Kernel geometry remains<=64. + let stride = if windowed { 64 } else { chunk.len() }; + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + let stride = if matches!(boundary, Some(window_numeric::BoundaryPlan::FullMicro2)) { + 2 + } else { + stride + }; + for first in (0..chunk.len()).step_by(stride) { + let window = if windowed { + Some(chunk.open_micro_window(layer)?) + } else { + None + }; + let count = chunk.micro_len()?; + let end = first.checked_add(count).ok_or(Error::Overflow)?; + if end > chunk.len() || chunk.micro_row_index(0)? != first { + return Err(Error::IdentityMismatch); + } + let mut attention = Vec::new(); + attention + .try_reserve_exact(count) + .map_err(|_| Error::InputAllocation)?; + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + let mut gr_micro_bank = None; + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + let mut ple_micro = if matches!( + policy, + ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr + ) && layer.get() == 1 + { + let (prior, inputs) = chunk.prepare_ple_micro_inputs(layer, |index, txn| { + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + InputStage::prepare_ple_micro_input( + binding, + previous[index].as_ref().ok_or(Error::IdentityMismatch)?, + txn, + ) + })?; + Some(InputStage::apply_ple_micro_cached( + binding, + context, + prior, + inputs, + dense_cache, + )?) + } else { + None + }; + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if micro_gr { + let retained_bytes = count.checked_mul(227888).ok_or(Error::Overflow)?; + moe_cache.reserve_mmq_transient(binding, context, retained_bytes)?; + #[cfg(test)] + let closed_end = chunk.test_window_journal().last().map(|(_, _, end)| *end); + attention = chunk_diagnostic( + "attention-micro-read", + Some(layer.get()), + first, + count, + chunk.read_attention_micro( + layer, + |index, txn| { + #[cfg(test)] + if let Some(window_numeric::BoundaryPlan::CancelFirstLayerAt193 { + observed, + cancelled: latch, + }) = &boundary + && layer.get() == 0 + && index == 193 + { + if txn.position().get() != 193 { + return Err(Error::IdentityMismatch); + } + observed.set(Some(( + index, + closed_end.ok_or(Error::IdentityMismatch)?, + ))); + latch.set(true); + } + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + prepare_layer_attention_micro( + binding, + layer, + previous[index].as_ref(), + txn, + dense_cache, + ple_micro.as_mut(), + ) + }, + |inputs| { + let completed = if matches!( + policy, + ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr + ) { + GrStage::read_micro_attention_native( + binding, + context, + inputs, + dense_cache, + )? + } else { + GrStage::read_micro_attention( + binding, + context, + inputs, + dense_cache, + )? + }; + let (bank, rows) = completed.into_parts(); + gr_micro_bank = Some(bank); + Ok(rows) + }, + ), + )?; + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(batch) = ple_micro.take() + && !batch.is_consumed() + { + return Err(Error::IdentityMismatch); + } + if !micro_gr { + for (local, prior) in previous[first..end].iter().enumerate() { + let index = chunk.micro_row_index(local)?; + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(window_numeric::BoundaryPlan::CancelFirstLayerAt193 { + observed, + cancelled: latch, + }) = &boundary + && layer.get() == 0 + && index == 193 + { + let (_, position) = chunk.row_ids(index)?; + if position.get() != 193 { + return Err(Error::IdentityMismatch); + } + let closed_end = + chunk.test_window_journal().last().map(|(_, _, end)| *end); + observed.set(Some((index, closed_end.ok_or(Error::IdentityMismatch)?))); + // Set only at the genuine global row. The unchanged + // cancellation callback/fence below performs refusal. + latch.set(true); + } + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + attention.push(chunk_diagnostic( + "attention-read", + Some(layer.get()), + index, + 1, + chunk.read_attention_column(index, layer, |txn| { + let read = read_layer_attention( + binding, + layer, + prior.as_ref(), + txn, + Some(dense_cache), + )?; + GrStage::detach_attention(binding, read, txn) + }), + )?); + } + } + let native_prompt = matches!( + policy, + ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr + ); + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + let native_decode_qsa = + dense_cache.has_native_qsa() && descriptor.kind() == BoundLayerKind::Qsa; + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] + let native_decode_qsa = false; + let mut projected = if native_prompt || native_decode_qsa { + // Literal prompt projections are native GEMM chains; + // the scalar Q6 column program is not also executed. + (0..count).map(|_| Vec::new()).collect() + } else { + chunk_diagnostic( + "q6-columns", + Some(layer.get()), + first, + count, + prepare_q6_layer_columns( + binding, + dense_cache, + &chunk, + layer, + descriptor.kind(), + &attention, + micro_gr && gdn_device.is_some() && verification_context.is_none(), + ), + )? + }; + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + let mut native_moe = None; + let mut ffn_rows = Vec::new(); + ffn_rows + .try_reserve_exact(count) + .map_err(|_| Error::InputAllocation)?; + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(bank) = gr_micro_bank { + for slot in &mut previous[first..end] { + let _ = slot.take(); + } + let prepared_micro = prepare_micro_ffn_rows( + binding, + layer, + descriptor.kind(), + &mut chunk, + &attention, + &mut projected, + bank, + gdn_device.as_mut(), + dense_cache, + moe_cache, + native_prompt, + &mut cancelled, + )?; + ffn_rows = prepared_micro.0; + native_moe = prepared_micro.1; + } + if !micro_gr { + for (local, previous_slot) in previous[first..end].iter_mut().enumerate() { + let index = chunk.micro_row_index(local)?; + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + let (token, pos) = chunk.row_ids(index)?; + let _ = previous_slot.take(); + let prepared = chunk_diagnostic( + "causal-attention-ffn", + Some(layer.get()), + index, + 1, + if let Some(owner) = gdn_device.as_mut() { + chunk.prepare_attention_ffn_device_gdn( + index, + layer, + &attention[local], + |txn, residual, row| { + let attention = diagnose( + ForwardPhase::Gdn, + layer.get(), + pos, + GdnStage::step_chunk_selected( + binding, + layer, + residual.ready(), + txn, + dense_cache, + owner, + row, + projected[local].first_mut(), + ), + )?; + attention.validate_origin(&binding.identity())?; + attention.identity().validate(token, pos, layer)?; + let ffn = read_chunk_attention_ffn( + binding, + residual, + attention.output(), + attention.identity(), + txn, + dense_cache, + true, + )?; + let route = diagnose( + ForwardPhase::MoeRoute, + layer.get(), + pos, + MoeRouteStage::route_from_ffn( + binding, + layer, + ffn.ready(), + txn, + Some(dense_cache), + ), + )?; + let prepared = MoeExpertStage::prepare_chunk_row( + binding, layer, ffn, route, txn, + )?; + Ok((prepared, attention.into_edge())) + }, + ) + } else { + chunk.prepare_attention_ffn( + index, + layer, + &attention[local], + |txn, residual| { + let ffn = if matches!( + policy, + ChunkMoePolicy::ExperimentalRetainedGr + | ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr + | ChunkMoePolicy::ExperimentalMtpVerification + ) { + let ffn_result: Result> = + (|| { + let ffn = match descriptor.kind() { + BoundLayerKind::Gdn => { + let prior = txn.gdn_prior(layer)?; + let mut attention = diagnose( + ForwardPhase::Gdn, + layer.get(), + pos, + if let Some(projection) = + projected[local].first_mut() + { + GdnStage::step_projected( + binding, + layer, + residual.ready(), + &prior, + txn, + dense_cache, + projection, + ) + } else { + GdnStage::step( + binding, + layer, + residual.ready(), + &prior, + txn, + Some(dense_cache), + ) + }, + )?; + attention + .validate_origin(&binding.identity())?; + attention + .identity() + .validate(token, pos, layer)?; + let pending = attention.take_pending()?; + txn.stage_gdn(&prior, pending)?; + read_chunk_attention_ffn( + binding, + residual, + attention.output(), + attention.identity(), + txn, + dense_cache, + true, + )? + } + BoundLayerKind::Qsa => { + let attention = { + #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] + let native = dense_cache.has_native_qsa().then_some(dense_cache).map(|cache| + diagnose(ForwardPhase::QsaAttention,layer.get(),pos, + QsaAttentionStage::decode_native(binding,layer,residual.ready(),txn,cache))).transpose()?; + #[cfg(not(all(any(target_os="linux",target_os="windows"),target_arch="x86_64")))] + let native = None; + if let Some(completed)=native { completed } else { + let prior = txn.qsa_prior(layer)?; + let mut prepared = diagnose( + ForwardPhase::QsaIndex, + layer.get(), + pos, + QsaIndexStage::prepare_projected( + binding, + layer, + residual.ready(), + pos, + &prior, + txn, + dense_cache, + &mut projected[local], + ), + )?; + prepared.validate_origin( + &binding.identity(), + layer, + )?; + prepared + .identity() + .validate(token, pos, layer)?; + let pending = prepared.take_pending()?; + txn.stage_qsa(&prior, pending)?; + let attention = diagnose( + ForwardPhase::QsaAttention, + layer.get(), + pos, + QsaAttentionStage::decode_with_scratch( + binding, + layer, + prepared, + txn, + Some(dense_cache), + dense_cache.qsa_attention_workspace(), + ), + )?; + attention + } + }; + attention.validate_origin( + &binding.identity(), + layer, + )?; + attention + .identity() + .validate(token, pos, layer)?; + read_chunk_attention_ffn( + binding, + residual, + attention.output(), + attention.identity(), + txn, + dense_cache, + true, + )? + } + }; + Ok(ffn) + })(); + ffn_result? + } else { + let injected_result = (|| { + let injected = match descriptor.kind() { + BoundLayerKind::Gdn => { + let prior = txn.gdn_prior(layer)?; + let mut attention = diagnose( + ForwardPhase::Gdn, + layer.get(), + pos, + if let Some(projection) = + projected[local].first_mut() + { + GdnStage::step_projected( + binding, + layer, + residual.ready(), + &prior, + txn, + dense_cache, + projection, + ) + } else { + GdnStage::step( + binding, + layer, + residual.ready(), + &prior, + txn, + Some(dense_cache), + ) + }, + )?; + attention + .validate_origin(&binding.identity())?; + attention + .identity() + .validate(token, pos, layer)?; + let pending = attention.take_pending()?; + txn.stage_gdn(&prior, pending)?; + diagnose( + ForwardPhase::GrAttentionInject, + layer.get(), + pos, + GrStage::inject_detached( + binding, + residual, + attention.output(), + attention.identity(), + txn, + ), + )? + } + BoundLayerKind::Qsa => { + let attention = { + #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] + let native = dense_cache.has_native_qsa().then_some(dense_cache).map(|cache| + diagnose(ForwardPhase::QsaAttention,layer.get(),pos, + QsaAttentionStage::decode_native(binding,layer,residual.ready(),txn,cache))).transpose()?; + #[cfg(not(all(any(target_os="linux",target_os="windows"),target_arch="x86_64")))] + let native = None; + if let Some(completed)=native { completed } else { + let prior = txn.qsa_prior(layer)?; + let mut prepared = diagnose( + ForwardPhase::QsaIndex, + layer.get(), + pos, + QsaIndexStage::prepare_projected( + binding, + layer, + residual.ready(), + pos, + &prior, + txn, + dense_cache, + &mut projected[local], + ), + )?; + prepared.validate_origin( + &binding.identity(), + layer, + )?; + prepared + .identity() + .validate(token, pos, layer)?; + let pending = prepared.take_pending()?; + txn.stage_qsa(&prior, pending)?; + let attention = diagnose( + ForwardPhase::QsaAttention, + layer.get(), + pos, + QsaAttentionStage::decode_with_scratch( + binding, + layer, + prepared, + txn, + Some(dense_cache), + dense_cache.qsa_attention_workspace(), + ), + )?; + attention + } + }; + attention.validate_origin( + &binding.identity(), + layer, + )?; + attention + .identity() + .validate(token, pos, layer)?; + diagnose( + ForwardPhase::GrAttentionInject, + layer.get(), + pos, + GrStage::inject_detached( + binding, + residual, + attention.output(), + attention.identity(), + txn, + ), + )? + } + }; + Ok(injected) + })( + ); + let injected = residual.finish(injected_result)?; + diagnose( + ForwardPhase::GrFfn, + layer.get(), + pos, + GrStage::read_ffn( + binding, + layer, + &injected, + txn, + Some(dense_cache), + ), + )? + }; + (|| { + let route = diagnose( + ForwardPhase::MoeRoute, + layer.get(), + pos, + MoeRouteStage::route_from_ffn( + binding, + layer, + ffn.ready(), + txn, + Some(dense_cache), + ), + )?; + MoeExpertStage::prepare_chunk_row( + binding, layer, ffn, route, txn, + ) + })() + }, + ) + }, + )?; + ffn_rows.push(prepared); + } + } + drop(projected); + drop(attention); + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if matches!(policy, ChunkMoePolicy::Layer0Diagnostic) { + if layer.get() != 0 { + return Err(Error::IdentityMismatch); + } + MoeExpertStage::test_layer0_same_rows( + binding, layer, &ffn_rows, &mut chunk, moe_cache, + )?; + // Actual unpublished chunk drops here, before FFN injection/MTP/head. + return Err(Error::Unsupported(Stage::Executor)); + } + let experts = chunk_diagnostic("moe-experts", Some(layer.get()), first, count, { + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + let native_result = if native_prompt { + Some(MoeExpertStage::execute_chunk_mmq_native_prompt( + binding, + layer, + &ffn_rows, + &mut chunk, + moe_cache, + &mut cancelled, + native_moe.as_mut().ok_or(Error::IdentityMismatch)?, + dense_cache, + )) + } else { + None + }; + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] + let native_result: Option< + Result>, + > = None; + if let Some(result) = native_result { + result + } else { + match policy { + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + ChunkMoePolicy::Layer0Diagnostic => { + return Err(Error::IdentityMismatch); + } + ChunkMoePolicy::Native | ChunkMoePolicy::ExperimentalRetainedGr => { + MoeExpertStage::execute_chunk( + binding, + layer, + &ffn_rows, + &mut chunk, + moe_cache, + &mut cancelled, + ) + } + ChunkMoePolicy::ExperimentalResidentMmq + | ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr + | ChunkMoePolicy::ExperimentalMtpVerification => { + MoeExpertStage::execute_chunk_mmq( + binding, + layer, + &ffn_rows, + &mut chunk, + moe_cache, + &mut cancelled, + ) + } + } + } + }); + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + let cleanup = native_moe + .take() + .map_or(Ok(()), |products| products.release()); + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] + let cleanup = Ok(()); + if cleanup.is_err() { + moe_cache.note_transport_failure(); + } + let experts = experts.and_then(|values| cleanup.map(|()| values))?; + if experts.len() != ffn_rows.len() { + return Err(Error::IdentityMismatch); + } + let mut batch_rows = Vec::new(); + let mut proofs = Vec::new(); + batch_rows + .try_reserve_exact(ffn_rows.len()) + .map_err(|_| Error::InputAllocation)?; + proofs + .try_reserve_exact(ffn_rows.len()) + .map_err(|_| Error::InputAllocation)?; + for (local, (row, expert)) in ffn_rows.into_iter().zip(experts).enumerate() { + let index = chunk.micro_row_index(local)?; + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + let (prepared, proof) = + chunk.prepare_ffn_injection(index, layer, row, binding, expert)?; + batch_rows.push(prepared); + proofs.push(proof); + } + // Actual single CUDA launch over tightly packed token columns, + // then only genuine finite FFN producers complete the rows. + let completed = chunk_diagnostic( + "gr-ffn-batch-inject", + Some(layer.get()), + first, + count, + chunk.batch_outputs(|context| { + GrStage::inject_batch(binding, context, batch_rows, dense_cache) + }), + )?; + if completed.len() != proofs.len() { + return Err(Error::IdentityMismatch); + } + for ((slot, proof), residual) in + previous[first..end].iter_mut().zip(proofs).zip(completed) + { + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + *slot = Some(chunk.complete_layer_batch(proof, residual)?); + } + // All temporaries/projection borrows were consumed or dropped. + // Consuming this actual capability is the sole window transition. + if let Some(window) = window { + chunk.close_micro_window(window)?; + } + } + // The last real micro capability has closed and all actual FFN + // rows completed. Only now materialize/adopt the canonical boundary. + if let Some(owner) = gdn_device.take() { + chunk.finish_gdn_chunk(owner, binding, dense_cache)?; + } + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if matches!(boundary, Some(window_numeric::BoundaryPlan::FirstLayer)) + && layer.get() == 0 + { + chunk.test_observe_first_layer(&previous)?; + return Ok(chunk); // Deliberately unfinished: cannot warm or publish. + } + } + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if verification_lease.is_some() { + chunk.materialize_device_gdn_observer(binding, dense_cache, &mut cancelled)?; + } + let mut execute_head = |txn: &mut QwenStepTxn<'_, 'driver>, residual: &InjectedResidual| { + if matches!(policy, ChunkMoePolicy::ExperimentalMtpVerification) && cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + let logits = chunk_diagnostic( + "output-head", + None, + 0, + 1, + output.logits_cached(binding, residual, txn, Some(dense_cache)), + )?; + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + output.test_reset_replay_capture(&logits)?; + txn.finish_forward(logits) + }; + if matches!(policy, ChunkMoePolicy::ExperimentalMtpVerification) { + chunk.finish_mtp_verification(&previous, &mut execute_head)?; + } else { + chunk.finish(&previous, execute_head)?; + } + Ok(chunk) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/gdn_chain/impl_chain.rs b/crates/leleka-runtime/src/qwen_forward/gdn_chain/impl_chain.rs index 226204c1..8bf95777 100644 --- a/crates/leleka-runtime/src/qwen_forward/gdn_chain/impl_chain.rs +++ b/crates/leleka-runtime/src/qwen_forward/gdn_chain/impl_chain.rs @@ -3,768 +3,11 @@ #[allow(unused_imports)] use super::*; -impl<'ctx> Chain<'ctx> { - pub(in super::super) fn new( - context: &'ctx Context<'ctx>, - binding: BindingIdentity, - identity: TokenLayer, - failed: Rc>, - ) -> Result { - if failed.get() { - return Err(Error::CudaExecution); - } - if identity.layer().get() >= 48 || identity.layer().get() % 4 == 3 { - return Err(Error::InvalidLayer); - } - let mut buffers = Vec::new(); - buffers - .try_reserve_exact(32) - .map_err(|_| Error::InputAllocation)?; - Ok(Self { - context, - binding, - identity, - epoch: Rc::new(()), - failed, - buffers, - qk_workspace: None, - qk_return: None, - verification_pool: None, - fixed_slots: Vec::new(), - }) - } - pub(in super::super) fn validate( - &self, - context: &Context<'_>, - binding: &BindingIdentity, - identity: TokenLayer, - ) -> Result<()> { - if self.failed.get() { - return Err(Error::CudaExecution); - } - if !std::ptr::eq(self.context, context) - || !self.binding.matches(binding) - || self.identity != identity - { - return Err(Error::IdentityMismatch); - } - Ok(()) - } - pub(in super::super) fn set_verification_pool(&mut self, pool: super::super::verification::PoolRow<'ctx>) -> Result<()> { - self.check()?; - if !self.buffers.is_empty() || self.qk_workspace.is_some() || self.verification_pool.is_some() { return Err(Error::IdentityMismatch); } - self.fixed_slots.try_reserve_exact(5).map_err(|_| Error::InputAllocation)?; - self.verification_pool = Some(RefCell::new(pool)); - Ok(()) - } - pub(super) fn return_fixed(&self, role: Role, buffer: DeviceBuffer<'ctx>) -> Option { - let result = self.verification_pool.as_ref().ok_or(Error::IdentityMismatch).and_then(|pool| { - pool.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.put(role, buffer) - }); - if result.is_err() { self.failed.set(true); } - result.err() - } - pub(in super::super) fn set_qk_workspace(&mut self, owner: Rc>) -> Result<()> { - self.check()?; - if self.qk_workspace.is_some() || !self.buffers.is_empty() - || self.identity.layer().get() >= 48 || self.identity.layer().get() % 4 == 3 - { return Err(Error::IdentityMismatch); } - owner.validate(self.context, &self.binding, &self.failed)?; - self.qk_workspace = Some(owner); - Ok(()) - } - pub(in super::super) fn scope_key(&self) -> Rc<()> { - self.epoch.clone() - } - pub(super) fn check(&self) -> Result<()> { - if self.failed.get() { - Err(Error::CudaExecution) - } else { - Ok(()) - } - } - pub(in super::super) fn buffer(&self, product: &Product, role: Role) -> Result<&DeviceBuffer<'ctx>> { - self.check()?; - if product.role != role || !Rc::ptr_eq(&self.epoch, &product.epoch) { - return Err(Error::IdentityMismatch); - } - validate_values(&product.values, role.count())?; - if let Some(returning) = &self.qk_return - && returning.slot == product.slot - { - if role != Role::Qk || returning.row != self.identity - || !Rc::ptr_eq(&returning.epoch, &self.epoch) - { return Err(Error::IdentityMismatch); } - returning.owner.validate(self.context, &self.binding, &self.failed)?; - } - let buffer = self - .buffers - .get(product.slot) - .and_then(Option::as_ref) - .ok_or(Error::IdentityMismatch)?; - if buffer.len() != role.count() * 4 { - return Err(Error::InvalidDimension); - } - Ok(buffer) - } - // Shared slot validation of pending operands and completed products. - pub(super) fn device_slot(&self, slot: usize, product_role: Role, epoch: &Rc<()>, role: Role) -> Result<&DeviceBuffer<'ctx>> { - self.check()?; - if product_role != role || !Rc::ptr_eq(&self.epoch, epoch) { - return Err(Error::IdentityMismatch); - } - if let Some(returning) = &self.qk_return - && returning.slot == slot - { - if role != Role::Qk || returning.row != self.identity - || !Rc::ptr_eq(&returning.epoch, &self.epoch) - { return Err(Error::IdentityMismatch); } - returning.owner.validate(self.context, &self.binding, &self.failed)?; - } - let buffer = self - .buffers - .get(slot) - .and_then(Option::as_ref) - .ok_or(Error::IdentityMismatch)?; - if buffer.len() != role.count() * 4 { - return Err(Error::InvalidDimension); - } - Ok(buffer) - } - pub(in super::super) fn device_buffer(&self, product: &DeviceProduct, role: Role) -> Result<&DeviceBuffer<'ctx>> { - self.device_slot(product.slot, product.role, &product.epoch, role) - } - // Pending operands are admissible only as inputs/outputs of the queued prefix. - pub(super) fn operand_buffer(&self, operand: &DeviceOperand, role: Role) -> Result<&DeviceBuffer<'ctx>> { - self.device_slot(operand.slot, operand.role, &operand.epoch, role) - } - // Mint the completed product from a pending operand. Callable only after a - // clean complete drain that scanned that operand's buffer. - pub(super) fn complete(&self, operand: DeviceOperand) -> DeviceProduct { - DeviceProduct { slot: operand.slot, role: operand.role, epoch: operand.epoch } - } - pub(super) fn track_device(&mut self, role: Role, buffer: DeviceBuffer<'ctx>) -> DeviceOperand { - let slot = self.buffers.len(); - self.buffers.push(Some(buffer)); - DeviceOperand { slot, role, epoch: self.epoch.clone() } - } - // Queued rows never use the fixed verification pool; those rows keep the - // scalar path unchanged. - pub(super) fn reserve_device(&mut self, role: Role) -> Result { - self.check()?; - if self.verification_pool.is_some() { return Err(Error::IdentityMismatch); } - self.buffers.try_reserve(1).map_err(|_| Error::InputAllocation)?; - let buffer = allocate(self.context, role.count())?; - Ok(self.track_device(role, buffer)) - } - // The retained whole QK slot with its preset positive-zero tail; only the - // original GdnQk kernel writes its first 4096 words. It returns to the - // workspace through the same slot bookkeeping as `normalize_qk`. - pub(super) fn reserve_qk_device(&mut self) -> Result { - self.check()?; - let owner = self.qk_workspace.clone().ok_or(Error::IdentityMismatch)?; - if self.qk_return.is_some() || self.verification_pool.is_some() { - return Err(Error::IdentityMismatch); - } - self.buffers.try_reserve(1).map_err(|_| Error::InputAllocation)?; - let buffer = owner.take(self.context, &self.binding, &self.failed)?; - let product = self.track_device(Role::Qk, buffer); - self.qk_return = Some(QkReturn { - owner, slot: product.slot, row: self.identity, epoch: Rc::clone(&self.epoch), - }); - Ok(product) - } - // Same projection call as `project`, but the output stays on device; its - // finite scan is queued, never skipped. Only the three queue-scanned roles. - pub(in super::super) fn project_device( - &mut self, - matrix: &DeviceBuffer<'_>, - kind: GdnMatrixKind, - source: &DeviceBuffer<'_>, - role: Role, - ) -> Result { - if !matches!(role, Role::Alpha | Role::BetaRaw | Role::Z) { - return Err(Error::IdentityMismatch); - } - let product = self.reserve_device(role)?; - let operation = { - let output = self - .buffers - .get_mut(product.slot) - .and_then(Option::as_mut) - .ok_or(Error::IdentityMismatch)?; - dispatch_projection(self.context, matrix, source, output, kind, 2560, role.count()) - .map_err(driver_error) - }; - if let Err(primary) = operation { - self.note(primary); - return Err(primary); - } - Ok(product) - } - pub(in super::super) fn project_out_device( - &mut self, - matrix: &DeviceBuffer<'_>, - kind: GdnMatrixKind, - normalized: &DeviceProduct, - ) -> Result { - let [product] = self.produce([Role::Out], |chain, out| { - dispatch_projection( - chain.context, - matrix, - chain.device_buffer(normalized, Role::Normalized)?, - &mut out[0], - kind, - VALUES, - 2560, - ) - .map_err(driver_error)?; - Ok([download(&out[0], 2560)?]) - })?; - Ok(product) - } - // ONE drain for conv, QK, beta sigmoid, gates, recurrence, out-norm and a - // full finite scan of every stage output. The scalar chain's twelve - // intermediate host readbacks and its separate launch fences are gone; the - // arithmetic assets, operand order and finite boundaries are the same, and - // the earliest non-finite stage still refuses the row. Nothing is published - // unless the complete drain was clean. - pub(in super::super) fn run_row_queue( - &mut self, - queue: &mut GdnRowQueue<'ctx>, - inputs: QueueInputs<'_, 'ctx>, - ) -> Result { - self.check()?; - if self.verification_pool.is_some() || self.qk_workspace.is_none() { - return Err(Error::IdentityMismatch); - } - // Product allocations first: all of them are chain slots, so any later - // refusal is freed or returned by the ordinary drain. - let raw = self.reserve_device(Role::Raw)?; - let next = self.reserve_device(Role::NextHistory)?; - let h = self.reserve_device(Role::H)?; - let qk = self.reserve_qk_device()?; - let sigmoid = self.reserve_device(Role::Beta)?; - let gate = self.reserve_device(Role::Gate)?; - let readout = self.reserve_device(Role::Readout)?; - let normalized = self.reserve_device(Role::Normalized)?; - let drained = (|| -> Result<_> { - let this = &*self; - let history = this.buffer(inputs.history, Role::History)?; - let qkv = match &inputs.qkv { - QkvInput::Host(product) => Some(this.buffer(product, Role::Qkv)?), - QkvInput::Columns { .. } => None, - }; - let alpha = this.operand_buffer(inputs.alpha, Role::Alpha)?; - let beta_raw = this.operand_buffer(inputs.beta_raw, Role::BetaRaw)?; - let z = this.operand_buffer(inputs.z, Role::Z)?; - let raw_buffer = this.operand_buffer(&raw, Role::Raw)?; - let next_buffer = this.operand_buffer(&next, Role::NextHistory)?; - let h_buffer = this.operand_buffer(&h, Role::H)?; - let qk_buffer = this.operand_buffer(&qk, Role::Qk)?; - let sigmoid_buffer = this.operand_buffer(&sigmoid, Role::Beta)?; - let gate_buffer = this.operand_buffer(&gate, Role::Gate)?; - let readout_buffer = this.operand_buffer(&readout, Role::Readout)?; - let normalized_buffer = this.operand_buffer(&normalized, Role::Normalized)?; - let mut prefix = queue.begin().map_err(driver_error)?; - if let QkvInput::Columns { buffer, row } = &inputs.qkv { - prefix.scan_qkv_columns(buffer, *row).map_err(driver_error)?; - } - prefix.scan_alpha(alpha).map_err(driver_error)?; - prefix.scan_beta_raw(beta_raw).map_err(driver_error)?; - match (&inputs.qkv, qkv) { - (QkvInput::Host(_), Some(qkv)) => prefix - .conv_silu(history, qkv, inputs.conv_weights, next_buffer, raw_buffer, h_buffer) - .map_err(driver_error)?, - (QkvInput::Columns { buffer, row }, None) => prefix - .conv_silu_columns( - history, - buffer, - *row, - inputs.conv_weights, - next_buffer, - raw_buffer, - h_buffer, - ) - .map_err(driver_error)?, - _ => return Err(Error::IdentityMismatch), - } - prefix.qk_l2(h_buffer, qk_buffer, inputs.epsilon).map_err(driver_error)?; - prefix.beta_sigmoid(beta_raw, sigmoid_buffer).map_err(driver_error)?; - prefix - .gate_softplus(alpha, inputs.dt, inputs.a, gate_buffer) - .map_err(driver_error)?; - prefix - .recurrence( - inputs.state, - qk_buffer, - h_buffer, - gate_buffer, - sigmoid_buffer, - inputs.next_state, - readout_buffer, - ) - .map_err(driver_error)?; - prefix.scan_z(z).map_err(driver_error)?; - prefix - .out_norm(readout_buffer, z, inputs.gamma, normalized_buffer, inputs.epsilon) - .map_err(driver_error)?; - prefix.fetch_next_history(next_buffer).map_err(driver_error)?; - prefix.finish().map_err(driver_error) - })(); - let completion = match drained { - Ok(completion) => completion, - Err(primary) => { - self.note(primary); - return Err(primary); - } - }; - // A completed numerical refusal is the same NonFinite as the scalar - // chain's full readback validation; no history is returned. - let values = completion - .into_next_history() - .map_err(|_| Error::NonFinite)?; - validate_values(&values, Role::NextHistory.count())?; - Ok(QueuedRow { - next_history: Product { - slot: next.slot, - role: Role::NextHistory, - epoch: next.epoch.clone(), - values, - }, - normalized: self.complete(normalized), - }) - } - pub(in super::super) fn borrow_recurrence<'chain>( - &'chain mut self, - row: &super::super::super::session::chunk::GdnChunkRow, - products: [&'chain Product; 4], - ) -> Result> { - self.check()?; - if row.identity() != self.identity { - return Err(Error::IdentityMismatch); - } - let roles = [Role::Qk, Role::H, Role::Gate, Role::Beta]; - // Validate every source/witness before freeing anything. Product fields - // are private and only completed producers can mint these identities. - for (product, role) in products.into_iter().zip(roles) { - self.buffer(product, role)?; - } - let slots = products.map(|product| product.slot); - for (index, slot) in slots.iter().enumerate() { - if slots[..index].contains(slot) { - return Err(Error::IdentityMismatch); - } - } - // History has already been consumed as its unchanged canonical host - // product. Retain only the four current recurrence input allocations. - self.release_in_scope(&slots)?; - Ok(RecurrenceBorrow { - row: row.readout_key(), - scope: Rc::clone(&self.epoch), - chain: self, - products, - }) - } - pub(in super::super) fn borrow_scalar_recurrence<'chain>( - &'chain mut self, - prior: &super::super::GdnPrior, - txn: &super::super::QwenStepTxn<'_, '_>, - products: [&'chain Product; 4], - ) -> Result> { - txn.validate_binding(&self.binding)?; - txn.validate_input(self.identity.token(), self.identity.position())?; - txn.validate_gdn_prior(prior, self.identity.layer())?; - self.validate(txn.cuda_context()?, &self.binding, self.identity)?; - for (product, role) in products - .into_iter() - .zip([Role::Qk, Role::H, Role::Gate, Role::Beta]) - { - self.buffer(product, role)?; - } - let slots = products.map(|product| product.slot); - for (index, slot) in slots.iter().enumerate() { - if slots[..index].contains(slot) { - return Err(Error::IdentityMismatch); - } - } - // All witnesses and current producer identities precede any cleanup. - self.release_in_scope(&slots)?; - Ok(ScalarRecurrenceBorrow { - prior: prior.clone(), - scope: Rc::clone(&self.epoch), - chain: self, - products, - }) - } - pub(in super::super) fn release_chunk_sources(&mut self) -> Result<()> { - self.release_in_scope(&[]) - } - pub(super) fn release_in_scope(&mut self, retained: &[usize]) -> Result<()> { - let mut error = None; - for slot in (0..self.buffers.len()).rev() { - if !retained.contains(&slot) - && let Some(buffer) = self.buffers[slot].take() - { - let failure = if self.qk_return.as_ref().is_some_and(|v| v.slot == slot) { - let returning = self.qk_return.take().expect("actual retained QK slot"); - returning.owner.put(buffer).err() - } else if let Some((_, role)) = self.fixed_slots.iter().find(|(actual, _)| *actual == slot) { - self.return_fixed(*role, buffer) - } else { - self.free(buffer) - }; - if let Some(failure) = failure { error.get_or_insert(failure); } - } - } - // Keep every vacated slot until ordinary drain rotates the epoch. - // Later readout/Z products append; no stale product can alias a reused - // slot while the completed readout still carries this exact scope. - error.map_or(Ok(()), Err) - } - pub(super) fn track(&mut self, role: Role, buffer: DeviceBuffer<'ctx>, values: Box<[f32]>) -> Product { - let slot = self.buffers.len(); - if self.verification_pool.is_some() && matches!(role, Role::Qk | Role::H | Role::Gate | Role::Beta | Role::Readout) { - self.fixed_slots.push((slot, role)); - } - self.buffers.push(Some(buffer)); - Product { - slot, - role, - epoch: self.epoch.clone(), - values, - } - } - pub(in super::super) fn upload(&mut self, role: Role, values: &[f32]) -> Result { - self.check()?; - if !matches!( - role, - Role::Input | Role::History | Role::Conv | Role::Dt | Role::A | Role::Gamma - ) { - return Err(Error::IdentityMismatch); - } - self.upload_values(role, values) - } - // Only this importer can admit computed QKV: the real sealed producer - // must pass all original branch/source/provider/one-use checks first. - #[allow(clippy::too_many_arguments)] - pub(in super::super) fn import_projected_qkv( - &mut self, - projection: &mut super::super::super::q6_attention_columns::ProjectionRow<'_, '_>, - binding: &super::super::ModelBinding, - cache: &super::super::DenseWeightCache<'_>, - txn: &super::super::QwenStepTxn<'_, '_>, - layer: super::super::LayerId, - input: &super::super::ResidualReady, - ) -> Result { - self.validate(txn.cuda_context()?, &binding.identity(), input.identity())?; - let values = projection.take( - binding, - cache, - txn, - layer, - input, - super::super::super::q6_attention_columns::Role::GdnQkv, - )?; - self.upload_values(Role::Qkv, &values) - } - pub(super) fn upload_values(&mut self, role: Role, values: &[f32]) -> Result { - self.check()?; - self.buffers - .try_reserve(1) - .map_err(|_| Error::InputAllocation)?; - validate_values(values, role.count())?; - let mut bytes = Vec::new(); - bytes - .try_reserve_exact(values.len() * 4) - .map_err(|_| Error::InputAllocation)?; - for value in values { - bytes.extend_from_slice(&value.to_le_bytes()); - } - let mut host = Vec::new(); - host.try_reserve_exact(values.len()) - .map_err(|_| Error::InputAllocation)?; - host.extend_from_slice(values); - let mut buffer = allocate(self.context, role.count())?; - if let Err(error) = buffer.copy_from(&bytes) { - let primary = driver_error(error); - self.note(primary); - self.free(buffer); - return Err(primary); - } - Ok(self.track(role, buffer, host.into_boxed_slice())) - } - pub(super) fn note(&self, error: Error) { - if error == Error::CudaExecution { - self.failed.set(true); - } - } - pub(super) fn free(&self, buffer: DeviceBuffer<'ctx>) -> Option { - match buffer.release() { - Ok(()) => None, - Err(error) => { - self.failed.set(true); - Some(driver_error(error)) - } - } - } - // Producers perform the kernel and all mandatory finite D2H themselves. - // Callers never provide a separately computed numeric proof for a buffer. - pub(super) fn produce( - &mut self, - roles: [Role; N], - operation: impl FnOnce(&Self, &mut [DeviceBuffer<'ctx>]) -> Result<[Box<[f32]>; N]>, - ) -> Result<[Product; N]> { - self.check()?; - self.buffers - .try_reserve(N) - .map_err(|_| Error::InputAllocation)?; - let mut buffers = Vec::new(); - buffers - .try_reserve_exact(N) - .map_err(|_| Error::InputAllocation)?; - let mut products = Vec::new(); - products - .try_reserve_exact(N) - .map_err(|_| Error::InputAllocation)?; - let result = (|| { - for role in roles { - let fixed = self.verification_pool.as_ref().map(|pool| { - pool.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.take(role) - }).transpose()?.flatten(); - buffers.push(match fixed { Some(buffer) => buffer, None => allocate(self.context, role.count())? }); - } - operation(self, &mut buffers) - })(); - let values = match result { - Ok(values) => values, - Err(primary) => { - self.note(primary); - for (buffer, role) in buffers.into_iter().zip(roles) { - if self.verification_pool.is_some() && matches!(role, Role::Qk | Role::H | Role::Gate | Role::Beta) { - self.return_fixed(role, buffer); - } else { self.free(buffer); } - } - return Err(primary); - } - }; - for ((buffer, values), role) in buffers.into_iter().zip(values).zip(roles) { - products.push(self.track(role, buffer, values)); - } - products.try_into().map_err(|_| Error::IdentityMismatch) - } - pub(in super::super) fn project( - &mut self, - matrix: &DeviceBuffer<'_>, - kind: GdnMatrixKind, - source: &DeviceBuffer<'_>, - role: Role, - ) -> Result { - let columns = match role { - Role::Qkv | Role::Alpha | Role::BetaRaw | Role::Z => 2560, - _ => return Err(Error::IdentityMismatch), - }; - let [product] = self.produce([role], |chain, out| { - dispatch_projection( - chain.context, - matrix, - source, - &mut out[0], - kind, - columns, - role.count(), - ) - .map_err(driver_error)?; - Ok([download(&out[0], role.count())?]) - })?; - Ok(product) - } - pub(in super::super) fn project_out( - &mut self, - matrix: &DeviceBuffer<'_>, - kind: GdnMatrixKind, - normalized: &Product, - ) -> Result { - let [product] = self.produce([Role::Out], |chain, out| { - dispatch_projection( - chain.context, - matrix, - chain.buffer(normalized, Role::Normalized)?, - &mut out[0], - kind, - VALUES, - 2560, - ) - .map_err(driver_error)?; - Ok([download(&out[0], 2560)?]) - })?; - Ok(product) - } - pub(in super::super) fn convolve( - &mut self, - history: &Product, - qkv: &Product, - weights: &DeviceBuffer<'_>, - ) -> Result<(Product, Product)> { - let [next, _raw, h] = - self.produce([Role::NextHistory, Role::Raw, Role::H], |chain, out| { - let (next, rest) = out.split_at_mut(1); - let (raw, h) = rest.split_at_mut(1); - chain - .context - .gdn_conv_silu_f32( - chain.buffer(history, Role::History)?, - chain.buffer(qkv, Role::Qkv)?, - weights, - &mut next[0], - &mut raw[0], - &mut h[0], - ) - .map_err(driver_error)?; - let raw_values = download(&raw[0], CHANNELS)?; - let next_values = download(&next[0], HISTORY_ELEMENTS)?; - let h_values = download(&h[0], CHANNELS)?; - Ok([next_values, raw_values, h_values]) - })?; - Ok((next, h)) - } - pub(in super::super) fn normalize_qk(&mut self, h: &Product, epsilon: f32) -> Result { - if let Some(owner) = self.qk_workspace.clone() { - self.check()?; - if self.qk_return.is_some() { return Err(Error::IdentityMismatch); } - self.buffers.try_reserve(1).map_err(|_| Error::InputAllocation)?; - let mut buffer = owner.take(self.context, &self.binding, &self.failed)?; - let operation = self.buffer(h, Role::H).and_then(|h| { - normalize_retained_qk(self.context, h, &mut buffer, epsilon) - }); - let values = match operation { - Ok(values) => values, - Err(primary) => { - self.note(primary); - let _ = owner.put(buffer); - return Err(primary); - } - }; - let product = self.track(Role::Qk, buffer, values); - self.qk_return = Some(QkReturn { - owner, slot: product.slot, row: self.identity, epoch: Rc::clone(&self.epoch), - }); - return Ok(product); - } - let [product] = self.produce([Role::Qk], |chain, out| { - // Fixed ABI writes only4096 words; preserve original initialized tail. - out[0] - .copy_from(&[0u8; CHANNELS * 4]) - .map_err(driver_error)?; - chain - .context - .gdn_qk_l2_f32(chain.buffer(h, Role::H)?, &mut out[0], epsilon) - .map_err(driver_error)?; - Ok([download(&out[0], CHANNELS)?]) - })?; - Ok(product) - } - pub(in super::super) fn gates( - &mut self, - alpha: &Product, - beta: &Product, - dt: &DeviceBuffer<'_>, - a: &DeviceBuffer<'_>, - ) -> Result<(Product, Product)> { - let [sigmoid, gate] = self.produce([Role::Beta, Role::Gate], |chain, out| { - chain - .context - .gdn_beta_sigmoid_f32(chain.buffer(beta, Role::BetaRaw)?, &mut out[0]) - .map_err(driver_error)?; - // Read and validate sigmoid before invoking gate, matching legacy. - let sigmoid = download(&out[0], 48)?; - chain - .context - .gdn_gate_softplus_f32(chain.buffer(alpha, Role::Alpha)?, dt, a, &mut out[1]) - .map_err(driver_error)?; - Ok([sigmoid, download(&out[1], 48)?]) - })?; - Ok((gate, sigmoid)) - } - pub(in super::super) fn import_readout( - &mut self, - readout: super::super::mirror::MirrorReadout<'ctx>, - prior: &super::super::GdnPrior, - ) -> Result { - self.check()?; - if !prior.mirror_admits(&self.binding, self.identity.layer().get()) { - return Err(Error::IdentityMismatch); - } - self.buffers - .try_reserve(1) - .map_err(|_| Error::InputAllocation)?; - let (buffer, values) = readout.into_parts( - self.context, - &self.failed, - prior, - self.identity, - &self.epoch, - )?; - Ok(self.track(Role::Readout, buffer, values)) - } - pub(in super::super) fn import_chunk_readout( - &mut self, - readout: super::super::chunk_device::ChunkReadout<'ctx>, - row: &super::super::super::session::chunk::GdnChunkRow, - ) -> Result { - self.check()?; - self.buffers - .try_reserve(1) - .map_err(|_| Error::InputAllocation)?; - if row.identity() != self.identity { - return Err(Error::IdentityMismatch); - } - let (buffer, values) = readout.into_parts(self.context, &self.failed, row, &self.epoch)?; - Ok(self.track(Role::Readout, buffer, values)) - } - pub(in super::super) fn out_norm( - &mut self, - readout: &Product, - z: &Product, - gamma: &DeviceBuffer<'_>, - epsilon: f32, - ) -> Result { - let [product] = self.produce([Role::Normalized], |chain, out| { - chain - .context - .gdn_out_norm_f32( - chain.buffer(readout, Role::Readout)?, - chain.buffer(z, Role::Z)?, - gamma, - &mut out[0], - epsilon, - ) - .map_err(driver_error)?; - Ok([download(&out[0], VALUES)?]) - })?; - Ok(product) - } - pub(in super::super) fn drain(&mut self) -> Result<()> { - // Epoch change makes all old capabilities invalid even when slots are reused. - self.epoch = Rc::new(()); - let mut error = None; - while let Some(buffer) = self.buffers.pop() { - let slot = self.buffers.len(); - if let Some(buffer) = buffer { - let failure = if self.qk_return.as_ref().is_some_and(|v| v.slot == slot) { - let returning = self.qk_return.take().expect("actual retained QK slot"); - returning.owner.put(buffer).err() - } else if let Some((_, role)) = self.fixed_slots.iter().find(|(actual, _)| *actual == slot) { - self.return_fixed(*role, buffer) - } else { - self.free(buffer) - }; - if let Some(failure) = failure { error.get_or_insert(failure); } - } - } - error.map_or(Ok(()), Err) - } - pub(in super::super) fn finish(mut self) -> Result<()> { - self.drain() - } -} +#[path = "impl_chain/impl_chain_2.rs"] +mod impl_chain_2; +#[path = "impl_chain/impl_chain_2_2.rs"] +mod impl_chain_2_2; +#[path = "impl_chain/impl_chain_3.rs"] +mod impl_chain_3; +#[path = "impl_chain/impl_chain_4.rs"] +mod impl_chain_4; diff --git a/crates/leleka-runtime/src/qwen_forward/gdn_chain/impl_chain/impl_chain_2.rs b/crates/leleka-runtime/src/qwen_forward/gdn_chain/impl_chain/impl_chain_2.rs new file mode 100644 index 00000000..b6cb3f59 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/gdn_chain/impl_chain/impl_chain_2.rs @@ -0,0 +1,227 @@ +//! Moved out of the parent module by STRA-338: impl Chain. + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> Chain<'ctx> { + pub(in super::super::super) fn new( + context: &'ctx Context<'ctx>, + binding: BindingIdentity, + identity: TokenLayer, + failed: Rc>, + ) -> Result { + if failed.get() { + return Err(Error::CudaExecution); + } + if identity.layer().get() >= 48 || identity.layer().get() % 4 == 3 { + return Err(Error::InvalidLayer); + } + let mut buffers = Vec::new(); + buffers + .try_reserve_exact(32) + .map_err(|_| Error::InputAllocation)?; + Ok(Self { + context, + binding, + identity, + epoch: Rc::new(()), + failed, + buffers, + qk_workspace: None, + qk_return: None, + verification_pool: None, + fixed_slots: Vec::new(), + }) + } + pub(in super::super::super) fn validate( + &self, + context: &Context<'_>, + binding: &BindingIdentity, + identity: TokenLayer, + ) -> Result<()> { + if self.failed.get() { + return Err(Error::CudaExecution); + } + if !std::ptr::eq(self.context, context) + || !self.binding.matches(binding) + || self.identity != identity + { + return Err(Error::IdentityMismatch); + } + Ok(()) + } + pub(in super::super::super) fn set_verification_pool(&mut self, pool: super::super::super::verification::PoolRow<'ctx>) -> Result<()> { + self.check()?; + if !self.buffers.is_empty() || self.qk_workspace.is_some() || self.verification_pool.is_some() { return Err(Error::IdentityMismatch); } + self.fixed_slots.try_reserve_exact(5).map_err(|_| Error::InputAllocation)?; + self.verification_pool = Some(RefCell::new(pool)); + Ok(()) + } + pub(in super::super) fn return_fixed(&self, role: Role, buffer: DeviceBuffer<'ctx>) -> Option { + let result = self.verification_pool.as_ref().ok_or(Error::IdentityMismatch).and_then(|pool| { + pool.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.put(role, buffer) + }); + if result.is_err() { self.failed.set(true); } + result.err() + } + pub(in super::super::super) fn set_qk_workspace(&mut self, owner: Rc>) -> Result<()> { + self.check()?; + if self.qk_workspace.is_some() || !self.buffers.is_empty() + || self.identity.layer().get() >= 48 || self.identity.layer().get() % 4 == 3 + { return Err(Error::IdentityMismatch); } + owner.validate(self.context, &self.binding, &self.failed)?; + self.qk_workspace = Some(owner); + Ok(()) + } + pub(in super::super::super) fn scope_key(&self) -> Rc<()> { + self.epoch.clone() + } + pub(in super::super) fn check(&self) -> Result<()> { + if self.failed.get() { + Err(Error::CudaExecution) + } else { + Ok(()) + } + } + pub(in super::super::super) fn buffer(&self, product: &Product, role: Role) -> Result<&DeviceBuffer<'ctx>> { + self.check()?; + if product.role != role || !Rc::ptr_eq(&self.epoch, &product.epoch) { + return Err(Error::IdentityMismatch); + } + validate_values(&product.values, role.count())?; + if let Some(returning) = &self.qk_return + && returning.slot == product.slot + { + if role != Role::Qk || returning.row != self.identity + || !Rc::ptr_eq(&returning.epoch, &self.epoch) + { return Err(Error::IdentityMismatch); } + returning.owner.validate(self.context, &self.binding, &self.failed)?; + } + let buffer = self + .buffers + .get(product.slot) + .and_then(Option::as_ref) + .ok_or(Error::IdentityMismatch)?; + if buffer.len() != role.count() * 4 { + return Err(Error::InvalidDimension); + } + Ok(buffer) + } + // Shared slot validation of pending operands and completed products. + pub(in super::super) fn device_slot(&self, slot: usize, product_role: Role, epoch: &Rc<()>, role: Role) -> Result<&DeviceBuffer<'ctx>> { + self.check()?; + if product_role != role || !Rc::ptr_eq(&self.epoch, epoch) { + return Err(Error::IdentityMismatch); + } + if let Some(returning) = &self.qk_return + && returning.slot == slot + { + if role != Role::Qk || returning.row != self.identity + || !Rc::ptr_eq(&returning.epoch, &self.epoch) + { return Err(Error::IdentityMismatch); } + returning.owner.validate(self.context, &self.binding, &self.failed)?; + } + let buffer = self + .buffers + .get(slot) + .and_then(Option::as_ref) + .ok_or(Error::IdentityMismatch)?; + if buffer.len() != role.count() * 4 { + return Err(Error::InvalidDimension); + } + Ok(buffer) + } + pub(in super::super::super) fn device_buffer(&self, product: &DeviceProduct, role: Role) -> Result<&DeviceBuffer<'ctx>> { + self.device_slot(product.slot, product.role, &product.epoch, role) + } + // Pending operands are admissible only as inputs/outputs of the queued prefix. + pub(in super::super) fn operand_buffer(&self, operand: &DeviceOperand, role: Role) -> Result<&DeviceBuffer<'ctx>> { + self.device_slot(operand.slot, operand.role, &operand.epoch, role) + } + // Mint the completed product from a pending operand. Callable only after a + // clean complete drain that scanned that operand's buffer. + pub(in super::super) fn complete(&self, operand: DeviceOperand) -> DeviceProduct { + DeviceProduct { slot: operand.slot, role: operand.role, epoch: operand.epoch } + } + pub(in super::super) fn track_device(&mut self, role: Role, buffer: DeviceBuffer<'ctx>) -> DeviceOperand { + let slot = self.buffers.len(); + self.buffers.push(Some(buffer)); + DeviceOperand { slot, role, epoch: self.epoch.clone() } + } + // Queued rows never use the fixed verification pool; those rows keep the + // scalar path unchanged. + pub(in super::super) fn reserve_device(&mut self, role: Role) -> Result { + self.check()?; + if self.verification_pool.is_some() { return Err(Error::IdentityMismatch); } + self.buffers.try_reserve(1).map_err(|_| Error::InputAllocation)?; + let buffer = allocate(self.context, role.count())?; + Ok(self.track_device(role, buffer)) + } + // The retained whole QK slot with its preset positive-zero tail; only the + // original GdnQk kernel writes its first 4096 words. It returns to the + // workspace through the same slot bookkeeping as `normalize_qk`. + pub(in super::super) fn reserve_qk_device(&mut self) -> Result { + self.check()?; + let owner = self.qk_workspace.clone().ok_or(Error::IdentityMismatch)?; + if self.qk_return.is_some() || self.verification_pool.is_some() { + return Err(Error::IdentityMismatch); + } + self.buffers.try_reserve(1).map_err(|_| Error::InputAllocation)?; + let buffer = owner.take(self.context, &self.binding, &self.failed)?; + let product = self.track_device(Role::Qk, buffer); + self.qk_return = Some(QkReturn { + owner, slot: product.slot, row: self.identity, epoch: Rc::clone(&self.epoch), + }); + Ok(product) + } + // Same projection call as `project`, but the output stays on device; its + // finite scan is queued, never skipped. Only the three queue-scanned roles. + pub(in super::super::super) fn project_device( + &mut self, + matrix: &DeviceBuffer<'_>, + kind: GdnMatrixKind, + source: &DeviceBuffer<'_>, + role: Role, + ) -> Result { + if !matches!(role, Role::Alpha | Role::BetaRaw | Role::Z) { + return Err(Error::IdentityMismatch); + } + let product = self.reserve_device(role)?; + let operation = { + let output = self + .buffers + .get_mut(product.slot) + .and_then(Option::as_mut) + .ok_or(Error::IdentityMismatch)?; + dispatch_projection(self.context, matrix, source, output, kind, 2560, role.count()) + .map_err(driver_error) + }; + if let Err(primary) = operation { + self.note(primary); + return Err(primary); + } + Ok(product) + } + pub(in super::super::super) fn project_out_device( + &mut self, + matrix: &DeviceBuffer<'_>, + kind: GdnMatrixKind, + normalized: &DeviceProduct, + ) -> Result { + let [product] = self.produce([Role::Out], |chain, out| { + dispatch_projection( + chain.context, + matrix, + chain.device_buffer(normalized, Role::Normalized)?, + &mut out[0], + kind, + VALUES, + 2560, + ) + .map_err(driver_error)?; + Ok([download(&out[0], 2560)?]) + })?; + Ok(product) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/gdn_chain/impl_chain/impl_chain_2_2.rs b/crates/leleka-runtime/src/qwen_forward/gdn_chain/impl_chain/impl_chain_2_2.rs new file mode 100644 index 00000000..70ace468 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/gdn_chain/impl_chain/impl_chain_2_2.rs @@ -0,0 +1,253 @@ +//! Moved out of the parent module by STRA-338: impl Chain (2). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> Chain<'ctx> { + // ONE drain for conv, QK, beta sigmoid, gates, recurrence, out-norm and a + // full finite scan of every stage output. The scalar chain's twelve + // intermediate host readbacks and its separate launch fences are gone; the + // arithmetic assets, operand order and finite boundaries are the same, and + // the earliest non-finite stage still refuses the row. Nothing is published + // unless the complete drain was clean. + pub(in super::super::super) fn run_row_queue( + &mut self, + queue: &mut GdnRowQueue<'ctx>, + inputs: QueueInputs<'_, 'ctx>, + ) -> Result { + self.check()?; + if self.verification_pool.is_some() || self.qk_workspace.is_none() { + return Err(Error::IdentityMismatch); + } + // Product allocations first: all of them are chain slots, so any later + // refusal is freed or returned by the ordinary drain. + let raw = self.reserve_device(Role::Raw)?; + let next = self.reserve_device(Role::NextHistory)?; + let h = self.reserve_device(Role::H)?; + let qk = self.reserve_qk_device()?; + let sigmoid = self.reserve_device(Role::Beta)?; + let gate = self.reserve_device(Role::Gate)?; + let readout = self.reserve_device(Role::Readout)?; + let normalized = self.reserve_device(Role::Normalized)?; + let drained = (|| -> Result<_> { + let this = &*self; + let history = this.buffer(inputs.history, Role::History)?; + let qkv = match &inputs.qkv { + QkvInput::Host(product) => Some(this.buffer(product, Role::Qkv)?), + QkvInput::Columns { .. } => None, + }; + let alpha = this.operand_buffer(inputs.alpha, Role::Alpha)?; + let beta_raw = this.operand_buffer(inputs.beta_raw, Role::BetaRaw)?; + let z = this.operand_buffer(inputs.z, Role::Z)?; + let raw_buffer = this.operand_buffer(&raw, Role::Raw)?; + let next_buffer = this.operand_buffer(&next, Role::NextHistory)?; + let h_buffer = this.operand_buffer(&h, Role::H)?; + let qk_buffer = this.operand_buffer(&qk, Role::Qk)?; + let sigmoid_buffer = this.operand_buffer(&sigmoid, Role::Beta)?; + let gate_buffer = this.operand_buffer(&gate, Role::Gate)?; + let readout_buffer = this.operand_buffer(&readout, Role::Readout)?; + let normalized_buffer = this.operand_buffer(&normalized, Role::Normalized)?; + let mut prefix = queue.begin().map_err(driver_error)?; + if let QkvInput::Columns { buffer, row } = &inputs.qkv { + prefix.scan_qkv_columns(buffer, *row).map_err(driver_error)?; + } + prefix.scan_alpha(alpha).map_err(driver_error)?; + prefix.scan_beta_raw(beta_raw).map_err(driver_error)?; + match (&inputs.qkv, qkv) { + (QkvInput::Host(_), Some(qkv)) => prefix + .conv_silu(history, qkv, inputs.conv_weights, next_buffer, raw_buffer, h_buffer) + .map_err(driver_error)?, + (QkvInput::Columns { buffer, row }, None) => prefix + .conv_silu_columns( + history, + buffer, + *row, + inputs.conv_weights, + next_buffer, + raw_buffer, + h_buffer, + ) + .map_err(driver_error)?, + _ => return Err(Error::IdentityMismatch), + } + prefix.qk_l2(h_buffer, qk_buffer, inputs.epsilon).map_err(driver_error)?; + prefix.beta_sigmoid(beta_raw, sigmoid_buffer).map_err(driver_error)?; + prefix + .gate_softplus(alpha, inputs.dt, inputs.a, gate_buffer) + .map_err(driver_error)?; + prefix + .recurrence( + inputs.state, + qk_buffer, + h_buffer, + gate_buffer, + sigmoid_buffer, + inputs.next_state, + readout_buffer, + ) + .map_err(driver_error)?; + prefix.scan_z(z).map_err(driver_error)?; + prefix + .out_norm(readout_buffer, z, inputs.gamma, normalized_buffer, inputs.epsilon) + .map_err(driver_error)?; + prefix.fetch_next_history(next_buffer).map_err(driver_error)?; + prefix.finish().map_err(driver_error) + })(); + let completion = match drained { + Ok(completion) => completion, + Err(primary) => { + self.note(primary); + return Err(primary); + } + }; + // A completed numerical refusal is the same NonFinite as the scalar + // chain's full readback validation; no history is returned. + let values = completion + .into_next_history() + .map_err(|_| Error::NonFinite)?; + validate_values(&values, Role::NextHistory.count())?; + Ok(QueuedRow { + next_history: Product { + slot: next.slot, + role: Role::NextHistory, + epoch: next.epoch.clone(), + values, + }, + normalized: self.complete(normalized), + }) + } + pub(in super::super::super) fn borrow_recurrence<'chain>( + &'chain mut self, + row: &super::super::super::super::session::chunk::GdnChunkRow, + products: [&'chain Product; 4], + ) -> Result> { + self.check()?; + if row.identity() != self.identity { + return Err(Error::IdentityMismatch); + } + let roles = [Role::Qk, Role::H, Role::Gate, Role::Beta]; + // Validate every source/witness before freeing anything. Product fields + // are private and only completed producers can mint these identities. + for (product, role) in products.into_iter().zip(roles) { + self.buffer(product, role)?; + } + let slots = products.map(|product| product.slot); + for (index, slot) in slots.iter().enumerate() { + if slots[..index].contains(slot) { + return Err(Error::IdentityMismatch); + } + } + // History has already been consumed as its unchanged canonical host + // product. Retain only the four current recurrence input allocations. + self.release_in_scope(&slots)?; + Ok(RecurrenceBorrow { + row: row.readout_key(), + scope: Rc::clone(&self.epoch), + chain: self, + products, + }) + } + pub(in super::super::super) fn borrow_scalar_recurrence<'chain>( + &'chain mut self, + prior: &super::super::super::GdnPrior, + txn: &super::super::super::QwenStepTxn<'_, '_>, + products: [&'chain Product; 4], + ) -> Result> { + txn.validate_binding(&self.binding)?; + txn.validate_input(self.identity.token(), self.identity.position())?; + txn.validate_gdn_prior(prior, self.identity.layer())?; + self.validate(txn.cuda_context()?, &self.binding, self.identity)?; + for (product, role) in products + .into_iter() + .zip([Role::Qk, Role::H, Role::Gate, Role::Beta]) + { + self.buffer(product, role)?; + } + let slots = products.map(|product| product.slot); + for (index, slot) in slots.iter().enumerate() { + if slots[..index].contains(slot) { + return Err(Error::IdentityMismatch); + } + } + // All witnesses and current producer identities precede any cleanup. + self.release_in_scope(&slots)?; + Ok(ScalarRecurrenceBorrow { + prior: prior.clone(), + scope: Rc::clone(&self.epoch), + chain: self, + products, + }) + } + pub(in super::super::super) fn release_chunk_sources(&mut self) -> Result<()> { + self.release_in_scope(&[]) + } + pub(in super::super) fn release_in_scope(&mut self, retained: &[usize]) -> Result<()> { + let mut error = None; + for slot in (0..self.buffers.len()).rev() { + if !retained.contains(&slot) + && let Some(buffer) = self.buffers[slot].take() + { + let failure = if self.qk_return.as_ref().is_some_and(|v| v.slot == slot) { + let returning = self.qk_return.take().expect("actual retained QK slot"); + returning.owner.put(buffer).err() + } else if let Some((_, role)) = self.fixed_slots.iter().find(|(actual, _)| *actual == slot) { + self.return_fixed(*role, buffer) + } else { + self.free(buffer) + }; + if let Some(failure) = failure { error.get_or_insert(failure); } + } + } + // Keep every vacated slot until ordinary drain rotates the epoch. + // Later readout/Z products append; no stale product can alias a reused + // slot while the completed readout still carries this exact scope. + error.map_or(Ok(()), Err) + } + pub(in super::super) fn track(&mut self, role: Role, buffer: DeviceBuffer<'ctx>, values: Box<[f32]>) -> Product { + let slot = self.buffers.len(); + if self.verification_pool.is_some() && matches!(role, Role::Qk | Role::H | Role::Gate | Role::Beta | Role::Readout) { + self.fixed_slots.push((slot, role)); + } + self.buffers.push(Some(buffer)); + Product { + slot, + role, + epoch: self.epoch.clone(), + values, + } + } + pub(in super::super::super) fn upload(&mut self, role: Role, values: &[f32]) -> Result { + self.check()?; + if !matches!( + role, + Role::Input | Role::History | Role::Conv | Role::Dt | Role::A | Role::Gamma + ) { + return Err(Error::IdentityMismatch); + } + self.upload_values(role, values) + } + // Only this importer can admit computed QKV: the real sealed producer + // must pass all original branch/source/provider/one-use checks first. + #[allow(clippy::too_many_arguments)] + pub(in super::super::super) fn import_projected_qkv( + &mut self, + projection: &mut super::super::super::super::q6_attention_columns::ProjectionRow<'_, '_>, + binding: &super::super::super::ModelBinding, + cache: &super::super::super::DenseWeightCache<'_>, + txn: &super::super::super::QwenStepTxn<'_, '_>, + layer: super::super::super::LayerId, + input: &super::super::super::ResidualReady, + ) -> Result { + self.validate(txn.cuda_context()?, &binding.identity(), input.identity())?; + let values = projection.take( + binding, + cache, + txn, + layer, + input, + super::super::super::super::q6_attention_columns::Role::GdnQkv, + )?; + self.upload_values(Role::Qkv, &values) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/gdn_chain/impl_chain/impl_chain_3.rs b/crates/leleka-runtime/src/qwen_forward/gdn_chain/impl_chain/impl_chain_3.rs new file mode 100644 index 00000000..f25211d8 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/gdn_chain/impl_chain/impl_chain_3.rs @@ -0,0 +1,247 @@ +//! Moved out of the parent module by STRA-338: impl Chain (3). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> Chain<'ctx> { + pub(in super::super) fn upload_values(&mut self, role: Role, values: &[f32]) -> Result { + self.check()?; + self.buffers + .try_reserve(1) + .map_err(|_| Error::InputAllocation)?; + validate_values(values, role.count())?; + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(values.len() * 4) + .map_err(|_| Error::InputAllocation)?; + for value in values { + bytes.extend_from_slice(&value.to_le_bytes()); + } + let mut host = Vec::new(); + host.try_reserve_exact(values.len()) + .map_err(|_| Error::InputAllocation)?; + host.extend_from_slice(values); + let mut buffer = allocate(self.context, role.count())?; + if let Err(error) = buffer.copy_from(&bytes) { + let primary = driver_error(error); + self.note(primary); + self.free(buffer); + return Err(primary); + } + Ok(self.track(role, buffer, host.into_boxed_slice())) + } + pub(in super::super) fn note(&self, error: Error) { + if error == Error::CudaExecution { + self.failed.set(true); + } + } + pub(in super::super) fn free(&self, buffer: DeviceBuffer<'ctx>) -> Option { + match buffer.release() { + Ok(()) => None, + Err(error) => { + self.failed.set(true); + Some(driver_error(error)) + } + } + } + // Producers perform the kernel and all mandatory finite D2H themselves. + // Callers never provide a separately computed numeric proof for a buffer. + pub(in super::super) fn produce( + &mut self, + roles: [Role; N], + operation: impl FnOnce(&Self, &mut [DeviceBuffer<'ctx>]) -> Result<[Box<[f32]>; N]>, + ) -> Result<[Product; N]> { + self.check()?; + self.buffers + .try_reserve(N) + .map_err(|_| Error::InputAllocation)?; + let mut buffers = Vec::new(); + buffers + .try_reserve_exact(N) + .map_err(|_| Error::InputAllocation)?; + let mut products = Vec::new(); + products + .try_reserve_exact(N) + .map_err(|_| Error::InputAllocation)?; + let result = (|| { + for role in roles { + let fixed = self.verification_pool.as_ref().map(|pool| { + pool.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.take(role) + }).transpose()?.flatten(); + buffers.push(match fixed { Some(buffer) => buffer, None => allocate(self.context, role.count())? }); + } + operation(self, &mut buffers) + })(); + let values = match result { + Ok(values) => values, + Err(primary) => { + self.note(primary); + for (buffer, role) in buffers.into_iter().zip(roles) { + if self.verification_pool.is_some() && matches!(role, Role::Qk | Role::H | Role::Gate | Role::Beta) { + self.return_fixed(role, buffer); + } else { self.free(buffer); } + } + return Err(primary); + } + }; + for ((buffer, values), role) in buffers.into_iter().zip(values).zip(roles) { + products.push(self.track(role, buffer, values)); + } + products.try_into().map_err(|_| Error::IdentityMismatch) + } + pub(in super::super::super) fn project( + &mut self, + matrix: &DeviceBuffer<'_>, + kind: GdnMatrixKind, + source: &DeviceBuffer<'_>, + role: Role, + ) -> Result { + let columns = match role { + Role::Qkv | Role::Alpha | Role::BetaRaw | Role::Z => 2560, + _ => return Err(Error::IdentityMismatch), + }; + let [product] = self.produce([role], |chain, out| { + dispatch_projection( + chain.context, + matrix, + source, + &mut out[0], + kind, + columns, + role.count(), + ) + .map_err(driver_error)?; + Ok([download(&out[0], role.count())?]) + })?; + Ok(product) + } + pub(in super::super::super) fn project_out( + &mut self, + matrix: &DeviceBuffer<'_>, + kind: GdnMatrixKind, + normalized: &Product, + ) -> Result { + let [product] = self.produce([Role::Out], |chain, out| { + dispatch_projection( + chain.context, + matrix, + chain.buffer(normalized, Role::Normalized)?, + &mut out[0], + kind, + VALUES, + 2560, + ) + .map_err(driver_error)?; + Ok([download(&out[0], 2560)?]) + })?; + Ok(product) + } + pub(in super::super::super) fn convolve( + &mut self, + history: &Product, + qkv: &Product, + weights: &DeviceBuffer<'_>, + ) -> Result<(Product, Product)> { + let [next, _raw, h] = + self.produce([Role::NextHistory, Role::Raw, Role::H], |chain, out| { + let (next, rest) = out.split_at_mut(1); + let (raw, h) = rest.split_at_mut(1); + chain + .context + .gdn_conv_silu_f32( + chain.buffer(history, Role::History)?, + chain.buffer(qkv, Role::Qkv)?, + weights, + &mut next[0], + &mut raw[0], + &mut h[0], + ) + .map_err(driver_error)?; + let raw_values = download(&raw[0], CHANNELS)?; + let next_values = download(&next[0], HISTORY_ELEMENTS)?; + let h_values = download(&h[0], CHANNELS)?; + Ok([next_values, raw_values, h_values]) + })?; + Ok((next, h)) + } + pub(in super::super::super) fn normalize_qk(&mut self, h: &Product, epsilon: f32) -> Result { + if let Some(owner) = self.qk_workspace.clone() { + self.check()?; + if self.qk_return.is_some() { return Err(Error::IdentityMismatch); } + self.buffers.try_reserve(1).map_err(|_| Error::InputAllocation)?; + let mut buffer = owner.take(self.context, &self.binding, &self.failed)?; + let operation = self.buffer(h, Role::H).and_then(|h| { + normalize_retained_qk(self.context, h, &mut buffer, epsilon) + }); + let values = match operation { + Ok(values) => values, + Err(primary) => { + self.note(primary); + let _ = owner.put(buffer); + return Err(primary); + } + }; + let product = self.track(Role::Qk, buffer, values); + self.qk_return = Some(QkReturn { + owner, slot: product.slot, row: self.identity, epoch: Rc::clone(&self.epoch), + }); + return Ok(product); + } + let [product] = self.produce([Role::Qk], |chain, out| { + // Fixed ABI writes only4096 words; preserve original initialized tail. + out[0] + .copy_from(&[0u8; CHANNELS * 4]) + .map_err(driver_error)?; + chain + .context + .gdn_qk_l2_f32(chain.buffer(h, Role::H)?, &mut out[0], epsilon) + .map_err(driver_error)?; + Ok([download(&out[0], CHANNELS)?]) + })?; + Ok(product) + } + pub(in super::super::super) fn gates( + &mut self, + alpha: &Product, + beta: &Product, + dt: &DeviceBuffer<'_>, + a: &DeviceBuffer<'_>, + ) -> Result<(Product, Product)> { + let [sigmoid, gate] = self.produce([Role::Beta, Role::Gate], |chain, out| { + chain + .context + .gdn_beta_sigmoid_f32(chain.buffer(beta, Role::BetaRaw)?, &mut out[0]) + .map_err(driver_error)?; + // Read and validate sigmoid before invoking gate, matching legacy. + let sigmoid = download(&out[0], 48)?; + chain + .context + .gdn_gate_softplus_f32(chain.buffer(alpha, Role::Alpha)?, dt, a, &mut out[1]) + .map_err(driver_error)?; + Ok([sigmoid, download(&out[1], 48)?]) + })?; + Ok((gate, sigmoid)) + } + pub(in super::super::super) fn import_readout( + &mut self, + readout: super::super::super::mirror::MirrorReadout<'ctx>, + prior: &super::super::super::GdnPrior, + ) -> Result { + self.check()?; + if !prior.mirror_admits(&self.binding, self.identity.layer().get()) { + return Err(Error::IdentityMismatch); + } + self.buffers + .try_reserve(1) + .map_err(|_| Error::InputAllocation)?; + let (buffer, values) = readout.into_parts( + self.context, + &self.failed, + prior, + self.identity, + &self.epoch, + )?; + Ok(self.track(Role::Readout, buffer, values)) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/gdn_chain/impl_chain/impl_chain_4.rs b/crates/leleka-runtime/src/qwen_forward/gdn_chain/impl_chain/impl_chain_4.rs new file mode 100644 index 00000000..ede1c650 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/gdn_chain/impl_chain/impl_chain_4.rs @@ -0,0 +1,68 @@ +//! Moved out of the parent module by STRA-338: impl Chain (4). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> Chain<'ctx> { + pub(in super::super::super) fn import_chunk_readout( + &mut self, + readout: super::super::super::chunk_device::ChunkReadout<'ctx>, + row: &super::super::super::super::session::chunk::GdnChunkRow, + ) -> Result { + self.check()?; + self.buffers + .try_reserve(1) + .map_err(|_| Error::InputAllocation)?; + if row.identity() != self.identity { + return Err(Error::IdentityMismatch); + } + let (buffer, values) = readout.into_parts(self.context, &self.failed, row, &self.epoch)?; + Ok(self.track(Role::Readout, buffer, values)) + } + pub(in super::super::super) fn out_norm( + &mut self, + readout: &Product, + z: &Product, + gamma: &DeviceBuffer<'_>, + epsilon: f32, + ) -> Result { + let [product] = self.produce([Role::Normalized], |chain, out| { + chain + .context + .gdn_out_norm_f32( + chain.buffer(readout, Role::Readout)?, + chain.buffer(z, Role::Z)?, + gamma, + &mut out[0], + epsilon, + ) + .map_err(driver_error)?; + Ok([download(&out[0], VALUES)?]) + })?; + Ok(product) + } + pub(in super::super::super) fn drain(&mut self) -> Result<()> { + // Epoch change makes all old capabilities invalid even when slots are reused. + self.epoch = Rc::new(()); + let mut error = None; + while let Some(buffer) = self.buffers.pop() { + let slot = self.buffers.len(); + if let Some(buffer) = buffer { + let failure = if self.qk_return.as_ref().is_some_and(|v| v.slot == slot) { + let returning = self.qk_return.take().expect("actual retained QK slot"); + returning.owner.put(buffer).err() + } else if let Some((_, role)) = self.fixed_slots.iter().find(|(actual, _)| *actual == slot) { + self.return_fixed(*role, buffer) + } else { + self.free(buffer) + }; + if let Some(failure) = failure { error.get_or_insert(failure); } + } + } + error.map_or(Ok(()), Err) + } + pub(in super::super::super) fn finish(mut self) -> Result<()> { + self.drain() + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/gdn_chunk_device/impl_gdnchunkdevice.rs b/crates/leleka-runtime/src/qwen_forward/gdn_chunk_device/impl_gdnchunkdevice.rs index 2833bbd6..24fcebbc 100644 --- a/crates/leleka-runtime/src/qwen_forward/gdn_chunk_device/impl_gdnchunkdevice.rs +++ b/crates/leleka-runtime/src/qwen_forward/gdn_chunk_device/impl_gdnchunkdevice.rs @@ -3,536 +3,9 @@ #[allow(unused_imports)] use super::*; -impl<'ctx> GdnChunkDevice<'ctx> { - pub(in crate::qwen_forward) fn new( - binding: &ModelBinding, - current: &Context<'_>, - cache: &DenseWeightCache<'ctx>, - start: GdnChunkStart, - ) -> Result { - let context = cache.retained_context(binding, current)?; - let failed = cache.transport_failure_flag(binding, context)?; - start.validate_binding(&binding.identity())?; - validate_values(start.prior().values(), STATE_ELEMENTS)?; - validate_values(start.prior().history(), HISTORY_ELEMENTS)?; - preflight_budget( - context.budget_bytes(), - context - .allocated_bytes() - .checked_add(CHUNK_DEVICE_CHARGE) - .ok_or(Error::Overflow)?, - )?; - let mut owner = Self { - context, - failed, - start, - state: None, - next: None, - guard: None, - history: None, - cursor: 0, - inflight: false, - valid: true, - verification: None, - verified_rows: Vec::new(), - initial: None, - queue: None, - queue_enabled: false, - }; - let operation = (|| { - let mut history = Vec::new(); - history - .try_reserve_exact(HISTORY_ELEMENTS) - .map_err(|_| Error::InputAllocation)?; - history.extend_from_slice(owner.start.prior().history()); - owner.history = Some(history.into_boxed_slice()); - // One canonical upload per layer/chunk, even on an old mirror hit. - // No position-only key or intermediate host state is manufactured. - // LELEKA_PREFILL_GDN_MIRROR=0: always upload the canonical host values (the A/B arm) - let resident = if mirror_reuse_enabled() { - cache - .gdn_mirror(binding, owner.start.prior().layer().get(), context)? - .take_resident_for(owner.start.prior(), cache)? - } else { - None - }; - owner.state = Some(match resident { - Some(buffer) => buffer, - None => upload(context, owner.start.prior().values())?, - }); - owner.next = Some(cache.take_gdn_scratch(context, STATE_ELEMENTS * 4)?); - owner.guard = Some(cache.take_gdn_guard(binding, context)?); - Ok(()) - })(); - if let Err(primary) = operation { - owner.note(primary); - let _ = owner.cleanup(); - return Err(primary); - } - Ok(owner) - } - pub(in crate::qwen_forward) fn new_verification( - binding: &ModelBinding, current: &Context<'_>, cache: &DenseWeightCache<'ctx>, start: GdnChunkStart, - lease: Rc, - ) -> Result { - let context = cache.retained_context(binding, current)?; - let failed = cache.transport_failure_flag(binding, context)?; - let workspace = cache.gdn_verification_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; - validate_values(start.prior().history(), HISTORY_ELEMENTS)?; - let mut history = Vec::new(); history.try_reserve_exact(HISTORY_ELEMENTS).map_err(|_|Error::InputAllocation)?; - history.extend_from_slice(start.prior().history()); - let mut verified_rows = Vec::new(); verified_rows.try_reserve_exact(start.count()).map_err(|_|Error::InputAllocation)?; - let ([state,next,initial],guard) = workspace.try_borrow_mut().map_err(|_|Error::IdentityMismatch)?.take_layer(&lease,&start)?; - Ok(Self { context, failed, start, state:Some(state),next:Some(next),guard:Some(guard),history:Some(history.into_boxed_slice()), - cursor:0,inflight:false,valid:true,verification:Some((workspace,lease)),verified_rows,initial:Some(initial), - queue:None,queue_enabled:false }) - } - pub(in super::super) fn verification_pool(&self, row:&GdnChunkRow)->Result>> { - if self.verification.is_none(){return Ok(None);} - self.validate_row(row,&self.start.binding(),self.context)?; - self.verification.as_ref().map(|(owner,lease)|super::super::verification::Workspace::row_pool(owner.clone(),lease.clone(),row)).transpose() - } - pub(in crate::qwen_forward) fn is_verification(&self)->bool {self.verification.is_some()} - pub(super) fn note(&mut self, error: Error) { - self.valid = false; - if let Some((_,lease))=&self.verification { lease.refuse(); } - if error == Error::CudaExecution { - self.failed.set(true); - } - } - pub(in super::super) fn refuse(&mut self, error: Error) { - self.note(error); - } - pub(in super::super) fn validate_row( - &self, - row: &GdnChunkRow, - binding: &BindingIdentity, - context: &Context<'_>, - ) -> Result<()> { - if self.failed.get() { - return Err(Error::CudaExecution); - } - if !self.valid || self.inflight || !std::ptr::eq(self.context, context) { - return Err(Error::IdentityMismatch); - } - row.validate(&self.start, self.cursor, binding) - } - /// Explicit opt-in for the closed one-drain row queue. Verification rows - /// keep their fixed pool path; the scalar chain stays the default. - pub(in crate::qwen_forward) fn enable_row_queue(&mut self) -> Result<()> { - if self.verification.is_some() || !self.valid || self.inflight { - return Err(Error::IdentityMismatch); - } - self.queue_enabled = true; - Ok(()) - } - pub(in super::super) fn row_queue_enabled(&self) -> bool { - self.queue_enabled && self.verification.is_none() - } - /// Lend the persistent queue for one row; `put_row_queue` returns it. The - /// first call creates and charges it. A queue lost on an error path is - /// simply closed by Drop and recreated by the next row. - pub(in super::super) fn take_row_queue(&mut self) -> Result> { - if !self.row_queue_enabled() { - return Err(Error::IdentityMismatch); - } - match self.queue.take() { - Some(queue) => Ok(queue), - None => self.context.gdn_row_queue().map_err(|error| { - let error = driver_error(error); - self.note(error); - error - }), - } - } - pub(in super::super) fn put_row_queue(&mut self, queue: GdnRowQueue<'ctx>) { - if queue.is_failed() || self.queue.is_some() { - self.failed.set(true); - return; - } - self.queue = Some(queue); - } - /// The authenticated current-state and next-state owners for one queued - /// recurrence. Nothing is mutated; the step only becomes `inflight` after a - /// clean complete drain (`complete_queued_step`). - pub(in super::super) fn queue_operands( - &self, - row: &GdnChunkRow, - ) -> Result<(&DeviceBuffer<'ctx>, &DeviceBuffer<'ctx>)> { - self.validate_row(row, &self.start.binding(), self.context)?; - if !self.row_queue_enabled() { - return Err(Error::IdentityMismatch); - } - Ok(( - self.state.as_ref().ok_or(Error::IdentityMismatch)?, - self.next.as_ref().ok_or(Error::IdentityMismatch)?, - )) - } - pub(in super::super) fn complete_queued_step(&mut self, row: &GdnChunkRow) -> Result<()> { - self.validate_row(row, &self.start.binding(), self.context)?; - if !self.row_queue_enabled() { - return Err(Error::IdentityMismatch); - } - self.inflight = true; - Ok(()) - } - /// The authenticated prior-state and final-state owners for one batched - /// Strata-prefill step over `rows`, which must be the next consecutive - /// rows of this chunk starting at the cursor. Nothing is mutated; verification - /// devices keep their per-row pool path and refuse batches. - pub(in super::super) fn batch_operands( - &self, - rows: &[GdnChunkRow], - ) -> Result<(&DeviceBuffer<'ctx>, &DeviceBuffer<'ctx>)> { - if rows.is_empty() { - return Err(Error::IdentityMismatch); - } - for (offset, row) in rows.iter().enumerate() { - let cursor = self.cursor.checked_add(offset).ok_or(Error::Overflow)?; - self.validate_batch_row(row, cursor)?; - } - Ok(( - self.state.as_ref().ok_or(Error::IdentityMismatch)?, - self.next.as_ref().ok_or(Error::IdentityMismatch)?, - )) - } - pub(super) fn validate_batch_row(&self, row: &GdnChunkRow, cursor: usize) -> Result<()> { - if self.failed.get() { - return Err(Error::CudaExecution); - } - if !self.valid || self.inflight || self.verification.is_some() { - return Err(Error::IdentityMismatch); - } - row.validate(&self.start, cursor, &self.start.binding()) - } - /// Genuine current micro-window operands: the micro must be exactly this - /// chunk's next rows from the cursor (its own capability checks), then the - /// ordinary consecutive-row validation applies. - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in super::super) fn micro_operands( - &self, - micro: &GdnChunkMicro, - binding: &BindingIdentity, - ) -> Result<(&DeviceBuffer<'ctx>, &DeviceBuffer<'ctx>)> { - micro.validate(&self.start, self.cursor, binding)?; - self.batch_operands(µ_rows(micro)?) - } - /// Adopt the final state of a micro-window batch that drained clean; the - /// edges are the micro's own genuine rows. - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in super::super) fn finish_micro( - &mut self, - micro: &GdnChunkMicro, - binding: &BindingIdentity, - history: Box<[f32]>, - ) -> Result> { - micro.validate(&self.start, self.cursor, binding)?; - self.finish_batch(micro_rows(micro)?, history) - } - /// Adopt the final state of a batch that drained clean: the separate `next` - /// owner becomes the chunk state, the history becomes the batch's canonical - /// next history, the cursor advances over all rows, and only now are the - /// row edges minted. No mid-chunk state exists to relabel. - pub(in super::super) fn finish_batch( - &mut self, - rows: Vec, - history: Box<[f32]>, - ) -> Result> { - if rows.is_empty() { - return Err(Error::IdentityMismatch); - } - for (offset, row) in rows.iter().enumerate() { - let cursor = self.cursor.checked_add(offset).ok_or(Error::Overflow)?; - self.validate_batch_row(row, cursor)?; - } - validate_values(&history, HISTORY_ELEMENTS)?; - if self.state.is_none() || self.next.is_none() { - return Err(Error::IdentityMismatch); - } - let cursor = self.cursor.checked_add(rows.len()).ok_or(Error::Overflow)?; - let mut edges = Vec::new(); - edges - .try_reserve_exact(rows.len()) - .map_err(|_| Error::InputAllocation)?; - std::mem::swap(&mut self.state, &mut self.next); - self.history = Some(history); - self.cursor = cursor; - self.inflight = false; - edges.extend(rows.into_iter().map(|row| ChunkEdge { row, verified: None })); - Ok(edges) - } - pub(in super::super) fn history(&self) -> Result<&[f32]> { - if let Some(row)=self.verified_rows.last() { return Ok(row.history()); } - self.history.as_deref().ok_or(Error::IdentityMismatch) - } - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in super::super) fn compute( - &mut self, - row: &GdnChunkRow, - scope: Rc<()>, - inputs: [&[f32]; 5], - ) -> Result> { - self.validate_row(row, &self.start.binding(), self.context)?; - for (values, count) in inputs.into_iter().zip([2048, 2048, VALUES, 48, 48]) { - validate_values(values, count)?; - } - preflight_budget(self.context.budget_bytes(), self.context.allocated_bytes())?; - let mut temporary = Vec::new(); - temporary - .try_reserve_exact(5) - .map_err(|_| Error::InputAllocation)?; - let mut output = None; - let operation = (|| { - for values in inputs { - temporary.push(upload(self.context, values)?); - } - output = Some(allocate(self.context, VALUES)?); - self.context - .gdn_step_f32( - self.initial.as_ref().filter(|_| self.cursor==0).or(self.state.as_ref()).ok_or(Error::IdentityMismatch)?, - &temporary[0], - &temporary[1], - &temporary[2], - &temporary[3], - &temporary[4], - self.next.as_mut().ok_or(Error::IdentityMismatch)?, - output.as_mut().ok_or(Error::IdentityMismatch)?, - ) - .map_err(driver_error)?; - // Preserve earliest full-state refusal before readout or any later operation. - if !self - .guard - .as_mut() - .ok_or(Error::IdentityMismatch)? - .check_next_state(self.next.as_ref().ok_or(Error::IdentityMismatch)?) - .map_err(driver_error)? - { - return Err(Error::NonFinite); - } - download(output.as_ref().ok_or(Error::IdentityMismatch)?, VALUES) - })(); - let mut cleanup = None; - for buffer in temporary { - if let Err(error) = buffer.release() { - self.failed.set(true); - cleanup.get_or_insert(driver_error(error)); - } - } - let result = operation.and_then(|values| cleanup.map_or(Ok(values), Err)); - match result { - Ok(values) => { - self.inflight = true; - Ok(ChunkReadout { - context: self.context, - failed: self.failed.clone(), - row: row.readout_key(), - identity: row.identity(), - scope, - buffer: output.take(), - values: Some(values), - verification: None, - }) - } - Err(primary) => { - self.note(primary); - if let Some(buffer) = output - && buffer.release().is_err() - { - self.failed.set(true); - } - Err(primary) - } - } - } - pub(in super::super) fn compute_borrowed( - &mut self, - row: &GdnChunkRow, - inputs: super::super::chain::RecurrenceBorrow<'_, 'ctx>, - ) -> Result> { - self.validate_row(row, &self.start.binding(), self.context)?; - let (scope, [qk, h, gate, beta]) = - inputs.into_parts(self.context, &self.start.binding(), &self.failed, row)?; - preflight_budget(self.context.budget_bytes(), self.context.allocated_bytes())?; - let mut output = None; - let operation = (|| { - output = Some(if let Some((workspace,lease))=&self.verification { - workspace.try_borrow_mut().map_err(|_|Error::IdentityMismatch)?.take_readout(lease)? - } else { allocate(self.context, VALUES)? }); - if self.verification.is_some(){ - return super::super::verification::compute_row(self.context, - self.initial.as_ref().filter(|_|self.cursor==0).or(self.state.as_ref()).ok_or(Error::IdentityMismatch)?, - [qk,h,gate,beta],self.next.as_mut().ok_or(Error::IdentityMismatch)?, - output.as_mut().ok_or(Error::IdentityMismatch)?,self.guard.as_mut().ok_or(Error::IdentityMismatch)?); - } - // The driver admits these actual whole producers, then derives - // only fixed Q/K/V subspans. No view/handle is fabricated here. - self.context - .gdn_step_from_products_f32( - self.initial.as_ref().filter(|_| self.cursor==0).or(self.state.as_ref()).ok_or(Error::IdentityMismatch)?, - qk, - h, - gate, - beta, - self.next.as_mut().ok_or(Error::IdentityMismatch)?, - output.as_mut().ok_or(Error::IdentityMismatch)?, - ) - .map_err(driver_error)?; - // Identical full-state refusal precedes readout and all consumers. - if !self - .guard - .as_mut() - .ok_or(Error::IdentityMismatch)? - .check_next_state(self.next.as_ref().ok_or(Error::IdentityMismatch)?) - .map_err(driver_error)? - { - return Err(Error::NonFinite); - } - download(output.as_ref().ok_or(Error::IdentityMismatch)?, VALUES) - })(); - match operation { - Ok(values) => { - self.inflight = true; - Ok(ChunkReadout { - context: self.context, - failed: self.failed.clone(), - row: row.readout_key(), - identity: row.identity(), - scope, - buffer: output.take(), - values: Some(values), - verification: self.verification.as_ref().map(|(workspace,_)|workspace.clone()), - }) - } - Err(primary) => { - self.note(primary); - if let Some(buffer) = output { - let cleanup=if let Some((workspace,_))=&self.verification { - workspace.try_borrow_mut().map_err(|_|Error::IdentityMismatch).and_then(|mut owner|owner.put_readout(buffer)) - } else {buffer.release().map_err(driver_error)}; - if cleanup.is_err(){self.failed.set(true);} - } - Err(primary) - } - } - } - pub(in super::super) fn finish_row( - &mut self, - row: GdnChunkRow, - history: Box<[f32]>, - ) -> Result { - if self.failed.get() { - return Err(Error::CudaExecution); - } - if !self.valid || !self.inflight { - return Err(Error::IdentityMismatch); - } - row.validate(&self.start, self.cursor, &self.start.binding())?; - validate_values(&history, HISTORY_ELEMENTS)?; - if let Some((workspace,lease))=&self.verification { - let proof=workspace.try_borrow_mut().map_err(|_|Error::IdentityMismatch)?.record(lease,&self.start,row.clone(),history)?; - self.verified_rows.push(proof.clone()); - std::mem::swap(&mut self.state,&mut self.next); - self.history=None;self.cursor=self.cursor.checked_add(1).ok_or(Error::Overflow)?;self.inflight=false; - return Ok(ChunkEdge {row,verified:Some(proof)}); - } - std::mem::swap(&mut self.state, &mut self.next); - self.history = Some(history); - self.cursor = self.cursor.checked_add(1).ok_or(Error::Overflow)?; - self.inflight = false; - Ok(ChunkEdge { row, verified: None }) - } - pub(in crate::qwen_forward) fn finish( - mut self, - seal: GdnChunkSeal, - binding: &ModelBinding, - cache: &DenseWeightCache<'ctx>, - ) -> Result { - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin( - crate::qwen_forward::owner_wall_profile::Stage::Gdn, - ); - if self.failed.get() { - return Err(Error::CudaExecution); - } - if !self.valid || self.inflight { - return Err(Error::IdentityMismatch); - } - seal.validate(&self.start, self.cursor)?; - cache.retained_context(binding, self.context)?; - // `from_chunk_boundary` below scans the same values for finiteness; with the pool switch the first scan (in `download`) is skipped. - let values = if pool_enabled() { - download_unchecked(self.state.as_ref().ok_or(Error::IdentityMismatch)?, STATE_ELEMENTS)? - } else { - download(self.state.as_ref().ok_or(Error::IdentityMismatch)?, STATE_ELEMENTS)? - }; - let prior = GdnPrior::from_chunk_boundary( - self.start.prior(), - &seal, - values, - self.history.take().ok_or(Error::IdentityMismatch)?, - )?; - // Complete scratch/guard cleanup before adopting a live mirror identity. - if let Some(next) = self.next.take() { - cache.return_gdn_scratch(next).inspect_err(|_| self.failed.set(true))?; - } - if let Some(guard) = self.guard.take() { - cache.return_gdn_guard(guard).inspect_err(|_| self.failed.set(true))?; - } - let mut mirror = cache.gdn_mirror(binding, prior.layer().get(), self.context)?; - let buffer = self.state.take().ok_or(Error::IdentityMismatch)?; - mirror.adopt_chunk(self.context, buffer, &prior, cache)?; - self.valid = false; - Ok(prior) - } - pub(in crate::qwen_forward) fn finish_verification(mut self, seal:GdnChunkSeal, binding:&ModelBinding, cache:&DenseWeightCache<'ctx>)->Result<()> { - if self.failed.get(){return Err(Error::CudaExecution);} - if !self.valid || self.inflight || self.verification.is_none() || self.verified_rows.len()!=self.cursor {return Err(Error::IdentityMismatch);} - seal.validate(&self.start,self.cursor)?;cache.retained_context(binding,self.context)?; - self.return_verification_owners()?;self.valid=false;Ok(()) - } - pub(super) fn return_verification_owners(&mut self)->Result<()> { - let Some((workspace,_))=self.verification.as_ref() else {return Ok(());}; - if self.state.is_none() || self.next.is_none() || self.initial.is_none() || self.guard.is_none() { - self.failed.set(true);return Err(Error::IdentityMismatch); - } - let mut workspace=workspace.try_borrow_mut().map_err(|_|Error::IdentityMismatch)?; - workspace.return_layer([self.state.take().ok_or(Error::IdentityMismatch)?, - self.next.take().ok_or(Error::IdentityMismatch)?,self.initial.take().ok_or(Error::IdentityMismatch)?], - self.guard.take().ok_or(Error::IdentityMismatch)?) - } - pub(super) fn cleanup(&mut self) -> Result<()> { - self.valid = false; - let mut queue_error = None; - if let Some(queue) = self.queue.take() - && let Err(e) = queue.close() - { - self.failed.set(true); - queue_error = Some(driver_error(e)); - } - if self.verification.is_some() && self.initial.is_some() { - match self.return_verification_owners() { - Ok(())=>return Ok(()), - Err(primary)=>{ - self.failed.set(true); - if let Some(guard)=self.guard.take(){let _=guard.close();} - for buffer in [self.state.take(),self.next.take(),self.initial.take()].into_iter().flatten(){let _=buffer.release();} - return Err(primary); - } - } - } - let mut error = queue_error; - if let Some(guard) = self.guard.take() - && let Err(e) = guard.close() - { - self.failed.set(true); - error.get_or_insert(driver_error(e)); - } - for buffer in [self.state.take(), self.next.take()].into_iter().flatten() { - if let Err(e) = buffer.release() { - self.failed.set(true); - error.get_or_insert(driver_error(e)); - } - } - error.map_or(Ok(()), Err) - } -} +#[path = "impl_gdnchunkdevice/impl_gdnchunkdevice_2.rs"] +mod impl_gdnchunkdevice_2; +#[path = "impl_gdnchunkdevice/impl_gdnchunkdevice_2_2.rs"] +mod impl_gdnchunkdevice_2_2; +#[path = "impl_gdnchunkdevice/impl_gdnchunkdevice_3.rs"] +mod impl_gdnchunkdevice_3; diff --git a/crates/leleka-runtime/src/qwen_forward/gdn_chunk_device/impl_gdnchunkdevice/impl_gdnchunkdevice_2.rs b/crates/leleka-runtime/src/qwen_forward/gdn_chunk_device/impl_gdnchunkdevice/impl_gdnchunkdevice_2.rs new file mode 100644 index 00000000..b1485d18 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/gdn_chunk_device/impl_gdnchunkdevice/impl_gdnchunkdevice_2.rs @@ -0,0 +1,233 @@ +//! Moved out of the parent module by STRA-338: impl GdnChunkDevice. + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> GdnChunkDevice<'ctx> { + pub(in crate::qwen_forward) fn new( + binding: &ModelBinding, + current: &Context<'_>, + cache: &DenseWeightCache<'ctx>, + start: GdnChunkStart, + ) -> Result { + let context = cache.retained_context(binding, current)?; + let failed = cache.transport_failure_flag(binding, context)?; + start.validate_binding(&binding.identity())?; + validate_values(start.prior().values(), STATE_ELEMENTS)?; + validate_values(start.prior().history(), HISTORY_ELEMENTS)?; + preflight_budget( + context.budget_bytes(), + context + .allocated_bytes() + .checked_add(CHUNK_DEVICE_CHARGE) + .ok_or(Error::Overflow)?, + )?; + let mut owner = Self { + context, + failed, + start, + state: None, + next: None, + guard: None, + history: None, + cursor: 0, + inflight: false, + valid: true, + verification: None, + verified_rows: Vec::new(), + initial: None, + queue: None, + queue_enabled: false, + }; + let operation = (|| { + let mut history = Vec::new(); + history + .try_reserve_exact(HISTORY_ELEMENTS) + .map_err(|_| Error::InputAllocation)?; + history.extend_from_slice(owner.start.prior().history()); + owner.history = Some(history.into_boxed_slice()); + // One canonical upload per layer/chunk, even on an old mirror hit. + // No position-only key or intermediate host state is manufactured. + // LELEKA_PREFILL_GDN_MIRROR=0: always upload the canonical host values (the A/B arm) + let resident = if mirror_reuse_enabled() { + cache + .gdn_mirror(binding, owner.start.prior().layer().get(), context)? + .take_resident_for(owner.start.prior(), cache)? + } else { + None + }; + owner.state = Some(match resident { + Some(buffer) => buffer, + None => upload(context, owner.start.prior().values())?, + }); + owner.next = Some(cache.take_gdn_scratch(context, STATE_ELEMENTS * 4)?); + owner.guard = Some(cache.take_gdn_guard(binding, context)?); + Ok(()) + })(); + if let Err(primary) = operation { + owner.note(primary); + let _ = owner.cleanup(); + return Err(primary); + } + Ok(owner) + } + pub(in crate::qwen_forward) fn new_verification( + binding: &ModelBinding, current: &Context<'_>, cache: &DenseWeightCache<'ctx>, start: GdnChunkStart, + lease: Rc, + ) -> Result { + let context = cache.retained_context(binding, current)?; + let failed = cache.transport_failure_flag(binding, context)?; + let workspace = cache.gdn_verification_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; + validate_values(start.prior().history(), HISTORY_ELEMENTS)?; + let mut history = Vec::new(); history.try_reserve_exact(HISTORY_ELEMENTS).map_err(|_|Error::InputAllocation)?; + history.extend_from_slice(start.prior().history()); + let mut verified_rows = Vec::new(); verified_rows.try_reserve_exact(start.count()).map_err(|_|Error::InputAllocation)?; + let ([state,next,initial],guard) = workspace.try_borrow_mut().map_err(|_|Error::IdentityMismatch)?.take_layer(&lease,&start)?; + Ok(Self { context, failed, start, state:Some(state),next:Some(next),guard:Some(guard),history:Some(history.into_boxed_slice()), + cursor:0,inflight:false,valid:true,verification:Some((workspace,lease)),verified_rows,initial:Some(initial), + queue:None,queue_enabled:false }) + } + pub(in super::super::super) fn verification_pool(&self, row:&GdnChunkRow)->Result>> { + if self.verification.is_none(){return Ok(None);} + self.validate_row(row,&self.start.binding(),self.context)?; + self.verification.as_ref().map(|(owner,lease)|super::super::super::verification::Workspace::row_pool(owner.clone(),lease.clone(),row)).transpose() + } + pub(in crate::qwen_forward) fn is_verification(&self)->bool {self.verification.is_some()} + pub(in super::super) fn note(&mut self, error: Error) { + self.valid = false; + if let Some((_,lease))=&self.verification { lease.refuse(); } + if error == Error::CudaExecution { + self.failed.set(true); + } + } + pub(in super::super::super) fn refuse(&mut self, error: Error) { + self.note(error); + } + pub(in super::super::super) fn validate_row( + &self, + row: &GdnChunkRow, + binding: &BindingIdentity, + context: &Context<'_>, + ) -> Result<()> { + if self.failed.get() { + return Err(Error::CudaExecution); + } + if !self.valid || self.inflight || !std::ptr::eq(self.context, context) { + return Err(Error::IdentityMismatch); + } + row.validate(&self.start, self.cursor, binding) + } + /// Explicit opt-in for the closed one-drain row queue. Verification rows + /// keep their fixed pool path; the scalar chain stays the default. + pub(in crate::qwen_forward) fn enable_row_queue(&mut self) -> Result<()> { + if self.verification.is_some() || !self.valid || self.inflight { + return Err(Error::IdentityMismatch); + } + self.queue_enabled = true; + Ok(()) + } + pub(in super::super::super) fn row_queue_enabled(&self) -> bool { + self.queue_enabled && self.verification.is_none() + } + /// Lend the persistent queue for one row; `put_row_queue` returns it. The + /// first call creates and charges it. A queue lost on an error path is + /// simply closed by Drop and recreated by the next row. + pub(in super::super::super) fn take_row_queue(&mut self) -> Result> { + if !self.row_queue_enabled() { + return Err(Error::IdentityMismatch); + } + match self.queue.take() { + Some(queue) => Ok(queue), + None => self.context.gdn_row_queue().map_err(|error| { + let error = driver_error(error); + self.note(error); + error + }), + } + } + pub(in super::super::super) fn put_row_queue(&mut self, queue: GdnRowQueue<'ctx>) { + if queue.is_failed() || self.queue.is_some() { + self.failed.set(true); + return; + } + self.queue = Some(queue); + } + /// The authenticated current-state and next-state owners for one queued + /// recurrence. Nothing is mutated; the step only becomes `inflight` after a + /// clean complete drain (`complete_queued_step`). + pub(in super::super::super) fn queue_operands( + &self, + row: &GdnChunkRow, + ) -> Result<(&DeviceBuffer<'ctx>, &DeviceBuffer<'ctx>)> { + self.validate_row(row, &self.start.binding(), self.context)?; + if !self.row_queue_enabled() { + return Err(Error::IdentityMismatch); + } + Ok(( + self.state.as_ref().ok_or(Error::IdentityMismatch)?, + self.next.as_ref().ok_or(Error::IdentityMismatch)?, + )) + } + pub(in super::super::super) fn complete_queued_step(&mut self, row: &GdnChunkRow) -> Result<()> { + self.validate_row(row, &self.start.binding(), self.context)?; + if !self.row_queue_enabled() { + return Err(Error::IdentityMismatch); + } + self.inflight = true; + Ok(()) + } + /// The authenticated prior-state and final-state owners for one batched + /// Strata-prefill step over `rows`, which must be the next consecutive + /// rows of this chunk starting at the cursor. Nothing is mutated; verification + /// devices keep their per-row pool path and refuse batches. + pub(in super::super::super) fn batch_operands( + &self, + rows: &[GdnChunkRow], + ) -> Result<(&DeviceBuffer<'ctx>, &DeviceBuffer<'ctx>)> { + if rows.is_empty() { + return Err(Error::IdentityMismatch); + } + for (offset, row) in rows.iter().enumerate() { + let cursor = self.cursor.checked_add(offset).ok_or(Error::Overflow)?; + self.validate_batch_row(row, cursor)?; + } + Ok(( + self.state.as_ref().ok_or(Error::IdentityMismatch)?, + self.next.as_ref().ok_or(Error::IdentityMismatch)?, + )) + } + pub(in super::super) fn validate_batch_row(&self, row: &GdnChunkRow, cursor: usize) -> Result<()> { + if self.failed.get() { + return Err(Error::CudaExecution); + } + if !self.valid || self.inflight || self.verification.is_some() { + return Err(Error::IdentityMismatch); + } + row.validate(&self.start, cursor, &self.start.binding()) + } + /// Genuine current micro-window operands: the micro must be exactly this + /// chunk's next rows from the cursor (its own capability checks), then the + /// ordinary consecutive-row validation applies. + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in super::super::super) fn micro_operands( + &self, + micro: &GdnChunkMicro, + binding: &BindingIdentity, + ) -> Result<(&DeviceBuffer<'ctx>, &DeviceBuffer<'ctx>)> { + micro.validate(&self.start, self.cursor, binding)?; + self.batch_operands(µ_rows(micro)?) + } + /// Adopt the final state of a micro-window batch that drained clean; the + /// edges are the micro's own genuine rows. + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in super::super::super) fn finish_micro( + &mut self, + micro: &GdnChunkMicro, + binding: &BindingIdentity, + history: Box<[f32]>, + ) -> Result> { + micro.validate(&self.start, self.cursor, binding)?; + self.finish_batch(micro_rows(micro)?, history) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/gdn_chunk_device/impl_gdnchunkdevice/impl_gdnchunkdevice_2_2.rs b/crates/leleka-runtime/src/qwen_forward/gdn_chunk_device/impl_gdnchunkdevice/impl_gdnchunkdevice_2_2.rs new file mode 100644 index 00000000..1d1edde3 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/gdn_chunk_device/impl_gdnchunkdevice/impl_gdnchunkdevice_2_2.rs @@ -0,0 +1,220 @@ +//! Moved out of the parent module by STRA-338: impl GdnChunkDevice (2). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> GdnChunkDevice<'ctx> { + /// Adopt the final state of a batch that drained clean: the separate `next` + /// owner becomes the chunk state, the history becomes the batch's canonical + /// next history, the cursor advances over all rows, and only now are the + /// row edges minted. No mid-chunk state exists to relabel. + pub(in super::super::super) fn finish_batch( + &mut self, + rows: Vec, + history: Box<[f32]>, + ) -> Result> { + if rows.is_empty() { + return Err(Error::IdentityMismatch); + } + for (offset, row) in rows.iter().enumerate() { + let cursor = self.cursor.checked_add(offset).ok_or(Error::Overflow)?; + self.validate_batch_row(row, cursor)?; + } + validate_values(&history, HISTORY_ELEMENTS)?; + if self.state.is_none() || self.next.is_none() { + return Err(Error::IdentityMismatch); + } + let cursor = self.cursor.checked_add(rows.len()).ok_or(Error::Overflow)?; + let mut edges = Vec::new(); + edges + .try_reserve_exact(rows.len()) + .map_err(|_| Error::InputAllocation)?; + std::mem::swap(&mut self.state, &mut self.next); + self.history = Some(history); + self.cursor = cursor; + self.inflight = false; + edges.extend(rows.into_iter().map(|row| ChunkEdge { row, verified: None })); + Ok(edges) + } + pub(in super::super::super) fn history(&self) -> Result<&[f32]> { + if let Some(row)=self.verified_rows.last() { return Ok(row.history()); } + self.history.as_deref().ok_or(Error::IdentityMismatch) + } + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in super::super::super) fn compute( + &mut self, + row: &GdnChunkRow, + scope: Rc<()>, + inputs: [&[f32]; 5], + ) -> Result> { + self.validate_row(row, &self.start.binding(), self.context)?; + for (values, count) in inputs.into_iter().zip([2048, 2048, VALUES, 48, 48]) { + validate_values(values, count)?; + } + preflight_budget(self.context.budget_bytes(), self.context.allocated_bytes())?; + let mut temporary = Vec::new(); + temporary + .try_reserve_exact(5) + .map_err(|_| Error::InputAllocation)?; + let mut output = None; + let operation = (|| { + for values in inputs { + temporary.push(upload(self.context, values)?); + } + output = Some(allocate(self.context, VALUES)?); + self.context + .gdn_step_f32( + self.initial.as_ref().filter(|_| self.cursor==0).or(self.state.as_ref()).ok_or(Error::IdentityMismatch)?, + &temporary[0], + &temporary[1], + &temporary[2], + &temporary[3], + &temporary[4], + self.next.as_mut().ok_or(Error::IdentityMismatch)?, + output.as_mut().ok_or(Error::IdentityMismatch)?, + ) + .map_err(driver_error)?; + // Preserve earliest full-state refusal before readout or any later operation. + if !self + .guard + .as_mut() + .ok_or(Error::IdentityMismatch)? + .check_next_state(self.next.as_ref().ok_or(Error::IdentityMismatch)?) + .map_err(driver_error)? + { + return Err(Error::NonFinite); + } + download(output.as_ref().ok_or(Error::IdentityMismatch)?, VALUES) + })(); + let mut cleanup = None; + for buffer in temporary { + if let Err(error) = buffer.release() { + self.failed.set(true); + cleanup.get_or_insert(driver_error(error)); + } + } + let result = operation.and_then(|values| cleanup.map_or(Ok(values), Err)); + match result { + Ok(values) => { + self.inflight = true; + Ok(ChunkReadout { + context: self.context, + failed: self.failed.clone(), + row: row.readout_key(), + identity: row.identity(), + scope, + buffer: output.take(), + values: Some(values), + verification: None, + }) + } + Err(primary) => { + self.note(primary); + if let Some(buffer) = output + && buffer.release().is_err() + { + self.failed.set(true); + } + Err(primary) + } + } + } + pub(in super::super::super) fn compute_borrowed( + &mut self, + row: &GdnChunkRow, + inputs: super::super::super::chain::RecurrenceBorrow<'_, 'ctx>, + ) -> Result> { + self.validate_row(row, &self.start.binding(), self.context)?; + let (scope, [qk, h, gate, beta]) = + inputs.into_parts(self.context, &self.start.binding(), &self.failed, row)?; + preflight_budget(self.context.budget_bytes(), self.context.allocated_bytes())?; + let mut output = None; + let operation = (|| { + output = Some(if let Some((workspace,lease))=&self.verification { + workspace.try_borrow_mut().map_err(|_|Error::IdentityMismatch)?.take_readout(lease)? + } else { allocate(self.context, VALUES)? }); + if self.verification.is_some(){ + return super::super::super::verification::compute_row(self.context, + self.initial.as_ref().filter(|_|self.cursor==0).or(self.state.as_ref()).ok_or(Error::IdentityMismatch)?, + [qk,h,gate,beta],self.next.as_mut().ok_or(Error::IdentityMismatch)?, + output.as_mut().ok_or(Error::IdentityMismatch)?,self.guard.as_mut().ok_or(Error::IdentityMismatch)?); + } + // The driver admits these actual whole producers, then derives + // only fixed Q/K/V subspans. No view/handle is fabricated here. + self.context + .gdn_step_from_products_f32( + self.initial.as_ref().filter(|_| self.cursor==0).or(self.state.as_ref()).ok_or(Error::IdentityMismatch)?, + qk, + h, + gate, + beta, + self.next.as_mut().ok_or(Error::IdentityMismatch)?, + output.as_mut().ok_or(Error::IdentityMismatch)?, + ) + .map_err(driver_error)?; + // Identical full-state refusal precedes readout and all consumers. + if !self + .guard + .as_mut() + .ok_or(Error::IdentityMismatch)? + .check_next_state(self.next.as_ref().ok_or(Error::IdentityMismatch)?) + .map_err(driver_error)? + { + return Err(Error::NonFinite); + } + download(output.as_ref().ok_or(Error::IdentityMismatch)?, VALUES) + })(); + match operation { + Ok(values) => { + self.inflight = true; + Ok(ChunkReadout { + context: self.context, + failed: self.failed.clone(), + row: row.readout_key(), + identity: row.identity(), + scope, + buffer: output.take(), + values: Some(values), + verification: self.verification.as_ref().map(|(workspace,_)|workspace.clone()), + }) + } + Err(primary) => { + self.note(primary); + if let Some(buffer) = output { + let cleanup=if let Some((workspace,_))=&self.verification { + workspace.try_borrow_mut().map_err(|_|Error::IdentityMismatch).and_then(|mut owner|owner.put_readout(buffer)) + } else {buffer.release().map_err(driver_error)}; + if cleanup.is_err(){self.failed.set(true);} + } + Err(primary) + } + } + } + pub(in super::super::super) fn finish_row( + &mut self, + row: GdnChunkRow, + history: Box<[f32]>, + ) -> Result { + if self.failed.get() { + return Err(Error::CudaExecution); + } + if !self.valid || !self.inflight { + return Err(Error::IdentityMismatch); + } + row.validate(&self.start, self.cursor, &self.start.binding())?; + validate_values(&history, HISTORY_ELEMENTS)?; + if let Some((workspace,lease))=&self.verification { + let proof=workspace.try_borrow_mut().map_err(|_|Error::IdentityMismatch)?.record(lease,&self.start,row.clone(),history)?; + self.verified_rows.push(proof.clone()); + std::mem::swap(&mut self.state,&mut self.next); + self.history=None;self.cursor=self.cursor.checked_add(1).ok_or(Error::Overflow)?;self.inflight=false; + return Ok(ChunkEdge {row,verified:Some(proof)}); + } + std::mem::swap(&mut self.state, &mut self.next); + self.history = Some(history); + self.cursor = self.cursor.checked_add(1).ok_or(Error::Overflow)?; + self.inflight = false; + Ok(ChunkEdge { row, verified: None }) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/gdn_chunk_device/impl_gdnchunkdevice/impl_gdnchunkdevice_3.rs b/crates/leleka-runtime/src/qwen_forward/gdn_chunk_device/impl_gdnchunkdevice/impl_gdnchunkdevice_3.rs new file mode 100644 index 00000000..ce5169ef --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/gdn_chunk_device/impl_gdnchunkdevice/impl_gdnchunkdevice_3.rs @@ -0,0 +1,102 @@ +//! Moved out of the parent module by STRA-338: impl GdnChunkDevice (3). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> GdnChunkDevice<'ctx> { + pub(in crate::qwen_forward) fn finish( + mut self, + seal: GdnChunkSeal, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + ) -> Result { + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin( + crate::qwen_forward::owner_wall_profile::Stage::Gdn, + ); + if self.failed.get() { + return Err(Error::CudaExecution); + } + if !self.valid || self.inflight { + return Err(Error::IdentityMismatch); + } + seal.validate(&self.start, self.cursor)?; + cache.retained_context(binding, self.context)?; + // `from_chunk_boundary` below scans the same values for finiteness; with the pool switch the first scan (in `download`) is skipped. + let values = if pool_enabled() { + download_unchecked(self.state.as_ref().ok_or(Error::IdentityMismatch)?, STATE_ELEMENTS)? + } else { + download(self.state.as_ref().ok_or(Error::IdentityMismatch)?, STATE_ELEMENTS)? + }; + let prior = GdnPrior::from_chunk_boundary( + self.start.prior(), + &seal, + values, + self.history.take().ok_or(Error::IdentityMismatch)?, + )?; + // Complete scratch/guard cleanup before adopting a live mirror identity. + if let Some(next) = self.next.take() { + cache.return_gdn_scratch(next).inspect_err(|_| self.failed.set(true))?; + } + if let Some(guard) = self.guard.take() { + cache.return_gdn_guard(guard).inspect_err(|_| self.failed.set(true))?; + } + let mut mirror = cache.gdn_mirror(binding, prior.layer().get(), self.context)?; + let buffer = self.state.take().ok_or(Error::IdentityMismatch)?; + mirror.adopt_chunk(self.context, buffer, &prior, cache)?; + self.valid = false; + Ok(prior) + } + pub(in crate::qwen_forward) fn finish_verification(mut self, seal:GdnChunkSeal, binding:&ModelBinding, cache:&DenseWeightCache<'ctx>)->Result<()> { + if self.failed.get(){return Err(Error::CudaExecution);} + if !self.valid || self.inflight || self.verification.is_none() || self.verified_rows.len()!=self.cursor {return Err(Error::IdentityMismatch);} + seal.validate(&self.start,self.cursor)?;cache.retained_context(binding,self.context)?; + self.return_verification_owners()?;self.valid=false;Ok(()) + } + pub(in super::super) fn return_verification_owners(&mut self)->Result<()> { + let Some((workspace,_))=self.verification.as_ref() else {return Ok(());}; + if self.state.is_none() || self.next.is_none() || self.initial.is_none() || self.guard.is_none() { + self.failed.set(true);return Err(Error::IdentityMismatch); + } + let mut workspace=workspace.try_borrow_mut().map_err(|_|Error::IdentityMismatch)?; + workspace.return_layer([self.state.take().ok_or(Error::IdentityMismatch)?, + self.next.take().ok_or(Error::IdentityMismatch)?,self.initial.take().ok_or(Error::IdentityMismatch)?], + self.guard.take().ok_or(Error::IdentityMismatch)?) + } + pub(in super::super) fn cleanup(&mut self) -> Result<()> { + self.valid = false; + let mut queue_error = None; + if let Some(queue) = self.queue.take() + && let Err(e) = queue.close() + { + self.failed.set(true); + queue_error = Some(driver_error(e)); + } + if self.verification.is_some() && self.initial.is_some() { + match self.return_verification_owners() { + Ok(())=>return Ok(()), + Err(primary)=>{ + self.failed.set(true); + if let Some(guard)=self.guard.take(){let _=guard.close();} + for buffer in [self.state.take(),self.next.take(),self.initial.take()].into_iter().flatten(){let _=buffer.release();} + return Err(primary); + } + } + } + let mut error = queue_error; + if let Some(guard) = self.guard.take() + && let Err(e) = guard.close() + { + self.failed.set(true); + error.get_or_insert(driver_error(e)); + } + for buffer in [self.state.take(), self.next.take()].into_iter().flatten() { + if let Err(e) = buffer.release() { + self.failed.set(true); + error.get_or_insert(driver_error(e)); + } + } + error.map_or(Ok(()), Err) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/gdn_state_mirror/impl_gdnstatemirror.rs b/crates/leleka-runtime/src/qwen_forward/gdn_state_mirror/impl_gdnstatemirror.rs index d8f1406e..4aa6e5f3 100644 --- a/crates/leleka-runtime/src/qwen_forward/gdn_state_mirror/impl_gdnstatemirror.rs +++ b/crates/leleka-runtime/src/qwen_forward/gdn_state_mirror/impl_gdnstatemirror.rs @@ -3,448 +3,7 @@ #[allow(unused_imports)] use super::*; - -impl<'ctx> GdnStateMirror<'ctx> { - pub(in crate::qwen_forward) fn new( - binding: BindingIdentity, - layer: u32, - context: &'ctx Context<'ctx>, - failed: Rc>, - ) -> Result { - if failed.get() { - return Err(Error::CudaExecution); - } - if layer >= 48 { - return Err(Error::InvalidLayer); - } - // Charge all fixed mirrors while the actor loads, before lazy MoE can - // consume the scratch reserve. Uninitialized placeholders cannot hit. - preflight_budget( - context.budget_bytes(), - context - .allocated_bytes() - .checked_add(MIRROR_BYTES) - .ok_or(Error::Overflow)?, - )?; - let buffer = context.allocate(MIRROR_BYTES).map_err(driver_error)?; - Ok(Self { - context, - binding, - layer, - buffer: Some(buffer), - key: None, - failed, - #[cfg(test)] - hits: 0, - #[cfg(test)] - misses: 0, - }) - } - - pub(in super::super) fn compute( - &mut self, - prior: &GdnPrior, - q: &[f32], - k: &[f32], - v: &[f32], - gate: &[f32], - beta: &[f32], - ) -> Result<(Box<[f32]>, MirrorNext<'ctx>)> { - let (readout, next) = self.compute_inner(prior, q, k, v, gate, beta)?; - match readout.into_host() { - Ok(values) => Ok((values, next)), - Err(primary) => { - let _ = self.discard(next); - Err(primary) - } - } - } - - pub(in super::super) fn compute_retained( - &mut self, - prior: &GdnPrior, - identity: TokenLayer, - scope: Rc<()>, - inputs: [&[f32]; 5], - ) -> Result<(MirrorReadout<'ctx>, MirrorNext<'ctx>)> { - if identity.layer() != prior.layer() || identity.position().get() != prior.next_position() { - return Err(Error::IdentityMismatch); - } - let (mut readout, next) = - self.compute_inner(prior, inputs[0], inputs[1], inputs[2], inputs[3], inputs[4])?; - readout.identity = Some(identity); - readout.scope = Some(scope); - Ok((readout, next)) - } - - pub(super) fn compute_inner( - &mut self, - prior: &GdnPrior, - q: &[f32], - k: &[f32], - v: &[f32], - gate: &[f32], - beta: &[f32], - ) -> Result<(MirrorReadout<'ctx>, MirrorNext<'ctx>)> { - if self.failed.get() { - return Err(Error::CudaExecution); - } - if !prior.mirror_admits(&self.binding, self.layer) { - return Err(Error::IdentityMismatch); - } - for (values, count) in [ - (prior.values(), STATE_ELEMENTS), - (q, 2048), - (k, 2048), - (v, VALUES), - (gate, 48), - (beta, 48), - ] { - validate_values(values, count)?; - } - let resident = self.buffer.as_ref().ok_or(Error::CudaExecution)?; - if resident.len() != MIRROR_BYTES { - return Err(Error::InvalidDimension); - } - preflight_budget(self.context.budget_bytes(), self.context.allocated_bytes())?; - let hit = self.key.as_ref().is_some_and(|key| key.matches(prior)); - #[cfg(test)] - if hit { - self.hits += 1; - } else { - self.misses += 1; - } - let mut temporary = Vec::new(); - temporary - .try_reserve_exact(7) - .map_err(|_| Error::InputAllocation)?; - let mut next = None; - let mut output = None; - let operation = (|| -> Result { - // A rollback/reset miss uploads canonical host bytes into a - // transient prior; it never changes the identity of the mirror. - if !hit { - temporary.push(upload_checked(self.context, prior.values(), &self.failed)?); - } - let first = temporary.len(); - for values in [q, k, v, gate, beta] { - temporary.push(upload_checked(self.context, values, &self.failed)?); - } - next = Some(allocate(self.context, STATE_ELEMENTS)?); - output = Some(allocate(self.context, VALUES)?); - let state = if hit { resident } else { &temporary[0] }; - self.context - .gdn_step_f32( - state, - &temporary[first], - &temporary[first + 1], - &temporary[first + 2], - &temporary[first + 3], - &temporary[first + 4], - next.as_mut().ok_or(Error::IdentityMismatch)?, - output.as_mut().ok_or(Error::IdentityMismatch)?, - ) - .map_err(driver_error)?; - Ok(( - download( - next.as_ref().ok_or(Error::IdentityMismatch)?, - STATE_ELEMENTS, - )?, - download(output.as_ref().ok_or(Error::IdentityMismatch)?, VALUES)?, - )) - })(); - let mut cleanup = None; - for buffer in temporary { - if let Err(error) = buffer.release() { - self.failed.set(true); - cleanup.get_or_insert(driver_error(error)); - } - } - let result = match operation { - Err(primary) => Err(primary), - Ok(values) => cleanup.map_or(Ok(values), Err), - }; - match result { - Ok((state, readout)) => Ok(( - MirrorReadout { - context: self.context, - source: prior.clone(), - identity: None, - scope: None, - buffer: output.take(), - values: Some(readout), - failed: self.failed.clone(), - }, - MirrorNext { - context: self.context, - source: prior.clone(), - buffer: next.take().ok_or(Error::IdentityMismatch)?, - values: state, - }, - )), - Err(primary) => { - if primary == Error::CudaExecution { - self.failed.set(true); - } - if let Some(buffer) = next - && buffer.release().is_err() - { - self.failed.set(true); - } - if let Some(buffer) = output - && buffer.release().is_err() - { - self.failed.set(true); - } - Err(primary) - } - } - } - - pub(in super::super) fn discard(&mut self, next: MirrorNext<'ctx>) -> Result<()> { - next.buffer.release().map_err(|error| { - self.failed.set(true); - driver_error(error) - }) - } - - pub(in super::super) fn compute_borrowed( - &mut self, - prior: &GdnPrior, - identity: TokenLayer, - txn: &super::super::QwenStepTxn<'_, '_>, - inputs: super::super::chain::ScalarRecurrenceBorrow<'_, 'ctx>, - ) -> Result<(MirrorReadout<'ctx>, MirrorNext<'ctx>)> { - let (scope, [qk, h, gate, beta]) = inputs.into_parts( - self.context, - &self.binding, - &self.failed, - prior, - identity, - txn, - )?; - if self.failed.get() { - return Err(Error::CudaExecution); - } - if !prior.mirror_admits(&self.binding, self.layer) { - return Err(Error::IdentityMismatch); - } - validate_values(prior.values(), STATE_ELEMENTS)?; - let resident = self.buffer.as_ref().ok_or(Error::CudaExecution)?; - if resident.len() != MIRROR_BYTES { - return Err(Error::InvalidDimension); - } - preflight_budget(self.context.budget_bytes(), self.context.allocated_bytes())?; - let hit = self.key.as_ref().is_some_and(|key| key.matches(prior)); - #[cfg(test)] - if hit { - self.hits += 1; - } else { - self.misses += 1; - } - let mut temporary = Vec::new(); - temporary - .try_reserve_exact(1) - .map_err(|_| Error::InputAllocation)?; - let mut next = None; - let mut output = None; - let operation = (|| -> Result { - // A rollback/reset miss uploads canonical host bytes into a - // transient prior; it never changes the identity of the mirror. - if !hit { - temporary.push(upload_checked(self.context, prior.values(), &self.failed)?); - } - next = Some(allocate(self.context, STATE_ELEMENTS)?); - output = Some(allocate(self.context, VALUES)?); - let state = if hit { resident } else { &temporary[0] }; - self.context - .gdn_step_from_products_f32( - state, - qk, - h, - gate, - beta, - next.as_mut().ok_or(Error::IdentityMismatch)?, - output.as_mut().ok_or(Error::IdentityMismatch)?, - ) - .map_err(driver_error)?; - Ok(( - download( - next.as_ref().ok_or(Error::IdentityMismatch)?, - STATE_ELEMENTS, - )?, - download(output.as_ref().ok_or(Error::IdentityMismatch)?, VALUES)?, - )) - })(); - let mut cleanup = None; - for buffer in temporary { - if let Err(error) = buffer.release() { - self.failed.set(true); - cleanup.get_or_insert(driver_error(error)); - } - } - let result = match operation { - Err(primary) => Err(primary), - Ok(values) => cleanup.map_or(Ok(values), Err), - }; - match result { - Ok((state, readout)) => Ok(( - MirrorReadout { - context: self.context, - source: prior.clone(), - identity: Some(identity), - scope: Some(scope), - buffer: output.take(), - values: Some(readout), - failed: self.failed.clone(), - }, - MirrorNext { - context: self.context, - source: prior.clone(), - buffer: next.take().ok_or(Error::IdentityMismatch)?, - values: state, - }, - )), - Err(primary) => { - if primary == Error::CudaExecution { - self.failed.set(true); - } - if let Some(buffer) = next - && buffer.release().is_err() - { - self.failed.set(true); - } - if let Some(buffer) = output - && buffer.release().is_err() - { - self.failed.set(true); - } - Err(primary) - } - } - } - - pub(in super::super) fn publish( - &mut self, - next: MirrorNext<'ctx>, - identity: TokenLayer, - history: Box<[f32]>, - ) -> Result { - let MirrorNext { - context, - source, - buffer, - values, - } = next; - let admitted = (|| -> Result<(GdnStateKey, GdnPending)> { - if self.failed.get() { - return Err(Error::CudaExecution); - } - if !std::ptr::eq(self.context, context) - || buffer.len() != MIRROR_BYTES - || !source.mirror_admits(&self.binding, self.layer) - { - return Err(Error::IdentityMismatch); - } - // Only this producer owns the values downloaded from this exact - // candidate buffer. A caller cannot pair it with another payload. - let pending = GdnPending::new(&source, identity, values, history)?; - Ok((pending.mirror_next(&source)?.mirror_key(), pending)) - })(); - let (key, pending) = match admitted { - Ok(value) => value, - Err(primary) => { - let _ = self.release_buffer(buffer); - return Err(primary); - } - }; - // Never publish a hit key until replacement cleanup succeeded. - self.key = None; - let old = match self.buffer.take() { - Some(old) => old, - None => { - let _ = self.release_buffer(buffer); - return Err(Error::CudaExecution); - } - }; - if let Err(error) = old.release() { - self.failed.set(true); - let primary = driver_error(error); - let _ = self.release_buffer(buffer); - return Err(primary); - } - self.buffer = Some(buffer); - self.key = Some(key); - Ok(pending) - } - - /// The device image of `prior` when this mirror holds exactly that state (identity of the producing state, never a - /// position): the buffer moves to the caller and a fresh one takes its place, so the chunk starts from the very bytes - /// it downloaded as `prior` instead of converting and uploading them again. `adopt_chunk` releases the stand-in. - pub(in super::super) fn take_resident_for(&mut self, prior: &GdnPrior, cache: &super::super::DenseWeightCache<'ctx>) -> Result>> { - if self.failed.get() - || !prior.mirror_admits(&self.binding, self.layer) - || !self.key.as_ref().is_some_and(|key| key.matches(prior)) - || self.buffer.as_ref().is_none_or(|b| b.len() != MIRROR_BYTES) - { - return Ok(None); - } - let spare = cache.take_gdn_scratch(self.context, MIRROR_BYTES)?; - self.key = None; - Ok(self.buffer.replace(spare)) - } - - /// Actual sealed chunk producer alone provides canonical payload and buffer. - pub(in super::super) fn adopt_chunk( - &mut self, - context: &Context<'_>, - buffer: DeviceBuffer<'ctx>, - prior: &GdnPrior, - cache: &super::super::DenseWeightCache<'ctx>, - ) -> Result<()> { - if self.failed.get() - || !std::ptr::eq(self.context, context) - || buffer.len() != MIRROR_BYTES - || !prior.mirror_admits(&self.binding, self.layer) - { - let _ = self.release_buffer(buffer); - return Err(if self.failed.get() { - Error::CudaExecution - } else { - Error::IdentityMismatch - }); - } - self.key = None; - let Some(old) = self.buffer.take() else { - let _ = self.release_buffer(buffer); - return Err(Error::CudaExecution); - }; - if let Err(error) = cache.return_gdn_scratch(old) { - self.failed.set(true); - let _ = self.release_buffer(buffer); - return Err(error); - } - self.buffer = Some(buffer); - self.key = Some(prior.mirror_key()); - Ok(()) - } - - pub(super) fn release_buffer(&mut self, buffer: DeviceBuffer<'ctx>) -> Result<()> { - buffer.release().map_err(|error| { - self.failed.set(true); - driver_error(error) - }) - } - - pub(in crate::qwen_forward) fn close(mut self) -> Result<()> { - self.key = None; - match self.buffer.take() { - Some(buffer) => buffer.release().map_err(|error| { - self.failed.set(true); - driver_error(error) - }), - None if self.failed.get() => Err(Error::CudaExecution), - None => Ok(()), - } - } -} +#[path = "impl_gdnstatemirror/impl_gdnstatemirror_2.rs"] +mod impl_gdnstatemirror_2; +#[path = "impl_gdnstatemirror/impl_gdnstatemirror_2_2.rs"] +mod impl_gdnstatemirror_2_2; diff --git a/crates/leleka-runtime/src/qwen_forward/gdn_state_mirror/impl_gdnstatemirror/impl_gdnstatemirror_2.rs b/crates/leleka-runtime/src/qwen_forward/gdn_state_mirror/impl_gdnstatemirror/impl_gdnstatemirror_2.rs new file mode 100644 index 00000000..13a7dc77 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/gdn_state_mirror/impl_gdnstatemirror/impl_gdnstatemirror_2.rs @@ -0,0 +1,211 @@ +//! Moved out of the parent module by STRA-338: impl GdnStateMirror. + +#[allow(unused_imports)] +use super::*; + + + +impl<'ctx> GdnStateMirror<'ctx> { + pub(in crate::qwen_forward) fn new( + binding: BindingIdentity, + layer: u32, + context: &'ctx Context<'ctx>, + failed: Rc>, + ) -> Result { + if failed.get() { + return Err(Error::CudaExecution); + } + if layer >= 48 { + return Err(Error::InvalidLayer); + } + // Charge all fixed mirrors while the actor loads, before lazy MoE can + // consume the scratch reserve. Uninitialized placeholders cannot hit. + preflight_budget( + context.budget_bytes(), + context + .allocated_bytes() + .checked_add(MIRROR_BYTES) + .ok_or(Error::Overflow)?, + )?; + let buffer = context.allocate(MIRROR_BYTES).map_err(driver_error)?; + Ok(Self { + context, + binding, + layer, + buffer: Some(buffer), + key: None, + failed, + #[cfg(test)] + hits: 0, + #[cfg(test)] + misses: 0, + }) + } + + pub(in super::super::super) fn compute( + &mut self, + prior: &GdnPrior, + q: &[f32], + k: &[f32], + v: &[f32], + gate: &[f32], + beta: &[f32], + ) -> Result<(Box<[f32]>, MirrorNext<'ctx>)> { + let (readout, next) = self.compute_inner(prior, q, k, v, gate, beta)?; + match readout.into_host() { + Ok(values) => Ok((values, next)), + Err(primary) => { + let _ = self.discard(next); + Err(primary) + } + } + } + + pub(in super::super::super) fn compute_retained( + &mut self, + prior: &GdnPrior, + identity: TokenLayer, + scope: Rc<()>, + inputs: [&[f32]; 5], + ) -> Result<(MirrorReadout<'ctx>, MirrorNext<'ctx>)> { + if identity.layer() != prior.layer() || identity.position().get() != prior.next_position() { + return Err(Error::IdentityMismatch); + } + let (mut readout, next) = + self.compute_inner(prior, inputs[0], inputs[1], inputs[2], inputs[3], inputs[4])?; + readout.identity = Some(identity); + readout.scope = Some(scope); + Ok((readout, next)) + } + + pub(in super::super) fn compute_inner( + &mut self, + prior: &GdnPrior, + q: &[f32], + k: &[f32], + v: &[f32], + gate: &[f32], + beta: &[f32], + ) -> Result<(MirrorReadout<'ctx>, MirrorNext<'ctx>)> { + if self.failed.get() { + return Err(Error::CudaExecution); + } + if !prior.mirror_admits(&self.binding, self.layer) { + return Err(Error::IdentityMismatch); + } + for (values, count) in [ + (prior.values(), STATE_ELEMENTS), + (q, 2048), + (k, 2048), + (v, VALUES), + (gate, 48), + (beta, 48), + ] { + validate_values(values, count)?; + } + let resident = self.buffer.as_ref().ok_or(Error::CudaExecution)?; + if resident.len() != MIRROR_BYTES { + return Err(Error::InvalidDimension); + } + preflight_budget(self.context.budget_bytes(), self.context.allocated_bytes())?; + let hit = self.key.as_ref().is_some_and(|key| key.matches(prior)); + #[cfg(test)] + if hit { + self.hits += 1; + } else { + self.misses += 1; + } + let mut temporary = Vec::new(); + temporary + .try_reserve_exact(7) + .map_err(|_| Error::InputAllocation)?; + let mut next = None; + let mut output = None; + let operation = (|| -> Result { + // A rollback/reset miss uploads canonical host bytes into a + // transient prior; it never changes the identity of the mirror. + if !hit { + temporary.push(upload_checked(self.context, prior.values(), &self.failed)?); + } + let first = temporary.len(); + for values in [q, k, v, gate, beta] { + temporary.push(upload_checked(self.context, values, &self.failed)?); + } + next = Some(allocate(self.context, STATE_ELEMENTS)?); + output = Some(allocate(self.context, VALUES)?); + let state = if hit { resident } else { &temporary[0] }; + self.context + .gdn_step_f32( + state, + &temporary[first], + &temporary[first + 1], + &temporary[first + 2], + &temporary[first + 3], + &temporary[first + 4], + next.as_mut().ok_or(Error::IdentityMismatch)?, + output.as_mut().ok_or(Error::IdentityMismatch)?, + ) + .map_err(driver_error)?; + Ok(( + download( + next.as_ref().ok_or(Error::IdentityMismatch)?, + STATE_ELEMENTS, + )?, + download(output.as_ref().ok_or(Error::IdentityMismatch)?, VALUES)?, + )) + })(); + let mut cleanup = None; + for buffer in temporary { + if let Err(error) = buffer.release() { + self.failed.set(true); + cleanup.get_or_insert(driver_error(error)); + } + } + let result = match operation { + Err(primary) => Err(primary), + Ok(values) => cleanup.map_or(Ok(values), Err), + }; + match result { + Ok((state, readout)) => Ok(( + MirrorReadout { + context: self.context, + source: prior.clone(), + identity: None, + scope: None, + buffer: output.take(), + values: Some(readout), + failed: self.failed.clone(), + }, + MirrorNext { + context: self.context, + source: prior.clone(), + buffer: next.take().ok_or(Error::IdentityMismatch)?, + values: state, + }, + )), + Err(primary) => { + if primary == Error::CudaExecution { + self.failed.set(true); + } + if let Some(buffer) = next + && buffer.release().is_err() + { + self.failed.set(true); + } + if let Some(buffer) = output + && buffer.release().is_err() + { + self.failed.set(true); + } + Err(primary) + } + } + } + + pub(in super::super::super) fn discard(&mut self, next: MirrorNext<'ctx>) -> Result<()> { + next.buffer.release().map_err(|error| { + self.failed.set(true); + driver_error(error) + }) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/gdn_state_mirror/impl_gdnstatemirror/impl_gdnstatemirror_2_2.rs b/crates/leleka-runtime/src/qwen_forward/gdn_state_mirror/impl_gdnstatemirror/impl_gdnstatemirror_2_2.rs new file mode 100644 index 00000000..ae227671 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/gdn_state_mirror/impl_gdnstatemirror/impl_gdnstatemirror_2_2.rs @@ -0,0 +1,249 @@ +//! Moved out of the parent module by STRA-338: impl GdnStateMirror (2). + +#[allow(unused_imports)] +use super::*; + + + +impl<'ctx> GdnStateMirror<'ctx> { + + pub(in super::super::super) fn compute_borrowed( + &mut self, + prior: &GdnPrior, + identity: TokenLayer, + txn: &super::super::super::QwenStepTxn<'_, '_>, + inputs: super::super::super::chain::ScalarRecurrenceBorrow<'_, 'ctx>, + ) -> Result<(MirrorReadout<'ctx>, MirrorNext<'ctx>)> { + let (scope, [qk, h, gate, beta]) = inputs.into_parts( + self.context, + &self.binding, + &self.failed, + prior, + identity, + txn, + )?; + if self.failed.get() { + return Err(Error::CudaExecution); + } + if !prior.mirror_admits(&self.binding, self.layer) { + return Err(Error::IdentityMismatch); + } + validate_values(prior.values(), STATE_ELEMENTS)?; + let resident = self.buffer.as_ref().ok_or(Error::CudaExecution)?; + if resident.len() != MIRROR_BYTES { + return Err(Error::InvalidDimension); + } + preflight_budget(self.context.budget_bytes(), self.context.allocated_bytes())?; + let hit = self.key.as_ref().is_some_and(|key| key.matches(prior)); + #[cfg(test)] + if hit { + self.hits += 1; + } else { + self.misses += 1; + } + let mut temporary = Vec::new(); + temporary + .try_reserve_exact(1) + .map_err(|_| Error::InputAllocation)?; + let mut next = None; + let mut output = None; + let operation = (|| -> Result { + // A rollback/reset miss uploads canonical host bytes into a + // transient prior; it never changes the identity of the mirror. + if !hit { + temporary.push(upload_checked(self.context, prior.values(), &self.failed)?); + } + next = Some(allocate(self.context, STATE_ELEMENTS)?); + output = Some(allocate(self.context, VALUES)?); + let state = if hit { resident } else { &temporary[0] }; + self.context + .gdn_step_from_products_f32( + state, + qk, + h, + gate, + beta, + next.as_mut().ok_or(Error::IdentityMismatch)?, + output.as_mut().ok_or(Error::IdentityMismatch)?, + ) + .map_err(driver_error)?; + Ok(( + download( + next.as_ref().ok_or(Error::IdentityMismatch)?, + STATE_ELEMENTS, + )?, + download(output.as_ref().ok_or(Error::IdentityMismatch)?, VALUES)?, + )) + })(); + let mut cleanup = None; + for buffer in temporary { + if let Err(error) = buffer.release() { + self.failed.set(true); + cleanup.get_or_insert(driver_error(error)); + } + } + let result = match operation { + Err(primary) => Err(primary), + Ok(values) => cleanup.map_or(Ok(values), Err), + }; + match result { + Ok((state, readout)) => Ok(( + MirrorReadout { + context: self.context, + source: prior.clone(), + identity: Some(identity), + scope: Some(scope), + buffer: output.take(), + values: Some(readout), + failed: self.failed.clone(), + }, + MirrorNext { + context: self.context, + source: prior.clone(), + buffer: next.take().ok_or(Error::IdentityMismatch)?, + values: state, + }, + )), + Err(primary) => { + if primary == Error::CudaExecution { + self.failed.set(true); + } + if let Some(buffer) = next + && buffer.release().is_err() + { + self.failed.set(true); + } + if let Some(buffer) = output + && buffer.release().is_err() + { + self.failed.set(true); + } + Err(primary) + } + } + } + + pub(in super::super::super) fn publish( + &mut self, + next: MirrorNext<'ctx>, + identity: TokenLayer, + history: Box<[f32]>, + ) -> Result { + let MirrorNext { + context, + source, + buffer, + values, + } = next; + let admitted = (|| -> Result<(GdnStateKey, GdnPending)> { + if self.failed.get() { + return Err(Error::CudaExecution); + } + if !std::ptr::eq(self.context, context) + || buffer.len() != MIRROR_BYTES + || !source.mirror_admits(&self.binding, self.layer) + { + return Err(Error::IdentityMismatch); + } + // Only this producer owns the values downloaded from this exact + // candidate buffer. A caller cannot pair it with another payload. + let pending = GdnPending::new(&source, identity, values, history)?; + Ok((pending.mirror_next(&source)?.mirror_key(), pending)) + })(); + let (key, pending) = match admitted { + Ok(value) => value, + Err(primary) => { + let _ = self.release_buffer(buffer); + return Err(primary); + } + }; + // Never publish a hit key until replacement cleanup succeeded. + self.key = None; + let old = match self.buffer.take() { + Some(old) => old, + None => { + let _ = self.release_buffer(buffer); + return Err(Error::CudaExecution); + } + }; + if let Err(error) = old.release() { + self.failed.set(true); + let primary = driver_error(error); + let _ = self.release_buffer(buffer); + return Err(primary); + } + self.buffer = Some(buffer); + self.key = Some(key); + Ok(pending) + } + + /// The device image of `prior` when this mirror holds exactly that state (identity of the producing state, never a + /// position): the buffer moves to the caller and a fresh one takes its place, so the chunk starts from the very bytes + /// it downloaded as `prior` instead of converting and uploading them again. `adopt_chunk` releases the stand-in. + pub(in super::super::super) fn take_resident_for(&mut self, prior: &GdnPrior, cache: &super::super::super::DenseWeightCache<'ctx>) -> Result>> { + if self.failed.get() + || !prior.mirror_admits(&self.binding, self.layer) + || !self.key.as_ref().is_some_and(|key| key.matches(prior)) + || self.buffer.as_ref().is_none_or(|b| b.len() != MIRROR_BYTES) + { + return Ok(None); + } + let spare = cache.take_gdn_scratch(self.context, MIRROR_BYTES)?; + self.key = None; + Ok(self.buffer.replace(spare)) + } + + /// Actual sealed chunk producer alone provides canonical payload and buffer. + pub(in super::super::super) fn adopt_chunk( + &mut self, + context: &Context<'_>, + buffer: DeviceBuffer<'ctx>, + prior: &GdnPrior, + cache: &super::super::super::DenseWeightCache<'ctx>, + ) -> Result<()> { + if self.failed.get() + || !std::ptr::eq(self.context, context) + || buffer.len() != MIRROR_BYTES + || !prior.mirror_admits(&self.binding, self.layer) + { + let _ = self.release_buffer(buffer); + return Err(if self.failed.get() { + Error::CudaExecution + } else { + Error::IdentityMismatch + }); + } + self.key = None; + let Some(old) = self.buffer.take() else { + let _ = self.release_buffer(buffer); + return Err(Error::CudaExecution); + }; + if let Err(error) = cache.return_gdn_scratch(old) { + self.failed.set(true); + let _ = self.release_buffer(buffer); + return Err(error); + } + self.buffer = Some(buffer); + self.key = Some(prior.mirror_key()); + Ok(()) + } + + pub(in super::super) fn release_buffer(&mut self, buffer: DeviceBuffer<'ctx>) -> Result<()> { + buffer.release().map_err(|error| { + self.failed.set(true); + driver_error(error) + }) + } + + pub(in crate::qwen_forward) fn close(mut self) -> Result<()> { + self.key = None; + match self.buffer.take() { + Some(buffer) => buffer.release().map_err(|error| { + self.failed.set(true); + driver_error(error) + }), + None if self.failed.get() => Err(Error::CudaExecution), + None => Ok(()), + } + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache.rs b/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache.rs index 836c9683..bfc96d3f 100644 --- a/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache.rs +++ b/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache.rs @@ -3,2045 +3,23 @@ #[allow(unused_imports)] use super::*; -impl<'ctx> MoeWeightCache<'ctx> { - /// Source-only experimental candidate: preserve a reusable 1 GiB spill floor. - /// Root must bind this policy in fixture/serving identity before selection. - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(crate) fn new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile_mtp_input_spill_floor( - binding: &ModelBinding, - context: &'ctx Context<'ctx>, - bytes: &[u8], - ) -> Result { - Self::profile_with_mtp_input_and_spill_floor(binding, context, bytes, true, 1usize << 30) - } - pub(in super::super) fn note_transport_failure(&self) { - self.failed.set(true); - } - pub(crate) fn new(binding: &ModelBinding, context: &'ctx Context<'ctx>) -> Result { - Self::new_with_mtp_experts(binding, context, true) - } - /// Bytes `new` charges against the budget for the pinned MTP pack: the dense roles always, the 675 MiB expert bank only when it is uploaded. - pub(in crate::qwen_forward) const fn mtp_pack_charge(mtp_experts: bool) -> usize { - (if mtp_experts { MTP_PACK_EXPERT_BANK_BYTES } else { 0 }) + MTP_DENSE_LIMIT - } - /// `mtp_experts == false` leaves the pinned pack's EXPERT BANK (707,788,800 bytes, the draft layer's routed experts) out of VRAM. The serve stack - /// passes false when it loads the draft layer from an RT directory (`--mtp-rt-dir`, the product path): that path streams its own copy of the - /// experts (`original_mtp_rt_bank`) and never reads this one, so keeping both held 675 MiB of VRAM (and the host copy during the upload) for nothing. - /// The pack's dense roles are still uploaded: the draft-KV recording of the prompt path reads them through `mtp_matrix`. - pub(crate) fn new_with_mtp_experts(binding: &ModelBinding, context: &'ctx Context<'ctx>, mtp_experts: bool) -> Result { - let mut cache = Self { - context, - binding: binding.identity(), - main: HashMap::new(), - main_bytes: 0, - lru: None, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pinned: None, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - learned_main: false, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - learned_metadata_bytes: 0, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - adaptive: None, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - cpu_miss: None, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - routed_outputs: None, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - ephemeral_routed: None, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - adaptive_shared: None, - age: 0, - failed: Cell::new(false), - bank: None, - dense: Vec::new(), - counters: WeightCacheCounters::default(), - mtp_hits: Cell::new(0), - mmq_workspace: None, - mmq_policy: MmqRoutingPolicy::Existing, - original_prompt_mmq: false, - mmq_owner: Rc::new(()), - mtp_kv: RefCell::new(None), - mtp_experts: RefCell::new(None), - target_shared: None, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - native_prefill: None, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - original_prompt_device: None, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - original_expert_bank: None, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - original_copy_schedule: None, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - original_prompt_metadata_bytes: 0, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - original_finite_experts: [0; 48 * 512 / 64], - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - original_span_cache: (0, Vec::new()), - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - prompt_routing: None, - routed_finite: None, - routed_workspace: None, - routed_resident: None, - mtp_input_workspace: None, - #[cfg(test)] - mtp_input_completions: Cell::new(0), - #[cfg(test)] - shared_tail_witness: Cell::new(0), - #[cfg(test)] - lru_witness: Cell::new((0, 0, 0)), - #[cfg(test)] - mmq_dispatch_witness: Cell::new((0, 0, 0)), - #[cfg(test)] - mmq_triplet_witness: Cell::new((0, 0, 0)), - }; - cache.room(0)?; - if binding.has_mtp() { - let pack = binding.mtp_weights().map_err(binding_error)?; - cache.room(Self::mtp_pack_charge(mtp_experts))?; - if mtp_experts { - let data = pack.expert_bank(binding).map_err(binding_error)?; - let bank = cache.upload(&data)?; - cache.bank = Some(Rc::new(bank)); - drop(data); - cache.counters.misses = cache.counters.misses.saturating_add(1); - } - let mut total = 0usize; - for role in pack.dense_roles(binding).map_err(binding_error)? { - let rows = pack.dense_complete(binding, role).map_err(binding_error)?; - total = total - .checked_add(rows.bytes().len()) - .ok_or(Error::Overflow)?; - if total > MTP_DENSE_LIMIT { - return Err(Error::InvalidDimension); - } - let f32 = if rows.kind() == MtpKind::F32 { - let mut values = Vec::new(); - values - .try_reserve_exact(rows.bytes().len() / 4) - .map_err(|_| Error::InputAllocation)?; - for word in rows.bytes().as_chunks::<4>().0 { - values.push(f32::from_le_bytes(*word)); - } - Some(values.into_boxed_slice()) - } else { - None - }; - let buffer = cache.upload(rows.bytes())?; - cache - .dense - .try_reserve(1) - .map_err(|_| Error::InputAllocation)?; - cache.counters.misses = cache.counters.misses.saturating_add(1); - cache.dense.push(Dense { - role, - kind: rows.kind(), - rows: rows.rows(), - columns: rows.columns(), - buffer:Rc::new(buffer), - f32, - }); - } - } - Ok(cache) - } - /// Explicit private experiment only. Allocate/charge the persistent - /// workspace before MTP-bank upload or any lazy main-LRU fill. Normal new() - /// creates no workspace and keeps the unchanged native T1 path. - pub(crate) fn new_mmq(binding: &ModelBinding, context: &'ctx Context<'ctx>) -> Result { - let workspace = context.mmq_workspace().map_err(driver_error)?; - Self::assemble_mmq(binding, context, workspace) - } - /// Explicit private native-certified activation experiment. The immutable - /// workspace policy applies to GU and Down; normal new()/new_mmq() retain - /// their existing native/original-D4 policy, respectively. - pub(crate) fn new_native_mmq( - binding: &ModelBinding, - context: &'ctx Context<'ctx>, - ) -> Result { - let workspace = context.native_mmq_workspace().map_err(driver_error)?; - Self::assemble_mmq(binding, context, workspace) - } - /// Private source-only candidate: raw integer MMA is admitted only for - /// legal routed GU18. All persistent scratch (including 13,107,200 bytes - /// of integer dots) is charged before MTP upload and main-cache growth. - pub(crate) fn new_native_integer_iq3_mmq( - binding: &ModelBinding, - context: &'ctx Context<'ctx>, - ) -> Result { - Self::new_native_integer_iq3_mmq_with_prompt(binding, context, false) - } - pub(super) fn new_native_integer_iq3_mmq_with_prompt( - binding: &ModelBinding, - context: &'ctx Context<'ctx>, - original_prompt: bool, - ) -> Result { - let workspace = if original_prompt { - context.native_integer_iq3_mmq_original_formats_workspace() - } else { - context.native_integer_iq3_mmq_workspace() - }.map_err(driver_error)?; - let mut cache = Self::assemble_mmq(binding, context, workspace)?; - cache.mmq_policy = MmqRoutingPolicy::NativeIntegerIq3; - cache.original_prompt_mmq = original_prompt; - if binding.has_mtp() { - let result = (|| { - let charge = super::super::mtp_experts::fixed_workspace::ALLOCATED_BYTES; - cache.reserve_mmq_transient( - binding, - context, - charge.checked_add(512 * 1024).ok_or(Error::Overflow)?, - )?; - let fixed = super::super::mtp_experts::fixed_workspace::MtpExpertWorkspace::new( - binding.identity(), - Rc::clone(&cache.mmq_owner), - context, - )?; - *cache.mtp_experts.get_mut() = Some(fixed); - Ok(()) - })(); - if let Err(primary) = result { - let _ = cache.close(); - return Err(primary); - } - } - Ok(cache) - } - /// Existing explicit NativeDown outer256 retained-GR mode only. All old - /// constructors keep the original full-window MTP transport. - pub(crate) fn new_native_integer_iq3_mmq_retained_mtp_kv( - binding: &ModelBinding, - context: &'ctx Context<'ctx>, - ) -> Result { - Self::new_native_integer_iq3_mmq_retained_mtp_kv_with_prompt(binding, context, false) - } - pub(super) fn new_native_integer_iq3_mmq_retained_mtp_kv_with_prompt( - binding: &ModelBinding, - context: &'ctx Context<'ctx>, - original_prompt: bool, - ) -> Result { - if !binding.has_mtp() { - return Err(Error::IdentityMismatch); - } - if !room_fits( - context.allocated_bytes(), - context.budget_bytes(), - 0, - 128 * 1024 * 1024, - ) { - return Err(Error::InputAllocation); - } - let ring = context.mtp_dense_kv_ring().map_err(driver_error)?; - let cache = match Self::new_native_integer_iq3_mmq_with_prompt(binding, context, original_prompt) { - Ok(cache) => cache, - Err(primary) => { - let _ = ring.close(); - return Err(primary); - } - }; - let resident = MtpKvResident::new( - binding.identity(), - context, - Rc::clone(&cache.mmq_owner), - ring, - )?; - *cache.mtp_kv.borrow_mut() = Some(resident); - Ok(cache) - } - /// Explicit candidate-only target tail. The fixed owner is admitted while - /// main LRU is still empty; all default/Native/draft factories stay exact. - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(crate) fn new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail( - binding: &ModelBinding, - context: &'ctx Context<'ctx>, - ) -> Result { - Self::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_with_prompt(binding, context, false) - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(super) fn new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_with_prompt( - binding: &ModelBinding, - context: &'ctx Context<'ctx>, - original_prompt: bool, - ) -> Result { - let mut cache = Self::new_native_integer_iq3_mmq_retained_mtp_kv_with_prompt(binding, context, original_prompt)?; - let operation = (|| { - cache.reserve_mmq_transient( - binding, - context, - super::super::shared_expert_workspace::ALLOCATED_BYTES, - )?; - cache.reserve_mmq_transient( - binding, - context, - super::super::moe_prefill_batch::MOE_PREFILL_PERSISTENT_BYTES, - )?; - let native = super::super::moe_prefill_batch::MoePrefillResources::new( - context, - super::super::moe_prefill_batch::MoeBf16Profile::HighOnly, - )?; - if native.allocated_bytes() != super::super::moe_prefill_batch::MOE_PREFILL_PERSISTENT_BYTES { - let _ = native.close(); - return Err(Error::InvalidDimension); - } - cache.native_prefill = Some(RefCell::new(native)); - cache.target_shared = Some(super::super::shared_expert_workspace::TargetSharedWorkspace::new( - binding.identity(), - Rc::clone(&cache.mmq_owner), - context, - )?); - cache.validate(binding, context) - })(); - if let Err(primary) = operation { - let _ = cache.close(); - return Err(primary); - } - Ok(cache) - } - /// Only this private changed-model candidate creates bounded host index - /// metadata. Every prior constructor retains its original unindexed policy. - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(crate) fn new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_lru( - binding: &ModelBinding, - context: &'ctx Context<'ctx>, - ) -> Result { - Self::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_lru_with_prompt(binding, context, false) - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(super) fn new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_lru_with_prompt( - binding: &ModelBinding, - context: &'ctx Context<'ctx>, - original_prompt: bool, - ) -> Result { - let index = LruIndex::new()?; - let mut cache = - Self::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_with_prompt(binding, context, original_prompt)?; - if !cache.main.is_empty() || cache.main_bytes != 0 { - let _ = cache.close(); - return Err(Error::IdentityMismatch); - } - let operation = (|| { - // Fixed status and helper module precede indexed/pinned lazy weights. - // The existing physical and typed 128 MiB reserve remains separate. - cache.reserve_mmq_transient(binding, context, 4)?; - cache.routed_finite = Some(Rc::new(RoutedFiniteOwner::new(context)?)); - // Actual table/DownQ8/status capacity is separate from the reserve. - // Construct and observe module residency while main weights are empty. - cache.reserve_mmq_transient(binding, context, 46_596)?; - cache.routed_workspace = Some(Rc::new(RoutedWorkspaceOwner::new(context)?)); - cache.room(0)?; - cache.validate(binding, context) - })(); - if let Err(primary) = operation { - let _ = cache.close(); - return Err(primary); - } - cache.lru = Some(index); - Ok(cache) - } - #[cfg(test)] - pub(crate) fn test_lru_witness(&self) -> (u64, u64, u64) { - self.lru_witness.get() - } - #[cfg(test)] - pub(crate) fn test_lru_metadata_bytes(&self) -> Result { - self.lru - .as_ref() - .ok_or(Error::IdentityMismatch)? - .metadata_bytes() - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(crate) fn profile_preload_upload_bytes(&self) -> u64 { - self.pinned - .as_ref() - .map_or(0, |pool| pool.preload_upload_bytes) - } - pub(in super::super) fn uses_direct_native_down_packets(&self) -> bool { - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - return (self.pinned.is_some() || self.adaptive.is_some()) - && self.requires_iq3_mmq_admission(); - #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] - false - } - pub(in super::super) fn routed_finite_owner( - &self, - binding: &ModelBinding, - context: &Context<'_>, - ) -> Result>> { - self.validate(binding, context)?; - if !self.uses_direct_native_down_packets() { - return Err(Error::IdentityMismatch); - } - self.routed_finite - .as_ref() - .map(Rc::clone) - .ok_or(Error::IdentityMismatch) - } - pub(in super::super) fn routed_workspace_owner( - &self, - binding: &ModelBinding, - context: &Context<'_>, - ) -> Result>> { - self.validate(binding, context)?; - if !self.uses_direct_native_down_packets() { - return Err(Error::IdentityMismatch); - } - self.routed_workspace - .as_ref() - .map(Rc::clone) - .ok_or(Error::IdentityMismatch) - } - pub(super) fn is_pinned(&self, key: MoeWeightDescriptor) -> bool { - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if self - .adaptive_shared - .as_ref() - .is_some_and(|pool| pool.contains(key)) - { - return true; - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - return self.pinned.as_ref().is_some_and(|pool| { - pool.shared - .as_ref() - .is_some_and(|shared| shared.contains(key)) - || (!self.learned_main && pool.plan.contains(key.layer, key.expert, key.role)) - }); - #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] - { - let _ = key; - false - } - } - pub(super) fn spill_len(&self) -> Result { - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if let Some(pool) = &self.pinned { - return self - .main - .len() - .checked_sub(if self.learned_main { - 0 - } else { - pool.loaded_matrices - }) - .and_then(|n| { - n.checked_sub( - pool.shared - .as_ref() - .map_or(0, |shared| shared.descriptor_count()), - ) - }) - .ok_or(Error::IdentityMismatch); - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if let Some(shared) = &self.adaptive_shared { - return self - .main - .len() - .checked_sub(shared.descriptor_count()) - .ok_or(Error::IdentityMismatch); - } - Ok(self.main.len()) - } - pub(super) fn note_profile_request(&mut self, key: MoeWeightDescriptor, hit: bool) { - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if let Some(pool) = &mut self.pinned { - let counter = if (!self.learned_main - && pool.plan.contains(key.layer, key.expert, key.role)) - || pool - .shared - .as_ref() - .is_some_and(|shared| shared.contains(key)) - { - &mut pool.pinned_hits - } else if hit { - &mut pool.spill_hits - } else { - &mut pool.spill_misses - }; - *counter = counter.saturating_add(1); - } - #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] - { - let _ = (key, hit); - } - } - pub(super) fn reserve_main(&mut self, additional: usize) -> Result<()> { - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if let Some(pool) = &self.pinned { - if self - .main - .len() - .checked_add(additional) - .is_none_or(|n| n > pool.main_slot_limit || n > self.main.capacity()) - { - return Err(Error::InputAllocation); - } - // Current growth-left already covers this batch: do not reserve or - // rehash pinned-policy metadata after deletion/tombstone churn. - return Ok(()); - } - self.main - .try_reserve(additional) - .map_err(|_| Error::InputAllocation) - } - pub(super) fn prepare_lru_updates( - &self, - updates: &[(MoeWeightDescriptor, u64)], - ) -> Result> { - let Some(index) = &self.lru else { - return Ok(None); - }; - if index.len() != self.spill_len()? { - return Err(Error::IdentityMismatch); - } - if !(1..=3).contains(&updates.len()) { - return Err(Error::InvalidDimension); - } - let mut spill = [(updates[0].0, 0u64); 3]; - let mut count = 0; - for &(key, age) in updates { - if self.is_pinned(key) { - if !self.main.contains_key(&key) { - return Err(Error::IdentityMismatch); - } - continue; - } - spill[count] = (key, age); - count += 1; - if index.entry_age(key)? != self.main.get(&key).map(|entry| entry.age) { - return Err(Error::IdentityMismatch); - } - } - if count == 0 { - return Ok(None); - } - index.prepare_updates(&spill[..count]).map(Some) - } - pub(super) fn pinned_updates_allowed(&self) -> bool { - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - return self.pinned.is_some() || self.adaptive_shared.is_some(); - #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] - false - } - pub(super) fn commit_lru_updates(&mut self, updates: Option, count: u64) -> Result<()> { - let pinned_updates_allowed = self.pinned_updates_allowed(); - match (self.lru.as_mut(), updates) { - (None, None) => Ok(()), - (Some(_), None) if pinned_updates_allowed => Ok(()), - (Some(index), Some(updates)) => { - index.commit_updates(updates)?; - #[cfg(test)] - { - let (lookups, updates, removals) = self.lru_witness.get(); - self.lru_witness - .set((lookups, updates.saturating_add(count), removals)); - } - #[cfg(not(test))] - let _ = count; - Ok(()) - } - _ => Err(Error::IdentityMismatch), - } - } - pub(super) fn eviction_key(&self, protected: &[MoeWeightDescriptor]) -> Result { - let key = if let Some(index) = &self.lru { - if index.len() != self.spill_len()? { - return Err(Error::IdentityMismatch); - } - let key = index.oldest(protected)?.ok_or(Error::InputAllocation)?; - if self.is_pinned(key) - || index.entry_age(key)? != self.main.get(&key).map(|entry| entry.age) - { - return Err(Error::IdentityMismatch); - } - #[cfg(test)] - { - let (lookups, updates, removals) = self.lru_witness.get(); - self.lru_witness - .set((lookups.saturating_add(1), updates, removals)); - } - key - } else { - oldest_weight( - self.main - .iter() - .filter(|(key, _)| !protected.contains(key) && !self.is_pinned(**key)) - .map(|(key, entry)| (*key, entry.age)), - ) - .ok_or(Error::InputAllocation)? - }; - Ok(key) - } - pub(super) fn remove_lru_entry(&mut self, key: MoeWeightDescriptor) -> Result<()> { - if self.is_pinned(key) { - return Err(Error::IdentityMismatch); - } - let spill_len = self.spill_len()?; - if let Some(index) = &mut self.lru { - if index.len() != spill_len - || index.entry_age(key)? != self.main.get(&key).map(|entry| entry.age) - { - return Err(Error::IdentityMismatch); - } - index.remove(key)?; - #[cfg(test)] - { - let (lookups, updates, removals) = self.lru_witness.get(); - self.lru_witness - .set((lookups, updates, removals.saturating_add(1))); - } - } - Ok(()) - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in super::super) fn native_prefill_resources( - &self, - binding: &ModelBinding, - context: &Context<'_>, - ) -> Result>> { - self.validate(binding, context)?; - let owner = self - .native_prefill - .as_ref() - .ok_or(Error::IdentityMismatch)? - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch)?; - owner.validate_context(context)?; - Ok(owner) - } - /// Genuine binding-resolved whole immutable shared weights, held through - /// the closed native producer. Descriptors never authenticate arbitrary bytes. - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in super::super) fn with_native_shared_weights( - &mut self, - binding: &ModelBinding, - context: &Context<'_>, - layer: super::super::contract::LayerId, - transient: usize, - execute: impl FnOnce( - &'ctx Context<'ctx>, - super::super::moe_prefill_batch::SharedWeights<'_, 'ctx>, - &mut super::super::moe_prefill_batch::MoePrefillResources<'ctx>, - ) -> Result, - ) -> Result { - self.validate(binding, context)?; - let weights = binding - .moe_expert_weights(layer.get(), std::array::from_fn(|slot| slot as u32)) - .map_err(binding_error)?; - if !weights.matches(&binding.identity(), layer.get()) { - return Err(Error::IdentityMismatch); - } - let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down]; - let keys = [ - binding - .moe_weight_descriptor(&weights, MoeExpertSelection::Shared, roles[0]) - .map_err(binding_error)?, - binding - .moe_weight_descriptor(&weights, MoeExpertSelection::Shared, roles[1]) - .map_err(binding_error)?, - binding - .moe_weight_descriptor(&weights, MoeExpertSelection::Shared, roles[2]) - .map_err(binding_error)?, - binding - .moe_shared_scalar_descriptor(&weights) - .map_err(binding_error)?, - ]; - super::super::shared_expert_workspace::validate_descriptors(&keys)?; - if keys.iter().any(|key| key.layer != layer.get()) { - return Err(Error::IdentityMismatch); - } - for (index, key) in keys.iter().enumerate() { - let _ = self.main_entry_protected(*key, &keys, || { - if index == 3 { - binding.moe_shared_scalar(&weights).map_err(binding_error) - } else { - Ok(binding - .moe_expert_block( - &weights, - MoeExpertSelection::Shared, - roles[index], - 0, - key.rows, - ) - .map_err(binding_error)? - .into_bytes()) - } - })?; - } - // Filling these four weights may consume an earlier physical snapshot. - // Re-admit the real transient peak while protecting every lent owner. - self.room_protected(transient, &keys)?; - self.validate(binding, context)?; - let raw = |index: usize| -> Result<&DeviceBuffer<'ctx>> { - let entry = self.main.get(&keys[index]).ok_or(Error::IdentityMismatch)?; - if entry.charged_bytes != keys[index].bytes { - return Err(Error::IdentityMismatch); - } - match &entry.weight { - EncodedWeight::Raw(buffer) => Ok(buffer), - EncodedWeight::Dual(_, _) => Err(Error::IdentityMismatch), - } - }; - let buffers = [raw(0)?, raw(1)?, raw(2)?, raw(3)?]; - let mut owner = self.native_prefill_resources(binding, context)?; - let result = execute( - self.context, - super::super::moe_prefill_batch::SharedWeights { - keys: &keys, - buffers, - }, - &mut owner, - ); - if self.context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) { - self.failed.set(true); - } - result - } - pub(in super::super) fn has_target_shared_tail(&self) -> bool { - self.target_shared.is_some() - } - #[cfg(test)] - pub(crate) fn test_shared_tail_witness(&self) -> u64 { - self.shared_tail_witness.get() - } - /// Source-descriptor admission precedes all fills. Requested entries cannot - /// evict one another; every actual weight remains immutably borrowed until - /// the closed driver's completion/readback has consumed the result. - #[allow(clippy::too_many_arguments)] - pub(in super::super) fn compose_target_shared_tail( - &mut self, - binding: &ModelBinding, - context: &Context<'_>, - weights: &MoeExpertWeights, - identity: super::super::contract::TokenLayer, - activation: &DeviceBuffer<'_>, - packed: &DeviceBuffer<'_>, - route: &[f32; 10], - ) -> Result> { - self.validate(binding, context)?; - if !weights.matches(&binding.identity(), identity.layer().get()) { - return Err(Error::IdentityMismatch); - } - let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down]; - let keys = [ - binding - .moe_weight_descriptor(weights, MoeExpertSelection::Shared, roles[0]) - .map_err(binding_error)?, - binding - .moe_weight_descriptor(weights, MoeExpertSelection::Shared, roles[1]) - .map_err(binding_error)?, - binding - .moe_weight_descriptor(weights, MoeExpertSelection::Shared, roles[2]) - .map_err(binding_error)?, - binding - .moe_shared_scalar_descriptor(weights) - .map_err(binding_error)?, - ]; - super::super::shared_expert_workspace::validate_descriptors(&keys)?; - for (index, key) in keys.iter().enumerate() { - let _ = self.main_entry_protected(*key, &keys, || { - if index == 3 { - binding.moe_shared_scalar(weights).map_err(binding_error) - } else { - Ok(binding - .moe_expert_block( - weights, - MoeExpertSelection::Shared, - roles[index], - 0, - key.rows, - ) - .map_err(binding_error)? - .into_bytes()) - } - })?; - } - self.validate(binding, context)?; - let entries = &self.main; - let raw = |index: usize| -> Result<&DeviceBuffer<'ctx>> { - let entry = entries.get(&keys[index]).ok_or(Error::IdentityMismatch)?; - if entry.charged_bytes != keys[index].bytes { - return Err(Error::IdentityMismatch); - } - match &entry.weight { - EncodedWeight::Raw(buffer) => Ok(buffer), - EncodedWeight::Dual(_, _) => Err(Error::IdentityMismatch), - } - }; - let buffers = [raw(0)?, raw(1)?, raw(2)?, raw(3)?]; - let result = self - .target_shared - .as_mut() - .ok_or(Error::IdentityMismatch)? - .compose( - binding, - &self.mmq_owner, - context, - identity, - &keys, - buffers, - activation, - packed, - route, - ); - if context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) { - self.failed.set(true); - } - if result.is_ok() { - #[cfg(test)] - self.shared_tail_witness - .set(self.shared_tail_witness.get().saturating_add(1)); - } - result - } - #[allow(clippy::too_many_arguments)] - pub(in super::super) fn compose_fixed_mtp_experts( - &self, - binding: &ModelBinding, - context: &Context<'_>, - frame: &super::super::mtp::MtpFrame, - session: &super::super::session::QwenSession<'_>, - bank: &DeviceBuffer<'_>, - shared: [&DeviceBuffer<'_>; 4], - mixed: &[f32], - ids: [u32; 10], - weights: [f32; 10], - failed: Rc>, - ) -> Result> { - self.validate(binding, context)?; - frame.validate(binding, session)?; - if !self.requires_iq3_mmq_admission() { - return Err(Error::IdentityMismatch); - } - // Admit only these actual cache-owned immutable draft weight owners. - // No second descriptor/source read or hit-counter mutation is needed. - if self - .bank - .as_ref() - .is_none_or(|actual| !std::ptr::eq(&**actual, bank)) - { - return Err(Error::IdentityMismatch); - } - for (role, buffer) in [ - MtpRole::SharedGate, - MtpRole::SharedUp, - MtpRole::SharedDown, - MtpRole::SharedScalar, - ] - .into_iter() - .zip(shared) - { - let actual = self - .dense - .iter() - .find(|entry| entry.role == role) - .ok_or(Error::IdentityMismatch)?; - if !std::ptr::eq(&*actual.buffer, buffer) { - return Err(Error::IdentityMismatch); - } - } - let mut slot = self - .mtp_experts - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch)?; - let result = slot.as_mut().ok_or(Error::IdentityMismatch)?.compose( - binding, - &self.mmq_owner, - context, - frame, - session, - bank, - shared, - mixed, - ids, - weights, - Rc::clone(&failed), - ); - if failed.get() || context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) { - self.failed.set(true); - } - result - } - pub(in super::super) fn has_mtp_kv_ring(&self) -> Result { - let slot = self - .mtp_kv - .try_borrow() - .map_err(|_| Error::IdentityMismatch)?; - Ok(slot.is_some()) - } - pub(in super::super) fn prepare_mtp_kv( - &self, - binding: &ModelBinding, - context: &Context<'_>, - next: &super::super::mtp::DenseKv, - frame: &super::super::mtp::MtpFrame, - ) -> Result<()> { - self.validate(binding, context)?; - let mut slot = self - .mtp_kv - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch)?; - let result = slot.as_mut().ok_or(Error::IdentityMismatch)?.prepare( - binding, - context, - &self.mmq_owner, - next, - frame, - ); - if context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) { - self.failed.set(true); - } - result - } - pub(in super::super) fn attend_mtp_kv( - &self, - binding: &ModelBinding, - context: &Context<'_>, - next: &super::super::mtp::DenseKv, - frame: &super::super::mtp::MtpFrame, - query: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.prepare_mtp_kv(binding, context, next, frame)?; - let mut slot = self - .mtp_kv - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch)?; - let result = slot.as_mut().ok_or(Error::IdentityMismatch)?.attend( - query, - output, - u32::try_from(frame.position().get()).map_err(|_| Error::Overflow)?, - ); - if context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) { - self.failed.set(true); - } - result - } - pub(super) fn assemble_mmq( - binding: &ModelBinding, - context: &'ctx Context<'ctx>, - workspace: MmqWorkspace<'ctx>, - ) -> Result { - Self::assemble_mmq_with_mtp_experts(binding, context, workspace, true) - } - pub(super) fn assemble_mmq_with_mtp_experts( - binding: &ModelBinding, - context: &'ctx Context<'ctx>, - workspace: MmqWorkspace<'ctx>, - mtp_experts: bool, - ) -> Result { - if !room_fits(context.allocated_bytes(), context.budget_bytes(), 0, 0) { - let _ = workspace.close(); - return Err(Error::InputAllocation); - } - match Self::new_with_mtp_experts(binding, context, mtp_experts) { - Ok(mut cache) => { - cache.mmq_workspace = Some(workspace); - Ok(cache) - } - Err(primary) => { - let _ = workspace.close(); - Err(primary) - } - } - } - /// Cache-local observation of completed producers, never dispatch intent. - #[cfg(test)] - pub(in crate::qwen_forward) fn test_mmq_dispatch_witness(&self) -> (u64, u64, u64) { - self.mmq_dispatch_witness.get() - } - #[cfg(test)] - pub(in crate::qwen_forward) fn note_test_mmq_dispatch(&self, resident: bool, rows: usize) { - let (layers, columns, fallback) = self.mmq_dispatch_witness.get(); - self.mmq_dispatch_witness.set(if resident { - (layers + 1, columns + rows as u64 * 10, fallback) - } else { - (layers, columns, fallback + 1) - }); - } - /// Stable actor-owned context, admitted against the actual transaction's - /// context pointer. Never extend a short session/closure reference. - pub(in super::super) fn mmq_context( - &self, - binding: &ModelBinding, - observed: &Context<'_>, - ) -> Result<&'ctx Context<'ctx>> { - self.validate(binding, observed)?; - Ok(self.context) - } - pub(super) fn weight_layout(&self, key: MoeWeightDescriptor) -> Result> { - if self.original_prompt_mmq { original_dual_layout(key) } else { dual_layout(key) } - } - pub(in super::super) fn has_original_prompt_mmq(&self) -> bool { self.original_prompt_mmq } - /// Root's selected adaptive capacity factory calls this before any routed - /// prefix/adaptive publication. Same actual workspace, no second experiment. - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - pub(crate) fn admit_original_expert_groups(&mut self,binding:&ModelBinding, - context:&Context<'_>,capacity:u32)->Result<()> { - self.validate(binding,context)?; - if !self.original_prompt_mmq || !self.main.is_empty() || self.main_bytes!=0 - || self.adaptive.is_some() {return Err(Error::IdentityMismatch);} - let workspace=self.mmq_workspace.as_mut().ok_or(Error::IdentityMismatch)?; - workspace.enable_original_expert_groups(capacity).map_err(driver_error)?; - self.room(0)?; - self.validate(binding,context) - } - - pub(in super::super) fn requires_iq3_mmq_admission(&self) -> bool { - self.mmq_policy == MmqRoutingPolicy::NativeIntegerIq3 - } - /// Called only after every phase row and existing kind admission has been - /// checked. The new policy additionally verifies every actual descriptor - /// before activation quantization, cache fill, or a GU kernel can run. - pub(in super::super) fn admit_mmq_chunk( - &self, - binding: &ModelBinding, - context: &Context<'_>, - rows: usize, - triplets: &[[MoeWeightDescriptor; 3]], - original_prompt: bool, - ) -> Result> { - self.validate(binding, context)?; - if !(if original_prompt { 1..=64 } else { 2..=64 }).contains(&rows) - || self.mmq_workspace.is_none() || (original_prompt && !self.original_prompt_mmq) { - return Err(Error::IdentityMismatch); - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if self.adaptive.is_some() && !original_prompt { - return Ok(None); - } - if original_prompt || self.requires_iq3_mmq_admission() { - if triplets.len() != rows.checked_mul(10).ok_or(Error::Overflow)? { - return Err(Error::InvalidDimension); - } - for keys in triplets { - if !(if original_prompt { original_mmq_triplet(keys)? } else { integer_iq3_triplet(keys)? }) { - return Ok(None); - } - } - } - Ok(Some(MmqChunkAdmission { - owner: Rc::clone(&self.mmq_owner), - policy: self.mmq_policy, - original_prompt, - })) - } - pub(in super::super) fn with_mmq_workspace( - &mut self, - binding: &ModelBinding, - context: &Context<'_>, - admission: &MmqChunkAdmission, - execute: impl FnOnce(&mut Self, &mut MmqWorkspace<'ctx>) -> Result, - ) -> Result { - self.validate(binding, context)?; - if !Rc::ptr_eq(&self.mmq_owner, &admission.owner) || admission.policy != self.mmq_policy - || (admission.original_prompt && !self.original_prompt_mmq) { - return Err(Error::IdentityMismatch); - } - let mut workspace = self.mmq_workspace.take().ok_or(Error::IdentityMismatch)?; - let result = execute(self, &mut workspace); - self.mmq_workspace = Some(workspace); - if context.is_poisoned() || matches!(&result, Err(Error::CudaExecution)) { - self.failed.set(true); - } - result - } - /// Hold all three real immutable cache entries simultaneously. Staging - /// uses their original binding descriptors and padded charge once; a - /// missing/evicted descriptor refuses, never manufactures a weight view. - pub(in super::super) fn with_mmq_triplet( - &mut self, - binding: &ModelBinding, - weights: &MoeExpertWeights, - selection: MoeExpertSelection, - original_prompt: bool, - execute: impl FnOnce(&MmqWeights<'ctx>, &MmqWeights<'ctx>, &MmqWeights<'ctx>) -> Result, - ) -> Result { - if original_prompt && !self.original_prompt_mmq { return Err(Error::IdentityMismatch); } - if original_prompt || self.requires_iq3_mmq_admission() { - return self.with_integer_mmq_triplet(binding, weights, selection, original_prompt, execute); - } - self.validate(binding, self.context)?; - let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down]; - let mut keys = Vec::new(); - keys.try_reserve_exact(3) - .map_err(|_| Error::InputAllocation)?; - for role in roles { - let _ = self.matrix(binding, weights, selection, role)?; - keys.push( - binding - .moe_weight_descriptor(weights, selection, role) - .map_err(binding_error)?, - ); - } - execute( - self.mmq_owner(&keys[0])?, - self.mmq_owner(&keys[1])?, - self.mmq_owner(&keys[2])?, - ) - } - - // Only the explicit integer candidate uses the closed three-weight fill. - // Every requested owner stays resident while missing roles are admitted. - pub(super) fn with_integer_mmq_triplet( - &mut self, - binding: &ModelBinding, - weights: &MoeExpertWeights, - selection: MoeExpertSelection, - original_prompt: bool, - execute: impl FnOnce(&MmqWeights<'ctx>, &MmqWeights<'ctx>, &MmqWeights<'ctx>) -> Result, - ) -> Result { - self.validate(binding, self.context)?; - let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down]; - let keys = [ - binding - .moe_weight_descriptor(weights, selection, roles[0]) - .map_err(binding_error)?, - binding - .moe_weight_descriptor(weights, selection, roles[1]) - .map_err(binding_error)?, - binding - .moe_weight_descriptor(weights, selection, roles[2]) - .map_err(binding_error)?, - ]; - let layouts = [ - self.weight_layout(keys[0])?.ok_or(Error::InvalidDimension)?, - self.weight_layout(keys[1])?.ok_or(Error::InvalidDimension)?, - self.weight_layout(keys[2])?.ok_or(Error::InvalidDimension)?, - ]; - let formats = layouts.map(|(format, _)| format); - let charges = layouts.map(|(_, charge)| charge); - let mut missing = 0usize; - let mut extra = 0usize; - for (key, charged) in keys.iter().zip(charges) { - if !self.main.contains_key(key) { - missing += 1; - extra = extra.checked_add(charged).ok_or(Error::Overflow)?; - } else { - let owner = self.mmq_owner(key)?; - if owner.allocated_bytes() != charged { - return Err(Error::IdentityMismatch); - } - } - } - if !(if original_prompt { original_mmq_triplet(&keys)? } else { integer_iq3_triplet(&keys)? }) { - return Err(Error::InvalidDimension); - } - if keys - .iter() - .any(|key| self.is_pinned(*key) && !self.main.contains_key(key)) - { - return Err(Error::IdentityMismatch); - } - if missing == 0 || missing == 3 { - for key in keys { - self.note_profile_request(key, missing == 0); - } - } - let next_age = self.age.checked_add(3).ok_or(Error::Overflow)?; - if missing != 0 { - self.room_protected(extra, &keys)?; - self.reserve_main(missing)?; - } - if missing == 3 { - let update = self.prepare_lru_updates(&[ - (keys[0], self.age + 1), - (keys[1], self.age + 2), - (keys[2], next_age), - ])?; - // Read actual bound spans before any upload. The driver owns its - // padded staging until all attempted copies have completed. - let mut raw: [Box<[u8]>; 3] = std::array::from_fn(|_| Box::default()); - let mut read_bytes = 0usize; - for (index, (role, key)) in roles.into_iter().zip(&keys).enumerate() { - let block = binding - .moe_expert_block(weights, selection, role, 0, key.rows) - .map_err(binding_error)?; - if block.bytes().len() != key.bytes { - return Err(Error::InvalidDimension); - } - raw[index] = block.into_bytes(); - read_bytes = read_bytes.checked_add(key.bytes).ok_or(Error::Overflow)?; - } - let main_bytes = self.main_bytes.checked_add(extra).ok_or(Error::Overflow)?; - let context = self.context; - let uploaded = if original_prompt { - context.mmq_original_weight_triplet(formats, [&raw[0], &raw[1], &raw[2]]) - } else { - context.mmq_weight_triplet(formats, [&raw[0], &raw[1], &raw[2]]) - }; - let owners = match uploaded { - Ok(owners) => owners, - Err(error) => { - if context.is_poisoned() { - self.failed.set(true); - } - return Err(driver_error(error)); - } - }; - if owners - .iter() - .zip(&charges) - .any(|(owner, &charge)| owner.allocated_bytes() != charge) - { - for owner in owners.into_iter().rev() { - if owner.close().is_err() { - self.failed.set(true); - } - } - return Err(Error::IdentityMismatch); - } - if let Err(primary) = self.commit_lru_updates(update, 3) { - for owner in owners.into_iter().rev() { - if owner.close().is_err() { - self.failed.set(true); - } - } - return Err(primary); - } - // No fallible allocation/validation follows the first insertion. - // Publish the complete triplet only after driver completion. - for (index, owner) in owners.into_iter().enumerate() { - self.main.insert( - keys[index], - Entry { - weight: EncodedWeight::Dual(formats[index], owner), - charged_bytes: charges[index], - age: self.age + index as u64 + 1, - }, - ); - } - self.main_bytes = main_bytes; - self.age = next_age; - self.counters.misses = self.counters.misses.saturating_add(3); - self.counters.read_bytes = self.counters.read_bytes.saturating_add(read_bytes as u64); - self.counters.upload_bytes = self.counters.upload_bytes.saturating_add(extra as u64); - for (key, charge) in keys.into_iter().zip(charges) { - self.note_permanent_fill(key, key.bytes, charge); - } - } else if missing != 0 { - // Admission is not a reservation against other GPU actors. Every - // later physical-room query protects all requested roles again. - for (role, key) in roles.into_iter().zip(&keys) { - let _ = self.main_entry_protected(*key, &keys, || { - let block = binding - .moe_expert_block(weights, selection, role, 0, key.rows) - .map_err(binding_error)?; - Ok(block.into_bytes()) - })?; - } - } else { - // A complete resident hit allocates/uploads nothing, so it needs - // no physical-memory query or new admission reservation. - let update = self.prepare_lru_updates(&[ - (keys[0], self.age + 1), - (keys[1], self.age + 2), - (keys[2], next_age), - ])?; - self.commit_lru_updates(update, 3)?; - for (index, key) in keys.iter().enumerate() { - let entry = self.main.get_mut(key).ok_or(Error::IdentityMismatch)?; - entry.age = self.age + index as u64 + 1; - } - self.age = next_age; - self.counters.hits = self.counters.hits.saturating_add(3); - } - if missing == 0 { - for key in keys { - self.note_permanent_hit(key); - } - } - #[cfg(test)] - { - let (full, mixed, hit) = self.mmq_triplet_witness.get(); - self.mmq_triplet_witness.set(match missing { - 3 => (full.saturating_add(1), mixed, hit), - 0 => (full, mixed, hit.saturating_add(1)), - _ => (full, mixed.saturating_add(1), hit), - }); - } - self.validate(binding, self.context)?; - execute( - self.mmq_owner(&keys[0])?, - self.mmq_owner(&keys[1])?, - self.mmq_owner(&keys[2])?, - ) - } - - #[cfg(test)] - pub(in super::super) fn test_mmq_triplet_witness(&self) -> (u64, u64, u64) { - self.mmq_triplet_witness.get() - } - - pub(super) fn room_protected(&mut self, extra: usize, protected: &[MoeWeightDescriptor]) -> Result<()> { - loop { - let (free, _) = self.context.memory_info().map_err(driver_error)?; - let physical_room = extra - .checked_add(WORKING_RESERVE) - .is_some_and(|n| n <= free); - if physical_room - && room_fits( - self.context.allocated_bytes(), - self.context.budget_bytes(), - self.main_bytes, - extra, - ) - { - return Ok(()); - } - let key = self.eviction_key(protected)?; - self.remove_lru_entry(key)?; - let entry = self.main.remove(&key).ok_or(Error::IdentityMismatch)?; - if entry.weight.close().is_err() { - self.failed.set(true); - return Err(Error::CudaExecution); - } - self.main_bytes = self - .main_bytes - .checked_sub(entry.charged_bytes) - .ok_or(Error::Overflow)?; - self.counters.eviction_bytes = self - .counters - .eviction_bytes - .saturating_add(entry.charged_bytes as u64); - self.note_permanent_eviction(key, entry.charged_bytes); - } - } - pub(super) fn mmq_owner(&self, key: &MoeWeightDescriptor) -> Result<&MmqWeights<'ctx>> { - match &self.main.get(key).ok_or(Error::IdentityMismatch)?.weight { - EncodedWeight::Dual(_, owner) => Ok(owner), - EncodedWeight::Raw(_) => Err(Error::IdentityMismatch), - } - } - pub(crate) fn validate(&self, binding: &ModelBinding, context: &Context<'_>) -> Result<()> { - if self.failed.get() - || self.context.is_poisoned() - || self - .routed_finite - .as_ref() - .is_some_and(|owner| owner.is_failed()) - || self - .routed_workspace - .as_ref() - .is_some_and(|owner| owner.is_failed()) - || self - .routed_resident - .as_ref() - .is_some_and(|owner| owner.is_failed()) - || self - .mtp_input_workspace - .as_ref() - .is_some_and(|owner| owner.is_failed()) - { - return Err(Error::CudaExecution); - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if let Some(adaptive) = &self.adaptive { - adaptive.validate(binding)?; - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if let Some(outputs) = &self.routed_outputs { - outputs.validate(&binding.identity(), context)?; - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if let Some(owner) = &self.ephemeral_routed { - owner - .try_borrow() - .map_err(|_| Error::IdentityMismatch)? - .validate(binding, context)?; - } - if !self.binding.matches(&binding.identity()) || !std::ptr::eq(self.context, context) { - return Err(Error::IdentityMismatch); - } - Ok(()) - } - pub(crate) fn prepare_step( - &mut self, - binding: &ModelBinding, - context: &Context<'_>, - ) -> Result<()> { - self.validate(binding, context)?; - self.room(0) - } - /// Reserve the genuine caller's live transient peak by evicting immutable - /// main-cache entries before packet allocations. The normal working reserve - /// and original padded weight accounting remain separate and unchanged. - pub(in super::super) fn reserve_mmq_transient( - &mut self, - binding: &ModelBinding, - context: &Context<'_>, - extra: usize, - ) -> Result<()> { - self.validate(binding, context)?; - self.room(extra)?; - self.validate(binding, context) - } - pub(super) fn room(&mut self, extra: usize) -> Result<()> { - loop { - // The typed cap excludes driver modules and other GPU actors. - // Query actual current-context availability before own-cache - // admission; a snapshot is not a reservation against other actors. - let (free, _) = self.context.memory_info().map_err(driver_error)?; - let physical_room = extra - .checked_add(WORKING_RESERVE) - .is_some_and(|needed| needed <= free); - if physical_room - && room_fits( - self.context.allocated_bytes(), - self.context.budget_bytes(), - self.main_bytes, - extra, - ) - { - return Ok(()); - } - let key = self.eviction_key(&[])?; - self.remove_lru_entry(key)?; - let entry = self.main.remove(&key).ok_or(Error::IdentityMismatch)?; - if entry.weight.close().is_err() { - self.failed.set(true); - return Err(Error::CudaExecution); - } - self.main_bytes = self - .main_bytes - .checked_sub(entry.charged_bytes) - .ok_or(Error::Overflow)?; - self.counters.eviction_bytes = self - .counters - .eviction_bytes - .saturating_add(entry.charged_bytes as u64); - self.note_permanent_eviction(key, entry.charged_bytes); - } - } - pub(super) fn upload(&mut self, bytes: &[u8]) -> Result> { - let mut buffer = match self.context.allocate(bytes.len()) { - Ok(buffer) => buffer, - Err(error) => { - self.failed.set(true); - return Err(driver_error(error)); - } - }; - if buffer.copy_from(bytes).is_err() { - self.failed.set(true); - let _ = buffer.release(); - return Err(Error::CudaExecution); - } - self.counters.read_bytes = self.counters.read_bytes.saturating_add(bytes.len() as u64); - self.counters.upload_bytes = self - .counters - .upload_bytes - .saturating_add(bytes.len() as u64); - Ok(buffer) - } - pub(super) fn main_entry_protected( - &mut self, - key: MoeWeightDescriptor, - protected: &[MoeWeightDescriptor], - read: impl FnOnce() -> Result>, - ) -> Result> { - if self.failed.get() { - return Err(Error::CudaExecution); - } - let hit = self.main.contains_key(&key); - if self.is_pinned(key) && !hit { - return Err(Error::IdentityMismatch); - } - self.note_profile_request(key, hit); - self.age = self.age.checked_add(1).ok_or(Error::Overflow)?; - if hit { - let update = self.prepare_lru_updates(&[(key, self.age)])?; - self.commit_lru_updates(update, 1)?; - self.counters.hits = self.counters.hits.saturating_add(1); - } else { - self.counters.misses = self.counters.misses.saturating_add(1); - let dual = self.weight_layout(key)?; - let charged_bytes = dual.map_or(key.bytes, |(_, bytes)| bytes); - self.room_protected(charged_bytes, protected)?; - self.reserve_main(1)?; - let update = self.prepare_lru_updates(&[(key, self.age)])?; - let bytes = read()?; - if bytes.len() != key.bytes { - return Err(Error::InvalidDimension); - } - let weight = if let Some((format, expected)) = dual { - let owner = match self.context.mmq_weights(format, &bytes) { - Ok(owner) => owner, - Err(error) => { - if self.context.is_poisoned() { - self.failed.set(true); - } - return Err(driver_error(error)); - } - }; - if owner.allocated_bytes() != expected { - let cleanup = owner.close(); - if cleanup.is_err() { - self.failed.set(true); - } - return Err(Error::IdentityMismatch); - } - self.counters.read_bytes = - self.counters.read_bytes.saturating_add(bytes.len() as u64); - self.counters.upload_bytes = self - .counters - .upload_bytes - .saturating_add(charged_bytes as u64); - EncodedWeight::Dual(format, owner) - } else { - EncodedWeight::Raw(self.upload(&bytes)?) - }; - let main_bytes = self - .main_bytes - .checked_add(charged_bytes) - .ok_or(Error::Overflow)?; - if let Err(primary) = self.commit_lru_updates(update, 1) { - if weight.close().is_err() { - self.failed.set(true); - } - return Err(primary); - } - self.main_bytes = main_bytes; - self.main.insert( - key, - Entry { - weight, - charged_bytes, - age: self.age, - }, - ); - } - self.note_permanent_lookup(key, hit); - let entry = self.main.get_mut(&key).ok_or(Error::IdentityMismatch)?; - entry.age = self.age; - Ok(match &entry.weight { - EncodedWeight::Raw(buffer) => CachedMoeMatrix::Raw(buffer), - EncodedWeight::Dual(format, owner) => CachedMoeMatrix::Dual(*format, owner), - }) - } - pub(super) fn main_entry( - &mut self, - key: MoeWeightDescriptor, - read: impl FnOnce() -> Result>, - ) -> Result> { - if self.failed.get() { - return Err(Error::CudaExecution); - } - let hit = self.main.contains_key(&key); - if self.is_pinned(key) && !hit { - return Err(Error::IdentityMismatch); - } - self.note_profile_request(key, hit); - self.age = self.age.checked_add(1).ok_or(Error::Overflow)?; - if hit { - let update = self.prepare_lru_updates(&[(key, self.age)])?; - self.commit_lru_updates(update, 1)?; - self.counters.hits = self.counters.hits.saturating_add(1); - } else { - self.counters.misses = self.counters.misses.saturating_add(1); - let dual = self.weight_layout(key)?; - let charged_bytes = dual.map_or(key.bytes, |(_, bytes)| bytes); - self.room(charged_bytes)?; - self.reserve_main(1)?; - let update = self.prepare_lru_updates(&[(key, self.age)])?; - let bytes = read()?; - if bytes.len() != key.bytes { - return Err(Error::InvalidDimension); - } - let weight = if let Some((format, expected)) = dual { - let owner = match self.context.mmq_weights(format, &bytes) { - Ok(owner) => owner, - Err(error) => { - if self.context.is_poisoned() { - self.failed.set(true); - } - return Err(driver_error(error)); - } - }; - if owner.allocated_bytes() != expected { - let cleanup = owner.close(); - if cleanup.is_err() { - self.failed.set(true); - } - return Err(Error::IdentityMismatch); - } - self.counters.read_bytes = - self.counters.read_bytes.saturating_add(bytes.len() as u64); - self.counters.upload_bytes = self - .counters - .upload_bytes - .saturating_add(charged_bytes as u64); - EncodedWeight::Dual(format, owner) - } else { - EncodedWeight::Raw(self.upload(&bytes)?) - }; - let main_bytes = self - .main_bytes - .checked_add(charged_bytes) - .ok_or(Error::Overflow)?; - if let Err(primary) = self.commit_lru_updates(update, 1) { - if weight.close().is_err() { - self.failed.set(true); - } - return Err(primary); - } - self.main_bytes = main_bytes; - self.main.insert( - key, - Entry { - weight, - charged_bytes, - age: self.age, - }, - ); - } - self.note_permanent_lookup(key, hit); - let entry = self.main.get_mut(&key).ok_or(Error::IdentityMismatch)?; - entry.age = self.age; - Ok(match &entry.weight { - EncodedWeight::Raw(buffer) => CachedMoeMatrix::Raw(buffer), - EncodedWeight::Dual(format, owner) => CachedMoeMatrix::Dual(*format, owner), - }) - } - /// Selected scoped cold GU only. The genuine final source block transfers - /// its storage at the original role point; hits keep the original policy. - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(super) fn main_entry_owned_gate_up( - &mut self, - key: MoeWeightDescriptor, - read: impl FnOnce() -> Result>, - ) -> Result> { - if self.failed.get() { - return Err(Error::CudaExecution); - } - let hit = self.main.contains_key(&key); - if self.is_pinned(key) && !hit { - return Err(Error::IdentityMismatch); - } - self.note_profile_request(key, hit); - self.age = self.age.checked_add(1).ok_or(Error::Overflow)?; - if hit { - let update = self.prepare_lru_updates(&[(key, self.age)])?; - self.commit_lru_updates(update, 1)?; - self.counters.hits = self.counters.hits.saturating_add(1); - } else { - self.counters.misses = self.counters.misses.saturating_add(1); - let dual = self.weight_layout(key)?; - let charged_bytes = dual.map_or(key.bytes, |(_, bytes)| bytes); - self.room(charged_bytes)?; - self.reserve_main(1)?; - let update = self.prepare_lru_updates(&[(key, self.age)])?; - let bytes = read()?; - if bytes.len() != key.bytes { - return Err(Error::InvalidDimension); - } - let raw_bytes = bytes.len(); - let weight = if let Some((format, expected)) = dual { - let kind = match key.raw_kind { - 18 => leleka_cuda_driver::RoutedFormat::IQ3_XXS, - 22 => leleka_cuda_driver::RoutedFormat::IQ2_S, - _ => return Err(Error::InvalidDimension), - }; - let shape = leleka_cuda_driver::ProjectionSpec { - kind: leleka_cuda_driver::ProjectionKind::Routed(kind), - rows: key.rows, - columns: key.columns, - }; - let owner = - match self - .context - .mmq_weights_owned_gate_up(shape, format, bytes.into_vec()) - { - Ok(owner) => owner, - Err(error) => { - if self.context.is_poisoned() { - self.failed.set(true); - } - return Err(driver_error(error)); - } - }; - if owner.allocated_bytes() != expected { - let cleanup = owner.close(); - if cleanup.is_err() { - self.failed.set(true); - } - return Err(Error::IdentityMismatch); - } - self.counters.read_bytes = - self.counters.read_bytes.saturating_add(raw_bytes as u64); - self.counters.upload_bytes = self - .counters - .upload_bytes - .saturating_add(charged_bytes as u64); - EncodedWeight::Dual(format, owner) - } else { - EncodedWeight::Raw(self.upload(&bytes)?) - }; - let main_bytes = self - .main_bytes - .checked_add(charged_bytes) - .ok_or(Error::Overflow)?; - if let Err(primary) = self.commit_lru_updates(update, 1) { - if weight.close().is_err() { - self.failed.set(true); - } - return Err(primary); - } - self.main_bytes = main_bytes; - self.main.insert( - key, - Entry { - weight, - charged_bytes, - age: self.age, - }, - ); - } - self.note_permanent_lookup(key, hit); - let entry = self.main.get_mut(&key).ok_or(Error::IdentityMismatch)?; - entry.age = self.age; - Ok(match &entry.weight { - EncodedWeight::Raw(buffer) => CachedMoeMatrix::Raw(buffer), - EncodedWeight::Dual(format, owner) => CachedMoeMatrix::Dual(*format, owner), - }) - } - /// Fill through the original cache policy, then retain actual immutable - /// cache/weight/failure-cell loans for the complete closed consumer. - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in super::super) fn with_matrix_routed_source<'source, 'group, T>( - &mut self, - binding: &ModelBinding, - source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'source, 'group>, - member: usize, - role: MoeMatrixRole, - consume: impl FnOnce( - CachedMoeMatrix<'_, 'ctx>, - &RoutedSourceHealth<'_, 'ctx>, - &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'source, 'group>, - ) -> Result, - ) -> Result { - self.validate(binding, self.context)?; - if !self.uses_direct_native_down_packets() { - return Err(Error::IdentityMismatch); - } - source.validate_binding(binding).map_err(binding_error)?; - let key = source.descriptor(member, role).map_err(binding_error)?; - if let Some(adaptive) = &self.adaptive - && key.expert.is_some() - { - let matrix = adaptive - .matrix(binding, key)? - .ok_or(Error::Unsupported(super::super::contract::Stage::MoeExpert))?; - let health = RoutedSourceHealth { - binding: &self.binding, - context: self.context, - failed: &self.failed, - }; - return consume(matrix, &health, source); - } - // The temporary returned view ends here. No cache fill/eviction occurs - // while the consumer below holds actual cache fields immutably. - let read = || { - Ok(source - .block(member, role) - .map_err(binding_error)? - .into_bytes()) - }; - let _ = - if key.expert.is_some() && matches!(key.role, 0 | 1) && matches!(key.raw_kind, 18 | 22) - { - self.main_entry_owned_gate_up(key, read)? - } else { - self.main_entry(key, read)? - }; - self.validate(binding, self.context)?; - let entry = self.main.get(&key).ok_or(Error::IdentityMismatch)?; - let matrix = match &entry.weight { - EncodedWeight::Raw(buffer) => CachedMoeMatrix::Raw(buffer), - EncodedWeight::Dual(format, owner) => CachedMoeMatrix::Dual(*format, owner), - }; - let health = RoutedSourceHealth { - binding: &self.binding, - context: self.context, - failed: &self.failed, - }; - consume(matrix, &health, source) - } - pub(in super::super) fn matrix( - &mut self, - binding: &ModelBinding, - weights: &MoeExpertWeights, - selection: MoeExpertSelection, - role: MoeMatrixRole, - ) -> Result> { - self.validate(binding, self.context)?; - let key = binding - .moe_weight_descriptor(weights, selection, role) - .map_err(binding_error)?; - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if self.adaptive.is_some() && key.expert.is_some() { - return self - .adaptive - .as_ref() - .ok_or(Error::IdentityMismatch)? - .matrix(binding, key)? - .ok_or(Error::Unsupported(super::super::contract::Stage::MoeExpert)); - } - self.main_entry(key, || { - let block = binding - .moe_expert_block(weights, selection, role, 0, key.rows) - .map_err(binding_error)?; - Ok(block.into_bytes()) - }) - } - pub(crate) fn shared_scalar( - &mut self, - binding: &ModelBinding, - weights: &MoeExpertWeights, - ) -> Result<&DeviceBuffer<'ctx>> { - self.validate(binding, self.context)?; - let key = binding - .moe_shared_scalar_descriptor(weights) - .map_err(binding_error)?; - match self.main_entry(key, || { - binding.moe_shared_scalar(weights).map_err(binding_error) - })? { - CachedMoeMatrix::Raw(buffer) => Ok(buffer), - CachedMoeMatrix::Dual(_, _) => Err(Error::IdentityMismatch), - } - } - /// Only the explicit new profile factory calls this before PrefixPlan/preload. - /// Eligibility uses immutable already-loaded metadata, not a hoisted source check. - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(super) fn admit_mtp_input_workspace(&mut self, binding: &ModelBinding) -> Result<()> { - self.validate(binding, self.context)?; - if !self.main.is_empty() || self.main_bytes != 0 || self.mtp_input_workspace.is_some() { - return Err(Error::IdentityMismatch); - } - let supported = [MtpRole::FcEmbedding, MtpRole::FcHidden] - .into_iter() - .all(|role| { - self.dense.iter().any(|entry| { - entry.role == role - && (entry.kind, entry.rows, entry.columns) == (MtpKind::Q8_0, 2560, 2560) - }) - }) - && [(MtpRole::EmbeddingNorm, 2560), (MtpRole::HiddenNorm, 10240)] - .into_iter() - .all(|(role, words)| { - self.dense.iter().any(|entry| { - entry.role == role - && entry.kind == MtpKind::F32 - && entry - .f32 - .as_ref() - .is_some_and(|values| values.len() == words) - }) - }); - if !supported { - return Ok(()); - } - // Actual Context charge is counted once. Both admission predicates leave - // the independent working reserve; metadata plan sees the eager allocation. - self.reserve_mmq_transient(binding, self.context, MTP_INPUT_WORKSPACE_BYTES)?; - self.mtp_input_workspace = Some(Rc::new(MtpInputWorkspaceOwner::new( - self.binding.clone(), - self.context, - )?)); - self.room(0)?; - self.validate(binding, self.context) - } - #[cfg(test)] - pub(in super::super) fn note_mtp_input_completed(&self) { - self.mtp_input_completions - .set(self.mtp_input_completions.get().saturating_add(1)); - } - #[cfg(test)] - pub(crate) fn test_mtp_input_completions(&self) -> u64 { - self.mtp_input_completions.get() - } - pub(in super::super) fn has_mtp_input_workspace(&self) -> bool { - self.mtp_input_workspace.is_some() - } - pub(in super::super) fn mtp_input_workspace_owner( - &self, - binding: &ModelBinding, - context: &Context<'_>, - ) -> Result>> { - self.validate(binding, context)?; - let owner = self - .mtp_input_workspace - .as_ref() - .ok_or(Error::IdentityMismatch)?; - if !owner.binding.matches(&binding.identity()) || !std::ptr::eq(owner.context, context) { - return Err(Error::IdentityMismatch); - } - Ok(Rc::clone(owner)) - } - pub(crate) fn mtp_bank( - &self, - binding: &ModelBinding, - context: &Context<'_>, - ) -> Result<&DeviceBuffer<'ctx>> { - self.validate(binding, context)?; - binding - .mtp_weights() - .map_err(binding_error)? - .validate_sources(binding) - .map_err(binding_error)?; - self.mtp_hits.set(self.mtp_hits.get().saturating_add(1)); - self.bank.as_deref().ok_or(Error::IdentityMismatch) - } - pub(crate) fn mtp_matrix( - &self, - binding: &ModelBinding, - context: &Context<'_>, - role: MtpRole, - ) -> Result<(MtpKind, usize, usize, &DeviceBuffer<'ctx>)> { - self.validate(binding, context)?; - let pack = binding.mtp_weights().map_err(binding_error)?; - pack.validate_sources(binding).map_err(binding_error)?; - let entry = self - .dense - .iter() - .find(|e| e.role == role) - .ok_or(Error::IdentityMismatch)?; - if pack.dense_shape(binding, role).map_err(binding_error)? - != (entry.kind, entry.rows, entry.columns) - { - return Err(Error::IdentityMismatch); - } - self.mtp_hits.set(self.mtp_hits.get().saturating_add(1)); - Ok((entry.kind, entry.rows, entry.columns, &entry.buffer)) - } - pub(crate) fn mtp_f32(&self, binding: &ModelBinding, role: MtpRole) -> Result<&[f32]> { - self.mtp_matrix(binding, self.context, role)?; - self.dense - .iter() - .find(|e| e.role == role) - .and_then(|e| e.f32.as_deref()) - .ok_or(Error::InvalidDimension) - } - pub(crate) fn counters(&self) -> WeightCacheCounters { - let mut counters = self.counters; - counters.hits = counters.hits.saturating_add(self.mtp_hits.get()); - counters - } - pub(crate) fn close(mut self) -> Result<()> { - let mut failed = self.failed.get(); - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if let Some(owner) = self.original_copy_schedule.take() { - failed |= owner.close().is_err(); - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if let Some(owner) = self.original_prompt_device.take() { - failed |= owner.close().is_err(); - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - { - self.original_finite_experts = [0; 48 * 512 / 64]; - self.original_span_cache = (0, Vec::new()); - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if let Some(bank) = self.original_expert_bank.take() { - failed |= match Rc::try_unwrap(bank) { - Ok(bank) => bank.close().is_err(), - Err(bank) => { drop(bank); true } - }; - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if let Some(owner) = self.ephemeral_routed.take() { - failed |= match Rc::try_unwrap(owner) { - Ok(owner) => owner.into_inner().close().is_err(), - Err(owner) => { - drop(owner); - true - } - }; - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if let Some(owner) = self.routed_outputs.take() { - failed |= match Rc::try_unwrap(owner) { - Ok(owner) => owner.close().is_err(), - Err(owner) => { - drop(owner); - true - } - }; - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if let Some(adaptive) = self.adaptive.take() { - failed |= adaptive.close().is_err(); - } - if let Some(owner) = self.mtp_input_workspace.take() { - failed |= match Rc::try_unwrap(owner) { - Ok(owner) => owner.close().is_err(), - Err(owner) => { - drop(owner); - true - } - }; - } - if let Some(owner) = self.routed_resident.take() { - failed |= match Rc::try_unwrap(owner) { - Ok(owner) => owner.close().is_err(), - Err(owner) => { - drop(owner); - true - } - }; - } - if let Some(owner) = self.routed_workspace.take() { - failed |= match Rc::try_unwrap(owner) { - Ok(owner) => owner.close().is_err(), - Err(owner) => { - drop(owner); - true - } - }; - } - if let Some(owner) = self.routed_finite.take() { - failed |= match Rc::try_unwrap(owner) { - Ok(owner) => owner.close().is_err(), - Err(owner) => { - drop(owner); - true - } - }; - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if let Some(owner) = self.native_prefill.take() { - failed |= owner.into_inner().close().is_err(); - } - if let Some(workspace) = self.target_shared.take() { - failed |= workspace.close().is_err(); - } - if let Some(workspace) = self.mtp_experts.get_mut().take() { - failed |= workspace.close().is_err(); - } - if let Some(ring) = self.mtp_kv.get_mut().take() { - failed |= ring.close().is_err(); - } - if let Some(workspace) = self.mmq_workspace.take() { - failed |= workspace.close().is_err(); - } - // No more lookup/publication is possible during consuming teardown. - // Drop metadata before draining every actual weight owner. - drop(self.lru.take()); - for (_, entry) in self.main.drain() { - failed |= entry.weight.close().is_err(); - } - for entry in self.dense.drain(..) { - // Captured graphs retain genuine immutable allocations. Releasing - // this cache's reference cannot free a graph's live weight bank. - if let Ok(buffer)=Rc::try_unwrap(entry.buffer){failed|=buffer.release().is_err();} - } - if let Some(bank) = self.bank.take() { - if let Ok(bank)=Rc::try_unwrap(bank){failed|=bank.release().is_err();} - } - if failed { - Err(Error::CudaExecution) - } else { - Ok(()) - } - } -} +#[path = "impl_moeweightcache/impl_moeweightcache_2.rs"] +mod impl_moeweightcache_2; +#[path = "impl_moeweightcache/impl_moeweightcache_2_2.rs"] +mod impl_moeweightcache_2_2; +#[path = "impl_moeweightcache/impl_moeweightcache_3.rs"] +mod impl_moeweightcache_3; +#[path = "impl_moeweightcache/impl_moeweightcache_4.rs"] +mod impl_moeweightcache_4; +#[path = "impl_moeweightcache/impl_moeweightcache_5.rs"] +mod impl_moeweightcache_5; +#[path = "impl_moeweightcache/impl_moeweightcache_6.rs"] +mod impl_moeweightcache_6; +#[path = "impl_moeweightcache/impl_moeweightcache_7.rs"] +mod impl_moeweightcache_7; +#[path = "impl_moeweightcache/impl_moeweightcache_8.rs"] +mod impl_moeweightcache_8; +#[path = "impl_moeweightcache/impl_moeweightcache_9.rs"] +mod impl_moeweightcache_9; +#[path = "impl_moeweightcache/impl_moeweightcache_10.rs"] +mod impl_moeweightcache_10; diff --git a/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_10.rs b/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_10.rs new file mode 100644 index 00000000..a3489c95 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_10.rs @@ -0,0 +1,126 @@ +//! Moved out of the parent module by STRA-338: impl MoeWeightCache (10). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> MoeWeightCache<'ctx> { + pub(crate) fn close(mut self) -> Result<()> { + let mut failed = self.failed.get(); + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(owner) = self.original_copy_schedule.take() { + failed |= owner.close().is_err(); + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(owner) = self.original_prompt_device.take() { + failed |= owner.close().is_err(); + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + { + self.original_finite_experts = [0; 48 * 512 / 64]; + self.original_span_cache = (0, Vec::new()); + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(bank) = self.original_expert_bank.take() { + failed |= match Rc::try_unwrap(bank) { + Ok(bank) => bank.close().is_err(), + Err(bank) => { drop(bank); true } + }; + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(owner) = self.ephemeral_routed.take() { + failed |= match Rc::try_unwrap(owner) { + Ok(owner) => owner.into_inner().close().is_err(), + Err(owner) => { + drop(owner); + true + } + }; + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(owner) = self.routed_outputs.take() { + failed |= match Rc::try_unwrap(owner) { + Ok(owner) => owner.close().is_err(), + Err(owner) => { + drop(owner); + true + } + }; + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(adaptive) = self.adaptive.take() { + failed |= adaptive.close().is_err(); + } + if let Some(owner) = self.mtp_input_workspace.take() { + failed |= match Rc::try_unwrap(owner) { + Ok(owner) => owner.close().is_err(), + Err(owner) => { + drop(owner); + true + } + }; + } + if let Some(owner) = self.routed_resident.take() { + failed |= match Rc::try_unwrap(owner) { + Ok(owner) => owner.close().is_err(), + Err(owner) => { + drop(owner); + true + } + }; + } + if let Some(owner) = self.routed_workspace.take() { + failed |= match Rc::try_unwrap(owner) { + Ok(owner) => owner.close().is_err(), + Err(owner) => { + drop(owner); + true + } + }; + } + if let Some(owner) = self.routed_finite.take() { + failed |= match Rc::try_unwrap(owner) { + Ok(owner) => owner.close().is_err(), + Err(owner) => { + drop(owner); + true + } + }; + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(owner) = self.native_prefill.take() { + failed |= owner.into_inner().close().is_err(); + } + if let Some(workspace) = self.target_shared.take() { + failed |= workspace.close().is_err(); + } + if let Some(workspace) = self.mtp_experts.get_mut().take() { + failed |= workspace.close().is_err(); + } + if let Some(ring) = self.mtp_kv.get_mut().take() { + failed |= ring.close().is_err(); + } + if let Some(workspace) = self.mmq_workspace.take() { + failed |= workspace.close().is_err(); + } + // No more lookup/publication is possible during consuming teardown. + // Drop metadata before draining every actual weight owner. + drop(self.lru.take()); + for (_, entry) in self.main.drain() { + failed |= entry.weight.close().is_err(); + } + for entry in self.dense.drain(..) { + // Captured graphs retain genuine immutable allocations. Releasing + // this cache's reference cannot free a graph's live weight bank. + if let Ok(buffer)=Rc::try_unwrap(entry.buffer){failed|=buffer.release().is_err();} + } + if let Some(bank) = self.bank.take() { + if let Ok(bank)=Rc::try_unwrap(bank){failed|=bank.release().is_err();} + } + if failed { + Err(Error::CudaExecution) + } else { + Ok(()) + } + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_2.rs b/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_2.rs new file mode 100644 index 00000000..236c07c1 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_2.rs @@ -0,0 +1,252 @@ +//! Moved out of the parent module by STRA-338: impl MoeWeightCache. + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> MoeWeightCache<'ctx> { + /// Source-only experimental candidate: preserve a reusable 1 GiB spill floor. + /// Root must bind this policy in fixture/serving identity before selection. + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(crate) fn new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile_mtp_input_spill_floor( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + bytes: &[u8], + ) -> Result { + Self::profile_with_mtp_input_and_spill_floor(binding, context, bytes, true, 1usize << 30) + } + pub(in super::super::super) fn note_transport_failure(&self) { + self.failed.set(true); + } + pub(crate) fn new(binding: &ModelBinding, context: &'ctx Context<'ctx>) -> Result { + Self::new_with_mtp_experts(binding, context, true) + } + /// Bytes `new` charges against the budget for the pinned MTP pack: the dense roles always, the 675 MiB expert bank only when it is uploaded. + pub(in crate::qwen_forward) const fn mtp_pack_charge(mtp_experts: bool) -> usize { + (if mtp_experts { MTP_PACK_EXPERT_BANK_BYTES } else { 0 }) + MTP_DENSE_LIMIT + } + /// `mtp_experts == false` leaves the pinned pack's EXPERT BANK (707,788,800 bytes, the draft layer's routed experts) out of VRAM. The serve stack + /// passes false when it loads the draft layer from an RT directory (`--mtp-rt-dir`, the product path): that path streams its own copy of the + /// experts (`original_mtp_rt_bank`) and never reads this one, so keeping both held 675 MiB of VRAM (and the host copy during the upload) for nothing. + /// The pack's dense roles are still uploaded: the draft-KV recording of the prompt path reads them through `mtp_matrix`. + pub(crate) fn new_with_mtp_experts(binding: &ModelBinding, context: &'ctx Context<'ctx>, mtp_experts: bool) -> Result { + let mut cache = Self { + context, + binding: binding.identity(), + main: HashMap::new(), + main_bytes: 0, + lru: None, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pinned: None, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + learned_main: false, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + learned_metadata_bytes: 0, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + adaptive: None, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + cpu_miss: None, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + routed_outputs: None, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + ephemeral_routed: None, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + adaptive_shared: None, + age: 0, + failed: Cell::new(false), + bank: None, + dense: Vec::new(), + counters: WeightCacheCounters::default(), + mtp_hits: Cell::new(0), + mmq_workspace: None, + mmq_policy: MmqRoutingPolicy::Existing, + original_prompt_mmq: false, + mmq_owner: Rc::new(()), + mtp_kv: RefCell::new(None), + mtp_experts: RefCell::new(None), + target_shared: None, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + native_prefill: None, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + original_prompt_device: None, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + original_expert_bank: None, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + original_copy_schedule: None, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + original_prompt_metadata_bytes: 0, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + original_finite_experts: [0; 48 * 512 / 64], + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + original_span_cache: (0, Vec::new()), + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + prompt_routing: None, + routed_finite: None, + routed_workspace: None, + routed_resident: None, + mtp_input_workspace: None, + #[cfg(test)] + mtp_input_completions: Cell::new(0), + #[cfg(test)] + shared_tail_witness: Cell::new(0), + #[cfg(test)] + lru_witness: Cell::new((0, 0, 0)), + #[cfg(test)] + mmq_dispatch_witness: Cell::new((0, 0, 0)), + #[cfg(test)] + mmq_triplet_witness: Cell::new((0, 0, 0)), + }; + cache.room(0)?; + if binding.has_mtp() { + let pack = binding.mtp_weights().map_err(binding_error)?; + cache.room(Self::mtp_pack_charge(mtp_experts))?; + if mtp_experts { + let data = pack.expert_bank(binding).map_err(binding_error)?; + let bank = cache.upload(&data)?; + cache.bank = Some(Rc::new(bank)); + drop(data); + cache.counters.misses = cache.counters.misses.saturating_add(1); + } + let mut total = 0usize; + for role in pack.dense_roles(binding).map_err(binding_error)? { + let rows = pack.dense_complete(binding, role).map_err(binding_error)?; + total = total + .checked_add(rows.bytes().len()) + .ok_or(Error::Overflow)?; + if total > MTP_DENSE_LIMIT { + return Err(Error::InvalidDimension); + } + let f32 = if rows.kind() == MtpKind::F32 { + let mut values = Vec::new(); + values + .try_reserve_exact(rows.bytes().len() / 4) + .map_err(|_| Error::InputAllocation)?; + for word in rows.bytes().as_chunks::<4>().0 { + values.push(f32::from_le_bytes(*word)); + } + Some(values.into_boxed_slice()) + } else { + None + }; + let buffer = cache.upload(rows.bytes())?; + cache + .dense + .try_reserve(1) + .map_err(|_| Error::InputAllocation)?; + cache.counters.misses = cache.counters.misses.saturating_add(1); + cache.dense.push(Dense { + role, + kind: rows.kind(), + rows: rows.rows(), + columns: rows.columns(), + buffer:Rc::new(buffer), + f32, + }); + } + } + Ok(cache) + } + /// Explicit private experiment only. Allocate/charge the persistent + /// workspace before MTP-bank upload or any lazy main-LRU fill. Normal new() + /// creates no workspace and keeps the unchanged native T1 path. + pub(crate) fn new_mmq(binding: &ModelBinding, context: &'ctx Context<'ctx>) -> Result { + let workspace = context.mmq_workspace().map_err(driver_error)?; + Self::assemble_mmq(binding, context, workspace) + } + /// Explicit private native-certified activation experiment. The immutable + /// workspace policy applies to GU and Down; normal new()/new_mmq() retain + /// their existing native/original-D4 policy, respectively. + pub(crate) fn new_native_mmq( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + ) -> Result { + let workspace = context.native_mmq_workspace().map_err(driver_error)?; + Self::assemble_mmq(binding, context, workspace) + } + /// Private source-only candidate: raw integer MMA is admitted only for + /// legal routed GU18. All persistent scratch (including 13,107,200 bytes + /// of integer dots) is charged before MTP upload and main-cache growth. + pub(crate) fn new_native_integer_iq3_mmq( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + ) -> Result { + Self::new_native_integer_iq3_mmq_with_prompt(binding, context, false) + } + pub(in super::super) fn new_native_integer_iq3_mmq_with_prompt( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + original_prompt: bool, + ) -> Result { + let workspace = if original_prompt { + context.native_integer_iq3_mmq_original_formats_workspace() + } else { + context.native_integer_iq3_mmq_workspace() + }.map_err(driver_error)?; + let mut cache = Self::assemble_mmq(binding, context, workspace)?; + cache.mmq_policy = MmqRoutingPolicy::NativeIntegerIq3; + cache.original_prompt_mmq = original_prompt; + if binding.has_mtp() { + let result = (|| { + let charge = super::super::super::mtp_experts::fixed_workspace::ALLOCATED_BYTES; + cache.reserve_mmq_transient( + binding, + context, + charge.checked_add(512 * 1024).ok_or(Error::Overflow)?, + )?; + let fixed = super::super::super::mtp_experts::fixed_workspace::MtpExpertWorkspace::new( + binding.identity(), + Rc::clone(&cache.mmq_owner), + context, + )?; + *cache.mtp_experts.get_mut() = Some(fixed); + Ok(()) + })(); + if let Err(primary) = result { + let _ = cache.close(); + return Err(primary); + } + } + Ok(cache) + } + /// Existing explicit NativeDown outer256 retained-GR mode only. All old + /// constructors keep the original full-window MTP transport. + pub(crate) fn new_native_integer_iq3_mmq_retained_mtp_kv( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + ) -> Result { + Self::new_native_integer_iq3_mmq_retained_mtp_kv_with_prompt(binding, context, false) + } + pub(in super::super) fn new_native_integer_iq3_mmq_retained_mtp_kv_with_prompt( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + original_prompt: bool, + ) -> Result { + if !binding.has_mtp() { + return Err(Error::IdentityMismatch); + } + if !room_fits( + context.allocated_bytes(), + context.budget_bytes(), + 0, + 128 * 1024 * 1024, + ) { + return Err(Error::InputAllocation); + } + let ring = context.mtp_dense_kv_ring().map_err(driver_error)?; + let cache = match Self::new_native_integer_iq3_mmq_with_prompt(binding, context, original_prompt) { + Ok(cache) => cache, + Err(primary) => { + let _ = ring.close(); + return Err(primary); + } + }; + let resident = MtpKvResident::new( + binding.identity(), + context, + Rc::clone(&cache.mmq_owner), + ring, + )?; + *cache.mtp_kv.borrow_mut() = Some(resident); + Ok(cache) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_2_2.rs b/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_2_2.rs new file mode 100644 index 00000000..5ad06de5 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_2_2.rs @@ -0,0 +1,244 @@ +//! Moved out of the parent module by STRA-338: impl MoeWeightCache (2). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> MoeWeightCache<'ctx> { + /// Explicit candidate-only target tail. The fixed owner is admitted while + /// main LRU is still empty; all default/Native/draft factories stay exact. + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(crate) fn new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + ) -> Result { + Self::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_with_prompt(binding, context, false) + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in super::super) fn new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_with_prompt( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + original_prompt: bool, + ) -> Result { + let mut cache = Self::new_native_integer_iq3_mmq_retained_mtp_kv_with_prompt(binding, context, original_prompt)?; + let operation = (|| { + cache.reserve_mmq_transient( + binding, + context, + super::super::super::shared_expert_workspace::ALLOCATED_BYTES, + )?; + cache.reserve_mmq_transient( + binding, + context, + super::super::super::moe_prefill_batch::MOE_PREFILL_PERSISTENT_BYTES, + )?; + let native = super::super::super::moe_prefill_batch::MoePrefillResources::new( + context, + super::super::super::moe_prefill_batch::MoeBf16Profile::HighOnly, + )?; + if native.allocated_bytes() != super::super::super::moe_prefill_batch::MOE_PREFILL_PERSISTENT_BYTES { + let _ = native.close(); + return Err(Error::InvalidDimension); + } + cache.native_prefill = Some(RefCell::new(native)); + cache.target_shared = Some(super::super::super::shared_expert_workspace::TargetSharedWorkspace::new( + binding.identity(), + Rc::clone(&cache.mmq_owner), + context, + )?); + cache.validate(binding, context) + })(); + if let Err(primary) = operation { + let _ = cache.close(); + return Err(primary); + } + Ok(cache) + } + /// Only this private changed-model candidate creates bounded host index + /// metadata. Every prior constructor retains its original unindexed policy. + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(crate) fn new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_lru( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + ) -> Result { + Self::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_lru_with_prompt(binding, context, false) + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in super::super) fn new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_lru_with_prompt( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + original_prompt: bool, + ) -> Result { + let index = LruIndex::new()?; + let mut cache = + Self::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_with_prompt(binding, context, original_prompt)?; + if !cache.main.is_empty() || cache.main_bytes != 0 { + let _ = cache.close(); + return Err(Error::IdentityMismatch); + } + let operation = (|| { + // Fixed status and helper module precede indexed/pinned lazy weights. + // The existing physical and typed 128 MiB reserve remains separate. + cache.reserve_mmq_transient(binding, context, 4)?; + cache.routed_finite = Some(Rc::new(RoutedFiniteOwner::new(context)?)); + // Actual table/DownQ8/status capacity is separate from the reserve. + // Construct and observe module residency while main weights are empty. + cache.reserve_mmq_transient(binding, context, 46_596)?; + cache.routed_workspace = Some(Rc::new(RoutedWorkspaceOwner::new(context)?)); + cache.room(0)?; + cache.validate(binding, context) + })(); + if let Err(primary) = operation { + let _ = cache.close(); + return Err(primary); + } + cache.lru = Some(index); + Ok(cache) + } + #[cfg(test)] + pub(crate) fn test_lru_witness(&self) -> (u64, u64, u64) { + self.lru_witness.get() + } + #[cfg(test)] + pub(crate) fn test_lru_metadata_bytes(&self) -> Result { + self.lru + .as_ref() + .ok_or(Error::IdentityMismatch)? + .metadata_bytes() + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(crate) fn profile_preload_upload_bytes(&self) -> u64 { + self.pinned + .as_ref() + .map_or(0, |pool| pool.preload_upload_bytes) + } + pub(in super::super::super) fn uses_direct_native_down_packets(&self) -> bool { + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + return (self.pinned.is_some() || self.adaptive.is_some()) + && self.requires_iq3_mmq_admission(); + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] + false + } + pub(in super::super::super) fn routed_finite_owner( + &self, + binding: &ModelBinding, + context: &Context<'_>, + ) -> Result>> { + self.validate(binding, context)?; + if !self.uses_direct_native_down_packets() { + return Err(Error::IdentityMismatch); + } + self.routed_finite + .as_ref() + .map(Rc::clone) + .ok_or(Error::IdentityMismatch) + } + pub(in super::super::super) fn routed_workspace_owner( + &self, + binding: &ModelBinding, + context: &Context<'_>, + ) -> Result>> { + self.validate(binding, context)?; + if !self.uses_direct_native_down_packets() { + return Err(Error::IdentityMismatch); + } + self.routed_workspace + .as_ref() + .map(Rc::clone) + .ok_or(Error::IdentityMismatch) + } + pub(in super::super) fn is_pinned(&self, key: MoeWeightDescriptor) -> bool { + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if self + .adaptive_shared + .as_ref() + .is_some_and(|pool| pool.contains(key)) + { + return true; + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + return self.pinned.as_ref().is_some_and(|pool| { + pool.shared + .as_ref() + .is_some_and(|shared| shared.contains(key)) + || (!self.learned_main && pool.plan.contains(key.layer, key.expert, key.role)) + }); + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] + { + let _ = key; + false + } + } + pub(in super::super) fn spill_len(&self) -> Result { + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(pool) = &self.pinned { + return self + .main + .len() + .checked_sub(if self.learned_main { + 0 + } else { + pool.loaded_matrices + }) + .and_then(|n| { + n.checked_sub( + pool.shared + .as_ref() + .map_or(0, |shared| shared.descriptor_count()), + ) + }) + .ok_or(Error::IdentityMismatch); + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(shared) = &self.adaptive_shared { + return self + .main + .len() + .checked_sub(shared.descriptor_count()) + .ok_or(Error::IdentityMismatch); + } + Ok(self.main.len()) + } + pub(in super::super) fn note_profile_request(&mut self, key: MoeWeightDescriptor, hit: bool) { + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(pool) = &mut self.pinned { + let counter = if (!self.learned_main + && pool.plan.contains(key.layer, key.expert, key.role)) + || pool + .shared + .as_ref() + .is_some_and(|shared| shared.contains(key)) + { + &mut pool.pinned_hits + } else if hit { + &mut pool.spill_hits + } else { + &mut pool.spill_misses + }; + *counter = counter.saturating_add(1); + } + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] + { + let _ = (key, hit); + } + } + pub(in super::super) fn reserve_main(&mut self, additional: usize) -> Result<()> { + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(pool) = &self.pinned { + if self + .main + .len() + .checked_add(additional) + .is_none_or(|n| n > pool.main_slot_limit || n > self.main.capacity()) + { + return Err(Error::InputAllocation); + } + // Current growth-left already covers this batch: do not reserve or + // rehash pinned-policy metadata after deletion/tombstone churn. + return Ok(()); + } + self.main + .try_reserve(additional) + .map_err(|_| Error::InputAllocation) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_3.rs b/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_3.rs new file mode 100644 index 00000000..1691327a --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_3.rs @@ -0,0 +1,228 @@ +//! Moved out of the parent module by STRA-338: impl MoeWeightCache (3). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> MoeWeightCache<'ctx> { + pub(in super::super) fn prepare_lru_updates( + &self, + updates: &[(MoeWeightDescriptor, u64)], + ) -> Result> { + let Some(index) = &self.lru else { + return Ok(None); + }; + if index.len() != self.spill_len()? { + return Err(Error::IdentityMismatch); + } + if !(1..=3).contains(&updates.len()) { + return Err(Error::InvalidDimension); + } + let mut spill = [(updates[0].0, 0u64); 3]; + let mut count = 0; + for &(key, age) in updates { + if self.is_pinned(key) { + if !self.main.contains_key(&key) { + return Err(Error::IdentityMismatch); + } + continue; + } + spill[count] = (key, age); + count += 1; + if index.entry_age(key)? != self.main.get(&key).map(|entry| entry.age) { + return Err(Error::IdentityMismatch); + } + } + if count == 0 { + return Ok(None); + } + index.prepare_updates(&spill[..count]).map(Some) + } + pub(in super::super) fn pinned_updates_allowed(&self) -> bool { + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + return self.pinned.is_some() || self.adaptive_shared.is_some(); + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] + false + } + pub(in super::super) fn commit_lru_updates(&mut self, updates: Option, count: u64) -> Result<()> { + let pinned_updates_allowed = self.pinned_updates_allowed(); + match (self.lru.as_mut(), updates) { + (None, None) => Ok(()), + (Some(_), None) if pinned_updates_allowed => Ok(()), + (Some(index), Some(updates)) => { + index.commit_updates(updates)?; + #[cfg(test)] + { + let (lookups, updates, removals) = self.lru_witness.get(); + self.lru_witness + .set((lookups, updates.saturating_add(count), removals)); + } + #[cfg(not(test))] + let _ = count; + Ok(()) + } + _ => Err(Error::IdentityMismatch), + } + } + pub(in super::super) fn eviction_key(&self, protected: &[MoeWeightDescriptor]) -> Result { + let key = if let Some(index) = &self.lru { + if index.len() != self.spill_len()? { + return Err(Error::IdentityMismatch); + } + let key = index.oldest(protected)?.ok_or(Error::InputAllocation)?; + if self.is_pinned(key) + || index.entry_age(key)? != self.main.get(&key).map(|entry| entry.age) + { + return Err(Error::IdentityMismatch); + } + #[cfg(test)] + { + let (lookups, updates, removals) = self.lru_witness.get(); + self.lru_witness + .set((lookups.saturating_add(1), updates, removals)); + } + key + } else { + oldest_weight( + self.main + .iter() + .filter(|(key, _)| !protected.contains(key) && !self.is_pinned(**key)) + .map(|(key, entry)| (*key, entry.age)), + ) + .ok_or(Error::InputAllocation)? + }; + Ok(key) + } + pub(in super::super) fn remove_lru_entry(&mut self, key: MoeWeightDescriptor) -> Result<()> { + if self.is_pinned(key) { + return Err(Error::IdentityMismatch); + } + let spill_len = self.spill_len()?; + if let Some(index) = &mut self.lru { + if index.len() != spill_len + || index.entry_age(key)? != self.main.get(&key).map(|entry| entry.age) + { + return Err(Error::IdentityMismatch); + } + index.remove(key)?; + #[cfg(test)] + { + let (lookups, updates, removals) = self.lru_witness.get(); + self.lru_witness + .set((lookups, updates, removals.saturating_add(1))); + } + } + Ok(()) + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in super::super::super) fn native_prefill_resources( + &self, + binding: &ModelBinding, + context: &Context<'_>, + ) -> Result>> { + self.validate(binding, context)?; + let owner = self + .native_prefill + .as_ref() + .ok_or(Error::IdentityMismatch)? + .try_borrow_mut() + .map_err(|_| Error::IdentityMismatch)?; + owner.validate_context(context)?; + Ok(owner) + } + /// Genuine binding-resolved whole immutable shared weights, held through + /// the closed native producer. Descriptors never authenticate arbitrary bytes. + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in super::super::super) fn with_native_shared_weights( + &mut self, + binding: &ModelBinding, + context: &Context<'_>, + layer: super::super::super::contract::LayerId, + transient: usize, + execute: impl FnOnce( + &'ctx Context<'ctx>, + super::super::super::moe_prefill_batch::SharedWeights<'_, 'ctx>, + &mut super::super::super::moe_prefill_batch::MoePrefillResources<'ctx>, + ) -> Result, + ) -> Result { + self.validate(binding, context)?; + let weights = binding + .moe_expert_weights(layer.get(), std::array::from_fn(|slot| slot as u32)) + .map_err(binding_error)?; + if !weights.matches(&binding.identity(), layer.get()) { + return Err(Error::IdentityMismatch); + } + let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down]; + let keys = [ + binding + .moe_weight_descriptor(&weights, MoeExpertSelection::Shared, roles[0]) + .map_err(binding_error)?, + binding + .moe_weight_descriptor(&weights, MoeExpertSelection::Shared, roles[1]) + .map_err(binding_error)?, + binding + .moe_weight_descriptor(&weights, MoeExpertSelection::Shared, roles[2]) + .map_err(binding_error)?, + binding + .moe_shared_scalar_descriptor(&weights) + .map_err(binding_error)?, + ]; + super::super::super::shared_expert_workspace::validate_descriptors(&keys)?; + if keys.iter().any(|key| key.layer != layer.get()) { + return Err(Error::IdentityMismatch); + } + for (index, key) in keys.iter().enumerate() { + let _ = self.main_entry_protected(*key, &keys, || { + if index == 3 { + binding.moe_shared_scalar(&weights).map_err(binding_error) + } else { + Ok(binding + .moe_expert_block( + &weights, + MoeExpertSelection::Shared, + roles[index], + 0, + key.rows, + ) + .map_err(binding_error)? + .into_bytes()) + } + })?; + } + // Filling these four weights may consume an earlier physical snapshot. + // Re-admit the real transient peak while protecting every lent owner. + self.room_protected(transient, &keys)?; + self.validate(binding, context)?; + let raw = |index: usize| -> Result<&DeviceBuffer<'ctx>> { + let entry = self.main.get(&keys[index]).ok_or(Error::IdentityMismatch)?; + if entry.charged_bytes != keys[index].bytes { + return Err(Error::IdentityMismatch); + } + match &entry.weight { + EncodedWeight::Raw(buffer) => Ok(buffer), + EncodedWeight::Dual(_, _) => Err(Error::IdentityMismatch), + } + }; + let buffers = [raw(0)?, raw(1)?, raw(2)?, raw(3)?]; + let mut owner = self.native_prefill_resources(binding, context)?; + let result = execute( + self.context, + super::super::super::moe_prefill_batch::SharedWeights { + keys: &keys, + buffers, + }, + &mut owner, + ); + if self.context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) { + self.failed.set(true); + } + result + } + pub(in super::super::super) fn has_target_shared_tail(&self) -> bool { + self.target_shared.is_some() + } + #[cfg(test)] + pub(crate) fn test_shared_tail_witness(&self) -> u64 { + self.shared_tail_witness.get() + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_4.rs b/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_4.rs new file mode 100644 index 00000000..d8618e3d --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_4.rs @@ -0,0 +1,254 @@ +//! Moved out of the parent module by STRA-338: impl MoeWeightCache (4). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> MoeWeightCache<'ctx> { + /// Source-descriptor admission precedes all fills. Requested entries cannot + /// evict one another; every actual weight remains immutably borrowed until + /// the closed driver's completion/readback has consumed the result. + #[allow(clippy::too_many_arguments)] + pub(in super::super::super) fn compose_target_shared_tail( + &mut self, + binding: &ModelBinding, + context: &Context<'_>, + weights: &MoeExpertWeights, + identity: super::super::super::contract::TokenLayer, + activation: &DeviceBuffer<'_>, + packed: &DeviceBuffer<'_>, + route: &[f32; 10], + ) -> Result> { + self.validate(binding, context)?; + if !weights.matches(&binding.identity(), identity.layer().get()) { + return Err(Error::IdentityMismatch); + } + let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down]; + let keys = [ + binding + .moe_weight_descriptor(weights, MoeExpertSelection::Shared, roles[0]) + .map_err(binding_error)?, + binding + .moe_weight_descriptor(weights, MoeExpertSelection::Shared, roles[1]) + .map_err(binding_error)?, + binding + .moe_weight_descriptor(weights, MoeExpertSelection::Shared, roles[2]) + .map_err(binding_error)?, + binding + .moe_shared_scalar_descriptor(weights) + .map_err(binding_error)?, + ]; + super::super::super::shared_expert_workspace::validate_descriptors(&keys)?; + for (index, key) in keys.iter().enumerate() { + let _ = self.main_entry_protected(*key, &keys, || { + if index == 3 { + binding.moe_shared_scalar(weights).map_err(binding_error) + } else { + Ok(binding + .moe_expert_block( + weights, + MoeExpertSelection::Shared, + roles[index], + 0, + key.rows, + ) + .map_err(binding_error)? + .into_bytes()) + } + })?; + } + self.validate(binding, context)?; + let entries = &self.main; + let raw = |index: usize| -> Result<&DeviceBuffer<'ctx>> { + let entry = entries.get(&keys[index]).ok_or(Error::IdentityMismatch)?; + if entry.charged_bytes != keys[index].bytes { + return Err(Error::IdentityMismatch); + } + match &entry.weight { + EncodedWeight::Raw(buffer) => Ok(buffer), + EncodedWeight::Dual(_, _) => Err(Error::IdentityMismatch), + } + }; + let buffers = [raw(0)?, raw(1)?, raw(2)?, raw(3)?]; + let result = self + .target_shared + .as_mut() + .ok_or(Error::IdentityMismatch)? + .compose( + binding, + &self.mmq_owner, + context, + identity, + &keys, + buffers, + activation, + packed, + route, + ); + if context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) { + self.failed.set(true); + } + if result.is_ok() { + #[cfg(test)] + self.shared_tail_witness + .set(self.shared_tail_witness.get().saturating_add(1)); + } + result + } + #[allow(clippy::too_many_arguments)] + pub(in super::super::super) fn compose_fixed_mtp_experts( + &self, + binding: &ModelBinding, + context: &Context<'_>, + frame: &super::super::super::mtp::MtpFrame, + session: &super::super::super::session::QwenSession<'_>, + bank: &DeviceBuffer<'_>, + shared: [&DeviceBuffer<'_>; 4], + mixed: &[f32], + ids: [u32; 10], + weights: [f32; 10], + failed: Rc>, + ) -> Result> { + self.validate(binding, context)?; + frame.validate(binding, session)?; + if !self.requires_iq3_mmq_admission() { + return Err(Error::IdentityMismatch); + } + // Admit only these actual cache-owned immutable draft weight owners. + // No second descriptor/source read or hit-counter mutation is needed. + if self + .bank + .as_ref() + .is_none_or(|actual| !std::ptr::eq(&**actual, bank)) + { + return Err(Error::IdentityMismatch); + } + for (role, buffer) in [ + MtpRole::SharedGate, + MtpRole::SharedUp, + MtpRole::SharedDown, + MtpRole::SharedScalar, + ] + .into_iter() + .zip(shared) + { + let actual = self + .dense + .iter() + .find(|entry| entry.role == role) + .ok_or(Error::IdentityMismatch)?; + if !std::ptr::eq(&*actual.buffer, buffer) { + return Err(Error::IdentityMismatch); + } + } + let mut slot = self + .mtp_experts + .try_borrow_mut() + .map_err(|_| Error::IdentityMismatch)?; + let result = slot.as_mut().ok_or(Error::IdentityMismatch)?.compose( + binding, + &self.mmq_owner, + context, + frame, + session, + bank, + shared, + mixed, + ids, + weights, + Rc::clone(&failed), + ); + if failed.get() || context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) { + self.failed.set(true); + } + result + } + pub(in super::super::super) fn has_mtp_kv_ring(&self) -> Result { + let slot = self + .mtp_kv + .try_borrow() + .map_err(|_| Error::IdentityMismatch)?; + Ok(slot.is_some()) + } + pub(in super::super::super) fn prepare_mtp_kv( + &self, + binding: &ModelBinding, + context: &Context<'_>, + next: &super::super::super::mtp::DenseKv, + frame: &super::super::super::mtp::MtpFrame, + ) -> Result<()> { + self.validate(binding, context)?; + let mut slot = self + .mtp_kv + .try_borrow_mut() + .map_err(|_| Error::IdentityMismatch)?; + let result = slot.as_mut().ok_or(Error::IdentityMismatch)?.prepare( + binding, + context, + &self.mmq_owner, + next, + frame, + ); + if context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) { + self.failed.set(true); + } + result + } + pub(in super::super::super) fn attend_mtp_kv( + &self, + binding: &ModelBinding, + context: &Context<'_>, + next: &super::super::super::mtp::DenseKv, + frame: &super::super::super::mtp::MtpFrame, + query: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + ) -> Result<()> { + self.prepare_mtp_kv(binding, context, next, frame)?; + let mut slot = self + .mtp_kv + .try_borrow_mut() + .map_err(|_| Error::IdentityMismatch)?; + let result = slot.as_mut().ok_or(Error::IdentityMismatch)?.attend( + query, + output, + u32::try_from(frame.position().get()).map_err(|_| Error::Overflow)?, + ); + if context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) { + self.failed.set(true); + } + result + } + pub(in super::super) fn assemble_mmq( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + workspace: MmqWorkspace<'ctx>, + ) -> Result { + Self::assemble_mmq_with_mtp_experts(binding, context, workspace, true) + } + pub(in super::super) fn assemble_mmq_with_mtp_experts( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + workspace: MmqWorkspace<'ctx>, + mtp_experts: bool, + ) -> Result { + if !room_fits(context.allocated_bytes(), context.budget_bytes(), 0, 0) { + let _ = workspace.close(); + return Err(Error::InputAllocation); + } + match Self::new_with_mtp_experts(binding, context, mtp_experts) { + Ok(mut cache) => { + cache.mmq_workspace = Some(workspace); + Ok(cache) + } + Err(primary) => { + let _ = workspace.close(); + Err(primary) + } + } + } + /// Cache-local observation of completed producers, never dispatch intent. + #[cfg(test)] + pub(in crate::qwen_forward) fn test_mmq_dispatch_witness(&self) -> (u64, u64, u64) { + self.mmq_dispatch_witness.get() + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_5.rs b/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_5.rs new file mode 100644 index 00000000..8e023f4f --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_5.rs @@ -0,0 +1,138 @@ +//! Moved out of the parent module by STRA-338: impl MoeWeightCache (5). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> MoeWeightCache<'ctx> { + #[cfg(test)] + pub(in crate::qwen_forward) fn note_test_mmq_dispatch(&self, resident: bool, rows: usize) { + let (layers, columns, fallback) = self.mmq_dispatch_witness.get(); + self.mmq_dispatch_witness.set(if resident { + (layers + 1, columns + rows as u64 * 10, fallback) + } else { + (layers, columns, fallback + 1) + }); + } + /// Stable actor-owned context, admitted against the actual transaction's + /// context pointer. Never extend a short session/closure reference. + pub(in super::super::super) fn mmq_context( + &self, + binding: &ModelBinding, + observed: &Context<'_>, + ) -> Result<&'ctx Context<'ctx>> { + self.validate(binding, observed)?; + Ok(self.context) + } + pub(in super::super) fn weight_layout(&self, key: MoeWeightDescriptor) -> Result> { + if self.original_prompt_mmq { original_dual_layout(key) } else { dual_layout(key) } + } + pub(in super::super::super) fn has_original_prompt_mmq(&self) -> bool { self.original_prompt_mmq } + /// Root's selected adaptive capacity factory calls this before any routed + /// prefix/adaptive publication. Same actual workspace, no second experiment. + #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] + pub(crate) fn admit_original_expert_groups(&mut self,binding:&ModelBinding, + context:&Context<'_>,capacity:u32)->Result<()> { + self.validate(binding,context)?; + if !self.original_prompt_mmq || !self.main.is_empty() || self.main_bytes!=0 + || self.adaptive.is_some() {return Err(Error::IdentityMismatch);} + let workspace=self.mmq_workspace.as_mut().ok_or(Error::IdentityMismatch)?; + workspace.enable_original_expert_groups(capacity).map_err(driver_error)?; + self.room(0)?; + self.validate(binding,context) + } + + pub(in super::super::super) fn requires_iq3_mmq_admission(&self) -> bool { + self.mmq_policy == MmqRoutingPolicy::NativeIntegerIq3 + } + /// Called only after every phase row and existing kind admission has been + /// checked. The new policy additionally verifies every actual descriptor + /// before activation quantization, cache fill, or a GU kernel can run. + pub(in super::super::super) fn admit_mmq_chunk( + &self, + binding: &ModelBinding, + context: &Context<'_>, + rows: usize, + triplets: &[[MoeWeightDescriptor; 3]], + original_prompt: bool, + ) -> Result> { + self.validate(binding, context)?; + if !(if original_prompt { 1..=64 } else { 2..=64 }).contains(&rows) + || self.mmq_workspace.is_none() || (original_prompt && !self.original_prompt_mmq) { + return Err(Error::IdentityMismatch); + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if self.adaptive.is_some() && !original_prompt { + return Ok(None); + } + if original_prompt || self.requires_iq3_mmq_admission() { + if triplets.len() != rows.checked_mul(10).ok_or(Error::Overflow)? { + return Err(Error::InvalidDimension); + } + for keys in triplets { + if !(if original_prompt { original_mmq_triplet(keys)? } else { integer_iq3_triplet(keys)? }) { + return Ok(None); + } + } + } + Ok(Some(MmqChunkAdmission { + owner: Rc::clone(&self.mmq_owner), + policy: self.mmq_policy, + original_prompt, + })) + } + pub(in super::super::super) fn with_mmq_workspace( + &mut self, + binding: &ModelBinding, + context: &Context<'_>, + admission: &MmqChunkAdmission, + execute: impl FnOnce(&mut Self, &mut MmqWorkspace<'ctx>) -> Result, + ) -> Result { + self.validate(binding, context)?; + if !Rc::ptr_eq(&self.mmq_owner, &admission.owner) || admission.policy != self.mmq_policy + || (admission.original_prompt && !self.original_prompt_mmq) { + return Err(Error::IdentityMismatch); + } + let mut workspace = self.mmq_workspace.take().ok_or(Error::IdentityMismatch)?; + let result = execute(self, &mut workspace); + self.mmq_workspace = Some(workspace); + if context.is_poisoned() || matches!(&result, Err(Error::CudaExecution)) { + self.failed.set(true); + } + result + } + /// Hold all three real immutable cache entries simultaneously. Staging + /// uses their original binding descriptors and padded charge once; a + /// missing/evicted descriptor refuses, never manufactures a weight view. + pub(in super::super::super) fn with_mmq_triplet( + &mut self, + binding: &ModelBinding, + weights: &MoeExpertWeights, + selection: MoeExpertSelection, + original_prompt: bool, + execute: impl FnOnce(&MmqWeights<'ctx>, &MmqWeights<'ctx>, &MmqWeights<'ctx>) -> Result, + ) -> Result { + if original_prompt && !self.original_prompt_mmq { return Err(Error::IdentityMismatch); } + if original_prompt || self.requires_iq3_mmq_admission() { + return self.with_integer_mmq_triplet(binding, weights, selection, original_prompt, execute); + } + self.validate(binding, self.context)?; + let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down]; + let mut keys = Vec::new(); + keys.try_reserve_exact(3) + .map_err(|_| Error::InputAllocation)?; + for role in roles { + let _ = self.matrix(binding, weights, selection, role)?; + keys.push( + binding + .moe_weight_descriptor(weights, selection, role) + .map_err(binding_error)?, + ); + } + execute( + self.mmq_owner(&keys[0])?, + self.mmq_owner(&keys[1])?, + self.mmq_owner(&keys[2])?, + ) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_6.rs b/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_6.rs new file mode 100644 index 00000000..d2ba4a82 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_6.rs @@ -0,0 +1,241 @@ +//! Moved out of the parent module by STRA-338: impl MoeWeightCache (6). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> MoeWeightCache<'ctx> { + + // Only the explicit integer candidate uses the closed three-weight fill. + // Every requested owner stays resident while missing roles are admitted. + pub(in super::super) fn with_integer_mmq_triplet( + &mut self, + binding: &ModelBinding, + weights: &MoeExpertWeights, + selection: MoeExpertSelection, + original_prompt: bool, + execute: impl FnOnce(&MmqWeights<'ctx>, &MmqWeights<'ctx>, &MmqWeights<'ctx>) -> Result, + ) -> Result { + self.validate(binding, self.context)?; + let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down]; + let keys = [ + binding + .moe_weight_descriptor(weights, selection, roles[0]) + .map_err(binding_error)?, + binding + .moe_weight_descriptor(weights, selection, roles[1]) + .map_err(binding_error)?, + binding + .moe_weight_descriptor(weights, selection, roles[2]) + .map_err(binding_error)?, + ]; + let layouts = [ + self.weight_layout(keys[0])?.ok_or(Error::InvalidDimension)?, + self.weight_layout(keys[1])?.ok_or(Error::InvalidDimension)?, + self.weight_layout(keys[2])?.ok_or(Error::InvalidDimension)?, + ]; + let formats = layouts.map(|(format, _)| format); + let charges = layouts.map(|(_, charge)| charge); + let mut missing = 0usize; + let mut extra = 0usize; + for (key, charged) in keys.iter().zip(charges) { + if !self.main.contains_key(key) { + missing += 1; + extra = extra.checked_add(charged).ok_or(Error::Overflow)?; + } else { + let owner = self.mmq_owner(key)?; + if owner.allocated_bytes() != charged { + return Err(Error::IdentityMismatch); + } + } + } + if !(if original_prompt { original_mmq_triplet(&keys)? } else { integer_iq3_triplet(&keys)? }) { + return Err(Error::InvalidDimension); + } + if keys + .iter() + .any(|key| self.is_pinned(*key) && !self.main.contains_key(key)) + { + return Err(Error::IdentityMismatch); + } + if missing == 0 || missing == 3 { + for key in keys { + self.note_profile_request(key, missing == 0); + } + } + let next_age = self.age.checked_add(3).ok_or(Error::Overflow)?; + if missing != 0 { + self.room_protected(extra, &keys)?; + self.reserve_main(missing)?; + } + if missing == 3 { + let update = self.prepare_lru_updates(&[ + (keys[0], self.age + 1), + (keys[1], self.age + 2), + (keys[2], next_age), + ])?; + // Read actual bound spans before any upload. The driver owns its + // padded staging until all attempted copies have completed. + let mut raw: [Box<[u8]>; 3] = std::array::from_fn(|_| Box::default()); + let mut read_bytes = 0usize; + for (index, (role, key)) in roles.into_iter().zip(&keys).enumerate() { + let block = binding + .moe_expert_block(weights, selection, role, 0, key.rows) + .map_err(binding_error)?; + if block.bytes().len() != key.bytes { + return Err(Error::InvalidDimension); + } + raw[index] = block.into_bytes(); + read_bytes = read_bytes.checked_add(key.bytes).ok_or(Error::Overflow)?; + } + let main_bytes = self.main_bytes.checked_add(extra).ok_or(Error::Overflow)?; + let context = self.context; + let uploaded = if original_prompt { + context.mmq_original_weight_triplet(formats, [&raw[0], &raw[1], &raw[2]]) + } else { + context.mmq_weight_triplet(formats, [&raw[0], &raw[1], &raw[2]]) + }; + let owners = match uploaded { + Ok(owners) => owners, + Err(error) => { + if context.is_poisoned() { + self.failed.set(true); + } + return Err(driver_error(error)); + } + }; + if owners + .iter() + .zip(&charges) + .any(|(owner, &charge)| owner.allocated_bytes() != charge) + { + for owner in owners.into_iter().rev() { + if owner.close().is_err() { + self.failed.set(true); + } + } + return Err(Error::IdentityMismatch); + } + if let Err(primary) = self.commit_lru_updates(update, 3) { + for owner in owners.into_iter().rev() { + if owner.close().is_err() { + self.failed.set(true); + } + } + return Err(primary); + } + // No fallible allocation/validation follows the first insertion. + // Publish the complete triplet only after driver completion. + for (index, owner) in owners.into_iter().enumerate() { + self.main.insert( + keys[index], + Entry { + weight: EncodedWeight::Dual(formats[index], owner), + charged_bytes: charges[index], + age: self.age + index as u64 + 1, + }, + ); + } + self.main_bytes = main_bytes; + self.age = next_age; + self.counters.misses = self.counters.misses.saturating_add(3); + self.counters.read_bytes = self.counters.read_bytes.saturating_add(read_bytes as u64); + self.counters.upload_bytes = self.counters.upload_bytes.saturating_add(extra as u64); + for (key, charge) in keys.into_iter().zip(charges) { + self.note_permanent_fill(key, key.bytes, charge); + } + } else if missing != 0 { + // Admission is not a reservation against other GPU actors. Every + // later physical-room query protects all requested roles again. + for (role, key) in roles.into_iter().zip(&keys) { + let _ = self.main_entry_protected(*key, &keys, || { + let block = binding + .moe_expert_block(weights, selection, role, 0, key.rows) + .map_err(binding_error)?; + Ok(block.into_bytes()) + })?; + } + } else { + // A complete resident hit allocates/uploads nothing, so it needs + // no physical-memory query or new admission reservation. + let update = self.prepare_lru_updates(&[ + (keys[0], self.age + 1), + (keys[1], self.age + 2), + (keys[2], next_age), + ])?; + self.commit_lru_updates(update, 3)?; + for (index, key) in keys.iter().enumerate() { + let entry = self.main.get_mut(key).ok_or(Error::IdentityMismatch)?; + entry.age = self.age + index as u64 + 1; + } + self.age = next_age; + self.counters.hits = self.counters.hits.saturating_add(3); + } + if missing == 0 { + for key in keys { + self.note_permanent_hit(key); + } + } + #[cfg(test)] + { + let (full, mixed, hit) = self.mmq_triplet_witness.get(); + self.mmq_triplet_witness.set(match missing { + 3 => (full.saturating_add(1), mixed, hit), + 0 => (full, mixed, hit.saturating_add(1)), + _ => (full, mixed.saturating_add(1), hit), + }); + } + self.validate(binding, self.context)?; + execute( + self.mmq_owner(&keys[0])?, + self.mmq_owner(&keys[1])?, + self.mmq_owner(&keys[2])?, + ) + } + + #[cfg(test)] + pub(in super::super::super) fn test_mmq_triplet_witness(&self) -> (u64, u64, u64) { + self.mmq_triplet_witness.get() + } + + pub(in super::super) fn room_protected(&mut self, extra: usize, protected: &[MoeWeightDescriptor]) -> Result<()> { + loop { + let (free, _) = self.context.memory_info().map_err(driver_error)?; + let physical_room = extra + .checked_add(WORKING_RESERVE) + .is_some_and(|n| n <= free); + if physical_room + && room_fits( + self.context.allocated_bytes(), + self.context.budget_bytes(), + self.main_bytes, + extra, + ) + { + return Ok(()); + } + let key = self.eviction_key(protected)?; + self.remove_lru_entry(key)?; + let entry = self.main.remove(&key).ok_or(Error::IdentityMismatch)?; + if entry.weight.close().is_err() { + self.failed.set(true); + return Err(Error::CudaExecution); + } + self.main_bytes = self + .main_bytes + .checked_sub(entry.charged_bytes) + .ok_or(Error::Overflow)?; + self.counters.eviction_bytes = self + .counters + .eviction_bytes + .saturating_add(entry.charged_bytes as u64); + self.note_permanent_eviction(key, entry.charged_bytes); + } + } + pub(in super::super) fn mmq_owner(&self, key: &MoeWeightDescriptor) -> Result<&MmqWeights<'ctx>> { + match &self.main.get(key).ok_or(Error::IdentityMismatch)?.weight { + EncodedWeight::Dual(_, owner) => Ok(owner), + EncodedWeight::Raw(_) => Err(Error::IdentityMismatch), + } + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_7.rs b/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_7.rs new file mode 100644 index 00000000..b31a2913 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_7.rs @@ -0,0 +1,213 @@ +//! Moved out of the parent module by STRA-338: impl MoeWeightCache (7). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> MoeWeightCache<'ctx> { + pub(crate) fn validate(&self, binding: &ModelBinding, context: &Context<'_>) -> Result<()> { + if self.failed.get() + || self.context.is_poisoned() + || self + .routed_finite + .as_ref() + .is_some_and(|owner| owner.is_failed()) + || self + .routed_workspace + .as_ref() + .is_some_and(|owner| owner.is_failed()) + || self + .routed_resident + .as_ref() + .is_some_and(|owner| owner.is_failed()) + || self + .mtp_input_workspace + .as_ref() + .is_some_and(|owner| owner.is_failed()) + { + return Err(Error::CudaExecution); + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(adaptive) = &self.adaptive { + adaptive.validate(binding)?; + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(outputs) = &self.routed_outputs { + outputs.validate(&binding.identity(), context)?; + } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(owner) = &self.ephemeral_routed { + owner + .try_borrow() + .map_err(|_| Error::IdentityMismatch)? + .validate(binding, context)?; + } + if !self.binding.matches(&binding.identity()) || !std::ptr::eq(self.context, context) { + return Err(Error::IdentityMismatch); + } + Ok(()) + } + pub(crate) fn prepare_step( + &mut self, + binding: &ModelBinding, + context: &Context<'_>, + ) -> Result<()> { + self.validate(binding, context)?; + self.room(0) + } + /// Reserve the genuine caller's live transient peak by evicting immutable + /// main-cache entries before packet allocations. The normal working reserve + /// and original padded weight accounting remain separate and unchanged. + pub(in super::super::super) fn reserve_mmq_transient( + &mut self, + binding: &ModelBinding, + context: &Context<'_>, + extra: usize, + ) -> Result<()> { + self.validate(binding, context)?; + self.room(extra)?; + self.validate(binding, context) + } + pub(in super::super) fn room(&mut self, extra: usize) -> Result<()> { + loop { + // The typed cap excludes driver modules and other GPU actors. + // Query actual current-context availability before own-cache + // admission; a snapshot is not a reservation against other actors. + let (free, _) = self.context.memory_info().map_err(driver_error)?; + let physical_room = extra + .checked_add(WORKING_RESERVE) + .is_some_and(|needed| needed <= free); + if physical_room + && room_fits( + self.context.allocated_bytes(), + self.context.budget_bytes(), + self.main_bytes, + extra, + ) + { + return Ok(()); + } + let key = self.eviction_key(&[])?; + self.remove_lru_entry(key)?; + let entry = self.main.remove(&key).ok_or(Error::IdentityMismatch)?; + if entry.weight.close().is_err() { + self.failed.set(true); + return Err(Error::CudaExecution); + } + self.main_bytes = self + .main_bytes + .checked_sub(entry.charged_bytes) + .ok_or(Error::Overflow)?; + self.counters.eviction_bytes = self + .counters + .eviction_bytes + .saturating_add(entry.charged_bytes as u64); + self.note_permanent_eviction(key, entry.charged_bytes); + } + } + pub(in super::super) fn upload(&mut self, bytes: &[u8]) -> Result> { + let mut buffer = match self.context.allocate(bytes.len()) { + Ok(buffer) => buffer, + Err(error) => { + self.failed.set(true); + return Err(driver_error(error)); + } + }; + if buffer.copy_from(bytes).is_err() { + self.failed.set(true); + let _ = buffer.release(); + return Err(Error::CudaExecution); + } + self.counters.read_bytes = self.counters.read_bytes.saturating_add(bytes.len() as u64); + self.counters.upload_bytes = self + .counters + .upload_bytes + .saturating_add(bytes.len() as u64); + Ok(buffer) + } + pub(in super::super) fn main_entry_protected( + &mut self, + key: MoeWeightDescriptor, + protected: &[MoeWeightDescriptor], + read: impl FnOnce() -> Result>, + ) -> Result> { + if self.failed.get() { + return Err(Error::CudaExecution); + } + let hit = self.main.contains_key(&key); + if self.is_pinned(key) && !hit { + return Err(Error::IdentityMismatch); + } + self.note_profile_request(key, hit); + self.age = self.age.checked_add(1).ok_or(Error::Overflow)?; + if hit { + let update = self.prepare_lru_updates(&[(key, self.age)])?; + self.commit_lru_updates(update, 1)?; + self.counters.hits = self.counters.hits.saturating_add(1); + } else { + self.counters.misses = self.counters.misses.saturating_add(1); + let dual = self.weight_layout(key)?; + let charged_bytes = dual.map_or(key.bytes, |(_, bytes)| bytes); + self.room_protected(charged_bytes, protected)?; + self.reserve_main(1)?; + let update = self.prepare_lru_updates(&[(key, self.age)])?; + let bytes = read()?; + if bytes.len() != key.bytes { + return Err(Error::InvalidDimension); + } + let weight = if let Some((format, expected)) = dual { + let owner = match self.context.mmq_weights(format, &bytes) { + Ok(owner) => owner, + Err(error) => { + if self.context.is_poisoned() { + self.failed.set(true); + } + return Err(driver_error(error)); + } + }; + if owner.allocated_bytes() != expected { + let cleanup = owner.close(); + if cleanup.is_err() { + self.failed.set(true); + } + return Err(Error::IdentityMismatch); + } + self.counters.read_bytes = + self.counters.read_bytes.saturating_add(bytes.len() as u64); + self.counters.upload_bytes = self + .counters + .upload_bytes + .saturating_add(charged_bytes as u64); + EncodedWeight::Dual(format, owner) + } else { + EncodedWeight::Raw(self.upload(&bytes)?) + }; + let main_bytes = self + .main_bytes + .checked_add(charged_bytes) + .ok_or(Error::Overflow)?; + if let Err(primary) = self.commit_lru_updates(update, 1) { + if weight.close().is_err() { + self.failed.set(true); + } + return Err(primary); + } + self.main_bytes = main_bytes; + self.main.insert( + key, + Entry { + weight, + charged_bytes, + age: self.age, + }, + ); + } + self.note_permanent_lookup(key, hit); + let entry = self.main.get_mut(&key).ok_or(Error::IdentityMismatch)?; + entry.age = self.age; + Ok(match &entry.weight { + EncodedWeight::Raw(buffer) => CachedMoeMatrix::Raw(buffer), + EncodedWeight::Dual(format, owner) => CachedMoeMatrix::Dual(*format, owner), + }) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_8.rs b/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_8.rs new file mode 100644 index 00000000..8f03f6d6 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_8.rs @@ -0,0 +1,256 @@ +//! Moved out of the parent module by STRA-338: impl MoeWeightCache (8). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> MoeWeightCache<'ctx> { + pub(in super::super) fn main_entry( + &mut self, + key: MoeWeightDescriptor, + read: impl FnOnce() -> Result>, + ) -> Result> { + if self.failed.get() { + return Err(Error::CudaExecution); + } + let hit = self.main.contains_key(&key); + if self.is_pinned(key) && !hit { + return Err(Error::IdentityMismatch); + } + self.note_profile_request(key, hit); + self.age = self.age.checked_add(1).ok_or(Error::Overflow)?; + if hit { + let update = self.prepare_lru_updates(&[(key, self.age)])?; + self.commit_lru_updates(update, 1)?; + self.counters.hits = self.counters.hits.saturating_add(1); + } else { + self.counters.misses = self.counters.misses.saturating_add(1); + let dual = self.weight_layout(key)?; + let charged_bytes = dual.map_or(key.bytes, |(_, bytes)| bytes); + self.room(charged_bytes)?; + self.reserve_main(1)?; + let update = self.prepare_lru_updates(&[(key, self.age)])?; + let bytes = read()?; + if bytes.len() != key.bytes { + return Err(Error::InvalidDimension); + } + let weight = if let Some((format, expected)) = dual { + let owner = match self.context.mmq_weights(format, &bytes) { + Ok(owner) => owner, + Err(error) => { + if self.context.is_poisoned() { + self.failed.set(true); + } + return Err(driver_error(error)); + } + }; + if owner.allocated_bytes() != expected { + let cleanup = owner.close(); + if cleanup.is_err() { + self.failed.set(true); + } + return Err(Error::IdentityMismatch); + } + self.counters.read_bytes = + self.counters.read_bytes.saturating_add(bytes.len() as u64); + self.counters.upload_bytes = self + .counters + .upload_bytes + .saturating_add(charged_bytes as u64); + EncodedWeight::Dual(format, owner) + } else { + EncodedWeight::Raw(self.upload(&bytes)?) + }; + let main_bytes = self + .main_bytes + .checked_add(charged_bytes) + .ok_or(Error::Overflow)?; + if let Err(primary) = self.commit_lru_updates(update, 1) { + if weight.close().is_err() { + self.failed.set(true); + } + return Err(primary); + } + self.main_bytes = main_bytes; + self.main.insert( + key, + Entry { + weight, + charged_bytes, + age: self.age, + }, + ); + } + self.note_permanent_lookup(key, hit); + let entry = self.main.get_mut(&key).ok_or(Error::IdentityMismatch)?; + entry.age = self.age; + Ok(match &entry.weight { + EncodedWeight::Raw(buffer) => CachedMoeMatrix::Raw(buffer), + EncodedWeight::Dual(format, owner) => CachedMoeMatrix::Dual(*format, owner), + }) + } + /// Selected scoped cold GU only. The genuine final source block transfers + /// its storage at the original role point; hits keep the original policy. + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in super::super) fn main_entry_owned_gate_up( + &mut self, + key: MoeWeightDescriptor, + read: impl FnOnce() -> Result>, + ) -> Result> { + if self.failed.get() { + return Err(Error::CudaExecution); + } + let hit = self.main.contains_key(&key); + if self.is_pinned(key) && !hit { + return Err(Error::IdentityMismatch); + } + self.note_profile_request(key, hit); + self.age = self.age.checked_add(1).ok_or(Error::Overflow)?; + if hit { + let update = self.prepare_lru_updates(&[(key, self.age)])?; + self.commit_lru_updates(update, 1)?; + self.counters.hits = self.counters.hits.saturating_add(1); + } else { + self.counters.misses = self.counters.misses.saturating_add(1); + let dual = self.weight_layout(key)?; + let charged_bytes = dual.map_or(key.bytes, |(_, bytes)| bytes); + self.room(charged_bytes)?; + self.reserve_main(1)?; + let update = self.prepare_lru_updates(&[(key, self.age)])?; + let bytes = read()?; + if bytes.len() != key.bytes { + return Err(Error::InvalidDimension); + } + let raw_bytes = bytes.len(); + let weight = if let Some((format, expected)) = dual { + let kind = match key.raw_kind { + 18 => leleka_cuda_driver::RoutedFormat::IQ3_XXS, + 22 => leleka_cuda_driver::RoutedFormat::IQ2_S, + _ => return Err(Error::InvalidDimension), + }; + let shape = leleka_cuda_driver::ProjectionSpec { + kind: leleka_cuda_driver::ProjectionKind::Routed(kind), + rows: key.rows, + columns: key.columns, + }; + let owner = + match self + .context + .mmq_weights_owned_gate_up(shape, format, bytes.into_vec()) + { + Ok(owner) => owner, + Err(error) => { + if self.context.is_poisoned() { + self.failed.set(true); + } + return Err(driver_error(error)); + } + }; + if owner.allocated_bytes() != expected { + let cleanup = owner.close(); + if cleanup.is_err() { + self.failed.set(true); + } + return Err(Error::IdentityMismatch); + } + self.counters.read_bytes = + self.counters.read_bytes.saturating_add(raw_bytes as u64); + self.counters.upload_bytes = self + .counters + .upload_bytes + .saturating_add(charged_bytes as u64); + EncodedWeight::Dual(format, owner) + } else { + EncodedWeight::Raw(self.upload(&bytes)?) + }; + let main_bytes = self + .main_bytes + .checked_add(charged_bytes) + .ok_or(Error::Overflow)?; + if let Err(primary) = self.commit_lru_updates(update, 1) { + if weight.close().is_err() { + self.failed.set(true); + } + return Err(primary); + } + self.main_bytes = main_bytes; + self.main.insert( + key, + Entry { + weight, + charged_bytes, + age: self.age, + }, + ); + } + self.note_permanent_lookup(key, hit); + let entry = self.main.get_mut(&key).ok_or(Error::IdentityMismatch)?; + entry.age = self.age; + Ok(match &entry.weight { + EncodedWeight::Raw(buffer) => CachedMoeMatrix::Raw(buffer), + EncodedWeight::Dual(format, owner) => CachedMoeMatrix::Dual(*format, owner), + }) + } + /// Fill through the original cache policy, then retain actual immutable + /// cache/weight/failure-cell loans for the complete closed consumer. + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in super::super::super) fn with_matrix_routed_source<'source, 'group, T>( + &mut self, + binding: &ModelBinding, + source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'source, 'group>, + member: usize, + role: MoeMatrixRole, + consume: impl FnOnce( + CachedMoeMatrix<'_, 'ctx>, + &RoutedSourceHealth<'_, 'ctx>, + &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'source, 'group>, + ) -> Result, + ) -> Result { + self.validate(binding, self.context)?; + if !self.uses_direct_native_down_packets() { + return Err(Error::IdentityMismatch); + } + source.validate_binding(binding).map_err(binding_error)?; + let key = source.descriptor(member, role).map_err(binding_error)?; + if let Some(adaptive) = &self.adaptive + && key.expert.is_some() + { + let matrix = adaptive + .matrix(binding, key)? + .ok_or(Error::Unsupported(super::super::super::contract::Stage::MoeExpert))?; + let health = RoutedSourceHealth { + binding: &self.binding, + context: self.context, + failed: &self.failed, + }; + return consume(matrix, &health, source); + } + // The temporary returned view ends here. No cache fill/eviction occurs + // while the consumer below holds actual cache fields immutably. + let read = || { + Ok(source + .block(member, role) + .map_err(binding_error)? + .into_bytes()) + }; + let _ = + if key.expert.is_some() && matches!(key.role, 0 | 1) && matches!(key.raw_kind, 18 | 22) + { + self.main_entry_owned_gate_up(key, read)? + } else { + self.main_entry(key, read)? + }; + self.validate(binding, self.context)?; + let entry = self.main.get(&key).ok_or(Error::IdentityMismatch)?; + let matrix = match &entry.weight { + EncodedWeight::Raw(buffer) => CachedMoeMatrix::Raw(buffer), + EncodedWeight::Dual(format, owner) => CachedMoeMatrix::Dual(*format, owner), + }; + let health = RoutedSourceHealth { + binding: &self.binding, + context: self.context, + failed: &self.failed, + }; + consume(matrix, &health, source) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_9.rs b/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_9.rs new file mode 100644 index 00000000..82648291 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_9.rs @@ -0,0 +1,168 @@ +//! Moved out of the parent module by STRA-338: impl MoeWeightCache (9). + +#[allow(unused_imports)] +use super::*; + + +impl<'ctx> MoeWeightCache<'ctx> { + pub(in super::super::super) fn matrix( + &mut self, + binding: &ModelBinding, + weights: &MoeExpertWeights, + selection: MoeExpertSelection, + role: MoeMatrixRole, + ) -> Result> { + self.validate(binding, self.context)?; + let key = binding + .moe_weight_descriptor(weights, selection, role) + .map_err(binding_error)?; + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if self.adaptive.is_some() && key.expert.is_some() { + return self + .adaptive + .as_ref() + .ok_or(Error::IdentityMismatch)? + .matrix(binding, key)? + .ok_or(Error::Unsupported(super::super::super::contract::Stage::MoeExpert)); + } + self.main_entry(key, || { + let block = binding + .moe_expert_block(weights, selection, role, 0, key.rows) + .map_err(binding_error)?; + Ok(block.into_bytes()) + }) + } + pub(crate) fn shared_scalar( + &mut self, + binding: &ModelBinding, + weights: &MoeExpertWeights, + ) -> Result<&DeviceBuffer<'ctx>> { + self.validate(binding, self.context)?; + let key = binding + .moe_shared_scalar_descriptor(weights) + .map_err(binding_error)?; + match self.main_entry(key, || { + binding.moe_shared_scalar(weights).map_err(binding_error) + })? { + CachedMoeMatrix::Raw(buffer) => Ok(buffer), + CachedMoeMatrix::Dual(_, _) => Err(Error::IdentityMismatch), + } + } + /// Only the explicit new profile factory calls this before PrefixPlan/preload. + /// Eligibility uses immutable already-loaded metadata, not a hoisted source check. + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in super::super) fn admit_mtp_input_workspace(&mut self, binding: &ModelBinding) -> Result<()> { + self.validate(binding, self.context)?; + if !self.main.is_empty() || self.main_bytes != 0 || self.mtp_input_workspace.is_some() { + return Err(Error::IdentityMismatch); + } + let supported = [MtpRole::FcEmbedding, MtpRole::FcHidden] + .into_iter() + .all(|role| { + self.dense.iter().any(|entry| { + entry.role == role + && (entry.kind, entry.rows, entry.columns) == (MtpKind::Q8_0, 2560, 2560) + }) + }) + && [(MtpRole::EmbeddingNorm, 2560), (MtpRole::HiddenNorm, 10240)] + .into_iter() + .all(|(role, words)| { + self.dense.iter().any(|entry| { + entry.role == role + && entry.kind == MtpKind::F32 + && entry + .f32 + .as_ref() + .is_some_and(|values| values.len() == words) + }) + }); + if !supported { + return Ok(()); + } + // Actual Context charge is counted once. Both admission predicates leave + // the independent working reserve; metadata plan sees the eager allocation. + self.reserve_mmq_transient(binding, self.context, MTP_INPUT_WORKSPACE_BYTES)?; + self.mtp_input_workspace = Some(Rc::new(MtpInputWorkspaceOwner::new( + self.binding.clone(), + self.context, + )?)); + self.room(0)?; + self.validate(binding, self.context) + } + #[cfg(test)] + pub(in super::super::super) fn note_mtp_input_completed(&self) { + self.mtp_input_completions + .set(self.mtp_input_completions.get().saturating_add(1)); + } + #[cfg(test)] + pub(crate) fn test_mtp_input_completions(&self) -> u64 { + self.mtp_input_completions.get() + } + pub(in super::super::super) fn has_mtp_input_workspace(&self) -> bool { + self.mtp_input_workspace.is_some() + } + pub(in super::super::super) fn mtp_input_workspace_owner( + &self, + binding: &ModelBinding, + context: &Context<'_>, + ) -> Result>> { + self.validate(binding, context)?; + let owner = self + .mtp_input_workspace + .as_ref() + .ok_or(Error::IdentityMismatch)?; + if !owner.binding.matches(&binding.identity()) || !std::ptr::eq(owner.context, context) { + return Err(Error::IdentityMismatch); + } + Ok(Rc::clone(owner)) + } + pub(crate) fn mtp_bank( + &self, + binding: &ModelBinding, + context: &Context<'_>, + ) -> Result<&DeviceBuffer<'ctx>> { + self.validate(binding, context)?; + binding + .mtp_weights() + .map_err(binding_error)? + .validate_sources(binding) + .map_err(binding_error)?; + self.mtp_hits.set(self.mtp_hits.get().saturating_add(1)); + self.bank.as_deref().ok_or(Error::IdentityMismatch) + } + pub(crate) fn mtp_matrix( + &self, + binding: &ModelBinding, + context: &Context<'_>, + role: MtpRole, + ) -> Result<(MtpKind, usize, usize, &DeviceBuffer<'ctx>)> { + self.validate(binding, context)?; + let pack = binding.mtp_weights().map_err(binding_error)?; + pack.validate_sources(binding).map_err(binding_error)?; + let entry = self + .dense + .iter() + .find(|e| e.role == role) + .ok_or(Error::IdentityMismatch)?; + if pack.dense_shape(binding, role).map_err(binding_error)? + != (entry.kind, entry.rows, entry.columns) + { + return Err(Error::IdentityMismatch); + } + self.mtp_hits.set(self.mtp_hits.get().saturating_add(1)); + Ok((entry.kind, entry.rows, entry.columns, &entry.buffer)) + } + pub(crate) fn mtp_f32(&self, binding: &ModelBinding, role: MtpRole) -> Result<&[f32]> { + self.mtp_matrix(binding, self.context, role)?; + self.dense + .iter() + .find(|e| e.role == role) + .and_then(|e| e.f32.as_deref()) + .ok_or(Error::InvalidDimension) + } + pub(crate) fn counters(&self) -> WeightCacheCounters { + let mut counters = self.counters; + counters.hits = counters.hits.saturating_add(self.mtp_hits.get()); + counters + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/mtp_decode/impl_mtpdecoder.rs b/crates/leleka-runtime/src/qwen_forward/mtp_decode/impl_mtpdecoder.rs index 428722bd..ac306396 100644 --- a/crates/leleka-runtime/src/qwen_forward/mtp_decode/impl_mtpdecoder.rs +++ b/crates/leleka-runtime/src/qwen_forward/mtp_decode/impl_mtpdecoder.rs @@ -3,615 +3,6 @@ #[allow(unused_imports)] use super::*; -impl MtpDecoder { - pub(crate) fn new(binding: &ModelBinding) -> Result { - Ok(Self { - draft: MtpSession::new(binding)?, - kv_prefill: None, - kv_prefill_host_charge: 0, - }) - } - - /// Fresh explicit outer256 policy, using the entire actual framed prompt. - /// The original Native constructor and retained continuations stay unchanged. - pub(crate) fn new_kv_prefill( - binding: &ModelBinding, - target: &QwenSession<'_>, - prompt: &[u32], - ) -> Result { - let mut decoder = Self::new(binding)?; - if prompt.len() == 1 { - return Ok(decoder); - } - if !(2..=crate::qwen_forward::contract::serving_cells() as usize).contains(&prompt.len()) { - return Err(Error::InvalidDimension); - } - // Admit this persistent baseline before allocating the owner/queue. - let host_charge = kv_prefill_host_charge(prompt.len())?; - if host_charge > 512 * 1024 * 1024 { - return Err(Error::InputAllocation); - } - let vocabulary = Dimension::new(248320)?; - let mut tokens = reserve(prompt.len())?; - for &token in prompt { - tokens.push(TokenId::new(u64::from(token), vocabulary)?); - } - decoder.kv_prefill = Some(mtp::MtpKvPrefill::new( - binding, - target, - &decoder.draft, - &tokens, - )?); - decoder.kv_prefill_host_charge = host_charge; - Ok(decoder) - } - - /// Persistent baseline remains charged while any warming owner is live. - pub(crate) fn prefill_host_remaining(&self, available: usize) -> Result { - available - .checked_sub(self.kv_prefill_host_charge) - .ok_or(Error::InputAllocation) - } - - /// Require the actual final target head and the jointly published real - /// draft before the first window; then release the warming certificate. - pub(crate) fn finish_kv_prefill( - &mut self, - binding: &ModelBinding, - target: &QwenSession<'_>, - source: &TargetStepProduct, - committed: &[u32], - ) -> Result<()> { - if let Some(owner) = self.kv_prefill.as_ref() { - owner.validate_ready(binding, &self.draft, target, source)?; - self.validate_resume(binding, target, source, committed)?; - self.kv_prefill = None; - self.kv_prefill_host_charge = 0; - } - Ok(()) - } - - /// Closed admission for the actor's single resident successful prefix. - /// Checks the actual committed target product and the actual draft prefix; - /// numerical equality or position alone never mints a reuse capability. - pub(crate) fn validate_resume( - &self, - binding: &ModelBinding, - target: &QwenSession<'_>, - source: &TargetStepProduct, - committed: &[u32], - ) -> Result<()> { - let (token, position, _, origin) = source.mtp_source(binding, target)?; - if committed.is_empty() - || committed.len() as u64 > crate::qwen_forward::contract::serving_cells() - || position.get().checked_add(1) != Some(committed.len() as u64) - || committed.last().copied() != Some(token.get()) - { - return Err(Error::IdentityMismatch); - } - let frame = self - .draft - .frame(binding, position, source.predicted(target)?, origin)?; - frame.validate(binding, target)?; - self.draft.prior(&frame)?; - Ok(()) - } - - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(crate) fn test_prefix_snapshot( - &self, - binding: &ModelBinding, - target: &QwenSession<'_>, - source: &TargetStepProduct, - committed: &[u32], - ) -> Result { - self.validate_resume(binding, target, source, committed)?; - let (_, position, _, origin) = source.mtp_source(binding, target)?; - let frame = self - .draft - .frame(binding, position, source.predicted(target)?, origin)?; - frame.validate(binding, target)?; - self.draft.test_prefix_snapshot(binding, &frame) - } - - /// Prefill every known-next prompt edge, except the final prompt product. - /// A fresh draft starts at position zero; skipped edges cannot be repaired - /// by silently resetting or creating a later-position draft. - pub(crate) fn warm( - &mut self, - binding: &ModelBinding, - target: &mut QwenSession<'_>, - source: &TargetStepProduct, - known_next: TokenId, - output: &OutputStage<'_, '_>, - cache: &MoeWeightCache<'_>, - ) -> Result<()> { - let prior = self.draft.checkpoint()?; - let result = (|| { - let input = - MtpInput::from_target(binding, target, &self.draft, source, known_next, cache)?; - mtp::step(binding, target, &mut self.draft, input, output, cache)?; - Ok(()) - })(); - if let Err(error) = result { - target.note_mtp_failure(&error); - self.draft.restore(&prior)?; - return Err(error); - } - Ok(()) - } - - /// Resident final target product plus the authoritative first appended input. - /// This known-next edge commits genuine draft state without an unused head. - pub(crate) fn warm_retained( - &mut self, - binding: &ModelBinding, - target: &mut QwenSession<'_>, - source: &TargetStepProduct, - known_next: TokenId, - cache: &MoeWeightCache<'_>, - ) -> Result<()> { - let prior = self.draft.checkpoint()?; - let result = (|| { - let input = - MtpInput::from_target(binding, target, &self.draft, source, known_next, cache)?; - mtp::warm_step(binding, target, &mut self.draft, input, cache) - })(); - if let Err(error) = result { - target.note_mtp_failure(&error); - self.draft.restore(&prior)?; - return Err(error); - } - Ok(()) - } - - pub(crate) fn warm_prefill( - &mut self, - binding: &ModelBinding, - target: &mut QwenSession<'_>, - source: &PrefillStepProduct, - known_next: TokenId, - cache: &MoeWeightCache<'_>, - ) -> Result<()> { - let prior = self.draft.checkpoint()?; - let result = (|| { - let input = - MtpInput::from_prefill(binding, target, &self.draft, source, known_next, cache)?; - mtp::warm_step(binding, target, &mut self.draft, input, cache) - })(); - if let Err(error) = result { - target.note_mtp_failure(&error); - self.draft.restore(&prior)?; - return Err(error); - } - Ok(()) - } - - #[allow(clippy::too_many_arguments)] - pub(crate) fn window<'driver>( - &mut self, - binding: &ModelBinding, - source: TargetStepProduct, - target: &mut QwenSession<'driver>, - output: &OutputStage<'_, '_>, - kar_cache: Option<&mut KarPleCache<'_>>, - cache: &mut MoeWeightCache<'driver>, - dense_cache: &DenseWeightCache<'_>, - spec: MtpWindowSpec, - cancelled: impl FnMut() -> bool, - ) -> std::result::Result { - if cache.requires_iq3_mmq_admission() { - self.window_batched( - binding, - source, - target, - output, - kar_cache, - cache, - dense_cache, - spec, - cancelled, - ) - } else { - self.window_scalar( - binding, - source, - target, - output, - kar_cache, - cache, - dense_cache, - spec, - cancelled, - ) - } - } - - /// Selected only by the existing explicit IQ3 integer/native Down policy. - /// Draft depth remains configured; target batch capacity is separately - /// admitted. Only predictions consumed by that capacity are generated/countable. - #[allow(clippy::too_many_arguments)] - pub(super) fn window_batched<'driver>( - &mut self, - binding: &ModelBinding, - source: TargetStepProduct, - target: &mut QwenSession<'driver>, - output: &OutputStage<'_, '_>, - mut kar_cache: Option<&mut KarPleCache<'_>>, - cache: &mut MoeWeightCache<'driver>, - dense_cache: &DenseWeightCache<'_>, - spec: MtpWindowSpec, - mut cancelled: impl FnMut() -> bool, - ) -> std::result::Result { - source.mtp_source(binding, target)?; - let first = source.predicted(target)?; - let source_position = source.position(target)?.get(); - if cancelled() { - return Err(MtpWindowError::Cancelled); - } - if spec.remaining == 0 || Some(first) == spec.eos { - return Ok(MtpVerifiedWindow { - tokens: Vec::new(), - latest: source, - eos: spec.remaining != 0 && Some(first) == spec.eos, - draft_steps: 0, - }); - } - if self.kv_prefill.is_some() || !cache.requires_iq3_mmq_admission() { - return Err(Error::IdentityMismatch.into()); - } - let limit = window_limit(source_position, spec.depth, spec.remaining)?; - let reuse_first_seed = limit > 1 && first_seed_reuse_enabled(cache); - let seed_host_charge = if reuse_first_seed { self.draft.first_seed_host_charge()? } else { 0 }; - let host_remaining = self.prefill_host_remaining(512 * 1024 * 1024)?; - let host_remaining = if reuse_first_seed { - host_remaining.checked_sub(seed_host_charge) - .ok_or(Error::InputAllocation)? - } else { host_remaining }; - // Pure complete-state admission before any draft/canonical mutation. - let capacity = QwenForward::mtp_target_window_capacity( - binding, - &source, - spec.eos, - target, - limit, - if cache.uses_strata_adaptive_experts() { - // Independent actual CPU wave and ephemeral staging coexist. - // Both are inside the unchanged 512MiB request admission. - host_remaining.checked_sub((48 + 16) * 1024 * 1024).ok_or(Error::InputAllocation)? - } else { host_remaining }, - )?; - let target_prior = target.checkpoint()?; - let mut draft_priors = reserve(1)?; - draft_priors.push(self.draft.checkpoint()?); - let mut candidates = reserve(limit + 1)?; - candidates.push(first); - let mut tokens = reserve(capacity)?; - let result = (|| { - let mut previous = None; - let mut first_seed = None; - let needed_predictions = needed_draft_predictions(capacity, limit)?; - for _ in 0..needed_predictions { - if cancelled() { - return Err(MtpWindowError::Cancelled); - } - let candidate = *candidates.last().ok_or(Error::IdentityMismatch)?; - if Some(candidate) == spec.eos { - break; - } - let input = match previous.as_ref() { - Some(product) => { - MtpInput::from_previous(binding, target, &self.draft, product, cache)? - } - None => MtpInput::from_target( - binding, - target, - &self.draft, - &source, - candidate, - cache, - )?, - }; - let seed_frame = if reuse_first_seed && previous.is_none() { - Some(input.frame().clone()) - } else { None }; - let product = mtp::step(binding, target, &mut self.draft, input, output, cache)?; - if let Some(frame) = seed_frame { - first_seed = Some((self.draft.checkpoint_first_seed(seed_host_charge)?, frame)); - } - candidates.push(product.predicted(binding, target)?); - previous = Some(product); - } - drop(previous); - let draft_steps = candidates.len().checked_sub(1).ok_or(Error::Overflow)?; - if let Some((seed, frame)) = first_seed { - // Recheck the authoritative target source before coupled restore. - source.mtp_source(binding, target)?; - if source.predicted(target)? != frame.token() - || source.position(target)? != frame.position() - { - return Err(Error::IdentityMismatch.into()); - } - self.draft.restore_first_seed( - binding, target, &frame, &seed, &mut draft_priors[0], - )?; - // The seed is now the actual committed draft; dropping its extra - // checkpoint precedes target journal/catchup allocation. - } else { - self.draft.restore(&draft_priors[0])?; - draft_priors.clear(); - // The old speculative epoch is unusable after rewind. Failure - // rollback retains only this new checkpoint; no nested warm rewind. - draft_priors.push(self.draft.checkpoint()?); - if cancelled() { - return Err(MtpWindowError::Cancelled); - } - let input = MtpInput::from_target(binding, target, &self.draft, &source, first, cache)?; - mtp::warm_step(binding, target, &mut self.draft, input, cache)?; - } - if cancelled() { - return Err(MtpWindowError::Cancelled); - } - let rows = capacity.min(limit).min(candidates.len()); - let mut stage_cancelled = false; - // Complete the previous refill after genuine draft compute but before - // target window journal allocation, preserving the shared host cap. - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if cache.uses_strata_adaptive_experts() { cache.poll_strata_adaptive(binding, true)?; } - let pending_result = { - let mut observe_cancel = || { - let current = cancelled(); - stage_cancelled |= current; - current - }; - QwenForward::prepare_mtp_target_window( - binding, - &source, - &candidates[..rows], - spec.eos, - target, - output, - kar_cache.as_deref_mut(), - cache, - dense_cache, - host_remaining, - &mut observe_cancel, - ) - }; - let pending = - pending_result.map_err(|error| window_stage_error(error, stage_cancelled))?; - let accepted = pending.accepted_rows(); - if accepted == 0 || accepted > rows || accepted > capacity || accepted > spec.remaining - { - return Err(Error::IdentityMismatch.into()); - } - // Capacity was reserved before work; accepted IDs/counters are - // assembled before either owner commits. They stay private on error. - tokens.extend_from_slice(&candidates[..accepted]); - let mut stage_cancelled = false; - let published = { - let mut observe_cancel = || { - let current = cancelled(); - stage_cancelled |= current; - current - }; - pending.publish_joint_with_gdn_replay(binding, &mut self.draft, cache, Some(dense_cache), &mut observe_cancel) - }; - let product = published.map_err(|error| window_stage_error(error, stage_cancelled))?; - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if cache.uses_strata_adaptive_experts() { - cache.poll_strata_adaptive(binding, false)?; - cache.strata_adaptive_completed_window(binding)?; - } - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - batch_gpu::after_joint_publish(); - if cancelled() { - return Err(MtpWindowError::Cancelled); - } - let eos = Some(product.predicted(target)?) == spec.eos; - Ok((product, eos, draft_steps)) - })(); - match result { - Ok((product, eos, draft_steps)) => Ok(MtpVerifiedWindow { - tokens, - latest: product, - eos, - draft_steps, - }), - Err(error) => { - if let MtpWindowError::Forward(cause) = error { - target.note_mtp_failure(&cause); - } - // Attempt BOTH full restores even when the first is refused by - // poison. Retain the primary error; never return private IDs. - let target_restore = target.restore_checkpoint(&target_prior); - let draft_restore = match draft_priors.first() { - Some(prior) => self.draft.restore(prior), - None => Ok(()), // remint failed before actual catchup - }; - if let Err(cause) = target_restore { - target.note_mtp_failure(&cause); - } - #[cfg(test)] - if target_restore.is_err() || draft_restore.is_err() { - eprintln!("MTP candidate rollback primary={error:?} target={target_restore:?} draft={draft_restore:?}"); - } - let _ = draft_restore; - Err(error) - } - } - } - - #[allow(clippy::too_many_arguments)] - pub(crate) fn window_scalar( - &mut self, - binding: &ModelBinding, - source: TargetStepProduct, - target: &mut QwenSession<'_>, - output: &OutputStage<'_, '_>, - mut kar_cache: Option<&mut KarPleCache<'_>>, - cache: &mut MoeWeightCache<'_>, - dense_cache: &DenseWeightCache<'_>, - spec: MtpWindowSpec, - mut cancelled: impl FnMut() -> bool, - ) -> std::result::Result { - source.mtp_source(binding, target)?; - let first = source.predicted(target)?; - let source_position = source.position(target)?.get(); - if cancelled() { - return Err(MtpWindowError::Cancelled); - } - if spec.remaining == 0 { - return Ok(MtpVerifiedWindow { - tokens: Vec::new(), - latest: source, - eos: false, - draft_steps: 0, - }); - } - if Some(first) == spec.eos { - return Ok(MtpVerifiedWindow { - tokens: Vec::new(), - latest: source, - eos: true, - draft_steps: 0, - }); - } - let limit = window_limit(source_position, spec.depth, spec.remaining)?; - let target_prior = target.checkpoint()?; - let mut draft_priors = reserve(1)?; - draft_priors.push(self.draft.checkpoint()?); - let mut candidates = reserve(limit + 1)?; - candidates.push(first); - let mut tokens = reserve(limit)?; - let mut latest = Some(source); - - let result = (|| { - let mut previous = None; - // All draft work is anchored to the original current target prefix. - // No source/product accessor from that prefix is used after target advance. - for _ in 0..limit { - if cancelled() { - return Err(MtpWindowError::Cancelled); - } - let candidate = *candidates.last().ok_or(Error::IdentityMismatch)?; - if Some(candidate) == spec.eos { - break; - } - let input = match previous.as_ref() { - Some(product) => { - MtpInput::from_previous(binding, target, &self.draft, product, cache)? - } - None => MtpInput::from_target( - binding, - target, - &self.draft, - latest.as_ref().ok_or(Error::IdentityMismatch)?, - candidate, - cache, - )?, - }; - let product = mtp::step(binding, target, &mut self.draft, input, output, cache)?; - candidates.push(product.predicted(binding, target)?); - previous = Some(product); - } - drop(previous); - let draft_steps = candidates.len() - 1; - // A matching token does not make its speculative residual/KV the - // actual target residual/KV. Discard the entire transient chain. - self.draft.restore(&draft_priors[0])?; - draft_priors.clear(); - // Rewind increments the draft epoch. The old checkpoint must never - // be used by failure rollback after real catch-up starts. If minting - // fails, the draft is already initial and no catch-up has occurred. - draft_priors.push(self.draft.checkpoint()?); - let mut expected = first; - let mut eos = false; - for candidate in candidates.iter().take(limit) { - if cancelled() { - return Err(MtpWindowError::Cancelled); - } - // The authoritative target prediction controls both acceptance - // and EOS. A draft-only EOS cannot end a target generation. - if Some(expected) == spec.eos { - eos = true; - break; - } - if *candidate != expected { - break; - } - let offset = u64::try_from(tokens.len()).map_err(|_| Error::Overflow)?; - let position = source_position - .checked_add(1) - .and_then(|p| p.checked_add(offset)) - .ok_or(Error::Overflow)?; - // Rebuild persistent cell i from CURRENT actual target R_i and - // verified token i+1 before target advancement invalidates R_i. - // Do not call warm(): its nested rewind would invalidate this - // window's fresh-epoch rollback checkpoint on failure. - let input = MtpInput::from_target( - binding, - target, - &self.draft, - latest.as_ref().ok_or(Error::IdentityMismatch)?, - expected, - cache, - )?; - mtp::warm_step(binding, target, &mut self.draft, input, cache)?; - if cancelled() { - return Err(MtpWindowError::Cancelled); - } - let product = QwenForward::step_for_mtp_cached( - binding, - expected, - Position::new(position, crate::qwen_forward::contract::position_dimension())?, - target, - output, - kar_cache.as_deref_mut(), - Some(cache), - Some(dense_cache), - )?; - // Read the new prediction while this product is still current. - expected = product.predicted(target)?; - latest = Some(product); - tokens.push(*candidate); - } - if Some(expected) == spec.eos { - eos = true; - } - if cancelled() { - return Err(MtpWindowError::Cancelled); - } - let product = latest.take().ok_or(Error::IdentityMismatch)?; - // Exactly k real catch-up cells precede the current target product - // at p+k. Leave that final cell for the next window; neither rejected - // cells nor any speculative residual survive into its prefix. - Ok((product, eos, draft_steps)) - })(); - match result { - Ok((product, eos, draft_steps)) => Ok(MtpVerifiedWindow { - tokens, - latest: product, - eos, - draft_steps, - }), - Err(error) => { - if let MtpWindowError::Forward(cause) = error { - target.note_mtp_failure(&cause); - } - // Attempt both restores even when sticky CUDA failure prevents - // target restoration. Never return any tokens from this branch. - let target_restore = target.restore_checkpoint(&target_prior); - let draft_restore = match draft_priors.first() { - Some(prior) => self.draft.restore(prior), - // Only reachable if remint failed immediately after rewind: - // no old-epoch access and the draft is already initial. - None => Ok(()), - }; - target_restore?; - draft_restore?; - Err(error) - } - } - } -} +mod impl_mtpdecoder_2; +mod impl_mtpdecoder_2_2; +mod impl_mtpdecoder_3; diff --git a/crates/leleka-runtime/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2.rs b/crates/leleka-runtime/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2.rs new file mode 100644 index 00000000..024ebc10 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2.rs @@ -0,0 +1,230 @@ +//! Moved out of the parent module by STRA-338: impl MtpDecoder. + +#[allow(unused_imports)] +use super::*; + + +impl MtpDecoder { + pub(crate) fn new(binding: &ModelBinding) -> Result { + Ok(Self { + draft: MtpSession::new(binding)?, + kv_prefill: None, + kv_prefill_host_charge: 0, + }) + } + + /// Fresh explicit outer256 policy, using the entire actual framed prompt. + /// The original Native constructor and retained continuations stay unchanged. + pub(crate) fn new_kv_prefill( + binding: &ModelBinding, + target: &QwenSession<'_>, + prompt: &[u32], + ) -> Result { + let mut decoder = Self::new(binding)?; + if prompt.len() == 1 { + return Ok(decoder); + } + if !(2..=crate::qwen_forward::contract::serving_cells() as usize).contains(&prompt.len()) { + return Err(Error::InvalidDimension); + } + // Admit this persistent baseline before allocating the owner/queue. + let host_charge = kv_prefill_host_charge(prompt.len())?; + if host_charge > 512 * 1024 * 1024 { + return Err(Error::InputAllocation); + } + let vocabulary = Dimension::new(248320)?; + let mut tokens = reserve(prompt.len())?; + for &token in prompt { + tokens.push(TokenId::new(u64::from(token), vocabulary)?); + } + decoder.kv_prefill = Some(mtp::MtpKvPrefill::new( + binding, + target, + &decoder.draft, + &tokens, + )?); + decoder.kv_prefill_host_charge = host_charge; + Ok(decoder) + } + + /// Persistent baseline remains charged while any warming owner is live. + pub(crate) fn prefill_host_remaining(&self, available: usize) -> Result { + available + .checked_sub(self.kv_prefill_host_charge) + .ok_or(Error::InputAllocation) + } + + /// Require the actual final target head and the jointly published real + /// draft before the first window; then release the warming certificate. + pub(crate) fn finish_kv_prefill( + &mut self, + binding: &ModelBinding, + target: &QwenSession<'_>, + source: &TargetStepProduct, + committed: &[u32], + ) -> Result<()> { + if let Some(owner) = self.kv_prefill.as_ref() { + owner.validate_ready(binding, &self.draft, target, source)?; + self.validate_resume(binding, target, source, committed)?; + self.kv_prefill = None; + self.kv_prefill_host_charge = 0; + } + Ok(()) + } + + /// Closed admission for the actor's single resident successful prefix. + /// Checks the actual committed target product and the actual draft prefix; + /// numerical equality or position alone never mints a reuse capability. + pub(crate) fn validate_resume( + &self, + binding: &ModelBinding, + target: &QwenSession<'_>, + source: &TargetStepProduct, + committed: &[u32], + ) -> Result<()> { + let (token, position, _, origin) = source.mtp_source(binding, target)?; + if committed.is_empty() + || committed.len() as u64 > crate::qwen_forward::contract::serving_cells() + || position.get().checked_add(1) != Some(committed.len() as u64) + || committed.last().copied() != Some(token.get()) + { + return Err(Error::IdentityMismatch); + } + let frame = self + .draft + .frame(binding, position, source.predicted(target)?, origin)?; + frame.validate(binding, target)?; + self.draft.prior(&frame)?; + Ok(()) + } + + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(crate) fn test_prefix_snapshot( + &self, + binding: &ModelBinding, + target: &QwenSession<'_>, + source: &TargetStepProduct, + committed: &[u32], + ) -> Result { + self.validate_resume(binding, target, source, committed)?; + let (_, position, _, origin) = source.mtp_source(binding, target)?; + let frame = self + .draft + .frame(binding, position, source.predicted(target)?, origin)?; + frame.validate(binding, target)?; + self.draft.test_prefix_snapshot(binding, &frame) + } + + /// Prefill every known-next prompt edge, except the final prompt product. + /// A fresh draft starts at position zero; skipped edges cannot be repaired + /// by silently resetting or creating a later-position draft. + pub(crate) fn warm( + &mut self, + binding: &ModelBinding, + target: &mut QwenSession<'_>, + source: &TargetStepProduct, + known_next: TokenId, + output: &OutputStage<'_, '_>, + cache: &MoeWeightCache<'_>, + ) -> Result<()> { + let prior = self.draft.checkpoint()?; + let result = (|| { + let input = + MtpInput::from_target(binding, target, &self.draft, source, known_next, cache)?; + mtp::step(binding, target, &mut self.draft, input, output, cache)?; + Ok(()) + })(); + if let Err(error) = result { + target.note_mtp_failure(&error); + self.draft.restore(&prior)?; + return Err(error); + } + Ok(()) + } + + /// Resident final target product plus the authoritative first appended input. + /// This known-next edge commits genuine draft state without an unused head. + pub(crate) fn warm_retained( + &mut self, + binding: &ModelBinding, + target: &mut QwenSession<'_>, + source: &TargetStepProduct, + known_next: TokenId, + cache: &MoeWeightCache<'_>, + ) -> Result<()> { + let prior = self.draft.checkpoint()?; + let result = (|| { + let input = + MtpInput::from_target(binding, target, &self.draft, source, known_next, cache)?; + mtp::warm_step(binding, target, &mut self.draft, input, cache) + })(); + if let Err(error) = result { + target.note_mtp_failure(&error); + self.draft.restore(&prior)?; + return Err(error); + } + Ok(()) + } + + pub(crate) fn warm_prefill( + &mut self, + binding: &ModelBinding, + target: &mut QwenSession<'_>, + source: &PrefillStepProduct, + known_next: TokenId, + cache: &MoeWeightCache<'_>, + ) -> Result<()> { + let prior = self.draft.checkpoint()?; + let result = (|| { + let input = + MtpInput::from_prefill(binding, target, &self.draft, source, known_next, cache)?; + mtp::warm_step(binding, target, &mut self.draft, input, cache) + })(); + if let Err(error) = result { + target.note_mtp_failure(&error); + self.draft.restore(&prior)?; + return Err(error); + } + Ok(()) + } + + #[allow(clippy::too_many_arguments)] + pub(crate) fn window<'driver>( + &mut self, + binding: &ModelBinding, + source: TargetStepProduct, + target: &mut QwenSession<'driver>, + output: &OutputStage<'_, '_>, + kar_cache: Option<&mut KarPleCache<'_>>, + cache: &mut MoeWeightCache<'driver>, + dense_cache: &DenseWeightCache<'_>, + spec: MtpWindowSpec, + cancelled: impl FnMut() -> bool, + ) -> std::result::Result { + if cache.requires_iq3_mmq_admission() { + self.window_batched( + binding, + source, + target, + output, + kar_cache, + cache, + dense_cache, + spec, + cancelled, + ) + } else { + self.window_scalar( + binding, + source, + target, + output, + kar_cache, + cache, + dense_cache, + spec, + cancelled, + ) + } + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2_2.rs b/crates/leleka-runtime/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2_2.rs new file mode 100644 index 00000000..5c0d5d11 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2_2.rs @@ -0,0 +1,223 @@ +//! Moved out of the parent module by STRA-338: impl MtpDecoder (2). + +#[allow(unused_imports)] +use super::*; + + +impl MtpDecoder { + + /// Selected only by the existing explicit IQ3 integer/native Down policy. + /// Draft depth remains configured; target batch capacity is separately + /// admitted. Only predictions consumed by that capacity are generated/countable. + #[allow(clippy::too_many_arguments)] + pub(in super::super) fn window_batched<'driver>( + &mut self, + binding: &ModelBinding, + source: TargetStepProduct, + target: &mut QwenSession<'driver>, + output: &OutputStage<'_, '_>, + mut kar_cache: Option<&mut KarPleCache<'_>>, + cache: &mut MoeWeightCache<'driver>, + dense_cache: &DenseWeightCache<'_>, + spec: MtpWindowSpec, + mut cancelled: impl FnMut() -> bool, + ) -> std::result::Result { + source.mtp_source(binding, target)?; + let first = source.predicted(target)?; + let source_position = source.position(target)?.get(); + if cancelled() { + return Err(MtpWindowError::Cancelled); + } + if spec.remaining == 0 || Some(first) == spec.eos { + return Ok(MtpVerifiedWindow { + tokens: Vec::new(), + latest: source, + eos: spec.remaining != 0 && Some(first) == spec.eos, + draft_steps: 0, + }); + } + if self.kv_prefill.is_some() || !cache.requires_iq3_mmq_admission() { + return Err(Error::IdentityMismatch.into()); + } + let limit = window_limit(source_position, spec.depth, spec.remaining)?; + let reuse_first_seed = limit > 1 && first_seed_reuse_enabled(cache); + let seed_host_charge = if reuse_first_seed { self.draft.first_seed_host_charge()? } else { 0 }; + let host_remaining = self.prefill_host_remaining(512 * 1024 * 1024)?; + let host_remaining = if reuse_first_seed { + host_remaining.checked_sub(seed_host_charge) + .ok_or(Error::InputAllocation)? + } else { host_remaining }; + // Pure complete-state admission before any draft/canonical mutation. + let capacity = QwenForward::mtp_target_window_capacity( + binding, + &source, + spec.eos, + target, + limit, + if cache.uses_strata_adaptive_experts() { + // Independent actual CPU wave and ephemeral staging coexist. + // Both are inside the unchanged 512MiB request admission. + host_remaining.checked_sub((48 + 16) * 1024 * 1024).ok_or(Error::InputAllocation)? + } else { host_remaining }, + )?; + let target_prior = target.checkpoint()?; + let mut draft_priors = reserve(1)?; + draft_priors.push(self.draft.checkpoint()?); + let mut candidates = reserve(limit + 1)?; + candidates.push(first); + let mut tokens = reserve(capacity)?; + let result = (|| { + let mut previous = None; + let mut first_seed = None; + let needed_predictions = needed_draft_predictions(capacity, limit)?; + for _ in 0..needed_predictions { + if cancelled() { + return Err(MtpWindowError::Cancelled); + } + let candidate = *candidates.last().ok_or(Error::IdentityMismatch)?; + if Some(candidate) == spec.eos { + break; + } + let input = match previous.as_ref() { + Some(product) => { + MtpInput::from_previous(binding, target, &self.draft, product, cache)? + } + None => MtpInput::from_target( + binding, + target, + &self.draft, + &source, + candidate, + cache, + )?, + }; + let seed_frame = if reuse_first_seed && previous.is_none() { + Some(input.frame().clone()) + } else { None }; + let product = mtp::step(binding, target, &mut self.draft, input, output, cache)?; + if let Some(frame) = seed_frame { + first_seed = Some((self.draft.checkpoint_first_seed(seed_host_charge)?, frame)); + } + candidates.push(product.predicted(binding, target)?); + previous = Some(product); + } + drop(previous); + let draft_steps = candidates.len().checked_sub(1).ok_or(Error::Overflow)?; + if let Some((seed, frame)) = first_seed { + // Recheck the authoritative target source before coupled restore. + source.mtp_source(binding, target)?; + if source.predicted(target)? != frame.token() + || source.position(target)? != frame.position() + { + return Err(Error::IdentityMismatch.into()); + } + self.draft.restore_first_seed( + binding, target, &frame, &seed, &mut draft_priors[0], + )?; + // The seed is now the actual committed draft; dropping its extra + // checkpoint precedes target journal/catchup allocation. + } else { + self.draft.restore(&draft_priors[0])?; + draft_priors.clear(); + // The old speculative epoch is unusable after rewind. Failure + // rollback retains only this new checkpoint; no nested warm rewind. + draft_priors.push(self.draft.checkpoint()?); + if cancelled() { + return Err(MtpWindowError::Cancelled); + } + let input = MtpInput::from_target(binding, target, &self.draft, &source, first, cache)?; + mtp::warm_step(binding, target, &mut self.draft, input, cache)?; + } + if cancelled() { + return Err(MtpWindowError::Cancelled); + } + let rows = capacity.min(limit).min(candidates.len()); + let mut stage_cancelled = false; + // Complete the previous refill after genuine draft compute but before + // target window journal allocation, preserving the shared host cap. + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if cache.uses_strata_adaptive_experts() { cache.poll_strata_adaptive(binding, true)?; } + let pending_result = { + let mut observe_cancel = || { + let current = cancelled(); + stage_cancelled |= current; + current + }; + QwenForward::prepare_mtp_target_window( + binding, + &source, + &candidates[..rows], + spec.eos, + target, + output, + kar_cache.as_deref_mut(), + cache, + dense_cache, + host_remaining, + &mut observe_cancel, + ) + }; + let pending = + pending_result.map_err(|error| window_stage_error(error, stage_cancelled))?; + let accepted = pending.accepted_rows(); + if accepted == 0 || accepted > rows || accepted > capacity || accepted > spec.remaining + { + return Err(Error::IdentityMismatch.into()); + } + // Capacity was reserved before work; accepted IDs/counters are + // assembled before either owner commits. They stay private on error. + tokens.extend_from_slice(&candidates[..accepted]); + let mut stage_cancelled = false; + let published = { + let mut observe_cancel = || { + let current = cancelled(); + stage_cancelled |= current; + current + }; + pending.publish_joint_with_gdn_replay(binding, &mut self.draft, cache, Some(dense_cache), &mut observe_cancel) + }; + let product = published.map_err(|error| window_stage_error(error, stage_cancelled))?; + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if cache.uses_strata_adaptive_experts() { + cache.poll_strata_adaptive(binding, false)?; + cache.strata_adaptive_completed_window(binding)?; + } + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + batch_gpu::after_joint_publish(); + if cancelled() { + return Err(MtpWindowError::Cancelled); + } + let eos = Some(product.predicted(target)?) == spec.eos; + Ok((product, eos, draft_steps)) + })(); + match result { + Ok((product, eos, draft_steps)) => Ok(MtpVerifiedWindow { + tokens, + latest: product, + eos, + draft_steps, + }), + Err(error) => { + if let MtpWindowError::Forward(cause) = error { + target.note_mtp_failure(&cause); + } + // Attempt BOTH full restores even when the first is refused by + // poison. Retain the primary error; never return private IDs. + let target_restore = target.restore_checkpoint(&target_prior); + let draft_restore = match draft_priors.first() { + Some(prior) => self.draft.restore(prior), + None => Ok(()), // remint failed before actual catchup + }; + if let Err(cause) = target_restore { + target.note_mtp_failure(&cause); + } + #[cfg(test)] + if target_restore.is_err() || draft_restore.is_err() { + eprintln!("MTP candidate rollback primary={error:?} target={target_restore:?} draft={draft_restore:?}"); + } + let _ = draft_restore; + Err(error) + } + } + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_3.rs b/crates/leleka-runtime/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_3.rs new file mode 100644 index 00000000..303c6320 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_3.rs @@ -0,0 +1,181 @@ +//! Moved out of the parent module by STRA-338: impl MtpDecoder (3). + +#[allow(unused_imports)] +use super::*; + + +impl MtpDecoder { + + #[allow(clippy::too_many_arguments)] + pub(crate) fn window_scalar( + &mut self, + binding: &ModelBinding, + source: TargetStepProduct, + target: &mut QwenSession<'_>, + output: &OutputStage<'_, '_>, + mut kar_cache: Option<&mut KarPleCache<'_>>, + cache: &mut MoeWeightCache<'_>, + dense_cache: &DenseWeightCache<'_>, + spec: MtpWindowSpec, + mut cancelled: impl FnMut() -> bool, + ) -> std::result::Result { + source.mtp_source(binding, target)?; + let first = source.predicted(target)?; + let source_position = source.position(target)?.get(); + if cancelled() { + return Err(MtpWindowError::Cancelled); + } + if spec.remaining == 0 { + return Ok(MtpVerifiedWindow { + tokens: Vec::new(), + latest: source, + eos: false, + draft_steps: 0, + }); + } + if Some(first) == spec.eos { + return Ok(MtpVerifiedWindow { + tokens: Vec::new(), + latest: source, + eos: true, + draft_steps: 0, + }); + } + let limit = window_limit(source_position, spec.depth, spec.remaining)?; + let target_prior = target.checkpoint()?; + let mut draft_priors = reserve(1)?; + draft_priors.push(self.draft.checkpoint()?); + let mut candidates = reserve(limit + 1)?; + candidates.push(first); + let mut tokens = reserve(limit)?; + let mut latest = Some(source); + + let result = (|| { + let mut previous = None; + // All draft work is anchored to the original current target prefix. + // No source/product accessor from that prefix is used after target advance. + for _ in 0..limit { + if cancelled() { + return Err(MtpWindowError::Cancelled); + } + let candidate = *candidates.last().ok_or(Error::IdentityMismatch)?; + if Some(candidate) == spec.eos { + break; + } + let input = match previous.as_ref() { + Some(product) => { + MtpInput::from_previous(binding, target, &self.draft, product, cache)? + } + None => MtpInput::from_target( + binding, + target, + &self.draft, + latest.as_ref().ok_or(Error::IdentityMismatch)?, + candidate, + cache, + )?, + }; + let product = mtp::step(binding, target, &mut self.draft, input, output, cache)?; + candidates.push(product.predicted(binding, target)?); + previous = Some(product); + } + drop(previous); + let draft_steps = candidates.len() - 1; + // A matching token does not make its speculative residual/KV the + // actual target residual/KV. Discard the entire transient chain. + self.draft.restore(&draft_priors[0])?; + draft_priors.clear(); + // Rewind increments the draft epoch. The old checkpoint must never + // be used by failure rollback after real catch-up starts. If minting + // fails, the draft is already initial and no catch-up has occurred. + draft_priors.push(self.draft.checkpoint()?); + let mut expected = first; + let mut eos = false; + for candidate in candidates.iter().take(limit) { + if cancelled() { + return Err(MtpWindowError::Cancelled); + } + // The authoritative target prediction controls both acceptance + // and EOS. A draft-only EOS cannot end a target generation. + if Some(expected) == spec.eos { + eos = true; + break; + } + if *candidate != expected { + break; + } + let offset = u64::try_from(tokens.len()).map_err(|_| Error::Overflow)?; + let position = source_position + .checked_add(1) + .and_then(|p| p.checked_add(offset)) + .ok_or(Error::Overflow)?; + // Rebuild persistent cell i from CURRENT actual target R_i and + // verified token i+1 before target advancement invalidates R_i. + // Do not call warm(): its nested rewind would invalidate this + // window's fresh-epoch rollback checkpoint on failure. + let input = MtpInput::from_target( + binding, + target, + &self.draft, + latest.as_ref().ok_or(Error::IdentityMismatch)?, + expected, + cache, + )?; + mtp::warm_step(binding, target, &mut self.draft, input, cache)?; + if cancelled() { + return Err(MtpWindowError::Cancelled); + } + let product = QwenForward::step_for_mtp_cached( + binding, + expected, + Position::new(position, crate::qwen_forward::contract::position_dimension())?, + target, + output, + kar_cache.as_deref_mut(), + Some(cache), + Some(dense_cache), + )?; + // Read the new prediction while this product is still current. + expected = product.predicted(target)?; + latest = Some(product); + tokens.push(*candidate); + } + if Some(expected) == spec.eos { + eos = true; + } + if cancelled() { + return Err(MtpWindowError::Cancelled); + } + let product = latest.take().ok_or(Error::IdentityMismatch)?; + // Exactly k real catch-up cells precede the current target product + // at p+k. Leave that final cell for the next window; neither rejected + // cells nor any speculative residual survive into its prefix. + Ok((product, eos, draft_steps)) + })(); + match result { + Ok((product, eos, draft_steps)) => Ok(MtpVerifiedWindow { + tokens, + latest: product, + eos, + draft_steps, + }), + Err(error) => { + if let MtpWindowError::Forward(cause) = error { + target.note_mtp_failure(&cause); + } + // Attempt both restores even when sticky CUDA failure prevents + // target restoration. Never return any tokens from this branch. + let target_restore = target.restore_checkpoint(&target_prior); + let draft_restore = match draft_priors.first() { + Some(prior) => self.draft.restore(prior), + // Only reachable if remint failed immediately after rewind: + // no old-epoch access and the draft is already initial. + None => Ok(()), + }; + target_restore?; + draft_restore?; + Err(error) + } + } + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/impl_prefixserve.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/impl_prefixserve.rs index e8ea6eba..71b079b1 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/impl_prefixserve.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/impl_prefixserve.rs @@ -3,415 +3,7 @@ #[allow(unused_imports)] use super::*; - -impl PrefixServe { - /// `identity`: whatever makes two runtimes' caches interchangeable (model digest, KV format...), hashed with the - /// block size into the summary's namespace. - pub(in super::super) fn new(cfg: PrefixConfig, capacity: usize, budget_bytes: u64, identity: &str) -> Self { - let block_tokens = cfg.resolved_block(capacity); - let namespace = fingerprint(&format!("{identity}|block={block_tokens}|chain={}", crate::prefix_cache::CHAIN_VERSION)); - let store = PrefixStore::new(StoreConfig { - block_tokens, - budget_bytes: usize::try_from(budget_bytes).unwrap_or(usize::MAX), - max_nodes: cfg.max_nodes, - policy: cfg.policy.clone(), - }); - Self { - cfg, - block_tokens, - namespace, - store, - live: Vec::new(), - req: None, - seen_state_bytes: None, - seen_block_bytes: None, - park_ms_request: 0.0, - consider_ms_request: 0.0, - admitted_request: 0, - bypass: false, - last_match_us: 0.0, - last_import_split: (0.0, 0.0), - configured_budget: usize::try_from(budget_bytes).unwrap_or(usize::MAX), - shed: false, - note: None, - } - } - - /// Apply the memory governor's shed directive (`Governor::directive`): `Some(bytes)` evicts down to that budget (lowest - /// expected-value-per-byte first), `None` restores the configured one after a shed. Returns the bytes evicted. - pub(in super::super) fn apply_shed(&mut self, target: Option, governor: &leleka_memory::Governor) -> usize { - match target { - Some(bytes) => { - let bytes = usize::try_from(bytes).unwrap_or(usize::MAX).min(self.configured_budget); - if bytes >= self.store.config().budget_bytes { - return 0; - } - let before = self.store.bytes(); - self.store.set_budget(bytes); - self.shed = true; - let freed = before.saturating_sub(self.store.bytes()); - governor.note_evicted(freed as u64); - if freed > 0 { - // the freed blocks sit in the allocator's arenas until they are returned: without this the shed would not move MemAvailable - leleka_memory::heap::trim(); - } - freed - } - None => { - if self.shed { - self.store.set_budget(self.configured_budget); - self.shed = false; - } - 0 - } - } - } - - - /// (import, draft re-anchoring) milliseconds of the last hit. - pub(in super::super) fn last_import_split(&self) -> (f64, f64) { - self.last_import_split - } - - /// Microseconds the last lookup took (also on a miss). - pub(in super::super) fn last_match_us(&self) -> f64 { - self.last_match_us - } - - /// While set, requests read their whole prompt from 0 on the grid and leave the store alone. - pub(in super::super) fn set_bypass(&mut self, bypass: bool) { - self.bypass = bypass; - } - - pub(in super::super) fn block_tokens(&self) -> usize { - self.block_tokens - } - pub(in super::super) fn namespace(&self) -> u64 { - self.namespace - } - pub(in super::super) fn stats(&self) -> &Stats { - self.store.stats() - } - pub(in super::super) fn bytes(&self) -> usize { - self.store.bytes() - } - pub(in super::super) fn budget_bytes(&self) -> usize { - self.store.config().budget_bytes - } - pub(in super::super) fn node_count(&self) -> usize { - self.store.node_count() - } - pub(in super::super) fn block_count(&self) -> usize { - self.store.block_count() - } - pub(in super::super) fn live_tokens(&self) -> usize { - self.live.len() - } - pub(in super::super) fn summary(&self, max_heads: usize) -> PrefixSummary { - PrefixSummary::build(&self.store, self.namespace, max_heads) - } - /// The `prefix_match` query: how much of a prompt (given as its chain) is cached. - pub(in super::super) fn prefix_match(&self, chain: &[u64]) -> PrefixMatch { - PrefixMatch { - namespace: crate::prefix_cache::summary::hex(self.namespace), - block_tokens: self.block_tokens as u32, - cached_tokens: self.store.prefix_match(chain) as u32, - } - } - #[cfg(test)] - pub(in super::super) fn store(&self) -> &PrefixStore { - &self.store - } - - /// The device state is unknown or gone: drop every checkpoint and the live claim. - pub(in super::super) fn invalidate(&mut self) { - self.store.clear(); - self.live.clear(); - self.req = None; - } - - /// Head of a request: install the deepest checkpoint that is a prefix of `prompt`, if any (`None` = read from 0; - /// the caller resets the owners). An error leaves the owners in an unknown place; the caller drops the cache. - pub(in super::super) fn begin>( - &mut self, - device: &mut D, - prompt: &[i32], - ) -> Result, Error> { - let g = self.block_tokens; - self.park_ms_request = 0.0; - self.consider_ms_request = 0.0; - self.admitted_request = 0; - if self.bypass { - self.req = None; - return Ok(None); - } - self.store.tick_at(prompt.len(), wall_ms()); - let limit = prompt.len().saturating_sub(1); - self.req = Some(Req { limit, last_grid: limit / g * g }); - let lookup = Instant::now(); - let found = self.store.longest_match(prompt, limit); - let match_us = lookup.elapsed().as_secs_f64() * 1e6; - let Some(hit) = found else { - self.store.record_miss(); - self.last_match_us = match_us; - // the caller resets the owners to the empty prompt, which also rewrites the first index row: no cell of the - // buffer is claimed any more, even if the request is cancelled before its first chunk - self.live.clear(); - return Ok(None); - }; - // Cells of the positional buffer that already hold this prefix. A request that extends everything the buffer - // holds is the session's own continuation (no copy needed beyond what the buffer lacks); one that leaves it - // somewhere inside came after another session. Whether the HIT is shared evidence is a different question: it is - // when histories fork below the node (`is_branch_point`), whichever session ran last. - let common_full = lcp(&self.live, &prompt[..limit]); - let continuation = !self.live.is_empty() && common_full == self.live.len(); - let switched = !continuation; - let branch = self.store.is_branch_point(hit.key); - let common = common_full.min(hit.tokens); - let copy = common < hit.tokens; - let started = Instant::now(); - let full = hit.tokens / g; - let first_block = (common / g).min(full); - let mut blocks = if copy { self.store.blocks_from(hit.key, first_block).ok_or(Error::IdentityMismatch)? } else { Vec::new() }; - if copy { - // a request-end checkpoint also carries the cells after its last full block - if let Some((tail, _, _)) = self.store.tail_of(hit.key) { - blocks.push((full, tail)); - } - } - let state = self.store.node_payload(hit.key).ok_or(Error::IdentityMismatch)?; - // the import overwrites every cell from the first named block on - self.live.truncate(if blocks.is_empty() { common } else { first_block * g }); - device.import(state, &blocks)?; - let imported_ms = started.elapsed().as_secs_f64() * 1e3; - device.restore_draft(state, hit.tokens)?; - let copied_tokens: usize = blocks.iter().map(|(j, _)| if *j < full { g } else { hit.tokens - full * g }).sum(); - let import_ms = started.elapsed().as_secs_f64() * 1e3; - self.last_import_split = (imported_ms, import_ms - imported_ms); - self.live.clear(); - self.live.extend_from_slice(&prompt[..hit.tokens]); - self.last_match_us = match_us; - self.store.record_hit_as(&hit, branch); - Ok(Some(Start { resume: hit.tokens, switched, branch, copied_tokens, import_ms, match_us })) - } - - /// The prefill is about to write the cells from `first` on. - pub(in super::super) fn before_chunk(&mut self, first: usize) { - self.live.truncate(first); - } - - /// A chunk ending at `end` was published: the cells below `end` are this prompt's; maybe checkpoint there. - /// An error means the checkpoint could not be built (the caller drops the cache, the request goes on). - pub(in super::super) fn after_chunk>( - &mut self, - device: &mut D, - prompt: &[i32], - end: usize, - ) -> Result { - let g = self.block_tokens; - // a long prefill can outlast a change of memory pressure: follow the governor between chunks, not only between requests - if let Some(governor) = leleka_memory::Governor::global() { - let directive = governor.directive(self.store.bytes() as u64); - self.apply_shed(directive.prefix_budget, governor); - } - if self.live.len() <= end { - let have = self.live.len(); - self.live.extend_from_slice(&prompt[have..end]); - } - let Some(req) = self.req.as_ref() else { return Ok(ChunkOutcome::Nothing) }; - self.note = None; - if end == 0 || end % g != 0 || end > req.limit { - return Ok(ChunkOutcome::Nothing); - } - let frontier = end == req.last_grid; - let (est_state, est_block) = device.estimate(g); - let est_state = self.seen_state_bytes.unwrap_or(est_state); - let est_block = self.seen_block_bytes.unwrap_or(est_block); - let considering = Instant::now(); - let verdict = self.store.consider(&prompt[..end], frontier, est_state, est_block); - self.consider_ms_request += considering.elapsed().as_secs_f64() * 1e3; - let candidate = match verdict { - Consider::Exists => return Ok(ChunkOutcome::Exists), - Consider::Rejected(why) => { - self.note = Some(format!("grid point {end} rejected by the policy: {why:?} (store {} MiB of {} MiB)", self.store.bytes() >> 20, self.configured_budget >> 20)); - return Ok(ChunkOutcome::Rejected(why)); - } - Consider::Admit(candidate) => candidate, - }; - let additional = (est_state + candidate.missing.len() * est_block) as u64; - let available = admission_reading(device.available_memory(), additional, self.cfg.memory_floor); - if !budget::admit_growth(available, additional, self.cfg.memory_floor) { - self.store.abort(candidate); - self.note = Some(format!( - "grid point {end}: low memory, available {} MiB, additional {} MiB, floor {} MiB", - available.map_or_else(|| "unknown".to_owned(), |b| (b >> 20).to_string()), - additional >> 20, - self.cfg.memory_floor >> 20 - )); - return Ok(ChunkOutcome::LowMemory); - } - let started = Instant::now(); - let state = device.park_state()?; - if device.position()? != end as u64 { - return Err(Error::IdentityMismatch); - } - let mut blocks = Vec::with_capacity(candidate.missing.len()); - for &j in &candidate.missing { - blocks.push((j, device.park_block(j * g, g)?)); - } - self.seen_state_bytes = Some(state.byte_size()); - if let Some((_, block)) = blocks.first() { - self.seen_block_bytes = Some(block.byte_size()); - } - let new_blocks = blocks.len(); - let bytes = state.byte_size() + blocks.iter().map(|(_, b)| b.byte_size()).sum::(); - let park_ms = started.elapsed().as_secs_f64() * 1e3; - self.store.commit(candidate, &prompt[..end], state, blocks).map_err(|_| Error::IdentityMismatch)?; - self.park_ms_request += park_ms; - self.admitted_request += 1; - Ok(ChunkOutcome::Admitted { tokens: end, new_blocks, bytes, park_ms }) - } - - /// The end of the prompt's prefill: the session stands at `prompt.len() - 1`. With `TailMode::Prompt` or `Reply`, checkpoint - /// there (a request-end checkpoint), unless that is a grid point. - pub(in super::super) fn after_prefill>(&mut self, device: &mut D, prompt: &[i32]) -> Result { - self.note = None; - if self.cfg.tail == TailMode::Off || self.bypass || self.req.is_none() { - self.note = Some(format!("no tail checkpoint: tail {:?}, bypass {}, request {}", self.cfg.tail, self.bypass, self.req.is_some())); - return Ok(ChunkOutcome::Nothing); - } - let end = prompt.len().saturating_sub(1); - self.admit_tail(device, &prompt[..end], None) - } - - /// The end of the decode: the session stands at `consumed.len()` (the prompt and the committed reply), settled, with the draft - /// ring in step. With `TailMode::Reply`, checkpoint there; the cells past the prompt are decode-produced. - /// The reason the last checkpoint attempt was not taken, with the numbers; read once. - pub(in super::super) fn take_note(&mut self) -> Option { - self.note.take() - } - - pub(in super::super) fn after_decode>(&mut self, device: &mut D, consumed: &[i32]) -> Result { - self.note = None; - if self.cfg.tail != TailMode::Reply || self.bypass || self.req.is_none() { - return Ok(ChunkOutcome::Nothing); - } - // the prompt-end checkpoint of this request stays: a client that resends the history without the reasoning of the reply - // continues from the prompt, not from the decode end - let keep = self.req.as_ref().map(|r| r.limit); - let outcome = self.admit_tail(device, consumed, keep)?; - if matches!(outcome, ChunkOutcome::Admitted { .. } | ChunkOutcome::Exists) { - // the buffer holds exactly these cells, and the node has a copy of them - self.live.clear(); - self.live.extend_from_slice(consumed); - } - Ok(outcome) - } - - pub(super) fn admit_tail>(&mut self, device: &mut D, tokens: &[i32], keep_end: Option) -> Result { - let g = self.block_tokens; - // a grid point is a pure checkpoint of its own (and a node below one block has no blocks to hang on) - let position = device.position()?; - if tokens.len() <= g || tokens.len() % g == 0 || position != tokens.len() as u64 { - self.note = Some(format!("not a tail position: {} tokens, grid {g}, the session stands at {position}", tokens.len())); - return Ok(ChunkOutcome::Nothing); - } - let (est_state, est_block) = device.estimate(g); - let est_state = self.seen_state_bytes.unwrap_or(est_state); - let est_block = self.seen_block_bytes.unwrap_or(est_block); - let considering = Instant::now(); - let verdict = self.store.consider_tail(tokens, true, est_state, est_block); - self.consider_ms_request += considering.elapsed().as_secs_f64() * 1e3; - let candidate = match verdict { - Consider::Exists => { - self.note = Some(format!("a checkpoint at {} tokens exists already", tokens.len())); - return Ok(ChunkOutcome::Exists); - } - Consider::Rejected(why) => { - self.note = Some(format!("rejected by the policy at {} tokens: {why:?} (store {} MiB of {} MiB)", tokens.len(), self.store.bytes() >> 20, self.configured_budget >> 20)); - return Ok(ChunkOutcome::Rejected(why)); - } - Consider::Admit(candidate) => candidate, - }; - let additional = (est_state + candidate.missing.len() * est_block + est_block) as u64; - let available = admission_reading(device.available_memory(), additional, self.cfg.memory_floor); - let missing = candidate.missing.len(); - if !budget::admit_growth(available, additional, self.cfg.memory_floor) { - self.store.abort(candidate); - self.note = Some(format!( - "low memory at {} tokens: available {} MiB, additional {} MiB (state {} + {} new blocks of {} MiB + the tail), floor {} MiB", - tokens.len(), - available.map_or_else(|| "unknown".to_owned(), |b| (b >> 20).to_string()), - additional >> 20, - est_state >> 20, - missing, - est_block >> 20, - self.cfg.memory_floor >> 20 - )); - return Ok(ChunkOutcome::LowMemory); - } - let started = Instant::now(); - let state = device.park_state()?; - if device.position()? != tokens.len() as u64 { - return Err(Error::IdentityMismatch); - } - let mut blocks = Vec::with_capacity(candidate.missing.len()); - for &j in &candidate.missing { - blocks.push((j, device.park_block(j * g, g)?)); - } - let full = tokens.len() / g; - let tail = device.park_tail(full * g, tokens.len() - full * g)?; - self.seen_state_bytes = Some(state.byte_size()); - let new_blocks = blocks.len(); - let bytes = state.byte_size() + tail.byte_size() + blocks.iter().map(|(_, b)| b.byte_size()).sum::(); - let park_ms = started.elapsed().as_secs_f64() * 1e3; - self.store.commit_tail_keeping(candidate, tokens, state, blocks, tail, keep_end).map_err(|_| Error::IdentityMismatch)?; - self.park_ms_request += park_ms; - self.admitted_request += 1; - Ok(ChunkOutcome::Admitted { tokens: tokens.len(), new_blocks, bytes, park_ms }) - } - - /// The request is over. `completed` is false when the owners are lost (the checkpoints and the live claim go); - /// a cancelled request is completed: its chunks kept the live claim honest. - pub(in super::super) fn finish(&mut self, completed: bool) { - self.req = None; - if !completed { - self.invalidate(); - } - } - - /// Admissions of the request just served and the time spent parking them. - pub(in super::super) fn request_parking(&self) -> (u64, f64, f64) { - (self.admitted_request, self.park_ms_request, self.consider_ms_request) - } - - /// The metrics line. - /// Drop the sessions nobody used for the retention time (called from the idle loop); returns how many nodes went. - pub(in super::super) fn expire_idle(&mut self) -> usize { - self.store.set_now(wall_ms()); - self.store.expire() - } - - pub(in super::super) fn describe(&self) -> String { - let s = self.store.stats(); - format!( - "prefix stats: nodes={} blocks={} used_mib={} budget_mib={} requests={} hits={} shared_hits={} misses={} reused_tokens={} prompt_tokens={} admitted={} rejected={} evicted={} expired={} already_cached={} live_tokens={}", - self.store.node_count(), - self.store.block_count(), - self.store.bytes() >> 20, - self.store.config().budget_bytes >> 20, - s.requests, - s.hits, - s.shared_hits, - s.misses, - s.reused_tokens, - s.prompt_tokens, - s.admitted, - s.rejected + s.rejected_after_build, - s.evicted, - s.expired, - s.already_cached, - self.live.len() - ) - } -} +#[path = "impl_prefixserve/impl_prefixserve_2.rs"] +mod impl_prefixserve_2; +#[path = "impl_prefixserve/impl_prefixserve_2_2.rs"] +mod impl_prefixserve_2_2; diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2.rs new file mode 100644 index 00000000..242294f8 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2.rs @@ -0,0 +1,203 @@ +//! Moved out of the parent module by STRA-338: impl PrefixServe. + +#[allow(unused_imports)] +use super::*; + + + +impl PrefixServe { + /// `identity`: whatever makes two runtimes' caches interchangeable (model digest, KV format...), hashed with the + /// block size into the summary's namespace. + pub(in super::super::super) fn new(cfg: PrefixConfig, capacity: usize, budget_bytes: u64, identity: &str) -> Self { + let block_tokens = cfg.resolved_block(capacity); + let namespace = fingerprint(&format!("{identity}|block={block_tokens}|chain={}", crate::prefix_cache::CHAIN_VERSION)); + let store = PrefixStore::new(StoreConfig { + block_tokens, + budget_bytes: usize::try_from(budget_bytes).unwrap_or(usize::MAX), + max_nodes: cfg.max_nodes, + policy: cfg.policy.clone(), + }); + Self { + cfg, + block_tokens, + namespace, + store, + live: Vec::new(), + req: None, + seen_state_bytes: None, + seen_block_bytes: None, + park_ms_request: 0.0, + consider_ms_request: 0.0, + admitted_request: 0, + bypass: false, + last_match_us: 0.0, + last_import_split: (0.0, 0.0), + configured_budget: usize::try_from(budget_bytes).unwrap_or(usize::MAX), + shed: false, + note: None, + } + } + + /// Apply the memory governor's shed directive (`Governor::directive`): `Some(bytes)` evicts down to that budget (lowest + /// expected-value-per-byte first), `None` restores the configured one after a shed. Returns the bytes evicted. + pub(in super::super::super) fn apply_shed(&mut self, target: Option, governor: &leleka_memory::Governor) -> usize { + match target { + Some(bytes) => { + let bytes = usize::try_from(bytes).unwrap_or(usize::MAX).min(self.configured_budget); + if bytes >= self.store.config().budget_bytes { + return 0; + } + let before = self.store.bytes(); + self.store.set_budget(bytes); + self.shed = true; + let freed = before.saturating_sub(self.store.bytes()); + governor.note_evicted(freed as u64); + if freed > 0 { + // the freed blocks sit in the allocator's arenas until they are returned: without this the shed would not move MemAvailable + leleka_memory::heap::trim(); + } + freed + } + None => { + if self.shed { + self.store.set_budget(self.configured_budget); + self.shed = false; + } + 0 + } + } + } + + + /// (import, draft re-anchoring) milliseconds of the last hit. + pub(in super::super::super) fn last_import_split(&self) -> (f64, f64) { + self.last_import_split + } + + /// Microseconds the last lookup took (also on a miss). + pub(in super::super::super) fn last_match_us(&self) -> f64 { + self.last_match_us + } + + /// While set, requests read their whole prompt from 0 on the grid and leave the store alone. + pub(in super::super::super) fn set_bypass(&mut self, bypass: bool) { + self.bypass = bypass; + } + + pub(in super::super::super) fn block_tokens(&self) -> usize { + self.block_tokens + } + pub(in super::super::super) fn namespace(&self) -> u64 { + self.namespace + } + pub(in super::super::super) fn stats(&self) -> &Stats { + self.store.stats() + } + pub(in super::super::super) fn bytes(&self) -> usize { + self.store.bytes() + } + pub(in super::super::super) fn budget_bytes(&self) -> usize { + self.store.config().budget_bytes + } + pub(in super::super::super) fn node_count(&self) -> usize { + self.store.node_count() + } + pub(in super::super::super) fn block_count(&self) -> usize { + self.store.block_count() + } + pub(in super::super::super) fn live_tokens(&self) -> usize { + self.live.len() + } + pub(in super::super::super) fn summary(&self, max_heads: usize) -> PrefixSummary { + PrefixSummary::build(&self.store, self.namespace, max_heads) + } + /// The `prefix_match` query: how much of a prompt (given as its chain) is cached. + pub(in super::super::super) fn prefix_match(&self, chain: &[u64]) -> PrefixMatch { + PrefixMatch { + namespace: crate::prefix_cache::summary::hex(self.namespace), + block_tokens: self.block_tokens as u32, + cached_tokens: self.store.prefix_match(chain) as u32, + } + } + #[cfg(test)] + pub(in super::super::super) fn store(&self) -> &PrefixStore { + &self.store + } + + /// The device state is unknown or gone: drop every checkpoint and the live claim. + pub(in super::super::super) fn invalidate(&mut self) { + self.store.clear(); + self.live.clear(); + self.req = None; + } + + /// Head of a request: install the deepest checkpoint that is a prefix of `prompt`, if any (`None` = read from 0; + /// the caller resets the owners). An error leaves the owners in an unknown place; the caller drops the cache. + pub(in super::super::super) fn begin>( + &mut self, + device: &mut D, + prompt: &[i32], + ) -> Result, Error> { + let g = self.block_tokens; + self.park_ms_request = 0.0; + self.consider_ms_request = 0.0; + self.admitted_request = 0; + if self.bypass { + self.req = None; + return Ok(None); + } + self.store.tick_at(prompt.len(), wall_ms()); + let limit = prompt.len().saturating_sub(1); + self.req = Some(Req { limit, last_grid: limit / g * g }); + let lookup = Instant::now(); + let found = self.store.longest_match(prompt, limit); + let match_us = lookup.elapsed().as_secs_f64() * 1e6; + let Some(hit) = found else { + self.store.record_miss(); + self.last_match_us = match_us; + // the caller resets the owners to the empty prompt, which also rewrites the first index row: no cell of the + // buffer is claimed any more, even if the request is cancelled before its first chunk + self.live.clear(); + return Ok(None); + }; + // Cells of the positional buffer that already hold this prefix. A request that extends everything the buffer + // holds is the session's own continuation (no copy needed beyond what the buffer lacks); one that leaves it + // somewhere inside came after another session. Whether the HIT is shared evidence is a different question: it is + // when histories fork below the node (`is_branch_point`), whichever session ran last. + let common_full = lcp(&self.live, &prompt[..limit]); + let continuation = !self.live.is_empty() && common_full == self.live.len(); + let switched = !continuation; + let branch = self.store.is_branch_point(hit.key); + let common = common_full.min(hit.tokens); + let copy = common < hit.tokens; + let started = Instant::now(); + let full = hit.tokens / g; + let first_block = (common / g).min(full); + let mut blocks = if copy { self.store.blocks_from(hit.key, first_block).ok_or(Error::IdentityMismatch)? } else { Vec::new() }; + if copy { + // a request-end checkpoint also carries the cells after its last full block + if let Some((tail, _, _)) = self.store.tail_of(hit.key) { + blocks.push((full, tail)); + } + } + let state = self.store.node_payload(hit.key).ok_or(Error::IdentityMismatch)?; + // the import overwrites every cell from the first named block on + self.live.truncate(if blocks.is_empty() { common } else { first_block * g }); + device.import(state, &blocks)?; + let imported_ms = started.elapsed().as_secs_f64() * 1e3; + device.restore_draft(state, hit.tokens)?; + let copied_tokens: usize = blocks.iter().map(|(j, _)| if *j < full { g } else { hit.tokens - full * g }).sum(); + let import_ms = started.elapsed().as_secs_f64() * 1e3; + self.last_import_split = (imported_ms, import_ms - imported_ms); + self.live.clear(); + self.live.extend_from_slice(&prompt[..hit.tokens]); + self.last_match_us = match_us; + self.store.record_hit_as(&hit, branch); + Ok(Some(Start { resume: hit.tokens, switched, branch, copied_tokens, import_ms, match_us })) + } + + /// The prefill is about to write the cells from `first` on. + pub(in super::super::super) fn before_chunk(&mut self, first: usize) { + self.live.truncate(first); + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2_2.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2_2.rs new file mode 100644 index 00000000..3e2aad5e --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2_2.rs @@ -0,0 +1,224 @@ +//! Moved out of the parent module by STRA-338: impl PrefixServe (2). + +#[allow(unused_imports)] +use super::*; + + + +impl PrefixServe { + + /// A chunk ending at `end` was published: the cells below `end` are this prompt's; maybe checkpoint there. + /// An error means the checkpoint could not be built (the caller drops the cache, the request goes on). + pub(in super::super::super) fn after_chunk>( + &mut self, + device: &mut D, + prompt: &[i32], + end: usize, + ) -> Result { + let g = self.block_tokens; + // a long prefill can outlast a change of memory pressure: follow the governor between chunks, not only between requests + if let Some(governor) = leleka_memory::Governor::global() { + let directive = governor.directive(self.store.bytes() as u64); + self.apply_shed(directive.prefix_budget, governor); + } + if self.live.len() <= end { + let have = self.live.len(); + self.live.extend_from_slice(&prompt[have..end]); + } + let Some(req) = self.req.as_ref() else { return Ok(ChunkOutcome::Nothing) }; + self.note = None; + if end == 0 || end % g != 0 || end > req.limit { + return Ok(ChunkOutcome::Nothing); + } + let frontier = end == req.last_grid; + let (est_state, est_block) = device.estimate(g); + let est_state = self.seen_state_bytes.unwrap_or(est_state); + let est_block = self.seen_block_bytes.unwrap_or(est_block); + let considering = Instant::now(); + let verdict = self.store.consider(&prompt[..end], frontier, est_state, est_block); + self.consider_ms_request += considering.elapsed().as_secs_f64() * 1e3; + let candidate = match verdict { + Consider::Exists => return Ok(ChunkOutcome::Exists), + Consider::Rejected(why) => { + self.note = Some(format!("grid point {end} rejected by the policy: {why:?} (store {} MiB of {} MiB)", self.store.bytes() >> 20, self.configured_budget >> 20)); + return Ok(ChunkOutcome::Rejected(why)); + } + Consider::Admit(candidate) => candidate, + }; + let additional = (est_state + candidate.missing.len() * est_block) as u64; + let available = admission_reading(device.available_memory(), additional, self.cfg.memory_floor); + if !budget::admit_growth(available, additional, self.cfg.memory_floor) { + self.store.abort(candidate); + self.note = Some(format!( + "grid point {end}: low memory, available {} MiB, additional {} MiB, floor {} MiB", + available.map_or_else(|| "unknown".to_owned(), |b| (b >> 20).to_string()), + additional >> 20, + self.cfg.memory_floor >> 20 + )); + return Ok(ChunkOutcome::LowMemory); + } + let started = Instant::now(); + let state = device.park_state()?; + if device.position()? != end as u64 { + return Err(Error::IdentityMismatch); + } + let mut blocks = Vec::with_capacity(candidate.missing.len()); + for &j in &candidate.missing { + blocks.push((j, device.park_block(j * g, g)?)); + } + self.seen_state_bytes = Some(state.byte_size()); + if let Some((_, block)) = blocks.first() { + self.seen_block_bytes = Some(block.byte_size()); + } + let new_blocks = blocks.len(); + let bytes = state.byte_size() + blocks.iter().map(|(_, b)| b.byte_size()).sum::(); + let park_ms = started.elapsed().as_secs_f64() * 1e3; + self.store.commit(candidate, &prompt[..end], state, blocks).map_err(|_| Error::IdentityMismatch)?; + self.park_ms_request += park_ms; + self.admitted_request += 1; + Ok(ChunkOutcome::Admitted { tokens: end, new_blocks, bytes, park_ms }) + } + + /// The end of the prompt's prefill: the session stands at `prompt.len() - 1`. With `TailMode::Prompt` or `Reply`, checkpoint + /// there (a request-end checkpoint), unless that is a grid point. + pub(in super::super::super) fn after_prefill>(&mut self, device: &mut D, prompt: &[i32]) -> Result { + self.note = None; + if self.cfg.tail == TailMode::Off || self.bypass || self.req.is_none() { + self.note = Some(format!("no tail checkpoint: tail {:?}, bypass {}, request {}", self.cfg.tail, self.bypass, self.req.is_some())); + return Ok(ChunkOutcome::Nothing); + } + let end = prompt.len().saturating_sub(1); + self.admit_tail(device, &prompt[..end], None) + } + + /// The end of the decode: the session stands at `consumed.len()` (the prompt and the committed reply), settled, with the draft + /// ring in step. With `TailMode::Reply`, checkpoint there; the cells past the prompt are decode-produced. + /// The reason the last checkpoint attempt was not taken, with the numbers; read once. + pub(in super::super::super) fn take_note(&mut self) -> Option { + self.note.take() + } + + pub(in super::super::super) fn after_decode>(&mut self, device: &mut D, consumed: &[i32]) -> Result { + self.note = None; + if self.cfg.tail != TailMode::Reply || self.bypass || self.req.is_none() { + return Ok(ChunkOutcome::Nothing); + } + // the prompt-end checkpoint of this request stays: a client that resends the history without the reasoning of the reply + // continues from the prompt, not from the decode end + let keep = self.req.as_ref().map(|r| r.limit); + let outcome = self.admit_tail(device, consumed, keep)?; + if matches!(outcome, ChunkOutcome::Admitted { .. } | ChunkOutcome::Exists) { + // the buffer holds exactly these cells, and the node has a copy of them + self.live.clear(); + self.live.extend_from_slice(consumed); + } + Ok(outcome) + } + + pub(in super::super) fn admit_tail>(&mut self, device: &mut D, tokens: &[i32], keep_end: Option) -> Result { + let g = self.block_tokens; + // a grid point is a pure checkpoint of its own (and a node below one block has no blocks to hang on) + let position = device.position()?; + if tokens.len() <= g || tokens.len() % g == 0 || position != tokens.len() as u64 { + self.note = Some(format!("not a tail position: {} tokens, grid {g}, the session stands at {position}", tokens.len())); + return Ok(ChunkOutcome::Nothing); + } + let (est_state, est_block) = device.estimate(g); + let est_state = self.seen_state_bytes.unwrap_or(est_state); + let est_block = self.seen_block_bytes.unwrap_or(est_block); + let considering = Instant::now(); + let verdict = self.store.consider_tail(tokens, true, est_state, est_block); + self.consider_ms_request += considering.elapsed().as_secs_f64() * 1e3; + let candidate = match verdict { + Consider::Exists => { + self.note = Some(format!("a checkpoint at {} tokens exists already", tokens.len())); + return Ok(ChunkOutcome::Exists); + } + Consider::Rejected(why) => { + self.note = Some(format!("rejected by the policy at {} tokens: {why:?} (store {} MiB of {} MiB)", tokens.len(), self.store.bytes() >> 20, self.configured_budget >> 20)); + return Ok(ChunkOutcome::Rejected(why)); + } + Consider::Admit(candidate) => candidate, + }; + let additional = (est_state + candidate.missing.len() * est_block + est_block) as u64; + let available = admission_reading(device.available_memory(), additional, self.cfg.memory_floor); + let missing = candidate.missing.len(); + if !budget::admit_growth(available, additional, self.cfg.memory_floor) { + self.store.abort(candidate); + self.note = Some(format!( + "low memory at {} tokens: available {} MiB, additional {} MiB (state {} + {} new blocks of {} MiB + the tail), floor {} MiB", + tokens.len(), + available.map_or_else(|| "unknown".to_owned(), |b| (b >> 20).to_string()), + additional >> 20, + est_state >> 20, + missing, + est_block >> 20, + self.cfg.memory_floor >> 20 + )); + return Ok(ChunkOutcome::LowMemory); + } + let started = Instant::now(); + let state = device.park_state()?; + if device.position()? != tokens.len() as u64 { + return Err(Error::IdentityMismatch); + } + let mut blocks = Vec::with_capacity(candidate.missing.len()); + for &j in &candidate.missing { + blocks.push((j, device.park_block(j * g, g)?)); + } + let full = tokens.len() / g; + let tail = device.park_tail(full * g, tokens.len() - full * g)?; + self.seen_state_bytes = Some(state.byte_size()); + let new_blocks = blocks.len(); + let bytes = state.byte_size() + tail.byte_size() + blocks.iter().map(|(_, b)| b.byte_size()).sum::(); + let park_ms = started.elapsed().as_secs_f64() * 1e3; + self.store.commit_tail_keeping(candidate, tokens, state, blocks, tail, keep_end).map_err(|_| Error::IdentityMismatch)?; + self.park_ms_request += park_ms; + self.admitted_request += 1; + Ok(ChunkOutcome::Admitted { tokens: tokens.len(), new_blocks, bytes, park_ms }) + } + + /// The request is over. `completed` is false when the owners are lost (the checkpoints and the live claim go); + /// a cancelled request is completed: its chunks kept the live claim honest. + pub(in super::super::super) fn finish(&mut self, completed: bool) { + self.req = None; + if !completed { + self.invalidate(); + } + } + + /// Admissions of the request just served and the time spent parking them. + pub(in super::super::super) fn request_parking(&self) -> (u64, f64, f64) { + (self.admitted_request, self.park_ms_request, self.consider_ms_request) + } + + /// The metrics line. + /// Drop the sessions nobody used for the retention time (called from the idle loop); returns how many nodes went. + pub(in super::super::super) fn expire_idle(&mut self) -> usize { + self.store.set_now(wall_ms()); + self.store.expire() + } + + pub(in super::super::super) fn describe(&self) -> String { + let s = self.store.stats(); + format!( + "prefix stats: nodes={} blocks={} used_mib={} budget_mib={} requests={} hits={} shared_hits={} misses={} reused_tokens={} prompt_tokens={} admitted={} rejected={} evicted={} expired={} already_cached={} live_tokens={}", + self.store.node_count(), + self.store.block_count(), + self.store.bytes() >> 20, + self.store.config().budget_bytes >> 20, + s.requests, + s.hits, + s.shared_hits, + s.misses, + s.reused_tokens, + s.prompt_tokens, + s.admitted, + s.rejected + s.rejected_after_build, + s.evicted, + s.expired, + s.already_cached, + self.live.len() + ) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack.rs index 4b7a57a0..12c96b15 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack.rs @@ -3,1237 +3,9 @@ #[allow(unused_imports)] use super::*; - -impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { - /// `generate.cpp` startup over the binding: embedding table, native head + embedding, dense weights at - /// the prompt capacity, the MoE arena cache, the target session, the prompt executor with the MTP - /// drafter, the prefill arena, and the per-request stages. `shared` is the session's reference to the - /// very context `context` borrows. - pub(crate) fn open( - binding: &'a ModelBinding, - context: &'ctx Context<'ctx>, - shared: Rc>, - config: StackConfig, - ) -> std::result::Result { - crate::bringup_trace!("DBG[{:.0}s] OriginalServeStack::open begin", dbg_el()); - config.validate().map_err(at("config.validate"))?; - // generate.cpp: qsa_set_kv_resident before any QSA state exists (every streamed owner sizes from it) - leleka_cuda_driver::configure_kv_resident(config.kv_resident).map_err(|_| ServeFailure { - error: Error::InvalidDimension, - detail: Some(format!("--kv-resident {}: the process already serves another resident KV window", config.kv_resident)), - })?; - if let Some(footprint) = config.kv_footprint() { - operator_note(&footprint.to_string()); - } - if !std::ptr::eq(context, &*shared) { - return Err(failure(Error::IdentityMismatch)); - } - if binding.layer_count() != 48 { - return Err(ServeFailure { error: Error::IdentityMismatch, detail: Some("the Original serve stack serves the 48-layer model only".to_owned()) }); - } - if !binding.has_mtp() { - return Err(ServeFailure { - error: Error::Unsupported(super::super::contract::Stage::Session), - detail: Some("the binding carries no MTP pack: the Original serve loop drafts with the MTP layer".to_owned()), - }); - } - let max_cells = usize::try_from(super::super::contract::serving_cells()).map_err(|_| failure(Error::Overflow))?; - let mut settings = OriginalServeSettings::from_environment(config.max_context, VOCABULARY, config.coupled); - let mut arm_label = String::from("env"); - let arm_order: Vec = OriginalServeSettings::arms_from_environment(config.max_context, VOCABULARY, config.coupled).into_iter().map(|(l, _)| l).collect(); - let mut parked = Vec::new(); - let arms = OriginalServeSettings::arms_from_environment(config.max_context, VOCABULARY, config.coupled); - let verifier_max_t = arms.iter().map(|(_, s)| s.max_t).chain([settings.max_t]).max().unwrap_or(settings.max_t); - if let Some(((label, first), rest)) = arms.split_first() { - settings = *first; - arm_label = label.clone(); - for (label, s) in rest { - parked.push((label.clone(), *s, s.controller().map_err(at("settings.controller"))?)); - } - } - let controller = settings.controller().map_err(at("settings.controller"))?; - let rope = RopeConstants::from_serving_context(); - let blobs = ExpertBlobSizes::from_binding(binding).map_err(at("ExpertBlobSizes::from_binding"))?; - let formats = expert_formats(binding).map_err(at("expert_formats"))?; - let layout = prefill_layout_options(config.capacity, max_cells, &blobs); - - vram_note(context, "open begin"); - // The native head + embedding come first: with LELEKA_PROMPT_EMBED_ALIAS=1 the prompt path's token table aliases the mapped host copy - // of the native embedding instead of a second copy in VRAM (the two are the same GGUF tensor). - let output = staged!("native head + embedding", context, OriginalNativeOutput::load(binding, context, NativeHeadDispatch::default(), true).map_err(at("OriginalNativeOutput::load"))?); - let embedding = staged!("embedding table", context, if OriginalPromptEmbedding::alias_enabled() { - OriginalPromptEmbedding::alias_native(binding, context, output.embedding(binding).map_err(at("OriginalNativeOutput::embedding"))?).map_err(at("OriginalPromptEmbedding::alias_native"))? - } else { - OriginalPromptEmbedding::load(binding, context).map_err(at("OriginalPromptEmbedding::load"))? - }); - let kar = staged!("KAR PLE cache", context, match binding.kar_ple_binding() { - Some(provider) => Some(KarPleCache::new(context, provider).map_err(at("KarPleCache::new"))?), - None => None, - }); - let dense = staged!("dense weights", context, DenseWeightCache::new_original_prompt_capacity(binding, context, config.capacity).map_err(at("DenseWeightCache::new_original_prompt_capacity"))?); - let mut moe = staged!("MoE arena cache", context, MoeWeightCache::new_original_prompt_arena(binding, context, layout, super::super::original_serve_config::mtp_pack_experts_needed(config.rt_directory.is_some())).map_err(at("MoeWeightCache::new_original_prompt_arena"))?); - if !super::super::original_serve_config::mtp_pack_experts_needed(config.rt_directory.is_some()) { - operator_note("footprint: the pinned MTP pack's expert bank (675 MiB) is not uploaded: the draft layer is loaded from the RT directory and never reads it (LELEKA_FOOTPRINT_LEGACY=1 keeps it)"); - } - vram_note(context, "after embedding, output, kar, dense, moe arena"); - let mut session = QwenSession::for_binding_on_shared_device(binding, shared); - let request = OriginalMtpRequest::ring_int8(verifier_max_t, config.capacity, settings.coupled, MTP_RESIDENT_CELLS); - let executor_stage = crate::memory_governor::begin("prompt executor + MTP drafter", Some(context)); - let (executor, draft) = match &config.rt_directory { - Some(directory) => OriginalPromptExecutor::select_rt_mtp( - binding, &dense, &mut session, context, &embedding, &output, directory, config.capacity, true, &request, - ) - .map_err(|e| ServeFailure { error: e.error, detail: e.message })?, - None => { - let mut executor = OriginalPromptExecutor::new( - binding, &dense, &mut session, context, &moe, &embedding, config.capacity, verifier_max_t, true, - ).map_err(at("OriginalPromptExecutor::new"))?; - let assembly = OriginalMtpFullOwner::assemble(binding, &session, context, &moe, &embedding, &output, &request) - .map_err(|e| ServeFailure { error: e.error, detail: e.message })?; - let draft = executor.install_full_mtp(binding, &session, assembly).map_err(at("install_full_mtp"))?; - (executor, draft) - } - }; - // RT-directory draft: the MTP dense roles sit twice in VRAM (this cache's pinned-pack upload and the RT bank's); merge them when proven byte-equal - if config.rt_directory.is_some() && !super::super::original_serve_config::legacy_footprint() { - if let Some(retained) = executor.retained_mtp_weights() { - let share = moe.share_rt_mtp_dense(retained).map_err(at("share_rt_mtp_dense"))?; - operator_note(&format!( - "footprint: MTP dense roles shared with the RT bank (byte-equal): {} shared, {} kept ({} differing), {:.1} MiB released", - share.shared, share.kept, share.differing, share.released_bytes as f64 / f64::from(1u32 << 20) - )); - } - } - vram_note(context, "after prompt executor and draft"); - let mut executor = executor; - crate::memory_governor::end(executor_stage, Some(context)); - // generate.cpp: the expert cache is sized after everything else, and the prompt path's own buffers - // after the cache when it cannot borrow them; without the tier the order is unchanged. - let tier = config.expert_tier.enabled(); - let mut arena = staged!("prefill arena", context, if tier { None } else { Some(context.original_prefill_arena(layout).map_err(at("original_prefill_arena"))?) }); - vram_note(context, "before cache"); - let history = staged!("penalty history", context, OriginalNativePenaltyHistory::new(binding, context).map_err(at("OriginalNativePenaltyHistory::new"))?); - let ple_history = context.allocate(PLE_HISTORY_BYTES).map_err(at("ple_history"))?; - let ple_scratch = context.allocate(PLE_SCRATCH_BYTES).map_err(at("ple_scratch"))?; - let pool = staged!("CPU expert pool", context, CpuExpertPool::new(binding, config.cpu_workers).map_err(at("CpuExpertPool::new"))?); - let empty_session = staged!("empty-prompt session checkpoint", context, executor.checkpoint_session(binding, &mut session).map_err(at("checkpoint_session"))?); - let empty_draft = staged!("empty-prompt draft checkpoint", context, draft.checkpoint(binding, &session).map_err(at("draft.checkpoint"))?); - let prefix = match &config.prefix { - Some(prefix_config) => { - let available = crate::conversation::memory::available_memory(); - // the budget comes from the memory governor (what is left above the floors), not from an independent default - let complement_pending = (config.expert_tier.resident_budget_gib.max(0.0) * (1u64 << 30) as f64) as u64; - let bytes = crate::memory_governor::resolve_prefix_budget(prefix_config.budget, available, complement_pending) - .unwrap_or_else(|| prefix_config.resolve_budget(available)); - let mut prefix_config = prefix_config.clone(); - if let Some(g) = leleka_memory::Governor::global() { - // stop admitting before anything has to be shed: soft floor + reserve (the real CRM session sat 4.4 GiB above a 3 GiB floor) - prefix_config.memory_floor = prefix_config.memory_floor.max(g.policy().admit_floor()); - } - let prefix_config = &prefix_config; - if bytes == 0 { - operator_note(&format!( - "prefix cache off (budget {:?}, available host memory {:?} MiB)", - prefix_config.budget, - available.map(|b| b >> 20) - )); - None - } else { - let identity = format!("qwen4exp:{PINNED_MODEL}:kv={:?}:resident={}", config.kv_format, config.kv_resident); - let serve = PrefixServe::new(prefix_config.clone(), config.capacity, bytes, &identity); - operator_note(&format!( - "prefix cache on: block/grid {} tokens, budget {} MiB, state ~{} MiB + {} B per token, host memory available {:?} MiB, namespace {}", - serve.block_tokens(), - bytes >> 20, - PARKED_STATE_ESTIMATE >> 20, - PARKED_BYTES_PER_TOKEN, - available.map(|b| b >> 20), - crate::prefix_cache::summary::hex(serve.namespace()) - )); - Some(serve) - } - } - None => None, - }; - let conversation = if prefix.is_some() { None } else { config.conversation.clone().map(ServeConversation::new) }; - let residency = ResidencyState::new(&config.expert_tier); - report_kernel_selection(); - vram_note(context, "before expert tier"); - let mut loan = None; - let tier_open = staged!("expert tier (VRAM slots + profile fill)", context, original_serve_residency::open_tier(binding, context, &moe, &config.expert_tier, config.capacity).map_err(at("expert tier"))?); - let expert_cache = match tier_open { - Some((cache, filled)) => { - if config.expert_tier.prefill_borrow && config.expert_tier.profile.is_some() { - loan = original_serve_residency::loan_slots(&cache, prefill_bytes(layout).map_err(at("prefill bytes"))?) - .map_err(at("expert-cache loan"))?; - } - operator_note(&format!( - "expert cache {} slots ({:.2} GiB, {}), {filled} filled from the profile; the prompt path {}; GPU experts round differently from the CPU's (bench/results/2026-09-27-cache-parity)", - cache.slots(), - cache.bytes() as f64 / f64::from(1u32 << 30), - if cache.per_layer_admission() { "per layer" } else { "global" }, - match loan { - Some(k) => format!("borrows its last {k} slots"), - None => "allocates its own buffers".to_owned(), - } - )); - Some(cache) - } - None => None, - }; - vram_note(context, "after expert tier"); - let mut loan_tiers: Vec = Vec::new(); - if let (Some(full), Some(cache), true) = (loan, expert_cache.as_ref(), config.loan_tiers) { - for rows in LOAN_TIER_ROWS.into_iter().filter(|&r| r < config.capacity) { - let tier_layout = PrefillLayoutOptions { capacity: rows, ..layout }; - let slots = original_serve_residency::loan_slots(cache, prefill_bytes(tier_layout).map_err(at("prefill bytes (tier)"))?).map_err(at("expert-cache loan (tier)"))?; - if let Some(slots) = slots.filter(|&s| s < full && loan_tiers.last().is_none_or(|t| s > t.slots)) { - loan_tiers.push(LoanTier { rows, layout: tier_layout, slots }); - } - } - if !loan_tiers.is_empty() { - operator_note(&format!( - "prompt loan ladder: {}, up to {} rows {full} slots", - loan_tiers.iter().map(|t| format!("up to {} rows {} slots", t.rows, t.slots)).collect::>().join(", "), - config.capacity - )); - } - } - let initial_owners: Vec> = expert_cache - .as_ref() - .map(|cache| (0..cache.slots()).map(|slot| cache.slot_owner(slot)).collect()) - .unwrap_or_default(); - if arena.is_none() && loan.is_none() { - arena = Some(staged!("prefill arena (after the expert tier)", context, context.original_prefill_arena(layout).map_err(at("original_prefill_arena"))?)); - } - let this = Self { - binding, - context, - conversation, - prefix, - tail_consumed: None, - reused: 0, - resume_point: 0, - full_policy: mtp_full_policy(&rope), - scalar_policy: mtp_scalar_policy(&rope), - config, - settings, - max_cells, - rope, - blobs, - formats, - controller, - parked, - arm_label, - arm_order, - verifier_max_t, - broken: None, - empty_session, - empty_draft, - history, - ple_history, - ple_scratch, - arena, - layout, - expert_cache, - loan, - loan_tiers, - residency, - initial_owners, - seed_report: None, - seed_counts: None, - refill_pending: false, - refill_due: false, - timing: (0.0, 0.0), - marks: TtftMarks::default(), - executor, - draft, - session, - pool, - kar, - moe, - dense, - output, - embedding, - }; - this.register_memory_classes(); - crate::memory_governor::post_open(); - if let Some(governor) = leleka_memory::Governor::global() { - governor.log(&format!("stack open; inventory of allocation classes (accounted by their owners): -{}", governor.inventory().table())); - governor.log(&format!("load ledger (measured: kernel and driver deltas per opening step): -{}", governor.ledger().table())); - governor.publish(); - } - Ok(this) - } - - /// `Some` once a physical owner was lost: the stack must be closed and rebuilt. - pub(crate) fn health(&self) -> Option { - self.broken - } - - /// One request. Admission, reset, prompt conditioning and decode in order; see `run_request`. - pub(crate) fn serve( - &mut self, - request: &ServeRequest, - emit: &mut dyn FnMut(&[i32]) -> Result<()>, - cancel: &mut dyn FnMut() -> bool, - ) -> std::result::Result { - self.apply_memory_directive(); - self.marks = TtftMarks::start(); - let max_context = self.config.max_context; - let result = run_request(self, request, max_context, emit, cancel); - self.note_memory(); - result - } - - /// Follow the memory governor between requests: under pressure the prefix cache evicts (and restores its budget when the - /// pressure is over), and the conversation checkpoints are dropped. Cheap: a few atomics when nothing changed. - pub(super) fn apply_memory_directive(&mut self) { - let Some(governor) = leleka_memory::Governor::global() else { return }; - let used = self.prefix.as_ref().map_or(0, |p| p.bytes() as u64); - let directive = governor.directive(used); - if let Some(prefix) = self.prefix.as_mut() { - let before = prefix.bytes(); - let freed = prefix.apply_shed(directive.prefix_budget, governor); - if freed > 0 { - operator_note(&format!( - "memory pressure ({}): prefix cache evicted {} MiB ({} -> {} MiB), budget {} MiB", - directive.level.as_str(), - freed >> 20, - before >> 20, - prefix.bytes() >> 20, - prefix.budget_bytes() >> 20 - )); - } - } - if directive.drop_conversation - && let Some(conversation) = self.conversation.as_mut() - && conversation.checkpoint_count() > 0 - { - conversation.invalidate(); - operator_note(&format!("memory pressure ({}): conversation checkpoints dropped", directive.level.as_str())); - } - } - - /// Keep the inventory's elastic classes current (the prefix store and the conversation checkpoints). - pub(super) fn note_memory(&self) { - if leleka_memory::Governor::global().is_none() { - return; - } - if let Some(prefix) = self.prefix.as_ref() { - crate::memory_governor::set_bytes("prefix.store", prefix.bytes() as u64); - if let Some(g) = leleka_memory::Governor::global() { - g.note_prefix_used(prefix.bytes() as u64); - } - } - if let Some(conversation) = self.conversation.as_ref() { - crate::memory_governor::set_bytes("conversation.checkpoints", conversation.checkpoint_count() as u64 * crate::memory_governor::CHECKPOINT_BYTES); - } - } - - /// Register the stack's allocation classes with the inventory (sizes from the owners' own formulas and counters). - pub(super) fn register_memory_classes(&self) { - use leleka_memory::{Space, When}; - let Some(governor) = leleka_memory::Governor::global() else { return }; - let _ = governor; - if let Some(f) = self.config.kv_footprint() { - crate::memory_governor::account("kv", "host_pinned", Space::HostPinned, When::Startup, "12 QSA layers x serving cells x 1056 B, pinned and device-mapped (the whole serving context, allocated at open)", f.pinned_host_bytes as u64); - crate::memory_governor::account("kv", "vram_window", Space::Device, When::Startup, "12 layers x resident pages x 4244 B (+ page table + resolver state)", f.vram_bytes as u64); - crate::memory_governor::account("kv", "prompt_stage", Space::Device, When::Startup, "one INT8 staging pool of the prompt path (identity layout)", f.stage_bytes as u64); - } - if let Ok(bytes) = prefill_bytes(self.layout) { - crate::memory_governor::account( - "prefill", - if self.loan.is_some() { "arena_borrowed" } else { "arena" }, - Space::Device, - When::Startup, - if self.loan.is_some() { "carve of the prefill arena, borrowed from the last slots of the expert cache (not additional)" } else { "carve of the prefill arena at the chunk capacity" }, - if self.loan.is_some() { 0 } else { bytes as u64 }, - ); - } - if let Some(cache) = self.expert_cache.as_ref() { - crate::memory_governor::account("expert_cache", "slots", Space::Device, When::Startup, "slots x slot bytes (VRAM expert tier)", cache.bytes() as u64); - } - crate::memory_governor::account("ple", "history_and_scratch", Space::Device, When::Startup, "PLE history image + scratch", (PLE_HISTORY_BYTES + PLE_SCRATCH_BYTES) as u64); - crate::memory_governor::account("context", "accounted_total", Space::Device, When::Lazy, "sum of the context's budgeted allocations (not additive with the classes above; see the ledger for the driver-seen total)", 0); - if let Some(prefix) = self.prefix.as_ref() { - crate::memory_governor::account( - "prefix", - "store", - Space::HostPageable, - When::Elastic, - "blocks (14,208 B per token) + node states (~127 MiB each) under the governor-granted budget", - prefix.bytes() as u64, - ); - } - if self.conversation.is_some() { - crate::memory_governor::account( - "conversation", - "checkpoints", - Space::HostPageable, - When::Elastic, - "checkpoints x ~118 MiB (GDN/PLE images, draft ring, index tails)", - 0, - ); - } - } - - /// Labels of the window policies of `LELEKA_SPEC_ARMS` in the order given (empty when unset), the live one included. - #[allow(dead_code)] - pub(crate) fn spec_arms(&self) -> Vec { - self.arm_order.clone() - } - /// Make `label` the window policy of the following requests (between requests only). Returns false for an unknown label. - #[allow(dead_code)] - pub(crate) fn select_spec_arm(&mut self, label: &str) -> bool { - if self.arm_label == label { - return true; - } - let Some(at) = self.parked.iter().position(|(l, _, _)| l == label) else { return false }; - let (new_label, new_settings, new_controller) = self.parked.swap_remove(at); - let old_label = std::mem::replace(&mut self.arm_label, new_label); - let old_settings = std::mem::replace(&mut self.settings, new_settings); - let old_controller = std::mem::replace(&mut self.controller, new_controller); - self.parked.push((old_label, old_settings, old_controller)); - true - } - /// The live arm's own request floor, if its label pinned one (`fixed4@0`). - #[allow(dead_code)] - pub(crate) fn spec_arm_min_p(&self) -> Option { - self.settings.request_min_p - } - #[allow(dead_code)] - pub(crate) fn spec_arm(&self) -> &str { - &self.arm_label - } - - /// Wall-clock milliseconds of the last request's prompt phase and decode phase. - #[cfg_attr(not(test), allow(dead_code))] - pub(crate) fn last_timing(&self) -> (f64, f64) { - self.timing - } - - /// Where the last request's time to first token went: `(resumed, prefilled, assembled, first_round)`, each the - /// milliseconds since `serve` was entered when that stage ended (`resumed`: the cache lookup, import and any reset; - /// `prefilled`: the prompt chunks, the lent-slot refill and the seed; `assembled`: the verifier (graphs, canonical - /// state upload); `first_round`: the first verified round was emitted). NaN for a stage the request did not reach. - #[allow(dead_code)] - pub(crate) fn ttft_marks(&self) -> [f64; 4] { - self.marks.as_array() - } - - /// The VRAM expert tier's counters (`None` when the tier is off). - pub(crate) fn expert_tier_stats(&self) -> Option { - self.expert_cache.as_ref().map(|cache| { - let mut stats = self.residency.stats; - stats.swaps = cache.swaps(); - stats - }) - } - - /// The tier's configuration, for an experiment that switches the adaptive tier or the seed between requests (the - /// adaptive counts are allocated at open, so `adapt_every` may be changed freely, a seed needs the tier on). - #[allow(dead_code)] - pub(crate) fn expert_tier_mut(&mut self) -> &mut ExpertTierConfig { - &mut self.config.expert_tier - } - - /// The last request's seed from the prompt's routing (`None`: seed off, or no prompt rows were read). - #[allow(dead_code)] - pub(crate) fn last_seed(&self) -> Option { - self.seed_report - } - - /// Cumulative (vram, pcie, cpu) window entries after each verified round of the last request. - #[allow(dead_code)] - pub(crate) fn round_marks(&self) -> Vec<[u64; 3]> { - self.residency.round_marks() - } - - /// A first-request state for an experiment: the tier back on the starting profile's set, the adaptive counts and - /// the draft/adaptation controller as in a new process. Returns the swaps the restore needed. - #[allow(dead_code)] - pub(crate) fn reset_expert_tier(&mut self) -> Result { - if let Some(error) = self.broken { - return Err(error); - } - self.residency.clear_usage(); - self.controller = self.settings.controller()?; - match self.expert_cache.as_mut() { - Some(cache) => original_serve_seed::restore_placement(self.binding, &self.moe, cache, &mut self.pool, &mut self.residency.spans, &self.initial_owners), - None => Ok(0), - } - } - - /// Prompt tokens the last request reused from the conversation cache (generate.cpp `REUSED`). - pub(crate) fn reused_tokens(&self) -> usize { - self.reused - } - - /// The position the conversation cache resumed the last request at (equals `reused_tokens` unless - /// `STRATA_CKPT_REREAD` re-read that prefix from 0). - #[cfg_attr(not(test), allow(dead_code))] - pub(crate) fn resume_point(&self) -> usize { - self.resume_point - } - - /// Drop every conversation checkpoint and the live state: the next request reads its whole prompt. - #[cfg_attr(not(test), allow(dead_code))] - pub(crate) fn forget_conversation(&mut self) { - if let Some(conversation) = self.conversation.as_mut() { - conversation.invalidate(); - } - if let Some(prefix) = self.prefix.as_mut() { - prefix.invalidate(); - } - } - - /// Verification arm: while set, requests read their whole prompt on the grid without using or changing the prefix - /// cache (the reference a cached request must reproduce). - #[allow(dead_code)] - pub(crate) fn prefix_bypass(&mut self, bypass: bool) { - if let Some(prefix) = self.prefix.as_mut() { - prefix.set_bypass(bypass); - } - } - - /// Drop the cached sessions nobody used for the retention time (60 minutes by default); the idle loop calls this. - pub(crate) fn prefix_expire_idle(&mut self) -> usize { - self.prefix.as_mut().map_or(0, |prefix| prefix.expire_idle()) - } - - /// The prefix cache's summary for a front router (`None` when the cache is off). - #[allow(dead_code)] - pub(crate) fn prefix_summary(&self, max_heads: usize) -> Option { - self.prefix.as_ref().map(|prefix| prefix.summary(max_heads)) - } - - /// The `prefix_match` query: how many tokens of the prompt whose block hash chain is `chain` are cached. - #[allow(dead_code)] - pub(crate) fn prefix_match(&self, chain: &[u64]) -> Option { - self.prefix.as_ref().map(|prefix| prefix.prefix_match(chain)) - } - - /// The prefix cache's metrics line (`None` when the cache is off). - #[allow(dead_code)] - pub(crate) fn prefix_metrics(&self) -> Option { - self.prefix.as_ref().map(|prefix| prefix.describe()) - } - - /// Bytes the prefix cache holds now (0 when it is off). - #[allow(dead_code)] - pub(crate) fn prefix_bytes(&self) -> usize { - self.prefix.as_ref().map_or(0, |prefix| prefix.bytes()) - } - - /// The prefix cache's current byte budget (0 when it is off or fully shed). - #[allow(dead_code)] - pub(crate) fn prefix_budget_bytes(&self) -> usize { - self.prefix.as_ref().map_or(0, |prefix| prefix.budget_bytes()) - } - - /// Close every owner in dependency order; the first failure is reported after all were attempted. - pub(crate) fn close(self) -> Result<()> { - let Self { - conversation, residency, history, ple_history, ple_scratch, arena, expert_cache, executor, draft, session, pool, kar, - moe, dense, output, embedding, .. - } = self; - drop(conversation); - // the span cache retains registered-source spans of the bank `moe` closes below - drop(residency); - let mut first: Option = None; - let mut note = |result: Result<()>| { - if let Err(error) = result { - first.get_or_insert(error); - } - }; - note(history.close()); - note(ple_history.release().map_err(|_| Error::CudaExecution)); - note(ple_scratch.release().map_err(|_| Error::CudaExecution)); - drop(arena); - if let Some(cache) = expert_cache { - note(cache.close().map_err(|e| super::super::original_serve_verifier::driver_error(&e))); - } - note(executor.close()); - note(draft.close()); - drop((session, pool, kar)); - note(moe.close()); - note(dense.close()); - // the prompt path's token table may alias the native embedding's mapped copy: it goes first - note(embedding.close()); - note(output.close()); - first.map_or(Ok(()), Err) - } - - pub(super) fn mark_broken(&mut self, error: Error) { - self.broken.get_or_insert(error); - } - - /// Hand the twelve QSA owners to a fresh verifier and run the request's decode phase over it. - pub(super) fn decode_phase( - &mut self, - request: &ServeRequest, - emit: &mut dyn FnMut(&[i32]) -> Result<()>, - cancel: &mut dyn FnMut() -> bool, - ) -> std::result::Result { - let Self { - binding, - context, - config, - settings, - max_cells, - rope, - blobs, - formats, - full_policy, - controller, - parked, - arm_label, - verifier_max_t, - history, - ple_history, - ple_scratch, - executor, - draft, - session, - pool, - kar, - moe, - dense, - output, - broken, - conversation, - expert_cache, - residency, - refill_pending, - refill_due, - marks, - prefix, - tail_consumed, - .. - } = self; - let binding: &ModelBinding = *binding; - let context: &'ctx Context<'ctx> = *context; - if controller.is_failed() { - // a failed restore/finish poisoned the controller; its adaptive cadence is the only thing lost - *controller = settings.controller()?; - } - crate::bringup_trace!("DBG[{:.0}s] decode_phase start", dbg_el()); - let sampling = RequestSampling::new(request.params, request.path)?; - let n = request.prompt.len(); - let base = session.original_verified_base()?; - crate::bringup_trace!("DBG[{:.0}s] decode: base position {} (n-1 = {})", dbg_el(), base.position, n as u64 - 1); - if base.position != (n as u64 - 1) { - return Err(Error::IdentityMismatch.into()); - } - // generate.cpp `ver.set_pcie_mode`: only a window that can stage anything over PCIe records the copy kernel. - let pcie_mode = match (expert_cache.as_ref(), moe.original_expert_bank()) { - (Some(_), Some(bank)) if config.expert_tier.pcie_num_for(bank.pageable()) > 0 => { - config.expert_tier.pcie_mode.graph_mode(bank.pageable(), blobs.spans_tile_blobs()).ok_or(Error::Unsupported( - super::super::contract::Stage::Session, - ))? - } - _ => 0, - }; - let p = profile::span("decode.seed_ple"); - seed_ple_history(&base, ple_history).map_err(|f| SpecError::Forward(f.error))?; - drop(p); - // the window reads the shared experts of all 48 layers in place: load/refresh them together first - let p = profile::span("decode.shared"); - let shared = moe.ensure_original_verify_shared(binding)?; - drop(p); - crate::bringup_trace!("DBG[{:.0}s] decode: shared experts loaded", dbg_el()); - let owners = executor.take_qsa_owners()?; - let ple_history: &DeviceBuffer<'ctx> = &*ple_history; - let weights = VerifyWeights { dense: &*dense, moe: &*moe, shared: &shared, formats: &*formats, ple_scratch: &*ple_scratch }; - let p = profile::span("decode.assemble"); - // queued after assembly's own uploads (canonical GDN image), before the graph capture - let mut queue_refill = || -> Result<()> { - if !std::mem::take(&mut *refill_due) { - return Ok(()); - } - if let Some(cache) = expert_cache.as_mut() { - let _p = profile::span("prefill.refill"); - original_serve_residency::refill_lent(binding, &*moe, cache, &mut residency.spans, true)?; - *refill_pending = true; - } - Ok(()) - }; - // A window or commit graph that does not fit in device memory costs the widest windows, not the request or the engine - // (upstream a8c1d4b7): the assembly is repeated with the windows that fit. The owners come back from each failure. - let mut owners_slot = Some(owners); - let (used_max_t, assembled) = assemble_with_window_fallback( - *verifier_max_t, - |max_t| { - let Some(owners) = owners_slot.take() else { - return Err((AssembleFailure { failure: Error::IdentityMismatch.into(), owners: None, window_cap: None }, None)); - }; - assemble( - binding, &weights, context, &*output, &base, owners, ple_history, rope, blobs, max_t, *max_cells, pcie_mode, - &mut queue_refill, - ) - .map_err(|mut lost| { - let cap = lost.window_cap.filter(|&cap| cap < max_t); - if cap.is_some() { - owners_slot = lost.owners.take(); - } - (lost, cap) - }) - }, - |failed, next| { - operator_text(&format!( - "decode window graphs: out of device memory recording windows up to T={failed}; retrying with windows up to T={next}" - )) - }, - ); - drop(p); - marks.assembled = marks.since(); - // the lent slots' refill copies (queued at the end of the prompt phase) have run behind the assembly: wait for them - // before a window or the tier's own bookkeeping touches the cache - if std::mem::take(refill_pending) { - if let Some(cache) = expert_cache.as_mut() { - if let Err(error) = original_serve_residency::settle_refill(cache) { - broken.get_or_insert(error); - if let Ok(resources) = assembled { - let _ = disassemble(resources).map(|owners| executor.adopt_qsa_owners(binding, &*dense, &mut *session, owners)); - } - return Err(SpecError::Forward(error)); - } - } - } - vram_note(context, "decode after assemble"); - crate::bringup_trace!("DBG[{:.0}s] decode: assemble -> {}", dbg_el(), if assembled.is_ok() { "ok" } else { "ERR" }); - let resources = match assembled { - Ok(resources) => resources, - Err(lost) => { - operator_line("assemble", &lost.failure); - if let Some(owners) = lost.owners { - if let Err(error) = executor.adopt_qsa_owners(binding, &*dense, &mut *session, owners) { - broken.get_or_insert(error); - } - } else { - broken.get_or_insert(Error::IdentityMismatch); - } - return Err(SpecError::Forward(lost.failure.error)); - } - }; - if used_max_t < *verifier_max_t { - // The card holds windows only up to `used_max_t`: every policy of the stack follows, for this and the later requests (the - // controllers restart; what they learned about the wider windows no longer applies). - operator_text(&format!( - "decode window graphs: windows limited to T<={used_max_t} (were T<={}): the policy, its arms and the MTP draft cap follow", - *verifier_max_t - )); - *verifier_max_t = used_max_t; - let narrowed = (|| -> Result<()> { - *settings = settings.with_window_cap(used_max_t); - *controller = settings.controller()?; - for (_, arm, arm_controller) in parked.iter_mut() { - *arm = arm.with_window_cap(used_max_t); - *arm_controller = arm.controller()?; - } - executor.set_mtp_max_drafts(binding, i32::try_from(settings.max_drafts()).map_err(|_| Error::Overflow)?) - })(); - if let Err(error) = narrowed { - let _ = disassemble(resources).map(|owners| executor.adopt_qsa_owners(binding, &*dense, &mut *session, owners)); - broken.get_or_insert(error); - return Err(SpecError::Forward(error)); - } - } - let DecodeResources { verifier, qsa, slots } = resources; - // the NaN guard's retry takes a refused window back from these (OriginalVerifier::discard_window) - qsa.set_window_snapshots(settings.nan_guard.retries > 0); - let committed = request.prompt[..n - 1].to_vec(); - // The window's expert tier: the GPU share first and the CPU pool on the rest, or the CPU pool alone. - let mut gpu_pool; - let pool: &mut dyn OriginalServePool<'ctx> = match (expert_cache.as_mut(), moe.original_expert_bank()) { - (Some(cache), Some(bank)) => { - let pcie_num = config.expert_tier.pcie_num_for(bank.pageable()); - let tail_rank = original_serve_residency::effective_tail_rank(&*cache); - let pcie_locked = if pcie_num > 0 && original_serve_residency::pcie_locked_only() { bank.locked_experts() } else { Vec::new() }; - gpu_pool = GpuExpertPool { - binding, - moe: &*moe, - cache, - bank, - cpu: &mut *pool, - state: &mut *residency, - pcie_num, - adapt_every: config.expert_tier.adapt_every, - adapt_swaps: config.expert_tier.adapt_swaps as usize, - tail_rank, - pcie_locked, - }; - &mut gpu_pool - } - (Some(_), None) => return Err(SpecError::Forward(Error::IdentityMismatch)), - (None, _) => &mut *pool, - }; - let owners = HostOwners { - binding, - dense: &*dense, - context, - session: &mut *session, - draft: &mut *draft, - executor: &mut *executor, - kar: kar.as_mut(), - history: &mut *history, - pool, - qsa: Rc::clone(&qsa), - slots, - ple_history, - policy: &*full_policy, - }; - let want_tail = config.prefix.as_ref().is_some_and(|p| p.tail == TailMode::Reply) && prefix.is_some(); - controller.set_final_draft(want_tail); - *tail_consumed = None; - let host = OriginalServeHost::new(owners, committed, config.max_context as u64, sampling); - let (served, verifier, outcome) = match host { - Err(error) => (Err(SpecError::Forward(error)), verifier, None), - Ok(host) => { - let port = super::super::original_serve_engine::TracePort(NativeServePort::new(verifier, host)); - let engine = OriginalServeEngine::new(port, VOCABULARY, settings.max_t, settings.max_drafts()); - match engine { - Err(error) => { - // `new` consumed the port on failure; the verifier is gone with it. Treated as lost below. - let _ = error; - broken.get_or_insert(Error::IdentityMismatch); - return Err(SpecError::Forward(Error::IdentityMismatch)); - } - Ok(mut engine) => { - crate::bringup_trace!("DBG[{:.0}s] decode: engine ready, serving", dbg_el()); - let started = Instant::now(); - let serve_span = profile::span("decode.serve"); - let result = engine.set_min_p(request.spec_min_p).map_err(SpecError::Forward).and_then(|()| { - serve_request( - controller, - &mut engine, - &request.prompt, - request.max_new, - request.spec_min_p, - &request.eos, - |tokens| { - if marks.first_round.is_nan() { - marks.first_round = marks.since(); - } - emit(tokens) - }, - &mut *cancel, - || started.elapsed().as_secs_f64() * 1e3, - ) - }); - drop(serve_span); - { - // the controller's round counters belong to this request in every window policy - let stats = controller.take_stats(); - if super::super::original_spec_controller::stats_enabled() { - eprintln!("DBG spec-stats arm={} {}", arm_label, stats.line()); - } - } - if let Err(e) = &result { crate::bringup_trace!("DBG[{:.0}s] serve_request err {e:?}", dbg_el()); } - let (mut verifier, mut host) = engine.into_port().0.into_parts(); - // STRATA_VERIFY_PROFILE=1: the GPU stage times of the request's windows (empty otherwise) - let gpu_profile = verifier.profile_report(); - if !gpu_profile.is_empty() { - eprintln!("DBG verify-profile:{gpu_profile}"); - } - // conversation cache: the session can be continued as is only when the draft ring - // stands at its position (then its recurrent state is settled to match) - let live = conversation.is_some() - && matches!(result, Ok(_) | Err(SpecError::Cancelled)) - && host.draft_in_step(); - // prefix cache, TailMode::Reply: the session settled and the ring in step (the final window was drafted) - let tail = want_tail && result.is_ok() && prefix.is_some() && host.draft_in_step(); - if want_tail && result.is_ok() && !tail { - operator_text("prefix tail: the draft ring is not at the session's position; no checkpoint at the end of this decode"); - } - if (result.is_ok() && config.settle_state) || live || tail { - match host.settle_state(&mut verifier) { - Ok(()) if live => { - if let Some(conversation) = conversation.as_mut() { - conversation.note_live(host.committed().to_vec()); - } - } - Ok(()) if tail => *tail_consumed = Some(host.committed().to_vec()), - Ok(()) => {} - Err(error) => { - broken.get_or_insert(error); - } - } - } - let outcome = host.finish(); - (result, verifier, Some(outcome)) - } - } - } - }; - // The MTP drafter's cached round programs and staged window are bound to THIS verifier's bank: release them before the - // bank closes (it is shared while they live) and so the next request captures against its own bank. - let p = profile::span("decode.release_mtp"); - let released = executor.mtp_release_verifier(binding); - drop(p); - if let Err(error) = released { - operator_line("release MTP verifier bindings", &failure(error)); - broken.get_or_insert(error); - } - // Close the verifier (drains both streams, drops the graphs) and take the physical owners back at - // the session's lineage; an abandoned window is rolled back there. - // the card at the end of the decode phase, graph pools and all windows captured: the real low-water mark of a request - vram_note(context, "decode end before disassemble"); - let p = profile::span("decode.disassemble"); - let disassembled = disassemble(DecodeResources { verifier, qsa, slots }); - drop(p); - match disassembled { - Ok(owners) => { - let _p = profile::span("decode.adopt"); - if let Err(error) = executor.adopt_qsa_owners(binding, &*dense, &mut *session, owners) { - broken.get_or_insert(error); - } - } - Err(lost) => { - operator_line("disassemble", &lost); - broken.get_or_insert(lost.error); - } - } - if outcome.is_some_and(|o| o.failed) { - broken.get_or_insert(Error::IdentityMismatch); - } - served - } - - /// Condition `prompt[resume..n-1]` through the batched Original prefill, one chunk transaction at a time - /// (the session and the draft ring stand at `resume`; with the conversation cache's `STRATA_CKPT_REREAD` - /// they stand at 0 and the reread segment comes first). After each published chunk the conversation cache - /// takes its periodic and turn/root checkpoints. - /// - /// With the expert tier, the swaps in flight land first (generate.cpp `apply_pending(true)`), every chunk - /// borrows the cache's last slots (`prefill_chunk`) and every lent slot is refilled before the decode - /// phase, whatever the read's outcome (generate.cpp `refill`). - pub(super) fn prefill_phase( - &mut self, - request: &ServeRequest, - resume: usize, - cancel: &mut dyn FnMut() -> bool, - ) -> std::result::Result<(), SpecError> { - self.residency.begin_request(); - self.seed_report = None; - if let Some(cache) = self.expert_cache.as_mut() { - let _p = profile::span("prefill.wait_swaps"); - cache.wait_swaps().map_err(|e| SpecError::Forward(super::super::original_serve_verifier::driver_error(&e)))?; - } - // LELEKA_ORIGINAL_SERVE_SEED: the MoE stage adds its host-known route counts per (layer, expert) - let seeding = self.config.expert_tier.seed_swaps > 0 && self.expert_cache.is_some(); - if seeding { - self.moe.capture_prompt_routing(true, self.config.expert_tier.seed_decay); - } - let p = profile::span("prefill.read"); - let read = self.prefill_actions(request, resume, cancel); - drop(p); - let _p = profile::span("prefill.refill"); - // a failed or cancelled read still refills at once (generate.cpp `refill`); a good one overlaps the copies with the - // decode phase's host-side assembly - // (the prompt-routing seed needs the lent slots refilled first, so it turns the deferral off for its requests) - let defer = read.is_ok() && !seeding && original_serve_residency::refill_defer_enabled() && self.loan.is_some() && self.expert_cache.is_some(); - let refilled = match (self.loan, self.expert_cache.as_mut()) { - (Some(_), Some(cache)) if !defer => { - original_serve_residency::refill_lent(self.binding, &self.moe, cache, &mut self.residency.spans, false).map(|_| ()) - } - _ => Ok(()), - }; - let routing = if seeding { self.moe.take_prompt_routing() } else { None }; - let seeded = match (&read, &refilled, routing) { - (Ok(()), Ok(()), Some(counts)) if !defer => { - let _p = profile::span("prefill.seed"); - self.seed_residency(&counts) - } - _ => Ok(()), - }; - self.refill_due = defer; - match (read, refilled, seeded) { - (Ok(()), Err(error), _) | (Ok(()), Ok(()), Err(error)) => { - self.mark_broken(error); - Err(SpecError::Forward(error)) - } - (read, _, _) => read, - } - } - - /// Put the prompt's own routing into the tier's placement before the first window (see `original_serve_seed`). - pub(super) fn seed_residency(&mut self, counts: &[f32]) -> Result<()> { - let tier = &self.config.expert_tier; - let (max, keep, usage) = (tier.seed_swaps, tier.seed_keep, tier.seed_usage); - let Some(cache) = self.expert_cache.as_mut() else { return Ok(()) }; - let started = Instant::now(); - let max_rows = tier.seed_max_rows; - if max_rows > 0 { - let rows = original_serve_seed::summarize(counts, &[]).rows; - if rows > max_rows as u64 { - if std::env::var_os("LELEKA_SEED_TRACE").is_some() { - eprintln!("DBG seed: skipped, the prompt routed {rows} rows (cap {max_rows})"); - } - return Ok(()); - } - } - let swaps = original_serve_seed::plan(counts, cache, max, keep); - let planned = started.elapsed(); - let mut report = original_serve_seed::summarize(counts, &swaps); - original_serve_seed::queue_swaps(self.binding, &self.moe, cache, &mut self.pool, &mut self.residency.spans, &swaps)?; - report.plan_ms = planned.as_secs_f64() * 1e3; - report.queue_ms = (started.elapsed() - planned).as_secs_f64() * 1e3; - self.residency.add_usage(counts, usage); - if std::env::var_os("LELEKA_SEED_TRACE").is_some() { - eprintln!( - "DBG seed: prompt rows {} routed -> {} swaps (gain {:.0}, most in one layer {}), plan {:.2} ms, queue {:.2} ms", - report.rows, report.planned, report.gain, report.max_layer_swaps, report.plan_ms, report.queue_ms - ); - } - self.seed_report = Some(report); - if std::env::var_os("LELEKA_SEED_TRACE").is_some() { - self.seed_counts = Some(counts.to_vec()); - } - Ok(()) - } - - /// `LELEKA_SEED_TRACE`: how much of the request's decode routing (the adaptive counts, so for a static arm) the resident - /// set covers: the starting profile's set, the prompt's top experts (what the seed installs, per layer slot counts of the - /// profile) and the best any static set could do (the decode's own top experts). - pub(super) fn seed_coverage_trace(&mut self) { - let Some(prompt) = self.seed_counts.take() else { return }; - let usage = self.residency.usage(); - if usage.len() != prompt.len() || self.config.expert_tier.adapt_every != 0 { - return; - } - let mut slots = [0usize; 48]; - let mut initial = vec![false; 48 * 512]; - for &(layer, expert) in self.initial_owners.iter().flatten() { - slots[layer] += 1; - initial[layer * 512 + expert] = true; - } - let total: f64 = usage.iter().map(|&u| f64::from(u)).sum(); - if total <= 0.0 { - return; - } - let (mut by_prompt, mut oracle, mut by_initial) = (0f64, 0f64, 0f64); - for layer in 0..48 { - let range = layer * 512..(layer + 1) * 512; - let mut order: Vec = (0..512).collect(); - order.sort_by(|&a, &b| prompt[range.start + b].total_cmp(&prompt[range.start + a])); - by_prompt += order.iter().take(slots[layer]).map(|&e| f64::from(usage[range.start + e])).sum::(); - let mut best: Vec = usage[range.clone()].to_vec(); - best.sort_by(|a, b| b.total_cmp(a)); - oracle += best.iter().take(slots[layer]).map(|&u| f64::from(u)).sum::(); - by_initial += (0..512).filter(|&e| initial[range.start + e]).map(|e| f64::from(usage[range.start + e])).sum::(); - } - // Opt-in: `seed_counts` is only recorded under LELEKA_SEED_TRACE, so this returns early (and prints nothing) otherwise. - eprintln!( - "DBG seed-coverage: decode entries {total:.0}; covered by the starting set {:.1}%, the prompt's top experts {:.1}%, the decode's own top experts {:.1}% (oracle)", - 100.0 * by_initial / total, - 100.0 * by_prompt / total, - 100.0 * oracle / total - ); - } - - pub(super) fn prefill_actions( - &mut self, - request: &ServeRequest, - resume: usize, - cancel: &mut dyn FnMut() -> bool, - ) -> std::result::Result<(), SpecError> { - let binding: &ModelBinding = self.binding; - let n = request.prompt.len(); - crate::bringup_trace!("DBG[{:.0}s] prefill_phase start n={n} resume={resume}", dbg_el()); - // generate.cpp: mtp.set_prompt_len(n) before the prompt is read; the draft cap and the request's - // sampling parameters configure the actor for the whole request. - let mtp_setup_span = profile::span("prefill.mtp_setup"); - self.executor.set_mtp_prompt_len(binding, n as i64)?; - self.executor.set_mtp_max_drafts(binding, i32::try_from(self.settings.max_drafts()).map_err(|_| Error::Overflow)?)?; - self.executor.set_mtp_draft_sampling(binding, &request.params)?; - drop(mtp_setup_span); - if n < 2 { - return Ok(()); - } - let setup_span = profile::span("prefill.setup"); - let tokens: Vec = request.prompt.iter().map(|&t| t as u32).collect(); - let source = OriginalPromptInput::from_tokenized(binding, &tokens)?; - let options = PromptOptions { - context_tokens: usize::try_from(self.config.max_context).map_err(|_| Error::Overflow)?, - prompt_cache: false, - turn_token: None, - root_min: 0, - // every conditioning read goes through the batched prefill (the verify-window read of short - // prompts needs the verifier during the prompt phase; see the open items) - short_read: 64, - force_batched: true, - verify_width: 4, - auto_max: 8192, - grid: 0, - }; - let (options, reread_to) = match (&self.prefix, &self.conversation) { - // the prefix cache reads on its grid and has no turn/root cuts: every checkpoint is a pure function of its tokens - // (a request that resumes between two grid points, from a request-end checkpoint, reads its suffix in as few chunks as the - // capacity allows: its states are not grid-canonical anyway) - (Some(prefix), _) => (PromptOptions { grid: if resume % prefix.block_tokens() == 0 { prefix.block_tokens() } else { 0 }, ..options }, None), - (None, Some(conversation)) => (conversation.config().plan_options(options), conversation.reread_to()), - (None, None) => (options, None), - }; - let capacity = self.config.capacity; - let plan = PromptPlan::new(&tokens, resume, reread_to, None, options, capacity).map_err(|e| { crate::bringup_trace!("DBG[{:.0}s] PromptPlan::new err {e:?} (n={n} capacity={capacity})", dbg_el()); plan_error(e) })?; - crate::bringup_trace!("DBG[{:.0}s] prompt plan ok", dbg_el()); - drop(setup_span); - for action in plan { - crate::bringup_trace!("DBG[{:.0}s] prompt action path={:?} first={} count={}", dbg_el(), action.path, action.first, action.count); - if action.path == PromptPath::FinalSeed { - // the last prompt token is the first verify input of the decode phase - break; - } - let PromptPath::Batched { .. } = action.path else { - return Err(Error::IdentityMismatch.into()); - }; - if self.session.target_origin()?.next_position() != action.first as u64 { - return Err(Error::IdentityMismatch.into()); - } - if cancel() { - return Err(SpecError::Cancelled); - } - if let Some(prefix) = self.prefix.as_mut() { - prefix.before_chunk(action.first); - } - self.prefill_chunk(&source, action.count, cancel)?; - self.after_prompt_action(&request.prompt, &action); - self.prefix_after_chunk(&request.prompt, action.first + action.count); - } - if self.session.target_origin()?.next_position() != (n as u64 - 1) { - return Err(Error::IdentityMismatch.into()); - } - self.prefix_after_prefill(&request.prompt); - Ok(()) - } - - /// One batched chunk of `count` rows from the session's position: the forward transaction and its publication. - /// With a loan the chunk's buffers are the expert cache's last slots, lent for this chunk only (the lent - /// slots stay misses until `prefill_phase` refills them); otherwise the stack's own buffers. - pub(super) fn prefill_chunk( - &mut self, - source: &Rc, - count: usize, - cancel: &mut dyn FnMut() -> bool, - ) -> std::result::Result<(), SpecError> { - let Self { - binding, moe, arena, layout, expert_cache, loan, loan_tiers, executor, draft, session, kar, dense, embedding, - scalar_policy, .. - } = self; - let mut chunk = PromptChunk { - binding: *binding, - executor: &mut *executor, - dense: &*dense, - session: &mut *session, - source, - kar: kar.as_mut(), - moe: &mut *moe, - draft: &mut *draft, - embedding: &*embedding, - scalar_policy: &*scalar_policy, - }; - let first = chunk.session.target_origin().map(|o| o.next_position()).unwrap_or(0); - super::super::prefill_profile::begin_chunk(); - let ran = match (*loan, expert_cache.as_mut(), arena.as_mut()) { - (Some(slots), Some(cache), _) => match { - let _span = super::super::prefill_profile::span(super::super::prefill_profile::Stage::Lend, None); - // the smallest rung of the ladder that holds the chunk - let (slots, options) = tier_for(loan_tiers, count).map_or((slots, *layout), |t| (t.slots, t.layout)); - cache.lend_prefill_tail(slots, options) - } { - Ok(mut lent) => chunk.run(count, &mut lent, cancel), - Err(e) => Err(SpecError::Forward(super::super::original_serve_verifier::driver_error(&e))), - }, - (_, _, Some(own)) => chunk.run(count, own, cancel), - _ => Err(Error::IdentityMismatch.into()), - }; - if ran.is_ok() { - super::super::prefill_profile::end_chunk(first, count); - } - ran - } - - /// The prefix cache at the end of the prefill: with `TailMode::Prompt` or `Reply` a checkpoint at `n - 1`, where the next turn of - /// the session resumes (its prompt starts with this one). A checkpoint that cannot be taken costs only itself. - pub(super) fn prefix_after_prefill(&mut self, prompt: &[i32]) { - let Some(mut prefix) = self.prefix.take() else { return }; - let _span = profile::span("prefix.after_prefill"); - match prefix.after_prefill(self, prompt) { - Ok(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms }) => { - operator_text(&format!("prefix tail admit (prompt end): tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", bytes >> 20)); - } - Ok(other) => operator_text(&format!("prefix tail (prompt end) not taken: {other:?}: {}", prefix.take_note().unwrap_or_default())), - Err(error) => operator_text(&format!("prefix cache: {error:?} while checkpointing the end of the prefill; skipped")), - } - self.prefix = Some(prefix); - } - - /// The end of the decode (`TailMode::Reply`): a checkpoint at the end of the prompt and the committed reply. The session is settled and the - /// draft ring stands at its position (`decode_phase` made sure); the cells past the prompt were produced by the decode. - pub(super) fn prefix_after_decode(&mut self, consumed: &[i32]) { - let Some(mut prefix) = self.prefix.take() else { return }; - let _span = profile::span("prefix.after_decode"); - match prefix.after_decode(self, consumed) { - Ok(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms }) => { - operator_text(&format!("prefix tail admit (decode end): tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", bytes >> 20)); - } - Ok(other) => operator_text(&format!("prefix tail (decode end) not taken: {other:?}: {}", prefix.take_note().unwrap_or_default())), - Err(error) => operator_text(&format!("prefix cache: {error:?} while checkpointing the end of the decode; skipped")), - } - self.prefix = Some(prefix); - } - - /// The prefix cache after a published chunk: a checkpoint at the grid point if the policy wants one. A checkpoint - /// that cannot be built costs the cache, never the request. - pub(super) fn prefix_after_chunk(&mut self, prompt: &[i32], end: usize) { - let Some(mut prefix) = self.prefix.take() else { return }; - let _span = profile::span("prefix.after_chunk"); - match prefix.after_chunk(self, prompt, end) { - Ok(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms }) => { - if std::env::var_os("LELEKA_PREFIX_TRACE").is_some() { - operator_text(&format!("prefix admit: tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", bytes >> 20)); - } - } - Ok(other) => { - if std::env::var_os("LELEKA_PREFIX_TRACE").is_some() && !matches!(other, ChunkOutcome::Nothing) { - operator_text(&format!("prefix admit (grid point {end}) not taken: {other:?}: {}", prefix.take_note().unwrap_or_default())); - } - } - Err(error) => { - operator_text(&format!("prefix cache: {error:?} while checkpointing; dropping the cache")); - prefix.invalidate(); - } - } - self.prefix = Some(prefix); - } - - /// A cancel between two prompt chunks leaves the session at the last published one: that is still the request's conversation - /// (`ServeConversation::note_cancelled_prefill`). The claim needs the same state a live continuation needs at the next - /// request: nothing lost, the recurrent state settled and the draft ring at the session's position. - pub(super) fn keep_conversation_after_cancelled_prefill(&mut self, request: &ServeRequest) { - let Some(mut conversation) = self.conversation.take() else { return }; - if let Ok(position) = ResumeDevice::position(self) { - let in_step = ResumeDevice::live_in_step(self); - if conversation.note_cancelled_prefill(&request.prompt, position, in_step) { - operator_text(&format!("cancelled request keeps its conversation: {position} tokens live")); - } - } - self.conversation = Some(conversation); - } - - /// The conversation cache's bookkeeping after a published chunk. A checkpoint that cannot be saved costs - /// the cache, never the request: the cache is dropped and the request goes on. - pub(super) fn after_prompt_action(&mut self, prompt: &[i32], action: &crate::backend::original_prompt::PromptAction) { - let Some(mut conversation) = self.conversation.take() else { return }; - let _span = profile::span("conv.after_action"); - if let Err(error) = conversation.after_action(self, prompt, action) { - operator_text(&format!("conversation cache: {error}; dropping the cache")); - conversation.invalidate(); - } - self.conversation = Some(conversation); - } -} +mod impl_originalservestack_2; +mod impl_originalservestack_2_2; +mod impl_originalservestack_3; +mod impl_originalservestack_4; +mod impl_originalservestack_5; +mod impl_originalservestack_6; diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2.rs new file mode 100644 index 00000000..edeb0e26 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2.rs @@ -0,0 +1,271 @@ +//! Moved out of the parent module by STRA-338: impl OriginalServeStack. + +#[allow(unused_imports)] +use super::*; + + + +impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { + /// `generate.cpp` startup over the binding: embedding table, native head + embedding, dense weights at + /// the prompt capacity, the MoE arena cache, the target session, the prompt executor with the MTP + /// drafter, the prefill arena, and the per-request stages. `shared` is the session's reference to the + /// very context `context` borrows. + pub(crate) fn open( + binding: &'a ModelBinding, + context: &'ctx Context<'ctx>, + shared: Rc>, + config: StackConfig, + ) -> std::result::Result { + crate::bringup_trace!("DBG[{:.0}s] OriginalServeStack::open begin", dbg_el()); + config.validate().map_err(at("config.validate"))?; + // generate.cpp: qsa_set_kv_resident before any QSA state exists (every streamed owner sizes from it) + leleka_cuda_driver::configure_kv_resident(config.kv_resident).map_err(|_| ServeFailure { + error: Error::InvalidDimension, + detail: Some(format!("--kv-resident {}: the process already serves another resident KV window", config.kv_resident)), + })?; + if let Some(footprint) = config.kv_footprint() { + operator_note(&footprint.to_string()); + } + if !std::ptr::eq(context, &*shared) { + return Err(failure(Error::IdentityMismatch)); + } + if binding.layer_count() != 48 { + return Err(ServeFailure { error: Error::IdentityMismatch, detail: Some("the Original serve stack serves the 48-layer model only".to_owned()) }); + } + if !binding.has_mtp() { + return Err(ServeFailure { + error: Error::Unsupported(super::super::super::contract::Stage::Session), + detail: Some("the binding carries no MTP pack: the Original serve loop drafts with the MTP layer".to_owned()), + }); + } + let max_cells = usize::try_from(super::super::super::contract::serving_cells()).map_err(|_| failure(Error::Overflow))?; + let mut settings = OriginalServeSettings::from_environment(config.max_context, VOCABULARY, config.coupled); + let mut arm_label = String::from("env"); + let arm_order: Vec = OriginalServeSettings::arms_from_environment(config.max_context, VOCABULARY, config.coupled).into_iter().map(|(l, _)| l).collect(); + let mut parked = Vec::new(); + let arms = OriginalServeSettings::arms_from_environment(config.max_context, VOCABULARY, config.coupled); + let verifier_max_t = arms.iter().map(|(_, s)| s.max_t).chain([settings.max_t]).max().unwrap_or(settings.max_t); + if let Some(((label, first), rest)) = arms.split_first() { + settings = *first; + arm_label = label.clone(); + for (label, s) in rest { + parked.push((label.clone(), *s, s.controller().map_err(at("settings.controller"))?)); + } + } + let controller = settings.controller().map_err(at("settings.controller"))?; + let rope = RopeConstants::from_serving_context(); + let blobs = ExpertBlobSizes::from_binding(binding).map_err(at("ExpertBlobSizes::from_binding"))?; + let formats = expert_formats(binding).map_err(at("expert_formats"))?; + let layout = prefill_layout_options(config.capacity, max_cells, &blobs); + + vram_note(context, "open begin"); + // The native head + embedding come first: with LELEKA_PROMPT_EMBED_ALIAS=1 the prompt path's token table aliases the mapped host copy + // of the native embedding instead of a second copy in VRAM (the two are the same GGUF tensor). + let output = staged!("native head + embedding", context, OriginalNativeOutput::load(binding, context, NativeHeadDispatch::default(), true).map_err(at("OriginalNativeOutput::load"))?); + let embedding = staged!("embedding table", context, if OriginalPromptEmbedding::alias_enabled() { + OriginalPromptEmbedding::alias_native(binding, context, output.embedding(binding).map_err(at("OriginalNativeOutput::embedding"))?).map_err(at("OriginalPromptEmbedding::alias_native"))? + } else { + OriginalPromptEmbedding::load(binding, context).map_err(at("OriginalPromptEmbedding::load"))? + }); + let kar = staged!("KAR PLE cache", context, match binding.kar_ple_binding() { + Some(provider) => Some(KarPleCache::new(context, provider).map_err(at("KarPleCache::new"))?), + None => None, + }); + let dense = staged!("dense weights", context, DenseWeightCache::new_original_prompt_capacity(binding, context, config.capacity).map_err(at("DenseWeightCache::new_original_prompt_capacity"))?); + let mut moe = staged!("MoE arena cache", context, MoeWeightCache::new_original_prompt_arena(binding, context, layout, super::super::super::original_serve_config::mtp_pack_experts_needed(config.rt_directory.is_some())).map_err(at("MoeWeightCache::new_original_prompt_arena"))?); + if !super::super::super::original_serve_config::mtp_pack_experts_needed(config.rt_directory.is_some()) { + operator_note("footprint: the pinned MTP pack's expert bank (675 MiB) is not uploaded: the draft layer is loaded from the RT directory and never reads it (LELEKA_FOOTPRINT_LEGACY=1 keeps it)"); + } + vram_note(context, "after embedding, output, kar, dense, moe arena"); + let mut session = QwenSession::for_binding_on_shared_device(binding, shared); + let request = OriginalMtpRequest::ring_int8(verifier_max_t, config.capacity, settings.coupled, MTP_RESIDENT_CELLS); + let executor_stage = crate::memory_governor::begin("prompt executor + MTP drafter", Some(context)); + let (executor, draft) = match &config.rt_directory { + Some(directory) => OriginalPromptExecutor::select_rt_mtp( + binding, &dense, &mut session, context, &embedding, &output, directory, config.capacity, true, &request, + ) + .map_err(|e| ServeFailure { error: e.error, detail: e.message })?, + None => { + let mut executor = OriginalPromptExecutor::new( + binding, &dense, &mut session, context, &moe, &embedding, config.capacity, verifier_max_t, true, + ).map_err(at("OriginalPromptExecutor::new"))?; + let assembly = OriginalMtpFullOwner::assemble(binding, &session, context, &moe, &embedding, &output, &request) + .map_err(|e| ServeFailure { error: e.error, detail: e.message })?; + let draft = executor.install_full_mtp(binding, &session, assembly).map_err(at("install_full_mtp"))?; + (executor, draft) + } + }; + // RT-directory draft: the MTP dense roles sit twice in VRAM (this cache's pinned-pack upload and the RT bank's); merge them when proven byte-equal + if config.rt_directory.is_some() && !super::super::super::original_serve_config::legacy_footprint() { + if let Some(retained) = executor.retained_mtp_weights() { + let share = moe.share_rt_mtp_dense(retained).map_err(at("share_rt_mtp_dense"))?; + operator_note(&format!( + "footprint: MTP dense roles shared with the RT bank (byte-equal): {} shared, {} kept ({} differing), {:.1} MiB released", + share.shared, share.kept, share.differing, share.released_bytes as f64 / f64::from(1u32 << 20) + )); + } + } + vram_note(context, "after prompt executor and draft"); + let mut executor = executor; + crate::memory_governor::end(executor_stage, Some(context)); + // generate.cpp: the expert cache is sized after everything else, and the prompt path's own buffers + // after the cache when it cannot borrow them; without the tier the order is unchanged. + let tier = config.expert_tier.enabled(); + let mut arena = staged!("prefill arena", context, if tier { None } else { Some(context.original_prefill_arena(layout).map_err(at("original_prefill_arena"))?) }); + vram_note(context, "before cache"); + let history = staged!("penalty history", context, OriginalNativePenaltyHistory::new(binding, context).map_err(at("OriginalNativePenaltyHistory::new"))?); + let ple_history = context.allocate(PLE_HISTORY_BYTES).map_err(at("ple_history"))?; + let ple_scratch = context.allocate(PLE_SCRATCH_BYTES).map_err(at("ple_scratch"))?; + let pool = staged!("CPU expert pool", context, CpuExpertPool::new(binding, config.cpu_workers).map_err(at("CpuExpertPool::new"))?); + let empty_session = staged!("empty-prompt session checkpoint", context, executor.checkpoint_session(binding, &mut session).map_err(at("checkpoint_session"))?); + let empty_draft = staged!("empty-prompt draft checkpoint", context, draft.checkpoint(binding, &session).map_err(at("draft.checkpoint"))?); + let prefix = match &config.prefix { + Some(prefix_config) => { + let available = crate::conversation::memory::available_memory(); + // the budget comes from the memory governor (what is left above the floors), not from an independent default + let complement_pending = (config.expert_tier.resident_budget_gib.max(0.0) * (1u64 << 30) as f64) as u64; + let bytes = crate::memory_governor::resolve_prefix_budget(prefix_config.budget, available, complement_pending) + .unwrap_or_else(|| prefix_config.resolve_budget(available)); + let mut prefix_config = prefix_config.clone(); + if let Some(g) = leleka_memory::Governor::global() { + // stop admitting before anything has to be shed: soft floor + reserve (the real CRM session sat 4.4 GiB above a 3 GiB floor) + prefix_config.memory_floor = prefix_config.memory_floor.max(g.policy().admit_floor()); + } + let prefix_config = &prefix_config; + if bytes == 0 { + operator_note(&format!( + "prefix cache off (budget {:?}, available host memory {:?} MiB)", + prefix_config.budget, + available.map(|b| b >> 20) + )); + None + } else { + let identity = format!("qwen4exp:{PINNED_MODEL}:kv={:?}:resident={}", config.kv_format, config.kv_resident); + let serve = PrefixServe::new(prefix_config.clone(), config.capacity, bytes, &identity); + operator_note(&format!( + "prefix cache on: block/grid {} tokens, budget {} MiB, state ~{} MiB + {} B per token, host memory available {:?} MiB, namespace {}", + serve.block_tokens(), + bytes >> 20, + PARKED_STATE_ESTIMATE >> 20, + PARKED_BYTES_PER_TOKEN, + available.map(|b| b >> 20), + crate::prefix_cache::summary::hex(serve.namespace()) + )); + Some(serve) + } + } + None => None, + }; + let conversation = if prefix.is_some() { None } else { config.conversation.clone().map(ServeConversation::new) }; + let residency = ResidencyState::new(&config.expert_tier); + report_kernel_selection(); + vram_note(context, "before expert tier"); + let mut loan = None; + let tier_open = staged!("expert tier (VRAM slots + profile fill)", context, original_serve_residency::open_tier(binding, context, &moe, &config.expert_tier, config.capacity).map_err(at("expert tier"))?); + let expert_cache = match tier_open { + Some((cache, filled)) => { + if config.expert_tier.prefill_borrow && config.expert_tier.profile.is_some() { + loan = original_serve_residency::loan_slots(&cache, prefill_bytes(layout).map_err(at("prefill bytes"))?) + .map_err(at("expert-cache loan"))?; + } + operator_note(&format!( + "expert cache {} slots ({:.2} GiB, {}), {filled} filled from the profile; the prompt path {}; GPU experts round differently from the CPU's (bench/results/2026-09-27-cache-parity)", + cache.slots(), + cache.bytes() as f64 / f64::from(1u32 << 30), + if cache.per_layer_admission() { "per layer" } else { "global" }, + match loan { + Some(k) => format!("borrows its last {k} slots"), + None => "allocates its own buffers".to_owned(), + } + )); + Some(cache) + } + None => None, + }; + vram_note(context, "after expert tier"); + let mut loan_tiers: Vec = Vec::new(); + if let (Some(full), Some(cache), true) = (loan, expert_cache.as_ref(), config.loan_tiers) { + for rows in LOAN_TIER_ROWS.into_iter().filter(|&r| r < config.capacity) { + let tier_layout = PrefillLayoutOptions { capacity: rows, ..layout }; + let slots = original_serve_residency::loan_slots(cache, prefill_bytes(tier_layout).map_err(at("prefill bytes (tier)"))?).map_err(at("expert-cache loan (tier)"))?; + if let Some(slots) = slots.filter(|&s| s < full && loan_tiers.last().is_none_or(|t| s > t.slots)) { + loan_tiers.push(LoanTier { rows, layout: tier_layout, slots }); + } + } + if !loan_tiers.is_empty() { + operator_note(&format!( + "prompt loan ladder: {}, up to {} rows {full} slots", + loan_tiers.iter().map(|t| format!("up to {} rows {} slots", t.rows, t.slots)).collect::>().join(", "), + config.capacity + )); + } + } + let initial_owners: Vec> = expert_cache + .as_ref() + .map(|cache| (0..cache.slots()).map(|slot| cache.slot_owner(slot)).collect()) + .unwrap_or_default(); + if arena.is_none() && loan.is_none() { + arena = Some(staged!("prefill arena (after the expert tier)", context, context.original_prefill_arena(layout).map_err(at("original_prefill_arena"))?)); + } + let this = Self { + binding, + context, + conversation, + prefix, + tail_consumed: None, + reused: 0, + resume_point: 0, + full_policy: mtp_full_policy(&rope), + scalar_policy: mtp_scalar_policy(&rope), + config, + settings, + max_cells, + rope, + blobs, + formats, + controller, + parked, + arm_label, + arm_order, + verifier_max_t, + broken: None, + empty_session, + empty_draft, + history, + ple_history, + ple_scratch, + arena, + layout, + expert_cache, + loan, + loan_tiers, + residency, + initial_owners, + seed_report: None, + seed_counts: None, + refill_pending: false, + refill_due: false, + timing: (0.0, 0.0), + marks: TtftMarks::default(), + executor, + draft, + session, + pool, + kar, + moe, + dense, + output, + embedding, + }; + this.register_memory_classes(); + crate::memory_governor::post_open(); + if let Some(governor) = leleka_memory::Governor::global() { + governor.log(&format!("stack open; inventory of allocation classes (accounted by their owners): +{}", governor.inventory().table())); + governor.log(&format!("load ledger (measured: kernel and driver deltas per opening step): +{}", governor.ledger().table())); + governor.publish(); + } + Ok(this) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2_2.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2_2.rs new file mode 100644 index 00000000..5fa844bf --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2_2.rs @@ -0,0 +1,257 @@ +//! Moved out of the parent module by STRA-338: impl OriginalServeStack (2). + +#[allow(unused_imports)] +use super::*; + + + +impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { + + /// `Some` once a physical owner was lost: the stack must be closed and rebuilt. + pub(crate) fn health(&self) -> Option { + self.broken + } + + /// One request. Admission, reset, prompt conditioning and decode in order; see `run_request`. + pub(crate) fn serve( + &mut self, + request: &ServeRequest, + emit: &mut dyn FnMut(&[i32]) -> Result<()>, + cancel: &mut dyn FnMut() -> bool, + ) -> std::result::Result { + self.apply_memory_directive(); + self.marks = TtftMarks::start(); + let max_context = self.config.max_context; + let result = run_request(self, request, max_context, emit, cancel); + self.note_memory(); + result + } + + /// Follow the memory governor between requests: under pressure the prefix cache evicts (and restores its budget when the + /// pressure is over), and the conversation checkpoints are dropped. Cheap: a few atomics when nothing changed. + pub(in super::super) fn apply_memory_directive(&mut self) { + let Some(governor) = leleka_memory::Governor::global() else { return }; + let used = self.prefix.as_ref().map_or(0, |p| p.bytes() as u64); + let directive = governor.directive(used); + if let Some(prefix) = self.prefix.as_mut() { + let before = prefix.bytes(); + let freed = prefix.apply_shed(directive.prefix_budget, governor); + if freed > 0 { + operator_note(&format!( + "memory pressure ({}): prefix cache evicted {} MiB ({} -> {} MiB), budget {} MiB", + directive.level.as_str(), + freed >> 20, + before >> 20, + prefix.bytes() >> 20, + prefix.budget_bytes() >> 20 + )); + } + } + if directive.drop_conversation + && let Some(conversation) = self.conversation.as_mut() + && conversation.checkpoint_count() > 0 + { + conversation.invalidate(); + operator_note(&format!("memory pressure ({}): conversation checkpoints dropped", directive.level.as_str())); + } + } + + /// Keep the inventory's elastic classes current (the prefix store and the conversation checkpoints). + pub(in super::super) fn note_memory(&self) { + if leleka_memory::Governor::global().is_none() { + return; + } + if let Some(prefix) = self.prefix.as_ref() { + crate::memory_governor::set_bytes("prefix.store", prefix.bytes() as u64); + if let Some(g) = leleka_memory::Governor::global() { + g.note_prefix_used(prefix.bytes() as u64); + } + } + if let Some(conversation) = self.conversation.as_ref() { + crate::memory_governor::set_bytes("conversation.checkpoints", conversation.checkpoint_count() as u64 * crate::memory_governor::CHECKPOINT_BYTES); + } + } + + /// Register the stack's allocation classes with the inventory (sizes from the owners' own formulas and counters). + pub(in super::super) fn register_memory_classes(&self) { + use leleka_memory::{Space, When}; + let Some(governor) = leleka_memory::Governor::global() else { return }; + let _ = governor; + if let Some(f) = self.config.kv_footprint() { + crate::memory_governor::account("kv", "host_pinned", Space::HostPinned, When::Startup, "12 QSA layers x serving cells x 1056 B, pinned and device-mapped (the whole serving context, allocated at open)", f.pinned_host_bytes as u64); + crate::memory_governor::account("kv", "vram_window", Space::Device, When::Startup, "12 layers x resident pages x 4244 B (+ page table + resolver state)", f.vram_bytes as u64); + crate::memory_governor::account("kv", "prompt_stage", Space::Device, When::Startup, "one INT8 staging pool of the prompt path (identity layout)", f.stage_bytes as u64); + } + if let Ok(bytes) = prefill_bytes(self.layout) { + crate::memory_governor::account( + "prefill", + if self.loan.is_some() { "arena_borrowed" } else { "arena" }, + Space::Device, + When::Startup, + if self.loan.is_some() { "carve of the prefill arena, borrowed from the last slots of the expert cache (not additional)" } else { "carve of the prefill arena at the chunk capacity" }, + if self.loan.is_some() { 0 } else { bytes as u64 }, + ); + } + if let Some(cache) = self.expert_cache.as_ref() { + crate::memory_governor::account("expert_cache", "slots", Space::Device, When::Startup, "slots x slot bytes (VRAM expert tier)", cache.bytes() as u64); + } + crate::memory_governor::account("ple", "history_and_scratch", Space::Device, When::Startup, "PLE history image + scratch", (PLE_HISTORY_BYTES + PLE_SCRATCH_BYTES) as u64); + crate::memory_governor::account("context", "accounted_total", Space::Device, When::Lazy, "sum of the context's budgeted allocations (not additive with the classes above; see the ledger for the driver-seen total)", 0); + if let Some(prefix) = self.prefix.as_ref() { + crate::memory_governor::account( + "prefix", + "store", + Space::HostPageable, + When::Elastic, + "blocks (14,208 B per token) + node states (~127 MiB each) under the governor-granted budget", + prefix.bytes() as u64, + ); + } + if self.conversation.is_some() { + crate::memory_governor::account( + "conversation", + "checkpoints", + Space::HostPageable, + When::Elastic, + "checkpoints x ~118 MiB (GDN/PLE images, draft ring, index tails)", + 0, + ); + } + } + + /// Labels of the window policies of `LELEKA_SPEC_ARMS` in the order given (empty when unset), the live one included. + #[allow(dead_code)] + pub(crate) fn spec_arms(&self) -> Vec { + self.arm_order.clone() + } + /// Make `label` the window policy of the following requests (between requests only). Returns false for an unknown label. + #[allow(dead_code)] + pub(crate) fn select_spec_arm(&mut self, label: &str) -> bool { + if self.arm_label == label { + return true; + } + let Some(at) = self.parked.iter().position(|(l, _, _)| l == label) else { return false }; + let (new_label, new_settings, new_controller) = self.parked.swap_remove(at); + let old_label = std::mem::replace(&mut self.arm_label, new_label); + let old_settings = std::mem::replace(&mut self.settings, new_settings); + let old_controller = std::mem::replace(&mut self.controller, new_controller); + self.parked.push((old_label, old_settings, old_controller)); + true + } + /// The live arm's own request floor, if its label pinned one (`fixed4@0`). + #[allow(dead_code)] + pub(crate) fn spec_arm_min_p(&self) -> Option { + self.settings.request_min_p + } + #[allow(dead_code)] + pub(crate) fn spec_arm(&self) -> &str { + &self.arm_label + } + + /// Wall-clock milliseconds of the last request's prompt phase and decode phase. + #[cfg_attr(not(test), allow(dead_code))] + pub(crate) fn last_timing(&self) -> (f64, f64) { + self.timing + } + + /// Where the last request's time to first token went: `(resumed, prefilled, assembled, first_round)`, each the + /// milliseconds since `serve` was entered when that stage ended (`resumed`: the cache lookup, import and any reset; + /// `prefilled`: the prompt chunks, the lent-slot refill and the seed; `assembled`: the verifier (graphs, canonical + /// state upload); `first_round`: the first verified round was emitted). NaN for a stage the request did not reach. + #[allow(dead_code)] + pub(crate) fn ttft_marks(&self) -> [f64; 4] { + self.marks.as_array() + } + + /// The VRAM expert tier's counters (`None` when the tier is off). + pub(crate) fn expert_tier_stats(&self) -> Option { + self.expert_cache.as_ref().map(|cache| { + let mut stats = self.residency.stats; + stats.swaps = cache.swaps(); + stats + }) + } + + /// The tier's configuration, for an experiment that switches the adaptive tier or the seed between requests (the + /// adaptive counts are allocated at open, so `adapt_every` may be changed freely, a seed needs the tier on). + #[allow(dead_code)] + pub(crate) fn expert_tier_mut(&mut self) -> &mut ExpertTierConfig { + &mut self.config.expert_tier + } + + /// The last request's seed from the prompt's routing (`None`: seed off, or no prompt rows were read). + #[allow(dead_code)] + pub(crate) fn last_seed(&self) -> Option { + self.seed_report + } + + /// Cumulative (vram, pcie, cpu) window entries after each verified round of the last request. + #[allow(dead_code)] + pub(crate) fn round_marks(&self) -> Vec<[u64; 3]> { + self.residency.round_marks() + } + + /// A first-request state for an experiment: the tier back on the starting profile's set, the adaptive counts and + /// the draft/adaptation controller as in a new process. Returns the swaps the restore needed. + #[allow(dead_code)] + pub(crate) fn reset_expert_tier(&mut self) -> Result { + if let Some(error) = self.broken { + return Err(error); + } + self.residency.clear_usage(); + self.controller = self.settings.controller()?; + match self.expert_cache.as_mut() { + Some(cache) => original_serve_seed::restore_placement(self.binding, &self.moe, cache, &mut self.pool, &mut self.residency.spans, &self.initial_owners), + None => Ok(0), + } + } + + /// Prompt tokens the last request reused from the conversation cache (generate.cpp `REUSED`). + pub(crate) fn reused_tokens(&self) -> usize { + self.reused + } + + /// The position the conversation cache resumed the last request at (equals `reused_tokens` unless + /// `STRATA_CKPT_REREAD` re-read that prefix from 0). + #[cfg_attr(not(test), allow(dead_code))] + pub(crate) fn resume_point(&self) -> usize { + self.resume_point + } + + /// Drop every conversation checkpoint and the live state: the next request reads its whole prompt. + #[cfg_attr(not(test), allow(dead_code))] + pub(crate) fn forget_conversation(&mut self) { + if let Some(conversation) = self.conversation.as_mut() { + conversation.invalidate(); + } + if let Some(prefix) = self.prefix.as_mut() { + prefix.invalidate(); + } + } + + /// Verification arm: while set, requests read their whole prompt on the grid without using or changing the prefix + /// cache (the reference a cached request must reproduce). + #[allow(dead_code)] + pub(crate) fn prefix_bypass(&mut self, bypass: bool) { + if let Some(prefix) = self.prefix.as_mut() { + prefix.set_bypass(bypass); + } + } + + /// Drop the cached sessions nobody used for the retention time (60 minutes by default); the idle loop calls this. + pub(crate) fn prefix_expire_idle(&mut self) -> usize { + self.prefix.as_mut().map_or(0, |prefix| prefix.expire_idle()) + } + + /// The prefix cache's summary for a front router (`None` when the cache is off). + #[allow(dead_code)] + pub(crate) fn prefix_summary(&self, max_heads: usize) -> Option { + self.prefix.as_ref().map(|prefix| prefix.summary(max_heads)) + } + + /// The `prefix_match` query: how many tokens of the prompt whose block hash chain is `chain` are cached. + #[allow(dead_code)] + pub(crate) fn prefix_match(&self, chain: &[u64]) -> Option { + self.prefix.as_ref().map(|prefix| prefix.prefix_match(chain)) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_3.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_3.rs new file mode 100644 index 00000000..3dcd0284 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_3.rs @@ -0,0 +1,64 @@ +//! Moved out of the parent module by STRA-338: impl OriginalServeStack (3). + +#[allow(unused_imports)] +use super::*; + + + +impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { + + /// The prefix cache's metrics line (`None` when the cache is off). + #[allow(dead_code)] + pub(crate) fn prefix_metrics(&self) -> Option { + self.prefix.as_ref().map(|prefix| prefix.describe()) + } + + /// Bytes the prefix cache holds now (0 when it is off). + #[allow(dead_code)] + pub(crate) fn prefix_bytes(&self) -> usize { + self.prefix.as_ref().map_or(0, |prefix| prefix.bytes()) + } + + /// The prefix cache's current byte budget (0 when it is off or fully shed). + #[allow(dead_code)] + pub(crate) fn prefix_budget_bytes(&self) -> usize { + self.prefix.as_ref().map_or(0, |prefix| prefix.budget_bytes()) + } + + /// Close every owner in dependency order; the first failure is reported after all were attempted. + pub(crate) fn close(self) -> Result<()> { + let Self { + conversation, residency, history, ple_history, ple_scratch, arena, expert_cache, executor, draft, session, pool, kar, + moe, dense, output, embedding, .. + } = self; + drop(conversation); + // the span cache retains registered-source spans of the bank `moe` closes below + drop(residency); + let mut first: Option = None; + let mut note = |result: Result<()>| { + if let Err(error) = result { + first.get_or_insert(error); + } + }; + note(history.close()); + note(ple_history.release().map_err(|_| Error::CudaExecution)); + note(ple_scratch.release().map_err(|_| Error::CudaExecution)); + drop(arena); + if let Some(cache) = expert_cache { + note(cache.close().map_err(|e| super::super::super::original_serve_verifier::driver_error(&e))); + } + note(executor.close()); + note(draft.close()); + drop((session, pool, kar)); + note(moe.close()); + note(dense.close()); + // the prompt path's token table may alias the native embedding's mapped copy: it goes first + note(embedding.close()); + note(output.close()); + first.map_or(Ok(()), Err) + } + + pub(in super::super) fn mark_broken(&mut self, error: Error) { + self.broken.get_or_insert(error); + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_4.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_4.rs new file mode 100644 index 00000000..599a132a --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_4.rs @@ -0,0 +1,341 @@ +//! Moved out of the parent module by STRA-338: impl OriginalServeStack (4). + +#[allow(unused_imports)] +use super::*; + + + +impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { + + /// Hand the twelve QSA owners to a fresh verifier and run the request's decode phase over it. + pub(in super::super) fn decode_phase( + &mut self, + request: &ServeRequest, + emit: &mut dyn FnMut(&[i32]) -> Result<()>, + cancel: &mut dyn FnMut() -> bool, + ) -> std::result::Result { + let Self { + binding, + context, + config, + settings, + max_cells, + rope, + blobs, + formats, + full_policy, + controller, + parked, + arm_label, + verifier_max_t, + history, + ple_history, + ple_scratch, + executor, + draft, + session, + pool, + kar, + moe, + dense, + output, + broken, + conversation, + expert_cache, + residency, + refill_pending, + refill_due, + marks, + prefix, + tail_consumed, + .. + } = self; + let binding: &ModelBinding = *binding; + let context: &'ctx Context<'ctx> = *context; + if controller.is_failed() { + // a failed restore/finish poisoned the controller; its adaptive cadence is the only thing lost + *controller = settings.controller()?; + } + crate::bringup_trace!("DBG[{:.0}s] decode_phase start", dbg_el()); + let sampling = RequestSampling::new(request.params, request.path)?; + let n = request.prompt.len(); + let base = session.original_verified_base()?; + crate::bringup_trace!("DBG[{:.0}s] decode: base position {} (n-1 = {})", dbg_el(), base.position, n as u64 - 1); + if base.position != (n as u64 - 1) { + return Err(Error::IdentityMismatch.into()); + } + // generate.cpp `ver.set_pcie_mode`: only a window that can stage anything over PCIe records the copy kernel. + let pcie_mode = match (expert_cache.as_ref(), moe.original_expert_bank()) { + (Some(_), Some(bank)) if config.expert_tier.pcie_num_for(bank.pageable()) > 0 => { + config.expert_tier.pcie_mode.graph_mode(bank.pageable(), blobs.spans_tile_blobs()).ok_or(Error::Unsupported( + super::super::super::contract::Stage::Session, + ))? + } + _ => 0, + }; + let p = profile::span("decode.seed_ple"); + seed_ple_history(&base, ple_history).map_err(|f| SpecError::Forward(f.error))?; + drop(p); + // the window reads the shared experts of all 48 layers in place: load/refresh them together first + let p = profile::span("decode.shared"); + let shared = moe.ensure_original_verify_shared(binding)?; + drop(p); + crate::bringup_trace!("DBG[{:.0}s] decode: shared experts loaded", dbg_el()); + let owners = executor.take_qsa_owners()?; + let ple_history: &DeviceBuffer<'ctx> = &*ple_history; + let weights = VerifyWeights { dense: &*dense, moe: &*moe, shared: &shared, formats: &*formats, ple_scratch: &*ple_scratch }; + let p = profile::span("decode.assemble"); + // queued after assembly's own uploads (canonical GDN image), before the graph capture + let mut queue_refill = || -> Result<()> { + if !std::mem::take(&mut *refill_due) { + return Ok(()); + } + if let Some(cache) = expert_cache.as_mut() { + let _p = profile::span("prefill.refill"); + original_serve_residency::refill_lent(binding, &*moe, cache, &mut residency.spans, true)?; + *refill_pending = true; + } + Ok(()) + }; + // A window or commit graph that does not fit in device memory costs the widest windows, not the request or the engine + // (upstream a8c1d4b7): the assembly is repeated with the windows that fit. The owners come back from each failure. + let mut owners_slot = Some(owners); + let (used_max_t, assembled) = assemble_with_window_fallback( + *verifier_max_t, + |max_t| { + let Some(owners) = owners_slot.take() else { + return Err((AssembleFailure { failure: Error::IdentityMismatch.into(), owners: None, window_cap: None }, None)); + }; + assemble( + binding, &weights, context, &*output, &base, owners, ple_history, rope, blobs, max_t, *max_cells, pcie_mode, + &mut queue_refill, + ) + .map_err(|mut lost| { + let cap = lost.window_cap.filter(|&cap| cap < max_t); + if cap.is_some() { + owners_slot = lost.owners.take(); + } + (lost, cap) + }) + }, + |failed, next| { + operator_text(&format!( + "decode window graphs: out of device memory recording windows up to T={failed}; retrying with windows up to T={next}" + )) + }, + ); + drop(p); + marks.assembled = marks.since(); + // the lent slots' refill copies (queued at the end of the prompt phase) have run behind the assembly: wait for them + // before a window or the tier's own bookkeeping touches the cache + if std::mem::take(refill_pending) { + if let Some(cache) = expert_cache.as_mut() { + if let Err(error) = original_serve_residency::settle_refill(cache) { + broken.get_or_insert(error); + if let Ok(resources) = assembled { + let _ = disassemble(resources).map(|owners| executor.adopt_qsa_owners(binding, &*dense, &mut *session, owners)); + } + return Err(SpecError::Forward(error)); + } + } + } + vram_note(context, "decode after assemble"); + crate::bringup_trace!("DBG[{:.0}s] decode: assemble -> {}", dbg_el(), if assembled.is_ok() { "ok" } else { "ERR" }); + let resources = match assembled { + Ok(resources) => resources, + Err(lost) => { + operator_line("assemble", &lost.failure); + if let Some(owners) = lost.owners { + if let Err(error) = executor.adopt_qsa_owners(binding, &*dense, &mut *session, owners) { + broken.get_or_insert(error); + } + } else { + broken.get_or_insert(Error::IdentityMismatch); + } + return Err(SpecError::Forward(lost.failure.error)); + } + }; + if used_max_t < *verifier_max_t { + // The card holds windows only up to `used_max_t`: every policy of the stack follows, for this and the later requests (the + // controllers restart; what they learned about the wider windows no longer applies). + operator_text(&format!( + "decode window graphs: windows limited to T<={used_max_t} (were T<={}): the policy, its arms and the MTP draft cap follow", + *verifier_max_t + )); + *verifier_max_t = used_max_t; + let narrowed = (|| -> Result<()> { + *settings = settings.with_window_cap(used_max_t); + *controller = settings.controller()?; + for (_, arm, arm_controller) in parked.iter_mut() { + *arm = arm.with_window_cap(used_max_t); + *arm_controller = arm.controller()?; + } + executor.set_mtp_max_drafts(binding, i32::try_from(settings.max_drafts()).map_err(|_| Error::Overflow)?) + })(); + if let Err(error) = narrowed { + let _ = disassemble(resources).map(|owners| executor.adopt_qsa_owners(binding, &*dense, &mut *session, owners)); + broken.get_or_insert(error); + return Err(SpecError::Forward(error)); + } + } + let DecodeResources { verifier, qsa, slots } = resources; + // the NaN guard's retry takes a refused window back from these (OriginalVerifier::discard_window) + qsa.set_window_snapshots(settings.nan_guard.retries > 0); + let committed = request.prompt[..n - 1].to_vec(); + // The window's expert tier: the GPU share first and the CPU pool on the rest, or the CPU pool alone. + let mut gpu_pool; + let pool: &mut dyn OriginalServePool<'ctx> = match (expert_cache.as_mut(), moe.original_expert_bank()) { + (Some(cache), Some(bank)) => { + let pcie_num = config.expert_tier.pcie_num_for(bank.pageable()); + let tail_rank = original_serve_residency::effective_tail_rank(&*cache); + let pcie_locked = if pcie_num > 0 && original_serve_residency::pcie_locked_only() { bank.locked_experts() } else { Vec::new() }; + gpu_pool = GpuExpertPool { + binding, + moe: &*moe, + cache, + bank, + cpu: &mut *pool, + state: &mut *residency, + pcie_num, + adapt_every: config.expert_tier.adapt_every, + adapt_swaps: config.expert_tier.adapt_swaps as usize, + tail_rank, + pcie_locked, + }; + &mut gpu_pool + } + (Some(_), None) => return Err(SpecError::Forward(Error::IdentityMismatch)), + (None, _) => &mut *pool, + }; + let owners = HostOwners { + binding, + dense: &*dense, + context, + session: &mut *session, + draft: &mut *draft, + executor: &mut *executor, + kar: kar.as_mut(), + history: &mut *history, + pool, + qsa: Rc::clone(&qsa), + slots, + ple_history, + policy: &*full_policy, + }; + let want_tail = config.prefix.as_ref().is_some_and(|p| p.tail == TailMode::Reply) && prefix.is_some(); + controller.set_final_draft(want_tail); + *tail_consumed = None; + let host = OriginalServeHost::new(owners, committed, config.max_context as u64, sampling); + let (served, verifier, outcome) = match host { + Err(error) => (Err(SpecError::Forward(error)), verifier, None), + Ok(host) => { + let port = super::super::super::original_serve_engine::TracePort(NativeServePort::new(verifier, host)); + let engine = OriginalServeEngine::new(port, VOCABULARY, settings.max_t, settings.max_drafts()); + match engine { + Err(error) => { + // `new` consumed the port on failure; the verifier is gone with it. Treated as lost below. + let _ = error; + broken.get_or_insert(Error::IdentityMismatch); + return Err(SpecError::Forward(Error::IdentityMismatch)); + } + Ok(mut engine) => { + crate::bringup_trace!("DBG[{:.0}s] decode: engine ready, serving", dbg_el()); + let started = Instant::now(); + let serve_span = profile::span("decode.serve"); + let result = engine.set_min_p(request.spec_min_p).map_err(SpecError::Forward).and_then(|()| { + serve_request( + controller, + &mut engine, + &request.prompt, + request.max_new, + request.spec_min_p, + &request.eos, + |tokens| { + if marks.first_round.is_nan() { + marks.first_round = marks.since(); + } + emit(tokens) + }, + &mut *cancel, + || started.elapsed().as_secs_f64() * 1e3, + ) + }); + drop(serve_span); + { + // the controller's round counters belong to this request in every window policy + let stats = controller.take_stats(); + if super::super::super::original_spec_controller::stats_enabled() { + eprintln!("DBG spec-stats arm={} {}", arm_label, stats.line()); + } + } + if let Err(e) = &result { crate::bringup_trace!("DBG[{:.0}s] serve_request err {e:?}", dbg_el()); } + let (mut verifier, mut host) = engine.into_port().0.into_parts(); + // STRATA_VERIFY_PROFILE=1: the GPU stage times of the request's windows (empty otherwise) + let gpu_profile = verifier.profile_report(); + if !gpu_profile.is_empty() { + eprintln!("DBG verify-profile:{gpu_profile}"); + } + // conversation cache: the session can be continued as is only when the draft ring + // stands at its position (then its recurrent state is settled to match) + let live = conversation.is_some() + && matches!(result, Ok(_) | Err(SpecError::Cancelled)) + && host.draft_in_step(); + // prefix cache, TailMode::Reply: the session settled and the ring in step (the final window was drafted) + let tail = want_tail && result.is_ok() && prefix.is_some() && host.draft_in_step(); + if want_tail && result.is_ok() && !tail { + operator_text("prefix tail: the draft ring is not at the session's position; no checkpoint at the end of this decode"); + } + if (result.is_ok() && config.settle_state) || live || tail { + match host.settle_state(&mut verifier) { + Ok(()) if live => { + if let Some(conversation) = conversation.as_mut() { + conversation.note_live(host.committed().to_vec()); + } + } + Ok(()) if tail => *tail_consumed = Some(host.committed().to_vec()), + Ok(()) => {} + Err(error) => { + broken.get_or_insert(error); + } + } + } + let outcome = host.finish(); + (result, verifier, Some(outcome)) + } + } + } + }; + // The MTP drafter's cached round programs and staged window are bound to THIS verifier's bank: release them before the + // bank closes (it is shared while they live) and so the next request captures against its own bank. + let p = profile::span("decode.release_mtp"); + let released = executor.mtp_release_verifier(binding); + drop(p); + if let Err(error) = released { + operator_line("release MTP verifier bindings", &failure(error)); + broken.get_or_insert(error); + } + // Close the verifier (drains both streams, drops the graphs) and take the physical owners back at + // the session's lineage; an abandoned window is rolled back there. + // the card at the end of the decode phase, graph pools and all windows captured: the real low-water mark of a request + vram_note(context, "decode end before disassemble"); + let p = profile::span("decode.disassemble"); + let disassembled = disassemble(DecodeResources { verifier, qsa, slots }); + drop(p); + match disassembled { + Ok(owners) => { + let _p = profile::span("decode.adopt"); + if let Err(error) = executor.adopt_qsa_owners(binding, &*dense, &mut *session, owners) { + broken.get_or_insert(error); + } + } + Err(lost) => { + operator_line("disassemble", &lost); + broken.get_or_insert(lost.error); + } + } + if outcome.is_some_and(|o| o.failed) { + broken.get_or_insert(Error::IdentityMismatch); + } + served + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_5.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_5.rs new file mode 100644 index 00000000..52516239 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_5.rs @@ -0,0 +1,217 @@ +//! Moved out of the parent module by STRA-338: impl OriginalServeStack (5). + +#[allow(unused_imports)] +use super::*; + + + +impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { + + /// Condition `prompt[resume..n-1]` through the batched Original prefill, one chunk transaction at a time + /// (the session and the draft ring stand at `resume`; with the conversation cache's `STRATA_CKPT_REREAD` + /// they stand at 0 and the reread segment comes first). After each published chunk the conversation cache + /// takes its periodic and turn/root checkpoints. + /// + /// With the expert tier, the swaps in flight land first (generate.cpp `apply_pending(true)`), every chunk + /// borrows the cache's last slots (`prefill_chunk`) and every lent slot is refilled before the decode + /// phase, whatever the read's outcome (generate.cpp `refill`). + pub(in super::super) fn prefill_phase( + &mut self, + request: &ServeRequest, + resume: usize, + cancel: &mut dyn FnMut() -> bool, + ) -> std::result::Result<(), SpecError> { + self.residency.begin_request(); + self.seed_report = None; + if let Some(cache) = self.expert_cache.as_mut() { + let _p = profile::span("prefill.wait_swaps"); + cache.wait_swaps().map_err(|e| SpecError::Forward(super::super::super::original_serve_verifier::driver_error(&e)))?; + } + // LELEKA_ORIGINAL_SERVE_SEED: the MoE stage adds its host-known route counts per (layer, expert) + let seeding = self.config.expert_tier.seed_swaps > 0 && self.expert_cache.is_some(); + if seeding { + self.moe.capture_prompt_routing(true, self.config.expert_tier.seed_decay); + } + let p = profile::span("prefill.read"); + let read = self.prefill_actions(request, resume, cancel); + drop(p); + let _p = profile::span("prefill.refill"); + // a failed or cancelled read still refills at once (generate.cpp `refill`); a good one overlaps the copies with the + // decode phase's host-side assembly + // (the prompt-routing seed needs the lent slots refilled first, so it turns the deferral off for its requests) + let defer = read.is_ok() && !seeding && original_serve_residency::refill_defer_enabled() && self.loan.is_some() && self.expert_cache.is_some(); + let refilled = match (self.loan, self.expert_cache.as_mut()) { + (Some(_), Some(cache)) if !defer => { + original_serve_residency::refill_lent(self.binding, &self.moe, cache, &mut self.residency.spans, false).map(|_| ()) + } + _ => Ok(()), + }; + let routing = if seeding { self.moe.take_prompt_routing() } else { None }; + let seeded = match (&read, &refilled, routing) { + (Ok(()), Ok(()), Some(counts)) if !defer => { + let _p = profile::span("prefill.seed"); + self.seed_residency(&counts) + } + _ => Ok(()), + }; + self.refill_due = defer; + match (read, refilled, seeded) { + (Ok(()), Err(error), _) | (Ok(()), Ok(()), Err(error)) => { + self.mark_broken(error); + Err(SpecError::Forward(error)) + } + (read, _, _) => read, + } + } + + /// Put the prompt's own routing into the tier's placement before the first window (see `original_serve_seed`). + pub(in super::super) fn seed_residency(&mut self, counts: &[f32]) -> Result<()> { + let tier = &self.config.expert_tier; + let (max, keep, usage) = (tier.seed_swaps, tier.seed_keep, tier.seed_usage); + let Some(cache) = self.expert_cache.as_mut() else { return Ok(()) }; + let started = Instant::now(); + let max_rows = tier.seed_max_rows; + if max_rows > 0 { + let rows = original_serve_seed::summarize(counts, &[]).rows; + if rows > max_rows as u64 { + if std::env::var_os("LELEKA_SEED_TRACE").is_some() { + eprintln!("DBG seed: skipped, the prompt routed {rows} rows (cap {max_rows})"); + } + return Ok(()); + } + } + let swaps = original_serve_seed::plan(counts, cache, max, keep); + let planned = started.elapsed(); + let mut report = original_serve_seed::summarize(counts, &swaps); + original_serve_seed::queue_swaps(self.binding, &self.moe, cache, &mut self.pool, &mut self.residency.spans, &swaps)?; + report.plan_ms = planned.as_secs_f64() * 1e3; + report.queue_ms = (started.elapsed() - planned).as_secs_f64() * 1e3; + self.residency.add_usage(counts, usage); + if std::env::var_os("LELEKA_SEED_TRACE").is_some() { + eprintln!( + "DBG seed: prompt rows {} routed -> {} swaps (gain {:.0}, most in one layer {}), plan {:.2} ms, queue {:.2} ms", + report.rows, report.planned, report.gain, report.max_layer_swaps, report.plan_ms, report.queue_ms + ); + } + self.seed_report = Some(report); + if std::env::var_os("LELEKA_SEED_TRACE").is_some() { + self.seed_counts = Some(counts.to_vec()); + } + Ok(()) + } + + /// `LELEKA_SEED_TRACE`: how much of the request's decode routing (the adaptive counts, so for a static arm) the resident + /// set covers: the starting profile's set, the prompt's top experts (what the seed installs, per layer slot counts of the + /// profile) and the best any static set could do (the decode's own top experts). + pub(in super::super) fn seed_coverage_trace(&mut self) { + let Some(prompt) = self.seed_counts.take() else { return }; + let usage = self.residency.usage(); + if usage.len() != prompt.len() || self.config.expert_tier.adapt_every != 0 { + return; + } + let mut slots = [0usize; 48]; + let mut initial = vec![false; 48 * 512]; + for &(layer, expert) in self.initial_owners.iter().flatten() { + slots[layer] += 1; + initial[layer * 512 + expert] = true; + } + let total: f64 = usage.iter().map(|&u| f64::from(u)).sum(); + if total <= 0.0 { + return; + } + let (mut by_prompt, mut oracle, mut by_initial) = (0f64, 0f64, 0f64); + for layer in 0..48 { + let range = layer * 512..(layer + 1) * 512; + let mut order: Vec = (0..512).collect(); + order.sort_by(|&a, &b| prompt[range.start + b].total_cmp(&prompt[range.start + a])); + by_prompt += order.iter().take(slots[layer]).map(|&e| f64::from(usage[range.start + e])).sum::(); + let mut best: Vec = usage[range.clone()].to_vec(); + best.sort_by(|a, b| b.total_cmp(a)); + oracle += best.iter().take(slots[layer]).map(|&u| f64::from(u)).sum::(); + by_initial += (0..512).filter(|&e| initial[range.start + e]).map(|e| f64::from(usage[range.start + e])).sum::(); + } + // Opt-in: `seed_counts` is only recorded under LELEKA_SEED_TRACE, so this returns early (and prints nothing) otherwise. + eprintln!( + "DBG seed-coverage: decode entries {total:.0}; covered by the starting set {:.1}%, the prompt's top experts {:.1}%, the decode's own top experts {:.1}% (oracle)", + 100.0 * by_initial / total, + 100.0 * by_prompt / total, + 100.0 * oracle / total + ); + } + + pub(in super::super) fn prefill_actions( + &mut self, + request: &ServeRequest, + resume: usize, + cancel: &mut dyn FnMut() -> bool, + ) -> std::result::Result<(), SpecError> { + let binding: &ModelBinding = self.binding; + let n = request.prompt.len(); + crate::bringup_trace!("DBG[{:.0}s] prefill_phase start n={n} resume={resume}", dbg_el()); + // generate.cpp: mtp.set_prompt_len(n) before the prompt is read; the draft cap and the request's + // sampling parameters configure the actor for the whole request. + let mtp_setup_span = profile::span("prefill.mtp_setup"); + self.executor.set_mtp_prompt_len(binding, n as i64)?; + self.executor.set_mtp_max_drafts(binding, i32::try_from(self.settings.max_drafts()).map_err(|_| Error::Overflow)?)?; + self.executor.set_mtp_draft_sampling(binding, &request.params)?; + drop(mtp_setup_span); + if n < 2 { + return Ok(()); + } + let setup_span = profile::span("prefill.setup"); + let tokens: Vec = request.prompt.iter().map(|&t| t as u32).collect(); + let source = OriginalPromptInput::from_tokenized(binding, &tokens)?; + let options = PromptOptions { + context_tokens: usize::try_from(self.config.max_context).map_err(|_| Error::Overflow)?, + prompt_cache: false, + turn_token: None, + root_min: 0, + // every conditioning read goes through the batched prefill (the verify-window read of short + // prompts needs the verifier during the prompt phase; see the open items) + short_read: 64, + force_batched: true, + verify_width: 4, + auto_max: 8192, + grid: 0, + }; + let (options, reread_to) = match (&self.prefix, &self.conversation) { + // the prefix cache reads on its grid and has no turn/root cuts: every checkpoint is a pure function of its tokens + // (a request that resumes between two grid points, from a request-end checkpoint, reads its suffix in as few chunks as the + // capacity allows: its states are not grid-canonical anyway) + (Some(prefix), _) => (PromptOptions { grid: if resume % prefix.block_tokens() == 0 { prefix.block_tokens() } else { 0 }, ..options }, None), + (None, Some(conversation)) => (conversation.config().plan_options(options), conversation.reread_to()), + (None, None) => (options, None), + }; + let capacity = self.config.capacity; + let plan = PromptPlan::new(&tokens, resume, reread_to, None, options, capacity).map_err(|e| { crate::bringup_trace!("DBG[{:.0}s] PromptPlan::new err {e:?} (n={n} capacity={capacity})", dbg_el()); plan_error(e) })?; + crate::bringup_trace!("DBG[{:.0}s] prompt plan ok", dbg_el()); + drop(setup_span); + for action in plan { + crate::bringup_trace!("DBG[{:.0}s] prompt action path={:?} first={} count={}", dbg_el(), action.path, action.first, action.count); + if action.path == PromptPath::FinalSeed { + // the last prompt token is the first verify input of the decode phase + break; + } + let PromptPath::Batched { .. } = action.path else { + return Err(Error::IdentityMismatch.into()); + }; + if self.session.target_origin()?.next_position() != action.first as u64 { + return Err(Error::IdentityMismatch.into()); + } + if cancel() { + return Err(SpecError::Cancelled); + } + if let Some(prefix) = self.prefix.as_mut() { + prefix.before_chunk(action.first); + } + self.prefill_chunk(&source, action.count, cancel)?; + self.after_prompt_action(&request.prompt, &action); + self.prefix_after_chunk(&request.prompt, action.first + action.count); + } + if self.session.target_origin()?.next_position() != (n as u64 - 1) { + return Err(Error::IdentityMismatch.into()); + } + self.prefix_after_prefill(&request.prompt); + Ok(()) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_6.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_6.rs new file mode 100644 index 00000000..05af1ad3 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_6.rs @@ -0,0 +1,135 @@ +//! Moved out of the parent module by STRA-338: impl OriginalServeStack (6). + +#[allow(unused_imports)] +use super::*; + + + +impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { + + /// One batched chunk of `count` rows from the session's position: the forward transaction and its publication. + /// With a loan the chunk's buffers are the expert cache's last slots, lent for this chunk only (the lent + /// slots stay misses until `prefill_phase` refills them); otherwise the stack's own buffers. + pub(in super::super) fn prefill_chunk( + &mut self, + source: &Rc, + count: usize, + cancel: &mut dyn FnMut() -> bool, + ) -> std::result::Result<(), SpecError> { + let Self { + binding, moe, arena, layout, expert_cache, loan, loan_tiers, executor, draft, session, kar, dense, embedding, + scalar_policy, .. + } = self; + let mut chunk = PromptChunk { + binding: *binding, + executor: &mut *executor, + dense: &*dense, + session: &mut *session, + source, + kar: kar.as_mut(), + moe: &mut *moe, + draft: &mut *draft, + embedding: &*embedding, + scalar_policy: &*scalar_policy, + }; + let first = chunk.session.target_origin().map(|o| o.next_position()).unwrap_or(0); + super::super::super::prefill_profile::begin_chunk(); + let ran = match (*loan, expert_cache.as_mut(), arena.as_mut()) { + (Some(slots), Some(cache), _) => match { + let _span = super::super::super::prefill_profile::span(super::super::super::prefill_profile::Stage::Lend, None); + // the smallest rung of the ladder that holds the chunk + let (slots, options) = tier_for(loan_tiers, count).map_or((slots, *layout), |t| (t.slots, t.layout)); + cache.lend_prefill_tail(slots, options) + } { + Ok(mut lent) => chunk.run(count, &mut lent, cancel), + Err(e) => Err(SpecError::Forward(super::super::super::original_serve_verifier::driver_error(&e))), + }, + (_, _, Some(own)) => chunk.run(count, own, cancel), + _ => Err(Error::IdentityMismatch.into()), + }; + if ran.is_ok() { + super::super::super::prefill_profile::end_chunk(first, count); + } + ran + } + + /// The prefix cache at the end of the prefill: with `TailMode::Prompt` or `Reply` a checkpoint at `n - 1`, where the next turn of + /// the session resumes (its prompt starts with this one). A checkpoint that cannot be taken costs only itself. + pub(in super::super) fn prefix_after_prefill(&mut self, prompt: &[i32]) { + let Some(mut prefix) = self.prefix.take() else { return }; + let _span = profile::span("prefix.after_prefill"); + match prefix.after_prefill(self, prompt) { + Ok(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms }) => { + operator_text(&format!("prefix tail admit (prompt end): tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", bytes >> 20)); + } + Ok(other) => operator_text(&format!("prefix tail (prompt end) not taken: {other:?}: {}", prefix.take_note().unwrap_or_default())), + Err(error) => operator_text(&format!("prefix cache: {error:?} while checkpointing the end of the prefill; skipped")), + } + self.prefix = Some(prefix); + } + + /// The end of the decode (`TailMode::Reply`): a checkpoint at the end of the prompt and the committed reply. The session is settled and the + /// draft ring stands at its position (`decode_phase` made sure); the cells past the prompt were produced by the decode. + pub(in super::super) fn prefix_after_decode(&mut self, consumed: &[i32]) { + let Some(mut prefix) = self.prefix.take() else { return }; + let _span = profile::span("prefix.after_decode"); + match prefix.after_decode(self, consumed) { + Ok(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms }) => { + operator_text(&format!("prefix tail admit (decode end): tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", bytes >> 20)); + } + Ok(other) => operator_text(&format!("prefix tail (decode end) not taken: {other:?}: {}", prefix.take_note().unwrap_or_default())), + Err(error) => operator_text(&format!("prefix cache: {error:?} while checkpointing the end of the decode; skipped")), + } + self.prefix = Some(prefix); + } + + /// The prefix cache after a published chunk: a checkpoint at the grid point if the policy wants one. A checkpoint + /// that cannot be built costs the cache, never the request. + pub(in super::super) fn prefix_after_chunk(&mut self, prompt: &[i32], end: usize) { + let Some(mut prefix) = self.prefix.take() else { return }; + let _span = profile::span("prefix.after_chunk"); + match prefix.after_chunk(self, prompt, end) { + Ok(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms }) => { + if std::env::var_os("LELEKA_PREFIX_TRACE").is_some() { + operator_text(&format!("prefix admit: tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", bytes >> 20)); + } + } + Ok(other) => { + if std::env::var_os("LELEKA_PREFIX_TRACE").is_some() && !matches!(other, ChunkOutcome::Nothing) { + operator_text(&format!("prefix admit (grid point {end}) not taken: {other:?}: {}", prefix.take_note().unwrap_or_default())); + } + } + Err(error) => { + operator_text(&format!("prefix cache: {error:?} while checkpointing; dropping the cache")); + prefix.invalidate(); + } + } + self.prefix = Some(prefix); + } + + /// A cancel between two prompt chunks leaves the session at the last published one: that is still the request's conversation + /// (`ServeConversation::note_cancelled_prefill`). The claim needs the same state a live continuation needs at the next + /// request: nothing lost, the recurrent state settled and the draft ring at the session's position. + pub(in super::super) fn keep_conversation_after_cancelled_prefill(&mut self, request: &ServeRequest) { + let Some(mut conversation) = self.conversation.take() else { return }; + if let Ok(position) = ResumeDevice::position(self) { + let in_step = ResumeDevice::live_in_step(self); + if conversation.note_cancelled_prefill(&request.prompt, position, in_step) { + operator_text(&format!("cancelled request keeps its conversation: {position} tokens live")); + } + } + self.conversation = Some(conversation); + } + + /// The conversation cache's bookkeeping after a published chunk. A checkpoint that cannot be saved costs + /// the cache, never the request: the cache is dropped and the request goes on. + pub(in super::super) fn after_prompt_action(&mut self, prompt: &[i32], action: &crate::backend::original_prompt::PromptAction) { + let Some(mut conversation) = self.conversation.take() else { return }; + let _span = profile::span("conv.after_action"); + if let Err(error) = conversation.after_action(self, prompt, action) { + operator_text(&format!("conversation cache: {error}; dropping the cache")); + conversation.invalidate(); + } + self.conversation = Some(conversation); + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/output/impl_outputstage.rs b/crates/leleka-runtime/src/qwen_forward/output/impl_outputstage.rs index f9bce8fd..54381c7a 100644 --- a/crates/leleka-runtime/src/qwen_forward/output/impl_outputstage.rs +++ b/crates/leleka-runtime/src/qwen_forward/output/impl_outputstage.rs @@ -3,501 +3,5 @@ #[allow(unused_imports)] use super::*; - -impl<'context, 'driver> OutputStage<'context, 'driver> { - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - pub(in crate::qwen_forward) fn logits_original_prompt( - &self,binding:&ModelBinding,completed:&super::super::prompt_device_rows::PromptDeviceFinal, - txn:&super::super::session::original_prompt::OriginalPromptTxn<'_, '_>, - cache:&super::super::dense_weight_cache::DenseWeightCache<'_>, - )->Result{ - txn.validate_final(completed)?; - let context=txn.context()?; - if !self.binding.matches(&binding.identity())||!std::ptr::eq(self.context,context){return Err(Error::IdentityMismatch)} - let mixed=GrStage::final_mix_original_prompt(binding,completed,txn,cache)?; - if mixed.len()!=EMBEDDING||mixed.iter().any(|value|!value.is_finite()){return Err(Error::NonFinite)} - if self.sampler_wants(completed.position())? {return Err(Error::Unsupported(Stage::Output));} - let logits=self.project_mixed(binding.identity(),completed.token(),completed.position(),&mixed,context,false)?; - txn.validate_final(completed)?;logits.validate_for(&binding.identity(),completed.token(),completed.position())?; - if matches!(&logits.values,LogitValues::Compact(_)){self.record_compact_completion()?;} - Ok(logits) - } - /// Validate and upload the one fixed output tensor once for this context. - /// The caller retains this stage for subsequent tokens; no per-token head - /// re-read or matrix transfer occurs. - pub(crate) fn load( - binding: &ModelBinding, - context: &'context Context<'driver>, - ) -> Result { - let required = context - .allocated_bytes() - .checked_add(OUTPUT_STAGE_BUDGET) - .ok_or(Error::Overflow)?; - if required > context.budget_bytes() { - return Err(Error::InputAllocation); - } - - let weights = binding.output_weights().map_err(binding_error)?; - validate_weight_owner(&weights, &binding.identity())?; - let mut device_weights = context - .allocate(OUTPUT_WEIGHT_BYTES) - .map_err(driver_error)?; - if let Err(error) = device_weights.copy_from(weights.bytes()) { - let primary = driver_error(error); - return combine(Err(primary), device_weights.release().map_err(driver_error)); - } - - Ok(Self { - context, - binding: binding.identity(), - weights: device_weights, - compact: std::cell::RefCell::new(None), - sampler: std::cell::RefCell::new(None), - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - compact_completions: std::cell::Cell::new(0), - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - reset_replay_record: std::cell::Cell::new(false), - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - reset_replay_logits: std::cell::RefCell::new(None), - }) - } - - // Explicit private qualification factory only. The fixed owner is charged - // before the existing head load and before the caller's profile preload. - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(crate) fn load_compact( - binding: &ModelBinding, - context: &'context Context<'driver>, - ) -> Result { - let required = context - .allocated_bytes() - .checked_add(OUTPUT_STAGE_BUDGET) - .and_then(|bytes| bytes.checked_add(HEAD_GREEDY_WORKSPACE_BYTES)) - .ok_or(Error::Overflow)?; - let physical = HEAD_GREEDY_WORKSPACE_BYTES - .checked_add(128 * 1024 * 1024) - .ok_or(Error::Overflow)?; - if required > context.budget_bytes() { - return Err(Error::InputAllocation); - } - let (free, _) = context.memory_info().map_err(driver_error)?; - if free < physical { - return Err(Error::InputAllocation); - } - let workspace = context.head_greedy_workspace().map_err(driver_error)?; - if workspace.allocated_bytes() != HEAD_GREEDY_WORKSPACE_BYTES { - let primary = Error::InvalidDimension; - let _ = workspace.close(); - return Err(primary); - } - match Self::load(binding, context) { - Ok(mut stage) => { - *stage.compact.get_mut() = Some(workspace); - Ok(stage) - } - Err(primary) => { - // All workspace resources are attempted; its actual Context - // retains uncertainty. The source/load error remains primary. - let _ = workspace.close(); - Err(primary) - } - } - } - - pub(in super::super) fn logits( - &self, - binding: &ModelBinding, - residual: &InjectedResidual, - txn: &mut QwenStepTxn, - ) -> Result { - self.logits_cached(binding, residual, txn, None) - } - - pub(in super::super) fn logits_cached( - &self, - binding: &ModelBinding, - residual: &InjectedResidual, - txn: &mut QwenStepTxn, - cache: Option<&super::super::dense_weight_cache::DenseWeightCache<'_>>, - ) -> Result { - let identity = binding.identity(); - txn.validate_binding(&identity)?; - if !self.binding.matches(&identity) { - return Err(Error::IdentityMismatch); - } - { - let context = txn.cuda_context()?; - if !std::ptr::eq(self.context, context) { - return Err(Error::IdentityMismatch); - } - } - - let token = txn.token(); - let position = txn.position(); - let final_layer = binding - .layer_count() - .checked_sub(1) - .ok_or(Error::InvalidLayer)?; - let layer = LayerId::new( - u64::from(final_layer), - Dimension::new(u64::from(binding.layer_count()))?, - )?; - residual.identity().validate(token, position, layer)?; - txn.validate_input(token, position)?; - - // STRA-162 owns this complete final output_hc computation. This is the - // sole call; output.rs never duplicates or reorders its GR arithmetic. - let mixed = GrStage::final_mix(binding, residual, txn, cache)?; - if mixed.len() != EMBEDDING { - return Err(Error::InvalidDimension); - } - if mixed.iter().any(|value| !value.is_finite()) { - return Err(Error::NonFinite); - } - - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if super::super::oracle_capture::enabled() { - super::super::oracle_capture::stage_f32(-1, "final_head_mixed", &mixed)?; - } - // A request sampler needs the complete vector, never the compact device argmax. - let sampled = self.sampler_wants(position)?; - let mut logits = self.project_mixed( - identity, - token, - position, - &mixed, - txn.cuda_context()?, - sampled, - )?; - if sampled { - logits = self.sample_complete(logits)?; - } - if matches!(&logits.values, LogitValues::Compact(_)) { - let current = binding.identity(); - txn.validate_binding(¤t)?; - txn.validate_input(token, position)?; - residual.identity().validate(token, position, layer)?; - let context = txn.cuda_context()?; - if !std::ptr::eq(self.context, context) { - return Err(Error::IdentityMismatch); - } - if context.is_poisoned() { - return Err(Error::CudaExecution); - } - logits.validate_for(¤t, token, position)?; - self.record_compact_completion()?; - } - Ok(logits) - } - - pub(in super::super) fn mtp_greedy( - &self, - binding: &ModelBinding, - mixed: &super::super::mtp::MtpFinalMixed, - session: &super::super::session::QwenSession<'_>, - ) -> Result { - mixed.frame().validate(binding, session)?; - let identity = binding.identity(); - let context = session.mtp_context()?; - if !self.binding.matches(&identity) || !std::ptr::eq(self.context, context) { - return Err(Error::IdentityMismatch); - } - // Sampling under MTP needs the coupled-draft machinery; it is not wired. - if self.sampler_wants(mixed.frame().position())? { - return Err(Error::Unsupported(Stage::Output)); - } - let logits = self.project_mixed( - identity, - mixed.frame().token(), - mixed.frame().position(), - mixed.values(), - context, - false, - )?; - if matches!(&logits.values, LogitValues::Compact(_)) { - mixed.frame().validate(binding, session)?; - let current = session.mtp_context()?; - if !std::ptr::eq(self.context, current) { - return Err(Error::IdentityMismatch); - } - if current.is_poisoned() { - return Err(Error::CudaExecution); - } - logits.validate_for( - &binding.identity(), - mixed.frame().token(), - mixed.frame().position(), - )?; - self.record_compact_completion()?; - } - greedy(logits) - } - - /// Arm the per-request sampler for the plain decode path. One request at a time. - pub(crate) fn arm_sampler(&self, sampler: super::super::step_sampler::StepSampler) -> Result<()> { - let mut slot = self - .sampler - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch)?; - if slot.is_some() { - return Err(Error::IdentityMismatch); - } - *slot = Some(sampler); - Ok(()) - } - - /// Disarm at request end, whatever its outcome. Never fails. - pub(crate) fn disarm_sampler(&self) { - if let Ok(mut slot) = self.sampler.try_borrow_mut() { - *slot = None; - } - } - - pub(super) fn sampler_wants(&self, position: Position) -> Result { - Ok(self - .sampler - .try_borrow() - .map_err(|_| Error::IdentityMismatch)? - .as_ref() - .is_some_and(|s| s.wants(position.get()))) - } - - /// Replace a complete finite vector by the token the armed sampler draws from it. - pub(super) fn sample_complete(&self, logits: FiniteLogits) -> Result { - let LogitValues::Full(values) = &logits.values else { - return Err(Error::IdentityMismatch); - }; - let floats: Vec = values.iter().map(|v| v.get()).collect(); - let token = self - .sampler - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch)? - .as_mut() - .ok_or(Error::IdentityMismatch)? - .pick(&floats, logits.position.get())?; - let token = TokenId::new(u64::from(token), Dimension::new(VOCABULARY as u64)?)?; - Ok(FiniteLogits { - values: LogitValues::Selected(token), - ..logits - }) - } - - pub(super) fn project_mixed( - &self, - identity: BindingIdentity, - token: TokenId, - position: Position, - mixed: &[f32], - context: &Context<'_>, - force_full: bool, - ) -> Result { - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin( - crate::qwen_forward::owner_wall_profile::Stage::Head, - ); - if self - .compact - .try_borrow() - .map_err(|_| Error::IdentityMismatch)? - .is_some() - && !force_full - && !self.full_head_observer_active() - { - return self.project_mixed_compact(identity, token, position, mixed, context); - } - if !self.binding.matches(&identity) || !std::ptr::eq(self.context, context) { - return Err(Error::IdentityMismatch); - } - if mixed.len() != EMBEDDING { - return Err(Error::InvalidDimension); - } - if mixed.iter().any(|v| !v.is_finite()) { - return Err(Error::NonFinite); - } - let required = context - .allocated_bytes() - .checked_add(OUTPUT_STAGE_BUDGET - OUTPUT_WEIGHT_BYTES) - .ok_or(Error::Overflow)?; - if required > context.budget_bytes() { - return Err(Error::InputAllocation); - } - // This limit was preflighted at load() as the persistent head plus all - // transient buffers and the Q6 driver's fixed scratch/status bytes. - let activation_bytes = encode_activation(mixed)?; - let mut activation = context.allocate(ACTIVATION_BYTES).map_err(driver_error)?; - if let Err(error) = activation.copy_from(&activation_bytes) { - let primary = driver_error(error); - return combine(Err(primary), activation.release().map_err(driver_error)); - } - - let mut candidate = match context.allocate(LOGIT_BYTES) { - Ok(buffer) => buffer, - Err(error) => { - let primary = driver_error(error); - return combine(Err(primary), activation.release().map_err(driver_error)); - } - }; - - let projection = context.q6_k_q8_1( - &self.weights, - &activation, - &mut candidate, - Q6KProjectionShape { - rows: VOCABULARY, - columns: EMBEDDING, - }, - ); - let mut result = projection.map_err(driver_error); - let mut decoded_logits = None; - if result.is_ok() { - let mut bytes = Vec::new(); - if bytes.try_reserve_exact(LOGIT_BYTES).is_err() { - result = Err(Error::InputAllocation); - } else { - bytes.resize(LOGIT_BYTES, 0); - if let Err(error) = candidate.copy_to(&mut bytes) { - result = Err(driver_error(error)); - } else { - match decode_logits(&bytes) { - Ok(values) => decoded_logits = Some(values), - Err(error) => result = Err(error), - } - } - } - } - - // Explicitly account for both short-lived buffers before publishing - // the stage-owned candidate. Any teardown failure is a refusal. - let candidate_release = candidate.release().map_err(driver_error); - let activation_release = activation.release().map_err(driver_error); - let result = combine(result, candidate_release); - let result = combine(result, activation_release); - result?; - let raw_logits = decoded_logits.ok_or(Error::InvalidDimension)?; - - Ok(FiniteLogits { - binding: identity, - token, - position, - values: LogitValues::Full(raw_logits.into_boxed_slice()), - }) - } - - // Called only after the producer's cleanup and the genuine target txn or - // draft frame has been revalidated. An attempted selection is not counted. - pub(super) fn record_compact_completion(&self) -> Result<()> { - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - self.compact_completions.set( - self.compact_completions - .get() - .checked_add(1) - .ok_or(Error::Overflow)?, - ); - Ok(()) - } - - pub(super) fn full_head_observer_active(&self) -> bool { - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - { - self.reset_replay_record.get() - || super::super::oracle_capture::enabled() - || super::super::mtp_decode::batch_gpu::collecting() - } - #[cfg(not(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] - { - false - } - } - - pub(super) fn project_mixed_compact( - &self, - identity: BindingIdentity, - token: TokenId, - position: Position, - mixed: &[f32], - context: &Context<'_>, - ) -> Result { - if !self.binding.matches(&identity) || !std::ptr::eq(self.context, context) { - return Err(Error::IdentityMismatch); - } - if mixed.len() != EMBEDDING { - return Err(Error::InvalidDimension); - } - if mixed.iter().any(|v| !v.is_finite()) { - return Err(Error::NonFinite); - } - let required = context - .allocated_bytes() - .checked_add(OUTPUT_STAGE_BUDGET - OUTPUT_WEIGHT_BYTES) - .ok_or(Error::Overflow)?; - if required > context.budget_bytes() { - return Err(Error::InputAllocation); - } - // This limit was preflighted at load() as the persistent head plus all - // transient buffers and the Q6 driver's fixed scratch/status bytes. - let activation_bytes = encode_activation(mixed)?; - let mut activation = context.allocate(ACTIVATION_BYTES).map_err(driver_error)?; - if let Err(error) = activation.copy_from(&activation_bytes) { - let primary = driver_error(error); - return combine(Err(primary), activation.release().map_err(driver_error)); - } - - let mut candidate = match context.allocate(LOGIT_BYTES) { - Ok(buffer) => buffer, - Err(error) => { - let primary = driver_error(error); - return combine(Err(primary), activation.release().map_err(driver_error)); - } - }; - - let projection = context.q6_k_q8_1( - &self.weights, - &activation, - &mut candidate, - Q6KProjectionShape { - rows: VOCABULARY, - columns: EMBEDDING, - }, - ); - let mut selection = None; - let mut result = projection.map_err(driver_error); - if result.is_ok() { - result = (|| { - // The exclusive loan ends before either source buffer is - // released. No immutable weight/cache callback is reentered. - let mut owner = self - .compact - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch)?; - let workspace = owner.as_mut().ok_or(Error::IdentityMismatch)?; - if workspace.allocated_bytes() != HEAD_GREEDY_WORKSPACE_BYTES { - return Err(Error::InvalidDimension); - } - selection = workspace.select(&candidate).map_err(driver_error)?; - if selection.is_none() { - return Err(Error::NonFinite); - } - Ok(()) - })(); - } - let candidate_release = candidate.release().map_err(driver_error); - let activation_release = activation.release().map_err(driver_error); - let result = combine(result, candidate_release); - let result = combine(result, activation_release); - result?; - if !self.binding.matches(&identity) || !std::ptr::eq(self.context, context) { - return Err(Error::IdentityMismatch); - } - if context.is_poisoned() { - return Err(Error::CudaExecution); - } - let selection = selection.ok_or(Error::NonFinite)?; - selected_token(&selection)?; - Ok(FiniteLogits { - binding: identity, - token, - position, - values: LogitValues::Compact(selection), - }) - } -} +mod impl_outputstage_2; +mod impl_outputstage_2_2; diff --git a/crates/leleka-runtime/src/qwen_forward/output/impl_outputstage/impl_outputstage_2.rs b/crates/leleka-runtime/src/qwen_forward/output/impl_outputstage/impl_outputstage_2.rs new file mode 100644 index 00000000..d36d5c60 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/output/impl_outputstage/impl_outputstage_2.rs @@ -0,0 +1,256 @@ +//! Moved out of the parent module by STRA-338: impl OutputStage. + +#[allow(unused_imports)] +use super::*; + + + +impl<'context, 'driver> OutputStage<'context, 'driver> { + #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] + pub(in crate::qwen_forward) fn logits_original_prompt( + &self,binding:&ModelBinding,completed:&super::super::super::prompt_device_rows::PromptDeviceFinal, + txn:&super::super::super::session::original_prompt::OriginalPromptTxn<'_, '_>, + cache:&super::super::super::dense_weight_cache::DenseWeightCache<'_>, + )->Result{ + txn.validate_final(completed)?; + let context=txn.context()?; + if !self.binding.matches(&binding.identity())||!std::ptr::eq(self.context,context){return Err(Error::IdentityMismatch)} + let mixed=GrStage::final_mix_original_prompt(binding,completed,txn,cache)?; + if mixed.len()!=EMBEDDING||mixed.iter().any(|value|!value.is_finite()){return Err(Error::NonFinite)} + if self.sampler_wants(completed.position())? {return Err(Error::Unsupported(Stage::Output));} + let logits=self.project_mixed(binding.identity(),completed.token(),completed.position(),&mixed,context,false)?; + txn.validate_final(completed)?;logits.validate_for(&binding.identity(),completed.token(),completed.position())?; + if matches!(&logits.values,LogitValues::Compact(_)){self.record_compact_completion()?;} + Ok(logits) + } + /// Validate and upload the one fixed output tensor once for this context. + /// The caller retains this stage for subsequent tokens; no per-token head + /// re-read or matrix transfer occurs. + pub(crate) fn load( + binding: &ModelBinding, + context: &'context Context<'driver>, + ) -> Result { + let required = context + .allocated_bytes() + .checked_add(OUTPUT_STAGE_BUDGET) + .ok_or(Error::Overflow)?; + if required > context.budget_bytes() { + return Err(Error::InputAllocation); + } + + let weights = binding.output_weights().map_err(binding_error)?; + validate_weight_owner(&weights, &binding.identity())?; + let mut device_weights = context + .allocate(OUTPUT_WEIGHT_BYTES) + .map_err(driver_error)?; + if let Err(error) = device_weights.copy_from(weights.bytes()) { + let primary = driver_error(error); + return combine(Err(primary), device_weights.release().map_err(driver_error)); + } + + Ok(Self { + context, + binding: binding.identity(), + weights: device_weights, + compact: std::cell::RefCell::new(None), + sampler: std::cell::RefCell::new(None), + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + compact_completions: std::cell::Cell::new(0), + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + reset_replay_record: std::cell::Cell::new(false), + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + reset_replay_logits: std::cell::RefCell::new(None), + }) + } + + // Explicit private qualification factory only. The fixed owner is charged + // before the existing head load and before the caller's profile preload. + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(crate) fn load_compact( + binding: &ModelBinding, + context: &'context Context<'driver>, + ) -> Result { + let required = context + .allocated_bytes() + .checked_add(OUTPUT_STAGE_BUDGET) + .and_then(|bytes| bytes.checked_add(HEAD_GREEDY_WORKSPACE_BYTES)) + .ok_or(Error::Overflow)?; + let physical = HEAD_GREEDY_WORKSPACE_BYTES + .checked_add(128 * 1024 * 1024) + .ok_or(Error::Overflow)?; + if required > context.budget_bytes() { + return Err(Error::InputAllocation); + } + let (free, _) = context.memory_info().map_err(driver_error)?; + if free < physical { + return Err(Error::InputAllocation); + } + let workspace = context.head_greedy_workspace().map_err(driver_error)?; + if workspace.allocated_bytes() != HEAD_GREEDY_WORKSPACE_BYTES { + let primary = Error::InvalidDimension; + let _ = workspace.close(); + return Err(primary); + } + match Self::load(binding, context) { + Ok(mut stage) => { + *stage.compact.get_mut() = Some(workspace); + Ok(stage) + } + Err(primary) => { + // All workspace resources are attempted; its actual Context + // retains uncertainty. The source/load error remains primary. + let _ = workspace.close(); + Err(primary) + } + } + } + + pub(in super::super::super) fn logits( + &self, + binding: &ModelBinding, + residual: &InjectedResidual, + txn: &mut QwenStepTxn, + ) -> Result { + self.logits_cached(binding, residual, txn, None) + } + + pub(in super::super::super) fn logits_cached( + &self, + binding: &ModelBinding, + residual: &InjectedResidual, + txn: &mut QwenStepTxn, + cache: Option<&super::super::super::dense_weight_cache::DenseWeightCache<'_>>, + ) -> Result { + let identity = binding.identity(); + txn.validate_binding(&identity)?; + if !self.binding.matches(&identity) { + return Err(Error::IdentityMismatch); + } + { + let context = txn.cuda_context()?; + if !std::ptr::eq(self.context, context) { + return Err(Error::IdentityMismatch); + } + } + + let token = txn.token(); + let position = txn.position(); + let final_layer = binding + .layer_count() + .checked_sub(1) + .ok_or(Error::InvalidLayer)?; + let layer = LayerId::new( + u64::from(final_layer), + Dimension::new(u64::from(binding.layer_count()))?, + )?; + residual.identity().validate(token, position, layer)?; + txn.validate_input(token, position)?; + + // STRA-162 owns this complete final output_hc computation. This is the + // sole call; output.rs never duplicates or reorders its GR arithmetic. + let mixed = GrStage::final_mix(binding, residual, txn, cache)?; + if mixed.len() != EMBEDDING { + return Err(Error::InvalidDimension); + } + if mixed.iter().any(|value| !value.is_finite()) { + return Err(Error::NonFinite); + } + + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if super::super::super::oracle_capture::enabled() { + super::super::super::oracle_capture::stage_f32(-1, "final_head_mixed", &mixed)?; + } + // A request sampler needs the complete vector, never the compact device argmax. + let sampled = self.sampler_wants(position)?; + let mut logits = self.project_mixed( + identity, + token, + position, + &mixed, + txn.cuda_context()?, + sampled, + )?; + if sampled { + logits = self.sample_complete(logits)?; + } + if matches!(&logits.values, LogitValues::Compact(_)) { + let current = binding.identity(); + txn.validate_binding(¤t)?; + txn.validate_input(token, position)?; + residual.identity().validate(token, position, layer)?; + let context = txn.cuda_context()?; + if !std::ptr::eq(self.context, context) { + return Err(Error::IdentityMismatch); + } + if context.is_poisoned() { + return Err(Error::CudaExecution); + } + logits.validate_for(¤t, token, position)?; + self.record_compact_completion()?; + } + Ok(logits) + } + + pub(in super::super::super) fn mtp_greedy( + &self, + binding: &ModelBinding, + mixed: &super::super::super::mtp::MtpFinalMixed, + session: &super::super::super::session::QwenSession<'_>, + ) -> Result { + mixed.frame().validate(binding, session)?; + let identity = binding.identity(); + let context = session.mtp_context()?; + if !self.binding.matches(&identity) || !std::ptr::eq(self.context, context) { + return Err(Error::IdentityMismatch); + } + // Sampling under MTP needs the coupled-draft machinery; it is not wired. + if self.sampler_wants(mixed.frame().position())? { + return Err(Error::Unsupported(Stage::Output)); + } + let logits = self.project_mixed( + identity, + mixed.frame().token(), + mixed.frame().position(), + mixed.values(), + context, + false, + )?; + if matches!(&logits.values, LogitValues::Compact(_)) { + mixed.frame().validate(binding, session)?; + let current = session.mtp_context()?; + if !std::ptr::eq(self.context, current) { + return Err(Error::IdentityMismatch); + } + if current.is_poisoned() { + return Err(Error::CudaExecution); + } + logits.validate_for( + &binding.identity(), + mixed.frame().token(), + mixed.frame().position(), + )?; + self.record_compact_completion()?; + } + greedy(logits) + } + + /// Arm the per-request sampler for the plain decode path. One request at a time. + pub(crate) fn arm_sampler(&self, sampler: super::super::super::step_sampler::StepSampler) -> Result<()> { + let mut slot = self + .sampler + .try_borrow_mut() + .map_err(|_| Error::IdentityMismatch)?; + if slot.is_some() { + return Err(Error::IdentityMismatch); + } + *slot = Some(sampler); + Ok(()) + } + + /// Disarm at request end, whatever its outcome. Never fails. + pub(crate) fn disarm_sampler(&self) { + if let Ok(mut slot) = self.sampler.try_borrow_mut() { + *slot = None; + } + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/output/impl_outputstage/impl_outputstage_2_2.rs b/crates/leleka-runtime/src/qwen_forward/output/impl_outputstage/impl_outputstage_2_2.rs new file mode 100644 index 00000000..6c2c05d1 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/output/impl_outputstage/impl_outputstage_2_2.rs @@ -0,0 +1,257 @@ +//! Moved out of the parent module by STRA-338: impl OutputStage (2). + +#[allow(unused_imports)] +use super::*; + + + +impl<'context, 'driver> OutputStage<'context, 'driver> { + + pub(in super::super) fn sampler_wants(&self, position: Position) -> Result { + Ok(self + .sampler + .try_borrow() + .map_err(|_| Error::IdentityMismatch)? + .as_ref() + .is_some_and(|s| s.wants(position.get()))) + } + + /// Replace a complete finite vector by the token the armed sampler draws from it. + pub(in super::super) fn sample_complete(&self, logits: FiniteLogits) -> Result { + let LogitValues::Full(values) = &logits.values else { + return Err(Error::IdentityMismatch); + }; + let floats: Vec = values.iter().map(|v| v.get()).collect(); + let token = self + .sampler + .try_borrow_mut() + .map_err(|_| Error::IdentityMismatch)? + .as_mut() + .ok_or(Error::IdentityMismatch)? + .pick(&floats, logits.position.get())?; + let token = TokenId::new(u64::from(token), Dimension::new(VOCABULARY as u64)?)?; + Ok(FiniteLogits { + values: LogitValues::Selected(token), + ..logits + }) + } + + pub(in super::super) fn project_mixed( + &self, + identity: BindingIdentity, + token: TokenId, + position: Position, + mixed: &[f32], + context: &Context<'_>, + force_full: bool, + ) -> Result { + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin( + crate::qwen_forward::owner_wall_profile::Stage::Head, + ); + if self + .compact + .try_borrow() + .map_err(|_| Error::IdentityMismatch)? + .is_some() + && !force_full + && !self.full_head_observer_active() + { + return self.project_mixed_compact(identity, token, position, mixed, context); + } + if !self.binding.matches(&identity) || !std::ptr::eq(self.context, context) { + return Err(Error::IdentityMismatch); + } + if mixed.len() != EMBEDDING { + return Err(Error::InvalidDimension); + } + if mixed.iter().any(|v| !v.is_finite()) { + return Err(Error::NonFinite); + } + let required = context + .allocated_bytes() + .checked_add(OUTPUT_STAGE_BUDGET - OUTPUT_WEIGHT_BYTES) + .ok_or(Error::Overflow)?; + if required > context.budget_bytes() { + return Err(Error::InputAllocation); + } + // This limit was preflighted at load() as the persistent head plus all + // transient buffers and the Q6 driver's fixed scratch/status bytes. + let activation_bytes = encode_activation(mixed)?; + let mut activation = context.allocate(ACTIVATION_BYTES).map_err(driver_error)?; + if let Err(error) = activation.copy_from(&activation_bytes) { + let primary = driver_error(error); + return combine(Err(primary), activation.release().map_err(driver_error)); + } + + let mut candidate = match context.allocate(LOGIT_BYTES) { + Ok(buffer) => buffer, + Err(error) => { + let primary = driver_error(error); + return combine(Err(primary), activation.release().map_err(driver_error)); + } + }; + + let projection = context.q6_k_q8_1( + &self.weights, + &activation, + &mut candidate, + Q6KProjectionShape { + rows: VOCABULARY, + columns: EMBEDDING, + }, + ); + let mut result = projection.map_err(driver_error); + let mut decoded_logits = None; + if result.is_ok() { + let mut bytes = Vec::new(); + if bytes.try_reserve_exact(LOGIT_BYTES).is_err() { + result = Err(Error::InputAllocation); + } else { + bytes.resize(LOGIT_BYTES, 0); + if let Err(error) = candidate.copy_to(&mut bytes) { + result = Err(driver_error(error)); + } else { + match decode_logits(&bytes) { + Ok(values) => decoded_logits = Some(values), + Err(error) => result = Err(error), + } + } + } + } + + // Explicitly account for both short-lived buffers before publishing + // the stage-owned candidate. Any teardown failure is a refusal. + let candidate_release = candidate.release().map_err(driver_error); + let activation_release = activation.release().map_err(driver_error); + let result = combine(result, candidate_release); + let result = combine(result, activation_release); + result?; + let raw_logits = decoded_logits.ok_or(Error::InvalidDimension)?; + + Ok(FiniteLogits { + binding: identity, + token, + position, + values: LogitValues::Full(raw_logits.into_boxed_slice()), + }) + } + + // Called only after the producer's cleanup and the genuine target txn or + // draft frame has been revalidated. An attempted selection is not counted. + pub(in super::super) fn record_compact_completion(&self) -> Result<()> { + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + self.compact_completions.set( + self.compact_completions + .get() + .checked_add(1) + .ok_or(Error::Overflow)?, + ); + Ok(()) + } + + pub(in super::super) fn full_head_observer_active(&self) -> bool { + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + { + self.reset_replay_record.get() + || super::super::super::oracle_capture::enabled() + || super::super::super::mtp_decode::batch_gpu::collecting() + } + #[cfg(not(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] + { + false + } + } + + pub(in super::super) fn project_mixed_compact( + &self, + identity: BindingIdentity, + token: TokenId, + position: Position, + mixed: &[f32], + context: &Context<'_>, + ) -> Result { + if !self.binding.matches(&identity) || !std::ptr::eq(self.context, context) { + return Err(Error::IdentityMismatch); + } + if mixed.len() != EMBEDDING { + return Err(Error::InvalidDimension); + } + if mixed.iter().any(|v| !v.is_finite()) { + return Err(Error::NonFinite); + } + let required = context + .allocated_bytes() + .checked_add(OUTPUT_STAGE_BUDGET - OUTPUT_WEIGHT_BYTES) + .ok_or(Error::Overflow)?; + if required > context.budget_bytes() { + return Err(Error::InputAllocation); + } + // This limit was preflighted at load() as the persistent head plus all + // transient buffers and the Q6 driver's fixed scratch/status bytes. + let activation_bytes = encode_activation(mixed)?; + let mut activation = context.allocate(ACTIVATION_BYTES).map_err(driver_error)?; + if let Err(error) = activation.copy_from(&activation_bytes) { + let primary = driver_error(error); + return combine(Err(primary), activation.release().map_err(driver_error)); + } + + let mut candidate = match context.allocate(LOGIT_BYTES) { + Ok(buffer) => buffer, + Err(error) => { + let primary = driver_error(error); + return combine(Err(primary), activation.release().map_err(driver_error)); + } + }; + + let projection = context.q6_k_q8_1( + &self.weights, + &activation, + &mut candidate, + Q6KProjectionShape { + rows: VOCABULARY, + columns: EMBEDDING, + }, + ); + let mut selection = None; + let mut result = projection.map_err(driver_error); + if result.is_ok() { + result = (|| { + // The exclusive loan ends before either source buffer is + // released. No immutable weight/cache callback is reentered. + let mut owner = self + .compact + .try_borrow_mut() + .map_err(|_| Error::IdentityMismatch)?; + let workspace = owner.as_mut().ok_or(Error::IdentityMismatch)?; + if workspace.allocated_bytes() != HEAD_GREEDY_WORKSPACE_BYTES { + return Err(Error::InvalidDimension); + } + selection = workspace.select(&candidate).map_err(driver_error)?; + if selection.is_none() { + return Err(Error::NonFinite); + } + Ok(()) + })(); + } + let candidate_release = candidate.release().map_err(driver_error); + let activation_release = activation.release().map_err(driver_error); + let result = combine(result, candidate_release); + let result = combine(result, activation_release); + result?; + if !self.binding.matches(&identity) || !std::ptr::eq(self.context, context) { + return Err(Error::IdentityMismatch); + } + if context.is_poisoned() { + return Err(Error::CudaExecution); + } + let selection = selection.ok_or(Error::NonFinite)?; + selected_token(&selection)?; + Ok(FiniteLogits { + binding: identity, + token, + position, + values: LogitValues::Compact(selection), + }) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/session/impl_qwensteptxn.rs b/crates/leleka-runtime/src/qwen_forward/session/impl_qwensteptxn.rs index abcbecb2..f5e6ac66 100644 --- a/crates/leleka-runtime/src/qwen_forward/session/impl_qwensteptxn.rs +++ b/crates/leleka-runtime/src/qwen_forward/session/impl_qwensteptxn.rs @@ -3,443 +3,5 @@ #[allow(unused_imports)] use super::*; - -impl<'driver> QwenStepTxn<'_, 'driver> { - pub(in super::super) fn token(&self) -> TokenId { - self.token - } - - pub(in super::super) fn position(&self) -> Position { - self.position - } - - // Private actual transaction identity for a retained GR scratch handoff. - // Numeric/token equality after rollback can never recreate this owner. - pub(in super::super) fn residual_handoff_owner(&self) -> Result> { - self.validate_binding(&self.session.binding)?; - self.validate_input(self.token, self.position)?; - Ok(Rc::clone(self.residual_handoff.get_or_init(|| Rc::new(())))) - } - - pub(in super::super) fn validate_projection_branch(&self, origin: &TargetStepOrigin) -> Result<()> { - self.check_owner()?; - origin.validate_projection_branch(self.session) - } - - pub(in super::super) fn validate_binding(&self, binding: &BindingIdentity) -> Result<()> { - self.check_owner()?; - if !self.binding.matches(binding) || !self.session.binding.matches(binding) { - return Err(Error::IdentityMismatch); - } - Ok(()) - } - - /// Borrow the session's actual device owner after transaction identity - /// checks. Returned buffers remain bounded by this Context borrow. - pub(in super::super) fn cuda_context(&self) -> Result<&Context<'driver>> { - self.validate_binding(&self.session.binding)?; - if self.session.cuda_failed { - return Err(Error::CudaExecution); - } - self.session - .cuda - .as_deref() - .ok_or(Error::Unsupported(Stage::Session)) - } - - /// Validate the complete bounded identities before any input artifact row - /// is read. Positions are strictly sequential within a session. - pub(in super::super) fn validate_input(&self, token: TokenId, position: Position) -> Result<()> { - self.check_owner()?; - if self.token != token || self.position != position { - return Err(Error::IdentityMismatch); - } - if position.get() != self.session.next_position { - return Err(Error::InvalidPosition); - } - Ok(()) - } - - /// Two committed predecessors in oldest-first order, with -1 denoting a - /// missing token. The current token is not included. - pub(in super::super) fn input_predecessors(&self) -> Result<[i32; 2]> { - self.check_owner()?; - Ok(self.session.predecessors) - } - - /// Retain fully validated input privately until all forward stages and - /// output checks succeed. It never updates committed history. - pub(in super::super) fn stage_input(&mut self, input: InputReady) -> Result> { - self.check_owner()?; - self.validate_binding(input.binding_identity())?; - self.validate_input(input.token(), input.position())?; - if self.input.is_some() { - return Err(Error::IdentityMismatch); - } - let input = Rc::new(input); - self.input = Some(Rc::clone(&input)); - Ok(input) - } - - pub(in super::super) fn input(&self) -> Result> { - self.check_owner()?; - self.input - .as_ref() - .map(Rc::clone) - .ok_or(Error::Unsupported(Stage::Input)) - } - - pub(super) fn ple_layer(&self) -> Result { - self.check_owner()?; - if !self.session.ple_required { - return Err(Error::InvalidLayer); - } - LayerId::new(1, Dimension::new(u64::from(self.session.layer_count))?) - } - - /// PLE history is an immutable producer snapshot. A zero history is only - /// allowed before the first committed token of a fresh or reset session. - pub(in super::super) fn ple_prior(&mut self) -> Result { - self.ple_layer()?; - self.validate_binding(&self.session.binding)?; - self.validate_input(self.token, self.position)?; - if self.ple_prior.is_none() { - let prior = match &self.session.ple_state { - Some(prior) => prior.clone(), - None if self.position.get() == 0 => { - PlePrior::zero(self.binding.clone(), &self.session.ple_owner)? - } - None => return Err(Error::IdentityMismatch), - }; - prior.validate(&self.binding, &self.session.ple_owner, self.position)?; - self.ple_prior = Some(prior); - } - self.ple_prior.clone().ok_or(Error::IdentityMismatch) - } - - pub(in super::super) fn validate_ple_prior(&self, prior: &PlePrior) -> Result<()> { - self.ple_layer()?; - self.validate_binding(&self.session.binding)?; - self.validate_input(self.token, self.position)?; - prior.validate(&self.binding, &self.session.ple_owner, self.position)?; - if !self - .ple_prior - .as_ref() - .is_some_and(|current| current.same_state(prior)) - { - return Err(Error::IdentityMismatch); - } - Ok(()) - } - - pub(in super::super) fn stage_ple(&mut self, prior: &PlePrior, pending: PlePending) -> Result<()> { - self.validate_ple_prior(prior)?; - pending.validate( - prior, - TokenLayer::new(self.token, self.position, self.ple_layer()?), - )?; - if self.ple_pending.is_some() { - return Err(Error::IdentityMismatch); - } - self.ple_pending = Some(pending); - Ok(()) - } - - pub(super) fn gdn_slot(&self, layer: LayerId) -> Result { - self.check_owner()?; - let expected = LayerId::new( - u64::from(layer.get()), - Dimension::new(u64::from(self.session.layer_count))?, - )?; - let index = layer.get() as usize; - if expected != layer || index >= STATE_CAPACITY || !self.session.gdn_layers[index] { - return Err(Error::InvalidLayer); - } - Ok(index) - } - - pub(in super::super) fn gdn_prior(&mut self, layer: LayerId) -> Result { - let index = self.gdn_slot(layer)?; - self.validate_binding(&self.session.binding)?; - self.validate_input(self.token, self.position)?; - if self.gdn_priors[index].is_none() { - let prior = match &self.session.gdn_states[index] { - Some(prior) => prior.clone(), - None if self.position.get() == 0 => { - GdnPrior::zero(self.binding.clone(), &self.session.gdn_owner, layer)? - } - None => return Err(Error::IdentityMismatch), - }; - prior.validate(&self.binding, &self.session.gdn_owner, layer, self.position)?; - self.gdn_priors[index] = Some(prior); - } - Ok(self.gdn_priors[index] - .as_ref() - .ok_or(Error::IdentityMismatch)? - .clone()) - } - - pub(in super::super) fn validate_gdn_prior(&self, prior: &GdnPrior, layer: LayerId) -> Result<()> { - let index = self.gdn_slot(layer)?; - self.validate_binding(&self.session.binding)?; - prior.validate(&self.binding, &self.session.gdn_owner, layer, self.position)?; - if !self.gdn_priors[index] - .as_ref() - .is_some_and(|current| current.same_state(prior)) - { - return Err(Error::IdentityMismatch); - } - Ok(()) - } - - pub(in super::super) fn stage_gdn(&mut self, prior: &GdnPrior, pending: GdnPending) -> Result<()> { - let layer = pending.layer(); - self.validate_gdn_prior(prior, layer)?; - pending.validate(prior, TokenLayer::new(self.token, self.position, layer))?; - let index = self.gdn_slot(layer)?; - if self.gdn_pending[index].is_some() { - return Err(Error::IdentityMismatch); - } - self.gdn_pending[index] = Some(pending); - Ok(()) - } - - pub(super) fn qsa_slot(&self, layer: LayerId) -> Result { - self.check_owner()?; - let expected = LayerId::new( - u64::from(layer.get()), - Dimension::new(u64::from(self.session.layer_count))?, - )?; - let index = layer.get() as usize; - if expected != layer || index >= STATE_CAPACITY || !self.session.qsa_layers[index] { - return Err(Error::InvalidLayer); - } - Ok(index) - } - - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - pub(in super::super) fn native_qsa_prior(&mut self,layer:LayerId, - kv:&leleka_cuda_driver::QsaPromptKv<'_>)->Result { - kv.validate_context(self.cuda_context()?).map_err(super::super::qsa_index::driver_error)?; - let index=self.qsa_slot(layer)?; - let prior=self.qsa_prior(layer)?; - if !prior.has_native_kv() { - // Only the genuine empty current session can create its initial - // snapshot from this real KV owner. Existing FP16 state never migrates. - if self.position.get()!=0 || prior.next_position()!=0 - || self.session.qsa_states[index].is_some() || self.qsa_pending[index].is_some() - {return Err(Error::IdentityMismatch);} - self.qsa_priors[index]=Some(QsaIndexPrior::empty_native(self.binding.clone(), - &self.session.qsa_owner,layer,kv)?); - } - let prior=self.qsa_priors[index].as_ref().ok_or(Error::IdentityMismatch)?.clone(); - self.validate_qsa_prior(&prior,layer)?; - prior.native_snapshot(kv)?;Ok(prior) - } - - pub(in super::super) fn qsa_prior(&mut self, layer: LayerId) -> Result { - let index = self.qsa_slot(layer)?; - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - if self.session.resident_qsa_states[index].is_some(){return Err(Error::Unsupported(Stage::QsaIndex));} - self.validate_binding(&self.session.binding)?; - self.validate_input(self.token, self.position)?; - if self.qsa_priors[index].is_none() { - let prior = match &self.session.qsa_states[index] { - Some(prior) => prior.clone(), - None if self.position.get() == 0 => { - QsaIndexPrior::empty(self.binding.clone(), &self.session.qsa_owner, layer)? - } - None => return Err(Error::IdentityMismatch), - }; - prior.validate(&self.binding, &self.session.qsa_owner, layer, self.position)?; - self.qsa_priors[index] = Some(prior); - } - Ok(self.qsa_priors[index] - .as_ref() - .ok_or(Error::IdentityMismatch)? - .clone()) - } - - pub(in super::super) fn validate_qsa_prior(&self, prior: &QsaIndexPrior, layer: LayerId) -> Result<()> { - let index = self.qsa_slot(layer)?; - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - if self.session.resident_qsa_states[index].is_some(){return Err(Error::Unsupported(Stage::QsaIndex));} - self.validate_binding(&self.session.binding)?; - self.validate_input(self.token, self.position)?; - prior.validate(&self.binding, &self.session.qsa_owner, layer, self.position)?; - if !self.qsa_priors[index] - .as_ref() - .is_some_and(|current| current.same_state(prior)) - { - return Err(Error::IdentityMismatch); - } - Ok(()) - } - - pub(in super::super) fn stage_qsa(&mut self, prior: &QsaIndexPrior, pending: QsaPending) -> Result<()> { - let layer = pending.layer(); - self.validate_qsa_prior(prior, layer)?; - pending.validate(prior, TokenLayer::new(self.token, self.position, layer))?; - let index = self.qsa_slot(layer)?; - if self.qsa_pending[index].is_some() { - return Err(Error::IdentityMismatch); - } - self.qsa_pending[index] = Some(pending); - Ok(()) - } - - /// Only a producer-owned completed FFN residual proves a layer complete. - pub(in super::super) fn mark_layer_complete(&mut self, residual: &InjectedResidual) -> Result<()> { - self.validate_binding(&self.session.binding)?; - let identity = residual.identity(); - residual.validate_origin(&self.binding, GrRole::Ffn(identity.layer().get()))?; - self.validate_layer_completion(identity)?; - self.completed_layers = self - .completed_layers - .checked_add(1) - .ok_or(Error::Overflow)?; - Ok(()) - } - - pub(super) fn validate_layer_completion(&self, identity: TokenLayer) -> Result<()> { - self.validate_input(identity.token(), identity.position())?; - if self.forward_output.is_some() || identity.layer().get() != self.completed_layers { - return Err(Error::IdentityMismatch); - } - let layer = LayerId::new( - u64::from(self.completed_layers), - Dimension::new(u64::from(self.session.layer_count))?, - )?; - if layer != identity.layer() { - return Err(Error::IdentityMismatch); - } - Ok(()) - } - - /// Finite logits and greedy selection are required after every bound layer. - pub(in super::super) fn finish_forward(&mut self, logits: FiniteLogits) -> Result { - self.validate_binding(&self.session.binding)?; - if self.forward_output.is_some() || self.prefill_finished { - return Err(Error::IdentityMismatch); - } - if self.completed_layers != self.session.layer_count || self.session.layer_count == 0 { - return Err(Error::Unsupported(Stage::Executor)); - } - logits.validate_for(&self.binding, self.token, self.position)?; - let output = greedy(logits)?; - self.forward_output = Some(output); - Ok(output) - } - - /// Known-next prefill completes all bound layers without manufacturing logits. - /// Only the actual final FFN producer can certify this distinct completion. - pub(in super::super) fn finish_prefill(&mut self, residual: &InjectedResidual) -> Result<()> { - self.validate_binding(&self.session.binding)?; - if self.session.layer_count == 0 - || self.completed_layers != self.session.layer_count - || self.forward_output.is_some() - || self.prefill_finished - { - return Err(Error::Unsupported(Stage::Executor)); - } - residual.validate_origin(&self.binding, GrRole::Ffn(self.session.layer_count - 1))?; - let identity = residual.identity(); - self.validate_input(identity.token(), identity.position())?; - if identity.layer().get() != self.session.layer_count - 1 - || residual.streams().len() != 10240 - { - return Err(Error::IdentityMismatch); - } - if residual.streams().iter().any(|value| !value.is_finite()) { - return Err(Error::NonFinite); - } - self.prefill_finished = true; - Ok(()) - } - - /// Publish the input token and advance exactly one position only after - /// the session-owned executor callback has returned success. Kept private - /// to this module so a stage cannot commit the shared transaction. - pub(super) fn commit(self, output: Option) -> Result<()> { - self.check_owner()?; - if output.is_none() && (self.session.layer_count == 0 || !self.prefill_finished) { - return Err(Error::Unsupported(Stage::Executor)); - } - if self.input.is_none() { - return Err(Error::Unsupported(Stage::Input)); - } - let next_position = self.position.get().checked_add(1).ok_or(Error::Overflow)?; - let token = i32::try_from(self.token.get()).map_err(|_| Error::InvalidToken)?; - let next_ple = if self.session.ple_required { - let next = self - .ple_pending - .ok_or(Error::Unsupported(Stage::Input))? - .into_prior(); - if next.next_position() != next_position { - return Err(Error::IdentityMismatch); - } - Some(next) - } else { - if self.ple_pending.is_some() { - return Err(Error::IdentityMismatch); - } - None - }; - let mut next_states = self.session.gdn_states.clone(); - for (index, pending) in self.gdn_pending.into_iter().enumerate() { - if self.session.gdn_layers[index] { - let next = pending.ok_or(Error::Unsupported(Stage::Gdn))?.into_prior(); - if next.layer().get() as usize != index || next.next_position() != next_position { - return Err(Error::IdentityMismatch); - } - next_states[index] = Some(next); - } else if pending.is_some() { - return Err(Error::IdentityMismatch); - } - } - let mut next_qsa = self.session.qsa_states.clone(); - for (index, pending) in self.qsa_pending.into_iter().enumerate() { - if self.session.qsa_layers[index] { - let next = pending - .ok_or(Error::Unsupported(Stage::QsaIndex))? - .into_prior(); - if next.layer().get() as usize != index || next.next_position() != next_position { - return Err(Error::IdentityMismatch); - } - next_qsa[index] = Some(next); - } else if pending.is_some() { - return Err(Error::IdentityMismatch); - } - } - if self.session.layer_count > 0 { - if self.completed_layers != self.session.layer_count { - return Err(Error::Unsupported(Stage::Executor)); - } - match output { - // A token callback without a produced logits/argmax is a skipped - // forward (Unsupported), distinct from a wrong callback token. - Some(_) if !self.prefill_finished && self.forward_output.is_none() => { - return Err(Error::Unsupported(Stage::Executor)); - } - Some(value) if !self.prefill_finished && self.forward_output == Some(value) => {} - None if self.prefill_finished && self.forward_output.is_none() => {} - _ => return Err(Error::IdentityMismatch), - } - } - let session = self.session; - session.complete_cuda()?; - session.ple_state = next_ple; - session.gdn_states = next_states; - session.qsa_states = next_qsa; - session.predecessors = [session.predecessors[1], token]; - session.next_position = next_position; - Ok(()) - } - - pub(super) fn check_owner(&self) -> Result<()> { - if self.owner_thread != std::thread::current().id() { - return Err(Error::IdentityMismatch); - } - Ok(()) - } -} +mod impl_qwensteptxn_2; +mod impl_qwensteptxn_2_2; diff --git a/crates/leleka-runtime/src/qwen_forward/session/impl_qwensteptxn/impl_qwensteptxn_2.rs b/crates/leleka-runtime/src/qwen_forward/session/impl_qwensteptxn/impl_qwensteptxn_2.rs new file mode 100644 index 00000000..93682eb0 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/session/impl_qwensteptxn/impl_qwensteptxn_2.rs @@ -0,0 +1,240 @@ +//! Moved out of the parent module by STRA-338: impl QwenStepTxn. + +#[allow(unused_imports)] +use super::*; + + + +impl<'driver> QwenStepTxn<'_, 'driver> { + pub(in super::super::super) fn token(&self) -> TokenId { + self.token + } + + pub(in super::super::super) fn position(&self) -> Position { + self.position + } + + // Private actual transaction identity for a retained GR scratch handoff. + // Numeric/token equality after rollback can never recreate this owner. + pub(in super::super::super) fn residual_handoff_owner(&self) -> Result> { + self.validate_binding(&self.session.binding)?; + self.validate_input(self.token, self.position)?; + Ok(Rc::clone(self.residual_handoff.get_or_init(|| Rc::new(())))) + } + + pub(in super::super::super) fn validate_projection_branch(&self, origin: &TargetStepOrigin) -> Result<()> { + self.check_owner()?; + origin.validate_projection_branch(self.session) + } + + pub(in super::super::super) fn validate_binding(&self, binding: &BindingIdentity) -> Result<()> { + self.check_owner()?; + if !self.binding.matches(binding) || !self.session.binding.matches(binding) { + return Err(Error::IdentityMismatch); + } + Ok(()) + } + + /// Borrow the session's actual device owner after transaction identity + /// checks. Returned buffers remain bounded by this Context borrow. + pub(in super::super::super) fn cuda_context(&self) -> Result<&Context<'driver>> { + self.validate_binding(&self.session.binding)?; + if self.session.cuda_failed { + return Err(Error::CudaExecution); + } + self.session + .cuda + .as_deref() + .ok_or(Error::Unsupported(Stage::Session)) + } + + /// Validate the complete bounded identities before any input artifact row + /// is read. Positions are strictly sequential within a session. + pub(in super::super::super) fn validate_input(&self, token: TokenId, position: Position) -> Result<()> { + self.check_owner()?; + if self.token != token || self.position != position { + return Err(Error::IdentityMismatch); + } + if position.get() != self.session.next_position { + return Err(Error::InvalidPosition); + } + Ok(()) + } + + /// Two committed predecessors in oldest-first order, with -1 denoting a + /// missing token. The current token is not included. + pub(in super::super::super) fn input_predecessors(&self) -> Result<[i32; 2]> { + self.check_owner()?; + Ok(self.session.predecessors) + } + + /// Retain fully validated input privately until all forward stages and + /// output checks succeed. It never updates committed history. + pub(in super::super::super) fn stage_input(&mut self, input: InputReady) -> Result> { + self.check_owner()?; + self.validate_binding(input.binding_identity())?; + self.validate_input(input.token(), input.position())?; + if self.input.is_some() { + return Err(Error::IdentityMismatch); + } + let input = Rc::new(input); + self.input = Some(Rc::clone(&input)); + Ok(input) + } + + pub(in super::super::super) fn input(&self) -> Result> { + self.check_owner()?; + self.input + .as_ref() + .map(Rc::clone) + .ok_or(Error::Unsupported(Stage::Input)) + } + + pub(in super::super) fn ple_layer(&self) -> Result { + self.check_owner()?; + if !self.session.ple_required { + return Err(Error::InvalidLayer); + } + LayerId::new(1, Dimension::new(u64::from(self.session.layer_count))?) + } + + /// PLE history is an immutable producer snapshot. A zero history is only + /// allowed before the first committed token of a fresh or reset session. + pub(in super::super::super) fn ple_prior(&mut self) -> Result { + self.ple_layer()?; + self.validate_binding(&self.session.binding)?; + self.validate_input(self.token, self.position)?; + if self.ple_prior.is_none() { + let prior = match &self.session.ple_state { + Some(prior) => prior.clone(), + None if self.position.get() == 0 => { + PlePrior::zero(self.binding.clone(), &self.session.ple_owner)? + } + None => return Err(Error::IdentityMismatch), + }; + prior.validate(&self.binding, &self.session.ple_owner, self.position)?; + self.ple_prior = Some(prior); + } + self.ple_prior.clone().ok_or(Error::IdentityMismatch) + } + + pub(in super::super::super) fn validate_ple_prior(&self, prior: &PlePrior) -> Result<()> { + self.ple_layer()?; + self.validate_binding(&self.session.binding)?; + self.validate_input(self.token, self.position)?; + prior.validate(&self.binding, &self.session.ple_owner, self.position)?; + if !self + .ple_prior + .as_ref() + .is_some_and(|current| current.same_state(prior)) + { + return Err(Error::IdentityMismatch); + } + Ok(()) + } + + pub(in super::super::super) fn stage_ple(&mut self, prior: &PlePrior, pending: PlePending) -> Result<()> { + self.validate_ple_prior(prior)?; + pending.validate( + prior, + TokenLayer::new(self.token, self.position, self.ple_layer()?), + )?; + if self.ple_pending.is_some() { + return Err(Error::IdentityMismatch); + } + self.ple_pending = Some(pending); + Ok(()) + } + + pub(in super::super) fn gdn_slot(&self, layer: LayerId) -> Result { + self.check_owner()?; + let expected = LayerId::new( + u64::from(layer.get()), + Dimension::new(u64::from(self.session.layer_count))?, + )?; + let index = layer.get() as usize; + if expected != layer || index >= STATE_CAPACITY || !self.session.gdn_layers[index] { + return Err(Error::InvalidLayer); + } + Ok(index) + } + + pub(in super::super::super) fn gdn_prior(&mut self, layer: LayerId) -> Result { + let index = self.gdn_slot(layer)?; + self.validate_binding(&self.session.binding)?; + self.validate_input(self.token, self.position)?; + if self.gdn_priors[index].is_none() { + let prior = match &self.session.gdn_states[index] { + Some(prior) => prior.clone(), + None if self.position.get() == 0 => { + GdnPrior::zero(self.binding.clone(), &self.session.gdn_owner, layer)? + } + None => return Err(Error::IdentityMismatch), + }; + prior.validate(&self.binding, &self.session.gdn_owner, layer, self.position)?; + self.gdn_priors[index] = Some(prior); + } + Ok(self.gdn_priors[index] + .as_ref() + .ok_or(Error::IdentityMismatch)? + .clone()) + } + + pub(in super::super::super) fn validate_gdn_prior(&self, prior: &GdnPrior, layer: LayerId) -> Result<()> { + let index = self.gdn_slot(layer)?; + self.validate_binding(&self.session.binding)?; + prior.validate(&self.binding, &self.session.gdn_owner, layer, self.position)?; + if !self.gdn_priors[index] + .as_ref() + .is_some_and(|current| current.same_state(prior)) + { + return Err(Error::IdentityMismatch); + } + Ok(()) + } + + pub(in super::super::super) fn stage_gdn(&mut self, prior: &GdnPrior, pending: GdnPending) -> Result<()> { + let layer = pending.layer(); + self.validate_gdn_prior(prior, layer)?; + pending.validate(prior, TokenLayer::new(self.token, self.position, layer))?; + let index = self.gdn_slot(layer)?; + if self.gdn_pending[index].is_some() { + return Err(Error::IdentityMismatch); + } + self.gdn_pending[index] = Some(pending); + Ok(()) + } + + pub(in super::super) fn qsa_slot(&self, layer: LayerId) -> Result { + self.check_owner()?; + let expected = LayerId::new( + u64::from(layer.get()), + Dimension::new(u64::from(self.session.layer_count))?, + )?; + let index = layer.get() as usize; + if expected != layer || index >= STATE_CAPACITY || !self.session.qsa_layers[index] { + return Err(Error::InvalidLayer); + } + Ok(index) + } + + #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] + pub(in super::super::super) fn native_qsa_prior(&mut self,layer:LayerId, + kv:&leleka_cuda_driver::QsaPromptKv<'_>)->Result { + kv.validate_context(self.cuda_context()?).map_err(super::super::super::qsa_index::driver_error)?; + let index=self.qsa_slot(layer)?; + let prior=self.qsa_prior(layer)?; + if !prior.has_native_kv() { + // Only the genuine empty current session can create its initial + // snapshot from this real KV owner. Existing FP16 state never migrates. + if self.position.get()!=0 || prior.next_position()!=0 + || self.session.qsa_states[index].is_some() || self.qsa_pending[index].is_some() + {return Err(Error::IdentityMismatch);} + self.qsa_priors[index]=Some(QsaIndexPrior::empty_native(self.binding.clone(), + &self.session.qsa_owner,layer,kv)?); + } + let prior=self.qsa_priors[index].as_ref().ok_or(Error::IdentityMismatch)?.clone(); + self.validate_qsa_prior(&prior,layer)?; + prior.native_snapshot(kv)?;Ok(prior) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/session/impl_qwensteptxn/impl_qwensteptxn_2_2.rs b/crates/leleka-runtime/src/qwen_forward/session/impl_qwensteptxn/impl_qwensteptxn_2_2.rs new file mode 100644 index 00000000..3a522bf7 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/session/impl_qwensteptxn/impl_qwensteptxn_2_2.rs @@ -0,0 +1,215 @@ +//! Moved out of the parent module by STRA-338: impl QwenStepTxn (2). + +#[allow(unused_imports)] +use super::*; + + + +impl<'driver> QwenStepTxn<'_, 'driver> { + + pub(in super::super::super) fn qsa_prior(&mut self, layer: LayerId) -> Result { + let index = self.qsa_slot(layer)?; + #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] + if self.session.resident_qsa_states[index].is_some(){return Err(Error::Unsupported(Stage::QsaIndex));} + self.validate_binding(&self.session.binding)?; + self.validate_input(self.token, self.position)?; + if self.qsa_priors[index].is_none() { + let prior = match &self.session.qsa_states[index] { + Some(prior) => prior.clone(), + None if self.position.get() == 0 => { + QsaIndexPrior::empty(self.binding.clone(), &self.session.qsa_owner, layer)? + } + None => return Err(Error::IdentityMismatch), + }; + prior.validate(&self.binding, &self.session.qsa_owner, layer, self.position)?; + self.qsa_priors[index] = Some(prior); + } + Ok(self.qsa_priors[index] + .as_ref() + .ok_or(Error::IdentityMismatch)? + .clone()) + } + + pub(in super::super::super) fn validate_qsa_prior(&self, prior: &QsaIndexPrior, layer: LayerId) -> Result<()> { + let index = self.qsa_slot(layer)?; + #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] + if self.session.resident_qsa_states[index].is_some(){return Err(Error::Unsupported(Stage::QsaIndex));} + self.validate_binding(&self.session.binding)?; + self.validate_input(self.token, self.position)?; + prior.validate(&self.binding, &self.session.qsa_owner, layer, self.position)?; + if !self.qsa_priors[index] + .as_ref() + .is_some_and(|current| current.same_state(prior)) + { + return Err(Error::IdentityMismatch); + } + Ok(()) + } + + pub(in super::super::super) fn stage_qsa(&mut self, prior: &QsaIndexPrior, pending: QsaPending) -> Result<()> { + let layer = pending.layer(); + self.validate_qsa_prior(prior, layer)?; + pending.validate(prior, TokenLayer::new(self.token, self.position, layer))?; + let index = self.qsa_slot(layer)?; + if self.qsa_pending[index].is_some() { + return Err(Error::IdentityMismatch); + } + self.qsa_pending[index] = Some(pending); + Ok(()) + } + + /// Only a producer-owned completed FFN residual proves a layer complete. + pub(in super::super::super) fn mark_layer_complete(&mut self, residual: &InjectedResidual) -> Result<()> { + self.validate_binding(&self.session.binding)?; + let identity = residual.identity(); + residual.validate_origin(&self.binding, GrRole::Ffn(identity.layer().get()))?; + self.validate_layer_completion(identity)?; + self.completed_layers = self + .completed_layers + .checked_add(1) + .ok_or(Error::Overflow)?; + Ok(()) + } + + pub(in super::super) fn validate_layer_completion(&self, identity: TokenLayer) -> Result<()> { + self.validate_input(identity.token(), identity.position())?; + if self.forward_output.is_some() || identity.layer().get() != self.completed_layers { + return Err(Error::IdentityMismatch); + } + let layer = LayerId::new( + u64::from(self.completed_layers), + Dimension::new(u64::from(self.session.layer_count))?, + )?; + if layer != identity.layer() { + return Err(Error::IdentityMismatch); + } + Ok(()) + } + + /// Finite logits and greedy selection are required after every bound layer. + pub(in super::super::super) fn finish_forward(&mut self, logits: FiniteLogits) -> Result { + self.validate_binding(&self.session.binding)?; + if self.forward_output.is_some() || self.prefill_finished { + return Err(Error::IdentityMismatch); + } + if self.completed_layers != self.session.layer_count || self.session.layer_count == 0 { + return Err(Error::Unsupported(Stage::Executor)); + } + logits.validate_for(&self.binding, self.token, self.position)?; + let output = greedy(logits)?; + self.forward_output = Some(output); + Ok(output) + } + + /// Known-next prefill completes all bound layers without manufacturing logits. + /// Only the actual final FFN producer can certify this distinct completion. + pub(in super::super::super) fn finish_prefill(&mut self, residual: &InjectedResidual) -> Result<()> { + self.validate_binding(&self.session.binding)?; + if self.session.layer_count == 0 + || self.completed_layers != self.session.layer_count + || self.forward_output.is_some() + || self.prefill_finished + { + return Err(Error::Unsupported(Stage::Executor)); + } + residual.validate_origin(&self.binding, GrRole::Ffn(self.session.layer_count - 1))?; + let identity = residual.identity(); + self.validate_input(identity.token(), identity.position())?; + if identity.layer().get() != self.session.layer_count - 1 + || residual.streams().len() != 10240 + { + return Err(Error::IdentityMismatch); + } + if residual.streams().iter().any(|value| !value.is_finite()) { + return Err(Error::NonFinite); + } + self.prefill_finished = true; + Ok(()) + } + + /// Publish the input token and advance exactly one position only after + /// the session-owned executor callback has returned success. Kept private + /// to this module so a stage cannot commit the shared transaction. + pub(in super::super) fn commit(self, output: Option) -> Result<()> { + self.check_owner()?; + if output.is_none() && (self.session.layer_count == 0 || !self.prefill_finished) { + return Err(Error::Unsupported(Stage::Executor)); + } + if self.input.is_none() { + return Err(Error::Unsupported(Stage::Input)); + } + let next_position = self.position.get().checked_add(1).ok_or(Error::Overflow)?; + let token = i32::try_from(self.token.get()).map_err(|_| Error::InvalidToken)?; + let next_ple = if self.session.ple_required { + let next = self + .ple_pending + .ok_or(Error::Unsupported(Stage::Input))? + .into_prior(); + if next.next_position() != next_position { + return Err(Error::IdentityMismatch); + } + Some(next) + } else { + if self.ple_pending.is_some() { + return Err(Error::IdentityMismatch); + } + None + }; + let mut next_states = self.session.gdn_states.clone(); + for (index, pending) in self.gdn_pending.into_iter().enumerate() { + if self.session.gdn_layers[index] { + let next = pending.ok_or(Error::Unsupported(Stage::Gdn))?.into_prior(); + if next.layer().get() as usize != index || next.next_position() != next_position { + return Err(Error::IdentityMismatch); + } + next_states[index] = Some(next); + } else if pending.is_some() { + return Err(Error::IdentityMismatch); + } + } + let mut next_qsa = self.session.qsa_states.clone(); + for (index, pending) in self.qsa_pending.into_iter().enumerate() { + if self.session.qsa_layers[index] { + let next = pending + .ok_or(Error::Unsupported(Stage::QsaIndex))? + .into_prior(); + if next.layer().get() as usize != index || next.next_position() != next_position { + return Err(Error::IdentityMismatch); + } + next_qsa[index] = Some(next); + } else if pending.is_some() { + return Err(Error::IdentityMismatch); + } + } + if self.session.layer_count > 0 { + if self.completed_layers != self.session.layer_count { + return Err(Error::Unsupported(Stage::Executor)); + } + match output { + // A token callback without a produced logits/argmax is a skipped + // forward (Unsupported), distinct from a wrong callback token. + Some(_) if !self.prefill_finished && self.forward_output.is_none() => { + return Err(Error::Unsupported(Stage::Executor)); + } + Some(value) if !self.prefill_finished && self.forward_output == Some(value) => {} + None if self.prefill_finished && self.forward_output.is_none() => {} + _ => return Err(Error::IdentityMismatch), + } + } + let session = self.session; + session.complete_cuda()?; + session.ple_state = next_ple; + session.gdn_states = next_states; + session.qsa_states = next_qsa; + session.predecessors = [session.predecessors[1], token]; + session.next_position = next_position; + Ok(()) + } + + pub(in super::super) fn check_owner(&self) -> Result<()> { + if self.owner_thread != std::thread::current().id() { + return Err(Error::IdentityMismatch); + } + Ok(()) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn.rs b/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn.rs index c7d2e3d9..70cbf935 100644 --- a/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn.rs +++ b/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn.rs @@ -3,1989 +3,21 @@ #[allow(unused_imports)] use super::*; - -impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { - /// Actual extra simultaneous owners of the selected native prompt PLE - /// batch. Caller reserves this before begin; default and verification - /// admission retain their existing exact charge and 512 MiB ceiling. - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in crate::qwen_forward) fn native_prefill_host_charge(tokens: usize) -> Result { - if !(1..=256).contains(&tokens) { return Err(Error::InvalidDimension); } - tokens.min(64).checked_mul(409600 + 51200) - .and_then(|bytes| bytes.checked_add(3_645_440 + 819_200 + 8192)) - // Genuine pooled flatten + end readback bytes/F32 + driver upload - // staging may coexist; persistent canonical pages stay separately - // admitted by the model owner. Construction/directory/attention - // readback temporaries also remain within this request charge. - .and_then(|bytes| bytes.checked_add(4 * 33_556_992 + 4 * 1024 * 1024)) - // Whole native router/shared host staging, route readback and the - // complete combined-output bytes/F32/row copies coexist with GR. - .and_then(|bytes| bytes.checked_add(tokens.min(64) * 50_000 + 8192)) - .ok_or(Error::Overflow) - } - pub(in crate::qwen_forward) fn begin( - session: &'session mut QwenSession<'driver>, - binding: &ModelBinding, - tokens: &[TokenId], - known_next: Option, - host_remaining: usize, - ) -> Result { - Self::begin_bounded(session, binding, tokens, known_next, host_remaining, false) - } - /// Private experimental admission. Normal serving's begin still caps64. - pub(in crate::qwen_forward) fn begin_windowed256( - session: &'session mut QwenSession<'driver>, - binding: &ModelBinding, - tokens: &[TokenId], - known_next: Option, - host_remaining: usize, - ) -> Result { - Self::begin_bounded( - session, - binding, - tokens, - known_next, - host_remaining.min(512 * 1024 * 1024), - true, - ) - } - pub(super) fn begin_bounded( - session: &'session mut QwenSession<'driver>, - binding: &ModelBinding, - tokens: &[TokenId], - known_next: Option, - host_remaining: usize, - windowed: bool, - ) -> Result { - let limit = if windowed { 256 } else { 64 }; - let origin = session.target_origin()?; - if !session.binding.matches(&binding.identity()) - || session.layer_count != 48 - || tokens.is_empty() - || tokens.len() > limit - { - return Err(Error::InvalidDimension); - } - let end = session - .next_position - .checked_add(tokens.len() as u64) - .ok_or(Error::Overflow)?; - let context_bound = Dimension::new(u64::from(binding.input_constants().context_length()))?; - if end >= u64::from(context_bound.get()) || end >= crate::qwen_forward::contract::serving_cells() { - return Err(Error::InvalidPosition); - } - let vocab = Dimension::new(248320)?; - for token in tokens.iter().copied().chain(known_next) { - if token != TokenId::new(u64::from(token.get()), vocab)? { - return Err(Error::InvalidToken); - } - } - let charge = if windowed { - host_charge_bounded(tokens.len(), end, 256)? - } else { - host_charge(tokens.len(), end)? - }; - if charge > host_remaining { - return Err(Error::InputAllocation); - } - let context = session.mtp_context()?; - if context - .allocated_bytes() - .checked_add(128 * 1024 * 1024) - .is_none_or(|n| n > context.budget_bytes()) - { - return Err(Error::InputAllocation); - } - let mut rows = Vec::new(); - rows.try_reserve_exact(tokens.len()) - .map_err(|_| Error::InputAllocation)?; - let mut witnesses = Vec::new(); - witnesses - .try_reserve_exact(tokens.len()) - .map_err(|_| Error::InputAllocation)?; - let mut predecessors = session.predecessors; - for (index, token) in tokens.iter().copied().enumerate() { - let position = Position::new(session.next_position + index as u64, context_bound)?; - rows.push(Row { - token, - position, - predecessors, - input: None, - completed: 0, - }); - predecessors = [ - predecessors[1], - i32::try_from(token.get()).map_err(|_| Error::InvalidToken)?, - ]; - } - Ok(Self { - verification: None, - next_ple: session.ple_state.clone(), - next_gdn: session.gdn_states.clone(), - gdn_chunk: None, - next_qsa: session.qsa_states.clone(), - session, - origin, - chunk: Rc::new(()), - rows, - witnesses, - next_layer: 0, - next_row: 0, - batch_layer: None, - batch_rows: Vec::new(), - batch_completed: 0, - attention_layer: None, - attention_next: 0, - attention_sources: Vec::new(), - attention_authorized: None, - known_next, - output: None, - finished: false, - aborted: false, - end, - windowed, - micro_cursor: 0, - active_micro: None, - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - test_micro_width: 64, - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - test_window_journal: Vec::new(), - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - test_partial_words: 0, - }) - } - pub(super) fn check(&self) -> Result<()> { - self.origin.validate(self.session)?; - if self.aborted { - return Err(Error::Unsupported(Stage::Session)); - } - Ok(()) - } - /// Phase belongs to this live transaction's actual verification journal. - /// Row count, window width and caller policy cannot mint this distinction. - pub(in crate::qwen_forward) fn is_mtp_verification(&self) -> Result { - self.check()?; - Ok(self.verification.is_some()) - } - pub(super) fn phase_span(&self) -> Result<(usize, usize)> { - self.check()?; - if !self.windowed { - return Ok((0, self.rows.len())); - } - let active = self.active_micro.as_ref().ok_or(Error::IdentityMismatch)?; - if active.layer.get() != self.next_layer - || active.first != self.micro_cursor - || active.end <= active.first - || active.end - active.first > 64 - || active.end > self.rows.len() - { - return Err(Error::IdentityMismatch); - } - Ok((active.first, active.end)) - } - pub(super) fn window_proof(&self) -> Option> { - self.active_micro.as_ref().map(|a| Rc::clone(&a.proof)) - } - pub(super) fn validate_window_proof(&self, proof: &Option>) -> Result<()> { - self.phase_span()?; - match (self.active_micro.as_ref(), proof) { - (None, None) if !self.windowed => Ok(()), - (Some(active), Some(proof)) if Rc::ptr_eq(&active.proof, proof) => Ok(()), - _ => Err(Error::IdentityMismatch), - } - } - /// Closed adapters receive a local kernel column, then obtain its actual - /// global row from the current transaction's active range. - pub(in crate::qwen_forward) fn micro_row_index(&self, local: usize) -> Result { - let (first, end) = self.phase_span()?; - let index = first.checked_add(local).ok_or(Error::Overflow)?; - if index >= end { - return Err(Error::IdentityMismatch); - } - Ok(index) - } - pub(in crate::qwen_forward) fn micro_len(&self) -> Result { - let (first, end) = self.phase_span()?; - Ok(end - first) - } - pub(in crate::qwen_forward) fn warm_row_limit(&self) -> usize { - if self.windowed { 256 } else { 64 } - } - pub(in crate::qwen_forward) fn open_micro_window( - &mut self, - layer: LayerId, - ) -> Result { - self.check()?; - if self - .gdn_chunk - .as_ref() - .is_some_and(|journal| journal.start.0.layer != layer) - { - return Err(Error::IdentityMismatch); - } - if !self.windowed - || self.finished - || self.active_micro.is_some() - || self.next_layer != layer.get() - || layer.get() >= 48 - || self.micro_cursor >= self.rows.len() - || self.next_row != self.micro_cursor - || self.attention_next != self.micro_cursor - || self.batch_layer.is_some() - || self.attention_layer.is_some() - || !self.batch_rows.is_empty() - || !self.attention_sources.is_empty() - || self.attention_authorized.is_some() - || self.rows.iter().any(|r| r.input.is_none()) - { - return Err(Error::IdentityMismatch); - } - let first = self.micro_cursor; - let width = 64; - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let width = self.test_micro_width; - if !(1..=64).contains(&width) { - return Err(Error::IdentityMismatch); - } - let end = first - .checked_add(width) - .ok_or(Error::Overflow)? - .min(self.rows.len()); - if self.rows[first..end] - .iter() - .any(|r| r.completed != layer.get()) - { - return Err(Error::IdentityMismatch); - } - let proof = Rc::new(()); - self.active_micro = Some(ActiveMicroWindow { - proof: Rc::clone(&proof), - layer, - first, - end, - }); - Ok(ChunkMicroWindow { - chunk: Rc::clone(&self.chunk), - proof, - layer, - first, - end, - }) - } - /// Consumes the exact minted capability; no next range can open early. - pub(in crate::qwen_forward) fn close_micro_window( - &mut self, - window: ChunkMicroWindow, - ) -> Result<()> { - let (first, end) = self.phase_span()?; - let active = self.active_micro.as_ref().ok_or(Error::IdentityMismatch)?; - if !Rc::ptr_eq(&self.chunk, &window.chunk) - || !Rc::ptr_eq(&active.proof, &window.proof) - || window.first != first - || window.end != end - || window.layer != active.layer - || self.next_row != end - || self.attention_next != end - || self.batch_layer.is_some() - || self.attention_layer.is_some() - || !self.batch_rows.is_empty() - || !self.attention_sources.is_empty() - || self.attention_authorized.is_some() - || self.rows[first..end] - .iter() - .any(|r| r.completed != self.next_layer + 1) - { - return Err(Error::IdentityMismatch); - } - if let Some(journal) = &self.gdn_chunk - && (journal.start.0.layer != window.layer || journal.accepted != end) - { - self.aborted = true; - return Err(Error::IdentityMismatch); - } - // Validate the all-outer barrier before changing any phase cursor. - if end == self.rows.len() && self.rows.iter().any(|r| r.completed != self.next_layer + 1) { - self.aborted = true; - return Err(Error::IdentityMismatch); - } - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - { - self.test_window_journal - .try_reserve(1) - .map_err(|_| Error::InputAllocation)?; - // The tuple is observed only after genuine finite completion and - // all capability checks, before the infallible cursor transition. - self.test_window_journal.push((self.next_layer, first, end)); - } - self.active_micro = None; - self.micro_cursor = end; - if end == self.rows.len() { - self.next_layer += 1; - self.micro_cursor = 0; - self.next_row = 0; - self.attention_next = 0; - } - Ok(()) - } - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in crate::qwen_forward) fn test_use_micro2(&mut self) -> Result<()> { - self.check()?; - if !self.windowed - || self.len() != 4 - || self.next_layer != 0 - || self.next_row != 0 - || self.active_micro.is_some() - || self.rows.iter().any(|r| r.input.is_some()) - { - return Err(Error::IdentityMismatch); - } - self.test_micro_width = 2; - Ok(()) - } - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in crate::qwen_forward) fn test_window_journal(&self) -> &[(u32, usize, usize)] { - &self.test_window_journal - } - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in crate::qwen_forward) fn test_observe_first_layer( - &mut self, - residuals: &[Option], - ) -> Result<()> { - self.check()?; - if !self.windowed - || self.next_layer != 1 - || self.next_row != 0 - || self.finished - || !self.witnesses.is_empty() - || self.active_micro.is_some() - || residuals.len() != self.len() - || self.rows.iter().any(|r| r.completed != 1) - { - return Err(Error::IdentityMismatch); - } - let layer = LayerId::new(0, Dimension::new(48)?)?; - let mut words = 0usize; - for (index, residual) in residuals.iter().enumerate() { - let residual = residual.as_ref().ok_or(Error::IdentityMismatch)?; - residual.validate_origin(&self.session.binding, GrRole::Ffn(0))?; - let (token, position) = self.row_ids(index)?; - residual.identity().validate(token, position, layer)?; - if residual.streams().len() != 10240 - || residual.streams().iter().any(|v| !v.is_finite()) - { - return Err(Error::NonFinite); - } - words = words - .checked_add(residual.streams().len()) - .ok_or(Error::Overflow)?; - } - let end = Position::new(self.end, crate::qwen_forward::contract::position_dimension())?; - if self.session.gdn_layers[0] { - self.next_gdn[0] - .as_ref() - .ok_or(Error::IdentityMismatch)? - .validate(&self.session.binding, &self.session.gdn_owner, layer, end)?; - } else if self.session.qsa_layers[0] { - self.next_qsa[0] - .as_ref() - .ok_or(Error::IdentityMismatch)? - .validate(&self.session.binding, &self.session.qsa_owner, layer, end)?; - } else { - return Err(Error::InvalidLayer); - } - self.test_partial_words = words; - Ok(()) - } - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in crate::qwen_forward) fn test_partial_words(&self) -> usize { - self.test_partial_words - } - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in crate::qwen_forward) fn test_publication_preflight_refused(&self) -> bool { - matches!( - self.validate_publish(), - Err(Error::Unsupported(Stage::Executor)) - ) - } - pub(in crate::qwen_forward) fn context(&self) -> Result<&Context<'driver>> { - self.check()?; - self.session.mtp_context() - } - /// The genuine rolling state at this prompt micro's first causal row. - /// Store an actual initial empty owner once; later validation compares the - /// same Rc state, not a reconstructed position or a batch's final state. - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in crate::qwen_forward) fn prompt_qsa_prior(&mut self, layer: LayerId) -> Result { - let (first, end) = self.phase_span()?; - let slot = layer.get() as usize; - if slot >= STATE_CAPACITY || !self.session.qsa_layers[slot] - || self.next_layer != layer.get() || self.next_row != first - || self.attention_layer != Some(layer) || self.attention_next != end - || self.batch_layer.is_some() || self.attention_authorized.is_some() - { return Err(Error::IdentityMismatch); } - let position = self.rows.get(first).ok_or(Error::InvalidPosition)?.position; - if self.next_qsa[slot].is_none() { - if position.get() != 0 { return Err(Error::IdentityMismatch); } - self.next_qsa[slot] = Some(QsaIndexPrior::empty( - self.session.binding.clone(), &self.session.qsa_owner, layer, - )?); - } - let prior = self.next_qsa[slot].as_ref().ok_or(Error::IdentityMismatch)?; - prior.validate(&self.session.binding, &self.session.qsa_owner, layer, position)?; - Ok(prior.clone()) - } - /// Bind the initial canonical INT8 state to the actual model-owned KV bank. - /// Existing FP16 state cannot be relabeled after a mode switch. - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in crate::qwen_forward) fn prompt_native_qsa_prior( - &mut self, layer: LayerId, kv: &leleka_cuda_driver::QsaPromptKv<'_>, - ) -> Result { - let (first, end) = self.phase_span()?; - let slot = layer.get() as usize; - if slot >= STATE_CAPACITY || !self.session.qsa_layers[slot] - || self.next_layer != layer.get() || self.next_row != first - || self.attention_layer != Some(layer) || self.attention_next != end - || self.batch_layer.is_some() || self.attention_authorized.is_some() - { return Err(Error::IdentityMismatch); } - kv.validate_context(self.session.mtp_context()?).map_err(super::super::super::qsa_index::driver_error)?; - let position = self.rows.get(first).ok_or(Error::InvalidPosition)?.position; - if self.next_qsa[slot].is_none() { - if position.get() != 0 { return Err(Error::IdentityMismatch); } - self.next_qsa[slot] = Some(QsaIndexPrior::empty_native( - self.session.binding.clone(), &self.session.qsa_owner, layer, kv, - )?); - } - let prior = self.next_qsa[slot].as_ref().ok_or(Error::IdentityMismatch)?; - prior.validate(&self.session.binding, &self.session.qsa_owner, layer, position)?; - prior.native_snapshot(kv)?; - Ok(prior.clone()) - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in crate::qwen_forward) fn validate_prompt_qsa_prior( - &self, layer: LayerId, prior: &QsaIndexPrior, - ) -> Result<()> { - let (first, end) = self.phase_span()?; - let slot = layer.get() as usize; - if slot >= STATE_CAPACITY || !self.session.qsa_layers[slot] - || self.next_layer != layer.get() || self.next_row != first - || self.attention_layer != Some(layer) || self.attention_next != end - || self.batch_layer.is_some() || self.attention_authorized.is_some() - || self.next_qsa[slot].as_ref().is_none_or(|actual| !actual.same_state(prior)) - { return Err(Error::IdentityMismatch); } - let position = self.rows.get(first).ok_or(Error::InvalidPosition)?.position; - prior.validate(&self.session.binding, &self.session.qsa_owner, layer, position) - } - pub(in crate::qwen_forward) fn original_session(&self) -> Result<&QwenSession<'driver>> { - self.check()?; - Ok(self.session) - } - pub(in crate::qwen_forward) fn rows(&self) -> &[ChunkRowResidual] { - &self.witnesses - } - pub(in crate::qwen_forward) fn start_position(&self) -> u64 { - self.session.next_position - } - pub(in crate::qwen_forward) fn end_position(&self) -> u64 { - self.end - } - pub(in crate::qwen_forward) fn with_mtp_row( - &mut self, - witness: &ChunkRowResidual, - execute: impl FnOnce( - &mut QwenSession<'driver>, - Position, - TokenId, - &[f32], - TargetStepOrigin, - ) -> Result<()>, - ) -> Result<()> { - let (_, position, next, streams) = self.validate_row(witness)?; - let next = next.ok_or(Error::Unsupported(Stage::Executor))?; - let origin = self.origin.clone(); - let result = execute(self.session, position, next, streams, origin); - if let Err(error) = result { - self.session.note_mtp_failure(&error); - self.aborted = true; - return Err(error); - } - self.validate_row(witness)?; - Ok(()) - } - pub(in crate::qwen_forward) fn validate_row<'a>( - &self, - witness: &'a ChunkRowResidual, - ) -> Result<(TokenId, Position, Option, &'a [f32])> { - self.check()?; - if self.gdn_chunk.is_some() - || !self.finished - || !witness.binding.matches(&self.session.binding) - || !Rc::ptr_eq(&witness.chunk, &self.chunk) - || !witness.origin.same_prefix(&self.origin) - { - return Err(Error::IdentityMismatch); - } - witness.origin.validate(self.session)?; - let index = usize::try_from( - witness - .position - .get() - .checked_sub(self.session.next_position) - .ok_or(Error::InvalidPosition)?, - ) - .map_err(|_| Error::Overflow)?; - let row = self.rows.get(index).ok_or(Error::InvalidPosition)?; - let expected_next = self - .rows - .get(index + 1) - .map(|r| r.token) - .or(self.known_next); - if row.token != witness.token - || row.position != witness.position - || row.completed != 48 - || witness.known_next != expected_next - || witness.streams.len() != 10240 - || witness.streams.iter().any(|v| !v.is_finite()) - { - return Err(Error::IdentityMismatch); - } - Ok(( - witness.token, - witness.position, - witness.known_next, - witness.streams.as_ref(), - )) - } - pub(in crate::qwen_forward) fn row_ids(&self, index: usize) -> Result<(TokenId, Position)> { - self.check()?; - let row = self.rows.get(index).ok_or(Error::InvalidPosition)?; - Ok((row.token, row.position)) - } - pub(in crate::qwen_forward) fn len(&self) -> usize { - self.rows.len() - } - - pub(in crate::qwen_forward) fn begin_gdn_chunk( - &mut self, - layer: LayerId, - ) -> Result { - self.check()?; - let slot = layer.get() as usize; - if !self.windowed - || self.gdn_chunk.is_some() - || self.active_micro.is_some() - || self.next_layer != layer.get() - || self.next_row != 0 - || self.micro_cursor != 0 - || slot >= 48 - || !self.session.gdn_layers[slot] - || self.rows.iter().any(|row| row.completed != layer.get()) - { - return Err(Error::IdentityMismatch); - } - let first = self.rows.first().ok_or(Error::InvalidPosition)?.position; - let prior = match &self.next_gdn[slot] { - Some(prior) => prior.clone(), - None if first.get() == 0 => { - GdnPrior::zero(self.session.binding.clone(), &self.session.gdn_owner, layer)? - } - None => return Err(Error::IdentityMismatch), - }; - prior.validate(&self.session.binding, &self.session.gdn_owner, layer, first)?; - let start = GdnChunkStart(Rc::new(GdnChunkAnchor { - binding: self.session.binding.clone(), - chunk: self.chunk.clone(), - prior, - layer, - first, - end: self.end, - count: self.rows.len(), - })); - start.validate_binding(&self.session.binding)?; - self.gdn_chunk = Some(GdnChunkJournal { - start: start.clone(), - accepted: 0, - }); - Ok(start) - } - pub(in crate::qwen_forward) fn finish_gdn_chunk<'ctx>( - &mut self, - owner: super::super::super::gdn::chunk_device::GdnChunkDevice<'ctx>, - binding: &ModelBinding, - cache: &super::super::super::dense_weight_cache::DenseWeightCache<'ctx>, - ) -> Result<()> { - self.check()?; - let journal = self.gdn_chunk.as_ref().ok_or(Error::IdentityMismatch)?; - let layer = journal.start.0.layer; - if !Rc::ptr_eq(&self.chunk, &journal.start.0.chunk) - || self.active_micro.is_some() - || self.micro_cursor != 0 - || self.next_row != 0 - || self.next_layer != layer.get() + 1 - || journal.accepted != self.rows.len() - || self.batch_layer.is_some() - || self.attention_layer.is_some() - || self.attention_authorized.is_some() - || self.rows.iter().any(|row| row.completed != layer.get() + 1) - { - self.aborted = true; - return Err(Error::IdentityMismatch); - } - let seal = GdnChunkSeal { - start: journal.start.clone(), - }; - if owner.is_verification() { - let result=owner.finish_verification(seal,binding,cache); - if let Err(error)=&result{self.session.note_mtp_failure(error);self.aborted=true;} - result?;self.gdn_chunk=None;return Ok(()); - } - let result = owner.finish(seal, binding, cache).and_then(|prior| { - prior.validate( - &self.session.binding, - &self.session.gdn_owner, - layer, - Position::new(self.end, crate::qwen_forward::contract::position_dimension())?, - )?; - Ok(prior) - }); - match result { - Ok(prior) => { - self.next_gdn[layer.get() as usize] = Some(prior); - self.gdn_chunk = None; - Ok(()) - } - Err(error) => { - self.session.note_mtp_failure(&error); - self.aborted = true; - Err(error) - } - } - } - // Ephemeral, private stage view: shares real binding/Context/state owners, - // never publishes or mints a TargetStepOrigin. Its unused layer states - // may have different positions; only the current causal layer is consumed. - pub(super) fn stage_view(&self, index: usize) -> Result> { - self.check()?; - let row = self.rows.get(index).ok_or(Error::InvalidPosition)?; - Ok(QwenSession { - binding: self.session.binding.clone(), - owner: Rc::clone(&self.session.owner), - owner_thread: self.session.owner_thread, - predecessors: row.predecessors, - next_position: row.position.get(), - cuda: self.session.cuda.clone(), - checkpoint_generation: self.session.checkpoint_generation, - cuda_failed: false, - layer_count: self.session.layer_count, - ple_required: self.session.ple_required, - ple_owner: self.session.ple_owner.clone(), - ple_state: self.next_ple.clone(), - gdn_layers: self.session.gdn_layers, - gdn_owner: self.session.gdn_owner.clone(), - gdn_states: self.next_gdn.clone(), - qsa_layers: self.session.qsa_layers, - qsa_owner: self.session.qsa_owner.clone(), - qsa_states: self.next_qsa.clone(), - state_lag: None, - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - resident_qsa_states:self.session.resident_qsa_states.clone(), - }) - } - pub(in crate::qwen_forward) fn input( - &mut self, - index: usize, - execute: impl FnOnce(&mut QwenStepTxn<'_, 'driver>) -> Result, - ) -> Result<()> { - if self.next_layer != 0 - || self.next_row != 0 - || self.rows.get(index).is_none_or(|r| r.input.is_some()) - { - return Err(Error::IdentityMismatch); - } - let mut view = self.stage_view(index)?; - let row = &self.rows[index]; - let mut step = view.begin(row.token, row.position)?; - let result = execute(&mut step).and_then(|input| step.stage_input(input)); - match result { - Ok(input) => { - self.rows[index].input = Some(input); - Ok(()) - } - Err(error) => { - self.session.note_mtp_failure(&error); - self.aborted = true; - Err(error) - } - } - } - /// Read immutable PLE inputs from the actual current layer-one window. - /// This grants no pending history and advances no causal cursor. The - /// batch producer still has to complete; chronological consumption below - /// validates each pending history against the genuine rolling prior. - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in crate::qwen_forward) fn prepare_ple_micro_inputs( - &mut self, - layer: LayerId, - mut prepare: impl FnMut(usize, &QwenStepTxn<'_, 'driver>) -> Result, - ) -> Result<(PlePrior, Vec)> { - let (first, end) = self.phase_span()?; - if layer.get() != 1 || self.next_layer != 1 - || self.next_row != first || self.attention_next != first - || self.batch_layer.is_some() || self.attention_layer.is_some() - || self.device_gdn_lease()?.is_some() - || !(1..=64).contains(&(end - first)) - || self.rows[first..end].iter().any(|row| row.completed != 1) - { - return Err(Error::IdentityMismatch); - } - let result = (|| { - let prior = self.next_ple.clone().ok_or(Error::Unsupported(Stage::Input))?; - if prior.next_position() != self.rows[first].position.get() { - return Err(Error::IdentityMismatch); - } - let mut inputs = Vec::new(); - inputs.try_reserve_exact(end-first).map_err(|_| Error::InputAllocation)?; - for index in first..end { - let mut view = self.stage_view(index)?; - let row = &self.rows[index]; - let mut step = view.begin(row.token, row.position)?; - step.input = Some(row.input.clone().ok_or(Error::Unsupported(Stage::Input))?); - step.completed_layers = row.completed; - if index == first { step.validate_ple_prior(&prior)?; } - inputs.push(prepare(index, &step)?); - } - Ok((prior, inputs)) - })(); - if let Err(error) = &result { - self.session.note_mtp_failure(error); - self.aborted = true; - } - result - } - /// Prepare one genuine micro-window chronologically, then complete its GR - /// reads as one device batch. PLE remains causal: each real pending history - /// is admitted before preparing the following position. None of the GR row - /// capabilities is published until the entire actual batch has completed. - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in crate::qwen_forward) fn read_attention_micro( - &mut self, - layer: LayerId, - mut prepare: impl FnMut( - usize, - &mut QwenStepTxn<'_, 'driver>, - ) -> Result, - execute: impl FnOnce( - Vec, - ) -> Result>, - ) -> Result> { - let (first, end) = self.phase_span()?; - if layer.get() != self.next_layer - || layer.get() >= 48 - || self.next_row != first - || self.attention_next != first - || self.batch_layer.is_some() - || self.attention_layer.is_some_and(|old| old != layer) - || !(1..=64).contains(&(end - first)) - || self.rows[first..end] - .iter() - .any(|row| row.completed != layer.get()) - { - return Err(Error::IdentityMismatch); - } - let result = (|| { - if self.attention_layer.is_none() { - self.attention_sources - .try_reserve_exact(self.rows.len()) - .map_err(|_| Error::InputAllocation)?; - self.attention_sources.resize_with(self.rows.len(), || None); - self.attention_layer = Some(layer); - } - if self.attention_sources.len() != self.rows.len() - || self.attention_sources[first..end].iter().any(Option::is_some) - { - return Err(Error::IdentityMismatch); - } - let mut inputs = Vec::new(); - inputs - .try_reserve_exact(end - first) - .map_err(|_| Error::InputAllocation)?; - for index in first..end { - if self.attention_next != index { - return Err(Error::IdentityMismatch); - } - let mut view = self.stage_view(index)?; - let row = &self.rows[index]; - let token = row.token; - let position = row.position; - let mut step = view.begin(token, position)?; - step.input = Some(row.input.clone().ok_or(Error::Unsupported(Stage::Input))?); - step.completed_layers = row.completed; - let input = prepare(index, &mut step)?; - input.validate_origin(&self.session.binding, GrRole::Attention(layer.get()))?; - input.identity().validate(token, position, layer)?; - if layer.get() == 1 && self.session.ple_required { - let next = step - .ple_pending - .take() - .ok_or(Error::Unsupported(Stage::Input))? - .into_prior(); - if next.next_position() != position.get() + 1 { - return Err(Error::IdentityMismatch); - } - self.next_ple = Some(next); - self.record_verification_ple(index, position)?; - } else if step.ple_pending.is_some() { - return Err(Error::IdentityMismatch); - } - if step.gdn_pending.iter().any(Option::is_some) - || step.qsa_pending.iter().any(Option::is_some) - { - return Err(Error::IdentityMismatch); - } - inputs.push(input); - self.attention_next += 1; - } - let reads = execute(inputs)?; - if reads.len() != end - first || self.attention_next != end { - return Err(Error::IdentityMismatch); - } - // Validate every completed producer before publishing even the - // first row. Token/position/role come from this actual transaction. - for (row, read) in self.rows[first..end].iter().zip(&reads) { - read.ready() - .validate_origin(&self.session.binding, GrRole::Attention(layer.get()))?; - read.ready().identity().validate(row.token, row.position, layer)?; - } - let mut completed = Vec::new(); - completed - .try_reserve_exact(reads.len()) - .map_err(|_| Error::InputAllocation)?; - for (index, read) in (first..end).zip(reads) { - let proof = Rc::new(()); - let read = Rc::new(read); - self.attention_sources[index] = Some(AttentionSource { - proof: Rc::clone(&proof), - read: Rc::clone(&read), - }); - completed.push(ChunkAttentionRow { - chunk: Rc::clone(&self.chunk), - proof, - index, - layer, - read, - window: self.window_proof(), - }); - } - Ok(completed) - })(); - if let Err(error) = &result { - self.session.note_mtp_failure(error); - self.aborted = true; - } - result - } - pub(in crate::qwen_forward) fn read_attention_column( - &mut self, - index: usize, - layer: LayerId, - execute: impl FnOnce(&mut QwenStepTxn<'_, 'driver>) -> Result, - ) -> Result { - let (first, end) = self.phase_span()?; - if layer.get() != self.next_layer - || layer.get() >= 48 - || self.next_row != first - || index < first - || index >= end - || self.batch_layer.is_some() - || index != self.attention_next - || self.attention_layer.is_some_and(|old| old != layer) - || self - .rows - .get(index) - .is_none_or(|row| row.completed != layer.get()) - { - return Err(Error::IdentityMismatch); - } - if self.attention_layer.is_none() { - self.attention_sources - .try_reserve_exact(self.rows.len()) - .map_err(|_| Error::InputAllocation)?; - self.attention_sources.resize_with(self.rows.len(), || None); - self.attention_layer = Some(layer); - } - let mut view = self.stage_view(index)?; - let row = &self.rows[index]; - let position = row.position; - let mut step = view.begin(row.token, row.position)?; - step.input = Some(row.input.clone().ok_or(Error::Unsupported(Stage::Input))?); - step.completed_layers = row.completed; - let result = execute(&mut step).and_then(|read| { - read.ready() - .validate_origin(&self.session.binding, GrRole::Attention(layer.get()))?; - read.ready() - .identity() - .validate(step.token(), position, layer)?; - if layer.get() == 1 && self.session.ple_required { - let next = step - .ple_pending - .take() - .ok_or(Error::Unsupported(Stage::Input))? - .into_prior(); - if next.next_position() != position.get() + 1 { - return Err(Error::IdentityMismatch); - } - self.next_ple = Some(next); - self.record_verification_ple(index, position)?; - } else if step.ple_pending.is_some() { - return Err(Error::IdentityMismatch); - } - if step.gdn_pending.iter().any(Option::is_some) - || step.qsa_pending.iter().any(Option::is_some) - { - return Err(Error::IdentityMismatch); - } - Ok(read) - }); - match result { - Ok(read) => { - let proof = Rc::new(()); - let read = Rc::new(read); - self.attention_sources[index] = Some(AttentionSource { - proof: Rc::clone(&proof), - read: Rc::clone(&read), - }); - self.attention_next += 1; - Ok(ChunkAttentionRow { - chunk: Rc::clone(&self.chunk), - proof, - index, - layer, - read, - window: self.window_proof(), - }) - } - Err(error) => { - self.session.note_mtp_failure(&error); - self.aborted = true; - Err(error) - } - } - } - pub(in crate::qwen_forward) fn validate_attention_input( - &self, - index: usize, - layer: LayerId, - ready: &super::super::super::gr::ResidualReady, - ) -> Result<()> { - let (first, end) = self.phase_span()?; - if index < first - || index >= end - || self.attention_layer != Some(layer) - || self.attention_next != end - { - return Err(Error::IdentityMismatch); - } - let source = self - .attention_sources - .get(index) - .and_then(Option::as_ref) - .ok_or(Error::IdentityMismatch)?; - if !std::ptr::eq(source.read.ready(), ready) { - return Err(Error::IdentityMismatch); - } - ready.validate_origin(&self.session.binding, GrRole::Attention(layer.get()))?; - let (token, position) = self.row_ids(index)?; - ready.identity().validate(token, position, layer) - } - pub(in crate::qwen_forward) fn validate_attention_column( - &self, - index: usize, - layer: LayerId, - read: &ChunkAttentionRow, - ) -> Result<()> { - self.validate_attention_input(index, layer, read.ready())?; - self.validate_window_proof(&read.window)?; - let source = self.attention_sources[index] - .as_ref() - .ok_or(Error::IdentityMismatch)?; - if !Rc::ptr_eq(&self.chunk, &read.chunk) - || !Rc::ptr_eq(&source.proof, &read.proof) - || !Rc::ptr_eq(&source.read, &read.read) - || read.index != index - || read.layer != layer - { - return Err(Error::IdentityMismatch); - } - Ok(()) - } - pub(in crate::qwen_forward) fn prepare_attention_layer_batch( - &mut self, - index: usize, - layer: LayerId, - read: &ChunkAttentionRow, - execute: impl FnOnce( - &mut QwenStepTxn<'_, 'driver>, - &super::super::super::gr::DetachedGrRead, - ) -> Result, - ) -> Result<(T, PreparedLayerRow)> { - self.validate_attention_input(index, layer, read.ready())?; - self.validate_window_proof(&read.window)?; - let source = self.attention_sources[index] - .as_ref() - .ok_or(Error::IdentityMismatch)?; - if !Rc::ptr_eq(&self.chunk, &read.chunk) - || !Rc::ptr_eq(&source.proof, &read.proof) - || !Rc::ptr_eq(&source.read, &read.read) - || read.index != index - || read.layer != layer - || self.attention_authorized.is_some() - { - return Err(Error::IdentityMismatch); - } - self.attention_authorized = Some(index); - let result = self.prepare_layer_batch(index, layer, |step| execute(step, &read.read)); - self.attention_authorized = None; - if result.is_ok() { - self.attention_sources[index] = None; - } - result - } - pub(in crate::qwen_forward) fn prepare_attention_ffn( - &mut self, - index: usize, - layer: LayerId, - read: &ChunkAttentionRow, - execute: impl FnOnce( - &mut QwenStepTxn<'_, 'driver>, - &super::super::super::gr::DetachedGrRead, - ) -> Result, - ) -> Result { - let (row, proof) = self.prepare_attention_layer_batch(index, layer, read, execute)?; - row.validate( - &self.session.binding, - self.rows[index].token, - self.rows[index].position, - layer, - )?; - Ok(ChunkFfnRow { proof, row }) - } - pub(in crate::qwen_forward) fn prepare_attention_ffn_device_gdn( - &mut self, - index: usize, - layer: LayerId, - read: &ChunkAttentionRow, - execute: impl FnOnce( - &mut QwenStepTxn<'_, 'driver>, - &super::super::super::gr::DetachedGrRead, - GdnChunkRow, - ) -> Result<( - super::super::super::moe_expert::PreparedMoeRow, - super::super::super::gdn::chunk_device::ChunkEdge, - )>, - ) -> Result { - self.validate_attention_input(index, layer, read.ready())?; - self.validate_window_proof(&read.window)?; - let source = self.attention_sources[index] - .as_ref() - .ok_or(Error::IdentityMismatch)?; - let journal = self.gdn_chunk.as_ref().ok_or(Error::IdentityMismatch)?; - if !Rc::ptr_eq(&self.chunk, &read.chunk) - || !Rc::ptr_eq(&source.proof, &read.proof) - || !Rc::ptr_eq(&source.read, &read.read) - || read.index != index - || read.layer != layer - || self.attention_authorized.is_some() - || journal.accepted != index - { - return Err(Error::IdentityMismatch); - } - let actual = &self.rows[index]; - let row = GdnChunkRow { - start: journal.start.clone(), - index, - identity: TokenLayer::new(actual.token, actual.position, layer), - proof: source.proof.clone(), - window: read.window.clone(), - key: Rc::new(()), - }; - row.validate(&journal.start, index, &self.session.binding)?; - self.attention_authorized = Some(index); - let result = self.prepare_layer_batch_internal(index, layer, |step| { - execute(step, &read.read, row).map(|(v, e)| (v, Some(e))) - }); - self.attention_authorized = None; - let (row, proof) = result?; - self.attention_sources[index] = None; - row.validate( - &self.session.binding, - self.rows[index].token, - self.rows[index].position, - layer, - )?; - Ok(ChunkFfnRow { proof, row }) - } - /// The device attention edge is genuine, but independent FFN GR reads may - /// be completed after collecting all causal attention rows of this window. - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in crate::qwen_forward) fn prepare_attention_device_gdn( - &mut self, - index: usize, - layer: LayerId, - read: &ChunkAttentionRow, - execute: impl FnOnce( - &mut QwenStepTxn<'_, 'driver>, - &super::super::super::gr::DetachedGrRead, - GdnChunkRow, - ) -> Result<(T, super::super::super::gdn::chunk_device::ChunkEdge)>, - ) -> Result<(T, PreparedLayerRow)> { - self.validate_attention_input(index, layer, read.ready())?; - self.validate_window_proof(&read.window)?; - let source = self.attention_sources[index] - .as_ref() - .ok_or(Error::IdentityMismatch)?; - let journal = self.gdn_chunk.as_ref().ok_or(Error::IdentityMismatch)?; - if !Rc::ptr_eq(&self.chunk, &read.chunk) - || !Rc::ptr_eq(&source.proof, &read.proof) - || !Rc::ptr_eq(&source.read, &read.read) - || read.index != index - || read.layer != layer - || self.attention_authorized.is_some() - || journal.accepted != index - { - return Err(Error::IdentityMismatch); - } - let actual = &self.rows[index]; - let row = GdnChunkRow { - start: journal.start.clone(), - index, - identity: TokenLayer::new(actual.token, actual.position, layer), - proof: source.proof.clone(), - window: read.window.clone(), - key: Rc::new(()), - }; - row.validate(&journal.start, index, &self.session.binding)?; - self.attention_authorized = Some(index); - let result = self.prepare_layer_batch_internal(index, layer, |step| { - execute(step, &read.read, row).map(|(value, edge)| (value, Some(edge))) - }); - self.attention_authorized = None; - if result.is_ok() { - self.attention_sources[index] = None; - } - result - } - - /// Complete the actual whole prompt GDN window before advancing any row - /// edge. Only genuine per-row products/edges of that completed batch may - /// then enter the ordinary current-transaction journal and GR producer. - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in crate::qwen_forward) fn prepare_attention_micro_gdn( - &mut self, - layer: LayerId, - attention: &[ChunkAttentionRow], - execute: impl FnOnce(&GdnChunkMicro, &Context<'driver>) -> Result>, - mut consume: impl FnMut( - usize, &mut QwenStepTxn<'_, 'driver>, - &super::super::super::gr::DetachedGrRead, R, - ) -> Result<(T, super::super::super::gdn::chunk_device::ChunkEdge)>, - ) -> Result> { - let (first, end) = self.phase_span()?; - let journal = self.gdn_chunk.as_ref().ok_or(Error::IdentityMismatch)?; - if self.device_gdn_lease()?.is_some() - || self.next_layer != layer.get() - || self.next_row != first - || self.attention_next != end - || self.batch_layer.is_some() - || self.attention_layer != Some(layer) - || self.attention_authorized.is_some() - || journal.accepted != first - || attention.len() != end - first - || !(1..=64).contains(&attention.len()) - { - return Err(Error::IdentityMismatch); - } - let mut micro = GdnChunkMicro { - start: journal.start.clone(), first, rows: Vec::new(), reads: Vec::new(), - }; - micro.rows.try_reserve_exact(attention.len()).map_err(|_| Error::InputAllocation)?; - micro.reads.try_reserve_exact(attention.len()).map_err(|_| Error::InputAllocation)?; - for (local, read) in attention.iter().enumerate() { - let index = first + local; - self.validate_attention_column(index, layer, read)?; - let actual = &self.rows[index]; - micro.rows.push(GdnChunkRow { - start: micro.start.clone(), index, - identity: TokenLayer::new(actual.token, actual.position, layer), - proof: Rc::clone(&read.proof), window: read.window.clone(), key: Rc::new(()), - }); - micro.reads.push(Rc::clone(&read.read)); - } - micro.validate(µ.start, first, &self.session.binding)?; - let result = (|| { - let products = execute(µ, self.session.mtp_context()?)?; - if products.len() != attention.len() { - return Err(Error::IdentityMismatch); - } - let mut completed = Vec::new(); - completed.try_reserve_exact(products.len()).map_err(|_| Error::InputAllocation)?; - for (local, (read, product)) in attention.iter().zip(products).enumerate() { - let index = first + local; - self.validate_attention_column(index, layer, read)?; - if self.gdn_chunk.as_ref().is_none_or(|journal| journal.accepted != index) { - return Err(Error::IdentityMismatch); - } - self.attention_authorized = Some(index); - let prepared = self.prepare_layer_batch_internal(index, layer, |step| { - consume(local, step, &read.read, product) - .map(|(value, edge)| (value, Some(edge))) - }); - self.attention_authorized = None; - completed.push(prepared?); - self.attention_sources[index] = None; - } - Ok(completed) - })(); - if let Err(error) = &result { - self.session.note_mtp_failure(error); - self.aborted = true; - } - result - } - - /// Validate a completed causal row against the actual read it registered. - /// The source has already left attention_sources, so the unique live - /// prepared-row proof carries its original Rc into the later Out batch. - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in crate::qwen_forward) fn validate_prepared_attention_input( - &self, proof: &PreparedLayerRow, - input: &super::super::super::gr::ResidualReady, - ) -> Result<()> { - let (first, end) = self.phase_span()?; - self.validate_window_proof(&proof.window)?; - if proof.index < first || proof.index >= end - || self.batch_layer != Some(proof.layer) - || self.next_layer != proof.layer.get() || self.next_row != end - || self.batch_completed != first - || !Rc::ptr_eq(&self.chunk, &proof.chunk) - || self.batch_rows.get(proof.index).and_then(Option::as_ref) - .is_none_or(|stored| !Rc::ptr_eq(stored, &proof.proof)) - { return Err(Error::IdentityMismatch); } - let source = proof.attention_source.as_ref().ok_or(Error::IdentityMismatch)?; - if !std::ptr::eq(source.ready(), input) { - return Err(Error::IdentityMismatch); - } - let actual = self.rows.get(proof.index).ok_or(Error::IdentityMismatch)?; - if actual.completed != proof.layer.get() { return Err(Error::IdentityMismatch); } - input.validate_origin(&self.session.binding, GrRole::Attention(proof.layer.get()))?; - input.identity().validate(actual.token, actual.position, proof.layer) - } - - /// Enlist a fully completed Out row into GR using its real causal proof - /// and current transaction, without advancing attention a second time. - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in crate::qwen_forward) fn prepare_attention_output_after_causal( - &mut self, proof: &PreparedLayerRow, source: &ChunkAttentionRow, - execute: impl FnOnce( - &mut QwenStepTxn<'_, 'driver>, &super::super::super::gr::DetachedGrRead, - ) -> Result, - ) -> Result { - self.validate_prepared_attention_input(proof, source.ready())?; - self.validate_window_proof(&source.window)?; - if source.index != proof.index || source.layer != proof.layer - || !Rc::ptr_eq(&self.chunk, &source.chunk) - || proof.attention_source.as_ref() - .is_none_or(|actual| !Rc::ptr_eq(actual, &source.read)) - { return Err(Error::IdentityMismatch); } - let actual = &self.rows[proof.index]; - let token = actual.token; - let position = actual.position; - let result = (|| { - let mut view = self.stage_view(proof.index)?; - let mut step = view.begin(token, position)?; - step.input = Some(actual.input.clone().ok_or(Error::Unsupported(Stage::Input))?); - step.completed_layers = actual.completed; - let output = execute(&mut step, &source.read)?; - if step.ple_pending.is_some() - || step.gdn_pending.iter().any(Option::is_some) - || step.qsa_pending.iter().any(Option::is_some) - { return Err(Error::IdentityMismatch); } - Ok(output) - })(); - if let Err(error) = &result { - self.session.note_mtp_failure(error); self.aborted = true; - } - result - } - - /// Consume the actual prepared attention proof and completed FFN read; - /// reopening a row for routing cannot advance its causal attention twice. - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in crate::qwen_forward) fn validate_prepared_ffn_read( - &self, proof: &PreparedLayerRow, read: &super::super::super::gr::DetachedGrRead, - ) -> Result { - let (first, end) = self.phase_span()?; - self.validate_window_proof(&proof.window)?; - if proof.index < first || proof.index >= end - || self.batch_layer != Some(proof.layer) - || self.next_layer != proof.layer.get() || self.next_row != end - || self.batch_completed != first || !Rc::ptr_eq(&self.chunk, &proof.chunk) - || self.batch_rows.get(proof.index).and_then(Option::as_ref) - .is_none_or(|stored| !Rc::ptr_eq(stored, &proof.proof)) - { return Err(Error::IdentityMismatch); } - let actual = &self.rows[proof.index]; - if actual.completed != proof.layer.get() { return Err(Error::IdentityMismatch); } - read.ready().validate_origin(&self.session.binding, GrRole::Ffn(proof.layer.get()))?; - let identity = read.ready().identity(); - identity.validate(actual.token, actual.position, proof.layer)?; - Ok(identity) - } - - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in crate::qwen_forward) fn prepare_ffn_after_attention( - &mut self, - proof: PreparedLayerRow, - read: super::super::super::gr::DetachedGrRead, - execute: impl FnOnce( - &mut QwenStepTxn<'_, 'driver>, - super::super::super::gr::DetachedGrRead, - ) -> Result, - ) -> Result { - let (first, end) = self.phase_span()?; - self.validate_window_proof(&proof.window)?; - if proof.index < first - || proof.index >= end - || self.batch_layer != Some(proof.layer) - || self.next_layer != proof.layer.get() - || self.next_row != end - || self.batch_completed != first - || !Rc::ptr_eq(&self.chunk, &proof.chunk) - || self.batch_rows.get(proof.index).and_then(Option::as_ref) - .is_none_or(|stored| !Rc::ptr_eq(stored, &proof.proof)) - { - return Err(Error::IdentityMismatch); - } - let actual = &self.rows[proof.index]; - let token = actual.token; - let position = actual.position; - if actual.completed != proof.layer.get() { - return Err(Error::IdentityMismatch); - } - read.ready().validate_origin(&self.session.binding, GrRole::Ffn(proof.layer.get()))?; - read.ready().identity().validate(token, position, proof.layer)?; - let result = (|| { - let mut view = self.stage_view(proof.index)?; - let mut step = view.begin(token, position)?; - step.input = Some(actual.input.clone().ok_or(Error::Unsupported(Stage::Input))?); - step.completed_layers = actual.completed; - let row = execute(&mut step, read)?; - if step.ple_pending.is_some() - || step.gdn_pending.iter().any(Option::is_some) - || step.qsa_pending.iter().any(Option::is_some) - { - return Err(Error::IdentityMismatch); - } - row.validate(&self.session.binding, token, position, proof.layer)?; - Ok(ChunkFfnRow { proof, row }) - })(); - if let Err(error) = &result { - self.session.note_mtp_failure(error); - self.aborted = true; - } - result - } - pub(super) fn roll_device_gdn( - &mut self, - step: &QwenStepTxn<'_, 'driver>, - index: usize, - layer: LayerId, - edge: super::super::super::gdn::chunk_device::ChunkEdge, - ) -> Result<()> { - if step.ple_pending.is_some() - || step.gdn_pending.iter().any(Option::is_some) - || step.qsa_pending.iter().any(Option::is_some) - || self.attention_authorized != Some(index) - { - return Err(Error::IdentityMismatch); - } - let (row,verified) = edge.into_parts(); - self.validate_window_proof(&row.window)?; - let journal = self.gdn_chunk.as_ref().ok_or(Error::IdentityMismatch)?; - row.validate(&journal.start, journal.accepted, &self.session.binding)?; - let actual = self.rows.get(index).ok_or(Error::IdentityMismatch)?; - let source = self - .attention_sources - .get(index) - .and_then(Option::as_ref) - .ok_or(Error::IdentityMismatch)?; - if row.index != index - || row.identity != TokenLayer::new(actual.token, actual.position, layer) - || !Rc::ptr_eq(&source.proof, &row.proof) - || !Rc::ptr_eq(&self.chunk, &row.start.0.chunk) - { - return Err(Error::IdentityMismatch); - } - if let Some(proof)=verified {self.record_device_gdn(index,layer,proof)?;} - else if self.device_gdn_lease()?.is_some(){return Err(Error::IdentityMismatch);} - self.gdn_chunk - .as_mut() - .ok_or(Error::IdentityMismatch)? - .accepted += 1; - Ok(()) - } - pub(in crate::qwen_forward) fn validate_ffn_row( - &self, - index: usize, - layer: LayerId, - row: &ChunkFfnRow, - ) -> Result<()> { - let (first, end) = self.phase_span()?; - let proof = &row.proof; - self.validate_window_proof(&proof.window)?; - let stored = self - .batch_rows - .get(index) - .and_then(Option::as_ref) - .ok_or(Error::IdentityMismatch)?; - if self.batch_layer != Some(layer) - || index < first - || index >= end - || self.next_row != end - || self.batch_completed != first - || proof.index != index - || proof.layer != layer - || !Rc::ptr_eq(&self.chunk, &proof.chunk) - || !Rc::ptr_eq(stored, &proof.proof) - { - return Err(Error::IdentityMismatch); - } - let (token, position) = self.row_ids(index)?; - row.row - .validate(&self.session.binding, token, position, layer) - } - pub(in crate::qwen_forward) fn prepare_ffn_injection( - &mut self, - index: usize, - layer: LayerId, - row: ChunkFfnRow, - binding: &ModelBinding, - expert: super::super::super::moe_expert::ExpertReady, - ) -> Result<(super::super::super::gr::GrBatchRow, PreparedLayerRow)> { - self.validate_ffn_row(index, layer, &row)?; - expert.validate_origin(&self.session.binding)?; - let (token, position) = self.row_ids(index)?; - expert.identity().validate(token, position, layer)?; - let mut view = self.stage_view(index)?; - let mut step = view.begin(token, position)?; - step.input = Some( - self.rows[index] - .input - .clone() - .ok_or(Error::Unsupported(Stage::Input))?, - ); - step.completed_layers = self.rows[index].completed; - let result = super::super::super::gr::GrStage::prepare_detached_batch_injection( - binding, - row.row.into_read(), - expert.output(), - expert.identity(), - &mut step, - ); - if let Err(error) = &result { - self.session.note_mtp_failure(error); - self.aborted = true; - } - Ok((result?, row.proof)) - } - pub(super) fn roll_actual_pending( - &mut self, - step: &mut QwenStepTxn<'_, 'driver>, - layer: LayerId, - position: Position, - ) -> Result<()> { - // Validate pending producers now, then release each previous rolling - // state before another row executes this causal layer. - let slot = layer.get() as usize; - let next_position = position.get().checked_add(1).ok_or(Error::Overflow)?; - if self.attention_layer == Some(layer) { - let index = self.attention_authorized.ok_or(Error::IdentityMismatch)?; - if self - .attention_sources - .get(index) - .and_then(Option::as_ref) - .is_none() - || step.ple_pending.is_some() - { - return Err(Error::IdentityMismatch); - } - } else { - if layer.get() == 1 && self.session.ple_required { - let next = step - .ple_pending - .take() - .ok_or(Error::Unsupported(Stage::Input))? - .into_prior(); - if next.next_position() != next_position { - return Err(Error::IdentityMismatch); - } - self.next_ple = Some(next); - self.record_verification_ple(self.next_row, position)?; - } else if step.ple_pending.is_some() { - return Err(Error::IdentityMismatch); - } - } - if self.session.gdn_layers[slot] { - let next = step.gdn_pending[slot] - .take() - .ok_or(Error::Unsupported(Stage::Gdn))? - .into_prior(); - if next.layer() != layer || next.next_position() != next_position { - return Err(Error::IdentityMismatch); - } - self.next_gdn[slot] = Some(next); - } else if self.session.qsa_layers[slot] { - let next = step.qsa_pending[slot] - .take() - .ok_or(Error::Unsupported(Stage::QsaIndex))? - .into_prior(); - if next.layer() != layer || next.next_position() != next_position { - return Err(Error::IdentityMismatch); - } - self.next_qsa[slot] = Some(next); - } else { - return Err(Error::InvalidLayer); - } - self.record_verification_prior(self.next_row, layer, position)?; - // No hidden noncurrent-layer candidate is admitted. - if step.gdn_pending.iter().any(Option::is_some) - || step.qsa_pending.iter().any(Option::is_some) - { - return Err(Error::IdentityMismatch); - } - Ok(()) - } - pub(in crate::qwen_forward) fn layer( - &mut self, - index: usize, - layer: LayerId, - execute: impl FnOnce(&mut QwenStepTxn<'_, 'driver>) -> Result, - ) -> Result { - self.check()?; - if self.windowed || self.batch_layer.is_some() || self.attention_layer.is_some() { - return Err(Error::IdentityMismatch); - } - if layer.get() != self.next_layer - || index != self.next_row - || layer.get() >= 48 - || self - .rows - .get(index) - .is_none_or(|r| r.completed != layer.get()) - { - return Err(Error::IdentityMismatch); - } - let mut view = self.stage_view(index)?; - let row = &self.rows[index]; - let mut step = view.begin(row.token, row.position)?; - step.input = Some(row.input.clone().ok_or(Error::Unsupported(Stage::Input))?); - step.completed_layers = row.completed; - let result = execute(&mut step).and_then(|residual| { - step.mark_layer_complete(&residual)?; - let position = step.position(); - self.roll_actual_pending(&mut step, layer, position)?; - Ok(residual) - }); - match result { - Ok(residual) => { - self.rows[index].completed += 1; - self.next_row += 1; - if self.next_row == self.rows.len() { - self.next_row = 0; - self.next_layer += 1; - } - Ok(residual) - } - Err(error) => { - self.session.note_mtp_failure(&error); - self.aborted = true; - Err(error) - } - } - } - pub(in crate::qwen_forward) fn prepare_layer_batch( - &mut self, - index: usize, - layer: LayerId, - execute: impl FnOnce(&mut QwenStepTxn<'_, 'driver>) -> Result, - ) -> Result<(T, PreparedLayerRow)> { - self.prepare_layer_batch_internal(index, layer, |step| { - execute(step).map(|prepared| (prepared, None)) - }) - } - pub(super) fn prepare_layer_batch_internal( - &mut self, - index: usize, - layer: LayerId, - execute: impl FnOnce( - &mut QwenStepTxn<'_, 'driver>, - ) -> Result<(T, Option)>, - ) -> Result<(T, PreparedLayerRow)> { - let (first, end) = self.phase_span()?; - if index < first || index >= end { - return Err(Error::IdentityMismatch); - } - if (self.windowed && self.attention_layer.is_none()) - || (self.attention_layer.is_some() && self.attention_authorized != Some(index)) - { - return Err(Error::IdentityMismatch); - } - if layer.get() != self.next_layer - || index != self.next_row - || layer.get() >= 48 - || self - .rows - .get(index) - .is_none_or(|r| r.completed != layer.get()) - || self.batch_layer.is_some_and(|current| current != layer) - { - return Err(Error::IdentityMismatch); - } - if self.batch_layer.is_none() { - if index != first { - return Err(Error::IdentityMismatch); - } - self.batch_rows - .try_reserve_exact(self.rows.len()) - .map_err(|_| Error::InputAllocation)?; - self.batch_rows.resize_with(self.rows.len(), || None); - self.batch_layer = Some(layer); - self.batch_completed = first; - } - let mut view = self.stage_view(index)?; - let row = &self.rows[index]; - let position = row.position; - let mut step = view.begin(row.token, row.position)?; - step.input = Some(row.input.clone().ok_or(Error::Unsupported(Stage::Input))?); - step.completed_layers = row.completed; - let result = execute(&mut step).and_then(|(prepared, edge)| { - if let Some(edge) = edge { - self.roll_device_gdn(&step, index, layer, edge)?; - } else { - if self.gdn_chunk.is_some() { - return Err(Error::IdentityMismatch); - } - self.roll_actual_pending(&mut step, layer, position)?; - } - Ok(prepared) - }); - match result { - Ok(prepared) => { - let proof = Rc::new(()); - self.batch_rows[index] = Some(Rc::clone(&proof)); - self.next_row += 1; - Ok(( - prepared, - PreparedLayerRow { - chunk: Rc::clone(&self.chunk), - proof, - index, - layer, - window: self.window_proof(), - attention_source: self.attention_sources.get(index) - .and_then(Option::as_ref).map(|source| Rc::clone(&source.read)), - }, - )) - } - Err(error) => { - self.session.note_mtp_failure(&error); - self.aborted = true; - Err(error) - } - } - } - pub(in crate::qwen_forward) fn batch_outputs( - &mut self, - execute: impl FnOnce(&Context<'driver>) -> Result, - ) -> Result { - let (first, end) = self.phase_span()?; - if self.batch_layer.is_none() - || self.next_row != end - || self - .batch_rows - .get(first..end) - .is_none_or(|rows| rows.iter().any(Option::is_none)) - { - return Err(Error::IdentityMismatch); - } - let result = execute(self.session.mtp_context()?); - if let Err(error) = &result { - self.session.note_mtp_failure(error); - self.aborted = true; - } - result - } - /// Closed experimental FFN execution retains an immutable borrow of the - /// actual transaction, so every D2D copy can revalidate its real row seal. - pub(in crate::qwen_forward) fn batch_outputs_ffn( - &mut self, - layer: LayerId, - rows: &[ChunkFfnRow], - execute: impl FnOnce(&Self, &Context<'driver>) -> Result, - ) -> Result { - if rows.len() != self.micro_len()? || !(1..=64).contains(&rows.len()) { - return Err(Error::InvalidDimension); - } - for (index, row) in rows.iter().enumerate() { - self.validate_ffn_row(self.micro_row_index(index)?, layer, row)?; - } - let result = execute(self, self.session.mtp_context()?).and_then(|value| { - for (index, row) in rows.iter().enumerate() { - self.validate_ffn_row(self.micro_row_index(index)?, layer, row)?; - } - Ok(value) - }); - if let Err(error) = &result { - self.session.note_mtp_failure(error); - self.aborted = true; - } - result - } - pub(in crate::qwen_forward) fn complete_layer_batch( - &mut self, - proof: PreparedLayerRow, - residual: InjectedResidual, - ) -> Result { - let (first, end) = self.phase_span()?; - self.validate_window_proof(&proof.window)?; - if proof.index < first - || proof.index >= end - || self.batch_layer != Some(proof.layer) - || !Rc::ptr_eq(&self.chunk, &proof.chunk) - || proof.index != self.batch_completed - || self.next_row != end - || self - .batch_rows - .get(proof.index) - .and_then(Option::as_ref) - .is_none_or(|p| !Rc::ptr_eq(p, &proof.proof)) - { - return Err(Error::IdentityMismatch); - } - let mut view = self.stage_view(proof.index)?; - let row = &self.rows[proof.index]; - let mut step = view.begin(row.token, row.position)?; - step.input = Some(row.input.clone().ok_or(Error::Unsupported(Stage::Input))?); - step.completed_layers = row.completed; - // Only actual GR producer-owned finite FFN residual completes the row. - if let Err(error) = step.mark_layer_complete(&residual) { - self.session.note_mtp_failure(&error); - self.aborted = true; - return Err(error); - } - self.rows[proof.index].completed += 1; - self.batch_rows[proof.index] = None; - self.batch_completed += 1; - if self.batch_completed == end { - if self.windowed { - self.next_row = end; - } else { - self.next_row = 0; - self.next_layer += 1; - } - self.batch_layer = None; - self.batch_rows.clear(); - self.batch_completed = 0; - self.attention_layer = None; - self.attention_next = if self.windowed { end } else { 0 }; - self.attention_sources.clear(); - self.attention_authorized = None; - } - Ok(residual) - } - - pub(in crate::qwen_forward) fn finish( - &mut self, - residuals: &[Option], - execute_head: impl FnOnce(&mut QwenStepTxn<'_, 'driver>, &InjectedResidual) -> Result, - ) -> Result<()> { - let result = self.finish_inner(residuals, execute_head); - if let Err(error) = &result { - self.session.note_mtp_failure(error); - self.aborted = true; - } - result - } - pub(super) fn finish_inner( - &mut self, - residuals: &[Option], - execute_head: impl FnOnce(&mut QwenStepTxn<'_, 'driver>, &InjectedResidual) -> Result, - ) -> Result<()> { - self.check()?; - if self.finished - || self.next_layer != 48 - || self.next_row != 0 - || self.active_micro.is_some() - || self.micro_cursor != 0 - || residuals.len() != self.rows.len() - { - return Err(Error::IdentityMismatch); - } - for (index, residual) in residuals.iter().enumerate() { - let row = &self.rows[index]; - let residual = residual - .as_ref() - .ok_or(Error::Unsupported(Stage::Executor))?; - residual.validate_origin(&self.session.binding, GrRole::Ffn(47))?; - residual.identity().validate( - row.token, - row.position, - LayerId::new(47, Dimension::new(48)?)?, - )?; - if row.completed != 48 - || residual.streams().len() != 10240 - || residual.streams().iter().any(|v| !v.is_finite()) - { - return Err(Error::NonFinite); - } - let mut streams = Vec::new(); - streams - .try_reserve_exact(10240) - .map_err(|_| Error::InputAllocation)?; - streams.extend_from_slice(residual.streams()); - self.witnesses.push(ChunkRowResidual { - binding: self.session.binding.clone(), - chunk: Rc::clone(&self.chunk), - origin: self.origin.clone(), - token: row.token, - position: row.position, - known_next: self - .rows - .get(index + 1) - .map(|r| r.token) - .or(self.known_next), - streams: Rc::new(streams.into_boxed_slice()), - }); - } - if self.known_next.is_none() { - let index = self.rows.len() - 1; - let mut view = self.stage_view(index)?; - let row = &self.rows[index]; - let mut step = view.begin(row.token, row.position)?; - step.input = row.input.clone(); - step.completed_layers = 48; - match execute_head( - &mut step, - residuals[index].as_ref().ok_or(Error::IdentityMismatch)?, - ) { - Ok(output) if step.forward_output == Some(output) && !step.prefill_finished => { - self.output = Some(output) - } - Ok(_) => return Err(Error::IdentityMismatch), - Err(error) => { - self.session.note_mtp_failure(&error); - return Err(error); - } - } - } - self.finished = true; - Ok(()) - } - pub(super) fn validate_publish(&self) -> Result<()> { - self.check()?; - if !self.finished - || self.active_micro.is_some() - || self.micro_cursor != 0 - || self.next_layer != 48 - || self.next_row != 0 - || self.witnesses.len() != self.rows.len() - || (self.known_next.is_none() != self.output.is_some()) - { - return Err(Error::Unsupported(Stage::Executor)); - } - for witness in &self.witnesses { - self.validate_row(witness)?; - } - let end_position = Position::new(self.end, crate::qwen_forward::contract::position_dimension())?; - if self.session.ple_required { - self.next_ple - .as_ref() - .ok_or(Error::Unsupported(Stage::Input))? - .validate(&self.session.binding, &self.session.ple_owner, end_position)?; - } - for slot in 0..STATE_CAPACITY { - let layer = LayerId::new(slot as u64, Dimension::new(48)?)?; - if self.session.gdn_layers[slot] { - if self.device_gdn_lease()?.is_some() { - self.validate_verification_state(self.rows.len()-1)?; - } else { - self.next_gdn[slot] - .as_ref() - .ok_or(Error::Unsupported(Stage::Gdn))? - .validate( - &self.session.binding, - &self.session.gdn_owner, - layer, - end_position, - )?; - } - } else if self.next_gdn[slot].is_some() { - return Err(Error::IdentityMismatch); - } - if self.session.qsa_layers[slot] { - self.next_qsa[slot] - .as_ref() - .ok_or(Error::Unsupported(Stage::QsaIndex))? - .validate( - &self.session.binding, - &self.session.qsa_owner, - layer, - end_position, - )?; - } else if self.next_qsa[slot].is_some() { - return Err(Error::IdentityMismatch); - } - } - Ok(()) - } - pub(in crate::qwen_forward) fn publish_joint( - self, - draft: impl ChunkDraftPublication, - ) -> Result { - if self.verification.is_some() { - return Err(Error::IdentityMismatch); - } - self.validate_publish()?; - draft.validate(&self)?; - self.session.complete_cuda()?; - let last = self.rows.last().ok_or(Error::InvalidPosition)?; - let predecessors = [ - last.predecessors[1], - i32::try_from(last.token.get()).map_err(|_| Error::InvalidToken)?, - ]; - let source = self.witnesses.last().ok_or(Error::IdentityMismatch)?; - let token = source.token; - let position = source.position; - let binding = source.binding.clone(); - let mut streams = Vec::new(); - streams - .try_reserve_exact(10240) - .map_err(|_| Error::InputAllocation)?; - streams.extend_from_slice(source.streams.as_ref()); - let streams = streams.into_boxed_slice(); - // Every fallible operation above. Neither target nor draft is exposed - // between these infallible assignments in this single-thread owner. - self.session.ple_state = self.next_ple; - self.session.gdn_states = self.next_gdn; - self.session.qsa_states = self.next_qsa; - self.session.predecessors = predecessors; - self.session.next_position = self.end; - draft.publish(); - let origin = super::super::checkpoint::committed_origin(self.session); - Ok(ChunkCommit { - binding, - token, - position, - output: self.output, - streams, - origin, - }) - } -} +#[path = "impl_qwenchunktxn/impl_qwenchunktxn_2.rs"] +mod impl_qwenchunktxn_2; +#[path = "impl_qwenchunktxn/impl_qwenchunktxn_2_2.rs"] +mod impl_qwenchunktxn_2_2; +#[path = "impl_qwenchunktxn/impl_qwenchunktxn_3.rs"] +mod impl_qwenchunktxn_3; +#[path = "impl_qwenchunktxn/impl_qwenchunktxn_4.rs"] +mod impl_qwenchunktxn_4; +#[path = "impl_qwenchunktxn/impl_qwenchunktxn_5.rs"] +mod impl_qwenchunktxn_5; +#[path = "impl_qwenchunktxn/impl_qwenchunktxn_6.rs"] +mod impl_qwenchunktxn_6; +#[path = "impl_qwenchunktxn/impl_qwenchunktxn_7.rs"] +mod impl_qwenchunktxn_7; +#[path = "impl_qwenchunktxn/impl_qwenchunktxn_8.rs"] +mod impl_qwenchunktxn_8; +#[path = "impl_qwenchunktxn/impl_qwenchunktxn_9.rs"] +mod impl_qwenchunktxn_9; diff --git a/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_2.rs b/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_2.rs new file mode 100644 index 00000000..ff5843fb --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_2.rs @@ -0,0 +1,215 @@ +//! Moved out of the parent module by STRA-338: impl QwenChunkTxn. + +#[allow(unused_imports)] +use super::*; + + + +impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { + /// Actual extra simultaneous owners of the selected native prompt PLE + /// batch. Caller reserves this before begin; default and verification + /// admission retain their existing exact charge and 512 MiB ceiling. + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in crate::qwen_forward) fn native_prefill_host_charge(tokens: usize) -> Result { + if !(1..=256).contains(&tokens) { return Err(Error::InvalidDimension); } + tokens.min(64).checked_mul(409600 + 51200) + .and_then(|bytes| bytes.checked_add(3_645_440 + 819_200 + 8192)) + // Genuine pooled flatten + end readback bytes/F32 + driver upload + // staging may coexist; persistent canonical pages stay separately + // admitted by the model owner. Construction/directory/attention + // readback temporaries also remain within this request charge. + .and_then(|bytes| bytes.checked_add(4 * 33_556_992 + 4 * 1024 * 1024)) + // Whole native router/shared host staging, route readback and the + // complete combined-output bytes/F32/row copies coexist with GR. + .and_then(|bytes| bytes.checked_add(tokens.min(64) * 50_000 + 8192)) + .ok_or(Error::Overflow) + } + pub(in crate::qwen_forward) fn begin( + session: &'session mut QwenSession<'driver>, + binding: &ModelBinding, + tokens: &[TokenId], + known_next: Option, + host_remaining: usize, + ) -> Result { + Self::begin_bounded(session, binding, tokens, known_next, host_remaining, false) + } + /// Private experimental admission. Normal serving's begin still caps64. + pub(in crate::qwen_forward) fn begin_windowed256( + session: &'session mut QwenSession<'driver>, + binding: &ModelBinding, + tokens: &[TokenId], + known_next: Option, + host_remaining: usize, + ) -> Result { + Self::begin_bounded( + session, + binding, + tokens, + known_next, + host_remaining.min(512 * 1024 * 1024), + true, + ) + } + pub(in super::super) fn begin_bounded( + session: &'session mut QwenSession<'driver>, + binding: &ModelBinding, + tokens: &[TokenId], + known_next: Option, + host_remaining: usize, + windowed: bool, + ) -> Result { + let limit = if windowed { 256 } else { 64 }; + let origin = session.target_origin()?; + if !session.binding.matches(&binding.identity()) + || session.layer_count != 48 + || tokens.is_empty() + || tokens.len() > limit + { + return Err(Error::InvalidDimension); + } + let end = session + .next_position + .checked_add(tokens.len() as u64) + .ok_or(Error::Overflow)?; + let context_bound = Dimension::new(u64::from(binding.input_constants().context_length()))?; + if end >= u64::from(context_bound.get()) || end >= crate::qwen_forward::contract::serving_cells() { + return Err(Error::InvalidPosition); + } + let vocab = Dimension::new(248320)?; + for token in tokens.iter().copied().chain(known_next) { + if token != TokenId::new(u64::from(token.get()), vocab)? { + return Err(Error::InvalidToken); + } + } + let charge = if windowed { + host_charge_bounded(tokens.len(), end, 256)? + } else { + host_charge(tokens.len(), end)? + }; + if charge > host_remaining { + return Err(Error::InputAllocation); + } + let context = session.mtp_context()?; + if context + .allocated_bytes() + .checked_add(128 * 1024 * 1024) + .is_none_or(|n| n > context.budget_bytes()) + { + return Err(Error::InputAllocation); + } + let mut rows = Vec::new(); + rows.try_reserve_exact(tokens.len()) + .map_err(|_| Error::InputAllocation)?; + let mut witnesses = Vec::new(); + witnesses + .try_reserve_exact(tokens.len()) + .map_err(|_| Error::InputAllocation)?; + let mut predecessors = session.predecessors; + for (index, token) in tokens.iter().copied().enumerate() { + let position = Position::new(session.next_position + index as u64, context_bound)?; + rows.push(Row { + token, + position, + predecessors, + input: None, + completed: 0, + }); + predecessors = [ + predecessors[1], + i32::try_from(token.get()).map_err(|_| Error::InvalidToken)?, + ]; + } + Ok(Self { + verification: None, + next_ple: session.ple_state.clone(), + next_gdn: session.gdn_states.clone(), + gdn_chunk: None, + next_qsa: session.qsa_states.clone(), + session, + origin, + chunk: Rc::new(()), + rows, + witnesses, + next_layer: 0, + next_row: 0, + batch_layer: None, + batch_rows: Vec::new(), + batch_completed: 0, + attention_layer: None, + attention_next: 0, + attention_sources: Vec::new(), + attention_authorized: None, + known_next, + output: None, + finished: false, + aborted: false, + end, + windowed, + micro_cursor: 0, + active_micro: None, + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + test_micro_width: 64, + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + test_window_journal: Vec::new(), + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + test_partial_words: 0, + }) + } + pub(in super::super) fn check(&self) -> Result<()> { + self.origin.validate(self.session)?; + if self.aborted { + return Err(Error::Unsupported(Stage::Session)); + } + Ok(()) + } + /// Phase belongs to this live transaction's actual verification journal. + /// Row count, window width and caller policy cannot mint this distinction. + pub(in crate::qwen_forward) fn is_mtp_verification(&self) -> Result { + self.check()?; + Ok(self.verification.is_some()) + } + pub(in super::super) fn phase_span(&self) -> Result<(usize, usize)> { + self.check()?; + if !self.windowed { + return Ok((0, self.rows.len())); + } + let active = self.active_micro.as_ref().ok_or(Error::IdentityMismatch)?; + if active.layer.get() != self.next_layer + || active.first != self.micro_cursor + || active.end <= active.first + || active.end - active.first > 64 + || active.end > self.rows.len() + { + return Err(Error::IdentityMismatch); + } + Ok((active.first, active.end)) + } + pub(in super::super) fn window_proof(&self) -> Option> { + self.active_micro.as_ref().map(|a| Rc::clone(&a.proof)) + } + pub(in super::super) fn validate_window_proof(&self, proof: &Option>) -> Result<()> { + self.phase_span()?; + match (self.active_micro.as_ref(), proof) { + (None, None) if !self.windowed => Ok(()), + (Some(active), Some(proof)) if Rc::ptr_eq(&active.proof, proof) => Ok(()), + _ => Err(Error::IdentityMismatch), + } + } + /// Closed adapters receive a local kernel column, then obtain its actual + /// global row from the current transaction's active range. + pub(in crate::qwen_forward) fn micro_row_index(&self, local: usize) -> Result { + let (first, end) = self.phase_span()?; + let index = first.checked_add(local).ok_or(Error::Overflow)?; + if index >= end { + return Err(Error::IdentityMismatch); + } + Ok(index) + } + pub(in crate::qwen_forward) fn micro_len(&self) -> Result { + let (first, end) = self.phase_span()?; + Ok(end - first) + } + pub(in crate::qwen_forward) fn warm_row_limit(&self) -> usize { + if self.windowed { 256 } else { 64 } + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_2_2.rs b/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_2_2.rs new file mode 100644 index 00000000..9cba3af9 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_2_2.rs @@ -0,0 +1,258 @@ +//! Moved out of the parent module by STRA-338: impl QwenChunkTxn (2). + +#[allow(unused_imports)] +use super::*; + + + +impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { + pub(in crate::qwen_forward) fn open_micro_window( + &mut self, + layer: LayerId, + ) -> Result { + self.check()?; + if self + .gdn_chunk + .as_ref() + .is_some_and(|journal| journal.start.0.layer != layer) + { + return Err(Error::IdentityMismatch); + } + if !self.windowed + || self.finished + || self.active_micro.is_some() + || self.next_layer != layer.get() + || layer.get() >= 48 + || self.micro_cursor >= self.rows.len() + || self.next_row != self.micro_cursor + || self.attention_next != self.micro_cursor + || self.batch_layer.is_some() + || self.attention_layer.is_some() + || !self.batch_rows.is_empty() + || !self.attention_sources.is_empty() + || self.attention_authorized.is_some() + || self.rows.iter().any(|r| r.input.is_none()) + { + return Err(Error::IdentityMismatch); + } + let first = self.micro_cursor; + let width = 64; + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + let width = self.test_micro_width; + if !(1..=64).contains(&width) { + return Err(Error::IdentityMismatch); + } + let end = first + .checked_add(width) + .ok_or(Error::Overflow)? + .min(self.rows.len()); + if self.rows[first..end] + .iter() + .any(|r| r.completed != layer.get()) + { + return Err(Error::IdentityMismatch); + } + let proof = Rc::new(()); + self.active_micro = Some(ActiveMicroWindow { + proof: Rc::clone(&proof), + layer, + first, + end, + }); + Ok(ChunkMicroWindow { + chunk: Rc::clone(&self.chunk), + proof, + layer, + first, + end, + }) + } + /// Consumes the exact minted capability; no next range can open early. + pub(in crate::qwen_forward) fn close_micro_window( + &mut self, + window: ChunkMicroWindow, + ) -> Result<()> { + let (first, end) = self.phase_span()?; + let active = self.active_micro.as_ref().ok_or(Error::IdentityMismatch)?; + if !Rc::ptr_eq(&self.chunk, &window.chunk) + || !Rc::ptr_eq(&active.proof, &window.proof) + || window.first != first + || window.end != end + || window.layer != active.layer + || self.next_row != end + || self.attention_next != end + || self.batch_layer.is_some() + || self.attention_layer.is_some() + || !self.batch_rows.is_empty() + || !self.attention_sources.is_empty() + || self.attention_authorized.is_some() + || self.rows[first..end] + .iter() + .any(|r| r.completed != self.next_layer + 1) + { + return Err(Error::IdentityMismatch); + } + if let Some(journal) = &self.gdn_chunk + && (journal.start.0.layer != window.layer || journal.accepted != end) + { + self.aborted = true; + return Err(Error::IdentityMismatch); + } + // Validate the all-outer barrier before changing any phase cursor. + if end == self.rows.len() && self.rows.iter().any(|r| r.completed != self.next_layer + 1) { + self.aborted = true; + return Err(Error::IdentityMismatch); + } + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + { + self.test_window_journal + .try_reserve(1) + .map_err(|_| Error::InputAllocation)?; + // The tuple is observed only after genuine finite completion and + // all capability checks, before the infallible cursor transition. + self.test_window_journal.push((self.next_layer, first, end)); + } + self.active_micro = None; + self.micro_cursor = end; + if end == self.rows.len() { + self.next_layer += 1; + self.micro_cursor = 0; + self.next_row = 0; + self.attention_next = 0; + } + Ok(()) + } + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in crate::qwen_forward) fn test_use_micro2(&mut self) -> Result<()> { + self.check()?; + if !self.windowed + || self.len() != 4 + || self.next_layer != 0 + || self.next_row != 0 + || self.active_micro.is_some() + || self.rows.iter().any(|r| r.input.is_some()) + { + return Err(Error::IdentityMismatch); + } + self.test_micro_width = 2; + Ok(()) + } + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in crate::qwen_forward) fn test_window_journal(&self) -> &[(u32, usize, usize)] { + &self.test_window_journal + } + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in crate::qwen_forward) fn test_observe_first_layer( + &mut self, + residuals: &[Option], + ) -> Result<()> { + self.check()?; + if !self.windowed + || self.next_layer != 1 + || self.next_row != 0 + || self.finished + || !self.witnesses.is_empty() + || self.active_micro.is_some() + || residuals.len() != self.len() + || self.rows.iter().any(|r| r.completed != 1) + { + return Err(Error::IdentityMismatch); + } + let layer = LayerId::new(0, Dimension::new(48)?)?; + let mut words = 0usize; + for (index, residual) in residuals.iter().enumerate() { + let residual = residual.as_ref().ok_or(Error::IdentityMismatch)?; + residual.validate_origin(&self.session.binding, GrRole::Ffn(0))?; + let (token, position) = self.row_ids(index)?; + residual.identity().validate(token, position, layer)?; + if residual.streams().len() != 10240 + || residual.streams().iter().any(|v| !v.is_finite()) + { + return Err(Error::NonFinite); + } + words = words + .checked_add(residual.streams().len()) + .ok_or(Error::Overflow)?; + } + let end = Position::new(self.end, crate::qwen_forward::contract::position_dimension())?; + if self.session.gdn_layers[0] { + self.next_gdn[0] + .as_ref() + .ok_or(Error::IdentityMismatch)? + .validate(&self.session.binding, &self.session.gdn_owner, layer, end)?; + } else if self.session.qsa_layers[0] { + self.next_qsa[0] + .as_ref() + .ok_or(Error::IdentityMismatch)? + .validate(&self.session.binding, &self.session.qsa_owner, layer, end)?; + } else { + return Err(Error::InvalidLayer); + } + self.test_partial_words = words; + Ok(()) + } + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in crate::qwen_forward) fn test_partial_words(&self) -> usize { + self.test_partial_words + } + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in crate::qwen_forward) fn test_publication_preflight_refused(&self) -> bool { + matches!( + self.validate_publish(), + Err(Error::Unsupported(Stage::Executor)) + ) + } + pub(in crate::qwen_forward) fn context(&self) -> Result<&Context<'driver>> { + self.check()?; + self.session.mtp_context() + } + /// The genuine rolling state at this prompt micro's first causal row. + /// Store an actual initial empty owner once; later validation compares the + /// same Rc state, not a reconstructed position or a batch's final state. + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in crate::qwen_forward) fn prompt_qsa_prior(&mut self, layer: LayerId) -> Result { + let (first, end) = self.phase_span()?; + let slot = layer.get() as usize; + if slot >= STATE_CAPACITY || !self.session.qsa_layers[slot] + || self.next_layer != layer.get() || self.next_row != first + || self.attention_layer != Some(layer) || self.attention_next != end + || self.batch_layer.is_some() || self.attention_authorized.is_some() + { return Err(Error::IdentityMismatch); } + let position = self.rows.get(first).ok_or(Error::InvalidPosition)?.position; + if self.next_qsa[slot].is_none() { + if position.get() != 0 { return Err(Error::IdentityMismatch); } + self.next_qsa[slot] = Some(QsaIndexPrior::empty( + self.session.binding.clone(), &self.session.qsa_owner, layer, + )?); + } + let prior = self.next_qsa[slot].as_ref().ok_or(Error::IdentityMismatch)?; + prior.validate(&self.session.binding, &self.session.qsa_owner, layer, position)?; + Ok(prior.clone()) + } + /// Bind the initial canonical INT8 state to the actual model-owned KV bank. + /// Existing FP16 state cannot be relabeled after a mode switch. + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in crate::qwen_forward) fn prompt_native_qsa_prior( + &mut self, layer: LayerId, kv: &leleka_cuda_driver::QsaPromptKv<'_>, + ) -> Result { + let (first, end) = self.phase_span()?; + let slot = layer.get() as usize; + if slot >= STATE_CAPACITY || !self.session.qsa_layers[slot] + || self.next_layer != layer.get() || self.next_row != first + || self.attention_layer != Some(layer) || self.attention_next != end + || self.batch_layer.is_some() || self.attention_authorized.is_some() + { return Err(Error::IdentityMismatch); } + kv.validate_context(self.session.mtp_context()?).map_err(super::super::super::super::qsa_index::driver_error)?; + let position = self.rows.get(first).ok_or(Error::InvalidPosition)?.position; + if self.next_qsa[slot].is_none() { + if position.get() != 0 { return Err(Error::IdentityMismatch); } + self.next_qsa[slot] = Some(QsaIndexPrior::empty_native( + self.session.binding.clone(), &self.session.qsa_owner, layer, kv, + )?); + } + let prior = self.next_qsa[slot].as_ref().ok_or(Error::IdentityMismatch)?; + prior.validate(&self.session.binding, &self.session.qsa_owner, layer, position)?; + prior.native_snapshot(kv)?; + Ok(prior.clone()) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_3.rs b/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_3.rs new file mode 100644 index 00000000..7495935e --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_3.rs @@ -0,0 +1,239 @@ +//! Moved out of the parent module by STRA-338: impl QwenChunkTxn (3). + +#[allow(unused_imports)] +use super::*; + + + +impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in crate::qwen_forward) fn validate_prompt_qsa_prior( + &self, layer: LayerId, prior: &QsaIndexPrior, + ) -> Result<()> { + let (first, end) = self.phase_span()?; + let slot = layer.get() as usize; + if slot >= STATE_CAPACITY || !self.session.qsa_layers[slot] + || self.next_layer != layer.get() || self.next_row != first + || self.attention_layer != Some(layer) || self.attention_next != end + || self.batch_layer.is_some() || self.attention_authorized.is_some() + || self.next_qsa[slot].as_ref().is_none_or(|actual| !actual.same_state(prior)) + { return Err(Error::IdentityMismatch); } + let position = self.rows.get(first).ok_or(Error::InvalidPosition)?.position; + prior.validate(&self.session.binding, &self.session.qsa_owner, layer, position) + } + pub(in crate::qwen_forward) fn original_session(&self) -> Result<&QwenSession<'driver>> { + self.check()?; + Ok(self.session) + } + pub(in crate::qwen_forward) fn rows(&self) -> &[ChunkRowResidual] { + &self.witnesses + } + pub(in crate::qwen_forward) fn start_position(&self) -> u64 { + self.session.next_position + } + pub(in crate::qwen_forward) fn end_position(&self) -> u64 { + self.end + } + pub(in crate::qwen_forward) fn with_mtp_row( + &mut self, + witness: &ChunkRowResidual, + execute: impl FnOnce( + &mut QwenSession<'driver>, + Position, + TokenId, + &[f32], + TargetStepOrigin, + ) -> Result<()>, + ) -> Result<()> { + let (_, position, next, streams) = self.validate_row(witness)?; + let next = next.ok_or(Error::Unsupported(Stage::Executor))?; + let origin = self.origin.clone(); + let result = execute(self.session, position, next, streams, origin); + if let Err(error) = result { + self.session.note_mtp_failure(&error); + self.aborted = true; + return Err(error); + } + self.validate_row(witness)?; + Ok(()) + } + pub(in crate::qwen_forward) fn validate_row<'a>( + &self, + witness: &'a ChunkRowResidual, + ) -> Result<(TokenId, Position, Option, &'a [f32])> { + self.check()?; + if self.gdn_chunk.is_some() + || !self.finished + || !witness.binding.matches(&self.session.binding) + || !Rc::ptr_eq(&witness.chunk, &self.chunk) + || !witness.origin.same_prefix(&self.origin) + { + return Err(Error::IdentityMismatch); + } + witness.origin.validate(self.session)?; + let index = usize::try_from( + witness + .position + .get() + .checked_sub(self.session.next_position) + .ok_or(Error::InvalidPosition)?, + ) + .map_err(|_| Error::Overflow)?; + let row = self.rows.get(index).ok_or(Error::InvalidPosition)?; + let expected_next = self + .rows + .get(index + 1) + .map(|r| r.token) + .or(self.known_next); + if row.token != witness.token + || row.position != witness.position + || row.completed != 48 + || witness.known_next != expected_next + || witness.streams.len() != 10240 + || witness.streams.iter().any(|v| !v.is_finite()) + { + return Err(Error::IdentityMismatch); + } + Ok(( + witness.token, + witness.position, + witness.known_next, + witness.streams.as_ref(), + )) + } + pub(in crate::qwen_forward) fn row_ids(&self, index: usize) -> Result<(TokenId, Position)> { + self.check()?; + let row = self.rows.get(index).ok_or(Error::InvalidPosition)?; + Ok((row.token, row.position)) + } + pub(in crate::qwen_forward) fn len(&self) -> usize { + self.rows.len() + } + + pub(in crate::qwen_forward) fn begin_gdn_chunk( + &mut self, + layer: LayerId, + ) -> Result { + self.check()?; + let slot = layer.get() as usize; + if !self.windowed + || self.gdn_chunk.is_some() + || self.active_micro.is_some() + || self.next_layer != layer.get() + || self.next_row != 0 + || self.micro_cursor != 0 + || slot >= 48 + || !self.session.gdn_layers[slot] + || self.rows.iter().any(|row| row.completed != layer.get()) + { + return Err(Error::IdentityMismatch); + } + let first = self.rows.first().ok_or(Error::InvalidPosition)?.position; + let prior = match &self.next_gdn[slot] { + Some(prior) => prior.clone(), + None if first.get() == 0 => { + GdnPrior::zero(self.session.binding.clone(), &self.session.gdn_owner, layer)? + } + None => return Err(Error::IdentityMismatch), + }; + prior.validate(&self.session.binding, &self.session.gdn_owner, layer, first)?; + let start = GdnChunkStart(Rc::new(GdnChunkAnchor { + binding: self.session.binding.clone(), + chunk: self.chunk.clone(), + prior, + layer, + first, + end: self.end, + count: self.rows.len(), + })); + start.validate_binding(&self.session.binding)?; + self.gdn_chunk = Some(GdnChunkJournal { + start: start.clone(), + accepted: 0, + }); + Ok(start) + } + pub(in crate::qwen_forward) fn finish_gdn_chunk<'ctx>( + &mut self, + owner: super::super::super::super::gdn::chunk_device::GdnChunkDevice<'ctx>, + binding: &ModelBinding, + cache: &super::super::super::super::dense_weight_cache::DenseWeightCache<'ctx>, + ) -> Result<()> { + self.check()?; + let journal = self.gdn_chunk.as_ref().ok_or(Error::IdentityMismatch)?; + let layer = journal.start.0.layer; + if !Rc::ptr_eq(&self.chunk, &journal.start.0.chunk) + || self.active_micro.is_some() + || self.micro_cursor != 0 + || self.next_row != 0 + || self.next_layer != layer.get() + 1 + || journal.accepted != self.rows.len() + || self.batch_layer.is_some() + || self.attention_layer.is_some() + || self.attention_authorized.is_some() + || self.rows.iter().any(|row| row.completed != layer.get() + 1) + { + self.aborted = true; + return Err(Error::IdentityMismatch); + } + let seal = GdnChunkSeal { + start: journal.start.clone(), + }; + if owner.is_verification() { + let result=owner.finish_verification(seal,binding,cache); + if let Err(error)=&result{self.session.note_mtp_failure(error);self.aborted=true;} + result?;self.gdn_chunk=None;return Ok(()); + } + let result = owner.finish(seal, binding, cache).and_then(|prior| { + prior.validate( + &self.session.binding, + &self.session.gdn_owner, + layer, + Position::new(self.end, crate::qwen_forward::contract::position_dimension())?, + )?; + Ok(prior) + }); + match result { + Ok(prior) => { + self.next_gdn[layer.get() as usize] = Some(prior); + self.gdn_chunk = None; + Ok(()) + } + Err(error) => { + self.session.note_mtp_failure(&error); + self.aborted = true; + Err(error) + } + } + } + // Ephemeral, private stage view: shares real binding/Context/state owners, + // never publishes or mints a TargetStepOrigin. Its unused layer states + // may have different positions; only the current causal layer is consumed. + pub(in super::super) fn stage_view(&self, index: usize) -> Result> { + self.check()?; + let row = self.rows.get(index).ok_or(Error::InvalidPosition)?; + Ok(QwenSession { + binding: self.session.binding.clone(), + owner: Rc::clone(&self.session.owner), + owner_thread: self.session.owner_thread, + predecessors: row.predecessors, + next_position: row.position.get(), + cuda: self.session.cuda.clone(), + checkpoint_generation: self.session.checkpoint_generation, + cuda_failed: false, + layer_count: self.session.layer_count, + ple_required: self.session.ple_required, + ple_owner: self.session.ple_owner.clone(), + ple_state: self.next_ple.clone(), + gdn_layers: self.session.gdn_layers, + gdn_owner: self.session.gdn_owner.clone(), + gdn_states: self.next_gdn.clone(), + qsa_layers: self.session.qsa_layers, + qsa_owner: self.session.qsa_owner.clone(), + qsa_states: self.next_qsa.clone(), + state_lag: None, + #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] + resident_qsa_states:self.session.resident_qsa_states.clone(), + }) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_4.rs b/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_4.rs new file mode 100644 index 00000000..2e89b3f5 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_4.rs @@ -0,0 +1,202 @@ +//! Moved out of the parent module by STRA-338: impl QwenChunkTxn (4). + +#[allow(unused_imports)] +use super::*; + + + +impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { + pub(in crate::qwen_forward) fn input( + &mut self, + index: usize, + execute: impl FnOnce(&mut QwenStepTxn<'_, 'driver>) -> Result, + ) -> Result<()> { + if self.next_layer != 0 + || self.next_row != 0 + || self.rows.get(index).is_none_or(|r| r.input.is_some()) + { + return Err(Error::IdentityMismatch); + } + let mut view = self.stage_view(index)?; + let row = &self.rows[index]; + let mut step = view.begin(row.token, row.position)?; + let result = execute(&mut step).and_then(|input| step.stage_input(input)); + match result { + Ok(input) => { + self.rows[index].input = Some(input); + Ok(()) + } + Err(error) => { + self.session.note_mtp_failure(&error); + self.aborted = true; + Err(error) + } + } + } + /// Read immutable PLE inputs from the actual current layer-one window. + /// This grants no pending history and advances no causal cursor. The + /// batch producer still has to complete; chronological consumption below + /// validates each pending history against the genuine rolling prior. + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in crate::qwen_forward) fn prepare_ple_micro_inputs( + &mut self, + layer: LayerId, + mut prepare: impl FnMut(usize, &QwenStepTxn<'_, 'driver>) -> Result, + ) -> Result<(PlePrior, Vec)> { + let (first, end) = self.phase_span()?; + if layer.get() != 1 || self.next_layer != 1 + || self.next_row != first || self.attention_next != first + || self.batch_layer.is_some() || self.attention_layer.is_some() + || self.device_gdn_lease()?.is_some() + || !(1..=64).contains(&(end - first)) + || self.rows[first..end].iter().any(|row| row.completed != 1) + { + return Err(Error::IdentityMismatch); + } + let result = (|| { + let prior = self.next_ple.clone().ok_or(Error::Unsupported(Stage::Input))?; + if prior.next_position() != self.rows[first].position.get() { + return Err(Error::IdentityMismatch); + } + let mut inputs = Vec::new(); + inputs.try_reserve_exact(end-first).map_err(|_| Error::InputAllocation)?; + for index in first..end { + let mut view = self.stage_view(index)?; + let row = &self.rows[index]; + let mut step = view.begin(row.token, row.position)?; + step.input = Some(row.input.clone().ok_or(Error::Unsupported(Stage::Input))?); + step.completed_layers = row.completed; + if index == first { step.validate_ple_prior(&prior)?; } + inputs.push(prepare(index, &step)?); + } + Ok((prior, inputs)) + })(); + if let Err(error) = &result { + self.session.note_mtp_failure(error); + self.aborted = true; + } + result + } + /// Prepare one genuine micro-window chronologically, then complete its GR + /// reads as one device batch. PLE remains causal: each real pending history + /// is admitted before preparing the following position. None of the GR row + /// capabilities is published until the entire actual batch has completed. + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in crate::qwen_forward) fn read_attention_micro( + &mut self, + layer: LayerId, + mut prepare: impl FnMut( + usize, + &mut QwenStepTxn<'_, 'driver>, + ) -> Result, + execute: impl FnOnce( + Vec, + ) -> Result>, + ) -> Result> { + let (first, end) = self.phase_span()?; + if layer.get() != self.next_layer + || layer.get() >= 48 + || self.next_row != first + || self.attention_next != first + || self.batch_layer.is_some() + || self.attention_layer.is_some_and(|old| old != layer) + || !(1..=64).contains(&(end - first)) + || self.rows[first..end] + .iter() + .any(|row| row.completed != layer.get()) + { + return Err(Error::IdentityMismatch); + } + let result = (|| { + if self.attention_layer.is_none() { + self.attention_sources + .try_reserve_exact(self.rows.len()) + .map_err(|_| Error::InputAllocation)?; + self.attention_sources.resize_with(self.rows.len(), || None); + self.attention_layer = Some(layer); + } + if self.attention_sources.len() != self.rows.len() + || self.attention_sources[first..end].iter().any(Option::is_some) + { + return Err(Error::IdentityMismatch); + } + let mut inputs = Vec::new(); + inputs + .try_reserve_exact(end - first) + .map_err(|_| Error::InputAllocation)?; + for index in first..end { + if self.attention_next != index { + return Err(Error::IdentityMismatch); + } + let mut view = self.stage_view(index)?; + let row = &self.rows[index]; + let token = row.token; + let position = row.position; + let mut step = view.begin(token, position)?; + step.input = Some(row.input.clone().ok_or(Error::Unsupported(Stage::Input))?); + step.completed_layers = row.completed; + let input = prepare(index, &mut step)?; + input.validate_origin(&self.session.binding, GrRole::Attention(layer.get()))?; + input.identity().validate(token, position, layer)?; + if layer.get() == 1 && self.session.ple_required { + let next = step + .ple_pending + .take() + .ok_or(Error::Unsupported(Stage::Input))? + .into_prior(); + if next.next_position() != position.get() + 1 { + return Err(Error::IdentityMismatch); + } + self.next_ple = Some(next); + self.record_verification_ple(index, position)?; + } else if step.ple_pending.is_some() { + return Err(Error::IdentityMismatch); + } + if step.gdn_pending.iter().any(Option::is_some) + || step.qsa_pending.iter().any(Option::is_some) + { + return Err(Error::IdentityMismatch); + } + inputs.push(input); + self.attention_next += 1; + } + let reads = execute(inputs)?; + if reads.len() != end - first || self.attention_next != end { + return Err(Error::IdentityMismatch); + } + // Validate every completed producer before publishing even the + // first row. Token/position/role come from this actual transaction. + for (row, read) in self.rows[first..end].iter().zip(&reads) { + read.ready() + .validate_origin(&self.session.binding, GrRole::Attention(layer.get()))?; + read.ready().identity().validate(row.token, row.position, layer)?; + } + let mut completed = Vec::new(); + completed + .try_reserve_exact(reads.len()) + .map_err(|_| Error::InputAllocation)?; + for (index, read) in (first..end).zip(reads) { + let proof = Rc::new(()); + let read = Rc::new(read); + self.attention_sources[index] = Some(AttentionSource { + proof: Rc::clone(&proof), + read: Rc::clone(&read), + }); + completed.push(ChunkAttentionRow { + chunk: Rc::clone(&self.chunk), + proof, + index, + layer, + read, + window: self.window_proof(), + }); + } + Ok(completed) + })(); + if let Err(error) = &result { + self.session.note_mtp_failure(error); + self.aborted = true; + } + result + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_5.rs b/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_5.rs new file mode 100644 index 00000000..44efe093 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_5.rs @@ -0,0 +1,249 @@ +//! Moved out of the parent module by STRA-338: impl QwenChunkTxn (5). + +#[allow(unused_imports)] +use super::*; + + + +impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { + pub(in crate::qwen_forward) fn read_attention_column( + &mut self, + index: usize, + layer: LayerId, + execute: impl FnOnce(&mut QwenStepTxn<'_, 'driver>) -> Result, + ) -> Result { + let (first, end) = self.phase_span()?; + if layer.get() != self.next_layer + || layer.get() >= 48 + || self.next_row != first + || index < first + || index >= end + || self.batch_layer.is_some() + || index != self.attention_next + || self.attention_layer.is_some_and(|old| old != layer) + || self + .rows + .get(index) + .is_none_or(|row| row.completed != layer.get()) + { + return Err(Error::IdentityMismatch); + } + if self.attention_layer.is_none() { + self.attention_sources + .try_reserve_exact(self.rows.len()) + .map_err(|_| Error::InputAllocation)?; + self.attention_sources.resize_with(self.rows.len(), || None); + self.attention_layer = Some(layer); + } + let mut view = self.stage_view(index)?; + let row = &self.rows[index]; + let position = row.position; + let mut step = view.begin(row.token, row.position)?; + step.input = Some(row.input.clone().ok_or(Error::Unsupported(Stage::Input))?); + step.completed_layers = row.completed; + let result = execute(&mut step).and_then(|read| { + read.ready() + .validate_origin(&self.session.binding, GrRole::Attention(layer.get()))?; + read.ready() + .identity() + .validate(step.token(), position, layer)?; + if layer.get() == 1 && self.session.ple_required { + let next = step + .ple_pending + .take() + .ok_or(Error::Unsupported(Stage::Input))? + .into_prior(); + if next.next_position() != position.get() + 1 { + return Err(Error::IdentityMismatch); + } + self.next_ple = Some(next); + self.record_verification_ple(index, position)?; + } else if step.ple_pending.is_some() { + return Err(Error::IdentityMismatch); + } + if step.gdn_pending.iter().any(Option::is_some) + || step.qsa_pending.iter().any(Option::is_some) + { + return Err(Error::IdentityMismatch); + } + Ok(read) + }); + match result { + Ok(read) => { + let proof = Rc::new(()); + let read = Rc::new(read); + self.attention_sources[index] = Some(AttentionSource { + proof: Rc::clone(&proof), + read: Rc::clone(&read), + }); + self.attention_next += 1; + Ok(ChunkAttentionRow { + chunk: Rc::clone(&self.chunk), + proof, + index, + layer, + read, + window: self.window_proof(), + }) + } + Err(error) => { + self.session.note_mtp_failure(&error); + self.aborted = true; + Err(error) + } + } + } + pub(in crate::qwen_forward) fn validate_attention_input( + &self, + index: usize, + layer: LayerId, + ready: &super::super::super::super::gr::ResidualReady, + ) -> Result<()> { + let (first, end) = self.phase_span()?; + if index < first + || index >= end + || self.attention_layer != Some(layer) + || self.attention_next != end + { + return Err(Error::IdentityMismatch); + } + let source = self + .attention_sources + .get(index) + .and_then(Option::as_ref) + .ok_or(Error::IdentityMismatch)?; + if !std::ptr::eq(source.read.ready(), ready) { + return Err(Error::IdentityMismatch); + } + ready.validate_origin(&self.session.binding, GrRole::Attention(layer.get()))?; + let (token, position) = self.row_ids(index)?; + ready.identity().validate(token, position, layer) + } + pub(in crate::qwen_forward) fn validate_attention_column( + &self, + index: usize, + layer: LayerId, + read: &ChunkAttentionRow, + ) -> Result<()> { + self.validate_attention_input(index, layer, read.ready())?; + self.validate_window_proof(&read.window)?; + let source = self.attention_sources[index] + .as_ref() + .ok_or(Error::IdentityMismatch)?; + if !Rc::ptr_eq(&self.chunk, &read.chunk) + || !Rc::ptr_eq(&source.proof, &read.proof) + || !Rc::ptr_eq(&source.read, &read.read) + || read.index != index + || read.layer != layer + { + return Err(Error::IdentityMismatch); + } + Ok(()) + } + pub(in crate::qwen_forward) fn prepare_attention_layer_batch( + &mut self, + index: usize, + layer: LayerId, + read: &ChunkAttentionRow, + execute: impl FnOnce( + &mut QwenStepTxn<'_, 'driver>, + &super::super::super::super::gr::DetachedGrRead, + ) -> Result, + ) -> Result<(T, PreparedLayerRow)> { + self.validate_attention_input(index, layer, read.ready())?; + self.validate_window_proof(&read.window)?; + let source = self.attention_sources[index] + .as_ref() + .ok_or(Error::IdentityMismatch)?; + if !Rc::ptr_eq(&self.chunk, &read.chunk) + || !Rc::ptr_eq(&source.proof, &read.proof) + || !Rc::ptr_eq(&source.read, &read.read) + || read.index != index + || read.layer != layer + || self.attention_authorized.is_some() + { + return Err(Error::IdentityMismatch); + } + self.attention_authorized = Some(index); + let result = self.prepare_layer_batch(index, layer, |step| execute(step, &read.read)); + self.attention_authorized = None; + if result.is_ok() { + self.attention_sources[index] = None; + } + result + } + pub(in crate::qwen_forward) fn prepare_attention_ffn( + &mut self, + index: usize, + layer: LayerId, + read: &ChunkAttentionRow, + execute: impl FnOnce( + &mut QwenStepTxn<'_, 'driver>, + &super::super::super::super::gr::DetachedGrRead, + ) -> Result, + ) -> Result { + let (row, proof) = self.prepare_attention_layer_batch(index, layer, read, execute)?; + row.validate( + &self.session.binding, + self.rows[index].token, + self.rows[index].position, + layer, + )?; + Ok(ChunkFfnRow { proof, row }) + } + pub(in crate::qwen_forward) fn prepare_attention_ffn_device_gdn( + &mut self, + index: usize, + layer: LayerId, + read: &ChunkAttentionRow, + execute: impl FnOnce( + &mut QwenStepTxn<'_, 'driver>, + &super::super::super::super::gr::DetachedGrRead, + GdnChunkRow, + ) -> Result<( + super::super::super::super::moe_expert::PreparedMoeRow, + super::super::super::super::gdn::chunk_device::ChunkEdge, + )>, + ) -> Result { + self.validate_attention_input(index, layer, read.ready())?; + self.validate_window_proof(&read.window)?; + let source = self.attention_sources[index] + .as_ref() + .ok_or(Error::IdentityMismatch)?; + let journal = self.gdn_chunk.as_ref().ok_or(Error::IdentityMismatch)?; + if !Rc::ptr_eq(&self.chunk, &read.chunk) + || !Rc::ptr_eq(&source.proof, &read.proof) + || !Rc::ptr_eq(&source.read, &read.read) + || read.index != index + || read.layer != layer + || self.attention_authorized.is_some() + || journal.accepted != index + { + return Err(Error::IdentityMismatch); + } + let actual = &self.rows[index]; + let row = GdnChunkRow { + start: journal.start.clone(), + index, + identity: TokenLayer::new(actual.token, actual.position, layer), + proof: source.proof.clone(), + window: read.window.clone(), + key: Rc::new(()), + }; + row.validate(&journal.start, index, &self.session.binding)?; + self.attention_authorized = Some(index); + let result = self.prepare_layer_batch_internal(index, layer, |step| { + execute(step, &read.read, row).map(|(v, e)| (v, Some(e))) + }); + self.attention_authorized = None; + let (row, proof) = result?; + self.attention_sources[index] = None; + row.validate( + &self.session.binding, + self.rows[index].token, + self.rows[index].position, + layer, + )?; + Ok(ChunkFfnRow { proof, row }) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_6.rs b/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_6.rs new file mode 100644 index 00000000..d09d02ff --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_6.rs @@ -0,0 +1,224 @@ +//! Moved out of the parent module by STRA-338: impl QwenChunkTxn (6). + +#[allow(unused_imports)] +use super::*; + + + +impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { + /// The device attention edge is genuine, but independent FFN GR reads may + /// be completed after collecting all causal attention rows of this window. + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in crate::qwen_forward) fn prepare_attention_device_gdn( + &mut self, + index: usize, + layer: LayerId, + read: &ChunkAttentionRow, + execute: impl FnOnce( + &mut QwenStepTxn<'_, 'driver>, + &super::super::super::super::gr::DetachedGrRead, + GdnChunkRow, + ) -> Result<(T, super::super::super::super::gdn::chunk_device::ChunkEdge)>, + ) -> Result<(T, PreparedLayerRow)> { + self.validate_attention_input(index, layer, read.ready())?; + self.validate_window_proof(&read.window)?; + let source = self.attention_sources[index] + .as_ref() + .ok_or(Error::IdentityMismatch)?; + let journal = self.gdn_chunk.as_ref().ok_or(Error::IdentityMismatch)?; + if !Rc::ptr_eq(&self.chunk, &read.chunk) + || !Rc::ptr_eq(&source.proof, &read.proof) + || !Rc::ptr_eq(&source.read, &read.read) + || read.index != index + || read.layer != layer + || self.attention_authorized.is_some() + || journal.accepted != index + { + return Err(Error::IdentityMismatch); + } + let actual = &self.rows[index]; + let row = GdnChunkRow { + start: journal.start.clone(), + index, + identity: TokenLayer::new(actual.token, actual.position, layer), + proof: source.proof.clone(), + window: read.window.clone(), + key: Rc::new(()), + }; + row.validate(&journal.start, index, &self.session.binding)?; + self.attention_authorized = Some(index); + let result = self.prepare_layer_batch_internal(index, layer, |step| { + execute(step, &read.read, row).map(|(value, edge)| (value, Some(edge))) + }); + self.attention_authorized = None; + if result.is_ok() { + self.attention_sources[index] = None; + } + result + } + + /// Complete the actual whole prompt GDN window before advancing any row + /// edge. Only genuine per-row products/edges of that completed batch may + /// then enter the ordinary current-transaction journal and GR producer. + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in crate::qwen_forward) fn prepare_attention_micro_gdn( + &mut self, + layer: LayerId, + attention: &[ChunkAttentionRow], + execute: impl FnOnce(&GdnChunkMicro, &Context<'driver>) -> Result>, + mut consume: impl FnMut( + usize, &mut QwenStepTxn<'_, 'driver>, + &super::super::super::super::gr::DetachedGrRead, R, + ) -> Result<(T, super::super::super::super::gdn::chunk_device::ChunkEdge)>, + ) -> Result> { + let (first, end) = self.phase_span()?; + let journal = self.gdn_chunk.as_ref().ok_or(Error::IdentityMismatch)?; + if self.device_gdn_lease()?.is_some() + || self.next_layer != layer.get() + || self.next_row != first + || self.attention_next != end + || self.batch_layer.is_some() + || self.attention_layer != Some(layer) + || self.attention_authorized.is_some() + || journal.accepted != first + || attention.len() != end - first + || !(1..=64).contains(&attention.len()) + { + return Err(Error::IdentityMismatch); + } + let mut micro = GdnChunkMicro { + start: journal.start.clone(), first, rows: Vec::new(), reads: Vec::new(), + }; + micro.rows.try_reserve_exact(attention.len()).map_err(|_| Error::InputAllocation)?; + micro.reads.try_reserve_exact(attention.len()).map_err(|_| Error::InputAllocation)?; + for (local, read) in attention.iter().enumerate() { + let index = first + local; + self.validate_attention_column(index, layer, read)?; + let actual = &self.rows[index]; + micro.rows.push(GdnChunkRow { + start: micro.start.clone(), index, + identity: TokenLayer::new(actual.token, actual.position, layer), + proof: Rc::clone(&read.proof), window: read.window.clone(), key: Rc::new(()), + }); + micro.reads.push(Rc::clone(&read.read)); + } + micro.validate(µ.start, first, &self.session.binding)?; + let result = (|| { + let products = execute(µ, self.session.mtp_context()?)?; + if products.len() != attention.len() { + return Err(Error::IdentityMismatch); + } + let mut completed = Vec::new(); + completed.try_reserve_exact(products.len()).map_err(|_| Error::InputAllocation)?; + for (local, (read, product)) in attention.iter().zip(products).enumerate() { + let index = first + local; + self.validate_attention_column(index, layer, read)?; + if self.gdn_chunk.as_ref().is_none_or(|journal| journal.accepted != index) { + return Err(Error::IdentityMismatch); + } + self.attention_authorized = Some(index); + let prepared = self.prepare_layer_batch_internal(index, layer, |step| { + consume(local, step, &read.read, product) + .map(|(value, edge)| (value, Some(edge))) + }); + self.attention_authorized = None; + completed.push(prepared?); + self.attention_sources[index] = None; + } + Ok(completed) + })(); + if let Err(error) = &result { + self.session.note_mtp_failure(error); + self.aborted = true; + } + result + } + + /// Validate a completed causal row against the actual read it registered. + /// The source has already left attention_sources, so the unique live + /// prepared-row proof carries its original Rc into the later Out batch. + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in crate::qwen_forward) fn validate_prepared_attention_input( + &self, proof: &PreparedLayerRow, + input: &super::super::super::super::gr::ResidualReady, + ) -> Result<()> { + let (first, end) = self.phase_span()?; + self.validate_window_proof(&proof.window)?; + if proof.index < first || proof.index >= end + || self.batch_layer != Some(proof.layer) + || self.next_layer != proof.layer.get() || self.next_row != end + || self.batch_completed != first + || !Rc::ptr_eq(&self.chunk, &proof.chunk) + || self.batch_rows.get(proof.index).and_then(Option::as_ref) + .is_none_or(|stored| !Rc::ptr_eq(stored, &proof.proof)) + { return Err(Error::IdentityMismatch); } + let source = proof.attention_source.as_ref().ok_or(Error::IdentityMismatch)?; + if !std::ptr::eq(source.ready(), input) { + return Err(Error::IdentityMismatch); + } + let actual = self.rows.get(proof.index).ok_or(Error::IdentityMismatch)?; + if actual.completed != proof.layer.get() { return Err(Error::IdentityMismatch); } + input.validate_origin(&self.session.binding, GrRole::Attention(proof.layer.get()))?; + input.identity().validate(actual.token, actual.position, proof.layer) + } + + /// Enlist a fully completed Out row into GR using its real causal proof + /// and current transaction, without advancing attention a second time. + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in crate::qwen_forward) fn prepare_attention_output_after_causal( + &mut self, proof: &PreparedLayerRow, source: &ChunkAttentionRow, + execute: impl FnOnce( + &mut QwenStepTxn<'_, 'driver>, &super::super::super::super::gr::DetachedGrRead, + ) -> Result, + ) -> Result { + self.validate_prepared_attention_input(proof, source.ready())?; + self.validate_window_proof(&source.window)?; + if source.index != proof.index || source.layer != proof.layer + || !Rc::ptr_eq(&self.chunk, &source.chunk) + || proof.attention_source.as_ref() + .is_none_or(|actual| !Rc::ptr_eq(actual, &source.read)) + { return Err(Error::IdentityMismatch); } + let actual = &self.rows[proof.index]; + let token = actual.token; + let position = actual.position; + let result = (|| { + let mut view = self.stage_view(proof.index)?; + let mut step = view.begin(token, position)?; + step.input = Some(actual.input.clone().ok_or(Error::Unsupported(Stage::Input))?); + step.completed_layers = actual.completed; + let output = execute(&mut step, &source.read)?; + if step.ple_pending.is_some() + || step.gdn_pending.iter().any(Option::is_some) + || step.qsa_pending.iter().any(Option::is_some) + { return Err(Error::IdentityMismatch); } + Ok(output) + })(); + if let Err(error) = &result { + self.session.note_mtp_failure(error); self.aborted = true; + } + result + } + + /// Consume the actual prepared attention proof and completed FFN read; + /// reopening a row for routing cannot advance its causal attention twice. + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in crate::qwen_forward) fn validate_prepared_ffn_read( + &self, proof: &PreparedLayerRow, read: &super::super::super::super::gr::DetachedGrRead, + ) -> Result { + let (first, end) = self.phase_span()?; + self.validate_window_proof(&proof.window)?; + if proof.index < first || proof.index >= end + || self.batch_layer != Some(proof.layer) + || self.next_layer != proof.layer.get() || self.next_row != end + || self.batch_completed != first || !Rc::ptr_eq(&self.chunk, &proof.chunk) + || self.batch_rows.get(proof.index).and_then(Option::as_ref) + .is_none_or(|stored| !Rc::ptr_eq(stored, &proof.proof)) + { return Err(Error::IdentityMismatch); } + let actual = &self.rows[proof.index]; + if actual.completed != proof.layer.get() { return Err(Error::IdentityMismatch); } + read.ready().validate_origin(&self.session.binding, GrRole::Ffn(proof.layer.get()))?; + let identity = read.ready().identity(); + identity.validate(actual.token, actual.position, proof.layer)?; + Ok(identity) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_7.rs b/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_7.rs new file mode 100644 index 00000000..f64c618f --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_7.rs @@ -0,0 +1,233 @@ +//! Moved out of the parent module by STRA-338: impl QwenChunkTxn (7). + +#[allow(unused_imports)] +use super::*; + + + +impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { + + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in crate::qwen_forward) fn prepare_ffn_after_attention( + &mut self, + proof: PreparedLayerRow, + read: super::super::super::super::gr::DetachedGrRead, + execute: impl FnOnce( + &mut QwenStepTxn<'_, 'driver>, + super::super::super::super::gr::DetachedGrRead, + ) -> Result, + ) -> Result { + let (first, end) = self.phase_span()?; + self.validate_window_proof(&proof.window)?; + if proof.index < first + || proof.index >= end + || self.batch_layer != Some(proof.layer) + || self.next_layer != proof.layer.get() + || self.next_row != end + || self.batch_completed != first + || !Rc::ptr_eq(&self.chunk, &proof.chunk) + || self.batch_rows.get(proof.index).and_then(Option::as_ref) + .is_none_or(|stored| !Rc::ptr_eq(stored, &proof.proof)) + { + return Err(Error::IdentityMismatch); + } + let actual = &self.rows[proof.index]; + let token = actual.token; + let position = actual.position; + if actual.completed != proof.layer.get() { + return Err(Error::IdentityMismatch); + } + read.ready().validate_origin(&self.session.binding, GrRole::Ffn(proof.layer.get()))?; + read.ready().identity().validate(token, position, proof.layer)?; + let result = (|| { + let mut view = self.stage_view(proof.index)?; + let mut step = view.begin(token, position)?; + step.input = Some(actual.input.clone().ok_or(Error::Unsupported(Stage::Input))?); + step.completed_layers = actual.completed; + let row = execute(&mut step, read)?; + if step.ple_pending.is_some() + || step.gdn_pending.iter().any(Option::is_some) + || step.qsa_pending.iter().any(Option::is_some) + { + return Err(Error::IdentityMismatch); + } + row.validate(&self.session.binding, token, position, proof.layer)?; + Ok(ChunkFfnRow { proof, row }) + })(); + if let Err(error) = &result { + self.session.note_mtp_failure(error); + self.aborted = true; + } + result + } + pub(in super::super) fn roll_device_gdn( + &mut self, + step: &QwenStepTxn<'_, 'driver>, + index: usize, + layer: LayerId, + edge: super::super::super::super::gdn::chunk_device::ChunkEdge, + ) -> Result<()> { + if step.ple_pending.is_some() + || step.gdn_pending.iter().any(Option::is_some) + || step.qsa_pending.iter().any(Option::is_some) + || self.attention_authorized != Some(index) + { + return Err(Error::IdentityMismatch); + } + let (row,verified) = edge.into_parts(); + self.validate_window_proof(&row.window)?; + let journal = self.gdn_chunk.as_ref().ok_or(Error::IdentityMismatch)?; + row.validate(&journal.start, journal.accepted, &self.session.binding)?; + let actual = self.rows.get(index).ok_or(Error::IdentityMismatch)?; + let source = self + .attention_sources + .get(index) + .and_then(Option::as_ref) + .ok_or(Error::IdentityMismatch)?; + if row.index != index + || row.identity != TokenLayer::new(actual.token, actual.position, layer) + || !Rc::ptr_eq(&source.proof, &row.proof) + || !Rc::ptr_eq(&self.chunk, &row.start.0.chunk) + { + return Err(Error::IdentityMismatch); + } + if let Some(proof)=verified {self.record_device_gdn(index,layer,proof)?;} + else if self.device_gdn_lease()?.is_some(){return Err(Error::IdentityMismatch);} + self.gdn_chunk + .as_mut() + .ok_or(Error::IdentityMismatch)? + .accepted += 1; + Ok(()) + } + pub(in crate::qwen_forward) fn validate_ffn_row( + &self, + index: usize, + layer: LayerId, + row: &ChunkFfnRow, + ) -> Result<()> { + let (first, end) = self.phase_span()?; + let proof = &row.proof; + self.validate_window_proof(&proof.window)?; + let stored = self + .batch_rows + .get(index) + .and_then(Option::as_ref) + .ok_or(Error::IdentityMismatch)?; + if self.batch_layer != Some(layer) + || index < first + || index >= end + || self.next_row != end + || self.batch_completed != first + || proof.index != index + || proof.layer != layer + || !Rc::ptr_eq(&self.chunk, &proof.chunk) + || !Rc::ptr_eq(stored, &proof.proof) + { + return Err(Error::IdentityMismatch); + } + let (token, position) = self.row_ids(index)?; + row.row + .validate(&self.session.binding, token, position, layer) + } + pub(in crate::qwen_forward) fn prepare_ffn_injection( + &mut self, + index: usize, + layer: LayerId, + row: ChunkFfnRow, + binding: &ModelBinding, + expert: super::super::super::super::moe_expert::ExpertReady, + ) -> Result<(super::super::super::super::gr::GrBatchRow, PreparedLayerRow)> { + self.validate_ffn_row(index, layer, &row)?; + expert.validate_origin(&self.session.binding)?; + let (token, position) = self.row_ids(index)?; + expert.identity().validate(token, position, layer)?; + let mut view = self.stage_view(index)?; + let mut step = view.begin(token, position)?; + step.input = Some( + self.rows[index] + .input + .clone() + .ok_or(Error::Unsupported(Stage::Input))?, + ); + step.completed_layers = self.rows[index].completed; + let result = super::super::super::super::gr::GrStage::prepare_detached_batch_injection( + binding, + row.row.into_read(), + expert.output(), + expert.identity(), + &mut step, + ); + if let Err(error) = &result { + self.session.note_mtp_failure(error); + self.aborted = true; + } + Ok((result?, row.proof)) + } + pub(in super::super) fn roll_actual_pending( + &mut self, + step: &mut QwenStepTxn<'_, 'driver>, + layer: LayerId, + position: Position, + ) -> Result<()> { + // Validate pending producers now, then release each previous rolling + // state before another row executes this causal layer. + let slot = layer.get() as usize; + let next_position = position.get().checked_add(1).ok_or(Error::Overflow)?; + if self.attention_layer == Some(layer) { + let index = self.attention_authorized.ok_or(Error::IdentityMismatch)?; + if self + .attention_sources + .get(index) + .and_then(Option::as_ref) + .is_none() + || step.ple_pending.is_some() + { + return Err(Error::IdentityMismatch); + } + } else { + if layer.get() == 1 && self.session.ple_required { + let next = step + .ple_pending + .take() + .ok_or(Error::Unsupported(Stage::Input))? + .into_prior(); + if next.next_position() != next_position { + return Err(Error::IdentityMismatch); + } + self.next_ple = Some(next); + self.record_verification_ple(self.next_row, position)?; + } else if step.ple_pending.is_some() { + return Err(Error::IdentityMismatch); + } + } + if self.session.gdn_layers[slot] { + let next = step.gdn_pending[slot] + .take() + .ok_or(Error::Unsupported(Stage::Gdn))? + .into_prior(); + if next.layer() != layer || next.next_position() != next_position { + return Err(Error::IdentityMismatch); + } + self.next_gdn[slot] = Some(next); + } else if self.session.qsa_layers[slot] { + let next = step.qsa_pending[slot] + .take() + .ok_or(Error::Unsupported(Stage::QsaIndex))? + .into_prior(); + if next.layer() != layer || next.next_position() != next_position { + return Err(Error::IdentityMismatch); + } + self.next_qsa[slot] = Some(next); + } else { + return Err(Error::InvalidLayer); + } + self.record_verification_prior(self.next_row, layer, position)?; + // No hidden noncurrent-layer candidate is admitted. + if step.gdn_pending.iter().any(Option::is_some) + || step.qsa_pending.iter().any(Option::is_some) + { + return Err(Error::IdentityMismatch); + } + Ok(()) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_8.rs b/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_8.rs new file mode 100644 index 00000000..6aa6ad61 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_8.rs @@ -0,0 +1,247 @@ +//! Moved out of the parent module by STRA-338: impl QwenChunkTxn (8). + +#[allow(unused_imports)] +use super::*; + + + +impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { + pub(in crate::qwen_forward) fn layer( + &mut self, + index: usize, + layer: LayerId, + execute: impl FnOnce(&mut QwenStepTxn<'_, 'driver>) -> Result, + ) -> Result { + self.check()?; + if self.windowed || self.batch_layer.is_some() || self.attention_layer.is_some() { + return Err(Error::IdentityMismatch); + } + if layer.get() != self.next_layer + || index != self.next_row + || layer.get() >= 48 + || self + .rows + .get(index) + .is_none_or(|r| r.completed != layer.get()) + { + return Err(Error::IdentityMismatch); + } + let mut view = self.stage_view(index)?; + let row = &self.rows[index]; + let mut step = view.begin(row.token, row.position)?; + step.input = Some(row.input.clone().ok_or(Error::Unsupported(Stage::Input))?); + step.completed_layers = row.completed; + let result = execute(&mut step).and_then(|residual| { + step.mark_layer_complete(&residual)?; + let position = step.position(); + self.roll_actual_pending(&mut step, layer, position)?; + Ok(residual) + }); + match result { + Ok(residual) => { + self.rows[index].completed += 1; + self.next_row += 1; + if self.next_row == self.rows.len() { + self.next_row = 0; + self.next_layer += 1; + } + Ok(residual) + } + Err(error) => { + self.session.note_mtp_failure(&error); + self.aborted = true; + Err(error) + } + } + } + pub(in crate::qwen_forward) fn prepare_layer_batch( + &mut self, + index: usize, + layer: LayerId, + execute: impl FnOnce(&mut QwenStepTxn<'_, 'driver>) -> Result, + ) -> Result<(T, PreparedLayerRow)> { + self.prepare_layer_batch_internal(index, layer, |step| { + execute(step).map(|prepared| (prepared, None)) + }) + } + pub(in super::super) fn prepare_layer_batch_internal( + &mut self, + index: usize, + layer: LayerId, + execute: impl FnOnce( + &mut QwenStepTxn<'_, 'driver>, + ) -> Result<(T, Option)>, + ) -> Result<(T, PreparedLayerRow)> { + let (first, end) = self.phase_span()?; + if index < first || index >= end { + return Err(Error::IdentityMismatch); + } + if (self.windowed && self.attention_layer.is_none()) + || (self.attention_layer.is_some() && self.attention_authorized != Some(index)) + { + return Err(Error::IdentityMismatch); + } + if layer.get() != self.next_layer + || index != self.next_row + || layer.get() >= 48 + || self + .rows + .get(index) + .is_none_or(|r| r.completed != layer.get()) + || self.batch_layer.is_some_and(|current| current != layer) + { + return Err(Error::IdentityMismatch); + } + if self.batch_layer.is_none() { + if index != first { + return Err(Error::IdentityMismatch); + } + self.batch_rows + .try_reserve_exact(self.rows.len()) + .map_err(|_| Error::InputAllocation)?; + self.batch_rows.resize_with(self.rows.len(), || None); + self.batch_layer = Some(layer); + self.batch_completed = first; + } + let mut view = self.stage_view(index)?; + let row = &self.rows[index]; + let position = row.position; + let mut step = view.begin(row.token, row.position)?; + step.input = Some(row.input.clone().ok_or(Error::Unsupported(Stage::Input))?); + step.completed_layers = row.completed; + let result = execute(&mut step).and_then(|(prepared, edge)| { + if let Some(edge) = edge { + self.roll_device_gdn(&step, index, layer, edge)?; + } else { + if self.gdn_chunk.is_some() { + return Err(Error::IdentityMismatch); + } + self.roll_actual_pending(&mut step, layer, position)?; + } + Ok(prepared) + }); + match result { + Ok(prepared) => { + let proof = Rc::new(()); + self.batch_rows[index] = Some(Rc::clone(&proof)); + self.next_row += 1; + Ok(( + prepared, + PreparedLayerRow { + chunk: Rc::clone(&self.chunk), + proof, + index, + layer, + window: self.window_proof(), + attention_source: self.attention_sources.get(index) + .and_then(Option::as_ref).map(|source| Rc::clone(&source.read)), + }, + )) + } + Err(error) => { + self.session.note_mtp_failure(&error); + self.aborted = true; + Err(error) + } + } + } + pub(in crate::qwen_forward) fn batch_outputs( + &mut self, + execute: impl FnOnce(&Context<'driver>) -> Result, + ) -> Result { + let (first, end) = self.phase_span()?; + if self.batch_layer.is_none() + || self.next_row != end + || self + .batch_rows + .get(first..end) + .is_none_or(|rows| rows.iter().any(Option::is_none)) + { + return Err(Error::IdentityMismatch); + } + let result = execute(self.session.mtp_context()?); + if let Err(error) = &result { + self.session.note_mtp_failure(error); + self.aborted = true; + } + result + } + /// Closed experimental FFN execution retains an immutable borrow of the + /// actual transaction, so every D2D copy can revalidate its real row seal. + pub(in crate::qwen_forward) fn batch_outputs_ffn( + &mut self, + layer: LayerId, + rows: &[ChunkFfnRow], + execute: impl FnOnce(&Self, &Context<'driver>) -> Result, + ) -> Result { + if rows.len() != self.micro_len()? || !(1..=64).contains(&rows.len()) { + return Err(Error::InvalidDimension); + } + for (index, row) in rows.iter().enumerate() { + self.validate_ffn_row(self.micro_row_index(index)?, layer, row)?; + } + let result = execute(self, self.session.mtp_context()?).and_then(|value| { + for (index, row) in rows.iter().enumerate() { + self.validate_ffn_row(self.micro_row_index(index)?, layer, row)?; + } + Ok(value) + }); + if let Err(error) = &result { + self.session.note_mtp_failure(error); + self.aborted = true; + } + result + } + pub(in crate::qwen_forward) fn complete_layer_batch( + &mut self, + proof: PreparedLayerRow, + residual: InjectedResidual, + ) -> Result { + let (first, end) = self.phase_span()?; + self.validate_window_proof(&proof.window)?; + if proof.index < first + || proof.index >= end + || self.batch_layer != Some(proof.layer) + || !Rc::ptr_eq(&self.chunk, &proof.chunk) + || proof.index != self.batch_completed + || self.next_row != end + || self + .batch_rows + .get(proof.index) + .and_then(Option::as_ref) + .is_none_or(|p| !Rc::ptr_eq(p, &proof.proof)) + { + return Err(Error::IdentityMismatch); + } + let mut view = self.stage_view(proof.index)?; + let row = &self.rows[proof.index]; + let mut step = view.begin(row.token, row.position)?; + step.input = Some(row.input.clone().ok_or(Error::Unsupported(Stage::Input))?); + step.completed_layers = row.completed; + // Only actual GR producer-owned finite FFN residual completes the row. + if let Err(error) = step.mark_layer_complete(&residual) { + self.session.note_mtp_failure(&error); + self.aborted = true; + return Err(error); + } + self.rows[proof.index].completed += 1; + self.batch_rows[proof.index] = None; + self.batch_completed += 1; + if self.batch_completed == end { + if self.windowed { + self.next_row = end; + } else { + self.next_row = 0; + self.next_layer += 1; + } + self.batch_layer = None; + self.batch_rows.clear(); + self.batch_completed = 0; + self.attention_layer = None; + self.attention_next = if self.windowed { end } else { 0 }; + self.attention_sources.clear(); + self.attention_authorized = None; + } + Ok(residual) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_9.rs b/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_9.rs new file mode 100644 index 00000000..85bc021d --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_9.rs @@ -0,0 +1,197 @@ +//! Moved out of the parent module by STRA-338: impl QwenChunkTxn (9). + +#[allow(unused_imports)] +use super::*; + + + +impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { + + pub(in crate::qwen_forward) fn finish( + &mut self, + residuals: &[Option], + execute_head: impl FnOnce(&mut QwenStepTxn<'_, 'driver>, &InjectedResidual) -> Result, + ) -> Result<()> { + let result = self.finish_inner(residuals, execute_head); + if let Err(error) = &result { + self.session.note_mtp_failure(error); + self.aborted = true; + } + result + } + pub(in super::super) fn finish_inner( + &mut self, + residuals: &[Option], + execute_head: impl FnOnce(&mut QwenStepTxn<'_, 'driver>, &InjectedResidual) -> Result, + ) -> Result<()> { + self.check()?; + if self.finished + || self.next_layer != 48 + || self.next_row != 0 + || self.active_micro.is_some() + || self.micro_cursor != 0 + || residuals.len() != self.rows.len() + { + return Err(Error::IdentityMismatch); + } + for (index, residual) in residuals.iter().enumerate() { + let row = &self.rows[index]; + let residual = residual + .as_ref() + .ok_or(Error::Unsupported(Stage::Executor))?; + residual.validate_origin(&self.session.binding, GrRole::Ffn(47))?; + residual.identity().validate( + row.token, + row.position, + LayerId::new(47, Dimension::new(48)?)?, + )?; + if row.completed != 48 + || residual.streams().len() != 10240 + || residual.streams().iter().any(|v| !v.is_finite()) + { + return Err(Error::NonFinite); + } + let mut streams = Vec::new(); + streams + .try_reserve_exact(10240) + .map_err(|_| Error::InputAllocation)?; + streams.extend_from_slice(residual.streams()); + self.witnesses.push(ChunkRowResidual { + binding: self.session.binding.clone(), + chunk: Rc::clone(&self.chunk), + origin: self.origin.clone(), + token: row.token, + position: row.position, + known_next: self + .rows + .get(index + 1) + .map(|r| r.token) + .or(self.known_next), + streams: Rc::new(streams.into_boxed_slice()), + }); + } + if self.known_next.is_none() { + let index = self.rows.len() - 1; + let mut view = self.stage_view(index)?; + let row = &self.rows[index]; + let mut step = view.begin(row.token, row.position)?; + step.input = row.input.clone(); + step.completed_layers = 48; + match execute_head( + &mut step, + residuals[index].as_ref().ok_or(Error::IdentityMismatch)?, + ) { + Ok(output) if step.forward_output == Some(output) && !step.prefill_finished => { + self.output = Some(output) + } + Ok(_) => return Err(Error::IdentityMismatch), + Err(error) => { + self.session.note_mtp_failure(&error); + return Err(error); + } + } + } + self.finished = true; + Ok(()) + } + pub(in super::super) fn validate_publish(&self) -> Result<()> { + self.check()?; + if !self.finished + || self.active_micro.is_some() + || self.micro_cursor != 0 + || self.next_layer != 48 + || self.next_row != 0 + || self.witnesses.len() != self.rows.len() + || (self.known_next.is_none() != self.output.is_some()) + { + return Err(Error::Unsupported(Stage::Executor)); + } + for witness in &self.witnesses { + self.validate_row(witness)?; + } + let end_position = Position::new(self.end, crate::qwen_forward::contract::position_dimension())?; + if self.session.ple_required { + self.next_ple + .as_ref() + .ok_or(Error::Unsupported(Stage::Input))? + .validate(&self.session.binding, &self.session.ple_owner, end_position)?; + } + for slot in 0..STATE_CAPACITY { + let layer = LayerId::new(slot as u64, Dimension::new(48)?)?; + if self.session.gdn_layers[slot] { + if self.device_gdn_lease()?.is_some() { + self.validate_verification_state(self.rows.len()-1)?; + } else { + self.next_gdn[slot] + .as_ref() + .ok_or(Error::Unsupported(Stage::Gdn))? + .validate( + &self.session.binding, + &self.session.gdn_owner, + layer, + end_position, + )?; + } + } else if self.next_gdn[slot].is_some() { + return Err(Error::IdentityMismatch); + } + if self.session.qsa_layers[slot] { + self.next_qsa[slot] + .as_ref() + .ok_or(Error::Unsupported(Stage::QsaIndex))? + .validate( + &self.session.binding, + &self.session.qsa_owner, + layer, + end_position, + )?; + } else if self.next_qsa[slot].is_some() { + return Err(Error::IdentityMismatch); + } + } + Ok(()) + } + pub(in crate::qwen_forward) fn publish_joint( + self, + draft: impl ChunkDraftPublication, + ) -> Result { + if self.verification.is_some() { + return Err(Error::IdentityMismatch); + } + self.validate_publish()?; + draft.validate(&self)?; + self.session.complete_cuda()?; + let last = self.rows.last().ok_or(Error::InvalidPosition)?; + let predecessors = [ + last.predecessors[1], + i32::try_from(last.token.get()).map_err(|_| Error::InvalidToken)?, + ]; + let source = self.witnesses.last().ok_or(Error::IdentityMismatch)?; + let token = source.token; + let position = source.position; + let binding = source.binding.clone(); + let mut streams = Vec::new(); + streams + .try_reserve_exact(10240) + .map_err(|_| Error::InputAllocation)?; + streams.extend_from_slice(source.streams.as_ref()); + let streams = streams.into_boxed_slice(); + // Every fallible operation above. Neither target nor draft is exposed + // between these infallible assignments in this single-thread owner. + self.session.ple_state = self.next_ple; + self.session.gdn_states = self.next_gdn; + self.session.qsa_states = self.next_qsa; + self.session.predecessors = predecessors; + self.session.next_position = self.end; + draft.publish(); + let origin = super::super::super::checkpoint::committed_origin(self.session); + Ok(ChunkCommit { + binding, + token, + position, + output: self.output, + streams, + origin, + }) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/session_chunk_verify/impl_qwenchunktxn.rs b/crates/leleka-runtime/src/qwen_forward/session_chunk_verify/impl_qwenchunktxn.rs index 7341fe7a..351806c5 100644 --- a/crates/leleka-runtime/src/qwen_forward/session_chunk_verify/impl_qwenchunktxn.rs +++ b/crates/leleka-runtime/src/qwen_forward/session_chunk_verify/impl_qwenchunktxn.rs @@ -3,582 +3,9 @@ #[allow(unused_imports)] use super::*; - -impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { - pub(in crate::qwen_forward) fn validate_verification_source( - binding: &ModelBinding, - source: &TargetStepProduct, - eos: Option, - session: &QwenSession<'driver>, - ) -> Result { - let (_, position, _, _) = source.mtp_source(binding, session)?; - let seed = source.predicted(session)?; - if !session.binding.matches(&binding.identity()) - || position.get().checked_add(1) != Some(session.next_position) - || Some(seed) == eos - { - return Err(Error::IdentityMismatch); - } - Ok(seed) - } - - pub(in crate::qwen_forward) fn preflight_mtp_verification( - session: &QwenSession<'driver>, - binding: &ModelBinding, - tokens: usize, - host_remaining: usize, - ) -> Result<()> { - session.target_origin()?; - if !session.binding.matches(&binding.identity()) || session.layer_count != 48 { - return Err(Error::IdentityMismatch); - } - let end = session - .next_position - .checked_add(tokens as u64) - .ok_or(Error::Overflow)?; - let extra = verification_extra_charge(tokens, end)?; - let total = host_charge_bounded(tokens, end, 256)? - .checked_add(extra) - .ok_or(Error::Overflow)?; - if end >= u64::from(binding.input_constants().context_length()) || end >= crate::qwen_forward::contract::serving_cells() { - return Err(Error::InvalidPosition); - } - if total > host_remaining.min(HOST_LIMIT) { - return Err(Error::InputAllocation); - } - Ok(()) - } - - pub(in crate::qwen_forward) fn begin_mtp_verification( - session: &'session mut QwenSession<'driver>, - binding: &ModelBinding, - tokens: &[TokenId], - host_remaining: usize, - ) -> Result { - Self::preflight_mtp_verification(session, binding, tokens.len(), host_remaining)?; - let end = session - .next_position - .checked_add(tokens.len() as u64) - .ok_or(Error::Overflow)?; - let extra = verification_extra_charge(tokens.len(), end)?; - let available = host_remaining - .min(HOST_LIMIT) - .checked_sub(extra) - .ok_or(Error::InputAllocation)?; - // Both charges are admitted before rows, pointer journals or numeric - // producers allocate. This preserves the old admission and VRAM cap. - let mut txn = Self::begin_windowed256(session, binding, tokens, None, available)?; - let mut states = Vec::new(); - states - .try_reserve_exact(tokens.len()) - .map_err(|_| Error::InputAllocation)?; - states.resize_with(tokens.len(), || PrefixState { - ple: None, - gdn: std::array::from_fn(|_| None), - device_gdn: std::array::from_fn(|_| None), - qsa: std::array::from_fn(|_| None), - head: None, - }); - txn.verification = Some(VerificationJournal { states, device_lease: None }); - Ok(txn) - } - - pub(in crate::qwen_forward) fn enable_device_gdn_verification(&mut self,binding:&ModelBinding,cache:&crate::qwen_forward::dense_weight_cache::DenseWeightCache<'_>,host_remaining:usize)->Result<()> { - self.check()?;self.origin.validate(self.session)?; - let context=self.session.mtp_context()?; - let Some(workspace)=cache.gdn_verification_workspace(binding,context)? else{return Ok(());}; - let metadata=workspace.try_borrow().map_err(|_|Error::IdentityMismatch)?.metadata_bytes()?; - let charged=host_charge_bounded(self.rows.len(),self.end,256)? - .checked_add(verification_extra_charge(self.rows.len(),self.end)?).and_then(|n|n.checked_add(metadata)).ok_or(Error::Overflow)?; - if charged>host_remaining.min(HOST_LIMIT){return Err(Error::InputAllocation);} - let journal=self.verification.as_mut().ok_or(Error::IdentityMismatch)?; - if journal.device_lease.is_some() || self.rows.len()>3 || self.next_layer!=0 || self.next_row!=0 {return Err(Error::IdentityMismatch);} - let lease=workspace.try_borrow_mut().map_err(|_|Error::IdentityMismatch)?.begin(&self.session.binding,&self.origin,&self.chunk,self.rows.len())?; - journal.device_lease=Some(lease);Ok(()) - } - pub(in crate::qwen_forward) fn device_gdn_lease(&self)->Result>>{ - let lease=self.verification.as_ref().and_then(|j|j.device_lease.as_ref()); - if lease.is_none(){return Ok(None);} - self.check()?;self.origin.validate(self.session)?; - if let Some(lease)=lease{lease.validate(&self.session.binding,&self.origin,&self.chunk,self.rows.len())?;} - Ok(lease.cloned()) - } - pub(in super::super) fn record_device_gdn(&mut self,index:usize,layer:LayerId,proof:Rc)->Result<()> { - let lease=self.device_gdn_lease()?.ok_or(Error::IdentityMismatch)?; - let row=self.rows.get(index).ok_or(Error::IdentityMismatch)?; - proof.validate(&lease,layer,index,TokenLayer::new(row.token,row.position,layer))?; - let state=self.verification.as_mut().ok_or(Error::IdentityMismatch)?.states.get_mut(index).ok_or(Error::IdentityMismatch)?; - if state.gdn[layer.get() as usize].is_some() || state.device_gdn[layer.get() as usize].is_some(){return Err(Error::IdentityMismatch);} - state.device_gdn[layer.get() as usize]=Some(proof);Ok(()) - } - pub(super) fn replay_device_prefix(&self,binding:&ModelBinding,cache:&crate::qwen_forward::dense_weight_cache::DenseWeightCache<'_>,count:usize,mut cancelled:impl FnMut()->bool)->Result<[Option;STATE_CAPACITY]>{ - let lease=self.device_gdn_lease()?.ok_or(Error::IdentityMismatch)?; - if count==0 || count>self.rows.len(){return Err(Error::IdentityMismatch);} - let workspace=cache.gdn_verification_workspace(binding,self.session.mtp_context()?)?.ok_or(Error::IdentityMismatch)?; - let mut sealed=std::array::from_fn(|_|None); - for (slot,output) in sealed.iter_mut().enumerate(){ - if !self.session.gdn_layers[slot]{continue;} - if cancelled(){return Err(Error::Unsupported(Stage::Executor));} - self.origin.validate(self.session)?; - let layer=LayerId::new(slot as u64,Dimension::new(48)?)?; - let mut proofs=Vec::new();proofs.try_reserve_exact(count).map_err(|_|Error::InputAllocation)?; - for index in 0..count { - let state=self.validate_verification_state(index)?; - let proof=state.device_gdn[slot].as_ref().ok_or(Error::IdentityMismatch)?; - let actual=&self.rows[index];proof.validate(&lease,layer,index,TokenLayer::new(actual.token,actual.position,layer))?; - proofs.push(proof.clone()); - } - let prior=workspace.try_borrow_mut().map_err(|_|Error::IdentityMismatch)?.replay(&lease,&proofs,&mut cancelled)?; - prior.validate(&self.session.binding,&self.session.gdn_owner,layer,Position::new(self.start_position().checked_add(count as u64).ok_or(Error::Overflow)?,crate::qwen_forward::contract::position_dimension())?)?; - *output=Some(prior); - } - if cancelled(){return Err(Error::Unsupported(Stage::Executor));} - self.origin.validate(self.session)?;Ok(sealed) - } - pub(in crate::qwen_forward) fn seal_device_gdn_prefix(&mut self,binding:&ModelBinding,cache:&crate::qwen_forward::dense_weight_cache::DenseWeightCache<'_>,prefix:&VerifiedTargetPrefix,cancelled:impl FnMut()->bool)->Result<()> { - self.validate_verified_prefix(prefix)?; - if self.device_gdn_lease()?.is_none(){return Ok(());} - // Stage ALL36 actual replayed canonical priors before either owner mutation. - let sealed=self.replay_device_prefix(binding,cache,prefix.count,cancelled)?; - self.verification.as_mut().ok_or(Error::IdentityMismatch)?.states[prefix.count-1].gdn=sealed;Ok(()) - } - #[cfg(all(test,any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - pub(in crate::qwen_forward) fn materialize_device_gdn_observer(&mut self,binding:&ModelBinding,cache:&crate::qwen_forward::dense_weight_cache::DenseWeightCache<'_>,mut cancelled:impl FnMut()->bool)->Result<()> { - if self.device_gdn_lease()?.is_none() || !crate::qwen_forward::mtp_decode::batch_gpu::collecting(){return Ok(());} - for count in 1..=self.rows.len(){ - let sealed=self.replay_device_prefix(binding,cache,count,&mut cancelled)?; - self.verification.as_mut().ok_or(Error::IdentityMismatch)?.states[count-1].gdn=sealed; - } - Ok(()) - } - pub(super) fn verification_row_position(&self, index: usize, position: Position) -> Result { - self.check()?; - let row = self.rows.get(index).ok_or(Error::IdentityMismatch)?; - if row.position != position || self.gdn_chunk.is_some() { - return Err(Error::IdentityMismatch); - } - Position::new( - position.get().checked_add(1).ok_or(Error::Overflow)?, - crate::qwen_forward::contract::position_dimension(), - ) - } - // PLE completes before this layer's GDN recurrence consumes its rows. - // Its genuine next prior may be journaled without claiming a GDN prior. - pub(super) fn verification_ple_row_position(&self, index: usize, position: Position) -> Result { - let Some(journal) = self.gdn_chunk.as_ref() else { - return self.verification_row_position(index, position); - }; - let (first, end) = self.phase_span()?; - let row = self.rows.get(index).ok_or(Error::IdentityMismatch)?; - let start = &journal.start.0; - journal.start.validate_binding(&self.session.binding)?; - if !Rc::ptr_eq(&start.chunk, &self.chunk) - || start.layer.get() != 1 - || self.next_layer != 1 - || start.count != self.rows.len() - || start.end != self.end - || self.rows.first().is_none_or(|row| row.position != start.first) - || start.first.get().checked_add(index as u64) != Some(position.get()) - || row.position != position - || row.completed != 1 - || index < first - || index >= end - || self.next_row != first - || self.attention_layer != Some(start.layer) - || self.attention_next != index - || self.batch_layer.is_some() - || self.attention_authorized.is_some() - || journal.accepted != first - { - return Err(Error::IdentityMismatch); - } - start.prior.validate(&self.session.binding, &self.session.gdn_owner, - start.layer, start.first)?; - Position::new(position.get().checked_add(1).ok_or(Error::Overflow)?, - crate::qwen_forward::contract::position_dimension()) - } - pub(in super::super) fn record_verification_ple( - &mut self, - index: usize, - position: Position, - ) -> Result<()> { - if self.verification.is_none() { - return Ok(()); - } - let end = self.verification_ple_row_position(index, position)?; - let prior = self - .next_ple - .as_ref() - .ok_or(Error::Unsupported(Stage::Input))?; - prior.validate(&self.session.binding, &self.session.ple_owner, end)?; - let journal = self.verification.as_mut().ok_or(Error::IdentityMismatch)?; - let state = journal - .states - .get_mut(index) - .ok_or(Error::IdentityMismatch)?; - if state.ple.is_some() { - return Err(Error::IdentityMismatch); - } - state.ple = Some(prior.clone()); - Ok(()) - } - pub(in super::super) fn record_verification_prior( - &mut self, - index: usize, - layer: LayerId, - position: Position, - ) -> Result<()> { - if self.verification.is_none() { - return Ok(()); - } - let end = self.verification_row_position(index, position)?; - let slot = layer.get() as usize; - if slot >= STATE_CAPACITY { - return Err(Error::InvalidLayer); - } - // Only the consumed producer prior is cloned; no numeric constructor, - // stale initial state or advanced metadata is used for a prefix. - if self.session.gdn_layers[slot] { - let prior = self.next_gdn[slot] - .as_ref() - .ok_or(Error::Unsupported(Stage::Gdn))?; - prior.validate(&self.session.binding, &self.session.gdn_owner, layer, end)?; - let state = self - .verification - .as_mut() - .ok_or(Error::IdentityMismatch)? - .states - .get_mut(index) - .ok_or(Error::IdentityMismatch)?; - if state.gdn[slot].is_some() { - return Err(Error::IdentityMismatch); - } - state.gdn[slot] = Some(prior.clone()); - } else if self.session.qsa_layers[slot] { - let prior = self.next_qsa[slot] - .as_ref() - .ok_or(Error::Unsupported(Stage::QsaIndex))?; - prior.validate(&self.session.binding, &self.session.qsa_owner, layer, end)?; - let state = self - .verification - .as_mut() - .ok_or(Error::IdentityMismatch)? - .states - .get_mut(index) - .ok_or(Error::IdentityMismatch)?; - if state.qsa[slot].is_some() { - return Err(Error::IdentityMismatch); - } - state.qsa[slot] = Some(prior.clone()); - } else { - return Err(Error::InvalidLayer); - } - Ok(()) - } - pub(in super::super) fn validate_verification_state(&self, index: usize) -> Result<&PrefixState> { - self.check()?; - let row = self.rows.get(index).ok_or(Error::IdentityMismatch)?; - if row.completed != 48 || self.gdn_chunk.is_some() { - return Err(Error::IdentityMismatch); - } - let end = Position::new( - row.position.get().checked_add(1).ok_or(Error::Overflow)?, - crate::qwen_forward::contract::position_dimension(), - )?; - let state = self - .verification - .as_ref() - .ok_or(Error::IdentityMismatch)? - .states - .get(index) - .ok_or(Error::IdentityMismatch)?; - if self.session.ple_required { - state - .ple - .as_ref() - .ok_or(Error::Unsupported(Stage::Input))? - .validate(&self.session.binding, &self.session.ple_owner, end)?; - } else if state.ple.is_some() { - return Err(Error::IdentityMismatch); - } - for slot in 0..STATE_CAPACITY { - let layer = LayerId::new(slot as u64, Dimension::new(48)?)?; - if self.session.gdn_layers[slot] { - if let Some(lease)=self.verification.as_ref().and_then(|j|j.device_lease.as_ref()) { - state.device_gdn[slot].as_ref().ok_or(Error::Unsupported(Stage::Gdn))? - .validate(lease,layer,index,TokenLayer::new(row.token,row.position,layer))?; - if let Some(prior)=&state.gdn[slot] {prior.validate(&self.session.binding,&self.session.gdn_owner,layer,end)?;} - } else { - state.gdn[slot] - .as_ref() - .ok_or(Error::Unsupported(Stage::Gdn))? - .validate(&self.session.binding, &self.session.gdn_owner, layer, end)?; - } - } else if state.gdn[slot].is_some() || state.device_gdn[slot].is_some() { - return Err(Error::IdentityMismatch); - } - if self.session.qsa_layers[slot] { - state.qsa[slot] - .as_ref() - .ok_or(Error::Unsupported(Stage::QsaIndex))? - .validate(&self.session.binding, &self.session.qsa_owner, layer, end)?; - } else if state.qsa[slot].is_some() { - return Err(Error::IdentityMismatch); - } - } - Ok(state) - } - - pub(in crate::qwen_forward) fn finish_mtp_verification( - &mut self, - residuals: &[Option], - mut execute_head: impl FnMut( - &mut QwenStepTxn<'_, 'driver>, - &InjectedResidual, - ) -> Result, - ) -> Result<()> { - let result = self.finish_mtp_verification_inner(residuals, &mut execute_head); - if let Err(error) = &result { - self.session.note_mtp_failure(error); - self.aborted = true; - } - result - } - pub(super) fn finish_mtp_verification_inner( - &mut self, - residuals: &[Option], - execute_head: &mut impl FnMut( - &mut QwenStepTxn<'_, 'driver>, - &InjectedResidual, - ) -> Result, - ) -> Result<()> { - self.check()?; - if self.finished - || self.known_next.is_some() - || self - .verification - .as_ref() - .is_none_or(|j| j.states.len() != self.rows.len()) - || self.next_layer != 48 - || self.next_row != 0 - || self.active_micro.is_some() - || self.micro_cursor != 0 - || residuals.len() != self.rows.len() - || !self.witnesses.is_empty() - { - return Err(Error::IdentityMismatch); - } - for (index, residual) in residuals.iter().enumerate() { - let row = &self.rows[index]; - let residual = residual - .as_ref() - .ok_or(Error::Unsupported(Stage::Executor))?; - residual.validate_origin(&self.session.binding, GrRole::Ffn(47))?; - residual.identity().validate( - row.token, - row.position, - LayerId::new(47, Dimension::new(48)?)?, - )?; - if residual.streams().len() != 10240 - || residual.streams().iter().any(|v| !v.is_finite()) - { - return Err(Error::NonFinite); - } - let state = self.validate_verification_state(index)?; - let mut view = self.stage_view(index)?; - // The head view has the actual complete row state, never the full - // chunk's final state relabelled with an intermediate position. - view.ple_state = state.ple.clone(); - if self.device_gdn_lease()?.is_none() || state.gdn.iter().any(Option::is_some) { - view.gdn_states = state.gdn.clone(); - } - // Device-only rows keep original unused canonical priors in the head - // view; actual current provisional rows were authenticated above. - // A diagnostic snapshot uses only real replay-materialized states. - view.qsa_states = state.qsa.clone(); - let mut step = view.begin(row.token, row.position)?; - step.input = row.input.clone(); - step.completed_layers = 48; - let head = execute_head(&mut step, residual)?; - if step.forward_output != Some(head) || step.prefill_finished { - return Err(Error::IdentityMismatch); - } - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if crate::qwen_forward::mtp_decode::batch_gpu::collecting() { - // Observation of the validated completed journal, never a - // session/Origin constructor or publication/restore authority. - let snapshot = super::super::super::ResetReplaySnapshot { - binding: self.session.binding.clone(), - predecessors: [ - row.predecessors[1], - i32::try_from(row.token.get()).map_err(|_| Error::InvalidToken)?, - ], - next_position: row.position.get().checked_add(1).ok_or(Error::Overflow)?, - layer_count: self.session.layer_count, - ple_required: self.session.ple_required, - ple: state.ple.clone(), - gdn_layers: self.session.gdn_layers, - gdn: state.gdn.clone(), - qsa_layers: self.session.qsa_layers, - qsa: state.qsa.clone(), - }; - crate::qwen_forward::mtp_decode::batch_gpu::collect_row( - row.token, - row.position, - head, - residual.streams(), - snapshot, - )?; - } - let mut streams = Vec::new(); - streams - .try_reserve_exact(10240) - .map_err(|_| Error::InputAllocation)?; - streams.extend_from_slice(residual.streams()); - self.witnesses.push(ChunkRowResidual { - binding: self.session.binding.clone(), - chunk: self.chunk.clone(), - origin: self.origin.clone(), - token: row.token, - position: row.position, - known_next: self.rows.get(index + 1).map(|r| r.token), - streams: Rc::new(streams.into_boxed_slice()), - }); - self.verification - .as_mut() - .ok_or(Error::IdentityMismatch)? - .states[index] - .head = Some(head); - } - self.output = self - .verification - .as_ref() - .and_then(|j| j.states.last()) - .and_then(|s| s.head); - self.finished = true; - self.validate_publish()?; - Ok(()) - } - - pub(in crate::qwen_forward) fn select_verified_prefix( - &self, - binding: &ModelBinding, - source: &TargetStepProduct, - eos: Option, - ) -> Result { - self.validate_publish()?; - if !(1..=4).contains(&self.rows.len()) { - return Err(Error::InvalidDimension); - } - let (_, position, _, source_origin) = source.mtp_source(binding, self.session)?; - if !self.session.binding.matches(&binding.identity()) - || !source_origin.same_prefix(&self.origin) - || position.get().checked_add(1) != Some(self.start_position()) - { - return Err(Error::IdentityMismatch); - } - let seed = source.predicted(self.session)?; - let mut tokens = [seed; 4]; - let mut heads = [seed; 4]; - // Every row is genuine and complete, including a rejected tail. - for index in 0..self.rows.len() { - tokens[index] = self.rows[index].token; - heads[index] = self - .validate_verification_state(index)? - .head - .ok_or(Error::Unsupported(Stage::Output))?; - } - let (count, expected) = greedy_prefix( - seed, - eos, - &tokens[..self.rows.len()], - &heads[..self.rows.len()], - )?; - Ok(VerifiedTargetPrefix { - chunk: self.chunk.clone(), - origin: self.origin.clone(), - count, - next: expected, - }) - } - - pub(in crate::qwen_forward) fn validate_verified_prefix( - &self, - prefix: &VerifiedTargetPrefix, - ) -> Result<()> { - self.validate_publish()?; - if !Rc::ptr_eq(&prefix.chunk, &self.chunk) - || !prefix.origin.same_prefix(&self.origin) - || prefix.count == 0 - || prefix.count > self.rows.len() - { - return Err(Error::IdentityMismatch); - } - prefix.origin.validate(self.session)?; - for index in 0..self.rows.len() { - self.validate_verification_state(index)? - .head - .ok_or(Error::Unsupported(Stage::Output))?; - } - if self.validate_verification_state(prefix.count - 1)?.head != Some(prefix.next) { - return Err(Error::IdentityMismatch); - } - Ok(()) - } - - pub(in crate::qwen_forward) fn publish_verified_joint( - mut self, - prefix: VerifiedTargetPrefix, - draft: impl VerifiedDraftPublication, - ) -> Result { - self.validate_verified_prefix(&prefix)?; - draft.validate(&self, &prefix)?; - self.session.complete_cuda()?; - let row = &self.rows[prefix.count - 1]; - let source = &self.witnesses[prefix.count - 1]; - let predecessors = [ - row.predecessors[1], - i32::try_from(row.token.get()).map_err(|_| Error::InvalidToken)?, - ]; - let end = row.position.get().checked_add(1).ok_or(Error::Overflow)?; - let mut streams = Vec::new(); - streams - .try_reserve_exact(10240) - .map_err(|_| Error::InputAllocation)?; - streams.extend_from_slice(source.streams.as_ref()); - let streams = streams.into_boxed_slice(); - let binding = source.binding.clone(); - let token = row.token; - let position = row.position; - let journal = self.verification.take().ok_or(Error::IdentityMismatch)?; - let state = journal - .states - .into_iter() - .nth(prefix.count - 1) - .ok_or(Error::IdentityMismatch)?; - if journal.device_lease.is_some() { - let end_position=Position::new(end,crate::qwen_forward::contract::position_dimension())?; - for slot in 0..STATE_CAPACITY {if self.session.gdn_layers[slot] { - state.gdn[slot].as_ref().ok_or(Error::Unsupported(Stage::Gdn))? - .validate(&self.session.binding,&self.session.gdn_owner,LayerId::new(slot as u64,Dimension::new(48)?)?,end_position)?; - }} - } - // All fallible work precedes either owner mutation. Rejected tail - // states and row witnesses are dropped; no epoch or position rewind. - self.session.ple_state = state.ple; - self.session.gdn_states = state.gdn; - self.session.qsa_states = state.qsa; - self.session.predecessors = predecessors; - self.session.next_position = end; - draft.publish(); - let origin = super::super::super::checkpoint::committed_origin(self.session); - Ok(ChunkCommit { - binding, - token, - position, - output: Some(prefix.next), - streams, - origin, - }) - } -} +#[path = "impl_qwenchunktxn/impl_qwenchunktxn_2.rs"] +mod impl_qwenchunktxn_2; +#[path = "impl_qwenchunktxn/impl_qwenchunktxn_2_2.rs"] +mod impl_qwenchunktxn_2_2; +#[path = "impl_qwenchunktxn/impl_qwenchunktxn_3.rs"] +mod impl_qwenchunktxn_3; diff --git a/crates/leleka-runtime/src/qwen_forward/session_chunk_verify/impl_qwenchunktxn/impl_qwenchunktxn_2.rs b/crates/leleka-runtime/src/qwen_forward/session_chunk_verify/impl_qwenchunktxn/impl_qwenchunktxn_2.rs new file mode 100644 index 00000000..f1f586f2 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/session_chunk_verify/impl_qwenchunktxn/impl_qwenchunktxn_2.rs @@ -0,0 +1,226 @@ +//! Moved out of the parent module by STRA-338: impl QwenChunkTxn. + +#[allow(unused_imports)] +use super::*; + + + +impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { + pub(in crate::qwen_forward) fn validate_verification_source( + binding: &ModelBinding, + source: &TargetStepProduct, + eos: Option, + session: &QwenSession<'driver>, + ) -> Result { + let (_, position, _, _) = source.mtp_source(binding, session)?; + let seed = source.predicted(session)?; + if !session.binding.matches(&binding.identity()) + || position.get().checked_add(1) != Some(session.next_position) + || Some(seed) == eos + { + return Err(Error::IdentityMismatch); + } + Ok(seed) + } + + pub(in crate::qwen_forward) fn preflight_mtp_verification( + session: &QwenSession<'driver>, + binding: &ModelBinding, + tokens: usize, + host_remaining: usize, + ) -> Result<()> { + session.target_origin()?; + if !session.binding.matches(&binding.identity()) || session.layer_count != 48 { + return Err(Error::IdentityMismatch); + } + let end = session + .next_position + .checked_add(tokens as u64) + .ok_or(Error::Overflow)?; + let extra = verification_extra_charge(tokens, end)?; + let total = host_charge_bounded(tokens, end, 256)? + .checked_add(extra) + .ok_or(Error::Overflow)?; + if end >= u64::from(binding.input_constants().context_length()) || end >= crate::qwen_forward::contract::serving_cells() { + return Err(Error::InvalidPosition); + } + if total > host_remaining.min(HOST_LIMIT) { + return Err(Error::InputAllocation); + } + Ok(()) + } + + pub(in crate::qwen_forward) fn begin_mtp_verification( + session: &'session mut QwenSession<'driver>, + binding: &ModelBinding, + tokens: &[TokenId], + host_remaining: usize, + ) -> Result { + Self::preflight_mtp_verification(session, binding, tokens.len(), host_remaining)?; + let end = session + .next_position + .checked_add(tokens.len() as u64) + .ok_or(Error::Overflow)?; + let extra = verification_extra_charge(tokens.len(), end)?; + let available = host_remaining + .min(HOST_LIMIT) + .checked_sub(extra) + .ok_or(Error::InputAllocation)?; + // Both charges are admitted before rows, pointer journals or numeric + // producers allocate. This preserves the old admission and VRAM cap. + let mut txn = Self::begin_windowed256(session, binding, tokens, None, available)?; + let mut states = Vec::new(); + states + .try_reserve_exact(tokens.len()) + .map_err(|_| Error::InputAllocation)?; + states.resize_with(tokens.len(), || PrefixState { + ple: None, + gdn: std::array::from_fn(|_| None), + device_gdn: std::array::from_fn(|_| None), + qsa: std::array::from_fn(|_| None), + head: None, + }); + txn.verification = Some(VerificationJournal { states, device_lease: None }); + Ok(txn) + } + + pub(in crate::qwen_forward) fn enable_device_gdn_verification(&mut self,binding:&ModelBinding,cache:&crate::qwen_forward::dense_weight_cache::DenseWeightCache<'_>,host_remaining:usize)->Result<()> { + self.check()?;self.origin.validate(self.session)?; + let context=self.session.mtp_context()?; + let Some(workspace)=cache.gdn_verification_workspace(binding,context)? else{return Ok(());}; + let metadata=workspace.try_borrow().map_err(|_|Error::IdentityMismatch)?.metadata_bytes()?; + let charged=host_charge_bounded(self.rows.len(),self.end,256)? + .checked_add(verification_extra_charge(self.rows.len(),self.end)?).and_then(|n|n.checked_add(metadata)).ok_or(Error::Overflow)?; + if charged>host_remaining.min(HOST_LIMIT){return Err(Error::InputAllocation);} + let journal=self.verification.as_mut().ok_or(Error::IdentityMismatch)?; + if journal.device_lease.is_some() || self.rows.len()>3 || self.next_layer!=0 || self.next_row!=0 {return Err(Error::IdentityMismatch);} + let lease=workspace.try_borrow_mut().map_err(|_|Error::IdentityMismatch)?.begin(&self.session.binding,&self.origin,&self.chunk,self.rows.len())?; + journal.device_lease=Some(lease);Ok(()) + } + pub(in crate::qwen_forward) fn device_gdn_lease(&self)->Result>>{ + let lease=self.verification.as_ref().and_then(|j|j.device_lease.as_ref()); + if lease.is_none(){return Ok(None);} + self.check()?;self.origin.validate(self.session)?; + if let Some(lease)=lease{lease.validate(&self.session.binding,&self.origin,&self.chunk,self.rows.len())?;} + Ok(lease.cloned()) + } + pub(in super::super::super) fn record_device_gdn(&mut self,index:usize,layer:LayerId,proof:Rc)->Result<()> { + let lease=self.device_gdn_lease()?.ok_or(Error::IdentityMismatch)?; + let row=self.rows.get(index).ok_or(Error::IdentityMismatch)?; + proof.validate(&lease,layer,index,TokenLayer::new(row.token,row.position,layer))?; + let state=self.verification.as_mut().ok_or(Error::IdentityMismatch)?.states.get_mut(index).ok_or(Error::IdentityMismatch)?; + if state.gdn[layer.get() as usize].is_some() || state.device_gdn[layer.get() as usize].is_some(){return Err(Error::IdentityMismatch);} + state.device_gdn[layer.get() as usize]=Some(proof);Ok(()) + } + pub(in super::super) fn replay_device_prefix(&self,binding:&ModelBinding,cache:&crate::qwen_forward::dense_weight_cache::DenseWeightCache<'_>,count:usize,mut cancelled:impl FnMut()->bool)->Result<[Option;STATE_CAPACITY]>{ + let lease=self.device_gdn_lease()?.ok_or(Error::IdentityMismatch)?; + if count==0 || count>self.rows.len(){return Err(Error::IdentityMismatch);} + let workspace=cache.gdn_verification_workspace(binding,self.session.mtp_context()?)?.ok_or(Error::IdentityMismatch)?; + let mut sealed=std::array::from_fn(|_|None); + for (slot,output) in sealed.iter_mut().enumerate(){ + if !self.session.gdn_layers[slot]{continue;} + if cancelled(){return Err(Error::Unsupported(Stage::Executor));} + self.origin.validate(self.session)?; + let layer=LayerId::new(slot as u64,Dimension::new(48)?)?; + let mut proofs=Vec::new();proofs.try_reserve_exact(count).map_err(|_|Error::InputAllocation)?; + for index in 0..count { + let state=self.validate_verification_state(index)?; + let proof=state.device_gdn[slot].as_ref().ok_or(Error::IdentityMismatch)?; + let actual=&self.rows[index];proof.validate(&lease,layer,index,TokenLayer::new(actual.token,actual.position,layer))?; + proofs.push(proof.clone()); + } + let prior=workspace.try_borrow_mut().map_err(|_|Error::IdentityMismatch)?.replay(&lease,&proofs,&mut cancelled)?; + prior.validate(&self.session.binding,&self.session.gdn_owner,layer,Position::new(self.start_position().checked_add(count as u64).ok_or(Error::Overflow)?,crate::qwen_forward::contract::position_dimension())?)?; + *output=Some(prior); + } + if cancelled(){return Err(Error::Unsupported(Stage::Executor));} + self.origin.validate(self.session)?;Ok(sealed) + } + pub(in crate::qwen_forward) fn seal_device_gdn_prefix(&mut self,binding:&ModelBinding,cache:&crate::qwen_forward::dense_weight_cache::DenseWeightCache<'_>,prefix:&VerifiedTargetPrefix,cancelled:impl FnMut()->bool)->Result<()> { + self.validate_verified_prefix(prefix)?; + if self.device_gdn_lease()?.is_none(){return Ok(());} + // Stage ALL36 actual replayed canonical priors before either owner mutation. + let sealed=self.replay_device_prefix(binding,cache,prefix.count,cancelled)?; + self.verification.as_mut().ok_or(Error::IdentityMismatch)?.states[prefix.count-1].gdn=sealed;Ok(()) + } + #[cfg(all(test,any(target_os="linux",target_os="windows"),target_arch="x86_64"))] + pub(in crate::qwen_forward) fn materialize_device_gdn_observer(&mut self,binding:&ModelBinding,cache:&crate::qwen_forward::dense_weight_cache::DenseWeightCache<'_>,mut cancelled:impl FnMut()->bool)->Result<()> { + if self.device_gdn_lease()?.is_none() || !crate::qwen_forward::mtp_decode::batch_gpu::collecting(){return Ok(());} + for count in 1..=self.rows.len(){ + let sealed=self.replay_device_prefix(binding,cache,count,&mut cancelled)?; + self.verification.as_mut().ok_or(Error::IdentityMismatch)?.states[count-1].gdn=sealed; + } + Ok(()) + } + pub(in super::super) fn verification_row_position(&self, index: usize, position: Position) -> Result { + self.check()?; + let row = self.rows.get(index).ok_or(Error::IdentityMismatch)?; + if row.position != position || self.gdn_chunk.is_some() { + return Err(Error::IdentityMismatch); + } + Position::new( + position.get().checked_add(1).ok_or(Error::Overflow)?, + crate::qwen_forward::contract::position_dimension(), + ) + } + // PLE completes before this layer's GDN recurrence consumes its rows. + // Its genuine next prior may be journaled without claiming a GDN prior. + pub(in super::super) fn verification_ple_row_position(&self, index: usize, position: Position) -> Result { + let Some(journal) = self.gdn_chunk.as_ref() else { + return self.verification_row_position(index, position); + }; + let (first, end) = self.phase_span()?; + let row = self.rows.get(index).ok_or(Error::IdentityMismatch)?; + let start = &journal.start.0; + journal.start.validate_binding(&self.session.binding)?; + if !Rc::ptr_eq(&start.chunk, &self.chunk) + || start.layer.get() != 1 + || self.next_layer != 1 + || start.count != self.rows.len() + || start.end != self.end + || self.rows.first().is_none_or(|row| row.position != start.first) + || start.first.get().checked_add(index as u64) != Some(position.get()) + || row.position != position + || row.completed != 1 + || index < first + || index >= end + || self.next_row != first + || self.attention_layer != Some(start.layer) + || self.attention_next != index + || self.batch_layer.is_some() + || self.attention_authorized.is_some() + || journal.accepted != first + { + return Err(Error::IdentityMismatch); + } + start.prior.validate(&self.session.binding, &self.session.gdn_owner, + start.layer, start.first)?; + Position::new(position.get().checked_add(1).ok_or(Error::Overflow)?, + crate::qwen_forward::contract::position_dimension()) + } + pub(in super::super::super) fn record_verification_ple( + &mut self, + index: usize, + position: Position, + ) -> Result<()> { + if self.verification.is_none() { + return Ok(()); + } + let end = self.verification_ple_row_position(index, position)?; + let prior = self + .next_ple + .as_ref() + .ok_or(Error::Unsupported(Stage::Input))?; + prior.validate(&self.session.binding, &self.session.ple_owner, end)?; + let journal = self.verification.as_mut().ok_or(Error::IdentityMismatch)?; + let state = journal + .states + .get_mut(index) + .ok_or(Error::IdentityMismatch)?; + if state.ple.is_some() { + return Err(Error::IdentityMismatch); + } + state.ple = Some(prior.clone()); + Ok(()) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/session_chunk_verify/impl_qwenchunktxn/impl_qwenchunktxn_2_2.rs b/crates/leleka-runtime/src/qwen_forward/session_chunk_verify/impl_qwenchunktxn/impl_qwenchunktxn_2_2.rs new file mode 100644 index 00000000..4476bf1b --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/session_chunk_verify/impl_qwenchunktxn/impl_qwenchunktxn_2_2.rs @@ -0,0 +1,246 @@ +//! Moved out of the parent module by STRA-338: impl QwenChunkTxn (2). + +#[allow(unused_imports)] +use super::*; + + + +impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { + pub(in super::super::super) fn record_verification_prior( + &mut self, + index: usize, + layer: LayerId, + position: Position, + ) -> Result<()> { + if self.verification.is_none() { + return Ok(()); + } + let end = self.verification_row_position(index, position)?; + let slot = layer.get() as usize; + if slot >= STATE_CAPACITY { + return Err(Error::InvalidLayer); + } + // Only the consumed producer prior is cloned; no numeric constructor, + // stale initial state or advanced metadata is used for a prefix. + if self.session.gdn_layers[slot] { + let prior = self.next_gdn[slot] + .as_ref() + .ok_or(Error::Unsupported(Stage::Gdn))?; + prior.validate(&self.session.binding, &self.session.gdn_owner, layer, end)?; + let state = self + .verification + .as_mut() + .ok_or(Error::IdentityMismatch)? + .states + .get_mut(index) + .ok_or(Error::IdentityMismatch)?; + if state.gdn[slot].is_some() { + return Err(Error::IdentityMismatch); + } + state.gdn[slot] = Some(prior.clone()); + } else if self.session.qsa_layers[slot] { + let prior = self.next_qsa[slot] + .as_ref() + .ok_or(Error::Unsupported(Stage::QsaIndex))?; + prior.validate(&self.session.binding, &self.session.qsa_owner, layer, end)?; + let state = self + .verification + .as_mut() + .ok_or(Error::IdentityMismatch)? + .states + .get_mut(index) + .ok_or(Error::IdentityMismatch)?; + if state.qsa[slot].is_some() { + return Err(Error::IdentityMismatch); + } + state.qsa[slot] = Some(prior.clone()); + } else { + return Err(Error::InvalidLayer); + } + Ok(()) + } + pub(in super::super::super) fn validate_verification_state(&self, index: usize) -> Result<&PrefixState> { + self.check()?; + let row = self.rows.get(index).ok_or(Error::IdentityMismatch)?; + if row.completed != 48 || self.gdn_chunk.is_some() { + return Err(Error::IdentityMismatch); + } + let end = Position::new( + row.position.get().checked_add(1).ok_or(Error::Overflow)?, + crate::qwen_forward::contract::position_dimension(), + )?; + let state = self + .verification + .as_ref() + .ok_or(Error::IdentityMismatch)? + .states + .get(index) + .ok_or(Error::IdentityMismatch)?; + if self.session.ple_required { + state + .ple + .as_ref() + .ok_or(Error::Unsupported(Stage::Input))? + .validate(&self.session.binding, &self.session.ple_owner, end)?; + } else if state.ple.is_some() { + return Err(Error::IdentityMismatch); + } + for slot in 0..STATE_CAPACITY { + let layer = LayerId::new(slot as u64, Dimension::new(48)?)?; + if self.session.gdn_layers[slot] { + if let Some(lease)=self.verification.as_ref().and_then(|j|j.device_lease.as_ref()) { + state.device_gdn[slot].as_ref().ok_or(Error::Unsupported(Stage::Gdn))? + .validate(lease,layer,index,TokenLayer::new(row.token,row.position,layer))?; + if let Some(prior)=&state.gdn[slot] {prior.validate(&self.session.binding,&self.session.gdn_owner,layer,end)?;} + } else { + state.gdn[slot] + .as_ref() + .ok_or(Error::Unsupported(Stage::Gdn))? + .validate(&self.session.binding, &self.session.gdn_owner, layer, end)?; + } + } else if state.gdn[slot].is_some() || state.device_gdn[slot].is_some() { + return Err(Error::IdentityMismatch); + } + if self.session.qsa_layers[slot] { + state.qsa[slot] + .as_ref() + .ok_or(Error::Unsupported(Stage::QsaIndex))? + .validate(&self.session.binding, &self.session.qsa_owner, layer, end)?; + } else if state.qsa[slot].is_some() { + return Err(Error::IdentityMismatch); + } + } + Ok(state) + } + + pub(in crate::qwen_forward) fn finish_mtp_verification( + &mut self, + residuals: &[Option], + mut execute_head: impl FnMut( + &mut QwenStepTxn<'_, 'driver>, + &InjectedResidual, + ) -> Result, + ) -> Result<()> { + let result = self.finish_mtp_verification_inner(residuals, &mut execute_head); + if let Err(error) = &result { + self.session.note_mtp_failure(error); + self.aborted = true; + } + result + } + pub(in super::super) fn finish_mtp_verification_inner( + &mut self, + residuals: &[Option], + execute_head: &mut impl FnMut( + &mut QwenStepTxn<'_, 'driver>, + &InjectedResidual, + ) -> Result, + ) -> Result<()> { + self.check()?; + if self.finished + || self.known_next.is_some() + || self + .verification + .as_ref() + .is_none_or(|j| j.states.len() != self.rows.len()) + || self.next_layer != 48 + || self.next_row != 0 + || self.active_micro.is_some() + || self.micro_cursor != 0 + || residuals.len() != self.rows.len() + || !self.witnesses.is_empty() + { + return Err(Error::IdentityMismatch); + } + for (index, residual) in residuals.iter().enumerate() { + let row = &self.rows[index]; + let residual = residual + .as_ref() + .ok_or(Error::Unsupported(Stage::Executor))?; + residual.validate_origin(&self.session.binding, GrRole::Ffn(47))?; + residual.identity().validate( + row.token, + row.position, + LayerId::new(47, Dimension::new(48)?)?, + )?; + if residual.streams().len() != 10240 + || residual.streams().iter().any(|v| !v.is_finite()) + { + return Err(Error::NonFinite); + } + let state = self.validate_verification_state(index)?; + let mut view = self.stage_view(index)?; + // The head view has the actual complete row state, never the full + // chunk's final state relabelled with an intermediate position. + view.ple_state = state.ple.clone(); + if self.device_gdn_lease()?.is_none() || state.gdn.iter().any(Option::is_some) { + view.gdn_states = state.gdn.clone(); + } + // Device-only rows keep original unused canonical priors in the head + // view; actual current provisional rows were authenticated above. + // A diagnostic snapshot uses only real replay-materialized states. + view.qsa_states = state.qsa.clone(); + let mut step = view.begin(row.token, row.position)?; + step.input = row.input.clone(); + step.completed_layers = 48; + let head = execute_head(&mut step, residual)?; + if step.forward_output != Some(head) || step.prefill_finished { + return Err(Error::IdentityMismatch); + } + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if crate::qwen_forward::mtp_decode::batch_gpu::collecting() { + // Observation of the validated completed journal, never a + // session/Origin constructor or publication/restore authority. + let snapshot = super::super::super::super::ResetReplaySnapshot { + binding: self.session.binding.clone(), + predecessors: [ + row.predecessors[1], + i32::try_from(row.token.get()).map_err(|_| Error::InvalidToken)?, + ], + next_position: row.position.get().checked_add(1).ok_or(Error::Overflow)?, + layer_count: self.session.layer_count, + ple_required: self.session.ple_required, + ple: state.ple.clone(), + gdn_layers: self.session.gdn_layers, + gdn: state.gdn.clone(), + qsa_layers: self.session.qsa_layers, + qsa: state.qsa.clone(), + }; + crate::qwen_forward::mtp_decode::batch_gpu::collect_row( + row.token, + row.position, + head, + residual.streams(), + snapshot, + )?; + } + let mut streams = Vec::new(); + streams + .try_reserve_exact(10240) + .map_err(|_| Error::InputAllocation)?; + streams.extend_from_slice(residual.streams()); + self.witnesses.push(ChunkRowResidual { + binding: self.session.binding.clone(), + chunk: self.chunk.clone(), + origin: self.origin.clone(), + token: row.token, + position: row.position, + known_next: self.rows.get(index + 1).map(|r| r.token), + streams: Rc::new(streams.into_boxed_slice()), + }); + self.verification + .as_mut() + .ok_or(Error::IdentityMismatch)? + .states[index] + .head = Some(head); + } + self.output = self + .verification + .as_ref() + .and_then(|j| j.states.last()) + .and_then(|s| s.head); + self.finished = true; + self.validate_publish()?; + Ok(()) + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/session_chunk_verify/impl_qwenchunktxn/impl_qwenchunktxn_3.rs b/crates/leleka-runtime/src/qwen_forward/session_chunk_verify/impl_qwenchunktxn/impl_qwenchunktxn_3.rs new file mode 100644 index 00000000..83258f80 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/session_chunk_verify/impl_qwenchunktxn/impl_qwenchunktxn_3.rs @@ -0,0 +1,131 @@ +//! Moved out of the parent module by STRA-338: impl QwenChunkTxn (3). + +#[allow(unused_imports)] +use super::*; + + + +impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { + + pub(in crate::qwen_forward) fn select_verified_prefix( + &self, + binding: &ModelBinding, + source: &TargetStepProduct, + eos: Option, + ) -> Result { + self.validate_publish()?; + if !(1..=4).contains(&self.rows.len()) { + return Err(Error::InvalidDimension); + } + let (_, position, _, source_origin) = source.mtp_source(binding, self.session)?; + if !self.session.binding.matches(&binding.identity()) + || !source_origin.same_prefix(&self.origin) + || position.get().checked_add(1) != Some(self.start_position()) + { + return Err(Error::IdentityMismatch); + } + let seed = source.predicted(self.session)?; + let mut tokens = [seed; 4]; + let mut heads = [seed; 4]; + // Every row is genuine and complete, including a rejected tail. + for index in 0..self.rows.len() { + tokens[index] = self.rows[index].token; + heads[index] = self + .validate_verification_state(index)? + .head + .ok_or(Error::Unsupported(Stage::Output))?; + } + let (count, expected) = greedy_prefix( + seed, + eos, + &tokens[..self.rows.len()], + &heads[..self.rows.len()], + )?; + Ok(VerifiedTargetPrefix { + chunk: self.chunk.clone(), + origin: self.origin.clone(), + count, + next: expected, + }) + } + + pub(in crate::qwen_forward) fn validate_verified_prefix( + &self, + prefix: &VerifiedTargetPrefix, + ) -> Result<()> { + self.validate_publish()?; + if !Rc::ptr_eq(&prefix.chunk, &self.chunk) + || !prefix.origin.same_prefix(&self.origin) + || prefix.count == 0 + || prefix.count > self.rows.len() + { + return Err(Error::IdentityMismatch); + } + prefix.origin.validate(self.session)?; + for index in 0..self.rows.len() { + self.validate_verification_state(index)? + .head + .ok_or(Error::Unsupported(Stage::Output))?; + } + if self.validate_verification_state(prefix.count - 1)?.head != Some(prefix.next) { + return Err(Error::IdentityMismatch); + } + Ok(()) + } + + pub(in crate::qwen_forward) fn publish_verified_joint( + mut self, + prefix: VerifiedTargetPrefix, + draft: impl VerifiedDraftPublication, + ) -> Result { + self.validate_verified_prefix(&prefix)?; + draft.validate(&self, &prefix)?; + self.session.complete_cuda()?; + let row = &self.rows[prefix.count - 1]; + let source = &self.witnesses[prefix.count - 1]; + let predecessors = [ + row.predecessors[1], + i32::try_from(row.token.get()).map_err(|_| Error::InvalidToken)?, + ]; + let end = row.position.get().checked_add(1).ok_or(Error::Overflow)?; + let mut streams = Vec::new(); + streams + .try_reserve_exact(10240) + .map_err(|_| Error::InputAllocation)?; + streams.extend_from_slice(source.streams.as_ref()); + let streams = streams.into_boxed_slice(); + let binding = source.binding.clone(); + let token = row.token; + let position = row.position; + let journal = self.verification.take().ok_or(Error::IdentityMismatch)?; + let state = journal + .states + .into_iter() + .nth(prefix.count - 1) + .ok_or(Error::IdentityMismatch)?; + if journal.device_lease.is_some() { + let end_position=Position::new(end,crate::qwen_forward::contract::position_dimension())?; + for slot in 0..STATE_CAPACITY {if self.session.gdn_layers[slot] { + state.gdn[slot].as_ref().ok_or(Error::Unsupported(Stage::Gdn))? + .validate(&self.session.binding,&self.session.gdn_owner,LayerId::new(slot as u64,Dimension::new(48)?)?,end_position)?; + }} + } + // All fallible work precedes either owner mutation. Rejected tail + // states and row witnesses are dropped; no epoch or position rewind. + self.session.ple_state = state.ple; + self.session.gdn_states = state.gdn; + self.session.qsa_states = state.qsa; + self.session.predecessors = predecessors; + self.session.next_position = end; + draft.publish(); + let origin = super::super::super::super::checkpoint::committed_origin(self.session); + Ok(ChunkCommit { + binding, + token, + position, + output: Some(prefix.next), + streams, + origin, + }) + } +} diff --git a/scripts/dev/rustsplit/implsplit.py b/scripts/dev/rustsplit/implsplit.py new file mode 100644 index 00000000..f4889ef8 --- /dev/null +++ b/scripts/dev/rustsplit/implsplit.py @@ -0,0 +1,59 @@ +"""Cut one long inherent `impl` block into several `impl` blocks of the same type, between its associated items.""" +import re + +from .items import parse_items, significant +from .lexer import tokenize + +DOC_LINE = re.compile(r"^\s*(///|#\[\s*doc\b)") + + +def _header_end(chunk): + """(index of the opening `{` of the impl body, index of its closing `}`) in `chunk`, or None.""" + sig = significant(tokenize(chunk)) + keyword = next((k for k, t in enumerate(sig) if t.text == "impl"), None) + if keyword is None: + return None + depth, opening = 0, None + for tok in sig[keyword:]: + depth += (tok.text in "([") - (tok.text in ")]") + if tok.text == "{" and depth == 0: + opening = tok.start + break + return (opening, sig[-1].start) if opening is not None and sig[-1].text == "}" else None + + +def _without_docs(header): + return "\n".join(row for row in header.split("\n") if not DOC_LINE.match(row)) + + +def _line_count(text): + return text.count("\n") + 1 + + +def _pack(items, body, target): + """Consecutive associated items packed into parts of about `target` lines.""" + parts, current = [], [] + for item in items: + if current and _line_count(body[current[0].start:item.end]) > target: + parts.append(current) + current = [] + current.append(item) + return parts + ([current] if current else []) + + +def split_impl(chunk, target): + """The impl blocks that replace `chunk`: one when it is short or has fewer than two associated items.""" + bounds = _header_end(chunk) + if bounds is None or _line_count(chunk) <= target: + return [chunk] + opening, closing = bounds + header, body = chunk[:opening + 1], chunk[opening + 1:closing] + parts = _pack(parse_items(body), body, target) + if len(parts) < 2: + return [chunk] + blocks = [] + for n, part in enumerate(parts): + end = len(body) if n == len(parts) - 1 else part[-1].end + text = header if n == 0 else _without_docs(header) + blocks.append(text + body[0 if n == 0 else part[0].start:end].rstrip() + "\n}") + return blocks diff --git a/scripts/dev/rustsplit/split.py b/scripts/dev/rustsplit/split.py index ac14ba05..503a525d 100644 --- a/scripts/dev/rustsplit/split.py +++ b/scripts/dev/rustsplit/split.py @@ -2,6 +2,7 @@ import re from dataclasses import dataclass, field +from .implsplit import split_impl from .items import cfg_attributes, parse_items, visibility_text from .retarget import retarget @@ -35,23 +36,35 @@ def unique(name, used): return candidate +class Packer: + """Fills groups of about `target` lines with chunks, in order.""" + + def __init__(self, target, reserved): + self.target, self.used, self.groups = target, set(reserved), [] + + def add(self, item, part, label): + """Append one chunk, a whole item or one block of a cut impl (`label` is "" or "_2", "_3" ... for cut blocks).""" + chunk = retarget(part, item.kind, item.inherent) + lines = chunk.count("\n") + 1 + if not self.groups or self.groups[-1].lines + lines > self.target: + self.groups.append(Group(unique(slug(item) + label, self.used))) + group = self.groups[-1] + group.chunks.append(chunk) + group.members.append(f"{item.kind} {item.name}" + (f" ({label.strip('_')})" if label else "")) + if item.kind == "fn": + group.exports.append((cfg_attributes(item.attrs), visibility_text(part), item.name)) + group.lines += lines + + def group_items(text, items, target, reserved): """Pack the movable items, in file order, into groups of about `target` lines.""" - groups, used = [], set(reserved) - for item in items: - if not movable(item): - continue + packer = Packer(target, reserved) + for item in (i for i in items if movable(i)): original = text[item.start:item.end] - chunk = retarget(original, item.kind, item.inherent) - lines = chunk.count("\n") + 1 - if not groups or groups[-1].lines + lines > target: - groups.append(Group(unique(slug(item), used))) - groups[-1].chunks.append(chunk) - groups[-1].members.append(f"{item.kind} {item.name}") - if item.kind == "fn": - groups[-1].exports.append((cfg_attributes(item.attrs), visibility_text(original), item.name)) - groups[-1].lines += lines - return groups + parts = split_impl(original, target) if item.kind == "impl" and item.inherent else [original] + for number, part in enumerate(parts, 1): + packer.add(item, part, f"_{number}" if number > 1 else "") + return packer.groups def remove_ranges(text, ranges): diff --git a/scripts/dev/rustsplit_test.py b/scripts/dev/rustsplit_test.py index 4855f19d..da9d8015 100644 --- a/scripts/dev/rustsplit_test.py +++ b/scripts/dev/rustsplit_test.py @@ -127,6 +127,16 @@ class Planning(unittest.TestCase): parent, _ = plan_split('#[cfg(unix)]\npub fn a() {}\n', 100) self.assertIn('#[cfg(unix)]\n#[allow(unused_imports)]\npub use a_fn::a;', parent) + def test_a_long_inherent_impl_is_cut_between_its_methods(self): + methods = "".join(f" fn m{n}(&self) -> u32 {{\n {n}\n }}\n" for n in range(6)) + source = f"/// Docs.\nimpl Big\nwhere\n T: Copy,\n{{\n{methods}}}\n" + parent, children = plan_split(source, 8) + text = "".join(children.values()) + self.assertEqual(text.count("impl Big"), 3) + self.assertEqual(text.count("/// Docs."), 1) + self.assertEqual(len(re.findall(r"fn m\d", text)), 6) + self.assertEqual(text.count("{") , text.count("}")) + def test_nothing_to_move_gives_none(self): self.assertIsNone(plan_split("use a::b;\nconst X: u8 = 1;\n", 100))