Implement common neural network layers in PyTorch
Implement Neural Network Layers from Scratch in PyTorch
Your task is to implement several common neural network building blocks entirely from scratch in PyTorch. You are restricted to using only basic tensor operations such as matmul, sum, mean, var, exp, max, reshape, transpose, and broadcasting. Crucially, you must not use any implementations from torch.nn.* or torch.nn.functional.* for these operations.
Layers to Implement:
-
ReLU (Rectified Linear Unit)
- Input: A tensor
xof any shape. - Output:
y = max(x, 0).
- Input: A tensor
-
Softmax (Numerically Stable)
- Input: A tensor
xand an integerdimspecifying the dimension along which to apply Softmax. - Output: The Softmax applied along the specified
dim. - Constraint: The implementation must be numerically stable for both very large and very small input values.
- Input: A tensor
-
Layer Normalization (LayerNorm)
- Input: A tensor
xwith shape[*, normalized_dim](or more generally, normalize over the lastkdimensions), along with learnable parametersgammaandbeta, and a small constantepsfor numerical stability. - Output: The normalized tensor.
- Input: A tensor
-
Batch Normalization (BatchNorm) - Training and Inference Modes
- Input: A tensor
x(e.g., typically[N, C, H, W]for convolutional layers), learnable parametersgammaandbeta, a small constanteps, amomentumvalue for updating running statistics, and statefulrunning_meanandrunning_vartensors. - Implementation Requirements:
- Training Forward Pass: Compute the mean and variance of the current batch, use these to normalize the input, and update the
running_meanandrunning_varusing the providedmomentum. - Inference Forward Pass: Use the stored
running_meanandrunning_var(instead of batch statistics) to normalize the input.
- Training Forward Pass: Compute the mean and variance of the current batch, use these to normalize the input, and update the
- Input: A tensor
-
Root Mean Square Normalization (RMSNorm)
- Input: A tensor
x, learnable parametergamma, and a small constanteps. - Output: The normalized tensor.
- Constraint: Normalize by the Root Mean Square (RMS) value, meaning no mean subtraction is performed.
- Input: A tensor
Verification
For each implemented component, you must describe how you would verify its correctness. This could include strategies such as comparing against a reference implementation (e.g., torch.nn equivalents), performing gradient checks (e.g., finite-difference checks), and testing edge cases like fp16 precision, tiny variance values, and various tensor shapes and ranks.
AI interview prep
Core dilemma
The central engineering conflict is balancing the precise mathematical implementation of core neural network operations with robust numerical stability and correct state management (for BatchNorm) using only low-level tensor primitives, while also demonstrating a deep understanding of verification strategies for these fundamental building blocks.
3 tradeoffs and 3 stress tests locked
Interview prep
Unlock the interviewer X-Ray rubric, tradeoff matrix, stress tests, clarifying questions, and key concepts.
Implement common neural network layers in PyTorch
Implement Neural Network Layers from Scratch in PyTorch
Your task is to implement several common neural network building blocks entirely from scratch in PyTorch. You are restricted to using only basic tensor operations such as matmul, sum, mean, var, exp, max, reshape, transpose, and broadcasting. Crucially, you must not use any implementations from torch.nn.* or torch.nn.functional.* for these operations.
Layers to Implement:
-
ReLU (Rectified Linear Unit)
- Input: A tensor
xof any shape. - Output:
y = max(x, 0).
- Input: A tensor
-
Softmax (Numerically Stable)
- Input: A tensor
xand an integerdimspecifying the dimension along which to apply Softmax. - Output: The Softmax applied along the specified
dim. - Constraint: The implementation must be numerically stable for both very large and very small input values.
- Input: A tensor
-
Layer Normalization (LayerNorm)
- Input: A tensor
xwith shape[*, normalized_dim](or more generally, normalize over the lastkdimensions), along with learnable parametersgammaandbeta, and a small constantepsfor numerical stability. - Output: The normalized tensor.
- Input: A tensor
-
Batch Normalization (BatchNorm) - Training and Inference Modes
- Input: A tensor
x(e.g., typically[N, C, H, W]for convolutional layers), learnable parametersgammaandbeta, a small constanteps, amomentumvalue for updating running statistics, and statefulrunning_meanandrunning_vartensors. - Implementation Requirements:
- Training Forward Pass: Compute the mean and variance of the current batch, use these to normalize the input, and update the
running_meanandrunning_varusing the providedmomentum. - Inference Forward Pass: Use the stored
running_meanandrunning_var(instead of batch statistics) to normalize the input.
- Training Forward Pass: Compute the mean and variance of the current batch, use these to normalize the input, and update the
- Input: A tensor
-
Root Mean Square Normalization (RMSNorm)
- Input: A tensor
x, learnable parametergamma, and a small constanteps. - Output: The normalized tensor.
- Constraint: Normalize by the Root Mean Square (RMS) value, meaning no mean subtraction is performed.
- Input: A tensor
Verification
For each implemented component, you must describe how you would verify its correctness. This could include strategies such as comparing against a reference implementation (e.g., torch.nn equivalents), performing gradient checks (e.g., finite-difference checks), and testing edge cases like fp16 precision, tiny variance values, and various tensor shapes and ranks.