HAKO upload: hako/nlp/nlg_head.py
Browse files- hako/nlp/nlg_head.py +91 -0
hako/nlp/nlg_head.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""NLG head: tiny causal transformer decoder over HAKO's byte-BPE tokens,
|
| 2 |
+
conditioned on the HAKO fused latent z_final (the "routed thinking state").
|
| 3 |
+
|
| 4 |
+
Theorem T-LM (well-posedness). The decoder is a 2-layer pre-norm transformer
|
| 5 |
+
with GELU and dropout; all parameters are Lipschitz on any bounded set, the
|
| 6 |
+
softmax output is a probability vector, and the cross-entropy loss over the
|
| 7 |
+
finite vocab V is bounded below by 0 and L-smooth in the logits; SGD with
|
| 8 |
+
clipped gradients and Robbins-Monro rates therefore has a.s. convergent loss
|
| 9 |
+
values (bounded-below supermartingale argument). Conditioning: the HAKO
|
| 10 |
+
latent enters as a prefix KV-free additive bias on the first position
|
| 11 |
+
(ContextFormer-style), keeping the causal mask exact for LM training.
|
| 12 |
+
QED.
|
| 13 |
+
"""
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
from typing import Optional
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
import torch.nn as nn
|
| 20 |
+
import torch.nn.functional as F
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class Block(nn.Module):
|
| 24 |
+
def __init__(self, d: int, heads: int, dropout: float) -> None:
|
| 25 |
+
super().__init__()
|
| 26 |
+
self.ln1 = nn.LayerNorm(d)
|
| 27 |
+
self.attn = nn.MultiheadAttention(d, heads, dropout=dropout,
|
| 28 |
+
batch_first=True)
|
| 29 |
+
self.ln2 = nn.LayerNorm(d)
|
| 30 |
+
self.mlp = nn.Sequential(nn.Linear(d, 2 * d), nn.GELU(),
|
| 31 |
+
nn.Dropout(dropout), nn.Linear(2 * d, d))
|
| 32 |
+
self.drop = nn.Dropout(dropout)
|
| 33 |
+
|
| 34 |
+
def forward(self, x: torch.Tensor, causal_mask: torch.Tensor) -> torch.Tensor:
|
| 35 |
+
h = self.ln1(x)
|
| 36 |
+
a, _ = self.attn(h, h, h, attn_mask=causal_mask, need_weights=False)
|
| 37 |
+
x = x + self.drop(a)
|
| 38 |
+
x = x + self.drop(self.mlp(self.ln2(x)))
|
| 39 |
+
return x
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class NLGHead(nn.Module):
|
| 43 |
+
def __init__(self, vocab: int, N_dim: int = 256, d: int = 256,
|
| 44 |
+
layers: int = 2, heads: int = 4, seq_len: int = 96,
|
| 45 |
+
dropout: float = 0.1, seed: int = 7) -> None:
|
| 46 |
+
super().__init__()
|
| 47 |
+
self.d = d
|
| 48 |
+
self.seq_len = seq_len
|
| 49 |
+
self.tok = nn.Embedding(vocab, d)
|
| 50 |
+
self.pos = nn.Embedding(seq_len, d)
|
| 51 |
+
self.blocks = nn.ModuleList([Block(d, heads, dropout)
|
| 52 |
+
for _ in range(layers)])
|
| 53 |
+
self.ln_f = nn.LayerNorm(d)
|
| 54 |
+
self.head = nn.Linear(d, vocab, bias=False)
|
| 55 |
+
self.cond = nn.Linear(N_dim, d) # HAKO latent -> context bias
|
| 56 |
+
self.drop = nn.Dropout(dropout)
|
| 57 |
+
|
| 58 |
+
def forward(self, ids: torch.Tensor,
|
| 59 |
+
z_cond: Optional[torch.Tensor] = None) -> torch.Tensor:
|
| 60 |
+
B, L = ids.shape
|
| 61 |
+
mask = torch.triu(torch.full((L, L), float("-inf")), diagonal=1)
|
| 62 |
+
x = self.drop(self.tok(ids) + self.pos(torch.arange(L, device=ids.device)))
|
| 63 |
+
if z_cond is not None:
|
| 64 |
+
x = x + self.cond(z_cond).view(B, 1, self.d)
|
| 65 |
+
for blk in self.blocks:
|
| 66 |
+
x = blk(x, mask)
|
| 67 |
+
return self.head(self.ln_f(x)) # (B, L, V) logits
|
| 68 |
+
|
| 69 |
+
def loss(self, ids: torch.Tensor,
|
| 70 |
+
z_cond: Optional[torch.Tensor] = None) -> torch.Tensor:
|
| 71 |
+
logits = self.forward(ids[:, :-1], z_cond)
|
| 72 |
+
return F.cross_entropy(logits.reshape(-1, logits.size(-1)),
|
| 73 |
+
ids[:, 1:].reshape(-1), ignore_index=-100)
|
| 74 |
+
|
| 75 |
+
@torch.no_grad()
|
| 76 |
+
def generate(self, prompt_ids: list, z_cond: Optional[torch.Tensor],
|
| 77 |
+
max_new: int = 40, temperature: float = 0.9,
|
| 78 |
+
top_k: int = 50) -> list:
|
| 79 |
+
ids = torch.tensor([prompt_ids[-self.seq_len:]], dtype=torch.long)
|
| 80 |
+
for _ in range(max_new):
|
| 81 |
+
logits = self.forward(ids[:, -self.seq_len:], z_cond)[0, -1]
|
| 82 |
+
logits = logits / max(temperature, 1e-3)
|
| 83 |
+
if top_k > 0:
|
| 84 |
+
v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
|
| 85 |
+
logits[logits < v[-1]] = float("-inf")
|
| 86 |
+
probs = torch.softmax(logits, dim=-1)
|
| 87 |
+
nxt = int(torch.multinomial(probs, 1))
|
| 88 |
+
ids = torch.cat([ids, torch.tensor([[nxt]], dtype=torch.long)], 1)
|
| 89 |
+
if nxt == 0:
|
| 90 |
+
break
|
| 91 |
+
return ids[0].tolist()
|