YouTube2Text

Flash Attention derived and coded from first principles with Triton (Python) — Transcript

by Umar Jamil · 76,417 words · 10,358 segments · language en · Watch on YouTube

Full transcript

  1. 0:00hello guys welcome back to my Channel
  2. 0:02today we are going to explore flesh
  3. 0:03attention now we are going to fles
  4. 0:06explore flesh attention from first
  5. 0:08principle which means that not only we
  6. 0:09will code flesh attention we will
  7. 0:11actually derive it so we pretend that
  8. 0:13the paper flesh attention paper never
  9. 0:15existed and we look at the attention
  10. 0:17competition and we look at the problem
  11. 0:19it has and we try to solve it step by
  12. 0:21step pretending that flashh attention
  13. 0:22never existed this will give us a deep
  14. 0:25understanding of how it works and also
  15. 0:27we will combine Theory with practice
  16. 0:29practice because we will code it now in
  17. 0:32order to code flash attention we we will
  18. 0:34need to write a kernel for our GPU and
  19. 0:37in our specific case I will be using an
  20. 0:38Nvidia GPU so Auda kernel but instead of
  21. 0:41writing C++ code we will use Tron which
  22. 0:43is a a way of converting python directly
  23. 0:46into um Cuda uh kernels that can run
  24. 0:50directly on the GPU and Tron you can
  25. 0:52think of it as a compiler that takes in
  26. 0:54Python and converts it into something
  27. 0:56that can run on the GPU um so let's look
  28. 0:59at the topics for today first of all I
  29. 1:01will give an introduction to multi-ad
  30. 1:03attention because we need to look at
  31. 1:04what is attention and how it's computed
  32. 1:06and what are the problems in Computing
  33. 1:08this attention then we will look at
  34. 1:10actually the most critical part of the
  35. 1:12attention computation is this softmax
  36. 1:14and how it impacts the computation and
  37. 1:16uh complexity we will look at what is
  38. 1:18online softmax then we will explore what
  39. 1:21is the GPU because we are going to write
  40. 1:22a kernel that will run on the GPU so we
  41. 1:24need to understand what is the
  42. 1:25difference for example the CPU and the
  43. 1:26GPU and what is the kernel and how it
  44. 1:29differ from a normal program that you
  45. 1:31write for the CPU we will look at how
  46. 1:34tensors are layout in memory so row
  47. 1:36major layout column major out Etc
  48. 1:39strides um we are going to look at block
  49. 1:42matrix multiplication Tron software
  50. 1:44pipeline all the optimization that Tryon
  51. 1:46does to our code finally we will be able
  52. 1:48to code the flash attention forward pass
  53. 1:51but of course we are not satisfied only
  54. 1:53by coding the forward pass we also want
  55. 1:54to code the backward pass but in order
  56. 1:57to code the backward pass we also need
  57. 1:58to understand how out works and the
  58. 2:01gradient descent works in the case of
  59. 2:03custom operations so we need to
  60. 2:05understand what are derivatives what are
  61. 2:07gradients what are jauan and then we
  62. 2:08calculate the gradient of the common
  63. 2:10operations that we use in Flash
  64. 2:12attention and finally we will have
  65. 2:14enough knowledge to code the backward
  66. 2:15pass for this reason this video is going
  67. 2:17to be super long but I hope you don't
  68. 2:20mind because we are going to learn a lot
  69. 2:22of course you may be wondering all of
  70. 2:24this requires a lot of knowledge that
  71. 2:26you may not have but that's not a
  72. 2:28problem because that's my problem
  73. 2:29because in this video I will make sure
  74. 2:31that if you only have high school
  75. 2:32calculus so you know what are
  76. 2:33derivatives you have basics of linear
  77. 2:36algebra like you know what is matrix
  78. 2:37multiplication or what is the transpose
  79. 2:39of a matrix and you have a basic
  80. 2:41knowledge of attention mechanism so like
  81. 2:43for example you have watched my previous
  82. 2:44video on the uh attention is all you
  83. 2:46need paper and you have a lot of patient
  84. 2:48that should be enough to understand all
  85. 2:51of this video because all the topics
  86. 2:53that I will introduce I will always
  87. 2:54introduce them in such a way that I um
  88. 2:57pretend that you don't know anything
  89. 2:58about that topic so so we try to derive
  90. 3:00everything from first principle
  91. 3:02everything from scratch okay now that we
  92. 3:04have seen the introduction let's go see
  93. 3:07the first part of the video which is the
  94. 3:09multihead attention all right let's talk
  95. 3:12about multi-head attention now I am
  96. 3:14using the slides from my previous video
  97. 3:16attention is all you need so uh we can
  98. 3:18look at very fast at what multi-head
  99. 3:20attention is and how it works I hope you
  100. 3:23remember the formula soft Max of the
  101. 3:25query multiplied by the transpose of the
  102. 3:26key divide by DK all multiplied by V
  103. 3:29because we will be using that a lot
  104. 3:31throughout the video now multi-ad
  105. 3:33attention starts from an input sequence
  106. 3:35or two input sequence in case we are
  107. 3:37talking about cross attention in the
  108. 3:39simple case of self attention we have
  109. 3:41one input sequence which is a sequence
  110. 3:43of in the case of language Model A
  111. 3:45sequence of tokens where we have sec
  112. 3:48number of tokens and each token is
  113. 3:51represented by an embedding so a vector
  114. 3:54with the model Dimensions the first
  115. 3:57thing that we do is we um convert this
  116. 4:00uh input sequence into query key and
  117. 4:02values through three linear projections
  118. 4:06one called WQ one called WK one called
  119. 4:09WV which in pytorch are represented
  120. 4:12through linear layers and these linear
  121. 4:14layers are of D model by D model so they
  122. 4:17do not change the shape of the input
  123. 4:19tensor and
  124. 4:22the after we do this job of projecting
  125. 4:26them they become three different
  126. 4:28sequences one called qu one called key
  127. 4:30and one called value so here I'm calling
  128. 4:32them Q Prime K Prime and V Prime then we
  129. 4:37divide them into smaller embeddings so
  130. 4:40each of this token which is made up of
  131. 4:43the model Dimensions we divide it into
  132. 4:45smaller tokens each one suppose we have
  133. 4:49four heads each one will have the model
  134. 4:52divided by four dimensions so this one
  135. 4:55is a sequence of tokens where each token
  136. 4:58is not the entire token but a part of
  137. 5:00the embedding of each token and this one
  138. 5:02is a another part of the embedding of
  139. 5:04the tokens and this one is another part
  140. 5:06of the embedding of the token Etc and we
  141. 5:08do this job for the query key and value
  142. 5:11sequence then we compute the attention
  143. 5:14as follows so the soft Marx of the query
  144. 5:16multiplied by the transpose of the key
  145. 5:18divide by the um the square root of DK
  146. 5:21where DK is the dimension of each head
  147. 5:24so how many dimensions each head is
  148. 5:27working with and then we do the
  149. 5:29multiplication with v and this will give
  150. 5:31us the output of the attention mechanism
  151. 5:34for each head and this job is done
  152. 5:36independently for each head this should
  153. 5:39be clear to you if it's not please watch
  154. 5:41my previous video on the attention
  155. 5:43mechanism because we will be working
  156. 5:45with this uh scenario a
  157. 5:48lot now uh then we take this o this uh
  158. 5:52the output of each head and then we
  159. 5:54concatenate it back in order to get the
  160. 5:58representation of each token uh as a
  161. 6:02full embedding so before we split this
  162. 6:04embedding into smaller embeddings this
  163. 6:07one here it's called the q1 Q2 Q3 Q4
  164. 6:10then after we compute the attention we
  165. 6:12get back um the output of each head and
  166. 6:15we concut it together to get back the
  167. 6:17full embedding Dimension which is this
  168. 6:19edge here we run it through another
  169. 6:21linear projection called wo which will
  170. 6:23be the output of the multi head
  171. 6:25attention now flesh attention is not
  172. 6:28concerned with all of these operations
  173. 6:30actually flesh attention is only
  174. 6:32concerned with the operation that
  175. 6:34require uh optimization and the
  176. 6:36operations that require optimizations
  177. 6:38are this one so the soft Marx of the
  178. 6:40query multiplied by the transpose of the
  179. 6:42key divide by the square root of DK
  180. 6:43multiplied by V which means that the
  181. 6:47projection of the input sequence through
  182. 6:48WQ WK and WV is not something that
  183. 6:51flashh attention is concerned about
  184. 6:53because that's a matrix multiplication
  185. 6:55so when you use a linear layer it's just
  186. 6:58a matrix multiplication of the inut with
  187. 7:00the weight Matrix of the linear layer
  188. 7:02and this kind of operation so the matrix
  189. 7:05multiplication is one of the most um
  190. 7:07optimized operation that we have in the
  191. 7:10GPU because the manufacturer of the GPU
  192. 7:12usually also releases um the necessary
  193. 7:15library for computing the the the metrix
  194. 7:18multiplication so actually these are
  195. 7:20quite fast and they do not require any
  196. 7:21optimization so flesh attention will
  197. 7:24pretend that the query is has already
  198. 7:26been passed through by WQ and the key
  199. 7:29has already passed through WK and the V
  200. 7:31has already passed from WB moreover
  201. 7:34flash attention will not be concerned
  202. 7:36with the projection with wo because
  203. 7:38that's also a matrix multiplication
  204. 7:40because the wo is always represented in
  205. 7:42byor as a linear layer so it's a matrix
  206. 7:44multiplication and matrix multiplication
  207. 7:47as we have seen are very um optimized so
  208. 7:50there is nothing to optimize there uh
  209. 7:53but what we need to optimize in terms of
  210. 7:55speed is this operation here soft marks
  211. 7:57of the query multiply by transpose of
  212. 7:59the keys by the square root of DK
  213. 8:00multiplied by V all right guys so now we
  214. 8:04have rehearsed what is multi head
  215. 8:05attention I also want to give you a lot
  216. 8:07of visualization which is
  217. 8:10basically here in the paper of the multi
  218. 8:13head attention we can see that we have
  219. 8:15the input that is uh v um K and Q so q k
  220. 8:20and V each of them runs through a linear
  221. 8:23layer which is the WQ WK and
  222. 8:26WV um then we do the scale dot product
  223. 8:30attention which is done independently
  224. 8:32for each head so each head will do query
  225. 8:34multipli by the transpose of the key
  226. 8:36divide by the square root of DEC where
  227. 8:38each query and each key is not the full
  228. 8:41embedding of each token but a part of
  229. 8:43the embedding of the token because we
  230. 8:44split them into smaller embeddings and
  231. 8:47eventually we take all the output of
  232. 8:49each of these head which are computed in
  233. 8:51parallel so that's why you see this
  234. 8:52Dimension Edge in the depth we
  235. 8:55concatenate them and then we run them
  236. 8:56through
  237. 8:57wo uh what are we we concerned with we
  238. 9:00are concerned with optimizing this
  239. 9:01particular block here the scaled do
  240. 9:03product attention so let's start our
  241. 9:06journey one thing that is very important
  242. 9:09to understand is why do we even need a
  243. 9:12better implementation of the attention
  244. 9:14mechanism and if you look at the flashh
  245. 9:16attention paper you will notice The
  246. 9:18Following part this is the paper flashh
  247. 9:20attention one and in the flashh
  248. 9:22attention one paper they describe the
  249. 9:24attention Implement imple implementation
  250. 9:26as it's done naively when using pytorch
  251. 9:29so first we do the multiplication of the
  252. 9:31query multiplied by the transpose of the
  253. 9:34keys then we apply the softmax to the
  254. 9:36output of this operation and finally we
  255. 9:38multiply the output of the softmax with
  256. 9:40the V Matrix to obtain the output of the
  257. 9:43attention the way this implementation is
  258. 9:45done by pytorch without any optimization
  259. 9:49is as follows so we load the first of
  260. 9:52all these tensors are residing in the
  261. 9:56GPU the GPU is made up of two main
  262. 9:59memories one is called the hbm which is
  263. 10:02the dram which is the the the ram of the
  264. 10:05GPU which is the 40 GB of the a100 for
  265. 10:09example so it's the biggest memory that
  266. 10:11we have in the GPU and then uh there are
  267. 10:15there is the shared memory so the
  268. 10:19problem of the GPU is that accessing
  269. 10:21this hbm so the global it's also called
  270. 10:24the global memory it's very very slow
  271. 10:26compared to the shared memory however
  272. 10:28the shared memory it's much much much
  273. 10:29smaller compared to the hbm and what
  274. 10:32they claim in the flesh attention paper
  275. 10:34is that the operation of the attention
  276. 10:36is IO bound meaning that if we keep
  277. 10:39accessing the um the um Global memory
  278. 10:44the overall uh operation of computing
  279. 10:47the attention is not because Computing
  280. 10:50all these operations it's slow but
  281. 10:51because we keep accessing the global
  282. 10:53memory which is slow so we call these
  283. 10:56kind of operations iob bound so the only
  284. 10:59way to improve this situation is to
  285. 11:02compute the attention inside the shared
  286. 11:04memory of the GPU which is much smaller
  287. 11:08which is much closer to the cores that
  288. 11:10actually do the computation so we we
  289. 11:12will need to kind of also split the
  290. 11:14attention computation into smaller
  291. 11:16blocks that can reside in the shared
  292. 11:19memory and we will see later in how this
  293. 11:23is possible through block matrix
  294. 11:24multiplication and this is in the paper
  295. 11:27here they call it the tiling and it's a
  296. 11:29very um uh how to say use the technique
  297. 11:32when doing um when writing kernels for
  298. 11:35the GPU uh which are usually involve
  299. 11:38some kind of metrix multiplication so
  300. 11:42now we know what problem the flashh
  301. 11:44attention is trying to solve it's trying
  302. 11:45to make sure that we do not need to
  303. 11:48access the hbm so the high bandwidth
  304. 11:50memory when Computing the uh attention
  305. 11:53but copying only a part of each Matrix
  306. 11:57inside the local memory so the sh shared
  307. 11:59memory of the GPU that is closer to the
  308. 12:02course and Computing a part of the
  309. 12:06output Matrix there then copying that
  310. 12:08part to the output in that is residing
  311. 12:11in the hbm and keep doing it for all the
  312. 12:13blocks in which we can divide these
  313. 12:15query key and value matrices and later
  314. 12:18we will see how this blocked computation
  315. 12:21is done but also we will see that the
  316. 12:23biggest problem in Computing this
  317. 12:25blocked computation is the softmax
  318. 12:27because the softmax needs to access
  319. 12:29all the row of the S Matrix to apply the
  320. 12:33soft Max
  321. 12:35because uh the the soft Max needs to
  322. 12:38have a normalization factor which is the
  323. 12:40sum of all the exponentials of all the
  324. 12:43values to which it is applied rowwise
  325. 12:45and we will see later how we will solve
  326. 12:47this problem so let's move
  327. 12:50on all right guys um okay when I say
  328. 12:53guys I mean guys and girls because I
  329. 12:55don't know in my usually I just say guys
  330. 12:58to you know but please girls don't feel
  331. 13:01excluded so we saw that FL fall flashh
  332. 13:04attention is only concerned in
  333. 13:06optimizing this soft Max of the
  334. 13:09transpose of soft Max of the query
  335. 13:11multip by three divide by the square
  336. 13:13root of DK multiplied by V and we need
  337. 13:16to introduce a little bit of notation so
  338. 13:18that we don't get lost um in the future
  339. 13:20slides first of all this is the formulas
  340. 13:23I took from the flashh attention paper
  341. 13:25but for now we Let's Pretend flashh
  342. 13:26attention never existed so we are trying
  343. 13:28to solve the the problem step by step
  344. 13:31now um we should treat this Q as
  345. 13:34something that has as the sequence that
  346. 13:36is the output of the input sequence that
  347. 13:39has already passed through WQ the K as
  348. 13:42something that has already passed
  349. 13:43through WK and v as something that has
  350. 13:46already passed through WV because we
  351. 13:48don't want to optimize the matrix
  352. 13:50multiplication because it's already fast
  353. 13:52enough another thing is let's talk about
  354. 13:55what are the dimensions of these
  355. 13:57matrices so we can then understand what
  356. 13:59is the the dimensions of the output of
  357. 14:02these operations we will see treat Q as
  358. 14:05a sequence of tokens with end tokens so
  359. 14:09n tokens where each token is D has D
  360. 14:13Dimension so lowercase D Dimensions why
  361. 14:17because usually we take the queries and
  362. 14:19then we split them into multiple heads
  363. 14:21so we have we pretend we have already
  364. 14:23done this splitting so we pretend we
  365. 14:25already took our input sequence we
  366. 14:27already run it through WQ and then we
  367. 14:28have already splited into multiple heads
  368. 14:31and each of these head will do the
  369. 14:34following operation so the the one we
  370. 14:37already saw and so the usual formula
  371. 14:40where multiply the transpose of the keys
  372. 14:42and each of this head will work with
  373. 14:44this dimensions for the query for the
  374. 14:47key and for the value sequence so now
  375. 14:50let's look at the uh the the dimensions
  376. 14:52of the output so the first operation
  377. 14:54that we will do is the query multiply by
  378. 14:56the transpose of the keys where the
  379. 14:57transpose of the keys is is a matrix
  380. 15:00that originally is n by D but become but
  381. 15:02with the transpose will be D by n so d
  382. 15:06by n and the result will be a matrix
  383. 15:09that is n byn because in a matrix
  384. 15:10multiplication the outer Dimensions
  385. 15:12become the dimension of the output
  386. 15:14Matrix what do we what is the next
  387. 15:17operation that we do we take the output
  388. 15:18of this operation so the query multiply
  389. 15:20by transpose of the keys and we run it
  390. 15:22through a soft Max operation and we will
  391. 15:23see what is the soft Max
  392. 15:25operation which preserves the shape of
  393. 15:28the input so it doesn't change the shape
  394. 15:30of the input Matrix it just changes the
  395. 15:32values of it and then we take the output
  396. 15:35of the softmax and we multiply it by V
  397. 15:38which will change the um which will uh
  398. 15:41change the of course the shape because
  399. 15:43the p Matrix is n by n so this one is n
  400. 15:47by n and V is um n by D so this one the
  401. 15:53output will be n byd the outer
  402. 15:55dimensions of this matrix
  403. 15:57multiplication now let's look at the
  404. 15:59details of each of these operations so
  405. 16:01when we do query multiply by transpose
  406. 16:02of the keys we will get a matrix that is
  407. 16:04n byn where each value in this Matrix is
  408. 16:08a dotproduct
  409. 16:09of a row of q and a column of K in
  410. 16:14particular the first element of this
  411. 16:16Matrix will be the dot product of the
  412. 16:18first query with the first key Vector
  413. 16:22the second element will be the
  414. 16:23dotproduct of the first query with the
  415. 16:25second key vector and the third element
  416. 16:28will be the first quy with the third key
  417. 16:30etc etc and the the let's say the the
  418. 16:34last row of this Matrix will be the dot
  419. 16:37product of the last query with the first
  420. 16:39key then the last query with the second
  421. 16:42key the last query with the third key
  422. 16:43etc etc until the last query with the
  423. 16:46last key um you may also notice that
  424. 16:49here I have written query transpose the
  425. 16:52key because when we um what is q1 first
  426. 16:56of all q1 is the first r of the query
  427. 17:00Matrix so little bit of um background on
  428. 17:04matrix multiplication so we know that
  429. 17:06when we do matrix multiplication each
  430. 17:08output element is one row of the first
  431. 17:11Matrix with one column of the second
  432. 17:12Matrix but we are doing the product of
  433. 17:15the first Matrix with the transpose of
  434. 17:17the second so it will be the do product
  435. 17:20of the one row of the query Matrix with
  436. 17:22one row of the key Matrix because we are
  437. 17:25doing the multiplication with key uh K
  438. 17:28transpose
  439. 17:30um when you take a vector from a matrix
  440. 17:34the usual notation so the in as as in
  441. 17:38how to say in um in in mathematics in a
  442. 17:41linear algebra we always pretend that a
  443. 17:43vector is a column Vector so we cannot
  444. 17:46just write Q multiplied by K because
  445. 17:49that would be mean uh that would mean we
  446. 17:51are doing the dot product of uh we are
  447. 17:55doing the kind of the matrix
  448. 17:57multiplication of one column Matrix with
  449. 18:00one column Matrix that is not possible
  450. 18:02because the shapes do not match so as a
  451. 18:05notation we write that we do the dot
  452. 18:07product of the first Matrix transpose
  453. 18:09which is a column Vector but we
  454. 18:11transpose it so it becomes a row Vector
  455. 18:13with the second Vector this is just
  456. 18:16because of notation guys so um you just
  457. 18:19need to pretend that this is the first
  458. 18:21query with the first key then the first
  459. 18:23query with the second key the first
  460. 18:24query with the third key etc etc etc so
  461. 18:27we are doing do of vectors then we apply
  462. 18:31this softmax
  463. 18:33operation the softmax operation what it
  464. 18:35will do it will transform each of these
  465. 18:38dot products which are scalars so the
  466. 18:40output of a DOT product is a scalar and
  467. 18:44it will transform each of these numbers
  468. 18:46in such a way that they become kind of a
  469. 18:48probability distribution rowwise which
  470. 18:51means that each of these numbers is
  471. 18:53between 0er and one and when we sum up
  472. 18:56these numbers together they are sum up
  473. 18:59to one and this condition this property
  474. 19:01will be valid for each row so this row
  475. 19:04also will sum up to one this row will
  476. 19:06sum up to one and this row will sum up
  477. 19:08to one etc etc
  478. 19:10etc let's see what is the softmax
  479. 19:12operation now uh given a vector so let's
  480. 19:17call it X which is made up of n
  481. 19:19Dimensions the softmax is defined as
  482. 19:22follows so it is the um the soft Max
  483. 19:26basically transforms this transforms
  484. 19:28this Vector into another Vector with the
  485. 19:31same Dimension where each item of the
  486. 19:33output Vector is calculated as follows
  487. 19:36so the E element of the output Vector is
  488. 19:39the exponential of the element input
  489. 19:42element divided by the summation of all
  490. 19:45the exponentials of all the dimensions
  491. 19:47of the
  492. 19:48vector basically this is called the
  493. 19:51normalization factor to make it all
  494. 19:53these numbers between zero and one we
  495. 19:55usually normalize that's why it's called
  496. 19:57the normalization factor and uh we use
  497. 20:00the soft Max because we want each of
  498. 20:02these numbers to be positive we don't
  499. 20:04want the stuff the output of this
  500. 20:06operation to be negative so that's why
  501. 20:08we use the exponential but there is a
  502. 20:11problem the problem is Imagine our input
  503. 20:13Vector is made up of many numbers that
  504. 20:16are maybe large so for example let's say
  505. 20:19X1 is equal to 100 X2 is equal to 200 X3
  506. 20:22is equal to 300 which is can happen um
  507. 20:26if we do the exponential of this number
  508. 20:28so the exponential of 100 that is going
  509. 20:31to be a huge number it's going to very
  510. 20:33close to Infinity uh at least compared
  511. 20:36to what we can store in a computer so
  512. 20:38the output of exponential of 100 may not
  513. 20:41fit into a floating Point 32 or a
  514. 20:43floating Point 16 number or even an
  515. 20:46integer of 32 bit so we cannot compute
  516. 20:50it because it will overflow our uh our
  517. 20:53variable our integer that is storing
  518. 20:55this value this
  519. 20:57output so we talk in this case about
  520. 21:00numerical instability so every time you
  521. 21:02hear the term numerical instability in
  522. 21:05computer science it means that the
  523. 21:06number cannot be represented within a
  524. 21:09fixed representation with the bits we
  525. 21:11have available which are usually 32 bit
  526. 21:14or 16 bit uh we have also 64bit but that
  527. 21:18would be too expensive to use um so
  528. 21:20let's try to find a solution to make
  529. 21:22this stuff here computable and
  530. 21:24numerically
  531. 21:25stable in order to make this soft Max
  532. 21:28operation numerically stable which means
  533. 21:31that we want these numbers to not
  534. 21:32explode or to become too small that they
  535. 21:35are not representable we need to find a
  536. 21:37solution and luckily it's quite easy so
  537. 21:40the softmax as we have seen before it is
  538. 21:43the following formula so each number is
  539. 21:45exponentiated and then we divide it by
  540. 21:47this normalization factor which is just
  541. 21:48the sum of the exponential of each input
  542. 21:50dimension of the input
  543. 21:52Vector um if we multiply the numerator
  544. 21:55and the denominator of a fraction with a
  545. 21:57constant uh with a number number then
  546. 21:59the fraction will not change so that's
  547. 22:00what we are going to do we are
  548. 22:01multiplying the numerator and this
  549. 22:02denominator with this factor C as long
  550. 22:06as C is not equal to zero of course uh
  551. 22:09then we can U take this C and by using
  552. 22:13the the distributive property of the
  553. 22:15product with respect to the sum we can
  554. 22:17bring this C inside of the summation as
  555. 22:19you can see here um then we can also
  556. 22:23write every number as the exponential of
  557. 22:25the log of itself because the
  558. 22:27exponential and the log will cancel out
  559. 22:31and um then we can by using the
  560. 22:34properties of the exponentials we know
  561. 22:35that the product of two exponential is
  562. 22:37equal to the sum of the is equal to the
  563. 22:40exponential of the sum of the arguments
  564. 22:42of each exponential and we do it on the
  565. 22:45numerator and in the denominator then we
  566. 22:48just call this quantity minus log c
  567. 22:51equal to K or k is equal to minus K is
  568. 22:55equal to log C so we can replace this
  569. 22:57quantity with k
  570. 22:59we can do that because this is a
  571. 23:01constant that we have chosen and we just
  572. 23:03are assigning it to another
  573. 23:05constant um so basically by doing this
  574. 23:08derivation we can see that we can sneak
  575. 23:11in a value inside of this exponential
  576. 23:14that if chosen carefully can reduce the
  577. 23:17argument of this exponential and we will
  578. 23:19choose this k equal to the maximum
  579. 23:22element inside of the input Vector that
  580. 23:24we are applying the soft Max to so that
  581. 23:28each this argument will be either zero
  582. 23:31in case x i is equal to the maximum
  583. 23:33element that we are processing of the
  584. 23:35vector or it will be less than zero and
  585. 23:38we know that the exponential when it's
  586. 23:40equal to zero will be equal to the
  587. 23:43output of the exponential will be one so
  588. 23:45the argument when it's zero it will be
  589. 23:46equal to one and when it's smaller than
  590. 23:49zero so it's in the negative range it
  591. 23:51will be between Z and one so which is
  592. 23:53easily representable with floating Point
  593. 23:5632 for example so this exponential will
  594. 23:59not explode anymore so basically to
  595. 24:02apply the the soft Max to a vector in a
  596. 24:06numerically safe way we need to find a k
  597. 24:10constant which is the maximum value of
  598. 24:12this vector and when we apply it we need
  599. 24:15to substract each element minus this
  600. 24:18constant that we have chosen so let's
  601. 24:20look at the algorithm to compute the
  602. 24:22soft Max so first of all given a vector
  603. 24:25or given an N byn Matrix because we want
  604. 24:28to apply the soft Max to this Matrix
  605. 24:30here which is n byn we need to go
  606. 24:33through each row of this Matrix and for
  607. 24:35each row we need to find the maximum
  608. 24:38value among the elements which takes
  609. 24:41time complexity linear with respect to
  610. 24:43the size of the vector to the size of
  611. 24:45the row to which we are applying the
  612. 24:47softmax then we need to compute the
  613. 24:49normalization factor which is this stuff
  614. 24:51here and we we cannot compute it before
  615. 24:55the step number one because we need to
  616. 24:57have the maximum element to compute this
  617. 24:59summation here and after we have
  618. 25:01calculated the the normalization factor
  619. 25:04we can then divide each elements
  620. 25:06exponential by the normalization factor
  621. 25:08and we cannot do the step number three
  622. 25:10before uh calculating the normalization
  623. 25:12factor because uh we need to divide each
  624. 25:15number by the normalization factor so if
  625. 25:17you like a pyo code for algorithms this
  626. 25:20is an algorithm for computing the
  627. 25:21softmax that we have seen right now so
  628. 25:24first we find the maximum of the row of
  629. 25:27to which we are applying the soft Max
  630. 25:29then we comput the normalization factor
  631. 25:31and then we apply the soft Max to each
  632. 25:33element which means that we calculate
  633. 25:34comput the exponential of each element
  634. 25:37minus the maximum value of the vector
  635. 25:40divided by the normalization factor now
  636. 25:44this pseo code is an algorithm that is
  637. 25:46quite slow because look at a practical
  638. 25:50example imagine we have this Vector here
  639. 25:52first we need to do step one find the
  640. 25:54maximum value in this Vector which is
  641. 25:56number five and this takes linear time
  642. 25:58computation then we need to calculate
  643. 26:00the normalization constant which is the
  644. 26:03sum of the exponential of each element
  645. 26:05minus the maximum value so e ^ of 3 - 5
  646. 26:09plus e to ^ of 2 - 5 etc etc and this we
  647. 26:13will call it l and then each we need to
  648. 26:16go again through this Vector again and
  649. 26:18take the exponential of each element
  650. 26:20minus the maximum divided by the uh
  651. 26:23normalization Factor so to apply the
  652. 26:26soft Max to an n byn Matrix we need to
  653. 26:29go through each element of this Matrix
  654. 26:32three times and these operations must be
  655. 26:34done sequentially so we cannot start
  656. 26:37operation two until we have done
  657. 26:38operation one and we cannot start
  658. 26:40operation three until we have done one
  659. 26:41and
  660. 26:42two so this is quite slow only to apply
  661. 26:47an operation that doesn't even change
  662. 26:49the shape of the matrix it's just uh
  663. 26:51normal normalizing the values so there
  664. 26:54must be a better way that that does not
  665. 26:57involve three sequential operations in
  666. 26:59which we need to go through this metrix
  667. 27:00three times let's
  668. 27:02see all right guys let's rehearse what
  669. 27:05is the problem that we are trying to
  670. 27:07solve the problem statement is the
  671. 27:09following can we find a better way to
  672. 27:12compute the softmax that does not
  673. 27:14involve going through the vector three
  674. 27:16times because let's look at the pseo
  675. 27:19code of the algorithm for computing the
  676. 27:20Lo the softmax that we have found so far
  677. 27:23imagine we have a vector made up of four
  678. 27:25elements the first thing that we need to
  679. 27:27do is to compute the maximum element in
  680. 27:29this Vector which means going through
  681. 27:32this for Loop here that allow us to
  682. 27:34compute the maximum element in this
  683. 27:36Vector which means that we start from
  684. 27:37the left side of the vector and
  685. 27:40iteratively go to the right side so we
  686. 27:41start from the first element arrive to
  687. 27:43the end and we compare the previously
  688. 27:46found maximum with the current element
  689. 27:48to find the global maximum basically
  690. 27:51this means that uh I I know that this is
  691. 27:53very simple uh I'm probably sure that
  692. 27:55you don't need to this example but
  693. 27:57making this example will help us
  694. 27:59understand what we will do next so
  695. 28:00please bear with me even if it's super
  696. 28:02simple what I'm doing um okay we at the
  697. 28:06beginning
  698. 28:07m0 is equal to minus infinity M1 is
  699. 28:12basically the for loop at the iteration
  700. 28:14number one which means that we are M1
  701. 28:17will be equal to the maximum of the
  702. 28:19previous estimate of the M which is
  703. 28:22minus infinity with the current element
  704. 28:25which is three so it will become equal
  705. 28:27to three then M2 will be equal to the
  706. 28:30maximum of the previously computed
  707. 28:32maximum so M1 so three with the current
  708. 28:35element which is two so it will be equal
  709. 28:37to three M3 will be equal to the maximum
  710. 28:41of the previously computed maximum so
  711. 28:43three with the current oops three with
  712. 28:46the current element which is five so it
  713. 28:48will be equal to five and M4 will be
  714. 28:50equal to the maximum of the previously
  715. 28:53computed maximum and the current element
  716. 28:55so it will be equal to five so this
  717. 28:57allow us to compute the maximum element
  718. 28:59so at the fourth iteration we will have
  719. 29:01the maximum the global maximum
  720. 29:03independently of what is the input
  721. 29:06array um delete okay after we have
  722. 29:09computed the maximum which we know is
  723. 29:11five we can compute the normalization
  724. 29:13factor so let's start with the l0 l0 is
  725. 29:16equal to Z L1 will be equal to the
  726. 29:19exponential of l0 so actually sorry it
  727. 29:22will be l0 plus the exponential of the
  728. 29:25current element so three minus the
  729. 29:28maximum element we have found in the
  730. 29:29previous for Loop so five then L2 will
  731. 29:33be equal to L1 plus the exponential of
  732. 29:36the uh the current element so it's two
  733. 29:39minus the maximum then L3 will be equal
  734. 29:43to L2 plus the exponential of um the
  735. 29:46current element 5 - 5 then L4 will be
  736. 29:49equal to the uh L3 + exponential of 1 -
  737. 29:555 if you expand this L this this will be
  738. 29:58basically equal to E power of 3 - 5 + e
  739. 30:03^ of 2 - 5 + e the^ of 5 - 5 + e the ^
  740. 30:08of 1 - 1 -
  741. 30:115 after we have computed this
  742. 30:14normalization Factor we can use it to
  743. 30:16normalize the each element in the input
  744. 30:18Vector which means that the X new X1 so
  745. 30:22X1 Prime let's see will be equal to e to
  746. 30:25the power of um uh what's the first
  747. 30:29element
  748. 30:30three - 5 divided by L that we computed
  749. 30:34in the previous for Loop so the L at the
  750. 30:37fourth
  751. 30:38iteration uh the new
  752. 30:41X2 so X2 Prime will be equal to the E
  753. 30:44to^ of 2 - 5 / L4 and X3 Prime will be
  754. 30:49equal to the E to power of 5 - 5 ided L4
  755. 30:54etc etc for all the
  756. 30:56elements uh I know this is super simple
  757. 30:58but it will help us later so in this for
  758. 31:02Loop we have that we need to go through
  759. 31:05the vector three TS because first we
  760. 31:06need to compute this for Loop then we
  761. 31:08need to compute this for Loop and then
  762. 31:10we need to compute another for Loop we
  763. 31:13cannot do them not in this sequence
  764. 31:15because in order to compute this for
  765. 31:16Loop we need to have the maximum element
  766. 31:18because we need it here and we cannot
  767. 31:21compute this forloop until we have
  768. 31:22computed the previous one because we
  769. 31:23need to have the normalization factor
  770. 31:26however we are stubborn and let's try to
  771. 31:29fuse these two operations into one for
  772. 31:31Loop which means that we go through the
  773. 31:33array and simultaneously compute Mi and
  774. 31:36simil in the same iteration we also try
  775. 31:38to compute LJ of course we will not be
  776. 31:41able to compute LJ because we don't have
  777. 31:43the global maximum because we didn't go
  778. 31:46through the all the um array yet however
  779. 31:49let's try to use the locally um the
  780. 31:52whatever estimate we have of the maximum
  781. 31:54so far so let's try to use instead of MN
  782. 31:56let's try to use m I so the local
  783. 31:58maximum that we have computed so far so
  784. 32:01if we apply the soft Max in this way in
  785. 32:03this fused way to this Vector we will
  786. 32:05have the following
  787. 32:07iterations um so this is our array or
  788. 32:11vector and the first step is MI so M1
  789. 32:15will be equal to the previous maximum
  790. 32:17which is minus infinity with the current
  791. 32:19element so the maximum minus infinity
  792. 32:21and the current element is equal to
  793. 32:23three and L1 will be equal to the
  794. 32:27previous l so l0 which is starts from
  795. 32:29zero plus e to the power of the current
  796. 32:32element minus we should be using the
  797. 32:34global maximum but we don't have the
  798. 32:36global maximum so let's use the whatever
  799. 32:38maximum we have so far so we can use
  800. 32:40three now at the second iteration we are
  801. 32:43at this element of the vector and we
  802. 32:45comput the maximum so far so the maximum
  803. 32:48so far is the previous maximum and the
  804. 32:50current element so the maximum of the
  805. 32:51previous maximum and the current element
  806. 32:53which is the maximum between three and
  807. 32:55two which is three uh and the the
  808. 32:58normalization factor is the previous
  809. 32:59normalization Factor plus exponential of
  810. 33:022 - 3 which is the current element minus
  811. 33:05whatever maximum we have so far now if
  812. 33:09our array were made only of these two
  813. 33:12elements so three and two then whatever
  814. 33:15we have computed is actually correct
  815. 33:17because the maximum that we have found
  816. 33:19is a three and it's actually the global
  817. 33:21maximum and the um normalization factor
  818. 33:24that we have computed is actually
  819. 33:26correct because each of the exponent
  820. 33:27itial has been computed with the global
  821. 33:29maximum because the first element was
  822. 33:31computed using three as the uh with the
  823. 33:35argument minus three and also the second
  824. 33:38element was computed with the argument
  825. 33:40with the argument having minus three in
  826. 33:42the in the argument which is the global
  827. 33:45maximum of the vector however when we
  828. 33:47arrive at the third iteration so let me
  829. 33:50delete this Vector so we arrive here at
  830. 33:52the third iteration the maximum will
  831. 33:54change which will also uh cause our
  832. 33:57normalization factor to get to to be
  833. 33:59wrong because we arrive at the element
  834. 34:02number three uh so the number five here
  835. 34:06and we computed the maximum so the
  836. 34:08maximum is the comparison of the
  837. 34:09previous maximum and the current element
  838. 34:12so the new maximum becomes five and the
  839. 34:15normalization factor is the previous
  840. 34:17normalization Factor so L2 plus the
  841. 34:19exponential of the current element minus
  842. 34:23the current estimate of the maximum
  843. 34:25which is five however
  844. 34:28if you look at this L3 this is wrong why
  845. 34:31because L3 is equal to if you expand
  846. 34:34this summation it will be equal to e to
  847. 34:36the power of 3 - 3 + e to power of 2 - 3
  848. 34:42+ e to the power of 5 minus 5 this
  849. 34:46exponential here is using five as the
  850. 34:49global maximum this exponential here is
  851. 34:51using three as the global maximum and
  852. 34:53this one is using three as the global
  853. 34:54maximum so the first two element have
  854. 34:56been computed
  855. 34:58thinking that the global maximum is
  856. 35:00three but actually we later we found a
  857. 35:02better Global maximum which is five so
  858. 35:04which makes this normalization Factor
  859. 35:06wrong however can we fix at the third
  860. 35:10iteration whatever normalization we have
  861. 35:12computed so far up to the second
  862. 35:14iteration actually we can because if we
  863. 35:18expand this so as we have here we have
  864. 35:21expanded
  865. 35:22it what we need here is here to have
  866. 35:25minus5 because that's actually the
  867. 35:27Global maximum that we have found so far
  868. 35:29not the minus three that we had at the
  869. 35:31previous iteration so and here we also
  870. 35:34need to fix this replace this -3 with
  871. 35:36minus5 how can we do that well if we
  872. 35:39multiply this one here and this one here
  873. 35:41with a correction factor that will sneak
  874. 35:45in a new maximum inside of this
  875. 35:48exponential then we solve the problem
  876. 35:50and actually this correction factor is
  877. 35:52very easy to calculate because at the
  878. 35:54third iteration if we multiply L2 so the
  879. 35:57previous prly computed normalization
  880. 35:59factor with this Factor here which is
  881. 36:00the exponential of the previous estimate
  882. 36:03of the maximum minus the current
  883. 36:05estimate of the maximum so five we will
  884. 36:08see that by the properties of the
  885. 36:12exponentials this one here will become e
  886. 36:14to the^ of 3 - 3 + 3 - 5 so this minus 3
  887. 36:18will cancel out with this three and also
  888. 36:21the second Factor will have this three
  889. 36:23will cancel out with this minus three
  890. 36:25will cancel out with this three and they
  891. 36:27will become e to ^ of 3 - 5 and 2 to the
  892. 36:30power of u e to the^ of 2 - 5 which is
  893. 36:33actually correct because at the third
  894. 36:35iteration we should be actually have we
  895. 36:38should be using minus5 as the maximum of
  896. 36:41the array so far um so basically what we
  897. 36:44have found is a way to fix whatever
  898. 36:48normalization Factor we have computed so
  899. 36:50far while iterating through the array
  900. 36:53when we found we when we find a better
  901. 36:56maximum compared to what we have so far
  902. 36:59and when we don't need to fix anything
  903. 37:01then the formula still stands because
  904. 37:03what we did here as a multiplic as a
  905. 37:06correction factor so this is the
  906. 37:08correction factor this correction factor
  907. 37:11is nothing more than the previous um
  908. 37:14previous maximum so the previous
  909. 37:16estimate of the maximum minus the
  910. 37:18current estimates of the maximum at the
  911. 37:20current iteration so the current
  912. 37:23Max um so this is basically M of IUS one
  913. 37:27and this is M of I so the current
  914. 37:30maximum at the current iteration and let
  915. 37:32me delete it otherwise it remains
  916. 37:34forever in my slides um so basically
  917. 37:38when we arrive to the last element we
  918. 37:40will see that the maximum doesn't change
  919. 37:42because we compare the previous maximum
  920. 37:44with the current element which is less
  921. 37:46than the previous maximum so the maximum
  922. 37:48doesn't change and we don't need to fix
  923. 37:51anything because the the the the
  924. 37:54previous L3 so the previously computed
  925. 37:57uh normalization factor is correct
  926. 37:59because they have all been using the
  927. 38:01minus5 so when we don't need to fix
  928. 38:03anything we just multiply by e to the
  929. 38:06power of the previous maximum minus the
  930. 38:08current maximum which is e to the power
  931. 38:10of zero in this case so it's not fixing
  932. 38:12anything so we have found a way to fix
  933. 38:16the previously computed normalization
  934. 38:19Factor while going through the array
  935. 38:21even if at the current iteration we
  936. 38:23don't have the global maximum yet so
  937. 38:26that every time the maximum changes we
  938. 38:28can fix and every time it doesn't change
  939. 38:30we just multiply with e to the^ of Z
  940. 38:33which is like multiplying with one so
  941. 38:36the new algorithm that we have found for
  942. 38:38the softmax is the following so we start
  943. 38:40with m0 equal to minus infinity we start
  944. 38:43with l0 equal to Z we go through the
  945. 38:45array we compute the locally uh the the
  946. 38:48local maximum so up so the maximum so
  947. 38:51far from the zeroth element to the E
  948. 38:55element so to the elements at which we
  949. 38:57are we are doing the
  950. 38:58iteration and the previously computed Li
  951. 39:02can be fixed by using this correction
  952. 39:05factor which is e to the power of the
  953. 39:06previous maximum minus the current
  954. 39:09maximum plus the exponential of the
  955. 39:12current element minus the current
  956. 39:14estimate of the maximum in this way we
  957. 39:17go through the array only once and we
  958. 39:20obtain two values the global maximum at
  959. 39:23at the end at the same time the uh the
  960. 39:26the ization factor and then we can use
  961. 39:29it to compute the softmax so we made
  962. 39:32three transformed the three passes
  963. 39:34through the array into two passes
  964. 39:37through the array and this is very
  965. 39:39important and we will see how we
  966. 39:41actually use it to derive flesh
  967. 39:44attention the example that I have given
  968. 39:46you so far is not really a proof that
  969. 39:49our algorithm will work in every case
  970. 39:51because we made a very simple example by
  971. 39:53using a vector made up of four elements
  972. 39:57but but does our new algorithm work in
  973. 40:00every single case with whatever the
  974. 40:02numbers are we need to prove that so we
  975. 40:05will prove that by induction so what
  976. 40:07first of all what are we trying to prove
  977. 40:10we have fused the first two for Loops
  978. 40:12into one for loop as you can see here
  979. 40:15what we expect is that at the end of
  980. 40:18this for Loop this MN so the m at the
  981. 40:22last iteration will be actually the
  982. 40:23global maximum in the vector and this Ln
  983. 40:27so the L at the last iteration will be
  984. 40:30equal to the sum of all the exponential
  985. 40:33of all the
  986. 40:34elements minus the maximum element of
  987. 40:37the vector so the global maximum of the
  988. 40:39vector and we need to prove that because
  989. 40:42what I did before was an example and
  990. 40:44that was not really a rigorous proof and
  991. 40:47the way we will prove it is by induction
  992. 40:49which is a typical way of proving these
  993. 40:51kind of um
  994. 40:53theorems now proof by induction
  995. 40:56basically Works in the following way we
  996. 40:58need to prove that our algorithm work
  997. 41:01works for a base case for example with
  998. 41:03Nal to 1 and then we pretend we assume
  999. 41:08that the algorithm work works on n and
  1000. 41:12we need to prove that it also works for
  1001. 41:14n + one if this holds then we have
  1002. 41:18proven our algorithm for every possible
  1003. 41:20n because it will work for the base case
  1004. 41:23so for example n equal to 1 and then by
  1005. 41:25using the induction step we say so this
  1006. 41:29if it works for n then it also works for
  1007. 41:31n + one then it means that it will also
  1008. 41:33work for two but then if it works for
  1009. 41:35two then it should also work for three
  1010. 41:36because of the induction step that we
  1011. 41:38will prove and if it works for three
  1012. 41:40then it will also work for four etc etc
  1013. 41:42up to
  1014. 41:43Infinity so let's prove it for the base
  1015. 41:45case which is n equal to 1 uh it's very
  1016. 41:48simple so uh at n equal to 1 this for
  1017. 41:52Loop will only have one iteration so M
  1018. 41:54M1 and L1 M1 will be be the maximum of
  1019. 41:58the previous M which is minus infinity
  1020. 42:00because we initialize m0 equal to minus
  1021. 42:03infinity um so it will be equal to U the
  1022. 42:07maximum of the previous M and the
  1023. 42:09current element which is X1 so it will
  1024. 42:11be equal to X1 whatever X1 is uh X1
  1025. 42:15usually will never be equal it cannot be
  1026. 42:17equal to minus infinity um because it's
  1027. 42:20a number in fixed representation so it
  1028. 42:23cannot be minus infinity um so we the
  1029. 42:26the X the M1 at the end so it will
  1030. 42:29because we have only one element n equal
  1031. 42:31to one this is M1 is also the last um M
  1032. 42:37of this of this for Loop it will be
  1033. 42:39equal to the global maximum of the
  1034. 42:41vector made up of only one element and
  1035. 42:43L1 will be equal to the previous L which
  1036. 42:46we start from zero so l0 multiply by a
  1037. 42:50correction factor which will be in this
  1038. 42:52case e to the power of minus infinity
  1039. 42:54because the correction factor is the
  1040. 42:56previous estimate of the max of the max
  1041. 42:59minus the current estimate of the max
  1042. 43:01but the previous estimate of the max is
  1043. 43:02minus infinity minus X1 it is equal to
  1044. 43:05minus infinity so this one will be this
  1045. 43:08will be canceled out and then plus e to
  1046. 43:11the^ of X1 minus the current maximum
  1047. 43:14which is X1 so
  1048. 43:17M1 and if this one will be equal to the
  1049. 43:21sum of all the elements of the vector
  1050. 43:23which is made up of only one element
  1051. 43:25minus uh the maximum element in the
  1052. 43:28array which is X1 so we have proven that
  1053. 43:31it works for n equal to 1 now we assume
  1054. 43:35that it works for n does it also work
  1055. 43:38for an array of vect or with a vector of
  1056. 43:41size n + one so let's see what happens
  1057. 43:46at the n + one iteration at the n+ one
  1058. 43:50iteration we will be doing the maximum
  1059. 43:52of the previous estimate of M which is
  1060. 43:54the m at the end iteration and the
  1061. 43:57current element so xn of + one this by
  1062. 44:01the properties of the Max uh function it
  1063. 44:05will be actually equal to the maximum of
  1064. 44:07the global Vector up to n + one uh
  1065. 44:11because um the maximum will choose
  1066. 44:13whatever is the maximum between the
  1067. 44:15previous estimate and the current
  1068. 44:17estimate and Ln + one which is the
  1069. 44:20normalization factor at the n + one
  1070. 44:22iteration will be equal to the Ln so the
  1071. 44:25previous estimate not previous by the
  1072. 44:27previous normalization Factor at at the
  1073. 44:30end iteration multiplied by the
  1074. 44:33correction factor which is the previous
  1075. 44:35maximum minus the current maximum plus
  1076. 44:38the exponential of x uh the current
  1077. 44:42element minus the current estimate of
  1078. 44:46the
  1079. 44:47maximum but
  1080. 44:49Ln we have we assume that this um
  1081. 44:53property so this algorithm works up to n
  1082. 44:57so Ln is for sure equal to the sum of
  1083. 45:01all the exponentials of the previous of
  1084. 45:04the vector up to n minus the local
  1085. 45:08maximum of the uh Vector up to the end
  1086. 45:12element which is
  1087. 45:14MN we multiply by the correction factor
  1088. 45:18if there is something to correct which
  1089. 45:20will be the previous maximum minus the
  1090. 45:23current maximum plus the exponential of
  1091. 45:25the current element minus the current
  1092. 45:27exp estimate of the
  1093. 45:29maximum now
  1094. 45:31by the properties of the exponentials so
  1095. 45:34we can bring this one inside of the uh
  1096. 45:37summation and we will see that this MN
  1097. 45:40and this MN will cancel out because it
  1098. 45:42will be exponential of XJ minus MN + MN
  1099. 45:46minus MN + one so this MN and this MN
  1100. 45:49will cancel out and we obtain this one
  1101. 45:51plus this Factor here that remains
  1102. 45:54unchanged however you can see that this
  1103. 45:57this stuff here is exactly the in the
  1104. 46:00argument of this summation for the at
  1105. 46:02the iteration n + one so it is this one
  1106. 46:05is e to the power of XJ where J is going
  1107. 46:09from 1 to n minus MN + 1 + e ^ of x n +
  1108. 46:151 - MN + 1 so the J only appears here
  1109. 46:20and it's equal maximum to n and this is
  1110. 46:22similar to being a j with n + one so we
  1111. 46:26can increase increase the index of this
  1112. 46:28summation by one and it will be the same
  1113. 46:32um and it will result in the same
  1114. 46:34summation so we have proven that also at
  1115. 46:37the n + one iteration we will have that
  1116. 46:41the L will be equal to the sum of all
  1117. 46:44the elements of the array the
  1118. 46:46exponential of all the elements of the
  1119. 46:48array up to the n+ one
  1120. 46:50element uh minus the maximum up to the n
  1121. 46:53+ one element so we have proven that if
  1122. 46:57it works for n then it also works for n
  1123. 46:59+ one um this is enough to prove that it
  1124. 47:02works for all sides of
  1125. 47:04arrays um don't worry if you didn't get
  1126. 47:08uh the proof by induction it is uh if
  1127. 47:10it's the first time you are seeing this
  1128. 47:12kind of proof it may take a little bit
  1129. 47:14to to get it um if you want to learn a
  1130. 47:17bit more about proof by induction I
  1131. 47:19recommend watching some other proof it's
  1132. 47:21very simple it's just you need to get
  1133. 47:22into the right mindset anyway let's move
  1134. 47:25forward
  1135. 47:28all right let's talk about block matrix
  1136. 47:30multiplication I know that you want to
  1137. 47:32jump to the code immediately and we will
  1138. 47:34go there we just need a little more
  1139. 47:36Theory actually so imagine we are doing
  1140. 47:39a matrix multiplication so we have a
  1141. 47:41matrix a we want to multiply it with a
  1142. 47:44matrix B and it will produce an output
  1143. 47:46Matrix C imagine the dimensions of the
  1144. 47:49first Matrix are M by K the second
  1145. 47:52Matrix is a k by n it will produce an
  1146. 47:55output Matrix that is m by n now imagine
  1147. 47:59we want to parallelize the computation
  1148. 48:01of this output Matrix I know that I
  1149. 48:03didn't talk about gpus yet so we will
  1150. 48:06not talk about gpus we will talk about
  1151. 48:09parallelization in the case of a
  1152. 48:11multicore CPU with which you are very
  1153. 48:14probably familiar with because right now
  1154. 48:17in nowadays when you buy a computer you
  1155. 48:19have a CPU and usually you can buy a
  1156. 48:22single core CPU or multie like a two
  1157. 48:24core four core eight core etc etc each
  1158. 48:27of the these cores are actually kind of
  1159. 48:29small CPUs inside your CPU that can
  1160. 48:31execute operations in parallel how to
  1161. 48:34parallelize the matrix multiplication
  1162. 48:37imagine you have this matrix
  1163. 48:39multiplication to parallelize each of
  1164. 48:41the output element in this C Matrix is a
  1165. 48:43DOT product of a row of the a matrix
  1166. 48:47with a column of the B Matrix for
  1167. 48:49example this element on the top left is
  1168. 48:52the dotproduct of the first row of a and
  1169. 48:55the First Column of B this element on
  1170. 48:58the top right of C is the dot product of
  1171. 49:00the first row of a and the last column
  1172. 49:03of B this element on the bottom left is
  1173. 49:06the dot product of the last row of a and
  1174. 49:09the First Column of B etc etc for all
  1175. 49:11the other elements now to parallelize
  1176. 49:14this computation we need as many cores
  1177. 49:16as is as there are elements in C if we
  1178. 49:19want to parallelize it uh so if M and N
  1179. 49:23are very small then maybe we have enough
  1180. 49:25course but imagine M and N are quite big
  1181. 49:29we imagine like 100 by 100 we don't have
  1182. 49:3210,000 cores right now in the CPUs so
  1183. 49:36how can we parallelize a matrix um
  1184. 49:39operation by using less cores than there
  1185. 49:42are elements in The Matrix itself that's
  1186. 49:46when we talk about block matrix
  1187. 49:48multiplication basically block matrix
  1188. 49:50multiplication means that you can divide
  1189. 49:53the original Matrix into smaller blocks
  1190. 49:56of of elements and then the operations
  1191. 50:00of matrix multiplication can be computed
  1192. 50:02between these blocks for example imagine
  1193. 50:05we have a matrix that is 8x4 it means
  1194. 50:08that it has eight
  1195. 50:10rows and four columns which means that
  1196. 50:13it has 32 elements and then we are
  1197. 50:16multiplying it with another Matrix that
  1198. 50:19is 4X 8 so it has four rows and eight
  1199. 50:24columns so it also has a 3 two elements
  1200. 50:28the output Matrix will should have 64
  1201. 50:31elements we don't have 64 cores so how
  1202. 50:34can we parallelize it imagine we only
  1203. 50:36have eight cores now with eight cores we
  1204. 50:39can divide this original Matrix a into
  1205. 50:42four blocks where the first block is
  1206. 50:45this top left block of two by no 4X two
  1207. 50:50elements so um uh how to say um eight
  1208. 50:55elements on the top top left and then
  1209. 50:58eight elements on the top right of this
  1210. 51:00Matrix then eight elements on the bottom
  1211. 51:02left and eight elements in the bottom
  1212. 51:04right of this Matrix these are four
  1213. 51:06blocks then we divide also the B Matrix
  1214. 51:09into um eight blocks where each block is
  1215. 51:12made up of four elements so this b11 is
  1216. 51:17the top left four elements in the
  1217. 51:19original Matrix this B4 is the top right
  1218. 51:22four elements in the original Matrix
  1219. 51:25this B21 is the
  1220. 51:27um bottom left for elements in the
  1221. 51:29origin etc etc etc how do we do this
  1222. 51:33block matrix multiplication we can watch
  1223. 51:35these matrices as made only by their
  1224. 51:39blocks so we can view this Matrix here
  1225. 51:41as made up only by its blocks we can
  1226. 51:44view this Matrix here as made up only by
  1227. 51:47its blocks and the output of this
  1228. 51:50multiplication will be a
  1229. 51:52matrices that is computed in the same
  1230. 51:55way as the original Matrix
  1231. 51:57but where the output of each dot product
  1232. 52:00will not be a single element of the
  1233. 52:02output Matrix but it will be a block of
  1234. 52:04elements of the output Matrix for
  1235. 52:07example the top left block here is the
  1236. 52:11dot product of the first row of this
  1237. 52:14Matrix with the First Column of this
  1238. 52:17Matrix and it will be computed as
  1239. 52:20follows so it will be a11 * b11 plus a12
  1240. 52:24* B21 and this output will not be a
  1241. 52:28single scalar but it will be a uh well
  1242. 52:32let me count it should be uh eight
  1243. 52:34elements so it should be four um made up
  1244. 52:38it's it should be a block of four
  1245. 52:40elements um or eight elements let me let
  1246. 52:44me count actually so because we have
  1247. 52:46eight blocks and it should be made up of
  1248. 52:48eight elements uh let's we can see that
  1249. 52:51here um how to find the dimensions of
  1250. 52:54this output block
  1251. 52:57uh well we can check what is a11 a11 is
  1252. 53:004X two so it's eight elements in as a
  1253. 53:04smaller Matrix made made up of eight
  1254. 53:06elements where the elements are
  1255. 53:08distributed in four rows and two columns
  1256. 53:11we are multiplying it by b11 which is a
  1257. 53:14smaller Matrix compared to the original
  1258. 53:15made up of 2x two elements so four
  1259. 53:19elements so when we multiply a 4x2
  1260. 53:22multiply by 2x two it will produce a 4x2
  1261. 53:24output uh block Matrix so
  1262. 53:28block so if we do this computation here
  1263. 53:31block by block it will produce a block
  1264. 53:34of output elements of the original
  1265. 53:36Matrix so not not a single scalar but a
  1266. 53:38block of outputs which makes it very
  1267. 53:40easy to parallelize because if we have
  1268. 53:43only eight cores we can assign each
  1269. 53:45output block to One Core and each core
  1270. 53:48will not produce one output element of
  1271. 53:50the original Matrix but it will produce
  1272. 53:52eight elements of the original Matrix as
  1273. 53:55a 4x2
  1274. 53:57Matrix um so basically block Matrix
  1275. 54:00allow us to um uh to do the matrix
  1276. 54:03multiplication either by element by
  1277. 54:05element so like in the original Matrix
  1278. 54:07so each row with each column or blocks
  1279. 54:09by blocks in the same way like we do
  1280. 54:11normal matrix multiplication because the
  1281. 54:13the matrix multiplication that we are
  1282. 54:15doing between blocks is the same way as
  1283. 54:17we do matrix multiplication with the
  1284. 54:19original Matrix and it will produce not
  1285. 54:22a scolar but a block and now let's see
  1286. 54:24why this is very important for us
  1287. 54:28so why should we care about block matrix
  1288. 54:30multiplication because we are trying to
  1289. 54:34compute the following operation so the
  1290. 54:36query multiplied by the transpose of the
  1291. 54:37keys and then we will should apply the
  1292. 54:40soft Marx of this operation and then we
  1293. 54:42should multiply the output of the
  1294. 54:44softmax with V for now let's ignore the
  1295. 54:47soft Marx let's pretend that we are not
  1296. 54:49going to apply any softmax so we take
  1297. 54:52the output of the query multiplied by
  1298. 54:53the transpose of the keys and we just
  1299. 54:55multiply it by V to obtain the output of
  1300. 54:57the attention which is wrong of course
  1301. 54:58but it simplifies our tract of what we
  1302. 55:01are going to do next so for for this
  1303. 55:04moment let's pretend that we are not
  1304. 55:05going to apply any soft Max so we just
  1305. 55:07do the query multiply by transpose of
  1306. 55:08the keys and directly we multiply the
  1307. 55:10result of this operation with v this
  1308. 55:12will result in a matrix that is n by D
  1309. 55:14so n tokens each made up of an embedding
  1310. 55:18of D Dimensions so lower case D
  1311. 55:21dimensions and we know that query key
  1312. 55:24and values are themselves matrices of n
  1313. 55:27by D Dimensions so the um um n tokens
  1314. 55:32which made up of embedding of the
  1315. 55:34dimensions so imagine we have a query
  1316. 55:37Matrix and the key and the value Matrix
  1317. 55:39that are 8 by 128 so we have eight
  1318. 55:42tokens each token is made up of 128
  1319. 55:46Dimensions we can divide as we have seen
  1320. 55:49each when we compute matrix
  1321. 55:51multiplication we can divide our um
  1322. 55:54Matrix into blocks how we choose the
  1323. 55:57blocks is up to us as long as the oper
  1324. 56:01the the shapes of the blocks match when
  1325. 56:03doing the matrix multiplication so for
  1326. 56:05example in the previous case we divided
  1327. 56:08our Matrix a into blocks such that the
  1328. 56:11the the shape of the block Matrix so the
  1329. 56:13Matrix that is made up only of the
  1330. 56:15blocks is compatible with the block
  1331. 56:18Matrix B so that this operation is
  1332. 56:21possible so this is the only requirement
  1333. 56:23that we need to be aware when doing the
  1334. 56:26matrix multiplication the shapes of the
  1335. 56:28blocked Matrix so the Matrix that is
  1336. 56:30made only of the blocks should match in
  1337. 56:32the matrix multiplication for the rest
  1338. 56:35it doesn't matter how we divide it so
  1339. 56:37imagine that we choose to divide this
  1340. 56:40query Matrix into blocks of rows and we
  1341. 56:43can do that we don't have to necessarily
  1342. 56:45divide also the columns we can just
  1343. 56:46divide the rows so that each Q is not a
  1344. 56:49single row but it's a group of two rows
  1345. 56:52so q1 is a group of the first two rows
  1346. 56:55of the Q Matrix of the Q sequence Q2 is
  1347. 56:58the group of the second two rows of the
  1348. 57:00Q sequence etc etc and we do the same
  1349. 57:03also for V for K we don't do it because
  1350. 57:06we are actually going to multiply with K
  1351. 57:09transposed so we do this subdivision
  1352. 57:11directly on K transposed so so we have
  1353. 57:15the Q which has been divided into groups
  1354. 57:18of rows and then we have a k transposed
  1355. 57:20which is a matrix that is 108 by 8
  1356. 57:24because it's the transpose of the Keys
  1357. 57:26which is 8 by
  1358. 57:27108 and we decide to divide each of the
  1359. 57:32column group of columns of K into a
  1360. 57:35single block so the K1 is the first two
  1361. 57:38columns of K transposed K2 is the second
  1362. 57:41group of two columns in K transposed etc
  1363. 57:44etc until K4 which is the last two
  1364. 57:47columns in K transposed the first
  1365. 57:49operation that we do is the
  1366. 57:50multiplication query multiply by the
  1367. 57:52transpose of the keys which basically
  1368. 57:54means that we need to multiply each
  1369. 57:56query with all the keys then the second
  1370. 57:59query with the all the keys etc etc now
  1371. 58:03each query is not a single row of the Q
  1372. 58:06sequence it's a group of two rows of the
  1373. 58:08Q sequence and each K is not a single
  1374. 58:11column of K transposed it's a group of
  1375. 58:14two columns of K transposed but doesn't
  1376. 58:16matter because we have seen that the
  1377. 58:17matrix multiplication if we write the
  1378. 58:19matrixes as made up of blocks we just
  1379. 58:22compute it in the same way when we do uh
  1380. 58:25normal matrix multiplication ation so we
  1381. 58:27are multiplying this matrix by this
  1382. 58:29Matrix and for what we know this Matrix
  1383. 58:32here is made up of four rows with some
  1384. 58:36Dimensions which is uh 128 dimensions
  1385. 58:40and this one here is made up of uh how
  1386. 58:42many rows 128 rows and four uh
  1387. 58:47columns I didn't uh draw The Columns
  1388. 58:50because it's too many to draw here but
  1389. 58:52you need to pretend it's a lot of
  1390. 58:53Dimensions one for each 128 for each
  1391. 58:56vector and here you need to pretend that
  1392. 58:58this is 128 rows when we do the matrix
  1393. 59:02multiplication we apply the normal M
  1394. 59:04matrix multiplication procedure which is
  1395. 59:06each output element so this first of all
  1396. 59:08the output shape of this Matrix of this
  1397. 59:10matrix multiplication will be 4x4
  1398. 59:12because it's the outer dimensions of the
  1399. 59:13two Matrix that they are
  1400. 59:15multiplying the first element of the
  1401. 59:17output will be the dot product of this
  1402. 59:19Vector here with this Vector here the
  1403. 59:23second element so this one here will be
  1404. 59:25done dot product of this Vector here
  1405. 59:28with this Vector here however this is
  1406. 59:30not vector and this is not a vector so
  1407. 59:33it's actually a matrix multiplication in
  1408. 59:36this case this element here is not a
  1409. 59:39scalar it is a group of elements of the
  1410. 59:41output Matrix because we are doing block
  1411. 59:43matrix multiplication and how many
  1412. 59:45elements it will be well we know that
  1413. 59:47the original q1 is a 2 by
  1414. 59:49128 the K1 is 108x 2 so it will be a
  1415. 59:54group of 2x two elements of the output
  1416. 59:57Matrix so we are doing the matrix
  1417. 1:00:00multiplication of the q1 with K1 then q1
  1418. 1:00:04with K2 then q1 with K3 q1 with K4 etc
  1419. 1:00:08etc for the first row and then the
  1420. 1:00:10second row will be Q2 with all the K and
  1421. 1:00:12the Q3 with all the ks and Q4 with all
  1422. 1:00:14the ks so as you can see when we do
  1423. 1:00:16matrix multiplication we don't even care
  1424. 1:00:19if what is underlying is a block or a
  1425. 1:00:22vector or a scalar we just apply the
  1426. 1:00:24same procedure for first um row of the
  1427. 1:00:28Black Block matrix multiplication with
  1428. 1:00:30the First Column of the Matrix M of the
  1429. 1:00:32second Matrix uh and then the first row
  1430. 1:00:35with the second column the first row
  1431. 1:00:38with the third column etc
  1432. 1:00:40etc let's then multiply because the
  1433. 1:00:43formula says that we need to multiply
  1434. 1:00:45query with the transpose of the keys and
  1435. 1:00:46then multiply by V all of these are um
  1436. 1:00:50block matrices now as you can see from
  1437. 1:00:53my using of colors every time time I
  1438. 1:00:56refer to the original Matrix I use the
  1439. 1:00:58blue color and every time I refer to the
  1440. 1:01:00block Matrix I use the pink color so we
  1441. 1:01:04need to multiply the output of the query
  1442. 1:01:06multiplied by the transpose of the key
  1443. 1:01:07then by V because we are skipping for
  1444. 1:01:09now the soft Max and later we will see
  1445. 1:01:11why so if we want to do this
  1446. 1:01:13multiplication we need to do the
  1447. 1:01:16following so it will be uh this Matrix
  1448. 1:01:19is made up of blocks and block matrix
  1449. 1:01:22multiplication just ignores this fact
  1450. 1:01:24and just does the matrix multiplication
  1451. 1:01:25like it is a normal matrix
  1452. 1:01:27multiplication so we do the first row
  1453. 1:01:29with the First Column then the first row
  1454. 1:01:32with the second column then the third
  1455. 1:01:34row the first row with the third column
  1456. 1:01:37etc etc so the first block of row how is
  1457. 1:01:40going to be calculated this out um this
  1458. 1:01:43output in the output Matrix of this
  1459. 1:01:44matrix multiplication well it will be
  1460. 1:01:47the um the the first row so the dot
  1461. 1:01:50product of the first row the dot product
  1462. 1:01:54because it's not really Dot product it's
  1463. 1:01:56the actually the matrix multiplication
  1464. 1:01:58of the first row but in a dotproduct way
  1465. 1:02:01let's say uh with the First Column which
  1466. 1:02:04is made up of V1 vs2 V3 and V4 so it
  1467. 1:02:08will be this element with V1 plus this
  1468. 1:02:11element with vs2 plus this element with
  1469. 1:02:14V3 plus this element with V4 uh and this
  1470. 1:02:18will be the first output element the
  1471. 1:02:21second output uh block will be this row
  1472. 1:02:26with this
  1473. 1:02:27column uh which will be this element
  1474. 1:02:30with V1 this element plus this element
  1475. 1:02:33with V2 plus this element with V3 plus
  1476. 1:02:36this element with V4 and this will
  1477. 1:02:37produce the second output
  1478. 1:02:40block etc etc also for the third and the
  1479. 1:02:43fourth block output let's look at what
  1480. 1:02:46is each block made up of so each block
  1481. 1:02:49is made up of the um the first element
  1482. 1:02:52so query 1 multip by qy1 because um
  1483. 1:02:56it's the result of the query multiply by
  1484. 1:02:58the keys with the V1 of the second
  1485. 1:03:01Matrix plus the this element with this
  1486. 1:03:04one plus this element with this one plus
  1487. 1:03:06this element with this one so the pelo
  1488. 1:03:10code for generating this output of this
  1489. 1:03:13attention mechanism which is not really
  1490. 1:03:14attention mechanism because we skip the
  1491. 1:03:16soft Max but I just want you to get into
  1492. 1:03:18the habit of thinking in terms of blocks
  1493. 1:03:22is the following so we take each query
  1494. 1:03:26lock um we go through each
  1495. 1:03:29query and as you can see let's look at
  1496. 1:03:31actually what this output is made up it
  1497. 1:03:34is made up of the query one multiplied
  1498. 1:03:36by key1 and the result multiply by V1
  1499. 1:03:39then the query one with K2 then the
  1500. 1:03:42result multiply by V2 then the query one
  1501. 1:03:45with the K3 and the result multiply by
  1502. 1:03:47V3 plus the query one with the K4 and
  1503. 1:03:50result multiplied by V4 this is
  1504. 1:03:52basically what we are doing is the dot
  1505. 1:03:54product of this row with this column
  1506. 1:03:57made up of
  1507. 1:03:59blocks um so the the pelo code for
  1508. 1:04:02generating this first row is the query
  1509. 1:04:05is the query number one and then we
  1510. 1:04:08iterate through the keys and the values
  1511. 1:04:10from one to four and we sum iteratively
  1512. 1:04:14so for each block basically to generate
  1513. 1:04:16this output Matrix and if you um for
  1514. 1:04:19each row we will see that it's a
  1515. 1:04:21different query with all the keys and
  1516. 1:04:23values and then this will be the the the
  1517. 1:04:25query number number three with all the
  1518. 1:04:26keys and values and this will be the
  1519. 1:04:28query four with all the keys and values
  1520. 1:04:31so to generate this output Matrix we
  1521. 1:04:33need to do we iterate through the
  1522. 1:04:34queries and this will be one row of this
  1523. 1:04:37output Matrix and then we need to do
  1524. 1:04:39this iterative sum of the query I that
  1525. 1:04:43we are iterating through multiply by the
  1526. 1:04:45J K and V and we keep summing them
  1527. 1:04:49iteratively and that would that will
  1528. 1:04:51produce the output Matrix or you can see
  1529. 1:04:53here I know that what I have done so far
  1530. 1:04:56is not useless not useful for Flash
  1531. 1:04:59attention but it's useful for us to get
  1532. 1:05:01into the mindset of computing this
  1533. 1:05:03product by blocks because later we will
  1534. 1:05:05use it also with the
  1535. 1:05:07softmax all right guys I I know that we
  1536. 1:05:11have comput what we have computed so far
  1537. 1:05:13is not really the soft Max operation is
  1538. 1:05:15not sorry the really the attention
  1539. 1:05:17mechanism because we have skipped the
  1540. 1:05:19soft Max so somehow we need to restore
  1541. 1:05:22it and the the following few I think
  1542. 1:05:25think 10 20 minutes we are going to be
  1543. 1:05:27really really challenging because I am
  1544. 1:05:30going to do a lot of operations that
  1545. 1:05:32will involve a lot of different blocks
  1546. 1:05:34and a lot of different metrix
  1547. 1:05:36multiplication and variants of the
  1548. 1:05:39softmax so it may be difficult to follow
  1549. 1:05:42however don't give up you can watch this
  1550. 1:05:45part twice three times and every time
  1551. 1:05:47you it will have a better understanding
  1552. 1:05:50I also recommend watch it until we reach
  1553. 1:05:52the flesh attention algorithm before we
  1554. 1:05:55start restarting from to to go back to
  1555. 1:05:58to rewatch it because you watch it we
  1556. 1:06:01reach the flesh attention algorithm and
  1557. 1:06:04it will give you a better understanding
  1558. 1:06:05of what have happened so far and then
  1559. 1:06:07you can rewatch it to deepen your
  1560. 1:06:10understanding another thing that I
  1561. 1:06:12recommend is take pen and paper and
  1562. 1:06:15write exactly the operations that you
  1563. 1:06:16are seeing and write the shapes of each
  1564. 1:06:20of these blocks of these elements that
  1565. 1:06:22are made in that are part in this um
  1566. 1:06:25Matrix
  1567. 1:06:26multiplications so that you better uh
  1568. 1:06:30understand what is happening and you
  1569. 1:06:31better remember what when I refer to a
  1570. 1:06:34particular element or a particular block
  1571. 1:06:37okay after giving this small uh
  1572. 1:06:40motivational speech Let's Start so what
  1573. 1:06:43we have done so far was query multipli
  1574. 1:06:46by the transpose of the keys however
  1575. 1:06:48each query is not a single row of the
  1576. 1:06:51query sequence but it's a block of
  1577. 1:06:54queries it's a block of rows in our
  1578. 1:06:57particular case this q1 is not one row
  1579. 1:07:00of the query sequence it's two rows of
  1580. 1:07:03the query sequence because we have
  1581. 1:07:04chosen as a block size a group of two
  1582. 1:07:07rows and this K transposed one is not
  1583. 1:07:11one column of the K transposed Matrix is
  1584. 1:07:15two columns of the K transposed Matrix
  1585. 1:07:17because we have chosen it like this and
  1586. 1:07:19if you don't remember let's go back to
  1587. 1:07:21see it uh here we have chosen K1 is 2
  1588. 1:07:25two columns and q1 is two rows of the
  1589. 1:07:28query original Matrix and every time I
  1590. 1:07:31use the blue color I am referring to the
  1591. 1:07:34original shape and every time I'm using
  1592. 1:07:36the pink or Violet whatever it is I am
  1593. 1:07:39referring to the block metrix so it's a
  1594. 1:07:42block of elements of the original
  1595. 1:07:45Matrix okay now uh the first thing that
  1596. 1:07:48we have done was query multiplied by the
  1597. 1:07:50transpose of the keys and this produces
  1598. 1:07:53a block patrix as output that we will
  1599. 1:07:56call S where each element s j so the S11
  1600. 1:08:02element of this Matrix will be the query
  1601. 1:08:04one with K transposed one the S12 will
  1602. 1:08:08be query one with K transposed 2 s13
  1603. 1:08:12will be query one with K transposed
  1604. 1:08:14three etc etc for all the rows and for
  1605. 1:08:17all the columns then we should be
  1606. 1:08:19applying the soft Max because if you
  1607. 1:08:21remember the formula is soft Max of the
  1608. 1:08:22query multiplied by the transpose of the
  1609. 1:08:24keys however I want to restore the
  1610. 1:08:27softmax operation but with a Twist which
  1611. 1:08:30means that we will apply the simplified
  1612. 1:08:32version of the softmax and we will call
  1613. 1:08:34it softmax star which is just the
  1614. 1:08:37softmax without the normalization so let
  1615. 1:08:40me write it for you what it
  1616. 1:08:42means uh let's do it with the same color
  1617. 1:08:45that I chose for the softmax which is
  1618. 1:08:48orange so the soft max if you remember
  1619. 1:08:51correctly if we remember it's the soft
  1620. 1:08:53Max
  1621. 1:08:56of to of a vector we apply it element
  1622. 1:08:59wise so each element is modified
  1623. 1:09:03according to the following formula so
  1624. 1:09:04the E element of the output Vector to
  1625. 1:09:07which we are applying the softmax is
  1626. 1:09:10equal to the
  1627. 1:09:12exponential of the E element of the
  1628. 1:09:16input Vector minus the maximum element
  1629. 1:09:20in the input Vector divided by a
  1630. 1:09:23normalization factor that is calculated
  1631. 1:09:25according to this
  1632. 1:09:26summation that is going from Jal to 1 up
  1633. 1:09:30to n of the
  1634. 1:09:32exponential of x i minus x max so
  1635. 1:09:37basically uh we are doing the
  1636. 1:09:39exponential of each element minus this x
  1637. 1:09:42Max and why are if you remember
  1638. 1:09:43correctly why are we subtracting this x
  1639. 1:09:45max to make this exponential numerically
  1640. 1:09:48stable computable because otherwise it
  1641. 1:09:51will explode and because we are applying
  1642. 1:09:53it to the numerator we also need to
  1643. 1:09:54apply it to the denominator okay the
  1644. 1:09:57softmax start operation is exactly like
  1645. 1:10:00the softmax but without the
  1646. 1:10:01normalization part which means that it's
  1647. 1:10:03just the numerator of the soft Max so we
  1648. 1:10:05will modify each element of the vector
  1649. 1:10:08to which we apply the soft Max star
  1650. 1:10:09according to this formula let me move it
  1651. 1:10:12more aligned like this so we just do
  1652. 1:10:15element element wise uh operation that
  1653. 1:10:18is the exponential of each element minus
  1654. 1:10:21the maximum to the of the vector to
  1655. 1:10:22which we are applying soft Max star
  1656. 1:10:26okay now why did I introduce this soft
  1657. 1:10:29maxar operation because we will be
  1658. 1:10:31applying it to the Matrix that we have
  1659. 1:10:33computed so far which is this s Matrix
  1660. 1:10:36so we applied soft Max star to each
  1661. 1:10:39element of this s Matrix but each
  1662. 1:10:42element of this s Matrix is itself a
  1663. 1:10:45matrix because it's a block Matrix and
  1664. 1:10:48each element of this s Matrix so for
  1665. 1:10:50example the element S11 is a 2x2 matrix
  1666. 1:10:53because it is coming from the product of
  1667. 1:10:55two matrices which are a group of rows
  1668. 1:10:58and a group of columns from the Q and
  1669. 1:11:00the K uh so for example this S11 is what
  1670. 1:11:04is um let's draw it actually this S11
  1671. 1:11:08will be for example made up of four
  1672. 1:11:10elements let's call it uh I don't know a
  1673. 1:11:14of
  1674. 1:11:15S11 uh let's let's choose better naming
  1675. 1:11:19let's call it I don't know
  1676. 1:11:21a uh
  1677. 1:11:25b c and d just the generic elements when
  1678. 1:11:30we apply the soft Max star to this S11
  1679. 1:11:33it will result so let's apply the soft
  1680. 1:11:36Max
  1681. 1:11:37star soft Max
  1682. 1:11:40star it will result in a
  1683. 1:11:43matrix that
  1684. 1:11:46is each element the exponential of each
  1685. 1:11:49element minus the maximum for each row
  1686. 1:11:51now we don't know which is the maximum
  1687. 1:11:53so let's choose one suppose that's the
  1688. 1:11:55maximum for this row is a and the
  1689. 1:11:57maximum for this row is D the first
  1690. 1:12:00element of the output of this soft Max
  1691. 1:12:02star applied to this block S11 will be
  1692. 1:12:06the
  1693. 1:12:08exponential of a multi minus a because
  1694. 1:12:12that's what we chose as the maximum for
  1695. 1:12:13this row the second element will be the
  1696. 1:12:16exponential of B minus a because it's
  1697. 1:12:19the maximum for that row then in the
  1698. 1:12:22bottom row it will be the exponential of
  1699. 1:12:25uh C minus D because that's the maximum
  1700. 1:12:28for the bottom row and this will be the
  1701. 1:12:30exponential of D minus D and that's the
  1702. 1:12:34exponential that's how the softmax star
  1703. 1:12:36will modify each block in this block
  1704. 1:12:39Matrix let me delete this stuff
  1705. 1:12:42otherwise it will remain in my slides
  1706. 1:12:44forever and later I want to share the
  1707. 1:12:45slides with you guys so you can use my
  1708. 1:12:47same slides so delete delete delete okay
  1709. 1:12:53after we have applied the soft Max to
  1710. 1:12:55each of the elements in this s Matrix we
  1711. 1:12:58will call it the P Matrix and each
  1712. 1:13:01element P11 will again be block of 2x
  1713. 1:13:04two
  1714. 1:13:05elements um so P11 will be the soft Max
  1715. 1:13:11so P11 will be the soft Max star applied
  1716. 1:13:14to S11 where S11 is what is query one k
  1717. 1:13:18transposed one and the p12 will be the
  1718. 1:13:20soft Max star applied to S12 where S12
  1719. 1:13:23is what is query one
  1720. 1:13:25multiplied by K transpose the two etc
  1721. 1:13:28etc etc for all the elements of
  1722. 1:13:30s okay now that we have applied this
  1723. 1:13:33softmax star operation the next
  1724. 1:13:35operation that we should be doing
  1725. 1:13:37according to the formula of the
  1726. 1:13:38attention is uh the softmax of the query
  1727. 1:13:41multiplied by the transpose of the keys
  1728. 1:13:43then the result of the softmax
  1729. 1:13:44multiplied by V I know that we didn't
  1730. 1:13:47apply the real soft Max we applied
  1731. 1:13:49softmax star which is softmax without
  1732. 1:13:51the normalization later we will see how
  1733. 1:13:54to compens at this lack of normalization
  1734. 1:13:57because we will do it at the end and
  1735. 1:13:58it's something that we can
  1736. 1:14:00do okay so we take this P Matrix which
  1737. 1:14:04is the result of the soft Max star
  1738. 1:14:06applied to this s Matrix and we multiply
  1739. 1:14:09it by
  1740. 1:14:10V what how do we do it well it's a block
  1741. 1:14:14it's a matrix made up of blocks of
  1742. 1:14:17matrices um so P11 is actually not a
  1743. 1:14:20scolar but it's a matrix of 2x two
  1744. 1:14:22elements and we need to multiplied by V
  1745. 1:14:25but we don't multiply with the original
  1746. 1:14:27sequence V but with the blocked sequence
  1747. 1:14:30V just like before where each V is not
  1748. 1:14:33one row of V but it's a group of rows of
  1749. 1:14:36v and how many rows is it is it is two
  1750. 1:14:39rows of V uh for now please ignore
  1751. 1:14:42completely whatever I have written here
  1752. 1:14:44because we will use it later so we need
  1753. 1:14:46to do this product of this Matrix here
  1754. 1:14:49which is made up of blocks remember with
  1755. 1:14:51this Matrix here which is made up of
  1756. 1:14:53blocks it is made up of four
  1757. 1:14:55four rows where each row is not really a
  1758. 1:14:58row it is a block of rows and this one
  1759. 1:15:01it is made up of 4x4 elements where each
  1760. 1:15:03element is not really a scolar but it's
  1761. 1:15:05a
  1762. 1:15:06matrix so as you remember in the block
  1763. 1:15:09matrix multiplication when the algorithm
  1764. 1:15:11for computing the matrix multiplication
  1765. 1:15:13is the same as the normal matrix
  1766. 1:15:15multiplication except that we use blocks
  1767. 1:15:18so what I am doing is guys uh the
  1768. 1:15:20following operation so let's write it
  1769. 1:15:22somewhere let's say o is equal to P
  1770. 1:15:25multip by V okay so um the first output
  1771. 1:15:30um row row because it's not really a row
  1772. 1:15:34but it's a block row uh will be computed
  1773. 1:15:37as follows the first row of this block
  1774. 1:15:40Matrix with the First with um the First
  1775. 1:15:43Column of this V Matrix and um we are
  1776. 1:15:48treating it uh like a block Matrix so it
  1777. 1:15:51will be P11 multip by V1 plus p12 ultip
  1778. 1:15:57by vs2 plus p13 * by V3 plus p14
  1779. 1:16:03multipli by
  1780. 1:16:04V4 this will produce the first output
  1781. 1:16:08row of O but it's not really a row
  1782. 1:16:11because it's a made up of two rows uh so
  1783. 1:16:15this stuff here is not one row it is two
  1784. 1:16:18row and we can prove that because what
  1785. 1:16:20is P11 P11 is let's write it somewhere
  1786. 1:16:24so P11 is a 2X two Matrix uh yeah 2 by
  1787. 1:16:29two and we are multiplying it with V1
  1788. 1:16:32which is a block of two rows of V so it
  1789. 1:16:35is a two rows by 128 Dimensions so it is
  1790. 1:16:40equal to 2x
  1791. 1:16:42128 so this stuff here is 2 by
  1792. 1:16:47128 so this block here the output block
  1793. 1:16:50that we are Computing is a block of two
  1794. 1:16:52rows of the output Matrix that we are
  1795. 1:16:55Computing uh I know this is really uh
  1796. 1:16:59difficult to follow because we are
  1797. 1:17:01involving blocks so we need to visualize
  1798. 1:17:03at the same time metrics as blocks and
  1799. 1:17:06as the original metrix that's why I
  1800. 1:17:09highly recommend you to pause the video
  1801. 1:17:12think it's through write down whatever
  1802. 1:17:14you need to write down because it's not
  1803. 1:17:17easy to find follow it just by
  1804. 1:17:19memorizing the shapes so you you
  1805. 1:17:20actually need to write down things
  1806. 1:17:23anyway we are Compu the first output
  1807. 1:17:26block of the output o Matrix now if we
  1808. 1:17:30if you remember uh the output um the
  1809. 1:17:34output this output here should be the
  1810. 1:17:38output of the output of the soft Max
  1811. 1:17:42multiplied by V now this soft Max has
  1812. 1:17:46not been applied to the entire row of
  1813. 1:17:51this Matrix here s Matrix here but
  1814. 1:17:54basically to compute this soft Max star
  1815. 1:17:57what we did was to compute the soft Max
  1816. 1:18:00star at each block independently from
  1817. 1:18:03the other blocks which means that the
  1818. 1:18:05maximum that we are using to compute
  1819. 1:18:07each soft Max star is not the global
  1820. 1:18:11maximum for the row of this s Matrix but
  1821. 1:18:15the local maximum of each block and this
  1822. 1:18:19is wrong actually because when we
  1823. 1:18:21compute the soft Max uh we apply the
  1824. 1:18:24soft Max we should be using the global
  1825. 1:18:27row I want to give you an example
  1826. 1:18:30without using blocks because otherwise I
  1827. 1:18:32think it's not easy to follow so when we
  1828. 1:18:35do the normal attention so we have a
  1829. 1:18:38query multiplied by the transpose of the
  1830. 1:18:41keys this produces a matrix that is n by
  1831. 1:18:43n so sequence by sequence where each
  1832. 1:18:47element of this Matrix so let's say
  1833. 1:18:49three four five I don't know how many is
  1834. 1:18:52one two three four five six yeah six
  1835. 1:18:56two 3 four and five six should be 1 2 3
  1836. 1:19:004 5 6 okay this one here should be the
  1837. 1:19:04dot product of the first query with the
  1838. 1:19:07uh first um let me use because query one
  1839. 1:19:12transpose the
  1840. 1:19:14key1 uh this is because as I said before
  1841. 1:19:17when we do the product of two vectors we
  1842. 1:19:21always treat them as column vectors so
  1843. 1:19:23when you want to write the DOT product
  1844. 1:19:25you cannot multiply two column vectors
  1845. 1:19:27you need to multiply one row Vector with
  1846. 1:19:29one column Vector that's why we
  1847. 1:19:30transpose this one if it confuses you
  1848. 1:19:32you can also write q1 K1 that's totally
  1849. 1:19:35fine it's just uh wrong from a notation
  1850. 1:19:38point of view anyway the first one will
  1851. 1:19:41be the dot product of the query one with
  1852. 1:19:43K1 the second element will be the dot
  1853. 1:19:46product of the query one with K2 the
  1854. 1:19:49third will be the query one with K3 etc
  1855. 1:19:52etc etc um
  1856. 1:19:55so this is q1 with K1 q1 with
  1857. 1:20:01K2 K2 and q1 with K3 q1 with
  1858. 1:20:08K4 um
  1859. 1:20:10anyway when we do the soft Max we
  1860. 1:20:13actually calculate the maximum on this
  1861. 1:20:15entire row however what we are doing is
  1862. 1:20:19we are actually doing a block matrix
  1863. 1:20:22multiplication and as you remember
  1864. 1:20:25um when we do by blocks we are grouping
  1865. 1:20:29together rows of queries and rows of
  1866. 1:20:33keys and in this particular case we are
  1867. 1:20:36grouping the two queries together to
  1868. 1:20:38create one uh one group of queries and
  1869. 1:20:42two keys together to create one block of
  1870. 1:20:45keys so we need another row of this one
  1871. 1:20:48so it's the let me ose query one k or
  1872. 1:20:52query 2 K1 this should be query 2 2
  1873. 1:20:55K1 query 2 K2 query 2 K3 query 2 K 4
  1874. 1:21:04query 2 K5 and query 2 K
  1875. 1:21:086 um when we each of this each of this
  1876. 1:21:14block here is
  1877. 1:21:16Computing this block here is Computing 2
  1878. 1:21:19by two elements of the original Matrix
  1879. 1:21:22if we had never applied the blocks so it
  1880. 1:21:24is
  1881. 1:21:25Computing these two four elements
  1882. 1:21:29here and if we apply the soft Max star
  1883. 1:21:33to each of these blocks we are not using
  1884. 1:21:36the maximum element in this row we are
  1885. 1:21:39only using the maximum element in each
  1886. 1:21:41block which means that when we will use
  1887. 1:21:44it in the downstream product with v
  1888. 1:21:46Matrix we will be summing values that
  1889. 1:21:50are wrong because each of these values
  1890. 1:21:52here will be based on a maximum that is
  1891. 1:21:55not the global maximum for this row it
  1892. 1:21:58is the local maximum of this block here
  1893. 1:22:02and um and this block here will have the
  1894. 1:22:05global the it will use the local maximum
  1895. 1:22:08of this block here and this block here
  1896. 1:22:10will use the local maximum of this block
  1897. 1:22:13here etc etc etc so what I'm trying to
  1898. 1:22:16say is that when you sum P11 with V1 P11
  1899. 1:22:21may have some Maximum local maximum that
  1900. 1:22:24is different than from the local maximum
  1901. 1:22:26of p12 and p13 may have a different
  1902. 1:22:29maximum local maximum that of P1 P11 and
  1903. 1:22:34p12 so we need to find a way to fix the
  1904. 1:22:39maximum that was used to compute the
  1905. 1:22:42exponential here with the maximum found
  1906. 1:22:46here in case the maximum here is higher
  1907. 1:22:49than the one local to P11 so if we have
  1908. 1:22:53found for example here a Max maximum
  1909. 1:22:54that is higher than the maximum used
  1910. 1:22:56here here then we need to fix this one
  1911. 1:22:58and this one because that maximum in the
  1912. 1:23:01soft Max should be the maximum for all
  1913. 1:23:03the row not the one belonging to the
  1914. 1:23:05each
  1915. 1:23:05block and this leads to our next step
  1916. 1:23:09how to fix
  1917. 1:23:10this first of all let me introduce a
  1918. 1:23:13little pseo code for computing this
  1919. 1:23:15output Matrix here which is an output
  1920. 1:23:18block Matrix and later we will use this
  1921. 1:23:22pelo code to adjust the error that we
  1922. 1:23:25have made in some blocks in case the
  1923. 1:23:28future blocks so the p13 has a better
  1924. 1:23:30maximum than P11 or p12 so to compute
  1925. 1:23:34this output Matrix
  1926. 1:23:36o we go through so for example to
  1927. 1:23:39compute the first row we choose well P11
  1928. 1:23:41is what is is um let's go back P11 is
  1929. 1:23:45let me delete also this one it's not
  1930. 1:23:47needed anymore P11 is the soft Max star
  1931. 1:23:51of q1 K1 p12 2 is the um soft maxar of
  1932. 1:23:56q1 K2 p13 is the soft maxar of q1 K3 p14
  1933. 1:24:02is the soft Mark star of q1
  1934. 1:24:05K4 um which means that uh to compute
  1935. 1:24:10this block here here we first need to
  1936. 1:24:13compute the P11 what is P11 well P11 is
  1937. 1:24:16the soft Max star of a block of Q and
  1938. 1:24:20another block of k k which in the case
  1939. 1:24:23of the first first row of the output
  1940. 1:24:25Matrix means that it is the query one
  1941. 1:24:29with the soft maxar of the query one
  1942. 1:24:31with key1 the soft maxar of the query 1
  1943. 1:24:34with K2 the soft maxar of the query 1
  1944. 1:24:36with K3 the soft maxar of the query 1
  1945. 1:24:38with K4 which means that we need to go
  1946. 1:24:41we need to make a for Loop through all
  1947. 1:24:43the keys while keeping the query fixed
  1948. 1:24:47so to compute the first output row we
  1949. 1:24:49need to do the soft maxar to produce P11
  1950. 1:24:53we need to do the soft ma out of query 1
  1951. 1:24:56K1 and um we sum it initially to zeros
  1952. 1:25:01because we don't um we need to
  1953. 1:25:02initialize our output somehow and we
  1954. 1:25:04initialize it with
  1955. 1:25:05zeros then we sum the next P1 to which
  1956. 1:25:10is the query one with the K2 and then we
  1957. 1:25:12sum the next p13 which is the query one
  1958. 1:25:15with the K3 etc etc that's why we have
  1959. 1:25:17this inner loop
  1960. 1:25:19here all right so however this output
  1961. 1:25:22that we Computing is wrong because I
  1962. 1:25:23told you we have computed the softmax
  1963. 1:25:26star using a statistics the maximum
  1964. 1:25:29value that is belonging to each block
  1965. 1:25:31and not the one that is the overall row
  1966. 1:25:34of the original Matrix how to fix that
  1967. 1:25:37we have a tool actually we have computed
  1968. 1:25:39before an algorithm called the online
  1969. 1:25:41softmax I don't know if I referred to it
  1970. 1:25:43before as the online softmax but it's
  1971. 1:25:45called the online softmax that allows to
  1972. 1:25:48fix previous iterations when we are
  1973. 1:25:51Computing the current iteration
  1974. 1:25:54Bas how well let's review the online
  1975. 1:25:57softmax we start imagine we are working
  1976. 1:26:00with one single Vector so we are a
  1977. 1:26:02vector made up of n elements the what we
  1978. 1:26:05do is we do a for Loop where we compute
  1979. 1:26:08iteratively the maximum up to the he
  1980. 1:26:12element and we fix the normalization
  1981. 1:26:15factor uh computed in previous iteration
  1982. 1:26:18in case we found a better maximum at the
  1983. 1:26:20current element if this is not clear
  1984. 1:26:23guys go go back and watch the online
  1985. 1:26:25soft Mar because this is very important
  1986. 1:26:27because this is what we are going to use
  1987. 1:26:29to fix this P11 p12 blocks in case we
  1988. 1:26:32found better maximum in p13 or p14
  1989. 1:26:36Etc so let's see how to apply this
  1990. 1:26:39online soft Marx to this case here so
  1991. 1:26:42that we can compute so you may be
  1992. 1:26:45wondering why are we going through all
  1993. 1:26:47these troubles I mean
  1994. 1:26:50why the real reason is when first of all
  1995. 1:26:53why did did we introduce block matrix
  1996. 1:26:55multiplication because we want to
  1997. 1:26:56compute matrix multiplication in
  1998. 1:26:58parallel so you can think that each of
  1999. 1:27:01this P11 because they are independent
  2000. 1:27:03from each other and because each of them
  2001. 1:27:05are using the maximum belonging to each
  2002. 1:27:07block they can be computed independently
  2003. 1:27:09from each other then however we need to
  2004. 1:27:12somehow aggregate their value and to
  2005. 1:27:14aggregate their value we need to fix the
  2006. 1:27:17values that have been calculated
  2007. 1:27:19independently because we didn't when
  2008. 1:27:21Computing values independently we don't
  2009. 1:27:22have a global view we have local view so
  2010. 1:27:25we compute local blocks P11 p12 p13 etc
  2011. 1:27:28etc and then when we aggregate these
  2012. 1:27:31values we need to fix them so that's why
  2013. 1:27:34we are trying to uh come up with this
  2014. 1:27:37system of fixing uh values that have
  2015. 1:27:39been calculated
  2016. 1:27:41independently so how to fix this let's
  2017. 1:27:44look at the following algorithm first of
  2018. 1:27:47all um this O Block here as I said
  2019. 1:27:51before it is a block of two rows
  2020. 1:27:54where each row is made up of 128
  2021. 1:27:57dimensions and we have seen that before
  2022. 1:27:59by checking the dimensions of P11 and V1
  2023. 1:28:02the result of P11 V1 which means that
  2024. 1:28:05for each output block we need to take
  2025. 1:28:08care of two maximums uh and two
  2026. 1:28:11normalization factors so up to now I
  2027. 1:28:13didn't use the normalization factor we
  2028. 1:28:15said that we are applying softmax star
  2029. 1:28:16which is the soft Max without the
  2030. 1:28:18normalization but eventually we will
  2031. 1:28:19need to compute this normalization so we
  2032. 1:28:23want to create an an algorithm that
  2033. 1:28:25fixes the maximum used to compute each
  2034. 1:28:27of this P11 and also computes
  2035. 1:28:30simultaneously the normalization factor
  2036. 1:28:33and at the end we will apply this
  2037. 1:28:35normalization factor and the way we will
  2038. 1:28:37do it is as follows we start with
  2039. 1:28:40initializing the maximum to minus
  2040. 1:28:42infinity one for each row that we are
  2041. 1:28:44Computing so is our output block is made
  2042. 1:28:46up of two rows so we need one maximum
  2043. 1:28:48for the top row and one maximum for the
  2044. 1:28:50bottom row and also the normalization
  2045. 1:28:53factor which we initialize with zero
  2046. 1:28:55because we didn't sum anything for now
  2047. 1:28:57and the output we initialize it with all
  2048. 1:28:59zeros because we didn't sum anything to
  2049. 1:29:01this output for now we
  2050. 1:29:04compute the we uh to compute the output
  2051. 1:29:08row so this output block here so this
  2052. 1:29:11output block here we need to go through
  2053. 1:29:14all the keys uh to produce this P11 p12
  2054. 1:29:18p13 p14 while the query is the query
  2055. 1:29:20number one the query block number one so
  2056. 1:29:24the first step that we do is we compute
  2057. 1:29:27the maximum of the first block
  2058. 1:29:30P11 which is the row Max so the maximum
  2059. 1:29:34for each row of the block um uh uh q1 K1
  2060. 1:29:40this is not P11 it's S1 sorry guys this
  2061. 1:29:43is
  2062. 1:29:45S11 so we compute the maximum of this
  2063. 1:29:48one and we call it actually S1 as you
  2064. 1:29:50can see
  2065. 1:29:51here um then we can um calculate P11
  2066. 1:29:56which is the soft Max star which is the
  2067. 1:29:58exponential of the query multip query 1
  2068. 1:30:02K1 so S1 minus the maximum in the local
  2069. 1:30:06group
  2070. 1:30:08S1 and we add it to our
  2071. 1:30:12output for now the output is initialized
  2072. 1:30:15with zero so for now ignore this part
  2073. 1:30:18here I will explain it later so for now
  2074. 1:30:20o1 should be equal only to P11 V1
  2075. 1:30:24now at the step number
  2076. 1:30:27two we may find in the local group S12
  2077. 1:30:31so this one is
  2078. 1:30:33S12 we may find a better maximum for the
  2079. 1:30:37top row and the bottom row and this
  2080. 1:30:40maximum is the M2 which may be better
  2081. 1:30:43than the previous maximum for each of
  2082. 1:30:45these two row but may also not be so we
  2083. 1:30:48need to find a way to fix in case it's
  2084. 1:30:50better and to not fix anything in case
  2085. 1:30:53it's not better
  2086. 1:30:54and the way we do it is this so we
  2087. 1:30:57compute the new maximum of the current
  2088. 1:30:59local row query
  2089. 1:31:012 we um calculated the p12 which is the
  2090. 1:31:05soft Max star of S2 which is S2 minus M2
  2091. 1:31:11which is the local maximum and then we
  2092. 1:31:13need to add it to the output however in
  2093. 1:31:17this case we may have found a better
  2094. 1:31:19maximum so how to fix the o1 which on
  2095. 1:31:23only use the maximum that was local to
  2096. 1:31:26S1 well we know that we can fix that by
  2097. 1:31:30using exponentials because each of these
  2098. 1:31:32element of o1 is just an exponential
  2099. 1:31:36without the normalization because we are
  2100. 1:31:37applying soft Max star so how to fix an
  2101. 1:31:41exponential with another exponential so
  2102. 1:31:43basically we are saying that uh we
  2103. 1:31:45multiply o1 which is a matrix so let me
  2104. 1:31:50show you what is this Matrix so o1
  2105. 1:31:54is a matrix made up of two rows so as
  2106. 1:31:57you can see here I have the shape of o1
  2107. 1:31:59it's a 2 by 128
  2108. 1:32:02Matrix so this is the top row so 011 012
  2109. 1:32:07blah blah blah until
  2110. 1:32:09o1
  2111. 1:32:11128 then
  2112. 1:32:13o21 o22 up blah and
  2113. 1:32:17o21
  2114. 1:32:19128 we need to fix this value how we
  2115. 1:32:23basically
  2116. 1:32:24just using the exponential that we have
  2117. 1:32:26used in the online softmax that we have
  2118. 1:32:28seen before so if we multiply this
  2119. 1:32:31Matrix here by a diagonal matrix that is
  2120. 1:32:35made as follows it's a diagonal matrix
  2121. 1:32:38made up of two elements because the
  2122. 1:32:40exponential of M1 minus M2 will be a
  2123. 1:32:43vector of two elements and the
  2124. 1:32:45exponential of a element y exponential
  2125. 1:32:48is another Vector of two elements and
  2126. 1:32:51this diag basically means that diagonal
  2127. 1:32:53Matrix where in the diagonal we have the
  2128. 1:32:56elements of the vector to which we are
  2129. 1:32:58applying this diag operation which means
  2130. 1:33:01that this value here will be the
  2131. 1:33:03exponential of the first element of
  2132. 1:33:08M1 so let me show you uh how to write it
  2133. 1:33:13exponential
  2134. 1:33:15of M1 minus M2 minus M2 so the first
  2135. 1:33:22element so let's call it one here here
  2136. 1:33:25is a zero here will be zero and let's
  2137. 1:33:28delete this one and we write another one
  2138. 1:33:30here
  2139. 1:33:32exponential M1 minus M2 but the second
  2140. 1:33:36element of this Vector so basically the
  2141. 1:33:39DI this notation here diag means
  2142. 1:33:42basically just take the vector and
  2143. 1:33:44distribute it over a n byn Matrix where
  2144. 1:33:47n is the size of the vector to which it
  2145. 1:33:48is applied and all the other elements of
  2146. 1:33:51this Matrix should be zeros this is what
  2147. 1:33:53this
  2148. 1:33:54means if we do this operation here we
  2149. 1:33:57will see that the output of this
  2150. 1:34:00multiplication will fix each element of
  2151. 1:34:04the top row using this exponential and
  2152. 1:34:08the bottom row with this exponential
  2153. 1:34:10which will basically cancel out this M1
  2154. 1:34:13that was computed in the previous
  2155. 1:34:15iteration and introduce the M2 that we
  2156. 1:34:18have computed in the current iteration
  2157. 1:34:19in each of these o elements in this o
  2158. 1:34:24block
  2159. 1:34:28Matrix okay so this output will be this
  2160. 1:34:34element will will multiply by this one
  2161. 1:34:37so it will fix o11 with this Factor here
  2162. 1:34:40and o1 21 will not be fixed by will be
  2163. 1:34:43multiplied by zero so it will not
  2164. 1:34:45contribute to this first output element
  2165. 1:34:48so this element here will only depend on
  2166. 1:34:50o11 fixed by the exponential of M1 minus
  2167. 1:34:55M2 but the first element of this vector
  2168. 1:34:58and then o12 will also be fixed by um
  2169. 1:35:02o12 will be fixed by this exponential
  2170. 1:35:04here but not by this one and all the
  2171. 1:35:06dimensions of the first row will be
  2172. 1:35:08fixed by this exponential and all the
  2173. 1:35:10dimensions of the second uh row here
  2174. 1:35:12will be fixed by this uh exponential
  2175. 1:35:15here this this scalar here which is the
  2176. 1:35:18second element of the vector X of M1
  2177. 1:35:21minus
  2178. 1:35:22M2 or okay it was really challenging
  2179. 1:35:25this one so so what we are doing is we
  2180. 1:35:30compute p12 and we fix all the elements
  2181. 1:35:33in P1 by multiplying by this Matrix here
  2182. 1:35:37by multiplying by this Factor here
  2183. 1:35:39Matrix Factor here and when we will
  2184. 1:35:42compute uh step three we will fix step
  2185. 1:35:45two etc etc etc now let's talk about the
  2186. 1:35:48normalization factor because for now we
  2187. 1:35:50have been ignoring it um the
  2188. 1:35:53normalization factor is something that
  2189. 1:35:54we can compute while Computing this
  2190. 1:35:57maximums because it is provided in the
  2191. 1:36:00pseo code of the online algorithm that
  2192. 1:36:02we have seen before for the soft Max so
  2193. 1:36:05while Computing the maximum we can
  2194. 1:36:06actually compute the uh normalization
  2195. 1:36:08Factor by fixing the normalization
  2196. 1:36:11factor of the previous iteration and
  2197. 1:36:13this is exactly what we are doing here
  2198. 1:36:15so at the first iteration we comput the
  2199. 1:36:17normalization factor using the local
  2200. 1:36:19maximum and at the second iteration so
  2201. 1:36:22you can for now ignore uh this one
  2202. 1:36:24because we are not fixing l0 with
  2203. 1:36:26anything because l0 will be zero so we
  2204. 1:36:29are just basically
  2205. 1:36:31um we are just Computing this summation
  2206. 1:36:34here so l0 will be zero so this Factor
  2207. 1:36:35here will be
  2208. 1:36:37zero um and when Computing L2 so the
  2209. 1:36:40normalization Step at the second
  2210. 1:36:42iteration we will fix L1 with an
  2211. 1:36:46exponential which guess what it's
  2212. 1:36:48exactly the same exponential that fixes
  2213. 1:36:50the maximum uh the P11 so it is the
  2214. 1:36:55previous estimation of the maximum minus
  2215. 1:36:57the current estimation of the maximum
  2216. 1:36:59plus the new uh normalization factor
  2217. 1:37:02using the local maximum and we keep
  2218. 1:37:04doing this job at the end we will obtain
  2219. 1:37:08a correct output for this uh metrix for
  2220. 1:37:13for this uh block here but without the
  2221. 1:37:17normalization how to apply the
  2222. 1:37:19normalization well the normalization is
  2223. 1:37:21something that is um we need to divide
  2224. 1:37:24each element of this o by the
  2225. 1:37:26normalization factor but because we are
  2226. 1:37:29keeping while iterating through these
  2227. 1:37:31for Loops we also calculate the
  2228. 1:37:34normalization factor we keep
  2229. 1:37:36accumulating it until we reach the end
  2230. 1:37:39of the iteration and then we apply the
  2231. 1:37:40normalization factor so we take the last
  2232. 1:37:43output and we just divide it by L4 which
  2233. 1:37:46is the normalization factor calculated
  2234. 1:37:48at the fourth iteration and that will
  2235. 1:37:51fix the soft Max all right guys so now
  2236. 1:37:55that we have derived the algorithm of
  2237. 1:37:57how to compute this output of the
  2238. 1:37:59attention blockwise why also fixing the
  2239. 1:38:01soft Max which is done independently in
  2240. 1:38:04each single block we know that the
  2241. 1:38:07normalization is done at the end I want
  2242. 1:38:10to also prove it so what we done when we
  2243. 1:38:12introduce this algorithm that computes
  2244. 1:38:14the soft Max in an online way we proved
  2245. 1:38:18by induction that this algorithm is
  2246. 1:38:20correct so at the end of this algorithm
  2247. 1:38:23this L of the last iteration will
  2248. 1:38:25actually be the normalization factor
  2249. 1:38:27that we can appli to get the soft Max so
  2250. 1:38:32we don't apply the normalization while
  2251. 1:38:34Computing this output in an online way
  2252. 1:38:37iteratively way by multiplying the query
  2253. 1:38:40with all the blocks of keys we apply it
  2254. 1:38:44at the end of this four iteration and at
  2255. 1:38:47the end of this four iteration we will
  2256. 1:38:49have the last
  2257. 1:38:50output um and we also know that the last
  2258. 1:38:54L will contain the exact normalization
  2259. 1:38:57factor that we need to apply to each row
  2260. 1:38:59because this o of four is a block of
  2261. 1:39:02output rows which is if you remember
  2262. 1:39:06from the attention mechanism each output
  2263. 1:39:09the output of the attention has the same
  2264. 1:39:11shape as the input query Vector which is
  2265. 1:39:15a sequence of tokens so this O is a
  2266. 1:39:18sequence of tokens that we need to apply
  2267. 1:39:20the normalization to and we know that
  2268. 1:39:23the correct factor is L4 so let's prove
  2269. 1:39:25this simple formula uh L4 is a vector
  2270. 1:39:29one for that contains as many elements
  2271. 1:39:31as there are rows in o4 so in this O
  2272. 1:39:35Block uh of
  2273. 1:39:38rows suppose that it contains uh two
  2274. 1:39:41rows like in the algorithm that I have
  2275. 1:39:43described so far in which we pretend
  2276. 1:39:45that we are grouping two rows of queries
  2277. 1:39:47with two columns of keys together so the
  2278. 1:39:50output o uh um the block O will contain
  2279. 1:39:54two rows of the output so we will have
  2280. 1:39:57two normalization factor in this L4
  2281. 1:40:00Vector here what we are doing with this
  2282. 1:40:04formula is we are taking this L4 vector
  2283. 1:40:07and we are creating a diagonal matrix
  2284. 1:40:09with it and then we are Computing the
  2285. 1:40:11inverse of this diagonal matrix so L4 is
  2286. 1:40:16a vector that contains two normalization
  2287. 1:40:18Factor so it's l i don't know let's call
  2288. 1:40:21it l L4 4 element 1 and L4 element
  2289. 1:40:282 this is our
  2290. 1:40:31L4 uh Vector then we have 04 o4 is a
  2291. 1:40:36matrix as you can see from the shape is
  2292. 1:40:382 by
  2293. 1:40:40128 Matrix so o is let's copy it
  2294. 1:40:44actually oh no let's not copy it o4 is a
  2295. 1:40:48matrix that is two
  2296. 1:40:49rows with 128 elements so so the first
  2297. 1:40:54row with 128 dimensions and the second
  2298. 1:40:56row with 128 Dimensions the first thing
  2299. 1:41:00that we are doing with this L4 is we are
  2300. 1:41:02converting it into a diagonal matrix
  2301. 1:41:04which will be a diagonal matrix 2x two
  2302. 1:41:06because it contains two elements so it
  2303. 1:41:09will become something like this so it
  2304. 1:41:12will be L4 the first element of L4 zero
  2305. 1:41:16and then zero L4 the second element of
  2306. 1:41:19this
  2307. 1:41:20Vector then we are Computing the inverse
  2308. 1:41:23of this Matrix the inverse of a diagonal
  2309. 1:41:26matrix is just the diagonal matrix with
  2310. 1:41:28each element on the diagonal that
  2311. 1:41:31becomes its
  2312. 1:41:32reciprocal uh this is from linear
  2313. 1:41:35algebra it's not I'm making it I'm
  2314. 1:41:37making this up so uh the inverse of this
  2315. 1:41:41Matrix here is equal
  2316. 1:41:44to uh the same uh diagonal matrix but
  2317. 1:41:47where each element is one over L4 the
  2318. 1:41:51first element of L4 zero 0 and 1 over uh
  2319. 1:41:56L4 the second element of L4 and then we
  2320. 1:42:00are multiplying this stuff here so let
  2321. 1:42:02me delete some stuff so this stuff here
  2322. 1:42:05is getting multiplied by
  2323. 1:42:08o which is a matrix that is 2 by
  2324. 1:42:12128 so we are doing this multiplication
  2325. 1:42:15now
  2326. 1:42:17multiply now the output of this so this
  2327. 1:42:21is two let me WR it 2x 2 * 2x 128 will
  2328. 1:42:28be a matrix that is 2x
  2329. 1:42:31128
  2330. 1:42:34where the first um dimension of the
  2331. 1:42:38first row of the output of this
  2332. 1:42:40operation will be the dot product of
  2333. 1:42:45this col this row here with the First
  2334. 1:42:48Column so basically we are dividing this
  2335. 1:42:50element here by L4 the first element of
  2336. 1:42:52L four the second uh output element here
  2337. 1:42:56will be the dot product of this row with
  2338. 1:42:58this second column so we are only
  2339. 1:43:00multiply we are dividing the the the the
  2340. 1:43:02second element here of this input Vector
  2341. 1:43:05here by L4 the first element of L4
  2342. 1:43:08because the all the elements of the
  2343. 1:43:10second row will be multiplied by zero so
  2344. 1:43:12they will not contribute to this output
  2345. 1:43:14row while the second output row will be
  2346. 1:43:16the dot this element here will be the
  2347. 1:43:18dot product of this row with the First
  2348. 1:43:21Column the first element
  2349. 1:43:23here is multiplied by zero so it will
  2350. 1:43:25not contribute to this output so it's
  2351. 1:43:27only the second ele the first row of the
  2352. 1:43:29second the first element of the second
  2353. 1:43:32row of the input Matrix here will be
  2354. 1:43:33divided by
  2355. 1:43:35l42 so basically this will be applied
  2356. 1:43:38will divide all the elements in the
  2357. 1:43:40second row and this will divide all the
  2358. 1:43:42element in the first row in producing
  2359. 1:43:44this one here which is exactly what we
  2360. 1:43:46need to do when we want to normalize we
  2361. 1:43:48need to apply this normalization factor
  2362. 1:43:50and this should uh help you better
  2363. 1:43:52visualize why this operation is
  2364. 1:43:54normalizing the vectors of the output at
  2365. 1:43:57the end and still obtaining the same
  2366. 1:43:59result now let's proceed further all
  2367. 1:44:02right guys finally we are ready to see
  2368. 1:44:04the flash attention forward pass uh by
  2369. 1:44:08um also comparing it with what we have
  2370. 1:44:09derived so far so if you look at the
  2371. 1:44:12flashh attention paper first of all this
  2372. 1:44:14is the flashh attention to forward pass
  2373. 1:44:16and later I will explain what are the
  2374. 1:44:18differences between the flashh attention
  2375. 1:44:19one and the flesh attention two um I
  2376. 1:44:22didn't want to jump directly to this uh
  2377. 1:44:24forward pass because I believe that even
  2378. 1:44:26if the derivation like the derivation
  2379. 1:44:29was a little uh difficult to follow I
  2380. 1:44:32believe that it gave you some intuition
  2381. 1:44:34into what is happening so even if you
  2382. 1:44:36understand 50% of it that's enough
  2383. 1:44:37because later we will also code it and
  2384. 1:44:40you should reach like a 90% of
  2385. 1:44:42understanding so every time we introduce
  2386. 1:44:44some new information it should improve
  2387. 1:44:45your be the the your understanding so
  2388. 1:44:49basically in flesh attention what we are
  2389. 1:44:51flesh attention to especially we we take
  2390. 1:44:53our um as input we have our uh query
  2391. 1:44:56Kean values which are sequence of tokens
  2392. 1:44:59each token is made up of a vector of D
  2393. 1:45:02dimensions and D lower case D dimensions
  2394. 1:45:06and we divide this query guess what into
  2395. 1:45:09blocks in how many blocks well depending
  2396. 1:45:12on this parameter BR which is the size
  2397. 1:45:15of the query block that we want to
  2398. 1:45:18choose so how many rows of query we want
  2399. 1:45:21to group together into one block and we
  2400. 1:45:23also do it with K and V and we divided
  2401. 1:45:27that into um blocks of uh um depending
  2402. 1:45:31on this parameter BC then we also
  2403. 1:45:34initialize the output which is the
  2404. 1:45:36output that we want to produce so the
  2405. 1:45:38what is the flashh attention Computing
  2406. 1:45:40well the flashh attention um is
  2407. 1:45:42Computing the following so it's
  2408. 1:45:44Computing the uh soft
  2409. 1:45:46Max soft Max of the query multiply by
  2410. 1:45:50the transpose of the keys divide by the
  2411. 1:45:52some normalization Factor uh multiply
  2412. 1:45:55that by V and um so that's what it's
  2413. 1:45:58going to compute and it's going to
  2414. 1:46:00computed this way first of all there is
  2415. 1:46:03an autor Loop through the queries which
  2416. 1:46:06corresponds to the same pelo code that
  2417. 1:46:09we have seen before because we want to
  2418. 1:46:11compute each block of the output
  2419. 1:46:13Matrix um in parallel with the with with
  2420. 1:46:17respect to the others so basically we
  2421. 1:46:19want to compute this output block and
  2422. 1:46:22this block all output block
  2423. 1:46:24independently this output block here
  2424. 1:46:26depends on the query one and all the
  2425. 1:46:28keys this output block here depends on
  2426. 1:46:31the query 2 and all the keys this output
  2427. 1:46:34block here depends on the query three
  2428. 1:46:36and all the keys where query 1 is not
  2429. 1:46:39the first query but it's the first group
  2430. 1:46:41of queries or first block of queries
  2431. 1:46:43query two is not the first um query two
  2432. 1:46:46is not the second row of the query
  2433. 1:46:47Matrix but it's the second block of the
  2434. 1:46:49query Matrix etc etc um so that's why we
  2435. 1:46:53have this outer um outer uh iteration
  2436. 1:46:58among all the blocks because we want to
  2437. 1:47:00compute all those blocks of the output
  2438. 1:47:02Matrix in parallel but to compute each
  2439. 1:47:04of these output block we need to go to
  2440. 1:47:07an iteration among all the keys that's
  2441. 1:47:09why we have an inner loop on the keys
  2442. 1:47:12and we do exactly the same operation
  2443. 1:47:14that we have done so far uh by hand so
  2444. 1:47:17first we compute the S Matrix which is
  2445. 1:47:19what the each block of query with the
  2446. 1:47:21corresponding block of the keys then we
  2447. 1:47:25compute the local maximum to the current
  2448. 1:47:28s block this is the local maximum and we
  2449. 1:47:31um compare it with the maximum of the
  2450. 1:47:34previous iteration because that's what
  2451. 1:47:36we do in the online softmax then we
  2452. 1:47:38compute the
  2453. 1:47:39P the P block which is the softmax star
  2454. 1:47:44of the S block minus the local maximum
  2455. 1:47:47of the S
  2456. 1:47:48block then we compute the uh
  2457. 1:47:51normalization Factor what is the
  2458. 1:47:53normalization factor it is the summation
  2459. 1:47:57of all the exponential of the soft Max
  2460. 1:47:59star but um uh by fixing the
  2461. 1:48:04normalization factor of the previous
  2462. 1:48:06step and we know how to fix the
  2463. 1:48:07normalization factor because we just
  2464. 1:48:10multiply by an exponential which is the
  2465. 1:48:12previous maximum minus the current
  2466. 1:48:14maximum that's what this factor is and
  2467. 1:48:17then we computed the output exactly
  2468. 1:48:19using the same uh correction factor that
  2469. 1:48:22we have seen before which is the
  2470. 1:48:23diagonal matrix made up of the diagonal
  2471. 1:48:26um where on the diagonal you have the
  2472. 1:48:28elements of this Vector here which is
  2473. 1:48:30the exponential of the previous maximum
  2474. 1:48:33minus the current maximum multiplied by
  2475. 1:48:35the output of the previous step because
  2476. 1:48:37we want to fix the previous step because
  2477. 1:48:39it was based on the previous P which was
  2478. 1:48:40using the maximum of the local previous
  2479. 1:48:43P plus the current p v which is based on
  2480. 1:48:47the current local maximum and it will be
  2481. 1:48:49fixed by the next
  2482. 1:48:51iteration okay okay and at the end after
  2483. 1:48:54we have gone through all the cas so we
  2484. 1:48:58have computed all the output block but
  2485. 1:49:01we didn't apply the normalization factor
  2486. 1:49:03and it's applied at the end because
  2487. 1:49:05while going through each key we are
  2488. 1:49:07calculating the L normalization factor
  2489. 1:49:10for the softmax because inside of this
  2490. 1:49:12for Loop we are just Computing the
  2491. 1:49:14softmax star so we are not normalizing
  2492. 1:49:16each value so at the end someone has to
  2493. 1:49:18normalize it and it will be this um this
  2494. 1:49:22this um instruction here which is use
  2495. 1:49:26the normalization factor that we have
  2496. 1:49:29computed over all the iterations and
  2497. 1:49:31apply it to each element of O because
  2498. 1:49:33the difference between the softx star
  2499. 1:49:36and the actual sofx is just the division
  2500. 1:49:38by the um the normalization factor and
  2501. 1:49:42this instruction here is actually
  2502. 1:49:44dividing each o with the corresponding
  2503. 1:49:47normalization Factor one for each row of
  2504. 1:49:50the block each row in the output block
  2505. 1:49:54that we are
  2506. 1:49:55Computing uh later we will see also what
  2507. 1:49:59do we do what is what does it what is
  2508. 1:50:01this SRAM what is the hbm for now I just
  2509. 1:50:03want you to concentrate on the um
  2510. 1:50:06operations that we are doing and they
  2511. 1:50:07are exactly the same operations that we
  2512. 1:50:09have done so far uh later we will see
  2513. 1:50:12also why do we need to save this stuff
  2514. 1:50:14here and etc etc but for now you should
  2515. 1:50:17have enough knowledge to be able to
  2516. 1:50:19follow what is written in the flesh
  2517. 1:50:21attention paper for with respect to the
  2518. 1:50:24forward pass algorithm and uh what we
  2519. 1:50:27are doing basically is just block matrix
  2520. 1:50:29multiplication and while Computing this
  2521. 1:50:31block we fix the previous block by using
  2522. 1:50:34tricks of the
  2523. 1:50:36exponential all right now that we have
  2524. 1:50:39seen forward Paths of the flashh
  2525. 1:50:41attention before we can implement it we
  2526. 1:50:43still lack a little bit of knowledge
  2527. 1:50:45because we don't know anything about the
  2528. 1:50:47gpus and we don't know anything about
  2529. 1:50:49Cuda and we don't know anything about
  2530. 1:50:50Triton so that's what we are going to
  2531. 1:50:52see
  2532. 1:50:53next all right guys it's time for us to
  2533. 1:50:56explore finally the GPU and the Cuda
  2534. 1:50:59programming model well uh let's start by
  2535. 1:51:01comparing the CPU and the GPU and this
  2536. 1:51:04will let us understand how Cuda works
  2537. 1:51:06then so first of all what is the Cuda
  2538. 1:51:07and what is the GPU the GPU is the
  2539. 1:51:09hardware unit that we are that we buy
  2540. 1:51:12and Cuda is a software stocks made by um
  2541. 1:51:15made by Nvidia or to write software for
  2542. 1:51:18this GPU that they sell AMD has its own
  2543. 1:51:21software stock and other manufacturer
  2544. 1:51:23have their own in this particular video
  2545. 1:51:26we will be seeing example of Cuda
  2546. 1:51:27kernels but the knowledge that you will
  2547. 1:51:29get can apply also to other gpus now the
  2548. 1:51:33first difference between a CPU and a GPU
  2549. 1:51:35is its purpose uh the GP the your
  2550. 1:51:38computer is right now running on a CPU
  2551. 1:51:41and your operating system is interfacing
  2552. 1:51:43with the CPU um in using the uh the the
  2553. 1:51:46so-called scheduler so right now
  2554. 1:51:49probably you are running a browser you
  2555. 1:51:50are also running some other software on
  2556. 1:51:52your computer
  2557. 1:51:53on your computer and the scheduler is
  2558. 1:51:56tasked with switching between them very
  2559. 1:51:58fast on your CPU in such a way that it
  2560. 1:52:00looks like to you that the processes are
  2561. 1:52:02running
  2562. 1:52:03concurrently uh this actually is a fake
  2563. 1:52:06kind of parallelism unless your CPU also
  2564. 1:52:09has multiple cores which nowadays CPUs
  2565. 1:52:12do have so a CPU usually has one or
  2566. 1:52:15multiple cores but not so many of them
  2567. 1:52:17so usually have dual core of quad core
  2568. 1:52:19or eight core CPU and each of the this
  2569. 1:52:22course can execute instructions in
  2570. 1:52:26parallel um the CPU is tasked the the
  2571. 1:52:30main purpose of the CPU is to execute
  2572. 1:52:32many different task uh and switching
  2573. 1:52:35between them very fast so maybe you have
  2574. 1:52:37a browser that is running a small game
  2575. 1:52:40and then you have another movie player
  2576. 1:52:42but then you have a word processor and
  2577. 1:52:43then you maybe have some uh utility to
  2578. 1:52:46manage your um to download files Etc so
  2579. 1:52:50most of these programs actually are not
  2580. 1:52:51computing intensive are actually iio
  2581. 1:52:53bound meaning that most of the time they
  2582. 1:52:55are either waiting for the network or
  2583. 1:52:57they are waiting for the dis and they
  2584. 1:52:59are very different from each other in
  2585. 1:53:01the purpose so a browser is completely
  2586. 1:53:03different from a movie player and it's
  2587. 1:53:05completely different from a word
  2588. 1:53:07processor um so the job of the CPU is to
  2589. 1:53:10actually reduce the latencies of
  2590. 1:53:12processing all these operations and it's
  2591. 1:53:15highly optimized to process to optimize
  2592. 1:53:18each of these execution unit called the
  2593. 1:53:20course which means that each course
  2594. 1:53:23has a part that is tasked to understand
  2595. 1:53:26first of all what is the next
  2596. 1:53:27instruction to run or to to predict the
  2597. 1:53:31branch of how the what the next uh
  2598. 1:53:34operation may be based on the conditions
  2599. 1:53:37that you are running for example if you
  2600. 1:53:38have a if condition the branch predictor
  2601. 1:53:41can understand what is the more most
  2602. 1:53:42likely next instruction and can do some
  2603. 1:53:45optimizations uh also the CPU is has a
  2604. 1:53:48lot of caches to reduce the latencies in
  2605. 1:53:50loading data from all the devices it can
  2606. 1:53:53interface with it can interface with the
  2607. 1:53:55uh the RAM for sure but it can also
  2608. 1:53:57interface with the dis it can also
  2609. 1:53:59interface with some peripherals like the
  2610. 1:54:01printer like the mouse like the keyboard
  2611. 1:54:02etc etc on the other hand the GPU is not
  2612. 1:54:07tasked to do many different things at
  2613. 1:54:09the same time but it's task to do one
  2614. 1:54:12thing or few things but on a massive
  2615. 1:54:15amount of data so the operations that we
  2616. 1:54:17do on the GPU are uh requires a lot of
  2617. 1:54:21computation and for that for this reason
  2618. 1:54:23most of the area so the physical area of
  2619. 1:54:26the GPU is dedicated to compute units so
  2620. 1:54:29this green stuff that you can see here
  2621. 1:54:31and these are called
  2622. 1:54:33course um and you can see that the part
  2623. 1:54:35that is dedicated to the control area so
  2624. 1:54:38the part that is um tusked with
  2625. 1:54:40understanding what is the next
  2626. 1:54:41instruction to run or to do some
  2627. 1:54:43optimization in this the program is very
  2628. 1:54:45little uh you may be thinking well uh
  2629. 1:54:48does it make it does it make the GPU uh
  2630. 1:54:51less fast compared to the GPU to the CPU
  2631. 1:54:54well not really because we have many
  2632. 1:54:56more coures that can compensate for this
  2633. 1:54:58um higher
  2634. 1:55:00latencies um okay I can give you a lot
  2635. 1:55:03of knowledge about the GPU from a
  2636. 1:55:05theoretical point of view I think the
  2637. 1:55:06best way to understand the Cuda
  2638. 1:55:08programming model is just to jump into
  2639. 1:55:09the code so we don't get bored okay
  2640. 1:55:12imagine we have a very simple task and
  2641. 1:55:15we have a
  2642. 1:55:16vector we have two vectors A and B and
  2643. 1:55:20we want to calculate the sum of these
  2644. 1:55:22two vectors vectors into and save the
  2645. 1:55:23result into another Vector C where each
  2646. 1:55:26item is the element wise sum of the
  2647. 1:55:29corresponding item of A and B how would
  2648. 1:55:32you proceed with this task on the CPU
  2649. 1:55:36well you would do a for Loop for example
  2650. 1:55:38so for example uh you would uh make a
  2651. 1:55:41for Loop that starts from the first
  2652. 1:55:42index so the index zero and C of0 is
  2653. 1:55:46equal to a of 0 plus b of0 then C of 1
  2654. 1:55:50is equal to uh a of 1 plus b of one Etc
  2655. 1:55:53and you do a for loop on all the
  2656. 1:55:55elements of this
  2657. 1:55:57Vector in the GPU we want to do the same
  2658. 1:56:00operation but in parallel because we
  2659. 1:56:02have a lot of compute units called
  2660. 1:56:04course and we want all of them to work
  2661. 1:56:06in parallel so the first thing that we
  2662. 1:56:08need to understand is how to divide the
  2663. 1:56:10work that we are going to do into
  2664. 1:56:13subunits of work and dedicate each core
  2665. 1:56:16to one subunit one simple subdivision
  2666. 1:56:19would be okay the first core should do
  2667. 1:56:21this summation the second core should do
  2668. 1:56:23this summation the third core should do
  2669. 1:56:26the summation etc etc so imagine we have
  2670. 1:56:30a eight element Vector we need eight
  2671. 1:56:32course to do this element wise
  2672. 1:56:35summation we will call the course
  2673. 1:56:38threads because it should also remind
  2674. 1:56:40you of the multi- threading uh that we
  2675. 1:56:42already use in operating system so
  2676. 1:56:44multiple threads work concurrently on
  2677. 1:56:46the same uh on the same or similar job
  2678. 1:56:49in the GPU let's look at the code now
  2679. 1:56:52the code that I am going to show you is
  2680. 1:56:54Auda kernel and it's written in C but
  2681. 1:56:56you don't have to understand C and you
  2682. 1:56:58don't have to understand this code what
  2683. 1:57:00I want you to understand is the
  2684. 1:57:01intuition behind it because later we
  2685. 1:57:03will need this knowledge and convert it
  2686. 1:57:05into Tron which is Python and you should
  2687. 1:57:07already be familiar with
  2688. 1:57:08python so let's go to the code and I
  2689. 1:57:12have a very simple vector addition uh we
  2690. 1:57:15can see it
  2691. 1:57:16here okay uh first of all how to do a
  2692. 1:57:21vector summation usually the GPU is
  2693. 1:57:24interfaced with a CPU and the CPU has to
  2694. 1:57:28first of all um tell the GPU what is the
  2695. 1:57:31data it he's going to work with so the
  2696. 1:57:33CPU needs to have these vectors it needs
  2697. 1:57:35to transfer them to the GPU then the GPU
  2698. 1:57:39needs to do this Vector summation then
  2699. 1:57:41the CPU has to copy back the information
  2700. 1:57:44from the output from the GPU to the CPU
  2701. 1:57:46and then make it available to the
  2702. 1:57:48program this is what we are going to do
  2703. 1:57:50here so we are going to allocate three
  2704. 1:57:54vectors of size n one called a one
  2705. 1:57:58called B and one is the output Vector we
  2706. 1:58:00initialize their items um randomly so a
  2707. 1:58:04of I uh is a random number between zero
  2708. 1:58:08and 100
  2709. 1:58:09excluded then we allocate memory on the
  2710. 1:58:13GPU to hold these vectors and then we
  2711. 1:58:15copy them to the GPU so we copyed the a
  2712. 1:58:17vector to the GPU and the B Vector to
  2713. 1:58:19the GPU of course we don't copy the
  2714. 1:58:21result because that's what we want the
  2715. 1:58:22GPU to populate with uh the output so we
  2716. 1:58:26just allocate it on the GPU what we
  2717. 1:58:28don't copy uh our output Vector on the
  2718. 1:58:30GPU because it's it's made of random
  2719. 1:58:33values then um what we do is we launch
  2720. 1:58:37the kernel the launching the kernel
  2721. 1:58:38means that we launch a program that the
  2722. 1:58:41GPU should execute in parallel on
  2723. 1:58:43multiple threads or multiple course each
  2724. 1:58:45of these threads should do a unit of
  2725. 1:58:48operation a unit of work that is
  2726. 1:58:50independent from the others actually
  2727. 1:58:51they can be dependent on the other but
  2728. 1:58:53we will not be talking about
  2729. 1:58:55synchronization um so we launched this
  2730. 1:58:58kernel and what we are seeing in this
  2731. 1:59:00line is launch one block of threads and
  2732. 1:59:04later we will see what are blocks but
  2733. 1:59:05you can think of you can ignore this one
  2734. 1:59:07for now what we are saying here is
  2735. 1:59:09launch n threads so n multi parallel
  2736. 1:59:13operations on with the following
  2737. 1:59:16arguments so the output where we want to
  2738. 1:59:18save data the input array a and the B uh
  2739. 1:59:22input B and the number of elements let's
  2740. 1:59:25see what happens inside of this method
  2741. 1:59:27this method is following a particular
  2742. 1:59:29syntax that is um um how to say Cuda uh
  2743. 1:59:34specific So This Global is actually
  2744. 1:59:36added it's like a superet of the C
  2745. 1:59:38language where we have some additional
  2746. 1:59:40keywords that belong to Cuda so it's not
  2747. 1:59:43really C it's Cuda
  2748. 1:59:46c um so it's a very simple uh method as
  2749. 1:59:49you can see and the first thing that we
  2750. 1:59:51need to do is
  2751. 1:59:52Cuda cannot know what each thread should
  2752. 1:59:56do it's we should tell each thread what
  2753. 1:59:59to do so the mapping between the data
  2754. 2:00:02and the what each thread should do it's
  2755. 2:00:04up to us as software
  2756. 2:00:06engineer Cuda what we do is when we ask
  2757. 2:00:09it to launch n threads in parallel it
  2758. 2:00:11will allocate n threads and assign a
  2759. 2:00:14unique identifier to each of these
  2760. 2:00:16threads in our simple case we can see it
  2761. 2:00:20like this so it will assign the first
  2762. 2:00:23thread the index zero so we are asking
  2763. 2:00:27for example imagine we have a vector of
  2764. 2:00:28eight elements it will assign the first
  2765. 2:00:31thread index zero here I call it one but
  2766. 2:00:33it's it's wrong but uh we can write
  2767. 2:00:36another number here so this will be
  2768. 2:00:38actually tread zero this will be tread
  2769. 2:00:39one this will be tread two tread three
  2770. 2:00:42tread four tread five tread six and
  2771. 2:00:45tread 7 so let me delete this
  2772. 2:00:49one so we don't get confused
  2773. 2:01:00and what we are seeing is that the item
  2774. 2:01:04that each thread should process is equal
  2775. 2:01:07to its thread index so this is the
  2776. 2:01:09thread zero so it should process the
  2777. 2:01:12item with index zero this is the thread
  2778. 2:01:14one and it should process the item with
  2779. 2:01:16index one this is the thread number two
  2780. 2:01:18and it should process the item with
  2781. 2:01:20index two and this is what we are doing
  2782. 2:01:22in this line of code we are saying which
  2783. 2:01:25item each thread should process which is
  2784. 2:01:27exactly the it's uh the thread
  2785. 2:01:30identifier so the thread ID uh later we
  2786. 2:01:33will see why why we have this dot X but
  2787. 2:01:36that's for later next thing that you
  2788. 2:01:39should see is okay we are doing the
  2789. 2:01:42output of the I position is equal to the
  2790. 2:01:45a um Vector at the E position plus the B
  2791. 2:01:49Vector at the E position so it's a very
  2792. 2:01:51simple summation element wise you may
  2793. 2:01:53have noticed this if statement why do we
  2794. 2:01:56need an if statement if we already know
  2795. 2:01:58that we are going to launch eight
  2796. 2:02:00threads and uh of course I will be
  2797. 2:02:04between um we already know that we are
  2798. 2:02:07going to launch n threads so I should of
  2799. 2:02:09course be less than n because each
  2800. 2:02:11thread ID will be between zero and N
  2801. 2:02:13minus one so why do we need this if
  2802. 2:02:15condition this is needed because when
  2803. 2:02:18you um Cuda when it launches a number of
  2804. 2:02:22threads this number of threads is always
  2805. 2:02:24a multiple of um a unit which is 32 in
  2806. 2:02:28the case of the Cuda so if we have like
  2807. 2:02:3234 elements in a vector and we ask Cuda
  2808. 2:02:35to launch 34 threads Cuda will not
  2809. 2:02:37launch 34 exactly it will launch 64
  2810. 2:02:40threads so multiple of 32 uh which is
  2811. 2:02:43the warp size by the way um and
  2812. 2:02:47U what we need to do is we need to ask
  2813. 2:02:50these threads to only work for we only
  2814. 2:02:54need to ask the threads that have a
  2815. 2:02:57corresponding element to work and all
  2816. 2:02:59the other that don't have a
  2817. 2:03:00corresponding element because the the uh
  2818. 2:03:02the vector is not large enough for all
  2819. 2:03:04of them to not do anything so do not
  2820. 2:03:06enter this uh uh if
  2821. 2:03:09statement there is another thing that we
  2822. 2:03:11should learn which is actually the
  2823. 2:03:14threads um actually when we have a group
  2824. 2:03:18of threads in in um Cuda programming
  2825. 2:03:20model but I believe also in other
  2826. 2:03:22gpus um a group of threads of 32 threads
  2827. 2:03:27is called a warp and this 32 threads
  2828. 2:03:30will share the same um control unit so
  2829. 2:03:34let's go back to the slide so as you saw
  2830. 2:03:38as you can see here we have this yellow
  2831. 2:03:40unit here in the GPU and a group of
  2832. 2:03:43threads will share the same control unit
  2833. 2:03:45which means that what is this control
  2834. 2:03:46unit it's a part of the hardware of the
  2835. 2:03:49GPU that is tasked with understanding
  2836. 2:03:51what is the next instruction to run now
  2837. 2:03:55if the group of threads is sharing the
  2838. 2:03:57same unit it means that this group of
  2839. 2:03:59thread will always execute the same
  2840. 2:04:01statement at any time they will always
  2841. 2:04:04work in synchrony will always work on
  2842. 2:04:07the same instruction it's it cannot be
  2843. 2:04:10like this thread is working on one
  2844. 2:04:11instruction and this one is working on
  2845. 2:04:13another instruction what does this mean
  2846. 2:04:15on a programming level it means that if
  2847. 2:04:19when we launch a group of threads of
  2848. 2:04:22course Cuda will spawn more threads than
  2849. 2:04:23we need if the if the number of elements
  2850. 2:04:26of our Vector is not a multiple of
  2851. 2:04:2932 this means that when we This Thread
  2852. 2:04:32they will first execute this uh
  2853. 2:04:34operation and each of them will have its
  2854. 2:04:36own uh value of this thread ID so they
  2855. 2:04:40will execute the same instruction but
  2856. 2:04:42the data at each instruction may be
  2857. 2:04:44different because each of them have
  2858. 2:04:45their own registers which means that
  2859. 2:04:48they will always they will for example
  2860. 2:04:51reach this statement here and the first
  2861. 2:04:53thread will have I equal to zero the
  2862. 2:04:55second thread will have I equal to 1 etc
  2863. 2:04:57etc even if they are executing the same
  2864. 2:04:59instruction this programming model is
  2865. 2:05:01called single instruction multiple data
  2866. 2:05:03Cuda likes to call it single instruction
  2867. 2:05:05multiple thread doesn't matter for us it
  2868. 2:05:08just means that they will always execute
  2869. 2:05:10the same instruction but the value of
  2870. 2:05:12the variables may be
  2871. 2:05:14different then after executing this
  2872. 2:05:17statement they will reach this statement
  2873. 2:05:19here the if statement and of course some
  2874. 2:05:21some of them will evaluate this
  2875. 2:05:23statement to true and some of them will
  2876. 2:05:25execute the statement to false which
  2877. 2:05:27also means that some of them should
  2878. 2:05:29enter this if statement and some of them
  2879. 2:05:31should not enter this if statement
  2880. 2:05:34however because the control unit is the
  2881. 2:05:36same for all of them they will be forced
  2882. 2:05:39to enter this if statement even if they
  2883. 2:05:41should not so how Cuda manages this
  2884. 2:05:44control Divergence it will basically
  2885. 2:05:46make work like this all the threads for
  2886. 2:05:49which this if statement is equal to True
  2887. 2:05:51will enter this if and will execute the
  2888. 2:05:53instructions inside of this if and all
  2889. 2:05:56the threads that have this statement
  2890. 2:05:59equal to false so the condition of this
  2891. 2:06:02if equal to false they will enter the
  2892. 2:06:04for Loop because they cannot not enter
  2893. 2:06:06it because they should be always
  2894. 2:06:07executing the same instruction at any
  2895. 2:06:09time but they will just not do any
  2896. 2:06:11operations inside of this for Loop they
  2897. 2:06:13will just sit
  2898. 2:06:15idle this is um called control
  2899. 2:06:18Divergence and it can reduce the um the
  2900. 2:06:21the throughput of your program so you
  2901. 2:06:23want to minimize it um but you may be
  2902. 2:06:27wondering why doesn't the GPU dedicate a
  2903. 2:06:29control unit to each core so that they
  2904. 2:06:31can work independently from each other
  2905. 2:06:33because the control unit is expensive to
  2906. 2:06:35add in the cheap area of the GPU it's
  2907. 2:06:37much more efficient to add more workers
  2908. 2:06:40instead of adding control area control
  2909. 2:06:42units for each worker so this is a
  2910. 2:06:45design choice of the GPU and it works
  2911. 2:06:47fine okay now that we have seen how a
  2912. 2:06:50kernel works Works let's move forward to
  2913. 2:06:54another
  2914. 2:06:55example all right the next example that
  2915. 2:06:58we are going to see is the following is
  2916. 2:07:00the same as the as before so we are
  2917. 2:07:02going to do a vector addition but
  2918. 2:07:04imagine that we have a very large Vector
  2919. 2:07:06so imagine that we have a vector with 1
  2920. 2:07:08million elements of course we could do
  2921. 2:07:11like before so we launch a kernel with 1
  2922. 2:07:14million threads the problem is Cuda will
  2923. 2:07:17reject it because it say I don't have 1
  2924. 2:07:19million threads to run in parallel so
  2925. 2:07:21how can we proceed in this case because
  2926. 2:07:23usually we are working with very big
  2927. 2:07:26matrices or very big vectors so we need
  2928. 2:07:28to process a massive amount of data so
  2929. 2:07:30how to manage a parallel um uh how to
  2930. 2:07:35say parallel computation when we do not
  2931. 2:07:37have enough uh computation course one
  2932. 2:07:41way is to divide the input Vector into
  2933. 2:07:44blocks of uh elements for example we may
  2934. 2:07:47decide for example imagine our um GPU
  2935. 2:07:51only has 32 cores in total we may divide
  2936. 2:07:54our input Vector into blocks of size 32
  2937. 2:07:58such that the first 32 element are the
  2938. 2:08:00first block the next 32 element are the
  2939. 2:08:02second block the third 32 element the
  2940. 2:08:05third block and the last 32 element are
  2941. 2:08:08the last
  2942. 2:08:09block in this way we can ask the GPU to
  2943. 2:08:13work on one block at a time so we can
  2944. 2:08:15say okay work on the first block and
  2945. 2:08:18after it has processed the first block
  2946. 2:08:20it can work on on the second block and
  2947. 2:08:22then the third block and the fourth
  2948. 2:08:23block this also allows the GPU itself to
  2949. 2:08:27manage subunit of work because imagine
  2950. 2:08:30now we have um blocks of 32 elements but
  2951. 2:08:34we have a GPU of 64 cores the GPU we can
  2952. 2:08:38also schedule two blocks at the same
  2953. 2:08:40time because it has enough course so we
  2954. 2:08:42need to give some granularity uh we need
  2955. 2:08:46to reduce the Gran uh increase the
  2956. 2:08:47granularity of our data to let the GPU
  2957. 2:08:51decide how many blocks to schedule this
  2958. 2:08:53is the reason we introduce blocks inside
  2959. 2:08:56of Cuda so let me make a concrete
  2960. 2:08:59example but with a very simple
  2961. 2:09:01assumption imagine our GPU only has two
  2962. 2:09:03cores or let's say four cores actually
  2963. 2:09:06uh so we have uh n is equal to eight
  2964. 2:09:10elements eight and we have four cores in
  2965. 2:09:15total so what we can do for example is
  2966. 2:09:17to is divide this uh um Vector into
  2967. 2:09:21groups of either four cores or even less
  2968. 2:09:24let's say two two elements at a time so
  2969. 2:09:27this is the block number one this is the
  2970. 2:09:29block number two this is the block
  2971. 2:09:32number three and this is the block
  2972. 2:09:34number
  2973. 2:09:35four we can ask Cuda to launch a kernel
  2974. 2:09:40that is made up of four blocks and where
  2975. 2:09:43each block is made up of two threads so
  2976. 2:09:46when we launch the um Cuda kernel we can
  2977. 2:09:50show the code now
  2978. 2:09:52we ask the Cuda where is the
  2979. 2:09:56instruction this first instruction tells
  2980. 2:09:59Cuda how many blocks we have and the
  2981. 2:10:01second part of this um in this uh um
  2982. 2:10:06symbols tells how many threads we have
  2983. 2:10:09for each block in our case we want um
  2984. 2:10:14nide by the block size number of blocks
  2985. 2:10:17where the block size in my picture is
  2986. 2:10:19two so how many blocks we will will have
  2987. 2:10:21we will have a number of blocks so the
  2988. 2:10:24number of
  2989. 2:10:29blocks is n / by two where two is the
  2990. 2:10:33block
  2991. 2:10:35size so this is the block size and this
  2992. 2:10:39will be equal to four blocks each of
  2993. 2:10:43size equal to two and this is what we
  2994. 2:10:45are doing here uh so we are saying that
  2995. 2:10:49the number of blocks is okay the ceiling
  2996. 2:10:51because it may not be a multiple of the
  2997. 2:10:53block size n of nide by the block size
  2998. 2:10:57and this tells how many blocks we have
  2999. 2:11:00and this is will be this will Define our
  3000. 2:11:02grid it means the grid is basically
  3001. 2:11:04telling how many blocks we have and then
  3002. 2:11:07each block is made up of block size
  3003. 2:11:09number of threads then the problem is
  3004. 2:11:12how do we assign the work to do to each
  3005. 2:11:15of these threads when we launch a kernel
  3006. 2:11:18like this with this configuration so the
  3007. 2:11:21number of blocks and the number of
  3008. 2:11:22threads per block Cuda will do the
  3009. 2:11:25following job it will assign this block
  3010. 2:11:29um each block an index called the block
  3011. 2:11:33ID where the block ID of the first block
  3012. 2:11:36is zero so let me write here so this
  3013. 2:11:38will have the first block will have a
  3014. 2:11:40block ID equal to zero and in each block
  3015. 2:11:45it will assign a thread ID and the
  3016. 2:11:48thread ID of the first thread of each
  3017. 2:11:50block will be the thread zero and the
  3018. 2:11:53second thread will be the thread number
  3019. 2:11:55one the second block will have block
  3020. 2:11:58ID block ID equal to one and the first
  3021. 2:12:02thread of this block will be the thread
  3022. 2:12:04number zero and the second thread of
  3023. 2:12:06this block will be the thread number one
  3024. 2:12:08the third block will have a block
  3025. 2:12:11ID block ID equal to two and the first
  3026. 2:12:15thread will be the thread number zero
  3027. 2:12:17and the second thread will be thread
  3028. 2:12:18number one Etc until the last block
  3029. 2:12:21which will be equal to three this will
  3030. 2:12:24be thread number zero and thread number
  3031. 2:12:25one the problem is now based only on the
  3032. 2:12:28index of the block and the index of the
  3033. 2:12:31thread how can we map it to what element
  3034. 2:12:34of the vector each thread should work
  3035. 2:12:36with one simple assignment would be to
  3036. 2:12:39just do uh well you can see that in this
  3037. 2:12:42case we need the uh this Vector um This
  3038. 2:12:46Thread here to work with element zero
  3039. 2:12:48this one should work with element one
  3040. 2:12:51this one should work with the element
  3041. 2:12:52number two this one to the element
  3042. 2:12:54number three this one four this one
  3043. 2:12:58five six and seven this five is so ugly
  3044. 2:13:04so let me write it
  3045. 2:13:06again how can we find the mapping given
  3046. 2:13:09only the block ID and the thread ID how
  3047. 2:13:12can we find Which element it should
  3048. 2:13:14correspond to well it's very simple
  3049. 2:13:15formula so you can see that the
  3050. 2:13:18element let's call it the element ID
  3051. 2:13:22which in the code I call it I is equal
  3052. 2:13:25to the block
  3053. 2:13:27ID multiplied by the size of each block
  3054. 2:13:31which is block size let's call
  3055. 2:13:33it block size yeah I have it block
  3056. 2:13:38size plus the tread
  3057. 2:13:42ID because in the case of the first
  3058. 2:13:45thread this will be equal to 0 * 2 + 0
  3059. 2:13:49which is 0 in this case it will be equal
  3060. 2:13:51to 0 * 2 which is 0 + 1 and it will be
  3061. 2:13:55equal to 1 in this case it will be equal
  3062. 2:13:57to 1 because block ID is equal 1 1 * 2
  3063. 2:14:00is equal to 2+ 0 is equal to 2 etc etc
  3064. 2:14:03and you can see that this formula works
  3065. 2:14:05for all the threads so the mapping when
  3066. 2:14:07we launch a Cuda kernel we are telling
  3067. 2:14:10the GPU how many blocks we want and how
  3068. 2:14:13many threads there are in in each block
  3069. 2:14:15but Cuda has no notion of how to map
  3070. 2:14:19each um Cuda has no way of knowing how
  3071. 2:14:22to map each um thread into the element
  3072. 2:14:28it should work with that's up to us and
  3073. 2:14:30that's what we are doing here when we
  3074. 2:14:32are creating this um uh Kel here so we
  3075. 2:14:36are telling that the each element each
  3076. 2:14:39thread should work with the E element of
  3077. 2:14:42the vector where I is calculated as
  3078. 2:14:44follow the block ID to which This Thread
  3079. 2:14:46belongs multiplied by the block size so
  3080. 2:14:49how many threads there are in in each
  3081. 2:14:51block plus the thread ID um and this
  3082. 2:14:55will tell the I element this particular
  3083. 2:14:57thread should work with by giving uh in
  3084. 2:15:01let's go back to the slides by choosing
  3085. 2:15:05the block size equal to two and having
  3086. 2:15:08four cores the GPU can choose to run one
  3087. 2:15:12block or two block concurrently if it
  3088. 2:15:15has enough free course so that's why we
  3089. 2:15:17want to work with by block by block
  3090. 2:15:19because it allows the GP you to choose
  3091. 2:15:21how it want to parallelize the
  3092. 2:15:23operations if it has enough course and
  3093. 2:15:26we don't need to have n course for n ve
  3094. 2:15:29n element Vector we can divide it into
  3095. 2:15:31smaller blocks and let the GPU manage
  3096. 2:15:33the scheduling let's see one last
  3097. 2:15:36example and then we move on to
  3098. 2:15:38Tron imagine now we want to do a matrix
  3099. 2:15:41addition instead of doing a vector
  3100. 2:15:43addition now in a matrix addition we
  3101. 2:15:46have data that we can see on two axes
  3102. 2:15:49one is the rows and one is the
  3103. 2:15:52columns it's usually uh we represent the
  3104. 2:15:55vertical axis as the y axis and the
  3105. 2:15:58horizontal axis as the
  3106. 2:16:01xaxis by using the same blocked um uh uh
  3107. 2:16:06intuition that we used before so
  3108. 2:16:08dividing the data input data into blocks
  3109. 2:16:11this is how we can divide the labor of
  3110. 2:16:13our maxr addition into blocks for
  3111. 2:16:16example we can divide our rows into
  3112. 2:16:19blocks and call this one the block block
  3113. 2:16:21zero and this one in the block one and
  3114. 2:16:23this one is the block two the same we
  3115. 2:16:25can do on the xaxis so we can choose
  3116. 2:16:29this one as the block zero this one as
  3117. 2:16:31the block one and this one as the block
  3118. 2:16:33two on the x axis with X is the column
  3119. 2:16:36axis and the Y is the row axis we don't
  3120. 2:16:39even have to choose the same block size
  3121. 2:16:42for the rows and the columns we can even
  3122. 2:16:44choose the to group together three
  3123. 2:16:47columns and two rows instead of doing
  3124. 2:16:50two and two in this case we need to find
  3125. 2:16:53because as we said before when we launch
  3126. 2:16:55a Cuda kernel Cuda will just assign IDs
  3127. 2:16:59to the blocks and the threads in each
  3128. 2:17:01block then it's up to us understanding
  3129. 2:17:03what to how to map the ID of the block
  3130. 2:17:06and its corresponding thread ID into the
  3131. 2:17:08data element that this particular thread
  3132. 2:17:10should work it should work with so in
  3133. 2:17:13the case of metrix addition we could say
  3134. 2:17:15that each thread should work with one
  3135. 2:17:18output element of the output Matrix C so
  3136. 2:17:21it will become the um the the sum of the
  3137. 2:17:24a element plus the B element and it
  3138. 2:17:26should map it to the C Matrix uh output
  3139. 2:17:30Matrix so how to do it imagine we have
  3140. 2:17:33six rows and we have six columns one
  3141. 2:17:37easy way would be to divide this rows
  3142. 2:17:39into three blocks each made up of two
  3143. 2:17:42rows and each column into three blocks
  3144. 2:17:46um each block made up of two columns
  3145. 2:17:49Cuda will launch
  3146. 2:17:52uh uh as many blocks as there are the
  3147. 2:17:54combinations of the rows and column
  3148. 2:17:56blocks so in this case we have uh three
  3149. 2:17:59blocks for the columns and three blocks
  3150. 2:18:01for the um uh rows so it will launch uh
  3151. 2:18:05nine blocks so this is the block number
  3152. 2:18:0800 because it's Cuda will identify the
  3153. 2:18:11dimensions of the block based on the um
  3154. 2:18:15uh axis in which we have divided it so
  3155. 2:18:18we will call this the X Dimension the
  3156. 2:18:20columns and the rows we will call it the
  3157. 2:18:22Y Dimension so it will launch as many
  3158. 2:18:24blocks as there are combinations of X
  3159. 2:18:26and y's in this case we have nine so
  3160. 2:18:28this will be the block 0 0 this will be
  3161. 2:18:31the block 01 this will be the block 02
  3162. 2:18:34this one will be the block 1 Z 1 one and
  3163. 2:18:38one two etc etc inside of each block we
  3164. 2:18:41will also divide the threads into X
  3165. 2:18:44threads and Y threads along the two
  3166. 2:18:46Dimensions so this will be the thread
  3167. 2:18:48zero and the thread one along the X axis
  3168. 2:18:51in the X block and this will be the
  3169. 2:18:54thread zero and the thread one in the Y
  3170. 2:18:57uh in the in the block zero of the y-
  3171. 2:18:59AIS and each block will have two threads
  3172. 2:19:03and they will be identified as thread
  3173. 2:19:05zero and thread
  3174. 2:19:06one so let's look at how the launch grid
  3175. 2:19:09Works in this case um so imagine we have
  3176. 2:19:13a matrix with number uh num rows number
  3177. 2:19:16of rows and num columns num calls number
  3178. 2:19:19of columns and we want to to divide each
  3179. 2:19:22row the rows into block size number of
  3180. 2:19:26rows and calls block size number of
  3181. 2:19:30columns um we define basically the
  3182. 2:19:33number of blocks that we need is this
  3183. 2:19:35one so this is just a fency way of
  3184. 2:19:37writing the ceiling of the num Rose
  3185. 2:19:39divide by The Rose block size and this
  3186. 2:19:41is just a feny way of writing the
  3187. 2:19:44ceiling of the number of columns divide
  3188. 2:19:46by the col's block size this tells us
  3189. 2:19:48how many blocks we will have on the rows
  3190. 2:19:50and how many we will have on the columns
  3191. 2:19:52the grid you can see here which tells us
  3192. 2:19:54how many blocks we have is a tole that
  3193. 2:19:57accepts three values which tells how
  3194. 2:20:00many blocks we want on the X Dimension
  3195. 2:20:02how many we want on the Y Dimension and
  3196. 2:20:04how many we want on the Z Dimension we
  3197. 2:20:07are not going to use the Z Dimension
  3198. 2:20:09because we only have a matrix then
  3199. 2:20:11inside of each block how many threads we
  3200. 2:20:13want for the X Dimension and for the Y
  3201. 2:20:16Dimension as the X Dimension we have
  3202. 2:20:19chosen The Columns so we are saying how
  3203. 2:20:21many blocks we want the columns and how
  3204. 2:20:23many blocks we want for the rows and
  3205. 2:20:25then inside of each block how many
  3206. 2:20:27threads we want for the column block and
  3207. 2:20:29how many threads we want for the row
  3208. 2:20:31block this will Define our launch grid
  3209. 2:20:34and what Cuda will do it will just
  3210. 2:20:36launch this following configuration so
  3211. 2:20:38it will launch as many blocks as there
  3212. 2:20:40are combinations of X and y's and inside
  3213. 2:20:42of each X and Y it will assign a thread
  3214. 2:20:45ID in such a way that the thread zero on
  3215. 2:20:49the X axxis is uh so there will be two
  3216. 2:20:52threads on the x- axis and two threads
  3217. 2:20:54on the y- axis of each block now let's
  3218. 2:20:57try to understand how to map just based
  3219. 2:20:59on the block ID on the x- axis just
  3220. 2:21:02based on the block ID on the y axis and
  3221. 2:21:05the thread ID on the X and y- axis how
  3222. 2:21:07to map it to the one element of the
  3223. 2:21:10output
  3224. 2:21:11Matrix uh let's look at the code so
  3225. 2:21:14first we can use the following formula
  3226. 2:21:16to identify which row this element
  3227. 2:21:18should work with uh which which uh the
  3228. 2:21:22uh which because each element of a
  3229. 2:21:24matrix is identified by two in this say
  3230. 2:21:26one is the row identifier and one is the
  3231. 2:21:28column identifier the row identifier we
  3232. 2:21:31can look at it like the block ID
  3233. 2:21:34multiplied by the block size plus the
  3234. 2:21:35thread ID uh let's see why it makes
  3235. 2:21:38sense so in this case for example this
  3236. 2:21:41uh thread will work with the row zero
  3237. 2:21:44because the block ID is on the y- axis
  3238. 2:21:46is zero and the thread i z zero so it's
  3239. 2:21:49block ID multiplied by the block size so
  3240. 2:21:520 plus 0 it will be zero so this element
  3241. 2:21:55will be working with the row number zero
  3242. 2:21:58and which column it will be working with
  3243. 2:22:00well it will be working with the block
  3244. 2:22:02ID zero multiplied by the block size on
  3245. 2:22:05the column which is again zero I mean
  3246. 2:22:07the block size is two but multiply by Z
  3247. 2:22:10it will be zero plus the thread zero so
  3248. 2:22:12it will be zero this element here on the
  3249. 2:22:16here it will be the block ID of the Y y
  3250. 2:22:20AIS multiplied by the block size plus
  3251. 2:22:23the thread so it will be the element
  3252. 2:22:25zero on the row and for the columns it
  3253. 2:22:28will be the element one let's see
  3254. 2:22:30another one for example here uh for
  3255. 2:22:33example this element here so this um how
  3256. 2:22:37this uh thread will uh which element it
  3257. 2:22:40will work with well it will be the block
  3258. 2:22:42size on the Y AIS multiplied by the the
  3259. 2:22:45block ID on the y axis multiplied by the
  3260. 2:22:47block size so it will be 1 multiplied by
  3261. 2:22:50two so that will be our row so the row
  3262. 2:22:52number
  3263. 2:22:53two uh which makes sense because it's
  3264. 2:22:55the um this is the row zero this is the
  3265. 2:22:58row one and this is the row two and the
  3266. 2:23:01column will be the uh block ID on the x
  3267. 2:23:05axis which in this case it's equal to 1
  3268. 2:23:07multiplied by the block size which is
  3269. 2:23:09equal to two so 2 + 1 is equal to 3 so
  3270. 2:23:14this uh thread here will work with the
  3271. 2:23:16element number two three and this
  3272. 2:23:19formula now makes sense so this is how
  3273. 2:23:21we use the block ID and the thread ID
  3274. 2:23:24inside of each block to map it to which
  3275. 2:23:26element this particular thread should
  3276. 2:23:28work with so as I said before Cuda has
  3277. 2:23:31no notion of knowing which element this
  3278. 2:23:34particular thread should work with this
  3279. 2:23:35is up to us just based on the block ID
  3280. 2:23:38and the thread ID that CA
  3281. 2:23:41assigns then we make sure that the uh
  3282. 2:23:43row index is less than the number of row
  3283. 2:23:45and the column index is less than number
  3284. 2:23:46of columns why because as I said before
  3285. 2:23:49when we launch um blocks and threads
  3286. 2:23:52Cuda will round up that number to a
  3287. 2:23:54multiple of 32 in the case of the
  3288. 2:23:56threads so which means that some of
  3289. 2:23:58these threads should not work with any
  3290. 2:24:00data so we make sure that all the
  3291. 2:24:01threads that should not have the
  3292. 2:24:03corresponding element to work with they
  3293. 2:24:05should be just sit idle inside of this
  3294. 2:24:07if
  3295. 2:24:09statement but the one that have it they
  3296. 2:24:11should go enter and do some job so we
  3297. 2:24:13calculate the index of the element of
  3298. 2:24:17the Matrix that this particular thread
  3299. 2:24:20should work with as follows which is the
  3300. 2:24:22row index multiplied by the number of
  3301. 2:24:24columns plus the column index uh this is
  3302. 2:24:27just another way of
  3303. 2:24:29writing uh a uh or for example this is
  3304. 2:24:34just another way of writing a of row
  3305. 2:24:40index call index but the way we allocate
  3306. 2:24:44arrays in C or C++ is a flattened array
  3307. 2:24:49where all the rows are one after another
  3308. 2:24:51so we need to identify the element
  3309. 2:24:53inside of the array based on its row
  3310. 2:24:56index and column index and this is the
  3311. 2:24:58formula that we use to identify it if
  3312. 2:25:00you have never worked with um uh arrays
  3313. 2:25:04in C++ or C then it doesn't matter
  3314. 2:25:07because later we will see tensor layouts
  3315. 2:25:09and this will be much more clear but if
  3316. 2:25:12you have already worked with then you
  3317. 2:25:13already know how to uh index an element
  3318. 2:25:15inside of a multi-dimensional array in
  3319. 2:25:18C++ and then we compute the output as uh
  3320. 2:25:21as usual so I know that this has been a
  3321. 2:25:24lot of information so what should we
  3322. 2:25:26should we remember from this the first
  3323. 2:25:28thing that we should remember is that we
  3324. 2:25:30decide how to divide the work on
  3325. 2:25:32whatever Matrix we are working with or
  3326. 2:25:34whatever thread we are working whatever
  3327. 2:25:36Vector we are working with we tell Cuda
  3328. 2:25:38how many blocks we want and we tell Cuda
  3329. 2:25:40how many threads we want in each block
  3330. 2:25:43based on the identifier of the block ID
  3331. 2:25:45and the thread ID we should come up with
  3332. 2:25:48a strategy on how to map it to a subunit
  3333. 2:25:50of work so which part of the Matrix or
  3334. 2:25:53which part of the vector that particular
  3335. 2:25:55thread should work with um now the next
  3336. 2:25:59step for us is to understand the tensor
  3337. 2:26:01layouts because we are going to work
  3338. 2:26:03with the tensors and we need to
  3339. 2:26:05understand how the tensors are lay out
  3340. 2:26:07in the memory of the GPU or in the CPU
  3341. 2:26:11as well actually so we need to
  3342. 2:26:13understand what is the row column row
  3343. 2:26:14major layout and the column major layout
  3344. 2:26:17what is the stride Etc and convert all
  3345. 2:26:19the knowledge that we have about Cuda
  3346. 2:26:21into Triton so that we can then code
  3347. 2:26:23with Triton our kernel so let's
  3348. 2:26:27go all right guys finally it's time for
  3349. 2:26:30us to explore tensor layouts now why do
  3350. 2:26:33we need to explore tensor layouts
  3351. 2:26:36because before we we have seen some
  3352. 2:26:38examples of Cuda kernels and when you
  3353. 2:26:41give a matrix to Cuda or to a Cuda Kel
  3354. 2:26:44or a vector to Cuda kernel Cuda will not
  3355. 2:26:47give you will not give you the entire
  3356. 2:26:49metrix like like in Python where you can
  3357. 2:26:51access each element by its index Cuda
  3358. 2:26:54will just give you a pointer a pointer
  3359. 2:26:56to the starting element of that
  3360. 2:26:58particular Matrix or the starting
  3361. 2:27:00element of that particular Vector then
  3362. 2:27:03it's up to you to calculate the memory
  3363. 2:27:05address of all the remaining elements so
  3364. 2:27:07suppose that we have a simple Vector in
  3365. 2:27:10py torch this simple Vector could be the
  3366. 2:27:13following which is a vector of shape
  3367. 2:27:16seven because it's a tensor with only
  3368. 2:27:18one dimension with shape seven which is
  3369. 2:27:20the number of elements in the First
  3370. 2:27:22Dimension uh for now ignore this
  3371. 2:27:24property called the slide and later I
  3372. 2:27:26will explain it what is it uh how this
  3373. 2:27:29tensor will be saved in the memory of
  3374. 2:27:31the CPU or in the GPU it will be saved
  3375. 2:27:34as follows suppose that the starting
  3376. 2:27:36address of the first element is the
  3377. 2:27:38address 100 and suppose that each
  3378. 2:27:41element is made up of a floating point
  3379. 2:27:43of 16 bit so it means that each element
  3380. 2:27:45will occupy two bytes so the start
  3381. 2:27:48address of the second element will be
  3382. 2:27:50the address 102 and the third element
  3383. 2:27:52will be 104 and the fourth element will
  3384. 2:27:55be 106 etc etc etc so uh this is exactly
  3385. 2:28:00what you get when you in see you get um
  3386. 2:28:02you allocate a vector or a matrix with
  3387. 2:28:05Malo so when you allocate in C um vector
  3388. 2:28:09or a memory with maloc C or the memory
  3389. 2:28:12allocator will just allocate enough
  3390. 2:28:15memory to store all the elements and it
  3391. 2:28:16will give you a pointer to the start
  3392. 2:28:18address of this memory then it's up to
  3393. 2:28:21you to understand where each of this
  3394. 2:28:23element is stored in that block of
  3395. 2:28:24memory and this is to to do this we
  3396. 2:28:28introduce a property called stride The
  3397. 2:28:30Stride tells us how many elements we
  3398. 2:28:33need to skip to arrive to the next
  3399. 2:28:35element in the particular dimension in
  3400. 2:28:38this case for example in the case of a
  3401. 2:28:40vector we only have one dimension which
  3402. 2:28:42is the X
  3403. 2:28:43Dimension uh or the columns Dimension
  3404. 2:28:46you can think of it so this is the first
  3405. 2:28:48column this is the second the third the
  3406. 2:28:49fourth fifth etc etc um so in order to
  3407. 2:28:53arrive from one element to the next we
  3408. 2:28:54just need to skip one element so to go
  3409. 2:28:57from here we need to just increase our
  3410. 2:28:59pointer by one element and then to go
  3411. 2:29:01here we need to increase again pointer
  3412. 2:29:02by one element Etc this allow us to do a
  3413. 2:29:05for loop on this tensor let's look at a
  3414. 2:29:09more complicated case like the Matrix so
  3415. 2:29:12the Matrix is
  3416. 2:29:13two-dimensional and suppose we have the
  3417. 2:29:15following Matrix which is made up of six
  3418. 2:29:17element with two rows and three Colum
  3419. 2:29:20columns so the shape of this tensor will
  3420. 2:29:22be 2x3 because it we have two rows and
  3421. 2:29:25three columns uh how this Matrix will be
  3422. 2:29:28saved in the memory in the memory it
  3423. 2:29:31will be just a
  3424. 2:29:33flattened um Matrix it means and this is
  3425. 2:29:36called the row major layout but there is
  3426. 2:29:38also another one called column major
  3427. 2:29:40layout that we will not be discussing so
  3428. 2:29:43how it will be stored in the memory is
  3429. 2:29:45as follows it will be the first elements
  3430. 2:29:47of the first row so the elements of the
  3431. 2:29:50the first row followed immediately by
  3432. 2:29:52the elements of the second row so that
  3433. 2:29:55the memory address imagine with this is
  3434. 2:29:57the memory address of the first element
  3435. 2:29:58is 62 to go to the next element we need
  3436. 2:30:01to increase the memory address by the
  3437. 2:30:03number of bytes that each element
  3438. 2:30:05occupies which is two bytes so the the
  3439. 2:30:08address of the second element will be 64
  3440. 2:30:11the third element will be 66 and the
  3441. 2:30:13next row will start immediately after
  3442. 2:30:15the end of the first
  3443. 2:30:17row let's introduce this property stri
  3444. 2:30:20so the stride is what the stride tells
  3445. 2:30:22us how many elements you need to skip in
  3446. 2:30:24each Dimension to arrive to the next
  3447. 2:30:26element of that dimension for example
  3448. 2:30:29imagine we want to um uh address um we
  3449. 2:30:33want to get the element so all the
  3450. 2:30:35elements of the first
  3451. 2:30:36row um so let's call this tensor here
  3452. 2:30:40let's call it t so T of zero and um this
  3453. 2:30:47basically this indexing here says give
  3454. 2:30:49me all the elements of the first row so
  3455. 2:30:52in the first row select the all only the
  3456. 2:30:54first row and give me all the elements
  3457. 2:30:55of that row how to how does this
  3458. 2:30:58indexing work well by starting from the
  3459. 2:31:01pointer to the first element it will
  3460. 2:31:04select only the first row and then it
  3461. 2:31:08will move the the index here one element
  3462. 2:31:12after another so it will select the
  3463. 2:31:14first one the second one the third one
  3464. 2:31:16how does it know that it needs to move
  3465. 2:31:17one element by one element because in in
  3466. 2:31:20this Dimension the stride is one so the
  3467. 2:31:22stride tells us how many elements you
  3468. 2:31:24need to skip to arrive to the next
  3469. 2:31:26element in that Dimension imagine now
  3470. 2:31:29that we want to uh get the T of let's
  3471. 2:31:32say zero and
  3472. 2:31:35one well in this case the T let's say t
  3473. 2:31:38of one actually and all the elements of
  3474. 2:31:41the first row it will first of all it
  3475. 2:31:44needs to skip some elements from the
  3476. 2:31:47first First Dimension it needs to skip
  3477. 2:31:49the element zero because we don't we are
  3478. 2:31:50not selecting it we only want to select
  3479. 2:31:52the element one of the First Dimension
  3480. 2:31:55which basically means the row with index
  3481. 2:31:57one so because it will start from the
  3482. 2:32:00first pointer to the first element it
  3483. 2:32:03will it needs to know how many elements
  3484. 2:32:05to skip and how many element to skip is
  3485. 2:32:07given by The Stride so the stride tells
  3486. 2:32:09us how many elements you need to skip to
  3487. 2:32:11arrive to the next element of the First
  3488. 2:32:12Dimension so in this case it will take
  3489. 2:32:15the pointer to the first element skip
  3490. 2:32:17three elements and it will be starting
  3491. 2:32:19with the second r go and then inside
  3492. 2:32:21this row it will go through the second
  3493. 2:32:23in the the the index of the second
  3494. 2:32:25dimension in which the stride is one so
  3495. 2:32:27it will just go one after another and it
  3496. 2:32:29will return only this part of the memory
  3497. 2:32:32so to rehearse the stride is just
  3498. 2:32:36a a number that tells us how many
  3499. 2:32:39elements you need to skip in each
  3500. 2:32:41Dimension to arrive to the next index in
  3501. 2:32:44that Dimension so it means that to go
  3502. 2:32:46from one row to the other we need to
  3503. 2:32:48skip three elements to go from one
  3504. 2:32:49column to the other we need to skip one
  3505. 2:32:52element um why is the stride useful well
  3506. 2:32:56the stride is useful because it allow us
  3507. 2:32:58to reshape tensors very easily and
  3508. 2:33:01without doing any computation let's see
  3509. 2:33:04um okay imagine we want to reshape a
  3510. 2:33:07matrix imagine initially the shape of
  3511. 2:33:09this Matrix is 2x3 so we have two row by
  3512. 2:33:12three columns and we have a stride
  3513. 2:33:14calculated as follow it means that to go
  3514. 2:33:16from one row to the other you need to
  3515. 2:33:17skip three elements and to go from one
  3516. 2:33:19column uh one row to the other you need
  3517. 2:33:20to skip three elements and to go from
  3518. 2:33:22one uh column to the next you need to uh
  3519. 2:33:25skip one element so you need to jump by
  3520. 2:33:27one element if we want to reshape it
  3521. 2:33:30into this shape so 3x two basically we
  3522. 2:33:33want to um have three rows and two
  3523. 2:33:37columns uh the the we can reshape it
  3524. 2:33:42without actually changing its memory
  3525. 2:33:45layout just by changing the stride
  3526. 2:33:48because look at this physical
  3527. 2:33:50configuration of the tensor and we can
  3528. 2:33:53access this same tensor as this shape or
  3529. 2:33:56as this shape exactly by using the same
  3530. 2:33:59physical view because to go from one row
  3531. 2:34:02to the next here the stride is three so
  3532. 2:34:05we need to skip three elements it means
  3533. 2:34:07that the starting address the starting
  3534. 2:34:09element of the second row is given by
  3535. 2:34:12the start point plus three elements so
  3536. 2:34:15exactly here the second row will start
  3537. 2:34:18and each element of the second row is
  3538. 2:34:21one after another because the stride of
  3539. 2:34:22the second dimension is one so you can
  3540. 2:34:26see that to get the second row we can
  3541. 2:34:28just start from here and then go one
  3542. 2:34:30after another and get all these elements
  3543. 2:34:33which is exactly the second row suppose
  3544. 2:34:35we want to obtain the second row of this
  3545. 2:34:37view here of this shape of this reshaped
  3546. 2:34:40Matrix how to do that let's look at the
  3547. 2:34:43stride the stri now is two in the row it
  3548. 2:34:46means that to go from one row to the
  3549. 2:34:47next we need to skip two elements so if
  3550. 2:34:50we want to select this row here we go
  3551. 2:34:52from the starting point of the uh memory
  3552. 2:34:55so this start pointer we skip um the
  3553. 2:34:59first two elements because the stride
  3554. 2:35:01says that to go from one row to the next
  3555. 2:35:03you need to skip two elements so we
  3556. 2:35:04arrive here and then we select exactly
  3557. 2:35:07two elements which are one after another
  3558. 2:35:09because the stride in the second
  3559. 2:35:10dimension is one so the um this stride
  3560. 2:35:15allow us to reshape the tensor without
  3561. 2:35:19changing the physical layout on how it
  3562. 2:35:21is stored in the memory
  3563. 2:35:24moreover The Stride also allow us to get
  3564. 2:35:27the transpose of a matrix without
  3565. 2:35:29changing the shape of how it is stored
  3566. 2:35:31in the memory so without changing the
  3567. 2:35:33arrangement of the elements in the
  3568. 2:35:34memory and this is very cool because we
  3569. 2:35:36can view the same Matrix as with without
  3570. 2:35:39the transpose and also the transpose
  3571. 2:35:41version of The Matrix without changing
  3572. 2:35:43anything in the memory so it comes for
  3573. 2:35:45free just by working with the index and
  3574. 2:35:47the stride so to trans The Matrix along
  3575. 2:35:50two Dimensions we just need to swap the
  3576. 2:35:52stride along this two Dimensions that we
  3577. 2:35:54want to transpose so in this case for
  3578. 2:35:56example imagine we want to get the
  3579. 2:35:57transpose of this Matrix we just need to
  3580. 2:36:00swap the strides so if we want to get
  3581. 2:36:02the second row of the transposed Matrix
  3582. 2:36:05how to get that well you we always have
  3583. 2:36:07the pointer to the first element where
  3584. 2:36:10the tensor is stored so at the beginning
  3585. 2:36:12of where the tensor is stored in the
  3586. 2:36:15memory and it says that in order to go
  3587. 2:36:18to from one row to the next we need to
  3588. 2:36:21skip one element which is correct
  3589. 2:36:25because as you can see the second
  3590. 2:36:26element is exactly the second element
  3591. 2:36:28also in the memory so we just Skip by
  3592. 2:36:31one and we get the starting point of the
  3593. 2:36:33second row and then to go from one
  3594. 2:36:36element to the next in within the same
  3595. 2:36:38row we need to skip three elements so
  3596. 2:36:41the second element of the second row
  3597. 2:36:44will be after three elements uh um after
  3598. 2:36:48the first element of the second row so
  3599. 2:36:49after two we need to skip three elements
  3600. 2:36:51so we skip this one we skip this one and
  3601. 2:36:53we arrive to this one eight which is
  3602. 2:36:55exactly the second column of the SE uh
  3603. 2:36:57of the second row so basically the the
  3604. 2:37:00the stride as you can see allow us to do
  3605. 2:37:02two things one is it allow us to reshape
  3606. 2:37:05the tensor without having to reallocate
  3607. 2:37:08it in another configuration in the
  3608. 2:37:10memory secondly it allow us to transpose
  3609. 2:37:13a matrix without having to rearrange the
  3610. 2:37:15elements in the memory which is great
  3611. 2:37:17because moving memory around is
  3612. 2:37:18expensive
  3613. 2:37:20uh and rearranging the memory is
  3614. 2:37:21expensive so that's it's great that this
  3615. 2:37:24this stuff comes for free
  3616. 2:37:26basically um another thing okay for
  3617. 2:37:29example do um if you try to you know
  3618. 2:37:32that in py torch there are two methods
  3619. 2:37:34to reshape a tensor one is called the
  3620. 2:37:36reshape method and one is called The
  3621. 2:37:38View method the after transposing a
  3622. 2:37:42matrix by swiping by swiping The Stride
  3623. 2:37:46of the two Dimensions that you want to
  3624. 2:37:48transpose you cannot reshape for free
  3625. 2:37:52the tensor anymore because um the tensor
  3626. 2:37:55basically what is the stride The Stride
  3627. 2:37:57how it is computed The Stride is just
  3628. 2:37:59the uh let me show you with a concrete
  3629. 2:38:03Example The Stride is just the product
  3630. 2:38:05of all the shape uh after um in the
  3631. 2:38:10future Dimensions so the stride of the
  3632. 2:38:13zero Dimension is just the product of
  3633. 2:38:16the elements in the shape of the future
  3634. 2:38:18Dimension so so the stride of zero is
  3635. 2:38:21just the product of all the shape
  3636. 2:38:23starting from the index number one uh
  3637. 2:38:26it's not easy to see with the two The
  3638. 2:38:27Matrix because we don't have enough
  3639. 2:38:28elements so let's do it with a three 3D
  3640. 2:38:31Matrix so this is a tensor with the
  3641. 2:38:33three dimensions so it is a shape of two
  3642. 2:38:364 three which means that we have two
  3643. 2:38:38matrices each Matrix is made up of four
  3644. 2:38:40rows and each M and three colums The
  3645. 2:38:44Stride is calculated as follows so the
  3646. 2:38:46zero Dimension stride is just the the
  3647. 2:38:49product of 4x3 and this three here comes
  3648. 2:38:53the with the product of just a three
  3649. 2:38:55with it with one because we don't have
  3650. 2:38:57any future dimension of the tree so when
  3651. 2:39:00we transpose this stri property is lost
  3652. 2:39:04and we cannot um after transposing this
  3653. 2:39:08matrix by swapping the strides we cannot
  3654. 2:39:10do further reshaping operations so
  3655. 2:39:13basically the the tensor is not log
  3656. 2:39:15contigous so this is a very Advanced
  3657. 2:39:18okay property if you it doesn't matter
  3658. 2:39:20if you know it or not but if you are
  3659. 2:39:22curious basically in a pytorch you
  3660. 2:39:24cannot um view a tensor after it has
  3661. 2:39:28been uh transposed because pytorch to
  3662. 2:39:31transpose a tensor will just swap the
  3663. 2:39:33two strides but it loses the stride
  3664. 2:39:35property which is basically the stride
  3665. 2:39:38will not be anymore the product of the
  3666. 2:39:40future shapes so this is not anym two
  3667. 2:39:45this should be two for example and this
  3668. 2:39:47should be one but after transposing this
  3669. 2:39:50property lost so you need to actually
  3670. 2:39:51reallocate the tensor if you want to
  3671. 2:39:54reshape it after it has been transposed
  3672. 2:39:56doesn't matter if you remember this it's
  3673. 2:39:58just a curiosity anyway so what is the
  3674. 2:40:01transpose what is the stride used for is
  3675. 2:40:03the St The Stride is used for two things
  3676. 2:40:05first of all it it is used to understand
  3677. 2:40:08how to Index this tensor so just by
  3678. 2:40:11having a pointer to the first to the
  3679. 2:40:13starting address of this tensor we can
  3680. 2:40:16Index this tensor however we like so we
  3681. 2:40:19we can access any row any column uh
  3682. 2:40:22moreover it allow us to reshape this
  3683. 2:40:25tensor for free so without rearranging
  3684. 2:40:27the elements inside the memory and third
  3685. 2:40:30it allow us to transpose the tensor
  3686. 2:40:33however we like just by swapping the
  3687. 2:40:34strides of two uh the two Dimensions
  3688. 2:40:37that we want to
  3689. 2:40:38transpose now that we have seen also how
  3690. 2:40:41the tensor is stored in the memory we
  3691. 2:40:43can finally go to see
  3692. 2:40:45Tron um and see some examples all all
  3693. 2:40:49right guys now that we have seen how uh
  3694. 2:40:52tensors work Tor leat Works how Cuda
  3695. 2:40:55works now we can see some examples of
  3696. 2:40:57Tron kernels to see how Triton differs
  3697. 2:41:00from Cuda now if you go on the Tron uh
  3698. 2:41:04Tron website you will find some
  3699. 2:41:06tutorials like in this section here and
  3700. 2:41:09Let's do let's work one tutorial
  3701. 2:41:11together to understand how Tron is
  3702. 2:41:13different from Cuda um so if you go to
  3703. 2:41:16the tutorial there are many examples so
  3704. 2:41:18first of all the code that I will be
  3705. 2:41:19coding for Flash attention is based on
  3706. 2:41:21this tutorial here fused attention that
  3707. 2:41:23you can see here but with some
  3708. 2:41:24modifications because I simplified the
  3709. 2:41:26code a lot I removed for example the fp8
  3710. 2:41:29implementation I also for example um
  3711. 2:41:32this code here on the fuse detention
  3712. 2:41:34only works in the backward pass only for
  3713. 2:41:36the causal attention while my code will
  3714. 2:41:38work for the causal and non-causal
  3715. 2:41:40attention uh the second another
  3716. 2:41:42modification I did is instead of using
  3717. 2:41:44the exponential two that they use here
  3718. 2:41:46to make things faster probably because
  3719. 2:41:48the exponential two is implemented uh
  3720. 2:41:50with a faster unit uh I I I use the the
  3721. 2:41:54original implementation of flash
  3722. 2:41:56attention which used the exponential
  3723. 2:41:57with the base e etc etc so I simplified
  3724. 2:42:01my code as much as possible to make it
  3725. 2:42:03simple to follow instead of making it
  3726. 2:42:04optimized so for sure my code will be
  3727. 2:42:07slower than the the fused attention that
  3728. 2:42:09you see here but mine should be more
  3729. 2:42:12comprehensible more easy to follow
  3730. 2:42:14anyway let's go to the vector addition
  3731. 2:42:16tutorial and if you go to the vector
  3732. 2:42:18addition tutorial there are some
  3733. 2:42:20examples on how to do a vector addition
  3734. 2:42:22with Tron uh this should allow you to
  3735. 2:42:24get into the mindset of how to write
  3736. 2:42:26kernels with Tron uh instead of writing
  3737. 2:42:29first the the kernel and then calling it
  3738. 2:42:32let's do the opposite so let's see how
  3739. 2:42:33to call this kernel and let's explore
  3740. 2:42:35how it works so I have already copied
  3741. 2:42:38the tutorial vector addition from the
  3742. 2:42:40website so let's look at first of all
  3743. 2:42:43what we want to achieve we have an input
  3744. 2:42:46Vector X and an input Vector y and we
  3745. 2:42:49want to compute the vector addition
  3746. 2:42:50which means that with the torch we want
  3747. 2:42:52to do the following operation and also
  3748. 2:42:54we want to do the same operation also
  3749. 2:42:56with the Triton by calling this method
  3750. 2:42:58add and then we want to compare the two
  3751. 2:43:00vectors output and they should be equal
  3752. 2:43:03or at least their difference should be
  3753. 2:43:04very very small because of course there
  3754. 2:43:06is always some rounding error in case
  3755. 2:43:08you are working with floating Point
  3756. 2:43:09numbers the size of this Vector is
  3757. 2:43:1298,000 elements and um we want to work
  3758. 2:43:16in a blocked way so as you remember
  3759. 2:43:18before with the Cuda you can do vector
  3760. 2:43:21addition by spawning a lot of number of
  3761. 2:43:24threads each doing one operation but
  3762. 2:43:26when the number of threads that you have
  3763. 2:43:27is not enough then you need to divide
  3764. 2:43:30the input Vector into blocks and this is
  3765. 2:43:32what we are going to do here so let's
  3766. 2:43:33look at this add method so this add
  3767. 2:43:36method basically will first of all
  3768. 2:43:38allocate the necessary memory for the
  3769. 2:43:41output Vector then it will compute the
  3770. 2:43:45launch grid the launch grid tells Tron
  3771. 2:43:48just like in Cuda how many um kernels we
  3772. 2:43:51want to how many blocks we want to
  3773. 2:43:53launch how many blocks of threads we
  3774. 2:43:56want to launch uh if you remember in the
  3775. 2:43:59Cuda kernel we specify how many blocks
  3776. 2:44:02we want and then how many Treads we want
  3777. 2:44:04for each block in the case of uh
  3778. 2:44:07Triton we tell how many um blocks we
  3779. 2:44:11want and then we don't force how many
  3780. 2:44:14threads to launch it will be Tron that
  3781. 2:44:17will choose how many threads to Launch
  3782. 2:44:20um we just tell what each group of
  3783. 2:44:23threads should do so in this case for
  3784. 2:44:26example we divide our number of elements
  3785. 2:44:29so n so which is 98,000 into blocks of
  3786. 2:44:33size block size which is initialized as
  3787. 2:44:371224 this is basically saying take the
  3788. 2:44:41to calculate the grid size you do the
  3789. 2:44:43ceiling division so basically this means
  3790. 2:44:45ceiling of oh oops seal of n elements
  3791. 2:44:51divided by block size this is the
  3792. 2:44:54meaning of this one so how many blocks
  3793. 2:44:56we want now what each block should do is
  3794. 2:45:00inside of the kernel so let's go to the
  3795. 2:45:02kernel and when we launch the the kernel
  3796. 2:45:05we we can specify that the launch Grid
  3797. 2:45:07in this uh Square parenthesis and then
  3798. 2:45:09in the uh round parenthesis we specify
  3799. 2:45:11the arguments of this kernel so let's go
  3800. 2:45:14to the
  3801. 2:45:15kernel we see that python uh Tron will
  3802. 2:45:20not give us access to the tensor X it
  3803. 2:45:22will give us a pointer to the first
  3804. 2:45:25element of this tensor and this takes us
  3805. 2:45:27back to the tensor layouts so the reason
  3806. 2:45:30we studied the tensor layouts and the
  3807. 2:45:32strides and all the stuff is because
  3808. 2:45:34Tron this code uh this add kernel will
  3809. 2:45:38run on the GPU and the GPU cannot um
  3810. 2:45:42does not index tensors like P torch by
  3811. 2:45:45using all the dimension and with the uh
  3812. 2:45:48broadcast casting and all this fancy
  3813. 2:45:50stuff the GPU will just give you the
  3814. 2:45:52pointer to the first element of this
  3815. 2:45:54tensor in the memory and then it's up to
  3816. 2:45:56you to compute all the indexes of all
  3817. 2:45:59the elements that you want to access so
  3818. 2:46:02this x PTR is the pointer to the first
  3819. 2:46:04element of the X Vector this y pointer
  3820. 2:46:08is the first the pointer to the first
  3821. 2:46:10element of the Y uh Vector then we have
  3822. 2:46:13the pointer to the output Vector where
  3823. 2:46:15we want to store the result of this
  3824. 2:46:17Matrix addition we specify how many many
  3825. 2:46:19elements our vectors have and what is
  3826. 2:46:21the block size so how many uh items each
  3827. 2:46:25block should process which may not
  3828. 2:46:28correspond to how many threads each um
  3829. 2:46:31each kernel will
  3830. 2:46:33have you may be confused because okay uh
  3831. 2:46:36in Tron in Cuda we specified how many
  3832. 2:46:40threads each um block should have so the
  3833. 2:46:44granularity that we manage is the thread
  3834. 2:46:45level here we are saying it's a group of
  3835. 2:46:48thread that should work with this
  3836. 2:46:50quantity of data then it's up to Tron to
  3837. 2:46:53optimize the number of threads that it
  3838. 2:46:56will actually use actually there are
  3839. 2:46:57tricks there there are ways to say how
  3840. 2:46:59many threads we actually want by
  3841. 2:47:00specifying the number of wordss but we
  3842. 2:47:02will see that later for now just
  3843. 2:47:04remember that this thread this Kel here
  3844. 2:47:07will process a number of elements in the
  3845. 2:47:10input vectors how many number how many
  3846. 2:47:13elements block size number of elements
  3847. 2:47:16first of all we need to identify which
  3848. 2:47:18block we are um we are in Cuda we use
  3849. 2:47:23the the variable called block ID dox to
  3850. 2:47:26identify the identifier of the block
  3851. 2:47:28which tells us which group of elements
  3852. 2:47:30we should be working with in Tryon you
  3853. 2:47:33do the same by using program ID and in
  3854. 2:47:37uh Cuda the block ID can be along the X
  3855. 2:47:40Y and Z axis in Tron these are called
  3856. 2:47:43the dimension zero one and two uh two
  3857. 2:47:46here we have onedimensional data so we
  3858. 2:47:48only use one AIS to specify the block
  3859. 2:47:51index so we get the block index which is
  3860. 2:47:54the P ID in this the Tron this called
  3861. 2:47:57the program ID it's more intuitive to
  3862. 2:48:00think of as the program like this is a
  3863. 2:48:03kind of a program that is running in par
  3864. 2:48:05with other programs that will have
  3865. 2:48:06different program ID and based on the
  3866. 2:48:09program ID we can understand what is the
  3867. 2:48:11starting element this program should
  3868. 2:48:13work with so this blue block of threads
  3869. 2:48:16should work with and to get that is just
  3870. 2:48:18the P ID multiplied by the block size so
  3871. 2:48:20the p 0 should be working with the
  3872. 2:48:23elements that starts from the element
  3873. 2:48:24zero the P id1 should start with the
  3874. 2:48:27element 1024 and the P2 should start
  3875. 2:48:30from the element 248 so it should skip
  3876. 2:48:33the first 248 elements and starts with
  3877. 2:48:35the element with index
  3878. 2:48:382048 next we Define how to load these
  3879. 2:48:41elements based on the
  3880. 2:48:44pointer in which of the X and the Y uh
  3881. 2:48:48vector
  3882. 2:48:49to do that we specify a list of offsets
  3883. 2:48:54with respect to the starting address
  3884. 2:48:56that we want to load so because each
  3885. 2:48:58program in Tron works with a group of uh
  3886. 2:49:02um of data so not one single element but
  3887. 2:49:05a block of elements we we need to
  3888. 2:49:08understand which elements to load so the
  3889. 2:49:10offset of this elements in the case of
  3890. 2:49:12the program ID zero it will load the
  3891. 2:49:14block start so zero plus the elements
  3892. 2:49:17from index 0 to 100
  3893. 2:49:211,424
  3894. 2:49:23excluded with the program element
  3895. 2:49:26um one this basically will result in a
  3896. 2:49:30vector that is uh well the program start
  3897. 2:49:34with PID equal to 1 will be24 then
  3898. 2:49:371025
  3899. 2:49:391,26 1027 etc etc until
  3900. 2:49:452047 um with the program number let's
  3901. 2:49:48say
  3902. 2:49:49two this uh this offsets will be the
  3903. 2:49:52elements
  3904. 2:49:54248
  3905. 2:49:56249 blah blah blah until 3,000 and
  3906. 2:50:00something um now we also as you remember
  3907. 2:50:04when we create
  3908. 2:50:06um when we launch a grid the number of
  3909. 2:50:10threads is not always based on the
  3910. 2:50:13number of elements in the block or the
  3911. 2:50:15number of elements in your vector it is
  3912. 2:50:17always a multiple of a base number which
  3913. 2:50:19is usually 32 which means that the grid
  3914. 2:50:23this program may have more threads that
  3915. 2:50:25it needs so some threads should not be
  3916. 2:50:28doing anything so should not be loading
  3917. 2:50:31any data and should not be Computing any
  3918. 2:50:32summation so what we this is what why we
  3919. 2:50:35need this mask this means that if um all
  3920. 2:50:39these offsets that we are loading should
  3921. 2:50:41be at most up to n elements because
  3922. 2:50:44imagine you have not 1 2,000 imagine you
  3923. 2:50:48have Vector of
  3924. 2:50:51260 Elements which means that this
  3925. 2:50:55offset for um the the third program of
  3926. 2:50:59this kernel will load the offset that go
  3927. 2:51:02from
  3928. 2:51:032048 2049 blah blah blah 20 60 and then
  3929. 2:51:07also 2061 2062 etc etc but we said that
  3930. 2:51:12we only have 260 elements so all the
  3931. 2:51:15elements 261 62 Etc until 300 and
  3932. 2:51:18something they don't exist so we need to
  3933. 2:51:21tell somehow that all the threads that
  3934. 2:51:24are working with this elements should
  3935. 2:51:26not load anything that's why we need
  3936. 2:51:28this mask this mask tells load among all
  3937. 2:51:32the offsets that this block should work
  3938. 2:51:34with only those elements that actually
  3939. 2:51:37exist for which this mask is true then
  3940. 2:51:41we load the elements of this current
  3941. 2:51:43program which is a group of elements
  3942. 2:51:46defined by these offsets
  3943. 2:51:49and only the one that for which this
  3944. 2:51:51mask is true so only the one that
  3945. 2:51:53actually exist all the other should be
  3946. 2:51:55ignored and we can also specify what it
  3947. 2:51:57should load in case this um the mask is
  3948. 2:52:01false um with another parameter but we
  3949. 2:52:04will not seeing that here we also load
  3950. 2:52:06the group of elements of the Y vector
  3951. 2:52:09and then we compute the output x + y so
  3952. 2:52:12if you remember previously in Cuda we we
  3953. 2:52:15did something like this like the output
  3954. 2:52:18of I is equal to the x of I plus the Y
  3955. 2:52:22of I so we did it one element at the
  3956. 2:52:25time because each thread was working
  3957. 2:52:27with one index here we are working with
  3958. 2:52:29a group of elements so this x is a group
  3959. 2:52:32of elements is a block of elements at
  3960. 2:52:35most of size block
  3961. 2:52:37size actually of size block size and
  3962. 2:52:41it's this Y is a group of elements from
  3963. 2:52:44the Y vector and we are Computing the
  3964. 2:52:47output
  3965. 2:52:48Group by group so this this is summing a
  3966. 2:52:51group of elements of X with the
  3967. 2:52:54corresponding group in y and writing it
  3968. 2:52:56in output then we need to restore this
  3969. 2:53:00output we need to store it in the output
  3970. 2:53:02tensor output PTR that you can see here
  3971. 2:53:05which is a pointer to the first element
  3972. 2:53:07of the output vector and we say that
  3973. 2:53:10where should we store this output Vector
  3974. 2:53:12which is of size shape of this Vector
  3975. 2:53:15here is block size where should we save
  3976. 2:53:18it well in the same offset to where
  3977. 2:53:21which we loaded X so if this uh program
  3978. 2:53:25work with the index 2048 2049 etc etc
  3979. 2:53:28then all this output should be written
  3980. 2:53:31in the same offset uh 2048 2049 Etc up
  3981. 2:53:35to 3,000 and something using the mask as
  3982. 2:53:38well because we don't want to write all
  3983. 2:53:40the values of this block size because
  3984. 2:53:42maybe we don't have enough elements so
  3985. 2:53:44only write the one that are actually
  3986. 2:53:46present in the vector so the reason we
  3987. 2:53:49need this mask is because Cuda will
  3988. 2:53:51launch a number of thread that is always
  3989. 2:53:52a multiple of a base unit that may not
  3990. 2:53:54be a a multiple of the vector size that
  3991. 2:53:58we are working with so we need to find a
  3992. 2:54:00way to tell some threads to not do
  3993. 2:54:02anything for those that the data is not
  3994. 2:54:05avilable so let's rehearse what you have
  3995. 2:54:07seen so far in Cuda the program that we
  3996. 2:54:10write is at the thread level so each
  3997. 2:54:12thread what it should do in Tron it's a
  3998. 2:54:15this block of data we work with a block
  3999. 2:54:19of threads what data this block of
  4000. 2:54:22thread should work
  4001. 2:54:25with all right guys the final finally
  4002. 2:54:28the moment has come so uh we are going
  4003. 2:54:31to quote the flashh attention for our
  4004. 2:54:33pass right now in Tron but let's
  4005. 2:54:35rehearse the algorithm so the goal of
  4006. 2:54:38the attention mechanism in specifically
  4007. 2:54:40in Triton uh in flesh attention is to
  4008. 2:54:43compute the attention output which is we
  4009. 2:54:45want to compute the output of the
  4010. 2:54:47following formula so the query
  4011. 2:54:48multiplied by the transpose of the key
  4012. 2:54:50divide by the square root of the head
  4013. 2:54:51Dimension all multiply we apply the soft
  4014. 2:54:54Max and then all um multiplied by
  4015. 2:54:57V now um we in this video we will be
  4016. 2:55:01coding the forward pass and also the
  4017. 2:55:04backward pass but before coding the
  4018. 2:55:06backward pass we need to understand how
  4019. 2:55:08the autograd works we need to understand
  4020. 2:55:10what is the gradient what is the
  4021. 2:55:12Jacobian how to derive the gradient of
  4022. 2:55:14the softmax operation how to derive the
  4023. 2:55:16gradient of the matrix multiplication
  4024. 2:55:18operation etc etc so that is going to be
  4025. 2:55:20another part of the video for now let's
  4026. 2:55:22concentrate on the forward pass right
  4027. 2:55:24now we have some tools so we know that
  4028. 2:55:27we have this thing called the GPU that
  4029. 2:55:28can parallelize operation among multiple
  4030. 2:55:30cores we know that in Cuda we can
  4031. 2:55:32parallelize operations by telling by
  4032. 2:55:35writing a program that is the definition
  4033. 2:55:37of what each thread should do or we can
  4034. 2:55:40follow the Tron programming mode which
  4035. 2:55:42is telling in Python what each group of
  4036. 2:55:46threads should do
  4037. 2:55:48the mapping between the what each thread
  4038. 2:55:51should do and the which element that
  4039. 2:55:54should thread work with is up to us to
  4040. 2:55:56the programmers and the same happens in
  4041. 2:55:59Tron we tell we how many blocks of
  4042. 2:56:02threads we want how much data each
  4043. 2:56:05thread should block of thread should
  4044. 2:56:08process so that's the block size that we
  4045. 2:56:10saw in the vector addition but then the
  4046. 2:56:13mapping between the elements of the
  4047. 2:56:15vector and the um the the identity of
  4048. 2:56:19each group of threads so the program ID
  4049. 2:56:21that we saw is up to us and the same
  4050. 2:56:25will happen when we recode flashh
  4051. 2:56:27attention let's see what can we par
  4052. 2:56:29parallelize in this flashh attention so
  4053. 2:56:31first of all this code that you see the
  4054. 2:56:34forward pass of the flashh attention is
  4055. 2:56:37takes as input query key and value that
  4056. 2:56:40is a vector that is a matrices of n by D
  4057. 2:56:45however usually in a Transformer Network
  4058. 2:56:48we don't have only one sequence made up
  4059. 2:56:51of D Dimensions we have many sequences
  4060. 2:56:54made up of D dimensions and this D is
  4061. 2:56:57the lower case D which is the the number
  4062. 2:57:00of Dimensions dedicated for each head
  4063. 2:57:02but we don't have only one head we have
  4064. 2:57:04multiple head so the algorithm that you
  4065. 2:57:07see here is what each head should work
  4066. 2:57:11so each uh head of each batch should do
  4067. 2:57:16moreover we have have seen before when
  4068. 2:57:19talking about block matrix
  4069. 2:57:20multiplication that we can parallelize
  4070. 2:57:22the computation of the output because
  4071. 2:57:24this output block here depends on the
  4072. 2:57:27query one and all the keys this one here
  4073. 2:57:29depends on the query group block of
  4074. 2:57:32query two with all the keys and this one
  4075. 2:57:34here is the query three with all the
  4076. 2:57:36keys Etc so because this one only
  4077. 2:57:39depends on query the group The Block
  4078. 2:57:41query one and this one only depends on
  4079. 2:57:43the Block query to they can work
  4080. 2:57:45independently from each other by sharing
  4081. 2:57:47of course work the the
  4082. 2:57:50keys another thing that we need to
  4083. 2:57:52understand about a Tron is the shared
  4084. 2:57:54memory so um the in the GPU we have the
  4085. 2:58:00high bandwidth memory and which is the
  4086. 2:58:03like kind of the ram so the when you buy
  4087. 2:58:05an a100 they tell you that it has 4 40
  4088. 2:58:08GB that's the amount of memory in the
  4089. 2:58:10high bandwidth memory so the D Ram so
  4090. 2:58:13let's look at actually the structure of
  4091. 2:58:15the
  4092. 2:58:15GPU uh which is here we have this dram
  4093. 2:58:19which is the big memory uh that we that
  4094. 2:58:22the GPU has and then each um streaming
  4095. 2:58:26multiprocessor so it's a let's call it
  4096. 2:58:28BL block of threads uh actually also
  4097. 2:58:31have a shared memory so inside of the
  4098. 2:58:33GPU actually we have we have these
  4099. 2:58:35streaming multiprocessors and these
  4100. 2:58:37streaming multiprocessors have a part of
  4101. 2:58:40memory called the shared memory which is
  4102. 2:58:41much smaller than the dram like much
  4103. 2:58:44much much smaller what changes between
  4104. 2:58:47these two mem
  4105. 2:58:48the access to the dram is very slow and
  4106. 2:58:51the access to the shared memory is very
  4107. 2:58:53very very fast so one thing that is
  4108. 2:58:56different between Cuda and Tron is that
  4109. 2:58:59whenever you load some information in
  4110. 2:59:01Cuda you are loading that information
  4111. 2:59:03directly from the global memory because
  4112. 2:59:05when we launch a Cuda kernel first of
  4113. 2:59:07all as you remember in my C C++ code we
  4114. 2:59:11first copy the tensors from or the
  4115. 2:59:13vectors from the CPU to the GPU and they
  4116. 2:59:16reside in the global memory of the GPU
  4117. 2:59:20then we load these elements directly
  4118. 2:59:22from the global memory but the access to
  4119. 2:59:24the global memory usually it's much much
  4120. 2:59:27much slower so what happens with the
  4121. 2:59:29flesh attention is that the flesh
  4122. 2:59:30attention computation in its the
  4123. 2:59:32attention computation in its naive
  4124. 2:59:34version the one that we can do with the
  4125. 2:59:36torch is very slow because access to the
  4126. 2:59:38global memory is very slow so we want to
  4127. 2:59:41use as much as possible the shared
  4128. 2:59:43memory so we want to reuse the elements
  4129. 2:59:46loaded from the global memory into the
  4130. 2:59:48shared memory so that we don't need to
  4131. 2:59:50access the global memory every time to
  4132. 2:59:51load elements from the vectors or the
  4133. 2:59:54matrices and um this is what happens
  4134. 2:59:56also in Tron so in Tryon whenever you
  4135. 2:59:58load some data you are copying the
  4136. 3:00:00information from the global memory to
  4137. 3:00:02the shared memory then whatever
  4138. 3:00:04operations that you're doing is done on
  4139. 3:00:06the shared memory and then when you
  4140. 3:00:08store the information you are copying
  4141. 3:00:10the data from the shared memory to the
  4142. 3:00:11global memory um this makes it much
  4143. 3:00:14faster so we always work with elements
  4144. 3:00:17that have been Lo in the shared memory
  4145. 3:00:20and this shared memory basically it's
  4146. 3:00:21shared for all the threads that belong
  4147. 3:00:24to the same uh block uh in Tron we have
  4148. 3:00:28an obstruction level that doesn't make
  4149. 3:00:30us work directly with the threads so we
  4150. 3:00:32always work with a group of threads that
  4151. 3:00:34belong to the same block that share this
  4152. 3:00:36shared memory so in Tron we are copying
  4153. 3:00:39information from the global memory to
  4154. 3:00:40the shared memory we do some operation
  4155. 3:00:42with it and then we store back to the
  4156. 3:00:43global memory and this is what we are
  4157. 3:00:45going to do with flash attention now
  4158. 3:00:47let's review the algorithm of Flesh
  4159. 3:00:49attention so in flesh attention we have
  4160. 3:00:51to go an out for Loop that is among all
  4161. 3:00:54the between all the keys and then an
  4162. 3:00:57inner loop that is sorry between all the
  4163. 3:00:59query blocks and then an inner loop that
  4164. 3:01:01is um through all the key
  4165. 3:01:04Block in the original flash attention
  4166. 3:01:07algorithm the flashh attention one the
  4167. 3:01:09outer block was on the keys and the
  4168. 3:01:11inner block was on the queries this made
  4169. 3:01:14it less parallelizable why because the
  4170. 3:01:17Outer Loop is on the queries and we have
  4171. 3:01:19seen before that the the output of this
  4172. 3:01:22um attention can be computed
  4173. 3:01:24independently for each block of queries
  4174. 3:01:27so it's much easier to parallelize so
  4175. 3:01:29this outer for Loop actually we don't
  4176. 3:01:30have to run a for Loop we just spawn
  4177. 3:01:32many kernels each working with one
  4178. 3:01:35iteration of this outer for Loop so each
  4179. 3:01:37working with a different query block of
  4180. 3:01:40this outer for Loop and the inner for
  4181. 3:01:43Loop is something that we have to
  4182. 3:01:44iterate through so each Trion kernel
  4183. 3:01:47will work with one query block and then
  4184. 3:01:51iterate through all the key blocks um
  4185. 3:01:54and inside of this key block we have
  4186. 3:01:56already seen the operations that we are
  4187. 3:01:58going to do which the we we we explored
  4188. 3:02:00before and at the end of this for Loop
  4189. 3:02:03we need to store back the output in the
  4190. 3:02:06high bandwidth
  4191. 3:02:08memory um and this is how it's going to
  4192. 3:02:11we are going to work another thing that
  4193. 3:02:13we should notice is that this s value
  4194. 3:02:16are n byd so as I said before but
  4195. 3:02:19usually in a um in
  4196. 3:02:22a Transformer model we don't have only
  4197. 3:02:25one sequence we have many sequences so
  4198. 3:02:27we can also parallelize on the number of
  4199. 3:02:29sequences that we have in the batch
  4200. 3:02:31because each batch can work
  4201. 3:02:32independently from each other and inside
  4202. 3:02:35each um and each head each sequence has
  4203. 3:02:38multiple heads so each head also can
  4204. 3:02:41work independently from each other
  4205. 3:02:42because that we know from the attention
  4206. 3:02:44is all un need paper that's what's the
  4207. 3:02:45meaning of head that's what's the
  4208. 3:02:47meaning of multi head attention so that
  4209. 3:02:49each head can compute the attention
  4210. 3:02:50independently from each other so we will
  4211. 3:02:52also parallelize along the head
  4212. 3:02:54Dimension and moreover if you look at
  4213. 3:02:57this definition of the query block we
  4214. 3:02:59can also split the query into blocks and
  4215. 3:03:01each query block can work independently
  4216. 3:03:03from the other query blocks by in
  4217. 3:03:05producing one output block this is how
  4218. 3:03:08we are going to parallelize so we are
  4219. 3:03:10going to parallelize each sequence in
  4220. 3:03:12the patch in inside of each sequence we
  4221. 3:03:14are going to paraliz each head and
  4222. 3:03:16inside of each head we are going to
  4223. 3:03:18paralyze each query block so how many
  4224. 3:03:21programs we we will have working in
  4225. 3:03:23parallel at most it will be uh the sequ
  4226. 3:03:27the number of batches so the bch the
  4227. 3:03:29number of sequences in the batch so the
  4228. 3:03:30batch
  4229. 3:03:31size it will be the batch
  4230. 3:03:34size multiplied by the number of
  4231. 3:03:40heads uh multiplied by the number of
  4232. 3:03:44blocks that we will divide the query
  4233. 3:03:46sequence into so let's call it the I
  4234. 3:03:49don't know block size
  4235. 3:03:51Q the block
  4236. 3:03:55size
  4237. 3:03:57Q all right now that we have seen this
  4238. 3:03:59one let's go actually code it
  4239. 3:04:03so I have already introduced a little
  4240. 3:04:05bit of the differences between my
  4241. 3:04:07implementation of The Flash attention
  4242. 3:04:08and the one that you can find on the
  4243. 3:04:10Tron documentation which is a first of
  4244. 3:04:12all I don't work with fp8 because I
  4245. 3:04:14believe this is unnecessary for our
  4246. 3:04:16explanation it's of course much faster
  4247. 3:04:18because the recent gpus also support
  4248. 3:04:21fb8 Second difference is that in the um
  4249. 3:04:25In the Flesh attention on the Triton
  4250. 3:04:28website the backward pass is only
  4251. 3:04:31implemented for the causal attention but
  4252. 3:04:32in my case I implement it for the causal
  4253. 3:04:34and the non-causal attention even if
  4254. 3:04:36it's slower and later I actually I want
  4255. 3:04:38to give you an exercise on how to
  4256. 3:04:39improve it um and the third difference
  4257. 3:04:43uh main difference is that I made make
  4258. 3:04:46explicit use of the soft Max scale so I
  4259. 3:04:50actually use the scale when needed
  4260. 3:04:53another difference is that in the online
  4261. 3:04:56uh Tron computation of The Flash
  4262. 3:04:58attention is this X is not really e to
  4263. 3:05:01the power of X but it's two to the power
  4264. 3:05:03of X and then they compensate it with by
  4265. 3:05:05by using the
  4266. 3:05:07logarithm however uh because probably
  4267. 3:05:10the implementation of two to the power
  4268. 3:05:12of X is faster than the e to the power
  4269. 3:05:14of X but in my case I retain the
  4270. 3:05:16original exponential because I want to
  4271. 3:05:18follow the original algorithm to make it
  4272. 3:05:20simpler to visualize the code along with
  4273. 3:05:23the algorithm as in the flash ration
  4274. 3:05:24paper
  4275. 3:05:27so uh I know I have created a lot of
  4276. 3:05:29hype so let's do it uh let's start by
  4277. 3:05:32creating a new um file let's call it
  4278. 3:05:36program. piy uh just like before when I
  4279. 3:05:38introduced Tron I will start by coding
  4280. 3:05:41first the code that will use our Kel and
  4281. 3:05:43then we code the Kel and we will only be
  4282. 3:05:45coding the forward P of the Kel
  4283. 3:05:48so let's start
  4284. 3:05:50by importing what we need to import
  4285. 3:05:52which is just the torch and the Triton
  4286. 3:05:55and secondly let's start by let me check
  4287. 3:05:58okay the co-pilot is already off so I
  4288. 3:06:00don't have to worry about that let's
  4289. 3:06:03start to implement the code that will
  4290. 3:06:05test our implementation of the Triton
  4291. 3:06:07and compare it with the naive
  4292. 3:06:08implementation of the attention
  4293. 3:06:10mechanism so we in uh we create our
  4294. 3:06:13query key and SE uh query key and value
  4295. 3:06:16sequence for test thing which is if you
  4296. 3:06:20remember it's query is the BET size it
  4297. 3:06:23has the dimension bet size because we
  4298. 3:06:24have a multiple
  4299. 3:06:26sequences each sequence has a number of
  4300. 3:06:28heads and it's made up of s tokens and
  4301. 3:06:32each token is identified by a head dim
  4302. 3:06:34number of
  4303. 3:06:35Dimensions uh if you in then this is
  4304. 3:06:39because we have already split each token
  4305. 3:06:42into smaller tokens each each with its
  4306. 3:06:45own head Dimension if you remove the N
  4307. 3:06:48heads Dimension then you put back you
  4308. 3:06:50concatenate all the dimensions of this
  4309. 3:06:52head
  4310. 3:06:53dim um we initialize the query key and
  4311. 3:06:56value sequence by using a normal
  4312. 3:06:58distribution this code I already took
  4313. 3:07:00from the tutorial of Tron so it's
  4314. 3:07:02nothing different and we require the
  4315. 3:07:05grad the gradient because we want to
  4316. 3:07:07compute the gradient with respect to
  4317. 3:07:08query key and value and um we will see
  4318. 3:07:10later why because because we want to
  4319. 3:07:12implement the back we want to test also
  4320. 3:07:13the backb pass even though we will not
  4321. 3:07:15be coding it now so the first thing that
  4322. 3:07:18we do is we Define our soft Max
  4323. 3:07:20scale which is as you remember the
  4324. 3:07:23formula is U query multiplied by the
  4325. 3:07:26transpose of the keys and then divided
  4326. 3:07:30by the square root of head
  4327. 3:07:34Dimension so DK or the DHE head sometime
  4328. 3:07:39it's called and then we need to so we
  4329. 3:07:41need to compute this one we can already
  4330. 3:07:43compute it it's this this is one over
  4331. 3:07:45the square root of the head dimension
  4332. 3:07:48um and then we also Define d o and later
  4333. 3:07:52we will see what is this but this is
  4334. 3:07:54basically we will be needed needed for
  4335. 3:07:56the backward
  4336. 3:08:00pass um don't worry if you don't
  4337. 3:08:03understand what is doo later we will see
  4338. 3:08:04it let's do the naive implementation of
  4339. 3:08:07the attention which is very simple which
  4340. 3:08:10is first we Define the mask and we use
  4341. 3:08:13this mask only if the attention we are
  4342. 3:08:15Computing is Cal so as you can see we
  4343. 3:08:17pass this parameter called causal that
  4344. 3:08:19tells if we want to compute the causal
  4345. 3:08:22attention or the not causal attention
  4346. 3:08:24and the D type which is float 16 because
  4347. 3:08:27we want to work directly with 16 bit
  4348. 3:08:30floating Point numbers we will not be
  4349. 3:08:32working with fp8 just because we we
  4350. 3:08:34don't we don't want to implement uh my
  4351. 3:08:36implementation is actually not as fast
  4352. 3:08:38as the one in the tutorial of the Tron
  4353. 3:08:40website but I believe it's much more
  4354. 3:08:43easier to
  4355. 3:08:44comprehend uh so we Define the mask
  4356. 3:08:48we compute the the the product query
  4357. 3:08:51multiply by the transpose of the key
  4358. 3:08:52divide by the square root of the head
  4359. 3:08:54Dimension so that's why we are
  4360. 3:08:55multiplying by Soft mask scale if the
  4361. 3:08:57attention we're Computing is Kaa then we
  4362. 3:08:59use this mask that we have computed so
  4363. 3:09:02we replace all the points all the dot
  4364. 3:09:05products where this mask is equal to
  4365. 3:09:07zero with minus Infinities and then the
  4366. 3:09:09soft mask will replace this minus
  4367. 3:09:10Infinities with zeros because then we
  4368. 3:09:13are applying the soft Max and the soft
  4369. 3:09:15Max is applied by rows just like the
  4370. 3:09:17normal attention we
  4371. 3:09:19compute okay the second thing that we do
  4372. 3:09:21is we want to um so the output is the
  4373. 3:09:25product of the output of the softmax
  4374. 3:09:27with the V so this is the reference
  4375. 3:09:29output on the naive implementation of um
  4376. 3:09:33flash of the attention mechanism then we
  4377. 3:09:36want to compute we want to also derive
  4378. 3:09:39the gradients of the output with respect
  4379. 3:09:42to the um
  4380. 3:09:44inputs and in this case it's the
  4381. 3:09:47the the V the K and the Q later we will
  4382. 3:09:51see what are we doing here then we want
  4383. 3:09:54also to we want to compare this
  4384. 3:09:56reference implementation with our Tron
  4385. 3:09:58implementation so let's do it so our
  4386. 3:10:01Tron implementation will be implemented
  4387. 3:10:02as a class called Tron attention that we
  4388. 3:10:06will call using this method called apply
  4389. 3:10:08and later we will see what is this
  4390. 3:10:09method in which we pass the query key
  4391. 3:10:11and value if we want to compute the Cal
  4392. 3:10:13attention the soft Mark scale that it
  4393. 3:10:15should be using and it should prod
  4394. 3:10:17produce some output which is the output
  4395. 3:10:19of the output of the softw multiplied by
  4396. 3:10:22V then we can run also the backward and
  4397. 3:10:24this backward will be the the the the
  4398. 3:10:26same backward that we will compute with
  4399. 3:10:28the um Tron
  4400. 3:10:30attention and then we
  4401. 3:10:33compare okay and then we can compare uh
  4402. 3:10:36the result of our implementation so this
  4403. 3:10:39Tron attention not apply with the
  4404. 3:10:41reference implementation which is this
  4405. 3:10:43one here and they should be uh we use
  4406. 3:10:46the the function all clause which
  4407. 3:10:48basically compares the elements of two
  4408. 3:10:50tensors and make sure that their
  4409. 3:10:52absolute difference is no more than this
  4410. 3:10:54one we are not using the relative
  4411. 3:10:56distance we are just using the absolute
  4412. 3:10:58distance between the two elements
  4413. 3:11:00corresponding elements of two vectors
  4414. 3:11:02this uh implementation that we have that
  4415. 3:11:05we will build will work with the causal
  4416. 3:11:06attention and also with not causal
  4417. 3:11:08attention while the the one that we saw
  4418. 3:11:10in the website of Tron it only works
  4419. 3:11:13with the uh the forward pass actually
  4420. 3:11:15works with the causal and non causal
  4421. 3:11:17while the backward pass only works in
  4422. 3:11:18the case of the Cal attention um okay
  4423. 3:11:22but it's highly optimized the one online
  4424. 3:11:24so if you want to learn a little more
  4425. 3:11:26tricks on how to optimize Triton kernels
  4426. 3:11:28there is a lot of knowledge there anyway
  4427. 3:11:30guys now let's try to uh implement this
  4428. 3:11:33Tron atten at least the forward pass so
  4429. 3:11:36let's go to implement this Triton
  4430. 3:11:38attention
  4431. 3:11:41class um okay here every time you want
  4432. 3:11:44to introduce a new operation into torch
  4433. 3:11:47you need to uh derive the um you need to
  4434. 3:11:51implement your operation by deriving
  4435. 3:11:53from this autograd do function class so
  4436. 3:11:56every operation in torch actually if
  4437. 3:11:58it's the soft Max or it's the I don't
  4438. 3:12:01know the the ru or the zgo or whatever
  4439. 3:12:04there is it is always implemented as a
  4440. 3:12:06as a function is a class that derives
  4441. 3:12:08from this function and it should provide
  4442. 3:12:10two method one called the forward pass
  4443. 3:12:12and one called the backward pass the
  4444. 3:12:14forward should produce the output of
  4445. 3:12:16this operation and the backward should
  4446. 3:12:17compute the
  4447. 3:12:19gradient um the gradient with of the
  4448. 3:12:22loss with respect to that the the input
  4449. 3:12:24of that function and later we will see
  4450. 3:12:26how that works for now let's concentrate
  4451. 3:12:28on the forward pass to implement the
  4452. 3:12:30forward pass we need to create a static
  4453. 3:12:32method that is called
  4454. 3:12:34forward which takes as input one thing
  4455. 3:12:38called the context so as you know in the
  4456. 3:12:40autograd in when training AAL networks
  4457. 3:12:43we have the forward pass and the
  4458. 3:12:44backward when Computing the backward
  4459. 3:12:46pass we need to reuse the activations of
  4460. 3:12:49each of the computation nodes during the
  4461. 3:12:51forward pass and this context basically
  4462. 3:12:53allow us to save the information to uh
  4463. 3:12:56for the necessary activations that we
  4464. 3:12:57will need during the backward pass and
  4465. 3:12:59later we will see in the tron um in the
  4466. 3:13:02flash attention algorithm what
  4467. 3:13:03information we need to save in order to
  4468. 3:13:06compute the backward pass for example
  4469. 3:13:08what we will need to save during the
  4470. 3:13:09backward pass we will need to recompute
  4471. 3:13:12on the Fly the soft the query multiply
  4472. 3:13:16by the transpose of the keys for each
  4473. 3:13:17block but we don't want to recompute the
  4474. 3:13:19normalization factor or the maximum
  4475. 3:13:21value for each row so we will save those
  4476. 3:13:23two values and actually we will not save
  4477. 3:13:26two values we will save one value with a
  4478. 3:13:27trick called The Log sum X log sum X
  4479. 3:13:30trick that we will see later anyway this
  4480. 3:13:33context is just a kind of a storage area
  4481. 3:13:36where we can save some stuff that will
  4482. 3:13:37be necessary for us to recompute the
  4483. 3:13:40backward and you can see whatever you
  4484. 3:13:42like then we have the input of this um
  4485. 3:13:45operation which is the query key and
  4486. 3:13:47value which is three tensors with the
  4487. 3:13:50Cal if we are going to compute the Cal
  4488. 3:13:52attention and the soft Mark scale that
  4489. 3:13:54we should apply based on the one over
  4490. 3:13:55the square root of the uh head
  4491. 3:13:59Dimension uh which we could also compute
  4492. 3:14:01it on the fly actually by the way by by
  4493. 3:14:03checking the shape of this but okay it
  4494. 3:14:05doesn't matter anyway so um the first
  4495. 3:14:08thing that we are going to do is to
  4496. 3:14:09extract the shapes of this objects and
  4497. 3:14:11make sure all the shapes are what we
  4498. 3:14:13expect them to be so the shape of the
  4499. 3:14:15query key and value is a bch size by
  4500. 3:14:18number of heads by sequence length by
  4501. 3:14:20head Dimension we make sure that the
  4502. 3:14:22head Dimension matches for the query key
  4503. 3:14:25and value uh they should match because
  4504. 3:14:28each Vector should should be of the same
  4505. 3:14:30size uh and then we declare what we
  4506. 3:14:34pre-allocate the output Vector so where
  4507. 3:14:37we should save our output so as you
  4508. 3:14:39remember the output in and the attention
  4509. 3:14:41mechanism has the same same shape as the
  4510. 3:14:44query key and value sequence where theer
  4511. 3:14:47Quan value sequence I want to remind you
  4512. 3:14:48is not the query value of the input of
  4513. 3:14:51the attention which is a sequence of
  4514. 3:14:53tokens but it's the output already of
  4515. 3:14:55the WQ WK and WV because flesh attention
  4516. 3:14:58is not concerned with optimizing those
  4517. 3:15:00metrix multiplication but only the
  4518. 3:15:02output of the WQ WK and
  4519. 3:15:05WB so we pre-allocate the output tensor
  4520. 3:15:08where we will store this output which
  4521. 3:15:10has the same shape as the query key and
  4522. 3:15:13sequence uh um Matrix
  4523. 3:15:17actually actually no not true actually
  4524. 3:15:20it has the same shape as the query but
  4525. 3:15:22it may not be the same as the key and
  4526. 3:15:24value why because there is this thing
  4527. 3:15:26called cross attention where the query
  4528. 3:15:29key and value are transposition are
  4529. 3:15:33different projection through WQ WK WV
  4530. 3:15:35not of the same input sequence but of
  4531. 3:15:37two sequence so cross attention happens
  4532. 3:15:40when we have a query that comes from one
  4533. 3:15:43uh sequence and the key and value come
  4534. 3:15:45from another sequence and they pass
  4535. 3:15:47through their own WK and WV and they may
  4536. 3:15:50not have the same sequence length so the
  4537. 3:15:52shapes of the output of the tension only
  4538. 3:15:54depends on the shape of the query
  4539. 3:15:55sequence not of the key and value
  4540. 3:15:58sequence this is happens during cross
  4541. 3:16:00attention but usually in language models
  4542. 3:16:02we always work with the self attention
  4543. 3:16:04so that should not happen um at least in
  4544. 3:16:07the Cal language models um then we have
  4545. 3:16:11um the stage and later we will see what
  4546. 3:16:13is this stage uh basically the stage
  4547. 3:16:15it's just a number that that tells if
  4548. 3:16:17the um operation that we are going to do
  4549. 3:16:20later is for the causal attention or for
  4550. 3:16:22the not causal attention and then we
  4551. 3:16:25need to La Define our launch grid the
  4552. 3:16:27launch grid tells us how many parallel
  4553. 3:16:30process we need to be launched by Tron
  4554. 3:16:33actually they will be launched by Cuda
  4555. 3:16:34but by we always work with the Triton as
  4556. 3:16:37an interface to Cuda so by
  4557. 3:16:40Triton so in Tron as I said before we
  4558. 3:16:43want to parallelize along the batch
  4559. 3:16:45Dimension so each batch each sequence in
  4560. 3:16:48the batch should work independently from
  4561. 3:16:50each other not only each inside of each
  4562. 3:16:53sequence in the batch each head should
  4563. 3:16:55work independently from each other so at
  4564. 3:16:57least we have a bch size multiplied by
  4565. 3:16:59number of heads
  4566. 3:17:02programs and for each of these program
  4567. 3:17:05we have another uh Dimension called the
  4568. 3:17:08we divide the query into blocks of
  4569. 3:17:11queries so um as you remember when
  4570. 3:17:15talking about a block matrix
  4571. 3:17:16multiplication we don't work with the
  4572. 3:17:17query as the original Matrix query
  4573. 3:17:19Matrix so where each query is one vector
  4574. 3:17:22or one token we work with group of
  4575. 3:17:25queries so each block of queries is a
  4576. 3:17:28group of tokens in the query
  4577. 3:17:30sequence so we are saying that we want
  4578. 3:17:33to launch at a number of um um kernels
  4579. 3:17:37or blocks of threads or a group of
  4580. 3:17:41threads along two Dimensions just like
  4581. 3:17:44the Cuda kernel can be launched along
  4582. 3:17:46Ong two Dimension X and Y here we are
  4583. 3:17:48launching programs along two Dimensions
  4584. 3:17:51one Dimensions that tells us which batch
  4585. 3:17:54which head of which batch we are going
  4586. 3:17:56to work with so which head of which uh
  4587. 3:18:00batch element are we going to work with
  4588. 3:18:05and inside this we are going to say okay
  4589. 3:18:08this is a sequence which group of
  4590. 3:18:11queries are we going to work
  4591. 3:18:15with are we going
  4592. 3:18:17to going to work with so overall and the
  4593. 3:18:23group of queries is what is the sequence
  4594. 3:18:25length divided by the number of queries
  4595. 3:18:28that we want to group together so the
  4596. 3:18:29block size Cube tells us how many
  4597. 3:18:31queries are there in each block of
  4598. 3:18:34queries so this CD is just the ceiling
  4599. 3:18:37division so it is equal to let me write
  4600. 3:18:39it here this is equal to ceiling of
  4601. 3:18:43sequence length divide by the block size
  4602. 3:18:46Q
  4603. 3:18:47this tells us uh how many blocks of Q we
  4604. 3:18:54have so let's rehearse we have a tensor
  4605. 3:18:58that is q that is B size by number of
  4606. 3:19:02heads and each flashh attention
  4607. 3:19:05algorithm will work with the following
  4608. 3:19:07the sequence length head Dimension
  4609. 3:19:09moreover we have seen that the flesh
  4610. 3:19:11attention has two Loops one is the outer
  4611. 3:19:14loop among all the query blocks one is
  4612. 3:19:16is the inner loop along all the key
  4613. 3:19:19block we have seen that the query block
  4614. 3:19:21can work independently from each other
  4615. 3:19:23so we can spawn as many programs in
  4616. 3:19:25parallel as there are number of blocks
  4617. 3:19:28of Q because they can work in parallel
  4618. 3:19:30so this grid tells us how many programs
  4619. 3:19:32there are that can work in parallel then
  4620. 3:19:34it will be the GPU that based on its
  4621. 3:19:36resources will decide how many program
  4622. 3:19:38actually to work in parallel if it has
  4623. 3:19:41enough resources to make them all work
  4624. 3:19:43in parallel wonderful if it doesn't have
  4625. 3:19:45enough resources to make them work in
  4626. 3:19:46par it will launch them sequentially one
  4627. 3:19:48after another and the last Dimension is
  4628. 3:19:51this is like the Z dimension in the
  4629. 3:19:55Cuda in the Cuda launch grid and we
  4630. 3:19:58don't want to use it because we don't
  4631. 3:19:59want an additional um level of
  4632. 3:20:03parallelism all right this is our launch
  4633. 3:20:05grid so we will launch a number of um
  4634. 3:20:09programs that is this one number of
  4635. 3:20:11programs of parallel programs or number
  4636. 3:20:14of parallel Kels and each kernel in Tron
  4637. 3:20:17work is a group of
  4638. 3:20:19threads which is a batch size multiplied
  4639. 3:20:23by number of
  4640. 3:20:25heads multiplied by number of blocks of
  4641. 3:20:29Q so how many blocks we have in we
  4642. 3:20:31divided the Q sequence
  4643. 3:20:34into okay let's continue so the we will
  4644. 3:20:38see what is this one so this m is
  4645. 3:20:41another Matrix that we will need and
  4646. 3:20:43it's the log sum Expo for the backward
  4647. 3:20:45pass and we will see at the end of this
  4648. 3:20:47video what it not at the end of this
  4649. 3:20:49video but at the end of the forward pass
  4650. 3:20:51what it's needed for but basically this
  4651. 3:20:53is you can think of it as the maximum
  4652. 3:20:56for each row um you we to to recompute
  4653. 3:21:00the query multiply by the key in the
  4654. 3:21:02backward pass we should also have if we
  4655. 3:21:04don't want to recompute the maximum for
  4656. 3:21:06hro and the normalization factor of the
  4657. 3:21:08softmax we should save two things one is
  4658. 3:21:10the maximum for each row and one is the
  4659. 3:21:14uh the normalization factor however by
  4660. 3:21:17using the log sum X trick we can only
  4661. 3:21:19save one value which is the as you can
  4662. 3:21:21see in the um algorithm of FL attention
  4663. 3:21:25it's this stuff here which is uh let's
  4664. 3:21:29see here it's this stuff here so this Li
  4665. 3:21:33which is the maximum for each row plus
  4666. 3:21:36the logarithm of the um of the
  4667. 3:21:40normalization
  4668. 3:21:41factor um and
  4669. 3:21:43basically in when Computing the back
  4670. 3:21:46pass we need to recompute on the Fly
  4671. 3:21:49this block here so the square multip by
  4672. 3:21:51the transpose of but to apply the soft
  4673. 3:21:52Max as you remember we need to have the
  4674. 3:21:54maximum for each row and the
  4675. 3:21:55normalization factor so uh we don't um
  4676. 3:21:59we don't recompute them during the
  4677. 3:22:00backward because we have already
  4678. 3:22:01computed them during the forward so we
  4679. 3:22:03save this information but we don't need
  4680. 3:22:04to save this two information separately
  4681. 3:22:06we can aggregate it into one single
  4682. 3:22:08value called Li and later we will see
  4683. 3:22:10how we can use
  4684. 3:22:12it all
  4685. 3:22:14right so we have defined find also this
  4686. 3:22:17one and we can proceed further so now we
  4687. 3:22:21launch our grid our
  4688. 3:22:24kernel don't be scared it's going to be
  4689. 3:22:26a little long so here so we are
  4690. 3:22:30launching the the kernel for the forward
  4691. 3:22:33pass by defining what is the launch grid
  4692. 3:22:36so how many of this program should run
  4693. 3:22:37in parallel at most we are passing the
  4694. 3:22:40query we are passing the key we are
  4695. 3:22:42passing the values we are passing the
  4696. 3:22:43soft Mark scale the M which is the
  4697. 3:22:46information that we need to save for the
  4698. 3:22:47backward pass it's actually the L in the
  4699. 3:22:51code of the pseo code of The Flash
  4700. 3:22:53attention algorithm here I call it m I
  4701. 3:22:56think because also in the original code
  4702. 3:22:58it was called
  4703. 3:22:59M um the O where the our kernel should
  4704. 3:23:03save its
  4705. 3:23:05output and then as you remember uh we
  4706. 3:23:08don't get all the nice access by um
  4707. 3:23:14indexing tensor like we are used to in
  4708. 3:23:16torch we only get a pointer to the
  4709. 3:23:19starting element of q a pointer to the
  4710. 3:23:21starting element of K and to the
  4711. 3:23:23starting element of v and then we have
  4712. 3:23:25to figure out all the index in the
  4713. 3:23:28memory of the other elements how to
  4714. 3:23:30calculate the index we need the stride
  4715. 3:23:33because the stride tells us how many
  4716. 3:23:35elements to skip to go from one
  4717. 3:23:37dimension to the other and that's why we
  4718. 3:23:39are passing the stride for each
  4719. 3:23:40dimension of each tensor actually in our
  4720. 3:23:43case uh we are only working with q k and
  4721. 3:23:47V that are actually of the same D type
  4722. 3:23:50and of the same shape so we should not
  4723. 3:23:52need actually to pass all all the stride
  4724. 3:23:55for each of these uh
  4725. 3:23:57tensors um because they should have the
  4726. 3:23:59same strides however in the original
  4727. 3:24:02code I believe they they were passing it
  4728. 3:24:03so I kept it so the stride allow will
  4729. 3:24:06allow us to index these pointers to
  4730. 3:24:10understand um to access the elements of
  4731. 3:24:14of this tensor just by using its
  4732. 3:24:16starting uh the pointer to the starting
  4733. 3:24:18element and then the strides we will be
  4734. 3:24:20able to index any element we want in the
  4735. 3:24:23tensor then we pass the information of
  4736. 3:24:26these shapes so the bch size the number
  4737. 3:24:28of heads the sequence length and the
  4738. 3:24:30head
  4739. 3:24:31Dimension and U which is the same for
  4740. 3:24:34all of them and then the stage the stage
  4741. 3:24:37indicates if we are going to compute
  4742. 3:24:38causal attention or not causal attention
  4743. 3:24:41so let's not implement it and let's
  4744. 3:24:43continue writing this method so the then
  4745. 3:24:46then we need to save some information
  4746. 3:24:48that we will be needed for the backward
  4747. 3:24:49pass which is this context variable that
  4748. 3:24:52I told you before so we save some
  4749. 3:24:54information for the backward pass which
  4750. 3:24:55is the query key and value uh which are
  4751. 3:24:58the tensor for which we want to compute
  4752. 3:25:00the gradient during the backward pass um
  4753. 3:25:03and then um um we need to store also
  4754. 3:25:07this m tensor and this o
  4755. 3:25:10tensor um then we can we need to also
  4756. 3:25:13store the causal uh variable so because
  4757. 3:25:16if if we computed the caal attention
  4758. 3:25:18during the for forward pass then during
  4759. 3:25:21the backward pass we need to um have
  4760. 3:25:23this information because we need to mask
  4761. 3:25:26out the things that we don't want to
  4762. 3:25:28contribute to the gradient but we will
  4763. 3:25:31see that later when Computing the
  4764. 3:25:32backward pass for now let's concentrate
  4765. 3:25:34on this attention
  4766. 3:25:35forward so we need to implement this
  4767. 3:25:38forward kernel that you can see so uh
  4768. 3:25:40underscore attention underscore forward
  4769. 3:25:42method now a Tron kernel is just a
  4770. 3:25:45python method with a particular
  4771. 3:25:47decorator called Tron go.get so we copy
  4772. 3:25:51and paste the signature so this is what
  4773. 3:25:54makes a method become a Tron kernel and
  4774. 3:25:58as you can see here we pass the query
  4775. 3:26:00key and value Matrix along with other
  4776. 3:26:02information the M Matrix please don't
  4777. 3:26:04confuse the M Matrix with the mask that
  4778. 3:26:07we will apply um uh on the Fly we will
  4779. 3:26:10generate it on the Fly because we are
  4780. 3:26:11only concerned in this case with a cal
  4781. 3:26:13attention or not causal attention we do
  4782. 3:26:16not accept custom masks
  4783. 3:26:18here um then we pass the strides of all
  4784. 3:26:21these tensors the B size the number
  4785. 3:26:24number of heads the sequence length the
  4786. 3:26:25head Dimension which is the shape of
  4787. 3:26:27each of these uh tensors um and the
  4788. 3:26:31block size Q and The Block size KV the
  4789. 3:26:33block size Q indicates how many queries
  4790. 3:26:36we want to group together to make one
  4791. 3:26:38block of the Q Matrix and how the KV
  4792. 3:26:41indicates how many keys and values we
  4793. 3:26:43want to put together to make one block
  4794. 3:26:45of the K and V Matrix which is what we
  4795. 3:26:49do when we do block matrix
  4796. 3:26:51multiplication this stage is a number
  4797. 3:26:53that indicates if it's a caal or um not
  4798. 3:26:56causal attention we are doing so it will
  4799. 3:26:58be three in case it's a caal and one in
  4800. 3:27:00case it's not
  4801. 3:27:01causal okay the first thing that we do
  4802. 3:27:03is to verify some information so we
  4803. 3:27:06verify that the um the block size of the
  4804. 3:27:10KV is less than or equal to the Head
  4805. 3:27:13Dimension to be honest I don't think we
  4806. 3:27:15need it with my code because I removed
  4807. 3:27:18most of the constraints so this uh this
  4808. 3:27:20check was also present in the original
  4809. 3:27:22code so I kept it but it all depends on
  4810. 3:27:24how we are later we will see what is the
  4811. 3:27:27autot tuning process and later we will
  4812. 3:27:28see uh what variables we are going to
  4813. 3:27:31autotune for and how many stages we will
  4814. 3:27:33choose how many warps we will choose etc
  4815. 3:27:35etc so let's leave it for later you can
  4816. 3:27:37comment it or you can keep it it
  4817. 3:27:39shouldn't
  4818. 3:27:40matter um the first thing that we do as
  4819. 3:27:42I said before we launch a grid so a grid
  4820. 3:27:46is a series of programs where we will
  4821. 3:27:48have some identifiers like in the coda
  4822. 3:27:50we had an identifier for the blocks on
  4823. 3:27:52the x axis and on the y axis in Tron we
  4824. 3:27:55get this identifier for the programs we
  4825. 3:27:59launched um
  4826. 3:28:02um uh sequence length divide by block
  4827. 3:28:05size Q number of programs along the zero
  4828. 3:28:08axis and the B size multiplied by number
  4829. 3:28:11of heads on along the first axis of the
  4830. 3:28:15uh green grid of the launch
  4831. 3:28:17grid which will help us identify which
  4832. 3:28:21um part of the query we are going to
  4833. 3:28:23work with in this program in this uh
  4834. 3:28:26kernel and also in which batch and on
  4835. 3:28:29which head this program should work with
  4836. 3:28:32so that's what we are going to do now we
  4837. 3:28:34are trying to understand what part of
  4838. 3:28:36the input we should work with based on
  4839. 3:28:39the IDS of the program which corresponds
  4840. 3:28:42to the block ID in
  4841. 3:28:44Cuda uh so let me copy so the program ID
  4842. 3:28:49zero indicates it's this stuff here
  4843. 3:28:51tells us which part of the queries so
  4844. 3:28:55which block of the queries we are going
  4845. 3:28:56to work with why do we have a block on
  4846. 3:28:59the query because as we saw before the
  4847. 3:29:00output can be computed independently for
  4848. 3:29:02each block of the queries while each
  4849. 3:29:05block of the query has to iterate
  4850. 3:29:07through all the key and
  4851. 3:29:09values um so this is what will tell us
  4852. 3:29:12what is the index of the block of the
  4853. 3:29:14queries we are going to work with in
  4854. 3:29:15this particular
  4855. 3:29:16program then we can understand also
  4856. 3:29:19which index which batch and which head
  4857. 3:29:22this program is associated with the
  4858. 3:29:24program ID number one is the product of
  4859. 3:29:26the uh batch size and number of heads it
  4860. 3:29:29means that we will have as many programs
  4861. 3:29:31on the axis number one as there are uh
  4862. 3:29:35indicated by this product so this
  4863. 3:29:37product lets us understand that this uh
  4864. 3:29:40product will tell us which batch and
  4865. 3:29:43which head this particular program is
  4866. 3:29:44associated with so uh to get the uh ID
  4867. 3:29:48of the batch we just divide this number
  4868. 3:29:50by the number of heads and it will give
  4869. 3:29:52us the head index and to get the head
  4870. 3:29:55index inside this batch we just do the
  4871. 3:29:58um this number here uh modulus the
  4872. 3:30:00number of heads
  4873. 3:30:02okay uh the next thing that we need to
  4874. 3:30:04do uh we need to okay first of all when
  4875. 3:30:10we pass a tensor because as you can see
  4876. 3:30:13here the Q parameter to this attention
  4877. 3:30:16forward method is a tensor because it's
  4878. 3:30:18the input of this function forward
  4879. 3:30:20function and this forward function is
  4880. 3:30:22called here when we do attention do
  4881. 3:30:25apply and it's this Q stuff here and
  4882. 3:30:28this Q stuff here has been created as a
  4883. 3:30:30tensor so when we pass a tensor to a
  4884. 3:30:32Triton kernel it's not really a tensor
  4885. 3:30:35it is a pointer to the first element of
  4886. 3:30:37that tensor in the memory now we need to
  4887. 3:30:40understand because now we know which
  4888. 3:30:42batch we are going to work with and
  4889. 3:30:44which head we are going to work with we
  4890. 3:30:46need to Index this tensor to select the
  4891. 3:30:48right batch and the right head inside of
  4892. 3:30:51the right batch which means that
  4893. 3:30:53basically we have this Q uh tensor so we
  4894. 3:30:57need to do some some sort of like some
  4895. 3:30:59stuff like this like Q of the index
  4896. 3:31:04batch and uh number of the number of
  4897. 3:31:08heads in the case the the which head we
  4898. 3:31:10are going to work with so it should be
  4899. 3:31:12index of head and we need to select
  4900. 3:31:15every everything that is inside this
  4901. 3:31:17indices so we are we need to enter the
  4902. 3:31:21tensor at the right location where the
  4903. 3:31:23particular sequence length and head
  4904. 3:31:25dimension for this batch and for this
  4905. 3:31:27head starts for that we need to generate
  4906. 3:31:30an offset in which we need to move this
  4907. 3:31:32tensor from because this T this pointer
  4908. 3:31:35sorry this not tensor this pointer from
  4909. 3:31:38because this pointer is pointing at the
  4910. 3:31:40beginning of the entire tensor so we
  4911. 3:31:41need to move in the bch size dimension
  4912. 3:31:44and in the number of heads dimension
  4913. 3:31:46to do that we generate the following
  4914. 3:31:49offset which will tell us where this uh
  4915. 3:31:52where this particular batch and where
  4916. 3:31:54this particular head starts in this
  4917. 3:31:56tensor and to do that we need to do the
  4918. 3:31:59strides we need to use the strides so
  4919. 3:32:00what we are going to do is we are
  4920. 3:32:02create going to create the qkv offset uh
  4921. 3:32:06this is should be the sequence
  4922. 3:32:08length um which will be the index batch
  4923. 3:32:11multiplied by The
  4924. 3:32:13Stride for the batch Dimension which
  4925. 3:32:15will tell do how many elements we need
  4926. 3:32:17to skip to get to the next batch and
  4927. 3:32:20it's based and we multiply it by the
  4928. 3:32:22index of the batch that we want so for
  4929. 3:32:24the zero batch we don't skip anything
  4930. 3:32:26because we already pointing to the first
  4931. 3:32:27element of that batch but if we are at
  4932. 3:32:30the batch one we will skip that many
  4933. 3:32:32number of elements plus we also need to
  4934. 3:32:35skip the some heads how many head we
  4935. 3:32:37need to skip based on which head we are
  4936. 3:32:38going to work with and what tells us how
  4937. 3:32:41how to go from one head to the next The
  4938. 3:32:43Stride of the head dimension so we
  4939. 3:32:46multiply the index head so the head that
  4940. 3:32:48we should be working with with the
  4941. 3:32:50stride Q
  4942. 3:32:52head all right then um we select now
  4943. 3:32:58Tron helps us with a new function that I
  4944. 3:33:02think it was quite recent that helps us
  4945. 3:33:05index element inside of a tensor without
  4946. 3:33:08having to deal with all the complex um
  4947. 3:33:11indexing maths that can be confusing for
  4948. 3:33:14beginners so I will be using few methods
  4949. 3:33:17to help us with this um uh with this
  4950. 3:33:22indexing and this function is called
  4951. 3:33:25make block pointer and it's this
  4952. 3:33:27following so basically this make block
  4953. 3:33:31pointer takes as input a
  4954. 3:33:33vector and sorry a pointer not a vector
  4955. 3:33:37takes as input a pointer in this case we
  4956. 3:33:40are
  4957. 3:33:41saying create a
  4958. 3:33:43block that has the following shape that
  4959. 3:33:46is sequence length by head dimmension so
  4960. 3:33:48let me do it one by one actually I don't
  4961. 3:33:50want to confuse you guys with all this
  4962. 3:33:51stuff Al together okay so take start um
  4963. 3:33:56there is a pointer that is right now
  4964. 3:33:58pointing at Q Plus Q KV offset so right
  4965. 3:34:01now it is not pointing at the first
  4966. 3:34:04batch but it's pointing exactly to our
  4967. 3:34:06batch so the the batch that this
  4968. 3:34:08particular program should be working
  4969. 3:34:09with and inside this badge to the
  4970. 3:34:11particular head that this program should
  4971. 3:34:14be working with which is is basically
  4972. 3:34:17saying that we have um we are pointing
  4973. 3:34:19to a tensor that is as follows so we are
  4974. 3:34:23pointing to the following tensors which
  4975. 3:34:25is the right
  4976. 3:34:27head the right uh sorry the right batch
  4977. 3:34:30and the right head and then we are
  4978. 3:34:32selecting everything inside so it's
  4979. 3:34:34pointing to the first element of this
  4980. 3:34:37particular
  4981. 3:34:38tensor this tensor particular tensor
  4982. 3:34:41because we have already selected the
  4983. 3:34:42batch and the head it is a
  4984. 3:34:44two-dimensional tensor with this the
  4985. 3:34:46following shape because the the
  4986. 3:34:48following dimensions are sequence length
  4987. 3:34:50and head dim so we are saying take this
  4988. 3:34:53pointer which contains a tensor of the
  4989. 3:34:57following shape sequence length and head
  4990. 3:34:59Dimension and I'm also giving you the
  4991. 3:35:02strides of this Dimensions that are in
  4992. 3:35:05this pointer so the the the two
  4993. 3:35:07Dimensions that are that we need are the
  4994. 3:35:09sequence Dimension and the head dim
  4995. 3:35:11Dimension which is this one for the Q
  4996. 3:35:14tensor and
  4997. 3:35:18um and in this um in this
  4998. 3:35:22query uh tensor we want to
  4999. 3:35:26select a block of queries based on the
  5000. 3:35:30query on the block of queries that this
  5001. 3:35:32program should be working with so I
  5002. 3:35:35think I need to maybe probably use the
  5003. 3:35:37iPad otherwise it can be very confusing
  5004. 3:35:39to visualize so uh let's do it actually
  5005. 3:35:43so let me see if I can create another
  5006. 3:35:45another here and let's use the
  5007. 3:35:52iPad all
  5008. 3:35:55right okay so we have a Q Vector Q
  5009. 3:36:00tensor because this construct we will be
  5010. 3:36:02using it for all the other tensor so if
  5011. 3:36:03you understand it for one tensor you
  5012. 3:36:05understand it for all the others we have
  5013. 3:36:07a Q tensor that is a
  5014. 3:36:09batch uh by number of
  5015. 3:36:13heads number of heads then the sequence
  5016. 3:36:17length and then the head
  5017. 3:36:24Dimension with the following line so the
  5018. 3:36:27this line here so when we create Q Plus
  5019. 3:36:31uh qkv offset we are already selecting
  5020. 3:36:34the right batch Dimension and already
  5021. 3:36:37the right head Dimension which means
  5022. 3:36:40that we have already forwarded our Q to
  5023. 3:36:44not point to the first batch and the
  5024. 3:36:46first head but to point to the exact
  5025. 3:36:49batch that this program is working with
  5026. 3:36:51and the exact head that this program is
  5027. 3:36:53working with which basically means that
  5028. 3:36:55right now it is pointing at a tensor
  5029. 3:36:57that is made up of these two
  5030. 3:37:00Dimensions now inside of this tensor we
  5031. 3:37:03also need to select the right block of
  5032. 3:37:06query that this program should work with
  5033. 3:37:09and this Dimension here so the sequence
  5034. 3:37:12Dimension is all the queries so we need
  5035. 3:37:15to select select the right queries so we
  5036. 3:37:17need to skip some queries how to skip
  5037. 3:37:19some queries well we say that we need to
  5038. 3:37:22skip block index multiplied by block
  5039. 3:37:25size Q number of queries because they
  5040. 3:37:28will be processed by another um by
  5041. 3:37:31another uh program that will have this
  5042. 3:37:35number here the program ID will be
  5043. 3:37:37different so we are selecting with this
  5044. 3:37:40line not only inside of the que the
  5045. 3:37:44right index and the head but also the
  5046. 3:37:46right position in this dimension in the
  5047. 3:37:48sequence length Dimension that will
  5048. 3:37:50point to the exact to the starting point
  5049. 3:37:52of the exact query block that this
  5050. 3:37:55particular program should be working
  5051. 3:37:56with this is what it's happening and we
  5052. 3:37:59are also creating this block basically
  5053. 3:38:02later we will see how it can be used um
  5054. 3:38:05to uh to create a block of the shape uh
  5055. 3:38:08we are telling what is the the size of
  5056. 3:38:11this tensor so this tensor has two
  5057. 3:38:14Dimensions because we are pointing to
  5058. 3:38:16the beginning of the right query
  5059. 3:38:19sequence so it has only two Dimensions
  5060. 3:38:21the sequence Dimension and the head dim
  5061. 3:38:23Dimension so it's the last
  5062. 3:38:24Dimension um and we are already pointing
  5063. 3:38:27to the right beginning of the sequence
  5064. 3:38:30uh Dimension because we have already
  5065. 3:38:32skipped some queries why we are skipping
  5066. 3:38:35some queries because these queries will
  5067. 3:38:36be handled by another program that will
  5068. 3:38:38have a block index Q to some other
  5069. 3:38:41values um and this order uh actually I
  5070. 3:38:46don't know what is this order you can
  5071. 3:38:47try to put 01 and one two I think it's
  5072. 3:38:49some optimization that Triton does I
  5073. 3:38:51have read the online documentation and I
  5074. 3:38:52couldn't find anything about it so this
  5075. 3:38:55is something that I will investigate but
  5076. 3:38:57actually even if you put a 01 it doesn't
  5077. 3:39:00matter so I think it's something that
  5078. 3:39:02you tell Triton uh if this you want the
  5079. 3:39:06transposed of this block or you want the
  5080. 3:39:08not transposed version of this block and
  5081. 3:39:09later we will see actually how we can
  5082. 3:39:11transpose the key block without doing
  5083. 3:39:13any transpose operation actually we we
  5084. 3:39:15will just change the strides like we
  5085. 3:39:17have seen before so um now this make
  5086. 3:39:22block pointer is not something that is
  5087. 3:39:25necessary but it makes our life easier
  5088. 3:39:27when we will Index this particular
  5089. 3:39:30pointer so we can treat this pointer
  5090. 3:39:32nearly as um nearly in the same way when
  5091. 3:39:35we work with the tensor in pytorch we
  5092. 3:39:38will be able to skip one uh increase uh
  5093. 3:39:41one index in one dimension without
  5094. 3:39:43having to do the computation of the
  5095. 3:39:45strides later when doing the backward
  5096. 3:39:48pass I will not use this one and do all
  5097. 3:39:50the pointer indexing by hand so you can
  5098. 3:39:52check the differences of indexing a
  5099. 3:39:54tensor by using make block pointer and
  5100. 3:39:56not by using it anyway to rehearse what
  5101. 3:39:59are we creating we are creating a
  5102. 3:40:01pointer to the right index in the batch
  5103. 3:40:05to the right index in the head Dimension
  5104. 3:40:07and we are already skipping some queries
  5105. 3:40:10based on the Block index que so this
  5106. 3:40:14pointer is already point to the right
  5107. 3:40:16block of queries that this particular
  5108. 3:40:17program should be working with let's
  5109. 3:40:19look Instead at the V and the K block
  5110. 3:40:23now so let's copy the V block now which
  5111. 3:40:28is similar to the query but we are not
  5112. 3:40:30going inside we are only indexing by the
  5113. 3:40:34index badge and the index head so what
  5114. 3:40:37this one actually let me write it here
  5115. 3:40:39is already skipping
  5116. 3:40:41so this amount of
  5117. 3:40:44queries this is what we are indexing
  5118. 3:40:46with this make block pointer so we are
  5119. 3:40:49in the right batch in the right head and
  5120. 3:40:51we are skipping some
  5121. 3:40:52queries here we are just indexing by
  5122. 3:40:57batch and by head so we are doing V of
  5123. 3:41:00index batch index head and we are not
  5124. 3:41:05selecting we are not skipping anything
  5125. 3:41:07because you see this offset is equal to
  5126. 3:41:09zero in the First Dimension in the
  5127. 3:41:11second dimension so we are not skipping
  5128. 3:41:13anything on the sequence length and we
  5129. 3:41:14are not SK anything in the head
  5130. 3:41:16dimmension Dimension head Dimension
  5131. 3:41:20Dimension um all right so let's look at
  5132. 3:41:23the K block pointer and this is
  5133. 3:41:26different because as you know when
  5134. 3:41:28Computing the flashh attention algorithm
  5135. 3:41:30we need to have access to the block of
  5136. 3:41:32queries and all the block of the key
  5137. 3:41:36transposed so when accessing the key we
  5138. 3:41:39shouldn't access it like we are
  5139. 3:41:41accessing Q we should invert the two uh
  5140. 3:41:44Di Dimensions that we want to transpose
  5141. 3:41:46for and that's very simple with make
  5142. 3:41:49block PTR and you can see it here we say
  5143. 3:41:52that we want to point to the right index
  5144. 3:41:55and to the right head and the tensor be
  5145. 3:41:59inside of it so let's let me write it
  5146. 3:42:01here so later I can explain in line by
  5147. 3:42:03line so what we are doing here is go to
  5148. 3:42:05the K tensor select the right batch
  5149. 3:42:08select the right head select everything
  5150. 3:42:12that is inside so it's a tensor of two
  5151. 3:42:14Dimensions with the sequence length and
  5152. 3:42:16the head dim because we we you can see
  5153. 3:42:18here um here uh sequence length and head
  5154. 3:42:22dims Etc but we don't want first
  5155. 3:42:25sequence length and then head dim we
  5156. 3:42:28want first head dim and then sequence
  5157. 3:42:29length so we want to transpose it how to
  5158. 3:42:31transpose it we just say that you need
  5159. 3:42:33to read this tensor with the two strides
  5160. 3:42:36transposed so we are saying first use
  5161. 3:42:38the stride of the dimension Dimension
  5162. 3:42:41and then use the stride of the sequence
  5163. 3:42:43Dimension and the shape of this uh
  5164. 3:42:47tensor is not sequence uh head dim it's
  5165. 3:42:51head dim sequence and it's a block of
  5166. 3:42:56KVs um why we are not putting directly
  5167. 3:43:00the sequence Dimension here because we
  5168. 3:43:03want to skip block by block later so we
  5169. 3:43:06are not selecting all the sequence
  5170. 3:43:08length in the sequence Dimension we are
  5171. 3:43:09just selecting a block of KVs and later
  5172. 3:43:12we will use another method to go to the
  5173. 3:43:14next block
  5174. 3:43:15so I hope that by showing you the
  5175. 3:43:18indexing like this it's a little easier
  5176. 3:43:20to follow the indexing so for each
  5177. 3:43:23tensor we are going in the right batch
  5178. 3:43:24in the right head Dimension and for the
  5179. 3:43:27query we are skipping some query blocks
  5180. 3:43:29because each each program will work with
  5181. 3:43:32a small different um query block but for
  5182. 3:43:35the key and value each program needs to
  5183. 3:43:38iterate through all the key and value so
  5184. 3:43:40we just point it to the first key and
  5185. 3:43:42value block and then we will advance by
  5186. 3:43:44one block by um we will advance uh one
  5187. 3:43:47block uh by one during the for Loop that
  5188. 3:43:50we will do
  5189. 3:43:51later then in the output also we need we
  5190. 3:43:55can make um a tensor block
  5191. 3:43:58tensor this basically creates a pointer
  5192. 3:44:01just like in the query key and value
  5193. 3:44:02case in which we select the right index
  5194. 3:44:05batch so what we are doing is we are
  5195. 3:44:07indexing by
  5196. 3:44:08batch we are indexing by head and we are
  5197. 3:44:12selecting everything that inside Unown
  5198. 3:44:14we are not cting everything inside we
  5199. 3:44:16are skipping also in this case some
  5200. 3:44:18blocks of queries uh because as I said
  5201. 3:44:21before the output has the same shape as
  5202. 3:44:24the query so um the this particular
  5203. 3:44:28block this particular program that we
  5204. 3:44:30that will have this particular block
  5205. 3:44:33index Q will only work with one block of
  5206. 3:44:35uh the queries which will produce only
  5207. 3:44:37one block of the output Matrix and we
  5208. 3:44:40need to select exactly that one so we we
  5209. 3:44:43can point this pointer exactly to the
  5210. 3:44:45point where we should start writing so
  5211. 3:44:48let's skip also in this case block index
  5212. 3:44:51Q multiplied by block size Q um
  5213. 3:44:56rows so we select exactly the block that
  5214. 3:44:59our um our program this particular
  5215. 3:45:03program will produce when I speak about
  5216. 3:45:06this particular program I mean the
  5217. 3:45:09program that is identified by this
  5218. 3:45:11program ID in the xzero axis and this
  5219. 3:45:14program ID in the first axis because
  5220. 3:45:16each of these program will run in
  5221. 3:45:18parallel hopefully and each of them will
  5222. 3:45:20have a different value for the block
  5223. 3:45:21index q and index batch
  5224. 3:45:24head okay now we have pointed our
  5225. 3:45:27pointers to the right position where
  5226. 3:45:29they should either read some information
  5227. 3:45:31or they should either write some
  5228. 3:45:33information by using make block pointer
  5229. 3:45:35these uh pointers can also be treated
  5230. 3:45:37directly as tensors so that's why we
  5231. 3:45:39specify the shapes of these tensors
  5232. 3:45:42because python uh Tryon right now
  5233. 3:45:43provides some methods to work directly
  5234. 3:45:46with uh blocks of um to work directly
  5235. 3:45:51with pointers like they are we are
  5236. 3:45:53accessing um tensors so we can index
  5237. 3:45:56them like
  5238. 3:45:57tensors all right so basically just try
  5239. 3:46:01on doing some calculation for you based
  5240. 3:46:03on the strides so you don't have to do
  5241. 3:46:05it by hand but later when we do the back
  5242. 3:46:06part T we will avoid using make block
  5243. 3:46:09pointer and we will see the indexing
  5244. 3:46:10done by
  5245. 3:46:12hand all right uh um as you know we are
  5246. 3:46:16processing a single block of queries so
  5247. 3:46:20let let's go back to the um algorithm
  5248. 3:46:23otherwise we we lose uh the site of what
  5249. 3:46:26we are
  5250. 3:46:27doing so let's go here and let's show my
  5251. 3:46:31iPad all right so as you know each
  5252. 3:46:34program we will parallelize along the
  5253. 3:46:37query block Dimension so each program
  5254. 3:46:39will work with a different query block
  5255. 3:46:41and then we need to do a for loop on all
  5256. 3:46:43the key and values
  5257. 3:46:45blocks right now we just uh moved our
  5258. 3:46:49pointers to the right position to select
  5259. 3:46:52the right query block that we should
  5260. 3:46:53work with and to the beginning of the
  5261. 3:46:56keys and values block that we should
  5262. 3:46:58work with based on which index and which
  5263. 3:47:00head this particular program should be
  5264. 3:47:02working
  5265. 3:47:04with all right now that we have pointed
  5266. 3:47:06our pointers to the right position in
  5267. 3:47:08which our program should be working it
  5268. 3:47:10inside of the big pointers that are um
  5269. 3:47:14inside of the big tensors that are the
  5270. 3:47:17that have the batch Dimension the number
  5271. 3:47:20of heads Dimension the sequence length
  5272. 3:47:23Dimension and the head Dimension we have
  5273. 3:47:25because we are pointing to the right
  5274. 3:47:27batch and we are pointing to the right
  5275. 3:47:28head these tensors have become two
  5276. 3:47:30dimensional tensors so they only work on
  5277. 3:47:33the they are only tensors on the
  5278. 3:47:35sequence length and on the head
  5279. 3:47:37Dimension now we need some mod some more
  5280. 3:47:40information that we will use
  5281. 3:47:42later the first information that we we
  5282. 3:47:44need is the offsets of each query inside
  5283. 3:47:49of the current block of queries that
  5284. 3:47:51this particular program should be
  5285. 3:47:52working with and that is given by the
  5286. 3:47:55following line so let me copy and paste
  5287. 3:47:59which is this one so the offsets of the
  5288. 3:48:02queries are the first of all they are
  5289. 3:48:07how many of them block size Q because
  5290. 3:48:09each block of queries is made up of
  5291. 3:48:11block size Q number of queries what is
  5292. 3:48:14each where it's a token and it's on the
  5293. 3:48:17head Dimension is um the dim Dimension
  5294. 3:48:20is not the all the embedding of the
  5295. 3:48:23token but a part of the embedding of
  5296. 3:48:25each token which part the part
  5297. 3:48:27corresponding to the head that this
  5298. 3:48:29particular program is going to work with
  5299. 3:48:32so we are generating the offsets that
  5300. 3:48:34will load this particular number of uh
  5301. 3:48:36this particular queries from the big
  5302. 3:48:38tensor that contains all queries and we
  5303. 3:48:41know that our queries start at the Block
  5304. 3:48:43index cu multiplied by block size Q
  5305. 3:48:46position so if this is the program
  5306. 3:48:49number zero they will the Imagine block
  5307. 3:48:51size is equal to four they will be the
  5308. 3:48:53query with index 0 1 two and three but
  5309. 3:48:57imagine we are the program number three
  5310. 3:49:00which means that we need to skip um
  5311. 3:49:02three multiplied by four so 12 so it
  5312. 3:49:05will point to the query number 13 14 15
  5313. 3:49:09and 16 etc etc
  5314. 3:49:11etc all right and we do the same for the
  5315. 3:49:14key and values initially the key and
  5316. 3:49:17values um is a range of keys and values
  5317. 3:49:21that we need at e each iteration and at
  5318. 3:49:23the beginning because our pointer for
  5319. 3:49:26the K andv is pointing to the beginning
  5320. 3:49:29of the sequence of key and value for
  5321. 3:49:31this particular badge and for this
  5322. 3:49:32particular head we are pointing to the
  5323. 3:49:35first block of key and value so we are
  5324. 3:49:37not skipping anything in the query case
  5325. 3:49:39we are skipping because our program will
  5326. 3:49:41only work with one single block of
  5327. 3:49:42queries in this case we don't skip
  5328. 3:49:45anything because we need to iterate
  5329. 3:49:46through these key and values so we are
  5330. 3:49:48pointing to the first uh block of key
  5331. 3:49:51values so imagine block size KV is equal
  5332. 3:49:53to four so this stuff here will be equal
  5333. 3:49:55to zero 1 2 and
  5334. 3:49:57three all right now we need as you
  5335. 3:50:02remember inside of the flashh atten
  5336. 3:50:03algorithm we need to compute a block of
  5337. 3:50:06query multiplied by the transpose of the
  5338. 3:50:08keys and to each of this block we need
  5339. 3:50:10to apply the soft Max star if you
  5340. 3:50:13remember what is the soft Max star is
  5341. 3:50:14the soft Max of without the
  5342. 3:50:18normalization so while Computing the
  5343. 3:50:20soft Max star we also actually compute
  5344. 3:50:22the normalization factor without
  5345. 3:50:24applying it and we apply the
  5346. 3:50:25normalization factor at the end so for
  5347. 3:50:27each block of query multiplied by
  5348. 3:50:30transpose of the keys we need to have
  5349. 3:50:32the maximum for each row in this
  5350. 3:50:34particular block and the normalization
  5351. 3:50:36factor for each row so that's why why we
  5352. 3:50:39need these two following
  5353. 3:50:41statistics which is this one and this
  5354. 3:50:44this is basically um a block uh it's a
  5355. 3:50:48block of numbers how many based on how
  5356. 3:50:51many queries we have in our block of
  5357. 3:50:53queries each one initialize with minus
  5358. 3:50:55infinity just like in my algorithm that
  5359. 3:50:57I show before so let me go back to the
  5360. 3:50:59slides in case we forgot um or actually
  5361. 3:51:03you can also check the flash attention
  5362. 3:51:04algorithm we initialize it with minus
  5363. 3:51:06Infinities so so far we are creating
  5364. 3:51:08this stuff here so we are initializing
  5365. 3:51:09the Mi we are we will be initializing
  5366. 3:51:11the LI I and we will initializing the o
  5367. 3:51:15and then we will show the inner loop
  5368. 3:51:17here um and this is exactly the
  5369. 3:51:19algorithm that we have seen before so we
  5370. 3:51:21initialize M with minus
  5371. 3:51:23Infinities now we initialize also the
  5372. 3:51:25L's so let me go back to the
  5373. 3:51:28code uh all
  5374. 3:51:32right so the L's are initialized with
  5375. 3:51:36this number here so
  5376. 3:51:39here in the O blocks as we can see from
  5377. 3:51:42the flashh algorithm they are the O
  5378. 3:51:44Block is initialized with zeros so
  5379. 3:51:46that's why we initialize a block this is
  5380. 3:51:48the output block that this particular
  5381. 3:51:50program will compute which is based on
  5382. 3:51:52the position in the batch and the
  5383. 3:51:55position in the indexes so it is one
  5384. 3:51:57block of the size block size Q so how
  5385. 3:51:59many queries there are in this block by
  5386. 3:52:01head
  5387. 3:52:02Dimension um which if you want to
  5388. 3:52:05visualize it let's go back to the slides
  5389. 3:52:08it is equal
  5390. 3:52:10to one block of this Matrix here so it's
  5391. 3:52:14one one block of the output Matrix so
  5392. 3:52:17one row of blocks uh one block of
  5393. 3:52:20rows uh okay so let's go back to the
  5394. 3:52:24code
  5395. 3:52:25now all right so now we have initialized
  5396. 3:52:29little stuff here so the output the Mi
  5397. 3:52:32and Li where Mi is the maximum for each
  5398. 3:52:35row in this particular query block and
  5399. 3:52:37the LI is the normalization factor for
  5400. 3:52:40each of the um items in the query for
  5401. 3:52:44each of
  5402. 3:52:45the rows in our query
  5403. 3:52:48block now we need to do the for Loop the
  5404. 3:52:51inner loop in the flashh attention
  5405. 3:52:53algorithm uh we will create a separate
  5406. 3:52:56method that will run the inner loop so
  5407. 3:52:59let's let me copy
  5408. 3:53:01it here and I am following the same
  5409. 3:53:04structure of the code that you see in
  5410. 3:53:05the tutorial of the Tron
  5411. 3:53:08website so um basically if we are
  5412. 3:53:11running the Cal attention or even if we
  5413. 3:53:14are not running the Cal attention we
  5414. 3:53:15make this for Loop and then we will make
  5415. 3:53:18another for Loop and I will show you why
  5416. 3:53:21so let me first write it and then we
  5417. 3:53:24will see so this function here will be
  5418. 3:53:27the inner loop this inner loop needs to
  5419. 3:53:29go through all key and value blocks one
  5420. 3:53:32by one and for each query and value
  5421. 3:53:36block it needs to fix the previous
  5422. 3:53:39calculated block of uh the the previous
  5423. 3:53:42softmax star block so basically what we
  5424. 3:53:45are doing here we will need to create a
  5425. 3:53:48function as the following where we are
  5426. 3:53:51going to iterate on all the key value
  5427. 3:53:53block we will need to compute the query
  5428. 3:53:55multiply by the transpose of the keys
  5429. 3:53:57using the query block that is fixed for
  5430. 3:53:59this program and the key is block is the
  5431. 3:54:02one that we are iterating it through and
  5432. 3:54:04for each of these queries we need to
  5433. 3:54:06calculate what is the maximum for each
  5434. 3:54:08row we need to compute the softmax star
  5435. 3:54:11so the softmax without the normalization
  5436. 3:54:14factor
  5437. 3:54:15we need to keep the statistics L which
  5438. 3:54:17is the normalization factor that we will
  5439. 3:54:19apply at the end of the iteration of the
  5440. 3:54:22for Loop and at the same time we need to
  5441. 3:54:26update the output so as you remember the
  5442. 3:54:28output is P11 * by V1 plus p12 * by vs2
  5443. 3:54:34but we need to fix the previous P11 so
  5444. 3:54:37to fix that we need to every time we sum
  5445. 3:54:39to O to the output we need to fix the
  5446. 3:54:43output of the previous
  5447. 3:54:45iteration um and then we increase
  5448. 3:54:49introduce the p and v block of the
  5449. 3:54:51current iteration so um here the author
  5450. 3:54:56of The the code for the the one that you
  5451. 3:54:58see on the Tron website decided to split
  5452. 3:55:02this for Loop into two steps why because
  5453. 3:55:06in the causal attention we need to uh
  5454. 3:55:09when we have a caal attention we have a
  5455. 3:55:12group of um we we don't we don't want
  5456. 3:55:14the query to attend keys that come after
  5457. 3:55:17it while in the non-causal attention we
  5458. 3:55:20let all the queries attend to all the
  5459. 3:55:22keys which also means that we will need
  5460. 3:55:24to have some kind of if statement inside
  5461. 3:55:27of this if U inside of this for Loop
  5462. 3:55:29through all the key and values in which
  5463. 3:55:31we need to check if the this particular
  5464. 3:55:34query that we are working with is comes
  5465. 3:55:38before or after the key and value in
  5466. 3:55:40case we are doing the caal attention so
  5467. 3:55:42instead of uh iterating through all the
  5468. 3:55:45keyan values also in the case of the Cal
  5469. 3:55:48attention by splitting it into two uh
  5470. 3:55:51steps we are saying uh first let's
  5471. 3:55:54iterate through all the keyan values for
  5472. 3:55:57which the index is smaller than the
  5473. 3:55:59current queries block and for this we
  5474. 3:56:02need to compute the attention in the
  5475. 3:56:04case of the causal and non-causal case
  5476. 3:56:07then for all the elements on the right
  5477. 3:56:10of this block so for which the key index
  5478. 3:56:13is more than the Q index in the case of
  5479. 3:56:15causal attention we don't need to
  5480. 3:56:17compute anything because it will be
  5481. 3:56:19masked out because in the soft Max it
  5482. 3:56:21will become zeros so it will not
  5483. 3:56:23contribute to the output so we don't
  5484. 3:56:25even have to compute
  5485. 3:56:26it um this is why we split this this for
  5486. 3:56:30Loop into two steps so first we iterate
  5487. 3:56:33to all the parts that are left to the
  5488. 3:56:35diagonal of the query multiplied by the
  5489. 3:56:37key
  5490. 3:56:38Matrix so for all the values for which
  5491. 3:56:41the query index is less than the key
  5492. 3:56:43index then we um and then we skip all
  5493. 3:56:48the parts to the right of this diagonal
  5494. 3:56:50in case we are working with a cal mask
  5495. 3:56:52but in case of the non-causal Mask we
  5496. 3:56:53compute the left part and the right part
  5497. 3:56:55of this
  5498. 3:56:56diagonal all right don't worry when we
  5499. 3:56:59recorde this for Loop it will be more
  5500. 3:57:00clear so I just wanted to give a little
  5501. 3:57:03introduction so let's go uh code this
  5502. 3:57:05inner loop what will this inner loop do
  5503. 3:57:08it will work with this particular query
  5504. 3:57:10block that we have found so this Q block
  5505. 3:57:14it will uh why I don't see the Q block
  5506. 3:57:17because I didn't load it well yeah uh
  5507. 3:57:20let's load it so we need to load the
  5508. 3:57:22query block actually we forgot to load
  5509. 3:57:24it so as you remember in Tron we we load
  5510. 3:57:27um data from the high bandwidth memory
  5511. 3:57:30to the SRAM so to the shared memory by
  5512. 3:57:32using the load statement and we are
  5513. 3:57:34telling load the query block that we
  5514. 3:57:37should be working with because this
  5515. 3:57:38pointer Q block PTR is already pointing
  5516. 3:57:41to the right block that we should be
  5517. 3:57:43working with so it's already skipping
  5518. 3:57:45all the blocks that other programs
  5519. 3:57:47should be working with and it will load
  5520. 3:57:51a uh a tensor of size of block size Q
  5521. 3:57:54had dim so the right block of
  5522. 3:57:58queries and we pass it to this inner
  5523. 3:58:00loop to which we pass the output so
  5524. 3:58:03where it should write this output the Li
  5525. 3:58:06and Mi which are the statistics for the
  5526. 3:58:09rows and for for the maximum for each
  5527. 3:58:12row of each query and the LI I which is
  5528. 3:58:14the normalization factor for each query
  5529. 3:58:17and the query block this program should
  5530. 3:58:19be working with the beginning of the key
  5531. 3:58:22and value block pointer because we need
  5532. 3:58:24to iterate through them so we just point
  5533. 3:58:27it to the beginning and then inside the
  5534. 3:58:28for inner for Loop we will iterate
  5535. 3:58:30through them then the soft Max scale
  5536. 3:58:32that we should use when Computing query
  5537. 3:58:34multiplied by the transpose of the keys
  5538. 3:58:37the block size so how many queries we
  5539. 3:58:39have in each block of Q and how many key
  5540. 3:58:41and value we have in each block of KV
  5541. 3:58:45uh this is a stage that tells us what uh
  5542. 3:58:48if we are on the left side of the
  5543. 3:58:49diagonal or on the right side of the
  5544. 3:58:51diagonal so it will tell us if we need
  5545. 3:58:52to apply the Cal mask or not based on
  5546. 3:58:55where we are and if we are need to apply
  5547. 3:58:57the Cal
  5548. 3:58:58mask um the offset q and the offset KV
  5549. 3:59:02are just the offsets of the query and
  5550. 3:59:04key inside of each q and KV block which
  5551. 3:59:07is a list of indices that tells us um
  5552. 3:59:12how many queries we have
  5553. 3:59:15uh and then the sequence length the
  5554. 3:59:17entire sequence length because in the
  5555. 3:59:19for Loop we need to iterate to all the
  5556. 3:59:21sequence length block by block so block
  5557. 3:59:23of KV block of KV block of KV all right
  5558. 3:59:26let's write this me let's write this
  5559. 3:59:28method and later we need actually need
  5560. 3:59:30to continue this method again so let's
  5561. 3:59:33go and let me go
  5562. 3:59:39here all right
  5563. 3:59:44so uh this method we have already seen
  5564. 3:59:47the signature so it's just another
  5565. 3:59:49kernel so it can be called by the first
  5566. 3:59:51kernel and this is something you can
  5567. 3:59:53also do in Cuda you can actually call
  5568. 3:59:56call one Cuda kernel from another Cuda
  5569. 3:59:58kernel um and then we based on the stage
  5570. 4:00:03of this inner loop we decide what we
  5571. 4:00:05need to do so when we are using caal um
  5572. 4:00:10causal attention so we only want to
  5573. 4:00:13apply the um attention to the queries
  5574. 4:00:16for which the index is less than or
  5575. 4:00:18equal to the key so we only want the
  5576. 4:00:20query to never attend to key and value
  5577. 4:00:23that come after it then um we pass the
  5578. 4:00:27value three for the stage parameter now
  5579. 4:00:31when we in the Cal case this will become
  5580. 4:00:344 minus 3 it is equal to 1 so what will
  5581. 4:00:36happen is that we will only work with
  5582. 4:00:40the range of um keys and values that are
  5583. 4:00:44are from zero up to the current block of
  5584. 4:00:46Q so all the keys that whose index is
  5585. 4:00:49less than or less than the the the index
  5586. 4:00:53of the queries we are working with so to
  5587. 4:00:55the left part of the Cal mask let me
  5588. 4:00:58draw it otherwise I think it's going to
  5589. 4:01:00be very difficult to follow so let's do
  5590. 4:01:02it actually so let's open a new one and
  5591. 4:01:06let's go here all right so we have been
  5592. 4:01:09using this one before so we can do it
  5593. 4:01:12again clear page all right in this now I
  5594. 4:01:17I want you to think of the following uh
  5595. 4:01:20Matrix as a block Matrix so let's draw
  5596. 4:01:22it in pink because I have been drawing
  5597. 4:01:24it all in pink we know that in the rows
  5598. 4:01:27of this query multiplied by the
  5599. 4:01:28transpose of the keys we have a uh the
  5600. 4:01:31queries blocks of queries so we are not
  5601. 4:01:35watching one single block we are
  5602. 4:01:36watching all the blocks right now so
  5603. 4:01:38this is the query block one this is the
  5604. 4:01:40query block two this is the query block
  5605. 4:01:41three this is the query block four each
  5606. 4:01:44of this query block is made up of
  5607. 4:01:45multiple tokens of queries and then we
  5608. 4:01:49have the key the key
  5609. 4:01:51blocks uh let's do it like this very
  5610. 4:01:55ugly but okay uh key 1 key block two key
  5611. 4:01:58block three key block four when apply
  5612. 4:02:02calculating the attention when you
  5613. 4:02:03calculate the caal attention so um like
  5614. 4:02:07with the causal mask you want only the
  5615. 4:02:10query to attend to keys that come before
  5616. 4:02:13it so when we apply the causal mask this
  5617. 4:02:16stuff here will be made up of zeros this
  5618. 4:02:18stuff here will be made up of zeros this
  5619. 4:02:20stuff here will be made up of zeros and
  5620. 4:02:21this stuff here and this stuff here and
  5621. 4:02:23this stuff here all made up of
  5622. 4:02:25zeros we never have to mask out anything
  5623. 4:02:28when we are in this case
  5624. 4:02:30because well when we are in this
  5625. 4:02:32particular scenario actually in this
  5626. 4:02:34particular scenario we don't need to
  5627. 4:02:35mask out anything for sure why because
  5628. 4:02:38all the key um keys in this block so in
  5629. 4:02:43this block of keys keys will have an
  5630. 4:02:45index that is smaller than the index of
  5631. 4:02:46the corresponding queries in case the uh
  5632. 4:02:49the key the block size of the query and
  5633. 4:02:52the key matches so imagine each query is
  5634. 4:02:54made up of three queries so each block
  5635. 4:02:56of query is made up of three queries so
  5636. 4:02:59this is the query number 0 1 and two
  5637. 4:03:02this is the query number 3 4 five really
  5638. 4:03:063 4 five yeah this will be the number uh
  5639. 4:03:09six 7 and eight and this will be the
  5640. 4:03:12query number nine 10 10 and 11 in total
  5641. 4:03:15we have 12 queries we will have the same
  5642. 4:03:17indices also for the keys in case we
  5643. 4:03:19choose the same uh size for the blocks
  5644. 4:03:23so this key key block here will be the
  5645. 4:03:26key number 0 1 and
  5646. 4:03:29two this will be the key number three
  5647. 4:03:32four five this will be the six six 7 and
  5648. 4:03:37eight etc etc ET now what happens is
  5649. 4:03:40that in this case as you can see the key
  5650. 4:03:43in this in indices of the keys are
  5651. 4:03:45always smaller than the indices of the
  5652. 4:03:47queries so we don't need to mask out
  5653. 4:03:49anything even in the case of the Cal
  5654. 4:03:51mask because we are sure that in this
  5655. 4:03:53case all of these dot products will
  5656. 4:03:56never be masked out also in this case
  5657. 4:03:58all these dot products will never be
  5658. 4:03:59masked out and also in this case we'll
  5659. 4:04:01never be masked out we'll never be
  5660. 4:04:02masked out and we'll never be masked out
  5661. 4:04:04and in this case however along the
  5662. 4:04:07diagonal some of the queries will be
  5663. 4:04:10more have will have an index that is
  5664. 4:04:13bigger than than that of the keys and
  5665. 4:04:15some of them will not be uh will not
  5666. 4:04:17have an index that is bigger than that
  5667. 4:04:19of the keys because these are blocks of
  5668. 4:04:22queries and blocks of keys some of them
  5669. 4:04:24need to be masked out and some of them
  5670. 4:04:26don't need to be masked out so we are
  5671. 4:04:28dividing our for Loop into multiple
  5672. 4:04:30steps the first step that we are doing
  5673. 4:04:32is all to the left of this diagonal in
  5674. 4:04:35which we don't need to mask out anything
  5675. 4:04:37then we will see another step here in
  5676. 4:04:40which we um uh we need to mask out and
  5677. 4:04:43then everything to the right of this
  5678. 4:04:46will be we will not even compute in the
  5679. 4:04:48case of cation because we already know
  5680. 4:04:50it's made up of zero so it will not comp
  5681. 4:04:52so the product query multiplied by the
  5682. 4:04:54by transpose of the keys after the
  5683. 4:04:55softmax will be made up of zeros so if
  5684. 4:04:58you look at the flesh attention
  5685. 4:04:59algorithm so um this stuff here the
  5686. 4:05:02contribution will be zero because we are
  5687. 4:05:04multiplying zero with v it will be zero
  5688. 4:05:06so we don't need to change the output so
  5689. 4:05:08why even compute this part of the Matrix
  5690. 4:05:11if we already know it's not going to
  5691. 4:05:12contribute to the output so we just skip
  5692. 4:05:14all those iterations and this is why we
  5693. 4:05:16are splitting the for loop I hope now
  5694. 4:05:18it's much more
  5695. 4:05:20clear all right so let's go back um okay
  5696. 4:05:25so uh we are now to the left part of the
  5697. 4:05:27diagonal in case of the stage number one
  5698. 4:05:29in the case of the stage number two it's
  5699. 4:05:31the part in exactly on the diagonal so
  5700. 4:05:34in which we need to do some dot products
  5701. 4:05:36and some other dot products we don't
  5702. 4:05:38need to do and then for the non-causal
  5703. 4:05:40attention we just go through the from
  5704. 4:05:42zero to the sequence length without
  5705. 4:05:44doing this
  5706. 4:05:45multi-step
  5707. 4:05:47um because we don't need to mask out
  5708. 4:05:49anything so this is why we have this
  5709. 4:05:50stage this tells us what is the lower
  5710. 4:05:53and higher index of the key block that
  5711. 4:05:56this particular stage should be working
  5712. 4:05:58with all right um now this function here
  5713. 4:06:03multiple of is just telling Tron that
  5714. 4:06:06this number here is a multiple of this
  5715. 4:06:08number so Tron can make some
  5716. 4:06:11optimizations so the stage one happens
  5717. 4:06:13when
  5718. 4:06:14when we are doing a causal attention so
  5719. 4:06:17stage number three in this function and
  5720. 4:06:204 minus 3 will become one so imagine we
  5721. 4:06:22are in the causal attention we will go
  5722. 4:06:24through the key and value block that are
  5723. 4:06:27to the left of the uh diagonal with
  5724. 4:06:30respect to the query block that we are
  5725. 4:06:32working
  5726. 4:06:33with um in the case we are doing not
  5727. 4:06:36causal attention in this first call to
  5728. 4:06:39the uh inner function this the stage
  5729. 4:06:42will be one so the uh four minus stage
  5730. 4:06:45will be equal to three so we will
  5731. 4:06:47execute this part of the if statement so
  5732. 4:06:49we will go through all the key and
  5733. 4:06:51values in
  5734. 4:06:53case uh for the Cal attention only as
  5735. 4:06:56you can see here we will do another
  5736. 4:06:58iteration here that will only be done
  5737. 4:07:00along the diagonal in which we need to
  5738. 4:07:02mask out something and we don't need to
  5739. 4:07:04mask out something because inside of
  5740. 4:07:06each blocks there will be some keys that
  5741. 4:07:08have the index uh below the index of the
  5742. 4:07:11query and some that have above the index
  5743. 4:07:13of the query quy so only in the Cal
  5744. 4:07:15attention we will call this function
  5745. 4:07:17twice the first time with Stage equal to
  5746. 4:07:20one and the second time with Stage equal
  5747. 4:07:23to two and the second time we will only
  5748. 4:07:25iterate through the group of kyv blocks
  5749. 4:07:29that are exactly on the diagonal of the
  5750. 4:07:33um Matrix S multiply by transpose of the
  5751. 4:07:35keys the big Matrix that is made up of
  5752. 4:07:37all the
  5753. 4:07:38blocks all right now that this should be
  5754. 4:07:41clear let's proceed further so let's um
  5755. 4:07:45because we need to do the for Loop the
  5756. 4:07:46inner for Loop of the flashh attention
  5757. 4:07:49let's go and load the first blocks of
  5758. 4:07:52key and values which is exactly the one
  5759. 4:07:54that the key and V blocks are currently
  5760. 4:07:57pointing at which is the Zer z00
  5761. 4:08:01block so uh we we defined the the
  5762. 4:08:04pointers basically um we we we point the
  5763. 4:08:08key and value blocks to the first uh key
  5764. 4:08:11and value block that this uh for Loop
  5765. 4:08:14should be working with which will be
  5766. 4:08:16based on the stage so if it's the first
  5767. 4:08:18call to this function they will be
  5768. 4:08:20pointing to the first block in the case
  5769. 4:08:22of the uh causal and non causal if it's
  5770. 4:08:26the second call to this function which
  5771. 4:08:27only happs happens in the case of the
  5772. 4:08:29causal attention they will be pointing
  5773. 4:08:32exactly to the key and value block to
  5774. 4:08:33the
  5775. 4:08:34diagonal all right then we need to make
  5776. 4:08:37the for
  5777. 4:08:38Loop so let's Loop over all the for Loop
  5778. 4:08:42so let's do it
  5779. 4:08:44so Loop over the key and value and what
  5780. 4:08:48we do is um okay we we let the compiler
  5781. 4:08:52know that this number here the start KV
  5782. 4:08:55will always be a multiple of the block
  5783. 4:08:56size KV because we will be moving from
  5784. 4:08:59one KV block to the next KV block block
  5785. 4:09:01by block so we let the compiler know
  5786. 4:09:04that this number here start KV is a
  5787. 4:09:06multiple of block size KV it doesn't
  5788. 4:09:07change anything from a logic point of
  5789. 4:09:09view we are just telling giving some
  5790. 4:09:10hint to the compiler so it can do some
  5791. 4:09:13other optimization that Tron does um now
  5792. 4:09:18the first thing that we see in the flash
  5793. 4:09:19attention algorithm is we need to
  5794. 4:09:21compute the product of the query so this
  5795. 4:09:24the particular block of the query that
  5796. 4:09:25we are working with with the current KV
  5797. 4:09:28Block in this iteration so let's do it
  5798. 4:09:31so we compute K andv so we load the the
  5799. 4:09:36the query have already been loaded by
  5800. 4:09:37the color of this function we have
  5801. 4:09:39loaded it
  5802. 4:09:41here here we have a already loaded the
  5803. 4:09:44query but we need to load the current
  5804. 4:09:45block of K so we load the current block
  5805. 4:09:49of K indicated by the K pointer and we
  5806. 4:09:53multi we do the matrix multiplication of
  5807. 4:09:55the current block of query the the block
  5808. 4:09:58of query with the current block of K
  5809. 4:10:01which is already transposed because when
  5810. 4:10:03we loaded this k k when we defined the K
  5811. 4:10:07block pointer we defined it already with
  5812. 4:10:10the stride changed so we are reading the
  5813. 4:10:12T already already transposed so we are
  5814. 4:10:14doing the query multipli by the
  5815. 4:10:16transpose of the keys
  5816. 4:10:18basically okay now let's do
  5817. 4:10:23here this part here basically
  5818. 4:10:26saying okay if the stage is to when the
  5819. 4:10:29stages to is when we are exactly on the
  5820. 4:10:31diagonal we know that some of the
  5821. 4:10:33queries will have an index that is
  5822. 4:10:35bigger than that of the keys and some of
  5823. 4:10:37them we have an index that is smaller
  5824. 4:10:38than that of the keys so we need to
  5825. 4:10:40apply the Cal mask only in this case so
  5826. 4:10:44uh basically what we do is we Define the
  5827. 4:10:47mask that we should be applying so the
  5828. 4:10:49mask will mask out all the values for
  5829. 4:10:53which this mask is not true so when this
  5830. 4:10:56mask is true when the index of the query
  5831. 4:10:59is more than the index of the K and vs
  5832. 4:11:03and um we uh okay we apply the soft Max
  5833. 4:11:06scale so as you remember we here we only
  5834. 4:11:09computed query multiplied by the
  5835. 4:11:10transpose of the keys but we also need
  5836. 4:11:11to divide by the square root of head
  5837. 4:11:14Dimension and we do it
  5838. 4:11:16here um and then we because we already
  5839. 4:11:19computed
  5840. 4:11:21the uh the the product we can calculate
  5841. 4:11:24the maximum for each
  5842. 4:11:26row and then we uh we we substract
  5843. 4:11:31because uh when later in the flashh
  5844. 4:11:33attention algorithm we have another
  5845. 4:11:35operation which is the which I call the
  5846. 4:11:38softmax star and as you remember the
  5847. 4:11:40softmax star needs to to do uh each row
  5848. 4:11:46each element of the S Matrix so the
  5849. 4:11:48query multiplied by the transpose of the
  5850. 4:11:50keys minus the maximum for each row so
  5851. 4:11:53we can already compute the maximum for
  5852. 4:11:55each row and we can also before
  5853. 4:11:58Computing the maximum for each row we
  5854. 4:12:00need to mask out all the elements that
  5855. 4:12:03will be masked out in the stage number
  5856. 4:12:05two which is along the
  5857. 4:12:07diagonal and how to mask out we just
  5858. 4:12:10replace with minus infinity before
  5859. 4:12:12applying the soft Max all the values for
  5860. 4:12:14which the mask is false um so right now
  5861. 4:12:17we are we have computed what we have
  5862. 4:12:19computed the query multiplied by
  5863. 4:12:21transport of the keys we have masked out
  5864. 4:12:23in case we need to mask and when we need
  5865. 4:12:24to mask only when we are along the
  5866. 4:12:26diagonal in all the other cases we don't
  5867. 4:12:28need to mask out anything we just
  5868. 4:12:30multiply by the soft Max scale and then
  5869. 4:12:32we um we subtract the MJ the MJ is the
  5870. 4:12:36maximum value for each row because we
  5871. 4:12:39need to compute the softmax star
  5872. 4:12:41operation which is the softmax with the
  5873. 4:12:43normalization which in the flash
  5874. 4:12:44attention algorithm is exactly this
  5875. 4:12:46operation which will produce the
  5876. 4:12:49P okay so let's go here so now we can
  5877. 4:12:53compute the P block which is this stuff
  5878. 4:12:56here which is the exponential of the
  5879. 4:12:59query KV block variable here which have
  5880. 4:13:02already substracted the m so we have
  5881. 4:13:05already substracted this uh Mi at the
  5882. 4:13:09previous instruction so now we can just
  5883. 4:13:11apply the exponential and this is what
  5884. 4:13:14we are doing here uh okay then we need
  5885. 4:13:19to compute the uh sum of the the row for
  5886. 4:13:23the before the um uh normalization
  5887. 4:13:27Factor so for the current block we will
  5888. 4:13:29have a a list of uh we we will have the
  5889. 4:13:33P block for the current KV block to
  5890. 4:13:37compute the normalization factor for the
  5891. 4:13:39softmax we need to keep summing up these
  5892. 4:13:42exponentials and later we will fix the
  5893. 4:13:45exponentials the um the normalization
  5894. 4:13:48factor that we computed at the previous
  5895. 4:13:50step but we will do that later so now we
  5896. 4:13:52just computed the normalization factor
  5897. 4:13:54for the current block which is just the
  5898. 4:13:56sum of all the values on a single row uh
  5899. 4:13:59which is the same as what we did before
  5900. 4:14:02here as you can see
  5901. 4:14:05here when I show you the algorithm so
  5902. 4:14:08for each um for each block we do the row
  5903. 4:14:11sum as you can see here
  5904. 4:14:13of the P Matrix what is the P Matrix is
  5905. 4:14:17the exponential of the S minus M and for
  5906. 4:14:21now we didn't apply the the the
  5907. 4:14:23correction to the previous block that's
  5908. 4:14:25it so we computed the L J for the
  5909. 4:14:28current K andv block and then we comput
  5910. 4:14:31the correction factor for the previous
  5911. 4:14:33block so the correction factor for the
  5912. 4:14:35previous block if you remember the
  5913. 4:14:36formula from the paper is this one is
  5914. 4:14:39the exponential of the previous estimate
  5915. 4:14:41of the maximum minus the current
  5916. 4:14:43estimate of the maximum which is exactly
  5917. 4:14:45this one so the previous estimate of the
  5918. 4:14:46maximum minus the current estimate of
  5919. 4:14:48the maximum uh we will see later why Mi
  5920. 4:14:51is the previous estimate of the maximum
  5921. 4:14:53and what m j is the current estimate of
  5922. 4:14:55the maximum because it is coming from
  5923. 4:14:57the current block that we are Computing
  5924. 4:14:59Mi is the let's say the the one that um
  5925. 4:15:04it is the the one of the previous
  5926. 4:15:05iteration because later we will override
  5927. 4:15:08Mi with m j but I'm just following the
  5928. 4:15:12flashh attention gthm so far so I am
  5929. 4:15:14Computing the correction factor of the
  5930. 4:15:16previous Li which in the flash attention
  5931. 4:15:19algorithm is let me show you uh this
  5932. 4:15:22stuff here so it is this stuff here this
  5933. 4:15:27one
  5934. 4:15:28here um okay and then we apply it so
  5935. 4:15:32apply the correction factor so we apply
  5936. 4:15:36it so we apply the previous Li with the
  5937. 4:15:39correction factor plus the current Li
  5938. 4:15:42which is the one coming from the current
  5939. 4:15:44P block the one that we computed with
  5940. 4:15:45the current K andv with the current
  5941. 4:15:48iteration and right now we are doing
  5942. 4:15:50this operation so Li is equal to the
  5943. 4:15:53previous Li multiplied by the correction
  5944. 4:15:56factor all right and then what we need
  5945. 4:15:59to do okay we need to as you remember
  5946. 4:16:01the formula is um we um calculate the P
  5947. 4:16:05block and then we need to multiply by
  5948. 4:16:06the V block so we need to load the V
  5949. 4:16:08block so let's load it
  5950. 4:16:13we loaded the V block based on the
  5951. 4:16:15pointer of the V block to which this um
  5952. 4:16:19to to which the pointer V is is pointing
  5953. 4:16:22to at the beginning of this iteration in
  5954. 4:16:24case we are in stage number three so in
  5955. 4:16:27case we are doing for example not Cal
  5956. 4:16:28attention it will be pointing to the
  5957. 4:16:30first k v block uh V block and then okay
  5958. 4:16:35here there is just a type conversion so
  5959. 4:16:38we make sure this is in floating Point
  5960. 4:16:4116 and then we
  5961. 4:16:43compute the output block so we are
  5962. 4:16:46Computing the following so we just take
  5963. 4:16:50v p multiply it by V and we add it to
  5964. 4:16:53the output and this is what we are doing
  5965. 4:16:54here we take P we multiply it by V and
  5966. 4:16:58we add it to the O Block uh let's go
  5967. 4:17:01actually to this line one by one so
  5968. 4:17:03first of all we need to fix the previous
  5969. 4:17:05Aus block with the correction factor
  5970. 4:17:07correction factor that we have here so
  5971. 4:17:09we can fix the previous block with this
  5972. 4:17:11Alpha term here which is the correction
  5973. 4:17:14factor for the previous
  5974. 4:17:15block and so we just fixed the previous
  5975. 4:17:18block for now but we didn't add the new
  5976. 4:17:20PV so to add the new PV we do the dot
  5977. 4:17:23product of p and v and this third
  5978. 4:17:25argument tells the dot this not DOT
  5979. 4:17:28product it's actually the matrix
  5980. 4:17:29multiplication uh tell this matrix
  5981. 4:17:31multiplication to use this element here
  5982. 4:17:34as uh the accumulator so this is exactly
  5983. 4:17:37the same as doing uh P block multiplied
  5984. 4:17:41by the V block
  5985. 4:17:43uh O Block Plus equal to P block
  5986. 4:17:46multiplied by the V block uh this is
  5987. 4:17:49just optimized because anyway this dot
  5988. 4:17:52uh function here needs some place where
  5989. 4:17:54to store the intermediate results so why
  5990. 4:17:56not just store it where it should
  5991. 4:17:58actually go and because it um the dot
  5992. 4:18:02the the the matrix multiplication is
  5993. 4:18:04just a DOT product and the dot product
  5994. 4:18:06is just a repeated sum this accumulator
  5995. 4:18:09will be will this dot will keep summing
  5996. 4:18:13the result to this block here which will
  5997. 4:18:16exactly result in this uh um instruction
  5998. 4:18:20like we have done the matrix
  5999. 4:18:22multiplication separately and we added
  6000. 4:18:23it to the O Block so this is uh that's
  6001. 4:18:27why this argument is called the
  6002. 4:18:30accumulator all right so we have also
  6003. 4:18:32computed the output and then we save the
  6004. 4:18:36new estimation of the maximum for the
  6005. 4:18:39current iteration and it becomes Mi so
  6006. 4:18:41at the next we can use it to calculate
  6007. 4:18:44the correction
  6008. 4:18:45factor and then we have finished for the
  6009. 4:18:48current block and then we can move on to
  6010. 4:18:50the next block so we advance our K and V
  6011. 4:18:53pointers by one block of K and v um we
  6012. 4:18:58advance it differently because we know
  6013. 4:19:00that the V block is a pointer to a
  6014. 4:19:04tensor of shape let me write it here
  6015. 4:19:07this is a tensor of shape uh sequence
  6016. 4:19:11length head dim
  6017. 4:19:14so we need to increase the sequence
  6018. 4:19:15length by one KV uh the block size KV uh
  6019. 4:19:19while the K block is actually the K
  6020. 4:19:22transpose block so we need to and it is
  6021. 4:19:25transposed because we have exchanged the
  6022. 4:19:27strides and the shape so it is head
  6023. 4:19:33Dimension head Dimension sequence length
  6024. 4:19:36so we don't change the head Dimension we
  6025. 4:19:38just Advance the sequence length by
  6026. 4:19:40sequence uh block size KB so basically
  6027. 4:19:43we are just going to point to the next
  6028. 4:19:45block of K and to the next block of a
  6029. 4:19:47v I hope to you were able to follow the
  6030. 4:19:50algorithm of flash atation I try to use
  6031. 4:19:53the same names I try to use the more or
  6032. 4:19:55less the same logic and always writing
  6033. 4:19:56the formula that I am referring to so
  6034. 4:19:59hopefully you didn't get lost I think
  6035. 4:20:00the only difference that there is
  6036. 4:20:02between the flashh attention algorithm
  6037. 4:20:04as written on the paper and this code is
  6038. 4:20:05probably this Alpha which is the
  6039. 4:20:07correction factor but I hope it's easily
  6040. 4:20:10understandable anyway um then we just
  6041. 4:20:13return the O Block so O
  6042. 4:20:15Block Li I which is the um the
  6043. 4:20:20normalization factor for each row in the
  6044. 4:20:23current output block which is also a q
  6045. 4:20:26block because we are working with one Q
  6046. 4:20:28block independently from the other
  6047. 4:20:30programs and Mi is the maximum value for
  6048. 4:20:33each row which will be needed for the
  6049. 4:20:36backward pass because when in the
  6050. 4:20:38backward pass we will compute the Q quy
  6051. 4:20:41query multip by transport of the key
  6052. 4:20:42blck on the Fly we need to also apply
  6053. 4:20:45the soft Max but instead of recomputing
  6054. 4:20:46the stuff which we already computed
  6055. 4:20:48during the forward pass we just save
  6056. 4:20:50them and reuse them during the backward
  6057. 4:20:52pass which will save us some
  6058. 4:20:54computation um now I know it's time to
  6059. 4:20:57talk about the log some X trick because
  6060. 4:20:59we are going to use it so let's go back
  6061. 4:21:02to the old method so let's go here all
  6062. 4:21:05right so we have computed two calls of
  6063. 4:21:09this function in case we are working
  6064. 4:21:10with caal attention in case of the we
  6065. 4:21:13are Computing Cal attention we call this
  6066. 4:21:14function once to work with all the query
  6067. 4:21:17blocks that are to the left side of the
  6068. 4:21:19diagonal of the query key Matrix then we
  6069. 4:21:22do another call of this function to work
  6070. 4:21:24only with those blocks of keys that
  6071. 4:21:27exactly lie on the diagonal of the query
  6072. 4:21:29key uh
  6073. 4:21:31Matrix uh because in this case some of
  6074. 4:21:34the values need to be masked out and
  6075. 4:21:36some of them do not need to be masked
  6076. 4:21:38out moreover by doing this we can avoid
  6077. 4:21:42computer in the dot products for all
  6078. 4:21:44those values in the Cal m in the causal
  6079. 4:21:47case for which the key is index of the
  6080. 4:21:50key is higher than the index of the
  6081. 4:21:52query saving some computation because
  6082. 4:21:54anyway they will be resulting after the
  6083. 4:21:56soft Max in zeros and they will not
  6084. 4:21:58contribute to the output so it should be
  6085. 4:22:01faster uh okay now let's go back to the
  6086. 4:22:04this method here so calling method and
  6087. 4:22:07there is one last thing that we need to
  6088. 4:22:08do which is uh we need to compute the
  6089. 4:22:12log some exp and now I will show you
  6090. 4:22:14what is it so in order for the backward
  6091. 4:22:17pass to recompute the soft Max without
  6092. 4:22:19having to recalculate the normalization
  6093. 4:22:21factor and the maximum value for each
  6094. 4:22:23row we should be actually saving two
  6095. 4:22:25different stuff one is the maximum for
  6096. 4:22:27each row in the query block and one is
  6097. 4:22:30the normalization factor for each query
  6098. 4:22:32in the query block however there is a
  6099. 4:22:34trick and the trick is okay it's not
  6100. 4:22:37really called log some X trick because
  6101. 4:22:39the logm X trick is used for another
  6102. 4:22:41purpose but let's call it logm X trick
  6103. 4:22:44number two so um the logm X trick number
  6104. 4:22:47two is something as like this so let me
  6105. 4:22:50open the slides so when we do um query
  6106. 4:22:55multiply by transpose with the keys we
  6107. 4:22:57get a matrix that is made up of dot
  6108. 4:22:59products so something like this like
  6109. 4:23:02this is one dot product so let's call it
  6110. 4:23:04query one transpose the key1 query one
  6111. 4:23:08transpose the key2 this is a query two
  6112. 4:23:11transpose the key one one and this is
  6113. 4:23:13query 2 transpose the key2 then we need
  6114. 4:23:17to apply the soft Max right so the soft
  6115. 4:23:19Max is what is the let's write the
  6116. 4:23:21formula of the soft Max for each of
  6117. 4:23:23these vectors so this is a vector and
  6118. 4:23:25this is a vector because we applied it
  6119. 4:23:26by rows for each of these vectors it
  6120. 4:23:29will modify element wise each element as
  6121. 4:23:31follows so the soft Max of x i is equal
  6122. 4:23:35to the exponential of x i minus oh my
  6123. 4:23:40God I didn't leave enough space so let's
  6124. 4:23:42move this stuff here
  6125. 4:23:45back and this stuff here a little left
  6126. 4:23:49all right it will be the soft Max of um
  6127. 4:23:51the exponential of each element minus
  6128. 4:23:53the maximum for the current Vector to
  6129. 4:23:56which we are applying the soft
  6130. 4:23:59Max divided by the normalization factor
  6131. 4:24:02which is the summation over all possible
  6132. 4:24:04JS where n in this case is equal to two
  6133. 4:24:07because we have each Vector is made up
  6134. 4:24:08of two elements of the exponential of x
  6135. 4:24:12i- x
  6136. 4:24:14max now imagine we already have X Max
  6137. 4:24:20and we already have this summation in
  6138. 4:24:22the flashh alation algorithm in the
  6139. 4:24:23forward pass this stuff here is called
  6140. 4:24:25Li and this stuff here is called
  6141. 4:24:28Mi what we are going to save in the code
  6142. 4:24:31you can see here we are saving actually
  6143. 4:24:34not Mi and Li separately we will be
  6144. 4:24:37saving Mi I plus the logarithm of Li I
  6145. 4:24:42so we are going to save Mi plus the log
  6146. 4:24:47of Li I so what will happen is that when
  6147. 4:24:52we will um compute the um compute the
  6148. 4:24:56backward pass we need to recreate this
  6149. 4:24:57Matrix here on the Fly which means that
  6150. 4:24:59we need to recompute the query multiply
  6151. 4:25:01by the transpose of the keys and we to
  6152. 4:25:04um and then we should apply the softmax
  6153. 4:25:07to apply the softmax we should need this
  6154. 4:25:08stuff and this stuff here but we have
  6155. 4:25:11only this stuff here so so this is the
  6156. 4:25:13Mi plus the logarithm of Li so when we
  6157. 4:25:16Computing the softmax we will compute
  6158. 4:25:18the following so we will compute the
  6159. 4:25:20softmax as follows uh we will Define
  6160. 4:25:23let's call it a new softmax so let me
  6161. 4:25:25use another color
  6162. 4:25:28uh
  6163. 4:25:30here we will apply the softmax as
  6164. 4:25:33follows so
  6165. 4:25:36softmax of
  6166. 4:25:38XI let's call it the soft Max 2
  6167. 4:25:43because it's I don't want to confuse
  6168. 4:25:45soft Max is equal to the exponential of
  6169. 4:25:49each
  6170. 4:25:51element minus we will substract this
  6171. 4:25:53value here the one corresponding to the
  6172. 4:25:56current row to which we are applying the
  6173. 4:25:57soft Max so it will be the exponential
  6174. 4:26:00of x i minus m i minus the log of Li
  6175. 4:26:06I if we expand this expression this will
  6176. 4:26:09become the
  6177. 4:26:11exponential of
  6178. 4:26:12because exponential the sum of two expon
  6179. 4:26:15the exponential of the sum is equal to
  6180. 4:26:17the product of the two exponentials we
  6181. 4:26:19can also write it like this so it will
  6182. 4:26:21be the exponential of x i minus m i
  6183. 4:26:25divided
  6184. 4:26:26by the
  6185. 4:26:29exponential
  6186. 4:26:30um the exponential of the log of Li I
  6187. 4:26:35which guess what it is equal to the
  6188. 4:26:38exponential of x i minus m i
  6189. 4:26:42divided by Li I which is exactly the
  6190. 4:26:44normalization factor and we also have Mi
  6191. 4:26:47so instead of saving two values we save
  6192. 4:26:49only one value and when we apply it the
  6193. 4:26:51exponentials properties will take care
  6194. 4:26:54of actually also normalizing each value
  6195. 4:26:56to which we apply it um if you don't
  6196. 4:26:58remember the properties of the
  6197. 4:26:59exponential it is very simple so the
  6198. 4:27:01exponential of a MTI plus b is equal to
  6199. 4:27:06the exponential of a multiplied by the
  6200. 4:27:09exponential of B and the exponential of
  6201. 4:27:14a uh not exponential it's the
  6202. 4:27:18exponential a minus B is equal to the
  6203. 4:27:23exponential of a divided by the
  6204. 4:27:25exponential of B and this is the the
  6205. 4:27:29trick that we're using so that's why we
  6206. 4:27:30don't need to save two different values
  6207. 4:27:32we just need to save one value and then
  6208. 4:27:34when we apply it it will automatically
  6209. 4:27:36be taken care will take care of
  6210. 4:27:38normalizing because of the properties of
  6211. 4:27:40the
  6212. 4:27:40exponential all right let's move forward
  6213. 4:27:43so we have also created this um value
  6214. 4:27:46that we will use during the backward
  6215. 4:27:48pass now uh as you remember in the flash
  6216. 4:27:52attention algorithm we don't normalize
  6217. 4:27:54each block while Computing it we
  6218. 4:27:56normalize the output at the end and this
  6219. 4:27:59is exactly what we are going to do here
  6220. 4:28:02so we normalize the block at the end
  6221. 4:28:04after we have computed all the
  6222. 4:28:05normalization factors that we need for
  6223. 4:28:07all the rows that belong to the current
  6224. 4:28:09output
  6225. 4:28:10block um we save this Mi so we save it
  6226. 4:28:14um this Mi is what is the normalization
  6227. 4:28:18factor and the maximum for each row that
  6228. 4:28:22we will need for the backward pass so we
  6229. 4:28:23need to save it in a tensor that we will
  6230. 4:28:26use during the backward pass so we need
  6231. 4:28:27to understand which tensor is this and
  6232. 4:28:30it's the tensor that we called M which
  6233. 4:28:32is a tensor of a b size numb heads and
  6234. 4:28:35sequence length Dimensions so we need to
  6235. 4:28:37select the right point in this tensor to
  6236. 4:28:40select to where we should save this Mi
  6237. 4:28:43values uh so we need to select the right
  6238. 4:28:46B size index and the right number of uh
  6239. 4:28:48head
  6240. 4:28:49index uh so we advance this pointer by
  6241. 4:28:53the following offset which is M
  6242. 4:28:58plus um the index batch head because
  6243. 4:29:02each um index okay the index batch head
  6244. 4:29:06is what is the index of the current
  6245. 4:29:08program that includes information about
  6246. 4:29:11which head we are working working with
  6247. 4:29:12and which batch we are working with
  6248. 4:29:14because each of this um for each batch
  6249. 4:29:18and for each head we have a sequence
  6250. 4:29:21length we can skip n uh a number of
  6251. 4:29:25sequence length based on which index is
  6252. 4:29:29um okay what we are doing is basically
  6253. 4:29:31we are
  6254. 4:29:34skipping uh for each uh batch and for
  6255. 4:29:38each head we will have a sequence length
  6256. 4:29:40because each to token in the sequence
  6257. 4:29:43has a maximum value and each token in
  6258. 4:29:45the sequence will have a normalization
  6259. 4:29:47value So based on the current
  6260. 4:29:49combination of batch and head we can
  6261. 4:29:52skip a number of sequence length that
  6262. 4:29:54other programs will process so uh
  6263. 4:29:57because in this uh tensor we have the
  6264. 4:30:00sequence length as the last Dimension
  6265. 4:30:02and we have what is the combined index
  6266. 4:30:05of the batch size and number of head
  6267. 4:30:07size we can skip a number of sequence of
  6268. 4:30:10length based on the combined in index
  6269. 4:30:12which is given by the program index
  6270. 4:30:13number one which is the index batch head
  6271. 4:30:16that we have here and this is why we
  6272. 4:30:18skip here a sequence length number um
  6273. 4:30:22multiplied by the index batch head this
  6274. 4:30:25m is pointing to the
  6275. 4:30:27first uh element of the entire tensor so
  6276. 4:30:31we we are skipping the heads and the
  6277. 4:30:34batch based on the combined index index
  6278. 4:30:37batch head that this particular program
  6279. 4:30:39is working with and then we have off
  6280. 4:30:41Cube of skew is because each um of this
  6281. 4:30:46Kels the attention forward method will
  6282. 4:30:48work with one um query block uh each
  6283. 4:30:54query block has some indices for the
  6284. 4:30:57exact queries it includes and this is
  6285. 4:31:00given by off skew variable that you can
  6286. 4:31:02see here which is how many blocks of
  6287. 4:31:05queries we need to skip because they
  6288. 4:31:06will be processed by other programs plus
  6289. 4:31:09the range of queries that this
  6290. 4:31:10particular that Noti this that a
  6291. 4:31:13particular block of queries has so uh
  6292. 4:31:16imagine this particular program is
  6293. 4:31:18working with the queries that go from I
  6294. 4:31:21don't know from uh 12 to 16 then this
  6295. 4:31:24will be 12 13 14 15 so the normalization
  6296. 4:31:28factor and the maximum value for each
  6297. 4:31:30row we only have that for the this for
  6298. 4:31:34this indices of query queries so 12 13
  6299. 4:31:3714 and 15 and that's why we need to also
  6300. 4:31:40skip the number of queries that this
  6301. 4:31:42particular program works with which is
  6302. 4:31:44already included in this offset offs Q
  6303. 4:31:48variable all right so now we can store
  6304. 4:31:51the Mi so because we have the point to
  6305. 4:31:53which where it should be saved and we
  6306. 4:31:56can also store the output which was
  6307. 4:31:58computed of by our inner for Loop and
  6308. 4:32:01this guys is the forward step of the
  6309. 4:32:04attention flashh
  6310. 4:32:06attention now we should go forward which
  6311. 4:32:09is we should compute the backward path
  6312. 4:32:12we also have all the ingredients for
  6313. 4:32:13computing the backward pass because we
  6314. 4:32:15have already seen this trick which is
  6315. 4:32:17the logm X trick so we already know what
  6316. 4:32:20um how to use it to compute the query
  6317. 4:32:23key block during the backward pass on
  6318. 4:32:25the
  6319. 4:32:25Fly what we miss to understand the
  6320. 4:32:28backward pass well we need to understand
  6321. 4:32:29what is the first of all what is the
  6322. 4:32:31backward pass why do we even need a
  6323. 4:32:32backward pass we need to understand what
  6324. 4:32:34is the autograd of py torch how does it
  6325. 4:32:37work how to compute the gradient what is
  6326. 4:32:40the gradient how to compute do we need
  6327. 4:32:42to what is the Jacobian when Computing
  6328. 4:32:44the gradient on the backward pass do we
  6329. 4:32:45even need to compute that so we need to
  6330. 4:32:47derive all the formulas of the backward
  6331. 4:32:49pass by hand so if you are in for the
  6332. 4:32:51challenge let's continue all right so
  6333. 4:32:54now before looking at the flesh
  6334. 4:32:56attentions backward pass at at the
  6335. 4:32:59algorithm we need to understand why we
  6336. 4:33:01even need a backward pass and to
  6337. 4:33:03understand why we even need a backward
  6338. 4:33:04pass so before looking at the autograd
  6339. 4:33:06of P torch we should be looking at what
  6340. 4:33:09is what are derivatives what are
  6341. 4:33:11gradients what are jaian so that when we
  6342. 4:33:12talk about derivatives gradients and
  6343. 4:33:14jaian we don't feel lost so I will do a
  6344. 4:33:17very fast uh let's say rehearsal of what
  6345. 4:33:21these topics are now what is the
  6346. 4:33:24derivative when you have a function that
  6347. 4:33:25takes as input a real value and outputs
  6348. 4:33:28a real value we talk about derivatives
  6349. 4:33:31which is defined as follows the
  6350. 4:33:33derivative of the function with respect
  6351. 4:33:34to its variable uh X is defined as the
  6352. 4:33:38limit for a step size that goes to zero
  6353. 4:33:40of the function evaluated at X Plus H so
  6354. 4:33:44X plus the step size minus F evaluated
  6355. 4:33:47at The
  6356. 4:33:48X at x divided by the step size so
  6357. 4:33:52intuitively we are saying is the ratio
  6358. 4:33:54of how much the output change for a
  6359. 4:33:57small change for how much the input has
  6360. 4:33:59changed in the
  6361. 4:34:00function that this also gives you the
  6362. 4:34:02intuitive um intuition uh of why the
  6363. 4:34:07gradient is the derivative is also the
  6364. 4:34:10tells you the inclination of the tangent
  6365. 4:34:12line of the um to the function at the
  6366. 4:34:15point in which it's
  6367. 4:34:17evaluated I will use also the following
  6368. 4:34:19notation to denote the derivative so the
  6369. 4:34:23derivative I am used to write it as like
  6370. 4:34:25this so frime of X but it's also
  6371. 4:34:28possible to write it as D of f ofx with
  6372. 4:34:30respect to DX or D of Y where Y is the
  6373. 4:34:33output of the function with respect to X
  6374. 4:34:35and they are all equal to the same thing
  6375. 4:34:37which is the definition
  6376. 4:34:39above if we invert this form here and we
  6377. 4:34:42take H to the left side we can also
  6378. 4:34:45write the follows so if we want to
  6379. 4:34:48evaluate the function um at at the
  6380. 4:34:52position X+ H we can also evaluate it as
  6381. 4:34:56F Prime of H so the derivative of the
  6382. 4:35:00function in the point x multiplied by H
  6383. 4:35:03which is the step size plus f of x this
  6384. 4:35:07is actually also how we derive the ler
  6385. 4:35:09rule uh for computing the differential
  6386. 4:35:12equations but that's not the topic of
  6387. 4:35:13today so this H we can also call it
  6388. 4:35:17Delta X so f of x plus Delta X is more
  6389. 4:35:20or less because here we have a limit
  6390. 4:35:22that says when this only happens when H
  6391. 4:35:24is very very very small so that's why we
  6392. 4:35:26put this more or less approximately so f
  6393. 4:35:30of x plus Delta X is more or less equal
  6394. 4:35:33to frime of X multip by Delta X Plus F
  6395. 4:35:37ofx this you can also read it as follows
  6396. 4:35:40that if by inverting this formula um if
  6397. 4:35:45x changes by a little amount and this
  6398. 4:35:49little amount is Delta X how much y will
  6399. 4:35:53change y will change by this exact
  6400. 4:35:56amount which is the derivative of y with
  6401. 4:35:59respect to X so Dy with respect to DX
  6402. 4:36:02multiplied by how much X has changed so
  6403. 4:36:05this Dy DX tells us how much y will
  6404. 4:36:08change with a small change of x if we
  6405. 4:36:12multiply with the actual change of X it
  6406. 4:36:14will tell us by how exactly y will be
  6407. 4:36:17affected um I don't want to use stay too
  6408. 4:36:21much on this but I I would like to use
  6409. 4:36:24this intuition to introduce the chain
  6410. 4:36:27rule because imagine we have a function
  6411. 4:36:31of a function so imagine we have Z is
  6412. 4:36:33equal to F of G of
  6413. 4:36:35X we can think of X being mapped into a
  6414. 4:36:39variable y through the function G and
  6415. 4:36:41then y being mapped to into variable Z
  6416. 4:36:44through the function f if x changes by a
  6417. 4:36:47little bit and by a little bit I mean
  6418. 4:36:49Delta X how much y will change well y
  6419. 4:36:52will change by Delta Y what is Delta y
  6420. 4:36:55Delta Y is the derivative of y with
  6421. 4:36:57respect to X multiply by the step size
  6422. 4:36:59of
  6423. 4:37:00X but if y changes it will also affect Z
  6424. 4:37:04because there is a direct mapping
  6425. 4:37:06between Y and Z so how much Z will
  6426. 4:37:09change for a small change in y let's see
  6427. 4:37:11so if y changes from the old y by a
  6428. 4:37:15small step Delta y then Z will also
  6429. 4:37:18change by some Delta Z and this Delta Z
  6430. 4:37:21is the DZ of on Dy multip by Delta y if
  6431. 4:37:26we replace this Delta by with the Delta
  6432. 4:37:29y that we have computed in the
  6433. 4:37:30expression
  6434. 4:37:31above we arrive to the chain rule it
  6435. 4:37:34will tell us how Z will be affected so
  6436. 4:37:37this is Delta Z what is um the effect on
  6437. 4:37:41Z for a small change on X and it's the
  6438. 4:37:45product of the two derivatives one with
  6439. 4:37:49of Y with respect to S and one Z with
  6440. 4:37:51respect to Y and this is the chain rule
  6441. 4:37:53that we study in high school so it is if
  6442. 4:37:56you want to compute DZ on DX it is DZ on
  6443. 4:38:01Dy mtip Dy DX uh which is very intuitive
  6444. 4:38:05if you think about the following example
  6445. 4:38:08so you can think of Z as the price of uh
  6446. 4:38:11C
  6447. 4:38:12and X as the price of the oil how much
  6448. 4:38:16will the a small change in the price of
  6449. 4:38:19oil affect the price of a car well the
  6450. 4:38:22small change in the price of the oil
  6451. 4:38:24will affect for example a variable Y
  6452. 4:38:26which could be the price of uh
  6453. 4:38:29electricity so if how much the price of
  6454. 4:38:33electricity will affect the price of a
  6455. 4:38:36car it's through the derivative of the
  6456. 4:38:38price of electricity with respect to the
  6457. 4:38:40uh the price of the car with respect to
  6458. 4:38:42the um electricity so to to get the
  6459. 4:38:46effect of the price of oil on the price
  6460. 4:38:48of the car we just multiply the two
  6461. 4:38:50effects and this is the intuition behind
  6462. 4:38:52the chain rule anyway let's talk about
  6463. 4:38:55gradients so when we have a function
  6464. 4:38:57that as input takes a vector and
  6465. 4:39:00produces a scalar we talk not anymore
  6466. 4:39:02about derivatives we talk about
  6467. 4:39:05gradients so imagine we have a function
  6468. 4:39:08that takes as input a vector made up of
  6469. 4:39:11two Dimensions but n dimension in
  6470. 4:39:12general and it produces a scolar when do
  6471. 4:39:15we have to deal with this kind of
  6472. 4:39:17function for example loss functions loss
  6473. 4:39:19functions are something that are always
  6474. 4:39:22a scalar as output and as input they
  6475. 4:39:24take tensors so um for example imagine
  6476. 4:39:27the crossentropy loss it will take
  6477. 4:39:29a a sequence of tokens each tokens with
  6478. 4:39:33its own Logics and it will compute one
  6479. 4:39:35single number which is the
  6480. 4:39:37loss so how to uh View the effect on the
  6481. 4:39:42output with respect to the input in this
  6482. 4:39:44case well if x changes by a little
  6483. 4:39:47amount and this little amount is not
  6484. 4:39:49anymore a number but it's a vector so if
  6485. 4:39:51change the X the old the X Plus Delta x
  6486. 4:39:57uh is a vector sum then y will also be
  6487. 4:40:00affected by what y will be affected by d
  6488. 4:40:04y on DX multiply by Delta X however this
  6489. 4:40:07Delta X is not a number anymore it's a
  6490. 4:40:10vector because X1 may change by a little
  6491. 4:40:13bit X2 will change by a little bit X3
  6492. 4:40:15will change by a little bit X4 blah blah
  6493. 4:40:17blah until xn will change by a little
  6494. 4:40:18bit so this is actually a DOT product of
  6495. 4:40:22this Vector multiplied by this Vector
  6496. 4:40:25why a DOT product because y will be
  6497. 4:40:28affected by the change in X1 it will be
  6498. 4:40:31affected by the change in X2 it will be
  6499. 4:40:33change affected by the change in X3 up
  6500. 4:40:36to xn and each of the contribution of
  6501. 4:40:39the contribution of X1 will the partial
  6502. 4:40:42derivative of y with respect to X1
  6503. 4:40:44multiply by how much X1 has changed plus
  6504. 4:40:48the contribution FX2 will be the partial
  6505. 4:40:51derivative of y with respect to X2
  6506. 4:40:53multiply by how much X2 has changed blah
  6507. 4:40:56blah blah until the last uh contribution
  6508. 4:40:58of
  6509. 4:40:59xn so and the chain rule in this case
  6510. 4:41:02also applies in the same way as in the
  6511. 4:41:04scalar case so the formula does not
  6512. 4:41:06change also for the change rule here I
  6513. 4:41:08just want you to to to remind that in
  6514. 4:41:11this case we are talking about a
  6515. 4:41:13gradient and the gradient is just a
  6516. 4:41:15vector um made up of all the partial
  6517. 4:41:18derivatives of the output with respect
  6518. 4:41:21each of the input variables that are in
  6519. 4:41:23the input
  6520. 4:41:24Vector when we talk about a function
  6521. 4:41:27that have as input a vector and produces
  6522. 4:41:30a vector then we don't talk about
  6523. 4:41:33gradient anymore we talk about jacobians
  6524. 4:41:35so if our input X the input X of this
  6525. 4:41:39function changes by a little amount and
  6526. 4:41:41this Delta X is a vector then the output
  6527. 4:41:44y will also change and this output y
  6528. 4:41:47will change by a Delta y that is not a
  6529. 4:41:50number anymore it is a vector and this
  6530. 4:41:53Vector is the result of this quantity Dy
  6531. 4:41:56on DX multiplied by Delta X Delta X is a
  6532. 4:42:00vector so this one to be a vector it has
  6533. 4:42:04this one here has to be a matrix and
  6534. 4:42:06this Matrix is called the Jacobian it is
  6535. 4:42:09a matrix that has as many rows
  6536. 4:42:11later we will talk about the denotations
  6537. 4:42:13so it has as many rows as there are
  6538. 4:42:15output variables and as many columns as
  6539. 4:42:18there are input variables the first row
  6540. 4:42:21will be the partial derivative of the
  6541. 4:42:24first output variable with respect to
  6542. 4:42:26all the input variables the second row
  6543. 4:42:28will be the partial derivative of the
  6544. 4:42:31second output variable with respect to
  6545. 4:42:33all the input variables and the last row
  6546. 4:42:35will be the partial derivatives of the
  6547. 4:42:37last output uh variable with respect to
  6548. 4:42:40all the input variable in the input
  6549. 4:42:43Vector um now let's talk about notations
  6550. 4:42:47the Jacobian that I have written here is
  6551. 4:42:50is is written according to the uh
  6552. 4:42:52numerator layout this is called the
  6553. 4:42:55numerator layout and there is another um
  6554. 4:42:58convention called the oh not layout
  6555. 4:43:00sorry guys it's called the numerator
  6556. 4:43:02convention and there is another
  6557. 4:43:03convention called denominator convention
  6558. 4:43:05or notation in which um the rows are not
  6559. 4:43:10the
  6560. 4:43:11the number of rows is not the equivalent
  6561. 4:43:13to the number of output variables but
  6562. 4:43:16equal to the number of input variables
  6563. 4:43:18so um the fact that I have we we choose
  6564. 4:43:22to write the Jacobian as follows is
  6565. 4:43:24based on a convention you can also write
  6566. 4:43:28the the Jacobian according to the
  6567. 4:43:30denominator convention just by
  6568. 4:43:32transposing this Jacobian here and also
  6569. 4:43:34the formula for the chain rule changes
  6570. 4:43:36accordingly for now I want to keep the
  6571. 4:43:39formula for the chain rule just like the
  6572. 4:43:40one for the scolar case so that's why I
  6573. 4:43:43am using this notation here but later we
  6574. 4:43:45can change between one notation to the
  6575. 4:43:47other just by doing a
  6576. 4:43:49transposition okay now that we have
  6577. 4:43:51reviewed what is derivative what is a
  6578. 4:43:53gradient and what is a Jacobian let's
  6579. 4:43:56talk about um what happens when we take
  6580. 4:43:59derivatives with respect to tensors of a
  6581. 4:44:02tensor with respect to another tensor in
  6582. 4:44:04this case we talk about the Jacobian but
  6583. 4:44:06it's called the generalized Jacobian so
  6584. 4:44:09if we have the function that is add
  6585. 4:44:11input takes a tensor of DX
  6586. 4:44:15Dimensions where the first shape this is
  6587. 4:44:18kind of the shape of the tensor so the
  6588. 4:44:20first element of the shape is N1 the
  6589. 4:44:22second element of the shape of the input
  6590. 4:44:24Vector is N2 etc etc until n DX and it
  6591. 4:44:29produces an output tensor that has this
  6592. 4:44:31shape so M1 M2 blah blah blah m d y in
  6593. 4:44:36this case the formula for the chain rule
  6594. 4:44:39doesn't change and
  6595. 4:44:41if x changes by little amount so by
  6596. 4:44:45Delta X which is a
  6597. 4:44:47tensor y will also be affected by how
  6598. 4:44:50much by Dy on DX multip by Delta X and
  6599. 4:44:55this is a tensor product it will be a
  6600. 4:44:58Jacobian uh this is called generalized
  6601. 4:45:00Jacobian with the following shape so all
  6602. 4:45:03the dimensions of the output multiplied
  6603. 4:45:06by all the dimensions of the
  6604. 4:45:08input all right this is very abstract
  6605. 4:45:11for now we will see actually a concrete
  6606. 4:45:13case of this one because we will be
  6607. 4:45:15deriving the the gradient of the output
  6608. 4:45:18of a matrix
  6609. 4:45:20multiplication uh the the gradient of
  6610. 4:45:23the loss when Computing backward pass
  6611. 4:45:25with respect to each of the input of the
  6612. 4:45:26matrix multiplication operation and we
  6613. 4:45:28will do it also for the soft Max and we
  6614. 4:45:30will do it also for the attention so I
  6615. 4:45:32don't want to jump to too many topics I
  6616. 4:45:33just wanted us to get into the right
  6617. 4:45:35mindset so we know that derivatives when
  6618. 4:45:37we have scalar functions gradients when
  6619. 4:45:40the output is scolar input is a vector
  6620. 4:45:43Jacobian when the input and output are
  6621. 4:45:45both vectors generalized Jacobian when
  6622. 4:45:46the input and the output are tensors the
  6623. 4:45:50chain rule always works in the same way
  6624. 4:45:53all right let's talk about Auto autog
  6625. 4:45:56gradient I will do the scalar case and
  6626. 4:45:58then we will extend it to the tensor
  6627. 4:46:00case so imagine we have a very simple
  6628. 4:46:03computation graph why we have
  6629. 4:46:04computation graph because we are talking
  6630. 4:46:05about neural networks and neural
  6631. 4:46:07networks are nothing more than
  6632. 4:46:08computation graphs where we have some
  6633. 4:46:10input with we have some parameters and
  6634. 4:46:11we do some operations with this input
  6635. 4:46:13and parameters suppose that you have an
  6636. 4:46:15input a and this input a is multiplied
  6637. 4:46:18by a weight a parameter weight it's just
  6638. 4:46:21a scalar U and it produces an output y1
  6639. 4:46:25this y1 is then summed up with another
  6640. 4:46:27number called B1 and it produces Y2 this
  6641. 4:46:30Y2 is then raised to the power of two so
  6642. 4:46:32this Z to the^ of two is just the power
  6643. 4:46:34of two of the input and it produces Y3
  6644. 4:46:38and this Y3 becomes our loss function so
  6645. 4:46:41it's a scalar now uh what we uh want to
  6646. 4:46:45do to apply gradient descent is we want
  6647. 4:46:47to compute the gradient of the um loss
  6648. 4:46:50function with respect to each of the
  6649. 4:46:52input of this computation graph so each
  6650. 4:46:54of the leaves of these computation
  6651. 4:46:56graphs what are the leaves it's this
  6652. 4:46:58node here so the parameter nodes and the
  6653. 4:47:00input
  6654. 4:47:01nodes um and to do that there are two
  6655. 4:47:04ways one is if you have access to the uh
  6656. 4:47:09expression that relates Direct the input
  6657. 4:47:11to the uh uh output so the to the loss
  6658. 4:47:15then you can directly compute the the
  6659. 4:47:17gradient the derivative in this case
  6660. 4:47:19because it's not a gradient it's a
  6661. 4:47:20scalar versus scalar so in this case
  6662. 4:47:23imagine we want to compute the
  6663. 4:47:24derivative of the loss with respect to
  6664. 4:47:26W1 imagine we have access to the um
  6665. 4:47:29exact um expression that relates the W1
  6666. 4:47:33to uh to the five which is our loss we
  6667. 4:47:36can compute it as follows so we just
  6668. 4:47:38derive this expression with respect to
  6669. 4:47:40W1 which is two * because this is the
  6670. 4:47:43power of two of a function so it is two
  6671. 4:47:45multiplied by the function multiplied by
  6672. 4:47:48the the derivative of the content of
  6673. 4:47:50this function with respect to the
  6674. 4:47:51variable that we are deriving so it will
  6675. 4:47:54become the following expression there is
  6676. 4:47:57another way which is by using the chain
  6677. 4:47:59rule so we can use the derivative of
  6678. 4:48:02five with respect to Y W1 is the
  6679. 4:48:04derivative of I with respect to Y3 which
  6680. 4:48:08is the previous uh output of the
  6681. 4:48:10previous node then the derivative of 53
  6682. 4:48:12with respect to the previous the output
  6683. 4:48:14of the previous node so and then the
  6684. 4:48:17multiplied by the derivative of Y2 with
  6685. 4:48:19respect to the output of the previous
  6686. 4:48:21node and then the derivative of y1 with
  6687. 4:48:24respect to W1 if we do all this chain of
  6688. 4:48:27multiplication we will obtain the same
  6689. 4:48:29result and you can see that here this
  6690. 4:48:31stuff here is exactly equal to this
  6691. 4:48:33stuff
  6692. 4:48:34here by doing this procedure here we
  6693. 4:48:37will note something that is
  6694. 4:48:41I want to zoom out a little bit okay to
  6695. 4:48:43compute the the derivative of five with
  6696. 4:48:47respect to W1 we are doing all this
  6697. 4:48:50chain of multiplication but what is each
  6698. 4:48:53item in what is each um uh factor in
  6699. 4:48:57this sequence of multiplications well
  6700. 4:49:00this stuff here is nothing more than the
  6701. 4:49:02derivative of five with respect to Y2
  6702. 4:49:06these multiplications here are nothing
  6703. 4:49:08more than the derivative of five with
  6704. 4:49:10respect to to W uh to respect to y1 and
  6705. 4:49:14all of them combined are the derivative
  6706. 4:49:16of f with respect to W1 what pytorch
  6707. 4:49:20will do it will do the following pytorch
  6708. 4:49:23will do the backward pass because
  6709. 4:49:25pytorch knows what is the computation
  6710. 4:49:28graph that relates the output so the
  6711. 4:49:31loss function in this case and the
  6712. 4:49:34variable for which we want to compute
  6713. 4:49:35the gradient right now we are talking
  6714. 4:49:37about derivatives so uh it's not
  6715. 4:49:40gradient but the mechanism is exactly
  6716. 4:49:42the same so pytorch will say uh it will
  6717. 4:49:48py is like a person that knocks the door
  6718. 4:49:52of this operation and
  6719. 4:49:54says um hey
  6720. 4:49:58operation expon power of two if I give
  6721. 4:50:01you the gradient of the loss with
  6722. 4:50:04respect to Y3 which is one because loss
  6723. 4:50:06and Y3 are actually the same can you
  6724. 4:50:09give me the gradient of the loss with
  6725. 4:50:11respect to Y2 because a Pythor actually
  6726. 4:50:14does not Implement an autograd system in
  6727. 4:50:17in the sense that it does not know the
  6728. 4:50:19symbolic operations that led to the
  6729. 4:50:21output it just knows what are the
  6730. 4:50:24functions that computed the output and
  6731. 4:50:26each function has a function each
  6732. 4:50:28function is a class in Python that
  6733. 4:50:30implements two methods one is the
  6734. 4:50:32forward step and one is the backward
  6735. 4:50:34step the forward steps takes the input
  6736. 4:50:37so in this case Y2 and computes the
  6737. 4:50:38output Y3 the back First Step will take
  6738. 4:50:42the gradient of the loss with respect to
  6739. 4:50:45its output and needs to compute the
  6740. 4:50:47gradient of the loss with respect to its
  6741. 4:50:49input how can we do that well it's very
  6742. 4:50:53simple because pytorch will knock the
  6743. 4:50:55door as let me copy it this stuff here
  6744. 4:50:58otherwise it's not easy to go back and
  6745. 4:51:00forth
  6746. 4:51:02so okay and let's past it here pytorch
  6747. 4:51:05will knock the door of this function
  6748. 4:51:08here and will say hey if I give you
  6749. 4:51:11the loss of the Lo the the gradient of
  6750. 4:51:14the loss function with respect to your
  6751. 4:51:15output can you give me the gradient of
  6752. 4:51:18the loss function with respect to your
  6753. 4:51:19input yes the function can do it why
  6754. 4:51:22because of the chain rule this operator
  6755. 4:51:24here this function here can just do take
  6756. 4:51:27the loss uh the gradient of the loss
  6757. 4:51:29function with respect to its output
  6758. 4:51:31multiply it by the
  6759. 4:51:33Jacobian uh or in this case the
  6760. 4:51:36derivative of its output with respect to
  6761. 4:51:38its input and it will be equal to the
  6762. 4:51:40gradient of the loss with respect to its
  6763. 4:51:42input then pytorch will take this one
  6764. 4:51:44and knock the door at the next operator
  6765. 4:51:46which is this one this summation and
  6766. 4:51:48we'll say hey if I give you the gradient
  6767. 4:51:51of the loss with respect to your output
  6768. 4:51:54can you give me the gradient of the loss
  6769. 4:51:56with respect to your input yes this
  6770. 4:51:58operator can do it because this operator
  6771. 4:52:00just needs to apply the chain rule so it
  6772. 4:52:02will take the gradient of the loss with
  6773. 4:52:03respect to um to Y2 which is provided by
  6774. 4:52:06pytorch and by multiplying it with the
  6775. 4:52:10the Jacobian in this case it's the
  6776. 4:52:12derivative the derivative of the its
  6777. 4:52:14output with respect to its input it can
  6778. 4:52:16compute the uh the gradient of the loss
  6779. 4:52:18with respect to its input then pytorch
  6780. 4:52:21will take this output of this backward
  6781. 4:52:23pass and will knock the door of the next
  6782. 4:52:25operator which is this product and we
  6783. 4:52:28ask again the same question hey if I
  6784. 4:52:30give you the gradient of the loss with
  6785. 4:52:32respect to your output can you give me
  6786. 4:52:34the gradient of the loss with respect to
  6787. 4:52:35your input yes this will do the same
  6788. 4:52:38exact job it will take the gradient of
  6789. 4:52:40the loss with respect to the output
  6790. 4:52:42multiplied by the Jacobian of the output
  6791. 4:52:44with respect to the input and obtain the
  6792. 4:52:47gradient of the loss with respect to the
  6793. 4:52:49input and this is how py toch runs the
  6794. 4:52:51backward step it runs one operator at
  6795. 4:52:55the time backwards in the computation
  6796. 4:52:57graph knocking the door of each operator
  6797. 4:53:01and asking always the same question if I
  6798. 4:53:03give you the output the gradient of the
  6799. 4:53:04loss with respect to your output can you
  6800. 4:53:06give me the gradient of the loss with
  6801. 4:53:08respect to your input and each operator
  6802. 4:53:10will just apply the chain rule to to to
  6803. 4:53:13get this um to get this gradient to
  6804. 4:53:16calculate this gradient that pych needs
  6805. 4:53:18why pytorch cannot do it by itself
  6806. 4:53:20because pytorch does not do symbolic um
  6807. 4:53:23mathematics it does not have access to
  6808. 4:53:25the exact expression that each function
  6809. 4:53:27is Computing it just uses the function
  6810. 4:53:30as a blackbox that computes forward and
  6811. 4:53:33backward however with the Jacobian we
  6812. 4:53:36have a problem and let's see what is the
  6813. 4:53:38problem all right so up to now we have
  6814. 4:53:41been working with a compostition graph
  6815. 4:53:43that is made up of Scholars but the
  6816. 4:53:45things that we have said they work in
  6817. 4:53:47the scolar case but also in the tensor
  6818. 4:53:49case so let's go back see what is our
  6819. 4:53:52computation graph we have seen that
  6820. 4:53:54pytorch will go Operator by operator
  6821. 4:53:57asking always the same question if I
  6822. 4:53:59give you the gradient of the loss with
  6823. 4:54:00respect to your output can you compute
  6824. 4:54:02me the gradient of the loss with respect
  6825. 4:54:04to your input and each operator can just
  6826. 4:54:07apply the chain rule to compute that uh
  6827. 4:54:10imagine now that all of these operators
  6828. 4:54:12are working not with scolars but are
  6829. 4:54:14working with tensors which means that
  6830. 4:54:16the derivative of the output with
  6831. 4:54:18respect to the input of each operator is
  6832. 4:54:20not a derivative it will be a Jacobian
  6833. 4:54:23because the output will be a tensor a
  6834. 4:54:25generalized Jacobian and input will be a
  6835. 4:54:28tensor which means also that this
  6836. 4:54:30quantity here so the derivative of the
  6837. 4:54:32loss with respect to the input in this
  6838. 4:54:34case will not be a derivative it will be
  6839. 4:54:36a gradient because the output the loss
  6840. 4:54:38is a number always while the input in
  6841. 4:54:41this case y1 will be a tensor so number
  6842. 4:54:46output input is a tensor then we talk
  6843. 4:54:49about gradients so this will be a
  6844. 4:54:51gradient the and we will call it the
  6845. 4:54:53downstream gradient that the operator
  6846. 4:54:55needs to compute this will be the
  6847. 4:54:57Upstream gradient that pytorch will give
  6848. 4:54:59to the each of these operators so the
  6849. 4:55:02gradient of the loss with respect to the
  6850. 4:55:04output of each operator and each
  6851. 4:55:06operator needs to come up with this
  6852. 4:55:08Downstream gradient by using the
  6853. 4:55:11Jacobian however the Jacobian has a
  6854. 4:55:13problem let's see so uh imagine we are
  6855. 4:55:16implementing a simple operation that is
  6856. 4:55:19the matrix multiplication and the matrix
  6857. 4:55:21multiplication is takes as input X
  6858. 4:55:25tensor it multiplies it by a w Matrix
  6859. 4:55:28made up of parameters and produces a y
  6860. 4:55:30Matrix as output suppose that X is let's
  6861. 4:55:35call it n by D Matrix W is uh let's say
  6862. 4:55:40d by m
  6863. 4:55:42Matrix and so y will be a n by uh M
  6864. 4:55:49Matrix usually the input X is a sequence
  6865. 4:55:54of T of let's say vectors each of each
  6866. 4:55:58with d Dimensions so you can think of it
  6867. 4:56:01as a sequence of tokens each token is a
  6868. 4:56:03vector made up of the dimensions usually
  6869. 4:56:06we have many tokens so suppose that n
  6870. 4:56:09usually is at least
  6871. 4:56:111,24 at least in the most recent
  6872. 4:56:14language models we even have millions of
  6873. 4:56:16tokens actually so uh ND is also
  6874. 4:56:20actually quite big it usually it is at
  6875. 4:56:23least 1,24 also so also this one
  6876. 4:56:27is24 um D and M M is also at least 1024
  6877. 4:56:32so we can actually become 22 2048 let's
  6878. 4:56:35say so I I like the powers of two by the
  6879. 4:56:38way so the problem of the Jacobian is
  6880. 4:56:41this if we compute want to compute this
  6881. 4:56:43Downstream gradient by multiplying the
  6882. 4:56:45Upstream gradient with the Jacobian this
  6883. 4:56:48Jacobian matrix is huge because look at
  6884. 4:56:51the dimensions here this will be a
  6885. 4:56:53matrix that
  6886. 4:56:55is um it will be well n by
  6887. 4:56:59m multiplied so it will be a generalized
  6888. 4:57:03Jacobian so it will be a tensor that has
  6889. 4:57:05a shape n m uh and then the input is X
  6890. 4:57:10so it is n by D so how many elements it
  6891. 4:57:13will have well it will have
  6892. 4:57:161,24 multiplied by m which is
  6893. 4:57:20248 multip by 1024 multi by D which is
  6894. 4:57:261,24 so it is at least wow it's billions
  6895. 4:57:31more than 1 billion
  6896. 4:57:33elements so it is impossible actually to
  6897. 4:57:37materialize this Matrix here in the
  6898. 4:57:39memory because in the ram of the GPU
  6899. 4:57:41because it will be too
  6900. 4:57:43big so but we need to compute this down
  6901. 4:57:46screen gradient because pytorch needs it
  6902. 4:57:48to continue calculating the gradient uh
  6903. 4:57:50of the loss function with respect to
  6904. 4:57:52each of the nodes in the computation
  6905. 4:57:54graph so how can we proceed the first
  6906. 4:57:57thing that we should notice is that this
  6907. 4:57:59G ve this uh Jacobian is actually a
  6908. 4:58:02sparse Matrix and I want to show you why
  6909. 4:58:05it is a actually is a super super super
  6910. 4:58:07sparse Matrix because um if if you look
  6911. 4:58:10at the input what is the effect of the
  6912. 4:58:13input on the output the input is a
  6913. 4:58:16sequence of
  6914. 4:58:17tokens so this is the token number one
  6915. 4:58:20it's a vector of some Dimensions 1,24
  6916. 4:58:23dimensions then we have another token as
  6917. 4:58:25input then we have another tokens as
  6918. 4:58:27input then we have another tokens as
  6919. 4:58:29input and we multiply by the W Matrix
  6920. 4:58:32which is made up of some columns uh some
  6921. 4:58:36uh columns so this one is n by D
  6922. 4:58:40right yes and W is uh d by m so d by m
  6923. 4:58:47this will produce a matrix that is n by
  6924. 4:58:49m so it will be also a sequence of
  6925. 4:58:51tokens each made up of M Dimensions so
  6926. 4:58:55it will be a matrix like this so this
  6927. 4:58:57will be the first output token this will
  6928. 4:59:00be the second output token this will be
  6929. 4:59:02the third output token and this will be
  6930. 4:59:04the fourth output
  6931. 4:59:06token now this output row here
  6932. 4:59:10is the dotproduct of this input row with
  6933. 4:59:13all the columns so the derivative of
  6934. 4:59:17each of these Dimensions with respect to
  6935. 4:59:20the dimensions of all the other tokens
  6936. 4:59:22will be zero because they do not
  6937. 4:59:23contribute to this output so the
  6938. 4:59:27Jacobian will have zeros every time the
  6939. 4:59:31we are calculating the derivative of
  6940. 4:59:33this First Dimension with respect to any
  6941. 4:59:36other element of other tokens that's why
  6942. 4:59:40we always can come up with a better
  6943. 4:59:42formula for computing this Downstream
  6944. 4:59:44gradient that does not involve the
  6945. 4:59:46materialization of the Jacobian because
  6946. 4:59:48the M the Jacobian itself is sparse so
  6947. 4:59:51let's see how we can optimize this uh
  6948. 4:59:53computation without materializing the
  6949. 4:59:55Jacobian in the case of matrix
  6950. 4:59:56multiplication because we need it for
  6951. 4:59:58flesh
  6952. 5:00:00attention all right guys so before
  6953. 5:00:02proceeding to the backward uh watch the
  6954. 5:00:05formulas of the backward path of the
  6955. 5:00:06flesh attention uh let's look at how to
  6956. 5:00:09compute the gradient of the matrix
  6957. 5:00:11multiplication operation with respect to
  6958. 5:00:13its input so imagine we are create okay
  6959. 5:00:16Pythor already have actually how to
  6960. 5:00:18compute the the the the gradient of the
  6961. 5:00:22uh inputs of the matrix multiplication
  6962. 5:00:24with the gradient of the loss with
  6963. 5:00:25respect to the input of the matrix
  6964. 5:00:26multiplication operation but in Flash
  6965. 5:00:29attention we are creating a custom
  6966. 5:00:31kernel which means that the custom
  6967. 5:00:33kernel is fusing multiple operations
  6968. 5:00:35into one operation so when pyro will
  6969. 5:00:39knock the door of our operator it will
  6970. 5:00:41ask the our operator which is the Tron
  6971. 5:00:44attention operator that we have built
  6972. 5:00:46what is the gradient of the loss
  6973. 5:00:48function with respect to q k and V
  6974. 5:00:49because that's the input of our function
  6975. 5:00:52so if we look at the code that we have
  6976. 5:00:53built so far you can see that our trial
  6977. 5:00:56rotation will be a node in the
  6978. 5:00:58computation graph that Tak take takes as
  6979. 5:01:01input q k and V and produces an output
  6980. 5:01:05then pyro will give us the gradient of
  6981. 5:01:07the loss with respect to that output so
  6982. 5:01:09it will will give us d o so the
  6983. 5:01:11derivative of the loss with the gradient
  6984. 5:01:13of the loss with respect to O and then
  6985. 5:01:16we'll ask this class here so Tron
  6986. 5:01:19attention to compute the gradient of the
  6987. 5:01:21loss with respect to Q K and B because
  6988. 5:01:24we are fusing multiple operations
  6989. 5:01:26together so we are Computing on the Fly
  6990. 5:01:27the soft Max of query query multiply by
  6991. 5:01:29the transp of the key and then
  6992. 5:01:31multiplying doing the soft Max and
  6993. 5:01:32multiplying it by uh V to compute the
  6994. 5:01:36output uh we need to compute this
  6995. 5:01:38gradients internally to compute this um
  6996. 5:01:41the gradient of the inputs so because in
  6997. 5:01:44this operations that we are doing fusing
  6998. 5:01:46together there is a matrix
  6999. 5:01:48multiplication we need to derive by hand
  7000. 5:01:50the matrix multiplication uh the
  7001. 5:01:52gradient of the of the loss function
  7002. 5:01:55with respect to the input of the matrix
  7003. 5:01:56multiplication operation so that we can
  7004. 5:01:59uh provide it to P torch that's why we
  7005. 5:02:02need to derive this formula uh I will uh
  7006. 5:02:06derive it in the simp in a very simple
  7007. 5:02:08way and um
  7008. 5:02:11and then we will do it for the soft Max
  7009. 5:02:12as well because these are the two things
  7010. 5:02:14that we need to derive by hand to derive
  7011. 5:02:15the formula of The Flash attentions
  7012. 5:02:17backward
  7013. 5:02:18pass so let's start imagine we have a a
  7014. 5:02:23computation graph uh in od in the
  7015. 5:02:25computation graph called the matrix
  7016. 5:02:27multiplication and this node in the
  7017. 5:02:29computation graph is doing a matrix
  7018. 5:02:30multiplication so it is Computing the
  7019. 5:02:32following operation Y is equal to X
  7020. 5:02:36multiplied W now what py will give us as
  7021. 5:02:41input when Computing the backward path
  7022. 5:02:44of this node py torch will give us the
  7023. 5:02:46gradient of the loss so it will give us
  7024. 5:02:49DF with respect to Dy so the output of
  7025. 5:02:53this node and we ask us to compute the
  7026. 5:02:57gradient of the loss function so the
  7027. 5:02:59gradient of the loss function with
  7028. 5:03:01respect to DX and the gradient of the
  7029. 5:03:04loss function with respect to the W uh
  7030. 5:03:08the easiest one to work with and the one
  7031. 5:03:09that I will be showing and the other one
  7032. 5:03:11I will not show in the video but I will
  7033. 5:03:12attach the PDF slide on how it is
  7034. 5:03:14computed because they are very similar
  7035. 5:03:16in the way they are computed so I don't
  7036. 5:03:18want to make the video too long for
  7037. 5:03:20Unnecessary
  7038. 5:03:21reasons let's compute the gradient of
  7039. 5:03:25the uh loss function with respect to the
  7040. 5:03:29um input so with respect to
  7041. 5:03:32X all right so how to do that by hand
  7042. 5:03:35without materializing the Jacobian
  7043. 5:03:37because as we have seen we cannot just
  7044. 5:03:40use the chain rule by materializing the
  7045. 5:03:41Jacobian which would be the easiest way
  7046. 5:03:43because the Jacobian is very big Matrix
  7047. 5:03:45that cannot even fit in the memory of
  7048. 5:03:47the GPU so we need to find a smarter way
  7049. 5:03:51we exploit the fact that the Jacobian is
  7050. 5:03:53sparse so hopefully we will get formula
  7051. 5:03:55that does not involve the
  7052. 5:03:57materialization of a very big sparse
  7053. 5:03:59Jacobian let's see so uh let's see um
  7054. 5:04:03let's when dealing with this kind of
  7055. 5:04:06derivations I always recommend to make
  7056. 5:04:08some example tensors so suppose that
  7057. 5:04:12that X is a tensor of size let's say n
  7058. 5:04:16by
  7059. 5:04:18D and where n let's say n is equal to 1
  7060. 5:04:22and D is equal to let's say three and um
  7061. 5:04:27X the W is a tensor also or a matrix
  7062. 5:04:32with the shape let's say d by
  7063. 5:04:35m where m is equal to let's say 4
  7064. 5:04:40um and Y will have as a consequence the
  7065. 5:04:45shape n by
  7066. 5:04:48m so it will have the shape um well 1 by
  7067. 5:04:554 what pyto will give us pyto will give
  7068. 5:04:58us the following quantity so it will
  7069. 5:04:59give us this stuff here so the gradient
  7070. 5:05:02of the loss function with respect to the
  7071. 5:05:04output of this operator which is y so it
  7072. 5:05:07will give us a vector or a tensor
  7073. 5:05:10actually with the following Dimension
  7074. 5:05:12which is n by
  7075. 5:05:14m and we need to compute the gradient of
  7076. 5:05:18the loss function with respect to X
  7077. 5:05:21which should be a tensor of shape n by D
  7078. 5:05:24because um when dealing with the
  7079. 5:05:26gradient it always has the shape of the
  7080. 5:05:29input variable because it's the output
  7081. 5:05:32which is a scalar with respect to each
  7082. 5:05:34element in the input so it has the same
  7083. 5:05:36shape as the
  7084. 5:05:38denominator all right so uh when dealing
  7085. 5:05:41with these kind of problems I always
  7086. 5:05:43recommend to create example matrices and
  7087. 5:05:45then work out what happens to the output
  7088. 5:05:47and then try to work out the the the the
  7089. 5:05:51the the gradient Matrix so let's do it
  7090. 5:05:54so let's see that what is how is the
  7091. 5:05:56output computed well the output will be
  7092. 5:05:58a matrix that is 1
  7093. 5:06:02by4 computed as follows it will be the
  7094. 5:06:05input so 1 by3 so let's call the input X
  7095. 5:06:10X11
  7096. 5:06:12X12
  7097. 5:06:13x13 it will be multiplied by another
  7098. 5:06:16Matrix W that is has Dimension 3 by 4 so
  7099. 5:06:22it will be three rows by four columns so
  7100. 5:06:25it will be W1 1 W12
  7101. 5:06:30W13
  7102. 5:06:33w14 then w21 w22 w23
  7103. 5:06:39W2
  7104. 5:06:414 W3 1
  7105. 5:06:44w32
  7106. 5:06:46w33 W 3
  7107. 5:06:494 if we do this matrix multiplication it
  7108. 5:06:52will be well it will produce the
  7109. 5:06:54following Matrix that is okay this is
  7110. 5:06:56one row by three columns this is three
  7111. 5:06:59column three rows by four columns so the
  7112. 5:07:02output will be a matrix that is 1 by
  7113. 5:07:05four so one row by four columns so it
  7114. 5:07:08will be uh uh let me write it with a
  7115. 5:07:11smaller because otherwise it will never
  7116. 5:07:13fit here
  7117. 5:07:14so let's do it like this it will be X11
  7118. 5:07:19ultip by
  7119. 5:07:21w11 plus
  7120. 5:07:24X12 * by
  7121. 5:07:27w21 plus x13 *
  7122. 5:07:32w31 and this will be the first element
  7123. 5:07:34of the output the second element of the
  7124. 5:07:37output will be um
  7125. 5:07:41X11 with W12 X11 with
  7126. 5:07:46W12 plus
  7127. 5:07:49X12 with one two with
  7128. 5:07:54w22 plus
  7129. 5:07:56x13 with
  7130. 5:07:59w32 this will be the second element of
  7131. 5:08:01the output Matrix the third element of
  7132. 5:08:04the output Matrix will be let me move
  7133. 5:08:06this stuff on the left otherwise it will
  7134. 5:08:08never fit
  7135. 5:08:10so okay I think now it can fit this will
  7136. 5:08:14be X I need also to watch this one so
  7137. 5:08:16X11 with W13
  7138. 5:08:19X1 X11 with
  7139. 5:08:22W13 plus X1 2 with W 2 3 plus x 1 3 with
  7140. 5:08:31W3 3 and then we multiply the same row
  7141. 5:08:35with the last column so it will be X11
  7142. 5:08:40w14 + X12 W2 4 + X1 3 W3
  7143. 5:08:494 this will be the output uh y if we do
  7144. 5:08:54the matrix multiplication what pyto will
  7145. 5:08:56give us it will give us the gradient of
  7146. 5:08:58the
  7147. 5:08:59loss so it will give us Delta fi with
  7148. 5:09:02respect to Delta y because it's a
  7149. 5:09:05gradient it has the same shape as the
  7150. 5:09:07denominator so it has a shape that is
  7151. 5:09:091x4 let's call it because we don't know
  7152. 5:09:12what this value will be they will be
  7153. 5:09:14provided to us by pytorch let's just
  7154. 5:09:16give them generic name like
  7155. 5:09:20dy11
  7156. 5:09:22dy12
  7157. 5:09:24dy13 and
  7158. 5:09:27dy4 like
  7159. 5:09:29this now to compute the um uh the
  7160. 5:09:34downstream gradient that we need to
  7161. 5:09:36provide to py torure we should be
  7162. 5:09:37Computing the we should be m realizing
  7163. 5:09:39the jacoban which
  7164. 5:09:42is um which is uh okay let's write the
  7165. 5:09:46chain the chain rule formula so we need
  7166. 5:09:49to provide Delta fi to with respect to
  7167. 5:09:52Delta X which is equal to Delta fi with
  7168. 5:09:57respect to Delta y this is provided by
  7169. 5:09:59by torch multiplied by the Jacobian
  7170. 5:10:02which is Delta y with respect to Delta
  7171. 5:10:06X now instead of materializing this
  7172. 5:10:09Jacobian let's try to do this let's
  7173. 5:10:12materialize it now and let's do the
  7174. 5:10:14multiplication of these two L quantities
  7175. 5:10:16to see if something simplifies so this
  7176. 5:10:19stuff here will be Dy with respect to DX
  7177. 5:10:23which means the derivative of every
  7178. 5:10:26output y with respect to every input X
  7179. 5:10:30how many output we have we have four
  7180. 5:10:32elements as the output which is this
  7181. 5:10:34stuff here and we have three element as
  7182. 5:10:38input in the X
  7183. 5:10:40Matrix so it will be as follows I I
  7184. 5:10:43don't know how to let me copy it because
  7185. 5:10:46my screen is not big enough and I
  7186. 5:10:49remember that X is X11 and xx2
  7187. 5:10:53so uh Delta y with respect to Delta X
  7188. 5:10:58will have the following entries so the
  7189. 5:11:03uh y1 with respect to X11 and as you can
  7190. 5:11:07see y1 only has one X11 appearing as
  7191. 5:11:11multiplied by w11 so the derivative with
  7192. 5:11:14respect to X11 will be
  7193. 5:11:17w11 then y11 so this stuff with respect
  7194. 5:11:21to X12 it will be
  7195. 5:11:26w21 then X um y11 with respect to x13
  7196. 5:11:33will be
  7197. 5:11:35w31 the second row of this Matrix will
  7198. 5:11:37be the derivative
  7199. 5:11:39of the partial derivative of the second
  7200. 5:11:41output so w Y2 with respect to all the X
  7201. 5:11:46inputs which will be the derivative
  7202. 5:11:49partial derivatives of this stuff here
  7203. 5:11:50with respect to every X which is
  7204. 5:11:55W12 w22 I guess and
  7205. 5:12:01w32 now let me check if it's what I'm
  7206. 5:12:04doing is correct yes because I've
  7207. 5:12:05already done it so I can always double
  7208. 5:12:08check uh uh and then we have W the
  7209. 5:12:13partial derivatives of this stuff here
  7210. 5:12:15with respect to all the
  7211. 5:12:17X which is
  7212. 5:12:20W13
  7213. 5:12:23w23 and
  7214. 5:12:25w33 then the partial derivatives of the
  7215. 5:12:28last output so y4 with respect to all
  7216. 5:12:31the X which will be W
  7217. 5:12:35oh
  7218. 5:12:37w14 W2 4 and
  7219. 5:12:41w34 we obtain the following
  7220. 5:12:45Jacobian if um but this Jacobian as you
  7221. 5:12:49can see it's just equal to W
  7222. 5:12:53transposed so we don't need to
  7223. 5:12:55materialize the Jacobian we can just do
  7224. 5:12:57the multiplication of whatever uh
  7225. 5:13:00gradient pytorch is giving us multiply
  7226. 5:13:03it by W transposed and we will get the
  7227. 5:13:05downstream gradient so let me rewrite so
  7228. 5:13:09we know have we know what we are doing
  7229. 5:13:11so D on D DX is equal to
  7230. 5:13:16D with respect to Y multiplied by Dy on
  7231. 5:13:22DX but we have seen that Dy on DX is
  7232. 5:13:25just equal to W transposed so this is
  7233. 5:13:28equal to D on DX Dy multiplied by W
  7234. 5:13:34transposed and this gives us the
  7235. 5:13:36downstream gradient so in order to
  7236. 5:13:37provide the downstream gradient that
  7237. 5:13:39pytorch need we just need to take
  7238. 5:13:41whatever gradient pytorch will give us
  7239. 5:13:42multiply it by W transposed and it will
  7240. 5:13:45give us the gradient of the loss
  7241. 5:13:47function with respect to the input X of
  7242. 5:13:49the matrix
  7243. 5:13:50multiplication in the same way we can
  7244. 5:13:52also arrive to the formula for the
  7245. 5:13:55gradient of the loss function with
  7246. 5:13:56respect to W and it is equal to X
  7247. 5:14:01transposed multiplied by
  7248. 5:14:03Dy with respect to uh DW uh Dy
  7249. 5:14:10how to remember these formulas these are
  7250. 5:14:13there is a ponic rule which is um these
  7251. 5:14:17are the only possible ways for this to
  7252. 5:14:20have the shape of X and this to have the
  7253. 5:14:24shape of w because this ones this stuff
  7254. 5:14:27here will have the same shape of Y so it
  7255. 5:14:30will be
  7256. 5:14:32u n by m this stuff here will have shape
  7257. 5:14:37of w transpose W is is d by m so w
  7258. 5:14:40transpose should be M by
  7259. 5:14:44D and the resulting operation of this
  7260. 5:14:47matrix multiplication or tensor
  7261. 5:14:50multiplication will be n by D which is
  7262. 5:14:53exactly the same shape as
  7263. 5:14:57X in this case we will have that XT is
  7264. 5:15:01the transpose of T and it is uh n by D
  7265. 5:15:05so it's D by n
  7266. 5:15:09multiplied by D with respect to Dy which
  7267. 5:15:12is a gradient so it has the same shape
  7268. 5:15:14as the
  7269. 5:15:16denominator uh so it has uh n by
  7270. 5:15:22m uh and the output will have um shape d
  7271. 5:15:27by m which is exactly the um the shape
  7272. 5:15:31of w so if you to to remember them this
  7273. 5:15:35is the only way this shape work out
  7274. 5:15:37otherwise they don't work out so this is
  7275. 5:15:38a nimonic formula on how to remember how
  7276. 5:15:40to compute the gradient of the inputs of
  7277. 5:15:43a matrix multiplication given the
  7278. 5:15:45gradient of the loss with respect to the
  7279. 5:15:47output of the matrix multiplication and
  7280. 5:15:49the inputs to the matrix multiplication
  7281. 5:15:50are the input Matrix and the parameter
  7282. 5:15:52Matrix W now we need to derive the
  7283. 5:15:55gradient of the output of the softmax
  7284. 5:15:58with respect to the input of the softmax
  7285. 5:16:00because that's another operation that we
  7286. 5:16:02do in our fused attention because we are
  7287. 5:16:04fusing many operations together which is
  7288. 5:16:05matrix multiplication and the soft Max
  7289. 5:16:08so this is the second ingredient that we
  7290. 5:16:09need to understand the backward pass of
  7291. 5:16:11flash attention so let's do
  7292. 5:16:13it I will use to make this derivation I
  7293. 5:16:16will use the same notation as in the
  7294. 5:16:18flash attention paper so first of all
  7295. 5:16:21let's write the title of this stuff
  7296. 5:16:23which is the
  7297. 5:16:28gradient
  7298. 5:16:31through the soft
  7299. 5:16:37Max um the first operation that we do in
  7300. 5:16:40um during computation of the attention
  7301. 5:16:43is we we compute the product of the
  7302. 5:16:45query multipli by the transpose of the
  7303. 5:16:46keys we do in a block-wise ways it means
  7304. 5:16:49that we do it block by block but it
  7305. 5:16:50doesn't matter because the end result is
  7306. 5:16:52the same so we can also we can write s =
  7307. 5:16:55to Q multip by the transpose of the keys
  7308. 5:16:59and then we apply the soft Max to this
  7309. 5:17:01operation to the result of this
  7310. 5:17:03operation and we call this output P
  7311. 5:17:06which is the soft Max
  7312. 5:17:10of s and after the we have applied the
  7313. 5:17:14soft Max we take the output of the soft
  7314. 5:17:15Max we multiply it by V to obtain the
  7315. 5:17:18output so the output is equal to P
  7316. 5:17:20multiplied by
  7317. 5:17:22v um now we need to understand how to uh
  7318. 5:17:26because as I saw as I as I said before
  7319. 5:17:29pytorch autograd works in the following
  7320. 5:17:31way pytorch will treat our attention
  7321. 5:17:34computation as a black box so we will
  7322. 5:17:36have a computation graph like the
  7323. 5:17:38following
  7324. 5:17:39we will have a query input a key input
  7325. 5:17:43and a value input which are sequences of
  7326. 5:17:45tokens each one with some embedding
  7327. 5:17:48Dimension these are fed to some black
  7328. 5:17:51box called the
  7329. 5:17:53attention which is our implementation of
  7330. 5:17:55the attention which is the function that
  7331. 5:17:57we started coding before this will be
  7332. 5:18:00fed as input to this node in the
  7333. 5:18:02computation graph and the computation
  7334. 5:18:04graph will output an output tensor o
  7335. 5:18:09what pyro will give us pyro will give us
  7336. 5:18:11the gradient of the loss with respect to
  7337. 5:18:14the
  7338. 5:18:15output so as you remember py knocks the
  7339. 5:18:18door knocks the door at each operator
  7340. 5:18:21and says if I give you the gradient of
  7341. 5:18:24the loss with respect to your output can
  7342. 5:18:26you give me the gradient of the loss
  7343. 5:18:27with respect to your inputs and this is
  7344. 5:18:30what we need to figure out so giving the
  7345. 5:18:32gradient of the loss with respect to the
  7346. 5:18:34output we need to understand how to
  7347. 5:18:37compute the gradient of the loss
  7348. 5:18:39with respect to WQ the gradient of the
  7349. 5:18:42loss with respect to w k the gradient of
  7350. 5:18:45the loss with respect to w v however the
  7351. 5:18:49there is no direct connection between q
  7352. 5:18:51and o or k and o because there are two
  7353. 5:18:54intermediate operation so one there is a
  7354. 5:18:56first a matrix multiplication then there
  7355. 5:18:58is a softx then there is an additional
  7356. 5:18:59matrix multiplication however we have
  7357. 5:19:01tools that allow us to understand how
  7358. 5:19:04the gradient propagates through multiple
  7359. 5:19:06operations when they are applied in
  7360. 5:19:07sequence and that's called The Chain
  7361. 5:19:10rule however we have seen that applying
  7362. 5:19:12the chain rule in its naive way by
  7363. 5:19:15materializing the Jacobian is invisible
  7364. 5:19:17so we need to understand how to apply
  7365. 5:19:20the chain rule without materializing the
  7366. 5:19:22Jacobian and that's what we are going to
  7367. 5:19:24figure out for one of the operations
  7368. 5:19:26inside of this attention computation
  7369. 5:19:28which is the softmax and that's why we
  7370. 5:19:30are going to do this derivation which I
  7371. 5:19:32promise is the last one that we will do
  7372. 5:19:34and then we will finally go to code the
  7373. 5:19:36backward path of fles attention we
  7374. 5:19:39cannot proceed directly to coding the
  7375. 5:19:40backward pass of The Flash attention
  7376. 5:19:41because if we look at the formulas on
  7377. 5:19:43how it is computed we will not
  7378. 5:19:45understand how the um the derivation
  7379. 5:19:48comes
  7380. 5:19:49out okay now we can
  7381. 5:19:52start so let me delete this stuff delete
  7382. 5:19:55and imagine for Simplicity now we apply
  7383. 5:19:59the soft Max to a uh rowwise to this s
  7384. 5:20:03Matrix so each row is soft maxed
  7385. 5:20:07independently from the others
  7386. 5:20:09so let's see what happens to one single
  7387. 5:20:11row of this Matrix and for Simplicity I
  7388. 5:20:15we call it s so s is uh a single row of
  7389. 5:20:20the S Matrix I could also call it s of I
  7390. 5:20:24but if I do it like this we will have to
  7391. 5:20:26carry over the index I okay guys just
  7392. 5:20:30just do it we will carry over the index
  7393. 5:20:32all right so let's call SI one row of
  7394. 5:20:35the S Matrix so SI is equal to Let's
  7395. 5:20:38let's say it's the in tensor notation py
  7396. 5:20:41tensor notation it would be like this so
  7397. 5:20:43from The Matrix S so from the tensor s
  7398. 5:20:47we take the I row and all the columns
  7399. 5:20:50this is the definition of Si I know it's
  7400. 5:20:52very ugly notation but it helps you
  7401. 5:20:54understand and this is a vector of size
  7402. 5:20:57and
  7403. 5:20:59dimensions uh we apply the soft Max to
  7404. 5:21:01this uh vector and we will obtain an
  7405. 5:21:04output vector and we call it Pi Pi is
  7406. 5:21:08equal to the uh soft Max soft Max of Si
  7407. 5:21:15so as we have seen the soft Max
  7408. 5:21:16operation does not change the shape of
  7409. 5:21:18the input it just change element wise
  7410. 5:21:21each number um so it the output will
  7411. 5:21:24also be a vector of size R to the power
  7412. 5:21:27of n now
  7413. 5:21:30um what is the soft Max so the soft Max
  7414. 5:21:33is defined as follows the soft Max
  7415. 5:21:39of uh well p i j so the J element of the
  7416. 5:21:44p i Vector is equal to the exponential
  7417. 5:21:50of the J element of the SI
  7418. 5:21:54Vector divided by a nor normalization
  7419. 5:21:58factor that is computed as follows uh
  7420. 5:22:01with uh let's say not J let's use K in
  7421. 5:22:05this case not even K let's use l
  7422. 5:22:09is equal to 1 up to n of e to the power
  7423. 5:22:13of s i
  7424. 5:22:16l all right so uh first of all you may
  7425. 5:22:21be wondering the soft Max that we are
  7426. 5:22:24that we apply during the forward pass of
  7427. 5:22:26the computation of the attention is not
  7428. 5:22:28really this softmax because in if you
  7429. 5:22:30remember what we applied before we were
  7430. 5:22:33applying the soft Marx where each of the
  7431. 5:22:35argument of the exponential is reduced
  7432. 5:22:38by the maximum element in the vector to
  7433. 5:22:40which we appli the soft Max so it was
  7434. 5:22:43more or less like this so s i minus SI
  7435. 5:22:47Max so the maximum element in the SI J
  7436. 5:22:51SI
  7437. 5:22:52vector and also the argument of the
  7438. 5:22:54denominator was reduced by Si
  7439. 5:22:58Max
  7440. 5:23:00however we also proved that this stuff
  7441. 5:23:03here is equivalent to the standard soft
  7442. 5:23:06Max without this reduction in the
  7443. 5:23:07argument because this reduction in the
  7444. 5:23:09argument is only added because we want
  7445. 5:23:13to make it numerically safe to compute
  7446. 5:23:15but there is it's equivalent to do it
  7447. 5:23:18without from a mathematical point of
  7448. 5:23:20view on the computer of course it will
  7449. 5:23:23be become numerically unstable but from
  7450. 5:23:25a mathematical point of view it is the
  7451. 5:23:27same thing which also means that doesn't
  7452. 5:23:31doesn't matter how you comput the
  7453. 5:23:33forward pass if it's equivalent to
  7454. 5:23:36another mathematical definition you can
  7455. 5:23:37always use the other mathematical
  7456. 5:23:39definition to compute the backward pass
  7457. 5:23:41it will result in the same value if you
  7458. 5:23:44didn't understand what I said let me
  7459. 5:23:45give you a more simple example which is
  7460. 5:23:48um imagine you have a uh do you remember
  7461. 5:23:52the formula from high school this one so
  7462. 5:23:55Co cosine of s of X Plus sin 2 of X is
  7463. 5:24:02equal to one now imagine we compute uh
  7464. 5:24:06an output Y is equal to cosine 2 of X
  7465. 5:24:11and then we need to compute the
  7466. 5:24:13derivative
  7467. 5:24:14of y with respect to X it doesn't matter
  7468. 5:24:19if you compute it as the derivative of
  7469. 5:24:23cosine squared of X with respect to X or
  7470. 5:24:28if you compute it as the derivative of 1
  7471. 5:24:33- sin 2 of X with respect to to X
  7472. 5:24:39because they will result in exactly the
  7473. 5:24:41same result uh because the two
  7474. 5:24:43definitions are equivalent and this is
  7475. 5:24:45why we don't need to add this um this
  7476. 5:24:48factor in the exponential uh because the
  7477. 5:24:50two definitions are equivalent
  7478. 5:24:52mathematically we just use the
  7479. 5:24:54numerically save one because when
  7480. 5:24:55computed on the on the computer we need
  7481. 5:24:57something that is numerically save uh
  7482. 5:25:00stable that will not
  7483. 5:25:02overflow all right now um what do we
  7484. 5:25:06want to obtain
  7485. 5:25:08so we want to obtain the uh the gradient
  7486. 5:25:12of the loss with respect to the input
  7487. 5:25:15Vector of the soft Max which is the SI
  7488. 5:25:17Vector given the gradient of the loss
  7489. 5:25:21with respect to the output of the
  7490. 5:25:23softmax which is the pi
  7491. 5:25:26Vector multi and we can obtain that with
  7492. 5:25:30the chain rule multiply that by the
  7493. 5:25:34Jacobian Pi with respect to uh s
  7494. 5:25:41now we uh the chain R is always valid
  7495. 5:25:45let's see what does this Jacobian look
  7496. 5:25:47like um all right so this Jacobian will
  7497. 5:25:52be the pi with respect to Delta
  7498. 5:25:58SII uh well we need to do it let's look
  7499. 5:26:02at what each element in this jacoban
  7500. 5:26:04will look like so the J element with
  7501. 5:26:07respect to to the let's say the K
  7502. 5:26:10element so we are
  7503. 5:26:13um we are Computing the
  7504. 5:26:18the we are looking at what each element
  7505. 5:26:22in this Jacobian will look like which is
  7506. 5:26:24what is the Jacobian it's each element
  7507. 5:26:27in the out in the numerator of the
  7508. 5:26:29Jacobian derived with respect to each
  7509. 5:26:32element in the denominator of the
  7510. 5:26:34Jacobian uh in this uh fraction here so
  7511. 5:26:38we are saying for each element in the
  7512. 5:26:40output Vector derived with respect to
  7513. 5:26:43each element in the input Vector this is
  7514. 5:26:45the what we are writing here so what is
  7515. 5:26:48how is the output Vector obtained well P
  7516. 5:26:52J we know that it is equal to by the
  7517. 5:26:54definition of the softmax is obtained as
  7518. 5:26:56follows so e to the power of s
  7519. 5:27:01j divided by the normalization factor
  7520. 5:27:07let's call it l
  7521. 5:27:10is equal to 1 to n e to the power
  7522. 5:27:15of uh s i
  7523. 5:27:19l uh all derived with respect to s i
  7524. 5:27:25k i k so what we are trying to do is we
  7525. 5:27:29know that the P Vector is suppose it's a
  7526. 5:27:31vector with the three elements so this
  7527. 5:27:33is a p one this is well P11
  7528. 5:27:381 one P1 2 and
  7529. 5:27:42p13 the S Vector will be a vector also
  7530. 5:27:45with the three elements so it will be
  7531. 5:27:47the
  7532. 5:27:48S11 S12 and
  7533. 5:27:52s13 what we are trying to do is
  7534. 5:27:54calculate what the Jacobian will be the
  7535. 5:27:56derivative of this one with respect to
  7536. 5:27:58all the input Vector then then the
  7537. 5:28:01second row of the Jacobian will be the
  7538. 5:28:02derivative of this one with respect to
  7539. 5:28:04each of this input element then the
  7540. 5:28:06third row of the Jacobian will be this
  7541. 5:28:08stuff here with respect to derived with
  7542. 5:28:10respect to each of the input element of
  7543. 5:28:12the S Vector we are trying to understand
  7544. 5:28:15what does the generic element in this
  7545. 5:28:17Jacobian look like based on the J date
  7546. 5:28:20element of the output Vector so this J
  7547. 5:28:22index refers to the output vector and
  7548. 5:28:24the K element in the input
  7549. 5:28:27Vector all right so what can happen when
  7550. 5:28:31we do this uh jacoban is that we have a
  7551. 5:28:36this one here is the derivative of a
  7552. 5:28:39fraction of two functions and we know
  7553. 5:28:42from high school that the derivative of
  7554. 5:28:44the fraction of two functions is as
  7555. 5:28:46follows so the derivative oops the
  7556. 5:28:50derivative let me write like this of f
  7557. 5:28:54of x with respect to G of X Prime is
  7558. 5:29:00equal to with respect to X by the way is
  7559. 5:29:03equal
  7560. 5:29:04to uh F Prime oops
  7561. 5:29:09of x * by G of x minus uh G Prime of x f
  7562. 5:29:16of
  7563. 5:29:18x all divided by the uh G of x to the
  7564. 5:29:23power of 2 like this now let's apply it
  7565. 5:29:26here so this will become here we will
  7566. 5:29:29have two cases either the variable that
  7567. 5:29:32we are deriving with respect to so this
  7568. 5:29:34s i k has the same index as the variable
  7569. 5:29:38being derived so either we are doing P11
  7570. 5:29:42with respect to S11 or we are doing P11
  7571. 5:29:45with respect to something else that has
  7572. 5:29:46not the same index so like P11 with
  7573. 5:29:49respect to S12 or s13 so there are two
  7574. 5:29:51cases that we need to consider suppose
  7575. 5:29:53that we are deriving P11 with respect to
  7576. 5:29:56S11 or we are deriving p12 with respect
  7577. 5:29:58to S12 or we are deriving p13 with
  7578. 5:30:00respect to s13 so we are deriving the
  7579. 5:30:03element of the output with respect to
  7580. 5:30:06the same element in the input with the
  7581. 5:30:08same
  7582. 5:30:09index so in this case the this um this
  7583. 5:30:14uh derivative will look like the
  7584. 5:30:16following so it's the derivative of f so
  7585. 5:30:21the numerator with respect to the
  7586. 5:30:23denominator that has the same index so
  7587. 5:30:25we are saying that in this
  7588. 5:30:27case uh J is equal to K
  7589. 5:30:33so uh the numerator with respect to SI J
  7590. 5:30:37with respect to uh e to the power of s j
  7591. 5:30:40with respect to s j will be e to the
  7592. 5:30:43power of s j so because e to the power
  7593. 5:30:47of X1 with respect to X1 will be e to
  7594. 5:30:50the power of X1 so this is equal to I am
  7595. 5:30:53reducing the size
  7596. 5:30:55now e to the power of s i j then we need
  7597. 5:31:00to multiply that by the denominator of
  7598. 5:31:03the fraction which is this summation
  7599. 5:31:06here so the summation
  7600. 5:31:08over all possible
  7601. 5:31:11L of e to^ of s i
  7602. 5:31:15l uh minus the derivative of the
  7603. 5:31:19denominator with respect to the variable
  7604. 5:31:22being derived so this denominator is the
  7605. 5:31:25sum of all the exponentials of all the
  7606. 5:31:27input elements if we derive it with
  7607. 5:31:30respect to one particular input element
  7608. 5:31:32there will be at least one term that
  7609. 5:31:34contains that input element and so the
  7610. 5:31:37the all the other terms will result in
  7611. 5:31:39zero so the only derivative that will
  7612. 5:31:41survive will be the e to the power of s
  7613. 5:31:43i k with respect to s i
  7614. 5:31:46k so we write minus e to the power of Si
  7615. 5:31:51i
  7616. 5:31:56k multiplied by the numerator which is e
  7617. 5:31:59to the^ of Si
  7618. 5:32:02J all this divided by the denominator to
  7619. 5:32:07the power of two which is this summation
  7620. 5:32:10here so L = to 1 up to n e^ of s i
  7621. 5:32:16l all to the power of two and this stuff
  7622. 5:32:20here will be equal to well we can see
  7623. 5:32:23that the this two term this one and this
  7624. 5:32:25one have a one term factor in common
  7625. 5:32:28which is e to the power of s j so we can
  7626. 5:32:30collect that so e to the power of s i j
  7627. 5:32:36multiplied by the
  7628. 5:32:45summation minus e to the power of s i
  7629. 5:32:50k all this divided by the denominator uh
  7630. 5:32:54which is the power of two of this stuff
  7631. 5:32:56here so let me just copy and paste it
  7632. 5:32:58which is let me rotate it also because I
  7633. 5:33:00don't know why I always write
  7634. 5:33:03little
  7635. 5:33:05little yeah all right and this stuff
  7636. 5:33:08here is equal to well uh we can separate
  7637. 5:33:13the two terms so we can separate this
  7638. 5:33:15term here and this term here because the
  7639. 5:33:18denominator is to the power of
  7640. 5:33:20two so we can write it also as e to the
  7641. 5:33:23power of s
  7642. 5:33:25j mided by the denominator so which is
  7643. 5:33:30summation of l = 1 up to n e to the^ of
  7644. 5:33:34s i
  7645. 5:33:35l uh multiplied by this stuff here so
  7646. 5:33:41this stuff here divided by the same
  7647. 5:33:44denominator so there's summation of l =
  7648. 5:33:481 up to n e to the^ of s i
  7649. 5:33:52l minus E to the^ of s i
  7650. 5:33:56k i Am s i k divided by the same uh
  7651. 5:34:03denominator
  7652. 5:34:08s i
  7653. 5:34:10l now this one can be written as this
  7654. 5:34:14stuff here is nothing more than the
  7655. 5:34:16output element P J because this one is
  7656. 5:34:19just the soft Max applied to the SI J
  7657. 5:34:22element which we know that the output of
  7658. 5:34:25the softmax applied to the SI element is
  7659. 5:34:27called P because it's one element of the
  7660. 5:34:29output Vector which we called P so this
  7661. 5:34:32stuff here is equal to p i
  7662. 5:34:35j multiplied by
  7663. 5:34:38this stuff here will be equal to 1 minus
  7664. 5:34:41this stuff here what is this stuff here
  7665. 5:34:43is the output of the soft Max appli to
  7666. 5:34:46the s i k element so it will be p i k so
  7667. 5:34:50it is equal to 1 minus p i
  7668. 5:34:56k okay and this is in the case the the
  7669. 5:35:00the variable with respect to which we
  7670. 5:35:03derive has the same index as the
  7671. 5:35:05numerator in this uh fraction
  7672. 5:35:08here uh in this derivative here uh the
  7673. 5:35:12other case is when the two variables so
  7674. 5:35:15the the output the index of the output
  7675. 5:35:18with respect to the index of the input
  7676. 5:35:20are not the same in this case we will
  7677. 5:35:23have another case so we will have that
  7678. 5:35:25J uh let me write it again so this stuff
  7679. 5:35:31here hope I can copy it all
  7680. 5:35:34without in the other case in which s is
  7681. 5:35:38not equal to
  7682. 5:35:40J uh not s it's j not equal to K so J is
  7683. 5:35:46not equal to K what
  7684. 5:35:48happens in this case it will be well uh
  7685. 5:35:52the derivative of the numerator because
  7686. 5:35:55we need to apply again this formula here
  7687. 5:35:56so derivative of the numerator with
  7688. 5:35:58respect to something that is not the
  7689. 5:36:00same variable it will be zero because
  7690. 5:36:02it's like Computing the derivative e to
  7691. 5:36:05the^ of X1 with respect to X X2 it will
  7692. 5:36:08be zero so it will be zero so all the
  7693. 5:36:11first term here will become zero no
  7694. 5:36:14matter what is g of x minus the
  7695. 5:36:17derivative of the denominator of this
  7696. 5:36:20fraction here with respect to the
  7697. 5:36:22variable SI
  7698. 5:36:24K uh G Prime of s i k so this is all the
  7699. 5:36:29variable in the input and we are
  7700. 5:36:31deriving it with respect to one
  7701. 5:36:33particular variable of the input so only
  7702. 5:36:35one item in the summation will survive
  7703. 5:36:38so it will be the item s i
  7704. 5:36:40k so it will be e to the power of s i k
  7705. 5:36:47multiplied by f of x which is the
  7706. 5:36:50numerator in this fraction which is e to
  7707. 5:36:52the power oh we forgot a minus e to the
  7708. 5:36:55power of s
  7709. 5:36:58j uh let me see if I forgot something
  7710. 5:37:01all divided by the denominator of this
  7711. 5:37:04fraction here to the power of two
  7712. 5:37:07so it is equal to the
  7713. 5:37:10summation l = 1 up to n of e to the
  7714. 5:37:13power of s i l all to the power of
  7715. 5:37:19two uh I believe I didn't forget
  7716. 5:37:21anything so let's continue so here also
  7717. 5:37:25we can see that this one here is because
  7718. 5:37:29okay let's separate it minus E to the^
  7719. 5:37:32of s i k divided by the summation l = 1
  7720. 5:37:39up to n of e^ of s i l multiplied by e^
  7721. 5:37:45of s i j divided by the summation l = 1
  7722. 5:37:51up to n of e to the power of s i
  7723. 5:37:56l this stuff here is nothing more than
  7724. 5:37:59the soft Max appli to the K element of
  7725. 5:38:01the SI Vector this one here is nothing
  7726. 5:38:04more than the softmax applied to the J
  7727. 5:38:06element of the s I Vector so we know
  7728. 5:38:09what these are we know that we call them
  7729. 5:38:13P minus p i k p i
  7730. 5:38:18j so in the end we have two cases one is
  7731. 5:38:24the derivative of this stuff here looks
  7732. 5:38:27like the
  7733. 5:38:29following each item in the Jacobian
  7734. 5:38:31looks like the following when the
  7735. 5:38:33numerator and the denominator have the
  7736. 5:38:35same index so J equal to K this stuff
  7737. 5:38:39here is equal to now this notation here
  7738. 5:38:42is wrong so I shouldn't be writing it
  7739. 5:38:45with equal sign but doesn't matter guys
  7740. 5:38:46it's we are doing a
  7741. 5:38:49little um okay so p i
  7742. 5:38:52j p i j multiplied by 1 minus p i k let
  7743. 5:38:59me check yes the other Cas is when the J
  7744. 5:39:02is not equal to k then this stuff here
  7745. 5:39:05let me write it like this
  7746. 5:39:08will be equal to minus p i k MTI p i
  7747. 5:39:16j now that we know what the two typical
  7748. 5:39:19cases of this Jacobian look like let's
  7749. 5:39:22actually look at what this Jacobian look
  7750. 5:39:24like in The Matrix
  7751. 5:39:26form so this Jacobian will look like the
  7752. 5:39:31following it will be a matrix that is
  7753. 5:39:33more or less like the following it will
  7754. 5:39:36be an n byn Matrix where n is the size
  7755. 5:39:39of the input vector and the output
  7756. 5:39:42vector and here the first element of the
  7757. 5:39:46Jacobian as you saw as you remember uh
  7758. 5:39:49the first row of the Jacobian in the
  7759. 5:39:51numerator convention is the uh
  7760. 5:39:54derivative of the first output with
  7761. 5:39:56respect to all the input so this first
  7762. 5:39:59term here will be the derivative of P11
  7763. 5:40:02with respect to
  7764. 5:40:05S11 so in this case J and K match so we
  7765. 5:40:08know that it will be equal to P1 1 * 1 -
  7766. 5:40:14P11 the second element to the right of
  7767. 5:40:17this one so the element one two will be
  7768. 5:40:19uh the derivative of p12 with respect to
  7769. 5:40:23uh sorry the P11 with respect to S12 the
  7770. 5:40:26J and K do not match so we will be in
  7771. 5:40:29this case here so it will be minus
  7772. 5:40:32P11
  7773. 5:40:34p12 the third element you can check it
  7774. 5:40:37by yourself it will be minus P1 1 p13
  7775. 5:40:42blah blah blah until the end which will
  7776. 5:40:44be - P11
  7777. 5:40:48p1n the second row of this Jacobian will
  7778. 5:40:51be uh will look like this so it will be
  7779. 5:40:54the derivative of p12 with respect to
  7780. 5:40:56S11 the J and K do not match so we are
  7781. 5:41:00in this case here so it will be minus P1
  7782. 5:41:042 P11
  7783. 5:41:07then the next element it will be the
  7784. 5:41:10derivative of p12 with respect to S12 so
  7785. 5:41:13J and K match so we are in the first
  7786. 5:41:15case so it will be P1 2 * 1 minus
  7787. 5:41:21p12 then this stuff here will be equal
  7788. 5:41:24to then the third element will be minus
  7789. 5:41:27P1 2 with respect to
  7790. 5:41:29p13 blah blah blah and until we arrive
  7791. 5:41:33to the last one which is minus P1 2 with
  7792. 5:41:36respect to P1 n not with respect to
  7793. 5:41:38multiply
  7794. 5:41:39by and all the elements like this until
  7795. 5:41:42the last row the last row will be the
  7796. 5:41:44the first element of the last row will
  7797. 5:41:45be the derivative of the uh last output
  7798. 5:41:50element with respect to the first input
  7799. 5:41:52element so it will be the derivative of
  7800. 5:41:54p1n with respect to S11 so um the two
  7801. 5:41:59indices do not match so we are in the
  7802. 5:42:01second case so it will be minus P1 n
  7803. 5:42:07P11 this will be minus P1 n p12 etc etc
  7804. 5:42:14etc let me do also the third element
  7805. 5:42:16since we are here so minus P1 n P1 3 etc
  7806. 5:42:21etc etc until the last element of the
  7807. 5:42:24last row which will be minus
  7808. 5:42:28p1n P1 N I
  7809. 5:42:31guess oh no that's wrong guys because
  7810. 5:42:34the two indices match so it should be
  7811. 5:42:37p1n multiplied 1 minus
  7812. 5:42:41p1n this is what the Jacobian will look
  7813. 5:42:44like let's see if we can find a better
  7814. 5:42:47um uh how to generate this Jacobian with
  7815. 5:42:50some pattern
  7816. 5:42:52recognition let's write it in a
  7817. 5:42:54different way first of all the thing
  7818. 5:42:56first thing that we can notice is that
  7819. 5:42:57this Jacobian is symmetric so you can
  7820. 5:42:59see that this element is equal to this
  7821. 5:43:01element if you expand the third row you
  7822. 5:43:03will see that it's equal to this element
  7823. 5:43:05this one on the top right corner is
  7824. 5:43:07equal to the one in the top bottom left
  7825. 5:43:09corner um so this Matrix is
  7826. 5:43:13symmetric the second thing that we can
  7827. 5:43:15notice is that only the element in the
  7828. 5:43:18diagonal are different they have an
  7829. 5:43:21additional term because you can look at
  7830. 5:43:24this element here so let me write this
  7831. 5:43:28element here can also be written as
  7832. 5:43:31P11 minus P11 * by P11 the second
  7833. 5:43:37element here in the second uh row so
  7834. 5:43:41second diagonal element of this Matrix
  7835. 5:43:43is p12 minus p12 * p12 so this the
  7836. 5:43:50element on the diagonal actually look
  7837. 5:43:51like just like the other elements they
  7838. 5:43:53just have an additional
  7839. 5:43:55term which is P11 in the first diagonal
  7840. 5:43:59element p12 in the second diagonal
  7841. 5:44:02element so we can also say that this
  7842. 5:44:06Matrix here is the product of all the
  7843. 5:44:09possible combinations of P J with p i
  7844. 5:44:13k which you we can obtain with an outer
  7845. 5:44:17product or even with the product of one
  7846. 5:44:20column with the transpose of the same
  7847. 5:44:22column so if you do one column Vector
  7848. 5:44:26for example imagine p is a column vector
  7849. 5:44:29and you do p multiplied by PT you obtain
  7850. 5:44:32all the possible combinations of
  7851. 5:44:33products of these two vectors because
  7852. 5:44:35this will be one
  7853. 5:44:38I can do a simple case so P11 P1 let's
  7854. 5:44:40call it P2
  7855. 5:44:42P3 uh multiplied by the row
  7856. 5:44:46Vector P1 P2 P3 this will generate all
  7857. 5:44:51the possible uh combinations of products
  7858. 5:44:53between P1 and the P the first vector
  7859. 5:44:56and the second Vector because this will
  7860. 5:44:58be a 3X one this is 1 by3 so it will be
  7861. 5:45:01generated 3x3 vector and it will be uh
  7862. 5:45:04equal to P1 P1
  7863. 5:45:08uh P1 P2 P1 P2 P1 P3 etc etc etc
  7864. 5:45:15moreover we can see that in the diagonal
  7865. 5:45:18of the Matrix we have this additional
  7866. 5:45:21term this additional term P1 in the
  7867. 5:45:25first diagonal element p p12 in the
  7868. 5:45:28second diagonal element p13 in the third
  7869. 5:45:30diagonal element uh I actually call it
  7870. 5:45:33P1 it's wrong because I should call it
  7871. 5:45:36Pi I that's why I didn't want to bring
  7872. 5:45:37the I uh indices so it's not really P1
  7873. 5:45:40it's should be Pi I Pi Pi I Pi because
  7874. 5:45:45we are doing it for the generic I Pi
  7875. 5:45:48Vector so let me fix the indices p i n p
  7876. 5:45:55I3 uh this is
  7877. 5:46:01one one one
  7878. 5:46:04one Pi I and pi
  7879. 5:46:08okay so this is Pi
  7880. 5:46:11Pi Pi Pi Pi Pi Pi I Pi I
  7881. 5:46:17okay we can obtain um so we can write
  7882. 5:46:21the this
  7883. 5:46:22um this Jacobian here also as the
  7884. 5:46:26diagonal matrix that in the diagonal has
  7885. 5:46:30all the element of the pi I
  7886. 5:46:32Vector minus the P Vector multiplied by
  7887. 5:46:36the transpose of itself so with itself
  7888. 5:46:39but transposed because we need all the
  7889. 5:46:42elements to be kind of a combination of
  7890. 5:46:44one element of p with it with another
  7891. 5:46:46element of p plus only on the diagonal
  7892. 5:46:49we need some this additional term which
  7893. 5:46:51are the elements of p and all the
  7894. 5:46:53elements of the the the output of this P
  7895. 5:46:56multipli by P transposed are negated
  7896. 5:46:58that's why we need this minus sign so if
  7897. 5:47:01you look at the flashh attention paper
  7898. 5:47:02they give you this formula here they say
  7899. 5:47:04that if Y is equal to the soft
  7900. 5:47:09Max of X then the
  7901. 5:47:14Jacobian uh will look like the following
  7902. 5:47:17will be um
  7903. 5:47:20diagonal of Y minus y y transposed where
  7904. 5:47:26Y is
  7905. 5:47:28um
  7906. 5:47:30the is a column
  7907. 5:47:32Vector all right guys I know this has
  7908. 5:47:34been long so let's take a pause and we
  7909. 5:47:37are going to now um uh code finally
  7910. 5:47:40first of all let's check the mathematics
  7911. 5:47:42of the backward path of Flesh attention
  7912. 5:47:44we will see it briefly I will not do any
  7913. 5:47:47more derivation but I will explain it
  7914. 5:47:50and then we finally switch to coding it
  7915. 5:47:52so let's
  7916. 5:47:53go all right guys now finally we can see
  7917. 5:47:57the um the backward path of the flashh
  7918. 5:47:59attention so we will be looking at the
  7919. 5:48:02algorithm and if you look at the the the
  7920. 5:48:05appendix of the flesh attention p paper
  7921. 5:48:07you will see this part b.2 where they
  7922. 5:48:09derive the backward pass step by step
  7923. 5:48:12now I don't want to do all the s all the
  7924. 5:48:15steps of this derivation because it's
  7925. 5:48:17going to be too long but I want to give
  7926. 5:48:19you all the tools necessary to
  7927. 5:48:21understand it now let's start from what
  7928. 5:48:25kind of um
  7929. 5:48:27uh how to say conventions they are using
  7930. 5:48:31uh notations they are using in this
  7931. 5:48:33paper so the first thing that we need to
  7932. 5:48:35rehearse is the naming of what is what
  7933. 5:48:39is the name of each
  7934. 5:48:40Matrix uh as you know in the forward
  7935. 5:48:43attention in the forward pass we do the
  7936. 5:48:45query multiplied by the transpose of the
  7937. 5:48:47key and the output of this we call it s
  7938. 5:48:50then we apply the soft Max to this s
  7939. 5:48:52Matrix and it becomes the P Matrix the
  7940. 5:48:55soft marks is applied by rows then we
  7941. 5:48:58talk take this P Matrix and we multiply
  7942. 5:49:00by a v Matrix to obtain the output of
  7943. 5:49:02the
  7944. 5:49:03attention
  7945. 5:49:05um let's look at for example how the
  7946. 5:49:08computation of the I row of the output
  7947. 5:49:12is computed based on the P Matrix and
  7948. 5:49:14the V Matrix so we can understand this
  7949. 5:49:16kind of notation that they are using
  7950. 5:49:17here in the paper because the way I read
  7951. 5:49:20this formula here is the E row of the
  7952. 5:49:23output which is a column Vector because
  7953. 5:49:26in when we write in um in mathemat in
  7954. 5:49:28linear algebra whenever we write the
  7955. 5:49:30name of a vector it is always by
  7956. 5:49:33convention a column Vector but the
  7957. 5:49:36origin of this particular Vector is
  7958. 5:49:38actually a row of the output Matrix
  7959. 5:49:41let's try to understand what is the
  7960. 5:49:44output uh row of a matrix in a matrix
  7961. 5:49:48multiplication now um so that we can
  7962. 5:49:51understand how to go from here to here
  7963. 5:49:53um so let's write a generic matrix
  7964. 5:49:56multiplication for example an a matrix
  7965. 5:49:59let's say that it is the
  7966. 5:50:02following and we only write one row
  7967. 5:50:05actually let me Zoom again and I want to
  7968. 5:50:08write smaller so we have enough space so
  7969. 5:50:11we make a matrix that has a row let's
  7970. 5:50:14call it A1 A2
  7971. 5:50:17A3 and then we multiply this will be a
  7972. 5:50:21matrix with many rows like the this one
  7973. 5:50:23because we want to study the effect only
  7974. 5:50:26of one row and we multiply it by another
  7975. 5:50:29Matrix let's call it this one is the
  7976. 5:50:31Matrix a and it has I don't know let's
  7977. 5:50:34say n rows by three columns then we
  7978. 5:50:39should have another Matrix B with three
  7979. 5:50:42columns and some number of um three rows
  7980. 5:50:46and some number of column let's say four
  7981. 5:50:48columns so we call the first uh row
  7982. 5:50:52let's call
  7983. 5:50:54it let me Zoom more so it's
  7984. 5:50:58b11
  7985. 5:51:00B12 B1 3
  7986. 5:51:04b14 then this one should be B2 2 1
  7987. 5:51:08B22
  7988. 5:51:09b23
  7989. 5:51:11B24 this should be b31
  7990. 5:51:16b32 uh
  7991. 5:51:18b33 B3 4 Etc I know I am not very
  7992. 5:51:23rigorous in my notation I should have
  7993. 5:51:25called all these elements with the
  7994. 5:51:27capital letter a and the capital letter
  7995. 5:51:29B so this is the notation that you use
  7996. 5:51:31when referring to single item of a a
  7997. 5:51:34matrix but please forgive me for this so
  7998. 5:51:38the output of this matrix multiplication
  7999. 5:51:40will be another Matrix that is n
  8000. 5:51:44by4 so it will be n by 4 so we will have
  8001. 5:51:48four columns for each uh row of the
  8002. 5:51:53output I want to write the output in a
  8003. 5:51:56different way so I want to write it as
  8004. 5:51:59follows as a vector only so the first
  8005. 5:52:02output row as a vector and want to
  8006. 5:52:05understand what is is each dimension of
  8007. 5:52:07this Vector so because otherwise I don't
  8008. 5:52:10have enough space to write it here so
  8009. 5:52:12the uh first uh let's write it so let's
  8010. 5:52:16call it o I want to write what is O of
  8011. 5:52:20one which is the first row of the output
  8012. 5:52:24but written as a column Vector so o of
  8013. 5:52:28one will be here we should use the small
  8014. 5:52:32letter O of one should be a vector where
  8015. 5:52:36the First Dimension is the dot product
  8016. 5:52:39of this stuff here so the first row of
  8017. 5:52:41the a matrix with the First Column of
  8018. 5:52:44the B Matrix so the first uh let's say
  8019. 5:52:48Dimension will be A1 with
  8020. 5:52:53b11 uh I should also call this one a11
  8021. 5:52:56a12
  8022. 5:52:59actually and a13 so A1
  8023. 5:53:043 uh because we have many rows in the a
  8024. 5:53:06matrix so let me use the correct naming
  8025. 5:53:09so this will be a11 with b11 a11
  8026. 5:53:14b11 plus
  8027. 5:53:17a12 * by
  8028. 5:53:20B21 plus
  8029. 5:53:23a13 with
  8030. 5:53:26b31 and this will be the first dimension
  8031. 5:53:29of the first row of the output Matrix
  8032. 5:53:32o the second dimension of the first row
  8033. 5:53:36of the output Matrix o will be the
  8034. 5:53:38dotproduct of this row of the a matrix
  8035. 5:53:41with the second column of the B Matrix
  8036. 5:53:44and let me write here B so it will be
  8037. 5:53:49a11
  8038. 5:53:52B12 plus
  8039. 5:53:54a12
  8040. 5:53:56B22 plus
  8041. 5:53:59a13 b
  8042. 5:54:0232 the third dimension will be a11
  8043. 5:54:08B1
  8044. 5:54:093 plus A1 2 B2
  8045. 5:54:143 plus A1 3
  8046. 5:54:18b33 the fourth dimension will be
  8047. 5:54:22a11 uh
  8048. 5:54:25b14 + A1 2 b 2 4 plus A1 3 B 3
  8049. 5:54:344 now this is the output the first
  8050. 5:54:37output row of the O Matrix and it's a
  8051. 5:54:40vector called o1 and these are this is
  8052. 5:54:43the first dimension of this Vector this
  8053. 5:54:45is the second this one is the third and
  8054. 5:54:46this is the fourth dimension and each of
  8055. 5:54:48this stuff here is one
  8056. 5:54:51scalar um so the
  8057. 5:54:54output o1 which is the first row of the
  8058. 5:54:58output Matrix can also be written
  8059. 5:55:02as the first element as you can see in
  8060. 5:55:06is a sum of many vectors where the first
  8061. 5:55:10element is
  8062. 5:55:12a11 Multiplied let me use a smaller uh
  8063. 5:55:15this one but I want to use a smaller I
  8064. 5:55:18can't change the size
  8065. 5:55:20here okay doesn't matter so as you can
  8066. 5:55:22see here there is A1 multiplying a
  8067. 5:55:25different B number every time so this is
  8068. 5:55:29b11 B12 B13 b14 what is b11 B12 B13 b14
  8069. 5:55:34it is the first row of the B Matrix so
  8070. 5:55:37it is equal to B uh 1 and all the
  8071. 5:55:41dimensions of the first row then plus
  8072. 5:55:46then we have the element
  8073. 5:55:48a12 multiplied by B21 B22 b23 Etc and
  8074. 5:55:54this is uh the second row of the B
  8075. 5:55:56Matrix so we use the tensor rotation of
  8076. 5:56:00py torch to describe this row which is a
  8077. 5:56:03b uh two and all the dimensions of
  8078. 5:56:07B2 uh so it looks this is a vector
  8079. 5:56:10scalar product and
  8080. 5:56:14plus uh
  8081. 5:56:17a13 multiplied by B uh
  8082. 5:56:213 and all the dimensions of P3 this one
  8083. 5:56:25can also be written
  8084. 5:56:27as um the
  8085. 5:56:30summation over all possible I that go
  8086. 5:56:33from 1 to three where 1 to 3 is how many
  8087. 5:56:37uh uh columns there are in the a
  8088. 5:56:41matrix uh of
  8089. 5:56:44a i
  8090. 5:56:46j uh well
  8091. 5:56:48A1 let's call let's call this one J
  8092. 5:56:51actually sorry let's call it
  8093. 5:56:54J equal to one and let's call this the
  8094. 5:56:58generic e row of the output Matrix will
  8095. 5:57:02be a i1 a I2 and a I3 each one
  8096. 5:57:08multiplied by the corresponding Row in
  8097. 5:57:11the B Matrix so we can write it as a i j
  8098. 5:57:17multiplied by B uh J where BJ is the uh
  8099. 5:57:23a row of
  8100. 5:57:25B uh we can also write it like this to
  8101. 5:57:29indicate that this is a vector and this
  8102. 5:57:31is exactly what they do here so the
  8103. 5:57:34output in the output Matrix when we do
  8104. 5:57:37the multiplication P multipli by V the E
  8105. 5:57:40row of the output Matrix we call it oi
  8106. 5:57:45which is a vector but by notation it is
  8107. 5:57:47a column Vector where the elements of
  8108. 5:57:50this column Vector are actually the
  8109. 5:57:52elements of the E row of O uh this is
  8110. 5:57:56only by notation guys uh is equal to the
  8111. 5:58:00E row of P so the E row of the Matrix
  8112. 5:58:03that is on the left in the matrix
  8113. 5:58:05multiplication multiply by all the
  8114. 5:58:07columns of the V Matrix which can also
  8115. 5:58:10be written as the summation over all the
  8116. 5:58:12elements of the I row of P so all the
  8117. 5:58:15elements of the I row of the first
  8118. 5:58:18Matrix the one on the left in the matrix
  8119. 5:58:20multiplication multiplied by each Vector
  8120. 5:58:24in the v Matrix where the J Matrix here
  8121. 5:58:26in V is each row of the V Matrix
  8122. 5:58:31so and P J can also be written as um p
  8123. 5:58:35is what is um the the output of the soft
  8124. 5:58:39Max so as you know the output of the
  8125. 5:58:41soft Max is e to the power of the
  8126. 5:58:43element input of the softmax what is the
  8127. 5:58:46element input of the softmax is the
  8128. 5:58:48query multiplied by the transpose of the
  8129. 5:58:49keys so it's a DOT product between one
  8130. 5:58:51query and one key and that's why you
  8131. 5:58:53have this stuff here in the exponential
  8132. 5:58:56so this is the first step in
  8133. 5:58:58understanding this derivation another
  8134. 5:59:00thing that we have studied so far is how
  8135. 5:59:02to derive the uh backward path of the
  8136. 5:59:05matrix multiplication
  8137. 5:59:06and of the soft Max so now let's use it
  8138. 5:59:10in the matrix multiplication let's
  8139. 5:59:12rehearse the formula so the if given a
  8140. 5:59:15matrix multiplication that is y = to X
  8141. 5:59:18multiplied w we know that given the
  8142. 5:59:22gradient of the loss function with
  8143. 5:59:24respect to Y so the output of this
  8144. 5:59:26operation we know how to derive the
  8145. 5:59:28gradient of the loss with respect to one
  8146. 5:59:30of the input of this function which is
  8147. 5:59:32the x or W to get the gradient with
  8148. 5:59:36respect to X we need to take the
  8149. 5:59:38Upstream gradient so the the gradient
  8150. 5:59:41with respect to the output multiply by
  8151. 5:59:43the transpose of WT and to get the
  8152. 5:59:46gradient with respect to w we need to do
  8153. 5:59:49the XT so the input transposed
  8154. 5:59:53multiplied by the upstreaming gradient
  8155. 5:59:55this one is the formula that we didn't
  8156. 5:59:57derive and this one is the formula that
  8157. 5:59:59we derived but how to derive them is
  8158. 6:00:01exactly the same
  8159. 6:00:03procedure in attention we are doing the
  8160. 6:00:08last product that we are doing is O
  8161. 6:00:10equal to P multiplied by V what pyo will
  8162. 6:00:14give us as input during the backward
  8163. 6:00:16pass is the gradient of the loss with
  8164. 6:00:19respect to the output and we need to use
  8165. 6:00:21this gradient of the loss with respect
  8166. 6:00:22to the output of the attention to derive
  8167. 6:00:25the gradient of the loss with respect to
  8168. 6:00:27Q with respect to K and with respect to
  8169. 6:00:30V so that it can then be used by the
  8170. 6:00:32operators in the backward pass in the in
  8171. 6:00:36computation graph in the operations
  8172. 6:00:38before okay so but in order to arrive to
  8173. 6:00:42the gradient with respect to query key
  8174. 6:00:44and value we need to derive the gradient
  8175. 6:00:46with respect to each intermediate
  8176. 6:00:49operation so the last operation that we
  8177. 6:00:52do is O equal to P multiplied by V so
  8178. 6:00:55the gradient with respect to O of the
  8179. 6:00:58loss with respect to V given the
  8180. 6:01:00gradient of the loss with respect to O
  8181. 6:01:04it is exactly like Computing the
  8182. 6:01:06gradient of um the of the loss with
  8183. 6:01:08respect to X in a matrix multiplication
  8184. 6:01:11and we know that it is equal to the PT
  8185. 6:01:15so just by analogy guys so this is our
  8186. 6:01:17reference point and I am just changing
  8187. 6:01:18the names here and you should understand
  8188. 6:01:21what is the analogy here so um the
  8189. 6:01:24gradient of the loss with respect to V
  8190. 6:01:26which is the Matrix on the right which
  8191. 6:01:28is like Computing it with respect to to
  8192. 6:01:30W it is equal to just like this formula
  8193. 6:01:33here so the transpose of the Matrix on
  8194. 6:01:35the left multiplied by the Upstream
  8195. 6:01:37gradient which in the paper they write
  8196. 6:01:40it as this so DV is equal to PT
  8197. 6:01:43multiplied by d o and it's the formula
  8198. 6:01:45that you say you can see here the other
  8199. 6:01:48derivation is how to derive the gradient
  8200. 6:01:50with respect to DP DP is just like
  8201. 6:01:53deriving the gradient of the loss with
  8202. 6:01:55respect to the Matrix that is on the
  8203. 6:01:57left side of the matrix multiplication
  8204. 6:01:59so it is just like deriving the gradient
  8205. 6:02:01of the loss with respect to X in the
  8206. 6:02:04reference uh formulas
  8207. 6:02:07which is equal to the Upstream gradient
  8208. 6:02:09multiplied by the transpose of the other
  8209. 6:02:11Matrix which in the notation of the
  8210. 6:02:13paper they write it as DP is equal to d
  8211. 6:02:15o multili by V transposed and it's this
  8212. 6:02:18formula here how they compute this Stu
  8213. 6:02:22here is exactly as above so as as this
  8214. 6:02:25derivation here they call
  8215. 6:02:27VJ the J row of the V Matrix and they
  8216. 6:02:33write it as um p i J multip by d o how
  8217. 6:02:37to arrive to this formula here well
  8218. 6:02:39let's do it
  8219. 6:02:41so let me write let's see
  8220. 6:02:44okay theoretically we know that from
  8221. 6:02:47this derivation here so from this
  8222. 6:02:50derivation here or from this derivation
  8223. 6:02:52here we know that the I row of the
  8224. 6:02:55output in a matrix multiplication first
  8225. 6:02:58of all let's simplify our life every
  8226. 6:03:00time you see a transposed and you don't
  8227. 6:03:01like work with the transposed in a
  8228. 6:03:02matrix multiplication just give it a
  8229. 6:03:04different name and then work with the
  8230. 6:03:06different name and after when you have
  8231. 6:03:08derived the formula you resubstitute the
  8232. 6:03:11transpose operation in this case we are
  8233. 6:03:14doing DV is equal to P transpose multip
  8234. 6:03:17by d o let's call P transposed let's
  8235. 6:03:20give it a name that we are not we didn't
  8236. 6:03:22use so far so let's call it f I always
  8237. 6:03:24used F when it's available so um we call
  8238. 6:03:30DV is equal to f d o we know from above
  8239. 6:03:36here from this derivation here or this
  8240. 6:03:39derivation here is
  8241. 6:03:41equivalent that the output of a matrix
  8242. 6:03:44multiplication so the out I row of the
  8243. 6:03:47let's not the J row let's call it the J
  8244. 6:03:49row d
  8245. 6:03:51v j is equal to a summation of each
  8246. 6:03:57element of the J row of f of the first
  8247. 6:04:02Matrix so we do the let's see here they
  8248. 6:04:06do the sum by I so let's do it by I it's
  8249. 6:04:09the sum over all possible I of the uh I
  8250. 6:04:14element in the
  8251. 6:04:17J row of the first Matrix so f j uh yeah
  8252. 6:04:24FJ
  8253. 6:04:26I multiplied dot product not DOT product
  8254. 6:04:30this is a a scolar uh Vector
  8255. 6:04:33multiplication multiplied by a vector
  8256. 6:04:35that is let me check what was the
  8257. 6:04:37formula so it was the J row of the other
  8258. 6:04:41Matrix so in this case it should be the
  8259. 6:04:44I row of the other
  8260. 6:04:46Matrix uh o of
  8261. 6:04:50I where I this is the I row of I this is
  8262. 6:04:54the J row of the V
  8263. 6:04:58Matrix um and but also we we know that f
  8264. 6:05:03is not a matrix that we have it's
  8265. 6:05:05actually the transposed of P which means
  8266. 6:05:07that fji will be equal to p i j because
  8267. 6:05:10in a matrix transposition you invert the
  8268. 6:05:13two indices so this is the summation
  8269. 6:05:16over all possible I's of P not j i but
  8270. 6:05:21IJ multiplied by oi and this should be
  8271. 6:05:25equal to the same formula that you see
  8272. 6:05:26on the right here this allows you to
  8273. 6:05:29compute one output Row in the v
  8274. 6:05:33Matrix okay and we know that p is just
  8275. 6:05:37um the output of the softmax the soft
  8276. 6:05:40output of the softmax is the input of
  8277. 6:05:42the softmax to the exponential of the
  8278. 6:05:44input of the softmax divided by the
  8279. 6:05:47normalization factor
  8280. 6:05:49associated with the that row so because
  8281. 6:05:52we are iterating through the row of I it
  8282. 6:05:55will be the I the normalization factor
  8283. 6:05:58associated with that row of um of
  8284. 6:06:02OI so we know that the for formula for
  8285. 6:06:06the p is equal to the soft Max of s now
  8286. 6:06:11the I row of P will be the soft Max of
  8287. 6:06:14the E row of s and this is what is
  8288. 6:06:16written here we know from our derivation
  8289. 6:06:19that the Jacobian with respect to the
  8290. 6:06:23softmax operation so if we have an input
  8291. 6:06:26X and the output is y of the softmax
  8292. 6:06:28operation the Jacobian of this um of the
  8293. 6:06:31Y with respect to the x is equal to the
  8294. 6:06:34diagonal y it's a diagonal matrix of the
  8295. 6:06:37element of the factor y minus y * y
  8296. 6:06:41transposed and we have also seen before
  8297. 6:06:43that this Matrix is
  8298. 6:06:46symmetric however you may not understand
  8299. 6:06:49this formula here because we have seen
  8300. 6:06:51from our uh in the chain rule we always
  8301. 6:06:54write it like this we always write that
  8302. 6:06:56the downstream gradient so the D um uh
  8303. 6:07:01Fe of let's say um TX
  8304. 6:07:06should be equal to the uh Upstream
  8305. 6:07:08gradient so d f with respect to Dy
  8306. 6:07:12multiplied by Dy and um with respect to
  8307. 6:07:18DX this only works if you make this
  8308. 6:07:21Matrix here as in the numerator
  8309. 6:07:24convention the numerator convention is
  8310. 6:07:27one of the two convention in which you
  8311. 6:07:28can create a Jacobian we so far we have
  8312. 6:07:31always written it as the numerator
  8313. 6:07:33convention if you use the Ator
  8314. 6:07:35convention this is a row vector and this
  8315. 6:07:38is a row Vector however if you want to
  8316. 6:07:42treat this stuff here as a column Vector
  8317. 6:07:45then you need to take the transposed or
  8318. 6:07:47you need to make the Jacobian in the
  8319. 6:07:49denominator
  8320. 6:07:50convention how to get this formula here
  8321. 6:07:53because this formula here is basically
  8322. 6:07:54doing the Jacobi and multiply by the
  8323. 6:07:57Upstream um uh gradient not the gradient
  8324. 6:08:01Upstream gradient multiplied by the
  8325. 6:08:02Jacobian and it's only because here we
  8326. 6:08:04treat it as a column vector and when you
  8327. 6:08:06do the you want to transform a row
  8328. 6:08:09Vector into a column Vector you take the
  8329. 6:08:10transpose of both sides of the equation
  8330. 6:08:12and let's do it actually so we apply the
  8331. 6:08:15transpose to the both side of the
  8332. 6:08:19equation okay um in a matrix
  8333. 6:08:23multiplication if you do uh a b
  8334. 6:08:26transposed it become B transposed
  8335. 6:08:30multiplied by a transposed so the
  8336. 6:08:32transposed is applied independently to
  8337. 6:08:34each input of the the matrix
  8338. 6:08:35multiplication but we invert the matrix
  8339. 6:08:37multiplication and if you remember the
  8340. 6:08:39matrix multiplication is not commutative
  8341. 6:08:42so what we do here is that we say okay
  8342. 6:08:44it will be the D Fe of DX and here they
  8343. 6:08:48call
  8344. 6:08:50it here they call it
  8345. 6:08:54DSi so it will basically just become D
  8346. 6:08:59on DX if you treat this one as a column
  8347. 6:09:02Vector so this one as a column Vector
  8348. 6:09:04will be equal to Dy on DX as a column
  8349. 6:09:09Vector as a Jacobian in um in
  8350. 6:09:13denominator layout in this case
  8351. 6:09:15multiplied by d f on d y as a column
  8352. 6:09:19Vector this one is a column Vector this
  8353. 6:09:21is a column vector and this is what you
  8354. 6:09:23see here that's why the Jacobian is on
  8355. 6:09:25the left side of the Upstream
  8356. 6:09:27gradient uh what else we need well I I
  8357. 6:09:31know that there is a lot of things here
  8358. 6:09:32in this derivation but I prefer actually
  8359. 6:09:35going directly to the code otherwise I
  8360. 6:09:36think it's going to be too
  8361. 6:09:38boring um so let's go to the code and
  8362. 6:09:41while writing the code I go back to the
  8363. 6:09:43formulas in which we can find the
  8364. 6:09:45association of what we are doing and the
  8365. 6:09:48formula in the paper I think this is the
  8366. 6:09:50best uh way so let's proceed further all
  8367. 6:09:54right guys now we can finally code the
  8368. 6:09:56backward pass before we code the
  8369. 6:09:58backward pass let's look at the
  8370. 6:09:59algorithm of the backward pass as
  8371. 6:10:00written in the paper this is the paper
  8372. 6:10:02flashh attention one and I will because
  8373. 6:10:07we will follow the structure of the code
  8374. 6:10:09that is present on the Tron website so
  8375. 6:10:12it's not my idea to split it like this
  8376. 6:10:15but I simplified it in s i simplified it
  8377. 6:10:18so it's different than the one that you
  8378. 6:10:20can find online because mine is a
  8379. 6:10:21simplified version and mine works with
  8380. 6:10:24causal and non-causal
  8381. 6:10:25attention um so first if you look at
  8382. 6:10:29this algorithm you need to you can see
  8383. 6:10:31that we have an utor Loop through all
  8384. 6:10:34the K and V blocks and an inner loop
  8385. 6:10:37through all the query
  8386. 6:10:39blocks however as you can see to compute
  8387. 6:10:42the DQ which is the downstream gradient
  8388. 6:10:46of the the loss with respect to the Q uh
  8389. 6:10:50Matrix we need to have an iteration
  8390. 6:10:52through all the ks and to compute each
  8391. 6:10:55DC block we need to have an iteration
  8392. 6:10:58through all the cues so if we follow the
  8393. 6:11:01loop like it is it would involve writing
  8394. 6:11:04to the high bandwidth memory so to the
  8395. 6:11:07dram of the GPU at every inner iteration
  8396. 6:11:10and that could be also that that is not
  8397. 6:11:12so
  8398. 6:11:13efficient um and also if we don't want
  8399. 6:11:16to write it would require some sort of
  8400. 6:11:18inter some sort of um synchronization
  8401. 6:11:20between blocks which is also not very
  8402. 6:11:23efficient so we split we will split this
  8403. 6:11:26four into two parts because we can see
  8404. 6:11:29that each DQ depends on a loop over the
  8405. 6:11:33case and each d DK depends on a loop
  8406. 6:11:36over all the cues so to compute DK we
  8407. 6:11:40will fix the Kate block and iterate
  8408. 6:11:43through all the Q blocks then we will do
  8409. 6:11:45another iteration in which we fix the Q
  8410. 6:11:47block and iterate through all the KV
  8411. 6:11:49blocks to compute the Q this is what we
  8412. 6:11:52are going to follow and this is an idea
  8413. 6:11:54that I took from the original
  8414. 6:11:55implementation that is present on Tron
  8415. 6:11:58website another thing that we can notice
  8416. 6:12:00here is um where where is it here to
  8417. 6:12:05comput DQ and DK so um a DQ vector and a
  8418. 6:12:09DK Vector we need this element this
  8419. 6:12:13information here called di di and it's
  8420. 6:12:16shared between the two so we can
  8421. 6:12:19precompute it and then we can reuse it
  8422. 6:12:21for the qite vector to compute the qite
  8423. 6:12:24vector and the DK Vector what is this di
  8424. 6:12:28di is um is uh introduced here and it's
  8425. 6:12:33the dot product of a um Vector that is
  8426. 6:12:36the DOI Vector multiply by o Vector so
  8427. 6:12:40the first thing that we will do is do a
  8428. 6:12:42loop over all the vectors in O and d o
  8429. 6:12:46and do their dot products to compute
  8430. 6:12:48this di element then we will use this di
  8431. 6:12:52element and actually uh let me see yeah
  8432. 6:12:56and then we will use this di element to
  8433. 6:12:58update to to compute DQ and DK and we
  8434. 6:13:02will also have another two Loops one in
  8435. 6:13:04which we fix Q and we iterate through
  8436. 6:13:06all the keys and one in we fix the keys
  8437. 6:13:08and iterate through all the cues so
  8438. 6:13:11let's start so now that we know more or
  8439. 6:13:13less the structure of the code that we
  8440. 6:13:16are all right so um we start by writing
  8441. 6:13:20this backward
  8442. 6:13:22function
  8443. 6:13:26here uh let me check yeah okay so do you
  8444. 6:13:32remember this is saved tensor these are
  8445. 6:13:34all the information that we save during
  8446. 6:13:36the forward pass uh to compute the
  8447. 6:13:39backward pass now to to optimize the
  8448. 6:13:43memory utilization in um flash attention
  8449. 6:13:46we don't save the query multiplied by
  8450. 6:13:49the transpose of the key Matrix because
  8451. 6:13:51that would be a sequence by sequence
  8452. 6:13:52Matrix that is too big to save into the
  8453. 6:13:55hbm in the dam during the forward pass
  8454. 6:13:58and then re reget it back from the hbm
  8455. 6:14:01into the local memory because I want to
  8456. 6:14:03remind you that in Tron uh compared to
  8457. 6:14:06Cuda in Tron what we do is we load stuff
  8458. 6:14:09from the high band withd memory in the
  8459. 6:14:11shared memory so the SRAM we do all the
  8460. 6:14:15operations there and then after when we
  8461. 6:14:17call the store method we save the
  8462. 6:14:19element from the shared memory into the
  8463. 6:14:22high band WID memory so in order to not
  8464. 6:14:25materialize this s Matrix in its
  8465. 6:14:27entirety save it to the hbm and then
  8466. 6:14:30Reet it back which could be very slow
  8467. 6:14:32and secondly actually it is very
  8468. 6:14:34expensive because usually right now we
  8469. 6:14:36are Computing attention on thousands and
  8470. 6:14:39thousands of tokens so imagine saving a
  8471. 6:14:41matrix that is 5,000 by 5,000 that's a
  8472. 6:14:44big Matrix to save for each batch uh for
  8473. 6:14:48each batch and for each head so that
  8474. 6:14:51would be really too expensive to
  8475. 6:14:53save so the idea in Flash attention is
  8476. 6:14:56to recompute what we can compute on the
  8477. 6:14:58fly during the backward pass because
  8478. 6:15:00anyway if we were to load it it would be
  8479. 6:15:03Memory IO found so it's faster to
  8480. 6:15:06recompute than to save it and restore it
  8481. 6:15:09from the memory this is the idea of
  8482. 6:15:11flashh
  8483. 6:15:12attention Okay so we saved some stuff
  8484. 6:15:15during the forward pass and now we can
  8485. 6:15:17access it back during the backward pass
  8486. 6:15:19and this stuff is saved in the context
  8487. 6:15:22and this it's it's a kind of a
  8488. 6:15:24dictionary that is made available by by
  8489. 6:15:26P
  8490. 6:15:27torture all right so we get back the
  8491. 6:15:30query key and values and as you know P
  8492. 6:15:33torch during the autograph will just
  8493. 6:15:35give us the gradient of the loss with
  8494. 6:15:37respect to the output of our
  8495. 6:15:39implementation of the attention of our
  8496. 6:15:42attention so this is Tron attention and
  8497. 6:15:45then we need to compute DQ DK and DV by
  8498. 6:15:48using only the gradient of the output
  8499. 6:15:50with respect to the the deloss with
  8500. 6:15:51respect to the output um we do for some
  8501. 6:15:55checks so here I know I could optimize
  8502. 6:15:59this code and make it even smaller by
  8503. 6:16:01for example checking that here the
  8504. 6:16:03stride that I am using I actually inside
  8505. 6:16:05of the code I always uh pretend that the
  8506. 6:16:08stride is the same but uh doesn't matter
  8507. 6:16:11I just take the code from Tron and uh
  8508. 6:16:13try to simplify it my goal was to
  8509. 6:16:15simplify it not optimize it
  8510. 6:16:17so all right we create the um the
  8511. 6:16:22vectors the tensors in which we will
  8512. 6:16:24store the result of this backward pass
  8513. 6:16:26which is the DQ DK and DV and as you
  8514. 6:16:29know from what we have seen of the
  8515. 6:16:31definition of the gradient the size of
  8516. 6:16:34the output of the gradient Vector is the
  8517. 6:16:38size of the uh Vector with respect to
  8518. 6:16:41which we calculate the gradient because
  8519. 6:16:42in the numerator is always a scalar and
  8520. 6:16:44we compute the gradient with respect to
  8521. 6:16:46all the elements in the input Vector so
  8522. 6:16:47the output the gradient itself is a
  8523. 6:16:50vector of the same size of the element
  8524. 6:16:53by which we compute the gradient with
  8525. 6:16:54respect to so uh we got some information
  8526. 6:16:59on the bed size blah blah blah and later
  8527. 6:17:02we will see what is this number of warps
  8528. 6:17:04and number number of stages I will not
  8529. 6:17:06explain it now it's how P torch number
  8530. 6:17:10of Parts warps is an indication on how
  8531. 6:17:12many threads we want to launch in our
  8532. 6:17:13grid and number of stages is actually
  8533. 6:17:15the number of stages that is used in
  8534. 6:17:17software pipelining we will see later
  8535. 6:17:18what is software pipelining when we talk
  8536. 6:17:20about the autot
  8537. 6:17:22tuning then we Define some uh
  8538. 6:17:26blocks uh in the original um in the
  8539. 6:17:29original code I think they call it a
  8540. 6:17:31block kv1 kv2 k q1 1 and Q2 I think it
  8541. 6:17:36was confusing I call it block macro and
  8542. 6:17:38block micro because the things that we
  8543. 6:17:40will fix and the things that we will
  8544. 6:17:42iterate from will be once is the query
  8545. 6:17:45so we fix the query block and we iterate
  8546. 6:17:48through all the keys and then we will
  8547. 6:17:50fix the keys and values block and we
  8548. 6:17:53iterate through the queries the one that
  8549. 6:17:55we iterate on is the micro one and the
  8550. 6:17:57one that we fix is the macro one this is
  8551. 6:18:00my uh the naming that I am
  8552. 6:18:03using um then we as I said before we
  8553. 6:18:06need to precompute the DI elements that
  8554. 6:18:09we saw in the paper before so that's the
  8555. 6:18:11first kernel that we are going to launch
  8556. 6:18:13and this kernel will have its own launch
  8557. 6:18:16grid because later we want to optimize
  8558. 6:18:18the uh the tuning of this carel later we
  8559. 6:18:21will talk about tuning with respect to
  8560. 6:18:24its own parameters so uh let me see what
  8561. 6:18:28are we going to do so here so the first
  8562. 6:18:31kernel that we are going to launch is
  8563. 6:18:33this pre-process kernel
  8564. 6:18:35this preprocess can will pre-compute all
  8565. 6:18:37the DI elements that we need to compute
  8566. 6:18:39I remember DK and DV if I no DQ and
  8567. 6:18:45DK and this di element depends only on o
  8568. 6:18:50and d o um so let's do it and uh let's
  8569. 6:18:55create another function uh called
  8570. 6:18:57backward pre-process what is the process
  8571. 6:19:00pre-process grid this is the launch grid
  8572. 6:19:02of this function of this car
  8573. 6:19:05and this will be launched on um
  8574. 6:19:08independently for each batch and for
  8575. 6:19:10each head and moreover it will be work
  8576. 6:19:13with a block size of vectors of O what
  8577. 6:19:17is this block what is this number of
  8578. 6:19:19vectors of O it will be the block size
  8579. 6:19:22macro so on 128 vectors of O so uh let
  8580. 6:19:27me copy the signat of this function this
  8581. 6:19:30is here so let's write it here it's fine
  8582. 6:19:36yeah okay this function takes uh The
  8583. 6:19:39Matrix o so it's a pointer to The Matrix
  8584. 6:19:42o it's a pointer to the d o and it's a
  8585. 6:19:45pointer to The Matrix D where we will
  8586. 6:19:46store this di elements and we have one
  8587. 6:19:49for each Vector in the
  8588. 6:19:52output uh that's why the shape of this D
  8589. 6:19:55is batch size number heads sequence
  8590. 6:19:58length it means it's one for each of the
  8591. 6:20:00output element in the output of the
  8592. 6:20:02attention this di uh where is it
  8593. 6:20:05actually it's not this one it's this one
  8594. 6:20:08yeah like M so it has the same shape as
  8595. 6:20:12M which is as you can see it is this
  8596. 6:20:14size here so bch size number heads and
  8597. 6:20:17sequence length M if you remember is the
  8598. 6:20:19Matrix that we Sav during the forward
  8599. 6:20:20pass which includes the normalization
  8600. 6:20:23factor of the soft Max and also the
  8601. 6:20:25maximum element but in log some exp
  8602. 6:20:28format so that when we apply it will
  8603. 6:20:31automatically apply the maximum element
  8604. 6:20:32for each row and also normalize that at
  8605. 6:20:34the same time which I think I proved
  8606. 6:20:37previously uh
  8607. 6:20:40so let me do it so we write it like this
  8608. 6:20:44so we extract
  8609. 6:20:46the uh the index of this program so this
  8610. 6:20:49program has two uh index uh like
  8611. 6:20:54identifier this is is equivalent to the
  8612. 6:20:56Cuda identifier and this is along the
  8613. 6:20:58axis zero so let's see what we uh what
  8614. 6:21:01we what did we launch on the axis zero
  8615. 6:21:04so on the axis zero of this launch grid
  8616. 6:21:06we defined what is the block of vectors
  8617. 6:21:09of uh the O that this particular will
  8618. 6:21:13program will work with and the second
  8619. 6:21:16axis is which batch and which head
  8620. 6:21:19inside of each batch this particular
  8621. 6:21:21program will work with so this
  8622. 6:21:23identifies the block index of Q so which
  8623. 6:21:26group of vectors in the O Matrix this
  8624. 6:21:29particular program will work with here
  8625. 6:21:31is called Q I believe because I copied
  8626. 6:21:34it from the original code where they
  8627. 6:21:36call it q but I could have eventually
  8628. 6:21:38also called it
  8629. 6:21:39o um so we Define uh so basically this
  8630. 6:21:44means that we uh for this program we
  8631. 6:21:47need to skip some query vectors that
  8632. 6:21:50have been already or that will be or
  8633. 6:21:52have been already processed by other
  8634. 6:21:53programs in parallel so we will only
  8635. 6:21:56block with a number of query vectors
  8636. 6:22:00inside of O that have the following
  8637. 6:22:03indices so so imagine that query block
  8638. 6:22:05size is I think it's 128 the way we have
  8639. 6:22:08defined it but suppose it's four for
  8640. 6:22:11Simplicity so this one will be and the
  8641. 6:22:16query vectors are how many are sequence
  8642. 6:22:19length number of query vectors we have
  8643. 6:22:21so some of Imagine The query vectors are
  8644. 6:22:24in total they are I don't know let's say
  8645. 6:22:27uh 64 and 32 will be managed by other
  8646. 6:22:31programs so this particular off skq will
  8647. 6:22:33be equal to 33 34 35 and 36 this tells
  8648. 6:22:39me which query vectors or which vectors
  8649. 6:22:42in the output o Matrix among all the
  8650. 6:22:45vectors in the O Matrix this particular
  8651. 6:22:47program is going to work
  8652. 6:22:50with okay so then we extract also the
  8653. 6:22:53index of the batch which tells us which
  8654. 6:22:56batch and which head in each batch this
  8655. 6:22:59particular program is going to work with
  8656. 6:23:02which is the dimension one of our launch
  8657. 6:23:04grid
  8658. 6:23:05and then we Define the offset of the
  8659. 6:23:07dimension because we need to load all
  8660. 6:23:08the dimensions of each Vector so these
  8661. 6:23:10are the uh it's a vector uh that tells
  8662. 6:23:14um which Dimensions we need to load from
  8663. 6:23:15each vector and we will load all of them
  8664. 6:23:17so we don't divide on the head Dimension
  8665. 6:23:20uh Dimension we just divide on the
  8666. 6:23:22sequence length
  8667. 6:23:24Dimension the the load among multiple
  8668. 6:23:27programs um you will see in this part of
  8669. 6:23:30the the video so when we are writing the
  8670. 6:23:32backward pass that we will not be using
  8671. 6:23:35the make block pointer like we did
  8672. 6:23:37during the forward pass so this function
  8673. 6:23:40here we will work with directly with
  8674. 6:23:42indexing by using the
  8675. 6:23:44strides so let's do
  8676. 6:23:49it so let's load a single block of rows
  8677. 6:23:53of O which I want to remind you has the
  8678. 6:23:56same shape as q and that's why we can
  8679. 6:23:57call it block size Q um so the O Block
  8680. 6:24:00that we are loading is O so uh the load
  8681. 6:24:03function accepts a pointer to what it
  8682. 6:24:06should load uh actually not a pointer it
  8683. 6:24:10accepts a array of pointers or a
  8684. 6:24:12multi-dimensional array of pointer in
  8685. 6:24:14case you want to load a multidimensional
  8686. 6:24:16data so actually load also allows you to
  8687. 6:24:18load um two dimensional data in this
  8688. 6:24:22case we are going to load two
  8689. 6:24:24dimensional data which is a block of
  8690. 6:24:27rows of O which should be a block a
  8691. 6:24:30tensor of the shape uh block size Q in
  8692. 6:24:34this case multiplied by the other
  8693. 6:24:37dimension being head
  8694. 6:24:39Dimension but we don't we need to tell
  8695. 6:24:41it where in this o Matrix it needs to
  8696. 6:24:44find this one first of all we need to
  8697. 6:24:46skip some batches and some heads based
  8698. 6:24:50on what the head and the batch that will
  8699. 6:24:52be processed by other programs So based
  8700. 6:24:54on the index that this um program will
  8701. 6:24:58process of the batch and the head we
  8702. 6:25:00need to skip all the other um batches
  8703. 6:25:03and heads
  8704. 6:25:05uh let's write the shape of this tensor
  8705. 6:25:07so the O tensor has a shape block size
  8706. 6:25:10uh not block size bch
  8707. 6:25:12size number of
  8708. 6:25:15heads then sequence length and then head
  8709. 6:25:19Dimension each block and each head will
  8710. 6:25:22have sequence length multiplied by dim
  8711. 6:25:25head dim number of items So based on our
  8712. 6:25:28index we skip how many items the our
  8713. 6:25:31index multiplied by head Dimension
  8714. 6:25:33multiplied by sequence length so what I
  8715. 6:25:37mean is this the batch zero and the head
  8716. 6:25:39zero will have sequence length
  8717. 6:25:42multiplied by head Dimension items the
  8718. 6:25:46batch zero and the head one will also
  8719. 6:25:47have the same number of items and the
  8720. 6:25:49batch zero and head two will also have
  8721. 6:25:52the same number of items so how many
  8722. 6:25:54items sequence length multiplied by head
  8723. 6:25:56Dimension do we need to skip from the
  8724. 6:25:58starting of the O tensor it is equal to
  8725. 6:26:01the index of the current batch and head
  8726. 6:26:03indicator so because this index
  8727. 6:26:05indicates both um the head in the batch
  8728. 6:26:09and the head inside of each bat because
  8729. 6:26:11it's already the product of the head and
  8730. 6:26:14the batch so how many we skip indicated
  8731. 6:26:18by the this index and after we point to
  8732. 6:26:22this starting point of the current batch
  8733. 6:26:24and the current head we need to select a
  8734. 6:26:26two-dimensional tensor where the offsets
  8735. 6:26:30are indicated for the rows by off SK and
  8736. 6:26:34that's that's why we have this one um
  8737. 6:26:37the I don't know what this is called
  8738. 6:26:40this is the the index U semicolon index
  8739. 6:26:45that tells all the all these vectors in
  8740. 6:26:48offc will with an additional dimension
  8741. 6:26:51for the columns and this columns will be
  8742. 6:26:54the offs dim so basically this will
  8743. 6:26:56select a tensor of the following shape
  8744. 6:26:58inside of this big tensor that includes
  8745. 6:27:01pet
  8746. 6:27:02size and number number of
  8747. 6:27:06heads this is what we are doing so we
  8748. 6:27:08are saying select a tensor of this size
  8749. 6:27:11inside of one that is made up of four
  8750. 6:27:13dimensions by skipping the elements of
  8751. 6:27:16all the batch and heads that will be
  8752. 6:27:19processed by other programs I always
  8753. 6:27:21talk in terms of programs because in
  8754. 6:27:24Tron these are called programs in Cuda
  8755. 6:27:26you would refer to them as
  8756. 6:27:29kernels all right so this one is done I
  8757. 6:27:32hope it is this recently clear um all
  8758. 6:27:36right so then we also load a single
  8759. 6:27:39block of
  8760. 6:27:41D in the same way because we are going
  8761. 6:27:43to load a a group of vectors from all
  8762. 6:27:46the sequence length also from D and the
  8763. 6:27:49D has the same shape as o which has the
  8764. 6:27:52same shape as q and that's why we can
  8765. 6:27:55use the um the the block index we call
  8766. 6:27:58it Q because it's equivalent because
  8767. 6:28:00they have the same
  8768. 6:28:01shape okay and how to compute this di
  8769. 6:28:05element well it's written in the paper
  8770. 6:28:07so if we go in the in the what is it man
  8771. 6:28:12if we go here it shows you how to
  8772. 6:28:14compute the DI of each given a block of
  8773. 6:28:18D and um a block of O it tells you how
  8774. 6:28:21to compute di which is the row sum which
  8775. 6:28:25means the the sum of by rows for each
  8776. 6:28:28row we will have one sum for each Vector
  8777. 6:28:30in the O Matrix we will have one sum of
  8778. 6:28:33the element wise product so this stuff
  8779. 6:28:36here is the element wise product of D oi
  8780. 6:28:38multiplied by oi so it's not um uh
  8781. 6:28:43matrix multiplication it's element wise
  8782. 6:28:44product which means each element of one
  8783. 6:28:46Matrix with the corresponding element of
  8784. 6:28:48the second Matrix and the output shape
  8785. 6:28:50it will be the same as the two matric
  8786. 6:28:53which must have the same
  8787. 6:28:55shape okay so we compute this di
  8788. 6:29:00block which will have shape block size Q
  8789. 6:29:03because we will have one sum for each
  8790. 6:29:07Vector uh then well we need to store it
  8791. 6:29:10somewhere so we need to calculate where
  8792. 6:29:11to store it inside of the D Matrix uh
  8793. 6:29:15well the D Matrix is I remember
  8794. 6:29:18correctly has the same shape as M so it
  8795. 6:29:20should be batch
  8796. 6:29:22size uh number of heads and sequence
  8797. 6:29:26length so we need to select the right
  8798. 6:29:29batch and the right head and also the
  8799. 6:29:31right position inside of the sequence
  8800. 6:29:32length based on the block index Cube
  8801. 6:29:35that we
  8802. 6:29:37have uh okay so let me
  8803. 6:29:42index
  8804. 6:29:43[Music]
  8805. 6:29:45okay all right because we already um so
  8806. 6:29:49we skip um again just like before we
  8807. 6:29:52know that D is of this size each botch
  8808. 6:29:55and each head will have sequence length
  8809. 6:29:58number of elements so how many number of
  8810. 6:30:00elements we need to skip from the
  8811. 6:30:01starting of the uh tensor is sequence
  8812. 6:30:04length multiplied by the combined index
  8813. 6:30:08B size head
  8814. 6:30:10number uh and plus we need to also skip
  8815. 6:30:12some queries based on our block index q
  8816. 6:30:15and it's this skipping is already done
  8817. 6:30:18inside of off skq so we add off skew and
  8818. 6:30:21then once we have computed the index
  8819. 6:30:23where we should store this di I block
  8820. 6:30:25why did I even call it d block let's
  8821. 6:30:29store it so let
  8822. 6:30:32me I didn't call it block I think it was
  8823. 6:30:35already in the original code but this is
  8824. 6:30:36di I and this big Matrix D is actually
  8825. 6:30:40the Matrix that includes all the DI for
  8826. 6:30:43one for each token in the sequence
  8827. 6:30:47length all right so the pre-processing
  8828. 6:30:50has been done now we need to do prepare
  8829. 6:30:53the two for Loops as you remember I said
  8830. 6:30:55before we will be doing two for Loops
  8831. 6:30:57one in which we fix the query and we
  8832. 6:31:00iterate through all the keys and values
  8833. 6:31:02and one in which we fix the key and
  8834. 6:31:04value block and we iterate through all
  8835. 6:31:05the queries and while coding it I will
  8836. 6:31:08always show you the formula from the
  8837. 6:31:09paper so don't worry let's start with
  8838. 6:31:13the next iteration so first we create
  8839. 6:31:15the launch grid for the next iteration
  8840. 6:31:18um as the launch grid is always the same
  8841. 6:31:20so we first because we we need to keep
  8842. 6:31:23one block fixed and iterate through all
  8843. 6:31:25the other blocks uh the block that we
  8844. 6:31:28keep fixed we Define how many programs
  8845. 6:31:30we have that run in parallel uh and the
  8846. 6:31:32block that is fixed has a block size
  8847. 6:31:35macro number of elements that's why we
  8848. 6:31:37create a sequence length divide by block
  8849. 6:31:39size macro number of blocks uh thread
  8850. 6:31:43blocks uh or programs in this AIS uh the
  8851. 6:31:47AIS to in this grid is I could have used
  8852. 6:31:50also the XIs one IND differently I think
  8853. 6:31:52it was already done here in the original
  8854. 6:31:54code it's um will indicate which batch
  8855. 6:31:58and which head inside of each batch we
  8856. 6:32:00are going to work
  8857. 6:32:02with uh so so and just like the uh
  8858. 6:32:07forward pass we will also use a variable
  8859. 6:32:09called stage that if the attention that
  8860. 6:32:11we are Computing is caal it will be
  8861. 6:32:13equal to three and if we are Computing a
  8862. 6:32:15non-causal attention then it will be
  8863. 6:32:16equal to
  8864. 6:32:18one um the first iteration we will fix K
  8865. 6:32:21and V blocks and we will iterate through
  8866. 6:32:24all the Q blocks in size of block size
  8867. 6:32:28micro number of query
  8868. 6:32:32vectors uh so let's look at the
  8869. 6:32:34signature so we pass we we launch it as
  8870. 6:32:37a launch grid because um and we we have
  8871. 6:32:41defined how many programs we have so we
  8872. 6:32:43have how many uh KV blocks we will have
  8873. 6:32:47it's a sequence land divide by the block
  8874. 6:32:49size macro because that's the the block
  8875. 6:32:51that we will keep fixed in this uh for
  8876. 6:32:53Loop in this
  8877. 6:32:55function and then we go through all the
  8878. 6:32:58query blocks in size of block size micro
  8879. 6:33:01which I defined it as 32 and later we
  8880. 6:33:04will talk about autot tuning and how to
  8881. 6:33:05tune these
  8882. 6:33:06values all right so I passed the query
  8883. 6:33:09Vector the key vector and the V Vector
  8884. 6:33:12uh sorry not Vector tensors now the
  8885. 6:33:15query tensor K tensor and V tensor and
  8886. 6:33:17they are pointing to the beginning of
  8887. 6:33:19the tensor which means that they are
  8888. 6:33:21beginning to the first botch and the
  8889. 6:33:23first head and the first token and the
  8890. 6:33:25first dimension of the tensors then we
  8891. 6:33:28pass the soft Max scale we pass d o DQ
  8892. 6:33:32DK and DV m is the one that is needed to
  8893. 6:33:36compute as you remember from what we
  8894. 6:33:38said before we did not see if the P
  8895. 6:33:41Matrix in the hbm because we want to
  8896. 6:33:44recompute it on the fly during the
  8897. 6:33:45backward pass so the query multiply by
  8898. 6:33:47transpose of the keys it's a very big
  8899. 6:33:49Matrix to save in the hbm and restore it
  8900. 6:33:51so we want to compute it on the fly but
  8901. 6:33:54we don't need to recompute the
  8902. 6:33:55normalization factor and the maximum
  8903. 6:33:57element for each row to apply the soft
  8904. 6:33:59Max that was already computed during the
  8905. 6:34:02forward pass and saved into this Matrix
  8906. 6:34:04M which includes the log sum exp of the
  8907. 6:34:08maximum of each row plus the logarithm
  8908. 6:34:11of the normalization factor with the
  8909. 6:34:13theug sum X trick we can just apply it
  8910. 6:34:16and it will also normalize each value
  8911. 6:34:19then we have the d uh V uh tensor that
  8912. 6:34:23we computed here with all the DI values
  8913. 6:34:25one for each Vector in the O tensor then
  8914. 6:34:29we need to pass some uh the number of
  8915. 6:34:31heads the sequence length the block size
  8916. 6:34:34that we want to use for the KV which is
  8917. 6:34:36the macro block size and the micro block
  8918. 6:34:38size is always the one that we iterate
  8919. 6:34:39on I think using this name it should be
  8920. 6:34:42easier to understand which one we are
  8921. 6:34:43iterating and which we want keep fixed
  8922. 6:34:45so the fixed one is macro and the
  8923. 6:34:47iterating one is the micro um head
  8924. 6:34:51Dimension um and later we will see why
  8925. 6:34:53we use a different block size to iterate
  8926. 6:34:55from because this is related to the
  8927. 6:34:57number of stages that Tron can divide
  8928. 6:35:00your for Loop into thanks to soft
  8929. 6:35:03pipelining then we have head Dimension
  8930. 6:35:06the stage indicates if the attention
  8931. 6:35:09that we computed in the forward pass was
  8932. 6:35:11Cal or not
  8933. 6:35:13cal um the number of warps and the
  8934. 6:35:15number of stages which we defined as
  8935. 6:35:17fixed but later we will talk about Auto
  8936. 6:35:19tuning so uh sometimes I repeat the same
  8937. 6:35:22stuff over and over so I should change
  8938. 6:35:25that
  8939. 6:35:26um okay let's write the signature of
  8940. 6:35:30this function um
  8941. 6:35:33let's put it here but
  8942. 6:35:36so we already described what is the
  8943. 6:35:40signature of this function let's go
  8944. 6:35:41directly to the meat so the first thing
  8945. 6:35:44that we need to do is understand the
  8946. 6:35:45offset by which we need to move this
  8947. 6:35:47query key and value and the offset is
  8948. 6:35:50given by the first of all we need to
  8949. 6:35:52enter the right batch and the right head
  8950. 6:35:54inside of each batch we compute the
  8951. 6:35:57index of the batch just like during the
  8952. 6:35:58forward pass by dividing the program the
  8953. 6:36:02program index which is a multiplic of
  8954. 6:36:04the index of the head and of the the
  8955. 6:36:07batch we divide it by the number of
  8956. 6:36:10heads to get which batch this program is
  8957. 6:36:12working with and to get the head we just
  8958. 6:36:13do the modulus just like in the for Loop
  8959. 6:36:16uh forward
  8960. 6:36:17pass um the offset batch head indicates
  8961. 6:36:21let me check what is it for okay it
  8962. 6:36:23enters the right batch and the right
  8963. 6:36:25head so what is the stride if you
  8964. 6:36:27remember correctly The Stride tells us
  8965. 6:36:29how many items you need to skip in that
  8966. 6:36:31Dimension to arrive to the next index in
  8967. 6:36:32the same dimension so if we want to skip
  8968. 6:36:35index number of batch we need multiply
  8969. 6:36:37it by the stride batch which is how many
  8970. 6:36:40elements you need to skip to arrive to
  8971. 6:36:42the next batch plus we also need to
  8972. 6:36:44enter the right head so we multiply um
  8973. 6:36:47the index of the head multiplied by The
  8974. 6:36:49Stride of the head to enter exactly in
  8975. 6:36:53that head in the tensor for each of the
  8976. 6:36:56qk and V
  8977. 6:36:57matrices uh plus we also have this is
  8978. 6:37:00will be used for if I remember for m and
  8979. 6:37:03d because m and d only don't have the um
  8980. 6:37:07the head di head Dimension so they are
  8981. 6:37:10only bch size number of heads sequence
  8982. 6:37:12length so we just use the index batch
  8983. 6:37:14multiplied by sequence length because
  8984. 6:37:16for each batch and on each head we will
  8985. 6:37:18have sequence length number of item so
  8986. 6:37:19you can think of it at the stride to
  8987. 6:37:21move from one batch head to the next
  8988. 6:37:23batch
  8989. 6:37:25head uh or to the yeah so
  8990. 6:37:30uh let's move the pointers
  8991. 6:37:35and this was so we move the pointer q k
  8992. 6:37:39and V by the offset batch head because
  8993. 6:37:42we want to enter the right um batch and
  8994. 6:37:46the right head inside of these big
  8995. 6:37:47tensors and we do it also for d o DQ DK
  8996. 6:37:51and DV because they have the same shape
  8997. 6:37:53as a q k and V and d o also has the same
  8998. 6:37:56shape as Q so they have the same shape
  8999. 6:37:58so we move by the same uh by the same
  9000. 6:38:01offset all right
  9001. 6:38:03so and then we move m and d to move them
  9002. 6:38:07to the right starting point on which the
  9003. 6:38:10sequence of the current head and the
  9004. 6:38:13current batch and the current head
  9005. 6:38:15starts so they are pointing to the first
  9006. 6:38:18Vector of the sequence dedicated to the
  9007. 6:38:21current badge and the current
  9008. 6:38:22head and the same is true for qk and V
  9009. 6:38:26and the d o DQ DK
  9010. 6:38:29andb okay then we load some other stuff
  9011. 6:38:34because here we fix in this iteration in
  9012. 6:38:37this method we are going to do a for
  9013. 6:38:39Loop in which we fix KV and we iterate
  9014. 6:38:42through Q so we first need to load this
  9015. 6:38:45dibs block of KV and we do it as
  9016. 6:38:50follows as follows so we know we need to
  9017. 6:38:53load a 2d tensor so we need to Define
  9018. 6:38:56what are the ranges in the second
  9019. 6:38:59dimension of each um vector k and V that
  9020. 6:39:03we need to load and it's defined by the
  9021. 6:39:05this
  9022. 6:39:07um by this
  9023. 6:39:09Factor then we uh we want to understand
  9024. 6:39:12which KV block this particular program
  9025. 6:39:15is going to work with so this particular
  9026. 6:39:18program is going to skip some KVs that
  9027. 6:39:20will already be managed by other
  9028. 6:39:22programs that may be running in parallel
  9029. 6:39:24and how to understand what this program
  9030. 6:39:26should be working with in based on the
  9031. 6:39:28index of the program zero which is
  9032. 6:39:32defined on sequence divide by the block
  9033. 6:39:35size macro and if you remember block
  9034. 6:39:37size macro is the thing that we fix so
  9035. 6:39:40it's telling us this program ID zero
  9036. 6:39:42will tell us how many uh block size
  9037. 6:39:44macro KV are already being managed by
  9038. 6:39:48other programs so we shouldn't care
  9039. 6:39:50about them so we skip them so let's go
  9040. 6:39:53back here and this is the number of
  9041. 6:39:55vectors that we need to skip so our KB
  9042. 6:39:58Start From Start KB and how many we need
  9043. 6:40:01to load them well depends on what is the
  9044. 6:40:04block KV this block KV is equal to block
  9045. 6:40:07size macro so it will be
  9046. 6:40:09128
  9047. 6:40:11vectors so we Define our um tensors two
  9048. 6:40:17dimensional tensors that we will store
  9049. 6:40:19in the SRAM because in Tron every time
  9050. 6:40:22you load something you load it from the
  9051. 6:40:23hbm into the SRAM so we Define where
  9052. 6:40:27they should be saved in the SRAM and
  9053. 6:40:28they are initially zeros and now we load
  9054. 6:40:31them so we load them as as
  9055. 6:40:36follows um we say that okay in the K uh
  9056. 6:40:42in the K tensor pointer which is already
  9057. 6:40:44pointing to the right index to the right
  9058. 6:40:48batch and to the right head because
  9059. 6:40:50that's something that we did
  9060. 6:40:52here we say we should need we need to
  9061. 6:40:55load the right sequence of keys which
  9062. 6:40:58should start from offs key because this
  9063. 6:41:01already includes how many We Should Skip
  9064. 6:41:04in the sequence length Dimension and for
  9065. 6:41:06each of these Vector we need to load all
  9066. 6:41:08the dimensions in
  9067. 6:41:11the in the head Dimension Dimension uh
  9068. 6:41:15because the K if I want to remind you is
  9069. 6:41:19batch number of
  9070. 6:41:22heads um sequence length and head
  9071. 6:41:27dim Now by using this line we are
  9072. 6:41:30skipping to the right B and to the right
  9073. 6:41:33head so it's like we already indexed
  9074. 6:41:36here and here we already selected an
  9075. 6:41:37index so right now this K is pointing to
  9076. 6:41:40the beginning of a tensor of two
  9077. 6:41:42Dimension and we tell okay we don't want
  9078. 6:41:45all the sequence we want some part of
  9079. 6:41:48this sequence which part the one that is
  9080. 6:41:50indicated by this start
  9081. 6:41:52KV um and how many of in the sequence
  9082. 6:41:56length we want well we want uh I I think
  9083. 6:42:00it's easy to write it like this so we
  9084. 6:42:02can write it that from start KV to start
  9085. 6:42:05KV plus block
  9086. 6:42:08KV uh so we want this number of tensor
  9087. 6:42:13exactly at this location and for head
  9088. 6:42:15Dimension what do we want to select we
  9089. 6:42:17want to select all the dimension so we
  9090. 6:42:19say that we want from zero to head
  9091. 6:42:22Dimension which is exactly this offs
  9092. 6:42:26dim
  9093. 6:42:28okay uh we do it for the K block and we
  9094. 6:42:31do it for the V block
  9095. 6:42:33uh here I think I didn't change the
  9096. 6:42:35comment this should be block
  9097. 6:42:38KV and this should be block KV before it
  9098. 6:42:41was called block kv1 right like in the
  9099. 6:42:44original code uh I simplified a little
  9100. 6:42:47bit the naming I think this one is
  9101. 6:42:48better easier to follow because in the
  9102. 6:42:50original code they also do for two for
  9103. 6:42:53Loops but in the second for Loop they do
  9104. 6:42:55it backward just to not change the
  9105. 6:42:56structure of the loops but I think mine
  9106. 6:42:58is more verbos but easier to
  9107. 6:43:01understand and probably less efficient
  9108. 6:43:03mine is much less
  9109. 6:43:05efficient um then we have offc because
  9110. 6:43:08we need to understand for each block of
  9111. 6:43:11queries how many vectors we need to load
  9112. 6:43:14and it's indicated by this offs q and
  9113. 6:43:17how many are them it's a block Q block Q
  9114. 6:43:20in the col color of this method was
  9115. 6:43:23block size micro so it is 32
  9116. 6:43:27vectors okay um now we need to access
  9117. 6:43:33Q vectors and O vectors trans uh no Q
  9118. 6:43:37vectors but already transposed and the O
  9119. 6:43:40vectors also we need to access them
  9120. 6:43:42because we are going to iterate through
  9121. 6:43:46queries and O vectors actually also why
  9122. 6:43:51because let's look at here let's look at
  9123. 6:43:54the formulas in the paper to compute VJ
  9124. 6:43:58so to compute the dvj that's what we are
  9125. 6:44:02trying to compute here we need to
  9126. 6:44:04iterate through all the D vectors and to
  9127. 6:44:07compute DK we need to iterate through
  9128. 6:44:09all the QI uh
  9129. 6:44:13vectors because the QI is a block of
  9130. 6:44:16vectors uh so uh that's why we need um
  9131. 6:44:20and why do we need to access a q as a
  9132. 6:44:23transposed because we need to compute
  9133. 6:44:25let me show you here uh P transpose that
  9134. 6:44:29to compute P transpose we need to we
  9135. 6:44:32need the Q trans transpose because the p
  9136. 6:44:34would be the soft Max of the query
  9137. 6:44:36multipli by the transpose of the
  9138. 6:44:38keys after we apply the soft Max it
  9139. 6:44:40becomes P but if you want the transposed
  9140. 6:44:43of P then you need to do query
  9141. 6:44:46transposed K multip by query transposed
  9142. 6:44:49so that's why we accessed query
  9143. 6:44:51transposed instead of
  9144. 6:44:52queries and the way we access query
  9145. 6:44:55transposed is just by playing with the
  9146. 6:44:58stride so let's do it like this and I
  9147. 6:45:02have also written the comment on why we
  9148. 6:45:04can do
  9149. 6:45:05it so this is equivalent to accessing
  9150. 6:45:09the
  9151. 6:45:10query uh how many first okay what is
  9152. 6:45:13this um what is this operation uh what
  9153. 6:45:17is this operation here this is saying go
  9154. 6:45:20to the query starting point starting um
  9155. 6:45:24pointer to the query which is already
  9156. 6:45:27pointing to the right batch and to the
  9157. 6:45:29right head for which this particular
  9158. 6:45:31program should work with and select a
  9159. 6:45:34two-dimensional Vector where you repeat
  9160. 6:45:36the query starting point along the uh in
  9161. 6:45:40this case along the columns but we
  9162. 6:45:42should be repeating it along the rows
  9163. 6:45:43because we want to select rows of
  9164. 6:45:46queries however if we want to select uh
  9165. 6:45:48the query transpose we just invert the
  9166. 6:45:51two Dimensions so this is a let me
  9167. 6:45:53actually show you without doing the
  9168. 6:45:55query transpose so let's do it
  9169. 6:45:57simplified like this so to access the
  9170. 6:46:01query um
  9171. 6:46:03the query pointers without transposition
  9172. 6:46:05we can just do like this go to the query
  9173. 6:46:08tensor and create a 2d tensor where in
  9174. 6:46:13the rows you put the starting point of
  9175. 6:46:16each query that you want to get and um
  9176. 6:46:20and replicate each of this pointer also
  9177. 6:46:22on the column that's the meaning of
  9178. 6:46:24adding this Dimension none this is
  9179. 6:46:27equivalent to when you do in py torch
  9180. 6:46:29the UNS squeeze like you are call
  9181. 6:46:33offs Q multiplied not un squeeze I think
  9182. 6:46:41one so this is equivalent to adding the
  9183. 6:46:43column Dimension to this tensor and
  9184. 6:46:46repeating all the values that are on the
  9185. 6:46:48on all the um on the columns how many
  9186. 6:46:52columns will be there it will be
  9187. 6:46:54broadcasted when we sum it with the dist
  9188. 6:46:56tensor here um this is a combination of
  9189. 6:47:00UNS squeezing and broadcasting so we are
  9190. 6:47:03taking the query vectors indicated by
  9191. 6:47:06offs
  9192. 6:47:07cuq um and um then we are uh for each
  9193. 6:47:12query Vector we are selecting all the
  9194. 6:47:15head Dimensions indicated by dim if you
  9195. 6:47:18invert this broadcasting it will create
  9196. 6:47:21the transpose of the the the query
  9197. 6:47:24Vector that you're trying to access so
  9198. 6:47:26this stuff here is equivalent to the
  9199. 6:47:29these two lines so accessing query and
  9200. 6:47:31then transposing
  9201. 6:47:34and uh it's something that you can do U
  9202. 6:47:37I could write down what is happening at
  9203. 6:47:40the pointer level so basically you need
  9204. 6:47:42to think of offc as being a vector of
  9205. 6:47:47pointers uh we multiplied by the
  9206. 6:47:50sequence stride which tells us how many
  9207. 6:47:53element we need to skip to go from one
  9208. 6:47:56query Vector to the next because each
  9209. 6:47:59stride Q will be the stride will IND
  9210. 6:48:02will be equal to in the case the head
  9211. 6:48:03Dimension is 128 The Stride of the
  9212. 6:48:06sequence Dimension will be 128 it means
  9213. 6:48:09that to go from one query Vector to the
  9214. 6:48:11next you need to um you need to uh uh go
  9215. 6:48:16forward by 128 elements because I want
  9216. 6:48:19to remind you that in the memory the
  9217. 6:48:21tensors are always stored like flattened
  9218. 6:48:25like each Dimension is flattened with
  9219. 6:48:27the next Dimension so imagine you have
  9220. 6:48:30three rows and four columns but the
  9221. 6:48:32first you will have the first three rows
  9222. 6:48:34then the sorry the first row so the
  9223. 6:48:36first four columns then the next four
  9224. 6:48:38columns then the next four columns row
  9225. 6:48:40after
  9226. 6:48:41row U it's difficult to visualize until
  9227. 6:48:45you write it down so uh how to write it
  9228. 6:48:48down take um create a vector of offs
  9229. 6:48:52skew so what is offc at the beginning is
  9230. 6:48:55is a range that is from here from 0 to
  9231. 6:48:59100 no 0 to 32 0 1 2 3 4 five 6 7 etc
  9232. 6:49:07etc we are multiplying each one with the
  9233. 6:49:10stride of the sequence so this will not
  9234. 6:49:13skip any element this will skip exactly
  9235. 6:49:15128 elements this will skip exactly
  9236. 6:49:19implying that the head Dimension is
  9237. 6:49:21128 uh this will skip two times 128
  9238. 6:49:25element this will skip three times 128
  9239. 6:49:28elements and then we are adding also
  9240. 6:49:32another Di di menion to this Vector so
  9241. 6:49:34this will be a vector then you broadcast
  9242. 6:49:36it on head Dimension number of columns
  9243. 6:49:39and to each of them you add one number
  9244. 6:49:43so it will become a vector like fall
  9245. 6:49:45okay let me just do it guys otherwise I
  9246. 6:49:47think it's too
  9247. 6:49:49confusing okay so we have a vector that
  9248. 6:49:52is as follows so zero then we have 128
  9249. 6:49:55then we have two * 128 then we have 3 *
  9250. 6:49:59128 etc etc we are adding how many
  9251. 6:50:02columns indicated by off dim so off dim
  9252. 6:50:05has how many columns it has a head dim
  9253. 6:50:07number of columns please for Simplicity
  9254. 6:50:09let's pretend it's not
  9255. 6:50:11128 Dimensions let's pretend it's four
  9256. 6:50:14dimensions so this will be four this
  9257. 6:50:16will be 2 * 4 this will be three * 4 we
  9258. 6:50:21are adding another dimension that is the
  9259. 6:50:23dim
  9260. 6:50:24Dimension each one multiplied by The
  9261. 6:50:27Stride of dim which will be one because
  9262. 6:50:29it's the last
  9263. 6:50:31Dimension um stride de so we are adding
  9264. 6:50:35how many columns
  9265. 6:50:37four uh so we are adding um one 0 1 2 3
  9266. 6:50:42I guess 0 1 2 3 right also to here this
  9267. 6:50:45one we are adding oh oh my God 0 1 2 3
  9268. 6:50:51and also to this one we are
  9269. 6:50:53adding 0 1 2
  9270. 6:50:573 uh okay and then also to this one we
  9271. 6:51:01are adding 0 1 2 3 so what this will
  9272. 6:51:04select this will select from the
  9273. 6:51:07starting point of the pointer Q it will
  9274. 6:51:10select the element zero then the element
  9275. 6:51:13one then the element two and then the
  9276. 6:51:15element three which is exactly the head
  9277. 6:51:18dimension of the first Vector that we
  9278. 6:51:20should be selecting then it will
  9279. 6:51:23select uh the element four from the
  9280. 6:51:26starting point of the vector the element
  9281. 6:51:28uh sorry this one let me write the
  9282. 6:51:29result of this operation so this one
  9283. 6:51:31will be 0 1 2 three then it will select
  9284. 6:51:34the element four 5 6 7 then it will
  9285. 6:51:37select the element um eight I guess 9 10
  9286. 6:51:4111 and then it will select the element
  9287. 6:51:4312 13 14
  9288. 6:51:4715 so from the starting point of where
  9289. 6:51:51this Q is pointing it will select the
  9290. 6:51:54first element right after this que the
  9291. 6:51:56second element right after this que the
  9292. 6:51:58third element right after this Q etc etc
  9293. 6:52:00and this will be the f you can see that
  9294. 6:52:03this will be the first query Vector this
  9295. 6:52:05will be the second query Vector this
  9296. 6:52:06will be the third query Vector this is
  9297. 6:52:08the fourth query Vector because in the
  9298. 6:52:10memory they are stored one after another
  9299. 6:52:12they are flattened so in the memory they
  9300. 6:52:14are stored like this they are stored
  9301. 6:52:16like the
  9302. 6:52:18following they are stored like this one
  9303. 6:52:20after another so it will select all of
  9304. 6:52:22them and we also create a virtual tensor
  9305. 6:52:25with the right shape that we want to
  9306. 6:52:28visualize it into so as you saw as we
  9307. 6:52:30saw before when you work with a tensor
  9308. 6:52:33layout in memory you can always view it
  9309. 6:52:35as whatever shape you like based on the
  9310. 6:52:38shape that you want and the reshaping is
  9311. 6:52:40always free doesn't involve changing the
  9312. 6:52:43arrangement of the elements in the
  9313. 6:52:45memory I hope now it's more clear so now
  9314. 6:52:47we can proceed
  9315. 6:52:48further oh my God it was quite
  9316. 6:52:51complicated so whenever I get stuck I
  9317. 6:52:53just draw things and I think you should
  9318. 6:52:55do it too because that's the only way to
  9319. 6:52:57learn uh if you try to imagine
  9320. 6:52:59everything in your head it's always
  9321. 6:53:01difficult
  9322. 6:53:03and we do the same job for the O vectors
  9323. 6:53:05in the O vectors we don't access it as
  9324. 6:53:08access it as um transposed because we
  9325. 6:53:11don't need it in transposed only the Q
  9326. 6:53:13we need it
  9327. 6:53:15transposed okay it race through the
  9328. 6:53:17sequence dimension of the query so we
  9329. 6:53:20start from the query number
  9330. 6:53:22zero in the current um well in the query
  9331. 6:53:26we need to go through the all the
  9332. 6:53:27sequence length Dimension because only
  9333. 6:53:29the key we select the right key that we
  9334. 6:53:31want to work with so I want to remind
  9335. 6:53:33you here we fix the key and we go
  9336. 6:53:35through all the
  9337. 6:53:36queries but the query we need to start
  9338. 6:53:38from zero until sequence length so the
  9339. 6:53:40number of steps of this for Loop will
  9340. 6:53:42be uh sequence length divide by block Q
  9341. 6:53:47uh so if we have 1,000 elements in the
  9342. 6:53:50sequence and the block Q is the 32 it
  9343. 6:53:52will be 1,00 divide by 32 I'm bad choice
  9344. 6:53:55of 1,000 should be 1,24 otherwise it's
  9345. 6:53:58not divisible so then we go through each
  9346. 6:54:01block in this for Loop and we load a
  9347. 6:54:03block of Q the first one indicated by
  9348. 6:54:06our pointer and at the end of the
  9349. 6:54:08iteration we will move it to the next um
  9350. 6:54:11to the next block of
  9351. 6:54:13Q okay we'll add also the log log Su exp
  9352. 6:54:17values that are stored in the M Matrix
  9353. 6:54:20uh because we want to compute on the Fly
  9354. 6:54:23PT PT is the transposed of the soft Max
  9355. 6:54:28of query multiplied by the keys but we
  9356. 6:54:30want to not take quy multiply by the
  9357. 6:54:33transpose of the key and then do the
  9358. 6:54:34transpose we just already access um Q as
  9359. 6:54:37transposed so we can already compute a
  9360. 6:54:39PT instead of computing p and then
  9361. 6:54:41transposing
  9362. 6:54:43it um so we load the offsets of the
  9363. 6:54:48elements that we need from this log some
  9364. 6:54:50exp
  9365. 6:54:52x uh Matrix which is the m Matrix that
  9366. 6:54:55we computed during the forward pass and
  9367. 6:54:58we access a block of Q at a time the one
  9368. 6:55:02we are currently working with in the
  9369. 6:55:06iteration then we access a
  9370. 6:55:10query key transposed already so we do
  9371. 6:55:13the if you want to get a PT um P should
  9372. 6:55:18be um this is actually not P because we
  9373. 6:55:20didn't do the soft Marx it's actually s
  9374. 6:55:23t but okay if you want to get PT you
  9375. 6:55:26need to get the soft Max of
  9376. 6:55:29STD um the soft Max of St is what it's a
  9377. 6:55:35transpose of s what is s is a query
  9378. 6:55:38multipied by transpose of ke so to get
  9379. 6:55:39St you need to do um key transposed no
  9380. 6:55:43key multiplied by query transposed so as
  9381. 6:55:44you remember in the matrix
  9382. 6:55:46multiplication if you transpose the
  9383. 6:55:49matrix multiplication you need to also
  9384. 6:55:50invert the two uh element in the matrix
  9385. 6:55:53multiplication so that's why we are
  9386. 6:55:55doing a key multiply by quy transposed
  9387. 6:55:58this will give us s transposed we are
  9388. 6:56:00also scaling it with the softmax
  9389. 6:56:03scale before we apply the to apply the
  9390. 6:56:06softmax we just need to do the
  9391. 6:56:08exponential of each element minus its
  9392. 6:56:11maximum divide by the normalization
  9393. 6:56:13value but with the log sum XT we just
  9394. 6:56:15need to um each element um subtracted by
  9395. 6:56:19the M value which already includes the
  9396. 6:56:21normalization factor uh I think I
  9397. 6:56:24already did the derivation of this so we
  9398. 6:56:26don't need to go through that again okay
  9399. 6:56:29so now we have the PT block actually so
  9400. 6:56:32this this formula I should have written
  9401. 6:56:33St
  9402. 6:56:35actually okay um then when doing the
  9403. 6:56:41causal attention we also need to um mask
  9404. 6:56:46out some
  9405. 6:56:47values um so as you can see here so the
  9406. 6:56:52in this case the Cal mask is applied
  9407. 6:56:55after the soft Max has been computed
  9408. 6:56:57because during this one is a you are
  9409. 6:57:00used to uh compute the apply the soft
  9410. 6:57:03the Cal mask before Computing the soft
  9411. 6:57:05Max attention but this is actually
  9412. 6:57:07during the forward pass because you
  9413. 6:57:10don't want the normalization factor to
  9414. 6:57:12be affected by the element that should
  9415. 6:57:13be
  9416. 6:57:14zero uh but we already computed the
  9417. 6:57:17normalization factor so it cannot be
  9418. 6:57:19affected anymore so we can compute we
  9419. 6:57:21can mask out after applying the sofware
  9420. 6:57:23because the normalization factor has
  9421. 6:57:24already been calculated based on the
  9422. 6:57:26fact that we applied the mask and that's
  9423. 6:57:29why we we we can apply it after applying
  9424. 6:57:31the soft Max
  9425. 6:57:33uh so the mask is always the same so if
  9426. 6:57:36the query is more than the the index of
  9427. 6:57:39the query um so the mask is true in this
  9428. 6:57:42case for all the values that do not need
  9429. 6:57:44to be masked so all the values that do
  9430. 6:57:46not need to be masked are this ones here
  9431. 6:57:49uh and all the other value will be um
  9432. 6:57:52will be replaced with the
  9433. 6:57:53zeros all right so after we have the PT
  9434. 6:57:59block already masked we can calculate
  9435. 6:58:01the DV DV I will write I will point to
  9436. 6:58:05the right formula in the paper so we
  9437. 6:58:07load a block of the O why do we know to
  9438. 6:58:10load a block of do let's look at the
  9439. 6:58:12paper so how to compute the DV block so
  9440. 6:58:15the DV block is computed
  9441. 6:58:18as the old DV plus so a repeated sum as
  9442. 6:58:22you can see as you can see it's here
  9443. 6:58:24plus
  9444. 6:58:25equal the old DV plus PT so here PT
  9445. 6:58:30dropped indicates the P IJ after
  9446. 6:58:34applying the Dropout in this
  9447. 6:58:36implementation we don't support the
  9448. 6:58:37Dropout and also very few models
  9449. 6:58:40actually use the Dropout in the
  9450. 6:58:42attention um so PT multiplied by DOI so
  9451. 6:58:46a block of DOI and DOI is the same block
  9452. 6:58:51that should be also um DOI and Ki Qi are
  9453. 6:58:56referring to always the same block of
  9454. 6:58:58rows in the respective um t s that's why
  9455. 6:59:03because this inly iteration I indicates
  9456. 6:59:05a block of q and a block of O but
  9457. 6:59:10they're always referring to the same
  9458. 6:59:12positions in the tensors because d o has
  9459. 6:59:15the same shape as DQ so we go through
  9460. 6:59:18the blocks of query and d o
  9461. 6:59:21simultaneously because one is needed for
  9462. 6:59:24DV so for D DV we need d o and for DK we
  9463. 6:59:28need
  9464. 6:59:29q and that's why we compute the DV as
  9465. 6:59:32follows just like from the paper so PT
  9466. 6:59:35block multiplied by d o as you can see
  9467. 6:59:37it's a ppose multiplied by d o block so
  9468. 6:59:41we have comput computed the do block um
  9469. 6:59:44then we need to load the DI element that
  9470. 6:59:47we computed precomputed
  9471. 6:59:50initially uh the d uh with the first
  9472. 6:59:53call to the function called the
  9473. 6:59:55attention backward Pro
  9474. 6:59:57pre-process because we will need it for
  9475. 6:59:59Decay so let's see
  9476. 7:00:03um and how many of them we are loading
  9477. 7:00:06exactly the same number of query that we
  9478. 7:00:08load because um they are we load always
  9479. 7:00:12the same number of block size micro
  9480. 7:00:15number of
  9481. 7:00:16vectors okay I will copy some stuff and
  9482. 7:00:19explain it step by step so um the next
  9483. 7:00:23operation that we need to do is to
  9484. 7:00:24compute this DK to compute DK we need
  9485. 7:00:29DST to compute DST we need need to to
  9486. 7:00:32get
  9487. 7:00:34DPT so let's go one by one let's go from
  9488. 7:00:38the B from the end to the beginning of
  9489. 7:00:41this uh formulas so we don't uh we we we
  9490. 7:00:45where where everything is used to where
  9491. 7:00:47everything is created so let's start
  9492. 7:00:49from DK if you look at the paper DK is
  9493. 7:00:53equal to the old DK plus DS transposed
  9494. 7:00:57multiply by a block of
  9495. 7:00:59Q um and this is is what is written here
  9496. 7:01:03so it is plus equal means basically just
  9497. 7:01:05the old plus the new some um it's an
  9498. 7:01:08incremental addition so increment the
  9499. 7:01:11old K with some new stuff which is this
  9500. 7:01:13stuff here so the soft Max scale
  9501. 7:01:16multiplied because also there is a soft
  9502. 7:01:18ma scale this tow here multiplied by the
  9503. 7:01:22matrix multiplication between the St
  9504. 7:01:24block and the transposed of um and and
  9505. 7:01:30Q and Q you can see here this q but we
  9506. 7:01:34don't have a Q we have a Q transpose so
  9507. 7:01:37we take the transpose of Q transpose and
  9508. 7:01:39it becomes back Q now let's look at this
  9509. 7:01:42DST block DST is calculated as follows
  9510. 7:01:47so in the formula of the paper we have
  9511. 7:01:48DS d s is here it is yeah it is here and
  9512. 7:01:54it is equal to a block P J multiplied
  9513. 7:01:57element wise with DPI minus Di now um we
  9514. 7:02:04don't need the S we need the S
  9515. 7:02:06transposed so to compute the S
  9516. 7:02:08transposed this is an element wise
  9517. 7:02:11multiplication not a matrix
  9518. 7:02:13multiplication which means that when you
  9519. 7:02:14take the transpose of this operation you
  9520. 7:02:16don't need to invert anything you just
  9521. 7:02:17need to take the transpose of the two
  9522. 7:02:20operan so to compute the St we take the
  9523. 7:02:23transpose of P which is the PT and we
  9524. 7:02:26already have that and then the transpose
  9525. 7:02:29of everything that is inside of the
  9526. 7:02:30parenthesis so this
  9527. 7:02:32DPT minus di I where we inverted the
  9528. 7:02:35rows with the columns so this DPT is
  9529. 7:02:39what well in the paper we know the
  9530. 7:02:41formula for DP DP is here and it is
  9531. 7:02:44equal to D wait wait wait DP here and it
  9532. 7:02:49is equal to d o multi by V transposed so
  9533. 7:02:54uh but we don't need the DP we need the
  9534. 7:02:56DPT and in this case it's not an element
  9535. 7:02:58wise multiplication it is a matrix
  9536. 7:03:00multiplication so um in order to get not
  9537. 7:03:04DP DP but DPT we need to take the
  9538. 7:03:07transpose of these two operants of this
  9539. 7:03:09matrix multiplication and in the matrix
  9540. 7:03:11multiplication when you take the
  9541. 7:03:12transpose you need to also invert the
  9542. 7:03:14order of the two operants so we need to
  9543. 7:03:17take the VT transposed which becomes V
  9544. 7:03:21so the V block Matrix multiplied by the
  9545. 7:03:24other operand so D oi transposed and
  9546. 7:03:28that's why we are doing the transpose of
  9547. 7:03:30d o
  9548. 7:03:31um right now I'm not going through all
  9549. 7:03:34the single pointers because I already
  9550. 7:03:36told you how to check what a pointer is
  9551. 7:03:38pointing to and what an offsets is
  9552. 7:03:40referring to I hope that now you have a
  9553. 7:03:43better understanding on how these
  9554. 7:03:44pointers work in uh Triton which is also
  9555. 7:03:47the same way in the in which they work
  9556. 7:03:49in Cuda because um in the GPU we only
  9557. 7:03:53get a pointer to the starting point uh
  9558. 7:03:55to the starting address of the tensor
  9559. 7:03:57and then we need to work out all this
  9560. 7:03:58indices we have computed the DK block
  9561. 7:04:01block so we now go to the next query uh
  9562. 7:04:04to the next block of
  9563. 7:04:06queries and um so uh the next GL block
  9564. 7:04:11of queries because we are fixing K and V
  9565. 7:04:15blocks and we are iterating through all
  9566. 7:04:17the queries so we need to move the query
  9567. 7:04:19transpose
  9568. 7:04:21pointers uh by stride sequence which
  9569. 7:04:23means that how can we go from one query
  9570. 7:04:26to the next and we multiply with the
  9571. 7:04:29current um block Q which is a vector
  9572. 7:04:32which indicates the pointers to the
  9573. 7:04:34current element in Q that we are
  9574. 7:04:36accessing and we do it also for the O
  9575. 7:04:38and we use the block Q as element and
  9576. 7:04:40the stride Q because the O and Q all
  9577. 7:04:44have the same
  9578. 7:04:46shape okay after we have run the for
  9579. 7:04:48Loop of all the queries we can store
  9580. 7:04:51this DK and DV block so we write it back
  9581. 7:04:55as
  9582. 7:04:56follows and this is the end of our
  9583. 7:05:00function guys so so we save the DV block
  9584. 7:05:03exactly in the position inside of the
  9585. 7:05:07current okay DV is already I believe
  9586. 7:05:09pointing to the right batch and to the
  9587. 7:05:11right head because we incremented it
  9588. 7:05:13here and also in the case of Decay then
  9589. 7:05:16we need to tell it in the sequence
  9590. 7:05:18Dimension where they should save this um
  9591. 7:05:21block of K and V and this is indicated
  9592. 7:05:24by this one we say and we create the the
  9593. 7:05:27pointers just like before guys don't
  9594. 7:05:29make me do it again it's a really really
  9595. 7:05:32um easy if you write it down like you
  9596. 7:05:34write this uh um Vector of key and
  9597. 7:05:39values pointers which is not pointers
  9598. 7:05:42actually they are a range of the of key
  9599. 7:05:46and value that you need to take from the
  9600. 7:05:48sequence
  9601. 7:05:49Dimension you add another dimension that
  9602. 7:05:52is the column so you repeat each value
  9603. 7:05:54in the columns and then you add the
  9604. 7:05:56dimension here for the head Dimension
  9605. 7:06:00anyway after we have Cal at the pointers
  9606. 7:06:02where we should store the DK and DV we
  9607. 7:06:05store them in the um the pointers of um
  9608. 7:06:08we store them in the DV um uh I mean we
  9609. 7:06:12store them in the DV uh tensor and the
  9610. 7:06:14DK tensor what do we save we save the DV
  9611. 7:06:17block and the DK block which is the one
  9612. 7:06:20that we were um uh incrementally
  9613. 7:06:23changing in the for Loop that we have
  9614. 7:06:26written okay now that we finish this one
  9615. 7:06:28we can go to the next function that will
  9616. 7:06:30do the other for Loop so let's do it
  9617. 7:06:34okay so now we do the second part of the
  9618. 7:06:38iteration which is this one so let me
  9619. 7:06:40just copy it and then we we we describe
  9620. 7:06:43it uh let's write it here okay we use
  9621. 7:06:47the same lunch grid as before of course
  9622. 7:06:50we need to declare this function and
  9623. 7:06:51again we um we because the grid is
  9624. 7:06:54defined for the block size Macro for
  9625. 7:06:57what is the thing that we keep fixed and
  9626. 7:07:00then we in the side of the for iteration
  9627. 7:07:02we do um steps of block size micro in
  9628. 7:07:07this case we are fixing q and we are
  9629. 7:07:09iterating through K
  9630. 7:07:11andv uh because we need to compute DQ
  9631. 7:07:14right now we have computed DK and
  9632. 7:07:17DV okay uh the I believe the arguments
  9633. 7:07:20are the same as before so and actually
  9634. 7:07:22this is also the reason why in the
  9635. 7:07:24original implementation on the Tron
  9636. 7:07:26website the author decided to um to use
  9637. 7:07:30the same for Loop but different
  9638. 7:07:32arguments and uh I believe it was a
  9639. 7:07:35little confusing so that's why I just
  9640. 7:07:36separated them I just repeat the code
  9641. 7:07:38twice it's the goal of this video is to
  9642. 7:07:41be as easy to understand as possible not
  9643. 7:07:44to be as efficient as possible
  9644. 7:07:46so uh let's go uh here so let me copy
  9645. 7:07:50the signature again and we Define this
  9646. 7:07:56function here okay so uh again we need
  9647. 7:08:01to first move the query key and value uh
  9648. 7:08:04to the right pointers which will point
  9649. 7:08:06to the exact batch and the exact head
  9650. 7:08:09that we are working with in this program
  9651. 7:08:12so um let's do it let me check where is
  9652. 7:08:16the code here and the first part is
  9653. 7:08:19exactly the same as the other for Loop
  9654. 7:08:21that we have
  9655. 7:08:22written so let's go here and really is I
  9656. 7:08:26just copied so it's exactly the same so
  9657. 7:08:29we check what is the index batch head we
  9658. 7:08:32move the query key value pointers to the
  9659. 7:08:34right place the d o DQ DK DV point to
  9660. 7:08:37the right place the m and d to the right
  9661. 7:08:38place exactly like before so I don't
  9662. 7:08:41think I need to explain that
  9663. 7:08:43again and then we load a block of Q the
  9664. 7:08:47one that we will keep
  9665. 7:08:50fixed so
  9666. 7:08:54DQ let me load a lot of stuff here
  9667. 7:08:57actually
  9668. 7:09:03okay we Define the offset that we will
  9669. 7:09:05need to load the blocks of k&p in the
  9670. 7:09:08head Dimension because we are going to
  9671. 7:09:10iterate in the k
  9672. 7:09:11andv um we will access them as
  9673. 7:09:14transposed blocks so instead of
  9674. 7:09:16accessing them directly as K and v We
  9675. 7:09:19access access them as KT and VT and you
  9676. 7:09:23know that that's possible just by
  9677. 7:09:24changing the
  9678. 7:09:26strides uh in this case because we are
  9679. 7:09:29treating them as 2D vectors we treat the
  9680. 7:09:31offs KV when you want to access K as
  9681. 7:09:35just not transposed but K you treat this
  9682. 7:09:38offs KV as a row Vector uh sorry a
  9683. 7:09:42column Vector so you repeat on the rows
  9684. 7:09:45each k um offset that you want to access
  9685. 7:09:49in this case we are repeating it as a we
  9686. 7:09:51are treating it as a row Vector so it
  9687. 7:09:53will be repeated on the
  9688. 7:09:55rows um sorry it will be broadcasted on
  9689. 7:09:58the column Dimension and that's how you
  9690. 7:10:01can access the transposed version of K
  9691. 7:10:03and how you can access the transposed
  9692. 7:10:05version of V another thing that we are
  9693. 7:10:08doing is we are loading the Q Vector
  9694. 7:10:10which Vector well based on ofq which is
  9695. 7:10:13based on the start Q which is based on
  9696. 7:10:16the exact starting point in which this
  9697. 7:10:18particular program should be working
  9698. 7:10:20with because this particular program
  9699. 7:10:21works as two
  9700. 7:10:23Dimensions uh the First Dimension
  9701. 7:10:25indicate which batch and which head this
  9702. 7:10:27program should be working with and the
  9703. 7:10:29second dimension which is the program
  9704. 7:10:30index number zero indicates which among
  9705. 7:10:33all the sequence length which query this
  9706. 7:10:36particular program is going to work with
  9707. 7:10:37this is indicated by the index block um
  9708. 7:10:41this should be actually Q in this case I
  9709. 7:10:43forgot to change the name so actually
  9710. 7:10:45let me change it so it's index Q because
  9711. 7:10:48we start we skip some Q how many Q we
  9712. 7:10:50skip um based on the index of the
  9713. 7:10:53current program multiplied by how many
  9714. 7:10:56uh blocks have already been processed by
  9715. 7:10:58the previous
  9716. 7:11:00programs this this will tell us inside
  9717. 7:11:02of the sequence length what are the
  9718. 7:11:04queries that this one needs to select so
  9719. 7:11:06that's why we use the start query plus
  9720. 7:11:09the range that is block Q so imagine the
  9721. 7:11:12starting query for this program among
  9722. 7:11:14all the sequence length is 100 then this
  9723. 7:11:16will load the query row 100 1001 1002
  9724. 7:11:21blah blah blah until 100 plus block Q
  9725. 7:11:24minus
  9726. 7:11:25one this is the range that we of the
  9727. 7:11:28query vectors that we will load in this
  9728. 7:11:30program
  9729. 7:11:32uh we load the block of Q by using a Q
  9730. 7:11:36Plus the offset repeated on the columns
  9731. 7:11:40so we treat it as a column Vector but we
  9732. 7:11:44repeat broadcast it on the rows
  9733. 7:11:46Vector um where each uh column will be
  9734. 7:11:50one head Dimension multiply by The
  9735. 7:11:52Stride in this case we actually can also
  9736. 7:11:54not multiply by The Stride because the
  9737. 7:11:56stride in the uh Dimension Dimension so
  9738. 7:11:59the last dimension of the batch is one
  9739. 7:12:01uh because to go from one
  9740. 7:12:04um actually the stride um how it is
  9741. 7:12:07defined the stride of the last Dimension
  9742. 7:12:10is always one because to go one element
  9743. 7:12:12to the next element you should move to
  9744. 7:12:15move it to by one
  9745. 7:12:18element um so we load the DQ which is
  9746. 7:12:21the stuff that we are going to compute
  9747. 7:12:23in this
  9748. 7:12:25um iteration and then we have D that we
  9749. 7:12:29need to load and the do use the same
  9750. 7:12:31offset as Q because D and DQ have the
  9751. 7:12:34same shape and they work in the same way
  9752. 7:12:36so we load a block of Q and we load the
  9753. 7:12:40corresponding block of
  9754. 7:12:42O of d o in this case and d o has the
  9755. 7:12:46same shape as o which has the same shape
  9756. 7:12:47as Q Plus we need to load also the M
  9757. 7:12:51normalization factors which are in the M
  9758. 7:12:53Matrix which one the cor the one
  9759. 7:12:55corresponding to this particular group
  9760. 7:12:57of queries that we are going to work
  9761. 7:12:59with in this particular program
  9762. 7:13:02we start with the uh offsets uh are the
  9763. 7:13:06as you can see the offsets are the first
  9764. 7:13:08block of KV starting from the zero
  9765. 7:13:11position so because we will iterate
  9766. 7:13:13through all the KVs and we start from
  9767. 7:13:15the zero KV so the key key Vector zero
  9768. 7:13:19and the V Vector zero and then we will
  9769. 7:13:21move by block KV number of vectors
  9770. 7:13:25forward at each
  9771. 7:13:27iteration I hope I didn't go too fast
  9772. 7:13:29because most of the things that are
  9773. 7:13:31written here are very similar to what we
  9774. 7:13:33have already done um in the the other
  9775. 7:13:36for Loop so I don't want to be you know
  9776. 7:13:38repeat myself too much um what it matter
  9777. 7:13:41is actually the the formulas that we
  9778. 7:13:43will use which is exactly the one in the
  9779. 7:13:45paper
  9780. 7:13:46so uh we go through this GL blocks of
  9781. 7:13:51keyway KV we load the first block of KR
  9782. 7:13:55transposed and V transposed which is
  9783. 7:13:58loaded like this as usual you tell it
  9784. 7:14:00what pointers the elements you want to
  9785. 7:14:03load and what are the pointers of the
  9786. 7:14:05another element that you want to load
  9787. 7:14:06and it will load the the block that you
  9788. 7:14:08are asking Tron to load inside of the
  9789. 7:14:11SRAM so this stuff all reside in the
  9790. 7:14:14SRAM and also Q resides in the SRAM and
  9791. 7:14:16also d o reside in the
  9792. 7:14:20SRAM um then we compute the query
  9793. 7:14:23multiply by the transpose of the keys
  9794. 7:14:24because we need to compute the P block
  9795. 7:14:27so the query the qk block is just the
  9796. 7:14:31query in the current query block with
  9797. 7:14:33the K transposed in the current query
  9798. 7:14:36Block in the current key
  9799. 7:14:38block um why but we access query the
  9800. 7:14:43keys already as transposed so we don't
  9801. 7:14:45need to transpose it and anyway even if
  9802. 7:14:48we did if we need to transpose it it's
  9803. 7:14:50just um it's not um doesn't require any
  9804. 7:14:54computation to transpose a matrix we
  9805. 7:14:56just access it in a different
  9806. 7:14:59way uh because in the memory layout it's
  9807. 7:15:02always stored kind of as a flattened
  9808. 7:15:04array um then we computed the P block
  9809. 7:15:07which is the output of the soft Marx so
  9810. 7:15:09each of the query key we substract the
  9811. 7:15:12log sum exp value for the this uh block
  9812. 7:15:16of queries that's why for loading the M
  9813. 7:15:19Block we use the offsets of the queries
  9814. 7:15:22that we are
  9815. 7:15:23loading uh and as you remember the M
  9816. 7:15:25Block already includes also the
  9817. 7:15:27normalization factor because each m is
  9818. 7:15:29actually the maximum value for each row
  9819. 7:15:32plus the logarithm of the normalization
  9820. 7:15:34factor that when you apply with the
  9821. 7:15:36properties of the exponential it goes
  9822. 7:15:38into the
  9823. 7:15:40denominator okay and then we apply again
  9824. 7:15:43the auto regressive
  9825. 7:15:46masking
  9826. 7:15:50oops what did I
  9827. 7:15:53do let me go back to the code here so we
  9828. 7:15:57have the stage this one so when we
  9829. 7:16:00launch the back backward pass stage
  9830. 7:16:02three indicates that it's a the in the
  9831. 7:16:05forward pass we computed the caal
  9832. 7:16:08attention and the one indicates that we
  9833. 7:16:10computed the non-causal attention so if
  9834. 7:16:13we computed the causal attention in the
  9835. 7:16:15forward pass we also need to mask out
  9836. 7:16:18these elements in the backward
  9837. 7:16:20pass so we check um we created The Mask
  9838. 7:16:24which tells us which index uh this mask
  9839. 7:16:27is true for only for the elements for
  9840. 7:16:30which the query index is more than the
  9841. 7:16:32key index and if this is true then we uh
  9842. 7:16:37we don't mask otherwise we
  9843. 7:16:39mask um let's compute the next operation
  9844. 7:16:44which is to compute DP and DS actually I
  9845. 7:16:47let's compute directly DK and then we
  9846. 7:16:49explain it like before so we start from
  9847. 7:16:51the end and we go to where this stuff
  9848. 7:16:54what is needed to computed so if you
  9849. 7:16:57look at the formula uh let me check
  9850. 7:17:02check this one we don't need I think
  9851. 7:17:07okay uh let's go here to the iPad okay
  9852. 7:17:13what we are trying to compute here is
  9853. 7:17:16DQ so DQ as you can see in the paper is
  9854. 7:17:21DQ is equal to the old DQ plus to which
  9855. 7:17:26is the soft Max scale which is this
  9856. 7:17:29stuff here m multiplied by the matrix
  9857. 7:17:33multiplication between DS and K block so
  9858. 7:17:37the DS block is here and the K block is
  9859. 7:17:42the transpose of the KT block because we
  9860. 7:17:44are accessing K already as a transposed
  9861. 7:17:47block we could also access K directly as
  9862. 7:17:50not transposed block by inverting if you
  9863. 7:17:54want to access it as a transpose block
  9864. 7:17:56just do like this like here none this
  9865. 7:18:00will treat it as a row vector and
  9866. 7:18:03broadcast along the columns otherwise
  9867. 7:18:06and also this one you need to change so
  9868. 7:18:08this one you should need to change
  9869. 7:18:10because this one you need
  9870. 7:18:12to treat it as um a column Vector the
  9871. 7:18:16dimensions but if you want to access it
  9872. 7:18:18as a k transpose then you just inverted
  9873. 7:18:20these two operations I hope I didn't
  9874. 7:18:23mess up anything so let's move forward
  9875. 7:18:26um so okay we know that the formula for
  9876. 7:18:29the uh DQ is exactly the same as the uh
  9877. 7:18:33as the paper one but what is this DS
  9878. 7:18:35block let's look at the paper this DS
  9879. 7:18:38block is coming from this stuff here so
  9880. 7:18:42this I believe this stuff here d s which
  9881. 7:18:46is a
  9882. 7:18:47pi the P block element wise
  9883. 7:18:50multiplication with DPI minus di which
  9884. 7:18:53is DPI minus d i now what is um the this
  9885. 7:18:59P block the p block is exactly the
  9886. 7:19:01output of the soft Max which we already
  9887. 7:19:03have what is the DP block well the DP
  9888. 7:19:06block is exactly d o multiplied by V
  9889. 7:19:09transposed which is d o which we already
  9890. 7:19:13loaded and it's here multiplied by the
  9891. 7:19:15transpose of the V which we already load
  9892. 7:19:17as transposed and this is how we comput
  9893. 7:19:20the
  9894. 7:19:21DQ uh let's Inc then of course we need
  9895. 7:19:24to move to the next uh block of uh KVs
  9896. 7:19:28so we increment the pointers just just
  9897. 7:19:30like before so we move to the next block
  9898. 7:19:34of keys and
  9899. 7:19:36values and also we move the
  9900. 7:19:40pointers um just like before and then we
  9901. 7:19:43need to store the result of DQ and this
  9902. 7:19:46way we only need to do one right to the
  9903. 7:19:49hbm by dividing the for Loop like the
  9904. 7:19:52following so if you look at the original
  9905. 7:19:55algorithm uh I I don't know if the
  9906. 7:19:57original algorithm actually corresponds
  9907. 7:19:59in to to the implementation that they
  9908. 7:20:01did in Cuda but I don't think so because
  9909. 7:20:04it would not be so
  9910. 7:20:05optimized but in the original algorithm
  9911. 7:20:08in the paper they say that you need to
  9912. 7:20:10go through all the keys and then while
  9913. 7:20:12going through the keys you need to go to
  9914. 7:20:14all the cues and for each queue that you
  9915. 7:20:15visit then you need to write back the
  9916. 7:20:18queue while you are updating it which is
  9917. 7:20:19not optimized that's why we needed to do
  9918. 7:20:22two for Loops one in which we fix the
  9919. 7:20:25query and we updated the keys because
  9920. 7:20:27each Keys update depends only on
  9921. 7:20:29particular block of Que
  9922. 7:20:31uh on all the blocks of Q sorry and then
  9923. 7:20:34we fix the queries and we iterate
  9924. 7:20:36through all the keys because one block
  9925. 7:20:37of Q depends on all the blocks of
  9926. 7:20:40K and this is why we split and this is
  9927. 7:20:42the second Loop that we have
  9928. 7:20:44written now we have written everything
  9929. 7:20:47that we need to for flashh attention um
  9930. 7:20:50the forward pass and the backward pass
  9931. 7:20:52so uh we should be ready to uh launch
  9932. 7:20:56the uh the kernel I hope I didn't make
  9933. 7:20:59any mistake in copying the
  9934. 7:21:01so I don't think I will try to launch it
  9935. 7:21:04and if there is any any error I will
  9936. 7:21:05just use my reference code which I have
  9937. 7:21:07already written that I used as a copy
  9938. 7:21:09the only difference up to now between my
  9939. 7:21:12reference code and the one that we have
  9940. 7:21:14written is the autot tuning which I
  9941. 7:21:16didn't explain so let's talk about the
  9942. 7:21:18autot tuning so the autot tuning is also
  9943. 7:21:20something that was already present in
  9944. 7:21:21the original paper and I kept it as is
  9945. 7:21:24uh I removed the autot tuning for the
  9946. 7:21:26backward
  9947. 7:21:27pass but in the forward pass you if you
  9948. 7:21:31check there is this code here that
  9949. 7:21:33indicates um the autotuning
  9950. 7:21:35configuration for Tron so Tryon
  9951. 7:21:38basically um cannot know uh beforehand
  9952. 7:21:41what is the best block size or what is
  9953. 7:21:43the best block size for the query or
  9954. 7:21:45what is the best block size for the key
  9955. 7:21:47and values or what is the best block
  9956. 7:21:49size for another dimension that we have
  9957. 7:21:52we need to try based on the hardware
  9958. 7:21:54that we are running on based on the
  9959. 7:21:56availability on the SRAM based on the
  9960. 7:21:59thread quaren that Tron can apply so I
  9961. 7:22:02didn't talk also about thread quaring
  9962. 7:22:05basically in Cuda you can choose if each
  9963. 7:22:07thread does one Atomic operation for
  9964. 7:22:09example in a matrix addition each thread
  9965. 7:22:12is doing one addition of one particular
  9966. 7:22:15element of the output Matrix or it's
  9967. 7:22:16managing multiple elements this is
  9968. 7:22:18called thread quaring and I think I
  9969. 7:22:21didn't check the documentation but I
  9970. 7:22:22believe Tron does it for you based on
  9971. 7:22:25the Block size that you give it and the
  9972. 7:22:27number of warps that you want the number
  9973. 7:22:29of warps is what is um a block of
  9974. 7:22:32threads of 32 threads that work Cooper
  9975. 7:22:36cooperatively running the same
  9976. 7:22:38instruction always at the same time the
  9977. 7:22:41number of stages is more interesting
  9978. 7:22:43it's an optimization that Tron does um
  9979. 7:22:48basically it is not Loop and rolling so
  9980. 7:22:52actually let's talk about uh let's talk
  9981. 7:22:54about software pipelining because this
  9982. 7:22:56is the last part that we need to
  9983. 7:22:57understand from this code which is the
  9984. 7:22:58aing so I believe that most interesting
  9985. 7:23:01part here is not choosing the block size
  9986. 7:23:03Q and The Block size K because that is
  9987. 7:23:05just kind of you try whatever whatever
  9988. 7:23:08configuration works best based on the
  9989. 7:23:10timing CA Tron will actually run all
  9990. 7:23:13these configurations for you every time
  9991. 7:23:15the sequence length or the head
  9992. 7:23:16Dimension changes and for every pair of
  9993. 7:23:19head Dimension and sequence length it
  9994. 7:23:21will choose the best configuration that
  9995. 7:23:23runs in the least amount of time that
  9996. 7:23:25gives you the best throughput actually
  9997. 7:23:28um so let's look at this num stages what
  9998. 7:23:31is it and how it works um so let's do it
  9999. 7:23:36okay so uh software pipelining
  10000. 7:23:39is is used when you have kind of a for
  10001. 7:23:42Loop so you have a sequential operation
  10002. 7:23:44in which each iteration does not depend
  10003. 7:23:47on the previous iteration so the
  10004. 7:23:48operations that you do in one iteration
  10005. 7:23:50are independent from what you have done
  10006. 7:23:51in the previous iteration which is more
  10007. 7:23:53or less what we have done before in our
  10008. 7:23:55for Loops actually there I believe there
  10009. 7:23:58are um uh how to say conditions in which
  10010. 7:24:02this doesn't have to be three so like
  10011. 7:24:04the operations can depend on each other
  10012. 7:24:06and you still can do software
  10013. 7:24:08pipelining so for example imagine you
  10014. 7:24:11have the following for Loop uh for Loop
  10015. 7:24:14that Row from one to n and first you
  10016. 7:24:17load some data then you load some other
  10017. 7:24:19data then you do a matrix multiplication
  10018. 7:24:21and then you store some data so here you
  10019. 7:24:23are reading data here you are reading
  10020. 7:24:25data here you are Computing some stuff
  10021. 7:24:27and here you are writing data if we look
  10022. 7:24:30at what happens at it each iteration we
  10023. 7:24:33will see the following picture imagine
  10024. 7:24:35our GPU is made up of a compute unit and
  10025. 7:24:38a a unit that is dedicated to loading
  10026. 7:24:41stuff so reading from the memory or
  10027. 7:24:43writing to the
  10028. 7:24:44memory what we will see in the time
  10029. 7:24:46scale is that at the first iteration
  10030. 7:24:49first we are reading some data and the
  10031. 7:24:51compute unit is Idle because we need
  10032. 7:24:53this data then we are reading some more
  10033. 7:24:55data and the computer unit is Idle
  10034. 7:24:57because we need this data then finally
  10035. 7:24:58we have enough data and then we can
  10036. 7:25:00compute this operation and the reading
  10037. 7:25:02unit is idle and then we are writing
  10038. 7:25:04some data back to the memory and the
  10039. 7:25:06comput unit is again idle and then it
  10040. 7:25:08will be idle for another two time steps
  10041. 7:25:11until it has enough data to run the
  10042. 7:25:13computation so as you can see this is
  10043. 7:25:16not very efficient because at any time
  10044. 7:25:19point in time there is only one unit
  10045. 7:25:22working and the other is a sitting Idol
  10046. 7:25:24so one way to uh optimize this for Loop
  10047. 7:25:27is to do software pipelining and you can
  10048. 7:25:29tell try to do it for your for Loops by
  10049. 7:25:32telling it how many stages you want so
  10050. 7:25:34let's see how it works so to pipeline a
  10051. 7:25:37for Loop means that first of all you
  10052. 7:25:39need to convert all these operations
  10053. 7:25:41into async operations and in Cuda at
  10054. 7:25:44least in the GPU of mvidia there are the
  10055. 7:25:47async loading from the memory and the
  10056. 7:25:49async load writing to the memory which
  10057. 7:25:52basically means that I spawn a load
  10058. 7:25:54operation and after and um when I I only
  10059. 7:25:58I check if it has completed when I
  10060. 7:26:00actually need it so I will spawn this
  10061. 7:26:03operation and this instruction will
  10062. 7:26:05return immediately and move to the next
  10063. 7:26:07instruction here I will spawn a load
  10064. 7:26:09iteration and this will return
  10065. 7:26:10immediately and move to the next
  10066. 7:26:12instruction and then I can uh compute
  10067. 7:26:15but before Computing I just check if
  10068. 7:26:17these two operations have completed so I
  10069. 7:26:19can spawn immediately two reads and then
  10070. 7:26:22I just check if this uh they have
  10071. 7:26:24completed so with software pipelining
  10072. 7:26:27what we are doing is we are pipelining
  10073. 7:26:30operations of different iterations into
  10074. 7:26:33a single iterations so first basically
  10075. 7:26:36what we will do is we will do the read
  10076. 7:26:38the first Matrix that we need for
  10077. 7:26:40computing this matrix multiplication
  10078. 7:26:42then at this next iteration we read the
  10079. 7:26:46um the uh we we read the first Matrix of
  10080. 7:26:50the second iteration and also read the
  10081. 7:26:53second matric of the first iteration so
  10082. 7:26:57I call it read a and read B which
  10083. 7:26:59indicates read the first Matrix of the
  10084. 7:27:02uh that we need and the b means the read
  10085. 7:27:04the second Matrix that we
  10086. 7:27:06need uh all these operations are
  10087. 7:27:09asynchronous then I launch another
  10088. 7:27:11asynchronous operation at the third
  10089. 7:27:12iteration that says read the um the
  10090. 7:27:16first Matrix of the third iteration and
  10091. 7:27:19then read the uh second Matrix of the um
  10092. 7:27:24of the second iteration and then compute
  10093. 7:27:28the matrix multiplication because at the
  10094. 7:27:30third iteration this one and this one
  10095. 7:27:32should have completed but but while
  10096. 7:27:36Computing the matrix multiplication I
  10097. 7:27:38don't keep the loading unit idle because
  10098. 7:27:41they are still Computing this this and
  10099. 7:27:43this load this can only work if you can
  10100. 7:27:46spawn async
  10101. 7:27:48operations so at the third iteration I
  10102. 7:27:51can compute this matrix multiplication
  10103. 7:27:53by using this one and this one because
  10104. 7:27:55they should have finished but while I'm
  10105. 7:27:57Computing the matrix multiplication I
  10106. 7:27:59already spound some async operations to
  10107. 7:28:01load the data necessary for the second
  10108. 7:28:03iteration and the third iteration so at
  10109. 7:28:07the fourth iteration I will spound the
  10110. 7:28:10loading of the data for the fourth
  10111. 7:28:12iteration loading the data for the third
  10112. 7:28:15iteration while Computing the matrix
  10113. 7:28:16multiplication of the second iteration
  10114. 7:28:18because they should have already
  10115. 7:28:19completed by now uh actually it's not
  10116. 7:28:22like we expect them to have been
  10117. 7:28:24completed there are um Primitives in the
  10118. 7:28:27language or in the Cuda language to
  10119. 7:28:29check if the operation has completed so
  10120. 7:28:31actually before doing the matric
  10121. 7:28:33multiplication we will actually check if
  10122. 7:28:35the asyn operation has finished so it's
  10123. 7:28:37not like we just expect it to be
  10124. 7:28:39finished with respect to time uh this is
  10125. 7:28:42like in JavaScript you have these things
  10126. 7:28:44called prom promise I remember and you
  10127. 7:28:47can wait for the promise to be finished
  10128. 7:28:50before you actually need them but you
  10129. 7:28:51can spawn as many promise as you want in
  10130. 7:28:54C I think they are called tasks so you
  10131. 7:28:56spawn as many tasks as you want and then
  10132. 7:28:59when you need the it then you just wait
  10133. 7:29:01for them only the one that you needed
  10134. 7:29:04while the other are still running in the
  10135. 7:29:05background asynchronously this is the
  10136. 7:29:07whole idea of software
  10137. 7:29:09pipelining um software pipelining as you
  10138. 7:29:13can see only works when you have a sync
  10139. 7:29:15operations and also it increases the
  10140. 7:29:17memory requirement for your program
  10141. 7:29:19because when uh matrix multiplication
  10142. 7:29:22one uh is going to run we may have
  10143. 7:29:26enough data for the first two iterations
  10144. 7:29:29plus plus half data for the third
  10145. 7:29:31iteration so we increase the memory
  10146. 7:29:33requirement for the um
  10147. 7:29:36SRAM okay and P Tron will do this
  10148. 7:29:40software pipelining for you it will
  10149. 7:29:42convert all the load all the stores and
  10150. 7:29:44maybe also the metrix multiplication
  10151. 7:29:46into a sync operations and do this
  10152. 7:29:48pipelining for you if you are confused
  10153. 7:29:50by how it works there is another easy
  10154. 7:29:52solution to explain you how it works
  10155. 7:29:54because it's already something that we
  10156. 7:29:55do in model training it is called
  10157. 7:29:58pipeline parallelism
  10158. 7:30:00so in pipeline parallelism it works as
  10159. 7:30:03follows we have a very big neural
  10160. 7:30:05network that does not fit in a single
  10161. 7:30:07GPU so imagine this neural network is
  10162. 7:30:09made up of three layers layer one layer
  10163. 7:30:11two and layer three but this is so big
  10164. 7:30:14it does not fit entirely in one simple
  10165. 7:30:16GPU so one way would be to put this each
  10166. 7:30:19layer into one GPU so we put for example
  10167. 7:30:22layer one into GPU
  10168. 7:30:24one a layer two into GPU 2 layer three
  10169. 7:30:28into GPU number three so imagine we have
  10170. 7:30:32an input for this Neal Network so we put
  10171. 7:30:34it to the first GPU the GPU one will
  10172. 7:30:37process the layer one and generate some
  10173. 7:30:39output which will be transferred to the
  10174. 7:30:42gpu2 which will calculate its own output
  10175. 7:30:44and transfer it to the gp3 which will
  10176. 7:30:46compute its own output and finally we
  10177. 7:30:48will have the output of the Nal Network
  10178. 7:30:50the problem is when you send the output
  10179. 7:30:53of the gpu1 to the gpu2 for the gpu2 to
  10180. 7:30:56do its own thing the gpu1 now is free so
  10181. 7:30:59it is a waste of resources we could
  10182. 7:31:01always should keep the gpus busy so what
  10183. 7:31:04one thing that we can do is instead of
  10184. 7:31:06sending all the the mega batch to the
  10185. 7:31:09gpu1 we send many smaller batches how
  10186. 7:31:12does it work imagine that we send the
  10187. 7:31:15batch number zero so patch zero uh to
  10188. 7:31:20the gpu1 the gpu1 will compute its
  10189. 7:31:23output and send it to the gpu2 so now
  10190. 7:31:24the gpu2 is Computing the batch number
  10191. 7:31:28zero so now the batch zero is not here
  10192. 7:31:30anymore but now the GPU one is free so
  10193. 7:31:33we send another micro batch called the
  10194. 7:31:35batch
  10195. 7:31:38one then gpu2 will finish processing the
  10196. 7:31:42batch zero and we'll send it to the
  10197. 7:31:45batch to the GPU number three so now the
  10198. 7:31:47GPU 3 has the batch number
  10199. 7:31:49zero and the gpu2 now is free so we
  10200. 7:31:52transferred and hopefully also gpu1 has
  10201. 7:31:54finished so we transfer the batch number
  10202. 7:31:56one from gpu1 to gpu2 the bches um and
  10203. 7:32:01then the GP one will be free so so we
  10204. 7:32:04transfer here becomes one and now this
  10205. 7:32:07one is free so because it's gpu1 is free
  10206. 7:32:10we can introduce another batch so batch
  10207. 7:32:12number two etc etc etc so we always
  10208. 7:32:15introduce when while moving one batch
  10209. 7:32:18from one GPU to the other we introduce a
  10210. 7:32:21new batch at the beginning of the
  10211. 7:32:22pipeline and they shift by one position
  10212. 7:32:24at every iteration this will keep the
  10213. 7:32:27gpus always busy uh there is only one
  10214. 7:32:30problem of the pipeline parallelism
  10215. 7:32:32which is the this bubbling effect
  10216. 7:32:34because to create this pipeline you at
  10217. 7:32:36the beginning of this um okay actually
  10218. 7:32:38in the pipeline paradism you also have
  10219. 7:32:40the problem of the backward step so the
  10220. 7:32:42backward step has to run exactly in
  10221. 7:32:44Reverse in the order in which you
  10222. 7:32:46receive the micro batches while in Tron
  10223. 7:32:50when doing software
  10224. 7:32:52pipelining you have the problem of the
  10225. 7:32:54prologue and the epilog because you need
  10226. 7:32:56to create this Pipeline and and
  10227. 7:33:00to start the pipelining and at the end
  10228. 7:33:03of the pipeline you need to uh use all
  10229. 7:33:05the stuff that is currently in the
  10230. 7:33:07pipeline so only in the beginning step
  10231. 7:33:10and in the last step of this for Loop
  10232. 7:33:12your um all the units of this GPU may
  10233. 7:33:16not be working
  10234. 7:33:17simultaneously which what does it mean
  10235. 7:33:20it means that in order to use pipelining
  10236. 7:33:22you want the number of iterations of
  10237. 7:33:24your for Loop to be much more bigger
  10238. 7:33:25than the number of stages in which your
  10239. 7:33:27iteration is divided into in this case
  10240. 7:33:29we have four stages these are called
  10241. 7:33:31stages so you want the number of
  10242. 7:33:33iterations to be much more to to be much
  10243. 7:33:36larger than the number of stages all
  10244. 7:33:38right guys finally I have completed the
  10245. 7:33:41video um I hope that you learned a lot
  10246. 7:33:44from this video I believe that we can
  10247. 7:33:45run the Tron code so let's run it
  10248. 7:33:48actually uh let's see I copied
  10249. 7:33:51everything I believe we also put the
  10250. 7:33:52code to test it but we didn't uh put the
  10251. 7:33:57uh main method which we can copy right
  10252. 7:34:00now I hope there is no error so I really
  10253. 7:34:02hope there is no error I really hope so
  10254. 7:34:07um let me check if I am in the right
  10255. 7:34:10machine I am so let's just run
  10256. 7:34:16program prey if there is an error I will
  10257. 7:34:19just copy my own reference
  10258. 7:34:21implementation but I hope it works
  10259. 7:34:24because otherwise I forgot something so
  10260. 7:34:27I'm running my code on an h100 uh
  10261. 7:34:29because my company has h100 uh if you
  10262. 7:34:32have a smaller uh GPU what you can do is
  10263. 7:34:34you can reduce the sequence length uh
  10264. 7:34:37you can reduce the BET BET size I think
  10265. 7:34:39is already one when we call it uh oh no
  10266. 7:34:43the BET size you can reduce the BET size
  10267. 7:34:44the number of heads the sequence length
  10268. 7:34:46you can even put head Dimension equal to
  10269. 7:34:478 and sequence length equal to 16 uh
  10270. 7:34:51let's
  10271. 7:34:52check uh run backward Tron backward
  10272. 7:34:56return the incorrect number of grading
  10273. 7:34:58expected five got one
  10274. 7:35:00we probably forgot some return statement
  10275. 7:35:02I
  10276. 7:35:03believe
  10277. 7:35:05yes so I forgot the return statement
  10278. 7:35:09here so in the backward pass after
  10279. 7:35:10running the last for Loop we need to
  10280. 7:35:13return the stuff that we have
  10281. 7:35:15computed cross finger
  10282. 7:35:18again okay passed so the backward pass
  10283. 7:35:22that is computed by torch it is
  10284. 7:35:24equivalent to our backward patch up to
  10285. 7:35:2710 to the power of minus two error
  10286. 7:35:30absolute error um so when you as you can
  10287. 7:35:33see this backward that we run here is
  10288. 7:35:36different than the backward that we run
  10289. 7:35:37here because when you apply Tron
  10290. 7:35:40attention it will introduce a new
  10291. 7:35:42computation graph in the computation
  10292. 7:35:43graph of our tensors that will include
  10293. 7:35:46this Triton attention operator and when
  10294. 7:35:48pyto want to compute the backward pass
  10295. 7:35:50it will just call the backward function
  10296. 7:35:52of this Tron attention to computed and
  10297. 7:35:55it will populate the grad value of all
  10298. 7:35:57the tensors that are the input to this
  10299. 7:36:00Triton
  10300. 7:36:01attention and this is how pytorch
  10301. 7:36:03autograd Works guys uh thank you for
  10302. 7:36:06watching my video guys it has been super
  10303. 7:36:09super super
  10304. 7:36:10demanding I spent many uh months first
  10305. 7:36:13of all to learn myself about the Tron
  10306. 7:36:15about Cuda about Flash atten Etc uh also
  10307. 7:36:19I have a full-time job so it it's is
  10308. 7:36:21really hard to make videos like this
  10309. 7:36:22like I need to dedicate you know the
  10310. 7:36:24nights the mornings the the weekends I
  10311. 7:36:26spend three days just to record this
  10312. 7:36:28video because sometimes I don't like how
  10313. 7:36:29I explain something sometimes I make
  10314. 7:36:31mistake or sometimes I need to restart
  10315. 7:36:33because what I'm doing is wrong etc etc
  10316. 7:36:37um I believe there should be no big
  10317. 7:36:39errors in what I have done so far but
  10318. 7:36:41for sure my notation is completely bad
  10319. 7:36:44like because all the mathematics I know
  10320. 7:36:46has been self-taught by I I learned it
  10321. 7:36:49by myself so because I didn't learn it
  10322. 7:36:51in Academia I have bad habits and I'm
  10323. 7:36:54trying to get rid of them so I use the
  10324. 7:36:56very bad notation sometime I call with
  10325. 7:36:58the capital letter sometime with this
  10326. 7:37:00lower case sometimes I just forget the
  10327. 7:37:02index Etc so I'm trying to solve these
  10328. 7:37:04problems um I believe I have explained
  10329. 7:37:07everything so I should be uh you should
  10330. 7:37:10have all the knowledge to derive all the
  10331. 7:37:13formulas that you see in the paper of
  10332. 7:37:14the flashh attention uh and you should
  10333. 7:37:17also have an internal image on how the
  10334. 7:37:19back the the the attention calculation
  10335. 7:37:22is working block by blocks I know that I
  10336. 7:37:25could have spent 20 hours explaining
  10337. 7:37:27things better but I also have a life and
  10338. 7:37:29I also have a wife so I I I I cannot
  10339. 7:37:32make a 100 hours videos um also there
  10340. 7:37:36were some interruptions making these
  10341. 7:37:38videos I I removed some wisdom teeth so
  10342. 7:37:40it took me at least one more than one
  10343. 7:37:43week to to to to recover because it was
  10344. 7:37:46so painful uh so thank you guys for
  10345. 7:37:48watching my video I hope you learned a
  10346. 7:37:50lot also this time I as you can see
  10347. 7:37:52Triton is something new there is not
  10348. 7:37:54much documentation so something that I
  10349. 7:37:56have said about Tron may not be totally
  10350. 7:37:58correct because really there is very
  10351. 7:38:00little documentation so all the Tron
  10352. 7:38:02that I have learned is by looking at the
  10353. 7:38:04code written by others and try to
  10354. 7:38:07understand
  10355. 7:38:08it
  10356. 7:38:09um and I think that's it guys so I wish
  10357. 7:38:14you a wonderful day and see you next
  10358. 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.