Flash Attention derived and coded from first principles with Triton (Python) — Transcript
Full transcript
- 0:00hello guys welcome back to my Channel
- 0:02today we are going to explore flesh
- 0:03attention now we are going to fles
- 0:06explore flesh attention from first
- 0:08principle which means that not only we
- 0:09will code flesh attention we will
- 0:11actually derive it so we pretend that
- 0:13the paper flesh attention paper never
- 0:15existed and we look at the attention
- 0:17competition and we look at the problem
- 0:19it has and we try to solve it step by
- 0:21step pretending that flashh attention
- 0:22never existed this will give us a deep
- 0:25understanding of how it works and also
- 0:27we will combine Theory with practice
- 0:29practice because we will code it now in
- 0:32order to code flash attention we we will
- 0:34need to write a kernel for our GPU and
- 0:37in our specific case I will be using an
- 0:38Nvidia GPU so Auda kernel but instead of
- 0:41writing C++ code we will use Tron which
- 0:43is a a way of converting python directly
- 0:46into um Cuda uh kernels that can run
- 0:50directly on the GPU and Tron you can
- 0:52think of it as a compiler that takes in
- 0:54Python and converts it into something
- 0:56that can run on the GPU um so let's look
- 0:59at the topics for today first of all I
- 1:01will give an introduction to multi-ad
- 1:03attention because we need to look at
- 1:04what is attention and how it's computed
- 1:06and what are the problems in Computing
- 1:08this attention then we will look at
- 1:10actually the most critical part of the
- 1:12attention computation is this softmax
- 1:14and how it impacts the computation and
- 1:16uh complexity we will look at what is
- 1:18online softmax then we will explore what
- 1:21is the GPU because we are going to write
- 1:22a kernel that will run on the GPU so we
- 1:24need to understand what is the
- 1:25difference for example the CPU and the
- 1:26GPU and what is the kernel and how it
- 1:29differ from a normal program that you
- 1:31write for the CPU we will look at how
- 1:34tensors are layout in memory so row
- 1:36major layout column major out Etc
- 1:39strides um we are going to look at block
- 1:42matrix multiplication Tron software
- 1:44pipeline all the optimization that Tryon
- 1:46does to our code finally we will be able
- 1:48to code the flash attention forward pass
- 1:51but of course we are not satisfied only
- 1:53by coding the forward pass we also want
- 1:54to code the backward pass but in order
- 1:57to code the backward pass we also need
- 1:58to understand how out works and the
- 2:01gradient descent works in the case of
- 2:03custom operations so we need to
- 2:05understand what are derivatives what are
- 2:07gradients what are jauan and then we
- 2:08calculate the gradient of the common
- 2:10operations that we use in Flash
- 2:12attention and finally we will have
- 2:14enough knowledge to code the backward
- 2:15pass for this reason this video is going
- 2:17to be super long but I hope you don't
- 2:20mind because we are going to learn a lot
- 2:22of course you may be wondering all of
- 2:24this requires a lot of knowledge that
- 2:26you may not have but that's not a
- 2:28problem because that's my problem
- 2:29because in this video I will make sure
- 2:31that if you only have high school
- 2:32calculus so you know what are
- 2:33derivatives you have basics of linear
- 2:36algebra like you know what is matrix
- 2:37multiplication or what is the transpose
- 2:39of a matrix and you have a basic
- 2:41knowledge of attention mechanism so like
- 2:43for example you have watched my previous
- 2:44video on the uh attention is all you
- 2:46need paper and you have a lot of patient
- 2:48that should be enough to understand all
- 2:51of this video because all the topics
- 2:53that I will introduce I will always
- 2:54introduce them in such a way that I um
- 2:57pretend that you don't know anything
- 2:58about that topic so so we try to derive
- 3:00everything from first principle
- 3:02everything from scratch okay now that we
- 3:04have seen the introduction let's go see
- 3:07the first part of the video which is the
- 3:09multihead attention all right let's talk
- 3:12about multi-head attention now I am
- 3:14using the slides from my previous video
- 3:16attention is all you need so uh we can
- 3:18look at very fast at what multi-head
- 3:20attention is and how it works I hope you
- 3:23remember the formula soft Max of the
- 3:25query multiplied by the transpose of the
- 3:26key divide by DK all multiplied by V
- 3:29because we will be using that a lot
- 3:31throughout the video now multi-ad
- 3:33attention starts from an input sequence
- 3:35or two input sequence in case we are
- 3:37talking about cross attention in the
- 3:39simple case of self attention we have
- 3:41one input sequence which is a sequence
- 3:43of in the case of language Model A
- 3:45sequence of tokens where we have sec
- 3:48number of tokens and each token is
- 3:51represented by an embedding so a vector
- 3:54with the model Dimensions the first
- 3:57thing that we do is we um convert this
- 4:00uh input sequence into query key and
- 4:02values through three linear projections
- 4:06one called WQ one called WK one called
- 4:09WV which in pytorch are represented
- 4:12through linear layers and these linear
- 4:14layers are of D model by D model so they
- 4:17do not change the shape of the input
- 4:19tensor and
- 4:22the after we do this job of projecting
- 4:26them they become three different
- 4:28sequences one called qu one called key
- 4:30and one called value so here I'm calling
- 4:32them Q Prime K Prime and V Prime then we
- 4:37divide them into smaller embeddings so
- 4:40each of this token which is made up of
- 4:43the model Dimensions we divide it into
- 4:45smaller tokens each one suppose we have
- 4:49four heads each one will have the model
- 4:52divided by four dimensions so this one
- 4:55is a sequence of tokens where each token
- 4:58is not the entire token but a part of
- 5:00the embedding of each token and this one
- 5:02is a another part of the embedding of
- 5:04the tokens and this one is another part
- 5:06of the embedding of the token Etc and we
- 5:08do this job for the query key and value
- 5:11sequence then we compute the attention
- 5:14as follows so the soft Marx of the query
- 5:16multiplied by the transpose of the key
- 5:18divide by the um the square root of DK
- 5:21where DK is the dimension of each head
- 5:24so how many dimensions each head is
- 5:27working with and then we do the
- 5:29multiplication with v and this will give
- 5:31us the output of the attention mechanism
- 5:34for each head and this job is done
- 5:36independently for each head this should
- 5:39be clear to you if it's not please watch
- 5:41my previous video on the attention
- 5:43mechanism because we will be working
- 5:45with this uh scenario a
- 5:48lot now uh then we take this o this uh
- 5:52the output of each head and then we
- 5:54concatenate it back in order to get the
- 5:58representation of each token uh as a
- 6:02full embedding so before we split this
- 6:04embedding into smaller embeddings this
- 6:07one here it's called the q1 Q2 Q3 Q4
- 6:10then after we compute the attention we
- 6:12get back um the output of each head and
- 6:15we concut it together to get back the
- 6:17full embedding Dimension which is this
- 6:19edge here we run it through another
- 6:21linear projection called wo which will
- 6:23be the output of the multi head
- 6:25attention now flesh attention is not
- 6:28concerned with all of these operations
- 6:30actually flesh attention is only
- 6:32concerned with the operation that
- 6:34require uh optimization and the
- 6:36operations that require optimizations
- 6:38are this one so the soft Marx of the
- 6:40query multiplied by the transpose of the
- 6:42key divide by the square root of DK
- 6:43multiplied by V which means that the
- 6:47projection of the input sequence through
- 6:48WQ WK and WV is not something that
- 6:51flashh attention is concerned about
- 6:53because that's a matrix multiplication
- 6:55so when you use a linear layer it's just
- 6:58a matrix multiplication of the inut with
- 7:00the weight Matrix of the linear layer
- 7:02and this kind of operation so the matrix
- 7:05multiplication is one of the most um
- 7:07optimized operation that we have in the
- 7:10GPU because the manufacturer of the GPU
- 7:12usually also releases um the necessary
- 7:15library for computing the the the metrix
- 7:18multiplication so actually these are
- 7:20quite fast and they do not require any
- 7:21optimization so flesh attention will
- 7:24pretend that the query is has already
- 7:26been passed through by WQ and the key
- 7:29has already passed through WK and the V
- 7:31has already passed from WB moreover
- 7:34flash attention will not be concerned
- 7:36with the projection with wo because
- 7:38that's also a matrix multiplication
- 7:40because the wo is always represented in
- 7:42byor as a linear layer so it's a matrix
- 7:44multiplication and matrix multiplication
- 7:47as we have seen are very um optimized so
- 7:50there is nothing to optimize there uh
- 7:53but what we need to optimize in terms of
- 7:55speed is this operation here soft marks
- 7:57of the query multiply by transpose of
- 7:59the keys by the square root of DK
- 8:00multiplied by V all right guys so now we
- 8:04have rehearsed what is multi head
- 8:05attention I also want to give you a lot
- 8:07of visualization which is
- 8:10basically here in the paper of the multi
- 8:13head attention we can see that we have
- 8:15the input that is uh v um K and Q so q k
- 8:20and V each of them runs through a linear
- 8:23layer which is the WQ WK and
- 8:26WV um then we do the scale dot product
- 8:30attention which is done independently
- 8:32for each head so each head will do query
- 8:34multipli by the transpose of the key
- 8:36divide by the square root of DEC where
- 8:38each query and each key is not the full
- 8:41embedding of each token but a part of
- 8:43the embedding of the token because we
- 8:44split them into smaller embeddings and
- 8:47eventually we take all the output of
- 8:49each of these head which are computed in
- 8:51parallel so that's why you see this
- 8:52Dimension Edge in the depth we
- 8:55concatenate them and then we run them
- 8:56through
- 8:57wo uh what are we we concerned with we
- 9:00are concerned with optimizing this
- 9:01particular block here the scaled do
- 9:03product attention so let's start our
- 9:06journey one thing that is very important
- 9:09to understand is why do we even need a
- 9:12better implementation of the attention
- 9:14mechanism and if you look at the flashh
- 9:16attention paper you will notice The
- 9:18Following part this is the paper flashh
- 9:20attention one and in the flashh
- 9:22attention one paper they describe the
- 9:24attention Implement imple implementation
- 9:26as it's done naively when using pytorch
- 9:29so first we do the multiplication of the
- 9:31query multiplied by the transpose of the
- 9:34keys then we apply the softmax to the
- 9:36output of this operation and finally we
- 9:38multiply the output of the softmax with
- 9:40the V Matrix to obtain the output of the
- 9:43attention the way this implementation is
- 9:45done by pytorch without any optimization
- 9:49is as follows so we load the first of
- 9:52all these tensors are residing in the
- 9:56GPU the GPU is made up of two main
- 9:59memories one is called the hbm which is
- 10:02the dram which is the the the ram of the
- 10:05GPU which is the 40 GB of the a100 for
- 10:09example so it's the biggest memory that
- 10:11we have in the GPU and then uh there are
- 10:15there is the shared memory so the
- 10:19problem of the GPU is that accessing
- 10:21this hbm so the global it's also called
- 10:24the global memory it's very very slow
- 10:26compared to the shared memory however
- 10:28the shared memory it's much much much
- 10:29smaller compared to the hbm and what
- 10:32they claim in the flesh attention paper
- 10:34is that the operation of the attention
- 10:36is IO bound meaning that if we keep
- 10:39accessing the um the um Global memory
- 10:44the overall uh operation of computing
- 10:47the attention is not because Computing
- 10:50all these operations it's slow but
- 10:51because we keep accessing the global
- 10:53memory which is slow so we call these
- 10:56kind of operations iob bound so the only
- 10:59way to improve this situation is to
- 11:02compute the attention inside the shared
- 11:04memory of the GPU which is much smaller
- 11:08which is much closer to the cores that
- 11:10actually do the computation so we we
- 11:12will need to kind of also split the
- 11:14attention computation into smaller
- 11:16blocks that can reside in the shared
- 11:19memory and we will see later in how this
- 11:23is possible through block matrix
- 11:24multiplication and this is in the paper
- 11:27here they call it the tiling and it's a
- 11:29very um uh how to say use the technique
- 11:32when doing um when writing kernels for
- 11:35the GPU uh which are usually involve
- 11:38some kind of metrix multiplication so
- 11:42now we know what problem the flashh
- 11:44attention is trying to solve it's trying
- 11:45to make sure that we do not need to
- 11:48access the hbm so the high bandwidth
- 11:50memory when Computing the uh attention
- 11:53but copying only a part of each Matrix
- 11:57inside the local memory so the sh shared
- 11:59memory of the GPU that is closer to the
- 12:02course and Computing a part of the
- 12:06output Matrix there then copying that
- 12:08part to the output in that is residing
- 12:11in the hbm and keep doing it for all the
- 12:13blocks in which we can divide these
- 12:15query key and value matrices and later
- 12:18we will see how this blocked computation
- 12:21is done but also we will see that the
- 12:23biggest problem in Computing this
- 12:25blocked computation is the softmax
- 12:27because the softmax needs to access
- 12:29all the row of the S Matrix to apply the
- 12:33soft Max
- 12:35because uh the the soft Max needs to
- 12:38have a normalization factor which is the
- 12:40sum of all the exponentials of all the
- 12:43values to which it is applied rowwise
- 12:45and we will see later how we will solve
- 12:47this problem so let's move
- 12:50on all right guys um okay when I say
- 12:53guys I mean guys and girls because I
- 12:55don't know in my usually I just say guys
- 12:58to you know but please girls don't feel
- 13:01excluded so we saw that FL fall flashh
- 13:04attention is only concerned in
- 13:06optimizing this soft Max of the
- 13:09transpose of soft Max of the query
- 13:11multip by three divide by the square
- 13:13root of DK multiplied by V and we need
- 13:16to introduce a little bit of notation so
- 13:18that we don't get lost um in the future
- 13:20slides first of all this is the formulas
- 13:23I took from the flashh attention paper
- 13:25but for now we Let's Pretend flashh
- 13:26attention never existed so we are trying
- 13:28to solve the the problem step by step
- 13:31now um we should treat this Q as
- 13:34something that has as the sequence that
- 13:36is the output of the input sequence that
- 13:39has already passed through WQ the K as
- 13:42something that has already passed
- 13:43through WK and v as something that has
- 13:46already passed through WV because we
- 13:48don't want to optimize the matrix
- 13:50multiplication because it's already fast
- 13:52enough another thing is let's talk about
- 13:55what are the dimensions of these
- 13:57matrices so we can then understand what
- 13:59is the the dimensions of the output of
- 14:02these operations we will see treat Q as
- 14:05a sequence of tokens with end tokens so
- 14:09n tokens where each token is D has D
- 14:13Dimension so lowercase D Dimensions why
- 14:17because usually we take the queries and
- 14:19then we split them into multiple heads
- 14:21so we have we pretend we have already
- 14:23done this splitting so we pretend we
- 14:25already took our input sequence we
- 14:27already run it through WQ and then we
- 14:28have already splited into multiple heads
- 14:31and each of these head will do the
- 14:34following operation so the the one we
- 14:37already saw and so the usual formula
- 14:40where multiply the transpose of the keys
- 14:42and each of this head will work with
- 14:44this dimensions for the query for the
- 14:47key and for the value sequence so now
- 14:50let's look at the uh the the dimensions
- 14:52of the output so the first operation
- 14:54that we will do is the query multiply by
- 14:56the transpose of the keys where the
- 14:57transpose of the keys is is a matrix
- 15:00that originally is n by D but become but
- 15:02with the transpose will be D by n so d
- 15:06by n and the result will be a matrix
- 15:09that is n byn because in a matrix
- 15:10multiplication the outer Dimensions
- 15:12become the dimension of the output
- 15:14Matrix what do we what is the next
- 15:17operation that we do we take the output
- 15:18of this operation so the query multiply
- 15:20by transpose of the keys and we run it
- 15:22through a soft Max operation and we will
- 15:23see what is the soft Max
- 15:25operation which preserves the shape of
- 15:28the input so it doesn't change the shape
- 15:30of the input Matrix it just changes the
- 15:32values of it and then we take the output
- 15:35of the softmax and we multiply it by V
- 15:38which will change the um which will uh
- 15:41change the of course the shape because
- 15:43the p Matrix is n by n so this one is n
- 15:47by n and V is um n by D so this one the
- 15:53output will be n byd the outer
- 15:55dimensions of this matrix
- 15:57multiplication now let's look at the
- 15:59details of each of these operations so
- 16:01when we do query multiply by transpose
- 16:02of the keys we will get a matrix that is
- 16:04n byn where each value in this Matrix is
- 16:08a dotproduct
- 16:09of a row of q and a column of K in
- 16:14particular the first element of this
- 16:16Matrix will be the dot product of the
- 16:18first query with the first key Vector
- 16:22the second element will be the
- 16:23dotproduct of the first query with the
- 16:25second key vector and the third element
- 16:28will be the first quy with the third key
- 16:30etc etc and the the let's say the the
- 16:34last row of this Matrix will be the dot
- 16:37product of the last query with the first
- 16:39key then the last query with the second
- 16:42key the last query with the third key
- 16:43etc etc until the last query with the
- 16:46last key um you may also notice that
- 16:49here I have written query transpose the
- 16:52key because when we um what is q1 first
- 16:56of all q1 is the first r of the query
- 17:00Matrix so little bit of um background on
- 17:04matrix multiplication so we know that
- 17:06when we do matrix multiplication each
- 17:08output element is one row of the first
- 17:11Matrix with one column of the second
- 17:12Matrix but we are doing the product of
- 17:15the first Matrix with the transpose of
- 17:17the second so it will be the do product
- 17:20of the one row of the query Matrix with
- 17:22one row of the key Matrix because we are
- 17:25doing the multiplication with key uh K
- 17:28transpose
- 17:30um when you take a vector from a matrix
- 17:34the usual notation so the in as as in
- 17:38how to say in um in in mathematics in a
- 17:41linear algebra we always pretend that a
- 17:43vector is a column Vector so we cannot
- 17:46just write Q multiplied by K because
- 17:49that would be mean uh that would mean we
- 17:51are doing the dot product of uh we are
- 17:55doing the kind of the matrix
- 17:57multiplication of one column Matrix with
- 18:00one column Matrix that is not possible
- 18:02because the shapes do not match so as a
- 18:05notation we write that we do the dot
- 18:07product of the first Matrix transpose
- 18:09which is a column Vector but we
- 18:11transpose it so it becomes a row Vector
- 18:13with the second Vector this is just
- 18:16because of notation guys so um you just
- 18:19need to pretend that this is the first
- 18:21query with the first key then the first
- 18:23query with the second key the first
- 18:24query with the third key etc etc etc so
- 18:27we are doing do of vectors then we apply
- 18:31this softmax
- 18:33operation the softmax operation what it
- 18:35will do it will transform each of these
- 18:38dot products which are scalars so the
- 18:40output of a DOT product is a scalar and
- 18:44it will transform each of these numbers
- 18:46in such a way that they become kind of a
- 18:48probability distribution rowwise which
- 18:51means that each of these numbers is
- 18:53between 0er and one and when we sum up
- 18:56these numbers together they are sum up
- 18:59to one and this condition this property
- 19:01will be valid for each row so this row
- 19:04also will sum up to one this row will
- 19:06sum up to one and this row will sum up
- 19:08to one etc etc
- 19:10etc let's see what is the softmax
- 19:12operation now uh given a vector so let's
- 19:17call it X which is made up of n
- 19:19Dimensions the softmax is defined as
- 19:22follows so it is the um the soft Max
- 19:26basically transforms this transforms
- 19:28this Vector into another Vector with the
- 19:31same Dimension where each item of the
- 19:33output Vector is calculated as follows
- 19:36so the E element of the output Vector is
- 19:39the exponential of the element input
- 19:42element divided by the summation of all
- 19:45the exponentials of all the dimensions
- 19:47of the
- 19:48vector basically this is called the
- 19:51normalization factor to make it all
- 19:53these numbers between zero and one we
- 19:55usually normalize that's why it's called
- 19:57the normalization factor and uh we use
- 20:00the soft Max because we want each of
- 20:02these numbers to be positive we don't
- 20:04want the stuff the output of this
- 20:06operation to be negative so that's why
- 20:08we use the exponential but there is a
- 20:11problem the problem is Imagine our input
- 20:13Vector is made up of many numbers that
- 20:16are maybe large so for example let's say
- 20:19X1 is equal to 100 X2 is equal to 200 X3
- 20:22is equal to 300 which is can happen um
- 20:26if we do the exponential of this number
- 20:28so the exponential of 100 that is going
- 20:31to be a huge number it's going to very
- 20:33close to Infinity uh at least compared
- 20:36to what we can store in a computer so
- 20:38the output of exponential of 100 may not
- 20:41fit into a floating Point 32 or a
- 20:43floating Point 16 number or even an
- 20:46integer of 32 bit so we cannot compute
- 20:50it because it will overflow our uh our
- 20:53variable our integer that is storing
- 20:55this value this
- 20:57output so we talk in this case about
- 21:00numerical instability so every time you
- 21:02hear the term numerical instability in
- 21:05computer science it means that the
- 21:06number cannot be represented within a
- 21:09fixed representation with the bits we
- 21:11have available which are usually 32 bit
- 21:14or 16 bit uh we have also 64bit but that
- 21:18would be too expensive to use um so
- 21:20let's try to find a solution to make
- 21:22this stuff here computable and
- 21:24numerically
- 21:25stable in order to make this soft Max
- 21:28operation numerically stable which means
- 21:31that we want these numbers to not
- 21:32explode or to become too small that they
- 21:35are not representable we need to find a
- 21:37solution and luckily it's quite easy so
- 21:40the softmax as we have seen before it is
- 21:43the following formula so each number is
- 21:45exponentiated and then we divide it by
- 21:47this normalization factor which is just
- 21:48the sum of the exponential of each input
- 21:50dimension of the input
- 21:52Vector um if we multiply the numerator
- 21:55and the denominator of a fraction with a
- 21:57constant uh with a number number then
- 21:59the fraction will not change so that's
- 22:00what we are going to do we are
- 22:01multiplying the numerator and this
- 22:02denominator with this factor C as long
- 22:06as C is not equal to zero of course uh
- 22:09then we can U take this C and by using
- 22:13the the distributive property of the
- 22:15product with respect to the sum we can
- 22:17bring this C inside of the summation as
- 22:19you can see here um then we can also
- 22:23write every number as the exponential of
- 22:25the log of itself because the
- 22:27exponential and the log will cancel out
- 22:31and um then we can by using the
- 22:34properties of the exponentials we know
- 22:35that the product of two exponential is
- 22:37equal to the sum of the is equal to the
- 22:40exponential of the sum of the arguments
- 22:42of each exponential and we do it on the
- 22:45numerator and in the denominator then we
- 22:48just call this quantity minus log c
- 22:51equal to K or k is equal to minus K is
- 22:55equal to log C so we can replace this
- 22:57quantity with k
- 22:59we can do that because this is a
- 23:01constant that we have chosen and we just
- 23:03are assigning it to another
- 23:05constant um so basically by doing this
- 23:08derivation we can see that we can sneak
- 23:11in a value inside of this exponential
- 23:14that if chosen carefully can reduce the
- 23:17argument of this exponential and we will
- 23:19choose this k equal to the maximum
- 23:22element inside of the input Vector that
- 23:24we are applying the soft Max to so that
- 23:28each this argument will be either zero
- 23:31in case x i is equal to the maximum
- 23:33element that we are processing of the
- 23:35vector or it will be less than zero and
- 23:38we know that the exponential when it's
- 23:40equal to zero will be equal to the
- 23:43output of the exponential will be one so
- 23:45the argument when it's zero it will be
- 23:46equal to one and when it's smaller than
- 23:49zero so it's in the negative range it
- 23:51will be between Z and one so which is
- 23:53easily representable with floating Point
- 23:5632 for example so this exponential will
- 23:59not explode anymore so basically to
- 24:02apply the the soft Max to a vector in a
- 24:06numerically safe way we need to find a k
- 24:10constant which is the maximum value of
- 24:12this vector and when we apply it we need
- 24:15to substract each element minus this
- 24:18constant that we have chosen so let's
- 24:20look at the algorithm to compute the
- 24:22soft Max so first of all given a vector
- 24:25or given an N byn Matrix because we want
- 24:28to apply the soft Max to this Matrix
- 24:30here which is n byn we need to go
- 24:33through each row of this Matrix and for
- 24:35each row we need to find the maximum
- 24:38value among the elements which takes
- 24:41time complexity linear with respect to
- 24:43the size of the vector to the size of
- 24:45the row to which we are applying the
- 24:47softmax then we need to compute the
- 24:49normalization factor which is this stuff
- 24:51here and we we cannot compute it before
- 24:55the step number one because we need to
- 24:57have the maximum element to compute this
- 24:59summation here and after we have
- 25:01calculated the the normalization factor
- 25:04we can then divide each elements
- 25:06exponential by the normalization factor
- 25:08and we cannot do the step number three
- 25:10before uh calculating the normalization
- 25:12factor because uh we need to divide each
- 25:15number by the normalization factor so if
- 25:17you like a pyo code for algorithms this
- 25:20is an algorithm for computing the
- 25:21softmax that we have seen right now so
- 25:24first we find the maximum of the row of
- 25:27to which we are applying the soft Max
- 25:29then we comput the normalization factor
- 25:31and then we apply the soft Max to each
- 25:33element which means that we calculate
- 25:34comput the exponential of each element
- 25:37minus the maximum value of the vector
- 25:40divided by the normalization factor now
- 25:44this pseo code is an algorithm that is
- 25:46quite slow because look at a practical
- 25:50example imagine we have this Vector here
- 25:52first we need to do step one find the
- 25:54maximum value in this Vector which is
- 25:56number five and this takes linear time
- 25:58computation then we need to calculate
- 26:00the normalization constant which is the
- 26:03sum of the exponential of each element
- 26:05minus the maximum value so e ^ of 3 - 5
- 26:09plus e to ^ of 2 - 5 etc etc and this we
- 26:13will call it l and then each we need to
- 26:16go again through this Vector again and
- 26:18take the exponential of each element
- 26:20minus the maximum divided by the uh
- 26:23normalization Factor so to apply the
- 26:26soft Max to an n byn Matrix we need to
- 26:29go through each element of this Matrix
- 26:32three times and these operations must be
- 26:34done sequentially so we cannot start
- 26:37operation two until we have done
- 26:38operation one and we cannot start
- 26:40operation three until we have done one
- 26:41and
- 26:42two so this is quite slow only to apply
- 26:47an operation that doesn't even change
- 26:49the shape of the matrix it's just uh
- 26:51normal normalizing the values so there
- 26:54must be a better way that that does not
- 26:57involve three sequential operations in
- 26:59which we need to go through this metrix
- 27:00three times let's
- 27:02see all right guys let's rehearse what
- 27:05is the problem that we are trying to
- 27:07solve the problem statement is the
- 27:09following can we find a better way to
- 27:12compute the softmax that does not
- 27:14involve going through the vector three
- 27:16times because let's look at the pseo
- 27:19code of the algorithm for computing the
- 27:20Lo the softmax that we have found so far
- 27:23imagine we have a vector made up of four
- 27:25elements the first thing that we need to
- 27:27do is to compute the maximum element in
- 27:29this Vector which means going through
- 27:32this for Loop here that allow us to
- 27:34compute the maximum element in this
- 27:36Vector which means that we start from
- 27:37the left side of the vector and
- 27:40iteratively go to the right side so we
- 27:41start from the first element arrive to
- 27:43the end and we compare the previously
- 27:46found maximum with the current element
- 27:48to find the global maximum basically
- 27:51this means that uh I I know that this is
- 27:53very simple uh I'm probably sure that
- 27:55you don't need to this example but
- 27:57making this example will help us
- 27:59understand what we will do next so
- 28:00please bear with me even if it's super
- 28:02simple what I'm doing um okay we at the
- 28:06beginning
- 28:07m0 is equal to minus infinity M1 is
- 28:12basically the for loop at the iteration
- 28:14number one which means that we are M1
- 28:17will be equal to the maximum of the
- 28:19previous estimate of the M which is
- 28:22minus infinity with the current element
- 28:25which is three so it will become equal
- 28:27to three then M2 will be equal to the
- 28:30maximum of the previously computed
- 28:32maximum so M1 so three with the current
- 28:35element which is two so it will be equal
- 28:37to three M3 will be equal to the maximum
- 28:41of the previously computed maximum so
- 28:43three with the current oops three with
- 28:46the current element which is five so it
- 28:48will be equal to five and M4 will be
- 28:50equal to the maximum of the previously
- 28:53computed maximum and the current element
- 28:55so it will be equal to five so this
- 28:57allow us to compute the maximum element
- 28:59so at the fourth iteration we will have
- 29:01the maximum the global maximum
- 29:03independently of what is the input
- 29:06array um delete okay after we have
- 29:09computed the maximum which we know is
- 29:11five we can compute the normalization
- 29:13factor so let's start with the l0 l0 is
- 29:16equal to Z L1 will be equal to the
- 29:19exponential of l0 so actually sorry it
- 29:22will be l0 plus the exponential of the
- 29:25current element so three minus the
- 29:28maximum element we have found in the
- 29:29previous for Loop so five then L2 will
- 29:33be equal to L1 plus the exponential of
- 29:36the uh the current element so it's two
- 29:39minus the maximum then L3 will be equal
- 29:43to L2 plus the exponential of um the
- 29:46current element 5 - 5 then L4 will be
- 29:49equal to the uh L3 + exponential of 1 -
- 29:555 if you expand this L this this will be
- 29:58basically equal to E power of 3 - 5 + e
- 30:03^ of 2 - 5 + e the^ of 5 - 5 + e the ^
- 30:08of 1 - 1 -
- 30:115 after we have computed this
- 30:14normalization Factor we can use it to
- 30:16normalize the each element in the input
- 30:18Vector which means that the X new X1 so
- 30:22X1 Prime let's see will be equal to e to
- 30:25the power of um uh what's the first
- 30:29element
- 30:30three - 5 divided by L that we computed
- 30:34in the previous for Loop so the L at the
- 30:37fourth
- 30:38iteration uh the new
- 30:41X2 so X2 Prime will be equal to the E
- 30:44to^ of 2 - 5 / L4 and X3 Prime will be
- 30:49equal to the E to power of 5 - 5 ided L4
- 30:54etc etc for all the
- 30:56elements uh I know this is super simple
- 30:58but it will help us later so in this for
- 31:02Loop we have that we need to go through
- 31:05the vector three TS because first we
- 31:06need to compute this for Loop then we
- 31:08need to compute this for Loop and then
- 31:10we need to compute another for Loop we
- 31:13cannot do them not in this sequence
- 31:15because in order to compute this for
- 31:16Loop we need to have the maximum element
- 31:18because we need it here and we cannot
- 31:21compute this forloop until we have
- 31:22computed the previous one because we
- 31:23need to have the normalization factor
- 31:26however we are stubborn and let's try to
- 31:29fuse these two operations into one for
- 31:31Loop which means that we go through the
- 31:33array and simultaneously compute Mi and
- 31:36simil in the same iteration we also try
- 31:38to compute LJ of course we will not be
- 31:41able to compute LJ because we don't have
- 31:43the global maximum because we didn't go
- 31:46through the all the um array yet however
- 31:49let's try to use the locally um the
- 31:52whatever estimate we have of the maximum
- 31:54so far so let's try to use instead of MN
- 31:56let's try to use m I so the local
- 31:58maximum that we have computed so far so
- 32:01if we apply the soft Max in this way in
- 32:03this fused way to this Vector we will
- 32:05have the following
- 32:07iterations um so this is our array or
- 32:11vector and the first step is MI so M1
- 32:15will be equal to the previous maximum
- 32:17which is minus infinity with the current
- 32:19element so the maximum minus infinity
- 32:21and the current element is equal to
- 32:23three and L1 will be equal to the
- 32:27previous l so l0 which is starts from
- 32:29zero plus e to the power of the current
- 32:32element minus we should be using the
- 32:34global maximum but we don't have the
- 32:36global maximum so let's use the whatever
- 32:38maximum we have so far so we can use
- 32:40three now at the second iteration we are
- 32:43at this element of the vector and we
- 32:45comput the maximum so far so the maximum
- 32:48so far is the previous maximum and the
- 32:50current element so the maximum of the
- 32:51previous maximum and the current element
- 32:53which is the maximum between three and
- 32:55two which is three uh and the the
- 32:58normalization factor is the previous
- 32:59normalization Factor plus exponential of
- 33:022 - 3 which is the current element minus
- 33:05whatever maximum we have so far now if
- 33:09our array were made only of these two
- 33:12elements so three and two then whatever
- 33:15we have computed is actually correct
- 33:17because the maximum that we have found
- 33:19is a three and it's actually the global
- 33:21maximum and the um normalization factor
- 33:24that we have computed is actually
- 33:26correct because each of the exponent
- 33:27itial has been computed with the global
- 33:29maximum because the first element was
- 33:31computed using three as the uh with the
- 33:35argument minus three and also the second
- 33:38element was computed with the argument
- 33:40with the argument having minus three in
- 33:42the in the argument which is the global
- 33:45maximum of the vector however when we
- 33:47arrive at the third iteration so let me
- 33:50delete this Vector so we arrive here at
- 33:52the third iteration the maximum will
- 33:54change which will also uh cause our
- 33:57normalization factor to get to to be
- 33:59wrong because we arrive at the element
- 34:02number three uh so the number five here
- 34:06and we computed the maximum so the
- 34:08maximum is the comparison of the
- 34:09previous maximum and the current element
- 34:12so the new maximum becomes five and the
- 34:15normalization factor is the previous
- 34:17normalization Factor so L2 plus the
- 34:19exponential of the current element minus
- 34:23the current estimate of the maximum
- 34:25which is five however
- 34:28if you look at this L3 this is wrong why
- 34:31because L3 is equal to if you expand
- 34:34this summation it will be equal to e to
- 34:36the power of 3 - 3 + e to power of 2 - 3
- 34:42+ e to the power of 5 minus 5 this
- 34:46exponential here is using five as the
- 34:49global maximum this exponential here is
- 34:51using three as the global maximum and
- 34:53this one is using three as the global
- 34:54maximum so the first two element have
- 34:56been computed
- 34:58thinking that the global maximum is
- 35:00three but actually we later we found a
- 35:02better Global maximum which is five so
- 35:04which makes this normalization Factor
- 35:06wrong however can we fix at the third
- 35:10iteration whatever normalization we have
- 35:12computed so far up to the second
- 35:14iteration actually we can because if we
- 35:18expand this so as we have here we have
- 35:21expanded
- 35:22it what we need here is here to have
- 35:25minus5 because that's actually the
- 35:27Global maximum that we have found so far
- 35:29not the minus three that we had at the
- 35:31previous iteration so and here we also
- 35:34need to fix this replace this -3 with
- 35:36minus5 how can we do that well if we
- 35:39multiply this one here and this one here
- 35:41with a correction factor that will sneak
- 35:45in a new maximum inside of this
- 35:48exponential then we solve the problem
- 35:50and actually this correction factor is
- 35:52very easy to calculate because at the
- 35:54third iteration if we multiply L2 so the
- 35:57previous prly computed normalization
- 35:59factor with this Factor here which is
- 36:00the exponential of the previous estimate
- 36:03of the maximum minus the current
- 36:05estimate of the maximum so five we will
- 36:08see that by the properties of the
- 36:12exponentials this one here will become e
- 36:14to the^ of 3 - 3 + 3 - 5 so this minus 3
- 36:18will cancel out with this three and also
- 36:21the second Factor will have this three
- 36:23will cancel out with this minus three
- 36:25will cancel out with this three and they
- 36:27will become e to ^ of 3 - 5 and 2 to the
- 36:30power of u e to the^ of 2 - 5 which is
- 36:33actually correct because at the third
- 36:35iteration we should be actually have we
- 36:38should be using minus5 as the maximum of
- 36:41the array so far um so basically what we
- 36:44have found is a way to fix whatever
- 36:48normalization Factor we have computed so
- 36:50far while iterating through the array
- 36:53when we found we when we find a better
- 36:56maximum compared to what we have so far
- 36:59and when we don't need to fix anything
- 37:01then the formula still stands because
- 37:03what we did here as a multiplic as a
- 37:06correction factor so this is the
- 37:08correction factor this correction factor
- 37:11is nothing more than the previous um
- 37:14previous maximum so the previous
- 37:16estimate of the maximum minus the
- 37:18current estimates of the maximum at the
- 37:20current iteration so the current
- 37:23Max um so this is basically M of IUS one
- 37:27and this is M of I so the current
- 37:30maximum at the current iteration and let
- 37:32me delete it otherwise it remains
- 37:34forever in my slides um so basically
- 37:38when we arrive to the last element we
- 37:40will see that the maximum doesn't change
- 37:42because we compare the previous maximum
- 37:44with the current element which is less
- 37:46than the previous maximum so the maximum
- 37:48doesn't change and we don't need to fix
- 37:51anything because the the the the
- 37:54previous L3 so the previously computed
- 37:57uh normalization factor is correct
- 37:59because they have all been using the
- 38:01minus5 so when we don't need to fix
- 38:03anything we just multiply by e to the
- 38:06power of the previous maximum minus the
- 38:08current maximum which is e to the power
- 38:10of zero in this case so it's not fixing
- 38:12anything so we have found a way to fix
- 38:16the previously computed normalization
- 38:19Factor while going through the array
- 38:21even if at the current iteration we
- 38:23don't have the global maximum yet so
- 38:26that every time the maximum changes we
- 38:28can fix and every time it doesn't change
- 38:30we just multiply with e to the^ of Z
- 38:33which is like multiplying with one so
- 38:36the new algorithm that we have found for
- 38:38the softmax is the following so we start
- 38:40with m0 equal to minus infinity we start
- 38:43with l0 equal to Z we go through the
- 38:45array we compute the locally uh the the
- 38:48local maximum so up so the maximum so
- 38:51far from the zeroth element to the E
- 38:55element so to the elements at which we
- 38:57are we are doing the
- 38:58iteration and the previously computed Li
- 39:02can be fixed by using this correction
- 39:05factor which is e to the power of the
- 39:06previous maximum minus the current
- 39:09maximum plus the exponential of the
- 39:12current element minus the current
- 39:14estimate of the maximum in this way we
- 39:17go through the array only once and we
- 39:20obtain two values the global maximum at
- 39:23at the end at the same time the uh the
- 39:26the ization factor and then we can use
- 39:29it to compute the softmax so we made
- 39:32three transformed the three passes
- 39:34through the array into two passes
- 39:37through the array and this is very
- 39:39important and we will see how we
- 39:41actually use it to derive flesh
- 39:44attention the example that I have given
- 39:46you so far is not really a proof that
- 39:49our algorithm will work in every case
- 39:51because we made a very simple example by
- 39:53using a vector made up of four elements
- 39:57but but does our new algorithm work in
- 40:00every single case with whatever the
- 40:02numbers are we need to prove that so we
- 40:05will prove that by induction so what
- 40:07first of all what are we trying to prove
- 40:10we have fused the first two for Loops
- 40:12into one for loop as you can see here
- 40:15what we expect is that at the end of
- 40:18this for Loop this MN so the m at the
- 40:22last iteration will be actually the
- 40:23global maximum in the vector and this Ln
- 40:27so the L at the last iteration will be
- 40:30equal to the sum of all the exponential
- 40:33of all the
- 40:34elements minus the maximum element of
- 40:37the vector so the global maximum of the
- 40:39vector and we need to prove that because
- 40:42what I did before was an example and
- 40:44that was not really a rigorous proof and
- 40:47the way we will prove it is by induction
- 40:49which is a typical way of proving these
- 40:51kind of um
- 40:53theorems now proof by induction
- 40:56basically Works in the following way we
- 40:58need to prove that our algorithm work
- 41:01works for a base case for example with
- 41:03Nal to 1 and then we pretend we assume
- 41:08that the algorithm work works on n and
- 41:12we need to prove that it also works for
- 41:14n + one if this holds then we have
- 41:18proven our algorithm for every possible
- 41:20n because it will work for the base case
- 41:23so for example n equal to 1 and then by
- 41:25using the induction step we say so this
- 41:29if it works for n then it also works for
- 41:31n + one then it means that it will also
- 41:33work for two but then if it works for
- 41:35two then it should also work for three
- 41:36because of the induction step that we
- 41:38will prove and if it works for three
- 41:40then it will also work for four etc etc
- 41:42up to
- 41:43Infinity so let's prove it for the base
- 41:45case which is n equal to 1 uh it's very
- 41:48simple so uh at n equal to 1 this for
- 41:52Loop will only have one iteration so M
- 41:54M1 and L1 M1 will be be the maximum of
- 41:58the previous M which is minus infinity
- 42:00because we initialize m0 equal to minus
- 42:03infinity um so it will be equal to U the
- 42:07maximum of the previous M and the
- 42:09current element which is X1 so it will
- 42:11be equal to X1 whatever X1 is uh X1
- 42:15usually will never be equal it cannot be
- 42:17equal to minus infinity um because it's
- 42:20a number in fixed representation so it
- 42:23cannot be minus infinity um so we the
- 42:26the X the M1 at the end so it will
- 42:29because we have only one element n equal
- 42:31to one this is M1 is also the last um M
- 42:37of this of this for Loop it will be
- 42:39equal to the global maximum of the
- 42:41vector made up of only one element and
- 42:43L1 will be equal to the previous L which
- 42:46we start from zero so l0 multiply by a
- 42:50correction factor which will be in this
- 42:52case e to the power of minus infinity
- 42:54because the correction factor is the
- 42:56previous estimate of the max of the max
- 42:59minus the current estimate of the max
- 43:01but the previous estimate of the max is
- 43:02minus infinity minus X1 it is equal to
- 43:05minus infinity so this one will be this
- 43:08will be canceled out and then plus e to
- 43:11the^ of X1 minus the current maximum
- 43:14which is X1 so
- 43:17M1 and if this one will be equal to the
- 43:21sum of all the elements of the vector
- 43:23which is made up of only one element
- 43:25minus uh the maximum element in the
- 43:28array which is X1 so we have proven that
- 43:31it works for n equal to 1 now we assume
- 43:35that it works for n does it also work
- 43:38for an array of vect or with a vector of
- 43:41size n + one so let's see what happens
- 43:46at the n + one iteration at the n+ one
- 43:50iteration we will be doing the maximum
- 43:52of the previous estimate of M which is
- 43:54the m at the end iteration and the
- 43:57current element so xn of + one this by
- 44:01the properties of the Max uh function it
- 44:05will be actually equal to the maximum of
- 44:07the global Vector up to n + one uh
- 44:11because um the maximum will choose
- 44:13whatever is the maximum between the
- 44:15previous estimate and the current
- 44:17estimate and Ln + one which is the
- 44:20normalization factor at the n + one
- 44:22iteration will be equal to the Ln so the
- 44:25previous estimate not previous by the
- 44:27previous normalization Factor at at the
- 44:30end iteration multiplied by the
- 44:33correction factor which is the previous
- 44:35maximum minus the current maximum plus
- 44:38the exponential of x uh the current
- 44:42element minus the current estimate of
- 44:46the
- 44:47maximum but
- 44:49Ln we have we assume that this um
- 44:53property so this algorithm works up to n
- 44:57so Ln is for sure equal to the sum of
- 45:01all the exponentials of the previous of
- 45:04the vector up to n minus the local
- 45:08maximum of the uh Vector up to the end
- 45:12element which is
- 45:14MN we multiply by the correction factor
- 45:18if there is something to correct which
- 45:20will be the previous maximum minus the
- 45:23current maximum plus the exponential of
- 45:25the current element minus the current
- 45:27exp estimate of the
- 45:29maximum now
- 45:31by the properties of the exponentials so
- 45:34we can bring this one inside of the uh
- 45:37summation and we will see that this MN
- 45:40and this MN will cancel out because it
- 45:42will be exponential of XJ minus MN + MN
- 45:46minus MN + one so this MN and this MN
- 45:49will cancel out and we obtain this one
- 45:51plus this Factor here that remains
- 45:54unchanged however you can see that this
- 45:57this stuff here is exactly the in the
- 46:00argument of this summation for the at
- 46:02the iteration n + one so it is this one
- 46:05is e to the power of XJ where J is going
- 46:09from 1 to n minus MN + 1 + e ^ of x n +
- 46:151 - MN + 1 so the J only appears here
- 46:20and it's equal maximum to n and this is
- 46:22similar to being a j with n + one so we
- 46:26can increase increase the index of this
- 46:28summation by one and it will be the same
- 46:32um and it will result in the same
- 46:34summation so we have proven that also at
- 46:37the n + one iteration we will have that
- 46:41the L will be equal to the sum of all
- 46:44the elements of the array the
- 46:46exponential of all the elements of the
- 46:48array up to the n+ one
- 46:50element uh minus the maximum up to the n
- 46:53+ one element so we have proven that if
- 46:57it works for n then it also works for n
- 46:59+ one um this is enough to prove that it
- 47:02works for all sides of
- 47:04arrays um don't worry if you didn't get
- 47:08uh the proof by induction it is uh if
- 47:10it's the first time you are seeing this
- 47:12kind of proof it may take a little bit
- 47:14to to get it um if you want to learn a
- 47:17bit more about proof by induction I
- 47:19recommend watching some other proof it's
- 47:21very simple it's just you need to get
- 47:22into the right mindset anyway let's move
- 47:25forward
- 47:28all right let's talk about block matrix
- 47:30multiplication I know that you want to
- 47:32jump to the code immediately and we will
- 47:34go there we just need a little more
- 47:36Theory actually so imagine we are doing
- 47:39a matrix multiplication so we have a
- 47:41matrix a we want to multiply it with a
- 47:44matrix B and it will produce an output
- 47:46Matrix C imagine the dimensions of the
- 47:49first Matrix are M by K the second
- 47:52Matrix is a k by n it will produce an
- 47:55output Matrix that is m by n now imagine
- 47:59we want to parallelize the computation
- 48:01of this output Matrix I know that I
- 48:03didn't talk about gpus yet so we will
- 48:06not talk about gpus we will talk about
- 48:09parallelization in the case of a
- 48:11multicore CPU with which you are very
- 48:14probably familiar with because right now
- 48:17in nowadays when you buy a computer you
- 48:19have a CPU and usually you can buy a
- 48:22single core CPU or multie like a two
- 48:24core four core eight core etc etc each
- 48:27of the these cores are actually kind of
- 48:29small CPUs inside your CPU that can
- 48:31execute operations in parallel how to
- 48:34parallelize the matrix multiplication
- 48:37imagine you have this matrix
- 48:39multiplication to parallelize each of
- 48:41the output element in this C Matrix is a
- 48:43DOT product of a row of the a matrix
- 48:47with a column of the B Matrix for
- 48:49example this element on the top left is
- 48:52the dotproduct of the first row of a and
- 48:55the First Column of B this element on
- 48:58the top right of C is the dot product of
- 49:00the first row of a and the last column
- 49:03of B this element on the bottom left is
- 49:06the dot product of the last row of a and
- 49:09the First Column of B etc etc for all
- 49:11the other elements now to parallelize
- 49:14this computation we need as many cores
- 49:16as is as there are elements in C if we
- 49:19want to parallelize it uh so if M and N
- 49:23are very small then maybe we have enough
- 49:25course but imagine M and N are quite big
- 49:29we imagine like 100 by 100 we don't have
- 49:3210,000 cores right now in the CPUs so
- 49:36how can we parallelize a matrix um
- 49:39operation by using less cores than there
- 49:42are elements in The Matrix itself that's
- 49:46when we talk about block matrix
- 49:48multiplication basically block matrix
- 49:50multiplication means that you can divide
- 49:53the original Matrix into smaller blocks
- 49:56of of elements and then the operations
- 50:00of matrix multiplication can be computed
- 50:02between these blocks for example imagine
- 50:05we have a matrix that is 8x4 it means
- 50:08that it has eight
- 50:10rows and four columns which means that
- 50:13it has 32 elements and then we are
- 50:16multiplying it with another Matrix that
- 50:19is 4X 8 so it has four rows and eight
- 50:24columns so it also has a 3 two elements
- 50:28the output Matrix will should have 64
- 50:31elements we don't have 64 cores so how
- 50:34can we parallelize it imagine we only
- 50:36have eight cores now with eight cores we
- 50:39can divide this original Matrix a into
- 50:42four blocks where the first block is
- 50:45this top left block of two by no 4X two
- 50:50elements so um uh how to say um eight
- 50:55elements on the top top left and then
- 50:58eight elements on the top right of this
- 51:00Matrix then eight elements on the bottom
- 51:02left and eight elements in the bottom
- 51:04right of this Matrix these are four
- 51:06blocks then we divide also the B Matrix
- 51:09into um eight blocks where each block is
- 51:12made up of four elements so this b11 is
- 51:17the top left four elements in the
- 51:19original Matrix this B4 is the top right
- 51:22four elements in the original Matrix
- 51:25this B21 is the
- 51:27um bottom left for elements in the
- 51:29origin etc etc etc how do we do this
- 51:33block matrix multiplication we can watch
- 51:35these matrices as made only by their
- 51:39blocks so we can view this Matrix here
- 51:41as made up only by its blocks we can
- 51:44view this Matrix here as made up only by
- 51:47its blocks and the output of this
- 51:50multiplication will be a
- 51:52matrices that is computed in the same
- 51:55way as the original Matrix
- 51:57but where the output of each dot product
- 52:00will not be a single element of the
- 52:02output Matrix but it will be a block of
- 52:04elements of the output Matrix for
- 52:07example the top left block here is the
- 52:11dot product of the first row of this
- 52:14Matrix with the First Column of this
- 52:17Matrix and it will be computed as
- 52:20follows so it will be a11 * b11 plus a12
- 52:24* B21 and this output will not be a
- 52:28single scalar but it will be a uh well
- 52:32let me count it should be uh eight
- 52:34elements so it should be four um made up
- 52:38it's it should be a block of four
- 52:40elements um or eight elements let me let
- 52:44me count actually so because we have
- 52:46eight blocks and it should be made up of
- 52:48eight elements uh let's we can see that
- 52:51here um how to find the dimensions of
- 52:54this output block
- 52:57uh well we can check what is a11 a11 is
- 53:004X two so it's eight elements in as a
- 53:04smaller Matrix made made up of eight
- 53:06elements where the elements are
- 53:08distributed in four rows and two columns
- 53:11we are multiplying it by b11 which is a
- 53:14smaller Matrix compared to the original
- 53:15made up of 2x two elements so four
- 53:19elements so when we multiply a 4x2
- 53:22multiply by 2x two it will produce a 4x2
- 53:24output uh block Matrix so
- 53:28block so if we do this computation here
- 53:31block by block it will produce a block
- 53:34of output elements of the original
- 53:36Matrix so not not a single scalar but a
- 53:38block of outputs which makes it very
- 53:40easy to parallelize because if we have
- 53:43only eight cores we can assign each
- 53:45output block to One Core and each core
- 53:48will not produce one output element of
- 53:50the original Matrix but it will produce
- 53:52eight elements of the original Matrix as
- 53:55a 4x2
- 53:57Matrix um so basically block Matrix
- 54:00allow us to um uh to do the matrix
- 54:03multiplication either by element by
- 54:05element so like in the original Matrix
- 54:07so each row with each column or blocks
- 54:09by blocks in the same way like we do
- 54:11normal matrix multiplication because the
- 54:13the matrix multiplication that we are
- 54:15doing between blocks is the same way as
- 54:17we do matrix multiplication with the
- 54:19original Matrix and it will produce not
- 54:22a scolar but a block and now let's see
- 54:24why this is very important for us
- 54:28so why should we care about block matrix
- 54:30multiplication because we are trying to
- 54:34compute the following operation so the
- 54:36query multiplied by the transpose of the
- 54:37keys and then we will should apply the
- 54:40soft Marx of this operation and then we
- 54:42should multiply the output of the
- 54:44softmax with V for now let's ignore the
- 54:47soft Marx let's pretend that we are not
- 54:49going to apply any softmax so we take
- 54:52the output of the query multiplied by
- 54:53the transpose of the keys and we just
- 54:55multiply it by V to obtain the output of
- 54:57the attention which is wrong of course
- 54:58but it simplifies our tract of what we
- 55:01are going to do next so for for this
- 55:04moment let's pretend that we are not
- 55:05going to apply any soft Max so we just
- 55:07do the query multiply by transpose of
- 55:08the keys and directly we multiply the
- 55:10result of this operation with v this
- 55:12will result in a matrix that is n by D
- 55:14so n tokens each made up of an embedding
- 55:18of D Dimensions so lower case D
- 55:21dimensions and we know that query key
- 55:24and values are themselves matrices of n
- 55:27by D Dimensions so the um um n tokens
- 55:32which made up of embedding of the
- 55:34dimensions so imagine we have a query
- 55:37Matrix and the key and the value Matrix
- 55:39that are 8 by 128 so we have eight
- 55:42tokens each token is made up of 128
- 55:46Dimensions we can divide as we have seen
- 55:49each when we compute matrix
- 55:51multiplication we can divide our um
- 55:54Matrix into blocks how we choose the
- 55:57blocks is up to us as long as the oper
- 56:01the the shapes of the blocks match when
- 56:03doing the matrix multiplication so for
- 56:05example in the previous case we divided
- 56:08our Matrix a into blocks such that the
- 56:11the the shape of the block Matrix so the
- 56:13Matrix that is made up only of the
- 56:15blocks is compatible with the block
- 56:18Matrix B so that this operation is
- 56:21possible so this is the only requirement
- 56:23that we need to be aware when doing the
- 56:26matrix multiplication the shapes of the
- 56:28blocked Matrix so the Matrix that is
- 56:30made only of the blocks should match in
- 56:32the matrix multiplication for the rest
- 56:35it doesn't matter how we divide it so
- 56:37imagine that we choose to divide this
- 56:40query Matrix into blocks of rows and we
- 56:43can do that we don't have to necessarily
- 56:45divide also the columns we can just
- 56:46divide the rows so that each Q is not a
- 56:49single row but it's a group of two rows
- 56:52so q1 is a group of the first two rows
- 56:55of the Q Matrix of the Q sequence Q2 is
- 56:58the group of the second two rows of the
- 57:00Q sequence etc etc and we do the same
- 57:03also for V for K we don't do it because
- 57:06we are actually going to multiply with K
- 57:09transposed so we do this subdivision
- 57:11directly on K transposed so so we have
- 57:15the Q which has been divided into groups
- 57:18of rows and then we have a k transposed
- 57:20which is a matrix that is 108 by 8
- 57:24because it's the transpose of the Keys
- 57:26which is 8 by
- 57:27108 and we decide to divide each of the
- 57:32column group of columns of K into a
- 57:35single block so the K1 is the first two
- 57:38columns of K transposed K2 is the second
- 57:41group of two columns in K transposed etc
- 57:44etc until K4 which is the last two
- 57:47columns in K transposed the first
- 57:49operation that we do is the
- 57:50multiplication query multiply by the
- 57:52transpose of the keys which basically
- 57:54means that we need to multiply each
- 57:56query with all the keys then the second
- 57:59query with the all the keys etc etc now
- 58:03each query is not a single row of the Q
- 58:06sequence it's a group of two rows of the
- 58:08Q sequence and each K is not a single
- 58:11column of K transposed it's a group of
- 58:14two columns of K transposed but doesn't
- 58:16matter because we have seen that the
- 58:17matrix multiplication if we write the
- 58:19matrixes as made up of blocks we just
- 58:22compute it in the same way when we do uh
- 58:25normal matrix multiplication ation so we
- 58:27are multiplying this matrix by this
- 58:29Matrix and for what we know this Matrix
- 58:32here is made up of four rows with some
- 58:36Dimensions which is uh 128 dimensions
- 58:40and this one here is made up of uh how
- 58:42many rows 128 rows and four uh
- 58:47columns I didn't uh draw The Columns
- 58:50because it's too many to draw here but
- 58:52you need to pretend it's a lot of
- 58:53Dimensions one for each 128 for each
- 58:56vector and here you need to pretend that
- 58:58this is 128 rows when we do the matrix
- 59:02multiplication we apply the normal M
- 59:04matrix multiplication procedure which is
- 59:06each output element so this first of all
- 59:08the output shape of this Matrix of this
- 59:10matrix multiplication will be 4x4
- 59:12because it's the outer dimensions of the
- 59:13two Matrix that they are
- 59:15multiplying the first element of the
- 59:17output will be the dot product of this
- 59:19Vector here with this Vector here the
- 59:23second element so this one here will be
- 59:25done dot product of this Vector here
- 59:28with this Vector here however this is
- 59:30not vector and this is not a vector so
- 59:33it's actually a matrix multiplication in
- 59:36this case this element here is not a
- 59:39scalar it is a group of elements of the
- 59:41output Matrix because we are doing block
- 59:43matrix multiplication and how many
- 59:45elements it will be well we know that
- 59:47the original q1 is a 2 by
- 59:49128 the K1 is 108x 2 so it will be a
- 59:54group of 2x two elements of the output
- 59:57Matrix so we are doing the matrix
- 1:00:00multiplication of the q1 with K1 then q1
- 1:00:04with K2 then q1 with K3 q1 with K4 etc
- 1:00:08etc for the first row and then the
- 1:00:10second row will be Q2 with all the K and
- 1:00:12the Q3 with all the ks and Q4 with all
- 1:00:14the ks so as you can see when we do
- 1:00:16matrix multiplication we don't even care
- 1:00:19if what is underlying is a block or a
- 1:00:22vector or a scalar we just apply the
- 1:00:24same procedure for first um row of the
- 1:00:28Black Block matrix multiplication with
- 1:00:30the First Column of the Matrix M of the
- 1:00:32second Matrix uh and then the first row
- 1:00:35with the second column the first row
- 1:00:38with the third column etc
- 1:00:40etc let's then multiply because the
- 1:00:43formula says that we need to multiply
- 1:00:45query with the transpose of the keys and
- 1:00:46then multiply by V all of these are um
- 1:00:50block matrices now as you can see from
- 1:00:53my using of colors every time time I
- 1:00:56refer to the original Matrix I use the
- 1:00:58blue color and every time I refer to the
- 1:01:00block Matrix I use the pink color so we
- 1:01:04need to multiply the output of the query
- 1:01:06multiplied by the transpose of the key
- 1:01:07then by V because we are skipping for
- 1:01:09now the soft Max and later we will see
- 1:01:11why so if we want to do this
- 1:01:13multiplication we need to do the
- 1:01:16following so it will be uh this Matrix
- 1:01:19is made up of blocks and block matrix
- 1:01:22multiplication just ignores this fact
- 1:01:24and just does the matrix multiplication
- 1:01:25like it is a normal matrix
- 1:01:27multiplication so we do the first row
- 1:01:29with the First Column then the first row
- 1:01:32with the second column then the third
- 1:01:34row the first row with the third column
- 1:01:37etc etc so the first block of row how is
- 1:01:40going to be calculated this out um this
- 1:01:43output in the output Matrix of this
- 1:01:44matrix multiplication well it will be
- 1:01:47the um the the first row so the dot
- 1:01:50product of the first row the dot product
- 1:01:54because it's not really Dot product it's
- 1:01:56the actually the matrix multiplication
- 1:01:58of the first row but in a dotproduct way
- 1:02:01let's say uh with the First Column which
- 1:02:04is made up of V1 vs2 V3 and V4 so it
- 1:02:08will be this element with V1 plus this
- 1:02:11element with vs2 plus this element with
- 1:02:14V3 plus this element with V4 uh and this
- 1:02:18will be the first output element the
- 1:02:21second output uh block will be this row
- 1:02:26with this
- 1:02:27column uh which will be this element
- 1:02:30with V1 this element plus this element
- 1:02:33with V2 plus this element with V3 plus
- 1:02:36this element with V4 and this will
- 1:02:37produce the second output
- 1:02:40block etc etc also for the third and the
- 1:02:43fourth block output let's look at what
- 1:02:46is each block made up of so each block
- 1:02:49is made up of the um the first element
- 1:02:52so query 1 multip by qy1 because um
- 1:02:56it's the result of the query multiply by
- 1:02:58the keys with the V1 of the second
- 1:03:01Matrix plus the this element with this
- 1:03:04one plus this element with this one plus
- 1:03:06this element with this one so the pelo
- 1:03:10code for generating this output of this
- 1:03:13attention mechanism which is not really
- 1:03:14attention mechanism because we skip the
- 1:03:16soft Max but I just want you to get into
- 1:03:18the habit of thinking in terms of blocks
- 1:03:22is the following so we take each query
- 1:03:26lock um we go through each
- 1:03:29query and as you can see let's look at
- 1:03:31actually what this output is made up it
- 1:03:34is made up of the query one multiplied
- 1:03:36by key1 and the result multiply by V1
- 1:03:39then the query one with K2 then the
- 1:03:42result multiply by V2 then the query one
- 1:03:45with the K3 and the result multiply by
- 1:03:47V3 plus the query one with the K4 and
- 1:03:50result multiplied by V4 this is
- 1:03:52basically what we are doing is the dot
- 1:03:54product of this row with this column
- 1:03:57made up of
- 1:03:59blocks um so the the pelo code for
- 1:04:02generating this first row is the query
- 1:04:05is the query number one and then we
- 1:04:08iterate through the keys and the values
- 1:04:10from one to four and we sum iteratively
- 1:04:14so for each block basically to generate
- 1:04:16this output Matrix and if you um for
- 1:04:19each row we will see that it's a
- 1:04:21different query with all the keys and
- 1:04:23values and then this will be the the the
- 1:04:25query number number three with all the
- 1:04:26keys and values and this will be the
- 1:04:28query four with all the keys and values
- 1:04:31so to generate this output Matrix we
- 1:04:33need to do we iterate through the
- 1:04:34queries and this will be one row of this
- 1:04:37output Matrix and then we need to do
- 1:04:39this iterative sum of the query I that
- 1:04:43we are iterating through multiply by the
- 1:04:45J K and V and we keep summing them
- 1:04:49iteratively and that would that will
- 1:04:51produce the output Matrix or you can see
- 1:04:53here I know that what I have done so far
- 1:04:56is not useless not useful for Flash
- 1:04:59attention but it's useful for us to get
- 1:05:01into the mindset of computing this
- 1:05:03product by blocks because later we will
- 1:05:05use it also with the
- 1:05:07softmax all right guys I I know that we
- 1:05:11have comput what we have computed so far
- 1:05:13is not really the soft Max operation is
- 1:05:15not sorry the really the attention
- 1:05:17mechanism because we have skipped the
- 1:05:19soft Max so somehow we need to restore
- 1:05:22it and the the following few I think
- 1:05:25think 10 20 minutes we are going to be
- 1:05:27really really challenging because I am
- 1:05:30going to do a lot of operations that
- 1:05:32will involve a lot of different blocks
- 1:05:34and a lot of different metrix
- 1:05:36multiplication and variants of the
- 1:05:39softmax so it may be difficult to follow
- 1:05:42however don't give up you can watch this
- 1:05:45part twice three times and every time
- 1:05:47you it will have a better understanding
- 1:05:50I also recommend watch it until we reach
- 1:05:52the flesh attention algorithm before we
- 1:05:55start restarting from to to go back to
- 1:05:58to rewatch it because you watch it we
- 1:06:01reach the flesh attention algorithm and
- 1:06:04it will give you a better understanding
- 1:06:05of what have happened so far and then
- 1:06:07you can rewatch it to deepen your
- 1:06:10understanding another thing that I
- 1:06:12recommend is take pen and paper and
- 1:06:15write exactly the operations that you
- 1:06:16are seeing and write the shapes of each
- 1:06:20of these blocks of these elements that
- 1:06:22are made in that are part in this um
- 1:06:25Matrix
- 1:06:26multiplications so that you better uh
- 1:06:30understand what is happening and you
- 1:06:31better remember what when I refer to a
- 1:06:34particular element or a particular block
- 1:06:37okay after giving this small uh
- 1:06:40motivational speech Let's Start so what
- 1:06:43we have done so far was query multipli
- 1:06:46by the transpose of the keys however
- 1:06:48each query is not a single row of the
- 1:06:51query sequence but it's a block of
- 1:06:54queries it's a block of rows in our
- 1:06:57particular case this q1 is not one row
- 1:07:00of the query sequence it's two rows of
- 1:07:03the query sequence because we have
- 1:07:04chosen as a block size a group of two
- 1:07:07rows and this K transposed one is not
- 1:07:11one column of the K transposed Matrix is
- 1:07:15two columns of the K transposed Matrix
- 1:07:17because we have chosen it like this and
- 1:07:19if you don't remember let's go back to
- 1:07:21see it uh here we have chosen K1 is 2
- 1:07:25two columns and q1 is two rows of the
- 1:07:28query original Matrix and every time I
- 1:07:31use the blue color I am referring to the
- 1:07:34original shape and every time I'm using
- 1:07:36the pink or Violet whatever it is I am
- 1:07:39referring to the block metrix so it's a
- 1:07:42block of elements of the original
- 1:07:45Matrix okay now uh the first thing that
- 1:07:48we have done was query multiplied by the
- 1:07:50transpose of the keys and this produces
- 1:07:53a block patrix as output that we will
- 1:07:56call S where each element s j so the S11
- 1:08:02element of this Matrix will be the query
- 1:08:04one with K transposed one the S12 will
- 1:08:08be query one with K transposed 2 s13
- 1:08:12will be query one with K transposed
- 1:08:14three etc etc for all the rows and for
- 1:08:17all the columns then we should be
- 1:08:19applying the soft Max because if you
- 1:08:21remember the formula is soft Max of the
- 1:08:22query multiplied by the transpose of the
- 1:08:24keys however I want to restore the
- 1:08:27softmax operation but with a Twist which
- 1:08:30means that we will apply the simplified
- 1:08:32version of the softmax and we will call
- 1:08:34it softmax star which is just the
- 1:08:37softmax without the normalization so let
- 1:08:40me write it for you what it
- 1:08:42means uh let's do it with the same color
- 1:08:45that I chose for the softmax which is
- 1:08:48orange so the soft max if you remember
- 1:08:51correctly if we remember it's the soft
- 1:08:53Max
- 1:08:56of to of a vector we apply it element
- 1:08:59wise so each element is modified
- 1:09:03according to the following formula so
- 1:09:04the E element of the output Vector to
- 1:09:07which we are applying the softmax is
- 1:09:10equal to the
- 1:09:12exponential of the E element of the
- 1:09:16input Vector minus the maximum element
- 1:09:20in the input Vector divided by a
- 1:09:23normalization factor that is calculated
- 1:09:25according to this
- 1:09:26summation that is going from Jal to 1 up
- 1:09:30to n of the
- 1:09:32exponential of x i minus x max so
- 1:09:37basically uh we are doing the
- 1:09:39exponential of each element minus this x
- 1:09:42Max and why are if you remember
- 1:09:43correctly why are we subtracting this x
- 1:09:45max to make this exponential numerically
- 1:09:48stable computable because otherwise it
- 1:09:51will explode and because we are applying
- 1:09:53it to the numerator we also need to
- 1:09:54apply it to the denominator okay the
- 1:09:57softmax start operation is exactly like
- 1:10:00the softmax but without the
- 1:10:01normalization part which means that it's
- 1:10:03just the numerator of the soft Max so we
- 1:10:05will modify each element of the vector
- 1:10:08to which we apply the soft Max star
- 1:10:09according to this formula let me move it
- 1:10:12more aligned like this so we just do
- 1:10:15element element wise uh operation that
- 1:10:18is the exponential of each element minus
- 1:10:21the maximum to the of the vector to
- 1:10:22which we are applying soft Max star
- 1:10:26okay now why did I introduce this soft
- 1:10:29maxar operation because we will be
- 1:10:31applying it to the Matrix that we have
- 1:10:33computed so far which is this s Matrix
- 1:10:36so we applied soft Max star to each
- 1:10:39element of this s Matrix but each
- 1:10:42element of this s Matrix is itself a
- 1:10:45matrix because it's a block Matrix and
- 1:10:48each element of this s Matrix so for
- 1:10:50example the element S11 is a 2x2 matrix
- 1:10:53because it is coming from the product of
- 1:10:55two matrices which are a group of rows
- 1:10:58and a group of columns from the Q and
- 1:11:00the K uh so for example this S11 is what
- 1:11:04is um let's draw it actually this S11
- 1:11:08will be for example made up of four
- 1:11:10elements let's call it uh I don't know a
- 1:11:14of
- 1:11:15S11 uh let's let's choose better naming
- 1:11:19let's call it I don't know
- 1:11:21a uh
- 1:11:25b c and d just the generic elements when
- 1:11:30we apply the soft Max star to this S11
- 1:11:33it will result so let's apply the soft
- 1:11:36Max
- 1:11:37star soft Max
- 1:11:40star it will result in a
- 1:11:43matrix that
- 1:11:46is each element the exponential of each
- 1:11:49element minus the maximum for each row
- 1:11:51now we don't know which is the maximum
- 1:11:53so let's choose one suppose that's the
- 1:11:55maximum for this row is a and the
- 1:11:57maximum for this row is D the first
- 1:12:00element of the output of this soft Max
- 1:12:02star applied to this block S11 will be
- 1:12:06the
- 1:12:08exponential of a multi minus a because
- 1:12:12that's what we chose as the maximum for
- 1:12:13this row the second element will be the
- 1:12:16exponential of B minus a because it's
- 1:12:19the maximum for that row then in the
- 1:12:22bottom row it will be the exponential of
- 1:12:25uh C minus D because that's the maximum
- 1:12:28for the bottom row and this will be the
- 1:12:30exponential of D minus D and that's the
- 1:12:34exponential that's how the softmax star
- 1:12:36will modify each block in this block
- 1:12:39Matrix let me delete this stuff
- 1:12:42otherwise it will remain in my slides
- 1:12:44forever and later I want to share the
- 1:12:45slides with you guys so you can use my
- 1:12:47same slides so delete delete delete okay
- 1:12:53after we have applied the soft Max to
- 1:12:55each of the elements in this s Matrix we
- 1:12:58will call it the P Matrix and each
- 1:13:01element P11 will again be block of 2x
- 1:13:04two
- 1:13:05elements um so P11 will be the soft Max
- 1:13:11so P11 will be the soft Max star applied
- 1:13:14to S11 where S11 is what is query one k
- 1:13:18transposed one and the p12 will be the
- 1:13:20soft Max star applied to S12 where S12
- 1:13:23is what is query one
- 1:13:25multiplied by K transpose the two etc
- 1:13:28etc etc for all the elements of
- 1:13:30s okay now that we have applied this
- 1:13:33softmax star operation the next
- 1:13:35operation that we should be doing
- 1:13:37according to the formula of the
- 1:13:38attention is uh the softmax of the query
- 1:13:41multiplied by the transpose of the keys
- 1:13:43then the result of the softmax
- 1:13:44multiplied by V I know that we didn't
- 1:13:47apply the real soft Max we applied
- 1:13:49softmax star which is softmax without
- 1:13:51the normalization later we will see how
- 1:13:54to compens at this lack of normalization
- 1:13:57because we will do it at the end and
- 1:13:58it's something that we can
- 1:14:00do okay so we take this P Matrix which
- 1:14:04is the result of the soft Max star
- 1:14:06applied to this s Matrix and we multiply
- 1:14:09it by
- 1:14:10V what how do we do it well it's a block
- 1:14:14it's a matrix made up of blocks of
- 1:14:17matrices um so P11 is actually not a
- 1:14:20scolar but it's a matrix of 2x two
- 1:14:22elements and we need to multiplied by V
- 1:14:25but we don't multiply with the original
- 1:14:27sequence V but with the blocked sequence
- 1:14:30V just like before where each V is not
- 1:14:33one row of V but it's a group of rows of
- 1:14:36v and how many rows is it is it is two
- 1:14:39rows of V uh for now please ignore
- 1:14:42completely whatever I have written here
- 1:14:44because we will use it later so we need
- 1:14:46to do this product of this Matrix here
- 1:14:49which is made up of blocks remember with
- 1:14:51this Matrix here which is made up of
- 1:14:53blocks it is made up of four
- 1:14:55four rows where each row is not really a
- 1:14:58row it is a block of rows and this one
- 1:15:01it is made up of 4x4 elements where each
- 1:15:03element is not really a scolar but it's
- 1:15:05a
- 1:15:06matrix so as you remember in the block
- 1:15:09matrix multiplication when the algorithm
- 1:15:11for computing the matrix multiplication
- 1:15:13is the same as the normal matrix
- 1:15:15multiplication except that we use blocks
- 1:15:18so what I am doing is guys uh the
- 1:15:20following operation so let's write it
- 1:15:22somewhere let's say o is equal to P
- 1:15:25multip by V okay so um the first output
- 1:15:30um row row because it's not really a row
- 1:15:34but it's a block row uh will be computed
- 1:15:37as follows the first row of this block
- 1:15:40Matrix with the First with um the First
- 1:15:43Column of this V Matrix and um we are
- 1:15:48treating it uh like a block Matrix so it
- 1:15:51will be P11 multip by V1 plus p12 ultip
- 1:15:57by vs2 plus p13 * by V3 plus p14
- 1:16:03multipli by
- 1:16:04V4 this will produce the first output
- 1:16:08row of O but it's not really a row
- 1:16:11because it's a made up of two rows uh so
- 1:16:15this stuff here is not one row it is two
- 1:16:18row and we can prove that because what
- 1:16:20is P11 P11 is let's write it somewhere
- 1:16:24so P11 is a 2X two Matrix uh yeah 2 by
- 1:16:29two and we are multiplying it with V1
- 1:16:32which is a block of two rows of V so it
- 1:16:35is a two rows by 128 Dimensions so it is
- 1:16:40equal to 2x
- 1:16:42128 so this stuff here is 2 by
- 1:16:47128 so this block here the output block
- 1:16:50that we are Computing is a block of two
- 1:16:52rows of the output Matrix that we are
- 1:16:55Computing uh I know this is really uh
- 1:16:59difficult to follow because we are
- 1:17:01involving blocks so we need to visualize
- 1:17:03at the same time metrics as blocks and
- 1:17:06as the original metrix that's why I
- 1:17:09highly recommend you to pause the video
- 1:17:12think it's through write down whatever
- 1:17:14you need to write down because it's not
- 1:17:17easy to find follow it just by
- 1:17:19memorizing the shapes so you you
- 1:17:20actually need to write down things
- 1:17:23anyway we are Compu the first output
- 1:17:26block of the output o Matrix now if we
- 1:17:30if you remember uh the output um the
- 1:17:34output this output here should be the
- 1:17:38output of the output of the soft Max
- 1:17:42multiplied by V now this soft Max has
- 1:17:46not been applied to the entire row of
- 1:17:51this Matrix here s Matrix here but
- 1:17:54basically to compute this soft Max star
- 1:17:57what we did was to compute the soft Max
- 1:18:00star at each block independently from
- 1:18:03the other blocks which means that the
- 1:18:05maximum that we are using to compute
- 1:18:07each soft Max star is not the global
- 1:18:11maximum for the row of this s Matrix but
- 1:18:15the local maximum of each block and this
- 1:18:19is wrong actually because when we
- 1:18:21compute the soft Max uh we apply the
- 1:18:24soft Max we should be using the global
- 1:18:27row I want to give you an example
- 1:18:30without using blocks because otherwise I
- 1:18:32think it's not easy to follow so when we
- 1:18:35do the normal attention so we have a
- 1:18:38query multiplied by the transpose of the
- 1:18:41keys this produces a matrix that is n by
- 1:18:43n so sequence by sequence where each
- 1:18:47element of this Matrix so let's say
- 1:18:49three four five I don't know how many is
- 1:18:52one two three four five six yeah six
- 1:18:56two 3 four and five six should be 1 2 3
- 1:19:004 5 6 okay this one here should be the
- 1:19:04dot product of the first query with the
- 1:19:07uh first um let me use because query one
- 1:19:12transpose the
- 1:19:14key1 uh this is because as I said before
- 1:19:17when we do the product of two vectors we
- 1:19:21always treat them as column vectors so
- 1:19:23when you want to write the DOT product
- 1:19:25you cannot multiply two column vectors
- 1:19:27you need to multiply one row Vector with
- 1:19:29one column Vector that's why we
- 1:19:30transpose this one if it confuses you
- 1:19:32you can also write q1 K1 that's totally
- 1:19:35fine it's just uh wrong from a notation
- 1:19:38point of view anyway the first one will
- 1:19:41be the dot product of the query one with
- 1:19:43K1 the second element will be the dot
- 1:19:46product of the query one with K2 the
- 1:19:49third will be the query one with K3 etc
- 1:19:52etc etc um
- 1:19:55so this is q1 with K1 q1 with
- 1:20:01K2 K2 and q1 with K3 q1 with
- 1:20:08K4 um
- 1:20:10anyway when we do the soft Max we
- 1:20:13actually calculate the maximum on this
- 1:20:15entire row however what we are doing is
- 1:20:19we are actually doing a block matrix
- 1:20:22multiplication and as you remember
- 1:20:25um when we do by blocks we are grouping
- 1:20:29together rows of queries and rows of
- 1:20:33keys and in this particular case we are
- 1:20:36grouping the two queries together to
- 1:20:38create one uh one group of queries and
- 1:20:42two keys together to create one block of
- 1:20:45keys so we need another row of this one
- 1:20:48so it's the let me ose query one k or
- 1:20:52query 2 K1 this should be query 2 2
- 1:20:55K1 query 2 K2 query 2 K3 query 2 K 4
- 1:21:04query 2 K5 and query 2 K
- 1:21:086 um when we each of this each of this
- 1:21:14block here is
- 1:21:16Computing this block here is Computing 2
- 1:21:19by two elements of the original Matrix
- 1:21:22if we had never applied the blocks so it
- 1:21:24is
- 1:21:25Computing these two four elements
- 1:21:29here and if we apply the soft Max star
- 1:21:33to each of these blocks we are not using
- 1:21:36the maximum element in this row we are
- 1:21:39only using the maximum element in each
- 1:21:41block which means that when we will use
- 1:21:44it in the downstream product with v
- 1:21:46Matrix we will be summing values that
- 1:21:50are wrong because each of these values
- 1:21:52here will be based on a maximum that is
- 1:21:55not the global maximum for this row it
- 1:21:58is the local maximum of this block here
- 1:22:02and um and this block here will have the
- 1:22:05global the it will use the local maximum
- 1:22:08of this block here and this block here
- 1:22:10will use the local maximum of this block
- 1:22:13here etc etc etc so what I'm trying to
- 1:22:16say is that when you sum P11 with V1 P11
- 1:22:21may have some Maximum local maximum that
- 1:22:24is different than from the local maximum
- 1:22:26of p12 and p13 may have a different
- 1:22:29maximum local maximum that of P1 P11 and
- 1:22:34p12 so we need to find a way to fix the
- 1:22:39maximum that was used to compute the
- 1:22:42exponential here with the maximum found
- 1:22:46here in case the maximum here is higher
- 1:22:49than the one local to P11 so if we have
- 1:22:53found for example here a Max maximum
- 1:22:54that is higher than the maximum used
- 1:22:56here here then we need to fix this one
- 1:22:58and this one because that maximum in the
- 1:23:01soft Max should be the maximum for all
- 1:23:03the row not the one belonging to the
- 1:23:05each
- 1:23:05block and this leads to our next step
- 1:23:09how to fix
- 1:23:10this first of all let me introduce a
- 1:23:13little pseo code for computing this
- 1:23:15output Matrix here which is an output
- 1:23:18block Matrix and later we will use this
- 1:23:22pelo code to adjust the error that we
- 1:23:25have made in some blocks in case the
- 1:23:28future blocks so the p13 has a better
- 1:23:30maximum than P11 or p12 so to compute
- 1:23:34this output Matrix
- 1:23:36o we go through so for example to
- 1:23:39compute the first row we choose well P11
- 1:23:41is what is is um let's go back P11 is
- 1:23:45let me delete also this one it's not
- 1:23:47needed anymore P11 is the soft Max star
- 1:23:51of q1 K1 p12 2 is the um soft maxar of
- 1:23:56q1 K2 p13 is the soft maxar of q1 K3 p14
- 1:24:02is the soft Mark star of q1
- 1:24:05K4 um which means that uh to compute
- 1:24:10this block here here we first need to
- 1:24:13compute the P11 what is P11 well P11 is
- 1:24:16the soft Max star of a block of Q and
- 1:24:20another block of k k which in the case
- 1:24:23of the first first row of the output
- 1:24:25Matrix means that it is the query one
- 1:24:29with the soft maxar of the query one
- 1:24:31with key1 the soft maxar of the query 1
- 1:24:34with K2 the soft maxar of the query 1
- 1:24:36with K3 the soft maxar of the query 1
- 1:24:38with K4 which means that we need to go
- 1:24:41we need to make a for Loop through all
- 1:24:43the keys while keeping the query fixed
- 1:24:47so to compute the first output row we
- 1:24:49need to do the soft maxar to produce P11
- 1:24:53we need to do the soft ma out of query 1
- 1:24:56K1 and um we sum it initially to zeros
- 1:25:01because we don't um we need to
- 1:25:02initialize our output somehow and we
- 1:25:04initialize it with
- 1:25:05zeros then we sum the next P1 to which
- 1:25:10is the query one with the K2 and then we
- 1:25:12sum the next p13 which is the query one
- 1:25:15with the K3 etc etc that's why we have
- 1:25:17this inner loop
- 1:25:19here all right so however this output
- 1:25:22that we Computing is wrong because I
- 1:25:23told you we have computed the softmax
- 1:25:26star using a statistics the maximum
- 1:25:29value that is belonging to each block
- 1:25:31and not the one that is the overall row
- 1:25:34of the original Matrix how to fix that
- 1:25:37we have a tool actually we have computed
- 1:25:39before an algorithm called the online
- 1:25:41softmax I don't know if I referred to it
- 1:25:43before as the online softmax but it's
- 1:25:45called the online softmax that allows to
- 1:25:48fix previous iterations when we are
- 1:25:51Computing the current iteration
- 1:25:54Bas how well let's review the online
- 1:25:57softmax we start imagine we are working
- 1:26:00with one single Vector so we are a
- 1:26:02vector made up of n elements the what we
- 1:26:05do is we do a for Loop where we compute
- 1:26:08iteratively the maximum up to the he
- 1:26:12element and we fix the normalization
- 1:26:15factor uh computed in previous iteration
- 1:26:18in case we found a better maximum at the
- 1:26:20current element if this is not clear
- 1:26:23guys go go back and watch the online
- 1:26:25soft Mar because this is very important
- 1:26:27because this is what we are going to use
- 1:26:29to fix this P11 p12 blocks in case we
- 1:26:32found better maximum in p13 or p14
- 1:26:36Etc so let's see how to apply this
- 1:26:39online soft Marx to this case here so
- 1:26:42that we can compute so you may be
- 1:26:45wondering why are we going through all
- 1:26:47these troubles I mean
- 1:26:50why the real reason is when first of all
- 1:26:53why did did we introduce block matrix
- 1:26:55multiplication because we want to
- 1:26:56compute matrix multiplication in
- 1:26:58parallel so you can think that each of
- 1:27:01this P11 because they are independent
- 1:27:03from each other and because each of them
- 1:27:05are using the maximum belonging to each
- 1:27:07block they can be computed independently
- 1:27:09from each other then however we need to
- 1:27:12somehow aggregate their value and to
- 1:27:14aggregate their value we need to fix the
- 1:27:17values that have been calculated
- 1:27:19independently because we didn't when
- 1:27:21Computing values independently we don't
- 1:27:22have a global view we have local view so
- 1:27:25we compute local blocks P11 p12 p13 etc
- 1:27:28etc and then when we aggregate these
- 1:27:31values we need to fix them so that's why
- 1:27:34we are trying to uh come up with this
- 1:27:37system of fixing uh values that have
- 1:27:39been calculated
- 1:27:41independently so how to fix this let's
- 1:27:44look at the following algorithm first of
- 1:27:47all um this O Block here as I said
- 1:27:51before it is a block of two rows
- 1:27:54where each row is made up of 128
- 1:27:57dimensions and we have seen that before
- 1:27:59by checking the dimensions of P11 and V1
- 1:28:02the result of P11 V1 which means that
- 1:28:05for each output block we need to take
- 1:28:08care of two maximums uh and two
- 1:28:11normalization factors so up to now I
- 1:28:13didn't use the normalization factor we
- 1:28:15said that we are applying softmax star
- 1:28:16which is the soft Max without the
- 1:28:18normalization but eventually we will
- 1:28:19need to compute this normalization so we
- 1:28:23want to create an an algorithm that
- 1:28:25fixes the maximum used to compute each
- 1:28:27of this P11 and also computes
- 1:28:30simultaneously the normalization factor
- 1:28:33and at the end we will apply this
- 1:28:35normalization factor and the way we will
- 1:28:37do it is as follows we start with
- 1:28:40initializing the maximum to minus
- 1:28:42infinity one for each row that we are
- 1:28:44Computing so is our output block is made
- 1:28:46up of two rows so we need one maximum
- 1:28:48for the top row and one maximum for the
- 1:28:50bottom row and also the normalization
- 1:28:53factor which we initialize with zero
- 1:28:55because we didn't sum anything for now
- 1:28:57and the output we initialize it with all
- 1:28:59zeros because we didn't sum anything to
- 1:29:01this output for now we
- 1:29:04compute the we uh to compute the output
- 1:29:08row so this output block here so this
- 1:29:11output block here we need to go through
- 1:29:14all the keys uh to produce this P11 p12
- 1:29:18p13 p14 while the query is the query
- 1:29:20number one the query block number one so
- 1:29:24the first step that we do is we compute
- 1:29:27the maximum of the first block
- 1:29:30P11 which is the row Max so the maximum
- 1:29:34for each row of the block um uh uh q1 K1
- 1:29:40this is not P11 it's S1 sorry guys this
- 1:29:43is
- 1:29:45S11 so we compute the maximum of this
- 1:29:48one and we call it actually S1 as you
- 1:29:50can see
- 1:29:51here um then we can um calculate P11
- 1:29:56which is the soft Max star which is the
- 1:29:58exponential of the query multip query 1
- 1:30:02K1 so S1 minus the maximum in the local
- 1:30:06group
- 1:30:08S1 and we add it to our
- 1:30:12output for now the output is initialized
- 1:30:15with zero so for now ignore this part
- 1:30:18here I will explain it later so for now
- 1:30:20o1 should be equal only to P11 V1
- 1:30:24now at the step number
- 1:30:27two we may find in the local group S12
- 1:30:31so this one is
- 1:30:33S12 we may find a better maximum for the
- 1:30:37top row and the bottom row and this
- 1:30:40maximum is the M2 which may be better
- 1:30:43than the previous maximum for each of
- 1:30:45these two row but may also not be so we
- 1:30:48need to find a way to fix in case it's
- 1:30:50better and to not fix anything in case
- 1:30:53it's not better
- 1:30:54and the way we do it is this so we
- 1:30:57compute the new maximum of the current
- 1:30:59local row query
- 1:31:012 we um calculated the p12 which is the
- 1:31:05soft Max star of S2 which is S2 minus M2
- 1:31:11which is the local maximum and then we
- 1:31:13need to add it to the output however in
- 1:31:17this case we may have found a better
- 1:31:19maximum so how to fix the o1 which on
- 1:31:23only use the maximum that was local to
- 1:31:26S1 well we know that we can fix that by
- 1:31:30using exponentials because each of these
- 1:31:32element of o1 is just an exponential
- 1:31:36without the normalization because we are
- 1:31:37applying soft Max star so how to fix an
- 1:31:41exponential with another exponential so
- 1:31:43basically we are saying that uh we
- 1:31:45multiply o1 which is a matrix so let me
- 1:31:50show you what is this Matrix so o1
- 1:31:54is a matrix made up of two rows so as
- 1:31:57you can see here I have the shape of o1
- 1:31:59it's a 2 by 128
- 1:32:02Matrix so this is the top row so 011 012
- 1:32:07blah blah blah until
- 1:32:09o1
- 1:32:11128 then
- 1:32:13o21 o22 up blah and
- 1:32:17o21
- 1:32:19128 we need to fix this value how we
- 1:32:23basically
- 1:32:24just using the exponential that we have
- 1:32:26used in the online softmax that we have
- 1:32:28seen before so if we multiply this
- 1:32:31Matrix here by a diagonal matrix that is
- 1:32:35made as follows it's a diagonal matrix
- 1:32:38made up of two elements because the
- 1:32:40exponential of M1 minus M2 will be a
- 1:32:43vector of two elements and the
- 1:32:45exponential of a element y exponential
- 1:32:48is another Vector of two elements and
- 1:32:51this diag basically means that diagonal
- 1:32:53Matrix where in the diagonal we have the
- 1:32:56elements of the vector to which we are
- 1:32:58applying this diag operation which means
- 1:33:01that this value here will be the
- 1:33:03exponential of the first element of
- 1:33:08M1 so let me show you uh how to write it
- 1:33:13exponential
- 1:33:15of M1 minus M2 minus M2 so the first
- 1:33:22element so let's call it one here here
- 1:33:25is a zero here will be zero and let's
- 1:33:28delete this one and we write another one
- 1:33:30here
- 1:33:32exponential M1 minus M2 but the second
- 1:33:36element of this Vector so basically the
- 1:33:39DI this notation here diag means
- 1:33:42basically just take the vector and
- 1:33:44distribute it over a n byn Matrix where
- 1:33:47n is the size of the vector to which it
- 1:33:48is applied and all the other elements of
- 1:33:51this Matrix should be zeros this is what
- 1:33:53this
- 1:33:54means if we do this operation here we
- 1:33:57will see that the output of this
- 1:34:00multiplication will fix each element of
- 1:34:04the top row using this exponential and
- 1:34:08the bottom row with this exponential
- 1:34:10which will basically cancel out this M1
- 1:34:13that was computed in the previous
- 1:34:15iteration and introduce the M2 that we
- 1:34:18have computed in the current iteration
- 1:34:19in each of these o elements in this o
- 1:34:24block
- 1:34:28Matrix okay so this output will be this
- 1:34:34element will will multiply by this one
- 1:34:37so it will fix o11 with this Factor here
- 1:34:40and o1 21 will not be fixed by will be
- 1:34:43multiplied by zero so it will not
- 1:34:45contribute to this first output element
- 1:34:48so this element here will only depend on
- 1:34:50o11 fixed by the exponential of M1 minus
- 1:34:55M2 but the first element of this vector
- 1:34:58and then o12 will also be fixed by um
- 1:35:02o12 will be fixed by this exponential
- 1:35:04here but not by this one and all the
- 1:35:06dimensions of the first row will be
- 1:35:08fixed by this exponential and all the
- 1:35:10dimensions of the second uh row here
- 1:35:12will be fixed by this uh exponential
- 1:35:15here this this scalar here which is the
- 1:35:18second element of the vector X of M1
- 1:35:21minus
- 1:35:22M2 or okay it was really challenging
- 1:35:25this one so so what we are doing is we
- 1:35:30compute p12 and we fix all the elements
- 1:35:33in P1 by multiplying by this Matrix here
- 1:35:37by multiplying by this Factor here
- 1:35:39Matrix Factor here and when we will
- 1:35:42compute uh step three we will fix step
- 1:35:45two etc etc etc now let's talk about the
- 1:35:48normalization factor because for now we
- 1:35:50have been ignoring it um the
- 1:35:53normalization factor is something that
- 1:35:54we can compute while Computing this
- 1:35:57maximums because it is provided in the
- 1:36:00pseo code of the online algorithm that
- 1:36:02we have seen before for the soft Max so
- 1:36:05while Computing the maximum we can
- 1:36:06actually compute the uh normalization
- 1:36:08Factor by fixing the normalization
- 1:36:11factor of the previous iteration and
- 1:36:13this is exactly what we are doing here
- 1:36:15so at the first iteration we comput the
- 1:36:17normalization factor using the local
- 1:36:19maximum and at the second iteration so
- 1:36:22you can for now ignore uh this one
- 1:36:24because we are not fixing l0 with
- 1:36:26anything because l0 will be zero so we
- 1:36:29are just basically
- 1:36:31um we are just Computing this summation
- 1:36:34here so l0 will be zero so this Factor
- 1:36:35here will be
- 1:36:37zero um and when Computing L2 so the
- 1:36:40normalization Step at the second
- 1:36:42iteration we will fix L1 with an
- 1:36:46exponential which guess what it's
- 1:36:48exactly the same exponential that fixes
- 1:36:50the maximum uh the P11 so it is the
- 1:36:55previous estimation of the maximum minus
- 1:36:57the current estimation of the maximum
- 1:36:59plus the new uh normalization factor
- 1:37:02using the local maximum and we keep
- 1:37:04doing this job at the end we will obtain
- 1:37:08a correct output for this uh metrix for
- 1:37:13for this uh block here but without the
- 1:37:17normalization how to apply the
- 1:37:19normalization well the normalization is
- 1:37:21something that is um we need to divide
- 1:37:24each element of this o by the
- 1:37:26normalization factor but because we are
- 1:37:29keeping while iterating through these
- 1:37:31for Loops we also calculate the
- 1:37:34normalization factor we keep
- 1:37:36accumulating it until we reach the end
- 1:37:39of the iteration and then we apply the
- 1:37:40normalization factor so we take the last
- 1:37:43output and we just divide it by L4 which
- 1:37:46is the normalization factor calculated
- 1:37:48at the fourth iteration and that will
- 1:37:51fix the soft Max all right guys so now
- 1:37:55that we have derived the algorithm of
- 1:37:57how to compute this output of the
- 1:37:59attention blockwise why also fixing the
- 1:38:01soft Max which is done independently in
- 1:38:04each single block we know that the
- 1:38:07normalization is done at the end I want
- 1:38:10to also prove it so what we done when we
- 1:38:12introduce this algorithm that computes
- 1:38:14the soft Max in an online way we proved
- 1:38:18by induction that this algorithm is
- 1:38:20correct so at the end of this algorithm
- 1:38:23this L of the last iteration will
- 1:38:25actually be the normalization factor
- 1:38:27that we can appli to get the soft Max so
- 1:38:32we don't apply the normalization while
- 1:38:34Computing this output in an online way
- 1:38:37iteratively way by multiplying the query
- 1:38:40with all the blocks of keys we apply it
- 1:38:44at the end of this four iteration and at
- 1:38:47the end of this four iteration we will
- 1:38:49have the last
- 1:38:50output um and we also know that the last
- 1:38:54L will contain the exact normalization
- 1:38:57factor that we need to apply to each row
- 1:38:59because this o of four is a block of
- 1:39:02output rows which is if you remember
- 1:39:06from the attention mechanism each output
- 1:39:09the output of the attention has the same
- 1:39:11shape as the input query Vector which is
- 1:39:15a sequence of tokens so this O is a
- 1:39:18sequence of tokens that we need to apply
- 1:39:20the normalization to and we know that
- 1:39:23the correct factor is L4 so let's prove
- 1:39:25this simple formula uh L4 is a vector
- 1:39:29one for that contains as many elements
- 1:39:31as there are rows in o4 so in this O
- 1:39:35Block uh of
- 1:39:38rows suppose that it contains uh two
- 1:39:41rows like in the algorithm that I have
- 1:39:43described so far in which we pretend
- 1:39:45that we are grouping two rows of queries
- 1:39:47with two columns of keys together so the
- 1:39:50output o uh um the block O will contain
- 1:39:54two rows of the output so we will have
- 1:39:57two normalization factor in this L4
- 1:40:00Vector here what we are doing with this
- 1:40:04formula is we are taking this L4 vector
- 1:40:07and we are creating a diagonal matrix
- 1:40:09with it and then we are Computing the
- 1:40:11inverse of this diagonal matrix so L4 is
- 1:40:16a vector that contains two normalization
- 1:40:18Factor so it's l i don't know let's call
- 1:40:21it l L4 4 element 1 and L4 element
- 1:40:282 this is our
- 1:40:31L4 uh Vector then we have 04 o4 is a
- 1:40:36matrix as you can see from the shape is
- 1:40:382 by
- 1:40:40128 Matrix so o is let's copy it
- 1:40:44actually oh no let's not copy it o4 is a
- 1:40:48matrix that is two
- 1:40:49rows with 128 elements so so the first
- 1:40:54row with 128 dimensions and the second
- 1:40:56row with 128 Dimensions the first thing
- 1:41:00that we are doing with this L4 is we are
- 1:41:02converting it into a diagonal matrix
- 1:41:04which will be a diagonal matrix 2x two
- 1:41:06because it contains two elements so it
- 1:41:09will become something like this so it
- 1:41:12will be L4 the first element of L4 zero
- 1:41:16and then zero L4 the second element of
- 1:41:19this
- 1:41:20Vector then we are Computing the inverse
- 1:41:23of this Matrix the inverse of a diagonal
- 1:41:26matrix is just the diagonal matrix with
- 1:41:28each element on the diagonal that
- 1:41:31becomes its
- 1:41:32reciprocal uh this is from linear
- 1:41:35algebra it's not I'm making it I'm
- 1:41:37making this up so uh the inverse of this
- 1:41:41Matrix here is equal
- 1:41:44to uh the same uh diagonal matrix but
- 1:41:47where each element is one over L4 the
- 1:41:51first element of L4 zero 0 and 1 over uh
- 1:41:56L4 the second element of L4 and then we
- 1:42:00are multiplying this stuff here so let
- 1:42:02me delete some stuff so this stuff here
- 1:42:05is getting multiplied by
- 1:42:08o which is a matrix that is 2 by
- 1:42:12128 so we are doing this multiplication
- 1:42:15now
- 1:42:17multiply now the output of this so this
- 1:42:21is two let me WR it 2x 2 * 2x 128 will
- 1:42:28be a matrix that is 2x
- 1:42:31128
- 1:42:34where the first um dimension of the
- 1:42:38first row of the output of this
- 1:42:40operation will be the dot product of
- 1:42:45this col this row here with the First
- 1:42:48Column so basically we are dividing this
- 1:42:50element here by L4 the first element of
- 1:42:52L four the second uh output element here
- 1:42:56will be the dot product of this row with
- 1:42:58this second column so we are only
- 1:43:00multiply we are dividing the the the the
- 1:43:02second element here of this input Vector
- 1:43:05here by L4 the first element of L4
- 1:43:08because the all the elements of the
- 1:43:10second row will be multiplied by zero so
- 1:43:12they will not contribute to this output
- 1:43:14row while the second output row will be
- 1:43:16the dot this element here will be the
- 1:43:18dot product of this row with the First
- 1:43:21Column the first element
- 1:43:23here is multiplied by zero so it will
- 1:43:25not contribute to this output so it's
- 1:43:27only the second ele the first row of the
- 1:43:29second the first element of the second
- 1:43:32row of the input Matrix here will be
- 1:43:33divided by
- 1:43:35l42 so basically this will be applied
- 1:43:38will divide all the elements in the
- 1:43:40second row and this will divide all the
- 1:43:42element in the first row in producing
- 1:43:44this one here which is exactly what we
- 1:43:46need to do when we want to normalize we
- 1:43:48need to apply this normalization factor
- 1:43:50and this should uh help you better
- 1:43:52visualize why this operation is
- 1:43:54normalizing the vectors of the output at
- 1:43:57the end and still obtaining the same
- 1:43:59result now let's proceed further all
- 1:44:02right guys finally we are ready to see
- 1:44:04the flash attention forward pass uh by
- 1:44:08um also comparing it with what we have
- 1:44:09derived so far so if you look at the
- 1:44:12flashh attention paper first of all this
- 1:44:14is the flashh attention to forward pass
- 1:44:16and later I will explain what are the
- 1:44:18differences between the flashh attention
- 1:44:19one and the flesh attention two um I
- 1:44:22didn't want to jump directly to this uh
- 1:44:24forward pass because I believe that even
- 1:44:26if the derivation like the derivation
- 1:44:29was a little uh difficult to follow I
- 1:44:32believe that it gave you some intuition
- 1:44:34into what is happening so even if you
- 1:44:36understand 50% of it that's enough
- 1:44:37because later we will also code it and
- 1:44:40you should reach like a 90% of
- 1:44:42understanding so every time we introduce
- 1:44:44some new information it should improve
- 1:44:45your be the the your understanding so
- 1:44:49basically in flesh attention what we are
- 1:44:51flesh attention to especially we we take
- 1:44:53our um as input we have our uh query
- 1:44:56Kean values which are sequence of tokens
- 1:44:59each token is made up of a vector of D
- 1:45:02dimensions and D lower case D dimensions
- 1:45:06and we divide this query guess what into
- 1:45:09blocks in how many blocks well depending
- 1:45:12on this parameter BR which is the size
- 1:45:15of the query block that we want to
- 1:45:18choose so how many rows of query we want
- 1:45:21to group together into one block and we
- 1:45:23also do it with K and V and we divided
- 1:45:27that into um blocks of uh um depending
- 1:45:31on this parameter BC then we also
- 1:45:34initialize the output which is the
- 1:45:36output that we want to produce so the
- 1:45:38what is the flashh attention Computing
- 1:45:40well the flashh attention um is
- 1:45:42Computing the following so it's
- 1:45:44Computing the uh soft
- 1:45:46Max soft Max of the query multiply by
- 1:45:50the transpose of the keys divide by the
- 1:45:52some normalization Factor uh multiply
- 1:45:55that by V and um so that's what it's
- 1:45:58going to compute and it's going to
- 1:46:00computed this way first of all there is
- 1:46:03an autor Loop through the queries which
- 1:46:06corresponds to the same pelo code that
- 1:46:09we have seen before because we want to
- 1:46:11compute each block of the output
- 1:46:13Matrix um in parallel with the with with
- 1:46:17respect to the others so basically we
- 1:46:19want to compute this output block and
- 1:46:22this block all output block
- 1:46:24independently this output block here
- 1:46:26depends on the query one and all the
- 1:46:28keys this output block here depends on
- 1:46:31the query 2 and all the keys this output
- 1:46:34block here depends on the query three
- 1:46:36and all the keys where query 1 is not
- 1:46:39the first query but it's the first group
- 1:46:41of queries or first block of queries
- 1:46:43query two is not the first um query two
- 1:46:46is not the second row of the query
- 1:46:47Matrix but it's the second block of the
- 1:46:49query Matrix etc etc um so that's why we
- 1:46:53have this outer um outer uh iteration
- 1:46:58among all the blocks because we want to
- 1:47:00compute all those blocks of the output
- 1:47:02Matrix in parallel but to compute each
- 1:47:04of these output block we need to go to
- 1:47:07an iteration among all the keys that's
- 1:47:09why we have an inner loop on the keys
- 1:47:12and we do exactly the same operation
- 1:47:14that we have done so far uh by hand so
- 1:47:17first we compute the S Matrix which is
- 1:47:19what the each block of query with the
- 1:47:21corresponding block of the keys then we
- 1:47:25compute the local maximum to the current
- 1:47:28s block this is the local maximum and we
- 1:47:31um compare it with the maximum of the
- 1:47:34previous iteration because that's what
- 1:47:36we do in the online softmax then we
- 1:47:38compute the
- 1:47:39P the P block which is the softmax star
- 1:47:44of the S block minus the local maximum
- 1:47:47of the S
- 1:47:48block then we compute the uh
- 1:47:51normalization Factor what is the
- 1:47:53normalization factor it is the summation
- 1:47:57of all the exponential of the soft Max
- 1:47:59star but um uh by fixing the
- 1:48:04normalization factor of the previous
- 1:48:06step and we know how to fix the
- 1:48:07normalization factor because we just
- 1:48:10multiply by an exponential which is the
- 1:48:12previous maximum minus the current
- 1:48:14maximum that's what this factor is and
- 1:48:17then we computed the output exactly
- 1:48:19using the same uh correction factor that
- 1:48:22we have seen before which is the
- 1:48:23diagonal matrix made up of the diagonal
- 1:48:26um where on the diagonal you have the
- 1:48:28elements of this Vector here which is
- 1:48:30the exponential of the previous maximum
- 1:48:33minus the current maximum multiplied by
- 1:48:35the output of the previous step because
- 1:48:37we want to fix the previous step because
- 1:48:39it was based on the previous P which was
- 1:48:40using the maximum of the local previous
- 1:48:43P plus the current p v which is based on
- 1:48:47the current local maximum and it will be
- 1:48:49fixed by the next
- 1:48:51iteration okay okay and at the end after
- 1:48:54we have gone through all the cas so we
- 1:48:58have computed all the output block but
- 1:49:01we didn't apply the normalization factor
- 1:49:03and it's applied at the end because
- 1:49:05while going through each key we are
- 1:49:07calculating the L normalization factor
- 1:49:10for the softmax because inside of this
- 1:49:12for Loop we are just Computing the
- 1:49:14softmax star so we are not normalizing
- 1:49:16each value so at the end someone has to
- 1:49:18normalize it and it will be this um this
- 1:49:22this um instruction here which is use
- 1:49:26the normalization factor that we have
- 1:49:29computed over all the iterations and
- 1:49:31apply it to each element of O because
- 1:49:33the difference between the softx star
- 1:49:36and the actual sofx is just the division
- 1:49:38by the um the normalization factor and
- 1:49:42this instruction here is actually
- 1:49:44dividing each o with the corresponding
- 1:49:47normalization Factor one for each row of
- 1:49:50the block each row in the output block
- 1:49:54that we are
- 1:49:55Computing uh later we will see also what
- 1:49:59do we do what is what does it what is
- 1:50:01this SRAM what is the hbm for now I just
- 1:50:03want you to concentrate on the um
- 1:50:06operations that we are doing and they
- 1:50:07are exactly the same operations that we
- 1:50:09have done so far uh later we will see
- 1:50:12also why do we need to save this stuff
- 1:50:14here and etc etc but for now you should
- 1:50:17have enough knowledge to be able to
- 1:50:19follow what is written in the flesh
- 1:50:21attention paper for with respect to the
- 1:50:24forward pass algorithm and uh what we
- 1:50:27are doing basically is just block matrix
- 1:50:29multiplication and while Computing this
- 1:50:31block we fix the previous block by using
- 1:50:34tricks of the
- 1:50:36exponential all right now that we have
- 1:50:39seen forward Paths of the flashh
- 1:50:41attention before we can implement it we
- 1:50:43still lack a little bit of knowledge
- 1:50:45because we don't know anything about the
- 1:50:47gpus and we don't know anything about
- 1:50:49Cuda and we don't know anything about
- 1:50:50Triton so that's what we are going to
- 1:50:52see
- 1:50:53next all right guys it's time for us to
- 1:50:56explore finally the GPU and the Cuda
- 1:50:59programming model well uh let's start by
- 1:51:01comparing the CPU and the GPU and this
- 1:51:04will let us understand how Cuda works
- 1:51:06then so first of all what is the Cuda
- 1:51:07and what is the GPU the GPU is the
- 1:51:09hardware unit that we are that we buy
- 1:51:12and Cuda is a software stocks made by um
- 1:51:15made by Nvidia or to write software for
- 1:51:18this GPU that they sell AMD has its own
- 1:51:21software stock and other manufacturer
- 1:51:23have their own in this particular video
- 1:51:26we will be seeing example of Cuda
- 1:51:27kernels but the knowledge that you will
- 1:51:29get can apply also to other gpus now the
- 1:51:33first difference between a CPU and a GPU
- 1:51:35is its purpose uh the GP the your
- 1:51:38computer is right now running on a CPU
- 1:51:41and your operating system is interfacing
- 1:51:43with the CPU um in using the uh the the
- 1:51:46so-called scheduler so right now
- 1:51:49probably you are running a browser you
- 1:51:50are also running some other software on
- 1:51:52your computer
- 1:51:53on your computer and the scheduler is
- 1:51:56tasked with switching between them very
- 1:51:58fast on your CPU in such a way that it
- 1:52:00looks like to you that the processes are
- 1:52:02running
- 1:52:03concurrently uh this actually is a fake
- 1:52:06kind of parallelism unless your CPU also
- 1:52:09has multiple cores which nowadays CPUs
- 1:52:12do have so a CPU usually has one or
- 1:52:15multiple cores but not so many of them
- 1:52:17so usually have dual core of quad core
- 1:52:19or eight core CPU and each of the this
- 1:52:22course can execute instructions in
- 1:52:26parallel um the CPU is tasked the the
- 1:52:30main purpose of the CPU is to execute
- 1:52:32many different task uh and switching
- 1:52:35between them very fast so maybe you have
- 1:52:37a browser that is running a small game
- 1:52:40and then you have another movie player
- 1:52:42but then you have a word processor and
- 1:52:43then you maybe have some uh utility to
- 1:52:46manage your um to download files Etc so
- 1:52:50most of these programs actually are not
- 1:52:51computing intensive are actually iio
- 1:52:53bound meaning that most of the time they
- 1:52:55are either waiting for the network or
- 1:52:57they are waiting for the dis and they
- 1:52:59are very different from each other in
- 1:53:01the purpose so a browser is completely
- 1:53:03different from a movie player and it's
- 1:53:05completely different from a word
- 1:53:07processor um so the job of the CPU is to
- 1:53:10actually reduce the latencies of
- 1:53:12processing all these operations and it's
- 1:53:15highly optimized to process to optimize
- 1:53:18each of these execution unit called the
- 1:53:20course which means that each course
- 1:53:23has a part that is tasked to understand
- 1:53:26first of all what is the next
- 1:53:27instruction to run or to to predict the
- 1:53:31branch of how the what the next uh
- 1:53:34operation may be based on the conditions
- 1:53:37that you are running for example if you
- 1:53:38have a if condition the branch predictor
- 1:53:41can understand what is the more most
- 1:53:42likely next instruction and can do some
- 1:53:45optimizations uh also the CPU is has a
- 1:53:48lot of caches to reduce the latencies in
- 1:53:50loading data from all the devices it can
- 1:53:53interface with it can interface with the
- 1:53:55uh the RAM for sure but it can also
- 1:53:57interface with the dis it can also
- 1:53:59interface with some peripherals like the
- 1:54:01printer like the mouse like the keyboard
- 1:54:02etc etc on the other hand the GPU is not
- 1:54:07tasked to do many different things at
- 1:54:09the same time but it's task to do one
- 1:54:12thing or few things but on a massive
- 1:54:15amount of data so the operations that we
- 1:54:17do on the GPU are uh requires a lot of
- 1:54:21computation and for that for this reason
- 1:54:23most of the area so the physical area of
- 1:54:26the GPU is dedicated to compute units so
- 1:54:29this green stuff that you can see here
- 1:54:31and these are called
- 1:54:33course um and you can see that the part
- 1:54:35that is dedicated to the control area so
- 1:54:38the part that is um tusked with
- 1:54:40understanding what is the next
- 1:54:41instruction to run or to do some
- 1:54:43optimization in this the program is very
- 1:54:45little uh you may be thinking well uh
- 1:54:48does it make it does it make the GPU uh
- 1:54:51less fast compared to the GPU to the CPU
- 1:54:54well not really because we have many
- 1:54:56more coures that can compensate for this
- 1:54:58um higher
- 1:55:00latencies um okay I can give you a lot
- 1:55:03of knowledge about the GPU from a
- 1:55:05theoretical point of view I think the
- 1:55:06best way to understand the Cuda
- 1:55:08programming model is just to jump into
- 1:55:09the code so we don't get bored okay
- 1:55:12imagine we have a very simple task and
- 1:55:15we have a
- 1:55:16vector we have two vectors A and B and
- 1:55:20we want to calculate the sum of these
- 1:55:22two vectors vectors into and save the
- 1:55:23result into another Vector C where each
- 1:55:26item is the element wise sum of the
- 1:55:29corresponding item of A and B how would
- 1:55:32you proceed with this task on the CPU
- 1:55:36well you would do a for Loop for example
- 1:55:38so for example uh you would uh make a
- 1:55:41for Loop that starts from the first
- 1:55:42index so the index zero and C of0 is
- 1:55:46equal to a of 0 plus b of0 then C of 1
- 1:55:50is equal to uh a of 1 plus b of one Etc
- 1:55:53and you do a for loop on all the
- 1:55:55elements of this
- 1:55:57Vector in the GPU we want to do the same
- 1:56:00operation but in parallel because we
- 1:56:02have a lot of compute units called
- 1:56:04course and we want all of them to work
- 1:56:06in parallel so the first thing that we
- 1:56:08need to understand is how to divide the
- 1:56:10work that we are going to do into
- 1:56:13subunits of work and dedicate each core
- 1:56:16to one subunit one simple subdivision
- 1:56:19would be okay the first core should do
- 1:56:21this summation the second core should do
- 1:56:23this summation the third core should do
- 1:56:26the summation etc etc so imagine we have
- 1:56:30a eight element Vector we need eight
- 1:56:32course to do this element wise
- 1:56:35summation we will call the course
- 1:56:38threads because it should also remind
- 1:56:40you of the multi- threading uh that we
- 1:56:42already use in operating system so
- 1:56:44multiple threads work concurrently on
- 1:56:46the same uh on the same or similar job
- 1:56:49in the GPU let's look at the code now
- 1:56:52the code that I am going to show you is
- 1:56:54Auda kernel and it's written in C but
- 1:56:56you don't have to understand C and you
- 1:56:58don't have to understand this code what
- 1:57:00I want you to understand is the
- 1:57:01intuition behind it because later we
- 1:57:03will need this knowledge and convert it
- 1:57:05into Tron which is Python and you should
- 1:57:07already be familiar with
- 1:57:08python so let's go to the code and I
- 1:57:12have a very simple vector addition uh we
- 1:57:15can see it
- 1:57:16here okay uh first of all how to do a
- 1:57:21vector summation usually the GPU is
- 1:57:24interfaced with a CPU and the CPU has to
- 1:57:28first of all um tell the GPU what is the
- 1:57:31data it he's going to work with so the
- 1:57:33CPU needs to have these vectors it needs
- 1:57:35to transfer them to the GPU then the GPU
- 1:57:39needs to do this Vector summation then
- 1:57:41the CPU has to copy back the information
- 1:57:44from the output from the GPU to the CPU
- 1:57:46and then make it available to the
- 1:57:48program this is what we are going to do
- 1:57:50here so we are going to allocate three
- 1:57:54vectors of size n one called a one
- 1:57:58called B and one is the output Vector we
- 1:58:00initialize their items um randomly so a
- 1:58:04of I uh is a random number between zero
- 1:58:08and 100
- 1:58:09excluded then we allocate memory on the
- 1:58:13GPU to hold these vectors and then we
- 1:58:15copy them to the GPU so we copyed the a
- 1:58:17vector to the GPU and the B Vector to
- 1:58:19the GPU of course we don't copy the
- 1:58:21result because that's what we want the
- 1:58:22GPU to populate with uh the output so we
- 1:58:26just allocate it on the GPU what we
- 1:58:28don't copy uh our output Vector on the
- 1:58:30GPU because it's it's made of random
- 1:58:33values then um what we do is we launch
- 1:58:37the kernel the launching the kernel
- 1:58:38means that we launch a program that the
- 1:58:41GPU should execute in parallel on
- 1:58:43multiple threads or multiple course each
- 1:58:45of these threads should do a unit of
- 1:58:48operation a unit of work that is
- 1:58:50independent from the others actually
- 1:58:51they can be dependent on the other but
- 1:58:53we will not be talking about
- 1:58:55synchronization um so we launched this
- 1:58:58kernel and what we are seeing in this
- 1:59:00line is launch one block of threads and
- 1:59:04later we will see what are blocks but
- 1:59:05you can think of you can ignore this one
- 1:59:07for now what we are saying here is
- 1:59:09launch n threads so n multi parallel
- 1:59:13operations on with the following
- 1:59:16arguments so the output where we want to
- 1:59:18save data the input array a and the B uh
- 1:59:22input B and the number of elements let's
- 1:59:25see what happens inside of this method
- 1:59:27this method is following a particular
- 1:59:29syntax that is um um how to say Cuda uh
- 1:59:34specific So This Global is actually
- 1:59:36added it's like a superet of the C
- 1:59:38language where we have some additional
- 1:59:40keywords that belong to Cuda so it's not
- 1:59:43really C it's Cuda
- 1:59:46c um so it's a very simple uh method as
- 1:59:49you can see and the first thing that we
- 1:59:51need to do is
- 1:59:52Cuda cannot know what each thread should
- 1:59:56do it's we should tell each thread what
- 1:59:59to do so the mapping between the data
- 2:00:02and the what each thread should do it's
- 2:00:04up to us as software
- 2:00:06engineer Cuda what we do is when we ask
- 2:00:09it to launch n threads in parallel it
- 2:00:11will allocate n threads and assign a
- 2:00:14unique identifier to each of these
- 2:00:16threads in our simple case we can see it
- 2:00:20like this so it will assign the first
- 2:00:23thread the index zero so we are asking
- 2:00:27for example imagine we have a vector of
- 2:00:28eight elements it will assign the first
- 2:00:31thread index zero here I call it one but
- 2:00:33it's it's wrong but uh we can write
- 2:00:36another number here so this will be
- 2:00:38actually tread zero this will be tread
- 2:00:39one this will be tread two tread three
- 2:00:42tread four tread five tread six and
- 2:00:45tread 7 so let me delete this
- 2:00:49one so we don't get confused
- 2:01:00and what we are seeing is that the item
- 2:01:04that each thread should process is equal
- 2:01:07to its thread index so this is the
- 2:01:09thread zero so it should process the
- 2:01:12item with index zero this is the thread
- 2:01:14one and it should process the item with
- 2:01:16index one this is the thread number two
- 2:01:18and it should process the item with
- 2:01:20index two and this is what we are doing
- 2:01:22in this line of code we are saying which
- 2:01:25item each thread should process which is
- 2:01:27exactly the it's uh the thread
- 2:01:30identifier so the thread ID uh later we
- 2:01:33will see why why we have this dot X but
- 2:01:36that's for later next thing that you
- 2:01:39should see is okay we are doing the
- 2:01:42output of the I position is equal to the
- 2:01:45a um Vector at the E position plus the B
- 2:01:49Vector at the E position so it's a very
- 2:01:51simple summation element wise you may
- 2:01:53have noticed this if statement why do we
- 2:01:56need an if statement if we already know
- 2:01:58that we are going to launch eight
- 2:02:00threads and uh of course I will be
- 2:02:04between um we already know that we are
- 2:02:07going to launch n threads so I should of
- 2:02:09course be less than n because each
- 2:02:11thread ID will be between zero and N
- 2:02:13minus one so why do we need this if
- 2:02:15condition this is needed because when
- 2:02:18you um Cuda when it launches a number of
- 2:02:22threads this number of threads is always
- 2:02:24a multiple of um a unit which is 32 in
- 2:02:28the case of the Cuda so if we have like
- 2:02:3234 elements in a vector and we ask Cuda
- 2:02:35to launch 34 threads Cuda will not
- 2:02:37launch 34 exactly it will launch 64
- 2:02:40threads so multiple of 32 uh which is
- 2:02:43the warp size by the way um and
- 2:02:47U what we need to do is we need to ask
- 2:02:50these threads to only work for we only
- 2:02:54need to ask the threads that have a
- 2:02:57corresponding element to work and all
- 2:02:59the other that don't have a
- 2:03:00corresponding element because the the uh
- 2:03:02the vector is not large enough for all
- 2:03:04of them to not do anything so do not
- 2:03:06enter this uh uh if
- 2:03:09statement there is another thing that we
- 2:03:11should learn which is actually the
- 2:03:14threads um actually when we have a group
- 2:03:18of threads in in um Cuda programming
- 2:03:20model but I believe also in other
- 2:03:22gpus um a group of threads of 32 threads
- 2:03:27is called a warp and this 32 threads
- 2:03:30will share the same um control unit so
- 2:03:34let's go back to the slide so as you saw
- 2:03:38as you can see here we have this yellow
- 2:03:40unit here in the GPU and a group of
- 2:03:43threads will share the same control unit
- 2:03:45which means that what is this control
- 2:03:46unit it's a part of the hardware of the
- 2:03:49GPU that is tasked with understanding
- 2:03:51what is the next instruction to run now
- 2:03:55if the group of threads is sharing the
- 2:03:57same unit it means that this group of
- 2:03:59thread will always execute the same
- 2:04:01statement at any time they will always
- 2:04:04work in synchrony will always work on
- 2:04:07the same instruction it's it cannot be
- 2:04:10like this thread is working on one
- 2:04:11instruction and this one is working on
- 2:04:13another instruction what does this mean
- 2:04:15on a programming level it means that if
- 2:04:19when we launch a group of threads of
- 2:04:22course Cuda will spawn more threads than
- 2:04:23we need if the if the number of elements
- 2:04:26of our Vector is not a multiple of
- 2:04:2932 this means that when we This Thread
- 2:04:32they will first execute this uh
- 2:04:34operation and each of them will have its
- 2:04:36own uh value of this thread ID so they
- 2:04:40will execute the same instruction but
- 2:04:42the data at each instruction may be
- 2:04:44different because each of them have
- 2:04:45their own registers which means that
- 2:04:48they will always they will for example
- 2:04:51reach this statement here and the first
- 2:04:53thread will have I equal to zero the
- 2:04:55second thread will have I equal to 1 etc
- 2:04:57etc even if they are executing the same
- 2:04:59instruction this programming model is
- 2:05:01called single instruction multiple data
- 2:05:03Cuda likes to call it single instruction
- 2:05:05multiple thread doesn't matter for us it
- 2:05:08just means that they will always execute
- 2:05:10the same instruction but the value of
- 2:05:12the variables may be
- 2:05:14different then after executing this
- 2:05:17statement they will reach this statement
- 2:05:19here the if statement and of course some
- 2:05:21some of them will evaluate this
- 2:05:23statement to true and some of them will
- 2:05:25execute the statement to false which
- 2:05:27also means that some of them should
- 2:05:29enter this if statement and some of them
- 2:05:31should not enter this if statement
- 2:05:34however because the control unit is the
- 2:05:36same for all of them they will be forced
- 2:05:39to enter this if statement even if they
- 2:05:41should not so how Cuda manages this
- 2:05:44control Divergence it will basically
- 2:05:46make work like this all the threads for
- 2:05:49which this if statement is equal to True
- 2:05:51will enter this if and will execute the
- 2:05:53instructions inside of this if and all
- 2:05:56the threads that have this statement
- 2:05:59equal to false so the condition of this
- 2:06:02if equal to false they will enter the
- 2:06:04for Loop because they cannot not enter
- 2:06:06it because they should be always
- 2:06:07executing the same instruction at any
- 2:06:09time but they will just not do any
- 2:06:11operations inside of this for Loop they
- 2:06:13will just sit
- 2:06:15idle this is um called control
- 2:06:18Divergence and it can reduce the um the
- 2:06:21the throughput of your program so you
- 2:06:23want to minimize it um but you may be
- 2:06:27wondering why doesn't the GPU dedicate a
- 2:06:29control unit to each core so that they
- 2:06:31can work independently from each other
- 2:06:33because the control unit is expensive to
- 2:06:35add in the cheap area of the GPU it's
- 2:06:37much more efficient to add more workers
- 2:06:40instead of adding control area control
- 2:06:42units for each worker so this is a
- 2:06:45design choice of the GPU and it works
- 2:06:47fine okay now that we have seen how a
- 2:06:50kernel works Works let's move forward to
- 2:06:54another
- 2:06:55example all right the next example that
- 2:06:58we are going to see is the following is
- 2:07:00the same as the as before so we are
- 2:07:02going to do a vector addition but
- 2:07:04imagine that we have a very large Vector
- 2:07:06so imagine that we have a vector with 1
- 2:07:08million elements of course we could do
- 2:07:11like before so we launch a kernel with 1
- 2:07:14million threads the problem is Cuda will
- 2:07:17reject it because it say I don't have 1
- 2:07:19million threads to run in parallel so
- 2:07:21how can we proceed in this case because
- 2:07:23usually we are working with very big
- 2:07:26matrices or very big vectors so we need
- 2:07:28to process a massive amount of data so
- 2:07:30how to manage a parallel um uh how to
- 2:07:35say parallel computation when we do not
- 2:07:37have enough uh computation course one
- 2:07:41way is to divide the input Vector into
- 2:07:44blocks of uh elements for example we may
- 2:07:47decide for example imagine our um GPU
- 2:07:51only has 32 cores in total we may divide
- 2:07:54our input Vector into blocks of size 32
- 2:07:58such that the first 32 element are the
- 2:08:00first block the next 32 element are the
- 2:08:02second block the third 32 element the
- 2:08:05third block and the last 32 element are
- 2:08:08the last
- 2:08:09block in this way we can ask the GPU to
- 2:08:13work on one block at a time so we can
- 2:08:15say okay work on the first block and
- 2:08:18after it has processed the first block
- 2:08:20it can work on on the second block and
- 2:08:22then the third block and the fourth
- 2:08:23block this also allows the GPU itself to
- 2:08:27manage subunit of work because imagine
- 2:08:30now we have um blocks of 32 elements but
- 2:08:34we have a GPU of 64 cores the GPU we can
- 2:08:38also schedule two blocks at the same
- 2:08:40time because it has enough course so we
- 2:08:42need to give some granularity uh we need
- 2:08:46to reduce the Gran uh increase the
- 2:08:47granularity of our data to let the GPU
- 2:08:51decide how many blocks to schedule this
- 2:08:53is the reason we introduce blocks inside
- 2:08:56of Cuda so let me make a concrete
- 2:08:59example but with a very simple
- 2:09:01assumption imagine our GPU only has two
- 2:09:03cores or let's say four cores actually
- 2:09:06uh so we have uh n is equal to eight
- 2:09:10elements eight and we have four cores in
- 2:09:15total so what we can do for example is
- 2:09:17to is divide this uh um Vector into
- 2:09:21groups of either four cores or even less
- 2:09:24let's say two two elements at a time so
- 2:09:27this is the block number one this is the
- 2:09:29block number two this is the block
- 2:09:32number three and this is the block
- 2:09:34number
- 2:09:35four we can ask Cuda to launch a kernel
- 2:09:40that is made up of four blocks and where
- 2:09:43each block is made up of two threads so
- 2:09:46when we launch the um Cuda kernel we can
- 2:09:50show the code now
- 2:09:52we ask the Cuda where is the
- 2:09:56instruction this first instruction tells
- 2:09:59Cuda how many blocks we have and the
- 2:10:01second part of this um in this uh um
- 2:10:06symbols tells how many threads we have
- 2:10:09for each block in our case we want um
- 2:10:14nide by the block size number of blocks
- 2:10:17where the block size in my picture is
- 2:10:19two so how many blocks we will will have
- 2:10:21we will have a number of blocks so the
- 2:10:24number of
- 2:10:29blocks is n / by two where two is the
- 2:10:33block
- 2:10:35size so this is the block size and this
- 2:10:39will be equal to four blocks each of
- 2:10:43size equal to two and this is what we
- 2:10:45are doing here uh so we are saying that
- 2:10:49the number of blocks is okay the ceiling
- 2:10:51because it may not be a multiple of the
- 2:10:53block size n of nide by the block size
- 2:10:57and this tells how many blocks we have
- 2:11:00and this is will be this will Define our
- 2:11:02grid it means the grid is basically
- 2:11:04telling how many blocks we have and then
- 2:11:07each block is made up of block size
- 2:11:09number of threads then the problem is
- 2:11:12how do we assign the work to do to each
- 2:11:15of these threads when we launch a kernel
- 2:11:18like this with this configuration so the
- 2:11:21number of blocks and the number of
- 2:11:22threads per block Cuda will do the
- 2:11:25following job it will assign this block
- 2:11:29um each block an index called the block
- 2:11:33ID where the block ID of the first block
- 2:11:36is zero so let me write here so this
- 2:11:38will have the first block will have a
- 2:11:40block ID equal to zero and in each block
- 2:11:45it will assign a thread ID and the
- 2:11:48thread ID of the first thread of each
- 2:11:50block will be the thread zero and the
- 2:11:53second thread will be the thread number
- 2:11:55one the second block will have block
- 2:11:58ID block ID equal to one and the first
- 2:12:02thread of this block will be the thread
- 2:12:04number zero and the second thread of
- 2:12:06this block will be the thread number one
- 2:12:08the third block will have a block
- 2:12:11ID block ID equal to two and the first
- 2:12:15thread will be the thread number zero
- 2:12:17and the second thread will be thread
- 2:12:18number one Etc until the last block
- 2:12:21which will be equal to three this will
- 2:12:24be thread number zero and thread number
- 2:12:25one the problem is now based only on the
- 2:12:28index of the block and the index of the
- 2:12:31thread how can we map it to what element
- 2:12:34of the vector each thread should work
- 2:12:36with one simple assignment would be to
- 2:12:39just do uh well you can see that in this
- 2:12:42case we need the uh this Vector um This
- 2:12:46Thread here to work with element zero
- 2:12:48this one should work with element one
- 2:12:51this one should work with the element
- 2:12:52number two this one to the element
- 2:12:54number three this one four this one
- 2:12:58five six and seven this five is so ugly
- 2:13:04so let me write it
- 2:13:06again how can we find the mapping given
- 2:13:09only the block ID and the thread ID how
- 2:13:12can we find Which element it should
- 2:13:14correspond to well it's very simple
- 2:13:15formula so you can see that the
- 2:13:18element let's call it the element ID
- 2:13:22which in the code I call it I is equal
- 2:13:25to the block
- 2:13:27ID multiplied by the size of each block
- 2:13:31which is block size let's call
- 2:13:33it block size yeah I have it block
- 2:13:38size plus the tread
- 2:13:42ID because in the case of the first
- 2:13:45thread this will be equal to 0 * 2 + 0
- 2:13:49which is 0 in this case it will be equal
- 2:13:51to 0 * 2 which is 0 + 1 and it will be
- 2:13:55equal to 1 in this case it will be equal
- 2:13:57to 1 because block ID is equal 1 1 * 2
- 2:14:00is equal to 2+ 0 is equal to 2 etc etc
- 2:14:03and you can see that this formula works
- 2:14:05for all the threads so the mapping when
- 2:14:07we launch a Cuda kernel we are telling
- 2:14:10the GPU how many blocks we want and how
- 2:14:13many threads there are in in each block
- 2:14:15but Cuda has no notion of how to map
- 2:14:19each um Cuda has no way of knowing how
- 2:14:22to map each um thread into the element
- 2:14:28it should work with that's up to us and
- 2:14:30that's what we are doing here when we
- 2:14:32are creating this um uh Kel here so we
- 2:14:36are telling that the each element each
- 2:14:39thread should work with the E element of
- 2:14:42the vector where I is calculated as
- 2:14:44follow the block ID to which This Thread
- 2:14:46belongs multiplied by the block size so
- 2:14:49how many threads there are in in each
- 2:14:51block plus the thread ID um and this
- 2:14:55will tell the I element this particular
- 2:14:57thread should work with by giving uh in
- 2:15:01let's go back to the slides by choosing
- 2:15:05the block size equal to two and having
- 2:15:08four cores the GPU can choose to run one
- 2:15:12block or two block concurrently if it
- 2:15:15has enough free course so that's why we
- 2:15:17want to work with by block by block
- 2:15:19because it allows the GP you to choose
- 2:15:21how it want to parallelize the
- 2:15:23operations if it has enough course and
- 2:15:26we don't need to have n course for n ve
- 2:15:29n element Vector we can divide it into
- 2:15:31smaller blocks and let the GPU manage
- 2:15:33the scheduling let's see one last
- 2:15:36example and then we move on to
- 2:15:38Tron imagine now we want to do a matrix
- 2:15:41addition instead of doing a vector
- 2:15:43addition now in a matrix addition we
- 2:15:46have data that we can see on two axes
- 2:15:49one is the rows and one is the
- 2:15:52columns it's usually uh we represent the
- 2:15:55vertical axis as the y axis and the
- 2:15:58horizontal axis as the
- 2:16:01xaxis by using the same blocked um uh uh
- 2:16:06intuition that we used before so
- 2:16:08dividing the data input data into blocks
- 2:16:11this is how we can divide the labor of
- 2:16:13our maxr addition into blocks for
- 2:16:16example we can divide our rows into
- 2:16:19blocks and call this one the block block
- 2:16:21zero and this one in the block one and
- 2:16:23this one is the block two the same we
- 2:16:25can do on the xaxis so we can choose
- 2:16:29this one as the block zero this one as
- 2:16:31the block one and this one as the block
- 2:16:33two on the x axis with X is the column
- 2:16:36axis and the Y is the row axis we don't
- 2:16:39even have to choose the same block size
- 2:16:42for the rows and the columns we can even
- 2:16:44choose the to group together three
- 2:16:47columns and two rows instead of doing
- 2:16:50two and two in this case we need to find
- 2:16:53because as we said before when we launch
- 2:16:55a Cuda kernel Cuda will just assign IDs
- 2:16:59to the blocks and the threads in each
- 2:17:01block then it's up to us understanding
- 2:17:03what to how to map the ID of the block
- 2:17:06and its corresponding thread ID into the
- 2:17:08data element that this particular thread
- 2:17:10should work it should work with so in
- 2:17:13the case of metrix addition we could say
- 2:17:15that each thread should work with one
- 2:17:18output element of the output Matrix C so
- 2:17:21it will become the um the the sum of the
- 2:17:24a element plus the B element and it
- 2:17:26should map it to the C Matrix uh output
- 2:17:30Matrix so how to do it imagine we have
- 2:17:33six rows and we have six columns one
- 2:17:37easy way would be to divide this rows
- 2:17:39into three blocks each made up of two
- 2:17:42rows and each column into three blocks
- 2:17:46um each block made up of two columns
- 2:17:49Cuda will launch
- 2:17:52uh uh as many blocks as there are the
- 2:17:54combinations of the rows and column
- 2:17:56blocks so in this case we have uh three
- 2:17:59blocks for the columns and three blocks
- 2:18:01for the um uh rows so it will launch uh
- 2:18:05nine blocks so this is the block number
- 2:18:0800 because it's Cuda will identify the
- 2:18:11dimensions of the block based on the um
- 2:18:15uh axis in which we have divided it so
- 2:18:18we will call this the X Dimension the
- 2:18:20columns and the rows we will call it the
- 2:18:22Y Dimension so it will launch as many
- 2:18:24blocks as there are combinations of X
- 2:18:26and y's in this case we have nine so
- 2:18:28this will be the block 0 0 this will be
- 2:18:31the block 01 this will be the block 02
- 2:18:34this one will be the block 1 Z 1 one and
- 2:18:38one two etc etc inside of each block we
- 2:18:41will also divide the threads into X
- 2:18:44threads and Y threads along the two
- 2:18:46Dimensions so this will be the thread
- 2:18:48zero and the thread one along the X axis
- 2:18:51in the X block and this will be the
- 2:18:54thread zero and the thread one in the Y
- 2:18:57uh in the in the block zero of the y-
- 2:18:59AIS and each block will have two threads
- 2:19:03and they will be identified as thread
- 2:19:05zero and thread
- 2:19:06one so let's look at how the launch grid
- 2:19:09Works in this case um so imagine we have
- 2:19:13a matrix with number uh num rows number
- 2:19:16of rows and num columns num calls number
- 2:19:19of columns and we want to to divide each
- 2:19:22row the rows into block size number of
- 2:19:26rows and calls block size number of
- 2:19:30columns um we define basically the
- 2:19:33number of blocks that we need is this
- 2:19:35one so this is just a fency way of
- 2:19:37writing the ceiling of the num Rose
- 2:19:39divide by The Rose block size and this
- 2:19:41is just a feny way of writing the
- 2:19:44ceiling of the number of columns divide
- 2:19:46by the col's block size this tells us
- 2:19:48how many blocks we will have on the rows
- 2:19:50and how many we will have on the columns
- 2:19:52the grid you can see here which tells us
- 2:19:54how many blocks we have is a tole that
- 2:19:57accepts three values which tells how
- 2:20:00many blocks we want on the X Dimension
- 2:20:02how many we want on the Y Dimension and
- 2:20:04how many we want on the Z Dimension we
- 2:20:07are not going to use the Z Dimension
- 2:20:09because we only have a matrix then
- 2:20:11inside of each block how many threads we
- 2:20:13want for the X Dimension and for the Y
- 2:20:16Dimension as the X Dimension we have
- 2:20:19chosen The Columns so we are saying how
- 2:20:21many blocks we want the columns and how
- 2:20:23many blocks we want for the rows and
- 2:20:25then inside of each block how many
- 2:20:27threads we want for the column block and
- 2:20:29how many threads we want for the row
- 2:20:31block this will Define our launch grid
- 2:20:34and what Cuda will do it will just
- 2:20:36launch this following configuration so
- 2:20:38it will launch as many blocks as there
- 2:20:40are combinations of X and y's and inside
- 2:20:42of each X and Y it will assign a thread
- 2:20:45ID in such a way that the thread zero on
- 2:20:49the X axxis is uh so there will be two
- 2:20:52threads on the x- axis and two threads
- 2:20:54on the y- axis of each block now let's
- 2:20:57try to understand how to map just based
- 2:20:59on the block ID on the x- axis just
- 2:21:02based on the block ID on the y axis and
- 2:21:05the thread ID on the X and y- axis how
- 2:21:07to map it to the one element of the
- 2:21:10output
- 2:21:11Matrix uh let's look at the code so
- 2:21:14first we can use the following formula
- 2:21:16to identify which row this element
- 2:21:18should work with uh which which uh the
- 2:21:22uh which because each element of a
- 2:21:24matrix is identified by two in this say
- 2:21:26one is the row identifier and one is the
- 2:21:28column identifier the row identifier we
- 2:21:31can look at it like the block ID
- 2:21:34multiplied by the block size plus the
- 2:21:35thread ID uh let's see why it makes
- 2:21:38sense so in this case for example this
- 2:21:41uh thread will work with the row zero
- 2:21:44because the block ID is on the y- axis
- 2:21:46is zero and the thread i z zero so it's
- 2:21:49block ID multiplied by the block size so
- 2:21:520 plus 0 it will be zero so this element
- 2:21:55will be working with the row number zero
- 2:21:58and which column it will be working with
- 2:22:00well it will be working with the block
- 2:22:02ID zero multiplied by the block size on
- 2:22:05the column which is again zero I mean
- 2:22:07the block size is two but multiply by Z
- 2:22:10it will be zero plus the thread zero so
- 2:22:12it will be zero this element here on the
- 2:22:16here it will be the block ID of the Y y
- 2:22:20AIS multiplied by the block size plus
- 2:22:23the thread so it will be the element
- 2:22:25zero on the row and for the columns it
- 2:22:28will be the element one let's see
- 2:22:30another one for example here uh for
- 2:22:33example this element here so this um how
- 2:22:37this uh thread will uh which element it
- 2:22:40will work with well it will be the block
- 2:22:42size on the Y AIS multiplied by the the
- 2:22:45block ID on the y axis multiplied by the
- 2:22:47block size so it will be 1 multiplied by
- 2:22:50two so that will be our row so the row
- 2:22:52number
- 2:22:53two uh which makes sense because it's
- 2:22:55the um this is the row zero this is the
- 2:22:58row one and this is the row two and the
- 2:23:01column will be the uh block ID on the x
- 2:23:05axis which in this case it's equal to 1
- 2:23:07multiplied by the block size which is
- 2:23:09equal to two so 2 + 1 is equal to 3 so
- 2:23:14this uh thread here will work with the
- 2:23:16element number two three and this
- 2:23:19formula now makes sense so this is how
- 2:23:21we use the block ID and the thread ID
- 2:23:24inside of each block to map it to which
- 2:23:26element this particular thread should
- 2:23:28work with so as I said before Cuda has
- 2:23:31no notion of knowing which element this
- 2:23:34particular thread should work with this
- 2:23:35is up to us just based on the block ID
- 2:23:38and the thread ID that CA
- 2:23:41assigns then we make sure that the uh
- 2:23:43row index is less than the number of row
- 2:23:45and the column index is less than number
- 2:23:46of columns why because as I said before
- 2:23:49when we launch um blocks and threads
- 2:23:52Cuda will round up that number to a
- 2:23:54multiple of 32 in the case of the
- 2:23:56threads so which means that some of
- 2:23:58these threads should not work with any
- 2:24:00data so we make sure that all the
- 2:24:01threads that should not have the
- 2:24:03corresponding element to work with they
- 2:24:05should be just sit idle inside of this
- 2:24:07if
- 2:24:09statement but the one that have it they
- 2:24:11should go enter and do some job so we
- 2:24:13calculate the index of the element of
- 2:24:17the Matrix that this particular thread
- 2:24:20should work with as follows which is the
- 2:24:22row index multiplied by the number of
- 2:24:24columns plus the column index uh this is
- 2:24:27just another way of
- 2:24:29writing uh a uh or for example this is
- 2:24:34just another way of writing a of row
- 2:24:40index call index but the way we allocate
- 2:24:44arrays in C or C++ is a flattened array
- 2:24:49where all the rows are one after another
- 2:24:51so we need to identify the element
- 2:24:53inside of the array based on its row
- 2:24:56index and column index and this is the
- 2:24:58formula that we use to identify it if
- 2:25:00you have never worked with um uh arrays
- 2:25:04in C++ or C then it doesn't matter
- 2:25:07because later we will see tensor layouts
- 2:25:09and this will be much more clear but if
- 2:25:12you have already worked with then you
- 2:25:13already know how to uh index an element
- 2:25:15inside of a multi-dimensional array in
- 2:25:18C++ and then we compute the output as uh
- 2:25:21as usual so I know that this has been a
- 2:25:24lot of information so what should we
- 2:25:26should we remember from this the first
- 2:25:28thing that we should remember is that we
- 2:25:30decide how to divide the work on
- 2:25:32whatever Matrix we are working with or
- 2:25:34whatever thread we are working whatever
- 2:25:36Vector we are working with we tell Cuda
- 2:25:38how many blocks we want and we tell Cuda
- 2:25:40how many threads we want in each block
- 2:25:43based on the identifier of the block ID
- 2:25:45and the thread ID we should come up with
- 2:25:48a strategy on how to map it to a subunit
- 2:25:50of work so which part of the Matrix or
- 2:25:53which part of the vector that particular
- 2:25:55thread should work with um now the next
- 2:25:59step for us is to understand the tensor
- 2:26:01layouts because we are going to work
- 2:26:03with the tensors and we need to
- 2:26:05understand how the tensors are lay out
- 2:26:07in the memory of the GPU or in the CPU
- 2:26:11as well actually so we need to
- 2:26:13understand what is the row column row
- 2:26:14major layout and the column major layout
- 2:26:17what is the stride Etc and convert all
- 2:26:19the knowledge that we have about Cuda
- 2:26:21into Triton so that we can then code
- 2:26:23with Triton our kernel so let's
- 2:26:27go all right guys finally it's time for
- 2:26:30us to explore tensor layouts now why do
- 2:26:33we need to explore tensor layouts
- 2:26:36because before we we have seen some
- 2:26:38examples of Cuda kernels and when you
- 2:26:41give a matrix to Cuda or to a Cuda Kel
- 2:26:44or a vector to Cuda kernel Cuda will not
- 2:26:47give you will not give you the entire
- 2:26:49metrix like like in Python where you can
- 2:26:51access each element by its index Cuda
- 2:26:54will just give you a pointer a pointer
- 2:26:56to the starting element of that
- 2:26:58particular Matrix or the starting
- 2:27:00element of that particular Vector then
- 2:27:03it's up to you to calculate the memory
- 2:27:05address of all the remaining elements so
- 2:27:07suppose that we have a simple Vector in
- 2:27:10py torch this simple Vector could be the
- 2:27:13following which is a vector of shape
- 2:27:16seven because it's a tensor with only
- 2:27:18one dimension with shape seven which is
- 2:27:20the number of elements in the First
- 2:27:22Dimension uh for now ignore this
- 2:27:24property called the slide and later I
- 2:27:26will explain it what is it uh how this
- 2:27:29tensor will be saved in the memory of
- 2:27:31the CPU or in the GPU it will be saved
- 2:27:34as follows suppose that the starting
- 2:27:36address of the first element is the
- 2:27:38address 100 and suppose that each
- 2:27:41element is made up of a floating point
- 2:27:43of 16 bit so it means that each element
- 2:27:45will occupy two bytes so the start
- 2:27:48address of the second element will be
- 2:27:50the address 102 and the third element
- 2:27:52will be 104 and the fourth element will
- 2:27:55be 106 etc etc etc so uh this is exactly
- 2:28:00what you get when you in see you get um
- 2:28:02you allocate a vector or a matrix with
- 2:28:05Malo so when you allocate in C um vector
- 2:28:09or a memory with maloc C or the memory
- 2:28:12allocator will just allocate enough
- 2:28:15memory to store all the elements and it
- 2:28:16will give you a pointer to the start
- 2:28:18address of this memory then it's up to
- 2:28:21you to understand where each of this
- 2:28:23element is stored in that block of
- 2:28:24memory and this is to to do this we
- 2:28:28introduce a property called stride The
- 2:28:30Stride tells us how many elements we
- 2:28:33need to skip to arrive to the next
- 2:28:35element in the particular dimension in
- 2:28:38this case for example in the case of a
- 2:28:40vector we only have one dimension which
- 2:28:42is the X
- 2:28:43Dimension uh or the columns Dimension
- 2:28:46you can think of it so this is the first
- 2:28:48column this is the second the third the
- 2:28:49fourth fifth etc etc um so in order to
- 2:28:53arrive from one element to the next we
- 2:28:54just need to skip one element so to go
- 2:28:57from here we need to just increase our
- 2:28:59pointer by one element and then to go
- 2:29:01here we need to increase again pointer
- 2:29:02by one element Etc this allow us to do a
- 2:29:05for loop on this tensor let's look at a
- 2:29:09more complicated case like the Matrix so
- 2:29:12the Matrix is
- 2:29:13two-dimensional and suppose we have the
- 2:29:15following Matrix which is made up of six
- 2:29:17element with two rows and three Colum
- 2:29:20columns so the shape of this tensor will
- 2:29:22be 2x3 because it we have two rows and
- 2:29:25three columns uh how this Matrix will be
- 2:29:28saved in the memory in the memory it
- 2:29:31will be just a
- 2:29:33flattened um Matrix it means and this is
- 2:29:36called the row major layout but there is
- 2:29:38also another one called column major
- 2:29:40layout that we will not be discussing so
- 2:29:43how it will be stored in the memory is
- 2:29:45as follows it will be the first elements
- 2:29:47of the first row so the elements of the
- 2:29:50the first row followed immediately by
- 2:29:52the elements of the second row so that
- 2:29:55the memory address imagine with this is
- 2:29:57the memory address of the first element
- 2:29:58is 62 to go to the next element we need
- 2:30:01to increase the memory address by the
- 2:30:03number of bytes that each element
- 2:30:05occupies which is two bytes so the the
- 2:30:08address of the second element will be 64
- 2:30:11the third element will be 66 and the
- 2:30:13next row will start immediately after
- 2:30:15the end of the first
- 2:30:17row let's introduce this property stri
- 2:30:20so the stride is what the stride tells
- 2:30:22us how many elements you need to skip in
- 2:30:24each Dimension to arrive to the next
- 2:30:26element of that dimension for example
- 2:30:29imagine we want to um uh address um we
- 2:30:33want to get the element so all the
- 2:30:35elements of the first
- 2:30:36row um so let's call this tensor here
- 2:30:40let's call it t so T of zero and um this
- 2:30:47basically this indexing here says give
- 2:30:49me all the elements of the first row so
- 2:30:52in the first row select the all only the
- 2:30:54first row and give me all the elements
- 2:30:55of that row how to how does this
- 2:30:58indexing work well by starting from the
- 2:31:01pointer to the first element it will
- 2:31:04select only the first row and then it
- 2:31:08will move the the index here one element
- 2:31:12after another so it will select the
- 2:31:14first one the second one the third one
- 2:31:16how does it know that it needs to move
- 2:31:17one element by one element because in in
- 2:31:20this Dimension the stride is one so the
- 2:31:22stride tells us how many elements you
- 2:31:24need to skip to arrive to the next
- 2:31:26element in that Dimension imagine now
- 2:31:29that we want to uh get the T of let's
- 2:31:32say zero and
- 2:31:35one well in this case the T let's say t
- 2:31:38of one actually and all the elements of
- 2:31:41the first row it will first of all it
- 2:31:44needs to skip some elements from the
- 2:31:47first First Dimension it needs to skip
- 2:31:49the element zero because we don't we are
- 2:31:50not selecting it we only want to select
- 2:31:52the element one of the First Dimension
- 2:31:55which basically means the row with index
- 2:31:57one so because it will start from the
- 2:32:00first pointer to the first element it
- 2:32:03will it needs to know how many elements
- 2:32:05to skip and how many element to skip is
- 2:32:07given by The Stride so the stride tells
- 2:32:09us how many elements you need to skip to
- 2:32:11arrive to the next element of the First
- 2:32:12Dimension so in this case it will take
- 2:32:15the pointer to the first element skip
- 2:32:17three elements and it will be starting
- 2:32:19with the second r go and then inside
- 2:32:21this row it will go through the second
- 2:32:23in the the the index of the second
- 2:32:25dimension in which the stride is one so
- 2:32:27it will just go one after another and it
- 2:32:29will return only this part of the memory
- 2:32:32so to rehearse the stride is just
- 2:32:36a a number that tells us how many
- 2:32:39elements you need to skip in each
- 2:32:41Dimension to arrive to the next index in
- 2:32:44that Dimension so it means that to go
- 2:32:46from one row to the other we need to
- 2:32:48skip three elements to go from one
- 2:32:49column to the other we need to skip one
- 2:32:52element um why is the stride useful well
- 2:32:56the stride is useful because it allow us
- 2:32:58to reshape tensors very easily and
- 2:33:01without doing any computation let's see
- 2:33:04um okay imagine we want to reshape a
- 2:33:07matrix imagine initially the shape of
- 2:33:09this Matrix is 2x3 so we have two row by
- 2:33:12three columns and we have a stride
- 2:33:14calculated as follow it means that to go
- 2:33:16from one row to the other you need to
- 2:33:17skip three elements and to go from one
- 2:33:19column uh one row to the other you need
- 2:33:20to skip three elements and to go from
- 2:33:22one uh column to the next you need to uh
- 2:33:25skip one element so you need to jump by
- 2:33:27one element if we want to reshape it
- 2:33:30into this shape so 3x two basically we
- 2:33:33want to um have three rows and two
- 2:33:37columns uh the the we can reshape it
- 2:33:42without actually changing its memory
- 2:33:45layout just by changing the stride
- 2:33:48because look at this physical
- 2:33:50configuration of the tensor and we can
- 2:33:53access this same tensor as this shape or
- 2:33:56as this shape exactly by using the same
- 2:33:59physical view because to go from one row
- 2:34:02to the next here the stride is three so
- 2:34:05we need to skip three elements it means
- 2:34:07that the starting address the starting
- 2:34:09element of the second row is given by
- 2:34:12the start point plus three elements so
- 2:34:15exactly here the second row will start
- 2:34:18and each element of the second row is
- 2:34:21one after another because the stride of
- 2:34:22the second dimension is one so you can
- 2:34:26see that to get the second row we can
- 2:34:28just start from here and then go one
- 2:34:30after another and get all these elements
- 2:34:33which is exactly the second row suppose
- 2:34:35we want to obtain the second row of this
- 2:34:37view here of this shape of this reshaped
- 2:34:40Matrix how to do that let's look at the
- 2:34:43stride the stri now is two in the row it
- 2:34:46means that to go from one row to the
- 2:34:47next we need to skip two elements so if
- 2:34:50we want to select this row here we go
- 2:34:52from the starting point of the uh memory
- 2:34:55so this start pointer we skip um the
- 2:34:59first two elements because the stride
- 2:35:01says that to go from one row to the next
- 2:35:03you need to skip two elements so we
- 2:35:04arrive here and then we select exactly
- 2:35:07two elements which are one after another
- 2:35:09because the stride in the second
- 2:35:10dimension is one so the um this stride
- 2:35:15allow us to reshape the tensor without
- 2:35:19changing the physical layout on how it
- 2:35:21is stored in the memory
- 2:35:24moreover The Stride also allow us to get
- 2:35:27the transpose of a matrix without
- 2:35:29changing the shape of how it is stored
- 2:35:31in the memory so without changing the
- 2:35:33arrangement of the elements in the
- 2:35:34memory and this is very cool because we
- 2:35:36can view the same Matrix as with without
- 2:35:39the transpose and also the transpose
- 2:35:41version of The Matrix without changing
- 2:35:43anything in the memory so it comes for
- 2:35:45free just by working with the index and
- 2:35:47the stride so to trans The Matrix along
- 2:35:50two Dimensions we just need to swap the
- 2:35:52stride along this two Dimensions that we
- 2:35:54want to transpose so in this case for
- 2:35:56example imagine we want to get the
- 2:35:57transpose of this Matrix we just need to
- 2:36:00swap the strides so if we want to get
- 2:36:02the second row of the transposed Matrix
- 2:36:05how to get that well you we always have
- 2:36:07the pointer to the first element where
- 2:36:10the tensor is stored so at the beginning
- 2:36:12of where the tensor is stored in the
- 2:36:15memory and it says that in order to go
- 2:36:18to from one row to the next we need to
- 2:36:21skip one element which is correct
- 2:36:25because as you can see the second
- 2:36:26element is exactly the second element
- 2:36:28also in the memory so we just Skip by
- 2:36:31one and we get the starting point of the
- 2:36:33second row and then to go from one
- 2:36:36element to the next in within the same
- 2:36:38row we need to skip three elements so
- 2:36:41the second element of the second row
- 2:36:44will be after three elements uh um after
- 2:36:48the first element of the second row so
- 2:36:49after two we need to skip three elements
- 2:36:51so we skip this one we skip this one and
- 2:36:53we arrive to this one eight which is
- 2:36:55exactly the second column of the SE uh
- 2:36:57of the second row so basically the the
- 2:37:00the stride as you can see allow us to do
- 2:37:02two things one is it allow us to reshape
- 2:37:05the tensor without having to reallocate
- 2:37:08it in another configuration in the
- 2:37:10memory secondly it allow us to transpose
- 2:37:13a matrix without having to rearrange the
- 2:37:15elements in the memory which is great
- 2:37:17because moving memory around is
- 2:37:18expensive
- 2:37:20uh and rearranging the memory is
- 2:37:21expensive so that's it's great that this
- 2:37:24this stuff comes for free
- 2:37:26basically um another thing okay for
- 2:37:29example do um if you try to you know
- 2:37:32that in py torch there are two methods
- 2:37:34to reshape a tensor one is called the
- 2:37:36reshape method and one is called The
- 2:37:38View method the after transposing a
- 2:37:42matrix by swiping by swiping The Stride
- 2:37:46of the two Dimensions that you want to
- 2:37:48transpose you cannot reshape for free
- 2:37:52the tensor anymore because um the tensor
- 2:37:55basically what is the stride The Stride
- 2:37:57how it is computed The Stride is just
- 2:37:59the uh let me show you with a concrete
- 2:38:03Example The Stride is just the product
- 2:38:05of all the shape uh after um in the
- 2:38:10future Dimensions so the stride of the
- 2:38:13zero Dimension is just the product of
- 2:38:16the elements in the shape of the future
- 2:38:18Dimension so so the stride of zero is
- 2:38:21just the product of all the shape
- 2:38:23starting from the index number one uh
- 2:38:26it's not easy to see with the two The
- 2:38:27Matrix because we don't have enough
- 2:38:28elements so let's do it with a three 3D
- 2:38:31Matrix so this is a tensor with the
- 2:38:33three dimensions so it is a shape of two
- 2:38:364 three which means that we have two
- 2:38:38matrices each Matrix is made up of four
- 2:38:40rows and each M and three colums The
- 2:38:44Stride is calculated as follows so the
- 2:38:46zero Dimension stride is just the the
- 2:38:49product of 4x3 and this three here comes
- 2:38:53the with the product of just a three
- 2:38:55with it with one because we don't have
- 2:38:57any future dimension of the tree so when
- 2:39:00we transpose this stri property is lost
- 2:39:04and we cannot um after transposing this
- 2:39:08matrix by swapping the strides we cannot
- 2:39:10do further reshaping operations so
- 2:39:13basically the the tensor is not log
- 2:39:15contigous so this is a very Advanced
- 2:39:18okay property if you it doesn't matter
- 2:39:20if you know it or not but if you are
- 2:39:22curious basically in a pytorch you
- 2:39:24cannot um view a tensor after it has
- 2:39:28been uh transposed because pytorch to
- 2:39:31transpose a tensor will just swap the
- 2:39:33two strides but it loses the stride
- 2:39:35property which is basically the stride
- 2:39:38will not be anymore the product of the
- 2:39:40future shapes so this is not anym two
- 2:39:45this should be two for example and this
- 2:39:47should be one but after transposing this
- 2:39:50property lost so you need to actually
- 2:39:51reallocate the tensor if you want to
- 2:39:54reshape it after it has been transposed
- 2:39:56doesn't matter if you remember this it's
- 2:39:58just a curiosity anyway so what is the
- 2:40:01transpose what is the stride used for is
- 2:40:03the St The Stride is used for two things
- 2:40:05first of all it it is used to understand
- 2:40:08how to Index this tensor so just by
- 2:40:11having a pointer to the first to the
- 2:40:13starting address of this tensor we can
- 2:40:16Index this tensor however we like so we
- 2:40:19we can access any row any column uh
- 2:40:22moreover it allow us to reshape this
- 2:40:25tensor for free so without rearranging
- 2:40:27the elements inside the memory and third
- 2:40:30it allow us to transpose the tensor
- 2:40:33however we like just by swapping the
- 2:40:34strides of two uh the two Dimensions
- 2:40:37that we want to
- 2:40:38transpose now that we have seen also how
- 2:40:41the tensor is stored in the memory we
- 2:40:43can finally go to see
- 2:40:45Tron um and see some examples all all
- 2:40:49right guys now that we have seen how uh
- 2:40:52tensors work Tor leat Works how Cuda
- 2:40:55works now we can see some examples of
- 2:40:57Tron kernels to see how Triton differs
- 2:41:00from Cuda now if you go on the Tron uh
- 2:41:04Tron website you will find some
- 2:41:06tutorials like in this section here and
- 2:41:09Let's do let's work one tutorial
- 2:41:11together to understand how Tron is
- 2:41:13different from Cuda um so if you go to
- 2:41:16the tutorial there are many examples so
- 2:41:18first of all the code that I will be
- 2:41:19coding for Flash attention is based on
- 2:41:21this tutorial here fused attention that
- 2:41:23you can see here but with some
- 2:41:24modifications because I simplified the
- 2:41:26code a lot I removed for example the fp8
- 2:41:29implementation I also for example um
- 2:41:32this code here on the fuse detention
- 2:41:34only works in the backward pass only for
- 2:41:36the causal attention while my code will
- 2:41:38work for the causal and non-causal
- 2:41:40attention uh the second another
- 2:41:42modification I did is instead of using
- 2:41:44the exponential two that they use here
- 2:41:46to make things faster probably because
- 2:41:48the exponential two is implemented uh
- 2:41:50with a faster unit uh I I I use the the
- 2:41:54original implementation of flash
- 2:41:56attention which used the exponential
- 2:41:57with the base e etc etc so I simplified
- 2:42:01my code as much as possible to make it
- 2:42:03simple to follow instead of making it
- 2:42:04optimized so for sure my code will be
- 2:42:07slower than the the fused attention that
- 2:42:09you see here but mine should be more
- 2:42:12comprehensible more easy to follow
- 2:42:14anyway let's go to the vector addition
- 2:42:16tutorial and if you go to the vector
- 2:42:18addition tutorial there are some
- 2:42:20examples on how to do a vector addition
- 2:42:22with Tron uh this should allow you to
- 2:42:24get into the mindset of how to write
- 2:42:26kernels with Tron uh instead of writing
- 2:42:29first the the kernel and then calling it
- 2:42:32let's do the opposite so let's see how
- 2:42:33to call this kernel and let's explore
- 2:42:35how it works so I have already copied
- 2:42:38the tutorial vector addition from the
- 2:42:40website so let's look at first of all
- 2:42:43what we want to achieve we have an input
- 2:42:46Vector X and an input Vector y and we
- 2:42:49want to compute the vector addition
- 2:42:50which means that with the torch we want
- 2:42:52to do the following operation and also
- 2:42:54we want to do the same operation also
- 2:42:56with the Triton by calling this method
- 2:42:58add and then we want to compare the two
- 2:43:00vectors output and they should be equal
- 2:43:03or at least their difference should be
- 2:43:04very very small because of course there
- 2:43:06is always some rounding error in case
- 2:43:08you are working with floating Point
- 2:43:09numbers the size of this Vector is
- 2:43:1298,000 elements and um we want to work
- 2:43:16in a blocked way so as you remember
- 2:43:18before with the Cuda you can do vector
- 2:43:21addition by spawning a lot of number of
- 2:43:24threads each doing one operation but
- 2:43:26when the number of threads that you have
- 2:43:27is not enough then you need to divide
- 2:43:30the input Vector into blocks and this is
- 2:43:32what we are going to do here so let's
- 2:43:33look at this add method so this add
- 2:43:36method basically will first of all
- 2:43:38allocate the necessary memory for the
- 2:43:41output Vector then it will compute the
- 2:43:45launch grid the launch grid tells Tron
- 2:43:48just like in Cuda how many um kernels we
- 2:43:51want to how many blocks we want to
- 2:43:53launch how many blocks of threads we
- 2:43:56want to launch uh if you remember in the
- 2:43:59Cuda kernel we specify how many blocks
- 2:44:02we want and then how many Treads we want
- 2:44:04for each block in the case of uh
- 2:44:07Triton we tell how many um blocks we
- 2:44:11want and then we don't force how many
- 2:44:14threads to launch it will be Tron that
- 2:44:17will choose how many threads to Launch
- 2:44:20um we just tell what each group of
- 2:44:23threads should do so in this case for
- 2:44:26example we divide our number of elements
- 2:44:29so n so which is 98,000 into blocks of
- 2:44:33size block size which is initialized as
- 2:44:371224 this is basically saying take the
- 2:44:41to calculate the grid size you do the
- 2:44:43ceiling division so basically this means
- 2:44:45ceiling of oh oops seal of n elements
- 2:44:51divided by block size this is the
- 2:44:54meaning of this one so how many blocks
- 2:44:56we want now what each block should do is
- 2:45:00inside of the kernel so let's go to the
- 2:45:02kernel and when we launch the the kernel
- 2:45:05we we can specify that the launch Grid
- 2:45:07in this uh Square parenthesis and then
- 2:45:09in the uh round parenthesis we specify
- 2:45:11the arguments of this kernel so let's go
- 2:45:14to the
- 2:45:15kernel we see that python uh Tron will
- 2:45:20not give us access to the tensor X it
- 2:45:22will give us a pointer to the first
- 2:45:25element of this tensor and this takes us
- 2:45:27back to the tensor layouts so the reason
- 2:45:30we studied the tensor layouts and the
- 2:45:32strides and all the stuff is because
- 2:45:34Tron this code uh this add kernel will
- 2:45:38run on the GPU and the GPU cannot um
- 2:45:42does not index tensors like P torch by
- 2:45:45using all the dimension and with the uh
- 2:45:48broadcast casting and all this fancy
- 2:45:50stuff the GPU will just give you the
- 2:45:52pointer to the first element of this
- 2:45:54tensor in the memory and then it's up to
- 2:45:56you to compute all the indexes of all
- 2:45:59the elements that you want to access so
- 2:46:02this x PTR is the pointer to the first
- 2:46:04element of the X Vector this y pointer
- 2:46:08is the first the pointer to the first
- 2:46:10element of the Y uh Vector then we have
- 2:46:13the pointer to the output Vector where
- 2:46:15we want to store the result of this
- 2:46:17Matrix addition we specify how many many
- 2:46:19elements our vectors have and what is
- 2:46:21the block size so how many uh items each
- 2:46:25block should process which may not
- 2:46:28correspond to how many threads each um
- 2:46:31each kernel will
- 2:46:33have you may be confused because okay uh
- 2:46:36in Tron in Cuda we specified how many
- 2:46:40threads each um block should have so the
- 2:46:44granularity that we manage is the thread
- 2:46:45level here we are saying it's a group of
- 2:46:48thread that should work with this
- 2:46:50quantity of data then it's up to Tron to
- 2:46:53optimize the number of threads that it
- 2:46:56will actually use actually there are
- 2:46:57tricks there there are ways to say how
- 2:46:59many threads we actually want by
- 2:47:00specifying the number of wordss but we
- 2:47:02will see that later for now just
- 2:47:04remember that this thread this Kel here
- 2:47:07will process a number of elements in the
- 2:47:10input vectors how many number how many
- 2:47:13elements block size number of elements
- 2:47:16first of all we need to identify which
- 2:47:18block we are um we are in Cuda we use
- 2:47:23the the variable called block ID dox to
- 2:47:26identify the identifier of the block
- 2:47:28which tells us which group of elements
- 2:47:30we should be working with in Tryon you
- 2:47:33do the same by using program ID and in
- 2:47:37uh Cuda the block ID can be along the X
- 2:47:40Y and Z axis in Tron these are called
- 2:47:43the dimension zero one and two uh two
- 2:47:46here we have onedimensional data so we
- 2:47:48only use one AIS to specify the block
- 2:47:51index so we get the block index which is
- 2:47:54the P ID in this the Tron this called
- 2:47:57the program ID it's more intuitive to
- 2:48:00think of as the program like this is a
- 2:48:03kind of a program that is running in par
- 2:48:05with other programs that will have
- 2:48:06different program ID and based on the
- 2:48:09program ID we can understand what is the
- 2:48:11starting element this program should
- 2:48:13work with so this blue block of threads
- 2:48:16should work with and to get that is just
- 2:48:18the P ID multiplied by the block size so
- 2:48:20the p 0 should be working with the
- 2:48:23elements that starts from the element
- 2:48:24zero the P id1 should start with the
- 2:48:27element 1024 and the P2 should start
- 2:48:30from the element 248 so it should skip
- 2:48:33the first 248 elements and starts with
- 2:48:35the element with index
- 2:48:382048 next we Define how to load these
- 2:48:41elements based on the
- 2:48:44pointer in which of the X and the Y uh
- 2:48:48vector
- 2:48:49to do that we specify a list of offsets
- 2:48:54with respect to the starting address
- 2:48:56that we want to load so because each
- 2:48:58program in Tron works with a group of uh
- 2:49:02um of data so not one single element but
- 2:49:05a block of elements we we need to
- 2:49:08understand which elements to load so the
- 2:49:10offset of this elements in the case of
- 2:49:12the program ID zero it will load the
- 2:49:14block start so zero plus the elements
- 2:49:17from index 0 to 100
- 2:49:211,424
- 2:49:23excluded with the program element
- 2:49:26um one this basically will result in a
- 2:49:30vector that is uh well the program start
- 2:49:34with PID equal to 1 will be24 then
- 2:49:371025
- 2:49:391,26 1027 etc etc until
- 2:49:452047 um with the program number let's
- 2:49:48say
- 2:49:49two this uh this offsets will be the
- 2:49:52elements
- 2:49:54248
- 2:49:56249 blah blah blah until 3,000 and
- 2:50:00something um now we also as you remember
- 2:50:04when we create
- 2:50:06um when we launch a grid the number of
- 2:50:10threads is not always based on the
- 2:50:13number of elements in the block or the
- 2:50:15number of elements in your vector it is
- 2:50:17always a multiple of a base number which
- 2:50:19is usually 32 which means that the grid
- 2:50:23this program may have more threads that
- 2:50:25it needs so some threads should not be
- 2:50:28doing anything so should not be loading
- 2:50:31any data and should not be Computing any
- 2:50:32summation so what we this is what why we
- 2:50:35need this mask this means that if um all
- 2:50:39these offsets that we are loading should
- 2:50:41be at most up to n elements because
- 2:50:44imagine you have not 1 2,000 imagine you
- 2:50:48have Vector of
- 2:50:51260 Elements which means that this
- 2:50:55offset for um the the third program of
- 2:50:59this kernel will load the offset that go
- 2:51:02from
- 2:51:032048 2049 blah blah blah 20 60 and then
- 2:51:07also 2061 2062 etc etc but we said that
- 2:51:12we only have 260 elements so all the
- 2:51:15elements 261 62 Etc until 300 and
- 2:51:18something they don't exist so we need to
- 2:51:21tell somehow that all the threads that
- 2:51:24are working with this elements should
- 2:51:26not load anything that's why we need
- 2:51:28this mask this mask tells load among all
- 2:51:32the offsets that this block should work
- 2:51:34with only those elements that actually
- 2:51:37exist for which this mask is true then
- 2:51:41we load the elements of this current
- 2:51:43program which is a group of elements
- 2:51:46defined by these offsets
- 2:51:49and only the one that for which this
- 2:51:51mask is true so only the one that
- 2:51:53actually exist all the other should be
- 2:51:55ignored and we can also specify what it
- 2:51:57should load in case this um the mask is
- 2:52:01false um with another parameter but we
- 2:52:04will not seeing that here we also load
- 2:52:06the group of elements of the Y vector
- 2:52:09and then we compute the output x + y so
- 2:52:12if you remember previously in Cuda we we
- 2:52:15did something like this like the output
- 2:52:18of I is equal to the x of I plus the Y
- 2:52:22of I so we did it one element at the
- 2:52:25time because each thread was working
- 2:52:27with one index here we are working with
- 2:52:29a group of elements so this x is a group
- 2:52:32of elements is a block of elements at
- 2:52:35most of size block
- 2:52:37size actually of size block size and
- 2:52:41it's this Y is a group of elements from
- 2:52:44the Y vector and we are Computing the
- 2:52:47output
- 2:52:48Group by group so this this is summing a
- 2:52:51group of elements of X with the
- 2:52:54corresponding group in y and writing it
- 2:52:56in output then we need to restore this
- 2:53:00output we need to store it in the output
- 2:53:02tensor output PTR that you can see here
- 2:53:05which is a pointer to the first element
- 2:53:07of the output vector and we say that
- 2:53:10where should we store this output Vector
- 2:53:12which is of size shape of this Vector
- 2:53:15here is block size where should we save
- 2:53:18it well in the same offset to where
- 2:53:21which we loaded X so if this uh program
- 2:53:25work with the index 2048 2049 etc etc
- 2:53:28then all this output should be written
- 2:53:31in the same offset uh 2048 2049 Etc up
- 2:53:35to 3,000 and something using the mask as
- 2:53:38well because we don't want to write all
- 2:53:40the values of this block size because
- 2:53:42maybe we don't have enough elements so
- 2:53:44only write the one that are actually
- 2:53:46present in the vector so the reason we
- 2:53:49need this mask is because Cuda will
- 2:53:51launch a number of thread that is always
- 2:53:52a multiple of a base unit that may not
- 2:53:54be a a multiple of the vector size that
- 2:53:58we are working with so we need to find a
- 2:54:00way to tell some threads to not do
- 2:54:02anything for those that the data is not
- 2:54:05avilable so let's rehearse what you have
- 2:54:07seen so far in Cuda the program that we
- 2:54:10write is at the thread level so each
- 2:54:12thread what it should do in Tron it's a
- 2:54:15this block of data we work with a block
- 2:54:19of threads what data this block of
- 2:54:22thread should work
- 2:54:25with all right guys the final finally
- 2:54:28the moment has come so uh we are going
- 2:54:31to quote the flashh attention for our
- 2:54:33pass right now in Tron but let's
- 2:54:35rehearse the algorithm so the goal of
- 2:54:38the attention mechanism in specifically
- 2:54:40in Triton uh in flesh attention is to
- 2:54:43compute the attention output which is we
- 2:54:45want to compute the output of the
- 2:54:47following formula so the query
- 2:54:48multiplied by the transpose of the key
- 2:54:50divide by the square root of the head
- 2:54:51Dimension all multiply we apply the soft
- 2:54:54Max and then all um multiplied by
- 2:54:57V now um we in this video we will be
- 2:55:01coding the forward pass and also the
- 2:55:04backward pass but before coding the
- 2:55:06backward pass we need to understand how
- 2:55:08the autograd works we need to understand
- 2:55:10what is the gradient what is the
- 2:55:12Jacobian how to derive the gradient of
- 2:55:14the softmax operation how to derive the
- 2:55:16gradient of the matrix multiplication
- 2:55:18operation etc etc so that is going to be
- 2:55:20another part of the video for now let's
- 2:55:22concentrate on the forward pass right
- 2:55:24now we have some tools so we know that
- 2:55:27we have this thing called the GPU that
- 2:55:28can parallelize operation among multiple
- 2:55:30cores we know that in Cuda we can
- 2:55:32parallelize operations by telling by
- 2:55:35writing a program that is the definition
- 2:55:37of what each thread should do or we can
- 2:55:40follow the Tron programming mode which
- 2:55:42is telling in Python what each group of
- 2:55:46threads should do
- 2:55:48the mapping between the what each thread
- 2:55:51should do and the which element that
- 2:55:54should thread work with is up to us to
- 2:55:56the programmers and the same happens in
- 2:55:59Tron we tell we how many blocks of
- 2:56:02threads we want how much data each
- 2:56:05thread should block of thread should
- 2:56:08process so that's the block size that we
- 2:56:10saw in the vector addition but then the
- 2:56:13mapping between the elements of the
- 2:56:15vector and the um the the identity of
- 2:56:19each group of threads so the program ID
- 2:56:21that we saw is up to us and the same
- 2:56:25will happen when we recode flashh
- 2:56:27attention let's see what can we par
- 2:56:29parallelize in this flashh attention so
- 2:56:31first of all this code that you see the
- 2:56:34forward pass of the flashh attention is
- 2:56:37takes as input query key and value that
- 2:56:40is a vector that is a matrices of n by D
- 2:56:45however usually in a Transformer Network
- 2:56:48we don't have only one sequence made up
- 2:56:51of D Dimensions we have many sequences
- 2:56:54made up of D dimensions and this D is
- 2:56:57the lower case D which is the the number
- 2:57:00of Dimensions dedicated for each head
- 2:57:02but we don't have only one head we have
- 2:57:04multiple head so the algorithm that you
- 2:57:07see here is what each head should work
- 2:57:11so each uh head of each batch should do
- 2:57:16moreover we have have seen before when
- 2:57:19talking about block matrix
- 2:57:20multiplication that we can parallelize
- 2:57:22the computation of the output because
- 2:57:24this output block here depends on the
- 2:57:27query one and all the keys this one here
- 2:57:29depends on the query group block of
- 2:57:32query two with all the keys and this one
- 2:57:34here is the query three with all the
- 2:57:36keys Etc so because this one only
- 2:57:39depends on query the group The Block
- 2:57:41query one and this one only depends on
- 2:57:43the Block query to they can work
- 2:57:45independently from each other by sharing
- 2:57:47of course work the the
- 2:57:50keys another thing that we need to
- 2:57:52understand about a Tron is the shared
- 2:57:54memory so um the in the GPU we have the
- 2:58:00high bandwidth memory and which is the
- 2:58:03like kind of the ram so the when you buy
- 2:58:05an a100 they tell you that it has 4 40
- 2:58:08GB that's the amount of memory in the
- 2:58:10high bandwidth memory so the D Ram so
- 2:58:13let's look at actually the structure of
- 2:58:15the
- 2:58:15GPU uh which is here we have this dram
- 2:58:19which is the big memory uh that we that
- 2:58:22the GPU has and then each um streaming
- 2:58:26multiprocessor so it's a let's call it
- 2:58:28BL block of threads uh actually also
- 2:58:31have a shared memory so inside of the
- 2:58:33GPU actually we have we have these
- 2:58:35streaming multiprocessors and these
- 2:58:37streaming multiprocessors have a part of
- 2:58:40memory called the shared memory which is
- 2:58:41much smaller than the dram like much
- 2:58:44much much smaller what changes between
- 2:58:47these two mem
- 2:58:48the access to the dram is very slow and
- 2:58:51the access to the shared memory is very
- 2:58:53very very fast so one thing that is
- 2:58:56different between Cuda and Tron is that
- 2:58:59whenever you load some information in
- 2:59:01Cuda you are loading that information
- 2:59:03directly from the global memory because
- 2:59:05when we launch a Cuda kernel first of
- 2:59:07all as you remember in my C C++ code we
- 2:59:11first copy the tensors from or the
- 2:59:13vectors from the CPU to the GPU and they
- 2:59:16reside in the global memory of the GPU
- 2:59:20then we load these elements directly
- 2:59:22from the global memory but the access to
- 2:59:24the global memory usually it's much much
- 2:59:27much slower so what happens with the
- 2:59:29flesh attention is that the flesh
- 2:59:30attention computation in its the
- 2:59:32attention computation in its naive
- 2:59:34version the one that we can do with the
- 2:59:36torch is very slow because access to the
- 2:59:38global memory is very slow so we want to
- 2:59:41use as much as possible the shared
- 2:59:43memory so we want to reuse the elements
- 2:59:46loaded from the global memory into the
- 2:59:48shared memory so that we don't need to
- 2:59:50access the global memory every time to
- 2:59:51load elements from the vectors or the
- 2:59:54matrices and um this is what happens
- 2:59:56also in Tron so in Tryon whenever you
- 2:59:58load some data you are copying the
- 3:00:00information from the global memory to
- 3:00:02the shared memory then whatever
- 3:00:04operations that you're doing is done on
- 3:00:06the shared memory and then when you
- 3:00:08store the information you are copying
- 3:00:10the data from the shared memory to the
- 3:00:11global memory um this makes it much
- 3:00:14faster so we always work with elements
- 3:00:17that have been Lo in the shared memory
- 3:00:20and this shared memory basically it's
- 3:00:21shared for all the threads that belong
- 3:00:24to the same uh block uh in Tron we have
- 3:00:28an obstruction level that doesn't make
- 3:00:30us work directly with the threads so we
- 3:00:32always work with a group of threads that
- 3:00:34belong to the same block that share this
- 3:00:36shared memory so in Tron we are copying
- 3:00:39information from the global memory to
- 3:00:40the shared memory we do some operation
- 3:00:42with it and then we store back to the
- 3:00:43global memory and this is what we are
- 3:00:45going to do with flash attention now
- 3:00:47let's review the algorithm of Flesh
- 3:00:49attention so in flesh attention we have
- 3:00:51to go an out for Loop that is among all
- 3:00:54the between all the keys and then an
- 3:00:57inner loop that is sorry between all the
- 3:00:59query blocks and then an inner loop that
- 3:01:01is um through all the key
- 3:01:04Block in the original flash attention
- 3:01:07algorithm the flashh attention one the
- 3:01:09outer block was on the keys and the
- 3:01:11inner block was on the queries this made
- 3:01:14it less parallelizable why because the
- 3:01:17Outer Loop is on the queries and we have
- 3:01:19seen before that the the output of this
- 3:01:22um attention can be computed
- 3:01:24independently for each block of queries
- 3:01:27so it's much easier to parallelize so
- 3:01:29this outer for Loop actually we don't
- 3:01:30have to run a for Loop we just spawn
- 3:01:32many kernels each working with one
- 3:01:35iteration of this outer for Loop so each
- 3:01:37working with a different query block of
- 3:01:40this outer for Loop and the inner for
- 3:01:43Loop is something that we have to
- 3:01:44iterate through so each Trion kernel
- 3:01:47will work with one query block and then
- 3:01:51iterate through all the key blocks um
- 3:01:54and inside of this key block we have
- 3:01:56already seen the operations that we are
- 3:01:58going to do which the we we we explored
- 3:02:00before and at the end of this for Loop
- 3:02:03we need to store back the output in the
- 3:02:06high bandwidth
- 3:02:08memory um and this is how it's going to
- 3:02:11we are going to work another thing that
- 3:02:13we should notice is that this s value
- 3:02:16are n byd so as I said before but
- 3:02:19usually in a um in
- 3:02:22a Transformer model we don't have only
- 3:02:25one sequence we have many sequences so
- 3:02:27we can also parallelize on the number of
- 3:02:29sequences that we have in the batch
- 3:02:31because each batch can work
- 3:02:32independently from each other and inside
- 3:02:35each um and each head each sequence has
- 3:02:38multiple heads so each head also can
- 3:02:41work independently from each other
- 3:02:42because that we know from the attention
- 3:02:44is all un need paper that's what's the
- 3:02:45meaning of head that's what's the
- 3:02:47meaning of multi head attention so that
- 3:02:49each head can compute the attention
- 3:02:50independently from each other so we will
- 3:02:52also parallelize along the head
- 3:02:54Dimension and moreover if you look at
- 3:02:57this definition of the query block we
- 3:02:59can also split the query into blocks and
- 3:03:01each query block can work independently
- 3:03:03from the other query blocks by in
- 3:03:05producing one output block this is how
- 3:03:08we are going to parallelize so we are
- 3:03:10going to parallelize each sequence in
- 3:03:12the patch in inside of each sequence we
- 3:03:14are going to paraliz each head and
- 3:03:16inside of each head we are going to
- 3:03:18paralyze each query block so how many
- 3:03:21programs we we will have working in
- 3:03:23parallel at most it will be uh the sequ
- 3:03:27the number of batches so the bch the
- 3:03:29number of sequences in the batch so the
- 3:03:30batch
- 3:03:31size it will be the batch
- 3:03:34size multiplied by the number of
- 3:03:40heads uh multiplied by the number of
- 3:03:44blocks that we will divide the query
- 3:03:46sequence into so let's call it the I
- 3:03:49don't know block size
- 3:03:51Q the block
- 3:03:55size
- 3:03:57Q all right now that we have seen this
- 3:03:59one let's go actually code it
- 3:04:03so I have already introduced a little
- 3:04:05bit of the differences between my
- 3:04:07implementation of The Flash attention
- 3:04:08and the one that you can find on the
- 3:04:10Tron documentation which is a first of
- 3:04:12all I don't work with fp8 because I
- 3:04:14believe this is unnecessary for our
- 3:04:16explanation it's of course much faster
- 3:04:18because the recent gpus also support
- 3:04:21fb8 Second difference is that in the um
- 3:04:25In the Flesh attention on the Triton
- 3:04:28website the backward pass is only
- 3:04:31implemented for the causal attention but
- 3:04:32in my case I implement it for the causal
- 3:04:34and the non-causal attention even if
- 3:04:36it's slower and later I actually I want
- 3:04:38to give you an exercise on how to
- 3:04:39improve it um and the third difference
- 3:04:43uh main difference is that I made make
- 3:04:46explicit use of the soft Max scale so I
- 3:04:50actually use the scale when needed
- 3:04:53another difference is that in the online
- 3:04:56uh Tron computation of The Flash
- 3:04:58attention is this X is not really e to
- 3:05:01the power of X but it's two to the power
- 3:05:03of X and then they compensate it with by
- 3:05:05by using the
- 3:05:07logarithm however uh because probably
- 3:05:10the implementation of two to the power
- 3:05:12of X is faster than the e to the power
- 3:05:14of X but in my case I retain the
- 3:05:16original exponential because I want to
- 3:05:18follow the original algorithm to make it
- 3:05:20simpler to visualize the code along with
- 3:05:23the algorithm as in the flash ration
- 3:05:24paper
- 3:05:27so uh I know I have created a lot of
- 3:05:29hype so let's do it uh let's start by
- 3:05:32creating a new um file let's call it
- 3:05:36program. piy uh just like before when I
- 3:05:38introduced Tron I will start by coding
- 3:05:41first the code that will use our Kel and
- 3:05:43then we code the Kel and we will only be
- 3:05:45coding the forward P of the Kel
- 3:05:48so let's start
- 3:05:50by importing what we need to import
- 3:05:52which is just the torch and the Triton
- 3:05:55and secondly let's start by let me check
- 3:05:58okay the co-pilot is already off so I
- 3:06:00don't have to worry about that let's
- 3:06:03start to implement the code that will
- 3:06:05test our implementation of the Triton
- 3:06:07and compare it with the naive
- 3:06:08implementation of the attention
- 3:06:10mechanism so we in uh we create our
- 3:06:13query key and SE uh query key and value
- 3:06:16sequence for test thing which is if you
- 3:06:20remember it's query is the BET size it
- 3:06:23has the dimension bet size because we
- 3:06:24have a multiple
- 3:06:26sequences each sequence has a number of
- 3:06:28heads and it's made up of s tokens and
- 3:06:32each token is identified by a head dim
- 3:06:34number of
- 3:06:35Dimensions uh if you in then this is
- 3:06:39because we have already split each token
- 3:06:42into smaller tokens each each with its
- 3:06:45own head Dimension if you remove the N
- 3:06:48heads Dimension then you put back you
- 3:06:50concatenate all the dimensions of this
- 3:06:52head
- 3:06:53dim um we initialize the query key and
- 3:06:56value sequence by using a normal
- 3:06:58distribution this code I already took
- 3:07:00from the tutorial of Tron so it's
- 3:07:02nothing different and we require the
- 3:07:05grad the gradient because we want to
- 3:07:07compute the gradient with respect to
- 3:07:08query key and value and um we will see
- 3:07:10later why because because we want to
- 3:07:12implement the back we want to test also
- 3:07:13the backb pass even though we will not
- 3:07:15be coding it now so the first thing that
- 3:07:18we do is we Define our soft Max
- 3:07:20scale which is as you remember the
- 3:07:23formula is U query multiplied by the
- 3:07:26transpose of the keys and then divided
- 3:07:30by the square root of head
- 3:07:34Dimension so DK or the DHE head sometime
- 3:07:39it's called and then we need to so we
- 3:07:41need to compute this one we can already
- 3:07:43compute it it's this this is one over
- 3:07:45the square root of the head dimension
- 3:07:48um and then we also Define d o and later
- 3:07:52we will see what is this but this is
- 3:07:54basically we will be needed needed for
- 3:07:56the backward
- 3:08:00pass um don't worry if you don't
- 3:08:03understand what is doo later we will see
- 3:08:04it let's do the naive implementation of
- 3:08:07the attention which is very simple which
- 3:08:10is first we Define the mask and we use
- 3:08:13this mask only if the attention we are
- 3:08:15Computing is Cal so as you can see we
- 3:08:17pass this parameter called causal that
- 3:08:19tells if we want to compute the causal
- 3:08:22attention or the not causal attention
- 3:08:24and the D type which is float 16 because
- 3:08:27we want to work directly with 16 bit
- 3:08:30floating Point numbers we will not be
- 3:08:32working with fp8 just because we we
- 3:08:34don't we don't want to implement uh my
- 3:08:36implementation is actually not as fast
- 3:08:38as the one in the tutorial of the Tron
- 3:08:40website but I believe it's much more
- 3:08:43easier to
- 3:08:44comprehend uh so we Define the mask
- 3:08:48we compute the the the product query
- 3:08:51multiply by the transpose of the key
- 3:08:52divide by the square root of the head
- 3:08:54Dimension so that's why we are
- 3:08:55multiplying by Soft mask scale if the
- 3:08:57attention we're Computing is Kaa then we
- 3:08:59use this mask that we have computed so
- 3:09:02we replace all the points all the dot
- 3:09:05products where this mask is equal to
- 3:09:07zero with minus Infinities and then the
- 3:09:09soft mask will replace this minus
- 3:09:10Infinities with zeros because then we
- 3:09:13are applying the soft Max and the soft
- 3:09:15Max is applied by rows just like the
- 3:09:17normal attention we
- 3:09:19compute okay the second thing that we do
- 3:09:21is we want to um so the output is the
- 3:09:25product of the output of the softmax
- 3:09:27with the V so this is the reference
- 3:09:29output on the naive implementation of um
- 3:09:33flash of the attention mechanism then we
- 3:09:36want to compute we want to also derive
- 3:09:39the gradients of the output with respect
- 3:09:42to the um
- 3:09:44inputs and in this case it's the
- 3:09:47the the V the K and the Q later we will
- 3:09:51see what are we doing here then we want
- 3:09:54also to we want to compare this
- 3:09:56reference implementation with our Tron
- 3:09:58implementation so let's do it so our
- 3:10:01Tron implementation will be implemented
- 3:10:02as a class called Tron attention that we
- 3:10:06will call using this method called apply
- 3:10:08and later we will see what is this
- 3:10:09method in which we pass the query key
- 3:10:11and value if we want to compute the Cal
- 3:10:13attention the soft Mark scale that it
- 3:10:15should be using and it should prod
- 3:10:17produce some output which is the output
- 3:10:19of the output of the softw multiplied by
- 3:10:22V then we can run also the backward and
- 3:10:24this backward will be the the the the
- 3:10:26same backward that we will compute with
- 3:10:28the um Tron
- 3:10:30attention and then we
- 3:10:33compare okay and then we can compare uh
- 3:10:36the result of our implementation so this
- 3:10:39Tron attention not apply with the
- 3:10:41reference implementation which is this
- 3:10:43one here and they should be uh we use
- 3:10:46the the function all clause which
- 3:10:48basically compares the elements of two
- 3:10:50tensors and make sure that their
- 3:10:52absolute difference is no more than this
- 3:10:54one we are not using the relative
- 3:10:56distance we are just using the absolute
- 3:10:58distance between the two elements
- 3:11:00corresponding elements of two vectors
- 3:11:02this uh implementation that we have that
- 3:11:05we will build will work with the causal
- 3:11:06attention and also with not causal
- 3:11:08attention while the the one that we saw
- 3:11:10in the website of Tron it only works
- 3:11:13with the uh the forward pass actually
- 3:11:15works with the causal and non causal
- 3:11:17while the backward pass only works in
- 3:11:18the case of the Cal attention um okay
- 3:11:22but it's highly optimized the one online
- 3:11:24so if you want to learn a little more
- 3:11:26tricks on how to optimize Triton kernels
- 3:11:28there is a lot of knowledge there anyway
- 3:11:30guys now let's try to uh implement this
- 3:11:33Tron atten at least the forward pass so
- 3:11:36let's go to implement this Triton
- 3:11:38attention
- 3:11:41class um okay here every time you want
- 3:11:44to introduce a new operation into torch
- 3:11:47you need to uh derive the um you need to
- 3:11:51implement your operation by deriving
- 3:11:53from this autograd do function class so
- 3:11:56every operation in torch actually if
- 3:11:58it's the soft Max or it's the I don't
- 3:12:01know the the ru or the zgo or whatever
- 3:12:04there is it is always implemented as a
- 3:12:06as a function is a class that derives
- 3:12:08from this function and it should provide
- 3:12:10two method one called the forward pass
- 3:12:12and one called the backward pass the
- 3:12:14forward should produce the output of
- 3:12:16this operation and the backward should
- 3:12:17compute the
- 3:12:19gradient um the gradient with of the
- 3:12:22loss with respect to that the the input
- 3:12:24of that function and later we will see
- 3:12:26how that works for now let's concentrate
- 3:12:28on the forward pass to implement the
- 3:12:30forward pass we need to create a static
- 3:12:32method that is called
- 3:12:34forward which takes as input one thing
- 3:12:38called the context so as you know in the
- 3:12:40autograd in when training AAL networks
- 3:12:43we have the forward pass and the
- 3:12:44backward when Computing the backward
- 3:12:46pass we need to reuse the activations of
- 3:12:49each of the computation nodes during the
- 3:12:51forward pass and this context basically
- 3:12:53allow us to save the information to uh
- 3:12:56for the necessary activations that we
- 3:12:57will need during the backward pass and
- 3:12:59later we will see in the tron um in the
- 3:13:02flash attention algorithm what
- 3:13:03information we need to save in order to
- 3:13:06compute the backward pass for example
- 3:13:08what we will need to save during the
- 3:13:09backward pass we will need to recompute
- 3:13:12on the Fly the soft the query multiply
- 3:13:16by the transpose of the keys for each
- 3:13:17block but we don't want to recompute the
- 3:13:19normalization factor or the maximum
- 3:13:21value for each row so we will save those
- 3:13:23two values and actually we will not save
- 3:13:26two values we will save one value with a
- 3:13:27trick called The Log sum X log sum X
- 3:13:30trick that we will see later anyway this
- 3:13:33context is just a kind of a storage area
- 3:13:36where we can save some stuff that will
- 3:13:37be necessary for us to recompute the
- 3:13:40backward and you can see whatever you
- 3:13:42like then we have the input of this um
- 3:13:45operation which is the query key and
- 3:13:47value which is three tensors with the
- 3:13:50Cal if we are going to compute the Cal
- 3:13:52attention and the soft Mark scale that
- 3:13:54we should apply based on the one over
- 3:13:55the square root of the uh head
- 3:13:59Dimension uh which we could also compute
- 3:14:01it on the fly actually by the way by by
- 3:14:03checking the shape of this but okay it
- 3:14:05doesn't matter anyway so um the first
- 3:14:08thing that we are going to do is to
- 3:14:09extract the shapes of this objects and
- 3:14:11make sure all the shapes are what we
- 3:14:13expect them to be so the shape of the
- 3:14:15query key and value is a bch size by
- 3:14:18number of heads by sequence length by
- 3:14:20head Dimension we make sure that the
- 3:14:22head Dimension matches for the query key
- 3:14:25and value uh they should match because
- 3:14:28each Vector should should be of the same
- 3:14:30size uh and then we declare what we
- 3:14:34pre-allocate the output Vector so where
- 3:14:37we should save our output so as you
- 3:14:39remember the output in and the attention
- 3:14:41mechanism has the same same shape as the
- 3:14:44query key and value sequence where theer
- 3:14:47Quan value sequence I want to remind you
- 3:14:48is not the query value of the input of
- 3:14:51the attention which is a sequence of
- 3:14:53tokens but it's the output already of
- 3:14:55the WQ WK and WV because flesh attention
- 3:14:58is not concerned with optimizing those
- 3:15:00metrix multiplication but only the
- 3:15:02output of the WQ WK and
- 3:15:05WB so we pre-allocate the output tensor
- 3:15:08where we will store this output which
- 3:15:10has the same shape as the query key and
- 3:15:13sequence uh um Matrix
- 3:15:17actually actually no not true actually
- 3:15:20it has the same shape as the query but
- 3:15:22it may not be the same as the key and
- 3:15:24value why because there is this thing
- 3:15:26called cross attention where the query
- 3:15:29key and value are transposition are
- 3:15:33different projection through WQ WK WV
- 3:15:35not of the same input sequence but of
- 3:15:37two sequence so cross attention happens
- 3:15:40when we have a query that comes from one
- 3:15:43uh sequence and the key and value come
- 3:15:45from another sequence and they pass
- 3:15:47through their own WK and WV and they may
- 3:15:50not have the same sequence length so the
- 3:15:52shapes of the output of the tension only
- 3:15:54depends on the shape of the query
- 3:15:55sequence not of the key and value
- 3:15:58sequence this is happens during cross
- 3:16:00attention but usually in language models
- 3:16:02we always work with the self attention
- 3:16:04so that should not happen um at least in
- 3:16:07the Cal language models um then we have
- 3:16:11um the stage and later we will see what
- 3:16:13is this stage uh basically the stage
- 3:16:15it's just a number that that tells if
- 3:16:17the um operation that we are going to do
- 3:16:20later is for the causal attention or for
- 3:16:22the not causal attention and then we
- 3:16:25need to La Define our launch grid the
- 3:16:27launch grid tells us how many parallel
- 3:16:30process we need to be launched by Tron
- 3:16:33actually they will be launched by Cuda
- 3:16:34but by we always work with the Triton as
- 3:16:37an interface to Cuda so by
- 3:16:40Triton so in Tron as I said before we
- 3:16:43want to parallelize along the batch
- 3:16:45Dimension so each batch each sequence in
- 3:16:48the batch should work independently from
- 3:16:50each other not only each inside of each
- 3:16:53sequence in the batch each head should
- 3:16:55work independently from each other so at
- 3:16:57least we have a bch size multiplied by
- 3:16:59number of heads
- 3:17:02programs and for each of these program
- 3:17:05we have another uh Dimension called the
- 3:17:08we divide the query into blocks of
- 3:17:11queries so um as you remember when
- 3:17:15talking about a block matrix
- 3:17:16multiplication we don't work with the
- 3:17:17query as the original Matrix query
- 3:17:19Matrix so where each query is one vector
- 3:17:22or one token we work with group of
- 3:17:25queries so each block of queries is a
- 3:17:28group of tokens in the query
- 3:17:30sequence so we are saying that we want
- 3:17:33to launch at a number of um um kernels
- 3:17:37or blocks of threads or a group of
- 3:17:41threads along two Dimensions just like
- 3:17:44the Cuda kernel can be launched along
- 3:17:46Ong two Dimension X and Y here we are
- 3:17:48launching programs along two Dimensions
- 3:17:51one Dimensions that tells us which batch
- 3:17:54which head of which batch we are going
- 3:17:56to work with so which head of which uh
- 3:18:00batch element are we going to work with
- 3:18:05and inside this we are going to say okay
- 3:18:08this is a sequence which group of
- 3:18:11queries are we going to work
- 3:18:15with are we going
- 3:18:17to going to work with so overall and the
- 3:18:23group of queries is what is the sequence
- 3:18:25length divided by the number of queries
- 3:18:28that we want to group together so the
- 3:18:29block size Cube tells us how many
- 3:18:31queries are there in each block of
- 3:18:34queries so this CD is just the ceiling
- 3:18:37division so it is equal to let me write
- 3:18:39it here this is equal to ceiling of
- 3:18:43sequence length divide by the block size
- 3:18:46Q
- 3:18:47this tells us uh how many blocks of Q we
- 3:18:54have so let's rehearse we have a tensor
- 3:18:58that is q that is B size by number of
- 3:19:02heads and each flashh attention
- 3:19:05algorithm will work with the following
- 3:19:07the sequence length head Dimension
- 3:19:09moreover we have seen that the flesh
- 3:19:11attention has two Loops one is the outer
- 3:19:14loop among all the query blocks one is
- 3:19:16is the inner loop along all the key
- 3:19:19block we have seen that the query block
- 3:19:21can work independently from each other
- 3:19:23so we can spawn as many programs in
- 3:19:25parallel as there are number of blocks
- 3:19:28of Q because they can work in parallel
- 3:19:30so this grid tells us how many programs
- 3:19:32there are that can work in parallel then
- 3:19:34it will be the GPU that based on its
- 3:19:36resources will decide how many program
- 3:19:38actually to work in parallel if it has
- 3:19:41enough resources to make them all work
- 3:19:43in parallel wonderful if it doesn't have
- 3:19:45enough resources to make them work in
- 3:19:46par it will launch them sequentially one
- 3:19:48after another and the last Dimension is
- 3:19:51this is like the Z dimension in the
- 3:19:55Cuda in the Cuda launch grid and we
- 3:19:58don't want to use it because we don't
- 3:19:59want an additional um level of
- 3:20:03parallelism all right this is our launch
- 3:20:05grid so we will launch a number of um
- 3:20:09programs that is this one number of
- 3:20:11programs of parallel programs or number
- 3:20:14of parallel Kels and each kernel in Tron
- 3:20:17work is a group of
- 3:20:19threads which is a batch size multiplied
- 3:20:23by number of
- 3:20:25heads multiplied by number of blocks of
- 3:20:29Q so how many blocks we have in we
- 3:20:31divided the Q sequence
- 3:20:34into okay let's continue so the we will
- 3:20:38see what is this one so this m is
- 3:20:41another Matrix that we will need and
- 3:20:43it's the log sum Expo for the backward
- 3:20:45pass and we will see at the end of this
- 3:20:47video what it not at the end of this
- 3:20:49video but at the end of the forward pass
- 3:20:51what it's needed for but basically this
- 3:20:53is you can think of it as the maximum
- 3:20:56for each row um you we to to recompute
- 3:21:00the query multiply by the key in the
- 3:21:02backward pass we should also have if we
- 3:21:04don't want to recompute the maximum for
- 3:21:06hro and the normalization factor of the
- 3:21:08softmax we should save two things one is
- 3:21:10the maximum for each row and one is the
- 3:21:14uh the normalization factor however by
- 3:21:17using the log sum X trick we can only
- 3:21:19save one value which is the as you can
- 3:21:21see in the um algorithm of FL attention
- 3:21:25it's this stuff here which is uh let's
- 3:21:29see here it's this stuff here so this Li
- 3:21:33which is the maximum for each row plus
- 3:21:36the logarithm of the um of the
- 3:21:40normalization
- 3:21:41factor um and
- 3:21:43basically in when Computing the back
- 3:21:46pass we need to recompute on the Fly
- 3:21:49this block here so the square multip by
- 3:21:51the transpose of but to apply the soft
- 3:21:52Max as you remember we need to have the
- 3:21:54maximum for each row and the
- 3:21:55normalization factor so uh we don't um
- 3:21:59we don't recompute them during the
- 3:22:00backward because we have already
- 3:22:01computed them during the forward so we
- 3:22:03save this information but we don't need
- 3:22:04to save this two information separately
- 3:22:06we can aggregate it into one single
- 3:22:08value called Li and later we will see
- 3:22:10how we can use
- 3:22:12it all
- 3:22:14right so we have defined find also this
- 3:22:17one and we can proceed further so now we
- 3:22:21launch our grid our
- 3:22:24kernel don't be scared it's going to be
- 3:22:26a little long so here so we are
- 3:22:30launching the the kernel for the forward
- 3:22:33pass by defining what is the launch grid
- 3:22:36so how many of this program should run
- 3:22:37in parallel at most we are passing the
- 3:22:40query we are passing the key we are
- 3:22:42passing the values we are passing the
- 3:22:43soft Mark scale the M which is the
- 3:22:46information that we need to save for the
- 3:22:47backward pass it's actually the L in the
- 3:22:51code of the pseo code of The Flash
- 3:22:53attention algorithm here I call it m I
- 3:22:56think because also in the original code
- 3:22:58it was called
- 3:22:59M um the O where the our kernel should
- 3:23:03save its
- 3:23:05output and then as you remember uh we
- 3:23:08don't get all the nice access by um
- 3:23:14indexing tensor like we are used to in
- 3:23:16torch we only get a pointer to the
- 3:23:19starting element of q a pointer to the
- 3:23:21starting element of K and to the
- 3:23:23starting element of v and then we have
- 3:23:25to figure out all the index in the
- 3:23:28memory of the other elements how to
- 3:23:30calculate the index we need the stride
- 3:23:33because the stride tells us how many
- 3:23:35elements to skip to go from one
- 3:23:37dimension to the other and that's why we
- 3:23:39are passing the stride for each
- 3:23:40dimension of each tensor actually in our
- 3:23:43case uh we are only working with q k and
- 3:23:47V that are actually of the same D type
- 3:23:50and of the same shape so we should not
- 3:23:52need actually to pass all all the stride
- 3:23:55for each of these uh
- 3:23:57tensors um because they should have the
- 3:23:59same strides however in the original
- 3:24:02code I believe they they were passing it
- 3:24:03so I kept it so the stride allow will
- 3:24:06allow us to index these pointers to
- 3:24:10understand um to access the elements of
- 3:24:14of this tensor just by using its
- 3:24:16starting uh the pointer to the starting
- 3:24:18element and then the strides we will be
- 3:24:20able to index any element we want in the
- 3:24:23tensor then we pass the information of
- 3:24:26these shapes so the bch size the number
- 3:24:28of heads the sequence length and the
- 3:24:30head
- 3:24:31Dimension and U which is the same for
- 3:24:34all of them and then the stage the stage
- 3:24:37indicates if we are going to compute
- 3:24:38causal attention or not causal attention
- 3:24:41so let's not implement it and let's
- 3:24:43continue writing this method so the then
- 3:24:46then we need to save some information
- 3:24:48that we will be needed for the backward
- 3:24:49pass which is this context variable that
- 3:24:52I told you before so we save some
- 3:24:54information for the backward pass which
- 3:24:55is the query key and value uh which are
- 3:24:58the tensor for which we want to compute
- 3:25:00the gradient during the backward pass um
- 3:25:03and then um um we need to store also
- 3:25:07this m tensor and this o
- 3:25:10tensor um then we can we need to also
- 3:25:13store the causal uh variable so because
- 3:25:16if if we computed the caal attention
- 3:25:18during the for forward pass then during
- 3:25:21the backward pass we need to um have
- 3:25:23this information because we need to mask
- 3:25:26out the things that we don't want to
- 3:25:28contribute to the gradient but we will
- 3:25:31see that later when Computing the
- 3:25:32backward pass for now let's concentrate
- 3:25:34on this attention
- 3:25:35forward so we need to implement this
- 3:25:38forward kernel that you can see so uh
- 3:25:40underscore attention underscore forward
- 3:25:42method now a Tron kernel is just a
- 3:25:45python method with a particular
- 3:25:47decorator called Tron go.get so we copy
- 3:25:51and paste the signature so this is what
- 3:25:54makes a method become a Tron kernel and
- 3:25:58as you can see here we pass the query
- 3:26:00key and value Matrix along with other
- 3:26:02information the M Matrix please don't
- 3:26:04confuse the M Matrix with the mask that
- 3:26:07we will apply um uh on the Fly we will
- 3:26:10generate it on the Fly because we are
- 3:26:11only concerned in this case with a cal
- 3:26:13attention or not causal attention we do
- 3:26:16not accept custom masks
- 3:26:18here um then we pass the strides of all
- 3:26:21these tensors the B size the number
- 3:26:24number of heads the sequence length the
- 3:26:25head Dimension which is the shape of
- 3:26:27each of these uh tensors um and the
- 3:26:31block size Q and The Block size KV the
- 3:26:33block size Q indicates how many queries
- 3:26:36we want to group together to make one
- 3:26:38block of the Q Matrix and how the KV
- 3:26:41indicates how many keys and values we
- 3:26:43want to put together to make one block
- 3:26:45of the K and V Matrix which is what we
- 3:26:49do when we do block matrix
- 3:26:51multiplication this stage is a number
- 3:26:53that indicates if it's a caal or um not
- 3:26:56causal attention we are doing so it will
- 3:26:58be three in case it's a caal and one in
- 3:27:00case it's not
- 3:27:01causal okay the first thing that we do
- 3:27:03is to verify some information so we
- 3:27:06verify that the um the block size of the
- 3:27:10KV is less than or equal to the Head
- 3:27:13Dimension to be honest I don't think we
- 3:27:15need it with my code because I removed
- 3:27:18most of the constraints so this uh this
- 3:27:20check was also present in the original
- 3:27:22code so I kept it but it all depends on
- 3:27:24how we are later we will see what is the
- 3:27:27autot tuning process and later we will
- 3:27:28see uh what variables we are going to
- 3:27:31autotune for and how many stages we will
- 3:27:33choose how many warps we will choose etc
- 3:27:35etc so let's leave it for later you can
- 3:27:37comment it or you can keep it it
- 3:27:39shouldn't
- 3:27:40matter um the first thing that we do as
- 3:27:42I said before we launch a grid so a grid
- 3:27:46is a series of programs where we will
- 3:27:48have some identifiers like in the coda
- 3:27:50we had an identifier for the blocks on
- 3:27:52the x axis and on the y axis in Tron we
- 3:27:55get this identifier for the programs we
- 3:27:59launched um
- 3:28:02um uh sequence length divide by block
- 3:28:05size Q number of programs along the zero
- 3:28:08axis and the B size multiplied by number
- 3:28:11of heads on along the first axis of the
- 3:28:15uh green grid of the launch
- 3:28:17grid which will help us identify which
- 3:28:21um part of the query we are going to
- 3:28:23work with in this program in this uh
- 3:28:26kernel and also in which batch and on
- 3:28:29which head this program should work with
- 3:28:32so that's what we are going to do now we
- 3:28:34are trying to understand what part of
- 3:28:36the input we should work with based on
- 3:28:39the IDS of the program which corresponds
- 3:28:42to the block ID in
- 3:28:44Cuda uh so let me copy so the program ID
- 3:28:49zero indicates it's this stuff here
- 3:28:51tells us which part of the queries so
- 3:28:55which block of the queries we are going
- 3:28:56to work with why do we have a block on
- 3:28:59the query because as we saw before the
- 3:29:00output can be computed independently for
- 3:29:02each block of the queries while each
- 3:29:05block of the query has to iterate
- 3:29:07through all the key and
- 3:29:09values um so this is what will tell us
- 3:29:12what is the index of the block of the
- 3:29:14queries we are going to work with in
- 3:29:15this particular
- 3:29:16program then we can understand also
- 3:29:19which index which batch and which head
- 3:29:22this program is associated with the
- 3:29:24program ID number one is the product of
- 3:29:26the uh batch size and number of heads it
- 3:29:29means that we will have as many programs
- 3:29:31on the axis number one as there are uh
- 3:29:35indicated by this product so this
- 3:29:37product lets us understand that this uh
- 3:29:40product will tell us which batch and
- 3:29:43which head this particular program is
- 3:29:44associated with so uh to get the uh ID
- 3:29:48of the batch we just divide this number
- 3:29:50by the number of heads and it will give
- 3:29:52us the head index and to get the head
- 3:29:55index inside this batch we just do the
- 3:29:58um this number here uh modulus the
- 3:30:00number of heads
- 3:30:02okay uh the next thing that we need to
- 3:30:04do uh we need to okay first of all when
- 3:30:10we pass a tensor because as you can see
- 3:30:13here the Q parameter to this attention
- 3:30:16forward method is a tensor because it's
- 3:30:18the input of this function forward
- 3:30:20function and this forward function is
- 3:30:22called here when we do attention do
- 3:30:25apply and it's this Q stuff here and
- 3:30:28this Q stuff here has been created as a
- 3:30:30tensor so when we pass a tensor to a
- 3:30:32Triton kernel it's not really a tensor
- 3:30:35it is a pointer to the first element of
- 3:30:37that tensor in the memory now we need to
- 3:30:40understand because now we know which
- 3:30:42batch we are going to work with and
- 3:30:44which head we are going to work with we
- 3:30:46need to Index this tensor to select the
- 3:30:48right batch and the right head inside of
- 3:30:51the right batch which means that
- 3:30:53basically we have this Q uh tensor so we
- 3:30:57need to do some some sort of like some
- 3:30:59stuff like this like Q of the index
- 3:31:04batch and uh number of the number of
- 3:31:08heads in the case the the which head we
- 3:31:10are going to work with so it should be
- 3:31:12index of head and we need to select
- 3:31:15every everything that is inside this
- 3:31:17indices so we are we need to enter the
- 3:31:21tensor at the right location where the
- 3:31:23particular sequence length and head
- 3:31:25dimension for this batch and for this
- 3:31:27head starts for that we need to generate
- 3:31:30an offset in which we need to move this
- 3:31:32tensor from because this T this pointer
- 3:31:35sorry this not tensor this pointer from
- 3:31:38because this pointer is pointing at the
- 3:31:40beginning of the entire tensor so we
- 3:31:41need to move in the bch size dimension
- 3:31:44and in the number of heads dimension
- 3:31:46to do that we generate the following
- 3:31:49offset which will tell us where this uh
- 3:31:52where this particular batch and where
- 3:31:54this particular head starts in this
- 3:31:56tensor and to do that we need to do the
- 3:31:59strides we need to use the strides so
- 3:32:00what we are going to do is we are
- 3:32:02create going to create the qkv offset uh
- 3:32:06this is should be the sequence
- 3:32:08length um which will be the index batch
- 3:32:11multiplied by The
- 3:32:13Stride for the batch Dimension which
- 3:32:15will tell do how many elements we need
- 3:32:17to skip to get to the next batch and
- 3:32:20it's based and we multiply it by the
- 3:32:22index of the batch that we want so for
- 3:32:24the zero batch we don't skip anything
- 3:32:26because we already pointing to the first
- 3:32:27element of that batch but if we are at
- 3:32:30the batch one we will skip that many
- 3:32:32number of elements plus we also need to
- 3:32:35skip the some heads how many head we
- 3:32:37need to skip based on which head we are
- 3:32:38going to work with and what tells us how
- 3:32:41how to go from one head to the next The
- 3:32:43Stride of the head dimension so we
- 3:32:46multiply the index head so the head that
- 3:32:48we should be working with with the
- 3:32:50stride Q
- 3:32:52head all right then um we select now
- 3:32:58Tron helps us with a new function that I
- 3:33:02think it was quite recent that helps us
- 3:33:05index element inside of a tensor without
- 3:33:08having to deal with all the complex um
- 3:33:11indexing maths that can be confusing for
- 3:33:14beginners so I will be using few methods
- 3:33:17to help us with this um uh with this
- 3:33:22indexing and this function is called
- 3:33:25make block pointer and it's this
- 3:33:27following so basically this make block
- 3:33:31pointer takes as input a
- 3:33:33vector and sorry a pointer not a vector
- 3:33:37takes as input a pointer in this case we
- 3:33:40are
- 3:33:41saying create a
- 3:33:43block that has the following shape that
- 3:33:46is sequence length by head dimmension so
- 3:33:48let me do it one by one actually I don't
- 3:33:50want to confuse you guys with all this
- 3:33:51stuff Al together okay so take start um
- 3:33:56there is a pointer that is right now
- 3:33:58pointing at Q Plus Q KV offset so right
- 3:34:01now it is not pointing at the first
- 3:34:04batch but it's pointing exactly to our
- 3:34:06batch so the the batch that this
- 3:34:08particular program should be working
- 3:34:09with and inside this badge to the
- 3:34:11particular head that this program should
- 3:34:14be working with which is is basically
- 3:34:17saying that we have um we are pointing
- 3:34:19to a tensor that is as follows so we are
- 3:34:23pointing to the following tensors which
- 3:34:25is the right
- 3:34:27head the right uh sorry the right batch
- 3:34:30and the right head and then we are
- 3:34:32selecting everything inside so it's
- 3:34:34pointing to the first element of this
- 3:34:37particular
- 3:34:38tensor this tensor particular tensor
- 3:34:41because we have already selected the
- 3:34:42batch and the head it is a
- 3:34:44two-dimensional tensor with this the
- 3:34:46following shape because the the
- 3:34:48following dimensions are sequence length
- 3:34:50and head dim so we are saying take this
- 3:34:53pointer which contains a tensor of the
- 3:34:57following shape sequence length and head
- 3:34:59Dimension and I'm also giving you the
- 3:35:02strides of this Dimensions that are in
- 3:35:05this pointer so the the the two
- 3:35:07Dimensions that are that we need are the
- 3:35:09sequence Dimension and the head dim
- 3:35:11Dimension which is this one for the Q
- 3:35:14tensor and
- 3:35:18um and in this um in this
- 3:35:22query uh tensor we want to
- 3:35:26select a block of queries based on the
- 3:35:30query on the block of queries that this
- 3:35:32program should be working with so I
- 3:35:35think I need to maybe probably use the
- 3:35:37iPad otherwise it can be very confusing
- 3:35:39to visualize so uh let's do it actually
- 3:35:43so let me see if I can create another
- 3:35:45another here and let's use the
- 3:35:52iPad all
- 3:35:55right okay so we have a Q Vector Q
- 3:36:00tensor because this construct we will be
- 3:36:02using it for all the other tensor so if
- 3:36:03you understand it for one tensor you
- 3:36:05understand it for all the others we have
- 3:36:07a Q tensor that is a
- 3:36:09batch uh by number of
- 3:36:13heads number of heads then the sequence
- 3:36:17length and then the head
- 3:36:24Dimension with the following line so the
- 3:36:27this line here so when we create Q Plus
- 3:36:31uh qkv offset we are already selecting
- 3:36:34the right batch Dimension and already
- 3:36:37the right head Dimension which means
- 3:36:40that we have already forwarded our Q to
- 3:36:44not point to the first batch and the
- 3:36:46first head but to point to the exact
- 3:36:49batch that this program is working with
- 3:36:51and the exact head that this program is
- 3:36:53working with which basically means that
- 3:36:55right now it is pointing at a tensor
- 3:36:57that is made up of these two
- 3:37:00Dimensions now inside of this tensor we
- 3:37:03also need to select the right block of
- 3:37:06query that this program should work with
- 3:37:09and this Dimension here so the sequence
- 3:37:12Dimension is all the queries so we need
- 3:37:15to select select the right queries so we
- 3:37:17need to skip some queries how to skip
- 3:37:19some queries well we say that we need to
- 3:37:22skip block index multiplied by block
- 3:37:25size Q number of queries because they
- 3:37:28will be processed by another um by
- 3:37:31another uh program that will have this
- 3:37:35number here the program ID will be
- 3:37:37different so we are selecting with this
- 3:37:40line not only inside of the que the
- 3:37:44right index and the head but also the
- 3:37:46right position in this dimension in the
- 3:37:48sequence length Dimension that will
- 3:37:50point to the exact to the starting point
- 3:37:52of the exact query block that this
- 3:37:55particular program should be working
- 3:37:56with this is what it's happening and we
- 3:37:59are also creating this block basically
- 3:38:02later we will see how it can be used um
- 3:38:05to uh to create a block of the shape uh
- 3:38:08we are telling what is the the size of
- 3:38:11this tensor so this tensor has two
- 3:38:14Dimensions because we are pointing to
- 3:38:16the beginning of the right query
- 3:38:19sequence so it has only two Dimensions
- 3:38:21the sequence Dimension and the head dim
- 3:38:23Dimension so it's the last
- 3:38:24Dimension um and we are already pointing
- 3:38:27to the right beginning of the sequence
- 3:38:30uh Dimension because we have already
- 3:38:32skipped some queries why we are skipping
- 3:38:35some queries because these queries will
- 3:38:36be handled by another program that will
- 3:38:38have a block index Q to some other
- 3:38:41values um and this order uh actually I
- 3:38:46don't know what is this order you can
- 3:38:47try to put 01 and one two I think it's
- 3:38:49some optimization that Triton does I
- 3:38:51have read the online documentation and I
- 3:38:52couldn't find anything about it so this
- 3:38:55is something that I will investigate but
- 3:38:57actually even if you put a 01 it doesn't
- 3:39:00matter so I think it's something that
- 3:39:02you tell Triton uh if this you want the
- 3:39:06transposed of this block or you want the
- 3:39:08not transposed version of this block and
- 3:39:09later we will see actually how we can
- 3:39:11transpose the key block without doing
- 3:39:13any transpose operation actually we we
- 3:39:15will just change the strides like we
- 3:39:17have seen before so um now this make
- 3:39:22block pointer is not something that is
- 3:39:25necessary but it makes our life easier
- 3:39:27when we will Index this particular
- 3:39:30pointer so we can treat this pointer
- 3:39:32nearly as um nearly in the same way when
- 3:39:35we work with the tensor in pytorch we
- 3:39:38will be able to skip one uh increase uh
- 3:39:41one index in one dimension without
- 3:39:43having to do the computation of the
- 3:39:45strides later when doing the backward
- 3:39:48pass I will not use this one and do all
- 3:39:50the pointer indexing by hand so you can
- 3:39:52check the differences of indexing a
- 3:39:54tensor by using make block pointer and
- 3:39:56not by using it anyway to rehearse what
- 3:39:59are we creating we are creating a
- 3:40:01pointer to the right index in the batch
- 3:40:05to the right index in the head Dimension
- 3:40:07and we are already skipping some queries
- 3:40:10based on the Block index que so this
- 3:40:14pointer is already point to the right
- 3:40:16block of queries that this particular
- 3:40:17program should be working with let's
- 3:40:19look Instead at the V and the K block
- 3:40:23now so let's copy the V block now which
- 3:40:28is similar to the query but we are not
- 3:40:30going inside we are only indexing by the
- 3:40:34index badge and the index head so what
- 3:40:37this one actually let me write it here
- 3:40:39is already skipping
- 3:40:41so this amount of
- 3:40:44queries this is what we are indexing
- 3:40:46with this make block pointer so we are
- 3:40:49in the right batch in the right head and
- 3:40:51we are skipping some
- 3:40:52queries here we are just indexing by
- 3:40:57batch and by head so we are doing V of
- 3:41:00index batch index head and we are not
- 3:41:05selecting we are not skipping anything
- 3:41:07because you see this offset is equal to
- 3:41:09zero in the First Dimension in the
- 3:41:11second dimension so we are not skipping
- 3:41:13anything on the sequence length and we
- 3:41:14are not SK anything in the head
- 3:41:16dimmension Dimension head Dimension
- 3:41:20Dimension um all right so let's look at
- 3:41:23the K block pointer and this is
- 3:41:26different because as you know when
- 3:41:28Computing the flashh attention algorithm
- 3:41:30we need to have access to the block of
- 3:41:32queries and all the block of the key
- 3:41:36transposed so when accessing the key we
- 3:41:39shouldn't access it like we are
- 3:41:41accessing Q we should invert the two uh
- 3:41:44Di Dimensions that we want to transpose
- 3:41:46for and that's very simple with make
- 3:41:49block PTR and you can see it here we say
- 3:41:52that we want to point to the right index
- 3:41:55and to the right head and the tensor be
- 3:41:59inside of it so let's let me write it
- 3:42:01here so later I can explain in line by
- 3:42:03line so what we are doing here is go to
- 3:42:05the K tensor select the right batch
- 3:42:08select the right head select everything
- 3:42:12that is inside so it's a tensor of two
- 3:42:14Dimensions with the sequence length and
- 3:42:16the head dim because we we you can see
- 3:42:18here um here uh sequence length and head
- 3:42:22dims Etc but we don't want first
- 3:42:25sequence length and then head dim we
- 3:42:28want first head dim and then sequence
- 3:42:29length so we want to transpose it how to
- 3:42:31transpose it we just say that you need
- 3:42:33to read this tensor with the two strides
- 3:42:36transposed so we are saying first use
- 3:42:38the stride of the dimension Dimension
- 3:42:41and then use the stride of the sequence
- 3:42:43Dimension and the shape of this uh
- 3:42:47tensor is not sequence uh head dim it's
- 3:42:51head dim sequence and it's a block of
- 3:42:56KVs um why we are not putting directly
- 3:43:00the sequence Dimension here because we
- 3:43:03want to skip block by block later so we
- 3:43:06are not selecting all the sequence
- 3:43:08length in the sequence Dimension we are
- 3:43:09just selecting a block of KVs and later
- 3:43:12we will use another method to go to the
- 3:43:14next block
- 3:43:15so I hope that by showing you the
- 3:43:18indexing like this it's a little easier
- 3:43:20to follow the indexing so for each
- 3:43:23tensor we are going in the right batch
- 3:43:24in the right head Dimension and for the
- 3:43:27query we are skipping some query blocks
- 3:43:29because each each program will work with
- 3:43:32a small different um query block but for
- 3:43:35the key and value each program needs to
- 3:43:38iterate through all the key and value so
- 3:43:40we just point it to the first key and
- 3:43:42value block and then we will advance by
- 3:43:44one block by um we will advance uh one
- 3:43:47block uh by one during the for Loop that
- 3:43:50we will do
- 3:43:51later then in the output also we need we
- 3:43:55can make um a tensor block
- 3:43:58tensor this basically creates a pointer
- 3:44:01just like in the query key and value
- 3:44:02case in which we select the right index
- 3:44:05batch so what we are doing is we are
- 3:44:07indexing by
- 3:44:08batch we are indexing by head and we are
- 3:44:12selecting everything that inside Unown
- 3:44:14we are not cting everything inside we
- 3:44:16are skipping also in this case some
- 3:44:18blocks of queries uh because as I said
- 3:44:21before the output has the same shape as
- 3:44:24the query so um the this particular
- 3:44:28block this particular program that we
- 3:44:30that will have this particular block
- 3:44:33index Q will only work with one block of
- 3:44:35uh the queries which will produce only
- 3:44:37one block of the output Matrix and we
- 3:44:40need to select exactly that one so we we
- 3:44:43can point this pointer exactly to the
- 3:44:45point where we should start writing so
- 3:44:48let's skip also in this case block index
- 3:44:51Q multiplied by block size Q um
- 3:44:56rows so we select exactly the block that
- 3:44:59our um our program this particular
- 3:45:03program will produce when I speak about
- 3:45:06this particular program I mean the
- 3:45:09program that is identified by this
- 3:45:11program ID in the xzero axis and this
- 3:45:14program ID in the first axis because
- 3:45:16each of these program will run in
- 3:45:18parallel hopefully and each of them will
- 3:45:20have a different value for the block
- 3:45:21index q and index batch
- 3:45:24head okay now we have pointed our
- 3:45:27pointers to the right position where
- 3:45:29they should either read some information
- 3:45:31or they should either write some
- 3:45:33information by using make block pointer
- 3:45:35these uh pointers can also be treated
- 3:45:37directly as tensors so that's why we
- 3:45:39specify the shapes of these tensors
- 3:45:42because python uh Tryon right now
- 3:45:43provides some methods to work directly
- 3:45:46with uh blocks of um to work directly
- 3:45:51with pointers like they are we are
- 3:45:53accessing um tensors so we can index
- 3:45:56them like
- 3:45:57tensors all right so basically just try
- 3:46:01on doing some calculation for you based
- 3:46:03on the strides so you don't have to do
- 3:46:05it by hand but later when we do the back
- 3:46:06part T we will avoid using make block
- 3:46:09pointer and we will see the indexing
- 3:46:10done by
- 3:46:12hand all right uh um as you know we are
- 3:46:16processing a single block of queries so
- 3:46:20let let's go back to the um algorithm
- 3:46:23otherwise we we lose uh the site of what
- 3:46:26we are
- 3:46:27doing so let's go here and let's show my
- 3:46:31iPad all right so as you know each
- 3:46:34program we will parallelize along the
- 3:46:37query block Dimension so each program
- 3:46:39will work with a different query block
- 3:46:41and then we need to do a for loop on all
- 3:46:43the key and values
- 3:46:45blocks right now we just uh moved our
- 3:46:49pointers to the right position to select
- 3:46:52the right query block that we should
- 3:46:53work with and to the beginning of the
- 3:46:56keys and values block that we should
- 3:46:58work with based on which index and which
- 3:47:00head this particular program should be
- 3:47:02working
- 3:47:04with all right now that we have pointed
- 3:47:06our pointers to the right position in
- 3:47:08which our program should be working it
- 3:47:10inside of the big pointers that are um
- 3:47:14inside of the big tensors that are the
- 3:47:17that have the batch Dimension the number
- 3:47:20of heads Dimension the sequence length
- 3:47:23Dimension and the head Dimension we have
- 3:47:25because we are pointing to the right
- 3:47:27batch and we are pointing to the right
- 3:47:28head these tensors have become two
- 3:47:30dimensional tensors so they only work on
- 3:47:33the they are only tensors on the
- 3:47:35sequence length and on the head
- 3:47:37Dimension now we need some mod some more
- 3:47:40information that we will use
- 3:47:42later the first information that we we
- 3:47:44need is the offsets of each query inside
- 3:47:49of the current block of queries that
- 3:47:51this particular program should be
- 3:47:52working with and that is given by the
- 3:47:55following line so let me copy and paste
- 3:47:59which is this one so the offsets of the
- 3:48:02queries are the first of all they are
- 3:48:07how many of them block size Q because
- 3:48:09each block of queries is made up of
- 3:48:11block size Q number of queries what is
- 3:48:14each where it's a token and it's on the
- 3:48:17head Dimension is um the dim Dimension
- 3:48:20is not the all the embedding of the
- 3:48:23token but a part of the embedding of
- 3:48:25each token which part the part
- 3:48:27corresponding to the head that this
- 3:48:29particular program is going to work with
- 3:48:32so we are generating the offsets that
- 3:48:34will load this particular number of uh
- 3:48:36this particular queries from the big
- 3:48:38tensor that contains all queries and we
- 3:48:41know that our queries start at the Block
- 3:48:43index cu multiplied by block size Q
- 3:48:46position so if this is the program
- 3:48:49number zero they will the Imagine block
- 3:48:51size is equal to four they will be the
- 3:48:53query with index 0 1 two and three but
- 3:48:57imagine we are the program number three
- 3:49:00which means that we need to skip um
- 3:49:02three multiplied by four so 12 so it
- 3:49:05will point to the query number 13 14 15
- 3:49:09and 16 etc etc
- 3:49:11etc all right and we do the same for the
- 3:49:14key and values initially the key and
- 3:49:17values um is a range of keys and values
- 3:49:21that we need at e each iteration and at
- 3:49:23the beginning because our pointer for
- 3:49:26the K andv is pointing to the beginning
- 3:49:29of the sequence of key and value for
- 3:49:31this particular badge and for this
- 3:49:32particular head we are pointing to the
- 3:49:35first block of key and value so we are
- 3:49:37not skipping anything in the query case
- 3:49:39we are skipping because our program will
- 3:49:41only work with one single block of
- 3:49:42queries in this case we don't skip
- 3:49:45anything because we need to iterate
- 3:49:46through these key and values so we are
- 3:49:48pointing to the first uh block of key
- 3:49:51values so imagine block size KV is equal
- 3:49:53to four so this stuff here will be equal
- 3:49:55to zero 1 2 and
- 3:49:57three all right now we need as you
- 3:50:02remember inside of the flashh atten
- 3:50:03algorithm we need to compute a block of
- 3:50:06query multiplied by the transpose of the
- 3:50:08keys and to each of this block we need
- 3:50:10to apply the soft Max star if you
- 3:50:13remember what is the soft Max star is
- 3:50:14the soft Max of without the
- 3:50:18normalization so while Computing the
- 3:50:20soft Max star we also actually compute
- 3:50:22the normalization factor without
- 3:50:24applying it and we apply the
- 3:50:25normalization factor at the end so for
- 3:50:27each block of query multiplied by
- 3:50:30transpose of the keys we need to have
- 3:50:32the maximum for each row in this
- 3:50:34particular block and the normalization
- 3:50:36factor for each row so that's why why we
- 3:50:39need these two following
- 3:50:41statistics which is this one and this
- 3:50:44this is basically um a block uh it's a
- 3:50:48block of numbers how many based on how
- 3:50:51many queries we have in our block of
- 3:50:53queries each one initialize with minus
- 3:50:55infinity just like in my algorithm that
- 3:50:57I show before so let me go back to the
- 3:50:59slides in case we forgot um or actually
- 3:51:03you can also check the flash attention
- 3:51:04algorithm we initialize it with minus
- 3:51:06Infinities so so far we are creating
- 3:51:08this stuff here so we are initializing
- 3:51:09the Mi we are we will be initializing
- 3:51:11the LI I and we will initializing the o
- 3:51:15and then we will show the inner loop
- 3:51:17here um and this is exactly the
- 3:51:19algorithm that we have seen before so we
- 3:51:21initialize M with minus
- 3:51:23Infinities now we initialize also the
- 3:51:25L's so let me go back to the
- 3:51:28code uh all
- 3:51:32right so the L's are initialized with
- 3:51:36this number here so
- 3:51:39here in the O blocks as we can see from
- 3:51:42the flashh algorithm they are the O
- 3:51:44Block is initialized with zeros so
- 3:51:46that's why we initialize a block this is
- 3:51:48the output block that this particular
- 3:51:50program will compute which is based on
- 3:51:52the position in the batch and the
- 3:51:55position in the indexes so it is one
- 3:51:57block of the size block size Q so how
- 3:51:59many queries there are in this block by
- 3:52:01head
- 3:52:02Dimension um which if you want to
- 3:52:05visualize it let's go back to the slides
- 3:52:08it is equal
- 3:52:10to one block of this Matrix here so it's
- 3:52:14one one block of the output Matrix so
- 3:52:17one row of blocks uh one block of
- 3:52:20rows uh okay so let's go back to the
- 3:52:24code
- 3:52:25now all right so now we have initialized
- 3:52:29little stuff here so the output the Mi
- 3:52:32and Li where Mi is the maximum for each
- 3:52:35row in this particular query block and
- 3:52:37the LI is the normalization factor for
- 3:52:40each of the um items in the query for
- 3:52:44each of
- 3:52:45the rows in our query
- 3:52:48block now we need to do the for Loop the
- 3:52:51inner loop in the flashh attention
- 3:52:53algorithm uh we will create a separate
- 3:52:56method that will run the inner loop so
- 3:52:59let's let me copy
- 3:53:01it here and I am following the same
- 3:53:04structure of the code that you see in
- 3:53:05the tutorial of the Tron
- 3:53:08website so um basically if we are
- 3:53:11running the Cal attention or even if we
- 3:53:14are not running the Cal attention we
- 3:53:15make this for Loop and then we will make
- 3:53:18another for Loop and I will show you why
- 3:53:21so let me first write it and then we
- 3:53:24will see so this function here will be
- 3:53:27the inner loop this inner loop needs to
- 3:53:29go through all key and value blocks one
- 3:53:32by one and for each query and value
- 3:53:36block it needs to fix the previous
- 3:53:39calculated block of uh the the previous
- 3:53:42softmax star block so basically what we
- 3:53:45are doing here we will need to create a
- 3:53:48function as the following where we are
- 3:53:51going to iterate on all the key value
- 3:53:53block we will need to compute the query
- 3:53:55multiply by the transpose of the keys
- 3:53:57using the query block that is fixed for
- 3:53:59this program and the key is block is the
- 3:54:02one that we are iterating it through and
- 3:54:04for each of these queries we need to
- 3:54:06calculate what is the maximum for each
- 3:54:08row we need to compute the softmax star
- 3:54:11so the softmax without the normalization
- 3:54:14factor
- 3:54:15we need to keep the statistics L which
- 3:54:17is the normalization factor that we will
- 3:54:19apply at the end of the iteration of the
- 3:54:22for Loop and at the same time we need to
- 3:54:26update the output so as you remember the
- 3:54:28output is P11 * by V1 plus p12 * by vs2
- 3:54:34but we need to fix the previous P11 so
- 3:54:37to fix that we need to every time we sum
- 3:54:39to O to the output we need to fix the
- 3:54:43output of the previous
- 3:54:45iteration um and then we increase
- 3:54:49introduce the p and v block of the
- 3:54:51current iteration so um here the author
- 3:54:56of The the code for the the one that you
- 3:54:58see on the Tron website decided to split
- 3:55:02this for Loop into two steps why because
- 3:55:06in the causal attention we need to uh
- 3:55:09when we have a caal attention we have a
- 3:55:12group of um we we don't we don't want
- 3:55:14the query to attend keys that come after
- 3:55:17it while in the non-causal attention we
- 3:55:20let all the queries attend to all the
- 3:55:22keys which also means that we will need
- 3:55:24to have some kind of if statement inside
- 3:55:27of this if U inside of this for Loop
- 3:55:29through all the key and values in which
- 3:55:31we need to check if the this particular
- 3:55:34query that we are working with is comes
- 3:55:38before or after the key and value in
- 3:55:40case we are doing the caal attention so
- 3:55:42instead of uh iterating through all the
- 3:55:45keyan values also in the case of the Cal
- 3:55:48attention by splitting it into two uh
- 3:55:51steps we are saying uh first let's
- 3:55:54iterate through all the keyan values for
- 3:55:57which the index is smaller than the
- 3:55:59current queries block and for this we
- 3:56:02need to compute the attention in the
- 3:56:04case of the causal and non-causal case
- 3:56:07then for all the elements on the right
- 3:56:10of this block so for which the key index
- 3:56:13is more than the Q index in the case of
- 3:56:15causal attention we don't need to
- 3:56:17compute anything because it will be
- 3:56:19masked out because in the soft Max it
- 3:56:21will become zeros so it will not
- 3:56:23contribute to the output so we don't
- 3:56:25even have to compute
- 3:56:26it um this is why we split this this for
- 3:56:30Loop into two steps so first we iterate
- 3:56:33to all the parts that are left to the
- 3:56:35diagonal of the query multiplied by the
- 3:56:37key
- 3:56:38Matrix so for all the values for which
- 3:56:41the query index is less than the key
- 3:56:43index then we um and then we skip all
- 3:56:48the parts to the right of this diagonal
- 3:56:50in case we are working with a cal mask
- 3:56:52but in case of the non-causal Mask we
- 3:56:53compute the left part and the right part
- 3:56:55of this
- 3:56:56diagonal all right don't worry when we
- 3:56:59recorde this for Loop it will be more
- 3:57:00clear so I just wanted to give a little
- 3:57:03introduction so let's go uh code this
- 3:57:05inner loop what will this inner loop do
- 3:57:08it will work with this particular query
- 3:57:10block that we have found so this Q block
- 3:57:14it will uh why I don't see the Q block
- 3:57:17because I didn't load it well yeah uh
- 3:57:20let's load it so we need to load the
- 3:57:22query block actually we forgot to load
- 3:57:24it so as you remember in Tron we we load
- 3:57:27um data from the high bandwidth memory
- 3:57:30to the SRAM so to the shared memory by
- 3:57:32using the load statement and we are
- 3:57:34telling load the query block that we
- 3:57:37should be working with because this
- 3:57:38pointer Q block PTR is already pointing
- 3:57:41to the right block that we should be
- 3:57:43working with so it's already skipping
- 3:57:45all the blocks that other programs
- 3:57:47should be working with and it will load
- 3:57:51a uh a tensor of size of block size Q
- 3:57:54had dim so the right block of
- 3:57:58queries and we pass it to this inner
- 3:58:00loop to which we pass the output so
- 3:58:03where it should write this output the Li
- 3:58:06and Mi which are the statistics for the
- 3:58:09rows and for for the maximum for each
- 3:58:12row of each query and the LI I which is
- 3:58:14the normalization factor for each query
- 3:58:17and the query block this program should
- 3:58:19be working with the beginning of the key
- 3:58:22and value block pointer because we need
- 3:58:24to iterate through them so we just point
- 3:58:27it to the beginning and then inside the
- 3:58:28for inner for Loop we will iterate
- 3:58:30through them then the soft Max scale
- 3:58:32that we should use when Computing query
- 3:58:34multiplied by the transpose of the keys
- 3:58:37the block size so how many queries we
- 3:58:39have in each block of Q and how many key
- 3:58:41and value we have in each block of KV
- 3:58:45uh this is a stage that tells us what uh
- 3:58:48if we are on the left side of the
- 3:58:49diagonal or on the right side of the
- 3:58:51diagonal so it will tell us if we need
- 3:58:52to apply the Cal mask or not based on
- 3:58:55where we are and if we are need to apply
- 3:58:57the Cal
- 3:58:58mask um the offset q and the offset KV
- 3:59:02are just the offsets of the query and
- 3:59:04key inside of each q and KV block which
- 3:59:07is a list of indices that tells us um
- 3:59:12how many queries we have
- 3:59:15uh and then the sequence length the
- 3:59:17entire sequence length because in the
- 3:59:19for Loop we need to iterate to all the
- 3:59:21sequence length block by block so block
- 3:59:23of KV block of KV block of KV all right
- 3:59:26let's write this me let's write this
- 3:59:28method and later we need actually need
- 3:59:30to continue this method again so let's
- 3:59:33go and let me go
- 3:59:39here all right
- 3:59:44so uh this method we have already seen
- 3:59:47the signature so it's just another
- 3:59:49kernel so it can be called by the first
- 3:59:51kernel and this is something you can
- 3:59:53also do in Cuda you can actually call
- 3:59:56call one Cuda kernel from another Cuda
- 3:59:58kernel um and then we based on the stage
- 4:00:03of this inner loop we decide what we
- 4:00:05need to do so when we are using caal um
- 4:00:10causal attention so we only want to
- 4:00:13apply the um attention to the queries
- 4:00:16for which the index is less than or
- 4:00:18equal to the key so we only want the
- 4:00:20query to never attend to key and value
- 4:00:23that come after it then um we pass the
- 4:00:27value three for the stage parameter now
- 4:00:31when we in the Cal case this will become
- 4:00:344 minus 3 it is equal to 1 so what will
- 4:00:36happen is that we will only work with
- 4:00:40the range of um keys and values that are
- 4:00:44are from zero up to the current block of
- 4:00:46Q so all the keys that whose index is
- 4:00:49less than or less than the the the index
- 4:00:53of the queries we are working with so to
- 4:00:55the left part of the Cal mask let me
- 4:00:58draw it otherwise I think it's going to
- 4:01:00be very difficult to follow so let's do
- 4:01:02it actually so let's open a new one and
- 4:01:06let's go here all right so we have been
- 4:01:09using this one before so we can do it
- 4:01:12again clear page all right in this now I
- 4:01:17I want you to think of the following uh
- 4:01:20Matrix as a block Matrix so let's draw
- 4:01:22it in pink because I have been drawing
- 4:01:24it all in pink we know that in the rows
- 4:01:27of this query multiplied by the
- 4:01:28transpose of the keys we have a uh the
- 4:01:31queries blocks of queries so we are not
- 4:01:35watching one single block we are
- 4:01:36watching all the blocks right now so
- 4:01:38this is the query block one this is the
- 4:01:40query block two this is the query block
- 4:01:41three this is the query block four each
- 4:01:44of this query block is made up of
- 4:01:45multiple tokens of queries and then we
- 4:01:49have the key the key
- 4:01:51blocks uh let's do it like this very
- 4:01:55ugly but okay uh key 1 key block two key
- 4:01:58block three key block four when apply
- 4:02:02calculating the attention when you
- 4:02:03calculate the caal attention so um like
- 4:02:07with the causal mask you want only the
- 4:02:10query to attend to keys that come before
- 4:02:13it so when we apply the causal mask this
- 4:02:16stuff here will be made up of zeros this
- 4:02:18stuff here will be made up of zeros this
- 4:02:20stuff here will be made up of zeros and
- 4:02:21this stuff here and this stuff here and
- 4:02:23this stuff here all made up of
- 4:02:25zeros we never have to mask out anything
- 4:02:28when we are in this case
- 4:02:30because well when we are in this
- 4:02:32particular scenario actually in this
- 4:02:34particular scenario we don't need to
- 4:02:35mask out anything for sure why because
- 4:02:38all the key um keys in this block so in
- 4:02:43this block of keys keys will have an
- 4:02:45index that is smaller than the index of
- 4:02:46the corresponding queries in case the uh
- 4:02:49the key the block size of the query and
- 4:02:52the key matches so imagine each query is
- 4:02:54made up of three queries so each block
- 4:02:56of query is made up of three queries so
- 4:02:59this is the query number 0 1 and two
- 4:03:02this is the query number 3 4 five really
- 4:03:063 4 five yeah this will be the number uh
- 4:03:09six 7 and eight and this will be the
- 4:03:12query number nine 10 10 and 11 in total
- 4:03:15we have 12 queries we will have the same
- 4:03:17indices also for the keys in case we
- 4:03:19choose the same uh size for the blocks
- 4:03:23so this key key block here will be the
- 4:03:26key number 0 1 and
- 4:03:29two this will be the key number three
- 4:03:32four five this will be the six six 7 and
- 4:03:37eight etc etc ET now what happens is
- 4:03:40that in this case as you can see the key
- 4:03:43in this in indices of the keys are
- 4:03:45always smaller than the indices of the
- 4:03:47queries so we don't need to mask out
- 4:03:49anything even in the case of the Cal
- 4:03:51mask because we are sure that in this
- 4:03:53case all of these dot products will
- 4:03:56never be masked out also in this case
- 4:03:58all these dot products will never be
- 4:03:59masked out and also in this case we'll
- 4:04:01never be masked out we'll never be
- 4:04:02masked out and we'll never be masked out
- 4:04:04and in this case however along the
- 4:04:07diagonal some of the queries will be
- 4:04:10more have will have an index that is
- 4:04:13bigger than than that of the keys and
- 4:04:15some of them will not be uh will not
- 4:04:17have an index that is bigger than that
- 4:04:19of the keys because these are blocks of
- 4:04:22queries and blocks of keys some of them
- 4:04:24need to be masked out and some of them
- 4:04:26don't need to be masked out so we are
- 4:04:28dividing our for Loop into multiple
- 4:04:30steps the first step that we are doing
- 4:04:32is all to the left of this diagonal in
- 4:04:35which we don't need to mask out anything
- 4:04:37then we will see another step here in
- 4:04:40which we um uh we need to mask out and
- 4:04:43then everything to the right of this
- 4:04:46will be we will not even compute in the
- 4:04:48case of cation because we already know
- 4:04:50it's made up of zero so it will not comp
- 4:04:52so the product query multiplied by the
- 4:04:54by transpose of the keys after the
- 4:04:55softmax will be made up of zeros so if
- 4:04:58you look at the flesh attention
- 4:04:59algorithm so um this stuff here the
- 4:05:02contribution will be zero because we are
- 4:05:04multiplying zero with v it will be zero
- 4:05:06so we don't need to change the output so
- 4:05:08why even compute this part of the Matrix
- 4:05:11if we already know it's not going to
- 4:05:12contribute to the output so we just skip
- 4:05:14all those iterations and this is why we
- 4:05:16are splitting the for loop I hope now
- 4:05:18it's much more
- 4:05:20clear all right so let's go back um okay
- 4:05:25so uh we are now to the left part of the
- 4:05:27diagonal in case of the stage number one
- 4:05:29in the case of the stage number two it's
- 4:05:31the part in exactly on the diagonal so
- 4:05:34in which we need to do some dot products
- 4:05:36and some other dot products we don't
- 4:05:38need to do and then for the non-causal
- 4:05:40attention we just go through the from
- 4:05:42zero to the sequence length without
- 4:05:44doing this
- 4:05:45multi-step
- 4:05:47um because we don't need to mask out
- 4:05:49anything so this is why we have this
- 4:05:50stage this tells us what is the lower
- 4:05:53and higher index of the key block that
- 4:05:56this particular stage should be working
- 4:05:58with all right um now this function here
- 4:06:03multiple of is just telling Tron that
- 4:06:06this number here is a multiple of this
- 4:06:08number so Tron can make some
- 4:06:11optimizations so the stage one happens
- 4:06:13when
- 4:06:14when we are doing a causal attention so
- 4:06:17stage number three in this function and
- 4:06:204 minus 3 will become one so imagine we
- 4:06:22are in the causal attention we will go
- 4:06:24through the key and value block that are
- 4:06:27to the left of the uh diagonal with
- 4:06:30respect to the query block that we are
- 4:06:32working
- 4:06:33with um in the case we are doing not
- 4:06:36causal attention in this first call to
- 4:06:39the uh inner function this the stage
- 4:06:42will be one so the uh four minus stage
- 4:06:45will be equal to three so we will
- 4:06:47execute this part of the if statement so
- 4:06:49we will go through all the key and
- 4:06:51values in
- 4:06:53case uh for the Cal attention only as
- 4:06:56you can see here we will do another
- 4:06:58iteration here that will only be done
- 4:07:00along the diagonal in which we need to
- 4:07:02mask out something and we don't need to
- 4:07:04mask out something because inside of
- 4:07:06each blocks there will be some keys that
- 4:07:08have the index uh below the index of the
- 4:07:11query and some that have above the index
- 4:07:13of the query quy so only in the Cal
- 4:07:15attention we will call this function
- 4:07:17twice the first time with Stage equal to
- 4:07:20one and the second time with Stage equal
- 4:07:23to two and the second time we will only
- 4:07:25iterate through the group of kyv blocks
- 4:07:29that are exactly on the diagonal of the
- 4:07:33um Matrix S multiply by transpose of the
- 4:07:35keys the big Matrix that is made up of
- 4:07:37all the
- 4:07:38blocks all right now that this should be
- 4:07:41clear let's proceed further so let's um
- 4:07:45because we need to do the for Loop the
- 4:07:46inner for Loop of the flashh attention
- 4:07:49let's go and load the first blocks of
- 4:07:52key and values which is exactly the one
- 4:07:54that the key and V blocks are currently
- 4:07:57pointing at which is the Zer z00
- 4:08:01block so uh we we defined the the
- 4:08:04pointers basically um we we we point the
- 4:08:08key and value blocks to the first uh key
- 4:08:11and value block that this uh for Loop
- 4:08:14should be working with which will be
- 4:08:16based on the stage so if it's the first
- 4:08:18call to this function they will be
- 4:08:20pointing to the first block in the case
- 4:08:22of the uh causal and non causal if it's
- 4:08:26the second call to this function which
- 4:08:27only happs happens in the case of the
- 4:08:29causal attention they will be pointing
- 4:08:32exactly to the key and value block to
- 4:08:33the
- 4:08:34diagonal all right then we need to make
- 4:08:37the for
- 4:08:38Loop so let's Loop over all the for Loop
- 4:08:42so let's do it
- 4:08:44so Loop over the key and value and what
- 4:08:48we do is um okay we we let the compiler
- 4:08:52know that this number here the start KV
- 4:08:55will always be a multiple of the block
- 4:08:56size KV because we will be moving from
- 4:08:59one KV block to the next KV block block
- 4:09:01by block so we let the compiler know
- 4:09:04that this number here start KV is a
- 4:09:06multiple of block size KV it doesn't
- 4:09:07change anything from a logic point of
- 4:09:09view we are just telling giving some
- 4:09:10hint to the compiler so it can do some
- 4:09:13other optimization that Tron does um now
- 4:09:18the first thing that we see in the flash
- 4:09:19attention algorithm is we need to
- 4:09:21compute the product of the query so this
- 4:09:24the particular block of the query that
- 4:09:25we are working with with the current KV
- 4:09:28Block in this iteration so let's do it
- 4:09:31so we compute K andv so we load the the
- 4:09:36the query have already been loaded by
- 4:09:37the color of this function we have
- 4:09:39loaded it
- 4:09:41here here we have a already loaded the
- 4:09:44query but we need to load the current
- 4:09:45block of K so we load the current block
- 4:09:49of K indicated by the K pointer and we
- 4:09:53multi we do the matrix multiplication of
- 4:09:55the current block of query the the block
- 4:09:58of query with the current block of K
- 4:10:01which is already transposed because when
- 4:10:03we loaded this k k when we defined the K
- 4:10:07block pointer we defined it already with
- 4:10:10the stride changed so we are reading the
- 4:10:12T already already transposed so we are
- 4:10:14doing the query multipli by the
- 4:10:16transpose of the keys
- 4:10:18basically okay now let's do
- 4:10:23here this part here basically
- 4:10:26saying okay if the stage is to when the
- 4:10:29stages to is when we are exactly on the
- 4:10:31diagonal we know that some of the
- 4:10:33queries will have an index that is
- 4:10:35bigger than that of the keys and some of
- 4:10:37them we have an index that is smaller
- 4:10:38than that of the keys so we need to
- 4:10:40apply the Cal mask only in this case so
- 4:10:44uh basically what we do is we Define the
- 4:10:47mask that we should be applying so the
- 4:10:49mask will mask out all the values for
- 4:10:53which this mask is not true so when this
- 4:10:56mask is true when the index of the query
- 4:10:59is more than the index of the K and vs
- 4:11:03and um we uh okay we apply the soft Max
- 4:11:06scale so as you remember we here we only
- 4:11:09computed query multiplied by the
- 4:11:10transpose of the keys but we also need
- 4:11:11to divide by the square root of head
- 4:11:14Dimension and we do it
- 4:11:16here um and then we because we already
- 4:11:19computed
- 4:11:21the uh the the product we can calculate
- 4:11:24the maximum for each
- 4:11:26row and then we uh we we substract
- 4:11:31because uh when later in the flashh
- 4:11:33attention algorithm we have another
- 4:11:35operation which is the which I call the
- 4:11:38softmax star and as you remember the
- 4:11:40softmax star needs to to do uh each row
- 4:11:46each element of the S Matrix so the
- 4:11:48query multiplied by the transpose of the
- 4:11:50keys minus the maximum for each row so
- 4:11:53we can already compute the maximum for
- 4:11:55each row and we can also before
- 4:11:58Computing the maximum for each row we
- 4:12:00need to mask out all the elements that
- 4:12:03will be masked out in the stage number
- 4:12:05two which is along the
- 4:12:07diagonal and how to mask out we just
- 4:12:10replace with minus infinity before
- 4:12:12applying the soft Max all the values for
- 4:12:14which the mask is false um so right now
- 4:12:17we are we have computed what we have
- 4:12:19computed the query multiplied by
- 4:12:21transport of the keys we have masked out
- 4:12:23in case we need to mask and when we need
- 4:12:24to mask only when we are along the
- 4:12:26diagonal in all the other cases we don't
- 4:12:28need to mask out anything we just
- 4:12:30multiply by the soft Max scale and then
- 4:12:32we um we subtract the MJ the MJ is the
- 4:12:36maximum value for each row because we
- 4:12:39need to compute the softmax star
- 4:12:41operation which is the softmax with the
- 4:12:43normalization which in the flash
- 4:12:44attention algorithm is exactly this
- 4:12:46operation which will produce the
- 4:12:49P okay so let's go here so now we can
- 4:12:53compute the P block which is this stuff
- 4:12:56here which is the exponential of the
- 4:12:59query KV block variable here which have
- 4:13:02already substracted the m so we have
- 4:13:05already substracted this uh Mi at the
- 4:13:09previous instruction so now we can just
- 4:13:11apply the exponential and this is what
- 4:13:14we are doing here uh okay then we need
- 4:13:19to compute the uh sum of the the row for
- 4:13:23the before the um uh normalization
- 4:13:27Factor so for the current block we will
- 4:13:29have a a list of uh we we will have the
- 4:13:33P block for the current KV block to
- 4:13:37compute the normalization factor for the
- 4:13:39softmax we need to keep summing up these
- 4:13:42exponentials and later we will fix the
- 4:13:45exponentials the um the normalization
- 4:13:48factor that we computed at the previous
- 4:13:50step but we will do that later so now we
- 4:13:52just computed the normalization factor
- 4:13:54for the current block which is just the
- 4:13:56sum of all the values on a single row uh
- 4:13:59which is the same as what we did before
- 4:14:02here as you can see
- 4:14:05here when I show you the algorithm so
- 4:14:08for each um for each block we do the row
- 4:14:11sum as you can see here
- 4:14:13of the P Matrix what is the P Matrix is
- 4:14:17the exponential of the S minus M and for
- 4:14:21now we didn't apply the the the
- 4:14:23correction to the previous block that's
- 4:14:25it so we computed the L J for the
- 4:14:28current K andv block and then we comput
- 4:14:31the correction factor for the previous
- 4:14:33block so the correction factor for the
- 4:14:35previous block if you remember the
- 4:14:36formula from the paper is this one is
- 4:14:39the exponential of the previous estimate
- 4:14:41of the maximum minus the current
- 4:14:43estimate of the maximum which is exactly
- 4:14:45this one so the previous estimate of the
- 4:14:46maximum minus the current estimate of
- 4:14:48the maximum uh we will see later why Mi
- 4:14:51is the previous estimate of the maximum
- 4:14:53and what m j is the current estimate of
- 4:14:55the maximum because it is coming from
- 4:14:57the current block that we are Computing
- 4:14:59Mi is the let's say the the one that um
- 4:15:04it is the the one of the previous
- 4:15:05iteration because later we will override
- 4:15:08Mi with m j but I'm just following the
- 4:15:12flashh attention gthm so far so I am
- 4:15:14Computing the correction factor of the
- 4:15:16previous Li which in the flash attention
- 4:15:19algorithm is let me show you uh this
- 4:15:22stuff here so it is this stuff here this
- 4:15:27one
- 4:15:28here um okay and then we apply it so
- 4:15:32apply the correction factor so we apply
- 4:15:36it so we apply the previous Li with the
- 4:15:39correction factor plus the current Li
- 4:15:42which is the one coming from the current
- 4:15:44P block the one that we computed with
- 4:15:45the current K andv with the current
- 4:15:48iteration and right now we are doing
- 4:15:50this operation so Li is equal to the
- 4:15:53previous Li multiplied by the correction
- 4:15:56factor all right and then what we need
- 4:15:59to do okay we need to as you remember
- 4:16:01the formula is um we um calculate the P
- 4:16:05block and then we need to multiply by
- 4:16:06the V block so we need to load the V
- 4:16:08block so let's load it
- 4:16:13we loaded the V block based on the
- 4:16:15pointer of the V block to which this um
- 4:16:19to to which the pointer V is is pointing
- 4:16:22to at the beginning of this iteration in
- 4:16:24case we are in stage number three so in
- 4:16:27case we are doing for example not Cal
- 4:16:28attention it will be pointing to the
- 4:16:30first k v block uh V block and then okay
- 4:16:35here there is just a type conversion so
- 4:16:38we make sure this is in floating Point
- 4:16:4116 and then we
- 4:16:43compute the output block so we are
- 4:16:46Computing the following so we just take
- 4:16:50v p multiply it by V and we add it to
- 4:16:53the output and this is what we are doing
- 4:16:54here we take P we multiply it by V and
- 4:16:58we add it to the O Block uh let's go
- 4:17:01actually to this line one by one so
- 4:17:03first of all we need to fix the previous
- 4:17:05Aus block with the correction factor
- 4:17:07correction factor that we have here so
- 4:17:09we can fix the previous block with this
- 4:17:11Alpha term here which is the correction
- 4:17:14factor for the previous
- 4:17:15block and so we just fixed the previous
- 4:17:18block for now but we didn't add the new
- 4:17:20PV so to add the new PV we do the dot
- 4:17:23product of p and v and this third
- 4:17:25argument tells the dot this not DOT
- 4:17:28product it's actually the matrix
- 4:17:29multiplication uh tell this matrix
- 4:17:31multiplication to use this element here
- 4:17:34as uh the accumulator so this is exactly
- 4:17:37the same as doing uh P block multiplied
- 4:17:41by the V block
- 4:17:43uh O Block Plus equal to P block
- 4:17:46multiplied by the V block uh this is
- 4:17:49just optimized because anyway this dot
- 4:17:52uh function here needs some place where
- 4:17:54to store the intermediate results so why
- 4:17:56not just store it where it should
- 4:17:58actually go and because it um the dot
- 4:18:02the the the matrix multiplication is
- 4:18:04just a DOT product and the dot product
- 4:18:06is just a repeated sum this accumulator
- 4:18:09will be will this dot will keep summing
- 4:18:13the result to this block here which will
- 4:18:16exactly result in this uh um instruction
- 4:18:20like we have done the matrix
- 4:18:22multiplication separately and we added
- 4:18:23it to the O Block so this is uh that's
- 4:18:27why this argument is called the
- 4:18:30accumulator all right so we have also
- 4:18:32computed the output and then we save the
- 4:18:36new estimation of the maximum for the
- 4:18:39current iteration and it becomes Mi so
- 4:18:41at the next we can use it to calculate
- 4:18:44the correction
- 4:18:45factor and then we have finished for the
- 4:18:48current block and then we can move on to
- 4:18:50the next block so we advance our K and V
- 4:18:53pointers by one block of K and v um we
- 4:18:58advance it differently because we know
- 4:19:00that the V block is a pointer to a
- 4:19:04tensor of shape let me write it here
- 4:19:07this is a tensor of shape uh sequence
- 4:19:11length head dim
- 4:19:14so we need to increase the sequence
- 4:19:15length by one KV uh the block size KV uh
- 4:19:19while the K block is actually the K
- 4:19:22transpose block so we need to and it is
- 4:19:25transposed because we have exchanged the
- 4:19:27strides and the shape so it is head
- 4:19:33Dimension head Dimension sequence length
- 4:19:36so we don't change the head Dimension we
- 4:19:38just Advance the sequence length by
- 4:19:40sequence uh block size KB so basically
- 4:19:43we are just going to point to the next
- 4:19:45block of K and to the next block of a
- 4:19:47v I hope to you were able to follow the
- 4:19:50algorithm of flash atation I try to use
- 4:19:53the same names I try to use the more or
- 4:19:55less the same logic and always writing
- 4:19:56the formula that I am referring to so
- 4:19:59hopefully you didn't get lost I think
- 4:20:00the only difference that there is
- 4:20:02between the flashh attention algorithm
- 4:20:04as written on the paper and this code is
- 4:20:05probably this Alpha which is the
- 4:20:07correction factor but I hope it's easily
- 4:20:10understandable anyway um then we just
- 4:20:13return the O Block so O
- 4:20:15Block Li I which is the um the
- 4:20:20normalization factor for each row in the
- 4:20:23current output block which is also a q
- 4:20:26block because we are working with one Q
- 4:20:28block independently from the other
- 4:20:30programs and Mi is the maximum value for
- 4:20:33each row which will be needed for the
- 4:20:36backward pass because when in the
- 4:20:38backward pass we will compute the Q quy
- 4:20:41query multip by transport of the key
- 4:20:42blck on the Fly we need to also apply
- 4:20:45the soft Max but instead of recomputing
- 4:20:46the stuff which we already computed
- 4:20:48during the forward pass we just save
- 4:20:50them and reuse them during the backward
- 4:20:52pass which will save us some
- 4:20:54computation um now I know it's time to
- 4:20:57talk about the log some X trick because
- 4:20:59we are going to use it so let's go back
- 4:21:02to the old method so let's go here all
- 4:21:05right so we have computed two calls of
- 4:21:09this function in case we are working
- 4:21:10with caal attention in case of the we
- 4:21:13are Computing Cal attention we call this
- 4:21:14function once to work with all the query
- 4:21:17blocks that are to the left side of the
- 4:21:19diagonal of the query key Matrix then we
- 4:21:22do another call of this function to work
- 4:21:24only with those blocks of keys that
- 4:21:27exactly lie on the diagonal of the query
- 4:21:29key uh
- 4:21:31Matrix uh because in this case some of
- 4:21:34the values need to be masked out and
- 4:21:36some of them do not need to be masked
- 4:21:38out moreover by doing this we can avoid
- 4:21:42computer in the dot products for all
- 4:21:44those values in the Cal m in the causal
- 4:21:47case for which the key is index of the
- 4:21:50key is higher than the index of the
- 4:21:52query saving some computation because
- 4:21:54anyway they will be resulting after the
- 4:21:56soft Max in zeros and they will not
- 4:21:58contribute to the output so it should be
- 4:22:01faster uh okay now let's go back to the
- 4:22:04this method here so calling method and
- 4:22:07there is one last thing that we need to
- 4:22:08do which is uh we need to compute the
- 4:22:12log some exp and now I will show you
- 4:22:14what is it so in order for the backward
- 4:22:17pass to recompute the soft Max without
- 4:22:19having to recalculate the normalization
- 4:22:21factor and the maximum value for each
- 4:22:23row we should be actually saving two
- 4:22:25different stuff one is the maximum for
- 4:22:27each row in the query block and one is
- 4:22:30the normalization factor for each query
- 4:22:32in the query block however there is a
- 4:22:34trick and the trick is okay it's not
- 4:22:37really called log some X trick because
- 4:22:39the logm X trick is used for another
- 4:22:41purpose but let's call it logm X trick
- 4:22:44number two so um the logm X trick number
- 4:22:47two is something as like this so let me
- 4:22:50open the slides so when we do um query
- 4:22:55multiply by transpose with the keys we
- 4:22:57get a matrix that is made up of dot
- 4:22:59products so something like this like
- 4:23:02this is one dot product so let's call it
- 4:23:04query one transpose the key1 query one
- 4:23:08transpose the key2 this is a query two
- 4:23:11transpose the key one one and this is
- 4:23:13query 2 transpose the key2 then we need
- 4:23:17to apply the soft Max right so the soft
- 4:23:19Max is what is the let's write the
- 4:23:21formula of the soft Max for each of
- 4:23:23these vectors so this is a vector and
- 4:23:25this is a vector because we applied it
- 4:23:26by rows for each of these vectors it
- 4:23:29will modify element wise each element as
- 4:23:31follows so the soft Max of x i is equal
- 4:23:35to the exponential of x i minus oh my
- 4:23:40God I didn't leave enough space so let's
- 4:23:42move this stuff here
- 4:23:45back and this stuff here a little left
- 4:23:49all right it will be the soft Max of um
- 4:23:51the exponential of each element minus
- 4:23:53the maximum for the current Vector to
- 4:23:56which we are applying the soft
- 4:23:59Max divided by the normalization factor
- 4:24:02which is the summation over all possible
- 4:24:04JS where n in this case is equal to two
- 4:24:07because we have each Vector is made up
- 4:24:08of two elements of the exponential of x
- 4:24:12i- x
- 4:24:14max now imagine we already have X Max
- 4:24:20and we already have this summation in
- 4:24:22the flashh alation algorithm in the
- 4:24:23forward pass this stuff here is called
- 4:24:25Li and this stuff here is called
- 4:24:28Mi what we are going to save in the code
- 4:24:31you can see here we are saving actually
- 4:24:34not Mi and Li separately we will be
- 4:24:37saving Mi I plus the logarithm of Li I
- 4:24:42so we are going to save Mi plus the log
- 4:24:47of Li I so what will happen is that when
- 4:24:52we will um compute the um compute the
- 4:24:56backward pass we need to recreate this
- 4:24:57Matrix here on the Fly which means that
- 4:24:59we need to recompute the query multiply
- 4:25:01by the transpose of the keys and we to
- 4:25:04um and then we should apply the softmax
- 4:25:07to apply the softmax we should need this
- 4:25:08stuff and this stuff here but we have
- 4:25:11only this stuff here so so this is the
- 4:25:13Mi plus the logarithm of Li so when we
- 4:25:16Computing the softmax we will compute
- 4:25:18the following so we will compute the
- 4:25:20softmax as follows uh we will Define
- 4:25:23let's call it a new softmax so let me
- 4:25:25use another color
- 4:25:28uh
- 4:25:30here we will apply the softmax as
- 4:25:33follows so
- 4:25:36softmax of
- 4:25:38XI let's call it the soft Max 2
- 4:25:43because it's I don't want to confuse
- 4:25:45soft Max is equal to the exponential of
- 4:25:49each
- 4:25:51element minus we will substract this
- 4:25:53value here the one corresponding to the
- 4:25:56current row to which we are applying the
- 4:25:57soft Max so it will be the exponential
- 4:26:00of x i minus m i minus the log of Li
- 4:26:06I if we expand this expression this will
- 4:26:09become the
- 4:26:11exponential of
- 4:26:12because exponential the sum of two expon
- 4:26:15the exponential of the sum is equal to
- 4:26:17the product of the two exponentials we
- 4:26:19can also write it like this so it will
- 4:26:21be the exponential of x i minus m i
- 4:26:25divided
- 4:26:26by the
- 4:26:29exponential
- 4:26:30um the exponential of the log of Li I
- 4:26:35which guess what it is equal to the
- 4:26:38exponential of x i minus m i
- 4:26:42divided by Li I which is exactly the
- 4:26:44normalization factor and we also have Mi
- 4:26:47so instead of saving two values we save
- 4:26:49only one value and when we apply it the
- 4:26:51exponentials properties will take care
- 4:26:54of actually also normalizing each value
- 4:26:56to which we apply it um if you don't
- 4:26:58remember the properties of the
- 4:26:59exponential it is very simple so the
- 4:27:01exponential of a MTI plus b is equal to
- 4:27:06the exponential of a multiplied by the
- 4:27:09exponential of B and the exponential of
- 4:27:14a uh not exponential it's the
- 4:27:18exponential a minus B is equal to the
- 4:27:23exponential of a divided by the
- 4:27:25exponential of B and this is the the
- 4:27:29trick that we're using so that's why we
- 4:27:30don't need to save two different values
- 4:27:32we just need to save one value and then
- 4:27:34when we apply it it will automatically
- 4:27:36be taken care will take care of
- 4:27:38normalizing because of the properties of
- 4:27:40the
- 4:27:40exponential all right let's move forward
- 4:27:43so we have also created this um value
- 4:27:46that we will use during the backward
- 4:27:48pass now uh as you remember in the flash
- 4:27:52attention algorithm we don't normalize
- 4:27:54each block while Computing it we
- 4:27:56normalize the output at the end and this
- 4:27:59is exactly what we are going to do here
- 4:28:02so we normalize the block at the end
- 4:28:04after we have computed all the
- 4:28:05normalization factors that we need for
- 4:28:07all the rows that belong to the current
- 4:28:09output
- 4:28:10block um we save this Mi so we save it
- 4:28:14um this Mi is what is the normalization
- 4:28:18factor and the maximum for each row that
- 4:28:22we will need for the backward pass so we
- 4:28:23need to save it in a tensor that we will
- 4:28:26use during the backward pass so we need
- 4:28:27to understand which tensor is this and
- 4:28:30it's the tensor that we called M which
- 4:28:32is a tensor of a b size numb heads and
- 4:28:35sequence length Dimensions so we need to
- 4:28:37select the right point in this tensor to
- 4:28:40select to where we should save this Mi
- 4:28:43values uh so we need to select the right
- 4:28:46B size index and the right number of uh
- 4:28:48head
- 4:28:49index uh so we advance this pointer by
- 4:28:53the following offset which is M
- 4:28:58plus um the index batch head because
- 4:29:02each um index okay the index batch head
- 4:29:06is what is the index of the current
- 4:29:08program that includes information about
- 4:29:11which head we are working working with
- 4:29:12and which batch we are working with
- 4:29:14because each of this um for each batch
- 4:29:18and for each head we have a sequence
- 4:29:21length we can skip n uh a number of
- 4:29:25sequence length based on which index is
- 4:29:29um okay what we are doing is basically
- 4:29:31we are
- 4:29:34skipping uh for each uh batch and for
- 4:29:38each head we will have a sequence length
- 4:29:40because each to token in the sequence
- 4:29:43has a maximum value and each token in
- 4:29:45the sequence will have a normalization
- 4:29:47value So based on the current
- 4:29:49combination of batch and head we can
- 4:29:52skip a number of sequence length that
- 4:29:54other programs will process so uh
- 4:29:57because in this uh tensor we have the
- 4:30:00sequence length as the last Dimension
- 4:30:02and we have what is the combined index
- 4:30:05of the batch size and number of head
- 4:30:07size we can skip a number of sequence of
- 4:30:10length based on the combined in index
- 4:30:12which is given by the program index
- 4:30:13number one which is the index batch head
- 4:30:16that we have here and this is why we
- 4:30:18skip here a sequence length number um
- 4:30:22multiplied by the index batch head this
- 4:30:25m is pointing to the
- 4:30:27first uh element of the entire tensor so
- 4:30:31we we are skipping the heads and the
- 4:30:34batch based on the combined index index
- 4:30:37batch head that this particular program
- 4:30:39is working with and then we have off
- 4:30:41Cube of skew is because each um of this
- 4:30:46Kels the attention forward method will
- 4:30:48work with one um query block uh each
- 4:30:54query block has some indices for the
- 4:30:57exact queries it includes and this is
- 4:31:00given by off skew variable that you can
- 4:31:02see here which is how many blocks of
- 4:31:05queries we need to skip because they
- 4:31:06will be processed by other programs plus
- 4:31:09the range of queries that this
- 4:31:10particular that Noti this that a
- 4:31:13particular block of queries has so uh
- 4:31:16imagine this particular program is
- 4:31:18working with the queries that go from I
- 4:31:21don't know from uh 12 to 16 then this
- 4:31:24will be 12 13 14 15 so the normalization
- 4:31:28factor and the maximum value for each
- 4:31:30row we only have that for the this for
- 4:31:34this indices of query queries so 12 13
- 4:31:3714 and 15 and that's why we need to also
- 4:31:40skip the number of queries that this
- 4:31:42particular program works with which is
- 4:31:44already included in this offset offs Q
- 4:31:48variable all right so now we can store
- 4:31:51the Mi so because we have the point to
- 4:31:53which where it should be saved and we
- 4:31:56can also store the output which was
- 4:31:58computed of by our inner for Loop and
- 4:32:01this guys is the forward step of the
- 4:32:04attention flashh
- 4:32:06attention now we should go forward which
- 4:32:09is we should compute the backward path
- 4:32:12we also have all the ingredients for
- 4:32:13computing the backward pass because we
- 4:32:15have already seen this trick which is
- 4:32:17the logm X trick so we already know what
- 4:32:20um how to use it to compute the query
- 4:32:23key block during the backward pass on
- 4:32:25the
- 4:32:25Fly what we miss to understand the
- 4:32:28backward pass well we need to understand
- 4:32:29what is the first of all what is the
- 4:32:31backward pass why do we even need a
- 4:32:32backward pass we need to understand what
- 4:32:34is the autograd of py torch how does it
- 4:32:37work how to compute the gradient what is
- 4:32:40the gradient how to compute do we need
- 4:32:42to what is the Jacobian when Computing
- 4:32:44the gradient on the backward pass do we
- 4:32:45even need to compute that so we need to
- 4:32:47derive all the formulas of the backward
- 4:32:49pass by hand so if you are in for the
- 4:32:51challenge let's continue all right so
- 4:32:54now before looking at the flesh
- 4:32:56attentions backward pass at at the
- 4:32:59algorithm we need to understand why we
- 4:33:01even need a backward pass and to
- 4:33:03understand why we even need a backward
- 4:33:04pass so before looking at the autograd
- 4:33:06of P torch we should be looking at what
- 4:33:09is what are derivatives what are
- 4:33:11gradients what are jaian so that when we
- 4:33:12talk about derivatives gradients and
- 4:33:14jaian we don't feel lost so I will do a
- 4:33:17very fast uh let's say rehearsal of what
- 4:33:21these topics are now what is the
- 4:33:24derivative when you have a function that
- 4:33:25takes as input a real value and outputs
- 4:33:28a real value we talk about derivatives
- 4:33:31which is defined as follows the
- 4:33:33derivative of the function with respect
- 4:33:34to its variable uh X is defined as the
- 4:33:38limit for a step size that goes to zero
- 4:33:40of the function evaluated at X Plus H so
- 4:33:44X plus the step size minus F evaluated
- 4:33:47at The
- 4:33:48X at x divided by the step size so
- 4:33:52intuitively we are saying is the ratio
- 4:33:54of how much the output change for a
- 4:33:57small change for how much the input has
- 4:33:59changed in the
- 4:34:00function that this also gives you the
- 4:34:02intuitive um intuition uh of why the
- 4:34:07gradient is the derivative is also the
- 4:34:10tells you the inclination of the tangent
- 4:34:12line of the um to the function at the
- 4:34:15point in which it's
- 4:34:17evaluated I will use also the following
- 4:34:19notation to denote the derivative so the
- 4:34:23derivative I am used to write it as like
- 4:34:25this so frime of X but it's also
- 4:34:28possible to write it as D of f ofx with
- 4:34:30respect to DX or D of Y where Y is the
- 4:34:33output of the function with respect to X
- 4:34:35and they are all equal to the same thing
- 4:34:37which is the definition
- 4:34:39above if we invert this form here and we
- 4:34:42take H to the left side we can also
- 4:34:45write the follows so if we want to
- 4:34:48evaluate the function um at at the
- 4:34:52position X+ H we can also evaluate it as
- 4:34:56F Prime of H so the derivative of the
- 4:35:00function in the point x multiplied by H
- 4:35:03which is the step size plus f of x this
- 4:35:07is actually also how we derive the ler
- 4:35:09rule uh for computing the differential
- 4:35:12equations but that's not the topic of
- 4:35:13today so this H we can also call it
- 4:35:17Delta X so f of x plus Delta X is more
- 4:35:20or less because here we have a limit
- 4:35:22that says when this only happens when H
- 4:35:24is very very very small so that's why we
- 4:35:26put this more or less approximately so f
- 4:35:30of x plus Delta X is more or less equal
- 4:35:33to frime of X multip by Delta X Plus F
- 4:35:37ofx this you can also read it as follows
- 4:35:40that if by inverting this formula um if
- 4:35:45x changes by a little amount and this
- 4:35:49little amount is Delta X how much y will
- 4:35:53change y will change by this exact
- 4:35:56amount which is the derivative of y with
- 4:35:59respect to X so Dy with respect to DX
- 4:36:02multiplied by how much X has changed so
- 4:36:05this Dy DX tells us how much y will
- 4:36:08change with a small change of x if we
- 4:36:12multiply with the actual change of X it
- 4:36:14will tell us by how exactly y will be
- 4:36:17affected um I don't want to use stay too
- 4:36:21much on this but I I would like to use
- 4:36:24this intuition to introduce the chain
- 4:36:27rule because imagine we have a function
- 4:36:31of a function so imagine we have Z is
- 4:36:33equal to F of G of
- 4:36:35X we can think of X being mapped into a
- 4:36:39variable y through the function G and
- 4:36:41then y being mapped to into variable Z
- 4:36:44through the function f if x changes by a
- 4:36:47little bit and by a little bit I mean
- 4:36:49Delta X how much y will change well y
- 4:36:52will change by Delta Y what is Delta y
- 4:36:55Delta Y is the derivative of y with
- 4:36:57respect to X multiply by the step size
- 4:36:59of
- 4:37:00X but if y changes it will also affect Z
- 4:37:04because there is a direct mapping
- 4:37:06between Y and Z so how much Z will
- 4:37:09change for a small change in y let's see
- 4:37:11so if y changes from the old y by a
- 4:37:15small step Delta y then Z will also
- 4:37:18change by some Delta Z and this Delta Z
- 4:37:21is the DZ of on Dy multip by Delta y if
- 4:37:26we replace this Delta by with the Delta
- 4:37:29y that we have computed in the
- 4:37:30expression
- 4:37:31above we arrive to the chain rule it
- 4:37:34will tell us how Z will be affected so
- 4:37:37this is Delta Z what is um the effect on
- 4:37:41Z for a small change on X and it's the
- 4:37:45product of the two derivatives one with
- 4:37:49of Y with respect to S and one Z with
- 4:37:51respect to Y and this is the chain rule
- 4:37:53that we study in high school so it is if
- 4:37:56you want to compute DZ on DX it is DZ on
- 4:38:01Dy mtip Dy DX uh which is very intuitive
- 4:38:05if you think about the following example
- 4:38:08so you can think of Z as the price of uh
- 4:38:11C
- 4:38:12and X as the price of the oil how much
- 4:38:16will the a small change in the price of
- 4:38:19oil affect the price of a car well the
- 4:38:22small change in the price of the oil
- 4:38:24will affect for example a variable Y
- 4:38:26which could be the price of uh
- 4:38:29electricity so if how much the price of
- 4:38:33electricity will affect the price of a
- 4:38:36car it's through the derivative of the
- 4:38:38price of electricity with respect to the
- 4:38:40uh the price of the car with respect to
- 4:38:42the um electricity so to to get the
- 4:38:46effect of the price of oil on the price
- 4:38:48of the car we just multiply the two
- 4:38:50effects and this is the intuition behind
- 4:38:52the chain rule anyway let's talk about
- 4:38:55gradients so when we have a function
- 4:38:57that as input takes a vector and
- 4:39:00produces a scalar we talk not anymore
- 4:39:02about derivatives we talk about
- 4:39:05gradients so imagine we have a function
- 4:39:08that takes as input a vector made up of
- 4:39:11two Dimensions but n dimension in
- 4:39:12general and it produces a scolar when do
- 4:39:15we have to deal with this kind of
- 4:39:17function for example loss functions loss
- 4:39:19functions are something that are always
- 4:39:22a scalar as output and as input they
- 4:39:24take tensors so um for example imagine
- 4:39:27the crossentropy loss it will take
- 4:39:29a a sequence of tokens each tokens with
- 4:39:33its own Logics and it will compute one
- 4:39:35single number which is the
- 4:39:37loss so how to uh View the effect on the
- 4:39:42output with respect to the input in this
- 4:39:44case well if x changes by a little
- 4:39:47amount and this little amount is not
- 4:39:49anymore a number but it's a vector so if
- 4:39:51change the X the old the X Plus Delta x
- 4:39:57uh is a vector sum then y will also be
- 4:40:00affected by what y will be affected by d
- 4:40:04y on DX multiply by Delta X however this
- 4:40:07Delta X is not a number anymore it's a
- 4:40:10vector because X1 may change by a little
- 4:40:13bit X2 will change by a little bit X3
- 4:40:15will change by a little bit X4 blah blah
- 4:40:17blah until xn will change by a little
- 4:40:18bit so this is actually a DOT product of
- 4:40:22this Vector multiplied by this Vector
- 4:40:25why a DOT product because y will be
- 4:40:28affected by the change in X1 it will be
- 4:40:31affected by the change in X2 it will be
- 4:40:33change affected by the change in X3 up
- 4:40:36to xn and each of the contribution of
- 4:40:39the contribution of X1 will the partial
- 4:40:42derivative of y with respect to X1
- 4:40:44multiply by how much X1 has changed plus
- 4:40:48the contribution FX2 will be the partial
- 4:40:51derivative of y with respect to X2
- 4:40:53multiply by how much X2 has changed blah
- 4:40:56blah blah until the last uh contribution
- 4:40:58of
- 4:40:59xn so and the chain rule in this case
- 4:41:02also applies in the same way as in the
- 4:41:04scalar case so the formula does not
- 4:41:06change also for the change rule here I
- 4:41:08just want you to to to remind that in
- 4:41:11this case we are talking about a
- 4:41:13gradient and the gradient is just a
- 4:41:15vector um made up of all the partial
- 4:41:18derivatives of the output with respect
- 4:41:21each of the input variables that are in
- 4:41:23the input
- 4:41:24Vector when we talk about a function
- 4:41:27that have as input a vector and produces
- 4:41:30a vector then we don't talk about
- 4:41:33gradient anymore we talk about jacobians
- 4:41:35so if our input X the input X of this
- 4:41:39function changes by a little amount and
- 4:41:41this Delta X is a vector then the output
- 4:41:44y will also change and this output y
- 4:41:47will change by a Delta y that is not a
- 4:41:50number anymore it is a vector and this
- 4:41:53Vector is the result of this quantity Dy
- 4:41:56on DX multiplied by Delta X Delta X is a
- 4:42:00vector so this one to be a vector it has
- 4:42:04this one here has to be a matrix and
- 4:42:06this Matrix is called the Jacobian it is
- 4:42:09a matrix that has as many rows
- 4:42:11later we will talk about the denotations
- 4:42:13so it has as many rows as there are
- 4:42:15output variables and as many columns as
- 4:42:18there are input variables the first row
- 4:42:21will be the partial derivative of the
- 4:42:24first output variable with respect to
- 4:42:26all the input variables the second row
- 4:42:28will be the partial derivative of the
- 4:42:31second output variable with respect to
- 4:42:33all the input variables and the last row
- 4:42:35will be the partial derivatives of the
- 4:42:37last output uh variable with respect to
- 4:42:40all the input variable in the input
- 4:42:43Vector um now let's talk about notations
- 4:42:47the Jacobian that I have written here is
- 4:42:50is is written according to the uh
- 4:42:52numerator layout this is called the
- 4:42:55numerator layout and there is another um
- 4:42:58convention called the oh not layout
- 4:43:00sorry guys it's called the numerator
- 4:43:02convention and there is another
- 4:43:03convention called denominator convention
- 4:43:05or notation in which um the rows are not
- 4:43:10the
- 4:43:11the number of rows is not the equivalent
- 4:43:13to the number of output variables but
- 4:43:16equal to the number of input variables
- 4:43:18so um the fact that I have we we choose
- 4:43:22to write the Jacobian as follows is
- 4:43:24based on a convention you can also write
- 4:43:28the the Jacobian according to the
- 4:43:30denominator convention just by
- 4:43:32transposing this Jacobian here and also
- 4:43:34the formula for the chain rule changes
- 4:43:36accordingly for now I want to keep the
- 4:43:39formula for the chain rule just like the
- 4:43:40one for the scolar case so that's why I
- 4:43:43am using this notation here but later we
- 4:43:45can change between one notation to the
- 4:43:47other just by doing a
- 4:43:49transposition okay now that we have
- 4:43:51reviewed what is derivative what is a
- 4:43:53gradient and what is a Jacobian let's
- 4:43:56talk about um what happens when we take
- 4:43:59derivatives with respect to tensors of a
- 4:44:02tensor with respect to another tensor in
- 4:44:04this case we talk about the Jacobian but
- 4:44:06it's called the generalized Jacobian so
- 4:44:09if we have the function that is add
- 4:44:11input takes a tensor of DX
- 4:44:15Dimensions where the first shape this is
- 4:44:18kind of the shape of the tensor so the
- 4:44:20first element of the shape is N1 the
- 4:44:22second element of the shape of the input
- 4:44:24Vector is N2 etc etc until n DX and it
- 4:44:29produces an output tensor that has this
- 4:44:31shape so M1 M2 blah blah blah m d y in
- 4:44:36this case the formula for the chain rule
- 4:44:39doesn't change and
- 4:44:41if x changes by little amount so by
- 4:44:45Delta X which is a
- 4:44:47tensor y will also be affected by how
- 4:44:50much by Dy on DX multip by Delta X and
- 4:44:55this is a tensor product it will be a
- 4:44:58Jacobian uh this is called generalized
- 4:45:00Jacobian with the following shape so all
- 4:45:03the dimensions of the output multiplied
- 4:45:06by all the dimensions of the
- 4:45:08input all right this is very abstract
- 4:45:11for now we will see actually a concrete
- 4:45:13case of this one because we will be
- 4:45:15deriving the the gradient of the output
- 4:45:18of a matrix
- 4:45:20multiplication uh the the gradient of
- 4:45:23the loss when Computing backward pass
- 4:45:25with respect to each of the input of the
- 4:45:26matrix multiplication operation and we
- 4:45:28will do it also for the soft Max and we
- 4:45:30will do it also for the attention so I
- 4:45:32don't want to jump to too many topics I
- 4:45:33just wanted us to get into the right
- 4:45:35mindset so we know that derivatives when
- 4:45:37we have scalar functions gradients when
- 4:45:40the output is scolar input is a vector
- 4:45:43Jacobian when the input and output are
- 4:45:45both vectors generalized Jacobian when
- 4:45:46the input and the output are tensors the
- 4:45:50chain rule always works in the same way
- 4:45:53all right let's talk about Auto autog
- 4:45:56gradient I will do the scalar case and
- 4:45:58then we will extend it to the tensor
- 4:46:00case so imagine we have a very simple
- 4:46:03computation graph why we have
- 4:46:04computation graph because we are talking
- 4:46:05about neural networks and neural
- 4:46:07networks are nothing more than
- 4:46:08computation graphs where we have some
- 4:46:10input with we have some parameters and
- 4:46:11we do some operations with this input
- 4:46:13and parameters suppose that you have an
- 4:46:15input a and this input a is multiplied
- 4:46:18by a weight a parameter weight it's just
- 4:46:21a scalar U and it produces an output y1
- 4:46:25this y1 is then summed up with another
- 4:46:27number called B1 and it produces Y2 this
- 4:46:30Y2 is then raised to the power of two so
- 4:46:32this Z to the^ of two is just the power
- 4:46:34of two of the input and it produces Y3
- 4:46:38and this Y3 becomes our loss function so
- 4:46:41it's a scalar now uh what we uh want to
- 4:46:45do to apply gradient descent is we want
- 4:46:47to compute the gradient of the um loss
- 4:46:50function with respect to each of the
- 4:46:52input of this computation graph so each
- 4:46:54of the leaves of these computation
- 4:46:56graphs what are the leaves it's this
- 4:46:58node here so the parameter nodes and the
- 4:47:00input
- 4:47:01nodes um and to do that there are two
- 4:47:04ways one is if you have access to the uh
- 4:47:09expression that relates Direct the input
- 4:47:11to the uh uh output so the to the loss
- 4:47:15then you can directly compute the the
- 4:47:17gradient the derivative in this case
- 4:47:19because it's not a gradient it's a
- 4:47:20scalar versus scalar so in this case
- 4:47:23imagine we want to compute the
- 4:47:24derivative of the loss with respect to
- 4:47:26W1 imagine we have access to the um
- 4:47:29exact um expression that relates the W1
- 4:47:33to uh to the five which is our loss we
- 4:47:36can compute it as follows so we just
- 4:47:38derive this expression with respect to
- 4:47:40W1 which is two * because this is the
- 4:47:43power of two of a function so it is two
- 4:47:45multiplied by the function multiplied by
- 4:47:48the the derivative of the content of
- 4:47:50this function with respect to the
- 4:47:51variable that we are deriving so it will
- 4:47:54become the following expression there is
- 4:47:57another way which is by using the chain
- 4:47:59rule so we can use the derivative of
- 4:48:02five with respect to Y W1 is the
- 4:48:04derivative of I with respect to Y3 which
- 4:48:08is the previous uh output of the
- 4:48:10previous node then the derivative of 53
- 4:48:12with respect to the previous the output
- 4:48:14of the previous node so and then the
- 4:48:17multiplied by the derivative of Y2 with
- 4:48:19respect to the output of the previous
- 4:48:21node and then the derivative of y1 with
- 4:48:24respect to W1 if we do all this chain of
- 4:48:27multiplication we will obtain the same
- 4:48:29result and you can see that here this
- 4:48:31stuff here is exactly equal to this
- 4:48:33stuff
- 4:48:34here by doing this procedure here we
- 4:48:37will note something that is
- 4:48:41I want to zoom out a little bit okay to
- 4:48:43compute the the derivative of five with
- 4:48:47respect to W1 we are doing all this
- 4:48:50chain of multiplication but what is each
- 4:48:53item in what is each um uh factor in
- 4:48:57this sequence of multiplications well
- 4:49:00this stuff here is nothing more than the
- 4:49:02derivative of five with respect to Y2
- 4:49:06these multiplications here are nothing
- 4:49:08more than the derivative of five with
- 4:49:10respect to to W uh to respect to y1 and
- 4:49:14all of them combined are the derivative
- 4:49:16of f with respect to W1 what pytorch
- 4:49:20will do it will do the following pytorch
- 4:49:23will do the backward pass because
- 4:49:25pytorch knows what is the computation
- 4:49:28graph that relates the output so the
- 4:49:31loss function in this case and the
- 4:49:34variable for which we want to compute
- 4:49:35the gradient right now we are talking
- 4:49:37about derivatives so uh it's not
- 4:49:40gradient but the mechanism is exactly
- 4:49:42the same so pytorch will say uh it will
- 4:49:48py is like a person that knocks the door
- 4:49:52of this operation and
- 4:49:54says um hey
- 4:49:58operation expon power of two if I give
- 4:50:01you the gradient of the loss with
- 4:50:04respect to Y3 which is one because loss
- 4:50:06and Y3 are actually the same can you
- 4:50:09give me the gradient of the loss with
- 4:50:11respect to Y2 because a Pythor actually
- 4:50:14does not Implement an autograd system in
- 4:50:17in the sense that it does not know the
- 4:50:19symbolic operations that led to the
- 4:50:21output it just knows what are the
- 4:50:24functions that computed the output and
- 4:50:26each function has a function each
- 4:50:28function is a class in Python that
- 4:50:30implements two methods one is the
- 4:50:32forward step and one is the backward
- 4:50:34step the forward steps takes the input
- 4:50:37so in this case Y2 and computes the
- 4:50:38output Y3 the back First Step will take
- 4:50:42the gradient of the loss with respect to
- 4:50:45its output and needs to compute the
- 4:50:47gradient of the loss with respect to its
- 4:50:49input how can we do that well it's very
- 4:50:53simple because pytorch will knock the
- 4:50:55door as let me copy it this stuff here
- 4:50:58otherwise it's not easy to go back and
- 4:51:00forth
- 4:51:02so okay and let's past it here pytorch
- 4:51:05will knock the door of this function
- 4:51:08here and will say hey if I give you
- 4:51:11the loss of the Lo the the gradient of
- 4:51:14the loss function with respect to your
- 4:51:15output can you give me the gradient of
- 4:51:18the loss function with respect to your
- 4:51:19input yes the function can do it why
- 4:51:22because of the chain rule this operator
- 4:51:24here this function here can just do take
- 4:51:27the loss uh the gradient of the loss
- 4:51:29function with respect to its output
- 4:51:31multiply it by the
- 4:51:33Jacobian uh or in this case the
- 4:51:36derivative of its output with respect to
- 4:51:38its input and it will be equal to the
- 4:51:40gradient of the loss with respect to its
- 4:51:42input then pytorch will take this one
- 4:51:44and knock the door at the next operator
- 4:51:46which is this one this summation and
- 4:51:48we'll say hey if I give you the gradient
- 4:51:51of the loss with respect to your output
- 4:51:54can you give me the gradient of the loss
- 4:51:56with respect to your input yes this
- 4:51:58operator can do it because this operator
- 4:52:00just needs to apply the chain rule so it
- 4:52:02will take the gradient of the loss with
- 4:52:03respect to um to Y2 which is provided by
- 4:52:06pytorch and by multiplying it with the
- 4:52:10the Jacobian in this case it's the
- 4:52:12derivative the derivative of the its
- 4:52:14output with respect to its input it can
- 4:52:16compute the uh the gradient of the loss
- 4:52:18with respect to its input then pytorch
- 4:52:21will take this output of this backward
- 4:52:23pass and will knock the door of the next
- 4:52:25operator which is this product and we
- 4:52:28ask again the same question hey if I
- 4:52:30give you the gradient of the loss with
- 4:52:32respect to your output can you give me
- 4:52:34the gradient of the loss with respect to
- 4:52:35your input yes this will do the same
- 4:52:38exact job it will take the gradient of
- 4:52:40the loss with respect to the output
- 4:52:42multiplied by the Jacobian of the output
- 4:52:44with respect to the input and obtain the
- 4:52:47gradient of the loss with respect to the
- 4:52:49input and this is how py toch runs the
- 4:52:51backward step it runs one operator at
- 4:52:55the time backwards in the computation
- 4:52:57graph knocking the door of each operator
- 4:53:01and asking always the same question if I
- 4:53:03give you the output the gradient of the
- 4:53:04loss with respect to your output can you
- 4:53:06give me the gradient of the loss with
- 4:53:08respect to your input and each operator
- 4:53:10will just apply the chain rule to to to
- 4:53:13get this um to get this gradient to
- 4:53:16calculate this gradient that pych needs
- 4:53:18why pytorch cannot do it by itself
- 4:53:20because pytorch does not do symbolic um
- 4:53:23mathematics it does not have access to
- 4:53:25the exact expression that each function
- 4:53:27is Computing it just uses the function
- 4:53:30as a blackbox that computes forward and
- 4:53:33backward however with the Jacobian we
- 4:53:36have a problem and let's see what is the
- 4:53:38problem all right so up to now we have
- 4:53:41been working with a compostition graph
- 4:53:43that is made up of Scholars but the
- 4:53:45things that we have said they work in
- 4:53:47the scolar case but also in the tensor
- 4:53:49case so let's go back see what is our
- 4:53:52computation graph we have seen that
- 4:53:54pytorch will go Operator by operator
- 4:53:57asking always the same question if I
- 4:53:59give you the gradient of the loss with
- 4:54:00respect to your output can you compute
- 4:54:02me the gradient of the loss with respect
- 4:54:04to your input and each operator can just
- 4:54:07apply the chain rule to compute that uh
- 4:54:10imagine now that all of these operators
- 4:54:12are working not with scolars but are
- 4:54:14working with tensors which means that
- 4:54:16the derivative of the output with
- 4:54:18respect to the input of each operator is
- 4:54:20not a derivative it will be a Jacobian
- 4:54:23because the output will be a tensor a
- 4:54:25generalized Jacobian and input will be a
- 4:54:28tensor which means also that this
- 4:54:30quantity here so the derivative of the
- 4:54:32loss with respect to the input in this
- 4:54:34case will not be a derivative it will be
- 4:54:36a gradient because the output the loss
- 4:54:38is a number always while the input in
- 4:54:41this case y1 will be a tensor so number
- 4:54:46output input is a tensor then we talk
- 4:54:49about gradients so this will be a
- 4:54:51gradient the and we will call it the
- 4:54:53downstream gradient that the operator
- 4:54:55needs to compute this will be the
- 4:54:57Upstream gradient that pytorch will give
- 4:54:59to the each of these operators so the
- 4:55:02gradient of the loss with respect to the
- 4:55:04output of each operator and each
- 4:55:06operator needs to come up with this
- 4:55:08Downstream gradient by using the
- 4:55:11Jacobian however the Jacobian has a
- 4:55:13problem let's see so uh imagine we are
- 4:55:16implementing a simple operation that is
- 4:55:19the matrix multiplication and the matrix
- 4:55:21multiplication is takes as input X
- 4:55:25tensor it multiplies it by a w Matrix
- 4:55:28made up of parameters and produces a y
- 4:55:30Matrix as output suppose that X is let's
- 4:55:35call it n by D Matrix W is uh let's say
- 4:55:40d by m
- 4:55:42Matrix and so y will be a n by uh M
- 4:55:49Matrix usually the input X is a sequence
- 4:55:54of T of let's say vectors each of each
- 4:55:58with d Dimensions so you can think of it
- 4:56:01as a sequence of tokens each token is a
- 4:56:03vector made up of the dimensions usually
- 4:56:06we have many tokens so suppose that n
- 4:56:09usually is at least
- 4:56:111,24 at least in the most recent
- 4:56:14language models we even have millions of
- 4:56:16tokens actually so uh ND is also
- 4:56:20actually quite big it usually it is at
- 4:56:23least 1,24 also so also this one
- 4:56:27is24 um D and M M is also at least 1024
- 4:56:32so we can actually become 22 2048 let's
- 4:56:35say so I I like the powers of two by the
- 4:56:38way so the problem of the Jacobian is
- 4:56:41this if we compute want to compute this
- 4:56:43Downstream gradient by multiplying the
- 4:56:45Upstream gradient with the Jacobian this
- 4:56:48Jacobian matrix is huge because look at
- 4:56:51the dimensions here this will be a
- 4:56:53matrix that
- 4:56:55is um it will be well n by
- 4:56:59m multiplied so it will be a generalized
- 4:57:03Jacobian so it will be a tensor that has
- 4:57:05a shape n m uh and then the input is X
- 4:57:10so it is n by D so how many elements it
- 4:57:13will have well it will have
- 4:57:161,24 multiplied by m which is
- 4:57:20248 multip by 1024 multi by D which is
- 4:57:261,24 so it is at least wow it's billions
- 4:57:31more than 1 billion
- 4:57:33elements so it is impossible actually to
- 4:57:37materialize this Matrix here in the
- 4:57:39memory because in the ram of the GPU
- 4:57:41because it will be too
- 4:57:43big so but we need to compute this down
- 4:57:46screen gradient because pytorch needs it
- 4:57:48to continue calculating the gradient uh
- 4:57:50of the loss function with respect to
- 4:57:52each of the nodes in the computation
- 4:57:54graph so how can we proceed the first
- 4:57:57thing that we should notice is that this
- 4:57:59G ve this uh Jacobian is actually a
- 4:58:02sparse Matrix and I want to show you why
- 4:58:05it is a actually is a super super super
- 4:58:07sparse Matrix because um if if you look
- 4:58:10at the input what is the effect of the
- 4:58:13input on the output the input is a
- 4:58:16sequence of
- 4:58:17tokens so this is the token number one
- 4:58:20it's a vector of some Dimensions 1,24
- 4:58:23dimensions then we have another token as
- 4:58:25input then we have another tokens as
- 4:58:27input then we have another tokens as
- 4:58:29input and we multiply by the W Matrix
- 4:58:32which is made up of some columns uh some
- 4:58:36uh columns so this one is n by D
- 4:58:40right yes and W is uh d by m so d by m
- 4:58:47this will produce a matrix that is n by
- 4:58:49m so it will be also a sequence of
- 4:58:51tokens each made up of M Dimensions so
- 4:58:55it will be a matrix like this so this
- 4:58:57will be the first output token this will
- 4:59:00be the second output token this will be
- 4:59:02the third output token and this will be
- 4:59:04the fourth output
- 4:59:06token now this output row here
- 4:59:10is the dotproduct of this input row with
- 4:59:13all the columns so the derivative of
- 4:59:17each of these Dimensions with respect to
- 4:59:20the dimensions of all the other tokens
- 4:59:22will be zero because they do not
- 4:59:23contribute to this output so the
- 4:59:27Jacobian will have zeros every time the
- 4:59:31we are calculating the derivative of
- 4:59:33this First Dimension with respect to any
- 4:59:36other element of other tokens that's why
- 4:59:40we always can come up with a better
- 4:59:42formula for computing this Downstream
- 4:59:44gradient that does not involve the
- 4:59:46materialization of the Jacobian because
- 4:59:48the M the Jacobian itself is sparse so
- 4:59:51let's see how we can optimize this uh
- 4:59:53computation without materializing the
- 4:59:55Jacobian in the case of matrix
- 4:59:56multiplication because we need it for
- 4:59:58flesh
- 5:00:00attention all right guys so before
- 5:00:02proceeding to the backward uh watch the
- 5:00:05formulas of the backward path of the
- 5:00:06flesh attention uh let's look at how to
- 5:00:09compute the gradient of the matrix
- 5:00:11multiplication operation with respect to
- 5:00:13its input so imagine we are create okay
- 5:00:16Pythor already have actually how to
- 5:00:18compute the the the the gradient of the
- 5:00:22uh inputs of the matrix multiplication
- 5:00:24with the gradient of the loss with
- 5:00:25respect to the input of the matrix
- 5:00:26multiplication operation but in Flash
- 5:00:29attention we are creating a custom
- 5:00:31kernel which means that the custom
- 5:00:33kernel is fusing multiple operations
- 5:00:35into one operation so when pyro will
- 5:00:39knock the door of our operator it will
- 5:00:41ask the our operator which is the Tron
- 5:00:44attention operator that we have built
- 5:00:46what is the gradient of the loss
- 5:00:48function with respect to q k and V
- 5:00:49because that's the input of our function
- 5:00:52so if we look at the code that we have
- 5:00:53built so far you can see that our trial
- 5:00:56rotation will be a node in the
- 5:00:58computation graph that Tak take takes as
- 5:01:01input q k and V and produces an output
- 5:01:05then pyro will give us the gradient of
- 5:01:07the loss with respect to that output so
- 5:01:09it will will give us d o so the
- 5:01:11derivative of the loss with the gradient
- 5:01:13of the loss with respect to O and then
- 5:01:16we'll ask this class here so Tron
- 5:01:19attention to compute the gradient of the
- 5:01:21loss with respect to Q K and B because
- 5:01:24we are fusing multiple operations
- 5:01:26together so we are Computing on the Fly
- 5:01:27the soft Max of query query multiply by
- 5:01:29the transp of the key and then
- 5:01:31multiplying doing the soft Max and
- 5:01:32multiplying it by uh V to compute the
- 5:01:36output uh we need to compute this
- 5:01:38gradients internally to compute this um
- 5:01:41the gradient of the inputs so because in
- 5:01:44this operations that we are doing fusing
- 5:01:46together there is a matrix
- 5:01:48multiplication we need to derive by hand
- 5:01:50the matrix multiplication uh the
- 5:01:52gradient of the of the loss function
- 5:01:55with respect to the input of the matrix
- 5:01:56multiplication operation so that we can
- 5:01:59uh provide it to P torch that's why we
- 5:02:02need to derive this formula uh I will uh
- 5:02:06derive it in the simp in a very simple
- 5:02:08way and um
- 5:02:11and then we will do it for the soft Max
- 5:02:12as well because these are the two things
- 5:02:14that we need to derive by hand to derive
- 5:02:15the formula of The Flash attentions
- 5:02:17backward
- 5:02:18pass so let's start imagine we have a a
- 5:02:23computation graph uh in od in the
- 5:02:25computation graph called the matrix
- 5:02:27multiplication and this node in the
- 5:02:29computation graph is doing a matrix
- 5:02:30multiplication so it is Computing the
- 5:02:32following operation Y is equal to X
- 5:02:36multiplied W now what py will give us as
- 5:02:41input when Computing the backward path
- 5:02:44of this node py torch will give us the
- 5:02:46gradient of the loss so it will give us
- 5:02:49DF with respect to Dy so the output of
- 5:02:53this node and we ask us to compute the
- 5:02:57gradient of the loss function so the
- 5:02:59gradient of the loss function with
- 5:03:01respect to DX and the gradient of the
- 5:03:04loss function with respect to the W uh
- 5:03:08the easiest one to work with and the one
- 5:03:09that I will be showing and the other one
- 5:03:11I will not show in the video but I will
- 5:03:12attach the PDF slide on how it is
- 5:03:14computed because they are very similar
- 5:03:16in the way they are computed so I don't
- 5:03:18want to make the video too long for
- 5:03:20Unnecessary
- 5:03:21reasons let's compute the gradient of
- 5:03:25the uh loss function with respect to the
- 5:03:29um input so with respect to
- 5:03:32X all right so how to do that by hand
- 5:03:35without materializing the Jacobian
- 5:03:37because as we have seen we cannot just
- 5:03:40use the chain rule by materializing the
- 5:03:41Jacobian which would be the easiest way
- 5:03:43because the Jacobian is very big Matrix
- 5:03:45that cannot even fit in the memory of
- 5:03:47the GPU so we need to find a smarter way
- 5:03:51we exploit the fact that the Jacobian is
- 5:03:53sparse so hopefully we will get formula
- 5:03:55that does not involve the
- 5:03:57materialization of a very big sparse
- 5:03:59Jacobian let's see so uh let's see um
- 5:04:03let's when dealing with this kind of
- 5:04:06derivations I always recommend to make
- 5:04:08some example tensors so suppose that
- 5:04:12that X is a tensor of size let's say n
- 5:04:16by
- 5:04:18D and where n let's say n is equal to 1
- 5:04:22and D is equal to let's say three and um
- 5:04:27X the W is a tensor also or a matrix
- 5:04:32with the shape let's say d by
- 5:04:35m where m is equal to let's say 4
- 5:04:40um and Y will have as a consequence the
- 5:04:45shape n by
- 5:04:48m so it will have the shape um well 1 by
- 5:04:554 what pyto will give us pyto will give
- 5:04:58us the following quantity so it will
- 5:04:59give us this stuff here so the gradient
- 5:05:02of the loss function with respect to the
- 5:05:04output of this operator which is y so it
- 5:05:07will give us a vector or a tensor
- 5:05:10actually with the following Dimension
- 5:05:12which is n by
- 5:05:14m and we need to compute the gradient of
- 5:05:18the loss function with respect to X
- 5:05:21which should be a tensor of shape n by D
- 5:05:24because um when dealing with the
- 5:05:26gradient it always has the shape of the
- 5:05:29input variable because it's the output
- 5:05:32which is a scalar with respect to each
- 5:05:34element in the input so it has the same
- 5:05:36shape as the
- 5:05:38denominator all right so uh when dealing
- 5:05:41with these kind of problems I always
- 5:05:43recommend to create example matrices and
- 5:05:45then work out what happens to the output
- 5:05:47and then try to work out the the the the
- 5:05:51the the gradient Matrix so let's do it
- 5:05:54so let's see that what is how is the
- 5:05:56output computed well the output will be
- 5:05:58a matrix that is 1
- 5:06:02by4 computed as follows it will be the
- 5:06:05input so 1 by3 so let's call the input X
- 5:06:10X11
- 5:06:12X12
- 5:06:13x13 it will be multiplied by another
- 5:06:16Matrix W that is has Dimension 3 by 4 so
- 5:06:22it will be three rows by four columns so
- 5:06:25it will be W1 1 W12
- 5:06:30W13
- 5:06:33w14 then w21 w22 w23
- 5:06:39W2
- 5:06:414 W3 1
- 5:06:44w32
- 5:06:46w33 W 3
- 5:06:494 if we do this matrix multiplication it
- 5:06:52will be well it will produce the
- 5:06:54following Matrix that is okay this is
- 5:06:56one row by three columns this is three
- 5:06:59column three rows by four columns so the
- 5:07:02output will be a matrix that is 1 by
- 5:07:05four so one row by four columns so it
- 5:07:08will be uh uh let me write it with a
- 5:07:11smaller because otherwise it will never
- 5:07:13fit here
- 5:07:14so let's do it like this it will be X11
- 5:07:19ultip by
- 5:07:21w11 plus
- 5:07:24X12 * by
- 5:07:27w21 plus x13 *
- 5:07:32w31 and this will be the first element
- 5:07:34of the output the second element of the
- 5:07:37output will be um
- 5:07:41X11 with W12 X11 with
- 5:07:46W12 plus
- 5:07:49X12 with one two with
- 5:07:54w22 plus
- 5:07:56x13 with
- 5:07:59w32 this will be the second element of
- 5:08:01the output Matrix the third element of
- 5:08:04the output Matrix will be let me move
- 5:08:06this stuff on the left otherwise it will
- 5:08:08never fit
- 5:08:10so okay I think now it can fit this will
- 5:08:14be X I need also to watch this one so
- 5:08:16X11 with W13
- 5:08:19X1 X11 with
- 5:08:22W13 plus X1 2 with W 2 3 plus x 1 3 with
- 5:08:31W3 3 and then we multiply the same row
- 5:08:35with the last column so it will be X11
- 5:08:40w14 + X12 W2 4 + X1 3 W3
- 5:08:494 this will be the output uh y if we do
- 5:08:54the matrix multiplication what pyto will
- 5:08:56give us it will give us the gradient of
- 5:08:58the
- 5:08:59loss so it will give us Delta fi with
- 5:09:02respect to Delta y because it's a
- 5:09:05gradient it has the same shape as the
- 5:09:07denominator so it has a shape that is
- 5:09:091x4 let's call it because we don't know
- 5:09:12what this value will be they will be
- 5:09:14provided to us by pytorch let's just
- 5:09:16give them generic name like
- 5:09:20dy11
- 5:09:22dy12
- 5:09:24dy13 and
- 5:09:27dy4 like
- 5:09:29this now to compute the um uh the
- 5:09:34downstream gradient that we need to
- 5:09:36provide to py torure we should be
- 5:09:37Computing the we should be m realizing
- 5:09:39the jacoban which
- 5:09:42is um which is uh okay let's write the
- 5:09:46chain the chain rule formula so we need
- 5:09:49to provide Delta fi to with respect to
- 5:09:52Delta X which is equal to Delta fi with
- 5:09:57respect to Delta y this is provided by
- 5:09:59by torch multiplied by the Jacobian
- 5:10:02which is Delta y with respect to Delta
- 5:10:06X now instead of materializing this
- 5:10:09Jacobian let's try to do this let's
- 5:10:12materialize it now and let's do the
- 5:10:14multiplication of these two L quantities
- 5:10:16to see if something simplifies so this
- 5:10:19stuff here will be Dy with respect to DX
- 5:10:23which means the derivative of every
- 5:10:26output y with respect to every input X
- 5:10:30how many output we have we have four
- 5:10:32elements as the output which is this
- 5:10:34stuff here and we have three element as
- 5:10:38input in the X
- 5:10:40Matrix so it will be as follows I I
- 5:10:43don't know how to let me copy it because
- 5:10:46my screen is not big enough and I
- 5:10:49remember that X is X11 and xx2
- 5:10:53so uh Delta y with respect to Delta X
- 5:10:58will have the following entries so the
- 5:11:03uh y1 with respect to X11 and as you can
- 5:11:07see y1 only has one X11 appearing as
- 5:11:11multiplied by w11 so the derivative with
- 5:11:14respect to X11 will be
- 5:11:17w11 then y11 so this stuff with respect
- 5:11:21to X12 it will be
- 5:11:26w21 then X um y11 with respect to x13
- 5:11:33will be
- 5:11:35w31 the second row of this Matrix will
- 5:11:37be the derivative
- 5:11:39of the partial derivative of the second
- 5:11:41output so w Y2 with respect to all the X
- 5:11:46inputs which will be the derivative
- 5:11:49partial derivatives of this stuff here
- 5:11:50with respect to every X which is
- 5:11:55W12 w22 I guess and
- 5:12:01w32 now let me check if it's what I'm
- 5:12:04doing is correct yes because I've
- 5:12:05already done it so I can always double
- 5:12:08check uh uh and then we have W the
- 5:12:13partial derivatives of this stuff here
- 5:12:15with respect to all the
- 5:12:17X which is
- 5:12:20W13
- 5:12:23w23 and
- 5:12:25w33 then the partial derivatives of the
- 5:12:28last output so y4 with respect to all
- 5:12:31the X which will be W
- 5:12:35oh
- 5:12:37w14 W2 4 and
- 5:12:41w34 we obtain the following
- 5:12:45Jacobian if um but this Jacobian as you
- 5:12:49can see it's just equal to W
- 5:12:53transposed so we don't need to
- 5:12:55materialize the Jacobian we can just do
- 5:12:57the multiplication of whatever uh
- 5:13:00gradient pytorch is giving us multiply
- 5:13:03it by W transposed and we will get the
- 5:13:05downstream gradient so let me rewrite so
- 5:13:09we know have we know what we are doing
- 5:13:11so D on D DX is equal to
- 5:13:16D with respect to Y multiplied by Dy on
- 5:13:22DX but we have seen that Dy on DX is
- 5:13:25just equal to W transposed so this is
- 5:13:28equal to D on DX Dy multiplied by W
- 5:13:34transposed and this gives us the
- 5:13:36downstream gradient so in order to
- 5:13:37provide the downstream gradient that
- 5:13:39pytorch need we just need to take
- 5:13:41whatever gradient pytorch will give us
- 5:13:42multiply it by W transposed and it will
- 5:13:45give us the gradient of the loss
- 5:13:47function with respect to the input X of
- 5:13:49the matrix
- 5:13:50multiplication in the same way we can
- 5:13:52also arrive to the formula for the
- 5:13:55gradient of the loss function with
- 5:13:56respect to W and it is equal to X
- 5:14:01transposed multiplied by
- 5:14:03Dy with respect to uh DW uh Dy
- 5:14:10how to remember these formulas these are
- 5:14:13there is a ponic rule which is um these
- 5:14:17are the only possible ways for this to
- 5:14:20have the shape of X and this to have the
- 5:14:24shape of w because this ones this stuff
- 5:14:27here will have the same shape of Y so it
- 5:14:30will be
- 5:14:32u n by m this stuff here will have shape
- 5:14:37of w transpose W is is d by m so w
- 5:14:40transpose should be M by
- 5:14:44D and the resulting operation of this
- 5:14:47matrix multiplication or tensor
- 5:14:50multiplication will be n by D which is
- 5:14:53exactly the same shape as
- 5:14:57X in this case we will have that XT is
- 5:15:01the transpose of T and it is uh n by D
- 5:15:05so it's D by n
- 5:15:09multiplied by D with respect to Dy which
- 5:15:12is a gradient so it has the same shape
- 5:15:14as the
- 5:15:16denominator uh so it has uh n by
- 5:15:22m uh and the output will have um shape d
- 5:15:27by m which is exactly the um the shape
- 5:15:31of w so if you to to remember them this
- 5:15:35is the only way this shape work out
- 5:15:37otherwise they don't work out so this is
- 5:15:38a nimonic formula on how to remember how
- 5:15:40to compute the gradient of the inputs of
- 5:15:43a matrix multiplication given the
- 5:15:45gradient of the loss with respect to the
- 5:15:47output of the matrix multiplication and
- 5:15:49the inputs to the matrix multiplication
- 5:15:50are the input Matrix and the parameter
- 5:15:52Matrix W now we need to derive the
- 5:15:55gradient of the output of the softmax
- 5:15:58with respect to the input of the softmax
- 5:16:00because that's another operation that we
- 5:16:02do in our fused attention because we are
- 5:16:04fusing many operations together which is
- 5:16:05matrix multiplication and the soft Max
- 5:16:08so this is the second ingredient that we
- 5:16:09need to understand the backward pass of
- 5:16:11flash attention so let's do
- 5:16:13it I will use to make this derivation I
- 5:16:16will use the same notation as in the
- 5:16:18flash attention paper so first of all
- 5:16:21let's write the title of this stuff
- 5:16:23which is the
- 5:16:28gradient
- 5:16:31through the soft
- 5:16:37Max um the first operation that we do in
- 5:16:40um during computation of the attention
- 5:16:43is we we compute the product of the
- 5:16:45query multipli by the transpose of the
- 5:16:46keys we do in a block-wise ways it means
- 5:16:49that we do it block by block but it
- 5:16:50doesn't matter because the end result is
- 5:16:52the same so we can also we can write s =
- 5:16:55to Q multip by the transpose of the keys
- 5:16:59and then we apply the soft Max to this
- 5:17:01operation to the result of this
- 5:17:03operation and we call this output P
- 5:17:06which is the soft Max
- 5:17:10of s and after the we have applied the
- 5:17:14soft Max we take the output of the soft
- 5:17:15Max we multiply it by V to obtain the
- 5:17:18output so the output is equal to P
- 5:17:20multiplied by
- 5:17:22v um now we need to understand how to uh
- 5:17:26because as I saw as I as I said before
- 5:17:29pytorch autograd works in the following
- 5:17:31way pytorch will treat our attention
- 5:17:34computation as a black box so we will
- 5:17:36have a computation graph like the
- 5:17:38following
- 5:17:39we will have a query input a key input
- 5:17:43and a value input which are sequences of
- 5:17:45tokens each one with some embedding
- 5:17:48Dimension these are fed to some black
- 5:17:51box called the
- 5:17:53attention which is our implementation of
- 5:17:55the attention which is the function that
- 5:17:57we started coding before this will be
- 5:18:00fed as input to this node in the
- 5:18:02computation graph and the computation
- 5:18:04graph will output an output tensor o
- 5:18:09what pyro will give us pyro will give us
- 5:18:11the gradient of the loss with respect to
- 5:18:14the
- 5:18:15output so as you remember py knocks the
- 5:18:18door knocks the door at each operator
- 5:18:21and says if I give you the gradient of
- 5:18:24the loss with respect to your output can
- 5:18:26you give me the gradient of the loss
- 5:18:27with respect to your inputs and this is
- 5:18:30what we need to figure out so giving the
- 5:18:32gradient of the loss with respect to the
- 5:18:34output we need to understand how to
- 5:18:37compute the gradient of the loss
- 5:18:39with respect to WQ the gradient of the
- 5:18:42loss with respect to w k the gradient of
- 5:18:45the loss with respect to w v however the
- 5:18:49there is no direct connection between q
- 5:18:51and o or k and o because there are two
- 5:18:54intermediate operation so one there is a
- 5:18:56first a matrix multiplication then there
- 5:18:58is a softx then there is an additional
- 5:18:59matrix multiplication however we have
- 5:19:01tools that allow us to understand how
- 5:19:04the gradient propagates through multiple
- 5:19:06operations when they are applied in
- 5:19:07sequence and that's called The Chain
- 5:19:10rule however we have seen that applying
- 5:19:12the chain rule in its naive way by
- 5:19:15materializing the Jacobian is invisible
- 5:19:17so we need to understand how to apply
- 5:19:20the chain rule without materializing the
- 5:19:22Jacobian and that's what we are going to
- 5:19:24figure out for one of the operations
- 5:19:26inside of this attention computation
- 5:19:28which is the softmax and that's why we
- 5:19:30are going to do this derivation which I
- 5:19:32promise is the last one that we will do
- 5:19:34and then we will finally go to code the
- 5:19:36backward path of fles attention we
- 5:19:39cannot proceed directly to coding the
- 5:19:40backward pass of The Flash attention
- 5:19:41because if we look at the formulas on
- 5:19:43how it is computed we will not
- 5:19:45understand how the um the derivation
- 5:19:48comes
- 5:19:49out okay now we can
- 5:19:52start so let me delete this stuff delete
- 5:19:55and imagine for Simplicity now we apply
- 5:19:59the soft Max to a uh rowwise to this s
- 5:20:03Matrix so each row is soft maxed
- 5:20:07independently from the others
- 5:20:09so let's see what happens to one single
- 5:20:11row of this Matrix and for Simplicity I
- 5:20:15we call it s so s is uh a single row of
- 5:20:20the S Matrix I could also call it s of I
- 5:20:24but if I do it like this we will have to
- 5:20:26carry over the index I okay guys just
- 5:20:30just do it we will carry over the index
- 5:20:32all right so let's call SI one row of
- 5:20:35the S Matrix so SI is equal to Let's
- 5:20:38let's say it's the in tensor notation py
- 5:20:41tensor notation it would be like this so
- 5:20:43from The Matrix S so from the tensor s
- 5:20:47we take the I row and all the columns
- 5:20:50this is the definition of Si I know it's
- 5:20:52very ugly notation but it helps you
- 5:20:54understand and this is a vector of size
- 5:20:57and
- 5:20:59dimensions uh we apply the soft Max to
- 5:21:01this uh vector and we will obtain an
- 5:21:04output vector and we call it Pi Pi is
- 5:21:08equal to the uh soft Max soft Max of Si
- 5:21:15so as we have seen the soft Max
- 5:21:16operation does not change the shape of
- 5:21:18the input it just change element wise
- 5:21:21each number um so it the output will
- 5:21:24also be a vector of size R to the power
- 5:21:27of n now
- 5:21:30um what is the soft Max so the soft Max
- 5:21:33is defined as follows the soft Max
- 5:21:39of uh well p i j so the J element of the
- 5:21:44p i Vector is equal to the exponential
- 5:21:50of the J element of the SI
- 5:21:54Vector divided by a nor normalization
- 5:21:58factor that is computed as follows uh
- 5:22:01with uh let's say not J let's use K in
- 5:22:05this case not even K let's use l
- 5:22:09is equal to 1 up to n of e to the power
- 5:22:13of s i
- 5:22:16l all right so uh first of all you may
- 5:22:21be wondering the soft Max that we are
- 5:22:24that we apply during the forward pass of
- 5:22:26the computation of the attention is not
- 5:22:28really this softmax because in if you
- 5:22:30remember what we applied before we were
- 5:22:33applying the soft Marx where each of the
- 5:22:35argument of the exponential is reduced
- 5:22:38by the maximum element in the vector to
- 5:22:40which we appli the soft Max so it was
- 5:22:43more or less like this so s i minus SI
- 5:22:47Max so the maximum element in the SI J
- 5:22:51SI
- 5:22:52vector and also the argument of the
- 5:22:54denominator was reduced by Si
- 5:22:58Max
- 5:23:00however we also proved that this stuff
- 5:23:03here is equivalent to the standard soft
- 5:23:06Max without this reduction in the
- 5:23:07argument because this reduction in the
- 5:23:09argument is only added because we want
- 5:23:13to make it numerically safe to compute
- 5:23:15but there is it's equivalent to do it
- 5:23:18without from a mathematical point of
- 5:23:20view on the computer of course it will
- 5:23:23be become numerically unstable but from
- 5:23:25a mathematical point of view it is the
- 5:23:27same thing which also means that doesn't
- 5:23:31doesn't matter how you comput the
- 5:23:33forward pass if it's equivalent to
- 5:23:36another mathematical definition you can
- 5:23:37always use the other mathematical
- 5:23:39definition to compute the backward pass
- 5:23:41it will result in the same value if you
- 5:23:44didn't understand what I said let me
- 5:23:45give you a more simple example which is
- 5:23:48um imagine you have a uh do you remember
- 5:23:52the formula from high school this one so
- 5:23:55Co cosine of s of X Plus sin 2 of X is
- 5:24:02equal to one now imagine we compute uh
- 5:24:06an output Y is equal to cosine 2 of X
- 5:24:11and then we need to compute the
- 5:24:13derivative
- 5:24:14of y with respect to X it doesn't matter
- 5:24:19if you compute it as the derivative of
- 5:24:23cosine squared of X with respect to X or
- 5:24:28if you compute it as the derivative of 1
- 5:24:33- sin 2 of X with respect to to X
- 5:24:39because they will result in exactly the
- 5:24:41same result uh because the two
- 5:24:43definitions are equivalent and this is
- 5:24:45why we don't need to add this um this
- 5:24:48factor in the exponential uh because the
- 5:24:50two definitions are equivalent
- 5:24:52mathematically we just use the
- 5:24:54numerically save one because when
- 5:24:55computed on the on the computer we need
- 5:24:57something that is numerically save uh
- 5:25:00stable that will not
- 5:25:02overflow all right now um what do we
- 5:25:06want to obtain
- 5:25:08so we want to obtain the uh the gradient
- 5:25:12of the loss with respect to the input
- 5:25:15Vector of the soft Max which is the SI
- 5:25:17Vector given the gradient of the loss
- 5:25:21with respect to the output of the
- 5:25:23softmax which is the pi
- 5:25:26Vector multi and we can obtain that with
- 5:25:30the chain rule multiply that by the
- 5:25:34Jacobian Pi with respect to uh s
- 5:25:41now we uh the chain R is always valid
- 5:25:45let's see what does this Jacobian look
- 5:25:47like um all right so this Jacobian will
- 5:25:52be the pi with respect to Delta
- 5:25:58SII uh well we need to do it let's look
- 5:26:02at what each element in this jacoban
- 5:26:04will look like so the J element with
- 5:26:07respect to to the let's say the K
- 5:26:10element so we are
- 5:26:13um we are Computing the
- 5:26:18the we are looking at what each element
- 5:26:22in this Jacobian will look like which is
- 5:26:24what is the Jacobian it's each element
- 5:26:27in the out in the numerator of the
- 5:26:29Jacobian derived with respect to each
- 5:26:32element in the denominator of the
- 5:26:34Jacobian uh in this uh fraction here so
- 5:26:38we are saying for each element in the
- 5:26:40output Vector derived with respect to
- 5:26:43each element in the input Vector this is
- 5:26:45the what we are writing here so what is
- 5:26:48how is the output Vector obtained well P
- 5:26:52J we know that it is equal to by the
- 5:26:54definition of the softmax is obtained as
- 5:26:56follows so e to the power of s
- 5:27:01j divided by the normalization factor
- 5:27:07let's call it l
- 5:27:10is equal to 1 to n e to the power
- 5:27:15of uh s i
- 5:27:19l uh all derived with respect to s i
- 5:27:25k i k so what we are trying to do is we
- 5:27:29know that the P Vector is suppose it's a
- 5:27:31vector with the three elements so this
- 5:27:33is a p one this is well P11
- 5:27:381 one P1 2 and
- 5:27:42p13 the S Vector will be a vector also
- 5:27:45with the three elements so it will be
- 5:27:47the
- 5:27:48S11 S12 and
- 5:27:52s13 what we are trying to do is
- 5:27:54calculate what the Jacobian will be the
- 5:27:56derivative of this one with respect to
- 5:27:58all the input Vector then then the
- 5:28:01second row of the Jacobian will be the
- 5:28:02derivative of this one with respect to
- 5:28:04each of this input element then the
- 5:28:06third row of the Jacobian will be this
- 5:28:08stuff here with respect to derived with
- 5:28:10respect to each of the input element of
- 5:28:12the S Vector we are trying to understand
- 5:28:15what does the generic element in this
- 5:28:17Jacobian look like based on the J date
- 5:28:20element of the output Vector so this J
- 5:28:22index refers to the output vector and
- 5:28:24the K element in the input
- 5:28:27Vector all right so what can happen when
- 5:28:31we do this uh jacoban is that we have a
- 5:28:36this one here is the derivative of a
- 5:28:39fraction of two functions and we know
- 5:28:42from high school that the derivative of
- 5:28:44the fraction of two functions is as
- 5:28:46follows so the derivative oops the
- 5:28:50derivative let me write like this of f
- 5:28:54of x with respect to G of X Prime is
- 5:29:00equal to with respect to X by the way is
- 5:29:03equal
- 5:29:04to uh F Prime oops
- 5:29:09of x * by G of x minus uh G Prime of x f
- 5:29:16of
- 5:29:18x all divided by the uh G of x to the
- 5:29:23power of 2 like this now let's apply it
- 5:29:26here so this will become here we will
- 5:29:29have two cases either the variable that
- 5:29:32we are deriving with respect to so this
- 5:29:34s i k has the same index as the variable
- 5:29:38being derived so either we are doing P11
- 5:29:42with respect to S11 or we are doing P11
- 5:29:45with respect to something else that has
- 5:29:46not the same index so like P11 with
- 5:29:49respect to S12 or s13 so there are two
- 5:29:51cases that we need to consider suppose
- 5:29:53that we are deriving P11 with respect to
- 5:29:56S11 or we are deriving p12 with respect
- 5:29:58to S12 or we are deriving p13 with
- 5:30:00respect to s13 so we are deriving the
- 5:30:03element of the output with respect to
- 5:30:06the same element in the input with the
- 5:30:08same
- 5:30:09index so in this case the this um this
- 5:30:14uh derivative will look like the
- 5:30:16following so it's the derivative of f so
- 5:30:21the numerator with respect to the
- 5:30:23denominator that has the same index so
- 5:30:25we are saying that in this
- 5:30:27case uh J is equal to K
- 5:30:33so uh the numerator with respect to SI J
- 5:30:37with respect to uh e to the power of s j
- 5:30:40with respect to s j will be e to the
- 5:30:43power of s j so because e to the power
- 5:30:47of X1 with respect to X1 will be e to
- 5:30:50the power of X1 so this is equal to I am
- 5:30:53reducing the size
- 5:30:55now e to the power of s i j then we need
- 5:31:00to multiply that by the denominator of
- 5:31:03the fraction which is this summation
- 5:31:06here so the summation
- 5:31:08over all possible
- 5:31:11L of e to^ of s i
- 5:31:15l uh minus the derivative of the
- 5:31:19denominator with respect to the variable
- 5:31:22being derived so this denominator is the
- 5:31:25sum of all the exponentials of all the
- 5:31:27input elements if we derive it with
- 5:31:30respect to one particular input element
- 5:31:32there will be at least one term that
- 5:31:34contains that input element and so the
- 5:31:37the all the other terms will result in
- 5:31:39zero so the only derivative that will
- 5:31:41survive will be the e to the power of s
- 5:31:43i k with respect to s i
- 5:31:46k so we write minus e to the power of Si
- 5:31:51i
- 5:31:56k multiplied by the numerator which is e
- 5:31:59to the^ of Si
- 5:32:02J all this divided by the denominator to
- 5:32:07the power of two which is this summation
- 5:32:10here so L = to 1 up to n e^ of s i
- 5:32:16l all to the power of two and this stuff
- 5:32:20here will be equal to well we can see
- 5:32:23that the this two term this one and this
- 5:32:25one have a one term factor in common
- 5:32:28which is e to the power of s j so we can
- 5:32:30collect that so e to the power of s i j
- 5:32:36multiplied by the
- 5:32:45summation minus e to the power of s i
- 5:32:50k all this divided by the denominator uh
- 5:32:54which is the power of two of this stuff
- 5:32:56here so let me just copy and paste it
- 5:32:58which is let me rotate it also because I
- 5:33:00don't know why I always write
- 5:33:03little
- 5:33:05little yeah all right and this stuff
- 5:33:08here is equal to well uh we can separate
- 5:33:13the two terms so we can separate this
- 5:33:15term here and this term here because the
- 5:33:18denominator is to the power of
- 5:33:20two so we can write it also as e to the
- 5:33:23power of s
- 5:33:25j mided by the denominator so which is
- 5:33:30summation of l = 1 up to n e to the^ of
- 5:33:34s i
- 5:33:35l uh multiplied by this stuff here so
- 5:33:41this stuff here divided by the same
- 5:33:44denominator so there's summation of l =
- 5:33:481 up to n e to the^ of s i
- 5:33:52l minus E to the^ of s i
- 5:33:56k i Am s i k divided by the same uh
- 5:34:03denominator
- 5:34:08s i
- 5:34:10l now this one can be written as this
- 5:34:14stuff here is nothing more than the
- 5:34:16output element P J because this one is
- 5:34:19just the soft Max applied to the SI J
- 5:34:22element which we know that the output of
- 5:34:25the softmax applied to the SI element is
- 5:34:27called P because it's one element of the
- 5:34:29output Vector which we called P so this
- 5:34:32stuff here is equal to p i
- 5:34:35j multiplied by
- 5:34:38this stuff here will be equal to 1 minus
- 5:34:41this stuff here what is this stuff here
- 5:34:43is the output of the soft Max appli to
- 5:34:46the s i k element so it will be p i k so
- 5:34:50it is equal to 1 minus p i
- 5:34:56k okay and this is in the case the the
- 5:35:00the variable with respect to which we
- 5:35:03derive has the same index as the
- 5:35:05numerator in this uh fraction
- 5:35:08here uh in this derivative here uh the
- 5:35:12other case is when the two variables so
- 5:35:15the the output the index of the output
- 5:35:18with respect to the index of the input
- 5:35:20are not the same in this case we will
- 5:35:23have another case so we will have that
- 5:35:25J uh let me write it again so this stuff
- 5:35:31here hope I can copy it all
- 5:35:34without in the other case in which s is
- 5:35:38not equal to
- 5:35:40J uh not s it's j not equal to K so J is
- 5:35:46not equal to K what
- 5:35:48happens in this case it will be well uh
- 5:35:52the derivative of the numerator because
- 5:35:55we need to apply again this formula here
- 5:35:56so derivative of the numerator with
- 5:35:58respect to something that is not the
- 5:36:00same variable it will be zero because
- 5:36:02it's like Computing the derivative e to
- 5:36:05the^ of X1 with respect to X X2 it will
- 5:36:08be zero so it will be zero so all the
- 5:36:11first term here will become zero no
- 5:36:14matter what is g of x minus the
- 5:36:17derivative of the denominator of this
- 5:36:20fraction here with respect to the
- 5:36:22variable SI
- 5:36:24K uh G Prime of s i k so this is all the
- 5:36:29variable in the input and we are
- 5:36:31deriving it with respect to one
- 5:36:33particular variable of the input so only
- 5:36:35one item in the summation will survive
- 5:36:38so it will be the item s i
- 5:36:40k so it will be e to the power of s i k
- 5:36:47multiplied by f of x which is the
- 5:36:50numerator in this fraction which is e to
- 5:36:52the power oh we forgot a minus e to the
- 5:36:55power of s
- 5:36:58j uh let me see if I forgot something
- 5:37:01all divided by the denominator of this
- 5:37:04fraction here to the power of two
- 5:37:07so it is equal to the
- 5:37:10summation l = 1 up to n of e to the
- 5:37:13power of s i l all to the power of
- 5:37:19two uh I believe I didn't forget
- 5:37:21anything so let's continue so here also
- 5:37:25we can see that this one here is because
- 5:37:29okay let's separate it minus E to the^
- 5:37:32of s i k divided by the summation l = 1
- 5:37:39up to n of e^ of s i l multiplied by e^
- 5:37:45of s i j divided by the summation l = 1
- 5:37:51up to n of e to the power of s i
- 5:37:56l this stuff here is nothing more than
- 5:37:59the soft Max appli to the K element of
- 5:38:01the SI Vector this one here is nothing
- 5:38:04more than the softmax applied to the J
- 5:38:06element of the s I Vector so we know
- 5:38:09what these are we know that we call them
- 5:38:13P minus p i k p i
- 5:38:18j so in the end we have two cases one is
- 5:38:24the derivative of this stuff here looks
- 5:38:27like the
- 5:38:29following each item in the Jacobian
- 5:38:31looks like the following when the
- 5:38:33numerator and the denominator have the
- 5:38:35same index so J equal to K this stuff
- 5:38:39here is equal to now this notation here
- 5:38:42is wrong so I shouldn't be writing it
- 5:38:45with equal sign but doesn't matter guys
- 5:38:46it's we are doing a
- 5:38:49little um okay so p i
- 5:38:52j p i j multiplied by 1 minus p i k let
- 5:38:59me check yes the other Cas is when the J
- 5:39:02is not equal to k then this stuff here
- 5:39:05let me write it like this
- 5:39:08will be equal to minus p i k MTI p i
- 5:39:16j now that we know what the two typical
- 5:39:19cases of this Jacobian look like let's
- 5:39:22actually look at what this Jacobian look
- 5:39:24like in The Matrix
- 5:39:26form so this Jacobian will look like the
- 5:39:31following it will be a matrix that is
- 5:39:33more or less like the following it will
- 5:39:36be an n byn Matrix where n is the size
- 5:39:39of the input vector and the output
- 5:39:42vector and here the first element of the
- 5:39:46Jacobian as you saw as you remember uh
- 5:39:49the first row of the Jacobian in the
- 5:39:51numerator convention is the uh
- 5:39:54derivative of the first output with
- 5:39:56respect to all the input so this first
- 5:39:59term here will be the derivative of P11
- 5:40:02with respect to
- 5:40:05S11 so in this case J and K match so we
- 5:40:08know that it will be equal to P1 1 * 1 -
- 5:40:14P11 the second element to the right of
- 5:40:17this one so the element one two will be
- 5:40:19uh the derivative of p12 with respect to
- 5:40:23uh sorry the P11 with respect to S12 the
- 5:40:26J and K do not match so we will be in
- 5:40:29this case here so it will be minus
- 5:40:32P11
- 5:40:34p12 the third element you can check it
- 5:40:37by yourself it will be minus P1 1 p13
- 5:40:42blah blah blah until the end which will
- 5:40:44be - P11
- 5:40:48p1n the second row of this Jacobian will
- 5:40:51be uh will look like this so it will be
- 5:40:54the derivative of p12 with respect to
- 5:40:56S11 the J and K do not match so we are
- 5:41:00in this case here so it will be minus P1
- 5:41:042 P11
- 5:41:07then the next element it will be the
- 5:41:10derivative of p12 with respect to S12 so
- 5:41:13J and K match so we are in the first
- 5:41:15case so it will be P1 2 * 1 minus
- 5:41:21p12 then this stuff here will be equal
- 5:41:24to then the third element will be minus
- 5:41:27P1 2 with respect to
- 5:41:29p13 blah blah blah and until we arrive
- 5:41:33to the last one which is minus P1 2 with
- 5:41:36respect to P1 n not with respect to
- 5:41:38multiply
- 5:41:39by and all the elements like this until
- 5:41:42the last row the last row will be the
- 5:41:44the first element of the last row will
- 5:41:45be the derivative of the uh last output
- 5:41:50element with respect to the first input
- 5:41:52element so it will be the derivative of
- 5:41:54p1n with respect to S11 so um the two
- 5:41:59indices do not match so we are in the
- 5:42:01second case so it will be minus P1 n
- 5:42:07P11 this will be minus P1 n p12 etc etc
- 5:42:14etc let me do also the third element
- 5:42:16since we are here so minus P1 n P1 3 etc
- 5:42:21etc etc until the last element of the
- 5:42:24last row which will be minus
- 5:42:28p1n P1 N I
- 5:42:31guess oh no that's wrong guys because
- 5:42:34the two indices match so it should be
- 5:42:37p1n multiplied 1 minus
- 5:42:41p1n this is what the Jacobian will look
- 5:42:44like let's see if we can find a better
- 5:42:47um uh how to generate this Jacobian with
- 5:42:50some pattern
- 5:42:52recognition let's write it in a
- 5:42:54different way first of all the thing
- 5:42:56first thing that we can notice is that
- 5:42:57this Jacobian is symmetric so you can
- 5:42:59see that this element is equal to this
- 5:43:01element if you expand the third row you
- 5:43:03will see that it's equal to this element
- 5:43:05this one on the top right corner is
- 5:43:07equal to the one in the top bottom left
- 5:43:09corner um so this Matrix is
- 5:43:13symmetric the second thing that we can
- 5:43:15notice is that only the element in the
- 5:43:18diagonal are different they have an
- 5:43:21additional term because you can look at
- 5:43:24this element here so let me write this
- 5:43:28element here can also be written as
- 5:43:31P11 minus P11 * by P11 the second
- 5:43:37element here in the second uh row so
- 5:43:41second diagonal element of this Matrix
- 5:43:43is p12 minus p12 * p12 so this the
- 5:43:50element on the diagonal actually look
- 5:43:51like just like the other elements they
- 5:43:53just have an additional
- 5:43:55term which is P11 in the first diagonal
- 5:43:59element p12 in the second diagonal
- 5:44:02element so we can also say that this
- 5:44:06Matrix here is the product of all the
- 5:44:09possible combinations of P J with p i
- 5:44:13k which you we can obtain with an outer
- 5:44:17product or even with the product of one
- 5:44:20column with the transpose of the same
- 5:44:22column so if you do one column Vector
- 5:44:26for example imagine p is a column vector
- 5:44:29and you do p multiplied by PT you obtain
- 5:44:32all the possible combinations of
- 5:44:33products of these two vectors because
- 5:44:35this will be one
- 5:44:38I can do a simple case so P11 P1 let's
- 5:44:40call it P2
- 5:44:42P3 uh multiplied by the row
- 5:44:46Vector P1 P2 P3 this will generate all
- 5:44:51the possible uh combinations of products
- 5:44:53between P1 and the P the first vector
- 5:44:56and the second Vector because this will
- 5:44:58be a 3X one this is 1 by3 so it will be
- 5:45:01generated 3x3 vector and it will be uh
- 5:45:04equal to P1 P1
- 5:45:08uh P1 P2 P1 P2 P1 P3 etc etc etc
- 5:45:15moreover we can see that in the diagonal
- 5:45:18of the Matrix we have this additional
- 5:45:21term this additional term P1 in the
- 5:45:25first diagonal element p p12 in the
- 5:45:28second diagonal element p13 in the third
- 5:45:30diagonal element uh I actually call it
- 5:45:33P1 it's wrong because I should call it
- 5:45:36Pi I that's why I didn't want to bring
- 5:45:37the I uh indices so it's not really P1
- 5:45:40it's should be Pi I Pi Pi I Pi because
- 5:45:45we are doing it for the generic I Pi
- 5:45:48Vector so let me fix the indices p i n p
- 5:45:55I3 uh this is
- 5:46:01one one one
- 5:46:04one Pi I and pi
- 5:46:08okay so this is Pi
- 5:46:11Pi Pi Pi Pi Pi Pi I Pi I
- 5:46:17okay we can obtain um so we can write
- 5:46:21the this
- 5:46:22um this Jacobian here also as the
- 5:46:26diagonal matrix that in the diagonal has
- 5:46:30all the element of the pi I
- 5:46:32Vector minus the P Vector multiplied by
- 5:46:36the transpose of itself so with itself
- 5:46:39but transposed because we need all the
- 5:46:42elements to be kind of a combination of
- 5:46:44one element of p with it with another
- 5:46:46element of p plus only on the diagonal
- 5:46:49we need some this additional term which
- 5:46:51are the elements of p and all the
- 5:46:53elements of the the the output of this P
- 5:46:56multipli by P transposed are negated
- 5:46:58that's why we need this minus sign so if
- 5:47:01you look at the flashh attention paper
- 5:47:02they give you this formula here they say
- 5:47:04that if Y is equal to the soft
- 5:47:09Max of X then the
- 5:47:14Jacobian uh will look like the following
- 5:47:17will be um
- 5:47:20diagonal of Y minus y y transposed where
- 5:47:26Y is
- 5:47:28um
- 5:47:30the is a column
- 5:47:32Vector all right guys I know this has
- 5:47:34been long so let's take a pause and we
- 5:47:37are going to now um uh code finally
- 5:47:40first of all let's check the mathematics
- 5:47:42of the backward path of Flesh attention
- 5:47:44we will see it briefly I will not do any
- 5:47:47more derivation but I will explain it
- 5:47:50and then we finally switch to coding it
- 5:47:52so let's
- 5:47:53go all right guys now finally we can see
- 5:47:57the um the backward path of the flashh
- 5:47:59attention so we will be looking at the
- 5:48:02algorithm and if you look at the the the
- 5:48:05appendix of the flesh attention p paper
- 5:48:07you will see this part b.2 where they
- 5:48:09derive the backward pass step by step
- 5:48:12now I don't want to do all the s all the
- 5:48:15steps of this derivation because it's
- 5:48:17going to be too long but I want to give
- 5:48:19you all the tools necessary to
- 5:48:21understand it now let's start from what
- 5:48:25kind of um
- 5:48:27uh how to say conventions they are using
- 5:48:31uh notations they are using in this
- 5:48:33paper so the first thing that we need to
- 5:48:35rehearse is the naming of what is what
- 5:48:39is the name of each
- 5:48:40Matrix uh as you know in the forward
- 5:48:43attention in the forward pass we do the
- 5:48:45query multiplied by the transpose of the
- 5:48:47key and the output of this we call it s
- 5:48:50then we apply the soft Max to this s
- 5:48:52Matrix and it becomes the P Matrix the
- 5:48:55soft marks is applied by rows then we
- 5:48:58talk take this P Matrix and we multiply
- 5:49:00by a v Matrix to obtain the output of
- 5:49:02the
- 5:49:03attention
- 5:49:05um let's look at for example how the
- 5:49:08computation of the I row of the output
- 5:49:12is computed based on the P Matrix and
- 5:49:14the V Matrix so we can understand this
- 5:49:16kind of notation that they are using
- 5:49:17here in the paper because the way I read
- 5:49:20this formula here is the E row of the
- 5:49:23output which is a column Vector because
- 5:49:26in when we write in um in mathemat in
- 5:49:28linear algebra whenever we write the
- 5:49:30name of a vector it is always by
- 5:49:33convention a column Vector but the
- 5:49:36origin of this particular Vector is
- 5:49:38actually a row of the output Matrix
- 5:49:41let's try to understand what is the
- 5:49:44output uh row of a matrix in a matrix
- 5:49:48multiplication now um so that we can
- 5:49:51understand how to go from here to here
- 5:49:53um so let's write a generic matrix
- 5:49:56multiplication for example an a matrix
- 5:49:59let's say that it is the
- 5:50:02following and we only write one row
- 5:50:05actually let me Zoom again and I want to
- 5:50:08write smaller so we have enough space so
- 5:50:11we make a matrix that has a row let's
- 5:50:14call it A1 A2
- 5:50:17A3 and then we multiply this will be a
- 5:50:21matrix with many rows like the this one
- 5:50:23because we want to study the effect only
- 5:50:26of one row and we multiply it by another
- 5:50:29Matrix let's call it this one is the
- 5:50:31Matrix a and it has I don't know let's
- 5:50:34say n rows by three columns then we
- 5:50:39should have another Matrix B with three
- 5:50:42columns and some number of um three rows
- 5:50:46and some number of column let's say four
- 5:50:48columns so we call the first uh row
- 5:50:52let's call
- 5:50:54it let me Zoom more so it's
- 5:50:58b11
- 5:51:00B12 B1 3
- 5:51:04b14 then this one should be B2 2 1
- 5:51:08B22
- 5:51:09b23
- 5:51:11B24 this should be b31
- 5:51:16b32 uh
- 5:51:18b33 B3 4 Etc I know I am not very
- 5:51:23rigorous in my notation I should have
- 5:51:25called all these elements with the
- 5:51:27capital letter a and the capital letter
- 5:51:29B so this is the notation that you use
- 5:51:31when referring to single item of a a
- 5:51:34matrix but please forgive me for this so
- 5:51:38the output of this matrix multiplication
- 5:51:40will be another Matrix that is n
- 5:51:44by4 so it will be n by 4 so we will have
- 5:51:48four columns for each uh row of the
- 5:51:53output I want to write the output in a
- 5:51:56different way so I want to write it as
- 5:51:59follows as a vector only so the first
- 5:52:02output row as a vector and want to
- 5:52:05understand what is is each dimension of
- 5:52:07this Vector so because otherwise I don't
- 5:52:10have enough space to write it here so
- 5:52:12the uh first uh let's write it so let's
- 5:52:16call it o I want to write what is O of
- 5:52:20one which is the first row of the output
- 5:52:24but written as a column Vector so o of
- 5:52:28one will be here we should use the small
- 5:52:32letter O of one should be a vector where
- 5:52:36the First Dimension is the dot product
- 5:52:39of this stuff here so the first row of
- 5:52:41the a matrix with the First Column of
- 5:52:44the B Matrix so the first uh let's say
- 5:52:48Dimension will be A1 with
- 5:52:53b11 uh I should also call this one a11
- 5:52:56a12
- 5:52:59actually and a13 so A1
- 5:53:043 uh because we have many rows in the a
- 5:53:06matrix so let me use the correct naming
- 5:53:09so this will be a11 with b11 a11
- 5:53:14b11 plus
- 5:53:17a12 * by
- 5:53:20B21 plus
- 5:53:23a13 with
- 5:53:26b31 and this will be the first dimension
- 5:53:29of the first row of the output Matrix
- 5:53:32o the second dimension of the first row
- 5:53:36of the output Matrix o will be the
- 5:53:38dotproduct of this row of the a matrix
- 5:53:41with the second column of the B Matrix
- 5:53:44and let me write here B so it will be
- 5:53:49a11
- 5:53:52B12 plus
- 5:53:54a12
- 5:53:56B22 plus
- 5:53:59a13 b
- 5:54:0232 the third dimension will be a11
- 5:54:08B1
- 5:54:093 plus A1 2 B2
- 5:54:143 plus A1 3
- 5:54:18b33 the fourth dimension will be
- 5:54:22a11 uh
- 5:54:25b14 + A1 2 b 2 4 plus A1 3 B 3
- 5:54:344 now this is the output the first
- 5:54:37output row of the O Matrix and it's a
- 5:54:40vector called o1 and these are this is
- 5:54:43the first dimension of this Vector this
- 5:54:45is the second this one is the third and
- 5:54:46this is the fourth dimension and each of
- 5:54:48this stuff here is one
- 5:54:51scalar um so the
- 5:54:54output o1 which is the first row of the
- 5:54:58output Matrix can also be written
- 5:55:02as the first element as you can see in
- 5:55:06is a sum of many vectors where the first
- 5:55:10element is
- 5:55:12a11 Multiplied let me use a smaller uh
- 5:55:15this one but I want to use a smaller I
- 5:55:18can't change the size
- 5:55:20here okay doesn't matter so as you can
- 5:55:22see here there is A1 multiplying a
- 5:55:25different B number every time so this is
- 5:55:29b11 B12 B13 b14 what is b11 B12 B13 b14
- 5:55:34it is the first row of the B Matrix so
- 5:55:37it is equal to B uh 1 and all the
- 5:55:41dimensions of the first row then plus
- 5:55:46then we have the element
- 5:55:48a12 multiplied by B21 B22 b23 Etc and
- 5:55:54this is uh the second row of the B
- 5:55:56Matrix so we use the tensor rotation of
- 5:56:00py torch to describe this row which is a
- 5:56:03b uh two and all the dimensions of
- 5:56:07B2 uh so it looks this is a vector
- 5:56:10scalar product and
- 5:56:14plus uh
- 5:56:17a13 multiplied by B uh
- 5:56:213 and all the dimensions of P3 this one
- 5:56:25can also be written
- 5:56:27as um the
- 5:56:30summation over all possible I that go
- 5:56:33from 1 to three where 1 to 3 is how many
- 5:56:37uh uh columns there are in the a
- 5:56:41matrix uh of
- 5:56:44a i
- 5:56:46j uh well
- 5:56:48A1 let's call let's call this one J
- 5:56:51actually sorry let's call it
- 5:56:54J equal to one and let's call this the
- 5:56:58generic e row of the output Matrix will
- 5:57:02be a i1 a I2 and a I3 each one
- 5:57:08multiplied by the corresponding Row in
- 5:57:11the B Matrix so we can write it as a i j
- 5:57:17multiplied by B uh J where BJ is the uh
- 5:57:23a row of
- 5:57:25B uh we can also write it like this to
- 5:57:29indicate that this is a vector and this
- 5:57:31is exactly what they do here so the
- 5:57:34output in the output Matrix when we do
- 5:57:37the multiplication P multipli by V the E
- 5:57:40row of the output Matrix we call it oi
- 5:57:45which is a vector but by notation it is
- 5:57:47a column Vector where the elements of
- 5:57:50this column Vector are actually the
- 5:57:52elements of the E row of O uh this is
- 5:57:56only by notation guys uh is equal to the
- 5:58:00E row of P so the E row of the Matrix
- 5:58:03that is on the left in the matrix
- 5:58:05multiplication multiply by all the
- 5:58:07columns of the V Matrix which can also
- 5:58:10be written as the summation over all the
- 5:58:12elements of the I row of P so all the
- 5:58:15elements of the I row of the first
- 5:58:18Matrix the one on the left in the matrix
- 5:58:20multiplication multiplied by each Vector
- 5:58:24in the v Matrix where the J Matrix here
- 5:58:26in V is each row of the V Matrix
- 5:58:31so and P J can also be written as um p
- 5:58:35is what is um the the output of the soft
- 5:58:39Max so as you know the output of the
- 5:58:41soft Max is e to the power of the
- 5:58:43element input of the softmax what is the
- 5:58:46element input of the softmax is the
- 5:58:48query multiplied by the transpose of the
- 5:58:49keys so it's a DOT product between one
- 5:58:51query and one key and that's why you
- 5:58:53have this stuff here in the exponential
- 5:58:56so this is the first step in
- 5:58:58understanding this derivation another
- 5:59:00thing that we have studied so far is how
- 5:59:02to derive the uh backward path of the
- 5:59:05matrix multiplication
- 5:59:06and of the soft Max so now let's use it
- 5:59:10in the matrix multiplication let's
- 5:59:12rehearse the formula so the if given a
- 5:59:15matrix multiplication that is y = to X
- 5:59:18multiplied w we know that given the
- 5:59:22gradient of the loss function with
- 5:59:24respect to Y so the output of this
- 5:59:26operation we know how to derive the
- 5:59:28gradient of the loss with respect to one
- 5:59:30of the input of this function which is
- 5:59:32the x or W to get the gradient with
- 5:59:36respect to X we need to take the
- 5:59:38Upstream gradient so the the gradient
- 5:59:41with respect to the output multiply by
- 5:59:43the transpose of WT and to get the
- 5:59:46gradient with respect to w we need to do
- 5:59:49the XT so the input transposed
- 5:59:53multiplied by the upstreaming gradient
- 5:59:55this one is the formula that we didn't
- 5:59:57derive and this one is the formula that
- 5:59:59we derived but how to derive them is
- 6:00:01exactly the same
- 6:00:03procedure in attention we are doing the
- 6:00:08last product that we are doing is O
- 6:00:10equal to P multiplied by V what pyo will
- 6:00:14give us as input during the backward
- 6:00:16pass is the gradient of the loss with
- 6:00:19respect to the output and we need to use
- 6:00:21this gradient of the loss with respect
- 6:00:22to the output of the attention to derive
- 6:00:25the gradient of the loss with respect to
- 6:00:27Q with respect to K and with respect to
- 6:00:30V so that it can then be used by the
- 6:00:32operators in the backward pass in the in
- 6:00:36computation graph in the operations
- 6:00:38before okay so but in order to arrive to
- 6:00:42the gradient with respect to query key
- 6:00:44and value we need to derive the gradient
- 6:00:46with respect to each intermediate
- 6:00:49operation so the last operation that we
- 6:00:52do is O equal to P multiplied by V so
- 6:00:55the gradient with respect to O of the
- 6:00:58loss with respect to V given the
- 6:01:00gradient of the loss with respect to O
- 6:01:04it is exactly like Computing the
- 6:01:06gradient of um the of the loss with
- 6:01:08respect to X in a matrix multiplication
- 6:01:11and we know that it is equal to the PT
- 6:01:15so just by analogy guys so this is our
- 6:01:17reference point and I am just changing
- 6:01:18the names here and you should understand
- 6:01:21what is the analogy here so um the
- 6:01:24gradient of the loss with respect to V
- 6:01:26which is the Matrix on the right which
- 6:01:28is like Computing it with respect to to
- 6:01:30W it is equal to just like this formula
- 6:01:33here so the transpose of the Matrix on
- 6:01:35the left multiplied by the Upstream
- 6:01:37gradient which in the paper they write
- 6:01:40it as this so DV is equal to PT
- 6:01:43multiplied by d o and it's the formula
- 6:01:45that you say you can see here the other
- 6:01:48derivation is how to derive the gradient
- 6:01:50with respect to DP DP is just like
- 6:01:53deriving the gradient of the loss with
- 6:01:55respect to the Matrix that is on the
- 6:01:57left side of the matrix multiplication
- 6:01:59so it is just like deriving the gradient
- 6:02:01of the loss with respect to X in the
- 6:02:04reference uh formulas
- 6:02:07which is equal to the Upstream gradient
- 6:02:09multiplied by the transpose of the other
- 6:02:11Matrix which in the notation of the
- 6:02:13paper they write it as DP is equal to d
- 6:02:15o multili by V transposed and it's this
- 6:02:18formula here how they compute this Stu
- 6:02:22here is exactly as above so as as this
- 6:02:25derivation here they call
- 6:02:27VJ the J row of the V Matrix and they
- 6:02:33write it as um p i J multip by d o how
- 6:02:37to arrive to this formula here well
- 6:02:39let's do it
- 6:02:41so let me write let's see
- 6:02:44okay theoretically we know that from
- 6:02:47this derivation here so from this
- 6:02:50derivation here or from this derivation
- 6:02:52here we know that the I row of the
- 6:02:55output in a matrix multiplication first
- 6:02:58of all let's simplify our life every
- 6:03:00time you see a transposed and you don't
- 6:03:01like work with the transposed in a
- 6:03:02matrix multiplication just give it a
- 6:03:04different name and then work with the
- 6:03:06different name and after when you have
- 6:03:08derived the formula you resubstitute the
- 6:03:11transpose operation in this case we are
- 6:03:14doing DV is equal to P transpose multip
- 6:03:17by d o let's call P transposed let's
- 6:03:20give it a name that we are not we didn't
- 6:03:22use so far so let's call it f I always
- 6:03:24used F when it's available so um we call
- 6:03:30DV is equal to f d o we know from above
- 6:03:36here from this derivation here or this
- 6:03:39derivation here is
- 6:03:41equivalent that the output of a matrix
- 6:03:44multiplication so the out I row of the
- 6:03:47let's not the J row let's call it the J
- 6:03:49row d
- 6:03:51v j is equal to a summation of each
- 6:03:57element of the J row of f of the first
- 6:04:02Matrix so we do the let's see here they
- 6:04:06do the sum by I so let's do it by I it's
- 6:04:09the sum over all possible I of the uh I
- 6:04:14element in the
- 6:04:17J row of the first Matrix so f j uh yeah
- 6:04:24FJ
- 6:04:26I multiplied dot product not DOT product
- 6:04:30this is a a scolar uh Vector
- 6:04:33multiplication multiplied by a vector
- 6:04:35that is let me check what was the
- 6:04:37formula so it was the J row of the other
- 6:04:41Matrix so in this case it should be the
- 6:04:44I row of the other
- 6:04:46Matrix uh o of
- 6:04:50I where I this is the I row of I this is
- 6:04:54the J row of the V
- 6:04:58Matrix um and but also we we know that f
- 6:05:03is not a matrix that we have it's
- 6:05:05actually the transposed of P which means
- 6:05:07that fji will be equal to p i j because
- 6:05:10in a matrix transposition you invert the
- 6:05:13two indices so this is the summation
- 6:05:16over all possible I's of P not j i but
- 6:05:21IJ multiplied by oi and this should be
- 6:05:25equal to the same formula that you see
- 6:05:26on the right here this allows you to
- 6:05:29compute one output Row in the v
- 6:05:33Matrix okay and we know that p is just
- 6:05:37um the output of the softmax the soft
- 6:05:40output of the softmax is the input of
- 6:05:42the softmax to the exponential of the
- 6:05:44input of the softmax divided by the
- 6:05:47normalization factor
- 6:05:49associated with the that row so because
- 6:05:52we are iterating through the row of I it
- 6:05:55will be the I the normalization factor
- 6:05:58associated with that row of um of
- 6:06:02OI so we know that the for formula for
- 6:06:06the p is equal to the soft Max of s now
- 6:06:11the I row of P will be the soft Max of
- 6:06:14the E row of s and this is what is
- 6:06:16written here we know from our derivation
- 6:06:19that the Jacobian with respect to the
- 6:06:23softmax operation so if we have an input
- 6:06:26X and the output is y of the softmax
- 6:06:28operation the Jacobian of this um of the
- 6:06:31Y with respect to the x is equal to the
- 6:06:34diagonal y it's a diagonal matrix of the
- 6:06:37element of the factor y minus y * y
- 6:06:41transposed and we have also seen before
- 6:06:43that this Matrix is
- 6:06:46symmetric however you may not understand
- 6:06:49this formula here because we have seen
- 6:06:51from our uh in the chain rule we always
- 6:06:54write it like this we always write that
- 6:06:56the downstream gradient so the D um uh
- 6:07:01Fe of let's say um TX
- 6:07:06should be equal to the uh Upstream
- 6:07:08gradient so d f with respect to Dy
- 6:07:12multiplied by Dy and um with respect to
- 6:07:18DX this only works if you make this
- 6:07:21Matrix here as in the numerator
- 6:07:24convention the numerator convention is
- 6:07:27one of the two convention in which you
- 6:07:28can create a Jacobian we so far we have
- 6:07:31always written it as the numerator
- 6:07:33convention if you use the Ator
- 6:07:35convention this is a row vector and this
- 6:07:38is a row Vector however if you want to
- 6:07:42treat this stuff here as a column Vector
- 6:07:45then you need to take the transposed or
- 6:07:47you need to make the Jacobian in the
- 6:07:49denominator
- 6:07:50convention how to get this formula here
- 6:07:53because this formula here is basically
- 6:07:54doing the Jacobi and multiply by the
- 6:07:57Upstream um uh gradient not the gradient
- 6:08:01Upstream gradient multiplied by the
- 6:08:02Jacobian and it's only because here we
- 6:08:04treat it as a column vector and when you
- 6:08:06do the you want to transform a row
- 6:08:09Vector into a column Vector you take the
- 6:08:10transpose of both sides of the equation
- 6:08:12and let's do it actually so we apply the
- 6:08:15transpose to the both side of the
- 6:08:19equation okay um in a matrix
- 6:08:23multiplication if you do uh a b
- 6:08:26transposed it become B transposed
- 6:08:30multiplied by a transposed so the
- 6:08:32transposed is applied independently to
- 6:08:34each input of the the matrix
- 6:08:35multiplication but we invert the matrix
- 6:08:37multiplication and if you remember the
- 6:08:39matrix multiplication is not commutative
- 6:08:42so what we do here is that we say okay
- 6:08:44it will be the D Fe of DX and here they
- 6:08:48call
- 6:08:50it here they call it
- 6:08:54DSi so it will basically just become D
- 6:08:59on DX if you treat this one as a column
- 6:09:02Vector so this one as a column Vector
- 6:09:04will be equal to Dy on DX as a column
- 6:09:09Vector as a Jacobian in um in
- 6:09:13denominator layout in this case
- 6:09:15multiplied by d f on d y as a column
- 6:09:19Vector this one is a column Vector this
- 6:09:21is a column vector and this is what you
- 6:09:23see here that's why the Jacobian is on
- 6:09:25the left side of the Upstream
- 6:09:27gradient uh what else we need well I I
- 6:09:31know that there is a lot of things here
- 6:09:32in this derivation but I prefer actually
- 6:09:35going directly to the code otherwise I
- 6:09:36think it's going to be too
- 6:09:38boring um so let's go to the code and
- 6:09:41while writing the code I go back to the
- 6:09:43formulas in which we can find the
- 6:09:45association of what we are doing and the
- 6:09:48formula in the paper I think this is the
- 6:09:50best uh way so let's proceed further all
- 6:09:54right guys now we can finally code the
- 6:09:56backward pass before we code the
- 6:09:58backward pass let's look at the
- 6:09:59algorithm of the backward pass as
- 6:10:00written in the paper this is the paper
- 6:10:02flashh attention one and I will because
- 6:10:07we will follow the structure of the code
- 6:10:09that is present on the Tron website so
- 6:10:12it's not my idea to split it like this
- 6:10:15but I simplified it in s i simplified it
- 6:10:18so it's different than the one that you
- 6:10:20can find online because mine is a
- 6:10:21simplified version and mine works with
- 6:10:24causal and non-causal
- 6:10:25attention um so first if you look at
- 6:10:29this algorithm you need to you can see
- 6:10:31that we have an utor Loop through all
- 6:10:34the K and V blocks and an inner loop
- 6:10:37through all the query
- 6:10:39blocks however as you can see to compute
- 6:10:42the DQ which is the downstream gradient
- 6:10:46of the the loss with respect to the Q uh
- 6:10:50Matrix we need to have an iteration
- 6:10:52through all the ks and to compute each
- 6:10:55DC block we need to have an iteration
- 6:10:58through all the cues so if we follow the
- 6:11:01loop like it is it would involve writing
- 6:11:04to the high bandwidth memory so to the
- 6:11:07dram of the GPU at every inner iteration
- 6:11:10and that could be also that that is not
- 6:11:12so
- 6:11:13efficient um and also if we don't want
- 6:11:16to write it would require some sort of
- 6:11:18inter some sort of um synchronization
- 6:11:20between blocks which is also not very
- 6:11:23efficient so we split we will split this
- 6:11:26four into two parts because we can see
- 6:11:29that each DQ depends on a loop over the
- 6:11:33case and each d DK depends on a loop
- 6:11:36over all the cues so to compute DK we
- 6:11:40will fix the Kate block and iterate
- 6:11:43through all the Q blocks then we will do
- 6:11:45another iteration in which we fix the Q
- 6:11:47block and iterate through all the KV
- 6:11:49blocks to compute the Q this is what we
- 6:11:52are going to follow and this is an idea
- 6:11:54that I took from the original
- 6:11:55implementation that is present on Tron
- 6:11:58website another thing that we can notice
- 6:12:00here is um where where is it here to
- 6:12:05comput DQ and DK so um a DQ vector and a
- 6:12:09DK Vector we need this element this
- 6:12:13information here called di di and it's
- 6:12:16shared between the two so we can
- 6:12:19precompute it and then we can reuse it
- 6:12:21for the qite vector to compute the qite
- 6:12:24vector and the DK Vector what is this di
- 6:12:28di is um is uh introduced here and it's
- 6:12:33the dot product of a um Vector that is
- 6:12:36the DOI Vector multiply by o Vector so
- 6:12:40the first thing that we will do is do a
- 6:12:42loop over all the vectors in O and d o
- 6:12:46and do their dot products to compute
- 6:12:48this di element then we will use this di
- 6:12:52element and actually uh let me see yeah
- 6:12:56and then we will use this di element to
- 6:12:58update to to compute DQ and DK and we
- 6:13:02will also have another two Loops one in
- 6:13:04which we fix Q and we iterate through
- 6:13:06all the keys and one in we fix the keys
- 6:13:08and iterate through all the cues so
- 6:13:11let's start so now that we know more or
- 6:13:13less the structure of the code that we
- 6:13:16are all right so um we start by writing
- 6:13:20this backward
- 6:13:22function
- 6:13:26here uh let me check yeah okay so do you
- 6:13:32remember this is saved tensor these are
- 6:13:34all the information that we save during
- 6:13:36the forward pass uh to compute the
- 6:13:39backward pass now to to optimize the
- 6:13:43memory utilization in um flash attention
- 6:13:46we don't save the query multiplied by
- 6:13:49the transpose of the key Matrix because
- 6:13:51that would be a sequence by sequence
- 6:13:52Matrix that is too big to save into the
- 6:13:55hbm in the dam during the forward pass
- 6:13:58and then re reget it back from the hbm
- 6:14:01into the local memory because I want to
- 6:14:03remind you that in Tron uh compared to
- 6:14:06Cuda in Tron what we do is we load stuff
- 6:14:09from the high band withd memory in the
- 6:14:11shared memory so the SRAM we do all the
- 6:14:15operations there and then after when we
- 6:14:17call the store method we save the
- 6:14:19element from the shared memory into the
- 6:14:22high band WID memory so in order to not
- 6:14:25materialize this s Matrix in its
- 6:14:27entirety save it to the hbm and then
- 6:14:30Reet it back which could be very slow
- 6:14:32and secondly actually it is very
- 6:14:34expensive because usually right now we
- 6:14:36are Computing attention on thousands and
- 6:14:39thousands of tokens so imagine saving a
- 6:14:41matrix that is 5,000 by 5,000 that's a
- 6:14:44big Matrix to save for each batch uh for
- 6:14:48each batch and for each head so that
- 6:14:51would be really too expensive to
- 6:14:53save so the idea in Flash attention is
- 6:14:56to recompute what we can compute on the
- 6:14:58fly during the backward pass because
- 6:15:00anyway if we were to load it it would be
- 6:15:03Memory IO found so it's faster to
- 6:15:06recompute than to save it and restore it
- 6:15:09from the memory this is the idea of
- 6:15:11flashh
- 6:15:12attention Okay so we saved some stuff
- 6:15:15during the forward pass and now we can
- 6:15:17access it back during the backward pass
- 6:15:19and this stuff is saved in the context
- 6:15:22and this it's it's a kind of a
- 6:15:24dictionary that is made available by by
- 6:15:26P
- 6:15:27torture all right so we get back the
- 6:15:30query key and values and as you know P
- 6:15:33torch during the autograph will just
- 6:15:35give us the gradient of the loss with
- 6:15:37respect to the output of our
- 6:15:39implementation of the attention of our
- 6:15:42attention so this is Tron attention and
- 6:15:45then we need to compute DQ DK and DV by
- 6:15:48using only the gradient of the output
- 6:15:50with respect to the the deloss with
- 6:15:51respect to the output um we do for some
- 6:15:55checks so here I know I could optimize
- 6:15:59this code and make it even smaller by
- 6:16:01for example checking that here the
- 6:16:03stride that I am using I actually inside
- 6:16:05of the code I always uh pretend that the
- 6:16:08stride is the same but uh doesn't matter
- 6:16:11I just take the code from Tron and uh
- 6:16:13try to simplify it my goal was to
- 6:16:15simplify it not optimize it
- 6:16:17so all right we create the um the
- 6:16:22vectors the tensors in which we will
- 6:16:24store the result of this backward pass
- 6:16:26which is the DQ DK and DV and as you
- 6:16:29know from what we have seen of the
- 6:16:31definition of the gradient the size of
- 6:16:34the output of the gradient Vector is the
- 6:16:38size of the uh Vector with respect to
- 6:16:41which we calculate the gradient because
- 6:16:42in the numerator is always a scalar and
- 6:16:44we compute the gradient with respect to
- 6:16:46all the elements in the input Vector so
- 6:16:47the output the gradient itself is a
- 6:16:50vector of the same size of the element
- 6:16:53by which we compute the gradient with
- 6:16:54respect to so uh we got some information
- 6:16:59on the bed size blah blah blah and later
- 6:17:02we will see what is this number of warps
- 6:17:04and number number of stages I will not
- 6:17:06explain it now it's how P torch number
- 6:17:10of Parts warps is an indication on how
- 6:17:12many threads we want to launch in our
- 6:17:13grid and number of stages is actually
- 6:17:15the number of stages that is used in
- 6:17:17software pipelining we will see later
- 6:17:18what is software pipelining when we talk
- 6:17:20about the autot
- 6:17:22tuning then we Define some uh
- 6:17:26blocks uh in the original um in the
- 6:17:29original code I think they call it a
- 6:17:31block kv1 kv2 k q1 1 and Q2 I think it
- 6:17:36was confusing I call it block macro and
- 6:17:38block micro because the things that we
- 6:17:40will fix and the things that we will
- 6:17:42iterate from will be once is the query
- 6:17:45so we fix the query block and we iterate
- 6:17:48through all the keys and then we will
- 6:17:50fix the keys and values block and we
- 6:17:53iterate through the queries the one that
- 6:17:55we iterate on is the micro one and the
- 6:17:57one that we fix is the macro one this is
- 6:18:00my uh the naming that I am
- 6:18:03using um then we as I said before we
- 6:18:06need to precompute the DI elements that
- 6:18:09we saw in the paper before so that's the
- 6:18:11first kernel that we are going to launch
- 6:18:13and this kernel will have its own launch
- 6:18:16grid because later we want to optimize
- 6:18:18the uh the tuning of this carel later we
- 6:18:21will talk about tuning with respect to
- 6:18:24its own parameters so uh let me see what
- 6:18:28are we going to do so here so the first
- 6:18:31kernel that we are going to launch is
- 6:18:33this pre-process kernel
- 6:18:35this preprocess can will pre-compute all
- 6:18:37the DI elements that we need to compute
- 6:18:39I remember DK and DV if I no DQ and
- 6:18:45DK and this di element depends only on o
- 6:18:50and d o um so let's do it and uh let's
- 6:18:55create another function uh called
- 6:18:57backward pre-process what is the process
- 6:19:00pre-process grid this is the launch grid
- 6:19:02of this function of this car
- 6:19:05and this will be launched on um
- 6:19:08independently for each batch and for
- 6:19:10each head and moreover it will be work
- 6:19:13with a block size of vectors of O what
- 6:19:17is this block what is this number of
- 6:19:19vectors of O it will be the block size
- 6:19:22macro so on 128 vectors of O so uh let
- 6:19:27me copy the signat of this function this
- 6:19:30is here so let's write it here it's fine
- 6:19:36yeah okay this function takes uh The
- 6:19:39Matrix o so it's a pointer to The Matrix
- 6:19:42o it's a pointer to the d o and it's a
- 6:19:45pointer to The Matrix D where we will
- 6:19:46store this di elements and we have one
- 6:19:49for each Vector in the
- 6:19:52output uh that's why the shape of this D
- 6:19:55is batch size number heads sequence
- 6:19:58length it means it's one for each of the
- 6:20:00output element in the output of the
- 6:20:02attention this di uh where is it
- 6:20:05actually it's not this one it's this one
- 6:20:08yeah like M so it has the same shape as
- 6:20:12M which is as you can see it is this
- 6:20:14size here so bch size number heads and
- 6:20:17sequence length M if you remember is the
- 6:20:19Matrix that we Sav during the forward
- 6:20:20pass which includes the normalization
- 6:20:23factor of the soft Max and also the
- 6:20:25maximum element but in log some exp
- 6:20:28format so that when we apply it will
- 6:20:31automatically apply the maximum element
- 6:20:32for each row and also normalize that at
- 6:20:34the same time which I think I proved
- 6:20:37previously uh
- 6:20:40so let me do it so we write it like this
- 6:20:44so we extract
- 6:20:46the uh the index of this program so this
- 6:20:49program has two uh index uh like
- 6:20:54identifier this is is equivalent to the
- 6:20:56Cuda identifier and this is along the
- 6:20:58axis zero so let's see what we uh what
- 6:21:01we what did we launch on the axis zero
- 6:21:04so on the axis zero of this launch grid
- 6:21:06we defined what is the block of vectors
- 6:21:09of uh the O that this particular will
- 6:21:13program will work with and the second
- 6:21:16axis is which batch and which head
- 6:21:19inside of each batch this particular
- 6:21:21program will work with so this
- 6:21:23identifies the block index of Q so which
- 6:21:26group of vectors in the O Matrix this
- 6:21:29particular program will work with here
- 6:21:31is called Q I believe because I copied
- 6:21:34it from the original code where they
- 6:21:36call it q but I could have eventually
- 6:21:38also called it
- 6:21:39o um so we Define uh so basically this
- 6:21:44means that we uh for this program we
- 6:21:47need to skip some query vectors that
- 6:21:50have been already or that will be or
- 6:21:52have been already processed by other
- 6:21:53programs in parallel so we will only
- 6:21:56block with a number of query vectors
- 6:22:00inside of O that have the following
- 6:22:03indices so so imagine that query block
- 6:22:05size is I think it's 128 the way we have
- 6:22:08defined it but suppose it's four for
- 6:22:11Simplicity so this one will be and the
- 6:22:16query vectors are how many are sequence
- 6:22:19length number of query vectors we have
- 6:22:21so some of Imagine The query vectors are
- 6:22:24in total they are I don't know let's say
- 6:22:27uh 64 and 32 will be managed by other
- 6:22:31programs so this particular off skq will
- 6:22:33be equal to 33 34 35 and 36 this tells
- 6:22:39me which query vectors or which vectors
- 6:22:42in the output o Matrix among all the
- 6:22:45vectors in the O Matrix this particular
- 6:22:47program is going to work
- 6:22:50with okay so then we extract also the
- 6:22:53index of the batch which tells us which
- 6:22:56batch and which head in each batch this
- 6:22:59particular program is going to work with
- 6:23:02which is the dimension one of our launch
- 6:23:04grid
- 6:23:05and then we Define the offset of the
- 6:23:07dimension because we need to load all
- 6:23:08the dimensions of each Vector so these
- 6:23:10are the uh it's a vector uh that tells
- 6:23:14um which Dimensions we need to load from
- 6:23:15each vector and we will load all of them
- 6:23:17so we don't divide on the head Dimension
- 6:23:20uh Dimension we just divide on the
- 6:23:22sequence length
- 6:23:24Dimension the the load among multiple
- 6:23:27programs um you will see in this part of
- 6:23:30the the video so when we are writing the
- 6:23:32backward pass that we will not be using
- 6:23:35the make block pointer like we did
- 6:23:37during the forward pass so this function
- 6:23:40here we will work with directly with
- 6:23:42indexing by using the
- 6:23:44strides so let's do
- 6:23:49it so let's load a single block of rows
- 6:23:53of O which I want to remind you has the
- 6:23:56same shape as q and that's why we can
- 6:23:57call it block size Q um so the O Block
- 6:24:00that we are loading is O so uh the load
- 6:24:03function accepts a pointer to what it
- 6:24:06should load uh actually not a pointer it
- 6:24:10accepts a array of pointers or a
- 6:24:12multi-dimensional array of pointer in
- 6:24:14case you want to load a multidimensional
- 6:24:16data so actually load also allows you to
- 6:24:18load um two dimensional data in this
- 6:24:22case we are going to load two
- 6:24:24dimensional data which is a block of
- 6:24:27rows of O which should be a block a
- 6:24:30tensor of the shape uh block size Q in
- 6:24:34this case multiplied by the other
- 6:24:37dimension being head
- 6:24:39Dimension but we don't we need to tell
- 6:24:41it where in this o Matrix it needs to
- 6:24:44find this one first of all we need to
- 6:24:46skip some batches and some heads based
- 6:24:50on what the head and the batch that will
- 6:24:52be processed by other programs So based
- 6:24:54on the index that this um program will
- 6:24:58process of the batch and the head we
- 6:25:00need to skip all the other um batches
- 6:25:03and heads
- 6:25:05uh let's write the shape of this tensor
- 6:25:07so the O tensor has a shape block size
- 6:25:10uh not block size bch
- 6:25:12size number of
- 6:25:15heads then sequence length and then head
- 6:25:19Dimension each block and each head will
- 6:25:22have sequence length multiplied by dim
- 6:25:25head dim number of items So based on our
- 6:25:28index we skip how many items the our
- 6:25:31index multiplied by head Dimension
- 6:25:33multiplied by sequence length so what I
- 6:25:37mean is this the batch zero and the head
- 6:25:39zero will have sequence length
- 6:25:42multiplied by head Dimension items the
- 6:25:46batch zero and the head one will also
- 6:25:47have the same number of items and the
- 6:25:49batch zero and head two will also have
- 6:25:52the same number of items so how many
- 6:25:54items sequence length multiplied by head
- 6:25:56Dimension do we need to skip from the
- 6:25:58starting of the O tensor it is equal to
- 6:26:01the index of the current batch and head
- 6:26:03indicator so because this index
- 6:26:05indicates both um the head in the batch
- 6:26:09and the head inside of each bat because
- 6:26:11it's already the product of the head and
- 6:26:14the batch so how many we skip indicated
- 6:26:18by the this index and after we point to
- 6:26:22this starting point of the current batch
- 6:26:24and the current head we need to select a
- 6:26:26two-dimensional tensor where the offsets
- 6:26:30are indicated for the rows by off SK and
- 6:26:34that's that's why we have this one um
- 6:26:37the I don't know what this is called
- 6:26:40this is the the index U semicolon index
- 6:26:45that tells all the all these vectors in
- 6:26:48offc will with an additional dimension
- 6:26:51for the columns and this columns will be
- 6:26:54the offs dim so basically this will
- 6:26:56select a tensor of the following shape
- 6:26:58inside of this big tensor that includes
- 6:27:01pet
- 6:27:02size and number number of
- 6:27:06heads this is what we are doing so we
- 6:27:08are saying select a tensor of this size
- 6:27:11inside of one that is made up of four
- 6:27:13dimensions by skipping the elements of
- 6:27:16all the batch and heads that will be
- 6:27:19processed by other programs I always
- 6:27:21talk in terms of programs because in
- 6:27:24Tron these are called programs in Cuda
- 6:27:26you would refer to them as
- 6:27:29kernels all right so this one is done I
- 6:27:32hope it is this recently clear um all
- 6:27:36right so then we also load a single
- 6:27:39block of
- 6:27:41D in the same way because we are going
- 6:27:43to load a a group of vectors from all
- 6:27:46the sequence length also from D and the
- 6:27:49D has the same shape as o which has the
- 6:27:52same shape as q and that's why we can
- 6:27:55use the um the the block index we call
- 6:27:58it Q because it's equivalent because
- 6:28:00they have the same
- 6:28:01shape okay and how to compute this di
- 6:28:05element well it's written in the paper
- 6:28:07so if we go in the in the what is it man
- 6:28:12if we go here it shows you how to
- 6:28:14compute the DI of each given a block of
- 6:28:18D and um a block of O it tells you how
- 6:28:21to compute di which is the row sum which
- 6:28:25means the the sum of by rows for each
- 6:28:28row we will have one sum for each Vector
- 6:28:30in the O Matrix we will have one sum of
- 6:28:33the element wise product so this stuff
- 6:28:36here is the element wise product of D oi
- 6:28:38multiplied by oi so it's not um uh
- 6:28:43matrix multiplication it's element wise
- 6:28:44product which means each element of one
- 6:28:46Matrix with the corresponding element of
- 6:28:48the second Matrix and the output shape
- 6:28:50it will be the same as the two matric
- 6:28:53which must have the same
- 6:28:55shape okay so we compute this di
- 6:29:00block which will have shape block size Q
- 6:29:03because we will have one sum for each
- 6:29:07Vector uh then well we need to store it
- 6:29:10somewhere so we need to calculate where
- 6:29:11to store it inside of the D Matrix uh
- 6:29:15well the D Matrix is I remember
- 6:29:18correctly has the same shape as M so it
- 6:29:20should be batch
- 6:29:22size uh number of heads and sequence
- 6:29:26length so we need to select the right
- 6:29:29batch and the right head and also the
- 6:29:31right position inside of the sequence
- 6:29:32length based on the block index Cube
- 6:29:35that we
- 6:29:37have uh okay so let me
- 6:29:42index
- 6:29:43[Music]
- 6:29:45okay all right because we already um so
- 6:29:49we skip um again just like before we
- 6:29:52know that D is of this size each botch
- 6:29:55and each head will have sequence length
- 6:29:58number of elements so how many number of
- 6:30:00elements we need to skip from the
- 6:30:01starting of the uh tensor is sequence
- 6:30:04length multiplied by the combined index
- 6:30:08B size head
- 6:30:10number uh and plus we need to also skip
- 6:30:12some queries based on our block index q
- 6:30:15and it's this skipping is already done
- 6:30:18inside of off skq so we add off skew and
- 6:30:21then once we have computed the index
- 6:30:23where we should store this di I block
- 6:30:25why did I even call it d block let's
- 6:30:29store it so let
- 6:30:32me I didn't call it block I think it was
- 6:30:35already in the original code but this is
- 6:30:36di I and this big Matrix D is actually
- 6:30:40the Matrix that includes all the DI for
- 6:30:43one for each token in the sequence
- 6:30:47length all right so the pre-processing
- 6:30:50has been done now we need to do prepare
- 6:30:53the two for Loops as you remember I said
- 6:30:55before we will be doing two for Loops
- 6:30:57one in which we fix the query and we
- 6:31:00iterate through all the keys and values
- 6:31:02and one in which we fix the key and
- 6:31:04value block and we iterate through all
- 6:31:05the queries and while coding it I will
- 6:31:08always show you the formula from the
- 6:31:09paper so don't worry let's start with
- 6:31:13the next iteration so first we create
- 6:31:15the launch grid for the next iteration
- 6:31:18um as the launch grid is always the same
- 6:31:20so we first because we we need to keep
- 6:31:23one block fixed and iterate through all
- 6:31:25the other blocks uh the block that we
- 6:31:28keep fixed we Define how many programs
- 6:31:30we have that run in parallel uh and the
- 6:31:32block that is fixed has a block size
- 6:31:35macro number of elements that's why we
- 6:31:37create a sequence length divide by block
- 6:31:39size macro number of blocks uh thread
- 6:31:43blocks uh or programs in this AIS uh the
- 6:31:47AIS to in this grid is I could have used
- 6:31:50also the XIs one IND differently I think
- 6:31:52it was already done here in the original
- 6:31:54code it's um will indicate which batch
- 6:31:58and which head inside of each batch we
- 6:32:00are going to work
- 6:32:02with uh so so and just like the uh
- 6:32:07forward pass we will also use a variable
- 6:32:09called stage that if the attention that
- 6:32:11we are Computing is caal it will be
- 6:32:13equal to three and if we are Computing a
- 6:32:15non-causal attention then it will be
- 6:32:16equal to
- 6:32:18one um the first iteration we will fix K
- 6:32:21and V blocks and we will iterate through
- 6:32:24all the Q blocks in size of block size
- 6:32:28micro number of query
- 6:32:32vectors uh so let's look at the
- 6:32:34signature so we pass we we launch it as
- 6:32:37a launch grid because um and we we have
- 6:32:41defined how many programs we have so we
- 6:32:43have how many uh KV blocks we will have
- 6:32:47it's a sequence land divide by the block
- 6:32:49size macro because that's the the block
- 6:32:51that we will keep fixed in this uh for
- 6:32:53Loop in this
- 6:32:55function and then we go through all the
- 6:32:58query blocks in size of block size micro
- 6:33:01which I defined it as 32 and later we
- 6:33:04will talk about autot tuning and how to
- 6:33:05tune these
- 6:33:06values all right so I passed the query
- 6:33:09Vector the key vector and the V Vector
- 6:33:12uh sorry not Vector tensors now the
- 6:33:15query tensor K tensor and V tensor and
- 6:33:17they are pointing to the beginning of
- 6:33:19the tensor which means that they are
- 6:33:21beginning to the first botch and the
- 6:33:23first head and the first token and the
- 6:33:25first dimension of the tensors then we
- 6:33:28pass the soft Max scale we pass d o DQ
- 6:33:32DK and DV m is the one that is needed to
- 6:33:36compute as you remember from what we
- 6:33:38said before we did not see if the P
- 6:33:41Matrix in the hbm because we want to
- 6:33:44recompute it on the fly during the
- 6:33:45backward pass so the query multiply by
- 6:33:47transpose of the keys it's a very big
- 6:33:49Matrix to save in the hbm and restore it
- 6:33:51so we want to compute it on the fly but
- 6:33:54we don't need to recompute the
- 6:33:55normalization factor and the maximum
- 6:33:57element for each row to apply the soft
- 6:33:59Max that was already computed during the
- 6:34:02forward pass and saved into this Matrix
- 6:34:04M which includes the log sum exp of the
- 6:34:08maximum of each row plus the logarithm
- 6:34:11of the normalization factor with the
- 6:34:13theug sum X trick we can just apply it
- 6:34:16and it will also normalize each value
- 6:34:19then we have the d uh V uh tensor that
- 6:34:23we computed here with all the DI values
- 6:34:25one for each Vector in the O tensor then
- 6:34:29we need to pass some uh the number of
- 6:34:31heads the sequence length the block size
- 6:34:34that we want to use for the KV which is
- 6:34:36the macro block size and the micro block
- 6:34:38size is always the one that we iterate
- 6:34:39on I think using this name it should be
- 6:34:42easier to understand which one we are
- 6:34:43iterating and which we want keep fixed
- 6:34:45so the fixed one is macro and the
- 6:34:47iterating one is the micro um head
- 6:34:51Dimension um and later we will see why
- 6:34:53we use a different block size to iterate
- 6:34:55from because this is related to the
- 6:34:57number of stages that Tron can divide
- 6:35:00your for Loop into thanks to soft
- 6:35:03pipelining then we have head Dimension
- 6:35:06the stage indicates if the attention
- 6:35:09that we computed in the forward pass was
- 6:35:11Cal or not
- 6:35:13cal um the number of warps and the
- 6:35:15number of stages which we defined as
- 6:35:17fixed but later we will talk about Auto
- 6:35:19tuning so uh sometimes I repeat the same
- 6:35:22stuff over and over so I should change
- 6:35:25that
- 6:35:26um okay let's write the signature of
- 6:35:30this function um
- 6:35:33let's put it here but
- 6:35:36so we already described what is the
- 6:35:40signature of this function let's go
- 6:35:41directly to the meat so the first thing
- 6:35:44that we need to do is understand the
- 6:35:45offset by which we need to move this
- 6:35:47query key and value and the offset is
- 6:35:50given by the first of all we need to
- 6:35:52enter the right batch and the right head
- 6:35:54inside of each batch we compute the
- 6:35:57index of the batch just like during the
- 6:35:58forward pass by dividing the program the
- 6:36:02program index which is a multiplic of
- 6:36:04the index of the head and of the the
- 6:36:07batch we divide it by the number of
- 6:36:10heads to get which batch this program is
- 6:36:12working with and to get the head we just
- 6:36:13do the modulus just like in the for Loop
- 6:36:16uh forward
- 6:36:17pass um the offset batch head indicates
- 6:36:21let me check what is it for okay it
- 6:36:23enters the right batch and the right
- 6:36:25head so what is the stride if you
- 6:36:27remember correctly The Stride tells us
- 6:36:29how many items you need to skip in that
- 6:36:31Dimension to arrive to the next index in
- 6:36:32the same dimension so if we want to skip
- 6:36:35index number of batch we need multiply
- 6:36:37it by the stride batch which is how many
- 6:36:40elements you need to skip to arrive to
- 6:36:42the next batch plus we also need to
- 6:36:44enter the right head so we multiply um
- 6:36:47the index of the head multiplied by The
- 6:36:49Stride of the head to enter exactly in
- 6:36:53that head in the tensor for each of the
- 6:36:56qk and V
- 6:36:57matrices uh plus we also have this is
- 6:37:00will be used for if I remember for m and
- 6:37:03d because m and d only don't have the um
- 6:37:07the head di head Dimension so they are
- 6:37:10only bch size number of heads sequence
- 6:37:12length so we just use the index batch
- 6:37:14multiplied by sequence length because
- 6:37:16for each batch and on each head we will
- 6:37:18have sequence length number of item so
- 6:37:19you can think of it at the stride to
- 6:37:21move from one batch head to the next
- 6:37:23batch
- 6:37:25head uh or to the yeah so
- 6:37:30uh let's move the pointers
- 6:37:35and this was so we move the pointer q k
- 6:37:39and V by the offset batch head because
- 6:37:42we want to enter the right um batch and
- 6:37:46the right head inside of these big
- 6:37:47tensors and we do it also for d o DQ DK
- 6:37:51and DV because they have the same shape
- 6:37:53as a q k and V and d o also has the same
- 6:37:56shape as Q so they have the same shape
- 6:37:58so we move by the same uh by the same
- 6:38:01offset all right
- 6:38:03so and then we move m and d to move them
- 6:38:07to the right starting point on which the
- 6:38:10sequence of the current head and the
- 6:38:13current batch and the current head
- 6:38:15starts so they are pointing to the first
- 6:38:18Vector of the sequence dedicated to the
- 6:38:21current badge and the current
- 6:38:22head and the same is true for qk and V
- 6:38:26and the d o DQ DK
- 6:38:29andb okay then we load some other stuff
- 6:38:34because here we fix in this iteration in
- 6:38:37this method we are going to do a for
- 6:38:39Loop in which we fix KV and we iterate
- 6:38:42through Q so we first need to load this
- 6:38:45dibs block of KV and we do it as
- 6:38:50follows as follows so we know we need to
- 6:38:53load a 2d tensor so we need to Define
- 6:38:56what are the ranges in the second
- 6:38:59dimension of each um vector k and V that
- 6:39:03we need to load and it's defined by the
- 6:39:05this
- 6:39:07um by this
- 6:39:09Factor then we uh we want to understand
- 6:39:12which KV block this particular program
- 6:39:15is going to work with so this particular
- 6:39:18program is going to skip some KVs that
- 6:39:20will already be managed by other
- 6:39:22programs that may be running in parallel
- 6:39:24and how to understand what this program
- 6:39:26should be working with in based on the
- 6:39:28index of the program zero which is
- 6:39:32defined on sequence divide by the block
- 6:39:35size macro and if you remember block
- 6:39:37size macro is the thing that we fix so
- 6:39:40it's telling us this program ID zero
- 6:39:42will tell us how many uh block size
- 6:39:44macro KV are already being managed by
- 6:39:48other programs so we shouldn't care
- 6:39:50about them so we skip them so let's go
- 6:39:53back here and this is the number of
- 6:39:55vectors that we need to skip so our KB
- 6:39:58Start From Start KB and how many we need
- 6:40:01to load them well depends on what is the
- 6:40:04block KV this block KV is equal to block
- 6:40:07size macro so it will be
- 6:40:09128
- 6:40:11vectors so we Define our um tensors two
- 6:40:17dimensional tensors that we will store
- 6:40:19in the SRAM because in Tron every time
- 6:40:22you load something you load it from the
- 6:40:23hbm into the SRAM so we Define where
- 6:40:27they should be saved in the SRAM and
- 6:40:28they are initially zeros and now we load
- 6:40:31them so we load them as as
- 6:40:36follows um we say that okay in the K uh
- 6:40:42in the K tensor pointer which is already
- 6:40:44pointing to the right index to the right
- 6:40:48batch and to the right head because
- 6:40:50that's something that we did
- 6:40:52here we say we should need we need to
- 6:40:55load the right sequence of keys which
- 6:40:58should start from offs key because this
- 6:41:01already includes how many We Should Skip
- 6:41:04in the sequence length Dimension and for
- 6:41:06each of these Vector we need to load all
- 6:41:08the dimensions in
- 6:41:11the in the head Dimension Dimension uh
- 6:41:15because the K if I want to remind you is
- 6:41:19batch number of
- 6:41:22heads um sequence length and head
- 6:41:27dim Now by using this line we are
- 6:41:30skipping to the right B and to the right
- 6:41:33head so it's like we already indexed
- 6:41:36here and here we already selected an
- 6:41:37index so right now this K is pointing to
- 6:41:40the beginning of a tensor of two
- 6:41:42Dimension and we tell okay we don't want
- 6:41:45all the sequence we want some part of
- 6:41:48this sequence which part the one that is
- 6:41:50indicated by this start
- 6:41:52KV um and how many of in the sequence
- 6:41:56length we want well we want uh I I think
- 6:42:00it's easy to write it like this so we
- 6:42:02can write it that from start KV to start
- 6:42:05KV plus block
- 6:42:08KV uh so we want this number of tensor
- 6:42:13exactly at this location and for head
- 6:42:15Dimension what do we want to select we
- 6:42:17want to select all the dimension so we
- 6:42:19say that we want from zero to head
- 6:42:22Dimension which is exactly this offs
- 6:42:26dim
- 6:42:28okay uh we do it for the K block and we
- 6:42:31do it for the V block
- 6:42:33uh here I think I didn't change the
- 6:42:35comment this should be block
- 6:42:38KV and this should be block KV before it
- 6:42:41was called block kv1 right like in the
- 6:42:44original code uh I simplified a little
- 6:42:47bit the naming I think this one is
- 6:42:48better easier to follow because in the
- 6:42:50original code they also do for two for
- 6:42:53Loops but in the second for Loop they do
- 6:42:55it backward just to not change the
- 6:42:56structure of the loops but I think mine
- 6:42:58is more verbos but easier to
- 6:43:01understand and probably less efficient
- 6:43:03mine is much less
- 6:43:05efficient um then we have offc because
- 6:43:08we need to understand for each block of
- 6:43:11queries how many vectors we need to load
- 6:43:14and it's indicated by this offs q and
- 6:43:17how many are them it's a block Q block Q
- 6:43:20in the col color of this method was
- 6:43:23block size micro so it is 32
- 6:43:27vectors okay um now we need to access
- 6:43:33Q vectors and O vectors trans uh no Q
- 6:43:37vectors but already transposed and the O
- 6:43:40vectors also we need to access them
- 6:43:42because we are going to iterate through
- 6:43:46queries and O vectors actually also why
- 6:43:51because let's look at here let's look at
- 6:43:54the formulas in the paper to compute VJ
- 6:43:58so to compute the dvj that's what we are
- 6:44:02trying to compute here we need to
- 6:44:04iterate through all the D vectors and to
- 6:44:07compute DK we need to iterate through
- 6:44:09all the QI uh
- 6:44:13vectors because the QI is a block of
- 6:44:16vectors uh so uh that's why we need um
- 6:44:20and why do we need to access a q as a
- 6:44:23transposed because we need to compute
- 6:44:25let me show you here uh P transpose that
- 6:44:29to compute P transpose we need to we
- 6:44:32need the Q trans transpose because the p
- 6:44:34would be the soft Max of the query
- 6:44:36multipli by the transpose of the
- 6:44:38keys after we apply the soft Max it
- 6:44:40becomes P but if you want the transposed
- 6:44:43of P then you need to do query
- 6:44:46transposed K multip by query transposed
- 6:44:49so that's why we accessed query
- 6:44:51transposed instead of
- 6:44:52queries and the way we access query
- 6:44:55transposed is just by playing with the
- 6:44:58stride so let's do it like this and I
- 6:45:02have also written the comment on why we
- 6:45:04can do
- 6:45:05it so this is equivalent to accessing
- 6:45:09the
- 6:45:10query uh how many first okay what is
- 6:45:13this um what is this operation uh what
- 6:45:17is this operation here this is saying go
- 6:45:20to the query starting point starting um
- 6:45:24pointer to the query which is already
- 6:45:27pointing to the right batch and to the
- 6:45:29right head for which this particular
- 6:45:31program should work with and select a
- 6:45:34two-dimensional Vector where you repeat
- 6:45:36the query starting point along the uh in
- 6:45:40this case along the columns but we
- 6:45:42should be repeating it along the rows
- 6:45:43because we want to select rows of
- 6:45:46queries however if we want to select uh
- 6:45:48the query transpose we just invert the
- 6:45:51two Dimensions so this is a let me
- 6:45:53actually show you without doing the
- 6:45:55query transpose so let's do it
- 6:45:57simplified like this so to access the
- 6:46:01query um
- 6:46:03the query pointers without transposition
- 6:46:05we can just do like this go to the query
- 6:46:08tensor and create a 2d tensor where in
- 6:46:13the rows you put the starting point of
- 6:46:16each query that you want to get and um
- 6:46:20and replicate each of this pointer also
- 6:46:22on the column that's the meaning of
- 6:46:24adding this Dimension none this is
- 6:46:27equivalent to when you do in py torch
- 6:46:29the UNS squeeze like you are call
- 6:46:33offs Q multiplied not un squeeze I think
- 6:46:41one so this is equivalent to adding the
- 6:46:43column Dimension to this tensor and
- 6:46:46repeating all the values that are on the
- 6:46:48on all the um on the columns how many
- 6:46:52columns will be there it will be
- 6:46:54broadcasted when we sum it with the dist
- 6:46:56tensor here um this is a combination of
- 6:47:00UNS squeezing and broadcasting so we are
- 6:47:03taking the query vectors indicated by
- 6:47:06offs
- 6:47:07cuq um and um then we are uh for each
- 6:47:12query Vector we are selecting all the
- 6:47:15head Dimensions indicated by dim if you
- 6:47:18invert this broadcasting it will create
- 6:47:21the transpose of the the the query
- 6:47:24Vector that you're trying to access so
- 6:47:26this stuff here is equivalent to the
- 6:47:29these two lines so accessing query and
- 6:47:31then transposing
- 6:47:34and uh it's something that you can do U
- 6:47:37I could write down what is happening at
- 6:47:40the pointer level so basically you need
- 6:47:42to think of offc as being a vector of
- 6:47:47pointers uh we multiplied by the
- 6:47:50sequence stride which tells us how many
- 6:47:53element we need to skip to go from one
- 6:47:56query Vector to the next because each
- 6:47:59stride Q will be the stride will IND
- 6:48:02will be equal to in the case the head
- 6:48:03Dimension is 128 The Stride of the
- 6:48:06sequence Dimension will be 128 it means
- 6:48:09that to go from one query Vector to the
- 6:48:11next you need to um you need to uh uh go
- 6:48:16forward by 128 elements because I want
- 6:48:19to remind you that in the memory the
- 6:48:21tensors are always stored like flattened
- 6:48:25like each Dimension is flattened with
- 6:48:27the next Dimension so imagine you have
- 6:48:30three rows and four columns but the
- 6:48:32first you will have the first three rows
- 6:48:34then the sorry the first row so the
- 6:48:36first four columns then the next four
- 6:48:38columns then the next four columns row
- 6:48:40after
- 6:48:41row U it's difficult to visualize until
- 6:48:45you write it down so uh how to write it
- 6:48:48down take um create a vector of offs
- 6:48:52skew so what is offc at the beginning is
- 6:48:55is a range that is from here from 0 to
- 6:48:59100 no 0 to 32 0 1 2 3 4 five 6 7 etc
- 6:49:07etc we are multiplying each one with the
- 6:49:10stride of the sequence so this will not
- 6:49:13skip any element this will skip exactly
- 6:49:15128 elements this will skip exactly
- 6:49:19implying that the head Dimension is
- 6:49:21128 uh this will skip two times 128
- 6:49:25element this will skip three times 128
- 6:49:28elements and then we are adding also
- 6:49:32another Di di menion to this Vector so
- 6:49:34this will be a vector then you broadcast
- 6:49:36it on head Dimension number of columns
- 6:49:39and to each of them you add one number
- 6:49:43so it will become a vector like fall
- 6:49:45okay let me just do it guys otherwise I
- 6:49:47think it's too
- 6:49:49confusing okay so we have a vector that
- 6:49:52is as follows so zero then we have 128
- 6:49:55then we have two * 128 then we have 3 *
- 6:49:59128 etc etc we are adding how many
- 6:50:02columns indicated by off dim so off dim
- 6:50:05has how many columns it has a head dim
- 6:50:07number of columns please for Simplicity
- 6:50:09let's pretend it's not
- 6:50:11128 Dimensions let's pretend it's four
- 6:50:14dimensions so this will be four this
- 6:50:16will be 2 * 4 this will be three * 4 we
- 6:50:21are adding another dimension that is the
- 6:50:23dim
- 6:50:24Dimension each one multiplied by The
- 6:50:27Stride of dim which will be one because
- 6:50:29it's the last
- 6:50:31Dimension um stride de so we are adding
- 6:50:35how many columns
- 6:50:37four uh so we are adding um one 0 1 2 3
- 6:50:42I guess 0 1 2 3 right also to here this
- 6:50:45one we are adding oh oh my God 0 1 2 3
- 6:50:51and also to this one we are
- 6:50:53adding 0 1 2
- 6:50:573 uh okay and then also to this one we
- 6:51:01are adding 0 1 2 3 so what this will
- 6:51:04select this will select from the
- 6:51:07starting point of the pointer Q it will
- 6:51:10select the element zero then the element
- 6:51:13one then the element two and then the
- 6:51:15element three which is exactly the head
- 6:51:18dimension of the first Vector that we
- 6:51:20should be selecting then it will
- 6:51:23select uh the element four from the
- 6:51:26starting point of the vector the element
- 6:51:28uh sorry this one let me write the
- 6:51:29result of this operation so this one
- 6:51:31will be 0 1 2 three then it will select
- 6:51:34the element four 5 6 7 then it will
- 6:51:37select the element um eight I guess 9 10
- 6:51:4111 and then it will select the element
- 6:51:4312 13 14
- 6:51:4715 so from the starting point of where
- 6:51:51this Q is pointing it will select the
- 6:51:54first element right after this que the
- 6:51:56second element right after this que the
- 6:51:58third element right after this Q etc etc
- 6:52:00and this will be the f you can see that
- 6:52:03this will be the first query Vector this
- 6:52:05will be the second query Vector this
- 6:52:06will be the third query Vector this is
- 6:52:08the fourth query Vector because in the
- 6:52:10memory they are stored one after another
- 6:52:12they are flattened so in the memory they
- 6:52:14are stored like this they are stored
- 6:52:16like the
- 6:52:18following they are stored like this one
- 6:52:20after another so it will select all of
- 6:52:22them and we also create a virtual tensor
- 6:52:25with the right shape that we want to
- 6:52:28visualize it into so as you saw as we
- 6:52:30saw before when you work with a tensor
- 6:52:33layout in memory you can always view it
- 6:52:35as whatever shape you like based on the
- 6:52:38shape that you want and the reshaping is
- 6:52:40always free doesn't involve changing the
- 6:52:43arrangement of the elements in the
- 6:52:45memory I hope now it's more clear so now
- 6:52:47we can proceed
- 6:52:48further oh my God it was quite
- 6:52:51complicated so whenever I get stuck I
- 6:52:53just draw things and I think you should
- 6:52:55do it too because that's the only way to
- 6:52:57learn uh if you try to imagine
- 6:52:59everything in your head it's always
- 6:53:01difficult
- 6:53:03and we do the same job for the O vectors
- 6:53:05in the O vectors we don't access it as
- 6:53:08access it as um transposed because we
- 6:53:11don't need it in transposed only the Q
- 6:53:13we need it
- 6:53:15transposed okay it race through the
- 6:53:17sequence dimension of the query so we
- 6:53:20start from the query number
- 6:53:22zero in the current um well in the query
- 6:53:26we need to go through the all the
- 6:53:27sequence length Dimension because only
- 6:53:29the key we select the right key that we
- 6:53:31want to work with so I want to remind
- 6:53:33you here we fix the key and we go
- 6:53:35through all the
- 6:53:36queries but the query we need to start
- 6:53:38from zero until sequence length so the
- 6:53:40number of steps of this for Loop will
- 6:53:42be uh sequence length divide by block Q
- 6:53:47uh so if we have 1,000 elements in the
- 6:53:50sequence and the block Q is the 32 it
- 6:53:52will be 1,00 divide by 32 I'm bad choice
- 6:53:55of 1,000 should be 1,24 otherwise it's
- 6:53:58not divisible so then we go through each
- 6:54:01block in this for Loop and we load a
- 6:54:03block of Q the first one indicated by
- 6:54:06our pointer and at the end of the
- 6:54:08iteration we will move it to the next um
- 6:54:11to the next block of
- 6:54:13Q okay we'll add also the log log Su exp
- 6:54:17values that are stored in the M Matrix
- 6:54:20uh because we want to compute on the Fly
- 6:54:23PT PT is the transposed of the soft Max
- 6:54:28of query multiplied by the keys but we
- 6:54:30want to not take quy multiply by the
- 6:54:33transpose of the key and then do the
- 6:54:34transpose we just already access um Q as
- 6:54:37transposed so we can already compute a
- 6:54:39PT instead of computing p and then
- 6:54:41transposing
- 6:54:43it um so we load the offsets of the
- 6:54:48elements that we need from this log some
- 6:54:50exp
- 6:54:52x uh Matrix which is the m Matrix that
- 6:54:55we computed during the forward pass and
- 6:54:58we access a block of Q at a time the one
- 6:55:02we are currently working with in the
- 6:55:06iteration then we access a
- 6:55:10query key transposed already so we do
- 6:55:13the if you want to get a PT um P should
- 6:55:18be um this is actually not P because we
- 6:55:20didn't do the soft Marx it's actually s
- 6:55:23t but okay if you want to get PT you
- 6:55:26need to get the soft Max of
- 6:55:29STD um the soft Max of St is what it's a
- 6:55:35transpose of s what is s is a query
- 6:55:38multipied by transpose of ke so to get
- 6:55:39St you need to do um key transposed no
- 6:55:43key multiplied by query transposed so as
- 6:55:44you remember in the matrix
- 6:55:46multiplication if you transpose the
- 6:55:49matrix multiplication you need to also
- 6:55:50invert the two uh element in the matrix
- 6:55:53multiplication so that's why we are
- 6:55:55doing a key multiply by quy transposed
- 6:55:58this will give us s transposed we are
- 6:56:00also scaling it with the softmax
- 6:56:03scale before we apply the to apply the
- 6:56:06softmax we just need to do the
- 6:56:08exponential of each element minus its
- 6:56:11maximum divide by the normalization
- 6:56:13value but with the log sum XT we just
- 6:56:15need to um each element um subtracted by
- 6:56:19the M value which already includes the
- 6:56:21normalization factor uh I think I
- 6:56:24already did the derivation of this so we
- 6:56:26don't need to go through that again okay
- 6:56:29so now we have the PT block actually so
- 6:56:32this this formula I should have written
- 6:56:33St
- 6:56:35actually okay um then when doing the
- 6:56:41causal attention we also need to um mask
- 6:56:46out some
- 6:56:47values um so as you can see here so the
- 6:56:52in this case the Cal mask is applied
- 6:56:55after the soft Max has been computed
- 6:56:57because during this one is a you are
- 6:57:00used to uh compute the apply the soft
- 6:57:03the Cal mask before Computing the soft
- 6:57:05Max attention but this is actually
- 6:57:07during the forward pass because you
- 6:57:10don't want the normalization factor to
- 6:57:12be affected by the element that should
- 6:57:13be
- 6:57:14zero uh but we already computed the
- 6:57:17normalization factor so it cannot be
- 6:57:19affected anymore so we can compute we
- 6:57:21can mask out after applying the sofware
- 6:57:23because the normalization factor has
- 6:57:24already been calculated based on the
- 6:57:26fact that we applied the mask and that's
- 6:57:29why we we we can apply it after applying
- 6:57:31the soft Max
- 6:57:33uh so the mask is always the same so if
- 6:57:36the query is more than the the index of
- 6:57:39the query um so the mask is true in this
- 6:57:42case for all the values that do not need
- 6:57:44to be masked so all the values that do
- 6:57:46not need to be masked are this ones here
- 6:57:49uh and all the other value will be um
- 6:57:52will be replaced with the
- 6:57:53zeros all right so after we have the PT
- 6:57:59block already masked we can calculate
- 6:58:01the DV DV I will write I will point to
- 6:58:05the right formula in the paper so we
- 6:58:07load a block of the O why do we know to
- 6:58:10load a block of do let's look at the
- 6:58:12paper so how to compute the DV block so
- 6:58:15the DV block is computed
- 6:58:18as the old DV plus so a repeated sum as
- 6:58:22you can see as you can see it's here
- 6:58:24plus
- 6:58:25equal the old DV plus PT so here PT
- 6:58:30dropped indicates the P IJ after
- 6:58:34applying the Dropout in this
- 6:58:36implementation we don't support the
- 6:58:37Dropout and also very few models
- 6:58:40actually use the Dropout in the
- 6:58:42attention um so PT multiplied by DOI so
- 6:58:46a block of DOI and DOI is the same block
- 6:58:51that should be also um DOI and Ki Qi are
- 6:58:56referring to always the same block of
- 6:58:58rows in the respective um t s that's why
- 6:59:03because this inly iteration I indicates
- 6:59:05a block of q and a block of O but
- 6:59:10they're always referring to the same
- 6:59:12positions in the tensors because d o has
- 6:59:15the same shape as DQ so we go through
- 6:59:18the blocks of query and d o
- 6:59:21simultaneously because one is needed for
- 6:59:24DV so for D DV we need d o and for DK we
- 6:59:28need
- 6:59:29q and that's why we compute the DV as
- 6:59:32follows just like from the paper so PT
- 6:59:35block multiplied by d o as you can see
- 6:59:37it's a ppose multiplied by d o block so
- 6:59:41we have comput computed the do block um
- 6:59:44then we need to load the DI element that
- 6:59:47we computed precomputed
- 6:59:50initially uh the d uh with the first
- 6:59:53call to the function called the
- 6:59:55attention backward Pro
- 6:59:57pre-process because we will need it for
- 6:59:59Decay so let's see
- 7:00:03um and how many of them we are loading
- 7:00:06exactly the same number of query that we
- 7:00:08load because um they are we load always
- 7:00:12the same number of block size micro
- 7:00:15number of
- 7:00:16vectors okay I will copy some stuff and
- 7:00:19explain it step by step so um the next
- 7:00:23operation that we need to do is to
- 7:00:24compute this DK to compute DK we need
- 7:00:29DST to compute DST we need need to to
- 7:00:32get
- 7:00:34DPT so let's go one by one let's go from
- 7:00:38the B from the end to the beginning of
- 7:00:41this uh formulas so we don't uh we we we
- 7:00:45where where everything is used to where
- 7:00:47everything is created so let's start
- 7:00:49from DK if you look at the paper DK is
- 7:00:53equal to the old DK plus DS transposed
- 7:00:57multiply by a block of
- 7:00:59Q um and this is is what is written here
- 7:01:03so it is plus equal means basically just
- 7:01:05the old plus the new some um it's an
- 7:01:08incremental addition so increment the
- 7:01:11old K with some new stuff which is this
- 7:01:13stuff here so the soft Max scale
- 7:01:16multiplied because also there is a soft
- 7:01:18ma scale this tow here multiplied by the
- 7:01:22matrix multiplication between the St
- 7:01:24block and the transposed of um and and
- 7:01:30Q and Q you can see here this q but we
- 7:01:34don't have a Q we have a Q transpose so
- 7:01:37we take the transpose of Q transpose and
- 7:01:39it becomes back Q now let's look at this
- 7:01:42DST block DST is calculated as follows
- 7:01:47so in the formula of the paper we have
- 7:01:48DS d s is here it is yeah it is here and
- 7:01:54it is equal to a block P J multiplied
- 7:01:57element wise with DPI minus Di now um we
- 7:02:04don't need the S we need the S
- 7:02:06transposed so to compute the S
- 7:02:08transposed this is an element wise
- 7:02:11multiplication not a matrix
- 7:02:13multiplication which means that when you
- 7:02:14take the transpose of this operation you
- 7:02:16don't need to invert anything you just
- 7:02:17need to take the transpose of the two
- 7:02:20operan so to compute the St we take the
- 7:02:23transpose of P which is the PT and we
- 7:02:26already have that and then the transpose
- 7:02:29of everything that is inside of the
- 7:02:30parenthesis so this
- 7:02:32DPT minus di I where we inverted the
- 7:02:35rows with the columns so this DPT is
- 7:02:39what well in the paper we know the
- 7:02:41formula for DP DP is here and it is
- 7:02:44equal to D wait wait wait DP here and it
- 7:02:49is equal to d o multi by V transposed so
- 7:02:54uh but we don't need the DP we need the
- 7:02:56DPT and in this case it's not an element
- 7:02:58wise multiplication it is a matrix
- 7:03:00multiplication so um in order to get not
- 7:03:04DP DP but DPT we need to take the
- 7:03:07transpose of these two operants of this
- 7:03:09matrix multiplication and in the matrix
- 7:03:11multiplication when you take the
- 7:03:12transpose you need to also invert the
- 7:03:14order of the two operants so we need to
- 7:03:17take the VT transposed which becomes V
- 7:03:21so the V block Matrix multiplied by the
- 7:03:24other operand so D oi transposed and
- 7:03:28that's why we are doing the transpose of
- 7:03:30d o
- 7:03:31um right now I'm not going through all
- 7:03:34the single pointers because I already
- 7:03:36told you how to check what a pointer is
- 7:03:38pointing to and what an offsets is
- 7:03:40referring to I hope that now you have a
- 7:03:43better understanding on how these
- 7:03:44pointers work in uh Triton which is also
- 7:03:47the same way in the in which they work
- 7:03:49in Cuda because um in the GPU we only
- 7:03:53get a pointer to the starting point uh
- 7:03:55to the starting address of the tensor
- 7:03:57and then we need to work out all this
- 7:03:58indices we have computed the DK block
- 7:04:01block so we now go to the next query uh
- 7:04:04to the next block of
- 7:04:06queries and um so uh the next GL block
- 7:04:11of queries because we are fixing K and V
- 7:04:15blocks and we are iterating through all
- 7:04:17the queries so we need to move the query
- 7:04:19transpose
- 7:04:21pointers uh by stride sequence which
- 7:04:23means that how can we go from one query
- 7:04:26to the next and we multiply with the
- 7:04:29current um block Q which is a vector
- 7:04:32which indicates the pointers to the
- 7:04:34current element in Q that we are
- 7:04:36accessing and we do it also for the O
- 7:04:38and we use the block Q as element and
- 7:04:40the stride Q because the O and Q all
- 7:04:44have the same
- 7:04:46shape okay after we have run the for
- 7:04:48Loop of all the queries we can store
- 7:04:51this DK and DV block so we write it back
- 7:04:55as
- 7:04:56follows and this is the end of our
- 7:05:00function guys so so we save the DV block
- 7:05:03exactly in the position inside of the
- 7:05:07current okay DV is already I believe
- 7:05:09pointing to the right batch and to the
- 7:05:11right head because we incremented it
- 7:05:13here and also in the case of Decay then
- 7:05:16we need to tell it in the sequence
- 7:05:18Dimension where they should save this um
- 7:05:21block of K and V and this is indicated
- 7:05:24by this one we say and we create the the
- 7:05:27pointers just like before guys don't
- 7:05:29make me do it again it's a really really
- 7:05:32um easy if you write it down like you
- 7:05:34write this uh um Vector of key and
- 7:05:39values pointers which is not pointers
- 7:05:42actually they are a range of the of key
- 7:05:46and value that you need to take from the
- 7:05:48sequence
- 7:05:49Dimension you add another dimension that
- 7:05:52is the column so you repeat each value
- 7:05:54in the columns and then you add the
- 7:05:56dimension here for the head Dimension
- 7:06:00anyway after we have Cal at the pointers
- 7:06:02where we should store the DK and DV we
- 7:06:05store them in the um the pointers of um
- 7:06:08we store them in the DV um uh I mean we
- 7:06:12store them in the DV uh tensor and the
- 7:06:14DK tensor what do we save we save the DV
- 7:06:17block and the DK block which is the one
- 7:06:20that we were um uh incrementally
- 7:06:23changing in the for Loop that we have
- 7:06:26written okay now that we finish this one
- 7:06:28we can go to the next function that will
- 7:06:30do the other for Loop so let's do it
- 7:06:34okay so now we do the second part of the
- 7:06:38iteration which is this one so let me
- 7:06:40just copy it and then we we we describe
- 7:06:43it uh let's write it here okay we use
- 7:06:47the same lunch grid as before of course
- 7:06:50we need to declare this function and
- 7:06:51again we um we because the grid is
- 7:06:54defined for the block size Macro for
- 7:06:57what is the thing that we keep fixed and
- 7:07:00then we in the side of the for iteration
- 7:07:02we do um steps of block size micro in
- 7:07:07this case we are fixing q and we are
- 7:07:09iterating through K
- 7:07:11andv uh because we need to compute DQ
- 7:07:14right now we have computed DK and
- 7:07:17DV okay uh the I believe the arguments
- 7:07:20are the same as before so and actually
- 7:07:22this is also the reason why in the
- 7:07:24original implementation on the Tron
- 7:07:26website the author decided to um to use
- 7:07:30the same for Loop but different
- 7:07:32arguments and uh I believe it was a
- 7:07:35little confusing so that's why I just
- 7:07:36separated them I just repeat the code
- 7:07:38twice it's the goal of this video is to
- 7:07:41be as easy to understand as possible not
- 7:07:44to be as efficient as possible
- 7:07:46so uh let's go uh here so let me copy
- 7:07:50the signature again and we Define this
- 7:07:56function here okay so uh again we need
- 7:08:01to first move the query key and value uh
- 7:08:04to the right pointers which will point
- 7:08:06to the exact batch and the exact head
- 7:08:09that we are working with in this program
- 7:08:12so um let's do it let me check where is
- 7:08:16the code here and the first part is
- 7:08:19exactly the same as the other for Loop
- 7:08:21that we have
- 7:08:22written so let's go here and really is I
- 7:08:26just copied so it's exactly the same so
- 7:08:29we check what is the index batch head we
- 7:08:32move the query key value pointers to the
- 7:08:34right place the d o DQ DK DV point to
- 7:08:37the right place the m and d to the right
- 7:08:38place exactly like before so I don't
- 7:08:41think I need to explain that
- 7:08:43again and then we load a block of Q the
- 7:08:47one that we will keep
- 7:08:50fixed so
- 7:08:54DQ let me load a lot of stuff here
- 7:08:57actually
- 7:09:03okay we Define the offset that we will
- 7:09:05need to load the blocks of k&p in the
- 7:09:08head Dimension because we are going to
- 7:09:10iterate in the k
- 7:09:11andv um we will access them as
- 7:09:14transposed blocks so instead of
- 7:09:16accessing them directly as K and v We
- 7:09:19access access them as KT and VT and you
- 7:09:23know that that's possible just by
- 7:09:24changing the
- 7:09:26strides uh in this case because we are
- 7:09:29treating them as 2D vectors we treat the
- 7:09:31offs KV when you want to access K as
- 7:09:35just not transposed but K you treat this
- 7:09:38offs KV as a row Vector uh sorry a
- 7:09:42column Vector so you repeat on the rows
- 7:09:45each k um offset that you want to access
- 7:09:49in this case we are repeating it as a we
- 7:09:51are treating it as a row Vector so it
- 7:09:53will be repeated on the
- 7:09:55rows um sorry it will be broadcasted on
- 7:09:58the column Dimension and that's how you
- 7:10:01can access the transposed version of K
- 7:10:03and how you can access the transposed
- 7:10:05version of V another thing that we are
- 7:10:08doing is we are loading the Q Vector
- 7:10:10which Vector well based on ofq which is
- 7:10:13based on the start Q which is based on
- 7:10:16the exact starting point in which this
- 7:10:18particular program should be working
- 7:10:20with because this particular program
- 7:10:21works as two
- 7:10:23Dimensions uh the First Dimension
- 7:10:25indicate which batch and which head this
- 7:10:27program should be working with and the
- 7:10:29second dimension which is the program
- 7:10:30index number zero indicates which among
- 7:10:33all the sequence length which query this
- 7:10:36particular program is going to work with
- 7:10:37this is indicated by the index block um
- 7:10:41this should be actually Q in this case I
- 7:10:43forgot to change the name so actually
- 7:10:45let me change it so it's index Q because
- 7:10:48we start we skip some Q how many Q we
- 7:10:50skip um based on the index of the
- 7:10:53current program multiplied by how many
- 7:10:56uh blocks have already been processed by
- 7:10:58the previous
- 7:11:00programs this this will tell us inside
- 7:11:02of the sequence length what are the
- 7:11:04queries that this one needs to select so
- 7:11:06that's why we use the start query plus
- 7:11:09the range that is block Q so imagine the
- 7:11:12starting query for this program among
- 7:11:14all the sequence length is 100 then this
- 7:11:16will load the query row 100 1001 1002
- 7:11:21blah blah blah until 100 plus block Q
- 7:11:24minus
- 7:11:25one this is the range that we of the
- 7:11:28query vectors that we will load in this
- 7:11:30program
- 7:11:32uh we load the block of Q by using a Q
- 7:11:36Plus the offset repeated on the columns
- 7:11:40so we treat it as a column Vector but we
- 7:11:44repeat broadcast it on the rows
- 7:11:46Vector um where each uh column will be
- 7:11:50one head Dimension multiply by The
- 7:11:52Stride in this case we actually can also
- 7:11:54not multiply by The Stride because the
- 7:11:56stride in the uh Dimension Dimension so
- 7:11:59the last dimension of the batch is one
- 7:12:01uh because to go from one
- 7:12:04um actually the stride um how it is
- 7:12:07defined the stride of the last Dimension
- 7:12:10is always one because to go one element
- 7:12:12to the next element you should move to
- 7:12:15move it to by one
- 7:12:18element um so we load the DQ which is
- 7:12:21the stuff that we are going to compute
- 7:12:23in this
- 7:12:25um iteration and then we have D that we
- 7:12:29need to load and the do use the same
- 7:12:31offset as Q because D and DQ have the
- 7:12:34same shape and they work in the same way
- 7:12:36so we load a block of Q and we load the
- 7:12:40corresponding block of
- 7:12:42O of d o in this case and d o has the
- 7:12:46same shape as o which has the same shape
- 7:12:47as Q Plus we need to load also the M
- 7:12:51normalization factors which are in the M
- 7:12:53Matrix which one the cor the one
- 7:12:55corresponding to this particular group
- 7:12:57of queries that we are going to work
- 7:12:59with in this particular program
- 7:13:02we start with the uh offsets uh are the
- 7:13:06as you can see the offsets are the first
- 7:13:08block of KV starting from the zero
- 7:13:11position so because we will iterate
- 7:13:13through all the KVs and we start from
- 7:13:15the zero KV so the key key Vector zero
- 7:13:19and the V Vector zero and then we will
- 7:13:21move by block KV number of vectors
- 7:13:25forward at each
- 7:13:27iteration I hope I didn't go too fast
- 7:13:29because most of the things that are
- 7:13:31written here are very similar to what we
- 7:13:33have already done um in the the other
- 7:13:36for Loop so I don't want to be you know
- 7:13:38repeat myself too much um what it matter
- 7:13:41is actually the the formulas that we
- 7:13:43will use which is exactly the one in the
- 7:13:45paper
- 7:13:46so uh we go through this GL blocks of
- 7:13:51keyway KV we load the first block of KR
- 7:13:55transposed and V transposed which is
- 7:13:58loaded like this as usual you tell it
- 7:14:00what pointers the elements you want to
- 7:14:03load and what are the pointers of the
- 7:14:05another element that you want to load
- 7:14:06and it will load the the block that you
- 7:14:08are asking Tron to load inside of the
- 7:14:11SRAM so this stuff all reside in the
- 7:14:14SRAM and also Q resides in the SRAM and
- 7:14:16also d o reside in the
- 7:14:20SRAM um then we compute the query
- 7:14:23multiply by the transpose of the keys
- 7:14:24because we need to compute the P block
- 7:14:27so the query the qk block is just the
- 7:14:31query in the current query block with
- 7:14:33the K transposed in the current query
- 7:14:36Block in the current key
- 7:14:38block um why but we access query the
- 7:14:43keys already as transposed so we don't
- 7:14:45need to transpose it and anyway even if
- 7:14:48we did if we need to transpose it it's
- 7:14:50just um it's not um doesn't require any
- 7:14:54computation to transpose a matrix we
- 7:14:56just access it in a different
- 7:14:59way uh because in the memory layout it's
- 7:15:02always stored kind of as a flattened
- 7:15:04array um then we computed the P block
- 7:15:07which is the output of the soft Marx so
- 7:15:09each of the query key we substract the
- 7:15:12log sum exp value for the this uh block
- 7:15:16of queries that's why for loading the M
- 7:15:19Block we use the offsets of the queries
- 7:15:22that we are
- 7:15:23loading uh and as you remember the M
- 7:15:25Block already includes also the
- 7:15:27normalization factor because each m is
- 7:15:29actually the maximum value for each row
- 7:15:32plus the logarithm of the normalization
- 7:15:34factor that when you apply with the
- 7:15:36properties of the exponential it goes
- 7:15:38into the
- 7:15:40denominator okay and then we apply again
- 7:15:43the auto regressive
- 7:15:46masking
- 7:15:50oops what did I
- 7:15:53do let me go back to the code here so we
- 7:15:57have the stage this one so when we
- 7:16:00launch the back backward pass stage
- 7:16:02three indicates that it's a the in the
- 7:16:05forward pass we computed the caal
- 7:16:08attention and the one indicates that we
- 7:16:10computed the non-causal attention so if
- 7:16:13we computed the causal attention in the
- 7:16:15forward pass we also need to mask out
- 7:16:18these elements in the backward
- 7:16:20pass so we check um we created The Mask
- 7:16:24which tells us which index uh this mask
- 7:16:27is true for only for the elements for
- 7:16:30which the query index is more than the
- 7:16:32key index and if this is true then we uh
- 7:16:37we don't mask otherwise we
- 7:16:39mask um let's compute the next operation
- 7:16:44which is to compute DP and DS actually I
- 7:16:47let's compute directly DK and then we
- 7:16:49explain it like before so we start from
- 7:16:51the end and we go to where this stuff
- 7:16:54what is needed to computed so if you
- 7:16:57look at the formula uh let me check
- 7:17:02check this one we don't need I think
- 7:17:07okay uh let's go here to the iPad okay
- 7:17:13what we are trying to compute here is
- 7:17:16DQ so DQ as you can see in the paper is
- 7:17:21DQ is equal to the old DQ plus to which
- 7:17:26is the soft Max scale which is this
- 7:17:29stuff here m multiplied by the matrix
- 7:17:33multiplication between DS and K block so
- 7:17:37the DS block is here and the K block is
- 7:17:42the transpose of the KT block because we
- 7:17:44are accessing K already as a transposed
- 7:17:47block we could also access K directly as
- 7:17:50not transposed block by inverting if you
- 7:17:54want to access it as a transpose block
- 7:17:56just do like this like here none this
- 7:18:00will treat it as a row vector and
- 7:18:03broadcast along the columns otherwise
- 7:18:06and also this one you need to change so
- 7:18:08this one you should need to change
- 7:18:10because this one you need
- 7:18:12to treat it as um a column Vector the
- 7:18:16dimensions but if you want to access it
- 7:18:18as a k transpose then you just inverted
- 7:18:20these two operations I hope I didn't
- 7:18:23mess up anything so let's move forward
- 7:18:26um so okay we know that the formula for
- 7:18:29the uh DQ is exactly the same as the uh
- 7:18:33as the paper one but what is this DS
- 7:18:35block let's look at the paper this DS
- 7:18:38block is coming from this stuff here so
- 7:18:42this I believe this stuff here d s which
- 7:18:46is a
- 7:18:47pi the P block element wise
- 7:18:50multiplication with DPI minus di which
- 7:18:53is DPI minus d i now what is um the this
- 7:18:59P block the p block is exactly the
- 7:19:01output of the soft Max which we already
- 7:19:03have what is the DP block well the DP
- 7:19:06block is exactly d o multiplied by V
- 7:19:09transposed which is d o which we already
- 7:19:13loaded and it's here multiplied by the
- 7:19:15transpose of the V which we already load
- 7:19:17as transposed and this is how we comput
- 7:19:20the
- 7:19:21DQ uh let's Inc then of course we need
- 7:19:24to move to the next uh block of uh KVs
- 7:19:28so we increment the pointers just just
- 7:19:30like before so we move to the next block
- 7:19:34of keys and
- 7:19:36values and also we move the
- 7:19:40pointers um just like before and then we
- 7:19:43need to store the result of DQ and this
- 7:19:46way we only need to do one right to the
- 7:19:49hbm by dividing the for Loop like the
- 7:19:52following so if you look at the original
- 7:19:55algorithm uh I I don't know if the
- 7:19:57original algorithm actually corresponds
- 7:19:59in to to the implementation that they
- 7:20:01did in Cuda but I don't think so because
- 7:20:04it would not be so
- 7:20:05optimized but in the original algorithm
- 7:20:08in the paper they say that you need to
- 7:20:10go through all the keys and then while
- 7:20:12going through the keys you need to go to
- 7:20:14all the cues and for each queue that you
- 7:20:15visit then you need to write back the
- 7:20:18queue while you are updating it which is
- 7:20:19not optimized that's why we needed to do
- 7:20:22two for Loops one in which we fix the
- 7:20:25query and we updated the keys because
- 7:20:27each Keys update depends only on
- 7:20:29particular block of Que
- 7:20:31uh on all the blocks of Q sorry and then
- 7:20:34we fix the queries and we iterate
- 7:20:36through all the keys because one block
- 7:20:37of Q depends on all the blocks of
- 7:20:40K and this is why we split and this is
- 7:20:42the second Loop that we have
- 7:20:44written now we have written everything
- 7:20:47that we need to for flashh attention um
- 7:20:50the forward pass and the backward pass
- 7:20:52so uh we should be ready to uh launch
- 7:20:56the uh the kernel I hope I didn't make
- 7:20:59any mistake in copying the
- 7:21:01so I don't think I will try to launch it
- 7:21:04and if there is any any error I will
- 7:21:05just use my reference code which I have
- 7:21:07already written that I used as a copy
- 7:21:09the only difference up to now between my
- 7:21:12reference code and the one that we have
- 7:21:14written is the autot tuning which I
- 7:21:16didn't explain so let's talk about the
- 7:21:18autot tuning so the autot tuning is also
- 7:21:20something that was already present in
- 7:21:21the original paper and I kept it as is
- 7:21:24uh I removed the autot tuning for the
- 7:21:26backward
- 7:21:27pass but in the forward pass you if you
- 7:21:31check there is this code here that
- 7:21:33indicates um the autotuning
- 7:21:35configuration for Tron so Tryon
- 7:21:38basically um cannot know uh beforehand
- 7:21:41what is the best block size or what is
- 7:21:43the best block size for the query or
- 7:21:45what is the best block size for the key
- 7:21:47and values or what is the best block
- 7:21:49size for another dimension that we have
- 7:21:52we need to try based on the hardware
- 7:21:54that we are running on based on the
- 7:21:56availability on the SRAM based on the
- 7:21:59thread quaren that Tron can apply so I
- 7:22:02didn't talk also about thread quaring
- 7:22:05basically in Cuda you can choose if each
- 7:22:07thread does one Atomic operation for
- 7:22:09example in a matrix addition each thread
- 7:22:12is doing one addition of one particular
- 7:22:15element of the output Matrix or it's
- 7:22:16managing multiple elements this is
- 7:22:18called thread quaring and I think I
- 7:22:21didn't check the documentation but I
- 7:22:22believe Tron does it for you based on
- 7:22:25the Block size that you give it and the
- 7:22:27number of warps that you want the number
- 7:22:29of warps is what is um a block of
- 7:22:32threads of 32 threads that work Cooper
- 7:22:36cooperatively running the same
- 7:22:38instruction always at the same time the
- 7:22:41number of stages is more interesting
- 7:22:43it's an optimization that Tron does um
- 7:22:48basically it is not Loop and rolling so
- 7:22:52actually let's talk about uh let's talk
- 7:22:54about software pipelining because this
- 7:22:56is the last part that we need to
- 7:22:57understand from this code which is the
- 7:22:58aing so I believe that most interesting
- 7:23:01part here is not choosing the block size
- 7:23:03Q and The Block size K because that is
- 7:23:05just kind of you try whatever whatever
- 7:23:08configuration works best based on the
- 7:23:10timing CA Tron will actually run all
- 7:23:13these configurations for you every time
- 7:23:15the sequence length or the head
- 7:23:16Dimension changes and for every pair of
- 7:23:19head Dimension and sequence length it
- 7:23:21will choose the best configuration that
- 7:23:23runs in the least amount of time that
- 7:23:25gives you the best throughput actually
- 7:23:28um so let's look at this num stages what
- 7:23:31is it and how it works um so let's do it
- 7:23:36okay so uh software pipelining
- 7:23:39is is used when you have kind of a for
- 7:23:42Loop so you have a sequential operation
- 7:23:44in which each iteration does not depend
- 7:23:47on the previous iteration so the
- 7:23:48operations that you do in one iteration
- 7:23:50are independent from what you have done
- 7:23:51in the previous iteration which is more
- 7:23:53or less what we have done before in our
- 7:23:55for Loops actually there I believe there
- 7:23:58are um uh how to say conditions in which
- 7:24:02this doesn't have to be three so like
- 7:24:04the operations can depend on each other
- 7:24:06and you still can do software
- 7:24:08pipelining so for example imagine you
- 7:24:11have the following for Loop uh for Loop
- 7:24:14that Row from one to n and first you
- 7:24:17load some data then you load some other
- 7:24:19data then you do a matrix multiplication
- 7:24:21and then you store some data so here you
- 7:24:23are reading data here you are reading
- 7:24:25data here you are Computing some stuff
- 7:24:27and here you are writing data if we look
- 7:24:30at what happens at it each iteration we
- 7:24:33will see the following picture imagine
- 7:24:35our GPU is made up of a compute unit and
- 7:24:38a a unit that is dedicated to loading
- 7:24:41stuff so reading from the memory or
- 7:24:43writing to the
- 7:24:44memory what we will see in the time
- 7:24:46scale is that at the first iteration
- 7:24:49first we are reading some data and the
- 7:24:51compute unit is Idle because we need
- 7:24:53this data then we are reading some more
- 7:24:55data and the computer unit is Idle
- 7:24:57because we need this data then finally
- 7:24:58we have enough data and then we can
- 7:25:00compute this operation and the reading
- 7:25:02unit is idle and then we are writing
- 7:25:04some data back to the memory and the
- 7:25:06comput unit is again idle and then it
- 7:25:08will be idle for another two time steps
- 7:25:11until it has enough data to run the
- 7:25:13computation so as you can see this is
- 7:25:16not very efficient because at any time
- 7:25:19point in time there is only one unit
- 7:25:22working and the other is a sitting Idol
- 7:25:24so one way to uh optimize this for Loop
- 7:25:27is to do software pipelining and you can
- 7:25:29tell try to do it for your for Loops by
- 7:25:32telling it how many stages you want so
- 7:25:34let's see how it works so to pipeline a
- 7:25:37for Loop means that first of all you
- 7:25:39need to convert all these operations
- 7:25:41into async operations and in Cuda at
- 7:25:44least in the GPU of mvidia there are the
- 7:25:47async loading from the memory and the
- 7:25:49async load writing to the memory which
- 7:25:52basically means that I spawn a load
- 7:25:54operation and after and um when I I only
- 7:25:58I check if it has completed when I
- 7:26:00actually need it so I will spawn this
- 7:26:03operation and this instruction will
- 7:26:05return immediately and move to the next
- 7:26:07instruction here I will spawn a load
- 7:26:09iteration and this will return
- 7:26:10immediately and move to the next
- 7:26:12instruction and then I can uh compute
- 7:26:15but before Computing I just check if
- 7:26:17these two operations have completed so I
- 7:26:19can spawn immediately two reads and then
- 7:26:22I just check if this uh they have
- 7:26:24completed so with software pipelining
- 7:26:27what we are doing is we are pipelining
- 7:26:30operations of different iterations into
- 7:26:33a single iterations so first basically
- 7:26:36what we will do is we will do the read
- 7:26:38the first Matrix that we need for
- 7:26:40computing this matrix multiplication
- 7:26:42then at this next iteration we read the
- 7:26:46um the uh we we read the first Matrix of
- 7:26:50the second iteration and also read the
- 7:26:53second matric of the first iteration so
- 7:26:57I call it read a and read B which
- 7:26:59indicates read the first Matrix of the
- 7:27:02uh that we need and the b means the read
- 7:27:04the second Matrix that we
- 7:27:06need uh all these operations are
- 7:27:09asynchronous then I launch another
- 7:27:11asynchronous operation at the third
- 7:27:12iteration that says read the um the
- 7:27:16first Matrix of the third iteration and
- 7:27:19then read the uh second Matrix of the um
- 7:27:24of the second iteration and then compute
- 7:27:28the matrix multiplication because at the
- 7:27:30third iteration this one and this one
- 7:27:32should have completed but but while
- 7:27:36Computing the matrix multiplication I
- 7:27:38don't keep the loading unit idle because
- 7:27:41they are still Computing this this and
- 7:27:43this load this can only work if you can
- 7:27:46spawn async
- 7:27:48operations so at the third iteration I
- 7:27:51can compute this matrix multiplication
- 7:27:53by using this one and this one because
- 7:27:55they should have finished but while I'm
- 7:27:57Computing the matrix multiplication I
- 7:27:59already spound some async operations to
- 7:28:01load the data necessary for the second
- 7:28:03iteration and the third iteration so at
- 7:28:07the fourth iteration I will spound the
- 7:28:10loading of the data for the fourth
- 7:28:12iteration loading the data for the third
- 7:28:15iteration while Computing the matrix
- 7:28:16multiplication of the second iteration
- 7:28:18because they should have already
- 7:28:19completed by now uh actually it's not
- 7:28:22like we expect them to have been
- 7:28:24completed there are um Primitives in the
- 7:28:27language or in the Cuda language to
- 7:28:29check if the operation has completed so
- 7:28:31actually before doing the matric
- 7:28:33multiplication we will actually check if
- 7:28:35the asyn operation has finished so it's
- 7:28:37not like we just expect it to be
- 7:28:39finished with respect to time uh this is
- 7:28:42like in JavaScript you have these things
- 7:28:44called prom promise I remember and you
- 7:28:47can wait for the promise to be finished
- 7:28:50before you actually need them but you
- 7:28:51can spawn as many promise as you want in
- 7:28:54C I think they are called tasks so you
- 7:28:56spawn as many tasks as you want and then
- 7:28:59when you need the it then you just wait
- 7:29:01for them only the one that you needed
- 7:29:04while the other are still running in the
- 7:29:05background asynchronously this is the
- 7:29:07whole idea of software
- 7:29:09pipelining um software pipelining as you
- 7:29:13can see only works when you have a sync
- 7:29:15operations and also it increases the
- 7:29:17memory requirement for your program
- 7:29:19because when uh matrix multiplication
- 7:29:22one uh is going to run we may have
- 7:29:26enough data for the first two iterations
- 7:29:29plus plus half data for the third
- 7:29:31iteration so we increase the memory
- 7:29:33requirement for the um
- 7:29:36SRAM okay and P Tron will do this
- 7:29:40software pipelining for you it will
- 7:29:42convert all the load all the stores and
- 7:29:44maybe also the metrix multiplication
- 7:29:46into a sync operations and do this
- 7:29:48pipelining for you if you are confused
- 7:29:50by how it works there is another easy
- 7:29:52solution to explain you how it works
- 7:29:54because it's already something that we
- 7:29:55do in model training it is called
- 7:29:58pipeline parallelism
- 7:30:00so in pipeline parallelism it works as
- 7:30:03follows we have a very big neural
- 7:30:05network that does not fit in a single
- 7:30:07GPU so imagine this neural network is
- 7:30:09made up of three layers layer one layer
- 7:30:11two and layer three but this is so big
- 7:30:14it does not fit entirely in one simple
- 7:30:16GPU so one way would be to put this each
- 7:30:19layer into one GPU so we put for example
- 7:30:22layer one into GPU
- 7:30:24one a layer two into GPU 2 layer three
- 7:30:28into GPU number three so imagine we have
- 7:30:32an input for this Neal Network so we put
- 7:30:34it to the first GPU the GPU one will
- 7:30:37process the layer one and generate some
- 7:30:39output which will be transferred to the
- 7:30:42gpu2 which will calculate its own output
- 7:30:44and transfer it to the gp3 which will
- 7:30:46compute its own output and finally we
- 7:30:48will have the output of the Nal Network
- 7:30:50the problem is when you send the output
- 7:30:53of the gpu1 to the gpu2 for the gpu2 to
- 7:30:56do its own thing the gpu1 now is free so
- 7:30:59it is a waste of resources we could
- 7:31:01always should keep the gpus busy so what
- 7:31:04one thing that we can do is instead of
- 7:31:06sending all the the mega batch to the
- 7:31:09gpu1 we send many smaller batches how
- 7:31:12does it work imagine that we send the
- 7:31:15batch number zero so patch zero uh to
- 7:31:20the gpu1 the gpu1 will compute its
- 7:31:23output and send it to the gpu2 so now
- 7:31:24the gpu2 is Computing the batch number
- 7:31:28zero so now the batch zero is not here
- 7:31:30anymore but now the GPU one is free so
- 7:31:33we send another micro batch called the
- 7:31:35batch
- 7:31:38one then gpu2 will finish processing the
- 7:31:42batch zero and we'll send it to the
- 7:31:45batch to the GPU number three so now the
- 7:31:47GPU 3 has the batch number
- 7:31:49zero and the gpu2 now is free so we
- 7:31:52transferred and hopefully also gpu1 has
- 7:31:54finished so we transfer the batch number
- 7:31:56one from gpu1 to gpu2 the bches um and
- 7:32:01then the GP one will be free so so we
- 7:32:04transfer here becomes one and now this
- 7:32:07one is free so because it's gpu1 is free
- 7:32:10we can introduce another batch so batch
- 7:32:12number two etc etc etc so we always
- 7:32:15introduce when while moving one batch
- 7:32:18from one GPU to the other we introduce a
- 7:32:21new batch at the beginning of the
- 7:32:22pipeline and they shift by one position
- 7:32:24at every iteration this will keep the
- 7:32:27gpus always busy uh there is only one
- 7:32:30problem of the pipeline parallelism
- 7:32:32which is the this bubbling effect
- 7:32:34because to create this pipeline you at
- 7:32:36the beginning of this um okay actually
- 7:32:38in the pipeline paradism you also have
- 7:32:40the problem of the backward step so the
- 7:32:42backward step has to run exactly in
- 7:32:44Reverse in the order in which you
- 7:32:46receive the micro batches while in Tron
- 7:32:50when doing software
- 7:32:52pipelining you have the problem of the
- 7:32:54prologue and the epilog because you need
- 7:32:56to create this Pipeline and and
- 7:33:00to start the pipelining and at the end
- 7:33:03of the pipeline you need to uh use all
- 7:33:05the stuff that is currently in the
- 7:33:07pipeline so only in the beginning step
- 7:33:10and in the last step of this for Loop
- 7:33:12your um all the units of this GPU may
- 7:33:16not be working
- 7:33:17simultaneously which what does it mean
- 7:33:20it means that in order to use pipelining
- 7:33:22you want the number of iterations of
- 7:33:24your for Loop to be much more bigger
- 7:33:25than the number of stages in which your
- 7:33:27iteration is divided into in this case
- 7:33:29we have four stages these are called
- 7:33:31stages so you want the number of
- 7:33:33iterations to be much more to to be much
- 7:33:36larger than the number of stages all
- 7:33:38right guys finally I have completed the
- 7:33:41video um I hope that you learned a lot
- 7:33:44from this video I believe that we can
- 7:33:45run the Tron code so let's run it
- 7:33:48actually uh let's see I copied
- 7:33:51everything I believe we also put the
- 7:33:52code to test it but we didn't uh put the
- 7:33:57uh main method which we can copy right
- 7:34:00now I hope there is no error so I really
- 7:34:02hope there is no error I really hope so
- 7:34:07um let me check if I am in the right
- 7:34:10machine I am so let's just run
- 7:34:16program prey if there is an error I will
- 7:34:19just copy my own reference
- 7:34:21implementation but I hope it works
- 7:34:24because otherwise I forgot something so
- 7:34:27I'm running my code on an h100 uh
- 7:34:29because my company has h100 uh if you
- 7:34:32have a smaller uh GPU what you can do is
- 7:34:34you can reduce the sequence length uh
- 7:34:37you can reduce the BET BET size I think
- 7:34:39is already one when we call it uh oh no
- 7:34:43the BET size you can reduce the BET size
- 7:34:44the number of heads the sequence length
- 7:34:46you can even put head Dimension equal to
- 7:34:478 and sequence length equal to 16 uh
- 7:34:51let's
- 7:34:52check uh run backward Tron backward
- 7:34:56return the incorrect number of grading
- 7:34:58expected five got one
- 7:35:00we probably forgot some return statement
- 7:35:02I
- 7:35:03believe
- 7:35:05yes so I forgot the return statement
- 7:35:09here so in the backward pass after
- 7:35:10running the last for Loop we need to
- 7:35:13return the stuff that we have
- 7:35:15computed cross finger
- 7:35:18again okay passed so the backward pass
- 7:35:22that is computed by torch it is
- 7:35:24equivalent to our backward patch up to
- 7:35:2710 to the power of minus two error
- 7:35:30absolute error um so when you as you can
- 7:35:33see this backward that we run here is
- 7:35:36different than the backward that we run
- 7:35:37here because when you apply Tron
- 7:35:40attention it will introduce a new
- 7:35:42computation graph in the computation
- 7:35:43graph of our tensors that will include
- 7:35:46this Triton attention operator and when
- 7:35:48pyto want to compute the backward pass
- 7:35:50it will just call the backward function
- 7:35:52of this Tron attention to computed and
- 7:35:55it will populate the grad value of all
- 7:35:57the tensors that are the input to this
- 7:36:00Triton
- 7:36:01attention and this is how pytorch
- 7:36:03autograd Works guys uh thank you for
- 7:36:06watching my video guys it has been super
- 7:36:09super super
- 7:36:10demanding I spent many uh months first
- 7:36:13of all to learn myself about the Tron
- 7:36:15about Cuda about Flash atten Etc uh also
- 7:36:19I have a full-time job so it it's is
- 7:36:21really hard to make videos like this
- 7:36:22like I need to dedicate you know the
- 7:36:24nights the mornings the the weekends I
- 7:36:26spend three days just to record this
- 7:36:28video because sometimes I don't like how
- 7:36:29I explain something sometimes I make
- 7:36:31mistake or sometimes I need to restart
- 7:36:33because what I'm doing is wrong etc etc
- 7:36:37um I believe there should be no big
- 7:36:39errors in what I have done so far but
- 7:36:41for sure my notation is completely bad
- 7:36:44like because all the mathematics I know
- 7:36:46has been self-taught by I I learned it
- 7:36:49by myself so because I didn't learn it
- 7:36:51in Academia I have bad habits and I'm
- 7:36:54trying to get rid of them so I use the
- 7:36:56very bad notation sometime I call with
- 7:36:58the capital letter sometime with this
- 7:37:00lower case sometimes I just forget the
- 7:37:02index Etc so I'm trying to solve these
- 7:37:04problems um I believe I have explained
- 7:37:07everything so I should be uh you should
- 7:37:10have all the knowledge to derive all the
- 7:37:13formulas that you see in the paper of
- 7:37:14the flashh attention uh and you should
- 7:37:17also have an internal image on how the
- 7:37:19back the the the attention calculation
- 7:37:22is working block by blocks I know that I
- 7:37:25could have spent 20 hours explaining
- 7:37:27things better but I also have a life and
- 7:37:29I also have a wife so I I I I cannot
- 7:37:32make a 100 hours videos um also there
- 7:37:36were some interruptions making these
- 7:37:38videos I I removed some wisdom teeth so
- 7:37:40it took me at least one more than one
- 7:37:43week to to to to recover because it was
- 7:37:46so painful uh so thank you guys for
- 7:37:48watching my video I hope you learned a
- 7:37:50lot also this time I as you can see
- 7:37:52Triton is something new there is not
- 7:37:54much documentation so something that I
- 7:37:56have said about Tron may not be totally
- 7:37:58correct because really there is very
- 7:38:00little documentation so all the Tron
- 7:38:02that I have learned is by looking at the
- 7:38:04code written by others and try to
- 7:38:07understand
- 7:38:08it
- 7:38:09um and I think that's it guys so I wish
- 7:38:14you a wonderful day and see you next
- 7:38:16time on my channel
About this transcript
This page contains the full transcript of Flash Attention derived and coded from first principles with Triton (Python) by Umar Jamil, generated from the public captions YouTube serves with the video. The transcript has 76,417 words across 10,358 segments, with the original timestamps preserved so you can click any line to jump to that moment in the embedded player.
What you can do with it
Use the transcript to take notes, quote the speaker, build a study guide, generate a summary with ChatGPT or Claude via the YouTube Summary tool, or export it as a timed subtitle file with YouTube to SRT. You can also re-open it in the transcriber to choose a caption track available on the video.
Free YouTube transcript tool
YouTube2Text is a free YouTube transcript generator — no signup, no daily limit. Paste any YouTube link and get the full transcript instantly, with timestamps, click-to-jump, caption language selection, AI prompts for ChatGPT, Claude, and Gemini, and exports to TXT, SRT, VTT, or Markdown.