Skip to content

$ Matrix Multiply, mmu

Matrix multiply, dot product

x mmu y    mmu[x;y]
x$y        $[x;y]

Where x and y are both float vectors or matrixes, returns their matrix or dot product.

count y must match one of the following:

  • count x where x is a vector
  • count first x where x is a matrix
q)a:2 4#2 4 8 3 5 6 0 7f
q)b:4 3#"f"$til 12
q)a mmu b
87 104 121
81 99  117

q)c:3 3#2 4 8 3 5 6 0 7 1f
q)1=c mmu inv c
100b
010b
001b

q)(1 2 3f;4 5 6f)$(7 8f;9 10f;11 12f)
58  64
139 154

q)1 2 3f$4 5 6f  /dot product of two vectors
32f

Each item of the result is the dot product of a row of x and a column of y:

q)(a mmu b)[0;1]
104f
q)sum a[0]*b[;1]
104f

Other numeric types signal a type error, so convert them to float first. Arguments whose lengths don't match signal a length error.

q)1 2 3$4 5 6
'type
  [0]  1 2 3$4 5 6
            ^
q)1 2 3f$4 5f
'length
  [0]  1 2 3f$4 5f
             ^

Working in parallel

Use secondary threads via peach.

q)mmu[;b]peach a
87 104 121
81 99  117

BLAS module

For large matrixes, the BLAS module runs matrix multiplication in an optimized BLAS library such as OpenBLAS or Intel MKL. blas.dgemm[A;B;C;params] returns (alpha*op[A] mmu op[B])+beta*C, where op optionally transposes its argument, so you can scale, transpose, and add in a single call.

Load the module, naming the BLAS library to use:

blas:use(`kx.fusion:blas;([lib:`openblas]))

On macOS, pass the file name or path of the library as a string instead, for example ([lib:"libopenblas.dylib"]), or ([lib:"/System/Library/Frameworks/Accelerate.framework/Versions/Current/Frameworks/vecLib.framework/vecLib"]) for Apple Accelerate.

q)x:(1 2 3f;4 5 6f)
q)y:(7 8f;9 10f;11 12f)
q)blas.dgemm[x;y;2 2#0f;([alpha:1f;beta:0f;transA:"N";transB:"N"])]
58  64
139 154
q)blas.ddot[1 2 3f;4 5 6f]   / dot product
32f

The results can differ from mmu in the last digits, because the library can sum the products in a different order.

A q matrix is a list of separate row vectors, but BLAS needs each matrix in one contiguous block of memory. blas.dgemm therefore copies its matrix arguments to contiguous memory before calling the library, which needs extra memory of about the size of the arguments. Vector arguments are passed without a copy.

The benefit of the BLAS module comes mainly from matrix operations such as blas.dgemm. For elementwise vector operations such as blas.daxpy and blas.dscal, q’s own arithmetic (for example y+a*x or a*x) is about as fast. Measure on your own hardware and data.


Overloads of $

Mathematics, BLAS module

Matrix multiplication