PowerMachine commited on
Commit
e96c019
·
verified ·
1 Parent(s): 8286d7e

Delete cnn_bigru/training/auto_learner.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. cnn_bigru/training/auto_learner.py +0 -261
cnn_bigru/training/auto_learner.py DELETED
@@ -1,261 +0,0 @@
1
- """auto_learner.py — Auto-aprendizado: ajuste dinâmico de LR e controle de gradiente.
2
-
3
- Implementa as seções 9-10 de dados.txt:
4
-
5
- 9. AJUSTE DINÂMICO DAS TAXAS DE APRENDIZADO:
6
- fator_G = exp(-κ * ||grad_G||) * (1 + v_media) / 2
7
- novo_eta_G = eta_G * fator_G
8
-
9
- fator_V = exp(-κ * ||grad_V||) * (1 + L_V_media)^{-1}
10
- novo_eta_V = eta_V * fator_V
11
-
12
- 10. CONTROLE DE EXPLOSÃO DE GRADIENTE E ESPECTRAL NORM:
13
- - clip_grad_norm_(params, GRAD_CLIP)
14
- - Spectral normalization (power iteration) para Conv1D e Linear
15
- """
16
- from __future__ import annotations
17
-
18
- import logging
19
- import math
20
- from dataclasses import dataclass
21
- from typing import Dict, List, Optional, Tuple
22
-
23
- import torch
24
- import torch.nn as nn
25
-
26
- logger = logging.getLogger(__name__)
27
-
28
-
29
- @dataclass
30
- class AutoLearnConfig:
31
- """Configuração do auto-aprendizado."""
32
- kappa_curv: float = 0.01 # κ — fator de ajuste de η com norma do gradiente
33
- grad_clip: float = 1.0 # τ — clipping de gradiente (norma L2)
34
- spectral_radius: float = 1.0 # limite para norma espectral
35
- lr_min: float = 1e-6 # LR mínimo
36
- lr_max: float = 1e-2 # LR máximo
37
- initial_lr_G: float = 1e-3 # LR inicial do gerador
38
- initial_lr_V: float = 1e-3 # LR inicial do verificador
39
- use_spectral_norm: bool = True
40
- apply_after_step: bool = True
41
-
42
-
43
- class AutoLearner:
44
- """Controla ajuste dinâmico de LR, clipping e spectral norm.
45
-
46
- Não é um nn.Module — é um controlador que atua sobre modelos externos.
47
- """
48
-
49
- def __init__(self, config: AutoLearnConfig):
50
- self.cfg = config
51
- self.current_lr_G = config.initial_lr_G
52
- self.current_lr_V = config.initial_lr_V
53
- self.history: List[Dict] = []
54
-
55
- def compute_total_grad_norm(self, model: nn.Module) -> float:
56
- """Calcula a norma L2 total dos gradientes do modelo."""
57
- total = 0.0
58
- for p in model.parameters():
59
- if p.grad is not None:
60
- total += p.grad.data.norm(2).item() ** 2
61
- return math.sqrt(total)
62
-
63
- def update_learning_rates(
64
- self,
65
- grad_G_norm: float,
66
- grad_V_norm: float,
67
- v_mean: float,
68
- L_V_mean: float,
69
- ) -> Tuple[float, float]:
70
- """Atualiza dinamicamente as taxas de aprendizado.
71
-
72
- Args:
73
- grad_G_norm: norma L2 do gradiente do gerador
74
- grad_V_norm: norma L2 do gradiente do verificador
75
- v_mean: média das probabilidades do verificador
76
- L_V_mean: perda média do verificador
77
-
78
- Returns:
79
- (novo_eta_G, novo_eta_V)
80
- """
81
- # Fator do gerador: exp(-κ * ||grad||) * (1 + v_media) / 2
82
- fator_G = math.exp(-self.cfg.kappa_curv * grad_G_norm) * ((1.0 + v_mean) / 2.0)
83
- novo_eta_G = self.current_lr_G * fator_G
84
-
85
- # Fator do verificador: exp(-κ * ||grad||) * (1 + L_V)^{-1}
86
- # Evita divisão por zero
87
- fator_V = math.exp(-self.cfg.kappa_curv * grad_V_norm) / max(1.0 + L_V_mean, 1e-6)
88
- novo_eta_V = self.current_lr_V * fator_V
89
-
90
- # Clamp para evitar valores absurdos
91
- novo_eta_G = max(self.cfg.lr_min, min(self.cfg.lr_max, novo_eta_G))
92
- novo_eta_V = max(self.cfg.lr_min, min(self.cfg.lr_max, novo_eta_V))
93
-
94
- self.current_lr_G = novo_eta_G
95
- self.current_lr_V = novo_eta_V
96
-
97
- self.history.append({
98
- "lr_G": novo_eta_G,
99
- "lr_V": novo_eta_V,
100
- "grad_G_norm": grad_G_norm,
101
- "grad_V_norm": grad_V_norm,
102
- "v_mean": v_mean,
103
- "L_V_mean": L_V_mean,
104
- })
105
-
106
- return novo_eta_G, novo_eta_V
107
-
108
- def apply_clipping(self, *models: nn.Module) -> None:
109
- """Aplica gradient clipping global nos modelos."""
110
- for model in models:
111
- if model is not None:
112
- torch.nn.utils.clip_grad_norm_(model.parameters(), self.cfg.grad_clip)
113
-
114
- def apply_spectral_norm(self, model: nn.Module) -> int:
115
- """Aplica normalização espectral via power iteration em Conv1d/Linear.
116
-
117
- Após cada step, força ||W||_2 <= spectral_radius.
118
- """
119
- if not self.cfg.use_spectral_norm:
120
- return 0
121
- n_normalized = 0
122
- for module in model.modules():
123
- if isinstance(module, (nn.Linear, nn.Conv1d, nn.Conv2d)):
124
- if module.weight is not None and module.weight.dim() >= 2:
125
- try:
126
- with torch.no_grad():
127
- # Power iteration (1 iteração)
128
- W = module.weight
129
- # Reshape para 2D se necessário
130
- W_flat = W.reshape(W.size(0), -1)
131
- # u, v aleatórios (ou reutiliza se já existe)
132
- if not hasattr(module, "_spec_u"):
133
- u = torch.randn(W_flat.size(0), 1, device=W.device, dtype=W.dtype)
134
- u = u / u.norm()
135
- else:
136
- u = module._spec_u
137
- v = torch.matmul(W_flat.T, u)
138
- v = v / v.norm().clamp(min=1e-8)
139
- u = torch.matmul(W_flat, v)
140
- u = u / u.norm().clamp(min=1e-8)
141
- module._spec_u = u.detach()
142
- sigma = (u.T @ W_flat @ v).item()
143
- if sigma > self.cfg.spectral_radius:
144
- scale = self.cfg.spectral_radius / sigma
145
- module.weight.data.mul_(scale)
146
- n_normalized += 1
147
- except Exception as e:
148
- logger.debug("Spectral norm falhou em %s: %s", type(module).__name__, e)
149
- return n_normalized
150
-
151
- def set_optimizer_lr(self, optimizer: torch.optim.Optimizer, lr: float) -> None:
152
- """Atualiza a taxa de aprendizado de um otimizador."""
153
- for pg in optimizer.param_groups:
154
- pg["lr"] = lr
155
-
156
-
157
- def orthogonal_init_model(model: nn.Module) -> int:
158
- """Aplica inicialização ortogonal em todas as camadas Linear/Conv/GRUCell."""
159
- n = 0
160
- for module in model.modules():
161
- if isinstance(module, (nn.Linear, nn.Conv1d, nn.Conv2d)):
162
- try:
163
- nn.init.orthogonal_(module.weight)
164
- if module.bias is not None:
165
- nn.init.zeros_(module.bias)
166
- n += 1
167
- except Exception:
168
- pass
169
- elif isinstance(module, (nn.GRUCell, nn.GRU, nn.LSTM)):
170
- for name, p in module.named_parameters():
171
- if "weight" in name and p.dim() >= 2:
172
- try:
173
- nn.init.orthogonal_(p)
174
- n += 1
175
- except Exception:
176
- pass
177
- elif "bias" in name:
178
- nn.init.zeros_(p)
179
- return n
180
-
181
-
182
- def estimate_curvature(
183
- model: nn.Module,
184
- loss_fn,
185
- *args,
186
- eps: float = 1e-3,
187
- n_samples: int = 5,
188
- ) -> torch.Tensor:
189
- """Estima curvatura da perda via diferenças finitas.
190
-
191
- Para uma amostra de parâmetros, calcula:
192
- curv ≈ (L(θ + ε) - 2L(θ) + L(θ - ε)) / ε²
193
-
194
- Retorna a média das estimativas.
195
- """
196
- curvatures = []
197
- params = [p for p in model.parameters() if p.requires_grad and p.dim() >= 2]
198
- if not params:
199
- return torch.tensor(0.0)
200
-
201
- # Subamostra
202
- n_samples = min(n_samples, len(params))
203
- indices = torch.randperm(len(params))[:n_samples]
204
-
205
- for idx in indices:
206
- p = params[idx]
207
- # Pega um elemento aleatório
208
- flat = p.data.view(-1)
209
- if flat.numel() == 0:
210
- continue
211
- i = torch.randint(0, flat.numel(), (1,)).item()
212
- orig = flat[i].item()
213
-
214
- with torch.no_grad():
215
- # L(θ)
216
- try:
217
- loss_0 = loss_fn(*args)
218
- if isinstance(loss_0, dict):
219
- loss_0 = loss_0["total"]
220
- loss_0 = float(loss_0)
221
- except Exception:
222
- continue
223
-
224
- # L(θ + ε)
225
- flat[i] = orig + eps
226
- try:
227
- loss_p = loss_fn(*args)
228
- if isinstance(loss_p, dict):
229
- loss_p = loss_p["total"]
230
- loss_p = float(loss_p)
231
- except Exception:
232
- flat[i] = orig
233
- continue
234
-
235
- # L(θ - ε)
236
- flat[i] = orig - eps
237
- try:
238
- loss_m = loss_fn(*args)
239
- if isinstance(loss_m, dict):
240
- loss_m = loss_m["total"]
241
- loss_m = float(loss_m)
242
- except Exception:
243
- flat[i] = orig
244
- continue
245
-
246
- flat[i] = orig
247
- curv = (loss_p - 2 * loss_0 + loss_m) / (eps ** 2)
248
- curvatures.append(curv)
249
-
250
- if not curvatures:
251
- return torch.tensor(0.0)
252
-
253
- return torch.tensor(sum(curvatures) / len(curvatures))
254
-
255
-
256
- __all__ = [
257
- "AutoLearnConfig",
258
- "AutoLearner",
259
- "orthogonal_init_model",
260
- "estimate_curvature",
261
- ]