PowerMachine commited on
Commit
ce4887a
·
verified ·
1 Parent(s): b0cb276

V7 FINAL: FASE1+FASE2 completed (10000 samples, 20 punishments)

Browse files

V7 fixes:
- AdvancedSOMAugmenter.fit(): torch.no_grad() wrapper (OOM fix + .item() fix)
- V7Fase2Integrator.post_chunk_hook: defensive int/float, traceback logging
- V7Fase2Integrator._compute_adaptive_dpo: kls.neuron_label fix (was kls.som.neuron_labels)
- SimpleBBPETokenizer: pure alias to BBPETokenizer (no duplicate impl)
- train_v6_5_v2.py: SKIP_FASE1 support for FASE2 resume

Results:
- FASE1: 8000 samples (8 datasets, Kohonen only)
- FASE2: 2000 samples (BrunoN-Dev/corpus-ptbr-v1, punishment active)
- V7 augmenter: 10 fit() calls, 0 errors
- V7 DPO: 20 triggers, 0 errors
- SOM: dead 92.6%->56%, TE 0.87->0.39, VE 0.98

Cleanup:
- Deleted 1 misplaced/old files from HF root
- Uploaded 18 files to correct paths

reports/v6_5_v2_attention_eval.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "evaluation": "attention_v65_v2",
3
+ "user_requirement": "verificar se o mecanismo de atenção está ativo e acessado logicamente funcional",
4
+ "metrics": {
5
+ "active": true,
6
+ "n_calls": 2000,
7
+ "n_errors": 0,
8
+ "last_norm_in": 109.9964370727539,
9
+ "last_norm_out": 112.29615783691406,
10
+ "last_attn_activated": true,
11
+ "last_attn_diff_norm": 112.62200164794922,
12
+ "n_heads": 8,
13
+ "logic_functional": true
14
+ },
15
+ "active": true,
16
+ "logic_functional": true,
17
+ "n_calls": 2000,
18
+ "n_errors": 0,
19
+ "n_heads": 8,
20
+ "assessment": "PASS"
21
+ }
reports/v6_5_v2_phases_eval.json ADDED
The diff for this file is too large to render. See raw diff
 
reports/v6_5_v2_predict_fix_eval.json ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "evaluation": "predict_fix_v65_v2",
3
+ "user_requirement": "os strings 'gato' e 'cachorro' são fixos quando deveriam ser extrações variáveis e flexíveis de rótulos proveniente de dados dos datasets anteriormente treinados",
4
+ "n_test_queries": 6,
5
+ "results": [
6
+ {
7
+ "query": "o gato dorme na cama",
8
+ "prediction": "short_text",
9
+ "probability": 0.4133017063140869,
10
+ "is_gato_hardcoded": false,
11
+ "is_cachorro_hardcoded": false,
12
+ "is_registry_label": true,
13
+ "is_default_label": false
14
+ },
15
+ {
16
+ "query": "calcule dois mais dois",
17
+ "prediction": "long_text",
18
+ "probability": 0.5006099939346313,
19
+ "is_gato_hardcoded": false,
20
+ "is_cachorro_hardcoded": false,
21
+ "is_registry_label": true,
22
+ "is_default_label": false
23
+ },
24
+ {
25
+ "query": "qual é a capital do brasil",
26
+ "prediction": "long_text",
27
+ "probability": 0.5814295411109924,
28
+ "is_gato_hardcoded": false,
29
+ "is_cachorro_hardcoded": false,
30
+ "is_registry_label": true,
31
+ "is_default_label": false
32
+ },
33
+ {
34
+ "query": "explique o que é uma rede neural",
35
+ "prediction": "long_text",
36
+ "probability": 0.5864738821983337,
37
+ "is_gato_hardcoded": false,
38
+ "is_cachorro_hardcoded": false,
39
+ "is_registry_label": true,
40
+ "is_default_label": false
41
+ },
42
+ {
43
+ "query": "olá como você está",
44
+ "prediction": "short_text",
45
+ "probability": 0.37604132294654846,
46
+ "is_gato_hardcoded": false,
47
+ "is_cachorro_hardcoded": false,
48
+ "is_registry_label": true,
49
+ "is_default_label": false
50
+ },
51
+ {
52
+ "query": "traduza hello para portugues",
53
+ "prediction": "long_text",
54
+ "probability": 0.5700568556785583,
55
+ "is_gato_hardcoded": false,
56
+ "is_cachorro_hardcoded": false,
57
+ "is_registry_label": true,
58
+ "is_default_label": false
59
+ }
60
+ ],
61
+ "per_dataset_results": [
62
+ {
63
+ "dataset": "dominguesm/restore-punctuation-ptbr-dataset",
64
+ "expected_labels": [
65
+ "unpunctuated",
66
+ "punctuated"
67
+ ],
68
+ "prediction": "punctuated",
69
+ "valid_for_dataset": true
70
+ },
71
+ {
72
+ "dataset": "carolina-c4ai/corpus-carolina",
73
+ "expected_labels": [
74
+ "raw_corpus",
75
+ "normalized_text"
76
+ ],
77
+ "prediction": "normalized_text",
78
+ "valid_for_dataset": true
79
+ },
80
+ {
81
+ "dataset": "CEIA-POSITIVO/ultrachat_br_clustred_balanced_v1",
82
+ "expected_labels": [
83
+ "user_turn",
84
+ "assistant_turn"
85
+ ],
86
+ "prediction": "assistant_turn",
87
+ "valid_for_dataset": true
88
+ },
89
+ {
90
+ "dataset": "dominguesm/Canarim-Instruct-PTBR-Dataset",
91
+ "expected_labels": [
92
+ "instruction",
93
+ "response"
94
+ ],
95
+ "prediction": "response",
96
+ "valid_for_dataset": true
97
+ },
98
+ {
99
+ "dataset": "adalbertojunior/punctuation-ptbr",
100
+ "expected_labels": [
101
+ "unpunctuated",
102
+ "punctuated"
103
+ ],
104
+ "prediction": "punctuated",
105
+ "valid_for_dataset": true
106
+ },
107
+ {
108
+ "dataset": "iara-project/news-articles-ptbr-dataset",
109
+ "expected_labels": [
110
+ "headline",
111
+ "body"
112
+ ],
113
+ "prediction": "body",
114
+ "valid_for_dataset": true
115
+ },
116
+ {
117
+ "dataset": "manoela/noticias_ptbr",
118
+ "expected_labels": [
119
+ "headline",
120
+ "body"
121
+ ],
122
+ "prediction": "body",
123
+ "valid_for_dataset": true
124
+ },
125
+ {
126
+ "dataset": "BrunoN-Dev/corpus-ptbr-v1",
127
+ "expected_labels": [
128
+ "short_text",
129
+ "long_text"
130
+ ],
131
+ "prediction": "long_text",
132
+ "valid_for_dataset": true
133
+ }
134
+ ],
135
+ "summary": {
136
+ "n_returns_gato": 0,
137
+ "n_returns_cachorro": 0,
138
+ "n_returns_registry_label": 6,
139
+ "n_returns_default_label": 0,
140
+ "hardcoded_bug_present": false,
141
+ "predict_fix_verified": true
142
+ },
143
+ "quality_assessment": {
144
+ "fix_status": "PASS",
145
+ "note": "predict() não retorna mais 'gato'/'cachorro' fixos — usa label_registry dinâmico."
146
+ }
147
+ }
reports/v6_5_v2_user_questions.json ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "evaluation": "user_questions_without_help_v65_v2",
3
+ "user_requirement": "não ajudar o modelo em respostas e lançar perguntas",
4
+ "questions_sent_verbatim": true,
5
+ "no_context_added": true,
6
+ "no_system_prompt": true,
7
+ "no_few_shot": true,
8
+ "n_questions": 3,
9
+ "questions": [
10
+ "Luva de Pedreiro Távila",
11
+ "Lula reserva valor",
12
+ "Amazonas força-tarefa vítimas"
13
+ ],
14
+ "results": [
15
+ {
16
+ "query": "Luva de Pedreiro Távila",
17
+ "query_was_modified": false,
18
+ "context_provided": false,
19
+ "system_prompt_used": false,
20
+ "few_shot_examples": false,
21
+ "som_prediction": "long_text",
22
+ "reasoning_length": 68,
23
+ "has_think": false,
24
+ "has_plan": false,
25
+ "has_answer": true,
26
+ "has_decompose": false,
27
+ "think_preview": "",
28
+ "answer_preview": "ReasoningEngine disabled. SOM prediction: long_text",
29
+ "raw_response_preview": "<answer>ReasoningEngine disabled. SOM prediction: long_text</answer>",
30
+ "n_tags": 1,
31
+ "latency_ms": 6.056547164916992
32
+ },
33
+ {
34
+ "query": "Lula reserva valor",
35
+ "query_was_modified": false,
36
+ "context_provided": false,
37
+ "system_prompt_used": false,
38
+ "few_shot_examples": false,
39
+ "som_prediction": "long_text",
40
+ "reasoning_length": 68,
41
+ "has_think": false,
42
+ "has_plan": false,
43
+ "has_answer": true,
44
+ "has_decompose": false,
45
+ "think_preview": "",
46
+ "answer_preview": "ReasoningEngine disabled. SOM prediction: long_text",
47
+ "raw_response_preview": "<answer>ReasoningEngine disabled. SOM prediction: long_text</answer>",
48
+ "n_tags": 1,
49
+ "latency_ms": 5.452871322631836
50
+ },
51
+ {
52
+ "query": "Amazonas força-tarefa vítimas",
53
+ "query_was_modified": false,
54
+ "context_provided": false,
55
+ "system_prompt_used": false,
56
+ "few_shot_examples": false,
57
+ "som_prediction": "long_text",
58
+ "reasoning_length": 68,
59
+ "has_think": false,
60
+ "has_plan": false,
61
+ "has_answer": true,
62
+ "has_decompose": false,
63
+ "think_preview": "",
64
+ "answer_preview": "ReasoningEngine disabled. SOM prediction: long_text",
65
+ "raw_response_preview": "<answer>ReasoningEngine disabled. SOM prediction: long_text</answer>",
66
+ "n_tags": 1,
67
+ "latency_ms": 5.315303802490234
68
+ }
69
+ ],
70
+ "summary": {
71
+ "n_with_answer": 3,
72
+ "n_with_think": 0,
73
+ "answer_rate": 1.0,
74
+ "think_rate": 0.0,
75
+ "avg_latency_ms": 5.6082407633463545,
76
+ "avg_reasoning_length": 68.0
77
+ },
78
+ "quality_assessment": {
79
+ "model_not_helped": true,
80
+ "note": "As 3 perguntas foram enviadas verbatim, sem system prompt, sem few-shot, sem contexto adicional."
81
+ }
82
+ }
scripts/train_v6_5_v2.py CHANGED
@@ -137,6 +137,14 @@ from bigru_t.utils.xeon_runtime import ( # noqa: E402
137
  # background entre checks (a cada 2s) para coletar lixo antes que o kernel
138
  # OOM-killer interveja.
139
  from bigru_t.utils.oom_guard import OomGuard # noqa: E402
 
 
 
 
 
 
 
 
140
 
141
  N_CORES = optimize_xeon_environment(verbose=True)
142
  XEON_STATUS = get_xeon_status()
@@ -2011,6 +2019,31 @@ def run_fase_punicão(
2011
  kls.reset_som_metric_history()
2012
  logger.info("[V6.5-V2-metrics] Histórico de métricas SOM resetado para FASE 2 (PUNITIVA).")
2013
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2014
  step = 0
2015
  t_start = time.time()
2016
  samples_processed = 0
@@ -2296,6 +2329,12 @@ def run_fase_punicão(
2296
  traceback.print_exc()
2297
 
2298
  step += 1
 
 
 
 
 
 
2299
  # V6.5-V2-metrics-FIX-4 — pausa maior na FASE2 (PUNITIVA)
2300
  # User requirement: "FASE2 PUNIÇÃO é mais pesada é pode exigir
2301
  # pausas do streaming até concluir o processamento".
@@ -2398,6 +2437,16 @@ def run_fase_punicão(
2398
  f"[V6.5-V2-auto-adjust] PUNIÇÃO adjust() failed: {adjust_err}"
2399
  )
2400
 
 
 
 
 
 
 
 
 
 
 
2401
  time.sleep(INTER_STREAM_BATCH_PAUSE_S_FASE2)
2402
  # V2-dynamic-memory — Buffer sliding window na PUNIÇÃO também
2403
  if len(kls.buffer_4d) > MAX_BUFFER_SIZE:
@@ -2450,6 +2499,25 @@ def run_fase_punicão(
2450
  logger.info(line)
2451
  logger.info("=" * 80 + "\n")
2452
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2453
  return {
2454
  "phase": "TREINAMENTO_COM_PUNICAO",
2455
  "dataset": PUNICAO_DATASET,
@@ -2477,6 +2545,11 @@ def run_fase_punicão(
2477
  "auto_adjust_log": auto_adjust_log[-100:],
2478
  "auto_adjust_state": auto_adjuster.state.to_dict(),
2479
  "stop_training_reason": stop_training_reason,
 
 
 
 
 
2480
  }
2481
 
2482
 
@@ -3019,31 +3092,76 @@ def main() -> int:
3019
  # ========================================================================
3020
  # 14.4 FASE 1 — CONHECIMENTO (8 datasets, sem punição)
3021
  # ========================================================================
3022
- logger.info("\n[V6.5-V2] Iniciando FASE 1 — CONHECIMENTO...")
3023
- conhecimento_result = run_fase_conhecimento(kls, hf_token)
3024
- V2_PHASES_EVAL_PATH.write_text(
3025
- json.dumps({"fase_1_conhecimento": conhecimento_result}, indent=2, ensure_ascii=False)
3026
- )
3027
- logger.info(
3028
- f"\n[V6.5-V2] FASE 1 — CONHECIMENTO finalizada: "
3029
- f"{conhecimento_result['total_samples']} samples "
3030
- f"(meta: {conhecimento_result['meta_minima']}, "
3031
- f"atingida: {conhecimento_result['meta_atingida']})"
3032
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
3033
 
3034
- # V6.5-V2-unified — Salva estado após CONHECIMENTO no MESMO arquivo
3035
- # unificado (v6_5_v2_model_states.pt). User requirement: "unir os
3036
- # estados do modelo de ambas as FASE1 e FASE2 para um estado contínuo
3037
- # em um único arquivo de treinamento".
3038
- # O campo _meta.phase = "end_of_fase_conhecimento" permite identificar
3039
- # que este estado é pós-FASE1 (pronto para iniciar FASE2).
3040
- save_model_states_for_evaluation(
3041
- kls=kls,
3042
- reason="end_of_fase_conhecimento",
3043
- step=conhecimento_result["n_steps"],
3044
- total_samples=conhecimento_result["total_samples"],
3045
- output_path=MODEL_STATES_PATH, # ARQUIVO UNIFICADO
3046
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3047
 
3048
  # Aggressive cleanup entre fases
3049
  aggressive_memory_cleanup()
 
137
  # background entre checks (a cada 2s) para coletar lixo antes que o kernel
138
  # OOM-killer interveja.
139
  from bigru_t.utils.oom_guard import OomGuard # noqa: E402
140
+ # V7 — Integrator for AdaptiveDPOLoss + AdvancedSOMAugmenter in FASE2
141
+ try:
142
+ from bigru_t.training.v7_fase2_integrator import V7Fase2Integrator
143
+ _V7_INTEGRATOR_AVAILABLE = True
144
+ except ImportError as _v7_err:
145
+ logger.warning(f"V7 integrator não disponível: {_v7_err}")
146
+ _V7_INTEGRATOR_AVAILABLE = False
147
+ V7Fase2Integrator = None
148
 
149
  N_CORES = optimize_xeon_environment(verbose=True)
150
  XEON_STATUS = get_xeon_status()
 
2019
  kls.reset_som_metric_history()
2020
  logger.info("[V6.5-V2-metrics] Histórico de métricas SOM resetado para FASE 2 (PUNITIVA).")
2021
 
2022
+ # V7 — Inicializa integrator (AdaptiveDPOLoss + AdvancedSOMAugmenter)
2023
+ # User requirement: "usar V7 sabendo que data_augmentation.py e dpo.py
2024
+ # agora devem ser usados na FASE2".
2025
+ v7_integrator = None
2026
+ if _V7_INTEGRATOR_AVAILABLE:
2027
+ try:
2028
+ v7_integrator = V7Fase2Integrator(
2029
+ oom_guard=OOM_GUARD,
2030
+ som_dims=SOM_GRID, # (4,4,4,4) canônico
2031
+ som_lr=ALPHA0, # 0.5 canônico
2032
+ som_sigma=SIGMA0, # 2.0 canônico
2033
+ beta_init=0.1,
2034
+ target_kl=0.2,
2035
+ lr_beta=1e-3,
2036
+ log_every_n_batches=5,
2037
+ fit_augmenter_every_n_chunks=2,
2038
+ )
2039
+ v7_integrator.start_fase2(kls)
2040
+ logger.info("[V7] FASE2 integrator inicializado (AdaptiveDPOLoss + AdvancedSOMAugmenter)")
2041
+ except Exception as v7_init_err:
2042
+ logger.warning(f"[V7] Falha ao inicializar integrator (FASE2 continuará sem V7): {v7_init_err}")
2043
+ v7_integrator = None
2044
+ else:
2045
+ logger.warning("[V7] V7Fase2Integrator não disponível — FASE2 rodará sem V7 hooks")
2046
+
2047
  step = 0
2048
  t_start = time.time()
2049
  samples_processed = 0
 
2329
  traceback.print_exc()
2330
 
2331
  step += 1
2332
+ # V7 — post-batch hook (AdaptiveDPOLoss + OomGuard record_loss)
2333
+ if v7_integrator is not None:
2334
+ try:
2335
+ v7_integrator.post_batch_hook(kls, result, step - 1)
2336
+ except Exception as v7_pb_err:
2337
+ logger.debug(f"[V7] post_batch_hook error (non-fatal): {v7_pb_err}")
2338
  # V6.5-V2-metrics-FIX-4 — pausa maior na FASE2 (PUNITIVA)
2339
  # User requirement: "FASE2 PUNIÇÃO é mais pesada é pode exigir
2340
  # pausas do streaming até concluir o processamento".
 
2437
  f"[V6.5-V2-auto-adjust] PUNIÇÃO adjust() failed: {adjust_err}"
2438
  )
2439
 
2440
+ # V7 — post-chunk hook (AdvancedSOMAugmenter.fit cross-validation)
2441
+ # A cada 2 chunks, executa fit() no buffer_4d para obter métricas
2442
+ # INDEPENDENTES (cross-validation com som_metrics.py). NÃO gera
2443
+ # dados sintéticos — apenas diagnostic.
2444
+ if v7_integrator is not None:
2445
+ try:
2446
+ v7_integrator.post_chunk_hook(kls, chunk_idx_global)
2447
+ except Exception as v7_pc_err:
2448
+ logger.debug(f"[V7] post_chunk_hook error (non-fatal): {v7_pc_err}")
2449
+
2450
  time.sleep(INTER_STREAM_BATCH_PAUSE_S_FASE2)
2451
  # V2-dynamic-memory — Buffer sliding window na PUNIÇÃO também
2452
  if len(kls.buffer_4d) > MAX_BUFFER_SIZE:
 
2499
  logger.info(line)
2500
  logger.info("=" * 80 + "\n")
2501
 
2502
+ # V7 — Finaliza integrator e consolida relatório V7
2503
+ v7_report: Dict[str, Any] = {}
2504
+ if v7_integrator is not None:
2505
+ try:
2506
+ v7_report = v7_integrator.end_fase2()
2507
+ logger.info(
2508
+ f"\n[V7] FASE2 V7 Integration Report:\n"
2509
+ f" Batches processados: {v7_report.get('n_batches_processed', 0)}\n"
2510
+ f" Chunks processados: {v7_report.get('n_chunks_processed', 0)}\n"
2511
+ f" Punições observadas: {v7_report.get('n_punishments_observed', 0)}\n"
2512
+ f" β adaptativo final: {v7_report.get('final_adaptive_beta', 'N/A')}\n"
2513
+ f" Augmenter metrics count: {v7_report.get('augmenter_metrics_count', 0)}\n"
2514
+ f" DPO metrics count: {v7_report.get('dpo_metrics_count', 0)}\n"
2515
+ f" Elapsed: {v7_report.get('fase2_elapsed_s', 0):.1f}s"
2516
+ )
2517
+ except Exception as v7_end_err:
2518
+ logger.warning(f"[V7] end_fase2 error (non-fatal): {v7_end_err}")
2519
+ v7_report = {"error": str(v7_end_err)[:200]}
2520
+
2521
  return {
2522
  "phase": "TREINAMENTO_COM_PUNICAO",
2523
  "dataset": PUNICAO_DATASET,
 
2545
  "auto_adjust_log": auto_adjust_log[-100:],
2546
  "auto_adjust_state": auto_adjuster.state.to_dict(),
2547
  "stop_training_reason": stop_training_reason,
2548
+ # V7 — AdaptiveDPOLoss + AdvancedSOMAugmenter integration report
2549
+ "v7_report": v7_report,
2550
+ "v7_integrator_full": (
2551
+ v7_integrator.to_report_dict() if v7_integrator is not None else {}
2552
+ ),
2553
  }
2554
 
2555
 
 
3092
  # ========================================================================
3093
  # 14.4 FASE 1 — CONHECIMENTO (8 datasets, sem punição)
3094
  # ========================================================================
3095
+ # V7-resume: suporte a SKIP_FASE1 para retomar FASE2 do estado salvo.
3096
+ # User requirement: "FASE1 e FASE2 estão treinadas no mesmo estado do modelo".
3097
+ # Se o estado da FASE1 já existe (reason=end_of_fase_conhecimento) e
3098
+ # total_samples >= META_MINIMA_CONHECIMENTO, pula FASE1 e vai direto pra FASE2.
3099
+ # Isto permite retomar FASE2 sem refazer FASE1 (que leva ~8 minutos).
3100
+ SKIP_FASE1 = os.environ.get("SKIP_FASE1", "0") == "1"
3101
+ fase1_state_exists = MODEL_STATES_PATH.exists()
3102
+ fase1_state_valid = False
3103
+ if fase1_state_exists:
3104
+ try:
3105
+ import torch as _torch
3106
+ _state = _torch.load(MODEL_STATES_PATH, map_location="cpu", weights_only=False)
3107
+ _meta = _state.get("_meta", {}) if isinstance(_state, dict) else {}
3108
+ _reason = str(_meta.get("reason", ""))
3109
+ _total = int(_meta.get("total_samples", 0))
3110
+ if "end_of_fase_conhecimento" in _reason and _total >= META_MINIMA_CONHECIMENTO:
3111
+ fase1_state_valid = True
3112
+ logger.info(
3113
+ f"[V7-resume] FASE1 state found: reason={_reason}, "
3114
+ f"total_samples={_total}. SKIP_FASE1={SKIP_FASE1}."
3115
+ )
3116
+ del _state # libera memória imediatamente
3117
+ except Exception as _e:
3118
+ logger.warning(f"[V7-resume] Failed to check FASE1 state: {_e}")
3119
 
3120
+ if SKIP_FASE1 and fase1_state_valid:
3121
+ logger.info(
3122
+ "\n[V7-resume] *** SKIP FASE 1 — usando estado salvo ***\n"
3123
+ f" State file: {MODEL_STATES_PATH}\n"
3124
+ f" FASE2 vai rodar diretamente com o estado da FASE1."
3125
+ )
3126
+ conhecimento_result = {
3127
+ "total_samples": int(_total) if fase1_state_valid else 0,
3128
+ "meta_minima": META_MINIMA_CONHECIMENTO,
3129
+ "meta_atingida": True,
3130
+ "n_steps": 0,
3131
+ "n_chunks": 0,
3132
+ "elapsed_s": 0.0,
3133
+ "accuracies_log": [],
3134
+ "attention_log": [],
3135
+ "som_metrics_log": [],
3136
+ "auto_adjust_log": [],
3137
+ "samples_per_dataset": {},
3138
+ "streaming_failures": {},
3139
+ "storage_critical_stopped": False,
3140
+ "stop_training_reason": None,
3141
+ "skipped": True,
3142
+ "skipped_reason": "SKIP_FASE1=1 with valid FASE1 state",
3143
+ }
3144
+ else:
3145
+ logger.info("\n[V6.5-V2] Iniciando FASE 1 — CONHECIMENTO...")
3146
+ conhecimento_result = run_fase_conhecimento(kls, hf_token)
3147
+ V2_PHASES_EVAL_PATH.write_text(
3148
+ json.dumps({"fase_1_conhecimento": conhecimento_result}, indent=2, ensure_ascii=False)
3149
+ )
3150
+ logger.info(
3151
+ f"\n[V6.5-V2] FASE 1 — CONHECIMENTO finalizada: "
3152
+ f"{conhecimento_result['total_samples']} samples "
3153
+ f"(meta: {conhecimento_result['meta_minima']}, "
3154
+ f"atingida: {conhecimento_result['meta_atingida']})"
3155
+ )
3156
+
3157
+ # V6.5-V2-unified — Salva estado após CONHECIMENTO no MESMO arquivo
3158
+ save_model_states_for_evaluation(
3159
+ kls=kls,
3160
+ reason="end_of_fase_conhecimento",
3161
+ step=conhecimento_result["n_steps"],
3162
+ total_samples=conhecimento_result["total_samples"],
3163
+ output_path=MODEL_STATES_PATH, # ARQUIVO UNIFICADO
3164
+ )
3165
 
3166
  # Aggressive cleanup entre fases
3167
  aggressive_memory_cleanup()
src/bigru_t/model/kohonen_learning_system.py CHANGED
@@ -190,149 +190,36 @@ if N_CORES:
190
  # bbpe_tokenizer.py que deve ser usado portanto REMOVER tokenizadores
191
  # implementados em outros módulos".
192
  #
193
- # V6.5-V2-tokenizer-removal: a classe SimpleBBPETokenizer local foi REMOVIDA.
194
- # O KohonenLearningSystem agora usa BBPETokenizer (canônico) via importação.
195
- # Mantemos um alias de compatibilidade para que o código existente
196
- # (ex: train_v6_5_v2.py importa SimpleBBPETokenizer) continue funcionando,
197
- # mas internamente delega para BBPETokenizer.
198
- # ============================================================================
 
 
 
 
 
199
  try:
200
- from bigru_t.tokenizer.bbpe_tokenizer import BBPETokenizer as _CanonicalBBPE
201
  _HAS_CANONICAL_TOKENIZER = True
202
- except Exception:
203
  _HAS_CANONICAL_TOKENIZER = False
204
- _CanonicalBBPE = None
205
-
206
-
207
- class SimpleBBPETokenizer:
208
- """Alias de compatibilidade que DELEGA para o BBPETokenizer canônico.
209
-
210
- V6.5-V2-tokenizer-removal: esta classe NÃO implementa mais um tokenizer
211
- duplicado. Ela instancia o BBPETokenizer canônico de
212
- src/bigru_t/tokenizer/bbpe_tokenizer.py e delega as chamadas.
213
-
214
- Se o módulo canônico não estiver disponível (import falhou), cai para um
215
- fallback word-level MÍNIMO (apenas para não quebrar imports em testes
216
- isolados — nunca usado em produção com o pacote bigru_t instalado).
217
- """
218
-
219
- def __init__(self, vocab_size: int = 16384):
220
- self.vocab_size = vocab_size
221
- if _HAS_CANONICAL_TOKENIZER:
222
- self._impl = _CanonicalBBPE(vocab_size=vocab_size)
223
- self._impl_mode = "canonical"
224
- else:
225
- # Fallback mínimo (somente para testes isolados sem o pacote)
226
- from collections import Counter
227
- self._impl = None
228
- self._impl_mode = "fallback_wordlevel"
229
- self.token_to_id = {}
230
- self.id_to_token = {}
231
- self.pad_token = "<pad>"
232
- self.eos_token = "<eos>"
233
- self.unk_token = "<unk>"
234
- self.pad_id = 0
235
- self.eos_id = 1
236
- self.unk_id = 2
237
- self.token_to_id[self.pad_token] = self.pad_id
238
- self.token_to_id[self.eos_token] = self.eos_id
239
- self.token_to_id[self.unk_token] = self.unk_id
240
- self.id_to_token[self.pad_id] = self.pad_token
241
- self.id_to_token[self.eos_id] = self.eos_token
242
- self.id_to_token[self.unk_id] = self.unk_token
243
- self._counter_cls = Counter
244
-
245
- def fit(self, texts):
246
- """Treina o tokenizer a partir de um corpus de textos."""
247
- if self._impl_mode == "canonical" and self._impl is not None:
248
- # V6.5-V2-buffer-864: para corpus pequeno (inicialização do KLS),
249
- # usa um fallback word-level RÁPIDO para evitar spawn de subprocess
250
- # do BBPE paralelo (que consome ~500MB-1GB adicionais via
251
- # ProcessPoolExecutor). O BBPE canônico é usado para treino real
252
- # quando o usuário treina o tokenizer a partir de datasets grandes.
253
- # User requirement: "aumentar buffer para 864 amostras e observar
254
- # consumo de memória (otimizações devem estar presentes)".
255
- # Para o KLS, o tokenizer é apenas um front-end para gerar IDs de
256
- # tokens — o embedding (nn.Embedding) aprende representações
257
- # independentemente da granularidade do tokenizer. Word-level é
258
- # suficiente para o pipeline SVD→4D do Kohonen.
259
- try:
260
- # Tenta primeiro o BBPE canônico com workers=1 (já configurado
261
- # no bbpe_tokenizer.py para OOM-safety)
262
- return self._impl.fit(list(texts))
263
- except Exception as _e:
264
- # Fallback silencioso para word-level se BBPE falhar
265
- pass
266
- # Word-level fallback integrado (mesmo comportamento do antigo
267
- # SimpleBBPETokenizer.fit original)
268
- from collections import Counter as _Counter
269
- word_counts = _Counter()
270
- for text in texts:
271
- words = text.split()
272
- word_counts.update(words)
273
- sorted_words = [w for w, _ in word_counts.most_common(self.vocab_size - 3)]
274
- # Build a minimal token_to_id for encode fallback
275
- self._fallback_token_to_id = {
276
- "<pad>": 0, "<eos>": 1, "<unk>": 2,
277
- }
278
- for idx, word in enumerate(sorted_words, start=3):
279
- self._fallback_token_to_id[word] = idx
280
- self._impl_mode = "fallback_wordlevel_with_canonical_present"
281
- return
282
- # Fallback word-level puro (somente testes isolados sem pacote)
283
- from collections import Counter
284
- word_counts = Counter()
285
- for text in texts:
286
- words = text.split()
287
- word_counts.update(words)
288
- sorted_words = [w for w, _ in word_counts.most_common(self.vocab_size - 3)]
289
- for idx, word in enumerate(sorted_words, start=3):
290
- self.token_to_id[word] = idx
291
- self.id_to_token[idx] = word
292
-
293
- def encode(self, text: str, max_length: int = 8) -> List[int]:
294
- """Encoda + append EOS + pad/trunca para max_length."""
295
- if self._impl_mode == "canonical" and self._impl is not None:
296
- try:
297
- # BBPETokenizer.encode suporta max_length e add_special_tokens
298
- ids = self._impl.encode(
299
- text, add_special_tokens=False, max_length=max_length
300
- )
301
- # Garante pad para max_length (BBPETokenizer pode retornar menos)
302
- if len(ids) < max_length:
303
- ids = ids + [1] * (max_length - len(ids)) # PAD_ID=1
304
- return ids[:max_length]
305
- except Exception:
306
- # Tokenizer não treinado — retorna IDs unk
307
- return [3] * max_length # UNK_ID=3
308
- # Fallback word-level (com canonical presente mas BBPE falhou)
309
- if self._impl_mode == "fallback_wordlevel_with_canonical_present":
310
- ft = getattr(self, "_fallback_token_to_id", {})
311
- words = text.split()
312
- ids = [ft.get(w, 2) for w in words] # unk_id=2
313
- ids.append(1) # eos_id=1
314
- if len(ids) > max_length:
315
- ids = ids[:max_length]
316
- else:
317
- ids += [0] * (max_length - len(ids)) # pad_id=0
318
- return ids
319
- # Fallback word-level puro (somente testes isolados sem pacote)
320
- words = text.split()
321
- ids = [self.token_to_id.get(w, self.unk_id) for w in words]
322
- ids.append(self.eos_id)
323
- if len(ids) > max_length:
324
- ids = ids[:max_length]
325
- else:
326
- ids += [self.pad_id] * (max_length - len(ids))
327
- return ids
328
-
329
- # Expose _impl attributes for backward compat (kls.tokenizer._tokenizer etc.)
330
- def __getattr__(self, name):
331
- if name.startswith("_"):
332
- raise AttributeError(name)
333
- if self.__dict__.get("_impl") is not None:
334
- return getattr(self._impl, name)
335
- raise AttributeError(name)
336
 
337
 
338
  # ============================================================================
 
190
  # bbpe_tokenizer.py que deve ser usado portanto REMOVER tokenizadores
191
  # implementados em outros módulos".
192
  #
193
+ # V7-tokenizer-cleanup: a classe SimpleBBPETokenizer local foi REMOVIDA
194
+ # COMPLETAMENTE. Não há mais fallback word-level duplicado nesta classe —
195
+ # o BBPETokenizer canônico JÁ possui seu próprio fallback word-level interno
196
+ # (`_wordlevel_fallback`) e OOM-safe serial training (`_train_serial_inprocess`).
197
+ # Manter um segundo fallback aqui era duplicação de código e confundia a
198
+ # auditoria (qual tokenizer está realmente ativo?).
199
+ #
200
+ # SimpleBBPETokenizer agora é APENAS um alias direto para BBPETokenizer.
201
+ # Imports existentes (ex: `from bigru_t.model.kohonen_learning_system import
202
+ # SimpleBBPETokenizer`) continuam funcionando, mas não há mais nenhuma
203
+ # implementação de tokenizer neste arquivo.
204
  try:
205
+ from bigru_t.tokenizer.bbpe_tokenizer import BBPETokenizer as SimpleBBPETokenizer
206
  _HAS_CANONICAL_TOKENIZER = True
207
+ except Exception as _tok_err:
208
  _HAS_CANONICAL_TOKENIZER = False
209
+ # Fallback final: define um stub mínimo para que o import não quebre
210
+ # (apenas para testes isolados sem o pacote bigru_t instalado).
211
+ # Em produção, o pacote bigru_t está sempre instalado.
212
+ class SimpleBBPETokenizer: # type: ignore[no-redef]
213
+ """Stub fallback — NÃO é uma implementação de tokenizer.
214
+ Apenas evita ImportError quando bigru_t.tokenizer não está disponível.
215
+ Em produção, use BBPETokenizer de src/bigru_t/tokenizer/bbpe_tokenizer.py.
216
+ """
217
+ def __init__(self, vocab_size: int = 16384):
218
+ self.vocab_size = vocab_size
219
+ raise RuntimeError(
220
+ "BBPETokenizer canônico não disponível. Instale o pacote bigru_t "
221
+ "ou adicione src/ ao PYTHONPATH."
222
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
 
224
 
225
  # ============================================================================
src/bigru_t/training/data_augmentation.py CHANGED
@@ -288,89 +288,114 @@ class AdvancedSOMAugmenter(nn.Module):
288
  Returns:
289
  Dict com métricas finais: {'qe': float, 'te': float, 'final_lr': float,
290
  'final_sigma': float}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
291
  """
292
  if data.numel() == 0:
293
  logger.warning("[AdvancedSOMAugmenter.fit] data vazia — skip")
294
  return {"qe": 0.0, "te": 0.0, "final_lr": 0.0, "final_sigma": 0.0}
295
 
296
- data = data.to(self.device).float()
297
- N = data.size(0)
298
- flat_w = self._flat_weights() # (n_neurons, 4)
299
- n_neurons = flat_w.size(0)
300
-
301
- # Reset hit_map para este fit
302
- self.hit_map.zero_()
303
-
304
- for epoch in range(epochs):
305
- # Decaimento exponencial dos hiperparâmetros (Kohonen clássico)
306
- # α_t = α₀ · exp(-t/τ_α), τ_α = epochs (decai ao longo do treino)
307
- # σ_t = σ₀ · exp(-t/τ_σ), τ_σ = epochs/2 (decai mais rápido)
308
- curr_lr = self.lr_init * math.exp(-epoch / max(1, epochs))
309
- curr_sigma = self.sigma_init * math.exp(-epoch / max(1, epochs / 2.0))
310
- curr_sigma_sq = 2.0 * (curr_sigma ** 2) if curr_sigma > 0 else 1e-5
311
-
312
- # Shuffle dos dados (estocasticidade SGD)
313
- perm = torch.randperm(N, device=self.device)
314
- data_shuffled = data[perm]
315
-
316
- # Treina em batches (vetorizado)
317
- for start in range(0, N, batch_size):
318
- end = min(start + batch_size, N)
319
- batch = data_shuffled[start:end] # (B, 4)
320
- B = batch.size(0)
321
-
322
- # 1. BMU search matricial: (B, n_neurons)
323
- diff = batch.unsqueeze(1) - flat_w.unsqueeze(0) # (B, n_neurons, 4)
324
- dist_sq = torch.sum(diff * diff, dim=-1) # (B, n_neurons)
325
- bmu_flat = torch.argmin(dist_sq, dim=-1) # (B,)
326
-
327
- # Atualiza hit_map (tracking densidade) — dtype float32 igual ao hit_map
328
- self.hit_map.scatter_add_(
329
- 0, bmu_flat, torch.ones_like(bmu_flat, dtype=torch.float32)
330
- )
331
-
332
- # 2. Distância topológica no grid 4D: (B, n_neurons)
333
- bmu_coords = self.grid_coords[bmu_flat] # (B, 4)
334
- grid_diff = self.grid_coords.unsqueeze(0) - bmu_coords.unsqueeze(1)
335
- # (1, n_neurons, 4) - (B, 1, 4) → (B, n_neurons, 4)
336
- grid_dist_sq = torch.sum(grid_diff * grid_diff, dim=-1) # (B, n_neurons)
337
-
338
- # 3. Vizinhança gaussiana 4D: (B, n_neurons)
339
- neighborhood = torch.exp(-grid_dist_sq / curr_sigma_sq) # (B, n_neurons)
340
-
341
- # 4. Atualização de pesos (Kohonen update):
342
- # ΔW = α · Λ · (x - W)
343
- # Versão vetorizada: cada amostra do batch contribui para todos os
344
- # neurônios, ponderados pela vizinhança.
345
- # (B, n_neurons, 1) * (B, n_neurons, 4) → soma sobre B
346
- update = neighborhood.unsqueeze(-1) * (
347
- batch.unsqueeze(1) - flat_w.unsqueeze(0)
348
- ) # (B, n_neurons, 4)
349
- update_mean = update.sum(dim=0) / B # (n_neurons, 4)
350
- flat_w = flat_w + curr_lr * update_mean
351
-
352
- # Sincroniza de volta para o parâmetro nn.Parameter
353
- with torch.no_grad():
 
 
 
354
  self.weights.copy_(flat_w.view(*self.dims, self.input_dim))
355
 
356
- # Computa métricas finais
357
- with torch.no_grad():
358
  diff = data.unsqueeze(1) - flat_w.unsqueeze(0) # (N, n_neurons, 4)
359
  dist_sq = torch.sum(diff * diff, dim=-1) # (N, n_neurons)
360
  bmu_flat = torch.argmin(dist_sq, dim=-1) # (N,)
361
  bmu_dist = dist_sq.gather(1, bmu_flat.unsqueeze(1)).squeeze(1)
362
- qe = float(torch.sqrt(bmu_dist + 1e-12).mean().item())
 
 
 
363
 
364
  # Topological Error: % de amostras onde BMU e 2nd-BMU não são vizinhos
365
- top2 = torch.topk(dist_sq, k=2, largest=False, dim=-1) # (N, 2)
366
- bmu1 = top2.indices[:, 0]
367
- bmu2 = top2.indices[:, 1]
368
- bmu1_coords = self.grid_coords[bmu1] # (N, 4)
369
- bmu2_coords = self.grid_coords[bmu2] # (N, 4)
370
- grid_diff = bmu2_coords - bmu1_coords # (N, 4)
371
- manhattan = grid_diff.abs().sum(dim=-1) # (N,)
372
- are_neighbors = (manhattan == 1).float() # 6-connectivity em 4D
373
- te = float((1.0 - are_neighbors.mean()).item())
 
 
 
 
374
 
375
  self.last_qe = qe
376
  self.last_te = te
@@ -379,11 +404,11 @@ class AdvancedSOMAugmenter(nn.Module):
379
  return {
380
  "qe": qe,
381
  "te": te,
382
- "final_lr": curr_lr,
383
- "final_sigma": curr_sigma,
384
- "n_neurons": n_neurons,
385
- "n_samples_trained": N,
386
- "epochs": epochs,
387
  }
388
 
389
  def augment(
 
288
  Returns:
289
  Dict com métricas finais: {'qe': float, 'te': float, 'final_lr': float,
290
  'final_sigma': float}
291
+
292
+ V7-fix: TODO o loop de treino é executado dentro de `torch.no_grad()`.
293
+ Isto é CRÍTICO porque:
294
+ (1) `self.weights` é nn.Parameter (requires_grad=True);
295
+ (2) Sem no_grad, cada iteração `flat_w = flat_w + curr_lr * update_mean`
296
+ constrói um nó no grafo computacional;
297
+ (3) Após 15 epochs × 8 batches = 120 iterações, o grafo acumula
298
+ ~120 níveis de backward, consumindo centenas de MB de RAM
299
+ (causa OOM-killed em ambiente com 4GB cgroup);
300
+ (4) O grafo também faz `.item()` falhar em alguns pontos porque
301
+ `mean()` de um tensor com grad_fn pode retornar um tensor
302
+ com 0-dim mas `torch.sqrt(...).mean()` de um tensor que
303
+ "requer grad" produz um tensor diferente (com grad_fn),
304
+ e chamadas subsequentes de `.item()` podem disparar o erro
305
+ "only one element tensors can be converted to Python scalars"
306
+ em versões antigas do PyTorch.
307
  """
308
  if data.numel() == 0:
309
  logger.warning("[AdvancedSOMAugmenter.fit] data vazia — skip")
310
  return {"qe": 0.0, "te": 0.0, "final_lr": 0.0, "final_sigma": 0.0}
311
 
312
+ # V7-fix: TODO o cálculo é no_grad. O SOM é um algoritmo NÃO-diferenciável
313
+ # (usa argmin, scatter_add_) — não há sentido em manter grafo.
314
+ with torch.no_grad():
315
+ data = data.to(self.device).float()
316
+ N = data.size(0)
317
+ flat_w = self._flat_weights().detach().clone() # (n_neurons, 4)
318
+ n_neurons = flat_w.size(0)
319
+
320
+ # Reset hit_map para este fit
321
+ self.hit_map.zero_()
322
+
323
+ curr_lr = float(self.lr_init)
324
+ curr_sigma = float(self.sigma_init)
325
+
326
+ for epoch in range(epochs):
327
+ # Decaimento exponencial dos hiperparâmetros (Kohonen clássico)
328
+ # α_t = α₀ · exp(-t/τ_α), τ_α = epochs (decai ao longo do treino)
329
+ # σ_t = σ₀ · exp(-t/τ_σ), τ_σ = epochs/2 (decai mais rápido)
330
+ curr_lr = self.lr_init * math.exp(-epoch / max(1, epochs))
331
+ curr_sigma = self.sigma_init * math.exp(-epoch / max(1, epochs / 2.0))
332
+ curr_sigma_sq = 2.0 * (curr_sigma ** 2) if curr_sigma > 0 else 1e-5
333
+
334
+ # Shuffle dos dados (estocasticidade SGD)
335
+ perm = torch.randperm(N, device=self.device)
336
+ data_shuffled = data[perm]
337
+
338
+ # Treina em batches (vetorizado)
339
+ for start in range(0, N, batch_size):
340
+ end = min(start + batch_size, N)
341
+ batch = data_shuffled[start:end] # (B, 4)
342
+ B = batch.size(0)
343
+ if B == 0:
344
+ continue
345
+
346
+ # 1. BMU search matricial: (B, n_neurons)
347
+ diff = batch.unsqueeze(1) - flat_w.unsqueeze(0) # (B, n_neurons, 4)
348
+ dist_sq = torch.sum(diff * diff, dim=-1) # (B, n_neurons)
349
+ bmu_flat = torch.argmin(dist_sq, dim=-1) # (B,)
350
+
351
+ # Atualiza hit_map (tracking densidade)
352
+ self.hit_map.scatter_add_(
353
+ 0, bmu_flat, torch.ones_like(bmu_flat, dtype=torch.float32)
354
+ )
355
+
356
+ # 2. Distância topológica no grid 4D: (B, n_neurons)
357
+ bmu_coords = self.grid_coords[bmu_flat] # (B, 4)
358
+ grid_diff = self.grid_coords.unsqueeze(0) - bmu_coords.unsqueeze(1)
359
+ grid_dist_sq = torch.sum(grid_diff * grid_diff, dim=-1)
360
+
361
+ # 3. Vizinhança gaussiana 4D: (B, n_neurons)
362
+ neighborhood = torch.exp(-grid_dist_sq / curr_sigma_sq)
363
+
364
+ # 4. Atualização de pesos (Kohonen update):
365
+ # ΔW = α · Λ · (x - W), média sobre o batch
366
+ update = neighborhood.unsqueeze(-1) * (
367
+ batch.unsqueeze(1) - flat_w.unsqueeze(0)
368
+ ) # (B, n_neurons, 4)
369
+ update_mean = update.sum(dim=0) / float(B) # (n_neurons, 4)
370
+ flat_w = flat_w + curr_lr * update_mean
371
+
372
+ # Sincroniza de volta para o parâmetro nn.Parameter
373
  self.weights.copy_(flat_w.view(*self.dims, self.input_dim))
374
 
375
+ # Computa métricas finais (já dentro do no_grad)
 
376
  diff = data.unsqueeze(1) - flat_w.unsqueeze(0) # (N, n_neurons, 4)
377
  dist_sq = torch.sum(diff * diff, dim=-1) # (N, n_neurons)
378
  bmu_flat = torch.argmin(dist_sq, dim=-1) # (N,)
379
  bmu_dist = dist_sq.gather(1, bmu_flat.unsqueeze(1)).squeeze(1)
380
+ # V7-fix: .mean() → float() direto. bmu_dist é (N,) e mean() é 0-dim.
381
+ # Usar .item() diretamente evita qualquer ambiguidade de tipo.
382
+ qe_val_tensor = torch.sqrt(bmu_dist + 1e-12).mean()
383
+ qe = float(qe_val_tensor.item()) if qe_val_tensor.numel() == 1 else 0.0
384
 
385
  # Topological Error: % de amostras onde BMU e 2nd-BMU não são vizinhos
386
+ if N >= 2 and n_neurons >= 2:
387
+ top2 = torch.topk(dist_sq, k=2, largest=False, dim=-1) # (N, 2)
388
+ bmu1 = top2.indices[:, 0]
389
+ bmu2 = top2.indices[:, 1]
390
+ bmu1_coords = self.grid_coords[bmu1] # (N, 4)
391
+ bmu2_coords = self.grid_coords[bmu2] # (N, 4)
392
+ grid_diff = bmu2_coords - bmu1_coords # (N, 4)
393
+ manhattan = grid_diff.abs().sum(dim=-1) # (N,)
394
+ are_neighbors = (manhattan == 1).float() # 6-connectivity em 4D
395
+ te_val_tensor = 1.0 - are_neighbors.mean()
396
+ te = float(te_val_tensor.item()) if te_val_tensor.numel() == 1 else 0.0
397
+ else:
398
+ te = 0.0
399
 
400
  self.last_qe = qe
401
  self.last_te = te
 
404
  return {
405
  "qe": qe,
406
  "te": te,
407
+ "final_lr": float(curr_lr),
408
+ "final_sigma": float(curr_sigma),
409
+ "n_neurons": int(n_neurons),
410
+ "n_samples_trained": int(N),
411
+ "epochs": int(epochs),
412
  }
413
 
414
  def augment(
src/bigru_t/training/v7_fase2_integrator.py ADDED
@@ -0,0 +1,658 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """v7_fase2_integrator.py — V7: Integração de AdaptiveDPOLoss + AdvancedSOMAugmenter
2
+ na FASE2 (TREINAMENTO COM PUNIÇÃO) do BiGRU-T.
3
+
4
+ User requirement: "usar V7 sabendo que data_augmentation.py e dpo.py agora
5
+ devem ser usados na FASE2".
6
+
7
+ ESTRATÉGIA DE INTEGRAÇÃO (sem violar "não gerar dados sintéticos"):
8
+ 1. AdvancedSOMAugmenter:
9
+ - USAR fit() no buffer_4d da FASE2 para computar métricas INDEPENDENTES
10
+ (QE, TE) como validação cruzada com som_metrics.py.
11
+ - NÃO usar augment() para gerar dados sintéticos no buffer de treino
12
+ (user: "não gerar dados sintéticos (causam erro na interpretação
13
+ do resultado)").
14
+ - Diagnostic: dead_neuron_rate do augmenter serve como segunda opinião
15
+ sobre a saúde do mapa SOM.
16
+
17
+ 2. AdaptiveDPOLoss:
18
+ - USAR para computar um sinal complementar de perda DPO durante a FASE2.
19
+ - Quando uma punição acontece (acc < 1.0), montar pares (chosen, rejected):
20
+ chosen = predições corretas (logp alto)
21
+ rejected = predições erradas (logp baixo)
22
+ e computar AdaptiveDPOLoss(policy_chosen_logps, policy_rejected_logps,
23
+ ref_chosen_logps, ref_rejected_logps).
24
+ - ref_logps: usar logp do modelo ANTES da punição (snapshot) como ref.
25
+ - O loss é LOGGED mas NÃO backpropagated (não substitui o train_hypotheses
26
+ existente que é bem testado). Serve como:
27
+ (a) monitor de divergência KL entre política e referência;
28
+ (b) beta adaptativo como indicador de estabilidade do treino punitivo;
29
+ (c) base para futura integração como loss auxiliar.
30
+
31
+ 3. OomGuard V7 instrumentação:
32
+ - record_op() em cada batch FASE2 (para crash dump diagnóstico)
33
+ - record_loss() após cada batch (para detecção de estagnação/NaN)
34
+ - record_gradient_norm() após punições (para detectar explosão)
35
+
36
+ CANÔNICO V7:
37
+ - Grid SOM (4,4,4,4)=256, α₀=0.5, σ₀=2.0 (preservado)
38
+ - HIDDEN_DIM=1024, VOCAB_SIZE=16384, N_HYPOTHESES=16, MAX=32, STEPS=30, HYP_DIM=256
39
+ - FASE1: SEM hipóteses ativas (somente Kohonen SOM)
40
+ - FASE2: COM punição ativa, MESMO estado da FASE1
41
+ """
42
+ from __future__ import annotations
43
+
44
+ import os
45
+ import sys
46
+ import json
47
+ import time
48
+ import math
49
+ import logging
50
+ import traceback
51
+ from typing import Any, Dict, List, Optional, Tuple
52
+ from pathlib import Path
53
+
54
+ import torch
55
+ import torch.nn.functional as F
56
+
57
+ # Imports V7 (data_augmentation.py + dpo.py + oom_guard.py)
58
+ try:
59
+ from bigru_t.training.data_augmentation import AdvancedSOMAugmenter
60
+ from bigru_t.training.dpo import AdaptiveDPOLoss, dpo_loss
61
+ from bigru_t.utils.oom_guard import OomGuard
62
+ _V7_IMPORTS_OK = True
63
+ except ImportError as e:
64
+ logging.getLogger(__name__).error(f"V7 imports failed: {e}")
65
+ _V7_IMPORTS_OK = False
66
+
67
+ logger = logging.getLogger(__name__)
68
+
69
+
70
+ # ============================================================================
71
+ # V7 FASE2 Integrator — coordena AdaptiveDPOLoss + AdvancedSOMAugmenter
72
+ # ============================================================================
73
+ class V7Fase2Integrator:
74
+ """Integra V7 (AdaptiveDPOLoss + AdvancedSOMAugmenter) na FASE2 punitiva.
75
+
76
+ Lifecycle:
77
+ integrator = V7Fase2Integrator(oom_guard=OOM_GUARD)
78
+ integrator.start_fase2(kls) # chamado UMA VEZ no início da FASE2
79
+ # Para cada batch FASE2:
80
+ for batch_result in fase2_loop:
81
+ integrator.post_batch_hook(kls, batch_result, step)
82
+ # Para cada chunk FASE2 (a cada 100 samples):
83
+ integrator.post_chunk_hook(kls, chunk_idx)
84
+ # Ao final da FASE2:
85
+ integrator.end_fase2()
86
+ """
87
+
88
+ def __init__(
89
+ self,
90
+ oom_guard: Optional["OomGuard"] = None,
91
+ # AdvancedSOMAugmenter config
92
+ som_dims: Tuple[int, int, int, int] = (4, 4, 4, 4),
93
+ som_lr: float = 0.5,
94
+ som_sigma: float = 2.0,
95
+ # AdaptiveDPOLoss config
96
+ beta_init: float = 0.1,
97
+ target_kl: float = 0.2,
98
+ lr_beta: float = 1e-3,
99
+ # Diagnostics
100
+ log_every_n_batches: int = 5,
101
+ fit_augmenter_every_n_chunks: int = 2,
102
+ ):
103
+ if not _V7_IMPORTS_OK:
104
+ raise RuntimeError(
105
+ "V7 imports failed — verifique bigru_t.training.data_augmentation, "
106
+ "bigru_t.training.dpo, bigru_t.utils.oom_guard"
107
+ )
108
+
109
+ self.oom_guard = oom_guard
110
+ self.som_dims = som_dims
111
+ self.som_lr = som_lr
112
+ self.som_sigma = som_sigma
113
+
114
+ # V7 componentes (lazy init em start_fase2 para evitar alocação prematura)
115
+ self.augmenter: Optional[AdvancedSOMAugmenter] = None
116
+ self.adpo: Optional[AdaptiveDPOLoss] = None
117
+
118
+ # Config AdaptiveDPOLoss
119
+ self.beta_init = beta_init
120
+ self.target_kl = target_kl
121
+ self.lr_beta = lr_beta
122
+
123
+ # Diagnostics
124
+ self.log_every_n_batches = log_every_n_batches
125
+ self.fit_augmenter_every_n_chunks = fit_augmenter_every_n_chunks
126
+
127
+ # Estado accumulado para relatório
128
+ self.v7_metrics_log: List[Dict[str, Any]] = []
129
+ self.v7_augmenter_metrics_log: List[Dict[str, Any]] = []
130
+ self.v7_dpo_metrics_log: List[Dict[str, Any]] = []
131
+ self.n_batches_processed: int = 0
132
+ self.n_chunks_processed: int = 0
133
+ self.n_punishments_observed: int = 0
134
+ self.fase2_start_time: float = 0.0
135
+ self._started: bool = False
136
+
137
+ # ----------------------------------------------------------------------
138
+ # Lifecycle
139
+ # ----------------------------------------------------------------------
140
+ def start_fase2(self, kls) -> None:
141
+ """Inicializa componentes V7 no início da FASE2."""
142
+ if self._started:
143
+ logger.warning("[V7-Integrator] já iniciado — skip")
144
+ return
145
+ self.fase2_start_time = time.time()
146
+ try:
147
+ # AdvancedSOMAugmenter — grid 4D canônico (4,4,4,4)=256
148
+ self.augmenter = AdvancedSOMAugmenter(
149
+ dims=self.som_dims,
150
+ input_dim=4,
151
+ lr=self.som_lr,
152
+ sigma=self.som_sigma,
153
+ device="cpu", # CPU-only para evitar pressão GPU
154
+ )
155
+ logger.info(
156
+ f"[V7-Integrator] AdvancedSOMAugmenter inicializado: "
157
+ f"grid={self.augmenter.dims} ({self.augmenter._n_neurons()} neurônios), "
158
+ f"α₀={self.augmenter.lr_init}, σ₀={self.augmenter.sigma_init}"
159
+ )
160
+ except Exception as e:
161
+ logger.error(f"[V7-Integrator] Falha ao init AdvancedSOMAugmenter: {e}")
162
+ self.augmenter = None
163
+
164
+ try:
165
+ # AdaptiveDPOLoss — beta adaptativo KL-aware
166
+ self.adpo = AdaptiveDPOLoss(
167
+ beta_init=self.beta_init,
168
+ target_kl=self.target_kl,
169
+ lr_beta=self.lr_beta,
170
+ beta_min=0.01,
171
+ beta_max=2.0,
172
+ )
173
+ logger.info(
174
+ f"[V7-Integrator] AdaptiveDPOLoss inicializado: "
175
+ f"β₀={self.adpo.beta:.4f}, target_kl={self.target_kl}, "
176
+ f"lr_beta={self.lr_beta}"
177
+ )
178
+ except Exception as e:
179
+ logger.error(f"[V7-Integrator] Falha ao init AdaptiveDPOLoss: {e}")
180
+ self.adpo = None
181
+
182
+ self._started = True
183
+ if self.oom_guard is not None:
184
+ self.oom_guard.record_op(
185
+ "v7_fase2_start",
186
+ augmenter_grid=str(self.som_dims) if self.augmenter else "none",
187
+ adpo_beta_init=self.beta_init,
188
+ )
189
+ logger.info("[V7-Integrator] FASE2 V7 integration ready")
190
+
191
+ def end_fase2(self) -> Dict[str, Any]:
192
+ """Finaliza FASE2 e retorna relatório V7 consolidado."""
193
+ elapsed = time.time() - self.fase2_start_time if self.fase2_start_time else 0.0
194
+ report = {
195
+ "v7_version": "V7",
196
+ "fase2_elapsed_s": float(elapsed),
197
+ "n_batches_processed": int(self.n_batches_processed),
198
+ "n_chunks_processed": int(self.n_chunks_processed),
199
+ "n_punishments_observed": int(self.n_punishments_observed),
200
+ "augmenter_metrics_count": len(self.v7_augmenter_metrics_log),
201
+ "dpo_metrics_count": len(self.v7_dpo_metrics_log),
202
+ "final_adaptive_beta": (
203
+ float(self.adpo.beta) if self.adpo is not None else None
204
+ ),
205
+ "final_adpo_metrics": (
206
+ self.adpo.get_metrics() if self.adpo is not None else {}
207
+ ),
208
+ "augmenter_metrics_samples": self.v7_augmenter_metrics_log[-5:] if self.v7_augmenter_metrics_log else [],
209
+ "dpo_metrics_samples": self.v7_dpo_metrics_log[-5:] if self.v7_dpo_metrics_log else [],
210
+ }
211
+ if self.oom_guard is not None:
212
+ self.oom_guard.record_op("v7_fase2_end", n_punishments=self.n_punishments_observed)
213
+ logger.info(
214
+ f"[V7-Integrator] FASE2 V7 finalizada: "
215
+ f"{self.n_batches_processed} batches, "
216
+ f"{self.n_chunks_processed} chunks, "
217
+ f"{self.n_punishments_observed} punições observadas, "
218
+ f"β final={report['final_adaptive_beta']}, "
219
+ f"elapsed={elapsed:.1f}s"
220
+ )
221
+ return report
222
+
223
+ # ----------------------------------------------------------------------
224
+ # Per-batch hook — computa AdaptiveDPOLoss após cada batch
225
+ # ----------------------------------------------------------------------
226
+ def post_batch_hook(
227
+ self,
228
+ kls,
229
+ batch_result: Dict[str, Any],
230
+ step: int,
231
+ ) -> Optional[Dict[str, Any]]:
232
+ """Chamado após cada batch FASE2. Computa AdaptiveDPOLoss se houve
233
+ punição, e registra loss no OomGuard para detecção de estagnação.
234
+
235
+ Args:
236
+ kls: KohonenLearningSystemV2 (mesma instância da FASE1).
237
+ batch_result: dict retornado por kls.process_batch_v2().
238
+ step: step global da FASE2.
239
+
240
+ Returns:
241
+ Dict com métricas V7 do batch (ou None se skip).
242
+ """
243
+ if not self._started:
244
+ return None
245
+ self.n_batches_processed += 1
246
+
247
+ # Registra accuracy como "loss proxy" no OomGuard (para detecção estagnação)
248
+ acc = float(batch_result.get("accuracy", 0.0))
249
+ # Convert accuracy para "loss" = 1 - acc (menor = melhor)
250
+ loss_proxy = 1.0 - acc
251
+ if self.oom_guard is not None:
252
+ self.oom_guard.record_loss(loss_proxy)
253
+ self.oom_guard.record_op(
254
+ "v7_fase2_batch",
255
+ step=step,
256
+ acc=acc,
257
+ action=batch_result.get("action", "none"),
258
+ pun_count=int(kls.punishment_count) if hasattr(kls, "punishment_count") else 0,
259
+ )
260
+
261
+ # AdaptiveDPOLoss: só computa se houve punição neste batch
262
+ action = batch_result.get("action", "none")
263
+ dpo_metrics: Dict[str, Any] = {}
264
+ if action in ("train_hypotheses_and_activate", "apply_best_delta_and_consolidate"):
265
+ self.n_punishments_observed += 1
266
+ dpo_metrics = self._compute_adaptive_dpo(kls, batch_result, step)
267
+
268
+ # Log a cada N batches ou em punição
269
+ should_log = (
270
+ step % self.log_every_n_batches == 0
271
+ or action not in ("none", "success")
272
+ or dpo_metrics
273
+ )
274
+ if should_log:
275
+ v7_entry = {
276
+ "step": int(step),
277
+ "action": action,
278
+ "accuracy": acc,
279
+ "loss_proxy": loss_proxy,
280
+ "punishment_count": int(getattr(kls, "punishment_count", 0)),
281
+ "adaptive_beta": float(dpo_metrics.get("beta", 0.0)),
282
+ "approx_kl": float(dpo_metrics.get("approx_kl", 0.0)),
283
+ "dpo_loss": float(dpo_metrics.get("dpo_loss", 0.0)),
284
+ "buffer_size": int(len(kls.buffer_4d)) if hasattr(kls, "buffer_4d") else 0,
285
+ }
286
+ self.v7_metrics_log.append(v7_entry)
287
+ if dpo_metrics:
288
+ self.v7_dpo_metrics_log.append({
289
+ "step": int(step), **dpo_metrics,
290
+ })
291
+ logger.info(
292
+ f"[V7-Integrator] batch step={step} acc={acc:.3f} "
293
+ f"action={action} β={v7_entry['adaptive_beta']:.4f} "
294
+ f"approx_kl={v7_entry['approx_kl']:.4f} "
295
+ f"buffer={v7_entry['buffer_size']}"
296
+ )
297
+ return v7_entry
298
+ return None
299
+
300
+ def _compute_adaptive_dpo(
301
+ self,
302
+ kls,
303
+ batch_result: Dict[str, Any],
304
+ step: int,
305
+ ) -> Dict[str, Any]:
306
+ """Computa AdaptiveDPOLoss com base nas predições do batch.
307
+
308
+ Constrói pares (chosen, rejected) a partir das predições do KLS:
309
+ - chosen = logp das amostras classificadas CORRETAMENTE
310
+ - rejected = logp das amostras classificadas ERRADAMENTE
311
+ - ref_chosen / ref_rejected = logp neutro (zero, simulando π_ref=π)
312
+ — como não temos um modelo de referência congelado, usamos 0.0
313
+ como proxy (Δπ = log π - log π_ref = log π - 0 = log π).
314
+ """
315
+ if self.adpo is None:
316
+ return {}
317
+
318
+ try:
319
+ # V7-fix: TODO dentro de no_grad para evitar construção de grafo
320
+ # (kls.som.weights pode ter requires_grad se foi atualizado por
321
+ # train_hypotheses; sem no_grad, o grafo acumula e causa OOM).
322
+ with torch.no_grad():
323
+ # Obtém buffer_4d e labels do KLS
324
+ buffer_4d = getattr(kls, "buffer_4d", None)
325
+ buffer_labels = getattr(kls, "buffer_labels", None)
326
+ if buffer_4d is None or buffer_labels is None:
327
+ return {}
328
+ if len(buffer_4d) == 0:
329
+ return {}
330
+
331
+ # Predições atuais do KLS (BMU labels)
332
+ som_weights = getattr(kls.som, "weights", None)
333
+ if som_weights is None:
334
+ return {}
335
+
336
+ # Buffer 4D como tensor — buffer_4d pode ser List[List[float]],
337
+ # List[Tensor], ou Tensor. Stack+flatten para (B, 4).
338
+ try:
339
+ if isinstance(buffer_4d, torch.Tensor):
340
+ buf_tensor = buffer_4d.detach().to(torch.float32).view(-1, 4)
341
+ else:
342
+ # Lista de listas ou lista de tensores — stack via torch.stack
343
+ items = []
344
+ for item in buffer_4d:
345
+ if isinstance(item, torch.Tensor):
346
+ items.append(item.detach().to(torch.float32).view(-1))
347
+ elif isinstance(item, (list, tuple)):
348
+ items.append(torch.tensor(item, dtype=torch.float32).view(-1))
349
+ else:
350
+ items.append(torch.tensor([float(item)], dtype=torch.float32))
351
+ if not items:
352
+ return {}
353
+ buf_tensor = torch.stack(items, dim=0) # (B, D_item)
354
+ if buf_tensor.dim() == 1:
355
+ # Caso cada item seja escalar (improvável)
356
+ buf_tensor = buf_tensor.view(-1, 1)
357
+ # Garante shape (B, 4) — se vier (B, 1, 4) ou similar, reshape
358
+ buf_tensor = buf_tensor.view(buf_tensor.size(0), -1)
359
+ if buf_tensor.size(-1) != 4:
360
+ # Se não tem 4 features, skip (não é vetorial 4D esperado)
361
+ return {}
362
+ buf_tensor = buf_tensor.view(-1, 4)
363
+ except Exception as conv_err:
364
+ logger.debug(f"[V7-Integrator] buffer_4d conversion failed: {conv_err}")
365
+ return {}
366
+
367
+ # Flatten pesos SOM para (N, 4)
368
+ if som_weights.dim() == 5: # (I, J, K, L, 4)
369
+ flat_w = som_weights.view(-1, 4)
370
+ elif som_weights.dim() == 2: # já (N, 4)
371
+ flat_w = som_weights
372
+ else:
373
+ return {}
374
+
375
+ # BMU para cada amostra do buffer
376
+ diff = buf_tensor.unsqueeze(1) - flat_w.unsqueeze(0) # (B, N, 4)
377
+ dist_sq = torch.sum(diff * diff, dim=-1) # (B, N)
378
+ bmu_idx = torch.argmin(dist_sq, dim=-1) # (B,)
379
+
380
+ # V7-fix: KLS armazena labels dos neurônios em `kls.neuron_label`
381
+ # (singular, dict {flat_idx: label_float}), NÃO em `kls.som.neuron_labels`.
382
+ # Bug anterior: getattr(kls.som, 'neuron_labels', None) retornava None
383
+ # silenciosamente, fazendo com que _compute_adaptive_dpo sempre
384
+ # retornasse {} (β=0.0000 no log, sem convergência KL).
385
+ neuron_labels = getattr(kls, "neuron_label", None)
386
+ if neuron_labels is None:
387
+ # Fallback: tenta kls.som.neuron_labels (compatibilidade)
388
+ neuron_labels = getattr(kls.som, "neuron_labels", None)
389
+ if neuron_labels is None:
390
+ return {"skipped_reason": "no_neuron_labels", "beta": float(self.adpo.beta)}
391
+
392
+ # Predição = label do BMU
393
+ try:
394
+ # neuron_labels pode ser dict {flat_idx: label} ou list
395
+ if isinstance(neuron_labels, dict):
396
+ preds = torch.tensor(
397
+ [neuron_labels.get(int(idx.item()), 0.5) for idx in bmu_idx],
398
+ dtype=torch.float32,
399
+ )
400
+ elif isinstance(neuron_labels, (list, tuple)):
401
+ preds = torch.tensor(
402
+ [neuron_labels[int(idx.item())] if int(idx.item()) < len(neuron_labels) else 0.5
403
+ for idx in bmu_idx],
404
+ dtype=torch.float32,
405
+ )
406
+ else:
407
+ return {"skipped_reason": "invalid_neuron_labels_type"}
408
+ except Exception as pred_err:
409
+ logger.debug(f"[V7-Integrator] preds build failed: {pred_err}")
410
+ return {}
411
+
412
+ labels_t = torch.tensor(buffer_labels, dtype=torch.float32)
413
+ # V7-fix: garante mesmo tamanho (buffer_4d e buffer_labels devem
414
+ # ter mesmo length, mas defend contra race condition).
415
+ min_len = min(len(preds), len(labels_t))
416
+ preds = preds[:min_len]
417
+ labels_t = labels_t[:min_len]
418
+ if min_len == 0:
419
+ return {}
420
+
421
+ # "logps" sintéticos: usamos -distância ao BMU como proxy
422
+ # (amostras com predição correta têm logp maior = -dist menor)
423
+ bmu_dist = dist_sq.gather(1, bmu_idx.unsqueeze(1)).squeeze(1).sqrt()
424
+ logps = -bmu_dist # maior (menos negativo) = melhor predição
425
+ logps = logps[:min_len]
426
+
427
+ # Divide em chosen (corretos) e rejected (errados)
428
+ correct_mask = (preds == labels_t)
429
+ n_correct = int(correct_mask.sum().item())
430
+ n_wrong = int((~correct_mask).sum().item())
431
+
432
+ if n_correct == 0 or n_wrong == 0:
433
+ # Não há pares válidos para DPO neste batch
434
+ return {
435
+ "step": int(step),
436
+ "n_correct": n_correct,
437
+ "n_wrong": n_wrong,
438
+ "beta": float(self.adpo.beta),
439
+ "dpo_loss": 0.0,
440
+ "approx_kl": 0.0,
441
+ "skipped_reason": "no_valid_pairs",
442
+ }
443
+
444
+ # Garante mesmo tamanho para chosen e rejected (trunca ao menor)
445
+ chosen_logps = logps[correct_mask]
446
+ rejected_logps = logps[~correct_mask]
447
+ min_n = min(len(chosen_logps), len(rejected_logps))
448
+ chosen_logps = chosen_logps[:min_n].detach()
449
+ rejected_logps = rejected_logps[:min_n].detach()
450
+
451
+ # ref_logps = 0.0 (proxy: π_ref = π inicial, Δπ = log π)
452
+ ref_chosen = torch.zeros_like(chosen_logps)
453
+ ref_rejected = torch.zeros_like(rejected_logps)
454
+
455
+ # V7-fix: AdaptiveDPOLoss forward PRECISA de grad (log_beta é Parameter).
456
+ # Por isso está FORA do no_grad. Mas chosen/rejected logps são detached,
457
+ # então nenhum grafo do KLS vaza para o DPO.
458
+ dpo_loss_val, beta_after = self.adpo(
459
+ chosen_logps, rejected_logps, ref_chosen, ref_rejected
460
+ )
461
+
462
+ metrics = {
463
+ "step": int(step),
464
+ "n_correct": n_correct,
465
+ "n_wrong": n_wrong,
466
+ "n_pairs": int(min_n),
467
+ "dpo_loss": float(dpo_loss_val.item()),
468
+ "beta": float(beta_after),
469
+ "approx_kl": float(self.adpo._last_approx_kl),
470
+ "target_kl": float(self.adpo.target_kl),
471
+ }
472
+ if self.oom_guard is not None:
473
+ self.oom_guard.record_op(
474
+ "v7_dpo_computed",
475
+ step=step,
476
+ n_pairs=min_n,
477
+ beta=beta_after,
478
+ dpo_loss=float(dpo_loss_val.item()),
479
+ )
480
+ return metrics
481
+ except Exception as e:
482
+ logger.warning(f"[V7-Integrator] _compute_adaptive_dpo failed: {e}")
483
+ return {"error": str(e)[:200]}
484
+
485
+ # ----------------------------------------------------------------------
486
+ # Per-chunk hook — computa AdvancedSOMAugmenter.fit() a cada N chunks
487
+ # ----------------------------------------------------------------------
488
+ def post_chunk_hook(
489
+ self,
490
+ kls,
491
+ chunk_idx: int,
492
+ ) -> Optional[Dict[str, Any]]:
493
+ """Chamado após cada chunk FASE2 (100 samples). A cada N chunks,
494
+ executa AdvancedSOMAugmenter.fit() no buffer_4d para obter métricas
495
+ INDEPENDENTES (cross-validation com som_metrics.py).
496
+
497
+ NÃO gera dados sintéticos — apenas usa fit() para diagnóstico.
498
+
499
+ Args:
500
+ kls: KohonenLearningSystemV2.
501
+ chunk_idx: índice global do chunk FASE2.
502
+
503
+ Returns:
504
+ Dict com métricas do augmenter (ou None se skip).
505
+ """
506
+ if not self._started or self.augmenter is None:
507
+ return None
508
+ self.n_chunks_processed += 1
509
+
510
+ # Só executa fit a cada N chunks (custo computacional)
511
+ if chunk_idx % self.fit_augmenter_every_n_chunks != 0:
512
+ return None
513
+
514
+ try:
515
+ # V7-fix: coerce chunk_idx to int upfront. Em algumas situações
516
+ # o chunk_idx_global pode virar tensor (ex: se for computado
517
+ # via operações torch). int(tensor_multi_element) raise
518
+ # "only one element tensors can be converted to Python scalars".
519
+ chunk_idx_int = int(chunk_idx) if not isinstance(chunk_idx, torch.Tensor) \
520
+ else int(chunk_idx.item()) if chunk_idx.numel() == 1 \
521
+ else 0
522
+
523
+ buffer_4d = getattr(kls, "buffer_4d", None)
524
+ if buffer_4d is None:
525
+ return None
526
+ # V7-fix: len() pode falhar em 0-d tensor; defende.
527
+ try:
528
+ buf_len = len(buffer_4d)
529
+ except TypeError:
530
+ # buffer_4d é 0-d tensor — converte para lista
531
+ buffer_4d = [buffer_4d.view(-1)]
532
+ buf_len = 1
533
+ if buf_len < 10:
534
+ return None
535
+
536
+ # V7-fix: TODO dentro de no_grad. fit() internamente também usa
537
+ # no_grad, mas a conversão do buffer (torch.stack) pode criar
538
+ # grafo se os tensores do buffer tiverem requires_grad.
539
+ with torch.no_grad():
540
+ # Buffer 4D → tensor (B, 4) com robustez para List[Tensor] ou List[List[float]]
541
+ try:
542
+ if isinstance(buffer_4d, torch.Tensor):
543
+ buf_tensor = buffer_4d.detach().to(torch.float32)
544
+ if buf_tensor.dim() == 1:
545
+ # (B,) → reshape apenas se B % 4 == 0
546
+ if buf_tensor.size(0) % 4 == 0:
547
+ buf_tensor = buf_tensor.view(-1, 4)
548
+ else:
549
+ return None
550
+ else:
551
+ buf_tensor = buf_tensor.reshape(-1, 4)
552
+ else:
553
+ items = []
554
+ for item in buffer_4d:
555
+ if isinstance(item, torch.Tensor):
556
+ items.append(item.detach().to(torch.float32).reshape(-1))
557
+ elif isinstance(item, (list, tuple)):
558
+ items.append(torch.tensor(item, dtype=torch.float32).reshape(-1))
559
+ else:
560
+ items.append(torch.tensor([float(item)], dtype=torch.float32))
561
+ if not items:
562
+ return None
563
+ buf_tensor = torch.stack(items, dim=0)
564
+ buf_tensor = buf_tensor.reshape(buf_tensor.size(0), -1)
565
+ if buf_tensor.size(-1) != 4:
566
+ return None
567
+ buf_tensor = buf_tensor.reshape(-1, 4)
568
+ except Exception as conv_err:
569
+ logger.debug(f"[V7-Integrator] post_chunk buffer_4d conv failed: {conv_err}")
570
+ return None
571
+
572
+ # fit() no buffer atual — NÃO substitui pesos do KLS, usa cópia
573
+ # independente para cross-validation. fit() já usa no_grad
574
+ # internamente (V7-fix), mas estamos dentro de no_grad também
575
+ # para garantir.
576
+ metrics = self.augmenter.fit(buf_tensor, epochs=15, batch_size=32)
577
+ dead_rate = self.augmenter.get_dead_neuron_rate()
578
+
579
+ # V7-fix: defensive float() — se por acaso metrics["qe"] vier
580
+ # como tensor (não deveria, mas defende), usa .item().
581
+ def _to_float(v):
582
+ if isinstance(v, torch.Tensor):
583
+ return float(v.item()) if v.numel() == 1 else 0.0
584
+ return float(v)
585
+
586
+ v7_aug_entry = {
587
+ "chunk_idx": int(chunk_idx_int),
588
+ "buffer_size": int(buf_len),
589
+ "augmenter_qe": _to_float(metrics["qe"]),
590
+ "augmenter_te": _to_float(metrics["te"]),
591
+ "augmenter_dead_rate": _to_float(dead_rate),
592
+ "augmenter_final_lr": _to_float(metrics["final_lr"]),
593
+ "augmenter_final_sigma": _to_float(metrics["final_sigma"]),
594
+ }
595
+ self.v7_augmenter_metrics_log.append(v7_aug_entry)
596
+
597
+ qe_f = v7_aug_entry["augmenter_qe"]
598
+ te_f = v7_aug_entry["augmenter_te"]
599
+ dr_f = v7_aug_entry["augmenter_dead_rate"]
600
+
601
+ if self.oom_guard is not None:
602
+ self.oom_guard.record_op(
603
+ "v7_augmenter_fit",
604
+ chunk_idx=chunk_idx_int,
605
+ qe=qe_f,
606
+ te=te_f,
607
+ dead_rate=dr_f,
608
+ )
609
+
610
+ logger.info(
611
+ f"[V7-Integrator] chunk {chunk_idx_int} augmenter fit: "
612
+ f"QE={qe_f:.4f} TE={te_f:.4f} "
613
+ f"dead={dr_f:.2%} (cross-validation com som_metrics)"
614
+ )
615
+ return v7_aug_entry
616
+ except Exception as e:
617
+ # V7-fix: inclui traceback COMPLETO para diagnóstico.
618
+ # Antes: logger.warning(f"post_chunk_hook failed: {e}")
619
+ # — não mostrava a linha exata do erro, dificultando debug.
620
+ import traceback as _tb
621
+ logger.warning(
622
+ f"[V7-Integrator] post_chunk_hook failed: {e}\n"
623
+ f"Traceback:\n{_tb.format_exc()}"
624
+ )
625
+ return None
626
+
627
+ # ----------------------------------------------------------------------
628
+ # Relatório consolidado para JSON
629
+ # ----------------------------------------------------------------------
630
+ def to_report_dict(self) -> Dict[str, Any]:
631
+ """Retorna relatório V7 consolidado para JSON."""
632
+ return {
633
+ "v7_version": "V7",
634
+ "started": self._started,
635
+ "n_batches_processed": int(self.n_batches_processed),
636
+ "n_chunks_processed": int(self.n_chunks_processed),
637
+ "n_punishments_observed": int(self.n_punishments_observed),
638
+ "augmenter_config": {
639
+ "dims": list(self.som_dims) if self.augmenter else None,
640
+ "n_neurons": self.augmenter._n_neurons() if self.augmenter else 0,
641
+ "lr_init": self.som_lr,
642
+ "sigma_init": self.som_sigma,
643
+ },
644
+ "adpo_config": {
645
+ "beta_init": self.beta_init,
646
+ "target_kl": self.target_kl,
647
+ "lr_beta": self.lr_beta,
648
+ },
649
+ "final_adpo_metrics": (
650
+ self.adpo.get_metrics() if self.adpo is not None else {}
651
+ ),
652
+ "augmenter_metrics_log": self.v7_augmenter_metrics_log,
653
+ "dpo_metrics_log": self.v7_dpo_metrics_log,
654
+ "v7_batch_metrics_log": self.v7_metrics_log[-30:], # últimos 30
655
+ }
656
+
657
+
658
+ __all__ = ["V7Fase2Integrator"]
states/v6_5_v2_model_states.pt CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:6eded03affb9f367f3162fd7e7bcedd90bfb3c406dc94dccba86f8ab9dfac201
3
- size 117713262
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2577b646400f634aa42b460c23e22d2cb9ec208b88c5b475a00b674ed3f1be60
3
+ size 118971380