Optional
Broadcasting, gradients, and tensor shape
NumPy notebook — silent (n,1)×(n,) broadcasting, grad accumulation without clearing, and shape alignment. Self-check in the notebook.
- Version
- v1
- Seed
- 0
- Minutes
- ~25
- Evidence
- Self-check in the notebook
Data: synthetic NumPy arrays; no external dataset
Until platform auto-check exists, compare cell output with the expected numbers in the notebook. This is not a debt and does not affect mastery.
Download the notebook and run it locally. Its environment requirements are listed inside.
Notebook contents
Readable on your phone. The code below has not been executed in the browser; download the notebook to run it.
DL · Broadcasting, градиенты, форма тензора / Broadcasting, grads, shapes
Activity version: 1 · Seed: 0 (и 7 в ячейке формы) · Данные: синтетические массивы NumPy, без внешних датасетов.
RU. Ноутбук воспроизводит три тихих бага из темы PyTorch и автоматическое дифференцирование: (1) broadcasting (n,1) с (n,), (2) накопление .grad без zero_grad, (3) выравнивание формы перед лоссом. Только NumPy — без GPU и без обязательного PyTorch.
EN. Three silent bugs from PyTorch and autograd: broadcasting (n,1) vs (n,), gradient accumulation without zero_grad, and fixing tensor shape before the loss. NumPy-only.
Ожидаемые числа / Expected numbers
| Check | Value | Tolerance |
|---|---|---|
Broadcast MSE (3,1)-(3,) |
1.333… (= 12/9) |
abs ≤ 1e-9 |
Fixed MSE after squeeze |
0.0 |
exact |
w after 5 steps without clear |
≈ 3.53133 |
abs ≤ 1e-5 |
w after 5 steps with clear |
≈ 1.22853 |
abs ≤ 1e-5 |
Самопроверка в ноутбуке
Пока нет автопроверки на платформе: сравните вывод ячеек с таблицей выше. Это не влияет на освоение темы и сертификат.
import numpy as np
SEED = 0
np.random.seed(SEED)
print("seed", SEED)
1. Broadcasting: (n, 1) минус (n,) → (n, n)
Для совпадающих значений (1,2,3) целевой MSE = 0, но broadcast усредняет девять квадратов → 12/9 = 1.333….
pred = np.array([[1.0], [2.0], [3.0]]) # (3, 1)
target = np.array([1.0, 2.0, 3.0]) # (3,)
diff_bad = pred - target
mse_bad = float((diff_bad ** 2).mean())
mse_ok = float(((pred.squeeze(1) - target) ** 2).mean())
print("diff_bad.shape", diff_bad.shape) # expect (3, 3)
print("mse_bad", mse_bad) # expect 1.3333333333333333
print("mse_ok", mse_ok) # expect 0.0
assert diff_bad.shape == (3, 3)
assert abs(mse_bad - 12 / 9) < 1e-9
assert mse_ok == 0.0
print("OK: broadcasting check")
2. Накопление градиента без очистки / Accumulation without zero_grad
, , старт . С очисткой — обычный SGD. Без очистки шаг использует .
eta = 0.1
# Without clearing: accumulate every past gradient
w = 0.0
grads = []
trace_bad = [w]
for _ in range(5):
g = w - 3.0 # dL/dw
grads.append(g)
w = w - eta * sum(grads)
trace_bad.append(w)
# With clearing each step
w = 0.0
trace_ok = [w]
for _ in range(5):
g = w - 3.0
w = w - eta * g
trace_ok.append(w)
print("without clear:", [round(x, 8) for x in trace_bad])
print("with clear: ", [round(x, 8) for x in trace_ok])
# Expected finals: without ≈ 3.53133, with ≈ 1.22853
assert abs(trace_bad[-1] - 3.53133) < 1e-5
assert abs(trace_ok[-1] - 1.22853) < 1e-5
print("OK: grad accumulation check")
3. Исправление формы / Fixing shape before the loss
Семя 7: вектор-столбец минус вектор снова даёт матрицу. Выровняйте оси до вычитания.
rng = np.random.default_rng(7)
n = 4
x = rng.normal(size=(n, 1))
y = rng.normal(size=(n,))
print("bad broadcast shape", (x - y).shape) # (4, 4)
print("fixed shape", (x.reshape(n) - y).shape) # (4,)
assert (x - y).shape == (n, n)
assert (x.reshape(n) - y).shape == (n,)
print("OK: shape fix check")
Самопроверка в ноутбуке / Notebook self-check
-
mse_bad ≈ 1.333…,mse_ok == 0 - финальные
wсовпали с таблицей (допуски выше) - формы
(4,4)vs(4,)понятны
Опционально: повторите broadcasting и zero_grad в PyTorch (torch не требуется для этой самопроверки).