Browse and solve 1,200+ machine learning coding challenges on Deep-ML. Filter by difficulty (beginner, intermediate, advanced) and category (linear algebra, machine learning, deep learning, NLP, computer vision). Write Python solutions in the browser and get instant feedback against test cases.
Deep-ML | Tinygrad: Gradient Clipping by NormTinygrad: Gradient Clipping by Norm
Tinygrad: Gradient Clipping by Norm
Mediumtinygrad
Example:
Input:
Two parameters with grads of norm 3 and 4; max_norm = 1.0
Output:
Returns 5.0; both gradients scaled down to total norm 1.0.
Reasoning:
Total norm is sqrt(3^2 + 4^2) = 5. Since 5 > 1, every grad is scaled by 1/5. The returned value is the pre-scaling total, 5.0.
Implement clip_grad_norm(parameters, max_norm) that mirrors PyTorch's torch.nn.utils.clip_grad_norm_ for tinygrad parameters. Given an iterable of parameter Tensors whose .grad attribute has been populated:
Compute the total L2 norm across all gradients flattened into a single vector:
∥g∥2=∑i,pgp,i2.
If ∥g∥2>max_norm, scale every gradient (in place via attribute reassignment) by max_norm/∥g∥2.
If ∥g∥2≤max_norm, leave the gradients unchanged.
Return the original total norm as a Python float.
Parameters whose .grad is None should be skipped, not raise.
Hints
Compute each parameter's squared L2 norm via (g ** 2).sum().item(). Summing those gives the squared total norm; take its sqrt for the total.
Tinygrad has no in-place mul_; just reassign the attribute: p.grad = p.grad * scale.
.item() forces realization; call it once on the final scalar to return a Python float.