File size: 10,205 Bytes
ca48c71 | 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 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 | from __future__ import annotations
import math
import os
import sys
from typing import Any, Dict, List, Optional
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
from base_model import BaseModel # noqa: E402
from utils import emit_progress # noqa: E402
from dataset import VOCAB_SIZE # noqa: E402
class _TransformerCNN(nn.Module):
"""Arquitetura híbrida: Transformer Encoder + 1D Highway CNN (CharNN)."""
def __init__(
self,
vocab_size: int,
max_seq_len: int,
d_model: int,
num_classes: int,
dropout: float = 0.1,
) -> None:
super().__init__()
self.d_model = d_model
self.embedding = nn.Embedding(vocab_size, d_model, padding_idx=0)
self.pos_embedding = nn.Embedding(max_seq_len, d_model)
encoder_layer = nn.TransformerEncoderLayer(
d_model=d_model,
nhead=4,
dim_feedforward=d_model * 2,
dropout=dropout,
batch_first=True,
)
self.transformer = nn.TransformerEncoder(encoder_layer, num_layers=2)
# Camadas convolucionais 1D com diferentes tamanhos de kernel (estilo CharNN)
self.convs = nn.ModuleList([
nn.Conv1d(in_channels=d_model, out_channels=64, kernel_size=k)
for k in (1, 3, 5, 7)
])
self.dropout = nn.Dropout(dropout)
self.fc1 = nn.Linear(64 * 4, 64)
self.relu = nn.ReLU()
self.fc_out = nn.Linear(64, num_classes)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = x.long()
bsz, seq_len = x.size()
positions = torch.arange(0, seq_len, device=x.device).unsqueeze(0).expand(bsz, seq_len)
# 1. Estágio Transformer (Extração de Embeddings)
emb = self.embedding(x) * math.sqrt(self.d_model) + self.pos_embedding(positions)
trans_out = self.transformer(emb) # (B, L, d_model)
# 2. Estágio CharNN (Convoluções 1D + Global Max Pooling)
conv_in = trans_out.transpose(1, 2) # (B, d_model, L)
pooled_outputs = []
for conv in self.convs:
c = torch.relu(conv(conv_in))
pooled = torch.max(c, dim=2)[0]
pooled_outputs.append(pooled)
features = torch.cat(pooled_outputs, dim=1)
features = self.dropout(self.relu(self.fc1(features)))
return self.fc_out(features)
class TransformerCNN(BaseModel):
"""Wrapper do Transformer-CNN compatível com BaseModel."""
def build_model(self) -> nn.Module:
hp = self.config.get("hyperparameters", {})
self._d_model = int(hp.get("d_model", 64))
self._max_seq_len = int(hp.get("max_seq_len", self.input_size or 120))
self._dropout = float(hp.get("dropout", 0.1))
self.device = torch.device(
"cuda"
if torch.cuda.is_available() and self.config.get("use_cuda", True)
else "cpu"
)
model = _TransformerCNN(
vocab_size=VOCAB_SIZE,
max_seq_len=self._max_seq_len,
d_model=self._d_model,
num_classes=self.num_classes,
dropout=self._dropout,
).to(self.device)
self.criterion = nn.CrossEntropyLoss()
return model
def train_model(
self,
train_loader: DataLoader,
val_loader: Optional[DataLoader],
epochs: int,
lr: float,
**kwargs: Any,
) -> Dict[str, Any]:
hp = self.config.get("hyperparameters", {})
epochs = int(hp.get("epochs", epochs))
lr = float(hp.get("learning_rate", lr))
weight_decay = float(hp.get("weight_decay", 0.0001))
optimizer_name = str(hp.get("optimizer", "adam")).lower()
optimizer = self._build_optimizer(optimizer_name, lr, weight_decay)
history: Dict[str, Any] = {
"train_loss": [], "train_acc": [],
"val_loss": [], "val_acc": [],
}
n_batches = max(len(train_loader), 1)
total_train_steps = max(epochs * n_batches, 1)
best_val_acc = -float("inf")
best_epoch = -1
for epoch in range(1, epochs + 1):
self.model.train()
run_loss = 0.0
correct = 0
total = 0
for X, y in train_loader:
X = X.to(self.device)
y = y.to(self.device)
optimizer.zero_grad()
logits = self.model(X)
loss = self.criterion(logits, y)
loss.backward()
optimizer.step()
run_loss += float(loss.item()) * X.size(0)
preds = logits.argmax(dim=1)
correct += int((preds == y).sum().item())
total += int(y.size(0))
global_step = (epoch - 1) * n_batches
emit_progress(int(global_step * 100 / total_train_steps), total_train_steps)
train_loss = run_loss / max(total, 1)
train_acc = correct / max(total, 1)
history["train_loss"].append(round(train_loss, 6))
history["train_acc"].append(round(train_acc, 6))
val_loss, val_acc = (float("nan"), float("nan"))
if val_loader is not None:
val_metrics = self.evaluate(val_loader)
val_loss = val_metrics["loss"]
val_acc = val_metrics["accuracy"]
if val_acc > best_val_acc:
best_val_acc = val_acc
best_epoch = epoch
history["val_loss"].append(round(val_loss, 6))
history["val_acc"].append(round(val_acc, 6))
print(
f"Epoch [{epoch:>3}/{epochs}] "
f"train_loss={train_loss:.4f} train_acc={train_acc:.4f} "
f"val_loss={val_loss:.4f} val_acc={val_acc:.4f}"
)
history["best_epoch"] = best_epoch
history["best_val_acc"] = round(best_val_acc, 6) if best_epoch > 0 else None
self.history = history
return history
def evaluate(self, data_loader: DataLoader) -> Dict[str, float]:
self.model.eval()
loss_sum = 0.0
correct = 0
total = 0
with torch.no_grad():
for X, y in data_loader:
X = X.to(self.device)
y = y.to(self.device)
logits = self.model(X)
loss = self.criterion(logits, y)
loss_sum += float(loss.item()) * X.size(0)
preds = logits.argmax(dim=1)
correct += int((preds == y).sum().item())
total += int(y.size(0))
return {
"loss": loss_sum / max(total, 1),
"accuracy": correct / max(total, 1),
"n": total,
}
def predict(self, inputs: Any) -> np.ndarray:
self.model.eval()
with torch.no_grad():
if isinstance(inputs, DataLoader):
outs: List[np.ndarray] = []
for batch in inputs:
X = batch[0] if isinstance(batch, (tuple, list)) else batch
X = X.to(self.device)
outs.append(self.model(X).argmax(dim=1).cpu().numpy())
return np.concatenate(outs, axis=0)
if isinstance(inputs, np.ndarray):
X = torch.from_numpy(inputs.astype(np.int64)).to(self.device)
elif isinstance(inputs, torch.Tensor):
X = inputs.long().to(self.device)
else:
X = torch.tensor(inputs, dtype=torch.long).to(self.device)
if X.ndim == 1:
X = X.unsqueeze(0)
return self.model(X).argmax(dim=1).cpu().numpy()
def save_model(self, filename: str) -> str:
path = os.path.join(self.model_dir, filename)
torch.save(
{
"state_dict": self.model.state_dict(),
"input_size": self.input_size,
"num_classes": self.num_classes,
"d_model": self._d_model,
"max_seq_len": self._max_seq_len,
"dropout": self._dropout,
"project_name": self.project_name,
},
path,
)
print(f"✓ Model saved to {path}")
return path
def load_model(self, filename: str) -> None:
path = filename if os.path.isabs(filename) else os.path.join(self.model_dir, filename)
ckpt = torch.load(path, map_location=self.device)
self._d_model = ckpt.get("d_model", self._d_model)
self._max_seq_len = ckpt.get("max_seq_len", self._max_seq_len)
self._dropout = ckpt.get("dropout", self._dropout)
self.model = _TransformerCNN(
vocab_size=VOCAB_SIZE,
max_seq_len=self._max_seq_len,
d_model=self._d_model,
num_classes=ckpt["num_classes"],
dropout=self._dropout,
).to(self.device)
self.model.load_state_dict(ckpt["state_dict"])
def _build_optimizer(self, name: str, lr: float, weight_decay: float) -> optim.Optimizer:
params = self.model.parameters()
if name == "sgd":
return optim.SGD(params, lr=lr, momentum=0.9, weight_decay=weight_decay)
if name == "rmsprop":
return optim.RMSprop(params, lr=lr, weight_decay=weight_decay)
return optim.Adam(params, lr=lr, weight_decay=weight_decay)
def create_model(
input_size: int,
num_classes: int,
project_name: str,
base_path: str,
config: Optional[Dict[str, Any]] = None,
) -> TransformerCNN:
return TransformerCNN(
input_size=input_size,
num_classes=num_classes,
project_name=project_name,
base_path=base_path,
framework="pytorch",
config=config or {},
) |