400Ping commented on code in PR #694:
URL: https://github.com/apache/mahout/pull/694#discussion_r2594843022


##########
qdp/qdp-python/tests/test_high_fidelity.py:
##########
@@ -0,0 +1,235 @@
+#
+# 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 include: full-stack verification, async pipeline, fidelity metrics,
+zero-copy validation, and edge cases (boundaries, stability, memory, threads).
+"""
+
+import pytest
+import torch
+import numpy as np
+import concurrent.futures
+from mahout_qdp import QdpEngine
+
+np.random.seed(2026)
+
+# ASYNC_THRESHOLD = 1MB / sizeof(f64) = 131072
+PIPELINE_CHUNK_SIZE = 131072
+
+
+def calculate_fidelity(
+    state_vector_gpu: torch.Tensor, ground_truth_cpu: np.ndarray
+) -> float:
+    """Calculate quantum state fidelity: F = |<ψ_gpu | ψ_cpu>|²"""
+    psi_gpu = state_vector_gpu.cpu().numpy()
+
+    if np.any(np.isnan(psi_gpu)) or np.any(np.isinf(psi_gpu)):
+        return 0.0
+
+    assert psi_gpu.shape == ground_truth_cpu.shape, (
+        f"Shape mismatch: {psi_gpu.shape} vs {ground_truth_cpu.shape}"
+    )
+
+    overlap = np.vdot(ground_truth_cpu, psi_gpu)
+    fidelity = np.abs(overlap) ** 2
+    return float(fidelity)
+
+
[email protected](scope="module")
+def engine():
+    """Initialize QDP engine (module-scoped singleton)."""
+    try:
+        return QdpEngine(0)
+    except RuntimeError as e:
+        pytest.skip(f"CUDA initialization failed: {e}")
+
+
+# 1. Core Logic and Boundary Tests
+
+
[email protected]
[email protected](
+    "num_qubits, data_size, desc",
+    [
+        (4, 16, "Small - Sync Path"),
+        (10, 1000, "Medium - Padding Logic"),
+        (18, PIPELINE_CHUNK_SIZE, "Boundary - Exact Chunk Size"),
+        (18, PIPELINE_CHUNK_SIZE + 1, "Boundary - Chunk + 1"),
+        (18, PIPELINE_CHUNK_SIZE * 2, "Boundary - Two Exact Chunks"),
+        (20, 1_000_000, "Large - Async Pipeline"),
+    ],
+)
+def test_amplitude_encoding_fidelity_comprehensive(engine, num_qubits, 
data_size, desc):
+    """Test fidelity across sync path, async pipeline, and chunk boundaries."""
+    print(f"\n[Test Case] {desc} (Size: {data_size})")
+
+    raw_data = np.random.rand(data_size).astype(np.float64)
+    norm = np.linalg.norm(raw_data)
+    expected_state = raw_data / norm
+
+    state_len = 1 << num_qubits
+    if data_size < state_len:
+        padding = np.zeros(state_len - data_size, dtype=np.float64)
+        expected_state = np.concatenate([expected_state, padding])
+
+    expected_state_complex = expected_state.astype(np.complex128)
+    qtensor = engine.encode(raw_data.tolist(), num_qubits, "amplitude")
+    torch_state = torch.from_dlpack(qtensor)
+
+    assert torch_state.is_cuda, "Tensor must be on GPU"
+    assert torch_state.dtype == torch.complex128, "Tensor must be Complex128"
+    assert torch_state.shape[0] == state_len, "Tensor shape must match 2^n"
+
+    fidelity = calculate_fidelity(torch_state, expected_state_complex)
+    print(f"Fidelity: {fidelity:.16f}")
+
+    assert fidelity > (1.0 - 1e-14), f"Fidelity loss in {desc}! F={fidelity}"
+
+
[email protected]
+def test_complex_integrity(engine):
+    """Verify imaginary part is strictly 0 for amplitude encoding."""
+    num_qubits = 12
+    data_size = 3000  # Non-power-of-2 size
+
+    raw_data = np.random.rand(data_size).astype(np.float64)
+    qtensor = engine.encode(raw_data.tolist(), num_qubits, "amplitude")
+    torch_state = torch.from_dlpack(qtensor)
+
+    imag_error = torch.sum(torch.abs(torch_state.imag)).item()
+    print(f"\nSum of imaginary parts (should be 0): {imag_error}")
+    assert imag_error == 0.0, "State vector contains non-zero imaginary 
components!"

Review Comment:
   If the backend ever introduces more floating-point operations, we might 
start seeing tiny numerical noise (~1e-16) even for real-valued encodings. 
Maybe we could relax this to something like `assert imag_error <= 1e-14` (or 
similar), so the test still guards the invariant without being too brittle.



-- 
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