MAT Manual
Table of Contents
 1 The mglmat ASDF System
 2 Links
 3 Introduction
 4 Tutorial
 5 Basics
 6 Element types
 7 Printing
 8 Shaping
 9 Assembling
 10 Caching
 11 BLAS Operations
 12 Destructive API
 13 Nondestructive API
 14 Mappings
 15 Random numbers
 16 I/O
 17 Debugging
 18 Facet API
 19 Writing Extensions
[in package MGLMAT]
1 The mglmat ASDF System
 Version: 0.1.0
 Description:
mat
is library for working with multidimensional arrays which supports efficient interfacing to foreign and CUDA code. BLAS and CUBLAS bindings are available.  Licence: MIT, see COPYING.
 Author: GĂˇbor Melis mailto:mega@retes.hu
 Mailto: mega@retes.hu
 Homepage: http://melisgl.github.io/mglmat
 Bug tracker: https://github.com/melisgl/mglmat/issues
 Source control: GIT
2 Links
Here is the official repository and the HTML documentation for the latest version.
3 Introduction
3.1 What's MGLMAT?
MGLMAT is library for working with multidimensional arrays which supports efficient interfacing to foreign and CUDA code with automatic translations between cuda, foreign and lisp storage. BLAS and CUBLAS bindings are available.
3.2 What kind of matrices are supported?
Currently only rowmajor single and double float matrices are supported, but it would be easy to add single and double precision complex types too. Other numeric types, such as byte and native integer, can be added too, but they are not supported by CUBLAS. There are no restrictions on the number of dimensions, and reshaping is possible. All functions operate on the visible portion of the matrix (which is subject to displacement and shaping), invisible elements are not affected.
3.3 Where to Get it?
All dependencies are in quicklisp except for
CLCUDA that needs to be
fetched from github. Just clone CLCUDA and MGLMAT into
quicklisp/localprojects/
and you are set. MGLMAT itself lives
at github, too.
Prettierthanmarkdown HTML documentation crosslinked with other libraries is available as part of PAX World.
4 Tutorial
We are going to see how to create matrices, access their contents.
Creating matrices is just like creating lisp arrays:
(makemat '6)
==> #<MAT 6 A #(0.0d0 0.0d0 0.0d0 0.0d0 0.0d0 0.0d0)>
(makemat '(2 3) :ctype :float :initialcontents '((1 2 3) (4 5 6)))
==> #<MAT 2x3 AB #2A((1.0 2.0 3.0) (4.0 5.0 6.0))>
(makemat '(2 3 4) :initialelement 1)
==> #<MAT 2x3x4 A #3A(((1.0d0 1.0d0 1.0d0 1.0d0)
> (1.0d0 1.0d0 1.0d0 1.0d0)
> (1.0d0 1.0d0 1.0d0 1.0d0))
> ((1.0d0 1.0d0 1.0d0 1.0d0)
> (1.0d0 1.0d0 1.0d0 1.0d0)
> (1.0d0 1.0d0 1.0d0 1.0d0)))>
The most prominent difference from lisp arrays is that mat
s are
always numeric and their element type (called ctype
here) defaults
to :double
.
Individual elements can be accessed or set with mref
:
(let ((m (makemat '(2 3))))
(setf (mref m 0 0) 1)
(setf (mref m 0 1) (* 2 (mref m 0 0)))
(incf (mref m 0 2) 4)
m)
==> #<MAT 2x3 AB #2A((1.0d0 2.0d0 4.0d0) (0.0d0 0.0d0 0.0d0))>
Compared to aref
mref
is a very expensive operation and it's best
used sparingly. Instead, typical code relies much more on matrix
level operations:
(princ (scal! 2 (fill! 3 (makemat 4))))
.. #<MAT 4 BF #(6.0d0 6.0d0 6.0d0 6.0d0)>
==> #<MAT 4 ABF #(6.0d0 6.0d0 6.0d0 6.0d0)>
The content of a matrix can be accessed in various representations called facets. MGLMAT takes care of synchronizing these facets by copying data around lazily, but doing its best to share storage for facets that allow it.
Notice the abf
in the printed results. It illustrates that behind
the scenes fill!
worked on the backingarray
facet (hence the b
) that's basically a 1d lisp array. scal!
on the
other hand made a foreign call to the BLAS dscal
function for
which it needed the foreignarray
facet (f
).
Finally, the a
stands for the array
facet that was
created when the array was printed. All facets are uptodate (else
some of the characters would be lowercase). This is possible because
these three facets actually share storage which is never the case
for the cudaarray
facet. Now if we have a
CUDAcapable GPU, CUDA can be enabled with withcuda*
:
(withcuda* ()
(princ (scal! 2 (fill! 3 (makemat 4)))))
.. #<MAT 4 C #(6.0d0 6.0d0 6.0d0 6.0d0)>
==> #<MAT 4 A #(6.0d0 6.0d0 6.0d0 6.0d0)>
Note the lonely c
showing that only the cudaarray
facet was used for both fill!
and scal!
. When withcuda*
exits and
destroys the CUDA context, it destroys all CUDA facets, moving their
data to the array
facet, so the returned mat
only has
that facet.
When there is no highlevel operation that does what we want, we may need to add new operations. This is usually best accomplished by accessing one of the facets directly, as in the following example:
(defun logdet (mat)
"Logarithm of the determinant of MAT. Return 1, 1 or 0 (or
equivalent) to correct for the sign, as the second value."
(withfacets ((array (mat 'array :direction :input)))
(lla:logdet array)))
Notice that logdet
doesn't know about CUDA at all. withfacets
gives it the content of the matrix as a normal multidimensional lisp
array, copying the data from the GPU or elsewhere if necessary. This
allows new representations (facet
s) to be added easily and it also
avoids copying if the facet is already uptodate. Of course, adding
CUDA support to logdet
could make it more efficient.
Adding support for matrices that, for instance, live on a remote machine is thus possible with a new facet type and existing code would continue to work (albeit possibly slowly). Then one could optimize the bottleneck operations by sending commands over the network instead of copying data.
It is a bad idea to conflate resource management policy and algorithms. MGLMAT does its best to keep them separate.
5 Basics

A
mat
is a datacube
that is much like a lisp array, it supportsdisplacement
, arbitrarydimensions
andinitialelement
with the usual semantics. However, amat
supports different representations of the same data. See Tutorial for an introduction.
[reader] matctype mat (:ctype = *defaultmatctype*)
One of
*supportedctypes*
. The matrix can hold only values of this type.
[reader] matdisplacement mat (:displacement = 0)
A value in the
[0,maxsize]
interval. This is like the DISPLACEDINDEXOFFSET of a lisp array, but displacement is relative to the start of the underlying storage vector.
[reader] matdimensions mat (:dimensions)
Like
arraydimensions
. It holds a list of dimensions, but it is allowed to pass in scalars too.
[function] matdimension mat axisnumber
Return the dimension along
axisnumber
. Similar toarraydimension
.
[reader] matinitialelement mat (:initialelement = 0)
If nonnil, then when a facet is created, it is filled with
initialelement
coerced to the appropriate numeric type. Ifnil
, then no initialization is performed.

The number of elements in the visible portion of the array. This is always the product of the elements
matdimensions
and is similar toarraytotalsize
.
[reader] matmaxsize mat (:maxsize)
The number of elements for which storage may be allocated. This is
displacement
+matsize
+slack
whereslack
is the number of trailing invisible elements.
[function] makemat dimensions &rest args &key (ctype *defaultmatctype*) (displacement 0) maxsize initialelement initialcontents (synchronization *defaultsynchronization*) displacedto (cudaenabled *defaultmatcudaenabled*)
Return a new
mat
object. Ifinitialcontents
is given then the matrix contents are initialized withreplace!
. See classmat
for the description of the rest of the parameters. This is exactly what (makeinstance
'mat
...) does exceptdimensions
is not a keyword argument so thatmakemat
looks more likemakearray
. The semantics ofsynchronization
are desribed in the Synchronization section.If specified,
displacedto
must be amat
object large enough (in the sense of itsmatsize
), to holddisplacement
plus(reduce #'* dimensions)
elements. Just like withmakearray
,initialelement
andinitialcontents
must not be supplied together withdisplacedto
. See Shaping for more.
[function] arraytomat array &key ctype (synchronization *defaultsynchronization*)
Create a
mat
that's equivalent toarray
. Displacement of the created array will be 0 and the size will be equal toarraytotalsize
. Ifctype
is nonnil, then it will be the ctype of the new matrix. Elsearray
's type is converted to a ctype. If there is no corresponding ctype, then*defaultmatctype*
is used. Elements ofarray
are coerced toctype
.Also see Synchronization.
[function] replace! mat seqofseqs
Replace the contents of
mat
with the elements ofseqofseqs
.seqofseqs
is a nested sequence of sequences similar to theinitialcontents
argument ofmakearray
. The total number of elements must match the size ofmat
. Returnsmat
.seqofseqs
may contain multidimensional arrays as leafs, so the following is legal:(replace! (makemat '(1 2 3)) '(#2A((1 2 3) (4 5 6)))) ==> #<MAT 1x2x3 AB #3A(((1.0d0 2.0d0 3.0d0) (4.0d0 5.0d0 6.0d0)))>
[function] mref mat &rest indices
Like
aref
for arrays. Don't use this if you care about performance at all.setf
able. When set, the value is coerced to the ctype ofmat
withcoercetoctype
. Note that currentlymref
always operates on thebackingarray
facet so it can trigger copying of facets. When it'ssetf
'ed, however, it will update thecudaarray
if cuda is enabled and it is uptodate or there are no facets at all.
[function] rowmajormref mat index
Like
rowmajoraref
for arrays. Don't use this if you care about performance at all.setf
able. When set, the value is coerced to the ctype ofmat
withcoercetoctype
. Note that currentlyrowmajormref
always operates on thebackingarray
facet so it can trigger copying of facets. When it'ssetf
'ed, however, it will update thecudaarray
if cuda is enabled and it is uptodate or there are no facets at all.
[function] matrowmajorindex mat &rest subscripts
Like
arrayrowmajorindex
for arrays.
6 Element types
 [variable] *supportedctypes* (:float :double)
[variable] *defaultmatctype* :double
By default
mat
s are created with this ctype. One of:float
or:double
.
[function] coercetoctype x &key (ctype *defaultmatctype*)
Coerce the scalar
x
to the lisp type corresponding toctype
.
7 Printing

Controls whether the contents of a
mat
object are printed as an array (subject to the standard printer control variables).
[variable] *printmatfacets* t
Controls whether a summary of existing and uptodate facets is printed when a
mat
object is printed. The summary that looks likeABcfh
indicates that all five facets (array
,backingarray
,cudaarray
,foreignarray
,cudahostarray
) are present and the first two are uptodate. A summary of a single # indicates that there are no facets.
8 Shaping
We are going to discuss various ways to change the visible portion
and dimensions of matrices. Conceptually a matrix has an underlying
nondisplaced storage vector. For (makemat 10 :displacement
7 :maxsize 21)
this underlying vector looks like this:
displacement  visible elements  slack
. . . . . . . 0 0 0 0 0 0 0 0 0 0 . . . .
Whenever a matrix is reshaped (or displaced to in lisp terminology), its displacement and dimensions change but the underlying vector does not.
The rules for accessing displaced matrices is the same as always: multiple readers can run in parallel, but attempts to write will result in an error if there are either readers or writers on any of the matrices that share the same underlying vector.
8.1 Comparison to Lisp Arrays
One way to reshape and displace mat
objects is with makemat
and
its displacedto
argument whose semantics are similar to that of
makearray
in that the displacement is relative to the
displacement of displacedto
.
(let* ((base (makemat 10 :initialelement 5 :displacement 1))
(mat (makemat 6 :displacedto base :displacement 2)))
(fill! 1 mat)
(values base mat))
==> #<MAT 1+10+0 A #(5.0d0 5.0d0 1.0d0 1.0d0 1.0d0 1.0d0 1.0d0 1.0d0 5.0d0
> 5.0d0)>
==> #<MAT 3+6+2 AB #(1.0d0 1.0d0 1.0d0 1.0d0 1.0d0 1.0d0)>
There are important semantic differences compared to lisp arrays all which follow from the fact that displacement operates on the underlying conceptual nondisplaced vector.
Matrices can be displaced and have slack even without
displacedto
just likebase
in the above example.It's legal to alias invisible elements of
displacedto
as long as the new matrix fits into the underlying storage.Negative displacements are allowed with
displacedto
as long as the adjusted displacement is nonnegative.Further shaping operations can make invisible portions of the
displacedto
matrix visible by changing the displacement.In contrast to
arraydisplacement
,matdisplacement
only returns an offset into the underlying storage vector.
8.2 Functional Shaping
The following functions are collectively called the functional shaping operations, since they don't alter their arguments in any way. Still, since storage is aliased modification to the returned matrix will affect the original.
[function] reshapeanddisplace mat dimensions displacement
Return a new matrix of
dimensions
that aliasesmat
's storage at offsetdisplacement
.displacement
0 is equivalent to the start of the storage ofmat
regardless ofmat
's displacement.
[function] reshape mat dimensions
Return a new matrix of
dimensions
whose displacement is the same as the displacement ofmat
.
[function] displace mat displacement
Return a new matrix that aliases
mat
's storage at offsetdisplacement
.displacement
0 is equivalent to the start of the storage ofmat
regardless ofmat
's displacement. The returned matrix has the same dimensions asmat
.
8.3 Destructive Shaping
The following destructive operations don't alter the contents of
the matrix, but change what is visible. adjust!
is the odd one out,
it may create a new mat
.
[function] reshapeanddisplace! mat dimensions displacement
Change the visible (or active) portion of
mat
by altering its displacement offset and dimensions. Future operations will only affect this visible portion as if the rest of the elements were not there. Returnmat
.displacement
+ the new size must not exceedmatmaxsize
. Furthermore, there must be no facets being viewed (withwithfacets
) when calling this function as the identity of the facets is not stable.
[function] reshape! mat dimensions
Like
reshapeanddisplace!
but only alters the dimensions.
[function] displace! mat displacement
Like
reshapeanddisplace!
but only alters the displacement.
[function] reshapetorowmatrix! mat row
Reshape the 2d
mat
to make only a singlerow
visible. This is made possible by the rowmajor layout, hence no column counterpart. Returnmat
.
[macro] withshapeanddisplacement (mat &optional (dimensions nil) (displacement nil)) &body body
Reshape and displace
mat
ifdimensions
and/ordisplacement
is given and restore the original shape and displacement afterbody
is executed. If neither is specificed, then nothing will be changed, butbody
is still allowed to alter the shape and displacement.
[function] adjust! mat dimensions displacement &key (destroyoldp t)
Like
reshapeanddisplace!
but creates a new matrix ifmat
isn't large enough. If a new matrix is created, the contents are not copied over and the old matrix is destroyed withdestroycube
ifdestroyoldp
.
9 Assembling
The functions here assemble a single mat
from a number of
mat
s.
[function] stack! axis mats mat
Stack
mats
alongaxis
intomat
and returnmat
. Ifaxis
is 0, placemats
intomat
below each other starting from the top. Ifaxis
is 1, placemats
side by side starting from the left. Higheraxis
are also supported. All dimensions except foraxis
must be the same for allmats
.
[function] stack axis mats &key (ctype *defaultmatctype*)
Like
stack!
but return a newmat
ofctype
.(stack 1 (list (makemat '(3 2) :initialelement 0) (makemat '(3 1) :initialelement 1))) ==> #<MAT 3x3 B #2A((0.0d0 0.0d0 1.0d0) > (0.0d0 0.0d0 1.0d0) > (0.0d0 0.0d0 1.0d0))>
10 Caching
Allocating and initializing a mat
object and its necessary facets
can be expensive. The following macros remember the previous value
of a binding in the same thread and /place/. Only weak references
are constructed so the cached objects can be garbage collected.
While the cache is global, thread safety is guaranteed by having separate subcaches per thread. Each subcache is keyed by a /place/ object that's either explicitly specified or else is unique to each invocation of the caching macro, so different occurrences of caching macros in the source never share data. Still, recursion could lead to data sharing between different invocations of the same function. To prevent this, the cached object is removed from the cache while it is used so other invocations will create a fresh one which isn't particularly efficient but at least it's safe.
[macro] withthreadcachedmat (var dimensions &rest args &key (place :scratch) (ctype '*defaultmatctype*) (displacement 0) maxsize (initialelement 0) initialcontents) &body body
Bind
var
to a matrix ofdimensions
,ctype
, etc. Cache this matrix, and possibly reuse it later by reshaping it. Whenbody
exits the cached object is updated with the binding ofvar
whichbody
may change.There is a separate cache for each thread and each
place
(undereq
). Since every cache holds exactly onemat
perctype
, nestedwiththreadcachedmat
often want to use differentplace
s. By convention, these places are called:scratch1
,:scratch2
, etc.
[macro] withthreadcachedmats specs &body body
A shorthand for writing nested
withthreadcachedmat
calls.(withthreadcachedmat (a ...) (withthreadcachedmat (b ...) ...))
is equivalent to:
(withthreadcachedmat ((a ...) (b ...)) ...)
[macro] withones (var dimensions &key (ctype '*defaultmatctype*) (place :ones)) &body body
Bind
var
to a matrix ofdimensions
whose every element is 1. The matrix is cached for efficiency.
11 BLAS Operations
Only some BLAS functions are implemented, but it should be easy to
add more as needed. All of them default to using CUDA, if it is
initialized and enabled (see usecudap
).
Level 1 BLAS operations
[function] asum x &key (n (matsize x)) (incx 1)
Return the l1 norm of
x
, that is, sum of the absolute values of its elements.
[function] axpy! alpha x y &key (n (matsize x)) (incx 1) (incy 1)
Set
y
toalpha
*x
+y
. Returny
.
[function] copy! x y &key (n (matsize x)) (incx 1) (incy 1)
Copy
x
intoy
. Returny
.
[function] dot x y &key (n (matsize x)) (incx 1) (incy 1)
Return the dot product of
x
andy
.
[function] nrm2 x &key (n (matsize x)) (incx 1)
Return the l2 norm of
x
, which is the square root of the sum of the squares of its elements.
[function] scal! alpha x &key (n (matsize x)) (incx 1)
Set
x
toalpha
*x
. Returnx
.
Level 3 BLAS operations
[function] gemm! alpha a b beta c &key transposea? transposeb? m n k lda ldb ldc
Basically
c
=alpha
*a
' *b
' +beta
*c
.a
' isa
or its transpose depending ontransposea?
.b
' isb
or its transpose depending ontransposeb?
. Returnsc
.a
' is an MxK matrix.b
' is a KxN matrix.c
is an MxN matrix.lda
is the width of the matrixa
(not ofa
'). Ifa
is not transposed, thenk
<=lda
, if it's transposed thenm
<=lda
.ldb
is the width of the matrixb
(not ofb
'). Ifb
is not transposed, thenn
<=ldb
, if it's transposed thenk
<=ldb
.In the example below M=3, N=2, K=5, LDA=6, LDB=3, LDC=4. The cells marked with + do not feature in the calculation.
N + + K B+ + + +++ K + ++ M A+ C++ + ++ ++++++ ++++
12 Destructive API
[function] .square! x &key (n (matsize x))
Set
x
to its elementwise square. Returnx
.
[function] .sqrt! x &key (n (matsize x))
Set
x
to its elementwise square root. Returnx
.
[function] .log! x &key (n (matsize x))
Set
x
to its elementwise natural logarithm. Returnx
.
[function] .exp! x &key (n (matsize x))
Apply
exp
elementwise tox
in a destructive manner. Returnx
.
[function] .expt! x power
Raise matrix
x
topower
in an elementwise manner. Returnx
. Note that CUDA and nonCUDA implementations may disagree on the treatment of NaNs, infinities and complex results. In particular, the lisp implementation always computes therealpart
of the results while CUDA's pow() returns NaNs instead of complex numbers.
[function] .inv! x &key (n (matsize x))
Set
x
to its elementwise inverse(/ 1 x)
. Returnx
.
[function] .logistic! x &key (n (matsize x))
Destructively apply the logistic function to
x
in an elementwise manner. Returnx
.
[function] .+! alpha x
Add the scalar
alpha
to each element ofx
destructively modifyingx
. Returnx
.
 [function] .*! x y
[function] geem! alpha a b beta c
Like
gemm!
, but multiplication is elementwise. This is not a standard BLAS routine.
[function] geerv! alpha a x beta b
GEneric Elementwise Row  Vector multiplication.
B = beta * B + alpha a .* X*
wherex*
is a matrix of the same shape asa
whose every row isx
. Perform elementwise multiplication on each row ofa
with the vectorx
and add the scaled result to the corresponding row ofb
. Returnb
. This is not a standard BLAS routine.
[function] .<! x y
For each element of
x
andy
sety
to 1 if the element iny
is greater than the element inx
, and to 0 otherwise. Returny
.
[function] .min! alpha x
Set each element of
x
toalpha
if it's greater thanalpha
. Returnx
.
[function] .max! alpha x
Set each element of
x
toalpha
if it's less thanalpha
. Returnx
.
[function] addsign! alpha a beta b
Add the elementwise sign (1, 0 or 1 for negative, zero and positive numbers respectively) of
a
timesalpha
tobeta
*b
. Returnb
.
[function] fill! alpha x &key (n (matsize x))
Fill matrix
x
withalpha
. Returnx
.
[function] sum! x y &key axis (alpha 1) (beta 0)
Sum matrix
x
alongaxis
and addalpha
*sum
s tobeta
*y
destructively modifyingy
. Returny
. On a 2d matrix (nothing else is supported currently), ifaxis
is 0, then columns are summed, ifaxis
is 1 then rows are summed.
[function] scalerows! scales a &key (result a)
Set
result
todiag(scales)*a
and return it.a
is anMxN
matrix,scales
is treated as a lengthm
vector.
[function] scalecolumns! scales a &key (result a)
Set
result
toa*diag(scales)
and return it.a
is anMxN
matrix,scales
is treated as a lengthn
vector.
[function] .sin! x &key (n (matsize x))
Apply
sin
elementwise tox
in a destructive manner. Returnx
.
[function] .cos! x &key (n (matsize x))
Apply
cos
elementwise tox
in a destructive manner. Returnx
.
[function] .tan! x &key (n (matsize x))
Apply
tan
elementwise tox
in a destructive manner. Returnx
.
[function] .sinh! x &key (n (matsize x))
Apply
sinh
elementwise tox
in a destructive manner. Returnx
.
[function] .cosh! x &key (n (matsize x))
Apply
cosh
elementwise tox
in a destructive manner. Returnx
.
[function] .tanh! x &key (n (matsize x))
Apply
tanh
elementwise tox
in a destructive manner. Returnx
.
Finally, some neural network operations.
[function] convolve! x w y &key start stride anchor batched
y
=y
+ conv(x
,w
) and returny
. Ifbatched
, then the first dimension ofx
andy
is the number of elements in the batch (B), else B is assumed to be 1. The rest of the dimensions encode the input (x
) and output (y
) N dimensional feature maps.start
,stride
andanchor
are lists of length N.start
is the multidimensional index of the first element of the input feature map (for each element in the batch) for which the convolution must be computed. Then (elt
stride
( N 1)) is added to the last element ofstart
and so on until (arraydimension
x
1) is reached. Then the last element ofstart
is reset, (elt
stride
( N 2)) is added to the first but last element ofstart
and we scan the last dimension again. Take a 2d example,start
is (0 0),stride
is (1 2), andx
is a B*2x7 matrix.w
is:1 2 1 2 4 2 1 2 1
and
anchor
is (1 1) which refers to the element ofw
whose value is 4. This anchor point ofw
is placed over elements ofx
whose multi dimensional index is in numbers in this figure (only one element in the batch is shown):0,0 . 0,2 . 0,4 . 0,6 1,0 . 1,2 . 1,4 . 1,6
When applying
w
at position P ofx
, the convolution is the sum of the products of overlapping elements ofx
andw
whenw
'sanchor
is placed at P. Elements ofw
over the edges ofx
are multiplied with 0 so are effectively ignored. The order of application ofw
to positions defined bystart
,stride
andanchor
is undefined.y
must be a B*2x4 (or 2x4 if notbatched
) matrix in this example, just large enough to hold the results of the convolutions.
[function] deriveconvolve! x xd w wd yd &key start stride anchor batched
Add the dF/dX to
xd
and and dF/dW towd
whereyd
is dF/dY for some function F where Y is the result of convolution with the same arguments.
 [function] maxpool! x y &key start stride anchor batched pooldimensions
[function] derivemaxpool! x xd y yd &key start stride anchor batched pooldimensions
Add the dF/dX to
xd
and and dF/dW to WD whereyd
is dF/dY for some function F wherey
is the result ofmaxpool!
with the same arguments.
13 Nondestructive API

Return a copy of the active portion with regards to displacement and shape of
a
.
[function] copyrow a row
Return
row
ofa
as a new 1d matrix.
[function] copycolumn a column
Return
column
ofa
as a new 1d matrix.

Return the first element of
a
.a
must be of size 1.
[function] scalarasmat x &key (ctype (lisp>ctype (typeof x)))
Return a matrix of one dimension and one element:
x
.ctype
, the type of the matrix, defaults to the ctype corresponding to the type ofx
.
[function] m= a b
Check whether
a
andb
, which must be matrices of the same size, are elementwise equal.

Return the transpose of
a
.
[function] m* a b &key transposea? transposeb?
Compute op(
a
) * op(b
). Where op is either the identity or the transpose operation depending ontransposea?
andtransposeb?
.
[function] mm* m &rest args
Convenience function to multiply several matrices.
(mm* a b c) => a * b * c
[function] m a b
Return
a
b
.
[function] m+ a b
Return
a
+b
.

Return the inverse of
a
.
[function] logdet mat
Logarithm of the determinant of
mat
. Return 1, 1 or 0 (or equivalent) to correct for the sign, as the second value.
14 Mappings
[function] mapconcat fn mats mat &key key passrawp
Call
fn
with each element ofmats
andmat
temporarily reshaped to the dimensions of the current element ofmats
and returnmat
. For the next element the displacement is increased so that there is no overlap.mats
is keyed bykey
just like the CL sequence functions. Normally,fn
is called with the matrix returned bykey
. However, ifpassrawp
, then the matrix returned bykey
is only used to calculate dimensions and the element ofmats
that was passed tokey
is passed tofn
, too.(mapconcat #'copy! (list (makemat 2) (makemat 4 :initialelement 1)) (makemat '(2 3))) ==> #<MAT 2x3 AB #2A((0.0d0 0.0d0 1.0d0) (1.0d0 1.0d0 1.0d0))>
[function] mapdisplacements fn mat dimensions &key (displacementstart 0) displacementstep
Call
fn
withmat
reshaped todimensions
, first displaced bydisplacementstart
that's incremented bydisplacementstep
each iteration while there are enough elements left fordimensions
at the current displacement. Returnsmat
.(let ((mat (makemat 14 :initialcontents '(1 0 1 2 3 4 5 6 7 8 9 10 11 12)))) (reshapeanddisplace! mat '(4 3) 1) (mapdisplacements #'print mat 4)) .. .. #<MAT 1+4+9 B #(0.0d0 1.0d0 2.0d0 3.0d0)> .. #<MAT 5+4+5 B #(4.0d0 5.0d0 6.0d0 7.0d0)> .. #<MAT 9+4+1 B #(8.0d0 9.0d0 10.0d0 11.0d0)>
[function] mapmatsinto resultmat fn &rest mats
Like
cl:mapinto
but format
objects. Destructively modifiesresultmat
to contain the results of applyingfn
to each element in the argumentmats
in turn.
15 Random numbers
Unless noted these work efficiently with CUDA.
[genericfunction] copyrandomstate state
Return a copy of
state
be it a lisp or cuda random state.
[function] uniformrandom! mat &key (limit 1)
Fill
mat
with random numbers sampled uniformly from the [0,LIMIT) interval ofmat
's type.
[function] gaussianrandom! mat &key (mean 0) (stddev 1)
Fill
mat
with independent normally distributed random numbers withmean
andstddev
.
[function] mvgaussianrandom &key means covariances
Return a column vector of samples from the multivariate normal distribution defined by
means
(Nx1) andcovariances
(NxN). No CUDA implementation.
[function] orthogonalrandom! m &key (scale 1)
Fill the matrix
m
with random values in such a way thatm^t * m
is the identity matrix (or something close ifm
is wide). Returnm
.
16 I/O

If true, a header with
matctype
andmatsize
is written bywritemat
before the contents andreadmat
checks that these match the matrix into which it is reading.
[genericfunction] writemat mat stream
Write
mat
to binarystream
in portable binary format. Returnmat
. Displacement and size are taken into account, only visible elements are written. Also see*matheaders*
.
[genericfunction] readmat mat stream
Destructively modify the visible portion (with regards to displacement and shape) of
mat
by readingmatsize
number of elements from binarystream
. Returnmat
. Also see*matheaders*
.
17 Debugging
The largest class of bugs has to do with synchronization of facets
being broken. This is almost always caused by an operation that
mispecifies the direction
argument of withfacet
. For example, the
matrix argument of scal!
should be accessed with direciton :io
. But
if it's :input
instead, then subsequent access to the array
(0
1
) facet
will not see the changes made by axpy!
, and if it's :output
, then
any changes made to the array
facet since the last update of the
cudaarray
facet will not be copied and from the wrong input scal!
will compute the wrong result.
Using the SLIME inspector or trying to access the
cudaarray
facet from threads other than the one in
which the corresponding CUDA context was initialized will fail. For
now, the easy way out is to debug the code with CUDA disabled (see
*cudaenabled*
).
Another thing that tends to come up is figuring out where memory is used.
[function] matroom &key (stream *standardoutput*) (verbose t)
Calls
foreignroom
andcudaroom
.
[macro] withmatcounters (&key count nbytes) &body body
Count all
mat
allocations and also the number of bytes they may require. May require here really means an upper bound, because(makemat (expt 2 60))
doesn't actually uses memory until one of its facets is accessed (don't simply evaluate it though, printing the result will access thearray
facet if*printmat*
). Also, while facets today all require the same number of bytes, this may change in the future. This is a debugging tool, don't use it in production.(withmatcounters (:count count :nbytes nbytes) (assert (= count 0)) (assert (= nbytes 0)) (makemat '(2 3) :ctype :double) (assert (= count 1)) (assert (= nbytes (* 2 3 8))) (withmatcounters (:nbytes nbytes1 :count count1) (makemat '7 :ctype :float) (assert (= count1 1)) (assert (= nbytes1 (* 7 4)))) (assert (= nbytes (+ (* 2 3 8) (* 7 4)))) (assert (= count 2)))
18 Facet API
18.1 Facets
A mat
is a cube
(see Cube Manual) whose facets are
different representations of numeric arrays. These facets can be
accessed with withfacets
with one of the following
facetname
locatives:

The corresponding facet's value is a one dimensional lisp array or a static vector that also looks exactly like a lisp array but is allocated in foreign memory. See
*foreignarraystrategy*
.

Same as
backingarray
if the matrix is onedimensional, all elements are visible (see Shaping), else it's a lisp array displaced to the backing array.

The facet's value is a
foreignarray
which is anoffsetpointer
wrapping a CFFI pointer. See*foreignarraystrategy*
.

This facet's value is a basically the same as that of
foreignarray
. In fact, they share storage. The difference is that accessingcudahostarray
ensures that the foreign memory region is pagelocked and registered with the CUDA Driver API function cuMemHostRegister(). Copying between GPU memory (cudaarray
) and registered memory is significantly faster than with nonregistered memory and also allows overlapping copying with computation. Seewithsyncingcudafacets
.

The facet's value is a
cudaarray
, which is anoffsetpointer
wrapping aclcuda.driverapi:cudeviceptr
, allocated withclcuda.driverapi:cumemalloc
and freed automatically.
Facets bound by with withfacets
are to be treated as dynamic
extent: it is not allowed to keep a reference to them beyond the
dynamic scope of withfacets
.
For example, to implement the fill!
operation using only the
backingarray
, one could do this:
(let ((displacement (matdisplacement x))
(size (matsize x)))
(withfacets ((x* (x 'backingarray :direction :output)))
(fill x* 1 :start displacement :end (+ displacement size))))
direction
is :output
because we clobber all values in x
. Armed
with this knowledge about the direction, withfacets
will not copy
data from another facet if the backing array is not uptodate.
To transpose a 2d matrix with the array
facet:
(destructuringbind (nrows ncolumns) (matdimensions x)
(withfacets ((x* (x 'array :direction :io)))
(dotimes (row nrows)
(dotimes (column ncolumns)
(setf (aref x* row column) (aref x* column row))))))
Note that direction
is :io
, because we need the data in this facet
to be uptodate (that's the input part) and we are invalidating all
other facets by changing values (that's the output part).
To sum the values of a matrix using the foreignarray
facet:
(let ((sum 0))
(withfacets ((x* (x 'foreignarray :direction :input)))
(let ((pointer (offsetpointer x*)))
(loop for index below (matsize x)
do (incf sum (cffi:memaref pointer (matctype x) index)))))
sum)
See direction
for a complete description of :input
, :output
and :io
.
For mat
objects, that needs to be refined. If a mat
is reshaped
and/or displaced in a way that not all elements are visible then
those elements are always kept intact and copied around. This is
accomplished by turning :output
into :io
automatically on such mat
s.
We have finished our introduction to the various facets. It must be
said though that one can do anything without ever accessing a facet
directly or even being aware of them as most operations on mat
s
take care of choosing the most appropriate facet behind the scenes.
In particular, most operations automatically use CUDA, if available
and initialized. See withcuda*
for detail.
18.2 Foreign arrays
One facet of mat
objects is foreignarray
which is
backed by a memory area that can be a pinned lisp array or is
allocated in foreign memory depending on *foreignarraystrategy*
.

foreignarray
wraps a foreign pointer (in the sense ofcffi:pointerp
). That is, bothoffsetpointer
andbasepointer
return a foreign pointer. There are no other public operations that work withforeignarray
objects, their sole purpose is represent facets ofmat
objects.
[variable] *foreignarraystrategy* "see below"
One of
:pinned
,:static
and:cudahost
(see typeforeignarraystrategy
). This variable controls how foreign arrays are handled and it can be changed at any time.If it's
:pinned
(only supported if (pinningsupportedp
), then no separate storage is allocated for the foreign array. Instead, it aliases the lisp array (via thebackingarray
facet).If it's
:static
, then the lisp backing arrays are allocated statically via the staticvectors library. On some implementations, explicit freeing of static vectors is necessary, this is taken care of by finalizers or can be controlled withwithfacetbarrier
.destroycube
anddestroyfacet
may also be of help.:cudahost
is the same as:static
, but any copies to/from the GPU (i.e. thecudaarray
facet) will be done via thecudahostarray
facet whose memory pages will also be locked and registered withcuMemHostRegister
which allows quicker and asynchronous copying to and from CUDA land.The default is
:pinned
if available, because it's the most efficient. If pinning is not available, then it's:static
.

One of
:pinned
,:static
and:cudahost
. See*foreignarraystrategy*
for their semantics.
[function] pinningsupportedp
Return true iff the lisp implementation efficiently supports pinning lisp arrays. Pinning ensures that the garbage collector doesn't move the array in memory. Currently this is only supported on SBCL gencgc platforms.
[function] foreignroom &key (stream *standardoutput*) (verbose t)
Print a summary of foreign memory usage to
stream
. Ifverbose
, make the output human easily readable, else try to present it in a very concise way. Sample output withverbose
:Foreign memory usage: foreign arrays: 450 (used bytes: 3,386,295,808)
The same data presented with
verbose
false:f: 450 (3,386,295,808)
18.3 CUDA
[function] cudaavailablep &key (deviceid 0)
Check that a cuda context is already in initialized in the current thread or a device with
deviceid
is available.
[macro] withcuda* (&key (enabled '*cudaenabled*) (deviceid '*cudadefaultdeviceid*) (randomseed '*cudadefaultrandomseed*) (nrandomstates '*cudadefaultnrandomstates*) npoolbytes) &body body
Initializes CUDA with with all bells and whistles before
body
and deinitializes it after. Simply wrappingwithcuda*
around a piece code is enough to make use of the first available CUDA device or fall back on blas and lisp kernels if there is none.If CUDA is already initialized, then it sets up a facet barrier which destroys
cudaarray
andcudahostarray
facets after ensuring that thearray
facet is uptodate.Else, if CUDA is available and
enabled
, then in addition to the facet barrier, a CUDA context is set up,*nmemcpyhosttodevice*
,*nmemcpydevicetohost*
are bound to zero, a cublas handle created, and*curandstate*
is bound to acurandxorwowstate
withnrandomstates
, seeded withrandomseed
, and allocation of device memory is limited tonpoolbytes
(nil
means no limit, see CUDA Memory Management).Else  that is, if CUDA is not available,
body
is simply executed.
[function] callwithcuda fn &key ((:enabled *cudaenabled*) *cudaenabled*) (deviceid *cudadefaultdeviceid*) (randomseed *cudadefaultrandomseed*) (nrandomstates *cudadefaultnrandomstates*) npoolbytes
Like
withcuda*
, but takes a no argument function instead of the macro'sbody
.

Set or bind this to false to disable all use of cuda. If this is done from within
withcuda
, then cuda becomes temporarily disabled. If this is done from outsidewithcuda
, then it changes the default values of theenabled
argument of any futurewithcuda*
s which turns off cuda initialization entirely.
[accessor] cudaenabled mat (:cudaenabled = *defaultmatcudaenabled*)
The control provided by
*cudaenabled*
can be too coarse. This flag provides a perobject mechanism to turn cuda off. If it is set tonil
, then any operation that pays attention to this flag will not create or access thecudaarray
facet. Implementationally speaking, this is easily accomplished by usingusecudap
.
[variable] *defaultmatcudaenabled* t
The default for
cudaenabled
.
[variable] *nmemcpyhosttodevice* 0
Incremented each time a host to device copy is performed. Bound to 0 by
withcuda*
. Useful for tracking down performance problems.
[variable] *nmemcpydevicetohost* 0
Incremented each time a device to host copy is performed. Bound to 0 by
withcuda*
. Useful for tracking down performance problems.
[variable] *cudadefaultdeviceid* 0
The default value of
withcuda*
's:deviceid
argument.
[variable] *cudadefaultrandomseed* 1234
The default value of
withcuda*
's:randomseed
argument.
[variable] *cudadefaultnrandomstates* 4096
The default value of
withcuda*
's:nrandomstates
argument.
18.3.1 CUDA Memory Management
The GPU (called device in CUDA terminology) has its own memory and it can only perform computation on data in this device memory so there is some copying involved to and from main memory. Efficient algorithms often allocate device memory up front and minimize the amount of copying that has to be done by computing as much as possible on the GPU.
MGLMAT reduces the cost of device of memory allocations by
maintaining a cache of currently unused allocations from which it
first tries to satisfy allocation requests. The total size of all
the allocated device memory regions (be they in use or currently
unused but cached) is never more than npoolbytes
as specified in
withcuda*
. npoolbytes
being nil
means no limit.
[condition] cudaoutofmemory storagecondition
If an allocation request cannot be satisfied (either because of
npoolbytes
or physical device memory limits being reached), thencudaoutofmemory
is signalled.
[function] cudaroom &key (stream *standardoutput*) (verbose t)
When CUDA is in use (see
usecudap
), print a summary of memory usage in the current CUDA context tostream
. Ifverbose
, make the output human easily readable, else try to present it in a very concise way. Sample output withverbose
:CUDA memory usage: device arrays: 450 (used bytes: 3,386,295,808, pooled bytes: 1,816,657,920) host arrays: 14640 (used bytes: 17,380,147,200) host>device copies: 154,102,488, device>host copies: 117,136,434
The same data presented with
verbose
false:d: 450 (3,386,295,808 + 1,816,657,920), h: 14640 (17,380,147,200) h>d: 154,102,488, d>h: 117,136,434
That's it about reducing the cost allocations. The other important performance consideration, minimizing the amount copying done, is very hard to do if the data doesn't fit in device memory which is often a very limited resource. In this case the next best thing is to do the copying concurrently with computation.
[macro] withsyncingcudafacets (matstocuda matstocudahost &key (safep '*syncingcudafacetssafep*)) &body body
Update CUDA facets in a possibly asynchronous way while
body
executes. Behind the scenes, a separate CUDA stream is used to copy between registered host memory and device memory. Whenwithsyncingcudafacets
finishes either by returning normally or by a performing a nonlocalexit the following are true:All
mat
s inmatstocuda
have an uptodatecudaarray
facet.All
mat
s inmatstocudahost
have an uptodatecudahostarray
facet and nocudaarray
.
It is an error if the same matrix appears in both
matstocuda
andmatstocudahost
, but the same matrix may appear any number of times in one of them.If
safep
is true, then the all matrices in either of the two lists are effectively locked for output untilwithsyncingcudafacets
finishes. With SAFEnil
, unsafe accesses to facets of these matrices are not detected, but the whole operation has a bit less overhead.
[variable] *syncingcudafacetssafep* t
The default value of the
safep
argument ofwithsyncingcudafacets
.
Also note that often the easiest thing to do is to prevent the use
of CUDA (and consequently the creation of cudaarray
facets, and allocations). This can be done either by binding
*cudaenabled*
to nil
or by setting cudaenabled
to nil
on specific
matrices.
19 Writing Extensions
New operations are usually implemented in lisp, CUDA, or by calling a foreign function in, for instance, BLAS, CUBLAS, CURAND.
19.1 Lisp Extensions
[macro] definelispkernel (name &key (ctypes '(:float :double))) (&rest params) &body body
This is very much like
definecudakernel
but for normal lisp code. It knows how to deal withmat
objects and can define the same function for multiplectypes
. Example:(definelispkernel (lisp.+!) ((alpha singlefloat) (x :mat :input) (startx index) (n index)) (loop for xi oftype index upfrom startx below (the! index (+ startx n)) do (incf (aref x xi) alpha)))
Parameters are either of the form
(<name> <lisptype)
or(<name> :mat <direction>)
. In the latter case, the appropriate CFFI pointer is passed to the kernel.<direction>
is passed on to thewithfacet
that's used to acquire the foreign array. Note that the return type is not declared.Both the signature and the body are written as if for single floats, but one function is defined for each ctype in
ctypes
by transforming types, constants and code by substituting them with their ctype equivalents. Currently this means that one needs to write only one kernel forsinglefloat
anddoublefloat
. All such functions get the declaration from*defaultlispkerneldeclarations*
.Finally, a dispatcher function with
name
is defined which determines the ctype of themat
objects passed for:mat
typed parameters. It's an error if they are not of the same type. Scalars declaredsinglefloat
are coerced to that type and the appropriate kernel is called.
[variable] *defaultlispkerneldeclarations* ((optimize speed (sbc:insertarrayboundschecks 0)))
These declarations are added automatically to kernel functions.
19.2 CUDA Extensions
[function] usecudap &rest mats
Return true if cuda is enabled (
*cudaenabled*
), it's initialized and allmats
havecudaenabled
. Operations of matrices use this to decide whether to go for the CUDA implementation or BLAS/Lisp. It's provided for implementing new operations.
[function] choose1dblockandgrid n maxnwarpsperblock
Return two values, one suitable as the
:blockdim
, the other as the:griddim
argument for a cuda kernel call where both are onedimensional (only the first element may be different from 1).The number of threads in a block is a multiple of
*cudawarpsize*
. The number of blocks is between 1 and and*cudamaxnblocks*
. This means that the kernel must be able handle any number of elements in each thread. For example, a strided kernel that adds a constant to each element of a lengthn
vector looks like this:(let ((stride (* blockdimx griddimx))) (do ((i (+ (* blockdimx blockidxx) threadidxx) (+ i stride))) ((>= i n)) (set (aref x i) (+ (aref x i) alpha))))
It is often the most efficient to have
maxnwarpsperblock
around 4. Note that the maximum number of threads per block is limited by hardware (512 for compute capability < 2.0, 1024 for later versions), so*cudamaxnblocks*
timesmaxnwarpsperblock
must not exceed that limit.
[function] choose2dblockandgrid dimensions maxnwarpsperblock
Return two values, one suitable as the
:blockdim
, the other as the:griddim
argument for a cuda kernel call where both are twodimensional (only the first two elements may be different from 1).The number of threads in a block is a multiple of
*cudawarpsize*
. The number of blocks is between 1 and and*cudamaxnblocks*
. Currently  but this may change  theblockdimx
is always*cudawarpsize*
andgriddimx
is always 1.This means that the kernel must be able handle any number of elements in each thread. For example, a strided kernel that adds a constant to each element of a HEIGHT*WIDTH matrix looks like this:
(let ((idx (+ (* blockdimx blockidxx) threadidxx)) (idy (+ (* blockdimy blockidxy) threadidxy)) (stridex (* blockdimx griddimx)) (stridey (* blockdimy griddimy))) (do ((row idy (+ row stridey))) ((>= row height)) (let ((i (* row width))) (do ((column idx (+ column stridex))) ((>= column width)) (set (aref x i) (+ (aref x i) alpha)) (incf i stridex)))))
[function] choose3dblockandgrid dimensions maxnwarpsperblock
Return two values, one suitable as the
:blockdim
, the other as the:griddim
argument for a cuda kernel call where both are twodimensional (only the first two elements may be different from 1).The number of threads in a block is a multiple of
*cudawarpsize*
. The number of blocks is between 1 and and*cudamaxnblocks*
. Currently  but this may change  theblockdimx
is always*cudawarpsize*
andgriddimx
is always 1.This means that the kernel must be able handle any number of elements in each thread. For example, a strided kernel that adds a constant to each element of a
thickness
*height
*width
3d array looks like this:(let ((idx (+ (* blockdimx blockidxx) threadidxx)) (idy (+ (* blockdimy blockidxy) threadidxy)) (idz (+ (* blockdimz blockidxz) threadidxz)) (stridex (* blockdimx griddimx)) (stridey (* blockdimy griddimy)) (stridez (* blockdimz griddimz))) (do ((plane idz (+ plane stridez))) ((>= plane thickness)) (do ((row idy (+ row stridey))) ((>= row height)) (let ((i (* (+ (* plane height) row) width))) (do ((column idx (+ column stridex))) ((>= column width)) (set (aref x i) (+ (aref x i) alpha)) (incf i stridex))))))
[macro] definecudakernel (name &key (ctypes '(:float :double))) (returntype params) &body body
This is an extended
clcuda:defkernel
macro. It knows how to deal withmat
objects and can define the same function for multiplectypes
. Example:(definecudakernel (cuda.+!) (void ((alpha float) (x :mat :input) (n int))) (let ((stride (* blockdimx griddimx))) (do ((i (+ (* blockdimx blockidxx) threadidxx) (+ i stride))) ((>= i n)) (set (aref x i) (+ (aref x i) alpha)))))
The signature looks pretty much like in
clcuda:defkernel
, but parameters can take the form of(<name> :mat <direction>)
too, in which case the appropriateclcuda.driverapi:cudeviceptr
is passed to the kernel.<direction>
is passed on to thewithfacet
that's used to acquire the cuda array.Both the signature and the body are written as if for single floats, but one function is defined for each ctype in
ctypes
by transforming types, constants and code by substituting them with their ctype equivalents. Currently this means that one needs to write only one kernel forfloat
anddouble
.Finally, a dispatcher function with
name
is defined which determines the ctype of themat
objects passed for:mat
typed parameters. It's an error if they are not of the same type. Scalars declaredfloat
are coerced to that type and the appropriate kernel is called.
19.2.1 CUBLAS
In a withcuda*
BLAS Operations will automatically use CUBLAS. No need to
use these at all.
 [reader] cublaserrorfunctionname cublaserror (:functionname)
 [reader] cublaserrorstatus cublaserror (:status)
 [function] cublascreate handle
 [function] cublasdestroy &key (handle *cublashandle*)
 [macro] withcublashandle nil &body body
 [function] cublasgetversion version &key (handle *cublashandle*)
19.2.2 CURAND
This the low level CURAND API. You probably want Random numbers instead.
 [macro] withcurandstate (state) &body body