Skip to main content
The Tensor class represents multi-dimensional arrays used for model inputs and outputs in ONNX Runtime JavaScript.

Importing

Creating Tensors

Constructor

Creates a new tensor.
Parameters:
  • type: Data type of the tensor
  • data: Tensor data as typed array or array
  • dims: Shape of the tensor (optional for 1D)

Float32 Tensor

Int64 Tensor

String Tensor

1D Tensor (No Dims)

Tensor Types

Supported data types:

Type Mapping

Tensor Properties

data

Gets the tensor data.
Example:

dims

Gets the tensor dimensions.
Example:

type

Gets the tensor data type.
Example:

size

Gets the total number of elements.
Example:

GPU Tensors (WebGPU)

Creating from GPU Buffer

Example:

WebGL Texture

Practical Examples

Image Tensor

Batch Tensor

Text Tokenization

Attention Mask

Tensor Manipulation

Reshaping

Normalization

Working with Different Formats

HWC to CHW Conversion

One-Hot Encoding

Memory Management

Reusing Buffers

Type Guards

Performance Tips

  1. Reuse typed arrays: Avoid creating new arrays for each inference
  2. Use appropriate types: Match model input types exactly
  3. Pre-allocate buffers: Create tensor buffers once
  4. Batch processing: Combine multiple inputs when possible
  5. GPU tensors: Use WebGPU buffers for better performance

See Also