"""PTB Zaremba small configuration in PyTorch, with equal-budget GRU comparison."""
import math, json, hashlib, time
from pathlib import Path
import torch
from torch import nn

torch.set_num_threads(2)
root = Path('ptb')
hashes = {'train':'fcea919f6cf83f35d4d00c6cbf08040d13d4155226340912e2fef9c9c4102cbf', 'valid':'c9fe6985fe0d4ccb578183407d7668fc6066c20700cb4cf87d8ff1cc34df1bf2', 'test':'dd65dff31e70846b2a6030a87482edcd5d199130cdcfa1f3dccbb033728deee0'}
for split, digest in hashes.items():
    assert hashlib.sha256((root / f'{split}.txt').read_bytes()).hexdigest() == digest
def tokens(split):
    return (root / f'{split}.txt').read_text(encoding='utf-8').replace('\n', ' <eos> ').split()
train_words = tokens('train')
vocab = {w:i for i,w in enumerate(sorted(set(train_words)))}
assert len(vocab) == 10000
def encode(words):
    return torch.tensor([vocab.get(w, vocab['<unk>']) for w in words], dtype=torch.long, device='cuda')
def batchify(ids):
    return ids[:ids.numel()//20*20].view(20,-1).T.contiguous()
train, valid, test = (batchify(encode(tokens(split))) for split in ('train','valid','test'))
class Model(nn.Module):
    def __init__(self, kind):
        super().__init__()
        self.emb = nn.Embedding(len(vocab), 200)
        self.rnn = (nn.LSTM if kind == 'LSTM' else nn.GRU)(200, 200, 2)
        self.head = nn.Linear(200, len(vocab))
        for p in self.parameters(): nn.init.uniform_(p, -.1, .1)
    def forward(self, x, state):
        h, state = self.rnn(self.emb(x), state)
        return self.head(h), state
def epoch(model, data, opt=None):
    model.train(opt is not None)
    state = None; total = torch.zeros((),device=data.device,dtype=torch.float64); count = 0
    for start in range(0, data.size(0)-1, 20):
        length = min(20, data.size(0)-1-start)
        x = data[start:start+length]; y = data[start+1:start+1+length]
        if state is not None: state = tuple(z.detach() for z in state) if isinstance(state, tuple) else state.detach()
        with torch.set_grad_enabled(opt is not None):
            logits, state = model(x, state)
            loss = nn.functional.cross_entropy(logits.reshape(-1,len(vocab)), y.reshape(-1))
            if opt is not None:
                # Torch7 sums per-time-step batch-mean losses before clipping.
                opt.zero_grad(set_to_none=True); (loss * length).backward()
                nn.utils.clip_grad_norm_(model.parameters(), 5); opt.step()
        total += loss.detach().to(torch.float64)*y.numel(); count += y.numel()
    return math.exp(total.item()/count)

out=Path('ptb-full-results.json')
records=json.loads(out.read_text(encoding='utf-8')) if out.exists() else []
for kind in ('LSTM','GRU'):
    for rate in (1., .5):
        if any(r['kind']==kind and r['rate']==rate for r in records): continue
        torch.manual_seed(31); torch.cuda.manual_seed_all(31)
        model=Model(kind).cuda(); opt=torch.optim.SGD(model.parameters(),lr=rate)
        start=time.time(); history=[]
        checkpoint=out.with_name(f'ptb-{kind}-{rate}-progress.pt')
        if checkpoint.exists():
            saved=torch.load(checkpoint,weights_only=True,map_location='cpu')
            model.load_state_dict(saved['model']); opt.load_state_dict(saved['optimizer']); history=saved['history']
        for ep in range(len(history)+1,14):
            # Original script divides the learning rate after epoch 5.
            opt.param_groups[0]['lr']=rate / (2 ** max(0,ep-5))
            tr=epoch(model,train,opt); va=epoch(model,valid)
            history.append({'epoch':ep,'lr':opt.param_groups[0]['lr'],'train':tr,'valid':va})
            temp=checkpoint.with_suffix('.tmp')
            torch.save({'model':model.state_dict(),'optimizer':opt.state_dict(),'history':history},temp)
            temp.replace(checkpoint)
            print(kind,rate,ep,'train',round(tr,3),'valid',round(va,3),flush=True)
        state_path=out.with_name(f'ptb-{kind}-{rate}.pt')
        torch.save(model.state_dict(),state_path)
        records.append({'kind':kind,'rate':rate,'history':history,'state':str(state_path),'seconds':time.time()-start})
        out.write_text(json.dumps(records,indent=2),encoding='utf-8')
for kind in ('LSTM','GRU'):
    group=[r for r in records if r['kind']==kind]
    best=min(group,key=lambda r:r['history'][-1]['valid'])
    selected=[r for r in group if r['rate']==1.]
    if best not in selected: selected.append(best)
    for record in selected:
        model=Model(kind).cuda(); model.load_state_dict(torch.load(record['state'],weights_only=True))
        record['test']=epoch(model,test)
        print('TEST',kind,record['rate'],record['test'],flush=True)
out.write_text(json.dumps(records,indent=2),encoding='utf-8')
