uzmorph-net 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,66 @@
1
+ Metadata-Version: 2.4
2
+ Name: uzmorph-net
3
+ Version: 0.1.0
4
+ Summary: Multi-task neural morphological analyzer and lemmatizer for Uzbek
5
+ Home-page: https://github.com/UlugbekSalaev/uzmorph-net
6
+ Author: Ulugbek Salaev
7
+ Author-email: Ulugbek Salaev <ulugbek0302@gmail.com>
8
+ License: MIT
9
+ Project-URL: Homepage, https://github.com/UlugbekSalaev/uzmorph-net
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
14
+ Classifier: Topic :: Text Processing :: Linguistic
15
+ Requires-Python: >=3.8
16
+ Description-Content-Type: text/markdown
17
+ Requires-Dist: torch>=1.12.0
18
+ Dynamic: author
19
+ Dynamic: home-page
20
+ Dynamic: requires-python
21
+
22
+ # uzmorph-net
23
+
24
+ Multi-task neural morphological analyzer and lemmatizer for Uzbek.
25
+
26
+ ## Installation
27
+
28
+ ```bash
29
+ pip install uzmorph-net
30
+ ```
31
+
32
+ ## Quick Start
33
+
34
+ ```python
35
+ from uzmorphnet import UzMorphNet
36
+
37
+ analyzer = UzMorphNet()
38
+
39
+ # Structured output
40
+ results = analyzer.analyze("Bolalar maktabga ketishdi.")
41
+ for item in results:
42
+ print(item["word"], "->", item["lemma"], item["pos"], item["features"])
43
+
44
+ # Formatted table output
45
+ analyzer.print_result("Bolalar maktabga ketishdi.")
46
+ ```
47
+
48
+ Sample output:
49
+
50
+ ```text
51
+ Bolalar bola NOUN case=Nom|number=Plur
52
+ maktabga maktab NOUN case=Dat
53
+ ketishdi ketish VERB _
54
+ . . PUNCT _
55
+ ```
56
+
57
+ ## Architecture
58
+
59
+ - Character-level 1D-CNN encoder (`kernels = [3, 5, 7]`)
60
+ - Word-level Transformer context encoder (`d_model = 256`, `3` layers, `4` heads)
61
+ - Adaptive context-morphology gating mechanism
62
+ - Multi-task classification heads (POS + morphological attributes) and GRU lemma decoder
63
+
64
+ ## License
65
+
66
+ MIT License.
@@ -0,0 +1,19 @@
1
+ uzmorphnet/__init__.py,sha256=-9wj4rdijT97m3iJjN59EaB8oy6SDs4PKgYGFBaa1qw,267
2
+ uzmorphnet/analyzer.py,sha256=humPoPf0Eq4RsazwML5E_nS3T97fEl5xTlHIxxJ5e68,5474
3
+ uzmorphnet/config.py,sha256=e_TIAgBnpuTwx7S7-RZRgxpzf6CVqt-as9TFlVkxS2E,664
4
+ uzmorphnet/lemma_decoder.py,sha256=FHCnkF9vtQ4ZH6pgW3kHLeF-VmJTYjFKgZdqRzLCvH0,4547
5
+ uzmorphnet/uzmorph_model.py,sha256=FpcV2DuSxYUGGzPJZHzbEY5LQmTnkB-2z7P773NEMfU,10900
6
+ uzmorphnet/checkpoints/UzMorph_clean_seed42.pt,sha256=hF54fruV7xMHQ6ef-gRigJ3OAQ1ynkoLhYgVY5DErR4,18306150
7
+ uzmorphnet/model/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ uzmorphnet/model/char_encoder.py,sha256=-L6YYp0jcMuBO7zzFo7K0kO94FyAh02kYdBoXuOYvQA,2735
9
+ uzmorphnet/model/consistency.py,sha256=wGR5sMGeb0M28KRHenRfCo-E4IF1GVHzAchGuzb3jGc,4168
10
+ uzmorphnet/model/contextual_encoder.py,sha256=9Bhs6MuVZXn1acZYALUK5vOfmZ2mF6euvdwWBHZSaI8,6894
11
+ uzmorphnet/model/focal_loss.py,sha256=rT2Y_N617pDnOWAKDr2Vr30dzehQI-GrNxW-pcZtkb8,2353
12
+ uzmorphnet/model/gating.py,sha256=K-Yi7OaOP-F1Yo0EJ21g98InnWoQqJDnnSok0V4AE14,2221
13
+ uzmorphnet/model/heads.py,sha256=cvJq8Y2jd_G0eB0UDQzC3__fqEWMmqAXm25bitcMkrE,6083
14
+ uzmorphnet/model/morph_encoder.py,sha256=PnNA8VGl2ug5LI1geM0rb6cwOX8SvJRGIn_obzb7nlg,1421
15
+ uzmorphnet/model/uncertainty.py,sha256=MKPyx7YcWbciCZ_iViseFvwE4_Y1F2yWTMqTZlqOxW8,2192
16
+ uzmorph_net-0.1.0.dist-info/METADATA,sha256=byO5hzr8fz51Xnfiv1Epsp-ysZjqK9BAu6W7DgjM2k8,1859
17
+ uzmorph_net-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
18
+ uzmorph_net-0.1.0.dist-info/top_level.txt,sha256=xMLkViF2a6hIqJ6mFfosJm4naqZZGkHS0I1-nZ6OxbM,11
19
+ uzmorph_net-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ uzmorphnet
uzmorphnet/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ """
2
+ uzmorph-net: Multi-task neural morphological analyzer and lemmatizer for Uzbek.
3
+ """
4
+
5
+ __version__ = "0.1.0"
6
+ __author__ = "Ulugbek Salaev"
7
+
8
+ from .analyzer import UzMorphNet
9
+ from .uzmorph_model import UzbekMorphModelV2
10
+
11
+ __all__ = ["UzMorphNet", "UzbekMorphModelV2"]
uzmorphnet/analyzer.py ADDED
@@ -0,0 +1,143 @@
1
+ """High-level inference API for Uzbek neural morphological analysis."""
2
+ import re
3
+ from typing import Dict, List, Optional, Union
4
+ import torch
5
+
6
+ from .config import DEFAULT_CHECKPOINT, cfg
7
+ from .uzmorph_model import NONE_IDX, PAD_IDX, UzbekMorphModelV2
8
+
9
+ EOS_IDX = 3
10
+ SOS_IDX = 2
11
+ UNK_IDX = 1
12
+
13
+
14
+ class UzMorphNet:
15
+ """Multi-task neural morphological analyzer and lemmatizer for Uzbek.
16
+
17
+ Uses a 1D-CNN character encoder, compact Transformer context encoder,
18
+ and an adaptive context-morphology gating mechanism.
19
+ """
20
+
21
+ def __init__(self, checkpoint_path: Optional[str] = None, device: Optional[str] = None):
22
+ self.checkpoint_path = checkpoint_path or DEFAULT_CHECKPOINT
23
+ if device is None:
24
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
25
+ else:
26
+ self.device = torch.device(device)
27
+
28
+ ckpt = torch.load(self.checkpoint_path, map_location=self.device, weights_only=False)
29
+ self.label_vocabs = ckpt["label_vocabs"]
30
+ self.word_vocab = ckpt["word_vocab"]
31
+
32
+ self.model = UzbekMorphModelV2(
33
+ cfg=cfg,
34
+ label_vocabs=self.label_vocabs,
35
+ word_vocab_size=len(self.word_vocab),
36
+ compat_matrix=None,
37
+ encoder_type="transformer",
38
+ use_gating=True,
39
+ use_consistency=False,
40
+ use_uncertainty=True,
41
+ train_none=ckpt.get("train_none", True),
42
+ ).to(self.device)
43
+
44
+ self.model.load_state_dict(ckpt["model_state_dict"], strict=False)
45
+ self.model.eval()
46
+
47
+ self.char_vocab = self.label_vocabs["char"]
48
+ self.char_inv = {i: c for c, i in self.char_vocab.items()}
49
+ self.inv_vocabs = {
50
+ t: {i: l for l, i in v.items()}
51
+ for t, v in self.label_vocabs.items()
52
+ if t != "char"
53
+ }
54
+
55
+ @staticmethod
56
+ def tokenize(text: str) -> List[str]:
57
+ """Split raw Uzbek text into word and punctuation tokens."""
58
+ return re.findall(r"[\w'`\u2018\u2019\u02bb\u02bc-]+|[^\w\s]", text)
59
+
60
+ def _encode_tokens(self, tokens: List[str]):
61
+ max_w = max((len(t) for t in tokens), default=1) + 2
62
+ char_ids = torch.zeros(1, len(tokens), max_w, dtype=torch.long, device=self.device)
63
+ tok_ids = torch.zeros(1, len(tokens), dtype=torch.long, device=self.device)
64
+ unk_word = self.word_vocab.get("<UNK>", UNK_IDX)
65
+ unk_char = self.char_vocab.get("<UNK>", UNK_IDX)
66
+
67
+ for si, tok in enumerate(tokens):
68
+ tok_ids[0, si] = self.word_vocab.get(tok.lower(), unk_word)
69
+ for ci, ch in enumerate(tok[:max_w]):
70
+ char_ids[0, si, ci] = self.char_vocab.get(ch, unk_char)
71
+
72
+ lengths = torch.tensor([len(tokens)], dtype=torch.long, device=self.device)
73
+ return char_ids, tok_ids, lengths
74
+
75
+ def _decode_lemma(self, ids: List[int]) -> str:
76
+ out = []
77
+ for v in ids:
78
+ if v in (PAD_IDX, EOS_IDX):
79
+ break
80
+ if v not in (UNK_IDX, SOS_IDX):
81
+ out.append(self.char_inv.get(v, ""))
82
+ return "".join(out)
83
+
84
+ @torch.no_grad()
85
+ def analyze(self, text: Union[str, List[str]]) -> List[Dict]:
86
+ """Analyze an Uzbek sentence or list of tokens.
87
+
88
+ Args:
89
+ text: Input sentence string or pre-tokenized list of words.
90
+
91
+ Returns:
92
+ List of dictionaries with keys: 'word', 'lemma', 'pos', 'features', 'gate'.
93
+ """
94
+ tokens = self.tokenize(text) if isinstance(text, str) else list(text)
95
+ if not tokens:
96
+ return []
97
+
98
+ char_ids, tok_ids, lengths = self._encode_tokens(tokens)
99
+ out = self.model(
100
+ char_ids,
101
+ token_ids=tok_ids,
102
+ lengths=lengths,
103
+ teacher_forcing=False,
104
+ decode_lemma=True,
105
+ )
106
+
107
+ lemma_preds = out["lemma_logits"].argmax(dim=-1)[0] if "lemma_logits" in out else None
108
+ gate_vals = out["gate"].mean(dim=-1)[0] if out.get("gate") is not None else None
109
+
110
+ results = []
111
+ for si, tok in enumerate(tokens):
112
+ pos_id = out["logits"]["pos"][0, si].argmax().item()
113
+ pos = self.inv_vocabs["pos"].get(pos_id, "_")
114
+
115
+ features = {}
116
+ for task, inv_map in self.inv_vocabs.items():
117
+ if task == "pos" or task not in out["logits"]:
118
+ continue
119
+ tid = out["logits"][task][0, si].argmax().item()
120
+ if tid not in (PAD_IDX, NONE_IDX):
121
+ val = inv_map.get(tid, "")
122
+ if val and val not in ("<PAD>", "<NONE>", "<UNK>"):
123
+ features[task] = val
124
+
125
+ lemma = self._decode_lemma(lemma_preds[si].tolist()) if lemma_preds is not None else tok.lower()
126
+ gate = round(float(gate_vals[si].item()), 4) if gate_vals is not None else None
127
+
128
+ results.append({
129
+ "word": tok,
130
+ "lemma": lemma,
131
+ "pos": pos,
132
+ "features": features,
133
+ "gate": gate,
134
+ })
135
+ return results
136
+
137
+ def print_result(self, text: Union[str, List[str]]) -> List[Dict]:
138
+ """Analyze text and print a formatted morphological table."""
139
+ results = self.analyze(text)
140
+ for item in results:
141
+ feats_str = "|".join(f"{k}={v}" for k, v in item["features"].items()) or "_"
142
+ print(f"{item['word']:18s} {item['lemma']:15s} {item['pos']:6s} {feats_str}")
143
+ return results
uzmorphnet/config.py ADDED
@@ -0,0 +1,28 @@
1
+ """Package-internal model configuration for uzmorph-net."""
2
+ import os
3
+
4
+ PACKAGE_DIR = os.path.dirname(os.path.abspath(__file__))
5
+ DEFAULT_CHECKPOINT = os.path.join(PACKAGE_DIR, "checkpoints", "UzMorph_clean_seed42.pt")
6
+
7
+
8
+ class ModelConfig:
9
+ """Architecture hyperparameters matching the trained MDPI AI checkpoint."""
10
+ char_embed_dim = 64
11
+ char_vocab_size = 128
12
+ cnn_filters = 128
13
+ cnn_kernels = [3, 5, 7]
14
+
15
+ token_embed_dim = 128
16
+ combined_dim = token_embed_dim + cnn_filters * len(cnn_kernels)
17
+
18
+ d_model = 256
19
+ n_heads = 4
20
+ d_ff = 512
21
+ n_layers = 3
22
+ dropout = 0.3
23
+
24
+ alpha_cons = 0.1
25
+ beta_align = 0.05
26
+
27
+
28
+ cfg = ModelConfig()
@@ -0,0 +1,103 @@
1
+ """Tezkor va to'g'ri belgi darajasidagi lemma dekoderi.
2
+
3
+ Eski `LemmaDecoderHead` dan ikkita farqi bor:
4
+
5
+ 1. **Teacher forcing faqat o'qitishda.** Eski kodda baholash paytida ham
6
+ dekoderga haqiqiy (gold) lemma belgilari berilar edi, ya'ni model har
7
+ qadamda to'g'ri javobni ko'rib turardi. Bu lemma aniqligini sun'iy
8
+ ravishda ko'taradi. Bu yerda `teacher_forcing=False` da model faqat
9
+ o'zining oldingi bashoratiga tayanadi (free-running decoding).
10
+
11
+ 2. **Tezlik.** O'qitishda butun ketma-ketlik `nn.GRU` orqali bir marta
12
+ o'tkaziladi (vaqt bo'yicha parallel), va faqat haqiqiy tokenlar
13
+ dekodlanadi -- padding o'rinlari tashlab yuboriladi. Eski kod
14
+ B*S*L marta `GRUCell` chaqirar edi, shu jumladan padding uchun ham.
15
+
16
+ Matematik jihatdan teacher forcing rejimi eski dekoder bilan bir xil:
17
+ P(l_i | w_i) = prod_t P(l_it | l_{i,<t}, h_i)
18
+ """
19
+ import torch
20
+ import torch.nn as nn
21
+
22
+ BOS_ID = 2
23
+ EOS_ID = 3
24
+
25
+
26
+ class LemmaDecoder(nn.Module):
27
+ """h_i vektoridan lemma belgilarini ketma-ket generatsiya qiladi."""
28
+
29
+ def __init__(self, char_vocab_size: int, embed_dim: int = 64,
30
+ hidden_dim: int = 256, dropout: float = 0.2):
31
+ super().__init__()
32
+ self.char_embed = nn.Embedding(char_vocab_size, embed_dim, padding_idx=0)
33
+ self.proj_init = nn.Linear(hidden_dim, hidden_dim)
34
+ self.gru = nn.GRU(embed_dim + hidden_dim, hidden_dim, batch_first=True)
35
+ self.out = nn.Sequential(
36
+ nn.Linear(hidden_dim, hidden_dim),
37
+ nn.GELU(),
38
+ nn.Dropout(dropout),
39
+ nn.Linear(hidden_dim, char_vocab_size),
40
+ )
41
+ self.hidden_dim = hidden_dim
42
+ self.char_vocab_size = char_vocab_size
43
+
44
+ def forward(self, h: torch.Tensor, target_lemma_chars: torch.Tensor = None,
45
+ valid_mask: torch.Tensor = None, max_len: int = 30,
46
+ teacher_forcing: bool = True) -> torch.Tensor:
47
+ """
48
+ h : (B, S, H) token tasvirlari
49
+ target_lemma_chars: (B, S, L) gold lemma belgilari
50
+ valid_mask : (B, S) bool -- True bo'lgan o'rinlargina dekodlanadi
51
+ teacher_forcing : True bo'lsa gold belgilar kiritiladi (faqat o'qitish)
52
+
53
+ Qaytaradi: (B, S, L, V) logitlar. Dekodlanmagan o'rinlar nol bilan
54
+ to'ldiriladi -- ular yo'qotish funksiyasida ham, baholashda ham
55
+ hisobga olinmaydi.
56
+ """
57
+ B, S, H = h.shape
58
+ device = h.device
59
+
60
+ if target_lemma_chars is not None:
61
+ L = target_lemma_chars.size(2)
62
+ else:
63
+ L = max_len
64
+
65
+ if valid_mask is None:
66
+ valid_mask = torch.ones(B, S, dtype=torch.bool, device=device)
67
+
68
+ flat_mask = valid_mask.reshape(B * S)
69
+ idx = flat_mask.nonzero(as_tuple=True)[0]
70
+
71
+ logits = h.new_zeros(B * S, L, self.char_vocab_size)
72
+ if idx.numel() == 0:
73
+ return logits.view(B, S, L, self.char_vocab_size)
74
+
75
+ h_sel = h.reshape(B * S, H)[idx] # (N, H)
76
+ N = h_sel.size(0)
77
+ h0 = torch.tanh(self.proj_init(h_sel)).unsqueeze(0) # (1, N, H)
78
+
79
+ if teacher_forcing and target_lemma_chars is not None:
80
+ # Butun ketma-ketlik bir o'tishda: kirish = <BOS> + gold[:-1]
81
+ tgt = target_lemma_chars.reshape(B * S, L)[idx] # (N, L)
82
+ bos = torch.full((N, 1), BOS_ID, dtype=torch.long, device=device)
83
+ dec_in = torch.cat([bos, tgt[:, :-1]], dim=1) # (N, L)
84
+ emb = self.char_embed(dec_in) # (N, L, E)
85
+ ctx = h_sel.unsqueeze(1).expand(-1, L, -1) # (N, L, H)
86
+ gru_out, _ = self.gru(torch.cat([emb, ctx], dim=-1), h0)
87
+ sel_logits = self.out(gru_out) # (N, L, V)
88
+ else:
89
+ # Free-running: har qadamda modelning o'z bashorati kiritiladi
90
+ step_in = torch.full((N,), BOS_ID, dtype=torch.long, device=device)
91
+ hidden = h0
92
+ ctx = h_sel.unsqueeze(1) # (N, 1, H)
93
+ steps = []
94
+ for _ in range(L):
95
+ emb = self.char_embed(step_in).unsqueeze(1) # (N, 1, E)
96
+ gru_out, hidden = self.gru(torch.cat([emb, ctx], dim=-1), hidden)
97
+ step_logit = self.out(gru_out) # (N, 1, V)
98
+ steps.append(step_logit)
99
+ step_in = step_logit.squeeze(1).argmax(dim=-1)
100
+ sel_logits = torch.cat(steps, dim=1) # (N, L, V)
101
+
102
+ logits[idx] = sel_logits
103
+ return logits.view(B, S, L, self.char_vocab_size)
File without changes
@@ -0,0 +1,83 @@
1
+ """
2
+ Character-level 1D-CNN Encoder for Uzbek Words.
3
+
4
+ Formula:
5
+ c_ij = Embed(char_ij)
6
+ h_ij^{(k)} = ReLU(W^{(k)} * [c_{i,j}; ...; c_{i,j+k-1}] + b^{(k)}), k in {3, 5, 7}
7
+ e_i^{char} = [max_j h_ij^{(3)}; max_j h_ij^{(5)}; max_j h_ij^{(7)}]
8
+ """
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+
13
+
14
+ class CharCNNEncoder(nn.Module):
15
+ """
16
+ Multi-width 1D-CNN Character Encoder.
17
+
18
+ Input: char_ids tensor of shape (B, S, W) or (N, W)
19
+ - B: batch size
20
+ - S: sequence length (number of words in sentence)
21
+ - W: max word length (number of characters in word)
22
+
23
+ Output: character representation tensor of shape (B, S, num_kernels * num_filters)
24
+ or (N, num_kernels * num_filters)
25
+ """
26
+
27
+ def __init__(self, vocab_size: int, embed_dim: int = 64,
28
+ num_filters: int = 128, kernels: list = [3, 5, 7],
29
+ dropout: float = 0.3):
30
+ super().__init__()
31
+ self.embedding = nn.Embedding(vocab_size, embed_dim, padding_idx=0)
32
+ self.dropout = nn.Dropout(dropout)
33
+
34
+ # 1D Convolution layers for each kernel size
35
+ self.convs = nn.ModuleList([
36
+ nn.Conv1d(
37
+ in_channels=embed_dim,
38
+ out_channels=num_filters,
39
+ kernel_size=k,
40
+ padding=k // 2 # same padding
41
+ )
42
+ for k in kernels
43
+ ])
44
+
45
+ self.out_dim = len(kernels) * num_filters
46
+
47
+ def forward(self, char_ids: torch.Tensor) -> torch.Tensor:
48
+ """
49
+ Forward pass.
50
+ char_ids can be 2D (N, W) or 3D (B, S, W).
51
+ """
52
+ is_3d = (char_ids.dim() == 3)
53
+ if is_3d:
54
+ B, S, W = char_ids.shape
55
+ # Flatten to (B*S, W)
56
+ char_ids = char_ids.view(B * S, W)
57
+ else:
58
+ N, W = char_ids.shape
59
+
60
+ # Embedding: (N, W) -> (N, W, embed_dim)
61
+ x = self.embedding(char_ids)
62
+ x = self.dropout(x)
63
+
64
+ # Transpose for Conv1d: (N, embed_dim, W)
65
+ x = x.transpose(1, 2)
66
+
67
+ # Apply multi-kernel Conv1d + ReLU + Global Max Pooling
68
+ conv_outputs = []
69
+ for conv in self.convs:
70
+ # Conv output: (N, num_filters, W)
71
+ h = F.relu(conv(x))
72
+ # Global max pooling over character sequence: (N, num_filters)
73
+ pooled, _ = torch.max(h, dim=2)
74
+ conv_outputs.append(pooled)
75
+
76
+ # Concatenate features from all kernel sizes: (N, num_kernels * num_filters)
77
+ char_rep = torch.cat(conv_outputs, dim=-1)
78
+
79
+ if is_3d:
80
+ # Reshape back to (B, S, out_dim)
81
+ char_rep = char_rep.view(B, S, self.out_dim)
82
+
83
+ return char_rep
@@ -0,0 +1,104 @@
1
+ """
2
+ Structured Grammatical Consistency Regularizer.
3
+
4
+ Formula:
5
+ L_cons = - sum_i sum_{c_a, c_b} P(y_i^a = c_a) * P(y_i^b = c_b) * log C^{(a,b)}_{c_a, c_b}
6
+
7
+ Enforces morphological rules (e.g. VERB + Case=Ablative is invalid, NOUN + Tense=Past is invalid).
8
+ """
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+ from typing import Dict, Tuple, Set
13
+
14
+
15
+ class ConsistencyRegularizer(nn.Module):
16
+ """
17
+ Grammatical Consistency Regularizer using Soft Compatibility Matrices.
18
+ """
19
+
20
+ def __init__(self, compat_matrix: Dict[Tuple[str, str], Set[Tuple[str, str]]],
21
+ label_vocabs: Dict[str, Dict], eps: float = 1e-6):
22
+ super().__init__()
23
+ self.eps = eps
24
+ self.compat_matrices = {}
25
+
26
+ # Precompute compatibility tensor for each feature pair
27
+ for (feat_a, feat_b), valid_combos in compat_matrix.items():
28
+ if feat_a not in label_vocabs or feat_b not in label_vocabs:
29
+ continue
30
+
31
+ vocab_a = label_vocabs[feat_a]
32
+ vocab_b = label_vocabs[feat_b]
33
+ dim_a = len(vocab_a)
34
+ dim_b = len(vocab_b)
35
+
36
+ # Matrix C: (dim_a, dim_b) initialized to eps (invalid)
37
+ C = torch.full((dim_a, dim_b), fill_value=eps)
38
+
39
+ # Fill valid combinations with 1.0
40
+ for val_a, val_b in valid_combos:
41
+ idx_a = vocab_a.get(val_a, None)
42
+ idx_b = vocab_b.get(val_b, None)
43
+ if idx_a is not None and idx_b is not None:
44
+ C[idx_a, idx_b] = 1.0
45
+
46
+ # Special case: <PAD> and <NONE> are always compatible with everything
47
+ for special in ['<PAD>', '<NONE>']:
48
+ if special in vocab_a:
49
+ C[vocab_a[special], :] = 1.0
50
+ if special in vocab_b:
51
+ C[:, vocab_b[special]] = 1.0
52
+
53
+ # Register as buffer so it moves to GPU with module
54
+ buffer_name = f"C_{feat_a}_{feat_b}"
55
+ self.register_buffer(buffer_name, C)
56
+ self.compat_matrices[(feat_a, feat_b)] = buffer_name
57
+
58
+ def forward(self, predictions: Dict[str, torch.Tensor],
59
+ mask: torch.Tensor = None) -> torch.Tensor:
60
+ """
61
+ predictions: dict of logits {task_name: (B, S, num_classes), ...}
62
+ mask: optional (B, S) boolean tensor where True means valid token (not PAD)
63
+
64
+ Returns scalar consistency loss tensor.
65
+ """
66
+ total_cons_loss = 0.0
67
+ num_pairs = 0
68
+
69
+ for (feat_a, feat_b), buffer_name in self.compat_matrices.items():
70
+ if feat_a not in predictions or feat_b not in predictions:
71
+ continue
72
+
73
+ logits_a = predictions[feat_a] # (B, S, dim_a)
74
+ logits_b = predictions[feat_b] # (B, S, dim_b)
75
+
76
+ probs_a = F.softmax(logits_a, dim=-1) # (B, S, dim_a)
77
+ probs_b = F.softmax(logits_b, dim=-1) # (B, S, dim_b)
78
+
79
+ C_mat = getattr(self, buffer_name) # (dim_a, dim_b)
80
+ log_C = torch.log(C_mat + 1e-10) # (dim_a, dim_b)
81
+
82
+ # Compute joint probability P(a) * P(b): (B, S, dim_a, dim_b)
83
+ # P_joint[b, s, i, j] = probs_a[b, s, i] * probs_b[b, s, j]
84
+ probs_a_exp = probs_a.unsqueeze(-1) # (B, S, dim_a, 1)
85
+ probs_b_exp = probs_b.unsqueeze(-2) # (B, S, 1, dim_b)
86
+
87
+ joint_probs = probs_a_exp * probs_b_exp # (B, S, dim_a, dim_b)
88
+
89
+ # Expected penalty: - sum_{i,j} joint_probs_{i,j} * log_C_{i,j}
90
+ loss_per_token = -torch.sum(joint_probs * log_C, dim=(-2, -1)) # (B, S)
91
+
92
+ if mask is not None:
93
+ loss_per_token = loss_per_token * mask.float()
94
+ denom = mask.float().sum() + 1e-8
95
+ pair_loss = loss_per_token.sum() / denom
96
+ else:
97
+ pair_loss = loss_per_token.mean()
98
+
99
+ total_cons_loss = total_cons_loss + pair_loss
100
+ num_pairs += 1
101
+
102
+ if num_pairs > 0:
103
+ return total_cons_loss / num_pairs
104
+ return torch.tensor(0.0, device=next(self.parameters()).device)