← Back to Home

Six tinygrad Fixes, Animated: Conv2d, Cross-Entropy, Dropout and BatchNorm

1. Conv2d said no to stride=(1, 1)

#19325 · merged Nov 14 · tinygrad/nn/__init__.py

padding='same' keeps the output the size of the input input + zero padding output · same size stride=1 ≡ stride=(1, 1)
BEFORE · stride != 1
stride=1BUILDS stride=(1, 1)VALUEERROR stride=2VALUEERROR stride=(1, 2)VALUEERROR
AFTER · check every value
stride=1BUILDS stride=(1, 1)BUILDS stride=2VALUEERROR stride=(1, 2)VALUEERROR

2. The loss was half what it should be

#19353 · merged Nov 15 · tinygrad/mixin/op.py

ignore_index=-1 means “skip this sample”
x13
x2-1
skip
x37
x4-1
skip
mean loss = sum ÷ 2 labeled samples
BEFORE · no mask when ignore_index=-1 Labels
label-1label-1
Counted in the mean
1111
7.0896 / 4 = 1.7724
AFTER · always mask Labels
label-1label-1
Counted in the mean
1010
7.0896 / 2 = 3.5448

3. nll_loss crashed without a batch

#19337 · merged Nov 16 · tinygrad/mixin/op.py

nll_loss picks the target class’s score from each row
batched · shape (3, 4)
x[0,0]x[0,1]x[0,2]x[0,3]target 2
x[1,0]x[1,1]x[1,2]x[1,3]target 0
x[2,0]x[2,1]x[2,2]x[2,3]target 3
dim 0 = samples ↓ · dim 1 = classes →
one sample · shape (4,)
x[0]x[1]x[2]x[3]target 1
dim 0 = classes → · there is no dim 1
BEFORE · always gather on dim 1 x, shape (2,) · target 1
x[0]x[1]
x.gather(1, …) CRASH
AFTER · classes on dim 0 when 1-D x, shape (2,) · target 1
x[0]x[1]
x.gather(0, …) → loss = −x[1]

4. dropout(1.0) cut the gradient off

#19520 · merged Nov 23 · tinygrad/mixin/rand.py

dropout zeroes a fraction p of activations during training
p = 0.5
p = 1
forward→loss→backward→grad for every weight→optimizer step
BEFORE · const_like(0) x const 0 loss × grad = None
AFTER · self * 0 x x × 0 loss grad = 0

5. Expanded tensors wouldn’t load

#19557 · merged Nov 24 · tinygrad/nn/state.py

PyTorch saves a tensor as storage + size + stride storage tensor stride 1 1.02.0 1.02.0 stride 0 1.0 1.01.0
torch.save→file: storage, size, stride→tinygrad rebuilds the tensor
BEFORE · unfold only storage [1.0] · size (2,) · stride (0,)
[1.0]→ unfold →[1.0]→ reshape(2) →shape mismatch
AFTER · unfold, then expand storage [1.0] · size (2,) · stride (0,)
[1.0]→ unfold →[1.0]→ expand →[1.0][1.0]
→ reshape(2) →[1.0, 1.0]

6. BatchNorm crashed in mixed precision

#19630 · merged Nov 27 · tinygrad/nn/__init__.py

BatchNorm keeps running stats to use at inference batches → batch mean running mean
running stats f16 half precisioninput f32 full precision
BEFORE · assign the promoted result
running_mean f16+batch_mean f32
→update f32→ assign →buffer f16 ✗
AFTER · cast, then assign
running_mean f16+batch_mean f32
→update f32→ .cast →update f16
→ assign →buffer f16 ✓