shmulc commited on
Commit
e929009
ยท
verified ยท
1 Parent(s): 07abc97

Update probe.py, exp_encoders.py, data/numberbatch_he.npy, data/numberbatch_he_vocab.json

Browse files
data/numberbatch_he.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c245273f3d045e6320da4d3df68041c10b08697c45b50dc3a862dc0392b355c9
3
+ size 23467328
data/numberbatch_he_vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
exp_encoders.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Experimental encoders that are intentionally separate from the serving path.
2
+
3
+ ``NumberbatchEncoder`` has a fixed vocabulary: it never uses a subword or
4
+ semantic fallback. Lookup tries, in this exact order: (1) the supplied surface
5
+ form, (2) that form with one leading Hebrew servile prefix removed when it
6
+ starts with one of ื”, ื•, ื‘, ื›, ืœ, ืž, ืฉ, and (3) underscores/spaces exchanged
7
+ for the exact and prefix-stripped forms, in that order. An unresolved word is
8
+ represented by an all-NaN row so experiment code can explicitly exclude it as
9
+ OOV.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import json
16
+ from pathlib import Path
17
+
18
+ import numpy as np
19
+
20
+
21
+ DATA = Path(__file__).resolve().parent / "data"
22
+ SERVILE_PREFIXES = frozenset("ื”ื•ื‘ื›ืœืžืฉ")
23
+
24
+
25
+ class NumberbatchEncoder:
26
+ """Fixed-vocabulary Hebrew ConceptNet Numberbatch 19.08 vectors."""
27
+
28
+ def __init__(self) -> None:
29
+ self.model_id = "conceptnet-numberbatch-he-19.08"
30
+ with (DATA / "numberbatch_he_vocab.json").open(encoding="utf-8") as source:
31
+ self.vocab = json.load(source)
32
+ self.vectors = np.load(DATA / "numberbatch_he.npy", mmap_mode="r")
33
+ if self.vectors.ndim != 2 or self.vectors.dtype != np.float32:
34
+ raise ValueError("Numberbatch vectors must be a 2-D float32 array")
35
+ if len(self.vocab) != self.vectors.shape[0]:
36
+ raise ValueError("Numberbatch vocabulary and vector rows are misaligned")
37
+ if len(set(self.vocab)) != len(self.vocab):
38
+ raise ValueError("Numberbatch vocabulary contains duplicate surface terms")
39
+ self.word_to_row = {word: row for row, word in enumerate(self.vocab)}
40
+
41
+ @property
42
+ def dim(self) -> int:
43
+ return int(self.vectors.shape[1])
44
+
45
+ def _candidates(self, word: str):
46
+ """Yield documented, trivial lookup variants once each."""
47
+ base = [word]
48
+ if word and word[0] in SERVILE_PREFIXES:
49
+ base.append(word[1:])
50
+ seen: set[str] = set()
51
+ # Exact surface form, then one prefix-stripped form.
52
+ for candidate in base:
53
+ if candidate not in seen:
54
+ seen.add(candidate)
55
+ yield candidate
56
+ # Finally try only the two trivial multiword spelling exchanges.
57
+ for candidate in base:
58
+ for variant in (candidate.replace("_", " "), candidate.replace(" ", "_")):
59
+ if variant not in seen:
60
+ seen.add(variant)
61
+ yield variant
62
+
63
+ def _row_for(self, word: str) -> int | None:
64
+ for candidate in self._candidates(word):
65
+ row = self.word_to_row.get(candidate)
66
+ if row is not None:
67
+ return row
68
+ return None
69
+
70
+ def embed(self, words) -> np.ndarray:
71
+ words = list(words)
72
+ result = np.full((len(words), self.dim), np.nan, dtype=np.float32)
73
+ for output_row, word in enumerate(words):
74
+ row = self._row_for(word)
75
+ if row is not None:
76
+ result[output_row] = self.vectors[row]
77
+ elif len(words) < 100:
78
+ result[output_row] = 0.0
79
+ return result
80
+
81
+
82
+ class BlendEncoder:
83
+ """Concatenated L2-normalized blend of fastText and Numberbatch."""
84
+
85
+ def __init__(self, w_ft: float, w_nb: float) -> None:
86
+ self.model_id = f"blend_ft_{w_ft}_nb_{w_nb}"
87
+ from probe import make_encoder
88
+ self.ft = make_encoder("fasttext")
89
+ self.nb = NumberbatchEncoder()
90
+ self.w_ft = w_ft
91
+ self.w_nb = w_nb
92
+
93
+ def embed(self, words) -> np.ndarray:
94
+ words = list(words)
95
+ V_ft = self.ft.embed(words)
96
+ V_nb = self.nb.embed(words)
97
+ V_nb_clean = np.nan_to_num(V_nb, nan=0.0)
98
+ V_blend = np.concatenate([self.w_ft * V_ft, self.w_nb * V_nb_clean], axis=-1)
99
+ norms = np.linalg.norm(V_blend, axis=1, keepdims=True)
100
+ V_blend /= (norms + 1e-9)
101
+ return V_blend
102
+
103
+
104
+ def make_exp_encoder(key: str):
105
+ """Return the experimental Numberbatch encoder, a BlendEncoder, or a registered probe encoder."""
106
+ if key == "numberbatch":
107
+ return NumberbatchEncoder()
108
+ if key.startswith("blend_"):
109
+ parts = key.split("_")
110
+ if len(parts) == 3:
111
+ w_ft = float(parts[1])
112
+ w_nb = float(parts[2])
113
+ return BlendEncoder(w_ft, w_nb)
114
+ from probe import make_encoder
115
+
116
+ return make_encoder(key)
117
+
118
+
119
+ def _selftest() -> None:
120
+ encoder = NumberbatchEncoder()
121
+ words = ["ืžืœืš", "ืฉื•ืœื—ืŸ", "ื ื”ืจ", "ืคืจื•ื™ื“"]
122
+ vectors = encoder.embed(words)
123
+ cosines = vectors @ vectors.T
124
+ print(f"model_id={encoder.model_id}")
125
+ print(f"dim={encoder.dim} N={len(encoder.vocab)}")
126
+ print("pairwise_cosines")
127
+ print(" " + " ".join(f"{word:>8}" for word in words))
128
+ for word, row in zip(words, cosines):
129
+ print(f"{word:>6} " + " ".join(f"{value:8.4f}" for value in row))
130
+ oov = encoder.embed(["ื–ื–ื–ื–ื–ื–ื–"])[0]
131
+ print(f"oov_all_nan={bool(np.isnan(oov).all())}")
132
+ if not np.isnan(oov).all():
133
+ raise SystemExit("OOV handling failed")
134
+
135
+
136
+ if __name__ == "__main__":
137
+ parser = argparse.ArgumentParser()
138
+ parser.add_argument("--selftest", action="store_true")
139
+ args = parser.parse_args()
140
+ if args.selftest:
141
+ _selftest()
142
+ else:
143
+ parser.print_help()
probe.py CHANGED
@@ -47,6 +47,9 @@ ENCODERS = {
47
  # (morphology/OOV); often competitive with contextual encoders for bare-word
48
  # association. Handles OOV via subwords.
49
  "fasttext": dict(kind="fasttext", path=os.path.join(DATA, "cc.he.300.bin")),
 
 
 
50
  # Hebrew-native, newest Dicta encoder (needs transformers<5).
51
  "neodictabert": dict(kind="st", model_id="dicta-il/neodictabert-bilingual-embed"),
52
  # 2025 multilingual SOTA-small.
@@ -153,6 +156,9 @@ class CompressedFastTextEncoder:
153
 
154
 
155
  def make_encoder(key: str):
 
 
 
156
  cfg = ENCODERS[key]
157
  if cfg["kind"] == "fasttext":
158
  # Deploy uses the compressed model when FASTTEXT_COMPRESSED points at one; local dev
@@ -369,13 +375,14 @@ def cohesion_keep(enc, words, floor: float = 0.24, pin=frozenset(), mode: str =
369
 
370
 
371
  def served_count(read, keep_rel: float = 0.66, pin=frozenset(),
372
- enc=None, cohesion_floor: float | None = None, cohesion_mode: str = "any"):
 
373
  """The words a clue should *claim* and light up, from a board reading.
374
 
375
  `read` = list of {word, role, sim} ordered by sim desc (an encoder's reading of the clue).
376
  Two stages:
377
  1. Walk the *safe run* (team words reached before any enemy word) and keep each next word
378
- while it stays strong: above `keep_rel`ร— the top target AND no sharp cliff (< 0.5ร— the
379
  previous kept word). A pinned word is always kept. This adapts the count to how many
380
  words are genuinely clustered โ€” a tight trio stays 3, "1 strong + noise tail" shrinks.
381
  2. Cohesion trim (when `enc` + `cohesion_floor` given): drop any kept word that doesn't
@@ -397,7 +404,7 @@ def served_count(read, keep_rel: float = 0.66, pin=frozenset(),
397
  s = simmap[w]
398
  if w in pin:
399
  kept.append(w); prev = s; continue
400
- if s < top * keep_rel or s < prev * 0.5:
401
  break
402
  kept.append(w); prev = s
403
  if enc is not None and cohesion_floor is not None and len(kept) > 1:
@@ -442,7 +449,14 @@ def encoder_spymaster(enc, board: Board, clue_vocab, clue_emb=None, vocab_lemmas
442
  return np.clip(adj[:, mask].max(1), 0, None) if mask.any() else np.zeros(len(cand))
443
 
444
  adj_my = adj[:, is_my]
445
- top_my = np.sort(adj_my, axis=1)[:, ::-1][:, :m].sum(1)
 
 
 
 
 
 
 
446
  g = top_my - lam_a * tier_max(is_as) - lam_opp * tier_max(is_opp) - lam_neu * tier_max(is_neu)
447
  if vocab_freq is not None and lam_f:
448
  g = g + lam_f * np.asarray(vocab_freq, dtype=np.float32)[keep]
@@ -483,8 +497,19 @@ def encoder_clue_candidates(enc, board: Board, clue_vocab, clue_emb=None, vocab_
483
  safe = adj_my > (enemy_ceiling[:, None] + safe_margin) # beats every enemy word by margin
484
  if fixed:
485
  g_team = adj_my.sum(1) # honour the user's chosen targets
486
- else: # sum of the top-m *safe* team words
487
- g_team = np.sort(np.where(safe, adj_my, 0.0), 1)[:, ::-1][:, :m].sum(1)
 
 
 
 
 
 
 
 
 
 
 
488
  g = g_team - lam_a * tmax(is_as) - lam_opp * tmax(is_opp) - lam_neu * tmax(is_neu)
489
  if vocab_freq is not None and lam_f:
490
  g = g + lam_f * np.asarray(vocab_freq, dtype=np.float32)[keep]
 
47
  # (morphology/OOV); often competitive with contextual encoders for bare-word
48
  # association. Handles OOV via subwords.
49
  "fasttext": dict(kind="fasttext", path=os.path.join(DATA, "cc.he.300.bin")),
50
+ # Concatenated L2-normalized blend of fastText and ConceptNet Numberbatch.
51
+ "blend_0.5_0.5": dict(kind="blend", w_ft=0.5, w_nb=0.5),
52
+ "blend_0.7_0.3": dict(kind="blend", w_ft=0.7, w_nb=0.3),
53
  # Hebrew-native, newest Dicta encoder (needs transformers<5).
54
  "neodictabert": dict(kind="st", model_id="dicta-il/neodictabert-bilingual-embed"),
55
  # 2025 multilingual SOTA-small.
 
156
 
157
 
158
  def make_encoder(key: str):
159
+ if key == "numberbatch" or key.startswith("blend_"):
160
+ from exp_encoders import make_exp_encoder
161
+ return make_exp_encoder(key)
162
  cfg = ENCODERS[key]
163
  if cfg["kind"] == "fasttext":
164
  # Deploy uses the compressed model when FASTTEXT_COMPRESSED points at one; local dev
 
375
 
376
 
377
  def served_count(read, keep_rel: float = 0.66, pin=frozenset(),
378
+ enc=None, cohesion_floor: float | None = None, cohesion_mode: str = "any",
379
+ cliff: float = 0.5):
380
  """The words a clue should *claim* and light up, from a board reading.
381
 
382
  `read` = list of {word, role, sim} ordered by sim desc (an encoder's reading of the clue).
383
  Two stages:
384
  1. Walk the *safe run* (team words reached before any enemy word) and keep each next word
385
+ while it stays strong: above `keep_rel`ร— the top target AND no sharp cliff (< cliffร— the
386
  previous kept word). A pinned word is always kept. This adapts the count to how many
387
  words are genuinely clustered โ€” a tight trio stays 3, "1 strong + noise tail" shrinks.
388
  2. Cohesion trim (when `enc` + `cohesion_floor` given): drop any kept word that doesn't
 
404
  s = simmap[w]
405
  if w in pin:
406
  kept.append(w); prev = s; continue
407
+ if s < top * keep_rel or s < prev * cliff:
408
  break
409
  kept.append(w); prev = s
410
  if enc is not None and cohesion_floor is not None and len(kept) > 1:
 
449
  return np.clip(adj[:, mask].max(1), 0, None) if mask.any() else np.zeros(len(cand))
450
 
451
  adj_my = adj[:, is_my]
452
+ m = min(m, adj_my.shape[1])
453
+ sorted_my = np.sort(adj_my, axis=1)[:, ::-1]
454
+ if m >= 2:
455
+ top_my = sorted_my[:, :m].mean(1) + 1.0 * sorted_my[:, m - 1]
456
+ elif m == 1:
457
+ top_my = sorted_my[:, 0]
458
+ else:
459
+ top_my = np.full(len(cand), -99.0, dtype=np.float32)
460
  g = top_my - lam_a * tier_max(is_as) - lam_opp * tier_max(is_opp) - lam_neu * tier_max(is_neu)
461
  if vocab_freq is not None and lam_f:
462
  g = g + lam_f * np.asarray(vocab_freq, dtype=np.float32)[keep]
 
497
  safe = adj_my > (enemy_ceiling[:, None] + safe_margin) # beats every enemy word by margin
498
  if fixed:
499
  g_team = adj_my.sum(1) # honour the user's chosen targets
500
+ else: # mean + minimum of the top-k *safe* team words (k <= m)
501
+ safe_counts = safe.sum(1)
502
+ sorted_safe = np.sort(np.where(safe, adj_my, -9.0), 1)[:, ::-1]
503
+ g_team = np.zeros(len(cand), dtype=np.float32)
504
+ for k_val in range(1, m + 1):
505
+ mask = (safe_counts == k_val) if k_val < m else (safe_counts >= k_val)
506
+ if not mask.any():
507
+ continue
508
+ if k_val >= 2:
509
+ g_team[mask] = sorted_safe[mask, :k_val].mean(1) + 1.0 * sorted_safe[mask, k_val - 1]
510
+ else:
511
+ g_team[mask] = sorted_safe[mask, 0] - 0.5
512
+ g_team[safe_counts == 0] = -99.0
513
  g = g_team - lam_a * tmax(is_as) - lam_opp * tmax(is_opp) - lam_neu * tmax(is_neu)
514
  if vocab_freq is not None and lam_f:
515
  g = g + lam_f * np.asarray(vocab_freq, dtype=np.float32)[keep]