uzmorph-net 0.1.0__tar.gz

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,2 @@
1
+ include README.md
2
+ recursive-include uzmorphnet/checkpoints *.pt
@@ -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,45 @@
1
+ # uzmorph-net
2
+
3
+ Multi-task neural morphological analyzer and lemmatizer for Uzbek.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install uzmorph-net
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```python
14
+ from uzmorphnet import UzMorphNet
15
+
16
+ analyzer = UzMorphNet()
17
+
18
+ # Structured output
19
+ results = analyzer.analyze("Bolalar maktabga ketishdi.")
20
+ for item in results:
21
+ print(item["word"], "->", item["lemma"], item["pos"], item["features"])
22
+
23
+ # Formatted table output
24
+ analyzer.print_result("Bolalar maktabga ketishdi.")
25
+ ```
26
+
27
+ Sample output:
28
+
29
+ ```text
30
+ Bolalar bola NOUN case=Nom|number=Plur
31
+ maktabga maktab NOUN case=Dat
32
+ ketishdi ketish VERB _
33
+ . . PUNCT _
34
+ ```
35
+
36
+ ## Architecture
37
+
38
+ - Character-level 1D-CNN encoder (`kernels = [3, 5, 7]`)
39
+ - Word-level Transformer context encoder (`d_model = 256`, `3` layers, `4` heads)
40
+ - Adaptive context-morphology gating mechanism
41
+ - Multi-task classification heads (POS + morphological attributes) and GRU lemma decoder
42
+
43
+ ## License
44
+
45
+ MIT License.
@@ -0,0 +1,27 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "uzmorph-net"
7
+ version = "0.1.0"
8
+ authors = [
9
+ { name = "Ulugbek Salaev", email = "ulugbek0302@gmail.com" }
10
+ ]
11
+ description = "Multi-task neural morphological analyzer and lemmatizer for Uzbek"
12
+ readme = "README.md"
13
+ requires-python = ">=3.8"
14
+ license = { text = "MIT" }
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Operating System :: OS Independent",
19
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
20
+ "Topic :: Text Processing :: Linguistic"
21
+ ]
22
+ dependencies = [
23
+ "torch>=1.12.0"
24
+ ]
25
+
26
+ [project.urls]
27
+ "Homepage" = "https://github.com/UlugbekSalaev/uzmorph-net"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,29 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ setup(
4
+ name="uzmorph-net",
5
+ version="0.1.0",
6
+ author="Ulugbek Salaev",
7
+ author_email="ulugbek0302@gmail.com",
8
+ description="Multi-task neural morphological analyzer and lemmatizer for Uzbek",
9
+ long_description=open("README.md", encoding="utf-8").read(),
10
+ long_description_content_type="text/markdown",
11
+ url="https://github.com/UlugbekSalaev/uzmorph-net",
12
+ packages=find_packages(),
13
+ include_package_data=True,
14
+ package_data={
15
+ "uzmorphnet": [
16
+ "checkpoints/*.pt",
17
+ ]
18
+ },
19
+ install_requires=[
20
+ "torch>=1.12.0",
21
+ ],
22
+ classifiers=[
23
+ "Programming Language :: Python :: 3",
24
+ "License :: OSI Approved :: MIT License",
25
+ "Operating System :: OS Independent",
26
+ "Topic :: Text Processing :: Linguistic",
27
+ ],
28
+ python_requires=">=3.8",
29
+ )
@@ -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,24 @@
1
+ MANIFEST.in
2
+ README.md
3
+ pyproject.toml
4
+ setup.py
5
+ uzmorph_net.egg-info/PKG-INFO
6
+ uzmorph_net.egg-info/SOURCES.txt
7
+ uzmorph_net.egg-info/dependency_links.txt
8
+ uzmorph_net.egg-info/requires.txt
9
+ uzmorph_net.egg-info/top_level.txt
10
+ uzmorphnet/__init__.py
11
+ uzmorphnet/analyzer.py
12
+ uzmorphnet/config.py
13
+ uzmorphnet/lemma_decoder.py
14
+ uzmorphnet/uzmorph_model.py
15
+ uzmorphnet/checkpoints/UzMorph_clean_seed42.pt
16
+ uzmorphnet/model/__init__.py
17
+ uzmorphnet/model/char_encoder.py
18
+ uzmorphnet/model/consistency.py
19
+ uzmorphnet/model/contextual_encoder.py
20
+ uzmorphnet/model/focal_loss.py
21
+ uzmorphnet/model/gating.py
22
+ uzmorphnet/model/heads.py
23
+ uzmorphnet/model/morph_encoder.py
24
+ uzmorphnet/model/uncertainty.py
@@ -0,0 +1 @@
1
+ torch>=1.12.0
@@ -0,0 +1 @@
1
+ uzmorphnet
@@ -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"]
@@ -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
@@ -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