Implement common neural network layers in PyTorch
Startups.ComMachine Learning Engineer · OnsiteLast updated
This question evaluates proficiency in implementing core neural-network primitives (ReLU, numerically-stable Softmax, LayerNorm, BatchNorm with running statistics, and RMSNorm), numerical stability and normalization concepts, and understanding of autograd-compatible tensor operations.
Implement the following neural-network building blocks from scratch in PyTorch (using only basic tensor ops such as matmul, sum, mean, var, exp, max, reshape, transpose, broadcasting). Do not call torch.nn.* or torch.nn.functional.* implementations of the same ops.
- ReLU
- Input: tensor
xof any shape. - Output:
y = max(x, 0).
- Softmax (numerically stable)
- Input: tensor
xand an integerdim. - Output: softmax along
dim. - Must be stable for large/small values.
- LayerNorm
- Input:
xwith shape[*, normalized_dim](or more generally normalize over the lastkdims), learnablegamma,beta, andeps. - Output: normalized tensor.
- BatchNorm (training and inference)
- Input:
x(e.g.,[N, C, H, W]), learnablegamma,beta,eps,momentum, plusrunning_meanandrunning_var. - Implement:
- Training forward: compute batch stats and update running stats.
- Inference forward: use running stats.
- RMSNorm
- Input:
x, learnablegamma,eps. - Normalize by RMS (no mean subtraction).
For each component, describe how you would verify correctness (e.g., compare to a reference implementation, run gradient checks / finite-difference checks, test edge cases such as fp16, tiny variance, and different tensor shapes).
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.