PIXELBANKv9.1.0
Menu

Implement Straight-Through Estimator

Problem Statement

Implement a Straight-Through Estimator (STE) that binarizes in the forward pass but passes gradients through unchanged in the backward pass.

Background

The STE is crucial for training networks with discrete operations (e.g., binary neural networks, quantization). Forward: binarize to -1 or +1. Backward: pass gradient straight through as if the binarization didn't happen.

Your Task

The starter code defines a StraightThroughEstimator class and test harness. Implement an STE that binarizes the input using the sign function in the forward pass but allows gradients to flow through unchanged in the backward pass.

Output Format

The function returns a dictionary with "output" (binarized values: -1, 0, or 1) and "grad" (should pass through unchanged).

Example:

Input:
None
Output:
{'output': [-1.0, -1.0, 1.0, 1.0, 1.0], 'grad': [1.0, 2.0, 3.0, 4.0, 5.0]}
Reasoning:
  • The input [-2.5, -0.5, 0.3, 1.5, 3.0] is first binarized using the sign() function, resulting in [-1.0, -1.0, 1.0, 1.0, 1.0].
  • This binarized output is then multiplied element-wise by [1.0, 2.0, 3.0, 4.0, 5.0], giving [-1.0, -2.0, 3.0, 4.0, 5.0], and the sum of these products is computed as −1.0−2.0+3.0+4.0+5.0=9.0-1.0 - 2.0 + 3.0 + 4.0 + 5.0 = 9.0.
  • The backward() function is then called on this sum, which applies the chain rule to compute the gradients of the loss with respect to the input, but due to the Straight-Through Estimator, the gradients are passed through unchanged, resulting in [1.0, 2.0, 3.0, 4.0, 5.0].
  • The final output is a dictionary containing the binarized output [-1.0, -1.0, 1.0, 1.0, 1.0] and the gradient of the input [1.0, 2.0, 3.0, 4.0, 5.0].

Constraints:

  • Forward must binarize using sign()
  • Backward must pass gradient through unchanged
  • This is the key trick for binary neural networks
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Implement Straight-Through Estimator - Hard | PixelBank