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
DTypelists eleven names, butcomplex64andcomplex128are reserved:tensor()andzeros()throwDTypeErrorfor them. Use the standaloneComplex,Complex64ArrayandComplex128Arraytypes fromdeepbox/ndarrayfor complex data. Thestringdtype has limited support.promoteTypes(a, b)returns the dtype that a binary operation on two tensors produces. The order isbool,uint8,int32,int64, thenfloat16andbfloat16,float32,float64. An integer with a float gives the float type, andfloat16withbfloat16givesfloat32.toFloatDTypeandisFloatDTypecover operations with fractional results.Deviceis"cpu" | "webgpu" | "wasm". Naming a device here does not make it usable. It needs a registered backend, see Config & Backends and Devices & Execution.checkArray,checkXYandcheckIsFittedare the validation helpers for custom estimators. They throwDataValidationErrorfor bad input andNotFittedErrorfor an unfitted estimator. The snake_case names (check_array,check_X_y,check_is_fitted) are deprecated aliases. Thevalidate*helpers are on the Utilities page.
Axis
typeAxis 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
typeLogical 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
typeSupported 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
typeMaps 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
typeExtended 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
typeNumeric DTypes whose JavaScript element type is number. Excludes int64 (BigInt), complex64/complex128, and string.
type ScalarDType = "float16" | "bfloat16" | "float32" | "float64" | "int32" | "uint8" | "bool";Shape
typeRepresents 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
typeType 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: Sreadonly dtype: Dreadonly device: Devicereadonly data: TensorStoragereadonly strides: readonly number[]readonly offset: numberreadonly size: numberreadonly ndim: number
TensorStorage
typeBacking 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
typeUnion 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
constconst DEVICES: readonly Device[];DTYPES
constconst DTYPES: readonly DType[];NumericDType
typeAll DType values except "string". Used when an operation requires numeric data.
type NumericDType = Exclude<DType, "string">;NumericTypedArray
typeNumeric typed arrays (excludes BigInt64Array).
type NumericTypedArray = Float32Array | Float64Array | Int32Array | Uint8Array;isDevice
function isDevice(value: unknown): value is Device;Type guard to check if a value is a valid Device.
Parameters
valueunknown- The value to check
Returns
value is DeviceTrue if value is a valid Device, false otherwise
import { isDevice } from 'deepbox/core'; if (isDevice('cpu')) { console.log('Valid device');} isDevice('gpu'); // falseisDevice('cpu'); // trueisDType
function isDType(value: unknown): value is DType;Type guard to check if a value is a valid DType.
Parameters
valueunknown- The value to check
Returns
value is DTypeTrue if value is a valid DType, false otherwise
import { isDType } from 'deepbox/core'; if (isDType('float32')) { console.log('Valid dtype');} isDType('float128'); // falseisDType('int32'); // trueisFloatDType
function isFloatDType(dtype: DType): boolean;True for float16, bfloat16, float32 and float64.
Parameters
dtypeDType- Data type identifier
Returns
boolean
isFloatDType("float32"); // trueisFloatDType("int32"); // falsepromoteTypes
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
aDType- First dtype
bDType- Second dtype
Returns
DTypeThe common dtype both operands convert to
Throws
DTypeErrorIf either dtype isstring
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
dtypeDType- Input dtype
Returns
"float16" | "bfloat16" | "float32" | "float64"dtype itself for float dtypes, otherwise "float32"
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
arrT- 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
arrreadonly number[]- The number array
indexnumber- The index to access
defaultValueoptionalnumber- 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
arrBigInt64Array- The BigInt64Array
indexnumber- 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
arrTypedArray- The typed array
indexnumber- The index to access
Returns
numberThe element at the index as a number
Throws
IndexErrorIf the index is out of boundsDataValidationErrorIf 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
arrNumericTypedArray- The numeric typed array
indexnumber- 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
shapereadonly number[]- The shape array
indexnumber- 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
arrreadonly string[]- The string array
indexnumber- 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
arrTypedArray- 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
arrTypedArray- 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
valueunknown- The value to check
Returns
value is TypedArrayTrue if value is a supported TypedArray, false otherwise
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))); // falseshapesEqual
function shapesEqual(a: readonly number[], b: readonly number[]): boolean;Check if two shapes are equal element-wise.
Parameters
areadonly number[]- First shape
breadonly number[]- Second shape
Returns
booleanTrue if shapes have the same length and each dimension matches
import { shapesEqual } from 'deepbox/core'; shapesEqual([2, 3], [2, 3]); // trueshapesEqual([2, 3], [3, 2]); // falseThese 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.
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);Found a mistake? Open an issue.