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?
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.
/* 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
m,nandkdescribe the productop(A) op(B), not the stored shapes. A is stored 250 by 5 but transposed, soop(A)is 5 by 250. - 2In row-major
ldais 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)
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.
# 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
- 1The same 12,500 flops as the covariance in topic 1; the call also reads 1,250 + 1,250 numbers, and writes 25.
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.
# 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
- 1Parameter 9 is
lda: the call stops before it reads a single number.
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.
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.
# 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
- 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.
What the tasks ask
- 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
dgemmcall, checked in the order of the argument list. - 2`cblas_dgemm`Validate, check the buffers, then compute
alpha op(A) op(B) + beta Cin place with every element placed byoffset. Withbetaequal to 0 the old C is never read. - 3`lapacke_dgesv`Return
infoinstead of raising: the negative position of an illegal argument, the positiveinfoof a singular matrix, 0 after writing LU, pivots and solutions back in the caller's layout.
cblas_dgemm as A with CblasTrans. What is the lda?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