σμ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.3·~50 minAdvanced

Storage order and the leading dimension

Skill positionModule 1 of 4 · Topic 3 of 3
1.3 Storage order and the leading dimension
—Lab score— / 100Total XP—Streak—
Lecture0% read

4 min readCode examples: 3

  1. 01The idea in plain words
  2. 02Row-major and column-major on real returns
  3. 03Windows into a bigger matrix
  4. 04What the tasks ask

Give a BLAS routine the covariance matrix of five stocks and it answers correctly. Give it the matrix of 250 days of returns stored the other way round and it answers just as calmly, with 250 wrong numbers and no error. What do you have to tell the routine about a matrix, and what does it simply trust you on?

01

The idea in plain words

Where we are. Topic 1 counted what the three BLAS levels cost, and topic 2 showed that tiles keep the matrix product from drowning in memory traffic. Both treated a matrix as a list of rows. Real memory is a single line of numbers, so before any routine can be called, someone has to decide how the table is laid along that line. This topic is about that decision, and the two ways a call can get it wrong. The next topics move to the solvers that read the same matrix.

There are two obvious ways to lay a table along a line. Row-major stores the first row, then the second, and so on; it is what C, NumPy and most programmers expect. Column-major stores the first column, then the second; it is what Fortran does, and BLAS and LAPACK were written in Fortran, so they expect it. The same six numbers give two different lists, and a routine that reads one as if it were the other works on a different matrix without any complaint.

DefinitionLeading dimension

The step in the flat list from the start of one row (row-major) or column (column-major) to the start of the next. It equals the row or column length when the matrix fills its memory, and is larger when the matrix is a window into a bigger one.

02

Row-major and column-major on real returns

X is the 250 by 5 table of demeaned daily returns from the earlier topics and cov the 5 by 5 covariance matrix built from it. We store both in both orders. The covariance matrix is symmetric, which will matter in a moment.

main.pyPython
# Store the 5 by 5 covariance matrix and the 250 by 5 returns in both orderscov_row = pack(cov, "row")cov_col = pack(cov, "col")print("covariance:", len(cov_row), "numbers | same list in both orders?", cov_row == cov_col)1x_row = pack(X, "row")x_col = pack(X, "col")print("returns:", len(x_row), "numbers | same list?", x_row == x_col)2print("first five, row-major:   ", [round(v * 100, 2) for v in x_row[:5]])print("first five, column-major:", [round(v * 100, 2) for v in x_col[:5]])
covariance: 25 numbers | same list in both orders? True
returns: 1250 numbers | same list? False
first five, row-major:    [-0.4, -0.53, 0.24, -0.66, -1.82]
first five, column-major: [-0.4, 0.81, 0.38, 0.76, -0.32]
  1. 1A symmetric matrix is its own transpose, so both orders give the same list.
  2. 2The returns are not symmetric (they are not even square): the five stocks of day one, against 250 days of one stock.
A symmetric matrix hides the mistake

If you test a routine only on a covariance matrix, row-major and column-major agree and every order mistake passes. The bug appears the first time a non-symmetric matrix (returns, a regression design matrix, a rectangular block) goes through. Test with a matrix that is not symmetric, and not square.

Now the silent mistake. The portfolio return on every day is X times the weights. We call gemv_flat first with the order the buffer was written in, then with the other order: same numbers, same function, no error.

main.pyPython
# The same 1,250 numbers read in the right order and in the wrong oneright = gemv_flat(Blas(), "row", 5, 250, 5, x_row, weights)wrong = gemv_flat(Blas(), "col", 250, 250, 5, x_row, weights)1print("right, first three days (%):", [round(v * 100, 3) for v in right[:3]])print("wrong, first three days (%):", [round(v * 100, 3) for v in wrong[:3]])print("average absolute gap (%):", round(sum(abs(a - b) for a, b in zip(right, wrong)) / 250 * 100, 3))
right, first three days (%): [-0.634, -0.013, 0.306]
wrong, first three days (%): [0.536, 1.046, -0.648]
average absolute gap (%): 0.764
  1. 1The call is legal: with ld 250 and 250 rows the buffer is exactly long enough. It just answers a different question.
03

Windows into a bigger matrix

The leading dimension earns its name when a routine should work on part of a matrix without copying it. The covariance block of the first three stocks is the top-left 3 by 3 corner of the 5 by 5 matrix. Its columns are still 5 apart in memory, so we pass the same ld of 5 and only change m and n. A block that does not start in the corner begins at a different offset: pass the list from that position.

main.pyPython
# The 3 by 3 block of the first three stocks, and the 2 by 2 block of stocks 2 and 3top_left = unpack(cov_col, "col", 5, 3, 3)print("block of stocks 1-3, variances (e-4):", [round(top_left[i][i] * 1e4, 2) for i in range(3)])start = offset("col", 5, 1, 1)inner = unpack(cov_col[start:], "col", 5, 2, 2)1print("block starts at", start, "| covariance of stocks 2 and 3 (e-4):", round(inner[0][1] * 1e4, 2))print("same value read straight from the full matrix:", round(cov[1][2] * 1e4, 2))
block of stocks 1-3, variances (e-4): [2.5, 1.97, 2.57]
block starts at 6 | covariance of stocks 2 and 3 (e-4): -0.13
same value read straight from the full matrix: -0.13
  1. 1unpack never copies the matrix: it only needs the start and the same leading dimension, and it reads past the window's edge without confusion.
row-major: (i, j) → i · ld + j column-major: (i, j) → j · ld + i(1)Where element (i, j) lives in the flat list; ld is the step between rows (or columns).
Six numbers, two layoutsThe matrix [[1, 2, 3], [4, 5, 6]]
Row-major list1 2 3 4 5 6ld 3
Column-major list1 4 2 5 3 6ld 2
Column-major list read as row-major[[1,4,2],[5,3,6]]a different matrix, no error
04

What the tasks ask

  1. 1
    `offset`The one place that knows the layout: i * ld + j for row-major, j * ld + i for column-major, and an error for anything else.
  2. 2
    `pack` and `unpack`Write a matrix into a flat list with gaps when ld is larger, and read a matrix or a window back, using offset for every element.
  3. 3
    `gemv_flat`A matrix-vector product that reads a flat buffer the way a BLAS call does, checks ld and the buffer length before counting anything, and charges the cost of dgemv.

Key takeaways

  • Memory has one dimension A matrix needs an order and a leading dimension to be read back correctly. BLAS and LAPACK expect column-major; NumPy and C use row-major.
  • The wrong order does not raise Same numbers, different matrix, and a symmetric covariance matrix hides it. Test with a matrix that is neither symmetric nor square.
  • A window is a start plus the same ld That is how a routine works on part of a matrix with no copy. Next: the solvers that read these buffers.
Quick check
A 3 by 4 matrix is stored column-major with ld 3. Where is element (row 2, column 1), counting from 0?
Pick an answer.

Lab · what's graded

4 tasks · 100 pts
  • Find an element with offset25 pts
  • Store a matrix with pack25 pts
  • Read a matrix or a window with unpack25 pts
  • Multiply a flat matrix with gemv_flat25 pts
Explorer · lab-3-1
▾ lab-3-1
…
bash · in-browser
learner@quantcraft:~/lab-3-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

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