#serde #serialize-deserialize #type #tch-rs

tch-serde

Serialize/Deserialize tch-rs types with serde

12 releases (7 breaking)

0.8.0 Apr 3, 2022
0.7.0 Nov 14, 2021
0.6.0 Jun 26, 2021
0.4.0 Mar 26, 2021
0.1.2 Jul 21, 2020

#1503 in Encoding

29 downloads per month

MIT license

20KB
421 lines

tch-serde: Serialize/Deserialize tch-rs types with serde

This crate provides {ser,de}ialization methods for tch-rs common types.

docs.rs | crates.io

Usage

For example, annotate #[serde(with = "tch_serde::serde_tensor")] attributes to enable serialization on tensor field.

use tch::{Device, Kind, Tensor};

#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct Example {
    #[serde(with = "tch_serde::serde_tensor")]
    tensor: Tensor,
    #[serde(with = "tch_serde::serde_kind")]
    kind: Kind,
    #[serde(with = "tch_serde::serde_device")]
    device: Device,
    #[serde(with = "tch_serde::serde_reduction")]
    reduction: Reduction,
}

fn main() {
    let example = Example {
        tensor: Tensor::randn(&[2, 3], (Kind::Float, Device::Cuda(0))),
        kind: Kind::Float,
        device: Device::Cpu,
        reduction: Reduction::Mean,
    };
    let text = serde_json::to_string_pretty(&example).unwrap();
    println!("{}", text);
}

License

MIT license. See the LICENSE file.

Dependencies

~7–10MB
~210K SLoC