Rust · Scalar Types

Scalar Types

use numkong::bf16;use numkong::e2m1x2;use numkong::e2m3;use numkong::e3m2;use numkong::e4m3;use numkong::e5m2;use numkong::f16;use numkong::i4x2;use numkong::u1x8;use numkong::u4x2;use numkong::FloatConvertible;use numkong::FloatLike;use numkong::NumberLike;use numkong::StorageElement;use numkong::Ue4m3;use numkong::Ue8m0;use numkong::Roots;use numkong::CastDType;use numkong::CastOps;use numkong::DenseToScaledOps;use numkong::BlockScaledDescriptor;use numkong::BlockScaledFormat;use numkong::Mxfp4;use numkong::Mxfp6E2m3;use numkong::Mxfp6E3m2;use numkong::Mxfp8E4m3;use numkong::Mxfp8E5m2;use numkong::Mxint8;use numkong::Nvfp4;use numkong::types::complex;use numkong::*; 8.0.0-rc.1 · b1f866ab

The scalar wrappers are storage-first types. They are not decorative aliases over f32.

TypeLayoutBytesRangeInfNaN
f161+5+102±65504yesyes
bf161+8+72±3.4×10³⁸yesyes
e4m31+4+31±448noyes
e5m21+5+21±57344yesyes
e2m31+2+3 (6 bit)1±7.5nono
e3m21+3+2 (6 bit)1±28nono
u1x88 packed bits10–1 per bit……
u4x22×4-bit uint10–15 per nib……
i4x22×4-bit int1−8–7 per nib……

The trait hierarchy documents intent:

  • StorageElement — raw storable element type.
  • NumberLike — adds numeric conversion and ordering.
  • FloatConvertible — adds unpacking and float-domain conversion.

The output type is intentionally wider than the storage type for many operations. For example, i8::dot returns i32. f32::dot returns a wider accumulator type. Moments reductions widen even more aggressively.

§ Type Casting

The cast function performs bulk conversion between contiguous slices. Any pair of types that implement CastDType (all NumberLike scalars) can be converted.

use numkong::{cast, f16, bf16};

let src: Vec<f32> = vec![1.0, 2.0, 3.0];
let mut dst: Vec<f16> = vec![f16::from(0.0_f32); 3];
cast(&src, &mut dst).unwrap();
assert!((dst[0].to_f32() - 1.0).abs() < 0.01);

Tensor, TensorView, and TensorSpan expose casting via the CastOps trait. cast() allocates a new tensor; cast_into() writes into a pre-allocated TensorSpan. Strided and non-contiguous views are supported: the implementation scans strides from the innermost dimension outward to find the longest contiguous tail, then walks the outer dimensions and casts each contiguous block in a single kernel call.

use numkong::{Tensor, f16};

let src = Tensor::<f32>::full(&[4, 4], 1.0).unwrap();
let mut dst = Tensor::<f16>::zeros(&[4, 4]).unwrap();
src.view().cast_into(&mut dst.span()).unwrap();

API

Types

f16cHalf-precision (32-bit) complex number — two f16 components.
types.rs:2206 ↗
pub type f16c = complex<f16>;

Kernel outputs are widened to f32c.

bf16cBFloat16 (32-bit) complex number — two bf16 components.
types.rs:2208 ↗
pub type bf16c = complex<bf16>;

Kernel outputs widened to f32c.

f32cSingle-precision (64-bit) complex number — two f32 components.
types.rs:2210 ↗
pub type f32c = complex<f32>;
f64cDouble-precision (128-bit) complex number — two f64 components.
types.rs:2212 ↗
pub type f64c = complex<f64>;
Structbf16BFloat16 (16-bit) floating-point number — truncated IEEE 754 single-precision.69
types.rs:293 ↗
pub struct bf16(pub u16);

Layout: sign(1) + exponent(8) + mantissa(7), bias=127. Range: ±3.39×10³⁸, same dynamic range as f32, epsilon at 1.0 ≈ 7.81×10⁻³. 32 514 of 65 280 finite values (49.8%) fall in [−1, +1]. Wider dynamic range than f16 but lower precision, 7 vs 10 mantissa bits.

Fields

0u16

Examples

use numkong::bf16;

let brain = bf16::from_f32(3.14);
let float = brain.to_f32();

Implements

ProbabilitySimilarity, Reductions, SpatialSimilarity, FloatLike, Attention, AttentionRope, CastDType, Bilinear, Mahalanobis, Dot, VDot, EachScale, EachSum, EachBlend, EachFma, EachSwiGlu, EachRmsNorm, EachRmsCast, MaxSim, KullbackLeibler, JensenShannon, ReduceMoments, ReduceMinMax, Angular, Euclidean, Dots, Angulars, Euclideans, Clone, Copy, StructuralPartialEq, PartialEq, Eq, Default, Debug, Display, LowerHex, UpperHex, Binary, Add, Sub, Mul, Div, Neg, PartialOrd, From<f32>, From<bf16>, StorageElement, NumberLike, FloatConvertible
attention_packed_gradientsCompute the gradients of attention_packed with respect to the queries, keys and values over the task window tasks_begin..tasks_end of the (segment, kv_head) grid, the end clipped to the grid.
types.rs:574 ↗
pub unsafe fn attention_packed_gradients(
    head_count: usize,
    heads: usize,
    depth: usize,
    query_offsets: *const u32,
    query_token_count: usize,
    scale: f32,
    keys_before: usize,
    keys_after: usize,
    queries: *const Self,
    query_stride: usize,
    key_value_packed: *const u8,
    output: *const f32,
    output_gradient: *const f32,
    output_stride: usize,
    log_sum_exp: *const f32,
    query_gradient: *mut f32,
    query_gradient_stride: usize,
    key_gradient: *mut f32,
    value_gradient: *mut f32,
    key_value_gradient_stride: usize,
    tasks_begin: usize,
    tasks_end: usize,
) -> Result<(), Error>

output and log_sum_exp are the forward's results. The query gradient holds one row of head_count * depth values per query token, spaced query_gradient_stride bytes apart. Key and value gradients hold one row of heads * depth values per key token at key_offsets[segment] + token of the offsets the cache was packed with, spaced key_value_gradient_stride bytes apart; rows past a segment's key count are never written, and all others are overwritten.

Safety

  • the forward's safety contract holds for queries, key_value_packed, query_offsets and query_token_count
  • every gradient buffer must be writable for its extent, and output and output_gradient share output_stride
ZEROPositive zero.
types.rs:297 ↗
pub const ZERO: Self = _;
ONEPositive one.
types.rs:300 ↗
pub const ONE: Self = _;
NEG_ONENegative one.
types.rs:303 ↗
pub const NEG_ONE: Self = _;
NANQuiet NaN, i.e.
types.rs:305 ↗
pub const NAN: Self = _;

Not a Number.

from_f32Converts an f32 value to bf16.
types.rs:318 ↗
pub fn from_f32(value: f32) -> Self
fn from_f32(v: f32) -> Self

Convert from f32 to this type.

Out-of-range values saturate.

Examples

use numkong::bf16;
// bf16 matches f32's ±3.39e38 range but with only 7 bits of mantissa.
let brain = bf16::from_f32(1.0e30);
assert!((brain.to_f32() - 1.0e30).abs() < 1.0e28);
to_*_f32× 3Converts this value back to f32.
types.rs:326 ↗
pub fn to__f32(self) -> f32

Examples

use numkong::f16;
let half = f16::from_f32(-2.5);
assert_eq!(half.to_f32(), -2.5);
is_*_nan× 6Returns true if this value is NaN.
types.rs:334 ↗
pub fn is__nan(self) -> bool

E2M3FN has no infinities - all special values are NaN.

is_*_infinite× 4Returns true if this value is positive or negative infinity.
types.rs:338 ↗
pub fn is__infinite(self) -> bool

E2M3FN has no infinities.

is_*_finite× 6Returns true if this number is neither infinite nor NaN.
types.rs:342 ↗
pub fn is__finite(self) -> bool

Note: E2M3FN format has no infinities or NaN.

Note: the E4M3 format has no infinities at all.

*× 5Returns the absolute value of self.
types.rs:346 ↗
pub fn abs(self) -> Self
attention_pack_*_pack_size× 3Returns bytes enough to pack token_count keys in segment_count segments, however split.
types.rs:441 ↗

Inherited from Attention

fn attention_pack__pack_size(
    heads: usize,
    depth: usize,
    token_count: usize,
    segment_count: usize,
) -> Result<usize, Error>
attention_packed_*_packed_shape× 3Reads the KV-cache geometry — heads, depth, segments — from the packed header. # Safety packed must point to a buffer produced by attention_pack.
types.rs:462 ↗

Inherited from Attention

unsafe fn attention_packed__packed_shape(packed: *const u8) -> Result<(usize, usize, usize), Error>
attention_*_pack× 3Pack a window of the (segment, kv_head) task grid into the KV-cache blob. # Safety - k / v must point to token matrices with key_stride / value_stride byte rows covering every token addressed by key_offsets + key_lengths - key_offsets holds segment_count + 1 non-decreasing slot boundaries, and key_lengths is null or holds one count per segment, at most its slot's width - key_value_packed must have at least attention_pack_size(..) bytes
types.rs:476 ↗

Inherited from Attention

unsafe fn attention__pack(
    heads: usize,
    depth: usize,
    key_offsets: *const u32,
    key_lengths: *const u32,
    segment_count: usize,
    keys: *const Self,
    key_stride: usize,
    values: *const Self,
    value_stride: usize,
    key_value_packed: *mut u8,
    tasks_begin: usize,
    tasks_end: usize,
) -> Result<(), Error>

Windows run in any order: the one starting at task 0 also writes the header and directory, which no window reads.

attention_*_packed× 3Compute attention over the half-open task window tasks_begin..tasks_end of the (query token, head) grid, task token * head_count + head, the end clipped to the grid.
types.rs:511 ↗

Inherited from Attention

unsafe fn attention__packed(
    head_count: usize,
    heads: usize,
    depth: usize,
    query_offsets: *const u32,
    query_token_count: usize,
    scale: f32,
    keys_before: usize,
    keys_after: usize,
    queries: *const Self,
    query_stride: usize,
    key_value_packed: *const u8,
    output: *mut f32,
    output_stride: usize,
    log_sum_exp: *mut f32,
    tasks_begin: usize,
    tasks_end: usize,
) -> Result<(), Error>

Each segment's queries align to the end of its keys: row r of a segment with q queries and k keys sits at position p = r + k - q and sees key j when p - keys_before <= j <= p + keys_after. usize::MAX leaves a side unbounded, so causal is (usize::MAX, 0), a sliding window of w keys is (w - 1, 0) and bidirectional is (usize::MAX, usize::MAX). Rows that see no key are written as zeros.

Safety

  • key_value_packed must have been produced by attention_pack with matching geometry
  • queries rows addressed by query_offsets must be valid, output writable with output_stride byte rows
  • query_token_count equals query_offsets[segments]
  • log_sum_exp is null or writable for one value per query token and head
attention_rope_*_rope_into× 2Rotates a 2D [rows,head_count × depth] tensor in place using the [rows,depth/2] cos/sin angle grids, shared across heads, for an even depth of channels per head.
types.rs:1873 ↗

Inherited from AttentionRope

fn attention_rope__rope_into<XMut, const RX: usize>(
    x: &mut XMut,
    cos: &[f32],
    sin: &[f32],
    head_count: usize,
    depth: usize,
) -> Result<(), Error>
where
    XMut: TensorMut<Self, RX> + ?Sized,

The row stride is read from the tensor, so x may be a non-contiguous sub-span, for example the Q or K column-section of a fused QKV buffer. Returns Err on a shape mismatch.

bilinearComputes the bilinear form aᵀ × C × b.
types.rs:252 ↗

Inherited from Bilinear

fn bilinear(a: &[Self], b: &[Self], c: &[Self]) -> Result<Self::Output, Error>

Arguments

  • a - First vector of length n
  • b - Second vector of length n
  • c - Metric tensor, symmetric [n,n] matrix in row-major order, flattened to length n²

Errors

Error::InvalidShape for empty vectors, Error::ShapeMismatch if lengths are incompatible, or Error::KernelFailed carrying the kernel's status.

mahalanobisComputes the Mahalanobis distance √((a−b)ᵀ × C × (a−b)).
types.rs:534 ↗

Inherited from Mahalanobis

fn mahalanobis(a: &[Self], b: &[Self], c: &[Self]) -> Result<Self::Output, Error>

Arguments

  • a - First vector of length n
  • b - Second vector of length n
  • c - Inverse covariance matrix, a symmetric [n,n] matrix in row-major order, flattened to length n²

Errors

Error::InvalidShape for empty vectors, Error::ShapeMismatch if lengths are incompatible, or Error::KernelFailed carrying the kernel's status.

dotComputes the dot product of two equally long slices.
types.rs:333 ↗

Inherited from Dot

fn dot(first: &[Self], second: &[Self]) -> Result<Self::Output, Error>
innerAlias for dot.
types.rs:268 ↗

Inherited from Dot

fn inner(first: &[Self], second: &[Self]) -> Result<Self::Output, Error>
vdotHermitian inner product.
types.rs:644 ↗

Inherited from VDot

fn vdot(first: &[Self], second: &[Self]) -> Result<Self::Output, Error>

On real-valued types this falls back to Dot::dot; on complex types it returns ∑ᵢ conj(aᵢ) × bᵢ computed in the widened accumulator described by Dot::Output.

each_*_scale× 6Writes resultᵢ = α × aᵢ + β into the pre-sized output slice.
types.rs:1226 ↗

Inherited from EachScale

fn each__scale(a: &[Self], alpha: f32, beta: f32, result: &mut [Self]) -> Result<(), Error>

Both slices, a and result, must have identical length — the kernel does not allocate.

Examples

use numkong::EachScale;
let input = [1.0_f32, 2.0, 3.0];
let mut output = [0.0_f32; 3];
// Rescale to [-1, 1]: alpha = 2/(max-min) = 1.0, beta = -1 - 1*min = -2.0
f32::each_scale(&input, 1.0, -2.0, &mut output).unwrap();
assert_eq!(output, [-1.0, 0.0, 1.0]);
each_scale_*_scale_inplace× 6In-place affine: dataᵢ = α × dataᵢ + β.
types.rs:1242 ↗

Inherited from EachScale

fn each_scale__scale_inplace(data: &mut [Self], alpha: f32, beta: f32) -> Result<(), Error>

Both source and destination pointers are derived from the single &mut, so no aliased &[Self] + &mut [Self] over the same storage is formed.

each_*_sum× 6Writes resultᵢ = aᵢ + bᵢ into the pre-sized output slice.
types.rs:1917 ↗

Inherited from EachSum

fn each__sum(a: &[Self], b: &[Self], result: &mut [Self]) -> Result<(), Error>
each_sum_*_sum_inplace× 6In-place sum: dataᵢ = dataᵢ + otherᵢ.
types.rs:1933 ↗

Inherited from EachSum

fn each_sum__sum_inplace(data: &mut [Self], other: &[Self]) -> Result<(), Error>

data is both the a operand and the result; its source and destination pointers come from the single &mut, while other is disjoint storage — no aliased &[Self] + &mut [Self] over the same buffer is formed.

each_*_blend× 6Writes resultᵢ = α × aᵢ + β × bᵢ into the pre-sized output slice.
types.rs:2621 ↗

Inherited from EachBlend

fn each__blend(
    a: &[Self],
    b: &[Self],
    alpha: f32,
    beta: f32,
    result: &mut [Self],
) -> Result<(), Error>
each_blend_*_blend_inplace× 6In-place blend: dataᵢ = α × dataᵢ + β × otherᵢ.
types.rs:2639 ↗

Inherited from EachBlend

fn each_blend__blend_inplace(data: &mut [Self], other: &[Self], alpha: f32, beta: f32) -> Result<(), Error>

data is both the a operand and the result; its source and destination pointers come from the single &mut, while other is disjoint storage — no aliased &[Self] + &mut [Self] over the same buffer is formed.

each_*_fma× 6Writes resultᵢ = α × aᵢ × bᵢ + β × cᵢ into the pre-sized output slice.
types.rs:3452 ↗

Inherited from EachFma

fn each__fma(
    a: &[Self],
    b: &[Self],
    c: &[Self],
    alpha: f32,
    beta: f32,
    result: &mut [Self],
) -> Result<(), Error>
each_fma_*_fma_inplace× 6In-place fused multiply-add with the c operand bound to a: dataᵢ = α × dataᵢ × bᵢ + β × dataᵢ.
types.rs:3472 ↗

Inherited from EachFma

fn each_fma__fma_inplace(data: &mut [Self], b: &[Self], alpha: f32, beta: f32) -> Result<(), Error>

data is the a operand, the c operand, and the result — all derived from the single &mut, while b is disjoint storage. This matches out-of-place mul_tensor, which wires c = self and is the only in-place FMA caller. No aliased &[Self] + &mut [Self] over the same buffer is formed.

swiglu_*_into× 2Fused SwiGLU of 2D tensors: y = silu(gate_scale × gate) × up × output_scale.
types.rs:4610 ↗

Inherited from EachSwiGlu

fn swiglu__into<GIn, UIn, YOut, const RG: usize, const RU: usize, const RY: usize>(
    gate: &GIn,
    up: Option<&UIn>,
    y: &mut YOut,
    gate_scale: f32,
    output_scale: f32,
) -> Result<(), Error>
where
    GIn: TensorRef<Self, RG> + ?Sized,
    UIn: TensorRef<Self, RU> + ?Sized,
    YOut: TensorMut<Self, RY> + ?Sized,

Strides are read from the tensors, so gate, up, and y may be independent strided sub-spans, for example the two column halves of a [rows,2×columns] gate|up buffer, while up = None reduces to plain SiLU. Returns Err on a shape mismatch.

rmsnorm_*_into× 2Grouped RMSNorm of a 2D [rows,groups×columns] tensor into y of the same shape.
types.rs:4852 ↗

Inherited from EachRmsNorm

fn rmsnorm__into<XIn, YOut, const RX: usize, const RY: usize>(
    x: &XIn,
    gamma: Option<&[f32]>,
    y: &mut YOut,
    groups: usize,
    epsilon: f32,
) -> Result<(), Error>
where
    XIn: TensorRef<Self, RX> + ?Sized,
    YOut: TensorMut<Self, RY> + ?Sized,

Row strides are read from the tensors, so x and y may be non-contiguous sub-spans, for example a strided section of a fused activation buffer. gamma is an optional per-column gain of length columns (None = unit scale). Returns Err on a shape mismatch.

rmscast_*_into× 6Grouped RMSNorm of a 2D [rows,groups×columns] tensor of Self::Input into y, a tensor of Self of the same shape, with ε added to the mean square of the raw input.
types.rs:5020 ↗

Inherited from EachRmsCast

fn rmscast__into<XIn, YOut, const RX: usize, const RY: usize>(
    x: &XIn,
    gamma: Option<&[f32]>,
    y: &mut YOut,
    groups: usize,
    epsilon: f32,
) -> Result<(), Error>
where
    XIn: TensorRef<Self::Input, RX> + ?Sized,
    YOut: TensorMut<Self, RY> + ?Sized,

Returns Err on a shape mismatch.

maxsim_pack_*_pack_size× 2Returns the packed buffer size in bytes for vectors vectors of given depth.
types.rs:328 ↗

Inherited from MaxSim

fn maxsim_pack__pack_size(vectors: usize, depth: usize) -> Result<usize, Error>
maxsim_packed_*_packed_shape× 2Reads the packed vector count and depth from the buffer header. # Safety packed must point to a buffer produced by maxsim_pack.
types.rs:334 ↗

Inherited from MaxSim

unsafe fn maxsim_packed__packed_shape(packed: *const u8) -> Result<(usize, usize), Error>
maxsim_*_pack× 2Pack vectors into backend-specific quantized format.
types.rs:341 ↗

Inherited from MaxSim

unsafe fn maxsim__pack(
    data: *const Self,
    vectors: usize,
    depth: usize,
    stride: usize,
    packed: *mut u8,
) -> Result<(), Error>

Packing fuses no transposition, so depth-major vectors are transposed in a separate pass first.

Safety

  • data must point to vectors rows of depth elements, byte stride stride
  • packed must have at least maxsim_pack_size(vectors, depth) bytes
maxsim_*_packed× 2Compute MaxSim score on pre-packed buffers.
types.rs:360 ↗

Inherited from MaxSim

unsafe fn maxsim__packed(
    queries: *const u8,
    documents: *const u8,
    query_count: usize,
    document_count: usize,
    depth: usize,
    result: *mut Self::Score,
) -> Result<(), Error>

Safety

  • Both buffers must have been produced by maxsim_pack with matching depth
  • result must point to valid, writable memory for Self::Score
kullbackleiblerComputes the Kullback-Leibler divergence of a from b.
types.rs:172 ↗

Inherited from KullbackLeibler

fn kullbackleibler(a: &[Self], b: &[Self]) -> Result<Self::Output, Error>
klAlias for kullbackleibler.
types.rs:107 ↗

Inherited from KullbackLeibler

fn kl(a: &[Self], b: &[Self]) -> Result<Self::Output, Error>
jensenshannonComputes the Jensen-Shannon divergence between a and b.
types.rs:274 ↗

Inherited from JensenShannon

fn jensenshannon(a: &[Self], b: &[Self]) -> Result<Self::Output, Error>
jsAlias for jensenshannon.
types.rs:209 ↗

Inherited from JensenShannon

fn js(a: &[Self], b: &[Self]) -> Result<Self::Output, Error>
reduce_momentsCompute (sum, sum_of_squares) for data with the given stride in bytes.
types.rs:573 ↗

Inherited from ReduceMoments

fn reduce_moments(
    data: &[Self],
    stride: usize,
) -> Result<(Self::SumOutput, Self::SumSqOutput), Error>

Use stride = size_of::<Self>() for contiguous data.

Reads data.len() logical elements starting at data.as_ptr(), advancing by stride between each — pass size_of::<Self>() for contiguous storage.

reduce_minmaxReturns Ok(Some(MinMaxResult)) for the given data with the specified stride, or Ok(None) if all elements are NaN.
types.rs:894 ↗

Inherited from ReduceMinMax

fn reduce_minmax(data: &[Self], stride: usize) -> Result<Option<MinMaxResult<Self::Output>>, Error>

Reads data.len() logical elements starting at data.as_ptr(), advancing by stride between each — pass size_of::<Self>() for contiguous storage.

angularComputes the angular distance between two equally long slices.
types.rs:432 ↗

Inherited from Angular

fn angular(a: &[Self], b: &[Self]) -> Result<Self::Output, Error>
cosineAlias for angular.
types.rs:367 ↗

Inherited from Angular

fn cosine(a: &[Self], b: &[Self]) -> Result<Self::Output, Error>
sqeuclideanSquared Euclidean distance, i.e.
types.rs:759 ↗

Inherited from Euclidean

fn sqeuclidean(a: &[Self], b: &[Self]) -> Result<Self::SqEuclideanOutput, Error>

L2². Faster than euclidean for comparisons.

euclideanEuclidean distance, i.e.
types.rs:776 ↗

Inherited from Euclidean

fn euclidean(a: &[Self], b: &[Self]) -> Result<Self::EuclideanOutput, Error>

L2. True metric distance.

dots_pack_*_pack_size× 10Returns the size in bytes needed for the packed B matrix buffer.
types.rs:1172 ↗

Inherited from Dots

fn dots_pack__pack_size(columns: usize, depth: usize) -> Result<usize, Error>
dots_packed_*_packed_shape× 10Reads the packed B matrix's columns and depth from its header. # Safety packed must point to a buffer produced by dots_pack.
types.rs:1177 ↗

Inherited from Dots

unsafe fn dots_packed__packed_shape(packed: *const u8) -> Result<(usize, usize), Error>
dots_*_pack× 10Packs the B matrix into an optimized backend-specific layout.
types.rs:1184 ↗

Inherited from Dots

unsafe fn dots__pack(
    matrix: *const Self,
    columns: usize,
    depth: usize,
    matrix_stride: usize,
    packed: *mut u8,
    columns_begin: usize,
    columns_end: usize,
) -> Result<(), Error>

Packing fuses no transposition, so a transposed B is transposed in a separate pass first.

Safety

  • b must point to valid memory for columns * depth elements
  • packed must point to a buffer of at least dots_pack_size(columns, depth) bytes
dots_*_packed× 10Computes C = A × Bᵀ using packed B.
types.rs:1207 ↗

Inherited from Dots

unsafe fn dots__packed(
    queries: *const Self,
    packed: *const u8,
    output: *mut Self::Accumulator,
    rows: usize,
    columns: usize,
    depth: usize,
    query_stride: usize,
    output_stride: usize,
) -> Result<(), Error>

Safety

  • a must point to valid memory for rows * depth elements with given stride
  • packed must be a buffer filled by dots_pack
  • c must point to valid memory for rows × columns elements with given stride
dots_*_symmetric× 10Computes C = A × Aᵀ where C is symmetric.
types.rs:1234 ↗

Inherited from Dots

unsafe fn dots__symmetric(
    vectors: *const Self,
    vector_count: usize,
    depth: usize,
    stride: usize,
    result: *mut Self::Accumulator,
    result_stride: usize,
    rows_begin: usize,
    rows_end: usize,
) -> Result<(), Error>

Given input matrix A of shape [n,k], computes the symmetric matrix of all pairwise dot products. Only the upper triangle is computed, then mirrored to the lower triangle.

Safety

  • vectors must point to valid memory for vector_count × depth elements with given stride
  • result must point to valid memory for vector_count×vector_count elements, given stride
  • Strides are in bytes, not elements
  • rows_begin <= rows_end; rows_end is clamped to vector_count
angulars_*_packed× 9Computes angular distances between A rows and packed B columns.
types.rs:1234 ↗

Inherited from Angulars

unsafe fn angulars__packed(
    queries: *const Self,
    packed: *const u8,
    output: *mut Self::SpatialResult,
    rows: usize,
    columns: usize,
    depth: usize,
    query_stride: usize,
    output_stride: usize,
) -> Result<(), Error>

Safety

  • a must point to valid memory for rows * depth elements with given stride
  • packed must be a buffer filled by Dots::dots_pack
  • c must point to valid memory for rows × columns result elements with given stride
angulars_*_symmetric× 9Computes symmetric angular distance matrix.
types.rs:1261 ↗

Inherited from Angulars

unsafe fn angulars__symmetric(
    vectors: *const Self,
    vector_count: usize,
    depth: usize,
    stride: usize,
    result: *mut Self::SpatialResult,
    result_stride: usize,
    rows_begin: usize,
    rows_end: usize,
) -> Result<(), Error>

Safety

  • vectors must point to valid memory for vector_count * depth elements
  • result must point to valid memory for vector_count * vector_count result elements
euclideans_*_packed× 9Computes euclidean distances between A rows and packed B columns.
types.rs:1292 ↗

Inherited from Euclideans

unsafe fn euclideans__packed(
    queries: *const Self,
    packed: *const u8,
    output: *mut Self::SpatialResult,
    rows: usize,
    columns: usize,
    depth: usize,
    query_stride: usize,
    output_stride: usize,
) -> Result<(), Error>

Safety

  • a must point to valid memory for rows * depth elements with given stride
  • packed must be a buffer filled by Dots::dots_pack
  • c must point to valid memory for rows × columns result elements with given stride
euclideans_*_symmetric× 9Computes symmetric euclidean distance matrix.
types.rs:1319 ↗

Inherited from Euclideans

unsafe fn euclideans__symmetric(
    vectors: *const Self,
    vector_count: usize,
    depth: usize,
    stride: usize,
    result: *mut Self::SpatialResult,
    result_stride: usize,
    rows_begin: usize,
    rows_end: usize,
) -> Result<(), Error>

Safety

  • vectors must point to valid memory for vector_count * depth elements
  • result must point to valid memory for vector_count * vector_count result elements
zeroThe additive identity.
types.rs:1770 ↗

Inherited from StorageElement

fn zero() -> Self
oneThe multiplicative identity.
types.rs:1771 ↗

Inherited from StorageElement

fn one() -> Self
dimensions_per_*_per_value× 14Number of logical dimensions packed into one storage value.
types.rs:1601 ↗

Inherited from StorageElement

fn dimensions_per__per_value() -> usize

Default: 1 for all normal types. Override for sub-byte packed types.

dimensions_to_*_to_values× 14Storage values needed to hold dims logical dimensions.
types.rs:1611 ↗

Inherited from StorageElement

fn dimensions_to__to_values(dims: usize) -> usize

dims counts dimensions, a multiple of the values per byte, so the division is exact, and every bounds check that guards a storage offset must be written in these units, the conversion between the two counts a packed container tracks — a check counting dimensions paired with an offset counting storage values is how an index eight times too large passes as in-range.

locate_*_dim× 14Split a logical dimension index into the storage value holding it and its position inside.
types.rs:1620 ↗

Inherited from StorageElement

fn locate__dim(dim_index: usize) -> DimLocation

The counterpart to dimensions_to_values, for the callers that must reach an individual dimension rather than count them. Pair it with FloatConvertible::unpack to read the dimension out, or with DimMut to write one back.

has_*_infinity× 11Whether the type can represent infinity.
types.rs:1781 ↗

Inherited from NumberLike

fn has__infinity() -> bool
has_*_nan× 11Whether the type can represent NaN.
types.rs:1782 ↗

Inherited from NumberLike

fn has__nan() -> bool
has_*_subnormals× 11Whether the type can represent subnormal values.
types.rs:1783 ↗

Inherited from NumberLike

fn has__subnormals() -> bool
max_*_value× 11Largest finite value of the type, as f32.
types.rs:1784 ↗

Inherited from NumberLike

fn max__value() -> f32
min_*_positive× 11Smallest positive normal value of the type, as f32.
types.rs:1785 ↗

Inherited from NumberLike

fn min__positive() -> f32
from_f64Convert from f64 to this type — by default via an f32 roundtrip.
types.rs:1679 ↗

Inherited from NumberLike

fn from_f64(v: f64) -> Self
to_*_f64× 11Convert from this type to f64 — by default via an f32 roundtrip.
types.rs:1681 ↗

Inherited from NumberLike

fn to__f64(self) -> f64
*× 11Unpack all logical sub-dimensions from this packed value.
types.rs:2391 ↗

Inherited from FloatConvertible

fn unpack(self) -> [bf16; 1]
packPack sub-dimension scalars into a single storage value.
types.rs:2393 ↗

Inherited from FloatConvertible

fn pack(dims: [bf16; 1]) -> Self
Structe2m1x2Packed FP4, E2M1, element pair: two 4-bit elements share one byte.2
types.rs:1580 ↗
pub struct e2m1x2(pub u8);

This is the storage scalar for the elements tensor of NVFP4 / MXFP4. Like the other sub-byte packers (u4x2), it reports dimensions_per_value() == 2 so a tensor of logical shape [rows,columns] allocates rows * columns / 2 bytes, as nk_block_scaled_elements_size. Bytes are produced and consumed by the C kernel (element_dtype = nk_e2m1_k); Rust never unpacks the nibbles itself.

Fields

0u8

Implements

Dots, Angulars, Euclideans, Clone, Copy, StructuralPartialEq, PartialEq, Eq, Default, Debug, StorageElement
zeroThe additive identity.
types.rs:2052 ↗

Inherited from StorageElement

fn zero() -> Self
oneThe multiplicative identity.
types.rs:2053 ↗

Inherited from StorageElement

fn one() -> Self
Structe2m36-bit E2M3 micro-float, padded to 8-bit storage.18
types.rs:797 ↗
pub struct e2m3(pub u8);

Layout: sign(1) + exponent(2) + mantissa(3), bias=1. Range: ±7.5, no infinities. Only 64 total codes; 18 (28.1%) fall in [−1, +1]. 72% of codes lie outside [−1, +1] — poor resolution for normalized vectors. Exact integer dot products via exponent-sum binning across 15 bins.

Fields

0u8

Examples

use numkong::e2m3;

let fp6 = e2m3::from_f32(2.5);
let float = fp6.to_f32();

Implements

Reductions, SpatialSimilarity, FloatLike, CastDType, Dot, VDot, EachScale, EachSum, EachBlend, EachFma, EachRmsCast, ReduceMoments, ReduceMinMax, Angular, Euclidean, Dots, Angulars, Euclideans, Clone, Copy, StructuralPartialEq, PartialEq, Eq, Default, Debug, Display, LowerHex, UpperHex, Binary, Add, Sub, Mul, Div, Neg, PartialOrd, From<f32>, From<e2m3>, StorageElement, NumberLike, FloatConvertible
ZEROPositive zero.
types.rs:801 ↗
pub const ZERO: Self = _;
ONEPositive one.
types.rs:804 ↗
pub const ONE: Self = _;
NEG_ONENegative one.
types.rs:807 ↗
pub const NEG_ONE: Self = _;
from_f32Convert an f32 value to e2m3.
types.rs:821 ↗
pub fn from_f32(value: f32) -> Self
fn from_f32(v: f32) -> Self

Convert from f32 to this type.

Out-of-range values saturate.

Examples

use numkong::e2m3;
// e2m3 covers ±7.5 with 3 mantissa bits — suitable for fine ratios
// in a narrow dynamic range.
let tiny = e2m3::from_f32(1.5);
assert_eq!(tiny.to_f32(), 1.5);
to_*_f32× 8Convert from this type to f32.
types.rs:829 ↗
pub fn to__f32(self) -> f32
dotComputes the dot product of two equally long slices.
types.rs:433 ↗

Inherited from Dot

fn dot(first: &[Self], second: &[Self]) -> Result<Self::Output, Error>
innerAlias for dot.
types.rs:268 ↗

Inherited from Dot

fn inner(first: &[Self], second: &[Self]) -> Result<Self::Output, Error>
vdotHermitian inner product.
types.rs:644 ↗

Inherited from VDot

fn vdot(first: &[Self], second: &[Self]) -> Result<Self::Output, Error>

On real-valued types this falls back to Dot::dot; on complex types it returns ∑ᵢ conj(aᵢ) × bᵢ computed in the widened accumulator described by Dot::Output.

reduce_momentsCompute (sum, sum_of_squares) for data with the given stride in bytes.
types.rs:600 ↗

Inherited from ReduceMoments

fn reduce_moments(
    data: &[Self],
    stride: usize,
) -> Result<(Self::SumOutput, Self::SumSqOutput), Error>

Use stride = size_of::<Self>() for contiguous data.

Reads data.len() logical elements starting at data.as_ptr(), advancing by stride between each — pass size_of::<Self>() for contiguous storage.

reduce_minmaxReturns Ok(Some(MinMaxResult)) for the given data with the specified stride, or Ok(None) if all elements are NaN.
types.rs:945 ↗

Inherited from ReduceMinMax

fn reduce_minmax(data: &[Self], stride: usize) -> Result<Option<MinMaxResult<Self::Output>>, Error>

Reads data.len() logical elements starting at data.as_ptr(), advancing by stride between each — pass size_of::<Self>() for contiguous storage.

angularComputes the angular distance between two equally long slices.
types.rs:532 ↗

Inherited from Angular

fn angular(a: &[Self], b: &[Self]) -> Result<Self::Output, Error>
cosineAlias for angular.
types.rs:367 ↗

Inherited from Angular

fn cosine(a: &[Self], b: &[Self]) -> Result<Self::Output, Error>
sqeuclideanSquared Euclidean distance, i.e.
types.rs:954 ↗

Inherited from Euclidean

fn sqeuclidean(a: &[Self], b: &[Self]) -> Result<Self::SqEuclideanOutput, Error>

L2². Faster than euclidean for comparisons.

euclideanEuclidean distance, i.e.
types.rs:971 ↗

Inherited from Euclidean

fn euclidean(a: &[Self], b: &[Self]) -> Result<Self::EuclideanOutput, Error>

L2. True metric distance.

zeroThe additive identity.
types.rs:1826 ↗

Inherited from StorageElement

fn zero() -> Self
oneThe multiplicative identity.
types.rs:1827 ↗

Inherited from StorageElement

fn one() -> Self
from_f64Convert from f64 to this type — by default via an f32 roundtrip.
types.rs:1679 ↗

Inherited from NumberLike

fn from_f64(v: f64) -> Self
packPack sub-dimension scalars into a single storage value.
types.rs:2420 ↗

Inherited from FloatConvertible

fn pack(dims: [e2m3; 1]) -> Self
Structe3m26-bit E3M2 micro-float, padded to 8-bit storage.17
types.rs:965 ↗
pub struct e3m2(pub u8);

Layout: sign(1) + exponent(3) + mantissa(2), bias=3. Range: ±28, supports infinities. Only 64 total codes; 26 (40.6%) fall in [−1, +1]. Exact integer dot products via exponent-sum binning across 15 bins.

Fields

0u8

Examples

use numkong::e3m2;

let fp6 = e3m2::from_f32(2.5);
let float = fp6.to_f32();

Implements

Reductions, SpatialSimilarity, FloatLike, CastDType, Dot, VDot, EachScale, EachSum, EachBlend, EachFma, EachRmsCast, ReduceMoments, ReduceMinMax, Angular, Euclidean, Dots, Angulars, Euclideans, Clone, Copy, StructuralPartialEq, PartialEq, Eq, Default, Debug, Display, LowerHex, UpperHex, Binary, Add, Sub, Mul, Div, Neg, PartialOrd, From<f32>, From<e3m2>, StorageElement, NumberLike, FloatConvertible
ZEROPositive zero.
types.rs:969 ↗
pub const ZERO: Self = _;
ONEPositive one.
types.rs:972 ↗
pub const ONE: Self = _;
NEG_ONENegative one.
types.rs:975 ↗
pub const NEG_ONE: Self = _;
from_f32Convert an f32 value to e3m2.
types.rs:988 ↗
pub fn from_f32(value: f32) -> Self
fn from_f32(v: f32) -> Self

Convert from f32 to this type.

Out-of-range values saturate.

Examples

use numkong::e3m2;
// e3m2 trades mantissa bits for a larger range (±28).
let tiny = e3m2::from_f32(16.0);
assert_eq!(tiny.to_f32(), 16.0);
dotComputes the dot product of two equally long slices.
types.rs:453 ↗

Inherited from Dot

fn dot(first: &[Self], second: &[Self]) -> Result<Self::Output, Error>
innerAlias for dot.
types.rs:268 ↗

Inherited from Dot

fn inner(first: &[Self], second: &[Self]) -> Result<Self::Output, Error>
vdotHermitian inner product.
types.rs:644 ↗

Inherited from VDot

fn vdot(first: &[Self], second: &[Self]) -> Result<Self::Output, Error>

On real-valued types this falls back to Dot::dot; on complex types it returns ∑ᵢ conj(aᵢ) × bᵢ computed in the widened accumulator described by Dot::Output.

reduce_momentsCompute (sum, sum_of_squares) for data with the given stride in bytes.
types.rs:609 ↗

Inherited from ReduceMoments

fn reduce_moments(
    data: &[Self],
    stride: usize,
) -> Result<(Self::SumOutput, Self::SumSqOutput), Error>

Use stride = size_of::<Self>() for contiguous data.

Reads data.len() logical elements starting at data.as_ptr(), advancing by stride between each — pass size_of::<Self>() for contiguous storage.

reduce_minmaxReturns Ok(Some(MinMaxResult)) for the given data with the specified stride, or Ok(None) if all elements are NaN.
types.rs:962 ↗

Inherited from ReduceMinMax

fn reduce_minmax(data: &[Self], stride: usize) -> Result<Option<MinMaxResult<Self::Output>>, Error>

Reads data.len() logical elements starting at data.as_ptr(), advancing by stride between each — pass size_of::<Self>() for contiguous storage.

angularComputes the angular distance between two equally long slices.
types.rs:552 ↗

Inherited from Angular

fn angular(a: &[Self], b: &[Self]) -> Result<Self::Output, Error>
cosineAlias for angular.
types.rs:367 ↗

Inherited from Angular

fn cosine(a: &[Self], b: &[Self]) -> Result<Self::Output, Error>
sqeuclideanSquared Euclidean distance, i.e.
types.rs:993 ↗

Inherited from Euclidean

fn sqeuclidean(a: &[Self], b: &[Self]) -> Result<Self::SqEuclideanOutput, Error>

L2². Faster than euclidean for comparisons.

euclideanEuclidean distance, i.e.
types.rs:1010 ↗

Inherited from Euclidean

fn euclidean(a: &[Self], b: &[Self]) -> Result<Self::EuclideanOutput, Error>

L2. True metric distance.

zeroThe additive identity.
types.rs:1843 ↗

Inherited from StorageElement

fn zero() -> Self
oneThe multiplicative identity.
types.rs:1844 ↗

Inherited from StorageElement

fn one() -> Self
from_f64Convert from f64 to this type — by default via an f32 roundtrip.
types.rs:1679 ↗

Inherited from NumberLike

fn from_f64(v: f64) -> Self
packPack sub-dimension scalars into a single storage value.
types.rs:2429 ↗

Inherited from FloatConvertible

fn pack(dims: [e3m2; 1]) -> Self
Structe4m38-bit E4M3 floating-point number, OCP FP8.19
types.rs:457 ↗
pub struct e4m3(pub u8);

Layout: sign(1) + exponent(4) + mantissa(3), bias=7. Range: ±448, no infinities, all-ones exponent means NaN. 114 of 254 finite values (44.9%) fall in [−1, +1]. Exact integer dot products via exponent-sum binning across 29 bins.

Fields

0u8

Examples

use numkong::e4m3;

let fp8 = e4m3::from_f32(2.5);
let float = fp8.to_f32();

Implements

Reductions, SpatialSimilarity, FloatLike, Attention, AttentionRope, CastDType, Dot, VDot, EachScale, EachSum, EachBlend, EachFma, EachSwiGlu, EachRmsNorm, EachRmsCast, ReduceMoments, ReduceMinMax, Angular, Euclidean, Dots, Angulars, Euclideans, Clone, Copy, StructuralPartialEq, PartialEq, Eq, Default, Debug, Display, LowerHex, UpperHex, Binary, Add, Sub, Mul, Div, Neg, PartialOrd, From<f32>, From<e4m3>, StorageElement, NumberLike, FloatConvertible
ZEROPositive zero.
types.rs:461 ↗
pub const ZERO: Self = _;
ONEOne.
types.rs:463 ↗
pub const ONE: Self = _;
NEG_ONENegative one.
types.rs:465 ↗
pub const NEG_ONE: Self = _;
NANQuiet NaN, i.e.
types.rs:467 ↗
pub const NAN: Self = _;

Not a Number.

from_f32Converts an f32 value to e4m3.
types.rs:480 ↗
pub fn from_f32(value: f32) -> Self
fn from_f32(v: f32) -> Self

Convert from f32 to this type.

Out-of-range values saturate.

Examples

use numkong::e4m3;
// e4m3 quantises to ~4 effective decimal digits inside ±448.
let fp8 = e4m3::from_f32(3.5);
assert_eq!(fp8.to_f32(), 3.5);
is_*_infinite× 2Returns true if this value is ±∞.
types.rs:500 ↗
pub fn is__infinite(self) -> bool

Always false for E4M3 — no infinities.

dotComputes the dot product of two equally long slices.
types.rs:393 ↗

Inherited from Dot

fn dot(first: &[Self], second: &[Self]) -> Result<Self::Output, Error>
innerAlias for dot.
types.rs:268 ↗

Inherited from Dot

fn inner(first: &[Self], second: &[Self]) -> Result<Self::Output, Error>
vdotHermitian inner product.
types.rs:644 ↗

Inherited from VDot

fn vdot(first: &[Self], second: &[Self]) -> Result<Self::Output, Error>

On real-valued types this falls back to Dot::dot; on complex types it returns ∑ᵢ conj(aᵢ) × bᵢ computed in the widened accumulator described by Dot::Output.

reduce_momentsCompute (sum, sum_of_squares) for data with the given stride in bytes.
types.rs:582 ↗

Inherited from ReduceMoments

fn reduce_moments(
    data: &[Self],
    stride: usize,
) -> Result<(Self::SumOutput, Self::SumSqOutput), Error>

Use stride = size_of::<Self>() for contiguous data.

Reads data.len() logical elements starting at data.as_ptr(), advancing by stride between each — pass size_of::<Self>() for contiguous storage.

reduce_minmaxReturns Ok(Some(MinMaxResult)) for the given data with the specified stride, or Ok(None) if all elements are NaN.
types.rs:911 ↗

Inherited from ReduceMinMax

fn reduce_minmax(data: &[Self], stride: usize) -> Result<Option<MinMaxResult<Self::Output>>, Error>

Reads data.len() logical elements starting at data.as_ptr(), advancing by stride between each — pass size_of::<Self>() for contiguous storage.

angularComputes the angular distance between two equally long slices.
types.rs:492 ↗

Inherited from Angular

fn angular(a: &[Self], b: &[Self]) -> Result<Self::Output, Error>
cosineAlias for angular.
types.rs:367 ↗

Inherited from Angular

fn cosine(a: &[Self], b: &[Self]) -> Result<Self::Output, Error>
sqeuclideanSquared Euclidean distance, i.e.
types.rs:876 ↗

Inherited from Euclidean

fn sqeuclidean(a: &[Self], b: &[Self]) -> Result<Self::SqEuclideanOutput, Error>

L2². Faster than euclidean for comparisons.

euclideanEuclidean distance, i.e.
types.rs:893 ↗

Inherited from Euclidean

fn euclidean(a: &[Self], b: &[Self]) -> Result<Self::EuclideanOutput, Error>

L2. True metric distance.

zeroThe additive identity.
types.rs:1789 ↗

Inherited from StorageElement

fn zero() -> Self
oneThe multiplicative identity.
types.rs:1790 ↗

Inherited from StorageElement

fn one() -> Self
from_f64Convert from f64 to this type — by default via an f32 roundtrip.
types.rs:1679 ↗

Inherited from NumberLike

fn from_f64(v: f64) -> Self
packPack sub-dimension scalars into a single storage value.
types.rs:2402 ↗

Inherited from FloatConvertible

fn pack(dims: [e4m3; 1]) -> Self
Structe5m28-bit E5M2 floating-point number, OCP FP8.18
types.rs:621 ↗
pub struct e5m2(pub u8);

Layout: sign(1) + exponent(5) + mantissa(2), bias=15. Range: ±57 344, supports infinities. Only 4 mantissa levels per exponent. 122 of 248 finite values (49.2%) fall in [−1, +1]. High cancellation risk in dot products — consider compensated accumulation.

Fields

0u8

Examples

use numkong::e5m2;

let fp8 = e5m2::from_f32(2.5);
let float = fp8.to_f32();

Implements

Reductions, SpatialSimilarity, FloatLike, CastDType, Dot, VDot, EachScale, EachSum, EachBlend, EachFma, EachRmsCast, ReduceMoments, ReduceMinMax, Angular, Euclidean, Dots, Angulars, Euclideans, Clone, Copy, StructuralPartialEq, PartialEq, Eq, Default, Debug, Display, LowerHex, UpperHex, Binary, Add, Sub, Mul, Div, Neg, PartialOrd, From<f32>, From<e5m2>, StorageElement, NumberLike, FloatConvertible
ZEROPositive zero.
types.rs:625 ↗
pub const ZERO: Self = _;
ONEPositive one.
types.rs:628 ↗
pub const ONE: Self = _;
NEG_ONENegative one.
types.rs:631 ↗
pub const NEG_ONE: Self = _;
NANQuiet NaN, i.e.
types.rs:633 ↗
pub const NAN: Self = _;

Not a Number.

from_f32Convert an f32 value to e5m2.
types.rs:646 ↗
pub fn from_f32(value: f32) -> Self
fn from_f32(v: f32) -> Self

Convert from f32 to this type.

Out-of-range values saturate.

Examples

use numkong::e5m2;
// e5m2 trades mantissa precision for wider range (up to ~57 344).
let fp8 = e5m2::from_f32(1024.0);
assert_eq!(fp8.to_f32(), 1024.0);
dotComputes the dot product of two equally long slices.
types.rs:413 ↗

Inherited from Dot

fn dot(first: &[Self], second: &[Self]) -> Result<Self::Output, Error>
innerAlias for dot.
types.rs:268 ↗

Inherited from Dot

fn inner(first: &[Self], second: &[Self]) -> Result<Self::Output, Error>
vdotHermitian inner product.
types.rs:644 ↗

Inherited from VDot

fn vdot(first: &[Self], second: &[Self]) -> Result<Self::Output, Error>

On real-valued types this falls back to Dot::dot; on complex types it returns ∑ᵢ conj(aᵢ) × bᵢ computed in the widened accumulator described by Dot::Output.

reduce_momentsCompute (sum, sum_of_squares) for data with the given stride in bytes.
types.rs:591 ↗

Inherited from ReduceMoments

fn reduce_moments(
    data: &[Self],
    stride: usize,
) -> Result<(Self::SumOutput, Self::SumSqOutput), Error>

Use stride = size_of::<Self>() for contiguous data.

Reads data.len() logical elements starting at data.as_ptr(), advancing by stride between each — pass size_of::<Self>() for contiguous storage.

reduce_minmaxReturns Ok(Some(MinMaxResult)) for the given data with the specified stride, or Ok(None) if all elements are NaN.
types.rs:928 ↗

Inherited from ReduceMinMax

fn reduce_minmax(data: &[Self], stride: usize) -> Result<Option<MinMaxResult<Self::Output>>, Error>

Reads data.len() logical elements starting at data.as_ptr(), advancing by stride between each — pass size_of::<Self>() for contiguous storage.

angularComputes the angular distance between two equally long slices.
types.rs:512 ↗

Inherited from Angular

fn angular(a: &[Self], b: &[Self]) -> Result<Self::Output, Error>
cosineAlias for angular.
types.rs:367 ↗

Inherited from Angular

fn cosine(a: &[Self], b: &[Self]) -> Result<Self::Output, Error>
sqeuclideanSquared Euclidean distance, i.e.
types.rs:915 ↗

Inherited from Euclidean

fn sqeuclidean(a: &[Self], b: &[Self]) -> Result<Self::SqEuclideanOutput, Error>

L2². Faster than euclidean for comparisons.

euclideanEuclidean distance, i.e.
types.rs:932 ↗

Inherited from Euclidean

fn euclidean(a: &[Self], b: &[Self]) -> Result<Self::EuclideanOutput, Error>

L2. True metric distance.

zeroThe additive identity.
types.rs:1807 ↗

Inherited from StorageElement

fn zero() -> Self
oneThe multiplicative identity.
types.rs:1808 ↗

Inherited from StorageElement

fn one() -> Self
from_f64Convert from f64 to this type — by default via an f32 roundtrip.
types.rs:1679 ↗

Inherited from NumberLike

fn from_f64(v: f64) -> Self
packPack sub-dimension scalars into a single storage value.
types.rs:2411 ↗

Inherited from FloatConvertible

fn pack(dims: [e5m2; 1]) -> Self
Structf16Half-precision (16-bit) IEEE 754 floating-point number.46
types.rs:128 ↗
pub struct f16(pub u16);

Layout: sign(1) + exponent(5) + mantissa(10), bias=15. Range: ±65504, epsilon at 1.0 ≈ 9.77×10⁻⁴, subnormal min ≈ 5.96×10⁻⁸. 30 722 of 63 488 finite values (48.4%) fall in [−1, +1]. All arithmetic via f32 upcast/downcast.

Fields

0u16

Examples

use numkong::f16;

// Create from f32
let half = f16::from_f32(3.14);

// Convert back to f32
let float = half.to_f32();

// Direct access to bits
let bits = half.0;

Implements

ProbabilitySimilarity, Reductions, SpatialSimilarity, Trigonometry, FloatLike, Attention, CastDType, Bilinear, Mahalanobis, Dot, VDot, EachScale, EachSum, EachBlend, EachFma, EachRmsCast, MaxSim, KullbackLeibler, JensenShannon, ReduceMoments, ReduceMinMax, Roots, Shapes, Angular, Euclidean, TrigSin, TrigCos, TrigAtan, Dots, Angulars, Euclideans, Clone, Copy, StructuralPartialEq, PartialEq, Eq, Default, Debug, Display, LowerHex, UpperHex, Binary, Add, Sub, Mul, Div, Neg, PartialOrd, From<f32>, From<f16>, StorageElement, NumberLike, FloatConvertible
ZEROPositive zero.
types.rs:132 ↗
pub const ZERO: Self = _;
ONEPositive one.
types.rs:134 ↗
pub const ONE: Self = _;
NEG_ONENegative one.
types.rs:136 ↗
pub const NEG_ONE: Self = _;
NANQuiet NaN, i.e.
types.rs:138 ↗
pub const NAN: Self = _;

Not a Number.

from_f32Converts an f32 value to f16.
types.rs:151 ↗
pub fn from_f32(value: f32) -> Self
fn from_f32(v: f32) -> Self

Convert from f32 to this type.

Out-of-range values saturate.

Examples

use numkong::f16;
// Roundtrip a value well inside f16's ±65504 range.
let half = f16::from_f32(3.14);
assert!((half.to_f32() - 3.14).abs() < 1e-2);
absReturns |self|.
types.rs:187 ↗
pub fn abs(self) -> Self
bilinearComputes the bilinear form aᵀ × C × b.
types.rs:221 ↗

Inherited from Bilinear

fn bilinear(a: &[Self], b: &[Self], c: &[Self]) -> Result<Self::Output, Error>

Arguments

  • a - First vector of length n
  • b - Second vector of length n
  • c - Metric tensor, symmetric [n,n] matrix in row-major order, flattened to length n²

Errors

Error::InvalidShape for empty vectors, Error::ShapeMismatch if lengths are incompatible, or Error::KernelFailed carrying the kernel's status.

mahalanobisComputes the Mahalanobis distance √((a−b)ᵀ × C × (a−b)).
types.rs:503 ↗

Inherited from Mahalanobis

fn mahalanobis(a: &[Self], b: &[Self], c: &[Self]) -> Result<Self::Output, Error>

Arguments

  • a - First vector of length n
  • b - Second vector of length n
  • c - Inverse covariance matrix, a symmetric [n,n] matrix in row-major order, flattened to length n²

Errors

Error::InvalidShape for empty vectors, Error::ShapeMismatch if lengths are incompatible, or Error::KernelFailed carrying the kernel's status.

dotComputes the dot product of two equally long slices.
types.rs:313 ↗

Inherited from Dot

fn dot(first: &[Self], second: &[Self]) -> Result<Self::Output, Error>
innerAlias for dot.
types.rs:268 ↗

Inherited from Dot

fn inner(first: &[Self], second: &[Self]) -> Result<Self::Output, Error>
vdotHermitian inner product.
types.rs:644 ↗

Inherited from VDot

fn vdot(first: &[Self], second: &[Self]) -> Result<Self::Output, Error>

On real-valued types this falls back to Dot::dot; on complex types it returns ∑ᵢ conj(aᵢ) × bᵢ computed in the widened accumulator described by Dot::Output.

kullbackleiblerComputes the Kullback-Leibler divergence of a from b.
types.rs:152 ↗

Inherited from KullbackLeibler

fn kullbackleibler(a: &[Self], b: &[Self]) -> Result<Self::Output, Error>
klAlias for kullbackleibler.
types.rs:107 ↗

Inherited from KullbackLeibler

fn kl(a: &[Self], b: &[Self]) -> Result<Self::Output, Error>
jensenshannonComputes the Jensen-Shannon divergence between a and b.
types.rs:254 ↗

Inherited from JensenShannon

fn jensenshannon(a: &[Self], b: &[Self]) -> Result<Self::Output, Error>
jsAlias for jensenshannon.
types.rs:209 ↗

Inherited from JensenShannon

fn js(a: &[Self], b: &[Self]) -> Result<Self::Output, Error>
reduce_momentsCompute (sum, sum_of_squares) for data with the given stride in bytes.
types.rs:564 ↗

Inherited from ReduceMoments

fn reduce_moments(
    data: &[Self],
    stride: usize,
) -> Result<(Self::SumOutput, Self::SumSqOutput), Error>

Use stride = size_of::<Self>() for contiguous data.

Reads data.len() logical elements starting at data.as_ptr(), advancing by stride between each — pass size_of::<Self>() for contiguous storage.

reduce_minmaxReturns Ok(Some(MinMaxResult)) for the given data with the specified stride, or Ok(None) if all elements are NaN.
types.rs:877 ↗

Inherited from ReduceMinMax

fn reduce_minmax(data: &[Self], stride: usize) -> Result<Option<MinMaxResult<Self::Output>>, Error>

Reads data.len() logical elements starting at data.as_ptr(), advancing by stride between each — pass size_of::<Self>() for contiguous storage.

*× 2Non-negative square root of self, routed through NumKong's runtime-dispatched kernel.
types.rs:54 ↗

Inherited from Roots

fn sqrt(self) -> Self
*× 2Reciprocal square root 1 / √x of self as a single primitive op where the hardware allows.
types.rs:55 ↗

Inherited from Roots

fn rsqrt(self) -> Self
shapes_pack_sizeReturns the bytes a pack of points points takes.
types.rs:613 ↗

Inherited from Shapes

fn shapes_pack_size(points: usize) -> Result<usize, Error>
shapes_packPacks one cloud: centers it and rotates it onto its principal axes.
types.rs:619 ↗

Inherited from Shapes

unsafe fn shapes_pack(points: &[[Self; 3]], packed: *mut u8) -> Result<(), Error>

Safety

packed must have shapes_pack_size(points.len()) writable bytes on an nk_default_alignment_k boundary.

shapes_pack_normalizedPacks one cloud like Shapes::shapes_pack, also dividing it by its RMS distance from the centroid, which the pack keeps as its scale, or by 1 when the cloud has no spread.
types.rs:630 ↗

Inherited from Shapes

unsafe fn shapes_pack_normalized(points: &[[Self; 3]], packed: *mut u8) -> Result<(), Error>

Safety

The contract of Shapes::shapes_pack.

shapes_packed_shapeReads the pose and bounds of a pack into every non-null output: its number of points, its mean input point, the unit quaternion (x, y, z, w) rotating the centered cloud onto its principal axes, what the rotated cloud was divided by, the descending eigenvalues of the packed points' second moments, and the largest packed point norm.
types.rs:641 ↗

Inherited from Shapes

unsafe fn shapes_packed_shape(
    packed: *const u8,
    points: *mut usize,
    centroid: *mut f32,
    frame: *mut f32,
    scale: *mut f32,
    spreads: *mut f32,
    max_radius: *mut f32,
) -> Result<(), Error>

Safety

packed must point to a pack of Self, and the non-null outputs must hold 1, 3, 4, 1, 3 and 1 writable values in that order.

shapes_unpackWrites the cloud of a pack back interleaved, in its original pose and scale, within one rounding to Self.
types.rs:664 ↗

Inherited from Shapes

unsafe fn shapes_unpack(packed: *const u8, points: *mut [Self; 3]) -> Result<(), Error>

Safety

packed must point to a pack of Self, and points must hold as many writable points as it packed.

rmsds_packedSuperposed RMSDs between every row cloud and every column cloud of equally many points.
types.rs:670 ↗

Inherited from Shapes

unsafe fn rmsds_packed(
    a_packed: *const *const u8,
    rows: usize,
    b_packed: *const *const u8,
    columns: usize,
    results: *mut f32,
    results_stride: usize,
    capabilities: Capabilities,
    stream: *mut c_void,
) -> Result<(), Error>

Safety

  • a_packed and b_packed must hold rows and columns pointers to packs of Self
  • results must hold rows rows of columns distances, results_stride bytes apart
  • stream must be null or a live stream of the group capabilities name, null on the CPU, and on a GPU everything above must stay alive and untouched until that stream joins
hausdorffs_packedHausdorff distances between every row cloud and every column cloud.
types.rs:693 ↗

Inherited from Shapes

unsafe fn hausdorffs_packed(
    a_packed: *const *const u8,
    rows: usize,
    b_packed: *const *const u8,
    columns: usize,
    results: *mut f32,
    results_stride: usize,
    rotations: *mut f32,
    limit: f32,
    capabilities: Capabilities,
    stream: *mut c_void,
) -> Result<(), Error>

Safety

The contract of Shapes::rmsds_packed, plus rotations must be null or hold rows × columns × 9 writable values.

chamfers_workspace_sizeReturns the workspace bytes Chamfer needs between clouds of up to row_points and column_points points.
types.rs:720 ↗

Inherited from Shapes

fn chamfers_workspace_size(
    row_points: usize,
    column_points: usize,
    capabilities: Capabilities,
) -> Result<usize, Error>
chamfers_packedChamfer distances between every row cloud and every column cloud.
types.rs:731 ↗

Inherited from Shapes

unsafe fn chamfers_packed(
    a_packed: *const *const u8,
    rows: usize,
    b_packed: *const *const u8,
    columns: usize,
    results: *mut f32,
    results_stride: usize,
    rotations: *mut f32,
    limit: f32,
    workspace: *mut u8,
    workspace_bytes: usize,
    capabilities: Capabilities,
    stream: *mut c_void,
) -> Result<(), Error>

Safety

The contract of Shapes::hausdorffs_packed, plus workspace must have workspace_bytes writable bytes, on the default alignment, as Shapes::chamfers_workspace_size reports for the largest clouds.

wassersteinprocrustes_workspace_sizeReturns the workspace bytes Wasserstein-Procrustes needs between clouds of up to row_points and column_points points.
types.rs:762 ↗

Inherited from Shapes

fn wassersteinprocrustes_workspace_size(
    row_points: usize,
    column_points: usize,
    capabilities: Capabilities,
) -> Result<usize, Error>
wassersteinprocrustes_packedWasserstein-Procrustes distances between every row cloud and every column cloud.
types.rs:775 ↗

Inherited from Shapes

unsafe fn wassersteinprocrustes_packed(
    a_packed: *const *const u8,
    rows: usize,
    b_packed: *const *const u8,
    columns: usize,
    results: *mut f32,
    results_stride: usize,
    rotations: *mut f32,
    workspace: *mut u8,
    workspace_bytes: usize,
    capabilities: Capabilities,
    stream: *mut c_void,
) -> Result<(), Error>

Safety

The contract of Shapes::chamfers_packed, plus workspace must have workspace_bytes writable bytes on an nk_default_alignment_k boundary.

gromovwassersteins_workspace_sizeReturns the workspace bytes Gromov-Wasserstein needs between clouds of up to row_points and column_points points.
types.rs:804 ↗

Inherited from Shapes

fn gromovwassersteins_workspace_size(
    row_points: usize,
    column_points: usize,
    capabilities: Capabilities,
) -> Result<usize, Error>
gromovwassersteins_packedGromov-Wasserstein distances between every row cloud and every column cloud.
types.rs:817 ↗

Inherited from Shapes

unsafe fn gromovwassersteins_packed(
    a_packed: *const *const u8,
    rows: usize,
    b_packed: *const *const u8,
    columns: usize,
    results: *mut f32,
    results_stride: usize,
    rotations: *mut f32,
    workspace: *mut u8,
    workspace_bytes: usize,
    capabilities: Capabilities,
    stream: *mut c_void,
) -> Result<(), Error>

Safety

angularComputes the angular distance between two equally long slices.
types.rs:412 ↗

Inherited from Angular

fn angular(a: &[Self], b: &[Self]) -> Result<Self::Output, Error>
cosineAlias for angular.
types.rs:367 ↗

Inherited from Angular

fn cosine(a: &[Self], b: &[Self]) -> Result<Self::Output, Error>
sqeuclideanSquared Euclidean distance, i.e.
types.rs:720 ↗

Inherited from Euclidean

fn sqeuclidean(a: &[Self], b: &[Self]) -> Result<Self::SqEuclideanOutput, Error>

L2². Faster than euclidean for comparisons.

euclideanEuclidean distance, i.e.
types.rs:737 ↗

Inherited from Euclidean

fn euclidean(a: &[Self], b: &[Self]) -> Result<Self::EuclideanOutput, Error>

L2. True metric distance.

sinWrites the sine of every input element, in radians, into the output slice.
types.rs:144 ↗

Inherited from TrigSin

fn sin(inputs: &[Self], outputs: &mut [Self]) -> Result<(), Error>
sin_inplaceIn-place sine: data[i] = sin(data[i]).
types.rs:158 ↗

Inherited from TrigSin

fn sin_inplace(data: &mut [Self]) -> Result<(), Error>

Both source and destination pointers are derived from the single &mut, so no aliased &[Self] + &mut [Self] over the same storage is formed.

cosWrites the cosine of every input element, in radians, into the output slice.
types.rs:238 ↗

Inherited from TrigCos

fn cos(inputs: &[Self], outputs: &mut [Self]) -> Result<(), Error>
cos_inplaceIn-place cosine: data[i] = cos(data[i]).
types.rs:252 ↗

Inherited from TrigCos

fn cos_inplace(data: &mut [Self]) -> Result<(), Error>

Both source and destination pointers are derived from the single &mut, so no aliased &[Self] + &mut [Self] over the same storage is formed.

atanWrites the arctangent of every input element, in radians, into the output slice.
types.rs:332 ↗

Inherited from TrigAtan

fn atan(inputs: &[Self], outputs: &mut [Self]) -> Result<(), Error>
atan_inplaceIn-place arctangent: data[i] = atan(data[i]).
types.rs:346 ↗

Inherited from TrigAtan

fn atan_inplace(data: &mut [Self]) -> Result<(), Error>

Both source and destination pointers are derived from the single &mut, so no aliased &[Self] + &mut [Self] over the same storage is formed.

zeroThe additive identity.
types.rs:1751 ↗

Inherited from StorageElement

fn zero() -> Self
oneThe multiplicative identity.
types.rs:1752 ↗

Inherited from StorageElement

fn one() -> Self
from_f64Convert from f64 to this type — by default via an f32 roundtrip.
types.rs:1679 ↗

Inherited from NumberLike

fn from_f64(v: f64) -> Self
packPack sub-dimension scalars into a single storage value.
types.rs:2384 ↗

Inherited from FloatConvertible

fn pack(dims: [f16; 1]) -> Self
Structi4x2Packed 4-bit signed integer pair (2 × i4 in one byte).22
types.rs:1484 ↗
pub struct i4x2(pub u8);

Layout: high nibble = first element, low nibble = second element, two's complement. Range per element: [−8, +7]. Elements sign-extended to i8 for arithmetic.

Fields

0u8

Implements

Reductions, SpatialSimilarity, FloatLike, Dot, VDot, ReduceMoments, ReduceMinMax, Angular, Euclidean, Dots, Angulars, Euclideans, Clone, Copy, StructuralPartialEq, PartialEq, Eq, Default, Debug, Display, LowerHex, UpperHex, Binary, From<(i8, i8)>, From<i4x2>, StorageElement, NumberLike, FloatConvertible
newCreate from raw packed byte.
types.rs:1519 ↗
pub const fn new(packed: u8) -> Self
*× 2Get the raw packed byte.
types.rs:1523 ↗
pub const fn packed(self) -> u8
from_i8sConstruct from two i8 values with saturation to -8..7, first in the high nibble.
types.rs:1527 ↗
pub const fn from_i8s(first: i8, second: i8) -> Self
to_i8sExtract to two i8 values, sign-extended from 4 bits, the high nibble first.
types.rs:1547 ↗
pub const fn to_i8s(self) -> (i8, i8)
dotComputes the dot product of two equally long slices.
types.rs:473 ↗

Inherited from Dot

fn dot(first: &[Self], second: &[Self]) -> Result<Self::Output, Error>
innerAlias for dot.
types.rs:268 ↗

Inherited from Dot

fn inner(first: &[Self], second: &[Self]) -> Result<Self::Output, Error>
vdotHermitian inner product.
types.rs:644 ↗

Inherited from VDot

fn vdot(first: &[Self], second: &[Self]) -> Result<Self::Output, Error>

On real-valued types this falls back to Dot::dot; on complex types it returns ∑ᵢ conj(aᵢ) × bᵢ computed in the widened accumulator described by Dot::Output.

reduce_momentsCompute (sum, sum_of_squares) for data with the given stride in bytes.
types.rs:618 ↗

Inherited from ReduceMoments

fn reduce_moments(
    data: &[Self],
    stride: usize,
) -> Result<(Self::SumOutput, Self::SumSqOutput), Error>

Use stride = size_of::<Self>() for contiguous data.

Reads data.len() logical elements starting at data.as_ptr(), advancing by stride between each — pass size_of::<Self>() for contiguous storage.

reduce_minmaxReturns Ok(Some(MinMaxResult)) for the given data with the specified stride, or Ok(None) if all elements are NaN.
types.rs:979 ↗

Inherited from ReduceMinMax

fn reduce_minmax(data: &[Self], stride: usize) -> Result<Option<MinMaxResult<Self::Output>>, Error>

Reads data.len() logical elements starting at data.as_ptr(), advancing by stride between each — pass size_of::<Self>() for contiguous storage.

angularComputes the angular distance between two equally long slices.
types.rs:572 ↗

Inherited from Angular

fn angular(a: &[Self], b: &[Self]) -> Result<Self::Output, Error>
cosineAlias for angular.
types.rs:367 ↗

Inherited from Angular

fn cosine(a: &[Self], b: &[Self]) -> Result<Self::Output, Error>
sqeuclideanSquared Euclidean distance, i.e.
types.rs:1032 ↗

Inherited from Euclidean

fn sqeuclidean(a: &[Self], b: &[Self]) -> Result<Self::SqEuclideanOutput, Error>

L2². Faster than euclidean for comparisons.

euclideanEuclidean distance, i.e.
types.rs:1050 ↗

Inherited from Euclidean

fn euclidean(a: &[Self], b: &[Self]) -> Result<Self::EuclideanOutput, Error>

L2. True metric distance.

zeroThe additive identity.
types.rs:2017 ↗

Inherited from StorageElement

fn zero() -> Self
oneThe multiplicative identity.
types.rs:2018 ↗

Inherited from StorageElement

fn one() -> Self
from_f32Convert from f32 to this type.
types.rs:2023 ↗

Inherited from NumberLike

fn from_f32(v: f32) -> Self
from_f64Convert from f64 to this type — by default via an f32 roundtrip.
types.rs:1679 ↗

Inherited from NumberLike

fn from_f64(v: f64) -> Self
*× 5Absolute value.
types.rs:1684 ↗

Inherited from NumberLike

fn abs(self) -> Self
is_*_nan× 5Whether the value is NaN.
types.rs:1686 ↗

Inherited from NumberLike

fn is__nan(self) -> bool
is_*_finite× 5Whether the value is neither infinite nor NaN.
types.rs:1688 ↗

Inherited from NumberLike

fn is__finite(self) -> bool
is_*_infinite× 5Whether the value is infinite.
types.rs:1690 ↗

Inherited from NumberLike

fn is__infinite(self) -> bool
packPack sub-dimension scalars into a single storage value.
types.rs:2513 ↗

Inherited from FloatConvertible

fn pack(dims: [i8; 2]) -> Self
Structu1x8Packed 8-bit bit-vector — 8 booleans in one byte.20
types.rs:1318 ↗
pub struct u1x8(pub u8);

Layout: 8 bits packed into one byte, MSB = dimension 0. Used for Hamming distance and Jaccard similarity via popcount.

Fields

0u8

Implements

Reductions, BinarySimilarity, FloatLike, Dot, VDot, ReduceMoments, ReduceMinMax, Hamming, Jaccard, Dots, Hammings, Jaccards, Clone, Copy, StructuralPartialEq, PartialEq, Eq, Default, Debug, Display, LowerHex, UpperHex, Binary, From<(bool, bool, bool, bool, bool, bool, bool, bool)>, From<u1x8>, StorageElement, NumberLike, FloatConvertible
newCreate from raw packed bits.
types.rs:1351 ↗
pub const fn new(bits: u8) -> Self
bitsGet the raw packed bits.
types.rs:1355 ↗
pub const fn bits(self) -> u8
from_boolsConstruct from 8 booleans (b0 = MSB, b7 = LSB).
types.rs:1359 ↗
pub const fn from_bools(
    b0: bool,
    b1: bool,
    b2: bool,
    b3: bool,
    b4: bool,
    b5: bool,
    b6: bool,
    b7: bool,
) -> Self
to_boolsExtract to 8 booleans (b0 = MSB, b7 = LSB).
types.rs:1374 ↗
pub const fn to_bools(self) -> (bool, bool, bool, bool, bool, bool, bool, bool)
dotComputes the dot product of two equally long slices.
types.rs:515 ↗

Inherited from Dot

fn dot(first: &[Self], second: &[Self]) -> Result<Self::Output, Error>
innerAlias for dot.
types.rs:268 ↗

Inherited from Dot

fn inner(first: &[Self], second: &[Self]) -> Result<Self::Output, Error>
vdotHermitian inner product.
types.rs:644 ↗

Inherited from VDot

fn vdot(first: &[Self], second: &[Self]) -> Result<Self::Output, Error>

On real-valued types this falls back to Dot::dot; on complex types it returns ∑ᵢ conj(aᵢ) × bᵢ computed in the widened accumulator described by Dot::Output.

reduce_momentsCompute (sum, sum_of_squares) for data with the given stride in bytes.
types.rs:636 ↗

Inherited from ReduceMoments

fn reduce_moments(
    data: &[Self],
    stride: usize,
) -> Result<(Self::SumOutput, Self::SumSqOutput), Error>

Use stride = size_of::<Self>() for contiguous data.

Reads data.len() logical elements starting at data.as_ptr(), advancing by stride between each — pass size_of::<Self>() for contiguous storage.

reduce_minmaxReturns Ok(Some(MinMaxResult)) for the given data with the specified stride, or Ok(None) if all elements are NaN.
types.rs:1013 ↗

Inherited from ReduceMinMax

fn reduce_minmax(data: &[Self], stride: usize) -> Result<Option<MinMaxResult<Self::Output>>, Error>

Reads data.len() logical elements starting at data.as_ptr(), advancing by stride between each — pass size_of::<Self>() for contiguous storage.

hammingComputes the Hamming distance between two equally long slices.
types.rs:84 ↗

Inherited from Hamming

fn hamming(a: &[Self], b: &[Self]) -> Result<Self::Output, Error>
jaccardComputes the Jaccard distance between two equally long slices.
types.rs:144 ↗

Inherited from Jaccard

fn jaccard(a: &[Self], b: &[Self]) -> Result<Self::Output, Error>
hammings_packedComputes Hamming distances between values matrix rows and packed query rows.
types.rs:150 ↗

Inherited from Hammings

unsafe fn hammings_packed(
    queries: *const Self,
    packed: *const u8,
    result: *mut u32,
    rows: usize,
    columns: usize,
    depth: usize,
    v_stride: usize,
    r_stride: usize,
) -> Result<(), Error>

Safety

  • a must point to valid memory for the values matrix
  • packed must be a buffer filled by Dots::dots_pack
  • result must point to valid memory for rows × columns u32 elements
hammings_symmetricComputes symmetric Gram matrix of Hamming distances: C = A × Aᵀ.
types.rs:177 ↗

Inherited from Hammings

unsafe fn hammings_symmetric(
    vectors: *const Self,
    vector_count: usize,
    depth: usize,
    stride: usize,
    result: *mut u32,
    result_stride: usize,
    rows_begin: usize,
    rows_end: usize,
) -> Result<(), Error>

Safety

  • vectors must point to valid memory for the input matrix
  • result must point to valid memory for vector_count * vector_count u32 elements
jaccards_packedComputes Jaccard distances between values matrix rows and packed query rows.
types.rs:267 ↗

Inherited from Jaccards

unsafe fn jaccards_packed(
    queries: *const Self,
    packed: *const u8,
    result: *mut Self::JaccardResult,
    rows: usize,
    columns: usize,
    depth: usize,
    v_stride: usize,
    r_stride: usize,
) -> Result<(), Error>

Safety

  • a must point to valid memory for the values matrix
  • packed must be a buffer filled by Dots::dots_pack
  • result must point to valid memory for rows × columns elements
jaccards_symmetricComputes symmetric Gram matrix of Jaccard distances.
types.rs:294 ↗

Inherited from Jaccards

unsafe fn jaccards_symmetric(
    vectors: *const Self,
    vector_count: usize,
    depth: usize,
    stride: usize,
    result: *mut Self::JaccardResult,
    result_stride: usize,
    rows_begin: usize,
    rows_end: usize,
) -> Result<(), Error>

Safety

  • vectors must point to valid memory for the input matrix
  • result must point to valid memory for vector_count * vector_count elements
zeroThe additive identity.
types.rs:2061 ↗

Inherited from StorageElement

fn zero() -> Self
oneThe multiplicative identity.
types.rs:2062 ↗

Inherited from StorageElement

fn one() -> Self
from_f32Convert from f32 to this type.
types.rs:2067 ↗

Inherited from NumberLike

fn from_f32(v: f32) -> Self
from_f64Convert from f64 to this type — by default via an f32 roundtrip.
types.rs:1679 ↗

Inherited from NumberLike

fn from_f64(v: f64) -> Self
packPack sub-dimension scalars into a single storage value.
types.rs:2540 ↗

Inherited from FloatConvertible

fn pack(dims: [u8; 8]) -> Self
Structu4x2Packed 4-bit unsigned integer pair (2 × u4 in one byte).17
types.rs:1410 ↗
pub struct u4x2(pub u8);

Layout: high nibble = first element, low nibble = second element. Range per element: [0, 15]. Elements zero-extended to u8 for arithmetic.

Fields

0u8

Implements

Reductions, SpatialSimilarity, FloatLike, Dot, VDot, ReduceMoments, ReduceMinMax, Angular, Euclidean, Dots, Angulars, Euclideans, Clone, Copy, StructuralPartialEq, PartialEq, Eq, Default, Debug, Display, LowerHex, UpperHex, Binary, From<(u8, u8)>, From<u4x2>, StorageElement, NumberLike, FloatConvertible
newCreate from raw packed byte.
types.rs:1445 ↗
pub const fn new(packed: u8) -> Self
from_u8sConstruct from two u8 values with saturation to 0..15, first in the high nibble.
types.rs:1453 ↗
pub const fn from_u8s(first: u8, second: u8) -> Self
to_u8sExtract to two u8 values (0..15 each), the high nibble first.
types.rs:1461 ↗
pub const fn to_u8s(self) -> (u8, u8)
dotComputes the dot product of two equally long slices.
types.rs:494 ↗

Inherited from Dot

fn dot(first: &[Self], second: &[Self]) -> Result<Self::Output, Error>
innerAlias for dot.
types.rs:268 ↗

Inherited from Dot

fn inner(first: &[Self], second: &[Self]) -> Result<Self::Output, Error>
vdotHermitian inner product.
types.rs:644 ↗

Inherited from VDot

fn vdot(first: &[Self], second: &[Self]) -> Result<Self::Output, Error>

On real-valued types this falls back to Dot::dot; on complex types it returns ∑ᵢ conj(aᵢ) × bᵢ computed in the widened accumulator described by Dot::Output.

reduce_momentsCompute (sum, sum_of_squares) for data with the given stride in bytes.
types.rs:627 ↗

Inherited from ReduceMoments

fn reduce_moments(
    data: &[Self],
    stride: usize,
) -> Result<(Self::SumOutput, Self::SumSqOutput), Error>

Use stride = size_of::<Self>() for contiguous data.

Reads data.len() logical elements starting at data.as_ptr(), advancing by stride between each — pass size_of::<Self>() for contiguous storage.

reduce_minmaxReturns Ok(Some(MinMaxResult)) for the given data with the specified stride, or Ok(None) if all elements are NaN.
types.rs:996 ↗

Inherited from ReduceMinMax

fn reduce_minmax(data: &[Self], stride: usize) -> Result<Option<MinMaxResult<Self::Output>>, Error>

Reads data.len() logical elements starting at data.as_ptr(), advancing by stride between each — pass size_of::<Self>() for contiguous storage.

angularComputes the angular distance between two equally long slices.
types.rs:593 ↗

Inherited from Angular

fn angular(a: &[Self], b: &[Self]) -> Result<Self::Output, Error>
cosineAlias for angular.
types.rs:367 ↗

Inherited from Angular

fn cosine(a: &[Self], b: &[Self]) -> Result<Self::Output, Error>
sqeuclideanSquared Euclidean distance, i.e.
types.rs:1073 ↗

Inherited from Euclidean

fn sqeuclidean(a: &[Self], b: &[Self]) -> Result<Self::SqEuclideanOutput, Error>

L2². Faster than euclidean for comparisons.

euclideanEuclidean distance, i.e.
types.rs:1091 ↗

Inherited from Euclidean

fn euclidean(a: &[Self], b: &[Self]) -> Result<Self::EuclideanOutput, Error>

L2. True metric distance.

zeroThe additive identity.
types.rs:2034 ↗

Inherited from StorageElement

fn zero() -> Self
oneThe multiplicative identity.
types.rs:2035 ↗

Inherited from StorageElement

fn one() -> Self
from_f32Convert from f32 to this type.
types.rs:2040 ↗

Inherited from NumberLike

fn from_f32(v: f32) -> Self
from_f64Convert from f64 to this type — by default via an f32 roundtrip.
types.rs:1679 ↗

Inherited from NumberLike

fn from_f64(v: f64) -> Self
packPack sub-dimension scalars into a single storage value.
types.rs:2525 ↗

Inherited from FloatConvertible

fn pack(dims: [u8; 2]) -> Self
TraitFloatConvertibleTrait for types that can unpack/pack logical sub-dimensions.3
types.rs:2346 ↗
pub trait FloatConvertible: NumberLike

For normal scalar types (dimensions_per_value() == 1), DimScalar = Self and Unpacked = [Self; 1]. For packed sub-byte types, DimScalar is the natural scalar type for individual sub-dimensions, such as i8 for i4x2.

Implementors

DimScalarScalar type for individual sub-dimensions.
types.rs:2348 ↗
type DimScalar: Copy + Default + NumberLike;
UnpackedFixed-size array holding all unpacked sub-dimensions.
types.rs:2351 ↗
type Unpacked: AsRef<[Self::DimScalar]> + AsMut<[Self::DimScalar]> + Copy + Default;
packPack sub-dimension scalars into a single storage value.
types.rs:2357 ↗
fn pack(dims: Self::Unpacked) -> Self
TraitFloatLikeBackward-compatible alias: any type implementing NumberLike also implements FloatLike.
types.rs:1705 ↗
pub trait FloatLike: NumberLike

Implementors

TraitNumberLikeTrait for types that support conversion to/from f32 with classification and constants.2
types.rs:1673 ↗
pub trait NumberLike: StorageElement

Provides a unified interface for all numeric types used in NumKong, including half-precision floats, mini-floats, integers, and packed types.

Implementors

from_f32Convert from f32 to this type.
types.rs:1675 ↗
fn from_f32(v: f32) -> Self
from_f64Convert from f64 to this type — by default via an f32 roundtrip.
types.rs:1679 ↗
fn from_f64(v: f64) -> Self
TraitStorageElementMinimal trait for types that can be stored in vectors and tensors.2
types.rs:1594 ↗
pub trait StorageElement: Sized + Copy + Clone + Default + Debug

Provides identity elements (zero, one) and sub-byte packing metadata. Does not require numeric conversion — use NumberLike for that.

Implementors

zeroThe additive identity.
types.rs:1596 ↗
fn zero() -> Self
oneThe multiplicative identity.
types.rs:1598 ↗
fn one() -> Self
StructUe4m3NVFP4 per-block scale byte: an unsigned E4M3 magnitude with the sign bit forced to 0.5
types.rs:1139 ↗
pub struct Ue4m3(pub u8);

Stores one scale per 16-element NVFP4 block. Layout matches nk_ue4m3_t (1 byte). Decodes to a positive f32 multiplier; from_f32 takes the absolute value.

Fields

0u8

Examples

use numkong::Ue4m3;

let scale = Ue4m3::from_f32(2.0);
assert_eq!(scale.to_f32(), 2.0);

Implements

Clone, Copy, StructuralPartialEq, PartialEq, Eq, Default, Debug, StorageElement
ZEROThe all-zero byte — decodes to 0.0.
types.rs:1143 ↗
pub const ZERO: Self = _;
from_f32Encodes an f32 magnitude into a UE4M3 scale byte — absolute value, round-to-nearest.
types.rs:1150 ↗
pub fn from_f32(value: f32) -> Self

UE4M3 is E4M3 with the sign bit forced to 0, so this reuses the linkable E4M3 encoder on |value| and masks off the sign. NaN maps to the E4M3 NaN code (0x7F).

to_f32Decodes this UE4M3 scale byte to a non-negative f32 multiplier.
types.rs:1160 ↗
pub fn to_f32(self) -> f32
zeroThe additive identity.
types.rs:1170 ↗

Inherited from StorageElement

fn zero() -> Self
oneThe multiplicative identity.
types.rs:1171 ↗

Inherited from StorageElement

fn one() -> Self
StructUe8m0MX-family per-block scale byte: an unsigned power-of-two exponent, UE8M0.4
types.rs:1190 ↗
pub struct Ue8m0(pub u8);

Stores one scale per 32-element MX block, a 1-byte layout matching nk_ue8m0_t. Decodes to a positive power-of-two f32 multiplier; from_f32 rounds the magnitude UP to the smallest power of two that is ≥ |value|.

Fields

0u8

Examples

use numkong::Ue8m0;

let scale = Ue8m0::from_f32(4.0);
assert_eq!(scale.to_f32(), 4.0);

Implements

Clone, Copy, StructuralPartialEq, PartialEq, Eq, Default, Debug, StorageElement
from_f32Encodes an f32 magnitude into a UE8M0 scale byte.
types.rs:1199 ↗
pub fn from_f32(value: f32) -> Self

Rounds the magnitude to the nearest power of two — round-to-nearest in log2 space, the OCP MX convention; the split point is the geometric midpoint √2·2ᵉ. NaN → 0xFF, block-NaN sentinel, zero/subnormal → 0x00, overflow/±∞ → 0xFE.

to_f32Decodes this UE8M0 scale byte to a power-of-two f32 multiplier.
types.rs:1226 ↗
pub fn to_f32(self) -> f32

0x00 → 0.0, 0xFF → NaN, otherwise 2^(byte − 127).

zeroThe additive identity.
types.rs:1246 ↗

Inherited from StorageElement

fn zero() -> Self
oneThe multiplicative identity.
types.rs:1247 ↗

Inherited from StorageElement

fn one() -> Self
TraitRootsScalar square-root and reciprocal-square-root operations backed by NumKong's exported kernels.
scalar.rs:36 ↗
pub trait Roots: Sized

Unlike f32::sqrt / f64::sqrt, this routes into the hand-tuned NumKong C kernels; on ISAs with a dedicated reciprocal-sqrt, such as vrsqrte on NEON or vrsqrt14 on AVX-512, rsqrt uses a single Newton refinement to ~1 ULP — roughly 2-4× faster than computing 1 / √x explicitly.

Implementors

TraitCastDTypeTrait for types that can participate in cast operations.
cast.rs:101 ↗
pub trait CastDType: Sealed + StorageElement

This trait is sealed - users cannot implement it for their own types.

Implementors

TraitCastOpsExtension trait: type casting for any TensorRef implementor.2
cast.rs:209 ↗
pub trait CastOps<Source: Clone + CastDType, const MAX_RANK: usize>: TensorRef<Source, MAX_RANK>

Implementors

castCasts every element to Destination, returning a new tensor of the same shape.
cast.rs:211 ↗
fn cast<Destination: Clone + CastDType>(
    &self,
) -> Result<Tensor<Destination, Self::Alloc, MAX_RANK>, Error>
where
    Self::Alloc: Clone,
cast_intoCast into a pre-allocated sink.
cast.rs:220 ↗
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.

TraitDenseToScaledOpsEncode a dense f32 matrix into a ScaledTensor.1
cast.rs:763 ↗
pub trait DenseToScaledOps<const MAX_RANK: usize>: TensorRef<f32, MAX_RANK>

The source must be a contiguous 2D [rows,columns] view with columns divisible by F::BLOCK_SIZE. For formats with a per-tensor scale, such as NVFP4, the multiplier is derived from the tensor amax by the kernel — we seed the buffer with 0.0 and read it back. Extension trait: encode any dense f32 tensor into a block-scaled ScaledTensor.

Blanket-implemented for every TensorRef<f32, MAX_RANK>, so Tensor<f32>, TensorView<f32>, and TensorSpan<f32> all expose .cast_to_scaled::<F>() without an intervening .view().

Implementors

cast_to_scaledEncodes the tensor into the block-scaled format F.
cast.rs:765 ↗
fn cast_to_scaled<F: BlockScaledFormat>(&self) -> Result<ScaledTensor<F, Self::Alloc>, Error>
where
    Self::Alloc: Clone,
StructBlockScaledDescriptor#[repr(C)] mirror of nk_block_scaled_format_t.3
cast.rs:247 ↗
pub struct BlockScaledDescriptor

Field order and types match the C struct exactly so a *const can be handed to nk_cast_best. The tensor_scale_dtype field is nk_f32_k for NVFP4 and nk_dtype_unknown_k (0) for the MX family; block_size is 0 for plain buffers.

Fields

element_dtypeu32Type of the packed elements.
scale_dtypeu32Type of the per-block scales.
tensor_scale_dtypeu32Type of the per-tensor scale, nk_dtype_unknown_k when there is none.
block_sizeusizeElements per scaled block, 0 for plain buffers.

Implements

Clone, Copy, Debug, StructuralPartialEq, PartialEq, Eq
plainnk_plain(dtype) — a non-block-scaled buffer of element_dtype.
cast.rs:261 ↗
pub fn plain(element_dtype: u32) -> Self
elements_sizeElement storage bytes for count logical elements — mirrors nk_block_scaled_elements_size: count * element_bits / 8.
cast.rs:274 ↗
pub fn elements_size(&self, count: usize) -> usize

count counts dimensions, a multiple of the values per byte.

scales_sizeScale storage bytes for count logical elements — mirrors nk_block_scaled_scales_size: 0 when plain, else round_up(count, block_size).
cast.rs:279 ↗
pub fn scales_size(&self, count: usize) -> usize
TraitBlockScaledFormatCompile-time description of a block-scaled tensor layout.5
cast.rs:548 ↗
pub trait BlockScaledFormat

Each implementor is a zero-sized tag (Nvfp4, Mxfp4, …). The associated types name the storage scalars of the two composed tensors: Element for the packed values and Scale for the per-block scale bytes.

Implementors

ElementStorage scalar of the elements tensor, e.g.
cast.rs:550 ↗
type Element: StorageElement + Clone;

e2m1x2, e4m3, i8.

ScaleStorage scalar of the block_scales tensor (Ue4m3 or Ue8m0).
cast.rs:552 ↗
type Scale: StorageElement + Clone;
BLOCK_SIZELogical elements per block; quantization is on the last axis.
cast.rs:554 ↗
const BLOCK_SIZE: usize;
HAS_TENSOR_SCALEWhether this format carries a per-tensor f32 multiplier (tensor_scale).
cast.rs:556 ↗
const HAS_TENSOR_SCALE: bool;
*× 8The C descriptor literal for this format.
cast.rs:558 ↗
fn descriptor() -> BlockScaledDescriptor
StructMxfp4OCP MXFP4: E2M1 elements, UE8M0 block scale (block=32), no tensor scale.
cast.rs:581 ↗
pub struct Mxfp4;

Implements

Clone, Copy, Debug, Default, BlockScaledFormat
StructMxfp6E2m3OCP MXFP6 (E2M3 variant): E2M3 elements, UE8M0 block scale (block=32).
cast.rs:599 ↗
pub struct Mxfp6E2m3;

Implements

Clone, Copy, Debug, Default, BlockScaledFormat
StructMxfp6E3m2OCP MXFP6 (E3M2 variant): E3M2 elements, UE8M0 block scale (block=32).
cast.rs:617 ↗
pub struct Mxfp6E3m2;

Implements

Clone, Copy, Debug, Default, BlockScaledFormat
StructMxfp8E4m3OCP MXFP8 (E4M3 variant): E4M3 elements, UE8M0 block scale (block=32).
cast.rs:635 ↗
pub struct Mxfp8E4m3;

Implements

Clone, Copy, Debug, Default, BlockScaledFormat
StructMxfp8E5m2OCP MXFP8 (E5M2 variant): E5M2 elements, UE8M0 block scale (block=32).
cast.rs:653 ↗
pub struct Mxfp8E5m2;

Implements

Clone, Copy, Debug, Default, BlockScaledFormat
StructMxint8OCP MXINT8: i8 elements, UE8M0 block scale (block=32).
cast.rs:671 ↗
pub struct Mxint8;

Implements

Clone, Copy, Debug, Default, BlockScaledFormat
StructNvfp4NVIDIA NVFP4: E2M1 elements, UE4M3 block scale (block=16), per-tensor f32 scale.
cast.rs:563 ↗
pub struct Nvfp4;

Implements

Clone, Copy, Debug, Default, BlockScaledFormat
StructcomplexComplex number with adjacent real and imaginary components of type Scalar.9
types.rs:2171 ↗
pub struct complex<Scalar>

Layout: {re: Scalar, im: Scalar}. Supports conjugate, norm², and component access. Concrete aliases: f16c, bf16c, f32c, f64c.

Fields

reScalarReal component.
imScalarImaginary component.

Implements

FloatLike, Debug, Clone, Copy, StructuralPartialEq, PartialEq, Default, From<f32>, Add, Sub, Mul, Div, Neg, Display, StorageElement, NumberLike, FloatConvertible
from_real_imagBuilds a complex number from its real and imaginary components.
types.rs:2180 ↗
pub const fn from_real_imag(re: Scalar, im: Scalar) -> Self
to_real_imagSplits the complex number into its real and imaginary components.
types.rs:2183 ↗
pub const fn to_real_imag(self) -> (Scalar, Scalar)
where
    Scalar: Copy,
conjComplex conjugate.
types.rs:2193 ↗
pub fn conj(self) -> Self
norm_sqrSquared magnitude, re² + im².
types.rs:2201 ↗
pub fn norm_sqr(self) -> Scalar::Norm
zeroThe additive identity.
types.rs:2288 ↗

Inherited from StorageElement

fn zero() -> Self
oneThe multiplicative identity.
types.rs:2294 ↗

Inherited from StorageElement

fn one() -> Self
from_f32Convert from f32 to this type.
types.rs:2303 ↗

Inherited from NumberLike

fn from_f32(v: f32) -> Self
from_f64Convert from f64 to this type — by default via an f32 roundtrip.
types.rs:2305 ↗

Inherited from NumberLike

fn from_f64(v: f64) -> Self
packPack sub-dimension scalars into a single storage value.
types.rs:2334 ↗

Inherited from FloatConvertible

fn pack(dims: [complex<Scalar>; 1]) -> Self

Functions

castCast source slice elements to destination slice.
cast.rs:188 ↗
pub fn cast<S: CastDType, D: CastDType>(source: &[S], dest: &mut [D]) -> Result<(), Error>

Converts elements from source type S to destination type D using hardware-accelerated SIMD operations when available.

Arguments

  • source - Source slice of elements to cast
  • dest - Destination slice to receive cast elements; must be same length as source

Errors

Examples

use numkong::{f16, cast};

let f16_data: Vec<f16> = vec![f16::from_f32(1.0), f16::from_f32(2.0)];
let mut f32_data: Vec<f32> = vec![0.0; f16_data.len()];
cast(&f16_data, &mut f32_data);