PowerMachine commited on
Commit
5b9aab4
·
verified ·
1 Parent(s): a062271

V6.5-7ds cleanup: remove legacy scripts/train_v6_5_final.py

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