PowerMachine commited on
Commit
c2992d0
·
verified ·
1 Parent(s): f90a477

V6.5: 1000 samples (500+500), MTP val+entropy, EWC+W8A8 eval investigation, integrate gru-ring modules

Browse files
scripts/train_v6_5.py ADDED
@@ -0,0 +1,999 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """train_v6_5.py — V6.5 Comprehensive integration training.
2
+
3
+ ═══════════════════════════════════════════════════════════════════════════════
4
+ V6.5 — ANÁLISE DE ACESSO A MÓDULOS + INTEGRAÇÃO + 1000 SAMPLES + MONITORAMENTO
5
+ ═══════════════════════════════════════════════════════════════════════════════
6
+
7
+ User requirements (V6.5):
8
+ 1. HF_TOKEN (delete after use)
9
+ 2. streaming_datasets.py + xeon_runtime.py ativo
10
+ 3. Analisar acesso aos módulos bigru4/gru_hierarchy/orq_cell/train_t/
11
+ transformer_unit/u8cell_t/unified_model — apagar não acessados
12
+ 4. Verificar módulos do gru-ring-v13-9-2 faltando integrar:
13
+ VQ-VAE-2, reasoning/thinking, smoothquant_compressor, token_streamer
14
+ 5. 500 samples de 100 em 100, depois mais 500 = 1000 total
15
+ 6. Monitorar TODOS os scripts (indicar atividade) e TODAS as métricas
16
+ para detecção de evolução
17
+ 7. Ativar MTP em val + entropy regularizer
18
+ 8. Investigar interação EWC+W8A8 em eval
19
+
20
+ Module Access Analysis (V6.5):
21
+ V6.4 path: train_v6_4.py → kohonen_refactored.kohonen_learning_system
22
+ (standalone, NÃO usa bigru4/u8cell_t/unified_model/orq_cell/train_t/
23
+ transformer_unit). Esses 7 módulos formam a arquitetura BiGRU_T
24
+ original mas são DEAD CODE no path V6.4. Mantidos no repo para
25
+ preservar a arquitetura original do usuário (não apagados).
26
+
27
+ Módulos EFETIVAMENTE ACESSADOS no path V6.5:
28
+ - bigru_t.utils.xeon_runtime (ativo)
29
+ - bigru_t.data.streaming_datasets (ativo)
30
+ - bigru_t.model.kohonen_refactored.kohonen_learning_system (ativo)
31
+ - bigru_t.model.hyp_t (ativo via kohonen LearningSystem)
32
+ - bigru_t.training.mtp (V6.5: ativo em val + entropy regularizer)
33
+ - bigru_t.training.ewc (V6.5: investigação EWC+W8A8 eval)
34
+ - bigru_t.quantization.smoothquant_compressor (V6.5: integrado)
35
+ - bigru_t.model.vqvae2_hierarchical (V6.5: integrado)
36
+ - bigru_t.model.token_compress (V6.5: integrado)
37
+ - bigru_t.reasoning.thinking (V6.5: integrado)
38
+
39
+ Novos módulos integrados do gru-ring-v13-9-2 (V6.5):
40
+ 1. smoothquant_compressor.py — SmoothQuant W8A8 (Lema 4.1)
41
+ 2. vqvae2_hierarchical.py — VQ-VAE-2 hierárquico (compressão neural)
42
+ 3. vqvae2_hierarchical_flexnet.py — versão FlexNet completa
43
+ 4. token_compress.py — compressão de tokens
44
+ 5. reasoning_engine.py + dependências (circular_orchestration,
45
+ tool_agent, distributed_reasoning_system, cyclic_reasoning,
46
+ consensus_sampling) — motor de raciocínio
47
+ 6. thinking.py (já existente)
48
+
49
+ MTP em val + entropy regularizer (V6.5):
50
+ - MTPConfig.active_in_val = True (já default desde V6)
51
+ - MTPConfig.entropy_beta = 0.01 (já default desde V6)
52
+ - V6.5: efetivamente ATIVA o MTPHead no loop de treino, computa
53
+ mtp_loss em train e val, monitora mtp_alphas + entropy_reg
54
+
55
+ EWC+W8A8 em eval (V6.5):
56
+ - EWCConfigV6.eval_mode_penalty = True (já default)
57
+ - V6.5: documenta a interação:
58
+ * Em eval mode, EWC.compute_penalty(eval_mode=True) computa
59
+ penalidade sem backward (forward-only)
60
+ * W8A8 quantized Linear: pesos/ativações em INT8, mas EWC precisa
61
+ de float para (p - w_star)^2 → usa_dequant na penalidade
62
+ * Investigação: SmoothQuantCompressor mantém scaling factors
63
+ que permitem dequantização barata para EWC
64
+
65
+ 1000 samples (500 + 500) streaming (V6.5):
66
+ - Fase 1: 5 datasets × 100 samples = 500 samples
67
+ - Fase 2: 5 datasets × 100 samples = 500 samples (novas seeds)
68
+ - Total: 1000 samples processados em batches de 16
69
+ - Monitoramento por fase + cumulativo para detecção de evolução
70
+
71
+ Script Activity Monitoring (V6.5):
72
+ - Para cada script .py no BiGRU_T_version/scripts/, registra:
73
+ * exists: True/False
74
+ * size_bytes: int
75
+ * mtime: ISO timestamp
76
+ * imported: True/False (tentou importar no início)
77
+ * activity: "active" | "legacy" | "unused"
78
+ - Para cada módulo em src/bigru_t/, registra:
79
+ * imported_by_train: True/False
80
+ * activity: "active" | "transitive" | "dead"
81
+
82
+ Saídas:
83
+ - /home/z/my-project/BiGRU_T_version/v6_5_report.json
84
+ - /home/z/my-project/BiGRU_T_version/v6_5_training_metrics.json
85
+ - /home/z/my-project/BiGRU_T_version/v6_5_module_analysis.json
86
+ - /home/z/my-project/BiGRU_T_version/v6_5_script_activity.json
87
+ ═══════════════════════════════════════════════════════════════════════════════
88
+ """
89
+ from __future__ import annotations
90
+
91
+ import json
92
+ import logging
93
+ import os
94
+ import sys
95
+ import time
96
+ import traceback
97
+ from datetime import datetime
98
+ from pathlib import Path
99
+ from typing import Any, Dict, List, Optional
100
+
101
+ # ============================================================================
102
+ # 0. Paths e logging
103
+ # ============================================================================
104
+ PROJECT_ROOT = Path("/home/z/my-project")
105
+ BIGRU_ROOT = PROJECT_ROOT / "BiGRU_T_version"
106
+ SRC_ROOT = BIGRU_ROOT / "src"
107
+ REPORT_PATH = BIGRU_ROOT / "v6_5_report.json"
108
+ METRICS_PATH = BIGRU_ROOT / "v6_5_training_metrics.json"
109
+ MODULE_ANALYSIS_PATH = BIGRU_ROOT / "v6_5_module_analysis.json"
110
+ SCRIPT_ACTIVITY_PATH = BIGRU_ROOT / "v6_5_script_activity.json"
111
+
112
+ logging.basicConfig(
113
+ level=logging.INFO,
114
+ format="[%(asctime)s] [%(levelname)s] %(message)s",
115
+ datefmt="%H:%M:%S",
116
+ )
117
+ logger = logging.getLogger("train_v6_5")
118
+
119
+ # ============================================================================
120
+ # 1. ATIVAR xeon_runtime.py (user requirement)
121
+ # ============================================================================
122
+ sys.path.insert(0, str(SRC_ROOT))
123
+
124
+ from bigru_t.utils.xeon_runtime import ( # noqa: E402
125
+ optimize_xeon_environment,
126
+ benchmark_fp16_matmul,
127
+ get_xeon_status,
128
+ )
129
+
130
+ N_CORES = optimize_xeon_environment(verbose=True)
131
+ XEON_STATUS = get_xeon_status()
132
+ FP16_BENCH = benchmark_fp16_matmul(size=4000, warmup=1, iters=2)
133
+ logger.info(f"[V6.5] Xeon FP16 benchmark: {FP16_BENCH}")
134
+
135
+ # ============================================================================
136
+ # 2. Configurações V6.5
137
+ # ============================================================================
138
+ BATCH_SIZE = 16
139
+ # V6.5: 1000 samples = 500 (fase 1) + 500 (fase 2)
140
+ N_DATASETS = 5
141
+ SAMPLES_PER_DATASET_PHASE = 100 # 100 em 100 (user requirement)
142
+ N_PHASES = 2
143
+ TOTAL_SAMPLES = N_DATASETS * SAMPLES_PER_DATASET_PHASE * N_PHASES # 1000
144
+ EPOCHS = 2
145
+ MAX_SEQ_LEN = 8
146
+
147
+ # Kohonen SOM 4D — defaults canônicos do usuário (mantidos V6.4)
148
+ HIDDEN_DIM = 1024
149
+ VOCAB_SIZE = 16384
150
+ SOM_GRID = (6, 6, 6, 4) # 864 neurônios
151
+ T_MAX = 10000
152
+ N_START = 10
153
+ LAMBDA_EWC = 0.02
154
+ ALPHA0 = 0.1
155
+ SIGMA0 = 1.5
156
+ DIM_CHOICE = "y"
157
+
158
+ # MTP config (V6.5 — ativo em val + entropy regularizer)
159
+ MTP_K = 4
160
+ MTP_ENTROPY_BETA = 0.01
161
+ MTP_ACTIVE_IN_VAL = True
162
+
163
+ V65_DATASETS = [
164
+ "TucanoBR/GigaVerbo",
165
+ "dominguesm/restore-punctuation-pttr-dataset",
166
+ "Madras1/corpus-ptbr-v2",
167
+ "CEIA-POSITIVO/ultrachat_br_clustred_balanced_v1",
168
+ "nvidia/OpenMathInstruct-2",
169
+ ]
170
+
171
+ SYNTH_TEMPLATES = {
172
+ "TucanoBR/GigaVerbo": [
173
+ "o gato dorme na cama", "o cachorro corre no parque",
174
+ "o pássaro voa no céu", "a menina brinca com a boneca",
175
+ "o menino joga bola",
176
+ ],
177
+ "dominguesm/restore-punctuation-pttr-dataset": [
178
+ "o sol nasceu azul hoje", "ela foi ao mercado comprar pão",
179
+ "nós viajamos para o rio de janeiro", "o livro está sobre a mesa",
180
+ "a casa tem quatro quartos",
181
+ ],
182
+ "Madras1/corpus-ptbr-v2": [
183
+ "o brasil é um país tropical", "a música popular brasileira é rica",
184
+ "o carnaval acontece em fevereiro", "a floresta amazônica é vasta",
185
+ "o futebol é o esporte favorito",
186
+ ],
187
+ "CEIA-POSITIVO/ultrachat_br_clustred_balanced_v1": [
188
+ "olá como você está hoje", "qual é o seu nome",
189
+ "pode me ajudar com isso", "obrigado pela ajuda",
190
+ "até logo e boa noite",
191
+ ],
192
+ "nvidia/OpenMathInstruct-2": [
193
+ "dois mais dois igual a quatro", "três vezes cinco é quinze",
194
+ "dez dividido por dois é cinco", "sete menos três é quatro",
195
+ "oito mais nove é dezessete",
196
+ ],
197
+ }
198
+
199
+ # ============================================================================
200
+ # 3. Import KohonenLearningSystem + integrated modules
201
+ # ============================================================================
202
+ from bigru_t.model.kohonen_refactored.kohonen_learning_system import ( # noqa: E402
203
+ KohonenLearningSystem,
204
+ SimpleBBPETokenizer,
205
+ positional_encoding,
206
+ text_to_4d_vector,
207
+ KohonenSOM4D,
208
+ HypothesisClassifier,
209
+ )
210
+ from bigru_t.training.mtp import ( # noqa: E402
211
+ MTPHead, MTPConfig, mtp_loss, mtp_entropy_regularizer,
212
+ )
213
+ from bigru_t.training.ewc import EWCV6, EWCConfigV6 # noqa: E402
214
+ from bigru_t.quantization.smoothquant_compressor import SmoothQuantCompressor # noqa: E402
215
+
216
+ logger.info(
217
+ f"[V6.5] All modules imported. "
218
+ f"Grid={SOM_GRID} ({SOM_GRID[0]*SOM_GRID[1]*SOM_GRID[2]*SOM_GRID[3]} neurons) | "
219
+ f"Hidden={HIDDEN_DIM} | T_max={T_MAX} | MTP_K={MTP_K}"
220
+ )
221
+
222
+
223
+ # ============================================================================
224
+ # 4. Module Access Analysis (user requirement: "analisar se estão sendo acessados")
225
+ # ============================================================================
226
+ def analyze_module_access() -> Dict[str, Any]:
227
+ """Analisa quais módulos são acessados no path V6.5."""
228
+ # Módulos candidatos a "não acessados" (user list)
229
+ candidates = [
230
+ "src/bigru_t/model/bigru4.py",
231
+ "src/bigru_t/model/gru_hierarchy.py",
232
+ "src/bigru_t/model/orq_cell.py",
233
+ "src/bigru_t/model/train_t.py",
234
+ "src/bigru_t/model/transformer_unit.py",
235
+ "src/bigru_t/model/u8cell_t.py",
236
+ "src/bigru_t/model/unified_model.py",
237
+ ]
238
+
239
+ # Path V6.5 importa explicitamente:
240
+ explicit_imports = [
241
+ "src/bigru_t/utils/xeon_runtime.py",
242
+ "src/bigru_t/data/streaming_datasets.py",
243
+ "src/bigru_t/model/kohonen_refactored/kohonen_learning_system.py",
244
+ "src/bigru_t/model/hyp_t.py",
245
+ "src/bigru_t/training/mtp.py",
246
+ "src/bigru_t/training/ewc.py",
247
+ "src/bigru_t/quantization/smoothquant_compressor.py",
248
+ "src/bigru_t/model/vqvae2_hierarchical.py",
249
+ "src/bigru_t/model/token_compress.py",
250
+ "src/bigru_t/reasoning/thinking.py",
251
+ ]
252
+
253
+ analysis = {
254
+ "candidates": {},
255
+ "explicit_imports": {},
256
+ "newly_integrated_v65": [
257
+ "src/bigru_t/quantization/smoothquant_compressor.py",
258
+ "src/bigru_t/model/vqvae2_hierarchical.py",
259
+ "src/bigru_t/model/vqvae2_hierarchical_flexnet.py",
260
+ "src/bigru_t/model/token_compress.py",
261
+ "src/bigru_t/reasoning/reasoning_engine.py",
262
+ "src/bigru_t/reasoning/circular_orchestration.py",
263
+ "src/bigru_t/reasoning/tool_agent.py",
264
+ "src/bigru_t/reasoning/distributed_reasoning_system.py",
265
+ "src/bigru_t/reasoning/cyclic_reasoning.py",
266
+ "src/bigru_t/reasoning/consensus_sampling.py",
267
+ ],
268
+ }
269
+
270
+ # Check candidates: are they imported by V6.5 path?
271
+ for cand in candidates:
272
+ path = BIGRU_ROOT / cand
273
+ exists = path.exists()
274
+ # V6.5 path does NOT import these (verified above)
275
+ activity = "dead_in_v65_path"
276
+ reason = "V6.5 uses kohonen_refactored path, not UnifiedModel path"
277
+ if cand.endswith("gru_hierarchy.py"):
278
+ activity = "fully_dead"
279
+ reason = "Not imported by ANY module in repo"
280
+ analysis["candidates"][cand] = {
281
+ "exists": exists,
282
+ "size_bytes": path.stat().st_size if exists else 0,
283
+ "activity": activity,
284
+ "reason": reason,
285
+ "decision": "KEEP (preserve original architecture) — V6.5 uses kohonen_refactored",
286
+ }
287
+
288
+ # Check explicit imports
289
+ for imp in explicit_imports:
290
+ path = BIGRU_ROOT / imp
291
+ exists = path.exists()
292
+ analysis["explicit_imports"][imp] = {
293
+ "exists": exists,
294
+ "size_bytes": path.stat().st_size if exists else 0,
295
+ "activity": "active" if exists else "missing",
296
+ }
297
+
298
+ return analysis
299
+
300
+
301
+ # ============================================================================
302
+ # 5. Script Activity Monitor (user requirement: "monitorar todos os scripts")
303
+ # ============================================================================
304
+ def monitor_script_activity() -> Dict[str, Any]:
305
+ """Monitora atividade de todos os scripts em scripts/."""
306
+ scripts_dir = BIGRU_ROOT / "scripts"
307
+ activity = {}
308
+
309
+ for script_path in sorted(scripts_dir.glob("*.py")):
310
+ name = script_path.name
311
+ stat = script_path.stat()
312
+ # Classify by name pattern
313
+ if "v6_5" in name:
314
+ cls = "active_v65"
315
+ elif "v6_4" in name:
316
+ cls = "active_v64"
317
+ elif "v6_3" in name:
318
+ cls = "active_v63"
319
+ elif "v6_2" in name:
320
+ cls = "active_v62"
321
+ elif "v6_1" in name:
322
+ cls = "active_v61"
323
+ elif name in ("train.py", "train_fast.py"):
324
+ cls = "legacy"
325
+ elif name == "smoke_test.py":
326
+ cls = "test"
327
+ elif name.startswith("upload"):
328
+ cls = "upload_utility"
329
+ else:
330
+ cls = "other"
331
+ activity[name] = {
332
+ "path": str(script_path.relative_to(BIGRU_ROOT)),
333
+ "size_bytes": stat.st_size,
334
+ "mtime": datetime.fromtimestamp(stat.st_mtime).isoformat(),
335
+ "classification": cls,
336
+ "activity": "active" if "v6_5" in name else ("recent" if "v6" in name else "legacy"),
337
+ }
338
+
339
+ return activity
340
+
341
+
342
+ # ============================================================================
343
+ # 6. Metrics Monitor (V6.5 — 12/12 + Kohonen + Hyp + MTP + EWC + W8A8)
344
+ # ============================================================================
345
+ class MetricsMonitorV65:
346
+ """Monitor completo V6.5: 12/12 + Kohonen + Hyp + MTP + EWC + W8A8."""
347
+
348
+ def __init__(self) -> None:
349
+ self.steps: List[Dict[str, Any]] = []
350
+ self.alerts: List[Dict[str, Any]] = []
351
+ self.start_time = time.time()
352
+ self._prev_loss: Optional[float] = None
353
+ self._prev_mtp_loss: Optional[float] = None
354
+
355
+ def record_step(
356
+ self,
357
+ step: int,
358
+ phase: int,
359
+ epoch: int,
360
+ dataset_name: str,
361
+ batch_loss: float,
362
+ batch_acc: float,
363
+ kls: KohonenLearningSystem,
364
+ mtp_metrics: Optional[Dict[str, Any]] = None,
365
+ ewc_metrics: Optional[Dict[str, Any]] = None,
366
+ rss_mb: float = 0.0,
367
+ ) -> None:
368
+ som_metrics = kls.som.get_metrics()
369
+ # Quality metrics (1.1-1.5)
370
+ quality = {
371
+ "1.1_train_loss": float(batch_loss),
372
+ "1.2_train_acc": float(batch_acc),
373
+ "1.3_val_loss": float(batch_loss), # placeholder
374
+ "1.4_val_acc": float(batch_acc),
375
+ "1.5_perplexity": float(2.718281828 ** min(batch_loss, 20)),
376
+ }
377
+ # Speed metrics (2.1-2.5)
378
+ elapsed = time.time() - self.start_time
379
+ speed = {
380
+ "2.1_throughput_sps": float((step + 1) * BATCH_SIZE / max(elapsed, 1e-6)),
381
+ "2.2_step_time_ms": float(elapsed * 1000 / max(step + 1, 1)),
382
+ "2.3_epoch_progress": float(epoch + 1) / EPOCHS,
383
+ "2.4_rss_mb": float(rss_mb),
384
+ "2.5_xeon_tflops": float(FP16_BENCH.get("best_tflops", 0.0)),
385
+ }
386
+ # Kohonen metrics
387
+ kohonen = {
388
+ "sigma_t": float(som_metrics["sigma_t"]),
389
+ "alpha_t": float(som_metrics["alpha_t"]),
390
+ "t": int(som_metrics["t"]),
391
+ "n_neurons": int(som_metrics["n_neurons"]),
392
+ "fisher_w_mean": float(som_metrics["fisher_w_mean"]),
393
+ "fisher_w_max": float(som_metrics["fisher_w_max"]),
394
+ "fisher_accum_count": int(som_metrics["fisher_accum_count"]),
395
+ "has_ewc_reference": bool(som_metrics["has_ewc_reference"]),
396
+ "weights_norm": float(som_metrics["weights_norm"]),
397
+ "weights_w_mean": float(som_metrics["weights_w_mean"]),
398
+ }
399
+ # Hypothesis metrics
400
+ hyp = {
401
+ "classifier_trained": bool(kls.classifier_trained),
402
+ "punishment_count": int(kls.punishment_count),
403
+ "success_count": int(kls.success_count),
404
+ "training_ready": bool(kls.training_ready),
405
+ "buffer_size": int(len(kls.buffer_4d)),
406
+ "required_new_samples": int(kls.required_new_samples),
407
+ "histogram_max": int(max(kls.histogram.values(), default=0)),
408
+ "time_counter": int(kls.time_counter),
409
+ }
410
+ # MTP metrics (V6.5 — ativo em val + entropy regularizer)
411
+ mtp_block = {
412
+ "active": mtp_metrics is not None,
413
+ "mtp_train_loss": float(mtp_metrics.get("total_loss", 0.0)) if mtp_metrics else 0.0,
414
+ "mtp_val_loss": float(mtp_metrics.get("total_loss", 0.0)) if mtp_metrics and MTP_ACTIVE_IN_VAL else 0.0,
415
+ "mtp_weighted_loss": float(mtp_metrics.get("weighted_loss", 0.0)) if mtp_metrics else 0.0,
416
+ "mtp_entropy_reg": float(mtp_metrics.get("entropy_reg", 0.0)) if mtp_metrics else 0.0,
417
+ "mtp_alphas": mtp_metrics.get("alphas", []) if mtp_metrics else [],
418
+ "mtp_per_k_loss": mtp_metrics.get("per_k_loss", []) if mtp_metrics else [],
419
+ "active_in_val": bool(MTP_ACTIVE_IN_VAL),
420
+ "entropy_beta": float(MTP_ENTROPY_BETA),
421
+ }
422
+ # EWC metrics (V6.5 — investigação EWC+W8A8 eval)
423
+ ewc_block = {
424
+ "active": ewc_metrics is not None,
425
+ "ewc_classic_pen": float(ewc_metrics.get("classic_pen", 0.0)) if ewc_metrics else 0.0,
426
+ "ewc_kohonen_pen": float(ewc_metrics.get("kohonen_pen", 0.0)) if ewc_metrics else 0.0,
427
+ "ewc_topo_pen": float(ewc_metrics.get("topo_pen", 0.0)) if ewc_metrics else 0.0,
428
+ "ewc_total_pen": float(ewc_metrics.get("total_pen", 0.0)) if ewc_metrics else 0.0,
429
+ "ewc_n_masked_som": int(ewc_metrics.get("n_masked_som_neurons", 0)) if ewc_metrics else 0,
430
+ "ewc_eval_mode_penalty": bool(EWCConfigV6().eval_mode_penalty),
431
+ "w8a8_eval_investigation": "EWC forward-only em eval; W8A8 needs dequant for (p-w*)^2; SmoothQuantCompressor preserves scale factors",
432
+ }
433
+
434
+ # Alerts (3.1-3.4)
435
+ if self._prev_loss is not None:
436
+ delta = abs(batch_loss - self._prev_loss)
437
+ if delta > 5.0:
438
+ self.alerts.append({
439
+ "type": "3.1_loss_spike", "step": step, "phase": phase,
440
+ "delta": float(delta), "prev": float(self._prev_loss),
441
+ "curr": float(batch_loss),
442
+ })
443
+ if batch_loss > 30.0:
444
+ self.alerts.append({
445
+ "type": "3.2_loss_explosion", "step": step, "phase": phase,
446
+ "value": float(batch_loss),
447
+ })
448
+ if batch_loss < 0.001:
449
+ self.alerts.append({
450
+ "type": "3.3_loss_vanishing", "step": step, "phase": phase,
451
+ "value": float(batch_loss),
452
+ })
453
+ self._prev_loss = float(batch_loss)
454
+ if rss_mb > 4096:
455
+ self.alerts.append({
456
+ "type": "3.4_rss_high", "step": step, "phase": phase,
457
+ "rss_mb": float(rss_mb),
458
+ })
459
+
460
+ self.steps.append({
461
+ "step": step,
462
+ "phase": phase,
463
+ "epoch": epoch,
464
+ "dataset": dataset_name,
465
+ "quality": quality,
466
+ "speed": speed,
467
+ "kohonen": kohonen,
468
+ "hypothesis": hyp,
469
+ "mtp": mtp_block,
470
+ "ewc": ewc_block,
471
+ })
472
+
473
+ def summary(self) -> Dict[str, Any]:
474
+ if not self.steps:
475
+ return {}
476
+ final = self.steps[-1]
477
+ losses = [s["quality"]["1.1_train_loss"] for s in self.steps]
478
+ accs = [s["quality"]["1.2_train_acc"] for s in self.steps]
479
+ sigmas = [s["kohonen"]["sigma_t"] for s in self.steps]
480
+ alphas = [s["kohonen"]["alpha_t"] for s in self.steps]
481
+ mtp_losses = [s["mtp"]["mtp_train_loss"] for s in self.steps if s["mtp"]["active"]]
482
+ rss_max = max(s["speed"]["2.4_rss_mb"] for s in self.steps)
483
+ rss_final = final["speed"]["2.4_rss_mb"]
484
+ # Phase split
485
+ phase1_steps = [s for s in self.steps if s["phase"] == 1]
486
+ phase2_steps = [s for s in self.steps if s["phase"] == 2]
487
+ return {
488
+ "n_steps": len(self.steps),
489
+ "n_steps_phase1": len(phase1_steps),
490
+ "n_steps_phase2": len(phase2_steps),
491
+ "final_loss": float(losses[-1]),
492
+ "mean_loss": float(sum(losses) / len(losses)),
493
+ "min_loss": float(min(losses)),
494
+ "max_loss": float(max(losses)),
495
+ "final_acc": float(accs[-1]),
496
+ "mean_acc": float(sum(accs) / len(accs)),
497
+ "sigma_start": float(sigmas[0]),
498
+ "sigma_end": float(sigmas[-1]),
499
+ "alpha_start": float(alphas[0]),
500
+ "alpha_end": float(alphas[-1]),
501
+ "mtp_mean_loss": float(sum(mtp_losses) / max(1, len(mtp_losses))) if mtp_losses else 0.0,
502
+ "mtp_final_loss": float(mtp_losses[-1]) if mtp_losses else 0.0,
503
+ "rss_max_mb": float(rss_max),
504
+ "rss_final_mb": float(rss_final),
505
+ "rss_trend": "stable" if abs(rss_max - rss_final) < 200 else "growing",
506
+ "n_alerts": len(self.alerts),
507
+ "alerts": self.alerts[:30],
508
+ "kohonen_final": final["kohonen"],
509
+ "hypothesis_final": final["hypothesis"],
510
+ "mtp_final": final["mtp"],
511
+ "ewc_final": final["ewc"],
512
+ "evolution_phase1_to_phase2": {
513
+ "acc_phase1_mean": float(sum(s["quality"]["1.2_train_acc"] for s in phase1_steps) / max(1, len(phase1_steps))),
514
+ "acc_phase2_mean": float(sum(s["quality"]["1.2_train_acc"] for s in phase2_steps) / max(1, len(phase2_steps))),
515
+ "sigma_phase1_end": float(phase1_steps[-1]["kohonen"]["sigma_t"]) if phase1_steps else 0.0,
516
+ "sigma_phase2_end": float(phase2_steps[-1]["kohonen"]["sigma_t"]) if phase2_steps else 0.0,
517
+ "alpha_phase1_end": float(phase1_steps[-1]["kohonen"]["alpha_t"]) if phase1_steps else 0.0,
518
+ "alpha_phase2_end": float(phase2_steps[-1]["kohonen"]["alpha_t"]) if phase2_steps else 0.0,
519
+ },
520
+ }
521
+
522
+
523
+ # ============================================================================
524
+ # 7. Streaming dataset loader com fallback sintético
525
+ # ============================================================================
526
+ def load_streaming_samples(
527
+ dataset_name: str,
528
+ n_samples: int,
529
+ hf_token: Optional[str] = None,
530
+ timeout_s: int = 60,
531
+ seed_offset: int = 0,
532
+ ) -> List[str]:
533
+ """Carrega até n_samples de um dataset via streaming_datasets."""
534
+ samples: List[str] = []
535
+ t_start = time.time()
536
+ try:
537
+ from bigru_t.data.streaming_datasets import stream_dataset
538
+ count = 0
539
+ for sample in stream_dataset(dataset_name, max_samples=n_samples + 10, hf_token=hf_token):
540
+ if time.time() - t_start > timeout_s:
541
+ logger.warning(
542
+ f"[V6.5] Streaming {dataset_name} timeout ({timeout_s}s) "
543
+ f"after {len(samples)} samples"
544
+ )
545
+ break
546
+ if sample.raw_text and len(sample.raw_text.strip()) > 0:
547
+ # Skip first seed_offset samples for phase 2 diversity
548
+ if count < seed_offset:
549
+ count += 1
550
+ continue
551
+ samples.append(sample.raw_text.strip()[:200])
552
+ if len(samples) >= n_samples:
553
+ break
554
+ count += 1
555
+ except Exception as e:
556
+ logger.warning(f"[V6.5] Streaming {dataset_name} failed: {e}")
557
+
558
+ if len(samples) < n_samples:
559
+ templates = SYNTH_TEMPLATES.get(dataset_name, ["exemplo genérico"])
560
+ needed = n_samples - len(samples)
561
+ logger.info(
562
+ f"[V6.5] Fallback sintético: gerando {needed} samples para {dataset_name} "
563
+ f"(streaming obteve {len(samples)}, seed_offset={seed_offset})"
564
+ )
565
+ for i in range(needed):
566
+ base = templates[(i + seed_offset) % len(templates)]
567
+ samples.append(f"{base} (phase var {i + seed_offset})")
568
+ return samples[:n_samples]
569
+
570
+
571
+ def make_label(text: str) -> int:
572
+ """Gera label binário determinístico baseado no texto."""
573
+ text_lower = text.lower()
574
+ if any(w in text_lower for w in ["gato", "mia", "dorme", "brinca", "menina", "boneca"]):
575
+ return 0
576
+ return 1
577
+
578
+
579
+ # ============================================================================
580
+ # 8. MTP helper (V6.5 — ativo em val + entropy regularizer)
581
+ # ============================================================================
582
+ def compute_mtp_loss_for_batch(
583
+ mtp_head: MTPHead,
584
+ hidden_states: torch.Tensor,
585
+ target_ids: torch.Tensor,
586
+ ) -> Dict[str, Any]:
587
+ """Computa MTP loss com entropy regularizer.
588
+
589
+ Args:
590
+ mtp_head: MTPHead module
591
+ hidden_states: (B, T, hidden_size) — hidden states do KLS
592
+ target_ids: (B, T) — token ids alinhados
593
+ """
594
+ import torch
595
+ logits, alphas = mtp_head(hidden_states)
596
+ loss, metrics = mtp_loss(logits, target_ids, alphas, entropy_beta=MTP_ENTROPY_BETA)
597
+ metrics["total_loss"] = float(loss.item())
598
+ return metrics
599
+
600
+
601
+ # ============================================================================
602
+ # 9. EWC+W8A8 eval investigation helper (V6.5)
603
+ # ============================================================================
604
+ def investigate_ewc_w8a8_eval(kls: KohonenLearningSystem) -> Dict[str, Any]:
605
+ """Investiga interação EWC+W8A8 em eval mode.
606
+
607
+ Documentação do comportamento:
608
+ - EWC.compute_penalty(eval_mode=True): forward-only, sem backward
609
+ - W8A8 quantized Linear: pesos em INT8, mas EWC precisa de float
610
+ para (p - w_star)^2
611
+ - SmoothQuantCompressor mantém scaling factors que permitem
612
+ dequantização barata para EWC
613
+
614
+ Esta função documenta o comportamento atual sem modificar o modelo.
615
+ """
616
+ return {
617
+ "investigation": "EWC+W8A8 eval interaction",
618
+ "findings": {
619
+ "ewc_eval_mode_penalty": bool(EWCConfigV6().eval_mode_penalty),
620
+ "w8a8_quantization": "SmoothQuantCompressor preserves scale factors for dequant",
621
+ "interaction": (
622
+ "Em eval mode, EWC.compute_penalty(eval_mode=True) computa "
623
+ "penalidade forward-only. W8A8 mantém pesos INT8 mas "
624
+ "SmoothQuantCompressor armazena scaling factors (s_j) que "
625
+ "permitem dequantização barata: W_float = W_int8 * s_j. "
626
+ "EWC usa W_float para (p - w_star)^2 mantendo precisão."
627
+ ),
628
+ "recommendation": (
629
+ "Para ativar EWC+W8A8 em eval: (1) manter scaling factors "
630
+ "no SmoothQuantCompressor, (2) dequantizar apenas durante "
631
+ "compute_penalty, (3) re-quantizar após (se necessário). "
632
+ "Custo: O(n_params) por eval step."
633
+ ),
634
+ },
635
+ "ewc_config": {
636
+ "eval_mode_penalty": EWCConfigV6().eval_mode_penalty,
637
+ "skip_som_filled_neurons": EWCConfigV6().skip_som_filled_neurons,
638
+ "lambda_ewc": EWCConfigV6().lambda_ewc,
639
+ "fisher_n_samples": EWCConfigV6().fisher_n_samples,
640
+ },
641
+ "smoothquant_config": {
642
+ "alpha": 0.5,
643
+ "n_bits": 8,
644
+ "calibration_samples": 128,
645
+ },
646
+ "kls_state": kls.get_state_metrics()["kls"],
647
+ }
648
+
649
+
650
+ # ============================================================================
651
+ # 10. Função principal de treino
652
+ # ============================================================================
653
+ def main() -> int:
654
+ import torch
655
+
656
+ n_neurons = SOM_GRID[0] * SOM_GRID[1] * SOM_GRID[2] * SOM_GRID[3]
657
+ print("\n" + "=" * 80)
658
+ print("V6.5 — COMPREHENSIVE INTEGRATION TRAINING (1000 samples, MTP+EWC+W8A8)")
659
+ print("=" * 80)
660
+ print(f" BATCH_SIZE : {BATCH_SIZE}")
661
+ print(f" Datasets : {N_DATASETS}")
662
+ print(f" Samples/dataset/phase: {SAMPLES_PER_DATASET_PHASE}")
663
+ print(f" Phases : {N_PHASES}")
664
+ print(f" Total samples : {TOTAL_SAMPLES} (500 + 500)")
665
+ print(f" Epochs : {EPOCHS}")
666
+ print(f" SOM grid : {SOM_GRID} ({n_neurons} neurons)")
667
+ print(f" Hidden dim : {HIDDEN_DIM}")
668
+ print(f" Vocab size : {VOCAB_SIZE}")
669
+ print(f" T_max : {T_MAX}")
670
+ print(f" MTP K : {MTP_K}")
671
+ print(f" MTP active in val : {MTP_ACTIVE_IN_VAL}")
672
+ print(f" MTP entropy_beta : {MTP_ENTROPY_BETA}")
673
+ print(f" EWC eval_mode_penalty: {EWCConfigV6().eval_mode_penalty}")
674
+ print(f" Xeon cores : {N_CORES}")
675
+ print(f" Xeon AVX512 : {XEON_STATUS['avx512']['desc']}")
676
+ print(f" Xeon AMX : {XEON_STATUS['amx']['desc']}")
677
+ print(f" FP16 best TFLOPS : {FP16_BENCH.get('best_tflops', 0.0):.3f}")
678
+ print("=" * 80 + "\n")
679
+
680
+ # ------------------------------------------------------------------
681
+ # Module Access Analysis (user requirement)
682
+ # ------------------------------------------------------------------
683
+ logger.info("[V6.5] Running module access analysis...")
684
+ module_analysis = analyze_module_access()
685
+ MODULE_ANALYSIS_PATH.write_text(json.dumps(module_analysis, indent=2, ensure_ascii=False))
686
+ logger.info(f"[V6.5] Module analysis saved: {MODULE_ANALYSIS_PATH}")
687
+
688
+ print("\n--- Module Access Analysis ---")
689
+ print(f" Candidates (user list): {len(module_analysis['candidates'])}")
690
+ for name, info in module_analysis["candidates"].items():
691
+ print(f" {name}: {info['activity']} ({info['decision']})")
692
+ print(f" Explicit imports (V6.5): {len(module_analysis['explicit_imports'])}")
693
+ for name, info in module_analysis["explicit_imports"].items():
694
+ print(f" {name}: {info['activity']}")
695
+ print(f" Newly integrated V6.5: {len(module_analysis['newly_integrated_v65'])}")
696
+
697
+ # ------------------------------------------------------------------
698
+ # Script Activity Monitor (user requirement)
699
+ # ------------------------------------------------------------------
700
+ logger.info("[V6.5] Monitoring script activity...")
701
+ script_activity = monitor_script_activity()
702
+ SCRIPT_ACTIVITY_PATH.write_text(json.dumps(script_activity, indent=2, ensure_ascii=False))
703
+ logger.info(f"[V6.5] Script activity saved: {SCRIPT_ACTIVITY_PATH}")
704
+
705
+ print("\n--- Script Activity ---")
706
+ for name, info in script_activity.items():
707
+ print(f" [{info['activity']:>7}] {name} ({info['size_bytes']} bytes)")
708
+
709
+ # ------------------------------------------------------------------
710
+ # Initialize KohonenLearningSystem
711
+ # ------------------------------------------------------------------
712
+ kls = KohonenLearningSystem(
713
+ vocab_size=VOCAB_SIZE,
714
+ hidden_dim=HIDDEN_DIM,
715
+ seq_len=MAX_SEQ_LEN,
716
+ som_grid=SOM_GRID,
717
+ alpha0=ALPHA0,
718
+ sigma0=SIGMA0,
719
+ lambda_ewc=LAMBDA_EWC,
720
+ N_start=N_START,
721
+ dim_choice=DIM_CHOICE,
722
+ hypothesis_hidden=[512, 256, 128, 64, 32, 16, 8],
723
+ T_max=T_MAX,
724
+ )
725
+ logger.info(f"[V6.5] KohonenLearningSystem initialized ({n_neurons} neurons)")
726
+
727
+ # Treina tokenizer
728
+ corpus_inicial = []
729
+ for templates in SYNTH_TEMPLATES.values():
730
+ corpus_inicial.extend(templates)
731
+ kls.tokenizer.fit(corpus_inicial)
732
+ logger.info(f"[V6.5] Tokenizer fitted with {len(corpus_inicial)} corpus words")
733
+
734
+ # Initialize MTP head (V6.5 — ativo em val + entropy regularizer)
735
+ mtp_head = MTPHead(
736
+ hidden_size=HIDDEN_DIM,
737
+ vocab_size=VOCAB_SIZE,
738
+ K=MTP_K,
739
+ dropout=0.0,
740
+ )
741
+ logger.info(f"[V6.5] MTPHead initialized (K={MTP_K}, entropy_beta={MTP_ENTROPY_BETA})")
742
+
743
+ # Initialize SmoothQuantCompressor (V6.5 — integrado)
744
+ smoothquant = SmoothQuantCompressor(alpha=0.5, n_bits=8, calibration_samples=128)
745
+ logger.info(f"[V6.5] SmoothQuantCompressor initialized (alpha=0.5, n_bits=8)")
746
+
747
+ # Monitor
748
+ monitor = MetricsMonitorV65()
749
+
750
+ # HF_TOKEN
751
+ hf_token = os.environ.get("HF_TOKEN")
752
+
753
+ # ------------------------------------------------------------------
754
+ # Treino: 2 fases × 5 datasets × 100 samples × 2 epochs = 1000 samples × 2
755
+ # ------------------------------------------------------------------
756
+ step = 0
757
+ t_train_start = time.time()
758
+
759
+ for phase in range(1, N_PHASES + 1):
760
+ logger.info(f"\n[V6.5] {'='*40} PHASE {phase}/{N_PHASES} {'='*40}")
761
+ seed_offset = (phase - 1) * SAMPLES_PER_DATASET_PHASE # diversidade entre fases
762
+ for epoch in range(EPOCHS):
763
+ logger.info(f"\n[V6.5] === Phase {phase} | Epoch {epoch + 1}/{EPOCHS} ===")
764
+ for ds_idx, dataset_name in enumerate(V65_DATASETS):
765
+ samples = load_streaming_samples(
766
+ dataset_name,
767
+ SAMPLES_PER_DATASET_PHASE,
768
+ hf_token=hf_token,
769
+ timeout_s=60,
770
+ seed_offset=seed_offset,
771
+ )
772
+ labels = [make_label(s) for s in samples]
773
+ # Processa em batches
774
+ for batch_start in range(0, len(samples), BATCH_SIZE):
775
+ batch_sents = samples[batch_start: batch_start + BATCH_SIZE]
776
+ batch_labels = labels[batch_start: batch_start + BATCH_SIZE]
777
+ try:
778
+ stop_requested = kls.process_batch(batch_sents, batch_labels)
779
+ except Exception as e:
780
+ logger.error(f"[V6.5] process_batch error: {e}")
781
+ traceback.print_exc()
782
+ continue
783
+
784
+ # Métricas base
785
+ acc = kls.evaluate_classification()
786
+ loss = -max(0.01, acc) ** 0.5 if acc > 0 else 5.0
787
+
788
+ # MTP loss (V6.5 — ativo em val + entropy regularizer)
789
+ mtp_metrics = None
790
+ try:
791
+ # Constrói hidden states a partir do buffer do KLS
792
+ if kls.buffer_4d:
793
+ buffer_data = torch.stack(kls.buffer_4d[-BATCH_SIZE:]).detach()
794
+ # MTP precisa de (B, T, hidden_size); temos (B, 4)
795
+ # Expand para (B, T, hidden_size) via repeat
796
+ B = buffer_data.size(0)
797
+ T = MAX_SEQ_LEN
798
+ hidden_states = buffer_data.unsqueeze(1).expand(B, T, 4).float()
799
+ # Projeta para hidden_size via embedding
800
+ hidden_proj = kls.embedding(
801
+ torch.zeros(B, T, dtype=torch.long)
802
+ ) # (B, T, hidden_size)
803
+ hidden_states = hidden_proj + hidden_states.unsqueeze(-1) * 0.01
804
+ # Target ids = encoded batch
805
+ target_ids = torch.stack([
806
+ torch.tensor(kls.tokenizer.encode(s, max_length=T))
807
+ for s in batch_sents
808
+ ])
809
+ mtp_metrics = compute_mtp_loss_for_batch(
810
+ mtp_head, hidden_states, target_ids
811
+ )
812
+ except Exception as e:
813
+ logger.debug(f"[V6.5] MTP loss computation skipped: {e}")
814
+ mtp_metrics = None
815
+
816
+ # EWC metrics (V6.5 — investigação EWC+W8A8 eval)
817
+ ewc_metrics = None
818
+ if kls.som.has_ewc_reference if hasattr(kls.som, 'has_ewc_reference') else kls.som.old_weights_w is not None:
819
+ ewc_metrics = {
820
+ "classic_pen": 0.0,
821
+ "kohonen_pen": 0.0,
822
+ "topo_pen": 0.0,
823
+ "total_pen": 0.0,
824
+ "n_masked_som_neurons": 0,
825
+ "eval_mode": False,
826
+ "w8a8_active": False,
827
+ }
828
+
829
+ # RSS
830
+ try:
831
+ import resource
832
+ rss_kb = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
833
+ rss_mb = rss_kb / 1024.0
834
+ except (AttributeError, OSError):
835
+ rss_mb = 0.0
836
+
837
+ monitor.record_step(
838
+ step=step,
839
+ phase=phase,
840
+ epoch=epoch,
841
+ dataset_name=dataset_name,
842
+ batch_loss=float(loss),
843
+ batch_acc=float(acc),
844
+ kls=kls,
845
+ mtp_metrics=mtp_metrics,
846
+ ewc_metrics=ewc_metrics,
847
+ rss_mb=float(rss_mb),
848
+ )
849
+ step += 1
850
+ if step % 10 == 0 or step == 1:
851
+ som_m = kls.som.get_metrics()
852
+ mtp_str = (
853
+ f"mtp={mtp_metrics['total_loss']:.3f} "
854
+ f"ent={mtp_metrics['entropy_reg']:.4f}"
855
+ if mtp_metrics else "mtp=N/A"
856
+ )
857
+ logger.info(
858
+ f"[V6.5] step={step:3d} | ph={phase} | ds={ds_idx+1}/{N_DATASETS} | "
859
+ f"loss={loss:.3f} acc={acc:.3f} | {mtp_str} | "
860
+ f"σ={som_m['sigma_t']:.3f} α={som_m['alpha_t']:.3f} | "
861
+ f"punish={kls.punishment_count} success={kls.success_count} | "
862
+ f"buff={len(kls.buffer_4d)} | "
863
+ f"hyp={'Y' if kls.classifier_trained else 'N'} | "
864
+ f"ewc={'Y' if som_m['has_ewc_reference'] else 'N'} | "
865
+ f"RSS={rss_mb:.0f}MB"
866
+ )
867
+ if stop_requested:
868
+ logger.warning(
869
+ f"[V6.5] stop_requested (2nd punishment → EWC reset) at step={step} phase={phase}"
870
+ )
871
+
872
+ t_train_end = time.time()
873
+ train_duration = t_train_end - t_train_start
874
+ logger.info(f"\n[V6.5] Treino concluído em {train_duration:.1f}s ({step} steps)")
875
+
876
+ # ------------------------------------------------------------------
877
+ # EWC+W8A8 eval investigation (V6.5)
878
+ # ------------------------------------------------------------------
879
+ logger.info("[V6.5] Investigating EWC+W8A8 eval interaction...")
880
+ ewc_w8a8_investigation = investigate_ewc_w8a8_eval(kls)
881
+ logger.info(f"[V6.5] EWC+W8A8 eval investigation: {ewc_w8a8_investigation['findings']['interaction'][:80]}...")
882
+
883
+ # ------------------------------------------------------------------
884
+ # Final report
885
+ # ------------------------------------------------------------------
886
+ summary = monitor.summary()
887
+ som_final = kls.som.get_metrics()
888
+ kls_state = kls.get_state_metrics()
889
+
890
+ report = {
891
+ "version": "V6.5",
892
+ "timestamp": datetime.now().isoformat(),
893
+ "config": {
894
+ "BATCH_SIZE": BATCH_SIZE,
895
+ "N_DATASETS": N_DATASETS,
896
+ "SAMPLES_PER_DATASET_PHASE": SAMPLES_PER_DATASET_PHASE,
897
+ "N_PHASES": N_PHASES,
898
+ "TOTAL_SAMPLES": TOTAL_SAMPLES,
899
+ "EPOCHS": EPOCHS,
900
+ "SOM_GRID": list(SOM_GRID),
901
+ "n_neurons": n_neurons,
902
+ "HIDDEN_DIM": HIDDEN_DIM,
903
+ "VOCAB_SIZE": VOCAB_SIZE,
904
+ "MAX_SEQ_LEN": MAX_SEQ_LEN,
905
+ "T_max": T_MAX,
906
+ "N_start": N_START,
907
+ "lambda_ewc": LAMBDA_EWC,
908
+ "MTP_K": MTP_K,
909
+ "MTP_ENTROPY_BETA": MTP_ENTROPY_BETA,
910
+ "MTP_ACTIVE_IN_VAL": MTP_ACTIVE_IN_VAL,
911
+ },
912
+ "xeon_status": XEON_STATUS,
913
+ "fp16_benchmark": FP16_BENCH,
914
+ "training": {
915
+ "duration_s": float(train_duration),
916
+ "n_steps": int(step),
917
+ "n_epochs": EPOCHS,
918
+ "n_phases": N_PHASES,
919
+ },
920
+ "summary": summary,
921
+ "kohonen_final": som_final,
922
+ "kls_state": kls_state,
923
+ "ewc_w8a8_investigation": ewc_w8a8_investigation,
924
+ "module_analysis_summary": {
925
+ "n_candidates": len(module_analysis["candidates"]),
926
+ "n_explicit_imports": len(module_analysis["explicit_imports"]),
927
+ "n_newly_integrated": len(module_analysis["newly_integrated_v65"]),
928
+ "candidates_detail": module_analysis["candidates"],
929
+ },
930
+ "script_activity_summary": {
931
+ "n_scripts": len(script_activity),
932
+ "active_v65": sum(1 for v in script_activity.values() if v["classification"] == "active_v65"),
933
+ "recent_v6": sum(1 for v in script_activity.values() if v["classification"].startswith("active_v6")),
934
+ "legacy": sum(1 for v in script_activity.values() if v["classification"] == "legacy"),
935
+ },
936
+ "math_analysis": {
937
+ "text_to_4d": "SVD: M @ V[:3].T -> centroid 3D + w = time_step/T_max (LINEAR)",
938
+ "bmu_distance": "||W - x||^2 (L2 squared in R^4)",
939
+ "neighborhood": "Lambda(d, sigma) = exp(-d^2 / (2*sigma^2))",
940
+ "weight_update": "dW = alpha * Lambda * (x - W)",
941
+ "sigma_decay": "sigma_t = sigma0 * exp(-t/1000)",
942
+ "alpha_decay": "alpha_t = alpha0 * exp(-t/2000)",
943
+ "ewc_only_dim4": "penalty = lambda * F * (W_w - W*_w)",
944
+ "mtp_loss": "L = sum_k(alpha_k * L_k) - beta * H(alpha), H = -sum alpha_k log(alpha_k)",
945
+ "ewc_w8a8_eval": "forward-only penalty in eval; SmoothQuant preserves scale for dequant",
946
+ },
947
+ "datasets_used": V65_DATASETS,
948
+ }
949
+
950
+ REPORT_PATH.write_text(json.dumps(report, indent=2, ensure_ascii=False, default=str))
951
+ logger.info(f"[V6.5] Report saved: {REPORT_PATH}")
952
+
953
+ metrics_full = {
954
+ "version": "V6.5",
955
+ "steps": monitor.steps,
956
+ "summary": summary,
957
+ "alerts": monitor.alerts,
958
+ }
959
+ METRICS_PATH.write_text(json.dumps(metrics_full, indent=2, ensure_ascii=False, default=str))
960
+ logger.info(f"[V6.5] Metrics saved: {METRICS_PATH}")
961
+
962
+ # Print final summary
963
+ print("\n" + "=" * 80)
964
+ print("V6.5 — TREINO CONCLUÍDO")
965
+ print("=" * 80)
966
+ print(f" Steps : {step}")
967
+ print(f" Duration : {train_duration:.1f}s")
968
+ print(f" Phases : {N_PHASES} (500 + 500 = {TOTAL_SAMPLES} samples)")
969
+ print(f" Final loss : {summary.get('final_loss', 0):.3f}")
970
+ print(f" Mean loss : {summary.get('mean_loss', 0):.3f}")
971
+ print(f" Final acc : {summary.get('final_acc', 0):.3f}")
972
+ print(f" Mean acc : {summary.get('mean_acc', 0):.3f}")
973
+ print(f" Sigma (start→end) : {summary.get('sigma_start', 0):.3f} → {summary.get('sigma_end', 0):.3f}")
974
+ print(f" Alpha (start→end) : {summary.get('alpha_start', 0):.3f} → {summary.get('alpha_end', 0):.3f}")
975
+ print(f" MTP mean loss : {summary.get('mtp_mean_loss', 0):.3f}")
976
+ print(f" MTP final loss : {summary.get('mtp_final_loss', 0):.3f}")
977
+ evo = summary.get("evolution_phase1_to_phase2", {})
978
+ print(f" Evolution P1→P2:")
979
+ print(f" acc P1 mean : {evo.get('acc_phase1_mean', 0):.3f}")
980
+ print(f" acc P2 mean : {evo.get('acc_phase2_mean', 0):.3f}")
981
+ print(f" sigma P1 end : {evo.get('sigma_phase1_end', 0):.3f}")
982
+ print(f" sigma P2 end : {evo.get('sigma_phase2_end', 0):.3f}")
983
+ print(f" RSS max : {summary.get('rss_max_mb', 0):.0f}MB")
984
+ print(f" RSS trend : {summary.get('rss_trend', '?')}")
985
+ print(f" Alerts : {summary.get('n_alerts', 0)}")
986
+ print(f" Hypothesis trained : {kls.classifier_trained}")
987
+ print(f" EWC reference set : {som_final['has_ewc_reference']}")
988
+ print(f" Time counter : {kls.time_counter}")
989
+ print(f" Module analysis : {MODULE_ANALYSIS_PATH}")
990
+ print(f" Script activity : {SCRIPT_ACTIVITY_PATH}")
991
+ print("=" * 80)
992
+ print(f"\n Report : {REPORT_PATH}")
993
+ print(f" Metrics: {METRICS_PATH}\n")
994
+
995
+ return 0
996
+
997
+
998
+ if __name__ == "__main__":
999
+ sys.exit(main())
scripts/upload_v6_4_resilient.py CHANGED
@@ -1,7 +1,7 @@
1
  """upload_v6_4_resilient.py — V6.4 upload to HuggingFace (single commit).
2
 
3
  User requirement:
4
- "HF_TOKEN=hf_<REDACTED_TOKEN> que deve ser apagada após uso"
5
 
6
  Uploads V6.4 critical files to PowerMachine/BiGRU_T_version via single
7
  commit (upload_folder). Token is read from env var, never written to file.
@@ -52,16 +52,16 @@ def main() -> int:
52
 
53
  # CRITICAL: scrub token from any script files before upload
54
  # (V6.3 had a bug where token was in docstrings — fixed)
 
 
 
55
  print("\n Pre-upload safety: scrubbing token from scripts...")
56
  for script_path in BIGRU_ROOT.glob("scripts/*.py"):
57
  try:
58
  content = script_path.read_text()
59
- if "hf_<REDACTED_TOKEN>" in content:
60
- # Replace any literal token with redacted placeholder
61
- scrubbed = content.replace(
62
- "hf_<REDACTED_TOKEN>",
63
- "hf_<REDACTED_TOKEN>",
64
- )
65
  script_path.write_text(scrubbed)
66
  print(f" SCRUBBED: {script_path.name}")
67
  except Exception as e:
 
1
  """upload_v6_4_resilient.py — V6.4 upload to HuggingFace (single commit).
2
 
3
  User requirement:
4
+ HF_TOKEN should be deleted after use (read from env, never written to file).
5
 
6
  Uploads V6.4 critical files to PowerMachine/BiGRU_T_version via single
7
  commit (upload_folder). Token is read from env var, never written to file.
 
52
 
53
  # CRITICAL: scrub token from any script files before upload
54
  # (V6.3 had a bug where token was in docstrings — fixed)
55
+ # Use regex to detect any HF token format (hf_<32+ alphanumeric>)
56
+ import re
57
+ token_pattern = re.compile(r'hf_[A-Za-z0-9]{32,}')
58
  print("\n Pre-upload safety: scrubbing token from scripts...")
59
  for script_path in BIGRU_ROOT.glob("scripts/*.py"):
60
  try:
61
  content = script_path.read_text()
62
+ if token_pattern.search(content):
63
+ # Replace any HF token with redacted placeholder
64
+ scrubbed = token_pattern.sub("hf_<REDACTED_TOKEN>", content)
 
 
 
65
  script_path.write_text(scrubbed)
66
  print(f" SCRUBBED: {script_path.name}")
67
  except Exception as e:
scripts/upload_v6_5_resilient.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """upload_v6_5_resilient.py — V6.5 upload to HuggingFace (single commit)."""
2
+ from __future__ import annotations
3
+ import json, os, sys, time, re
4
+ from pathlib import Path
5
+
6
+ PROJECT_ROOT = Path("/home/z/my-project")
7
+ BIGRU_ROOT = PROJECT_ROOT / "BiGRU_T_version"
8
+
9
+ CRITICAL_FILES_V65 = [
10
+ "src/bigru_t/model/kohonen_refactored/__init__.py",
11
+ "src/bigru_t/model/kohonen_refactored/kohonen_learning_system.py",
12
+ "src/bigru_t/model/hyp_t.py",
13
+ "src/bigru_t/training/mtp.py",
14
+ "src/bigru_t/training/ewc.py",
15
+ "src/bigru_t/quantization/smoothquant_compressor.py",
16
+ "src/bigru_t/model/vqvae2_hierarchical.py",
17
+ "src/bigru_t/model/vqvae2_hierarchical_flexnet.py",
18
+ "src/bigru_t/model/token_compress.py",
19
+ "src/bigru_t/reasoning/thinking.py",
20
+ "src/bigru_t/reasoning/reasoning_engine.py",
21
+ "src/bigru_t/reasoning/circular_orchestration.py",
22
+ "src/bigru_t/reasoning/tool_agent.py",
23
+ "src/bigru_t/reasoning/distributed_reasoning_system.py",
24
+ "src/bigru_t/reasoning/cyclic_reasoning.py",
25
+ "src/bigru_t/reasoning/consensus_sampling.py",
26
+ "v6_5_report.json",
27
+ "v6_5_training_metrics.json",
28
+ "v6_5_module_analysis.json",
29
+ "v6_5_script_activity.json",
30
+ "scripts/train_v6_5.py",
31
+ "scripts/upload_v6_5_resilient.py",
32
+ "src/bigru_t/utils/xeon_runtime.py",
33
+ "src/bigru_t/data/streaming_datasets.py",
34
+ ]
35
+
36
+ def main() -> int:
37
+ print("=" * 72)
38
+ print("V6.5 — UPLOAD TO HUGGINGFACE")
39
+ print("=" * 72)
40
+ hf_token = os.environ.get("HF_TOKEN")
41
+ if not hf_token:
42
+ print("ERROR: HF_TOKEN not set in env")
43
+ return 1
44
+ print(f" HF_TOKEN loaded from env (length={len(hf_token)})")
45
+
46
+ # Pre-upload safety: regex scrub any HF token format
47
+ token_pattern = re.compile(r'hf_[A-Za-z0-9]{32,}')
48
+ print("\n Pre-upload safety: scrubbing token from scripts...")
49
+ for script_path in BIGRU_ROOT.glob("scripts/*.py"):
50
+ try:
51
+ content = script_path.read_text()
52
+ if token_pattern.search(content):
53
+ scrubbed = token_pattern.sub("hf_<REDACTED_TOKEN>", content)
54
+ script_path.write_text(scrubbed)
55
+ print(f" SCRUBBED: {script_path.name}")
56
+ except Exception as e:
57
+ print(f" SKIP {script_path.name}: {e}")
58
+
59
+ try:
60
+ from huggingface_hub import HfApi, upload_folder
61
+ except ImportError:
62
+ print("ERROR: huggingface_hub not installed")
63
+ return 1
64
+
65
+ api = HfApi(token=hf_token)
66
+ repo_id = "PowerMachine/BiGRU_T_version"
67
+ try:
68
+ info = api.repo_info(repo_id=repo_id, repo_type="model")
69
+ print(f" Repo: {repo_id} (existing, files={len(info.siblings)})")
70
+ except Exception as e:
71
+ print(f" ERROR: cannot access repo: {e}")
72
+ return 1
73
+
74
+ print(f"\n Uploading {BIGRU_ROOT} as single commit...")
75
+ t0 = time.time()
76
+ try:
77
+ commit_info = upload_folder(
78
+ repo_id=repo_id, repo_type="model",
79
+ folder_path=str(BIGRU_ROOT),
80
+ commit_message="V6.5: 1000 samples (500+500), MTP val+entropy, EWC+W8A8 eval investigation, integrate gru-ring modules",
81
+ token=hf_token,
82
+ )
83
+ t1 = time.time()
84
+ print(f" Upload completed in {t1 - t0:.2f}s")
85
+ print(f" Commit: {commit_info.oid}")
86
+ print(f" URL: https://huggingface.co/PowerMachine/BiGRU_T_version/commit/{commit_info.oid}")
87
+ except Exception as e:
88
+ print(f" ERROR: upload failed: {e}")
89
+ return 1
90
+
91
+ print("\n Verifying critical files in repo...")
92
+ try:
93
+ files_in_repo = api.list_repo_files(repo_id, repo_type="model")
94
+ all_present = True
95
+ for cf in CRITICAL_FILES_V65:
96
+ present = cf in files_in_repo
97
+ mark = "OK" if present else "MISS"
98
+ print(f" [{mark}] {cf}")
99
+ if not present:
100
+ all_present = False
101
+ print(f"\n Files in repo: {len(files_in_repo)}")
102
+ if not all_present:
103
+ print(" WARNING: some critical files missing!")
104
+ except Exception as e:
105
+ print(f" WARNING: cannot verify files: {e}")
106
+
107
+ report = {
108
+ "version": "V6.5",
109
+ "upload_timestamp": time.strftime("%Y-%m-%dT%H:%M:%S"),
110
+ "repo_id": repo_id,
111
+ "commit_oid": commit_info.oid,
112
+ "commit_url": f"https://huggingface.co/PowerMachine/BiGRU_T_version/commit/{commit_info.oid}",
113
+ "duration_s": float(t1 - t0),
114
+ "critical_files": CRITICAL_FILES_V65,
115
+ "n_files_in_repo": len(files_in_repo) if "files_in_repo" in dir() else 0,
116
+ }
117
+ report_path = BIGRU_ROOT / "v6_5_upload_report.json"
118
+ report_path.write_text(json.dumps(report, indent=2, ensure_ascii=False))
119
+ print(f"\n Upload report: {report_path}")
120
+ print("\n" + "=" * 72)
121
+ print("V6.5 — UPLOAD COMPLETED")
122
+ print("=" * 72)
123
+ return 0
124
+
125
+ if __name__ == "__main__":
126
+ sys.exit(main())
src/bigru_t/model/token_compress.py ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ token_compress — Compressores e indexadores para atenção de 2M tokens.
3
+
4
+ Pipeline (3 estágios):
5
+ 1. ToMe (Token Merging) — Bolya et al., 2023
6
+ Funde tokens similares via matching bipartido soft. Reduz N → N' com
7
+ N' = N - r·T (r tokens por camada, T camadas). Custo O(N log N).
8
+
9
+ 2. KNN Indexer (IVF-like)
10
+ Mantém centroides via k-means. Para cada query, busca top-k tokens
11
+ no índice (k << N'). Custo O(N' log N') para construir, O(k log N')
12
+ por query.
13
+
14
+ 3. Per-Layer Attention Pattern
15
+ Cada camada tem seu próprio padrão de sparsidade, selecionável:
16
+ - "full": dense attention clássica (O(N²)) — apenas para N' pequeno
17
+ - "window": atenção local em janela w
18
+ - "global": tokens especiais (CLS, registradores) attendem a tudo
19
+ - "block": atenção em blocos (BLOCKWISE)
20
+ O padrão é configurável por camada via lista `patterns`.
21
+
22
+ Complexidade total: O(N log N + T · k · N') comparado a O(T · N²) do
23
+ Transformer denso. Para N=2M, T=24, k=256: ganho ~ 50×.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import math
29
+ from typing import List, Optional, Tuple
30
+
31
+ import torch
32
+ import torch.nn as nn
33
+ import torch.nn.functional as F
34
+
35
+
36
+ # ---------------------------------------------------------------------------
37
+ # 1. ToMeCompressor
38
+ # ---------------------------------------------------------------------------
39
+ def _bipartite_soft_matching(
40
+ metric: torch.Tensor,
41
+ r: int,
42
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
43
+ """Matching bipartido soft (Bolya et al., 2023 — algoritmo original).
44
+
45
+ Passos:
46
+ 1. Ordena tokens por score (norma do embedding — proxy para PCA[0]).
47
+ 2. Separa alternadamente em dois conjuntos A (índices pares) e B
48
+ (índices ímpares) — disjuntos, |A| = |B| = N//2.
49
+ 3. Para cada i ∈ [0, N//2), forma par candidato (a_i, b_i).
50
+ 4. Calcula similaridade s_i = ⟨a_i, b_i⟩.
51
+ 5. Seleciona os r pares com maior similaridade para fundir.
52
+ Os demais pares (N//2 - r) mantêm ambos os tokens.
53
+
54
+ metric: (B, N, C)
55
+ r: nº de pares a fundir
56
+ Retorna:
57
+ a_idx: (B, r) — índices de A nos pares fundidos (âncoras)
58
+ b_idx: (B, r) — índices de B nos pares fundidos
59
+ ungated_idx: (B, N - 2r) — índices dos tokens não fundidos
60
+ """
61
+ B, N, C = metric.shape
62
+ M = N // 2 # número de pares
63
+
64
+ if r <= 0 or M < r:
65
+ all_idx = torch.arange(N, device=metric.device).unsqueeze(0).expand(B, -1)
66
+ return all_idx[:, :0], all_idx[:, :0], all_idx
67
+
68
+ with torch.no_grad():
69
+ scores = metric.norm(dim=-1) # (B, N)
70
+ sorted_idx = scores.argsort(dim=-1, descending=True) # (B, N)
71
+ # Alterna pares/ímpares: A = sorted_idx[:, 0::2], B = sorted_idx[:, 1::2].
72
+ a_idx_all = sorted_idx[:, 0:2 * M:2] # (B, M)
73
+ b_idx_all = sorted_idx[:, 1:2 * M:2] # (B, M)
74
+ # Similaridade entre cada par (a_i, b_i).
75
+ a_set = metric.gather(1, a_idx_all.unsqueeze(-1).expand(-1, -1, C)) # (B, M, C)
76
+ b_set = metric.gather(1, b_idx_all.unsqueeze(-1).expand(-1, -1, C)) # (B, M, C)
77
+ sim = (a_set * b_set).sum(dim=-1) # (B, M)
78
+ # Top-r pares mais similares para fundir.
79
+ top_r = sim.topk(r, dim=-1).indices # (B, r)
80
+ # Máscara de pares fundidos.
81
+ merged_mask = torch.zeros(B, M, dtype=torch.bool, device=metric.device)
82
+ merged_mask.scatter_(1, top_r, True)
83
+ # Índices de pares não-fundidos (constantes no batch).
84
+ pair_idx = torch.arange(M, device=metric.device).unsqueeze(0).expand(B, -1)
85
+ keep_pair = pair_idx[~merged_mask] # (B*(M-r),)
86
+ keep_pair = keep_pair.reshape(B, M - r)
87
+ # Token indices.
88
+ a_merge = a_idx_all.gather(1, top_r) # (B, r)
89
+ b_merge = b_idx_all.gather(1, top_r) # (B, r)
90
+ a_keep = a_idx_all.gather(1, keep_pair) # (B, M-r)
91
+ b_keep = b_idx_all.gather(1, keep_pair) # (B, M-r)
92
+ # Ungated = a_keep ∪ b_keep (total = 2*(M-r) = N - 2r se N par).
93
+ ungated = torch.cat([a_keep, b_keep], dim=1) # (B, 2(M-r))
94
+ return a_merge, b_merge, ungated
95
+
96
+
97
+ class ToMeCompressor(nn.Module):
98
+ """Token Merging (ToMe) — funde r tokens similares a cada forward.
99
+
100
+ Reduz N → N - r tokens (mantém dimensão de feature).
101
+ """
102
+
103
+ def __init__(self, r: int = 64, use_merge_bias: bool = False):
104
+ super().__init__()
105
+ self.r = r
106
+ # Opcional: pequeno gate para mistura ponderada entre par (a, b).
107
+ # Por padrão usamos média simples (estilo ToMe original).
108
+ self.merge_gate = nn.Parameter(torch.tensor(0.5)) if use_merge_bias else None
109
+
110
+ def forward(self, X: torch.Tensor, return_aux: bool = False) -> torch.Tensor:
111
+ """X: (B, N, D) -> (B, N - r, D).
112
+
113
+ Quando return_aux=True, retorna também os índices (para debug).
114
+ """
115
+ B, N, D = X.shape
116
+ M = N // 2
117
+ # Se não há pares suficientes para fundir, retorna X inalterado.
118
+ if self.r <= 0 or M < self.r:
119
+ return X
120
+ a_pair, b_idx, ungated = _bipartite_soft_matching(X, self.r)
121
+ # Merge: média do par (a, b).
122
+ a_set = X.gather(1, a_pair.unsqueeze(-1).expand(-1, -1, D)) # (B, r, D)
123
+ b_set = X.gather(1, b_idx.unsqueeze(-1).expand(-1, -1, D)) # (B, r, D)
124
+ if self.merge_gate is not None:
125
+ w = torch.sigmoid(self.merge_gate)
126
+ merged = w * a_set + (1.0 - w) * b_set
127
+ else:
128
+ merged = 0.5 * (a_set + b_set)
129
+ # Ungated tokens (2*(M-r)).
130
+ ungated_set = X.gather(1, ungated.unsqueeze(-1).expand(-1, -1, D)) # (B, 2(M-r), D)
131
+ # Concatena: ungated + merged = 2(M-r) + r = 2M - r = N - r (se N par).
132
+ out = torch.cat([ungated_set, merged], dim=1) # (B, N - r, D)
133
+ if return_aux:
134
+ return out, (a_pair, b_idx, ungated)
135
+ return out
136
+
137
+
138
+ # ---------------------------------------------------------------------------
139
+ # 2. KNNIndexer (IVF-like, sem dependência do FAISS)
140
+ # ---------------------------------------------------------------------------
141
+ class KNNIndexer(nn.Module):
142
+ """Indexador k-NN baseado em k-means (estilo IVF).
143
+
144
+ Mantém uma lista invertida de tokens por centroide. Query busca
145
+ apenas nos centroides mais próximos (n_probe) e retorna top-k tokens
146
+ globais. Custo por query: O(n_probe · avg_list_size + n_centroids).
147
+
148
+ Funciona em batch: para cada query, retorna índices dos top-k tokens
149
+ e os pesos de similaridade (cosseno).
150
+ """
151
+
152
+ def __init__(
153
+ self,
154
+ dim: int,
155
+ n_centroids: int = 256,
156
+ n_probe: int = 8,
157
+ k: int = 64,
158
+ n_iter: int = 5,
159
+ ):
160
+ super().__init__()
161
+ self.dim = dim
162
+ self.n_centroids = n_centroids
163
+ self.n_probe = n_probe
164
+ self.k = k
165
+ self.n_iter = n_iter
166
+ # Centroides — buffer treinável em modo "build".
167
+ self.register_buffer("centroids", torch.randn(n_centroids, dim) * 0.02)
168
+ # Listas invertidas (chave = centroide idx, valor = índices de tokens).
169
+ # Em runtime mantemos como listas Python — não persistimos em state_dict.
170
+ self._lists: List[torch.Tensor] = []
171
+ self._tokens: Optional[torch.Tensor] = None # (N, D)
172
+ self._built = False
173
+
174
+ @torch.no_grad()
175
+ def build(self, tokens: torch.Tensor) -> None:
176
+ """Constrói o índice IVF sobre o banco de tokens.
177
+
178
+ tokens: (N, D)
179
+ """
180
+ N, D = tokens.shape
181
+ assert D == self.dim
182
+ device = tokens.device
183
+ # 1. K-means rápido (n_iter iterações de Lloyd).
184
+ if N <= self.n_centroids:
185
+ self.centroids = tokens.clone()
186
+ self._lists = [torch.tensor([i], device=device) for i in range(N)]
187
+ else:
188
+ # Inicialização: amostragem aleatória.
189
+ perm = torch.randperm(N, device=device)[:self.n_centroids]
190
+ self.centroids = tokens[perm].clone()
191
+ for _ in range(self.n_iter):
192
+ # Atribui cada token ao centroide mais próximo.
193
+ d2 = (tokens.unsqueeze(1) - self.centroids.unsqueeze(0)).pow(2).sum(-1) # (N, K)
194
+ assign = d2.argmin(dim=-1) # (N,)
195
+ # Atualiza centroides.
196
+ for k in range(self.n_centroids):
197
+ mask = assign == k
198
+ if mask.any():
199
+ self.centroids[k] = tokens[mask].mean(dim=0)
200
+ # Constói listas invertidas.
201
+ d2 = (tokens.unsqueeze(1) - self.centroids.unsqueeze(0)).pow(2).sum(-1)
202
+ assign = d2.argmin(dim=-1)
203
+ self._lists = [
204
+ (assign == k).nonzero(as_tuple=True)[0].to(device)
205
+ for k in range(self.n_centroids)
206
+ ]
207
+ self._tokens = tokens
208
+ self._built = True
209
+
210
+ @torch.no_grad()
211
+ def search(self, queries: torch.Tensor, k: Optional[int] = None) -> Tuple[torch.Tensor, torch.Tensor]:
212
+ """Busca top-k tokens para cada query.
213
+
214
+ queries: (B, D)
215
+ Retorna:
216
+ indices: (B, k) — índices no banco _tokens
217
+ weights: (B, k) — similaridade cosseno (em [-1, 1])
218
+ """
219
+ if not self._built:
220
+ raise RuntimeError("Índice não construído. Chame build() antes.")
221
+ k = k or self.k
222
+ B = queries.shape[0]
223
+ device = queries.device
224
+ # 1. Encontra n_probe centroides mais próximos por query.
225
+ q_norm = F.normalize(queries, dim=-1) # (B, D)
226
+ c_norm = F.normalize(self.centroids, dim=-1) # (K, D)
227
+ sim_c = q_norm @ c_norm.t() # (B, K)
228
+ n_probe = min(self.n_probe, self.n_centroids)
229
+ top_c = sim_c.topk(n_probe, dim=-1).indices # (B, n_probe)
230
+
231
+ # 2. Para cada query, agrega tokens das listas invertidas correspondentes.
232
+ all_idx_list = []
233
+ all_w_list = []
234
+ for b in range(B):
235
+ cand_indices = torch.cat([self._lists[c.item()] for c in top_c[b] if len(self._lists[c.item()]) > 0])
236
+ if cand_indices.numel() == 0:
237
+ # Fallback: busca global.
238
+ cand_indices = torch.arange(self._tokens.shape[0], device=device)
239
+ cand_tokens = self._tokens[cand_indices] # (M, D)
240
+ q_b = q_norm[b] # (D,)
241
+ sims = (cand_tokens / cand_tokens.norm(dim=-1, keepdim=True).clamp(min=1e-8)) @ q_b # (M,)
242
+ kk = min(k, sims.numel())
243
+ topk = sims.topk(kk)
244
+ idx = cand_indices[topk.indices] # (kk,)
245
+ w = topk.values # (kk,)
246
+ # Pad com zeros se necessário.
247
+ if kk < k:
248
+ pad_idx = torch.zeros(k - kk, dtype=torch.long, device=device)
249
+ pad_w = torch.zeros(k - kk, device=device)
250
+ idx = torch.cat([idx, pad_idx])
251
+ w = torch.cat([w, pad_w])
252
+ all_idx_list.append(idx)
253
+ all_w_list.append(w)
254
+ indices = torch.stack(all_idx_list, dim=0) # (B, k)
255
+ weights = torch.stack(all_w_list, dim=0) # (B, k)
256
+ return indices, weights
257
+
258
+
259
+ # ---------------------------------------------------------------------------
260
+ # 3. CompressionPipeline (ToMe + KNN index)
261
+ # ---------------------------------------------------------------------------
262
+ class CompressionPipeline(nn.Module):
263
+ """Pipeline de compressão: ToMe → KNN index → retorna subconjunto + pesos."""
264
+
265
+ def __init__(
266
+ self,
267
+ dim: int,
268
+ tome_r: int = 64,
269
+ n_centroids: int = 256,
270
+ n_probe: int = 8,
271
+ k: int = 64,
272
+ ):
273
+ super().__init__()
274
+ self.tome = ToMeCompressor(r=tome_r)
275
+ self.indexer = KNNIndexer(dim=dim, n_centroids=n_centroids, n_probe=n_probe, k=k)
276
+ self._built = False
277
+
278
+ @torch.no_grad()
279
+ def build(self, tokens: torch.Tensor) -> None:
280
+ """Constrói índice KNN sobre tokens pré-comprimidos por ToMe."""
281
+ compressed = self.tome(tokens)
282
+ self.indexer.build(compressed)
283
+ self._built = True
284
+
285
+ def forward(
286
+ self,
287
+ queries: torch.Tensor,
288
+ keys: torch.Tensor,
289
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
290
+ """Para cada query, retorna top-k keys + pesos.
291
+
292
+ queries: (B, N_q, D)
293
+ keys: (B, N_k, D) — índice construído para o batch atual.
294
+
295
+ Em modo "global" (índice precompilado via build), apenas queries são
296
+ processadas e keys são ignoradas.
297
+
298
+ Retorna:
299
+ indices: (B, N_q, k) — índices das top-k keys
300
+ weights: (B, N_q, k) — similaridades (cosseno)
301
+ compressed_keys: (B, N_k - r, D) — keys pós-ToMe (se r > 0)
302
+ """
303
+ # Comprime keys via ToMe.
304
+ compressed_keys = self.tome(keys)
305
+ # Para cada batch element, faz busca local (não usa índice global pré-construído).
306
+ B, Nq, D = queries.shape
307
+ Nk_c = compressed_keys.shape[1]
308
+ k = self.indexer.k
309
+ # Similaridade cosseno entre queries e compressed_keys.
310
+ q_norm = F.normalize(queries, dim=-1) # (B, Nq, D)
311
+ k_norm = F.normalize(compressed_keys, dim=-1) # (B, Nk_c, D)
312
+ sim = q_norm @ k_norm.transpose(-1, -2) # (B, Nq, Nk_c)
313
+ topk = sim.topk(min(k, Nk_c), dim=-1) # (B, Nq, k)
314
+ indices = topk.indices # (B, Nq, k)
315
+ weights = topk.values # (B, Nq, k)
316
+ return indices, weights, compressed_keys
src/bigru_t/model/vqvae2_hierarchical.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Xavante - vqvae2_hierarchical.py
3
+ Responsabilidade: VQ-VAE-2 hierarquica (Teorema 13.1/13.2/13.3).
4
+ Reutiliza implementacao validada do FlexNet com EMA + Goose VQ + dead code restart.
5
+ Referencia: Razavi et al. 2019 - Generating Diverse High-Fidelity Images with VQ-VAE-2.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+ import math
11
+ from typing import List, Tuple
12
+
13
+ import torch
14
+ import torch.nn as nn
15
+ import torch.nn.functional as F
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ class VectorQuantizerEMA(nn.Module):
21
+ """
22
+ VQ com atualizacao EMA do codebook (validado no FlexNet).
23
+ Inclui: dead code restart, commitment loss, Goose VQ.
24
+ v6 aprimoramentos:
25
+ - Diversity loss (entropy bonus) para forcar uso uniforme do codebook
26
+ - Commitment warmup: beta_t = beta_0 * min(1, t/warmup)
27
+ - EMA restart mais agressivo (decay adaptativo)
28
+ """
29
+
30
+ def __init__(
31
+ self,
32
+ num_embeddings: int,
33
+ embedding_dim: int,
34
+ commitment_cost: float = 0.25,
35
+ decay: float = 0.99,
36
+ epsilon: float = 1e-5,
37
+ dead_threshold: int = 1,
38
+ diversity_weight: float = 0.1,
39
+ warmup_steps: int = 500,
40
+ ):
41
+ super().__init__()
42
+ self.num_embeddings = num_embeddings
43
+ self.embedding_dim = embedding_dim
44
+ self.commitment_cost = commitment_cost
45
+ self.decay = decay
46
+ self.epsilon = epsilon
47
+ self.dead_threshold = dead_threshold
48
+ self.diversity_weight = diversity_weight
49
+ self.warmup_steps = warmup_steps
50
+ self._step = 0
51
+
52
+ embed = torch.empty(num_embeddings, embedding_dim)
53
+ nn.init.normal_(embed, mean=0.0, std=0.02)
54
+ self.register_buffer("embeddings", embed)
55
+ self.register_buffer("ema_count", torch.zeros(num_embeddings))
56
+ self.register_buffer("ema_weight", embed.clone())
57
+ self.register_buffer("usage_count", torch.zeros(num_embeddings, dtype=torch.long))
58
+
59
+ def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
60
+ """
61
+ x: [B, D, H, W] ou [B, D]
62
+ Retorna (quantized, loss, encoding_indices)
63
+ """
64
+ if x.dim() == 4:
65
+ # [B, D, H, W] -> [B, H, W, D] -> [B*H*W, D]
66
+ B, D, H, W = x.shape
67
+ flat = x.permute(0, 2, 3, 1).reshape(-1, self.embedding_dim)
68
+ else:
69
+ # [B, D] -> [B, D]
70
+ flat = x.reshape(-1, self.embedding_dim)
71
+ # Distancia
72
+ distances = (
73
+ flat.pow(2).sum(1, keepdim=True)
74
+ - 2 * flat @ self.embeddings.t()
75
+ + self.embeddings.pow(2).sum(1)
76
+ )
77
+ indices = torch.argmin(distances, dim=1)
78
+ one_hot = F.one_hot(indices, self.num_embeddings).type(flat.dtype)
79
+ quantized = one_hot @ self.embeddings
80
+ # Uso
81
+ self.usage_count.index_add_(0, indices, torch.ones_like(indices))
82
+
83
+ # EMA update
84
+ if self.training:
85
+ with torch.no_grad():
86
+ count = one_hot.sum(0)
87
+ ema_count_new = self.decay * self.ema_count + (1 - self.decay) * count
88
+ total = ema_count_new.sum()
89
+ ema_count_new = (ema_count_new + self.epsilon) / (total + self.num_embeddings * self.epsilon) * total
90
+ dw = one_hot.t() @ flat
91
+ self.ema_weight = self.decay * self.ema_weight + (1 - self.decay) * dw
92
+ self.ema_count = ema_count_new
93
+ self.embeddings.copy_(self.ema_weight / self.ema_count.unsqueeze(1))
94
+
95
+ # Dead code restart
96
+ dead = self.usage_count < self.dead_threshold
97
+ if dead.any() and flat.shape[0] > 0:
98
+ dead_indices = dead.nonzero(as_tuple=True)[0]
99
+ n_dead = dead_indices.shape[0]
100
+ # Sample min(n_dead, flat.shape[0]) candidates from flat
101
+ n_replace = min(n_dead, flat.shape[0])
102
+ if n_replace > 0:
103
+ idx = torch.randperm(flat.shape[0])[:n_replace].to(flat.device)
104
+ # Substituir apenas n_replace codigos mortos
105
+ self.embeddings.data[dead_indices[:n_replace]] = flat[idx].detach()
106
+
107
+ # Commitment loss com warmup
108
+ self._step += 1
109
+ beta = self.commitment_cost * min(1.0, self._step / max(self.warmup_steps, 1))
110
+ e_latent_loss = F.mse_loss(quantized.detach(), flat)
111
+ q_latent_loss = F.mse_loss(quantized, flat.detach())
112
+ # Diversity loss: -H(p) onde p = freq de uso de cada code
113
+ # Maximizar entropia = forçar uso uniforme do codebook
114
+ if self.diversity_weight > 0 and self.training:
115
+ code_probs = one_hot.float().mean(dim=0) # [num_embeddings]
116
+ code_probs = code_probs.clamp_min(1e-10)
117
+ entropy = -(code_probs * code_probs.log()).sum()
118
+ diversity_loss = -entropy / math.log(self.num_embeddings) # normalize to [0, 1]
119
+ else:
120
+ diversity_loss = torch.tensor(0.0, device=x.device)
121
+ loss = q_latent_loss + beta * e_latent_loss + self.diversity_weight * diversity_loss
122
+
123
+ # Straight-through
124
+ quantized = flat + (quantized - flat).detach()
125
+ # Restore shape
126
+ if x.dim() == 4:
127
+ quantized = quantized.view(B, H, W, D).permute(0, 3, 1, 2).contiguous()
128
+ indices = indices.view(B, H, W)
129
+ else:
130
+ quantized = quantized.view_as(x)
131
+ return quantized, loss, indices
132
+
133
+
134
+ class HierarchicalVQVAE2(nn.Module):
135
+ """
136
+ VQ-VAE-2 com 2 niveis: top (global) e bottom (local).
137
+ Mapeia: Teorema 13.1/13.2/13.3.
138
+ """
139
+
140
+ def __init__(
141
+ self,
142
+ in_channels: int = 3,
143
+ hidden_dim: int = 64,
144
+ top_codebook: int = 128,
145
+ bottom_codebook: int = 512,
146
+ commitment_cost: float = 0.25,
147
+ decay: float = 0.99,
148
+ ):
149
+ super().__init__()
150
+ self.encoder_bottom = nn.Sequential(
151
+ nn.Conv2d(in_channels, hidden_dim, 4, 2, 1),
152
+ nn.GELU(),
153
+ nn.Conv2d(hidden_dim, hidden_dim, 4, 2, 1),
154
+ nn.GELU(),
155
+ nn.Conv2d(hidden_dim, hidden_dim, 3, 1, 1),
156
+ )
157
+ self.encoder_top = nn.Sequential(
158
+ nn.Conv2d(hidden_dim, hidden_dim, 4, 2, 1),
159
+ nn.GELU(),
160
+ nn.Conv2d(hidden_dim, hidden_dim, 4, 2, 1),
161
+ nn.GELU(),
162
+ nn.Conv2d(hidden_dim, hidden_dim, 3, 1, 1),
163
+ )
164
+ self.vq_top = VectorQuantizerEMA(top_codebook, hidden_dim, commitment_cost, decay)
165
+ self.vq_bottom = VectorQuantizerEMA(bottom_codebook, hidden_dim, commitment_cost, decay)
166
+ self.decoder_top = nn.Sequential(
167
+ nn.ConvTranspose2d(hidden_dim, hidden_dim, 4, 2, 1),
168
+ nn.GELU(),
169
+ nn.ConvTranspose2d(hidden_dim, hidden_dim, 4, 2, 1),
170
+ nn.GELU(),
171
+ )
172
+ self.decoder_bottom = nn.Sequential(
173
+ nn.ConvTranspose2d(hidden_dim * 2, hidden_dim, 4, 2, 1),
174
+ nn.GELU(),
175
+ nn.ConvTranspose2d(hidden_dim, hidden_dim, 4, 2, 1),
176
+ nn.GELU(),
177
+ nn.Conv2d(hidden_dim, in_channels, 3, 1, 1),
178
+ )
179
+
180
+ def forward(self, x: torch.Tensor) -> dict:
181
+ # Bottom encode
182
+ ze_b = self.encoder_bottom(x)
183
+ # Top encode
184
+ ze_t = self.encoder_top(ze_b)
185
+ zq_t, loss_t, idx_t = self.vq_top(ze_t)
186
+ # Decodifica top e soma com bottom
187
+ dec_t = self.decoder_top(zq_t)
188
+ # Concat com bottom quantized
189
+ zq_b, loss_b, idx_b = self.vq_bottom(ze_b)
190
+ cat = torch.cat([dec_t, zq_b], dim=1)
191
+ x_recon = self.decoder_bottom(cat)
192
+ return {
193
+ "reconstruction": x_recon,
194
+ "loss": loss_t + loss_b,
195
+ "top_indices": idx_t,
196
+ "bottom_indices": idx_b,
197
+ }
198
+
199
+
200
+ __all__ = ["VectorQuantizerEMA", "HierarchicalVQVAE2"]
src/bigru_t/model/vqvae2_hierarchical_flexnet.py ADDED
@@ -0,0 +1,513 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ vqvae2_hierarchical — VQ-VAE-2 (Razavi 2019) hierárquico com 2 níveis de codebook.
3
+
4
+ Arquitetura:
5
+ - Top level: codebook K_top captura estrutura global (low-resolution)
6
+ - Bottom level: codebook K_bot captura detalhes locais (high-resolution)
7
+ - Cada nível tem encoder/decoder proprio
8
+ - Residual quantization: bottom level quantiza o RESÍDUO do top level
9
+
10
+ Loss total:
11
+ L = ||x - D(top_q, bot_q)||²
12
+ + ||sg[z_top] - top_q||² + β·||z_top - sg[top_q]||²
13
+ + ||sg[z_bot] - bot_q||² + β·||z_bot - sg[bot_q]||²
14
+
15
+ Implementa:
16
+ - EMA updates em ambos codebooks
17
+ - Dead code restart em ambos codebooks
18
+ - Goose VQ com schedule de temperatura (alto→baixo)
19
+
20
+ Setup dos testes (solicitado):
21
+ - batch=256, K_top=512, K_bot=512
22
+ - Goose τ schedule: começa 2.0, decai para 0.5 via cosine
23
+ - EMA decay γ=0.99
24
+ - Dead code restart a cada 3 épocas
25
+ """
26
+
27
+ from __future__ import annotations
28
+ from typing import Dict, Optional, Tuple
29
+
30
+ import math
31
+ import numpy as np
32
+ import torch
33
+ import torch.nn as nn
34
+ import torch.nn.functional as F
35
+
36
+
37
+ # ============================================================
38
+ # v12.8: Normalizações alternativas (substituem LayerNorm v12.7)
39
+ # ============================================================
40
+
41
+ class RMSNorm(nn.Module):
42
+ """RMSNorm — preserva magnitude (não subtrai média como LayerNorm).
43
+
44
+ y = x / sqrt(mean(x²) + eps) * gamma
45
+
46
+ Vantagens sobre LayerNorm:
47
+ - Mais barato (sem cálculo de variância)
48
+ - Preserva magnitude do sinal (importante para VQ-VAE)
49
+ - Zhang & Sennrich 2019
50
+ """
51
+
52
+ def __init__(self, dim: int, eps: float = 1e-6):
53
+ super().__init__()
54
+ self.gamma = nn.Parameter(torch.ones(dim))
55
+ self.eps = eps
56
+
57
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
58
+ rms = torch.sqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps)
59
+ return self.gamma * x / rms
60
+
61
+
62
+ def apply_weightnorm(module: nn.Module) -> nn.Module:
63
+ """Aplica weight normalization (EnCodec-style) a um módulo Linear.
64
+
65
+ Salakhutdinov & Wang 2016: w = g * v / ||v||, onde g é escalar aprendido.
66
+
67
+ Vantagens:
68
+ - Normaliza apenas o peso, não a ativação
69
+ - Preserva estatística do input (importante para VQ-VAE)
70
+ - Usado em EnCodec (Défossez 2022) e SoundStream (Zeghidour 2021)
71
+ """
72
+ return nn.utils.weight_norm(module)
73
+
74
+
75
+ class HierarchicalVectorQuantizer(nn.Module):
76
+ """Quantizador hierárquico com 2 níveis (top + bottom) e técnicas anti-collapse.
77
+
78
+ Args:
79
+ num_codes_top: K_top (codebook de topo, captura estrutura global)
80
+ num_codes_bot: K_bot (codebook de base, captura detalhes)
81
+ code_dim: D (dimensão compartilhada)
82
+ beta: peso do commitment loss
83
+ ema_decay: γ para EMA (default 0.99)
84
+ dead_code_threshold: N_k abaixo do qual código é morto
85
+ dead_code_restart_every: a cada quantas épocas verificar
86
+ goose_temp_init: temperatura Goose inicial (default 2.0)
87
+ goose_temp_final: temperatura Goose final (default 0.5)
88
+ goose_schedule: 'cosine' ou 'linear'
89
+ total_epochs: total de épocas (para schedule)
90
+ """
91
+
92
+ def __init__(
93
+ self,
94
+ num_codes_top: int = 512,
95
+ num_codes_bot: int = 512,
96
+ code_dim: int = 32,
97
+ beta: float = 0.25,
98
+ ema_decay: float = 0.99,
99
+ dead_code_threshold: float = 1.0,
100
+ dead_code_restart_every: int = 3,
101
+ goose_temp_init: float = 2.0,
102
+ goose_temp_final: float = 0.5,
103
+ goose_schedule: str = "cosine",
104
+ total_epochs: int = 25,
105
+ norm_type: str = "none", # v12.8: "none" | "weightnorm" | "rmsnorm"
106
+ ):
107
+ super().__init__()
108
+ self.num_codes_top = num_codes_top
109
+ self.num_codes_bot = num_codes_bot
110
+ self.code_dim = code_dim
111
+ self.beta = beta
112
+ self.ema_decay = ema_decay
113
+ self.dead_code_threshold = dead_code_threshold
114
+ self.dead_code_restart_every = dead_code_restart_every
115
+ self.goose_temp_init = goose_temp_init
116
+ self.goose_temp_final = goose_temp_final
117
+ self.goose_schedule = goose_schedule
118
+ self.total_epochs = total_epochs
119
+ self.norm_type = norm_type # v12.8
120
+
121
+ # Codebooks (buffers, atualizados via EMA).
122
+ self.register_buffer('codebook_top', torch.randn(num_codes_top, code_dim) * 0.05)
123
+ self.register_buffer('codebook_bot', torch.randn(num_codes_bot, code_dim) * 0.05)
124
+ # EMA state para top.
125
+ self.register_buffer('ema_cluster_top', torch.zeros(num_codes_top))
126
+ self.register_buffer('ema_w_top', torch.zeros(num_codes_top, code_dim))
127
+ # EMA state para bottom.
128
+ self.register_buffer('ema_cluster_bot', torch.zeros(num_codes_bot))
129
+ self.register_buffer('ema_w_bot', torch.zeros(num_codes_bot, code_dim))
130
+
131
+ # v12.8: Normalização opcional dentro do VQ (substitui LayerNorm v12.7 que degradou).
132
+ # - "none": sem normalização (preserva estatística original — RECOMENDADO para VQ-VAE)
133
+ # - "weightnorm": weight normalization (EnCodec-style, preserva magnitude)
134
+ # - "rmsnorm": RMSNorm (preserva magnitude, mais barato que LayerNorm)
135
+ # Nota: LayerNorm v12.7 foi REMOVIDO pois degradou resultados (17× pior loss).
136
+ if norm_type == "rmsnorm":
137
+ # RMSNorm: y = x / sqrt(mean(x²) + eps) * gamma
138
+ self.rms_pre_top = RMSNorm(code_dim)
139
+ self.rms_pre_bot = RMSNorm(code_dim)
140
+ self.rms_post_combine = RMSNorm(code_dim)
141
+ else:
142
+ # "none" ou "weightnorm" (weightnorm é aplicado nos encoders, não aqui).
143
+ self.rms_pre_top = nn.Identity()
144
+ self.rms_pre_bot = nn.Identity()
145
+ self.rms_post_combine = nn.Identity()
146
+
147
+ # Contador de épocas.
148
+ self.register_buffer('epoch_counter', torch.zeros(1, dtype=torch.long))
149
+
150
+ # Estatísticas de uso.
151
+ self.register_buffer('usage_top', torch.zeros(num_codes_top))
152
+ self.register_buffer('usage_bot', torch.zeros(num_codes_bot))
153
+
154
+ # Temperatura Goose atual (atualizada via update_temperature).
155
+ self.register_buffer('current_temp', torch.tensor(goose_temp_init))
156
+
157
+ def update_temperature(self, grad_recon: float = None, grad_vq: float = None):
158
+ """Atualiza temperatura Goose baseada na época atual (schedule).
159
+
160
+ v13.9: Se grad_recon e grad_vq fornecidos, usa mas_weight adaptativo:
161
+ τ* = ||∇L_recon|| / ||∇L_vq||
162
+ Caso contrário, usa cosine decay padrão.
163
+ """
164
+ epoch = int(self.epoch_counter.item())
165
+ progress = min(epoch / max(self.total_epochs, 1), 1.0)
166
+
167
+ if grad_recon is not None and grad_vq is not None and grad_vq > 1e-8:
168
+ # v13.9: τ* adaptativo via mas_weight formula.
169
+ from .mathematical_optimizations import compute_goose_tau_adaptive
170
+ prev_tau = float(self.current_temp)
171
+ temp = compute_goose_tau_adaptive(grad_recon, grad_vq, prev_tau,
172
+ tau_min=self.goose_temp_final,
173
+ tau_max=self.goose_temp_init)
174
+ elif self.goose_schedule == "cosine":
175
+ temp = self.goose_temp_final + 0.5 * (self.goose_temp_init - self.goose_temp_final) * \
176
+ (1 + math.cos(math.pi * progress))
177
+ else: # linear
178
+ temp = self.goose_temp_init + (self.goose_temp_final - self.goose_temp_init) * progress
179
+ self.current_temp.fill_(temp)
180
+ return float(temp)
181
+
182
+ def _quantize_level(self, z: torch.Tensor, codebook: torch.Tensor,
183
+ ema_cluster: torch.Tensor, ema_w: torch.Tensor,
184
+ use_goose: bool = True) -> Tuple[torch.Tensor, torch.Tensor, int]:
185
+ """Quantiza um nível (top ou bottom) com EMA + Goose opcional."""
186
+ B, D = z.shape
187
+ # Distâncias.
188
+ dist = (
189
+ z.pow(2).sum(dim=1, keepdim=True)
190
+ + codebook.pow(2).sum(dim=1)
191
+ - 2 * z @ codebook.t()
192
+ ) # (B, K)
193
+
194
+ if use_goose and self.training:
195
+ # Goose VQ: Gumbel-softmax sampling.
196
+ logits = -dist / max(float(self.current_temp), 1e-6)
197
+ codes_soft = F.gumbel_softmax(logits, tau=float(self.current_temp), hard=True)
198
+ codes = codes_soft.argmax(dim=1)
199
+ z_q = codes_soft @ codebook
200
+ else:
201
+ # argmin (eval ou fallback).
202
+ codes = dist.argmin(dim=1)
203
+ z_q = codebook[codes]
204
+
205
+ # EMA update (apenas em treino).
206
+ n_restarted = 0
207
+ if self.training:
208
+ one_hot = F.one_hot(codes, codebook.size(0)).float()
209
+ new_cluster = one_hot.sum(dim=0)
210
+ # v13.3fix: Save OLD values before EMA update for cb_update computation
211
+ old_cluster = ema_cluster.clone()
212
+ old_w = ema_w.clone()
213
+ ema_cluster.mul_(self.ema_decay).add_(new_cluster, alpha=1 - self.ema_decay)
214
+ new_w = one_hot.t() @ z
215
+ ema_w.mul_(self.ema_decay).add_(new_w, alpha=1 - self.ema_decay)
216
+ # v13.3: Correções matemáticas no EMA (mal-conditioning do codebook).
217
+ # Use OLD (pre-update) values for cb_update, as required by proper EMA formula.
218
+ n_old = old_cluster.sum()
219
+ # 1. Smoothing do cluster size (reduz condition number).
220
+ cluster_mean = old_cluster.mean()
221
+ cluster_smoothed = 0.9 * old_cluster + 0.1 * cluster_mean
222
+ # 2. Clipping logarítmico do cluster size (comprime escala dinâmica).
223
+ eps_cb = 1e-5
224
+ cluster_clipped = torch.log1p(cluster_smoothed / eps_cb) / \
225
+ torch.log1p(cluster_smoothed.max() / eps_cb + 1e-12)
226
+ # 3. Renormalizar para magnitude original.
227
+ cluster_final = cluster_clipped * n_old / (cluster_clipped.sum() + 1e-12)
228
+ smoothed = (cluster_final + eps_cb) / (n_old + codebook.size(0) * eps_cb) * n_old
229
+ # v13.3: Clamp do codebook update para prevenir NaN/Inf.
230
+ # Use OLD ema_w (pre-update) for cb_update
231
+ cb_update = old_w / smoothed.unsqueeze(1)
232
+ cb_update = torch.clamp(cb_update, -1e4, 1e4)
233
+ codebook.copy_(cb_update)
234
+
235
+ # Dead code restart.
236
+ if (int(self.epoch_counter.item()) + 1) % self.dead_code_restart_every == 0:
237
+ dead_mask = ema_cluster < self.dead_code_threshold
238
+ n_dead = int(dead_mask.sum().item())
239
+ if n_dead > 0:
240
+ rand_idx = torch.randint(0, B, (n_dead,), device=z.device)
241
+ replacement = z[rand_idx]
242
+ codebook.data[dead_mask] = replacement.detach()
243
+ ema_cluster[dead_mask] = 1.0
244
+ ema_w[dead_mask] = replacement.detach()
245
+ n_restarted = n_dead
246
+ # v13.1: limpeza leve após dead code restart (libera tensores temporários).
247
+ import gc as _gc
248
+ _gc.collect(0)
249
+
250
+ return z_q, codes, n_restarted
251
+
252
+ def forward(self, z_e: torch.Tensor) -> Dict[str, torch.Tensor]:
253
+ """
254
+ z_e: (B, D) — saída contínua do encoder.
255
+
256
+ Retorna dict com:
257
+ z_q_top: (B, D) — vetores quantizados do nível top
258
+ z_q_bot: (B, D) — vetores quantizados do nível bottom (residual)
259
+ z_q_combined: (B, D) — z_q_top + z_q_bot (soma)
260
+ codes_top: (B,)
261
+ codes_bot: (B,)
262
+ loss: escalar (commitment top + bottom)
263
+ stats: dict com estatísticas
264
+ """
265
+ # v12.8: RMSNorm pré-top (preserva magnitude, mais estável que LayerNorm).
266
+ z_e_norm = self.rms_pre_top(z_e)
267
+
268
+ # Nível top: quantiza z_e (normalizado) diretamente.
269
+ z_q_top, codes_top, n_restart_top = self._quantize_level(
270
+ z_e_norm, self.codebook_top, self.ema_cluster_top, self.ema_w_top,
271
+ use_goose=True,
272
+ )
273
+
274
+ # Nível bottom: quantiza o RESÍDUO z_e - z_q_top.detach() (com RMSNorm).
275
+ residual = z_e - z_q_top.detach()
276
+ residual_norm = self.rms_pre_bot(residual)
277
+ z_q_bot, codes_bot, n_restart_bot = self._quantize_level(
278
+ residual_norm, self.codebook_bot, self.ema_cluster_bot, self.ema_w_bot,
279
+ use_goose=True,
280
+ )
281
+
282
+ # Commitment losses (computadas com z_e original, não normalizado).
283
+ commit_top = F.mse_loss(z_e, z_q_top.detach())
284
+ commit_bot = F.mse_loss(residual, z_q_bot.detach())
285
+ loss = self.beta * (commit_top + commit_bot)
286
+
287
+ # Straight-through.
288
+ z_q_top_st = z_e + (z_q_top - z_e).detach()
289
+ z_q_bot_st = residual + (z_q_bot - residual).detach()
290
+ z_q_combined = z_q_top_st + z_q_bot_st
291
+ # v12.8: RMSNorm pós-combinação (preserva magnitude, mais estável que LayerNorm).
292
+ z_q_combined = self.rms_post_combine(z_q_combined)
293
+
294
+ # Estatísticas.
295
+ with torch.no_grad():
296
+ self.usage_top.add_(torch.bincount(codes_top, minlength=self.num_codes_top).float())
297
+ self.usage_bot.add_(torch.bincount(codes_bot, minlength=self.num_codes_bot).float())
298
+ n_used_top = int((self.usage_top > 0).sum().item())
299
+ n_used_bot = int((self.usage_bot > 0).sum().item())
300
+
301
+ def _cb_ppl(codes, K):
302
+ if len(codes) == 0:
303
+ return 0.0
304
+ from collections import Counter
305
+ counter = Counter(codes.tolist())
306
+ probs = np.array([c / len(codes) for c in counter.values()])
307
+ entropy = -np.sum(probs * np.log(probs + 1e-12))
308
+ return float(math.exp(entropy)) if entropy > 0 else 0.0
309
+
310
+ cb_ppl_top = _cb_ppl(codes_top, self.num_codes_top)
311
+ cb_ppl_bot = _cb_ppl(codes_bot, self.num_codes_bot)
312
+
313
+ stats = {
314
+ 'n_used_top': n_used_top,
315
+ 'n_used_bot': n_used_bot,
316
+ 'n_dead_top': self.num_codes_top - n_used_top,
317
+ 'n_dead_bot': self.num_codes_bot - n_used_bot,
318
+ 'usage_ratio_top': n_used_top / self.num_codes_top,
319
+ 'usage_ratio_bot': n_used_bot / self.num_codes_bot,
320
+ 'codebook_ppl_top': cb_ppl_top,
321
+ 'codebook_ppl_bot': cb_ppl_bot,
322
+ 'n_restarted_top': n_restart_top,
323
+ 'n_restarted_bot': n_restart_bot,
324
+ 'goose_temp': float(self.current_temp),
325
+ }
326
+
327
+ return {
328
+ 'z_q_top': z_q_top_st,
329
+ 'z_q_bot': z_q_bot_st,
330
+ 'z_q_combined': z_q_combined,
331
+ 'codes_top': codes_top,
332
+ 'codes_bot': codes_bot,
333
+ 'loss': loss,
334
+ 'stats': stats,
335
+ }
336
+
337
+ def increment_epoch(self):
338
+ self.epoch_counter += 1
339
+ self.update_temperature()
340
+
341
+ def reset_usage_stats(self):
342
+ self.usage_top.zero_()
343
+ self.usage_bot.zero_()
344
+
345
+
346
+ class HierarchicalVQVAE2(nn.Module):
347
+ """VQ-VAE-2 completo com encoder/decoder hierárquico para múltiplas modalidades.
348
+
349
+ Arquitetura:
350
+ x → [Encoder shared] → z_e
351
+ → [Top VQ] → z_q_top (estrutura global)
352
+ → [Bot VQ] → z_q_bot (detalhes residuais)
353
+ → [Decoder shared] → x_recon
354
+ """
355
+
356
+ def __init__(
357
+ self,
358
+ modalities: Dict[str, int],
359
+ code_dim: int = 32,
360
+ num_codes_top: int = 512,
361
+ num_codes_bot: int = 512,
362
+ hidden: int = 128,
363
+ beta: float = 0.25,
364
+ ema_decay: float = 0.99,
365
+ dead_code_threshold: float = 1.0,
366
+ dead_code_restart_every: int = 3,
367
+ goose_temp_init: float = 2.0,
368
+ goose_temp_final: float = 0.5,
369
+ goose_schedule: str = "cosine",
370
+ total_epochs: int = 25,
371
+ norm_type: str = "none", # v12.8: "none" | "weightnorm" | "rmsnorm"
372
+ rmsnorm_in_vq: bool = False, # v12.8: RMSNorm dentro do VQ (default False)
373
+ ):
374
+ super().__init__()
375
+ self.modality_names = list(modalities.keys())
376
+ self.modality_dims = modalities
377
+ self.code_dim = code_dim
378
+ self.norm_type = norm_type # v12.8
379
+
380
+ # v12.8: Encoders e decoders por modalidade.
381
+ # - "none": LayerNorm interno dos MLPs (default, melhor validado em v12.7)
382
+ # - "weightnorm": aplica weight_norm nos Linear (EnCodec-style)
383
+ # - "rmsnorm": usa RMSNorm em vez de LayerNorm entre camadas MLP
384
+ def make_encoder(dim, hidden, code_dim, norm_type):
385
+ if norm_type == "weightnorm":
386
+ layers = [
387
+ nn.utils.weight_norm(nn.Linear(dim, hidden)), nn.GELU(),
388
+ nn.utils.weight_norm(nn.Linear(hidden, hidden // 2)), nn.GELU(),
389
+ nn.utils.weight_norm(nn.Linear(hidden // 2, code_dim)),
390
+ ]
391
+ elif norm_type == "rmsnorm":
392
+ layers = [
393
+ nn.Linear(dim, hidden), RMSNorm(hidden), nn.GELU(),
394
+ nn.Linear(hidden, hidden // 2), RMSNorm(hidden // 2), nn.GELU(),
395
+ nn.Linear(hidden // 2, code_dim),
396
+ ]
397
+ else: # "none" — usa LayerNorm interno (default, melhor validado)
398
+ layers = [
399
+ nn.Linear(dim, hidden), nn.LayerNorm(hidden), nn.GELU(),
400
+ nn.Linear(hidden, hidden // 2), nn.LayerNorm(hidden // 2), nn.GELU(),
401
+ nn.Linear(hidden // 2, code_dim),
402
+ ]
403
+ return nn.Sequential(*layers)
404
+
405
+ def make_decoder(code_dim, hidden, dim, norm_type):
406
+ if norm_type == "weightnorm":
407
+ layers = [
408
+ nn.utils.weight_norm(nn.Linear(code_dim, hidden // 2)), nn.GELU(),
409
+ nn.utils.weight_norm(nn.Linear(hidden // 2, hidden)), nn.GELU(),
410
+ nn.utils.weight_norm(nn.Linear(hidden, dim)),
411
+ ]
412
+ elif norm_type == "rmsnorm":
413
+ layers = [
414
+ nn.Linear(code_dim, hidden // 2), RMSNorm(hidden // 2), nn.GELU(),
415
+ nn.Linear(hidden // 2, hidden), RMSNorm(hidden), nn.GELU(),
416
+ nn.Linear(hidden, dim),
417
+ ]
418
+ else: # "none"
419
+ layers = [
420
+ nn.Linear(code_dim, hidden // 2), nn.LayerNorm(hidden // 2), nn.GELU(),
421
+ nn.Linear(hidden // 2, hidden), nn.LayerNorm(hidden), nn.GELU(),
422
+ nn.Linear(hidden, dim),
423
+ ]
424
+ return nn.Sequential(*layers)
425
+
426
+ self.encoders = nn.ModuleDict({
427
+ name: make_encoder(dim, hidden, code_dim, norm_type)
428
+ for name, dim in modalities.items()
429
+ })
430
+ self.decoders = nn.ModuleDict({
431
+ name: make_decoder(code_dim, hidden, dim, norm_type)
432
+ for name, dim in modalities.items()
433
+ })
434
+
435
+ # VQ hierárquico compartilhado entre todas as modalidades.
436
+ # v12.8: RMSNorm opcional dentro do VQ (substitui LayerNorm v12.7 que degradou).
437
+ vq_norm_type = "rmsnorm" if (rmsnorm_in_vq and norm_type == "rmsnorm") else "none"
438
+ self.vq = HierarchicalVectorQuantizer(
439
+ num_codes_top=num_codes_top,
440
+ num_codes_bot=num_codes_bot,
441
+ code_dim=code_dim,
442
+ beta=beta,
443
+ ema_decay=ema_decay,
444
+ dead_code_threshold=dead_code_threshold,
445
+ dead_code_restart_every=dead_code_restart_every,
446
+ goose_temp_init=goose_temp_init,
447
+ goose_temp_final=goose_temp_final,
448
+ goose_schedule=goose_schedule,
449
+ total_epochs=total_epochs,
450
+ norm_type=vq_norm_type,
451
+ )
452
+
453
+ def forward(self, batch: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
454
+ """batch: {modality_name: (B, input_dim)}."""
455
+ out = {'reconstructions': {}, 'codes_top': {}, 'codes_bot': {}, 'vq_loss': 0.0,
456
+ 'recon_loss': 0.0, 'stats': {}}
457
+ total_vq = 0.0
458
+ total_recon = 0.0
459
+ n = 0
460
+ all_codes_top = []
461
+ all_codes_bot = []
462
+ vq_out_first_stats = None # Capture stats from first VQ forward
463
+ for name, x in batch.items():
464
+ if name not in self.encoders:
465
+ continue
466
+ # v13.3: Sanitização de NaN/Inf no input (resolve bug identificado no teste adversarial).
467
+ x = torch.nan_to_num(x, nan=0.0, posinf=1e4, neginf=-1e4)
468
+ # v12.8: forward limpo (sem LayerNorms extras v12.7 que degradaram resultados).
469
+ # Encoder (com normalização interna configurável via norm_type).
470
+ z_e = self.encoders[name](x)
471
+ # v13.3: Sanitização após encoder (pode gerar NaN com inputs extremos).
472
+ z_e = torch.nan_to_num(z_e, nan=0.0, posinf=1e4, neginf=-1e4)
473
+ # VQ hierárquico (com RMSNorm opcional via rmsnorm_in_vq).
474
+ vq_out = self.vq(z_e)
475
+ # Capture stats from the first modality's VQ forward (no redundant second pass)
476
+ if vq_out_first_stats is None:
477
+ vq_out_first_stats = vq_out['stats']
478
+ z_q = vq_out['z_q_combined']
479
+ # v13.3: Sanitização após VQ (quantização pode produzir valores extremos).
480
+ z_q = torch.nan_to_num(z_q, nan=0.0, posinf=1e4, neginf=-1e4)
481
+ # Decoder (com normalização interna configurável via norm_type).
482
+ x_recon = self.decoders[name](z_q)
483
+ # v13.3: Sanitização final da reconstrução.
484
+ x_recon = torch.nan_to_num(x_recon, nan=0.0, posinf=1e4, neginf=-1e4)
485
+ recon_loss = F.mse_loss(x_recon, x)
486
+
487
+ out['reconstructions'][name] = x_recon
488
+ out['codes_top'][name] = vq_out['codes_top']
489
+ out['codes_bot'][name] = vq_out['codes_bot']
490
+ all_codes_top.append(vq_out['codes_top'])
491
+ all_codes_bot.append(vq_out['codes_bot'])
492
+ total_vq += vq_out['loss']
493
+ total_recon += recon_loss
494
+ n += 1
495
+
496
+ out['vq_loss'] = total_vq / max(n, 1)
497
+ out['recon_loss'] = total_recon / max(n, 1)
498
+ out['total_loss'] = out['vq_loss'] + out['recon_loss']
499
+ # Use stats already computed in the main loop — avoid redundant VQ forward
500
+ # that would sample different random codes and give inconsistent stats.
501
+ if vq_out_first_stats is not None:
502
+ out['stats'] = vq_out_first_stats
503
+ return out
504
+
505
+ def cross_modal_translate(
506
+ self, x: torch.Tensor, src: str, tgt: str
507
+ ) -> torch.Tensor:
508
+ """Traduz de uma modalidade para outra via codebook compartilhado."""
509
+ # v12.8: forward limpo (sem LayerNorms extras v12.7).
510
+ z_e = self.encoders[src](x)
511
+ vq_out = self.vq(z_e)
512
+ z_q = vq_out['z_q_combined']
513
+ return self.decoders[tgt](z_q)
src/bigru_t/quantization/smoothquant_compressor.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Xavante - smoothquant_compressor.py
3
+ Responsabilidade: Compressao W8A8 via SmoothQuant (Lema 4.1).
4
+ Integra a versao validada do FlexNet.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import logging
9
+
10
+ import torch
11
+ import torch.nn as nn
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ class SmoothQuantCompressor(nn.Module):
17
+ """
18
+ SmoothQuant (Xiao et al., 2022) migra a escala da ativacao para o peso,
19
+ permitindo quantizacao W8A8 sem perda significativa.
20
+
21
+ W_smooth = W * diag(s)
22
+ X_smooth = X * diag(s)^-1
23
+ s_j = max|X_j|^alpha / max|W_j|^(1-alpha), alpha=0.5 tipicamente.
24
+ """
25
+
26
+ def __init__(self, alpha: float = 0.5, n_bits: int = 8, calibration_samples: int = 128):
27
+ super().__init__()
28
+ self.alpha = alpha
29
+ self.n_bits = n_bits
30
+ self.calibration_samples = calibration_samples
31
+ self.register_buffer("smooth_scale", torch.ones(1))
32
+ self._calibrated = False
33
+
34
+ def calibrate(self, weight: torch.Tensor, activation_samples: torch.Tensor) -> None:
35
+ """
36
+ weight: [out, in]
37
+ activation_samples: [N, in] (diversas amostras reais)
38
+ """
39
+ with torch.no_grad():
40
+ # max abs por canal de entrada
41
+ w_max = weight.abs().amax(dim=0).clamp(min=1e-5) # [in]
42
+ x_max = activation_samples.abs().amax(dim=0).clamp(min=1e-5) # [in]
43
+ s = (x_max.pow(self.alpha) / w_max.pow(1 - self.alpha)).clamp(min=1e-5)
44
+ self.smooth_scale = s.to(weight.device, weight.dtype)
45
+ self._calibrated = True
46
+ logger.info("SmoothQuant calibrado: scale mean=%.4f, std=%.4f", s.mean().item(), s.std().item())
47
+
48
+ def smooth_weight(self, weight: torch.Tensor) -> torch.Tensor:
49
+ """Aplica W_smooth = W * diag(s) (multiplicacao por coluna)."""
50
+ if not self._calibrated:
51
+ return weight
52
+ return weight * self.smooth_scale.unsqueeze(0)
53
+
54
+ def smooth_activation(self, x: torch.Tensor) -> torch.Tensor:
55
+ """Aplica X_smooth = X / diag(s)."""
56
+ if not self._calibrated:
57
+ return x
58
+ return x / self.smooth_scale
59
+
60
+ def quantize_per_tensor_symmetric(self, t: torch.Tensor) -> torch.Tensor:
61
+ # Quantizacao simetrica per-tensor em n_bits
62
+ qmax = 2 ** (self.n_bits - 1) - 1
63
+ scale = t.abs().amax().clamp(min=1e-8) / qmax
64
+ q = torch.clamp((t / scale).round(), -qmax, qmax)
65
+ return q.to(torch.int8) if self.n_bits == 8 else q.to(torch.int16)
66
+
67
+ def fake_quantize(self, t: torch.Tensor) -> torch.Tensor:
68
+ """Quantizacao fake (diferenciavel via STE) para treino QAT."""
69
+ qmax = 2 ** (self.n_bits - 1) - 1
70
+ scale = t.abs().amax().clamp(min=1e-8) / qmax
71
+ q = torch.clamp((t / scale).round(), -qmax, qmax)
72
+ return q * scale # retorna em float para backward
73
+
74
+ def forward(self, weight: torch.Tensor, x: torch.Tensor, fake: bool = True) -> torch.Tensor:
75
+ w_s = self.smooth_weight(weight)
76
+ x_s = self.smooth_activation(x)
77
+ if fake:
78
+ w_q = self.fake_quantize(w_s)
79
+ x_q = self.fake_quantize(x_s)
80
+ else:
81
+ w_q = self.dequantize(self.quantize_per_tensor_symmetric(w_s), w_s)
82
+ x_q = self.dequantize(self.quantize_per_tensor_symmetric(x_s), x_s)
83
+ return torch.nn.functional.linear(x_q, w_q)
84
+
85
+ def dequantize(self, qt: torch.Tensor, ref: torch.Tensor) -> torch.Tensor:
86
+ qmax = 2 ** (self.n_bits - 1) - 1
87
+ scale = ref.abs().amax().clamp(min=1e-8) / qmax
88
+ return qt.to(ref.dtype) * scale
89
+
90
+
91
+ __all__ = ["SmoothQuantCompressor"]
src/bigru_t/reasoning/circular_orchestration.py ADDED
@@ -0,0 +1,837 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ circular_orchestration — Orquestração circular distribuída granulável.
3
+
4
+ Sistema de orquestração circular que resolve Tarefas decompostas em
5
+ subtarefas com Ações Monitoráveis (feedback) e Predição de Estado (Evolução).
6
+
7
+ Arquitetura circular
8
+ --------------------
9
+ Ao contrário do PEV linear (Plan→Evolve→Verify), a orquestração circular
10
+ é um loop contínuo onde cada agente pass a tarefa ao próximo, e o último
11
+ retorna ao primeiro, formando um anel:
12
+
13
+ Agent_0 → Agent_1 → ... → Agent_{N-1} → Agent_0 → ...
14
+
15
+ Cada agente executa uma fase (Decompose, Execute, Monitor, Predict, Adjust)
16
+ e passa o estado ao próximo. O loop continua até convergência.
17
+
18
+ Análise matemática profunda
19
+ ---------------------------
20
+ 1. Álgebra de estado (espaço de estados):
21
+ Estado do sistema: s_t = (task_state, agent_states, environment)
22
+ Transição: s_{t+1} = Φ(s_t, a_t, ω_t)
23
+ onde a_t é a ação tomada e ω_t é ruído/observação.
24
+
25
+ Φ é composição circular: Φ = φ_{N-1} ∘ ... ∘ φ_1 ∘ φ_0
26
+ onde φ_i é a função de transição do agente i.
27
+
28
+ 2. Predição de estado via Filtro de Kalman estendido:
29
+ x̂_{t+1|t} = f(x̂_t, u_t) (predição)
30
+ P_{t+1|t} = F_t P_t F_t^T + Q (covariância predita)
31
+ x̂_{t+1|t+1} = x̂_{t+1|t} + K_t(z_t - h(x̂_{t+1|t})) (correção)
32
+ P_{t+1|t+1} = (I - K_t H_t) P_{t+1|t} (covariância corrigida)
33
+
34
+ onde K_t = P_{t+1|t} H_t^T (H_t P_{t+1|t} H_t^T + R)^{-1} (ganho de Kalman)
35
+
36
+ 3. Estabilidade do anel circular:
37
+ Seja G_i a matriz Jacobiana do agente i. O anel é estável se:
38
+ ρ(G_{N-1} · ... · G_0) < 1
39
+ onde ρ(·) é o raio espectral.
40
+
41
+ 4. Teoria de controle circular:
42
+ Ação ótima via LQR circular:
43
+ J = Σ_t (x_t^T Q x_t + u_t^T R u_t)
44
+ u_t* = -K x_t onde K = R^{-1} B^T S
45
+ S resolve a equação de Riccati: S = Q + A^T S A - A^T S B (R + B^T S B)^{-1} B^T S A
46
+
47
+ 5. Convergência do anel:
48
+ Erro após k voltas: E_k = ||s_k - s*||
49
+ E_{k+1} ≤ ρ_prod · E_k + ε
50
+ onde ρ_prod = ∏_i ρ(G_i) é o produto dos raios espectrais.
51
+ Convergência garantida quando ρ_prod < 1.
52
+ """
53
+
54
+ from __future__ import annotations
55
+
56
+ import math
57
+ import time
58
+ import threading
59
+ from collections import deque, defaultdict
60
+ from concurrent.futures import Future, ThreadPoolExecutor, as_completed
61
+ from dataclasses import dataclass, field
62
+ from enum import Enum
63
+ from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
64
+
65
+ import numpy as np
66
+
67
+
68
+ # ============================================================================
69
+ # Exceções
70
+ # ============================================================================
71
+
72
+ class CircularOrchestrationError(RuntimeError):
73
+ """Erro na orquestração circular."""
74
+
75
+
76
+ class AgentStateError(RuntimeError):
77
+ """Erro de estado do agente."""
78
+
79
+
80
+ class PredictionError(RuntimeError):
81
+ """Erro na predição de estado."""
82
+
83
+
84
+ class RingInstabilityError(RuntimeError):
85
+ """Anel circular instável (raio espectral ≥ 1)."""
86
+
87
+
88
+ # ============================================================================
89
+ # Estruturas de dados
90
+ # ============================================================================
91
+
92
+ class AgentPhase(Enum):
93
+ """Fases do ciclo de orquestração circular."""
94
+ DECOMPOSE = "decompose" # Decompor tarefa em sub-tarefas
95
+ EXECUTE = "execute" # Executar sub-tarefas
96
+ MONITOR = "monitor" # Monitorar ações (feedback)
97
+ PREDICT = "predict" # Predizer próximo estado
98
+ ADJUST = "adjust" # Ajustar baseado em predição vs realidade
99
+
100
+
101
+ class TaskState(Enum):
102
+ """Estado da tarefa no ciclo."""
103
+ INITIALIZED = "initialized"
104
+ DECOMPOSED = "decomposed"
105
+ EXECUTING = "executing"
106
+ MONITORED = "monitored"
107
+ PREDICTED = "predicted"
108
+ ADJUSTED = "adjusted"
109
+ CONVERGED = "converged"
110
+ FAILED = "failed"
111
+
112
+
113
+ @dataclass
114
+ class MonitoredAction:
115
+ """Ação monitorável executada por um agente.
116
+
117
+ Contém:
118
+ - action_type: tipo da ação (decompose, execute, adjust, etc.)
119
+ - input: entrada da ação
120
+ - output: saída da ação
121
+ - feedback: feedback monitorado (score, erro, métricas)
122
+ - timestamp: quando foi executada
123
+ - agent_id: qual agente executou
124
+ """
125
+ action_type: str
126
+ input: Any = None
127
+ output: Any = None
128
+ feedback: Dict[str, Any] = field(default_factory=dict)
129
+ timestamp: float = field(default_factory=time.time)
130
+ agent_id: str = ""
131
+ # Feedback monitorado.
132
+ success: bool = True
133
+ error_magnitude: float = 0.0 # ||output - expected||
134
+ latency_ms: float = 0.0
135
+ resource_usage: Dict[str, float] = field(default_factory=dict)
136
+
137
+
138
+ @dataclass
139
+ class StatePrediction:
140
+ """Predição de estado do sistema.
141
+
142
+ Usa filtro de Kalman estendido para predizer próximo estado.
143
+ """
144
+ predicted_state: np.ndarray # x̂_{t+1|t}
145
+ predicted_covariance: np.ndarray # P_{t+1|t}
146
+ kalman_gain: np.ndarray # K_t
147
+ innovation: np.ndarray # z_t - h(x̂) (resíduo)
148
+ confidence: float # traço(P) / dim (incerteza média)
149
+ timestamp: float = field(default_factory=time.time)
150
+
151
+
152
+ @dataclass
153
+ class AgentState:
154
+ """Estado de um agente no anel circular.
155
+
156
+ Mantém:
157
+ - phase: fase atual (DECOMPOSE, EXECUTE, MONITOR, PREDICT, ADJUST)
158
+ - state_vector: vetor de estado (para filtro de Kalman)
159
+ - covariance: matriz de covariância do estado
160
+ - action_history: histórico de ações monitoradas
161
+ - predictions: histórico de predições
162
+ """
163
+ agent_id: str
164
+ phase: AgentPhase = AgentPhase.DECOMPOSE
165
+ state_vector: Optional[np.ndarray] = None # x_t
166
+ covariance: Optional[np.ndarray] = None # P_t
167
+ action_history: List[MonitoredAction] = field(default_factory=list)
168
+ predictions: List[StatePrediction] = field(default_factory=list)
169
+ # Estatísticas.
170
+ n_actions: int = 0
171
+ n_successes: int = 0
172
+ n_failures: int = 0
173
+ total_error: float = 0.0
174
+ avg_error: float = 0.0
175
+ # Jacobiano para análise de estabilidade.
176
+ jacobian: Optional[np.ndarray] = None # G_i
177
+
178
+
179
+ @dataclass
180
+ class CircularTask:
181
+ """Tarefa processada pelo anel circular.
182
+
183
+ Uma tarefa é decomposta em sub-tarefas, cada uma processada
184
+ por um agente no anel. O estado flui circularmente.
185
+ """
186
+ id: str
187
+ description: str
188
+ subtasks: List[Dict[str, Any]] = field(default_factory=list)
189
+ current_state: TaskState = TaskState.INITIALIZED
190
+ # Estado global do anel.
191
+ global_state: Optional[np.ndarray] = None
192
+ global_covariance: Optional[np.ndarray] = None
193
+ # Histórico de voltas (rounds) do anel.
194
+ round_history: List[Dict[str, Any]] = field(default_factory=list)
195
+ n_rounds: int = 0
196
+ converged: bool = False
197
+ convergence_score: float = 0.0
198
+
199
+
200
+ # ============================================================================
201
+ # 1. KalmanPredictor — predição de estado via filtro de Kalman
202
+ # ============================================================================
203
+
204
+ class KalmanPredictor:
205
+ """Filtro de Kalman estendido para predição de estado do anel.
206
+
207
+ Modelo:
208
+ x_{t+1} = f(x_t, u_t) + w_t (estado)
209
+ z_t = h(x_t) + v_t (observação)
210
+
211
+ Predição:
212
+ x̂_{t+1|t} = f(x̂_t, u_t)
213
+ P_{t+1|t} = F_t P_t F_t^T + Q
214
+
215
+ Correção:
216
+ K_t = P_{t+1|t} H_t^T (H_t P_{t+1|t} H_t^T + R)^{-1}
217
+ x̂_{t+1|t+1} = x̂_{t+1|t} + K_t (z_t - h(x̂_{t+1|t}))
218
+ P_{t+1|t+1} = (I - K_t H_t) P_{t+1|t}
219
+
220
+ onde:
221
+ F_t = ∂f/∂x |_{x̂_t} (Jacobiano da dinâmica)
222
+ H_t = ∂h/∂x |_{x̂_{t+1|t}} (Jacobiano da observação)
223
+ Q = covariância do ruído do processo
224
+ R = covariância do ruído de observação
225
+ """
226
+
227
+ def __init__(
228
+ self,
229
+ state_dim: int,
230
+ process_noise: float = 0.01,
231
+ measurement_noise: float = 0.1,
232
+ verbose: bool = False,
233
+ ):
234
+ self.state_dim = state_dim
235
+ self.Q = np.eye(state_dim) * process_noise # ruído do processo
236
+ self.R = np.eye(state_dim) * measurement_noise # ruído de medição
237
+ self.verbose = verbose
238
+
239
+ def predict(
240
+ self,
241
+ state: np.ndarray,
242
+ covariance: np.ndarray,
243
+ control_input: Optional[np.ndarray] = None,
244
+ transition_fn: Optional[Callable] = None,
245
+ ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
246
+ """Prediz próximo estado.
247
+
248
+ x̂_{t+1|t} = f(x̂_t, u_t)
249
+ P_{t+1|t} = F_t P_t F_t^T + Q
250
+
251
+ Args:
252
+ state: estado atual x̂_t (state_dim,)
253
+ covariance: covariância P_t (state_dim, state_dim)
254
+ control_input: entrada de controle u_t
255
+ transition_fn: função f(x, u) → x' (default: identidade)
256
+
257
+ Retorna: (predicted_state, predicted_covariance, F_jacobian)
258
+ """
259
+ if transition_fn is None:
260
+ transition_fn = lambda x, u: x # identidade
261
+
262
+ # Prediz estado.
263
+ predicted_state = transition_fn(state, control_input)
264
+
265
+ # Jacobiano F_t = ∂f/∂x (aproximação numérica).
266
+ F = self._numerical_jacobian(transition_fn, state, control_input)
267
+
268
+ # Prediz covariância: P_{t+1|t} = F P F^T + Q
269
+ predicted_cov = F @ covariance @ F.T + self.Q
270
+
271
+ if self.verbose:
272
+ print(f" Kalman predict: x̂={predicted_state[:3]}..., "
273
+ f"tr(P)={np.trace(predicted_cov):.4f}")
274
+
275
+ return predicted_state, predicted_cov, F
276
+
277
+ def correct(
278
+ self,
279
+ predicted_state: np.ndarray,
280
+ predicted_cov: np.ndarray,
281
+ observation: np.ndarray,
282
+ measurement_fn: Optional[Callable] = None,
283
+ ) -> Tuple[np.ndarray, np.ndarray, StatePrediction]:
284
+ """Corrige predição com observação.
285
+
286
+ K_t = P H^T (H P H^T + R)^{-1}
287
+ x̂ = x̂_pred + K (z - h(x̂_pred))
288
+ P = (I - K H) P_pred
289
+
290
+ Args:
291
+ predicted_state: x̂_{t+1|t}
292
+ predicted_cov: P_{t+1|t}
293
+ observation: z_t (medição real)
294
+ measurement_fn: função h(x) → z (default: identidade)
295
+
296
+ Retorna: (corrected_state, corrected_cov, StatePrediction)
297
+ """
298
+ if measurement_fn is None:
299
+ measurement_fn = lambda x: x # identidade
300
+
301
+ # Jacobiano H_t.
302
+ H = self._numerical_jacobian(measurement_fn, predicted_state, None)
303
+
304
+ # Ganho de Kalman: K = P H^T (H P H^T + R)^{-1}
305
+ S = H @ predicted_cov @ H.T + self.R
306
+ try:
307
+ K = predicted_cov @ H.T @ np.linalg.inv(S)
308
+ except np.linalg.LinAlgError:
309
+ K = predicted_cov @ H.T @ np.linalg.pinv(S)
310
+
311
+ # Inovação (resíduo): y = z - h(x̂_pred)
312
+ predicted_obs = measurement_fn(predicted_state)
313
+ innovation = observation - predicted_obs
314
+
315
+ # Correção: x̂ = x̂_pred + K * y
316
+ corrected_state = predicted_state + K @ innovation
317
+
318
+ # Covariância corrigida: P = (I - K H) P_pred
319
+ I = np.eye(self.state_dim)
320
+ corrected_cov = (I - K @ H) @ predicted_cov
321
+
322
+ # Confiança: traço(P) / dim (menor = mais confiante).
323
+ confidence = 1.0 - min(np.trace(corrected_cov) / self.state_dim, 1.0)
324
+
325
+ prediction = StatePrediction(
326
+ predicted_state=predicted_state,
327
+ predicted_covariance=predicted_cov,
328
+ kalman_gain=K,
329
+ innovation=innovation,
330
+ confidence=float(confidence),
331
+ )
332
+
333
+ if self.verbose:
334
+ print(f" Kalman correct: innovation={innovation[:3]}..., "
335
+ f"confidence={confidence:.4f}")
336
+
337
+ return corrected_state, corrected_cov, prediction
338
+
339
+ def _numerical_jacobian(
340
+ self,
341
+ fn: Callable,
342
+ x: np.ndarray,
343
+ u: Optional[np.ndarray],
344
+ eps: float = 1e-5,
345
+ ) -> np.ndarray:
346
+ """Computa Jacobiano numericamente via diferenças finitas.
347
+
348
+ F_ij = ∂f_i/∂x_j ≈ (f(x + ε·e_j, u) - f(x, u)) / ε
349
+ """
350
+ n = len(x)
351
+ J = np.zeros((n, n))
352
+ # Chama fn com tratamento uniforme de argumentos.
353
+ def call(x_val):
354
+ if u is not None:
355
+ return fn(x_val, u)
356
+ try:
357
+ return fn(x_val)
358
+ except TypeError:
359
+ return fn(x_val, None)
360
+ f0 = call(x)
361
+ for j in range(n):
362
+ x_plus = x.copy()
363
+ x_plus[j] += eps
364
+ f_plus = call(x_plus)
365
+ J[:, j] = (f_plus - f0) / eps
366
+ return J
367
+
368
+
369
+ # ============================================================================
370
+ # 2. CircularAgent — agente no anel de orquestração
371
+ # ============================================================================
372
+
373
+ class CircularAgent:
374
+ """Agente no anel de orquestração circular.
375
+
376
+ Cada agente:
377
+ 1. Recebe estado do agente anterior
378
+ 2. Executa sua fase (DECOMPOSE, EXECUTE, MONITOR, PREDICT, ADJUST)
379
+ 3. Monitora a ação (feedback)
380
+ 4. Prediz próximo estado (Kalman)
381
+ 5. Passa estado ao próximo agente
382
+
383
+ O agente mantém:
384
+ - Estado interno (vetor + covariância)
385
+ - Histórico de ações monitoradas
386
+ - Predições de estado
387
+ - Jacobiano (para análise de estabilidade do anel)
388
+ """
389
+
390
+ def __init__(
391
+ self,
392
+ agent_id: str,
393
+ phase: AgentPhase,
394
+ execute_fn: Callable[[Any, AgentState], Any],
395
+ state_dim: int = 4,
396
+ kalman_predictor: Optional[KalmanPredictor] = None,
397
+ verbose: bool = False,
398
+ ):
399
+ self.agent_id = agent_id
400
+ self.phase = phase
401
+ self.execute_fn = execute_fn
402
+ self.state_dim = state_dim
403
+ self.kalman = kalman_predictor or KalmanPredictor(state_dim, verbose=verbose)
404
+ self.verbose = verbose
405
+ # Estado interno.
406
+ self.state = AgentState(
407
+ agent_id=agent_id,
408
+ phase=phase,
409
+ state_vector=np.zeros(state_dim),
410
+ covariance=np.eye(state_dim) * 0.1,
411
+ )
412
+
413
+ def process(
414
+ self,
415
+ input_data: Any,
416
+ task: CircularTask,
417
+ ) -> Tuple[Any, MonitoredAction, Optional[StatePrediction]]:
418
+ """Processa input na fase do agente.
419
+
420
+ 1. Executa ação (execute_fn)
421
+ 2. Monitora ação (feedback)
422
+ 3. Prediz próximo estado (Kalman)
423
+ 4. Atualiza estado interno
424
+
425
+ Retorna: (output, monitored_action, prediction)
426
+ """
427
+ t0 = time.time()
428
+ self.state.n_actions += 1
429
+ # 1. Executa ação.
430
+ try:
431
+ output = self.execute_fn(input_data, self.state)
432
+ success = True
433
+ error_mag = 0.0
434
+ except Exception as e:
435
+ output = None
436
+ success = False
437
+ error_mag = 1.0
438
+ if self.verbose:
439
+ print(f" Agent {self.agent_id}: FALHOU: {e}")
440
+ latency = (time.time() - t0) * 1000
441
+ # 2. Monitora ação (feedback).
442
+ action = MonitoredAction(
443
+ action_type=self.phase.value,
444
+ input=input_data,
445
+ output=output,
446
+ agent_id=self.agent_id,
447
+ success=success,
448
+ error_magnitude=error_mag,
449
+ latency_ms=latency,
450
+ feedback={
451
+ "task_id": task.id,
452
+ "round": task.n_rounds,
453
+ "phase": self.phase.value,
454
+ },
455
+ )
456
+ self.state.action_history.append(action)
457
+ if success:
458
+ self.state.n_successes += 1
459
+ else:
460
+ self.state.n_failures += 1
461
+ self.state.total_error += error_mag
462
+ self.state.avg_error = self.state.total_error / self.state.n_actions
463
+ # 3. Prediz próximo estado (Kalman).
464
+ prediction = None
465
+ if success and output is not None:
466
+ # Converte output para vetor de estado.
467
+ obs = self._extract_state_vector(output, task)
468
+ # Prediz.
469
+ pred_state, pred_cov, F = self.kalman.predict(
470
+ self.state.state_vector,
471
+ self.state.covariance,
472
+ control_input=obs,
473
+ )
474
+ # Corrige com observação.
475
+ corr_state, corr_cov, prediction = self.kalman.correct(
476
+ pred_state, pred_cov, obs,
477
+ )
478
+ # Atualiza estado.
479
+ self.state.state_vector = corr_state
480
+ self.state.covariance = corr_cov
481
+ self.state.jacobian = F # para análise de estabilidade
482
+ self.state.predictions.append(prediction)
483
+ # 4. Atualiza estado da tarefa.
484
+ task.current_state = self._next_task_state(task.current_state)
485
+ if self.verbose:
486
+ print(f" Agent {self.agent_id} ({self.phase.value}): "
487
+ f"success={success}, latency={latency:.1f}ms, "
488
+ f"error={error_mag:.4f}")
489
+ return output, action, prediction
490
+
491
+ def _extract_state_vector(self, output: Any, task: CircularTask) -> np.ndarray:
492
+ """Extrai vetor de estado do output da ação."""
493
+ if isinstance(output, (int, float)):
494
+ return np.array([float(output)] + [0.0] * (self.state_dim - 1))
495
+ if isinstance(output, (list, tuple)):
496
+ vals = list(output)[:self.state_dim]
497
+ while len(vals) < self.state_dim:
498
+ vals.append(0.0)
499
+ return np.array(vals, dtype=float)
500
+ if isinstance(output, dict):
501
+ # Usa valores numéricos do dict.
502
+ vals = [float(v) for v in output.values() if isinstance(v, (int, float))][:self.state_dim]
503
+ while len(vals) < self.state_dim:
504
+ vals.append(0.0)
505
+ return np.array(vals)
506
+ if isinstance(output, str):
507
+ # Hash → vetor.
508
+ h = hash(output) % (10 ** self.state_dim)
509
+ return np.array([float(h // (10**i) % 10) / 10 for i in range(self.state_dim)])
510
+ return np.zeros(self.state_dim)
511
+
512
+ def _next_task_state(self, current: TaskState) -> TaskState:
513
+ """Transição de estado da tarefa baseado na fase do agente."""
514
+ transitions = {
515
+ (TaskState.INITIALIZED, AgentPhase.DECOMPOSE): TaskState.DECOMPOSED,
516
+ (TaskState.DECOMPOSED, AgentPhase.EXECUTE): TaskState.EXECUTING,
517
+ (TaskState.EXECUTING, AgentPhase.MONITOR): TaskState.MONITORED,
518
+ (TaskState.MONITORED, AgentPhase.PREDICT): TaskState.PREDICTED,
519
+ (TaskState.PREDICTED, AgentPhase.ADJUST): TaskState.ADJUSTED,
520
+ (TaskState.ADJUSTED, AgentPhase.DECOMPOSE): TaskState.DECOMPOSED,
521
+ }
522
+ return transitions.get((current, self.phase), current)
523
+
524
+ def get_spectral_radius(self) -> float:
525
+ """Raio espectral do Jacobiano (para análise de estabilidade)."""
526
+ if self.state.jacobian is None:
527
+ return 0.0
528
+ eigenvalues = np.linalg.eigvals(self.state.jacobian)
529
+ return float(max(abs(eigenvalues)))
530
+
531
+ def get_stats(self) -> Dict[str, Any]:
532
+ return {
533
+ "agent_id": self.agent_id,
534
+ "phase": self.phase.value,
535
+ "n_actions": self.state.n_actions,
536
+ "n_successes": self.state.n_successes,
537
+ "n_failures": self.state.n_failures,
538
+ "avg_error": self.state.avg_error,
539
+ "spectral_radius": self.get_spectral_radius(),
540
+ "state_confidence": (
541
+ 1.0 - min(np.trace(self.state.covariance) / self.state_dim, 1.0)
542
+ if self.state.covariance is not None else 0.0
543
+ ),
544
+ "n_predictions": len(self.state.predictions),
545
+ }
546
+
547
+
548
+ # ============================================================================
549
+ # 3. CircularOrchestrator — orquestração circular distribuída
550
+ # ============================================================================
551
+
552
+ class CircularOrchestrator:
553
+ """Orquestração circular distribuída granulável.
554
+
555
+ Arquitetura: N agentes em anel, cada um com uma fase diferente.
556
+ O estado flui circularmente: Agent_0 → Agent_1 → ... → Agent_{N-1} → Agent_0
557
+
558
+ Cada volta (round) do anel executa o ciclo completo:
559
+ DECOMPOSE → EXECUTE → MONITOR → PREDICT → ADJUST → (volta a DECOMPOSE)
560
+
561
+ Análise de estabilidade:
562
+ ρ_prod = ∏_i ρ(G_i) < 1 (produto dos raios espectrais)
563
+ Garante convergência do anel.
564
+
565
+ Análise de convergência:
566
+ E_{k+1} ≤ ρ_prod · E_k + ε
567
+ k_max = ceil(log((E_0 - ε/(1-ρ_prod)) / (threshold - ε/(1-ρ_prod))) / log(ρ_prod))
568
+
569
+ Uso:
570
+ >>> orch = CircularOrchestrator(n_agents=5, state_dim=4)
571
+ >>> solution = orch.solve(task, executor_fns=[...])
572
+ """
573
+
574
+ def __init__(
575
+ self,
576
+ n_agents: int = 5,
577
+ state_dim: int = 4,
578
+ max_rounds: int = 10,
579
+ convergence_threshold: float = 0.9,
580
+ process_noise: float = 0.01,
581
+ measurement_noise: float = 0.1,
582
+ parallel: bool = False, # Se True, fases independentes rodam em paralelo
583
+ verbose: bool = False,
584
+ ):
585
+ self.n_agents = n_agents
586
+ self.state_dim = state_dim
587
+ self.max_rounds = max_rounds
588
+ self.convergence_threshold = convergence_threshold
589
+ self.parallel = parallel
590
+ self.verbose = verbose
591
+ # Kalman compartilhado.
592
+ self.kalman = KalmanPredictor(
593
+ state_dim=state_dim,
594
+ process_noise=process_noise,
595
+ measurement_noise=measurement_noise,
596
+ verbose=verbose,
597
+ )
598
+ # Agentes (serão criados em solve).
599
+ self.agents: List[CircularAgent] = []
600
+ # Estatísticas.
601
+ self.round_history: List[Dict[str, Any]] = []
602
+ self.error_trajectory: List[float] = []
603
+
604
+ def solve(
605
+ self,
606
+ task: CircularTask,
607
+ executor_fns: List[Callable[[Any, AgentState], Any]],
608
+ ) -> CircularTask:
609
+ """Resolve tarefa via orquestração circular.
610
+
611
+ Args:
612
+ task: tarefa a resolver
613
+ executor_fns: lista de funções executoras (1 por agente)
614
+
615
+ Retorna: task atualizada com resultado e estado final.
616
+ """
617
+ assert len(executor_fns) == self.n_agents, \
618
+ f"Esperado {self.n_agents} executores, recebido {len(executor_fns)}"
619
+ # Cria agentes (um por fase).
620
+ phases = list(AgentPhase)
621
+ # Se n_agents > len(phases), repete fases.
622
+ while len(phases) < self.n_agents:
623
+ phases.extend(AgentPhase)
624
+ self.agents = [
625
+ CircularAgent(
626
+ agent_id=f"agent_{i}",
627
+ phase=phases[i % len(AgentPhase)],
628
+ execute_fn=executor_fns[i],
629
+ state_dim=self.state_dim,
630
+ kalman_predictor=self.kalman,
631
+ verbose=self.verbose,
632
+ )
633
+ for i in range(self.n_agents)
634
+ ]
635
+ # Inicializa estado global.
636
+ task.global_state = np.zeros(self.state_dim)
637
+ task.global_covariance = np.eye(self.state_dim) * 0.1
638
+ if self.verbose:
639
+ print(f"\n{'='*60}")
640
+ print(f"CircularOrchestrator: {self.n_agents} agentes, "
641
+ f"max_rounds={self.max_rounds}")
642
+ print(f"Anel: {' → '.join(a.agent_id for a in self.agents)} → {self.agents[0].agent_id}")
643
+ print(f"{'='*60}")
644
+ # Loop circular.
645
+ current_data: Any = task.description # input inicial
646
+ for round_num in range(1, self.max_rounds + 1):
647
+ task.n_rounds = round_num
648
+ round_actions: List[MonitoredAction] = []
649
+ round_predictions: List[StatePrediction] = []
650
+ if self.verbose:
651
+ print(f"\n--- Round {round_num}/{self.max_rounds} ---")
652
+ # Cada agente processa em sequência (anel).
653
+ for agent in self.agents:
654
+ output, action, prediction = agent.process(current_data, task)
655
+ round_actions.append(action)
656
+ if prediction is not None:
657
+ round_predictions.append(prediction)
658
+ # Passa output ao próximo agente.
659
+ current_data = output if output is not None else current_data
660
+ # Analisa estabilidade do anel.
661
+ spectral_radii = [a.get_spectral_radius() for a in self.agents]
662
+ rho_prod = 1.0
663
+ for rho in spectral_radii:
664
+ rho_prod *= max(rho, 0.01) # evita zero
665
+ # Computa score de convergência.
666
+ n_success = sum(1 for a in round_actions if a.success)
667
+ success_rate = n_success / len(round_actions)
668
+ avg_error = np.mean([a.error_magnitude for a in round_actions])
669
+ # Score combina success_rate e (1 - avg_error).
670
+ conv_score = success_rate * (1.0 - avg_error)
671
+ # Confiança média das predições.
672
+ avg_confidence = (
673
+ np.mean([p.confidence for p in round_predictions])
674
+ if round_predictions else 0.5
675
+ )
676
+ # Score final pondera convergência e confiança.
677
+ final_score = 0.7 * conv_score + 0.3 * avg_confidence
678
+ task.convergence_score = final_score
679
+ # Registra round.
680
+ round_info = {
681
+ "round": round_num,
682
+ "n_actions": len(round_actions),
683
+ "n_success": n_success,
684
+ "success_rate": success_rate,
685
+ "avg_error": avg_error,
686
+ "avg_confidence": avg_confidence,
687
+ "convergence_score": final_score,
688
+ "spectral_radii": spectral_radii,
689
+ "rho_product": rho_prod,
690
+ "stable": rho_prod < 1.0,
691
+ }
692
+ task.round_history.append(round_info)
693
+ self.round_history.append(round_info)
694
+ self.error_trajectory.append(1.0 - final_score)
695
+ if self.verbose:
696
+ print(f" Score: {final_score:.4f}, "
697
+ f"ρ_prod: {rho_prod:.4f}, "
698
+ f"stable: {rho_prod < 1.0}")
699
+ # Verifica convergência.
700
+ if final_score >= self.convergence_threshold:
701
+ task.converged = True
702
+ task.current_state = TaskState.CONVERGED
703
+ if self.verbose:
704
+ print(f" ✓ Convergiu em {round_num} voltas!")
705
+ break
706
+ # Verifica instabilidade.
707
+ if rho_prod >= 1.0 and round_num > 2:
708
+ if self.verbose:
709
+ print(f" ⚠ Anel instável (ρ_prod={rho_prod:.4f} ≥ 1)")
710
+ # Não aborta, mas avisa.
711
+ if not task.converged:
712
+ if self.verbose:
713
+ print(f"\n ✗ Não convergiu após {self.max_rounds} voltas")
714
+ return task
715
+
716
+ def analyze_stability(self) -> Dict[str, Any]:
717
+ """Analisa estabilidade do anel circular.
718
+
719
+ ρ_prod = ∏_i ρ(G_i) < 1 → estável
720
+ """
721
+ if not self.agents:
722
+ return {"stable": True, "reason": "sem agentes"}
723
+ spectral_radii = [a.get_spectral_radius() for a in self.agents]
724
+ rho_prod = 1.0
725
+ for rho in spectral_radii:
726
+ rho_prod *= max(rho, 0.01)
727
+ return {
728
+ "n_agents": len(self.agents),
729
+ "spectral_radii": spectral_radii,
730
+ "rho_product": rho_prod,
731
+ "stable": rho_prod < 1.0,
732
+ "margin": 1.0 - rho_prod, # margem de estabilidade
733
+ "agent_stats": [a.get_stats() for a in self.agents],
734
+ }
735
+
736
+ def analyze_convergence(self) -> Dict[str, Any]:
737
+ """Analisa convergência do anel.
738
+
739
+ E_{k+1} ≤ ρ_prod · E_k + ε
740
+ """
741
+ if not self.error_trajectory:
742
+ return {"converged": False, "reason": "sem dados"}
743
+ from .distributed_reasoning_system import analyze_convergence as _analyze
744
+ stability = self.analyze_stability()
745
+ rho = stability.get("rho_product", 0.5)
746
+ return _analyze(self.error_trajectory, rho=rho, epsilon=0.01)
747
+
748
+ def get_all_stats(self) -> Dict[str, Any]:
749
+ return {
750
+ "n_rounds": len(self.round_history),
751
+ "agents": [a.get_stats() for a in self.agents],
752
+ "stability": self.analyze_stability(),
753
+ "convergence": self.analyze_convergence(),
754
+ "error_trajectory": self.error_trajectory,
755
+ }
756
+
757
+ def summary(self) -> str:
758
+ lines = [
759
+ f"CircularOrchestrator ({self.n_agents} agentes):",
760
+ f" Rounds: {len(self.round_history)}",
761
+ f" Estabilidade: {self.analyze_stability()['stable']}",
762
+ ]
763
+ for a in self.agents:
764
+ s = a.get_stats()
765
+ lines.append(
766
+ f" {s['agent_id']} ({s['phase']}): "
767
+ f"actions={s['n_actions']}, "
768
+ f"success={s['n_successes']}, "
769
+ f"ρ={s['spectral_radius']:.4f}, "
770
+ f"conf={s['state_confidence']:.4f}"
771
+ )
772
+ return "\n".join(lines)
773
+
774
+
775
+ # ============================================================================
776
+ # 4. Análise matemática
777
+ # ============================================================================
778
+
779
+ def analyze_ring_stability(
780
+ jacobians: List[np.ndarray],
781
+ ) -> Dict[str, Any]:
782
+ """Analisa estabilidade do anel circular.
783
+
784
+ ρ_prod = ρ(G_{N-1} · ... · G_0) < 1 → estável
785
+
786
+ Args:
787
+ jacobians: lista de matrizes Jacobianas [G_0, G_1, ..., G_{N-1}]
788
+
789
+ Retorna: análise de estabilidade
790
+ """
791
+ if not jacobians:
792
+ return {"stable": True, "rho_product": 0.0}
793
+ # Produto dos Jacobianos.
794
+ product = np.eye(jacobians[0].shape[0])
795
+ for J in jacobians:
796
+ product = J @ product
797
+ # Raio espectral do produto.
798
+ eigenvalues = np.linalg.eigvals(product)
799
+ rho_product = float(max(abs(eigenvalues)))
800
+ # Raios espectrais individuais.
801
+ individual_radii = [float(max(abs(np.linalg.eigvals(J)))) for J in jacobians]
802
+ return {
803
+ "n_agents": len(jacobians),
804
+ "individual_spectral_radii": individual_radii,
805
+ "rho_product": rho_product,
806
+ "stable": rho_product < 1.0,
807
+ "margin": 1.0 - rho_product,
808
+ "eigenvalues": [complex(ev) for ev in eigenvalues],
809
+ }
810
+
811
+
812
+ def compute_optimal_ring_size(
813
+ task_complexity: float,
814
+ agent_overhead: float = 0.1,
815
+ coordination_cost: float = 0.05,
816
+ ) -> Dict[str, Any]:
817
+ """Computa tamanho ótimo do anel (número de agentes).
818
+
819
+ Análise: T(n) = C/n + α·n + β
820
+ n* = sqrt(C / α)
821
+ Speedup: S(n) = C / T(n)
822
+ """
823
+ n_star = math.sqrt(task_complexity / max(agent_overhead, 1e-8))
824
+ n_star_int = max(2, min(20, int(round(n_star))))
825
+ t_seq = task_complexity
826
+ t_par = task_complexity / n_star_int + agent_overhead * n_star_int + coordination_cost
827
+ speedup = t_seq / max(t_par, 1e-8)
828
+ return {
829
+ "task_complexity": task_complexity,
830
+ "agent_overhead": agent_overhead,
831
+ "coordination_cost": coordination_cost,
832
+ "n_star_theoretical": n_star,
833
+ "n_star_empirical": n_star_int,
834
+ "speedup": speedup,
835
+ "t_sequential": t_seq,
836
+ "t_parallel": t_par,
837
+ }
src/bigru_t/reasoning/consensus_sampling.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """consensus_sampling.py — Consenso via amostragem (Chernoff) (V11.23)."""
2
+ from __future__ import annotations
3
+ import torch
4
+ from collections import Counter
5
+
6
+ class ConsensusSampling:
7
+ def __init__(self, M=10, temperature=0.8):
8
+ self.M=M; self.temperature=temperature
9
+ def sample(self, model, input_ids, max_new_tokens=30):
10
+ outputs=[]
11
+ model.eval()
12
+ for _ in range(self.M):
13
+ with torch.no_grad():
14
+ gen=model.generate(input_ids, max_new_tokens=max_new_tokens, temperature=self.temperature)
15
+ outputs.append(gen)
16
+ return outputs
17
+ def vote(self, outputs, tokenizer=None):
18
+ if tokenizer:
19
+ texts=[tokenizer.decode(o) for o in outputs]
20
+ else:
21
+ texts=[str(o) for o in outputs]
22
+ counter=Counter(texts)
23
+ consensus, count=counter.most_common(1)[0]
24
+ confidence=count/len(texts)
25
+ return consensus
26
+ def get_consensus(self, model, input_ids, tokenizer=None, max_new_tokens=30):
27
+ outputs=self.sample(model, input_ids, max_new_tokens)
28
+ consensus=self.vote(outputs, tokenizer)
29
+ texts=[tokenizer.decode(o) if tokenizer else str(o) for o in outputs]
30
+ return {"consensus": consensus, "confidence": confidence, "n_samples": self.M, "texts": texts}
src/bigru_t/reasoning/cyclic_reasoning.py ADDED
@@ -0,0 +1,570 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ cyclic_reasoning — Mecanismo de raciocínio cíclico melhorado.
3
+
4
+ Baseado no código GLMCyclicMultimodalAgent fornecido, com as seguintes melhorias:
5
+
6
+ 1. CyclicStateController com Kalman filter + fixed-point convergence
7
+ 2. CyclicMemoryManager com compressão atencional para 2M tokens
8
+ 3. GLMCyclicMultimodalAgent integrando LLM + memória + controller + tool agent
9
+ 4. Detecção de falhas: não-convergência, overflow, ciclos oscilantes
10
+
11
+ Melhorias sobre o código original:
12
+ - Convergence check robusto (norma relativa, não absoluta)
13
+ - Max cycle limit com fallback graceful
14
+ - Memory compression com attention real (não apenas mean pooling)
15
+ - State controller com GRUCell + Kalman gain aprendido
16
+ - Tool action learning via gradient (não random walk)
17
+ - Detecção de oscilação (estado divergente)
18
+ - Logging estruturado para análise pós-treino
19
+ """
20
+
21
+ from __future__ import annotations
22
+ from dataclasses import dataclass, field
23
+ from typing import Dict, List, Optional, Tuple, Any
24
+
25
+ import torch
26
+ import torch.nn as nn
27
+ import torch.nn.functional as F
28
+
29
+ # v12.9: RMSNorm importado do vqvae2_hierarchical (reutilização)
30
+ from .vqvae2_hierarchical import RMSNorm
31
+
32
+
33
+ @dataclass
34
+ class CyclicReasoningConfig:
35
+ """Configuração do sistema de raciocínio cíclico."""
36
+ hidden_size: int = 256
37
+ tool_dim: int = 64
38
+ max_cycles: int = 10
39
+ convergence_threshold: float = 0.01
40
+ # Detecção de falhas
41
+ divergence_threshold: float = 10.0 # Se ||error|| > 10× inicial, aborta
42
+ oscillation_window: int = 3 # Janela para detectar oscilação
43
+ oscillation_tol: float = 0.05 # Tolerância para considerar oscilante
44
+ # Memória
45
+ memory_compress_threshold: int = 512 # Tokens antes de comprimir
46
+ memory_window: int = 256 # Tamanho do contexto recente mantido
47
+ # Transformer (configurável — conforme solicitado v12.5)
48
+ num_transformer_layers: int = 8 # Era hard-coded 2; agora configurável
49
+ transformer_nhead: int = 8 # Número de cabeças da attention
50
+ transformer_dim_ff: int = 2048 # dim_feedforward (default 4× hidden)
51
+ # v12.9: Normalização configurável
52
+ # "layernorm": LayerNorm no transformer + LayerNorm entre camadas (v12.6)
53
+ # "rmsnorm": RMSNorm no transformer + RMSNorm entre camadas
54
+ # "hybrid": RMSNorm nos MLPs (tool_generator, kalman) + LayerNorm no transformer
55
+ transformer_norm_type: str = "layernorm" # "layernorm" | "rmsnorm"
56
+ mlp_norm_type: str = "none" # "none" | "rmsnorm" (LayerNorm nos MLPs não testado)
57
+ # Logging
58
+ log_every_cycle: bool = True
59
+
60
+
61
+ class CyclicStateController(nn.Module):
62
+ """Controlador cíclico com filtro de Kalman e convergência por ponto fixo.
63
+
64
+ Matemática:
65
+ S_hat_{t+1} = f(S_t, u_t) # Predição (GRUCell)
66
+ e_t = y_t - H * S_hat # Inovação (erro)
67
+ K_t = MLP([S_hat, e_t]) # Ganho de Kalman aprendido
68
+ S_{t+1} = S_hat + K_t * e_t # Atualização
69
+ converge se ||e_t|| < epsilon # Ponto fixo
70
+ """
71
+
72
+ def __init__(self, hidden_size: int, tool_dim: int, mlp_norm_type: str = "none"):
73
+ super().__init__()
74
+ self.hidden_size = hidden_size
75
+ self.tool_dim = tool_dim
76
+ self.mlp_norm_type = mlp_norm_type
77
+ # Preditor do próximo estado (GRU recorrente).
78
+ self.state_transition = nn.GRUCell(hidden_size, hidden_size)
79
+ # Projeção da ação da ferramenta para o espaço do estado.
80
+ self.action_proj = nn.Linear(tool_dim, hidden_size)
81
+ # Projeção do estado predito para o espaço de observação.
82
+ self.obs_proj = nn.Linear(hidden_size, hidden_size)
83
+ # v12.9: MLP do Kalman gain com normalização opcional.
84
+ if mlp_norm_type == "rmsnorm":
85
+ self.kalman_gain_net = nn.Sequential(
86
+ nn.Linear(hidden_size * 2, hidden_size),
87
+ RMSNorm(hidden_size),
88
+ nn.ReLU(),
89
+ nn.Linear(hidden_size, hidden_size),
90
+ nn.Sigmoid(), # K_t ∈ [0, 1]
91
+ )
92
+ else:
93
+ self.kalman_gain_net = nn.Sequential(
94
+ nn.Linear(hidden_size * 2, hidden_size),
95
+ nn.ReLU(),
96
+ nn.Linear(hidden_size, hidden_size),
97
+ nn.Sigmoid(), # K_t ∈ [0, 1]
98
+ )
99
+
100
+ def forward(
101
+ self,
102
+ current_state: torch.Tensor,
103
+ tool_action: torch.Tensor,
104
+ observed_state: torch.Tensor,
105
+ ) -> Tuple[torch.Tensor, torch.Tensor, Dict[str, float]]:
106
+ """
107
+ Args:
108
+ current_state: (B, H) estado atual.
109
+ tool_action: (B, T) ação da ferramenta.
110
+ observed_state: (B, H) estado observado.
111
+
112
+ Retorna:
113
+ adjusted_state: (B, H) próximo estado ajustado.
114
+ convergence_metric: (B, 1) norma L2 do erro.
115
+ diagnostics: dict com métricas para logging.
116
+ """
117
+ # 1. Predição do próximo estado baseado na ação.
118
+ action_embed = self.action_proj(tool_action)
119
+ predicted_state = self.state_transition(current_state, action_embed)
120
+
121
+ # 2. Inovação (erro): e_t = y_t - H * S_hat.
122
+ H_predicted = self.obs_proj(predicted_state)
123
+ error = observed_state - H_predicted
124
+
125
+ # 3. Ganho de Kalman K_t ∈ [0, 1]^H (sigmoid).
126
+ K = self.kalman_gain_net(torch.cat([predicted_state, error], dim=-1))
127
+ # v13.9: Fisher Clipping no Kalman gain (reduz mal-conditioning).
128
+ # K pode ter dimensões ≈ 0 (baixa confiança) e ≈ 1 (alta confiança),
129
+ # criando condition number extremo. Fisher Clipping comprime o range.
130
+ from .mathematical_optimizations import fisher_clip_log
131
+ K = fisher_clip_log(K, eps=1e-8)
132
+
133
+ # 4. Atualização do estado.
134
+ adjusted_state = predicted_state + K * error
135
+
136
+ # Norma do erro (para checar convergência).
137
+ convergence_metric = torch.norm(error, p=2, dim=-1, keepdim=True)
138
+
139
+ # Diagnósticos.
140
+ with torch.no_grad():
141
+ diagnostics = {
142
+ 'error_norm_mean': float(convergence_metric.mean().item()),
143
+ 'error_norm_max': float(convergence_metric.max().item()),
144
+ 'kalman_gain_mean': float(K.mean().item()),
145
+ 'state_norm': float(torch.norm(adjusted_state, p=2, dim=-1).mean().item()),
146
+ 'innovation_cosine': float(F.cosine_similarity(
147
+ observed_state, predicted_state, dim=-1
148
+ ).mean().item()),
149
+ }
150
+
151
+ return adjusted_state, convergence_metric, diagnostics
152
+
153
+
154
+ class CyclicMemoryManager(nn.Module):
155
+ """Gestor de memória cíclica com compressão atencional.
156
+
157
+ Estratégia:
158
+ - Mantém últimos `memory_window` tokens sem compressão (contexto recente).
159
+ - Quando o histórico excede `memory_compress_threshold`, comprime o histórico
160
+ antigo em um único vetor latente via cross-attention.
161
+ - Isto permite suportar contextos longos (até 2M tokens teoricamente)
162
+ sem estourar a memória.
163
+ """
164
+
165
+ def __init__(self, config: CyclicReasoningConfig):
166
+ super().__init__()
167
+ self.config = config
168
+ self.attention_compressor = nn.MultiheadAttention(
169
+ embed_dim=config.hidden_size,
170
+ num_heads=8, # fixo para simplicidade
171
+ batch_first=True,
172
+ )
173
+ # LayerNorm para estabilizar após compressão.
174
+ self.norm = nn.LayerNorm(config.hidden_size)
175
+
176
+ def forward(
177
+ self,
178
+ history_embeddings: torch.Tensor,
179
+ current_cycle_embeddings: torch.Tensor,
180
+ ) -> Tuple[torch.Tensor, Dict[str, int]]:
181
+ """
182
+ Args:
183
+ history_embeddings: (B, T_hist, H) histórico acumulado.
184
+ current_cycle_embeddings: (B, T_curr, H) embeddings do ciclo atual.
185
+
186
+ Retorna:
187
+ context_embeds: (B, T_out, H) contexto comprimido.
188
+ stats: dict com tamanhos antes/depois.
189
+ """
190
+ # Concatena histórico com ciclo atual.
191
+ full_context = torch.cat([history_embeddings, current_cycle_embeddings], dim=1)
192
+ T_full = full_context.size(1)
193
+ stats = {'tokens_before': T_full}
194
+
195
+ if T_full > self.config.memory_compress_threshold:
196
+ # Comprime histórico antigo em um único vetor latente.
197
+ # Query: últimos `memory_window` tokens.
198
+ # Key/Value: todos os tokens anteriores ao `memory_window`.
199
+ window = self.config.memory_window
200
+ query = full_context[:, -window:, :]
201
+ kv = full_context[:, :-window, :]
202
+ compressed, _ = self.attention_compressor(query, kv, kv)
203
+ # Pool do comprimido para 1 token + manter janela recente.
204
+ compressed_pooled = compressed.mean(dim=1, keepdim=True)
205
+ compressed_pooled = self.norm(compressed_pooled)
206
+ output = torch.cat([compressed_pooled, full_context[:, -window:, :]], dim=1)
207
+ stats['tokens_after'] = output.size(1)
208
+ stats['compression_ratio'] = stats['tokens_before'] / max(stats['tokens_after'], 1)
209
+ else:
210
+ output = full_context
211
+ stats['tokens_after'] = T_full
212
+ stats['compression_ratio'] = 1.0
213
+
214
+ return output, stats
215
+
216
+
217
+ class GLMCyclicReasoningAgent(nn.Module):
218
+ """Agente de raciocínio cíclico GLM com LLM + memória + controller + tool.
219
+
220
+ Melhorias sobre o código original:
221
+ - Convergence check robusto (norma relativa)
222
+ - Detecção de divergência e oscilação
223
+ - Logging estruturado por ciclo
224
+ - Tool action via MLP (não random walk)
225
+ - Fallback graceful quando não converge
226
+ """
227
+
228
+ def __init__(
229
+ self,
230
+ config: CyclicReasoningConfig,
231
+ vocab_size: int = 1000,
232
+ image_feature_dim: int = 256,
233
+ ):
234
+ super().__init__()
235
+ self.config = config
236
+ self.vocab_size = vocab_size
237
+ self.image_feature_dim = image_feature_dim
238
+
239
+ # v12.9: Helper para criar módulos de normalização conforme config.
240
+ norm_type_tf = config.transformer_norm_type # "layernorm" | "rmsnorm"
241
+ norm_type_mlp = config.mlp_norm_type # "none" | "rmsnorm"
242
+ use_rmsnorm_tf = (norm_type_tf == "rmsnorm")
243
+ use_rmsnorm_mlp = (norm_type_mlp == "rmsnorm")
244
+
245
+ def make_norm(dim):
246
+ return RMSNorm(dim) if use_rmsnorm_tf else nn.LayerNorm(dim)
247
+
248
+ # Embeddings.
249
+ self.text_embed = nn.Embedding(vocab_size, config.hidden_size)
250
+ self.image_proj = nn.Linear(image_feature_dim, config.hidden_size)
251
+ # v12.9: Norm após embedding (LayerNorm ou RMSNorm conforme config).
252
+ self.input_norm = make_norm(config.hidden_size)
253
+
254
+ # LLM base (Transformer Encoder com norm entre camadas).
255
+ dim_ff = config.transformer_dim_ff if config.transformer_dim_ff > 0 else config.hidden_size * 4
256
+ encoder_layer = nn.TransformerEncoderLayer(
257
+ d_model=config.hidden_size,
258
+ nhead=config.transformer_nhead,
259
+ dim_feedforward=dim_ff,
260
+ batch_first=True,
261
+ activation='gelu',
262
+ norm_first=True, # Pre-LN (mais estável com muitas camadas)
263
+ )
264
+ # v12.9: Substituir LayerNorms internos do encoder_layer por RMSNorm se configurado.
265
+ if use_rmsnorm_tf:
266
+ encoder_layer.norm1 = RMSNorm(config.hidden_size)
267
+ encoder_layer.norm2 = RMSNorm(config.hidden_size)
268
+ # v13.10: Aplicar Fisher Clipping em attention weights do transformer.
269
+ # Registra hook no self_attn para clipping dos scores antes do softmax.
270
+ self._clip_attention = True
271
+ original_self_attn = encoder_layer.self_attn
272
+
273
+ class ClippedAttention(nn.Module):
274
+ """Wrapper que aplica Fisher Clipping nos attention scores."""
275
+ def __init__(self, attn_module):
276
+ super().__init__()
277
+ self.attn = attn_module
278
+
279
+ def forward(self, query, key, value, **kwargs):
280
+ # Computar scores manualmente para aplicar clipping.
281
+ # nn.MultiheadAttention faz Q@K^T internamente.
282
+ # Em vez de interceptar, usamos abordagem via need_weights.
283
+ kwargs.setdefault('need_weights', False)
284
+ return self.attn(query, key, value, **kwargs)
285
+
286
+ # Nota: Fisher Clipping em attention scores requer acesso aos scores
287
+ # antes do softmax. nn.MultiheadAttention não expõe isso facilmente.
288
+ # Alternativa: aplicar clipping via post-hoc no output do transformer.
289
+ # Para implementação completa, seria necessário custom MultiheadAttention.
290
+ # Por agora, registramos que o clipping está disponível via clip_attention_weights()
291
+ # e pode ser aplicado em implementações custom de attention.
292
+ # Camadas individuais com norm entre elas.
293
+ layers = []
294
+ for i in range(config.num_transformer_layers):
295
+ layers.append(encoder_layer)
296
+ if i < config.num_transformer_layers - 1:
297
+ layers.append(make_norm(config.hidden_size))
298
+ self.transformer = nn.Sequential(*layers)
299
+ # Norm final após transformer.
300
+ self.output_norm = make_norm(config.hidden_size)
301
+
302
+ # Componentes cíclicos.
303
+ self.memory_manager = CyclicMemoryManager(config)
304
+ self.state_controller = CyclicStateController(
305
+ config.hidden_size, config.tool_dim,
306
+ mlp_norm_type=norm_type_mlp,
307
+ )
308
+
309
+ # v12.9: Tool action generator com normalização opcional nos MLPs.
310
+ if use_rmsnorm_mlp:
311
+ self.tool_generator = nn.Sequential(
312
+ nn.Linear(config.hidden_size, config.hidden_size),
313
+ RMSNorm(config.hidden_size),
314
+ nn.GELU(),
315
+ nn.Linear(config.hidden_size, config.tool_dim),
316
+ )
317
+ else:
318
+ self.tool_generator = nn.Sequential(
319
+ nn.Linear(config.hidden_size, config.hidden_size),
320
+ nn.GELU(),
321
+ nn.Linear(config.hidden_size, config.tool_dim),
322
+ )
323
+
324
+ # LM head.
325
+ self.lm_head = nn.Linear(config.hidden_size, vocab_size)
326
+
327
+ def run_inference_loop(
328
+ self,
329
+ initial_input_ids: torch.Tensor,
330
+ image_features: Optional[torch.Tensor] = None,
331
+ initial_tool_action: Optional[torch.Tensor] = None,
332
+ return_history: bool = True,
333
+ ) -> Dict[str, Any]:
334
+ """
335
+ Executa o sistema cíclico até convergência.
336
+
337
+ Args:
338
+ initial_input_ids: (B, T) tokens de entrada.
339
+ image_features: (B, T_img, D_img) features de imagem (opcional).
340
+ initial_tool_action: (B, tool_dim) ação inicial (opcional).
341
+ return_history: se True, retorna histórico completo de ciclos.
342
+
343
+ Retorna:
344
+ dict com:
345
+ final_logits: (B, T, V) logits finais.
346
+ final_state: (B, H) estado final do agente.
347
+ converged: bool — se convergiu dentro de max_cycles.
348
+ cycles_run: int — número de ciclos executados.
349
+ final_error: float — norma final do erro.
350
+ history: lista de dicts com logs por ciclo.
351
+ failure_mode: str | None — 'diverged', 'oscillating', 'max_cycles', None.
352
+ """
353
+ batch_size = initial_input_ids.size(0)
354
+ device = initial_input_ids.device
355
+
356
+ # Inicialização.
357
+ inputs_embeds = self.text_embed(initial_input_ids)
358
+ if image_features is not None:
359
+ img_embeds = self.image_proj(image_features)
360
+ inputs_embeds = torch.cat([img_embeds, inputs_embeds], dim=1)
361
+
362
+ # Estado inicial do agente (resumo do problema).
363
+ agent_state = inputs_embeds.mean(dim=1)
364
+ history_embeds = inputs_embeds
365
+
366
+ # Tool action inicial.
367
+ if initial_tool_action is None:
368
+ tool_action = torch.zeros(batch_size, self.config.tool_dim, device=device)
369
+ else:
370
+ tool_action = initial_tool_action
371
+
372
+ # Tracking para detecção de falhas.
373
+ error_history: List[float] = []
374
+ history: List[Dict[str, Any]] = []
375
+ failure_mode = None
376
+ converged = False
377
+ cycles_run = 0
378
+ initial_error = None
379
+
380
+ for cycle in range(self.config.max_cycles):
381
+ cycles_run = cycle + 1
382
+
383
+ # 1. Memória (evita estouro de contexto).
384
+ context_embeds, mem_stats = self.memory_manager(
385
+ history_embeds, history_embeds
386
+ )
387
+
388
+ # 2. Processamento LLM (com input_norm e output_norm).
389
+ # v13.4: Sanitização NaN/Inf antes do transformer.
390
+ context_embeds = torch.nan_to_num(context_embeds, nan=0.0, posinf=1e4, neginf=-1e4)
391
+ context_embeds = self.input_norm(context_embeds)
392
+ hidden_states = self.transformer(context_embeds)
393
+ # v13.4: Sanitização NaN/Inf após transformer (attention pode produzir extremos).
394
+ hidden_states = torch.nan_to_num(hidden_states, nan=0.0, posinf=1e4, neginf=-1e4)
395
+ hidden_states = self.output_norm(hidden_states)
396
+
397
+ # 3. Observação: em sistema real viria da execução da tool.
398
+ # Aqui simulamos convergência gradual para o estado predito.
399
+ noise_scale = max(0.5 / (cycle + 1), 0.01)
400
+ observed_state = hidden_states.mean(dim=1) + noise_scale * torch.randn_like(agent_state)
401
+
402
+ # 4. Atualização do estado via Kalman.
403
+ agent_state, convergence_metric, diag = self.state_controller(
404
+ agent_state, tool_action, observed_state
405
+ )
406
+
407
+ error_norm = float(convergence_metric.mean().item())
408
+ error_history.append(error_norm)
409
+ if initial_error is None:
410
+ initial_error = max(error_norm, 1e-6)
411
+
412
+ # 5. Geração de próxima ação/tool.
413
+ tool_action = self.tool_generator(agent_state)
414
+
415
+ # 6. Geração de próximo token.
416
+ logits = self.lm_head(hidden_states)
417
+ next_token_id = torch.argmax(logits[:, -1, :], dim=-1)
418
+
419
+ # Log do ciclo.
420
+ cycle_log = {
421
+ 'cycle': cycle + 1,
422
+ 'token_generated': int(next_token_id[0].item()),
423
+ 'error_norm': error_norm,
424
+ 'relative_error': error_norm / initial_error,
425
+ 'kalman_gain': diag['kalman_gain_mean'],
426
+ 'innovation_cosine': diag['innovation_cosine'],
427
+ 'mem_tokens_before': mem_stats['tokens_before'],
428
+ 'mem_tokens_after': mem_stats['tokens_after'],
429
+ 'mem_compression_ratio': mem_stats['compression_ratio'],
430
+ }
431
+ history.append(cycle_log)
432
+
433
+ if self.config.log_every_cycle:
434
+ print(f" Cycle {cycle+1}: error={error_norm:.4f} "
435
+ f"(rel={error_norm/initial_error:.3f}) "
436
+ f"K={diag['kalman_gain_mean']:.3f} "
437
+ f"token={next_token_id[0].item()}")
438
+
439
+ # 7. Condição de parada (ponto fixo).
440
+ if error_norm < self.config.convergence_threshold:
441
+ converged = True
442
+ print(f">>> Convergência atingida no ciclo {cycle+1}!")
443
+ break
444
+
445
+ # 8. Detecção de divergência (erro crescendo muito).
446
+ if error_norm > self.config.divergence_threshold * initial_error:
447
+ failure_mode = 'diverged'
448
+ print(f"!!! Divergência detectada no ciclo {cycle+1} "
449
+ f"(error={error_norm:.4f} > {self.config.divergence_threshold * initial_error:.4f})")
450
+ break
451
+
452
+ # 9. Detecção de oscilação (variância alta nos últimos N ciclos).
453
+ if len(error_history) >= self.config.oscillation_window:
454
+ window = error_history[-self.config.oscillation_window:]
455
+ window_std = float(torch.tensor(window).std().item())
456
+ window_mean = float(torch.tensor(window).mean().item())
457
+ if window_std > self.config.oscillation_tol and window_std / max(window_mean, 1e-6) > 0.3:
458
+ failure_mode = 'oscillating'
459
+ print(f"!!! Oscilação detectada no ciclo {cycle+1} "
460
+ f"(std={window_std:.4f}, mean={window_mean:.4f})")
461
+ break
462
+
463
+ # Prepara próximo ciclo: adiciona token gerado ao histórico.
464
+ next_token_embed = self.text_embed(next_token_id.unsqueeze(-1))
465
+ history_embeds = torch.cat([history_embeds, next_token_embed], dim=1)
466
+ # v13.1: limpeza leve entre ciclos (libera tensores intermediários).
467
+ # Only gc.collect every 50 cycles, not every cycle (very expensive).
468
+ if (cycle + 1) % 50 == 0:
469
+ import gc as _gc
470
+ _gc.collect(0)
471
+
472
+ if not converged and failure_mode is None:
473
+ failure_mode = 'max_cycles'
474
+ print(f">>> Atingiu max_cycles={self.config.max_cycles} sem convergir.")
475
+
476
+ return {
477
+ 'final_logits': logits,
478
+ 'final_state': agent_state,
479
+ 'converged': converged,
480
+ 'cycles_run': cycles_run,
481
+ 'final_error': error_history[-1] if error_history else float('inf'),
482
+ 'initial_error': initial_error,
483
+ 'history': history if return_history else [],
484
+ 'failure_mode': failure_mode,
485
+ 'error_history': error_history,
486
+ }
487
+
488
+
489
+ class ReasoningDiagnostics:
490
+ """Análise pós-execução do loop de raciocínio cíclico.
491
+
492
+ Detecta padrões de falha e sugere melhorias.
493
+ """
494
+
495
+ @staticmethod
496
+ def analyze(result: Dict[str, Any]) -> Dict[str, Any]:
497
+ """Analisa resultado de run_inference_loop e retorna diagnóstico."""
498
+ error_hist = result.get('error_history', [])
499
+ history = result.get('history', [])
500
+
501
+ analysis = {
502
+ 'converged': result['converged'],
503
+ 'cycles_run': result['cycles_run'],
504
+ 'failure_mode': result['failure_mode'],
505
+ 'initial_error': result.get('initial_error'),
506
+ 'final_error': result.get('final_error'),
507
+ 'error_reduction_pct': 0.0,
508
+ 'avg_kalman_gain': 0.0,
509
+ 'avg_innovation_cosine': 0.0,
510
+ 'mem_compression_used': False,
511
+ 'avg_compression_ratio': 1.0,
512
+ 'error_trend': 'unknown',
513
+ 'recommendations': [],
514
+ }
515
+
516
+ if error_hist and result.get('initial_error'):
517
+ init = result['initial_error']
518
+ final = result['final_error']
519
+ if init > 0:
520
+ analysis['error_reduction_pct'] = (init - final) / init * 100
521
+
522
+ if history:
523
+ analysis['avg_kalman_gain'] = sum(h['kalman_gain'] for h in history) / len(history)
524
+ analysis['avg_innovation_cosine'] = sum(h['innovation_cosine'] for h in history) / len(history)
525
+ compressions = [h['mem_compression_ratio'] for h in history if h['mem_compression_ratio'] > 1.0]
526
+ if compressions:
527
+ analysis['mem_compression_used'] = True
528
+ analysis['avg_compression_ratio'] = sum(compressions) / len(compressions)
529
+
530
+ # Tendência do erro.
531
+ if len(error_hist) >= 2:
532
+ first_half = error_hist[:len(error_hist)//2]
533
+ second_half = error_hist[len(error_hist)//2:]
534
+ if sum(second_half) < sum(first_half):
535
+ analysis['error_trend'] = 'decreasing'
536
+ elif sum(second_half) > sum(first_half):
537
+ analysis['error_trend'] = 'increasing'
538
+ else:
539
+ analysis['error_trend'] = 'stable'
540
+
541
+ # Recomendações.
542
+ if not analysis['converged']:
543
+ if analysis['failure_mode'] == 'diverged':
544
+ analysis['recommendations'].append(
545
+ "Reduzir learning rate do state_controller ou aumentar divergence_threshold"
546
+ )
547
+ elif analysis['failure_mode'] == 'oscillating':
548
+ analysis['recommendations'].append(
549
+ "Aumentar patience para oscilação ou suavizar Kalman gain (maior sigmoid)"
550
+ )
551
+ elif analysis['failure_mode'] == 'max_cycles':
552
+ analysis['recommendations'].append(
553
+ "Aumentar max_cycles ou reduzir convergence_threshold"
554
+ )
555
+
556
+ if analysis['avg_kalman_gain'] > 0.8:
557
+ analysis['recommendations'].append(
558
+ "Kalman gain muito alto — estado super-reativo às observações"
559
+ )
560
+ elif analysis['avg_kalman_gain'] < 0.1:
561
+ analysis['recommendations'].append(
562
+ "Kalman gain muito baixo — estado não está incorporando observações"
563
+ )
564
+
565
+ if analysis['avg_innovation_cosine'] < 0.0:
566
+ analysis['recommendations'].append(
567
+ "Inovação e predição anti-correlacionadas — revisar obs_proj"
568
+ )
569
+
570
+ return analysis
src/bigru_t/reasoning/distributed_reasoning_system.py ADDED
@@ -0,0 +1,807 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ distributed_reasoning_system — Sistema distribuído granulável para LRM.
3
+
4
+ Arquitetura Plan → Evolve → Verify (PEV) com:
5
+ - Planejamento: decomposição de problema em sub-tarefas (granularidade variável)
6
+ - Evolução: execução paralela de sub-tarefas via agentes distribuídos
7
+ - Verificação: checagem de erros, ajustes, e feedback para Planejamento
8
+
9
+ Análise matemática profunda
10
+ ---------------------------
11
+ 1. Teoria da decomposição ótima (granularidade):
12
+ Sea um problema P com complexidade C(P). Decompor em n sub-tarefas
13
+ {s_1,...,s_n} com complexidades {c_1,...,c_n} onde Σc_i ≥ C(P)
14
+ (overhead de decomposição). O tempo paralelo é max(c_i) + T_coord.
15
+
16
+ Granularidade ótima: n* = argmin_n [max(c_i(n)) + T_coord(n)]
17
+ onde c_i(n) ≈ C(P)/n (assumindo divisão equilibrada) e
18
+ T_coord(n) = α·n + β (custo linear de coordenação).
19
+
20
+ Resolvendo: n* = sqrt(C(P) / (α·(1 + β/α)))
21
+
22
+ 2. Convergência do loop PEV:
23
+ Seja E_k o erro após k iterações do loop Plan→Evolve→Verify.
24
+ E_{k+1} = ρ·E_k + ε_verify
25
+ onde ρ ∈ [0,1) é a taxa de correção e ε_verify é o erro residual
26
+ do verificador. Convergência garantida quando ρ < 1.
27
+
28
+ Taxa de convergência: E_k ≤ ρ^k · E_0 + ε_verify/(1-ρ)
29
+
30
+ 3. Teoria de jogos (Planejador vs Verificador):
31
+ Planejador escolhe estratégia σ_P, Verificador escolhe σ_V.
32
+ Jogo zero-sum: u_P(σ_P, σ_V) = -u_V(σ_P, σ_V).
33
+ Equilíbrio de Nash: (σ_P*, σ_V*) onde nenhum pode melhorar unilateralmente.
34
+ Valor do jogo: v = max_σP min_σV u_P(σ_P, σ_V).
35
+
36
+ 4. Álgebra de composição de sub-tarefas:
37
+ Seja T: Problem → Solution uma transformação. Decompor P em {s_i}:
38
+ T(P) = compose(T(s_1), ..., T(s_n))
39
+ onde compose é a álgebra de combinação (monóide associativo).
40
+ Propriedade: T(P) = compose(T(s_1), ..., T(s_n)) ⊕ E_decompose
41
+ onde E_decompose é o erro de decomposição (→ 0 com granularidade fina).
42
+
43
+ 5. Distribuição de probabilidade sobre estratégias:
44
+ P(estratégia | problema) = softmax(score(estratégia, problema) / τ)
45
+ onde τ é temperatura (→ 0: greedy, → ∞: uniforme).
46
+ Atualização Bayesiana após verificação:
47
+ P(estratégia | problema, resultado) ∝ P(resultado | estratégia) · P(estratégia | problema)
48
+ """
49
+
50
+ from __future__ import annotations
51
+
52
+ import math
53
+ import time
54
+ import threading
55
+ from collections import defaultdict, deque
56
+ from concurrent.futures import Future, ThreadPoolExecutor, as_completed
57
+ from dataclasses import dataclass, field
58
+ from enum import Enum
59
+ from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
60
+
61
+ import numpy as np
62
+
63
+
64
+ # ============================================================================
65
+ # Exceções
66
+ # ============================================================================
67
+
68
+ class ReasoningError(RuntimeError):
69
+ """Erro no sistema de raciocínio."""
70
+
71
+
72
+ class PlanError(ReasoningError):
73
+ """Erro no planejamento."""
74
+
75
+
76
+ class EvolveError(ReasoningError):
77
+ """Erro na evolução/execução."""
78
+
79
+
80
+ class VerifyError(ReasoningError):
81
+ """Erro na verificação."""
82
+
83
+
84
+ class ConvergenceFailure(ReasoningError):
85
+ """Sistema PEV não convergiu após max_iterations."""
86
+
87
+
88
+ # ============================================================================
89
+ # Estruturas de dados
90
+ # ============================================================================
91
+
92
+ class TaskStatus(Enum):
93
+ PENDING = "pending"
94
+ PLANNED = "planned"
95
+ EXECUTING = "executing"
96
+ VERIFIED = "verified"
97
+ FAILED = "failed"
98
+ NEEDS_REPLAN = "needs_replan"
99
+
100
+
101
+ @dataclass
102
+ class SubTask:
103
+ """Sub-tarefa decomposta do problema principal."""
104
+ id: str
105
+ description: str
106
+ complexity: float # custo estimado
107
+ dependencies: Set[str] = field(default_factory=set) # IDs de sub-tarefas dependentes
108
+ status: TaskStatus = TaskStatus.PENDING
109
+ result: Optional[Any] = None
110
+ error: Optional[str] = None
111
+ verify_score: Optional[float] = None # score de verificação [0, 1]
112
+ iterations: int = 0
113
+ metadata: Dict[str, Any] = field(default_factory=dict)
114
+
115
+
116
+ @dataclass
117
+ class Problem:
118
+ """Problema a ser resolvido pelo sistema PEV."""
119
+ id: str
120
+ description: str
121
+ complexity: float # estimativa de complexidade
122
+ constraints: Dict[str, Any] = field(default_factory=dict)
123
+ context: Dict[str, Any] = field(default_factory=dict)
124
+ max_iterations: int = 5
125
+ convergence_threshold: float = 0.95 # score mínimo para aceitar
126
+
127
+
128
+ @dataclass
129
+ class Solution:
130
+ """Solução produzida pelo sistema PEV."""
131
+ problem_id: str
132
+ result: Any
133
+ verify_score: float
134
+ iterations: int
135
+ subtasks: List[SubTask]
136
+ total_time_s: float
137
+ converged: bool
138
+ error_history: List[Dict[str, Any]] = field(default_factory=list)
139
+
140
+
141
+ @dataclass
142
+ class PEVStats:
143
+ """Estatísticas do loop Plan→Evolve→Verify."""
144
+ n_iterations: int = 0
145
+ n_subtasks_total: int = 0
146
+ n_subtasks_verified: int = 0
147
+ n_subtasks_failed: int = 0
148
+ n_replans: int = 0
149
+ total_plan_time_s: float = 0.0
150
+ total_evolve_time_s: float = 0.0
151
+ total_verify_time_s: float = 0.0
152
+ error_trajectory: List[float] = field(default_factory=list)
153
+
154
+
155
+ # ============================================================================
156
+ # 1. Planner — decomposição granular de problemas
157
+ # ============================================================================
158
+
159
+ class Planner:
160
+ """Planejador: decomponhe problema em sub-tarefas granulares.
161
+
162
+ Análise matemática da granularidade ótima:
163
+ n* = sqrt(C(P) / (α·(1 + β/α)))
164
+ onde C(P) é complexidade, α é custo por sub-tarefa, β é overhead fixo.
165
+
166
+ Estratégias de decomposição:
167
+ 1. UNIFORM: divide em n sub-tarefas de complexidade igual
168
+ 2. ADAPTIVE: divide baseado em estrutura do problema
169
+ 3. RECURSIVE: sub-tarefas podem ser进一步 decompostas
170
+ """
171
+
172
+ def __init__(
173
+ self,
174
+ max_subtasks: int = 20,
175
+ min_subtasks: int = 2,
176
+ alpha: float = 0.1, # custo por sub-tarefa
177
+ beta: float = 0.05, # overhead fixo
178
+ strategy: str = "adaptive",
179
+ verbose: bool = False,
180
+ ):
181
+ self.max_subtasks = max_subtasks
182
+ self.min_subtasks = min_subtasks
183
+ self.alpha = alpha
184
+ self.beta = beta
185
+ self.strategy = strategy
186
+ self.verbose = verbose
187
+
188
+ def _compute_optimal_granularity(self, complexity: float) -> int:
189
+ """Computa granularidade ótima n* = sqrt(C / (α·(1+β/α)))."""
190
+ denom = self.alpha * (1 + self.beta / self.alpha)
191
+ if denom < 1e-12:
192
+ return self.min_subtasks
193
+ n_star = math.sqrt(complexity / denom)
194
+ return max(self.min_subtasks, min(self.max_subtasks, int(round(n_star))))
195
+
196
+ def plan(
197
+ self,
198
+ problem: Problem,
199
+ feedback: Optional[List[Dict[str, Any]]] = None,
200
+ ) -> List[SubTask]:
201
+ """Decompõe problema em sub-tarefas.
202
+
203
+ Args:
204
+ problem: problema a decompor
205
+ feedback: feedback da iteração anterior (para replanejamento)
206
+
207
+ Retorna: lista de SubTasks
208
+ """
209
+ t0 = time.time()
210
+ n = self._compute_optimal_granularity(problem.complexity)
211
+ if self.verbose:
212
+ print(f" Planner: granularidade ótima n*={n} "
213
+ f"(C={problem.complexity}, α={self.alpha}, β={self.beta})")
214
+ # Se há feedback, ajusta n.
215
+ if feedback:
216
+ # Aumenta granularidade se houve falhas (mais sub-tarefas = mais isolamento).
217
+ n_failures = sum(1 for f in feedback if f.get("status") == "failed")
218
+ n = min(self.max_subtasks, n + n_failures)
219
+ if self.verbose:
220
+ print(f" Planner: ajustado para n={n} (feedback: {n_failures} falhas)")
221
+
222
+ subtasks = []
223
+ if self.strategy == "uniform":
224
+ subtasks = self._decompose_uniform(problem, n)
225
+ elif self.strategy == "adaptive":
226
+ subtasks = self._decompose_adaptive(problem, n)
227
+ else:
228
+ subtasks = self._decompose_uniform(problem, n)
229
+
230
+ # Adiciona dependências (grafo DAG).
231
+ for i, st in enumerate(subtasks):
232
+ if i > 0:
233
+ st.dependencies.add(subtasks[i-1].id)
234
+
235
+ if self.verbose:
236
+ print(f" Planner: {len(subtasks)} sub-tarefas criadas em "
237
+ f"{time.time()-t0:.3f}s")
238
+ return subtasks
239
+
240
+ def _decompose_uniform(self, problem: Problem, n: int) -> List[SubTask]:
241
+ """Decomposição uniforme: n sub-tarefas de complexidade igual."""
242
+ c_per = problem.complexity / n
243
+ return [
244
+ SubTask(
245
+ id=f"{problem.id}_st_{i}",
246
+ description=f"Sub-tarefa {i}/{n}: parte {i+1} de '{problem.description}'",
247
+ complexity=c_per,
248
+ )
249
+ for i in range(n)
250
+ ]
251
+
252
+ def _decompose_adaptive(self, problem: Problem, n: int) -> List[SubTask]:
253
+ """Decomposição adaptativa: complexidade varia baseado em estrutura.
254
+
255
+ Heurística: primeiro 30% das sub-tarefas têm complexidade maior
256
+ (mais difíceis), resto é mais simples.
257
+ """
258
+ subtasks = []
259
+ # Distribui complexidade: primeiras sub-tarefas mais pesadas.
260
+ weights = np.array([1.5 if i < n * 0.3 else 0.8 for i in range(n)])
261
+ weights = weights / weights.sum()
262
+ complexities = problem.complexity * weights
263
+ for i in range(n):
264
+ subtasks.append(SubTask(
265
+ id=f"{problem.id}_st_{i}",
266
+ description=f"Sub-tarefa adaptativa {i}/{n}",
267
+ complexity=float(complexities[i]),
268
+ metadata={"weight": float(weights[i])},
269
+ ))
270
+ return subtasks
271
+
272
+
273
+ # ============================================================================
274
+ # 2. Evolver — execução paralela de sub-tarefas
275
+ # ============================================================================
276
+
277
+ class Evolver:
278
+ """Evoluidor: executa sub-tarefas em paralelo via agentes distribuídos.
279
+
280
+ Usa ThreadPoolExecutor para paralelismo. Respeita dependências (DAG).
281
+ """
282
+
283
+ def __init__(
284
+ self,
285
+ n_workers: int = 4,
286
+ timeout_s: float = 30.0,
287
+ verbose: bool = False,
288
+ ):
289
+ self.n_workers = n_workers
290
+ self.timeout_s = timeout_s
291
+ self.verbose = verbose
292
+
293
+ def evolve(
294
+ self,
295
+ subtasks: List[SubTask],
296
+ executor_fn: Callable[[SubTask], Any],
297
+ ) -> List[SubTask]:
298
+ """Executa sub-tarefas em paralelo, respeitando dependências.
299
+
300
+ Args:
301
+ subtasks: lista de sub-tarefas
302
+ executor_fn: função que executa uma sub-tarefa
303
+
304
+ Retorna: sub-tarefas atualizadas com resultados
305
+ """
306
+ t0 = time.time()
307
+ task_map = {st.id: st for st in subtasks}
308
+ completed: Set[str] = set()
309
+ remaining = set(st.id for st in subtasks)
310
+ # Executa em rounds (respeita DAG).
311
+ with ThreadPoolExecutor(max_workers=self.n_workers) as pool:
312
+ while remaining:
313
+ # Encontra sub-tarefas prontas (dependências satisfeitas).
314
+ ready = [
315
+ sid for sid in remaining
316
+ if task_map[sid].dependencies.issubset(completed)
317
+ ]
318
+ if not ready:
319
+ # Deadlock: dependências circulares.
320
+ raise EvolveError(
321
+ f"Deadlock: sub-tarefas {remaining} têm dependências circulares"
322
+ )
323
+ # Submete prontas.
324
+ futures = {
325
+ pool.submit(self._execute_task, task_map[sid], executor_fn): sid
326
+ for sid in ready
327
+ }
328
+ # Coleta.
329
+ for fut in as_completed(futures, timeout=self.timeout_s):
330
+ sid = futures[fut]
331
+ try:
332
+ result = fut.result()
333
+ task_map[sid].result = result
334
+ task_map[sid].status = TaskStatus.EXECUTING
335
+ completed.add(sid)
336
+ remaining.discard(sid)
337
+ if self.verbose:
338
+ print(f" Evolver: {sid} OK")
339
+ except Exception as e:
340
+ task_map[sid].error = str(e)
341
+ task_map[sid].status = TaskStatus.FAILED
342
+ completed.add(sid) # marca como processada
343
+ remaining.discard(sid)
344
+ if self.verbose:
345
+ print(f" Evolver: {sid} FALHOU: {e}")
346
+ if self.verbose:
347
+ print(f" Evolver: {len(completed)} sub-tarefas em {time.time()-t0:.3f}s")
348
+ return list(task_map.values())
349
+
350
+ def _execute_task(
351
+ self,
352
+ task: SubTask,
353
+ executor_fn: Callable,
354
+ ) -> Any:
355
+ """Executa uma sub-tarefa com timeout."""
356
+ task.status = TaskStatus.EXECUTING
357
+ task.iterations += 1
358
+ return executor_fn(task)
359
+
360
+
361
+ # ============================================================================
362
+ # 3. Verifier — verificação de resultados
363
+ # ============================================================================
364
+
365
+ class Verifier:
366
+ """Verificador: checa resultados de sub-tarefas.
367
+
368
+ Análise matemática da convergência:
369
+ E_{k+1} = ρ·E_k + ε_verify
370
+ E_k ≤ ρ^k · E_0 + ε_verify/(1-ρ)
371
+
372
+ Tipos de verificação:
373
+ 1. CONSISTENCY: checa consistência entre sub-tarefas
374
+ 2. BOUNDS: checa se resultado está dentro de limites esperados
375
+ 3. CROSS_VALIDATION: valida cruzando resultados
376
+ """
377
+
378
+ def __init__(
379
+ self,
380
+ verify_fn: Optional[Callable[[SubTask, Any], float]] = None,
381
+ consistency_threshold: float = 0.8,
382
+ verbose: bool = False,
383
+ ):
384
+ self.verify_fn = verify_fn or self._default_verify
385
+ self.consistency_threshold = consistency_threshold
386
+ self.verbose = verbose
387
+
388
+ def verify(
389
+ self,
390
+ subtasks: List[SubTask],
391
+ problem: Problem,
392
+ ) -> Tuple[List[SubTask], float, List[Dict[str, Any]]]:
393
+ """Verifica resultados das sub-tarefas.
394
+
395
+ Retorna: (subtasks_atualizadas, score_global, feedback)
396
+ """
397
+ t0 = time.time()
398
+ feedback = []
399
+ scores = []
400
+ for st in subtasks:
401
+ if st.status == TaskStatus.FAILED:
402
+ st.verify_score = 0.0
403
+ feedback.append({
404
+ "id": st.id, "status": "failed",
405
+ "error": st.error, "action": "replan",
406
+ })
407
+ scores.append(0.0)
408
+ continue
409
+ if st.result is None:
410
+ st.verify_score = 0.0
411
+ feedback.append({
412
+ "id": st.id, "status": "no_result", "action": "reexecute",
413
+ })
414
+ scores.append(0.0)
415
+ continue
416
+ # Verifica.
417
+ score = self.verify_fn(st, st.result)
418
+ st.verify_score = score
419
+ scores.append(score)
420
+ if score >= self.consistency_threshold:
421
+ st.status = TaskStatus.VERIFIED
422
+ feedback.append({
423
+ "id": st.id, "status": "verified",
424
+ "score": score, "action": "accept",
425
+ })
426
+ else:
427
+ st.status = TaskStatus.NEEDS_REPLAN
428
+ feedback.append({
429
+ "id": st.id, "status": "needs_replan",
430
+ "score": score, "action": "replan",
431
+ })
432
+ # Score global: média harmônica (penaliza sub-tarefas com score baixo).
433
+ # Sub-tarefas falhadas (score=0) contam como epsilon para evitar divisão por zero.
434
+ eps_score = 0.01
435
+ all_scores = [max(s, eps_score) for s in scores]
436
+ global_score = len(all_scores) / sum(1/s for s in all_scores)
437
+ if self.verbose:
438
+ print(f" Verifier: score global={global_score:.4f}, "
439
+ f"feedback={len(feedback)} itens em {time.time()-t0:.3f}s")
440
+ return subtasks, global_score, feedback
441
+
442
+ def _default_verify(self, task: SubTask, result: Any) -> float:
443
+ """Verificação default: checa se resultado não é None e é razoável."""
444
+ if result is None:
445
+ return 0.0
446
+ if isinstance(result, (int, float)):
447
+ return 1.0 if not math.isnan(result) else 0.0
448
+ if isinstance(result, str):
449
+ return 1.0 if len(result) > 0 else 0.0
450
+ if isinstance(result, (list, dict)):
451
+ return 1.0 if len(result) > 0 else 0.5
452
+ return 0.8 # default para tipos desconhecidos
453
+
454
+
455
+ # ============================================================================
456
+ # 4. PEVSystem — sistema distribuído Plan→Evolve→Verify
457
+ # ============================================================================
458
+
459
+ class PEVSystem:
460
+ """Sistema distribuído granulável Plan→Evolve→Verify.
461
+
462
+ Loop principal:
463
+ 1. PLAN: Planner decompõe problema em sub-tarefas
464
+ 2. EVOLVE: Evolver executa sub-tarefas em paralelo
465
+ 3. VERIFY: Verifier checa resultados
466
+ 4. Se score < threshold: feedback → PLAN (replanejamento)
467
+ 5. Repete até convergência ou max_iterations
468
+
469
+ Análise de convergência:
470
+ E_{k+1} = ρ·E_k + ε_verify
471
+ Convergência garantida quando ρ < 1 (verificador corrige > 0% do erro).
472
+ k_max = ceil(log((E_0 - ε/(1-ρ)) / (threshold - ε/(1-ρ))) / log(ρ))
473
+
474
+ Uso:
475
+ >>> system = PEVSystem()
476
+ >>> solution = system.solve(problem, executor_fn=my_executor)
477
+ """
478
+
479
+ def __init__(
480
+ self,
481
+ n_workers: int = 4,
482
+ max_subtasks: int = 20,
483
+ planner_strategy: str = "adaptive",
484
+ alpha: float = 0.1,
485
+ beta: float = 0.05,
486
+ consistency_threshold: float = 0.8,
487
+ verify_fn: Optional[Callable] = None,
488
+ verbose: bool = False,
489
+ ):
490
+ self.planner = Planner(
491
+ max_subtasks=max_subtasks,
492
+ alpha=alpha, beta=beta,
493
+ strategy=planner_strategy,
494
+ verbose=verbose,
495
+ )
496
+ self.evolver = Evolver(
497
+ n_workers=n_workers,
498
+ verbose=verbose,
499
+ )
500
+ self.verifier = Verifier(
501
+ verify_fn=verify_fn,
502
+ consistency_threshold=consistency_threshold,
503
+ verbose=verbose,
504
+ )
505
+ self.verbose = verbose
506
+ self.stats = PEVStats()
507
+
508
+ def solve(
509
+ self,
510
+ problem: Problem,
511
+ executor_fn: Callable[[SubTask], Any],
512
+ ) -> Solution:
513
+ """Resolve problema via loop PEV.
514
+
515
+ Args:
516
+ problem: problema a resolver
517
+ executor_fn: função que executa uma sub-tarefa
518
+
519
+ Retorna: Solution
520
+ """
521
+ t0 = time.time()
522
+ feedback = None
523
+ all_subtasks: List[SubTask] = []
524
+ error_history = []
525
+ converged = False
526
+ for iteration in range(1, problem.max_iterations + 1):
527
+ self.stats.n_iterations = iteration
528
+ if self.verbose:
529
+ print(f"\n--- PEV Iteração {iteration}/{problem.max_iterations} ---")
530
+
531
+ # 1. PLAN.
532
+ t_plan = time.time()
533
+ subtasks = self.planner.plan(problem, feedback)
534
+ self.stats.total_plan_time_s += time.time() - t_plan
535
+ self.stats.n_subtasks_total += len(subtasks)
536
+
537
+ # 2. EVOLVE.
538
+ t_evolve = time.time()
539
+ subtasks = self.evolver.evolve(subtasks, executor_fn)
540
+ self.stats.total_evolve_time_s += time.time() - t_evolve
541
+
542
+ # 3. VERIFY.
543
+ t_verify = time.time()
544
+ subtasks, global_score, feedback = self.verifier.verify(subtasks, problem)
545
+ self.stats.total_verify_time_s += time.time() - t_verify
546
+ self.stats.error_trajectory.append(1.0 - global_score)
547
+
548
+ # Conta status.
549
+ n_verified = sum(1 for st in subtasks if st.status == TaskStatus.VERIFIED)
550
+ n_failed = sum(1 for st in subtasks if st.status == TaskStatus.FAILED)
551
+ n_replan = sum(1 for st in subtasks if st.status == TaskStatus.NEEDS_REPLAN)
552
+ self.stats.n_subtasks_verified += n_verified
553
+ self.stats.n_subtasks_failed += n_failed
554
+ self.stats.n_replans += n_replan
555
+
556
+ all_subtasks = subtasks
557
+ if self.verbose:
558
+ print(f" Score: {global_score:.4f} "
559
+ f"(verified={n_verified}, failed={n_failed}, replan={n_replan})")
560
+
561
+ # 4. Convergência?
562
+ if global_score >= problem.convergence_threshold:
563
+ converged = True
564
+ if self.verbose:
565
+ print(f" ✓ Convergiu em {iteration} iterações")
566
+ break
567
+
568
+ # 5. Prepara feedback para próxima iteração.
569
+ error_history.append({
570
+ "iteration": iteration,
571
+ "score": global_score,
572
+ "n_verified": n_verified,
573
+ "n_failed": n_failed,
574
+ "n_replan": n_replan,
575
+ })
576
+ if n_replan > 0:
577
+ feedback = [f for f in feedback if f.get("action") == "replan"]
578
+
579
+ if not converged:
580
+ if self.verbose:
581
+ print(f" ✗ Não convergiu após {problem.max_iterations} iterações")
582
+
583
+ # Compõe solução final.
584
+ result = self._compose_solution(all_subtasks)
585
+ total_time = time.time() - t0
586
+ return Solution(
587
+ problem_id=problem.id,
588
+ result=result,
589
+ verify_score=self.stats.error_trajectory[-1] if self.stats.error_trajectory else 0.0,
590
+ iterations=self.stats.n_iterations,
591
+ subtasks=all_subtasks,
592
+ total_time_s=total_time,
593
+ converged=converged,
594
+ error_history=error_history,
595
+ )
596
+
597
+ def _compose_solution(self, subtasks: List[SubTask]) -> Any:
598
+ """Compõe solução final a partir de sub-tarefas.
599
+
600
+ Álgebra de composição: T(P) = compose(T(s_1), ..., T(s_n))
601
+ """
602
+ results = []
603
+ for st in subtasks:
604
+ if st.status == TaskStatus.VERIFIED and st.result is not None:
605
+ results.append(st.result)
606
+ if not results:
607
+ return None
608
+ if len(results) == 1:
609
+ return results[0]
610
+ # Tenta concatenar se possível.
611
+ if all(isinstance(r, (list,)) for r in results):
612
+ return [item for r in results for item in r]
613
+ if all(isinstance(r, dict) for r in results):
614
+ merged = {}
615
+ for r in results:
616
+ merged.update(r)
617
+ return merged
618
+ # Retorna lista de resultados.
619
+ return results
620
+
621
+ def get_stats(self) -> PEVStats:
622
+ return self.stats
623
+
624
+ def summary(self) -> str:
625
+ s = self.stats
626
+ return (
627
+ f"PEVSystem Stats:\n"
628
+ f" Iterações: {s.n_iterations}\n"
629
+ f" Sub-tarefas: {s.n_subtasks_total} total, "
630
+ f"{s.n_subtasks_verified} verificadas, {s.n_subtasks_failed} falhas\n"
631
+ f" Replanejamentos: {s.n_replans}\n"
632
+ f" Tempo: plan={s.total_plan_time_s:.3f}s, "
633
+ f"evolve={s.total_evolve_time_s:.3f}s, "
634
+ f"verify={s.total_verify_time_s:.3f}s\n"
635
+ f" Trajetória de erro: {[f'{e:.4f}' for e in s.error_trajectory]}"
636
+ )
637
+
638
+
639
+ # ============================================================================
640
+ # 5. BayesianStrategySelector — seleção Bayesiana de estratégias
641
+ # ============================================================================
642
+
643
+ class BayesianStrategySelector:
644
+ """Seleção Bayesiana de estratégias de decomposição.
645
+
646
+ Mantém posterior sobre estratégias dado histórico de resultados.
647
+ P(estratégia | problema, resultado) ∝ P(resultado | estratégia) · P(estratégia | problema)
648
+
649
+ Estratégias: ['uniform', 'adaptive', 'recursive']
650
+ Para cada estratégia, mantém Beta(α, β) sobre probabilidade de sucesso.
651
+ """
652
+
653
+ def __init__(
654
+ self,
655
+ strategies: List[str] = None,
656
+ prior_alpha: float = 1.0,
657
+ prior_beta: float = 1.0,
658
+ temperature: float = 1.0,
659
+ ):
660
+ self.strategies = strategies or ["uniform", "adaptive", "recursive"]
661
+ self.temperature = temperature
662
+ # Posterior Beta(α, β) para cada estratégia.
663
+ self.posteriors: Dict[str, Tuple[float, float]] = {
664
+ s: (prior_alpha, prior_beta) for s in self.strategies
665
+ }
666
+ # Histórico de resultados.
667
+ self.history: List[Dict[str, Any]] = []
668
+
669
+ def select(self) -> str:
670
+ """Seleciona estratégia via Thompson sampling."""
671
+ samples = {}
672
+ for s in self.strategies:
673
+ a, b = self.posteriors[s]
674
+ samples[s] = np.random.beta(a, b)
675
+ return max(samples, key=samples.get)
676
+
677
+ def update(self, strategy: str, success: bool, score: float = 0.0) -> None:
678
+ """Atualiza posterior após observação."""
679
+ a, b = self.posteriors[strategy]
680
+ if success:
681
+ a += 1 + score # score pondera o sucesso
682
+ else:
683
+ b += 1
684
+ self.posteriors[strategy] = (a, b)
685
+ self.history.append({
686
+ "strategy": strategy,
687
+ "success": success,
688
+ "score": score,
689
+ "posterior": (a, b),
690
+ })
691
+
692
+ def get_probabilities(self) -> Dict[str, float]:
693
+ """Retorna probabilidade esperada de sucesso por estratégia."""
694
+ return {
695
+ s: a / (a + b)
696
+ for s, (a, b) in self.posteriors.items()
697
+ }
698
+
699
+ def summary(self) -> str:
700
+ lines = ["BayesianStrategySelector:"]
701
+ for s in self.strategies:
702
+ a, b = self.posteriors[s]
703
+ p = a / (a + b)
704
+ lines.append(f" {s}: Beta({a:.1f}, {b:.1f}), P(sucesso)={p:.3f}")
705
+ return "\n".join(lines)
706
+
707
+
708
+ # ============================================================================
709
+ # 6. Análise matemática — funções de análise
710
+ # ============================================================================
711
+
712
+ def analyze_convergence(
713
+ error_trajectory: List[float],
714
+ rho: float = 0.5,
715
+ epsilon: float = 0.01,
716
+ ) -> Dict[str, Any]:
717
+ """Analisa convergência do loop PEV.
718
+
719
+ E_{k+1} = ρ·E_k + ε
720
+ E_k ≤ ρ^k · E_0 + ε/(1-ρ)
721
+
722
+ Args:
723
+ error_trajectory: lista de erros por iteração
724
+ rho: taxa de correção estimada
725
+ epsilon: erro residual do verificador
726
+
727
+ Retorna: análise de convergência
728
+ """
729
+ if not error_trajectory:
730
+ return {"converged": False, "reason": "sem dados"}
731
+ n = len(error_trajectory)
732
+ final_error = error_trajectory[-1]
733
+ initial_error = error_trajectory[0]
734
+ # Estima ρ empiricamente.
735
+ if n > 1:
736
+ rhos = []
737
+ for i in range(n - 1):
738
+ if error_trajectory[i] > epsilon:
739
+ rho_est = (error_trajectory[i+1] - epsilon) / max(error_trajectory[i], 1e-8)
740
+ rhos.append(max(0, min(1, rho_est)))
741
+ rho_empirical = np.mean(rhos) if rhos else rho
742
+ else:
743
+ rho_empirical = rho
744
+ # Prediz k_max para threshold.
745
+ threshold = 0.05 # 5% de erro
746
+ if rho_empirical < 1 and (initial_error - epsilon/(1-rho_empirical)) > 0:
747
+ k_max_pred = math.ceil(
748
+ math.log((threshold - epsilon/(1-rho_empirical)) /
749
+ max(initial_error - epsilon/(1-rho_empirical), 1e-8)) /
750
+ math.log(max(rho_empirical, 1e-8))
751
+ )
752
+ else:
753
+ k_max_pred = float('inf')
754
+ return {
755
+ "n_iterations": n,
756
+ "initial_error": initial_error,
757
+ "final_error": final_error,
758
+ "rho_empirical": float(rho_empirical),
759
+ "epsilon": epsilon,
760
+ "converged": final_error < threshold,
761
+ "k_max_predicted": k_max_pred if k_max_pred != float('inf') else -1,
762
+ "error_ratio": final_error / max(initial_error, 1e-8),
763
+ "trajectory": error_trajectory,
764
+ }
765
+
766
+
767
+ def analyze_granularity(
768
+ complexity: float,
769
+ alpha: float = 0.1,
770
+ beta: float = 0.05,
771
+ n_range: List[int] = None,
772
+ ) -> Dict[str, Any]:
773
+ """Analisa granularidade ótima teórica.
774
+
775
+ n* = sqrt(C / (α·(1+β/α)))
776
+
777
+ Para cada n, computa:
778
+ - T_parallel(n) = C/n + α·n + β
779
+ - S(n) = C / T_parallel(n) (speedup vs sequencial)
780
+ """
781
+ if n_range is None:
782
+ n_range = list(range(1, 21))
783
+ results = []
784
+ for n in n_range:
785
+ t_seq = complexity
786
+ t_par = complexity / n + alpha * n + beta
787
+ speedup = t_seq / t_par if t_par > 0 else 0
788
+ results.append({
789
+ "n": n,
790
+ "t_sequential": t_seq,
791
+ "t_parallel": t_par,
792
+ "speedup": speedup,
793
+ })
794
+ # n ótimo teórico.
795
+ denom = alpha * (1 + beta / alpha)
796
+ n_star = math.sqrt(complexity / denom) if denom > 0 else 1
797
+ # n ótimo empírico.
798
+ best_n = max(results, key=lambda x: x["speedup"])
799
+ return {
800
+ "complexity": complexity,
801
+ "alpha": alpha,
802
+ "beta": beta,
803
+ "n_star_theoretical": n_star,
804
+ "n_star_empirical": best_n["n"],
805
+ "max_speedup": best_n["speedup"],
806
+ "results": results,
807
+ }
src/bigru_t/reasoning/reasoning_engine.py ADDED
@@ -0,0 +1,522 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ reasoning_engine — Sistema de raciocínio (Reasoning/Thinking) integrável.
3
+
4
+ Sistema de raciocínio com plena capacidade de:
5
+ - Planejamento (decomposição de problemas em sub-tarefas)
6
+ - Monitoramento (feedback de ações)
7
+ - Decomposição e distribuição de tarefas
8
+ - Predição de estado (Evolução via Kalman)
9
+ - Ajustamento (feedback loop)
10
+ - Coordenação (orquestração circular)
11
+ - Processamento (execução paralela)
12
+ - Ações (uso de tools)
13
+ - Retorno de requisições (respostas)
14
+
15
+ Streaming de raciocínio:
16
+ - Tag <think>...</think> (como DeepSeek-R1, QwQ)
17
+ - Tag <tool_call>...</tool_call> (como LangChain/LangGraph)
18
+ - Tag <answer>...</answer> (resposta final)
19
+ - Compatível com Ollama, LangChain, vLLM
20
+
21
+ Integra:
22
+ - HanoiCircularOrchestrator (raciocínio circular)
23
+ - ToolAgentCoordinator (uso de ferramentas)
24
+ - PEVSystem (Plan→Evolve→Verify)
25
+ - CircularOrchestrator (anel com Kalman)
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import json
31
+ import re
32
+ import time
33
+ from collections import deque
34
+ from dataclasses import dataclass, field
35
+ from enum import Enum
36
+ from typing import Any, Callable, Dict, Generator, Iterator, List, Optional, Tuple, Union
37
+
38
+ from .circular_orchestration import (
39
+ CircularOrchestrator, CircularAgent, KalmanPredictor,
40
+ CircularTask, AgentPhase, MonitoredAction, StatePrediction,
41
+ )
42
+ from .tool_agent import ToolAgentCoordinator, ToolWrapper, MCPConnection
43
+ from .distributed_reasoning_system import PEVSystem, Problem, SubTask
44
+
45
+
46
+ # ============================================================================
47
+ # Tags de raciocínio (compatível com Ollama/LangChain)
48
+ # ============================================================================
49
+
50
+ class ThinkTag(Enum):
51
+ """Tags de streaming de raciocínio."""
52
+ THINK_OPEN = "<think>"
53
+ THINK_CLOSE = "</think>"
54
+ TOOL_OPEN = "<tool_call>"
55
+ TOOL_CLOSE = "</tool_call>"
56
+ ANSWER_OPEN = "<answer>"
57
+ ANSWER_CLOSE = "</answer>"
58
+ PLAN_OPEN = "<plan>"
59
+ PLAN_CLOSE = "</plan>"
60
+ DECOMPOSE_OPEN = "<decompose>"
61
+ DECOMPOSE_CLOSE = "</decompose>"
62
+ MONITOR_OPEN = "<monitor>"
63
+ MONITOR_CLOSE = "</monitor>"
64
+ PREDICT_OPEN = "<predict>"
65
+ PREDICT_CLOSE = "</predict>"
66
+ ADJUST_OPEN = "<adjust>"
67
+ ADJUST_CLOSE = "</adjust>"
68
+
69
+
70
+ class ReasoningPhase(Enum):
71
+ """Fases do raciocínio."""
72
+ THINKING = "thinking"
73
+ PLANNING = "planning"
74
+ DECOMPOSING = "decomposing"
75
+ EXECUTING = "executing"
76
+ MONITORING = "monitoring"
77
+ PREDICTING = "predicting"
78
+ ADJUSTING = "adjusting"
79
+ TOOL_USE = "tool_use"
80
+ ANSWERING = "answering"
81
+
82
+
83
+ # ============================================================================
84
+ # ReasoningStep — um passo do raciocínio
85
+ # ============================================================================
86
+
87
+ @dataclass
88
+ class ReasoningStep:
89
+ """Um passo do processo de raciocínio."""
90
+ phase: ReasoningPhase
91
+ content: str
92
+ timestamp: float = field(default_factory=time.time)
93
+ tool_name: Optional[str] = None
94
+ tool_input: Optional[Any] = None
95
+ tool_output: Optional[Any] = None
96
+ metadata: Dict[str, Any] = field(default_factory=dict)
97
+
98
+ def to_tag(self) -> str:
99
+ """Converte para tag de streaming."""
100
+ if self.phase == ReasoningPhase.THINKING:
101
+ return f"{ThinkTag.THINK_OPEN.value}\n{self.content}\n{ThinkTag.THINK_CLOSE.value}"
102
+ elif self.phase == ReasoningPhase.PLANNING:
103
+ return f"{ThinkTag.PLAN_OPEN.value}\n{self.content}\n{ThinkTag.PLAN_CLOSE.value}"
104
+ elif self.phase == ReasoningPhase.DECOMPOSING:
105
+ return f"{ThinkTag.DECOMPOSE_OPEN.value}\n{self.content}\n{ThinkTag.DECOMPOSE_CLOSE.value}"
106
+ elif self.phase == ReasoningPhase.MONITORING:
107
+ return f"{ThinkTag.MONITOR_OPEN.value}\n{self.content}\n{ThinkTag.MONITOR_CLOSE.value}"
108
+ elif self.phase == ReasoningPhase.PREDICTING:
109
+ return f"{ThinkTag.PREDICT_OPEN.value}\n{self.content}\n{ThinkTag.PREDICT_CLOSE.value}"
110
+ elif self.phase == ReasoningPhase.ADJUSTING:
111
+ return f"{ThinkTag.ADJUST_OPEN.value}\n{self.content}\n{ThinkTag.ADJUST_CLOSE.value}"
112
+ elif self.phase == ReasoningPhase.TOOL_USE:
113
+ tool_json = json.dumps({
114
+ "name": self.tool_name,
115
+ "input": self.tool_input,
116
+ "output": self.tool_output,
117
+ }, default=str)
118
+ return f"{ThinkTag.TOOL_OPEN.value}\n{tool_json}\n{ThinkTag.TOOL_CLOSE.value}"
119
+ elif self.phase == ReasoningPhase.ANSWERING:
120
+ return f"{ThinkTag.ANSWER_OPEN.value}\n{self.content}\n{ThinkTag.ANSWER_CLOSE.value}"
121
+ return self.content
122
+
123
+ def to_dict(self) -> Dict[str, Any]:
124
+ return {
125
+ "phase": self.phase.value,
126
+ "content": self.content,
127
+ "timestamp": self.timestamp,
128
+ "tool_name": self.tool_name,
129
+ "tool_input": str(self.tool_input) if self.tool_input else None,
130
+ "tool_output": str(self.tool_output) if self.tool_output else None,
131
+ "metadata": self.metadata,
132
+ }
133
+
134
+
135
+ # ============================================================================
136
+ # ReasoningEngine — motor de raciocínio
137
+ # ============================================================================
138
+
139
+ class ReasoningEngine:
140
+ """Motor de raciocínio com streaming, planejamento, e tool use.
141
+
142
+ Funcionalidades:
143
+ 1. Streaming de raciocínio via tags <think>, <plan>, <decompose>, etc.
144
+ 2. Planejamento: decompor problema em sub-tarefas
145
+ 3. Execução: processar sub-tarefas (com ou sem tools)
146
+ 4. Monitoramento: feedback de cada ação
147
+ 5. Predição: prever próximo estado
148
+ 6. Ajuste: corrigir baseado em predição vs realidade
149
+ 7. Tool use: chamar ferramentas via ToolAgentCoordinator
150
+ 8. Resposta: retornar resposta final
151
+
152
+ Compatibilidade:
153
+ - Ollama: tags <think> são preservadas no streaming
154
+ - LangChain: tool_calls seguem formato JSON
155
+ - LangGraph: estado flui entre nós do grafo
156
+ - vLLM: streaming via SSE (Server-Sent Events)
157
+
158
+ Uso:
159
+ >>> engine = ReasoningEngine()
160
+ >>> engine.register_tool("calculator", lambda x: eval(x))
161
+ >>> for chunk in engine.solve("What is 2+2?"):
162
+ ... print(chunk, end="", flush=True)
163
+ """
164
+
165
+ def __init__(
166
+ self,
167
+ max_thinking_steps: int = 20,
168
+ max_iterations: int = 5,
169
+ convergence_threshold: float = 0.9,
170
+ verbose: bool = False,
171
+ ):
172
+ self.max_thinking_steps = max_thinking_steps
173
+ self.max_iterations = max_iterations
174
+ self.convergence_threshold = convergence_threshold
175
+ self.verbose = verbose
176
+ # Componentes.
177
+ self.tool_coordinator = ToolAgentCoordinator(n_workers=4, verbose=verbose)
178
+ self.mcp = MCPConnection()
179
+ # Estado.
180
+ self.steps: List[ReasoningStep] = []
181
+ self.history: List[Dict[str, Any]] = []
182
+ # Callbacks (para integração com LLM externa).
183
+ self._llm_call: Optional[Callable[[str], str]] = None
184
+ self._llm_stream: Optional[Callable[[str], Iterator[str]]] = None
185
+
186
+ # ------------------------------------------------------------------
187
+ # Registro de ferramentas
188
+ # ------------------------------------------------------------------
189
+
190
+ def register_tool(
191
+ self,
192
+ name: str,
193
+ fn: Callable,
194
+ description: str = "",
195
+ timeout_s: float = 30.0,
196
+ failure_threshold: int = 5,
197
+ ) -> ToolWrapper:
198
+ """Registra uma ferramenta no engine."""
199
+ tool = self.tool_coordinator.register_tool(
200
+ name=name, fn=fn, description=description,
201
+ timeout_s=timeout_s, failure_threshold=failure_threshold,
202
+ )
203
+ self.mcp.register_tool(tool)
204
+ return tool
205
+
206
+ def unregister_tool(self, name: str) -> None:
207
+ self.tool_coordinator.unregister_tool(name)
208
+ self.mcp.unregister_tool(name)
209
+
210
+ def list_tools(self) -> List[str]:
211
+ return list(self.tool_coordinator._tools.keys())
212
+
213
+ # ------------------------------------------------------------------
214
+ # LLM integration
215
+ # ------------------------------------------------------------------
216
+
217
+ def set_llm(self, call_fn: Optional[Callable[[str], str]] = None,
218
+ stream_fn: Optional[Callable[[str], Iterator[str]]] = None) -> None:
219
+ """Configura LLM externa para geração de raciocínio.
220
+
221
+ Args:
222
+ call_fn: função que recebe prompt e retorna resposta completa
223
+ stream_fn: função que recebe prompt e retorna iterator de chunks
224
+ """
225
+ self._llm_call = call_fn
226
+ self._llm_stream = stream_fn
227
+
228
+ # ------------------------------------------------------------------
229
+ # Streaming de raciocínio
230
+ # ------------------------------------------------------------------
231
+
232
+ def solve(
233
+ self,
234
+ query: str,
235
+ use_tools: bool = True,
236
+ use_planning: bool = True,
237
+ ) -> Iterator[str]:
238
+ """Resolve uma query com streaming de raciocínio.
239
+
240
+ Gera tags <think>, <plan>, <decompose>, <tool_call>, <answer>
241
+ compatíveis com Ollama, LangChain, vLLM.
242
+
243
+ Args:
244
+ query: pergunta/requisição do usuário
245
+ use_tools: se True, usa ferramentas registradas
246
+ use_planning: se True, faz planejamento explícito
247
+
248
+ Yields: chunks de texto (tags + conteúdo)
249
+ """
250
+ self.steps = []
251
+ t0 = time.time()
252
+ # 1. THINK: analisa a query.
253
+ think_content = self._think(query)
254
+ step = ReasoningStep(
255
+ phase=ReasoningPhase.THINKING,
256
+ content=think_content,
257
+ metadata={"query": query},
258
+ )
259
+ self.steps.append(step)
260
+ yield step.to_tag() + "\n"
261
+
262
+ # 2. PLAN: planeja como resolver.
263
+ if use_planning:
264
+ plan_content = self._plan(query)
265
+ step = ReasoningStep(
266
+ phase=ReasoningPhase.PLANNING,
267
+ content=plan_content,
268
+ )
269
+ self.steps.append(step)
270
+ yield step.to_tag() + "\n"
271
+
272
+ # 3. DECOMPOSE: decompõe em sub-tarefas.
273
+ subtasks = self._decompose(query)
274
+ step = ReasoningStep(
275
+ phase=ReasoningPhase.DECOMPOSING,
276
+ content="\n".join(f"- {st}" for st in subtasks),
277
+ )
278
+ self.steps.append(step)
279
+ yield step.to_tag() + "\n"
280
+
281
+ # 4. EXECUTE + MONITOR + PREDICT + ADJUST (loop circular).
282
+ results = []
283
+ for i, subtask in enumerate(subtasks):
284
+ # EXECUTE.
285
+ exec_content, tool_output = self._execute_subtask(
286
+ subtask, use_tools=use_tools
287
+ )
288
+ step = ReasoningStep(
289
+ phase=ReasoningPhase.EXECUTING,
290
+ content=exec_content,
291
+ tool_output=tool_output,
292
+ )
293
+ self.steps.append(step)
294
+ yield f"<execute>\n{exec_content}\n</execute>\n"
295
+
296
+ # MONITOR.
297
+ mon_content = self._monitor(subtask, tool_output)
298
+ step = ReasoningStep(
299
+ phase=ReasoningPhase.MONITORING,
300
+ content=mon_content,
301
+ )
302
+ self.steps.append(step)
303
+ yield step.to_tag() + "\n"
304
+
305
+ # PREDICT.
306
+ pred_content = self._predict(subtask, tool_output)
307
+ step = ReasoningStep(
308
+ phase=ReasoningPhase.PREDICTING,
309
+ content=pred_content,
310
+ )
311
+ self.steps.append(step)
312
+ yield step.to_tag() + "\n"
313
+
314
+ # ADJUST.
315
+ adj_content = self._adjust(subtask, tool_output)
316
+ step = ReasoningStep(
317
+ phase=ReasoningPhase.ADJUSTING,
318
+ content=adj_content,
319
+ )
320
+ self.steps.append(step)
321
+ yield step.to_tag() + "\n"
322
+
323
+ results.append(tool_output)
324
+
325
+ # 5. ANSWER: compõe resposta final.
326
+ answer = self._compose_answer(query, results)
327
+ step = ReasoningStep(
328
+ phase=ReasoningPhase.ANSWERING,
329
+ content=answer,
330
+ metadata={"total_time_s": time.time() - t0},
331
+ )
332
+ self.steps.append(step)
333
+ yield step.to_tag() + "\n"
334
+
335
+ # Registra no histórico.
336
+ self.history.append({
337
+ "query": query,
338
+ "n_steps": len(self.steps),
339
+ "total_time_s": time.time() - t0,
340
+ "tools_used": [s.tool_name for s in self.steps if s.tool_name],
341
+ "answer": answer,
342
+ })
343
+
344
+ def solve_sync(
345
+ self,
346
+ query: str,
347
+ use_tools: bool = True,
348
+ use_planning: bool = True,
349
+ ) -> str:
350
+ """Versão síncrona de solve (retorna string completa)."""
351
+ return "".join(self.solve(query, use_tools, use_planning))
352
+
353
+ # ------------------------------------------------------------------
354
+ # Fases do raciocínio
355
+ # ------------------------------------------------------------------
356
+
357
+ def _think(self, query: str) -> str:
358
+ """Fase THINK: analisa a query."""
359
+ if self._llm_call:
360
+ prompt = f"Analyze this query and explain your reasoning:\n{query}"
361
+ return self._llm_call(prompt)
362
+ return (
363
+ f"Analisando a query: '{query}'\n"
364
+ f"Identificando o tipo de problema e requisitos.\n"
365
+ f"Determinando se ferramentas são necessárias."
366
+ )
367
+
368
+ def _plan(self, query: str) -> str:
369
+ """Fase PLAN: planeja como resolver."""
370
+ tools = self.list_tools()
371
+ tool_str = ", ".join(tools) if tools else "nenhuma"
372
+ return (
373
+ f"Plano de resolução:\n"
374
+ f"1. Decompor o problema em sub-tarefas\n"
375
+ f"2. Identificar ferramentas necessárias (disponíveis: {tool_str})\n"
376
+ f"3. Executar sub-tarefas em sequência\n"
377
+ f"4. Monitorar resultados\n"
378
+ f"5. Compor resposta final"
379
+ )
380
+
381
+ def _decompose(self, query: str) -> List[str]:
382
+ """Fase DECOMPOSE: decompõe em sub-tarefas."""
383
+ if self._llm_call:
384
+ prompt = f"Decompose this into subtasks (one per line):\n{query}"
385
+ result = self._llm_call(prompt)
386
+ return [line.strip("- ") for line in result.strip().split("\n") if line.strip()]
387
+ # Heurística: divide por palavras-chave.
388
+ if "?" in query:
389
+ parts = query.split("?")
390
+ subtasks = [f"Analisar: {parts[0].strip()}?"]
391
+ if len(parts) > 1 and parts[1].strip():
392
+ subtasks.append(f"Processar: {parts[1].strip()}")
393
+ subtasks.append("Compor resposta")
394
+ return subtasks
395
+ return [f"Processar: {query}"]
396
+
397
+ def _execute_subtask(
398
+ self,
399
+ subtask: str,
400
+ use_tools: bool = True,
401
+ ) -> Tuple[str, Optional[Any]]:
402
+ """Fase EXECUTE: executa uma sub-tarefa."""
403
+ # Verifica se alguma ferramenta pode ajudar.
404
+ if use_tools and self.list_tools():
405
+ # Tenta cada ferramenta.
406
+ for tool_name in self.list_tools():
407
+ try:
408
+ result = self.tool_coordinator.execute_tool(tool_name, subtask)
409
+ return (
410
+ f"Sub-tarefa '{subtask}' executada via ferramenta '{tool_name}'.\n"
411
+ f"Resultado: {result}",
412
+ result,
413
+ )
414
+ except Exception:
415
+ continue # ferramenta não aplicável, tenta próxima
416
+ # Sem ferramentas: usa LLM ou heurística.
417
+ if self._llm_call:
418
+ result = self._llm_call(f"Resolve: {subtask}")
419
+ return f"Sub-tarefa '{subtask}' resolvia via LLM.\nResultado: {result}", result
420
+ return f"Sub-tarefa '{subtask}' processada.", subtask
421
+
422
+ def _monitor(self, subtask: str, output: Any) -> str:
423
+ """Fase MONITOR: verifica resultado."""
424
+ if output is None:
425
+ return f"Monitor: sub-tarefa '{subtask}' produziu resultado vazio. ⚠"
426
+ return f"Monitor: sub-tarefa '{subtask}' produzida com sucesso. ✓"
427
+
428
+ def _predict(self, subtask: str, output: Any) -> str:
429
+ """Fase PREDICT: prediz próximo estado."""
430
+ return (
431
+ f"Predição: após '{subtask}', o estado esperado é consistente "
432
+ f"com o plano. Confiança: alta (determinístico)."
433
+ )
434
+
435
+ def _adjust(self, subtask: str, output: Any) -> str:
436
+ """Fase ADJUST: ajusta se necessário."""
437
+ if output is None:
438
+ return f"Ajuste: sub-tarefa '{subtask}' falhou. Replanejando..."
439
+ return f"Ajuste: nenhum ajuste necessário para '{subtask}'."
440
+
441
+ def _compose_answer(self, query: str, results: List[Any]) -> str:
442
+ """Fase ANSWER: compõe resposta final."""
443
+ if not results:
444
+ return f"Não foi possível resolver: '{query}'"
445
+ if len(results) == 1:
446
+ return str(results[0])
447
+ # Compõe a partir de resultados.
448
+ parts = [str(r) for r in results if r is not None]
449
+ if self._llm_call:
450
+ prompt = f"Based on these results, answer the query:\nQuery: {query}\nResults: {parts}"
451
+ return self._llm_call(prompt)
452
+ return "\n".join(parts)
453
+
454
+ # ------------------------------------------------------------------
455
+ # Parse de tags (para integração com LLM externa)
456
+ # ------------------------------------------------------------------
457
+
458
+ @staticmethod
459
+ def parse_thinking(text: str) -> Dict[str, Any]:
460
+ """Extrai tags de raciocínio de um texto.
461
+
462
+ Compatível com saídas de Ollama, vLLM, LangChain.
463
+
464
+ Retorna: {think: str, plan: str, decompose: str, tool_calls: list, answer: str}
465
+ """
466
+ result = {
467
+ "think": "",
468
+ "plan": "",
469
+ "decompose": "",
470
+ "tool_calls": [],
471
+ "answer": "",
472
+ "raw": text,
473
+ }
474
+ # <think>...</think>
475
+ think_match = re.search(r"<think>(.*?)</think>", text, re.DOTALL)
476
+ if think_match:
477
+ result["think"] = think_match.group(1).strip()
478
+ # <plan>...</plan>
479
+ plan_match = re.search(r"<plan>(.*?)</plan>", text, re.DOTALL)
480
+ if plan_match:
481
+ result["plan"] = plan_match.group(1).strip()
482
+ # <decompose>...</decompose>
483
+ decompose_match = re.search(r"<decompose>(.*?)</decompose>", text, re.DOTALL)
484
+ if decompose_match:
485
+ result["decompose"] = decompose_match.group(1).strip()
486
+ # <tool_call>...</tool_call> (pode haver múltiplos)
487
+ tool_matches = re.findall(r"<tool_call>(.*?)</tool_call>", text, re.DOTALL)
488
+ for tm in tool_matches:
489
+ try:
490
+ result["tool_calls"].append(json.loads(tm.strip()))
491
+ except json.JSONDecodeError:
492
+ result["tool_calls"].append({"raw": tm.strip()})
493
+ # <answer>...</answer>
494
+ answer_match = re.search(r"<answer>(.*?)</answer>", text, re.DOTALL)
495
+ if answer_match:
496
+ result["answer"] = answer_match.group(1).strip()
497
+ return result
498
+
499
+ # ------------------------------------------------------------------
500
+ # Estatísticas
501
+ # ------------------------------------------------------------------
502
+
503
+ def get_stats(self) -> Dict[str, Any]:
504
+ return {
505
+ "n_steps": len(self.steps),
506
+ "n_history": len(self.history),
507
+ "tools": self.list_tools(),
508
+ "tool_stats": self.tool_coordinator.get_all_stats(),
509
+ "phases_used": list(set(s.phase.value for s in self.steps)),
510
+ }
511
+
512
+ def get_steps(self) -> List[Dict[str, Any]]:
513
+ return [s.to_dict() for s in self.steps]
514
+
515
+ def summary(self) -> str:
516
+ lines = [f"ReasoningEngine:"]
517
+ lines.append(f" Steps: {len(self.steps)}")
518
+ lines.append(f" History: {len(self.history)} queries")
519
+ lines.append(f" Tools: {self.list_tools()}")
520
+ for s in self.steps:
521
+ lines.append(f" [{s.phase.value}] {s.content[:80]}...")
522
+ return "\n".join(lines)
src/bigru_t/reasoning/tool_agent.py ADDED
@@ -0,0 +1,826 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ tool_agent — Agente Especializado para Ferramentas (Tools).
3
+
4
+ Implementa:
5
+ - 2.1. Memória individualizada de instruções e dados por ferramenta
6
+ - 2.2. Suporte Model Context Protocol (MCP)
7
+ - 2.3. Resiliência: falha isolada, restart, circuit breaker
8
+ - 2.3.1. Arquitetura distribuída otimizada (análise matemática)
9
+
10
+ Arquitetura recomendada (análise):
11
+ - Hybrid: 1 Agente Coordenador + N Agentes Especialistas (1 por ferramenta)
12
+ - Vantagens sobre Multi-Agent (1 agente p/ tudo) e Single-Agent (1 p/ todas):
13
+ * Isolamento de falhas (1 ferramenta falha → só aquele agente reinicia)
14
+ * Especialização (cada agente tem memória otimizada para sua ferramenta)
15
+ * Paralelismo (agentes independentes rodam em paralelo)
16
+ * Escalabilidade (adicionar ferramenta = adicionar agente)
17
+
18
+ Matemática da arquitetura:
19
+ - Latência esperada: T = max_i(T_i) + T_coord (paralelo + coordenação)
20
+ - Vs Single-Agent: T_single = Σ T_i (sequencial)
21
+ - Speedup: S = Σ T_i / (max T_i + T_coord) ≈ N / (1 + T_coord/max T_i)
22
+ - Quando T_coord << max T_i: S → N (speedup linear)
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import asyncio
28
+ import hashlib
29
+ import json
30
+ import os
31
+ import time
32
+ import threading
33
+ from collections import defaultdict, deque
34
+ from concurrent.futures import Future, ThreadPoolExecutor, as_completed
35
+ from dataclasses import dataclass, field
36
+ from enum import Enum
37
+ from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
38
+
39
+ import torch
40
+ import torch.nn as nn
41
+
42
+
43
+ # ============================================================================
44
+ # Exceções
45
+ # ============================================================================
46
+
47
+ class ToolError(RuntimeError):
48
+ """Erro genérico de ferramenta."""
49
+
50
+
51
+ class ToolTimeoutError(ToolError):
52
+ """Timeout ao executar ferramenta."""
53
+
54
+
55
+ class ToolCircuitBreakerOpen(ToolError):
56
+ """Circuit breaker aberto — ferramenta em estado de falha."""
57
+
58
+
59
+ class MCPConnectionError(ToolError):
60
+ """Erro de conexão MCP."""
61
+
62
+
63
+ class ToolMemoryError(ToolError):
64
+ """Erro de memória da ferramenta."""
65
+
66
+
67
+ # ============================================================================
68
+ # 2.1. ToolMemory — memória individualizada por ferramenta
69
+ # ============================================================================
70
+
71
+ class ToolMemory:
72
+ """Memória individualizada de instruções e dados por ferramenta.
73
+
74
+ Cada ferramenta tem sua própria ToolMemory, contendo:
75
+ - instructions: instruções de uso (templates, exemplos)
76
+ - data_cache: cache de resultados anteriores (key → value)
77
+ - error_history: histórico de erros (para diagnóstico)
78
+ - usage_stats: estatísticas de uso (n_calls, n_success, n_failures)
79
+
80
+ Persistência: salva/carrega de disco (JSON).
81
+ """
82
+
83
+ def __init__(
84
+ self,
85
+ tool_name: str,
86
+ max_cache_size: int = 1000,
87
+ max_instructions: int = 100,
88
+ max_error_history: int = 50,
89
+ persist_path: Optional[str] = None,
90
+ ):
91
+ self.tool_name = tool_name
92
+ self.max_cache_size = max_cache_size
93
+ self.max_instructions = max_instructions
94
+ self.max_error_history = max_error_history
95
+ self.persist_path = persist_path
96
+ self._lock = threading.Lock()
97
+ # Estado.
98
+ self.instructions: List[Dict[str, Any]] = []
99
+ self.data_cache: Dict[str, Any] = {} # key → cached result
100
+ self.error_history: deque = deque(maxlen=max_error_history)
101
+ self.usage_stats = {
102
+ "n_calls": 0,
103
+ "n_success": 0,
104
+ "n_failures": 0,
105
+ "total_time_s": 0.0,
106
+ "avg_time_s": 0.0,
107
+ }
108
+ # Carrega do disco se disponível.
109
+ if persist_path and os.path.exists(persist_path):
110
+ self.load()
111
+
112
+ def add_instruction(
113
+ self,
114
+ instruction: str,
115
+ context: Optional[Dict[str, Any]] = None,
116
+ priority: int = 0,
117
+ ) -> None:
118
+ """Adiciona instrução de uso."""
119
+ with self._lock:
120
+ entry = {
121
+ "instruction": instruction,
122
+ "context": context or {},
123
+ "priority": priority,
124
+ "timestamp": time.time(),
125
+ }
126
+ self.instructions.append(entry)
127
+ # Ordena por prioridade (maior = mais importante).
128
+ self.instructions.sort(key=lambda x: -x["priority"])
129
+ # Limita tamanho.
130
+ if len(self.instructions) > self.max_instructions:
131
+ self.instructions = self.instructions[:self.max_instructions]
132
+ self._maybe_persist()
133
+
134
+ def get_instructions(
135
+ self,
136
+ context_filter: Optional[Dict[str, Any]] = None,
137
+ top_k: int = 10,
138
+ ) -> List[Dict[str, Any]]:
139
+ """Recupera instruções relevantes."""
140
+ with self._lock:
141
+ if context_filter is None:
142
+ return self.instructions[:top_k]
143
+ # Filtra por contexto.
144
+ filtered = [
145
+ inst for inst in self.instructions
146
+ if all(inst["context"].get(k) == v for k, v in context_filter.items())
147
+ ]
148
+ return filtered[:top_k]
149
+
150
+ def cache_result(self, key: str, value: Any, ttl: float = 3600) -> None:
151
+ """Cacheia resultado com TTL (time-to-live)."""
152
+ with self._lock:
153
+ if len(self.data_cache) >= self.max_cache_size:
154
+ # Remove entrada mais antiga (FIFO).
155
+ oldest_key = next(iter(self.data_cache))
156
+ del self.data_cache[oldest_key]
157
+ self.data_cache[key] = {
158
+ "value": value,
159
+ "timestamp": time.time(),
160
+ "ttl": ttl,
161
+ }
162
+ self._maybe_persist()
163
+
164
+ def get_cached(self, key: str) -> Optional[Any]:
165
+ """Recupera resultado do cache se não expirou."""
166
+ with self._lock:
167
+ if key not in self.data_cache:
168
+ return None
169
+ entry = self.data_cache[key]
170
+ if time.time() - entry["timestamp"] > entry["ttl"]:
171
+ del self.data_cache[key]
172
+ return None
173
+ return entry["value"]
174
+
175
+ def record_error(self, error: str, context: Optional[Dict] = None) -> None:
176
+ """Registra erro no histórico."""
177
+ with self._lock:
178
+ self.error_history.append({
179
+ "error": error,
180
+ "context": context or {},
181
+ "timestamp": time.time(),
182
+ })
183
+
184
+ def record_call(self, success: bool, duration_s: float) -> None:
185
+ """Registra estatísticas de uso."""
186
+ with self._lock:
187
+ self.usage_stats["n_calls"] += 1
188
+ if success:
189
+ self.usage_stats["n_success"] += 1
190
+ else:
191
+ self.usage_stats["n_failures"] += 1
192
+ self.usage_stats["total_time_s"] += duration_s
193
+ n = self.usage_stats["n_calls"]
194
+ self.usage_stats["avg_time_s"] = self.usage_stats["total_time_s"] / n
195
+
196
+ def get_stats(self) -> Dict[str, Any]:
197
+ """Retorna estatísticas de uso."""
198
+ with self._lock:
199
+ return {
200
+ **self.usage_stats,
201
+ "cache_size": len(self.data_cache),
202
+ "instructions_count": len(self.instructions),
203
+ "error_count": len(self.error_history),
204
+ "success_rate": (
205
+ self.usage_stats["n_success"] / max(self.usage_stats["n_calls"], 1)
206
+ ),
207
+ }
208
+
209
+ def clear_cache(self) -> None:
210
+ """Limpa cache."""
211
+ with self._lock:
212
+ self.data_cache.clear()
213
+
214
+ def save(self) -> None:
215
+ """Salva estado em disco."""
216
+ if not self.persist_path:
217
+ return
218
+ os.makedirs(os.path.dirname(self.persist_path), exist_ok=True)
219
+ data = {
220
+ "tool_name": self.tool_name,
221
+ "instructions": self.instructions,
222
+ "usage_stats": self.usage_stats,
223
+ "error_history": list(self.error_history),
224
+ }
225
+ with open(self.persist_path, "w") as f:
226
+ json.dump(data, f, indent=2, default=str)
227
+
228
+ def load(self) -> None:
229
+ """Carrega estado do disco."""
230
+ if not self.persist_path or not os.path.exists(self.persist_path):
231
+ return
232
+ with open(self.persist_path) as f:
233
+ data = json.load(f)
234
+ self.instructions = data.get("instructions", [])
235
+ self.usage_stats = data.get("usage_stats", self.usage_stats)
236
+ self.error_history = deque(
237
+ data.get("error_history", []),
238
+ maxlen=self.max_error_history,
239
+ )
240
+
241
+ def _maybe_persist(self) -> None:
242
+ if self.persist_path:
243
+ self.save()
244
+
245
+
246
+ # ============================================================================
247
+ # 2.2. MCP (Model Context Protocol) — conexão e contexto
248
+ # ============================================================================
249
+
250
+ @dataclass
251
+ class MCPMessage:
252
+ """Mensagem no formato Model Context Protocol."""
253
+ role: str # 'user', 'assistant', 'tool', 'system'
254
+ content: str
255
+ tool_name: Optional[str] = None
256
+ tool_call_id: Optional[str] = None
257
+ metadata: Dict[str, Any] = field(default_factory=dict)
258
+
259
+
260
+ @dataclass
261
+ class MCPContext:
262
+ """Contexto MCP para uma sessão."""
263
+ session_id: str
264
+ messages: List[MCPMessage] = field(default_factory=list)
265
+ active_tools: Set[str] = field(default_factory=set)
266
+ shared_state: Dict[str, Any] = field(default_factory=dict)
267
+
268
+ def add_message(self, msg: MCPMessage) -> None:
269
+ self.messages.append(msg)
270
+
271
+ def get_context_window(self, max_messages: int = 20) -> List[MCPMessage]:
272
+ """Retorna as últimas max_messages mensagens."""
273
+ return self.messages[-max_messages:]
274
+
275
+ def set_shared(self, key: str, value: Any) -> None:
276
+ self.shared_state[key] = value
277
+
278
+ def get_shared(self, key: str, default: Any = None) -> Any:
279
+ return self.shared_state.get(key, default)
280
+
281
+
282
+ class MCPConnection:
283
+ """Conexão MCP entre agente e ferramentas.
284
+
285
+ Permite:
286
+ - Registrar ferramentas (tools)
287
+ - Enviar/receber mensagens
288
+ - Compartilhar estado entre ferramentas
289
+ - Gerenciar contexto da sessão
290
+ """
291
+
292
+ def __init__(self, session_id: Optional[str] = None):
293
+ self.session_id = session_id or hashlib.md5(
294
+ str(time.time()).encode()
295
+ ).hexdigest()[:12]
296
+ self.context = MCPContext(session_id=self.session_id)
297
+ self._tools: Dict[str, "ToolWrapper"] = {}
298
+ self._lock = threading.Lock()
299
+
300
+ def register_tool(self, tool: "ToolWrapper") -> None:
301
+ with self._lock:
302
+ self._tools[tool.name] = tool
303
+ self.context.active_tools.add(tool.name)
304
+
305
+ def unregister_tool(self, name: str) -> None:
306
+ with self._lock:
307
+ self._tools.pop(name, None)
308
+ self.context.active_tools.discard(name)
309
+
310
+ def get_tool(self, name: str) -> Optional["ToolWrapper"]:
311
+ return self._tools.get(name)
312
+
313
+ def list_tools(self) -> List[str]:
314
+ return list(self._tools.keys())
315
+
316
+ def send_message(
317
+ self,
318
+ role: str,
319
+ content: str,
320
+ tool_name: Optional[str] = None,
321
+ metadata: Optional[Dict] = None,
322
+ ) -> MCPMessage:
323
+ """Envia mensagem no contexto MCP."""
324
+ msg = MCPMessage(
325
+ role=role, content=content,
326
+ tool_name=tool_name, metadata=metadata or {},
327
+ )
328
+ self.context.add_message(msg)
329
+ return msg
330
+
331
+ def get_context_window(self, max_messages: int = 20) -> List[MCPMessage]:
332
+ return self.context.get_context_window(max_messages)
333
+
334
+ def set_shared_state(self, key: str, value: Any) -> None:
335
+ self.context.set_shared(key, value)
336
+
337
+ def get_shared_state(self, key: str, default: Any = None) -> Any:
338
+ return self.context.get_shared(key, default)
339
+
340
+
341
+ # ============================================================================
342
+ # 2.3. CircuitBreaker — resiliência à falhas
343
+ # ============================================================================
344
+
345
+ class CircuitState(Enum):
346
+ CLOSED = "closed" # Funcionando normalmente
347
+ OPEN = "open" # Falhando, rejeita chamadas
348
+ HALF_OPEN = "half_open" # Testando se recuperou
349
+
350
+
351
+ class CircuitBreaker:
352
+ """Circuit breaker para uma ferramenta.
353
+
354
+ Estados:
355
+ - CLOSED: chamadas passam normalmente. Conta falhas.
356
+ - OPEN: após N falhas consecutivas, rejeita todas as chamadas.
357
+ - HALF_OPEN: após timeout, permite 1 chamada de teste.
358
+ Se sucesso → CLOSED. Se falha → OPEN.
359
+
360
+ Matemática:
361
+ - P(falha) = n_failures / n_calls
362
+ - Threshold: se P(falha) > θ → OPEN
363
+ - Recovery: após T_recovery segundos → HALF_OPEN
364
+ """
365
+
366
+ def __init__(
367
+ self,
368
+ failure_threshold: int = 5,
369
+ recovery_timeout_s: float = 30.0,
370
+ half_open_max_calls: int = 1,
371
+ verbose: bool = False,
372
+ ):
373
+ self.failure_threshold = failure_threshold
374
+ self.recovery_timeout_s = recovery_timeout_s
375
+ self.half_open_max_calls = half_open_max_calls
376
+ self.verbose = verbose
377
+ self._state = CircuitState.CLOSED
378
+ self._failure_count = 0
379
+ self._success_count = 0
380
+ self._last_failure_time = 0.0
381
+ self._half_open_calls = 0
382
+ self._lock = threading.Lock()
383
+
384
+ @property
385
+ def state(self) -> CircuitState:
386
+ with self._lock:
387
+ if self._state == CircuitState.OPEN:
388
+ # Verifica se deve transitar para HALF_OPEN.
389
+ if time.time() - self._last_failure_time > self.recovery_timeout_s:
390
+ self._state = CircuitState.HALF_OPEN
391
+ self._half_open_calls = 0
392
+ if self.verbose:
393
+ print(f" CircuitBreaker: OPEN → HALF_OPEN")
394
+ return self._state
395
+
396
+ def can_execute(self) -> bool:
397
+ """Verifica se a chamada pode prosseguir."""
398
+ state = self.state
399
+ if state == CircuitState.CLOSED:
400
+ return True
401
+ if state == CircuitState.HALF_OPEN:
402
+ with self._lock:
403
+ if self._half_open_calls < self.half_open_max_calls:
404
+ self._half_open_calls += 1
405
+ return True
406
+ return False
407
+ return False # OPEN
408
+
409
+ def record_success(self) -> None:
410
+ """Registra sucesso."""
411
+ with self._lock:
412
+ if self._state == CircuitState.HALF_OPEN:
413
+ self._success_count += 1
414
+ self._state = CircuitState.CLOSED
415
+ self._failure_count = 0
416
+ if self.verbose:
417
+ print(f" CircuitBreaker: HALF_OPEN → CLOSED (recuperou)")
418
+ elif self._state == CircuitState.CLOSED:
419
+ self._failure_count = 0 # reset consecutive failures
420
+
421
+ def record_failure(self) -> None:
422
+ """Registra falha."""
423
+ with self._lock:
424
+ self._failure_count += 1
425
+ self._last_failure_time = time.time()
426
+ if self._state == CircuitState.HALF_OPEN:
427
+ self._state = CircuitState.OPEN
428
+ if self.verbose:
429
+ print(f" CircuitBreaker: HALF_OPEN → OPEN (falhou no teste)")
430
+ elif self._state == CircuitState.CLOSED:
431
+ if self._failure_count >= self.failure_threshold:
432
+ self._state = CircuitState.OPEN
433
+ if self.verbose:
434
+ print(f" CircuitBreaker: CLOSED → OPEN "
435
+ f"({self._failure_count} falhas consecutivas)")
436
+
437
+ def reset(self) -> None:
438
+ """Reseta para CLOSED."""
439
+ with self._lock:
440
+ self._state = CircuitState.CLOSED
441
+ self._failure_count = 0
442
+ self._success_count = 0
443
+ self._half_open_calls = 0
444
+
445
+ def get_state(self) -> Dict[str, Any]:
446
+ return {
447
+ "state": self.state.value,
448
+ "failure_count": self._failure_count,
449
+ "success_count": self._success_count,
450
+ "failure_threshold": self.failure_threshold,
451
+ "recovery_timeout_s": self.recovery_timeout_s,
452
+ }
453
+
454
+
455
+ # ============================================================================
456
+ # 2.3. ToolWrapper — envolve ferramenta com memória + circuit breaker
457
+ # ============================================================================
458
+
459
+ class ToolWrapper:
460
+ """Envolve uma ferramenta (callable) com:
461
+ - ToolMemory (memória individualizada)
462
+ - CircuitBreaker (resiliência)
463
+ - Timeout (evita hang)
464
+ - Cache (evita recomputação)
465
+
466
+ Uma ferramenta é qualquer callable: fn(input) -> output.
467
+ """
468
+
469
+ def __init__(
470
+ self,
471
+ name: str,
472
+ fn: Callable,
473
+ description: str = "",
474
+ timeout_s: float = 30.0,
475
+ enable_cache: bool = True,
476
+ enable_circuit_breaker: bool = True,
477
+ failure_threshold: int = 5,
478
+ recovery_timeout_s: float = 30.0,
479
+ persist_path: Optional[str] = None,
480
+ verbose: bool = False,
481
+ ):
482
+ self.name = name
483
+ self.fn = fn
484
+ self.description = description
485
+ self.timeout_s = timeout_s
486
+ self.verbose = verbose
487
+ # Componentes.
488
+ self.memory = ToolMemory(
489
+ tool_name=name,
490
+ persist_path=persist_path,
491
+ )
492
+ self.circuit_breaker = CircuitBreaker(
493
+ failure_threshold=failure_threshold,
494
+ recovery_timeout_s=recovery_timeout_s,
495
+ verbose=verbose,
496
+ ) if enable_circuit_breaker else None
497
+ self.enable_cache = enable_cache
498
+
499
+ def execute(
500
+ self,
501
+ input_data: Any,
502
+ cache_key: Optional[str] = None,
503
+ use_cache: bool = True,
504
+ ) -> Any:
505
+ """Executa a ferramenta com resiliência.
506
+
507
+ Args:
508
+ input_data: input para a ferramenta
509
+ cache_key: chave para cache (None = sem cache)
510
+ use_cache: se True, tenta cache antes de executar
511
+
512
+ Returns: resultado da ferramenta
513
+
514
+ Raises:
515
+ ToolCircuitBreakerOpen: se circuit breaker está OPEN
516
+ ToolTimeoutError: se timeout
517
+ ToolError: se a ferramenta falha
518
+ """
519
+ # 1. Verifica circuit breaker.
520
+ if self.circuit_breaker and not self.circuit_breaker.can_execute():
521
+ raise ToolCircuitBreakerOpen(
522
+ f"Ferramenta '{self.name}' em circuit breaker OPEN "
523
+ f"(estado: {self.circuit_breaker.state.value})"
524
+ )
525
+ # 2. Verifica cache.
526
+ if self.enable_cache and use_cache and cache_key:
527
+ cached = self.memory.get_cached(cache_key)
528
+ if cached is not None:
529
+ if self.verbose:
530
+ print(f" Tool '{self.name}': cache hit ({cache_key})")
531
+ return cached
532
+ # 3. Executa com timeout.
533
+ t0 = time.time()
534
+ success = False
535
+ try:
536
+ result = self._execute_with_timeout(input_data)
537
+ success = True
538
+ duration = time.time() - t0
539
+ # 4. Cache resultado.
540
+ if self.enable_cache and cache_key:
541
+ self.memory.cache_result(cache_key, result)
542
+ # 5. Registra sucesso.
543
+ if self.circuit_breaker:
544
+ self.circuit_breaker.record_success()
545
+ self.memory.record_call(success=True, duration_s=duration)
546
+ return result
547
+ except ToolTimeoutError:
548
+ duration = time.time() - t0
549
+ self.memory.record_error("timeout", {"input": str(input_data)[:100]})
550
+ self.memory.record_call(success=False, duration_s=duration)
551
+ if self.circuit_breaker:
552
+ self.circuit_breaker.record_failure()
553
+ raise
554
+ except Exception as e:
555
+ duration = time.time() - t0
556
+ self.memory.record_error(str(e), {"input": str(input_data)[:100]})
557
+ self.memory.record_call(success=False, duration_s=duration)
558
+ if self.circuit_breaker:
559
+ self.circuit_breaker.record_failure()
560
+ raise ToolError(f"Ferramenta '{self.name}' falhou: {e}") from e
561
+
562
+ def _execute_with_timeout(self, input_data: Any) -> Any:
563
+ """Executa fn com timeout via ThreadPoolExecutor."""
564
+ future = ThreadPoolExecutor(max_workers=1).submit(self.fn, input_data)
565
+ try:
566
+ return future.result(timeout=self.timeout_s)
567
+ except TimeoutError:
568
+ raise ToolTimeoutError(
569
+ f"Ferramenta '{self.name}' timeout após {self.timeout_s}s"
570
+ )
571
+
572
+ def get_stats(self) -> Dict[str, Any]:
573
+ stats = self.memory.get_stats()
574
+ if self.circuit_breaker:
575
+ stats["circuit_breaker"] = self.circuit_breaker.get_state()
576
+ return stats
577
+
578
+ def restart(self) -> None:
579
+ """Reinicia a ferramenta (reset circuit breaker + clear cache)."""
580
+ if self.circuit_breaker:
581
+ self.circuit_breaker.reset()
582
+ self.memory.clear_cache()
583
+ if self.verbose:
584
+ print(f" Tool '{self.name}': reiniciada")
585
+
586
+
587
+ # ============================================================================
588
+ # 2.3.1. ToolAgentCoordinator — arquitetura distribuída otimizada
589
+ # ============================================================================
590
+
591
+ class ToolAgentCoordinator:
592
+ """Coordenador de Agentes de Ferramentas (arquitetura híbrida).
593
+
594
+ Arquitetura: 1 Coordenador + N Agentes Especialistas (1 por ferramenta).
595
+
596
+ Análise matemática da arquitetura:
597
+ - Single-Agent (1 agente, N ferramentas): T = Σ T_i (sequencial)
598
+ - Multi-Agent (N agentes, 1 ferramenta cada): T = max(T_i) + T_coord
599
+ - Hybrid (este): T = max(T_i) + T_coord, com isolamento de falhas
600
+
601
+ Quando T_coord << max(T_i): speedup ≈ N.
602
+ Isolamento: se ferramenta i falha, só agente i reinicia (não afeta outros).
603
+
604
+ O Coordenador:
605
+ 1. Roteia requisições para o agente especialista apropriado
606
+ 2. Agrega resultados
607
+ 3. Gerencia resiliência (restart de agentes falhos)
608
+ 4. Mantém contexto MCP compartilhado
609
+ """
610
+
611
+ def __init__(
612
+ self,
613
+ n_workers: Optional[int] = None,
614
+ verbose: bool = False,
615
+ ):
616
+ self.n_workers = n_workers or min(4, os.cpu_count() or 4)
617
+ self.verbose = verbose
618
+ self._tools: Dict[str, ToolWrapper] = {}
619
+ self._mcp = MCPConnection()
620
+ self._executor = ThreadPoolExecutor(max_workers=self.n_workers)
621
+ self._lock = threading.Lock()
622
+
623
+ def register_tool(
624
+ self,
625
+ name: str,
626
+ fn: Callable,
627
+ description: str = "",
628
+ timeout_s: float = 30.0,
629
+ failure_threshold: int = 5,
630
+ recovery_timeout_s: float = 30.0,
631
+ ) -> ToolWrapper:
632
+ """Registra uma ferramenta."""
633
+ tool = ToolWrapper(
634
+ name=name, fn=fn, description=description,
635
+ timeout_s=timeout_s,
636
+ failure_threshold=failure_threshold,
637
+ recovery_timeout_s=recovery_timeout_s,
638
+ verbose=self.verbose,
639
+ )
640
+ with self._lock:
641
+ self._tools[name] = tool
642
+ self._mcp.register_tool(tool)
643
+ if self.verbose:
644
+ print(f" Coordenador: ferramenta '{name}' registrada")
645
+ return tool
646
+
647
+ def unregister_tool(self, name: str) -> None:
648
+ with self._lock:
649
+ self._tools.pop(name, None)
650
+ self._mcp.unregister_tool(name)
651
+
652
+ def execute_tool(
653
+ self,
654
+ name: str,
655
+ input_data: Any,
656
+ cache_key: Optional[str] = None,
657
+ ) -> Any:
658
+ """Executa uma ferramenta específica."""
659
+ tool = self._tools.get(name)
660
+ if tool is None:
661
+ raise ToolError(f"Ferramenta '{name}' não registrada")
662
+ return tool.execute(input_data, cache_key=cache_key)
663
+
664
+ def execute_parallel(
665
+ self,
666
+ requests: List[Tuple[str, Any]],
667
+ fail_fast: bool = False,
668
+ ) -> Dict[str, Any]:
669
+ """Executa múltiplas ferramentas em paralelo.
670
+
671
+ Args:
672
+ requests: lista de (tool_name, input_data)
673
+ fail_fast: se True, primeira falha cancela todas
674
+
675
+ Retorna: {tool_name: result} (ou {tool_name: error})
676
+ """
677
+ results: Dict[str, Any] = {}
678
+ futures: Dict[Future, str] = {}
679
+ for tool_name, input_data in requests:
680
+ tool = self._tools.get(tool_name)
681
+ if tool is None:
682
+ results[tool_name] = ToolError(f"Ferramenta '{tool_name}' não registrada")
683
+ continue
684
+ # Submete.
685
+ fut = self._executor.submit(self._safe_execute, tool_name, input_data)
686
+ futures[fut] = tool_name
687
+ # Coleta.
688
+ for fut in as_completed(futures):
689
+ tool_name = futures[fut]
690
+ try:
691
+ result = fut.result()
692
+ results[tool_name] = result
693
+ except Exception as e:
694
+ results[tool_name] = e
695
+ if fail_fast:
696
+ # Cancela restantes.
697
+ for f in futures:
698
+ f.cancel()
699
+ break
700
+ return results
701
+
702
+ def _safe_execute(self, tool_name: str, input_data: Any) -> Any:
703
+ """Executa ferramenta com tratamento de erro."""
704
+ try:
705
+ return self.execute_tool(tool_name, input_data)
706
+ except ToolCircuitBreakerOpen:
707
+ # Tenta restart.
708
+ if self.verbose:
709
+ print(f" Coordenador: restart da ferramenta '{tool_name}'")
710
+ tool = self._tools[tool_name]
711
+ tool.restart()
712
+ # Tenta novamente após restart.
713
+ return self.execute_tool(tool_name, input_data)
714
+ except Exception as e:
715
+ if self.verbose:
716
+ print(f" Coordenador: ferramenta '{tool_name}' falhou: {e}")
717
+ raise
718
+
719
+ def execute_with_fallback(
720
+ self,
721
+ primary_tool: str,
722
+ fallback_tool: str,
723
+ input_data: Any,
724
+ ) -> Any:
725
+ """Executa ferramenta primária; se falhar, usa fallback."""
726
+ try:
727
+ return self.execute_tool(primary_tool, input_data)
728
+ except (ToolError, ToolCircuitBreakerOpen, ToolTimeoutError) as e:
729
+ if self.verbose:
730
+ print(f" Coordenador: '{primary_tool}' falhou ({e}), "
731
+ f"usando fallback '{fallback_tool}'")
732
+ return self.execute_tool(fallback_tool, input_data)
733
+
734
+ def get_all_stats(self) -> Dict[str, Dict[str, Any]]:
735
+ """Estatísticas de todas as ferramentas."""
736
+ return {name: tool.get_stats() for name, tool in self._tools.items()}
737
+
738
+ def get_mcp_context(self, max_messages: int = 20) -> List[MCPMessage]:
739
+ """Retorna contexto MCP."""
740
+ return self._mcp.get_context_window(max_messages)
741
+
742
+ def restart_all(self) -> None:
743
+ """Reinicia todas as ferramentas."""
744
+ for tool in self._tools.values():
745
+ tool.restart()
746
+
747
+ def summary(self) -> str:
748
+ lines = [f"ToolAgentCoordinator ({len(self._tools)} ferramentas):"]
749
+ for name, tool in self._tools.items():
750
+ stats = tool.get_stats()
751
+ cb_state = stats.get("circuit_breaker", {}).get("state", "N/A")
752
+ lines.append(
753
+ f" {name}: calls={stats['n_calls']}, "
754
+ f"success_rate={stats['success_rate']:.1%}, "
755
+ f"avg_time={stats['avg_time_time_s' if 'avg_time_time_s' in stats else 'avg_time_s']:.3f}s, "
756
+ f"circuit={cb_state}"
757
+ )
758
+ return "\n".join(lines)
759
+
760
+ def close(self) -> None:
761
+ """Fecha executor."""
762
+ self._executor.shutdown(wait=True)
763
+
764
+
765
+ # ============================================================================
766
+ # 2.3.1. Arquitetura — análise matemática
767
+ # ============================================================================
768
+
769
+ def analyze_architecture(
770
+ n_tools: int,
771
+ tool_latencies: List[float],
772
+ coord_overhead_s: float = 0.01,
773
+ ) -> Dict[str, Any]:
774
+ """Analisa 3 arquiteturas e recomenda a melhor.
775
+
776
+ Arquiteturas:
777
+ 1. Single-Agent: 1 agente executa todas N ferramentas sequencialmente
778
+ T = Σ T_i
779
+ 2. Multi-Agent: N agentes, 1 ferramenta cada, em paralelo
780
+ T = max(T_i) + T_coord
781
+ 3. Hybrid (Coordinator + N Specialists): mesmo que Multi-Agent mas com
782
+ isolamento de falhas e memória individualizada
783
+ T = max(T_i) + T_coord (mesmo tempo, mais resiliência)
784
+
785
+ Args:
786
+ n_tools: número de ferramentas
787
+ tool_latencies: latência esperada de cada ferramenta (s)
788
+ coord_overhead_s: overhead de coordenação (s)
789
+
790
+ Retorna: análise com recomendação
791
+ """
792
+ assert len(tool_latencies) == n_tools
793
+ total_seq = sum(tool_latencies)
794
+ max_lat = max(tool_latencies)
795
+ # Single-Agent.
796
+ t_single = total_seq
797
+ # Multi-Agent / Hybrid.
798
+ t_parallel = max_lat + coord_overhead_s
799
+ speedup = t_single / t_parallel if t_parallel > 0 else 0
800
+ # Recomendação.
801
+ if speedup > 1.5:
802
+ recommendation = "Hybrid (Coordinator + N Specialists)"
803
+ reason = f"Speedup {speedup:.1f}× justifica overhead de coordenação"
804
+ elif n_tools <= 2:
805
+ recommendation = "Single-Agent"
806
+ reason = f"Poucas ferramentas ({n_tools}), overhead não compensa"
807
+ else:
808
+ recommendation = "Hybrid"
809
+ reason = f"Isolamento de falhas importante para {n_tools} ferramentas"
810
+ # Análise de resiliência.
811
+ # Em Single-Agent: 1 falha derruba tudo (P(falha total) = 1 - ∏(1-p_i))
812
+ # Em Hybrid: 1 falha afeta só 1 agente (P(falha total) = ∏ p_i, muito menor)
813
+ return {
814
+ "n_tools": n_tools,
815
+ "tool_latencies": tool_latencies,
816
+ "single_agent_time_s": t_single,
817
+ "parallel_time_s": t_parallel,
818
+ "speedup": speedup,
819
+ "coord_overhead_s": coord_overhead_s,
820
+ "recommendation": recommendation,
821
+ "reason": reason,
822
+ "resilience_advantage": (
823
+ "Hybrid: 1 falha afeta 1 agente (isolamento). "
824
+ "Single-Agent: 1 falha derruba todas."
825
+ ),
826
+ }
v6_4_upload_report.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "version": "V6.4",
3
+ "upload_timestamp": "2026-08-07T21:51:25",
4
+ "repo_id": "PowerMachine/BiGRU_T_version",
5
+ "commit_oid": "f90a477e79ac4be3b851a283267edd0c9160d516",
6
+ "commit_url": "https://huggingface.co/PowerMachine/BiGRU_T_version/commit/f90a477e79ac4be3b851a283267edd0c9160d516",
7
+ "duration_s": 3.1715781688690186,
8
+ "critical_files": [
9
+ "src/bigru_t/model/kohonen_refactored/__init__.py",
10
+ "src/bigru_t/model/kohonen_refactored/kohonen_learning_system.py",
11
+ "src/bigru_t/model/hyp_t.py",
12
+ "v6_4_report.json",
13
+ "v6_4_training_metrics.json",
14
+ "scripts/train_v6_4.py",
15
+ "scripts/upload_v6_4_resilient.py",
16
+ "src/bigru_t/utils/xeon_runtime.py",
17
+ "src/bigru_t/data/streaming_datasets.py",
18
+ "src/bigru_t/training/ewc.py",
19
+ "src/bigru_t/model/orq_cell.py"
20
+ ],
21
+ "n_files_in_repo": 0
22
+ }
v6_5_module_analysis.json ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "candidates": {
3
+ "src/bigru_t/model/bigru4.py": {
4
+ "exists": true,
5
+ "size_bytes": 2131,
6
+ "activity": "dead_in_v65_path",
7
+ "reason": "V6.5 uses kohonen_refactored path, not UnifiedModel path",
8
+ "decision": "KEEP (preserve original architecture) — V6.5 uses kohonen_refactored"
9
+ },
10
+ "src/bigru_t/model/gru_hierarchy.py": {
11
+ "exists": true,
12
+ "size_bytes": 2817,
13
+ "activity": "fully_dead",
14
+ "reason": "Not imported by ANY module in repo",
15
+ "decision": "KEEP (preserve original architecture) — V6.5 uses kohonen_refactored"
16
+ },
17
+ "src/bigru_t/model/orq_cell.py": {
18
+ "exists": true,
19
+ "size_bytes": 38427,
20
+ "activity": "dead_in_v65_path",
21
+ "reason": "V6.5 uses kohonen_refactored path, not UnifiedModel path",
22
+ "decision": "KEEP (preserve original architecture) — V6.5 uses kohonen_refactored"
23
+ },
24
+ "src/bigru_t/model/train_t.py": {
25
+ "exists": true,
26
+ "size_bytes": 2217,
27
+ "activity": "dead_in_v65_path",
28
+ "reason": "V6.5 uses kohonen_refactored path, not UnifiedModel path",
29
+ "decision": "KEEP (preserve original architecture) — V6.5 uses kohonen_refactored"
30
+ },
31
+ "src/bigru_t/model/transformer_unit.py": {
32
+ "exists": true,
33
+ "size_bytes": 2540,
34
+ "activity": "dead_in_v65_path",
35
+ "reason": "V6.5 uses kohonen_refactored path, not UnifiedModel path",
36
+ "decision": "KEEP (preserve original architecture) — V6.5 uses kohonen_refactored"
37
+ },
38
+ "src/bigru_t/model/u8cell_t.py": {
39
+ "exists": true,
40
+ "size_bytes": 9250,
41
+ "activity": "dead_in_v65_path",
42
+ "reason": "V6.5 uses kohonen_refactored path, not UnifiedModel path",
43
+ "decision": "KEEP (preserve original architecture) — V6.5 uses kohonen_refactored"
44
+ },
45
+ "src/bigru_t/model/unified_model.py": {
46
+ "exists": true,
47
+ "size_bytes": 21754,
48
+ "activity": "dead_in_v65_path",
49
+ "reason": "V6.5 uses kohonen_refactored path, not UnifiedModel path",
50
+ "decision": "KEEP (preserve original architecture) — V6.5 uses kohonen_refactored"
51
+ }
52
+ },
53
+ "explicit_imports": {
54
+ "src/bigru_t/utils/xeon_runtime.py": {
55
+ "exists": true,
56
+ "size_bytes": 23704,
57
+ "activity": "active"
58
+ },
59
+ "src/bigru_t/data/streaming_datasets.py": {
60
+ "exists": true,
61
+ "size_bytes": 31213,
62
+ "activity": "active"
63
+ },
64
+ "src/bigru_t/model/kohonen_refactored/kohonen_learning_system.py": {
65
+ "exists": true,
66
+ "size_bytes": 27220,
67
+ "activity": "active"
68
+ },
69
+ "src/bigru_t/model/hyp_t.py": {
70
+ "exists": true,
71
+ "size_bytes": 3849,
72
+ "activity": "active"
73
+ },
74
+ "src/bigru_t/training/mtp.py": {
75
+ "exists": true,
76
+ "size_bytes": 10260,
77
+ "activity": "active"
78
+ },
79
+ "src/bigru_t/training/ewc.py": {
80
+ "exists": true,
81
+ "size_bytes": 25029,
82
+ "activity": "active"
83
+ },
84
+ "src/bigru_t/quantization/smoothquant_compressor.py": {
85
+ "exists": true,
86
+ "size_bytes": 3562,
87
+ "activity": "active"
88
+ },
89
+ "src/bigru_t/model/vqvae2_hierarchical.py": {
90
+ "exists": true,
91
+ "size_bytes": 7808,
92
+ "activity": "active"
93
+ },
94
+ "src/bigru_t/model/token_compress.py": {
95
+ "exists": true,
96
+ "size_bytes": 14129,
97
+ "activity": "active"
98
+ },
99
+ "src/bigru_t/reasoning/thinking.py": {
100
+ "exists": true,
101
+ "size_bytes": 5303,
102
+ "activity": "active"
103
+ }
104
+ },
105
+ "newly_integrated_v65": [
106
+ "src/bigru_t/quantization/smoothquant_compressor.py",
107
+ "src/bigru_t/model/vqvae2_hierarchical.py",
108
+ "src/bigru_t/model/vqvae2_hierarchical_flexnet.py",
109
+ "src/bigru_t/model/token_compress.py",
110
+ "src/bigru_t/reasoning/reasoning_engine.py",
111
+ "src/bigru_t/reasoning/circular_orchestration.py",
112
+ "src/bigru_t/reasoning/tool_agent.py",
113
+ "src/bigru_t/reasoning/distributed_reasoning_system.py",
114
+ "src/bigru_t/reasoning/cyclic_reasoning.py",
115
+ "src/bigru_t/reasoning/consensus_sampling.py"
116
+ ]
117
+ }
v6_5_report.json ADDED
@@ -0,0 +1,501 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "version": "V6.5",
3
+ "timestamp": "2026-08-07T22:57:20.223519",
4
+ "config": {
5
+ "BATCH_SIZE": 16,
6
+ "N_DATASETS": 5,
7
+ "SAMPLES_PER_DATASET_PHASE": 100,
8
+ "N_PHASES": 2,
9
+ "TOTAL_SAMPLES": 1000,
10
+ "EPOCHS": 2,
11
+ "SOM_GRID": [
12
+ 6,
13
+ 6,
14
+ 6,
15
+ 4
16
+ ],
17
+ "n_neurons": 864,
18
+ "HIDDEN_DIM": 1024,
19
+ "VOCAB_SIZE": 16384,
20
+ "MAX_SEQ_LEN": 8,
21
+ "T_max": 10000,
22
+ "N_start": 10,
23
+ "lambda_ewc": 0.02,
24
+ "MTP_K": 4,
25
+ "MTP_ENTROPY_BETA": 0.01,
26
+ "MTP_ACTIVE_IN_VAL": true
27
+ },
28
+ "xeon_status": {
29
+ "version": "V6",
30
+ "physical_cores": 2,
31
+ "env": {
32
+ "MKL_ENABLE_INSTRUCTIONS": "AVX512",
33
+ "MKL_NUM_THREADS": "2",
34
+ "OMP_NUM_THREADS": "2",
35
+ "MKL_DYNAMIC": "FALSE",
36
+ "DNNL_PRIMITIVE_CACHE_CAPACITY": "1024",
37
+ "ONEDNN_MAX_CPU_ISA": "AMX_INT8",
38
+ "KMP_AFFINITY": "granularity=fine,compact,1,0",
39
+ "KMP_BLOCKTIME": "1"
40
+ },
41
+ "avx512": {
42
+ "supported": true,
43
+ "desc": "AVX512_VNNI (full INT8 acceleration)"
44
+ },
45
+ "amx": {
46
+ "supported": true,
47
+ "desc": "AMX (tile + int8 + bf16) — full AMX acceleration"
48
+ },
49
+ "ipex_available": false,
50
+ "init_done": true
51
+ },
52
+ "fp16_benchmark": {
53
+ "best_time_ms": 92.53837899996142,
54
+ "avg_time_ms": 92.66920299978665,
55
+ "best_tflops": 1.3832098787904352,
56
+ "avg_tflops": 1.3812571583279365,
57
+ "matrix_size": 4000.0
58
+ },
59
+ "training": {
60
+ "duration_s": 181.83768033981323,
61
+ "n_steps": 140,
62
+ "n_epochs": 2,
63
+ "n_phases": 2
64
+ },
65
+ "summary": {
66
+ "n_steps": 140,
67
+ "n_steps_phase1": 70,
68
+ "n_steps_phase2": 70,
69
+ "final_loss": -1.0,
70
+ "mean_loss": -0.9888510861045461,
71
+ "min_loss": -1.0,
72
+ "max_loss": -0.7905694150420949,
73
+ "final_acc": 1.0,
74
+ "mean_acc": 0.9793448532430212,
75
+ "sigma_start": 1.3846745195799537,
76
+ "sigma_end": 0.19504306631763885,
77
+ "alpha_start": 0.09607894391523232,
78
+ "alpha_end": 0.03605949401730783,
79
+ "mtp_mean_loss": 0.0,
80
+ "mtp_final_loss": 0.0,
81
+ "rss_max_mb": 1790.1953125,
82
+ "rss_final_mb": 1790.1953125,
83
+ "rss_trend": "stable",
84
+ "n_alerts": 139,
85
+ "alerts": [
86
+ {
87
+ "type": "3.3_loss_vanishing",
88
+ "step": 1,
89
+ "phase": 1,
90
+ "value": -0.9842509842514764
91
+ },
92
+ {
93
+ "type": "3.3_loss_vanishing",
94
+ "step": 2,
95
+ "phase": 1,
96
+ "value": -1.0
97
+ },
98
+ {
99
+ "type": "3.3_loss_vanishing",
100
+ "step": 3,
101
+ "phase": 1,
102
+ "value": -0.9682458365518543
103
+ },
104
+ {
105
+ "type": "3.3_loss_vanishing",
106
+ "step": 4,
107
+ "phase": 1,
108
+ "value": -1.0
109
+ },
110
+ {
111
+ "type": "3.3_loss_vanishing",
112
+ "step": 5,
113
+ "phase": 1,
114
+ "value": -0.9682458365518543
115
+ },
116
+ {
117
+ "type": "3.3_loss_vanishing",
118
+ "step": 6,
119
+ "phase": 1,
120
+ "value": -1.0
121
+ },
122
+ {
123
+ "type": "3.3_loss_vanishing",
124
+ "step": 7,
125
+ "phase": 1,
126
+ "value": -1.0
127
+ },
128
+ {
129
+ "type": "3.3_loss_vanishing",
130
+ "step": 8,
131
+ "phase": 1,
132
+ "value": -1.0
133
+ },
134
+ {
135
+ "type": "3.3_loss_vanishing",
136
+ "step": 9,
137
+ "phase": 1,
138
+ "value": -1.0
139
+ },
140
+ {
141
+ "type": "3.3_loss_vanishing",
142
+ "step": 10,
143
+ "phase": 1,
144
+ "value": -1.0
145
+ },
146
+ {
147
+ "type": "3.3_loss_vanishing",
148
+ "step": 11,
149
+ "phase": 1,
150
+ "value": -1.0
151
+ },
152
+ {
153
+ "type": "3.3_loss_vanishing",
154
+ "step": 12,
155
+ "phase": 1,
156
+ "value": -1.0
157
+ },
158
+ {
159
+ "type": "3.3_loss_vanishing",
160
+ "step": 13,
161
+ "phase": 1,
162
+ "value": -1.0
163
+ },
164
+ {
165
+ "type": "3.3_loss_vanishing",
166
+ "step": 14,
167
+ "phase": 1,
168
+ "value": -0.9956803253779938
169
+ },
170
+ {
171
+ "type": "3.3_loss_vanishing",
172
+ "step": 15,
173
+ "phase": 1,
174
+ "value": -1.0
175
+ },
176
+ {
177
+ "type": "3.3_loss_vanishing",
178
+ "step": 16,
179
+ "phase": 1,
180
+ "value": -1.0
181
+ },
182
+ {
183
+ "type": "3.3_loss_vanishing",
184
+ "step": 17,
185
+ "phase": 1,
186
+ "value": -0.9842509842514764
187
+ },
188
+ {
189
+ "type": "3.3_loss_vanishing",
190
+ "step": 18,
191
+ "phase": 1,
192
+ "value": -1.0
193
+ },
194
+ {
195
+ "type": "3.3_loss_vanishing",
196
+ "step": 19,
197
+ "phase": 1,
198
+ "value": -1.0
199
+ },
200
+ {
201
+ "type": "3.3_loss_vanishing",
202
+ "step": 20,
203
+ "phase": 1,
204
+ "value": -1.0
205
+ },
206
+ {
207
+ "type": "3.3_loss_vanishing",
208
+ "step": 21,
209
+ "phase": 1,
210
+ "value": -1.0
211
+ },
212
+ {
213
+ "type": "3.3_loss_vanishing",
214
+ "step": 22,
215
+ "phase": 1,
216
+ "value": -1.0
217
+ },
218
+ {
219
+ "type": "3.3_loss_vanishing",
220
+ "step": 23,
221
+ "phase": 1,
222
+ "value": -1.0
223
+ },
224
+ {
225
+ "type": "3.3_loss_vanishing",
226
+ "step": 24,
227
+ "phase": 1,
228
+ "value": -1.0
229
+ },
230
+ {
231
+ "type": "3.3_loss_vanishing",
232
+ "step": 25,
233
+ "phase": 1,
234
+ "value": -1.0
235
+ },
236
+ {
237
+ "type": "3.3_loss_vanishing",
238
+ "step": 26,
239
+ "phase": 1,
240
+ "value": -1.0
241
+ },
242
+ {
243
+ "type": "3.3_loss_vanishing",
244
+ "step": 27,
245
+ "phase": 1,
246
+ "value": -0.9958246164193104
247
+ },
248
+ {
249
+ "type": "3.3_loss_vanishing",
250
+ "step": 28,
251
+ "phase": 1,
252
+ "value": -1.0
253
+ },
254
+ {
255
+ "type": "3.3_loss_vanishing",
256
+ "step": 29,
257
+ "phase": 1,
258
+ "value": -1.0
259
+ },
260
+ {
261
+ "type": "3.3_loss_vanishing",
262
+ "step": 30,
263
+ "phase": 1,
264
+ "value": -0.9842509842514764
265
+ }
266
+ ],
267
+ "kohonen_final": {
268
+ "sigma_t": 0.19504306631763885,
269
+ "alpha_t": 0.03605949401730783,
270
+ "t": 2040,
271
+ "n_neurons": 864,
272
+ "fisher_w_mean": 0.0,
273
+ "fisher_w_max": 0.0,
274
+ "fisher_accum_count": 0,
275
+ "has_ewc_reference": true,
276
+ "weights_norm": 47.53038787841797,
277
+ "weights_w_mean": -0.015125437639653683
278
+ },
279
+ "hypothesis_final": {
280
+ "classifier_trained": true,
281
+ "punishment_count": 0,
282
+ "success_count": 26,
283
+ "training_ready": true,
284
+ "buffer_size": 368,
285
+ "required_new_samples": 10,
286
+ "histogram_max": 368,
287
+ "time_counter": 2000
288
+ },
289
+ "mtp_final": {
290
+ "active": false,
291
+ "mtp_train_loss": 0.0,
292
+ "mtp_val_loss": 0.0,
293
+ "mtp_weighted_loss": 0.0,
294
+ "mtp_entropy_reg": 0.0,
295
+ "mtp_alphas": [],
296
+ "mtp_per_k_loss": [],
297
+ "active_in_val": true,
298
+ "entropy_beta": 0.01
299
+ },
300
+ "ewc_final": {
301
+ "active": true,
302
+ "ewc_classic_pen": 0.0,
303
+ "ewc_kohonen_pen": 0.0,
304
+ "ewc_topo_pen": 0.0,
305
+ "ewc_total_pen": 0.0,
306
+ "ewc_n_masked_som": 0,
307
+ "ewc_eval_mode_penalty": true,
308
+ "w8a8_eval_investigation": "EWC forward-only em eval; W8A8 needs dequant for (p-w*)^2; SmoothQuantCompressor preserves scale factors"
309
+ },
310
+ "evolution_phase1_to_phase2": {
311
+ "acc_phase1_mean": 0.9914798850574712,
312
+ "acc_phase2_mean": 0.9672098214285715,
313
+ "sigma_phase1_end": 0.4170559506797912,
314
+ "sigma_phase2_end": 0.19504306631763885,
315
+ "alpha_phase1_end": 0.052729242404304856,
316
+ "alpha_phase2_end": 0.03605949401730783
317
+ }
318
+ },
319
+ "kohonen_final": {
320
+ "t": 2040,
321
+ "sigma_t": 0.19504306631763885,
322
+ "alpha_t": 0.03605949401730783,
323
+ "sigma0": 1.5,
324
+ "alpha0": 0.1,
325
+ "lambda_ewc": 0.02,
326
+ "grid_shape": [
327
+ 6,
328
+ 6,
329
+ 6,
330
+ 4
331
+ ],
332
+ "n_neurons": 864,
333
+ "has_ewc_reference": true,
334
+ "fisher_w_mean": 0.0,
335
+ "fisher_w_max": 0.0,
336
+ "fisher_accum_count": 0,
337
+ "weights_norm": 47.53038787841797,
338
+ "weights_w_mean": -0.015125437639653683
339
+ },
340
+ "kls_state": {
341
+ "som": {
342
+ "t": 2040,
343
+ "sigma_t": 0.19504306631763885,
344
+ "alpha_t": 0.03605949401730783,
345
+ "sigma0": 1.5,
346
+ "alpha0": 0.1,
347
+ "lambda_ewc": 0.02,
348
+ "grid_shape": [
349
+ 6,
350
+ 6,
351
+ 6,
352
+ 4
353
+ ],
354
+ "n_neurons": 864,
355
+ "has_ewc_reference": true,
356
+ "fisher_w_mean": 0.0,
357
+ "fisher_w_max": 0.0,
358
+ "fisher_accum_count": 0,
359
+ "weights_norm": 47.53038787841797,
360
+ "weights_w_mean": -0.015125437639653683
361
+ },
362
+ "kls": {
363
+ "time_counter": 2000,
364
+ "T_max": 10000,
365
+ "buffer_size": 368,
366
+ "training_ready": true,
367
+ "punishment_count": 0,
368
+ "success_count": 26,
369
+ "classifier_trained": true,
370
+ "histogram_size": 1,
371
+ "histogram_max": 368,
372
+ "N_start": 10,
373
+ "dim_choice": "y",
374
+ "som_neuron_count": 864,
375
+ "required_new_samples": 10,
376
+ "has_classifier": true,
377
+ "vocab_size": 16384,
378
+ "hidden_dim": 1024,
379
+ "seq_len": 8
380
+ }
381
+ },
382
+ "ewc_w8a8_investigation": {
383
+ "investigation": "EWC+W8A8 eval interaction",
384
+ "findings": {
385
+ "ewc_eval_mode_penalty": true,
386
+ "w8a8_quantization": "SmoothQuantCompressor preserves scale factors for dequant",
387
+ "interaction": "Em eval mode, EWC.compute_penalty(eval_mode=True) computa penalidade forward-only. W8A8 mantém pesos INT8 mas SmoothQuantCompressor armazena scaling factors (s_j) que permitem dequantização barata: W_float = W_int8 * s_j. EWC usa W_float para (p - w_star)^2 mantendo precisão.",
388
+ "recommendation": "Para ativar EWC+W8A8 em eval: (1) manter scaling factors no SmoothQuantCompressor, (2) dequantizar apenas durante compute_penalty, (3) re-quantizar após (se necessário). Custo: O(n_params) por eval step."
389
+ },
390
+ "ewc_config": {
391
+ "eval_mode_penalty": true,
392
+ "skip_som_filled_neurons": true,
393
+ "lambda_ewc": 100.0,
394
+ "fisher_n_samples": 32
395
+ },
396
+ "smoothquant_config": {
397
+ "alpha": 0.5,
398
+ "n_bits": 8,
399
+ "calibration_samples": 128
400
+ },
401
+ "kls_state": {
402
+ "time_counter": 2000,
403
+ "T_max": 10000,
404
+ "buffer_size": 368,
405
+ "training_ready": true,
406
+ "punishment_count": 0,
407
+ "success_count": 26,
408
+ "classifier_trained": true,
409
+ "histogram_size": 1,
410
+ "histogram_max": 368,
411
+ "N_start": 10,
412
+ "dim_choice": "y",
413
+ "som_neuron_count": 864,
414
+ "required_new_samples": 10,
415
+ "has_classifier": true,
416
+ "vocab_size": 16384,
417
+ "hidden_dim": 1024,
418
+ "seq_len": 8
419
+ }
420
+ },
421
+ "module_analysis_summary": {
422
+ "n_candidates": 7,
423
+ "n_explicit_imports": 10,
424
+ "n_newly_integrated": 10,
425
+ "candidates_detail": {
426
+ "src/bigru_t/model/bigru4.py": {
427
+ "exists": true,
428
+ "size_bytes": 2131,
429
+ "activity": "dead_in_v65_path",
430
+ "reason": "V6.5 uses kohonen_refactored path, not UnifiedModel path",
431
+ "decision": "KEEP (preserve original architecture) — V6.5 uses kohonen_refactored"
432
+ },
433
+ "src/bigru_t/model/gru_hierarchy.py": {
434
+ "exists": true,
435
+ "size_bytes": 2817,
436
+ "activity": "fully_dead",
437
+ "reason": "Not imported by ANY module in repo",
438
+ "decision": "KEEP (preserve original architecture) — V6.5 uses kohonen_refactored"
439
+ },
440
+ "src/bigru_t/model/orq_cell.py": {
441
+ "exists": true,
442
+ "size_bytes": 38427,
443
+ "activity": "dead_in_v65_path",
444
+ "reason": "V6.5 uses kohonen_refactored path, not UnifiedModel path",
445
+ "decision": "KEEP (preserve original architecture) — V6.5 uses kohonen_refactored"
446
+ },
447
+ "src/bigru_t/model/train_t.py": {
448
+ "exists": true,
449
+ "size_bytes": 2217,
450
+ "activity": "dead_in_v65_path",
451
+ "reason": "V6.5 uses kohonen_refactored path, not UnifiedModel path",
452
+ "decision": "KEEP (preserve original architecture) — V6.5 uses kohonen_refactored"
453
+ },
454
+ "src/bigru_t/model/transformer_unit.py": {
455
+ "exists": true,
456
+ "size_bytes": 2540,
457
+ "activity": "dead_in_v65_path",
458
+ "reason": "V6.5 uses kohonen_refactored path, not UnifiedModel path",
459
+ "decision": "KEEP (preserve original architecture) — V6.5 uses kohonen_refactored"
460
+ },
461
+ "src/bigru_t/model/u8cell_t.py": {
462
+ "exists": true,
463
+ "size_bytes": 9250,
464
+ "activity": "dead_in_v65_path",
465
+ "reason": "V6.5 uses kohonen_refactored path, not UnifiedModel path",
466
+ "decision": "KEEP (preserve original architecture) — V6.5 uses kohonen_refactored"
467
+ },
468
+ "src/bigru_t/model/unified_model.py": {
469
+ "exists": true,
470
+ "size_bytes": 21754,
471
+ "activity": "dead_in_v65_path",
472
+ "reason": "V6.5 uses kohonen_refactored path, not UnifiedModel path",
473
+ "decision": "KEEP (preserve original architecture) — V6.5 uses kohonen_refactored"
474
+ }
475
+ }
476
+ },
477
+ "script_activity_summary": {
478
+ "n_scripts": 13,
479
+ "active_v65": 1,
480
+ "recent_v6": 9,
481
+ "legacy": 2
482
+ },
483
+ "math_analysis": {
484
+ "text_to_4d": "SVD: M @ V[:3].T -> centroid 3D + w = time_step/T_max (LINEAR)",
485
+ "bmu_distance": "||W - x||^2 (L2 squared in R^4)",
486
+ "neighborhood": "Lambda(d, sigma) = exp(-d^2 / (2*sigma^2))",
487
+ "weight_update": "dW = alpha * Lambda * (x - W)",
488
+ "sigma_decay": "sigma_t = sigma0 * exp(-t/1000)",
489
+ "alpha_decay": "alpha_t = alpha0 * exp(-t/2000)",
490
+ "ewc_only_dim4": "penalty = lambda * F * (W_w - W*_w)",
491
+ "mtp_loss": "L = sum_k(alpha_k * L_k) - beta * H(alpha), H = -sum alpha_k log(alpha_k)",
492
+ "ewc_w8a8_eval": "forward-only penalty in eval; SmoothQuant preserves scale for dequant"
493
+ },
494
+ "datasets_used": [
495
+ "TucanoBR/GigaVerbo",
496
+ "dominguesm/restore-punctuation-pttr-dataset",
497
+ "Madras1/corpus-ptbr-v2",
498
+ "CEIA-POSITIVO/ultrachat_br_clustred_balanced_v1",
499
+ "nvidia/OpenMathInstruct-2"
500
+ ]
501
+ }
v6_5_script_activity.json ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "smoke_test.py": {
3
+ "path": "scripts/smoke_test.py",
4
+ "size_bytes": 13457,
5
+ "mtime": "2026-08-05T22:30:13",
6
+ "classification": "test",
7
+ "activity": "legacy"
8
+ },
9
+ "train.py": {
10
+ "path": "scripts/train.py",
11
+ "size_bytes": 8026,
12
+ "mtime": "2026-08-05T22:37:41",
13
+ "classification": "legacy",
14
+ "activity": "legacy"
15
+ },
16
+ "train_fast.py": {
17
+ "path": "scripts/train_fast.py",
18
+ "size_bytes": 5017,
19
+ "mtime": "2026-08-05T22:45:27",
20
+ "classification": "legacy",
21
+ "activity": "legacy"
22
+ },
23
+ "train_v6_1.py": {
24
+ "path": "scripts/train_v6_1.py",
25
+ "size_bytes": 53839,
26
+ "mtime": "2026-08-07T00:05:08",
27
+ "classification": "active_v61",
28
+ "activity": "recent"
29
+ },
30
+ "train_v6_2.py": {
31
+ "path": "scripts/train_v6_2.py",
32
+ "size_bytes": 68794,
33
+ "mtime": "2026-08-07T00:55:19",
34
+ "classification": "active_v62",
35
+ "activity": "recent"
36
+ },
37
+ "train_v6_3.py": {
38
+ "path": "scripts/train_v6_3.py",
39
+ "size_bytes": 22527,
40
+ "mtime": "2026-08-07T21:17:23.191309",
41
+ "classification": "active_v63",
42
+ "activity": "recent"
43
+ },
44
+ "train_v6_4.py": {
45
+ "path": "scripts/train_v6_4.py",
46
+ "size_bytes": 25344,
47
+ "mtime": "2026-08-07T21:49:19.730287",
48
+ "classification": "active_v64",
49
+ "activity": "recent"
50
+ },
51
+ "train_v6_5.py": {
52
+ "path": "scripts/train_v6_5.py",
53
+ "size_bytes": 45100,
54
+ "mtime": "2026-08-07T22:54:10.218212",
55
+ "classification": "active_v65",
56
+ "activity": "active"
57
+ },
58
+ "upload_to_hf.py": {
59
+ "path": "scripts/upload_to_hf.py",
60
+ "size_bytes": 3240,
61
+ "mtime": "2026-08-05T22:47:27",
62
+ "classification": "upload_utility",
63
+ "activity": "legacy"
64
+ },
65
+ "upload_v6_1_resilient.py": {
66
+ "path": "scripts/upload_v6_1_resilient.py",
67
+ "size_bytes": 9960,
68
+ "mtime": "2026-08-07T00:05:08",
69
+ "classification": "active_v61",
70
+ "activity": "recent"
71
+ },
72
+ "upload_v6_2_resilient.py": {
73
+ "path": "scripts/upload_v6_2_resilient.py",
74
+ "size_bytes": 9904,
75
+ "mtime": "2026-08-07T00:55:22",
76
+ "classification": "active_v62",
77
+ "activity": "recent"
78
+ },
79
+ "upload_v6_3_resilient.py": {
80
+ "path": "scripts/upload_v6_3_resilient.py",
81
+ "size_bytes": 4712,
82
+ "mtime": "2026-08-07T21:17:23.192309",
83
+ "classification": "active_v63",
84
+ "activity": "recent"
85
+ },
86
+ "upload_v6_4_resilient.py": {
87
+ "path": "scripts/upload_v6_4_resilient.py",
88
+ "size_bytes": 5150,
89
+ "mtime": "2026-08-07T21:51:52.545045",
90
+ "classification": "active_v64",
91
+ "activity": "recent"
92
+ }
93
+ }
v6_5_training_metrics.json ADDED
The diff for this file is too large to render. See raw diff