1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! Scientific Data Format Implementations
//!
//! This module provides serialization support for scientific computing formats,
//! particularly HDF5 which is widely used in scientific computing for its
//! support of hierarchical data, compression, and metadata.
// Imports needed by both real implementations and stubs
#[allow(unused_imports)]
use super::common::{SerializationFormat, SerializationOptions, TensorMetadata};
#[allow(unused_imports)]
use crate::{Tensor, TensorElement};
#[allow(unused_imports)]
use std::path::Path;
#[allow(unused_imports)]
use torsh_core::error::{Result, TorshError};
/// HDF5 format implementation
#[cfg(feature = "serialize-hdf5")]
pub mod hdf5 {
use super::*;
use crate::DeviceType;
use ::hdf5::{types::VarLenUnicode, Dataset, File, Group, H5Type};
/// Serialize tensor to HDF5 format
///
/// Creates an HDF5 file with the tensor data stored as a dataset
/// and metadata stored as attributes. Supports compression and
/// chunking for large datasets.
///
/// # Arguments
/// * `tensor` - Tensor to serialize
/// * `path` - Output file path
/// * `dataset_name` - Name for the dataset within the HDF5 file
/// * `options` - Serialization options
///
/// # Returns
/// * `Result<()>` - Ok if successful, error otherwise
pub fn serialize_hdf5<T: TensorElement + H5Type>(
tensor: &Tensor<T>,
path: &Path,
dataset_name: &str,
options: &SerializationOptions,
) -> Result<()> {
let file = File::create(path).map_err(|e| {
TorshError::SerializationError(format!("Failed to create HDF5 file: {}", e))
})?;
// Get tensor data and shape
let data = tensor.data()?;
let shape_dims: Vec<usize> = tensor.shape().dims().to_vec();
// Create dataset with optional compression
let mut dataset_builder = file.new_dataset::<T>().shape(&shape_dims);
if options.compression_level > 0 {
// Enable compression - use deflate which is more widely supported
dataset_builder = dataset_builder.deflate(options.compression_level.min(9));
}
// Enable chunking for large datasets
if let Some(chunk_size) = options.chunk_size {
let total_elements = shape_dims.iter().product::<usize>();
if total_elements > chunk_size {
// Calculate chunk dimensions
let elements_per_chunk = chunk_size / std::mem::size_of::<T>();
if elements_per_chunk > 0 {
let chunk_dims = calculate_chunk_dims(&shape_dims, elements_per_chunk);
dataset_builder = dataset_builder.chunk(&chunk_dims);
}
}
}
let dataset = dataset_builder.create(dataset_name).map_err(|e| {
TorshError::SerializationError(format!("Failed to create HDF5 dataset: {}", e))
})?;
// Write tensor data
dataset.write(&*data).map_err(|e| {
TorshError::SerializationError(format!("Failed to write tensor data to HDF5: {}", e))
})?;
// Create and store metadata
let metadata = TensorMetadata::from_tensor(
tensor,
options,
SerializationFormat::Hdf5,
data.len() * std::mem::size_of::<T>(),
);
// Store metadata as HDF5 attributes
store_metadata_as_attributes(&dataset, &metadata)?;
// Store custom metadata - temporarily disabled due to HDF5 API compatibility
// TODO: Implement proper string metadata storage when HDF5 API is updated
for (_key, _value) in &options.metadata {
// Custom metadata storage disabled for now
}
Ok(())
}
/// Deserialize tensor from HDF5 format
///
/// Reads an HDF5 file and reconstructs the tensor with its metadata.
/// Automatically handles decompression and chunked data.
///
/// # Arguments
/// * `path` - Input file path
/// * `dataset_name` - Name of the dataset within the HDF5 file
///
/// # Returns
/// * `Result<Tensor<T>>` - Deserialized tensor or error
pub fn deserialize_hdf5<T: TensorElement + H5Type>(
path: &Path,
dataset_name: &str,
) -> Result<Tensor<T>> {
let file = File::open(path).map_err(|e| {
TorshError::SerializationError(format!("Failed to open HDF5 file: {}", e))
})?;
let dataset = file.dataset(dataset_name).map_err(|e| {
TorshError::SerializationError(format!(
"Failed to open HDF5 dataset '{}': {}",
dataset_name, e
))
})?;
// Read shape information
let shape_dims = dataset.shape();
if shape_dims.is_empty() {
return Err(TorshError::SerializationError(
"HDF5 dataset has empty shape".to_string(),
));
}
// Read tensor data (HDF5 handles decompression automatically)
let data: Vec<T> = dataset.read_raw().map_err(|e| {
TorshError::SerializationError(format!("Failed to read tensor data from HDF5: {}", e))
})?;
// Verify data size consistency
let expected_size = shape_dims.iter().product::<usize>();
if data.len() != expected_size {
return Err(TorshError::SerializationError(format!(
"HDF5 data size mismatch: expected {} elements, got {}",
expected_size,
data.len()
)));
}
// Read metadata from attributes
let device = read_device_from_attributes(&dataset)?;
// Create tensor
let tensor = Tensor::from_data(data, shape_dims, device)?;
// Set requires_grad if available
if let Ok(_requires_grad) = dataset
.attr("requires_grad")
.and_then(|attr| attr.read_scalar::<bool>())
{
// TODO: Implement mutable set_requires_grad when autograd is available
// For now, the requires_grad field is set during tensor construction
}
Ok(tensor)
}
/// List datasets in an HDF5 file
///
/// # Arguments
/// * `path` - HDF5 file path
///
/// # Returns
/// * `Result<Vec<String>>` - List of dataset names or error
pub fn list_datasets(path: &Path) -> Result<Vec<String>> {
let file = File::open(path).map_err(|e| {
TorshError::SerializationError(format!("Failed to open HDF5 file: {}", e))
})?;
let mut datasets = Vec::new();
collect_datasets(&file, "/", &mut datasets)?;
Ok(datasets)
}
/// Get dataset metadata without loading data
///
/// # Arguments
/// * `path` - HDF5 file path
/// * `dataset_name` - Dataset name
///
/// # Returns
/// * `Result<TensorMetadata>` - Metadata or error
pub fn get_dataset_metadata(path: &Path, dataset_name: &str) -> Result<TensorMetadata> {
let file = File::open(path).map_err(|e| {
TorshError::SerializationError(format!("Failed to open HDF5 file: {}", e))
})?;
let dataset = file.dataset(dataset_name).map_err(|e| {
TorshError::SerializationError(format!("Failed to open dataset: {}", e))
})?;
read_metadata_from_attributes(&dataset)
}
/// Helper function to store metadata as HDF5 attributes
fn store_metadata_as_attributes(dataset: &Dataset, metadata: &TensorMetadata) -> Result<()> {
// Store device information - temporarily disabled due to HDF5 API compatibility
// TODO: Implement proper device storage when HDF5 string API is updated
let _device_info = format!("{:?}", metadata.device);
// Store gradient requirement
dataset
.new_attr::<bool>()
.create("requires_grad")
.map_err(|e| {
TorshError::SerializationError(format!(
"Failed to create requires_grad attribute: {}",
e
))
})?
.write_scalar(&metadata.requires_grad)
.map_err(|e| {
TorshError::SerializationError(format!(
"Failed to write requires_grad attribute: {}",
e
))
})?;
// Store data type - temporarily disabled due to HDF5 API compatibility
// TODO: Implement proper dtype storage when HDF5 string API is updated
let _dtype_info = &metadata.dtype_name;
// Store version - temporarily disabled due to HDF5 API compatibility
// TODO: Implement proper version storage when HDF5 string API is updated
let _version_info = &metadata.version;
// Store timestamp
dataset
.new_attr::<u64>()
.create("timestamp")
.map_err(|e| {
TorshError::SerializationError(format!(
"Failed to create timestamp attribute: {}",
e
))
})?
.write_scalar(&metadata.timestamp)
.map_err(|e| {
TorshError::SerializationError(format!(
"Failed to write timestamp attribute: {}",
e
))
})?;
Ok(())
}
/// Helper function to read device information from HDF5 attributes
fn read_device_from_attributes(dataset: &Dataset) -> Result<DeviceType> {
let device_str: VarLenUnicode = dataset
.attr("device")
.map_err(|e| {
TorshError::SerializationError(format!("Failed to read device attribute: {}", e))
})?
.read_scalar()
.map_err(|e| {
TorshError::SerializationError(format!("Failed to read device value: {}", e))
})?;
let device = match device_str.as_str() {
"Cpu" => DeviceType::Cpu,
s if s.starts_with("Cuda(") => {
let id_str = &s[5..s.len() - 1];
let id: usize = id_str.parse().unwrap_or(0);
DeviceType::Cuda(id)
}
s if s.starts_with("Metal(") => {
let id_str = &s[6..s.len() - 1];
let id: usize = id_str.parse().unwrap_or(0);
DeviceType::Metal(id)
}
_ => DeviceType::Cpu, // Default fallback
};
Ok(device)
}
/// Helper function to read metadata from HDF5 attributes
fn read_metadata_from_attributes(dataset: &Dataset) -> Result<TensorMetadata> {
let device = read_device_from_attributes(dataset)?;
let requires_grad = dataset
.attr("requires_grad")
.and_then(|attr| attr.read_scalar::<bool>())
.unwrap_or(false);
let dtype_name: String = dataset
.attr("dtype")
.and_then(|attr| attr.read_scalar::<VarLenUnicode>())
.map(|s| s.to_string())
.unwrap_or_else(|_| "unknown".to_string());
let version: String = dataset
.attr("version")
.and_then(|attr| attr.read_scalar::<VarLenUnicode>())
.map(|s| s.to_string())
.unwrap_or_else(|_| "unknown".to_string());
let timestamp = dataset
.attr("timestamp")
.and_then(|attr| attr.read_scalar::<u64>())
.unwrap_or(0);
use torsh_core::shape::Shape;
let shape_dims = dataset.shape();
let shape = Shape::new(shape_dims.clone());
Ok(TensorMetadata {
shape,
device,
requires_grad,
dtype_name,
version,
timestamp,
custom_metadata: std::collections::HashMap::new(),
format: "Hdf5".to_string(),
data_size: shape_dims.iter().product::<usize>() * std::mem::size_of::<f32>(), // Approximate
compressed: false, // HDF5 compression is transparent
checksum: None,
})
}
/// Helper function to calculate optimal chunk dimensions
fn calculate_chunk_dims(shape: &[usize], target_elements: usize) -> Vec<usize> {
if shape.is_empty() {
return Vec::new();
}
let mut chunk_dims = shape.to_vec();
let total_elements = shape.iter().product::<usize>();
if total_elements <= target_elements {
return chunk_dims;
}
// Start from the last dimension and reduce chunk size
let mut remaining_elements = target_elements;
for i in (0..chunk_dims.len()).rev() {
if remaining_elements >= chunk_dims[i] {
remaining_elements /= chunk_dims[i];
} else {
chunk_dims[i] = remaining_elements;
remaining_elements = 1;
}
if remaining_elements <= 1 {
break;
}
}
chunk_dims
}
/// Helper function to recursively collect dataset names
fn collect_datasets(group: &Group, prefix: &str, datasets: &mut Vec<String>) -> Result<()> {
for name in group.member_names().map_err(|e| {
TorshError::SerializationError(format!("Failed to list group members: {}", e))
})? {
let full_path = if prefix == "/" {
format!("/{}", name)
} else {
format!("{}/{}", prefix, name)
};
if group.link_exists(&name) {
match group.group(&name) {
Ok(subgroup) => {
collect_datasets(&subgroup, &full_path, datasets)?;
}
Err(_) => {
// Assume it's a dataset
datasets.push(full_path);
}
}
}
}
Ok(())
}
}
/// Stub implementation when HDF5 feature is not enabled
#[cfg(not(feature = "serialize-hdf5"))]
pub mod hdf5 {
use super::*;
pub fn serialize_hdf5<T: TensorElement>(
_tensor: &Tensor<T>,
_path: &Path,
_dataset_name: &str,
_options: &SerializationOptions,
) -> Result<()> {
Err(TorshError::SerializationError(
"HDF5 serialization requires the 'serialize-hdf5' feature to be enabled".to_string(),
))
}
pub fn deserialize_hdf5<T: TensorElement>(
_path: &Path,
_dataset_name: &str,
) -> Result<Tensor<T>> {
Err(TorshError::SerializationError(
"HDF5 deserialization requires the 'serialize-hdf5' feature to be enabled".to_string(),
))
}
pub fn list_datasets(_path: &Path) -> Result<Vec<String>> {
Err(TorshError::SerializationError(
"HDF5 operations require the 'serialize-hdf5' feature to be enabled".to_string(),
))
}
pub fn get_dataset_metadata(_path: &Path, _dataset_name: &str) -> Result<TensorMetadata> {
Err(TorshError::SerializationError(
"HDF5 operations require the 'serialize-hdf5' feature to be enabled".to_string(),
))
}
}