Implementation:Tensorflow Tfjs CPU Cast Kernel
Appearance
| Knowledge Sources | |
|---|---|
| Domains | Deep_Learning, CPU_Backend |
| Last Updated | 2026-02-10 06:00 GMT |
Overview
The Cast kernel implements data type conversion for tensors on the CPU backend. It supports casting between numeric types (int32, float32, bool) and handles complex64 as a special case by decomposing into real/imaginary parts. When casting to higher precision with no encoding loss, it reuses the underlying data buffer via identity.
Code Reference
Source Location
tfjs-backend-cpu/src/kernels/Cast.ts (GitHub)
Signature
export function castImpl(
values: TypedArray, shape: number[], inputType: DataType,
dtype: DataType): [number[], DataType, TypedArray]
export function cast(
args: {inputs: CastInputs, backend: MathBackendCPU, attrs: CastAttrs}):
TensorInfo
Imports
import {Cast, CastAttrs, CastInputs, DataType, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';
import {MathBackendCPU} from '../backend_cpu';
import {createSimpleBinaryKernelImpl} from '../utils/binary_impl';
import {zeros} from '../utils/zeros_impl';
import {complex} from './Complex';
import {identity} from './Identity';
import {real} from './Real';
Kernel Registration
export const castConfig: KernelConfig = {
kernelName: Cast,
backendName: 'cpu',
kernelFunc: cast as unknown as KernelFunc
};
I/O Contract
| Parameter | Type | Description |
|---|---|---|
inputs.x |
TensorInfo |
The input tensor to cast |
attrs.dtype |
DataType |
Target data type ('int32', 'float32', 'bool', 'complex64')
|
| Return | TensorInfo |
A new tensor with the requested dtype |
Implementation Details
- To
int32: UsesInt32Array.from(values)for direct type coercion. - To
bool: Applies a binary comparison against zero usingcreateSimpleBinaryKernelImpl(equivalent tonotEqual(x, 0), implemented inline to avoid circular dependencies). - To
complex64: Casts the input tofloat32, creates a zero-filled imaginary part, and combines them via thecomplexkernel. - From
complex64: Extracts the real part viareal, then recursively casts to the target dtype. - No encoding loss: Returns an identity reference with the dtype overridden (no data copy).
Usage Examples
import {cast} from './Cast';
// Cast float32 tensor to int32
const result = cast({
inputs: {x: floatTensor},
backend: cpuBackend,
attrs: {dtype: 'int32'}
});
Related Pages
Page Connections
Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment