"""akello - standalone Lugbara <-> Ateso direct translation (inference only).
pip install torch sentencepiece safetensors huggingface_hub
from akello import Translator
t = Translator("path/to/this/folder") # or Translator("amDANIEL2024/akello_base")
t.translate("", "lgg2teo")
t.translate([""], "teo2lgg")
Directions: "lgg2teo" (Lugbara -> Ateso) and "teo2lgg" (Ateso -> Lugbara).
"""
import json
import math
import os
import sentencepiece as spm
import torch
import torch.nn as nn
import torch.nn.functional as F
from safetensors.torch import load_file
PAD, UNK, BOS, EOS = 0, 1, 2, 3
def clean_text(s):
s = str(s).replace("’", "'").replace("‘", "'").replace("“", '"').replace("”", '"')
return " ".join(s.split())
def _sinusoid(n, d):
pos = torch.arange(n, dtype=torch.float32).unsqueeze(1)
div = torch.exp(torch.arange(0, d, 2, dtype=torch.float32) * (-math.log(10000.0) / d))
pe = torch.zeros(n, d)
pe[:, 0::2] = torch.sin(pos * div)
pe[:, 1::2] = torch.cos(pos * div)
return pe
class Seq2Seq(nn.Module):
"""Pre-LN encoder-decoder Transformer; one embedding matrix shared by encoder, decoder and output."""
def __init__(self, arch):
super().__init__()
d = arch["d_model"]
self.arch, self.scale = arch, d ** 0.5
self.emb = nn.Embedding(arch["vocab"], d, padding_idx=PAD)
self.register_buffer("pe", _sinusoid(arch["max_pos"], d), persistent=False)
self.drop = nn.Dropout(arch["dropout"])
kw = dict(d_model=d, nhead=arch["heads"], dim_feedforward=arch["ffn"], dropout=arch["dropout"],
activation="gelu", batch_first=True, norm_first=True)
self.encoder = nn.TransformerEncoder(nn.TransformerEncoderLayer(**kw), arch["enc_layers"],
norm=nn.LayerNorm(d), enable_nested_tensor=False)
self.decoder = nn.TransformerDecoder(nn.TransformerDecoderLayer(**kw), arch["dec_layers"],
norm=nn.LayerNorm(d))
def encode(self, src):
pad = src.eq(PAD)
x = self.drop(self.emb(src) * self.scale + self.pe[:src.size(1)])
return self.encoder(x, src_key_padding_mask=pad), pad
def decode(self, tgt, memory, mem_pad):
L = tgt.size(1)
x = self.drop(self.emb(tgt) * self.scale + self.pe[:L])
causal = torch.triu(torch.ones(L, L, dtype=torch.bool, device=tgt.device), diagonal=1)
h = self.decoder(x, memory, tgt_mask=causal, memory_key_padding_mask=mem_pad)
return F.linear(h, self.emb.weight)
class Translator:
def __init__(self, path="amDANIEL2024/akello_base", device=None, token=None):
if not os.path.isdir(path):
from huggingface_hub import snapshot_download
path = snapshot_download(path, token=token)
with open(os.path.join(path, "config.json"), encoding="utf-8") as f:
self.config = json.load(f)
self.arch = self.config["arch"]
self.V = self.arch["vocab"]
self.sp = spm.SentencePieceProcessor(model_file=os.path.join(path, "spm.model"))
assert self.sp.get_piece_size() == self.V, "tokenizer and model sizes differ"
a, b = self.arch["langs"]
# the tag names the TARGET language
self.tags = {f"{a}2{b}": self.sp.piece_to_id(f"<2{b}>"), f"{b}2{a}": self.sp.piece_to_id(f"<2{a}>")}
self.device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu"))
self.model = Seq2Seq(self.arch)
self.model.load_state_dict(load_file(os.path.join(path, "model.safetensors")))
self.model.to(self.device).eval()
self._amp = self.device.type == "cuda"
def _autocast(self):
return torch.autocast(device_type=self.device.type, dtype=torch.float16, enabled=self._amp)
@torch.no_grad()
def _beam_search(self, src, beam, max_len, length_penalty):
B, dev, V = src.size(0), src.device, self.V
with self._autocast():
memory, mpad = self.model.encode(src)
D = memory.size(-1)
memory = memory.unsqueeze(1).expand(B, beam, -1, -1).reshape(B * beam, -1, D)
mpad = mpad.unsqueeze(1).expand(B, beam, -1).reshape(B * beam, -1)
ys = torch.full((B * beam, 1), BOS, dtype=torch.long, device=dev)
scores = torch.zeros(B, beam, device=dev)
scores[:, 1:] = -1e9
fin = torch.zeros(B * beam, dtype=torch.bool, device=dev)
base = (torch.arange(B, device=dev) * beam).unsqueeze(1)
for _ in range(max_len):
with self._autocast():
logits = self.model.decode(ys, memory, mpad)[:, -1]
logp = F.log_softmax(logits.float(), dim=-1)
logp[:, PAD] = -1e9
logp[:, BOS] = -1e9
if fin.any():
logp[fin] = -1e9
logp[fin, PAD] = 0.0
cand = (scores.view(-1, 1) + logp).view(B, beam * V)
top, idx = cand.topk(beam, dim=1)
sel = (base + idx // V).view(-1)
word = (idx % V).view(-1, 1)
ys = torch.cat([ys[sel], word], dim=1)
fin = fin[sel] | (word.squeeze(1) == EOS)
scores = top
if fin.all():
break
body = ys[:, 1:]
is_eos = body.eq(EOS)
length = torch.where(is_eos.any(1), is_eos.float().argmax(1) + 1,
torch.full_like(fin, body.size(1), dtype=torch.long))
norm = scores.view(-1) / (((5.0 + length.float()) / 6.0) ** length_penalty)
best = norm.view(B, beam).argmax(1)
rows = torch.arange(B, device=dev) * beam + best
out = []
for r in rows.tolist():
seq = body[r].tolist()
if EOS in seq:
seq = seq[:seq.index(EOS)]
out.append([t for t in seq if t != PAD])
return out
@torch.no_grad()
def translate(self, texts, direction, beam=4, length_penalty=0.6, batch_size=24):
"""texts: a string or a list of strings. direction: "lgg2teo" or "teo2lgg". Returns a string or a list."""
if direction not in self.tags:
raise ValueError(f"direction must be one of {sorted(self.tags)}")
single = isinstance(texts, str)
texts = [texts] if single else list(texts)
max_pos = self.arch["max_pos"]
tag = self.tags[direction]
enc = self.sp.encode([clean_text(t) for t in texts])
ids = [[tag] + e[:max_pos - 3] + [EOS] for e in enc]
order = sorted(range(len(texts)), key=lambda i: len(ids[i]), reverse=True)
out = [None] * len(texts)
for b in range(0, len(order), batch_size):
idxs = order[b:b + batch_size]
L = max(len(ids[i]) for i in idxs)
src = torch.zeros((len(idxs), L), dtype=torch.long)
for r, i in enumerate(idxs):
src[r, :len(ids[i])] = torch.tensor(ids[i])
hyps = self._beam_search(src.to(self.device), beam, min(max_pos - 1, int(L * 1.6) + 10), length_penalty)
for i, h in zip(idxs, hyps):
out[i] = self.sp.decode(h)
return out[0] if single else out