Skip to main content

qualia_core_db/platform/
npu_ffi.rs

1//! GPU sieve and native host domain bridges
2//! Uses `wgpu` to execute cross-platform GPU compute shaders (Vulkan/DX12/Metal/WebGPU)
3//! that filter the 5th Vector of the NQuin parallel arrays.
4
5#[cfg(all(not(target_arch = "wasm32"), feature = "gpu-runtime"))]
6pub mod gpu_sieve {
7    use crate::NQuin;
8    use etalon_wgsl_forge::numerical::compute_passes::bitmask::BitmaskFilter;
9    pub use etalon_wgsl_forge::numerical::compute_passes::bitmask::FilterMask64;
10
11    pub struct SieveOrchestrator {
12        filter: BitmaskFilter,
13    }
14    impl SieveOrchestrator {
15        pub async fn new() -> Option<Self> {
16            Some(Self {
17                filter: BitmaskFilter::new(include_str!("../shaders/sieve.wgsl")).await?,
18            })
19        }
20        pub async fn execute_sieve(&self, quins: &[NQuin], mask: u64) -> Option<Vec<u32>> {
21            self.filter
22                .execute_sieve(bytemuck::cast_slice(quins), quins.len(), mask, || {
23                    crate::telemetry::SIEVE_OPS_COUNT
24                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
25                })
26                .await
27        }
28    }
29}
30
31/// Core 2 FFI Bindings for Non-Euclidean Tropical Sieve (NETS)
32/// These C-ABI functions expose the Lorentz mapping and Min-Plus tropical arithmetic
33/// directly to the GPU/NPU orchestration layer, guaranteeing $O(1)$ routing.
34#[no_mangle]
35pub unsafe extern "C" fn nets_map_lorentz(
36    quins_ptr: *const crate::NQuin,
37    quins_len: usize,
38    out_lorentz_ptr: *mut crate::domains::mathematical::geometric::LorentzVector,
39) {
40    let quins = std::slice::from_raw_parts(quins_ptr, quins_len);
41    let out_lorentz = std::slice::from_raw_parts_mut(out_lorentz_ptr, quins_len);
42
43    for i in 0..quins_len {
44        out_lorentz[i] =
45            crate::domains::mathematical::geometric::LorentzVector::from_quin(&quins[i]);
46    }
47}
48
49#[no_mangle]
50/// NPU FFI: tropical-Voronoi route on the accelerator.
51pub unsafe extern "C" fn nets_tropical_voronoi_route(
52    queries_ptr: *const crate::domains::mathematical::geometric::LorentzVector,
53    queries_len: usize,
54    centroids_ptr: *const crate::domains::mathematical::geometric::MinPlusVoronoiCell,
55    centroids_len: usize,
56    out_cell_ids_ptr: *mut u32,
57) {
58    let queries = std::slice::from_raw_parts(queries_ptr, queries_len);
59    let centroids = std::slice::from_raw_parts(centroids_ptr, centroids_len);
60    let out_cell_ids = std::slice::from_raw_parts_mut(out_cell_ids_ptr, queries_len);
61
62    for i in 0..queries_len {
63        let query = &queries[i];
64        let mut best_id = 0;
65        let mut min_dist = f32::MAX;
66
67        for centroid in centroids {
68            let dist = centroid.tropical_distance(query);
69            if dist < min_dist {
70                min_dist = dist;
71                best_id = centroid.cell_id;
72            }
73        }
74
75        out_cell_ids[i] = best_id;
76        crate::telemetry::SIEVE_OPS_COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
77    }
78}
79
80/// Pure Rust Valency & Stoichiometric Bridges
81/// Previously C-ABI, now migrated to native Rust to avoid FFI overhead.
82pub fn nets_parse_smiles(smiles: &str) -> Option<crate::NQuin> {
83    if smiles.is_empty() {
84        return None;
85    }
86
87    let mol = crate::domains::chemical::organic_chemistry::parse_smiles(smiles);
88    if !mol.is_valid || mol.atoms.is_empty() {
89        return None;
90    }
91
92    let first_valence =
93        crate::domains::chemical::organic_chemistry::default_valence(&mol.atoms[0].element) as u64;
94    let total_valence: u64 = mol
95        .atoms
96        .iter()
97        .map(|a| crate::domains::chemical::organic_chemistry::default_valence(&a.element) as u64)
98        .sum();
99    let atom_count = mol.atoms.len() as u64;
100    let bond_count = mol.bonds.len() as u64;
101
102    // Pack: [0..15]: first atom valency, [16..31]: total valency, [32..47]: atom count, [48..63]: bond count
103    let object = (first_valence & 0xFFFF)
104        | ((total_valence & 0xFFFF) << 16)
105        | ((atom_count & 0xFFFF) << 32)
106        | ((bond_count & 0xFFFF) << 48);
107
108    let subject = crate::q_hash(smiles);
109    let predicate = crate::q_hash("IS_SMILES");
110    let context = 0;
111    let metadata = 0b01 << 61;
112    let parity = subject ^ predicate ^ object ^ context;
113
114    Some(crate::NQuin {
115        subject,
116        predicate,
117        object,
118        context,
119        metadata,
120        parity,
121    })
122}
123
124/// NPU valency for the net.
125pub fn nets_calculate_valency(molecule_quin: &crate::NQuin) -> i32 {
126    if molecule_quin.predicate == crate::q_hash("IS_SMILES") {
127        (molecule_quin.object & 0xFFFF) as i32
128    } else {
129        -1
130    }
131}