σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
BLAS and LAPACK skill›Module 1 · Matrix operations and memory›Topic 1.2·~1 hrAdvanced

Why GEMM is fast: blocking and cache

Skill positionModule 1 of 4 · Topic 2 of 3
1.2 Why GEMM is fast: blocking and cache
—Lab score— / 100Total XP—Streak—
Lecture0% read

4 min readCode examples: 3

  1. 01The idea in plain words
  2. 02The plain loop forgets its numbers
  3. 03Tiles that fit
  4. 04What the tasks ask

The covariance matrix of 12 stocks over 48 days needs only 1,296 numbers from memory, yet the plain triple loop fetches 7,632 of them on our toy cache. The arithmetic is identical. What can a program change to close that gap?

01

The idea in plain words

Where we are. The last topic showed that a matrix times matrix does about n times more arithmetic than it has numbers to fetch, so in principle it can keep the CPU busy. This topic shows what a real program must do to get that benefit: reuse each number while it is still in the fast memory next to the CPU. The next topic looks at how the same matrix is laid out in memory.

Memory comes in layers. Right next to the CPU sits a small, very fast store called the cache. When the program asks for a number that is in the cache, that is a hit and it is nearly free. When the number is not there, that is a miss: the number is fetched from main memory, which costs one word of traffic, and it pushes an older number out. Our toy cache throws out the one used longest ago, the usual rule.

DefinitionBlocking (tiling)

Splitting a big calculation into small tiles so that the numbers one tile needs all fit in the cache and are reused many times before the next tile is started.

02

The plain loop forgets its numbers

Here X is 48 days of returns for 12 stocks (48 rows, 12 columns) and Xt is its transpose. The covariance matrix is Xt times X, a 12 by 48 matrix times a 48 by 12 matrix. The cache holds only 108 numbers: it is a scale model, because a real cache holds thousands but a real matrix is thousands wide too.

main.pyPython
# The plain triple loop on the 12-stock covariance job, with a cache of 108 numberscache = Cache(108)cov = gemm_naive(cache, Xt, X)print("steps:", cache.hits + cache.misses, "touches | hits", cache.hits, "| misses", cache.misses)print("each number once would need", 12 * 48 + 48 * 12 + 12 * 12, "words; the loop moved", cache.misses)1
steps: 20736 touches | hits 13104 | misses 7632
each number once would need 1296 words; the loop moved 7632
  1. 15.9 times more traffic than the minimum, for exactly the same arithmetic.

The plain loop walks along a row of Xt and down a column of X for each result, so by the time it needs the same row again, 12 columns later, the cache has long since thrown it out. Each number is fetched about six times instead of once.

03

Tiles that fit

Blocking changes the order of the same steps. Instead of finishing one result at a time, the program picks a tile of block by block results and the matching strips of the inputs, and does all the work for that tile before moving on. When the three tiles (one each of A, B and C) fit in the cache, every number is brought in once per tile and then reused block times.

main.pyPython
# The same job in tiles of different sizes, the same cache of 108 numbersprint("cache of 108 numbers; best_block says", best_block(108))for block in (1, 3, 6, 8, 12):    cache = Cache(108)    gemm_blocked(cache, Xt, X, block)    print("block", block, "->", cache.misses, "words")1
cache of 108 numbers; best_block says 6
block 1 -> 7632 words
block 3 -> 4752 words
block 6 -> 3428 words
block 8 -> 3128 words
block 12 -> 8064 words
  1. 1Tiles of 6 to 8 fit and cut the traffic by more than half. A tile of 12 does not fit, and the traffic is worse than the plain loop.
tile traffic ≈ 2n³ / block + n² and 3 · block² ≤ cache(1)The model for square n by n matrices, and the condition that the tiles fit; the bigger the tile that fits, the less traffic.
A tile that is too big is worse than none

When the three tiles together are larger than the cache, each pass evicts numbers the next pass needs, and the cache thrashes. That is why best_block returns the largest size with 3 * b * b <= capacity and not simply the largest you can try. Real libraries tune the tile size for each CPU for exactly this reason.

Words moved by the 12-stock covariance, cache of 108Measured with gemm_naive and gemm_blocked
Plain loop7,632
Tile of 63,4282.2 times less
Tile of 83,1282.4 times less
Tile of 128,064too big
Words moved
Plain loop7632
Tile of 63428
Tile of 83128
Tile of 128064
main.pyPython
# The model against the measurement, for square 24 by 24 matrices and the same cachesquare = [[1.0] * 24 for _ in range(24)]for block in (3, 4, 6, 8):    cache = Cache(108)    gemm_blocked(cache, square, square, block)    print("block", block, "| measured", cache.misses, "| model", round(traffic_model(24, block)))1
block 3 | measured 9792 | model 9792
block 4 | measured 7488 | model 7488
block 6 | measured 6864 | model 5184
block 8 | measured 5184 | model 4032
  1. 1The model is exact at small tiles and about 25% low at tiles that nearly fill the cache, where neighbours start to evict each other.
04

What the tasks ask

  1. 1
    `Cache.touch`Answer hit or miss, update hits, misses and the use order, and evict the least recently used number when the cache is full.
  2. 2
    `gemm_blocked`The same product in tiles, touching the three numbers of every step in the order given, so the miss count is exact.
  3. 3
    `best_block` and `traffic_model`The largest tile whose three copies fit, and the traffic the model predicts; the tests compare it with what your gemm_blocked really measures.

Key takeaways

  • The data moves, not just the arithmetic The same arithmetic cost 7,632 words in one order and 3,128 in another. The order of the loops is a performance choice.
  • Size the tile to the cache Pick the largest tile with three copies that fit. Smaller wastes reuse; larger thrashes.
  • This is what a fast GEMM does Real libraries tile for several cache levels and for the registers. Next: how the matrix itself is laid out in memory.
Quick check
A cache holds 300 numbers. What does best_block(300) return, and why is a tile of 12 a bad choice?
Pick an answer.

Lab · what's graded

4 tasks · 100 pts
  • Least-recently-used cache with touch25 pts
  • Multiply in tiles with gemm_blocked25 pts
  • Pick a tile size with best_block25 pts
  • Predict the traffic with traffic_model25 pts
Explorer · lab-2-1
▾ lab-2-1
…
bash · in-browser
learner@quantcraft:~/lab-2-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-2-1 goes back to the starter files and the terminal is cleared. Your current solution will be lost — this can't be undone.

Will be reset
  • main.py → starter code
  • Terminal history and test output
  • Unsubmitted changes
Will be kept
  • Best lab score
  • Your XP and streak
  • Lecture progress and notes