File size: 10,951 Bytes
7215e83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
"""

Boundary-Aware Subword & 3-Zone Positional Character Lexical Encoder

====================================================================

Reusable lexical representation layer designed for open-vocabulary statutory NER

and Layer 4 Whole-Word Masked Statutory Language Modeling (MLM) pretraining.



Components:

  1. Layer 1 -- Boundary-Aware Subword 3-5-gram Bag (8,192 deterministic CRC32 buckets):

     Wraps each lowercase token as "<word>", extracts 3-, 4-, and 5-character n-grams,

     hashes deterministically into buckets 1..8192 (0=pad, 8193=MLM [MASK]), and pools

     with exact 1/sqrt(N) variance-preserving scaling + LayerNorm stream balancing.

  2. Layer 2 -- Boundary-Aware 3-Zone Positional Character CNN (Prefix / Root / Suffix):

     Wraps raw UTF-8 bytes with dedicated BOS (257), EOS (258), and MLM MASK (259) IDs,

     runs multi-scale Conv1d (kernels 2,3,4,5,7), pools separately over Prefix, Root,

     and Suffix zones computed from each token's true non-pad length, + LayerNorm.

  3. Layer 3 -- Train-Only Word Embedding with Stochastic Word-ID Dropout:

     Initialized at tight std=0.05 (matching conv/linear scale), drops non-pad word IDs

     to <unk> (1) at rate `word_dropout` (0.35 in NER, 0.0 in MLM) + LayerNorm.



Strict Rule: Strictly ZERO Regex (no `re` imports anywhere).

"""

from __future__ import annotations

import zlib

import torch
import torch.nn as nn
import torch.nn.functional as F

SUBWORD_BUCKETS = 8192
SUBWORD_MASK_ID = SUBWORD_BUCKETS + 1  # 8193: dedicated whole-word MLM mask token
SUBWORD_EMBED_ROWS = SUBWORD_BUCKETS + 2  # 0=pad, 1..8192=buckets, 8193=MASK
MAX_SUBWORDS_PER_TOKEN = 48

MAX_CHARS_BOUNDED = 30  # 1 BOS + up to 28 UTF-8 bytes + 1 EOS
CHAR_BOS_ID = 257
CHAR_EOS_ID = 258
CHAR_MASK_ID = 259
CHAR_VOCAB_SIZE = 260  # 0=pad, 1..256=bytes, 257=BOS, 258=EOS, 259=MLM MASK


def hash_subword_ngram(ngram: str, num_buckets: int = SUBWORD_BUCKETS) -> int:
    """Deterministic cross-session 32-bit CRC hash into [1, num_buckets]."""
    h = zlib.crc32(ngram.encode("utf-8", errors="replace")) & 0xFFFFFFFF
    return (h % num_buckets) + 1


def extract_subword_ids(

    word: str,

    num_buckets: int = SUBWORD_BUCKETS,

    max_subwords: int = MAX_SUBWORDS_PER_TOKEN,

) -> list[int]:
    """Extract boundary-wrapped character 3-, 4-, and 5-gram bucket IDs for a token.

    Prioritizes prefix and suffix n-grams per order if a word exceeds max_subwords.

    Always produces at least 1 non-zero bucket ID; pads with 0 to max_subwords."""
    wl = word.lower()
    bounded = "<" + wl + ">"
    L = len(bounded)

    per_order_cap = max(2, max_subwords // 3)
    half_cap = per_order_cap // 2

    ids: list[int] = []
    for n in (3, 4, 5):
        if L < n:
            continue
        grams = [bounded[i : i + n] for i in range(L - n + 1)]
        if len(grams) > per_order_cap:
            grams = grams[:half_cap] + grams[-half_cap:]
        for g in grams:
            ids.append(hash_subword_ngram(g, num_buckets=num_buckets))

    if not ids:
        ids.append(hash_subword_ngram(bounded, num_buckets=num_buckets))

    if len(ids) > max_subwords:
        ids = ids[:max_subwords]
    elif len(ids) < max_subwords:
        ids.extend([0] * (max_subwords - len(ids)))
    return ids


def mask_subword_ids(max_subwords: int = MAX_SUBWORDS_PER_TOKEN) -> list[int]:
    """Subword ID vector for a whole-word [MASK] token (zero spelling leakage)."""
    return [SUBWORD_MASK_ID] + [0] * (max_subwords - 1)


def char_tensor_bounded(word: str, max_chars: int = MAX_CHARS_BOUNDED) -> list[int]:
    """Encode token bytes wrapped with dedicated BOS (257) and EOS (258) markers."""
    max_bytes = max_chars - 2
    b = word.encode("utf-8", errors="replace")[:max_bytes]
    ids = [CHAR_BOS_ID] + [byte + 1 for byte in b] + [CHAR_EOS_ID]
    if len(ids) < max_chars:
        ids.extend([0] * (max_chars - len(ids)))
    return ids


def mask_char_tensor(max_chars: int = MAX_CHARS_BOUNDED) -> list[int]:
    """Character ID vector for a whole-word [MASK] token (zero byte leakage)."""
    return [CHAR_BOS_ID, CHAR_MASK_ID, CHAR_EOS_ID] + [0] * (max_chars - 3)


class SubwordCharLexicalEncoder(nn.Module):
    """Unified Layer 1 + Layer 2 + Layer 3 lexical encoder with tight init and stream LayerNorm.



    Output dimensionality:

      - 3-Zone Positional Char CNN (LayerNorm'd): 3 * 80 = 240

      - Subword 3-5-gram Bag (1/sqrt(N) + LayerNorm'd): 64

      - Train-only Word Embedding (word dropout + LayerNorm'd): 64

      Total lexical output dim = 368.

    """

    def __init__(

        self,

        vocab_size: int,

        subword_buckets: int = SUBWORD_BUCKETS,

        subword_dim: int = 64,

        word_dim: int = 64,

        byte_dim: int = 32,

        conv_channels: int = 16,

        kernels: tuple[int, ...] = (2, 3, 4, 5, 7),

        word_dropout: float = 0.35,

        init_std: float = 0.05,

    ):
        super().__init__()
        self.vocab_size = vocab_size
        self.subword_buckets = subword_buckets
        self.subword_dim = subword_dim
        self.word_dim = word_dim
        self.word_dropout = word_dropout
        self.kernels = list(kernels)

        # Layer 1: Boundary-aware subword 3-5-gram embedding bag (0=pad, 1..B=buckets, B+1=MASK)
        self.subword_emb = nn.Embedding(subword_buckets + 2, subword_dim, padding_idx=0)

        # Layer 2: Boundary-aware 3-zone positional Char-CNN
        self.byte_emb = nn.Embedding(CHAR_VOCAB_SIZE, byte_dim, padding_idx=0)
        self.convs = nn.ModuleList([
            nn.Conv1d(byte_dim, conv_channels, kernel_size=k, padding=k // 2)
            for k in self.kernels
        ])
        self.char_zone_dim = conv_channels * len(self.kernels)  # 80 per zone
        self.char_total_dim = 3 * self.char_zone_dim  # 240 (prefix + root + suffix)

        # Layer 3: Train-only word embedding table (0=pad, 1=<unk>)
        self.word_emb = nn.Embedding(vocab_size, word_dim, padding_idx=0)

        # Per-stream LayerNorm balancing so no stream overpowers another at fusion
        self.char_norm = nn.LayerNorm(self.char_total_dim)
        self.sw_norm = nn.LayerNorm(subword_dim)
        self.word_norm = nn.LayerNorm(word_dim)

        self.out_dim = self.char_total_dim + subword_dim + word_dim  # 368

        # Tight initialization to eliminate default N(0,1) static noise on rare/untouched buckets
        self._init_embeddings(init_std=init_std)

    def _init_embeddings(self, init_std: float = 0.05) -> None:
        with torch.no_grad():
            for emb in (self.subword_emb, self.word_emb, self.byte_emb):
                nn.init.normal_(emb.weight, mean=0.0, std=init_std)
                emb.weight[0].zero_()

    def zero_untouched_subwords(self, used_bucket_ids: set[int]) -> int:
        """Explicitly zero out any subword bucket row (1..subword_buckets) with freq == 0."""
        zeroed = 0
        with torch.no_grad():
            for bid in range(1, self.subword_buckets + 1):
                if bid not in used_bucket_ids:
                    self.subword_emb.weight[bid].zero_()
                    zeroed += 1
        return zeroed

    def forward(

        self,

        w_ids: torch.Tensor,

        c_mat: torch.Tensor,

        sw_ids: torch.Tensor,

    ) -> torch.Tensor:
        """

        Args:

            w_ids:  (B, T) word IDs (0=pad, 1=<unk>)

            c_mat:  (B, T, MAX_CHARS_BOUNDED) bounded byte IDs with BOS/EOS

            sw_ids: (B, T, MAX_SUBWORDS_PER_TOKEN) hashed 3-5-gram bucket IDs (0=pad)

        Returns:

            lex_repr: (B, T, 368)

        """
        B, T = w_ids.shape

        # Layer 3: Word embedding with training-time stochastic word-ID dropout to <unk> (1)
        if self.training and self.word_dropout > 0.0:
            drop_w = (torch.rand(B, T, device=w_ids.device) < self.word_dropout) & (w_ids != 0)
            w_ids_eff = torch.where(drop_w, torch.ones_like(w_ids), w_ids)
        else:
            w_ids_eff = w_ids
        w_repr = self.word_norm(self.word_emb(w_ids_eff))  # (B, T, 64)

        # Layer 1: Subword 3-5-gram bag with exact 1/sqrt(N) scaling + LayerNorm
        sw_embs = self.subword_emb(sw_ids)  # (B, T, S, 64), pad rows are exact 0
        sw_counts = (sw_ids != 0).sum(dim=2, keepdim=True).clamp(min=1).float()  # (B, T, 1)
        sw_repr = self.sw_norm(sw_embs.sum(dim=2) / torch.sqrt(sw_counts))  # (B, T, 64)

        # Layer 2: Boundary-aware 3-zone positional Char-CNN (Prefix / Root / Suffix)
        L = c_mat.size(2)
        c_flat = c_mat.reshape(B * T, L)  # (N, L)
        c_embs = self.byte_emb(c_flat).transpose(1, 2)  # (N, 32, L)

        # Trim even-kernel conv outputs to exact sequence length L for positional alignment
        conv_maps = [F.gelu(conv(c_embs)[:, :, :L]) for conv in self.convs]
        feat_map = torch.cat(conv_maps, dim=1)  # (N, 80, L)

        c_len = (c_flat != 0).sum(dim=1)  # (N,)
        pos = torch.arange(L, device=c_flat.device).unsqueeze(0)  # (1, L)
        c_len_u = c_len.unsqueeze(1)  # (N, 1)
        valid = pos < c_len_u  # (N, L)
        has_valid = valid.any(dim=1, keepdim=True)  # (N, 1)
        valid_safe = torch.where(has_valid, valid, pos == 0)

        # Prefix: BOS + first 4 bytes (positions 0..4 within valid)
        prefix_mask = valid_safe & (pos < 5)
        prefix_mask = torch.where(prefix_mask.any(dim=1, keepdim=True), prefix_mask, valid_safe)

        # Suffix: last 4 bytes + EOS (positions L_eff-5..L_eff-1 within valid)
        suffix_start = (c_len_u - 5).clamp(min=0)
        suffix_mask = valid_safe & (pos >= suffix_start)
        suffix_mask = torch.where(suffix_mask.any(dim=1, keepdim=True), suffix_mask, valid_safe)

        # Root / Interior
        long_word = c_len_u > 6
        root_mask = torch.where(
            long_word,
            valid_safe & (pos >= 2) & (pos < c_len_u - 2),
            valid_safe & (pos >= 1) & (pos < c_len_u - 1),
        )
        root_mask = torch.where(root_mask.any(dim=1, keepdim=True), root_mask, valid_safe)

        neg_fill = -1e4
        prefix_pool = feat_map.masked_fill(~prefix_mask.unsqueeze(1), neg_fill).max(dim=2)[0]
        root_pool = feat_map.masked_fill(~root_mask.unsqueeze(1), neg_fill).max(dim=2)[0]
        suffix_pool = feat_map.masked_fill(~suffix_mask.unsqueeze(1), neg_fill).max(dim=2)[0]

        zero_gate = has_valid.float()
        prefix_pool = prefix_pool * zero_gate
        root_pool = root_pool * zero_gate
        suffix_pool = suffix_pool * zero_gate

        char_repr = torch.cat([prefix_pool, root_pool, suffix_pool], dim=1).view(B, T, -1)
        char_repr = self.char_norm(char_repr)  # (B, T, 240)

        return torch.cat([char_repr, sw_repr, w_repr], dim=2)  # (B, T, 368)