Skip to content

v0.3.1-dev #67

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 13 commits into from
Apr 9, 2024
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
34 changes: 25 additions & 9 deletions acme/examples/autodiff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,35 @@ extern crate acme;

use acme::autodiff;

macro_rules! format_exp {
(symbolic: {exp: $ex:expr, vars: [$($var:ident),*] }) => {
{
format!("f({})\t= {}", stringify!($($var),*), stringify!($ex))
}

}
}

macro_rules! eval {
($var:ident: $ex:expr) => {
println!("Eval: {:?}", $ex);
println!("Gradient: {:?}", autodiff!($var: $ex));
{
let tmp = autodiff!($var: $ex);
let var = stringify!($var);
println!("*** Eval ***\nf({})\t= {}\nf({})\t= {:?}\nf'({})\t= {:?}\n", &var, stringify!($ex), $var, $ex, $var, &tmp);
tmp
}

}
}

fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let x = 2_f64;

let y = 3f64;
let exp = format_exp!(symbolic: {exp: x * y, vars: [x, y]});
println!("{}", exp);
// multiply(x, x);

samples(x);
trig_functions(x);

Ok(())
}
Expand All @@ -33,10 +49,10 @@ fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
// x * y
// }

fn samples(x: f64) {
eval!(x: x.tan());

eval!(x: x.sin());
fn trig_functions(x: f64) {
let _tangent = eval!(x: x.tan());

eval!(x: x.cos().sin());
let sine = eval!(x: x.sin());
assert_eq!(sine, x.cos());
let _cos_sin = eval!(x: x.cos().sin());
}
8 changes: 7 additions & 1 deletion acme/examples/simple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,14 @@
*/
extern crate acme;

use acme::prelude::BoxResult;
use acme::prelude::{nested, BoxResult};

fn main() -> BoxResult {
nested!(
for i in 0..3,
for j in 0..3,
for k in 0..3 => {
println!("({}, {}, {})", i, j, k)
});
Ok(())
}
89 changes: 87 additions & 2 deletions acme/examples/tensor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,98 @@

extern crate acme;

use acme::prelude::{BoxResult, Matmul, Tensor};
use acme::prelude::{Axis, BoxResult, IntoShape, Linspace, Matmul, Tensor};

fn main() -> BoxResult {
let shape = (3, 3);

// tensor_iter_mut(shape)?;
axis_iter(shape, 0)?;
Ok(())
}

pub fn axis_iter(shape: impl IntoShape, axis: usize) -> BoxResult<Tensor<f64>> {
let axis = Axis::new(axis);
let shape = shape.into_shape();
let n = shape.size();
let tensor = Tensor::linspace(0f64, n as f64, n).reshape(shape.clone())?;

let mut res = Vec::new();
for i in 0..tensor.shape()[axis] {
let mut tmp = Tensor::zeros(shape.ncols());
for k in 0..shape.ncols() {
tmp[[k]] = tensor[[i, k]];
}
res.push(tmp);
}
for i in res {
println!("{:?}", &i.to_vec());
}
Ok(tensor)
}

#[allow(dead_code)]
pub fn axis_iter_impl(shape: impl IntoShape, axis: usize) -> BoxResult<Tensor<f64>> {
let axis = Axis::new(axis);
let shape = shape.into_shape();
let n = shape.size();
let tensor = Tensor::linspace(0f64, n as f64, n).reshape(shape.clone())?;

let ns = tensor.layout().remove_axis(axis);
let mut res = Vec::new();
for i in 0..tensor.shape()[axis] {
for j in ns.shape().iter().copied() {
let mut tmp = Tensor::zeros(j);
for k in 0..ns.shape()[j] {
tmp[[k]] = tensor[[i, k]];
}
res.push(tmp);
}
}
for i in res {
println!("{:?}", &i.to_vec());
}
Ok(tensor)
}

pub fn example_matmul() -> BoxResult<Tensor<f64>> {
let shape = (2, 3);
let tensor: Tensor<f64> = Tensor::linspace(1.0, 7.0, 6).reshape(shape)?;
let b = tensor.t();
let c = tensor.matmul(&b);
println!("{:?}", &c);
Ok(())
Ok(c)
}

pub fn tensor_iter_mut(shape: impl IntoShape) -> BoxResult<Tensor<f64>> {
let shape = shape.into_shape();
let n = shape.size();
let exp = Vec::linspace(0f64, n as f64, n);
let mut tensor = Tensor::zeros(shape);
assert_ne!(&tensor, &exp);
for (elem, val) in tensor.iter_mut().zip(exp.iter()) {
*elem = *val;
}
assert_eq!(&tensor, &exp);
println!("{:?}", Vec::from_iter(&mut tensor.iter().rev()));
Ok(tensor)
}

pub fn tensor_iter_mut_rev(shape: impl IntoShape) -> BoxResult<Tensor<f64>> {
let shape = shape.into_shape();
let n = shape.size();
let exp = Vec::linspace(0f64, n as f64, n);
let mut tensor = Tensor::zeros(shape.clone());
assert_ne!(&tensor, &exp);
for (elem, val) in tensor.iter_mut().rev().zip(exp.iter()) {
*elem = *val;
}
// assert_eq!(&tensor, &exp);
let sample = Tensor::linspace(0f64, n as f64, n).reshape(shape)?;
println!("*** Reversed ***");
for i in sample.clone().iter().copied().rev() {
println!("{:?}", i);
}

Ok(tensor)
}
4 changes: 2 additions & 2 deletions core/src/error/err.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
Contrib: FL03 <jo3mccain@icloud.com>
*/
use super::kinds::{ErrorKind, ExternalError, SyncError};
use core::fmt::{self, Debug, Display};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use std::fmt::{Debug, Display};

#[cfg_attr(feature = "serde", derive(Deserialize, Serialize,))]
#[derive(Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
Expand Down Expand Up @@ -53,7 +53,7 @@ impl<K> Display for Error<K>
where
K: ToString,
{
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}: {}", self.kind.to_string(), self.message)
}
}
Expand Down
2 changes: 1 addition & 1 deletion core/src/error/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ pub use self::{err::*, kinds::*};
pub(crate) mod err;
pub(crate) mod kinds;

pub type Result<T = ()> = std::result::Result<T, Error>;
pub type Result<T = ()> = core::result::Result<T, Error>;

#[cfg(test)]
mod tests {}
1 change: 1 addition & 0 deletions core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ pub mod types;
pub mod prelude {
pub use crate::error::*;
pub use crate::id::*;
pub use crate::nested;
pub use crate::ops::prelude::*;
pub use crate::specs::prelude::*;
pub use crate::types::*;
Expand Down
2 changes: 1 addition & 1 deletion core/src/ops/binary/arithmetic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ macro_rules! operator {
}

impl core::fmt::Display for $op {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}", self.name())
}
}
Expand Down
18 changes: 18 additions & 0 deletions core/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,24 @@
Contrib: FL03 <jo3mccain@icloud.com>
*/

///
#[macro_export]
macro_rules! nested {
(@loop $exp:expr, for $i:ident in $iter:expr) => {
for $i in $iter {
$exp
}
};
(@loop $exp:expr, for $i:ident in $iter:expr, $($tail:tt)*) => {
for $i in $iter {
nested!(@loop $exp, $($tail)*);
}
};
($(for $i:ident in $iter:expr),* => {$exp:expr} ) => {
nested!(@loop $exp, $(for $i in $iter),*);
};
}

macro_rules! unit_enum_constructor {
($(($variant:ident, $method:ident)),*) => {
$(
Expand Down
10 changes: 5 additions & 5 deletions exp/ndtensor/src/data/repr/view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
*/
use crate::data::specs::*;
use crate::data::{Container, ContainerBase, ContainerView, ContainerViewMut};
use crate::iter::{Baseiter, ElementsBase, ElementsBaseMut, Iter, IterMut};
use crate::iter::{BaseIter, ElementsBase, ElementsBaseMut, Iter, IterMut};
use core::marker::PhantomData;
use core::ptr::NonNull;
use core::slice;
Expand Down Expand Up @@ -130,9 +130,9 @@ impl<'a, A> ContainerView<'a, A> {
// Internal Methods
impl<'a, A> ContainerView<'a, A> {
#[inline]
pub(crate) fn into_base_iter(self) -> Baseiter<A> {
pub(crate) fn into_base_iter(self) -> BaseIter<A> {
unsafe {
Baseiter::new(
BaseIter::new(
self.ptr.as_ptr(),
self.shape().clone(),
self.stride().clone(),
Expand All @@ -152,9 +152,9 @@ impl<'a, A> ContainerView<'a, A> {

impl<'a, A> ContainerViewMut<'a, A> {
#[inline]
pub(crate) fn into_base_iter(self) -> Baseiter<A> {
pub(crate) fn into_base_iter(self) -> BaseIter<A> {
unsafe {
Baseiter::new(
BaseIter::new(
self.ptr.as_ptr(),
self.shape().clone(),
self.stride().clone(),
Expand Down
42 changes: 21 additions & 21 deletions exp/ndtensor/src/iter/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,15 @@ pub enum ElementsRepr<S, C> {
/// Counted read only iterator
#[derive(Debug)]
pub struct ElementsBase<'a, A> {
inner: Baseiter<A>,
life: PhantomData<&'a A>,
inner: BaseIter<A>,
_life: PhantomData<&'a A>,
}

impl<'a, A> ElementsBase<'a, A> {
pub fn new(v: ContainerView<'a, A>) -> Self {
ElementsBase {
inner: v.into_base_iter(),
life: PhantomData,
_life: PhantomData,
}
}
}
Expand Down Expand Up @@ -72,7 +72,7 @@ impl<'a, A> ExactSizeIterator for ElementsBase<'a, A> {
/// Iterator element type is `&'a mut A`.
#[derive(Debug)]
pub struct ElementsBaseMut<'a, A> {
inner: Baseiter<A>,
inner: BaseIter<A>,
life: PhantomData<&'a mut A>,
}

Expand Down Expand Up @@ -128,29 +128,29 @@ impl<'a, A> ExactSizeIterator for ElementsBaseMut<'a, A> {
///
/// Iterator element type is `*mut A`.
#[derive(Debug)]
pub struct Baseiter<A> {
pub struct BaseIter<A> {
ptr: *mut A,
dim: Shape,
shape: Shape,
strides: Stride,
index: Option<Vec<usize>>,
}

impl<A> Baseiter<A> {
impl<A> BaseIter<A> {
/// Creating a Baseiter is unsafe because shape and stride parameters need
/// to be correct to avoid performing an unsafe pointer offset while
/// iterating.
#[inline]
pub unsafe fn new(ptr: *mut A, len: Shape, stride: Stride) -> Baseiter<A> {
Baseiter {
pub unsafe fn new(ptr: *mut A, shape: Shape, strides: Stride) -> BaseIter<A> {
BaseIter {
ptr,
index: len.first_index(),
dim: len,
strides: stride,
index: shape.first_index(),
shape,
strides,
}
}
}

impl<A> Iterator for Baseiter<A> {
impl<A> Iterator for BaseIter<A> {
type Item = *mut A;

#[inline]
Expand All @@ -160,37 +160,37 @@ impl<A> Iterator for Baseiter<A> {
Some(ref ix) => ix.clone(),
};
let offset = Shape::stride_offset(&index, &self.strides);
self.index = self.dim.next_for(index);
self.index = self.shape.next_for(index);
unsafe { Some(self.ptr.offset(offset)) }
}
}

impl<A> ExactSizeIterator for Baseiter<A> {
impl<A> ExactSizeIterator for BaseIter<A> {
fn len(&self) -> usize {
match self.index {
None => 0,
Some(ref ix) => {
let gone = crate::default_strides(&self.dim)
let gone = crate::default_strides(&self.shape)
.as_slice()
.iter()
.zip(ix.as_slice().iter())
.fold(0, |s, (&a, &b)| s + a * b);
self.dim.size() - gone
self.shape.size() - gone
}
}
}
}

impl<A> DoubleEndedIterator for Baseiter<A> {
impl<A> DoubleEndedIterator for BaseIter<A> {
#[inline]
fn next_back(&mut self) -> Option<*mut A> {
let index = match self.index.as_ref() {
None => return None,
Some(ix) => ix.clone(),
};
self.dim[0] -= 1;
let offset = Shape::stride_offset(&self.dim, &self.strides);
if index == self.dim {
self.shape[0] -= 1;
let offset = Shape::stride_offset(&self.shape, &self.strides);
if index == self.shape {
self.index = None;
}

Expand Down
Loading