"""K01.01 V1.0: deterministic teaching arithmetic, not a real tokenizer or Transformer."""
import math
import platform
from fractions import Fraction as F

V, D, B, n = 5, 2, 1, 6
vocab = {'BOS':0, '我':1, '喜欢':2, ' AI':3, 'EOS':4}
text = '我喜欢 AI'
parts = ['我', '喜欢', ' AI']
assert ''.join(parts) == text
ids = [vocab['BOS']] + [vocab[x] for x in parts] + [vocab['EOS']] * 2
m = [1,1,1,1,1,0]
E = [(0,0),(1,0),(0,1),(-1,1),(1,-1)]
# W rows in units of ln(2); actual W = these rows * ln(2).
W_units = [(0,0),(0,0),(1,0),(0,1),(0,2)]
assert len(E) == len(W_units) == V and all(len(r)==D for r in E+W_units)
assert B == 1 and len(ids) == n and all(0<=i<V for i in ids)
assert ids == [0,1,2,3,4,4] and sum(m) == 5
H0 = [E[i] for i in ids]
assert H0[4] == H0[5] == (1,-1)
# A causal prefix sum over valid keys; PAD query uses arbitrary zero placeholder.
H = [tuple(sum(H0[j][d] for j in range(t+1) if m[j]) for d in range(D))
     if m[t] else (0,0) for t in range(n)]
assert H == [(0,0),(1,0),(1,1),(0,2),(1,1),(0,0)]
U = [[sum(h[d]*w[d] for d in range(D)) for w in W_units] for h in H]
L = [[u*math.log(2) for u in row] for row in U]
weights = [[F(2)**u for u in row] for row in U]
P = [[w/sum(row) for w in row] for row in weights]
assert all(sum(row)==1 for row in P)
assert weights[:5] == [[1,1,1,1,1],[1,1,2,1,1],[1,1,2,2,4],[1,1,1,4,16],[1,1,2,2,4]]
for lr, pr in zip(L,P):
    c=max(lr); e=[math.exp(x-c) for x in lr]
    assert all(math.isclose(a/sum(e),float(b),rel_tol=1e-12) for a,b in zip(e,pr))
assert U[2]==[0,0,1,1,2] and U[3]==[0,0,0,2,4]
assert max(range(V),key=lambda k:L[2][k])==4 and P[2][3]==F(1,5)
I=-100

def evaluate(name, labels, expected_y, expected_targets, expected_path):
    y=labels[1:]+[I]
    assert y==expected_y
    valid=[t for t,k in enumerate(y) if k!=I]
    assert valid==expected_targets and all(m[t] and t+1<n and m[t+1] for t in valid)
    assert all(0<=y[t]<V for t in valid)
    assert valid
    path=math.prod(P[t][y[t]] for t in valid)
    assert path==expected_path
    nll=-sum(math.log(float(P[t][y[t]])) for t in valid)
    mean=nll/len(valid)
    stable=sum(math.log(sum(math.exp(x-max(L[t])) for x in L[t]))-(L[t][y[t]]-max(L[t])) for t in valid)
    assert math.isclose(nll,stable,abs_tol=1e-12)
    ppl=math.exp(mean)
    print(f'{name}: positions={valid}, y={y}, N_eff={len(valid)}, path={path}, NLL={nll:.9f}, mean={mean:.9f}, PPL={ppl:.9f}')
    return mean,ppl

print('Python',platform.python_version(),platform.system())
print('T:',ids,'valid:',m,'H0:',H0,'H:',H,'logits ln2 units:',U)
mean,ppl=evaluate('full next token',[0,1,2,3,4,I],[1,2,3,4,I,I],[0,1,2,3],F(16,1725))
assert abs(mean-1.1700984018064198)<1e-12 and abs(ppl-3.222309704024055)<1e-12
mean,ppl=evaluate('answer only',[I,I,I,3,4,I],[I,I,3,4,I,I],[2,3],F(16,115))
assert abs(mean-0.9861717030617344)<1e-12 and abs(ppl-2.680951323690902)<1e-12
mean,ppl=evaluate('EOS only',[I,I,I,I,4,I],[I,I,I,4,I,I],[3],F(16,23))
assert abs(mean-math.log(23/16))<1e-12 and abs(ppl-23/16)<1e-12
mean,ppl=evaluate('incorrect EOS ID-wide ignore',[I,I,I,3,I,I],[I,I,3,I,I,I],[2],F(1,5))
assert abs(ppl-5)<1e-12
# Future substitution cannot affect query 2 in the toy prefix function.
changed=ids.copy(); changed[3]=1
assert tuple(sum(E[changed[j]][d] for j in range(3) if m[j]) for d in range(D)) == H[2]
print('ALL ASSERTIONS PASS (teaching arithmetic only)')
