Manual Gradient Computation: Cumulative Products and Softmax Loss
Arrays & HashingAuto-graded · 14 test casesLast 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:
- Cumulative multiplication operation: Given an input sequence and upstream gradients, compute the forward pass (cumulative products) and backward pass (gradients with respect to inputs).
- 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, shapeN × C(N examples, C classes)labels: Integer class indices for each example, shapeN
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 asa, representing upstream gradientslogits: List of lists (N × C matrix) containing raw scoreslabels: 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.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires implementing gradient computations that an autograd system would perform automatically.
Part 1: Cumulative Product Gradients
Forward Pass: Build the cumulative products iteratively by maintaining a running product.
Backward Pass: Apply the chain rule in reverse. Each output y[i] depends on a[i] and y[i-1]:
y[i] = a[i] × y[i-1]
When gradient g[i] flows into y[i], it splits two ways:
- To
a[i]: The local gradient is∂y[i]/∂a[i] = y[i-1], so contribution isg[i] × y[i-1] - To
y[i-1]: The local gradient is∂y[i]/∂y[i-1] = a[i], so contribution isg[i] × a[i]
We accumulate gradients flowing into each position as we traverse backward. This avoids division and correctly handles zeros.
Part 2: Softmax Cross-Entropy
Forward Pass:
- For numerical stability, subtract the maximum logit from each row before computing exponentials (this doesn't change the softmax output)
- Compute softmax:
p[j] = exp(logit[j] - max) / sum(exp(logit[k] - max)) - Cross-entropy for one example:
-log(p[true_label]) - Average across the batch
Gradient Computation: The gradient of cross-entropy loss with respect to logits has a clean closed form:
∂L/∂logit[j] = p[j] - δ[j == true_label]
where δ is 1 if j is the true label, 0 otherwise. Scale by 1/batch_size for mean loss.
Why This Works: The derivative of softmax cross-entropy simplifies beautifully due to cancellation in the chain rule. The softmax probability minus the target indicator gives the gradient direction.
Complexity
Time: O(n) for cumulative products (two linear passes) + O(N × C) for softmax (one pass per example, linear in classes)
Space: O(n) for gradient storage + O(N × C) for output gradients
Solution
import math
from typing import Dict, List
def compute_manual_gradients(a, g, logits, labels):
n = len(a)
if len(g) != n:
raise ValueError("a and g must have the same length")
# Forward pass: compute cumulative products
cumulative = []
running_product = 1.0
for val in a:
running_product *= val
cumulative.append(running_product)
# Backward pass: propagate gradients through the computation graph
gradient_flow = list(g)
input_gradients = [0.0] * n
for i in range(n - 1, -1, -1):
prev_product = 1.0 if i == 0 else cumulative[i - 1]
input_gradients[i] = gradient_flow[i] * prev_product
if i > 0:
gradient_flow[i - 1] += gradient_flow[i] * a[i]
# Validate cross-entropy inputs
batch_size = len(logits)
if batch_size == 0 or len(labels) != batch_size:
raise ValueError("logits must be nonempty and match labels")
num_classes = len(logits[0])
if num_classes == 0 or any(len(row) != num_classes for row in logits):
raise ValueError("logits must be a nonempty rectangular matrix")
if any(label < 0 or label >= num_classes for label in labels):
raise ValueError("label out of range")
# Compute softmax cross-entropy loss and gradients
total_loss = 0.0
logit_gradients = []
for scores, true_label in zip(logits, labels):
max_score = max(scores)
exponentials = [math.exp(s - max_score) for s in scores]
sum_exp = sum(exponentials)
softmax_probs = [e / sum_exp for e in exponentials]
total_loss += math.log(sum_exp) + max_score - scores[true_label]
row_gradient = [
(prob - (1.0 if j == true_label else 0.0)) / batch_size
for j, prob in enumerate(softmax_probs)
]
logit_gradients.append(row_gradient)
return {
"prefix_products": cumulative,
"prefix_gradient": input_gradients,
"cross_entropy_loss": total_loss / batch_size,
"logits_gradient": logit_gradients,
}