tensor

    Zero-dependency, cross-platform N-dimensional Tensor library for MoonBit inference and numerical computing

    tensor
    ndarray
    ml
    inference
    simd
    wasm
    native
    Download zip
    Author
    Version
    0.1.0
    License
    Apache-2.0
    Last updated
    51 minutes ago
    Downloads
    3

    No dependencies

    #matrixlt/tensor

    零外部依赖、支持 native / wasm / wasm-gc / js 四端编译的纯 MoonBit 多维张量库,面向机器学习推理与高性能数值计算。

    #安装

    moon add matrixlt/tensor

    #核心能力

    • 紧凑非装箱存储:基于 FixedArray 封装 Float32 / Float64 / Int64 / Int32 / Bool 多类型存储,无泛型装箱开销;内置小端序原始字节流互转(from_f32_bytes_le / to_f32_bytes_le)。
    • 零拷贝视图模型:基于 (data, offset, shape, strides) 支持 transpose、squeeze、unsqueeze 与连续 reshape 的零拷贝视图变换。
    • 符号维度与形状推断底座:提供 SymDim / SymShape 符号维度建模,支持动态 Batch/序列维度绑定与解析。
    • 推理缓冲复用池(BufferPool):按精确长度分桶缓存 FixedArray[Float] 与 FixedArray[Byte],并提供 PoolStats 命中率统计,消除高频推理的中间激活 GC 抖动。
    • 完整 NumPy / ONNX 语义:支持多向广播形状与虚拟步长(broadcast_shape / broadcast_strides)、ONNX reshape(-1 自动推导与 0 复制维度)、flatten 与 argmax_f32。

    #快速示例

    let a = @tensor.Tensor::from_f32_array([2, 3], [1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
    let b = a.transpose([1, 0]).contiguous()
    let c = b.reshape([1, -1])

    let pool = @tensor.BufferPool::new()
    let scratch = pool.acquire_f32(1024)
    pool.release_f32(scratch)

    #许可证

    Apache-2.0

    TensorError

    pub(all) suberror TensorError {
    InvalidShape(String)
    ShapeMismatch(String)
    DTypeMismatch(String)
    IndexOutOfBounds(String)
    InvalidAxis(String)
    Unsupported(String)
    } derive(Eq,
    Debug
    )

    张量运算与构建过程中可能抛出的结构化错误类型。
    impl Show for TensorError

    BufferPool

    pub struct BufferPool {
    f32_buckets : Map[Int, Array[FixedArray[Float]]]
    byte_buckets : Map[Int, Array[FixedArray[Byte]]]
    hits : Int
    misses : Int
    max_per_bucket : Int
    }

    面向推理热路径的轻量级缓冲区复用池(参考 rten::TensorPool / ONNX Runtime Arena)。 按精确元素/字节长度分桶缓存已归还的 FixedArray[Float] 与 FixedArray[Byte], 避免每次前向推理反复分配大尺寸中间激活与 im2col 工作缓冲。

    BufferPool::acquire_bytes

    fn BufferPool::acquire_bytes(self : BufferPool, byte_len : Int) -> FixedArray[Byte]

    获取长度为 byte_len 的 FixedArray[Byte](供 SIMD 对齐缓冲与临时序列化复用)。

    BufferPool::acquire_f32

    fn BufferPool::acquire_f32(self : BufferPool, len : Int) -> FixedArray[Float]

    获取长度为 len 的 FixedArray[Float](命中缓存时零分配复用;未命中时新分配)。 注意:复用返回的缓冲区可能包含旧数据,调用方负责覆盖写入或在需要时清零。

    BufferPool::clear

    fn BufferPool::clear(self : BufferPool) -> Unit

    清空池内全部缓存缓冲区以释放内存。

    BufferPool::new

    fn BufferPool::new(max_per_bucket? : Int) -> BufferPool

    创建新的缓冲区复用池;max_per_bucket 限制单个尺寸桶最多缓存的缓冲数量,防止峰值内存滞留。

    BufferPool::release_bytes

    fn BufferPool::release_bytes(self : BufferPool, buf : FixedArray[Byte]) -> Unit

    归还 FixedArray[Byte] 至复用池。

    BufferPool::release_f32

    fn BufferPool::release_f32(self : BufferPool, buf : FixedArray[Float]) -> Unit

    归还不再使用的 FixedArray[Float] 至复用池中供后续算子复用。

    BufferPool::stats

    fn BufferPool::stats(self : BufferPool) -> PoolStats

    返回当前复用池的命中/未命中与已缓存缓冲区统计。

    DType

    pub(all) enum DType {
    Float32
    Float64
    Int64
    Int32
    Bool
    } derive(Eq,
    Debug
    )

    支持的张量基础数据类型,与 ONNX TensorProto.DataType 常用子集一一对应。
    impl Show for DType

    DType::byte_size

    fn DType::byte_size(self : DType) -> Int

    返回单个元素占用的字节数,便于内存估算与 raw_data 解码校验。

    DType::short_name

    fn DType::short_name(self : DType) -> String

    返回面向日志和 CLI 展示的简短类型名称。

    PoolStats

    pub(all) struct PoolStats {
    hits : Int
    misses : Int
    pooled_f32_buffers : Int
    pooled_byte_buffers : Int
    } derive(Eq,
    Debug
    )

    缓冲区复用池统计信息,用于监控高频推理场景下的内存复用命中率与 GC 压力。

    SymDim

    pub(all) enum SymDim {
    Static(Int)
    Sym(String)
    Unknown
    } derive(Eq,
    Debug
    )

    符号维度规格(参考 Tract TDim 与 ONNX TensorShapeProto.Dimension)。 用于在图编译与形状推断阶段同时表达静态维度、命名动态维度(如 batch / seq_len)与未知维度。

    SymDim::resolve

    fn SymDim::resolve(self : SymDim, bindings : Map[String, Int]) -> Int?

    使用运行期符号绑定表(如 {"batch": 4})尝试将符号维度解析为具体整数。

    SymDim::to_label

    fn SymDim::to_label(self : SymDim) -> String

    将单个符号维度格式化为人类可读字符串。

    SymShape

    pub struct SymShape {
    dims : Array[SymDim]
    } derive(Eq,
    Debug
    )

    符号形状包装类型,支持静态化解析、格式化与静态形状判定。

    SymShape::format

    fn SymShape::format(self : SymShape) -> String

    将 SymShape 格式化为 [batch, 1, 28, 28] 形式字符串。

    SymShape::from_dims

    fn SymShape::from_dims(dims : Array[SymDim]) -> SymShape

    从符号维度数组构造 SymShape。

    SymShape::from_static

    fn SymShape::from_static(shape : Array[Int]) -> SymShape

    从静态整数形状数组构造 SymShape。

    SymShape::is_fully_static

    fn SymShape::is_fully_static(self : SymShape) -> Bool

    判断该形状是否全部为已知静态维度。

    SymShape::rank

    fn SymShape::rank(self : SymShape) -> Int

    返回形状阶数(Rank)。

    SymShape::resolve

    fn SymShape::resolve(self : SymShape, bindings : Map[String, Int]) -> Array[Int] raise TensorError

    根据符号绑定表尝试将全部维度解析为静态 Array[Int];若有任一维度无法解析则报错。

    Tensor

    pub struct Tensor {
    data : TensorData
    offset : Int
    shape : Array[Int]
    strides : Array[Int]
    dtype : DType
    }

    多维张量核心结构。 采用 (data, offset, shape, strides) 视图模型,使 Transpose / Squeeze / Reshape(连续时) 能够在不复制底层缓冲的前提下零拷贝完成。

    Tensor::argmax_f32

    fn Tensor::argmax_f32(self : Tensor) -> (Int, Float) raise TensorError

    查找 Float32 张量中最大值的逻辑下标与数值(用于分类模型输出预测类别)。

    Tensor::contiguous

    fn Tensor::contiguous(self : Tensor) -> Tensor raise TensorError

    将张量转换为内存连续的拷贝;若当前已处于连续状态(offset=0 且行主序步长),直接返回自身。

    Tensor::dtype

    fn Tensor::dtype(self : Tensor) -> DType

    返回张量数据类型。

    Tensor::flat_index

    fn Tensor::flat_index(self : Tensor, indices : Array[Int]) -> Int raise TensorError

    将多维坐标转换为底层缓冲区的一维物理下标。

    Tensor::flatten

    fn Tensor::flatten(self : Tensor, axis? : Int) -> Tensor raise TensorError

    ONNX Flatten 算子语义:将张量展平为 2D 矩阵 [d0, d1], 其中 d0 是 [0, axis) 维度的乘积,d1 是 [axis, rank) 维度的乘积。

    Tensor::from_bool

    fn Tensor::from_bool(shape : Array[Int], data : FixedArray[Bool]) -> Tensor raise TensorError

    从 FixedArray[Bool] 构造 Bool 张量。

    Tensor::from_f32

    fn Tensor::from_f32(shape : Array[Int], data : FixedArray[Float]) -> Tensor raise TensorError

    从紧凑的 FixedArray[Float] 构造 Float32 张量。

    Tensor::from_f32_array

    fn Tensor::from_f32_array(shape : Array[Int], values : Array[Float]) -> Tensor raise TensorError

    从动态 Array[Float] 构造 Float32 张量(便于测试与外部数据导入)。

    Tensor::from_f32_bytes_le

    fn Tensor::from_f32_bytes_le(shape : Array[Int], raw : Bytes) -> Tensor raise TensorError

    从小端序原始字节流直接构造 Float32 张量(与 ONNX raw_data 及 SIMD 字节缓冲格式一致)。

    Tensor::from_f64

    fn Tensor::from_f64(shape : Array[Int], data : FixedArray[Double]) -> Tensor raise TensorError

    从 FixedArray[Double] 构造 Float64 张量。

    Tensor::from_i32

    fn Tensor::from_i32(shape : Array[Int], data : FixedArray[Int]) -> Tensor raise TensorError

    从 FixedArray[Int] 构造 Int32 张量。

    Tensor::from_i64

    fn Tensor::from_i64(shape : Array[Int], data : FixedArray[Int64]) -> Tensor raise TensorError

    从 FixedArray[Int64] 构造 Int64 张量(常用于 ONNX Reshape 的 shape 输入及索引)。

    Tensor::full_f32

    fn Tensor::full_f32(shape : Array[Int], value : Float) -> Tensor raise TensorError

    创建指定常量填充的 Float32 张量。

    Tensor::get_f32

    fn Tensor::get_f32(self : Tensor, indices : Array[Int]) -> Float raise TensorError

    读取指定多维坐标处的 Float32 元素值。

    Tensor::get_f32_flat

    fn Tensor::get_f32_flat(self : Tensor, linear : Int) -> Float raise TensorError

    按逻辑行主序下标读取 Float32 元素值(透明兼容非连续视图)。

    Tensor::is_contiguous

    fn Tensor::is_contiguous(self : Tensor) -> Bool

    判断张量在内存中是否为标准 C 风格行主序连续布局(且起始偏移为 0)。 注意:长度为 1 的维度其步长不影响逻辑连续性,但若元素总数为 0 则直接视为连续。

    Tensor::numel

    fn Tensor::numel(self : Tensor) -> Int

    返回张量逻辑元素总数。

    Tensor::offset

    fn Tensor::offset(self : Tensor) -> Int

    返回张量在底层缓冲区中的起始偏移。

    Tensor::physical_index_from_linear

    fn Tensor::physical_index_from_linear(self : Tensor, linear : Int) -> Int

    根据逻辑线性下标计算物理缓冲区下标(自动兼容非连续视图与广播步长)。

    Tensor::rank

    fn Tensor::rank(self : Tensor) -> Int

    返回张量维度阶数(Rank)。

    Tensor::raw_f32_buffer

    fn Tensor::raw_f32_buffer(self : Tensor) -> FixedArray[Float]?

    直接返回底层 Float32 缓冲区(不触发复制),供推理会话在生命周期结束后归还至 BufferPool。 调用方必须确保该张量及其所有共享视图不再被后续使用。

    Tensor::reshape

    fn Tensor::reshape(self : Tensor, target : Array[Int], allowzero? : Bool) -> Tensor raise TensorError

    按 ONNX Reshape 语义重塑张量形状:
    • 维度值 0(当 allowzero == false 时):从输入张量对应轴复制维度大小。
    • 维度值 -1:最多出现一次,根据总元素数自动推导。
    • 若当前张量已连续,返回零拷贝视图;否则先连续化后再重塑。

    Tensor::shape

    fn Tensor::shape(self : Tensor) -> Array[Int]

    返回张量形状的拷贝(防止外部直接修改破坏内部不变量)。

    Tensor::squeeze

    fn Tensor::squeeze(self : Tensor, axes : Array[Int]?) -> Tensor raise TensorError

    移除大小为 1 的指定轴;若 axes 为 None,则移除所有大小为 1 的轴。

    Tensor::strides

    fn Tensor::strides(self : Tensor) -> Array[Int]

    返回张量步长的拷贝。

    Tensor::summary

    fn Tensor::summary(self : Tensor) -> String

    返回简洁易读的张量摘要字符串,便于日志输出与 CLI 调试。

    Tensor::to_f32_buffer

    fn Tensor::to_f32_buffer(self : Tensor) -> FixedArray[Float] raise TensorError

    获取底层连续的 FixedArray[Float] 缓冲区。 若当前张量非连续,会先执行连续化复制以保证返回数组按行主序紧密排列。

    Tensor::to_f32_bytes_le

    fn Tensor::to_f32_bytes_le(self : Tensor) -> FixedArray[Byte] raise TensorError

    将 Float32 张量导出为小端序 FixedArray[Byte],便于直接传入 ml_kernels/vecmath 字节级 SIMD 内核。

    Tensor::to_i64_buffer

    fn Tensor::to_i64_buffer(self : Tensor) -> FixedArray[Int64] raise TensorError

    获取底层连续的 FixedArray[Int64] 缓冲区(常用于读取 ONNX Reshape 的目标 shape 张量)。

    Tensor::transpose

    fn Tensor::transpose(self : Tensor, perm : Array[Int]) -> Tensor raise TensorError

    零拷贝维度重排(Transpose)。 perm 为长度等于张量 rank 的置换数组,例如 2D 矩阵转置为 [1, 0]。

    Tensor::unsqueeze

    fn Tensor::unsqueeze(self : Tensor, axes : Array[Int]) -> Tensor raise TensorError

    在指定轴位置插入大小为 1 的新维度(支持负轴,按插入后新 rank 规范化)。

    Tensor::zeros_f32

    fn Tensor::zeros_f32(shape : Array[Int]) -> Tensor raise TensorError

    创建全 0 初始化的 Float32 张量。

    TensorData

    pub(all) enum TensorData {
    F32(FixedArray[Float])
    F64(FixedArray[Double])
    I64(FixedArray[Int64])
    I32(FixedArray[Int])
    Bool(FixedArray[Bool])
    }

    张量底层紧凑存储。 使用非装箱的 FixedArray 以减少 GC 对象开销,并为后续 SIMD 分块加载奠定基础。

    TensorData::len

    fn TensorData::len(self : TensorData) -> Int

    返回底层存储缓冲区的元素总长度。

    broadcast_shape

    fn broadcast_shape(a : Array[Int], b : Array[Int]) -> Array[Int] raise TensorError

    按 NumPy / ONNX 多向广播规则计算两个形状广播后的目标形状。 从末尾维度向右对齐:两维度相等,或其中之一为 1 时可广播;否则报错。

    broadcast_strides

    fn broadcast_strides(src_shape : Array[Int], src_strides : Array[Int], target_shape : Array[Int]) -> Array[Int] raise TensorError

    计算将源张量广播到 target_shape 后的虚拟步长数组。 发生广播(源维度为 1 或前导补齐维度)的轴步长置为 0,从而无需复制数据即可按目标坐标寻址。

    compute_strides

    fn compute_strides(shape : Array[Int]) -> Array[Int]

    按 C 风格行主序(Row-Major)计算给定形状的默认步长。 例如 shape = [2, 3, 4] 对应 strides = [12, 4, 1]。

    format_shape

    fn format_shape(shape : Array[Int]) -> String

    将整数形状数组格式化为 [d0, d1, ...] 字符串,供日志、摘要与错误信息使用。

    normalize_axis

    fn normalize_axis(axis : Int, rank : Int) -> Int raise TensorError

    将可能为负数的轴索引规范化到 [0, rank) 区间内。 例如 rank = 4, axis = -1 -> 3。

    num_elements

    fn num_elements(shape : Array[Int]) -> Int raise TensorError

    校验形状合法性并计算元素总数(空形状 [] 表示 0 维标量,元素数为 1)。

    unravel_index

    fn unravel_index(linear : Int, shape : Array[Int]) -> Array[Int]

    将行主序逻辑线性下标展开为多维坐标。 例如 shape = [2, 3], linear = 4 -> [1, 1]。