"""Original teaching experiment, CPU; no pretrained weights or network needed."""
import math
import platform
import torch

# A common vocabulary, with absent transitions carrying exactly zero mass.
# Fixed-depth experiment: no EOS until both decisions are made.
TREE = {(): {'A': .60, 'B': .35, 'C': .05},
        ('A',): {'X': .40, 'Y': .35, 'Z': .25},
        ('B',): {'W': .85, 'V': .15},
        ('C',): {'W': 1.0}}


def fixed_beam(tree, width, steps):
    """One active pool; deterministic lexical tie-break, scores in log space."""
    assert width >= 1 and steps >= 1
    pool = [((), 0.0)]
    for _ in range(steps):
        extensions = [(prefix + (token,), score + math.log(p))
                      for prefix, score in pool
                      for token, p in tree[prefix].items() if p > 0]
        pool = sorted(extensions, key=lambda x: (-x[1], x[0]))[:width]
    return pool


def score(s, length, length_penalty):
    assert length >= 1
    return s / length**length_penalty


def gnmt(s, length, alpha):
    return s / (((5 + length) / 6)**alpha)


def bound(s, length, maximum, length_penalty):
    """Upper bound for nonpositive additive increments and s <= 0."""
    assert s <= 0 and 1 <= length <= maximum
    return score(s, maximum if length_penalty > 0 else length, length_penalty)


def eos_beam(tree, width, max_new, length_penalty=0.0, eos='EOS'):
    """Reference teaching variant, not HF: all valid finished candidates eligible.
    At max_new, truncated prefixes are terminal but explicitly marked non-EOS.
    Uses exact pruning bound on surviving prefixes, not global optimality.
    """
    assert width >= 1 and max_new >= 1
    active = [((), 0.0)]
    done = []
    for t in range(1, max_new + 1):
        candidates = []
        for prefix, s in active:
            for token, p in tree[prefix].items():
                if p <= 0:
                    continue
                new, total = prefix + (token,), s + math.log(p)
                if token == eos or t == max_new:
                    done.append((new, total, token == eos))
                else:
                    candidates.append((new, total))
        done = sorted(done, key=lambda x: (-score(x[1], len(x[0]), length_penalty), x[0]))[:width]
        active = sorted(candidates, key=lambda x: (-x[1], x[0]))[:width]
        if not active:
            break
        if len(done) == width and max(bound(s,t,max_new,length_penalty) for _,s in active) < score(done[-1][1],len(done[-1][0]),length_penalty):
            break
    return done


def main():
    print('Python', platform.python_version(), 'PyTorch', torch.__version__, 'device=cpu')
    for dist in TREE.values():
        assert math.isclose(sum(dist.values()), 1)
    g, b = fixed_beam(TREE,1,2)[0], fixed_beam(TREE,2,2)[0]
    brute = max((p*q, (a,x)) for a,p in TREE[()].items() for x,q in TREE[(a,)].items())
    print('greedy',g[0],f'p={math.exp(g[1]):.6f} logp={g[1]:.6f}')
    print('beam2 ',b[0],f'p={math.exp(b[1]):.6f} logp={b[1]:.6f}')
    assert g[0] == ('A','X') and b[0] == ('B','W') and brute[1] == b[0]
    # An intentionally pruned global optimum. Same support convention.
    other={():{'A':.45,'B':.35,'C':.20}, ('A',):{'X':.34,'Y':.33,'Z':.33},
           ('B',):{'X':.34,'Y':.33,'Z':.33}, ('C',):{'X':1.0}}
    assert fixed_beam(other,2,2)[0][0] == ('A','X')
    assert fixed_beam(other,3,2)[0][0] == ('C','X')
    print('pruning counterexample: beam2=.153; beam3=.2')
    for a in (0,1,-1):
        print(f'HF lambda={a}: short={score(-5,5,a):.6f} long={score(-9,12,a):.6f}')
    print('GNMT alpha=.6:', f'{gnmt(-5,5,.6):.6f}', f'{gnmt(-9,12,.6):.6f}')
    assert score(-5,5,1)<score(-9,12,1) and gnmt(-5,5,.6)>gnmt(-9,12,.6)
    s,t,m,a=-4.,4,10,1.
    print('stop example:',score(s,t,a),bound(s,t,m,a),'worst=-.8 future=-.6')
    assert score(s,t,a)<-.8<score(-6,10,a)<bound(s,t,m,a)
    for length_penalty in (-1,0,1):
        for end in range(t,m+1):
            for extra in (0,-.1,-5):
                assert score(s+extra,end,length_penalty)<=bound(s,t,m,length_penalty)+1e-12
    # EOS and length-limit demo.
    e={():{'EOS':.4,'A':.6}, ('A',):{'EOS':.5,'B':.5}}
    result=eos_beam(e,2,2,0)
    assert result[0][0]==('EOS',) and result[0][2]
    truncated=eos_beam(e,2,2,1)
    assert truncated[0][0]==('A','B') and not truncated[0][2]
    print('EOS pool',result,'length cap',truncated)
    # vectorized step [batch, beam, vocab]; two batches, no cross-batch mixing.
    probs=torch.tensor([[[.4,.35,.25],[.85,.15,0]],[[.2,.3,.5],[.7,.2,.1]]],dtype=torch.float64)
    parents=torch.tensor([[.6,.35],[.8,.2]],dtype=torch.float64).log()
    # rows of zeros become -inf, never eligible in the selected examples.
    scores=probs.log()+parents[:,:,None]
    val, idx=scores.flatten(1).topk(2,dim=1)
    par, token=idx//3,idx%3
    offsets=torch.arange(2)[:,None]*2
    cache=torch.tensor([[10,11],[20,21],[30,31],[40,41]])
    reordered=cache.index_select(0,(par+offsets).flatten())
    assert par.tolist()==[[1,0],[0,0]] and token.tolist()==[[0,0],[2,1]]
    assert reordered.tolist()==[[20,21],[10,11],[30,31],[30,31]]
    assert torch.allclose(val.exp(),torch.tensor([[.2975,.24],[.4,.24]],dtype=torch.float64))
    print('flat',idx.tolist(),'parents',par.tolist(),'tokens',token.tolist(),'cache',reordered.tolist())
    # A bigram mask sees token IDs; previously seen prefix->suffix pairs.
    ids=[1,2,3,1]; banned={b for a,b in zip(ids,ids[1:]) if a==ids[-1]}
    assert banned=={2}
    print('bigram banned token ids:',sorted(banned))
    # Numerical stable log-softmax: raw logits across histories cannot be added.
    logits=torch.tensor([[100.,101.],[0.,1.]],dtype=torch.float64)
    logp=torch.log_softmax(logits,dim=-1)
    assert torch.allclose(logp[0],logp[1]) and torch.allclose(logp.exp().sum(-1),torch.ones(2,dtype=torch.float64))
    print('stable log_softmax',logp.tolist())
    # 32 layers, 8 KV heads, 128 head dim, 4096 tokens, 2 bytes, K=4.
    one=2*32*8*128*4096*2
    assert one==536870912 and 4*one==2147483648
    print('KV cache ideal bytes',one,4*one)
    print('ALL ASSERTIONS PASSED')

if __name__=='__main__':
    main()
