PowerMachine commited on
Commit
3a3f374
·
verified ·
1 Parent(s): 626d77b

V6.5-attn-v2 cleanup: remove legacy scripts/train_v6_5_7ds_attn.py

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