-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatrix_ops.py
103 lines (59 loc) · 1.89 KB
/
matrix_ops.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import math
import random
from itertools import cycle, islice
import numpy as np
from tqdm import tqdm
def shift(row, offset):
offset = offset % len(row)
return np.concatenate((row[offset:], row[:offset]))
def sigma(arr):
rows, _ = arr.shape
for idx in range(rows):
arr[idx] = shift(arr[idx], idx)
return arr
def theta(arr):
_, cols = arr.shape
for idx in range(cols):
arr[:,idx] = shift(arr[:,idx], idx)
return arr
def epsilon(arr, size, offset=0):
rows, _ = arr.shape
result = np.empty((rows, size))
for idx in range(rows):
result[idx] = np.array(list(
islice(cycle(shift(arr[idx], offset)), size)
))
return result
def omega(arr, size, offset=0):
_, cols = arr.shape
result = np.empty((size, cols))
for idx in range(cols):
result[:, idx] = np.array(list(
islice(cycle(shift(arr[:, idx], offset)), size)
))
return result
def hegmm(a, b):
assert a.ndim == 2, "matmul error: a-matrix dimensions must be 2"
assert b.ndim == 2, "matmul error: b-matrix dimensions must be 2"
assert a.shape[1] == b.shape[0], "matmul error: dimensions incompatable"
m, l = a.shape
l, n = b.shape
arr = np.zeros((m, n))
for k in range(l):
lhs = epsilon(sigma(a.copy()), n, offset=k)
rhs = omega(theta(b.copy()), m, offset=k)
addend = np.multiply(lhs, rhs)
arr+=addend
return arr
if __name__ == '__main__':
print("Running test cases...")
for i in tqdm(range(100)):
m = random.randint(2,20)
l = random.randint(2,20)
n = random.randint(2,20)
a = np.random.rand(m, l)
b = np.random.rand(l, n)
numpy_matmul = np.matmul(a.copy(), b.copy())
hegmm_matmul = hegmm(a.copy(), b.copy())
assert(np.allclose(numpy_matmul, hegmm_matmul))
print("PASSED")