Skip to content

deepbox/core

Types & Validation

Shared types and constants (Shape, Axis, DType, Device), dtype helpers such as promoteTypes, and the input checks that the estimators use.

  • deepbox/core
  • Types

Overview

  • DType lists eleven names, but complex64 and complex128 are reserved: tensor() and zeros() throw DTypeError for them. Use the standalone Complex, Complex64Array and Complex128Array types from deepbox/ndarray for complex data. The string dtype has limited support.
  • promoteTypes(a, b) returns the dtype that a binary operation on two tensors produces. The order is bool, uint8, int32, int64, then float16 and bfloat16, float32, float64. An integer with a float gives the float type, and float16 with bfloat16 gives float32. toFloatDType and isFloatDType cover operations with fractional results.
  • Device is "cpu" | "webgpu" | "wasm". Naming a device here does not make it usable. It needs a registered backend, see Config & Backends and Devices & Execution.
  • checkArray, checkXY and checkIsFitted are the validation helpers for custom estimators. They throw DataValidationError for bad input and NotFittedError for an unfitted estimator. The snake_case names (check_array, check_X_y, check_is_fitted) are deprecated aliases. The validate* helpers are on the Utilities page.

Types

14

Axis

type

Axis identifier.

Can be an integer index (0, 1, ...) or a string alias: - 0 aliases: "index", "rows" - 1 aliases: "columns"

type Axis = number | "index" | "rows" | "columns";

Device

type

Logical compute devices for tensors and modules.

- cpu: Default; CPU execution is always available for built-in ndarray ops. - webgpu: GPU execution. Register WebGpuBackend from deepbox/core (after await backend.init()); tensors created on (or moved to) this device store their data in GPU memory and the accelerated op set (element-wise arithmetic, activations, matmul and batched matmul, reductions over all or selected axes, 2-D convolution and pooling) dispatches to WGSL compute kernels automatically. Read results back with await t.cpu(). - wasm: WASM SIMD host accelerator. Register WasmBackend; tensors on this device keep zero-copy host storage, and eligible ops (contiguous float32 add, sub, mul and div) run through embedded SIMD kernels with bit-identical results, falling back to the CPU implementation otherwise. The dotContiguous and sumContiguous helpers of WasmBackend accumulate in four float32 lanes, so they can differ from the sequential CPU result in the last bits.

type Device = "cpu" | "webgpu" | "wasm";

DType

type

Supported data types for tensors.

- float16: 16-bit floating point (half precision, IEEE 754) - bfloat16: 16-bit Brain Floating Point (same exponent as float32) - float32: 32-bit floating point (single precision) - float64: 64-bit floating point (double precision) - int32: 32-bit signed integer - int64: 64-bit signed integer (BigInt) - uint8: 8-bit unsigned integer - bool: Boolean values (stored as uint8) - complex64: Reserved. Complex number with float32 real and imaginary parts. Tensors cannot be created with this dtype yet (a DTypeError is thrown); use Complex64Array for complex data. - complex128: Reserved. Complex number with float64 real and imaginary parts. Tensors cannot be created with this dtype yet (a DTypeError is thrown); use Complex128Array for complex data. - string: String values (limited support; backed by a string[])

type DType = "float16" | "bfloat16" | "float32" | "float64" | "int32" | "int64" | "uint8" | "bool" | "complex64" | "complex128" | "string";

ElementOf

type

Maps a DType to its JavaScript element type.

- string → string - int64 → bigint - all others → number (the complex dtypes are reserved and have no tensor storage yet)

type ElementOf<D extends DType> = D extends "string" ? string : D extends "int64" ? bigint : number;

ExtendedTypedArray

type

Extended array types for half-precision and complex dtypes.

These are software-emulated typed arrays that provide the same indexed-access interface as native TypedArrays but for types not natively supported by JavaScript.

type ExtendedTypedArray = import("../../ndarray/tensor/float16").Float16Array | import("../../ndarray/tensor/float16").BFloat16Array | import("../../ndarray/tensor/complex").Complex64Array | import("../../ndarray/tensor/complex").Complex128Array;

ScalarDType

type

Numeric DTypes whose JavaScript element type is number. Excludes int64 (BigInt), complex64/complex128, and string.

type ScalarDType = "float16" | "bfloat16" | "float32" | "float64" | "int32" | "uint8" | "bool";

Shape

type

Represents the dimensions of a multi-dimensional array (tensor).

Each element represents the size of that dimension. For example, [2, 3, 4] represents a 3D array with dimensions 2×3×4.

type Shape = readonly number[];

TensorLike

type

Type representing a tensor-like object.

This type defines the core properties that any tensor implementation must provide. It enables type-safe tensor operations and interoperability between different tensor implementations.

  • readonly shape: S
  • readonly dtype: D
  • readonly device: Device
  • readonly data: TensorStorage
  • readonly strides: readonly number[]
  • readonly offset: number
  • readonly size: number
  • readonly ndim: number

TensorStorage

type

Backing storage for a tensor.

Numeric tensors are backed by TypedArrays or ExtendedTypedArrays. String tensors are backed by a string array.

type TensorStorage = TypedArray | ExtendedTypedArray | string[];

TypedArray

type

Union type of all TypedArray types supported by Deepbox.

TypedArrays provide efficient storage and manipulation of numeric data in JavaScript, offering better performance than regular arrays for numerical computations.

type TypedArray = Float32Array | Float64Array | Int32Array | BigInt64Array | Uint8Array;

DEVICES

const
const DEVICES: readonly Device[];

DTYPES

const
const DTYPES: readonly DType[];

NumericDType

type

All DType values except "string". Used when an operation requires numeric data.

type NumericDType = Exclude<DType, "string">;

NumericTypedArray

type

Numeric typed arrays (excludes BigInt64Array).

type NumericTypedArray = Float32Array | Float64Array | Int32Array | Uint8Array;

Functions

16

isDevice

function isDevice(value: unknown): value is Device;

Type guard to check if a value is a valid Device.

Parameters

value
unknown
The value to check

Returns

value is DeviceTrue if value is a valid Device, false otherwise

Example
import { isDevice } from 'deepbox/core'; if (isDevice('cpu')) {  console.log('Valid device');} isDevice('gpu');  // falseisDevice('cpu');  // true

isDType

function isDType(value: unknown): value is DType;

Type guard to check if a value is a valid DType.

Parameters

value
unknown
The value to check

Returns

value is DTypeTrue if value is a valid DType, false otherwise

Example
import { isDType } from 'deepbox/core'; if (isDType('float32')) {  console.log('Valid dtype');} isDType('float128');  // falseisDType('int32');     // true

isFloatDType

function isFloatDType(dtype: DType): boolean;

True for float16, bfloat16, float32 and float64.

Parameters

dtype
DType
Data type identifier

Returns

boolean

Example
isFloatDType("float32"); // trueisFloatDType("int32"); // false

promoteTypes

function promoteTypes(a: DType, b: DType): DType;

Result dtype of a tensor-tensor binary operation (PyTorch-style type promotion).

The order is bool < uint8 < int32 < int64 < float16, bfloat16 < float32 < float64. Within one category the wider type wins, an integer combined with a float gives the float type, and float16 combined with bfloat16 gives float32. A complex dtype absorbs real dtypes (complex64 with float64 gives complex128). string never promotes.

Parameters

a
DType
First dtype
b
DType
Second dtype

Returns

DTypeThe common dtype both operands convert to

Throws

  • DTypeErrorIf either dtype is string
Example
promoteTypes("int32", "float32"); // "float32"promoteTypes("uint8", "int64"); // "int64"promoteTypes("float16", "bfloat16"); // "float32"

toFloatDType

function toFloatDType(dtype: DType): "float16" | "bfloat16" | "float32" | "float64";

Result dtype for operations that produce fractional values (exp, sqrt, mean, softmax, ...).

Float dtypes are kept as they are; integer and bool input computes in float32, Deepbox's default float dtype.

Parameters

dtype
DType
Input dtype

Returns

"float16" | "bfloat16" | "float32" | "float64"dtype itself for float dtypes, otherwise "float32"

Example
toFloatDType("float64"); // "float64"toFloatDType("int32"); // "float32"

asReadonlyArray

function asReadonlyArray<T extends number[]>(arr: T): readonly number[];

Create a readonly number array from mutable array with proper typing. This avoids the need for as Shape assertions.

Parameters

arr
T
The mutable number array

Returns

readonly number[]The same array typed as readonly

getArrayElement

function getArrayElement(arr: readonly number[], index: number, defaultValue?: number): number;

Get an element from a number array at the specified index. Returns the provided default value if the index is out of bounds.

Parameters

arr
readonly number[]
The number array
index
number
The index to access
defaultValueoptional
number
The default value to return if out of bounds (default: 0)

Returns

numberThe element at the index, or the default value if out of bounds

getBigIntElement

function getBigIntElement(arr: BigInt64Array, index: number): bigint;

Get an element from a BigInt64Array at the specified index.

Parameters

arr
BigInt64Array
The BigInt64Array
index
number
The index to access

Returns

bigintThe element at the index

Throws

  • IndexErrorIf the index is out of bounds

getElementAsNumber

function getElementAsNumber(arr: TypedArray, index: number): number;

Get an element from a TypedArray, returning as number. For BigInt64Array, converts to number (throws if out of safe integer range).

Parameters

arr
TypedArray
The typed array
index
number
The index to access

Returns

numberThe element at the index as a number

Throws

  • IndexErrorIf the index is out of bounds
  • DataValidationErrorIf a bigint value exceeds the safe integer range

getNumericElement

function getNumericElement(arr: NumericTypedArray, index: number): number;

Get an element from a numeric typed array at the specified index.

Parameters

arr
NumericTypedArray
The numeric typed array
index
number
The index to access

Returns

numberThe element at the index

Throws

  • IndexErrorIf the index is out of bounds

getShapeDim

function getShapeDim(shape: readonly number[], index: number): number;

Get an element from a shape array at the specified index. Returns 1 if the index is out of bounds (used in broadcasting where missing leading dimensions are treated as size 1).

Parameters

shape
readonly number[]
The shape array
index
number
The index to access

Returns

numberThe dimension at the index, or 1 if out of bounds

getStringElement

function getStringElement(arr: readonly string[], index: number): string;

Safely get a string from a string array at the specified index. Returns empty string if the index is out of bounds.

Parameters

arr
readonly string[]
The string array
index
number
The index to access

Returns

stringThe string at the index, or empty string if out of bounds

isBigInt64Array

function isBigInt64Array(arr: TypedArray): arr is BigInt64Array;

Type guard to check if a typed array is a BigInt64Array.

Parameters

arr
TypedArray
The typed array to check

Returns

arr is BigInt64ArrayTrue if the array is a BigInt64Array

isNumericTypedArray

function isNumericTypedArray(arr: TypedArray): arr is NumericTypedArray;

Type guard to check if a typed array is a numeric (non-BigInt) array.

Parameters

arr
TypedArray
The typed array to check

Returns

arr is NumericTypedArrayTrue if the array is a numeric typed array

isTypedArray

function isTypedArray(value: unknown): value is TypedArray;

Type guard to check if a value is one of the supported TypedArray types.

Details

Returns true for instances of the TypedArray classes in the Deepbox TypedArray union: Float32Array, Float64Array, Int32Array, BigInt64Array, and Uint8Array (subclasses such as Node.js Buffer included). Returns false for unsupported typed arrays (e.g. Uint16Array, Int16Array, Uint8ClampedArray), DataView, and regular arrays. The check uses instanceof, so arrays created in another realm (iframe, vm context) are not recognised.

Parameters

value
unknown
The value to check

Returns

value is TypedArrayTrue if value is a supported TypedArray, false otherwise

Example
import { isTypedArray } from 'deepbox/core'; isTypedArray(new Float32Array(10));  // trueisTypedArray(new Uint16Array(10));   // false (unsupported)isTypedArray([1, 2, 3]);             // falseisTypedArray(new DataView(new ArrayBuffer(10)));  // false

shapesEqual

function shapesEqual(a: readonly number[], b: readonly number[]): boolean;

Check if two shapes are equal element-wise.

Parameters

a
readonly number[]
First shape
b
readonly number[]
Second shape

Returns

booleanTrue if shapes have the same length and each dimension matches

Example
import { shapesEqual } from 'deepbox/core'; shapesEqual([2, 3], [2, 3]); // trueshapesEqual([2, 3], [3, 2]); // false

Deprecated names

3

These older spellings still work in 1.x. New code should use the names above.

  • check_arrayPrefer checkArray.
  • check_is_fittedPrefer checkIsFitted.
  • check_X_yPrefer checkXY.
core-types.ts
import {  DEVICES,  DTYPES,  checkArray,  checkXY,  isDType,  isDevice,  isFloatDType,  promoteTypes,  toFloatDType,  type Axis,  type DType,  type Shape,} from "deepbox/core";import { tensor } from "deepbox/ndarray"; const shape: Shape = [2, 3];const dtype: DType = "float32";const axis: Axis = 1; console.log(DTYPES.includes(dtype), DEVICES, isDType(dtype), isDevice("cpu"));console.log(promoteTypes("int32", "float32")); // float32console.log(promoteTypes("float16", "bfloat16")); // float32console.log(toFloatDType("int32"), isFloatDType("int32")); // float32 false // Validation helpers return their input or throw DataValidationError.const X = tensor([[1, 2], [3, 4]]);const y = tensor([0, 1]);checkArray(X, { ensureNdim: 2 });checkXY(X, y);console.log(shape, axis);