Download src/span_pooler.py from yamero999/law2code: direct link, hf CLI and curl.
- Browser
- Download file 7.64 kB
-
https://huggingface.co/spaces/yamero999/law2code/resolve/main/src/span_pooler.py
- Command line
-
hf download hf://spaces/yamero999/law2code/src/span_pooler.py
-
curl -L -o span_pooler.py https://huggingface.co/spaces/yamero999/law2code/resolve/main/src/span_pooler.py
7.64 kB
| """ | |
| Zero-Regex Context-Aware Span Pooler for Hierarchical Statutory AST Routing | |
| =========================================================================== | |
| Extracts fixed-dimensional, context-enriched span representations: | |
| v_span = Linear([AttnPool(h_s..e) ; h_s ; h_e ; h_{s-1} ; h_{e+1} ; WidthEmb ; GeomFeat]) | |
| Compiler-Grade Invariants: | |
| 1. Decoupled from sequence length: 1 single vector per candidate span. | |
| 2. Single-token safe (s == e): left (h_{s-1}) and right (h_{e+1}) boundary tokens | |
| preserve governing syntactic context (e.g. 'purchase of [goods]'), preventing | |
| representation collapse. | |
| 3. Strictly ZERO regex (AST self-audited). | |
| """ | |
| from __future__ import annotations | |
| import math | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| ATTEST_ANCHOR_KEYWORDS = frozenset({ | |
| "pan", "permanent account", "aadhaar", "invoice", "return", "udyam", "registration", | |
| "certificate", "form", "bill of supply", "debit note", "credit note", | |
| }) | |
| MODAL_VERBS = frozenset({"shall", "may", "must", "will", "can", "should", "would", "could"}) | |
| ACTION_VERBS = frozenset({ | |
| "deduct", "collect", "pay", "credit", "furnish", "file", "apply", "prescribe", "make", | |
| "exceed", "deem", "allow", "reduce", "charge", "withhold", "assess", "remit", | |
| }) | |
| PREPOSITION_WORDS = frozenset({ | |
| "for", "from", "under", "in", "to", "by", "of", "with", "at", "as", "upon", "where", | |
| "which", "whereas", "pursuant", "thereof", "therein", "thereon", "thereunder", "against", "between", | |
| }) | |
| MODIFIER_CONNECTIVES = frozenset({ | |
| "or", "and", "thousand", "hundred", "religious", "productive", "distinct", "relevant", "facility", | |
| }) | |
| class SpanAttentionPooling(nn.Module): | |
| """Learned multi-head attention pooling across token slices.""" | |
| def __init__(self, d_model: int = 256, n_heads: int = 4): | |
| super().__init__() | |
| self.d_model = d_model | |
| self.query = nn.Parameter(torch.randn(n_heads, d_model // n_heads) * 0.02) | |
| self.proj = nn.Linear(d_model, d_model) | |
| def forward(self, h_span: torch.Tensor) -> torch.Tensor: | |
| # h_span: (L, D) | |
| L, D = h_span.shape | |
| if L == 1: | |
| return h_span[0] | |
| n_heads = self.query.shape[0] | |
| head_dim = D // n_heads | |
| h_reshaped = h_span.view(L, n_heads, head_dim) # (L, H, D_h) | |
| # Dot product with learned query per head | |
| scores = (h_reshaped * self.query.unsqueeze(0)).sum(dim=-1) / math.sqrt(head_dim) # (L, H) | |
| attn = F.softmax(scores, dim=0).unsqueeze(-1) # (L, H, 1) | |
| pooled = (h_reshaped * attn).sum(dim=0).view(D) # (D,) | |
| return self.proj(pooled) | |
| class StatutorySpanPooler(nn.Module): | |
| """ | |
| Extracts rich span embeddings from encoder sequence representations, | |
| incorporating boundary context and learned span width. | |
| """ | |
| def __init__( | |
| self, | |
| d_model: int = 256, | |
| d_out: int = 256, | |
| max_width: int = 32, | |
| d_width: int = 32, | |
| d_geom: int = 36, | |
| dropout: float = 0.15, | |
| ): | |
| super().__init__() | |
| self.d_model = d_model | |
| self.max_width = max_width | |
| self.d_geom = d_geom | |
| self.attn_pool = SpanAttentionPooling(d_model=d_model, n_heads=4) | |
| self.width_embedding = nn.Embedding(max_width, d_width) | |
| # [AttnPool (256) + Start (256) + End (256) + LeftContext (256) + RightContext (256) + Width (32) + Geomx4 (144) + StatutoryAnchors (6)] | |
| in_dim = (d_model * 5) + d_width + (d_geom * 4) + 6 | |
| self.out_proj = nn.Sequential( | |
| nn.Linear(in_dim, d_out), | |
| nn.LayerNorm(d_out), | |
| nn.GELU(), | |
| nn.Dropout(dropout), | |
| nn.Linear(d_out, d_out), | |
| nn.LayerNorm(d_out), | |
| ) | |
| def pool_single_span( | |
| self, | |
| h_seq: torch.Tensor, # (T, D) | |
| g_seq: torch.Tensor, # (T, 36) | |
| s: int, | |
| e: int, | |
| span_text: str = "", | |
| ) -> torch.Tensor: | |
| T, D = h_seq.shape | |
| s = max(0, min(T - 1, s)) | |
| e = max(s, min(T - 1, e)) | |
| # 1. Attention Pooled Inner Span | |
| h_slice = h_seq[s : e + 1] | |
| h_attn = self.attn_pool(h_slice) | |
| # 2. Boundary Tokens | |
| h_s = h_seq[s] | |
| h_e = h_seq[e] | |
| # 3. Context Boundaries (Outside governing tokens, zero-padded at edges) | |
| h_left = h_seq[s - 1] if s > 0 else torch.zeros(D, device=h_seq.device, dtype=h_seq.dtype) | |
| h_right = h_seq[e + 1] if e < T - 1 else torch.zeros(D, device=h_seq.device, dtype=h_seq.dtype) | |
| # 4. Learned Width Embedding (clamped to max_width - 1) | |
| w_idx = min(self.max_width - 1, max(0, e - s)) | |
| w_emb = self.width_embedding(torch.tensor(w_idx, device=h_seq.device)) | |
| # 5. Span Syntactic & Discourse Geometry (Mean, Peak indicators, Left & Right boundary syntax) | |
| g_slice = g_seq[s : e + 1] | |
| g_mean = g_slice.mean(dim=0) | |
| g_max, _ = g_slice.max(dim=0) | |
| g_left = g_seq[s - 1] if s > 0 else torch.zeros(self.d_geom, device=g_seq.device, dtype=g_seq.dtype) | |
| g_right = g_seq[e + 1] if e < T - 1 else torch.zeros(self.d_geom, device=g_seq.device, dtype=g_seq.dtype) | |
| # 6. Zero-Regex 6-D Statutory Structural Anchor Vector | |
| words = [w.strip(" ,.-;:()[]\"'") for w in span_text.lower().split() if w.strip(" ,.-;:()[]\"'")] | |
| span_lower = span_text.lower() | |
| s_anchor = torch.zeros(6, device=h_seq.device, dtype=h_seq.dtype) | |
| # 0: Attestation Document Anchor (pan, permanent account, aadhaar, return, udyam, invoice, certificate) | |
| if any(k in span_lower for k in ATTEST_ANCHOR_KEYWORDS) or any(w in ATTEST_ANCHOR_KEYWORDS for w in words): | |
| s_anchor[0] = 1.0 | |
| # 1: Statutory Operand Noun Discourse Anchor (feature dim 7 in geometry vector) | |
| if g_slice[:, 7].max().item() > 0.5: | |
| s_anchor[1] = 1.0 | |
| # 2: Modal Verb Anchor (shall, may, must, will, can) | |
| if any(w in MODAL_VERBS for w in words): | |
| s_anchor[2] = 1.0 | |
| # 3: Action Verb Anchor (deduct, collect, pay, credit, furnish, make, or ends with -ed, -ing) | |
| if any(w in ACTION_VERBS or (len(w) > 3 and (w.endswith("ed") or w.endswith("ing"))) for w in words): | |
| s_anchor[3] = 1.0 | |
| # 4: Syntactic Preposition Anchor (for, from, under, in, to, by, of) | |
| if any(w in PREPOSITION_WORDS for w in words): | |
| s_anchor[4] = 1.0 | |
| # 5: Modifier / Trailing Connective Anchor (or, and, thousand, hundred) | |
| if any(w in MODIFIER_CONNECTIVES for w in words): | |
| s_anchor[5] = 1.0 | |
| # Concatenate full feature vector (in_dim = 1462) | |
| feat = torch.cat([h_attn, h_s, h_e, h_left, h_right, w_emb, g_mean, g_max, g_left, g_right, s_anchor], dim=0) | |
| return self.out_proj(feat.unsqueeze(0)).squeeze(0) # (d_out,) | |
| def pool_spans( | |
| self, | |
| h_seq: torch.Tensor, # (T, D) | |
| g_seq: torch.Tensor, # (T, 36) | |
| spans: list[tuple[int, int]], | |
| span_texts: list[str] | None = None, | |
| ) -> torch.Tensor: | |
| """Pools a batch of spans from one sequence into (N_spans, d_out).""" | |
| if not spans: | |
| return torch.zeros((0, self.d_model), device=h_seq.device) | |
| if span_texts is None: | |
| span_texts = [""] * len(spans) | |
| vecs = [self.pool_single_span(h_seq, g_seq, s, e, txt) for (s, e), txt in zip(spans, span_texts)] | |
| return torch.stack(vecs, dim=0) | |