Download predict.py from Urdatorn/Makron-code: direct link, hf CLI and curl.
- Browser
- Download file 4.11 kB
-
https://huggingface.co/Urdatorn/Makron-code/resolve/main/predict.py
- Command line
-
hf download hf://Urdatorn/Makron-code/predict.py
-
curl -L -o predict.py https://huggingface.co/Urdatorn/Makron-code/resolve/main/predict.py
4.11 kB
| ''' | |
| 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 | |
| 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())) | |