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 19, 2024
2 parents 7539e7c + 86a75ae commit de4ab91
Showing 1 changed file with 19 additions and 6 deletions.
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 de4ab91

Please sign in to comment.