Lecture 02 · NN Fundamentals

المحاضرة 02 · أساسيات الشبكات العصبية

Batch norm: transform and folding

Batch norm: التحويل والدمج (folding)

Slides 27–33الشرائح 27–33 P1 MUST

Normalize each feature over the batch, then let two learned numbers per feature put the range back wherever training wants it. At inference the statistics freeze, BN becomes a plain affine map, and it disappears into the layer before it.

سوِّ كل ميزة على مستوى الدفعة، ثم دع رقمين متعلَّمين لكل ميزة يعيدان المدى إلى حيث يريده التدريب. وعند inference تتجمد الإحصائيات، فيصبح BN مجرد تحويل affine بسيط، ويختفي داخل الطبقة التي قبله.

Why normalize at all

لماذا التطبيع (normalization) أصلاً

Slide 28 takes one layer y = Wx and names two things that make optimization hard:

الشريحة 28 تأخذ طبقة واحدة y = Wx وتذكر أمرين يجعلان optimization صعباً:

The idea (slide 29, Ioffe and Szegedy 2015): force the inputs of every layer to be "nicely scaled", zero mean and unit variance per dimension, using a differentiable function so gradients still flow through it.

الفكرة (الشريحة 29، Ioffe and Szegedy 2015): أجبر دخل كل طبقة على أن يكون "بمقياس مناسب"، أي بمتوسط صفر وتباين واحد لكل بُعد، باستخدام دالة قابلة للاشتقاق حتى تمر gradients من خلالها.

The transform, step by step

التحويل، خطوة بخطوة

Input x has shape N x D: N samples in the batch, D features. Statistics are computed down each column, per feature, across the batch.

الدخل x شكله N x D: N عيّنة في الدفعة وD ميزة. تُحسب الإحصائيات نزولاً في كل عمود، أي لكل ميزة عبر الدفعة.

x : N x D N D one μj, σj2 per column: shape D NORMALIZE (computed) x̂ = (x − μ) / √(σ² + ε) zero mean, unit variance SCALE + SHIFT (learned) y = γ x̂ + β γ, β : shape D training: μ, σ² from the current mini-batch inference: μ, σ² are frozen running averages
Slides 30 and 31. The red arrows run down the batch dimension: BN pools statistics across samples, one set per feature.
الشريحتان 30 و31. الأسهم الحمراء تسير على امتداد بُعد الدفعة: BN يجمع الإحصاءات عبر العينات، مجموعة واحدة لكل خاصية.
μj = (1/N) Σi xi,j     σj2 = (1/N) Σi (xi,j − μj)2
x̂i,j = (xi,j − μj) / √(σj2 + ε)     yi,j = γj x̂i,j + βj

μ and σ2 each have shape D (per-channel mean and variance). x̂ and y have shape N x D. ε is a tiny constant (PyTorch default 1e-5) that prevents division by zero. The slide uses 1/N, the biased variance.

μ وσ2 شكل كل منهما D (متوسط وتباين لكل قناة). وx̂ وy شكلهما N x D. وε ثابت صغير جداً (القيمة الافتراضية في PyTorch هي 1e-5) يمنع القسمة على صفر. والشريحة تستخدم 1/N، أي التباين المتحيّز.

For a conv layer with output (N, C, H, W), D becomes the C channels and each channel's statistics are taken over N x H x W values. The parameters are still one γ and one β per channel.

في طبقة conv خرجها (N, C, H, W)، يصبح D هو القنوات C، وتُحسب إحصائيات كل قناة على N x H x W قيمة. ويبقى عدد parameters واحد γ وواحد β لكل قناة.

Why γ and β exist

لماذا يوجد γ وβ

Slide 30 asks: what if zero mean, unit variance is too hard a constraint? A tanh after BN would then live only in its near-linear middle. The fix (slide 31) is a learned scale γ and shift β per feature. They let the network squash or widen the range if it wants to, and in particular control how much saturation the following activation sees.

الشريحة 30 تسأل: ماذا لو كان المتوسط صفر والتباين واحد قيداً أشد من اللازم؟ فدالة tanh بعد BN ستعمل حينها فقط في منتصفها شبه الخطي. والحل (الشريحة 31) هو scale γ وshift β متعلَّمان لكل ميزة. يسمحان للشبكة بأن تضغط المدى أو توسّعه إن أرادت، وتحديداً أن تتحكم في مقدار saturation الذي تراه دالة التنشيط التالية.

γ = √(σ2 + ε),   β = μ   ⟹   y = x    (identity recovered)

So BN can never make the model less expressive: if normalization hurts, training can learn its way back to the identity, "as if there was no batch normalization".

إذن لا يمكن لـ BN أن يجعل النموذج أقل قدرة: فإذا كان التسوية ضارة، يستطيع التدريب أن يتعلم طريق العودة إلى identity، "وكأنه لا يوجد batch normalization".

Learned by gradient descent

تُتعلَّم بالانحدار التدريجي (gradient descent)

γ and β, shape D each. Trainable parameters, stored in the model.

γ وβ، شكل كل منهما D. parameters قابلة للتدريب، وتُخزَّن في النموذج.

Computed from data

تُحسب من البيانات

μ and σ2, shape D each. From the mini-batch in training; running averages (buffers, no gradient) at inference.

μ وσ2، شكل كل منهما D. من mini-batch أثناء التدريب، ومن running averages (مخازن بدون gradient) عند inference.

Workedمثال محلول
one feature, batch of N = 4, training mode, take ε ≈ 0
  x      = [2, 6, 2, 6]
  μ      = (2 + 6 + 2 + 6)/4                = 4
  σ²     = ((−2)² + 2² + (−2)² + 2²)/4      = 16/4 = 4
  √σ²    = 2
  x̂      = (x − 4)/2                        = [−1, 1, −1, 1]

learned γ = 3, β = 0.5
  y      = 3 x̂ + 0.5                        = [−2.5, 3.5, −2.5, 3.5]

check: mean(y) = 0.5 = β,  std(y) = 3 = γ

After BN the output's mean is β and its standard deviation is γ, whatever the input statistics were. That is what "γ and β choose the range" means.

بعد BN يصبح متوسط الخرج β وانحرافه المعياري γ، مهما كانت إحصائيات الدخل. وهذا هو معنى أن "γ وβ يختاران المدى".

Inference: BN becomes a linear operator

الاستدلال: BN يصبح عاملاً خطياً

Slide 32: at test time μj and σj2 are the (running) average of values seen during training, not statistics of the test batch. Testing must be deterministic and must work on a single input. With μ, σ2, γ, β all fixed, BN is just y = a·z + c per feature: "during testing batchnorm becomes a linear operator! Can be fused with the previous fully-connected or conv layer."

الشريحة 32: عند الاختبار تكون μj وσj2 هي المتوسط (التراكمي) للقيم التي ظهرت أثناء التدريب، لا إحصائيات دفعة الاختبار. فالاختبار يجب أن يكون حتمياً وأن يعمل على دخل واحد. ومع تثبيت μ وσ2 وγ وβ كلها، يصبح BN مجرد y = a·z + c لكل ميزة: "أثناء الاختبار يصبح batchnorm عاملاً خطياً! ويمكن دمجه مع طبقة fully-connected أو conv السابقة."

Deriving the fold

اشتقاق الدمج (fold)

The previous layer computes z = Wx + b. BN then computes y = γ (z − μ)/√(σ2 + ε) + β. Name the per-feature factor s = γ/√(σ2 + ε) and substitute:

الطبقة السابقة تحسب z = Wx + b. ثم يحسب BN: y = γ (z − μ)/√(σ2 + ε) + β. سمِّ العامل الخاص بكل ميزة s = γ/√(σ2 + ε) ثم عوّض:

y = s (Wx + b − μ) + β = (s W) x + s (b − μ) + β
W' = diag(γ / √(σ2 + ε)) W     b' = γ (b − μ) / √(σ2 + ε) + β

diag(s) W scales row j of W (the weights producing output feature j) by sj. For a conv, it scales every weight of output channel j's filter by sj. The deployed model keeps only W' and b'; γ, β, the running mean and the running variance vanish. That is why slide 33 says zero overhead at test time.

diag(s) W يضرب الصف j من W (الأوزان التي تُنتج ميزة الخرج j) في sj. وفي conv يضرب كل أوزان filter قناة الخرج j في sj. والنموذج المنشور يحتفظ فقط بـ W' وb'، بينما تختفي γ وβ وrunning mean وrunning variance. ولهذا تقول الشريحة 33 صفر كلفة إضافية عند الاختبار.

TRAINED GRAPH DEPLOYED GRAPH x conv / FC W, b BN (eval) μ, σ², γ, β FOLD x conv / FC W', b' s = γ / √(σ² + ε) W' = s · W (row-wise) b' = s (b − μ) + β one layer, one weight read, no extra MACs, no extra memory traffic
Folding is only legal once μ and σ² are frozen. During training they change with every mini-batch, so BN must stay a separate layer.
الدمج لا يجوز إلا بعد تجميد μ وσ². أثناء التدريب تتغيران مع كل دفعة صغيرة (mini-batch)، لذا يجب أن يبقى BN طبقة منفصلة.
Workedمثال محلول
scalar layer   z = w x + b,     w = 2,  b = 1
BN (eval)      running μ = 5,  σ² + ε = 4  (√ = 2),  γ = 3,  β = 0.5

s  = γ / √(σ² + ε) = 3 / 2       = 1.5
w' = s · w         = 1.5 x 2     = 3
b' = s (b − μ) + β = 1.5 x (1 − 5) + 0.5 = −6 + 0.5 = −5.5

check x = 4
  unfused: z = 2·4 + 1 = 9,  y = 3 (9 − 5)/2 + 0.5 = 6 + 0.5 = 6.5
  fused:   y = 3·4 − 5.5                           = 6.5   ✓

Why this matters on an embedded device

لماذا يهم هذا على جهاز مدمج

A BN layer left unfused costs one extra pass over the whole activation tensor: read it, multiply, add, write it back. On a microcontroller that is pure memory traffic for no new information. Folding removes it, and removes 4 stored vectors per BN layer (γ, β, running μ, running σ2).

طبقة BN غير المدمجة تكلّف مروراً إضافياً على كامل tensor التنشيط: اقرأه، واضرب، واجمع، ثم اكتبه مرة أخرى. وعلى microcontroller هذا نقل ذاكرة خالص بلا أي معلومة جديدة. والدمج يزيله، ويزيل 4 متجهات مخزّنة لكل طبقة BN (γ وβ وrunning μ وrunning σ2).

Folding also matters later in the course: quantization is applied to the folded weights W', because that is what the integer kernel actually multiplies. And BN's γ per channel is the importance signal that scaling-factor pruning reads in Lecture 04.

والدمج مهم أيضاً لاحقاً في المقرر: فالـ quantization يُطبَّق على الأوزان المدمجة W'، لأنها هي التي تضربها نواة الأعداد الصحيحة فعلاً. كما أن γ لكل قناة في BN هي إشارة الأهمية التي يقرؤها scaling-factor pruning في المحاضرة 04.

What slide 33 lists

ما الذي تسرده الشريحة 33

Trapفخ

Train mode and eval mode differ. Training uses the current mini-batch's μ and σ2; inference uses running averages. Run a model in training mode on a single sample and, for BN over N x D features, x − μ = 0 for every feature, so every output collapses to β.

وضع التدريب ووضع التقييم مختلفان. التدريب يستخدم μ وσ2 من mini-batch الحالي، وinference يستخدم running averages. شغّل نموذجاً في وضع التدريب على عيّنة واحدة، ومع BN على ميزات N x D يصبح x − μ = 0 لكل ميزة، فينهار كل خرج إلى β.

γ and β are learned; μ and σ2 are not. μ and σ2 are computed from data and never receive a gradient update.

γ وβ متعلَّمان، أما μ وσ2 فلا. μ وσ2 تُحسبان من البيانات ولا تتلقيان أي تحديث بالـ gradient.

Statistics are per feature over the batch, shape D, not per sample over its features (that is layer norm, next page).

الإحصائيات لكل ميزة عبر الدفعة، وشكلها D، لا لكل عيّنة عبر ميزاتها (ذلك هو layer norm، في الصفحة التالية).

Identity is γ = √(σ2 + ε), β = μ, not γ = 1, β = 0 (that only gives the plain normalized x̂).

identity تتحقق عند γ = √(σ2 + ε) وβ = μ، لا عند γ = 1 وβ = 0 (فهذه تعطي x̂ المسوّى فقط).

Memory hookمفتاح للحفظ

Normalize down the columns, then γ stretches and β slides. Frozen stats make BN a line, and a line folds into the layer before it.

سوِّ نزولاً في الأعمدة، ثم γ يمدّ وβ يُزيح. الإحصائيات المجمّدة تجعل BN خطاً مستقيماً، والخط المستقيم يندمج في الطبقة التي قبله.

Check yourself

اختبر نفسك

A BN layer follows a conv with 64 output channels. Which quantities are updated by gradient descent, and what is their shape?

طبقة BN تأتي بعد conv له 64 قناة خرج. أي الكميات تُحدَّث بالـ gradient descent، وما شكلها؟

Only the scale γ and shift β are trainable, one per channel. μ and σ2 are computed from the batch (training) or kept as running averages (inference), with no gradient. They are not per sample, so N x 64 (D) is wrong.

فقط scale γ وshift β قابلان للتدريب، واحد لكل قناة. أما μ وσ2 فتُحسبان من الدفعة (في التدريب) أو تُحفظان كـ running averages (في inference)، بلا gradient. وهي ليست لكل عيّنة، فالشكل N x 64 (الخيار D) خطأ.

In training mode one feature over a batch of 4 is x = [1, 1, 5, 5]. With γ = 2, β = −1 and ε ≈ 0, what is BN's output for the sample with x = 5?

في وضع التدريب، ميزة واحدة عبر دفعة من 4 عيّنات قيمها x = [1, 1, 5, 5]. مع γ = 2 وβ = −1 وε ≈ 0، ما خرج BN للعيّنة التي x = 5؟

μ = 12/4 = 3. σ2 = (4 + 4 + 4 + 4)/4 = 4, so √ = 2. x̂ = (5 − 3)/2 = 1. y = 2 · 1 + (−1) = 1. Option A applies γ and β to raw x (2 · 5 − 1). Option B forgets to divide by σ. Option D stops at the mean.

μ = 12/4 = 3. وσ2 = (4 + 4 + 4 + 4)/4 = 4، إذن الجذر يساوي 2. وx̂ = (5 − 3)/2 = 1. وy = 2 · 1 + (−1) = 1. الخيار A يطبّق γ وβ على x الخام (2 · 5 − 1). الخيار B ينسى القسمة على σ. والخيار D يتوقف عند المتوسط.

Fold BN into z = w x + b with w = 0.5, b = 2, running μ = 3, σ2 + ε = 0.25, γ = 2, β = 1. What are w' and b'?

ادمج BN في z = w x + b حيث w = 0.5 وb = 2 وrunning μ = 3 وσ2 + ε = 0.25 وγ = 2 وβ = 1. ما قيمتا w' وb'؟

s = γ/√(σ2 + ε) = 2/0.5 = 4. w' = 4 · 0.5 = 2. b' = 4 · (2 − 3) + 1 = −4 + 1 = −3. Check x = 1: unfused z = 2.5, y = 2 (2.5 − 3)/0.5 + 1 = −1; fused 2 · 1 − 3 = −1. Option B scales by γ only, forgetting the 1/√ term. Option C adds μ instead of subtracting it.

s = γ/√(σ2 + ε) = 2/0.5 = 4. وw' = 4 · 0.5 = 2. وb' = 4 · (2 − 3) + 1 = −4 + 1 = −3. تحقق عند x = 1: بدون دمج z = 2.5 وy = 2 (2.5 − 3)/0.5 + 1 = −1، ومع الدمج 2 · 1 − 3 = −1. الخيار B يضرب في γ فقط وينسى حد 1/√. والخيار C يجمع μ بدلاً من طرحه.

A student deploys a classifier and every single-image prediction comes out identical, regardless of the image. The classifier head is FC layers with BN (x : N x D). Most likely cause?

طالب نشر مصنّفاً فخرجت كل التنبؤات لصورة واحدة متطابقة، مهما كانت الصورة. رأس المصنّف طبقات FC مع BN (x : N x D). ما السبب الأرجح؟

In training mode BN normalizes with the current batch's statistics. With one sample, μ equals the sample itself, so x̂ = 0 and y = β no matter the input. Slide 33's warning: BN behaves differently in training and testing, a very common source of bugs. Folding (A) is exact and loses nothing.

في وضع التدريب يسوّي BN بإحصائيات الدفعة الحالية. ومع عيّنة واحدة يساوي μ العيّنة نفسها، فيصبح x̂ = 0 وy = β مهما كان الدخل. هذا تحذير الشريحة 33: BN يتصرف بشكل مختلف بين التدريب والاختبار، وهو مصدر شائع جداً للأخطاء. والدمج (الخيار A) دقيق تماماً ولا يُضيع شيئاً.

Which choice of γ and β makes BN return its input unchanged (y = x)?

أي اختيار لـ γ وβ يجعل BN يُرجع دخله كما هو (y = x)؟

y = γ (x − μ)/√(σ2 + ε) + β. With γ = √(σ2 + ε) the division cancels, leaving x − μ + β, and β = μ gives x. Option A gives the plain normalized x̂. Option D outputs the constant μ.

y = γ (x − μ)/√(σ2 + ε) + β. مع γ = √(σ2 + ε) تُلغى القسمة، فيبقى x − μ + β، وβ = μ يعطي x. الخيار A يعطي x̂ المسوّى فقط. والخيار D يُخرج الثابت μ.