pub type TensorIterator<'a, Scalar, const MAX_RANK: usize = DEFAULT_MAX_RANK> = TensorViewIterator<'a, Scalar, MAX_RANK>; The container model is unusual enough that it needs direct documentation.
Vector<T>owns one-dimensional storage.VectorView<'a, T>is an immutable borrowed view.VectorSpan<'a, T>is a mutable borrowed view.Tensor<T, A, MAX_RANK>owns N-dimensional storage and can use a custom allocator.TensorViewandTensorSpanare the borrowed forms.Matrix<T>is a rank-2 alias overTensor<T, _, 2>.
The allocator story is explicit. Tensor and DotsPackedMatrix are generic over core::alloc::Allocator and default to numkong::Global, which forwards to the system heap.
Views and spans borrow their owner’s allocator, and every allocating operation, like view.sin() or view.dots_packed(&packed), allocates its result through a clone of its first operand’s allocator.
An arena that is not Clone works by reference, as &Arena, and views over foreign memory report Global.
Owned allocations start on DEFAULT_ALIGNMENT, the C library’s boundary: 128 bytes on Arm and x86, 64 on WASM, 256 on IBM Z.
That does not mean callers must align their source buffers manually.
It means owned outputs and packed payloads are allocated in a SIMD-friendly way when the crate owns them.
Owned containers are fixed-capacity resizable. capacity() reports the allocated storage-value ceiling. resize() reshapes within that ceiling without moving storage, so an outstanding as_slice/view/span is never invalidated — the borrow checker rejects a &mut self resize while any borrow is alive, so this is enforced at compile time. reserve() is the explicit opt-in that may reallocate and move storage to grow, and clear() empties the logical shape while keeping capacity. ScaledTensor resizes its packed elements and per-block scales in lockstep.
use numkong::{RangeStep, SliceRange, Tensor};
let t = Tensor::<f32>::from_slice(&[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0], &[3, 3]).unwrap();
let col = t.slice((.., 1_usize)).unwrap(); // t[:, 1] — column 1
let rows = t.slice((0..2_usize, ..)).unwrap(); // t[0:2, :] — first two rows
let tail = t.slice((-2_isize.., ..)).unwrap(); // t[-2:, :] — last two rows
let neg = t.slice((.., -2..-1_isize)).unwrap(); // t[:, -2:-1]
let step = t.slice((.., RangeStep::new(0, 3, 2))).unwrap(); // t[:, ::2]
// Explicit &[SliceRange] syntax also works
let col = t.slice(&[SliceRange::full(), SliceRange::index(1)]).unwrap();Tuple elements implement SliceArg — each monomorphized with zero runtime dispatch:
| Rust syntax | Meaning |
|---|---|
.. | all |
0_usize / -1_isize | single index (negative wraps from end) |
1..4_usize / -3..-1_isize | half-open range |
..3_usize / ..-1_isize | from start |
1_usize.. / -2_isize.. | to end |
0..=2_usize / -3..=-1_isize | inclusive range |
RangeStep::new(0, 6, 2) | stepped (no Rust literal) |
Integer literals default to i32 — use _usize / _isize suffixes.
Negative isize values wrap from the dimension end, like Python.
Iteration works at the logical-dimension level.
For sub-byte types like i4x2, iteration yields one item per dimension, so a 6-dimension vector stored in 3 bytes yields 6 items.
Immutable iterators (iter()) yield DimRef<T>, which dereferences to T::DimScalar.
Mutable iterators (iter_mut()) yield DimMut<T>, which writes back on drop — the only way to mutate individual nibbles or bits.
use numkong::{Vector, i4x2};
let mut nibbles = Vector::<i4x2>::zeros(4).unwrap();
for (i, mut dim) in nibbles.iter_mut().enumerate() {
*dim = i as i8;
}
assert_eq!(nibbles.get(0_usize).unwrap(), 0);
assert_eq!(nibbles.get(3_usize).unwrap(), 3);Vectors and tensors can be converted between each other without copying:
use numkong::{Vector, Tensor};
let v = Vector::<f32>::from_scalars(&[1.0, 2.0, 3.0]).unwrap();
let t: Tensor<f32, _, 8> = v.into_tensor().unwrap();
assert_eq!(t.shape(), &[3]);
let v2 = t.into_vector().unwrap();
assert_eq!(v2.dims(), 3);The main layout rules are:
- General slicing and transposition are supported by views.
- Elementwise and many reduction kernels accept strided views.
- Matrix-style kernels require rank-2 inputs with contiguous rows.
- A tensor can be non-contiguous overall and still have contiguous rows.
- Some reductions have SIMD kernels for strided lanes.
- Some backends still fall back depending on alignment and dtype.
Sub-byte types (i4x2, u4x2, u1x8) use logical shapes.
A shape of [8] for i4x2 means 8 nibbles (stored in 4 bytes), not 8 bytes.
The innermost extent counts dimensions, a multiple of the values per byte: 2 for nibble types, 8 for bit types.
Transpose and reshape are not supported for sub-byte types — they return SubByteUnsupported.
API
Types
TensorIteratorBackward-compatible alias for TensorViewIterator.
TensorDimsBackward-compatible alias for TensorViewDims.
pub type TensorDims<'a, Scalar, const MAX_RANK: usize = DEFAULT_MAX_RANK> = TensorViewDims<'a, Scalar, MAX_RANK>; TensorValuesBackward-compatible alias for TensorViewDims.
pub type TensorValues<'a, Scalar, const MAX_RANK: usize = DEFAULT_MAX_RANK> = TensorViewDims<'a, Scalar, MAX_RANK>; MatrixType alias for a 2D matrix — a Tensor with MAX_RANK=2.
pub type Matrix<Scalar, Alloc = Global> = Tensor<Scalar, Alloc, 2>; MatrixViewType alias for an immutable 2D matrix view.
pub type MatrixView<'a, Scalar, Alloc = Global> = TensorView<'a, Scalar, 2, Alloc>; MatrixSpanType alias for a mutable 2D matrix view.
pub type MatrixSpan<'a, Scalar, Alloc = Global> = TensorSpan<'a, Scalar, 2, Alloc>; VectorIteratorBackward-compatible alias for VectorViewIterator.
pub type VectorIterator<'a, Scalar> = VectorViewIterator<'a, Scalar>; StructDimMutMutable proxy for a single logical dimension within a packed storage value.1
pub struct DimMut<'a, Scalar: FloatConvertible> On Drop, performs a read-modify-write: reads the current storage value, overwrites the
sub-dimension at sub_index, and writes back.
For normal types (dimensions_per_value() == 1), this is equivalent to &mut Scalar.
For sub-byte types, this enables modifying individual nibbles/bits.
Aliasing
In a standard for loop each proxy is dropped before the next is created; holding multiple
proxies to sub-dimensions of the same storage value simultaneously is safe but uses
last-writer-wins semantics.
Implements
Deref, DerefMut, Drop, Debug, DisplaynewCreate a new mutable dimension proxy.
pub unsafe fn new(ptr: *mut Scalar, sub_index: usize, value: Scalar::DimScalar) -> Self Safety
ptr must be valid for reads and writes for the duration of 'a.
StructDimRefImmutable proxy for a single logical dimension within a packed storage value.1
pub struct DimRef<'a, Scalar: FloatConvertible> For normal types this is equivalent to a Scalar::DimScalar copy.
For sub-byte types it represents one unpacked dimension from a packed value.
The lifetime ensures the proxy does not outlive the container it came from.
Implements
Copy, Clone, Deref, PartialEq, PartialOrd, Debug, DisplaynewCreate a new immutable dimension proxy.
pub fn new(value: Scalar::DimScalar) -> Self StructAxisIteratorIterator over sub-tensor views along a given axis.
pub struct AxisIterator<'a, Scalar, const MAX_RANK: usize = DEFAULT_MAX_RANK, Alloc = Global> Each item is a TensorView with the iterated dimension removed, leaving rank minus one. For a
rank-2 matrix, axis_views(0) yields row views.
Implements
Iterator, ExactSizeIterator, FusedIteratorStructAxisIteratorMutMutable iterator over sub-tensor spans along a given axis.
pub struct AxisIteratorMut<'a, Scalar, const MAX_RANK: usize = DEFAULT_MAX_RANK, Alloc = Global> Each item is a TensorSpan with the iterated dimension removed, leaving rank minus one. For a
rank-2 matrix, axis_spans(0) yields mutable row spans.
Implements
Iterator, ExactSizeIterator, FusedIteratorTraitCopyFromCopy storage from a Source into this container in place.1
pub trait CopyFrom<Source> Source is the natural read-side counterpart for the implementor:
&[Scalar], the raw storage slice, for an owning Tensor or Vector, or the matching View
type for span implementors, mirroring tensor_span::copy_from and vector_span::copy_from on
the C++ side.
Implementors
impl<Scalar: StorageElement, Alloc: Allocator, const MAX_RANK: usize> CopyFrom<&[Scalar]> for Tensor<Scalar, Alloc, MAX_RANK>impl<'a, 'b, Scalar: StorageElement, const MAX_RANK: usize, Alloc: Allocator, SourceAlloc: Allocator> CopyFrom<&'b TensorView<'_, Scalar, MAX_RANK, SourceAlloc>> for TensorSpan<'a, Scalar, MAX_RANK, Alloc>impl<Scalar: StorageElement, Alloc: Allocator> CopyFrom<&[Scalar]> for Vector<Scalar, Alloc>impl<'a, 'b, Scalar: StorageElement, Alloc: Allocator, SourceAlloc: Allocator> CopyFrom<&'b VectorView<'_, Scalar, SourceAlloc>> for VectorSpan<'a, Scalar, Alloc>
copy_*_from× 7Copy from source into self.
fn copy__from(&mut self, source: Source) -> Result<(), Error> Returns an error on a shape or storage mismatch and does not modify the destination on error.
TraitFillIn-place fill operations shared by every mutable container of Scalar.2
pub trait Fill<Scalar: StorageElement> Implemented for Tensor, TensorSpan, crate::vector::Vector, and
crate::vector::VectorSpan. Mirrors tensor_span::fill_zeros / fill and
vector_span::fill_zeros / fill from the C++ side. Both methods are infallible and operate on
every storage byte the container owns or borrows.
Implementors
impl<Scalar: StorageElement, Alloc: Allocator, const MAX_RANK: usize> Fill<Scalar> for Tensor<Scalar, Alloc, MAX_RANK>impl<'a, Scalar: StorageElement, const MAX_RANK: usize, Alloc: Allocator> Fill<Scalar> for TensorSpan<'a, Scalar, MAX_RANK, Alloc>impl<Scalar: StorageElement, Alloc: Allocator> Fill<Scalar> for Vector<Scalar, Alloc>impl<'a, Scalar: StorageElement, Alloc: Allocator> Fill<Scalar> for VectorSpan<'a, Scalar, Alloc>
fill_*_zeros× 5Set every storage byte to zero.
fn fill__zeros(&mut self) Works for every StorageElement since the binary-zero of
all NumKong scalar dtypes is the value-zero.
*× 5Set every storage element to value.
fn fill(&mut self, value: Scalar) For 1-byte storage, including sub-byte packings, this becomes a single byte-pattern memset; for multi-byte storage it falls through to a typed broadcast loop on the pre-zeroed buffer, so float NaN/inf patterns from uninitialised memory cannot leak through.
StructRangeStepA stepped range for use in tuple-based slicing — compile-time dispatch.2
pub struct RangeStep Rust has no built-in literal for stepped ranges, so this struct fills that gap. Use it inside
.slice() tuples:
t.slice((.., RangeStep::new(0, 6, 2))).unwrap(); // t[:, 0:6:2]
Fields
start | usize | First index, inclusive. |
|---|---|---|
end | usize | Last index, exclusive. |
step | isize | Distance between consecutive indices. |
Implements
newBuilds a stepped range from its bounds and step.
pub fn new(start: usize, end: usize, step: isize) -> Self *× 2Applies this argument to one dimension, appending its shape and stride and moving the offset.
Inherited from SliceArg
fn apply(
self,
dim_size: usize,
dim_stride: isize,
out_shape: &mut [usize],
out_strides: &mut [isize],
new_ndim: &mut usize,
offset: &mut isize,
) -> Result<(), Error> StructScaledTensorAn owning block-scaled tensor: two composed Tensors plus an optional per-tensor scale.11
pub struct ScaledTensor<F: BlockScaledFormat, A: Allocator = Global> A block-scaled tensor stores quantized values in blocks along its last axis. It is exactly:
elements: aTensor<F::Element>of logical shape(rows, columns), sub-byte packed for FP4 formats, andblock_scales: aTensor<F::Scale>of shape(rows, columns / F::BLOCK_SIZE)— one scale byte per block, andtensor_scale: anOption<f32>per-tensor multiplier (Somefor NVFP4,Nonefor MX).
This composes the existing tensor family rather than introducing a parallel hierarchy; the scale
newtypes (crate::Ue4m3 / crate::Ue8m0) and the packed element scalars are plain
StorageElements. Construct one with dense.view().cast_to_scaled::<F>() and decode it back
with scaled.view().cast::<f32>().
Implements
Debugfrom_partsAssemble a block-scaled tensor from its two component tensors and an optional scale.
pub fn from_parts(
elements: Tensor<F::Element, A>,
block_scales: Tensor<F::Scale, A>,
tensor_scale: Option<f32>,
) -> Result<Self, Error> The cast verbs in crate::cast are the usual way to build these; this constructor is
public so callers holding pre-quantized buffers can wrap them without a re-encode.
Both parts must agree, because nothing downstream re-checks them: decoding derives the scale
count from the elements shape alone and hands the scales pointer to the kernel, so a
block_scales shorter than that shape is read past its end. Whether a per-tensor multiplier
exists at all is fixed by the format rather than the caller, so a mismatch there is rejected
too — its value, for the formats that have one, is genuine data.
*× 2Borrow the packed element values.
pub fn elements(&self) -> TensorView<'_, F::Element, DEFAULT_MAX_RANK, A> block_*_scales× 2Borrow the per-block scale bytes.
pub fn block__scales(&self) -> TensorView<'_, F::Scale, DEFAULT_MAX_RANK, A> tensor_*_scale× 3The per-tensor multiplier (Some for NVFP4, None for the MX family).
pub fn tensor__scale(&self) -> Option<f32> shapeLogical (rows, columns) shape of the elements tensor.
pub fn shape(&self) -> &[usize] viewBorrow the whole tensor as a ScaledTensorView.
pub fn view(&self) -> ScaledTensorView<'_, F, A> spanBorrow the whole tensor mutably as a ScaledTensorSpan.
pub fn span(&mut self) -> ScaledTensorSpan<'_, F, A> capacityAllocated element-storage capacity of the packed elements buffer (F::Element slots) — the ceiling a coordinated resize honors.
pub fn capacity(&self) -> usize resizeResize the packed elements and the per-block scales in lockstep, moving neither buffer.
pub fn resize(&mut self, new_shape: &[usize]) -> Result<(), Error> Atomic: fails leaving both children unchanged if either would exceed its capacity — call
reserve first to grow.
reserveGrow both children's capacity to hold new_shape and its paired scales, reallocating if needed.
pub fn reserve(&mut self, new_shape: &[usize]) -> Result<(), Error> May move storage. A no-op when already large enough.
clearReset both children to empty while keeping their capacities.
pub fn clear(&mut self) StructScaledTensorSpanA borrowed, mutable view into a ScaledTensor — composed TensorSpans plus the scale.4
elementsMutably borrow the packed element values.
pub fn elements(&mut self) -> &mut TensorSpan<'a, F::Element, DEFAULT_MAX_RANK, A> block_scalesMutably borrow the per-block scale bytes.
pub fn block_scales(&mut self) -> &mut TensorSpan<'a, F::Scale, DEFAULT_MAX_RANK, A> shapeLogical shape of the packed elements.
pub fn shape(&self) -> &[usize] as_viewReborrow as a read-only ScaledTensorView.
pub fn as_view(&self) -> ScaledTensorView<'_, F, A> StructScaledTensorViewA borrowed, read-only view into a ScaledTensor — composed TensorViews plus the scale.5
pub struct ScaledTensorView<'a, F: BlockScaledFormat, A = Global> Implements
Debug, Clone, CopycastMaterialize this block-scaled view into a dense Tensor<T> of the same shape.
pub fn cast<T: Clone + CastDType>(&self) -> Result<Tensor<T, A>, Error> cast_to_scaledTranscode this block-scaled view into a different block-scaled format.
pub fn cast_to_scaled<G: BlockScaledFormat>(&self) -> Result<ScaledTensor<G, A>, Error> shapeLogical (rows, columns) shape.
pub fn shape(&self) -> &[usize] rowBorrow leading-axis index i as a new ScaledTensorView, slicing both sub-tensors in lockstep and keeping the rank, with the leading extent reduced to 1 rather than dropped.
pub fn row(&self, i: usize) -> Result<ScaledTensorView<'a, F, A>, Error> rowsSlice a contiguous leading-axis range start..end, slicing both sub-tensors in lockstep.
pub fn rows(&self, start: usize, end: usize) -> Result<ScaledTensorView<'a, F, A>, Error> TraitSliceArgProcesses one axis of a slice operation, directly computing the effect on output shape, strides, and byte offset — no intermediate enum dispatch.
pub trait SliceArg Each impl is monomorphized and fully inlined, so the compiler sees concrete types at every call site with zero runtime branching overhead.
Unsigned types: RangeFull, usize, Range<usize>, RangeTo<usize>, RangeFrom<usize>,
RangeInclusive<usize>.
Signed types (negative wraps from end): isize, Range<isize>, RangeTo<isize>,
RangeFrom<isize>, RangeInclusive<isize>.
Stepped: RangeStep — Rust has no built-in stepped range literal.
Note: integer literals default to i32, so write 0_usize not 0.
Implementors
impl SliceArg for RangeFullimpl SliceArg for usizeimpl SliceArg for isizeimpl SliceArg for Range<usize>impl SliceArg for Range<isize>impl SliceArg for RangeTo<usize>impl SliceArg for RangeTo<isize>impl SliceArg for RangeFrom<usize>impl SliceArg for RangeFrom<isize>impl SliceArg for RangeInclusive<usize>impl SliceArg for RangeInclusive<isize>impl SliceArg for RangeStep
EnumSliceRangeRepresents a range specification for slicing along one dimension.4
pub enum SliceRange Values
Full | Full range, equivalent to .. | |
|---|---|---|
Index | (usize) | Single index; reduces the dimension |
Range | { start: usize, end: usize } | Range from start to end exclusive, equivalent to start..end |
RangeStep | { start: usize, end: usize, step: isize } | Range from start to end with step, equivalent to start..end;step |
Implements
Debug, Clone, Copy, StructuralPartialEq, PartialEq, EqfullCreate a full range.
pub fn full() -> Self indexCreate a single index.
pub fn index(i: usize) -> Self rangeCreate a range from start to end.
pub fn range(start: usize, end: usize) -> Self range_stepCreate a range with step.
pub fn range_step(start: usize, end: usize, step: isize) -> Self TraitSliceSpecComputes the full slice layout from shape, strides, and ndim.1
pub trait SliceSpec Implemented for &[SliceRange] / &[SliceRange; N] — backward compat, runtime dispatch — and
tuples of SliceArg types from arity 1-8: compile-time dispatch, fully inlined with zero
branching overhead.
Implementors
impl SliceSpec for &[SliceRange]impl<const N: usize> SliceSpec for &[SliceRange; N]impl<Axis0: SliceArg> SliceSpec for (Axis0,)impl<Axis0: SliceArg, Axis1: SliceArg> SliceSpec for (Axis0, Axis1)impl<Axis0: SliceArg, Axis1: SliceArg, Axis2: SliceArg> SliceSpec for (Axis0, Axis1, Axis2)impl<Axis0: SliceArg, Axis1: SliceArg, Axis2: SliceArg, Axis3: SliceArg> SliceSpec for (Axis0, Axis1, Axis2, Axis3)impl<Axis0: SliceArg, Axis1: SliceArg, Axis2: SliceArg, Axis3: SliceArg, Axis4: SliceArg> SliceSpec for (Axis0, Axis1, Axis2, Axis3, Axis4)impl<Axis0: SliceArg, Axis1: SliceArg, Axis2: SliceArg, Axis3: SliceArg, Axis4: SliceArg, Axis5: SliceArg> SliceSpec for (Axis0, Axis1, Axis2, Axis3, Axis4, Axis5)impl<Axis0: SliceArg, Axis1: SliceArg, Axis2: SliceArg, Axis3: SliceArg, Axis4: SliceArg, Axis5: SliceArg, Axis6: SliceArg> SliceSpec for (Axis0, Axis1, Axis2, Axis3, Axis4, Axis5, Axis6)impl<Axis0: SliceArg, Axis1: SliceArg, Axis2: SliceArg, Axis3: SliceArg, Axis4: SliceArg, Axis5: SliceArg, Axis6: SliceArg, Axis7: SliceArg> SliceSpec for (Axis0, Axis1, Axis2, Axis3, Axis4, Axis5, Axis6, Axis7)
apply_layoutdims_per_value is the scalar's packing factor: on the innermost axis a range start counts logical dimensions while the stride spans a whole storage value, so the two must be reconciled here rather than by the caller.
fn apply_layout<const MAX_RANK: usize>(
self,
shape: &[usize; MAX_RANK],
strides: &[isize; MAX_RANK],
ndim: usize,
dims_per_value: usize,
) -> Result<([usize; MAX_RANK], [isize; MAX_RANK], usize, isize, usize), Error> StructTensorN-dimensional array with NumKong-accelerated operations.142
pub struct Tensor<Scalar: StorageElement, Alloc: Allocator = Global, const MAX_RANK: usize = DEFAULT_MAX_RANK> Uses raw memory allocation, not std::Vec, for maximum control.
Supports:
- Slicing and subviews, zero-copy
- Dot-product multiplication with
crate::dots::DotsPackedMatrix - Reductions — sum, min, max
- Elementwise ops — scale, sum, blend, fma
- Trigonometry — sin, cos, atan
Examples
// Requires linking against libnumkong C library
use numkong::{Tensor, DotsPackedMatrix};
let a = Tensor::<f32>::full(&[1024, 512], 1.0).unwrap();
let b = Tensor::<f32>::full(&[256, 512], 1.0).unwrap();
// Pack B once, multiply many times
let b_packed = DotsPackedMatrix::new(&b).unwrap();
let c = a.dots_packed(&b_packed).unwrap(); // Returns (1024 × 256)
Implements
CastOps<Source, R>, DenseToScaledOps<R>, AllCloseOps<Scalar, R>, ScaleOps<Scalar, R>, SumOps<Scalar, R>, BlendOps<Scalar, R>, FmaOps<Scalar, R>, BitwiseReductionsOps<MAX_RANK>, MomentsOps<Scalar, R>, MinMaxOps<Scalar, R>, TrigSinOps<Scalar, R>, TrigCosOps<Scalar, R>, TrigAtanOps<Scalar, R>, DotsPackedOps<Scalar, MAX_RANK>, SymmetricDotsOps<Scalar, R>, HammingsPackedOps<Scalar, MAX_RANK>, JaccardsPackedOps<Scalar, MAX_RANK>, SymmetricHammingsOps<Scalar, R>, SymmetricJaccardsOps<Scalar, R>, AngularsPackedOps<Scalar, MAX_RANK>, EuclideansPackedOps<Scalar, MAX_RANK>, SymmetricAngularsOps<Scalar, R>, SymmetricEuclideansOps<Scalar, R>, Send, Sync, Drop, TensorRef<Scalar, R>, TensorMut<Scalar, R>, Fill<Scalar>, CopyFrom<&[Scalar]>, Debug, IntoIterator, PartialEq, AsRef<[Scalar]>add_scalar_inplaceElement-wise add scalar in-place.
pub fn add_scalar_inplace(&mut self, scalar: Scalar::Scalar) -> Result<(), Error> sub_scalar_inplaceElement-wise subtract scalar in-place.
pub fn sub_scalar_inplace(&mut self, scalar: Scalar::Scalar) -> Result<(), Error> mul_scalar_inplaceElement-wise multiply scalar in-place.
pub fn mul_scalar_inplace(&mut self, scalar: Scalar::Scalar) -> Result<(), Error> add_tensor_inplaceElement-wise sum with another tensor, stored in self.
pub fn add_tensor_inplace<OtherAlloc: Allocator>(
&mut self,
other: &Tensor<Scalar, OtherAlloc, MAX_RANK>,
) -> Result<(), Error> sub_tensor_inplaceElement-wise difference with another tensor, stored in self.
pub fn sub_tensor_inplace<OtherAlloc: Allocator>(
&mut self,
other: &Tensor<Scalar, OtherAlloc, MAX_RANK>,
) -> Result<(), Error> mul_tensor_inplaceElement-wise product with another tensor, stored in self.
pub fn mul_tensor_inplace<OtherAlloc: Allocator>(
&mut self,
other: &Tensor<Scalar, OtherAlloc, MAX_RANK>,
) -> Result<(), Error> sin_inplaceElement-wise sine in-place.
pub fn sin_inplace(&mut self) -> Result<(), Error> cos_inplaceElement-wise cosine in-place.
pub fn cos_inplace(&mut self) -> Result<(), Error> atan_inplaceElement-wise arctangent in-place.
pub fn atan_inplace(&mut self) -> Result<(), Error> dots_packedDot-product multiply: C = self × packed_rightᵀ
pub fn dots_packed<PackedAlloc: Allocator>(
&self,
packed_right: &DotsPackedMatrix<Scalar, PackedAlloc>,
) -> Result<Tensor<Scalar::Accumulator, Alloc, MAX_RANK>, Error> fn dots_packed<PackedAlloc: Allocator>(
&self,
packed_right: &DotsPackedMatrix<Scalar, PackedAlloc>,
) -> Result<Tensor<Scalar::Accumulator, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, self must be 2D [m,k] with contiguous rows. packed_right contains B [n,k] packed. Returns C [m,n] using the same allocator as self.
Returns Err if:
- self is not 2D
- self has non-contiguous rows
- inner dimensions don't match
- output allocation fails
- the kernel refuses
packed_right, like one packed under other capabilities
hammings_packedComputes Hamming distances between rows of self and packed B matrix.
pub fn hammings_packed<PackedAlloc: Allocator>(
&self,
packed_right: &DotsPackedMatrix<Scalar, PackedAlloc>,
) -> Result<Tensor<u32, Alloc, MAX_RANK>, Error> fn hammings_packed<PackedAlloc: Allocator>(
&self,
packed_right: &DotsPackedMatrix<Scalar, PackedAlloc>,
) -> Result<Tensor<u32, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, Hamming distances: C = self × packed_rightᵀ
jaccards_packedComputes Jaccard distances between rows of self and packed B matrix.
pub fn jaccards_packed<PackedAlloc: Allocator>(
&self,
packed_right: &DotsPackedMatrix<Scalar, PackedAlloc>,
) -> Result<Tensor<Scalar::JaccardResult, Alloc, MAX_RANK>, Error> fn jaccards_packed<PackedAlloc: Allocator>(
&self,
packed_right: &DotsPackedMatrix<Scalar, PackedAlloc>,
) -> Result<Tensor<Scalar::JaccardResult, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, Jaccard distances: C = self × packed_rightᵀ
angulars_packedComputes angular distances between rows of self and packed B matrix.
pub fn angulars_packed<PackedAlloc: Allocator>(
&self,
packed_right: &DotsPackedMatrix<Scalar, PackedAlloc>,
) -> Result<Tensor<Scalar::SpatialResult, Alloc, MAX_RANK>, Error> fn angulars_packed<PackedAlloc: Allocator>(
&self,
packed_right: &DotsPackedMatrix<Scalar, PackedAlloc>,
) -> Result<Tensor<Scalar::SpatialResult, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, Angular distances: C = angular(self, packed_rightᵀ)
euclideans_packedComputes euclidean distances between rows of self and packed B matrix.
pub fn euclideans_packed<PackedAlloc: Allocator>(
&self,
packed_right: &DotsPackedMatrix<Scalar, PackedAlloc>,
) -> Result<Tensor<Scalar::SpatialResult, Alloc, MAX_RANK>, Error> fn euclideans_packed<PackedAlloc: Allocator>(
&self,
packed_right: &DotsPackedMatrix<Scalar, PackedAlloc>,
) -> Result<Tensor<Scalar::SpatialResult, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, Euclidean distances: C = euclidean(self, packed_rightᵀ)
cloneClone this tensor, returning an error on allocation failure.
pub fn clone(&self) -> Result<Self, Error> full_inCreates a new Tensor filled with a value using a custom allocator.
pub fn full_in(shape: &[usize], value: Scalar, alloc: Alloc) -> Result<Self, Error> The shape specifies logical dimensions. For sub-byte types the innermost extent counts
elements, a multiple of the values packed per byte, and storage holds total divided by
dimensions_per_value() packed values.
Returns Err if allocation fails or shape is invalid.
zeros_inCreates a zero-initialized Tensor using a custom allocator.
pub fn zeros_in(shape: &[usize], alloc: Alloc) -> Result<Self, Error>
where
Scalar: Default, Returns Err if allocation fails or shape is invalid.
ones_inCreates a Tensor filled with ones using a custom allocator.
pub fn ones_in(shape: &[usize], alloc: Alloc) -> Result<Self, Error>
where
Scalar: NumberLike, Returns Err if allocation fails or shape is invalid.
uninitialized_inCreates an uninitialized Tensor using a custom allocator.
pub unsafe fn uninitialized_in(shape: &[usize], alloc: Alloc) -> Result<Self, Error> Safety
The returned tensor's contents are uninitialized; reading before writing is undefined behavior.
from_slice_inCreates a Tensor from existing storage data using a custom allocator.
pub fn from_slice_in(data: &[Scalar], shape: &[usize], alloc: Alloc) -> Result<Self, Error> The shape specifies logical dimensions. For sub-byte types, the data slice holds
shape.product() divided by dimensions_per_value() storage values; for normal types,
data.len() equals shape.product().
from_scalars_inCreates a Tensor from per-dimension f32 values using a custom allocator.
pub fn from_scalars_in(scalars: &[f32], shape: &[usize], alloc: Alloc) -> Result<Self, Error>
where
Scalar: FloatConvertible,
Alloc: Clone, from_dims_inCreates a Tensor from per-dimension DimScalar values using a custom allocator.
pub fn from_dims_in(
dim_values: &[<Scalar as FloatConvertible>::DimScalar],
shape: &[usize],
alloc: Alloc,
) -> Result<Self, Error>
where
Scalar: FloatConvertible,
Alloc: Clone, Each element of dim_values represents one logical dimension; for sub-byte types the values
are packed into their storage representation. The length of dim_values must equal the
product of shape.
allocatorReturns a reference to the allocator.
pub fn allocator(&self) -> &Alloc storage_*_len× 3Number of storage values — for sub-byte types, less than numel.
pub fn storage__len(&self) -> usize into_vectorConvert a 1D contiguous tensor into a Vector, transferring ownership without copying.
pub fn into_vector(self) -> Result<Vector<Scalar, Alloc>, Error> Returns an error if the tensor is not 1D or not contiguous.
from_raw_parts_inConstruct a tensor from raw parts, taking ownership of the allocation.
pub unsafe fn from_raw_parts_in(
data: NonNull<Scalar>,
shape: [usize; MAX_RANK],
strides: [isize; MAX_RANK],
ndim: usize,
alloc: Alloc,
) -> Self Safety
datamust point to an allocation obtained fromalloc, aligned toDEFAULT_ALIGNMENT, whose backing buffer is sized for the storage count implied byshape(product(shape) / Scalar::dimensions_per_value()slots ofScalar).shape,strides, andndimmust be consistent with the data layout.- The caller must not free the memory — this tensor takes ownership.
shapeReturns the shape of the array.
pub fn shape(&self) -> &[usize] *× 3Returns the number of dimensions.
pub fn ndim(&self) -> usize *× 2Allocated storage-value capacity (Scalar slots) — the ceiling resize honors.
pub fn capacity(&self) -> usize Always >= numel() / Scalar::dimensions_per_value().
Always >= size_values().
resizeResize in place to new_shape without moving storage.
pub fn resize(&mut self, new_shape: &[usize]) -> Result<(), Error> Succeeds only when the packed storage fits capacity(), so as_ptr() stays stable — call
reserve first to grow. Returns Error::CapacityExceeded when it
would overflow or hits a shape error, leaving the tensor unchanged.
Examples
let mut t = Tensor::<f32>::zeros(&[8, 8])?; // capacity 64
t.resize(&[4, 4])?; // shrink within capacity; as_ptr() unchanged
assert!(t.resize(&[9, 8]).is_err()); // beyond capacity
reserveGrow the allocated capacity() to hold at least new_shape, reallocating and copying the live elements if needed.
pub fn reserve(&mut self, new_shape: &[usize]) -> Result<(), Error> A no-op when already large enough. Unlike resize
it may move storage. Returns Error::AllocationFailed on failure, leaving it unchanged.
clearReset to an empty rank-1 shape (numel() == 0) while keeping the allocated capacity().
pub fn clear(&mut self) stride_*_bytes× 3Returns the stride in bytes for the given dimension.
pub fn stride__bytes(&self, dim: usize) -> isize as_ptrReturns a pointer to the data.
pub fn as_ptr(&self) -> *const Scalar as_mut_ptrReturns a mutable pointer to the data.
pub fn as_mut_ptr(&mut self) -> *mut Scalar as_sliceReturns the underlying storage data as a slice.
pub fn as_slice(&self) -> &[Scalar] For sub-byte types, the slice holds packed storage values, not individual logical elements.
as_mut_sliceReturns the underlying storage data as a mutable slice.
pub fn as_mut_slice(&mut self) -> &mut [Scalar] For sub-byte types, the slice holds packed storage values, not individual logical elements.
rowReturns a row of a 2D array.
pub fn row(&self, i: usize) -> Option<&[Scalar]> row_mutReturns a mutable row of a 2D array.
pub fn row_mut(&mut self, i: usize) -> Option<&mut [Scalar]> fullCreates a new Tensor filled with a value using the global allocator.
pub fn full(shape: &[usize], value: Scalar) -> Result<Self, Error> Returns Err if allocation fails or shape is invalid.
Examples
use numkong::tensor::{Tensor, TensorRef};
let zeros = Tensor::<f32>::full(&[2, 3], 0.0).unwrap();
assert_eq!(zeros.shape(), &[2, 3]);
assert_eq!(zeros.numel(), 6);
assert!(zeros.as_slice().iter().all(|&v| v == 0.0));
zerosCreates a zero-initialized Tensor using the global allocator.
pub fn zeros(shape: &[usize]) -> Result<Self, Error>
where
Scalar: Default, onesCreates a Tensor filled with ones using the global allocator.
pub fn ones(shape: &[usize]) -> Result<Self, Error>
where
Scalar: NumberLike, uninitializedCreates an uninitialized Tensor using the global allocator.
pub unsafe fn uninitialized(shape: &[usize]) -> Result<Self, Error> Safety
The returned tensor's contents are uninitialized; reading before writing is undefined behavior.
from_sliceCreates a Tensor from existing slice data using the global allocator.
pub fn from_slice(data: &[Scalar], shape: &[usize]) -> Result<Self, Error> Returns Err if shape doesn't match data length or allocation fails.
from_scalarsCreates a Tensor from per-dimension f32 values using the global allocator.
pub fn from_scalars(scalars: &[f32], shape: &[usize]) -> Result<Self, Error>
where
Scalar: FloatConvertible, Each f32 is converted through FloatConvertible::DimScalar::from_f32 before storage. The
length of scalars must equal the product of shape.
from_dimsCreates a Tensor from per-dimension DimScalar values using the global allocator.
pub fn from_dims(
dim_values: &[<Scalar as FloatConvertible>::DimScalar],
shape: &[usize],
) -> Result<Self, Error>
where
Scalar: FloatConvertible, Each element of dim_values represents one logical dimension. The length of dim_values
must equal the product of shape.
axis_*_views× 2Iterate along the given axis, yielding sub-tensor views with rank-1.
pub fn axis__views<AnyIndex: VectorIndex>(
&self,
axis: AnyIndex,
) -> Result<AxisIterator<'_, Scalar, MAX_RANK, Alloc>, Error> axis_*_spans× 2Iterate mutably along the given axis, yielding sub-tensor spans with rank-1.
pub fn axis__spans<AnyIndex: VectorIndex>(
&mut self,
axis: AnyIndex,
) -> Result<AxisIteratorMut<'_, Scalar, MAX_RANK, Alloc>, Error> *× 3Returns a lazy iterator over all logical scalars in row-major order.
pub fn iter(&self) -> TensorViewIterator<'_, Scalar, MAX_RANK> Yields (position, DimRef) pairs. Use .iter().dims() for just dimensions.
Yields (position, DimRef) pairs. Use .iter().dims() for just dimensions. For sub-byte
types, the innermost dimension is expanded.
iter_*_mut× 2Returns a mutable iterator over all logical scalars in row-major order.
pub fn iter__mut(&mut self) -> TensorSpanIterator<'_, Scalar, MAX_RANK> Yields (position, DimMut) pairs. Use .iter_mut().dims() for just dimensions.
viewCreate a view of the entire array.
pub fn view(&self) -> TensorView<'_, Scalar, MAX_RANK, Alloc> fn view(&self) -> TensorView<'_, Scalar, R, Alloc> Borrow as an immutable TensorView with the same shape and strides.
spanCreate a mutable span of the entire tensor.
pub fn span(&mut self) -> TensorSpan<'_, Scalar, MAX_RANK, Alloc> The returned TensorSpan borrows self exclusively for '_. Use it to apply in-place
kernels, write to individual elements via TensorSpan::flat_mut /
TensorSpan::coords_mut, or pass it to APIs that need &mut (impl TensorMut<_, _>).
Examples
use numkong::tensor::Tensor;
let mut t = Tensor::<f32>::full(&[2, 2], 0.0).unwrap();
let mut span = t.span();
*span.flat_mut(0_usize).unwrap() = 42.0;
assert_eq!(*span.flat(0_usize).unwrap(), 42.0);
*× 3Get an element by flat logical row-major index.
pub fn flat<AnyIndex: VectorIndex>(&self, index: AnyIndex) -> Result<&Scalar, Error> Negative isize indices wrap from the end (-1 is the last element).
Returns Error::DimensionMismatch on a rank-0 view and
Error::IndexOutOfBounds when the index is outside the logical element count.
Examples
use numkong::tensor::Tensor;
let t = Tensor::<f32>::from_slice(&[1.0, 2.0, 3.0, 4.0], &[2, 2]).unwrap();
let view = t.view();
assert_eq!(*view.flat(0_usize).unwrap(), 1.0);
assert_eq!(*view.flat(-1_i32).unwrap(), 4.0);
flat_*_mut× 2Get a mutable element by flat logical row-major index.
pub fn flat__mut<AnyIndex: VectorIndex>(&mut self, index: AnyIndex) -> Result<&mut Scalar, Error> Negative isize indices wrap from the end. Returns Error::DimensionMismatch on a
rank-0 span and Error::IndexOutOfBounds when the index is out of range.
Examples
use numkong::tensor::Tensor;
let mut t = Tensor::<f32>::full(&[3], 0.0).unwrap();
let mut span = t.span();
*span.flat_mut(-1_i32).unwrap() = 9.0;
assert_eq!(*span.flat(2_usize).unwrap(), 9.0);
*× 3Get an element by exact coordinates.
pub fn coords<C: TensorCoordinates>(&self, coords: C) -> Result<&Scalar, Error> coords_*_mut× 2Get a mutable element by exact coordinates.
pub fn coords__mut<C: TensorCoordinates>(&mut self, coords: C) -> Result<&mut Scalar, Error> scalarAccess the scalar value of a rank-0 tensor.
pub fn scalar(&self) -> Result<&Scalar, Error> scalar_mutAccess the mutable scalar value of a rank-0 tensor.
pub fn scalar_mut(&mut self) -> Result<&mut Scalar, Error> slice_*_leading× 3Slice the leading axis by one index, reducing rank by one.
pub fn slice__leading<AnyIndex: VectorIndex>(
&self,
index: AnyIndex,
) -> Result<TensorView<'_, Scalar, MAX_RANK, Alloc>, Error> slice_leading_*_leading_mut× 2Slice the leading axis mutably by one index, reducing rank by one.
pub fn slice_leading__leading_mut<AnyIndex: VectorIndex>(
&mut self,
index: AnyIndex,
) -> Result<TensorSpan<'_, Scalar, MAX_RANK, Alloc>, Error> sliceSlice the array along multiple dimensions, returning a zero-copy view.
pub fn slice(&self, spec: impl SliceSpec) -> Result<TensorView<'_, Scalar, MAX_RANK, Alloc>, Error> Accepts tuples of Rust range types or &[SliceRange]. Scalar arguments reduce the rank,
range arguments preserve it, and RangeStep permits stepped sampling.
Examples
use numkong::tensor::{Tensor, SliceRange};
let arr = Tensor::<f32>::full(&[4, 5], 1.0).unwrap();
// Tuple syntax — preferred
let block = arr.slice((0..2_usize, ..)).unwrap(); // t[0:2, :]
let row = arr.slice((1_usize, ..)).unwrap(); // t[1, :]
assert_eq!(block.shape(), &[2, 5]);
assert_eq!(row.shape(), &[5]);
// Enum-based syntax still works for programmatic construction
let same_block = arr.slice(&[SliceRange::range(0, 2), SliceRange::full()]).unwrap();
assert_eq!(block.shape(), same_block.shape());
slice_mutSlice the array mutably along multiple dimensions.
pub fn slice_mut(
&mut self,
spec: impl SliceSpec,
) -> Result<TensorSpan<'_, Scalar, MAX_RANK, Alloc>, Error> Accepts tuples of Rust range types or &[SliceRange].
*× 3Transpose — reverse all dimensions, no data copy.
pub fn transpose(&self) -> Result<TensorView<'_, Scalar, MAX_RANK, Alloc>, Error> Returns an error for sub-byte types with ndim >= 2.
Returns an error for sub-byte types with ndim >= 2, since transposing would produce non-contiguous strides that break packed element addressing.
reshapeReshape the array — must have same total elements, contiguous only.
pub fn reshape(&self, new_shape: &[usize]) -> Result<TensorView<'_, Scalar, MAX_RANK, Alloc>, Error> *× 3Flatten to 1D; requires contiguous layout.
pub fn flatten(&self) -> Result<TensorView<'_, Scalar, MAX_RANK, Alloc>, Error> *× 3Remove dimensions of size 1.
pub fn squeeze(&self) -> TensorView<'_, Scalar, MAX_RANK, Alloc> scaleApply element-wise scale: result[i] = α × self[i] + β
pub fn scale(
&self,
alpha: Scalar::Scalar,
beta: Scalar::Scalar,
) -> Result<Tensor<Scalar, Alloc, MAX_RANK>, Error>
where
Alloc: Clone, Returns a new array with the scaled values.
scale_inplaceApply element-wise scale in-place: self[i] = α × self[i] + β
pub fn scale_inplace(&mut self, alpha: Scalar::Scalar, beta: Scalar::Scalar) -> Result<(), Error> addElement-wise sum: result[i] = self[i] + other[i]
pub fn add<OtherAlloc: Allocator, const OTHER_MAX_RANK: usize>(
&self,
other: &Tensor<Scalar, OtherAlloc, OTHER_MAX_RANK>,
) -> Result<Tensor<Scalar, Alloc, MAX_RANK>, Error>
where
Alloc: Clone, Returns a new array with the summed values.
add_inplaceElement-wise sum in-place: self[i] = self[i] + other[i]
pub fn add_inplace<OtherAlloc: Allocator, const OTHER_MAX_RANK: usize>(
&mut self,
other: &Tensor<Scalar, OtherAlloc, OTHER_MAX_RANK>,
) -> Result<(), Error> blendBlend: result[i] = α × self[i] + β × other[i]
pub fn blend<OtherAlloc: Allocator, const OTHER_MAX_RANK: usize>(
&self,
other: &Tensor<Scalar, OtherAlloc, OTHER_MAX_RANK>,
alpha: Scalar::Scalar,
beta: Scalar::Scalar,
) -> Result<Tensor<Scalar, Alloc, MAX_RANK>, Error>
where
Alloc: Clone, Returns a new array with the blend.
fmaFused multiply-add: result[i] = α × self[i] × b[i] + β × c[i]
pub fn fma<BAlloc: Allocator, CAlloc: Allocator, const B_MAX_RANK: usize, const C_MAX_RANK: usize>(
&self,
multiplier: &Tensor<Scalar, BAlloc, B_MAX_RANK>,
addend: &Tensor<Scalar, CAlloc, C_MAX_RANK>,
alpha: Scalar::Scalar,
beta: Scalar::Scalar,
) -> Result<Tensor<Scalar, Alloc, MAX_RANK>, Error>
where
Alloc: Clone, Returns a new array with the FMA result.
dot_productCompute the dot product of this array with another.
pub fn dot_product<OtherAlloc: Allocator, const OTHER_MAX_RANK: usize>(
&self,
other: &Tensor<Scalar, OtherAlloc, OTHER_MAX_RANK>,
) -> Result<Scalar::Output, Error> Both arrays must be 1D with the same length.
*× 2Casts every element to Destination, returning a new tensor of the same shape.
Inherited from CastOps
fn cast<Destination: Clone + CastDType>(
&self,
) -> Result<Tensor<Destination, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, cast_*_into× 2Cast into a pre-allocated sink.
Inherited from CastOps
fn cast__into<Destination, OutputTensor>(&self, out: &mut OutputTensor) -> Result<(), Error>
where
Destination: Clone + CastDType,
OutputTensor: TensorMut<Destination, MAX_RANK> + ?Sized, The destination may be a &mut Tensor<...> or a &mut TensorSpan<...>, any TensorMut; a strided sub-span works too.
cast_to_*_to_scaled× 3Encodes the tensor into the block-scaled format F.
Inherited from DenseToScaledOps
fn cast_to__to_scaled<F: BlockScaledFormat>(&self) -> Result<ScaledTensor<F, Self::Alloc>, Error>
where
Self::Alloc: Clone, *× 3Returns true iff both tensors share a shape and every element pair is within tolerance.
Inherited from AllCloseOps
fn allclose(&self, other: &impl TensorRef<Scalar, MAX_RANK> + ?Sized, atol: f64, rtol: f64) -> bool add_*_scalar× 2Element-wise add scalar into a new tensor.
Inherited from ScaleOps
fn add__scalar(&self, scalar: Scalar::Scalar) -> Result<Tensor<Scalar, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, sub_*_scalar× 2Element-wise subtract scalar into a new tensor.
Inherited from ScaleOps
fn sub__scalar(&self, scalar: Scalar::Scalar) -> Result<Tensor<Scalar, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, mul_*_scalar× 2Element-wise multiply scalar into a new tensor.
Inherited from ScaleOps
fn mul__scalar(&self, scalar: Scalar::Scalar) -> Result<Tensor<Scalar, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, scale_tensor_*_tensor_into× 3Writes α × aᵢ + β into the output tensor.
Inherited from ScaleOps
fn scale_tensor__tensor_into<OutputTensor: TensorMut<Scalar, MAX_RANK> + ?Sized>(
&self,
alpha: Scalar::Scalar,
beta: Scalar::Scalar,
out: &mut OutputTensor,
) -> Result<(), Error> add_scalar_*_scalar_into× 3Element-wise add scalar into the output tensor.
Inherited from ScaleOps
fn add_scalar__scalar_into<OutputTensor: TensorMut<Scalar, MAX_RANK> + ?Sized>(
&self,
scalar: Scalar::Scalar,
out: &mut OutputTensor,
) -> Result<(), Error> sub_scalar_*_scalar_into× 3Element-wise subtract scalar into the output tensor.
Inherited from ScaleOps
fn sub_scalar__scalar_into<OutputTensor: TensorMut<Scalar, MAX_RANK> + ?Sized>(
&self,
scalar: Scalar::Scalar,
out: &mut OutputTensor,
) -> Result<(), Error> mul_scalar_*_scalar_into× 3Element-wise multiply scalar into the output tensor.
Inherited from ScaleOps
fn mul_scalar__scalar_into<OutputTensor: TensorMut<Scalar, MAX_RANK> + ?Sized>(
&self,
scalar: Scalar::Scalar,
out: &mut OutputTensor,
) -> Result<(), Error> add_*_tensor× 2Element-wise sum of two tensors into a new tensor.
Inherited from SumOps
fn add__tensor(
&self,
other: &impl TensorRef<Scalar, MAX_RANK> + ?Sized,
) -> Result<Tensor<Scalar, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, add_tensor_*_tensor_into× 2Element-wise sum of two tensors into the output tensor.
Inherited from SumOps
fn add_tensor__tensor_into<OtherTensor, OutputTensor>(
&self,
other: &OtherTensor,
out: &mut OutputTensor,
) -> Result<(), Error>
where
OtherTensor: TensorRef<Scalar, MAX_RANK> + ?Sized,
OutputTensor: TensorMut<Scalar, MAX_RANK> + ?Sized, sub_*_tensor× 2Element-wise difference of two tensors into a new tensor.
Inherited from BlendOps
fn sub__tensor(
&self,
other: &impl TensorRef<Scalar, MAX_RANK> + ?Sized,
) -> Result<Tensor<Scalar, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, blend_tensor_*_tensor_into× 2Writes α × aᵢ + β × otherᵢ into the output tensor.
Inherited from BlendOps
fn blend_tensor__tensor_into<OtherTensor, OutputTensor>(
&self,
other: &OtherTensor,
alpha: Scalar::Scalar,
beta: Scalar::Scalar,
out: &mut OutputTensor,
) -> Result<(), Error>
where
OtherTensor: TensorRef<Scalar, MAX_RANK> + ?Sized,
OutputTensor: TensorMut<Scalar, MAX_RANK> + ?Sized, sub_tensor_*_tensor_into× 2Element-wise difference of two tensors into the output tensor.
Inherited from BlendOps
fn sub_tensor__tensor_into<OtherTensor, OutputTensor>(
&self,
other: &OtherTensor,
out: &mut OutputTensor,
) -> Result<(), Error>
where
OtherTensor: TensorRef<Scalar, MAX_RANK> + ?Sized,
OutputTensor: TensorMut<Scalar, MAX_RANK> + ?Sized, mul_*_tensor× 2Element-wise product of two tensors into a new tensor.
Inherited from FmaOps
fn mul__tensor(
&self,
other: &impl TensorRef<Scalar, MAX_RANK> + ?Sized,
) -> Result<Tensor<Scalar, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, fma_tensors_*_tensors_into× 2Writes α × aᵢ × bᵢ + β × cᵢ into the output tensor.
Inherited from FmaOps
fn fma_tensors__tensors_into<BTensor, CTensor, OutputTensor>(
&self,
b: &BTensor,
c: &CTensor,
alpha: Scalar::Scalar,
beta: Scalar::Scalar,
out: &mut OutputTensor,
) -> Result<(), Error>
where
BTensor: TensorRef<Scalar, MAX_RANK> + ?Sized,
CTensor: TensorRef<Scalar, MAX_RANK> + ?Sized,
OutputTensor: TensorMut<Scalar, MAX_RANK> + ?Sized, mul_tensor_*_tensor_into× 2Element-wise product of two tensors into the output tensor.
Inherited from FmaOps
fn mul_tensor__tensor_into<OtherTensor, OutputTensor>(
&self,
other: &OtherTensor,
out: &mut OutputTensor,
) -> Result<(), Error>
where
OtherTensor: TensorRef<Scalar, MAX_RANK> + ?Sized,
OutputTensor: TensorMut<Scalar, MAX_RANK> + ?Sized, *× 3Number of set bits across the entire tensor.
any_*_set× 3true if at least one bit in the tensor is set.
none_*_set× 3true if no bit in the tensor is set.
all_*_set× 3true if every bit in the tensor is set.
moments_*_all× 3Sum and sum of squares over all elements.
Inherited from MomentsOps
fn moments__all(&self) -> Result<(Scalar::SumOutput, Scalar::SumSqOutput), Error> moments_*_axis× 2Sum and sum of squares along one axis, into new tensors.
Inherited from MomentsOps
fn moments__axis<AnyIndex: VectorIndex>(
&self,
axis: AnyIndex,
keep_dims: bool,
) -> Result<(Tensor<<Scalar as ReduceMoments>::SumOutput, Self::Alloc, MAX_RANK>, Tensor<<Scalar as ReduceMoments>::SumSqOutput, Self::Alloc, MAX_RANK>), Error>
where
Self::Alloc: Clone, moments_axis_*_axis_into× 3Sum and sum of squares along one axis, into the output tensors.
Inherited from MomentsOps
fn moments_axis__axis_into<AnyIndex, SumTensor, SumSqTensor>(
&self,
axis: AnyIndex,
keep_dims: bool,
sum_out: &mut SumTensor,
sumsq_out: &mut SumSqTensor,
) -> Result<(), Error>
where
AnyIndex: VectorIndex,
SumTensor: TensorMut<Scalar::SumOutput, MAX_RANK> + ?Sized,
SumSqTensor: TensorMut<Scalar::SumSqOutput, MAX_RANK> + ?Sized, sum_*_all× 3Sum over all elements.
sum_*_axis× 2Sum along one axis, into a new tensor.
Inherited from MomentsOps
fn sum__axis<AnyIndex: VectorIndex>(
&self,
axis: AnyIndex,
keep_dims: bool,
) -> Result<Tensor<Scalar::SumOutput, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, sum_axis_*_axis_into× 3Sum along one axis, into the output tensor.
Inherited from MomentsOps
fn sum_axis__axis_into<AnyIndex, SumTensor>(
&self,
axis: AnyIndex,
keep_dims: bool,
out: &mut SumTensor,
) -> Result<(), Error>
where
AnyIndex: VectorIndex,
SumTensor: TensorMut<Scalar::SumOutput, MAX_RANK> + ?Sized, norm_*_all× 3Euclidean norm over all elements.
norm_*_axis× 2Euclidean norm along one axis, into a new tensor.
Inherited from MomentsOps
fn norm__axis<AnyIndex: VectorIndex>(
&self,
axis: AnyIndex,
keep_dims: bool,
) -> Result<Tensor<f64, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, norm_axis_*_axis_into× 3Euclidean norm along one axis, into the output tensor.
Inherited from MomentsOps
fn norm_axis__axis_into<AnyIndex, NormTensor>(
&self,
axis: AnyIndex,
keep_dims: bool,
out: &mut NormTensor,
) -> Result<(), Error>
where
AnyIndex: VectorIndex,
NormTensor: TensorMut<f64, MAX_RANK> + ?Sized, minmax_*_all× 3Minimum and maximum with their indices over all elements.
Inherited from MinMaxOps
fn minmax__all(&self) -> Result<MinMaxResult<Scalar::Output>, Error> minmax_*_axis× 2Minimum and maximum with their indices along one axis, into new tensors.
Inherited from MinMaxOps
fn minmax__axis<AnyIndex: VectorIndex>(
&self,
axis: AnyIndex,
keep_dims: bool,
) -> Result<MinMaxResult<Tensor<<Scalar as ReduceMinMax>::Output, Self::Alloc, MAX_RANK>, Tensor<usize, Self::Alloc, MAX_RANK>>, Error>
where
Self::Alloc: Clone, minmax_axis_*_axis_into× 3Minimum and maximum with their indices along one axis, into the output tensors.
Inherited from MinMaxOps
fn minmax_axis__axis_into<AnyIndex, ValueTensor, IndexTensor>(
&self,
axis: AnyIndex,
keep_dims: bool,
min_out: &mut ValueTensor,
argmin_out: &mut IndexTensor,
max_out: &mut ValueTensor,
argmax_out: &mut IndexTensor,
) -> Result<(), Error>
where
AnyIndex: VectorIndex,
ValueTensor: TensorMut<Scalar::Output, MAX_RANK> + ?Sized,
IndexTensor: TensorMut<usize, MAX_RANK> + ?Sized, min_*_all× 3Minimum over all elements.
argmin_*_all× 3Index of the minimum over all elements.
max_*_all× 3Maximum over all elements.
argmax_*_all× 3Index of the maximum over all elements.
min_*_axis× 2Minimum along one axis, into a new tensor.
Inherited from MinMaxOps
fn min__axis<AnyIndex: VectorIndex>(
&self,
axis: AnyIndex,
keep_dims: bool,
) -> Result<Tensor<Scalar::Output, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, argmin_*_axis× 2Index of the minimum along one axis, into a new tensor.
Inherited from MinMaxOps
fn argmin__axis<AnyIndex: VectorIndex>(
&self,
axis: AnyIndex,
keep_dims: bool,
) -> Result<Tensor<usize, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, max_*_axis× 2Maximum along one axis, into a new tensor.
Inherited from MinMaxOps
fn max__axis<AnyIndex: VectorIndex>(
&self,
axis: AnyIndex,
keep_dims: bool,
) -> Result<Tensor<Scalar::Output, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, argmax_*_axis× 2Index of the maximum along one axis, into a new tensor.
Inherited from MinMaxOps
fn argmax__axis<AnyIndex: VectorIndex>(
&self,
axis: AnyIndex,
keep_dims: bool,
) -> Result<Tensor<usize, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, *× 2Element-wise sine into a new tensor.
Inherited from TrigSinOps
fn sin(&self) -> Result<Tensor<Scalar, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, sin_*_into× 3Element-wise sine into the output tensor.
Inherited from TrigSinOps
fn sin__into<OutputTensor: TensorMut<Scalar, MAX_RANK> + ?Sized>(
&self,
out: &mut OutputTensor,
) -> Result<(), Error> *× 2Element-wise cosine into a new tensor.
Inherited from TrigCosOps
fn cos(&self) -> Result<Tensor<Scalar, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, cos_*_into× 3Element-wise cosine into the output tensor.
Inherited from TrigCosOps
fn cos__into<OutputTensor: TensorMut<Scalar, MAX_RANK> + ?Sized>(
&self,
out: &mut OutputTensor,
) -> Result<(), Error> *× 2Element-wise arctangent into a new tensor.
Inherited from TrigAtanOps
fn atan(&self) -> Result<Tensor<Scalar, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, atan_*_into× 3Element-wise arctangent into the output tensor.
Inherited from TrigAtanOps
fn atan__into<OutputTensor: TensorMut<Scalar, MAX_RANK> + ?Sized>(
&self,
out: &mut OutputTensor,
) -> Result<(), Error> dots_packed_*_packed_into× 3Dot-product multiply into an existing output, avoiding allocation.
Inherited from DotsPackedOps
fn dots_packed__packed_into<PackedAlloc, OutputTensor, const OUTPUT_MAX_RANK: usize>(
&self,
packed_right: &DotsPackedMatrix<Scalar, PackedAlloc>,
output: &mut OutputTensor,
) -> Result<(), Error>
where
PackedAlloc: Allocator,
OutputTensor: TensorMut<Scalar::Accumulator, OUTPUT_MAX_RANK>, The output may be a &mut Tensor<...> or &mut TensorSpan<...>; any writable tensor
container that implements TensorMut works. The kernel overwrites c entirely, so it
need not arrive pre-initialized.
dots_*_symmetric× 2Computes the upper triangle of the symmetric dot-product matrix of the rows with themselves.
Inherited from SymmetricDotsOps
fn dots__symmetric(&self) -> Result<Tensor<Scalar::Accumulator, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, dots_symmetric_*_symmetric_into× 2Writes the symmetric dot-product matrix into pre-allocated output, touching only the upper triangle of it.
Inherited from SymmetricDotsOps
fn dots_symmetric__symmetric_into<Out, const OUTPUT_MAX_RANK: usize>(
&self,
output: &mut Out,
) -> Result<(), Error>
where
Out: TensorMut<Scalar::Accumulator, OUTPUT_MAX_RANK>, hammings_packed_*_packed_into× 3Hamming distances into an existing output, avoiding allocation.
Inherited from HammingsPackedOps
fn hammings_packed__packed_into<PackedAlloc, OutputTensor, const OUTPUT_MAX_RANK: usize>(
&self,
packed_right: &DotsPackedMatrix<Scalar, PackedAlloc>,
output: &mut OutputTensor,
) -> Result<(), Error>
where
PackedAlloc: Allocator,
OutputTensor: TensorMut<u32, OUTPUT_MAX_RANK>, The output may be a &mut Tensor<...> or &mut TensorSpan<...>; any writable tensor
container that implements TensorMut works. The kernel overwrites c entirely, so it
need not arrive pre-initialized.
jaccards_packed_*_packed_into× 3Jaccard distances into an existing output, avoiding allocation.
Inherited from JaccardsPackedOps
fn jaccards_packed__packed_into<PackedAlloc, OutputTensor, const OUTPUT_MAX_RANK: usize>(
&self,
packed_right: &DotsPackedMatrix<Scalar, PackedAlloc>,
output: &mut OutputTensor,
) -> Result<(), Error>
where
PackedAlloc: Allocator,
OutputTensor: TensorMut<Scalar::JaccardResult, OUTPUT_MAX_RANK>, The output may be a &mut Tensor<...> or &mut TensorSpan<...>; any writable tensor
container that implements TensorMut works. The kernel overwrites c entirely, so it
need not arrive pre-initialized.
hammings_*_symmetric× 2Computes the upper triangle of the symmetric Hamming-distance matrix of the rows with themselves.
Inherited from SymmetricHammingsOps
fn hammings__symmetric(&self) -> Result<Tensor<u32, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, hammings_symmetric_*_symmetric_into× 2Writes the symmetric Hamming-distance matrix into pre-allocated output, touching only the upper triangle of it.
Inherited from SymmetricHammingsOps
fn hammings_symmetric__symmetric_into<Out, const OUTPUT_MAX_RANK: usize>(
&self,
output: &mut Out,
) -> Result<(), Error>
where
Out: TensorMut<u32, OUTPUT_MAX_RANK>, jaccards_*_symmetric× 2Computes the upper triangle of the symmetric Jaccard-distance matrix of the rows with themselves.
Inherited from SymmetricJaccardsOps
fn jaccards__symmetric(&self) -> Result<Tensor<Scalar::JaccardResult, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, jaccards_symmetric_*_symmetric_into× 2Writes the symmetric Jaccard-distance matrix into pre-allocated output, touching only the upper triangle of it.
Inherited from SymmetricJaccardsOps
fn jaccards_symmetric__symmetric_into<Out, const OUTPUT_MAX_RANK: usize>(
&self,
output: &mut Out,
) -> Result<(), Error>
where
Out: TensorMut<Scalar::JaccardResult, OUTPUT_MAX_RANK>, angulars_packed_*_packed_into× 3Angular distances into an existing output, avoiding allocation.
Inherited from AngularsPackedOps
fn angulars_packed__packed_into<PackedAlloc, OutputTensor, const OUTPUT_MAX_RANK: usize>(
&self,
packed_right: &DotsPackedMatrix<Scalar, PackedAlloc>,
output: &mut OutputTensor,
) -> Result<(), Error>
where
PackedAlloc: Allocator,
OutputTensor: TensorMut<Scalar::SpatialResult, OUTPUT_MAX_RANK>, The output may be a &mut Tensor<...> or &mut TensorSpan<...>; any writable tensor
container that implements TensorMut works. The kernel overwrites c entirely, so it
need not arrive pre-initialized.
euclideans_packed_*_packed_into× 3Euclidean distances into an existing output, avoiding allocation.
Inherited from EuclideansPackedOps
fn euclideans_packed__packed_into<PackedAlloc, OutputTensor, const OUTPUT_MAX_RANK: usize>(
&self,
packed_right: &DotsPackedMatrix<Scalar, PackedAlloc>,
output: &mut OutputTensor,
) -> Result<(), Error>
where
PackedAlloc: Allocator,
OutputTensor: TensorMut<Scalar::SpatialResult, OUTPUT_MAX_RANK>, The output may be a &mut Tensor<...> or &mut TensorSpan<...>; any writable tensor
container that implements TensorMut works. The kernel overwrites c entirely, so it
need not arrive pre-initialized.
angulars_*_symmetric× 2Computes the upper triangle of the symmetric angular-distance matrix of the rows with themselves.
Inherited from SymmetricAngularsOps
fn angulars__symmetric(&self) -> Result<Tensor<Scalar::SpatialResult, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, angulars_symmetric_*_symmetric_into× 2Writes the symmetric angular-distance matrix into pre-allocated output, touching only the upper triangle of it.
Inherited from SymmetricAngularsOps
fn angulars_symmetric__symmetric_into<Out, const OUTPUT_MAX_RANK: usize>(
&self,
output: &mut Out,
) -> Result<(), Error>
where
Out: TensorMut<Scalar::SpatialResult, OUTPUT_MAX_RANK>, euclideans_*_symmetric× 2Computes the upper triangle of the symmetric Euclidean-distance matrix of the rows with themselves.
Inherited from SymmetricEuclideansOps
fn euclideans__symmetric(
&self,
) -> Result<Tensor<Scalar::SpatialResult, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, euclideans_symmetric_*_symmetric_into× 2Writes the symmetric euclidean-distance matrix into pre-allocated output, touching only the upper triangle of it.
Inherited from SymmetricEuclideansOps
fn euclideans_symmetric__symmetric_into<Out, const OUTPUT_MAX_RANK: usize>(
&self,
output: &mut Out,
) -> Result<(), Error>
where
Out: TensorMut<Scalar::SpatialResult, OUTPUT_MAX_RANK>, *× 4Total number of logical elements, the product of the shape dimensions.
Inherited from TensorRef
fn numel(&self) -> usize Examples
let t = Tensor::<f32>::full(&[2, 3, 4], 0.0).unwrap();
assert_eq!(t.numel(), 24);
*× 4Alias for ndim — number of dimensions.
is_*_empty× 4Returns true if the tensor contains zero logical elements.
Inherited from TensorRef
fn is__empty(&self) -> bool A rank-0 tensor is a scalar and is not empty — it has one element.
has_contiguous_*_contiguous_rows× 4Returns true for rank-2 tensors whose innermost stride equals one element — the layout required by GEMM's left-hand matrix.
is_*_contiguous× 4Returns true if the entire tensor is stored in row-major contiguous order with no gaps.
Inherited from TensorRef
fn is__contiguous(&self) -> bool A contiguous tensor can be reinterpreted as a flat slice via
TensorView::as_contiguous_slice; a non-contiguous one cannot.
TraitTensorMutMutable structural access to N-dimensional tensor containers.1
pub trait TensorMut<Scalar: StorageElement, const MAX_RANK: usize>: TensorRef<Scalar, MAX_RANK> TensorMut is a supertrait of TensorRef that adds a single method — a mutable raw pointer
to the first element. It is implemented by Tensor, which owns its memory, and by
TensorSpan, which borrows a mutable sub-region. Immutable views (TensorView)
deliberately do not implement TensorMut.
Generic write-access helpers accept &mut (impl TensorMut<Scalar, R>) so they work uniformly
against owned tensors and span reborrows.
Implementors
impl<Scalar: StorageElement, Alloc: Allocator, const R: usize> TensorMut<Scalar, R> for Tensor<Scalar, Alloc, R>impl<'a, Scalar: StorageElement, const R: usize, Alloc: Allocator> TensorMut<Scalar, R> for TensorSpan<'a, Scalar, R, Alloc>
as_mut_ptrRaw mutable pointer to the first storage element.
fn as_mut_ptr(&mut self) -> *mut Scalar The pointer is valid for numel() divided by dimensions_per_value() writes and preserves
whatever stride layout TensorRef::stride_bytes reports — callers must honour the
per-axis strides when striding through non-contiguous memory.
TraitTensorRefRead-only structural access to N-dimensional tensor containers.7
pub trait TensorRef<Scalar: StorageElement, const MAX_RANK: usize> Implemented by Tensor, TensorView, and TensorSpan, enabling generic code over any
tensor-like container. Most operations in this crate accept `&(impl TensorRef<Scalar, MAX_RANK>
- ?Sized)` so you can mix owned tensors, views, and spans freely without copying.
The trait only exposes structural accessors — shape, strides, pointer, and a borrow-as-view
constructor. Element reads happen through the resulting TensorView. See TensorMut for
the mutable counterpart.
Implementors
impl<Scalar: StorageElement, Alloc: Allocator, const R: usize> TensorRef<Scalar, R> for Tensor<Scalar, Alloc, R>impl<'a, Scalar: StorageElement, const R: usize, Alloc: Allocator> TensorRef<Scalar, R> for TensorView<'a, Scalar, R, Alloc>impl<'a, Scalar: StorageElement, const R: usize, Alloc: Allocator> TensorRef<Scalar, R> for TensorSpan<'a, Scalar, R, Alloc>
AllocThe allocator of the owning tensor, which allocating operations clone for their result.
type Alloc: Allocator; An arena that is not Clone works by reference: &Arena is itself a Clone allocator.
*× 3The owning tensor's allocator, or Global for a view over foreign memory.
fn allocator(&self) -> &Self::Alloc shapeLogical shape as a slice of length ndim().
fn shape(&self) -> &[usize] For sub-byte types this is the number of individual elements, not the packed storage count.
ndimNumber of dimensions currently in use.
fn ndim(&self) -> usize Always satisfies ndim() <= MAX_RANK. A rank-0 tensor reports 0.
stride_bytesByte stride along dimension dim.
fn stride_bytes(&self, dim: usize) -> isize Negative values indicate reverse traversal, such as from a stepped slice. Only indices in
0..ndim() are valid.
Examples
let t = Tensor::<f32>::full(&[3, 4], 0.0).unwrap();
assert_eq!(t.stride_bytes(1), 4); // innermost f32 stride
as_ptrRaw pointer to the first storage element.
fn as_ptr(&self) -> *const Scalar The pointer is valid for shape().iter().product() logical reads, divided by
Scalar::dimensions_per_value() for sub-byte types.
*× 3Borrow as an immutable TensorView with the same shape and strides.
fn view(&self) -> TensorView<'_, Scalar, MAX_RANK, Self::Alloc> This is a zero-cost reborrow and is the normal entry point for extension-trait methods that want to delegate to view-level code.
StructTensorSpanA mutable, zero-copy view into a Tensor.29
pub struct TensorSpan<'a, Scalar, const MAX_RANK: usize = DEFAULT_MAX_RANK, Alloc = Global> TensorSpan borrows the parent tensor's memory exclusively for the duration of 'a, giving
write access without taking ownership. As with TensorView, a span may carry non-contiguous
byte strides so slicing, transposition, and stepped sub-views all remain free of data copies.
Spans are typically produced by Tensor::span or by a mutable slicing method such as
tensor.slice_mut((..,0_usize)). Lower-level construction from a raw pointer is available
through TensorSpan::from_raw_parts.
A span is the mutable counterpart of TensorView. At most one span to a given region may
exist at a time; reborrow via TensorSpan::as_view to hand out immutable sub-views without
surrendering the span.
The 'a lifetime ties the span to the owning tensor, so the referenced memory stays valid for
as long as the span exists.
Implements
CastOps<Source, R>, DenseToScaledOps<R>, AllCloseOps<Scalar, R>, ScaleOps<Scalar, R>, SumOps<Scalar, R>, BlendOps<Scalar, R>, FmaOps<Scalar, R>, BitwiseReductionsOps<MAX_RANK>, MomentsOps<Scalar, R>, MinMaxOps<Scalar, R>, TrigSinOps<Scalar, R>, TrigCosOps<Scalar, R>, TrigAtanOps<Scalar, R>, DotsPackedOps<Scalar, MAX_RANK>, SymmetricDotsOps<Scalar, R>, HammingsPackedOps<Scalar, MAX_RANK>, JaccardsPackedOps<Scalar, MAX_RANK>, SymmetricHammingsOps<Scalar, R>, SymmetricJaccardsOps<Scalar, R>, AngularsPackedOps<Scalar, MAX_RANK>, EuclideansPackedOps<Scalar, MAX_RANK>, SymmetricAngularsOps<Scalar, R>, SymmetricEuclideansOps<Scalar, R>, Debug, Send, Sync, TensorRef<Scalar, R>, TensorMut<Scalar, R>, Fill<Scalar>, CopyFrom<&'b TensorView<'_, Scalar, MAX_RANK, SourceAlloc>>, IntoIterator, PartialEqfrom_raw_partsCreate a mutable view from a raw pointer, shape, and byte strides, reporting Global as its allocator.
pub unsafe fn from_raw_parts(
data: *mut Scalar,
shape: &[usize],
strides_bytes: &[isize],
) -> Result<Self, Error> Safety
datamust be valid for reads and writes over the region described byshapeandstrides_bytes.- The pointed-to memory must outlive
'a. - No other references to the memory may exist for the duration of
'a.
Returns Err if shape.len() > MAX_RANK or shape.len() != strides_bytes.len().
from_raw_parts_inLike TensorSpan::from_raw_parts, reporting allocator to the operations that allocate.
pub unsafe fn from_raw_parts_in(
data: *mut Scalar,
shape: &[usize],
strides_bytes: &[isize],
allocator: &'a Alloc,
) -> Result<Self, Error> Safety
The same as for TensorSpan::from_raw_parts.
*× 2Returns the shape of the view.
pub fn shape(&self) -> &[usize] as_*_ptr× 2Returns a pointer to the first element.
pub fn as__ptr(&self) -> *const Scalar as_mut_ptrReturns a mutable pointer to the first element.
pub fn as_mut_ptr(&mut self) -> *mut Scalar as_viewReborrow as immutable view.
pub fn as_view(&self) -> TensorView<'_, Scalar, MAX_RANK, Alloc> scalarAccess the scalar value of a rank-0 tensor span.
pub fn scalar(&self) -> Result<&Scalar, Error> scalar_mutAccess the mutable scalar value of a rank-0 tensor span.
pub fn scalar_mut(&mut self) -> Result<&mut Scalar, Error> sliceSlice the span along multiple dimensions.
pub fn slice(&self, spec: impl SliceSpec) -> Result<TensorView<'_, Scalar, MAX_RANK, Alloc>, Error> Accepts tuples of Rust range types or &[SliceRange].
slice_mutSlice the span mutably along multiple dimensions.
pub fn slice_mut(
&mut self,
spec: impl SliceSpec,
) -> Result<TensorSpan<'_, Scalar, MAX_RANK, Alloc>, Error> Accepts tuples of Rust range types or &[SliceRange].
as_contiguous_*_contiguous_slice× 2Convert to slice; only valid for contiguous views.
pub fn as_contiguous__contiguous_slice(&self) -> Option<&[Scalar]> as_contiguous_slice_mutConvert to mutable slice; only valid for contiguous views.
pub fn as_contiguous_slice_mut(&mut self) -> Option<&mut [Scalar]> reshapeReshape the span — must have same total elements, contiguous only.
pub fn reshape(&self, new_shape: &[usize]) -> Result<TensorSpan<'a, Scalar, MAX_RANK, Alloc>, Error> Returns an error for sub-byte types.
to_ownedCopy the span contents to a new owned Tensor.
pub fn to_owned(&self) -> Result<Tensor<Scalar, Alloc, MAX_RANK>, Error>
where
Alloc: Clone, scale_inplaceIn-place affine: selfᵢ = α × selfᵢ + β.
pub fn scale_inplace(&mut self, alpha: Scalar::Scalar, beta: Scalar::Scalar) -> Result<(), Error> add_scalar_inplaceIn-place add scalar: selfᵢ = selfᵢ + scalar.
pub fn add_scalar_inplace(&mut self, scalar: Scalar::Scalar) -> Result<(), Error> sub_scalar_inplaceIn-place subtract scalar: selfᵢ = selfᵢ − scalar.
pub fn sub_scalar_inplace(&mut self, scalar: Scalar::Scalar) -> Result<(), Error> mul_scalar_inplaceIn-place multiply scalar: selfᵢ = selfᵢ × scalar.
pub fn mul_scalar_inplace(&mut self, scalar: Scalar::Scalar) -> Result<(), Error> add_inplaceIn-place sum: selfᵢ = selfᵢ + otherᵢ.
pub fn add_inplace<OtherAlloc: Allocator>(
&mut self,
other: &TensorView<'_, Scalar, MAX_RANK, OtherAlloc>,
) -> Result<(), Error> sub_inplaceIn-place subtract tensor: selfᵢ = selfᵢ − otherᵢ.
pub fn sub_inplace<OtherAlloc: Allocator>(
&mut self,
other: &TensorView<'_, Scalar, MAX_RANK, OtherAlloc>,
) -> Result<(), Error> mul_inplaceIn-place multiply tensor: selfᵢ = selfᵢ × otherᵢ.
pub fn mul_inplace<OtherAlloc: Allocator>(
&mut self,
other: &TensorView<'_, Scalar, MAX_RANK, OtherAlloc>,
) -> Result<(), Error> Mirrors out-of-place mul_tensor, which is an FMA with c = self and alpha = 1, beta = 0. The c operand is bound to self inside the kernel via the single span pointer, so
other remains the only foreign slice.
sin_inplaceIn-place sine: selfᵢ = sin(selfᵢ).
pub fn sin_inplace(&mut self) -> Result<(), Error> cos_inplaceIn-place cosine: selfᵢ = cos(selfᵢ).
pub fn cos_inplace(&mut self) -> Result<(), Error> atan_inplaceIn-place arctangent: selfᵢ = atan(selfᵢ).
pub fn atan_inplace(&mut self) -> Result<(), Error> dots_*_packed× 2Dot-product multiply: C = self × packed_rightᵀ
Inherited from DotsPackedOps
fn dots__packed<PackedAlloc: Allocator>(
&self,
packed_right: &DotsPackedMatrix<Scalar, PackedAlloc>,
) -> Result<Tensor<Scalar::Accumulator, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, self must be 2D [m,k] with contiguous rows. packed_right contains B [n,k]
packed. Returns C [m,n], allocated like self.
Returns Err if:
- self is not 2D
- self has non-contiguous rows
- inner dimensions don't match
- output allocation fails
- the kernel refuses
packed_right, like one packed under other capabilities
hammings_*_packed× 2Hamming distances: C = self × packed_rightᵀ
Inherited from HammingsPackedOps
fn hammings__packed<PackedAlloc: Allocator>(
&self,
packed_right: &DotsPackedMatrix<Scalar, PackedAlloc>,
) -> Result<Tensor<u32, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, self must be 2D [m,k] with contiguous rows. packed_right contains B [n,k]
packed. Returns C [m,n], allocated like self.
Returns Err if:
- self is not 2D
- self has non-contiguous rows
- inner dimensions don't match
- output allocation fails
- the kernel refuses
packed_right, like one packed under other capabilities
jaccards_*_packed× 2Jaccard distances: C = self × packed_rightᵀ
Inherited from JaccardsPackedOps
fn jaccards__packed<PackedAlloc: Allocator>(
&self,
packed_right: &DotsPackedMatrix<Scalar, PackedAlloc>,
) -> Result<Tensor<Scalar::JaccardResult, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, self must be 2D [m,k] with contiguous rows. packed_right contains B [n,k]
packed. Returns C [m,n], allocated like self.
Returns Err if:
- self is not 2D
- self has non-contiguous rows
- inner dimensions don't match
- output allocation fails
- the kernel refuses
packed_right, like one packed under other capabilities
angulars_*_packed× 2Angular distances: C = angular(self, packed_rightᵀ)
Inherited from AngularsPackedOps
fn angulars__packed<PackedAlloc: Allocator>(
&self,
packed_right: &DotsPackedMatrix<Scalar, PackedAlloc>,
) -> Result<Tensor<Scalar::SpatialResult, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, self must be 2D [m,k] with contiguous rows. packed_right contains B [n,k]
packed. Returns C [m,n], allocated like self.
Returns Err if:
- self is not 2D
- self has non-contiguous rows
- inner dimensions don't match
- output allocation fails
- the kernel refuses
packed_right, like one packed under other capabilities
euclideans_*_packed× 2Euclidean distances: C = euclidean(self, packed_rightᵀ)
Inherited from EuclideansPackedOps
fn euclideans__packed<PackedAlloc: Allocator>(
&self,
packed_right: &DotsPackedMatrix<Scalar, PackedAlloc>,
) -> Result<Tensor<Scalar::SpatialResult, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, self must be 2D [m,k] with contiguous rows. packed_right contains B [n,k]
packed. Returns C [m,n], allocated like self.
Returns Err if:
- self is not 2D
- self has non-contiguous rows
- inner dimensions don't match
- output allocation fails
- the kernel refuses
packed_right, like one packed under other capabilities
StructTensorSpanDimsA mutable dimension-only adapter over TensorSpanIterator, yielding DimMut items and discarding positions.
pub struct TensorSpanDims<'a, Scalar: FloatConvertible, const MAX_RANK: usize = DEFAULT_MAX_RANK> Implements
Iterator, ExactSizeIterator, FusedIteratorStructTensorSpanIteratorMutable element iterator over possibly non-contiguous tensor data.1
pub struct TensorSpanIterator<'a, Scalar: FloatConvertible, const MAX_RANK: usize = DEFAULT_MAX_RANK> Yields (position, DimMut<'a, Scalar>) pairs in row-major order at the logical-scalar level.
For sub-byte types, each proxy performs a read-modify-write on drop.
Implements
Iterator, ExactSizeIterator, FusedIteratordimsAdapt this iterator to yield only mutable dimension proxies, discarding positions.
pub fn dims(self) -> TensorSpanDims<'a, Scalar, MAX_RANK> StructTensorViewA read-only, zero-copy view into a Tensor.46
pub struct TensorView<'a, Scalar, const MAX_RANK: usize = DEFAULT_MAX_RANK, Alloc = Global> TensorView borrows the parent tensor's memory for the duration of 'a without owning or
copying any data. Views may have arbitrary byte strides, so they transparently represent
slicing, transposition, or step-sampling of the underlying storage — iteration and indexing
honour those strides.
A view is normally obtained by calling Tensor::view or by slicing:
tensor.slice((0..4_usize, ..)). For lower-level construction from a raw pointer plus
shape/stride arrays, see TensorView::from_raw_parts.
TensorView is the immutable counterpart of TensorSpan. Both share the same layout fields,
but a view cannot be used to mutate the backing storage. Multiple views into the same tensor may
coexist, subject to Rust's borrow rules; a mutable span excludes all other references.
The 'a lifetime ties the view to the source tensor or outer view, ensuring the referenced
memory outlives the view itself.
Implements
CastOps<Source, R>, DenseToScaledOps<R>, AllCloseOps<Scalar, R>, ScaleOps<Scalar, R>, SumOps<Scalar, R>, BlendOps<Scalar, R>, FmaOps<Scalar, R>, BitwiseReductionsOps<MAX_RANK>, MomentsOps<Scalar, R>, MinMaxOps<Scalar, R>, TrigSinOps<Scalar, R>, TrigCosOps<Scalar, R>, TrigAtanOps<Scalar, R>, DotsPackedOps<Scalar, MAX_RANK>, SymmetricDotsOps<Scalar, R>, HammingsPackedOps<Scalar, MAX_RANK>, JaccardsPackedOps<Scalar, MAX_RANK>, SymmetricHammingsOps<Scalar, R>, SymmetricJaccardsOps<Scalar, R>, AngularsPackedOps<Scalar, MAX_RANK>, EuclideansPackedOps<Scalar, MAX_RANK>, SymmetricAngularsOps<Scalar, R>, SymmetricEuclideansOps<Scalar, R>, Clone, Copy, Debug, Send, Sync, TensorRef<Scalar, R>, CopyFrom<&'b TensorView<'_, Scalar, MAX_RANK, SourceAlloc>>, IntoIterator, PartialEqdots_symmetricComputes the symmetric dot-product matrix C = A × Aᵀ.
pub fn dots_symmetric(&self) -> Result<Tensor<Scalar::Accumulator, Alloc, MAX_RANK>, Error>
where
Alloc: Clone, fn dots_symmetric(&self) -> Result<Tensor<Scalar::Accumulator, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, Computes the upper triangle of the symmetric dot-product matrix of the rows with themselves.
Given a matrix of row vectors, computes the symmetric [n,n] matrix of all pairwise dot products, where result[i,j] = dot(row_i, row_j).
Examples
use numkong::{Tensor, TensorView};
// 100 vectors of dimension 768
let vectors = Tensor::<f32>::full(&[100, 768], 0.0)?;
// Compute 100×100 symmetric matrix
let gram = vectors.view().dots_symmetric()?;
assert_eq!(gram.shape(), &[100, 100]);
dots_symmetric_intoComputes the symmetric dot-product matrix into pre-allocated output.
pub fn dots_symmetric_into<OutputTensor, const OUTPUT_MAX_RANK: usize>(
&self,
output: &mut OutputTensor,
) -> Result<(), Error>
where
OutputTensor: TensorMut<Scalar::Accumulator, OUTPUT_MAX_RANK>, fn dots_symmetric_into<Out, const OUTPUT_MAX_RANK: usize>(
&self,
output: &mut Out,
) -> Result<(), Error>
where
Out: TensorMut<Scalar::Accumulator, OUTPUT_MAX_RANK>, Writes the symmetric dot-product matrix into pre-allocated output, touching only the upper triangle of it.
Only the upper triangle of c is written; the lower triangle is queries as-is. The output
may be a &mut Tensor<...> or &mut TensorSpan<...>.
hammings_symmetricComputes symmetric Hamming distance matrix for a set of binary vectors.
pub fn hammings_symmetric(&self) -> Result<Tensor<u32, Alloc, MAX_RANK>, Error>
where
Alloc: Clone, fn hammings_symmetric(&self) -> Result<Tensor<u32, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, Computes the upper triangle of the symmetric Hamming-distance matrix of the rows with themselves.
hammings_symmetric_intoComputes symmetric Hamming distances into pre-allocated output, touching only the upper triangle of it.
pub fn hammings_symmetric_into<OutputTensor, const OUTPUT_MAX_RANK: usize>(
&self,
output: &mut OutputTensor,
) -> Result<(), Error>
where
OutputTensor: TensorMut<u32, OUTPUT_MAX_RANK>, fn hammings_symmetric_into<Out, const OUTPUT_MAX_RANK: usize>(
&self,
output: &mut Out,
) -> Result<(), Error>
where
Out: TensorMut<u32, OUTPUT_MAX_RANK>, Writes the symmetric Hamming-distance matrix into pre-allocated output, touching only the upper triangle of it.
jaccards_symmetricComputes symmetric Jaccard distance matrix for a set of binary vectors.
pub fn jaccards_symmetric(&self) -> Result<Tensor<Scalar::JaccardResult, Alloc, MAX_RANK>, Error>
where
Alloc: Clone, fn jaccards_symmetric(&self) -> Result<Tensor<Scalar::JaccardResult, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, Computes the upper triangle of the symmetric Jaccard-distance matrix of the rows with themselves.
jaccards_symmetric_intoComputes symmetric Jaccard distances into pre-allocated output, touching only the upper triangle of it.
pub fn jaccards_symmetric_into<OutputTensor, const OUTPUT_MAX_RANK: usize>(
&self,
output: &mut OutputTensor,
) -> Result<(), Error>
where
OutputTensor: TensorMut<Scalar::JaccardResult, OUTPUT_MAX_RANK>, fn jaccards_symmetric_into<Out, const OUTPUT_MAX_RANK: usize>(
&self,
output: &mut Out,
) -> Result<(), Error>
where
Out: TensorMut<Scalar::JaccardResult, OUTPUT_MAX_RANK>, Writes the symmetric Jaccard-distance matrix into pre-allocated output, touching only the upper triangle of it.
angulars_symmetricComputes symmetric angular distance matrix for a set of vectors.
pub fn angulars_symmetric(&self) -> Result<Tensor<Scalar::SpatialResult, Alloc, MAX_RANK>, Error>
where
Alloc: Clone, fn angulars_symmetric(&self) -> Result<Tensor<Scalar::SpatialResult, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, Computes the upper triangle of the symmetric angular-distance matrix of the rows with themselves.
angulars_symmetric_intoComputes symmetric angular distances into pre-allocated output, touching only the upper triangle of it.
pub fn angulars_symmetric_into<OutputTensor, const OUTPUT_MAX_RANK: usize>(
&self,
output: &mut OutputTensor,
) -> Result<(), Error>
where
OutputTensor: TensorMut<Scalar::SpatialResult, OUTPUT_MAX_RANK>, fn angulars_symmetric_into<Out, const OUTPUT_MAX_RANK: usize>(
&self,
output: &mut Out,
) -> Result<(), Error>
where
Out: TensorMut<Scalar::SpatialResult, OUTPUT_MAX_RANK>, Writes the symmetric angular-distance matrix into pre-allocated output, touching only the upper triangle of it.
euclideans_symmetricComputes symmetric euclidean distance matrix for a set of vectors.
pub fn euclideans_symmetric(&self) -> Result<Tensor<Scalar::SpatialResult, Alloc, MAX_RANK>, Error>
where
Alloc: Clone, fn euclideans_symmetric(
&self,
) -> Result<Tensor<Scalar::SpatialResult, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, Computes the upper triangle of the symmetric Euclidean-distance matrix of the rows with themselves.
euclideans_symmetric_intoComputes symmetric euclidean distances into pre-allocated output, touching only the upper triangle of it.
pub fn euclideans_symmetric_into<OutputTensor, const OUTPUT_MAX_RANK: usize>(
&self,
output: &mut OutputTensor,
) -> Result<(), Error>
where
OutputTensor: TensorMut<Scalar::SpatialResult, OUTPUT_MAX_RANK>, fn euclideans_symmetric_into<Out, const OUTPUT_MAX_RANK: usize>(
&self,
output: &mut Out,
) -> Result<(), Error>
where
Out: TensorMut<Scalar::SpatialResult, OUTPUT_MAX_RANK>, Writes the symmetric euclidean-distance matrix into pre-allocated output, touching only the upper triangle of it.
from_raw_partsCreate a view from a raw pointer, shape, and byte strides, reporting Global as its allocator.
pub unsafe fn from_raw_parts(
data: *const Scalar,
shape: &[usize],
strides_bytes: &[isize],
) -> Result<Self, Error> The shape specifies logical dimensions. For sub-byte types, the storage count is
shape.product() divided by dimensions_per_value(); for normal types the two are equal.
Safety
datamust be valid for reads over the region described byshapeandstrides_bytes.- The pointed-to memory must outlive
'a.
Returns Err if shape.len() > MAX_RANK or shape.len() != strides_bytes.len().
from_raw_parts_inLike TensorView::from_raw_parts, reporting allocator to the operations that allocate.
pub unsafe fn from_raw_parts_in(
data: *const Scalar,
shape: &[usize],
strides_bytes: &[isize],
allocator: &'a Alloc,
) -> Result<Self, Error> Safety
The same as for TensorView::from_raw_parts.
get_uncheckedGet element at flat index; only valid for contiguous views.
pub unsafe fn get_unchecked(&self, index: usize) -> &Scalar Safety
Caller must ensure the view is contiguous and index is in bounds.
scalarAccess the scalar value of a rank-0 tensor view.
pub fn scalar(&self) -> Result<&Scalar, Error> sliceSlice the view along multiple dimensions.
pub fn slice(&self, spec: impl SliceSpec) -> Result<TensorView<'a, Scalar, MAX_RANK, Alloc>, Error> Accepts tuples of Rust range types or &[SliceRange]. Indexing with a scalar reduces the
rank, while range arguments preserve it.
Examples
use numkong::tensor::{Tensor, SliceRange};
let t = Tensor::<f32>::full(&[4, 5], 1.0).unwrap();
let view = t.view();
// Rust-native tuple syntax
let row = view.slice((1_usize, ..)).unwrap(); // t[1, :]
let block = view.slice((1..3_usize, 0..4_usize)).unwrap();// t[1:3, 0:4]
// Enum-based syntax for programmatic construction
let same_row = view.slice(&[SliceRange::index(1), SliceRange::full()]).unwrap();
assert_eq!(row.shape(), same_row.shape());
to_ownedCopy the view contents to a new owned Tensor.
pub fn to_owned(&self) -> Result<Tensor<Scalar, Alloc, MAX_RANK>, Error>
where
Alloc: Clone, is_packed_contiguousTrue when the underlying storage bytes are densely packed in memory.
pub fn is_packed_contiguous(&self) -> bool Unlike is_contiguous, this accounts for sub-byte packing: the
innermost-axis extent is measured in storage values (shape / dimensions_per_value), so a
freshly-allocated e2m1x2 tensor, whose row stride is columns / 2 bytes, is recognized as
packed. Used by the block-scaled casts, which hand raw byte buffers to the C kernel.
as_packed_sliceStorage values as a slice when the bytes are packed, sub-byte aware.
pub fn as_packed_slice(&self) -> Option<&[Scalar]> Returns None for strided/transposed views. This is the sub-byte-aware companion to
as_contiguous_slice.
reshapeReshape the view — must have same total elements, contiguous only.
pub fn reshape(&self, new_shape: &[usize]) -> Result<TensorView<'a, Scalar, MAX_RANK, Alloc>, Error> For sub-byte types this returns an error, since a reshape would invalidate the packed element layout.
scale_tensorWrites α × aᵢ + β into a new tensor.
pub fn scale_tensor(
&self,
alpha: Scalar::Scalar,
beta: Scalar::Scalar,
) -> Result<Tensor<Scalar, Alloc, MAX_RANK>, Error>
where
Alloc: Clone, add_scalarElement-wise add scalar into a new tensor.
pub fn add_scalar(&self, scalar: Scalar::Scalar) -> Result<Tensor<Scalar, Alloc, MAX_RANK>, Error>
where
Alloc: Clone, fn add_scalar(&self, scalar: Scalar::Scalar) -> Result<Tensor<Scalar, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, sub_scalarElement-wise subtract scalar into a new tensor.
pub fn sub_scalar(&self, scalar: Scalar::Scalar) -> Result<Tensor<Scalar, Alloc, MAX_RANK>, Error>
where
Alloc: Clone, fn sub_scalar(&self, scalar: Scalar::Scalar) -> Result<Tensor<Scalar, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, mul_scalarElement-wise multiply scalar into a new tensor.
pub fn mul_scalar(&self, scalar: Scalar::Scalar) -> Result<Tensor<Scalar, Alloc, MAX_RANK>, Error>
where
Alloc: Clone, fn mul_scalar(&self, scalar: Scalar::Scalar) -> Result<Tensor<Scalar, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, add_tensorElement-wise sum of two tensors into a new tensor.
pub fn add_tensor<OtherAlloc: Allocator>(
&self,
other: &TensorView<'_, Scalar, MAX_RANK, OtherAlloc>,
) -> Result<Tensor<Scalar, Alloc, MAX_RANK>, Error>
where
Alloc: Clone, fn add_tensor(
&self,
other: &impl TensorRef<Scalar, MAX_RANK> + ?Sized,
) -> Result<Tensor<Scalar, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, add_tensor_intoElement-wise sum of two tensors into the output tensor.
pub fn add_tensor_into<OtherAlloc: Allocator, OutputTensor: TensorMut<Scalar, MAX_RANK> + ?Sized>(
&self,
other: &TensorView<'_, Scalar, MAX_RANK, OtherAlloc>,
out: &mut OutputTensor,
) -> Result<(), Error> fn add_tensor_into<OtherTensor, OutputTensor>(
&self,
other: &OtherTensor,
out: &mut OutputTensor,
) -> Result<(), Error>
where
OtherTensor: TensorRef<Scalar, MAX_RANK> + ?Sized,
OutputTensor: TensorMut<Scalar, MAX_RANK> + ?Sized, blend_tensorWrites α × aᵢ + β × otherᵢ into a new tensor.
pub fn blend_tensor<OtherAlloc: Allocator>(
&self,
other: &TensorView<'_, Scalar, MAX_RANK, OtherAlloc>,
alpha: Scalar::Scalar,
beta: Scalar::Scalar,
) -> Result<Tensor<Scalar, Alloc, MAX_RANK>, Error>
where
Alloc: Clone, blend_tensor_intoWrites α × aᵢ + β × otherᵢ into the output tensor.
pub fn blend_tensor_into<OtherAlloc: Allocator, OutputTensor: TensorMut<Scalar, MAX_RANK> + ?Sized>(
&self,
other: &TensorView<'_, Scalar, MAX_RANK, OtherAlloc>,
alpha: Scalar::Scalar,
beta: Scalar::Scalar,
out: &mut OutputTensor,
) -> Result<(), Error> fn blend_tensor_into<OtherTensor, OutputTensor>(
&self,
other: &OtherTensor,
alpha: Scalar::Scalar,
beta: Scalar::Scalar,
out: &mut OutputTensor,
) -> Result<(), Error>
where
OtherTensor: TensorRef<Scalar, MAX_RANK> + ?Sized,
OutputTensor: TensorMut<Scalar, MAX_RANK> + ?Sized, sub_tensorElement-wise difference of two tensors into a new tensor.
pub fn sub_tensor<OtherAlloc: Allocator>(
&self,
other: &TensorView<'_, Scalar, MAX_RANK, OtherAlloc>,
) -> Result<Tensor<Scalar, Alloc, MAX_RANK>, Error>
where
Alloc: Clone, fn sub_tensor(
&self,
other: &impl TensorRef<Scalar, MAX_RANK> + ?Sized,
) -> Result<Tensor<Scalar, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, sub_tensor_intoElement-wise difference of two tensors into the output tensor.
pub fn sub_tensor_into<OtherAlloc: Allocator, OutputTensor: TensorMut<Scalar, MAX_RANK> + ?Sized>(
&self,
other: &TensorView<'_, Scalar, MAX_RANK, OtherAlloc>,
out: &mut OutputTensor,
) -> Result<(), Error> fn sub_tensor_into<OtherTensor, OutputTensor>(
&self,
other: &OtherTensor,
out: &mut OutputTensor,
) -> Result<(), Error>
where
OtherTensor: TensorRef<Scalar, MAX_RANK> + ?Sized,
OutputTensor: TensorMut<Scalar, MAX_RANK> + ?Sized, fma_tensorsWrites α × aᵢ × bᵢ + β × cᵢ into a new tensor.
pub fn fma_tensors<BAlloc: Allocator, CAlloc: Allocator>(
&self,
b: &TensorView<'_, Scalar, MAX_RANK, BAlloc>,
c: &TensorView<'_, Scalar, MAX_RANK, CAlloc>,
alpha: Scalar::Scalar,
beta: Scalar::Scalar,
) -> Result<Tensor<Scalar, Alloc, MAX_RANK>, Error>
where
Alloc: Clone, fma_tensors_intoWrites α × aᵢ × bᵢ + β × cᵢ into the output tensor.
pub fn fma_tensors_into<BAlloc: Allocator, CAlloc: Allocator, OutputTensor: TensorMut<Scalar, MAX_RANK> + ?Sized>(
&self,
b: &TensorView<'_, Scalar, MAX_RANK, BAlloc>,
c: &TensorView<'_, Scalar, MAX_RANK, CAlloc>,
alpha: Scalar::Scalar,
beta: Scalar::Scalar,
out: &mut OutputTensor,
) -> Result<(), Error> fn fma_tensors_into<BTensor, CTensor, OutputTensor>(
&self,
b: &BTensor,
c: &CTensor,
alpha: Scalar::Scalar,
beta: Scalar::Scalar,
out: &mut OutputTensor,
) -> Result<(), Error>
where
BTensor: TensorRef<Scalar, MAX_RANK> + ?Sized,
CTensor: TensorRef<Scalar, MAX_RANK> + ?Sized,
OutputTensor: TensorMut<Scalar, MAX_RANK> + ?Sized, mul_tensorElement-wise product of two tensors into a new tensor.
pub fn mul_tensor<OtherAlloc: Allocator>(
&self,
other: &TensorView<'_, Scalar, MAX_RANK, OtherAlloc>,
) -> Result<Tensor<Scalar, Alloc, MAX_RANK>, Error>
where
Alloc: Clone, fn mul_tensor(
&self,
other: &impl TensorRef<Scalar, MAX_RANK> + ?Sized,
) -> Result<Tensor<Scalar, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, mul_tensor_intoElement-wise product of two tensors into the output tensor.
pub fn mul_tensor_into<OtherAlloc: Allocator, OutputTensor: TensorMut<Scalar, MAX_RANK> + ?Sized>(
&self,
other: &TensorView<'_, Scalar, MAX_RANK, OtherAlloc>,
out: &mut OutputTensor,
) -> Result<(), Error> fn mul_tensor_into<OtherTensor, OutputTensor>(
&self,
other: &OtherTensor,
out: &mut OutputTensor,
) -> Result<(), Error>
where
OtherTensor: TensorRef<Scalar, MAX_RANK> + ?Sized,
OutputTensor: TensorMut<Scalar, MAX_RANK> + ?Sized, castCasts every element to Destination, returning a new tensor of the same shape.
cast_intoCasts every element to Destination, writing into the output tensor.
pub fn cast_into<Destination, OutputTensor>(&self, out: &mut OutputTensor) -> Result<(), Error>
where
Destination: Clone + CastDType,
OutputTensor: TensorMut<Destination, MAX_RANK> + ?Sized, sinElement-wise sine into a new tensor.
pub fn sin(&self) -> Result<Tensor<Scalar, Alloc, MAX_RANK>, Error>
where
Alloc: Clone, fn sin(&self) -> Result<Tensor<Scalar, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, cosElement-wise cosine into a new tensor.
pub fn cos(&self) -> Result<Tensor<Scalar, Alloc, MAX_RANK>, Error>
where
Alloc: Clone, fn cos(&self) -> Result<Tensor<Scalar, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, atanElement-wise arctangent into a new tensor.
pub fn atan(&self) -> Result<Tensor<Scalar, Alloc, MAX_RANK>, Error>
where
Alloc: Clone, fn atan(&self) -> Result<Tensor<Scalar, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, moments_axisSum and sum of squares along one axis, into new tensors.
pub fn moments_axis<AnyIndex: VectorIndex>(
&self,
axis: AnyIndex,
keep_dims: bool,
) -> Result<(Tensor<<Scalar as ReduceMoments>::SumOutput, Alloc, MAX_RANK>, Tensor<<Scalar as ReduceMoments>::SumSqOutput, Alloc, MAX_RANK>), Error>
where
Alloc: Clone, fn moments_axis<AnyIndex: VectorIndex>(
&self,
axis: AnyIndex,
keep_dims: bool,
) -> Result<(Tensor<<Scalar as ReduceMoments>::SumOutput, Self::Alloc, MAX_RANK>, Tensor<<Scalar as ReduceMoments>::SumSqOutput, Self::Alloc, MAX_RANK>), Error>
where
Self::Alloc: Clone, sum_axisSum along one axis, into a new tensor.
pub fn sum_axis<AnyIndex: VectorIndex>(
&self,
axis: AnyIndex,
keep_dims: bool,
) -> Result<Tensor<Scalar::SumOutput, Alloc, MAX_RANK>, Error>
where
Alloc: Clone, fn sum_axis<AnyIndex: VectorIndex>(
&self,
axis: AnyIndex,
keep_dims: bool,
) -> Result<Tensor<Scalar::SumOutput, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, norm_axisEuclidean norm along one axis, into a new tensor.
pub fn norm_axis<AnyIndex: VectorIndex>(
&self,
axis: AnyIndex,
keep_dims: bool,
) -> Result<Tensor<f64, Alloc, MAX_RANK>, Error>
where
Alloc: Clone, fn norm_axis<AnyIndex: VectorIndex>(
&self,
axis: AnyIndex,
keep_dims: bool,
) -> Result<Tensor<f64, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, minmax_axisMinimum and maximum with their indices along one axis, into new tensors.
pub fn minmax_axis<AnyIndex: VectorIndex>(
&self,
axis: AnyIndex,
keep_dims: bool,
) -> Result<MinMaxResult<Tensor<<Scalar as ReduceMinMax>::Output, Alloc, MAX_RANK>, Tensor<usize, Alloc, MAX_RANK>>, Error>
where
Alloc: Clone, fn minmax_axis<AnyIndex: VectorIndex>(
&self,
axis: AnyIndex,
keep_dims: bool,
) -> Result<MinMaxResult<Tensor<<Scalar as ReduceMinMax>::Output, Self::Alloc, MAX_RANK>, Tensor<usize, Self::Alloc, MAX_RANK>>, Error>
where
Self::Alloc: Clone, min_axisMinimum along one axis, into a new tensor.
pub fn min_axis<AnyIndex: VectorIndex>(
&self,
axis: AnyIndex,
keep_dims: bool,
) -> Result<Tensor<Scalar::Output, Alloc, MAX_RANK>, Error>
where
Alloc: Clone, fn min_axis<AnyIndex: VectorIndex>(
&self,
axis: AnyIndex,
keep_dims: bool,
) -> Result<Tensor<Scalar::Output, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, argmin_axisIndex of the minimum along one axis, into a new tensor.
pub fn argmin_axis<AnyIndex: VectorIndex>(
&self,
axis: AnyIndex,
keep_dims: bool,
) -> Result<Tensor<usize, Alloc, MAX_RANK>, Error>
where
Alloc: Clone, fn argmin_axis<AnyIndex: VectorIndex>(
&self,
axis: AnyIndex,
keep_dims: bool,
) -> Result<Tensor<usize, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, max_axisMaximum along one axis, into a new tensor.
pub fn max_axis<AnyIndex: VectorIndex>(
&self,
axis: AnyIndex,
keep_dims: bool,
) -> Result<Tensor<Scalar::Output, Alloc, MAX_RANK>, Error>
where
Alloc: Clone, fn max_axis<AnyIndex: VectorIndex>(
&self,
axis: AnyIndex,
keep_dims: bool,
) -> Result<Tensor<Scalar::Output, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, argmax_axisIndex of the maximum along one axis, into a new tensor.
pub fn argmax_axis<AnyIndex: VectorIndex>(
&self,
axis: AnyIndex,
keep_dims: bool,
) -> Result<Tensor<usize, Alloc, MAX_RANK>, Error>
where
Alloc: Clone, fn argmax_axis<AnyIndex: VectorIndex>(
&self,
axis: AnyIndex,
keep_dims: bool,
) -> Result<Tensor<usize, Self::Alloc, MAX_RANK>, Error>
where
Self::Alloc: Clone, StructTensorViewDimsDimension-only adapter over TensorViewIterator, yielding DimRef without positions.
pub struct TensorViewDims<'a, Scalar: FloatConvertible, const MAX_RANK: usize = DEFAULT_MAX_RANK> Created by TensorViewIterator::dims().
Implements
Iterator, ExactSizeIterator, FusedIteratorStructTensorViewIteratorLazy element iterator over possibly non-contiguous tensor data.1
pub struct TensorViewIterator<'a, Scalar: FloatConvertible, const MAX_RANK: usize = DEFAULT_MAX_RANK> Yields (position, DimRef<'a, Scalar>) pairs in row-major order at the logical-scalar level.
For sub-byte types, the innermost dimension is expanded by dimensions_per_value; use
.dims() when only the dimension proxies are needed.
Cost per next() is O(1) amortized (O(ndim) only on carry propagation).
Implements
Iterator, ExactSizeIterator, FusedIteratordimsAdapt this iterator to yield only dimension proxies, discarding positions.
pub fn dims(self) -> TensorViewDims<'a, Scalar, MAX_RANK> StructVectorOwning, non-resizable, SIMD-aligned vector.39
pub struct Vector<Scalar: StorageElement, Alloc: Allocator = Global> Size is fixed at construction. Uses StorageElement for element types, including sub-byte
packed types via Scalar::dimensions_per_value().
Read and write dimensions with get/set, which return errors rather than panic, or iterators.
Implements
Send, Sync, Drop, Default, Fill<Scalar>, CopyFrom<&[Scalar]>, IntoIterator, AsRef<[Scalar]>, PartialEq, PartialEq<[<Scalar as FloatConvertible>::DimScalar]>, Debug, Displayfrom_raw_parts_inConstruct a vector from raw parts, taking ownership of the allocation.
pub unsafe fn from_raw_parts_in(data: NonNull<Scalar>, dims: usize, alloc: Alloc) -> Self Safety
datamust point to an allocation obtained fromalloc, aligned tocrate::DEFAULT_ALIGNMENT, whose backing buffer is sized for the storage count implied bydims(Scalar::dimensions_to_values(dims)slots ofScalar).- The caller must not free the memory — this vector takes ownership.
empty_inAn empty vector that owns no allocation, holding only the given allocator.
pub fn empty_in(alloc: Alloc) -> Self zeros_inCreate a zero-initialized vector with the given number of dimensions.
pub fn zeros_in(dims: usize, alloc: Alloc) -> Result<Self, Error> full_inCreate a vector filled with value.
pub fn full_in(dims: usize, value: Scalar, alloc: Alloc) -> Result<Self, Error> ones_inCreate a vector filled with ones.
pub fn ones_in(dims: usize, alloc: Alloc) -> Result<Self, Error>
where
Scalar: NumberLike, uninitialized_inCreate an uninitialized vector.
pub unsafe fn uninitialized_in(dims: usize, alloc: Alloc) -> Result<Self, Error> Safety
The returned vector's contents are uninitialized. Reading from it before writing is undefined behavior.
from_scalars_inCreate a vector from a slice of scalars — f32 values.
pub fn from_scalars_in(scalars: &[f32], alloc: Alloc) -> Result<Self, Error>
where
Scalar: FloatConvertible, Each f32 value is converted through DimScalar::from_f32() before storage.
from_dims_inCreate a vector from a slice of per-dimension scalars.
pub fn from_dims_in(dim_values: &[Scalar::DimScalar], alloc: Alloc) -> Result<Self, Error>
where
Scalar: FloatConvertible, Each element in dim_values corresponds to one logical dimension.
*× 3Number of logical dimensions.
pub fn dims(&self) -> usize sizeNumber of logical dimensions; same as dims().
pub fn size(&self) -> usize size_valuesNumber of underlying storage values (Scalar instances).
pub fn size_values(&self) -> usize is_emptyReturns true if the vector has zero dimensions.
pub fn is_empty(&self) -> bool resizeResize in place to new_dims dimensions without moving storage.
pub fn resize(&mut self, new_dims: usize) -> Result<(), Error> Succeeds only when the packed storage fits capacity(), so as_ptr() stays stable — call
reserve first to grow. Returns Error::CapacityExceeded otherwise,
leaving the vector unchanged.
Examples
let mut v = Vector::<f32>::zeros(8)?; // capacity 8
v.resize(3)?; // shrink within capacity; as_ptr() unchanged
assert!(v.resize(9).is_err()); // beyond capacity
reserveGrow the allocated capacity() to hold at least new_dims dimensions, reallocating and copying the live elements if needed.
pub fn reserve(&mut self, new_dims: usize) -> Result<(), Error> A no-op when already large enough. Unlike
resize it may move storage, invalidating any raw pointer captured outside
the borrow system. Returns Error::AllocationFailed on failure, unchanged.
clearReset to an empty vector (dims() == 0) while keeping the allocated capacity().
pub fn clear(&mut self) as_ptrRaw pointer to the underlying data.
pub fn as_ptr(&self) -> *const Scalar as_mut_ptrMutable raw pointer to the underlying data.
pub fn as_mut_ptr(&mut self) -> *mut Scalar size_bytesSize in bytes.
pub fn size_bytes(&self) -> usize viewCreate an immutable view of this vector.
pub fn view(&self) -> VectorView<'_, Scalar, Alloc> spanCreate a mutable span of this vector.
pub fn span(&mut self) -> VectorSpan<'_, Scalar, Alloc> getGet the logical dimension at index; supports signed indexing.
pub fn get<AnyIndex: VectorIndex>(&self, index: AnyIndex) -> Result<Scalar::DimScalar, Error>
where
Scalar: FloatConvertible, Returns the native DimScalar type, e.g. f64 for Vector<f64> or i8 for
Vector<i4x2>. For sub-byte types, unpacks the appropriate sub-dimension from the packed
storage value.
Examples
Positive and Python-style negative indexing:
use numkong::vector::Vector;
let v = Vector::<f32>::from_dims(&[10.0, 20.0, 30.0, 40.0, 50.0]).unwrap();
assert_eq!(v.get(0_usize).unwrap(), 10.0);
assert_eq!(v.get(-1_i32).unwrap(), 50.0);
assert_eq!(v.get(-5_i32).unwrap(), 10.0);
// Out-of-range indices return an error instead of panicking.
assert!(v.get(5_usize).is_err());
assert!(v.get(-6_i32).is_err());
setSet the logical dimension at index.
pub fn set<AnyIndex: VectorIndex>(
&mut self,
index: AnyIndex,
value: Scalar::DimScalar,
) -> Result<(), Error>
where
Scalar: FloatConvertible, Accepts the native DimScalar type. For sub-byte types, reads the current packed value,
updates the targeted sub-dimension, and writes back the modified packed value.
Examples
use numkong::vector::Vector;
let mut v = Vector::<f32>::zeros(4).unwrap();
v.set(0_usize, 1.0).unwrap();
// Signed indices let you write to the tail without computing the length.
v.set(-1_i32, 4.0).unwrap();
assert_eq!(v.get(0_usize).unwrap(), 1.0);
assert_eq!(v.get(3_usize).unwrap(), 4.0);
as_sliceGet a slice of the underlying storage values.
pub fn as_slice(&self) -> &[Scalar] For sub-byte types this returns the packed storage values, not the logical dimensions.
as_mut_sliceGet a mutable slice of the underlying storage values.
pub fn as_mut_slice(&mut self) -> &mut [Scalar] iterReturns an iterator over the logical dimension values, yielding DimRef proxies.
pub fn iter(&self) -> VectorViewIterator<'_, Scalar>
where
Scalar: FloatConvertible, iter_mutReturns a mutable iterator over the logical dimension values, yielding DimMut proxies.
pub fn iter_mut(&mut self) -> VectorSpanIterator<'_, Scalar>
where
Scalar: FloatConvertible, into_tensorConvert this vector into a 1D tensor, transferring ownership without copying.
pub fn into_tensor<const MAX_RANK: usize>(self) -> Result<Tensor<Scalar, Alloc, MAX_RANK>, Error> zerosCreate a zero-initialized vector with the global allocator.
pub fn zeros(dims: usize) -> Result<Self, Error> fullCreate a vector filled with value.
pub fn full(dims: usize, value: Scalar) -> Result<Self, Error> onesCreate a vector filled with ones.
pub fn ones(dims: usize) -> Result<Self, Error>
where
Scalar: NumberLike, uninitializedCreate an uninitialized vector.
pub unsafe fn uninitialized(dims: usize) -> Result<Self, Error> Safety
The returned vector's contents are uninitialized. Reading from it before writing is undefined behavior.
from_scalarsCreate a vector from scalar f32 values.
pub fn from_scalars(scalars: &[f32]) -> Result<Self, Error>
where
Scalar: FloatConvertible, from_dimsCreate a vector from per-dimension scalars.
pub fn from_dims(dims: &[Scalar::DimScalar]) -> Result<Self, Error>
where
Scalar: FloatConvertible, cloneClone this vector, returning an error on allocation failure.
pub fn clone(&self) -> Result<Self, Error> popcountNumber of set bits across the entire vector.
pub fn popcount(&self) -> Result<u64, Error> any_settrue if at least one bit in the vector is set.
pub fn any_set(&self) -> Result<bool, Error> none_settrue if no bit in the vector is set.
pub fn none_set(&self) -> Result<bool, Error> all_settrue if every bit in the vector is set.
pub fn all_set(&self) -> Result<bool, Error> *× 3Check if all elements are within tolerance of other.
pub fn allclose<OtherAlloc: Allocator>(
&self,
other: &Vector<Scalar, OtherAlloc>,
atol: f64,
rtol: f64,
) -> bool Returns false if dimensions differ; otherwise checks the formula |a − b| ≤ atol + rtol ×
|b| per element.
TraitVectorIndexTrait for vector index types.1
pub trait VectorIndex: Sealed + Copy Supports signed integers; negative counts from the end.
Implementors
impl VectorIndex for usizeimpl VectorIndex for u8impl VectorIndex for u16impl VectorIndex for u32impl VectorIndex for u64impl VectorIndex for isizeimpl VectorIndex for i8impl VectorIndex for i16impl VectorIndex for i32impl VectorIndex for i64
resolveResolve this index to a usize offset, or None if out of bounds.
fn resolve(self, len: usize) -> Option<usize> StructVectorSpanMutable, possibly strided, non-owning view into a vector.19
pub struct VectorSpan<'a, Scalar: StorageElement, Alloc = Global> VectorSpan is the read-write counterpart of [VectorView]: it still performs zero-copy
borrowing via a raw pointer, dimension count, and byte stride, but additionally allows element
writes through set, fill, and iter_mut. Spans are typically obtained via
Vector::span or a mutable slice of a tensor row.
Like views, spans support signed VectorIndex indexing, negative strides via
VectorSpan::as_view + VectorView::rev, and Python-style slicing through their view
projection. The 'a lifetime mirrors the owner of the underlying memory, and Rust's borrow
checker prevents aliasing a single span with any other reference for the duration of 'a.
Implements
Send, Sync, Fill<Scalar>, CopyFrom<&'b VectorView<'_, Scalar, SourceAlloc>>, IntoIterator, PartialEq, Debugfrom_raw_partsCreate a mutable view from a raw pointer, dimension count, and byte stride, reporting Global as its allocator.
pub unsafe fn from_raw_parts(data: *mut Scalar, dims: usize, stride: isize) -> Self Safety
datamust be valid for reads and writes ofdimselements at the given stride.- The pointed-to memory must outlive
'a. stridemust be non-zero for non-empty views.- No other references to the memory may exist for the duration of
'a.
from_raw_parts_inLike VectorSpan::from_raw_parts, reporting allocator as the span's allocator.
pub unsafe fn from_raw_parts_in(
data: *mut Scalar,
dims: usize,
stride: isize,
allocator: &'a Alloc,
) -> Self Safety
The same as for VectorSpan::from_raw_parts.
allocatorThe allocator of the vector this span borrows, or Global for foreign memory.
pub fn allocator(&self) -> &'a Alloc *× 2Number of logical dimensions; alias for dims.
pub fn size(&self) -> usize is_*× 3Returns true if empty.
stride_bytesStride in bytes.
pub fn stride_bytes(&self) -> isize as_*_ptr× 2Get the underlying pointer.
pub fn as__ptr(&self) -> *const Scalar as_mut_ptrGet the mutable underlying pointer.
pub fn as_mut_ptr(&mut self) -> *mut Scalar as_viewReborrow as an immutable view, sharing the same data pointer and stride.
pub fn as_view(&self) -> VectorView<'_, Scalar, Alloc> getGet element at index.
pub fn get<AnyIndex: VectorIndex>(&self, index: AnyIndex) -> Result<Scalar::DimScalar, Error>
where
Scalar: FloatConvertible, setSet the element at index.
pub fn set<AnyIndex: VectorIndex>(
&mut self,
index: AnyIndex,
value: Scalar::DimScalar,
) -> Result<(), Error>
where
Scalar: FloatConvertible, Accepts the native DimScalar type. For sub-byte types, uses value_index for stride-based
pointer walks to avoid buffer overwrite.
as_contiguous_sliceGet a contiguous slice, if this span is contiguous.
pub fn as_contiguous_slice(&self) -> Option<&[Scalar]> as_contiguous_slice_mutGet a mutable contiguous slice, if this span is contiguous.
pub fn as_contiguous_slice_mut(&mut self) -> Option<&mut [Scalar]> *× 2Returns an iterator over logical dimension values, yielding DimRef proxies.
pub fn iter(&self) -> VectorViewIterator<'_, Scalar>
where
Scalar: FloatConvertible, iter_mutReturns a mutable iterator over logical dimension values, yielding DimMut proxies.
pub fn iter_mut(&mut self) -> VectorSpanIterator<'_, Scalar>
where
Scalar: FloatConvertible, popcountNumber of set bits across the entire vector span.
pub fn popcount(&self) -> Result<u64, Error> any_settrue if at least one bit in the vector span is set.
pub fn any_set(&self) -> Result<bool, Error> none_settrue if no bit in the vector span is set.
pub fn none_set(&self) -> Result<bool, Error> all_settrue if every bit in the vector span is set.
pub fn all_set(&self) -> Result<bool, Error> StructVectorSpanIteratorStride-aware mutable iterator over logical dimensions, yielding DimMut proxies.
pub struct VectorSpanIterator<'a, Scalar: FloatConvertible> For normal types (dimensions_per_value=1), yields one proxy per storage value.
For sub-byte types, each proxy performs a read-modify-write on drop.
Implements ExactSizeIterator, FusedIterator, and DoubleEndedIterator.
Implements
Iterator, ExactSizeIterator, FusedIterator, DoubleEndedIteratorStructVectorViewImmutable, possibly strided, non-owning view into a vector.13
pub struct VectorView<'a, Scalar: StorageElement, Alloc = Global> VectorView is a zero-copy borrow: it holds a raw pointer, a dimension count, and a byte stride
between consecutive logical elements. It never frees its memory and is tied to the lifetime 'a
of whatever owns the storage — typically a Vector obtained via Vector::view, or a row /
column of a tensor.
Because the stride is stored in bytes and may be negative, views can walk memory in either
direction, skip entries via VectorView::strided, or expose a reversed iteration order
via VectorView::rev.
Use VectorView when only read access is needed. Its mutable counterpart is VectorSpan,
which offers the same striding semantics plus element writes. Both types support the
VectorIndex trait, so view.get(0_usize), view.get(-1_i32), and friends all resolve via
the same Python-style rules.
Implements
Send, Sync, Clone, Copy, CopyFrom<&'b VectorView<'_, Scalar, SourceAlloc>>, IntoIterator, PartialEq, Debugfrom_raw_partsCreate a view from a raw pointer, dimension count, and byte stride, reporting Global as its allocator.
pub unsafe fn from_raw_parts(data: *const Scalar, dims: usize, stride: isize) -> Self Safety
datamust be valid for reads ofdimselements at the given stride.- The pointed-to memory must outlive
'a. stridemust be non-zero for non-empty views.
from_raw_parts_inLike VectorView::from_raw_parts, reporting allocator as the view's allocator.
pub unsafe fn from_raw_parts_in(
data: *const Scalar,
dims: usize,
stride: isize,
allocator: &'a Alloc,
) -> Self Safety
The same as for VectorView::from_raw_parts.
allocatorThe allocator of the vector this view borrows, or Global for foreign memory.
pub fn allocator(&self) -> &'a Alloc stride_bytesStride in bytes between consecutive elements.
pub fn stride_bytes(&self) -> isize is_contiguousReturns true if elements are stored contiguously (stride == sizeof(Scalar)).
pub fn is_contiguous(&self) -> bool as_contiguous_sliceGet a contiguous slice, if this view is contiguous.
pub fn as_contiguous_slice(&self) -> Option<&'a [Scalar]> getGet element at index; supports signed indexing.
pub fn get<AnyIndex: VectorIndex>(&self, index: AnyIndex) -> Result<Scalar::DimScalar, Error>
where
Scalar: FloatConvertible, Returns the native DimScalar type. For sub-byte types, uses value_index for stride-based
pointer walks to avoid buffer overread.
revCreate a reversed view by negating the stride and pointing to the last element.
pub fn rev(&self) -> Self The returned view has the same number of dimensions but iterates in the opposite direction. For an empty view, returns a copy unchanged.
stridedCreate a sub-view with start, end, and step — Python-style slicing.
pub fn strided(&self, start: usize, end: usize, step: isize) -> Result<Self, Error> Supports negative steps for reverse iteration. step must be non-zero.
Returns an error if start or end exceed dims(), or if step == 0.
popcountNumber of set bits across the entire vector view.
pub fn popcount(&self) -> Result<u64, Error> any_settrue if at least one bit in the vector view is set.
pub fn any_set(&self) -> Result<bool, Error> none_settrue if no bit in the vector view is set.
pub fn none_set(&self) -> Result<bool, Error> all_settrue if every bit in the vector view is set.
pub fn all_set(&self) -> Result<bool, Error> StructVectorViewIteratorStride-aware immutable iterator over logical dimensions, yielding DimRef proxies.
pub struct VectorViewIterator<'a, Scalar: FloatConvertible> For normal types (dimensions_per_value=1), yields one proxy per storage value.
For sub-byte types, unpacks each storage value and yields sub-dimensions individually.
Implements ExactSizeIterator, FusedIterator, and DoubleEndedIterator.
Implements
Iterator, ExactSizeIterator, FusedIterator, DoubleEndedIteratorStructDimLocationWhere one logical dimension lives inside packed storage.2
pub struct DimLocation Produced by StorageElement::locate_dim. For the full-byte types both fields degenerate —
value_index is the dimension index and sub_index is always zero — so code written against
this stays correct for every scalar without branching on the packing factor.
Fields
value_index | usize | Index of the storage value holding the dimension. |
|---|---|---|
sub_index | usize | Position of the dimension within that storage value. |
Implements
Debug, Clone, Copy, StructuralPartialEq, PartialEq, Eqread_fromRead this dimension out of the storage value at slot.
pub unsafe fn read_from<Scalar: FloatConvertible>(self, slot: *const Scalar) -> Scalar::DimScalar Safety
slot must point at the storage value this location addresses — for a contiguous buffer
that is base.add(self.value_index), and for a strided one the corresponding stride step.
write_intoWrite value into this dimension, leaving the others sharing the storage value untouched.
pub unsafe fn write_into<Scalar: FloatConvertible>(
self,
slot: *mut Scalar,
value: Scalar::DimScalar,
) Sub-byte dimensions cannot be addressed individually, so a write is a read-modify-write of the whole storage value. Doing it here rather than at each call site is what keeps a caller from clobbering the neighbours that share the byte.
Safety
slot must point at the storage value this location addresses, and be writable.
StructBitRefImmutable reference to a single bit within a packed byte.1
pub struct BitRef<'a> Obtained by iterating over or indexing into a Vector<u1x8>. The mask selects which of the
eight bits the proxy represents; the byte itself is shared with the seven sibling proxies for
the same byte.
Examples
use numkong::vector::Vector;
use numkong::types::u1x8;
let mut v = Vector::<u1x8>::zeros(8).unwrap();
v.set(3_usize, 1).unwrap();
// Immutable iteration yields BitRef-like proxies that deref to the bit value.
let bits: Vec<u8> = v.iter().map(|b| *b).collect();
assert_eq!(bits, vec![0, 0, 0, 1, 0, 0, 0, 0]);
*× 2Read the bit as bool.
pub fn get(&self) -> bool StructBitRefMutMutable reference to a single bit within a packed byte.1
pub struct BitRefMut<'a> Obtained via mutable iteration / indexing of a Vector<u1x8>. Writes OR or AND the stored byte
so sibling bits are preserved; the mask selects which bit this proxy represents.
Examples
use numkong::vector::Vector;
use numkong::types::u1x8;
let mut v = Vector::<u1x8>::zeros(8).unwrap();
for (i, mut bit) in v.iter_mut().enumerate() {
*bit = (i % 2 == 0) as u8;
}
assert_eq!(v.get(0_usize).unwrap(), 1);
assert_eq!(v.get(1_usize).unwrap(), 0);
setSet the bit.
pub fn set(&self, value: bool) Constants
DEFAULT_MAX_RANKDefault maximum rank for tensors.
pub const DEFAULT_MAX_RANK: usize = 8;