CodeIsAbstract's picture
Upload decode_v2.py with huggingface_hub
b95bd7b verified
Raw History Blame Contribute Delete
14.5 kB
"""
decode_v2.py — Improved decoder for Sanskrit sandhi/samasa vigraha.
Fixes the provable decoder bugs found in decode_best.py (non-destructive; this
file does not modify decode_best.py):
1. Kosha scoring now normalizes terminal H->s/r and M->m, so valid words
like 'guruH', 'saH', 'manaH', 'aDikAraH' score properly instead of 0.
2. Surface-normalization for rejoin checks normalizes M->m and H->s.
3. Decoding is a BEAM SEARCH over (words, demodulated-remainder) states:
- the recursion state is the *demodulated* remainder returned by
Vidyut's split_at, which correctly handles vowel-absorption
boundaries (e.g. na + anftaM -> nAnftaM: the 'a' is restored in
the remainder);
- candidate boundaries are probability ISLANDS (low threshold, +/-1
window around peaks), so off-by-one boundary positions are still
reachable;
- each expansion verifies rejoin(first, remainder) == surface;
- the FINAL answer is globally verified: sandhi_join(words) must
reconstruct the ORIGINAL input, else the best-scoring
globally-consistent alternative is preferred.
Usage:
python decode_v2.py "vidyAdadAtivinayaMvinayAdyAtipAtratAm"
python decode_v2.py --test
"""
from __future__ import annotations
import os
import sys
import math
import argparse
from typing import List, Tuple, Optional
os.environ.setdefault("TMPDIR", os.path.join(os.path.dirname(os.path.abspath(__file__)), ".tmp"))
import torch
import decode_best as DB # reuses predict(), do_sandhi_join(), _splitter, _kosha
DELAY = 2
CAND_TH = 0.30 # any position with prob >= this is a candidate boundary
PEAK_TH = 0.50 # +/-1 window around positions >= this are candidates
WINDOW = 1
BEAM = 8
MAX_WORDS = 14
FRAG_PENALTY = 0.8 # per-word penalty favoring natural (fewer) segmentations
# ---------------------------------------------------------------------------
# Fixed helpers
# ---------------------------------------------------------------------------
def _norm(s: str) -> str:
"""Surface-normalize for equality comparisons: M~m and H~s."""
return s.replace("M", "m").replace("H", "s")
def safe_join(*arg_words) -> str:
"""do_sandhi_join with a guard: sandhi_parser.join can return None for
some pairs (e.g. with avagraha). Falls back to plain concatenation."""
if not arg_words:
return ""
join = arg_words[0]
for word in arg_words[1:]:
try:
j = DB._sandhi.join(DB.SanskritImmutableString(join, encoding="slp1"),
DB.SanskritImmutableString(word, encoding="slp1"))
join_list = sorted(list(j)) if j is not None else []
except Exception:
join_list = []
filtered = [o for o in join_list if o != (join + word)]
if len(filtered):
join = filtered[0]
elif join_list:
join = join_list[0]
else:
join = join + word
return join.replace(" ", "")
def join_variants(*words, cap: int = 12) -> List[str]:
"""All sandhi-join variants of a word sequence (each pair can have
several surface realisations; sorted() in do_sandhi_join picks just one
arbitrarily, which may not equal the actual surface)."""
if not words:
return [""]
variants = [words[0]]
for word in words[1:]:
nv = []
for j in variants:
try:
jl = DB._sandhi.join(DB.SanskritImmutableString(j, encoding="slp1"),
DB.SanskritImmutableString(word, encoding="slp1"))
except Exception:
jl = None
if jl:
nv.extend(o.replace(" ", "") for o in jl)
else:
nv.append(j + word)
variants = list(dict.fromkeys(nv))[:cap]
return variants
def rejoins(surface: str, *words) -> bool:
"""True if SOME sandhi-join variant of words reconstructs `surface`
(normalized). Unlike do_sandhi_join, this is not fooled by the
arbitrary sorted()-variant selection (e.g. guruH vs gurur)."""
if not words:
return False
s = _norm(surface)
return any(_norm(v) == s for v in join_variants(*words))
def kosha_variants(word: str):
vs = {word}
if word.endswith("H"):
vs.add(word[:-1] + "s")
vs.add(word[:-1] + "r")
if word.endswith("M"):
vs.add(word[:-1] + "m")
if word.endswith("m"):
vs.add(word[:-1] + "M")
if word.endswith("s"):
vs.add(word[:-1] + "H")
vs.add(word[:-1] + "r")
if word.endswith("r"):
vs.add(word[:-1] + "s")
vs.add(word[:-1] + "H")
return vs
def word_score(word: str) -> float:
"""Fixed kosha score: 1.0 pada / 0.5 stem / 0.0 non-word, with H/M
normalization so 'guruH', 'manaH', 'saH', 'anftaM' validate correctly."""
if not word or len(word) < 2:
return 0.0
if word in DB.SAFE_PREFIX_CANDIDATES:
return 1.0
for v in kosha_variants(word):
entries = DB._kosha.get(v)
if entries:
from vidyut.kosha import PadaEntry
if any(isinstance(e, PadaEntry) for e in entries):
return 1.0
return 0.5
return 0.0
def word_prior(word: str) -> float:
"""Ranking bonus for a candidate word (pada > stem > junk)."""
ws = word_score(word)
if ws >= 1.0:
return 1.2
if ws >= 0.5:
return 0.3
return -3.0
# ---------------------------------------------------------------------------
# Candidate generation
# ---------------------------------------------------------------------------
def island_positions(probs, n: int, cand_th: float = CAND_TH,
peak_th: float = PEAK_TH) -> List[int]:
"""Boundary candidates: all positions with prob >= cand_th, plus +/-1
around any position with prob >= peak_th."""
pos = set()
for i in range(n):
p = probs[i].item()
if p >= cand_th:
pos.add(i)
if p >= peak_th:
for d in range(1, WINDOW + 1):
if i - d >= 0:
pos.add(i - d)
if i + d < n:
pos.add(i + d)
return sorted(pos)
def split_candidates(surface: str, idx: int) -> List[Tuple[str, str]]:
"""Grammar-valid (first, remainder) splits of `surface` at boundary idx
(idx = index of the last char of the first word). The demodulated
remainder is returned so vowel-absorption boundaries stay aligned."""
out = []
if idx < 0 or idx >= len(surface):
return out
try:
splits = DB._splitter.split_at(surface, idx)
except Exception:
splits = []
seen = set()
for s in splits:
f, sec = s.first, s.second
if not f or not sec:
continue
if (f, sec) in seen:
continue
seen.add((f, sec))
if rejoins(surface, f, sec):
out.append((f, sec))
return out
# ---------------------------------------------------------------------------
# Beam search
# ---------------------------------------------------------------------------
def decode(model, text: str, beam_size: int = BEAM, cand_th: float = CAND_TH,
max_words: int = MAX_WORDS, delay: int = DELAY):
"""Return (words, score, verified) — verified=True iff the words rejoin
to the original input. Never raises; never drops the input silently."""
if not text:
return [], 0.0, False
def logit(p: float) -> float:
p = max(min(p, 1 - 1e-5), 1e-5)
return math.log(p / (1 - p))
beam = [([], text, 0.0)] # (words, remaining_surface, score)
complete = []
for step in range(max_words):
if not beam:
break
nxt = []
for words, remaining, score in beam:
if not remaining:
complete.append((words, score))
continue
rprobs = DB.predict(model, remaining, delay=delay)
cands = island_positions(rprobs, len(remaining), cand_th)
expanded = False
for k in cands:
for f, sec in split_candidates(remaining, k):
wsc = word_score(f)
if wsc <= 0:
continue
sc = (score
+ logit(rprobs[k].item())
+ word_prior(f)
- FRAG_PENALTY)
nxt.append((words + [f], sec, sc))
expanded = True
if not expanded and len(words) + 1 < max_words:
# dead end: try completing the whole remainder as one word
wsc = word_score(remaining)
if wsc > 0:
nxt.append((words + [remaining], "",
score + word_prior(remaining) - FRAG_PENALTY))
# dedupe by (words, remaining) keeping best score
best = {}
for words, remaining, score in nxt:
key = (tuple(words), remaining)
if key not in best or score > best[key][0]:
best[key] = (score, words)
# deterministic ordering: score desc, then key asc (tie-breaking must
# not depend on dict insertion order, which varies with hash seed)
beam = []
for (wkey, rem) in sorted(best.keys(), key=lambda k: (-best[k][0], k)):
beam.append((list(best[(wkey, rem)][1]), rem, best[(wkey, rem)][0]))
beam = beam[:beam_size]
# keep anything that completed
complete = sorted(complete, key=lambda x: (-x[1], x[0]))
# also allow the beam itself to hold completed states
for words, remaining, score in beam:
if not remaining:
complete.append((words, score))
complete = sorted(set((tuple(w), s) for w, s in complete),
key=lambda x: (-x[1], x[0]))
# Global verification: SOME join of the words must reconstruct the input
verified_list = []
for words, score in complete:
if not words:
continue
if rejoins(text, *words):
verified_list.append((words, score, True))
if verified_list:
words, score, _ = max(verified_list, key=lambda x: (x[1], x[0]))
return list(words), score, True
# Fallback: best-scoring complete segmentation (flag as unverified)
if complete:
words, score = complete[0]
return list(words), score, False
# Total failure: return the input as a single token rather than dropping it
return [text], -1e9, False
def decode_wrap(model, text: str, **kw) -> List[str]:
"""Handle '~' split markers like decode_best.wrap_complex_string_handler,
then decode each chunk and concatenate."""
inputs = []
t = text
while "~" in t:
try:
splits = list(DB._sandhi.split_at(DB.SanskritImmutableString(t), t.index("~") - 1))
except Exception:
splits = []
for s in splits:
if t == safe_join(*s):
inputs.append(s[0])
t = s[1]
break
else:
inputs.append(t)
t = ""
if t:
inputs.append(t)
result = []
for chunk in inputs:
words, score, verified = decode(model, chunk, **kw)
result.extend(words)
return result
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
TEST_CASES = [
("vidyAdadAtivinayaMvinayAdyAtipAtratAm",
["vidyA", "dadAti", "vinayam", "vinayAt", "yAti", "pAtratAm"]),
("satyamevajayatenAnftaM",
["satyam", "eva", "jayate", "na", "anftam"]),
("gururbrahmAgururviSfuH",
["guruH", "brahmA", "guruH", "viSfuH"]),
("hitopadeSaHsurocanasya",
["hita", "upadeSaH", "surocanasya"]),
("sarvaDarmAnparityajyamAmekaMSaraRaMvraja",
["sarva", "DarmAn", "parityajya", "mAm", "ekam", "SaraRam", "vraja"]),
("tacCrutvAvacanamapuRyam",
["tat", "SrutvA", "vacanam", "apuRyam"]),
("so'vadatkimatra",
["saH", "avadat", "kim", "atra"]),
("ityuktvAkamalApatirantardaqe",
["iti", "uktvA", "kamalApatiH", "antaH", "daqe"]),
("etatmamamano'BirAmam",
["etat", "mama", "manaH", "aBirAmam"]),
("karmARyevADikArastemAphalezukadAcana",
["karmaRi", "eva", "aDikAraH", "te", "mA", "phalezu", "kadAcana"]),
]
def main():
parser = argparse.ArgumentParser(description="decode_v2: beam-search vigraha decoder")
parser.add_argument("text", nargs="?", default=None)
parser.add_argument("--test", action="store_true", help="run the 10 test cases")
parser.add_argument("--checkpoint", default="checkpoints/delayed_model_save_fixed_delay2_v2")
parser.add_argument("--beam", type=int, default=BEAM)
parser.add_argument("--cand-th", type=float, default=CAND_TH)
args = parser.parse_args()
device = torch.device("mps" if torch.backends.mps.is_available() else "cpu")
print(f"Device: {device}", file=sys.stderr)
model, delay = DB.load_model(args.checkpoint, device)
print(f"Loaded model (delay={delay})", file=sys.stderr)
if args.text:
raw = args.text
text = DB.give_correct_slp1_input(raw) if raw and any(ord(c) > 127 for c in raw) else raw.replace(" ", "")
res = decode_wrap(model, text, beam_size=args.beam, cand_th=args.cand_th)
print(f"{raw} => {res}")
return
if args.test:
exact = 0
norm_exact = 0
print(f"{'input':40s} {'exact':6s} {'norm':6s} {'rejoin':7s} decoded")
for inp, exp in TEST_CASES:
res = decode_wrap(model, inp, beam_size=args.beam, cand_th=args.cand_th)
ok = res == exp
nok = (len(res) == len(exp) and
all(_norm(a) == _norm(b) or
(a[:-1] == b[:-1] and a[-1:] in "Hsr" and b[-1:] in "Hsr")
for a, b in zip(res, exp)))
rejoined = safe_join(*res) if res else ""
rej = rejoins(inp, *res) if res else False
if ok:
exact += 1
if nok:
norm_exact += 1
print(f"{inp[:39]:40s} {str(ok):6s} {str(nok):6s} {str(rej):7s} {' + '.join(res)}")
print(f"\nExact: {exact}/{len(TEST_CASES)} (normalized: {norm_exact}/{len(TEST_CASES)})")
return
if __name__ == "__main__":
main()