Debian Codegraph @

tests/test_gemm.py

raw
1 from __future__ import division
2 from hypothesis import given, assume
3 from math import sqrt, floor
4 import numpy as np
5 import pytest
6
7 from blis_tests_common import *
8 from blis.py import gemm
9
10
11 def _stretch_matrix(data, m, n):
12 orig_len = len(data)
13 orig_m = m
14 orig_n = n
15 ratio = sqrt(len(data) / (m * n))
16 m = int(floor(m * ratio))
17 n = int(floor(n * ratio))
18 data = np.ascontiguousarray(data[:m*n], dtype=data.dtype)
19 return data.reshape((m, n)), m, n
20
21 def _reshape_for_gemm(A, B, a_rows, a_cols, out_cols, dtype, trans_a=False, trans_b=False):
22 A, a_rows, a_cols = _stretch_matrix(A, a_rows, a_cols)
23 if len(B) < a_cols or a_cols < 1:
24 return (None, None, None)
25 b_cols = int(floor(len(B) / a_cols))
26 B = np.ascontiguousarray(B.flatten()[:a_cols*b_cols], dtype=dtype)
27 B = B.reshape((a_cols, b_cols))
28 out_cols = B.shape[1]
29 C = np.zeros(shape=(A.shape[0], B.shape[1]), dtype=dtype)
30 if trans_a:
31 A = np.ascontiguousarray(A.T, dtype=dtype)
32 return A, B, C
33
34
35 def test_incompatible_shape():
36 with pytest.raises(ValueError):
37 gemm(np.zeros((2, 2)), np.zeros((3, 2)))
38 with pytest.raises(ValueError):
39 gemm(np.zeros((3, 2)), np.zeros((2, 2)), trans1=True)
40 with pytest.raises(ValueError):
41 gemm(np.zeros((2, 2)), np.zeros((2, 3)), trans2=True)
42 with pytest.raises(ValueError):
43 gemm(np.zeros((3, 2)), np.zeros((3, 2)), trans1=True, trans2=True)
44
45
46 @given(
47 ndarrays(min_len=10, max_len=100,
48 min_val=-100.0, max_val=100.0, dtype='float64'),
49 ndarrays(min_len=10, max_len=100,
50 min_val=-100.0, max_val=100.0, dtype='float64'),
51 integers(min_value=2, max_value=1000),
52 integers(min_value=2, max_value=1000),
53 integers(min_value=2, max_value=1000))
54 def test_memoryview_double_notrans(A, B, a_rows, a_cols, out_cols):
55 A, B, C = _reshape_for_gemm(A, B, a_rows, a_cols, out_cols, 'float64')
56 assume(A is not None)
57 assume(B is not None)
58 assume(C is not None)
59 assume(A.size >= 1)
60 assume(B.size >= 1)
61 assume(C.size >= 1)
62 gemm(A, B, out=C)
63 numpy_result = A.dot(B)
64 assert_allclose(numpy_result, C, atol=1e-3, rtol=1e-3)
65
66
67 @given(
68 ndarrays(min_len=10, max_len=100,
69 min_val=-100.0, max_val=100.0, dtype='float32'),
70 ndarrays(min_len=10, max_len=100,
71 min_val=-100.0, max_val=100.0, dtype='float32'),
72 integers(min_value=2, max_value=1000),
73 integers(min_value=2, max_value=1000),
74 integers(min_value=2, max_value=1000))
75 def test_memoryview_float_notrans(A, B, a_rows, a_cols, out_cols):
76 A, B, C = _reshape_for_gemm(A, B, a_rows, a_cols, out_cols, dtype='float32')
77 assume(A is not None)
78 assume(B is not None)
79 assume(C is not None)
80 assume(A.size >= 1)
81 assume(B.size >= 1)
82 assume(C.size >= 1)
83 gemm(A, B, out=C)
84 numpy_result = A.dot(B)
85 assert_allclose(numpy_result, C, atol=1e-3, rtol=1e-3)