diff --git a/Cargo.lock b/Cargo.lock index 526c1b310..44695fda4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1499,6 +1499,12 @@ version = "0.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5419bdc4f6a9207fbeba6d11b604d481addf78ecd10c11ad51e76c2f6482748d" +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + [[package]] name = "heck" version = "0.5.0" @@ -2190,8 +2196,10 @@ name = "ppvm-lindblad" version = "0.1.1" dependencies = [ "approx", + "bitvec", "criterion 0.7.0", "fxhash", + "hashbrown 0.17.1", "nalgebra", "ndarray", "num", diff --git a/crates/ppvm-lindblad/Cargo.toml b/crates/ppvm-lindblad/Cargo.toml index 961f48131..e0fd22271 100644 --- a/crates/ppvm-lindblad/Cargo.toml +++ b/crates/ppvm-lindblad/Cargo.toml @@ -8,7 +8,9 @@ publish = false description = "Direct Heisenberg-picture Lindbladian evolution on an adaptive Pauli-string basis." [dependencies] +bitvec = "1.0.1" fxhash = "0.2.1" +hashbrown = { version = "0.17.1", default-features = false } ndarray = "0.17" num = "0.4.3" ppvm-traits = { version = "0.1.1", path = "../ppvm-traits" } diff --git a/crates/ppvm-lindblad/src/algebra.rs b/crates/ppvm-lindblad/src/algebra.rs index 5fd3f4750..95b22850b 100644 --- a/crates/ppvm-lindblad/src/algebra.rs +++ b/crates/ppvm-lindblad/src/algebra.rs @@ -13,7 +13,6 @@ use crate::word::{Chunk, W_CHUNKS, Word}; use fxhash::FxHashMap; use num::Complex; -use ppvm_traits::PauliWordTrait; /// Magnitude below which an expanded Pauli coefficient is treated as /// cancellation noise and dropped. @@ -105,7 +104,7 @@ pub(crate) fn comm_product(h: &Word, p: &Word) -> (Word /// is `ω · out` with `ω = i^phase`. #[inline(always)] pub(crate) fn pauli_mul(p: &Word, q: &Word) -> (Word, u8) { - let mut out = Word::::new(p.n_qubits()); + let mut out = Word::::default(); let mut sign_count: u32 = 0; let mut imag_count: u32 = 0; for i in 0..C { @@ -120,6 +119,5 @@ pub(crate) fn pauli_mul(p: &Word, q: &Word) -> (Word, u out.xbits.data[i] = a ^ c; out.zbits.data[i] = b ^ d; } - out.rehash(); (out, ((2 * sign_count + imag_count) & 3) as u8) } diff --git a/crates/ppvm-lindblad/src/basis.rs b/crates/ppvm-lindblad/src/basis.rs index 09e162177..1658e451c 100644 --- a/crates/ppvm-lindblad/src/basis.rs +++ b/crates/ppvm-lindblad/src/basis.rs @@ -4,6 +4,7 @@ //! Basis-level `L*` operators: in-basis generator and off-basis leakage. use crate::Error; +use crate::candidates::StreamingProposer; use crate::sector::Sector; use crate::spec::LindbladSpec; use crate::truncate::{cap_map_to_room, order_by_desc_mag}; @@ -16,6 +17,18 @@ use rayon::prelude::*; /// into the live map (and the room-cap applied) once per chunk. const CHUNK_SIZE: usize = 4096; +/// Buffers one predictor-corrector trajectory reuses from step to step: +/// candidate lookup and generation storage, the generator cache, the +/// exponential's work vector and the saved pre-step coefficients. Candidate +/// words themselves occupy the main basis array's spare tail. +#[derive(Default)] +pub(crate) struct PcStepWorkspace { + pub(crate) proposer: StreamingProposer, + pub(crate) generator: Option, + pub(crate) taylor: Vec, + pub(crate) coefficient_auxiliary: Vec, +} + /// Build a `word → row` map for a basis assumed to contain unique Pauli /// words; debug-asserts the uniqueness invariant. pub fn build_basis_index(basis: &[Word]) -> FxHashMap, u32> { diff --git a/crates/ppvm-lindblad/src/candidates.rs b/crates/ppvm-lindblad/src/candidates.rs new file mode 100644 index 000000000..eb3330e4d --- /dev/null +++ b/crates/ppvm-lindblad/src/candidates.rs @@ -0,0 +1,363 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Candidate proposal for the real predictor-corrector step. +//! +//! A [`CandidateProposer`] chooses which strings outside the basis a step +//! admits. Candidates are written to the spare tail of the main basis array, +//! viewed through a [`CandidateBuffer`]. [`StreamingProposer`], the default, +//! computes the same candidates, rates and admission order as +//! [`LindbladSpec::leakage_with_prune`] followed by admission. + +use crate::indexed_candidates::IndexedCandidates; +use crate::truncate::order_by_desc_mag; +use crate::word::{Word, word_hash}; +use crate::{Error, LindbladSpec}; +use fxhash::FxHashMap; +use num::Complex; +use rayon::prelude::*; + +/// Sources per room cap, as in [`LindbladSpec::leakage_with_prune`]. +const CHUNK_SIZE: usize = 4096; +/// Sources whose actions are generated in parallel before serial accumulation. +/// Bounds the temporary output words independently of `CHUNK_SIZE`. +const GENERATION_BATCH: usize = 2048; + +/// Strategy that chooses which strings outside the basis a step admits. +/// +/// [`LindbladSpec::pc_step`] uses [`StreamingProposer`]; +/// [`LindbladSpec::pc_step_with_proposer`] takes any implementation. A step +/// calls `propose` and then `select` once per enlargement (at most twice). +pub trait CandidateProposer: Send { + /// Write candidate words to `buffer`'s tail with [`CandidateBuffer::push`]. + /// Candidates must be distinct and outside the basis and `protected`. + /// `maximum` bounds the enlarged basis, including the current basis. + fn propose( + &mut self, + model: &LindbladSpec, + buffer: &mut CandidateBuffer<'_, C>, + protected: &[Word], + maximum: usize, + ) -> Result<(), Error>; + + /// Move the admitted candidates to the start of the tail and return how + /// many there are: at most `maximum - basis().len()`, each with a rate + /// magnitude above `threshold`. They enter the basis with coefficient zero. + fn select(&mut self, buffer: &mut CandidateBuffer<'_, C>, threshold: f64) -> usize; +} + +/// The current basis plus its spare tail, where candidates are collected. +/// +/// The basis and its coefficients stay unchanged during proposal. Candidates +/// the step does not admit are discarded when the buffer is dropped. +pub struct CandidateBuffer<'a, const C: usize = { crate::W_CHUNKS }> { + pub(crate) words: &'a mut Vec>, + pub(crate) numeric: &'a mut Vec, + pub(crate) prefix: usize, + coefficients: &'a [f64], +} + +impl<'a, const C: usize> CandidateBuffer<'a, C> { + /// View `words` as the basis with coefficients `coefficients`. `numeric` + /// is cleared and lent to the proposer as scratch. + pub(crate) fn new( + words: &'a mut Vec>, + coefficients: &'a [f64], + numeric: &'a mut Vec, + ) -> Self { + assert_eq!(words.len(), coefficients.len()); + let prefix = words.len(); + numeric.clear(); + Self { + words, + numeric, + prefix, + coefficients, + } + } + + /// The current basis. + pub fn basis(&self) -> &[Word] { + &self.words[..self.prefix] + } + + /// Coefficients of [`Self::basis`]. + pub fn coefficients(&self) -> &[f64] { + self.coefficients + } + + /// Candidate words written so far. + pub fn candidates(&self) -> &[Word] { + &self.words[self.prefix..] + } + + /// Candidate words, for reordering in [`CandidateProposer::select`]. + pub fn candidates_mut(&mut self) -> &mut [Word] { + &mut self.words[self.prefix..] + } + + /// Append a candidate word. The tail shares the main basis array, so it + /// grows by a quarter of its capacity instead of doubling it. + pub fn push(&mut self, word: Word) { + if self.words.len() == self.words.capacity() { + self.words + .reserve_exact((self.words.capacity() / 4).max(32)); + } + self.words.push(word); + } + + /// Scratch the proposer may use for rates and ranking. The step reuses + /// it afterwards, so its contents do not survive `select`. + pub fn numeric_scratch(&mut self) -> &mut Vec { + self.numeric + } + + /// Admit the first `count` candidates into the basis. + pub(crate) fn finish(mut self, count: usize) { + assert!(count <= self.candidates().len()); + self.prefix += count; + } +} + +impl Drop for CandidateBuffer<'_, C> { + fn drop(&mut self) { + self.words.truncate(self.prefix); + self.numeric.clear(); + } +} + +/// Per-thread scratch for one string's generator action. +pub(crate) struct ActionScratch { + support: Vec, + candidates: Vec, + local: FxHashMap, Complex>, + active: Vec, + /// Output words with their [`word_hash`] and generator values, in the + /// order of [`LindbladSpec::compute_action_terms`]. + pub(crate) terms: Vec<(u64, Word, f64)>, +} + +impl ActionScratch { + pub(crate) fn new() -> Self { + Self { + support: Vec::new(), + candidates: Vec::new(), + local: FxHashMap::default(), + active: Vec::new(), + terms: Vec::new(), + } + } + + /// Fill [`Self::terms`] with `L*(word)`. Runs once per source string in + /// the generation loop, whose speed depends on this being inlined. + #[inline] + pub(crate) fn fill(&mut self, spec: &LindbladSpec, word: &Word) { + if let Some(plan) = &spec.pauli_plan { + plan.fill_keyed(word, &mut self.active, &mut self.terms); + self.terms + .sort_unstable_by(|(ha, a, _), (hb, b, _)| ha.cmp(hb).then_with(|| a.cmp(b))); + return; + } + let terms = spec.compute_action_terms( + word, + &mut self.support, + &mut self.candidates, + &mut self.local, + ); + self.terms.clear(); + self.terms.extend( + terms + .into_iter() + .map(|(word, value)| (word_hash(&word), word, value)), + ); + } +} + +/// The default proposer: chunk-capped signed leakage accumulation. +/// +/// Sources are processed in descending coefficient magnitude, and after every +/// `CHUNK_SIZE` sources only the `room` largest candidates are kept. Signed +/// sums and hash-table visitation order match +/// [`LindbladSpec::leakage_with_prune`], so admission and ties are identical. +#[derive(Default)] +pub struct StreamingProposer { + indexed: IndexedCandidates, + outputs: Vec, f64)>>, +} + +impl CandidateProposer for StreamingProposer { + fn propose( + &mut self, + model: &LindbladSpec, + buffer: &mut CandidateBuffer<'_, C>, + protected: &[Word], + maximum: usize, + ) -> Result<(), Error> { + self.indexed.reset(); + let in_basis: FxHashMap = + buffer.basis().iter().map(|w| (word_hash(w), ())).collect(); + let protected_set: FxHashMap = + protected.iter().map(|w| (word_hash(w), ())).collect(); + let order = order_by_desc_mag(buffer.coefficients()); + let room = maximum.saturating_sub(buffer.basis().len()); + self.outputs + .resize_with(GENERATION_BATCH.div_ceil(64), Vec::new); + for chunk in order.chunks(CHUNK_SIZE) { + for sources in chunk.chunks(GENERATION_BATCH) { + let basis = buffer.basis(); + let coefficients = buffer.coefficients(); + self.outputs + .par_iter_mut() + .zip(sources.par_chunks(64)) + .for_each_init(ActionScratch::new, |scratch, (output, indices)| { + output.clear(); + for &index in indices { + scratch.fill(model, &basis[index]); + for &(hash, word, value) in &scratch.terms { + if !in_basis.contains_key(&hash) + && !protected_set.contains_key(&hash) + { + output.push((word, coefficients[index] * value)); + } + } + } + }); + // Serial source order preserves coherent sums and admission ties. + for output in self.outputs.iter().take(sources.len().div_ceil(64)) { + for &(word, value) in output { + self.indexed.add(buffer, word, value); + } + } + } + self.indexed.cap(buffer, room); + } + for output in &mut self.outputs { + output.clear(); + } + Ok(()) + } + + fn select(&mut self, buffer: &mut CandidateBuffer<'_, C>, threshold: f64) -> usize { + let count = self.indexed.select(buffer, threshold); + self.indexed.reset(); + count + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::truncate::cap_map_to_room; + use crate::word_from_codes; + + #[test] + fn indexed_candidates_match_map_caps_ties_and_visitation() { + let seed = word_from_codes::<2>(&[1; 6]).unwrap(); + let mut words = vec![seed]; + let mut numeric = Vec::new(); + let mut buffer = CandidateBuffer::new(&mut words, &[0.5], &mut numeric); + let mut indexed = IndexedCandidates::default(); + let mut reference = FxHashMap::default(); + for chunk in 0..12 { + for i in 0..500 { + let code = (i * 37 + chunk * 11) % 4096; + let word = word_from_codes::<2>( + &(0..6) + .map(|q| ((code >> (2 * q)) & 3) as u8) + .collect::>(), + ) + .unwrap(); + let value = ((i + chunk) % 9) as f64 - 4.0; + *reference.entry(word).or_insert(0.0) += value; + indexed.add(&mut buffer, word, value); + } + cap_map_to_room(&mut reference, 300); + indexed.cap(&mut buffer, 300); + assert_eq!(buffer.basis(), &[seed]); + } + let expected: Vec<_> = reference + .into_iter() + .filter(|(_, value)| value.abs() > 1.5) + .map(|(word, _)| word) + .collect(); + let count = indexed.select(&mut buffer, 1.5); + buffer.finish(count); + assert_eq!( + words, + std::iter::once(seed).chain(expected).collect::>() + ); + assert!(numeric.is_empty()); + } + + #[test] + fn nonfinite_threshold_rejects_tail_and_preserves_prefix() { + let seed = word_from_codes::<2>(&[1, 0]).unwrap(); + let candidate = word_from_codes::<2>(&[0, 2]).unwrap(); + let mut words = vec![seed]; + let mut numeric = Vec::new(); + let mut buffer = CandidateBuffer::new(&mut words, &[1.0], &mut numeric); + let mut proposer = StreamingProposer::default(); + proposer.indexed.add(&mut buffer, candidate, 0.5); + let count = proposer.select(&mut buffer, f64::NAN); + buffer.finish(count); + assert_eq!(words, vec![seed]); + } + + /// Several room caps, more than one `CHUNK_SIZE` of sources, and thread + /// counts that split generation batches differently. + #[test] + fn streaming_admission_matches_leakage_with_prune() { + let n = 7; + let mut h = Vec::new(); + for site in 0..n - 1 { + for symbol in ['X', 'Y'] { + let mut term = vec!['I'; n]; + term[site] = symbol; + term[site + 1] = symbol; + h.push((term.into_iter().collect(), 0.3)); + } + } + let spec = LindbladSpec::<2>::new(n, &h, &[]).unwrap(); + let basis: Vec<_> = (0..14000) + .filter(|i| i % 3 != 0) + .map(|i| { + word_from_codes::<2>( + &(0..n) + .map(|q| ((i >> (2 * q)) & 3) as u8) + .collect::>(), + ) + .unwrap() + }) + .collect(); + let coefficients: Vec<_> = (0..basis.len()).map(|i| (i as f64).sin()).collect(); + for room in [0, 100, 2000] { + let maximum = basis.len() + room; + let expected: Vec<_> = spec + .leakage_with_prune(&basis, &coefficients, &[], maximum, 0.0) + .unwrap() + .into_iter() + .map(|(word, _)| word) + .collect(); + for threads in [1, 2, 6] { + let pool = rayon::ThreadPoolBuilder::new() + .num_threads(threads) + .build() + .unwrap(); + let mut words = basis.clone(); + let mut numeric = Vec::new(); + pool.install(|| { + let mut buffer = CandidateBuffer::new(&mut words, &coefficients, &mut numeric); + let mut proposer = StreamingProposer::default(); + proposer.propose(&spec, &mut buffer, &[], maximum).unwrap(); + let count = proposer.select(&mut buffer, 0.0); + buffer.finish(count); + }); + assert_eq!( + words[basis.len()..], + expected[..], + "room={room}, threads={threads}" + ); + } + } + } +} diff --git a/crates/ppvm-lindblad/src/compact_index.rs b/crates/ppvm-lindblad/src/compact_index.rs new file mode 100644 index 000000000..e91fbb23d --- /dev/null +++ b/crates/ppvm-lindblad/src/compact_index.rs @@ -0,0 +1,76 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Collision-safe basis lookup storing positions rather than duplicate words. + +use crate::word::{Word, word_hash}; +use hashbrown::{HashTable, hash_table::Entry}; + +pub(crate) struct CompactBasisIndex<'a, const C: usize> { + basis: &'a [Word], + table: HashTable, +} + +impl<'a, const C: usize> CompactBasisIndex<'a, C> { + pub(crate) fn new(basis: &'a [Word]) -> Self { + assert!( + basis.len() < u32::MAX as usize, + "basis exceeds u32 positions" + ); + let mut table = HashTable::with_capacity(basis.len()); + for (position, word) in basis.iter().enumerate() { + match table.entry( + word_hash(word), + |&index| basis[index as usize] == *word, + |&index| word_hash(&basis[index as usize]), + ) { + Entry::Vacant(entry) => { + entry.insert(position as u32); + } + Entry::Occupied(_) => panic!("duplicate Pauli word in basis"), + } + } + Self { basis, table } + } + + /// [`Self::get`] for a word whose [`word_hash`] the caller already has. + pub(crate) fn get_hashed(&self, word: &Word, hash: u64) -> Option { + self.table + .find(hash, |&index| self.basis[index as usize] == *word) + .copied() + } + + #[cfg(test)] + pub(crate) fn get(&self, word: &Word) -> Option { + // Control-byte fingerprints filter probes before loading full borrowed words. + self.table + .find(word_hash(word), |&index| { + self.basis[index as usize] == *word + }) + .copied() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::word_from_codes; + + #[test] + fn compact_lookup_checks_words_and_wide_registers() { + let basis: Vec<_> = (0..192) + .map(|site| { + let mut codes = vec![0; 128]; + codes[site / 3] = (site % 3 + 1) as u8; + word_from_codes::<2>(&codes).unwrap() + }) + .collect(); + let index = CompactBasisIndex::new(&basis); + for (i, word) in basis.iter().enumerate() { + assert_eq!(index.get(word), Some(i as u32)); + } + assert_eq!(index.get(&word_from_codes::<2>(&[2; 128]).unwrap()), None); + let wide = vec![word_from_codes::<8>(&vec![1; 512]).unwrap()]; + assert_eq!(CompactBasisIndex::new(&wide).get(&wide[0]), Some(0)); + } +} diff --git a/crates/ppvm-lindblad/src/indexed_candidates.rs b/crates/ppvm-lindblad/src/indexed_candidates.rs new file mode 100644 index 000000000..5130c2a3b --- /dev/null +++ b/crates/ppvm-lindblad/src/indexed_candidates.rs @@ -0,0 +1,160 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Stable candidate positions and chunk-capped ranking metadata. + +use crate::candidates::CandidateBuffer; +use crate::word::{Word, word_hash}; +use hashbrown::HashTable; + +#[derive(Default)] +pub(crate) struct IndexedCandidates { + state: Vec, + table: HashTable, + free: Vec, +} + +impl IndexedCandidates { + pub(crate) fn reset(&mut self) { + self.state.clear(); + self.free.clear(); + // Table growth history determines admission order, including magnitude ties. + self.table = HashTable::new(); + } + + /// Add `value` to `word`'s rate, inserting the word into the tail if new. + /// Runs once per generated term; inlined into the accumulation loop. + #[inline] + pub(crate) fn add( + &mut self, + buffer: &mut CandidateBuffer<'_, C>, + word: Word, + value: f64, + ) { + let hash = word_hash(&word); + if let Some(&index) = self.table.find(hash, |&index| { + buffer.words[buffer.prefix + index as usize] == word + }) { + buffer.numeric[index as usize] += value; + return; + } + let index = if let Some(index) = self.free.pop() { + buffer.words[buffer.prefix + index as usize] = word; + buffer.numeric[index as usize] = 0.0 + value; + self.state[index as usize] = 1; + index + } else { + if buffer.words.len() == buffer.words.capacity() { + buffer + .words + .reserve_exact((buffer.words.capacity() / 4).max(32)); + buffer + .numeric + .reserve_exact(buffer.words.capacity() - buffer.prefix - buffer.numeric.len()); + self.state + .reserve_exact(buffer.words.capacity() - buffer.prefix - self.state.len()); + } + let index = u32::try_from(buffer.numeric.len()).expect("candidate count exceeds u32"); + buffer.words.push(word); + buffer.numeric.push(0.0 + value); + self.state.push(1); + index + }; + self.table.insert_unique(hash, index, |&index| { + word_hash(&buffer.words[buffer.prefix + index as usize]) + }); + } + + pub(crate) fn cap(&mut self, buffer: &mut CandidateBuffer<'_, C>, room: usize) { + if self.table.len() <= room { + return; + } + if room == 0 { + buffer.words.truncate(buffer.prefix); + buffer.numeric.clear(); + self.state.clear(); + self.table.clear(); + self.free.clear(); + return; + } + let count = buffer.numeric.len(); + buffer.numeric.reserve_exact(self.table.len()); + // The rate prefix remains live while the tail holds nonnegative ranking keys. + for index in 0..count { + if self.state[index] != 0 { + buffer.numeric.push(buffer.numeric[index].abs()); + } + } + let (rates, keys) = buffer.numeric.split_at_mut(count); + let position = keys.len() - room; + let cutoff = keys + .select_nth_unstable_by_key(position, |v| v.to_bits()) + .1 + .to_bits(); + let above = keys.iter().filter(|v| v.to_bits() > cutoff).count(); + let mut ties = room - above; + for (rate, state) in rates.iter().zip(&mut self.state) { + if *state != 0 { + let magnitude = rate.abs().to_bits(); + *state = if magnitude > cutoff { + 3 + } else if magnitude == cutoff { + 2 + } else { + 1 + }; + } + } + self.table.retain(|index| { + let state = &mut self.state[*index as usize]; + if *state == 3 { + return true; + } + let keep = *state == 2 && ties > 0; + ties -= keep as usize; + if !keep { + *state = 0; + self.free.push(*index); + } + keep + }); + buffer.numeric.truncate(count); + } + + pub(crate) fn select( + &mut self, + buffer: &mut CandidateBuffer<'_, C>, + threshold: f64, + ) -> usize { + self.table + .retain(|index| buffer.numeric[*index as usize].abs() > threshold); + let slots = buffer.numeric.len(); + buffer.numeric.clear(); + buffer.numeric.resize(2 * slots, 0.0); + let (positions, labels) = buffer.numeric.split_at_mut(slots); + // Integer positions use lossless bit patterns in the shared numeric buffer. + // No floating arithmetic reads these temporary permutation entries. + for index in 0..slots { + let code = f64::from_bits(index as u64); + positions[index] = code; + labels[index] = code; + } + let mut count = 0; + for &original in &self.table { + if self.state[original as usize] == 0 { + continue; + } + let source = positions[original as usize].to_bits() as usize; + buffer + .words + .swap(buffer.prefix + count, buffer.prefix + source); + let displaced = labels[count].to_bits() as usize; + positions[displaced] = f64::from_bits(source as u64); + labels[source] = f64::from_bits(displaced as u64); + positions[original as usize] = f64::from_bits(count as u64); + labels[count] = f64::from_bits(original as u64); + count += 1; + } + count + } +} diff --git a/crates/ppvm-lindblad/src/lib.rs b/crates/ppvm-lindblad/src/lib.rs index 683e34751..e070acfd7 100644 --- a/crates/ppvm-lindblad/src/lib.rs +++ b/crates/ppvm-lindblad/src/lib.rs @@ -27,9 +27,11 @@ //! to `f64` at the boundary (with a debug-only check that `|Im|` is at //! FP noise). //! -//! Pauli strings are stored as [`ppvm_pauli_word::word::PauliWord`] backed by -//! a fixed array of `C` chunks (64-bit, or 32-bit on 32-bit targets) with -//! cached hashes for fast HashMap lookup. The crate is const-generic in `C` +//! Pauli strings are stored as [`Word`]: an X and a Z bit plane of `C` +//! chunks each (64-bit, or 32-bit on 32-bit targets) and nothing else, so a +//! 128-qubit word is 32 bytes. Hashes are computed from the planes when a table +//! needs them. [`GeneralWord`] is the corresponding `ppvm_pauli_word` type taken +//! by `ppvm_pauli_sum` symmetry routines. The crate is const-generic in `C` //! ([`Word`], [`LindbladSpec`]); the default is the 128-qubit width, //! and [`chunks_for`] picks the narrowest of the 128/256/512-qubit widths //! for a register. The hot-path commutator/ @@ -38,28 +40,36 @@ mod algebra; mod basis; +mod candidates; +mod compact_index; pub mod config; pub mod error; pub(crate) mod expm; +mod indexed_candidates; mod kossakowski; +mod pauli_plan; +#[cfg(test)] +mod reference; mod scalar; pub mod sector; mod spec; mod step; mod truncate; +mod unit_expm; mod word; /// Matrix-free / quspin-expm-backed `exp(dt·L*)·b` engine. See module docs. pub(crate) mod mf_expm; pub use basis::build_basis_index; +pub use candidates::{CandidateBuffer, CandidateProposer, StreamingProposer}; pub use config::PcStepConfig; pub use error::Error; pub use sector::{Sector, canonicalize_basis_to_rep}; pub use spec::{JumpInput, LindbladSpec}; pub use step::PcStepTimings; pub use word::{ - CHUNK_BITS, MAX_QUBITS, MAX_SUPPORTED_QUBITS, W_CHUNKS, WIDTHS, Word, chunks_for, + CHUNK_BITS, GeneralWord, MAX_QUBITS, MAX_SUPPORTED_QUBITS, W_CHUNKS, WIDTHS, Word, chunks_for, codes_from_word, max_qubits, parse_pauli_string, word_from_codes, }; diff --git a/crates/ppvm-lindblad/src/mf_expm.rs b/crates/ppvm-lindblad/src/mf_expm.rs index cd5da646b..3041643c3 100644 --- a/crates/ppvm-lindblad/src/mf_expm.rs +++ b/crates/ppvm-lindblad/src/mf_expm.rs @@ -25,9 +25,15 @@ //! picked with the tolerance-matched tables in [`crate::expm`]: a relaxed //! `tol=1e-6` table when the PC prunes coarsely (`drop_tol ≥ 1e-4`), else the //! double-precision table (keeping the exact-reference test paths bit-exact). +//! +//! Real adaptive steps on models whose jumps are all Hermitian Paulis use the +//! paired connection cache in [`crate::unit_expm`] instead of the CSR cache +//! (see [`expm_apply_inplace`]). +use crate::basis::PcStepWorkspace; use crate::scalar::Coeff; use crate::sector::Sector; +use crate::unit_expm::{UnitCache, UnitOp}; use crate::{LindbladSpec, Word, build_basis_index, expm}; use fxhash::{FxBuildHasher, FxHashMap}; use num::Complex; @@ -492,6 +498,70 @@ where v } +/// Taylor partition and backward-error tolerance for a real step. +/// +/// Matches the tolerance to the basis truncation: when the PC prunes coarsely +/// (drop_tol >= 1e-4) a double-precision exp is ~10 orders more accurate than +/// the state it acts on, so the relaxed (tol=1e-6, still >=100x tighter than +/// the cut) table is used — it admits a lower-degree Taylor polynomial and +/// cuts the SpMV count with no effect on the truncated result. At tight/zero +/// drop_tol we keep double precision so the exact-reference paths (orbit-rep +/// / merged) still agree bit-for-bit. +fn select_real_expm(t_norm: f64, drop_tol: f64) -> (u32, u32, f64) { + if drop_tol >= 1e-4 { + let (m, s) = expm::select_ms_loose(t_norm); + (m, s, 1e-6) + } else { + let (m, s) = expm::select_ms(t_norm); + (m, s, 1e-12) + } +} + +/// Apply `exp(dt · M)` to the real coefficients of an adaptive step, in place. +/// +/// When every jump is a Hermitian Pauli the model has a +/// [`crate::pauli_plan::PauliActionPlan`]; the generator is then stored as the +/// paired connection cache of [`crate::unit_expm`], and the workspace keeps +/// that cache and the Taylor work vector for the next call. Other models use +/// [`expm_apply_mf`]. +pub(crate) fn expm_apply_inplace( + spec: &LindbladSpec, + basis: &[Word], + dt: f64, + coefficients: &mut [f64], + drop_tol: f64, + workspace: &mut PcStepWorkspace, +) { + let Some(plan) = &spec.pauli_plan else { + let evolved = expm_apply_mf(spec, basis, dt, coefficients, drop_tol); + coefficients.copy_from_slice(&evolved); + return; + }; + if basis.is_empty() { + return; + } + let (cache, (mu, bound)) = UnitCache::build(plan, basis, workspace.generator.take()); + let (m, s, tol) = select_real_expm(dt.abs() * bound, drop_tol); + workspace.taylor.resize(2 * basis.len(), 0.0); + quspin_expm::ExpmOp::from_parts( + UnitOp { + cache: &cache, + plan, + }, + dt, + mu, + s as usize, + m as usize, + tol, + ) + .apply_into( + ndarray::ArrayViewMut1::from(coefficients), + &mut workspace.taylor, + ) + .expect("expm apply"); + workspace.generator = Some(cache); +} + /// Compute `exp(dt · M) · coeffs` for the in-basis-restricted generator /// `M`, matrix-free, via `quspin-expm`. Returns a fresh `Vec` of length /// `basis.len()`. @@ -511,22 +581,8 @@ pub(crate) fn expm_apply_mf( } let index = build_basis_index(basis); let (mat, per_col) = build_mf_cols(spec, basis, &index); - - // Pick the Taylor backward-error tolerance to match the basis truncation: - // when the PC prunes coarsely (drop_tol >= 1e-4) a double-precision exp is - // ~10 orders more accurate than the state it acts on, so the relaxed - // (tol=1e-6, still >=100x tighter than the cut) table is used — it admits a - // lower-degree Taylor polynomial and cuts the SpMV count with no effect on - // the truncated result. At tight/zero drop_tol we keep double precision so - // the exact-reference paths (orbit-rep / merged) still agree bit-for-bit. expm_apply_cached(&mat, &per_col, dt, coeffs, |t_norm| { - if drop_tol >= 1e-4 { - let (m, s) = expm::select_ms_loose(t_norm); - (m, s, 1e-6) - } else { - let (m, s) = expm::select_ms(t_norm); - (m, s, 1e-12) - } + select_real_expm(t_norm, drop_tol) }) } diff --git a/crates/ppvm-lindblad/src/pauli_plan.rs b/crates/ppvm-lindblad/src/pauli_plan.rs new file mode 100644 index 000000000..4afd88656 --- /dev/null +++ b/crates/ppvm-lindblad/src/pauli_plan.rs @@ -0,0 +1,246 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Shared parity tables and local phase rules for Pauli Hamiltonian actions. + +use crate::algebra::comm_product; +use crate::word::{CHUNK_BITS, Word, word_from_codes, word_hash, word_support}; +use fxhash::FxHashSet; + +struct Term { + word: Word, + sites: Option<[usize; 2]>, + signs: [i8; 16], +} + +pub(crate) struct UnitAction { + pub(crate) word: Word, + /// [`word_hash`] of `word`, computed once when the action is produced. + pub(crate) hash: u64, + pub(crate) value: f64, + pub(crate) unit: i32, +} + +pub(crate) struct PauliActionPlan { + terms: Vec>, + coefficients: Vec, + jumps: Vec, + words: usize, + tables: Vec, +} + +fn label(word: &Word, site: usize) -> usize { + let chunk = site / CHUNK_BITS; + let shift = site % CHUNK_BITS; + ((word.xbits.data[chunk] >> shift) & 1) as usize + | ((((word.zbits.data[chunk] >> shift) & 1) as usize) << 1) +} + +impl PauliActionPlan { + /// Number of Hamiltonian terms; their row-action codes are `±1..=term_count`. + pub(crate) fn term_count(&self) -> usize { + self.terms.len() + } + + pub(crate) fn has_diagonal_noise(&self) -> bool { + self.jumps.iter().any(|rate| *rate != 0.0) + } + + pub(crate) fn new(n: usize, h: &[(Word, f64)], jumps: &[(Word, f64)]) -> Option { + let mut seen = FxHashSet::default(); + if h.len() >= i32::MAX as usize || h.iter().any(|(word, _)| !seen.insert(*word)) { + return None; + } + let words = (h.len() + jumps.len()).div_ceil(64); + let mut tables = vec![0; n * 4 * words]; + for (index, (word, _)) in h.iter().chain(jumps).enumerate() { + for site in 0..n { + let generator = label(word, site); + for pauli in 1..4 { + if generator != 0 && generator != pauli { + tables[(site * 4 + pauli) * words + index / 64] |= 1u64 << (index % 64); + } + } + } + } + let terms = h + .iter() + .map(|&(word, _)| { + let mut support = Vec::new(); + word_support(&word, &mut support); + let sites = if (1..=2).contains(&support.len()) { + Some([support[0] as usize, *support.last().unwrap() as usize]) + } else { + None + }; + let mut signs = [0; 16]; + if let Some([a, b]) = sites { + for (pattern, sign) in signs.iter_mut().enumerate() { + let mut codes = vec![0; n]; + codes[a] = (pattern & 3) as u8; + if b != a { + codes[b] = (pattern >> 2) as u8; + } + *sign = comm_product(&word, &word_from_codes::(&codes).unwrap()).1 as i8; + } + } + Term { word, sites, signs } + }) + .collect(); + Some(Self { + terms, + coefficients: h.iter().map(|(_, coefficient)| *coefficient).collect(), + jumps: jumps.iter().map(|(_, rate)| *rate).collect(), + words, + tables, + }) + } + + #[cfg(test)] + pub(crate) fn fill( + &self, + word: &Word, + active: &mut Vec, + output: &mut Vec<(Word, f64)>, + ) { + output.clear(); + self.visit(word, active, |word, value, _| output.push((word, value))); + } + + /// Like [`Self::fill`], with each output word's [`word_hash`] first. + pub(crate) fn fill_keyed( + &self, + word: &Word, + active: &mut Vec, + output: &mut Vec<(u64, Word, f64)>, + ) { + output.clear(); + self.visit(word, active, |word, value, _| { + output.push((word_hash(&word), word, value)) + }); + } + + pub(crate) fn fill_units( + &self, + word: &Word, + active: &mut Vec, + output: &mut Vec>, + ) { + output.clear(); + self.visit(word, active, |word, value, unit| { + output.push(UnitAction { + hash: word_hash(&word), + word, + value, + unit, + }) + }); + } + + #[inline] + pub(crate) fn row_coefficient(&self, unit: i32) -> f64 { + let coefficient = self.coefficients[unit.unsigned_abs() as usize - 1]; + coefficient * if unit > 0 { 2.0 } else { -2.0 } + } + + // Hamiltonian codes identify the original model term and its row-action sign. + // A zero code denotes the separately accumulated Pauli-noise diagonal. + fn visit( + &self, + word: &Word, + active: &mut Vec, + mut emit: impl FnMut(Word, f64, i32), + ) { + active.clear(); + active.resize(self.words, 0); + for chunk in 0..C { + let mut support = word.xbits.data[chunk] | word.zbits.data[chunk]; + while support != 0 { + let site = chunk * CHUNK_BITS + support.trailing_zeros() as usize; + support &= support - 1; + let start = (site * 4 + label(word, site)) * self.words; + for (bits, table) in active + .iter_mut() + .zip(&self.tables[start..start + self.words]) + { + *bits ^= table; + } + } + } + let mut diagonal = 0.0; + for (block, &initial) in active.iter().enumerate() { + let mut bits = initial; + while bits != 0 { + let index = block * 64 + bits.trailing_zeros() as usize; + bits &= bits - 1; + if index >= self.terms.len() { + diagonal += -2.0 * self.jumps[index - self.terms.len()]; + continue; + } + let term = &self.terms[index]; + let (result, sign) = if let Some([a, b]) = term.sites { + let pattern = label(word, a) | if a == b { 0 } else { label(word, b) << 2 }; + let mut result = *word; + for chunk in 0..C { + result.xbits.data[chunk] ^= term.word.xbits.data[chunk]; + result.zbits.data[chunk] ^= term.word.zbits.data[chunk]; + } + (result, term.signs[pattern] as f64) + } else { + comm_product(&term.word, word) + }; + let value = self.coefficients[index] * sign; + if value != 0.0 { + let term = index as i32 + 1; + emit(result, value, if sign > 0.0 { -term } else { term }); + } + } + } + if diagonal != 0.0 { + emit(*word, diagonal, 0); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{JumpInput, LindbladSpec, parse_pauli_string}; + use num::Complex; + + #[test] + fn compiled_tables_match_every_local_pauli_and_diagonal_jump() { + let h = vec![ + ("XXII".into(), 0.3), + ("IYYI".into(), -0.7), + ("ZIIX".into(), 0.2), + ("IXYZ".into(), 0.4), + ]; + let jump = JumpInput { + lincomb: vec![("IZII".into(), Complex::new(1.0, 0.0))], + rate: 0.4, + }; + let spec = LindbladSpec::<2>::new(4, &h, &[jump]).unwrap(); + let parsed: Vec<_> = h + .iter() + .map(|(s, c)| (parse_pauli_string::<2>(s, 4).unwrap().0, *c)) + .collect(); + let jumps = [(parse_pauli_string::<2>("IZII", 4).unwrap().0, 0.4)]; + let plan = PauliActionPlan::new(4, &parsed, &jumps).unwrap(); + let mut active = Vec::new(); + let mut output = Vec::new(); + for code in 0..256 { + let word = word_from_codes::<2>( + &(0..4) + .map(|q| ((code >> (2 * q)) & 3) as u8) + .collect::>(), + ) + .unwrap(); + plan.fill(&word, &mut active, &mut output); + let mut expected = spec.action(&word); + output.sort_unstable_by_key(|(w, _)| *w); + expected.sort_unstable_by_key(|(w, _)| *w); + assert_eq!(output, expected); + } + } +} diff --git a/crates/ppvm-lindblad/src/reference.rs b/crates/ppvm-lindblad/src/reference.rs new file mode 100644 index 000000000..c5d09baa4 --- /dev/null +++ b/crates/ppvm-lindblad/src/reference.rs @@ -0,0 +1,64 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Allocating predictor-corrector step, built from the map-based leakage and +//! the column-assembled exponential, as the numerical reference for the +//! buffer-reusing [`LindbladSpec::pc_step`]. + +use crate::truncate::{add_leakage_capped, cap_basis, prune_basis}; +use crate::{Error, LindbladSpec, PcStepConfig, Word, mf_expm}; + +impl LindbladSpec { + pub(crate) fn pc_step_reference( + &self, + basis: &mut Vec>, + coeffs: &mut Vec, + dt: f64, + protected: &[Word], + cfg: &PcStepConfig, + ) -> Result<(), Error> { + self.run_in_pool(cfg, |this| { + this.pc_step_reference_inner(basis, coeffs, dt, protected, cfg) + }) + } + + fn pc_step_reference_inner( + &self, + basis: &mut Vec>, + coeffs: &mut Vec, + dt: f64, + protected: &[Word], + cfg: &PcStepConfig, + ) -> Result<(), Error> { + let PcStepConfig { + max_basis, + admit_basis, + drop_tol, + tau_add, + .. + } = *cfg; + let admit = admit_basis.unwrap_or(max_basis).max(max_basis); + let tau_add = tau_add.unwrap_or(0.0); + + let leak = self.leakage_with_prune(basis, coeffs, protected, admit, tau_add)?; + add_leakage_capped(basis, coeffs, leak, admit); + let coeffs_predict = mf_expm::expm_apply_mf(self, basis, dt, coeffs, drop_tol); + + let n_predict = basis.len(); + if admit > n_predict { + let leak2 = + self.leakage_with_prune(basis, &coeffs_predict, protected, admit, tau_add)?; + add_leakage_capped(basis, coeffs, leak2, admit); + } + if basis.len() == n_predict { + *coeffs = coeffs_predict; + } else { + drop(coeffs_predict); + *coeffs = mf_expm::expm_apply_mf(self, basis, dt, coeffs, drop_tol); + } + + prune_basis(basis, coeffs, drop_tol, protected); + cap_basis(basis, coeffs, max_basis, protected); + Ok(()) + } +} diff --git a/crates/ppvm-lindblad/src/sector.rs b/crates/ppvm-lindblad/src/sector.rs index 181d9359b..7aa648b8e 100644 --- a/crates/ppvm-lindblad/src/sector.rs +++ b/crates/ppvm-lindblad/src/sector.rs @@ -92,10 +92,11 @@ impl<'a> Sector<'a> { &self, q: &Word, ) -> Option<(Word, Complex, usize)> { - let (rep, idx, orbit_size) = self - .group - .canonicalize_in_sector_indexed(q, &self.characters)?; - Some((rep, self.characters.value(idx), orbit_size)) + let (rep, idx, orbit_size) = self.group.canonicalize_in_sector_indexed( + &q.to_general(self.group.n_qubits()), + &self.characters, + )?; + Some((Word::from(&rep), self.characters.value(idx), orbit_size)) } /// Number of **distinct** members of `w`'s translation orbit, or @@ -110,7 +111,7 @@ impl<'a> Sector<'a> { #[inline] pub fn orbit_size(&self, w: &Word) -> Option { self.group - .canonicalize_in_sector_indexed(w, &self.characters) + .canonicalize_in_sector_indexed(&w.to_general(self.group.n_qubits()), &self.characters) .map(|(_, _, orbit_size)| orbit_size) } } @@ -124,6 +125,6 @@ impl<'a> Sector<'a> { /// same rep, both are kept (caller should run a merge afterwards). pub fn canonicalize_basis_to_rep(basis: &mut [Word], group: &TranslationGroup) { for w in basis.iter_mut() { - *w = group.canonicalize(w); + *w = Word::from(&group.canonicalize(&w.to_general(group.n_qubits()))); } } diff --git a/crates/ppvm-lindblad/src/spec.rs b/crates/ppvm-lindblad/src/spec.rs index 2a86d87ed..fc637a657 100644 --- a/crates/ppvm-lindblad/src/spec.rs +++ b/crates/ppvm-lindblad/src/spec.rs @@ -53,6 +53,12 @@ fn candidate_terms(p_support: &[u32], index: &[Vec], scratch: &mut Vec /// costs more than the recompute (hash lookup ≳ recompute) and its several /// KB per cached word dominate memory at large basis sizes. pub struct LindbladSpec { + /// Buffers reused by [`Self::pc_step`], one per trajectory running + /// concurrently on this model. + pub(crate) workspaces: std::sync::Mutex>>, + /// Precompiled Pauli action, present when every jump is a Hermitian Pauli + /// (see [`crate::pauli_plan::PauliActionPlan::new`]). + pub(crate) pauli_plan: Option>, n_qubits: usize, h_terms: Vec>, j_kinds: Vec>, @@ -145,7 +151,22 @@ impl LindbladSpec { }); } + // Action tables for the fast path; only models whose jumps are all + // Hermitian Paulis have one. + let pauli_jumps: Option> = j_kinds + .iter() + .map(|j| match j { + JumpKind::HermitianPauli { word, rate } => Some((*word, *rate)), + _ => None, + }) + .collect(); + let pauli_plan = pauli_jumps.and_then(|jumps| { + let h: Vec<_> = h_parsed.iter().map(|h| (h.word, h.coeff)).collect(); + crate::pauli_plan::PauliActionPlan::new(n_qubits, &h, &jumps) + }); Ok(Self { + workspaces: std::sync::Mutex::new(Vec::new()), + pauli_plan, n_qubits, h_terms: h_parsed, j_kinds, @@ -166,6 +187,7 @@ impl LindbladSpec { ops: &[Vec<(String, Complex)>], k: &[Vec>], ) -> Result<(), Error> { + self.pauli_plan = None; for (pair, support) in kossakowski::compile(ops, k, self.n_qubits)? { let idx = self.j_kinds.len() as u32; self.j_kinds.push(JumpKind::Kossakowski(pair)); diff --git a/crates/ppvm-lindblad/src/step.rs b/crates/ppvm-lindblad/src/step.rs index debd9666f..70236f051 100644 --- a/crates/ppvm-lindblad/src/step.rs +++ b/crates/ppvm-lindblad/src/step.rs @@ -3,9 +3,11 @@ //! Predictor-corrector adaptive step `O ← exp(dt·L*) O`. +use crate::basis::PcStepWorkspace; +use crate::candidates::{CandidateBuffer, CandidateProposer, StreamingProposer}; use crate::sector::Sector; use crate::spec::LindbladSpec; -use crate::truncate::{add_leakage_capped, cap_basis, prune_basis}; +use crate::truncate::{add_leakage_capped, cap_basis, cap_basis_with_scratch, prune_basis}; use crate::word::Word; use crate::{Error, PcStepConfig, mf_expm}; use num::Complex; @@ -75,10 +77,8 @@ impl LindbladSpec { protected: &[Word], cfg: &PcStepConfig, ) -> Result<(), Error> { - self.run_in_pool(cfg, |this| { - this.pc_step_inner(basis, coeffs, dt, protected, cfg, false) - .map(|_| ()) - }) + self.pc_step_pooled::>(basis, coeffs, dt, protected, cfg, false, None) + .map(|_| ()) } /// Same as [`Self::pc_step`] but also returns a per-phase timing @@ -92,12 +92,91 @@ impl LindbladSpec { protected: &[Word], cfg: &PcStepConfig, ) -> Result { - self.run_in_pool(cfg, |this| { - this.pc_step_inner(basis, coeffs, dt, protected, cfg, true) - }) + self.pc_step_pooled::>(basis, coeffs, dt, protected, cfg, true, None) } - fn run_in_pool( + /// Same as [`Self::pc_step_timed`], but `proposer` chooses which strings + /// each enlargement admits instead of the default [`StreamingProposer`]. + /// The step's other buffers are still reused automatically. + pub fn pc_step_with_proposer>( + &self, + basis: &mut Vec>, + coeffs: &mut Vec, + dt: f64, + protected: &[Word], + cfg: &PcStepConfig, + proposer: &mut P, + ) -> Result { + self.pc_step_pooled(basis, coeffs, dt, protected, cfg, true, Some(proposer)) + } + + /// Run one step with a workspace checked out of the model's pool, using + /// `proposer` or, if `None`, the workspace's [`StreamingProposer`]. + #[allow(clippy::too_many_arguments)] + fn pc_step_pooled>( + &self, + basis: &mut Vec>, + coeffs: &mut Vec, + dt: f64, + protected: &[Word], + cfg: &PcStepConfig, + timed: bool, + proposer: Option<&mut P>, + ) -> Result { + if basis.len() != coeffs.len() { + return Err(Error::LengthMismatch { + what: "basis and coeffs", + a: basis.len(), + b: coeffs.len(), + }); + } + // Only checkout and return hold the lock; concurrent trajectories use separate buffers. + let mut workspace = self + .workspaces + .lock() + .unwrap_or_else(|error| error.into_inner()) + .pop() + .unwrap_or_default(); + reserve_step_capacity(self.n_qubits(), basis, coeffs, cfg, &mut workspace); + let result = match proposer { + Some(proposer) => self.run_in_pool(cfg, |this| { + this.pc_step_inner( + basis, + coeffs, + dt, + protected, + cfg, + timed, + &mut workspace, + proposer, + ) + }), + None => { + let mut streaming = std::mem::take(&mut workspace.proposer); + let result = self.run_in_pool(cfg, |this| { + this.pc_step_inner( + basis, + coeffs, + dt, + protected, + cfg, + timed, + &mut workspace, + &mut streaming, + ) + }); + workspace.proposer = streaming; + result + } + }; + self.workspaces + .lock() + .unwrap_or_else(|error| error.into_inner()) + .push(workspace); + result + } + + pub(crate) fn run_in_pool( &self, cfg: &PcStepConfig, f: impl FnOnce(&Self) -> Result + Send, @@ -113,7 +192,8 @@ impl LindbladSpec { } } - fn pc_step_inner( + #[allow(clippy::too_many_arguments)] + fn pc_step_inner>( &self, basis: &mut Vec>, coeffs: &mut Vec, @@ -121,6 +201,8 @@ impl LindbladSpec { protected: &[Word], cfg: &PcStepConfig, timed: bool, + workspace: &mut PcStepWorkspace, + proposer: &mut P, ) -> Result { let PcStepConfig { max_basis, @@ -138,67 +220,72 @@ impl LindbladSpec { let admit = admit_basis.unwrap_or(max_basis).max(max_basis); let tau_add = tau_add.unwrap_or(0.0); let mut t = PcStepTimings::default(); + let original_terms = basis.len(); - // 1. First-hop expansion. After this, `coeffs` contains the pre-step - // coefficients followed by zeros for the newly-added leakage strings. - // We rely on `coeffs` itself as the pre-step buffer for the corrector - // — no `.clone()` is needed because `expm_step` only borrows it. + // 1. First-hop expansion. Admitted words are appended to `basis` with + // zero coefficients. No basis permutation occurs before the final + // truncation, so the pre-step coefficients stay at their positions. let p = Phase::start(timed); - let leak = self.leakage_with_prune(basis, coeffs, protected, admit, tau_add)?; + let mut buffer = CandidateBuffer::new(basis, coeffs, &mut workspace.taylor); + proposer.propose(self, &mut buffer, protected, admit)?; p.stop(&mut t.leakage1_us); let p = Phase::start(timed); - add_leakage_capped(basis, coeffs, leak, admit); + admit_selected(proposer, buffer, tau_add, admit); + coeffs.resize(basis.len(), 0.0); p.stop(&mut t.expand1_us); - // 2. Predictor: `expm_step` reads `coeffs` immutably and returns a - // new owned vector with the predicted state. + // The exponential overwrites `coeffs`. Save the pre-step coefficients + // only when a second hop, and hence a corrector, is still possible. + if basis.len() < admit { + workspace.coefficient_auxiliary.clear(); + workspace + .coefficient_auxiliary + .extend_from_slice(&coeffs[..original_terms]); + } + + // 2. Predictor, in place. let p = Phase::start(timed); - let coeffs_predict = self.expm_step(basis, dt, coeffs, drop_tol); + mf_expm::expm_apply_inplace(self, basis, dt, coeffs, drop_tol, workspace); p.stop(&mut t.expm1_us); - // 3. Second-hop expansion from the predicted state. Extend `coeffs` - // with zeros for any newly-added second-hop strings so it remains a - // valid input (pre-step state) for the corrector. Once the basis is + // 3. Second-hop expansion from the predicted state. Once the basis is // full, the first hop usually fills the whole admission room; with // `room = 0` the second hop can admit nothing, so its leakage pass // is skipped. let n_predict = basis.len(); if admit > n_predict { let p = Phase::start(timed); - let leak2 = - self.leakage_with_prune(basis, &coeffs_predict, protected, admit, tau_add)?; + let mut buffer = CandidateBuffer::new(basis, coeffs, &mut workspace.taylor); + proposer.propose(self, &mut buffer, protected, admit)?; p.stop(&mut t.leakage2_us); let p = Phase::start(timed); - add_leakage_capped(basis, coeffs, leak2, admit); + admit_selected(proposer, buffer, tau_add, admit); + coeffs.resize(basis.len(), 0.0); p.stop(&mut t.expand2_us); } - // 4. Corrector: redo from pre-step state on the doubly-enlarged basis. - // If the second hop admitted nothing, the corrector would repeat the - // predictor's computation exactly, so the predicted state is kept. - if basis.len() == n_predict { - *coeffs = coeffs_predict; - } else { - drop(coeffs_predict); + // 4. Corrector: redo from the saved pre-step state on the enlarged + // basis. If the second hop admitted nothing, the corrector would + // repeat the predictor's computation exactly, so the predicted state + // is kept. + if basis.len() != n_predict { let p = Phase::start(timed); - *coeffs = self.expm_step(basis, dt, coeffs, drop_tol); + coeffs.clear(); + coeffs.extend_from_slice(&workspace.coefficient_auxiliary); + coeffs.resize(basis.len(), 0.0); + mf_expm::expm_apply_inplace(self, basis, dt, coeffs, drop_tol, workspace); p.stop(&mut t.expm2_us); } // 5. Prune basis entries below `drop_tol` (protected words never dropped). prune_basis(basis, coeffs, drop_tol, protected); - cap_basis(basis, coeffs, max_basis, protected); + // The exponential's work vector is idle until the next step's proposal. + cap_basis_with_scratch(basis, coeffs, max_basis, protected, &mut workspace.taylor); Ok(t) } - /// Compute `exp(dt · M) · b` for the in-basis-restricted generator - /// `M`, matrix-free, via `quspin-expm` (see [`crate::mf_expm`]). - fn expm_step(&self, basis: &[Word], dt: f64, b: &[f64], drop_tol: f64) -> Vec { - mf_expm::expm_apply_mf(self, basis, dt, b, drop_tol) - } - /// One predictor-corrector step in **orbit-rep form** at momentum /// `sector`: the same five phases as [`Self::pc_step`], but the basis /// holds only canonical translation-orbit representatives, the @@ -297,3 +384,257 @@ impl LindbladSpec { Ok(()) } } + +/// Let `proposer` select from `buffer`'s candidates and move them into the +/// basis, checking the admission bound `admit`. +fn admit_selected>( + proposer: &mut P, + mut buffer: CandidateBuffer<'_, C>, + threshold: f64, + admit: usize, +) { + let count = proposer.select(&mut buffer, threshold); + assert!( + count <= admit.saturating_sub(buffer.basis().len()), + "proposer selected more candidates than the admission bound allows" + ); + buffer.finish(count); +} + +/// Reserve the step's arrays from the active state, not from `max_basis`, +/// which may be an arbitrarily large rank limit. The two enlargements can +/// grow the basis to about three times its active size, bounded by the +/// admission cap and the number of Pauli strings on the register. +fn reserve_step_capacity( + n_qubits: usize, + basis: &mut Vec>, + coeffs: &mut Vec, + cfg: &PcStepConfig, + workspace: &mut PcStepWorkspace, +) { + let dimension = 1usize + .checked_shl((2 * n_qubits) as u32) + .unwrap_or(usize::MAX); + let admit = cfg.admit_basis.unwrap_or(cfg.max_basis).max(cfg.max_basis); + let active = basis.len().min(cfg.max_basis); + let bound = active.saturating_mul(3).min(admit).min(dimension); + if let Some(required) = bound.checked_mul(2) + && workspace.taylor.capacity() < required + { + workspace + .taylor + .reserve_exact(required - workspace.taylor.len()); + } + if let Some(reserve) = active.checked_mul(4) { + let reserve = reserve.max(bound).min(dimension); + if basis.capacity() < reserve { + basis.reserve_exact(reserve.saturating_sub(basis.len())); + } + if coeffs.capacity() < reserve { + coeffs.reserve_exact(reserve.saturating_sub(coeffs.len())); + } + } +} + +#[cfg(test)] +mod default_tests { + use super::*; + use crate::{JumpInput, word_from_codes}; + + #[test] + fn default_step_matches_original_with_general_jumps_and_kossakowski() { + let h = vec![ + ("XXI".into(), 0.3), + ("IYY".into(), -0.17), + ("XXI".into(), 0.13), + ]; + let jumps = vec![JumpInput { + lincomb: vec![ + ("XII".into(), Complex::new(0.5, 0.0)), + ("YII".into(), Complex::new(0.0, 0.5)), + ], + rate: 0.4, + }]; + let mut reference = LindbladSpec::<2>::new(3, &h, &jumps).unwrap(); + let mut optimized = LindbladSpec::<2>::new(3, &h, &jumps).unwrap(); + let operators = vec![ + vec![("IXI".into(), Complex::new(1.0, 0.0))], + vec![("IYI".into(), Complex::new(1.0, 0.0))], + ]; + let k = vec![ + vec![Complex::new(0.1, 0.0), Complex::new(0.0, 0.02)], + vec![Complex::new(0.0, -0.02), Complex::new(0.2, 0.0)], + ]; + reference.add_kossakowski(&operators, &k).unwrap(); + optimized.add_kossakowski(&operators, &k).unwrap(); + let seed = word_from_codes::<2>(&[2, 0, 0]).unwrap(); + let (mut a, mut b) = (vec![seed], vec![seed]); + let (mut ca, mut cb) = (vec![1.0], vec![1.0]); + for step in 0..12 { + let cfg = PcStepConfig { + max_basis: 8 + step % 3, + admit_basis: Some(24 + step % 4), + drop_tol: 1e-7, + num_threads: Some(2), + ..Default::default() + }; + reference + .pc_step_reference(&mut a, &mut ca, 0.1, &[seed], &cfg) + .unwrap(); + optimized + .pc_step(&mut b, &mut cb, 0.1, &[seed], &cfg) + .unwrap(); + assert_eq!(a, b); + assert_eq!(ca, cb); + } + let pool = optimized.workspaces.lock().unwrap(); + assert_eq!(pool.len(), 1); + assert!(pool[0].taylor.capacity() > 0); + assert!(pool[0].generator.is_none()); + } + + #[test] + fn concurrent_default_trajectories_share_model_without_sharing_scratch() { + let spec = + LindbladSpec::<2>::new(3, &[("XXI".into(), 0.3), ("IYY".into(), -0.17)], &[]).unwrap(); + let barrier = std::sync::Barrier::new(4); + std::thread::scope(|scope| { + for trajectory in 0..4 { + let spec = &spec; + let barrier = &barrier; + scope.spawn(move || { + let seed = word_from_codes::<2>(&[trajectory % 3 + 1, 0, 0]).unwrap(); + let cfg = PcStepConfig { + max_basis: 8 + trajectory as usize, + admit_basis: Some(24), + ..Default::default() + }; + let (mut a, mut b) = (vec![seed], vec![seed]); + let (mut ca, mut cb) = (vec![1.0], vec![1.0]); + barrier.wait(); + for _ in 0..6 { + spec.pc_step_reference(&mut a, &mut ca, 0.1, &[seed], &cfg) + .unwrap(); + spec.pc_step(&mut b, &mut cb, 0.1, &[seed], &cfg).unwrap(); + assert_eq!(a, b); + assert_eq!(ca, cb); + } + }); + } + }); + let pool = spec.workspaces.lock().unwrap(); + assert!(!pool.is_empty()); + assert!(pool.len() <= 4); + } + #[test] + fn large_rank_limit_does_not_eagerly_allocate_for_a_small_state() { + let n = 129; + let mut z = vec!['I'; n]; + z[0] = 'Z'; + let spec = LindbladSpec::<4>::new(n, &[(z.into_iter().collect(), 0.37)], &[]).unwrap(); + let mut codes = vec![0; n]; + codes[0] = 2; + let seed = word_from_codes::<4>(&codes).unwrap(); + let mut basis = vec![seed]; + let mut coeffs = vec![1.0]; + let cfg = PcStepConfig { + max_basis: 1 << 30, + admit_basis: Some(3 << 30), + ..Default::default() + }; + spec.pc_step(&mut basis, &mut coeffs, 0.1, &[seed], &cfg) + .unwrap(); + assert_eq!(basis, vec![seed]); + assert_eq!(coeffs, vec![1.0]); + assert!(basis.capacity() <= 8); + assert!(coeffs.capacity() <= 8); + let pool = spec.workspaces.lock().unwrap(); + assert!(pool[0].taylor.capacity() <= 16); + assert!(pool[0].coefficient_auxiliary.capacity() <= 8); + } + + #[test] + fn pauli_noise_step_matches_reference_and_keeps_caller_storage() { + let h = vec![ + ("XXI".into(), 0.3), + ("IYY".into(), -0.7), + ("ZII".into(), 0.2), + ]; + let jumps = vec![JumpInput { + lincomb: vec![("IZI".into(), Complex::new(1.0, 0.0))], + rate: 0.2, + }]; + let spec = LindbladSpec::<2>::new(3, &h, &jumps).unwrap(); + let seed = word_from_codes::<2>(&[3, 0, 0]).unwrap(); + let (mut a, mut b) = (vec![seed], vec![seed]); + let (mut ca, mut cb) = (vec![1.0], vec![1.0]); + b.reserve_exact(64 - b.len()); + cb.reserve_exact(64 - cb.len()); + let basis_storage = b.as_ptr(); + let coefficient_storage = cb.as_ptr(); + for step in 0..12 { + let cfg = PcStepConfig { + max_basis: if step == 0 { usize::MAX } else { 8 + step % 3 }, + admit_basis: if step == 0 { None } else { Some(24 + step % 4) }, + num_threads: Some(2), + ..Default::default() + }; + spec.pc_step_reference(&mut a, &mut ca, 0.1, &[seed], &cfg) + .unwrap(); + spec.pc_step(&mut b, &mut cb, 0.1, &[seed], &cfg).unwrap(); + assert_eq!(b.as_ptr(), basis_storage); + assert_eq!(cb.as_ptr(), coefficient_storage); + assert_eq!(a, b); + assert_eq!(ca, cb); + } + } + + /// The paired cache and the column-assembled reference sum in different + /// orders, so coefficients agree to rounding rather than bit for bit. + #[test] + fn pauli_noise_step_matches_reference_beyond_one_hundred_twenty_eight_qubits() { + let n = 129; + let term = |symbol: char, sites: &[usize]| { + let mut symbols = vec!['I'; n]; + for &site in sites { + symbols[site] = symbol; + } + symbols.into_iter().collect::() + }; + let h = vec![ + (term('X', &[0, 128]), 0.25), + (term('Y', &[64, 128]), -0.25), + (term('Z', &[0]), 0.25), + ]; + let jumps = vec![JumpInput { + lincomb: vec![(term('Z', &[64]), Complex::new(1.0, 0.0))], + rate: 0.2, + }]; + let spec = LindbladSpec::<4>::new(n, &h, &jumps).unwrap(); + let mut codes = vec![0; n]; + codes[128] = 2; + let seed = word_from_codes::<4>(&codes).unwrap(); + let (mut a, mut b) = (vec![seed], vec![seed]); + let (mut ca, mut cb) = (vec![1.0], vec![1.0]); + let cfg = PcStepConfig { + max_basis: 16, + admit_basis: Some(48), + num_threads: Some(2), + ..Default::default() + }; + for _ in 0..8 { + spec.pc_step_reference(&mut a, &mut ca, 0.1, &[seed], &cfg) + .unwrap(); + spec.pc_step(&mut b, &mut cb, 0.1, &[seed], &cfg).unwrap(); + let mut expected: Vec<_> = a.iter().copied().zip(ca.iter().copied()).collect(); + let mut actual: Vec<_> = b.iter().copied().zip(cb.iter().copied()).collect(); + expected.sort_unstable_by_key(|entry| entry.0); + actual.sort_unstable_by_key(|entry| entry.0); + assert_eq!(expected.len(), actual.len()); + for ((word_a, value_a), (word_b, value_b)) in expected.iter().zip(&actual) { + assert_eq!(word_a, word_b); + assert!((value_a - value_b).abs() < 2e-13); + } + } + } +} diff --git a/crates/ppvm-lindblad/src/tests.rs b/crates/ppvm-lindblad/src/tests.rs index 5c5666ba4..b4a72003e 100644 --- a/crates/ppvm-lindblad/src/tests.rs +++ b/crates/ppvm-lindblad/src/tests.rs @@ -5,6 +5,34 @@ use super::*; use fxhash::FxHashMap; use num::Complex; +/// `ppvm_pauli_sum` symmetry merges on the crate's compact words, via the general word type. +fn canonicalize_pauli_sum_complex( + basis: &mut Vec>, + coeffs: &mut Vec>, + group: &ppvm_pauli_sum::symmetry::TranslationGroup, + k: &[i32], +) { + let mut words: Vec<_> = basis + .iter() + .map(|w| w.to_general(group.n_qubits())) + .collect(); + ppvm_pauli_sum::symmetry::canonicalize_pauli_sum_complex(&mut words, coeffs, group, k); + *basis = words.iter().map(Word::from).collect(); +} + +fn canonicalize_pauli_sum( + basis: &mut Vec>, + coeffs: &mut Vec, + group: &ppvm_pauli_sum::symmetry::TranslationGroup, +) { + let mut words: Vec<_> = basis + .iter() + .map(|w| w.to_general(group.n_qubits())) + .collect(); + ppvm_pauli_sum::symmetry::canonicalize_pauli_sum(&mut words, coeffs, group); + *basis = words.iter().map(Word::from).collect(); +} + /// Test-only full-space complex predictor-corrector step, UNTRUNCATED: /// adds every nonzero leakage string (two hops) and applies the exact /// in-basis exponential to the complex coefficient vector. Reference @@ -125,8 +153,6 @@ fn assert_orbit_rep_matches_projection( dt: f64, n_steps: usize, ) { - use ppvm_pauli_sum::symmetry::canonicalize_pauli_sum_complex; - let spec = ::new(n, h_terms, &[]).unwrap(); let group = ppvm_pauli_sum::symmetry::TranslationGroup::chain_1d(n); let basis_full: Vec = seed @@ -178,7 +204,7 @@ fn assert_orbit_rep_matches_projection( let cf_val = mf .get(w) .copied() - .unwrap_or_else(|| panic!("rep {w} in orbit-rep but not in full-basis")); + .unwrap_or_else(|| panic!("rep {w:?} in orbit-rep but not in full-basis")); max_diff = max_diff.max((cm - cf_val).norm()); } assert!( @@ -326,7 +352,7 @@ fn complex_full_matches_real_at_kzero() { /// bit-identical up to FP noise. #[test] fn pc_step_matches_symmetry_merged_on_small_chain() { - use ppvm_pauli_sum::symmetry::{TranslationGroup, canonicalize_pauli_sum}; + use ppvm_pauli_sum::symmetry::TranslationGroup; let n = 4usize; let dt = 0.05f64; @@ -482,7 +508,7 @@ fn pc_step_is_bit_identical_across_thread_counts() { /// duplicate columns. The cap binds. #[test] fn pc_step_orbit_rep_is_bit_identical_across_thread_counts() { - use ppvm_pauli_sum::symmetry::{TranslationGroup, canonicalize_pauli_sum_complex}; + use ppvm_pauli_sum::symmetry::TranslationGroup; let n = 12usize; let lincomb: Vec<(String, Complex)> = (0..n) @@ -579,3 +605,30 @@ fn action_term_order_is_independent_of_scratch_capacity() { ); } } + +#[test] +fn compact_word_is_two_planes_and_hashes_and_orders_like_pauli_word() { + use std::hash::{BuildHasher, Hash, Hasher}; + assert_eq!(std::mem::size_of::>(), 32); + let fx = |h: &dyn Fn(&mut fxhash::FxHasher)| { + let mut state = fxhash::FxBuildHasher::default().build_hasher(); + h(&mut state); + state.finish() + }; + let words: Vec> = (0..400u64) + .map(|i| { + let codes: Vec = (0..100) + .map(|q| ((i.wrapping_mul(0x9e37_79b9_7f4a_7c15) >> (q % 61)) & 3) as u8) + .collect(); + word_from_codes::<2>(&codes).unwrap() + }) + .collect(); + for a in &words { + let pa = a.to_general(100); + assert_eq!(fx(&|s| a.hash(s)), fx(&|s| pa.hash(s))); + assert_eq!(Word::from(&pa), *a); + for b in words.iter().take(40) { + assert_eq!(a.cmp(b), pa.cmp(&b.to_general(100))); + } + } +} diff --git a/crates/ppvm-lindblad/src/truncate.rs b/crates/ppvm-lindblad/src/truncate.rs index 308e5e0a5..ae9f91a3a 100644 --- a/crates/ppvm-lindblad/src/truncate.rs +++ b/crates/ppvm-lindblad/src/truncate.rs @@ -68,6 +68,17 @@ pub(crate) fn cap_basis( coeffs: &mut Vec, max_basis: usize, protected: &[Word], +) { + cap_basis_with_scratch(basis, coeffs, max_basis, protected, &mut Vec::new()); +} + +/// [`cap_basis`] computing the magnitudes in `mags`, so an idle work buffer can hold them. +pub(crate) fn cap_basis_with_scratch( + basis: &mut Vec>, + coeffs: &mut Vec, + max_basis: usize, + protected: &[Word], + mags: &mut Vec, ) { if basis.len() <= max_basis { return; @@ -75,16 +86,18 @@ pub(crate) fn cap_basis( let protected_set: FxHashSet<&Word> = protected.iter().collect(); let n_prot = basis.iter().filter(|w| protected_set.contains(w)).count(); let slots = max_basis.saturating_sub(n_prot); - let mut mags: Vec = basis - .iter() - .zip(coeffs.iter()) - .filter(|(w, _)| !protected_set.contains(w)) - .map(|(_, c)| c.mag()) - .collect(); + mags.clear(); + mags.extend( + basis + .iter() + .zip(coeffs.iter()) + .filter(|(w, _)| !protected_set.contains(w)) + .map(|(_, c)| c.mag()), + ); if slots >= mags.len() { return; } - let mut keep = top_k_keeper(&mut mags, slots); + let mut keep = top_k_keeper(mags, slots); retain_in_place(basis, coeffs, |w, c| { protected_set.contains(w) || keep(c.mag()) }); diff --git a/crates/ppvm-lindblad/src/unit_expm.rs b/crates/ppvm-lindblad/src/unit_expm.rs new file mode 100644 index 000000000..51f325e51 --- /dev/null +++ b/crates/ppvm-lindblad/src/unit_expm.rs @@ -0,0 +1,670 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Coefficient-free Hamiltonian connections referencing the original model terms. +//! +//! A unit plan exists only when every dissipator is a Hermitian Pauli jump, so all +//! off-diagonal generator entries come from the Hamiltonian, with any noise on the +//! diagonal. In the orthonormal Pauli basis a Hamiltonian commutator is real +//! antisymmetric, term by term: row `i` reaches parent `j` through term `k` exactly when +//! row `j` reaches `i` through `k` with the opposite sign. Projection onto the working +//! basis keeps this, so the cache stores each connected pair once and the product +//! applies it in both directions. + +use crate::compact_index::CompactBasisIndex; +use crate::pauli_plan::{PauliActionPlan, UnitAction}; +use crate::word::Word; +use quspin_types::{LinearOperator, QuSpinError}; +use rayon::prelude::*; + +/// Signed Hamiltonian term code stored with each pair: 16 bits when the model has at +/// most `i16::MAX` terms, otherwise 32 bits. +trait Code: Copy + Default + Send + Sync { + fn pack(unit: i32) -> Self; + fn unit(self) -> i32; +} + +impl Code for i16 { + fn pack(unit: i32) -> Self { + unit as i16 + } + fn unit(self) -> i32 { + self as i32 + } +} + +impl Code for i32 { + fn pack(unit: i32) -> Self { + unit + } + fn unit(self) -> i32 { + self + } +} + +/// One stored pair: block-local row and parent positions and the signed term code +/// for the row's direction. The parent's block is given by the tile holding the entry. +#[derive(Clone, Copy, Default)] +struct Entry { + row: u16, + parent: u16, + unit: U, +} + +const _: () = assert!(std::mem::size_of::>() == 6); +const _: () = assert!(std::mem::size_of::>() == 8); + +/// Largest block-size exponent that keeps block-local positions in 16 bits. +const MAX_SHIFT: u32 = 16; + +/// Rows of one block and the pairs it owns, grouped by the other row's block. +struct Block { + /// `entries[tiles[b]..tiles[b + 1]]` pair rows of this block with rows of block `b`. + tiles: Vec, + entries: Vec>, + diagonal: Vec, +} + +impl Default for Block { + fn default() -> Self { + Self { + tiles: Vec::new(), + entries: Vec::new(), + diagonal: Vec::new(), + } + } +} + +enum Blocks { + Narrow(Vec>), + Wide(Vec>), +} + +pub(crate) struct UnitCache { + blocks: Blocks, + shift: u32, + dimension: usize, +} + +/// The block storing pairs between blocks `a` and `b`. Alternating the owner by parity +/// gives every block about half of its pairs, which balances both product passes. +fn owner(a: usize, b: usize) -> usize { + if (a + b).is_multiple_of(2) { + a.max(b) + } else { + a.min(b) + } +} + +/// Running reduction for the exponential's shift and norm bound without per-row storage. +/// +/// The exponential takes `mu` as the mean diagonal and the bound as the largest +/// `raw - |d| + |d - mu|` over rows, as in [`crate::mf_expm`]'s column-norm bound. Since `|d - mu| = max(d - mu, mu - d)`, that +/// maximum equals `max(max(raw - |d| + d) - mu, max(raw - |d| - d) + mu)`, which needs only +/// two running maxima and the diagonal sum. +#[derive(Clone, Copy)] +struct Bounds { + diagonal_sum: f64, + above: f64, + below: f64, + raw: f64, +} + +impl Default for Bounds { + fn default() -> Self { + Self { + diagonal_sum: 0.0, + above: f64::NEG_INFINITY, + below: f64::NEG_INFINITY, + raw: 0.0, + } + } +} + +impl Bounds { + fn add(&mut self, raw: f64, diagonal: f64) { + let off = raw - diagonal.abs(); + self.diagonal_sum += diagonal; + self.above = self.above.max(off + diagonal); + self.below = self.below.max(off - diagonal); + self.raw = self.raw.max(raw); + } + + fn merge(self, other: Self) -> Self { + Self { + diagonal_sum: self.diagonal_sum + other.diagonal_sum, + above: self.above.max(other.above), + below: self.below.max(other.below), + raw: self.raw.max(other.raw), + } + } + + fn finish(self, dimension: usize, noisy: bool) -> (f64, f64) { + if !noisy { + return (0.0, self.raw); + } + let mu = self.diagonal_sum / dimension as f64; + (mu, (self.above - mu).max(self.below + mu).max(0.0)) + } +} + +impl UnitCache { + #[cfg(test)] + fn block_count(&self) -> usize { + match &self.blocks { + Blocks::Narrow(b) => b.len(), + Blocks::Wide(b) => b.len(), + } + } + + pub(crate) fn build( + plan: &PauliActionPlan, + basis: &[Word], + previous: Option, + ) -> (Self, (f64, f64)) { + let dimension = basis.len(); + let shift = dimension + .div_ceil(256) + .max(64) + .next_power_of_two() + .trailing_zeros() + .min(MAX_SHIFT); + let index = CompactBasisIndex::new(basis); + let previous = previous.map(|cache| cache.blocks); + let (blocks, bounds) = if plan.term_count() <= i16::MAX as usize { + let blocks = match previous { + Some(Blocks::Narrow(blocks)) => blocks, + _ => Vec::new(), + }; + let (blocks, bounds) = build_blocks(plan, basis, &index, shift, blocks); + (Blocks::Narrow(blocks), bounds) + } else { + let blocks = match previous { + Some(Blocks::Wide(blocks)) => blocks, + _ => Vec::new(), + }; + let (blocks, bounds) = build_blocks(plan, basis, &index, shift, blocks); + (Blocks::Wide(blocks), bounds) + }; + ( + Self { + blocks, + shift, + dimension, + }, + bounds, + ) + } +} + +fn build_blocks( + plan: &PauliActionPlan, + basis: &[Word], + index: &CompactBasisIndex<'_, C>, + shift: u32, + mut blocks: Vec>, +) -> (Vec>, (f64, f64)) { + let dimension = basis.len(); + let rows = 1 << shift; + let count = dimension.div_ceil(rows); + let noisy = plan.has_diagonal_noise(); + blocks.resize_with(count, Block::default); + let metadata: Vec<_> = blocks + .par_iter_mut() + .enumerate() + .map_init( + || { + ( + Vec::::new(), + Vec::>::new(), + Vec::<(u32, Entry)>::new(), + Vec::::new(), + ) + }, + |(active, actions, staged, cursor), (block, storage)| { + let first = block * rows; + let length = rows.min(dimension - first); + staged.clear(); + storage.diagonal.clear(); + if noisy { + storage.diagonal.resize(length, 0.0); + } + let mut bounds = Bounds::default(); + for (row, word) in basis[first..first + length].iter().enumerate() { + plan.fill_units(word, active, actions); + // Hash order keeps successive index probes close together. + actions.sort_unstable_by(|a, b| { + a.hash.cmp(&b.hash).then_with(|| a.word.cmp(&b.word)) + }); + let mut raw = 0.0; + let mut diagonal = 0.0; + for action in actions.iter() { + raw += action.value.abs(); + if action.unit == 0 { + diagonal = action.value; + continue; + } + let Some(parent) = index.get_hashed(&action.word, action.hash) else { + continue; + }; + let parent = parent as usize; + let other = parent >> shift; + let stored = if other == block { + parent < first + row + } else { + owner(block, other) == block + }; + if stored { + staged.push(( + other as u32, + Entry { + row: row as u16, + parent: (parent - (other << shift)) as u16, + unit: U::pack(action.unit), + }, + )); + } + } + bounds.add(raw, diagonal); + if noisy { + storage.diagonal[row] = diagonal; + } + } + // Group entries by tile, keeping row order within each tile. + storage.tiles.clear(); + storage.tiles.resize(count + 1, 0); + for &(tile, _) in staged.iter() { + storage.tiles[tile as usize + 1] += 1; + } + for tile in 0..count { + storage.tiles[tile + 1] += storage.tiles[tile]; + } + // Entry storage keeps its capacity between builds and grows only when a + // build needs more, with 1/16 headroom, so capacity tracks the block's + // entry count and the allocation stays stable across exponentials. + storage.entries.clear(); + if storage.entries.capacity() < staged.len() { + storage.entries = Vec::new(); + storage + .entries + .reserve_exact(staged.len() + staged.len() / 16); + } + storage.entries.resize(staged.len(), Entry::default()); + cursor.clear(); + cursor.extend_from_slice(&storage.tiles[..count]); + for &(tile, entry) in staged.iter() { + let slot = &mut cursor[tile as usize]; + storage.entries[*slot as usize] = entry; + *slot += 1; + } + bounds + }, + ) + .collect(); + let bounds = metadata + .into_iter() + .fold(Bounds::default(), Bounds::merge) + .finish(dimension, noisy); + (blocks, bounds) +} + +pub(crate) struct UnitOp<'a, const C: usize> { + pub(crate) cache: &'a UnitCache, + pub(crate) plan: &'a PauliActionPlan, +} + +impl LinearOperator for UnitOp<'_, C> { + fn dim(&self) -> usize { + self.cache.dimension + } + fn parallel_hint(&self) -> bool { + false + } + fn dot(&self, overwrite: bool, input: &[f64], output: &mut [f64]) -> Result<(), QuSpinError> { + let shift = self.cache.shift; + match &self.cache.blocks { + Blocks::Narrow(blocks) => product(blocks, shift, self.plan, overwrite, input, output), + Blocks::Wide(blocks) => product(blocks, shift, self.plan, overwrite, input, output), + } + Ok(()) + } + fn trace(&self) -> f64 { + unreachable!("trace supplied to exponential") + } + fn onenorm(&self, _: f64) -> f64 { + unreachable!("norm supplied to exponential") + } + fn dot_transpose(&self, _: bool, _: &[f64], _: &mut [f64]) -> Result<(), QuSpinError> { + unreachable!("transpose unused by single-vector exponential") + } + fn dot_many( + &self, + _: bool, + _: ndarray::ArrayView2<'_, f64>, + _: ndarray::ArrayViewMut2<'_, f64>, + ) -> Result<(), QuSpinError> { + unreachable!("multiple vectors unused by single-vector exponential") + } + fn dot_chunk(&self, _: bool, _: &[f64], _: &mut [f64], _: usize) -> Result<(), QuSpinError> { + unreachable!("chunk products unused by single-vector exponential") + } + fn dot_transpose_chunk( + &self, + _: &[f64], + _: &[::Atomic], + _: std::ops::Range, + ) -> Result<(), QuSpinError> { + unreachable!("transpose chunks unused by single-vector exponential") + } +} + +fn product( + blocks: &[Block], + shift: u32, + plan: &PauliActionPlan, + overwrite: bool, + input: &[f64], + output: &mut [f64], +) { + let rows = 1usize << shift; + let slice = |block: usize| &input[block * rows..((block + 1) * rows).min(input.len())]; + // Rows gather from the pairs their block owns, in the stored direction. + output + .par_chunks_mut(rows) + .zip(blocks.par_iter()) + .enumerate() + .for_each(|(block, (output, storage))| { + let own = slice(block); + if storage.diagonal.is_empty() { + if overwrite { + output.fill(0.0); + } + } else { + for ((result, &d), &x) in output.iter_mut().zip(&storage.diagonal).zip(own) { + let value = if x != 0.0 { d * x } else { 0.0 }; + *result = if overwrite { value } else { *result + value }; + } + } + for other in 0..blocks.len() { + let x = slice(other); + let tile = storage.tiles[other] as usize..storage.tiles[other + 1] as usize; + for entry in &storage.entries[tile] { + let value = x[entry.parent as usize]; + if value != 0.0 { + output[entry.row as usize] += + plan.row_coefficient(entry.unit.unit()) * value; + } + } + } + }); + // Rows receive the mirrored direction of pairs owned by other blocks (and of + // their own block's pairs), with the opposite sign. + output + .par_chunks_mut(rows) + .enumerate() + .for_each(|(block, output)| { + for (other, storage) in blocks.iter().enumerate() { + let x = slice(other); + let tile = storage.tiles[block] as usize..storage.tiles[block + 1] as usize; + for entry in &storage.entries[tile] { + let value = x[entry.row as usize]; + if value != 0.0 { + output[entry.parent as usize] -= + plan.row_coefficient(entry.unit.unit()) * value; + } + } + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{JumpInput, LindbladSpec, PcStepConfig, word_from_codes}; + use num::Complex; + + #[test] + fn unit_products_match_general_generator_with_unequal_couplings_and_noise() { + let h = vec![ + ("XXII".into(), 0.3), + ("IYYI".into(), -0.71), + ("ZIIX".into(), 0.17), + ]; + let basis: Vec<_> = (0..256usize) + .filter(|code| code % 3 != 0) + .map(|code| { + word_from_codes::<2>( + &(0..4) + .map(|q| ((code >> (2 * q)) & 3) as u8) + .collect::>(), + ) + .unwrap() + }) + .collect(); + let input: Vec<_> = (0..basis.len()) + .map(|i| if i % 7 == 0 { 0.0 } else { (i as f64).sin() }) + .collect(); + for rate in [0.0, 0.23] { + let jumps = vec![JumpInput { + lincomb: vec![("IZII".into(), Complex::new(1.0, 0.0))], + rate, + }]; + let spec = LindbladSpec::<2>::new(4, &h, &jumps).unwrap(); + let plan = spec.pauli_plan.as_ref().unwrap(); + let (cache, _) = UnitCache::build(plan, &basis, None); + let op = UnitOp { + cache: &cache, + plan, + }; + let mut expected = vec![0.0; basis.len()]; + for (row, column, value) in spec.generator(&basis) { + if input[column] != 0.0 { + expected[row] += value * input[column]; + } + } + for threads in [1, 2, 6] { + let pool = rayon::ThreadPoolBuilder::new() + .num_threads(threads) + .build() + .unwrap(); + // Paired storage sums each row in a different order than the general + // generator, so products agree to rounding rather than bit for bit. + let close = |actual: &[f64], factor: f64| { + for (a, e) in actual.iter().zip(&expected) { + assert!( + (a - factor * e).abs() <= 1e-14 * (1.0 + e.abs()), + "{a} vs {e}" + ); + } + }; + let mut actual = vec![0.0; basis.len()]; + pool.install(|| op.dot(true, &input, &mut actual)).unwrap(); + close(&actual, 1.0); + pool.install(|| op.dot(false, &input, &mut actual)).unwrap(); + close(&actual, 2.0); + } + } + } + + #[test] + fn streaming_bounds_match_per_row_bounds() { + let rows: Vec<(f64, f64)> = (0..997) + .map(|i| { + let d = -((i * 37 % 101) as f64) * 0.013; + (d.abs() + ((i * 53 % 89) as f64) * 0.07, d) + }) + .collect(); + let mu = rows.iter().map(|(_, d)| *d).sum::() / rows.len() as f64; + let norm = rows + .iter() + .map(|&(raw, d)| raw - d.abs() + (d - mu).abs()) + .fold(0.0_f64, f64::max); + let expected = (mu, norm); + let merged = rows + .chunks(64) + .map(|chunk| { + let mut b = Bounds::default(); + for &(raw, d) in chunk { + b.add(raw, d); + } + b + }) + .fold(Bounds::default(), Bounds::merge) + .finish(rows.len(), true); + assert!((merged.0 - expected.0).abs() <= 1e-15); + assert!((merged.1 - expected.1).abs() <= 1e-13 * expected.1); + } + + #[test] + fn wide_term_codes_give_identical_products() { + let h = vec![ + ("XXII".into(), 0.3), + ("IYYI".into(), -0.71), + ("ZIIX".into(), 0.17), + ]; + let basis: Vec<_> = (0..256usize) + .filter(|code| code % 3 != 0) + .map(|code| { + word_from_codes::<2>( + &(0..4) + .map(|q| ((code >> (2 * q)) & 3) as u8) + .collect::>(), + ) + .unwrap() + }) + .collect(); + let input: Vec<_> = (0..basis.len()).map(|i| (i as f64).sin()).collect(); + let jumps = vec![JumpInput { + lincomb: vec![("IZII".into(), Complex::new(1.0, 0.0))], + rate: 0.23, + }]; + let spec = LindbladSpec::<2>::new(4, &h, &jumps).unwrap(); + let plan = spec.pauli_plan.as_ref().unwrap(); + let (narrow, bounds) = UnitCache::build(plan, &basis, None); + assert!(matches!(narrow.blocks, Blocks::Narrow(_))); + let index = CompactBasisIndex::new(&basis); + let (blocks, wide_bounds) = + build_blocks::<2, i32>(plan, &basis, &index, narrow.shift, Vec::new()); + assert_eq!(bounds, wide_bounds); + let wide = UnitCache { + blocks: Blocks::Wide(blocks), + shift: narrow.shift, + dimension: narrow.dimension, + }; + let mut a = vec![0.0; basis.len()]; + let mut b = vec![0.0; basis.len()]; + UnitOp { + cache: &narrow, + plan, + } + .dot(true, &input, &mut a) + .unwrap(); + UnitOp { cache: &wide, plan } + .dot(true, &input, &mut b) + .unwrap(); + assert_eq!(a, b); + } + + #[test] + fn paired_products_cover_many_blocks_and_are_thread_count_invariant() { + // Five qubits with a three-body term and unequal couplings; the basis spans + // more than four blocks, so pairs of both owner parities and within-block + // pairs are exercised. + let h = vec![ + ("XXIII".into(), 0.31), + ("IYYII".into(), -0.52), + ("IIZXI".into(), 0.27), + ("XIYIZ".into(), 0.11), + ("IIIYY".into(), 0.9), + ]; + let basis: Vec<_> = (0..1024usize) + .filter(|code| code % 5 != 1) + .map(|code| { + word_from_codes::<2>( + &(0..5) + .map(|q| ((code >> (2 * q)) & 3) as u8) + .collect::>(), + ) + .unwrap() + }) + .collect(); + let input: Vec<_> = (0..basis.len()) + .map(|i| { + if i % 11 == 0 { + 0.0 + } else { + (0.7 * i as f64).cos() + } + }) + .collect(); + for rate in [0.0, 0.4] { + let jumps = vec![JumpInput { + lincomb: vec![("IIZII".into(), Complex::new(1.0, 0.0))], + rate, + }]; + let spec = LindbladSpec::<2>::new(5, &h, &jumps).unwrap(); + let plan = spec.pauli_plan.as_ref().unwrap(); + let (cache, _) = UnitCache::build(plan, &basis, None); + assert!(cache.block_count() > 4); + let op = UnitOp { + cache: &cache, + plan, + }; + let mut expected = vec![0.0; basis.len()]; + for (row, column, value) in spec.generator(&basis) { + expected[row] += value * input[column]; + } + let mut first: Option> = None; + for threads in [1, 3, 6] { + let pool = rayon::ThreadPoolBuilder::new() + .num_threads(threads) + .build() + .unwrap(); + let mut actual = vec![0.0; basis.len()]; + pool.install(|| op.dot(true, &input, &mut actual)).unwrap(); + for (a, e) in actual.iter().zip(&expected) { + assert!((a - e).abs() <= 1e-13 * (1.0 + e.abs()), "{a} vs {e}"); + } + match &first { + Some(reference) => assert_eq!(&actual, reference), + None => first = Some(actual), + } + } + } + } + + #[test] + fn adding_a_general_dissipator_replaces_a_retained_unit_cache() { + let h = vec![("XXI".into(), 0.3), ("IYY".into(), -0.17)]; + let mut reference = LindbladSpec::<2>::new(3, &h, &[]).unwrap(); + let mut optimized = LindbladSpec::<2>::new(3, &h, &[]).unwrap(); + let seed = word_from_codes::<2>(&[2, 0, 0]).unwrap(); + let (mut a, mut b) = (vec![seed], vec![seed]); + let (mut ca, mut cb) = (vec![1.0], vec![1.0]); + let cfg = PcStepConfig { + max_basis: 8, + admit_basis: Some(24), + num_threads: Some(2), + ..Default::default() + }; + for step in 0..8 { + if step == 3 { + let operators = vec![vec![ + ("XII".into(), Complex::new(0.5, 0.0)), + ("YII".into(), Complex::new(0.0, 0.5)), + ]]; + let k = vec![vec![Complex::new(0.2, 0.0)]]; + reference.add_kossakowski(&operators, &k).unwrap(); + optimized.add_kossakowski(&operators, &k).unwrap(); + } + reference + .pc_step_reference(&mut a, &mut ca, 0.1, &[seed], &cfg) + .unwrap(); + optimized + .pc_step(&mut b, &mut cb, 0.1, &[seed], &cfg) + .unwrap(); + assert_eq!(a, b); + assert_eq!(ca, cb); + } + } +} diff --git a/crates/ppvm-lindblad/src/word.rs b/crates/ppvm-lindblad/src/word.rs index d79e9fe57..7c06fd716 100644 --- a/crates/ppvm-lindblad/src/word.rs +++ b/crates/ppvm-lindblad/src/word.rs @@ -4,9 +4,11 @@ //! Packed Pauli-word type and the string / `u8`-label codecs. use crate::Error; +use bitvec::array::BitArray; use fxhash::FxBuildHasher; use ppvm_pauli_word::word::PauliWord; use ppvm_traits::PauliWordTrait; +use std::hash::{Hash, Hasher}; /// Pauli-word storage chunk: `u64` on 64-bit targets, `u32` elsewhere /// (`bitvec` implements `BitStore` for `u64` only on 64-bit targets, so @@ -51,14 +53,82 @@ pub const fn chunks_for(n_qubits: usize) -> Option { None } -/// The Pauli-word storage type used throughout this crate, `C` chunks wide. +/// The Pauli-word storage type used throughout this crate, `C` chunks wide: +/// one X and one Z bit plane, 32 bytes at the default 128-qubit width. /// /// The crate is const-generic in the chunk count so a register of any size -/// up to [`MAX_SUPPORTED_QUBITS`] gets a fixed-size word; the default -/// `C = W_CHUNKS` covers 128 qubits, byte-for-byte the historical layout. -/// The `FxBuildHasher` matches the hash used by the `FxHashMap` keys we -/// wrap with; `REHASH=true` means `set()` keeps the cached hash in sync. -pub type Word = PauliWord<[Chunk; C], FxBuildHasher, true>; +/// up to [`MAX_SUPPORTED_QUBITS`] gets a fixed-size word. Unlike +/// [`GeneralWord`], a `Word` stores neither the qubit count, which belongs to +/// the model, nor a cached hash; bits at or above the register size are +/// always zero. Hashing and ordering agree with [`GeneralWord`] on the same +/// planes, so hash tables and sorts treat both types alike. +#[derive(Clone, Copy, Default, PartialOrd, Ord)] +pub struct Word { + /// X-bit plane, one bit per qubit. + pub xbits: BitArray<[Chunk; C]>, + /// Z-bit plane, one bit per qubit. + pub zbits: BitArray<[Chunk; C]>, +} + +/// The `ppvm_pauli_word` word with the same planes, which also stores the +/// register size and a cached hash. `ppvm_pauli_sum` symmetry routines take +/// this type. +pub type GeneralWord = PauliWord<[Chunk; C], FxBuildHasher, true>; + +impl Word { + /// The identity word for a register of `n_qubits` (at most the width's capacity). + pub fn new(n_qubits: usize) -> Self { + debug_assert!(n_qubits <= max_qubits::()); + Self::default() + } + + /// This word as a [`GeneralWord`] on `n_qubits` qubits. The qubit count + /// is an argument because a `Word` does not store it. + pub fn to_general(self, n_qubits: usize) -> GeneralWord { + let mut word = GeneralWord::::new(n_qubits); + word.xbits = self.xbits; + word.zbits = self.zbits; + word.rehash(); + word + } +} + +impl From<&GeneralWord> for Word { + fn from(word: &GeneralWord) -> Self { + Self { + xbits: word.xbits, + zbits: word.zbits, + } + } +} + +/// Compares the raw chunks, as [`GeneralWord`] does, rather than bit by bit. +impl PartialEq for Word { + #[inline(always)] + fn eq(&self, other: &Self) -> bool { + self.xbits.data == other.xbits.data && self.zbits.data == other.zbits.data + } +} + +impl Eq for Word {} + +/// Writes the hash [`GeneralWord`] caches for the same planes. +impl Hash for Word { + #[inline(always)] + fn hash(&self, state: &mut H) { + state.write_u64(GeneralWord::::plane_hash(&self.xbits, &self.zbits)); + } +} + +impl std::fmt::Debug for Word { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "Word(x={:x?}, z={:x?})", + self.xbits.data, self.zbits.data + ) + } +} /// `Err(TooManyQubits)` unless a `C`-chunk word holds `n_qubits`. pub(crate) fn check_width(n_qubits: usize) -> Result<(), Error> { @@ -89,13 +159,12 @@ pub fn word_from_codes(codes: &[u8]) -> Result, Error> { w.zbits.set(q, true); } } - w.rehash(); Ok(w) } /// Inverse of [`word_from_codes`]: write `n_qubits` Pauli labels into `out`. pub fn codes_from_word(w: &Word, out: &mut [u8]) { - debug_assert_eq!(out.len(), w.n_qubits()); + debug_assert!(out.len() <= max_qubits::()); for (q, slot) in out.iter_mut().enumerate() { let xb = w.xbits[q] as u8; let zb = w.zbits[q] as u8; @@ -138,25 +207,25 @@ pub fn parse_pauli_string( other => return Err(Error::InvalidPauliChar { c: other }), } } - w.rehash(); Ok((w, support)) } /// Compute the support (non-identity qubits) of `w`. pub(crate) fn word_support(w: &Word, out: &mut Vec) { out.clear(); - for q in 0..w.n_qubits() { - if w.xbits[q] || w.zbits[q] { - out.push(q as u32); + for chunk in 0..C { + let mut bits = w.xbits.data[chunk] | w.zbits.data[chunk]; + while bits != 0 { + out.push((chunk * CHUNK_BITS) as u32 + bits.trailing_zeros()); + bits &= bits - 1; } } } /// Compact 64-bit hash of a [`Word`], used as the key in cache-friendly /// membership tables: an `FxHashMap` over the basis has a working -/// set ~6× smaller than `FxHashMap`. The hash mixes the word's -/// cached hash once through `FxHasher` and never touches the 32-byte -/// payload. +/// set ~4× smaller than `FxHashMap`. The word's plane hash is +/// mixed once more through `FxHasher`. #[inline(always)] pub(crate) fn word_hash(w: &Word) -> u64 { use std::hash::{Hash, Hasher}; diff --git a/crates/ppvm-lindblad/tests/candidate_proposers.rs b/crates/ppvm-lindblad/tests/candidate_proposers.rs new file mode 100644 index 000000000..5684ac8fb --- /dev/null +++ b/crates/ppvm-lindblad/tests/candidate_proposers.rs @@ -0,0 +1,141 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Caller-supplied candidate proposers through the public API. + +use ppvm_lindblad::{ + CandidateBuffer, CandidateProposer, Error, LindbladSpec, PcStepConfig, StreamingProposer, Word, + word_from_codes, +}; + +/// Wraps the default proposer and records how the step drives it. +#[derive(Default)] +struct Recording { + inner: StreamingProposer, + proposals: usize, + selections: Vec, +} + +impl CandidateProposer for Recording { + fn propose( + &mut self, + model: &LindbladSpec, + buffer: &mut CandidateBuffer<'_>, + protected: &[Word], + maximum: usize, + ) -> Result<(), Error> { + self.proposals += 1; + assert_eq!(buffer.basis().len(), buffer.coefficients().len()); + assert!(buffer.candidates().is_empty()); + self.inner.propose(model, buffer, protected, maximum) + } + + fn select(&mut self, buffer: &mut CandidateBuffer<'_>, threshold: f64) -> usize { + let count = self.inner.select(buffer, threshold); + self.selections.push(count); + count + } +} + +/// Proposes the single-qubit X strings missing from the basis and admits +/// them in reverse order, using only the public buffer methods. +struct SingleQubitX { + n: usize, +} + +impl CandidateProposer for SingleQubitX { + fn propose( + &mut self, + _model: &LindbladSpec, + buffer: &mut CandidateBuffer<'_>, + protected: &[Word], + maximum: usize, + ) -> Result<(), Error> { + let room = maximum.saturating_sub(buffer.basis().len()); + for q in 0..self.n { + let mut codes = vec![0; self.n]; + codes[q] = 1; + let word = word_from_codes(&codes).unwrap(); + if buffer.candidates().len() < room + && !buffer.basis().contains(&word) + && !protected.contains(&word) + { + buffer.push(word); + } + } + Ok(()) + } + + fn select(&mut self, buffer: &mut CandidateBuffer<'_>, _threshold: f64) -> usize { + buffer.candidates_mut().reverse(); + buffer.candidates().len() + } +} + +fn model() -> LindbladSpec { + LindbladSpec::new( + 4, + &[ + ("XXII".into(), 0.3), + ("IYYI".into(), -0.7), + ("IIXX".into(), 0.2), + ], + &[], + ) + .unwrap() +} + +#[test] +fn wrapped_default_proposer_matches_pc_step() { + let model = model(); + let seed = word_from_codes(&[2, 0, 0, 0]).unwrap(); + let (mut a, mut b) = (vec![seed], vec![seed]); + let (mut ca, mut cb) = (vec![1.0], vec![1.0]); + let mut proposer = Recording::default(); + let cfg = PcStepConfig { + max_basis: 8, + admit_basis: Some(24), + num_threads: Some(2), + ..Default::default() + }; + for _ in 0..6 { + model.pc_step(&mut a, &mut ca, 0.1, &[seed], &cfg).unwrap(); + model + .pc_step_with_proposer(&mut b, &mut cb, 0.1, &[seed], &cfg, &mut proposer) + .unwrap(); + assert_eq!(a, b); + assert_eq!(ca, cb); + } + assert_eq!(proposer.proposals, proposer.selections.len()); + assert!(proposer.proposals >= 6); +} + +#[test] +fn custom_proposer_admits_its_selection_with_zero_coefficients() { + let model = model(); + let seed = word_from_codes(&[2, 0, 0, 0]).unwrap(); + let mut basis = vec![seed]; + let mut coeffs = vec![1.0]; + let cfg = PcStepConfig { + max_basis: 3, + admit_basis: Some(3), + ..Default::default() + }; + model + .pc_step_with_proposer( + &mut basis, + &mut coeffs, + 0.0, + &[seed], + &cfg, + &mut SingleQubitX { n: 4 }, + ) + .unwrap(); + let x = |q: usize| { + let mut codes = vec![0; 4]; + codes[q] = 1; + word_from_codes(&codes).unwrap() + }; + assert_eq!(basis, vec![seed, x(1), x(0)]); + assert_eq!(coeffs, vec![1.0, 0.0, 0.0]); +} diff --git a/crates/ppvm-lindblad/tests/word_width.rs b/crates/ppvm-lindblad/tests/word_width.rs index 7d3b5ea46..80c27ce7e 100644 --- a/crates/ppvm-lindblad/tests/word_width.rs +++ b/crates/ppvm-lindblad/tests/word_width.rs @@ -133,7 +133,7 @@ fn evolve_orbit(n: usize, k: i32, steps: usize) -> Vec<(Vec, let group = TranslationGroup::chain_1d(n); let k_modes = [k]; - let mut basis: Vec> = (0..n) + let basis: Vec> = (0..n) .map(|q| { let mut codes = vec![0u8; n]; codes[q] = 1; // X @@ -148,7 +148,9 @@ fn evolve_orbit(n: usize, k: i32, steps: usize) -> Vec<(Vec, ) }) .collect(); - canonicalize_pauli_sum_complex(&mut basis, &mut coeffs, &group, &k_modes); + let mut words: Vec<_> = basis.iter().map(|w| w.to_general(n)).collect(); + canonicalize_pauli_sum_complex(&mut words, &mut coeffs, &group, &k_modes); + let mut basis: Vec> = words.iter().map(Word::from).collect(); let sector = Sector::new(&group, &k_modes); let cfg = PcStepConfig { diff --git a/crates/ppvm-pauli-word/src/word/data.rs b/crates/ppvm-pauli-word/src/word/data.rs index 93946dcce..75d1c8cae 100644 --- a/crates/ppvm-pauli-word/src/word/data.rs +++ b/crates/ppvm-pauli-word/src/word/data.rs @@ -185,13 +185,7 @@ impl(), - ); + self.hash_cache = Self::plane_hash(&self.xbits, &self.zbits); } } @@ -253,6 +247,24 @@ impl + PauliWord +{ + /// The hash a word with bit planes `xbits` and `zbits` caches. It does not + /// depend on the qubit count, so a type that stores only the two planes + /// can hash exactly like this word. + #[inline(always)] + pub fn plane_hash(xbits: &BitArray, zbits: &BitArray) -> u64 { + S::word_hash( + &[ + bytemuck::bytes_of(&xbits.data), + bytemuck::bytes_of(&zbits.data), + ], + std::mem::size_of::(), + ) + } +} + impl Ord for PauliWord { fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.nqubits diff --git a/crates/ppvm-python-native/src/lindblad.rs b/crates/ppvm-python-native/src/lindblad.rs index dc209cd37..81f05952d 100644 --- a/crates/ppvm-python-native/src/lindblad.rs +++ b/crates/ppvm-python-native/src/lindblad.rs @@ -335,9 +335,11 @@ impl LindbladSpec { ) .map_err(map_err)?; - // Pack output. Basis may have grown; coeffs has the same new length. - let pairs: Vec<(Word, f64)> = basis_words.into_iter().zip(coeffs_vec).collect(); - pack_pauli_map(py, pairs, n_q) + // `pc_step` leaves spare capacity for the next step's enlargement; + // release it before NumPy takes ownership of the coefficients. + let basis_arr = encode_basis(py, &basis_words, n_q)?; + coeffs_vec.shrink_to_fit(); + Ok((basis_arr, coeffs_vec.into_pyarray(py))) }) } @@ -393,8 +395,9 @@ impl LindbladSpec { ) .map_err(map_err)?; - let pairs: Vec<(Word, f64)> = basis_words.into_iter().zip(coeffs_vec).collect(); - let map = pack_pauli_map(py, pairs, n_q)?; + let basis_arr = encode_basis(py, &basis_words, n_q)?; + coeffs_vec.shrink_to_fit(); + let map = (basis_arr, coeffs_vec.into_pyarray(py)); let d = pyo3::types::PyDict::new(py); d.set_item("leakage1_us", timings.leakage1_us)?; d.set_item("expand1_us", timings.expand1_us)?; diff --git a/crates/ppvm-python-native/src/symmetry.rs b/crates/ppvm-python-native/src/symmetry.rs index 4d8129a8a..5eacce39b 100644 --- a/crates/ppvm-python-native/src/symmetry.rs +++ b/crates/ppvm-python-native/src/symmetry.rs @@ -12,7 +12,7 @@ use num::Complex; use numpy::{Complex64, IntoPyArray, PyArray1, PyArray2, PyReadonlyArray1, PyReadonlyArray2}; -use ppvm_lindblad::{codes_from_word, word_from_codes}; +use ppvm_lindblad::{Word, codes_from_word, word_from_codes}; use ppvm_pauli_sum::symmetry as core_sym; use pyo3::{exceptions::PyValueError, prelude::*}; @@ -161,8 +161,8 @@ impl TranslationGroup { let mut out = vec![0u8; codes.len()]; with_width!(codes.len(), C => { let w = word_from_codes::(codes).map_err(|e| PyValueError::new_err(e.to_string()))?; - let canon = self.inner.canonicalize(&w); - codes_from_word(&canon, &mut out); + let canon = self.inner.canonicalize(&w.to_general(codes.len())); + codes_from_word(&Word::from(&canon), &mut out); PyResult::Ok(()) })?; Ok(out.into_pyarray(py)) @@ -205,12 +205,14 @@ pub fn canonicalize_basis_arr_complex<'py>( .map(|c| Complex::new(c.re, c.im)) .collect(); + let mut general: Vec<_> = basis_words.iter().map(|w| w.to_general(n_q)).collect(); core_sym::canonicalize_pauli_sum_complex( - &mut basis_words, + &mut general, &mut coeffs_vec, &group.inner, k_slice, ); + basis_words = general.iter().map(Word::from).collect(); let out_coeffs: Vec = coeffs_vec .iter() @@ -249,7 +251,8 @@ pub fn check_momentum_sector_arr<'py>( .iter() .map(|c| Complex::new(c.re, c.im)) .collect(); - core_sym::check_momentum_sector(&basis_words, &coeffs_vec, &group.inner, k_slice, tol) + let general: Vec<_> = basis_words.iter().map(|w| w.to_general(n_q)).collect(); + core_sym::check_momentum_sector(&general, &coeffs_vec, &group.inner, k_slice, tol) .map_err(|e| PyValueError::new_err(format!("{e}"))) }) } @@ -283,7 +286,9 @@ pub fn canonicalize_basis_arr<'py>( let mut basis_words = decode_basis::(&basis_view, n_q)?; let mut coeffs_vec = coeffs_slice.to_vec(); - core_sym::canonicalize_pauli_sum(&mut basis_words, &mut coeffs_vec, &group.inner); + let mut general: Vec<_> = basis_words.iter().map(|w| w.to_general(n_q)).collect(); + core_sym::canonicalize_pauli_sum(&mut general, &mut coeffs_vec, &group.inner); + basis_words = general.iter().map(Word::from).collect(); let basis_arr = encode_basis(py, &basis_words, n_q)?; Ok((basis_arr, coeffs_vec.into_pyarray(py)))