PowerMachine commited on
Commit
43b7b92
·
verified ·
1 Parent(s): e719654

V6+: add scripts/train_v6_progressive.py

Browse files
Files changed (1) hide show
  1. scripts/train_v6_progressive.py +1056 -0
scripts/train_v6_progressive.py ADDED
@@ -0,0 +1,1056 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """train_v6_progressive.py — Treino V6 com esquema progressivo de samples.
2
+
3
+ ═══════════════════════════════════════════════════════════════════════════════
4
+ ESQUEMA PROGRESSIVO (conforme solicitado pelo usuário)
5
+ ═══════════════════════════════════════════════════════════════════════════════
6
+
7
+ Estágios:
8
+ PONTUAÇÃO (start here):
9
+ 100 → 200 → 300 → 400 → 500 samples (limite 500)
10
+ TEXTO:
11
+ 100 → 200 → 300 → 400 → 500 samples (limite 500)
12
+ PESADOS:
13
+ 10 → 20 → 30 → 40 → 50 → 60 → 70 → 80 → 90 → 100 samples (limite 100)
14
+
15
+ A cada estágio:
16
+ * Treina 1 epoch (samples do estágio + cumulativos anteriores opcionais)
17
+ * Captura 12/12 métricas (igual V5/V6)
18
+ * Salva evolução (loss, perplexity, eval_acc, RSS, TFLOPS, etc.)
19
+ * DELETA binários do treino anterior (model checkpoints)
20
+ * Mantém apenas o estado em memória (continuidade do modelo)
21
+
22
+ Bug hunting V6 (continuação):
23
+ * Bug 6 (NOVO, esta rodada): EWC consolidate com torch.enable_grad() no
24
+ compute_fisher_diagonal — fix aplicado.
25
+ * Bug 7 (NOVO, esta rodada): mtp_alphas não se movem porque MTP não tem
26
+ gradient flowing via softmax com teacher forcing simples — adicionar
27
+ entropia regularizer nos alphas para forçar movimento.
28
+ * Bug 8 (conhecido): RLHF/TrustNeuralAgent só se move com reward feedback
29
+ — sem humano no loop, fica inerte (esperado).
30
+
31
+ Arquitetura: inovadora — avaliação humana necessária para resultados baixos.
32
+ """
33
+ from __future__ import annotations
34
+
35
+ import os
36
+ import sys
37
+ import time
38
+ import json
39
+ import gc
40
+ import math
41
+ import random
42
+ import psutil
43
+ import warnings
44
+ import shutil
45
+ from pathlib import Path
46
+ from typing import Optional, List, Dict, Any
47
+
48
+ # ==============================================================================
49
+ # CONFIGURAÇÃO XEON (ANTES de import torch)
50
+ # ==============================================================================
51
+ # Inline configuration (in case xeon_runtime.py is unavailable)
52
+ os.environ.setdefault("OMP_NUM_THREADS", "2")
53
+ os.environ.setdefault("MKL_NUM_THREADS", "2")
54
+ os.environ.setdefault("OMP_DYNAMIC", "FALSE")
55
+ os.environ.setdefault("MKL_DYNAMIC", "FALSE")
56
+ os.environ.setdefault("MKL_ENABLE_INSTRUCTIONS", "AVX512")
57
+ os.environ.setdefault("ONEDNN_MAX_CPU_ISA", "AMX_INT8")
58
+ os.environ.setdefault("DNNL_PRIMITIVE_CACHE_CAPACITY", "1024")
59
+ os.environ.setdefault("TOKENIZERS_PARALLELISM", "true")
60
+ os.environ.setdefault("PYTHONUNBUFFERED", "1")
61
+ os.environ.setdefault("KMP_AFFINITY", "granularity=fine,compact,1,0")
62
+ os.environ.setdefault("KMP_BLOCKTIME", "1")
63
+
64
+ warnings.filterwarnings("ignore", category=UserWarning)
65
+ warnings.filterwarnings("ignore", category=FutureWarning)
66
+ warnings.filterwarnings("ignore", category=DeprecationWarning)
67
+
68
+ # Path setup
69
+ SCRIPT_DIR = Path(__file__).resolve().parent
70
+ PROJECT_DIR = SCRIPT_DIR.parent
71
+ SRC_DIR = PROJECT_DIR / "BiGRU_T_version" / "src"
72
+ sys.path.insert(0, str(SRC_DIR))
73
+ sys.path.insert(0, str(SCRIPT_DIR))
74
+
75
+ import torch
76
+ import torch.nn as nn
77
+ import torch.nn.functional as F
78
+ import numpy as np
79
+
80
+ # Try to apply IPEX optimization
81
+ try:
82
+ import intel_extension_for_pytorch as ipex
83
+ HAS_IPEX = True
84
+ IPEX_VERSION = ipex.__version__
85
+ torch._C._jit_set_profiling_mode(False)
86
+ torch._C._jit_set_profiling_executor(False)
87
+ except ImportError:
88
+ HAS_IPEX = False
89
+ IPEX_VERSION = None
90
+
91
+ torch.set_num_threads(2)
92
+ torch.set_num_interop_threads(1)
93
+
94
+ # Imports do modelo
95
+ from bigru_t.model import UnifiedModel, UnifiedModelConfig
96
+ from bigru_t.model.orq_cell import OrqCell, KohonenSOM4D
97
+ from bigru_t.model.window_context import WindowContext
98
+ from bigru_t.model.mtp import MTPModule, MTPAdaptiveAttention, DynamicRepetitionPenalty
99
+ from bigru_t.training.elastic_weight_consolidation import ElasticWeightConsolidation
100
+ from bigru_t.training.rlhf_possibility_mapping import LearnablePossibilityMapping
101
+ from bigru_t.reasoning.reasoning_system import ReasoningEngine
102
+ from bigru_t.tools import ToolCache, ToolMutationEngine, ToolAgentCoordinator
103
+ from bigru_t.inference.optimized_pipeline import OptimizedPipeline
104
+ from bigru_t.inference.langchain_adapter import LangchainAdapter
105
+ from bigru_t.data.data_augmentation import augment_batch, mixup, embedding_noise
106
+ from bigru_t.training.meta_configurator import MetaConfigurator
107
+ from bigru_t.training.triplet_prototype_loss import TripletPrototypeLoss
108
+ from bigru_t.tokenizer.bbpe_tokenizer import BBPETokenizer, PAD_ID
109
+
110
+ # ==============================================================================
111
+ # CONFIG
112
+ # ==============================================================================
113
+ EPOCHS = 1 # progressive: 1 epoch per stage (was 2)
114
+ BATCH_SIZE = 8
115
+ MAX_SEQ_LEN = 24 # slightly larger to fit punctuation + text
116
+ LR = 3e-4
117
+ NUM_LAYERS_HYP = 8
118
+ TRIPLET_WEIGHT = 0.05
119
+ META_INTERVAL = 5 # less frequent meta (samples are larger now)
120
+
121
+ # Progressive stages
122
+ PUNCTUATION_STAGES = [100, 200, 300, 400, 500]
123
+ TEXT_STAGES = [100, 200, 300, 400, 500]
124
+ HEAVY_STAGES = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
125
+
126
+ VOCAB_SIZE = None # setado após carregar tokenizer
127
+
128
+ # Checkpoint dir to delete between stages
129
+ CHECKPOINT_DIR = PROJECT_DIR / "BiGRU_T_version" / "_temp_checkpoints"
130
+ CHECKPOINT_DIR.mkdir(parents=True, exist_ok=True)
131
+
132
+
133
+ # ==============================================================================
134
+ # MONITOR DE MÉTRICAS (12/12 — CPU-adaptado, com evolução)
135
+ # ==============================================================================
136
+ class MetricsMonitor:
137
+ def __init__(self):
138
+ self.train_losses: List[float] = []
139
+ self.val_losses: List[float] = []
140
+ self.perplexities: List[float] = []
141
+ self.tokens_per_sec: List[float] = []
142
+ self.tflops: List[float] = []
143
+ self.time_per_step_ms: List[float] = []
144
+ self.grad_norms: List[float] = []
145
+ self.cpu_pcts: List[float] = []
146
+ self.rss_mbs: List[float] = []
147
+ self.alerts: List[tuple] = []
148
+ self.eval_accs: List[float] = []
149
+ self.overfitting_gaps: List[float] = []
150
+ self.mtp_alphas: List[float] = []
151
+ self.som_quant_losses: List[float] = []
152
+ self.som_neighborhood_entropies: List[float] = []
153
+ self.som_sigmas: List[float] = []
154
+ self.ewc_lambdas: List[float] = []
155
+ self.rlhf_rewards: List[float] = []
156
+ self.reasoning_steps: List[int] = []
157
+
158
+ def record(self, **kwargs):
159
+ if "train_loss" in kwargs:
160
+ self.train_losses.append(float(kwargs["train_loss"]))
161
+ if "val_loss" in kwargs:
162
+ self.val_losses.append(float(kwargs["val_loss"]))
163
+ self.perplexities.append(math.exp(min(kwargs["val_loss"], 20)))
164
+ if "tokens_per_sec" in kwargs:
165
+ self.tokens_per_sec.append(float(kwargs["tokens_per_sec"]))
166
+ if "tflops" in kwargs:
167
+ self.tflops.append(float(kwargs["tflops"]))
168
+ if "time_per_step_ms" in kwargs:
169
+ self.time_per_step_ms.append(float(kwargs["time_per_step_ms"]))
170
+ if "grad_norm" in kwargs:
171
+ self.grad_norms.append(float(kwargs["grad_norm"]))
172
+ g = kwargs["grad_norm"]
173
+ if g < 1e-7:
174
+ self.alerts.append((len(self.grad_norms), "vanishing_grad", f"||g||={g:.2e}"))
175
+ elif g > 1e3:
176
+ self.alerts.append((len(self.grad_norms), "exploding_grad", f"||g||={g:.2e}"))
177
+ if "cpu_pct" in kwargs:
178
+ self.cpu_pcts.append(float(kwargs["cpu_pct"]))
179
+ if kwargs["cpu_pct"] < 80 and len(self.cpu_pcts) > 2:
180
+ self.alerts.append((len(self.cpu_pcts), "cpu_underutil", f"cpu={kwargs['cpu_pct']:.1f}%"))
181
+ if "rss_mb" in kwargs:
182
+ self.rss_mbs.append(float(kwargs["rss_mb"]))
183
+ if "eval_acc" in kwargs:
184
+ self.eval_accs.append(float(kwargs["eval_acc"]))
185
+ if "overfitting_gap" in kwargs:
186
+ self.overfitting_gaps.append(float(kwargs["overfitting_gap"]))
187
+ if "mtp_alpha_mean" in kwargs:
188
+ self.mtp_alphas.append(float(kwargs["mtp_alpha_mean"]))
189
+ if "som_quant_loss" in kwargs:
190
+ self.som_quant_losses.append(float(kwargs["som_quant_loss"]))
191
+ if "som_entropy" in kwargs:
192
+ self.som_neighborhood_entropies.append(float(kwargs["som_entropy"]))
193
+ if "som_sigma" in kwargs:
194
+ self.som_sigmas.append(float(kwargs["som_sigma"]))
195
+ if "ewc_lambda" in kwargs:
196
+ self.ewc_lambdas.append(float(kwargs["ewc_lambda"]))
197
+ if "rlhf_reward" in kwargs:
198
+ self.rlhf_rewards.append(float(kwargs["rlhf_reward"]))
199
+ if "reasoning_steps" in kwargs:
200
+ self.reasoning_steps.append(int(kwargs["reasoning_steps"]))
201
+
202
+ def check_loss_spike(self, step: int):
203
+ if len(self.train_losses) < 3:
204
+ return
205
+ recent = self.train_losses[-3:]
206
+ if recent[1] > 0 and recent[2] > 1.5 * recent[1]:
207
+ self.alerts.append((step, "loss_spike", f"{recent[1]:.3f} → {recent[2]:.3f}"))
208
+
209
+ def summary(self) -> dict:
210
+ return {
211
+ "n_steps": len(self.train_losses),
212
+ "final_train_loss": self.train_losses[-1] if self.train_losses else None,
213
+ "final_val_loss": self.val_losses[-1] if self.val_losses else None,
214
+ "final_perplexity": self.perplexities[-1] if self.perplexities else None,
215
+ "final_overfitting_gap": self.overfitting_gaps[-1] if self.overfitting_gaps else None,
216
+ "final_eval_acc": self.eval_accs[-1] if self.eval_accs else None,
217
+ "avg_tokens_per_sec": float(np.mean(self.tokens_per_sec)) if self.tokens_per_sec else None,
218
+ "avg_tflops": float(np.mean(self.tflops)) if self.tflops else None,
219
+ "avg_time_per_step_ms": float(np.mean(self.time_per_step_ms)) if self.time_per_step_ms else None,
220
+ "avg_grad_norm": float(np.mean(self.grad_norms)) if self.grad_norms else None,
221
+ "avg_cpu_pct": float(np.mean(self.cpu_pcts)) if self.cpu_pcts else None,
222
+ "final_rss_mb": self.rss_mbs[-1] if self.rss_mbs else None,
223
+ "max_rss_mb": max(self.rss_mbs) if self.rss_mbs else None,
224
+ "rss_trend": "stable" if (len(self.rss_mbs) < 3 or max(self.rss_mbs) - min(self.rss_mbs) < 100) else "growing",
225
+ "n_alerts": len(self.alerts),
226
+ "alerts": self.alerts[:50],
227
+ "alert_types": list(set(a[1] for a in self.alerts)),
228
+ "mtp_alpha_mean": self.mtp_alphas[-1] if self.mtp_alphas else None,
229
+ "som_quant_loss_final": self.som_quant_losses[-1] if self.som_quant_losses else None,
230
+ "som_entropy_final": self.som_neighborhood_entropies[-1] if self.som_neighborhood_entropies else None,
231
+ "som_sigma_final": self.som_sigmas[-1] if self.som_sigmas else None,
232
+ "ewc_lambda_final": self.ewc_lambdas[-1] if self.ewc_lambdas else None,
233
+ "rlhf_reward_final": self.rlhf_rewards[-1] if self.rlhf_rewards else None,
234
+ "reasoning_steps_final": self.reasoning_steps[-1] if self.reasoning_steps else None,
235
+ }
236
+
237
+
238
+ # ==============================================================================
239
+ # GERAÇÃO DE DADOS — PONTUAÇÃO, TEXTO, PESADOS
240
+ # ==============================================================================
241
+ def generate_punctuation_samples(tokenizer, n: int, max_len: int = 24) -> List[dict]:
242
+ """Datasets de pontuação — samples com vírgulas, pontos, pontos de interrogação."""
243
+ templates = [
244
+ "hello, how are you today?",
245
+ "the cat, the dog, and the bird.",
246
+ "what time is it? it is noon.",
247
+ "yes, i can do that for you.",
248
+ "no, thank you, i am fine.",
249
+ "the sun, the moon, and the stars.",
250
+ "are you sure? yes, i am sure.",
251
+ "first, second, third, fourth, fifth.",
252
+ "i think, therefore i am.",
253
+ "well, that is interesting, isn't it?",
254
+ "wait, what? are you serious?",
255
+ "one, two, three, four, five, six.",
256
+ "the man said, hello there.",
257
+ "she asked, where is the book?",
258
+ "he replied, it is here.",
259
+ "quick, fast, now, go, run!",
260
+ "slow, steady, patient, calm.",
261
+ "red, blue, green, yellow, white.",
262
+ "open, close, open, close, open.",
263
+ "up, down, left, right, forward.",
264
+ ]
265
+ samples = []
266
+ for i in range(n):
267
+ tmpl = templates[i % len(templates)]
268
+ # Add some variation: append index token
269
+ tmpl_full = tmpl
270
+ tokens = tokenizer.encode(tmpl_full)
271
+ if len(tokens) < 2:
272
+ tokens = tokens + [0] * (2 - len(tokens))
273
+ if len(tokens) > max_len:
274
+ tokens = tokens[:max_len]
275
+ else:
276
+ tokens = tokens + [0] * (max_len - len(tokens))
277
+ input_ids = torch.tensor(tokens, dtype=torch.long)
278
+ target = input_ids.clone()
279
+ target[1:] = input_ids[:-1].clone()
280
+ target[0] = 0
281
+ samples.append({
282
+ "input_ids": input_ids,
283
+ "target": target,
284
+ "type": "punctuation",
285
+ "caption": tmpl_full,
286
+ })
287
+ return samples
288
+
289
+
290
+ def generate_text_samples(tokenizer, n: int, max_len: int = 24) -> List[dict]:
291
+ """Datasets de texto — frases completas com estrutura gramatical."""
292
+ templates = [
293
+ "the quick brown fox jumps over the lazy dog",
294
+ "she sells seashells by the seashore every day",
295
+ "peter piper picked a peck of pickled peppers",
296
+ "how much wood would a woodchuck chuck if able",
297
+ "i scream you scream we all scream for ice cream",
298
+ "the rain in spain falls mainly on the plain",
299
+ "a stitch in time saves nine lives they say",
300
+ "the early bird catches the worm every morning",
301
+ "two plus two equals four in basic math class",
302
+ "three times three is nine as we all know well",
303
+ "the cat sat on the mat near the warm fire",
304
+ "the dog ran fast across the green grass field",
305
+ "birds fly high in the blue sky above us now",
306
+ "fish swim deep in the cool clear blue lake",
307
+ "the sun shines bright on the old wooden house",
308
+ "the moon glows soft in the dark night sky",
309
+ "rain falls hard on the roof of the cabin",
310
+ "wind blows cold through the trees in winter",
311
+ "the tree grows tall in the middle of forest",
312
+ "the river flows wide past the small village",
313
+ ]
314
+ samples = []
315
+ for i in range(n):
316
+ tmpl = templates[i % len(templates)]
317
+ tokens = tokenizer.encode(tmpl)
318
+ if len(tokens) < 2:
319
+ tokens = tokens + [0] * (2 - len(tokens))
320
+ if len(tokens) > max_len:
321
+ tokens = tokens[:max_len]
322
+ else:
323
+ tokens = tokens + [0] * (max_len - len(tokens))
324
+ input_ids = torch.tensor(tokens, dtype=torch.long)
325
+ target = input_ids.clone()
326
+ target[1:] = input_ids[:-1].clone()
327
+ target[0] = 0
328
+ samples.append({
329
+ "input_ids": input_ids,
330
+ "target": target,
331
+ "type": "text",
332
+ "caption": tmpl,
333
+ })
334
+ return samples
335
+
336
+
337
+ def generate_heavy_samples(tokenizer, n: int, max_len: int = 24) -> List[dict]:
338
+ """Datasets pesados — samples multimodais (simulados como longas com contexto)."""
339
+ # Heavy = multimodal-like, longer sequences, more complex structure
340
+ templates = [
341
+ "the image shows a cat sitting on a mat in the kitchen near the window",
342
+ "audio transcription of a man speaking loudly about the weather today",
343
+ "video frame shows a car driving fast on a highway during sunset hour",
344
+ "the chart displays sales data from q1 to q4 with rising trend clearly",
345
+ "scientific paper abstract about neural networks and their applications",
346
+ "code review feedback on a python function that processes large datasets",
347
+ "legal document clause about property rights and tenant obligations here",
348
+ "medical report summary indicating patient recovery is on right track now",
349
+ "financial analysis of quarterly earnings showing strong growth year",
350
+ "technical specification for a new hardware module with low power design",
351
+ ]
352
+ samples = []
353
+ for i in range(n):
354
+ tmpl = templates[i % len(templates)]
355
+ tokens = tokenizer.encode(tmpl)
356
+ if len(tokens) < 2:
357
+ tokens = tokens + [0] * (2 - len(tokens))
358
+ if len(tokens) > max_len:
359
+ tokens = tokens[:max_len]
360
+ else:
361
+ tokens = tokens + [0] * (max_len - len(tokens))
362
+ input_ids = torch.tensor(tokens, dtype=torch.long)
363
+ target = input_ids.clone()
364
+ target[1:] = input_ids[:-1].clone()
365
+ target[0] = 0
366
+ samples.append({
367
+ "input_ids": input_ids,
368
+ "target": target,
369
+ "type": "heavy",
370
+ "caption": tmpl,
371
+ })
372
+ return samples
373
+
374
+
375
+ def make_mini_mcq_eval(tokenizer, n_questions=8):
376
+ questions = [
377
+ ("2+2=?", ["3", "4", "5", "6"], 1),
378
+ ("3*3=?", ["6", "8", "9", "10"], 2),
379
+ ("5-1=?", ["3", "4", "5", "6"], 1),
380
+ ("6+6=?", ["10", "11", "12", "13"], 2),
381
+ ("10/2=?", ["4", "5", "6", "7"], 1),
382
+ ("7*2=?", ["12", "13", "14", "15"], 2),
383
+ ("8+1=?", ["8", "9", "10", "11"], 1),
384
+ ("4*5=?", ["15", "20", "25", "30"], 1),
385
+ ][:n_questions]
386
+ encoded = []
387
+ for q, opts, ans in questions:
388
+ q_tokens = tokenizer.encode(q)
389
+ opt_tokens = [tokenizer.encode(o) for o in opts]
390
+ encoded.append({
391
+ "q_tokens": q_tokens,
392
+ "opt_tokens": opt_tokens,
393
+ "answer_idx": ans,
394
+ })
395
+ return encoded
396
+
397
+
398
+ def _save_partial_report(evolution: List[dict], n_params: int,
399
+ current_stage: str = "", current_n: int = 0, current_epoch: int = 0):
400
+ """Save partial report (called after each stage) so progress is preserved on crash."""
401
+ try:
402
+ report = {
403
+ "version": "V6_progressive",
404
+ "timestamp": time.time(),
405
+ "note": "Partial report — saved incrementally after each stage. Last update: "
406
+ f"{current_stage} n={current_n} ep={current_epoch}",
407
+ "config": {
408
+ "epochs": EPOCHS,
409
+ "batch_size": BATCH_SIZE,
410
+ "max_seq_len": MAX_SEQ_LEN,
411
+ "num_layers_hyp": NUM_LAYERS_HYP,
412
+ "stages_punctuation": PUNCTUATION_STAGES,
413
+ "stages_text": TEXT_STAGES,
414
+ "stages_heavy": HEAVY_STAGES,
415
+ },
416
+ "evolution": evolution,
417
+ "n_stages_captured": len(evolution),
418
+ "n_stages_total_expected": len(PUNCTUATION_STAGES) + len(TEXT_STAGES) + len(HEAVY_STAGES),
419
+ "n_params": n_params,
420
+ }
421
+ report_path = PROJECT_DIR / "BiGRU_T_version" / "v6_progressive_report.json"
422
+ report_path.write_text(json.dumps(report, indent=2, ensure_ascii=False, default=str))
423
+ except Exception as e:
424
+ print(f" [WARN] _save_partial_report failed: {e}")
425
+
426
+
427
+ def cleanup_binaries():
428
+ """Delete training binaries (checkpoints, model_final, etc.) to free disk."""
429
+ if CHECKPOINT_DIR.exists():
430
+ # Remove .pt, .pth, .bin, .safetensors files
431
+ for ext in ["*.pt", "*.pth", "*.bin", "*.safetensors", "*.ckpt"]:
432
+ for f in CHECKPOINT_DIR.glob(ext):
433
+ try:
434
+ f.unlink()
435
+ print(f" [CLEAN] Deleted binary: {f.name}")
436
+ except Exception:
437
+ pass
438
+ # Also clean any model_final binaries
439
+ model_final_dir = PROJECT_DIR / "BiGRU_T_version" / "model_final"
440
+ if model_final_dir.exists():
441
+ for ext in ["*.pt", "*.pth", "*.bin", "*.safetensors", "*.ckpt"]:
442
+ for f in model_final_dir.glob(ext):
443
+ try:
444
+ f.unlink()
445
+ print(f" [CLEAN] Deleted model_final binary: {f.name}")
446
+ except Exception:
447
+ pass
448
+ # Cleanup torch and HF caches
449
+ gc.collect(0)
450
+ if hasattr(torch, "cuda") and torch.cuda.is_available():
451
+ torch.cuda.empty_cache()
452
+
453
+
454
+ # ==============================================================================
455
+ # TREINO POR ESTÁGIO
456
+ # ==============================================================================
457
+ def train_stage(
458
+ model, optimizer, pipeline, meta_cfg, ewc, mtp, rep_penalty,
459
+ monitor, mcq_eval, train_samples, val_samples,
460
+ stage_name: str, stage_n: int, epoch: int = 1,
461
+ prototypes: List[torch.Tensor] = None,
462
+ ) -> dict:
463
+ """Treina 1 estágio (1 ou mais epochs). Retorna summary do estágio."""
464
+ print(f"\n{'=' * 72}")
465
+ print(f" STAGE: {stage_name} (n={stage_n}, epoch={epoch})")
466
+ print(f"{'=' * 72}")
467
+
468
+ n_train = max(1, int(0.85 * len(train_samples)))
469
+ train_set = train_samples[:n_train]
470
+ val_set = val_samples[:max(1, len(val_samples))]
471
+
472
+ step = 0
473
+ t_start = time.perf_counter()
474
+ process = psutil.Process()
475
+ n_params = sum(p.numel() for p in model.parameters())
476
+
477
+ random.shuffle(train_set)
478
+
479
+ for batch_start in range(0, len(train_set), BATCH_SIZE):
480
+ batch = train_set[batch_start:batch_start + BATCH_SIZE]
481
+ if len(batch) < 2:
482
+ continue
483
+
484
+ input_ids = torch.stack([s["input_ids"] for s in batch])
485
+ targets = torch.stack([s["target"] for s in batch])
486
+
487
+ t_step_start = time.perf_counter()
488
+
489
+ # Data augmentation V6 (10% chance)
490
+ if random.random() < 0.1:
491
+ input_ids = augment_batch(input_ids, pad_id=0, p_delete=0.05, n_swaps=1, p_dropout=0.02)
492
+
493
+ # Forward via pipeline
494
+ try:
495
+ out = pipeline.forward(
496
+ input_ids, targets,
497
+ use_mtp=True,
498
+ use_reasoning=False,
499
+ use_rep_penalty=True,
500
+ return_aux=True,
501
+ )
502
+ logits = out["logits"]
503
+ loss = out["loss"]
504
+ aux = out.get("aux") or {}
505
+ except Exception as e:
506
+ print(f" [WARN] Pipeline forward failed: {e}")
507
+ model_out = model(input_ids)
508
+ if isinstance(model_out, tuple):
509
+ logits = model_out[0]
510
+ else:
511
+ logits = model_out
512
+ tgt_last = targets[:, -1]
513
+ loss = F.cross_entropy(logits, tgt_last, ignore_index=-100)
514
+ aux = {}
515
+
516
+ # Backward
517
+ optimizer.zero_grad()
518
+ loss.backward()
519
+ torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
520
+ optimizer.step()
521
+
522
+ # Stats
523
+ grad_norm = sum(
524
+ (p.grad ** 2).sum().item()
525
+ for p in model.parameters()
526
+ if p.grad is not None
527
+ ) ** 0.5
528
+ t_step = time.perf_counter() - t_step_start
529
+ cpu_pct = process.cpu_percent()
530
+ rss_mb = process.memory_info().rss / 1024 / 1024
531
+ n_tokens = input_ids.numel()
532
+ tps = n_tokens / t_step if t_step > 0 else 0
533
+ tflops = 6 * n_params * n_tokens / t_step / 1e12 if t_step > 0 else 0
534
+
535
+ mtp_alpha_val = 0.0
536
+ if isinstance(aux.get("mtp"), dict) and "alpha_1" in aux["mtp"]:
537
+ mtp_alpha_val = float(aux["mtp"]["alpha_1"])
538
+ elif hasattr(mtp, "alphas"):
539
+ try:
540
+ mtp_alpha_val = float(mtp.alphas[0].item())
541
+ except Exception:
542
+ pass
543
+
544
+ som_ql = float(aux.get("orq_som_quant_loss", 0.0)) if isinstance(aux.get("orq_som_quant_loss"), (int, float, int, float)) else 0.0
545
+ som_s = float(aux.get("orq_som_sigma", 0.0)) if isinstance(aux.get("orq_som_sigma"), (int, float, int, float)) else 0.0
546
+
547
+ monitor.record(
548
+ train_loss=float(loss.item()),
549
+ tokens_per_sec=tps,
550
+ tflops=tflops,
551
+ time_per_step_ms=t_step * 1000,
552
+ grad_norm=grad_norm,
553
+ cpu_pct=cpu_pct,
554
+ rss_mb=rss_mb,
555
+ mtp_alpha_mean=mtp_alpha_val,
556
+ som_quant_loss=som_ql,
557
+ som_sigma=som_s,
558
+ ewc_lambda=float(ewc.lambda_val.item()) if hasattr(ewc, "lambda_val") else 0.0,
559
+ rlhf_reward=0.0,
560
+ )
561
+ monitor.check_loss_spike(step)
562
+
563
+ if step % 10 == 0 or step < 5:
564
+ print(f" step {step+1:3d} | loss={loss.item():.4f} | tps={tps:.0f} | "
565
+ f"tflops={tflops:.4f} | ||g||={grad_norm:.2f} | cpu={cpu_pct:.0f}% | rss={rss_mb:.0f}MB")
566
+
567
+ # MetaConfigurator
568
+ if step % META_INTERVAL == 0 and step > 0:
569
+ try:
570
+ val_input = torch.stack([s["input_ids"] for s in val_set[:BATCH_SIZE]])
571
+ val_target = torch.stack([s["target"] for s in val_set[:BATCH_SIZE]])
572
+ val_target_last = val_target[:, -1]
573
+ meta_cfg.forward_with_meta(val_input, val_target_last)
574
+ except Exception as e:
575
+ pass # silent — meta failure is OK
576
+
577
+ # Cleanup
578
+ del logits, loss, input_ids, targets
579
+ if "aux" in dir():
580
+ del aux
581
+ gc.collect(0)
582
+
583
+ step += 1
584
+
585
+ # Validation
586
+ model.eval()
587
+ val_losses_epoch = []
588
+ with torch.no_grad():
589
+ for val_batch_start in range(0, len(val_set), BATCH_SIZE):
590
+ val_batch = val_set[val_batch_start:val_batch_start + BATCH_SIZE]
591
+ if len(val_batch) < 1:
592
+ continue
593
+ val_input = torch.stack([s["input_ids"] for s in val_batch])
594
+ val_target = torch.stack([s["target"] for s in val_batch])
595
+ try:
596
+ val_out = pipeline.forward(
597
+ val_input, val_target,
598
+ use_mtp=False, use_reasoning=False, use_rep_penalty=False,
599
+ return_aux=False,
600
+ )
601
+ val_loss = val_out["loss"]
602
+ if val_loss is not None:
603
+ val_losses_epoch.append(float(val_loss.item()))
604
+ except Exception:
605
+ model_out = model(val_input)
606
+ if isinstance(model_out, tuple):
607
+ val_logits = model_out[0]
608
+ else:
609
+ val_logits = model_out
610
+ tgt_last = val_target[:, -1]
611
+ vl = F.cross_entropy(val_logits, tgt_last, ignore_index=-100)
612
+ val_losses_epoch.append(float(vl.item()))
613
+
614
+ val_loss_mean = float(np.mean(val_losses_epoch)) if val_losses_epoch else 0.0
615
+ train_loss_mean = float(np.mean(monitor.train_losses[-step:])) if monitor.train_losses else 0.0
616
+ overfitting_gap = train_loss_mean - val_loss_mean
617
+ ppl = math.exp(min(val_loss_mean, 20))
618
+
619
+ # MCQ eval
620
+ eval_acc = 0.0
621
+ n_correct = 0
622
+ n_total = 0
623
+ with torch.no_grad():
624
+ for q in mcq_eval:
625
+ try:
626
+ q_t = torch.tensor([q["q_tokens"]], dtype=torch.long)
627
+ if q_t.shape[1] < MAX_SEQ_LEN:
628
+ q_t = F.pad(q_t, (0, MAX_SEQ_LEN - q_t.shape[1]))
629
+ else:
630
+ q_t = q_t[:, :MAX_SEQ_LEN]
631
+ out = model(q_t)
632
+ if isinstance(out, tuple):
633
+ q_logits = out[0]
634
+ else:
635
+ q_logits = out
636
+ if q_logits.dim() == 2:
637
+ last_logits = q_logits[0]
638
+ else:
639
+ last_logits = q_logits[0, -1, :]
640
+ opt_scores = []
641
+ for opt_tokens in q["opt_tokens"]:
642
+ if len(opt_tokens) > 0:
643
+ opt_scores.append(float(last_logits[opt_tokens[0]].item()))
644
+ else:
645
+ opt_scores.append(0.0)
646
+ pred_idx = int(np.argmax(opt_scores))
647
+ if pred_idx == q["answer_idx"]:
648
+ n_correct += 1
649
+ n_total += 1
650
+ except Exception:
651
+ n_total += 1
652
+ if n_total > 0:
653
+ eval_acc = n_correct / n_total
654
+
655
+ monitor.record(
656
+ val_loss=val_loss_mean,
657
+ overfitting_gap=overfitting_gap,
658
+ eval_acc=eval_acc,
659
+ )
660
+
661
+ elapsed = time.perf_counter() - t_start
662
+ print(f" STAGE END | val_loss={val_loss_mean:.4f} | train_avg={train_loss_mean:.4f} | "
663
+ f"ppl={ppl:.2f} | gap={overfitting_gap:+.4f} | eval_acc={eval_acc*100:.2f}% | "
664
+ f"elapsed={elapsed:.1f}s | n_steps={step}")
665
+
666
+ # SOM stats
667
+ som_stats = {}
668
+ if hasattr(model, "orq_cell") and hasattr(model.orq_cell, "som"):
669
+ som = model.orq_cell.som
670
+ som_stats = {
671
+ "sigma": float(som.sigma_current.item()),
672
+ "alpha": float(som.alpha_current.item()),
673
+ "step": int(som.step_count.item()),
674
+ }
675
+ print(f" SOM: σ={som_stats['sigma']:.3f}, α={som_stats['alpha']:.4f}, step={som_stats['step']}")
676
+
677
+ model.train()
678
+ return {
679
+ "stage": stage_name,
680
+ "n_samples": stage_n,
681
+ "epoch": epoch,
682
+ "n_steps": step,
683
+ "elapsed_s": elapsed,
684
+ "val_loss": val_loss_mean,
685
+ "train_loss_mean": train_loss_mean,
686
+ "overfitting_gap": overfitting_gap,
687
+ "perplexity": ppl,
688
+ "eval_acc": eval_acc,
689
+ "final_rss_mb": monitor.rss_mbs[-1] if monitor.rss_mbs else 0.0,
690
+ "max_rss_mb": max(monitor.rss_mbs) if monitor.rss_mbs else 0.0,
691
+ "avg_tflops": float(np.mean(monitor.tflops[-step:])) if monitor.tflops else 0.0,
692
+ "avg_tokens_per_sec": float(np.mean(monitor.tokens_per_sec[-step:])) if monitor.tokens_per_sec else 0.0,
693
+ "n_alerts_in_stage": sum(1 for a in monitor.alerts if a[0] >= len(monitor.train_losses) - step),
694
+ "som": som_stats,
695
+ "n_train": len(train_set),
696
+ "n_val": len(val_set),
697
+ }
698
+
699
+
700
+ # ==============================================================================
701
+ # MAIN
702
+ # ==============================================================================
703
+ def main():
704
+ print("=" * 72)
705
+ print("TREINO V6 PROGRESSIVO — esquema de samples crescente")
706
+ print("=" * 72)
707
+ print(f" Python: {sys.version.split()[0]}")
708
+ print(f" Torch: {torch.__version__}")
709
+ print(f" IPEX ativo: {HAS_IPEX}" + (f" (v{IPEX_VERSION})" if HAS_IPEX else ""))
710
+ print(f" OneDNN enabled: {torch.backends.mkldnn.enabled}")
711
+ print(f" ONEDNN_MAX_CPU_ISA: {os.environ.get('ONEDNN_MAX_CPU_ISA')}")
712
+ print(f" OMP_NUM_THREADS: {os.environ.get('OMP_NUM_THREADS')}")
713
+ print(f" EPOCHS: {EPOCHS}")
714
+ print(f" BATCH_SIZE: {BATCH_SIZE}")
715
+ print(f" MAX_SEQ_LEN: {MAX_SEQ_LEN}")
716
+ print(f" NUM_LAYERS_HYP: {NUM_LAYERS_HYP}")
717
+ print(f" Stages PUNCT: {PUNCTUATION_STAGES}")
718
+ print(f" Stages TEXT: {TEXT_STAGES}")
719
+ print(f" Stages HEAVY: {HEAVY_STAGES}")
720
+ print("=" * 72)
721
+
722
+ # 1. Tokenizer
723
+ tokenizer_path = str(PROJECT_DIR / "BiGRU_T_version" / "model_final" / "tokenizer" / "tokenizer.json")
724
+ print(f"\n[INFO] Loading tokenizer: {tokenizer_path}")
725
+ tokenizer = BBPETokenizer.load(tokenizer_path)
726
+ global VOCAB_SIZE
727
+ VOCAB_SIZE = tokenizer.vocab_size
728
+ print(f"[INFO] Tokenizer loaded: vocab_size={VOCAB_SIZE}")
729
+
730
+ # 2. Model
731
+ cfg = UnifiedModelConfig(
732
+ vocab_size=VOCAB_SIZE,
733
+ d_model=128,
734
+ max_seq_len=MAX_SEQ_LEN,
735
+ bigru_hidden=32,
736
+ d_transformer=64,
737
+ nhead_tu=4,
738
+ d_ff_tu=128,
739
+ output_dim_u8cell=64,
740
+ max_modules=8,
741
+ cache_len=16,
742
+ d_cache=128,
743
+ nhead_orq=8,
744
+ d_ff_orq=256,
745
+ trainT_dim=128,
746
+ nhead_train=4,
747
+ d_ff_train=256,
748
+ num_layers_train=2,
749
+ hypT_dim=128,
750
+ nhead_hyp=4,
751
+ d_ff_hyp=256,
752
+ num_layers_hyp=NUM_LAYERS_HYP,
753
+ use_circular_reasoning=True,
754
+ circular_n_cycles=3,
755
+ )
756
+ model = UnifiedModel(cfg)
757
+ n_params = sum(p.numel() for p in model.parameters())
758
+ print(f"[INFO] Model params: {n_params:,} ({n_params/1e6:.2f}M)")
759
+
760
+ # Apply IPEX optimize to model (CPU optimization)
761
+ if HAS_IPEX:
762
+ try:
763
+ model = ipex.optimize(model, level="O1")
764
+ print(f"[INFO] ipex.optimize applied (level=O1)")
765
+ except Exception as e:
766
+ print(f"[WARN] ipex.optimize failed: {e}")
767
+
768
+ # 3. V6 Components
769
+ mtp = MTPModule(d_model=128, vocab_size=VOCAB_SIZE, K=4, learnable_alpha=True)
770
+ if hasattr(model, "token_embedding"):
771
+ mtp.set_embedding(model.token_embedding)
772
+
773
+ mtp_adaptive_attn = MTPAdaptiveAttention(d_model=128, nhead=4, window_size=8)
774
+
775
+ rep_penalty = DynamicRepetitionPenalty(
776
+ vocab_size=VOCAB_SIZE, embedding_dim=128, window_size=32,
777
+ )
778
+ if hasattr(model, "token_embedding"):
779
+ rep_penalty.set_embedding(model.token_embedding)
780
+
781
+ reasoning_engine = ReasoningEngine(
782
+ d_model=128, vocab_size=VOCAB_SIZE, n_phases=8, max_steps=4,
783
+ use_bayesian_selector=True,
784
+ )
785
+
786
+ ewc = ElasticWeightConsolidation(model, lambda_init=10.0, adaptive_lambda=True)
787
+
788
+ rlhf_mapping = LearnablePossibilityMapping(
789
+ model=model, vocab_size=VOCAB_SIZE, d_model=128,
790
+ )
791
+
792
+ tool_cache = ToolCache(max_size=64, ttl=600.0)
793
+ tool_engine = ToolMutationEngine(cache=tool_cache)
794
+ def echo_tool(x):
795
+ return x
796
+ tool_engine.register("echo", echo_tool, "Echo tool for testing")
797
+ tool_engine.compose("double_echo", "echo", "echo", "Echo composed with echo")
798
+ tool_agent = ToolAgentCoordinator(mutation_engine=tool_engine, max_workers=2)
799
+
800
+ pipeline = OptimizedPipeline(
801
+ model=model,
802
+ tokenizer=tokenizer,
803
+ mtp=mtp,
804
+ mtp_adaptive_attn=mtp_adaptive_attn,
805
+ rep_penalty=rep_penalty,
806
+ reasoning_engine=reasoning_engine,
807
+ ewc=ewc,
808
+ rlhf_mapping=rlhf_mapping,
809
+ tool_engine=tool_engine,
810
+ tool_agent=tool_agent,
811
+ )
812
+
813
+ meta_cfg = MetaConfigurator(model, meta_lr=0.01)
814
+
815
+ optimizer = torch.optim.AdamW(model.parameters(), lr=LR, weight_decay=0.01)
816
+
817
+ monitor = MetricsMonitor()
818
+ mcq_eval = make_mini_mcq_eval(tokenizer, n_questions=8)
819
+
820
+ # 4. Run progressive stages
821
+ evolution: List[dict] = []
822
+ cumulative_punct = []
823
+ cumulative_text = []
824
+ cumulative_heavy = []
825
+
826
+ # === RESUME SUPPORT: skip already-completed stages ===
827
+ # If a partial report exists, load it and skip those stages
828
+ RESUME_REPORT = PROJECT_DIR / "BiGRU_T_version" / "v6_progressive_report.json"
829
+ if RESUME_REPORT.exists():
830
+ try:
831
+ old_report = json.loads(RESUME_REPORT.read_text())
832
+ old_evolution = old_report.get("evolution", [])
833
+ # Filter only complete stages (those with val_loss)
834
+ completed_stages = [
835
+ (e["stage"], e["n_samples"], e["epoch"])
836
+ for e in old_evolution
837
+ if e.get("val_loss") is not None
838
+ ]
839
+ if completed_stages:
840
+ print(f"\n[INFO] RESUME: Found {len(completed_stages)} completed stages from previous run:")
841
+ for s, n, ep in completed_stages:
842
+ print(f" - {s} n={n} ep={ep}")
843
+ # Carry over the old evolution entries
844
+ evolution = [e for e in old_evolution if e.get("val_loss") is not None]
845
+ # Filter the stages lists to skip completed ones
846
+ # (For simplicity, we just skip the entire stage type if its first stage is done)
847
+ # Actually, we need to skip per-stage, so let's just track which to skip
848
+ _skip_set = set(completed_stages)
849
+ def _should_skip(stage, n, ep):
850
+ return (stage, n, ep) in _skip_set
851
+ print(f"[INFO] Will skip these stages and continue from where it left off.")
852
+ else:
853
+ _should_skip = lambda *args: False
854
+ except Exception as e:
855
+ print(f"[WARN] Could not load resume report: {e}")
856
+ _should_skip = lambda *args: False
857
+ else:
858
+ _should_skip = lambda *args: False
859
+
860
+ # === PUNCTUATION STAGES ===
861
+ print(f"\n[INFO] === PONTUAÇÃO STAGES ===")
862
+ for stage_n in PUNCTUATION_STAGES:
863
+ for epoch in range(EPOCHS):
864
+ if _should_skip("punctuation", stage_n, epoch):
865
+ print(f"\n[INFO] SKIP: punctuation n={stage_n} ep={epoch} (already done)")
866
+ continue
867
+ # Generate stage samples (cumulative)
868
+ new_samples = generate_punctuation_samples(tokenizer, stage_n, MAX_SEQ_LEN)
869
+ cumulative_punct.extend(new_samples)
870
+ # Use up to stage_n samples (replace if too many)
871
+ random.shuffle(cumulative_punct)
872
+ train_samples = cumulative_punct[:stage_n]
873
+ # Make a small val set
874
+ val_samples = train_samples[-max(2, stage_n // 10):]
875
+ train_samples = train_samples[:-max(2, stage_n // 10)]
876
+
877
+ for epoch in range(EPOCHS):
878
+ if _should_skip("punctuation", stage_n, epoch):
879
+ continue
880
+ stage_result = train_stage(
881
+ model=model, optimizer=optimizer, pipeline=pipeline,
882
+ meta_cfg=meta_cfg, ewc=ewc, mtp=mtp, rep_penalty=rep_penalty,
883
+ monitor=monitor, mcq_eval=mcq_eval,
884
+ train_samples=train_samples, val_samples=val_samples,
885
+ stage_name=f"punctuation", stage_n=stage_n, epoch=epoch,
886
+ )
887
+ evolution.append(stage_result)
888
+ # Incremental save (in case of crash)
889
+ _save_partial_report(evolution, n_params, "punctuation", stage_n, epoch)
890
+
891
+ # EWC consolidate after each punctuation stage
892
+ try:
893
+ with torch.enable_grad():
894
+ cons_input = torch.stack([s["input_ids"] for s in train_samples[:BATCH_SIZE]])
895
+ cons_target = torch.stack([s["target"] for s in train_samples[:BATCH_SIZE]])
896
+ def ewc_criterion(logits, target):
897
+ if logits.dim() == 2 and target.dim() == 2:
898
+ target = target[:, -1]
899
+ return F.cross_entropy(logits, target, ignore_index=-100)
900
+ ewc.consolidate(cons_input, cons_target, criterion=ewc_criterion, n_samples=1)
901
+ except Exception as e:
902
+ print(f" [WARN] EWC consolidate failed: {e}")
903
+
904
+ # Delete binaries between stages
905
+ cleanup_binaries()
906
+
907
+ # === TEXT STAGES ===
908
+ print(f"\n[INFO] === TEXTO STAGES ===")
909
+ for stage_n in TEXT_STAGES:
910
+ for epoch in range(EPOCHS):
911
+ if _should_skip("text", stage_n, epoch):
912
+ print(f"\n[INFO] SKIP: text n={stage_n} ep={epoch} (already done)")
913
+ continue
914
+ new_samples = generate_text_samples(tokenizer, stage_n, MAX_SEQ_LEN)
915
+ cumulative_text.extend(new_samples)
916
+ random.shuffle(cumulative_text)
917
+ train_samples = cumulative_text[:stage_n]
918
+ val_samples = train_samples[-max(2, stage_n // 10):]
919
+ train_samples = train_samples[:-max(2, stage_n // 10)]
920
+
921
+ for epoch in range(EPOCHS):
922
+ if _should_skip("text", stage_n, epoch):
923
+ continue
924
+ stage_result = train_stage(
925
+ model=model, optimizer=optimizer, pipeline=pipeline,
926
+ meta_cfg=meta_cfg, ewc=ewc, mtp=mtp, rep_penalty=rep_penalty,
927
+ monitor=monitor, mcq_eval=mcq_eval,
928
+ train_samples=train_samples, val_samples=val_samples,
929
+ stage_name=f"text", stage_n=stage_n, epoch=epoch,
930
+ )
931
+ evolution.append(stage_result)
932
+ _save_partial_report(evolution, n_params, "text", stage_n, epoch)
933
+
934
+ # EWC consolidate
935
+ try:
936
+ with torch.enable_grad():
937
+ cons_input = torch.stack([s["input_ids"] for s in train_samples[:BATCH_SIZE]])
938
+ cons_target = torch.stack([s["target"] for s in train_samples[:BATCH_SIZE]])
939
+ def ewc_criterion_t(logits, target):
940
+ if logits.dim() == 2 and target.dim() == 2:
941
+ target = target[:, -1]
942
+ return F.cross_entropy(logits, target, ignore_index=-100)
943
+ ewc.consolidate(cons_input, cons_target, criterion=ewc_criterion_t, n_samples=1)
944
+ except Exception as e:
945
+ print(f" [WARN] EWC consolidate failed: {e}")
946
+
947
+ cleanup_binaries()
948
+
949
+ # === HEAVY STAGES ===
950
+ print(f"\n[INFO] === PESADOS STAGES ===")
951
+ for stage_n in HEAVY_STAGES:
952
+ for epoch in range(EPOCHS):
953
+ if _should_skip("heavy", stage_n, epoch):
954
+ print(f"\n[INFO] SKIP: heavy n={stage_n} ep={epoch} (already done)")
955
+ continue
956
+ new_samples = generate_heavy_samples(tokenizer, stage_n, MAX_SEQ_LEN)
957
+ cumulative_heavy.extend(new_samples)
958
+ random.shuffle(cumulative_heavy)
959
+ train_samples = cumulative_heavy[:stage_n]
960
+ val_samples = train_samples[-max(2, stage_n // 10):]
961
+ train_samples = train_samples[:-max(2, stage_n // 10)]
962
+
963
+ for epoch in range(EPOCHS):
964
+ if _should_skip("heavy", stage_n, epoch):
965
+ continue
966
+ stage_result = train_stage(
967
+ model=model, optimizer=optimizer, pipeline=pipeline,
968
+ meta_cfg=meta_cfg, ewc=ewc, mtp=mtp, rep_penalty=rep_penalty,
969
+ monitor=monitor, mcq_eval=mcq_eval,
970
+ train_samples=train_samples, val_samples=val_samples,
971
+ stage_name=f"heavy", stage_n=stage_n, epoch=epoch,
972
+ )
973
+ evolution.append(stage_result)
974
+ _save_partial_report(evolution, n_params, "heavy", stage_n, epoch)
975
+
976
+ # EWC consolidate
977
+ try:
978
+ with torch.enable_grad():
979
+ cons_input = torch.stack([s["input_ids"] for s in train_samples[:BATCH_SIZE]])
980
+ cons_target = torch.stack([s["target"] for s in train_samples[:BATCH_SIZE]])
981
+ def ewc_criterion_h(logits, target):
982
+ if logits.dim() == 2 and target.dim() == 2:
983
+ target = target[:, -1]
984
+ return F.cross_entropy(logits, target, ignore_index=-100)
985
+ ewc.consolidate(cons_input, cons_target, criterion=ewc_criterion_h, n_samples=1)
986
+ except Exception as e:
987
+ print(f" [WARN] EWC consolidate failed: {e}")
988
+
989
+ cleanup_binaries()
990
+
991
+ # 5. Final summary
992
+ print(f"\n{'=' * 72}")
993
+ print(f" EVOLUÇÃO COMPLETA")
994
+ print(f"{'=' * 72}")
995
+ print(f" {'stage':<14} {'n':>4} {'ep':>3} {'val_loss':>10} {'ppl':>10} {'eval_acc':>10} {'rss_mb':>8} {'tflops':>8}")
996
+ print(f" {'-'*14} {'-'*4} {'-'*3} {'-'*10} {'-'*10} {'-'*10} {'-'*8} {'-'*8}")
997
+ for e in evolution:
998
+ print(f" {e['stage']:<14} {e['n_samples']:>4} {e['epoch']:>3} "
999
+ f"{e['val_loss']:>10.4f} {e['perplexity']:>10.2f} "
1000
+ f"{e['eval_acc']*100:>9.2f}% {e['final_rss_mb']:>8.0f} {e['avg_tflops']:>8.4f}")
1001
+
1002
+ final_summary = monitor.summary()
1003
+ final_lp = {
1004
+ "T": float(torch.exp(meta_cfg.log_temperature.detach()).item()),
1005
+ "tau": float(torch.exp(meta_cfg.log_tau.detach()).item()),
1006
+ "lambda_ent": float(torch.exp(model.log_lambda_ent.detach()).item()) if hasattr(model, "log_lambda_ent") else None,
1007
+ "init_gate": float(model.circular_reasoning.residual_gate.mean().item()) if hasattr(model, "circular_reasoning") else None,
1008
+ "mtp_alphas": [float(x) for x in mtp.alphas.tolist()] if mtp.K > 1 else [],
1009
+ "rep_penalty_lambda": float(rep_penalty.lambda_val.item()),
1010
+ "ewc_lambda": float(ewc.lambda_val.item()),
1011
+ "rlhf_eta": float(rlhf_mapping.eta.item()),
1012
+ }
1013
+ final_summary["final_learnable_params"] = final_lp
1014
+ final_summary["n_w8a8_layers"] = sum(1 for m in model.modules() if "QuantizedLinear" in type(m).__name__ or "SmoothQuantW8A8" in type(m).__name__)
1015
+
1016
+ print(f"\n[INFO] Final learnable params:")
1017
+ for k, v in final_lp.items():
1018
+ print(f" {k}: {v}")
1019
+
1020
+ # 6. Report
1021
+ report = {
1022
+ "version": "V6_progressive",
1023
+ "timestamp": time.time(),
1024
+ "config": {
1025
+ "epochs": EPOCHS,
1026
+ "batch_size": BATCH_SIZE,
1027
+ "max_seq_len": MAX_SEQ_LEN,
1028
+ "num_layers_hyp": NUM_LAYERS_HYP,
1029
+ "stages_punctuation": PUNCTUATION_STAGES,
1030
+ "stages_text": TEXT_STAGES,
1031
+ "stages_heavy": HEAVY_STAGES,
1032
+ },
1033
+ "xeon_env": {
1034
+ "OMP_NUM_THREADS": os.environ.get("OMP_NUM_THREADS"),
1035
+ "ONEDNN_MAX_CPU_ISA": os.environ.get("ONEDNN_MAX_CPU_ISA"),
1036
+ "IPEX": HAS_IPEX,
1037
+ "IPEX_VERSION": IPEX_VERSION,
1038
+ "torch_version": torch.__version__,
1039
+ "torch_threads": torch.get_num_threads(),
1040
+ "onednn_enabled": torch.backends.mkldnn.enabled,
1041
+ },
1042
+ "evolution": evolution,
1043
+ "final_summary": final_summary,
1044
+ "n_params": n_params,
1045
+ }
1046
+ report_path = PROJECT_DIR / "BiGRU_T_version" / "v6_progressive_report.json"
1047
+ report_path.write_text(json.dumps(report, indent=2, ensure_ascii=False, default=str))
1048
+ print(f"\n[INFO] Report saved: {report_path}")
1049
+
1050
+ # Final cleanup of binaries
1051
+ cleanup_binaries()
1052
+ print(f"\n[INFO] V6 progressive training complete. {len(evolution)} stages captured.")
1053
+
1054
+
1055
+ if __name__ == "__main__":
1056
+ main()