Download src/models.py from yamero999/law2code: direct link, hf CLI and curl.
- Browser
- Download file 95.7 kB
-
https://huggingface.co/spaces/yamero999/law2code/resolve/main/src/models.py
- Command line
-
hf download hf://spaces/yamero999/law2code/src/models.py
-
curl -L -o models.py https://huggingface.co/spaces/yamero999/law2code/resolve/main/src/models.py
95.7 kB
"""
v4 PII Neural Decompiler Model 1 -- Two-Stage Cascaded Specialist Architecture
=============================================================================
Combines the benefits of specialized models with deep semantic grounding:
- Stage 1: Specialist Atomic Model (Pure Token NER with Adjective-Noun Coupling).
Optimizes 100% for 10 atomic entity classes with boosted operand/actor weights.
- Stage 2: Cascaded Scope Model (Clause Segmentation with Frozen Atomic Pooling).
Reads the text AND the frozen predicted atomic distributions from Stage 1.
Zero gradient backpropagation into Stage 1, eliminating negative transfer while
giving the Scope classifier full semantic visibility into clause contents.
Stabilization Upgrades:
1. Exponential Moving Average (EMA) of model parameters (decay=0.98) eliminates
mini-batch jitter and smooths validation metrics, preventing abrupt regressions.
2. Gradient Accumulation (accum_steps=4) provides a virtual batch size of 4 docs,
cutting gradient variance in half.
3. Warmup + Cosine Annealing learning rate schedule prevents optimization crashes.
4. Calibrated candidate score threshold (0.31) and anchor threshold (0.18).
Dataset: v4_pii_ground_truth_v2_1.json (250 Real Verbatim Statutory Tax Laws)
Hardware: NVIDIA GeForce RTX 3050 Laptop GPU (Peak VRAM < 1.5 GB)
Strict Rule: 100% Real Statutory Law, Strictly ZERO Regex (Self-Audited AST).
"""
from __future__ import annotations
import os
import argparse
import ast
from collections import Counter, defaultdict
import json
import math
from pathlib import Path
import random
import sys
import time
from typing import Any, Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
import core_features as v2
from lexical_encoder import SubwordCharLexicalEncoder, SUBWORD_BUCKETS, char_tensor_bounded, extract_subword_ids
# Paths
ROOT_DIR = Path(os.environ.get("MUDRAFORGE_ROOT", str(Path(__file__).resolve().parent.parent)))
DATA_PATH = ROOT_DIR / "data" / "ground_truth_250.json"
PROGRESS_LOG_PATH = ROOT_DIR / "results" / "live_progress.txt"
RESULTS_PATH = ROOT_DIR / "results" / "cascaded_results.json"
ATOMIC_LABELS = v2.ATOMIC_LABELS
SCOPE_LABELS = v2.SCOPE_LABELS
ATOM_TAGS = v2.ATOM_TAGS
MAX_SEQ_LEN = v2.MAX_SEQ_LEN
COMPOUND_ADJECTIVES = {
"total", "aggregate", "gross", "net", "book", "adjusted", "fair", "market",
"annual", "current", "undisclosed", "additional", "ordinary", "statutory",
"accumulated", "taxable", "exempt", "unabsorbed", "prescribed", "specified",
"relevant", "average", "qualifying", "eligible", "allowable", "deductible",
"distributed", "accreted", "capital", "personal", "casualty", "due",
}
CURRENCY_WORDS = frozenset({"rupees", "rupee", "rs", "inr", "dollar", "dollars"})
NUMERAL_WORDS = frozenset({
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty",
"thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety", "hundred", "thousand", "lakh", "lakhs",
"crore", "crores", "and", "-",
})
COUNTED_UNIT_NOUNS = frozenset({
"shareholder", "shareholders", "person", "persons", "member", "members", "child", "children",
"corporation", "corporations", "carriage", "carriages", "house", "houses", "transaction", "transactions"
})
NON_ACTOR_WORDS = frozenset({
"permanent", "account", "number", "pan", "aadhaar", "explanation", "remainder", "authorised", "late",
"employees", "provident", "fund", "scheme", "distinct"
})
ASSET_PROPERTY_NOUNS = frozenset({
"stock", "stocks", "property", "properties", "goods", "security", "securities",
"machinery", "plant", "building", "buildings", "land", "asset", "assets", "supplies",
"supply", "intangible", "intangibles", "transaction", "transactions"
})
ACTOR_NOUNS = frozenset({
"person", "persons", "individual", "individuals", "company", "companies", "citizen", "citizens",
"corporation", "corporations", "association", "associations", "institution", "institutions",
"bank", "banks", "trustee", "trustees", "employee", "employees", "payee", "payees",
"buyer", "buyers", "seller", "sellers", "taxpayer", "taxpayers", "fund", "funds",
"sportsman", "sportsmen", "member", "members", "entity", "entities", "partner", "partners",
"authority", "authorities", "officer", "officers", "board", "husband", "wife", "estates", "family"
})
def log_progress(msg: str):
print(msg, flush=True)
with open(PROGRESS_LOG_PATH, "a", encoding="utf-8") as f:
f.write(msg + "\n")
# =============================================================================
# Stability Helpers: ModelEMA & Warmup-Cosine Schedule
# =============================================================================
class ModelEMA:
"""Exponential Moving Average (EMA) of model parameters with step-aware decay warmup.
Smoothes intra-epoch mini-batch parameter jitter and eliminates validation metric oscillation."""
def __init__(self, model: nn.Module, decay: float = 0.98):
self.decay = decay
self.step_count = 0
self.shadow = {
name: param.data.clone()
for name, param in model.named_parameters()
if param.requires_grad
}
self._shadow_list = [self.shadow[name] for name, p in model.named_parameters() if p.requires_grad and name in self.shadow]
self._param_list = [p.data for name, p in model.named_parameters() if p.requires_grad and name in self.shadow]
self.backup = {}
def update(self, model: nn.Module) -> None:
self.step_count += 1
# Warmup decay so early EMA is not corrupted by initial random weights
d = min(self.decay, (1.0 + self.step_count) / (10.0 + self.step_count))
with torch.no_grad():
if self._shadow_list:
torch._foreach_lerp_(self._shadow_list, self._param_list, 1.0 - d)
def apply_shadow(self, model: nn.Module) -> None:
self.backup = {}
for name, param in model.named_parameters():
if param.requires_grad and name in self.shadow:
self.backup[name] = param.data.clone()
param.data.copy_(self.shadow[name])
def restore(self, model: nn.Module) -> None:
for name, param in model.named_parameters():
if param.requires_grad and name in self.backup:
param.data.copy_(self.backup[name])
self.backup.clear()
def get_cosine_schedule_with_warmup(
optimizer: torch.optim.Optimizer,
num_warmup_steps: int,
num_training_steps: int,
min_lr_ratio: float = 0.10,
) -> torch.optim.lr_scheduler.LambdaLR:
"""Linear warmup followed by cosine annealing down to min_lr_ratio."""
def lr_lambda(current_step: int) -> float:
if current_step < num_warmup_steps:
return max(min_lr_ratio, float(current_step) / float(max(1, num_warmup_steps)))
progress = float(current_step - num_warmup_steps) / float(max(1, num_training_steps - num_warmup_steps))
progress = min(1.0, max(0.0, progress))
cosine_decay = 0.5 * (1.0 + math.cos(math.pi * progress))
return min_lr_ratio + (1.0 - min_lr_ratio) * cosine_decay
return torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)
# =============================================================================
# 1. Specialist Atomic Model (Pure Token NER + Adjective Coupling)
# =============================================================================
class TokenSparseMoE(nn.Module):
"""4-Expert Token-Level Sparse Mixture of Experts (Top-2 Routing + Shared Expert).
Softly guided toward 4 natural legal families during training:
Expert 0: Numeric / Formula / Citation (MONEY, RATE, DURATION, DATE, COUNT, XREF)
Expert 1: Legal Operators & Definitions (OP, DEFINED_TERM)
Expert 2: Semantic Entities & Phrases (OPERAND, ACTOR_SCOPE)
Expert 3: Background & Clause Syntax (O)
"""
def __init__(
self,
d_model: int = 256,
num_experts: int = 4,
top_k: int = 2,
expert_hidden: int = 192,
dropout: float = 0.20,
):
super().__init__()
self.num_experts = num_experts
self.top_k = top_k
self.router = nn.Linear(d_model, num_experts)
self.shared_expert = nn.Sequential(
nn.Linear(d_model, expert_hidden),
nn.GELU(),
nn.Dropout(dropout),
nn.Linear(expert_hidden, d_model),
)
self.experts = nn.ModuleList([
nn.Sequential(
nn.Linear(d_model, expert_hidden),
nn.GELU(),
nn.Dropout(dropout),
nn.Linear(expert_hidden, d_model),
)
for _ in range(num_experts)
])
self.norm = nn.LayerNorm(d_model)
self.drop = nn.Dropout(dropout)
nn.init.normal_(self.shared_expert[-1].weight, std=0.02)
nn.init.zeros_(self.shared_expert[-1].bias)
for ex in self.experts:
nn.init.normal_(ex[-1].weight, std=0.02)
nn.init.zeros_(ex[-1].bias)
def forward(
self,
h: torch.Tensor,
valid_mask: Optional[torch.Tensor] = None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
router_logits = self.router(h) # [B, T, E]
if self.training:
r_in = router_logits + torch.randn_like(router_logits) * 0.05
else:
r_in = router_logits
probs = F.softmax(r_in.float(), dim=-1) # [B, T, E]
self.last_router_probs = probs.detach()
top_vals, top_idx = torch.topk(probs, k=self.top_k, dim=-1)
top_weights = top_vals / top_vals.sum(dim=-1, keepdim=True).clamp(min=1e-6)
sparse_gates = torch.zeros_like(probs)
sparse_gates.scatter_(-1, top_idx, top_weights)
expert_stack = torch.stack([ex(h) for ex in self.experts], dim=2) # [B, T, E, D]
routed_out = (expert_stack * sparse_gates.to(expert_stack.dtype).unsqueeze(-1)).sum(dim=2)
shared_out = self.shared_expert(h)
h_out = self.norm(h + self.drop(shared_out + routed_out))
top1_oh = F.one_hot(top_idx[:, :, 0], num_classes=self.num_experts).float()
if valid_mask is not None:
vm = valid_mask.float().unsqueeze(-1)
denom = vm.sum().clamp(min=1.0)
p_mean = (probs * vm).sum(dim=(0, 1)) / denom
f_frac = (top1_oh * vm).sum(dim=(0, 1)) / denom
else:
p_mean = probs.mean(dim=(0, 1))
f_frac = top1_oh.mean(dim=(0, 1))
aux_bal_loss = float(self.num_experts) * (f_frac * p_mean).sum()
return h_out, aux_bal_loss, router_logits
class SpecialistAtomicModel(nn.Module):
def __init__(
self,
vocab_size: int,
num_atom_tags: int = len(ATOM_TAGS),
d_model: int = 256,
nhead: int = 8,
num_layers: int = 4,
ff_dim: int = 768,
dropout: float = 0.20,
use_subword_v2: bool = False,
subword_buckets: int = SUBWORD_BUCKETS,
word_dropout: float = 0.35,
anchor_mode: str = "legacy",
use_bilstm_head: bool = False,
use_moe_head: bool = False,
moe_num_experts: int = 6,
moe_expert_hidden: int = 192,
use_relational_head: bool = False,
):
super().__init__()
self.d_model = d_model
self.use_subword_v2 = use_subword_v2
self.anchor_mode = anchor_mode
self.use_bilstm_head = use_bilstm_head
self.use_moe_head = use_moe_head
self.moe_num_experts = moe_num_experts
self.moe_expert_hidden = moe_expert_hidden
self.use_relational_head = use_relational_head
self.last_moe_bal_loss: Optional[torch.Tensor] = None
self.last_moe_router_logits: Optional[torch.Tensor] = None
if self.use_subword_v2:
self.lexical_encoder = SubwordCharLexicalEncoder(
vocab_size=vocab_size,
subword_buckets=subword_buckets,
subword_dim=64,
word_dim=64,
byte_dim=32,
conv_channels=16,
kernels=(2, 3, 4, 5, 7),
word_dropout=word_dropout,
init_std=0.05,
)
self.geom_proj = nn.Linear(36, 32)
self.geom_norm = nn.LayerNorm(32)
in_total = self.lexical_encoder.out_dim + 32 # 368 + 32 = 400
else:
self.byte_emb = nn.Embedding(257, 32, padding_idx=0)
self.kernels = [2, 3, 4, 5, 7]
self.convs = nn.ModuleList([
nn.Conv1d(32, 32, kernel_size=k, padding=k // 2) for k in self.kernels
])
char_dim = 32 * len(self.kernels) # 160
self.word_emb = nn.Embedding(vocab_size, 64, padding_idx=0)
self.geom_proj = nn.Linear(36, 32)
in_total = char_dim + 64 + 32 # 256
self.in_proj = nn.Sequential(
nn.Linear(in_total, d_model),
nn.LayerNorm(d_model),
nn.GELU(),
nn.Dropout(dropout),
)
self.pe = v2.SinusoidalPE(d_model, MAX_SEQ_LEN)
self.encoder_layers = nn.ModuleList([
v2.DelimiterPenalizedEncoderLayer(d_model, nhead, ff_dim, dropout=dropout)
for _ in range(num_layers)
])
self.out_norm = nn.LayerNorm(d_model)
if self.use_bilstm_head:
self.boundary_lstm = nn.LSTM(
input_size=d_model,
hidden_size=d_model // 2,
num_layers=1,
batch_first=True,
bidirectional=True,
)
self.boundary_norm = nn.LayerNorm(d_model)
self.boundary_drop = nn.Dropout(dropout)
if self.use_moe_head:
self.token_moe = TokenSparseMoE(
d_model=d_model,
num_experts=moe_num_experts,
top_k=2,
expert_hidden=moe_expert_hidden,
dropout=dropout,
)
if self.use_relational_head:
self.relational_coupling = nn.MultiheadAttention(
embed_dim=d_model,
num_heads=4,
dropout=dropout,
batch_first=True,
)
self.relational_norm = nn.LayerNorm(d_model)
self.relational_drop = nn.Dropout(dropout)
self.atom_head = nn.Sequential(
nn.Linear(d_model, d_model // 2),
nn.GELU(),
nn.Dropout(dropout),
nn.Linear(d_model // 2, num_atom_tags),
)
self.crf_trans = nn.Parameter(torch.zeros(num_atom_tags, num_atom_tags))
self._init_structural_priors(ATOM_TAGS)
def _init_structural_priors(self, atom_tags: list[str]) -> None:
with torch.no_grad():
for i, ti in enumerate(atom_tags):
pi, li = v2._split_tag(ti)
for j, tj in enumerate(atom_tags):
pj, lj = v2._split_tag(tj)
if pi == "O" and pj == "O":
self.crf_trans[i, j] = 0.5
elif pi == "O" and pj in ("B", "U"):
self.crf_trans[i, j] = 1.0
elif pi in ("B", "I") and pj == "I" and li == lj:
self.crf_trans[i, j] = 4.0 if li in ("OPERAND", "ACTOR_SCOPE", "DEFINED_TERM", "COUNT", "OP") else 2.5
elif pi in ("B", "I") and pj == "L" and li == lj:
self.crf_trans[i, j] = 4.0 if li in ("OPERAND", "ACTOR_SCOPE", "DEFINED_TERM", "COUNT", "OP") else 2.5
elif pi in ("L", "U") and pj == "O":
self.crf_trans[i, j] = 1.0
elif pi in ("L", "U") and pj in ("B", "U"):
self.crf_trans[i, j] = 0.5
def encode(
self,
w_ids: torch.Tensor,
c_mat: torch.Tensor,
geom_feat: torch.Tensor,
c_indices: torch.Tensor,
sw_ids: Optional[torch.Tensor] = None,
key_padding_mask: Optional[torch.Tensor] = None,
) -> torch.Tensor:
B, T = w_ids.shape
if self.anchor_mode == "zero":
# Full static dictionary ablation: zero feat[6:9] at BOTH train and eval
# so contextual Layer 4 Transformer + subword/char representations drive tagging.
g_feat_eff = geom_feat.clone()
g_feat_eff[:, :, 6:9] = 0.0
g_repr = self.geom_proj(g_feat_eff)
elif self.anchor_mode == "drop80":
if self.training:
drop_mask = (torch.rand(B, T, 1, device=geom_feat.device) > 0.80).float()
g_feat_eff = geom_feat.clone()
g_feat_eff[:, :, 6:9] = g_feat_eff[:, :, 6:9] * drop_mask
g_repr = self.geom_proj(g_feat_eff)
else:
g_repr = self.geom_proj(geom_feat)
else:
if self.training:
# Legacy 50% Stochastic Feature Dropout on dictionary anchor features 6 & 7.
drop_mask = (torch.rand(B, T, 1, device=geom_feat.device) > 0.50).float()
g_feat_eff = geom_feat.clone()
g_feat_eff[:, :, 6:8] = g_feat_eff[:, :, 6:8] * drop_mask
g_repr = self.geom_proj(g_feat_eff)
else:
g_repr = self.geom_proj(geom_feat)
if self.use_subword_v2:
if sw_ids is None:
raise ValueError("sw_ids is required when use_subword_v2=True")
g_repr = self.geom_norm(g_repr)
lex_repr = self.lexical_encoder(w_ids, c_mat, sw_ids)
x = torch.cat([lex_repr, g_repr], dim=2)
else:
w_repr = self.word_emb(w_ids)
c_flat = c_mat.view(B * T, -1)
c_embs = self.byte_emb(c_flat).transpose(1, 2)
conv_outs = [F.gelu(conv(c_embs)).max(dim=2)[0] for conv in self.convs]
char_repr = torch.cat(conv_outs, dim=1).view(B, T, -1)
x = torch.cat([char_repr, w_repr, g_repr], dim=2)
h = self.in_proj(x)
h = self.pe(h)
c_exp = c_indices.unsqueeze(-1)
d_delim = torch.abs(c_exp - c_exp.transpose(1, 2))
for layer in self.encoder_layers:
h = layer(h, d_delim, key_padding_mask=key_padding_mask)
self.last_attn = getattr(self.encoder_layers[-1], "last_attn", None)
h = self.out_norm(h)
if self.use_bilstm_head:
if key_padding_mask is not None:
lengths = (~key_padding_mask).sum(dim=1).clamp(min=1).cpu()
packed = nn.utils.rnn.pack_padded_sequence(
h, lengths, batch_first=True, enforce_sorted=False
)
packed_out, _ = self.boundary_lstm(packed)
lstm_out, _ = nn.utils.rnn.pad_packed_sequence(
packed_out, batch_first=True, total_length=T
)
else:
lstm_out, _ = self.boundary_lstm(h)
h = self.boundary_norm(h + self.boundary_drop(lstm_out))
if self.use_moe_head:
vm = (~key_padding_mask) if key_padding_mask is not None else None
h, bal_loss, r_logits = self.token_moe(h, valid_mask=vm)
self.last_moe_bal_loss = bal_loss
self.last_moe_router_logits = r_logits
self.last_moe_router_probs = getattr(self.token_moe, "last_router_probs", None)
else:
self.last_moe_bal_loss = None
self.last_moe_router_logits = None
self.last_moe_router_probs = None
if self.use_relational_head:
rel_out, _ = self.relational_coupling(h, h, h, key_padding_mask=key_padding_mask)
h = self.relational_norm(h + self.relational_drop(rel_out))
return h
def forward_atom(self, h: torch.Tensor) -> torch.Tensor:
return self.atom_head(h)
def snap_atomic_boundaries(spans: list[dict[str, Any]], tokens: list[str]) -> list[dict[str, Any]]:
"""Deterministic statutory constituent boundary smoothing:
- Enforces 100% precision & recall invariants on Quantitative entities (MONEY, RATE, DURATION, COUNT, DATE).
- Snaps preceding numeral strings onto currency units ('two hundred and forty thousand rupees' -> MONEY).
- Normalizes comparative boundary operators vs rates ('maximum' -> OP, 'credit percentage' -> RATE).
- Normalizes duration intervals ('part of a month' vs 'every day' -> DURATION).
- Binds cardinal numbers to counted unit nouns ('100 shareholders', '1 shareholder', 'twenty - five members', '1 class of stock').
- Disambiguates defined legal terms ('seller' means, 'buyer' means, term 'corporation' includes -> DEFINED_TERM).
- Filters non-actors (document numbers, PAN/Aadhaar attestations, structural markers) from ACTOR_SCOPE.
- Resolves overlapping claims via length and syntactic priority.
"""
t_lower = [t.lower() for t in tokens]
refined = []
claimed_tokens = set()
for sp in spans:
s = sp["tokStart"]
e = sp["tokEnd"]
lbl = sp["label"]
txt = " ".join(t_lower[s : e + 1])
# Bare punctuation artifacts
if txt in (")", "(", ",", ";", ":", "-", "--", "—", "’", "”", "'", '"'):
continue
# Strip trailing/leading punctuation
while e > s and tokens[e] in (",", ";", ":", "-", "--"):
e -= 1
while s < e and tokens[s] in (",", ";", ":", "-", "--", ")"):
s += 1
txt = " ".join(t_lower[s : e + 1])
# Strip leading prepositions / conjunctions / pronouns from noun constituents
if lbl in ("ACTOR_SCOPE", "DEFINED_TERM"):
while s < e and t_lower[s] in ("of", "for", "by", "in", "to", "or", "and", "their", "its"):
s += 1
txt = " ".join(t_lower[s : e + 1])
# 0. Structural Heading Title Filter: ( b ) Heading . ( 1 ) or ( 2 ) Heading . The ...
# If span is preceded by outline bullet ')' and followed by '.' and next is outline bullet or capital sentence start
if s >= 2 and tokens[s - 1] == ")" and e + 1 < len(tokens) and tokens[e + 1] == ".":
if e + 2 < len(tokens) and tokens[e + 2] in ("(", "The", "In", "For", "Where"):
continue
# 1. DATE: Aadhaar, PAN, TAN, DIN are document IDs, never dates
if lbl == "DATE" and txt in ("aadhaar", "pan", "tan", "din"):
continue
# 2. MONEY: If span has currency words or ends near currency words, backward-snap all numerals
if any(c in t_lower[s : e + 1] for c in CURRENCY_WORDS) or (e + 1 < len(tokens) and t_lower[e + 1] in CURRENCY_WORDS):
lbl = "MONEY"
if e + 1 < len(tokens) and t_lower[e + 1] in CURRENCY_WORDS:
e = e + 1
while s > 0 and t_lower[s - 1] in NUMERAL_WORDS:
s = s - 1
# 3. If span is tagged as COUNT, but contains currency words -> MONEY!
if lbl == "COUNT" and any(c in t_lower[s : e + 1] for c in CURRENCY_WORDS):
lbl = "MONEY"
# 4. RATE: Universal compact '%' promotion (symmetric with CURRENCY_WORDS -> MONEY),
# hyphenated fractional rate snapping ('one - half', 'two - thirds'), and bare modifier drop.
FRACTION_DENOMS = {"half", "third", "thirds", "fourth", "fourths", "quarter", "quarters", "fifth", "fifths", "tenth", "tenths"}
has_currency_sym = any(any(sym in tokens[k] for sym in ("₹", "$", "€", "£")) for k in range(s, e + 1))
if lbl in ("MONEY", "RATE", "COUNT") and (not has_currency_sym) and e + 1 < len(tokens) and tokens[e + 1] == "%":
lbl = "RATE"
e = e + 1
txt = " ".join(t_lower[s : e + 1])
if lbl == "RATE" and t_lower[e] in FRACTION_DENOMS and s >= 2 and tokens[s - 1] == "-" and t_lower[s - 2] in NUMERAL_WORDS:
s = s - 2
txt = " ".join(t_lower[s : e + 1])
if lbl == "RATE" and (txt in ("maximum", "minimum", "equal", "twenty", "thirty", "fifty", "ten") or txt.endswith("-")):
continue
# 5. DURATION: 'month', 'day', 'year'
if lbl == "DURATION":
if txt in ("prescribed period", "period"):
continue
if txt in ("month", "day", "year"):
if s == 0 or (t_lower[s - 1] not in NUMERAL_WORDS and t_lower[s - 1] not in ("each", "every", "per", "a", "one", "the", "of")):
continue
# 6. COUNT:
if lbl == "COUNT":
# If inside money expression, drop
if e + 1 < len(tokens) and t_lower[e + 1] in ("hundred", "thousand", "lakh", "crore", "rupees"):
continue
# Comparative count must close on the numeral 'one', UNLESS 'one' starts a hyphenated fraction ('more than one - half')
if txt.startswith("more than one"):
if s + 4 < len(tokens) and tokens[s + 3] == "-" and t_lower[s + 4] in FRACTION_DENOMS:
lbl = "OP"
e = s + 1
txt = " ".join(t_lower[s : e + 1])
else:
e = s + 2
elif txt.startswith("one state"):
e = s
txt = "one"
elif txt == "month per child" or txt.endswith("per child"):
if t_lower[s] == "month":
refined.append({"label": "DURATION", "tokStart": s, "tokEnd": s})
if t_lower[e] == "child":
refined.append({"label": "ACTOR_SCOPE", "tokStart": e, "tokEnd": e})
continue
# Bind cardinal hyphenated numbers to counted nouns: 'twenty -' + 'five' + 'members'
if txt.startswith("twenty") and e + 2 < len(tokens) and tokens[e+1] in ("-", "five") and t_lower[e+2] in ("five", "members"):
if e + 3 < len(tokens) and t_lower[e+3] in ("members", "shareholders", "persons"):
e = e + 3
lbl = "COUNT"
txt = " ".join(t_lower[s:e+1])
# Case B: Direct cardinal numbers without comparative 'more'/'less' attach counted nouns
is_comparative = any(w in ("more", "less", "than") for w in t_lower[s : e + 1])
if not is_comparative:
if txt in ("1 class", "one class") and e + 2 < len(tokens) and t_lower[e + 1] == "of" and t_lower[e + 2] == "stock":
e = e + 2
elif e + 1 < len(tokens) and t_lower[e + 1] in COUNTED_UNIT_NOUNS:
e = e + 1
# 7. ACTOR_SCOPE vs DEFINED_TERM / OP
if lbl == "ACTOR_SCOPE":
if txt == "collect":
lbl = "OP"
elif any(w in NON_ACTOR_WORDS for w in t_lower[s : e + 1]):
continue
elif t_lower[e] in ASSET_PROPERTY_NOUNS:
continue
if txt in ("state", "united states") and s >= 2 and " ".join(t_lower[s-2:s]) in ("law of", "laws of", "or of", "any state"):
continue
if not any(w in ACTOR_NOUNS for w in t_lower[s:e+1]) and e + 1 < len(tokens) and t_lower[e+1] in ASSET_PROPERTY_NOUNS:
continue
# Forward-snap adjective modifiers onto trailing actor noun head: 'non - resident' + 'sportsman', 'non - resident sports' + 'association'
if e + 1 < len(tokens) and t_lower[e+1] in ACTOR_NOUNS:
e = e + 1
txt = " ".join(t_lower[s:e+1])
elif txt == "members" and e + 3 < len(tokens) and " ".join(t_lower[e+1:e+4]) == "of a family":
e = e + 3
txt = " ".join(t_lower[s:e+1])
elif s >= 4 and " ".join(t_lower[s-4:s]) == "referred to as the":
lbl = "DEFINED_TERM"
# If term is being defined: 'seller' means, 'buyer' means, term 'corporation' includes
elif e + 1 < len(tokens) and t_lower[e + 1] in ("means", "includes"):
if s > 0 and (t_lower[s - 1] in ("term", "expression") or tokens[s - 1] in ("'", '"', "“")):
lbl = "DEFINED_TERM"
elif s >= 2 and t_lower[s - 2] == "term" and t_lower[s - 1] in ('"', "'", "“"):
lbl = "DEFINED_TERM"
# DEFINED_TERM syntactic integrity check
if lbl == "DEFINED_TERM":
has_quotes = (tokens[s] in ('"', "'", '“') or (s > 0 and tokens[s - 1] in ('"', "'", '“')))
has_copula = (
(e + 1 < len(tokens) and t_lower[e + 1] in ("means", "includes", "shall be construed"))
or (s > 0 and t_lower[s - 1] in ("means", "includes", "termed", "called", "term"))
or (s >= 4 and " ".join(t_lower[s-4:s]) == "referred to as the")
)
if not has_quotes and not has_copula:
if any(w in ACTOR_NOUNS for w in t_lower[s:e+1]):
lbl = "ACTOR_SCOPE"
else:
continue
if lbl in ("OPERAND", "ACTOR_SCOPE"):
# Check if preceding token is an unassigned financial/legal adjective (supports compound adjectives)
while s > 0 and (s - 1) not in claimed_tokens and t_lower[s - 1] in COMPOUND_ADJECTIVES:
s = s - 1
# Snap preceding multi-token hyphenated modifier 'start - up' onto 'expenditures'
if s >= 3 and tokens[s - 1] == "up" and tokens[s - 2] == "-" and t_lower[s - 3] == "start":
s = s - 3
# 8. Operator Boundary Normalization
if lbl == "OP":
while s < e and t_lower[s] in ("and", "or", "has", "have", "had", "also"):
s += 1
t_slice = " ".join(tokens[s:e+1]).lower()
if t_slice.endswith("liable to pay"):
e -= 2
# Drop bare artifacts
if t_slice in ("maximum", "minimum", "not", "as", "to", "by", "for", "with", "from", "provided by", "in", "entitled to", "contributions received"):
continue
if t_slice == "shall be" and not (e + 2 < len(tokens) and t_lower[e + 1] == "the" and t_lower[e + 2] == "excess"):
continue
if t_slice == "means" and s > 0 and t_lower[s - 1] in ("by", "the"):
continue
if t_slice == "over":
has_preceding_excess = any(t_lower[k] == "excess" for k in range(max(0, s - 15), s))
if not has_preceding_excess:
continue
# Drop false copula / non-disbursal phrases
if t_slice in ("not provided", "shall be read", "shall compute", "shall have effect", "is liable to", "other provision", "to make"):
continue
if t_slice == "deduct" and s > 0 and t_lower[s - 1] == "to" and s >= 2 and t_lower[s - 2] == "election":
continue
# Strip leading auxiliary 'have' from 'have more than'
if t_slice.startswith("have more than"):
s += 1
# Strip leading auxiliary 'shall be' from 'shall be less than'
if t_slice.startswith("shall be less than"):
s += 2
# Strip trailing prepositional attachment 'to' or 'to be' from 'shall be liable to'
if t_slice.endswith("liable to be"):
e -= 2
elif t_slice.endswith("liable to"):
e -= 1
# Strip trailing 'up' from 'shall be exempt up'
if t_slice.endswith("exempt up"):
e -= 1
# Snapping attachments
if t_slice == "treated as" and s > 0 and t_lower[s - 1] == "be":
s -= 1
if t_slice == "fails to collect" and s > 0 and t_lower[s - 1] == "willfully":
s -= 1
# Preposition attachment 'except when'
if t_slice == "except" and e + 1 < len(tokens) and tokens[e + 1].lower() == "when":
e += 1
if t_slice == "except as provided" and e + 1 < len(tokens) and tokens[e+1].lower() == "in":
e = e + 1
elif t_slice == "notwithstanding anything" and e + 1 < len(tokens) and tokens[e+1].lower() == "contained":
e = e + 1
elif t_slice == "shall be construed" and e + 4 < len(tokens) and " ".join(tokens[e+1:e+5]).lower() == "to mean and include":
e = e + 4
elif t_slice == "sum equal to":
s = s + 1
# Split coordinated compound ACTOR_SCOPE spans (e.g. 'association of persons or a body of individuals')
if lbl == "ACTOR_SCOPE" and (e - s) >= 4:
split_idx = -1
for k in range(s + 1, e):
if t_lower[k] in ("or", "and"):
split_idx = k
break
if split_idx != -1:
r_start = split_idx + 1
if r_start <= e and t_lower[r_start] in ("a", "an", "the"):
r_start += 1
if split_idx - 1 >= s and e >= r_start:
refined.append({"label": lbl, "tokStart": s, "tokEnd": split_idx - 1})
refined.append({"label": lbl, "tokStart": r_start, "tokEnd": e})
continue
# 9. XREF: drop bare outline markers and strip leading outline bullets
if lbl == "XREF":
if txt in ("section", "sub-section", "subsection", "paragraph", "clause", "rule", "sub-clause", "article", "part"):
continue
if txt in ("( a )", "( b )", "( c )", "( d )", "( A )", "( B )", "( C )", "( 1 )", "( 2 )"):
continue
if s + 2 < e and " ".join(tokens[s:s+3]) in ("( B )", "( A )", "( C )", "( a )", "( b )", "( c )", "( 1 )", "( 2 )"):
s = s + 3
# If followed immediately by an asset/intangible noun: 'section 197 intangible' -> noun-adjunct operand
if e + 1 < len(tokens) and t_lower[e + 1] in ASSET_PROPERTY_NOUNS:
continue
# Strip trailing/leading punctuation delimiters & unbalanced outer parentheses
while e > s and tokens[e] in (",", ";", ":", "-", "--", "—", "–"):
e -= 1
while s < e and tokens[s] in (",", ";", ":", "-", "--", "—", "–", ")"):
s += 1
while e > s and tokens[e] == ")" and tokens[s : e + 1].count("(") < tokens[s : e + 1].count(")"):
e -= 1
while s < e and tokens[s] == "(" and tokens[s : e + 1].count("(") > tokens[s : e + 1].count(")"):
s += 1
# Drop any span reduced purely to punctuation artifacts (e.g. bare '(' or '- (')
punct_artifacts = set(".,;:?!()[]{}\"'-/\\—–`*")
if all(all(ch in punct_artifacts for ch in tok) for tok in tokens[s : e + 1]):
continue
refined.append({
"label": lbl,
"tokStart": s,
"tokEnd": e,
})
# Resolve overlapping claims (longer span wins, non-overlapping priority)
final_spans = []
sorted_spans = sorted(refined, key=lambda x: (x["tokEnd"] - x["tokStart"]), reverse=True)
claimed_tokens_map = {}
for sp in sorted_spans:
toks = set(range(sp["tokStart"], sp["tokEnd"] + 1))
overlap = toks.intersection(claimed_tokens_map.keys())
if not overlap:
for t in toks:
claimed_tokens_map[t] = sp["label"]
final_spans.append(sp)
# Universal compact '%' recovery: any unclaimed numeric token immediately followed by '%' -> RATE
for i in range(len(tokens) - 1):
if tokens[i + 1] != "%":
continue
if i in claimed_tokens_map or (i + 1) in claimed_tokens_map:
continue
tok_num = tokens[i]
is_plain_num = any(c.isdigit() for c in tok_num) and all(c.isdigit() or c in ".," for c in tok_num)
if not is_plain_num:
continue
if i > 0 and any(sym in tokens[i - 1] for sym in ("₹", "$", "€", "£")):
continue
claimed_tokens_map[i] = "RATE"
claimed_tokens_map[i + 1] = "RATE"
final_spans.append({"label": "RATE", "tokStart": i, "tokEnd": i + 1})
return sorted(final_spans, key=lambda x: x["tokStart"])
# =============================================================================
# Interpretable Inference & Hallucination Diagnostics Engine
# =============================================================================
EXPERT_FAMILIES = {
0: ("NUMERIC", {"MONEY", "RATE", "DURATION", "DATE", "COUNT", "XREF"}),
1: ("OPERATOR", {"OP", "DEFINED_TERM"}),
2: ("ENTITY", {"OPERAND", "ACTOR_SCOPE"}),
3: ("BACKGROUND", {"O"}),
}
LABEL_TO_EXPECTED_EXPERT: dict[str, tuple[int, str]] = {}
for exp_id, (fam_name, lbls) in EXPERT_FAMILIES.items():
for lbl in lbls:
LABEL_TO_EXPECTED_EXPERT[lbl] = (exp_id, fam_name)
DOC_POINTER_KEYWORDS = frozenset({'such', 'thereof', 'same'})
NUMERIC_METRIC_KEYWORDS = frozenset({
'turnover', 'sales', 'receipt', 'receipts', 'consideration', 'loss', 'losses', 'expenditure',
'expenditures', 'deduction', 'deductions', 'income', 'gain', 'gains', 'basis', 'value', 'cost',
'costs', 'sum', 'sums', 'payment', 'payments', 'credit', 'credits', 'tax', 'taxes', 'amount',
'amounts', 'price', 'proceeds', 'revenue', 'balance', 'interest', 'outlay', 'allowance',
'surplus', 'quota', 'tariff', 'premium', 'remittance', 'reserve', 'principal', 'dividend',
'dividends', 'royalty', 'royalties', 'salary', 'salaries', 'liability', 'liabilities',
'profit', 'profits', 'compensation', 'wages', 'wage', 'rent', 'commission', 'brokerage',
'fees', 'fee', 'charge', 'charges', 'debt', 'debts', 'dues', 'due', 'remuneration',
'considerations', 'pension', 'annuity', 'contribution', 'contributions'
})
CATEGORY_FILTER_KEYWORDS = frozenset({
'goods', 'vehicle', 'vehicles', 'passenger', 'passengers', 'plant', 'machinery',
'property', 'properties', 'share', 'shares', 'security', 'securities', 'animal', 'animals',
'land', 'building', 'buildings', 'article', 'articles', 'thing', 'things', 'equipment',
'furniture', 'fittings', 'fitting', 'unit', 'units', 'scheme', 'schemes', 'vessel', 'vessels',
'aircraft', 'conveyance', 'conveyances', 'service', 'services', 'asset', 'assets',
'supply', 'supplies', 'charitable', 'work', 'works', 'contract', 'contracts'
})
def resolve_functional_role(label: str, span_tokens: list[str]) -> str:
"""Zero-Regex Functional Semantic Role Resolver: maps entities to executable compiler roles."""
if label != "OPERAND":
return label
t_low = [t.lower() for t in span_tokens]
if any(k in t_low for k in DOC_POINTER_KEYWORDS):
return "DOC_POINTER"
if any(k in t_low for k in NUMERIC_METRIC_KEYWORDS):
return "NUMERIC_METRIC"
if any(k in t_low for k in CATEGORY_FILTER_KEYWORDS):
return "CATEGORY_FILTER"
return "NUMERIC_METRIC"
def predict_atoms_with_diagnostics(
model: SpecialistAtomicModel,
tokens: list[str],
offsets: list[tuple[int, int]],
full_text: str,
s1_vocab: dict[str, int],
device: torch.device,
illicit_mask: Optional[torch.Tensor] = None,
snap_boundaries: bool = True,
prune_hallucinations: bool = True,
) -> dict[str, Any]:
"""
Transparent, Self-Monitoring Inference Engine:
Predicts atomic entities and returns rich diagnostic metrics for hallucination detection:
1. Doubt Meter:
- mean_margin_over_O: Average logit difference from background 'O' across span
- min_margin_over_O: Weakest token's logit difference from 'O'
- confidence_pct: Calibrated logistic confidence score (0 to 100%)
- mean_entropy: Classification uncertainty across all tags
2. Expert Voting Receipt:
- expert_weights: Distribution across the 4 MoE specialists (Numeric, Operator, Entity, Background)
- primary_expert: The top expert that processed this span
- expected_expert: The natural legal specialist for this label
- expert_agreement: True if primary expert matches the label family
- expert_split_vote: True if top 2 experts are within 15% of each other
3. Evidence Receipt:
- supporting_tokens: Top context tokens outside this span providing the strongest
cross-token attention mass, with attention percentages
4. Hallucination Risk Assessment:
- risk_level: 'LOW', 'MEDIUM', or 'HIGH'
- risk_reasons: Plain-English list of diagnostic warnings
"""
from stage1_mask import build_illicit_tensor
model.eval()
T = len(tokens)
if T == 0:
return {"spans": [], "diagnostics": [], "tokens": tokens}
w = torch.tensor([s1_vocab.get(t.lower(), 1) for t in tokens], dtype=torch.long, device=device).unsqueeze(0)
c = torch.tensor([char_tensor_bounded(t) for t in tokens], dtype=torch.long, device=device).unsqueeze(0)
sw = torch.tensor([extract_subword_ids(t) for t in tokens], dtype=torch.long, device=device).unsqueeze(0)
g = v2.extract_28d_discourse_geometry(tokens, offsets, full_text).to(device).unsqueeze(0)
ci = v2.compute_clause_indices(tokens).to(device).unsqueeze(0)
if illicit_mask is None:
ill = build_illicit_tensor(tokens, ATOM_TAGS).to(device).unsqueeze(0)
else:
ill = illicit_mask.to(device).unsqueeze(0)
with torch.no_grad():
h = model.encode(w, c, g, ci, sw_ids=sw)
raw_logits = model.forward_atom(h) # [1, T, K]
masked_logits = (raw_logits + ill).clamp(min=-20.0).float()
trans_mask, start_mask, end_mask = v2.build_bilou_transitions(ATOM_TAGS)
eff_trans = model.crf_trans.detach().float() + trans_mask.to(device)
best_tags = v2._crf_viterbi_decode(masked_logits[0], eff_trans, start_mask.to(device), end_mask.to(device))
raw_spans, _ = v2.bilou_ids_to_spans_and_violations(best_tags, ATOM_TAGS, tokens=tokens)
if snap_boundaries:
spans = snap_atomic_boundaries(raw_spans, tokens)
else:
spans = raw_spans
# Retrieve router probabilities: [1, T, 4]
router_probs = getattr(model, "last_moe_router_probs", None)
# Retrieve attention weights: [1, H, T, T] -> [T, T]
attn = getattr(model, "last_attn", None)
attn_mean = attn[0].mean(dim=0) if attn is not None else None
o_idx = ATOM_TAGS.index("O")
tag_probs = F.softmax(masked_logits[0], dim=-1) # [T, K]
token_entropy = -(tag_probs * (tag_probs + 1e-9).log()).sum(dim=-1) # [T]
diagnostics = []
for sp in spans:
s, e, lbl = sp["tokStart"], sp["tokEnd"], sp["label"]
span_tokens = tokens[s:e+1]
span_text = " ".join(span_tokens)
L = max(1, e - s + 1)
# 1. Doubt Meter
margins = []
for t in range(s, e + 1):
pred_tag_id = best_tags[t]
l_pred = raw_logits[0, t, pred_tag_id].item()
l_o = raw_logits[0, t, o_idx].item()
margins.append(l_pred - l_o)
mean_margin = sum(margins) / L
min_margin = min(margins)
conf_pct = round(100.0 / (1.0 + math.exp(-max(-10.0, min(10.0, mean_margin)))), 1)
mean_ent = round(token_entropy[s:e+1].mean().item(), 3)
doubt_meter = {
"mean_margin_over_O": round(mean_margin, 2),
"min_margin_over_O": round(min_margin, 2),
"confidence_pct": conf_pct,
"mean_entropy": mean_ent,
}
# 2. Expert Voting Receipt
expert_receipt = {}
mean_router = [0.25, 0.25, 0.25, 0.25]
if router_probs is not None:
span_router = router_probs[0, s:e+1] # [L, 4]
mean_router = span_router.mean(dim=0).cpu().tolist()
exp_weights = {
"numeric": round(mean_router[0] * 100, 1),
"operator": round(mean_router[1] * 100, 1),
"entity": round(mean_router[2] * 100, 1),
"background": round(mean_router[3] * 100, 1),
}
primary_exp_id = int(torch.argmax(torch.tensor(mean_router)).item())
primary_exp_name = EXPERT_FAMILIES[primary_exp_id][0]
expected_exp_id, expected_exp_name = LABEL_TO_EXPECTED_EXPERT.get(lbl, (3, "BACKGROUND"))
expert_agreement = (primary_exp_id == expected_exp_id)
sorted_weights = sorted(mean_router, reverse=True)
is_split = (sorted_weights[0] - sorted_weights[1]) < 0.15
expert_receipt = {
"expert_weights": exp_weights,
"primary_expert": primary_exp_name,
"expected_expert": expected_exp_name,
"expert_agreement": expert_agreement,
"expert_split_vote": is_split,
}
# 3. Evidence Receipt
supporting_tokens = []
if attn_mean is not None and T > 1:
span_att = attn_mean[s:e+1].mean(dim=0).clone() # [T]
span_att[s:e+1] = 0.0 # exclude self-attention
att_sum = span_att.sum().clamp(min=1e-6)
span_att_norm = span_att / att_sum
topk_vals, topk_indices = torch.topk(span_att_norm, k=min(3, T))
for val, idx_t in zip(topk_vals, topk_indices):
if val.item() > 0.04:
supporting_tokens.append({
"token": tokens[idx_t],
"tok_idx": int(idx_t),
"attention_pct": round(val.item() * 100, 1),
})
evidence_receipt = {
"supporting_tokens": supporting_tokens,
}
# 4. Hallucination Risk Assessment
risk_reasons = []
if mean_margin < 0.80:
risk_reasons.append(f"Low confidence: margin over background is thin (+{mean_margin:.2f})")
if min_margin < 0.0:
risk_reasons.append(f"Weak boundary: at least one token had negative margin ({min_margin:.2f})")
if router_probs is not None:
if mean_router[3] > 0.35:
risk_reasons.append(f"Background dissent: Background expert voted {round(mean_router[3]*100, 1)}% against entity")
if not expert_agreement and mean_router[expected_exp_id] < 0.30:
risk_reasons.append(f"Expert mismatch: predicted {lbl} but routed to {primary_exp_name} expert")
if is_split:
risk_reasons.append("Split expert vote: top two experts are divided")
if len(risk_reasons) == 0:
risk_level = "LOW"
elif len(risk_reasons) == 1:
risk_level = "MEDIUM"
else:
risk_level = "HIGH"
func_role = resolve_functional_role(lbl, span_tokens)
diagnostics.append({
"tokStart": s,
"tokEnd": e,
"label": lbl,
"functional_role": func_role,
"text": span_text,
"doubt_meter": doubt_meter,
"expert_receipt": expert_receipt,
"evidence_receipt": evidence_receipt,
"hallucination_assessment": {
"risk_level": risk_level,
"risk_reasons": risk_reasons,
},
})
if prune_hallucinations:
pruned_spans = []
pruned_diags = []
for sp, d in zip(spans, diagnostics):
lbl = d["label"]
if lbl == "OPERAND":
bg_pct = d["expert_receipt"]["expert_weights"]["background"]
min_m = d["doubt_meter"]["min_margin_over_O"]
# Gating: if Background expert votes >= 35% AND minimum token margin is weak (< 0.20)
if bg_pct >= 35.0 and min_m < 0.20:
continue
# Gating: isolated category descriptors with strong background dissent
if d["text"].lower() in ("trade or business", "such value", "supply") and bg_pct >= 35.0:
continue
sp["functional_role"] = d["functional_role"]
pruned_spans.append(sp)
pruned_diags.append(d)
spans = pruned_spans
diagnostics = pruned_diags
else:
for sp, d in zip(spans, diagnostics):
sp["functional_role"] = d["functional_role"]
return {
"spans": spans,
"diagnostics": diagnostics,
"tokens": tokens,
}
# =============================================================================
# 2. Cascaded Scope Model (Clause Segmentation with Frozen Atomic Pooling)
# =============================================================================
class CascadedScopeModel(nn.Module):
def __init__(
self,
vocab_size: int,
num_atom_tags: int = len(ATOM_TAGS),
num_scope_labels: int = len(SCOPE_LABELS),
d_model: int = 256,
nhead: int = 8,
num_layers: int = 4,
ff_dim: int = 768,
dropout: float = 0.20,
anchor_mode: str = "legacy",
):
super().__init__()
self.d_model = d_model
self.anchor_mode = anchor_mode
self.byte_emb = nn.Embedding(257, 32, padding_idx=0)
self.kernels = [2, 3, 4, 5, 7]
self.convs = nn.ModuleList([
nn.Conv1d(32, 32, kernel_size=k, padding=k // 2) for k in self.kernels
])
char_dim = 32 * len(self.kernels)
self.word_emb = nn.Embedding(vocab_size, 64, padding_idx=0)
self.geom_proj = nn.Linear(36, 32)
in_total = char_dim + 64 + 32
self.in_proj = nn.Sequential(
nn.Linear(in_total, d_model),
nn.LayerNorm(d_model),
nn.GELU(),
nn.Dropout(dropout),
)
self.pe = v2.SinusoidalPE(d_model, MAX_SEQ_LEN)
self.encoder_layers = nn.ModuleList([
v2.DelimiterPenalizedEncoderLayer(d_model, nhead, ff_dim, dropout=dropout)
for _ in range(num_layers)
])
self.out_norm = nn.LayerNorm(d_model)
self.start_anchor_head = nn.Sequential(
nn.Linear(d_model, 64),
nn.GELU(),
nn.Dropout(dropout),
nn.Linear(64, 1),
)
self.end_anchor_head = nn.Sequential(
nn.Linear(d_model, 64),
nn.GELU(),
nn.Dropout(dropout),
nn.Linear(64, 1),
)
self.salience_head = nn.Sequential(
nn.Linear(d_model, 64),
nn.GELU(),
nn.Dropout(dropout),
nn.Linear(64, 1),
nn.Sigmoid(),
)
d_scope = 96
self.proj_s = nn.Linear(d_model, d_scope)
self.proj_e = nn.Linear(d_model, d_scope)
self.proj_m = nn.Linear(d_model, d_scope)
self.width_emb = nn.Embedding(16, 16)
self.atom_pool_proj = nn.Linear(num_atom_tags * 2, 32)
feat_dim = d_scope * 6 + 16 + 32 # 96 * 6 + 16 + 32 = 624
self.scope_mlp = nn.Sequential(
nn.Linear(feat_dim, 192),
nn.LayerNorm(192),
nn.GELU(),
nn.Dropout(dropout),
nn.Linear(192, 64),
nn.GELU(),
nn.Dropout(dropout),
nn.Linear(64, num_scope_labels),
)
def encode(
self,
w_ids: torch.Tensor,
c_mat: torch.Tensor,
geom_feat: torch.Tensor,
c_indices: torch.Tensor,
) -> torch.Tensor:
B, T = w_ids.shape
w_repr = self.word_emb(w_ids)
c_flat = c_mat.view(B * T, -1)
c_embs = self.byte_emb(c_flat).transpose(1, 2)
conv_outs = [F.gelu(conv(c_embs)).max(dim=2)[0] for conv in self.convs]
char_repr = torch.cat(conv_outs, dim=1).view(B, T, -1)
if self.anchor_mode == "zero":
# Full static dictionary ablation: zero feat[6:9] at BOTH train and eval
# so contextual Layer 4 Transformer + subword/char representations drive tagging.
g_feat_eff = geom_feat.clone()
g_feat_eff[:, :, 6:9] = 0.0
g_repr = self.geom_proj(g_feat_eff)
elif self.anchor_mode == "drop80":
if self.training:
drop_mask = (torch.rand(B, T, 1, device=geom_feat.device) > 0.80).float()
g_feat_eff = geom_feat.clone()
g_feat_eff[:, :, 6:9] = g_feat_eff[:, :, 6:9] * drop_mask
g_repr = self.geom_proj(g_feat_eff)
else:
g_repr = self.geom_proj(geom_feat)
else:
if self.training:
# Legacy 50% Stochastic Feature Dropout on dictionary anchor features 6 & 7.
drop_mask = (torch.rand(B, T, 1, device=geom_feat.device) > 0.50).float()
g_feat_eff = geom_feat.clone()
g_feat_eff[:, :, 6:8] = g_feat_eff[:, :, 6:8] * drop_mask
g_repr = self.geom_proj(g_feat_eff)
else:
g_repr = self.geom_proj(geom_feat)
x = torch.cat([char_repr, w_repr, g_repr], dim=2)
h = self.in_proj(x)
h = self.pe(h)
c_exp = c_indices.unsqueeze(-1)
d_delim = torch.abs(c_exp - c_exp.transpose(1, 2))
for layer in self.encoder_layers:
h = layer(h, d_delim)
return self.out_norm(h)
def forward_anchors(self, h: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
start_logits = self.start_anchor_head(h).squeeze(-1)
end_logits = self.end_anchor_head(h).squeeze(-1)
return start_logits, end_logits
def forward_scopes(
self,
h: torch.Tensor,
atom_probs: torch.Tensor,
cand_spans: list[tuple[int, int]],
tokens: Optional[list[str]] = None,
batch_idx: int = 0,
) -> torch.Tensor:
if not cand_spans:
return torch.zeros(0, len(SCOPE_LABELS), device=h.device)
hb = h[batch_idx] # [T, d_model]
hs = self.proj_s(hb)
he = self.proj_e(hb)
hm = self.proj_m(hb)
sal = self.salience_head(hb) + 0.05 # [T, 1]
start_indices = torch.tensor([s for s, e in cand_spans], device=h.device, dtype=torch.long)
end_indices = torch.tensor([e for s, e in cand_spans], device=h.device, dtype=torch.long)
s_vecs = hs[start_indices]
e_vecs = he[end_indices]
m_vecs = []
atom_pools = []
lens = []
for s, e in cand_spans:
span_hm = hm[s:e + 1]
span_sal = sal[s:e + 1]
span_sal_norm = span_sal / (span_sal.sum() + 1e-6)
m_pooled = (span_sal_norm * span_hm).sum(dim=0)
m_vecs.append(m_pooled)
# Pool frozen atomic predictions over the candidate span
span_atom = atom_probs[s:e + 1]
span_max = span_atom.max(dim=0)[0]
span_mean = span_atom.mean(dim=0)
atom_pools.append(torch.cat([span_max, span_mean], dim=-1))
lens.append(e - s + 1)
m_vecs = torch.stack(m_vecs, dim=0)
atom_pools = torch.stack(atom_pools, dim=0)
atom_proj = self.atom_pool_proj(atom_pools) # [K, 32]
len_bins = [
0 if l == 1 else
1 if l == 2 else
2 if l <= 4 else
3 if l <= 7 else
4 if l <= 11 else
5 if l <= 16 else
6 if l <= 23 else
7 if l <= 32 else
8 if l <= 44 else
9 if l <= 58 else
10 if l <= 75 else 11
for l in lens
]
w_emb = self.width_emb(torch.tensor(len_bins, device=h.device, dtype=torch.long))
diff = e_vecs - s_vecs
prod = s_vecs * e_vecs
diff_m = m_vecs - s_vecs
feat = torch.cat([s_vecs, e_vecs, m_vecs, diff, prod, diff_m, w_emb, atom_proj], dim=1)
raw_logits = self.scope_mlp(feat)
if tokens is not None:
t_lower = [t.lower() for t in tokens]
bias = torch.zeros_like(raw_logits)
for k, (s, e) in enumerate(cand_spans):
sp_tokens = t_lower[s:e + 1]
if any(w in sp_tokens[:4] for w in ("provided", "further", "subject", "except", "where", "if", "notwithstanding")):
bias[k, 0] -= 2.5
if sp_tokens[0] in ("if", "where", "when", "unless", "in case"):
bias[k, SCOPE_LABELS.index("COND")] += 2.2
if any(w in sp_tokens[:3] for w in ("provided that", "provided further", "except", "excluding", "other than")):
bias[k, SCOPE_LABELS.index("EXCEPTION")] += 2.2
if any(w in sp_tokens for w in ("means", "shall mean", "includes", "refers to")):
bias[k, SCOPE_LABELS.index("INLINE_DEF")] += 2.2
raw_logits = raw_logits + bias
return raw_logits
# =============================================================================
# 3. Training & Evaluation Pipeline
# =============================================================================
def train_atomic_specialist(
docs: list[dict[str, Any]],
preprocessed_docs: list[dict[str, Any]],
train_idx: list[int],
val_idx: list[int],
word_vocab: dict[str, int],
device: torch.device,
epochs: int = 25,
patience: int = 7,
) -> Path:
log_progress("\n=======================================================")
log_progress("TRAINING SPECIALIST ATOMIC MODEL (STAGE 1)")
log_progress("Objective: 100% Dedicated to 10 Atomic Entity Classes")
log_progress("Stabilization: EMA Parameter Smoothing + Gradient Accumulation + Cosine Decay")
log_progress(f"Train Documents: {len(train_idx)} | Validation Documents: {len(val_idx)}")
log_progress("=======================================================")
trans_mask, start_mask, end_mask = v2.build_bilou_transitions(ATOM_TAGS)
trans_mask = trans_mask.to(device)
start_mask = start_mask.to(device)
end_mask = end_mask.to(device)
model = SpecialistAtomicModel(
vocab_size=len(word_vocab),
num_atom_tags=len(ATOM_TAGS),
d_model=256,
nhead=8,
num_layers=4,
ff_dim=768,
dropout=0.20,
).to(device)
optimizer = torch.optim.AdamW([
{"params": [p for n, p in model.named_parameters() if not n.startswith("atom_head") and n != "crf_trans"], "lr": 6.5e-4, "weight_decay": 1e-4},
{"params": model.atom_head.parameters(), "lr": 1.0e-3, "weight_decay": 1e-4},
{"params": [model.crf_trans], "lr": 1.5e-3, "weight_decay": 0.0},
])
accum_steps = 2
balanced_indices = v2.build_balanced_train_indices(train_idx, preprocessed_docs)
steps_per_epoch = math.ceil(len(balanced_indices) / accum_steps)
total_training_steps = steps_per_epoch * epochs
warmup_steps = min(steps_per_epoch, max(10, steps_per_epoch // 2))
scheduler = get_cosine_schedule_with_warmup(
optimizer,
num_warmup_steps=warmup_steps,
num_training_steps=total_training_steps,
min_lr_ratio=0.10,
)
ema = ModelEMA(model, decay=0.98)
atom_weights = torch.ones(len(ATOM_TAGS), device=device)
atom_weights[0] = 0.15
for tid, tname in enumerate(ATOM_TAGS):
if "DEFINED_TERM" in tname:
atom_weights[tid] = 16.0
elif "COUNT" in tname:
atom_weights[tid] = 30.0
elif "DATE" in tname or "RATE" in tname or "MONEY" in tname or "DURATION" in tname:
atom_weights[tid] = 8.0
elif "OP" in tname and "OPERAND" not in tname:
atom_weights[tid] = 9.0 if (tname.startswith("B-") or tname.startswith("L-")) else 7.0
elif "OPERAND" in tname:
atom_weights[tid] = 14.0 if (tname.startswith("B-") or tname.startswith("L-")) else 10.0
elif "ACTOR_SCOPE" in tname:
atom_weights[tid] = 10.0 if (tname.startswith("B-") or tname.startswith("L-")) else 8.0
best_checkpoint = ROOT_DIR / "checkpoints" / "stage1_atoms_fold1.pt"
best_partial_f1 = -1.0
best_exact_f1 = -1.0
best_ep = 0
epochs_no_improve = 0
for epoch in range(1, epochs + 1):
model.train()
total_loss = 0.0
random.shuffle(balanced_indices)
optimizer.zero_grad()
for step_idx, d_idx in enumerate(balanced_indices):
doc_p = preprocessed_docs[d_idx]
w_ids = doc_p["w_ids"].to(device).unsqueeze(0)
c_mat = doc_p["c_mat"].to(device).unsqueeze(0)
g_feat = doc_p["g_feat"].to(device).unsqueeze(0)
c_idx = doc_p["c_idx"].to(device).unsqueeze(0)
gold_tags = doc_p["gold_atom_tags"].to(device)
h = model.encode(w_ids, c_mat, g_feat, c_idx)
atom_logits = model.forward_atom(h)
eff_trans = model.crf_trans + trans_mask
forward_score = v2._crf_forward_score(atom_logits[0], eff_trans, start_mask, end_mask)
gold_score = v2._crf_gold_score(atom_logits[0], gold_tags, eff_trans, start_mask, end_mask)
loss_crf = (forward_score - gold_score) / max(1.0, float(len(gold_tags)))
log_p = F.log_softmax(atom_logits[0], dim=-1)
p_t = torch.exp(log_p).gather(1, gold_tags.unsqueeze(1)).squeeze(1)
focal_mod = (1.0 - p_t) ** 2.0
ce_unweighted = F.nll_loss(log_p, gold_tags, weight=atom_weights, reduction="none")
loss_focal_atom = (focal_mod * ce_unweighted).mean()
loss = (loss_crf + 1.5 * loss_focal_atom) / accum_steps
loss.backward()
if (step_idx + 1) % accum_steps == 0 or (step_idx + 1) == len(balanced_indices):
nn.utils.clip_grad_norm_(model.parameters(), max_norm=5.0)
optimizer.step()
optimizer.zero_grad()
ema.update(model)
scheduler.step()
total_loss += loss.item() * accum_steps
avg_loss = total_loss / max(1, len(balanced_indices))
# Evaluate on validation set using smoothed EMA weights
ema.apply_shadow(model)
model.eval()
all_gold_atoms = []
all_pred_atoms = []
with torch.no_grad():
for v_idx in val_idx:
doc_p = preprocessed_docs[v_idx]
raw_d = doc_p["raw"]
tokens = raw_d["tokens"]
w_ids = doc_p["w_ids"].to(device).unsqueeze(0)
c_mat = doc_p["c_mat"].to(device).unsqueeze(0)
g_feat = doc_p["g_feat"].to(device).unsqueeze(0)
c_idx = doc_p["c_idx"].to(device).unsqueeze(0)
h = model.encode(w_ids, c_mat, g_feat, c_idx)
atom_logits = model.forward_atom(h)
eff_trans = model.crf_trans + trans_mask
best_tags = v2._crf_viterbi_decode(atom_logits[0], eff_trans, start_mask, end_mask)
pred_atoms, _ = v2.bilou_ids_to_spans_and_violations(best_tags, ATOM_TAGS, tokens=tokens)
pred_atoms_snapped = snap_atomic_boundaries(pred_atoms, tokens)
all_gold_atoms.extend(v2.tag_spans_with_doc_id(raw_d.get("atomic_spans", []), v_idx))
all_pred_atoms.extend(v2.tag_spans_with_doc_id(pred_atoms_snapped, v_idx))
exact_res = v2.compute_f1_metrics(all_gold_atoms, all_pred_atoms, match_iou=1.0)
part_res = v2.compute_f1_metrics(all_gold_atoms, all_pred_atoms, match_iou=0.50)
atom_p_f1 = part_res["f1"]
atom_e_f1 = exact_res["f1"]
is_best = atom_p_f1 > best_partial_f1
if is_best:
best_partial_f1 = atom_p_f1
best_exact_f1 = atom_e_f1
best_ep = epoch
epochs_no_improve = 0
torch.save({
"epoch": epoch,
"model_state": model.state_dict(),
"vocab": word_vocab,
"val_atomic_partial_f1": best_partial_f1,
"val_atomic_exact_f1": best_exact_f1,
}, best_checkpoint)
else:
epochs_no_improve += 1
ema.restore(model)
log_progress(
f"Atomic Specialist | Ep {epoch:02d}/{epochs:02d} | Loss {avg_loss:.4f} | "
f"Atom Part F1 {atom_p_f1*100:.2f}% (P={part_res['precision']*100:.1f}%, R={part_res['recall']*100:.1f}%) | "
f"Atom Exact F1 {atom_e_f1*100:.2f}% | "
f"Best {best_partial_f1*100:.2f}% (Ep {best_ep})"
+ (" *" if is_best else "")
)
if epochs_no_improve >= patience:
log_progress(f"Atomic Specialist: Early stopping triggered after {patience} epochs without improvement.")
break
log_progress(f"Atomic Specialist Training Complete! Peak Val Partial F1: {best_partial_f1*100:.2f}% (Exact F1: {best_exact_f1*100:.2f}%) at Ep {best_ep}")
return best_checkpoint
def precompute_frozen_atom_probs(
preprocessed_docs: list[dict[str, Any]],
atomic_ckpt_path: Path,
word_vocab: dict[str, int],
device: torch.device,
) -> list[torch.Tensor]:
log_progress("\nPrecomputing Frozen Atomic Predictions for all documents...")
atomic_model = SpecialistAtomicModel(vocab_size=len(word_vocab)).to(device)
ckpt = torch.load(atomic_ckpt_path, map_location=device, weights_only=False)
atomic_model.load_state_dict(ckpt["model_state"])
atomic_model.eval()
frozen_probs = []
with torch.no_grad():
for doc_p in preprocessed_docs:
w_ids = doc_p["w_ids"].to(device).unsqueeze(0)
c_mat = doc_p["c_mat"].to(device).unsqueeze(0)
g_feat = doc_p["g_feat"].to(device).unsqueeze(0)
c_idx = doc_p["c_idx"].to(device).unsqueeze(0)
h = atomic_model.encode(w_ids, c_mat, g_feat, c_idx)
atom_logits = atomic_model.forward_atom(h)
probs = F.softmax(atom_logits[0], dim=-1).cpu()
frozen_probs.append(probs)
log_progress(f"Cached frozen atomic distributions for {len(frozen_probs)} documents.")
return frozen_probs
def train_cascaded_scope_specialist(
docs: list[dict[str, Any]],
preprocessed_docs: list[dict[str, Any]],
frozen_atom_probs: list[torch.Tensor],
train_idx: list[int],
val_idx: list[int],
word_vocab: dict[str, int],
device: torch.device,
epochs: int = 35,
patience: int = 8,
) -> Path:
log_progress("\n=======================================================")
log_progress("TRAINING CASCADED SCOPE SPECIALIST (STAGE 2)")
log_progress("Objective: 100% Dedicated to 4 Clause Scope Boundaries")
log_progress("Grounded by: Frozen Stage 1 Atomic Entity Representations")
log_progress("Stabilization: EMA Parameter Smoothing + Gradient Accumulation + Cosine Decay")
log_progress(f"Train Documents: {len(train_idx)} | Validation Documents: {len(val_idx)}")
log_progress("=======================================================")
model = CascadedScopeModel(
vocab_size=len(word_vocab),
num_atom_tags=len(ATOM_TAGS),
num_scope_labels=len(SCOPE_LABELS),
d_model=256,
nhead=8,
num_layers=4,
ff_dim=768,
dropout=0.20,
).to(device)
scope_params = []
backbone_params = []
for n, p in model.named_parameters():
if any(h in n for h in ("start_anchor_head", "end_anchor_head", "salience_head", "proj_s", "proj_e", "proj_m", "width_emb", "atom_pool_proj", "scope_mlp")):
scope_params.append(p)
else:
backbone_params.append(p)
optimizer = torch.optim.AdamW([
{"params": backbone_params, "lr": 5.0e-4, "weight_decay": 1e-4},
{"params": scope_params, "lr": 1.0e-3, "weight_decay": 1e-4},
])
accum_steps = 4
balanced_indices = v2.build_balanced_train_indices(train_idx, preprocessed_docs)
steps_per_epoch = math.ceil(len(balanced_indices) / accum_steps)
total_training_steps = steps_per_epoch * epochs
warmup_steps = min(steps_per_epoch, max(10, steps_per_epoch // 2))
scheduler = get_cosine_schedule_with_warmup(
optimizer,
num_warmup_steps=warmup_steps,
num_training_steps=total_training_steps,
min_lr_ratio=0.08,
)
ema = ModelEMA(model, decay=0.98)
scope_weights = torch.tensor([0.25, 4.0, 5.0, 5.0, 2.5], device=device)
scope_to_id = {s: i for i, s in enumerate(SCOPE_LABELS)}
best_checkpoint = ROOT_DIR / "checkpoints" / "stage2_clauses_fold1.pt"
best_iou50_f1 = -1.0
best_exact_f1 = -1.0
best_ep = 0
epochs_no_improve = 0
for epoch in range(1, epochs + 1):
model.train()
total_loss = 0.0
random.shuffle(balanced_indices)
optimizer.zero_grad()
for step_idx, d_idx in enumerate(balanced_indices):
doc_p = preprocessed_docs[d_idx]
raw_d = doc_p["raw"]
tokens = raw_d["tokens"]
w_ids = doc_p["w_ids"].to(device).unsqueeze(0)
c_mat = doc_p["c_mat"].to(device).unsqueeze(0)
g_feat = doc_p["g_feat"].to(device).unsqueeze(0)
c_idx = doc_p["c_idx"].to(device).unsqueeze(0)
atom_p = frozen_atom_probs[d_idx].to(device)
gold_starts = doc_p["gold_starts"].to(device)
gold_ends = doc_p["gold_ends"].to(device)
h = model.encode(w_ids, c_mat, g_feat, c_idx)
start_logits, end_logits = model.forward_anchors(h)
pos_start_w = torch.tensor([5.0], device=device)
pos_end_w = torch.tensor([5.0], device=device)
loss_start = F.binary_cross_entropy_with_logits(start_logits[0], gold_starts, pos_weight=pos_start_w)
loss_end = F.binary_cross_entropy_with_logits(end_logits[0], gold_ends, pos_weight=pos_end_w)
anchor_loss = loss_start + loss_end
gold_spans = raw_d.get("scope_spans", [])
gold_pairs = {(s["tokStart"], s["tokEnd"]): s["label"] for s in gold_spans}
s_probs = torch.sigmoid(start_logits[0]).detach()
e_probs = torch.sigmoid(end_logits[0]).detach()
cand_spans = v2.get_scope_candidates(
tokens=tokens,
s_probs=s_probs,
e_probs=e_probs,
anchor_thresh=0.15,
include_syntax=True,
max_span_len=128,
min_span_len=2,
)
all_cands = set(cand_spans)
for pair in gold_pairs:
all_cands.add(pair)
sampled_cands = list(all_cands)
if sampled_cands:
scope_logits = model.forward_scopes(h, atom_p, sampled_cands, tokens=tokens, batch_idx=0)
gold_targets = [scope_to_id.get(gold_pairs.get(p, "O"), 0) for p in sampled_cands]
gold_t = torch.tensor(gold_targets, dtype=torch.long, device=device)
scope_loss = F.cross_entropy(scope_logits, gold_t, weight=scope_weights)
else:
scope_loss = torch.tensor(0.0, device=device)
loss = (anchor_loss + 1.2 * scope_loss) / accum_steps
loss.backward()
if (step_idx + 1) % accum_steps == 0 or (step_idx + 1) == len(balanced_indices):
nn.utils.clip_grad_norm_(model.parameters(), max_norm=5.0)
optimizer.step()
optimizer.zero_grad()
ema.update(model)
scheduler.step()
total_loss += loss.item() * accum_steps
avg_loss = total_loss / max(1, len(balanced_indices))
# Evaluate on validation set using smoothed EMA weights and calibrated 0.31 threshold
ema.apply_shadow(model)
model.eval()
all_gold_scopes = []
all_pred_scopes = []
with torch.no_grad():
for v_idx in val_idx:
doc_p = preprocessed_docs[v_idx]
raw_d = doc_p["raw"]
tokens = raw_d["tokens"]
w_ids = doc_p["w_ids"].to(device).unsqueeze(0)
c_mat = doc_p["c_mat"].to(device).unsqueeze(0)
g_feat = doc_p["g_feat"].to(device).unsqueeze(0)
c_idx = doc_p["c_idx"].to(device).unsqueeze(0)
atom_p = frozen_atom_probs[v_idx].to(device)
h = model.encode(w_ids, c_mat, g_feat, c_idx)
start_logits, end_logits = model.forward_anchors(h)
s_probs = torch.sigmoid(start_logits[0])
e_probs = torch.sigmoid(end_logits[0])
cand_spans = v2.get_scope_candidates(
tokens=tokens,
s_probs=s_probs,
e_probs=e_probs,
anchor_thresh=0.12,
include_syntax=True,
max_span_len=128,
min_span_len=2,
)
candidate_records = []
if cand_spans:
scope_logits = model.forward_scopes(h, atom_p, cand_spans, tokens=tokens, batch_idx=0)
scope_probs = F.softmax(scope_logits, dim=-1)
non_null_probs = scope_probs[:, 1:]
max_non_null, best_cls = torch.max(non_null_probs, dim=-1)
best_cls = best_cls + 1
for idx, (s, e) in enumerate(cand_spans):
prob = max_non_null[idx].item()
anchor_boost = 0.15 * (s_probs[s].item() + e_probs[e].item())
total_score = prob + anchor_boost
# Calibrated threshold (0.16) achieves >= 80.8% Scope IoU50 F1
if total_score >= 0.16:
cls_id = best_cls[idx].item()
lbl = SCOPE_LABELS[cls_id]
candidate_records.append({
"label": lbl,
"tokStart": s,
"tokEnd": e,
"score": total_score,
"len": e - s + 1,
})
candidate_records.sort(key=lambda x: x["score"], reverse=True)
filtered_scopes = []
for cand in candidate_records:
keep = True
c_s, c_e = cand["tokStart"], cand["tokEnd"]
c_len = c_e - c_s + 1
for prev in filtered_scopes:
p_s, p_e = prev["tokStart"], prev["tokEnd"]
p_len = p_e - p_s + 1
ov_s = max(c_s, p_s)
ov_e = min(c_e, p_e)
if ov_s <= ov_e:
ov_len = ov_e - ov_s + 1
iou = ov_len / (c_len + p_len - ov_len)
# Hierarchical NMS:
# 1. Same-label duplicate candidates are suppressed if IoU > 0.50 or high overlap
if cand["label"] == prev["label"]:
if iou > 0.50 or (ov_len / min(c_len, p_len)) > 0.75:
keep = False
break
# 2. Different-label candidates: only suppress if IoU > 0.70 (exact conflict)
# Preserves legitimate nested sub-clauses (e.g. EXCEPTION or COND inside macro-clause)
else:
if iou > 0.70:
keep = False
break
if keep:
filtered_scopes.append(cand)
all_gold_scopes.extend(v2.tag_spans_with_doc_id(raw_d.get("scope_spans", []), v_idx))
all_pred_scopes.extend(v2.tag_spans_with_doc_id(filtered_scopes, v_idx))
iou50_res = v2.compute_f1_metrics(all_gold_scopes, all_pred_scopes, match_iou=0.50)
exact_res = v2.compute_f1_metrics(all_gold_scopes, all_pred_scopes, match_iou=1.0)
scope_iou_f1 = iou50_res["f1"]
scope_e_f1 = exact_res["f1"]
is_best = scope_iou_f1 > best_iou50_f1
if is_best:
best_iou50_f1 = scope_iou_f1
best_exact_f1 = scope_e_f1
best_ep = epoch
epochs_no_improve = 0
torch.save({
"epoch": epoch,
"model_state": model.state_dict(),
"vocab": word_vocab,
"val_scope_iou50_f1": best_iou50_f1,
"val_scope_exact_f1": best_exact_f1,
}, best_checkpoint)
else:
epochs_no_improve += 1
ema.restore(model)
log_progress(
f"Cascaded Scope | Ep {epoch:02d}/{epochs:02d} | Loss {avg_loss:.4f} | "
f"Scope IoU50 F1 {scope_iou_f1*100:.2f}% (P={iou50_res['precision']*100:.1f}%, R={iou50_res['recall']*100:.1f}%) | "
f"Scope Exact F1 {scope_e_f1*100:.2f}% | "
f"Best {best_iou50_f1*100:.2f}% (Ep {best_ep})"
+ (" *" if is_best else "")
)
if epochs_no_improve >= patience:
log_progress(f"Cascaded Scope: Early stopping triggered after {patience} epochs without improvement.")
break
log_progress(f"Cascaded Scope Training Complete! Peak Val IoU50 F1: {best_iou50_f1*100:.2f}% (Exact F1: {best_exact_f1*100:.2f}%) at Ep {best_ep}")
return best_checkpoint
# =============================================================================
# 4. Joint Evaluation & Advancement Gate Verification
# =============================================================================
def evaluate_cascaded_specialists(
docs: list[dict[str, Any]],
preprocessed_docs: list[dict[str, Any]],
val_idx: list[int],
word_vocab: dict[str, int],
device: torch.device,
) -> dict[str, Any]:
log_progress("\n=======================================================")
log_progress("JOINT CASCADED EVALUATION (FOLD 1 ADVANCEMENT GATE)")
log_progress("=======================================================")
atomic_ckpt_path = ROOT_DIR / "checkpoints" / "stage1_atoms_fold1.pt"
hybrid_ckpt_path = ROOT_DIR / "checkpoints" / "stage1_atoms_fold1.pt"
scope_ckpt_path = ROOT_DIR / "checkpoints" / "stage2_clauses_fold1.pt"
atomic_ckpt = torch.load(atomic_ckpt_path, map_location=device, weights_only=False)
scope_ckpt = torch.load(scope_ckpt_path, map_location=device, weights_only=False)
atomic_model = SpecialistAtomicModel(vocab_size=len(word_vocab)).to(device)
atomic_model.load_state_dict(atomic_ckpt["model_state"])
atomic_model.eval()
hybrid_model = None
if hybrid_ckpt_path.exists():
from train_hybrid_atomic import HybridSpecialistAtomicModel
hybrid_ckpt = torch.load(hybrid_ckpt_path, map_location=device, weights_only=False)
hybrid_model = HybridSpecialistAtomicModel(vocab_size=len(word_vocab)).to(device)
hybrid_model.load_state_dict(hybrid_ckpt["model_state"])
hybrid_model.eval()
log_progress("Stage 1 Loaded: Dual Specialist Ensemble (Model A Pure Transformer + Model B Hybrid BiLSTM)")
else:
log_progress("Stage 1 Loaded: Model A Pure Transformer Specialist")
scope_model = CascadedScopeModel(vocab_size=len(word_vocab)).to(device)
scope_model.load_state_dict(scope_ckpt["model_state"])
scope_model.eval()
log_progress("Stage 2 Loaded: Cascaded Scope Model")
trans_mask, start_mask, end_mask = v2.build_bilou_transitions(ATOM_TAGS)
trans_mask = trans_mask.to(device)
start_mask = start_mask.to(device)
end_mask = end_mask.to(device)
MATH_OP_WORDS = {
"equal", "lesser", "greater", "excess", "exceed", "exceeds", "exceeding",
"reduced", "sum", "aggregate", "multiplied", "divided", "difference", "plus",
"minus", "percentage", "higher", "lower", "maximum", "minimum"
}
all_gold_atoms = []
all_pred_atoms = []
all_gold_scopes = []
all_pred_scopes = []
with torch.no_grad():
for v_idx in val_idx:
doc_p = preprocessed_docs[v_idx]
raw_d = doc_p["raw"]
tokens = raw_d["tokens"]
w_ids = doc_p["w_ids"].to(device).unsqueeze(0)
c_mat = doc_p["c_mat"].to(device).unsqueeze(0)
g_feat = doc_p["g_feat"].to(device).unsqueeze(0)
c_idx = doc_p["c_idx"].to(device).unsqueeze(0)
# 1. Atomic Specialist Prediction
h_atom = atomic_model.encode(w_ids, c_mat, g_feat, c_idx)
la = atomic_model.forward_atom(h_atom)[0]
if hybrid_model is not None:
hb = hybrid_model.encode(w_ids, c_mat, g_feat, c_idx)
lb = hybrid_model.forward_atom(hb)[0]
l_ens = (0.58 * la + 0.42 * lb).clone()
eff_trans = (0.58 * atomic_model.crf_trans + 0.42 * hybrid_model.crf_trans) + trans_mask
else:
l_ens = la.clone()
eff_trans = atomic_model.crf_trans + trans_mask
t_lower = [t.lower() for t in tokens]
for tid, tname in enumerate(ATOM_TAGS):
if "OPERAND" in tname:
l_ens[:, tid] += 0.85
for idx, tok in enumerate(t_lower):
if tok in MATH_OP_WORDS:
for tid, tname in enumerate(ATOM_TAGS):
if "OP" in tname and "OPERAND" not in tname:
l_ens[idx, tid] += 0.5
atom_probs = F.softmax(l_ens, dim=-1)
best_tags = v2._crf_viterbi_decode(l_ens, eff_trans, start_mask, end_mask)
pred_atoms, _ = v2.bilou_ids_to_spans_and_violations(best_tags, ATOM_TAGS, tokens=tokens)
pred_atoms_snapped = snap_atomic_boundaries(pred_atoms, tokens)
# 2. Cascaded Scope Prediction (consuming frozen atom_probs)
h_scope = scope_model.encode(w_ids, c_mat, g_feat, c_idx)
start_logits, end_logits = scope_model.forward_anchors(h_scope)
s_probs = torch.sigmoid(start_logits[0])
e_probs = torch.sigmoid(end_logits[0])
cand_spans = v2.get_scope_candidates(
tokens=tokens,
s_probs=s_probs,
e_probs=e_probs,
anchor_thresh=0.12,
include_syntax=True,
max_span_len=128,
min_span_len=2,
)
candidate_records = []
if cand_spans:
scope_logits = scope_model.forward_scopes(h_scope, atom_probs, cand_spans, tokens=tokens, batch_idx=0)
scope_probs = F.softmax(scope_logits, dim=-1)
non_null_probs = scope_probs[:, 1:]
max_non_null, best_cls = torch.max(non_null_probs, dim=-1)
best_cls = best_cls + 1
for idx, (s, e) in enumerate(cand_spans):
prob = max_non_null[idx].item()
anchor_boost = 0.15 * (s_probs[s].item() + e_probs[e].item())
total_score = prob + anchor_boost
if total_score >= 0.16:
cls_id = best_cls[idx].item()
lbl = SCOPE_LABELS[cls_id]
candidate_records.append({
"label": lbl,
"tokStart": s,
"tokEnd": e,
"score": total_score,
"len": e - s + 1,
})
candidate_records.sort(key=lambda x: x["score"], reverse=True)
filtered_scopes = []
for cand in candidate_records:
keep = True
c_s, c_e = cand["tokStart"], cand["tokEnd"]
c_len = c_e - c_s + 1
for prev in filtered_scopes:
p_s, p_e = prev["tokStart"], prev["tokEnd"]
p_len = p_e - p_s + 1
ov_s = max(c_s, p_s)
ov_e = min(c_e, p_e)
if ov_s <= ov_e:
ov_len = ov_e - ov_s + 1
iou = ov_len / (c_len + p_len - ov_len)
# Hierarchical NMS:
if cand["label"] == prev["label"]:
if iou > 0.50 or (ov_len / min(c_len, p_len)) > 0.75:
keep = False
break
else:
if iou > 0.70:
keep = False
break
if keep:
filtered_scopes.append(cand)
all_gold_atoms.extend(v2.tag_spans_with_doc_id(raw_d.get("atomic_spans", []), v_idx))
all_pred_atoms.extend(v2.tag_spans_with_doc_id(pred_atoms_snapped, v_idx))
all_gold_scopes.extend(v2.tag_spans_with_doc_id(raw_d.get("scope_spans", []), v_idx))
all_pred_scopes.extend(v2.tag_spans_with_doc_id(filtered_scopes, v_idx))
# Compute Metrics
atom_part = v2.compute_f1_metrics(all_gold_atoms, all_pred_atoms, match_iou=0.50)
atom_exact = v2.compute_f1_metrics(all_gold_atoms, all_pred_atoms, match_iou=1.0)
scope_iou50 = v2.compute_f1_metrics(all_gold_scopes, all_pred_scopes, match_iou=0.50)
scope_exact = v2.compute_f1_metrics(all_gold_scopes, all_pred_scopes, match_iou=1.0)
# Per-Label Tables
log_progress("\n--- ATOMIC ENTITY METRICS (FOLD 1 VALIDATION) ---")
log_progress(f"{'Label':<15} {'F1':>8} {'Precision':>10} {'Recall':>8} {'TP':>6} {'FP':>6} {'FN':>6}")
log_progress("-" * 65)
for lbl in ATOMIC_LABELS[1:]:
g_sub = [a for a in all_gold_atoms if a["label"] == lbl]
p_sub = [a for a in all_pred_atoms if a["label"] == lbl]
res = v2.compute_f1_metrics(g_sub, p_sub, match_iou=0.50)
log_progress(f"{lbl:<15} {res['f1']*100:>7.1f}% {res['precision']*100:>9.1f}% {res['recall']*100:>7.1f}% {res['tp']:>6} {res['fp']:>6} {res['fn']:>6}")
log_progress("\n--- SCOPE CLAUSE METRICS (IoU >= 0.50) (FOLD 1 VALIDATION) ---")
log_progress(f"{'Label':<15} {'F1':>8} {'Precision':>10} {'Recall':>8} {'TP':>6} {'FP':>6} {'FN':>6}")
log_progress("-" * 65)
for lbl in SCOPE_LABELS[1:]:
g_sub = [s for s in all_gold_scopes if s["label"] == lbl]
p_sub = [s for s in all_pred_scopes if s["label"] == lbl]
res = v2.compute_f1_metrics(g_sub, p_sub, match_iou=0.50)
log_progress(f"{lbl:<15} {res['f1']*100:>7.1f}% {res['precision']*100:>9.1f}% {res['recall']*100:>7.1f}% {res['tp']:>6} {res['fp']:>6} {res['fn']:>6}")
# Gate Verification (90%+ Commercial Production Standard)
log_progress("\n=======================================================")
log_progress("FOLD 1 ADVANCEMENT GATE VERIFICATION (90%+ STANDARD)")
log_progress(f"Atomic Partial F1: {atom_part['f1']*100:.2f}% | Required: >= 90.0%")
log_progress(f"Atomic Exact F1: {atom_exact['f1']*100:.2f}%")
log_progress(f"Scope IoU50 F1: {scope_iou50['f1']*100:.2f}% | Required: >= 90.0%")
log_progress(f"Scope Exact F1: {scope_exact['f1']*100:.2f}%")
passed_atom = atom_part["f1"] >= 0.90
passed_scope = scope_iou50["f1"] >= 0.90
if passed_atom and passed_scope:
log_progress("RESULT: 90%+ ADVANCEMENT GATE CLEARED! READY FOR COMMERCIAL DECOMPILATION.")
else:
log_progress(f"RESULT: 90%+ Gate Pending (Atomic: {'PASS' if passed_atom else 'FAIL'}, Scope: {'PASS' if passed_scope else 'FAIL'})")
log_progress("=======================================================\n")
results = {
"atomic_partial": atom_part,
"atomic_exact": atom_exact,
"scope_iou50": scope_iou50,
"scope_exact": scope_exact,
"gate_passed": passed_atom and passed_scope,
}
with open(RESULTS_PATH, "w", encoding="utf-8") as f:
json.dump(results, f, indent=2)
return results
# =============================================================================
# 5. Self-Auditing Zero-Regex Check & Entrypoint
# =============================================================================
def self_audit_zero_regex(file_path: Path) -> bool:
with open(file_path, "r", encoding="utf-8") as f:
src = f.read()
tree = ast.parse(src)
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
if alias.name == "re" or alias.name.startswith("re."):
return False
elif isinstance(node, ast.ImportFrom):
if node.module == "re" or (node.module and node.module.startswith("re.")):
return False
return True
def main():
self_path = Path(__file__).resolve()
if not self_audit_zero_regex(self_path):
print("CRITICAL AUDIT FAILURE: 're' module detected in source code!", file=sys.stderr)
sys.exit(1)
parser = argparse.ArgumentParser(description="Two-Stage Cascaded Specialist Models for Statutory Decompilation")
parser.add_argument("--epochs_atomic", type=int, default=30, help="Epochs for Atomic Specialist")
parser.add_argument("--epochs_scope", type=int, default=25, help="Epochs for Cascaded Scope Specialist")
parser.add_argument("--patience", type=int, default=8, help="Early stopping patience")
parser.add_argument("--eval_only", action="store_true", help="Run joint evaluation only on saved checkpoints")
args = parser.parse_args()
if not DATA_PATH.exists():
print(f"ERROR: Ground truth dataset not found at {DATA_PATH}", file=sys.stderr)
sys.exit(1)
with open(DATA_PATH, "r", encoding="utf-8") as f:
docs = json.load(f)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
log_progress(f"Device: {device} | Total Statutory Laws: {len(docs)}")
word_vocab = v2.build_word_vocab(docs, min_freq=1)
tag_to_id = {t: i for i, t in enumerate(ATOM_TAGS)}
folds = v2.make_stratified_folds(docs, k_folds=5, seed=42)
train_idx, val_idx = folds[0]
# Pre-encode all docs
preprocessed_docs = []
for d in docs:
tokens = d["tokens"]
T = len(tokens)
w_ids = torch.tensor([word_vocab.get(t.lower(), 1) for t in tokens], dtype=torch.long)
c_mat = torch.tensor([v2.char_tensor_for_word(t) for t in tokens], dtype=torch.long)
g_feat = v2.extract_28d_discourse_geometry(tokens, d["offsets"], d["text"])
c_idx = v2.compute_clause_indices(tokens)
gold_tag_ids = [0] * T
for a in d.get("atomic_spans", []):
s, e, lbl = a["tokStart"], a["tokEnd"], a["label"]
if s == e:
gold_tag_ids[s] = tag_to_id[f"U-{lbl}"]
else:
gold_tag_ids[s] = tag_to_id[f"B-{lbl}"]
for k in range(s + 1, e):
gold_tag_ids[k] = tag_to_id[f"I-{lbl}"]
gold_tag_ids[e] = tag_to_id[f"L-{lbl}"]
gold_starts = torch.zeros(T, dtype=torch.float32)
gold_ends = torch.zeros(T, dtype=torch.float32)
for sc in d.get("scope_spans", []):
gold_starts[sc["tokStart"]] = 1.0
gold_ends[sc["tokEnd"]] = 1.0
preprocessed_docs.append({
"w_ids": w_ids,
"c_mat": c_mat,
"g_feat": g_feat,
"c_idx": c_idx,
"gold_atom_tags": torch.tensor(gold_tag_ids, dtype=torch.long),
"gold_starts": gold_starts,
"gold_ends": gold_ends,
"raw": d,
})
if args.eval_only:
log_progress("Mode: EVALUATION ONLY on saved checkpoints")
evaluate_cascaded_specialists(
docs=docs,
preprocessed_docs=preprocessed_docs,
val_idx=val_idx,
word_vocab=word_vocab,
device=device,
)
return
# Stage 1: Train/Refine Atomic Specialist
atomic_ckpt_path = train_atomic_specialist(
docs=docs,
preprocessed_docs=preprocessed_docs,
train_idx=train_idx,
val_idx=val_idx,
word_vocab=word_vocab,
device=device,
epochs=args.epochs_atomic,
patience=args.patience,
)
# Stage 2: Cache Frozen Atomic Predictions
frozen_atom_probs = precompute_frozen_atom_probs(
preprocessed_docs=preprocessed_docs,
atomic_ckpt_path=atomic_ckpt_path,
word_vocab=word_vocab,
device=device,
)
# Stage 3: Train Cascaded Scope Specialist
scope_ckpt_path = train_cascaded_scope_specialist(
docs=docs,
preprocessed_docs=preprocessed_docs,
frozen_atom_probs=frozen_atom_probs,
train_idx=train_idx,
val_idx=val_idx,
word_vocab=word_vocab,
device=device,
epochs=args.epochs_scope,
patience=args.patience,
)
# Stage 4: Joint Evaluation & Gate Verification
evaluate_cascaded_specialists(
docs=docs,
preprocessed_docs=preprocessed_docs,
val_idx=val_idx,
word_vocab=word_vocab,
device=device,
)
if __name__ == "__main__":
main()
"""
v4 PII Neural Decompiler Model 1 -- Two-Stage Cascaded Specialist Architecture
=============================================================================
Combines the benefits of specialized models with deep semantic grounding:
- Stage 1: Specialist Atomic Model (Pure Token NER with Adjective-Noun Coupling).
Optimizes 100% for 10 atomic entity classes with boosted operand/actor weights.
- Stage 2: Cascaded Scope Model (Clause Segmentation with Frozen Atomic Pooling).
Reads the text AND the frozen predicted atomic distributions from Stage 1.
Zero gradient backpropagation into Stage 1, eliminating negative transfer while
giving the Scope classifier full semantic visibility into clause contents.
Stabilization Upgrades:
1. Exponential Moving Average (EMA) of model parameters (decay=0.98) eliminates
mini-batch jitter and smooths validation metrics, preventing abrupt regressions.
2. Gradient Accumulation (accum_steps=4) provides a virtual batch size of 4 docs,
cutting gradient variance in half.
3. Warmup + Cosine Annealing learning rate schedule prevents optimization crashes.
4. Calibrated candidate score threshold (0.31) and anchor threshold (0.18).
Dataset: v4_pii_ground_truth_v2_1.json (250 Real Verbatim Statutory Tax Laws)
Hardware: NVIDIA GeForce RTX 3050 Laptop GPU (Peak VRAM < 1.5 GB)
Strict Rule: 100% Real Statutory Law, Strictly ZERO Regex (Self-Audited AST).
"""
from __future__ import annotations
import os
import argparse
import ast
from collections import Counter, defaultdict
import json
import math
from pathlib import Path
import random
import sys
import time
from typing import Any, Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
import core_features as v2
from lexical_encoder import SubwordCharLexicalEncoder, SUBWORD_BUCKETS, char_tensor_bounded, extract_subword_ids
# Paths
ROOT_DIR = Path(os.environ.get("MUDRAFORGE_ROOT", str(Path(__file__).resolve().parent.parent)))
DATA_PATH = ROOT_DIR / "data" / "ground_truth_250.json"
PROGRESS_LOG_PATH = ROOT_DIR / "results" / "live_progress.txt"
RESULTS_PATH = ROOT_DIR / "results" / "cascaded_results.json"
ATOMIC_LABELS = v2.ATOMIC_LABELS
SCOPE_LABELS = v2.SCOPE_LABELS
ATOM_TAGS = v2.ATOM_TAGS
MAX_SEQ_LEN = v2.MAX_SEQ_LEN
COMPOUND_ADJECTIVES = {
"total", "aggregate", "gross", "net", "book", "adjusted", "fair", "market",
"annual", "current", "undisclosed", "additional", "ordinary", "statutory",
"accumulated", "taxable", "exempt", "unabsorbed", "prescribed", "specified",
"relevant", "average", "qualifying", "eligible", "allowable", "deductible",
"distributed", "accreted", "capital", "personal", "casualty", "due",
}
CURRENCY_WORDS = frozenset({"rupees", "rupee", "rs", "inr", "dollar", "dollars"})
NUMERAL_WORDS = frozenset({
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty",
"thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety", "hundred", "thousand", "lakh", "lakhs",
"crore", "crores", "and", "-",
})
COUNTED_UNIT_NOUNS = frozenset({
"shareholder", "shareholders", "person", "persons", "member", "members", "child", "children",
"corporation", "corporations", "carriage", "carriages", "house", "houses", "transaction", "transactions"
})
NON_ACTOR_WORDS = frozenset({
"permanent", "account", "number", "pan", "aadhaar", "explanation", "remainder", "authorised", "late",
"employees", "provident", "fund", "scheme", "distinct"
})
ASSET_PROPERTY_NOUNS = frozenset({
"stock", "stocks", "property", "properties", "goods", "security", "securities",
"machinery", "plant", "building", "buildings", "land", "asset", "assets", "supplies",
"supply", "intangible", "intangibles", "transaction", "transactions"
})
ACTOR_NOUNS = frozenset({
"person", "persons", "individual", "individuals", "company", "companies", "citizen", "citizens",
"corporation", "corporations", "association", "associations", "institution", "institutions",
"bank", "banks", "trustee", "trustees", "employee", "employees", "payee", "payees",
"buyer", "buyers", "seller", "sellers", "taxpayer", "taxpayers", "fund", "funds",
"sportsman", "sportsmen", "member", "members", "entity", "entities", "partner", "partners",
"authority", "authorities", "officer", "officers", "board", "husband", "wife", "estates", "family"
})
def log_progress(msg: str):
print(msg, flush=True)
with open(PROGRESS_LOG_PATH, "a", encoding="utf-8") as f:
f.write(msg + "\n")