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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import math
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
|
| 7 |
+
from transformers import PreTrainedModel
|
| 8 |
+
|
| 9 |
+
from typing import List
|
| 10 |
+
|
| 11 |
+
from .config import LidirlLSTMConfig
|
| 12 |
+
|
| 13 |
+
def torch_max_no_pads(model_out, lengths):
|
| 14 |
+
indices = torch.arange(model_out.size(1)).to(model_out.device)
|
| 15 |
+
mask = (indices < lengths.view(-1, 1)).unsqueeze(-1).expand(model_out.size())
|
| 16 |
+
model_out = torch.where(mask, model_out, torch.tensor(-1e9))
|
| 17 |
+
max_pool = torch.max(model_out, 1)[0]
|
| 18 |
+
return max_pool
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class ProjectionLayer(nn.Module):
|
| 22 |
+
"""
|
| 23 |
+
Noise-aware labels layer or traditional linear projection
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
def __init__(self,
|
| 27 |
+
hidden_dim : int,
|
| 28 |
+
label_size : int,
|
| 29 |
+
montecarlo_layer : bool = False):
|
| 30 |
+
super().__init__()
|
| 31 |
+
self.montecarlo_layer = montecarlo_layer
|
| 32 |
+
if montecarlo_layer:
|
| 33 |
+
self.proj = MCSoftmaxDenseFA(hidden_dim, label_size, 1, logits_only=True)
|
| 34 |
+
else:
|
| 35 |
+
# eventually I'm considering making this a variable size classifier so it's a sequence of layers even though it's just one
|
| 36 |
+
self.projs = [
|
| 37 |
+
nn.Linear(hidden_dim, label_size)
|
| 38 |
+
]
|
| 39 |
+
self.proj = nn.Sequential(*self.projs)
|
| 40 |
+
self.init_layer()
|
| 41 |
+
|
| 42 |
+
def forward(self, x):
|
| 43 |
+
return self.proj(x)
|
| 44 |
+
|
| 45 |
+
def init_layer(self, pi : float = 0.01):
|
| 46 |
+
"""
|
| 47 |
+
Initialize the final classification layer so all predictions are close to 0
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
if self.montecarlo_layer:
|
| 51 |
+
self.proj.init_layer(pi)
|
| 52 |
+
return
|
| 53 |
+
|
| 54 |
+
for layer in self.proj.modules():
|
| 55 |
+
if isinstance(layer, nn.Linear):
|
| 56 |
+
nn.init.normal_(layer.weight, mean=0.0, std=0.01)
|
| 57 |
+
if layer.bias is not None:
|
| 58 |
+
# Bias: -log((1 - pi) / pi)
|
| 59 |
+
bias_value = -math.log((1 - pi) / pi)
|
| 60 |
+
nn.init.constant_(layer.bias, bias_value)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class MinLSTMCell(nn.Module):
|
| 64 |
+
"""
|
| 65 |
+
https://arxiv.org/pdf/2410.01201
|
| 66 |
+
https://github.com/YecanLee/min-LSTM-torch/blob/main/minLSTMcell.py
|
| 67 |
+
bidirectional and parallel
|
| 68 |
+
hold layer depth and sweep out the other dimensions
|
| 69 |
+
"""
|
| 70 |
+
def __init__(self,
|
| 71 |
+
embed_dim,
|
| 72 |
+
hidden_dim):
|
| 73 |
+
super(MinLSTMCell, self).__init__()
|
| 74 |
+
self.embed_dim = embed_dim
|
| 75 |
+
self.hidden_dim = hidden_dim
|
| 76 |
+
self.output_dim = embed_dim
|
| 77 |
+
|
| 78 |
+
# Initialize the linear layers for the forget gate, input gate, and hidden state transformation
|
| 79 |
+
self.linear_f = nn.Linear(embed_dim, hidden_dim)
|
| 80 |
+
self.linear_i = nn.Linear(embed_dim, hidden_dim)
|
| 81 |
+
self.linear_h = nn.Linear(embed_dim, hidden_dim)
|
| 82 |
+
|
| 83 |
+
def parallel_scan_log(self, log_coeffs, log_values):
|
| 84 |
+
# log_coeffs: (batch_size, seq_len, input_size)
|
| 85 |
+
# log_values: (batch_size, seq_len + 1, input_size)
|
| 86 |
+
a_star = F.pad(torch.cumsum(log_coeffs, dim=1), (0, 0, 1, 0))
|
| 87 |
+
log_h0_plus_b_star = torch.logcumsumexp(
|
| 88 |
+
log_values - a_star, dim=1)
|
| 89 |
+
log_h = a_star + log_h0_plus_b_star
|
| 90 |
+
return torch.exp(log_h)[:, 1:]
|
| 91 |
+
|
| 92 |
+
def g(self, x):
|
| 93 |
+
return torch.where(x >= 0, x+0.5, torch.sigmoid(x))
|
| 94 |
+
|
| 95 |
+
def log_g(self, x):
|
| 96 |
+
return torch.where(x >= 0, (F.relu(x)+0.5).log(), -F.softplus(-x))
|
| 97 |
+
|
| 98 |
+
def forward(self, inputs):
|
| 99 |
+
h_init = torch.zeros(inputs.size(0), 1, self.hidden_dim, device=inputs.device)
|
| 100 |
+
|
| 101 |
+
diff = F.softplus(-self.linear_f(inputs)) - F.softplus(-self.linear_i(inputs))
|
| 102 |
+
|
| 103 |
+
log_f = -F.softplus(diff)
|
| 104 |
+
log_i = -F.softplus(-diff)
|
| 105 |
+
log_h_0 = torch.log(h_init)
|
| 106 |
+
|
| 107 |
+
log_tilde_h = self.log_g(self.linear_h(inputs))
|
| 108 |
+
|
| 109 |
+
h = self.parallel_scan_log(log_f, torch.cat([log_h_0, log_i + log_tilde_h], dim=1))
|
| 110 |
+
return h
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class LSTMBlock(nn.Module):
|
| 114 |
+
def __init__(self,
|
| 115 |
+
embed_dim : int = 512,
|
| 116 |
+
hidden_dim : int = 2048,
|
| 117 |
+
num_layers : int = 6,
|
| 118 |
+
dropout : float = 0.1,
|
| 119 |
+
bidirectional : bool = False
|
| 120 |
+
):
|
| 121 |
+
super(LSTMBlock, self).__init__()
|
| 122 |
+
|
| 123 |
+
self.layers = []
|
| 124 |
+
last_dim = embed_dim
|
| 125 |
+
for _ in range(num_layers):
|
| 126 |
+
self.layers.append(MinLSTMCell(last_dim, hidden_dim))
|
| 127 |
+
self.layers.append(nn.LayerNorm(hidden_dim, elementwise_affine=True))
|
| 128 |
+
self.layers.append(nn.GELU())
|
| 129 |
+
self.layers.append(nn.Dropout(dropout))
|
| 130 |
+
last_dim = hidden_dim
|
| 131 |
+
self.model = nn.Sequential(*self.layers)
|
| 132 |
+
self.bidirectionality_term = 2 if bidirectional else 1
|
| 133 |
+
self.output_dim = hidden_dim * self.bidirectionality_term
|
| 134 |
+
self.bidirectional = bidirectional
|
| 135 |
+
|
| 136 |
+
def flip_sequence(self, inputs, lengths):
|
| 137 |
+
# Here we want to flip the sequence but keep the right-padding
|
| 138 |
+
# We can do this by flipping the sequence and then flipping the padding
|
| 139 |
+
new = []
|
| 140 |
+
for inp, leng in zip(inputs, lengths):
|
| 141 |
+
new.append(inp[:leng].flip(0))
|
| 142 |
+
return pad_sequence(new, batch_first=True).to(inputs.device)
|
| 143 |
+
|
| 144 |
+
def forward(self, inputs, lengths):
|
| 145 |
+
encoding = self.model(inputs)
|
| 146 |
+
last_token = encoding[torch.arange(encoding.size(0)), lengths - 1].view(inputs.size(0), 1, -1)
|
| 147 |
+
if self.bidirectional:
|
| 148 |
+
reverse_sequence = self.flip_sequence(inputs, lengths)
|
| 149 |
+
reverse_encoding = self.model(reverse_sequence)
|
| 150 |
+
reverse_last_token = reverse_encoding[torch.arange(reverse_encoding.size(0)), lengths - 1].view(inputs.size(0), 1, -1)
|
| 151 |
+
last_token = torch.cat((last_token, reverse_last_token), dim=-1)
|
| 152 |
+
|
| 153 |
+
return last_token, torch.ones((inputs.size(0), 1), device=inputs.device, dtype=torch.long)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class LidirlLSTM(PreTrainedModel):
|
| 157 |
+
"""
|
| 158 |
+
Defines the Lidirl LSTM Model
|
| 159 |
+
"""
|
| 160 |
+
|
| 161 |
+
config_class = LidirlLSTMConfig
|
| 162 |
+
def __init__(self, config):
|
| 163 |
+
super().__init__(config)
|
| 164 |
+
|
| 165 |
+
self.encoder = LSTMBlock(
|
| 166 |
+
embed_dim = config.embed_dim,
|
| 167 |
+
hidden_dim = config.hidden_dim,
|
| 168 |
+
num_layers = config.num_layers,
|
| 169 |
+
dropout = config.dropout,
|
| 170 |
+
bidirectional = config.bidirectional
|
| 171 |
+
)
|
| 172 |
+
self.embed_layer = nn.Embedding(config.vocab_size, config.embed_dim)
|
| 173 |
+
self.proj = ProjectionLayer(self.encoder.output_dim, config.label_size, config.montecarlo_layer)
|
| 174 |
+
|
| 175 |
+
self.label_size = config.label_size
|
| 176 |
+
self.max_length = config.max_length
|
| 177 |
+
self.multilabel = config.multilabel
|
| 178 |
+
self.monte_carlo = config.montecarlo_layer
|
| 179 |
+
|
| 180 |
+
self.labels = ["" for _ in config.labels]
|
| 181 |
+
for key, value in config.labels.items():
|
| 182 |
+
self.labels[value] = key
|
| 183 |
+
|
| 184 |
+
def forward(self, inputs, lengths):
|
| 185 |
+
inputs = inputs[:, :self.max_length]
|
| 186 |
+
lengths = lengths.clamp(max=self.max_length)
|
| 187 |
+
|
| 188 |
+
embeddings = self.embed_layer(inputs)
|
| 189 |
+
encoding, lengths = self.encoder(embeddings, lengths=lengths)
|
| 190 |
+
max_pool = torch_max_no_pads(encoding, lengths)
|
| 191 |
+
projection = self.proj(max_pool)
|
| 192 |
+
|
| 193 |
+
return projection
|
| 194 |
+
|
| 195 |
+
def __call__(self, inputs, lengths):
|
| 196 |
+
# this is inference only model
|
| 197 |
+
with torch.no_grad():
|
| 198 |
+
logits = self.forward(inputs, lengths)
|
| 199 |
+
if self.multilabel:
|
| 200 |
+
probs = torch.sigmoid(logits)
|
| 201 |
+
else:
|
| 202 |
+
probs = torch.softmax(logits, dim=-1)
|
| 203 |
+
return probs
|
| 204 |
+
|
| 205 |
+
def predict(self, inputs, lengths, threshold=0.5, top_k=None):
|
| 206 |
+
probs = self.__call__(inputs, lengths)
|
| 207 |
+
if top_k is not None and top_k > 0:
|
| 208 |
+
top_k_preds = torch.topk(probs, top_k, dim=1)
|
| 209 |
+
pred_labels = []
|
| 210 |
+
for pred, prob in zip(top_k_preds.indices, top_k_preds.values):
|
| 211 |
+
pred_labels.append([(self.labels[p.item()], pr.item()) for (p, pr) in zip(pred, prob)])
|
| 212 |
+
return pred_labels
|
| 213 |
+
if self.multilabel:
|
| 214 |
+
batch_idx, label_idx = torch.where(probs > threshold)
|
| 215 |
+
output = [[] for _ in range(len(inputs))]
|
| 216 |
+
for batch, label in zip(batch_idx, label_idx):
|
| 217 |
+
label_string = self.labels
|
| 218 |
+
output[batch.item()].append(
|
| 219 |
+
(self.labels[label.item()], probs[batch, label].item())
|
| 220 |
+
)
|
| 221 |
+
return output
|
| 222 |
+
|