KatInterview

Manual Gradient Computation: Cumulative Products and Softmax Loss

Arrays & HashingAuto-graded · 14 test cases
HardAuto-gradedArrays & Hashinggradientsbackpropagationnumerical-stability

Last updated

Implement forward and backward passes for cumulative multiplication and stable softmax cross-entropy loss without autograd libraries.

You will implement gradient calculations manually, simulating what an automatic differentiation framework does internally, but without using any autograd or ML framework gradient functions.

Task Overview

Your function receives four inputs and must compute gradients for two independent operations:

  1. Cumulative multiplication operation: Given an input sequence and upstream gradients, compute the forward pass (cumulative products) and backward pass (gradients with respect to inputs).
  2. Softmax cross-entropy loss: Given logits and labels, compute the loss value and its gradient with respect to the logits using numerically stable methods.

Part 1: Cumulative Multiplication

Given a sequence a = [a[0], a[1], ..., a[n-1]], the cumulative product operation produces y where:

  • y[0] = a[0]
  • y[1] = a[0] × a[1]
  • y[2] = a[0] × a[1] × a[2]
  • And so on: y[i] = a[0] × a[1] × ... × a[i]

Forward Pass: Compute the cumulative products y.

Backward Pass: Given upstream gradients g[i] = ∂L/∂y[i] for some scalar loss L, compute ∂L/∂a[k] for each position k using the chain rule. Your implementation must:

  • Run in O(n) time complexity
  • Not use division (inputs may contain zeros)
  • Handle edge cases including sequences with one or multiple zeros

Part 2: Softmax Cross-Entropy Loss

Given:

  • logits: A batch of raw scores, shape N × C (N examples, C classes)
  • labels: Integer class indices for each example, shape N

Compute:

  • The mean softmax cross-entropy loss (averaged over the batch)
  • The gradient of the loss with respect to each logit

Your implementation must:

  • Use numerically stable computation (subtract max before exp to prevent overflow)
  • Return gradients scaled appropriately by batch size
  • Work entirely in NumPy without calling library loss functions

Input Format

  • a: List of floats (may contain zeros or negative values)
  • g: List of floats, same length as a, representing upstream gradients
  • logits: List of lists (N × C matrix) containing raw scores
  • labels: List of N integers, each in range [0, C-1]

Output Format

Return a dictionary with these exact keys:

  • "prefix_products": List of cumulative products (forward pass result)
  • "prefix_gradient": List of gradients ∂L/∂a[k]
  • "cross_entropy_loss": Float, the mean loss value
  • "logits_gradient": List of lists (N × C), gradient ∂L/∂logits

Constraints

  • 1 ≤ len(a) ≤ 10,000
  • len(g) == len(a)
  • 1 ≤ N ≤ 1,000
  • 2 ≤ C ≤ 1,000
  • All logit rows have exactly C elements
  • 0 ≤ labels[i] < C for all i
  • Logit values may be very large (e.g., ±1000)

Examples

Example 1

Input: compute_manual_gradients([2, 3, 4], [1, 1, 1], [[1, 2, 3], [1, 0, -1]], [2, 0])

Output: {'prefix_products': [2, 6, 24], 'prefix_gradient': [16, 10, 6], 'cross_entropy_loss': 0.40760596444438046, 'logits_gradient': [[0.04501528658519023, 0.12236423552739882, -0.1673795221125891], [-0.1673795221125891, 0.12236423552739882, 0.04501528658519023]]}

Example 2

Input: compute_manual_gradients([0, 2, 3], [1, 1, 1], [[1000, -1000], [-1000, 1000]], [0, 1])

Output: {'prefix_products': [0, 0, 0], 'prefix_gradient': [9, 0, 0], 'cross_entropy_loss': 0, 'logits_gradient': [[0, 0], [0, 0]]}

Hints

Hint 1

For cumulative products, the gradient at position k depends on products of elements before and after k. Compute both prefix and suffix products to avoid division.

Hint 2

In the backward pass, think recursively: if you know the gradient flowing into y[i], how much flows into a[i] versus y[i-1]?

Hint 3

For softmax stability, subtract the maximum logit from each row before computing exponentials to prevent overflow while preserving the result.