File size: 4,113 Bytes
6bd4371 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | '''
Batched inference for a MacronizerModel. Same behaviour as the original
grc-macronizer/macron_model/predict.py (inputs chunked at
max_position_embeddings, marks only emitted at genuine dichrona), but lines
are run in padded batches so that scoring Norma during training is cheap.
from predict import MacronPredictor
p = MacronPredictor("Ericu950/oga-macronizer-char") # or a local checkpoint dir
p.macronize("ανθρωπος ανηρ")
'''
import argparse
import json
import os
import sys
import torch
from huggingface_hub import hf_hub_download
from model import MacronizerModel
from tokenizer import DiacriticVocab, decode, encode_plain, MACRON_SHORT, MACRON_LONG
PAD_ID = 0
def load_vocab(model_dir):
if os.path.isdir(model_dir):
path = os.path.join(model_dir, "diacritic_vocab.json")
if not os.path.exists(path):
path = os.path.join(os.path.dirname(os.path.normpath(model_dir)), "diacritic_vocab.json")
else:
path = hf_hub_download(repo_id=model_dir, filename="diacritic_vocab.json")
with open(path, encoding="utf-8") as f:
return DiacriticVocab.from_dict(json.load(f))
class MacronPredictor:
def __init__(self, model, vocab=None, device=None):
self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
if isinstance(model, MacronizerModel):
self.model, self.vocab = model, vocab
else:
self.model = MacronizerModel.from_pretrained(model).to(self.device)
self.vocab = load_vocab(model)
self.max_len = self.model.config.max_position_embeddings
@torch.no_grad()
def macronize_lines(self, lines, batch_size=256):
was_training = self.model.training
self.model.eval()
encs = [encode_plain(l, self.vocab, fit=False) if l.strip() else None for l in lines]
chunks = [] # (line index, start, plane1, plane2)
for i, e in enumerate(encs):
if e is None or not e["plane1"]:
continue
for s in range(0, len(e["plane1"]), self.max_len):
chunks.append((i, s, e["plane1"][s:s + self.max_len], e["plane2"][s:s + self.max_len]))
preds = {i: [0] * len(e["plane1"]) for i, e in enumerate(encs) if e is not None}
for b in range(0, len(chunks), batch_size):
batch = chunks[b:b + batch_size]
L = max(len(c[2]) for c in batch)
p1 = torch.full((len(batch), L), PAD_ID, dtype=torch.long)
p2 = torch.full((len(batch), L), PAD_ID, dtype=torch.long)
am = torch.zeros((len(batch), L), dtype=torch.long)
for k, (_, _, a, c) in enumerate(batch):
p1[k, :len(a)] = torch.tensor(a)
p2[k, :len(c)] = torch.tensor(c)
am[k, :len(a)] = 1
# a single unpadded chunk is run without a mask, exactly as the original predict.py
mask = None if len(batch) == 1 else am.to(self.device)
logits = self.model(plane1_ids=p1.to(self.device), plane2_ids=p2.to(self.device),
attention_mask=mask).logits
arg = logits.argmax(-1).cpu().tolist()
for k, (i, s, a, _) in enumerate(batch):
preds[i][s:s + len(a)] = arg[k][:len(a)]
if was_training:
self.model.train()
out = []
for i, (line, e) in enumerate(zip(lines, encs)):
if e is None or not e["plane1"]:
out.append(line)
continue
labels = [lab if elig and lab in (MACRON_SHORT, MACRON_LONG) else 0
for lab, elig in zip(preds[i], e["dichrona_mask"])]
out.append(decode(e["chars"], labels))
return out
def macronize(self, text):
return "\n".join(self.macronize_lines(text.split("\n")))
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--model_dir", required=True)
ap.add_argument("--text")
a = ap.parse_args()
p = MacronPredictor(a.model_dir)
print(p.macronize(a.text if a.text else sys.stdin.read()))
|