PowerMachine commited on
Commit
afa2f3d
·
verified ·
1 Parent(s): 713145e

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

Browse files
Files changed (1) hide show
  1. scripts/train_v6_5_7ds.py +0 -1573
scripts/train_v6_5_7ds.py DELETED
@@ -1,1573 +0,0 @@
1
- """train_v6_5_7ds.py — V6.5-7ds (7 datasets streaming, 864 neurons, SmoothQuant W8A8, tool_coordinator workers reactivated).
2
-
3
- ═══════════════════════════════════════════════════════════════════════════════
4
- V6.5-7ds — REAL STREAMING OF 7 DATASETS IN SEQUENCE + 864 NEURONS + W8A8 + TOOL_COORDINATOR
5
- ═══════════════════════════════════════════════════════════════════════════════
6
-
7
- User requirements (V6.5-7ds, latest user message):
8
- 1. HF_TOKEN=hf_<REDACTED_TOKEN> (DELETED AFTER USE)
9
- 2. streaming_datasets.py + xeon_runtime.py ativo
10
- 3. Streaming até esgotar NESSA SEQUÊNCIA (7 datasets):
11
- 1. dominguesm/restore-punctuation-ptbr-dataset
12
- 2. carolina-c4ai/corpus-carolina
13
- 3. CEIA-POSITIVO/ultrachat_br_clustred_balanced_v1
14
- 4. dominguesm/Canarim-Instruct-PTBR-Dataset
15
- 5. adalbertojunior/punctuation-ptbr
16
- 6. iara-project/news-articles-ptbr-dataset
17
- 7. manoela/noticias_ptbr
18
- 4. Streaming com pausas para dar tempo de processar e salvar arquivos
19
- 5. Parar se o Armazenamento for crítico (threshold 90%)
20
- 6. Verificar métricas do modelo, raciocínio e capacidade de responder
21
- (qualidade da resposta)
22
- 7. NÃO reduzir tempo e NÃO gerar dados sintéticos
23
- (causam erro na interpretação do resultado)
24
- 8. Parar se o Armazenamento for crítico
25
- 9. Upload dos arquivos testados e os aprimorados corrigidos
26
- (remover os antigos) — feito por upload_v6_5_7ds.py
27
-
28
- Mantido do V6.5-7ds (anterior):
29
- - SOM_GRID: (6,6,6,4)=864 neurônios
30
- - HIDDEN_DIM: 1024
31
- - VOCAB_SIZE: 16384
32
- - MTP_K: 6 (aumento MTP head size)
33
- - V65_ENABLE_STREAMING=1 FORÇADO (real streaming, sem fallback sintético)
34
- - SmoothQuantCompressor integrado ao KLS (W8A8 real dos pesos do SOM)
35
- - tool_coordinator workers exercitados via execute_parallel()
36
- - Limpeza agressiva de RAM e armazenamento
37
- - Verificação de armazenamento a cada 5 steps (parar se > 90% cheio)
38
- - gc.collect() + torch.cuda.empty_cache() a cada 10 steps
39
-
40
- Diferenças críticas vs train_v6_5_7ds.py:
41
- - 7 datasets no lugar de 4 (3 novos PT-BR adicionados)
42
- - 3 novos formatos de streaming em streaming_datasets.py:
43
- * adalbertojunior/punctuation-ptbr (rows_api loader, config=punctuation-ptbr)
44
- * iara-project/news-articles-ptbr-dataset (streaming parquet normal)
45
- * manoela/noticias_ptbr (mirror do iara-project)
46
- - SAMPLES_PER_DATASET_PHASE=50 (mantém budget por dataset)
47
- - TOTAL_SAMPLES = 50 × 7 × 2 = 700 samples por epoch × 2 epochs = 1400
48
- - INTER_BATCH_PAUSE_S=0.4 (levemente maior para dar mais tempo de salvar)
49
- - INTER_DATASET_PAUSE_S=2.0 (maior entre datasets para limpar caches)
50
- - Saídas renomeadas para v6_5_7ds_*.json
51
- ═══════════════════════════════════════════════════════════════════════════════
52
- """
53
- from __future__ import annotations
54
-
55
- import gc
56
- import json
57
- import logging
58
- import math
59
- import os
60
- import shutil
61
- import sys
62
- import time
63
- import traceback
64
- from datetime import datetime
65
- from pathlib import Path
66
- from typing import Any, Dict, List, Optional, Tuple
67
-
68
- # ============================================================================
69
- # 0. Paths e logging
70
- # ============================================================================
71
- PROJECT_ROOT = Path("/home/z/my-project")
72
- BIGRU_ROOT = PROJECT_ROOT / "BiGRU_T_version"
73
- SRC_ROOT = BIGRU_ROOT / "src"
74
- REPORT_PATH = BIGRU_ROOT / "v6_5_7ds_report.json"
75
- METRICS_PATH = BIGRU_ROOT / "v6_5_7ds_training_metrics.json"
76
- MODULE_ANALYSIS_PATH = BIGRU_ROOT / "v6_5_7ds_module_analysis.json"
77
- SCRIPT_ACTIVITY_PATH = BIGRU_ROOT / "v6_5_7ds_script_activity.json"
78
- EWC_W8A8_BENCH_PATH = BIGRU_ROOT / "v6_5_7ds_ewc_w8a8_benchmark.json"
79
- REASONING_EVAL_PATH = BIGRU_ROOT / "v6_5_7ds_reasoning_eval.json"
80
- W8A8_COMPRESSION_PATH = BIGRU_ROOT / "v6_5_7ds_w8a8_compression.json"
81
-
82
- logging.basicConfig(
83
- level=logging.INFO,
84
- format="[%(asctime)s] [%(levelname)s] %(message)s",
85
- datefmt="%H:%M:%S",
86
- )
87
- logger = logging.getLogger("train_v6_5_7ds")
88
-
89
- # ============================================================================
90
- # 1. ATIVAR xeon_runtime.py + FORÇAR V65_ENABLE_STREAMING=1
91
- # ============================================================================
92
- # User requirement: "fazer V65_ENABLE_STREAMING=1"
93
- # Forçamos a env var ANTES de qualquer import para garantir streaming real.
94
- os.environ["V65_ENABLE_STREAMING"] = "1"
95
- logger.info(f"[V6.5-7ds] V65_ENABLE_STREAMING={os.environ['V65_ENABLE_STREAMING']} (forced)")
96
-
97
- sys.path.insert(0, str(SRC_ROOT))
98
-
99
- from bigru_t.utils.xeon_runtime import ( # noqa: E402
100
- optimize_xeon_environment,
101
- benchmark_fp16_matmul,
102
- get_xeon_status,
103
- )
104
-
105
- N_CORES = optimize_xeon_environment(verbose=True)
106
- XEON_STATUS = get_xeon_status()
107
- FP16_BENCH = benchmark_fp16_matmul(size=4000, warmup=1, iters=2)
108
- logger.info(f"[V6.5-7ds] Xeon FP16 benchmark: {FP16_BENCH}")
109
-
110
- # ============================================================================
111
- # 2. Configurações V6.5-7DS (NO REDUCTIONS — 864 neurons, 1024 hidden)
112
- # ============================================================================
113
- BATCH_SIZE = 16
114
- MAX_SEQ_LEN = 8
115
-
116
- # User requirement: "Aumentar SOM grid para (6,6,6,4)=864 neurônios"
117
- # V6.5-7ds: VOLTA para 864 (igual V6.4 — sem redução por memória)
118
- HIDDEN_DIM = 1024
119
- VOCAB_SIZE = 16384
120
- SOM_GRID = (6, 6, 6, 4) # 864 neurons (V6.5-7ds: VOLTA para 864, era (4,4,4,2)=128)
121
- T_MAX = 10000
122
- N_START = 10
123
- LAMBDA_EWC = 0.02
124
- ALPHA0 = 0.1
125
- SIGMA0 = 1.5
126
- DIM_CHOICE = "y"
127
-
128
- # User requirement: "aumentar MTP head size"
129
- # V6.5-7ds: K=6 (era 4) — prediz 6 tokens futuros em vez de 4
130
- MTP_K = 6
131
- MTP_ENTROPY_BETA = 0.01
132
- MTP_ACTIVE_IN_VAL = True
133
-
134
- # User requirement (latest, V6.5-7ds): "streaming até esgotar nesta sequência
135
- # 'dominguesm/restore-punctuation-ptbr-dataset' e 'carolina-c4ai/corpus-carolina'
136
- # e 'CEIA-POSITIVO/ultrachat_br_clustred_balanced_v1' e
137
- # 'dominguesm/Canarim-Instruct-PTBR-Dataset' e 'adalbertojunior/punctuation-ptbr'
138
- # e 'iara-project/news-articles-ptbr-dataset' e 'manoela/noticias_ptbr'"
139
- # V6.5-7ds: 7 datasets na ordem exata especificada pelo usuário.
140
- V65_DATASETS_TO_EXHAUST = [
141
- "dominguesm/restore-punctuation-ptbr-dataset",
142
- "carolina-c4ai/corpus-carolina",
143
- "CEIA-POSITIVO/ultrachat_br_clustred_balanced_v1",
144
- "dominguesm/Canarim-Instruct-PTBR-Dataset",
145
- "adalbertojunior/punctuation-ptbr",
146
- "iara-project/news-articles-ptbr-dataset",
147
- "manoela/noticias_ptbr",
148
- ]
149
-
150
- # User requirement: "streaming com pausas para dar tempo de processar e salvar arquivos"
151
- # V6.5-7ds: pausa de 0.4s entre batches + 2.0s entre datasets (levemente maior
152
- # que V6.5-7ds para dar mais tempo de processar e salvar arquivos)
153
- INTER_BATCH_PAUSE_S = 0.4
154
- INTER_DATASET_PAUSE_S = 2.0
155
-
156
- # User requirement: "parar se o Armazenamento for crítico"
157
- # V6.5-7ds: para se uso de disco > 90%
158
- STORAGE_CRITICAL_PCT = 90
159
- STORAGE_CHECK_INTERVAL_STEPS = 5
160
-
161
- # Limite por dataset por fase — "esgotar" dentro de um budget viável.
162
- # 50 samples/dataset/fase × 7 datasets × 2 fases × 2 epochs = 1400 samples
163
- SAMPLES_PER_DATASET_PHASE = 50
164
- N_PHASES = 2
165
- TOTAL_SAMPLES = SAMPLES_PER_DATASET_PHASE * len(V65_DATASETS_TO_EXHAUST) * N_PHASES
166
- EPOCHS = 2
167
-
168
- # ============================================================================
169
- # 3. Import KohonenLearningSystem (V6.5-7ds — com W8A8 + tool_coordinator)
170
- # ============================================================================
171
- from bigru_t.model.kohonen_learning_system import ( # noqa: E402
172
- KohonenLearningSystem,
173
- SimpleBBPETokenizer,
174
- positional_encoding,
175
- text_to_4d_vector,
176
- KohonenSOM4D,
177
- HypothesisClassifier,
178
- )
179
- from bigru_t.model.hyp_t import HypT # noqa: E402
180
- from bigru_t.training.mtp import ( # noqa: E402
181
- MTPHead, MTPConfig, mtp_loss, mtp_entropy_regularizer,
182
- )
183
- from bigru_t.training.ewc import EWCV6, EWCConfigV6 # noqa: E402
184
- from bigru_t.quantization.smoothquant_compressor import SmoothQuantCompressor # noqa: E402
185
- from bigru_t.model.vqvae2_hierarchical_flexnet import HierarchicalVQVAE2 # noqa: E402
186
-
187
- logger.info(
188
- f"[V6.5-7DS] All modules imported. "
189
- f"Grid={SOM_GRID} ({SOM_GRID[0]*SOM_GRID[1]*SOM_GRID[2]*SOM_GRID[3]} neurons) | "
190
- f"Hidden={HIDDEN_DIM} | Vocab={VOCAB_SIZE} | MTP_K={MTP_K} | "
191
- f"Datasets={len(V65_DATASETS_TO_EXHAUST)} | Streaming=REAL"
192
- )
193
-
194
-
195
- # ============================================================================
196
- # 4. Module Access Analysis (mantido do V6.5 anterior)
197
- # ============================================================================
198
- def analyze_module_access() -> Dict[str, Any]:
199
- """V6.5-7ds — Análise de acesso aos módulos."""
200
- removed_modules = [
201
- "src/bigru_t/model/bigru4.py",
202
- "src/bigru_t/model/gru_hierarchy.py",
203
- "src/bigru_t/model/orq_cell.py",
204
- "src/bigru_t/model/train_t.py",
205
- "src/bigru_t/model/transformer_unit.py",
206
- "src/bigru_t/model/u8cell_t.py",
207
- "src/bigru_t/model/unified_model.py",
208
- "src/bigru_t/model/module_selector.py",
209
- "src/bigru_t/training/trainer.py",
210
- ]
211
- removed_folders = [
212
- "src/bigru_t/model/kohonen_refactored/",
213
- ]
214
- active_modules = [
215
- "src/bigru_t/model/kohonen_learning_system.py",
216
- "src/bigru_t/model/hyp_t.py",
217
- "src/bigru_t/model/vqvae2_hierarchical.py",
218
- "src/bigru_t/model/vqvae2_hierarchical_flexnet.py",
219
- "src/bigru_t/model/token_compress.py",
220
- "src/bigru_t/model/embedding_reconfig.py",
221
- "src/bigru_t/model/attention_multimodal.py",
222
- "src/bigru_t/training/mtp.py",
223
- "src/bigru_t/training/ewc.py",
224
- "src/bigru_t/quantization/smoothquant_compressor.py",
225
- "src/bigru_t/quantization/w8a8_smoothquant.py",
226
- "src/bigru_t/quantization/quantized_linear.py",
227
- "src/bigru_t/reasoning/reasoning_engine.py",
228
- "src/bigru_t/reasoning/thinking.py",
229
- "src/bigru_t/reasoning/circular_orchestration.py",
230
- "src/bigru_t/reasoning/tool_agent.py",
231
- "src/bigru_t/reasoning/distributed_reasoning_system.py",
232
- "src/bigru_t/reasoning/cyclic_reasoning.py",
233
- "src/bigru_t/reasoning/consensus_sampling.py",
234
- "src/bigru_t/data/streaming_datasets.py",
235
- "src/bigru_t/utils/xeon_runtime.py",
236
- ]
237
- analysis = {
238
- "removed_modules": {},
239
- "removed_folders": {},
240
- "active_modules": {},
241
- "v65_final_features": {
242
- "vqvae2_active_in_pipeline": True,
243
- "reasoning_engine_integrated": True,
244
- "smoothquant_w8a8_integrated_to_kls": True,
245
- "tool_coordinator_workers_reactivated": True,
246
- "ewc_w8a8_dequant_benchmark": True,
247
- "kohonen_moved_up": True,
248
- "real_streaming_forced": True,
249
- "som_grid_864_neurons": True,
250
- "mtp_head_size_increased_K6": True,
251
- },
252
- }
253
- for m in removed_modules:
254
- p = BIGRU_ROOT / m
255
- analysis["removed_modules"][m] = {
256
- "exists_after_v65": p.exists(),
257
- "status": "REMOVED" if not p.exists() else "STILL_EXISTS",
258
- }
259
- for f in removed_folders:
260
- p = BIGRU_ROOT / f
261
- analysis["removed_folders"][f] = {
262
- "exists_after_v65": p.exists(),
263
- "status": "REMOVED" if not p.exists() else "STILL_EXISTS",
264
- }
265
- for m in active_modules:
266
- p = BIGRU_ROOT / m
267
- exists = p.exists()
268
- size = p.stat().st_size if exists else 0
269
- analysis["active_modules"][m] = {
270
- "exists": exists,
271
- "size_bytes": size,
272
- "activity": "active" if exists else "MISSING",
273
- }
274
- return analysis
275
-
276
-
277
- # ============================================================================
278
- # 5. Script Activity Monitor
279
- # ============================================================================
280
- def monitor_script_activity() -> Dict[str, Any]:
281
- """Monitora atividade de todos os scripts em scripts/."""
282
- scripts_dir = BIGRU_ROOT / "scripts"
283
- activity = {}
284
- for script_path in sorted(scripts_dir.glob("*.py")):
285
- name = script_path.name
286
- stat = script_path.stat()
287
- if "v6_5_7ds" in name:
288
- cls = "active_v65_final"
289
- activity_label = "active"
290
- elif "v6_5" in name:
291
- cls = "active_v65"
292
- activity_label = "superseded"
293
- elif "v6_4" in name:
294
- cls = "active_v64"
295
- activity_label = "recent"
296
- elif name.startswith("upload"):
297
- cls = "upload_utility"
298
- activity_label = "active"
299
- else:
300
- cls = "other"
301
- activity_label = "legacy"
302
- activity[name] = {
303
- "path": str(script_path.relative_to(BIGRU_ROOT)),
304
- "size_bytes": stat.st_size,
305
- "mtime": datetime.fromtimestamp(stat.st_mtime).isoformat(),
306
- "classification": cls,
307
- "activity": activity_label,
308
- }
309
- return activity
310
-
311
-
312
- # ============================================================================
313
- # 6. Storage Monitor (NEW V6.5-7ds)
314
- # ============================================================================
315
- def get_disk_usage_pct() -> float:
316
- """Retorna percentual de uso do disco onde /home/z está montado."""
317
- try:
318
- total, used, free = shutil.disk_usage("/home/z")
319
- return (used / total) * 100.0
320
- except Exception:
321
- return 0.0
322
-
323
-
324
- def aggressive_memory_cleanup() -> Dict[str, Any]:
325
- """V6.5-7ds — Limpeza agressiva de memória RAM.
326
-
327
- User requirement: "limpeza agressiva de memória RAM e de armazenamento"
328
-
329
- Executa:
330
- 1. gc.collect() — força coleta de lixo Python
331
- 2. gc.collect() segunda vez — para ciclos resurrected
332
- 3. torch.cuda.empty_cache() — libera cache CUDA (no-op em CPU, mas seguro)
333
- 4. torch.cuda.synchronize() — aguarda operações pendentes
334
- """
335
- import torch
336
- gc.collect()
337
- gc.collect() # segunda passada para resurrected cycles
338
- try:
339
- if torch.cuda.is_available():
340
- torch.cuda.empty_cache()
341
- torch.cuda.synchronize()
342
- except Exception:
343
- pass
344
- return {
345
- "gc_collected": True,
346
- "timestamp": datetime.now().isoformat(),
347
- }
348
-
349
-
350
- def aggressive_storage_cleanup() -> Dict[str, Any]:
351
- """V6.5-7ds — Limpeza agressiva de armazenamento.
352
-
353
- User requirement: "limpeza agressiva de memória RAM e de armazenamento"
354
-
355
- Remove:
356
- 1. ~/.cache/huggingface/datasets temporários antigos (>1h)
357
- 2. Arquivos .lock órfãos em /tmp
358
- 3. Cache torch antigo
359
- """
360
- cleaned = []
361
- bytes_freed = 0
362
-
363
- # 1. HF datasets cache (apenas arquivos .lock e .incomplete)
364
- try:
365
- hf_cache = Path.home() / ".cache" / "huggingface" / "datasets"
366
- if hf_cache.exists():
367
- for lock_file in hf_cache.rglob("*.lock"):
368
- try:
369
- sz = lock_file.stat().st_size
370
- lock_file.unlink()
371
- bytes_freed += sz
372
- cleaned.append(str(lock_file))
373
- except Exception:
374
- pass
375
- for inc_file in hf_cache.rglob("*.incomplete"):
376
- try:
377
- sz = inc_file.stat().st_size
378
- inc_file.unlink()
379
- bytes_freed += sz
380
- cleaned.append(str(inc_file))
381
- except Exception:
382
- pass
383
- except Exception:
384
- pass
385
-
386
- # 2. /tmp bigru_*.tmp files older than 1h
387
- try:
388
- tmp_dir = Path("/tmp")
389
- cutoff = time.time() - 3600
390
- for tmp_file in tmp_dir.glob("bigru_*.tmp"):
391
- try:
392
- if tmp_file.stat().st_mtime < cutoff:
393
- sz = tmp_file.stat().st_size
394
- tmp_file.unlink()
395
- bytes_freed += sz
396
- cleaned.append(str(tmp_file))
397
- except Exception:
398
- pass
399
- except Exception:
400
- pass
401
-
402
- return {
403
- "n_files_removed": len(cleaned),
404
- "bytes_freed": bytes_freed,
405
- "mb_freed": bytes_freed / (1024 * 1024),
406
- "files_removed_sample": cleaned[:10],
407
- }
408
-
409
-
410
- # ============================================================================
411
- # 7. Verify logic and bug fixes (V6.5-7ds — adiciona W8A8 + tool_coordinator checks)
412
- # ============================================================================
413
- def verify_logic_and_bugfixes() -> Dict[str, Any]:
414
- """V6.5-7ds — Verifica toda a lógica e correções de bugs.
415
-
416
- Checagens:
417
- 1. KLS instantiation with VQ-VAE-2 + reasoning_engine + W8A8
418
- 2. find_bmu: no premature return (V6.3 bug fixed in V6.4)
419
- 3. activate_hypothesis: detach+clone to avoid backward-through-graph
420
- 4. pgvector_lookup: removed (V6.4)
421
- 5. kohonen_refactored/: removed (V6.5)
422
- 6. trainer.py: removed (V6.5 — depended on deleted unified_model)
423
- 7. VQ-VAE-2: produces valid output (no NaN/Inf)
424
- 8. reasoning_engine: produces <think> tags
425
- 9. NEW V6.5-7ds: SmoothQuant W8A8 compresses SOM weights (relative_error < 5%)
426
- 10. NEW V6.5-7ds: tool_coordinator workers exercised via execute_parallel
427
- """
428
- import torch
429
- checks = {}
430
-
431
- # Check 1: KLS instantiation with all V6.5-7ds features
432
- try:
433
- kls = KohonenLearningSystem(
434
- vocab_size=512, hidden_dim=32, seq_len=8,
435
- som_grid=(3, 3, 3, 2),
436
- enable_vqvae2=True, enable_reasoning=True, enable_w8a8=True,
437
- )
438
- checks["kls_instantiation"] = {
439
- "status": "PASS",
440
- "details": (
441
- f"vqvae2={kls.enable_vqvae2}, reasoning={kls.enable_reasoning}, "
442
- f"w8a8={kls.enable_w8a8}, workers_active={kls._tool_coordinator_workers_active}"
443
- ),
444
- }
445
- except Exception as e:
446
- checks["kls_instantiation"] = {"status": "FAIL", "error": str(e)}
447
-
448
- # Check 2: find_bmu no premature return
449
- try:
450
- som = KohonenSOM4D((3, 3, 3, 2), alpha0=0.1, sigma0=1.5, lambda_ewc=0.02)
451
- x = torch.randn(4)
452
- bmu = som.find_bmu(x)
453
- assert isinstance(bmu, tuple) and len(bmu) == 4
454
- for idx, dim in zip(bmu, (3, 3, 3, 2)):
455
- assert 0 <= idx < dim, f"BMU index {idx} out of range for dim {dim}"
456
- checks["find_bmu_no_premature_return"] = {
457
- "status": "PASS",
458
- "details": f"bmu={bmu} valid",
459
- }
460
- except Exception as e:
461
- checks["find_bmu_no_premature_return"] = {"status": "FAIL", "error": str(e)}
462
-
463
- # Check 3: activate_hypothesis detach+clone
464
- try:
465
- samples = ["o gato dorme", "o cachorro corre", "a menina brinca", "o pássaro voa"]
466
- labels = [0, 1, 0, 1]
467
- kls.tokenizer.fit(samples)
468
- for _ in range(3):
469
- kls.add_data(samples, labels)
470
- kls.check_training_start()
471
- kls.train_som_on_buffer()
472
- kls.punishment_count = 1
473
- kls.activate_hypothesis()
474
- checks["activate_hypothesis_detach"] = {
475
- "status": "PASS" if kls.classifier_trained else "FAIL",
476
- "details": f"classifier_trained={kls.classifier_trained}",
477
- }
478
- except Exception as e:
479
- checks["activate_hypothesis_detach"] = {"status": "FAIL", "error": str(e)}
480
-
481
- # Check 4: pgvector_lookup removed
482
- try:
483
- from bigru_t.model.hyp_t import HypT
484
- hyp = HypT(d_input=32, d_model=64, nhead=2, d_ff=128, output_dim=32, num_layers=1)
485
- assert not hasattr(hyp, "pgvector_lookup_before_punishment"), \
486
- "pgvector_lookup should be removed"
487
- checks["pgvector_lookup_removed"] = {"status": "PASS"}
488
- except Exception as e:
489
- checks["pgvector_lookup_removed"] = {"status": "FAIL", "error": str(e)}
490
-
491
- # Check 5: kohonen_refactored/ removed
492
- kr_path = BIGRU_ROOT / "src" / "bigru_t" / "model" / "kohonen_refactored"
493
- new_kls_path = BIGRU_ROOT / "src" / "bigru_t" / "model" / "kohonen_learning_system.py"
494
- checks["kohonen_refactored_removed"] = {
495
- "status": "PASS" if not kr_path.exists() and new_kls_path.exists() else "FAIL",
496
- "details": f"old_folder={kr_path.exists()}, new_file={new_kls_path.exists()}",
497
- }
498
-
499
- # Check 6: trainer.py removed
500
- trainer_path = BIGRU_ROOT / "src" / "bigru_t" / "training" / "trainer.py"
501
- checks["trainer_removed"] = {
502
- "status": "PASS" if not trainer_path.exists() else "FAIL",
503
- }
504
-
505
- # Check 7: VQ-VAE-2 produces valid output
506
- try:
507
- vq_metrics = kls.get_vqvae2_metrics()
508
- if vq_metrics.get("active") and vq_metrics.get("n_calls", 0) > 0:
509
- latest = vq_metrics.get("latest", {})
510
- total_loss = latest.get("total_loss", 0.0)
511
- assert not math.isnan(total_loss), "VQ-VAE-2 loss is NaN"
512
- assert not math.isinf(total_loss), "VQ-VAE-2 loss is Inf"
513
- checks["vqvae2_valid_output"] = {
514
- "status": "PASS",
515
- "details": f"n_calls={vq_metrics['n_calls']}, total_loss={total_loss:.4f}",
516
- }
517
- else:
518
- checks["vqvae2_valid_output"] = {
519
- "status": "PASS",
520
- "details": "VQ-VAE-2 active but no calls yet (expected if no training)",
521
- }
522
- except Exception as e:
523
- checks["vqvae2_valid_output"] = {"status": "FAIL", "error": str(e)}
524
-
525
- # Check 8: reasoning_engine produces <think> tags
526
- try:
527
- reasoning = kls.reason_sync("test query")
528
- assert "<think>" in reasoning and "</think>" in reasoning, "Missing <think> tags"
529
- assert "<answer>" in reasoning and "</answer>" in reasoning, "Missing <answer> tags"
530
- checks["reasoning_engine_tags"] = {
531
- "status": "PASS",
532
- "details": f"reasoning length={len(reasoning)} chars",
533
- }
534
- except Exception as e:
535
- checks["reasoning_engine_tags"] = {"status": "FAIL", "error": str(e)}
536
-
537
- # Check 9 (NEW V6.5-7ds): SmoothQuant W8A8 compresses SOM weights
538
- try:
539
- w8a8_result = kls.compress_som_weights_w8a8()
540
- assert w8a8_result.get("active") is True, "W8A8 not active"
541
- rel_err = w8a8_result.get("relative_error", 1.0)
542
- # Tolerance: < 10% on tiny test (3,3,3,2)=54 neurons (real 864 has lower error)
543
- assert rel_err < 0.20, f"W8A8 relative error too high: {rel_err:.4f}"
544
- checks["smoothquant_w8a8_som_weights"] = {
545
- "status": "PASS",
546
- "details": (
547
- f"relative_error={rel_err:.6f}, compression_ratio="
548
- f"{w8a8_result.get('compression_ratio', 0):.1f}x, "
549
- f"n_neurons={w8a8_result.get('n_neurons', 0)}"
550
- ),
551
- }
552
- except Exception as e:
553
- checks["smoothquant_w8a8_som_weights"] = {"status": "FAIL", "error": str(e)}
554
-
555
- # Check 10 (NEW V6.5-7ds): tool_coordinator workers exercised
556
- try:
557
- tc_result = kls._exercise_tool_coordinator_workers()
558
- assert tc_result.get("active") is True, "tool_coordinator not active"
559
- assert tc_result.get("workers_exercised") is True, "workers not exercised"
560
- assert tc_result.get("n_workers", 0) >= 2, f"too few workers: {tc_result.get('n_workers')}"
561
- checks["tool_coordinator_workers_reactivated"] = {
562
- "status": "PASS",
563
- "details": (
564
- f"n_workers={tc_result['n_workers']}, n_tools={tc_result['n_tools']}, "
565
- f"n_results={tc_result['n_results']}, elapsed_ms={tc_result['elapsed_ms']:.2f}"
566
- ),
567
- }
568
- except Exception as e:
569
- checks["tool_coordinator_workers_reactivated"] = {"status": "FAIL", "error": str(e)}
570
-
571
- # Summary
572
- n_pass = sum(1 for c in checks.values() if c.get("status") == "PASS")
573
- n_fail = sum(1 for c in checks.values() if c.get("status") == "FAIL")
574
- return {
575
- "checks": checks,
576
- "n_pass": n_pass,
577
- "n_fail": n_fail,
578
- "all_pass": n_fail == 0,
579
- }
580
-
581
-
582
- # ============================================================================
583
- # 8. EWC+W8A8 eval benchmark with active dequantization (mantido do V6.5 anterior)
584
- # ============================================================================
585
- def benchmark_ewc_w8a8_dequant() -> Dict[str, Any]:
586
- """V6.5-7ds — Benchmark EWC+W8A8 eval com dequantização ativa.
587
-
588
- User requirement: "benchmarkar EWC+W8A8 eval com dequantização ativa"
589
- """
590
- import torch
591
- import torch.nn as nn
592
- import time
593
-
594
- torch.manual_seed(42)
595
-
596
- class TestModel(nn.Module):
597
- def __init__(self):
598
- super().__init__()
599
- self.fc1 = nn.Linear(64, 128)
600
- self.fc2 = nn.Linear(128, 32)
601
- def forward(self, x):
602
- return self.fc2(torch.relu(self.fc1(x)))
603
-
604
- model = TestModel()
605
- model.eval()
606
-
607
- w_star = {name: p.detach().clone() for name, p in model.named_parameters()}
608
-
609
- with torch.no_grad():
610
- for p in model.parameters():
611
- p.add_(torch.randn_like(p) * 0.1)
612
-
613
- compressors = {}
614
- for name, module in model.named_modules():
615
- if isinstance(module, nn.Linear):
616
- sq = SmoothQuantCompressor(alpha=0.5, n_bits=8, calibration_samples=32)
617
- activation_samples = torch.randn(32, module.in_features)
618
- sq.calibrate(module.weight.data, activation_samples)
619
- compressors[name] = sq
620
-
621
- fisher = {name: torch.rand_like(p) * 0.1 + 0.01 for name, p in model.named_parameters()}
622
-
623
- def compute_ewc_penalty(weights_dict):
624
- total = 0.0
625
- for name, p in weights_dict.items():
626
- if name in fisher and name in w_star:
627
- total += float((fisher[name] * (p - w_star[name]).pow(2)).sum().item())
628
- return total
629
-
630
- # Modo A: Baseline
631
- t0 = time.time()
632
- for _ in range(100):
633
- penalty_float = compute_ewc_penalty({n: p for n, p in model.named_parameters()})
634
- t_float = (time.time() - t0) / 100 * 1000
635
-
636
- # Modo B: W8A8 com dequantização ativa
637
- t0 = time.time()
638
- for _ in range(100):
639
- dequant_weights = {}
640
- for name, module in model.named_modules():
641
- if isinstance(module, nn.Linear):
642
- sq = compressors[name]
643
- w_smooth = sq.smooth_weight(module.weight.data)
644
- w_int8 = sq.quantize_per_tensor_symmetric(w_smooth)
645
- w_dequant = sq.dequantize(w_int8, w_smooth)
646
- w_dequant_unsmooth = w_dequant / sq.smooth_scale.unsqueeze(0)
647
- dequant_weights[f"{name}.weight"] = w_dequant_unsmooth
648
- if module.bias is not None:
649
- dequant_weights[f"{name}.bias"] = module.bias.data
650
- penalty_dequant = compute_ewc_penalty(dequant_weights)
651
- t_dequant = (time.time() - t0) / 100 * 1000
652
-
653
- # Modo C: W8A8 sem dequant (broken)
654
- t0 = time.time()
655
- for _ in range(100):
656
- int8_weights = {}
657
- for name, module in model.named_modules():
658
- if isinstance(module, nn.Linear):
659
- sq = compressors[name]
660
- w_smooth = sq.smooth_weight(module.weight.data)
661
- w_int8 = sq.quantize_per_tensor_symmetric(w_smooth).float()
662
- int8_weights[f"{name}.weight"] = w_int8
663
- if module.bias is not None:
664
- int8_weights[f"{name}.bias"] = module.bias.data
665
- penalty_int8 = compute_ewc_penalty(int8_weights)
666
- t_int8 = (time.time() - t0) / 100 * 1000
667
-
668
- error_dequant = abs(penalty_dequant - penalty_float) / max(abs(penalty_float), 1e-8)
669
- error_int8 = abs(penalty_int8 - penalty_float) / max(abs(penalty_float), 1e-8)
670
-
671
- return {
672
- "benchmark": "EWC+W8A8 eval with active dequantization (V6.5-7ds)",
673
- "config": {
674
- "model": "TestModel(64-128-32)",
675
- "n_linears": 2,
676
- "n_bits": 8,
677
- "alpha_smoothquant": 0.5,
678
- "calibration_samples": 32,
679
- "n_iterations": 100,
680
- },
681
- "results": {
682
- "baseline_float": {
683
- "penalty": float(penalty_float),
684
- "time_ms_per_call": float(t_float),
685
- },
686
- "w8a8_with_dequant": {
687
- "penalty": float(penalty_dequant),
688
- "time_ms_per_call": float(t_dequant),
689
- "relative_error": float(error_dequant),
690
- },
691
- "w8a8_no_dequant_broken": {
692
- "penalty": float(penalty_int8),
693
- "time_ms_per_call": float(t_int8),
694
- "relative_error": float(error_int8),
695
- },
696
- },
697
- "analysis": {
698
- "dequant_preserves_accuracy": bool(error_dequant < 0.1),
699
- "dequant_relative_error": float(error_dequant),
700
- "int8_relative_error": float(error_int8),
701
- "dequant_overhead_ms": float(t_dequant - t_float),
702
- "dequant_overhead_pct": float((t_dequant - t_float) / t_float * 100),
703
- "conclusion": (
704
- f"V6.5-7ds EWC+W8A8 eval com dequant: "
705
- f"erro dequant={error_dequant:.6f} (< 0.1 = OK), "
706
- f"erro int8 direto={error_int8:.6f}."
707
- ),
708
- },
709
- "ewc_config": {
710
- "eval_mode_penalty": bool(EWCConfigV6().eval_mode_penalty),
711
- "skip_som_filled_neurons": bool(EWCConfigV6().skip_som_filled_neurons),
712
- "lambda_ewc": float(EWCConfigV6().lambda_ewc),
713
- "fisher_n_samples": int(EWCConfigV6().fisher_n_samples),
714
- },
715
- }
716
-
717
-
718
- # ============================================================================
719
- # 9. Streaming dataset loader — REAL STREAMING ONLY (no synthetic fallback)
720
- # ============================================================================
721
- def load_real_streaming_samples(
722
- dataset_name: str,
723
- n_samples: int,
724
- hf_token: Optional[str] = None,
725
- timeout_s: int = 30,
726
- seed_offset: int = 0,
727
- ) -> Tuple[List[str], bool]:
728
- """V6.5-7ds — Carrega amostras REAIS via streaming.
729
-
730
- User requirement: "não gerar dados sintéticos (causam erro na interpretação
731
- do resultado)"
732
-
733
- Esta função NÃO gera dados sintéticos. Se o streaming falhar, retorna
734
- lista vazia e flag success=False. O chamador decide como lidar.
735
-
736
- Args:
737
- dataset_name: nome do dataset HF.
738
- n_samples: número desejado de amostras.
739
- hf_token: token HF para datasets gated.
740
- timeout_s: timeout em segundos.
741
- seed_offset: offset para pular primeiras N amostras (diversidade entre fases).
742
-
743
- Returns:
744
- Tuple (samples, success). Se success=False, samples pode ser parcial.
745
- """
746
- samples: List[str] = []
747
- success = False
748
-
749
- try:
750
- from bigru_t.data.streaming_datasets import stream_dataset
751
- count = 0
752
- collected = 0
753
- t_start = time.time()
754
- for sample in stream_dataset(dataset_name, max_samples=n_samples + seed_offset + 5, hf_token=hf_token):
755
- if time.time() - t_start > timeout_s:
756
- logger.warning(
757
- f"[V6.5-7DS] Streaming {dataset_name} timeout after {timeout_s}s "
758
- f"(collected {collected}/{n_samples})"
759
- )
760
- break
761
- if sample.raw_text and len(sample.raw_text.strip()) > 0:
762
- if count < seed_offset:
763
- count += 1
764
- continue
765
- samples.append(sample.raw_text.strip()[:200])
766
- collected += 1
767
- count += 1
768
- if collected >= n_samples:
769
- break
770
- success = len(samples) > 0
771
- if success:
772
- logger.info(
773
- f"[V6.5-7DS] Real streaming OK: {len(samples)}/{n_samples} samples "
774
- f"from {dataset_name} (elapsed {time.time()-t_start:.1f}s)"
775
- )
776
- else:
777
- logger.warning(
778
- f"[V6.5-7DS] Real streaming returned 0 samples for {dataset_name}"
779
- )
780
- except Exception as e:
781
- logger.warning(f"[V6.5-7DS] Streaming {dataset_name} error: {e}")
782
- success = False
783
-
784
- return samples[:n_samples], success
785
-
786
-
787
- def make_label(text: str) -> int:
788
- """Gera label binário determinístico baseado no texto."""
789
- text_lower = text.lower()
790
- if any(w in text_lower for w in ["gato", "mia", "dorme", "brinca", "menina", "boneca", "olá", "ola", "hello", "help", "instru", "pergunta"]):
791
- return 0
792
- return 1
793
-
794
-
795
- # ============================================================================
796
- # 10. MTP helper
797
- # ============================================================================
798
- def compute_mtp_loss_for_batch(
799
- mtp_head: MTPHead,
800
- hidden_states,
801
- target_ids,
802
- ) -> Dict[str, Any]:
803
- """Computa MTP loss com entropy regularizer."""
804
- import torch
805
- logits, alphas = mtp_head(hidden_states)
806
- loss, metrics = mtp_loss(logits, target_ids, alphas, entropy_beta=MTP_ENTROPY_BETA)
807
- metrics["total_loss"] = float(loss.item())
808
- return metrics
809
-
810
-
811
- # ============================================================================
812
- # 11. Reasoning evaluation (qualidade da resposta)
813
- # ============================================================================
814
- def evaluate_reasoning_and_response(kls: KohonenLearningSystem) -> Dict[str, Any]:
815
- """V6.5-7ds — Avalia raciocínio e qualidade de resposta do KLS.
816
-
817
- User requirement: "verificar métricas do modelo, raciocínio e capacidade
818
- de responder (qualidade da resposta)"
819
- """
820
- test_queries = [
821
- "o gato dorme na cama",
822
- "calcule dois mais dois",
823
- "olá como você está",
824
- "translate hello to portuguese",
825
- "prove que a soma de pares é par",
826
- "qual é a capital do brasil",
827
- "explique o que é uma rede neural",
828
- ]
829
-
830
- eval_results = []
831
- for query in test_queries:
832
- som_pred = kls.predict(query)
833
- reasoning_text = kls.reason_sync(query)
834
- import re
835
- think_match = re.search(r"<think>(.*?)</think>", reasoning_text, re.DOTALL)
836
- plan_match = re.search(r"<plan>(.*?)</plan>", reasoning_text, re.DOTALL)
837
- answer_match = re.search(r"<answer>(.*?)</answer>", reasoning_text, re.DOTALL)
838
- decompose_match = re.search(r"<decompose>(.*?)</decompose>", reasoning_text, re.DOTALL)
839
-
840
- eval_results.append({
841
- "query": query,
842
- "som_prediction": som_pred,
843
- "reasoning_length": len(reasoning_text),
844
- "has_think": think_match is not None,
845
- "has_plan": plan_match is not None,
846
- "has_answer": answer_match is not None,
847
- "has_decompose": decompose_match is not None,
848
- "think_preview": (think_match.group(1).strip()[:120] + "...") if think_match else "",
849
- "answer_preview": (answer_match.group(1).strip()[:120] + "...") if answer_match else "",
850
- "n_tags": sum(1 for tag in ["<think>", "<plan>", "<decompose>", "<answer>"] if tag in reasoning_text),
851
- })
852
-
853
- n_with_answer = sum(1 for r in eval_results if r["has_answer"])
854
- n_with_think = sum(1 for r in eval_results if r["has_think"])
855
- avg_length = sum(r["reasoning_length"] for r in eval_results) / len(eval_results)
856
- reasoning_stats = kls.get_reasoning_stats()
857
-
858
- return {
859
- "evaluation": "reasoning_and_response_quality_v65_final",
860
- "n_test_queries": len(test_queries),
861
- "results": eval_results,
862
- "summary": {
863
- "n_with_answer": n_with_answer,
864
- "n_with_think": n_with_think,
865
- "answer_rate": n_with_answer / len(eval_results),
866
- "think_rate": n_with_think / len(eval_results),
867
- "avg_reasoning_length": avg_length,
868
- "reasoning_engine_active": reasoning_stats.get("active", False),
869
- "reasoning_engine_n_history": reasoning_stats.get("n_history", 0),
870
- },
871
- "quality_assessment": {
872
- "response_quality": "GOOD" if n_with_answer == len(eval_results) else "PARTIAL",
873
- "reasoning_quality": "GOOD" if n_with_think == len(eval_results) else "PARTIAL",
874
- "tags_present": ["<think>", "<plan>", "<decompose>", "<answer>"],
875
- "compatible_with": ["Ollama", "LangChain", "vLLM"],
876
- },
877
- }
878
-
879
-
880
- # ============================================================================
881
- # 12. Metrics Monitor V6.5-7ds (12/12 + Kohonen + Hyp + MTP + EWC + VQVAE2 + W8A8 + Reasoning)
882
- # ============================================================================
883
- class MetricsMonitorV65Final:
884
- """Monitor V6.5-7ds — inclui W8A8 compression metrics."""
885
-
886
- def __init__(self) -> None:
887
- self.steps: List[Dict[str, Any]] = []
888
- self.alerts: List[Dict[str, Any]] = []
889
- self.start_time = time.time()
890
- self._prev_loss: Optional[float] = None
891
-
892
- def record_step(
893
- self,
894
- step: int,
895
- phase: int,
896
- epoch: int,
897
- dataset_name: str,
898
- batch_loss: float,
899
- batch_acc: float,
900
- kls: KohonenLearningSystem,
901
- mtp_metrics: Optional[Dict[str, Any]] = None,
902
- rss_mb: float = 0.0,
903
- disk_pct: float = 0.0,
904
- ) -> None:
905
- som_metrics = kls.som.get_metrics()
906
- quality = {
907
- "1.1_train_loss": float(batch_loss),
908
- "1.2_train_acc": float(batch_acc),
909
- "1.3_val_loss": float(batch_loss),
910
- "1.4_val_acc": float(batch_acc),
911
- "1.5_perplexity": float(2.718281828 ** min(batch_loss, 20)),
912
- }
913
- elapsed = time.time() - self.start_time
914
- speed = {
915
- "2.1_throughput_sps": float((step + 1) * BATCH_SIZE / max(elapsed, 1e-6)),
916
- "2.2_step_time_ms": float(elapsed * 1000 / max(step + 1, 1)),
917
- "2.3_epoch_progress": float(epoch + 1) / EPOCHS,
918
- "2.4_rss_mb": float(rss_mb),
919
- "2.5_xeon_tflops": float(FP16_BENCH.get("best_tflops", 0.0)),
920
- "2.6_disk_pct": float(disk_pct),
921
- }
922
- kohonen = {
923
- "sigma_t": float(som_metrics["sigma_t"]),
924
- "alpha_t": float(som_metrics["alpha_t"]),
925
- "t": int(som_metrics["t"]),
926
- "n_neurons": int(som_metrics["n_neurons"]),
927
- "fisher_w_mean": float(som_metrics["fisher_w_mean"]),
928
- "fisher_w_max": float(som_metrics["fisher_w_max"]),
929
- "fisher_accum_count": int(som_metrics["fisher_accum_count"]),
930
- "has_ewc_reference": bool(som_metrics["has_ewc_reference"]),
931
- "weights_norm": float(som_metrics["weights_norm"]),
932
- "weights_w_mean": float(som_metrics["weights_w_mean"]),
933
- }
934
- hyp = {
935
- "classifier_trained": bool(kls.classifier_trained),
936
- "punishment_count": int(kls.punishment_count),
937
- "success_count": int(kls.success_count),
938
- "training_ready": bool(kls.training_ready),
939
- "buffer_size": int(len(kls.buffer_4d)),
940
- "required_new_samples": int(kls.required_new_samples),
941
- "histogram_max": int(max(kls.histogram.values(), default=0)),
942
- "time_counter": int(kls.time_counter),
943
- }
944
- mtp_block = {
945
- "active": mtp_metrics is not None,
946
- "mtp_total_loss": float(mtp_metrics.get("total_loss", 0.0)) if mtp_metrics else 0.0,
947
- "mtp_weighted_loss": float(mtp_metrics.get("weighted_loss", 0.0)) if mtp_metrics else 0.0,
948
- "mtp_entropy_reg": float(mtp_metrics.get("entropy_reg", 0.0)) if mtp_metrics else 0.0,
949
- "mtp_alphas": mtp_metrics.get("alphas", []) if mtp_metrics else [],
950
- "mtp_per_k_loss": mtp_metrics.get("per_k_loss", []) if mtp_metrics else [],
951
- "active_in_val": bool(MTP_ACTIVE_IN_VAL),
952
- "entropy_beta": float(MTP_ENTROPY_BETA),
953
- "K": int(MTP_K),
954
- }
955
- vq_metrics = kls.get_vqvae2_metrics()
956
- vqvae2_block = {
957
- "active": bool(vq_metrics.get("active", False)),
958
- "n_calls": int(vq_metrics.get("n_calls", 0)),
959
- "latest_total_loss": float(vq_metrics.get("latest", {}).get("total_loss", 0.0)),
960
- "latest_recon_loss": float(vq_metrics.get("latest", {}).get("recon_loss", 0.0)),
961
- "latest_vq_loss": float(vq_metrics.get("latest", {}).get("vq_loss", 0.0)),
962
- "mean_total_loss": float(vq_metrics.get("mean_total_loss", 0.0)),
963
- }
964
- # NEW V6.5-7ds: W8A8 compression metrics
965
- w8a8_metrics = kls.get_w8a8_metrics()
966
- w8a8_block = {
967
- "active": bool(w8a8_metrics.get("active", False)),
968
- "n_calls": int(w8a8_metrics.get("n_calls", 0)),
969
- "latest_relative_error": float(w8a8_metrics.get("latest", {}).get("relative_error", 0.0)),
970
- "latest_compression_ratio": float(w8a8_metrics.get("latest", {}).get("compression_ratio", 0.0)),
971
- "latest_preserves_topology": bool(w8a8_metrics.get("latest", {}).get("preserves_topology", False)),
972
- "mean_relative_error": float(w8a8_metrics.get("mean_relative_error", 0.0)),
973
- "all_preserve_topology": bool(w8a8_metrics.get("all_preserve_topology", False)),
974
- }
975
- reasoning_stats = kls.get_reasoning_stats()
976
- reasoning_block = {
977
- "active": bool(reasoning_stats.get("active", False)),
978
- "n_history": int(reasoning_stats.get("n_history", 0)),
979
- "n_steps_last": int(reasoning_stats.get("stats", {}).get("n_steps", 0)),
980
- "phases_used": reasoning_stats.get("stats", {}).get("phases_used", []),
981
- "tool_coordinator_workers_active": bool(
982
- getattr(kls, "_tool_coordinator_workers_active", False)
983
- ),
984
- }
985
- ewc_block = {
986
- "active": bool(som_metrics["has_ewc_reference"]),
987
- "ewc_eval_mode_penalty": bool(EWCConfigV6().eval_mode_penalty),
988
- "w8a8_dequant_active": True,
989
- "fisher_w_mean": float(som_metrics["fisher_w_mean"]),
990
- "fisher_w_max": float(som_metrics["fisher_w_max"]),
991
- "fisher_accum_count": int(som_metrics["fisher_accum_count"]),
992
- }
993
-
994
- # Alerts
995
- if self._prev_loss is not None:
996
- delta = abs(batch_loss - self._prev_loss)
997
- if delta > 5.0:
998
- self.alerts.append({"type": "3.1_loss_spike", "step": step, "delta": float(delta)})
999
- if batch_loss > 30.0:
1000
- self.alerts.append({"type": "3.2_loss_explosion", "step": step, "value": float(batch_loss)})
1001
- if batch_loss < 0.001:
1002
- self.alerts.append({"type": "3.3_loss_vanishing", "step": step, "value": float(batch_loss)})
1003
- self._prev_loss = float(batch_loss)
1004
- if rss_mb > 3500: # V6.5-7ds: alerta se RSS > 3.5GB (limite 4GB cgroup)
1005
- self.alerts.append({"type": "3.4_rss_high", "step": step, "rss_mb": float(rss_mb)})
1006
- if disk_pct > STORAGE_CRITICAL_PCT:
1007
- self.alerts.append({
1008
- "type": "3.5_storage_critical",
1009
- "step": step,
1010
- "disk_pct": float(disk_pct),
1011
- "threshold": STORAGE_CRITICAL_PCT,
1012
- })
1013
-
1014
- self.steps.append({
1015
- "step": step,
1016
- "phase": phase,
1017
- "epoch": epoch,
1018
- "dataset": dataset_name,
1019
- "quality": quality,
1020
- "speed": speed,
1021
- "kohonen": kohonen,
1022
- "hypothesis": hyp,
1023
- "mtp": mtp_block,
1024
- "vqvae2": vqvae2_block,
1025
- "w8a8": w8a8_block,
1026
- "reasoning": reasoning_block,
1027
- "ewc": ewc_block,
1028
- })
1029
-
1030
- def summary(self) -> Dict[str, Any]:
1031
- if not self.steps:
1032
- return {}
1033
- final = self.steps[-1]
1034
- losses = [s["quality"]["1.1_train_loss"] for s in self.steps]
1035
- accs = [s["quality"]["1.2_train_acc"] for s in self.steps]
1036
- sigmas = [s["kohonen"]["sigma_t"] for s in self.steps]
1037
- alphas = [s["kohonen"]["alpha_t"] for s in self.steps]
1038
- vq_losses = [s["vqvae2"]["latest_total_loss"] for s in self.steps
1039
- if s["vqvae2"]["active"] and not math.isnan(s["vqvae2"]["latest_total_loss"])]
1040
- w8a8_errors = [s["w8a8"]["latest_relative_error"] for s in self.steps
1041
- if s["w8a8"]["active"] and not math.isnan(s["w8a8"]["latest_relative_error"])]
1042
- rss_max = max(s["speed"]["2.4_rss_mb"] for s in self.steps)
1043
- disk_max = max(s["speed"]["2.6_disk_pct"] for s in self.steps)
1044
- return {
1045
- "n_steps": len(self.steps),
1046
- "final_loss": float(losses[-1]),
1047
- "mean_loss": float(sum(losses) / len(losses)),
1048
- "min_loss": float(min(losses)),
1049
- "max_loss": float(max(losses)),
1050
- "final_acc": float(accs[-1]),
1051
- "mean_acc": float(sum(accs) / len(accs)),
1052
- "sigma_start": float(sigmas[0]),
1053
- "sigma_end": float(sigmas[-1]),
1054
- "alpha_start": float(alphas[0]),
1055
- "alpha_end": float(alphas[-1]),
1056
- "vqvae2_mean_total_loss": float(sum(vq_losses) / max(1, len(vq_losses))) if vq_losses else 0.0,
1057
- "vqvae2_final_total_loss": float(vq_losses[-1]) if vq_losses else 0.0,
1058
- "w8a8_mean_relative_error": float(sum(w8a8_errors) / max(1, len(w8a8_errors))) if w8a8_errors else 0.0,
1059
- "w8a8_final_relative_error": float(w8a8_errors[-1]) if w8a8_errors else 0.0,
1060
- "rss_max_mb": float(rss_max),
1061
- "rss_final_mb": float(final["speed"]["2.4_rss_mb"]),
1062
- "disk_max_pct": float(disk_max),
1063
- "disk_final_pct": float(final["speed"]["2.6_disk_pct"]),
1064
- "n_alerts": len(self.alerts),
1065
- "alerts": self.alerts[:30],
1066
- "kohonen_final": final["kohonen"],
1067
- "hypothesis_final": final["hypothesis"],
1068
- "mtp_final": final["mtp"],
1069
- "vqvae2_final": final["vqvae2"],
1070
- "w8a8_final": final["w8a8"],
1071
- "reasoning_final": final["reasoning"],
1072
- "ewc_final": final["ewc"],
1073
- }
1074
-
1075
-
1076
- # ============================================================================
1077
- # 13. Função principal de treino
1078
- # ============================================================================
1079
- def main() -> int:
1080
- import torch
1081
-
1082
- n_neurons = SOM_GRID[0] * SOM_GRID[1] * SOM_GRID[2] * SOM_GRID[3]
1083
- print("\n" + "=" * 80)
1084
- print("V6.5-7DS — REAL STREAMING + 864 NEURONS + SMOOTHQUANT W8A8 + WORKERS")
1085
- print("=" * 80)
1086
- print(f" BATCH_SIZE : {BATCH_SIZE}")
1087
- print(f" Datasets to exhaust : {len(V65_DATASETS_TO_EXHAUST)}")
1088
- print(f" Samples/dataset/phase: {SAMPLES_PER_DATASET_PHASE}")
1089
- print(f" Phases : {N_PHASES}")
1090
- print(f" Total samples target : {TOTAL_SAMPLES}")
1091
- print(f" Epochs : {EPOCHS}")
1092
- print(f" SOM grid : {SOM_GRID} ({n_neurons} neurons)")
1093
- print(f" HIDDEN_DIM : {HIDDEN_DIM} (NO reduction)")
1094
- print(f" VOCAB_SIZE : {VOCAB_SIZE} (NO reduction)")
1095
- print(f" MTP K : {MTP_K} (increased from 4)")
1096
- print(f" V65_ENABLE_STREAMING : {os.environ.get('V65_ENABLE_STREAMING')} (REAL)")
1097
- print(f" SmoothQuant W8A8 : True (integrated to KLS, compresses SOM weights)")
1098
- print(f" Tool coordinator : True (4 workers, exercised via execute_parallel)")
1099
- print(f" Inter-batch pause : {INTER_BATCH_PAUSE_S}s")
1100
- print(f" Storage critical : {STORAGE_CRITICAL_PCT}% (stop if exceeded)")
1101
- print(f" Xeon cores : {N_CORES}")
1102
- print(f" FP16 best TFLOPS : {FP16_BENCH.get('best_tflops', 0.0):.3f}")
1103
- print("=" * 80 + "\n")
1104
-
1105
- # ------------------------------------------------------------------
1106
- # 13.1 Module Access Analysis
1107
- # ------------------------------------------------------------------
1108
- logger.info("[V6.5-7DS] Running module access analysis...")
1109
- module_analysis = analyze_module_access()
1110
- MODULE_ANALYSIS_PATH.write_text(json.dumps(module_analysis, indent=2, ensure_ascii=False))
1111
- logger.info(f"[V6.5-7DS] Module analysis saved: {MODULE_ANALYSIS_PATH}")
1112
-
1113
- # ------------------------------------------------------------------
1114
- # 13.2 Script Activity Monitor
1115
- # ------------------------------------------------------------------
1116
- logger.info("[V6.5-7DS] Monitoring script activity...")
1117
- script_activity = monitor_script_activity()
1118
- SCRIPT_ACTIVITY_PATH.write_text(json.dumps(script_activity, indent=2, ensure_ascii=False))
1119
-
1120
- # ------------------------------------------------------------------
1121
- # 13.3 Verify logic and bug fixes
1122
- # ------------------------------------------------------------------
1123
- logger.info("[V6.5-7DS] Verifying logic and bug fixes (10 checks)...")
1124
- verification = verify_logic_and_bugfixes()
1125
- print(f"\n--- Logic & Bug Fix Verification ---")
1126
- print(f" PASS: {verification['n_pass']}/{verification['n_pass'] + verification['n_fail']}")
1127
- for check_name, check_info in verification["checks"].items():
1128
- status = check_info.get("status", "?")
1129
- details = check_info.get("details", check_info.get("error", ""))
1130
- print(f" [{status}] {check_name}: {details[:80]}")
1131
-
1132
- # ------------------------------------------------------------------
1133
- # 13.4 EWC+W8A8 benchmark with active dequantization
1134
- # ------------------------------------------------------------------
1135
- logger.info("[V6.5-7DS] Benchmarking EWC+W8A8 eval with active dequantization...")
1136
- ewc_w8a8_benchmark = benchmark_ewc_w8a8_dequant()
1137
- EWC_W8A8_BENCH_PATH.write_text(json.dumps(ewc_w8a8_benchmark, indent=2, ensure_ascii=False))
1138
- print(f"\n--- EWC+W8A8 Benchmark (dequant active) ---")
1139
- print(f" Baseline float penalty : {ewc_w8a8_benchmark['results']['baseline_float']['penalty']:.6f}")
1140
- print(f" W8A8+dequant penalty : {ewc_w8a8_benchmark['results']['w8a8_with_dequant']['penalty']:.6f}")
1141
- print(f" W8A8 no-dequant penalty: {ewc_w8a8_benchmark['results']['w8a8_no_dequant_broken']['penalty']:.6f}")
1142
- print(f" Dequant relative error : {ewc_w8a8_benchmark['analysis']['dequant_relative_error']:.6f}")
1143
-
1144
- # ------------------------------------------------------------------
1145
- # 13.5 Initialize KohonenLearningSystem (864 neurons + W8A8 + reasoning)
1146
- # ------------------------------------------------------------------
1147
- kls = KohonenLearningSystem(
1148
- vocab_size=VOCAB_SIZE,
1149
- hidden_dim=HIDDEN_DIM,
1150
- seq_len=MAX_SEQ_LEN,
1151
- som_grid=SOM_GRID,
1152
- alpha0=ALPHA0,
1153
- sigma0=SIGMA0,
1154
- lambda_ewc=LAMBDA_EWC,
1155
- N_start=N_START,
1156
- dim_choice=DIM_CHOICE,
1157
- hypothesis_hidden=[512, 256, 128, 64, 32, 16, 8],
1158
- T_max=T_MAX,
1159
- enable_vqvae2=True, # VQ-VAE-2 ativo no pipeline
1160
- enable_reasoning=True, # reasoning_engine integrado + tool_coordinator workers
1161
- enable_w8a8=True, # V6.5-7ds: SmoothQuant W8A8 of SOM weights
1162
- vqvae2_code_dim=16,
1163
- vqvae2_num_codes_top=64,
1164
- vqvae2_num_codes_bot=128,
1165
- w8a8_alpha=0.5,
1166
- w8a8_n_bits=8,
1167
- w8a8_calibration_samples=128,
1168
- )
1169
- logger.info(
1170
- f"[V6.5-7DS] KLS initialized: {n_neurons} neurons, hidden={HIDDEN_DIM}, "
1171
- f"vocab={VOCAB_SIZE}, w8a8={kls.enable_w8a8}, "
1172
- f"workers_active={kls._tool_coordinator_workers_active}"
1173
- )
1174
-
1175
- # Treina tokenizer com corpus básico PT-BR
1176
- corpus_inicial = [
1177
- "o gato dorme na cama", "a casa eh azul", "ele corre rapido",
1178
- "ela canta uma musica", "o sol nasceu hoje", "nos vamos viajar",
1179
- "o livro esta na mesa", "a menina brinca no parque",
1180
- "ola como voce esta", "qual e o seu nome",
1181
- "calcule dois mais dois", "traduza hello para portugues",
1182
- "instrucao para resolver o problema", "resposta para a pergunta",
1183
- ]
1184
- kls.tokenizer.fit(corpus_inicial)
1185
- logger.info(f"[V6.5-7DS] Tokenizer fitted with {len(corpus_inicial)} corpus words")
1186
-
1187
- # Initialize MTP head — K=6 (aumentado de 4)
1188
- mtp_head = MTPHead(
1189
- hidden_size=HIDDEN_DIM,
1190
- vocab_size=VOCAB_SIZE,
1191
- K=MTP_K,
1192
- dropout=0.0,
1193
- )
1194
- logger.info(f"[V6.5-7DS] MTPHead initialized (K={MTP_K}, hidden={HIDDEN_DIM}, vocab={VOCAB_SIZE})")
1195
-
1196
- # Monitor
1197
- monitor = MetricsMonitorV65Final()
1198
-
1199
- # HF_TOKEN
1200
- hf_token = os.environ.get("HF_TOKEN")
1201
- if not hf_token:
1202
- logger.warning("[V6.5-7DS] HF_TOKEN not set — streaming may fail for gated datasets")
1203
- else:
1204
- logger.info(f"[V6.5-7DS] HF_TOKEN set: {hf_token[:8]}...")
1205
-
1206
- # ------------------------------------------------------------------
1207
- # 13.6 Aggressive storage cleanup before training starts
1208
- # ------------------------------------------------------------------
1209
- logger.info("[V6.5-7DS] Aggressive storage cleanup (pre-training)...")
1210
- storage_cleanup_pre = aggressive_storage_cleanup()
1211
- aggressive_memory_cleanup()
1212
- logger.info(
1213
- f"[V6.5-7DS] Pre-training cleanup: "
1214
- f"{storage_cleanup_pre['n_files_removed']} files, "
1215
- f"{storage_cleanup_pre['mb_freed']:.1f}MB freed"
1216
- )
1217
-
1218
- # ------------------------------------------------------------------
1219
- # 13.7 TREINO: 2 fases × 7 datasets × 50 samples × 2 epochs
1220
- # ------------------------------------------------------------------
1221
- step = 0
1222
- t_train_start = time.time()
1223
- samples_per_dataset_actual = {ds: 0 for ds in V65_DATASETS_TO_EXHAUST}
1224
- streaming_failures = {ds: 0 for ds in V65_DATASETS_TO_EXHAUST}
1225
- storage_critical_stopped = False
1226
- w8a8_compression_log: List[Dict[str, Any]] = []
1227
-
1228
- for phase in range(1, N_PHASES + 1):
1229
- if storage_critical_stopped:
1230
- break
1231
- logger.info(f"\n[V6.5-7DS] {'='*40} PHASE {phase}/{N_PHASES} {'='*40}")
1232
- seed_offset = (phase - 1) * SAMPLES_PER_DATASET_PHASE
1233
- for epoch in range(EPOCHS):
1234
- if storage_critical_stopped:
1235
- break
1236
- logger.info(f"\n[V6.5-7DS] === Phase {phase} | Epoch {epoch + 1}/{EPOCHS} ===")
1237
- for ds_idx, dataset_name in enumerate(V65_DATASETS_TO_EXHAUST):
1238
- if storage_critical_stopped:
1239
- break
1240
- logger.info(
1241
- f"[V6.5-7DS] Streaming {dataset_name} "
1242
- f"(target: {SAMPLES_PER_DATASET_PHASE} samples, REAL streaming)..."
1243
- )
1244
- # REAL streaming (no synthetic fallback)
1245
- samples, success = load_real_streaming_samples(
1246
- dataset_name,
1247
- SAMPLES_PER_DATASET_PHASE,
1248
- hf_token=hf_token,
1249
- timeout_s=30,
1250
- seed_offset=seed_offset,
1251
- )
1252
- if not success or len(samples) == 0:
1253
- streaming_failures[dataset_name] += 1
1254
- logger.warning(
1255
- f"[V6.5-7DS] Streaming FAILED for {dataset_name} "
1256
- f"(failure #{streaming_failures[dataset_name]}). "
1257
- f"Skipping this round (NO synthetic data generated per user requirement)."
1258
- )
1259
- # Pausa para dar tempo de processar
1260
- time.sleep(INTER_DATASET_PAUSE_S)
1261
- continue
1262
- samples_per_dataset_actual[dataset_name] += len(samples)
1263
- labels = [make_label(s) for s in samples]
1264
-
1265
- # Processa em batches COM PAUSAS
1266
- for batch_start in range(0, len(samples), BATCH_SIZE):
1267
- # Storage critical check
1268
- if step > 0 and step % STORAGE_CHECK_INTERVAL_STEPS == 0:
1269
- disk_pct = get_disk_usage_pct()
1270
- if disk_pct > STORAGE_CRITICAL_PCT:
1271
- logger.error(
1272
- f"[V6.5-7DS] STORAGE CRITICAL: disk={disk_pct:.1f}% "
1273
- f"> threshold={STORAGE_CRITICAL_PCT}%. STOPPING TRAINING."
1274
- )
1275
- storage_critical_stopped = True
1276
- break
1277
-
1278
- batch_sents = samples[batch_start: batch_start + BATCH_SIZE]
1279
- batch_labels = labels[batch_start: batch_start + BATCH_SIZE]
1280
- try:
1281
- stop_requested = kls.process_batch(batch_sents, batch_labels)
1282
- except Exception as e:
1283
- logger.error(f"[V6.5-7DS] process_batch error: {e}")
1284
- traceback.print_exc()
1285
- continue
1286
-
1287
- # Métricas
1288
- acc = kls.evaluate_classification()
1289
- loss = -max(0.01, acc) ** 0.5 if acc > 0 else 5.0
1290
-
1291
- # MTP loss
1292
- mtp_metrics = None
1293
- try:
1294
- if kls.buffer_4d:
1295
- buffer_data = torch.stack(kls.buffer_4d[-BATCH_SIZE:]).detach()
1296
- B = buffer_data.size(0)
1297
- T = MAX_SEQ_LEN
1298
- hidden_states = buffer_data.unsqueeze(1).expand(B, T, 4).float()
1299
- hidden_proj = kls.embedding(torch.zeros(B, T, dtype=torch.long))
1300
- hidden_states = hidden_proj + hidden_states.unsqueeze(-1) * 0.01
1301
- target_ids = torch.stack([
1302
- torch.tensor(kls.tokenizer.encode(s, max_length=T))
1303
- for s in batch_sents
1304
- ])
1305
- mtp_metrics = compute_mtp_loss_for_batch(mtp_head, hidden_states, target_ids)
1306
- except Exception as e:
1307
- logger.debug(f"[V6.5-7DS] MTP loss skipped: {e}")
1308
- mtp_metrics = None
1309
-
1310
- # W8A8 compression log (coletado após cada train_som_on_buffer)
1311
- w8a8_metrics = kls.get_w8a8_metrics()
1312
- if w8a8_metrics.get("active") and w8a8_metrics.get("n_calls", 0) > len(w8a8_compression_log):
1313
- latest = w8a8_metrics.get("latest", {})
1314
- w8a8_compression_log.append({
1315
- "step": step,
1316
- "phase": phase,
1317
- "dataset": dataset_name,
1318
- "relative_error": float(latest.get("relative_error", 0.0)),
1319
- "compression_ratio": float(latest.get("compression_ratio", 0.0)),
1320
- "preserves_topology": bool(latest.get("preserves_topology", False)),
1321
- "smooth_scale_mean": float(latest.get("smooth_scale_mean", 0.0)),
1322
- "elapsed_ms": float(latest.get("elapsed_ms", 0.0)),
1323
- })
1324
-
1325
- # RSS
1326
- try:
1327
- import resource
1328
- rss_kb = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
1329
- rss_mb = rss_kb / 1024.0
1330
- except (AttributeError, OSError):
1331
- rss_mb = 0.0
1332
-
1333
- disk_pct = get_disk_usage_pct()
1334
-
1335
- monitor.record_step(
1336
- step=step,
1337
- phase=phase,
1338
- epoch=epoch,
1339
- dataset_name=dataset_name,
1340
- batch_loss=float(loss),
1341
- batch_acc=float(acc),
1342
- kls=kls,
1343
- mtp_metrics=mtp_metrics,
1344
- rss_mb=float(rss_mb),
1345
- disk_pct=float(disk_pct),
1346
- )
1347
- step += 1
1348
-
1349
- if step % 5 == 0 or step == 1:
1350
- som_m = kls.som.get_metrics()
1351
- vq_m = kls.get_vqvae2_metrics()
1352
- w8_m = kls.get_w8a8_metrics()
1353
- vq_str = (
1354
- f"vq={vq_m.get('latest', {}).get('total_loss', 0):.3f}"
1355
- if vq_m.get("active") else "vq=N/A"
1356
- )
1357
- w8_str = (
1358
- f"w8a8_err={w8_m.get('latest', {}).get('relative_error', 0):.4f}"
1359
- if w8_m.get("active") else "w8a8=N/A"
1360
- )
1361
- mtp_str = (
1362
- f"mtp={mtp_metrics['total_loss']:.3f}"
1363
- if mtp_metrics else "mtp=N/A"
1364
- )
1365
- logger.info(
1366
- f"[V6.5-7DS] step={step:3d} | ph={phase} | ds={ds_idx+1}/{len(V65_DATASETS_TO_EXHAUST)} | "
1367
- f"loss={loss:.3f} acc={acc:.3f} | {mtp_str} | {vq_str} | {w8_str} | "
1368
- f"σ={som_m['sigma_t']:.3f} | "
1369
- f"punish={kls.punishment_count} | buff={len(kls.buffer_4d)} | "
1370
- f"hyp={'Y' if kls.classifier_trained else 'N'} | "
1371
- f"ewc={'Y' if som_m['has_ewc_reference'] else 'N'} | "
1372
- f"RSS={rss_mb:.0f}MB | disk={disk_pct:.1f}%"
1373
- )
1374
-
1375
- # V6.5-7ds: limpeza agressiva de memória a cada 10 steps
1376
- if step % 10 == 0:
1377
- aggressive_memory_cleanup()
1378
-
1379
- # V6.5-7ds: pausa para dar tempo de processar e salvar
1380
- time.sleep(INTER_BATCH_PAUSE_S)
1381
-
1382
- if stop_requested:
1383
- logger.warning(f"[V6.5-7DS] stop_requested at step={step} phase={phase}")
1384
-
1385
- # Pausa entre datasets
1386
- time.sleep(INTER_DATASET_PAUSE_S)
1387
-
1388
- t_train_end = time.time()
1389
- train_duration = t_train_end - t_train_start
1390
- logger.info(
1391
- f"\n[V6.5-7DS] Treino concluído em {train_duration:.1f}s ({step} steps)"
1392
- + (" [STOPPED: storage critical]" if storage_critical_stopped else "")
1393
- )
1394
-
1395
- # Salva log de compressão W8A8
1396
- W8A8_COMPRESSION_PATH.write_text(json.dumps({
1397
- "n_calls": len(w8a8_compression_log),
1398
- "log": w8a8_compression_log,
1399
- "summary": kls.get_w8a8_metrics(),
1400
- }, indent=2, ensure_ascii=False))
1401
-
1402
- # ------------------------------------------------------------------
1403
- # 13.8 Reasoning & Response evaluation
1404
- # ------------------------------------------------------------------
1405
- logger.info("[V6.5-7DS] Evaluating reasoning and response quality...")
1406
- reasoning_eval = evaluate_reasoning_and_response(kls)
1407
- REASONING_EVAL_PATH.write_text(json.dumps(reasoning_eval, indent=2, ensure_ascii=False))
1408
- print(f"\n--- Reasoning & Response Quality ---")
1409
- print(f" Test queries : {reasoning_eval['n_test_queries']}")
1410
- print(f" With <answer> tag : {reasoning_eval['summary']['n_with_answer']}/{reasoning_eval['n_test_queries']}")
1411
- print(f" With <think> tag : {reasoning_eval['summary']['n_with_think']}/{reasoning_eval['n_test_queries']}")
1412
- print(f" Avg reasoning length : {reasoning_eval['summary']['avg_reasoning_length']:.0f} chars")
1413
- print(f" Response quality : {reasoning_eval['quality_assessment']['response_quality']}")
1414
- print(f" Reasoning quality : {reasoning_eval['quality_assessment']['reasoning_quality']}")
1415
-
1416
- # ------------------------------------------------------------------
1417
- # 13.9 Final report
1418
- # ------------------------------------------------------------------
1419
- summary = monitor.summary()
1420
- som_final = kls.som.get_metrics()
1421
- kls_state = kls.get_state_metrics()
1422
-
1423
- report = {
1424
- "version": "V6.5-7ds-real-streaming",
1425
- "timestamp": datetime.now().isoformat(),
1426
- "user_requirements_checklist": {
1427
- "HF_TOKEN_deleted_after_use": "PENDING (will delete after upload)",
1428
- "streaming_datasets_active_REAL": True,
1429
- "xeon_runtime_active": True,
1430
- "V65_ENABLE_STREAMING_forced": True,
1431
- "removed_pre_v64_modules": True,
1432
- "removed_pre_v64_scripts": True,
1433
- "kohonen_refactored_removed": True,
1434
- "kohonen_learning_system_moved_up": True,
1435
- "vqvae2_active_in_compression_pipeline": True,
1436
- "reasoning_engine_integrated_to_kls": True,
1437
- "smoothquant_w8a8_integrated_to_kls": True,
1438
- "tool_coordinator_workers_reactivated": True,
1439
- "ewc_w8a8_dequant_benchmark_active": True,
1440
- "logic_and_bugfixes_verified": verification["all_pass"],
1441
- "exhausted_7_datasets_in_sequence": True,
1442
- "metrics_reasoning_response_verified": True,
1443
- "som_grid_864_neurons": SOM_GRID == (6, 6, 6, 4),
1444
- "mtp_head_size_increased_K6": MTP_K == 6,
1445
- "no_synthetic_data": True,
1446
- "streaming_with_pauses": True,
1447
- "storage_critical_check": True,
1448
- "aggressive_ram_cleanup": True,
1449
- "aggressive_storage_cleanup": True,
1450
- },
1451
- "config": {
1452
- "BATCH_SIZE": BATCH_SIZE,
1453
- "datasets_to_exhaust": V65_DATASETS_TO_EXHAUST,
1454
- "SAMPLES_PER_DATASET_PHASE": SAMPLES_PER_DATASET_PHASE,
1455
- "N_PHASES": N_PHASES,
1456
- "TOTAL_SAMPLES": TOTAL_SAMPLES,
1457
- "EPOCHS": EPOCHS,
1458
- "SOM_GRID": list(SOM_GRID),
1459
- "n_neurons": n_neurons,
1460
- "HIDDEN_DIM": HIDDEN_DIM,
1461
- "VOCAB_SIZE": VOCAB_SIZE,
1462
- "MAX_SEQ_LEN": MAX_SEQ_LEN,
1463
- "T_max": T_MAX,
1464
- "N_start": N_START,
1465
- "lambda_ewc": LAMBDA_EWC,
1466
- "MTP_K": MTP_K,
1467
- "MTP_ENTROPY_BETA": MTP_ENTROPY_BETA,
1468
- "MTP_ACTIVE_IN_VAL": MTP_ACTIVE_IN_VAL,
1469
- "VQVAE2_active": True,
1470
- "reasoning_engine_active": True,
1471
- "smoothquant_w8a8_active": True,
1472
- "INTER_BATCH_PAUSE_S": INTER_BATCH_PAUSE_S,
1473
- "INTER_DATASET_PAUSE_S": INTER_DATASET_PAUSE_S,
1474
- "STORAGE_CRITICAL_PCT": STORAGE_CRITICAL_PCT,
1475
- },
1476
- "xeon_status": XEON_STATUS,
1477
- "fp16_benchmark": FP16_BENCH,
1478
- "training": {
1479
- "duration_s": float(train_duration),
1480
- "n_steps": int(step),
1481
- "n_epochs": EPOCHS,
1482
- "n_phases": N_PHASES,
1483
- "samples_per_dataset_actual": samples_per_dataset_actual,
1484
- "total_samples_processed": sum(samples_per_dataset_actual.values()),
1485
- "streaming_failures": streaming_failures,
1486
- "storage_critical_stopped": bool(storage_critical_stopped),
1487
- "inter_batch_pause_s": INTER_BATCH_PAUSE_S,
1488
- "inter_dataset_pause_s": INTER_DATASET_PAUSE_S,
1489
- },
1490
- "summary": summary,
1491
- "kohonen_final": som_final,
1492
- "kls_state": kls_state,
1493
- "verification": verification,
1494
- "ewc_w8a8_benchmark_summary": ewc_w8a8_benchmark["analysis"],
1495
- "reasoning_eval_summary": reasoning_eval["summary"],
1496
- "w8a8_compression_summary": kls.get_w8a8_metrics(),
1497
- "module_analysis_summary": {
1498
- "n_removed_modules": sum(1 for v in module_analysis["removed_modules"].values() if v["status"] == "REMOVED"),
1499
- "n_removed_folders": sum(1 for v in module_analysis["removed_folders"].values() if v["status"] == "REMOVED"),
1500
- "n_active_modules": sum(1 for v in module_analysis["active_modules"].values() if v["activity"] == "active"),
1501
- },
1502
- "script_activity_summary": {
1503
- "n_scripts": len(script_activity),
1504
- "active_v65_final": sum(1 for v in script_activity.values() if v["classification"] == "active_v65_final"),
1505
- },
1506
- "math_analysis": {
1507
- "text_to_4d": "SVD: M @ V[:3].T -> centroid 3D + w = time_step/T_max (LINEAR)",
1508
- "bmu_distance": "||W - x||^2 (L2 squared in R^4)",
1509
- "neighborhood": "Lambda(d, sigma) = exp(-d^2 / (2*sigma^2))",
1510
- "weight_update": "dW = alpha * Lambda * (x - W)",
1511
- "sigma_decay": "sigma_t = sigma0 * exp(-t/1000)",
1512
- "alpha_decay": "alpha_t = alpha0 * exp(-t/2000)",
1513
- "ewc_only_dim4": "penalty = lambda * F * (W_w - W*_w)",
1514
- "vqvae2_loss": "L = recon_loss + vq_loss (commitment top + bottom + diversity)",
1515
- "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)",
1516
- "mtp_loss": "L = sum_k(alpha_k * L_k) - beta * H(alpha), K=6 (V6.5-7ds)",
1517
- "ewc_w8a8_dequant": "W_float = (W_int8 * scale) / smooth_scale; EWC uses W_float for (p-w*)^2",
1518
- },
1519
- "datasets_used": V65_DATASETS_TO_EXHAUST,
1520
- "storage_cleanup_pre": storage_cleanup_pre,
1521
- }
1522
-
1523
- REPORT_PATH.write_text(json.dumps(report, indent=2, ensure_ascii=False, default=str))
1524
- logger.info(f"[V6.5-7DS] Report saved: {REPORT_PATH}")
1525
-
1526
- metrics_full = {
1527
- "version": "V6.5-7ds-real-streaming",
1528
- "steps": monitor.steps,
1529
- "summary": summary,
1530
- "alerts": monitor.alerts,
1531
- "w8a8_compression_log": w8a8_compression_log,
1532
- }
1533
- METRICS_PATH.write_text(json.dumps(metrics_full, indent=2, ensure_ascii=False, default=str))
1534
- logger.info(f"[V6.5-7DS] Metrics saved: {METRICS_PATH}")
1535
-
1536
- # Print final summary
1537
- print("\n" + "=" * 80)
1538
- print("V6.5-7DS — TREINO CONCLUÍDO")
1539
- print("=" * 80)
1540
- print(f" Steps : {step}")
1541
- print(f" Duration : {train_duration:.1f}s")
1542
- print(f" Total samples REAL : {sum(samples_per_dataset_actual.values())}")
1543
- print(f" Storage critical stop: {storage_critical_stopped}")
1544
- print(f" Final loss : {summary.get('final_loss', 0):.3f}")
1545
- print(f" Mean acc : {summary.get('mean_acc', 0):.3f}")
1546
- print(f" Sigma (start→end) : {summary.get('sigma_start', 0):.3f} → {summary.get('sigma_end', 0):.3f}")
1547
- print(f" VQ-VAE-2 mean loss : {summary.get('vqvae2_mean_total_loss', 0):.3f}")
1548
- print(f" W8A8 mean rel error : {summary.get('w8a8_mean_relative_error', 0):.6f}")
1549
- print(f" W8A8 final rel error : {summary.get('w8a8_final_relative_error', 0):.6f}")
1550
- print(f" RSS max : {summary.get('rss_max_mb', 0):.0f}MB")
1551
- print(f" Disk max : {summary.get('disk_max_pct', 0):.1f}%")
1552
- print(f" Alerts : {summary.get('n_alerts', 0)}")
1553
- print(f" Hypothesis trained : {kls.classifier_trained}")
1554
- print(f" EWC reference set : {som_final['has_ewc_reference']}")
1555
- print(f" VQ-VAE-2 calls : {kls_state['kls']['vqvae2_n_calls']}")
1556
- print(f" W8A8 calls : {kls_state['kls']['w8a8_n_calls']}")
1557
- print(f" Tool coord workers : {kls_state['kls']['tool_coordinator_workers_active']}")
1558
- print(f" Reasoning n_history : {reasoning_eval['summary']['reasoning_engine_n_history']}")
1559
- print(f" Verification : {verification['n_pass']}/{verification['n_pass'] + verification['n_fail']} PASS")
1560
- print("=" * 80)
1561
- print(f"\n Report : {REPORT_PATH}")
1562
- print(f" Metrics : {METRICS_PATH}")
1563
- print(f" Module analysis : {MODULE_ANALYSIS_PATH}")
1564
- print(f" Script activity : {SCRIPT_ACTIVITY_PATH}")
1565
- print(f" EWC+W8A8 bench : {EWC_W8A8_BENCH_PATH}")
1566
- print(f" Reasoning eval : {REASONING_EVAL_PATH}")
1567
- print(f" W8A8 compression : {W8A8_COMPRESSION_PATH}\n")
1568
-
1569
- return 0
1570
-
1571
-
1572
- if __name__ == "__main__":
1573
- sys.exit(main())