Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Tensorflow Tfjs CPU Cast Kernel

From Leeroopedia
Revision as of 16:50, 16 February 2026 by Admin (talk | contribs) (Auto-imported from implementations/Tensorflow_Tfjs_CPU_Cast_Kernel.md)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)


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: Uses Int32Array.from(values) for direct type coercion.
  • To bool: Applies a binary comparison against zero using createSimpleBinaryKernelImpl (equivalent to notEqual(x, 0), implemented inline to avoid circular dependencies).
  • To complex64: Casts the input to float32, creates a zero-filled imaginary part, and combines them via the complex kernel.
  • From complex64: Extracts the real part via real, 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