Implementation:Tensorflow Tfjs CPU ResizeNearestNeighborGrad Kernel
| Knowledge Sources | |
|---|---|
| Domains | Deep_Learning, CPU_Backend |
| Last Updated | 2026-02-10 06:00 GMT |
Overview
The ResizeNearestNeighborGrad kernel computes the gradient of nearest-neighbor image resizing for the CPU backend. It determines which input pixels contributed to each output pixel in the forward pass and accumulates the upstream gradient values back to those input positions.
Code Reference
Source Location
tfjs-backend-cpu/src/kernels/ResizeNearestNeighborGrad.ts (GitHub)
Signature
export function resizeNearestNeighborGrad(args: {
inputs: ResizeNearestNeighborGradInputs,
backend: MathBackendCPU,
attrs: ResizeNearestNeighborGradAttrs
}): TensorInfo
Imports
import {KernelConfig, KernelFunc, ResizeNearestNeighborGrad, ResizeNearestNeighborGradAttrs, ResizeNearestNeighborGradInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';
import {MathBackendCPU} from '../backend_cpu';
import {assertNotComplex} from '../cpu_util';
Kernel Config
export const resizeNearestNeighborGradConfig: KernelConfig = {
kernelName: ResizeNearestNeighborGrad,
backendName: 'cpu',
kernelFunc: resizeNearestNeighborGrad as unknown as KernelFunc
};
I/O Contract
Inputs
| Name | Type | Description |
|---|---|---|
dy |
TensorInfo |
Upstream gradient of shape [batch, yHeight, yWidth, depth]
|
images |
TensorInfo |
Original input images of shape [batch, xHeight, xWidth, depth]
|
Attributes
| Name | Type | Description |
|---|---|---|
alignCorners |
boolean |
If true, aligns the corner pixels of input and output |
Output
Returns a TensorInfo with the same shape and dtype as images, containing accumulated gradients.
Algorithm
- Computes effective input and output sizes with
alignCornersadjustments. - Calculates forward and inverse height/width scaling ratios.
- Computes search window dimensions:
winHeight = ceil(invHeightScale) * 2 + 2andwinWidth = ceil(invWidthScale) * 2 + 2. - For each input pixel
[b, r, c, d]:- Determines a search window in
dycentered around the expected contributing output pixels. - For each
dypixel in the search window:- Computes the nearest-neighbor source row/column using
Math.round(ifalignCorners) orMath.floor. - If the source row and column match the current input position, accumulates the
dyvalue.
- Computes the nearest-neighbor source row/column using
- Stores the accumulated gradient in the output.
- Determines a search window in
Usage Example
This kernel is invoked automatically during backpropagation through tf.image.resizeNearestNeighbor:
import * as tf from '@tensorflow/tfjs-core';
import '@tensorflow/tfjs-backend-cpu';
const image = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]);
const grads = tf.grads(
(img) => tf.image.resizeNearestNeighbor(img, [4, 4]).sum());
const [dx] = grads([image]);
dx.print();