PowerMachine commited on
Commit
991b939
·
verified ·
1 Parent(s): b12e951

Delete docs/MATH_ANALYSIS.md with huggingface_hub

Browse files
Files changed (1) hide show
  1. docs/MATH_ANALYSIS.md +0 -819
docs/MATH_ANALYSIS.md DELETED
@@ -1,819 +0,0 @@
1
- # Análise Matemática — EWC, Context Window e Elementos Faltantes
2
-
3
- **Projeto:** CNN-BiGRU Multimodal Cooperativo Autoaprendível
4
- **Versão:** 2.0 (aprimoramento com EWC + Context Window + RoPE + Transformer Decoder)
5
- **Data:** 2026-08-11
6
-
7
- ---
8
-
9
- ## 1. Visão Geral
10
-
11
- Este documento registra a **análise matemática e lógica** da inclusão de:
12
-
13
- 1. **EWC (Elastic Weight Consolidation)** — aprendizado contínuo sem catastrophic forgetting
14
- 2. **Context Window** — janela deslizante com cache KV para sequências longas
15
- 3. **RoPE (Rotary Position Embeddings)** — codificação posicional rotacional
16
- 4. **CausalSelfAttention / TransformerBlock** — bloco decodificador causal
17
- 5. **Self-Attention final layer** — camada de auto-atenção verdadeira ao final de cada bloco (dados.txt linha 470)
18
-
19
- Também lista demais elementos faltantes identificados na análise do `dados.txt`.
20
-
21
- ---
22
-
23
- ## 2. Análise Matemática do EWC (Elastic Weight Consolidation)
24
-
25
- ### 2.1. Fundamentação Teórica
26
-
27
- O EWC (Kirkpatrick et al., 2017) regulariza o treinamento contínuo penalizando
28
- mudanças grandes nos parâmetros $\theta$ que foram importantes para tarefas
29
- anteriores. A importância é estimada pela **diagonal da matriz de informação
30
- de Fisher** $\mathcal{I}$.
31
-
32
- Para uma tarefa $\mathcal{T}_A$ treinada primeiro, a loss para a próxima tarefa
33
- $\mathcal{T}_B$ é:
34
-
35
- $$
36
- \mathcal{L}_{\text{total}}(\theta) \;=\; \mathcal{L}_{B}(\theta) \;+\; \sum_{i}
37
- \frac{\lambda_{\text{EWC}}}{2} \, \mathcal{I}_{i}^{A} \, \bigl(\theta_{i} -
38
- \theta_{A,i}^{*}\bigr)^{2}
39
- $$
40
-
41
- onde:
42
- - $\theta_{A}^{*}$ é o ótimo da tarefa $\mathcal{T}_A$ (congelado após treino de $A$)
43
- - $\mathcal{I}_{i}^{A}$ é a entrada diagonal $i$-ésima da matriz de Fisher para $A$
44
- - $\lambda_{\text{EWC}}$ é o peso da regularização
45
-
46
- ### 2.2. Estimativa da Matriz de Fisher (Diagonal)
47
-
48
- Para modelos com saída probabilística $p(y \mid x; \theta)$, a diagonal da
49
- Fisher Information Matrix pode ser estimada **em uma única passagem** como a
50
- média do quadrado dos gradientes pontuais:
51
-
52
- $$
53
- \mathcal{I}_{i}^{A} \;\approx\; \frac{1}{N} \sum_{n=1}^{N}
54
- \Bigl[\,\nabla_{\theta_{i}} \log p\bigl(y_{n}^{*} \mid x_{n}; \theta_{A}^{*}\bigr)
55
- \,\Bigr]^{2}
56
- $$
57
-
58
- onde $y_{n}^{*} = \arg\max_{y} p(y \mid x_n; \theta_A^*)$ (rótulo predito pelo
59
- próprio modelo — *empirical Fisher*).
60
-
61
- **Justificativa matemática:** A Fisher Information é a variância esperada do
62
- gradiente da log-verossimilhança; sob a hipótese de que $y_n^*$ é o rótulo
63
- verdadeiro (maximização), $\mathbb{E}[(\nabla \log p)^2] = -\mathbb{E}[\nabla^2
64
- \log p]$, que é a definição da Fisher Information. A versão *empirical* usa
65
- $y^*$ no lugar de $y$ verdadeiro, que é viesada porém consistente para modelos
66
- bem-treinados.
67
-
68
- ### 2.3. Integração na Função de Perda do CNN-BiGRU
69
-
70
- A perda total do projeto (conforme `dados.txt` seção 8) é:
71
-
72
- $$
73
- \mathcal{L}_{\text{total}} \;=\; \alpha \, \mathcal{L}_{G}^{\text{total}}
74
- \;+\; \beta \, \mathcal{L}_{V} \;+\; \gamma \, \mathcal{L}_{AH} \;+\; \delta \,
75
- \mathcal{L}_{\text{reg}}
76
- $$
77
-
78
- A inclusão do EWC adiciona um novo termo $\mathcal{L}_{\text{EWC}}$ à
79
- regularização $\mathcal{L}_{\text{reg}}$:
80
-
81
- $$
82
- \mathcal{L}_{\text{reg}}^{\text{new}} \;=\; \mathcal{L}_{\text{reg}}^{\text{old}}
83
- \;+\; \mathcal{L}_{\text{EWC}}
84
- \;=\; \lambda_{L2} \sum_i \theta_i^2 \;+\;
85
- \kappa \, \text{tr}(\hat{H}) \;+\; \sum_i \frac{\lambda_{\text{EWC}}}{2} \,
86
- F_i \, (\theta_i - \theta_i^*)^2
87
- $$
88
-
89
- **Implementação diferenciável:** a penalidade é uma forma quadrática nos
90
- parâmetros atuais, portanto $\nabla_{\theta} \mathcal{L}_{\text{EWC}} = \lambda_{\text{EWC}}
91
- \cdot F \odot (\theta - \theta^*)$, onde $\odot$ é produto Hadamard.
92
-
93
- ### 2.4. Pontos de Integração no Pipeline
94
-
95
- | Etapa | Ação | Módulo |
96
- |-------|------|--------|
97
- | Após treinar tarefa A | Calcular $F$ e armazenar $\theta^*$ | `utils/ewc.py:compute_fisher` |
98
- | A cada step da tarefa B | Somar $\mathcal{L}_{\text{EWC}}$ à perda | `losses/losses.py` |
99
- | Treino multitarefa | Manter lista $[(\theta^*_k, F_k)]$ e somar EWC de todas as tarefas anteriores | `utils/ewc.py:EWCState` |
100
-
101
- ### 2.5. Análise de Estabilidade
102
-
103
- - **Limit $\lambda_{\text{EWC}} \to 0$:** EWC desligado → catastrophic forgetting total
104
- - **Limit $\lambda_{\text{EWC}} \to \infty$:** parâmetros congelados → sem aprendizado novo
105
- - **Compromisso prático:** $\lambda_{\text{EWC}} \in [100, 10000]$ tipicamente
106
- recomendado na literatura
107
-
108
- **Garantia matemática:** sob a hipótese de que $\mathcal{L}_B$ é fortemente
109
- convexa em $\theta^*$ e $F \succ 0$, o EWC é equivalente a uma aproximação
110
- de Laplace da posterior $p(\theta \mid \mathcal{D}_A)$, garantindo que a solução
111
- ótima permaneça próxima de $\theta^*$ ao longo do treino de $\mathcal{T}_B$.
112
-
113
- ### 2.6. Riscos e Mitigação
114
-
115
- | Risco | Mitigação |
116
- |-------|-----------|
117
- | $F$ é ruidosa para pequenos batches | Usar `n_samples_fisher ≥ 500` e média móvel exponencial |
118
- | Memória: armazenar $F$ igual ao tamanho do modelo | Usar **diagonal apenas** (mesmo tamanho do modelo, viável) |
119
- | $\theta^*$ fica defasado após muitas tarefas | Implementar **online EWC**: $F^{\text{new}} = \gamma F^{\text{old}} + F^{\text{current}}$ |
120
- | EWC pode entrar em conflito com spectral norm | Aplicar EWC **apenas** aos pesos não-normalizados espectralmente |
121
-
122
- ---
123
-
124
- ## 3. Análise Matemática do Context Window
125
-
126
- ### 3.1. Motivação
127
-
128
- O `dados.txt` seção 7 (Transformer Decoder) define `max_seq_len` como
129
- comprimento máximo de contexto. Sem um mecanismo de **janela deslizante**, o
130
- modelo:
131
-
132
- 1. Não consegue processar entradas maiores que `max_seq_len`
133
- 2. Recomputa toda a sequência a cada token gerado → $O(T^2)$ em inferência
134
- 3. Não consegue manter coerência em diálogos longos
135
-
136
- ### 3.2. Formulação Matemática
137
-
138
- Seja $x_{1:T}$ uma sequência de comprimento $T > L_{\max}$ (janela máxima).
139
- Definimos a janela deslizante $\mathcal{W}_t$ no passo $t$ como:
140
-
141
- $$
142
- \mathcal{W}_t \;=\; x_{\max(1,\,t-L_{\max}+1)\,:\,t}
143
- $$
144
-
145
- A saída do modelo no passo $t$ depende apenas de $\mathcal{W}_t$:
146
-
147
- $$
148
- h_t \;=\; f_\theta\bigl(\mathcal{W}_t\bigr)
149
- $$
150
-
151
- ### 3.3. Cache KV para Atenção Eficiente
152
-
153
- Para a CausalSelfAttention, o custo de inferência autoregressiva sem cache é:
154
-
155
- $$
156
- \text{FLOPs}_{\text{no cache}}(T) \;=\; O\bigl(T^2 \cdot d\bigr)
157
- $$
158
-
159
- Com cache dos pares $(K, V)$ dos passos anteriores, cada novo token $t$ apenas:
160
-
161
- 1. Calcula $q_t, k_t, v_t$ para o novo token (custo $O(d)$)
162
- 2. Concatena com cache: $K_{1:t} = [K_{1:t-1}; k_t]$, $V_{1:t} = [V_{1:t-1}; v_t]$
163
- 3. Calcula atenção apenas do novo $q_t$ contra todo $K_{1:t}$ (custo $O(t \cdot d)$)
164
-
165
- $$
166
- \text{FLOPs}_{\text{with cache}}(T) \;=\; O\bigl(T \cdot d\bigr)
167
- $$
168
-
169
- **Speedup teórico:** fator $T$. Para $T = 512$ e $d = 256$, speedup ~512×.
170
-
171
- ### 3.4. Política de Evicção (Chunked Cache)
172
-
173
- Quando $|\mathcal{W}_t| > L_{\max}$, aplicamos uma política de evicção. As três
174
- estratégias analisadas:
175
-
176
- #### 3.4.1. Sliding Window Pura
177
- Mantém apenas os últimos $L_{\max}$ tokens. Custo: $O(L_{\max})$ por step.
178
- Desvantagem: perde informação histórica relevante.
179
-
180
- #### 3.4.2. Sink + Sliding (StreamingLLM)
181
- Mantém os primeiros $k$ tokens ("sink", tipicamente BOS + system prompt) e os
182
- últimos $L_{\max} - k$ tokens. Custo: $O(L_{\max})$. Vantagem: preserva
183
- informação estrutural inicial.
184
-
185
- $$
186
- \mathcal{W}_t \;=\; \bigl[\,x_{1:k}\,;\, x_{t-(L_{\max}-k)+1\,:\,t}\,\bigr]
187
- $$
188
-
189
- #### 3.4.3. Attention Recomputation (sem cache)
190
- Recomputa a atenção sobre toda a sequência a cada step. Custo: $O(T^2)$.
191
- Vantagem: máxima precisão. Desvantagem: proibitivo para $T$ grande.
192
-
193
- **Implementação escolhida:** Sink + Sliding (StreamingLLM), com $k=4$ tokens
194
- sink configurável. Esta estratégia tem garantia teórica de estabilidade para
195
- $T \to \infty$ (Xiao et al., 2023).
196
-
197
- ### 3.5. Integração com CNN-BiGRU Cooperativo
198
-
199
- O CNN-BiGRU cooperativo é **bidirecional** (processa $x_{1:T}$ em ambos os
200
- sentidos). Isto quebra a hipótese causal. Para preservar a bidirecionalidade:
201
-
202
- - **Modo encoder (treino/classificação):** sem cache, processa a janela inteira
203
- $\mathcal{W}_t$ com BiGRU normal (forward + backward).
204
- - **Modo decoder (geração):** usa GRU unidirecional + CausalSelfAttention com
205
- cache KV. Esta é a configuração usada para geração autoregressiva.
206
-
207
- ### 3.6. Análise de Complexidade
208
-
209
- | Componente | Sem Context Window | Com Context Window |
210
- |------------|-------------------|-------------------|
211
- | Geração de $T$ tokens | $O(T^2 d)$ | $O(T \cdot L_{\max} \cdot d)$ |
212
- | Memória de cache | $O(T d)$ | $O(L_{\max} d)$ |
213
- | Precisão em longas sequências | Falha para $T > L_{\max}$ | Mantém coerência via sink |
214
-
215
- ### 3.7. Riscos e Mitigação
216
-
217
- | Risco | Mitigação |
218
- |-------|-----------|
219
- | Perda de contexto ao evictar | Estratégia sink + sliding |
220
- | Cache desatualizado após fine-tuning | Invalidar cache quando pesos mudam |
221
- | Incompatibilidade com BiGRU (bidirecional) | Usar GRU unidirecional no decoder |
222
- | Memória cresce com $L_{\max}$ | Limitar $L_{\max} \leq 1024$ para CPU |
223
-
224
- ---
225
-
226
- ## 4. Demais Elementos Faltantes Identificados
227
-
228
- ### 4.1. RoPE (Rotary Position Embeddings)
229
-
230
- **Status no projeto atual:** AUSENTE. A codificação posicional atual depende
231
- apenas da convolução 1D (local) e da recorrência GRU (implícita).
232
-
233
- **Formulação matemática (Su et al., 2021):**
234
-
235
- Para um par $(q, k)$ em uma dada posição $(m, n)$, RoPE aplica uma rotação
236
- no plano 2D para cada par de dimensões $(q_{2i}, q_{2i+1})$:
237
-
238
- $$
239
- \begin{pmatrix} q'_{2i} \\ q'_{2i+1} \end{pmatrix}
240
- \;=\;
241
- \begin{pmatrix} \cos(m\theta_i) & -\sin(m\theta_i) \\ \sin(m\theta_i) & \cos(m\theta_i) \end{pmatrix}
242
- \begin{pmatrix} q_{2i} \\ q_{2i+1} \end{pmatrix}
243
- $$
244
-
245
- com $\theta_i = 10000^{-2i/d}$. A propriedade chave é:
246
-
247
- $$
248
- \langle \text{RoPE}(q, m), \text{RoPE}(k, n) \rangle \;=\; \langle
249
- \text{RoPE}(q, m-n), k \rangle
250
- $$
251
-
252
- → a atenção depende apenas da diferença posicional relativa, não absoluta.
253
-
254
- **Integração:** Substitui `position_embedding = nn.Embedding(max_seq_len, embed_dim)`
255
- no TransformerBlock. Aplica-se a `q` e `k` antes do produto escalar.
256
-
257
- ### 4.2. CausalSelfAttention / TransformerBlock
258
-
259
- **Status no projeto atual:** AUSENTE. Apenas Bahdanau attention existe no
260
- `generator_verifier.py`, e ela é não-causal (encoder-decoder).
261
-
262
- **Especificação (dados.txt seções 6-7):**
263
-
264
- ```python
265
- class CausalSelfAttention(nn.Module):
266
- # Multi-head com máscara triangular inferior
267
- # QKV projection unificada
268
- # Scaled dot-product: (q @ k.T) / sqrt(d_head)
269
- # Máscara causal: triu(ones(T,T)) == 0 → -inf
270
- # Softmax + dropout
271
-
272
- class TransformerBlock(nn.Module):
273
- # Pre-LN: x = x + attn(ln1(x))
274
- # x = x + ffn(ln2(x))
275
- # FFN: Linear(d, 4d) → GELU → Linear(4d, d) → Dropout
276
- ```
277
-
278
- **Integração:** Como camada opcional no `CooperativeCNNBiGRU` para agregar
279
- informação global antes da fusão final.
280
-
281
- ### 4.3. Self-Attention Final Layer (dados.txt linha 470)
282
-
283
- **Status no projeto atual:** PARCIAL. Existe `SelfAttentionSummary` mas usa
284
- `x.mean(dim=1)` como query — não é uma self-attention verdadeira.
285
-
286
- **Correção:** substituir por uma self-attention com `query = Linear(d, d)(x)`
287
- (verdadeira projeção de query, não média).
288
-
289
- ### 4.4. Gradient Checkpointing
290
-
291
- **Status no projeto atual:** Declarado em `memory_optimizer.py` mas NUNCA
292
- chamado. Deve ser ativado no `CooperativeTrainer` para reduzir consumo de
293
- VRAM em modelos grandes.
294
-
295
- ### 4.5. Weight Tying
296
-
297
- **Status no projeto atual:** AUSENTE. O `dados.txt` linha 632 explicitamente
298
- recomenda: `self.token_embedding.weight = self.lm_head.weight`. Deve ser
299
- opcional no `MultimodalCNNBiGRU`.
300
-
301
- ### 4.6. AMP (Automatic Mixed Precision)
302
-
303
- **Status no projeto atual:** PARCIAL — `memory_optimizer.amp_context` retorna
304
- `nullcontext()` para CPU. Como o `xeon_runtime.py` detecta AMX/AVX512_BF16,
305
- deve habilitar `bfloat16` autocast em CPU também (PyTorch 1.10+).
306
-
307
- ### 4.7. Online EWC
308
-
309
- **Status no projeto atual:** AUSENTE. Após múltiplas tarefas, a soma de
310
- $F_k$ explode em memória. Online EWC mantém apenas uma $F$ agregada:
311
-
312
- $$
313
- F^{\text{agg}} \;=\; \gamma \, F^{\text{prev}} \;+\; (1-\gamma) \, F^{\text{new}}
314
- $$
315
-
316
- ### 4.8. Tokenizer: add_tokens dinâmico
317
-
318
- **Status no projeto atual:** AUSENTE. O `BBPETokenizer` não suporta adicionar
319
- novos tokens após o treino. Útil para fine-tuning com vocabulário especializado.
320
-
321
- ### 4.9. Verificador Realmente Acionado
322
-
323
- **Status no projeto atual:** BUG. `trainer.py` instancia `VerifierCNNBiGRU`
324
- mas **NUNCA chama seu forward** — usa um proxy `sigmoid(fused.mean(-1))`.
325
-
326
- **Correção:** Chamar `verifier(premissas_a, passo_a, premissas_b, passo_b)`
327
- com tokens reais gerados pelo `GeneratorCNNBiGRU`.
328
-
329
- ### 4.10. Hipótese com Porta Funcional
330
-
331
- **Status no projeto atual:** BUG. `hypothesis_controller.py` calcula `gate`
332
- mas `output = gate*combined + (1-gate)*combined = combined` (sempre).
333
-
334
- **Correção:** `x_proj = hypothesis_layer(x)` (projeção real), `output = gate *
335
- x_proj + (1-gate) * x` (interpolação entre a hipótese e o input original).
336
-
337
- ### 4.11. Geração Autoregressiva Real
338
-
339
- **Status no projeto atual:** BUG. `inference.py` chama
340
- `model(..., mode="generate")` que retorna `[B, V]` (single-step) — não há
341
- autoregressão real.
342
-
343
- **Correção:** Implementar loop que:
344
- 1. Processa prompt inicial
345
- 2. A cada passo: extrai último logit, aplica sampling, anexa novo token,
346
- atualiza cache KV, repete
347
-
348
- ### 4.12. Multi-loss com Device Consistency
349
-
350
- **Status no projeto atual:** BUG. `losses.py` usa `torch.tensor(0.0)` sem
351
- `device=`, quebrando em GPU.
352
-
353
- **Correção:** Sempre criar tensores zero no device correto, ou usar
354
- `torch.zeros((), device=device)`.
355
-
356
- ### 4.13. Inicialização Ortogonal Robusta
357
-
358
- **Status no projeto atual:** PARCIAL — `_orthogonal_init` faz fallback
359
- silencioso para `xavier_uniform_` em caso de exceção.
360
-
361
- **Correção:** Registrar o erro em log, propagar exceção em modo debug.
362
-
363
- ### 4.14. Penalidade Exponencial Conforme Spec
364
-
365
- **Status no projeto atual:** DESVIO SEMÂNTICO. `losses.py` aplica
366
- $\sum \exp(\gamma(1-v))$ **apenas** para $v < \text{threshold}$, mas o
367
- `dados.txt` seção 8.2 diz "SE v_t < THRESHOLD_ERR: L_exp_penal += ..." (que é
368
- o comportamento atual — OK na verdade). Mas a soma linear
369
- $\sum (1-v_t)$ deve ser sobre TODOS os passos, não apenas os penalizados.
370
-
371
- **Revisão:** está correto conforme spec; apenas documentar claramente.
372
-
373
- ### 4.15. Package `__init__.py`
374
-
375
- **Status no projeto atual:** VAZIO. Deve exportar principais classes,
376
- definir `__version__`, configurar logging.
377
-
378
- ---
379
-
380
- ## 5. Resumo dos Elementos a Implementar
381
-
382
- | ID | Elemento | Prioridade | Complexidade | Impacto |
383
- |----|----------|-----------|--------------|---------|
384
- | E1 | EWC (Fisher + penalty) | Alta | Média | Mitiga catastrophic forgetting |
385
- | E2 | Context Window (sliding + KV cache) | Alta | Alta | Suporte a sequências longas |
386
- | E3 | RoPE | Média | Baixa | Codificação posicional relativa |
387
- | E4 | CausalSelfAttention + TransformerBlock | Alta | Média | Decoder autoregressivo |
388
- | E5 | Self-Attention final layer correta | Alta | Baixa | Resumo temporal conforme spec |
389
- | E6 | Gradient Checkpointing | Baixa | Baixa | Reduz VRAM |
390
- | E7 | Weight Tying | Baixa | Baixa | Reduz parâmetros |
391
- | E8 | AMP em CPU (bfloat16) | Média | Baixa | Speedup em Xeon |
392
- | E9 | Online EWC | Baixa | Baixa | Suporte a múltiplas tarefas |
393
- | E10 | Verificador real no trainer | Alta | Média | Funcionalidade core |
394
- | E11 | Hipótese com porta funcional | Alta | Baixa | Funcionalidade core |
395
- | E12 | Geração autoregressiva real | Alta | Alta | Inferência correta |
396
- | E13 | Multi-loss device-safe | Alta | Baixa | Correção de bug |
397
- | E14 | Orthogonal init robusto | Média | Baixa | Estabilidade |
398
- | E15 | `__init__.py` com exports | Baixa | Baixa | Usabilidade |
399
-
400
- ---
401
-
402
- ## 6. Plano de Implementação
403
-
404
- ### Fase 1 — Novos Módulos
405
- 1. `cnn_bigru/utils/ewc.py` — EWC completo (offline + online)
406
- 2. `cnn_bigru/models/context_window.py` — Context window com KV cache
407
- 3. `cnn_bigru/models/rope.py` — RoPE
408
- 4. `cnn_bigru/models/transformer_block.py` — CausalSelfAttention + TransformerBlock
409
-
410
- ### Fase 2 — Correções de Bugs Críticos
411
- 5. `cnn_bigru/models/cooperative_bigru.py` — Self-Attention final correta
412
- 6. `cnn_bigru/models/multimodal_model.py` — Fix dimensão d_text + weight tying
413
- 7. `cnn_bigru/training/hypothesis_controller.py` — Fix gate logic
414
- 8. `cnn_bigru/models/generator_verifier.py` — Fix enc_out repetition
415
- 9. `cnn_bigru/training/trainer.py` — Integrar verificador + hipótese + EWC + context window
416
- 10. `cnn_bigru/losses/losses.py` — Device-safe + EWC term
417
- 11. `cnn_bigru/training/auto_learner.py` — Buffer registration + l2_reg + try/finally
418
- 12. `cnn_bigru/inference/inference.py` — Geração autoregressiva real
419
- 13. `cnn_bigru/data/streaming_dataset.py` — Synthetic fallback reachability
420
- 14. `cnn_bigru/utils/semantic_embeddings.py` — Integrar no pipeline
421
-
422
- ### Fase 3 — Embalagem
423
- 15. `cnn_bigru/__init__.py` — Exports + versão
424
- 16. `cnn_bigru/scripts/push_to_hf.py` — `upload_folder` + filtro robusto
425
-
426
- ### Fase 4 — Validação
427
- 17. `cnn_bigru/tests/test_50_samples.py` — Testar todos os novos módulos
428
- 18. Executar teste, capturar erros, iterar
429
-
430
- ### Fase 5 — Publicação
431
- 19. Push para HF `CNN-BiGRU` (overwrite outdated)
432
- 20. Deletar `HF_TOKEN` do ambiente
433
-
434
- ---
435
-
436
- ## 7. Referências
437
-
438
- - Kirkpatrick, J. et al. **"Overcoming catastrophic forgetting in neural networks"**. PNAS 2017.
439
- - Xiao, G. et al. **"Efficient Streaming Language Models with Attention Sinks"**. 2023.
440
- - Su, J. et al. **"RoFormer: Enhanced Transformer with Rotary Position Embedding"**. 2021.
441
- - Vaswani, A. et al. **"Attention Is All You Need"**. NeurIPS 2017.
442
- - `dados.txt` — pseudocódigo completo do projeto CNN-BiGRU cooperativo.
443
-
444
- ---
445
-
446
- **Fim do documento.**
447
-
448
- ---
449
-
450
- # Análise Matemática v3.0 — Novos Módulos
451
-
452
- **Data:** 2026-08-11
453
- **Versão:** 3.0 (aprimoramento com 9 novos módulos)
454
-
455
- ---
456
-
457
- ## 8. Raciocínio Cíclico (Cyclic Reasoning)
458
-
459
- ### 8.1. Fundamentação
460
-
461
- O Raciocínio Cíclico refina iterativamente a representação $h \in \mathbb{R}^d$
462
- através de múltiplos ciclos, cada um combinando o estado atual com uma
463
- hipótese gerada por um controlador externo:
464
-
465
- $$
466
- h_0 \xrightarrow{\text{cycle 1}} h_1 \xrightarrow{\text{cycle 2}} h_2 \xrightarrow{\text{cycle 3}} \dots \xrightarrow{\text{cycle } C} h_C
467
- $$
468
-
469
- Em cada ciclo $c$:
470
-
471
- $$
472
- \begin{aligned}
473
- g_c &= \text{HypothesisController}(h_{c-1}, \text{penalty}_c) \in \mathbb{R}^d \\
474
- r_c &= \text{RefinementLayer}([h_{c-1}; g_c]) \in \mathbb{R}^d \\
475
- \alpha_c &= \sigma(w_\alpha^\top h_{c-1} + b_\alpha) \in [0, 1] \\
476
- h_c &= \text{LayerNorm}(h_{c-1} + \alpha_c \cdot r_c)
477
- \end{aligned}
478
- $$
479
-
480
- ### 8.2. Critério de Convergência
481
-
482
- O loop para quando $\|h_c - h_{c-1}\|_2 < \epsilon$ ou $c = C_{\max}$.
483
-
484
- ### 8.3. Garantias Matemáticas
485
-
486
- 1. **Diferenciabilidade**: todas as operações são diferenciáveis. Suporte a
487
- truncated BPTT (Backpropagation Through Time) com $K$ ciclos preservados
488
- no grafo.
489
- 2. **Contração**: se o refinement for Lipschitz com $L < 1$, a sequência
490
- $\{h_c\}$ é de Cauchy e converge.
491
- 3. **Anti-hallucination gate**: valor de verdade fuzzy $\tau_c \in [0, 1]$
492
- baseado em lógica de Łukasiewicz. Se $\tau_c < \tau_{\min}$, o ciclo é
493
- rejeitado (h permanece).
494
-
495
- ---
496
-
497
- ## 9. NLG (Natural Language Generation) com Medusa MTP
498
-
499
- ### 9.1. Arquitetura
500
-
501
- O módulo NLG combina:
502
- - **TransformerDecoderStack** (backbone causal com RoPE)
503
- - **MedusaMTP** (Multi-Token Prediction com $K$ cabeças extras)
504
- - **CyclicReasoning** (opcional, refinamento iterativo)
505
- - **ContextWindowManager** (janela deslizante com cache KV)
506
-
507
- ### 9.2. Loss de Treinamento
508
-
509
- $$
510
- \mathcal{L}_{\text{NLG}} = \mathcal{L}_{\text{CE}}(\text{lm\_head}(h_t), y_{t+1}) + \mu_{\text{medusa}} \cdot \mathcal{L}_{\text{Medusa}} + \mu_{\text{ewc}} \cdot \mathcal{L}_{\text{EWC}}
511
- $$
512
-
513
- onde:
514
-
515
- $$
516
- \mathcal{L}_{\text{Medusa}} = \sum_{k=1}^{K} \lambda_k \cdot \text{CE}(\text{head}_k(h_t), y_{t+k+1})
517
- $$
518
-
519
- com pesos decrescentes $\lambda_k = \frac{1}{k+1}$.
520
-
521
- ---
522
-
523
- ## 10. NLP (Natural Language Processing)
524
-
525
- ### 10.1. Tarefas Suportadas
526
-
527
- 1. **Sequence Classification**: $\text{logits} = \text{Linear}(D, C) \cdot \text{Pool}(\text{seq})$
528
- 2. **Token Classification**: $\text{logits}_{t} = \text{Linear}(D, L) \cdot h_t$ para cada posição $t$
529
- 3. **Span Detection**: $(\text{start\_logits}, \text{end\_logits}) = \text{Linear}(D, 1) \cdot h_t$
530
- 4. **Embedding (retrieval)**: $\text{emb} = \text{normalize}_{L^2}(\text{mean\_pool}(h))$
531
-
532
- ### 10.2. Loss InfoNCE para Retrieval
533
-
534
- $$
535
- \mathcal{L}_{\text{InfoNCE}} = -\log \frac{\exp(\text{sim}(q, p^+) / \tau)}{\exp(\text{sim}(q, p^+) / \tau) + \exp(\text{sim}(q, p^-) / \tau)}
536
- $$
537
-
538
- onde $\text{sim}(u, v) = \cos(u, v)$ (similaridade cosseno após normalização $L^2$).
539
-
540
- ---
541
-
542
- ## 11. W8A8 Quantization via SmoothQuant
543
-
544
- ### 11.1. Problema dos Outliers em Ativações
545
-
546
- Em modelos LLM, alguns canais de ativação têm outliers que saturam a
547
- quantização INT8 direta. A solução SmoothQuant (Xiao et al., 2023) migra
548
- a variância das ativações para os pesos.
549
-
550
- ### 11.2. Fórmula Matemática
551
-
552
- Seja $Y = X \cdot W$ onde $X \in \mathbb{R}^{B \times T \times d_{\text{in}}}$,
553
- $W \in \mathbb{R}^{d_{\text{in}} \times d_{\text{out}}}$.
554
-
555
- Para cada canal de entrada $i$, computa-se a escala de suavização:
556
-
557
- $$
558
- s_i = \frac{\max|X_i|^\alpha}{\max|W_i|^{1-\alpha}}, \quad \alpha \in [0, 1]
559
- $$
560
-
561
- com $\alpha = 0.5$ (default, balanceado).
562
-
563
- A operação matricial é matematicamente equivalente:
564
-
565
- $$
566
- Y = X \cdot W = \left(\frac{X}{s}\right) \cdot (s \cdot W) = X' \cdot W'
567
- $$
568
-
569
- Após a suavização, ambos $X'$ e $W'$ têm variância uniforme e podem ser
570
- quantizados a INT8 com perda mínima:
571
-
572
- $$
573
- X_q = \text{round}\left(\frac{X'}{\text{scale}_x}\right) \cdot \text{scale}_x, \quad
574
- W_q = \text{round}\left(\frac{W'}{\text{scale}_w}\right) \cdot \text{scale}_w
575
- $$
576
-
577
- ### 11.3. Redução de Memória
578
-
579
- - FP32: 4 bytes/parâmetro
580
- - INT8: 1 byte/parâmetro
581
- - **Redução teórica**: 4× (75%)
582
- - Em hardware com AMX/AVX512-VNNI: speedup de 2-4×
583
-
584
- ---
585
-
586
- ## 12. VQ-VAE-2 Hierárquico
587
-
588
- ### 12.1. Arquitetura de Dois Níveis
589
-
590
- $$
591
- x \xrightarrow{\text{BottomEnc}} z_b \xrightarrow{\text{TopEnc}} z_t \xrightarrow{\text{TopQ}} z_t^q \xrightarrow{\text{TopDec}} \hat{z}_t \xrightarrow{+ z_b^q} \xrightarrow{\text{BottomDec}} \hat{x}
592
- $$
593
-
594
- Onde:
595
- - $z_b \in \mathbb{R}^{B \times d_b \times H \times W}$: representação bottom (detalhes locais)
596
- - $z_t \in \mathbb{R}^{B \times d_t \times H/2 \times W/2}$: representação top (semântica global)
597
-
598
- ### 12.2. Loss Total
599
-
600
- $$
601
- \mathcal{L} = \mathcal{L}_{\text{recon}} + \beta \cdot (\mathcal{L}_{\text{commit}}^{\text{top}} + \mathcal{L}_{\text{commit}}^{\text{bottom}}) + \gamma \cdot (\mathcal{L}_{\text{codebook}}^{\text{top}} + \mathcal{L}_{\text{codebook}}^{\text{bottom}})
602
- $$
603
-
604
- onde:
605
- - $\mathcal{L}_{\text{recon}} = \text{MSE}(x, \hat{x})$
606
- - $\mathcal{L}_{\text{commit}}^k = \|\text{sg}(z_k) - e_k\|_2^2$ (commit loss)
607
- - $\mathcal{L}_{\text{codebook}}^k = \|z_k - \text{sg}(e_k)\|_2^2$ (codebook loss)
608
- - $\text{sg}$ = stop-gradient
609
-
610
- ### 12.3. Atualização EMA do Codebook
611
-
612
- $$
613
- \begin{aligned}
614
- n_k^{(t+1)} &= \gamma_{\text{ema}} \cdot n_k^{(t)} + (1 - \gamma_{\text{ema}}) \cdot \sum_i \mathbb{1}[k_i = k] \\
615
- m_k^{(t+1)} &= \gamma_{\text{ema}} \cdot m_k^{(t)} + (1 - \gamma_{\text{ema}}) \cdot \sum_i z_i \cdot \mathbb{1}[k_i = k] \\
616
- e_k &= \frac{m_k}{n_k + \epsilon}
617
- \end{aligned}
618
- $$
619
-
620
- ### 12.4. Straight-Through Estimator (STE)
621
-
622
- $$
623
- z_q^{\text{ST}} = z + (z_q - z).\text{detach}()
624
- $$
625
-
626
- Garante que o gradiente flua para $z$ apesar da operação não-diferenciável de quantização.
627
-
628
- ---
629
-
630
- ## 13. Multi-Token Prediction (MTP) com Medusa Heads
631
-
632
- ### 13.1. Cabeças Múltiplas
633
-
634
- Para cada hidden state $h_t$, o Medusa adiciona $K$ cabeças de previsão:
635
-
636
- $$
637
- y_{t+k} = \text{softmax}(W_k \cdot h_t + b_k), \quad k = 1, \ldots, K
638
- $$
639
-
640
- A cabeça $k=1$ é o LM head original; $k=2, \ldots, K$ são cabeças extras.
641
-
642
- ### 13.2. Loss Medusa
643
-
644
- $$
645
- \mathcal{L}_{\text{Medusa}} = \sum_{k=1}^{K} \lambda_k \cdot \text{CE}(\text{head}_k(h_t), y_{t+k+1})
646
- $$
647
-
648
- com $\lambda_k = \frac{1}{k+1}$ (pesos decrescentes — previsões mais distantes são mais difíceis).
649
-
650
- ### 13.3. Tree Decoding em Inferência
651
-
652
- Em inferência, cada cabeça Medusa gera top-$B$ candidatos, formando uma
653
- árvore de $B^K$ filhos. A árvore é avaliada em paralelo (single forward)
654
- e os candidatos são aceitos se coincidirem com a previsão do modelo.
655
-
656
- **Speedup teórico**: até $K\times$ (em prática 2-3× devido à taxa de aceitação < 1).
657
-
658
- ---
659
-
660
- ## 14. Multimodal Multi-Head Attention
661
-
662
- ### 14.1. Cross-Modal Attention
663
-
664
- Para modalidades $i$ e $j$ ($i \neq j$):
665
-
666
- $$
667
- \begin{aligned}
668
- Q_i &= H_i \cdot W_Q^i \\
669
- K_j &= H_j \cdot W_K^j \\
670
- V_j &= H_j \cdot W_V^j \\
671
- A_{i \to j} &= \text{softmax}\left(\frac{Q_i \cdot K_j^\top}{\sqrt{d_h}}\right) \cdot V_j
672
- \end{aligned}
673
- $$
674
-
675
- ### 14.2. Atualização da Modalidade
676
-
677
- $$
678
- H_i' = H_i + \sum_{j \neq i} A_{i \to j}
679
- $$
680
-
681
- ### 14.3. Modality Gate
682
-
683
- $$
684
- \alpha_i = \text{softmax}\left(\text{scorer}(\tanh(\text{proj}_i(\text{Pool}(H_i))))\right)
685
- $$
686
-
687
- Permite pesar dinamicamente cada modalidade (e.g., imagem é mais importante para pergunta visual).
688
-
689
- ### 14.4. Fusão Final
690
-
691
- $$
692
- H_{\text{fused}} = \text{Linear}\left([\alpha_a \cdot \bar{H}_a; \alpha_b \cdot \bar{H}_b; \alpha_{\text{img}} \cdot \bar{H}_{\text{img}}; \alpha_{\text{aud}} \cdot \bar{H}_{\text{aud}}]\right)
693
- $$
694
-
695
- ---
696
-
697
- ## 15. Long Context Window (1M tokens) — Chunked / Ring Attention
698
-
699
- ### 15.1. Motivação
700
-
701
- Para 1M tokens, o cache KV FP32 requer:
702
-
703
- $$
704
- \text{memória} = n_{\text{layers}} \times d_{\text{model}} \times 10^6 \times 8 \text{ bytes} \approx 12 \text{ GB}
705
- $$
706
-
707
- Isto é inviável em CPU. A solução é **chunked attention**: dividir a
708
- sequência em chunks de tamanho $C$ (e.g., 8192) e processar cada chunk
709
- separadamente.
710
-
711
- ### 15.2. Estratégias
712
-
713
- 1. **chunked**: cache KV apenas para o chunk atual + sink tokens
714
- 2. **ring**: Ring Attention — distribui chunks entre $N$ GPUs (memória/N)
715
- 3. **sink_sliding_long**: sink + sliding com window grande
716
- 4. **hybrid**: chunked para encoder, sink_sliding para decoder
717
-
718
- ### 15.3. Sumarização Hierárquica
719
-
720
- Para manter contexto global, cada chunk produz um sumário:
721
-
722
- $$
723
- \bar{c}_k = \text{Pool}(\text{Attention}(c_k))
724
- $$
725
-
726
- Os sumários são agregados em um contexto global:
727
-
728
- $$
729
- \bar{C} = \frac{1}{K} \sum_{k=1}^{K} \bar{c}_k
730
- $$
731
-
732
- ### 15.4. Memória por Chunk
733
-
734
- $$
735
- \text{memória/chunk} = n_{\text{layers}} \times d_{\text{model}} \times C \times 8 \approx 16 \text{ MB} \quad (C = 8192)
736
- $$
737
-
738
- ---
739
-
740
- ## 16. Monitor Completo
741
-
742
- ### 16.1. Métricas Rastreadas
743
-
744
- 1. **Treino**: loss, PPL, LR (G/V), grad norm, hypothesis activations, synergy history
745
- 2. **Inferência**: tokens gerados, Medusa accept rate, ms/token, throughput
746
- 3. **Evolução**: CyclicReasoning stats, VQ-VAE-2 codebook usage, quantization stats, EWC penalty evolution
747
- 4. **Sistema**: CPU%, memória (MB), GPU memory (se disponível)
748
-
749
- ### 16.2. Exportação
750
-
751
- - JSON report completo (`monitor_report.json`)
752
- - CSV time series (`batch_metrics.csv`)
753
- - Markdown summary (`monitor_summary.md`)
754
-
755
- ---
756
-
757
- ## 17. Elementos Adicionais Identificados como Faltantes
758
-
759
- Após análise completa dos requisitos v3.0, foram identificados os seguintes
760
- elementos que ainda podem ser adicionados em versões futuras:
761
-
762
- | ID | Elemento | Prioridade | Complexidade | Justificativa |
763
- |----|----------|-----------|--------------|---------------|
764
- | F1 | Speculative Decoding (diferente do Medusa) | Média | Média | Speedup adicional em inferência |
765
- | F2 | LoRA / QLoRA fine-tuning | Alta | Média | Treino eficiente em downstream tasks |
766
- | F3 | DPO / RLHF training | Alta | Alta | Alinhamento com preferências humanas |
767
- | F4 | Flash Attention 2 | Média | Baixa | Speedup em GPU (não aplicável em CPU) |
768
- | F5 | MoE (Mixture of Experts) | Baixa | Alta | Escalar capacidade sem aumentar FLOPs |
769
- | F6 | KV cache quantization (FP8) | Média | Baixa | Reduzir memória do cache KV |
770
- | F7 | Continuous batching | Alta | Alta | Throughput em serving |
771
- | F8 | Distributed training (DDP/FSDP) | Alta | Alta | Treino em múltiplas GPUs |
772
- | F9 | Gradient checkpointing | Alta | Baixa | Reduzir memória de treino |
773
- | F10 | Tokenizer special tokens expandable | Baixa | Baixa | Suporte a tool calling |
774
-
775
- ---
776
-
777
- ## 18. Plano de Implementação v3.0
778
-
779
- ### Fase 1 — Novos Módulos v3.0
780
- 1. `cnn_bigru/models/cyclic_reasoning.py` — Cyclic Reasoning com convergência
781
- 2. `cnn_bigru/models/medusa_heads.py` — Medusa MTP com K cabeças
782
- 3. `cnn_bigru/models/nlg.py` — NLG com Transformer Decoder + Medusa
783
- 4. `cnn_bigru/models/nlp.py` — NLP com 4 tarefas (SeqCls, TokCls, Span, Embed)
784
- 5. `cnn_bigru/models/multimodal_attention.py` — Cross-modal attention + modality gate
785
- 6. `cnn_bigru/utils/quantization.py` — W8A8 SmoothQuant
786
- 7. `cnn_bigru/utils/vqvae2.py` — VQ-VAE-2 hierárquico com EMA
787
- 8. `cnn_bigru/utils/monitoring.py` — Monitor completo
788
- 9. `cnn_bigru/models/context_window.py` — Estendido para 1M tokens (chunked/ring)
789
-
790
- ### Fase 2 — Correções de Bugs
791
- 10. `cnn_bigru/inference/inference.py` — Fix context_window misuse (mistura de históricos)
792
- 11. `cnn_bigru/models/generator_verifier.py` — Fix Verifier classifier dim (4*gru_hidden -> 8*gru_hidden)
793
-
794
- ### Fase 3 — Integração
795
- 12. `cnn_bigru/__init__.py` — Exports v3.0
796
- 13. `cnn_bigru/data/streaming_dataset.py` — Priorizar PowerMachine/CNN-BiGRU repo
797
-
798
- ### Fase 4 — Validação
799
- 14. `cnn_bigru/tests/test_500_samples.py` — Teste 500 amostras (5 batches x 100)
800
- 15. Executar teste, capturar erros, iterar
801
-
802
- ### Fase 5 — Publicação
803
- 16. Push para HF `CNN-BiGRU` (overwrite outdated)
804
- 17. Deletar `HF_TOKEN` do ambiente e scripts
805
- 18. Deletar estado salvo do modelo (não enviar para lugar algum)
806
-
807
- ---
808
-
809
- ## 19. Referências v3.0
810
-
811
- - Xiao, G. et al. **"SmoothQuant: Accurate and Efficient Post-Training Quantization for Large Language Models"**. 2023.
812
- - Roy, A. et al. **"Efficient Conditional Variational Autoencoders for Video Prediction"** (VQ-VAE-2). 2019.
813
- - Cai, T. et al. **"Medusa: Simple LLM Inference Acceleration Framework with Multiple Decoding Heads"**. 2024.
814
- - van den Oord, A. et al. **"Neural Discrete Representation Learning"** (VQ-VAE). NeurIPS 2017.
815
- - Liu, H. et al. **"Ring Attention with Blockwise Transformers for Near-Infinite Context"**. 2023.
816
-
817
- ---
818
-
819
- **Fim do documento v3.0.**