-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathneuron_test.py
More file actions
71 lines (53 loc) · 2.16 KB
/
neuron_test.py
File metadata and controls
71 lines (53 loc) · 2.16 KB
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
"""
Create tests for the neuron
Usage:
python3 neuron_test.py <input_number> <bit_width> <n_tests> <precision> <samples>
Output format:
The file has the following format (example with 4 inputs, i_n n=1,2,3,4):
<i_1> <i_2> <i_3> <i_4> <w_1> <w_2> <w_3> <w_4> <b> <o>
where i stands for input, w for weight, b for bias and o for output
"""
import argparse
import random
from decimal import Context, Decimal, setcontext
from math import ceil, log2
import numpy as np
from test_module import write_dat # noqa: E402
random.seed(7357)
parser = argparse.ArgumentParser(description="Testing script for neuron")
parser.add_argument("-inp", help="Number of inputs", type=int)
parser.add_argument("-bw", help="Bit width", type=int)
parser.add_argument("-prec", help="Precision", type=int)
parser.add_argument("-tests", help="Number of tests", type=int)
args = parser.parse_args()
RANGE = int(2 ** (args.bw / 2) - 1)
DELAY = 3 + ceil(log2(args.inp))
# Context for Decimal
ctx = Context(prec=args.prec)
setcontext(ctx)
# Test inputs without zero padding
test_inputs = [random.choices(range(-RANGE, RANGE), k=args.inp) for _ in range(args.tests)]
weights = [random.choices(range(-RANGE, RANGE), k=args.inp) for _ in range(args.tests)]
biases = [random.choices(range(-RANGE, RANGE), k=1) for _ in range(args.tests)]
# Create numpy arrays for the calculations
test_inputs = np.array(test_inputs, dtype=Decimal)
weights = np.array(weights, dtype=Decimal)
biases = np.array(biases, dtype=Decimal)
results = np.zeros((args.tests, 1))
# Calculate results
results[:, 0] = np.right_shift(
np.sum(test_inputs[:, 0 : args.inp] * weights, axis=1) + biases[:, 0], args.prec
)
# Convert arrays back to lists
test_inputs = test_inputs.tolist()
weights = weights.tolist()
biases = biases.tolist()
results = results.tolist()
# Zeros after the computation for the test inputs, weights and biases
for _ in range(DELAY):
test_inputs.append([0 for _ in range(args.inp)])
weights.append([0 for _ in range(args.inp)])
biases.append([0 for _ in range(1)])
# Results with zero padding
results = np.zeros((DELAY, 1)).tolist() + results
write_dat("neuron.dat", args.tests + DELAY, test_inputs, weights, biases, results)