code-switch-mtp / scripts /phase4_morpheme_boundaries.py
Anupam-Rawat-IITB's picture
Add code, result files and documentation
3bbd5dd verified
Raw History Blame Contribute Delete
17.7 kB
"""Phase 4e: morpheme starts inside words (Hindi only).
Word starts explain where multi-token prediction breaks between words. This
asks the same question one level down: inside a word, is a draft more likely
to fail -- and do the next-token and look-ahead objectives conflict more --
where a new morpheme begins (e.g. a case or plural suffix) than at other
within-word token positions?
Morphemes come from Morfessor Baseline (unsupervised, MDL-based), trained
on a word list from the Phase 3 training text: once on Devanagari words and
once on the same words romanized with the Phase 3 ITRANS transform, so each
script gets its own segmenter.
Tokens are located by their exact UTF-8 bytes (byte-level BPE), so the
analysis works identically on held-out text and on generated
continuations. A token is "within a word" when neither its first byte nor
the byte before it is whitespace; it "starts a morpheme" when it is within a
word and its first byte is a Morfessor boundary inside that word.
"""
import argparse
import csv
import json
import logging
import os
import re
import sys
import time
from collections import Counter, defaultdict
from pathlib import Path
os.environ.setdefault("CUDA_DEVICE_ORDER", "PCI_BUS_ID")
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import torch
import torch.nn.functional as F
import yaml
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("huggingface_hub").setLevel(logging.WARNING)
logger = logging.getLogger("phase4e")
DEVICE = "cuda:0"
N_HEADS = 4
WHITESPACE_BYTES = frozenset(b" \t\n\r\x0b\x0c")
DEVANAGARI_WORD = re.compile(r"^[ऀ-ॣ॰-ॿ]+$") # letters and marks; no danda, no digits
ITRANS_WORD = re.compile(r"^[A-Za-z][A-Za-z.~^]*$")
LEADING_STRIP = set(",;:!?\"'()[]{}<>«»“”‘’-–—/|।॥*")
TRAILING_STRIP = LEADING_STRIP | {"."} # a word-final '.' is sentence punctuation, never ITRANS-internal
def word_core(word: str, script: str) -> tuple:
"""(start, end) character span of the word without surrounding punctuation, or None if not a Hindi word.
ITRANS uses '.', '~' and '^' inside words (e.g. '.c', '.N'), so only a
trailing '.' is stripped; inside a word they are kept.
"""
start, end = 0, len(word)
while start < end and word[start] in LEADING_STRIP:
start += 1
while end > start and word[end - 1] in TRAILING_STRIP:
end -= 1
core = word[start:end]
pattern = DEVANAGARI_WORD if script == "devanagari" else ITRANS_WORD
return (start, end) if core and pattern.match(core) else None
def morph_boundaries(segment, core: str) -> list:
"""Character offsets strictly inside core where a new morpheme begins."""
morphs = segment(core)
offsets = []
pos = 0
for m in morphs[:-1]:
pos += len(m)
offsets.append(pos)
return offsets
def bytes_to_unicode() -> dict:
"""The GPT-2 byte <-> printable-unicode table that byte-level BPE vocabularies are written in."""
bs = list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
cs = bs[:]
n = 0
for b in range(256):
if b not in bs:
bs.append(b)
cs.append(256 + n)
n += 1
return dict(zip(bs, [chr(c) for c in cs]))
def token_byte_table(tokenizer) -> list:
"""Exact UTF-8 bytes of every vocabulary id (special tokens map to b'')."""
decoder = {v: k for k, v in bytes_to_unicode().items()}
special = set(tokenizer.all_special_ids)
table = []
for tid, piece in enumerate(tokenizer.convert_ids_to_tokens(list(range(len(tokenizer))))):
if tid in special or piece is None or any(ch not in decoder for ch in piece):
table.append(b"")
else:
table.append(bytes(decoder[ch] for ch in piece))
return table
def token_flags(ids: list, byte_table: list, segment, script: str) -> dict:
"""Per token: within-word and morpheme-start flags, plus alignment counts.
Args:
ids: token ids of one contiguous text.
byte_table: token_byte_table output.
segment: callable mapping a word core to its list of morphs.
script: 'devanagari' or 'itrans'.
"""
pieces = [byte_table[t] for t in ids]
starts = []
pos = 0
for p in pieces:
starts.append(pos)
pos += len(p)
text = b"".join(pieces)
morph_byte_offsets = set()
n_words = n_segmented = 0
i = 0
while i < len(text):
if text[i] in WHITESPACE_BYTES:
i += 1
continue
j = i
while j < len(text) and text[j] not in WHITESPACE_BYTES:
j += 1
n_words += 1
try:
word = text[i:j].decode("utf-8")
except UnicodeDecodeError:
word = None # a word cut mid-character at the text edge
span = word_core(word, script) if word else None
if span:
core = word[span[0] : span[1]]
bounds = morph_boundaries(segment, core)
if bounds:
n_segmented += 1
for b in bounds:
morph_byte_offsets.add(i + len(word[: span[0] + b].encode("utf-8")))
i = j
within = []
morph_start = []
for s, p in zip(starts, pieces):
inside = bool(p) and s > 0 and text[s] not in WHITESPACE_BYTES and text[s - 1] not in WHITESPACE_BYTES
within.append(inside)
morph_start.append(inside and s in morph_byte_offsets)
token_start_set = set(starts)
aligned = sum(1 for b in morph_byte_offsets if b in token_start_set)
return {
"within": within,
"morph_start": morph_start,
"n_words": n_words,
"n_segmented_words": n_segmented,
"n_morph_boundaries": len(morph_byte_offsets),
"n_morph_boundaries_at_token_start": aligned,
}
def build_word_counts(jsonl: str, skip_docs: int, n_docs: int) -> Counter:
"""Devanagari word counts from training documents (the first skip_docs are the held-out pool)."""
from src.train.data import iter_sangraha_docs
counts = Counter()
for idx, text in enumerate(iter_sangraha_docs(jsonl)):
if idx < skip_docs:
continue
if idx >= skip_docs + n_docs:
break
for w in text.split():
span = word_core(w, "devanagari")
if span:
counts[w[span[0] : span[1]]] += 1
return counts
def train_segmenter(counts: dict, model_path: Path):
"""Morfessor Baseline trained on word types (each type counted once); cached as a binary model file.
Type-based training is the usual choice for morphologically rich
languages: token- or log-count training leaves frequent inflected forms
whole (here it split under 10% of Hindi types, nearly all on -ों),
while type-based training at the default corpus weight splits stems
from suffixes (लड़क+ियों, किताब+ें, कर+ेंगे).
"""
import morfessor
io = morfessor.MorfessorIO()
if model_path.exists():
model = io.read_binary_model_file(str(model_path))
else:
model = morfessor.BaselineModel()
model.load_data([(1, w) for w in counts])
model.train_batch()
io.write_binary_model_file(str(model_path), model)
cache = {}
def segment(word: str) -> list:
if word not in cache:
cache[word] = model.viterbi_segment(word)[0]
return cache[word]
return segment
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--config", default="configs/phase3.yaml")
p.add_argument("--runs", nargs="+", default=["L4_seed0", "L4_seed1", "L2_seed0"])
p.add_argument("--train-docs", type=int, default=20000, help="training documents read for the word list")
p.add_argument("--min-count", type=int, default=5)
p.add_argument("--model-dir", default="/data/cs769_mtp/scratch/runs/phase4/morfessor")
p.add_argument("--n-docs", type=int, default=128)
p.add_argument("--max-tokens", type=int, default=512)
p.add_argument("--continuations", default="/data/cs769_mtp/scratch/runs/phase4/continuations/{condition}_p256_c64_n256.json")
p.add_argument("--completion-tokens", type=int, default=64)
p.add_argument("--train-only", action="store_true", help="build the segmenters and stop (CPU only)")
p.add_argument("--out", default="results/phase4_morpheme_boundaries.csv")
return p.parse_args()
def main() -> None:
from transformers import AutoTokenizer
from src.data.itrans_transliterate import romanize
args = parse_args()
with open(args.config, encoding="utf-8") as f:
cfg = yaml.safe_load(f)
started = time.perf_counter()
model_dir = Path(args.model_dir)
model_dir.mkdir(parents=True, exist_ok=True)
counts_path = model_dir / "hindi_word_counts.json"
if counts_path.exists():
counts = Counter(json.loads(counts_path.read_text()))
else:
counts = build_word_counts(cfg["sangraha_jsonl"], cfg["heldout_docs"] + 88, args.train_docs)
counts = Counter({w: c for w, c in counts.items() if c >= args.min_count})
counts_path.write_text(json.dumps(counts, ensure_ascii=False))
logger.info("word list: %d Devanagari types (count >= %d)", len(counts), args.min_count)
t0 = time.perf_counter()
segmenters = {"devanagari": train_segmenter(counts, model_dir / "morfessor_devanagari.bin")}
logger.info("devanagari segmenter ready in %.0fs", time.perf_counter() - t0)
roman_counts = Counter()
for w, c in counts.items():
r = romanize(w)
if word_core(r, "itrans") == (0, len(r)):
roman_counts[r] += c
t0 = time.perf_counter()
segmenters["itrans"] = train_segmenter(roman_counts, model_dir / "morfessor_itrans.bin")
logger.info("itrans segmenter ready in %.0fs (%d types)", time.perf_counter() - t0, len(roman_counts))
examples = []
for w, _ in counts.most_common(400):
dev = segmenters["devanagari"](w)
rom = romanize(w)
ita = segmenters["itrans"](rom) if word_core(rom, "itrans") == (0, len(rom)) else [rom]
if len(dev) > 1 or len(ita) > 1:
examples.append({"word": w, "devanagari_morphs": dev, "itrans": rom, "itrans_morphs": ita})
(model_dir / "segmentation_examples.json").write_text(json.dumps(examples[:40], ensure_ascii=False, indent=1))
if args.train_only:
return
from transformers import AutoModelForCausalLM
from scripts.phase4_boundary_decoding import LOOKAHEAD, drafts_for_doc, simulate_doc, word_start_table
from scripts.phase4_boundary_decoding import load_stack as load_any_stack
from scripts.phase4_gradient_conflict import per_position_grads
from src.train.data import load_heldout_texts
tokenizer = AutoTokenizer.from_pretrained(cfg["backbone"]["hf_id"])
backbone = AutoModelForCausalLM.from_pretrained(cfg["backbone"]["hf_id"], dtype=torch.float32).to(DEVICE)
backbone.eval()
for param in backbone.parameters():
param.requires_grad = False
byte_table = token_byte_table(tokenizer)
starts_table = word_start_table(tokenizer)
rows = [["run", "condition", "seed", "analysis", "cell", "metric", "value", "n"]]
def add(run, analysis, cell, metric, value, n):
condition, seed = run.split("_")
rows.append([run, condition, seed, analysis, cell, metric, f"{value:.6f}" if isinstance(value, float) else value, n])
for run in args.runs:
condition = run.split("_")[0]
script = "devanagari" if condition == "L4" else "itrans"
segment = segmenters[script]
t0 = time.perf_counter()
stack = load_any_stack(backbone, Path(cfg["checkpoint_dir"]) / run / "mtp.pt", shared_trunk=True)
for p in stack.parameters():
p.requires_grad_(False)
# held-out text: alignment statistics and gradient conflict inside words
texts = load_heldout_texts(str(Path(cfg["data_dir"]) / f"{condition}_heldout.jsonl"))[: args.n_docs]
conflict = defaultdict(lambda: [0, 0])
align = Counter()
for text in texts:
ids = tokenizer(text, add_special_tokens=False, truncation=True, max_length=args.max_tokens).input_ids
if len(ids) < N_HEADS + 4:
continue
fl = token_flags(ids, byte_table, segment, script)
align["within_tokens"] += sum(fl["within"])
align["morph_start_tokens"] += sum(fl["morph_start"])
align["tokens"] += len(ids)
align["morph_boundaries"] += fl["n_morph_boundaries"]
align["morph_boundaries_at_token_start"] += fl["n_morph_boundaries_at_token_start"]
align["words"] += fl["n_words"]
align["segmented_words"] += fl["n_segmented_words"]
block = torch.tensor([ids], dtype=torch.long, device=DEVICE)
seq = len(ids)
with torch.no_grad():
hidden = backbone.model(input_ids=block).last_hidden_state
trunk_out = stack.trunk_states(hidden)
leaf = trunk_out.detach().requires_grad_(True)
with torch.enable_grad():
grads = per_position_grads(stack, leaf, block)
for k in (2, 3):
valid = seq - k
neg = (F.cosine_similarity(grads[1][:valid], grads[k][:valid], dim=-1, eps=1e-12) < 0).tolist()
for p_ in range(valid):
span = range(p_ + 2, p_ + k + 1)
if not all(fl["within"][t] for t in span):
continue # the k-span leaves the word: covered by the word-level analysis
crosses_morph = any(fl["morph_start"][t] for t in span)
cell = conflict[(k, crosses_morph)]
cell[0] += 1
cell[1] += int(neg[p_])
del grads, leaf, trunk_out, hidden
for (k, c), (n, nc) in sorted(conflict.items()):
add(run, f"conflict_k{k}_within_word", "crosses_morpheme" if c else "same_morpheme", "conflict_rate", nc / n if n else float("nan"), n)
add(run, "alignment_heldout", "all", "share_within_word_tokens_starting_morpheme", align["morph_start_tokens"] / max(1, align["within_tokens"]), align["within_tokens"])
add(run, "alignment_heldout", "all", "share_morph_boundaries_at_token_start", align["morph_boundaries_at_token_start"] / max(1, align["morph_boundaries"]), align["morph_boundaries"])
add(run, "alignment_heldout", "all", "share_words_with_2plus_morphs", align["segmented_words"] / max(1, align["words"]), align["words"])
# generated continuations: draft acceptance at within-word positions
pairs = json.loads(Path(args.continuations.format(condition=condition)).read_text())
accept = defaultdict(lambda: [0, 0])
for prompt, cont in pairs:
horizon = min(args.completion_tokens, len(cont) - LOOKAHEAD + 1)
if horizon < 1:
continue
fl = token_flags(prompt + cont, byte_table, segment, script)
p0 = len(prompt) - 1
n_cont = len(cont) + 1
within_c = fl["within"][p0 : p0 + n_cont]
morph_c = fl["morph_start"][p0 : p0 + n_cont]
dd = drafts_for_doc(backbone, stack, prompt, cont, horizon, starts_table)
r_within = simulate_doc(dd["drafts"], dd["draft_starts"], dd["continuation"], within_c, horizon, "fixed4")
r_morph = simulate_doc(dd["drafts"], dd["draft_starts"], dd["continuation"], morph_c, horizon, "fixed4")
for rw, rm in zip(r_within, r_morph):
for i in range(N_HEADS):
if rw["n_acc"] < i:
break
if not rw["true_starts"][i]:
continue # the true token begins a word: not a within-word position
cell = accept[(i + 1, rm["true_starts"][i])]
cell[0] += 1
cell[1] += int(rw["n_acc"] > i)
for (i, m), (n, a) in sorted(accept.items()):
add(run, f"accept_pos{i}_within_word", "morpheme_start" if m else "inside_morpheme", "acceptance", a / n if n else float("nan"), n)
add(run, "meta", "all", "wall_seconds", time.perf_counter() - t0, 1)
logger.info(
"%s: conflict k2 within-word crosses-morph %.3f (n=%d) vs same %.3f (n=%d) | accept pos2 morph-start %.3f (n=%d) vs inside %.3f (n=%d) | morph-start share %.3f | %.0fs",
run,
conflict[(2, True)][1] / max(1, conflict[(2, True)][0]), conflict[(2, True)][0],
conflict[(2, False)][1] / max(1, conflict[(2, False)][0]), conflict[(2, False)][0],
accept[(2, True)][1] / max(1, accept[(2, True)][0]), accept[(2, True)][0],
accept[(2, False)][1] / max(1, accept[(2, False)][0]), accept[(2, False)][0],
align["morph_start_tokens"] / max(1, align["within_tokens"]),
time.perf_counter() - t0,
)
del stack
torch.cuda.empty_cache()
rows.append(["all_all", "all", "all", "meta", "all", "total_wall_seconds", f"{time.perf_counter() - started:.1f}", 1])
rows.append(["all_all", "all", "all", "meta", "all", "gpu", torch.cuda.get_device_name(DEVICE), 1])
Path(args.out).parent.mkdir(parents=True, exist_ok=True)
with open(args.out, "w", newline="", encoding="utf-8") as f:
csv.writer(f).writerows(rows)
logger.info("wrote %s", args.out)
if __name__ == "__main__":
main()