Skip to content

Add optional serde serialization support #250

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ jobs:
export AF_PATH=${GITHUB_WORKSPACE}/afbin
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${AF_PATH}/lib64
echo "Using cargo version: $(cargo --version)"
cargo build --all
cargo test --no-fail-fast
cargo build --all --all-features
cargo test --no-fail-fast --all-features

format:
name: Format Check
Expand Down
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,19 @@ statistics = []
vision = []
default = ["algorithm", "arithmetic", "blas", "data", "indexing", "graphics", "image", "lapack",
"ml", "macros", "random", "signal", "sparse", "statistics", "vision"]
afserde = ["serde"]

[dependencies]
libc = "0.2"
num = "0.2"
lazy_static = "1.0"
half = "1.5.0"
serde = { version = "1.0", features = ["derive"], optional = true }

[dev-dependencies]
half = "1.5.0"
serde_json = "1.0"
bincode = "1.3"

[build-dependencies]
serde_json = "1.0"
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Only, Major(M) & Minor(m) version numbers need to match. *p1* and *p2* are patch

## Supported platforms

Linux, Windows and OSX. Rust 1.15.1 or higher is required.
Linux, Windows and OSX. Rust 1.31 or newer is required.

## Use from Crates.io [![][6]][7] [![][8]][9]

Expand Down
2 changes: 1 addition & 1 deletion cuda-interop/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ rustacuda = "0.1"
rustacuda_core = "0.1"

[[example]]
name = "custom_kernel"
name = "afcuda_custom_kernel"
path = "examples/custom_kernel.rs"

[[example]]
Expand Down
1 change: 0 additions & 1 deletion cuda-interop/examples/cuda_af_app.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use arrayfire::{af_print, dim4, info, set_device, Array};
use rustacuda::prelude::*;
use rustacuda::*;

fn main() {
// MAKE SURE to do all rustacuda initilization before arrayfire API's
Expand Down
2 changes: 1 addition & 1 deletion opencl-interop/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ cl-sys = "0.4.2"
ocl-core = "0.11.2"

[[example]]
name = "custom_kernel"
name = "afocl_custom_kernel"
path = "examples/custom_kernel.rs"

[[example]]
Expand Down
2 changes: 1 addition & 1 deletion opencl-interop/examples/custom_kernel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ fn main() {
let af_ctx = afcl::get_context(false);
let af_que = afcl::get_queue(false);

let devid = unsafe { ocl_core::DeviceId::from_raw(af_did) };
let _devid = unsafe { ocl_core::DeviceId::from_raw(af_did) };
let contx = unsafe { ocl_core::Context::from_raw_copied_ptr(af_ctx) };
let queue = unsafe { ocl_core::CommandQueue::from_raw_copied_ptr(af_que) };

Expand Down
100 changes: 100 additions & 0 deletions src/core/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -851,6 +851,73 @@ pub fn is_eval_manual() -> bool {
}
}

#[cfg(feature = "afserde")]
mod afserde {
// Reimport required from super scope
use super::{Array, DType, Dim4, HasAfEnum};

use serde::de::{Deserializer, Error, Unexpected};
use serde::ser::Serializer;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct ArrayOnHost<T: HasAfEnum + std::fmt::Debug> {
dtype: DType,
shape: Dim4,
data: Vec<T>,
}

/// Serialize Implementation of Array
impl<T> Serialize for Array<T>
where
T: std::default::Default + std::clone::Clone + Serialize + HasAfEnum + std::fmt::Debug,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut vec = vec![T::default(); self.elements()];
self.host(&mut vec);
let arr_on_host = ArrayOnHost {
dtype: self.get_type(),
shape: self.dims().clone(),
data: vec,
};
arr_on_host.serialize(serializer)
}
}

/// Deserialize Implementation of Array
impl<'de, T> Deserialize<'de> for Array<T>
where
T: Deserialize<'de> + HasAfEnum + std::fmt::Debug,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
match ArrayOnHost::<T>::deserialize(deserializer) {
Ok(arr_on_host) => {
let read_dtype = arr_on_host.dtype;
let expected_dtype = T::get_af_dtype();
if expected_dtype != read_dtype {
let error_msg = format!(
"data type is {:?}, deserialized type is {:?}",
expected_dtype, read_dtype
);
return Err(Error::invalid_value(Unexpected::Enum, &error_msg.as_str()));
}
Ok(Array::<T>::new(
&arr_on_host.data,
arr_on_host.shape.clone(),
))
}
Err(err) => Err(err),
}
}
}
}

#[cfg(test)]
mod tests {
use super::super::array::print;
Expand Down Expand Up @@ -1082,4 +1149,37 @@ mod tests {
// 8.0000 8.0000 8.0000
// ANCHOR_END: accum_using_channel
}

#[cfg(feature = "afserde")]
mod serde_tests {
use super::super::Array;
use crate::algorithm::sum_all;
use crate::randu;

#[test]
fn array_serde_json() {
let input = randu!(u8; 2, 2);
let serd = match serde_json::to_string(&input) {
Ok(serialized_str) => serialized_str,
Err(e) => e.to_string(),
};

let deserd: Array<u8> = serde_json::from_str(&serd).unwrap();

assert_eq!(sum_all(&(input - deserd)), (0u32, 0u32));
}

#[test]
fn array_serde_bincode() {
let input = randu!(u8; 2, 2);
let encoded = match bincode::serialize(&input) {
Ok(encoded) => encoded,
Err(_) => vec![],
};

let decoded: Array<u8> = bincode::deserialize(&encoded).unwrap();

assert_eq!(sum_all(&(input - decoded)), (0u32, 0u32));
}
}
}
Loading