Skip to content

Commit 38c1026

Browse files
authored
Make tensors generic on their value type (#17)
- Tensors, reductions and printing are generic on the value type, which defaults to `f32`, so existing code works unchanged - `LeftComposition` can change the value type, e.g. a comparison turns `f32` into `bool` - Reductions are defined for `f32`, `f64` and `i64`, and `where_` takes a `bool` condition - `square`, `negate`, `scale`, `clamp` and the functions that only move indices are generic, and `pow` is removed - `A` and `B` name value types, `U` and `V` tensor types
1 parent a307be8 commit 38c1026

10 files changed

Lines changed: 344 additions & 171 deletions

File tree

‎src/display.rs‎

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
//! render the same way, by walking a shape.
44
55
use std::fmt;
6-
use std::fmt::Write as _;
6+
use std::fmt::{Display, Write as _};
77

88
use crate::domain::HRect;
99
use crate::mapping::{BoxedMapping, BoxedPowersetMapping};
@@ -13,41 +13,43 @@ use crate::tensor::{
1313

1414
/// A tensor whose domain is a hrect. Only these can be printed, since formatting
1515
/// walks a shape and visits every index of it.
16-
pub trait BoxedTensor: Tensor {
16+
pub trait BoxedTensor<A = f32>: Tensor<A> {
1717
fn hrect(&self) -> &HRect;
1818
}
1919

2020
/// Renders a boxed tensor. Every `Display` implementation below defers to this,
2121
/// and each is written for the boxed instantiation of its tensor only.
22-
pub fn format_boxed(tensor: &dyn BoxedTensor) -> String {
22+
pub fn format_boxed<A: Display>(tensor: &dyn BoxedTensor<A>) -> String {
2323
format_tensor(tensor.hrect().shape(), &|index| tensor.get(index))
2424
}
2525

26-
impl fmt::Display for Physical {
26+
impl<A: Clone + Display> Display for Physical<A> {
2727
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2828
f.write_str(&format_boxed(self))
2929
}
3030
}
3131

32-
impl<M: BoxedMapping + ?Sized> fmt::Display for RightComposition<M> {
32+
impl<M: BoxedMapping + ?Sized, A: Display> Display for RightComposition<M, A> {
3333
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3434
f.write_str(&format_boxed(self))
3535
}
3636
}
3737

38-
impl<T: BoxedTensor + ?Sized> fmt::Display for LeftComposition<T> {
38+
impl<U: BoxedTensor<A> + ?Sized, A, B: Display> Display for LeftComposition<U, A, B> {
3939
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4040
f.write_str(&format_boxed(self))
4141
}
4242
}
4343

44-
impl<R: Reduction, M: BoxedPowersetMapping + ?Sized> fmt::Display for ReductionTensor<R, M> {
44+
impl<R: Reduction<A>, M: BoxedPowersetMapping + ?Sized, A: Display> Display
45+
for ReductionTensor<R, M, A>
46+
{
4547
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4648
f.write_str(&format_boxed(self))
4749
}
4850
}
4951

50-
fn format_tensor(shape: &[usize], accessor: &dyn Fn(&[usize]) -> f32) -> String {
52+
fn format_tensor<A: Display>(shape: &[usize], accessor: &dyn Fn(&[usize]) -> A) -> String {
5153
if shape.is_empty() {
5254
return format!("tensor({})", accessor(&[]));
5355
}
@@ -70,11 +72,11 @@ fn format_tensor(shape: &[usize], accessor: &dyn Fn(&[usize]) -> f32) -> String
7072
out
7173
}
7274

73-
fn max_width(
75+
fn max_width<A: Display>(
7476
shape: &[usize],
7577
index: &mut [usize],
7678
dim: usize,
77-
accessor: &dyn Fn(&[usize]) -> f32,
79+
accessor: &dyn Fn(&[usize]) -> A,
7880
) -> usize {
7981
let mut width = 0;
8082
for i in 0..shape[dim] {
@@ -88,14 +90,14 @@ fn max_width(
8890
width
8991
}
9092

91-
fn format_nested(
93+
fn format_nested<A: Display>(
9294
out: &mut String,
9395
shape: &[usize],
9496
index: &mut [usize],
9597
dim: usize,
9698
indent: &str,
9799
width: usize,
98-
accessor: &dyn Fn(&[usize]) -> f32,
100+
accessor: &dyn Fn(&[usize]) -> A,
99101
) {
100102
let innermost = dim == shape.len() - 1;
101103
out.push('[');

‎src/functions.rs‎

Lines changed: 106 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
//! machinery of its own.
44
55
use std::assert_eq;
6+
use std::fmt::Display;
7+
use std::ops::{Mul, Neg};
68
use std::rc::Rc;
79

810
use crate::display::BoxedTensor;
@@ -12,48 +14,65 @@ use crate::mapping::{
1214
Squeeze, Unsqueeze, Where,
1315
};
1416
use crate::tensor::{
15-
JaggedTensor, LeftComposition, Physical, Product, Reduction, ReductionTensor, RightComposition,
16-
Sum, Tensor,
17+
JaggedTensor, LeftComposition, Physical, Product, ProductReduction, Reduction, ReductionTensor,
18+
RightComposition, Sum, SumReduction, Tensor,
1719
};
1820

19-
pub fn square<T: Tensor + ?Sized>(u: Rc<T>) -> LeftComposition<T> {
21+
pub fn square<A: Mul<Output = A> + Copy + 'static, U: Tensor<A> + ?Sized>(
22+
u: Rc<U>,
23+
) -> LeftComposition<U, A> {
2024
LeftComposition::new(u, |x| x * x)
2125
}
2226

23-
pub fn negate<T: Tensor + ?Sized>(u: Rc<T>) -> LeftComposition<T> {
27+
pub fn negate<A: Neg<Output = A> + 'static, U: Tensor<A> + ?Sized>(
28+
u: Rc<U>,
29+
) -> LeftComposition<U, A> {
2430
LeftComposition::new(u, |x| -x)
2531
}
2632

27-
pub fn scale<T: Tensor + ?Sized>(u: Rc<T>, factor: f32) -> LeftComposition<T> {
33+
pub fn scale<A: Mul<Output = A> + Copy + 'static, U: Tensor<A> + ?Sized>(
34+
u: Rc<U>,
35+
factor: A,
36+
) -> LeftComposition<U, A> {
2837
LeftComposition::new(u, move |x| x * factor)
2938
}
3039

31-
pub fn pow<T: Tensor + ?Sized>(u: Rc<T>, exponent: f32) -> LeftComposition<T> {
32-
LeftComposition::new(u, move |x| x.powf(exponent))
33-
}
34-
35-
/// Checking the bounds here rather than leaving it to `f32::clamp` reports the
36-
/// mistake where it is made, not at the first read, and rules out the NaN
37-
/// bounds that would panic there too.
38-
pub fn clamp<T: Tensor + ?Sized>(u: Rc<T>, low: f32, high: f32) -> LeftComposition<T> {
40+
/// Holds values between `low` and `high`. Checking the bounds here reports the
41+
/// mistake where it is made, not at the first read, and rules out NaN bounds,
42+
/// which nothing would be below or above.
43+
pub fn clamp<A: PartialOrd + Copy + Display + 'static, U: Tensor<A> + ?Sized>(
44+
u: Rc<U>,
45+
low: A,
46+
high: A,
47+
) -> LeftComposition<U, A> {
3948
assert!(low <= high, "clamp needs low <= high, got {low} and {high}");
40-
LeftComposition::new(u, move |x| x.clamp(low, high))
49+
LeftComposition::new(u, move |x| {
50+
if x < low {
51+
low
52+
} else if x > high {
53+
high
54+
} else {
55+
x
56+
}
57+
})
4158
}
4259

4360
/// Reorders the axes of a tensor: `axes[i]` is the axis of `u` that becomes
4461
/// axis `i` of the result.
45-
pub fn permute<T: BoxedTensor + 'static>(
46-
u: Rc<T>,
62+
pub fn permute<A: 'static, U: BoxedTensor<A> + 'static>(
63+
u: Rc<U>,
4764
axes: Vec<usize>,
48-
) -> RightComposition<Permutation> {
65+
) -> RightComposition<Permutation, A> {
4966
let codomain = u.hrect().clone();
5067
RightComposition::new(u, Rc::new(Permutation::new(codomain, axes)))
5168
}
5269

5370
/// Swaps the last two axes and leaves any leading ones alone, so a stack of
5471
/// matrices transposes matrix by matrix. At rank two this is the plain
5572
/// transpose.
56-
pub fn transpose<T: BoxedTensor + 'static>(u: Rc<T>) -> RightComposition<Permutation> {
73+
pub fn transpose<A: 'static, U: BoxedTensor<A> + 'static>(
74+
u: Rc<U>,
75+
) -> RightComposition<Permutation, A> {
5776
let ndim = u.domain().ndim();
5877
assert!(ndim >= 2, "transpose needs at least two dimensions");
5978
let mut axes: Vec<usize> = (0..ndim).collect();
@@ -63,11 +82,11 @@ pub fn transpose<T: BoxedTensor + 'static>(u: Rc<T>) -> RightComposition<Permuta
6382

6483
/// Moves the axis at `source` to `destination`; the axes left over keep their
6584
/// relative order.
66-
pub fn movedim<T: BoxedTensor + 'static>(
67-
u: Rc<T>,
85+
pub fn movedim<A: 'static, U: BoxedTensor<A> + 'static>(
86+
u: Rc<U>,
6887
source: usize,
6988
destination: usize,
70-
) -> RightComposition<Permutation> {
89+
) -> RightComposition<Permutation, A> {
7190
let ndim = u.domain().ndim();
7291
assert!(source < ndim, "source axis {source} is out of range");
7392
assert!(
@@ -82,7 +101,10 @@ pub fn movedim<T: BoxedTensor + 'static>(
82101

83102
/// Inserts an axis of extent 1 at `dim`, which can be anywhere from before the
84103
/// first axis to after the last.
85-
pub fn unsqueeze<T: BoxedTensor + 'static>(u: Rc<T>, dim: usize) -> RightComposition<Unsqueeze> {
104+
pub fn unsqueeze<A: 'static, U: BoxedTensor<A> + 'static>(
105+
u: Rc<U>,
106+
dim: usize,
107+
) -> RightComposition<Unsqueeze, A> {
86108
let codomain = u.hrect().clone();
87109
RightComposition::new(u, Rc::new(Unsqueeze::new(codomain, dim)))
88110
}
@@ -127,7 +149,10 @@ impl Dims for &[usize] {
127149
/// Drops axes of extent 1, as torch's `squeeze` does: `squeeze(u, ())` drops all
128150
/// of them, `squeeze(u, 1)` only axis 1, and `squeeze(u, [0, 2])` axes 0 and 2.
129151
/// A named axis whose extent isn't 1 is left alone.
130-
pub fn squeeze<T: BoxedTensor + 'static>(u: Rc<T>, dims: impl Dims) -> RightComposition<Squeeze> {
152+
pub fn squeeze<A: 'static, U: BoxedTensor<A> + 'static>(
153+
u: Rc<U>,
154+
dims: impl Dims,
155+
) -> RightComposition<Squeeze, A> {
131156
let codomain = u.hrect().clone();
132157
let ndim = codomain.shape().len();
133158
let named = dims.axes(ndim);
@@ -146,7 +171,10 @@ pub fn squeeze<T: BoxedTensor + 'static>(u: Rc<T>, dims: impl Dims) -> RightComp
146171
}
147172

148173
/// Joins tensors end to end along `dim`; their other extents must agree.
149-
pub fn concatenate(tensors: Vec<Rc<dyn BoxedTensor>>, dim: usize) -> RightComposition<Concat> {
174+
pub fn concatenate<A: 'static>(
175+
tensors: Vec<Rc<dyn BoxedTensor<A>>>,
176+
dim: usize,
177+
) -> RightComposition<Concat, A> {
150178
assert!(!tensors.is_empty(), "concatenate needs at least one tensor");
151179
let underlying = JaggedTensor::new(tensors);
152180
let codomain = underlying.jagged_domain().clone();
@@ -155,7 +183,10 @@ pub fn concatenate(tensors: Vec<Rc<dyn BoxedTensor>>, dim: usize) -> RightCompos
155183

156184
/// Joins tensors of one shape along a new axis at `dim`, by concatenating them
157185
/// once each has an axis of extent 1 there.
158-
pub fn stack(tensors: Vec<Rc<dyn BoxedTensor>>, dim: usize) -> RightComposition<Concat> {
186+
pub fn stack<A: 'static>(
187+
tensors: Vec<Rc<dyn BoxedTensor<A>>>,
188+
dim: usize,
189+
) -> RightComposition<Concat, A> {
159190
assert!(!tensors.is_empty(), "stack needs at least one tensor");
160191
let shape = tensors[0].hrect().clone();
161192
assert!(
@@ -166,20 +197,19 @@ pub fn stack(tensors: Vec<Rc<dyn BoxedTensor>>, dim: usize) -> RightComposition<
166197
.into_iter()
167198
.map(|tensor| {
168199
let unsqueeze = Unsqueeze::new(tensor.hrect().clone(), dim);
169-
Rc::new(RightComposition::new(tensor, Rc::new(unsqueeze))) as Rc<dyn BoxedTensor>
200+
Rc::new(RightComposition::new(tensor, Rc::new(unsqueeze))) as Rc<dyn BoxedTensor<A>>
170201
})
171202
.collect();
172203
concatenate(unsqueezed, dim)
173204
}
174205

175-
/// Reads `input` where `condition` is not zero and `other` where it is. torch's
176-
/// `where` takes a boolean condition; cten's tensors hold floats, so zero stands
177-
/// for false. `where` is a Rust keyword, hence the underscore.
178-
pub fn where_(
179-
condition: Rc<dyn BoxedTensor>,
180-
input: Rc<dyn BoxedTensor>,
181-
other: Rc<dyn BoxedTensor>,
182-
) -> RightComposition<Where> {
206+
/// Reads `input` where `condition` holds and `other` where it does not, as
207+
/// torch's `where` does. `where` is a Rust keyword, hence the underscore.
208+
pub fn where_<A: 'static>(
209+
condition: Rc<dyn BoxedTensor<bool>>,
210+
input: Rc<dyn BoxedTensor<A>>,
211+
other: Rc<dyn BoxedTensor<A>>,
212+
) -> RightComposition<Where, A> {
183213
let underlying = JaggedTensor::new(vec![input, other]);
184214
let codomain = underlying.jagged_domain().clone();
185215
RightComposition::new(
@@ -191,7 +221,13 @@ pub fn where_(
191221
/// Spreads a vector over the diagonal of a tensor of the given rank: rank two
192222
/// gives a diagonal matrix, rank three a tensor whose only non-zero indices
193223
/// are of the form `[i, i, i]`.
194-
pub fn diagonalize<T: BoxedTensor + 'static>(u: Rc<T>, rank: usize) -> Sum<Diagonal> {
224+
pub fn diagonalize<A: 'static, U: BoxedTensor<A> + 'static>(
225+
u: Rc<U>,
226+
rank: usize,
227+
) -> Sum<Diagonal, A>
228+
where
229+
SumReduction: Reduction<A>,
230+
{
195231
assert_eq!(u.domain().ndim(), 1, "diagonalize takes a vector");
196232
assert!(rank > 0, "a diagonal tensor has at least one dimension");
197233
let extent = u.hrect().shape()[0];
@@ -200,7 +236,7 @@ pub fn diagonalize<T: BoxedTensor + 'static>(u: Rc<T>, rank: usize) -> Sum<Diago
200236

201237
/// Reducing over the empty set gives the reduction's neutral element at every
202238
/// index, so a constant tensor needs no underlying data at all.
203-
fn neutral<R: Reduction>(shape: Vec<usize>) -> ReductionTensor<R, EmptyMapping> {
239+
fn neutral<R: Reduction<f32>>(shape: Vec<usize>) -> ReductionTensor<R, EmptyMapping> {
204240
let mapping = EmptyMapping::new(HRect::new(shape), HRect::new(vec![0]));
205241
ReductionTensor::new(Rc::new(Physical::new(vec![])), Rc::new(mapping))
206242
}
@@ -231,11 +267,14 @@ pub fn eye(n: usize) -> Sum<Diagonal> {
231267
/// `indices`, and zero everywhere else. As in torch, `indices` has one row per
232268
/// dimension, so column `k` is the coordinate of `values[k]`, and values at a
233269
/// repeated coordinate add up.
234-
pub fn sparse_coo_tensor(
270+
pub fn sparse_coo_tensor<A: 'static>(
235271
indices: Vec<Vec<usize>>,
236-
values: Rc<dyn BoxedTensor>,
272+
values: Rc<dyn BoxedTensor<A>>,
237273
size: Vec<usize>,
238-
) -> Sum<COO> {
274+
) -> Sum<COO, A>
275+
where
276+
SumReduction: Reduction<A>,
277+
{
239278
assert_eq!(
240279
indices.len(),
241280
size.len(),
@@ -273,30 +312,49 @@ pub fn sparse_coo_tensor(
273312
/// `physical` sits at `basis·x + offset`, and the tensor is zero off that
274313
/// lattice. `basis` has a row per dimension of `shape` and a column per
275314
/// dimension of `physical`. Values the lattice sends to one index add up.
276-
pub fn sparse_latticed_tensor<T: BoxedTensor + 'static>(
277-
physical: Rc<T>,
315+
pub fn sparse_latticed_tensor<A: 'static, U: BoxedTensor<A> + 'static>(
316+
physical: Rc<U>,
278317
basis: Vec<Vec<i64>>,
279318
offset: Vec<i64>,
280319
shape: Vec<usize>,
281-
) -> Sum<InvAffine> {
320+
) -> Sum<InvAffine, A>
321+
where
322+
SumReduction: Reduction<A>,
323+
{
282324
let affine = Affine::new(physical.hrect().clone(), basis, offset, HRect::new(shape));
283325
Sum::new(physical, Rc::new(InvAffine::new(affine)))
284326
}
285327

286-
pub fn sum<T: BoxedTensor + 'static>(input: Rc<T>, dim: usize) -> Sum<InvProjection> {
328+
pub fn sum<A: 'static, U: BoxedTensor<A> + 'static>(
329+
input: Rc<U>,
330+
dim: usize,
331+
) -> Sum<InvProjection, A>
332+
where
333+
SumReduction: Reduction<A>,
334+
{
287335
let codomain = input.hrect().clone();
288336
Sum::new(input, Rc::new(InvProjection::new(codomain, dim)))
289337
}
290338

291-
pub fn prod<T: BoxedTensor + 'static>(input: Rc<T>, dim: usize) -> Product<InvProjection> {
339+
pub fn prod<A: 'static, U: BoxedTensor<A> + 'static>(
340+
input: Rc<U>,
341+
dim: usize,
342+
) -> Product<InvProjection, A>
343+
where
344+
ProductReduction: Reduction<A>,
345+
{
292346
let codomain = input.hrect().clone();
293347
Product::new(input, Rc::new(InvProjection::new(codomain, dim)))
294348
}
295349

296-
pub fn mm<T1: BoxedTensor + 'static, T2: BoxedTensor + 'static>(
297-
mat1: Rc<T1>,
298-
mat2: Rc<T2>,
299-
) -> Sum<InvProjection> {
350+
pub fn mm<A: 'static, U: BoxedTensor<A> + 'static, V: BoxedTensor<A> + 'static>(
351+
mat1: Rc<U>,
352+
mat2: Rc<V>,
353+
) -> Sum<InvProjection, A>
354+
where
355+
SumReduction: Reduction<A>,
356+
ProductReduction: Reduction<A>,
357+
{
300358
assert_eq!(mat1.hrect().shape().len(), 2, "mat1 must be a matrix");
301359
assert_eq!(mat2.hrect().shape().len(), 2, "mat2 must be a matrix");
302360
assert_eq!(

‎src/lib.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@ pub mod tensor;
1212
pub use display::{BoxedTensor, format_boxed};
1313
pub use domain::{Domain, HRect, JaggedDomain};
1414
pub use functions::{
15-
Dims, clamp, concatenate, diagonalize, eye, eye_rect, mm, movedim, negate, ones, permute, pow,
16-
prod, scale, sparse_coo_tensor, sparse_latticed_tensor, square, squeeze, stack, sum, transpose,
15+
Dims, clamp, concatenate, diagonalize, eye, eye_rect, mm, movedim, negate, ones, permute, prod,
16+
scale, sparse_coo_tensor, sparse_latticed_tensor, square, squeeze, stack, sum, transpose,
1717
unsqueeze, where_, zeros,
1818
};
1919
pub use mapping::{

0 commit comments

Comments
 (0)