AI Hero Club

Transformer in Practice · Lesson 5

Marked Complete by You0 / 12

Saved in this browser only. Marking a lesson complete does not mean the project has passed verification.

Lesson Outline 9 subsections
Course Contents 12 lessons
Full course plan.
Transformer in Practice / Learning Plan ↗

LESSON 05 / 12Suggested study 120 minutes

From Residual Connections to a Complete Decoder Block

How do normalization, residual connections and a feed-forward network form a complete decoder block with checkable gradient paths?

4 Questions for This Lesson
  • Gradual calculation of population differentials LayerNom and accurate GELU feed
  • Write pre-LN forward and residual gradient for two branches
  • Diffusion of whole machine parameters by shape
  • Performed by checking the authentication block with algebra non-variable, numerical and structural
Course Project ZIP ↓

What This Lesson Builds and What It Assumes

The first four chapters already give a hyphen, embedding, location, and causally multi-headed focus. This chapter links attention to truly stackable decoder blocks. At the end of the chapter, you should be able to explain the shape, specific figures for uniformization, the gradient circuits for residues, and the number of parameters of the whole set of models, item by item. If average values, squares and arrays are calculated and guided by one function; if the multi-chain approach is described in local variations when needed. This does not prove that any deep network will be trained.

The amount agreed to be BB, the current sequence length is TT, hide width as dd, first number hh, the width of each head is dh=d/hd_h=d/h, front feed hides the width as ff. These are the positive integer numbers, and hh Integer dd block input. XX It's shape. [B,T,d][B,T,d] real; lower case below xx This indicates the length of one of the locations. dd vectors. Statistics are calculated along the final feature axis, neither over time nor over batches. All activations are in an empty schematic number.

This item freezes to pre-LN: each sub layer is first recalculated and then returned to the original input. There are two separate LayerNom units for each block, with a non-selective and biased linear Q/K/V/O map for attention. The precise GELU is activated, and the single stabilization constant is fixed. ε=10−5\varepsilon=10^{-5}. This chapter schilling dropout is zero, so the function is determined in a forward direction; with dropout on, constant equivalence against values should be fixed randomly or under evaluation mode.

Position-Wise LayerNorm: Mean, Population Variance, and Stability Constant

Definitions μ\mu For all of that position dd Arithmetic average of individual characteristics; defining centralised coordinates ci=xi−μc_i=x_i-\mu; defining population patterns variance vv To centralize squares and divide them by dd. This is not a statistical task to estimate an unknown overall variance from the sample, so it is not divided d−1d-1 is modified without prejudice. r=v+εr=\sqrt{v+\varepsilon}, standardize the value zi=ci/rz_i=c_i/r 。

μ=1d∑i=1dxi,ci=xi−μ,v=1d∑i=1dci2,zi=civ+ε,LN⁡(x)i=γizi+βi.\mu=\frac1d\sum_{i=1}^{d}x_i,\quad c_i=x_i-\mu,\quad v=\frac1d\sum_{i=1}^{d}c_i^2,\quad z_i=\frac{c_i}{\sqrt{v+\varepsilon}},\quad \operatorname{LN}(x)_i=\gamma_i z_i+\beta_i.
Definition: For each set of LayerNom there is a separate length d scaling parameter gamma and a deviation parameter beta.

Parameters γi\gamma_i and βi\beta_i It is the training-by-characterization scaling and deflection, with the default starting values of one and zero, respectively; the same set of parameters is shared in all batches and locations, but the statistical values are recalculated at each location. They do not press each position into the same vector, but they adjust the standardized coordinates. γ=1,β=0\gamma=1,\beta=0, the average of the results of the reclassification is zero because of the centralization coordinates and zero; its population variance is zero v/(v+ε)v/(v+\varepsilon) Not the strict one.

The final conclusion can be directly inserted into the verification: standardized squares and divides dd is equal to the original centralised squares and divided by d(v+ε)d(v+\varepsilon) The molecules are right. vv ♪ When... vv It's close to one when it's much larger than a stable constant; v=0v=0 , which is zero. Here comes the conditional value close, which cannot be reduced to a permanent unit variance. The average value of zero is no longer necessary after the analog parameter is not the default.

The peer check is an independent algebra test: one constant for all features aa, add the new mean aa, so the centralised coordinates remain the same, the differences are the same, and the output is the same. The positive scale does not replicate this conclusion: xx Multiply s>0s>0, the denominator becomes s2v+ε\sqrt{s^2v+\varepsilon}, the fixed stabilization constant has not been scaled down accordingly, so it is usually only approximate. If the entire length is consolidated over time, the future hyphen will enter the statistics, undermining the causal contract of the project.

Building a Block from Two Residual Branches

Remember. AA It keeps the input for a multi-purpose map of causes and consequences, as defined in the previous chapter. [B,T,d][B,T,d] shapes;keeping FF This is a pre-map for the next definition. The following two indicators indicate that the parameter of independent uniformization is not repeated for the same output. The first step is to generate an increment of attention by using the original input and to get an intermediate state. UU; second step based on UU Pre-generation feed increment, again UU Added to get block output YY 。

U=X+A(LN⁡1(X)),Y=U+F(LN⁡2(U)).U=X+A(\operatorname{LN}_1(X)),\qquad Y=U+F(\operatorname{LN}_2(U)).
Precise pre-LN to be agreed; this chapter dropout=0.

This order must be implemented on a case-by-case basis. The second one is read in the same way as the one that has been added to the increase of attention. UU Not at first. XX; otherwise you're making another calculation. The two ends must be the same shape and cannot rely on radio to make a mistake. [B,1,d][B,1,d] Increment is copied to the full. Attention is responsible for exchanging information between legitimate past positions, while the previous feed deals with the characteristics of each location separately and the weights are shared over time.

For the definition of pre-dips, a mathematical vector agreement is used to: W1W_1 Shape As [d,f][d,f] , b1b_1 Yes. [f][f] , W2W_2 Yes. [f,d][f,d] , b2b_2 Yes. [d][d]. Count first. a=xW1+b1a=xW_1+b_1, non-linear by coordinates, then multiplied W2W_2 Back to Width dd. The actual PyTorch Linear storage matrix is the output width in front of the output, so the call times its conversion; the mathematical matrix cannot be confused with the stored shape.

F(x)=g(xW1+b1)W2+b2,g(a)=aΦ(a),Φ(a)=12[1+erf⁡ ⁣(a2)].F(x)=g(xW_1+b_1)W_2+b_2,\qquad g(a)=a\Phi(a),\qquad \Phi(a)=\frac12\left[1+\operatorname{erf}\!\left(\frac a{\sqrt2}\right)\right].
Definitions: GELU executes by element; is a standard normal cumulative distribution function and erf is an error function.

Here import the error function as a special function provided by the standard library, defined as the equivalent erf⁡(u)=2∫0ue−s2 ds/π\operatorname{erf}(u)=2\int_0^u e^{-s^2}\,ds/\sqrt\pi So... Φ\Phi It is the probability that the sum will be in its current position, not a random coin toss; there is no sampling of the exact GELU forward. Negative input usually gets a small negative output, rather than a direct zero change like ReLU. If there is no non-linear layer between the two layers, the matrix multiplier can be merged into a layer of analogue map, and the extension repression does not increase the non-linear expression of this function.

Example 1: A Feed-forward Residual with a Nonzero Contribution

Take a position. d=f=2d=f=2, Enter x=(1,3)x=(1,3), both of which are the default values. In order to separate the pre-dips and project zero attention output, there is zero concentration increase. u=xu=x. Preset W1W_1 as a matrix of units, W2W_2 This is an example of a mechanism, not a recommendation to project zero when training is conducted.

The second set of homogenizations is calculated: the average is two, the centre is negative one and one, and the population is one. a=1/1.00001a=1/\sqrt{1.00001} Got it. z=(−a,a)z=(-a,a) of which a≈0.999995a\approx0.999995. Using standard normal symmetry, Φ(−a)=1−Φ(a)\Phi(-a)=1-\Phi(a);in values g(−a)≈−0.1586557g(-a)\approx-0.1586557 , g(a)≈0.8413393g(a)\approx0.8413393. Right multiplied by half of the unit matrix, with an increase of approximately (−0.0793278,0.4206696)(-0.0793278,0.4206696);back input, block output approximately (0.9206722,3.4206696)(0.9206722,3.4206696) 。

The output does not require an overall average value of zero, because reclassification takes place only at the branch entrance and the main road is kept in its original scale. g(a)−g(−a)=ag(a)-g(-a)=a, so the second coordinates of the increment minus the first coordinates should be the right one. a/2a/2; the value is about 0:49,99975. This constant equal is a different check path from the direct error function, where the positive value is still at GELU and the negative value is cut to zero; however, if the whole function is replaced by ReLU, it will still be able to do so, and a specific value must be checked.

Example 2: Failure Controls for Variance, Position, and Stability

Still one or three vectors, if you miswrite the dichotomy d−1d-1, with a two-point margin, standardization becomes negative at about 0:071 and positive at 0771. The shape is exactly right, but the values are about 30%; subsequent activations and residues will change. The correct difference should be one from “Square and di divided feature two”, which is not judged successful by the symmetrical appearance of the output. Symmetry can only check part of the error and cannot recognize the error in the denominator.

Retrieval Constant Vector (2,2)(2,2). The average value is two, the variance is zero; both coordinates are standardized when maintaining a stabilization constant are zero and the output equals β\beta. If the stable constant is deleted, the denominator is zero, and the formula is not defined; this is not a negligible small rounding error. Any common equalisation of the constant vector should still be given the same output. The code calculates the correct realization, the error denominator and the zero variant boundary, so that one success does not obscure the other two types of malfunctions.

Standalone ProgramIndependent standard library validation: forward feed values, GELU symmetry, shift constantness and zero-variable boundary.
import math
EPS = 1e-5
def layer_norm(x, eps=EPS, sample_variance=False):
    mean = sum(x) / len(x)
    divisor = len(x)-1 if sample_variance else len(x)
    variance = sum((v-mean)**2 for v in x) / divisor
    return [(v-mean)/math.sqrt(variance+eps) for v in x]
def gelu(x):
    return 0.5*x*(1+math.erf(x/math.sqrt(2)))
z = layer_norm([1.0, 3.0])
y = [x+0.5*gelu(v) for x,v in zip([1.0,3.0],z)]
assert abs((gelu(z[1])-gelu(z[0]))-z[1]) < 1e-12
assert layer_norm([2.0,2.0]) == [0.0,0.0]
shifted = layer_norm([11.0,13.0])
assert max(abs(a-b) for a,b in zip(z,shifted)) < 1e-12
expected_var = 1.0/(1.0+EPS)
assert abs(sum(v*v for v in z)/2-expected_var) < 1e-12
print('preLN residual', y)
print('wrong denominator', layer_norm([1.0,3.0],sample_variance=True))
try:
    layer_norm([2.0,2.0],eps=0.0)
except ZeroDivisionError:
    print('expected failure: zero variance without eps')

Residual Connections Provide a Direct Gradient Path Without Guaranteeing Learning

Equating a position or entire length to a column vector, only for discussion of the guide. Write for any debris sublayer y=x+R(x)y=x+R(x) of which RR is a de minimis function; JRJ_R Number of i,ji,j Item is output RiR_i Enter xjx_j . The bias. xix_i Yeah. xjx_j , the guide is the corresponding item of the unit matrix. Jy=I+JRJ_y=I+J_R. This constant item doesn't need to be regularized, focused and activated through the branch.

∇xℓ=(I+JR)T∇yℓ=∇yℓ+JRT∇yℓ.\nabla_x\ell=(I+J_R)^{\mathsf T}\nabla_y\ell=\nabla_y\ell+J_R^{\mathsf T}\nabla_y\ell.
Accurate chain rule: l Mark losses, gradients are recorded by column vector, and the T caption indicates conversion.

The first is the gradient that returns directly from the main road of the debris, and the second comes from the branch. They add up instead of opting for a reservation, so they can offset each other. R(x)=−xR(x)=-x, which is negative, with a constant zero output and a total of zero. So “There's always a way.” is the exact structure and “The gradient never disappears.” is not rolled out by it. Multiple sublayers are stacked with their respective accompaniment matrices, and single layer additions cannot be mistaken as an entire net gradient.

If Post-LN is used, the form becomes y=LN⁡(x+R(x))y=\operatorname{LN}(x+R(x)), the guide is a unicoded range. (I+JR)(I+J_R) This algebraic difference suggests that the two structures are different and do not necessarily constitute a better theorizing pre-LN under an arbitrary task. When all branches of this project are set aside for zero, the pre-LN block should be kept strictly in the input; if the code still exports a standardized vector, it is likely to move the unit back to the addup. The final LayerNom at the end of the model is another layer and does not belong to the constant test.

Shapes and Parameters: Counting Every Learnable Scalar

Another shape exercise: if the batch is two, three, four, two, eight, and the front bow is two times three times four; the search key is two times two times two times three times two; the attention weight is two times two times two times three times three; and then two times three times four is returned to two times three after the project. The first feed is two times three times eight, and the second linear layer is restored two times three times four. Any step of an accidental exchange of lengths and feature axes may be exposed only when they are not equal, so the test is that three and four are deliberately used.

The parameter ledger must also be separated from the active account. When the sequence becomes longer, the current activation and attention matrix grows, but the linear layer matrix does not grow with the unicoded parameters; rather, expanding the available table of positions increases the registered parameters, even if only one word is entered this time. Depending on whether the parameter is eligible for a gradient, then whether the batch gradient is not zero, and finally whether the optimizer actually holds them, there are three different questions. The latter two chapters will be tested separately and cannot skip because the total numbers match.

The four images of attention are all. d2d^2 weights per unit, total 4d24d^2; wrap Q/K/V into one [3d,d][3d,d] The storage matrix does not change the quantity. df+fd=2dfdf+fd=2df, the two-sided is f+df+d. Two lengths for each unit dd , two sets of 4d4d. Add each piece 4d2+2df+f+5d4d^2+2df+f+5d. The header only changes the delineation of these widths, fixed dd The total number of parameters will not be changed when the structure remains unchanged.

ObjectMathematical input & outputPyTorch storage/parameters
Q/K/V/O Projection[...,d]→[...,d][d,d] each, no bias; total 4d2
FF First level[...,d]→[...,f]weight [f,d],bias [f]
GELU[...,f]→[...,f]Zero learning parameters
FF 2nd floor[...,f]→[...,d]weight [d,f],bias [d]
Two, LayerNom.[...,d]→[...,d]gamma [d], beta [d]; total 4d
Impairment additionTwo [B,T,d] [B,T,d]Zero learning parameters
The mathematical right multiplied matrix corresponds to the frame storage transfer; active memory is not counted in parameters.

In order to extend the account book to the entire Chapter 7 machine, another word-size is defined. VV Maximum number of locations CC Number of blocks NN. The word embedded and the output of unstrapped weights VdVd, learning absolute position embedded in CdCd And eventually it's down to the same thing. 2d2d. The current actual input length TT Do not change the number of parameters in the registered list, only T≤CT\le C. The parameters are not shared among each other; if the same object is mistakenly returned, the number of parameters will be small.

P=2Vd+Cd+N(4d2+2df+f+5d)+2d.P=2Vd+Cd+N(4d^2+2df+f+5d)+2d.
Accurate parameter book: has no right to re-strengthen, to export headless bias, and each block is as above.

Take V=32,C=64,N=2,d=64,h=4,f=256V=32,C=64,N=2,d=64,h=4,f=256 The four pieces are projected at 16,384, with a pre-granting weight of 32,768 and a pre-release preference of 320, which is two,566 and a total of 49,728 and 56. Two,994,456; the word is embedded in the head with a head of 40,966 and the position is 4,966, the position of the final LN 128, for a total of 10,777,766. This figure is an accurate calculation of the configuration, not a visible byte, nor does it include the state of the optimifier.

Standalone ProgramThe total number of independent parameters is recalculated; counting with the shape table item by item constitutes category II inspection.
def parameter_count(V,C,N,d,f):
    per_block = 4*d*d + 2*d*f + (f+d) + 4*d
    return 2*V*d + C*d + N*per_block + 2*d
assert parameter_count(32,64,2,64,256) == 107776
assert parameter_count(10,6,2,4,8) == 424
print(parameter_count(32,64,2,64,256))

Project Contributions and Later Dependencies

The present chapter reads: hero_transformer/model.py Add two sets of homogenization, one by one. FFN with pre- LN Fragmentation blocks, using the pre-brand causality focus as a certified submodule access. The submission should show that the input output is identical, the two branches are zero-time-long, etc., that changing the future dictional characters does not affect past output, and that the parameter books are consistent with the registered parameters four results. The causality check moves from the attention layer to the block as a whole, to prevent the error of the single axis or a prior feedback action over time from being re-introverted.

Run in the Project DirectoryProject inspection: Need to achieve hero_transformer and PyTorch; cannot run as a separate segment of the standard library.
from hero_transformer.model import Config, TransformerLM
cfg = Config(vocab_size=32,block_size=64,d_model=64,n_heads=4,
             n_layers=2,d_ff=256,dropout=0.0)
model = TransformerLM(cfg)
actual = sum(p.numel() for p in model.parameters())
assert actual == 107776, actual
print('registered parameters', actual)

Chapter VI will be pushed back along the same calculation chart in this chapter to the gradients of LayerNom, GELU, linear layers and residues, so that the axes, stabilization constants and activation agreements cannot be replaced temporarily. Chapter VII repeats calls for multiple non-shared blocks, joins finalLN and head, with full logits and losses. The forward and parameter checks do not indicate that each parameter is connected to the gradient; that is the different nature of the latter two chapters that need to continue to be validated.

TRY IT YOURSELF

Practice one basic: full account for a small configuration

Sets V=10, C=6, N=2, d=4, h=2, f=8, other structures. Calculates the number of parameters per block and whole machine; changes h to one, will the quantity change?

Hint 1
The unit is assembled after the separate numbers of Q/K/V/O, FFN weights and deviations, and the two units are consolidated.
Hint 2
When the total widthd remains unchanged, changes in headlines only divide dimensions; words embedded, position sheets and eventually re-allocated are omitted.
Compare with the Solution
Four Projection As 4×16 = 64; the first two weights are: 2×4 × 8=64;the pre-supposition is 8+4 = 12;two sets are unified to 4×4 = 16. So each piece 156 Two. 312. Word embedded with head 2×10 × 4=80, the position sheet 6×4 = 24 Finally, it's down to the homogeneity. 8 All right, set it up. 80+24+312+8 = 424. h From II to I, the total width remains unchanged. 424; the width of each head is two to four and the behaviour of the focus calculation can be changed and the same model cannot be considered because of the same number of parameters.

TRY IT YOURSELF

Practice two-bit reasoning: A constant check equation for GELU

Without checking the value table, using standard normal density for zero symmetry, rolls g(a) - g(-a) =a. Explain why this check does not detect all GELU errors.

Hint 1
The relationship between (a) and (a) is first written by the normal density symmetry.
Hint 2
Inserts g(−a) and subtracts; finding another function also meets the same constant equation to determine the adequacy of the check.
Compare with the Solution
Density symmetrical and totals one, so (-a)= 1 -By definition (a). g(-a) =(-a)Φ(-a)=- a+a (a); so g(a) - g(-a) =aΦ(a)- [-a+aΦ(a)] =a. All the limited numbers a were created. But the erroneous writing of g as ReLU was also satisfied ReLU(a) - ReLU(-a) =a, so the constant equation is only necessary, not sufficient. a=1 or a =- 1 The contract is defined by the error function 0.84134 Or-- 0.15866, so that you can distinguish between the two functions.

TRY IT YOURSELF

Practice three-poll diagnostics: The constant is not the same as the constant model.

Forces zero output per concentration and FFN output, and the block test is passed. But the complete model output is still different from the input embedded, does there have to be bugs? List two types of malfunction that must be checked separately.

Hint 1
The comparative boundary of the zero-branch test is individual Block, and what are the location-by-position variations of the complete model?
Hint 2
Checks the parameters register books and future disturbances separately; they list problems that are not the same as a single item.
Compare with the Solution
Not necessarily. Keeps its input at this point, but the whole machine still contains position embedded, ultimately LayerNom and head that maps hidden width to the size of the vocabulary; eventually logits are not embedded. Tests should compare the same size at a single boundary. Check: first, whether the number of actually registered parameters is in the ledger to find shared blocks, missing registrations or unexpected bias; and second, whether past position output after disturbing future characters should be kept to detect errors in the mix of fruit mask, homogenization axes or sequence. These properties are independent of the zero branch logic and cannot be replaced by a PASS.

BUILD THE MECHANISM

Connect pre-LN debris

The same Starter.py achieves TransformerBlock.forward by calling the last step of student attention. This chapter only takes normal whole-section input; cache parameters are already in the scaffolds only to retain interfaces, and chapter 10 requires interpretation and use. Downloading this full course, running at the project root directory; editing only learner/starter.py.

Input and Output This chapter past_key_value=None 、 use_cache=False; first LN has a disability, then LN has a disability FFN ♪ The wreckage. ♪
Module configurations, parameters, dropout and meta-team returns are provided; the previous student attachment is restored only without a cache forward.

Run in the Project DirectoryStudy tasks to be completed
# TransformerBlock.forward(替换已提供类的此方法)
def forward(self, hidden, past_key_value=None, use_cache=False):
        raise NotImplementedError('block')
Hint 1

The input of each feeder is named first, distinguishing between the original Hidden and the homogenized value.

Hint 2

The Hidden after the first disability is the input for the second LN.

Hint 3

Zero branch should be constant; non-zero fixed weights count to distinguish pre/post LN 。

Independent inspection .venv/bin/python -m learner.check --stage block --output runs/learner-block.json

Migration test Change the FF width from 7 to 11 and maintain the input output width 4; explain why both residues can be added together.

Reference Implementation and Explanation
Run in the Project DirectoryReference achieved
# TransformerBlock.forward(替换已提供类的此方法)
def forward(self, hidden, past_key_value=None, use_cache=False):
        attended, present = self.attention(
            self.ln_attention(hidden), past_key_value, use_cache
        )
        hidden = hidden + attended
        hidden = hidden + self.feedforward(self.ln_feedforward(hidden))
        return hidden, present

CHECK YOUR UNDERSTANDING

Check Your Understanding

Answer first, then open the explanation to check your reasoning. These questions help reveal gaps in understanding; independent implementation and transfer require separate evaluation.

1. What is the demographic variance for standardized characteristics when the eps>0 is fixed and defaulted to mimic parameters?

Show ExplanationSquare and divided by d, molecules are primary v, the denominator is v+eps; constant input is zero.
2. Pre-LN's second residual margin should be calculated as?

Show ExplanationThe second branch must read U after the first disability has been completed; this project is being normalized at the branch entrance.
3. Fragmentation is comparable to I+J_R. What can you guarantee?

Show ExplanationR(x) =-x is the reverse case of zero overall guides; structural access is not a universal guarantee of training.
4. Fixed d with FFN width, changing only the number of valid headers h, how do the four projection parameters change?

Show ExplanationThe header is assigned total width; the four maps in this freezing structure still have d2 weights.

Manual completion records your progress; it does not certify your project.