From 7f90f5cabf43671b77bef40bb1fe735d52504cd5 Mon Sep 17 00:00:00 2001 From: Hsien-Cheng Huang Date: Fri, 26 Jun 2026 19:12:01 +0000 Subject: [PATCH] refactor(qdp): rename validate_tensor to validate_tensor_cpu and drop redundant check validate_tensor() re-checked is_pytorch_tensor() even though its only caller (QdpEngine::encode -> encode_from_pytorch) already guarantees the object is a torch.Tensor before dispatching to the CPU path. Remove the redundant check and rename the helper to validate_tensor_cpu to reflect that it only validates device placement -- which is also what rejects the non-CPU backends (CUDA/MPS/XLA/HPU). No behavior change. --- qdp/qdp-python/src/engine.rs | 4 ++-- qdp/qdp-python/src/pytorch.rs | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/qdp/qdp-python/src/engine.rs b/qdp/qdp-python/src/engine.rs index e3b9a9bd7a..08288909db 100644 --- a/qdp/qdp-python/src/engine.rs +++ b/qdp/qdp-python/src/engine.rs @@ -16,7 +16,7 @@ use crate::pytorch::{ extract_cuda_tensor_info, get_torch_cuda_stream_ptr, is_cuda_tensor, is_pytorch_tensor, - validate_cuda_tensor_for_encoding, validate_shape, validate_tensor, + validate_cuda_tensor_for_encoding, validate_shape, validate_tensor_cpu, }; use crate::tensor::QuantumTensor; use numpy::{PyReadonlyArray1, PyReadonlyArray2, PyUntypedArrayMethods}; @@ -206,7 +206,7 @@ impl QdpEngine { } // CPU tensor path - validate_tensor(data)?; + validate_tensor_cpu(data)?; // PERF: Avoid Tensor -> Python list -> Vec deep copies. // // For CPU tensors, `tensor.detach().numpy()` returns a NumPy view that shares the same diff --git a/qdp/qdp-python/src/pytorch.rs b/qdp/qdp-python/src/pytorch.rs index a46ae1df2c..8181e551f3 100644 --- a/qdp/qdp-python/src/pytorch.rs +++ b/qdp/qdp-python/src/pytorch.rs @@ -33,12 +33,12 @@ pub fn is_pytorch_tensor(obj: &Bound<'_, PyAny>) -> PyResult { Ok(module_name == "torch") } -/// Helper to validate CPU tensor -pub fn validate_tensor(tensor: &Bound<'_, PyAny>) -> PyResult<()> { - if !is_pytorch_tensor(tensor)? { - return Err(PyRuntimeError::new_err("Object is not a PyTorch Tensor")); - } - +/// Validate that a PyTorch tensor lives on the CPU. +/// +/// The caller must have already confirmed `tensor` is a `torch.Tensor` (e.g. +/// via [`is_pytorch_tensor`]). This function only checks device placement, so +/// it also rejects non-CPU backends such as CUDA, MPS, XLA, and HPU. +pub fn validate_tensor_cpu(tensor: &Bound<'_, PyAny>) -> PyResult<()> { let device = tensor.getattr("device")?; let device_type: String = device.getattr("type")?.extract()?;