qualia_core_db/platform/gpu.rs
1//! GPU integration for calculus modality.
2//!
3//! Provides cross-platform GPU compute shader execution for numerical integration
4//! and differential equation solving via portable `wgpu` (Vulkan / DX12 / Metal /
5//! WebGPU). The engine is **vendor-neutral**: there is no CUDA/cuFile path. The
6//! former NVIDIA GPUDirect-Storage bridge was removed; heterogeneous dispatch,
7//! mixed-precision policy, and the vendor-neutral storage path (mmap + staging
8//! upload) live in [`super::hetero_dispatch`].
9//!
10//! ## Architecture
11//!
12//! - **WebGPU (`wgpu`)**: portable compute on every backend; the single GPU path.
13//! - **Storage**: NVMe → OS page cache (`mmap`, `super::host`) → GPU staging upload.
14//! (NVIDIA GDS's true NVMe→VRAM DMA was deliberately declined — vendor-lock off
15//! the affordability critical path; see `hetero_dispatch.rs`.)
16//! - **State Tracking**: GPU results packed into Quin metadata field.
17#![cfg(all(not(target_arch = "wasm32"), feature = "gpu-runtime"))]
18
19use crate::NQuin;
20use std::io::Seek;
21use std::path::Path;
22
23/// The platform GPU integrator — uniformly the portable `wgpu` integrator on every
24/// backend. (The former CUDA/cuFile `CudaIntegrator` alias was removed for vendor
25/// neutrality; heterogeneous routing/fallback now lives in `super::hetero_dispatch`.)
26pub use WebGpuIntegrator as PlatformGpuIntegrator;
27
28// ─── Errors ─────────────────────────────────────────────────────────────────────
29
30pub use etalon_wgsl_forge::numerical::compute_passes::calculus::{GpuError, WebGpuIntegrator};
31
32// ─── GPU Integration Trait ─────────────────────────────────────────────────────
33
34/// Platform-agnostic GPU integration interface.
35///
36/// Abstracts over DirectStorage, GPUDirect, and WebGPU to provide a unified
37/// API for GPU-accelerated calculus operations.
38pub trait GpuIntegrator: Send {
39 /// Executes Simpson's rule integration on the GPU.
40 ///
41 /// # Arguments
42 ///
43 /// * `file_path` - Path to the data file (NVMe storage)
44 /// * `offset` - Byte offset in file (must be 4096-byte aligned)
45 /// * `size` - Number of bytes to process (must be 4096-byte aligned)
46 /// * `step_size` - Integration step size (f32 for Quin packing)
47 ///
48 /// # Returns
49 ///
50 /// The integrated value as f64, ready to pack into Quin metadata.
51 fn integrate_simpsons_gpu(
52 &mut self,
53 file_path: &Path,
54 offset: u64,
55 size: u64,
56 step_size: f32,
57 ) -> Result<f64, GpuError>;
58
59 /// Executes composite Simpson 3/8 quadrature on the GPU.
60 fn integrate_simpson_38_gpu(
61 &mut self,
62 file_path: &Path,
63 offset: u64,
64 size: u64,
65 step_size: f32,
66 ) -> Result<f64, GpuError>;
67
68 /// Returns available VRAM in bytes.
69 fn available_vram(&self) -> u64;
70}
71
72// ─── WebGPU Fallback Implementation ─────────────────────────────────────────────
73
74/// WebGPU-based GPU integrator (cross-platform fallback).
75///
76/// Uses wgpu to execute compute shaders when DirectStorage or GPUDirect
77/// are unavailable. Data flows: NVMe → CPU RAM → GPU VRAM.
78
79#[async_trait::async_trait]
80impl GpuIntegrator for WebGpuIntegrator {
81 fn integrate_simpsons_gpu(
82 &mut self,
83 file_path: &Path,
84 offset: u64,
85 size: u64,
86 step_size: f32,
87 ) -> Result<f64, GpuError> {
88 // Read data from file (CPU RAM path - fallback)
89 let mut file = std::fs::File::open(file_path)
90 .map_err(|e| GpuError::WebGPUUnavailable(format!("File open failed: {e}")))?;
91
92 use std::io::Read;
93 file.seek(std::io::SeekFrom::Start(offset))
94 .map_err(|e| GpuError::WebGPUUnavailable(format!("Seek failed: {e}")))?;
95
96 let mut buffer = vec![0u8; size as usize];
97 file.read_exact(&mut buffer)
98 .map_err(|e| GpuError::WebGPUUnavailable(format!("Read failed: {e}")))?;
99
100 // Execute on GPU
101 // Note: This is a blocking call in an async context - in production,
102 // we'd use a thread pool or async executor
103 let result = self.execute_compute(&buffer, step_size);
104
105 // For now, we'll block on the async result using the current runtime
106 // In production, this should be properly integrated with the async runtime
107 let handle = tokio::runtime::Handle::try_current()
108 .map_err(|e| GpuError::WebGPUUnavailable(format!("Tokio handle failed: {e}")))?;
109 handle.block_on(result)
110 }
111
112 fn integrate_simpson_38_gpu(
113 &mut self,
114 file_path: &Path,
115 offset: u64,
116 size: u64,
117 step_size: f32,
118 ) -> Result<f64, GpuError> {
119 // Read data from file (CPU RAM path)
120 let mut file = std::fs::File::open(file_path)
121 .map_err(|e| GpuError::WebGPUUnavailable(format!("File open failed: {e}")))?;
122
123 use std::io::Read;
124 file.seek(std::io::SeekFrom::Start(offset))
125 .map_err(|e| GpuError::WebGPUUnavailable(format!("Seek failed: {e}")))?;
126
127 let mut buffer = vec![0u8; size as usize];
128 file.read_exact(&mut buffer)
129 .map_err(|e| GpuError::WebGPUUnavailable(format!("Read failed: {e}")))?;
130
131 // Dispatch the composite Simpson 3/8 compute shader.
132 let handle = tokio::runtime::Handle::try_current()
133 .map_err(|e| GpuError::WebGPUUnavailable(format!("Tokio handle failed: {e}")))?;
134 handle.block_on(self.execute_simpson_38_compute(&buffer, step_size))
135 }
136
137 fn available_vram(&self) -> u64 {
138 // Use max_buffer_size from device limits as a practical proxy for available VRAM.
139 // On discrete GPUs this cap is typically set to the full VRAM size; on integrated
140 // GPUs it reflects the shared system memory window.
141 self.max_buffer_size()
142 }
143}
144
145// ─── GPU State Tracking ─────────────────────────────────────────────────────────
146
147/// Packs GPU computation result into Quin metadata field.
148///
149/// When the GPU finishes processing, the scalar result is written back
150/// to the host and packed into the Quin's metadata field for SLG VM resumption.
151pub fn pack_gpu_result_into_quin(quin: &mut NQuin, result: f64) {
152 quin.metadata = f64::to_bits(result);
153}
154
155/// Extracts GPU computation result from Quin metadata field.
156pub fn extract_gpu_result_from_quin(quin: &NQuin) -> f64 {
157 f64::from_bits(quin.metadata)
158}
159
160/// Creates a suspended Quin for GPU computation.
161///
162/// Packs the computation parameters into the Quin fields so the SLG VM
163/// can track the in-flight GPU operation.
164pub fn create_gpu_job_quin(job_id: u64, opcode: u8, file_offset: u64, step_size: f32) -> NQuin {
165 let mut quin = NQuin::default();
166 quin.subject = job_id;
167 quin.predicate = (opcode as u64) | (q_hash("calculus:gpu") << 8);
168 quin.object = file_offset;
169 quin.context = f32::to_bits(step_size) as u64;
170 quin.metadata = 0; // Will be filled with result
171 quin.parity = 0; // Will be computed
172 quin
173}
174
175// ─── Helper Functions ───────────────────────────────────────────────────────────
176
177/// Compile-time hashing function (reused from lib.rs) — 60-bit identity, in
178/// lockstep with `crate::q_hash` so the "calculus:gpu" predicate path joins.
179const fn q_hash(s: &str) -> u64 {
180 let mut hash: u64 = 0xcbf29ce484222325;
181 let bytes = s.as_bytes();
182 let mut i = 0;
183 while i < bytes.len() {
184 hash = hash ^ (bytes[i] as u64);
185 hash = hash.wrapping_mul(0x100000001b3);
186 i += 1;
187 }
188 hash & 0x0FFF_FFFF_FFFF_FFFF
189}
190
191// ─── Tests ─────────────────────────────────────────────────────────────────────
192
193#[cfg(test)]
194mod tests {
195 use super::*;
196
197 #[test]
198 fn test_gpu_result_packing() {
199 let result = 42.5f64;
200 let mut quin = NQuin::default();
201
202 pack_gpu_result_into_quin(&mut quin, result);
203
204 let extracted = extract_gpu_result_from_quin(&quin);
205 assert_eq!(extracted, result);
206 }
207
208 #[test]
209 fn test_gpu_job_quin_creation() {
210 let quin = create_gpu_job_quin(
211 12345, 0x50, // OP_SIMPSONS_INTEGRATION
212 4096, 0.001,
213 );
214
215 assert_eq!(quin.subject, 12345);
216 assert_eq!(quin.object, 4096);
217 assert_eq!(f32::from_bits(quin.context as u32), 0.001);
218 }
219
220 #[cfg(feature = "wgsl-forge")]
221 #[test]
222 fn calculus_shader_is_portable_and_semantically_named() {
223 let source = etalon_wgsl_forge::numerical::compute_passes::calculus::CALCULUS_WGSL;
224 crate::wgsl_forge::validate_wgsl(source).expect("calculus WGSL must Naga-validate");
225 assert!(!source.contains("array<f64>"));
226 assert!(!source.contains(": f64"));
227 assert!(!source.contains("rk4_step"));
228 assert!(source.contains("simpson_38_integration"));
229 }
230}