qsketch.rs

cdk-rsx/crates/cdk-rsx-collections-minima/src/qsketch.rs

qsketch.rs476 lines← SDK documentation
1//! QSketch weighted distinct cardinality (Qi et al., KDD 2024).2//!3//! Each distinct key has one immutable positive weight supplied by a pure4//! `ImmutableWeight` rule. Repeated keys do not accumulate weight. This is not a5//! balance, frequency, signed-update or deletion sketch. Registers implement6//! equations (5)-(6): max floor(-log2(Exp(weight))), clamped to -127..=127.7//! Their byte encoding is rank+127; zero-filled payloads represent -127.8//!9//! This first implementation directly generates the independent variables in10//! O(M) time instead of the ordered-update acceleration. Estimation solves the11//! paper's *truncated* maximum likelihood with bounded bisection and a 255-entry12//! transient histogram. It does not implement QSketch-Dyn. All nonempty payloads13//! have the same one-block 64 KiB physical floor as other Minima collections.14//! See `qsketch_provenance.md` for algorithm and licensing details.1516const SOURCE_POLICY: [u8; 32] = cdk_rsx_source_policy::source_policy!("qsketch.rs");1718use crate::hash::{XXH64_POLICY, Xxh64Pair, Xxh64Word, hash_key};19use crate::{Collection, CollectionId, Error, FixedKey, NODE_BYTES, Result, Storage, Workspace};20use cdk_rsx_engine_nyxus::NyxusData;21use core::marker::PhantomData;2223/// An immutable mathematical weight function of canonical key identity.24/// Implementations must be pure and return the same finite positive value for25/// equal keys throughout their lifetime, including upgrades and across merge26/// participants. Pin the complete implementation / configuration in CONTRACT.27/// There is deliberately no per-observation mutable weight argument.28pub trait ImmutableWeight<K: FixedKey>: 'static {29    const CONTRACT: [u8; 32];30    fn weight(key: &K) -> f64;31}3233/// Unit weights give ordinary distinct cardinality through QSketch's estimator.34pub struct UnitWeight;35impl<K: FixedKey> ImmutableWeight<K> for UnitWeight {36    const CONTRACT: [u8; 32] = crate::contract(37        "QSketchUnitWeight/v1",38        &["one"],39        &[SOURCE_POLICY, crate::MINIMA_POLICY],40    );41    fn weight(_: &K) -> f64 {42        1.043    }44}4546#[derive(Clone, Copy, Debug, PartialEq, Eq)]47pub enum QSketchStatus {48    Estimated,49    /// A populated sketch whose registers are all at the lower endpoint cannot50    /// distinguish zero from a positive weight below its representable range.51    BelowRegisterRange,52    AboveRegisterRange,53}5455#[derive(Clone, Copy, Debug, PartialEq)]56pub struct QSketchEstimate {57    pub estimate: f64,58    pub lower_registers: u32,59    pub upper_registers: u32,60    pub status: QSketchStatus,61}6263#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]64pub struct QSketchUpdate {65    pub registers_increased: u32,66    pub pages_read: u32,67    pub pages_written: u32,68}6970pub const QSKETCH_MAX_BATCH: usize = 4096;7172/// Reusable per-key preparation. All fields are overwritten before use; no73/// exact-key inventory or persistent cache is maintained by the sketch.74pub struct QSketchBatchEntry {75    hashes: Xxh64Pair,76    weight: f64,77    log_weight: f64,78}79impl Default for QSketchBatchEntry {80    fn default() -> Self {81        Self {82            hashes: Xxh64Pair::new(0, 0),83            weight: 1.0,84            log_weight: 0.0,85        }86    }87}8889/// Retained descriptor with one byte per register, no ordinary allocator field.90///91/// ```compile_fail92/// use cdk_rsx_collections_minima::{Arena, qsketch::QSketch};93/// use cdk_rsx_platform::VecMemory;94/// let mut arena = Arena::format(VecMemory::new()).unwrap();95/// let _ = QSketch::<u64, 65537>::new(&mut arena, 0);96/// ```97#[repr(C)]98pub struct QSketch<K: FixedKey, const M: usize = 1024, W: ImmutableWeight<K> = UnitWeight> {99    collection: Collection,100    seed: u64,101    key: PhantomData<fn() -> (K, W)>,102}103// SAFETY: only Collection and an integer are retained; neither K nor W exists104// in the descriptor. No provider or borrowed workspace is persisted.105unsafe impl<K: FixedKey, const M: usize, W: ImmutableWeight<K>> NyxusData for QSketch<K, M, W> {106    const __NYXUS_POLICY: [u8; 32] = Self::CONTRACT;107}108109impl<K: FixedKey, const M: usize, W: ImmutableWeight<K>> QSketch<K, M, W> {110    pub const REGISTER_COUNT: usize = {111        assert!(M >= 16 && M <= 65_536, "QSketch M must be in 16..=65536");112        M113    };114    pub const PAGE_COUNT: usize = Self::REGISTER_COUNT.div_ceil(NODE_BYTES);115    pub const CONTRACT: [u8; 32] = crate::contract(116        "MinimaQSketch/QuantizedIndependentExponential/TruncatedML/v1",117        &["byte=rank+127;rank=-127..127;255-invalid;max-merge;52-bit-midpoint"],118        &[119            SOURCE_POLICY,120            K::CONTRACT,121            W::CONTRACT,122            XXH64_POLICY,123            crate::MINIMA_POLICY,124            crate::width_contract("qsketch-registers", Self::REGISTER_COUNT, &[]),125        ],126    );127    pub fn new(storage: &mut dyn Storage, seed: u64) -> Result<Self> {128        const {129            assert!(M >= 16 && M <= 65_536, "QSketch M must be in 16..=65536");130            assert!(K::WIDTH <= NODE_BYTES, "QSketch key exceeds workspace");131        }132        Ok(Self {133            collection: Collection::new(storage)?,134            seed,135            key: PhantomData,136        })137    }138    pub const fn identity(&self) -> CollectionId {139        self.collection.identity()140    }141    pub const fn seed(&self) -> u64 {142        self.seed143    }144    pub fn allocated_blocks(&self) -> usize {145        self.collection.block_count()146    }147148    pub fn observe(149        &mut self,150        storage: &mut dyn Storage,151        key: &K,152        workspace: &mut Workspace<'_>,153    ) -> Result<QSketchUpdate> {154        let weight = W::weight(key);155        if !weight.is_finite() || weight <= 0.0 {156            return Err(Error::InvalidInput(157                "QSketch requires finite positive immutable weight",158            ));159        }160        self.collection.validate(storage)?;161        let key_hash = hash_key(key, self.seed, workspace);162        let hashes = Xxh64Pair::new(key_hash, self.seed ^ 0x5153_6b65_7463_6831);163        let log_weight = weight.log2();164        self.collection165            .ensure_nodes(storage, Self::PAGE_COUNT as u64)?;166        let mut stats = QSketchUpdate::default();167        for page in 0..Self::PAGE_COUNT {168            let first = page * NODE_BYTES;169            let used = (M - first).min(NODE_BYTES);170            self.collection171                .read_at(storage, first as u64, &mut workspace.bytes_mut()[..used])172                .expect("QSketch admitted observation read");173            stats.pages_read += 1;174            let mut changed = false;175            for (index, old) in workspace.bytes_mut()[..used].iter_mut().enumerate() {176                assert!(*old != 255, "corrupt QSketch register");177                if *old == 254 {178                    continue;179                }180                let hash = hashes.hash((first + index) as u64);181                let uniform = ((hash >> 12) as f64 + 0.5) / 4_503_599_627_370_496.0;182                // Keep one complete rank of rounding slack in both gates.183                let bound = weight * Self::increase_scale(*old);184                if 1.0 - uniform > bound {185                    continue;186                }187                let exponential = -uniform.ln();188                if exponential > bound {189                    continue;190                }191                let rank = Self::rank_exponential(exponential, log_weight);192                if rank > *old {193                    *old = rank;194                    changed = true;195                    stats.registers_increased += 1;196                }197            }198            if changed {199                self.collection200                    .write_at(201                        storage,202                        (page * NODE_BYTES) as u64,203                        &workspace.bytes()[..used],204                    )205                    .expect("QSketch admitted observation write");206                stats.pages_written += 1;207            }208        }209        Ok(stats)210    }211212    /// Preflight at most 4096 immutable weights, then keep each active page213    /// resident across all keys. Register-local key order and exact scalar214    /// ranks are retained: `registers_increased` includes the same intermediate215    /// increases as the scalar loop. Page counts report actual batch traffic.216    pub fn observe_many(217        &mut self,218        storage: &mut dyn Storage,219        keys: &[K],220        scratch: &mut [QSketchBatchEntry],221        workspace: &mut Workspace<'_>,222    ) -> Result<QSketchUpdate> {223        if keys.len() > QSKETCH_MAX_BATCH || scratch.len() < keys.len() {224            return Err(Error::Capacity);225        }226        let scratch = &mut scratch[..keys.len()];227        for (entry, key) in scratch.iter_mut().zip(keys) {228            let weight = W::weight(key);229            if !weight.is_finite() || weight <= 0.0 {230                return Err(Error::InvalidInput(231                    "QSketch requires finite positive immutable weight",232                ));233            }234            let key_hash = hash_key(key, self.seed, workspace);235            *entry = QSketchBatchEntry {236                hashes: Xxh64Pair::new(key_hash, self.seed ^ 0x5153_6b65_7463_6831),237                weight,238                log_weight: weight.log2(),239            };240        }241        self.collection.validate(storage)?;242        let mut stats = QSketchUpdate::default();243        if keys.is_empty() {244            return Ok(stats);245        }246        self.collection247            .ensure_nodes(storage, Self::PAGE_COUNT as u64)248            .expect("QSketch admitted batch allocation");249        for page in 0..Self::PAGE_COUNT {250            let first = page * NODE_BYTES;251            let used = (M - first).min(NODE_BYTES);252            self.collection253                .read_at(storage, first as u64, &mut workspace.bytes_mut()[..used])254                .expect("QSketch admitted batch read");255            stats.pages_read += 1;256            let mut changed = false;257            for (index, old) in workspace.bytes_mut()[..used].iter_mut().enumerate() {258                assert!(*old != 255, "corrupt QSketch register");259                if *old == 254 {260                    continue;261                }262                let index_hash = Xxh64Word::new((first + index) as u64);263                let mut scale = Self::increase_scale(*old);264                for entry in scratch.iter() {265                    let hash = entry.hashes.hash_prepared_second(&index_hash);266                    let uniform = ((hash >> 12) as f64 + 0.5) / 4_503_599_627_370_496.0;267                    let bound = entry.weight * scale;268                    if 1.0 - uniform > bound {269                        continue;270                    }271                    let exponential = -uniform.ln();272                    if exponential > bound {273                        continue;274                    }275                    let rank = Self::rank_exponential(exponential, entry.log_weight);276                    if rank > *old {277                        *old = rank;278                        changed = true;279                        stats.registers_increased += 1;280                        if rank == 254 {281                            break;282                        }283                        scale = Self::increase_scale(rank);284                    }285                }286            }287            if changed {288                self.collection289                    .write_at(storage, first as u64, &workspace.bytes()[..used])290                    .expect("QSketch admitted batch write");291                stats.pages_written += 1;292            }293        }294        Ok(stats)295    }296297    pub fn estimate(298        &self,299        storage: &dyn Storage,300        workspace: &mut Workspace<'_>,301    ) -> Result<QSketchEstimate> {302        self.collection.validate(storage)?;303        let mut histogram = [0u32; 255];304        if self.allocated_blocks() == 0 {305            return Ok(QSketchEstimate {306                estimate: 0.0,307                lower_registers: M as u32,308                upper_registers: 0,309                status: QSketchStatus::Estimated,310            });311        }312        for page in 0..Self::PAGE_COUNT {313            let used = (M - page * NODE_BYTES).min(NODE_BYTES);314            self.collection.read_at(315                storage,316                (page * NODE_BYTES) as u64,317                &mut workspace.bytes_mut()[..used],318            )?;319            for &rank in &workspace.bytes()[..used] {320                if rank == 255 {321                    return Err(Error::Corrupt("QSketch register"));322                }323                histogram[usize::from(rank)] += 1;324            }325        }326        Ok(estimate_histogram(&histogram, M as u32))327    }328329    /// Register-wise max is exact weighted-set union when both participants use330    /// the same immutable weight rule. Seed/configuration mismatch rejects331    /// before allocation and writes. Workspace is explicitly borrowed last.332    pub fn merge<QK: FixedKey, const N: usize, QW: ImmutableWeight<QK>>(333        &mut self,334        storage: &mut dyn Storage,335        other: &QSketch<QK, N, QW>,336        other_workspace: &mut Workspace<'_>,337        workspace: &mut Workspace<'_>,338    ) -> Result<QSketchUpdate> {339        if Self::CONTRACT != QSketch::<QK, N, QW>::CONTRACT || self.seed != other.seed {340            return Err(Error::InvalidInput("incompatible QSketch contract or seed"));341        }342        self.collection.validate(storage)?;343        other.collection.validate(storage)?;344        let mut stats = QSketchUpdate::default();345        if other.allocated_blocks() == 0 {346            return Ok(stats);347        }348        self.collection349            .ensure_nodes(storage, Self::PAGE_COUNT as u64)?;350        for page in 0..Self::PAGE_COUNT {351            let used = (M - page * NODE_BYTES).min(NODE_BYTES);352            self.collection353                .read_at(354                    storage,355                    (page * NODE_BYTES) as u64,356                    &mut workspace.bytes_mut()[..used],357                )358                .expect("QSketch admitted merge destination read");359            other360                .collection361                .read_at(362                    storage,363                    (page * NODE_BYTES) as u64,364                    &mut other_workspace.bytes_mut()[..used],365                )366                .expect("QSketch admitted merge source read");367            let source = other_workspace.bytes();368            stats.pages_read += 2;369            let mut changed = false;370            for (old, &new) in workspace.bytes_mut()[..used]371                .iter_mut()372                .zip(&source[..used])373            {374                assert!(*old != 255 && new != 255, "corrupt QSketch register");375                if new > *old {376                    *old = new;377                    changed = true;378                    stats.registers_increased += 1;379                }380            }381            if changed {382                self.collection383                    .write_at(384                        storage,385                        (page * NODE_BYTES) as u64,386                        &workspace.bytes()[..used],387                    )388                    .expect("QSketch admitted merge write");389                stats.pages_written += 1;390            }391        }392        Ok(stats)393    }394    pub fn clear(&mut self, storage: &mut dyn Storage) -> Result<()> {395        self.collection.truncate_nodes(storage, 0)396    }397398    fn increase_scale(old: u8) -> f64 {399        f64::from_bits(u64::from(1150 - u16::from(old)) << 52)400    }401402    fn rank_exponential(exponential: f64, log_weight: f64) -> u8 {403        // Compute in logarithms so valid subnormal/huge weights cannot404        // underflow/overflow the intermediate exponential sample.405        // The observation has already computed -ln(uniform). Its exact value406        // is also a stronger rejection bound than 1-uniform, so a noncandidate407        // can avoid this second logarithm without changing the quantization.408        let log_exponential = exponential.log2() - log_weight;409        let rank = (-log_exponential).floor().clamp(-127.0, 127.0) as i16;410        (rank + 127) as u8411    }412}413414fn estimate_histogram(histogram: &[u32; 255], m: u32) -> QSketchEstimate {415    let lower = histogram[0];416    let upper = histogram[254];417    let (estimate, status) = if lower == m {418        (0.0, QSketchStatus::BelowRegisterRange)419    } else if upper == m {420        (f64::INFINITY, QSketchStatus::AboveRegisterRange)421    } else {422        let first = (1..254).find(|&at| histogram[at] != 0).unwrap_or(254);423        let end = (first..254)424            .rev()425            .find(|&at| histogram[at] != 0)426            .map_or(first, |at| at + 1);427        let first_threshold = 2.0f64.powi(126 - first as i32);428        // Scale f(C) by C. This avoids 1/C and retains the same unique root.429        let score = |c: f64| {430            let mut value = -f64::from(lower) * c * 2.0f64.powi(126);431            let mut threshold = first_threshold;432            for &count in &histogram[first..end] {433                if count != 0 {434                    let z = c * threshold;435                    let ratio = if z == 0.0 { 1.0 } else { z / z.exp_m1() };436                    value += f64::from(count) * (ratio - z);437                }438                // Every threshold is an exact normal power of two. This439                // retains the same z bits as powi for each occupied bin.440                threshold *= 0.5;441            }442            if upper != 0 {443                let threshold = 2.0f64.powi(-127);444                let z = c * threshold;445                let ratio = if z == 0.0 { 1.0 } else { z / z.exp_m1() };446                value += f64::from(upper) * ratio;447            }448            value449        };450        // Fixed log-space bracket covers every finite interior rank. It also451        // prevents absolute-tolerance failure for tiny positive total weights.452        let (mut low, mut high) = (-200.0f64, 200.0f64);453        for _ in 0..100 {454            let mid = (low + high) * 0.5;455            if mid == low || mid == high {456                break;457            }458            if score(2.0f64.powf(mid)) > 0.0 {459                low = mid;460            } else {461                high = mid;462            }463        }464        (2.0f64.powf((low + high) * 0.5), QSketchStatus::Estimated)465    };466    QSketchEstimate {467        estimate,468        lower_registers: lower,469        upper_registers: upper,470        status,471    }472}473474#[cfg(test)]475#[path = "qsketch_tests.rs"]476mod tests;