Matrix Multiplication Checker

1. Code

{checker.py 1}
import array
import numpy as np
import struct
import sys

def check_mm():
    correct = True
    with open('.mm.debug', 'rb') as f:
        head = f.read(struct.calcsize('3i'))
        n, k, m = struct.unpack('3i', head)
        a, b, c_rr, c_rc, c_cr, c_cc = [array.array('f') for x in range(6)]
        a.fromfile(f, n*k)
        b.fromfile(f, k*m)
        a_r = np.reshape(a, (n, k), order='C')
        b_r = np.reshape(b, (k, m), order='C')
        a_c = np.reshape(a, (n, k), order='F')
        b_c = np.reshape(b, (k, m), order='F')
        c_rr.fromfile(f, n*m)
        c_mm = np.reshape(c_rr, (n, m), order='C')
        c_np = a_r @ b_r
        if (c_mm != c_np).any():
            print('mm rr failed')
            correct = False
        else:
            print('mm rr passed')
        c_rc.fromfile(f, n*m)
        c_mm = np.reshape(c_rc, (n, m), order='C')
        c_np = a_r @ b_c
        if (c_mm != c_np).any():
            print('mm rc failed')
            correct = False
        else:
            print('mm rc passed')
        c_cr.fromfile(f, n*m)
        c_mm = np.reshape(c_cr, (n, m), order='C')
        c_np = a_c @ b_r
        if (c_mm != c_np).any():
            print('mm cr failed')
            correct = False
        else:
            print('mm cr passed')
        c_cc.fromfile(f, n*m)
        c_mm = np.reshape(c_cc, (n, m), order='C')
        c_np = a_c @ b_c
        if (c_mm != c_np).any():
            print('mm cc failed')
            correct = False
        else:
            print('mm cc passed')
    return correct

def check_matvec():
    print('matvec checking not yet implemented')
    return False

def show_usage():
    print('Usage: {} [mm | matvec]*'.format(sys.argv[0]))
    raise SystemExit(4)

def main():
    status = 0
    if sys.argv == 1:
        show_usage()
    for arg in sys.argv[1:]:
        if arg == 'mm':
            if check_mm():
                print('mm output correct')
            else:
                print('mm output incorrect')
                status |= 1
        elif arg == 'matvec':
            if check_matvec():
                print('matvec output correct')
            else:
                print('matvec output incorrect')
                status |= 2
        else:
            show_usage()
    raise SystemExit(status)

if __name__ == '__main__':
    main()

Previous ChapterNext Chapter