viiccwen commented on code in PR #815: URL: https://github.com/apache/mahout/pull/815#discussion_r2683320042
########## qdp/qdp-core/tests/torch_io.rs: ########## @@ -0,0 +1,62 @@ +// +// 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. + +#[cfg(feature = "pytorch")] +mod pytorch_tests { + use qdp_core::io::read_torch_batch; + use qdp_core::reader::DataReader; + use qdp_core::readers::TorchReader; + use std::fs; + use tch::Tensor; + + #[test] + fn test_torch_reader_basic_1d() { + let temp_path = "/tmp/test_torch_basic_1d.pt"; Review Comment: Does this work in Windows? ########## qdp/qdp-core/src/readers/torch.rs: ########## @@ -0,0 +1,165 @@ +// +// 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. + +//! PyTorch tensor reader implementation. +//! +//! Supports `.pt`/`.pth` files containing a single tensor saved with `torch.save`. +//! The tensor must be 1D or 2D and will be converted to `float64`. +//! Requires the `pytorch` feature to be enabled. + +use std::path::Path; + +use crate::error::{MahoutError, Result}; +use crate::reader::DataReader; + +/// Reader for PyTorch `.pt`/`.pth` tensor files. +pub struct TorchReader { + path: std::path::PathBuf, + read: bool, +} + +impl TorchReader { + /// Create a new PyTorch reader. + /// + /// # Arguments + /// * `path` - Path to the `.pt`/`.pth` file + pub fn new<P: AsRef<Path>>(path: P) -> Result<Self> { + let path = path.as_ref(); + + match path.try_exists() { + Ok(false) => { + return Err(MahoutError::Io(format!( + "PyTorch file not found: {}", + path.display() + ))); + } + Err(e) => { + return Err(MahoutError::Io(format!( + "Failed to check if PyTorch file exists at {}: {}", + path.display(), + e + ))); + } + Ok(true) => {} + } + + Ok(Self { + path: path.to_path_buf(), + read: false, + }) + } +} + +impl DataReader for TorchReader { + fn read_batch(&mut self) -> Result<(Vec<f64>, usize, usize)> { + if self.read { + return Err(MahoutError::InvalidInput( + "Reader already consumed".to_string(), + )); + } + self.read = true; + + #[cfg(feature = "pytorch")] + { + return read_torch_tensor(&self.path); + } + + #[cfg(not(feature = "pytorch"))] + { + return Err(MahoutError::NotImplemented( + "PyTorch reader requires the 'pytorch' feature".to_string(), + )); + } + } + + fn get_sample_size(&self) -> Option<usize> { + None + } + + fn get_num_samples(&self) -> Option<usize> { + None + } +} + +#[cfg(feature = "pytorch")] +fn read_torch_tensor(path: &Path) -> Result<(Vec<f64>, usize, usize)> { + use tch::{Device, Kind, Tensor}; + + let tensor = Tensor::load(path).map_err(|e| { + MahoutError::Io(format!( + "Failed to load PyTorch tensor from {}: {}", + path.display(), + e + )) + })?; + + let tensor = tensor.to_device(Device::Cpu).to_kind(Kind::Double).contiguous(); + let sizes = tensor.size(); + let (num_samples, sample_size) = parse_shape(&sizes)?; Review Comment: I think we should validate tensor shape/size first, then do a bit expensive transform with device & type. -- 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]
