Skip to content

Commit

Permalink
sagemathgh-37375: Speed up square matrix times vector over GF(2)
Browse files Browse the repository at this point in the history
When doing a matrix-times-vector multiplication over F_2, there is some
inefficiency caused by calling `VectorSpace` to create a parent for the
result. This becomes noticeable when repeatedly multiplying small
matrices.

When the dimensions are all the same, this can be improved by using the
parent of the vector also as the parent for the result. Before:
```
sage: A = random_matrix(GF(2),10^2,10^2)
sage: v0 = vector(random_matrix(GF(2),10^2,1))
sage: %timeit A*v0
2.78 µs ± 128 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops
each)
```
After:
```
sage: A = random_matrix(GF(2),10,10)
sage: v0 = vector(random_matrix(GF(2),10,1))
sage: %timeit A*v0
995 ns ± 22.9 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops
each)
```

URL: sagemath#37375
Reported by: kedlaya
Reviewer(s): Lorenz Panny
  • Loading branch information
Release Manager committed Feb 18, 2024
2 parents 51b26bf + 86a75ae commit 4ef440c
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 10 deletions.
6 changes: 3 additions & 3 deletions build/pkgs/configure/checksums.ini
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
tarball=configure-VERSION.tar.gz
sha1=0c93ffbc40ee55c429b82c6070817c0133a05013
md5=96e8d0c3aa48cab18b60499c4d303a73
cksum=2523075193
sha1=916d899be471df2370fc359c35a08ee524ad5676
md5=7088925f8d8c9d4954c44c72b0201031
cksum=877876854
2 changes: 1 addition & 1 deletion build/pkgs/configure/package-version.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
81a374dc4dacba71cf071f981d496ff63b2b2acb
d54fa043a6118f6220b0a7071ee465c14599b3d0
25 changes: 19 additions & 6 deletions src/sage/matrix/matrix_mod2_dense.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -595,14 +595,27 @@ cdef class Matrix_mod2_dense(matrix_dense.Matrix_dense): # dense or sparse
sage: v = vector(GF(2), 0)
sage: m * v
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
Add a test involving a nonsquare matrix::
sage: A = random_matrix(GF(2),10^4,10^3)
sage: v0 = random_matrix(GF(2),10^3,1)
sage: v1 = v0.column(0)
sage: r0 = A*v0
sage: r1 = A*v1
sage: r0.column(0) == r1
True
"""
cdef mzd_t *tmp
global VectorSpace
if VectorSpace is None:
from sage.modules.free_module import VectorSpace
VS = VectorSpace(self._base_ring, self._nrows)
if not isinstance(v, Vector_mod2_dense):
v = VS(v)
if self._nrows == self._ncols and isinstance(v, Vector_mod2_dense):
VS = v.parent()
else:
global VectorSpace
if VectorSpace is None:
from sage.modules.free_module import VectorSpace
VS = VectorSpace(self._base_ring, self._nrows)
if not isinstance(v, Vector_mod2_dense):
v = VS(v)
if self.ncols() != v.degree():
raise ArithmeticError("number of columns of matrix must equal degree of vector")

Expand Down

0 comments on commit 4ef440c

Please sign in to comment.