Lecture 02 · NN Fundamentals

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

BN, LN, IN, GN and BN by hand

BN وLN وIN وGN، وBN باليد

Slides 34–38 الشرائح 34–38 P1 MUST

Four normalizations, one formula. The only thing that changes is which numbers are averaged together to make one mean. Then slide 38 makes you compute batch norm on a real mini-batch, every mean and variance by hand.

أربعة أنواع من normalization ومعادلة واحدة. الشيء الوحيد الذي يتغيّر هو: أيّ الأرقام تُجمع معاً لتعطي متوسطاً واحداً. ثم تطلب منك الشريحة 38 حساب batch norm على mini-batch حقيقية، كل متوسط وكل تباين باليد.

One formula, four choices of set

معادلة واحدة وأربعة خيارات للمجموعة

Every variant on slides 34 to 37 runs the same arithmetic: subtract a mean, divide by a standard deviation, then scale by γ and shift by β.

كل الأنواع في الشرائح من 34 إلى 37 تُجري الحساب نفسه: اطرح متوسطاً، واقسم على انحراف معياري، ثم اضرب في γ وأضف β.

y = γ · x − μ√(σ2 + ε) + β

Wu and He write it with a set Si: the mean μi used for value xi is averaged over the values k ∈ Si. Batch norm, layer norm, instance norm and group norm are just four definitions of Si. Learn the set and you know the method.

يكتبها Wu وHe باستخدام مجموعة Si: المتوسط μi المستخدم مع القيمة xi يُحسب على القيم k ∈ Si. إذن batch norm وlayer norm وinstance norm وgroup norm ليست إلا أربعة تعريفات مختلفة لـ Si. احفظ المجموعة تعرف الطريقة.

BATCH NORM N (samples) C one channel, all samples mu: 1 x C x 1 x 1 LAYER NORM N (samples) C one sample, all channels mu: N x 1 x 1 x 1 INSTANCE NORM N (samples) C one sample, one channel mu: N x C x 1 x 1 GROUP NORM N (samples) C one sample, C/G channels mu: N x G x 1 x 1 each cell = all H x W positions of one channel of one sample; shaded cells share one mean and one variance
Samples run across, channels run down. The shaded block is the set of values that share one μ and one σ.
العيّنات أفقياً والقنوات رأسياً. الكتلة المظلّلة هي مجموعة القيم التي تشترك في μ واحدة وσ واحدة.

في الرسم، العيّنات (N) أفقياً والقنوات (C) عمودياً، وكل خلية تمثل كل مواقع H x W لقناة واحدة من عيّنة واحدة. في batch norm يُظلَّل صفّ كامل: قناة واحدة عبر كل العيّنات. في layer norm عمود كامل: عيّنة واحدة بكل قنواتها. في instance norm خلية واحدة فقط. وفي group norm جزء من عمود: عيّنة واحدة ومجموعة من C/G قنوات. والخلايا المظلّلة تتشارك متوسطاً واحداً وتبايناً واحداً.

The shape rule

قاعدة الشكل

Read the shape of μ straight off the tensor: write a 1 wherever you averaged and the full size everywhere else. Batch norm on N×C×H×W averages over N, H and W, so μ is 1×C×1×1. Instance norm averages over H and W only, so μ is N×C×1×1.

اقرأ شكل μ مباشرة من الـ tensor: ضع 1 في كل محور أخذت عليه المتوسط والحجم الكامل في الباقي. batch norm على N×C×H×W يأخذ المتوسط على N وH وW، فيكون μ بشكل 1×C×1×1. وinstance norm يأخذ المتوسط على H وW فقط، فيكون μ بشكل N×C×1×1.

MethodالطريقةAverages overالمتوسط علىμ, σ shapeشكل μ, σγ, β shapeشكل γ, βNeeds a batch?يحتاج إلى batch؟Same at train and test?متطابق في التدريب والاختبار؟
BN, FC (slide 34 left)BN لطبقة FC (الشريحة 34 يساراً)N1 × D1 × DYesنعمNoلا
BN, conv (BatchNorm2d)BN للالتفاف (BatchNorm2d)N, H, W1×C×1×11×C×1×1YesنعمNoلا
Layer norm (slide 35)Layer norm (الشريحة 35)D, or C, H, W, per sampleD، أو C, H, W، لكل عيّنةN × 11 × DNoلاYesنعم
Instance norm (slide 36)Instance norm (الشريحة 36)H, W, per sample and channelH, W، لكل عيّنة ولكل قناةN×C×1×11×C×1×1NoلاYesنعم
Group norm (slide 37)Group norm (الشريحة 37)H, W and C/G channels, per sampleH, W وC/G من القنوات، لكل عيّنةN×G×1×11×C×1×1NoلاYesنعم

يلخّص الجدول العائلة كلها. BN لطبقة FC يأخذ المتوسط على N فيكون μ بشكل 1 × D. وBN للالتفاف يأخذه على N وH وW فيكون 1×C×1×1. وlayer norm يأخذه على كل خصائص العيّنة الواحدة فيكون N × 1. وinstance norm على H وW لكل عيّنة وقناة فيكون N×C×1×1. وgroup norm على H وW وC/G قناة فيكون N×G×1×1. أما γ وβ فهما لكل قناة (1×C×1×1) في BN وIN وGN، و1 × D في layer norm على مدخل N × D. والثلاثة الأخيرة لا تحتاج batch وتتصرف بالطريقة نفسها في التدريب والاختبار.

Notice γ and β do not follow the μ shape. They are learned per channel for BN, IN and GN, so a BatchNorm2d over 64 channels holds 128 learnable numbers whatever the image size. Slide 35 gives layer norm on an N × D input γ, β of shape 1 × D.

لاحظ أن γ وβ لا يتبعان شكل μ. فهما يُتعلَّمان لكل قناة في BN وIN وGN، ولذلك فإن BatchNorm2d على 64 قناة يحمل 128 رقماً قابلاً للتعلّم مهما كان حجم الصورة. والشريحة 35 تعطي layer norm على مدخل N × D قيم γ وβ بشكل 1 × D.

Why the batch-free three exist

لماذا وُجدت الأنواع الثلاثة التي لا تحتاج إلى batch

Layer norm (Ba, Kiros, Hinton 2016)

Layer norm (Ba, Kiros, Hinton 2016)

Statistics come from one sample's own features. Nothing depends on other samples, so slide 35 says it twice: same behavior at train and test, and it can be used in recurrent networks. It is the norm inside every transformer Add and Norm step.

الإحصاءات تأتي من خصائص العيّنة الواحدة نفسها، ولا شيء يعتمد على العيّنات الأخرى. لذلك تقول الشريحة 35 أمرين: السلوك نفسه في التدريب والاختبار، ويمكن استخدامه في الشبكات التكرارية (RNN). وهو نوع الـ normalization الموجود في كل خطوة Add and Norm داخل الـ transformer.

Instance norm (Ulyanov et al., CVPR 2017)

Instance norm (Ulyanov et al., CVPR 2017)

One mean per sample per channel, over the H × W plane only. It wipes out each image's contrast statistics, which is exactly what style transfer wants. Slide 36: same behavior at train and test.

متوسط واحد لكل عيّنة ولكل قناة، على مستوى H × W فقط. وهذا يمحو إحصاءات التباين الخاصة بكل صورة، وهو تماماً ما يريده نقل الأسلوب (style transfer). الشريحة 36: السلوك نفسه في التدريب والاختبار.

Group norm (Wu and He, ECCV 2018)

Group norm (Wu and He, ECCV 2018)

Split the C channels into G groups and average over H, W and the C/G channels of one group, per sample. G = 1 is layer norm, G = C is instance norm, and the default is G = 32. Its computation is independent of batch size, so it wins when the batch is tiny: ResNet-50 on ImageNet at batch size 2 has 34.7% error with BN and 24.1% with GN.

قسّم القنوات C إلى G مجموعة، وخذ المتوسط على H وW وC/G قناة من مجموعة واحدة، لكل عيّنة. عندما G = 1 يصبح layer norm، وعندما G = C يصبح instance norm، والقيمة الافتراضية G = 32. حسابه مستقل عن حجم الـ batch، لذلك يتفوّق عندما تكون الـ batch صغيرة جداً: ResNet-50 على ImageNet بحجم batch يساوي 2 يعطي خطأ 34.7% مع BN و24.1% مع GN.

On a device that can only fit one or two samples per training step, a batch-free norm is the difference between a model that trains and one that does not.

على جهاز لا يتّسع إلا لعيّنة أو عيّنتين في كل خطوة تدريب، فإن normalization لا يحتاج batch هو الفرق بين نموذج يتدرّب ونموذج لا يتدرّب.

Worked مثال محلول
one conv activation, N x C x H x W = 8 x 64 x 32 x 32

method        values per mean           number of means
BN            8 x 32 x 32  = 8192       64        (1 x 64 x 1 x 1)
LN            64 x 32 x 32 = 65536      8         (8 x 1 x 1 x 1)
IN            32 x 32      = 1024       8 x 64 = 512
GN, G = 32    2 x 32 x 32  = 2048       8 x 32 = 256

check: values per mean x number of means = 524288
       = 8 x 64 x 32 x 32 for every row

مثال محلول: tensor بشكل 8 x 64 x 32 x 32. في BN كل متوسط يجمع 8192 قيمة وعدد المتوسطات 64. في LN كل متوسط يجمع 65536 قيمة وعددها 8. في IN كل متوسط يجمع 1024 قيمة وعددها 512. وفي GN مع G = 32 كل متوسط يجمع 2048 قيمة وعددها 256. والتحقق: حاصل الضرب في كل صف يساوي 524288، أي عدد عناصر الـ tensor كله.

Memory hook خطّاف للذاكرة

"Batch norm is the only one that looks sideways." BN is the only method whose shaded set crosses the N axis. That single fact explains why it needs a batch, why it behaves differently at train and test, and why it fails at batch size 1 or 2.

"Batch norm هو الوحيد الذي ينظر إلى الجيران." BN هو الطريقة الوحيدة التي تعبر مجموعتها المظلّلة محور N. هذه الحقيقة الواحدة تفسّر لماذا يحتاج batch، ولماذا يختلف سلوكه بين التدريب والاختبار، ولماذا يفشل عند حجم batch يساوي 1 أو 2.

Batch norm by hand (slide 38)

Batch norm باليد (الشريحة 38)

Tom Yeh's sheet: four samples x1 to x4, each with three features, go through a linear layer, then ReLU, then BN, then scale and shift. Here BN works on an FC output, so each feature (row) gets one mean over the 4 samples.

ورقة Tom Yeh: أربع عيّنات من x1 إلى x4، لكل منها ثلاث خصائص، تمر عبر طبقة خطية، ثم ReLU، ثم BN، ثم scale and shift. هنا يعمل BN على مخرج طبقة FC، فكل خاصية (صف) تحصل على متوسط واحد عبر العيّنات الأربع.

Worked مثال محلول
inputs (columns):  x1 = (1, 0, 2)  x2 = (0, 3, 1)  x3 = (3, 1, 0)  x4 = (0, 1, 2)

linear layer, W rows and bias b:
  row 1  ( 1, 0,  1)   b =  0
  row 2  ( 1, 1,  0)   b = -1
  row 3  ( 0, 2, -1)   b =  0

step 1  z = W x + b, one sample at a time
             x1    x2    x3    x4
  row 1       3     1     3     2
  row 2       0     2     3     0
  row 3      -2     5     2     0

step 2  ReLU, only one negative entry: -2 becomes 0
  row 1       3     1     3     2
  row 2       0     2     3     0
  row 3       0     5     2     0

الخطوة 1: نحسب z = W x + b لكل عيّنة. مثلاً الصف الأول مع x1: 1·1 + 0·0 + 1·2 + 0 = 3. الخطوة 2: ReLU يحوّل القيمة السالبة الوحيدة -2 إلى 0.

Worked مثال محلول
step 3  batch statistics, per row, over the 4 samples, divide by m = 4

  row 1  values 3, 1, 3, 2
         sum 9          mu = 9/4 = 2.25
         deviations     0.75, -1.25, 0.75, -0.25
         squares        0.5625, 1.5625, 0.5625, 0.0625   sum 2.75
         var = 2.75/4 = 0.6875      sigma = 0.829

  row 2  values 0, 2, 3, 0
         sum 5          mu = 1.25
         deviations     -1.25, 0.75, 1.75, -1.25
         squares        1.5625, 0.5625, 3.0625, 1.5625   sum 6.75
         var = 6.75/4 = 1.6875      sigma = 1.299

  row 3  values 0, 5, 2, 0
         sum 7          mu = 1.75
         deviations     -1.75, 3.25, 0.25, -1.75
         squares        3.0625, 10.5625, 0.0625, 3.0625  sum 16.75
         var = 16.75/4 = 4.1875     sigma = 2.046

الخطوة 3: لكل صف نحسب المجموع ثم المتوسط بالقسمة على m = 4، ثم الانحرافات عن المتوسط ومربعاتها، ثم التباين بقسمة مجموع المربعات على 4. النتائج: المتوسطات 2.25 و1.25 و1.75، والتباينات 0.6875 و1.6875 و4.1875، والانحرافات المعيارية 0.829 و1.299 و2.046.

Worked مثال محلول
step 4  normalize: x_hat = (x - mu) / sigma   (eps ignored, it is ~1e-5)
             x1       x2       x3       x4
  row 1    0.905   -1.508    0.905   -0.302
  row 2   -0.962    0.577    1.347   -0.962
  row 3   -0.855    1.588    0.122   -0.855

step 5  scale and shift, trainable gamma = (2, 3, -1), beta = (0, 0, 1)
  y = gamma * x_hat + beta
             x1       x2       x3       x4
  row 1    1.81    -3.02     1.81    -0.60     (x2, beta 0)
  row 2   -2.89     1.73     4.04    -2.89     (x3, beta 0)
  row 3    1.86    -0.59     0.88     1.86     (x -1, then +1)

step 6  self-check every row
  row 1  mean 0 = beta    variance 4 = 2^2
  row 2  mean 0 = beta    variance 9 = 3^2
  row 3  mean 1 = beta    variance 1 = (-1)^2

الخطوة 4: نطرح متوسط الصف ونقسم على انحرافه المعياري. الخطوة 5: نضرب في γ = (2, 3, -1) ونضيف β = (0, 0, 1)، وهما المعاملان القابلان للتدريب في مصفوفة Scale & Shift على الشريحة. الخطوة 6: التحقق، متوسط كل صف في المخرج يساوي β، وتباينه يساوي γ2: أي 4 و9 و1.

Memorize this احفظ هذا

After BN, every feature's output has mean = β and variance = γ2 (exactly, when ε = 0). The x̂ row always has mean 0 and variance 1. Use this to check every by-hand answer: if row 3 above did not average to 1, there is an arithmetic slip.

بعد BN، مخرج كل خاصية له متوسط يساوي β وتباين يساوي γ2 (بالضبط عندما ε = 0). وصف x̂ دائماً متوسطه 0 وتباينه 1. استخدم هذا للتحقق من كل حل يدوي: لو لم يكن متوسط الصف الثالث أعلاه 1، فهناك خطأ حسابي.

Trap فخ

Divide by m, not m − 1. BN normalizes with the population (biased) variance: Algorithm 1 in Ioffe and Szegedy is σB2 = (1/m) Σ (xi − μB)2. Using m − 1 = 3 on row 1 gives 2.75/3 = 0.917, σ = 0.957 and x̂ = 0.783 instead of 0.905. The unbiased m/(m − 1) version only appears in the running variance stored for inference.

اقسم على m لا على m − 1. يستخدم BN تباين المجتمع (biased): الخوارزمية 1 عند Ioffe وSzegedy هي σB2 = (1/m) Σ (xi − μB)2. لو قسمت على m − 1 = 3 في الصف الأول لحصلت على 2.75/3 = 0.917 وσ = 0.957 وx̂ = 0.783 بدلاً من 0.905. ونسخة m/(m − 1) غير المتحيّزة لا تظهر إلا في running variance المحفوظ للاستدلال.

Know which one crosses the batch. Only BN averages over N. Layer norm is not "batch norm with a small batch": it averages across the features of one sample and never looks at other samples. Shrinking the batch degrades BN, it does not turn BN into LN.

اعرف أيها يعبر الـ batch. وحده BN يأخذ المتوسط على N. وlayer norm ليس "batch norm مع batch صغيرة": فهو يأخذ المتوسط على خصائص العيّنة الواحدة ولا ينظر أبداً إلى العيّنات الأخرى. تصغير الـ batch يُضعف BN، لكنه لا يحوّله إلى LN.

Per-feature, not per-sample. On slide 38 the mean is taken along each row (one feature across x1 to x4). Averaging down a column would be layer norm.

لكل خاصية، لا لكل عيّنة. في الشريحة 38 يُؤخذ المتوسط على طول كل صف (خاصية واحدة عبر x1 إلى x4). أما أخذه على العمود فهو layer norm.

Everything on one card

كل شيء في بطاقة واحدة

Normalization cheat card

بطاقة مراجعة التطبيع (normalization)

Check yourself

اختبر نفسك

A conv activation has shape N×C×H×W. Which normalization produces μ of shape N×C×1×1?

مخرج التفاف بشكل N×C×H×W. أي نوع من normalization يعطي μ بشكل N×C×1×1؟

A 1 appears wherever you averaged. N×C×1×1 keeps N and C and averages only H and W: one mean per sample per channel, which is instance norm. BN gives 1×C×1×1, LN gives N×1×1×1, and GN with G = 1 is LN.

يظهر الرقم 1 في كل محور أُخذ عليه المتوسط. الشكل N×C×1×1 يُبقي N وC ويأخذ المتوسط على H وW فقط: متوسط واحد لكل عيّنة ولكل قناة، وهذا هو instance norm. أما BN فيعطي 1×C×1×1، وLN يعطي N×1×1×1، وGN مع G = 1 هو LN.

One feature takes the values 3, 1, 3, 2 across a mini-batch of 4. What variance does batch norm use?

خاصية واحدة تأخذ القيم 3, 1, 3, 2 عبر mini-batch من 4 عيّنات. ما التباين الذي يستخدمه batch norm؟

μ = 9/4 = 2.25. Squared deviations 0.5625 + 1.5625 + 0.5625 + 0.0625 = 2.75. BN uses the population variance, so divide by m = 4: 0.6875. Option A is the sample variance (m − 1), the classic trap. Option C is σ, the square root of the right answer.

μ = 9/4 = 2.25. مجموع مربعات الانحرافات 0.5625 + 1.5625 + 0.5625 + 0.0625 = 2.75. يستخدم BN تباين المجتمع، فنقسم على m = 4: 0.6875. الخيار A هو تباين العيّنة (m − 1)، وهو الفخ المعروف. والخيار C هو σ، أي الجذر التربيعي للإجابة الصحيحة.

After BN with γ = −1 and β = 1 on one feature, what are the mean and variance of that feature's outputs over the batch?

بعد BN مع γ = −1 وβ = 1 على خاصية واحدة، ما متوسط مخرجات هذه الخاصية وتباينها عبر الـ batch؟

x̂ has mean 0 and variance 1. Then y = γx̂ + β has mean β = 1 and variance γ2 = (−1)2 = 1. A variance can never be negative (B), and the mean is β, not γ (D). This is row 3 of slide 38.

قيم x̂ متوسطها 0 وتباينها 1. ثم y = γx̂ + β متوسطه β = 1 وتباينه γ2 = (−1)2 = 1. التباين لا يكون سالباً أبداً (B)، والمتوسط هو β لا γ (D). وهذا هو الصف الثالث في الشريحة 38.

You fine-tune a detector on a microcontroller that fits only 2 images per step. Which normalization is the safest choice?

تريد إعادة تدريب نموذج كشف على متحكم دقيق لا يتّسع إلا لصورتين في كل خطوة. أي نوع من normalization هو الأكثر أماناً؟

BN estimates μ and σ from only 2 samples, so the estimates are noisy and its error rises sharply (ResNet-50 at batch 2: 34.7% with BN against 24.1% with GN). GN computes per sample and is independent of batch size. The formula is shared, but the set it averages over is what matters (D).

يقدّر BN قيمتي μ وσ من عيّنتين فقط، فتكون التقديرات مشوّشة ويرتفع الخطأ بحدة (ResNet-50 عند batch بحجم 2: 34.7% مع BN مقابل 24.1% مع GN). أما GN فيحسب لكل عيّنة وحدها، ومستقل عن حجم الـ batch. المعادلة مشتركة، لكن المجموعة التي يُؤخذ عليها المتوسط هي ما يهم (D).

A BatchNorm2d layer follows a conv with 64 output channels of size 32 × 32. How many learnable parameters does it hold?

طبقة BatchNorm2d تأتي بعد التفاف له 64 قناة مخرج بحجم 32 × 32. كم معاملاً قابلاً للتعلّم تحمل؟

γ and β are 1×C×1×1, so 2 × 64 = 128. The running μ and σ2 are stored buffers computed from data, not learned by backpropagation (C). They do not depend on H and W at all (A).

γ وβ بشكل 1×C×1×1، إذن 2 × 64 = 128. أما μ وσ2 الجاريان فهما قيم محفوظة تُحسب من البيانات ولا تُتعلَّم بالـ backpropagation (C). ولا يعتمدان على H وW إطلاقاً (A).