PowerMachine commited on
Commit
1bad449
·
verified ·
1 Parent(s): 49b8205

Delete README.md with huggingface_hub

Browse files
Files changed (1) hide show
  1. README.md +0 -276
README.md DELETED
@@ -1,276 +0,0 @@
1
- # CNN-BiGRU — Modelo Multimodal Cooperativo Autoaprendível (v2.0)
2
-
3
- Implementação completa de um LLM multimodal com arquitetura **CNN-BiGRU cooperativa**,
4
- inspirada nos projetos de referência:
5
-
6
- - `PowerMachine/gru-ring-v13-9-2/xavante_work/`
7
- - `PowerMachine/BiGRU_T_version/src/bigru_t/`
8
- - `dados.txt` (pseudocódigo matemático completo)
9
-
10
- O projeto é **diferente** dos anteriores: agrupa todos os componentes multimodais
11
- (texto + imagem + áudio) num único pipeline cooperativo, com divisão por competências.
12
-
13
- ---
14
-
15
- ## Novidades v2.0
16
-
17
- Esta versão adiciona os **módulos faltantes** identificados na análise matemática
18
- (`docs/MATH_ANALYSIS.md`):
19
-
20
- ### Novos Módulos
21
-
22
- | Módulo | Função | Arquivo |
23
- |--------|--------|---------|
24
- | **EWC** (Elastic Weight Consolidation) | Aprendizado contínuo sem catastrophic forgetting via matriz de Fisher | `utils/ewc.py` |
25
- | **Context Window** | Janela deslizante com cache KV para sequências longas (Sink+Sliding / StreamingLLM) | `models/context_window.py` |
26
- | **RoPE** (Rotary Position Embeddings) | Codificação posicional rotacional (atenção relativa) | `models/rope.py` |
27
- | **TransformerBlock** | CausalSelfAttention + FFN com Pre-LN (decoder-only, estilo GPT) | `models/transformer_block.py` |
28
-
29
- ### Bug Fixes Críticos
30
-
31
- - **`cooperative_bigru.py`**: `SelfAttentionSummary` agora é uma self-attention TRUE
32
- (CLS-token + multi-head + learned Q/K/V), não mais mean-pool.
33
- - **`hypothesis_controller.py`**: gate logic corrigido — `x_proj` agora é uma projeção
34
- LINEAR REAL do input (não mais `combined`, o que tornava o gate inefetivo).
35
- - **`generator_verifier.py`**: `enc_out` agora usa a sequência temporal REAL do encoder
36
- (não mais `fused.unsqueeze(1).expand(...)` que repetia o mesmo vetor).
37
- - **`trainer.py`**: verificador REALMENTE chamado (não proxy); saída da hipótese
38
- REALMENTE usada (não só flag); EWC integrado à perda total.
39
- - **`losses.py`**: todos os `torch.tensor(0.0)` agora usam `device=` correto.
40
- - **`auto_learner.py`**: `_spec_u` registrado como buffer (migra com `.to(device)`);
41
- `l2_reg` adicionado ao `AutoLearnConfig`; `estimate_curvature` agora usa `try/finally`.
42
- - **`inference.py`**: geração autoregressiva REAL via GeneratorCNNBiGRU (não single-step).
43
- - **`streaming_dataset.py`**: synthetic fallback agora é ALCANÇÁVEL quando HF falha
44
- silenciosamente; token HF é limpo após uso.
45
- - **`multimodal_model.py`**: `attn_mask_a`/`attn_mask_b` agora são usados; weight tying opcional.
46
-
47
- ---
48
-
49
- ## Características Principais
50
-
51
- ### 1. Arquitetura Cooperativa de 3 Níveis (do `dados.txt`)
52
-
53
- | Nível | Mecanismo | Descrição |
54
- |-------|-----------|-----------|
55
- | 1 | Cross-Attention Global | Ponte de cooperação pós-CNN entre redes A e B, com máscaras de padding |
56
- | 2 | Célula GRU Cooperativa Passo-a-Passo | `CellStepCooperativaComAtenuacao` com porta Gated (alfa ∈ [0,1]) |
57
- | 3 | Self-Attention Final + Fusão | Self-attention TRUE (CLS-token) + concatenação (128+128=256) |
58
-
59
- ### 2. Multimodal (Texto + Imagem + Áudio)
60
-
61
- - **Texto**: Dual-stream CNN-BiGRU cooperativo (streams A e B)
62
- - **Imagem**: `ImageEncoder` (CNN 2D → flatten → projeção)
63
- - **Áudio**: `AudioEncoder` (CNN 1D sobre espectrograma)
64
- - **Fusão**: `MultimodalFusion` com gated fusion por modalidade
65
-
66
- ### 3. Autoaprendizado (parâmetros matematicamente ajustados)
67
-
68
- Conforme `dados.txt` seções 9-10:
69
-
70
- - **Ajuste Dinâmico de LR**:
71
- - `fator_G = exp(-κ * ||grad_G||) * (1 + v_media) / 2`
72
- - `fator_V = exp(-κ * ||grad_V||) / (1 + L_V_media)`
73
- - **Controle de Gradiente**: clipping L2 + spectral normalization (power iteration, buffer registrado)
74
- - **Inicialização Ortogonal**: matrizes recorrentes e convolucionais (com log de fallback)
75
- - **Estimativa de Curvatura**: aproximação por diferenças finas (com try/finally)
76
-
77
- ### 4. EWC (Elastic Weight Consolidation) — NOVO v2.0
78
-
79
- - **Cálculo da diagonal da Matriz de Fisher** (empirical Fisher)
80
- - **Online EWC**: $F^{\text{agg}} = \gamma F^{\text{prev}} + (1-\gamma) F^{\text{new}}$
81
- - **Penalidade diferenciável**: $L_{\text{EWC}} = \sum_i \frac{\lambda}{2} F_i (\theta_i - \theta_i^*)^2$
82
- - **Integração à perda total**: $L_{\text{total}} = \alpha L_G + \beta L_V + \gamma L_{AH} + \delta L_{\text{reg}} + L_{\text{EWC}}$
83
-
84
- ### 5. Context Window — NOVO v2.0
85
-
86
- - **Cache KV** para CausalSelfAttention (speedup ~T× em inferência)
87
- - **Sliding Window + Sink** (StreamingLLM): mantém $k$ tokens iniciais + últimos $L_{\max}-k$
88
- - **Estratégias**: `sliding`, `sink_sliding` (default), `recompute`
89
- - **Integração com inferência**: `generate_with_sampling(context_window=cw)`
90
-
91
- ### 6. RoPE (Rotary Position Embeddings) — NOVO v2.0
92
-
93
- - Codificação posicional rotacional: $\theta_i = 10000^{-2i/d}$
94
- - Propriedade relacional: $\langle \text{RoPE}(q, m), \text{RoPE}(k, n) \rangle = \langle \text{RoPE}(q, m-n), k \rangle$
95
- - Cache de frequências como buffer (migra com `.to(device)`)
96
- - Extensão dinâmica para sequências longas
97
-
98
- ### 7. TransformerBlock (Decoder-Only) — NOVO v2.0
99
-
100
- - `CausalSelfAttention`: multi-head, máscara triangular inferior, QKV unificada
101
- - `TransformerBlock`: Pre-LN + residual + FFN (Linear → GELU → Linear)
102
- - `TransformerDecoderStack`: N camadas + LayerNorm final + LM head
103
- - **Weight tying** opcional (compartilha embedding ↔ lm_head)
104
- - Suporte a cache KV multicamada para geração autoregressiva
105
-
106
- ### 8. Mecanismo de Hipóteses (ativado em punições)
107
-
108
- Quando o verificador pune um passo (v < threshold), ativa:
109
-
110
- - **N hipóteses paralelas** com transforms lineares diferentes
111
- - **Seleção via Gumbel-Softmax** (diferenciável)
112
- - **Porta de ativação** baseada em v — CORRIGIDA v2.0: agora a saída das hipóteses é
113
- REALMENTE usada (interpolação `gate * combined + (1-gate) * x_proj`)
114
-
115
- ### 9. Synergy Search (N tentativas de acerto)
116
-
117
- No início de cada época, busca N combinações de hiperparâmetros (pesos das perdas)
118
- e seleciona a configuração de menor perda.
119
-
120
- ### 10. Múltiplas Funções de Perda
121
-
122
- Conforme `dados.txt` seção 8:
123
-
124
- ```
125
- L_total = α * L_G_total + β * L_V + γ * L_AH + δ * L_reg + L_EWC
126
- L_G_total = L_G + λ * L_penal_linear + μ * L_penal_exp
127
- L_penal_linear = Σ (1 - v_t) (todos os passos)
128
- L_penal_exp = Σ_{v_t < threshold} exp(γ * (1 - v_t)) (apenas graves)
129
- L_V = BCE(v_t, rotulo_real)
130
- L_AH = Σ (1 - τ_t) (anti-alucinação fuzzy)
131
- L_reg = L2 + curvatura
132
- L_EWC = Σ (λ/2) * F * (θ - θ*)² [NOVO v2.0]
133
- ```
134
-
135
- ### 11. Camada Anti-Alucinação (Lógica Fuzzy de Łukasiewicz)
136
-
137
- ```python
138
- NOT(x) = 1 - sigmoid(x)
139
- AND(x,y) = relu(sigmoid(x) + sigmoid(y) - 1)
140
- OR(x,y) = min(1, sigmoid(x) + sigmoid(y))
141
- IMP(x,y) = min(1, 1 - sigmoid(x) + sigmoid(y))
142
- ```
143
-
144
- ### 12. Inferência Avançada
145
-
146
- - Temperatura, Top-K, Top-P (Nucleus Sampling)
147
- - Presence Penalty, Frequency Penalty
148
- - **Geração autoregressiva REAL via GeneratorCNNBiGRU** (v2.0)
149
- - **Cache KV opcional** via ContextWindowManager (v2.0)
150
- - Avaliação de Perplexidade (PPL) com generator real
151
-
152
- ---
153
-
154
- ## Estrutura por Competências
155
-
156
- ```
157
- cnn_bigru/
158
- ├── tokenizer/ # Competência: tokenização
159
- │ └── bbpe_tokenizer.py # BBPE byte-level tokenizer
160
- ├── utils/ # Competência: utilitários
161
- │ ├── xeon_runtime.py # Ativação Intel Xeon (AVX512+AMX+IPEX)
162
- │ ├── memory_optimizer.py # Otimização de memória (AMP, GC, offload)
163
- │ ├── semantic_embeddings.py # Embeddings semânticos (Sinkhorn OT + IB)
164
- │ └── ewc.py # NOVO v2.0: Elastic Weight Consolidation
165
- ├── data/ # Competência: carregamento de dados
166
- │ └── streaming_dataset.py # Dataset streaming multimodal (com fallback)
167
- ├── models/ # Competência: modelos neurais
168
- │ ├── cooperative_bigru.py # Núcleo CNN-BiGRU cooperativo (self-attn TRUE)
169
- │ ├── multimodal_encoders.py # Encoders de imagem/áudio + fusão
170
- │ ├── multimodal_model.py # Modelo multimodal completo (weight tying opc.)
171
- │ ├── generator_verifier.py # Gerador + Verificador + Anti-alucinação
172
- │ ├── rope.py # NOVO v2.0: Rotary Position Embeddings
173
- │ ├── transformer_block.py # NOVO v2.0: CausalSelfAttention + TransformerBlock
174
- │ └── context_window.py # NOVO v2.0: Sliding window + KV cache
175
- ├── losses/ # Competência: funções de perda
176
- │ └── losses.py # Multi-loss + EWC penalty (device-safe)
177
- ├── training/ # Competência: treinamento
178
- │ ├── auto_learner.py # Ajuste dinâmico LR + spectral norm (buffer)
179
- │ ├── hypothesis_controller.py # Hipóteses + synergy search (gate fix)
180
- │ └── trainer.py # Loop cooperativo + EWC + verificador real
181
- ├── inference/ # Competência: inferência
182
- │ └── inference.py # Sampling + PPL + generator real + context window
183
- ├── tests/ # Competência: testes
184
- │ └── test_50_samples.py # Teste de 50 amostras (com novos módulos v2.0)
185
- ├── scripts/ # Competência: scripts auxiliares
186
- │ └── push_to_hf.py # Upload ao HF (upload_folder + retry)
187
- ├── docs/ # Competência: documentação
188
- │ └── MATH_ANALYSIS.md # NOVO v2.0: análise matemática de EWC + Context Window
189
- └── requirements.txt
190
- ```
191
-
192
- ---
193
-
194
- ## Como Executar
195
-
196
- ### Requisitos
197
-
198
- ```bash
199
- pip install torch tokenizers huggingface_hub datasets psutil tqdm numpy
200
- ```
201
-
202
- ### Teste de 50 Amostras (com novos módulos v2.0)
203
-
204
- ```bash
205
- python -m cnn_bigru.tests.test_50_samples
206
- ```
207
-
208
- O teste executa:
209
- 1. Ativação do runtime Xeon
210
- 2. Treino do BBPE tokenizer
211
- 3. Criação do dataset streaming (50 amostras)
212
- 4. Instanciação dos modelos
213
- 5. **Teste isolado dos novos módulos v2.0**:
214
- - EWC (Fisher, consolidate, penalty)
215
- - Context Window (cache KV, eviction)
216
- - RoPE (preservação de norma)
217
- - TransformerBlock (forward, cache, weight tying)
218
- 5'. Treinamento cooperativo com EWC + synergy + hipóteses + auto-learn
219
- 6. Inferência com generator + context window
220
- 7. Avaliação de perplexidade com generator
221
- 8. Relatório de erros lógicos ou falhas
222
-
223
- ### Resultado Esperado
224
-
225
- ```
226
- ✓ NENHUM ERRO CRÍTICO encontrado
227
- Amostras processadas: 50
228
- Synergy attempts: 3
229
- Hypothesis activations: variável
230
- EWC active: True
231
- Context Window active: True
232
- Used generator for inference: True
233
- STATUS: SUCESSO
234
- ```
235
-
236
- ---
237
-
238
- ## Análise Matemática
239
-
240
- A inclusão de EWC e Context Window foi analisada matematicamente em
241
- [`docs/MATH_ANALYSIS.md`](docs/MATH_ANALYSIS.md), cobrendo:
242
-
243
- 1. **EWC**: formulação da Fisher Information, integração na perda, garantia de Laplace
244
- 2. **Context Window**: complexidade computacional, políticas de evicção (sliding, sink+sliding, recompute)
245
- 3. **Demais elementos faltantes**: RoPE, CausalSelfAttention, Self-Attention final, etc.
246
-
247
- ---
248
-
249
- ## Referências
250
-
251
- - `dados.txt` (arquivo de entrada com pseudocódigo completo)
252
- - `huggingface.co/PowerMachine/gru-ring-v13-9-2/tree/main/xavante_work/`
253
- - `huggingface.co/PowerMachine/BiGRU_T_version/blob/main/src/bigru_t/tokenizer/bbpe_tokenizer.py`
254
- - `huggingface.co/PowerMachine/gru-ring-v13-9-2/blob/main/xavante_work/xavante/utils/semantic_embeddings.py`
255
- - `huggingface.co/PowerMachine/gru-ring-v13-9-2/blob/main/xavante_work/xavante/utils/memory_optimizer.py`
256
- - `huggingface.co/PowerMachine/gru-ring-v13-9-2/tree/main/xavante_work/xavante/training`
257
- - `huggingface.co/PowerMachine/BiGRU_T_version/blob/main/src/bigru_t/utils/xeon_runtime.py`
258
- - `huggingface.co/PowerMachine/gru-ring-v13-9-2/blob/main/xavante_work/flexnet/streaming_datasets_v13_9.py`
259
-
260
- ---
261
-
262
- ## Notas de Segurança
263
-
264
- - **HF_TOKEN**: usado apenas para push inicial ao repositório. Após o push, o token
265
- é removido do ambiente e dos scripts. Os scripts publicados não contêm nenhum
266
- token embutido.
267
- - **Exceções**: todos os módulos usam `try/except` com logging adequado para
268
- garantir robustez. O treinamento continua mesmo se alguns batches falharem.
269
- - **Curvatura**: `estimate_curvature` agora usa `try/finally` para garantir
270
- restauração dos parâmetros mesmo em caso de exceção.
271
-
272
- ---
273
-
274
- ## Licença
275
-
276
- MIT