CodeIsAbstract commited on
Commit
b95bd7b
·
verified ·
1 Parent(s): 607f167

Upload decode_v2.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. decode_v2.py +392 -0
decode_v2.py ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ decode_v2.py — Improved decoder for Sanskrit sandhi/samasa vigraha.
3
+
4
+ Fixes the provable decoder bugs found in decode_best.py (non-destructive; this
5
+ file does not modify decode_best.py):
6
+
7
+ 1. Kosha scoring now normalizes terminal H->s/r and M->m, so valid words
8
+ like 'guruH', 'saH', 'manaH', 'aDikAraH' score properly instead of 0.
9
+ 2. Surface-normalization for rejoin checks normalizes M->m and H->s.
10
+ 3. Decoding is a BEAM SEARCH over (words, demodulated-remainder) states:
11
+ - the recursion state is the *demodulated* remainder returned by
12
+ Vidyut's split_at, which correctly handles vowel-absorption
13
+ boundaries (e.g. na + anftaM -> nAnftaM: the 'a' is restored in
14
+ the remainder);
15
+ - candidate boundaries are probability ISLANDS (low threshold, +/-1
16
+ window around peaks), so off-by-one boundary positions are still
17
+ reachable;
18
+ - each expansion verifies rejoin(first, remainder) == surface;
19
+ - the FINAL answer is globally verified: sandhi_join(words) must
20
+ reconstruct the ORIGINAL input, else the best-scoring
21
+ globally-consistent alternative is preferred.
22
+
23
+ Usage:
24
+ python decode_v2.py "vidyAdadAtivinayaMvinayAdyAtipAtratAm"
25
+ python decode_v2.py --test
26
+ """
27
+ from __future__ import annotations
28
+
29
+ import os
30
+ import sys
31
+ import math
32
+ import argparse
33
+ from typing import List, Tuple, Optional
34
+
35
+ os.environ.setdefault("TMPDIR", os.path.join(os.path.dirname(os.path.abspath(__file__)), ".tmp"))
36
+
37
+ import torch
38
+
39
+ import decode_best as DB # reuses predict(), do_sandhi_join(), _splitter, _kosha
40
+
41
+ DELAY = 2
42
+ CAND_TH = 0.30 # any position with prob >= this is a candidate boundary
43
+ PEAK_TH = 0.50 # +/-1 window around positions >= this are candidates
44
+ WINDOW = 1
45
+ BEAM = 8
46
+ MAX_WORDS = 14
47
+ FRAG_PENALTY = 0.8 # per-word penalty favoring natural (fewer) segmentations
48
+
49
+
50
+ # ---------------------------------------------------------------------------
51
+ # Fixed helpers
52
+ # ---------------------------------------------------------------------------
53
+
54
+ def _norm(s: str) -> str:
55
+ """Surface-normalize for equality comparisons: M~m and H~s."""
56
+ return s.replace("M", "m").replace("H", "s")
57
+
58
+
59
+ def safe_join(*arg_words) -> str:
60
+ """do_sandhi_join with a guard: sandhi_parser.join can return None for
61
+ some pairs (e.g. with avagraha). Falls back to plain concatenation."""
62
+ if not arg_words:
63
+ return ""
64
+ join = arg_words[0]
65
+ for word in arg_words[1:]:
66
+ try:
67
+ j = DB._sandhi.join(DB.SanskritImmutableString(join, encoding="slp1"),
68
+ DB.SanskritImmutableString(word, encoding="slp1"))
69
+ join_list = sorted(list(j)) if j is not None else []
70
+ except Exception:
71
+ join_list = []
72
+ filtered = [o for o in join_list if o != (join + word)]
73
+ if len(filtered):
74
+ join = filtered[0]
75
+ elif join_list:
76
+ join = join_list[0]
77
+ else:
78
+ join = join + word
79
+ return join.replace(" ", "")
80
+
81
+
82
+ def join_variants(*words, cap: int = 12) -> List[str]:
83
+ """All sandhi-join variants of a word sequence (each pair can have
84
+ several surface realisations; sorted() in do_sandhi_join picks just one
85
+ arbitrarily, which may not equal the actual surface)."""
86
+ if not words:
87
+ return [""]
88
+ variants = [words[0]]
89
+ for word in words[1:]:
90
+ nv = []
91
+ for j in variants:
92
+ try:
93
+ jl = DB._sandhi.join(DB.SanskritImmutableString(j, encoding="slp1"),
94
+ DB.SanskritImmutableString(word, encoding="slp1"))
95
+ except Exception:
96
+ jl = None
97
+ if jl:
98
+ nv.extend(o.replace(" ", "") for o in jl)
99
+ else:
100
+ nv.append(j + word)
101
+ variants = list(dict.fromkeys(nv))[:cap]
102
+ return variants
103
+
104
+
105
+ def rejoins(surface: str, *words) -> bool:
106
+ """True if SOME sandhi-join variant of words reconstructs `surface`
107
+ (normalized). Unlike do_sandhi_join, this is not fooled by the
108
+ arbitrary sorted()-variant selection (e.g. guruH vs gurur)."""
109
+ if not words:
110
+ return False
111
+ s = _norm(surface)
112
+ return any(_norm(v) == s for v in join_variants(*words))
113
+
114
+
115
+ def kosha_variants(word: str):
116
+ vs = {word}
117
+ if word.endswith("H"):
118
+ vs.add(word[:-1] + "s")
119
+ vs.add(word[:-1] + "r")
120
+ if word.endswith("M"):
121
+ vs.add(word[:-1] + "m")
122
+ if word.endswith("m"):
123
+ vs.add(word[:-1] + "M")
124
+ if word.endswith("s"):
125
+ vs.add(word[:-1] + "H")
126
+ vs.add(word[:-1] + "r")
127
+ if word.endswith("r"):
128
+ vs.add(word[:-1] + "s")
129
+ vs.add(word[:-1] + "H")
130
+ return vs
131
+
132
+
133
+ def word_score(word: str) -> float:
134
+ """Fixed kosha score: 1.0 pada / 0.5 stem / 0.0 non-word, with H/M
135
+ normalization so 'guruH', 'manaH', 'saH', 'anftaM' validate correctly."""
136
+ if not word or len(word) < 2:
137
+ return 0.0
138
+ if word in DB.SAFE_PREFIX_CANDIDATES:
139
+ return 1.0
140
+ for v in kosha_variants(word):
141
+ entries = DB._kosha.get(v)
142
+ if entries:
143
+ from vidyut.kosha import PadaEntry
144
+ if any(isinstance(e, PadaEntry) for e in entries):
145
+ return 1.0
146
+ return 0.5
147
+ return 0.0
148
+
149
+
150
+ def word_prior(word: str) -> float:
151
+ """Ranking bonus for a candidate word (pada > stem > junk)."""
152
+ ws = word_score(word)
153
+ if ws >= 1.0:
154
+ return 1.2
155
+ if ws >= 0.5:
156
+ return 0.3
157
+ return -3.0
158
+
159
+
160
+ # ---------------------------------------------------------------------------
161
+ # Candidate generation
162
+ # ---------------------------------------------------------------------------
163
+
164
+ def island_positions(probs, n: int, cand_th: float = CAND_TH,
165
+ peak_th: float = PEAK_TH) -> List[int]:
166
+ """Boundary candidates: all positions with prob >= cand_th, plus +/-1
167
+ around any position with prob >= peak_th."""
168
+ pos = set()
169
+ for i in range(n):
170
+ p = probs[i].item()
171
+ if p >= cand_th:
172
+ pos.add(i)
173
+ if p >= peak_th:
174
+ for d in range(1, WINDOW + 1):
175
+ if i - d >= 0:
176
+ pos.add(i - d)
177
+ if i + d < n:
178
+ pos.add(i + d)
179
+ return sorted(pos)
180
+
181
+
182
+ def split_candidates(surface: str, idx: int) -> List[Tuple[str, str]]:
183
+ """Grammar-valid (first, remainder) splits of `surface` at boundary idx
184
+ (idx = index of the last char of the first word). The demodulated
185
+ remainder is returned so vowel-absorption boundaries stay aligned."""
186
+ out = []
187
+ if idx < 0 or idx >= len(surface):
188
+ return out
189
+ try:
190
+ splits = DB._splitter.split_at(surface, idx)
191
+ except Exception:
192
+ splits = []
193
+ seen = set()
194
+ for s in splits:
195
+ f, sec = s.first, s.second
196
+ if not f or not sec:
197
+ continue
198
+ if (f, sec) in seen:
199
+ continue
200
+ seen.add((f, sec))
201
+ if rejoins(surface, f, sec):
202
+ out.append((f, sec))
203
+ return out
204
+
205
+
206
+ # ---------------------------------------------------------------------------
207
+ # Beam search
208
+ # ---------------------------------------------------------------------------
209
+
210
+ def decode(model, text: str, beam_size: int = BEAM, cand_th: float = CAND_TH,
211
+ max_words: int = MAX_WORDS, delay: int = DELAY):
212
+ """Return (words, score, verified) — verified=True iff the words rejoin
213
+ to the original input. Never raises; never drops the input silently."""
214
+ if not text:
215
+ return [], 0.0, False
216
+
217
+ def logit(p: float) -> float:
218
+ p = max(min(p, 1 - 1e-5), 1e-5)
219
+ return math.log(p / (1 - p))
220
+
221
+ beam = [([], text, 0.0)] # (words, remaining_surface, score)
222
+ complete = []
223
+
224
+ for step in range(max_words):
225
+ if not beam:
226
+ break
227
+ nxt = []
228
+ for words, remaining, score in beam:
229
+ if not remaining:
230
+ complete.append((words, score))
231
+ continue
232
+ rprobs = DB.predict(model, remaining, delay=delay)
233
+ cands = island_positions(rprobs, len(remaining), cand_th)
234
+ expanded = False
235
+ for k in cands:
236
+ for f, sec in split_candidates(remaining, k):
237
+ wsc = word_score(f)
238
+ if wsc <= 0:
239
+ continue
240
+ sc = (score
241
+ + logit(rprobs[k].item())
242
+ + word_prior(f)
243
+ - FRAG_PENALTY)
244
+ nxt.append((words + [f], sec, sc))
245
+ expanded = True
246
+ if not expanded and len(words) + 1 < max_words:
247
+ # dead end: try completing the whole remainder as one word
248
+ wsc = word_score(remaining)
249
+ if wsc > 0:
250
+ nxt.append((words + [remaining], "",
251
+ score + word_prior(remaining) - FRAG_PENALTY))
252
+ # dedupe by (words, remaining) keeping best score
253
+ best = {}
254
+ for words, remaining, score in nxt:
255
+ key = (tuple(words), remaining)
256
+ if key not in best or score > best[key][0]:
257
+ best[key] = (score, words)
258
+ # deterministic ordering: score desc, then key asc (tie-breaking must
259
+ # not depend on dict insertion order, which varies with hash seed)
260
+ beam = []
261
+ for (wkey, rem) in sorted(best.keys(), key=lambda k: (-best[k][0], k)):
262
+ beam.append((list(best[(wkey, rem)][1]), rem, best[(wkey, rem)][0]))
263
+ beam = beam[:beam_size]
264
+ # keep anything that completed
265
+ complete = sorted(complete, key=lambda x: (-x[1], x[0]))
266
+
267
+ # also allow the beam itself to hold completed states
268
+ for words, remaining, score in beam:
269
+ if not remaining:
270
+ complete.append((words, score))
271
+ complete = sorted(set((tuple(w), s) for w, s in complete),
272
+ key=lambda x: (-x[1], x[0]))
273
+
274
+ # Global verification: SOME join of the words must reconstruct the input
275
+ verified_list = []
276
+ for words, score in complete:
277
+ if not words:
278
+ continue
279
+ if rejoins(text, *words):
280
+ verified_list.append((words, score, True))
281
+ if verified_list:
282
+ words, score, _ = max(verified_list, key=lambda x: (x[1], x[0]))
283
+ return list(words), score, True
284
+
285
+ # Fallback: best-scoring complete segmentation (flag as unverified)
286
+ if complete:
287
+ words, score = complete[0]
288
+ return list(words), score, False
289
+
290
+ # Total failure: return the input as a single token rather than dropping it
291
+ return [text], -1e9, False
292
+
293
+
294
+ def decode_wrap(model, text: str, **kw) -> List[str]:
295
+ """Handle '~' split markers like decode_best.wrap_complex_string_handler,
296
+ then decode each chunk and concatenate."""
297
+ inputs = []
298
+ t = text
299
+ while "~" in t:
300
+ try:
301
+ splits = list(DB._sandhi.split_at(DB.SanskritImmutableString(t), t.index("~") - 1))
302
+ except Exception:
303
+ splits = []
304
+ for s in splits:
305
+ if t == safe_join(*s):
306
+ inputs.append(s[0])
307
+ t = s[1]
308
+ break
309
+ else:
310
+ inputs.append(t)
311
+ t = ""
312
+ if t:
313
+ inputs.append(t)
314
+ result = []
315
+ for chunk in inputs:
316
+ words, score, verified = decode(model, chunk, **kw)
317
+ result.extend(words)
318
+ return result
319
+
320
+
321
+ # ---------------------------------------------------------------------------
322
+ # CLI
323
+ # ---------------------------------------------------------------------------
324
+
325
+ TEST_CASES = [
326
+ ("vidyAdadAtivinayaMvinayAdyAtipAtratAm",
327
+ ["vidyA", "dadAti", "vinayam", "vinayAt", "yAti", "pAtratAm"]),
328
+ ("satyamevajayatenAnftaM",
329
+ ["satyam", "eva", "jayate", "na", "anftam"]),
330
+ ("gururbrahmAgururviSfuH",
331
+ ["guruH", "brahmA", "guruH", "viSfuH"]),
332
+ ("hitopadeSaHsurocanasya",
333
+ ["hita", "upadeSaH", "surocanasya"]),
334
+ ("sarvaDarmAnparityajyamAmekaMSaraRaMvraja",
335
+ ["sarva", "DarmAn", "parityajya", "mAm", "ekam", "SaraRam", "vraja"]),
336
+ ("tacCrutvAvacanamapuRyam",
337
+ ["tat", "SrutvA", "vacanam", "apuRyam"]),
338
+ ("so'vadatkimatra",
339
+ ["saH", "avadat", "kim", "atra"]),
340
+ ("ityuktvAkamalApatirantardaqe",
341
+ ["iti", "uktvA", "kamalApatiH", "antaH", "daqe"]),
342
+ ("etatmamamano'BirAmam",
343
+ ["etat", "mama", "manaH", "aBirAmam"]),
344
+ ("karmARyevADikArastemAphalezukadAcana",
345
+ ["karmaRi", "eva", "aDikAraH", "te", "mA", "phalezu", "kadAcana"]),
346
+ ]
347
+
348
+
349
+ def main():
350
+ parser = argparse.ArgumentParser(description="decode_v2: beam-search vigraha decoder")
351
+ parser.add_argument("text", nargs="?", default=None)
352
+ parser.add_argument("--test", action="store_true", help="run the 10 test cases")
353
+ parser.add_argument("--checkpoint", default="checkpoints/delayed_model_save_fixed_delay2_v2")
354
+ parser.add_argument("--beam", type=int, default=BEAM)
355
+ parser.add_argument("--cand-th", type=float, default=CAND_TH)
356
+ args = parser.parse_args()
357
+
358
+ device = torch.device("mps" if torch.backends.mps.is_available() else "cpu")
359
+ print(f"Device: {device}", file=sys.stderr)
360
+ model, delay = DB.load_model(args.checkpoint, device)
361
+ print(f"Loaded model (delay={delay})", file=sys.stderr)
362
+
363
+ if args.text:
364
+ raw = args.text
365
+ text = DB.give_correct_slp1_input(raw) if raw and any(ord(c) > 127 for c in raw) else raw.replace(" ", "")
366
+ res = decode_wrap(model, text, beam_size=args.beam, cand_th=args.cand_th)
367
+ print(f"{raw} => {res}")
368
+ return
369
+
370
+ if args.test:
371
+ exact = 0
372
+ norm_exact = 0
373
+ print(f"{'input':40s} {'exact':6s} {'norm':6s} {'rejoin':7s} decoded")
374
+ for inp, exp in TEST_CASES:
375
+ res = decode_wrap(model, inp, beam_size=args.beam, cand_th=args.cand_th)
376
+ ok = res == exp
377
+ nok = (len(res) == len(exp) and
378
+ all(_norm(a) == _norm(b) or
379
+ (a[:-1] == b[:-1] and a[-1:] in "Hsr" and b[-1:] in "Hsr")
380
+ for a, b in zip(res, exp)))
381
+ rejoined = safe_join(*res) if res else ""
382
+ rej = rejoins(inp, *res) if res else False
383
+ if ok:
384
+ exact += 1
385
+ if nok:
386
+ norm_exact += 1
387
+ print(f"{inp[:39]:40s} {str(ok):6s} {str(nok):6s} {str(rej):7s} {' + '.join(res)}")
388
+ print(f"\nExact: {exact}/{len(TEST_CASES)} (normalized: {norm_exact}/{len(TEST_CASES)})")
389
+ return
390
+
391
+ if __name__ == "__main__":
392
+ main()