# Step 6: quantization. Store each weight as a whole number from -127 to 127
# (8 bits) instead of a 32-bit decimal, so the model is about 4 times smaller.
# Then write model.h, the file the C program in step 7 is built with.
import math
from tiny_nn import load_windows, split, forward, best, load


def to_int(v):
    return math.floor(v + 0.5)  # round to the nearest whole number


def biggest(rows):
    top = 0.0
    for row in rows:
        for v in row:
            if abs(v) > top:
                top = abs(v)
    return top


xs, ys = load_windows("windows.csv")
train_x, train_y, test_x, test_y = split(xs, ys)
net = load("pruned.txt")
w1, b1 = net[0]
w2, b2 = net[1]

# A scale says what one step of the whole numbers is worth.
IN_SCALE = 1 / 127          # inputs are between -1 and 1
s1 = biggest(w1) / 127
top_hidden = 0.0            # the biggest hidden value seen in training
for x in train_x:
    for h in forward(net, x)[0]:
        if h > top_hidden:
            top_hidden = h
sh = top_hidden / 127
s2 = biggest(w2) / 127

q_w1 = [[to_int(v / s1) for v in row] for row in w1]
q_b1 = [to_int(v / (s1 * IN_SCALE)) for v in b1]
m1 = to_int(s1 * IN_SCALE / sh * 65536)  # hidden = (sum * m1) >> 16
q_w2 = [[to_int(v / s2) for v in row] for row in w2]
q_b2 = [to_int(v / (s2 * sh)) for v in b2]


def run_int8(x):
    qx = [max(-127, min(127, to_int(v * 127))) for v in x]
    hidden = []
    for j in range(len(q_w1)):
        acc = q_b1[j]
        for i in range(len(qx)):
            acc += q_w1[j][i] * qx[i]
        if acc < 0:
            acc = 0
        hidden.append(min(127, (acc * m1) >> 16))
    out = []
    for k in range(len(q_w2)):
        acc = q_b2[k]
        for j in range(len(hidden)):
            acc += q_w2[k][j] * hidden[j]
        out.append(acc)
    return out


print("First row of weights as decimals:", " ".join(f"{v:.4f}" for v in w1[0]))
print("The same row as 8-bit numbers:   ", " ".join(str(v) for v in q_w1[0]))

right_float = 0
right_int = 0
for x, y in zip(test_x, test_y):
    if best(forward(net, x)[1]) == y:
        right_float += 1
    if best(run_int8(x)) == y:
        right_int += 1
print(f"Test windows right with decimals: {right_float} of {len(test_y)}. With 8-bit numbers: {right_int} of {len(test_y)}")

n_weights = len(w1) * len(w1[0]) + len(w2) * len(w2[0])
n_bias = len(b1) + len(b2)
print(f"As 32-bit decimals: {4 * (n_weights + n_bias)} bytes. As 8-bit weights: {n_weights + 4 * n_bias + 8} bytes")


def c_rows(rows):
    return ",\n".join("  { " + ", ".join(str(v) for v in row) + " }" for row in rows)


with open("model.h", "w") as f:
    f.write("/* Made by quantize.py from pruned.txt. Run it again instead of editing. */\n")
    f.write(f"#define N_IN {len(w1[0])}\n#define N_HID {len(w1)}\n#define N_OUT {len(w2)}\n")
    f.write("static const signed char W1[N_HID][N_IN] = {\n" + c_rows(q_w1) + "\n};\n")
    f.write("static const int B1[N_HID] = { " + ", ".join(str(v) for v in q_b1) + " };\n")
    f.write(f"static const long long M1 = {m1}; /* hidden = (sum * M1) >> 16 */\n")
    f.write("static const signed char W2[N_OUT][N_HID] = {\n" + c_rows(q_w2) + "\n};\n")
    f.write("static const int B2[N_OUT] = { " + ", ".join(str(v) for v in q_b2) + " };\n")
print("Wrote model.h for the C program")
