σμ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.1·~45 minAdvanced

The three levels of BLAS

Skill positionModule 1 of 4 · Topic 1 of 3
1.1 The three levels of BLAS
—Lab score— / 100Total XP—Streak—
Lecture0% read

4 min readCode examples: 3

  1. 01The idea in plain words
  2. 02Three levels, three costs
  3. 03Levels 1 and 2 on real returns
  4. 04Level 3: the covariance matrix
  5. 05What the tasks ask

Five stocks, 250 trading days: the covariance matrix of their returns costs 12,500 arithmetic operations, yet it moves only 2,525 numbers in and out of memory. Why does the second figure matter as much as the first, and what changes if the matrix is bigger?

01

The idea in plain words

Where we are. This is the first topic of the BLAS and LAPACK skill, so nothing comes before it. By the end you will have written the three kinds of BLAS routine in Python and measured what each costs. The next topics take the most important one apart (why a matrix times matrix is fast), and every topic after that works on the same covariance matrix of returns.

Every numerical routine does two kinds of work. It does arithmetic: additions and multiplications, which we count as flops. And it moves numbers: it must fetch each input from memory and write each result back, which we count as words. A fast CPU can do a lot of arithmetic in the time it takes to bring a single number from memory, so a routine is often limited by the second kind of work, not the first.

DefinitionArithmetic intensity

Flops divided by words: how many operations each number fetched from memory pays for. Low means the routine waits on memory; high means it keeps the CPU busy.

02

Three levels, three costs

BLAS sorts its routines into three levels by what they combine. Level 1 works on vectors (a dot product, y := alpha * x + y). Level 2 combines a matrix with a vector. Level 3 combines a matrix with a matrix. The table gives the cost of each for vectors of length n and square matrices of size n by n.

  • RoutineCost for size n
  • level 1: daxpyWhat does it cost?2n flops3n words
  • level 2: dgemvWhat does it cost?2n² flopsn² + 2n words
  • level 3: dgemmWhat does it cost?2n³ flops3n² words

Read the table slowly. The arithmetic grows as n, n² and n³, but the memory traffic grows as n, n² and n². Only at level 3 does the work grow faster than the data: a matrix times matrix does about n times more arithmetic than it has numbers to fetch. That single fact is why so much effort goes into making level 3 fast, and the next topic shows how.

03

Levels 1 and 2 on real returns

Here R holds the last 250 daily returns of AAPL, JPM, XOM, JNJ and KO (250 rows, one column per stock) and X is R with each column's average removed. The first example runs ddot on two columns, and daxpy to build the return of a two-stock mix.

main.pyPython
# Level 1: a dot product and an axpy on two columns of 250 returnsaapl = [row[0] for row in X]jpm = [row[1] for row in X]blas = Blas()cross = ddot(blas, aapl, jpm)print("cross product:", round(cross, 5), "| flops", blas.flops, "words", blas.words)1blas = Blas()mix = daxpy(blas, 0.5, aapl, [0.5 * v for v in jpm])print("mix of two stocks:", len(mix), "days | flops", blas.flops, "words", blas.words, "| flops per word", round(blas.intensity(), 2))2
cross product: 0.00902 | flops 500 words 500
mix of two stocks: 250 days | flops 500 words 750 | flops per word 0.67
  1. 1500 flops over 500 words: one operation per number fetched.
  2. 2Even less: 500 flops over 750 words, because y is read and written.

Level 2 comes next. A portfolio that puts 20% in each of the five stocks has, on every day, a return equal to the matrix X times the weight vector w. That is dgemv: 250 rows, 5 columns, and one answer per day.

main.pyPython
# Level 2: the daily return of an equal-weight portfolio is a matrix times a vectorweights = [0.2, 0.2, 0.2, 0.2, 0.2]blas = Blas()daily = dgemv(blas, X, weights)1print("days:", len(daily), "| flops", blas.flops, "words", blas.words, "| flops per word", round(blas.intensity(), 2))
days: 250 | flops 2500 words 1505 | flops per word 1.66
  1. 1A 250 by 5 matrix is read once: 1,250 numbers, plus 5 weights and 250 results, for 2,500 flops.
04

Level 3: the covariance matrix

The covariance matrix of the five stocks is Xᵀ X divided by 249. The matrix Xᵀ is 5 by 250 and X is 250 by 5, so this one dgemm call produces the whole 5 by 5 table of how the stocks move together. Then the portfolio variance is a dgemv and a ddot, the two lower levels again.

main.pyPython
# Level 3: covariance = X^T X / 249, then the portfolio variance with the lower levelsXt = [list(col) for col in zip(*X)]blas = Blas()cov = [[v / 249 for v in row] for row in dgemm(blas, Xt, X)]1print("covariance: flops", blas.flops, "words", blas.words, "| flops per word", round(blas.intensity(), 2))print("AAPL variance:", round(cov[0][0] * 1e4, 2), "e-4 | AAPL with JPM:", round(cov[0][1] * 1e4, 2), "e-4")blas = Blas()variance = ddot(blas, weights, dgemv(blas, cov, weights))2print("portfolio volatility a year:", round((variance * 252) ** 0.5 * 100, 1), "% | flops", blas.flops, "words", blas.words)
covariance: flops 12500 words 2525 | flops per word 4.95
AAPL variance: 2.5 e-4 | AAPL with JPM: 0.36 e-4
portfolio volatility a year: 11.0 % | flops 60 words 45
  1. 112,500 flops over 2,525 words: about five operations per number moved, three times better than the matrix times vector above.
  2. 2The small final step costs 60 flops: the result is the annual volatility of the equal-weight mix.
flops / words: daxpy 2n / 3n · dgemv 2n² / (n² + 2n) · dgemm 2n³ / 3n² = 2n / 3(1)Arithmetic intensity of the three levels for size n; only the last grows with n.
Flops per word by level and sizeMeasured with the routines above on arrays of ones
Level 1, any n0.67
Level 2, n = 501.92
Level 3, n = 5033.33
Level 3, n = 500333.33grows with n
Flops per word at n = 50
Level 10.67
Level 21.92
Level 333.33
These counts are the best case

The routines count each number moved exactly once, as if it stayed in the CPU after the first fetch. A real machine cannot keep a big matrix that close, so a plain triple loop moves the same number many times. The next topic counts that honestly with a cache, and shows how blocking brings the real cost back toward these ideal figures.

05

What the tasks ask

  1. 1
    `daxpy`Return alpha * x + y as a new list and charge 2n flops and 3n words.
  2. 2
    `dgemv` and `dgemm`Return the product as new lists, charge the exact flops and words, and reject shapes that do not fit before counting anything.
  3. 3
    `intensity`Run the routine of the chosen level on arrays of ones and return flops per word. It is the table above, measured instead of quoted.

Key takeaways

  • Count two things Flops measure arithmetic and words measure memory traffic; speed depends on both.
  • Only level 3 gets better with size Intensity is flat at levels 1 and 2 and equals 2n/3 at level 3, so matrix products are where fast libraries earn their keep.
  • Higher levels are built from lower ones A portfolio variance is a gemv and a dot; the covariance matrix is a gemm. Next: why that gemm can be made so fast.
Quick check
Which routine does the most arithmetic per number it moves, for large n?
Pick an answer.

Lab · what's graded

4 tasks · 100 pts
  • Level 1: daxpy25 pts
  • Level 2: dgemv25 pts
  • Level 3: dgemm25 pts
  • Flops per word with intensity25 pts
Explorer · lab-1-1
▾ lab-1-1
…
bash · in-browser
learner@quantcraft:~/lab-1-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-1-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