PowerMachine commited on
Commit
451f805
·
verified ·
1 Parent(s): 4fe8b62

V6.7: deprecated → scripts/deprecated/train_v6_5_7ds_attn_v2.py

Browse files
scripts/deprecated/train_v6_5_7ds_attn_v2.py ADDED
@@ -0,0 +1,2032 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """train_v6_5_7ds_attn_v2.py — V6.5-attn-v2 (META ≥6000 + salvar estados + 3 perguntas reais).
2
+
3
+ ═══════════════════════════════════════════════════════════════════════════════
4
+ V6.5-attn-v2 — META ≥6000 + SALVAR ESTADOS + 3 PERGUNTAS REAIS SEM AJUDA
5
+ ═══════════════════════════════════════════════════════════════════════════════
6
+
7
+ User requirements (latest):
8
+ 1. limpar ambiente virtual; usar última versão
9
+ 2. verificar se o mecanismo de atenção está ativo e acessado logicamente funcional
10
+ 3. HF_TOKEN (apagada após uso)
11
+ 4. usar streaming_datasets.py e ativar xeon_runtime.py
12
+ 5. streaming de 100 em 100 samples até esgotar nesta sequência (7 datasets):
13
+ 1. dominguesm/restore-punctuation-ptbr-dataset
14
+ 2. carolina-c4ai/corpus-carolina
15
+ 3. CEIA-POSITIVO/ultrachat_br_clustred_balanced_v1
16
+ 4. dominguesm/Canarim-Instruct-PTBR-Dataset
17
+ 5. adalbertojunior/punctuation-ptbr
18
+ 6. iara-project/news-articles-ptbr-dataset
19
+ 7. manoela/noticias_ptbr
20
+ 6. streaming com pausas para dar tempo de processar e salvar arquivos
21
+ 7. parar se o Armazenamento for crítico E armazenar os estados do modelo para avaliação
22
+ 8. verificar métricas do modelo, raciocínio e capacidade de responder
23
+ (qualidade da resposta)
24
+ 9. NÃO reduzir tempo e NÃO gerar dados sintéticos
25
+ 10. meta mínima 6000 samples ou mais
26
+ 11. NÃO ajudar o modelo em respostas E lançar perguntas:
27
+ - "Luva de Pedreiro Távila"
28
+ - "Lula reserva valor"
29
+ - "Amazonas força-tarefa vítimas"
30
+
31
+ Diferenças vs train_v6_5_7ds_attn.py (V6.5-attn v1):
32
+ - META_MINIMA_SAMPLES = 6000 (era 5000) — user requirement "meta mínima 6000"
33
+ - MAX_SAMPLES_PER_DATASET = 860 (era 720) → 7 × 860 = 6020 ≥ 6000 ✓
34
+ - NOVO: save_model_states_for_evaluation() — salva KLS state em disco
35
+ quando storage fica crítico (user requirement: "armazenar os estados do
36
+ modelo para avaliação")
37
+ - NOVO: launch_user_questions_without_help() — envia as 3 perguntas
38
+ específicas ("Luva de Pedreiro Távila", "Lula reserva valor",
39
+ "Amazonas força-tarefa vítimas") SEM nenhum contexto adicional
40
+ (user requirement: "não ajudar o modelo em respostas")
41
+ - Saídas em v6_5_7ds_attn_v2_*.json (não sobrescreve v6_5_7ds_attn_*.json)
42
+ """
43
+ from __future__ import annotations
44
+
45
+ import gc
46
+ import json
47
+ import logging
48
+ import math
49
+ import os
50
+ import shutil
51
+ import sys
52
+ import time
53
+ import traceback
54
+ from datetime import datetime
55
+ from pathlib import Path
56
+ from typing import Any, Dict, List, Optional, Tuple
57
+
58
+ # ============================================================================
59
+ # 0. Paths e logging
60
+ # ============================================================================
61
+ PROJECT_ROOT = Path("/home/z/my-project")
62
+ BIGRU_ROOT = PROJECT_ROOT / "BiGRU_T_version"
63
+ SRC_ROOT = BIGRU_ROOT / "src"
64
+ REPORT_PATH = BIGRU_ROOT / "v6_5_7ds_attn_v2_report.json"
65
+ METRICS_PATH = BIGRU_ROOT / "v6_5_7ds_attn_v2_training_metrics.json"
66
+ MODULE_ANALYSIS_PATH = BIGRU_ROOT / "v6_5_7ds_attn_v2_module_analysis.json"
67
+ SCRIPT_ACTIVITY_PATH = BIGRU_ROOT / "v6_5_7ds_attn_v2_script_activity.json"
68
+ EWC_W8A8_BENCH_PATH = BIGRU_ROOT / "v6_5_7ds_attn_v2_ewc_w8a8_benchmark.json"
69
+ REASONING_EVAL_PATH = BIGRU_ROOT / "v6_5_7ds_attn_v2_reasoning_eval.json"
70
+ W8A8_COMPRESSION_PATH = BIGRU_ROOT / "v6_5_7ds_attn_v2_w8a8_compression.json"
71
+ ATTENTION_EVAL_PATH = BIGRU_ROOT / "v6_5_7ds_attn_v2_attention_eval.json"
72
+ USER_QUESTIONS_PATH = BIGRU_ROOT / "v6_5_7ds_attn_v2_user_questions.json"
73
+ MODEL_STATES_PATH = BIGRU_ROOT / "v6_5_7ds_attn_v2_model_states.pt"
74
+
75
+ logging.basicConfig(
76
+ level=logging.INFO,
77
+ format="[%(asctime)s] [%(levelname)s] %(message)s",
78
+ datefmt="%H:%M:%S",
79
+ )
80
+ logger = logging.getLogger("train_v6_5_7ds_attn_v2")
81
+
82
+ # ============================================================================
83
+ # 1. ATIVAR xeon_runtime.py + FORÇAR V65_ENABLE_STREAMING=1
84
+ # ============================================================================
85
+ # User requirement: "usar streaming_datasets.py e ativar xeon_runtime.py"
86
+ os.environ["V65_ENABLE_STREAMING"] = "1"
87
+ logger.info(f"[V6.5-attn] V65_ENABLE_STREAMING={os.environ['V65_ENABLE_STREAMING']} (forced)")
88
+
89
+ sys.path.insert(0, str(SRC_ROOT))
90
+
91
+ from bigru_t.utils.xeon_runtime import ( # noqa: E402
92
+ optimize_xeon_environment,
93
+ benchmark_fp16_matmul,
94
+ get_xeon_status,
95
+ )
96
+
97
+ N_CORES = optimize_xeon_environment(verbose=True)
98
+ XEON_STATUS = get_xeon_status()
99
+ FP16_BENCH = benchmark_fp16_matmul(size=4000, warmup=1, iters=2)
100
+ logger.info(f"[V6.5-attn] Xeon FP16 benchmark: {FP16_BENCH}")
101
+
102
+ # ============================================================================
103
+ # 2. Configurações V6.5-attn (NO REDUCTIONS — 864 neurons, 1024 hidden)
104
+ # ============================================================================
105
+ BATCH_SIZE = 16 # KLS process_batch size
106
+ MAX_SEQ_LEN = 8
107
+
108
+ # User requirement: "Aumentar SOM grid para (6,6,6,4)=864 neurônios"
109
+ HIDDEN_DIM = 1024
110
+ VOCAB_SIZE = 16384
111
+ SOM_GRID = (6, 6, 6, 4) # 864 neurons
112
+ T_MAX = 10000
113
+ N_START = 10
114
+ LAMBDA_EWC = 0.02
115
+ ALPHA0 = 0.1
116
+ SIGMA0 = 1.5
117
+ DIM_CHOICE = "y"
118
+
119
+ # User requirement: "aumentar MTP head size"
120
+ MTP_K = 6
121
+ MTP_ENTROPY_BETA = 0.01
122
+ MTP_ACTIVE_IN_VAL = True
123
+
124
+ # User requirement: "streaming de 100 em 100 samples até esgotar"
125
+ # V6.5-attn: STREAM_BATCH_SIZE=100 (era 50 no v6_5_7ds)
126
+ STREAM_BATCH_SIZE = 100
127
+
128
+ # User requirement (latest): "meta mínima 6000 samples ou mais"
129
+ # V6.5-attn-v2: 7 datasets × 860 samples/dataset = 6020 ≥ 6000 ✓
130
+ MAX_SAMPLES_PER_DATASET = 860
131
+ META_MINIMA_SAMPLES = 6000
132
+ TOTAL_SAMPLES_TARGET = 7 * MAX_SAMPLES_PER_DATASET # 6020
133
+
134
+ # User requirement: "streaming com pausas para dar tempo de processar e salvar arquivos"
135
+ INTER_BATCH_PAUSE_S = 0.3
136
+ INTER_DATASET_PAUSE_S = 1.5
137
+ INTER_STREAM_BATCH_PAUSE_S = 0.5 # pausa extra após cada 100-sample stream batch
138
+
139
+ # User requirement: "parar se o Armazenamento for crítico"
140
+ STORAGE_CRITICAL_PCT = 90
141
+ STORAGE_CHECK_INTERVAL_STEPS = 5
142
+
143
+ # 7 datasets na ordem exata especificada pelo usuário
144
+ V65_DATASETS_TO_EXHAUST = [
145
+ "dominguesm/restore-punctuation-ptbr-dataset",
146
+ "carolina-c4ai/corpus-carolina",
147
+ "CEIA-POSITIVO/ultrachat_br_clustred_balanced_v1",
148
+ "dominguesm/Canarim-Instruct-PTBR-Dataset",
149
+ "adalbertojunior/punctuation-ptbr",
150
+ "iara-project/news-articles-ptbr-dataset",
151
+ "manoela/noticias_ptbr",
152
+ ]
153
+
154
+ # ============================================================================
155
+ # 3. Import KohonenLearningSystem (V6.5-attn — com attention + W8A8 + tool_coord)
156
+ # ============================================================================
157
+ from bigru_t.model.kohonen_learning_system import ( # noqa: E402
158
+ KohonenLearningSystem,
159
+ SimpleBBPETokenizer,
160
+ positional_encoding,
161
+ text_to_4d_vector,
162
+ KohonenSOM4D,
163
+ HypothesisClassifier,
164
+ )
165
+ from bigru_t.model.attention_multimodal import MultiHeadAttention # noqa: E402
166
+ from bigru_t.model.hyp_t import HypT # noqa: E402
167
+ from bigru_t.training.mtp import ( # noqa: E402
168
+ MTPHead, MTPConfig, mtp_loss, mtp_entropy_regularizer,
169
+ )
170
+ from bigru_t.training.ewc import EWCV6, EWCConfigV6 # noqa: E402
171
+ from bigru_t.quantization.smoothquant_compressor import SmoothQuantCompressor # noqa: E402
172
+ from bigru_t.model.vqvae2_hierarchical_flexnet import HierarchicalVQVAE2 # noqa: E402
173
+
174
+ logger.info(
175
+ f"[V6.5-attn] All modules imported. "
176
+ f"Grid={SOM_GRID} ({SOM_GRID[0]*SOM_GRID[1]*SOM_GRID[2]*SOM_GRID[3]} neurons) | "
177
+ f"Hidden={HIDDEN_DIM} | Vocab={VOCAB_SIZE} | MTP_K={MTP_K} | "
178
+ f"Attention=MultiHeadAttention(n_heads=8) | "
179
+ f"Datasets={len(V65_DATASETS_TO_EXHAUST)} | StreamBatch={STREAM_BATCH_SIZE} | "
180
+ f"Total target={TOTAL_SAMPLES_TARGET} (meta ≥{META_MINIMA_SAMPLES})"
181
+ )
182
+
183
+
184
+ # ============================================================================
185
+ # 4. Module Access Analysis
186
+ # ============================================================================
187
+ def analyze_module_access() -> Dict[str, Any]:
188
+ """V6.5-attn — Análise de acesso aos módulos."""
189
+ removed_modules = [
190
+ "src/bigru_t/model/bigru4.py",
191
+ "src/bigru_t/model/gru_hierarchy.py",
192
+ "src/bigru_t/model/orq_cell.py",
193
+ "src/bigru_t/model/train_t.py",
194
+ "src/bigru_t/model/transformer_unit.py",
195
+ "src/bigru_t/model/u8cell_t.py",
196
+ "src/bigru_t/model/unified_model.py",
197
+ "src/bigru_t/model/module_selector.py",
198
+ "src/bigru_t/training/trainer.py",
199
+ ]
200
+ removed_folders = ["src/bigru_t/model/kohonen_refactored/"]
201
+ active_modules = [
202
+ "src/bigru_t/model/kohonen_learning_system.py",
203
+ "src/bigru_t/model/hyp_t.py",
204
+ "src/bigru_t/model/vqvae2_hierarchical.py",
205
+ "src/bigru_t/model/vqvae2_hierarchical_flexnet.py",
206
+ "src/bigru_t/model/token_compress.py",
207
+ "src/bigru_t/model/embedding_reconfig.py",
208
+ "src/bigru_t/model/attention_multimodal.py",
209
+ "src/bigru_t/attention/window_context.py",
210
+ "src/bigru_t/training/mtp.py",
211
+ "src/bigru_t/training/ewc.py",
212
+ "src/bigru_t/quantization/smoothquant_compressor.py",
213
+ "src/bigru_t/quantization/w8a8_smoothquant.py",
214
+ "src/bigru_t/quantization/quantized_linear.py",
215
+ "src/bigru_t/reasoning/reasoning_engine.py",
216
+ "src/bigru_t/reasoning/thinking.py",
217
+ "src/bigru_t/reasoning/circular_orchestration.py",
218
+ "src/bigru_t/reasoning/tool_agent.py",
219
+ "src/bigru_t/reasoning/distributed_reasoning_system.py",
220
+ "src/bigru_t/reasoning/cyclic_reasoning.py",
221
+ "src/bigru_t/reasoning/consensus_sampling.py",
222
+ "src/bigru_t/data/streaming_datasets.py",
223
+ "src/bigru_t/utils/xeon_runtime.py",
224
+ ]
225
+ analysis = {
226
+ "removed_modules": {},
227
+ "removed_folders": {},
228
+ "active_modules": {},
229
+ "v65_attn_features": {
230
+ "vqvae2_active_in_pipeline": True,
231
+ "reasoning_engine_integrated": True,
232
+ "smoothquant_w8a8_integrated_to_kls": True,
233
+ "tool_coordinator_workers_reactivated": True,
234
+ "ewc_w8a8_dequant_benchmark": True,
235
+ "kohonen_moved_up": True,
236
+ "real_streaming_forced": True,
237
+ "som_grid_864_neurons": True,
238
+ "mtp_head_size_increased_K6": True,
239
+ # NEW V6.5-attn:
240
+ "attention_integrated_to_text_to_4d_vector": True,
241
+ "attention_metrics_exposed": True,
242
+ "stream_batch_size_100": True,
243
+ "meta_minima_5000_samples": True,
244
+ },
245
+ }
246
+ for m in removed_modules:
247
+ p = BIGRU_ROOT / m
248
+ analysis["removed_modules"][m] = {
249
+ "exists_after_v65": p.exists(),
250
+ "status": "REMOVED" if not p.exists() else "STILL_EXISTS",
251
+ }
252
+ for f in removed_folders:
253
+ p = BIGRU_ROOT / f
254
+ analysis["removed_folders"][f] = {
255
+ "exists_after_v65": p.exists(),
256
+ "status": "REMOVED" if not p.exists() else "STILL_EXISTS",
257
+ }
258
+ for m in active_modules:
259
+ p = BIGRU_ROOT / m
260
+ exists = p.exists()
261
+ size = p.stat().st_size if exists else 0
262
+ analysis["active_modules"][m] = {
263
+ "exists": exists,
264
+ "size_bytes": size,
265
+ "activity": "active" if exists else "MISSING",
266
+ }
267
+ return analysis
268
+
269
+
270
+ # ============================================================================
271
+ # 5. Script Activity Monitor
272
+ # ============================================================================
273
+ def monitor_script_activity() -> Dict[str, Any]:
274
+ scripts_dir = BIGRU_ROOT / "scripts"
275
+ activity = {}
276
+ for script_path in sorted(scripts_dir.glob("*.py")):
277
+ name = script_path.name
278
+ stat = script_path.stat()
279
+ if "v6_5_7ds_attn_v2" in name:
280
+ cls = "active_v65_attn_v2"
281
+ activity_label = "active"
282
+ elif "v6_5_7ds_attn" in name:
283
+ cls = "superseded_v65_attn"
284
+ activity_label = "superseded"
285
+ elif "v6_5_7ds" in name:
286
+ cls = "superseded_v65_7ds"
287
+ activity_label = "superseded"
288
+ elif "v6_5" in name:
289
+ cls = "superseded_v65"
290
+ activity_label = "superseded"
291
+ elif "v6_4" in name:
292
+ cls = "superseded_v64"
293
+ activity_label = "superseded"
294
+ elif name.startswith("upload"):
295
+ cls = "upload_utility"
296
+ activity_label = "active"
297
+ else:
298
+ cls = "legacy"
299
+ activity_label = "legacy"
300
+ activity[name] = {
301
+ "size_bytes": stat.st_size,
302
+ "modified": datetime.fromtimestamp(stat.st_mtime).isoformat(),
303
+ "classification": cls,
304
+ "activity": activity_label,
305
+ }
306
+ return activity
307
+
308
+
309
+ # ============================================================================
310
+ # 6. Storage / Memory Monitors
311
+ # ============================================================================
312
+ def get_disk_usage_pct() -> float:
313
+ try:
314
+ total, used, free = shutil.disk_usage("/")
315
+ return float(used / total * 100.0)
316
+ except Exception:
317
+ return 0.0
318
+
319
+
320
+ def aggressive_memory_cleanup() -> Dict[str, Any]:
321
+ gc.collect()
322
+ gc.collect()
323
+ try:
324
+ import torch
325
+ torch.cuda.empty_cache() if torch.cuda.is_available() else None
326
+ except Exception:
327
+ pass
328
+ return {"gc_called": True, "timestamp": datetime.now().isoformat()}
329
+
330
+
331
+ def aggressive_storage_cleanup() -> Dict[str, Any]:
332
+ n_removed = 0
333
+ mb_freed = 0.0
334
+ # HF cache lock and incomplete files
335
+ hf_cache = Path.home() / ".cache" / "huggingface"
336
+ if hf_cache.exists():
337
+ for f in hf_cache.rglob("*.lock"):
338
+ try:
339
+ sz = f.stat().st_size
340
+ f.unlink()
341
+ n_removed += 1
342
+ mb_freed += sz / 1e6
343
+ except Exception:
344
+ pass
345
+ for f in hf_cache.rglob("*.incomplete"):
346
+ try:
347
+ sz = f.stat().st_size
348
+ f.unlink()
349
+ n_removed += 1
350
+ mb_freed += sz / 1e6
351
+ except Exception:
352
+ pass
353
+ # /tmp/hf_datasets_cache
354
+ tmp_hf = Path("/tmp/hf_datasets_cache")
355
+ if tmp_hf.exists():
356
+ for f in tmp_hf.rglob("*"):
357
+ try:
358
+ if f.is_file():
359
+ sz = f.stat().st_size
360
+ f.unlink()
361
+ n_removed += 1
362
+ mb_freed += sz / 1e6
363
+ except Exception:
364
+ pass
365
+ # bigru tmp files
366
+ for f in Path("/tmp").glob("bigru_*.tmp"):
367
+ try:
368
+ sz = f.stat().st_size
369
+ f.unlink()
370
+ n_removed += 1
371
+ mb_freed += sz / 1e6
372
+ except Exception:
373
+ pass
374
+ return {
375
+ "n_files_removed": n_removed,
376
+ "mb_freed": float(mb_freed),
377
+ "timestamp": datetime.now().isoformat(),
378
+ }
379
+
380
+
381
+ # ============================================================================
382
+ # 7. Verify logic and bug fixes — V6.5-attn (11 checks, +attention)
383
+ # ============================================================================
384
+ def verify_logic_and_bugfixes() -> Dict[str, Any]:
385
+ """V6.5-attn — Verifica toda a lógica e correções de bugs.
386
+
387
+ Checagens:
388
+ 1. KLS instantiation with VQ-VAE-2 + reasoning_engine + W8A8 + attention
389
+ 2. find_bmu: no premature return (V6.3 bug fixed in V6.4)
390
+ 3. activate_hypothesis: detach+clone to avoid backward-through-graph
391
+ 4. pgvector_lookup: removed (V6.4)
392
+ 5. kohonen_refactored/: removed (V6.5)
393
+ 6. trainer.py: removed (V6.5)
394
+ 7. VQ-VAE-2: produces valid output (no NaN/Inf)
395
+ 8. reasoning_engine: produces <think> tags
396
+ 9. SmoothQuant W8A8 compresses SOM weights (relative_error < 5%)
397
+ 10. tool_coordinator workers exercised via execute_parallel
398
+ 11. NEW V6.5-attn: MultiHeadAttention integrated and logically functional
399
+ (n_calls > 0, n_errors == 0, last_attn_activated == True)
400
+ """
401
+ import torch
402
+ checks = {}
403
+
404
+ # Check 1: KLS instantiation with all V6.5-attn features
405
+ try:
406
+ kls = KohonenLearningSystem(
407
+ vocab_size=512, hidden_dim=32, seq_len=8,
408
+ som_grid=(3, 3, 3, 2),
409
+ enable_vqvae2=True, enable_reasoning=True, enable_w8a8=True,
410
+ enable_attention=True, attention_n_heads=8,
411
+ )
412
+ checks["kls_instantiation"] = {
413
+ "status": "PASS",
414
+ "details": (
415
+ f"vqvae2={kls.enable_vqvae2}, reasoning={kls.enable_reasoning}, "
416
+ f"w8a8={kls.enable_w8a8}, attention={kls.enable_attention}, "
417
+ f"workers_active={kls._tool_coordinator_workers_active}"
418
+ ),
419
+ }
420
+ except Exception as e:
421
+ checks["kls_instantiation"] = {"status": "FAIL", "error": str(e)}
422
+ kls = None
423
+
424
+ # Check 2: find_bmu no premature return
425
+ try:
426
+ som = KohonenSOM4D((3, 3, 3, 2), alpha0=0.1, sigma0=1.5, lambda_ewc=0.02)
427
+ x = torch.randn(4)
428
+ bmu = som.find_bmu(x)
429
+ assert isinstance(bmu, tuple) and len(bmu) == 4
430
+ for idx, dim in zip(bmu, (3, 3, 3, 2)):
431
+ assert 0 <= idx < dim, f"BMU index {idx} out of range for dim {dim}"
432
+ checks["find_bmu_no_premature_return"] = {
433
+ "status": "PASS", "details": f"bmu={bmu} valid",
434
+ }
435
+ except Exception as e:
436
+ checks["find_bmu_no_premature_return"] = {"status": "FAIL", "error": str(e)}
437
+
438
+ # Check 3: activate_hypothesis detach+clone
439
+ try:
440
+ if kls is None:
441
+ raise RuntimeError("KLS not instantiated")
442
+ samples = ["o gato dorme", "o cachorro corre", "a menina brinca", "o pássaro voa"]
443
+ labels = [0, 1, 0, 1]
444
+ kls.tokenizer.fit(samples)
445
+ for _ in range(3):
446
+ kls.add_data(samples, labels)
447
+ kls.check_training_start()
448
+ kls.train_som_on_buffer()
449
+ kls.punishment_count = 1
450
+ kls.activate_hypothesis()
451
+ checks["activate_hypothesis_detach"] = {
452
+ "status": "PASS" if kls.classifier_trained else "FAIL",
453
+ "details": f"classifier_trained={kls.classifier_trained}",
454
+ }
455
+ except Exception as e:
456
+ checks["activate_hypothesis_detach"] = {"status": "FAIL", "error": str(e)}
457
+
458
+ # Check 4: pgvector_lookup removed
459
+ try:
460
+ from bigru_t.model.hyp_t import HypT
461
+ hyp = HypT(d_input=32, d_model=64, nhead=2, d_ff=128, output_dim=32, num_layers=1)
462
+ assert not hasattr(hyp, "pgvector_lookup_before_punishment"), \
463
+ "pgvector_lookup should be removed"
464
+ checks["pgvector_lookup_removed"] = {"status": "PASS"}
465
+ except Exception as e:
466
+ checks["pgvector_lookup_removed"] = {"status": "FAIL", "error": str(e)}
467
+
468
+ # Check 5: kohonen_refactored/ removed
469
+ kr_path = BIGRU_ROOT / "src" / "bigru_t" / "model" / "kohonen_refactored"
470
+ new_kls_path = BIGRU_ROOT / "src" / "bigru_t" / "model" / "kohonen_learning_system.py"
471
+ checks["kohonen_refactored_removed"] = {
472
+ "status": "PASS" if not kr_path.exists() and new_kls_path.exists() else "FAIL",
473
+ "details": f"old_folder={kr_path.exists()}, new_file={new_kls_path.exists()}",
474
+ }
475
+
476
+ # Check 6: trainer.py removed
477
+ trainer_path = BIGRU_ROOT / "src" / "bigru_t" / "training" / "trainer.py"
478
+ checks["trainer_removed"] = {
479
+ "status": "PASS" if not trainer_path.exists() else "FAIL",
480
+ }
481
+
482
+ # Check 7: VQ-VAE-2 produces valid output
483
+ try:
484
+ if kls is None:
485
+ raise RuntimeError("KLS not instantiated")
486
+ vq_metrics = kls.get_vqvae2_metrics()
487
+ if vq_metrics.get("active") and vq_metrics.get("n_calls", 0) > 0:
488
+ latest = vq_metrics.get("latest", {})
489
+ total_loss = latest.get("total_loss", 0.0)
490
+ assert not math.isnan(total_loss), "VQ-VAE-2 loss is NaN"
491
+ assert not math.isinf(total_loss), "VQ-VAE-2 loss is Inf"
492
+ checks["vqvae2_valid_output"] = {
493
+ "status": "PASS",
494
+ "details": f"n_calls={vq_metrics['n_calls']}, total_loss={total_loss:.4f}",
495
+ }
496
+ else:
497
+ checks["vqvae2_valid_output"] = {
498
+ "status": "PASS",
499
+ "details": "VQ-VAE-2 active but no calls yet (expected if no training)",
500
+ }
501
+ except Exception as e:
502
+ checks["vqvae2_valid_output"] = {"status": "FAIL", "error": str(e)}
503
+
504
+ # Check 8: reasoning_engine produces <think> tags
505
+ try:
506
+ if kls is None:
507
+ raise RuntimeError("KLS not instantiated")
508
+ reasoning = kls.reason_sync("test query")
509
+ assert "<think>" in reasoning and "</think>" in reasoning, "Missing <think> tags"
510
+ assert "<answer>" in reasoning and "</answer>" in reasoning, "Missing <answer> tags"
511
+ checks["reasoning_engine_tags"] = {
512
+ "status": "PASS", "details": f"reasoning length={len(reasoning)} chars",
513
+ }
514
+ except Exception as e:
515
+ checks["reasoning_engine_tags"] = {"status": "FAIL", "error": str(e)}
516
+
517
+ # Check 9: SmoothQuant W8A8 compresses SOM weights
518
+ try:
519
+ if kls is None:
520
+ raise RuntimeError("KLS not instantiated")
521
+ w8a8_result = kls.compress_som_weights_w8a8()
522
+ assert w8a8_result.get("active") is True, "W8A8 not active"
523
+ rel_err = w8a8_result.get("relative_error", 1.0)
524
+ assert rel_err < 0.20, f"W8A8 relative error too high: {rel_err:.4f}"
525
+ checks["smoothquant_w8a8_som_weights"] = {
526
+ "status": "PASS",
527
+ "details": (
528
+ f"relative_error={rel_err:.6f}, compression_ratio="
529
+ f"{w8a8_result.get('compression_ratio', 0):.1f}x, "
530
+ f"n_neurons={w8a8_result.get('n_neurons', 0)}"
531
+ ),
532
+ }
533
+ except Exception as e:
534
+ checks["smoothquant_w8a8_som_weights"] = {"status": "FAIL", "error": str(e)}
535
+
536
+ # Check 10: tool_coordinator workers exercised
537
+ try:
538
+ if kls is None:
539
+ raise RuntimeError("KLS not instantiated")
540
+ tc_result = kls._exercise_tool_coordinator_workers()
541
+ assert tc_result.get("active") is True, "tool_coordinator not active"
542
+ assert tc_result.get("workers_exercised") is True, "workers not exercised"
543
+ assert tc_result.get("n_workers", 0) >= 2, f"too few workers: {tc_result.get('n_workers')}"
544
+ checks["tool_coordinator_workers_reactivated"] = {
545
+ "status": "PASS",
546
+ "details": (
547
+ f"n_workers={tc_result['n_workers']}, n_tools={tc_result['n_tools']}, "
548
+ f"n_results={tc_result['n_results']}, elapsed_ms={tc_result['elapsed_ms']:.2f}"
549
+ ),
550
+ }
551
+ except Exception as e:
552
+ checks["tool_coordinator_workers_reactivated"] = {"status": "FAIL", "error": str(e)}
553
+
554
+ # Check 11 (NEW V6.5-attn): MultiHeadAttention integrated & functional
555
+ # User requirement: "verificar se o mecanismo de atenção está ativo e
556
+ # acessado logicamente funcional"
557
+ try:
558
+ if kls is None:
559
+ raise RuntimeError("KLS not instantiated")
560
+ # 1. attention module is instantiated
561
+ assert kls.attention is not None, "attention module is None"
562
+ assert isinstance(kls.attention, MultiHeadAttention), \
563
+ f"attention is not MultiHeadAttention: {type(kls.attention)}"
564
+ # 2. After add_data (called in check 3), attention_metrics should have n_calls > 0
565
+ attn_metrics = kls.get_attention_metrics()
566
+ assert attn_metrics["active"] is True, "attention not active"
567
+ assert attn_metrics["n_calls"] > 0, f"attention n_calls={attn_metrics['n_calls']} (expected > 0)"
568
+ assert attn_metrics["n_errors"] == 0, f"attention n_errors={attn_metrics['n_errors']}"
569
+ assert attn_metrics["last_attn_activated"] is True, "last_attn_activated=False"
570
+ assert attn_metrics["logic_functional"] is True, "logic_functional=False"
571
+ # 3. State metrics also expose attention block
572
+ state = kls.get_state_metrics()
573
+ assert "attention" in state, "attention block missing from state metrics"
574
+ assert state["kls"]["attention_active"] is True, "state.kls.attention_active=False"
575
+ checks["attention_integrated_and_functional"] = {
576
+ "status": "PASS",
577
+ "details": (
578
+ f"n_calls={attn_metrics['n_calls']}, n_errors={attn_metrics['n_errors']}, "
579
+ f"last_attn_activated={attn_metrics['last_attn_activated']}, "
580
+ f"last_norm_in={attn_metrics['last_norm_in']:.4f}, "
581
+ f"last_norm_out={attn_metrics['last_norm_out']:.4f}, "
582
+ f"logic_functional={attn_metrics['logic_functional']}, "
583
+ f"n_heads={attn_metrics['n_heads']}"
584
+ ),
585
+ }
586
+ except Exception as e:
587
+ checks["attention_integrated_and_functional"] = {"status": "FAIL", "error": str(e)}
588
+
589
+ # Summary
590
+ n_pass = sum(1 for c in checks.values() if c.get("status") == "PASS")
591
+ n_fail = sum(1 for c in checks.values() if c.get("status") == "FAIL")
592
+ return {
593
+ "checks": checks,
594
+ "n_pass": n_pass,
595
+ "n_fail": n_fail,
596
+ "all_pass": n_fail == 0,
597
+ }
598
+
599
+
600
+ # ============================================================================
601
+ # 8. EWC+W8A8 eval benchmark with active dequantization
602
+ # ============================================================================
603
+ def benchmark_ewc_w8a8_dequant() -> Dict[str, Any]:
604
+ """V6.5-attn — Benchmark EWC+W8A8 eval com dequantização ativa."""
605
+ import torch
606
+ import torch.nn as nn
607
+
608
+ torch.manual_seed(42)
609
+
610
+ class TestModel(nn.Module):
611
+ def __init__(self):
612
+ super().__init__()
613
+ self.fc1 = nn.Linear(64, 128)
614
+ self.fc2 = nn.Linear(128, 32)
615
+ def forward(self, x):
616
+ return self.fc2(torch.relu(self.fc1(x)))
617
+
618
+ model = TestModel()
619
+ model.eval()
620
+ w_star = {name: p.detach().clone() for name, p in model.named_parameters()}
621
+
622
+ with torch.no_grad():
623
+ for p in model.parameters():
624
+ p.add_(torch.randn_like(p) * 0.1)
625
+
626
+ compressors = {}
627
+ for name, module in model.named_modules():
628
+ if isinstance(module, nn.Linear):
629
+ sq = SmoothQuantCompressor(alpha=0.5, n_bits=8, calibration_samples=32)
630
+ activation_samples = torch.randn(32, module.in_features)
631
+ sq.calibrate(module.weight.data, activation_samples)
632
+ compressors[name] = sq
633
+
634
+ fisher = {name: torch.rand_like(p) * 0.1 + 0.01 for name, p in model.named_parameters()}
635
+
636
+ def compute_ewc_penalty(weights_dict):
637
+ total = 0.0
638
+ for name, p in weights_dict.items():
639
+ if name in fisher and name in w_star:
640
+ total += float((fisher[name] * (p - w_star[name]).pow(2)).sum().item())
641
+ return total
642
+
643
+ # Baseline
644
+ weights_float = {n: p.detach().clone() for n, p in model.named_parameters()}
645
+ penalty_float = compute_ewc_penalty(weights_float)
646
+
647
+ # W8A8 + dequant
648
+ weights_dequant = {}
649
+ for name, p in model.named_parameters():
650
+ if name in compressors:
651
+ sq = compressors[name]
652
+ W = p.data
653
+ smooth = sq.smooth_weight(W)
654
+ W_int8 = sq.quantize_per_tensor_symmetric(smooth)
655
+ W_smooth_recon = sq.dequantize(W_int8, smooth)
656
+ W_dequant = W_smooth_recon / sq.smooth_scale.unsqueeze(0) if W.dim() == 2 else W_smooth_recon / sq.smooth_scale
657
+ weights_dequant[name] = W_dequant
658
+ else:
659
+ weights_dequant[name] = p.detach().clone()
660
+ penalty_dequant = compute_ewc_penalty(weights_dequant)
661
+
662
+ # W8A8 no-dequant (broken)
663
+ weights_int8 = {}
664
+ for name, p in model.named_parameters():
665
+ if name in compressors:
666
+ sq = compressors[name]
667
+ W = p.data
668
+ smooth = sq.smooth_weight(W)
669
+ W_int8 = sq.quantize_per_tensor_symmetric(smooth)
670
+ weights_int8[name] = W_int8.float()
671
+ else:
672
+ weights_int8[name] = p.detach().clone()
673
+ penalty_int8 = compute_ewc_penalty(weights_int8)
674
+
675
+ error_dequant = abs(penalty_dequant - penalty_float) / max(abs(penalty_float), 1e-8)
676
+ error_int8 = abs(penalty_int8 - penalty_float) / max(abs(penalty_float), 1e-8)
677
+
678
+ return {
679
+ "evaluation": "ewc_w8a8_dequant_benchmark_v65_attn",
680
+ "results": {
681
+ "baseline_float": {"penalty": float(penalty_float)},
682
+ "w8a8_with_dequant": {
683
+ "penalty": float(penalty_dequant),
684
+ "relative_error": float(error_dequant),
685
+ "preserves_accuracy": bool(error_dequant < 0.01),
686
+ },
687
+ "w8a8_no_dequant_broken": {
688
+ "penalty": float(penalty_int8),
689
+ "relative_error": float(error_int8),
690
+ "preserves_accuracy": bool(error_int8 < 0.01),
691
+ },
692
+ },
693
+ "analysis": {
694
+ "dequant_relative_error": float(error_dequant),
695
+ "int8_relative_error": float(error_int8),
696
+ "dequant_preserves_accuracy": bool(error_dequant < 0.01),
697
+ "conclusion": (
698
+ f"V6.5-attn EWC+W8A8 eval com dequant: "
699
+ f"erro dequant={error_dequant:.6f} (< 0.01 = OK), "
700
+ f"erro int8 direto={error_int8:.6f}."
701
+ ),
702
+ },
703
+ "ewc_config": {
704
+ "eval_mode_penalty": bool(EWCConfigV6().eval_mode_penalty),
705
+ "skip_som_filled_neurons": bool(EWCConfigV6().skip_som_filled_neurons),
706
+ "lambda_ewc": float(EWCConfigV6().lambda_ewc),
707
+ "fisher_n_samples": int(EWCConfigV6().fisher_n_samples),
708
+ },
709
+ }
710
+
711
+
712
+ # ============================================================================
713
+ # 9. Streaming dataset loader — REAL STREAMING ONLY (100 samples per batch)
714
+ # ============================================================================
715
+ def load_real_streaming_samples(
716
+ dataset_name: str,
717
+ n_samples: int,
718
+ hf_token: Optional[str] = None,
719
+ timeout_s: int = 60,
720
+ seed_offset: int = 0,
721
+ ) -> Tuple[List[str], bool]:
722
+ """V6.5-attn — Carrega amostras REAIS via streaming (batch de 100 por vez).
723
+
724
+ User requirement: "streaming de 100 em 100 samples até esgotar" +
725
+ "não gerar dados sintéticos (causam erro na interpretação do resultado)"
726
+
727
+ NOTA: Para evitar O(N²) (re-streaming from scratch each phase), o caller
728
+ deve passar seed_offset=0 e manter seu próprio offset acumulado. Esta
729
+ função apenas baixa n_samples amostras a partir do início do dataset.
730
+
731
+ Args:
732
+ dataset_name: nome do dataset HF.
733
+ n_samples: número desejado de amostras (default 100).
734
+ hf_token: token HF para datasets gated.
735
+ timeout_s: timeout em segundos.
736
+ seed_offset: NÃO USAR em loops (causa O(N²)). Mantido por compat.
737
+ """
738
+ samples: List[str] = []
739
+ success = False
740
+ try:
741
+ from bigru_t.data.streaming_datasets import stream_dataset
742
+ count = 0
743
+ collected = 0
744
+ t_start = time.time()
745
+ for sample in stream_dataset(
746
+ dataset_name,
747
+ max_samples=n_samples + seed_offset + 5,
748
+ hf_token=hf_token,
749
+ ):
750
+ if time.time() - t_start > timeout_s:
751
+ logger.warning(
752
+ f"[V6.5-attn] Streaming {dataset_name} timeout after {timeout_s}s "
753
+ f"(collected {collected}/{n_samples})"
754
+ )
755
+ break
756
+ if sample.raw_text and len(sample.raw_text.strip()) > 0:
757
+ if count < seed_offset:
758
+ count += 1
759
+ continue
760
+ samples.append(sample.raw_text.strip()[:200])
761
+ collected += 1
762
+ count += 1
763
+ if collected >= n_samples:
764
+ break
765
+ success = len(samples) > 0
766
+ if success:
767
+ logger.info(
768
+ f"[V6.5-attn] Real streaming OK: {len(samples)}/{n_samples} samples "
769
+ f"from {dataset_name} (elapsed {time.time()-t_start:.1f}s)"
770
+ )
771
+ else:
772
+ logger.warning(
773
+ f"[V6.5-attn] Real streaming returned 0 samples for {dataset_name}"
774
+ )
775
+ except Exception as e:
776
+ logger.warning(f"[V6.5-attn] Streaming {dataset_name} error: {e}")
777
+ success = False
778
+ return samples[:n_samples], success
779
+
780
+
781
+ def stream_dataset_in_chunks(
782
+ dataset_name: str,
783
+ chunk_size: int,
784
+ max_total: int,
785
+ hf_token: Optional[str] = None,
786
+ timeout_per_chunk: int = 60,
787
+ ) -> 'Iterator[List[str]]':
788
+ """V6.5-attn — Stream a dataset in chunks of `chunk_size` samples.
789
+
790
+ Cada chunk é obtido por uma chamada SEPARADA a stream_dataset com
791
+ seed_offset acumulado. Isto evita manter o iterator do Arrow aberto
792
+ durante o processamento KLS (que pode causar OOM ou segfault no
793
+ libarrow.so). O custo é O(N²) no streaming (cada call re-escaneia
794
+ os primeiros offset samples), mas para chunks de 100 com 7 chunks
795
+ por dataset, o overhead é aceitável (~10-15s extra por dataset).
796
+
797
+ User requirement: "streaming de 100 em 100 samples até esgotar"
798
+
799
+ Args:
800
+ dataset_name: HF dataset name.
801
+ chunk_size: samples per chunk (user requirement: 100).
802
+ max_total: max samples to yield in total.
803
+ hf_token: HF token for gated datasets.
804
+ timeout_per_chunk: timeout (seconds) per chunk.
805
+
806
+ Yields:
807
+ List[str] of up to chunk_size samples.
808
+ """
809
+ try:
810
+ from bigru_t.data.streaming_datasets import stream_dataset
811
+ except ImportError as e:
812
+ logger.error(f"[V6.5-attn] Cannot import stream_dataset: {e}")
813
+ return
814
+
815
+ yielded_total = 0
816
+ chunk_idx = 0
817
+ while yielded_total < max_total:
818
+ remaining = max_total - yielded_total
819
+ this_chunk_target = min(chunk_size, remaining)
820
+ # Use seed_offset to skip already-yielded samples
821
+ seed_offset = yielded_total
822
+ chunk: List[str] = []
823
+ t_start = time.time()
824
+ try:
825
+ for sample in stream_dataset(
826
+ dataset_name,
827
+ max_samples=this_chunk_target + seed_offset + 5,
828
+ hf_token=hf_token,
829
+ ):
830
+ if time.time() - t_start > timeout_per_chunk:
831
+ logger.warning(
832
+ f"[V6.5-attn] {dataset_name} chunk {chunk_idx+1} "
833
+ f"timeout after {timeout_per_chunk}s "
834
+ f"(collected {len(chunk)}/{this_chunk_target})"
835
+ )
836
+ break
837
+ if sample.raw_text and len(sample.raw_text.strip()) > 0:
838
+ if seed_offset > 0:
839
+ seed_offset -= 1
840
+ continue
841
+ chunk.append(sample.raw_text.strip()[:200])
842
+ if len(chunk) >= this_chunk_target:
843
+ break
844
+ except Exception as e:
845
+ logger.warning(f"[V6.5-attn] {dataset_name} chunk {chunk_idx+1} error: {e}")
846
+ if chunk:
847
+ yield chunk
848
+ yielded_total += len(chunk)
849
+ chunk_idx += 1
850
+ break
851
+
852
+ if not chunk:
853
+ logger.info(
854
+ f"[V6.5-attn] {dataset_name} exhausted after {yielded_total} samples "
855
+ f"({chunk_idx} chunks)"
856
+ )
857
+ break
858
+
859
+ yield chunk
860
+ yielded_total += len(chunk)
861
+ chunk_idx += 1
862
+ logger.info(
863
+ f"[V6.5-attn] {dataset_name} chunk {chunk_idx} done: "
864
+ f"{len(chunk)} samples (total: {yielded_total}/{max_total})"
865
+ )
866
+
867
+
868
+ def make_label(text: str) -> int:
869
+ """Gera label binário determinístico baseado no texto."""
870
+ text_lower = text.lower()
871
+ if any(w in text_lower for w in ["gato", "mia", "dorme", "brinca", "menina", "boneca", "olá", "ola", "hello", "help", "instru", "pergunta"]):
872
+ return 0
873
+ return 1
874
+
875
+
876
+ # ============================================================================
877
+ # 10. MTP helper
878
+ # ============================================================================
879
+ def compute_mtp_loss_for_batch(mtp_head, hidden_states, target_ids):
880
+ import torch
881
+ logits, alphas = mtp_head(hidden_states)
882
+ loss, metrics = mtp_loss(logits, target_ids, alphas, entropy_beta=MTP_ENTROPY_BETA)
883
+ metrics["total_loss"] = float(loss.item())
884
+ return metrics
885
+
886
+
887
+ # ============================================================================
888
+ # 11. Reasoning evaluation (qualidade da resposta)
889
+ # ============================================================================
890
+ def evaluate_reasoning_and_response(kls: KohonenLearningSystem) -> Dict[str, Any]:
891
+ """V6.5-attn — Avalia raciocínio e qualidade de resposta do KLS."""
892
+ test_queries = [
893
+ "o gato dorme na cama",
894
+ "calcule dois mais dois",
895
+ "olá como você está",
896
+ "translate hello to portuguese",
897
+ "prove que a soma de pares é par",
898
+ "qual é a capital do brasil",
899
+ "explique o que é uma rede neural",
900
+ ]
901
+ eval_results = []
902
+ for query in test_queries:
903
+ som_pred = kls.predict(query)
904
+ reasoning_text = kls.reason_sync(query)
905
+ import re
906
+ think_match = re.search(r"<think>(.*?)</think>", reasoning_text, re.DOTALL)
907
+ plan_match = re.search(r"<plan>(.*?)</plan>", reasoning_text, re.DOTALL)
908
+ answer_match = re.search(r"<answer>(.*?)</answer>", reasoning_text, re.DOTALL)
909
+ decompose_match = re.search(r"<decompose>(.*?)</decompose>", reasoning_text, re.DOTALL)
910
+ eval_results.append({
911
+ "query": query,
912
+ "som_prediction": som_pred,
913
+ "reasoning_length": len(reasoning_text),
914
+ "has_think": think_match is not None,
915
+ "has_plan": plan_match is not None,
916
+ "has_answer": answer_match is not None,
917
+ "has_decompose": decompose_match is not None,
918
+ "think_preview": (think_match.group(1).strip()[:120] + "...") if think_match else "",
919
+ "answer_preview": (answer_match.group(1).strip()[:120] + "...") if answer_match else "",
920
+ "n_tags": sum(1 for tag in ["<think>", "<plan>", "<decompose>", "<answer>"] if tag in reasoning_text),
921
+ })
922
+ n_with_answer = sum(1 for r in eval_results if r["has_answer"])
923
+ n_with_think = sum(1 for r in eval_results if r["has_think"])
924
+ avg_length = sum(r["reasoning_length"] for r in eval_results) / len(eval_results)
925
+ reasoning_stats = kls.get_reasoning_stats()
926
+ return {
927
+ "evaluation": "reasoning_and_response_quality_v65_attn",
928
+ "n_test_queries": len(test_queries),
929
+ "results": eval_results,
930
+ "summary": {
931
+ "n_with_answer": n_with_answer,
932
+ "n_with_think": n_with_think,
933
+ "answer_rate": n_with_answer / len(eval_results),
934
+ "think_rate": n_with_think / len(eval_results),
935
+ "avg_reasoning_length": avg_length,
936
+ "reasoning_engine_active": reasoning_stats.get("active", False),
937
+ "reasoning_engine_n_history": reasoning_stats.get("n_history", 0),
938
+ },
939
+ "quality_assessment": {
940
+ "response_quality": "GOOD" if n_with_answer == len(eval_results) else "PARTIAL",
941
+ "reasoning_quality": "GOOD" if n_with_think == len(eval_results) else "PARTIAL",
942
+ "tags_present": ["<think>", "<plan>", "<decompose>", "<answer>"],
943
+ "compatible_with": ["Ollama", "LangChain", "vLLM"],
944
+ },
945
+ }
946
+
947
+
948
+ # ============================================================================
949
+ # 12. Attention evaluation (NEW V6.5-attn)
950
+ # ============================================================================
951
+ def evaluate_attention(kls: KohonenLearningSystem) -> Dict[str, Any]:
952
+ """V6.5-attn — Avalia se o mecanismo de atenção está ativo e funcional.
953
+
954
+ User requirement: "verificar se o mecanismo de atenção está ativo e
955
+ acessado logicamente funcional"
956
+ """
957
+ import torch
958
+ # Snapshot das métricas atuais
959
+ metrics_snapshot = kls.get_attention_metrics()
960
+
961
+ # Teste explícito: chama text_to_4d_vector com attention e verifica output
962
+ test_text = "teste do mecanismo de atenção ativo"
963
+ vec_with_attn = text_to_4d_vector(
964
+ test_text, kls.tokenizer, kls.embedding, kls.hidden_dim,
965
+ kls.seq_len, kls.time_counter + 1, kls.T_max,
966
+ attention=kls.attention, attention_metrics=kls.attention_metrics,
967
+ )
968
+ vec_without_attn = text_to_4d_vector(
969
+ test_text, kls.tokenizer, kls.embedding, kls.hidden_dim,
970
+ kls.seq_len, kls.time_counter + 1, kls.T_max,
971
+ attention=None, attention_metrics=None,
972
+ )
973
+ # Verifica que vec_with_attn != vec_without_attn (attention modifies output)
974
+ diff = (vec_with_attn - vec_without_attn).norm().item()
975
+ metrics_after = kls.get_attention_metrics()
976
+ return {
977
+ "evaluation": "attention_active_and_functional_v65_attn",
978
+ "user_requirement": "verificar se o mecanismo de atenção está ativo e acessado logicamente funcional",
979
+ "module_type": str(type(kls.attention).__name__) if kls.attention else "None",
980
+ "module_is_MultiHeadAttention": isinstance(kls.attention, MultiHeadAttention),
981
+ "snapshot_before_explicit_test": metrics_snapshot,
982
+ "snapshot_after_explicit_test": metrics_after,
983
+ "explicit_test": {
984
+ "test_text": test_text,
985
+ "vec_with_attn_norm": float(vec_with_attn.norm().item()),
986
+ "vec_without_attn_norm": float(vec_without_attn.norm().item()),
987
+ "vec_diff_norm": float(diff),
988
+ "attention_modifies_output": bool(diff > 1e-6),
989
+ },
990
+ "summary": {
991
+ "active": metrics_after["active"],
992
+ "n_calls": metrics_after["n_calls"],
993
+ "n_errors": metrics_after["n_errors"],
994
+ "last_attn_activated": metrics_after["last_attn_activated"],
995
+ "logic_functional": metrics_after["logic_functional"],
996
+ "attention_modifies_output": bool(diff > 1e-6),
997
+ "verdict": "ACTIVE_AND_FUNCTIONAL" if (
998
+ metrics_after["logic_functional"] and diff > 1e-6
999
+ ) else "NOT_FUNCTIONAL",
1000
+ },
1001
+ }
1002
+
1003
+
1004
+ # ============================================================================
1005
+ # 11.5 NEW V6.5-attn-v2 — Salvar estados do modelo para avaliação
1006
+ # ============================================================================
1007
+ def save_model_states_for_evaluation(
1008
+ kls: KohonenLearningSystem,
1009
+ reason: str,
1010
+ step: int,
1011
+ total_samples: int,
1012
+ output_path: Optional[Path] = None,
1013
+ ) -> Dict[str, Any]:
1014
+ """V6.5-attn-v2 — Salva estados do modelo (SOM pesos, classifier, métricas)
1015
+ em disco para avaliação posterior.
1016
+
1017
+ User requirement (latest): "parar se o Armazenamento for crítico e
1018
+ armazenar os estados do modelo para avaliação"
1019
+
1020
+ Salva:
1021
+ - som.weights (I,J,K,L,4) — tensor principal do SOM
1022
+ - som.old_weights_w / fisher_w (se existirem)
1023
+ - classifier.state_dict() (se treinado)
1024
+ - kls.get_state_metrics() — snapshot completo das métricas
1025
+ - buffer_4d (até 128 amostras mais recentes, para reavaliação)
1026
+ - metadados (reason, step, total_samples, timestamp)
1027
+
1028
+ Args:
1029
+ kls: instância do KohonenLearningSystem.
1030
+ reason: motivo do save (ex: "storage_critical", "end_of_training").
1031
+ step: step atual.
1032
+ total_samples: total de samples processados até aqui.
1033
+ output_path: caminho do arquivo .pt (default MODEL_STATES_PATH).
1034
+
1035
+ Returns:
1036
+ Dict com metadados do save (caminho, tamanho, n_tensors).
1037
+ """
1038
+ import torch
1039
+ if output_path is None:
1040
+ output_path = MODEL_STATES_PATH
1041
+ try:
1042
+ state = {
1043
+ "_meta": {
1044
+ "reason": str(reason),
1045
+ "step": int(step),
1046
+ "total_samples": int(total_samples),
1047
+ "timestamp": datetime.now().isoformat(),
1048
+ "version": "V6.5-attn-v2",
1049
+ "som_grid": list(kls.som_grid),
1050
+ "n_neurons": int(kls.som_neuron_count),
1051
+ "hidden_dim": int(kls.hidden_dim),
1052
+ "vocab_size": int(kls.tokenizer.vocab_size),
1053
+ "classifier_trained": bool(kls.classifier_trained),
1054
+ "punishment_count": int(kls.punishment_count),
1055
+ "success_count": int(kls.success_count),
1056
+ "time_counter": int(kls.time_counter),
1057
+ },
1058
+ "som_weights": kls.som.weights.detach().clone().cpu(),
1059
+ "som_old_weights_w": (
1060
+ kls.som.old_weights_w.detach().clone().cpu()
1061
+ if kls.som.old_weights_w is not None else None
1062
+ ),
1063
+ "som_fisher_w": (
1064
+ kls.som.fisher_w.detach().clone().cpu()
1065
+ if kls.som.fisher_w is not None else None
1066
+ ),
1067
+ "embedding_state": {
1068
+ "weight": kls.embedding.weight.detach().clone().cpu(),
1069
+ },
1070
+ "classifier_state": (
1071
+ kls.classifier.state_dict() if kls.classifier is not None else None
1072
+ ),
1073
+ "state_metrics": kls.get_state_metrics(),
1074
+ "buffer_4d_tail": (
1075
+ [v.detach().clone().cpu() for v in kls.buffer_4d[-128:]]
1076
+ if kls.buffer_4d else []
1077
+ ),
1078
+ "buffer_labels_tail": list(kls.buffer_labels[-128:]) if kls.buffer_labels else [],
1079
+ }
1080
+ torch.save(state, output_path)
1081
+ size_mb = output_path.stat().st_size / 1e6
1082
+ logger.info(
1083
+ f"[V6.5-attn-v2] Model states saved to {output_path} "
1084
+ f"({size_mb:.1f}MB, reason={reason}, step={step}, "
1085
+ f"total_samples={total_samples})"
1086
+ )
1087
+ return {
1088
+ "saved": True,
1089
+ "path": str(output_path),
1090
+ "size_mb": float(size_mb),
1091
+ "reason": str(reason),
1092
+ "step": int(step),
1093
+ "total_samples": int(total_samples),
1094
+ "n_tensors": 5 + (1 if state["classifier_state"] else 0),
1095
+ "n_buffer_tail": len(state["buffer_4d_tail"]),
1096
+ }
1097
+ except Exception as e:
1098
+ logger.error(f"[V6.5-attn-v2] Failed to save model states: {e}")
1099
+ traceback.print_exc()
1100
+ return {
1101
+ "saved": False,
1102
+ "error": str(e)[:300],
1103
+ "reason": str(reason),
1104
+ "step": int(step),
1105
+ "total_samples": int(total_samples),
1106
+ }
1107
+
1108
+
1109
+ # ============================================================================
1110
+ # 11.6 NEW V6.5-attn-v2 — Lançar perguntas do usuário SEM AJUDAR o modelo
1111
+ # ============================================================================
1112
+ def launch_user_questions_without_help(
1113
+ kls: KohonenLearningSystem,
1114
+ ) -> Dict[str, Any]:
1115
+ """V6.5-attn-v2 — Envia as 3 perguntas específicas SEM nenhum contexto.
1116
+
1117
+ User requirement (latest): "não ajudar o modelo em respostas e lançar
1118
+ perguntas: 'Luva de Pedreiro Távila' e 'Lula reserva valor' e
1119
+ 'Amazonas força-tarefa vítimas'"
1120
+
1121
+ IMPORTANTE: As perguntas são enviadas EXATAMENTE como o usuário as escreveu,
1122
+ sem nenhum prompt adicional, sem contexto, sem instrução de formato,
1123
+ sem system prompt, sem few-shot examples. O modelo deve responder apenas
1124
+ com o que aprendeu — qualquer "ajuda" do script invalidaria a avaliação.
1125
+
1126
+ Para cada pergunta, registramos:
1127
+ - query (string exata enviada)
1128
+ - som_prediction (classificação binária do SOM)
1129
+ - reasoning_text (texto bruto produzido pelo ReasoningEngine)
1130
+ - has_think / has_plan / has_decompose / has_answer tags
1131
+ - think_preview / answer_preview (até 200 chars)
1132
+ - response_length, n_tags
1133
+ - latency_ms (tempo de resposta)
1134
+ """
1135
+ user_questions = [
1136
+ "Luva de Pedreiro Távila",
1137
+ "Lula reserva valor",
1138
+ "Amazonas força-tarefa vítimas",
1139
+ ]
1140
+ results = []
1141
+ import re
1142
+ for q in user_questions:
1143
+ t_start = time.time()
1144
+ try:
1145
+ som_pred = kls.predict(q)
1146
+ except Exception as e:
1147
+ som_pred = f"<predict_error: {e}>"
1148
+ try:
1149
+ reasoning_text = kls.reason_sync(q)
1150
+ except Exception as e:
1151
+ reasoning_text = f"<reasoning_error: {e}>"
1152
+ latency_ms = (time.time() - t_start) * 1000.0
1153
+ think_match = re.search(r"<think>(.*?)</think>", reasoning_text, re.DOTALL)
1154
+ plan_match = re.search(r"<plan>(.*?)</plan>", reasoning_text, re.DOTALL)
1155
+ answer_match = re.search(r"<answer>(.*?)</answer>", reasoning_text, re.DOTALL)
1156
+ decompose_match = re.search(r"<decompose>(.*?)</decompose>", reasoning_text, re.DOTALL)
1157
+ results.append({
1158
+ "query": q,
1159
+ "query_was_modified": False, # CRÍTICO: enviado exatamente como o usuário pediu
1160
+ "context_provided": False, # CRÍTICO: nenhum contexto adicional
1161
+ "system_prompt_used": False, # CRÍTICO: sem system prompt
1162
+ "few_shot_examples": False, # CRÍTICO: sem exemplos
1163
+ "som_prediction": str(som_pred),
1164
+ "reasoning_length": int(len(reasoning_text)),
1165
+ "has_think": bool(think_match),
1166
+ "has_plan": bool(plan_match),
1167
+ "has_answer": bool(answer_match),
1168
+ "has_decompose": bool(decompose_match),
1169
+ "think_preview": (
1170
+ think_match.group(1).strip()[:200] + ("..." if len(think_match.group(1)) > 200 else "")
1171
+ ) if think_match else "",
1172
+ "plan_preview": (
1173
+ plan_match.group(1).strip()[:200] + ("..." if len(plan_match.group(1)) > 200 else "")
1174
+ ) if plan_match else "",
1175
+ "answer_preview": (
1176
+ answer_match.group(1).strip()[:200] + ("..." if len(answer_match.group(1)) > 200 else "")
1177
+ ) if answer_match else "",
1178
+ "decompose_preview": (
1179
+ decompose_match.group(1).strip()[:200] + ("..." if len(decompose_match.group(1)) > 200 else "")
1180
+ ) if decompose_match else "",
1181
+ "raw_response_preview": reasoning_text[:500] + ("..." if len(reasoning_text) > 500 else ""),
1182
+ "n_tags": sum(1 for tag in ["<think>", "<plan>", "<decompose>", "<answer>"] if tag in reasoning_text),
1183
+ "latency_ms": float(latency_ms),
1184
+ })
1185
+ n_answer = sum(1 for r in results if r["has_answer"])
1186
+ n_think = sum(1 for r in results if r["has_think"])
1187
+ n_plan = sum(1 for r in results if r["has_plan"])
1188
+ n_decompose = sum(1 for r in results if r["has_decompose"])
1189
+ return {
1190
+ "evaluation": "user_questions_without_help_v65_attn_v2",
1191
+ "user_requirement": "não ajudar o modelo em respostas e lançar perguntas",
1192
+ "questions_sent_verbatim": True,
1193
+ "no_context_added": True,
1194
+ "no_system_prompt": True,
1195
+ "no_few_shot": True,
1196
+ "n_questions": len(user_questions),
1197
+ "questions": user_questions,
1198
+ "results": results,
1199
+ "summary": {
1200
+ "n_with_answer": n_answer,
1201
+ "n_with_think": n_think,
1202
+ "n_with_plan": n_plan,
1203
+ "n_with_decompose": n_decompose,
1204
+ "answer_rate": float(n_answer / max(1, len(results))),
1205
+ "think_rate": float(n_think / max(1, len(results))),
1206
+ "plan_rate": float(n_plan / max(1, len(results))),
1207
+ "decompose_rate": float(n_decompose / max(1, len(results))),
1208
+ "avg_latency_ms": float(sum(r["latency_ms"] for r in results) / max(1, len(results))),
1209
+ "avg_reasoning_length": float(sum(r["reasoning_length"] for r in results) / max(1, len(results))),
1210
+ },
1211
+ "quality_assessment": {
1212
+ "response_quality": "GOOD" if n_answer == len(results) else (
1213
+ "PARTIAL" if n_answer > 0 else "NO_RESPONSE"
1214
+ ),
1215
+ "reasoning_quality": "GOOD" if n_think == len(results) else (
1216
+ "PARTIAL" if n_think > 0 else "NO_REASONING"
1217
+ ),
1218
+ "model_not_helped": True, # CRÍTICO: resposta do modelo não foi auxiliada
1219
+ "note": (
1220
+ "As 3 perguntas foram enviadas verbatim, sem system prompt, "
1221
+ "sem few-shot, sem contexto adicional. Qualquer resposta "
1222
+ "produzida reflete apenas o que o modelo aprendeu no treino."
1223
+ ),
1224
+ },
1225
+ }
1226
+
1227
+
1228
+ # ============================================================================
1229
+ # 13. Metrics Monitor V6.5-attn (inclui attention block)
1230
+ # ============================================================================
1231
+ class MetricsMonitorV65Attn:
1232
+ def __init__(self) -> None:
1233
+ self.steps: List[Dict[str, Any]] = []
1234
+ self.alerts: List[Dict[str, Any]] = []
1235
+ self.start_time = time.time()
1236
+ self._prev_loss: Optional[float] = None
1237
+
1238
+ def record_step(
1239
+ self,
1240
+ step: int,
1241
+ phase: int,
1242
+ epoch: int,
1243
+ dataset_name: str,
1244
+ batch_loss: float,
1245
+ batch_acc: float,
1246
+ kls: KohonenLearningSystem,
1247
+ mtp_metrics: Optional[Dict[str, Any]] = None,
1248
+ rss_mb: float = 0.0,
1249
+ disk_pct: float = 0.0,
1250
+ ) -> None:
1251
+ som_metrics = kls.som.get_metrics()
1252
+ quality = {
1253
+ "1.1_train_loss": float(batch_loss),
1254
+ "1.2_train_acc": float(batch_acc),
1255
+ "1.3_val_loss": float(batch_loss),
1256
+ "1.4_val_acc": float(batch_acc),
1257
+ "1.5_perplexity": float(2.718281828 ** min(batch_loss, 20)),
1258
+ }
1259
+ elapsed = time.time() - self.start_time
1260
+ speed = {
1261
+ "2.1_throughput_sps": float((step + 1) * BATCH_SIZE / max(elapsed, 1e-6)),
1262
+ "2.2_step_time_ms": float(elapsed * 1000 / max(step + 1, 1)),
1263
+ "2.3_epoch_progress": 1.0,
1264
+ "2.4_rss_mb": float(rss_mb),
1265
+ "2.5_xeon_tflops": float(FP16_BENCH.get("best_tflops", 0.0)),
1266
+ "2.6_disk_pct": float(disk_pct),
1267
+ }
1268
+ kohonen = {
1269
+ "sigma_t": float(som_metrics["sigma_t"]),
1270
+ "alpha_t": float(som_metrics["alpha_t"]),
1271
+ "t": int(som_metrics["t"]),
1272
+ "n_neurons": int(som_metrics["n_neurons"]),
1273
+ "fisher_w_mean": float(som_metrics["fisher_w_mean"]),
1274
+ "fisher_w_max": float(som_metrics["fisher_w_max"]),
1275
+ "fisher_accum_count": int(som_metrics["fisher_accum_count"]),
1276
+ "has_ewc_reference": bool(som_metrics["has_ewc_reference"]),
1277
+ "weights_norm": float(som_metrics["weights_norm"]),
1278
+ "weights_w_mean": float(som_metrics["weights_w_mean"]),
1279
+ }
1280
+ hyp = {
1281
+ "classifier_trained": bool(kls.classifier_trained),
1282
+ "punishment_count": int(kls.punishment_count),
1283
+ "success_count": int(kls.success_count),
1284
+ "training_ready": bool(kls.training_ready),
1285
+ "buffer_size": int(len(kls.buffer_4d)),
1286
+ "required_new_samples": int(kls.required_new_samples),
1287
+ "histogram_max": int(max(kls.histogram.values(), default=0)),
1288
+ "time_counter": int(kls.time_counter),
1289
+ }
1290
+ mtp_block = {
1291
+ "active": mtp_metrics is not None,
1292
+ "mtp_total_loss": float(mtp_metrics.get("total_loss", 0.0)) if mtp_metrics else 0.0,
1293
+ "mtp_weighted_loss": float(mtp_metrics.get("weighted_loss", 0.0)) if mtp_metrics else 0.0,
1294
+ "mtp_entropy_reg": float(mtp_metrics.get("entropy_reg", 0.0)) if mtp_metrics else 0.0,
1295
+ "mtp_alphas": mtp_metrics.get("alphas", []) if mtp_metrics else [],
1296
+ "mtp_per_k_loss": mtp_metrics.get("per_k_loss", []) if mtp_metrics else [],
1297
+ "active_in_val": bool(MTP_ACTIVE_IN_VAL),
1298
+ "entropy_beta": float(MTP_ENTROPY_BETA),
1299
+ "K": int(MTP_K),
1300
+ }
1301
+ vq_metrics = kls.get_vqvae2_metrics()
1302
+ vqvae2_block = {
1303
+ "active": bool(vq_metrics.get("active", False)),
1304
+ "n_calls": int(vq_metrics.get("n_calls", 0)),
1305
+ "latest_total_loss": float(vq_metrics.get("latest", {}).get("total_loss", 0.0)),
1306
+ "latest_recon_loss": float(vq_metrics.get("latest", {}).get("recon_loss", 0.0)),
1307
+ "latest_vq_loss": float(vq_metrics.get("latest", {}).get("vq_loss", 0.0)),
1308
+ "mean_total_loss": float(vq_metrics.get("mean_total_loss", 0.0)),
1309
+ }
1310
+ w8a8_metrics = kls.get_w8a8_metrics()
1311
+ w8a8_block = {
1312
+ "active": bool(w8a8_metrics.get("active", False)),
1313
+ "n_calls": int(w8a8_metrics.get("n_calls", 0)),
1314
+ "latest_relative_error": float(w8a8_metrics.get("latest", {}).get("relative_error", 0.0)),
1315
+ "latest_compression_ratio": float(w8a8_metrics.get("latest", {}).get("compression_ratio", 0.0)),
1316
+ "latest_preserves_topology": bool(w8a8_metrics.get("latest", {}).get("preserves_topology", False)),
1317
+ "mean_relative_error": float(w8a8_metrics.get("mean_relative_error", 0.0)),
1318
+ "all_preserve_topology": bool(w8a8_metrics.get("all_preserve_topology", False)),
1319
+ }
1320
+ # NEW V6.5-attn: attention metrics
1321
+ attn_metrics = kls.get_attention_metrics()
1322
+ attention_block = {
1323
+ "active": bool(attn_metrics.get("active", False)),
1324
+ "n_calls": int(attn_metrics.get("n_calls", 0)),
1325
+ "n_errors": int(attn_metrics.get("n_errors", 0)),
1326
+ "last_norm_in": float(attn_metrics.get("last_norm_in", 0.0)),
1327
+ "last_norm_out": float(attn_metrics.get("last_norm_out", 0.0)),
1328
+ "last_attn_activated": bool(attn_metrics.get("last_attn_activated", False)),
1329
+ "last_attn_diff_norm": float(attn_metrics.get("last_attn_diff_norm", 0.0)),
1330
+ "n_heads": int(attn_metrics.get("n_heads", 0)),
1331
+ "logic_functional": bool(attn_metrics.get("logic_functional", False)),
1332
+ }
1333
+ reasoning_stats = kls.get_reasoning_stats()
1334
+ reasoning_block = {
1335
+ "active": bool(reasoning_stats.get("active", False)),
1336
+ "n_history": int(reasoning_stats.get("n_history", 0)),
1337
+ "n_steps_last": int(reasoning_stats.get("stats", {}).get("n_steps", 0)),
1338
+ "phases_used": reasoning_stats.get("stats", {}).get("phases_used", []),
1339
+ "tool_coordinator_workers_active": bool(
1340
+ getattr(kls, "_tool_coordinator_workers_active", False)
1341
+ ),
1342
+ }
1343
+ ewc_block = {
1344
+ "active": bool(som_metrics["has_ewc_reference"]),
1345
+ "ewc_eval_mode_penalty": bool(EWCConfigV6().eval_mode_penalty),
1346
+ "w8a8_dequant_active": True,
1347
+ "fisher_w_mean": float(som_metrics["fisher_w_mean"]),
1348
+ "fisher_w_max": float(som_metrics["fisher_w_max"]),
1349
+ "fisher_accum_count": int(som_metrics["fisher_accum_count"]),
1350
+ }
1351
+ # Alerts
1352
+ if self._prev_loss is not None:
1353
+ delta = abs(batch_loss - self._prev_loss)
1354
+ if delta > 5.0:
1355
+ self.alerts.append({"type": "3.1_loss_spike", "step": step, "delta": float(delta)})
1356
+ if batch_loss > 30.0:
1357
+ self.alerts.append({"type": "3.2_loss_explosion", "step": step, "value": float(batch_loss)})
1358
+ if batch_loss < 0.001:
1359
+ self.alerts.append({"type": "3.3_loss_vanishing", "step": step, "value": float(batch_loss)})
1360
+ self._prev_loss = float(batch_loss)
1361
+ if rss_mb > 3500:
1362
+ self.alerts.append({"type": "3.4_rss_high", "step": step, "rss_mb": float(rss_mb)})
1363
+ if disk_pct > STORAGE_CRITICAL_PCT:
1364
+ self.alerts.append({
1365
+ "type": "3.5_storage_critical", "step": step,
1366
+ "disk_pct": float(disk_pct), "threshold": STORAGE_CRITICAL_PCT,
1367
+ })
1368
+ if not attn_metrics.get("logic_functional", False) and attn_metrics.get("n_calls", 0) > 0:
1369
+ self.alerts.append({
1370
+ "type": "3.6_attention_not_functional", "step": step,
1371
+ "n_calls": int(attn_metrics.get("n_calls", 0)),
1372
+ "n_errors": int(attn_metrics.get("n_errors", 0)),
1373
+ })
1374
+
1375
+ self.steps.append({
1376
+ "step": step, "phase": phase, "epoch": epoch, "dataset": dataset_name,
1377
+ "quality": quality, "speed": speed, "kohonen": kohonen,
1378
+ "hypothesis": hyp, "mtp": mtp_block, "vqvae2": vqvae2_block,
1379
+ "w8a8": w8a8_block, "attention": attention_block,
1380
+ "reasoning": reasoning_block, "ewc": ewc_block,
1381
+ })
1382
+
1383
+ def summary(self) -> Dict[str, Any]:
1384
+ if not self.steps:
1385
+ return {}
1386
+ final = self.steps[-1]
1387
+ losses = [s["quality"]["1.1_train_loss"] for s in self.steps]
1388
+ accs = [s["quality"]["1.2_train_acc"] for s in self.steps]
1389
+ sigmas = [s["kohonen"]["sigma_t"] for s in self.steps]
1390
+ vq_losses = [s["vqvae2"]["latest_total_loss"] for s in self.steps
1391
+ if s["vqvae2"]["active"] and not math.isnan(s["vqvae2"]["latest_total_loss"])]
1392
+ w8a8_errors = [s["w8a8"]["latest_relative_error"] for s in self.steps
1393
+ if s["w8a8"]["active"] and not math.isnan(s["w8a8"]["latest_relative_error"])]
1394
+ attn_calls = [s["attention"]["n_calls"] for s in self.steps]
1395
+ rss_max = max(s["speed"]["2.4_rss_mb"] for s in self.steps)
1396
+ disk_max = max(s["speed"]["2.6_disk_pct"] for s in self.steps)
1397
+ return {
1398
+ "n_steps": len(self.steps),
1399
+ "final_loss": float(losses[-1]),
1400
+ "mean_loss": float(sum(losses) / len(losses)),
1401
+ "min_loss": float(min(losses)),
1402
+ "max_loss": float(max(losses)),
1403
+ "final_acc": float(accs[-1]),
1404
+ "mean_acc": float(sum(accs) / len(accs)),
1405
+ "sigma_start": float(sigmas[0]),
1406
+ "sigma_end": float(sigmas[-1]),
1407
+ "vqvae2_mean_total_loss": float(sum(vq_losses) / max(1, len(vq_losses))) if vq_losses else 0.0,
1408
+ "vqvae2_final_total_loss": float(vq_losses[-1]) if vq_losses else 0.0,
1409
+ "w8a8_mean_relative_error": float(sum(w8a8_errors) / max(1, len(w8a8_errors))) if w8a8_errors else 0.0,
1410
+ "w8a8_final_relative_error": float(w8a8_errors[-1]) if w8a8_errors else 0.0,
1411
+ "attention_final_n_calls": int(attn_calls[-1]) if attn_calls else 0,
1412
+ "attention_max_n_calls": int(max(attn_calls)) if attn_calls else 0,
1413
+ "rss_max_mb": float(rss_max),
1414
+ "rss_final_mb": float(final["speed"]["2.4_rss_mb"]),
1415
+ "disk_max_pct": float(disk_max),
1416
+ "disk_final_pct": float(final["speed"]["2.6_disk_pct"]),
1417
+ "n_alerts": len(self.alerts),
1418
+ "alerts": self.alerts[:30],
1419
+ "kohonen_final": final["kohonen"],
1420
+ "hypothesis_final": final["hypothesis"],
1421
+ "mtp_final": final["mtp"],
1422
+ "vqvae2_final": final["vqvae2"],
1423
+ "w8a8_final": final["w8a8"],
1424
+ "attention_final": final["attention"],
1425
+ "reasoning_final": final["reasoning"],
1426
+ "ewc_final": final["ewc"],
1427
+ }
1428
+
1429
+
1430
+ # ============================================================================
1431
+ # 14. Função principal de treino
1432
+ # ============================================================================
1433
+ def main() -> int:
1434
+ import torch
1435
+
1436
+ n_neurons = SOM_GRID[0] * SOM_GRID[1] * SOM_GRID[2] * SOM_GRID[3]
1437
+ print("\n" + "=" * 80)
1438
+ print("V6.5-attn-v2 — ATTENTION + 100/BATCH + 7 DATASETS + META ≥6000 + SAVE STATES + USER QUESTIONS")
1439
+ print("=" * 80)
1440
+ print(f" BATCH_SIZE : {BATCH_SIZE}")
1441
+ print(f" STREAM_BATCH_SIZE : {STREAM_BATCH_SIZE} (user: 'de 100 em 100')")
1442
+ print(f" Datasets to exhaust : {len(V65_DATASETS_TO_EXHAUST)}")
1443
+ print(f" Max samples/dataset : {MAX_SAMPLES_PER_DATASET}")
1444
+ print(f" Total samples target : {TOTAL_SAMPLES_TARGET} (meta ≥{META_MINIMA_SAMPLES})")
1445
+ print(f" SOM grid : {SOM_GRID} ({n_neurons} neurons)")
1446
+ print(f" HIDDEN_DIM : {HIDDEN_DIM}")
1447
+ print(f" VOCAB_SIZE : {VOCAB_SIZE}")
1448
+ print(f" MTP K : {MTP_K}")
1449
+ print(f" Attention : MultiHeadAttention (n_heads=8, integrated to text_to_4d_vector)")
1450
+ print(f" V65_ENABLE_STREAMING : {os.environ.get('V65_ENABLE_STREAMING')} (REAL)")
1451
+ print(f" SmoothQuant W8A8 : True")
1452
+ print(f" Tool coordinator : True (4 workers)")
1453
+ print(f" Inter-batch pause : {INTER_BATCH_PAUSE_S}s")
1454
+ print(f" Inter-stream pause : {INTER_STREAM_BATCH_PAUSE_S}s")
1455
+ print(f" Inter-dataset pause : {INTER_DATASET_PAUSE_S}s")
1456
+ print(f" Storage critical : {STORAGE_CRITICAL_PCT}%")
1457
+ print(f" Xeon cores : {N_CORES}")
1458
+ print(f" FP16 best TFLOPS : {FP16_BENCH.get('best_tflops', 0.0):.3f}")
1459
+ print("=" * 80 + "\n")
1460
+
1461
+ # 14.1 Module Access Analysis
1462
+ logger.info("[V6.5-attn] Running module access analysis...")
1463
+ module_analysis = analyze_module_access()
1464
+ MODULE_ANALYSIS_PATH.write_text(json.dumps(module_analysis, indent=2, ensure_ascii=False))
1465
+
1466
+ # 14.2 Script Activity Monitor
1467
+ logger.info("[V6.5-attn] Monitoring script activity...")
1468
+ script_activity = monitor_script_activity()
1469
+ SCRIPT_ACTIVITY_PATH.write_text(json.dumps(script_activity, indent=2, ensure_ascii=False))
1470
+
1471
+ # 14.3 Verify logic and bug fixes (11 checks, +attention)
1472
+ logger.info("[V6.5-attn] Verifying logic and bug fixes (11 checks, +attention)...")
1473
+ verification = verify_logic_and_bugfixes()
1474
+ print(f"\n--- Logic & Bug Fix Verification ---")
1475
+ print(f" PASS: {verification['n_pass']}/{verification['n_pass'] + verification['n_fail']}")
1476
+ for check_name, check_info in verification["checks"].items():
1477
+ status = check_info.get("status", "?")
1478
+ details = check_info.get("details", check_info.get("error", ""))
1479
+ print(f" [{status}] {check_name}: {details[:100]}")
1480
+
1481
+ # 14.4 EWC+W8A8 benchmark with active dequantization
1482
+ logger.info("[V6.5-attn] Benchmarking EWC+W8A8 eval with active dequantization...")
1483
+ ewc_w8a8_benchmark = benchmark_ewc_w8a8_dequant()
1484
+ EWC_W8A8_BENCH_PATH.write_text(json.dumps(ewc_w8a8_benchmark, indent=2, ensure_ascii=False))
1485
+ print(f"\n--- EWC+W8A8 Benchmark (dequant active) ---")
1486
+ print(f" Baseline float penalty : {ewc_w8a8_benchmark['results']['baseline_float']['penalty']:.6f}")
1487
+ print(f" W8A8+dequant penalty : {ewc_w8a8_benchmark['results']['w8a8_with_dequant']['penalty']:.6f}")
1488
+ print(f" W8A8 no-dequant penalty: {ewc_w8a8_benchmark['results']['w8a8_no_dequant_broken']['penalty']:.6f}")
1489
+ print(f" Dequant relative error : {ewc_w8a8_benchmark['analysis']['dequant_relative_error']:.6f}")
1490
+
1491
+ # 14.5 Initialize KLS (864 neurons + W8A8 + reasoning + ATTENTION)
1492
+ kls = KohonenLearningSystem(
1493
+ vocab_size=VOCAB_SIZE,
1494
+ hidden_dim=HIDDEN_DIM,
1495
+ seq_len=MAX_SEQ_LEN,
1496
+ som_grid=SOM_GRID,
1497
+ alpha0=ALPHA0,
1498
+ sigma0=SIGMA0,
1499
+ lambda_ewc=LAMBDA_EWC,
1500
+ N_start=N_START,
1501
+ dim_choice=DIM_CHOICE,
1502
+ hypothesis_hidden=[512, 256, 128, 64, 32, 16, 8],
1503
+ T_max=T_MAX,
1504
+ enable_vqvae2=True,
1505
+ enable_reasoning=True,
1506
+ enable_w8a8=True,
1507
+ vqvae2_code_dim=16,
1508
+ vqvae2_num_codes_top=64,
1509
+ vqvae2_num_codes_bot=128,
1510
+ w8a8_alpha=0.5,
1511
+ w8a8_n_bits=8,
1512
+ w8a8_calibration_samples=128,
1513
+ # V6.5-attn: attention ativo
1514
+ enable_attention=True,
1515
+ attention_n_heads=8,
1516
+ )
1517
+ logger.info(
1518
+ f"[V6.5-attn] KLS initialized: {n_neurons} neurons, hidden={HIDDEN_DIM}, "
1519
+ f"vocab={VOCAB_SIZE}, w8a8={kls.enable_w8a8}, "
1520
+ f"attention={kls.enable_attention} (n_heads={kls.attention_n_heads}), "
1521
+ f"workers_active={kls._tool_coordinator_workers_active}"
1522
+ )
1523
+
1524
+ # Treina tokenizer com corpus básico PT-BR
1525
+ corpus_inicial = [
1526
+ "o gato dorme na cama", "a casa eh azul", "ele corre rapido",
1527
+ "ela canta uma musica", "o sol nasceu hoje", "nos vamos viajar",
1528
+ "o livro esta na mesa", "a menina brinca no parque",
1529
+ "ola como voce esta", "qual e o seu nome",
1530
+ "calcule dois mais dois", "traduza hello para portugues",
1531
+ "instrucao para resolver o problema", "resposta para a pergunta",
1532
+ ]
1533
+ kls.tokenizer.fit(corpus_inicial)
1534
+ logger.info(f"[V6.5-attn] Tokenizer fitted with {len(corpus_inicial)} corpus words")
1535
+
1536
+ # Initialize MTP head — K=6
1537
+ mtp_head = MTPHead(
1538
+ hidden_size=HIDDEN_DIM,
1539
+ vocab_size=VOCAB_SIZE,
1540
+ K=MTP_K,
1541
+ dropout=0.0,
1542
+ )
1543
+ logger.info(f"[V6.5-attn] MTPHead initialized (K={MTP_K})")
1544
+
1545
+ # Monitor
1546
+ monitor = MetricsMonitorV65Attn()
1547
+
1548
+ # HF_TOKEN
1549
+ hf_token = os.environ.get("HF_TOKEN")
1550
+ if not hf_token:
1551
+ logger.warning("[V6.5-attn] HF_TOKEN not set — streaming may fail for gated datasets")
1552
+ else:
1553
+ logger.info(f"[V6.5-attn] HF_TOKEN set: {hf_token[:8]}...")
1554
+
1555
+ # 14.6 Aggressive storage cleanup before training starts
1556
+ # V6.5-attn: defensive — wrap in try/except to prevent crash here
1557
+ logger.info("[V6.5-attn] Aggressive storage cleanup (pre-training)...")
1558
+ try:
1559
+ storage_cleanup_pre = aggressive_storage_cleanup()
1560
+ aggressive_memory_cleanup()
1561
+ logger.info(
1562
+ f"[V6.5-attn] Pre-training cleanup: "
1563
+ f"{storage_cleanup_pre['n_files_removed']} files, "
1564
+ f"{storage_cleanup_pre['mb_freed']:.1f}MB freed"
1565
+ )
1566
+ except Exception as e:
1567
+ logger.warning(f"[V6.5-attn] Pre-training cleanup failed (continuing): {e}")
1568
+ storage_cleanup_pre = {"n_files_removed": 0, "mb_freed": 0.0, "error": str(e)[:200]}
1569
+ aggressive_memory_cleanup()
1570
+
1571
+ # 14.7 TREINO: stream 100 samples at a time per dataset, accumulate until
1572
+ # meta ≥5000 OR all datasets exhausted OR storage critical.
1573
+ # User requirement: "streaming de 100 em 100 samples até esgotar" +
1574
+ # "meta mínima 5000 samples ou mais"
1575
+ step = 0
1576
+ t_train_start = time.time()
1577
+ samples_per_dataset_actual = {ds: 0 for ds in V65_DATASETS_TO_EXHAUST}
1578
+ streaming_failures = {ds: 0 for ds in V65_DATASETS_TO_EXHAUST}
1579
+ storage_critical_stopped = False
1580
+ w8a8_compression_log: List[Dict[str, Any]] = []
1581
+ attention_log: List[Dict[str, Any]] = [] # NEW V6.5-attn
1582
+ chunk_idx_global = 0
1583
+
1584
+ for ds_idx, dataset_name in enumerate(V65_DATASETS_TO_EXHAUST):
1585
+ if storage_critical_stopped:
1586
+ break
1587
+ total_so_far = sum(samples_per_dataset_actual.values())
1588
+ if total_so_far >= TOTAL_SAMPLES_TARGET:
1589
+ logger.info(
1590
+ f"[V6.5-attn] Total target reached ({total_so_far} ≥ {TOTAL_SAMPLES_TARGET}). Stopping."
1591
+ )
1592
+ break
1593
+ logger.info(
1594
+ f"\n[V6.5-attn] {'='*40} DATASET {ds_idx+1}/{len(V65_DATASETS_TO_EXHAUST)}: "
1595
+ f"{dataset_name} {'='*40}"
1596
+ )
1597
+ logger.info(
1598
+ f"[V6.5-attn] Streaming {dataset_name} in chunks of {STREAM_BATCH_SIZE} "
1599
+ f"(target: {MAX_SAMPLES_PER_DATASET} samples max)..."
1600
+ )
1601
+ # STREAM IN CHUNKS of 100 — User requirement: "de 100 em 100 samples"
1602
+ try:
1603
+ chunk_iter = stream_dataset_in_chunks(
1604
+ dataset_name=dataset_name,
1605
+ chunk_size=STREAM_BATCH_SIZE,
1606
+ max_total=MAX_SAMPLES_PER_DATASET,
1607
+ hf_token=hf_token,
1608
+ timeout_per_chunk=60,
1609
+ )
1610
+ for chunk_samples in chunk_iter:
1611
+ if storage_critical_stopped:
1612
+ break
1613
+ total_so_far = sum(samples_per_dataset_actual.values())
1614
+ if total_so_far >= TOTAL_SAMPLES_TARGET:
1615
+ logger.info(
1616
+ f"[V6.5-attn] Total target reached during {dataset_name}. Stopping."
1617
+ )
1618
+ break
1619
+ chunk_idx_global += 1
1620
+ if not chunk_samples:
1621
+ streaming_failures[dataset_name] += 1
1622
+ logger.warning(
1623
+ f"[V6.5-attn] Empty chunk for {dataset_name} "
1624
+ f"(failure #{streaming_failures[dataset_name]})."
1625
+ )
1626
+ continue
1627
+ samples_per_dataset_actual[dataset_name] += len(chunk_samples)
1628
+ labels = [make_label(s) for s in chunk_samples]
1629
+ logger.info(
1630
+ f"[V6.5-attn] Processing chunk {chunk_idx_global} "
1631
+ f"({len(chunk_samples)} samples) from {dataset_name}"
1632
+ )
1633
+
1634
+ # Processa em batches COM PAUSAS
1635
+ for batch_start in range(0, len(chunk_samples), BATCH_SIZE):
1636
+ try:
1637
+ if step > 0 and step % STORAGE_CHECK_INTERVAL_STEPS == 0:
1638
+ disk_pct = get_disk_usage_pct()
1639
+ if disk_pct > STORAGE_CRITICAL_PCT:
1640
+ logger.error(
1641
+ f"[V6.5-attn-v2] STORAGE CRITICAL: disk={disk_pct:.1f}% "
1642
+ f"> threshold={STORAGE_CRITICAL_PCT}%. STOPPING TRAINING."
1643
+ )
1644
+ # V6.5-attn-v2 — User requirement: "parar se o Armazenamento
1645
+ # for crítico e armazenar os estados do modelo para avaliação"
1646
+ total_now = sum(samples_per_dataset_actual.values())
1647
+ save_model_states_for_evaluation(
1648
+ kls=kls,
1649
+ reason=f"storage_critical_disk_{disk_pct:.1f}pct",
1650
+ step=step,
1651
+ total_samples=total_now,
1652
+ )
1653
+ storage_critical_stopped = True
1654
+ break
1655
+
1656
+ batch_sents = chunk_samples[batch_start: batch_start + BATCH_SIZE]
1657
+ batch_labels = labels[batch_start: batch_start + BATCH_SIZE]
1658
+ try:
1659
+ stop_requested = kls.process_batch(batch_sents, batch_labels)
1660
+ except Exception as e:
1661
+ logger.error(f"[V6.5-attn] process_batch error: {e}")
1662
+ traceback.print_exc()
1663
+ continue
1664
+
1665
+ # Métricas
1666
+ acc = kls.evaluate_classification()
1667
+ loss = -max(0.01, acc) ** 0.5 if acc > 0 else 5.0
1668
+
1669
+ # MTP loss
1670
+ mtp_metrics = None
1671
+ try:
1672
+ if kls.buffer_4d:
1673
+ buffer_data = torch.stack(kls.buffer_4d[-BATCH_SIZE:]).detach()
1674
+ B = buffer_data.size(0)
1675
+ T = MAX_SEQ_LEN
1676
+ hidden_states = buffer_data.unsqueeze(1).expand(B, T, 4).float()
1677
+ hidden_proj = kls.embedding(torch.zeros(B, T, dtype=torch.long))
1678
+ hidden_states = hidden_proj + hidden_states.unsqueeze(-1) * 0.01
1679
+ target_ids = torch.stack([
1680
+ torch.tensor(kls.tokenizer.encode(s, max_length=T))
1681
+ for s in batch_sents
1682
+ ])
1683
+ mtp_metrics = compute_mtp_loss_for_batch(mtp_head, hidden_states, target_ids)
1684
+ except Exception as e:
1685
+ logger.debug(f"[V6.5-attn] MTP loss skipped: {e}")
1686
+ mtp_metrics = None
1687
+
1688
+ # W8A8 compression log
1689
+ w8a8_metrics = kls.get_w8a8_metrics()
1690
+ if w8a8_metrics.get("active") and w8a8_metrics.get("n_calls", 0) > len(w8a8_compression_log):
1691
+ latest = w8a8_metrics.get("latest", {})
1692
+ w8a8_compression_log.append({
1693
+ "step": step, "dataset": dataset_name,
1694
+ "chunk_idx": chunk_idx_global,
1695
+ "relative_error": float(latest.get("relative_error", 0.0)),
1696
+ "compression_ratio": float(latest.get("compression_ratio", 0.0)),
1697
+ "preserves_topology": bool(latest.get("preserves_topology", False)),
1698
+ "smooth_scale_mean": float(latest.get("smooth_scale_mean", 0.0)),
1699
+ "elapsed_ms": float(latest.get("elapsed_ms", 0.0)),
1700
+ })
1701
+
1702
+ # NEW V6.5-attn: attention log
1703
+ attn_metrics = kls.get_attention_metrics()
1704
+ if attn_metrics.get("n_calls", 0) > (len(attention_log) * 16):
1705
+ attention_log.append({
1706
+ "step": step, "dataset": dataset_name,
1707
+ "chunk_idx": chunk_idx_global,
1708
+ "n_calls": int(attn_metrics.get("n_calls", 0)),
1709
+ "n_errors": int(attn_metrics.get("n_errors", 0)),
1710
+ "last_norm_in": float(attn_metrics.get("last_norm_in", 0.0)),
1711
+ "last_norm_out": float(attn_metrics.get("last_norm_out", 0.0)),
1712
+ "last_attn_activated": bool(attn_metrics.get("last_attn_activated", False)),
1713
+ "last_attn_diff_norm": float(attn_metrics.get("last_attn_diff_norm", 0.0)),
1714
+ "logic_functional": bool(attn_metrics.get("logic_functional", False)),
1715
+ })
1716
+
1717
+ # RSS
1718
+ try:
1719
+ import resource
1720
+ rss_kb = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
1721
+ rss_mb = rss_kb / 1024.0
1722
+ except (AttributeError, OSError):
1723
+ rss_mb = 0.0
1724
+
1725
+ disk_pct = get_disk_usage_pct()
1726
+
1727
+ monitor.record_step(
1728
+ step=step, phase=1, epoch=0, dataset_name=dataset_name,
1729
+ batch_loss=float(loss), batch_acc=float(acc), kls=kls,
1730
+ mtp_metrics=mtp_metrics, rss_mb=float(rss_mb), disk_pct=float(disk_pct),
1731
+ )
1732
+ step += 1
1733
+
1734
+ if step % 5 == 0 or step == 1:
1735
+ som_m = kls.som.get_metrics()
1736
+ vq_m = kls.get_vqvae2_metrics()
1737
+ w8_m = kls.get_w8a8_metrics()
1738
+ attn_m = kls.get_attention_metrics()
1739
+ vq_str = (
1740
+ f"vq={vq_m.get('latest', {}).get('total_loss', 0):.3f}"
1741
+ if vq_m.get("active") else "vq=N/A"
1742
+ )
1743
+ w8_str = (
1744
+ f"w8a8_err={w8_m.get('latest', {}).get('relative_error', 0):.4f}"
1745
+ if w8_m.get("active") else "w8a8=N/A"
1746
+ )
1747
+ attn_str = (
1748
+ f"attn_calls={attn_m.get('n_calls', 0)}/{attn_m.get('n_errors', 0)}err"
1749
+ if attn_m.get("active") else "attn=N/A"
1750
+ )
1751
+ mtp_str = (
1752
+ f"mtp={mtp_metrics['total_loss']:.3f}"
1753
+ if mtp_metrics else "mtp=N/A"
1754
+ )
1755
+ total_so_far = sum(samples_per_dataset_actual.values())
1756
+ logger.info(
1757
+ f"[V6.5-attn] step={step:3d} | ds={ds_idx+1}/{len(V65_DATASETS_TO_EXHAUST)} | "
1758
+ f"chunk={chunk_idx_global} | "
1759
+ f"loss={loss:.3f} acc={acc:.3f} | {mtp_str} | {vq_str} | {w8_str} | {attn_str} | "
1760
+ f"σ={som_m['sigma_t']:.3f} | "
1761
+ f"punish={kls.punishment_count} | buff={len(kls.buffer_4d)} | "
1762
+ f"hyp={'Y' if kls.classifier_trained else 'N'} | "
1763
+ f"ewc={'Y' if som_m['has_ewc_reference'] else 'N'} | "
1764
+ f"total={total_so_far}/{TOTAL_SAMPLES_TARGET} (meta≥{META_MINIMA_SAMPLES}) | "
1765
+ f"RSS={rss_mb:.0f}MB | disk={disk_pct:.1f}%"
1766
+ )
1767
+
1768
+ # Limpeza agressiva de memória a cada 10 steps
1769
+ if step % 10 == 0:
1770
+ aggressive_memory_cleanup()
1771
+
1772
+ # Pausa para dar tempo de processar e salvar
1773
+ time.sleep(INTER_BATCH_PAUSE_S)
1774
+
1775
+ if stop_requested:
1776
+ logger.warning(f"[V6.5-attn] stop_requested at step={step}")
1777
+ except Exception as _e_step:
1778
+ logger.error(f"[V6.5-attn] step={step} batch error: {_e_step}")
1779
+ traceback.print_exc()
1780
+ step += 1 # advance even on error
1781
+ continue
1782
+
1783
+ # Pausa extra após cada 100-sample stream batch
1784
+ time.sleep(INTER_STREAM_BATCH_PAUSE_S)
1785
+ # V6.5-attn: defensive cleanup after each chunk — release Arrow state
1786
+ aggressive_memory_cleanup()
1787
+ except Exception as e:
1788
+ logger.error(f"[V6.5-attn] Error streaming {dataset_name}: {e}")
1789
+ traceback.print_exc()
1790
+ streaming_failures[dataset_name] += 1
1791
+ # Pausa entre datasets
1792
+ time.sleep(INTER_DATASET_PAUSE_S)
1793
+ # V6.5-attn: defensive cleanup after each dataset
1794
+ aggressive_memory_cleanup()
1795
+
1796
+ t_train_end = time.time()
1797
+ train_duration = t_train_end - t_train_start
1798
+ total_samples_actual = sum(samples_per_dataset_actual.values())
1799
+ logger.info(
1800
+ f"\n[V6.5-attn] Treino concluído em {train_duration:.1f}s ({step} steps, "
1801
+ f"{total_samples_actual} samples REAIS)"
1802
+ + (" [STOPPED: storage critical]" if storage_critical_stopped else "")
1803
+ + (" [META OK]" if total_samples_actual >= META_MINIMA_SAMPLES else " [META NOT MET]")
1804
+ )
1805
+
1806
+ # Salva W8A8 compression log
1807
+ W8A8_COMPRESSION_PATH.write_text(json.dumps({
1808
+ "n_calls": len(w8a8_compression_log),
1809
+ "log": w8a8_compression_log,
1810
+ "summary": kls.get_w8a8_metrics(),
1811
+ }, indent=2, ensure_ascii=False))
1812
+
1813
+ # 14.8 Attention evaluation
1814
+ logger.info("[V6.5-attn] Evaluating attention mechanism (active & functional)...")
1815
+ attention_eval = evaluate_attention(kls)
1816
+ ATTENTION_EVAL_PATH.write_text(json.dumps(attention_eval, indent=2, ensure_ascii=False))
1817
+ print(f"\n--- Attention Evaluation ---")
1818
+ print(f" Module type : {attention_eval['module_type']}")
1819
+ print(f" Is MultiHeadAttention : {attention_eval['module_is_MultiHeadAttention']}")
1820
+ print(f" n_calls : {attention_eval['snapshot_after_explicit_test']['n_calls']}")
1821
+ print(f" n_errors : {attention_eval['snapshot_after_explicit_test']['n_errors']}")
1822
+ print(f" last_attn_activated : {attention_eval['snapshot_after_explicit_test']['last_attn_activated']}")
1823
+ print(f" logic_functional : {attention_eval['snapshot_after_explicit_test']['logic_functional']}")
1824
+ print(f" attention_modifies_output: {attention_eval['explicit_test']['attention_modifies_output']}")
1825
+ print(f" VERDICT : {attention_eval['summary']['verdict']}")
1826
+
1827
+ # 14.9 Reasoning & Response evaluation
1828
+ logger.info("[V6.5-attn] Evaluating reasoning and response quality...")
1829
+ reasoning_eval = evaluate_reasoning_and_response(kls)
1830
+ REASONING_EVAL_PATH.write_text(json.dumps(reasoning_eval, indent=2, ensure_ascii=False))
1831
+ print(f"\n--- Reasoning & Response Quality ---")
1832
+ print(f" Test queries : {reasoning_eval['n_test_queries']}")
1833
+ print(f" With <answer> tag : {reasoning_eval['summary']['n_with_answer']}/{reasoning_eval['n_test_queries']}")
1834
+ print(f" With <think> tag : {reasoning_eval['summary']['n_with_think']}/{reasoning_eval['n_test_queries']}")
1835
+ print(f" Avg reasoning length : {reasoning_eval['summary']['avg_reasoning_length']:.0f} chars")
1836
+ print(f" Response quality : {reasoning_eval['quality_assessment']['response_quality']}")
1837
+ print(f" Reasoning quality : {reasoning_eval['quality_assessment']['reasoning_quality']}")
1838
+
1839
+ # V6.5-attn-v2 — User requirement: "não ajudar o modelo em respostas e
1840
+ # lançar perguntas: 'Luva de Pedreiro Távila', 'Lula reserva valor',
1841
+ # 'Amazonas força-tarefa vítimas'"
1842
+ logger.info("[V6.5-attn-v2] Launching 3 user questions WITHOUT helping the model...")
1843
+ user_questions_eval = launch_user_questions_without_help(kls)
1844
+ USER_QUESTIONS_PATH.write_text(json.dumps(user_questions_eval, indent=2, ensure_ascii=False))
1845
+ print(f"\n--- User Questions (sem ajuda do modelo) ---")
1846
+ print(f" Questions sent verbatim: {user_questions_eval['questions_sent_verbatim']}")
1847
+ print(f" No context added : {user_questions_eval['no_context_added']}")
1848
+ print(f" No system prompt : {user_questions_eval['no_system_prompt']}")
1849
+ print(f" No few-shot examples : {user_questions_eval['no_few_shot']}")
1850
+ for r in user_questions_eval["results"]:
1851
+ print(f" Q: '{r['query']}'")
1852
+ print(f" som_pred={r['som_prediction']} | len={r['reasoning_length']} chars | "
1853
+ f"tags={r['n_tags']}/4 | latency={r['latency_ms']:.0f}ms")
1854
+ if r["has_think"]:
1855
+ print(f" <think>: {r['think_preview'][:120]}")
1856
+ if r["has_answer"]:
1857
+ print(f" <answer>: {r['answer_preview'][:120]}")
1858
+ elif not r["has_think"] and not r["has_answer"]:
1859
+ print(f" raw_response: {r['raw_response_preview'][:200]}")
1860
+ print(f" Response quality: {user_questions_eval['quality_assessment']['response_quality']}")
1861
+ print(f" Reasoning quality: {user_questions_eval['quality_assessment']['reasoning_quality']}")
1862
+ print(f" Model not helped: {user_questions_eval['quality_assessment']['model_not_helped']}")
1863
+
1864
+ # V6.5-attn-v2 — Save model states at end of training (User requirement:
1865
+ # "armazenar os estados do modelo para avaliação")
1866
+ logger.info("[V6.5-attn-v2] Saving model states for evaluation (end of training)...")
1867
+ model_states_save = save_model_states_for_evaluation(
1868
+ kls=kls,
1869
+ reason="end_of_training",
1870
+ step=step,
1871
+ total_samples=total_samples_actual,
1872
+ )
1873
+
1874
+ # 14.10 Final report
1875
+ summary = monitor.summary()
1876
+ som_final = kls.som.get_metrics()
1877
+ kls_state = kls.get_state_metrics()
1878
+
1879
+ report = {
1880
+ "version": "V6.5-attn-v2-100batch-6000meta-save-states-user-questions",
1881
+ "timestamp": datetime.now().isoformat(),
1882
+ "user_requirements_checklist": {
1883
+ "HF_TOKEN_deleted_after_use": "PENDING (will delete after upload)",
1884
+ "streaming_datasets_active_REAL": True,
1885
+ "xeon_runtime_active": True,
1886
+ "V65_ENABLE_STREAMING_forced": True,
1887
+ "attention_active_and_logic_functional": attention_eval["summary"]["verdict"] == "ACTIVE_AND_FUNCTIONAL",
1888
+ "streaming_100_per_batch": STREAM_BATCH_SIZE == 100,
1889
+ "meta_minima_6000_atingida": total_samples_actual >= META_MINIMA_SAMPLES,
1890
+ "no_synthetic_data": True,
1891
+ "streaming_with_pauses": True,
1892
+ "storage_critical_check": True,
1893
+ "model_states_saved_for_evaluation": bool(model_states_save.get("saved", False)),
1894
+ "user_questions_launched_without_help": True,
1895
+ "aggressive_ram_cleanup": True,
1896
+ "aggressive_storage_cleanup": True,
1897
+ "metrics_reasoning_response_verified": True,
1898
+ "exhausted_7_datasets_in_sequence": True,
1899
+ "som_grid_864_neurons": SOM_GRID == (6, 6, 6, 4),
1900
+ "mtp_head_size_increased_K6": MTP_K == 6,
1901
+ "vqvae2_active_in_pipeline": True,
1902
+ "reasoning_engine_integrated_to_kls": True,
1903
+ "smoothquant_w8a8_integrated_to_kls": True,
1904
+ "tool_coordinator_workers_reactivated": True,
1905
+ "ewc_w8a8_dequant_benchmark_active": True,
1906
+ "logic_and_bugfixes_verified": verification["all_pass"],
1907
+ },
1908
+ "config": {
1909
+ "BATCH_SIZE": BATCH_SIZE,
1910
+ "STREAM_BATCH_SIZE": STREAM_BATCH_SIZE,
1911
+ "datasets_to_exhaust": V65_DATASETS_TO_EXHAUST,
1912
+ "MAX_SAMPLES_PER_DATASET": MAX_SAMPLES_PER_DATASET,
1913
+ "TOTAL_SAMPLES_TARGET": TOTAL_SAMPLES_TARGET,
1914
+ "META_MINIMA_SAMPLES": META_MINIMA_SAMPLES,
1915
+ "STREAM_BATCH_SIZE": STREAM_BATCH_SIZE,
1916
+ "SOM_GRID": list(SOM_GRID),
1917
+ "n_neurons": n_neurons,
1918
+ "HIDDEN_DIM": HIDDEN_DIM,
1919
+ "VOCAB_SIZE": VOCAB_SIZE,
1920
+ "MAX_SEQ_LEN": MAX_SEQ_LEN,
1921
+ "MTP_K": MTP_K,
1922
+ "INTER_BATCH_PAUSE_S": INTER_BATCH_PAUSE_S,
1923
+ "INTER_STREAM_BATCH_PAUSE_S": INTER_STREAM_BATCH_PAUSE_S,
1924
+ "INTER_DATASET_PAUSE_S": INTER_DATASET_PAUSE_S,
1925
+ "STORAGE_CRITICAL_PCT": STORAGE_CRITICAL_PCT,
1926
+ "ATTENTION_N_HEADS": 8,
1927
+ },
1928
+ "xeon_status": XEON_STATUS,
1929
+ "fp16_benchmark": FP16_BENCH,
1930
+ "training": {
1931
+ "duration_s": float(train_duration),
1932
+ "n_steps": int(step),
1933
+ "samples_per_dataset_actual": samples_per_dataset_actual,
1934
+ "total_samples_processed": total_samples_actual,
1935
+ "meta_minima_atingida": bool(total_samples_actual >= META_MINIMA_SAMPLES),
1936
+ "streaming_failures": streaming_failures,
1937
+ "storage_critical_stopped": bool(storage_critical_stopped),
1938
+ "inter_batch_pause_s": INTER_BATCH_PAUSE_S,
1939
+ "inter_stream_batch_pause_s": INTER_STREAM_BATCH_PAUSE_S,
1940
+ "inter_dataset_pause_s": INTER_DATASET_PAUSE_S,
1941
+ },
1942
+ "summary": summary,
1943
+ "kohonen_final": som_final,
1944
+ "kls_state": kls_state,
1945
+ "verification": verification,
1946
+ "attention_eval_summary": attention_eval["summary"],
1947
+ "ewc_w8a8_benchmark_summary": ewc_w8a8_benchmark["analysis"],
1948
+ "reasoning_eval_summary": reasoning_eval["summary"],
1949
+ "user_questions_eval_summary": user_questions_eval["summary"],
1950
+ "user_questions_quality_assessment": user_questions_eval["quality_assessment"],
1951
+ "model_states_save_info": model_states_save,
1952
+ "w8a8_compression_summary": kls.get_w8a8_metrics(),
1953
+ "attention_metrics_final": kls.get_attention_metrics(),
1954
+ "module_analysis_summary": {
1955
+ "n_removed_modules": sum(1 for v in module_analysis["removed_modules"].values() if v["status"] == "REMOVED"),
1956
+ "n_removed_folders": sum(1 for v in module_analysis["removed_folders"].values() if v["status"] == "REMOVED"),
1957
+ "n_active_modules": sum(1 for v in module_analysis["active_modules"].values() if v["activity"] == "active"),
1958
+ },
1959
+ "math_analysis": {
1960
+ "text_to_4d": "SVD: M @ V[:3].T -> centroid 3D + w = time_step/T_max (LINEAR)",
1961
+ "attention_pipeline": "fused (L,D) -> MultiHeadAttention(self-attn, n_heads=8) -> fused + attn_out -> SVD",
1962
+ "bmu_distance": "||W - x||^2 (L2 squared in R^4)",
1963
+ "neighborhood": "Lambda(d, sigma) = exp(-d^2 / (2*sigma^2))",
1964
+ "weight_update": "dW = alpha * Lambda * (x - W)",
1965
+ "sigma_decay": "sigma_t = sigma0 * exp(-t/1000)",
1966
+ "alpha_decay": "alpha_t = alpha0 * exp(-t/2000)",
1967
+ "ewc_only_dim4": "penalty = lambda * F * (W_w - W*_w)",
1968
+ "vqvae2_loss": "L = recon_loss + vq_loss (commitment top + bottom + diversity)",
1969
+ "smoothquant_w8a8": "s_j = max|X_j|^alpha / max|W_j|^(1-alpha); W_smooth = W * diag(s); INT8 quant; dequant = W_int8 * scale / diag(s)",
1970
+ "mtp_loss": "L = sum_k(alpha_k * L_k) - beta * H(alpha), K=6 (V6.5-attn)",
1971
+ "ewc_w8a8_dequant": "W_float = (W_int8 * scale) / smooth_scale; EWC uses W_float for (p-w*)^2",
1972
+ },
1973
+ "datasets_used": V65_DATASETS_TO_EXHAUST,
1974
+ "storage_cleanup_pre": storage_cleanup_pre,
1975
+ }
1976
+
1977
+ REPORT_PATH.write_text(json.dumps(report, indent=2, ensure_ascii=False, default=str))
1978
+ logger.info(f"[V6.5-attn] Report saved: {REPORT_PATH}")
1979
+
1980
+ metrics_full = {
1981
+ "version": "V6.5-attn-v2-100batch-6000meta-save-states-user-questions",
1982
+ "steps": monitor.steps,
1983
+ "summary": summary,
1984
+ "alerts": monitor.alerts,
1985
+ "w8a8_compression_log": w8a8_compression_log,
1986
+ "attention_log": attention_log,
1987
+ }
1988
+ METRICS_PATH.write_text(json.dumps(metrics_full, indent=2, ensure_ascii=False, default=str))
1989
+ logger.info(f"[V6.5-attn] Metrics saved: {METRICS_PATH}")
1990
+
1991
+ print("\n" + "=" * 80)
1992
+ print("V6.5-attn — TREINO CONCLUÍDO")
1993
+ print("=" * 80)
1994
+ print(f" Steps : {step}")
1995
+ print(f" Duration : {train_duration:.1f}s")
1996
+ print(f" Total samples REAL : {total_samples_actual} / target {TOTAL_SAMPLES_TARGET}")
1997
+ print(f" Meta ≥6000 atingida : {total_samples_actual >= META_MINIMA_SAMPLES}")
1998
+ print(f" Storage critical stop: {storage_critical_stopped}")
1999
+ print(f" Final loss : {summary.get('final_loss', 0):.3f}")
2000
+ print(f" Mean acc : {summary.get('mean_acc', 0):.3f}")
2001
+ print(f" Sigma (start→end) : {summary.get('sigma_start', 0):.3f} → {summary.get('sigma_end', 0):.3f}")
2002
+ print(f" VQ-VAE-2 mean loss : {summary.get('vqvae2_mean_total_loss', 0):.3f}")
2003
+ print(f" W8A8 mean rel error : {summary.get('w8a8_mean_relative_error', 0):.6f}")
2004
+ print(f" W8A8 final rel error : {summary.get('w8a8_final_relative_error', 0):.6f}")
2005
+ print(f" Attention final n_calls: {summary.get('attention_final_n_calls', 0)}")
2006
+ print(f" Attention verdict : {attention_eval['summary']['verdict']}")
2007
+ print(f" RSS max : {summary.get('rss_max_mb', 0):.0f}MB")
2008
+ print(f" Disk max : {summary.get('disk_max_pct', 0):.1f}%")
2009
+ print(f" Alerts : {summary.get('n_alerts', 0)}")
2010
+ print(f" Hypothesis trained : {kls.classifier_trained}")
2011
+ print(f" EWC reference set : {som_final['has_ewc_reference']}")
2012
+ print(f" VQ-VAE-2 calls : {kls_state['kls']['vqvae2_n_calls']}")
2013
+ print(f" W8A8 calls : {kls_state['kls']['w8a8_n_calls']}")
2014
+ print(f" Attention active : {kls_state['kls']['attention_active']}")
2015
+ print(f" Tool coord workers : {kls_state['kls']['tool_coordinator_workers_active']}")
2016
+ print(f" Reasoning n_history : {reasoning_eval['summary']['reasoning_engine_n_history']}")
2017
+ print(f" Verification : {verification['n_pass']}/{verification['n_pass'] + verification['n_fail']} PASS")
2018
+ print("=" * 80)
2019
+ print(f"\n Report : {REPORT_PATH}")
2020
+ print(f" Metrics : {METRICS_PATH}")
2021
+ print(f" Module analysis : {MODULE_ANALYSIS_PATH}")
2022
+ print(f" Script activity : {SCRIPT_ACTIVITY_PATH}")
2023
+ print(f" EWC+W8A8 bench : {EWC_W8A8_BENCH_PATH}")
2024
+ print(f" Reasoning eval : {REASONING_EVAL_PATH}")
2025
+ print(f" Attention eval : {ATTENTION_EVAL_PATH}")
2026
+ print(f" W8A8 compression : {W8A8_COMPRESSION_PATH}\n")
2027
+
2028
+ return 0
2029
+
2030
+
2031
+ if __name__ == "__main__":
2032
+ sys.exit(main())