Copilot commented on code in PR #1275:
URL: https://github.com/apache/mahout/pull/1275#discussion_r3106393556


##########
qdp/qdp-core/src/gpu/metrics.rs:
##########
@@ -0,0 +1,216 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements.  See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License.  You may obtain a copy of the License at
+//
+//    http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! Fidelity and trace distance metrics for quantum state validation.
+//!
+//! These utilities compare quantum states encoded at different precisions
+//! or by different implementations.  All computations download GPU data
+//! to the host and run on the CPU to produce a single scalar per sample.
+//! They are intended for **testing and validation**, not the hot path.
+
+#[cfg(target_os = "linux")]
+use cudarc::driver::CudaDevice;

Review Comment:
   On non-Linux builds, `Arc` is only needed by the `download_complex_*` 
helpers (which are `#[cfg(target_os = "linux")]`). As written, `use 
std::sync::Arc;` becomes an unused import on other targets. Consider gating 
this import with the same `cfg` to avoid warnings in non-Linux builds.



##########
qdp/qdp-python/qumat_qdp/loader.py:
##########
@@ -238,13 +242,18 @@ def null_handling(self, policy: str) -> QuantumDataLoader:
         return self
 
     def backend(self, name: str) -> QuantumDataLoader:
-        """Set encoding backend: ``'rust'`` or ``'pytorch'``.
+        """Set encoding backend: ``'rust'``, ``'pytorch'``, or ``'auto'``.
 
-        The PyTorch reference backend is intended for testing and must be
-        explicitly selected.  Returns self for chaining.
+        ``'auto'`` (default-like): tries the Rust backend first and silently
+        falls back to the PyTorch reference backend if the Rust extension is
+        unavailable.  ``'rust'`` raises if the extension is missing.
+        ``'pytorch'`` always uses the pure-PyTorch path.

Review Comment:
   `backend()` docstring says the `'auto'` backend “silently” falls back, but 
`_create_iterator()` emits a `RuntimeWarning` on fallback. Please update the 
docstring wording to match the actual behavior (and/or clarify when/why the 
warning is raised).



##########
qdp/qdp-core/src/gpu/metrics.rs:
##########
@@ -0,0 +1,216 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements.  See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License.  You may obtain a copy of the License at
+//
+//    http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! Fidelity and trace distance metrics for quantum state validation.
+//!
+//! These utilities compare quantum states encoded at different precisions
+//! or by different implementations.  All computations download GPU data
+//! to the host and run on the CPU to produce a single scalar per sample.
+//! They are intended for **testing and validation**, not the hot path.
+
+#[cfg(target_os = "linux")]
+use cudarc::driver::CudaDevice;
+use std::sync::Arc;
+
+#[cfg(target_os = "linux")]
+use qdp_kernels::{CuComplex, CuDoubleComplex};
+
+use crate::error::{MahoutError, Result};
+
+/// Compute the state fidelity |⟨ψ|φ⟩|² between two complex state vectors
+/// given as interleaved (re, im) f64 slices of equal length.
+///
+/// Both slices must have length `2 * state_dim` (re0, im0, re1, im1, ...).
+/// Returns a value in [0, 1].  Fidelity == 1 means identical states (up to
+/// global phase).
+pub fn fidelity_f64(state_a: &[f64], state_b: &[f64]) -> Result<f64> {
+    if state_a.len() != state_b.len() {
+        return Err(MahoutError::InvalidInput(format!(
+            "fidelity: length mismatch ({} vs {})",
+            state_a.len(),
+            state_b.len()
+        )));
+    }
+    if !state_a.len().is_multiple_of(2) {
+        return Err(MahoutError::InvalidInput(
+            "fidelity: length must be even (interleaved re/im 
pairs)".to_string(),
+        ));
+    }
+
+    // ⟨ψ|φ⟩ = Σ_i conj(a_i) * b_i
+    let mut re_acc = 0.0_f64;
+    let mut im_acc = 0.0_f64;
+    for i in (0..state_a.len()).step_by(2) {
+        let a_re = state_a[i];
+        let a_im = state_a[i + 1];
+        let b_re = state_b[i];
+        let b_im = state_b[i + 1];
+        // conj(a) * b = (a_re - i*a_im)(b_re + i*b_im)
+        //             = (a_re*b_re + a_im*b_im) + i*(a_re*b_im - a_im*b_re)
+        re_acc += a_re * b_re + a_im * b_im;
+        im_acc += a_re * b_im - a_im * b_re;
+    }
+
+    Ok(re_acc * re_acc + im_acc * im_acc)
+}

Review Comment:
   The `fidelity_*` docs say the return value is in `[0, 1]`, but the 
implementation returns the raw `|⟨ψ|φ⟩|²` accumulation without 
clamping/normalization. Even for normalized states, floating-point error can 
yield slightly >1 (and for non-normalized inputs it can be arbitrarily large). 
Either clamp the result to `[0,1]` (like `trace_distance_*` already does) 
and/or update the docs to state the normalization requirement and possible 
epsilon overshoot.



##########
qdp/qdp-core/src/pipeline_runner.rs:
##########
@@ -355,12 +412,30 @@ fn read_file_by_extension(
 
 /// Stateful iterator that yields one batch DLPack at a time for Python `for` 
loop consumption.
 /// Reads prefetched batches via a bounded channel.
+///
+/// # Thread safety
+/// `Receiver` is `!Sync`, so `rx` is wrapped in a `Mutex` to satisfy PyO3's 
`#[pyclass]`
+/// `Sync` bound.  In practice, `PyRefMut` guarantees exclusive access, so the 
lock is
+/// never contended at runtime.  `Sender` is already `Send + Sync` and needs 
no wrapper.
 pub struct PipelineIterator {
     engine: QdpEngine,
     config: PipelineConfig,
     rx: std::sync::Mutex<std::sync::mpsc::Receiver<Result<PrefetchedBatch>>>,
-    recycle_tx: std::sync::Mutex<std::sync::mpsc::Sender<BatchData>>,
-    _producer_handle: std::sync::Mutex<std::thread::JoinHandle<()>>,
+    recycle_tx: Option<std::sync::mpsc::Sender<BatchData>>,
+    producer_handle: Option<std::thread::JoinHandle<()>>,
+}
+
+impl Drop for PipelineIterator {
+    fn drop(&mut self) {
+        // Drop the recycle sender first to unblock the producer if it's 
waiting on try_recv.
+        // Doing it explicitly before joining makes the shutdown order 
deterministic.
+        drop(self.recycle_tx.take());
+        // Drain any remaining items so the producer's send() unblocks.
+        while self.rx.lock().unwrap().try_recv().is_ok() {}

Review Comment:
   `PipelineIterator::drop` can deadlock: draining `rx` until it’s temporarily 
empty doesn’t prevent the producer thread from refilling the bounded 
`sync_channel` and blocking again on `tx.send(..)` while `drop()` is waiting on 
`join()`. To make teardown deterministic, close the receiver before joining 
(e.g., store `rx` as `Mutex<Option<Receiver<_>>>` and `take()` it in `drop`), 
so `tx.send` fails and the producer exits.



##########
qdp/qdp-core/src/pipeline_runner.rs:
##########
@@ -99,10 +115,51 @@ pub trait BatchProducer: Send + 'static {
     fn produce(&mut self, recycled: Option<BatchData>) -> 
Result<Option<PrefetchedBatch>>;
 }
 
+/// Compute optimal prefetch depth to keep the CPU-side prefetch buffer under 
~256 MB,
+/// clamped to [1, 32].
+///
+/// The CPU prefetch buffer holds `prefetch_depth` batches of raw input data 
(not
+/// encoded state vectors, which live on the GPU).  For amplitude encoding the 
input
+/// size dominates; for angle/basis it is tiny, so the cap kicks in at the 
upper bound.
+///
+/// | num_qubits | encoding   | bytes/batch (f64, bs=64) | auto depth |
+/// |------------|------------ |--------------------------|------------|
+/// |  8         | amplitude  |  ~128 KB                 | 32         |
+/// | 12         | amplitude  |  ~2 MB                   | 32         |
+/// | 16         | amplitude  |  ~32 MB                  | 8          |
+/// | 20         | amplitude  |  ~512 MB                 | 1          |
+/// |  *         | angle/basis|  tiny                    | 32         |
+fn compute_optimal_prefetch_depth(
+    num_qubits: usize,
+    batch_size: usize,
+    encoding_method: &str,
+    float32: bool,
+) -> usize {
+    const TARGET_BYTES: usize = 256 * 1024 * 1024; // 256 MB
+    const MIN_DEPTH: usize = 1;
+    const MAX_DEPTH: usize = 32;
+
+    let sample_len = match encoding_method.to_lowercase().as_str() {
+        "angle" => num_qubits,
+        "basis" => 1,
+        _ => 1usize << num_qubits, // amplitude / iqp
+    };
+    let bytes_per_element = if float32 { 4usize } else { 8usize };
+    let bytes_per_batch = batch_size * sample_len * bytes_per_element;
+
+    if bytes_per_batch == 0 {
+        return MAX_DEPTH;
+    }
+    (TARGET_BYTES / bytes_per_batch).clamp(MIN_DEPTH, MAX_DEPTH)

Review Comment:
   `compute_optimal_prefetch_depth()` does unchecked shift/multiplication 
(`1usize << num_qubits`, `batch_size * sample_len * bytes_per_element`). For 
large `num_qubits`/`batch_size` this can overflow or panic, and an overflow to 
0 will incorrectly return `MAX_DEPTH` (32), defeating the safety goal and 
potentially reintroducing huge buffering. Use checked arithmetic (e.g., 
`checked_shl`, `checked_mul`) and treat overflow as “very large batch” so the 
function returns `MIN_DEPTH` (1).



##########
qdp/qdp-core/tests/gpu_fidelity.rs:
##########
@@ -0,0 +1,329 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements.  See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License.  You may obtain a copy of the License at
+//
+//    http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! Tests for fidelity / trace-distance metrics and F32 vs F64 precision
+//! comparison across different qubit counts.
+
+#![cfg(target_os = "linux")]
+
+use approx::assert_relative_eq;
+use qdp_core::gpu::metrics::{
+    fidelity_cross_precision, fidelity_f32, fidelity_f64, trace_distance_f64,
+};
+
+mod common;
+
+// ═══════════════════════════════════════════════════════════════════════
+// Unit tests for the fidelity / trace-distance functions themselves
+// ═══════════════════════════════════════════════════════════════════════
+
+#[test]
+fn test_fidelity_identical_states() {
+    // |0⟩ = (1+0i, 0+0i)  interleaved: [1, 0, 0, 0]
+    let state = vec![1.0, 0.0, 0.0, 0.0];
+    let f = fidelity_f64(&state, &state).unwrap();
+    assert_relative_eq!(f, 1.0, epsilon = 1e-12);
+}
+
+#[test]
+fn test_fidelity_orthogonal_states() {
+    // |0⟩ and |1⟩
+    let state_0 = vec![1.0, 0.0, 0.0, 0.0];
+    let state_1 = vec![0.0, 0.0, 1.0, 0.0];
+    let f = fidelity_f64(&state_0, &state_1).unwrap();
+    assert_relative_eq!(f, 0.0, epsilon = 1e-12);
+}
+
+#[test]
+fn test_fidelity_superposition() {
+    // |+⟩ = 1/√2 (|0⟩ + |1⟩)
+    let inv_sqrt2 = 1.0_f64 / 2.0_f64.sqrt();
+    let plus = vec![inv_sqrt2, 0.0, inv_sqrt2, 0.0];
+    let f = fidelity_f64(&plus, &plus).unwrap();
+    assert_relative_eq!(f, 1.0, epsilon = 1e-12);
+
+    // ⟨+|0⟩ = 1/√2, fidelity = 0.5
+    let zero = vec![1.0, 0.0, 0.0, 0.0];
+    let f2 = fidelity_f64(&plus, &zero).unwrap();
+    assert_relative_eq!(f2, 0.5, epsilon = 1e-12);
+}
+
+#[test]
+fn test_fidelity_global_phase() {
+    // |ψ⟩ = (0+i) * |0⟩ = [0, 1, 0, 0]  (global phase e^{iπ/2})
+    let state_a = vec![1.0, 0.0, 0.0, 0.0];
+    let state_b = vec![0.0, 1.0, 0.0, 0.0];
+    let f = fidelity_f64(&state_a, &state_b).unwrap();
+    // |⟨ψ|φ⟩|² = |⟨0| (i|0⟩)|² = |i|² = 1
+    assert_relative_eq!(f, 1.0, epsilon = 1e-12);
+}
+
+#[test]
+fn test_trace_distance_identical() {
+    let state = vec![1.0, 0.0, 0.0, 0.0];
+    let td = trace_distance_f64(&state, &state).unwrap();
+    assert_relative_eq!(td, 0.0, epsilon = 1e-12);
+}
+
+#[test]
+fn test_trace_distance_orthogonal() {
+    let state_0 = vec![1.0, 0.0, 0.0, 0.0];
+    let state_1 = vec![0.0, 0.0, 1.0, 0.0];
+    let td = trace_distance_f64(&state_0, &state_1).unwrap();
+    assert_relative_eq!(td, 1.0, epsilon = 1e-12);
+}
+
+#[test]
+fn test_fidelity_f32_basic() {
+    let state: Vec<f32> = vec![1.0, 0.0, 0.0, 0.0];
+    let f = fidelity_f32(&state, &state).unwrap();
+    assert_relative_eq!(f, 1.0, epsilon = 1e-6);
+}
+
+#[test]
+fn test_fidelity_cross_precision_basic() {
+    let state_f32: Vec<f32> = vec![1.0, 0.0, 0.0, 0.0];
+    let state_f64: Vec<f64> = vec![1.0, 0.0, 0.0, 0.0];
+    let f = fidelity_cross_precision(&state_f32, &state_f64).unwrap();
+    assert_relative_eq!(f, 1.0, epsilon = 1e-6);
+}
+
+#[test]
+fn test_fidelity_length_mismatch_errors() {
+    let a = vec![1.0, 0.0];
+    let b = vec![1.0, 0.0, 0.0, 0.0];
+    assert!(fidelity_f64(&a, &b).is_err());
+}
+
+#[test]
+fn test_fidelity_odd_length_errors() {
+    let a = vec![1.0, 0.0, 0.5];
+    assert!(fidelity_f64(&a, &a).is_err());
+}
+
+// ═══════════════════════════════════════════════════════════════════════
+// GPU-backed F32 vs F64 precision comparison tests
+// ═══════════════════════════════════════════════════════════════════════
+
+use qdp_core::Precision;
+use qdp_core::gpu::metrics::{download_complex_f32, download_complex_f64};
+
+/// Encode the same data at F32 and F64, download both, compute 
cross-precision fidelity.
+fn compare_f32_f64_amplitude(num_qubits: usize) -> Option<f64> {
+    let engine_f64 = common::qdp_engine_with_precision(Precision::Float64)?;
+    let engine_f32 = common::qdp_engine_with_precision(Precision::Float32)?;
+    let device = common::cuda_device()?;
+
+    let state_dim = 1usize << num_qubits;
+    let num_samples = 4;
+    let sample_size = state_dim;
+
+    // Build deterministic test data
+    let data_f64: Vec<f64> = (0..num_samples * sample_size)
+        .map(|i| ((i as f64) + 1.0) / (num_samples * sample_size) as f64)
+        .collect();
+    let data_f32: Vec<f32> = data_f64.iter().map(|&x| x as f32).collect();
+
+    // Encode at F64
+    let dlpack_f64 = engine_f64
+        .encode_batch(&data_f64, num_samples, sample_size, num_qubits, 
"amplitude")
+        .expect("F64 encode_batch should succeed");
+
+    // Encode at F32
+    let dlpack_f32 = engine_f32
+        .encode_batch_f32(&data_f32, num_samples, sample_size, num_qubits, 
"amplitude")
+        .expect("F32 encode_batch should succeed");
+
+    // Read back from GPU
+    let f64_tensor = unsafe { &(*dlpack_f64).dl_tensor };
+    let f32_tensor = unsafe { &(*dlpack_f32).dl_tensor };
+
+    let total_elements = num_samples * state_dim;
+    let host_f64 =
+        download_complex_f64(&device, f64_tensor.data as *const _, 
total_elements).unwrap();
+    let host_f32 =
+        download_complex_f32(&device, f32_tensor.data as *const _, 
total_elements).unwrap();
+
+    // Compute per-sample fidelity, return minimum
+    let mut min_fidelity = 1.0_f64;
+    for s in 0..num_samples {
+        let offset_f64 = s * state_dim * 2;
+        let offset_f32 = s * state_dim * 2;
+        let sample_f64 = &host_f64[offset_f64..offset_f64 + state_dim * 2];
+        let sample_f32 = &host_f32[offset_f32..offset_f32 + state_dim * 2];
+        let f = fidelity_cross_precision(sample_f32, sample_f64).unwrap();
+        if f < min_fidelity {
+            min_fidelity = f;
+        }
+    }
+
+    // Clean up DLPack
+    unsafe {
+        common::take_deleter_and_delete(dlpack_f64);
+        common::take_deleter_and_delete(dlpack_f32);
+    }
+
+    Some(min_fidelity)
+}
+
+#[test]
+fn test_f32_vs_f64_amplitude_8_qubits() {
+    let Some(fidelity) = compare_f32_f64_amplitude(8) else {
+        println!("SKIP: No GPU available");
+        return;
+    };
+    println!("F32 vs F64 fidelity @ 8 qubits: {:.10}", fidelity);
+    assert!(
+        fidelity > 1.0 - 1e-3,
+        "Fidelity too low at 8 qubits: {fidelity}"
+    );
+}
+
+#[test]
+fn test_f32_vs_f64_amplitude_12_qubits() {
+    let Some(fidelity) = compare_f32_f64_amplitude(12) else {
+        println!("SKIP: No GPU available");
+        return;
+    };
+    println!("F32 vs F64 fidelity @ 12 qubits: {:.10}", fidelity);
+    assert!(
+        fidelity > 1.0 - 1e-3,
+        "Fidelity too low at 12 qubits: {fidelity}"
+    );
+}
+
+#[test]
+fn test_f32_vs_f64_amplitude_16_qubits() {
+    let Some(fidelity) = compare_f32_f64_amplitude(16) else {
+        println!("SKIP: No GPU available");
+        return;
+    };
+    println!("F32 vs F64 fidelity @ 16 qubits: {:.10}", fidelity);
+    assert!(
+        fidelity > 1.0 - 1e-3,
+        "Fidelity too low at 16 qubits: {fidelity}"
+    );
+}
+
+#[test]
+fn test_f32_vs_f64_amplitude_20_qubits() {
+    let Some(fidelity) = compare_f32_f64_amplitude(20) else {
+        println!("SKIP: No GPU available");
+        return;
+    };
+    println!("F32 vs F64 fidelity @ 20 qubits: {:.10}", fidelity);
+    // At 20 qubits (1M elements), F32 norm precision degrades.
+    // We use a relaxed threshold here to document the baseline.
+    assert!(
+        fidelity > 1.0 - 1e-2,
+        "Fidelity too low at 20 qubits: {fidelity}"
+    );
+}
+
+// ═════════════════════════════════════════════════════════════════════���═

Review Comment:
   This section divider comment contains garbled replacement characters ("�"), 
which suggests an encoding/copy-paste issue in the source. Please 
remove/replace them so the test file is clean UTF-8 text.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to