Majid Al-RaimiBatch, layer, instance and group normalizationتطبيع الدفعة والطبقة والمثيل والمجموعة

COE 592Lecture 02المحاضرة 02Part 05الجزء 05

Batch, layer, instance and group normalizationتطبيع الدفعة والطبقة والمثيل والمجموعة

Why nicely scaled activations make optimization easier, how batch normalization computes, scales and shifts, how it changes at inference, and the axes each normalization variant averages over.لماذا تجعل التنشيطات ذات المقياس المناسب التحسين أسهل، وكيف يحسب تطبيع الدفعة (batch normalization) ثم يقيس ويزيح، وكيف يتغير أثناء الاستدلال (inference)، والمحاور التي يحسب كل نوع من التطبيع المتوسط عليها.

Conceptsالمفاهيم
5
Slidesالشرائح
27-38
Readingمدة القراءة
30 min30 دقيقة
Understoodما فهمته
0/5 conceptsمفاهيم

Why this part mattersلماذا يهمّ هذا الجزء

Every network you will compress, quantize or deploy in this course carries normalization layers. Batch normalization is a large part of why deep CNNs train at all, and it is also the first optimization you get for free on a microcontroller: at inference it folds into the layer before it and costs nothing.

This part builds the normalization family from one question: which numbers are averaged together to make one mean? Answer it for the batch axis and you have batch norm; answer it for the feature axis and you have layer norm, the block inside every transformer in part 06. Along the way you meet the exam staples of this lecture: tensor shapes, the train versus test difference, fusing BN into a linear layer, and computing BN on a tiny batch by hand.

كل شبكة ستضغطها أو تجري لها quantization أو تنشرها في هذا المقرر تحتوي على طبقات normalization. الـ batch normalization سبب رئيسي في أن شبكات الـ CNN العميقة تتدرب أصلًا، وهو أيضًا أول تحسين تحصل عليه مجانًا على الـ microcontroller: ففي الاستدلال (inference) يُدمج في الطبقة التي قبله ولا يكلّف شيئًا.

يبني هذا الجزء عائلة الـ normalization كلها من سؤال واحد: أي الأرقام تُجمع معًا لتكوين متوسط واحد؟ أجب عنه على محور الـ batch تحصل على الـ batch norm؛ وأجب عنه على محور الـ features تحصل على الـ layer norm، وهي الكتلة الموجودة داخل كل transformer في الجزء 06. وفي الطريق تقابل أساسيات الامتحان في هذه المحاضرة: أشكال الـ tensors، والفرق بين التدريب والاختبار، ودمج الـ BN في طبقة خطية، وحساب الـ BN يدويًا على batch صغيرة.

By the end you canفي نهاية هذا الجزء ستستطيع

  1. Explain why uncentered or unevenly scaled inputs make y = Wx hard to optimize.تشرح لماذا تجعل المدخلات غير المتمركزة حول الصفر أو المتفاوتة في المقياس تحسين y = Wx صعبًا.
  2. Write the batch norm transform with the shape of every tensor and say which parts are learned.تكتب تحويل الـ batch norm مع شكل (shape) كل tensor، وتحدد أي أجزائه يُتعلَّم.
  3. State why BN differs between training and inference and derive the fused W' and b'.تبيّن لماذا يختلف الـ BN بين التدريب والاستدلال (inference)، وتشتق W' و b' بعد الدمج (fusion).
  4. Name the axes each of BN, LN, IN and GN averages over and read off the resulting mu shape.تسمّي المحاور التي يحسب كلٌّ من BN و LN و IN و GN المتوسط عليها، وتستنتج منها شكل mu الناتج.
  5. Compute BN on a small mini-batch by hand and self-check with mean = beta and variance = gamma squared.تحسب الـ BN يدويًا على mini-batch صغيرة، وتتحقق بنفسك من أن المتوسط = beta والتباين = gamma تربيع.

Feed a linear layer y = Wx two raw features: a pixel intensity somewhere in 0 to 255 and a binary flag in 0 to 1. For both features to have a similar influence on y, the two corresponding entries of W must differ by about two orders of magnitude. And because neither feature is centered at zero, the layer needs a large Bias just to bring its outputs near zero, where the next activation function does useful work.

أدخِل إلى طبقة خطية y = Wx خاصيتين (features) خامتين: شدة بكسل في مكان ما بين 0 to 255 وعلامة ثنائية بين 0 to 1. لكي يكون للخاصيتين تأثير متقارب على y، يجب أن يختلف المدخلان المقابلان لهما في W بنحو رتبتين عشريتين (مئة ضعف تقريبًا). ولأن أيًّا من الخاصيتين ليست متمركزة حول الصفر، تحتاج الطبقة إلى bias كبير فقط لتقريب مخرجاتها من الصفر، حيث تؤدي دالة التنشيط (activation function) التالية عملًا مفيدًا.

Those are the two troubles every layer faces. Inputs that are not centered force a large bias, and inputs with different scales per element force the entries of W to vary a lot. Both make gradient descent slow, because one learning rate has to serve directions of very different steepness, so the update zig-zags along the steep direction while creeping along the shallow one. Goodfellow, Bengio and Courville motivate the same problem with a deep chain of layers: every update to an early layer changes the statistics that every later layer sees, so the layers keep re-adapting to each other.

هاتان هما المشكلتان اللتان تواجههما كل طبقة. المدخلات غير المتمركزة تفرض bias كبيرًا، والمدخلات ذات المقاييس المختلفة من عنصر لآخر تفرض أن تتفاوت قيم W كثيرًا. وكلتاهما تبطئ الـ gradient descent، لأن learning rate واحدًا يجب أن يخدم اتجاهات شديدة الاختلاف في انحدارها، فيتعرّج التحديث (zig-zag) على الاتجاه شديد الانحدار بينما يزحف ببطء على الاتجاه المنبسط. ويعلّل Goodfellow و Bengio و Courville المشكلة نفسها بسلسلة عميقة من الطبقات: كل تحديث لطبقة مبكرة يغيّر الإحصاءات التي تراها كل طبقة لاحقة، فتظل الطبقات تعيد التكيّف بعضها مع بعض.

The idea, due to Ioffe and Szegedy in 2015, is to stop hoping the inputs are nice and to force them to be. For each dimension k, subtract the mean and divide by the standard deviation, so that the dimension has zero mean and unit variance:

الفكرة، التي تعود إلى Ioffe و Szegedy عام 2015، هي أن نكفّ عن الأمل في أن تكون المدخلات جيدة وأن نجبرها على ذلك. لكل بُعد k، اطرح المتوسط واقسم على الانحراف المعياري، فيصبح لهذا البعد متوسط صفري وتباين يساوي واحدًا:

x^(k)=x(k)−E[x(k)]Var[x(k)]\hat{x}^{(k)} = \frac{x^{(k)} - \mathrm{E}[x^{(k)}]}{\sqrt{\mathrm{Var}[x^{(k)}]}}
Per-dimension standardization, the seed of batch normalization (slide 29)التوحيد القياسي لكل بُعد، وهو بذرة batch normalization (الشريحة 29)

The part that makes this a layer rather than a preprocessing step is that the map is differentiable. It sits inside the network, at any hidden layer, and gradients flow through it exactly as through a convolution. The CS231n notes call it differentiable preprocessing built into the network itself. On slide 27 this is why Normalization appears as the fifth component of a CNN, beside convolution, pooling, fully connected layers and activations, and slide 39 later returns to the same map with the activation function circled instead.

ما يجعل هذا طبقةً لا خطوة معالجة مسبقة (preprocessing) هو أن هذه الدالة قابلة للاشتقاق. فهي تقع داخل الشبكة، عند أي طبقة مخفية، وتمر الـ gradients خلالها تمامًا كما تمر خلال convolution. وتسمّيها ملاحظات CS231n معالجة مسبقة قابلة للاشتقاق مبنية داخل الشبكة نفسها. ولهذا يظهر Normalization في الشريحة 27 كمكوّن خامس للـ CNN، بجانب الـ convolution والـ pooling والطبقات الـ fully connected والـ activations، ثم تعود الشريحة 39 لاحقًا إلى الخريطة نفسها مع وضع دائرة حول دالة التنشيط بدلًا منه.

A raw feature cloud sits off-center with unequal spread. Standardizing every axis moves its mean to the origin and gives each axis unit variance.سحابة خاصيات خام تقع بعيدًا عن المركز وبانتشار غير متساوٍ. توحيد المقياس على كل محور ينقل متوسطها إلى نقطة الأصل ويعطي كل محور تباينًا يساوي واحدًا.

Recall

Give the two properties of an input x that make y = Wx hard to optimize, and what each forces the layer to do.اذكر الخاصيتين في المدخل x اللتين تجعلان تحسين y = Wx صعبًا، وما الذي تفرضه كل منهما على الطبقة.

Inputs not centered around zero, which forces a large bias, and inputs with different scaling per element, which forces the entries of W to vary a lot so that one learning rate fits badly in every direction.
مدخلات غير متمركزة حول الصفر، وهذا يفرض bias كبيرًا؛ ومدخلات بمقياس مختلف لكل عنصر، وهذا يفرض أن تتفاوت قيم W كثيرًا، فلا يناسب learning rate واحد كل الاتجاهات جيدًا.

Start with one column of numbers. Take the mini-batch from slide 38 after its ReLU, and look only at feature 1 across the four samples: (3, 1, 3, 2). Standardizing that column is the entire batch norm computation in miniature.

ابدأ بعمود واحد من الأرقام. خذ الـ mini-batch من الشريحة 38 بعد الـ ReLU، وانظر فقط إلى الخاصية 1 عبر العينات الأربع: (3, 1, 3, 2). توحيد مقياس هذا العمود هو حساب الـ batch norm كله في صورة مصغّرة.

Worked exampleمثال محلول

One feature, four samplesخاصية واحدة، أربع عينات

  1. Mean over the batchالمتوسط على امتداد الـ batch

    mu = (3 + 1 + 3 + 2) / 4 = 2.25
    mu = (3 + 1 + 3 + 2) / 4 = 2.25
  2. Variance over the batchالتباين على امتداد الـ batch

    sigma squared = ((0.75) squared + (-1.25) squared + (0.75) squared + (-0.25) squared) / 4 = 0.6875
    sigma squared = ((0.75) squared + (-1.25) squared + (0.75) squared + (-0.25) squared) / 4 = 0.6875
  3. Normalize each valueوحّد مقياس كل قيمة

    Divide each deviation by sqrt(0.6875 + eps), about 0.829: x_hat = (0.905, -1.508, 0.905, -0.302)
    اقسم كل انحراف عن المتوسط على sqrt(0.6875 + eps), about 0.829 (أي نحو 0.829): x_hat = (0.905, -1.508, 0.905, -0.302)
  4. Resultالنتيجة

    One mean and one variance for the feature, computed across the samples. Every feature gets its own pair.
    متوسط واحد وتباين واحد للخاصية، يُحسبان عبر العينات. وكل خاصية تحصل على زوجها الخاص.

Now the general rule. The input to a batch norm layer after a fully connected layer is a matrix x of shape N x D: N samples in the mini-batch (the Batch size) by D features. Every average runs down the N axis, and that is the whole story of the axes: one statistic per feature column, averaged over the sample rows.

الآن القاعدة العامة. المدخل إلى طبقة batch norm بعد طبقة fully connected هو مصفوفة x شكلها N x D: عدد N من العينات في الـ mini-batch (أي الـ batch size) في عدد D من الخاصيات. كل متوسط يُحسب نزولًا على محور N، وهذه هي قصة المحاور كلها: إحصائية واحدة لكل عمود خاصية، محسوبة بالمتوسط على صفوف العينات.

μj=1N∑i=1Nxi,jσj2=1N∑i=1N(xi,j−μj)2\mu_j = \frac{1}{N}\sum_{i=1}^{N} x_{i,j} \qquad \sigma_j^2 = \frac{1}{N}\sum_{i=1}^{N} (x_{i,j} - \mu_j)^2
Per-feature mean and variance over the batch, each of shape Dالمتوسط والتباين لكل سمة عبر الدفعة، وأبعاد كل منهما D
x^i,j=xi,j−μjσj2+εyi,j=γj x^i,j+βj\hat{x}_{i,j} = \frac{x_{i,j} - \mu_j}{\sqrt{\sigma_j^2 + \varepsilon}} \qquad y_{i,j} = \gamma_j\,\hat{x}_{i,j} + \beta_j
Normalize, then scale and shift. x_hat and y have shape N x D, gamma and beta have shape Dطبِّع ثم حجِّم وأزِح. أبعاد x_hat وy هي N x D، وأبعاد gamma وbeta هي D

Shape of every tensor in batch norm for a fully connected layerشكل كل tensor في الـ batch norm لطبقة fully connected

x
N x DN x D
mu_j
DD
sigma_j squared
DD
x_hat
N x DN x D
gamma, beta
DD
y
N x DN x D

The epsilon under the root is a tiny constant, 1e-5 by default in PyTorch, that prevents division by zero when a feature happens to be constant across the batch. It changes nothing numerically otherwise, but it appears in every formula and in every fusion derivation, so keep it.

الـ epsilon تحت الجذر ثابت صغير جدًا، قيمته 1e-5 افتراضيًا في PyTorch، يمنع القسمة على صفر حين تكون خاصية ما ثابتة عبر الـ batch. لا يغيّر شيئًا عدديًا فيما عدا ذلك، لكنه يظهر في كل معادلة وفي كل اشتقاق للدمج (fusion)، فاحتفظ به.

Why gamma and beta existلماذا توجد gamma و beta

Is forcing zero mean and unit variance always good? It is a hard constraint, and a network is not always best served by activations pinned to a standard distribution. So the layer gets two learnable vectors of shape D, gamma and beta, and outputs y = gamma x_hat + beta. Ioffe and Szegedy point out that setting gamma = sqrt(Var[x]) and beta = E[x] recovers the original activations, if that were the optimal thing to do. The network can therefore undo normalization entirely, which means normalization can never make the model less expressive; it can only change what is easy to learn.

هل فرض متوسط صفري وتباين يساوي واحدًا جيد دائمًا؟ إنه قيد صارم، والشبكة لا تُخدم دائمًا على أفضل وجه بتنشيطات مثبتة على توزيع معياري. لذلك تحصل الطبقة على متجهين قابلين للتعلّم شكلهما D، هما gamma و beta، وتُخرج y = gamma x_hat + beta. ويشير Ioffe و Szegedy إلى أن وضع gamma = sqrt(Var[x]) و beta = E[x] يستعيد التنشيطات الأصلية، إن كان ذلك هو الأمثل. فالشبكة إذن تستطيع إلغاء الـ normalization تمامًا، وهذا يعني أنه لا يمكن أن يجعل النموذج أقل قدرة على التعبير؛ كل ما يفعله أنه يغيّر ما يسهل تعلّمه.

Goodfellow, Bengio and Courville explain why the new parametrization learns more easily even though it can represent the same functions. In the original network the mean of a hidden unit is set by a long chain of interacting weights in all the layers below. After BN the mean is set by beta alone and the scale by gamma alone, two parameters with a direct, local effect on the quantity gradient descent needs to move.

يشرح Goodfellow و Bengio و Courville لماذا تتعلّم الصياغة الجديدة (parametrization) بسهولة أكبر رغم أنها تمثّل الدوال نفسها. في الشبكة الأصلية يتحدد متوسط الوحدة المخفية بسلسلة طويلة من الأوزان المتفاعلة في كل الطبقات التي تحتها. وبعد الـ BN يتحدد المتوسط بـ beta وحدها والمقياس بـ gamma وحدها، وهما معاملان لهما أثر مباشر ومحلي على الكمية التي يحتاج الـ gradient descent إلى تحريكها.

The tanh plot on slide 31 makes the point concrete. The derivative 1 - tanh squared (x) peaks at 1 at the origin and falls below 0.1 once |x| exceeds about 1.8. If normalized values feed a tanh, then gamma decides how far they reach into the flat, saturated tails and beta decides where the center of the band sits. A small gamma keeps the layer almost linear; a large one lets it saturate on purpose. The model chooses the amount of saturation instead of inheriting it from whatever scale the previous layer produced.

يجعل منحنى الـ tanh في الشريحة 31 الفكرة ملموسة. المشتقة 1 - tanh squared (x) تبلغ ذروتها 1 عند نقطة الأصل وتنخفض تحت 0.1 بمجرد أن تتجاوز |x| نحو 1.8. إذا دخلت القيم الموحّدة المقياس إلى tanh، فإن gamma تحدد إلى أي مدى تصل إلى الأطراف المسطّحة المشبعة، و beta تحدد أين يقع مركز النطاق. قيمة gamma صغيرة تُبقي الطبقة شبه خطية؛ وقيمة كبيرة تتيح لها التشبّع عن قصد. فالنموذج يختار مقدار التشبّع بدل أن يرثه من أي مقياس أنتجته الطبقة السابقة.

The band is the range of inputs a tanh receives. gamma widens it from the linear middle into the saturated tails, and beta slides its center.النطاق هو مدى المدخلات التي تستقبلها الـ tanh. الـ gamma توسّعه من المنتصف الخطي إلى الأطراف المشبعة، والـ beta تزيح مركزه.

Recall

For x of shape N x D, write the four BN equations and the shape of each of mu, sigma squared, x_hat, gamma, beta and y.لمدخل x شكله N x D، اكتب معادلات الـ BN الأربع وشكل كل من mu و sigma squared و x_hat و gamma و beta و y.

mu_j = (1/N) sum_i x_ij and sigma_j squared = (1/N) sum_i (x_ij - mu_j) squared, both of shape D. x_hat = (x - mu) / sqrt(sigma squared + eps), shape N x D. y = gamma x_hat + beta, shape N x D, with gamma and beta of shape D.
mu_j = (1/N) sum_i x_ij و sigma_j squared = (1/N) sum_i (x_ij - mu_j) squared، وشكل كل منهما D. و x_hat = (x - mu) / sqrt(sigma squared + eps)، وشكلها N x D. و y = gamma x_hat + beta، وشكلها N x D، مع gamma و beta بشكل D.

Quick checkاختبار سريع

For a fully connected layer with input of shape N x D, over which axis does batch normalization average to get one mean?لطبقة fully connected مدخلها بشكل N x D، على أي محور يحسب الـ batch normalization المتوسط للحصول على متوسط واحد؟

A keyword-spotting model on a microcontroller hears one audio clip at a time. A batch of one has zero variance, so the statistics of the "batch" are meaningless, and even a batch of ten would make the answer for one clip depend on which nine clips happened to arrive with it. Ioffe and Szegedy state the requirement plainly: at inference the output should depend only on the input, deterministically.

نموذج لاكتشاف الكلمات المفتاحية (keyword spotting) على microcontroller يسمع مقطعًا صوتيًا واحدًا في كل مرة. والـ batch المكوّنة من عينة واحدة تباينها صفر، فتكون إحصاءات هذه "الـ batch" بلا معنى، وحتى batch من عشرة مقاطع ستجعل إجابة مقطع واحد تعتمد على المقاطع التسعة التي صادف وصولها معه. ويصوغ Ioffe و Szegedy الشرط بوضوح: في الاستدلال يجب أن يعتمد المخرج على المدخل وحده، وبشكل حتمي (deterministic).

So the layer changes its source of statistics. During training it keeps a running average of the mini-batch means and variances it has seen. At inference it uses those stored values and ignores the batch entirely. PyTorch updates the buffers as running = (1 - momentum) running + momentum x_batch with momentum 0.1, normalizes with the biased variance during training, and stores the unbiased variance (divide by N - 1) in running_var, following the paper's m/(m - 1) correction. Goodfellow, Bengio and Courville note the payoff: with running averages the model can be evaluated on a single example.

لذلك تغيّر الطبقة مصدر إحصاءاتها. أثناء التدريب تحتفظ بـ متوسط متحرك (running average) لمتوسطات وتباينات الـ mini-batches التي رأتها. وفي الاستدلال تستخدم تلك القيم المخزنة وتتجاهل الـ batch تمامًا. يحدّث PyTorch هذه الـ buffers بالقاعدة running = (1 - momentum) running + momentum x_batch مع momentum قيمته 0.1، ويوحّد المقياس بالتباين المتحيز (biased) أثناء التدريب، ويخزّن التباين غير المتحيز (القسمة على N - 1) في running_var، تبعًا لتصحيح الورقة m/(m - 1). ويلاحظ Goodfellow و Bengio و Courville المكسب: مع المتوسطات المتحركة يمكن تقييم النموذج على مثال واحد.

Frozen statistics turn BN into an affine mapالإحصاءات المجمّدة تحوّل الـ BN إلى تحويل أفيني (affine map)

Once mu and sigma squared are constants, batch norm on feature j is nothing more than multiply by one number and add another. And if the layer before it is a linear layer z = Wx + b, two affine maps in a row are one affine map. Write it out:

بمجرد أن تصبح mu و sigma squared ثوابت، لا يعدو الـ batch norm على الخاصية j كونه ضربًا في عدد وإضافة عدد آخر. وإذا كانت الطبقة التي قبله طبقة خطية z = Wx + b، فإن تحويلين أفينيين متتاليين يساويان تحويلًا أفينيًا واحدًا. اكتبه صراحة:

y=γ⊙(Wx+b)−μσ2+ε+β=W′x+b′y = \gamma \odot \frac{(Wx + b) - \mu}{\sqrt{\sigma^2 + \varepsilon}} + \beta = W'x + b'
Batch norm after a linear layer, with frozen mu and sigma squaredbatch norm بعد طبقة خطية، مع تجميد mu ومربع sigma
W′=diag⁡ ⁣(γσ2+ε)Wb′=γ⊙b−μσ2+ε+βW' = \operatorname{diag}\!\left(\frac{\gamma}{\sqrt{\sigma^2 + \varepsilon}}\right) W \qquad b' = \gamma \odot \frac{b - \mu}{\sqrt{\sigma^2 + \varepsilon}} + \beta
BN fusion: row j of W is scaled by gamma_j / sqrt(sigma_j squared + eps), and the bias absorbs the shiftدمج BN: يُضرب الصف j من W في gamma_j / sqrt(sigma_j squared + eps)، ويمتص الانحياز الإزاحة

Read the first formula per output row j: the whole row of W is multiplied by the scalar gamma_j / sqrt(sigma_j squared + eps), and the bias becomes that scalar times (b_j - mu_j), plus beta_j. The same holds for a convolution: each output filter is scaled by its channel's factor. Ioffe and Szegedy already say this in the paper: the normalization is a linear transform that may be composed with the scaling by gamma and shift by beta into a single linear transform. PyTorch ships it as torch.nn.utils.fusion.fuse_conv_bn_eval, which requires both modules in eval mode with their running buffers computed. This is Batch norm fusion.

اقرأ المعادلة الأولى لكل صف مخرجات j: الصف كله من W يُضرب في العدد gamma_j / sqrt(sigma_j squared + eps)، ويصبح الـ bias هو هذا العدد مضروبًا في (b_j - mu_j) مضافًا إليه beta_j. والأمر نفسه ينطبق على الـ convolution: كل filter مخرجات يُحجَّم بمعامل قناته. وقد قال Ioffe و Szegedy هذا في الورقة نفسها: الـ normalization تحويل خطي يمكن تركيبه مع التحجيم بـ gamma والإزاحة بـ beta في تحويل خطي واحد. ويوفّره PyTorch باسم torch.nn.utils.fusion.fuse_conv_bn_eval، الذي يتطلب أن تكون الوحدتان في وضع eval وأن تكون الـ running buffers محسوبة. هذا هو BN fusion.

Worked exampleمثال محلول

Fusing BN into the slide 38 linear layerدمج الـ BN في الطبقة الخطية من الشريحة 38

  1. Take the linear layer and frozen statisticsخذ الطبقة الخطية والإحصاءات المجمّدة

    W = [[1, 0, 1], [1, 1, 0], [0, 2, -1]], b = (0, -1, 0), gamma = (2, 3, -1), beta = (0, 0, 1). For frozen statistics use the batch statistics of z = Wx + b itself (BN sits directly on the linear output, no ReLU in between): mu = (2.25, 1.25, 1.25), sigma squared = (0.6875, 1.6875, 6.6875).
    W = [[1, 0, 1], [1, 1, 0], [0, 2, -1]]، b = (0, -1, 0)، gamma = (2, 3, -1)، beta = (0, 0, 1). وكإحصاءات مجمّدة استخدم إحصاءات الـ batch لـ z = Wx + b نفسها (الـ BN يقع مباشرة على المخرج الخطي، دون ReLU بينهما): mu = (2.25, 1.25, 1.25)، sigma squared = (0.6875, 1.6875, 6.6875).
  2. Compute one scale factor per output rowاحسب معامل تحجيم واحدًا لكل صف مخرجات

    s_j = gamma_j / sqrt(sigma_j squared + eps), so s = (2.412, 2.309, -0.387).
    s_j = gamma_j / sqrt(sigma_j squared + eps)، إذن s = (2.412, 2.309, -0.387).
  3. Scale each row of W and rebuild the biasحجّم كل صف من W وأعد بناء الـ bias

    Row jالصف jgamma_j / sqrt(var_j + eps)gamma_j / sqrt(var_j + eps)Row j of W'الصف j من W'b'_jb'_j
    112 / 0.829 = 2.4122 / 0.829 = 2.412(2.412, 0, 2.412)(2.412, 0, 2.412)2.412 (0 - 2.25) + 0 = -5.4272.412 (0 - 2.25) + 0 = -5.427
    223 / 1.299 = 2.3093 / 1.299 = 2.309(2.309, 2.309, 0)(2.309, 2.309, 0)2.309 (-1 - 1.25) + 0 = -5.1962.309 (-1 - 1.25) + 0 = -5.196
    33-1 / 2.586 = -0.387-1 / 2.586 = -0.387(0, -0.773, 0.387)(0, -0.773, 0.387)-0.387 (0 - 1.25) + 1 = 1.483-0.387 (0 - 1.25) + 1 = 1.483
    Row jالصف jgamma_j / sqrt(var_j + eps)gamma_j / sqrt(var_j + eps)Row j of W'الصف j من W'b'_jb'_j
    112 / 0.829 = 2.4122 / 0.829 = 2.412(2.412, 0, 2.412)(2.412, 0, 2.412)2.412 (0 - 2.25) + 0 = -5.4272.412 (0 - 2.25) + 0 = -5.427
    223 / 1.299 = 2.3093 / 1.299 = 2.309(2.309, 2.309, 0)(2.309, 2.309, 0)2.309 (-1 - 1.25) + 0 = -5.1962.309 (-1 - 1.25) + 0 = -5.196
    33-1 / 2.586 = -0.387-1 / 2.586 = -0.387(0, -0.773, 0.387)(0, -0.773, 0.387)-0.387 (0 - 1.25) + 1 = 1.483-0.387 (0 - 1.25) + 1 = 1.483
  4. One linear layer replaces twoطبقة خطية واحدة تحل محل طبقتين

    W'x + b' agrees with BN(Wx + b) to floating-point precision on all four slide 38 samples, which you will meet in full in the last concept. The deployed model holds only W' and b'; gamma, beta, the running mean and the running variance vanish from the binary.
    W'x + b' يطابق BN(Wx + b) حتى دقة الفاصلة العائمة على عينات الشريحة 38 الأربع كلها، والتي ستقابلها كاملة في المفهوم الأخير. النموذج المنشور يحمل فقط W' و b'؛ أما gamma و beta والمتوسط المتحرك والتباين المتحرك فتختفي من الملف التنفيذي.
Two blocks at training time, FC and BN, become one FC block with new weights W' and b' at inference. No multiply-accumulate is added.كتلتان وقت التدريب، FC ثم BN، تصبحان كتلة FC واحدة بأوزان جديدة W' و b' في الاستدلال. لا تُضاف أي عملية multiply-accumulate.

For embedded deployment this is the reason the slide says zero overhead at test time. A fused network runs no extra multiply-accumulate operations, moves no extra activations through memory, launches one fewer kernel per layer, and stores four fewer vectors per layer in flash. In later lectures on pruning, the very gamma factors that get fused away are also what network slimming reads to decide which channels matter.

في النشر على الأنظمة المدمجة، هذا هو سبب قول الشريحة "صفر تكلفة إضافية وقت الاختبار". الشبكة المدموجة لا تنفّذ أي عمليات multiply-accumulate إضافية، ولا تنقل أي تنشيطات إضافية عبر الذاكرة، وتطلق kernel أقل بواحد في كل طبقة، وتخزّن أربعة متجهات أقل في كل طبقة في ذاكرة الـ flash. وفي محاضرات لاحقة عن الـ pruning، فإن معاملات gamma نفسها التي تُدمج وتختفي هنا هي ما يقرؤه الـ network slimming ليقرر أي القنوات مهمة.

What BN buys during training, and the one way it bitesما يقدّمه الـ BN أثناء التدريب، والطريقة الوحيدة التي يؤذيك بها

  • Much easier training and higher learning rates: normalizing each layer's input stops small parameter changes from amplifying into large, suboptimal changes in activations and gradients as they pass through many layers (Ioffe and Szegedy, section 3.3). On ImageNet the paper reaches the same accuracy as its baseline in 14 times fewer training steps.تدريب أسهل بكثير ومعدلات تعلّم أعلى: توحيد مقياس مدخل كل طبقة يمنع التغييرات الصغيرة في المعاملات من أن تتضخم إلى تغييرات كبيرة وغير مثلى في التنشيطات والـ gradients أثناء مرورها عبر طبقات كثيرة (Ioffe و Szegedy، القسم 3.3). وعلى ImageNet تصل الورقة إلى دقة خط الأساس نفسها بعدد خطوات تدريب أقل بـ 14 مرة.
  • Better gradient flow: the tanh argument from the previous concept applies at every layer. Activations are kept out of the saturated tails unless the model wants them there, so derivatives stay usable.تدفق أفضل للـ gradient: حجة الـ tanh من المفهوم السابق تنطبق عند كل طبقة. تُبقى التنشيطات خارج الأطراف المشبعة ما لم يرد النموذج وجودها هناك، فتظل المشتقات قابلة للاستخدام.
  • Robustness to initialization: scaling the weights of a layer by a constant scales its output by the same constant, and normalization divides that constant back out. The scale of the initial weights largely stops mattering.متانة أمام الـ initialization: ضرب أوزان طبقة في ثابت يضرب مخرجها في الثابت نفسه، والـ normalization يقسم هذا الثابت ويلغيه. فيتوقف مقياس الأوزان الابتدائية عن أن يكون مهمًا إلى حد كبير.
  • Regularization during training, the "How?" on slide 33: each sample is normalized with statistics that depend on the other random samples in its mini-batch, so the network no longer produces deterministic values for a given training example (section 3.4). That injected noise acts like a mild regularizer, and the paper reports that dropout can be removed or reduced in strength. Dive into Deep Learning notes that batch sizes around 50 to 100 inject roughly the right amount of noise.تنظيم (regularization) أثناء التدريب، وهو "How?" في الشريحة 33: كل عينة يُوحَّد مقياسها بإحصاءات تعتمد على العينات العشوائية الأخرى في الـ mini-batch الخاصة بها، فلا تعود الشبكة تنتج قيمًا حتمية لمثال تدريب معين (القسم 3.4). هذه الضوضاء المحقونة تعمل كمنظِّم خفيف، وتذكر الورقة أنه يمكن إزالة الـ dropout أو تخفيف قوته. ويلاحظ كتاب Dive into Deep Learning أن أحجام batch في حدود 50 to 100 تحقن تقريبًا المقدار المناسب من الضوضاء.

The red line on slide 33 is the hazard that follows from everything above. The layer computes something different in training mode (batch statistics) and evaluation mode (running statistics). Forget to call model.eval() and your deployed model's answer for one input depends on the other inputs in the batch and degrades silently; for a batch of one, x_hat is 0 by construction so every feature collapses to beta (PyTorch's BatchNorm1d refuses to run at all in that case). It is one of the most common bugs in deep learning code precisely because, for any larger batch, nothing crashes.

السطر الأحمر في الشريحة 33 هو الخطر الناتج عن كل ما سبق. الطبقة تحسب شيئًا مختلفًا في وضع التدريب (إحصاءات الـ batch) عنه في وضع التقييم (الإحصاءات المتحركة). انسَ استدعاء model.eval() وستصبح إجابة نموذجك المنشور لمدخل واحد معتمدة على المدخلات الأخرى في الـ batch، وتتدهور بصمت؛ وفي batch من عينة واحدة تكون x_hat مساوية لـ 0 بحكم التعريف، فتنهار كل خاصية إلى beta (والـ BatchNorm1d في PyTorch يرفض العمل أصلًا في هذه الحالة). إنه من أكثر الأخطاء شيوعًا في كود التعلّم العميق تحديدًا لأنه، مع أي batch أكبر، لا ينهار شيء.

VarianceالتباينFeature 1الخاصية 1Feature 2الخاصية 2Feature 3الخاصية 3
Biased (training)متحيز (biased، أثناء التدريب)0.68750.68751.68751.68754.18754.1875
Unbiased (running_var)غير متحيز (running_var)0.9170.9172.252.255.5835.583

Recall

Why does BN behave differently at train and test time, and what does PyTorch store to make test time work?لماذا يتصرف الـ BN بشكل مختلف بين التدريب والاختبار، وما الذي يخزّنه PyTorch ليعمل وقت الاختبار؟

Training normalizes with the current mini-batch statistics, which makes each output depend on the batch. Testing must be deterministic and work for a single input, so BN uses running_mean and running_var, buffers updated during training with momentum 0.1 (the variance stored unbiased).
التدريب يوحّد المقياس بإحصاءات الـ mini-batch الحالية، فيعتمد كل مخرج على الـ batch. أما الاختبار فيجب أن يكون حتميًا ويعمل مع مدخل واحد، لذلك يستخدم الـ BN كلًّا من running_mean و running_var، وهما buffers تُحدَّث أثناء التدريب بـ momentum قيمته 0.1 (والتباين يُخزَّن غير متحيز).

Recall

Derive W' and b' when BN with frozen statistics directly follows y = Wx + b.اشتق W' و b' عندما يأتي BN بإحصاءات مجمّدة مباشرة بعد y = Wx + b.

y = gamma (Wx + b - mu) / sqrt(sigma squared + eps) + beta. Distribute: W' = diag(gamma / sqrt(sigma squared + eps)) W and b' = gamma (b - mu) / sqrt(sigma squared + eps) + beta. Each output row of W is scaled by its own factor.
y = gamma (Wx + b - mu) / sqrt(sigma squared + eps) + beta. وزّع الحدود: W' = diag(gamma / sqrt(sigma squared + eps)) W و b' = gamma (b - mu) / sqrt(sigma squared + eps) + beta. كل صف مخرجات من W يُحجَّم بمعامله الخاص.

Quick checkاختبار سريع

During inference, which mean does a batch normalization layer subtract from its input?أثناء الاستدلال (inference)، أي متوسط تطرحه طبقة الـ batch normalization من مدخلها؟

Take one activation tensor from a convolution layer, N x C x H x W = 8 x 64 x 32 x 32. It holds about half a million numbers. Every normalization in this part does the same arithmetic, subtract a mean and divide by a standard deviation, then scale and shift. The only thing that distinguishes them is the answer to one question: which of those numbers are averaged together to make one mean?

خذ tensor تنشيطات واحدًا من طبقة convolution، N x C x H x W = 8 x 64 x 32 x 32. إنه يحمل نحو نصف مليون رقم. كل normalization في هذا الجزء يجري الحساب نفسه: اطرح متوسطًا واقسم على انحراف معياري، ثم حجّم وأزح. والشيء الوحيد الذي يميّز بعضها عن بعض هو الإجابة عن سؤال واحد: أي هذه الأرقام تُجمع معًا لتكوين متوسط واحد؟

Normalizationالـ normalizationValues per meanعدد القيم لكل متوسطNumber of meansعدد المتوسطات
Batch norm for convolutionsالـ batch norm للـ convolutions8 x 32 x 32 = 81928 x 32 x 32 = 81926464
Layer normالـ layer norm64 x 32 x 32 = 6553664 x 32 x 32 = 6553688
Instance norm, per Feature map per sampleالـ instance norm، لكل feature map لكل عينة32 x 32 = 102432 x 32 = 1024512512
Group normالـ group norm2 x 1024 = 20482 x 1024 = 2048256256
The same N x C x H x W = 8 x 64 x 32 x 32 tensor under each normalization: how many values one mean averages, and how many means the tensor holdsالـ tensor نفسه N x C x H x W = 8 x 64 x 32 x 32 تحت كل نوع normalization: كم قيمة يجمعها المتوسط الواحد، وكم متوسطًا يحمل الـ tensor

Wu and He write all four as one formula. Each value x_i is normalized with a mean and standard deviation computed over a set S_i, and different normalizations simply use different definitions of that set:

يكتب Wu و He الأربعة كلها في معادلة واحدة. كل قيمة x_i يُوحَّد مقياسها بمتوسط وانحراف معياري محسوبين على مجموعة S_i، وأنواع الـ normalization المختلفة تستخدم ببساطة تعريفات مختلفة لهذه المجموعة:

x^i=xi−μiσi,μi=1m∑k∈Sixk,σi=1m∑k∈Si(xk−μi)2+ε\hat{x}_i = \frac{x_i - \mu_i}{\sigma_i}, \qquad \mu_i = \frac{1}{m}\sum_{k \in S_i} x_k, \qquad \sigma_i = \sqrt{\frac{1}{m}\sum_{k \in S_i}(x_k - \mu_i)^2 + \varepsilon}
Wu and He, equations 1 and 2: one rule; equations 3, 4, 5 and 7 pick the set S_i for BN, LN, IN and GNWu وHe، المعادلتان 1 و2: قاعدة واحدة؛ والمعادلات 3 و4 و5 و7 تختار المجموعة S_i لكل من BN وLN وIN وGN
The same N x C x (H, W) tensor. Batch norm fills one channel slab across every sample and pixel; layer norm outlines one sample slab across every channel and pixel.الـ tensor نفسه N x C x (H, W). الـ batch norm يملأ شريحة قناة واحدة عبر كل العينات والبكسلات؛ والـ layer norm يحدد شريحة عينة واحدة عبر كل القنوات والبكسلات.
Normalizationالـ normalizationAverages overيحسب المتوسط علىmu, sigma shapeشكل mu و sigmagamma, beta shapeشكل gamma و betaSame at train and test?متطابق في التدريب والاختبار؟
BN, fully connectedالـ BN، طبقة fully connectedNN1 x D1 x D1 x D1 x DNoلا
BN, convolution (BatchNorm2d)الـ BN، convolution (BatchNorm2d)N, H, WN, H, W1 x C x 1 x 11 x C x 1 x 11 x C x 1 x 11 x C x 1 x 1Noلا
Layer normLayer normD (or C, H, W)D (أو C, H, W)N x 1 x 1 x 1 (N x 1 on slide 35)N x 1 x 1 x 1 (N x 1 في الشريحة 35)1 x D on slide 35; 1 x C x 1 x 1 in Wu and He1 x D في الشريحة 35؛ و 1 x C x 1 x 1 عند Wu و HeYesنعم
Instance normInstance normH, WH, WN x C x 1 x 1N x C x 1 x 11 x C x 1 x 11 x C x 1 x 1Yesنعم
Group normGroup normH, W and C/G channelsH, W و C/G من القنواتN x G x 1 x 1N x G x 1 x 11 x C x 1 x 11 x C x 1 x 1Yesنعم
The normalization family on a conv activation of shape N x C x H x W (slide 35 writes layer norm on an N x D input, so D there is C x H x W)عائلة الـ normalization على تنشيط conv شكله N x C x H x W (الشريحة 35 تكتب الـ layer norm على مدخل N x D، فيكون D هناك هو C x H x W)

Two patterns in that table carry most of the marks. First, the shape of mu is the tensor shape with a 1 wherever you averaged and the full size everywhere else. Batch norm averages over N, H, W and leaves 1 x C x 1 x 1; instance norm averages over H, W only and leaves N x C x 1 x 1. Second, gamma and beta do not follow the mu shape: they are per channel for BN, IN and GN. Ioffe and Szegedy learn a pair per feature map rather than per activation, and Wu and He write that BN, LN, IN and GN all learn a per-channel linear transform, the convention the table and the explorer below use. A BatchNorm2d over 64 channels therefore holds 128 learnable values, whatever the image size.

نمطان في هذا الجدول يحملان معظم الدرجات. الأول: شكل mu هو شكل الـ tensor مع 1 في كل محور حسبت عليه المتوسط، والحجم الكامل في كل محور آخر. الـ batch norm يحسب المتوسط على N, H, W ويترك 1 x C x 1 x 1؛ والـ instance norm يحسبه على H, W فقط ويترك N x C x 1 x 1. الثاني: gamma و beta لا تتبعان شكل mu: فهما لكل قناة في BN و IN و GN. يتعلّم Ioffe و Szegedy زوجًا لكل feature map لا لكل تنشيط، ويكتب Wu و He أن BN و LN و IN و GN كلها تتعلّم تحويلًا خطيًا لكل قناة، وهو الاصطلاح الذي يستخدمه الجدول والمستكشف أدناه. لذلك فإن BatchNorm2d على 64 قناة يحمل 128 قيمة قابلة للتعلّم، أيًّا كان حجم الصورة.

SimulatorمحاكيWhich cells share one mean? An N x C x (H, W) activation tensorأي الخلايا تتشارك متوسطًا واحدًا؟ موتر تنشيطات N x C x (H, W)

C/G = 1 (G = C) is instance normC/G = 1 (G = C) هو instance norm and و C/G = C (G = 1) is layer normC/G = C (G = 1) هو layer norm

CNH, W

Only the three visible faces are drawn. Lit cells share one mean with the anchor cell (teal column). Sample index runs into the depth, channel runs along the front edge.لا تُرسم إلا الأوجه الثلاثة الظاهرة. الخلايا المضاءة تشترك في متوسط واحد مع خلية المرجع (العمود الفيروزي). يمتد رقم العينة نحو العمق، وتمتد القناة على طول الحافة الأمامية.

Averages overN, H, WBatch norm on a 4 x 6 x 6 tensor (H, W flattened)Batch norm على موتر 4 x 6 x 6 (مع تسطيح H, W)
Cells per mean24values6 separate means in the tensor6 متوسطًا منفصلًا في الموتر
mu, sigma shape1 x 6 x 1 x 11 wherever you averaged, full size elsewhere1 في كل بُعد أخذت عليه المتوسط، والحجم الكامل في غيره
gamma, beta shape1 x 6 x 1 x 1running averages replace batch statistics at testالمتوسطات الجارية تحل محل إحصاءات الدفعة عند الاختبار

Why the batch-free variants existلماذا توجد الأنواع التي لا تحتاج batch

Layer norm was introduced by Ba, Kiros and Hinton for exactly the cases where a batch is awkward. Its statistics come from all of the summed inputs to the neurons in a layer on a single training case, so it performs exactly the same computation at training and test time and is straightforward to apply to recurrent networks by computing the statistics separately at each time step. Slide 35 lists both facts. Because it never looks at another sample, it also works at batch size one, and the Transformer block in part 06 uses it in every Add and Norm step: Vaswani and colleagues define each sub-layer output as LayerNorm(x + Sublayer(x)).

قدّم Ba و Kiros و Hinton الـ layer norm للحالات التي يكون فيها الـ batch غير ملائم تحديدًا. إحصاءاته تأتي من كل المدخلات المجمّعة للعصبونات في طبقة واحدة على حالة تدريب واحدة، فيجري الحساب نفسه تمامًا في التدريب والاختبار، ويسهل تطبيقه على الشبكات التكرارية (recurrent networks) بحساب الإحصاءات منفصلة عند كل خطوة زمنية. وتذكر الشريحة 35 الحقيقتين. ولأنه لا ينظر أبدًا إلى عينة أخرى، فهو يعمل أيضًا مع batch size يساوي واحدًا، وكتلة الـ transformer في الجزء 06 تستخدمه في كل خطوة Add and Norm: إذ يعرّف Vaswani وزملاؤه مخرج كل طبقة فرعية بأنه LayerNorm(x + Sublayer(x)).

Instance norm came from style transfer. Ulyanov, Vedaldi and Lempitsky found that replacing batch norm with instance norm, applied both at training and testing, sharply improved stylization, because the per-image contrast statistics are exactly what a style transfer network needs to discard. PyTorch's InstanceNorm2d defaults to no affine parameters and no running statistics.

جاء الـ instance norm من نقل الأسلوب (style transfer). وجد Ulyanov و Vedaldi و Lempitsky أن استبدال الـ batch norm بالـ instance norm، مطبَّقًا في التدريب والاختبار معًا، حسّن الأسلبة بشكل كبير، لأن إحصاءات التباين (contrast) الخاصة بكل صورة هي بالضبط ما تحتاج شبكة نقل الأسلوب إلى التخلص منه. والـ InstanceNorm2d في PyTorch يكون افتراضيًا بلا معاملات affine وبلا إحصاءات متحركة.

Group norm is the embedded and detection story. Wu and He show that batch norm's error increases rapidly when the batch size becomes smaller: a ResNet-50 on ImageNet at batch size 2 reaches 34.7 percent error with BN and 24.1 percent with GN, while GN's computation is independent of batch size. With G = 32 as the default, GN becomes LN when G = 1 and IN when G = C, which is what the explorer's two slider ends show: one channel per group is instance norm, all channels in one group is layer norm. When you fine-tune a model on a device with a memory budget that allows one or two samples per step, a batch-free normalization is the difference between a model that trains and one that does not. Wu and He note that dropping the batch size constraint can free considerably more memory, sixteen times or more.

الـ group norm هو قصة الأنظمة المدمجة والكشف عن الأجسام (detection). يُظهر Wu و He أن خطأ الـ batch norm يزداد بسرعة حين يصغر الـ batch size: نموذج ResNet-50 على ImageNet عند batch size يساوي 2 يصل إلى خطأ 34.7 percent مع BN و 24.1 percent مع GN، بينما حساب GN مستقل عن الـ batch size. ومع G = 32 كقيمة افتراضية، يصبح GN هو LN عندما G = 1 ويصبح IN عندما G = C، وهذا ما يُظهره طرفا شريط التمرير في المستكشف: قناة واحدة لكل مجموعة هي instance norm، وكل القنوات في مجموعة واحدة هي layer norm. حين تعيد ضبط (fine-tune) نموذج على جهاز بميزانية ذاكرة تسمح بعينة أو عينتين في كل خطوة، يكون الـ normalization الذي لا يحتاج batch هو الفرق بين نموذج يتدرب ونموذج لا يتدرب. ويلاحظ Wu و He أن التخلص من قيد الـ batch size قد يحرّر ذاكرة أكثر بكثير، ستة عشر ضعفًا أو أكثر.

Recall

A conv output is 8 x 64 x 32 x 32. Give the mu shape for BN, LN, IN and GN with 32 groups, and how many values each mean averages.مخرج conv شكله 8 x 64 x 32 x 32. أعطِ شكل mu لكل من BN و LN و IN و GN بـ 32 مجموعة، وعدد القيم التي يجمعها كل متوسط.

BN 1 x 64 x 1 x 1, 8192 values each. LN 8 x 1 x 1 x 1, 65536 values. IN 8 x 64 x 1 x 1, 1024 values. GN 8 x 32 x 1 x 1, 2048 values. gamma and beta are 1 x 64 x 1 x 1 for BN, IN and GN, and for LN too under Wu and He's per-channel convention (slide 35's 1 x D applies to an N x D input).
BN: 1 x 64 x 1 x 1، و 8192 قيمة لكل متوسط. LN: 8 x 1 x 1 x 1، و 65536 قيمة. IN: 8 x 64 x 1 x 1، و 1024 قيمة. GN: 8 x 32 x 1 x 1، و 2048 قيمة. و gamma و beta شكلهما 1 x 64 x 1 x 1 في BN و IN و GN، وفي LN أيضًا وفق اصطلاح Wu و He لكل قناة (أما 1 x D في الشريحة 35 فينطبق على مدخل N x D).

Quick checkاختبار سريع

A BatchNorm2d layer follows a convolution with 64 output channels of size 32 x 32. How many learnable parameters does it hold?طبقة BatchNorm2d تأتي بعد convolution لها 64 قناة مخرجات حجم كل منها 32 x 32. كم معاملًا قابلًا للتعلّم تحمل؟

Quick checkاختبار سريع

Which normalization gives identical outputs at training and test time and never depends on other samples in the batch?أي نوع normalization يعطي مخرجات متطابقة في التدريب والاختبار ولا يعتمد أبدًا على العينات الأخرى في الـ batch؟

Tom Yeh's batch norm worksheet runs a mini-batch of four samples with three features each passes through a linear layer, a ReLU, then batch norm. Filling in every cell is the single best preparation for the computational question on this topic, so here is every number, recomputed rather than copied from the heavily rounded original.

في ورقة عمل الـ batch norm من Tom Yeh تمر mini-batch من أربع عينات، لكل منها ثلاث خاصيات، عبر طبقة خطية، ثم ReLU، ثم batch norm. ملء كل خلية فيها هو أفضل تحضير على الإطلاق للسؤال الحسابي في هذا الموضوع، لذلك إليك كل رقم، مُعاد حسابه لا منقولًا من الأصل كثير التقريب.

The layout hides two conventions. The mini-batch is written as columns x1 = (1, 0, 2), x2 = (0, 3, 1), x3 = (3, 1, 0), x4 = (0, 1, 2) with a row of ones appended, so the red 3 x 4 "Linear Layer" block is [W | b] with W = [[1, 0, 1], [1, 1, 0], [0, 2, -1]] and b = (0, -1, 0). Likewise the "Scale and Shift" block is [diag(gamma) | beta] with gamma = (2, 3, -1) and beta = (0, 0, 1), applied to the normalized matrix with its own row of ones. The small two-column "Trainable Parameters" box (drawn as a 2 x 2 grid in the blank template) stands for the columns [gamma | beta]; for this three-feature layer it holds a 3 x 2 matrix.

يخفي التخطيط اصطلاحين. الـ mini-batch مكتوبة كأعمدة x1 = (1, 0, 2)، x2 = (0, 3, 1)، x3 = (3, 1, 0)، x4 = (0, 1, 2) مع صف من الآحاد مضاف إليها، فتكون الكتلة الحمراء 3 x 4 المسماة "Linear Layer" هي [W | b] حيث W = [[1, 0, 1], [1, 1, 0], [0, 2, -1]] و b = (0, -1, 0). وبالمثل فإن كتلة "Scale and Shift" هي [diag(gamma) | beta] حيث gamma = (2, 3, -1) و beta = (0, 0, 1)، مطبّقة على المصفوفة الموحّدة المقياس مع صف الآحاد الخاص بها. والمربع الصغير ذو العمودين "Trainable Parameters" (المرسوم كشبكة 2 x 2 في القالب الفارغ) يمثّل العمودين [gamma | beta]؛ ولهذه الطبقة ذات الخاصيات الثلاث يحمل مصفوفة 3 x 2.

Worked exampleمثال محلول

Batch norm on the slide 38 mini-batchالـ batch norm على mini-batch الشريحة 38

  1. Linear layer z = Wx + bالطبقة الخطية z = Wx + b

    Row 1 of W is (1, 0, 1) with bias 0, so for x1 it gives 1 + 2 = 3. Doing this for every row and sample: row 1 is (3, 1, 3, 2), row 2 is (0, 2, 3, 0), row 3 is (-2, 5, 2, 0).
    الصف 1 من W هو (1, 0, 1) مع bias يساوي 0، فيعطي لـ x1 القيمة 1 + 2 = 3. وبتكرار ذلك لكل صف وعينة: الصف 1 هو (3, 1, 3, 2)، والصف 2 هو (0, 2, 3, 0)، والصف 3 هو (-2, 5, 2, 0).
  2. ReLUReLU

    Only one value is negative. The -2 in row 3 becomes 0, so the batch norm input is (3, 1, 3, 2), (0, 2, 3, 0), (0, 5, 2, 0).
    قيمة واحدة فقط سالبة. الـ -2 في الصف 3 تصبح 0، فيكون مدخل الـ batch norm هو (3, 1, 3, 2)، (0, 2, 3, 0)، (0, 5, 2, 0).
  3. Batch statistics, one per feature rowإحصاءات الـ batch، واحدة لكل صف خاصية

    QuantityالكميةFeature 1الخاصية 1Feature 2الخاصية 2Feature 3الخاصية 3
    After ReLUبعد الـ ReLU3, 1, 3, 23, 1, 3, 20, 2, 3, 00, 2, 3, 00, 5, 2, 00, 5, 2, 0
    Sumالمجموع995577
    Mean (divide by N = 4)المتوسط (القسمة على N = 4)2.252.251.251.251.751.75
    Variance (biased, divide by N)التباين (متحيز، القسمة على N)0.68750.68751.68751.68754.18754.1875
    Standard deviationالانحراف المعياريabout 0.829نحو 0.829about 1.299نحو 1.299about 2.046نحو 2.046
    QuantityالكميةFeature 1الخاصية 1Feature 2الخاصية 2Feature 3الخاصية 3
    After ReLUبعد الـ ReLU3, 1, 3, 23, 1, 3, 20, 2, 3, 00, 2, 3, 00, 5, 2, 00, 5, 2, 0
    Sumالمجموع995577
    Mean (divide by N = 4)المتوسط (القسمة على N = 4)2.252.251.251.251.751.75
    Variance (biased, divide by N)التباين (متحيز، القسمة على N)0.68750.68751.68751.68754.18754.1875
    Standard deviationالانحراف المعياريabout 0.829نحو 0.829about 1.299نحو 1.299about 2.046نحو 2.046
  4. Normalizeوحّد المقياس

    Subtract the row mean, divide by the row standard deviation (with eps = 1e-5 under the root). For feature 1: (3 - 2.25) / 0.829 = 0.905, (1 - 2.25) / 0.829 = -1.508, and so on.
    اطرح متوسط الصف، واقسم على الانحراف المعياري للصف (مع eps = 1e-5 تحت الجذر). للخاصية 1: (3 - 2.25) / 0.829 = 0.905، (1 - 2.25) / 0.829 = -1.508، وهكذا.
  5. Scale and shift with gamma = (2, 3, -1), beta = (0, 0, 1)حجّم وأزح باستخدام gamma = (2, 3, -1) و beta = (0, 0, 1)

    RowالصفFeature 1الخاصية 1Feature 2الخاصية 2Feature 3الخاصية 3
    x_hatx_hat0.905, -1.508, 0.905, -0.3020.905, -1.508, 0.905, -0.302-0.962, 0.577, 1.347, -0.962-0.962, 0.577, 1.347, -0.962-0.855, 1.588, 0.122, -0.855-0.855, 1.588, 0.122, -0.855
    gamma, betagamma, beta2, 02, 03, 03, 0-1, 1-1, 1
    y = gamma x_hat + betay = gamma x_hat + beta1.81, -3.02, 1.81, -0.601.81, -3.02, 1.81, -0.60-2.89, 1.73, 4.04, -2.89-2.89, 1.73, 4.04, -2.891.86, -0.59, 0.88, 1.861.86, -0.59, 0.88, 1.86
    Mean of y (should be beta)متوسط y (يجب أن يساوي beta)000011
    Variance of y (should be gamma squared)تباين y (يجب أن يساوي gamma تربيع)449911
    RowالصفFeature 1الخاصية 1Feature 2الخاصية 2Feature 3الخاصية 3
    x_hatx_hat0.905, -1.508, 0.905, -0.3020.905, -1.508, 0.905, -0.302-0.962, 0.577, 1.347, -0.962-0.962, 0.577, 1.347, -0.962-0.855, 1.588, 0.122, -0.855-0.855, 1.588, 0.122, -0.855
    gamma, betagamma, beta2, 02, 03, 03, 0-1, 1-1, 1
    y = gamma x_hat + betay = gamma x_hat + beta1.81, -3.02, 1.81, -0.601.81, -3.02, 1.81, -0.60-2.89, 1.73, 4.04, -2.89-2.89, 1.73, 4.04, -2.891.86, -0.59, 0.88, 1.861.86, -0.59, 0.88, 1.86
    Mean of y (should be beta)متوسط y (يجب أن يساوي beta)000011
    Variance of y (should be gamma squared)تباين y (يجب أن يساوي gamma تربيع)449911
  6. Self-check in ten secondsتحقق ذاتي في عشر ثوانٍ

    Each output row has mean beta_j and variance gamma_j squared: means 0, 0, 1 and variances 4, 9, 1. If your rows do not satisfy this, the arithmetic slipped somewhere. Output values are rounded to two decimals, so treat them as approximate.
    كل صف من المخرجات متوسطه beta_j وتباينه gamma_j squared: المتوسطات 0, 0, 1 والتباينات 4, 9, 1. إن لم تحقق صفوفك ذلك، فقد انزلق الحساب في مكان ما. قيم المخرجات مقرّبة إلى منزلتين عشريتين، فاعتبرها تقريبية.
SimulatorمحاكيBatch norm step by step on the slide 38 mini-batchbatch norm خطوة بخطوة على الدفعة الصغيرة في الشريحة 38
01Linear layer z = Wx + bالطبقة الخطية z = Wx + b
Input X (features down, samples across)الإدخال X (الخصائص رأسيًا، والعينات أفقيًا)
x1x2x3x4
f11030
f20311
f32102
[W | b]
w1w2w3b
f11010
f2110-1
f302-10
z = Wx + b
x1x2x3x4
f13132
f20230
f3-2520
02ReLU before normalizationReLU قبل التطبيع
a = max(0, z), the BN inputa = max(0, z)، وهو مدخل BN
x1x2x3x4
f13132
f20230
f30520
03Batch statistics (from the four samples)إحصاءات الدفعة (من العينات الأربع)
f1f2f3
sum957
mean2.25001.25001.7500
var0.68751.68754.1875
std0.8291.2992.046
04Normalize x_hat = (x - mu) / sqrt(var + eps)التطبيع x_hat = (x - mu) / sqrt(var + eps)
x_hat
x1x2x3x4
f10.905-1.5080.905-0.302
f2-0.9620.5771.347-0.962
f3-0.8551.5880.122-0.855
05Scale and shift y = gamma x_hat + betaالتحجيم والإزاحة y = gamma x_hat + beta
gamma = (2, 3, -1), beta = (0, 0, 1)
x1x2x3x4
f11.809-3.0151.809-0.603
f2-2.8871.7324.041-2.887
f31.855-0.5880.8781.855
Same input, two modes: output for feature f1الإدخال نفسه بوضعين: الإخراج للخاصية f1
x1x2x3x4
train1.809-3.0151.809-0.603
eval4.0000.0004.0002.000

Sample x1 gives 1.81 with batch statistics and 4.00 with the running ones. A model left in train mode at deployment produces the first number and its value depends on which other samples share the batch.تعطي العينة x1 القيمة 1.81 بإحصاءات الدفعة، و4.00 بالإحصاءات الجارية. النموذج الذي يُترك في وضع التدريب عند النشر يُنتج الرقم الأول، وتتوقف قيمته على العينات الأخرى التي تشاركه الدفعة.

Fusion needs eval mode and BN directly after the linear layer (paper order). A ReLU in between blocks it.يتطلب الدمج وضع التقييم ووجود BN مباشرة بعد الطبقة الخطية (ترتيب الورقة). وجود ReLU بينهما يمنعه.

Switch the simulator to eval mode and the same four inputs produce different outputs with the simulator's placeholder running mean and variance of one (PyTorch itself starts running_mean at 0 and running_var at 1): sample 1, feature 1 gives 4.00 instead of 1.81. That gap is the slide 33 bug made visible. To reproduce the fusion table of the previous concept, switch the placement to the paper order, press "load this batch's statistics" so the running mean becomes 2.25, 1.25, 1.25 and the running variance 0.6875, 1.6875, 6.6875, then press fuse: W' and b' appear computed live, with the check that they reproduce BN(Wx + b). With the placeholder running values of one you get a different, equally valid fused layer with scales 2, 3, -1, because the fused weights depend on whatever statistics training froze.

حوّل المحاكي إلى وضع eval وستنتج المدخلات الأربعة نفسها مخرجات مختلفة مع المتوسط والتباين المتحركين المؤقتين في المحاكي اللذين يساويان واحدًا (أما PyTorch نفسه فيبدأ running_mean عند 0 و running_var عند 1): العينة 1، الخاصية 1 تعطي 4.00 بدلًا من 1.81. هذه الفجوة هي خطأ الشريحة 33 وقد صار مرئيًا. ولإعادة إنتاج جدول الدمج من المفهوم السابق، حوّل موضع الطبقة إلى ترتيب الورقة، واضغط "load this batch's statistics" فيصبح المتوسط المتحرك 2.25, 1.25, 1.25 والتباين المتحرك 0.6875, 1.6875, 6.6875، ثم اضغط fuse: يظهر W' و b' محسوبين مباشرة، مع التحقق من أنهما يعيدان إنتاج BN(Wx + b). ومع القيم المتحركة المؤقتة التي تساوي واحدًا تحصل على طبقة مدموجة مختلفة وصحيحة بالقدر نفسه بمعاملات تحجيم 2, 3, -1، لأن الأوزان المدموجة تعتمد على أي إحصاءات جمّدها التدريب.

Recall

Feature values after ReLU are (0, 2, 3, 0). Compute mu, sigma squared and x_hat with epsilon negligible.قيم خاصية بعد الـ ReLU هي (0, 2, 3, 0). احسب mu و sigma squared و x_hat مع إهمال epsilon.

mu = 5 / 4 = 1.25. Deviations (-1.25, 0.75, 1.75, -1.25), squared (1.5625, 0.5625, 3.0625, 1.5625), sum 6.75, so sigma squared = 1.6875 and sigma = 1.299. x_hat = (-0.962, 0.577, 1.347, -0.962).
mu = 5 / 4 = 1.25. الانحرافات (-1.25, 0.75, 1.75, -1.25)، ومربعاتها (1.5625, 0.5625, 3.0625, 1.5625)، ومجموعها 6.75، إذن sigma squared = 1.6875 و sigma = 1.299. و x_hat = (-0.962, 0.577, 1.347, -0.962).

Recall

Which of mu, sigma squared, gamma and beta are learned by backpropagation, and which are computed?أيٌّ من mu و sigma squared و gamma و beta يُتعلَّم بالـ backpropagation، وأيها يُحسب؟

gamma and beta are learned. mu and sigma squared are computed from the mini-batch during training and replaced by running averages at inference; no gradient step ever changes them directly.
gamma و beta تُتعلَّمان. أما mu و sigma squared فتُحسبان من الـ mini-batch أثناء التدريب وتُستبدلان بمتوسطات متحركة في الاستدلال؛ ولا تغيّرهما أي خطوة gradient مباشرة أبدًا.

Recapالخلاصة

If you remember nothing elseإن لم تتذكر شيئاً آخر فتذكّر هذا

  • Normalization exists because y = Wx is hard to optimize when inputs are off-center (a large bias is needed) or differently scaled (W entries must span very different magnitudes).وُجد الـ normalization لأن تحسين y = Wx صعب حين تكون المدخلات بعيدة عن المركز (فنحتاج bias كبيرًا) أو مختلفة المقياس (فيجب أن تمتد قيم W على مقادير متباعدة جدًا).
  • BN works per feature over the batch: mu and sigma squared have shape D, x_hat = (x - mu)/sqrt(sigma squared + eps), y = gamma x_hat + beta. gamma and beta are learned, mu and sigma are computed.يعمل الـ BN لكل feature على امتداد الـ batch: شكل mu و sigma تربيع هو D، و x_hat = (x - mu)/sqrt(sigma squared + eps)، و y = gamma x_hat + beta. الـ gamma و beta تُتعلَّم، أما mu و sigma فتُحسب.
  • gamma = sqrt(sigma squared + eps) and beta = mu recover the identity; before tanh they decide how far activations reach into the saturated tails.القيمتان gamma = sqrt(sigma squared + eps) و beta = mu تستعيدان دالة الهوية (identity)؛ وقبل tanh تحددان إلى أي مدى تصل الـ activations إلى الأطراف المشبعة (saturated tails).
  • At inference mu and sigma squared are running averages, so BN is an affine map that folds into the previous FC or conv: W' = diag(gamma/sqrt(sigma squared + eps)) W, b' = gamma (b - mu)/sqrt(sigma squared + eps) + beta, at zero test-time cost.في الاستدلال تكون mu و sigma تربيع متوسطات متحركة (running averages)، فيصبح الـ BN تحويلًا أفينيًا (affine) يُدمج في طبقة الـ FC أو الـ conv السابقة: W' = diag(gamma/sqrt(sigma squared + eps)) W و b' = gamma (b - mu)/sqrt(sigma squared + eps) + beta، دون أي تكلفة وقت الاختبار.
  • Benefits: easier training, better gradient flow, higher learning rates, robustness to initialization, regularization from batch noise. Hazard: train and eval mode behave differently.الفوائد: تدريب أسهل، وتدفق أفضل للـ gradient، ومعدلات تعلّم أعلى، ومتانة أمام الـ initialization، وتنظيم (regularization) ناتج عن ضوضاء الـ batch. الخطر: وضع التدريب ووضع التقييم (train و eval) يتصرفان بشكل مختلف.
  • BN for conv averages over N, H, W (mu is 1 x C x 1 x 1); LN over features per sample (N x 1); IN over H, W per sample and channel (N x C x 1 x 1); GN over H, W and C/G channels. gamma and beta are per channel (1 x C x 1 x 1) for BN, IN and GN; LN on an N x D input has them 1 x D on slide 35, per channel in Wu and He.الـ BN للـ conv يحسب المتوسط على N و H و W (شكل mu هو 1 x C x 1 x 1)؛ والـ LN على الـ features لكل عينة (N x 1)؛ والـ IN على H و W لكل عينة وقناة (N x C x 1 x 1)؛ والـ GN على H و W و C/G من القنوات. الـ gamma و beta لكل قناة (1 x C x 1 x 1) في BN و IN و GN؛ أما LN على مدخل N x D فشكلهما 1 x D في الشريحة 35، ولكل قناة عند Wu و He.
  • LN, IN and GN need no batch and behave the same at train and test, which is why LN runs in RNNs and transformers and GN wins at batch size 2.الـ LN و IN و GN لا تحتاج batch وتتصرف بالطريقة نفسها في التدريب والاختبار، ولهذا يُستخدم LN في الـ RNNs والـ transformers ويتفوق GN عند batch size يساوي 2.
  • Slide 38 batch: means 2.25, 1.25, 1.75; variances 0.6875, 1.6875, 4.1875; every output row has mean beta and variance gamma squared.batch الشريحة 38: المتوسطات 2.25 و 1.25 و 1.75؛ والتباينات 0.6875 و 1.6875 و 4.1875؛ وكل صف من المخرجات متوسطه beta وتباينه gamma تربيع.

Sourcesالمصادر