noahsantacruz commited on
Commit
fa5bb14
路
verified 路
1 Parent(s): ba34f47

v5b release: train_counts.json (the frequency prior, default weight 0.5), card explains the prior and its risk

Browse files
README.md CHANGED
@@ -15,6 +15,7 @@ Picks the meaning of a Hebrew or Aramaic abbreviation (roshei tevot, e.g. 专"砖,
15
  | `model.safetensors`, `config.json`, tokenizer files, `roshei_tevot_config.json` | the siamese model (BEREL 3.0 fine-tuned; `logit_scale`, span pooling) |
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
  | `roshei_tevot/` | the inference code (`predict.py`, candidate generation, encoding, detection) |
19
 
20
  ## Use
@@ -37,7 +38,7 @@ for t in rt.expand('讗诪专 专"砖 讘谉 诇拽讬砖 讘驻"讘 讚砖讘转, 讜讘住拽"讙 讻
37
  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.
38
  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 `拽讬爪讜专` / `住讬诪谉 讬'`).
39
  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.
40
- 4. **Score**: softmax over `logit_scale * cosine` (the model alone; `prior_weight` defaults to 0). The evaluation's frequency prior used each reading's count in the *training set*, which is worth about 1.5 points of top-1 there; this release carries the lexicon's *library* frequencies instead, and adding `prior_weight * log(1 + frequency)` with those **lowered** top-1 on 700 held-out val rows (92.4% at 0, 91.3% at 0.25, 89.6% at 0.5, 86.9% at 1.0). Leave `prior_weight` at 0 unless you supply your own counts.
41
  5. **Group by sense** and sum probabilities.
42
 
43
  ## Training and data
@@ -56,7 +57,7 @@ for t in rt.expand('讗诪专 专"砖 讘谉 诇拽讬砖 讘驻"讘 讚砖讘转, 讜讘住拽"讙 讻
56
  | abbr_val | 1,408 | 89.6 | 89.6 |
57
  | abbr_test_seen_keys | 1,409 | 89.1 | 89.9 |
58
 
59
- Each model with the training-count prior at the weight the evaluation picked on val (v5b 0.5, v4 0.25); the package runs with no prior, so expect about 1.5 points less on `val`-like text (the 700-row check above: 92.4% with this package's candidates). **At the same prior weight the two differ by 0.5 points or less**, within one training run's noise: v5b is cleaner data and a larger lexicon, not a measured accuracy gain. Top-3 on val / test_seen_keys is 99.5 / 99.6.
60
  Not measured on this revision: the comparison with Dicta (v4: 91.0% target accuracy on 500 held-out passages against Dicta's 58.0%).
61
 
62
  ## Known issues
 
15
  | `model.safetensors`, `config.json`, tokenizer files, `roshei_tevot_config.json` | the siamese model (BEREL 3.0 fine-tuned; `logit_scale`, span pooling) |
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
  | `roshei_tevot/` | the inference code (`predict.py`, candidate generation, encoding, detection) |
20
 
21
  ## Use
 
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). The prior is worth about 3 points of top-1 on a 700-row held-out val sample run through this package (92.4% at weight 0, 95.3% at 0.5, 94.9% at 1.0; with each row's exact dataset counts instead of this table it reaches 96.3% at 0.5, so the table is a slightly lossy copy). **Do not raise it much above 0.5**: on the full evaluation top-1 is flat from 0.5 to 2, but the gain comes from the frequent readings, and the rarer ones pay for it. On the v5b val split, accuracy on keys with few examples is 79 / 79 / 79 / 70 / 55% at weight 0 / 0.25 / 0.5 / 1 / 2, and on a token whose right reading is *not* the most frequent one 89 / 88 / 89 / 86 / 80%. 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.
42
  5. **Group by sense** and sum probabilities.
43
 
44
  ## Training and data
 
57
  | abbr_val | 1,408 | 89.6 | 89.6 |
58
  | abbr_test_seen_keys | 1,409 | 89.1 | 89.9 |
59
 
60
+ Each model with the training-count prior at the weight the evaluation picked on val (v5b 0.5, v4 0.25), which is what the package's default reproduces. **At the same prior weight the two differ by 0.5 points or less**, within one training run's noise: v5b is cleaner data and a larger lexicon, not a measured accuracy gain. Top-3 on val / test_seen_keys is 99.5 / 99.6.
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
roshei_tevot/__pycache__/__init__.cpython-39.pyc CHANGED
Binary files a/roshei_tevot/__pycache__/__init__.cpython-39.pyc and b/roshei_tevot/__pycache__/__init__.cpython-39.pyc differ
 
roshei_tevot/__pycache__/citations.cpython-39.pyc CHANGED
Binary files a/roshei_tevot/__pycache__/citations.cpython-39.pyc and b/roshei_tevot/__pycache__/citations.cpython-39.pyc differ
 
roshei_tevot/__pycache__/encoding.cpython-39.pyc CHANGED
Binary files a/roshei_tevot/__pycache__/encoding.cpython-39.pyc and b/roshei_tevot/__pycache__/encoding.cpython-39.pyc differ
 
roshei_tevot/__pycache__/index.cpython-39.pyc CHANGED
Binary files a/roshei_tevot/__pycache__/index.cpython-39.pyc and b/roshei_tevot/__pycache__/index.cpython-39.pyc differ
 
roshei_tevot/__pycache__/nonabbrev.cpython-39.pyc CHANGED
Binary files a/roshei_tevot/__pycache__/nonabbrev.cpython-39.pyc and b/roshei_tevot/__pycache__/nonabbrev.cpython-39.pyc differ
 
roshei_tevot/__pycache__/predict.cpython-39.pyc CHANGED
Binary files a/roshei_tevot/__pycache__/predict.cpython-39.pyc and b/roshei_tevot/__pycache__/predict.cpython-39.pyc differ
 
roshei_tevot/predict.py CHANGED
@@ -9,6 +9,7 @@ The model only RANKS the readings it is given, so the folder holds more than wei
9
  config.json, model.safetensors, tokenizer files, roshei_tevot_config.json the siamese model (`logit_scale`, `pooling`)
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
 
13
  What happens to a text, in order (each step is something the model does not do for itself):
14
  1. `find`: detect tokens that look like abbreviations (prefix letters allowed), clean quote marks, drop letter and divine names written with gershayim (nonabbrev.py).
@@ -16,7 +17,8 @@ What happens to a text, in order (each step is something the model does not do f
16
  geresh numerals too), `住注讬祝 拽讟谉 X` for `住拽"X`, the library's most frequent completions of a truncated word (诇讻转讞讬'), and citation readings (`住拽讬"讗`) except for a bare
17
  numeral or a token ending in a geresh (there they would win at p~1 with `拽讬爪讜专` / `住讬诪谉 讬'`).
18
  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.
19
- 4. score: softmax over `logit_scale * cosine + prior_weight * log(1 + frequency)`; the prior (off by default) is the lexicon's library frequency of the reading, which does not help (see DEFAULT_PRIOR_WEIGHT).
 
20
  5. senses: probabilities of readings of one sense class are summed and the classes ranked.
21
  """
22
  import json
@@ -34,23 +36,26 @@ from .vendor.hebrew import clean, numeral_value
34
 
35
  CONTEXT_WORDS = 200
36
  MAX_LENGTH = 512
37
- DEFAULT_PRIOR_WEIGHT = 0.0 # the model alone. The evaluation gains about 1.5 points top-1 from a prior of 0.25-1.0 on TRAIN-SET counts of each reading; the lexicon frequency used here is the library count, and on 700 held-out val rows it LOWERED top-1 (92.4 at 0, 91.3 at 0.25, 89.6 at 0.5, 86.9 at 1.0)
 
38
  CONFIG_FILE = "roshei_tevot_config.json"
 
39
 
40
 
41
  class RosheiTevot:
42
  def __init__(self, model, tokenizer, config: dict, index: ExpansionIndex, senses: Optional[dict] = None,
43
- prior_weight: float = DEFAULT_PRIOR_WEIGHT, device: str = "cpu"):
44
  self.model, self.tokenizer, self.index, self.senses = model.to(device).eval(), tokenizer, index, senses or {}
45
  self.pooling = config.get("pooling", "span")
46
  self.scale = float(config["logit_scale"])
47
- self.prior_weight = prior_weight
 
48
  self.device = device
49
  self._embeddings: dict[str, torch.Tensor] = {} # readings the index lacks (citation readings), embedded on demand
50
  self._sense_of: dict[str, dict[str, int]] = {}
51
 
52
  @classmethod
53
- def from_pretrained(cls, path: str, device: str = "cpu", prior_weight: float = DEFAULT_PRIOR_WEIGHT, threads: Optional[int] = None) -> "RosheiTevot":
54
  """`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)."""
55
  from transformers import AutoModel, AutoTokenizer
56
 
@@ -69,7 +74,26 @@ class RosheiTevot:
69
  index = ExpansionIndex.load(str(folder / "index"))
70
  senses_file = folder / "senses.json"
71
  senses = json.loads(senses_file.read_text()) if senses_file.exists() else {}
72
- return cls(model, tokenizer, config, index, senses, prior_weight, device)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
 
74
  # ---- senses -----------------------------------------------------------------------------------------------------------------
75
 
@@ -152,7 +176,8 @@ class RosheiTevot:
152
  queries = self._encode_queries([rows[i] for i, _ in live])
153
  for (i, found), q in zip(live, queries):
154
  texts = list(found)
155
- logits = self.scale * (self._expansion_vectors(texts) @ q) + w * torch.tensor([prior(found[t]) for t in texts])
 
156
  probs = torch.softmax(logits, dim=0).tolist()
157
  results[i] = {"senses": self._describe(rows[i]["surface"], dict(zip(texts, probs)), found), "n_readings": len(texts)}
158
  return results
 
9
  config.json, model.safetensors, tokenizer files, roshei_tevot_config.json the siamese model (`logit_scale`, `pooling`)
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).
 
17
  geresh numerals too), `住注讬祝 拽讟谉 X` for `住拽"X`, the library's most frequent completions of a truncated word (诇讻转讞讬'), and citation readings (`住拽讬"讗`) except for a bare
18
  numeral or a token ending in a geresh (there they would win at p~1 with `拽讬爪讜专` / `住讬诪谉 讬'`).
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
 
36
 
37
  CONTEXT_WORDS = 200
38
  MAX_LENGTH = 512
39
+ DEFAULT_PRIOR_WEIGHT = 0.5 # with train counts. On the evaluation (v5b) top-1 is 94.3 / 95.2 / 95.7 / 95.8 / 95.7 at weight 0 / 0.25 / 0.5 / 1 / 2 (val), but from 1.0 up the minority readings
40
+ # and rare keys lose: val rare-key accuracy 79 / 79 / 79 / 70 / 55, so 0.5 is the knee. The model alone (0) is the right choice with no counts.
41
  CONFIG_FILE = "roshei_tevot_config.json"
42
+ COUNTS_FILE = "train_counts.json"
43
 
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
55
  self._sense_of: dict[str, dict[str, int]] = {}
56
 
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, AutoTokenizer
61
 
 
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).
83
+ Training counts a SENSE through one spelling, so a spelling variant of a counted reading takes the count of its sense class."""
84
+ for bare in [surface] + [b for _, b in parses(surface)]:
85
+ table = self.train_counts.get(bare)
86
+ if table:
87
+ forms = [reading] + [reading[len(p):] for p, b in parses(surface) if b == bare and reading.startswith(p)]
88
+ for form in forms:
89
+ if form in table:
90
+ return table[form]
91
+ for form in forms:
92
+ idx = self._expansion_to_sense(bare).get(form)
93
+ if idx is not None:
94
+ entry = self.senses.get(bare, {}).get(str(idx), {})
95
+ return max((table.get(t, 0) for t in entry.get("expansions", []) + entry.get("texts", [])), default=0)
96
+ return 0
97
 
98
  # ---- senses -----------------------------------------------------------------------------------------------------------------
99
 
 
176
  queries = self._encode_queries([rows[i] for i, _ in live])
177
  for (i, found), q in zip(live, queries):
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
roshei_tevot/vendor/__pycache__/__init__.cpython-39.pyc CHANGED
Binary files a/roshei_tevot/vendor/__pycache__/__init__.cpython-39.pyc and b/roshei_tevot/vendor/__pycache__/__init__.cpython-39.pyc differ
 
roshei_tevot/vendor/__pycache__/checker.cpython-39.pyc CHANGED
Binary files a/roshei_tevot/vendor/__pycache__/checker.cpython-39.pyc and b/roshei_tevot/vendor/__pycache__/checker.cpython-39.pyc differ
 
roshei_tevot/vendor/__pycache__/detect.cpython-39.pyc CHANGED
Binary files a/roshei_tevot/vendor/__pycache__/detect.cpython-39.pyc and b/roshei_tevot/vendor/__pycache__/detect.cpython-39.pyc differ
 
roshei_tevot/vendor/__pycache__/hebrew.cpython-39.pyc CHANGED
Binary files a/roshei_tevot/vendor/__pycache__/hebrew.cpython-39.pyc and b/roshei_tevot/vendor/__pycache__/hebrew.cpython-39.pyc differ
 
roshei_tevot/vendor/__pycache__/numwords.cpython-39.pyc CHANGED
Binary files a/roshei_tevot/vendor/__pycache__/numwords.cpython-39.pyc and b/roshei_tevot/vendor/__pycache__/numwords.cpython-39.pyc differ
 
train_counts.json ADDED
The diff for this file is too large to render. See raw diff