Feature Extraction
Transformers
Safetensors
Hebrew
Official Aramaic (700-300 BCE)
bert
hebrew
abbreviations
roshei-tevot
sefaria
text-embeddings-inference
Instructions to use Sefaria/BeRTevot with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Sefaria/BeRTevot with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("feature-extraction", model="Sefaria/BeRTevot")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModel tokenizer = AutoTokenizer.from_pretrained("Sefaria/BeRTevot") model = AutoModel.from_pretrained("Sefaria/BeRTevot", device_map="auto") - Notebooks
- Google Colab
- Kaggle
v6: retrained on the rebuilt dataset (108 new lexicon readings, wrong prefixed readings of ב' removed); per-book tables (book_tables.json, optional book=); 405 readings merged into sense classes; tokenizer loaded from tokenizer.json (transformers 5's AutoTokenizer ignored the pre-tokenizer and cost about 10 points)
Browse files- README.md +22 -19
- book_tables.json +0 -0
- index/embeddings.npy +2 -2
- index/lexicon.json +0 -0
- model.safetensors +1 -1
- roshei_tevot/book_tables.py +162 -0
- roshei_tevot/encoding.py +20 -0
- roshei_tevot/predict.py +27 -12
- roshei_tevot_config.json +2 -2
- senses.json +0 -0
- train_counts.json +0 -0
- training_report.json +41 -41
README.md
CHANGED
|
@@ -4,7 +4,7 @@ language: [he, arc]
|
|
| 4 |
library_name: transformers
|
| 5 |
tags: [hebrew, abbreviations, roshei-tevot, sefaria]
|
| 6 |
---
|
| 7 |
-
# BeRTevot: expanding Hebrew and Aramaic abbreviations in context (BEREL 3.0, siamese),
|
| 8 |
|
| 9 |
Picks the meaning of a Hebrew or Aramaic abbreviation (roshei tevot, e.g. ר"ש, or a truncated word, e.g. אחרי') in context, by ranking the **sense classes** the Sefaria roshei tevot lexicon lists for it.
|
| 10 |
|
|
@@ -16,7 +16,8 @@ Picks the meaning of a Hebrew or Aramaic abbreviation (roshei tevot, e.g. ר"ש,
|
|
| 16 |
| `index/lexicon.json`, `index/embeddings.npy` | which readings a token can have (with library frequencies), one fp16 embedding per reading (135 MB) |
|
| 17 |
| `senses.json` | sense classes: readings that are spellings of one answer (`איכא דאמרי` / `אית דאמרין`) |
|
| 18 |
| `train_counts.json` | per key, how many training examples each reading labels: the frequency prior (2 MB) |
|
| 19 |
-
| `
|
|
|
|
| 20 |
|
| 21 |
## Use
|
| 22 |
```python
|
|
@@ -25,7 +26,7 @@ from huggingface_hub import snapshot_download
|
|
| 25 |
|
| 26 |
folder = snapshot_download("Sefaria/BeRTevot")
|
| 27 |
sys.path.insert(0, folder)
|
| 28 |
-
from roshei_tevot.predict import RosheiTevot # needs torch, transformers, numpy
|
| 29 |
|
| 30 |
rt = RosheiTevot.from_pretrained(folder) # CPU is fine: candidates are embedded in advance
|
| 31 |
for t in rt.expand('אמר ר"ש בן לקיש בפ"ב דשבת, ובסק"ג כתב הרמ"א')["tokens"]:
|
|
@@ -34,33 +35,35 @@ for t in rt.expand('אמר ר"ש בן לקיש בפ"ב דשבת, ובסק"ג כ
|
|
| 34 |
```
|
| 35 |
`expand` returns the cleaned text and, per abbreviation found, `senses`: sense classes best first (`probability` summed over a class's spellings, `readings` with each spelling's share, `label` the English gloss). A token the lexicon has no reading for gets empty `senses`.
|
| 36 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
## What the code does around the model (and why you should not skip it)
|
| 38 |
1. **Detect** tokens that look like abbreviations, with attached prefix letters; drop letter and divine names written with gershayim (אל"ף, הוי"ה): the model read them at p~1.
|
| 39 |
2. **Offer candidates**: the lexicon's readings for the token (as written or behind a prefix, letters must fit); the **number** for a numeral (`י"ד` -> `ארבעה עשר`, also behind a prefix, also one-letter geresh numerals `בג'`); `סעיף קטן X` for `סק"X`; for a **truncated word** (`לכתחי'`) the 8 most frequent library words that start with its letters; citation readings (`סקי"א`), but never for a bare numeral or a token ending in a geresh (there they win with `קיצור` / `סימן י'`).
|
| 40 |
3. **Encode**: the token wrapped in the added `<abbr>` markers, 200 words of context each side, 512 tokens, no title or category; the model's vector is the mean over the marked span.
|
| 41 |
-
4. **Score**: softmax over `logit_scale * cosine + prior_weight * log(1 + count)`, where `count` is how many *training* examples of the key the reading labels (`train_counts.json`), as in the evaluation. `prior_weight` defaults to 0.5 (0 when the counts file is absent).
|
| 42 |
5. **Group by sense** and sum probabilities.
|
| 43 |
|
| 44 |
## Training and data
|
| 45 |
-
- Base `dicta-il/BEREL_3.0`; one epoch of 600,000 rows sampled from 1,
|
| 46 |
-
- Data: Sefaria's roshei tevot dataset (
|
| 47 |
-
-
|
|
|
|
| 48 |
|
| 49 |
-
## Evaluation (
|
| 50 |
-
| split | answerable |
|
| 51 |
|---|---|---|---|
|
| 52 |
-
| val | 3,
|
| 53 |
-
| test_seen_keys | 4,
|
| 54 |
-
| test_unseen_keys | 336 |
|
| 55 |
-
| number_val | 2,103 | 98.3 | 98.1 |
|
| 56 |
-
| number_test_seen_keys | 2,063 | 98.1 | 98.4 |
|
| 57 |
-
| abbr_val | 1,408 | 89.6 | 89.6 |
|
| 58 |
-
| abbr_test_seen_keys | 1,409 | 89.1 | 89.9 |
|
| 59 |
|
| 60 |
-
|
| 61 |
Not measured on this revision: the comparison with Dicta (v4: 91.0% target accuracy on 500 held-out passages against Dicta's 58.0%).
|
| 62 |
|
| 63 |
## Known issues
|
| 64 |
-
- The lexicon still holds `פקי"א` = `פרק קי"א` (a citation pattern
|
| 65 |
- Whether a token is an abbreviation at all is decided by `detect`, not the model; common words with a geresh can be offered readings.
|
| 66 |
-
- Candidates are the lexicon's: a reading it lacks cannot be chosen, and `test_unseen_keys` (abbreviations never seen in training) is the weak spot (
|
|
|
|
|
|
| 4 |
library_name: transformers
|
| 5 |
tags: [hebrew, abbreviations, roshei-tevot, sefaria]
|
| 6 |
---
|
| 7 |
+
# BeRTevot: expanding Hebrew and Aramaic abbreviations in context (BEREL 3.0, siamese), v6 (Nov 25, 2026)
|
| 8 |
|
| 9 |
Picks the meaning of a Hebrew or Aramaic abbreviation (roshei tevot, e.g. ר"ש, or a truncated word, e.g. אחרי') in context, by ranking the **sense classes** the Sefaria roshei tevot lexicon lists for it.
|
| 10 |
|
|
|
|
| 16 |
| `index/lexicon.json`, `index/embeddings.npy` | which readings a token can have (with library frequencies), one fp16 embedding per reading (135 MB) |
|
| 17 |
| `senses.json` | sense classes: readings that are spellings of one answer (`איכא דאמרי` / `אית דאמרין`) |
|
| 18 |
| `train_counts.json` | per key, how many training examples each reading labels: the frequency prior (2 MB) |
|
| 19 |
+
| `book_tables.json` | optional per-book tables: the readings a book uses for its own abbreviations (see below) |
|
| 20 |
+
| `roshei_tevot/` | the inference code (`predict.py`, `book_tables.py`, candidate generation, encoding, detection) |
|
| 21 |
|
| 22 |
## Use
|
| 23 |
```python
|
|
|
|
| 26 |
|
| 27 |
folder = snapshot_download("Sefaria/BeRTevot")
|
| 28 |
sys.path.insert(0, folder)
|
| 29 |
+
from roshei_tevot.predict import RosheiTevot # needs torch, transformers, tokenizers, numpy
|
| 30 |
|
| 31 |
rt = RosheiTevot.from_pretrained(folder) # CPU is fine: candidates are embedded in advance
|
| 32 |
for t in rt.expand('אמר ר"ש בן לקיש בפ"ב דשבת, ובסק"ג כתב הרמ"א')["tokens"]:
|
|
|
|
| 35 |
```
|
| 36 |
`expand` returns the cleaned text and, per abbreviation found, `senses`: sense classes best first (`probability` summed over a class's spellings, `readings` with each spelling's share, `label` the English gloss). A token the lexicon has no reading for gets empty `senses`.
|
| 37 |
|
| 38 |
+
**Per-book tables (optional).** If you know the book a passage is from, pass its English index title: `rt.expand(text, book="Mishnah Berurah")` (or `rt.score(rows)` with a `book` in each row). A book with a table also gets its own readings of the key offered as candidates, boosted by `table_boost` (4.0); Rashi on the Talmud and Tosafot have one table each that serves every tractate, layered under a volume's own table. `rt.book_tables.titles()` lists the books. Tables were built from passages whose readings two independent LLM readers agreed on (not human gold) and are strictly a prior: without a `book` nothing changes.
|
| 39 |
+
|
| 40 |
+
**Transformers 4 and 5.** This release loads the tokenizer from `tokenizer.json` itself (`roshei_tevot.encoding.load_tokenizer`). BEREL's file defines its own pre-tokenizer, which keeps abbreviations like `תנ"ך` and `ר"ש` whole; transformers 5's `AutoTokenizer` ignores it, splits abbreviations into pieces the model never saw, and loses about 10 points of top-1 (on 250 majority-sense validation rows: 95.6% with the correct tokenization against 85.2% with `AutoTokenizer` under transformers 5.21, at prior weight 0). If you write your own loading code, do not use `AutoTokenizer.from_pretrained` on this folder with transformers 5; use `load_tokenizer`.
|
| 41 |
+
|
| 42 |
## What the code does around the model (and why you should not skip it)
|
| 43 |
1. **Detect** tokens that look like abbreviations, with attached prefix letters; drop letter and divine names written with gershayim (אל"ף, הוי"ה): the model read them at p~1.
|
| 44 |
2. **Offer candidates**: the lexicon's readings for the token (as written or behind a prefix, letters must fit); the **number** for a numeral (`י"ד` -> `ארבעה עשר`, also behind a prefix, also one-letter geresh numerals `בג'`); `סעיף קטן X` for `סק"X`; for a **truncated word** (`לכתחי'`) the 8 most frequent library words that start with its letters; citation readings (`סקי"א`), but never for a bare numeral or a token ending in a geresh (there they win with `קיצור` / `סימן י'`).
|
| 45 |
3. **Encode**: the token wrapped in the added `<abbr>` markers, 200 words of context each side, 512 tokens, no title or category; the model's vector is the mean over the marked span.
|
| 46 |
+
4. **Score**: softmax over `logit_scale * cosine + prior_weight * log(1 + count)`, where `count` is how many *training* examples of the key the reading labels (`train_counts.json`), as in the evaluation. `prior_weight` defaults to 0.5 (0 when the counts file is absent). On the validation split the prior is worth about 1.3 points of top-1 (94.2% at weight 0, 95.5% at 0.5), but the gain comes from the frequent readings and the rarer ones pay for it: for answers that are under 10% of their key's examples (104 validation rows) top-1 is 81.7% at weight 0 and 76.0% at 0.5. **Do not raise it much above 0.5.** A reading the training set never saw (a recent lexicon addition) has count 0 and is pushed down by `prior_weight * log(1 + the other readings' counts)`: about 3.5 logits, a factor of 30, at 0.5 for a reading seen 1,000 times. Lower it, or pass `prior_weight=0`, for text unlike the library (a different genre) or when you want the lexicon's newest readings to compete evenly.
|
| 47 |
5. **Group by sense** and sum probabilities.
|
| 48 |
|
| 49 |
## Training and data
|
| 50 |
+
- Base `dicta-il/BEREL_3.0`; one epoch of 600,000 rows sampled from 1,062,365 (weight 1/count(key)^0.5, synthetic rows 0.5, sense balancing β 0.5); spot A100, Nov 25, 2026. Run `rt-numbers-v6-siamese-2026-11-25`. Code: `train-roshei-tevot` in Sefaria/ML-Workflows; this release is assembled by `app/roshei_tevot/publish_hf.py` there.
|
| 51 |
+
- Data: Sefaria's roshei tevot dataset (v6, not public; the lexicon, sense classes and counts it produced are in this repo). Built by Sefaria/translation-engine `experiments/expand_roshei_tevot` (`NUMBERS.md` has the rounds v3, v4, v5b; `rebuild_v6.sh` rebuilds it).
|
| 52 |
+
- v6 = v5b plus: 108 lexicon readings from two rounds of gap sweeps over the library; `בשני` and `בשנים` removed from the readings of `ב'` (they came from first-letter alignment: the key is the number two, and the prefixed forms are not readings of it; `בשתי` is still there, put back by a later folding step). The hyperparameters and the training procedure are the same as v5b.
|
| 53 |
+
- `senses.json` also holds 405 readings that were added to the lexicon after the dataset's sense classes were built, merged into the class of their spelling variants (or into a new class of their own) after two rounds of independent model readers agreed; the other candidate merges (inflected forms and the like) were left separate.
|
| 54 |
|
| 55 |
+
## Evaluation (v6 splits; top-1 over rows with 2+ candidates and the label among them; prior weight 0.5)
|
| 56 |
+
| split | answerable | v6 | v5b |
|
| 57 |
|---|---|---|---|
|
| 58 |
+
| val | 3,210 | 95.5 | 95.6 |
|
| 59 |
+
| test_seen_keys | 4,900 | 95.5 | 95.4 |
|
| 60 |
+
| test_unseen_keys | 336 | 89.6 | 88.7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
+
Both models were scored on the same rows with the same code, v5b's index and v6's. **The two are equal within noise.** On val the balanced top-1 (mean over the majority, common and rare sense bands) is 87.8 for v6 and 88.7 for v5b at prior weight 0.5 (89.2 against 88.8 at weight 0); that gap is 6 rows. On the 554 val rows of the common and rare bands, 20 are right only for v5b and 14 only for v6 (McNemar p = 0.39); the rows v6 loses are mostly ambiguous rabbi names (`ר"י` as יוסי, יוחנן or יודן; `מוהר"ן` as נחמן or נתן), and v6 wins rows of the same kind. The +0.9 on unseen keys is 3 rows of 336 and is not significant. v6's value is the corrected lexicon, not a measured accuracy gain.
|
| 63 |
Not measured on this revision: the comparison with Dicta (v4: 91.0% target accuracy on 500 held-out passages against Dicta's 58.0%).
|
| 64 |
|
| 65 |
## Known issues
|
| 66 |
+
- The lexicon still holds `פקי"א` = `פרק קי"א` (a citation pattern whose removal the build re-adds) and `בשתי` as a reading of `ב'`.
|
| 67 |
- Whether a token is an abbreviation at all is decided by `detect`, not the model; common words with a geresh can be offered readings.
|
| 68 |
+
- Candidates are the lexicon's: a reading it lacks cannot be chosen, and `test_unseen_keys` (abbreviations never seen in training) is the weak spot (89.6%).
|
| 69 |
+
- Rabbi names written as the same abbreviation (`ר"י`) remain the largest source of errors; a book table or the author's other works help only where the book's habit is stable.
|
book_tables.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
index/embeddings.npy
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1bafb1e5e49bf1074e7fbc1860ca206b45cb01dbbbb117f7a8872e4fb8c16416
|
| 3 |
+
size 135089792
|
index/lexicon.json
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|
model.safetensors
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
size 735041208
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e9f00e6e421a61d0231017c26630c42fde30c549f8cfc778b1b9cd9e62a1e68a
|
| 3 |
size 735041208
|
roshei_tevot/book_tables.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Per-book tables: the readings a book uses for its own abbreviations, added to the model's scores when the book of a passage is known.
|
| 2 |
+
|
| 3 |
+
tables = BookTables.load("book_tables.json")
|
| 4 |
+
rt.score([{"surface": "ב\"ב", "before": ..., "after": ..., "book": "Mishnah Berurah"}]) # or rt.expand(text, book="Mishnah Berurah")
|
| 5 |
+
|
| 6 |
+
A book's own habits are often readings the lexicon lacks, and a few readings carry most of a book's uses (`ע"ש` is `על שם` in one book, `עין שם` in another).
|
| 7 |
+
A TABLE is `key -> [readings the book uses for it]`, built from passages whose readings two independent readers agreed on (experiments/book_prior in
|
| 8 |
+
Sefaria/translation-engine). For a book with a table:
|
| 9 |
+
- its readings of the token's key are OFFERED as candidates when the lexicon does not already offer them (`inject`, if the prior says `table_inject`);
|
| 10 |
+
- each candidate that is one of the book's readings gets `table_boost` added to its logit (`extra`).
|
| 11 |
+
A FAMILY is one table pooled from many volumes (Rashi on every tractate, Tosafot) and used for every member, so a volume with no table of its own still gets one; a volume
|
| 12 |
+
with its own table gets the union of the two (the larger boost).
|
| 13 |
+
Leave-one-out on labelled passages, model alone -> boost 4 with injection: Mishnah Berurah 79.7% -> 94.9%, Zeroa Yamin 76.2% -> 94.6%, Tikkunei Zohar 56.7% -> 94.3%
|
| 14 |
+
(53.6% -> 93.3% on passages sampled after the table was built), Rashi / Tosafot volumes held out of their family table 84.1% / 82.8% -> 93.5% / 93.4%.
|
| 15 |
+
|
| 16 |
+
File format (`book_tables.json`): a list of priors, each
|
| 17 |
+
{"title": "Mishnah Berurah", "table": {key: [reading, ...]}, "table_boost": 4.0, "table_inject": true,
|
| 18 |
+
"family_members": [titles] (only on a family prior: the books it applies to)
|
| 19 |
+
"wb", "counts", "ws", "ws_boost" (optional, older: wb * log(1 + the reading's labelled uses in the book) + ws_boost for the work-level reading ws[key])}
|
| 20 |
+
"""
|
| 21 |
+
import json
|
| 22 |
+
import math
|
| 23 |
+
import re
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
from typing import Iterable, Optional
|
| 26 |
+
|
| 27 |
+
from .vendor.detect import parses
|
| 28 |
+
from .vendor.hebrew import medial
|
| 29 |
+
|
| 30 |
+
FILE = "book_tables.json"
|
| 31 |
+
_GROUPS = ["וש", "ד", "בכל"] # attached prefixes in grammatical order: (ו ש)* then one of ב כ ל, and ד
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _words(text: str) -> list[str]:
|
| 35 |
+
return [medial(w) for w in re.sub(r"[^\w\s]", "", text).split()]
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _ym(word: str) -> str:
|
| 39 |
+
return word[:-2] + "ימ" if word.endswith("ינ") else word # ים / ין plural endings are one reading
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _prefix_variants(word: str) -> list[str]:
|
| 43 |
+
"""The ways of taking 1-3 attached prefix letters off a word (grammatical order, at least 2 letters left)."""
|
| 44 |
+
out, cur, gi = [], word, 0
|
| 45 |
+
for _ in range(3):
|
| 46 |
+
if len(cur) < 3:
|
| 47 |
+
break
|
| 48 |
+
g = next((k for k, grp in enumerate(_GROUPS) if cur[0] in grp and k >= gi), None)
|
| 49 |
+
if g is None:
|
| 50 |
+
break
|
| 51 |
+
cur = cur[1:]
|
| 52 |
+
gi = g if g == 0 else g + 1
|
| 53 |
+
out.append(cur)
|
| 54 |
+
return out
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _same_words(a: str, b: str) -> bool:
|
| 58 |
+
"""The same words, or the same words once attached prefix letters are taken off the first word of either side. Nothing looser: `בית שין` / `בית שני`,
|
| 59 |
+
`אמר ליה` / `אמרה ליה`, `רבי נחמיה` / `רב נחמן` stay different readings."""
|
| 60 |
+
wa, wb = [_ym(w) for w in _words(a)], [_ym(w) for w in _words(b)]
|
| 61 |
+
if not wa or not wb:
|
| 62 |
+
return False
|
| 63 |
+
if wa == wb:
|
| 64 |
+
return True
|
| 65 |
+
return any([rest] + x[1:] == y for x, y in ((wa, wb), (wb, wa)) for rest in _prefix_variants(x[0]))
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _forms(reading: str, surface: str) -> list[str]:
|
| 69 |
+
"""The reading, and it without each attached prefix the token carries (a reading may keep the token's prefix: `ובתוס'` = `ובתוספות`)."""
|
| 70 |
+
out = [reading]
|
| 71 |
+
for p in {p for p, _a in parses(surface)}:
|
| 72 |
+
if p and reading.startswith(p) and len(reading) > len(p) + 1:
|
| 73 |
+
out.append(reading[len(p):])
|
| 74 |
+
return out
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def same_reading(surface: str, a: str, b: str) -> bool:
|
| 78 |
+
"""Do two readings of a token mean the same thing: the same words, ignoring the token's attached prefix and a prefix letter on the first word (strict, see _same_words)."""
|
| 79 |
+
if not a or not b:
|
| 80 |
+
return False
|
| 81 |
+
return a == b or any(_same_words(x, y) for x in _forms(a, surface) for y in _forms(b, surface))
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class BookTables:
|
| 85 |
+
def __init__(self, priors: Iterable[dict] = ()):
|
| 86 |
+
self.priors: dict[str, dict] = {}
|
| 87 |
+
for prior in priors:
|
| 88 |
+
self.priors[prior["title"]] = prior
|
| 89 |
+
self._layered: dict[str, dict] = {}
|
| 90 |
+
|
| 91 |
+
@classmethod
|
| 92 |
+
def load(cls, *paths) -> "BookTables":
|
| 93 |
+
"""One or more JSON files, each a list of priors or a single prior (a file that is not there is skipped)."""
|
| 94 |
+
priors = []
|
| 95 |
+
for path in paths:
|
| 96 |
+
if Path(path).exists():
|
| 97 |
+
data = json.loads(Path(path).read_text(encoding="utf-8"))
|
| 98 |
+
priors.extend(data if isinstance(data, list) else [data])
|
| 99 |
+
return cls(priors)
|
| 100 |
+
|
| 101 |
+
@classmethod
|
| 102 |
+
def single(cls, title: str, table: dict, boost: float = 4.0, inject: bool = True) -> "BookTables":
|
| 103 |
+
"""One book's table given directly (for tests and evaluations that build the table themselves)."""
|
| 104 |
+
return cls([{"title": title, "table": table, "table_boost": boost, "table_inject": inject}])
|
| 105 |
+
|
| 106 |
+
def __bool__(self) -> bool:
|
| 107 |
+
return bool(self.priors)
|
| 108 |
+
|
| 109 |
+
def titles(self) -> list[str]:
|
| 110 |
+
"""The books with a table of their own, then every member of a family."""
|
| 111 |
+
return sorted({t for t in self.priors if not t.startswith("family:")} | {m for p in self.priors.values() for m in p.get("family_members", ())})
|
| 112 |
+
|
| 113 |
+
def family_of(self, book: str) -> Optional[dict]:
|
| 114 |
+
for prior in self.priors.values():
|
| 115 |
+
if book in prior.get("family_members", ()):
|
| 116 |
+
return prior
|
| 117 |
+
return None
|
| 118 |
+
|
| 119 |
+
def knows(self, book: str) -> bool:
|
| 120 |
+
return bool(book) and (book in self.priors or self.family_of(book) is not None)
|
| 121 |
+
|
| 122 |
+
def prior(self, book: str) -> Optional[dict]:
|
| 123 |
+
"""The prior to score a book with: its own, its family's, or both layered (the union of the tables, the larger boost)."""
|
| 124 |
+
own = self.priors.get(book) if book else None
|
| 125 |
+
fam = self.family_of(book) if book else None
|
| 126 |
+
if not fam or own is fam:
|
| 127 |
+
return own
|
| 128 |
+
if own is None:
|
| 129 |
+
return fam
|
| 130 |
+
if book not in self._layered:
|
| 131 |
+
table = {k: list(v) for k, v in fam.get("table", {}).items()}
|
| 132 |
+
for k, v in own.get("table", {}).items():
|
| 133 |
+
table[k] = list(dict.fromkeys(list(v) + table.get(k, [])))
|
| 134 |
+
self._layered[book] = {**own, "table": table, "table_boost": max(own.get("table_boost", 0.0), fam.get("table_boost", 0.0)), "table_inject": True}
|
| 135 |
+
return self._layered[book]
|
| 136 |
+
|
| 137 |
+
def inject(self, book: str, surface: str, found: dict) -> dict:
|
| 138 |
+
"""`found` ({reading: frequency}) plus the book's readings of the token's key that the lexicon does not already offer (frequency 0)."""
|
| 139 |
+
prior = self.prior(book)
|
| 140 |
+
if not prior or not prior.get("table_inject"):
|
| 141 |
+
return found
|
| 142 |
+
add = {}
|
| 143 |
+
for k in [surface] + [a for _p, a in parses(surface)]:
|
| 144 |
+
for reading in prior.get("table", {}).get(k, []):
|
| 145 |
+
if not any(same_reading(surface, reading, t) or same_reading(surface, t, reading) for t in found):
|
| 146 |
+
add[reading] = 0
|
| 147 |
+
return {**found, **add} if add else found
|
| 148 |
+
|
| 149 |
+
def extra(self, book: str, surface: str, texts: list[str]) -> list[float]:
|
| 150 |
+
"""The logit added to each reading by the book's prior."""
|
| 151 |
+
prior = self.prior(book)
|
| 152 |
+
if not prior:
|
| 153 |
+
return [0.0] * len(texts)
|
| 154 |
+
keys = [surface] + [a for _p, a in parses(surface)]
|
| 155 |
+
table, counts, ws = prior.get("table", {}), prior.get("counts", {}), prior.get("ws", {})
|
| 156 |
+
out = []
|
| 157 |
+
for t in texts:
|
| 158 |
+
n = sum(c for k in keys for lab, c in counts.get(k, {}).items() if same_reading(surface, lab, t))
|
| 159 |
+
work = prior.get("ws_boost", 0.0) if any(same_reading(surface, ws[k], t) for k in keys if k in ws) else 0.0
|
| 160 |
+
edition = prior.get("table_boost", 0.0) if any(same_reading(surface, e, t) for k in keys for e in table.get(k, [])) else 0.0
|
| 161 |
+
out.append(prior.get("wb", 0.0) * math.log1p(n) + work + edition)
|
| 162 |
+
return out
|
roshei_tevot/encoding.py
CHANGED
|
@@ -29,6 +29,26 @@ def add_markers(tokenizer) -> int:
|
|
| 29 |
return tokenizer.add_special_tokens({"additional_special_tokens": MARKERS})
|
| 30 |
|
| 31 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
def marker_ids(tokenizer) -> tuple[int, int]:
|
| 33 |
open_id, close_id = tokenizer.convert_tokens_to_ids(MARKERS)
|
| 34 |
if tokenizer.unk_token_id in (open_id, close_id):
|
|
|
|
| 29 |
return tokenizer.add_special_tokens({"additional_special_tokens": MARKERS})
|
| 30 |
|
| 31 |
|
| 32 |
+
def load_tokenizer(path: str):
|
| 33 |
+
"""The folder's tokenizer with the marker tokens added.
|
| 34 |
+
|
| 35 |
+
Loaded from `tokenizer.json` when there is one. BEREL's file defines its own pre-tokenizer (a regex that keeps `תנ"ך` / `ר"ש` whole); transformers 5's
|
| 36 |
+
`AutoTokenizer` rebuilds a generic BertTokenizer from the vocabulary and ignores it, so abbreviations are split into pieces the model never saw: on the same
|
| 37 |
+
250 majority-band rows top-1 fell from 95.6 to 85.2 at prior weight 0 (92.8 against 97.6 at 0.5), and every test query tokenized differently. transformers 4
|
| 38 |
+
reads tokenizer.json, so loading it directly gives the same ids under both."""
|
| 39 |
+
from pathlib import Path
|
| 40 |
+
|
| 41 |
+
from transformers import AutoTokenizer, PreTrainedTokenizerFast
|
| 42 |
+
|
| 43 |
+
file = Path(path) / "tokenizer.json"
|
| 44 |
+
if file.exists():
|
| 45 |
+
tokenizer = PreTrainedTokenizerFast(tokenizer_file=str(file), unk_token="[UNK]", pad_token="[PAD]", cls_token="[CLS]", sep_token="[SEP]", mask_token="[MASK]")
|
| 46 |
+
else:
|
| 47 |
+
tokenizer = AutoTokenizer.from_pretrained(path)
|
| 48 |
+
add_markers(tokenizer)
|
| 49 |
+
return tokenizer
|
| 50 |
+
|
| 51 |
+
|
| 52 |
def marker_ids(tokenizer) -> tuple[int, int]:
|
| 53 |
open_id, close_id = tokenizer.convert_tokens_to_ids(MARKERS)
|
| 54 |
if tokenizer.unk_token_id in (open_id, close_id):
|
roshei_tevot/predict.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
"""Run a trained roshei tevot model on text: find the abbreviations, offer each one's readings, rank them in context, group them by sense.
|
| 2 |
|
| 3 |
from roshei_tevot.steps.predict import RosheiTevot
|
| 4 |
-
rt = RosheiTevot.from_pretrained("Sefaria/
|
| 5 |
for token in rt.expand(text)["tokens"]:
|
| 6 |
print(token["surface"], token["senses"][0]["text"], token["senses"][0]["probability"])
|
| 7 |
|
|
@@ -10,6 +10,7 @@ The model only RANKS the readings it is given, so the folder holds more than wei
|
|
| 10 |
index/lexicon.json, index/embeddings.npy the lexicon (which readings a token can have, with library frequencies) and one embedding per reading
|
| 11 |
senses.json key -> sense index -> {label, texts, expansions}: readings of one sense (spelling variants) are one answer
|
| 12 |
train_counts.json key -> reading -> number of training examples it labels (the frequency prior; optional)
|
|
|
|
| 13 |
|
| 14 |
What happens to a text, in order (each step is something the model does not do for itself):
|
| 15 |
1. `find`: detect tokens that look like abbreviations (prefix letters allowed), clean quote marks, drop letter and divine names written with gershayim (nonabbrev.py).
|
|
@@ -19,6 +20,7 @@ What happens to a text, in order (each step is something the model does not do f
|
|
| 19 |
3. query: the token wrapped in the `<abbr>` markers, 200 words either side (`CONTEXT_WORDS`), no title / category (empty `| `); the model pools over the marked span.
|
| 20 |
4. score: softmax over `logit_scale * cosine + prior_weight * log(1 + count)`, `count` = how many TRAIN-set examples of the key the reading labels (`train_counts.json`), as in the
|
| 21 |
evaluation. A reading the training set never saw has count 0 and is therefore pushed down by up to `prior_weight * log(1 + the other readings' counts)`: that is the price of the prior.
|
|
|
|
| 22 |
5. senses: probabilities of readings of one sense class are summed and the classes ranked.
|
| 23 |
"""
|
| 24 |
import json
|
|
@@ -27,8 +29,9 @@ from typing import Optional
|
|
| 27 |
|
| 28 |
import torch
|
| 29 |
|
|
|
|
| 30 |
from .citations import expand as citation_readings
|
| 31 |
-
from .encoding import collate_candidates, collate_queries, encode_candidate, encode_query
|
| 32 |
from .index import ExpansionIndex, number_reading, prior
|
| 33 |
from .nonabbrev import is_non_abbreviation
|
| 34 |
from .vendor.detect import detect, parses
|
|
@@ -44,11 +47,12 @@ COUNTS_FILE = "train_counts.json"
|
|
| 44 |
|
| 45 |
class RosheiTevot:
|
| 46 |
def __init__(self, model, tokenizer, config: dict, index: ExpansionIndex, senses: Optional[dict] = None,
|
| 47 |
-
prior_weight: Optional[float] = None, device: str = "cpu", train_counts: Optional[dict] = None):
|
| 48 |
self.model, self.tokenizer, self.index, self.senses = model.to(device).eval(), tokenizer, index, senses or {}
|
| 49 |
self.pooling = config.get("pooling", "span")
|
| 50 |
self.scale = float(config["logit_scale"])
|
| 51 |
self.train_counts = train_counts or {}
|
|
|
|
| 52 |
self.prior_weight = prior_weight if prior_weight is not None else (DEFAULT_PRIOR_WEIGHT if self.train_counts else 0.0) # no counts: the model alone
|
| 53 |
self.device = device
|
| 54 |
self._embeddings: dict[str, torch.Tensor] = {} # readings the index lacks (citation readings), embedded on demand
|
|
@@ -57,7 +61,7 @@ class RosheiTevot:
|
|
| 57 |
@classmethod
|
| 58 |
def from_pretrained(cls, path: str, device: str = "cpu", prior_weight: Optional[float] = None, threads: Optional[int] = None) -> "RosheiTevot":
|
| 59 |
"""`path`: a folder laid out as in the module docstring, or a Hugging Face repo id (downloaded with `huggingface_hub.snapshot_download`, needs a login for a private repo)."""
|
| 60 |
-
from transformers import AutoModel
|
| 61 |
|
| 62 |
if threads:
|
| 63 |
torch.set_num_threads(threads)
|
|
@@ -70,13 +74,13 @@ class RosheiTevot:
|
|
| 70 |
if config.get("architecture", "siamese") != "siamese":
|
| 71 |
raise ValueError("Only a siamese model can be run from an index of expansion embeddings.")
|
| 72 |
model = AutoModel.from_pretrained(str(folder), add_pooling_layer=False)
|
| 73 |
-
tokenizer =
|
| 74 |
index = ExpansionIndex.load(str(folder / "index"))
|
| 75 |
senses_file = folder / "senses.json"
|
| 76 |
senses = json.loads(senses_file.read_text()) if senses_file.exists() else {}
|
| 77 |
counts_file = folder / COUNTS_FILE
|
| 78 |
counts = json.loads(counts_file.read_text()) if counts_file.exists() else {}
|
| 79 |
-
return cls(model, tokenizer, config, index, senses, prior_weight, device, counts)
|
| 80 |
|
| 81 |
def train_count(self, surface: str, reading: str) -> int:
|
| 82 |
"""How many training examples of this token's key the reading labels (the key may be the token itself or its prefix-stripped form; a prefixed reading counts as its bare one).
|
|
@@ -166,11 +170,19 @@ class RosheiTevot:
|
|
| 166 |
pattern = {} if (numeral_value(clean(surface)) is not None or surface.endswith("'")) else citation_readings(surface)
|
| 167 |
return {**pattern, **self.index.lexicon.candidates(surface)}
|
| 168 |
|
| 169 |
-
def score(self, rows: list[dict], prior_weight: Optional[float] = None) -> list[dict]:
|
| 170 |
-
"""rows: [{surface, before, after}] -> per row {senses: [sense groups, best first], n_readings} (no senses when the lexicon offers nothing for the token).
|
|
|
|
| 171 |
w = self.prior_weight if prior_weight is None else prior_weight
|
|
|
|
| 172 |
results: list[dict] = [{"senses": [], "n_readings": 0} for _ in rows]
|
| 173 |
-
live = [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
if not live:
|
| 175 |
return results
|
| 176 |
queries = self._encode_queries([rows[i] for i, _ in live])
|
|
@@ -178,6 +190,8 @@ class RosheiTevot:
|
|
| 178 |
texts = list(found)
|
| 179 |
counts = [self.train_count(rows[i]["surface"], t) for t in texts] if self.train_counts else [found[t] for t in texts] # without the table: library frequencies (they do not help, see the model card)
|
| 180 |
logits = self.scale * (self._expansion_vectors(texts) @ q) + w * torch.tensor([prior(c) for c in counts])
|
|
|
|
|
|
|
| 181 |
probs = torch.softmax(logits, dim=0).tolist()
|
| 182 |
results[i] = {"senses": self._describe(rows[i]["surface"], dict(zip(texts, probs)), found), "n_readings": len(texts)}
|
| 183 |
return results
|
|
@@ -196,10 +210,11 @@ class RosheiTevot:
|
|
| 196 |
offset += len(line) + 1
|
| 197 |
return "\n".join(lines), tokens
|
| 198 |
|
| 199 |
-
def expand(self, text: str, prior_weight: Optional[float] = None) -> dict:
|
| 200 |
-
"""{text (cleaned), tokens: [{surface, start, end, senses, n_readings, ...}]}; `senses[0]` is the answer (`senses[0]["text"]` its most likely spelling).
|
|
|
|
| 201 |
cleaned, tokens = self.find(text)
|
| 202 |
-
rows = [{"surface": t["surface"], "before": cleaned[:t["start"]], "after": cleaned[t["end"]:]} for t in tokens]
|
| 203 |
for t, res in zip(tokens, self.score(rows, prior_weight)):
|
| 204 |
t.update(res)
|
| 205 |
return {"text": cleaned, "tokens": tokens}
|
|
|
|
| 1 |
"""Run a trained roshei tevot model on text: find the abbreviations, offer each one's readings, rank them in context, group them by sense.
|
| 2 |
|
| 3 |
from roshei_tevot.steps.predict import RosheiTevot
|
| 4 |
+
rt = RosheiTevot.from_pretrained("Sefaria/BeRTevot") # or a local folder with the same layout
|
| 5 |
for token in rt.expand(text)["tokens"]:
|
| 6 |
print(token["surface"], token["senses"][0]["text"], token["senses"][0]["probability"])
|
| 7 |
|
|
|
|
| 10 |
index/lexicon.json, index/embeddings.npy the lexicon (which readings a token can have, with library frequencies) and one embedding per reading
|
| 11 |
senses.json key -> sense index -> {label, texts, expansions}: readings of one sense (spelling variants) are one answer
|
| 12 |
train_counts.json key -> reading -> number of training examples it labels (the frequency prior; optional)
|
| 13 |
+
book_tables.json per-book tables: the readings a book uses for its own abbreviations (optional, see book_tables.py)
|
| 14 |
|
| 15 |
What happens to a text, in order (each step is something the model does not do for itself):
|
| 16 |
1. `find`: detect tokens that look like abbreviations (prefix letters allowed), clean quote marks, drop letter and divine names written with gershayim (nonabbrev.py).
|
|
|
|
| 20 |
3. query: the token wrapped in the `<abbr>` markers, 200 words either side (`CONTEXT_WORDS`), no title / category (empty `| `); the model pools over the marked span.
|
| 21 |
4. score: softmax over `logit_scale * cosine + prior_weight * log(1 + count)`, `count` = how many TRAIN-set examples of the key the reading labels (`train_counts.json`), as in the
|
| 22 |
evaluation. A reading the training set never saw has count 0 and is therefore pushed down by up to `prior_weight * log(1 + the other readings' counts)`: that is the price of the prior.
|
| 23 |
+
With a `book` that has a table (book_tables.py) its readings of the token are added as candidates and boosted (`score(rows with "book")`, `expand(text, book=...)`).
|
| 24 |
5. senses: probabilities of readings of one sense class are summed and the classes ranked.
|
| 25 |
"""
|
| 26 |
import json
|
|
|
|
| 29 |
|
| 30 |
import torch
|
| 31 |
|
| 32 |
+
from .book_tables import FILE as BOOK_TABLES_FILE, BookTables
|
| 33 |
from .citations import expand as citation_readings
|
| 34 |
+
from .encoding import collate_candidates, collate_queries, encode_candidate, encode_query, load_tokenizer
|
| 35 |
from .index import ExpansionIndex, number_reading, prior
|
| 36 |
from .nonabbrev import is_non_abbreviation
|
| 37 |
from .vendor.detect import detect, parses
|
|
|
|
| 47 |
|
| 48 |
class RosheiTevot:
|
| 49 |
def __init__(self, model, tokenizer, config: dict, index: ExpansionIndex, senses: Optional[dict] = None,
|
| 50 |
+
prior_weight: Optional[float] = None, device: str = "cpu", train_counts: Optional[dict] = None, book_tables: Optional[BookTables] = None):
|
| 51 |
self.model, self.tokenizer, self.index, self.senses = model.to(device).eval(), tokenizer, index, senses or {}
|
| 52 |
self.pooling = config.get("pooling", "span")
|
| 53 |
self.scale = float(config["logit_scale"])
|
| 54 |
self.train_counts = train_counts or {}
|
| 55 |
+
self.book_tables = book_tables or BookTables() # per-book tables (book_tables.py), used for a row that names its `book`
|
| 56 |
self.prior_weight = prior_weight if prior_weight is not None else (DEFAULT_PRIOR_WEIGHT if self.train_counts else 0.0) # no counts: the model alone
|
| 57 |
self.device = device
|
| 58 |
self._embeddings: dict[str, torch.Tensor] = {} # readings the index lacks (citation readings), embedded on demand
|
|
|
|
| 61 |
@classmethod
|
| 62 |
def from_pretrained(cls, path: str, device: str = "cpu", prior_weight: Optional[float] = None, threads: Optional[int] = None) -> "RosheiTevot":
|
| 63 |
"""`path`: a folder laid out as in the module docstring, or a Hugging Face repo id (downloaded with `huggingface_hub.snapshot_download`, needs a login for a private repo)."""
|
| 64 |
+
from transformers import AutoModel
|
| 65 |
|
| 66 |
if threads:
|
| 67 |
torch.set_num_threads(threads)
|
|
|
|
| 74 |
if config.get("architecture", "siamese") != "siamese":
|
| 75 |
raise ValueError("Only a siamese model can be run from an index of expansion embeddings.")
|
| 76 |
model = AutoModel.from_pretrained(str(folder), add_pooling_layer=False)
|
| 77 |
+
tokenizer = load_tokenizer(str(folder)) # from tokenizer.json: transformers 5's AutoTokenizer would ignore its pre-tokenizer (see encoding.load_tokenizer)
|
| 78 |
index = ExpansionIndex.load(str(folder / "index"))
|
| 79 |
senses_file = folder / "senses.json"
|
| 80 |
senses = json.loads(senses_file.read_text()) if senses_file.exists() else {}
|
| 81 |
counts_file = folder / COUNTS_FILE
|
| 82 |
counts = json.loads(counts_file.read_text()) if counts_file.exists() else {}
|
| 83 |
+
return cls(model, tokenizer, config, index, senses, prior_weight, device, counts, BookTables.load(folder / BOOK_TABLES_FILE))
|
| 84 |
|
| 85 |
def train_count(self, surface: str, reading: str) -> int:
|
| 86 |
"""How many training examples of this token's key the reading labels (the key may be the token itself or its prefix-stripped form; a prefixed reading counts as its bare one).
|
|
|
|
| 170 |
pattern = {} if (numeral_value(clean(surface)) is not None or surface.endswith("'")) else citation_readings(surface)
|
| 171 |
return {**pattern, **self.index.lexicon.candidates(surface)}
|
| 172 |
|
| 173 |
+
def score(self, rows: list[dict], prior_weight: Optional[float] = None, book_tables: Optional[BookTables] = None) -> list[dict]:
|
| 174 |
+
"""rows: [{surface, before, after, book?}] -> per row {senses: [sense groups, best first], n_readings} (no senses when the lexicon offers nothing for the token).
|
| 175 |
+
A row with a `book` that has a table (`self.book_tables`, or `book_tables` given here) also gets the book's readings of the token as candidates and their boost."""
|
| 176 |
w = self.prior_weight if prior_weight is None else prior_weight
|
| 177 |
+
tables = self.book_tables if book_tables is None else book_tables
|
| 178 |
results: list[dict] = [{"senses": [], "n_readings": 0} for _ in rows]
|
| 179 |
+
live = []
|
| 180 |
+
for i, r in enumerate(rows):
|
| 181 |
+
found = self.candidates(r["surface"])
|
| 182 |
+
if tables and r.get("book"):
|
| 183 |
+
found = tables.inject(r["book"], r["surface"], found)
|
| 184 |
+
if found:
|
| 185 |
+
live.append((i, found))
|
| 186 |
if not live:
|
| 187 |
return results
|
| 188 |
queries = self._encode_queries([rows[i] for i, _ in live])
|
|
|
|
| 190 |
texts = list(found)
|
| 191 |
counts = [self.train_count(rows[i]["surface"], t) for t in texts] if self.train_counts else [found[t] for t in texts] # without the table: library frequencies (they do not help, see the model card)
|
| 192 |
logits = self.scale * (self._expansion_vectors(texts) @ q) + w * torch.tensor([prior(c) for c in counts])
|
| 193 |
+
if tables and rows[i].get("book"):
|
| 194 |
+
logits = logits + torch.tensor(tables.extra(rows[i]["book"], rows[i]["surface"], texts))
|
| 195 |
probs = torch.softmax(logits, dim=0).tolist()
|
| 196 |
results[i] = {"senses": self._describe(rows[i]["surface"], dict(zip(texts, probs)), found), "n_readings": len(texts)}
|
| 197 |
return results
|
|
|
|
| 210 |
offset += len(line) + 1
|
| 211 |
return "\n".join(lines), tokens
|
| 212 |
|
| 213 |
+
def expand(self, text: str, prior_weight: Optional[float] = None, book: Optional[str] = None) -> dict:
|
| 214 |
+
"""{text (cleaned), tokens: [{surface, start, end, senses, n_readings, ...}]}; `senses[0]` is the answer (`senses[0]["text"]` its most likely spelling).
|
| 215 |
+
`book`: the English index title of the text's book, to use its table when it has one (see book_tables.py)."""
|
| 216 |
cleaned, tokens = self.find(text)
|
| 217 |
+
rows = [{"surface": t["surface"], "before": cleaned[:t["start"]], "after": cleaned[t["end"]:], "book": book} for t in tokens]
|
| 218 |
for t, res in zip(tokens, self.score(rows, prior_weight)):
|
| 219 |
t.update(res)
|
| 220 |
return {"text": cleaned, "tokens": tokens}
|
roshei_tevot_config.json
CHANGED
|
@@ -3,11 +3,11 @@
|
|
| 3 |
"max_length": 512,
|
| 4 |
"context_words": 200,
|
| 5 |
"base_model": "/cache/huggingface/models/dicta-il__BEREL_3.0",
|
| 6 |
-
"dataset_repo": "gs://sefaria-ml-models/roshei-tevot/data/berel-roshei-tevot-numbers-
|
| 7 |
"min_candidates": 2,
|
| 8 |
"holdout_fold": null,
|
| 9 |
"n_folds": 5,
|
| 10 |
"candidate_source": "dataset",
|
| 11 |
"pooling": "span",
|
| 12 |
-
"logit_scale": 21.
|
| 13 |
}
|
|
|
|
| 3 |
"max_length": 512,
|
| 4 |
"context_words": 200,
|
| 5 |
"base_model": "/cache/huggingface/models/dicta-il__BEREL_3.0",
|
| 6 |
+
"dataset_repo": "gs://sefaria-ml-models/roshei-tevot/data/berel-roshei-tevot-numbers-v6",
|
| 7 |
"min_candidates": 2,
|
| 8 |
"holdout_fold": null,
|
| 9 |
"n_folds": 5,
|
| 10 |
"candidate_source": "dataset",
|
| 11 |
"pooling": "span",
|
| 12 |
+
"logit_scale": 21.191316604614258
|
| 13 |
}
|
senses.json
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|
train_counts.json
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|
training_report.json
CHANGED
|
@@ -1,11 +1,11 @@
|
|
| 1 |
{
|
| 2 |
"status": "success",
|
| 3 |
-
"run_name": "rt-numbers-
|
| 4 |
-
"started_at": "2026-11-
|
| 5 |
-
"finished_at": "2026-11-
|
| 6 |
"model_repo_id": "dicta-il/BEREL_3.0",
|
| 7 |
"revision": null,
|
| 8 |
-
"dataset_repo": "gs://sefaria-ml-models/roshei-tevot/data/berel-roshei-tevot-numbers-
|
| 9 |
"synthetic_weight": 0.5,
|
| 10 |
"sense_beta": 0.5,
|
| 11 |
"sense_max_boost": 10.0,
|
|
@@ -28,62 +28,62 @@
|
|
| 28 |
"samples_per_epoch": 600000
|
| 29 |
},
|
| 30 |
"architecture": "siamese",
|
| 31 |
-
"resumed_from_checkpoint":
|
| 32 |
"candidates": {
|
| 33 |
"train": {
|
| 34 |
-
"rows_in":
|
| 35 |
-
"rows_kept":
|
| 36 |
-
"dropped_below_min_candidates":
|
| 37 |
-
"gold_not_in_lexicon_lookup":
|
| 38 |
"candidate_source": "dataset",
|
| 39 |
-
"target_is_sense_class":
|
| 40 |
-
"dropped_and_right_by_default":
|
| 41 |
},
|
| 42 |
"val": {
|
| 43 |
-
"rows_in":
|
| 44 |
-
"rows_kept":
|
| 45 |
-
"dropped_below_min_candidates":
|
| 46 |
-
"gold_not_in_lexicon_lookup":
|
| 47 |
"candidate_source": "dataset",
|
| 48 |
-
"target_is_sense_class":
|
| 49 |
-
"dropped_and_right_by_default":
|
| 50 |
},
|
| 51 |
"ranking": {
|
| 52 |
-
"rows_in":
|
| 53 |
-
"rows_kept":
|
| 54 |
-
"dropped_below_min_candidates":
|
| 55 |
-
"gold_not_in_lexicon_lookup":
|
| 56 |
"candidate_source": "dataset",
|
| 57 |
-
"target_is_sense_class":
|
| 58 |
-
"dropped_and_right_by_default":
|
| 59 |
}
|
| 60 |
},
|
| 61 |
"train_metrics": {
|
| 62 |
-
"train_runtime":
|
| 63 |
-
"train_samples_per_second":
|
| 64 |
-
"train_steps_per_second":
|
| 65 |
-
"train_loss": 0.
|
| 66 |
"epoch": 0.9997866894197952
|
| 67 |
},
|
| 68 |
"final_eval": {
|
| 69 |
-
"eval_loss": 0.
|
| 70 |
-
"eval_runtime": 4.
|
| 71 |
-
"eval_samples_per_second":
|
| 72 |
-
"eval_steps_per_second": 6.
|
| 73 |
"epoch": 0.9997866894197952,
|
| 74 |
-
"eval_top1": 0.
|
| 75 |
-
"eval_frequency_top1": 0.
|
| 76 |
-
"eval_mrr": 0.
|
| 77 |
},
|
| 78 |
"best_validation_top1": {
|
| 79 |
"step": 4687,
|
| 80 |
-
"top1": 0.
|
| 81 |
-
"frequency_top1": 0.
|
| 82 |
-
"mrr": 0.
|
| 83 |
},
|
| 84 |
-
"mean_tokens_per_second":
|
| 85 |
-
"final_model_dir": "/tmp/roshei-tevot-
|
| 86 |
-
"cuda_peak_memory_bytes":
|
| 87 |
},
|
| 88 |
-
"model_uri": "gs://sefaria-ml-models/roshei-tevot/runs/rt-numbers-
|
| 89 |
}
|
|
|
|
| 1 |
{
|
| 2 |
"status": "success",
|
| 3 |
+
"run_name": "rt-numbers-v6-siamese-2026-11-25",
|
| 4 |
+
"started_at": "2026-11-25T17:10:38.860854+00:00",
|
| 5 |
+
"finished_at": "2026-11-25T17:19:17.926619+00:00",
|
| 6 |
"model_repo_id": "dicta-il/BEREL_3.0",
|
| 7 |
"revision": null,
|
| 8 |
+
"dataset_repo": "gs://sefaria-ml-models/roshei-tevot/data/berel-roshei-tevot-numbers-v6",
|
| 9 |
"synthetic_weight": 0.5,
|
| 10 |
"sense_beta": 0.5,
|
| 11 |
"sense_max_boost": 10.0,
|
|
|
|
| 28 |
"samples_per_epoch": 600000
|
| 29 |
},
|
| 30 |
"architecture": "siamese",
|
| 31 |
+
"resumed_from_checkpoint": "/tmp/roshei-tevot-e_9y8mmn/output/trainer/checkpoint-4001",
|
| 32 |
"candidates": {
|
| 33 |
"train": {
|
| 34 |
+
"rows_in": 1062365,
|
| 35 |
+
"rows_kept": 595462,
|
| 36 |
+
"dropped_below_min_candidates": 466903,
|
| 37 |
+
"gold_not_in_lexicon_lookup": 21698,
|
| 38 |
"candidate_source": "dataset",
|
| 39 |
+
"target_is_sense_class": 557408,
|
| 40 |
+
"dropped_and_right_by_default": 456027
|
| 41 |
},
|
| 42 |
"val": {
|
| 43 |
+
"rows_in": 6906,
|
| 44 |
+
"rows_kept": 3445,
|
| 45 |
+
"dropped_below_min_candidates": 3461,
|
| 46 |
+
"gold_not_in_lexicon_lookup": 409,
|
| 47 |
"candidate_source": "dataset",
|
| 48 |
+
"target_is_sense_class": 3112,
|
| 49 |
+
"dropped_and_right_by_default": 3287
|
| 50 |
},
|
| 51 |
"ranking": {
|
| 52 |
+
"rows_in": 6906,
|
| 53 |
+
"rows_kept": 3349,
|
| 54 |
+
"dropped_below_min_candidates": 3557,
|
| 55 |
+
"gold_not_in_lexicon_lookup": 409,
|
| 56 |
"candidate_source": "dataset",
|
| 57 |
+
"target_is_sense_class": 3112,
|
| 58 |
+
"dropped_and_right_by_default": 3287
|
| 59 |
}
|
| 60 |
},
|
| 61 |
"train_metrics": {
|
| 62 |
+
"train_runtime": 338.3604,
|
| 63 |
+
"train_samples_per_second": 1773.068,
|
| 64 |
+
"train_steps_per_second": 13.852,
|
| 65 |
+
"train_loss": 0.04710241866717085,
|
| 66 |
"epoch": 0.9997866894197952
|
| 67 |
},
|
| 68 |
"final_eval": {
|
| 69 |
+
"eval_loss": 0.40501412749290466,
|
| 70 |
+
"eval_runtime": 4.1413,
|
| 71 |
+
"eval_samples_per_second": 831.86,
|
| 72 |
+
"eval_steps_per_second": 6.52,
|
| 73 |
"epoch": 0.9997866894197952,
|
| 74 |
+
"eval_top1": 0.9417445482866044,
|
| 75 |
+
"eval_frequency_top1": 0.8218068535825546,
|
| 76 |
+
"eval_mrr": 0.9666229046135587
|
| 77 |
},
|
| 78 |
"best_validation_top1": {
|
| 79 |
"step": 4687,
|
| 80 |
+
"top1": 0.9417445482866044,
|
| 81 |
+
"frequency_top1": 0.8218068535825546,
|
| 82 |
+
"mrr": 0.9666229046135587
|
| 83 |
},
|
| 84 |
+
"mean_tokens_per_second": 151290.0049103657,
|
| 85 |
+
"final_model_dir": "/tmp/roshei-tevot-e_9y8mmn/output/final",
|
| 86 |
+
"cuda_peak_memory_bytes": 31316381184
|
| 87 |
},
|
| 88 |
+
"model_uri": "gs://sefaria-ml-models/roshei-tevot/runs/rt-numbers-v6-siamese-2026-11-25/final"
|
| 89 |
}
|