Transformers.js documentation

utils/tensor

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

utils/tensor

Helper module for Tensor processing.

These functions and classes are only used internally, meaning an end-user shouldn’t need to access anything here.


utils/tensor.Tensor

Kind: static class of utils/tensor


new Tensor(...args)

Create a new Tensor or copy an existing Tensor.

ParamType
...args*

tensor.dims : <code> Array. < number > </code>

Dimensions of the tensor.

Kind: instance property of Tensor


tensor.type : <code> DataType </code>

Type of the tensor.

Kind: instance property of Tensor


tensor.data : <code> DataArray </code>

The data stored in the tensor.

Kind: instance property of Tensor


tensor.size : <code> number </code>

The number of elements in the tensor.

Kind: instance property of Tensor


tensor.location : <code> string </code>

The location of the tensor data.

Kind: instance property of Tensor


tensor.Symbol.iterator() β‡’ <code> Iterator </code>

Returns an iterator object for iterating over the tensor data in row-major order. If the tensor has more than one dimension, the iterator will yield subarrays.

Kind: instance method of Tensor
Returns: Iterator - An iterator object for iterating over the tensor data in row-major order.


tensor._getitem(index) β‡’ <code> Tensor </code>

Index into a Tensor object.

Kind: instance method of Tensor
Returns: Tensor - The data at the specified index.

ParamTypeDescription
indexnumber

The index to access.


tensor.indexOf(item) β‡’ <code> number </code>

Kind: instance method of Tensor
Returns: number - The index of the first occurrence of item in the tensor data.

ParamTypeDescription
itemnumber | bigint

The item to search for in the tensor


tensor._subarray(index, iterSize, iterDims) β‡’ <code> Tensor </code>

Kind: instance method of Tensor

ParamType
indexnumber
iterSizenumber
iterDimsany

tensor.item() β‡’ <code> number </code> | <code> bigint </code>

Returns the value of this tensor as a standard JavaScript Number. This only works for tensors with one element. For other cases, see Tensor.tolist().

Kind: instance method of Tensor
Returns: number | bigint - The value of this tensor as a standard JavaScript Number.
Throws:

  • Error If the tensor has more than one element.

tensor.tolist() β‡’ <code> Array </code>

Convert tensor data to a n-dimensional JS list

Kind: instance method of Tensor


tensor.sigmoid() β‡’ <code> Tensor </code>

Return a new Tensor with the sigmoid function applied to each element.

Kind: instance method of Tensor
Returns: Tensor - The tensor with the sigmoid function applied.


tensor.sigmoid_() β‡’ <code> Tensor </code>

Applies the sigmoid function to the tensor in place.

Kind: instance method of Tensor
Returns: Tensor - Returns this.


tensor.map(callback) β‡’ <code> Tensor </code>

Return a new Tensor with a callback function applied to each element.

Kind: instance method of Tensor
Returns: Tensor - A new Tensor with the callback function applied to each element.

ParamTypeDescription
callbackfunction

The function to apply to each element. It should take three arguments: the current element, its index, and the tensor's data array.


tensor.map_(callback) β‡’ <code> Tensor </code>

Apply a callback function to each element of the tensor in place.

Kind: instance method of Tensor
Returns: Tensor - Returns this.

ParamTypeDescription
callbackfunction

The function to apply to each element. It should take three arguments: the current element, its index, and the tensor's data array.


tensor.mul(val) β‡’ <code> Tensor </code>

Return a new Tensor with every element multiplied by a constant.

Kind: instance method of Tensor
Returns: Tensor - The new tensor.

ParamTypeDescription
valnumber

The value to multiply by.


tensor.mul_(val) β‡’ <code> Tensor </code>

Multiply the tensor by a constant in place.

Kind: instance method of Tensor
Returns: Tensor - Returns this.

ParamTypeDescription
valnumber

The value to multiply by.


tensor.div(val) β‡’ <code> Tensor </code>

Return a new Tensor with every element divided by a constant.

Kind: instance method of Tensor
Returns: Tensor - The new tensor.

ParamTypeDescription
valnumber

The value to divide by.


tensor.div_(val) β‡’ <code> Tensor </code>

Divide the tensor by a constant in place.

Kind: instance method of Tensor
Returns: Tensor - Returns this.

ParamTypeDescription
valnumber

The value to divide by.


tensor.add(val) β‡’ <code> Tensor </code>

Return a new Tensor with every element added by a constant.

Kind: instance method of Tensor
Returns: Tensor - The new tensor.

ParamTypeDescription
valnumber

The value to add by.


tensor.add_(val) β‡’ <code> Tensor </code>

Add the tensor by a constant in place.

Kind: instance method of Tensor
Returns: Tensor - Returns this.

ParamTypeDescription
valnumber

The value to add by.


tensor.sub(val) β‡’ <code> Tensor </code>

Return a new Tensor with every element subtracted by a constant.

Kind: instance method of Tensor
Returns: Tensor - The new tensor.

ParamTypeDescription
valnumber

The value to subtract by.


tensor.sub_(val) β‡’ <code> Tensor </code>

Subtract the tensor by a constant in place.

Kind: instance method of Tensor
Returns: Tensor - Returns this.

ParamTypeDescription
valnumber

The value to subtract by.


tensor.permute(...dims) β‡’ <code> Tensor </code>

Return a permuted version of this Tensor, according to the provided dimensions.

Kind: instance method of Tensor
Returns: Tensor - The permuted tensor.

ParamTypeDescription
...dimsnumber

Dimensions to permute.


tensor.sum([dim], keepdim) β‡’

Returns the sum of each row of the input tensor in the given dimension dim.

Kind: instance method of Tensor
Returns: The summed tensor

ParamTypeDefaultDescription
[dim]number

The dimension or dimensions to reduce. If null, all dimensions are reduced.

keepdimbooleanfalse

Whether the output tensor has dim retained or not.


tensor.norm([p], [dim], [keepdim]) β‡’ <code> Tensor </code>

Returns the matrix norm or vector norm of a given tensor.

Kind: instance method of Tensor
Returns: Tensor - The norm of the tensor.

ParamTypeDefaultDescription
[p]number | string'fro'

The order of norm

[dim]number

Specifies which dimension of the tensor to calculate the norm across. If dim is None, the norm will be calculated across all dimensions of input.

[keepdim]booleanfalse

Whether the output tensors have dim retained or not.


tensor.normalize_([p], [dim]) β‡’ <code> Tensor </code>

Performs L_p normalization of inputs over specified dimension. Operates in place.

Kind: instance method of Tensor
Returns: Tensor - this for operation chaining.

ParamTypeDefaultDescription
[p]number2

The exponent value in the norm formulation

[dim]number1

The dimension to reduce


tensor.normalize([p], [dim]) β‡’ <code> Tensor </code>

Performs L_p normalization of inputs over specified dimension.

Kind: instance method of Tensor
Returns: Tensor - The normalized tensor.

ParamTypeDefaultDescription
[p]number2

The exponent value in the norm formulation

[dim]number1

The dimension to reduce


tensor.stride() β‡’ <code> Array. < number > </code>

Compute and return the stride of this tensor. Stride is the jump necessary to go from one element to the next one in the specified dimension dim.

Kind: instance method of Tensor
Returns: Array.<number> - The stride of this tensor.


tensor.squeeze([dim]) β‡’ <code> Tensor </code>

Returns a tensor with all specified dimensions of input of size 1 removed.

NOTE: The returned tensor shares the storage with the input tensor, so changing the contents of one will change the contents of the other. If you would like a copy, use tensor.clone() before squeezing.

Kind: instance method of Tensor
Returns: Tensor - The squeezed tensor

ParamTypeDefaultDescription
[dim]number

If given, the input will be squeezed only in the specified dimensions.


tensor.squeeze_()

In-place version of @see Tensor.squeeze

Kind: instance method of Tensor


tensor.unsqueeze(dim) β‡’ <code> Tensor </code>

Returns a new tensor with a dimension of size one inserted at the specified position.

NOTE: The returned tensor shares the same underlying data with this tensor.

Kind: instance method of Tensor
Returns: Tensor - The unsqueezed tensor

ParamTypeDefaultDescription
dimnumber

The index at which to insert the singleton dimension


tensor.unsqueeze_()

In-place version of @see Tensor.unsqueeze

Kind: instance method of Tensor


tensor.flatten_()

In-place version of @see Tensor.flatten

Kind: instance method of Tensor


tensor.flatten(start_dim, end_dim) β‡’ <code> Tensor </code>

Flattens input by reshaping it into a one-dimensional tensor. If start_dim or end_dim are passed, only dimensions starting with start_dim and ending with end_dim are flattened. The order of elements in input is unchanged.

Kind: instance method of Tensor
Returns: Tensor - The flattened tensor.

ParamTypeDefaultDescription
start_dimnumber0

the first dim to flatten

end_dimnumber

the last dim to flatten


tensor.view(...dims) β‡’ <code> Tensor </code>

Returns a new tensor with the same data as the self tensor but of a different shape.

Kind: instance method of Tensor
Returns: Tensor - The tensor with the same data but different shape

ParamTypeDescription
...dimsnumber

the desired size


tensor.clamp_()

In-place version of @see Tensor.clamp

Kind: instance method of Tensor


tensor.clamp(min, max) β‡’ <code> Tensor </code>

Clamps all elements in input into the range [ min, max ]

Kind: instance method of Tensor
Returns: Tensor - the output tensor.

ParamTypeDescription
minnumber

lower-bound of the range to be clamped to

maxnumber

upper-bound of the range to be clamped to


tensor.round_()

In-place version of @see Tensor.round

Kind: instance method of Tensor


tensor.round() β‡’ <code> Tensor </code>

Rounds elements of input to the nearest integer.

Kind: instance method of Tensor
Returns: Tensor - the output tensor.


tensor.to(type) β‡’ <code> Tensor </code>

Performs Tensor dtype conversion.

Kind: instance method of Tensor
Returns: Tensor - The converted tensor.

ParamTypeDescription
typeDataType

The desired data type.


utils/tensor.permute(tensor, axes) β‡’ <code> Tensor </code>

Permutes a tensor according to the provided axes.

Kind: static method of utils/tensor
Returns: Tensor - The permuted tensor.

ParamTypeDescription
tensorany

The input tensor to permute.

axesArray

The axes to permute the tensor along.


utils/tensor.interpolate(input, size, mode, align_corners) β‡’ <code> Tensor </code>

Interpolates an Tensor to the given size.

Kind: static method of utils/tensor
Returns: Tensor - The interpolated tensor.

ParamTypeDescription
inputTensor

The input tensor to interpolate. Data must be channel-first (i.e., [c, h, w])

sizeArray.<number>

The output size of the image

modestring

The interpolation mode

align_cornersboolean

Whether to align corners.


utils/tensor.interpolate_4d(input, options) β‡’ <code> Promise. < Tensor > </code>

Down/up samples the input. Inspired by https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html.

Kind: static method of utils/tensor
Returns: Promise.<Tensor> - The interpolated tensor.

ParamTypeDefaultDescription
inputTensor

the input tensor

optionsObject

the options for the interpolation

[options.size]*

output spatial size.

[options.mode]"bilinear" | "bicubic"'bilinear'

algorithm used for upsampling


utils/tensor.matmul(a, b) β‡’ <code> Promise. < Tensor > </code>

Matrix product of two tensors. Inspired by https://pytorch.org/docs/stable/generated/torch.matmul.html

Kind: static method of utils/tensor
Returns: Promise.<Tensor> - The matrix product of the two tensors.

ParamTypeDescription
aTensor

the first tensor to be multiplied

bTensor

the second tensor to be multiplied


utils/tensor.rfft(x, a) β‡’ <code> Promise. < Tensor > </code>

Computes the one dimensional Fourier transform of real-valued input. Inspired by https://pytorch.org/docs/stable/generated/torch.fft.rfft.html

Kind: static method of utils/tensor
Returns: Promise.<Tensor> - the output tensor.

ParamTypeDescription
xTensor

the real input tensor

aTensor

The dimension along which to take the one dimensional real FFT.


utils/tensor.topk(x, k) β‡’ <code> * </code>

Returns the k largest elements of the given input tensor. Inspired by https://pytorch.org/docs/stable/generated/torch.topk.html

Kind: static method of utils/tensor
Returns: * - the output tuple of (Tensor, LongTensor) of top-k elements and their indices.

ParamTypeDescription
xTensor

the input tensor

knumber

the k in "top-k"


utils/tensor.mean_pooling(last_hidden_state, attention_mask) β‡’ <code> Tensor </code>

Perform mean pooling of the last hidden state followed by a normalization step.

Kind: static method of utils/tensor
Returns: Tensor - Returns a new Tensor of shape [batchSize, embedDim].

ParamTypeDescription
last_hidden_stateTensor

Tensor of shape [batchSize, seqLength, embedDim]

attention_maskTensor

Tensor of shape [batchSize, seqLength]


utils/tensor.layer_norm(input, normalized_shape, options) β‡’ <code> Tensor </code>

Apply Layer Normalization for last certain number of dimensions.

Kind: static method of utils/tensor
Returns: Tensor - The normalized tensor.

ParamTypeDefaultDescription
inputTensor

The input tensor

normalized_shapeArray.<number>

input shape from an expected input of size

optionsObject

The options for the layer normalization

[options.eps]number1e-5

A value added to the denominator for numerical stability.


utils/tensor.cat(tensors, dim) β‡’ <code> Tensor </code>

Concatenates an array of tensors along a specified dimension.

Kind: static method of utils/tensor
Returns: Tensor - The concatenated tensor.

ParamTypeDescription
tensorsArray.<Tensor>

The array of tensors to concatenate.

dimnumber

The dimension to concatenate along.


utils/tensor.stack(tensors, dim) β‡’ <code> Tensor </code>

Stack an array of tensors along a specified dimension.

Kind: static method of utils/tensor
Returns: Tensor - The stacked tensor.

ParamTypeDescription
tensorsArray.<Tensor>

The array of tensors to stack.

dimnumber

The dimension to stack along.


utils/tensor.std_mean(input, dim, correction, keepdim) β‡’ <code> Array. < Tensor > </code>

Calculates the standard deviation and mean over the dimensions specified by dim. dim can be a single dimension or null to reduce over all dimensions.

Kind: static method of utils/tensor
Returns: Array.<Tensor> - A tuple of (std, mean) tensors.

ParamTypeDescription
inputTensor

the input tenso

dimnumber | null

the dimension to reduce. If None, all dimensions are reduced.

correctionnumber

difference between the sample size and sample degrees of freedom. Defaults to Bessel's correction, correction=1.

keepdimboolean

whether the output tensor has dim retained or not.


utils/tensor.mean(input, dim, keepdim) β‡’ <code> Tensor </code>

Returns the mean value of each row of the input tensor in the given dimension dim.

Kind: static method of utils/tensor
Returns: Tensor - A new tensor with means taken along the specified dimension.

ParamTypeDescription
inputTensor

the input tensor.

dimnumber | null

the dimension to reduce.

keepdimboolean

whether the output tensor has dim retained or not.


utils/tensor.full(size, fill_value) β‡’ <code> Tensor </code>

Creates a tensor of size size filled with fill_value. The tensor’s dtype is inferred from fill_value.

Kind: static method of utils/tensor
Returns: Tensor - The filled tensor.

ParamTypeDescription
sizeArray.<number>

A sequence of integers defining the shape of the output tensor.

fill_valuenumber | bigint

The value to fill the output tensor with.


utils/tensor.ones(size) β‡’ <code> Tensor </code>

Returns a tensor filled with the scalar value 1, with the shape defined by the variable argument size.

Kind: static method of utils/tensor
Returns: Tensor - The ones tensor.

ParamTypeDescription
sizeArray.<number>

A sequence of integers defining the shape of the output tensor.


utils/tensor.ones_like(tensor) β‡’ <code> Tensor </code>

Returns a tensor filled with the scalar value 1, with the same size as input.

Kind: static method of utils/tensor
Returns: Tensor - The ones tensor.

ParamTypeDescription
tensorTensor

The size of input will determine size of the output tensor.


utils/tensor.zeros(size) β‡’ <code> Tensor </code>

Returns a tensor filled with the scalar value 0, with the shape defined by the variable argument size.

Kind: static method of utils/tensor
Returns: Tensor - The zeros tensor.

ParamTypeDescription
sizeArray.<number>

A sequence of integers defining the shape of the output tensor.


utils/tensor.zeros_like(tensor) β‡’ <code> Tensor </code>

Returns a tensor filled with the scalar value 0, with the same size as input.

Kind: static method of utils/tensor
Returns: Tensor - The zeros tensor.

ParamTypeDescription
tensorTensor

The size of input will determine size of the output tensor.


utils/tensor.quantize_embeddings(tensor, precision) β‡’ <code> Tensor </code>

Quantizes the embeddings tensor to binary or unsigned binary precision.

Kind: static method of utils/tensor
Returns: Tensor - The quantized tensor.

ParamTypeDescription
tensorTensor

The tensor to quantize.

precision'binary' | 'ubinary'

The precision to use for quantization.


utils/tensor~args[0] : <code> ONNXTensor </code>

Kind: inner property of utils/tensor


utils/tensor~reshape(data, dimensions) β‡’ <code> * </code>

Reshapes a 1-dimensional array into an n-dimensional array, according to the provided dimensions.

Kind: inner method of utils/tensor
Returns: * - The reshaped array.

ParamTypeDescription
dataArray<T> | DataArray

The input array to reshape.

dimensionsDIM

The target shape/dimensions.

Example

reshape([10                    ], [1      ]); // Type: number[]      Value: [10]
  reshape([1, 2, 3, 4            ], [2, 2   ]); // Type: number[][]    Value: [[1, 2], [3, 4]]
  reshape([1, 2, 3, 4, 5, 6, 7, 8], [2, 2, 2]); // Type: number[][][]  Value: [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
  reshape([1, 2, 3, 4, 5, 6, 7, 8], [4, 2   ]); // Type: number[][]    Value: [[1, 2], [3, 4], [5, 6], [7, 8]]

reshape~reshapedArray : <code> any </code>

Kind: inner property of reshape


utils/tensor~DataArray : <code> * </code>

Kind: inner typedef of utils/tensor


utils/tensor~NestArray : <code> * </code>

This creates a nested array of a given type and depth (see examples).

Kind: inner typedef of utils/tensor
Example

NestArray<string, 1>; // string[]

Example

NestArray<number, 2>; // number[][]

Example

NestArray<string, 3>; // string[][][] etc.

< > Update on GitHub