viiccwen commented on code in PR #1000:
URL: https://github.com/apache/mahout/pull/1000#discussion_r2751386574


##########
qdp/qdp-python/src/lib.rs:
##########
@@ -1038,20 +1112,193 @@ impl QdpEngine {
             consumed: false,
         })
     }
+
+    /// Create a synthetic-data loader iterator for use in Python `for qt in 
loader`.
+    ///
+    /// Yields one QuantumTensor (batch) per iteration; releases GIL during 
encode.
+    /// Use with QuantumDataLoader builder or directly for streaming encode.
+    ///
+    /// Args:
+    ///     total_batches: Number of batches to yield
+    ///     batch_size: Samples per batch
+    ///     num_qubits: Qubits per sample
+    ///     encoding_method: "amplitude", "angle", or "basis"
+    ///     seed: Optional RNG seed for reproducible synthetic data
+    ///
+    /// Returns:
+    ///     PyQuantumLoader: iterator yielding QuantumTensor per __next__
+    #[cfg(target_os = "linux")]
+    #[pyo3(signature = (total_batches, batch_size=64, num_qubits=16, 
encoding_method="amplitude", seed=None))]
+    fn create_synthetic_loader(
+        &self,
+        total_batches: usize,
+        batch_size: usize,
+        num_qubits: u32,
+        encoding_method: &str,
+        seed: Option<u64>,
+    ) -> PyResult<PyQuantumLoader> {
+        let config = PipelineConfig {
+            device_id: 0,
+            num_qubits,
+            batch_size,
+            total_batches,
+            encoding_method: encoding_method.to_string(),
+            seed,
+            warmup_batches: 0,
+        };

Review Comment:
   device_id use hard-coded 0, config should equals to use actually.



##########
qdp/qdp-python/qumat_qdp/loader.py:
##########
@@ -0,0 +1,124 @@
+#
+# 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.
+
+"""
+Quantum Data Loader: Python builder for Rust-backed batch iterator.
+
+Usage:
+    from qumat_qdp import QuantumDataLoader
+
+    loader = (QuantumDataLoader(device_id=0).qubits(16).encoding("amplitude")
+              .batches(100, size=64).source_synthetic())
+    for qt in loader:
+        batch = torch.from_dlpack(qt)
+        ...
+"""
+
+from __future__ import annotations
+
+from functools import lru_cache
+from typing import TYPE_CHECKING, Iterator, Optional
+
+if TYPE_CHECKING:
+    import _qdp  # noqa: F401 -- for type checkers only
+
+# Lazy import _qdp at runtime until __iter__ is used; TYPE_CHECKING import 
above
+# is for type checkers only so they can resolve "_qdp.*" annotations if needed.
+
+
+@lru_cache(maxsize=1)
+def _get_qdp():
+    import _qdp as m
+
+    return m
+
+
+class QuantumDataLoader:
+    """
+    Builder for a synthetic-data quantum encoding iterator.
+
+    Yields one QuantumTensor (batch) per iteration. All encoding runs in Rust;
+    __iter__ returns the Rust-backed iterator from create_synthetic_loader.
+    """
+
+    def __init__(
+        self,
+        device_id: int = 0,
+        num_qubits: int = 16,
+        batch_size: int = 64,
+        total_batches: int = 100,
+        encoding_method: str = "amplitude",
+        seed: Optional[int] = None,

Review Comment:
   seed in Rust interface is: `seed: Option<u64>`, but in Python is: `seed: 
Optional[int] = None`.
   
   maybe we can add validate guard to raise `ValueError` with clear description.



##########
testing/qdp/test_benchmark_api.py:
##########
@@ -0,0 +1,94 @@
+#
+# 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 the benchmark API (QdpBenchmark, Rust pipeline only)."""
+
+from pathlib import Path
+
+import pytest
+
+# Allow importing benchmark API from qdp-python/benchmark and qumat_qdp from 
qdp-python
+_sys = __import__("sys")
+_qdp_python = Path(__file__).resolve().parent.parent.parent / "qdp" / 
"qdp-python"
+_bench_dir = _qdp_python / "benchmark"
+if _qdp_python.exists() and str(_qdp_python) not in _sys.path:
+    _sys.path.insert(0, str(_qdp_python))
+if _bench_dir.exists() and str(_bench_dir) not in _sys.path:
+    _sys.path.insert(0, str(_bench_dir))
+
+from .qdp_test_utils import requires_qdp  # noqa: E402
+
+
+@requires_qdp
+def test_benchmark_api_import():
+    """Test that the benchmark API exports only Rust-pipeline path (no 
encode_stream / Python loop)."""
+    import api
+
+    assert hasattr(api, "QdpBenchmark")
+    assert hasattr(api, "ThroughputResult")
+    assert hasattr(api, "LatencyResult")
+    # No naive Python for-loop API
+    assert not hasattr(api, "encode_stream")
+    assert not hasattr(api, "create_pipeline")
+    assert not hasattr(api, "StreamPipeline")
+    assert not hasattr(api, "PipelineConfig")
+
+
+@requires_qdp
[email protected]
+def test_qdp_benchmark_run_throughput():
+    """QdpBenchmark.run_throughput() calls Rust pipeline and returns 
ThroughputResult (requires GPU)."""
+    import api
+
+    result = (
+        api.QdpBenchmark(device_id=0)
+        .qubits(2)
+        .encoding("amplitude")
+        .batches(2, size=4)
+        .prefetch(2)
+        .run_throughput()
+    )
+    assert isinstance(result, api.ThroughputResult)
+    assert result.duration_sec >= 0
+    assert result.vectors_per_sec > 0
+
+
+@requires_qdp
[email protected]
+def test_qdp_benchmark_run_latency():
+    """QdpBenchmark.run_latency() calls Rust pipeline and returns 
LatencyResult (requires GPU)."""
+    import api
+
+    result = (
+        api.QdpBenchmark(device_id=0)
+        .qubits(2)
+        .encoding("amplitude")
+        .batches(2, size=4)
+        .prefetch(2)
+        .run_latency()
+    )
+    assert isinstance(result, api.LatencyResult)
+    assert result.duration_sec >= 0
+    assert result.latency_ms_per_vector > 0
+
+
+@requires_qdp
+def test_qdp_benchmark_validation():
+    """QdpBenchmark.run_throughput() raises if qubits/batches not set."""
+    import api
+
+    with pytest.raises(ValueError, match="qubits and batches"):
+        api.QdpBenchmark(device_id=0).run_throughput()

Review Comment:
   lacks of testing of `run_latency()` if qubits/batches not set. 



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