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,203 @@
1
+ """
2
+ Contextual Encoders for Uzbek Morphological Analysis.
3
+
4
+ Supports:
5
+ 1. CompactTransformerEncoder (Default — L=3, d_model=256, h=4)
6
+ 2. xLSTMEncoder (Extended sLSTM/mLSTM with exponential gating)
7
+ 3. BiLSTMEncoder (Baseline option for ablation)
8
+ """
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+ import math
13
+
14
+
15
+ class PositionalEncoding(nn.Module):
16
+ """Sinusoidal Positional Encoding for Transformer."""
17
+
18
+ def __init__(self, d_model: int, max_len: int = 512, dropout: float = 0.1):
19
+ super().__init__()
20
+ self.dropout = nn.Dropout(p=dropout)
21
+
22
+ pe = torch.zeros(max_len, d_model)
23
+ position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
24
+ div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
25
+
26
+ pe[:, 0::2] = torch.sin(position * div_term)
27
+ pe[:, 1::2] = torch.cos(position * div_term)
28
+ pe = pe.unsqueeze(0) # Shape: (1, max_len, d_model)
29
+
30
+ self.register_buffer('pe', pe)
31
+
32
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
33
+ """x shape: (B, S, d_model)"""
34
+ x = x + self.pe[:, :x.size(1)]
35
+ return self.dropout(x)
36
+
37
+
38
+ class CompactTransformerEncoder(nn.Module):
39
+ """
40
+ Compact Transformer Contextual Encoder.
41
+
42
+ Formula:
43
+ H^{(0)} = [e_1, e_2, ..., e_n]
44
+ A^{(l)} = Softmax(Q K^T / sqrt(d_k)) V
45
+ H^{(l)} = LayerNorm(H^{(l-1)} + FFN(LayerNorm(H^{(l-1)} + A^{(l)})))
46
+ """
47
+
48
+ def __init__(self, input_dim: int, d_model: int = 256, n_heads: int = 4,
49
+ d_ff: int = 512, n_layers: int = 3, dropout: float = 0.3):
50
+ super().__init__()
51
+
52
+ # Linear projection if input_dim != d_model
53
+ if input_dim != d_model:
54
+ self.input_proj = nn.Linear(input_dim, d_model)
55
+ else:
56
+ self.input_proj = nn.Identity()
57
+
58
+ self.pos_encoder = PositionalEncoding(d_model, dropout=dropout)
59
+
60
+ encoder_layer = nn.TransformerEncoderLayer(
61
+ d_model=d_model,
62
+ nhead=n_heads,
63
+ dim_feedforward=d_ff,
64
+ dropout=dropout,
65
+ activation='gelu',
66
+ batch_first=True,
67
+ norm_first=True
68
+ )
69
+
70
+ self.transformer = nn.TransformerEncoder(
71
+ encoder_layer,
72
+ num_layers=n_layers,
73
+ norm=nn.LayerNorm(d_model)
74
+ )
75
+
76
+ self.out_dim = d_model
77
+
78
+ def forward(self, x: torch.Tensor, mask: torch.Tensor = None) -> torch.Tensor:
79
+ """
80
+ x: (B, S, input_dim)
81
+ mask: boolean padding mask (B, S) where True indicates PADDING
82
+ """
83
+ x = self.input_proj(x)
84
+ x = self.pos_encoder(x)
85
+
86
+ # PyTorch TransformerEncoder accepts src_key_padding_mask of shape (B, S)
87
+ h_ctx = self.transformer(x, src_key_padding_mask=mask)
88
+ return h_ctx
89
+
90
+
91
+ class xLSTMBlock(nn.Module):
92
+ """
93
+ sLSTM Block with Exponential Gating (simplified xLSTM variant).
94
+
95
+ Formula:
96
+ i_t = exp(W_i x_t + U_i h_{t-1} + b_i)
97
+ f_t = exp(W_f x_t + U_f h_{t-1} + b_f)
98
+ z_t = tanh(W_z x_t + U_z h_{t-1} + b_z)
99
+ c_t = f_t * c_{t-1} + i_t * z_t
100
+ n_t = f_t * n_{t-1} + i_t
101
+ h_t = o_t * (c_t / n_t)
102
+ """
103
+
104
+ def __init__(self, hidden_dim: int):
105
+ super().__init__()
106
+ self.hidden_dim = hidden_dim
107
+
108
+ # Input, Forget, Output, Cell candidate gates
109
+ self.w_i = nn.Linear(hidden_dim, hidden_dim)
110
+ self.w_f = nn.Linear(hidden_dim, hidden_dim)
111
+ self.w_o = nn.Linear(hidden_dim, hidden_dim)
112
+ self.w_z = nn.Linear(hidden_dim, hidden_dim)
113
+
114
+ self.u_i = nn.Linear(hidden_dim, hidden_dim, bias=False)
115
+ self.u_f = nn.Linear(hidden_dim, hidden_dim, bias=False)
116
+ self.u_o = nn.Linear(hidden_dim, hidden_dim, bias=False)
117
+ self.u_z = nn.Linear(hidden_dim, hidden_dim, bias=False)
118
+
119
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
120
+ """x shape: (B, S, hidden_dim)"""
121
+ B, S, H = x.shape
122
+ h_t = torch.zeros(B, H, device=x.device)
123
+ c_t = torch.zeros(B, H, device=x.device)
124
+ n_t = torch.ones(B, H, device=x.device)
125
+
126
+ outputs = []
127
+
128
+ for t in range(S):
129
+ xt = x[:, t, :]
130
+
131
+ # Exponential gates with stabilization
132
+ i_logits = self.w_i(xt) + self.u_i(h_t)
133
+ f_logits = self.w_f(xt) + self.u_f(h_t)
134
+ o_logits = self.w_o(xt) + self.u_o(h_t)
135
+ z_logits = self.w_z(xt) + self.u_z(h_t)
136
+
137
+ # Stabilized exp gating
138
+ i_t = torch.exp(torch.clamp(i_logits, -10.0, 10.0))
139
+ f_t = torch.exp(torch.clamp(f_logits, -10.0, 10.0))
140
+ o_t = torch.sigmoid(o_logits)
141
+ z_t = torch.tanh(z_logits)
142
+
143
+ # Normalization state n_t and cell state c_t
144
+ n_t = f_t * n_t + i_t
145
+ c_t = f_t * c_t + i_t * z_t
146
+
147
+ # Output state with normalizer
148
+ h_t = o_t * (c_t / (n_t + 1e-8))
149
+ outputs.append(h_t.unsqueeze(1))
150
+
151
+ return torch.cat(outputs, dim=1)
152
+
153
+
154
+ class xLSTMEncoder(nn.Module):
155
+ """Bidirectional xLSTM Contextual Encoder."""
156
+
157
+ def __init__(self, input_dim: int, hidden_dim: int = 128, n_layers: int = 2,
158
+ dropout: float = 0.3):
159
+ super().__init__()
160
+ self.proj = nn.Linear(input_dim, hidden_dim)
161
+ self.fwd_blocks = nn.ModuleList([xLSTMBlock(hidden_dim) for _ in range(n_layers)])
162
+ self.bwd_blocks = nn.ModuleList([xLSTMBlock(hidden_dim) for _ in range(n_layers)])
163
+ self.dropout = nn.Dropout(dropout)
164
+ self.out_dim = hidden_dim * 2
165
+
166
+ def forward(self, x: torch.Tensor, mask: torch.Tensor = None) -> torch.Tensor:
167
+ x = self.proj(x)
168
+ x = self.dropout(x)
169
+
170
+ # Forward pass
171
+ h_fwd = x
172
+ for block in self.fwd_blocks:
173
+ h_fwd = block(h_fwd)
174
+
175
+ # Backward pass
176
+ x_rev = torch.flip(x, dims=[1])
177
+ h_bwd = x_rev
178
+ for block in self.bwd_blocks:
179
+ h_bwd = block(h_bwd)
180
+ h_bwd = torch.flip(h_bwd, dims=[1])
181
+
182
+ return torch.cat([h_fwd, h_bwd], dim=-1)
183
+
184
+
185
+ class BiLSTMEncoder(nn.Module):
186
+ """Standard BiLSTM Encoder for baseline ablation."""
187
+
188
+ def __init__(self, input_dim: int, hidden_dim: int = 128, n_layers: int = 2,
189
+ dropout: float = 0.3):
190
+ super().__init__()
191
+ self.lstm = nn.LSTM(
192
+ input_size=input_dim,
193
+ hidden_size=hidden_dim,
194
+ num_layers=n_layers,
195
+ batch_first=True,
196
+ bidirectional=True,
197
+ dropout=dropout if n_layers > 1 else 0.0
198
+ )
199
+ self.out_dim = hidden_dim * 2
200
+
201
+ def forward(self, x: torch.Tensor, mask: torch.Tensor = None) -> torch.Tensor:
202
+ h_ctx, _ = self.lstm(x)
203
+ return h_ctx
@@ -0,0 +1,65 @@
1
+ r"""
2
+ Class-Weighted Focal Loss for Multi-Task Imbalanced Morphological Attribute Classification.
3
+
4
+ Mathematical formulation:
5
+ FL(p_t) = - \alpha_t (1 - p_t)^\gamma \log(p_t)
6
+ """
7
+ import torch
8
+ import torch.nn as nn
9
+ import torch.nn.functional as F
10
+ from typing import Optional
11
+
12
+
13
+ class FocalLoss(nn.Module):
14
+ """
15
+ Focal Loss for addressing severe class imbalance in multi-task morphological feature prediction.
16
+ Focuses learning on hard negative/positive examples by applying a modulating factor (1 - p_t)^gamma.
17
+ """
18
+
19
+ def __init__(self, gamma: float = 2.0, alpha: Optional[torch.Tensor] = None,
20
+ ignore_index: int = 0, reduction: str = 'mean'):
21
+ super().__init__()
22
+ self.gamma = gamma
23
+ self.alpha = alpha
24
+ self.ignore_index = ignore_index
25
+ self.reduction = reduction
26
+
27
+ def forward(self, logits: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
28
+ """
29
+ Args:
30
+ logits: (N, C) or (B, S, C) prediction logits
31
+ targets: (N,) or (B, S) target class indices
32
+ """
33
+ if logits.dim() > 2:
34
+ logits = logits.view(-1, logits.size(-1))
35
+ targets = targets.view(-1)
36
+
37
+ # Mask ignored indices (PAD / NONE)
38
+ valid_mask = (targets != self.ignore_index)
39
+ if not valid_mask.any():
40
+ return torch.tensor(0.0, device=logits.device, requires_grad=True)
41
+
42
+ logits = logits[valid_mask]
43
+ targets = targets[valid_mask]
44
+
45
+ log_probs = F.log_softmax(logits, dim=-1)
46
+ probs = torch.exp(log_probs)
47
+
48
+ # Gather probability of true target class
49
+ target_log_probs = log_probs.gather(dim=-1, index=targets.unsqueeze(-1)).squeeze(-1)
50
+ target_probs = probs.gather(dim=-1, index=targets.unsqueeze(-1)).squeeze(-1)
51
+
52
+ # Focal modulating factor: (1 - p_t)^gamma
53
+ focal_factor = (1.0 - target_probs) ** self.gamma
54
+ loss = -focal_factor * target_log_probs
55
+
56
+ if self.alpha is not None:
57
+ alpha_weights = self.alpha.to(logits.device).gather(dim=0, index=targets)
58
+ loss = alpha_weights * loss
59
+
60
+ if self.reduction == 'mean':
61
+ return loss.mean()
62
+ elif self.reduction == 'sum':
63
+ return loss.sum()
64
+ else:
65
+ return loss
@@ -0,0 +1,66 @@
1
+ """
2
+ Adaptive Gating Mechanism for Uzbek Morphological Analysis.
3
+
4
+ Formulas:
5
+ g_i = sigmoid(W_g * [h_i^{ctx}; h_i^{morph}] + b_g)
6
+ h_i = g_i (odot) h_i^{ctx} + (1 - g_i) (odot) h_i^{morph}
7
+ """
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+
12
+
13
+ class AdaptiveGating(nn.Module):
14
+ """
15
+ Adaptive Context-Morphology Gating Mechanism.
16
+
17
+ Dynamically balances contextual representation h^{ctx} and explicit
18
+ morphological representation h^{morph} for each word token.
19
+
20
+ - g_i approx 1: token prediction relies more on sentence context (e.g. homonyms)
21
+ - g_i approx 0: token prediction relies more on affix morphology (e.g. inflected forms)
22
+ """
23
+
24
+ def __init__(self, d_ctx: int = 256, d_morph: int = 256, d_out: int = 256,
25
+ dropout: float = 0.2):
26
+ super().__init__()
27
+
28
+ # Linear projections to equalize dimensions if needed
29
+ self.proj_ctx = nn.Linear(d_ctx, d_out) if d_ctx != d_out else nn.Identity()
30
+ self.proj_morph = nn.Linear(d_morph, d_out) if d_morph != d_out else nn.Identity()
31
+
32
+ # Gate network: takes concat([h_ctx, h_morph]) -> g_i in [0, 1]^d_out
33
+ self.gate_net = nn.Sequential(
34
+ nn.Linear(d_out * 2, d_out),
35
+ nn.GELU(),
36
+ nn.Dropout(dropout),
37
+ nn.Linear(d_out, d_out),
38
+ nn.Sigmoid()
39
+ )
40
+
41
+ self.layer_norm = nn.LayerNorm(d_out)
42
+
43
+ def forward(self, h_ctx: torch.Tensor, h_morph: torch.Tensor) -> dict:
44
+ """
45
+ h_ctx: (B, S, d_ctx)
46
+ h_morph: (B, S, d_morph)
47
+
48
+ Returns dict:
49
+ 'h': (B, S, d_out) — gated combined representation
50
+ 'gate': (B, S, d_out) — gating activations for analysis/visualization
51
+ """
52
+ h_c = self.proj_ctx(h_ctx)
53
+ h_m = self.proj_morph(h_morph)
54
+
55
+ # Compute gating vector g_i: (B, S, d_out)
56
+ combined_features = torch.cat([h_c, h_m], dim=-1)
57
+ g = self.gate_net(combined_features)
58
+
59
+ # Gated fusion: h_i = g * h_ctx + (1 - g) * h_morph
60
+ h = g * h_c + (1.0 - g) * h_m
61
+ h = self.layer_norm(h)
62
+
63
+ return {
64
+ 'h': h,
65
+ 'gate': g
66
+ }
@@ -0,0 +1,177 @@
1
+ """
2
+ Multi-Task Prediction Heads for Uzbek Morphological Analysis.
3
+
4
+ Includes:
5
+ 1. ClassificationHeads: POS, Case, Number, Person, Tense, Mood, VerbForm, Voice
6
+ 2. LemmaDecoderHead: Character-level GRU decoder for lemmatization
7
+ 3. SegmentationHead: Character-level BIES classification for morpheme boundary detection
8
+ """
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+ from typing import Dict
13
+
14
+
15
+ class SingleClassificationHead(nn.Module):
16
+ """Single MLP classification head with LayerNorm + Dropout."""
17
+
18
+ def __init__(self, in_dim: int, num_classes: int, hidden_dim: int = 128, dropout: float = 0.2):
19
+ super().__init__()
20
+ self.net = nn.Sequential(
21
+ nn.Linear(in_dim, hidden_dim),
22
+ nn.GELU(),
23
+ nn.LayerNorm(hidden_dim),
24
+ nn.Dropout(dropout),
25
+ nn.Linear(hidden_dim, num_classes)
26
+ )
27
+
28
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
29
+ """x shape: (B, S, in_dim) -> logits: (B, S, num_classes)"""
30
+ return self.net(x)
31
+
32
+
33
+ class MultiTaskClassificationHeads(nn.Module):
34
+ """
35
+ Multi-Task Classification Heads for morphological attributes.
36
+ """
37
+
38
+ def __init__(self, in_dim: int, label_vocabs: Dict[str, Dict], hidden_dim: int = 128, dropout: float = 0.2):
39
+ super().__init__()
40
+ self.heads = nn.ModuleDict()
41
+ self.task_names = []
42
+
43
+ for task_name, vocab in label_vocabs.items():
44
+ if task_name in ['char', 'bies']:
45
+ continue
46
+ self.task_names.append(task_name)
47
+ self.heads[task_name] = SingleClassificationHead(
48
+ in_dim=in_dim,
49
+ num_classes=len(vocab),
50
+ hidden_dim=hidden_dim,
51
+ dropout=dropout
52
+ )
53
+
54
+ def forward(self, h: torch.Tensor) -> Dict[str, torch.Tensor]:
55
+ """
56
+ h: (B, S, in_dim)
57
+ Returns dict of logits: {task_name: (B, S, num_classes), ...}
58
+ """
59
+ logits = {}
60
+ for task_name in self.task_names:
61
+ logits[task_name] = self.heads[task_name](h)
62
+ return logits
63
+
64
+
65
+ class LemmaDecoderHead(nn.Module):
66
+ """
67
+ Character-level GRU Decoder for Lemmatization.
68
+
69
+ Takes word representation vector h_i and character embeddings of word form,
70
+ decodes lemma character by character: P(l_i | x_i) = prod_t P(l_it | l_{i,<t}, h_i)
71
+ """
72
+
73
+ def __init__(self, char_vocab_size: int, embed_dim: int = 64,
74
+ hidden_dim: int = 256, dropout: float = 0.2):
75
+ super().__init__()
76
+ self.char_embed = nn.Embedding(char_vocab_size, embed_dim, padding_idx=0)
77
+ self.proj_init = nn.Linear(hidden_dim, hidden_dim)
78
+
79
+ self.gru = nn.GRUCell(embed_dim + hidden_dim, hidden_dim)
80
+ self.out = nn.Sequential(
81
+ nn.Linear(hidden_dim, hidden_dim),
82
+ nn.GELU(),
83
+ nn.Dropout(dropout),
84
+ nn.Linear(hidden_dim, char_vocab_size)
85
+ )
86
+
87
+ self.hidden_dim = hidden_dim
88
+ self.char_vocab_size = char_vocab_size
89
+
90
+ def forward(self, h: torch.Tensor, target_lemma_chars: torch.Tensor = None,
91
+ max_len: int = 30) -> torch.Tensor:
92
+ """
93
+ h: (B, S, hidden_dim) — token representation
94
+ target_lemma_chars: optional (B, S, L) target character IDs for teacher forcing
95
+
96
+ Returns logits: (B, S, L, char_vocab_size)
97
+ """
98
+ B, S, H = h.shape
99
+
100
+ # Flatten (B, S, H) -> (B*S, H)
101
+ h_flat = h.view(B * S, H)
102
+
103
+ if target_lemma_chars is not None:
104
+ L = target_lemma_chars.size(2)
105
+ target_flat = target_lemma_chars.view(B * S, L)
106
+ else:
107
+ L = max_len
108
+ target_flat = None
109
+
110
+ # Initial hidden state derived from token vector
111
+ gru_h = torch.tanh(self.proj_init(h_flat))
112
+
113
+ # Initial input character: <BOS> (index 2) or zero
114
+ char_in = torch.full((B * S,), fill_value=2, dtype=torch.long, device=h.device)
115
+
116
+ logits_list = []
117
+
118
+ for t in range(L):
119
+ char_emb = self.char_embed(char_in) # (B*S, embed_dim)
120
+ gru_in = torch.cat([char_emb, h_flat], dim=-1) # (B*S, embed_dim + H)
121
+
122
+ gru_h = self.gru(gru_in, gru_h)
123
+ logit_t = self.out(gru_h) # (B*S, char_vocab_size)
124
+ logits_list.append(logit_t.unsqueeze(1)) # (B*S, 1, V)
125
+
126
+ if target_flat is not None:
127
+ # Teacher forcing
128
+ char_in = target_flat[:, t]
129
+ else:
130
+ # Greedy decoding
131
+ char_in = torch.argmax(logit_t, dim=-1)
132
+
133
+ # Concatenate time steps: (B*S, L, V)
134
+ all_logits = torch.cat(logits_list, dim=1)
135
+
136
+ # Reshape back to (B, S, L, V)
137
+ return all_logits.view(B, S, L, self.char_vocab_size)
138
+
139
+
140
+ class SegmentationHead(nn.Module):
141
+ """
142
+ Character-level Morpheme Segmentation Classifier (BIES tags).
143
+
144
+ Label scheme:
145
+ B: Begin morpheme
146
+ I: Inside morpheme
147
+ E: End morpheme
148
+ S: Single-char morpheme
149
+ """
150
+
151
+ def __init__(self, char_embed_dim: int = 128, hidden_dim: int = 128,
152
+ num_classes: int = 5, dropout: float = 0.2):
153
+ super().__init__()
154
+
155
+ self.bilstm = nn.LSTM(
156
+ input_size=char_embed_dim,
157
+ hidden_size=hidden_dim // 2,
158
+ num_layers=1,
159
+ batch_first=True,
160
+ bidirectional=True
161
+ )
162
+
163
+ self.classifier = nn.Sequential(
164
+ nn.Linear(hidden_dim, hidden_dim),
165
+ nn.GELU(),
166
+ nn.Dropout(dropout),
167
+ nn.Linear(hidden_dim, num_classes)
168
+ )
169
+
170
+ def forward(self, char_embeddings: torch.Tensor) -> torch.Tensor:
171
+ """
172
+ char_embeddings: (N, W, char_embed_dim) where N is batch size (words), W is max word length
173
+ Returns logits: (N, W, num_classes)
174
+ """
175
+ h_lstm, _ = self.bilstm(char_embeddings)
176
+ logits = self.classifier(h_lstm)
177
+ return logits
@@ -0,0 +1,46 @@
1
+ """
2
+ Morfologik Representation Encoder.
3
+
4
+ Formula:
5
+ h_i^{morph} = W_m * [e_{m_1}^{morph}; ...; e_{m_p}^{morph}] + b_m
6
+ """
7
+ import torch
8
+ import torch.nn as nn
9
+ import torch.nn.functional as F
10
+
11
+
12
+ class MorphEncoder(nn.Module):
13
+ """
14
+ Explicit Morfologik Representation Encoder.
15
+
16
+ Uses character CNN representations with dedicated projection and attention pooling
17
+ to form an explicit morphological representation vector h_i^{morph} for each word.
18
+ """
19
+
20
+ def __init__(self, char_dim: int, d_model: int = 256, dropout: float = 0.3):
21
+ super().__init__()
22
+
23
+ # Linear projection from character CNN features to morphological space
24
+ self.proj = nn.Sequential(
25
+ nn.Linear(char_dim, d_model),
26
+ nn.GELU(),
27
+ nn.Dropout(dropout),
28
+ nn.Linear(d_model, d_model),
29
+ nn.LayerNorm(d_model)
30
+ )
31
+
32
+ # Affix attention pooling layer
33
+ self.attn_w = nn.Linear(d_model, 1)
34
+
35
+ self.out_dim = d_model
36
+
37
+ def forward(self, char_rep: torch.Tensor, word_mask: torch.Tensor = None) -> torch.Tensor:
38
+ """
39
+ char_rep: (B, S, char_dim) — output from CharCNNEncoder
40
+ word_mask: optional boolean mask (B, S)
41
+ Returns h_morph: (B, S, d_model)
42
+ """
43
+ # Project character features: (B, S, d_model)
44
+ h_morph = self.proj(char_rep)
45
+
46
+ return h_morph
@@ -0,0 +1,58 @@
1
+ """
2
+ Uncertainty-Based Multi-Task Loss Weighting.
3
+
4
+ Formula:
5
+ L_{weighted} = sum_{k=1}^K (exp(-s_k) * L_k + 0.5 * s_k) + alpha * L_cons + beta * L_align
6
+ where s_k = log(sigma_k^2) is a learnable parameter per task.
7
+ """
8
+ import torch
9
+ import torch.nn as nn
10
+ from typing import Dict, List
11
+
12
+
13
+ class UncertaintyWeighting(nn.Module):
14
+ """
15
+ Automatic multi-task loss weighting using homoscedastic task uncertainty (Kendall & Gal, 2018).
16
+ """
17
+
18
+ def __init__(self, task_names: List[str]):
19
+ super().__init__()
20
+ self.task_names = task_names
21
+
22
+ # Learnable log variance parameters s_k = log(sigma_k^2)
23
+ # Initialized to 0.0 (so sigma_k^2 = 1, exp(-s_k) = 1)
24
+ self.log_vars = nn.ParameterDict({
25
+ task: nn.Parameter(torch.tensor(0.0)) for task in task_names
26
+ })
27
+
28
+ def forward(self, losses: Dict[str, torch.Tensor],
29
+ alpha_cons: float = 0.1, cons_loss: torch.Tensor = None,
30
+ beta_align: float = 0.05, align_loss: torch.Tensor = None) -> torch.Tensor:
31
+ """
32
+ losses: dict of task losses {task_name: scalar loss tensor}
33
+ cons_loss: optional consistency loss tensor
34
+ align_loss: optional morpheme alignment loss tensor
35
+
36
+ Returns total weighted multi-task loss tensor.
37
+ """
38
+ total_loss = 0.0
39
+
40
+ for task, loss_val in losses.items():
41
+ if task in self.log_vars:
42
+ # Clamp log variance to prevent Bayesian collapse (-3.0 to 3.0 bounds)
43
+ s_k = torch.clamp(self.log_vars[task], min=-3.0, max=3.0)
44
+ # Weighted loss: exp(-s_k) * L_k + 0.5 * s_k
45
+ weighted_task_loss = torch.exp(-s_k) * loss_val + 0.5 * s_k
46
+ total_loss = total_loss + weighted_task_loss
47
+ else:
48
+ total_loss = total_loss + loss_val
49
+
50
+ # Add consistency regularization loss
51
+ if cons_loss is not None:
52
+ total_loss = total_loss + alpha_cons * cons_loss
53
+
54
+ # Add morpheme alignment loss
55
+ if align_loss is not None:
56
+ total_loss = total_loss + beta_align * align_loss
57
+
58
+ return total_loss