σμ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 4 · Calling it for real›Topic 4.1·~1 hrAdvanced

Calling BLAS and LAPACK from C

Skill positionModule 4 of 4 · Topic 1 of 2
4.1 Calling BLAS and LAPACK from C
—Lab score— / 100Total XP—Streak—
Lecture0% read

4 min readCode examples: 4

  1. 01The idea in plain words
  2. 02The covariance in one call
  3. 03Illegal arguments
  4. 04Solving through LAPACKE
  5. 05What the tasks ask

The covariance matrix of five stocks is one C call with 14 arguments. Get the leading dimension of one of them wrong and BLAS stops with "parameter 9 had an illegal value". Get a different one wrong and it reads memory that is not yours without saying a word. Which arguments does the call check, and which does it trust?

01

The idea in plain words

Where we are. Everything so far was Python that behaved like BLAS and LAPACK. Real quant libraries are C and C++ programs that call the actual libraries, and the interface they use is the one in this topic. The previous topic chose a library; every library offers the same functions, so what you learn here works with all of them. The capstone then runs a whole pipeline.

In C, CBLAS is the standard C interface to BLAS (cblas_dgemm, cblas_dgemv, ...) and LAPACKE the one for LAPACK (LAPACKE_dgesv, ...). A matrix is not an object but a pointer to doubles plus numbers that describe it. For every matrix you pass the three things from topic 3: where it starts, its layout, and its leading dimension. Nothing else tells the library how big the buffer is.

cov.cc
/* Covariance of five stocks: C = (1/249) * X^T * X, with X stored row-major as 250 rows of 5 */#include <cblas.h>double x[250 * 5];   /* demeaned daily returns, one row per day */double cov[5 * 5];cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans,            5, 5, 250,        /* m, n, k: op(A) is 5 by 250, op(B) is 250 by 5 */1            1.0 / 249, x, 5,  /* alpha, A, lda: A is stored 250 by 5, a row has 5 numbers */2            x, 5,             /* B, ldb */            0.0, cov, 5);     /* beta, C, ldc: C is 5 by 5 */
  1. 1m, n and k describe the product op(A) op(B), not the stored shapes. A is stored 250 by 5 but transposed, so op(A) is 5 by 250.
  2. 2In row-major lda is the length of a stored row (5), not the number of rows (250). In column-major it would be 250.
  • LayoutSmallest leading dimension of a stored `rows` by `cols` matrix
  • CblasRowMajorA row is contiguousmax(1, cols)
  • CblasColMajorA column is contiguousmax(1, rows)
02

The covariance in one call

Our Python cblas_dgemm has the same arguments, with the counter first. x_row is X stored row-major (250 rows of 5) and x_col the same data column-major. The answer must not depend on which layout we chose, as long as the flags and leading dimensions say the truth.

main.pyPython
# The same covariance from the row-major copy and from the column-major copycov_row = [0.0] * 25blas = Blas()cblas_dgemm(blas, CblasRowMajor, CblasTrans, CblasNoTrans, 5, 5, 250, 1 / 249, x_row, 5, x_row, 5, 0.0, cov_row, 5)print("row-major:   flops", blas.flops, "words", blas.words, "| variances (e-4):", [round(cov_row[i * 5 + i] * 1e4, 2) for i in range(5)])1cov_col = [0.0] * 25cblas_dgemm(Blas(), CblasColMajor, CblasTrans, CblasNoTrans, 5, 5, 250, 1 / 249, x_col, 250, x_col, 250, 0.0, cov_col, 5)print("col-major:   variances (e-4):", [round(cov_col[i * 5 + i] * 1e4, 2) for i in range(5)])print("same matrix?", all(abs(cov_row[i * 5 + j] - cov_col[j * 5 + i]) < 1e-12 for i in range(5) for j in range(5)))
row-major:   flops 12500 words 2525 | variances (e-4): [2.5, 1.97, 2.57, 1.4, 1.41]
col-major:   variances (e-4): [2.5, 1.97, 2.57, 1.4, 1.41]
same matrix? True
  1. 1The same 12,500 flops as the covariance in topic 1; the call also reads 1,250 + 1,250 numbers, and writes 25.
03

Illegal arguments

Before computing anything, the reference BLAS checks the arguments it can check, in order, and reports the first bad one by its position in the argument list. This position is what check_gemm_args returns. The classic mistake is a layout mix-up: a leading dimension that is right for row-major but too small for column-major. LAPACKE reports the same kind of problem differently: as a negative return value, not by stopping.

main.pyPython
# The row-major leading dimension is wrong for column-major dataprint("row-major lda=5:", check_gemm_args(CblasRowMajor, CblasTrans, CblasNoTrans, 5, 5, 250, 5, 5, 5))print("col-major lda=5:", check_gemm_args(CblasColMajor, CblasTrans, CblasNoTrans, 5, 5, 250, 5, 250, 5))try:    cblas_dgemm(Blas(), CblasColMajor, CblasTrans, CblasNoTrans, 5, 5, 250, 1 / 249, x_col, 5, x_col, 250, 0.0, [0.0] * 25, 5)except ValueError as error:    print("cblas_dgemm:", error)1print("min_lda for a stored 250 by 5:", min_lda(CblasRowMajor, 250, 5), "row-major,", min_lda(CblasColMajor, 250, 5), "column-major")
row-major lda=5: 0
col-major lda=5: 9
cblas_dgemm: parameter 9 had an illegal value
min_lda for a stored 250 by 5: 5 row-major, 250 column-major
  1. 1Parameter 9 is lda: the call stops before it reads a single number.
What the real library does not check

The real cblas_dgemm receives a pointer and has no way to know where the buffer ends. Our buffer too short error is a courtesy of the model; in C, a buffer that is too small is read anyway, and you get wrong numbers or a crash, sometimes only on some inputs. A legal lda says nothing about whether your array is big enough. Allocate lda * rows (row-major) or lda * cols (column-major) numbers at least.

04

Solving through LAPACKE

LAPACKE_dgesv(layout, n, nrhs, a, lda, ipiv, b, ldb) overwrites a with the LU factors, fills ipiv and replaces b by the solutions, and returns an int. The row-major trap is ldb: b is n rows of nrhs numbers, so its leading dimension is nrhs, not n. We solve the minimum-variance system again, with the covariance matrix just built.

main.pyPython
# Minimum-variance weights through the LAPACKE interface, in both layoutsa, b, ipiv = list(cov_row), [1.0] * 5, [0] * 5info = lapacke_dgesv(Blas(), CblasRowMajor, 5, 1, a, 5, ipiv, b, 1)weights = [v / sum(b) for v in b]print("row-major: info", info, "| ipiv", ipiv, "| weights", [round(w, 3) for w in weights])1a2, b2, ipiv2 = list(cov_col), [1.0] * 5, [0] * 5info2 = lapacke_dgesv(Blas(), CblasColMajor, 5, 1, a2, 5, ipiv2, b2, 5)print("col-major: info", info2, "| same weights?", all(abs(x - y) < 1e-6 * abs(y) for x, y in zip(b2, b)))print("ldb=0 in row-major:", lapacke_dgesv(Blas(), CblasRowMajor, 5, 1, list(cov_row), 5, [0] * 5, [1.0] * 5, 0), "(argument 8 is illegal)")print("ldb=5 in column-major with nrhs=1 and a 5-number b:", lapacke_dgesv(Blas(), CblasColMajor, 5, 1, list(cov_col), 5, [0] * 5, [1.0] * 5, 5))
row-major: info 0 | ipiv [1, 2, 3, 4, 5] | weights [0.147, 0.242, 0.176, 0.199, 0.236]
col-major: info 0 | same weights? True
ldb=0 in row-major: -8 (argument 8 is illegal)
ldb=5 in column-major with nrhs=1 and a 5-number b: 0
  1. 1Weights of about 15%, 24%, 18%, 20% and 24%: the same as in the solver topic, now from a flat buffer and the C-style interface.
05

What the tasks ask

  1. 1
    `min_lda` and `check_gemm_args`The smallest legal leading dimension for a layout, and the position of the first illegal argument of a dgemm call, checked in the order of the argument list.
  2. 2
    `cblas_dgemm`Validate, check the buffers, then compute alpha op(A) op(B) + beta C in place with every element placed by offset. With beta equal to 0 the old C is never read.
  3. 3
    `lapacke_dgesv`Return info instead of raising: the negative position of an illegal argument, the positive info of a singular matrix, 0 after writing LU, pivots and solutions back in the caller's layout.

Key takeaways

  • A matrix is a pointer plus three numbers Layout, transpose flag and leading dimension must tell the truth about the buffer, because the library cannot see it.
  • BLAS stops, LAPACKE returns An illegal argument aborts a CBLAS call but comes back as a negative number from LAPACKE; check the return value of every LAPACKE call.
  • Time to put it together The capstone builds a covariance and eigenvalue pipeline on real returns, with a cost model to report on it.
Quick check
A 250 by 5 matrix of returns is stored row-major and you pass it to cblas_dgemm as A with CblasTrans. What is the lda?
Pick an answer.

Lab · what's graded

4 tasks · 100 pts
  • Smallest legal ld with min_lda25 pts
  • Find the illegal argument with check_gemm_args25 pts
  • Multiply in place with cblas_dgemm25 pts
  • Solve through lapacke_dgesv25 pts
Explorer · lab-9-1
▾ lab-9-1
…
bash · in-browser
learner@quantcraft:~/lab-9-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

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