zewi_base: pretrained Runyankole<->Acholi base (weights, tokenizer, code, model card)
Browse files- README.md +126 -0
- config.json +27 -0
- model.safetensors +3 -0
- spm.model +3 -0
- zewi.py +160 -0
README.md
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
language:
|
| 3 |
+
- nyn
|
| 4 |
+
- ach
|
| 5 |
+
library_name: pytorch
|
| 6 |
+
pipeline_tag: translation
|
| 7 |
+
tags:
|
| 8 |
+
- translation
|
| 9 |
+
- runyankole
|
| 10 |
+
- acholi
|
| 11 |
+
- seq2seq
|
| 12 |
+
- transformer
|
| 13 |
+
- synthetic-data
|
| 14 |
+
datasets:
|
| 15 |
+
- amDANIEL2024/tulati
|
| 16 |
+
license: mit
|
| 17 |
+
---
|
| 18 |
+
|
| 19 |
+
# zewi_base: direct Runyankole ⇄ Acholi translation (pretrained base)
|
| 20 |
+
|
| 21 |
+
`zewi_base` is a 89M-parameter encoder-decoder Transformer that translates **Runyankole → Acholi** and
|
| 22 |
+
**Acholi → Runyankole** directly, with one model and **no English on either side**. The direction is set by a prefix token on the
|
| 23 |
+
source (`<2ach>` / `<2nyn>`; the tag names the target language).
|
| 24 |
+
|
| 25 |
+
> **This is a pretrained base, not a finished translator.** It was trained only on *machine-translated* pairs: both the
|
| 26 |
+
> Runyankole side and the Acholi side of every training pair are output of one NLLB-based model (see *Training*). It has not been
|
| 27 |
+
> fine-tuned on human-translated data. Full test-set scores have **not been run yet** (see *Evaluation*).
|
| 28 |
+
|
| 29 |
+
## Quick start
|
| 30 |
+
|
| 31 |
+
```bash
|
| 32 |
+
pip install torch sentencepiece safetensors huggingface_hub
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
```python
|
| 36 |
+
import sys
|
| 37 |
+
from huggingface_hub import snapshot_download
|
| 38 |
+
|
| 39 |
+
folder = snapshot_download("amDANIEL2024/zewi_base") # add token="hf_..." if the repo is still private
|
| 40 |
+
sys.path.insert(0, folder)
|
| 41 |
+
from zewi import Translator
|
| 42 |
+
|
| 43 |
+
t = Translator(folder) # uses the GPU if there is one
|
| 44 |
+
acholi = t.translate("Okwombeka orugo kukatandika omu kwezi kw'okubanza 2000.", "nyn2ach")
|
| 45 |
+
print(acholi)
|
| 46 |
+
print(t.translate(acholi, "ach2nyn")) # back again
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
Directions are `"nyn2ach"` and `"ach2nyn"`. `translate` takes a string or a list and accepts `beam` (default 4).
|
| 50 |
+
This is a custom PyTorch model, not a `transformers` model, so `AutoModel` will not load it.
|
| 51 |
+
|
| 52 |
+
## Example outputs
|
| 53 |
+
|
| 54 |
+
Not yet added. Examples will be taken unedited from the SALT test set, mistakes included, once the evaluation has been run.
|
| 55 |
+
|
| 56 |
+
## Model
|
| 57 |
+
|
| 58 |
+
| | |
|
| 59 |
+
|---|---|
|
| 60 |
+
| Architecture | pre-LN Transformer encoder-decoder, 6 + 6 layers, d_model 640, 8 heads, FFN 2560, GELU |
|
| 61 |
+
| Parameters | 89M (input embedding, decoder embedding and output projection are tied) |
|
| 62 |
+
| Tokenizer | shared SentencePiece unigram, 32,000 pieces, case preserved, digits split (`spm.model`); trained on Runyankole and Acholi text only |
|
| 63 |
+
| Context | 256 positions (sinusoidal); training pairs were limited to 128 pieces per side |
|
| 64 |
+
| Weights | `model.safetensors` (float32) |
|
| 65 |
+
|
| 66 |
+
## Training
|
| 67 |
+
|
| 68 |
+
- **Data:** the Runyankole–Acholi pairs of [tulati](https://huggingface.co/datasets/amDANIEL2024/tulati), used in both
|
| 69 |
+
directions. In tulati every non-English column is a **machine translation** of one English column, made by
|
| 70 |
+
[Sunbird/translate-nllb-1.3b-salt](https://huggingface.co/Sunbird/translate-nllb-1.3b-salt); no human-written
|
| 71 |
+
Runyankole or Acholi is in it. The English source column was not used for this model. This card does not report how good that translator is for Runyankole or Acholi.
|
| 72 |
+
- **Filtering (counts from this run):** of 1,534,699 tulati rows, 87,670 were dropped because they were flagged empty, degenerate, looks-like-English or length-outlier in *either* language (flagged in Runyankole: 35,277, in Acholi: 61,272). Then 1,805 pairs with identical sides (removed) and 574 exact duplicates were removed, leaving 1,444,650 pairs. Decontamination against SALT dev/test removed 2 pair(s), leaving 1,444,648; 2,000 of those were held out for validation. No further pair-level filter was used.
|
| 73 |
+
- **Tokenizer:** trained on tulati plus the *text* of the SALT train split (Runyankole and Acholi only). The model weights were
|
| 74 |
+
trained on tulati only.
|
| 75 |
+
- **Schedule:** 5 epochs, 19,824 optimizer steps (about 25k target tokens per step), fp16 on one Kaggle T4,
|
| 76 |
+
label smoothing 0.1, AdamW, linear warmup then inverse-sqrt decay (peak LR 3e-4).
|
| 77 |
+
|
| 78 |
+
## Evaluation
|
| 79 |
+
|
| 80 |
+
<!-- RESULTS:START -->
|
| 81 |
+
**Complete SALT dev/test scores (BLEU, chrF, chrF++): not run yet.** SALT test has not been used for anything.
|
| 82 |
+
|
| 83 |
+
What has been measured so far, at the end of pretraining (step 19,824):
|
| 84 |
+
|
| 85 |
+
| Set | Direction | Loss | Quick chrF++ (greedy, first 128 sentences) |
|
| 86 |
+
|---|---|---|---|
|
| 87 |
+
| tulati validation (held-out machine-translated pairs) | nyn→ach | 1.405 | 52.62 |
|
| 88 |
+
| tulati validation (held-out machine-translated pairs) | ach→nyn | 1.461 | 52.40 |
|
| 89 |
+
| SALT dev (human translations) | nyn→ach | 3.547 | 34.99 |
|
| 90 |
+
| SALT dev (human translations) | ach→nyn | 3.629 | 37.24 |
|
| 91 |
+
|
| 92 |
+
The quick chrF++ is a noisy check on a small subset with greedy decoding; it is not comparable to full-set scores. SALT dev was only observed here, not used to choose anything.
|
| 93 |
+
|
| 94 |
+
Copy baseline on the complete SALT dev set (output the source sentence unchanged), sacreBLEU 2.5.1:
|
| 95 |
+
|
| 96 |
+
| Direction | BLEU | chrF | chrF++ |
|
| 97 |
+
|---|---|---|---|
|
| 98 |
+
| nyn→ach | 0.21 | 14.88 | 12.03 |
|
| 99 |
+
| ach→nyn | 0.21 | 12.76 | 10.60 |
|
| 100 |
+
<!-- RESULTS:END -->
|
| 101 |
+
|
| 102 |
+
Note that SALT's Runyankole and Acholi sentences are independent human translations of the same English sentence, so a
|
| 103 |
+
reference in one language is not a translation of the reference in the other.
|
| 104 |
+
|
| 105 |
+
## Limitations
|
| 106 |
+
|
| 107 |
+
- Both sides of every training pair are machine output, so the model inherits that translator's errors and style. Real
|
| 108 |
+
human-written text (dialect, spelling, code-switching) may be handled worse than benchmark numbers suggest. The table above
|
| 109 |
+
shows this: loss on held-out machine-translated pairs is far lower than loss on human-translated SALT dev.
|
| 110 |
+
- Meaning can be dropped or changed, especially for numbers, names and rare words. Do not use it for medical, legal
|
| 111 |
+
or other high-stakes content without human review.
|
| 112 |
+
- Sentence-level model: inputs longer than about 128 pieces are truncated or degrade.
|
| 113 |
+
- Outputs have not been reviewed by an Acholi reader.
|
| 114 |
+
|
| 115 |
+
## Files
|
| 116 |
+
|
| 117 |
+
`model.safetensors` weights · `config.json` architecture and training summary · `spm.model` tokenizer ·
|
| 118 |
+
`zewi.py` standalone inference code · `README.md` this card.
|
| 119 |
+
|
| 120 |
+
## License
|
| 121 |
+
|
| 122 |
+
Released under the MIT License (as are tulati, the translation model that generated the training data, and SALT).
|
| 123 |
+
|
| 124 |
+
## Author
|
| 125 |
+
|
| 126 |
+
Amanyire Daniel (amDANIEL2024) · domusdeiug@gmail.com · https://domusdeiug.com
|
config.json
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model_type": "zewi-seq2seq",
|
| 3 |
+
"arch": {
|
| 4 |
+
"vocab": 32000,
|
| 5 |
+
"d_model": 640,
|
| 6 |
+
"heads": 8,
|
| 7 |
+
"ffn": 2560,
|
| 8 |
+
"enc_layers": 6,
|
| 9 |
+
"dec_layers": 6,
|
| 10 |
+
"dropout": 0.1,
|
| 11 |
+
"max_pos": 256,
|
| 12 |
+
"langs": [
|
| 13 |
+
"nyn",
|
| 14 |
+
"ach"
|
| 15 |
+
]
|
| 16 |
+
},
|
| 17 |
+
"spm_sha": "a76c424a79866986",
|
| 18 |
+
"num_parameters": 89418240,
|
| 19 |
+
"pretrain_steps": 19824,
|
| 20 |
+
"pretrain_epochs_completed": 5,
|
| 21 |
+
"pretrain_target_tokens": 435697460,
|
| 22 |
+
"env": {
|
| 23 |
+
"torch": "2.11.0+cu130",
|
| 24 |
+
"sentencepiece": "0.2.1",
|
| 25 |
+
"safetensors": "0.8.0"
|
| 26 |
+
}
|
| 27 |
+
}
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:efc6f5bfb19631742f6f8d7c1006416ab89773087bc4864c3775d640d0f2d104
|
| 3 |
+
size 357692352
|
spm.model
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a76c424a7986698628fbe0c496f6e7019e9585515dd83e36f06e2b261215b3be
|
| 3 |
+
size 810040
|
zewi.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""zewi - standalone Runyankole <-> Acholi direct translation (inference only; no English involved).
|
| 2 |
+
|
| 3 |
+
pip install torch sentencepiece safetensors huggingface_hub
|
| 4 |
+
|
| 5 |
+
from zewi import Translator
|
| 6 |
+
t = Translator("path/to/this/folder") # or Translator("amDANIEL2024/zewi_base")
|
| 7 |
+
t.translate("<a Runyankole sentence>", "nyn2ach")
|
| 8 |
+
t.translate(["<an Acholi sentence>"], "ach2nyn")
|
| 9 |
+
|
| 10 |
+
Directions: "nyn2ach" (Runyankole -> Acholi) and "ach2nyn" (Acholi -> Runyankole).
|
| 11 |
+
"""
|
| 12 |
+
import json
|
| 13 |
+
import math
|
| 14 |
+
import os
|
| 15 |
+
|
| 16 |
+
import sentencepiece as spm
|
| 17 |
+
import torch
|
| 18 |
+
import torch.nn as nn
|
| 19 |
+
import torch.nn.functional as F
|
| 20 |
+
from safetensors.torch import load_file
|
| 21 |
+
|
| 22 |
+
PAD, UNK, BOS, EOS = 0, 1, 2, 3
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def clean_text(s):
|
| 26 |
+
s = str(s).replace("’", "'").replace("‘", "'").replace("“", '"').replace("”", '"')
|
| 27 |
+
return " ".join(s.split())
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _sinusoid(n, d):
|
| 31 |
+
pos = torch.arange(n, dtype=torch.float32).unsqueeze(1)
|
| 32 |
+
div = torch.exp(torch.arange(0, d, 2, dtype=torch.float32) * (-math.log(10000.0) / d))
|
| 33 |
+
pe = torch.zeros(n, d)
|
| 34 |
+
pe[:, 0::2] = torch.sin(pos * div)
|
| 35 |
+
pe[:, 1::2] = torch.cos(pos * div)
|
| 36 |
+
return pe
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class Seq2Seq(nn.Module):
|
| 40 |
+
"""Pre-LN encoder-decoder Transformer; one embedding matrix shared by encoder, decoder and output."""
|
| 41 |
+
|
| 42 |
+
def __init__(self, arch):
|
| 43 |
+
super().__init__()
|
| 44 |
+
d = arch["d_model"]
|
| 45 |
+
self.arch, self.scale = arch, d ** 0.5
|
| 46 |
+
self.emb = nn.Embedding(arch["vocab"], d, padding_idx=PAD)
|
| 47 |
+
self.register_buffer("pe", _sinusoid(arch["max_pos"], d), persistent=False)
|
| 48 |
+
self.drop = nn.Dropout(arch["dropout"])
|
| 49 |
+
kw = dict(d_model=d, nhead=arch["heads"], dim_feedforward=arch["ffn"], dropout=arch["dropout"],
|
| 50 |
+
activation="gelu", batch_first=True, norm_first=True)
|
| 51 |
+
self.encoder = nn.TransformerEncoder(nn.TransformerEncoderLayer(**kw), arch["enc_layers"],
|
| 52 |
+
norm=nn.LayerNorm(d), enable_nested_tensor=False)
|
| 53 |
+
self.decoder = nn.TransformerDecoder(nn.TransformerDecoderLayer(**kw), arch["dec_layers"],
|
| 54 |
+
norm=nn.LayerNorm(d))
|
| 55 |
+
|
| 56 |
+
def encode(self, src):
|
| 57 |
+
pad = src.eq(PAD)
|
| 58 |
+
x = self.drop(self.emb(src) * self.scale + self.pe[:src.size(1)])
|
| 59 |
+
return self.encoder(x, src_key_padding_mask=pad), pad
|
| 60 |
+
|
| 61 |
+
def decode(self, tgt, memory, mem_pad):
|
| 62 |
+
L = tgt.size(1)
|
| 63 |
+
x = self.drop(self.emb(tgt) * self.scale + self.pe[:L])
|
| 64 |
+
causal = torch.triu(torch.ones(L, L, dtype=torch.bool, device=tgt.device), diagonal=1)
|
| 65 |
+
h = self.decoder(x, memory, tgt_mask=causal, memory_key_padding_mask=mem_pad)
|
| 66 |
+
return F.linear(h, self.emb.weight)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class Translator:
|
| 70 |
+
def __init__(self, path="amDANIEL2024/zewi_base", device=None, token=None):
|
| 71 |
+
if not os.path.isdir(path):
|
| 72 |
+
from huggingface_hub import snapshot_download
|
| 73 |
+
path = snapshot_download(path, token=token)
|
| 74 |
+
with open(os.path.join(path, "config.json"), encoding="utf-8") as f:
|
| 75 |
+
self.config = json.load(f)
|
| 76 |
+
self.arch = self.config["arch"]
|
| 77 |
+
self.V = self.arch["vocab"]
|
| 78 |
+
self.sp = spm.SentencePieceProcessor(model_file=os.path.join(path, "spm.model"))
|
| 79 |
+
assert self.sp.get_piece_size() == self.V, "tokenizer and model sizes differ"
|
| 80 |
+
a, b = self.arch["langs"] # e.g. ["nyn", "ach"]
|
| 81 |
+
# the tag names the TARGET language
|
| 82 |
+
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}>")}
|
| 83 |
+
self.device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu"))
|
| 84 |
+
self.model = Seq2Seq(self.arch)
|
| 85 |
+
self.model.load_state_dict(load_file(os.path.join(path, "model.safetensors")))
|
| 86 |
+
self.model.to(self.device).eval()
|
| 87 |
+
self._amp = self.device.type == "cuda"
|
| 88 |
+
|
| 89 |
+
def _autocast(self):
|
| 90 |
+
return torch.autocast(device_type=self.device.type, dtype=torch.float16, enabled=self._amp)
|
| 91 |
+
|
| 92 |
+
@torch.no_grad()
|
| 93 |
+
def _beam_search(self, src, beam, max_len, length_penalty):
|
| 94 |
+
B, dev, V = src.size(0), src.device, self.V
|
| 95 |
+
with self._autocast():
|
| 96 |
+
memory, mpad = self.model.encode(src)
|
| 97 |
+
D = memory.size(-1)
|
| 98 |
+
memory = memory.unsqueeze(1).expand(B, beam, -1, -1).reshape(B * beam, -1, D)
|
| 99 |
+
mpad = mpad.unsqueeze(1).expand(B, beam, -1).reshape(B * beam, -1)
|
| 100 |
+
ys = torch.full((B * beam, 1), BOS, dtype=torch.long, device=dev)
|
| 101 |
+
scores = torch.zeros(B, beam, device=dev)
|
| 102 |
+
scores[:, 1:] = -1e9
|
| 103 |
+
fin = torch.zeros(B * beam, dtype=torch.bool, device=dev)
|
| 104 |
+
base = (torch.arange(B, device=dev) * beam).unsqueeze(1)
|
| 105 |
+
for _ in range(max_len):
|
| 106 |
+
with self._autocast():
|
| 107 |
+
logits = self.model.decode(ys, memory, mpad)[:, -1]
|
| 108 |
+
logp = F.log_softmax(logits.float(), dim=-1)
|
| 109 |
+
logp[:, PAD] = -1e9
|
| 110 |
+
logp[:, BOS] = -1e9
|
| 111 |
+
if fin.any():
|
| 112 |
+
logp[fin] = -1e9
|
| 113 |
+
logp[fin, PAD] = 0.0
|
| 114 |
+
cand = (scores.view(-1, 1) + logp).view(B, beam * V)
|
| 115 |
+
top, idx = cand.topk(beam, dim=1)
|
| 116 |
+
sel = (base + idx // V).view(-1)
|
| 117 |
+
word = (idx % V).view(-1, 1)
|
| 118 |
+
ys = torch.cat([ys[sel], word], dim=1)
|
| 119 |
+
fin = fin[sel] | (word.squeeze(1) == EOS)
|
| 120 |
+
scores = top
|
| 121 |
+
if fin.all():
|
| 122 |
+
break
|
| 123 |
+
body = ys[:, 1:]
|
| 124 |
+
is_eos = body.eq(EOS)
|
| 125 |
+
length = torch.where(is_eos.any(1), is_eos.float().argmax(1) + 1,
|
| 126 |
+
torch.full_like(fin, body.size(1), dtype=torch.long))
|
| 127 |
+
norm = scores.view(-1) / (((5.0 + length.float()) / 6.0) ** length_penalty)
|
| 128 |
+
best = norm.view(B, beam).argmax(1)
|
| 129 |
+
rows = torch.arange(B, device=dev) * beam + best
|
| 130 |
+
out = []
|
| 131 |
+
for r in rows.tolist():
|
| 132 |
+
seq = body[r].tolist()
|
| 133 |
+
if EOS in seq:
|
| 134 |
+
seq = seq[:seq.index(EOS)]
|
| 135 |
+
out.append([t for t in seq if t != PAD])
|
| 136 |
+
return out
|
| 137 |
+
|
| 138 |
+
@torch.no_grad()
|
| 139 |
+
def translate(self, texts, direction, beam=4, length_penalty=0.6, batch_size=24):
|
| 140 |
+
"""texts: a string or a list of strings. direction: e.g. "nyn2ach" or "ach2nyn". Returns a string or a list."""
|
| 141 |
+
if direction not in self.tags:
|
| 142 |
+
raise ValueError(f"direction must be one of {sorted(self.tags)}")
|
| 143 |
+
single = isinstance(texts, str)
|
| 144 |
+
texts = [texts] if single else list(texts)
|
| 145 |
+
max_pos = self.arch["max_pos"]
|
| 146 |
+
tag = self.tags[direction]
|
| 147 |
+
enc = self.sp.encode([clean_text(t) for t in texts])
|
| 148 |
+
ids = [[tag] + e[:max_pos - 3] + [EOS] for e in enc]
|
| 149 |
+
order = sorted(range(len(texts)), key=lambda i: len(ids[i]), reverse=True)
|
| 150 |
+
out = [None] * len(texts)
|
| 151 |
+
for b in range(0, len(order), batch_size):
|
| 152 |
+
idxs = order[b:b + batch_size]
|
| 153 |
+
L = max(len(ids[i]) for i in idxs)
|
| 154 |
+
src = torch.zeros((len(idxs), L), dtype=torch.long)
|
| 155 |
+
for r, i in enumerate(idxs):
|
| 156 |
+
src[r, :len(ids[i])] = torch.tensor(ids[i])
|
| 157 |
+
hyps = self._beam_search(src.to(self.device), beam, min(max_pos - 1, int(L * 1.6) + 10), length_penalty)
|
| 158 |
+
for i, h in zip(idxs, hyps):
|
| 159 |
+
out[i] = self.sp.decode(h)
|
| 160 |
+
return out[0] if single else out
|