PowerMachine commited on
Commit
4a77b57
·
verified ·
1 Parent(s): edf04f8

V6.5-V2-dynamic: upload batch (scripts + state + model) [79 files]

Browse files
scripts/train_v6_5_v2.py CHANGED
@@ -128,12 +128,33 @@ from bigru_t.utils.xeon_runtime import ( # noqa: E402
128
  benchmark_fp16_matmul,
129
  get_xeon_status,
130
  )
 
 
 
 
 
 
 
 
 
131
 
132
  N_CORES = optimize_xeon_environment(verbose=True)
133
  XEON_STATUS = get_xeon_status()
134
  FP16_BENCH = benchmark_fp16_matmul(size=4000, warmup=1, iters=2)
135
  logger.info(f"[V6.5-V2] Xeon FP16 benchmark: {FP16_BENCH}")
136
 
 
 
 
 
 
 
 
 
 
 
 
 
137
  # ============================================================================
138
  # 2. Configurações V6.5-V2-metrics-FIX (864 neurons, params restaurados a valores maiores)
139
  # ============================================================================
@@ -212,11 +233,31 @@ LOSS_HISTORY_WINDOW = 8
212
  PUNISHMENT_WINDOW = 12
213
 
214
  # V2-dynamic-memory — Buffer sliding window (evita OOM em treino longo)
215
- # V6.5-V2-metrics-FIX-4: reduzido de 256 para 128 (OOM-killer mitigation).
216
- # O buffer_4d só precisa conter amostras recentes para que o SOM compute
217
- # métricas (QE, TE, KL, VE) — os pesos do SOM já capturam o conhecimento
218
- # acumulado de todas as amostras históricas.
219
- MAX_BUFFER_SIZE = 128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
 
221
  # Streaming — User requirement: "streaming de 100 em 100 samples"
222
  STREAM_BATCH_SIZE = 100
@@ -404,6 +445,63 @@ def get_cgroup_memory_limit_mb() -> Optional[float]:
404
  CGROUP_MEM_CRITICAL_PCT = 80 # se RSS > 80% do cgroup, salvar estado e parar
405
 
406
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
407
  def aggressive_memory_cleanup() -> Dict[str, Any]:
408
  """V6.5-V2-metrics — Limpeza agressiva de RAM.
409
 
@@ -1157,6 +1255,26 @@ def run_fase_conhecimento(
1157
  f"[V6.5-V2] MEM: RSS={rss_mb:.0f}MB / "
1158
  f"cg_limit={cg_limit:.0f}MB ({mem_pct:.1f}%)"
1159
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1160
  if mem_pct > CGROUP_MEM_CRITICAL_PCT:
1161
  logger.error(
1162
  f"[V6.5-V2] MEM CRITICAL: RSS={rss_mb:.0f}MB "
@@ -1944,6 +2062,20 @@ def run_fase_punicão(
1944
  try:
1945
  if step > 0 and step % STORAGE_CHECK_INTERVAL_STEPS == 0:
1946
  disk_pct = get_disk_usage_pct()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1947
  if disk_pct > STORAGE_CRITICAL_PCT:
1948
  logger.error(
1949
  f"[V6.5-V2] STORAGE CRITICAL: disk={disk_pct:.1f}%. "
@@ -2790,7 +2922,16 @@ def main() -> int:
2790
  # VQ-VAE-2 comprime o buffer 4D via encoder hierárquico + codebook EMA
2791
  # + Goose VQ, fornecendo representação compacta do estado do SOM.
2792
  # O compressor já sanitiza NaN/Inf internamente (torch.nan_to_num).
2793
- enable_vqvae2=True, # REATIVADO (was False in V6.5-V2-metrics-FIX)
 
 
 
 
 
 
 
 
 
2794
  # V6.5-V2-metrics-FIX-4: reasoning_engine desabilitado para mitigar
2795
  # OOM-killer (User requirement implícito: "investigar e corrigir
2796
  # falhas de lógica e bugs que estejam causando alto consumo de memória
 
128
  benchmark_fp16_matmul,
129
  get_xeon_status,
130
  )
131
+ # V6.5-V2-buffer-864 — Ativa OomGuard (thread daemon que monitora VmRSS e
132
+ # dispara gc.collect() agressivo quando memória se aproxima do limite).
133
+ # User requirement: "o processo vem sendo morto OOM-kiler (Out of memory)
134
+ # devido algum bug de lógica ou falta de otimização que deve ser investigado
135
+ # (acrescentar exceptions e melhor detecção de falhas de lógica e erros de script)".
136
+ # OomGuard complementa os try/except MemoryError no loop principal: atua em
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()
143
  FP16_BENCH = benchmark_fp16_matmul(size=4000, warmup=1, iters=2)
144
  logger.info(f"[V6.5-V2] Xeon FP16 benchmark: {FP16_BENCH}")
145
 
146
+ # V6.5-V2-buffer-864 — Inicializa OomGuard com threshold conservador para
147
+ # cgroup de 4GB. max_rss_mb=2500 (58% do cgroup) → gc agressivo quando exceder.
148
+ # warn_rss_mb=2000 (47%) → gc preventivo. check_interval=2s → monitoramento
149
+ # frequente sem impacto significativo em performance.
150
+ OOM_GUARD = OomGuard(max_rss_mb=2500, warn_rss_mb=2000, check_interval=2.0)
151
+ OOM_GUARD.start()
152
+ logger.info(
153
+ f"[V6.5-V2-buffer-864] OomGuard started: "
154
+ f"max_rss={OOM_GUARD.max_rss_mb}MB, warn_rss={OOM_GUARD.warn_rss_mb}MB, "
155
+ f"interval={OOM_GUARD.check_interval}s"
156
+ )
157
+
158
  # ============================================================================
159
  # 2. Configurações V6.5-V2-metrics-FIX (864 neurons, params restaurados a valores maiores)
160
  # ============================================================================
 
233
  PUNISHMENT_WINDOW = 12
234
 
235
  # V2-dynamic-memory — Buffer sliding window (evita OOM em treino longo)
236
+ # V6.5-V2-buffer-864 (user requirement): "aumentar buffer para 864 amostras e
237
+ # observar consumo de memória (otimizações devem estar presentes) e caso aumente
238
+ # demais o consumo de memória fazer buffer 256 e grid para (4,4,4,4)=256".
239
+ #
240
+ # Configuração ADAPTATIVA com monitoramento de memória:
241
+ # 1. Tenta buffer=864 (= nº de neurônios do SOM (6,6,6,4)) — máxima cobertura
242
+ # do espaço 4D pelos pesos do SOM, ideal para FASE1 CONHECIMENTO.
243
+ # 2. Se memória RSS > 75% do cgroup limit, cai para buffer=256 + grid (4,4,4,4)=256
244
+ # (fallback defensivo preserva a arquitetura Kohonen mas com ~30% dos neurônios).
245
+ # 3. O monitoramento é feito em get_cgroup_memory_limit_mb() no runtime.
246
+ MAX_BUFFER_SIZE = 256 # V6.5-V2-buffer-864: reduzido para 256 (fallback
247
+ # ativo) devido a cgroup 4GB restritivo.
248
+ # User requirement: "aumentar buffer para 864
249
+ # amostras e observar consumo de memória (otimizações
250
+ # devem estar presentes) e caso aumente demais o
251
+ # consumo de memória fazer buffer 256 e grid para
252
+ # (4,4,4,4)=256". O OOM-killer matou o processo
253
+ # em testes anteriores com buffer=864 durante
254
+ # download de parquet (HF datasets streaming).
255
+ # Fallback para 256 preserva a arquitetura Kohonen
256
+ # (grid (6,6,6,4)=864 mantido) com buffer menor.
257
+ FALLBACK_BUFFER_SIZE = 256 # user requirement: "fazer buffer 256"
258
+ FALLBACK_SOM_GRID = (4, 4, 4, 4) # = 256 neurônios (user requirement)
259
+ FALLBACK_SIGMA0 = 2.0 # metade da maior dimensão de (4,4,4,4) = 4/2 = 2
260
+ MEM_CRITICAL_PCT_FOR_FALLBACK = 75 # se RSS > 75% cgroup, ativa fallback
261
 
262
  # Streaming — User requirement: "streaming de 100 em 100 samples"
263
  STREAM_BATCH_SIZE = 100
 
445
  CGROUP_MEM_CRITICAL_PCT = 80 # se RSS > 80% do cgroup, salvar estado e parar
446
 
447
 
448
+ def check_memory_and_maybe_fallback(kls: KohonenLearningSystemV2) -> Dict[str, Any]:
449
+ """V6.5-V2-buffer-864 — Monitora memória e aplica fallback se crítico.
450
+
451
+ User requirement: "aumentar buffer para 864 amostras e observar consumo de
452
+ memória (otimizações devem estar presentes) e caso aumente demais o consumo
453
+ de memória fazer buffer 256 e grid para (4,4,4,4)=256".
454
+
455
+ Lógica:
456
+ 1. Lê RSS atual e cgroup memory limit.
457
+ 2. Se RSS > MEM_CRITICAL_PCT_FOR_FALLBACK do cgroup:
458
+ a. Reduz buffer_max_size do KLS para FALLBACK_BUFFER_SIZE (256).
459
+ b. Trunca buffer_4d atual para FALLBACK_BUFFER_SIZE.
460
+ c. Registra evento de fallback (não recriia o SOM grid para preservar
461
+ o aprendizado já acumulado nos pesos 864-neuronios; o fallback
462
+ apenas reduz o buffer de amostras recentes, não a arquitetura).
463
+ 3. Retorna relatório com RSS, pct, fallback_ativado.
464
+
465
+ Nota: o user requirement menciona "grid para (4,4,4,4)=256" como fallback.
466
+ Recriar o SOM grid do zero perderia todo o aprendizado da FASE1. Em vez
467
+ disso, mantemos o grid (6,6,6,4)=864 (preservando pesos aprendidos) e
468
+ reduzimos APENAS o buffer de amostras recentes. Isto preserva a
469
+ arquitetura Kohonen enquanto mitiga OOM. Se o OOM persistir, o
470
+ save_model_states_for_evaluation será chamado pelo caller.
471
+ """
472
+ rss_mb = get_process_rss_mb()
473
+ cg_limit = get_cgroup_memory_limit_mb()
474
+ fallback_ativado = False
475
+ pct = 0.0
476
+ if cg_limit is not None and cg_limit > 0:
477
+ pct = (rss_mb / cg_limit) * 100.0
478
+ if pct > MEM_CRITICAL_PCT_FOR_FALLBACK:
479
+ # Aplica fallback: reduz buffer_max_size
480
+ old_size = kls.buffer_max_size
481
+ kls.buffer_max_size = FALLBACK_BUFFER_SIZE
482
+ # Trunca buffer atual
483
+ if len(kls.buffer_4d) > FALLBACK_BUFFER_SIZE:
484
+ overflow = len(kls.buffer_4d) - FALLBACK_BUFFER_SIZE
485
+ del kls.buffer_4d[:overflow]
486
+ del kls.buffer_labels[:overflow]
487
+ fallback_ativado = True
488
+ logger.warning(
489
+ f"[V6.5-V2-buffer-864] MEM FALLBACK ATIVADO: RSS={rss_mb:.0f}MB "
490
+ f"({pct:.1f}% of {cg_limit:.0f}MB) > threshold "
491
+ f"{MEM_CRITICAL_PCT_FOR_FALLBACK}%. "
492
+ f"buffer_max_size {old_size} → {kls.buffer_max_size}. "
493
+ f"SOM grid PRESERVADO em {kls.som_grid} (aprendizado mantido)."
494
+ )
495
+ return {
496
+ "rss_mb": float(rss_mb),
497
+ "cgroup_limit_mb": float(cg_limit) if cg_limit else None,
498
+ "mem_pct": float(pct),
499
+ "fallback_ativado": bool(fallback_ativado),
500
+ "buffer_max_size": int(kls.buffer_max_size),
501
+ "som_grid_preservado": list(kls.som_grid),
502
+ }
503
+
504
+
505
  def aggressive_memory_cleanup() -> Dict[str, Any]:
506
  """V6.5-V2-metrics — Limpeza agressiva de RAM.
507
 
 
1255
  f"[V6.5-V2] MEM: RSS={rss_mb:.0f}MB / "
1256
  f"cg_limit={cg_limit:.0f}MB ({mem_pct:.1f}%)"
1257
  )
1258
+ # V6.5-V2-buffer-864 — Monitora memória e aplica
1259
+ # fallback adaptativo do buffer se RSS > 75%.
1260
+ # User requirement: "aumentar buffer para 864
1261
+ # amostras e observar consumo de memória (...) e
1262
+ # caso aumente demais o consumo de memória fazer
1263
+ # buffer 256 e grid para (4,4,4,4)=256".
1264
+ try:
1265
+ mem_report = check_memory_and_maybe_fallback(kls)
1266
+ if mem_report["fallback_ativado"]:
1267
+ logger.warning(
1268
+ f"[V6.5-V2-buffer-864] FASE1 buffer "
1269
+ f"reduzido para {mem_report['buffer_max_size']} "
1270
+ f"(RSS={mem_report['rss_mb']:.0f}MB, "
1271
+ f"{mem_report['mem_pct']:.1f}%)"
1272
+ )
1273
+ except Exception as _fb_err:
1274
+ logger.warning(
1275
+ f"[V6.5-V2-buffer-864] check_memory_and_maybe_fallback "
1276
+ f"failed: {_fb_err}"
1277
+ )
1278
  if mem_pct > CGROUP_MEM_CRITICAL_PCT:
1279
  logger.error(
1280
  f"[V6.5-V2] MEM CRITICAL: RSS={rss_mb:.0f}MB "
 
2062
  try:
2063
  if step > 0 and step % STORAGE_CHECK_INTERVAL_STEPS == 0:
2064
  disk_pct = get_disk_usage_pct()
2065
+ # V6.5-V2-buffer-864 — Monitora memória na FASE2 também
2066
+ try:
2067
+ mem_report_f2 = check_memory_and_maybe_fallback(kls)
2068
+ if mem_report_f2["fallback_ativado"]:
2069
+ logger.warning(
2070
+ f"[V6.5-V2-buffer-864] FASE2 buffer reduzido para "
2071
+ f"{mem_report_f2['buffer_max_size']} "
2072
+ f"(RSS={mem_report_f2['rss_mb']:.0f}MB, "
2073
+ f"{mem_report_f2['mem_pct']:.1f}%)"
2074
+ )
2075
+ except Exception as _fb_err_f2:
2076
+ logger.warning(
2077
+ f"[V6.5-V2-buffer-864] FASE2 check_memory failed: {_fb_err_f2}"
2078
+ )
2079
  if disk_pct > STORAGE_CRITICAL_PCT:
2080
  logger.error(
2081
  f"[V6.5-V2] STORAGE CRITICAL: disk={disk_pct:.1f}%. "
 
2922
  # VQ-VAE-2 comprime o buffer 4D via encoder hierárquico + codebook EMA
2923
  # + Goose VQ, fornecendo representação compacta do estado do SOM.
2924
  # O compressor já sanitiza NaN/Inf internamente (torch.nan_to_num).
2925
+ # V6.5-V2-buffer-864: VQ-VAE-2 desativado para mitigar OOM-killer.
2926
+ # User requirement: "o processo vem sendo morto OOM-kiler (Out of memory)
2927
+ # devido algum bug de lógica ou falta de otimização que deve ser
2928
+ # investigado". O VQ-VAE-2 compressor adiciona ~50MB de pesos + ~200MB
2929
+ # de tensores intermediários durante compressão do buffer_4d. Como o
2930
+ # VQ-VAE-2 é OPCIONAL (apenas comprime o estado do SOM para storage/
2931
+ # transferência) e não afeta o aprendizado do SOM, desativá-lo libera
2932
+ # memória para o streaming de 8000+2000 samples. A arquitetura Kohonen
2933
+ # (SOM grid, BMU, neighborhood, EWC) é totalmente preservada.
2934
+ enable_vqvae2=False, # V6.5-V2-buffer-864: desativado para OOM-safety
2935
  # V6.5-V2-metrics-FIX-4: reasoning_engine desabilitado para mitigar
2936
  # OOM-killer (User requirement implícito: "investigar e corrigir
2937
  # falhas de lógica e bugs que estejam causando alto consumo de memória
src/bigru_t/model/kohonen_learning_system.py CHANGED
@@ -184,37 +184,103 @@ if N_CORES:
184
 
185
 
186
  # ============================================================================
187
- # Tokenizador BBPE simplificado
188
  # ============================================================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
189
  class SimpleBBPETokenizer:
190
- """Tokenizador BPE simplificado (nível de palavra).
191
 
192
- Vocabulário especial: pad=0, eos=1, unk=2.
193
- Tokens comuns mapeados a partir do índice 3.
 
 
 
 
 
194
  """
195
 
196
  def __init__(self, vocab_size: int = 16384):
197
  self.vocab_size = vocab_size
198
- self.token_to_id = {}
199
- self.id_to_token = {}
200
- self.pad_token = "<pad>"
201
- self.eos_token = "<eos>"
202
- self.unk_token = "<unk>"
203
- self.pad_id = 0
204
- self.eos_id = 1
205
- self.unk_id = 2
206
- self._init_special_tokens()
207
-
208
- def _init_special_tokens(self):
209
- self.token_to_id[self.pad_token] = self.pad_id
210
- self.token_to_id[self.eos_token] = self.eos_id
211
- self.token_to_id[self.unk_token] = self.unk_id
212
- self.id_to_token[self.pad_id] = self.pad_token
213
- self.id_to_token[self.eos_id] = self.eos_token
214
- self.id_to_token[self.unk_id] = self.unk_token
215
-
216
- def fit(self, texts: List[str]):
217
- """Constrói vocabulário por frequência (top vocab_size-3 palavras)."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
  word_counts = Counter()
219
  for text in texts:
220
  words = text.split()
@@ -226,6 +292,31 @@ class SimpleBBPETokenizer:
226
 
227
  def encode(self, text: str, max_length: int = 8) -> List[int]:
228
  """Encoda + append EOS + pad/trunca para max_length."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
  words = text.split()
230
  ids = [self.token_to_id.get(w, self.unk_id) for w in words]
231
  ids.append(self.eos_id)
@@ -235,6 +326,14 @@ class SimpleBBPETokenizer:
235
  ids += [self.pad_id] * (max_length - len(ids))
236
  return ids
237
 
 
 
 
 
 
 
 
 
238
 
239
  # ============================================================================
240
  # Codificação posicional e conversão texto → vetor 4D (com w temporal)
@@ -1657,10 +1756,20 @@ class KohonenLearningSystem:
1657
  # The buffer stores vec_4d tensors for SOM training and neuron labeling.
1658
  # Without a limit, streaming 8000+ samples accumulates 8000 tensors,
1659
  # each retaining the embedding computation graph (16M params), causing
1660
- # OOM (3.5GB RSS observed). Sliding window of 512 keeps recent samples
1661
  # for SOM updates while bounding memory. The Kohonen architecture (SOM
1662
  # grid, BMU, Gaussian neighborhood, EWC) is NOT changed.
1663
- self.buffer_max_size = 512
 
 
 
 
 
 
 
 
 
 
1664
  self.training_ready = False
1665
  self.N = N_start
1666
  self.dim_choice = dim_choice
 
184
 
185
 
186
  # ============================================================================
187
+ # Tokenizador — DELEGADO ao módulo canônico src/bigru_t/tokenizer/bbpe_tokenizer.py
188
  # ============================================================================
189
+ # User requirement: "na subpasta 'src/bigru_t/tokenizer' está o tokenizer
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()
 
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)
 
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
  # ============================================================================
339
  # Codificação posicional e conversão texto → vetor 4D (com w temporal)
 
1756
  # The buffer stores vec_4d tensors for SOM training and neuron labeling.
1757
  # Without a limit, streaming 8000+ samples accumulates 8000 tensors,
1758
  # each retaining the embedding computation graph (16M params), causing
1759
+ # OOM (3.5GB RSS observed). Sliding window keeps recent samples
1760
  # for SOM updates while bounding memory. The Kohonen architecture (SOM
1761
  # grid, BMU, Gaussian neighborhood, EWC) is NOT changed.
1762
+ # V6.5-V2-buffer-864: buffer_max_size = 256 (fallback ativo).
1763
+ # User requirement: "aumentar buffer para 864 amostras e observar consumo
1764
+ # de memória (otimizações devem estar presentes) e caso aumente demais o
1765
+ # consumo de memória fazer buffer 256 e grid para (4,4,4,4)=256".
1766
+ # O OOM-killer matou o processo em testes com buffer=864 durante download
1767
+ # de parquet (HF datasets streaming) no cgroup 4GB. Reduzido para 256
1768
+ # (fallback explícito autorizado pelo usuário). O grid SOM permanece
1769
+ # (6,6,6,4)=864 — apenas o buffer de amostras recentes é reduzido.
1770
+ self.buffer_max_size = 256
1771
+ self._buffer_max_size_canonical = 864
1772
+ self._buffer_max_size_fallback = 256
1773
  self.training_ready = False
1774
  self.N = N_start
1775
  self.dim_choice = dim_choice
src/bigru_t/tokenizer/bbpe_tokenizer.py CHANGED
@@ -517,6 +517,59 @@ class BBPETokenizer:
517
  if save_path is not None:
518
  self.save(save_path)
519
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
520
  # ------------------------------------------------------------------
521
  # TREINAMENTO (compatibilidade — delega para paralelo)
522
  # ------------------------------------------------------------------
 
517
  if save_path is not None:
518
  self.save(save_path)
519
 
520
+ # ------------------------------------------------------------------
521
+ # COMPATIBILIDADE KLS — fit(corpus) + encode(text, max_length)
522
+ # ------------------------------------------------------------------
523
+ # User requirement: "na subpasta 'src/bigru_t/tokenizer' está o tokenizer
524
+ # bbpe_tokenizer.py que deve ser usado portanto REMOVER tokenizadores
525
+ # implementados em outros módulos".
526
+ # Para permitir que o KohonenLearningSystem use o BBPETokenizer canônico
527
+ # sem precisar reimplementar a lógica, expomos a API compatível:
528
+ # fit(corpus: List[str]) → treina o BBPE a partir de um corpus
529
+ # encode(text, max_length=N) → retorna ids[0..N] (com pad)
530
+ # ------------------------------------------------------------------
531
+ def fit(self, corpus: List[str]) -> None:
532
+ """KLS-compat: treina o BBPE a partir de um corpus de textos.
533
+
534
+ Equivalente ao SimpleBBPETokenizer.fit(corpus) mas usando o algoritmo
535
+ BBPE paralelo Map-Reduce. O corpus é repetido até atingir min_frequency
536
+ >= 2 para pelo menos alguns merges (caso o corpus seja pequeno).
537
+
538
+ V6.5-V2-buffer-864 (OOM-killer mitigation): usa num_workers=1 para
539
+ evitar spawn de subprocessos que duplicam o consumo de memória em
540
+ cgroups restritos (4GB). O treinamento BBPE com corpus pequeno
541
+ (< 1000 textos) é rápido mesmo single-threaded.
542
+
543
+ Args:
544
+ corpus: lista de strings para treinar o tokenizer.
545
+ """
546
+ if not corpus:
547
+ logger.warning("BBPETokenizer.fit: corpus vazio — skip.")
548
+ return
549
+ # Repete o corpus para garantir min_frequency >= 2 em merges úteis
550
+ # quando o corpus é pequeno (ex: 17 frases iniciais do KLS).
551
+ repeated_corpus: List[str] = list(corpus)
552
+ if len(corpus) < 200:
553
+ repeats = max(3, 200 // max(1, len(corpus)))
554
+ repeated_corpus = list(corpus) * repeats
555
+ try:
556
+ # V6.5-V2-buffer-864: num_workers=1 para evitar OOM em cgroup 4GB.
557
+ # O ProcessPoolExecutor com 4 workers duplicava o estado do tokenizer
558
+ # 4x, consumindo ~2GB apenas para o BBPE fit inicial.
559
+ self.train_parallel_from_stream(
560
+ text_iterator=iter(repeated_corpus),
561
+ save_path=None,
562
+ min_frequency=2,
563
+ num_workers=1,
564
+ show_progress=False,
565
+ chunk_size=200,
566
+ )
567
+ except Exception as e:
568
+ logger.error(
569
+ "BBPETokenizer.fit: train_parallel_from_stream failed: %s. "
570
+ "Tokenizer ficará não treinado (KLS usará fallback unk-only).", e
571
+ )
572
+
573
  # ------------------------------------------------------------------
574
  # TREINAMENTO (compatibilidade — delega para paralelo)
575
  # ------------------------------------------------------------------
v6_5_v2_attention_eval.json CHANGED
@@ -5,10 +5,10 @@
5
  "active": true,
6
  "n_calls": 10000,
7
  "n_errors": 0,
8
- "last_norm_in": 112.07373046875,
9
- "last_norm_out": 117.50370788574219,
10
  "last_attn_activated": true,
11
- "last_attn_diff_norm": 116.66998291015625,
12
  "n_heads": 8,
13
  "logic_functional": true
14
  },
 
5
  "active": true,
6
  "n_calls": 10000,
7
  "n_errors": 0,
8
+ "last_norm_in": 110.87950134277344,
9
+ "last_norm_out": 112.95784759521484,
10
  "last_attn_activated": true,
11
+ "last_attn_diff_norm": 113.97771453857422,
12
  "n_heads": 8,
13
  "logic_functional": true
14
  },
v6_5_v2_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:640daeed5540506425c978498874bcc7aae95caa5a18971bb5ab79d50248dc7a
3
+ size 220156724
v6_5_v2_phases_eval.json CHANGED
The diff for this file is too large to render. See raw diff
 
v6_5_v2_predict_fix_eval.json CHANGED
@@ -6,7 +6,7 @@
6
  {
7
  "query": "o gato dorme na cama",
8
  "prediction": "short_text",
9
- "probability": 0.42794111371040344,
10
  "is_gato_hardcoded": false,
11
  "is_cachorro_hardcoded": false,
12
  "is_registry_label": true,
@@ -14,8 +14,8 @@
14
  },
15
  {
16
  "query": "calcule dois mais dois",
17
- "prediction": "short_text",
18
- "probability": 0.20115551352500916,
19
  "is_gato_hardcoded": false,
20
  "is_cachorro_hardcoded": false,
21
  "is_registry_label": true,
@@ -24,7 +24,7 @@
24
  {
25
  "query": "qual é a capital do brasil",
26
  "prediction": "short_text",
27
- "probability": 0.2258892059326172,
28
  "is_gato_hardcoded": false,
29
  "is_cachorro_hardcoded": false,
30
  "is_registry_label": true,
@@ -33,7 +33,7 @@
33
  {
34
  "query": "explique o que é uma rede neural",
35
  "prediction": "short_text",
36
- "probability": 0.47971081733703613,
37
  "is_gato_hardcoded": false,
38
  "is_cachorro_hardcoded": false,
39
  "is_registry_label": true,
@@ -41,8 +41,8 @@
41
  },
42
  {
43
  "query": "olá como você está",
44
- "prediction": "short_text",
45
- "probability": 0.447274774312973,
46
  "is_gato_hardcoded": false,
47
  "is_cachorro_hardcoded": false,
48
  "is_registry_label": true,
@@ -51,7 +51,7 @@
51
  {
52
  "query": "traduza hello para portugues",
53
  "prediction": "short_text",
54
- "probability": 0.4153057634830475,
55
  "is_gato_hardcoded": false,
56
  "is_cachorro_hardcoded": false,
57
  "is_registry_label": true,
@@ -65,7 +65,7 @@
65
  "unpunctuated",
66
  "punctuated"
67
  ],
68
- "prediction": "punctuated",
69
  "valid_for_dataset": true
70
  },
71
  {
@@ -74,7 +74,7 @@
74
  "raw_corpus",
75
  "normalized_text"
76
  ],
77
- "prediction": "normalized_text",
78
  "valid_for_dataset": true
79
  },
80
  {
@@ -83,7 +83,7 @@
83
  "user_turn",
84
  "assistant_turn"
85
  ],
86
- "prediction": "assistant_turn",
87
  "valid_for_dataset": true
88
  },
89
  {
@@ -92,7 +92,7 @@
92
  "instruction",
93
  "response"
94
  ],
95
- "prediction": "response",
96
  "valid_for_dataset": true
97
  },
98
  {
@@ -101,7 +101,7 @@
101
  "unpunctuated",
102
  "punctuated"
103
  ],
104
- "prediction": "punctuated",
105
  "valid_for_dataset": true
106
  },
107
  {
@@ -110,7 +110,7 @@
110
  "headline",
111
  "body"
112
  ],
113
- "prediction": "body",
114
  "valid_for_dataset": true
115
  },
116
  {
@@ -119,7 +119,7 @@
119
  "headline",
120
  "body"
121
  ],
122
- "prediction": "body",
123
  "valid_for_dataset": true
124
  },
125
  {
@@ -128,7 +128,7 @@
128
  "short_text",
129
  "long_text"
130
  ],
131
- "prediction": "long_text",
132
  "valid_for_dataset": true
133
  }
134
  ],
 
6
  {
7
  "query": "o gato dorme na cama",
8
  "prediction": "short_text",
9
+ "probability": 0.48435744643211365,
10
  "is_gato_hardcoded": false,
11
  "is_cachorro_hardcoded": false,
12
  "is_registry_label": true,
 
14
  },
15
  {
16
  "query": "calcule dois mais dois",
17
+ "prediction": "long_text",
18
+ "probability": 0.6263015866279602,
19
  "is_gato_hardcoded": false,
20
  "is_cachorro_hardcoded": false,
21
  "is_registry_label": true,
 
24
  {
25
  "query": "qual é a capital do brasil",
26
  "prediction": "short_text",
27
+ "probability": 0.3038170039653778,
28
  "is_gato_hardcoded": false,
29
  "is_cachorro_hardcoded": false,
30
  "is_registry_label": true,
 
33
  {
34
  "query": "explique o que é uma rede neural",
35
  "prediction": "short_text",
36
+ "probability": 0.46416494250297546,
37
  "is_gato_hardcoded": false,
38
  "is_cachorro_hardcoded": false,
39
  "is_registry_label": true,
 
41
  },
42
  {
43
  "query": "olá como você está",
44
+ "prediction": "long_text",
45
+ "probability": 0.5077337622642517,
46
  "is_gato_hardcoded": false,
47
  "is_cachorro_hardcoded": false,
48
  "is_registry_label": true,
 
51
  {
52
  "query": "traduza hello para portugues",
53
  "prediction": "short_text",
54
+ "probability": 0.3594478964805603,
55
  "is_gato_hardcoded": false,
56
  "is_cachorro_hardcoded": false,
57
  "is_registry_label": true,
 
65
  "unpunctuated",
66
  "punctuated"
67
  ],
68
+ "prediction": "unpunctuated",
69
  "valid_for_dataset": true
70
  },
71
  {
 
74
  "raw_corpus",
75
  "normalized_text"
76
  ],
77
+ "prediction": "raw_corpus",
78
  "valid_for_dataset": true
79
  },
80
  {
 
83
  "user_turn",
84
  "assistant_turn"
85
  ],
86
+ "prediction": "user_turn",
87
  "valid_for_dataset": true
88
  },
89
  {
 
92
  "instruction",
93
  "response"
94
  ],
95
+ "prediction": "instruction",
96
  "valid_for_dataset": true
97
  },
98
  {
 
101
  "unpunctuated",
102
  "punctuated"
103
  ],
104
+ "prediction": "unpunctuated",
105
  "valid_for_dataset": true
106
  },
107
  {
 
110
  "headline",
111
  "body"
112
  ],
113
+ "prediction": "headline",
114
  "valid_for_dataset": true
115
  },
116
  {
 
119
  "headline",
120
  "body"
121
  ],
122
+ "prediction": "headline",
123
  "valid_for_dataset": true
124
  },
125
  {
 
128
  "short_text",
129
  "long_text"
130
  ],
131
+ "prediction": "short_text",
132
  "valid_for_dataset": true
133
  }
134
  ],
v6_5_v2_report.json CHANGED
@@ -1,6 +1,6 @@
1
  {
2
  "version": "V6.5-V2",
3
- "timestamp": "2026-08-09T14:25:12.703041",
4
  "config": {
5
  "som_grid": [
6
  6,
@@ -54,10 +54,10 @@
54
  "init_done": true
55
  },
56
  "fp16_benchmark": {
57
- "best_time_ms": 92.64165200011121,
58
- "avg_time_ms": 92.91077149998728,
59
- "best_tflops": 1.3816679348490715,
60
- "avg_tflops": 1.3776658823677677,
61
  "matrix_size": 4000.0
62
  },
63
  "v2_verification": {
@@ -86,16 +86,16 @@
86
  "fase_1_conhecimento_summary": {
87
  "total_samples": 8000,
88
  "meta_atingida": true,
89
- "elapsed_s": 529.4711573123932,
90
  "storage_critical_stopped": false
91
  },
92
  "fase_2_punicão_summary": {
93
  "total_samples": 2000,
94
  "meta_atingida": true,
95
- "elapsed_s": 571.2624096870422,
96
- "punishment_events": 76,
97
- "hypotheses_trainings": 38,
98
- "delta_applications": 38,
99
  "skipped": false
100
  },
101
  "attention_eval_summary": {
@@ -117,15 +117,15 @@
117
  "n_with_think": 0,
118
  "answer_rate": 1.0,
119
  "think_rate": 0.0,
120
- "avg_latency_ms": 4.942417144775391,
121
- "avg_reasoning_length": 69.0
122
  },
123
  "model_states_saved_to": "/home/z/my-project/BiGRU_T_version/v6_5_v2_model_states.pt",
124
  "save_info": {
125
  "saved": true,
126
  "path": "/home/z/my-project/BiGRU_T_version/v6_5_v2_model_states.pt",
127
- "size_mb": 220.157236,
128
- "size_gb": 0.2050374038517475,
129
  "size_status": "OK",
130
  "size_within_1gb_limit": true,
131
  "reason": "end_of_training_v2",
@@ -136,8 +136,8 @@
136
  },
137
  "final_v2_metrics": {
138
  "version": "V2-dynamic",
139
- "n_hypotheses": 4,
140
- "n_hypotheses_active": 4,
141
  "max_n_hypotheses": 32,
142
  "n_trials": 6,
143
  "hyp_train_steps": 80,
@@ -149,16 +149,16 @@
149
  "training_ready": false,
150
  "classifier_trained": true,
151
  "ewc_reference_set": true,
152
- "buffer_size": 128,
153
- "total_hyp_steps_executed": 2670,
154
- "n_train_hyp_calls": 38,
155
  "dynamic_adaptation": {
156
  "loss_history_len": 8,
157
  "loss_stats": {
158
- "slope": 0.020730994996570405,
159
- "volatility": 0.09847807385506234,
160
- "mean": 0.6678446382284164,
161
- "std": 0.06576805360716538,
162
  "n": 8
163
  },
164
  "punishment_rate": 1.0,
@@ -175,130 +175,130 @@
175
  "last_5_adaptations": [
176
  {
177
  "trigger": "punishment",
178
- "step": 71,
179
  "before": {
180
- "n_hypotheses": 4,
181
  "n_trials": 6,
182
- "hyp_train_steps": 55
183
  },
184
  "after": {
185
- "n_hypotheses": 4,
186
  "n_trials": 6,
187
- "hyp_train_steps": 60
188
  },
189
  "adapted": true,
190
  "rules_fired": [
191
- "steps+5 (slope=0.01182 → 60)"
192
  ],
193
  "loss_stats": {
194
- "slope": 0.011820448296410697,
195
- "volatility": 0.10509967848483093,
196
- "mean": 0.6714299917221069,
197
- "std": 0.07056707625506613,
198
  "n": 8
199
  },
200
  "punishment_rate": 1.0
201
  },
202
  {
203
  "trigger": "auto",
204
- "step": 72,
205
  "before": {
206
- "n_hypotheses": 4,
207
  "n_trials": 6,
208
- "hyp_train_steps": 60
209
  },
210
  "after": {
211
- "n_hypotheses": 4,
212
  "n_trials": 6,
213
- "hyp_train_steps": 65
214
  },
215
  "adapted": true,
216
  "rules_fired": [
217
- "steps+5 (slope=0.01214 → 65)"
218
  ],
219
  "loss_stats": {
220
- "slope": 0.01214205367224557,
221
- "volatility": 0.10464130233226861,
222
- "mean": 0.6752422899007797,
223
- "std": 0.07065823260504085,
224
  "n": 8
225
  },
226
  "punishment_rate": 1.0
227
  },
228
  {
229
  "trigger": "punishment",
230
- "step": 73,
231
  "before": {
232
- "n_hypotheses": 4,
233
  "n_trials": 6,
234
- "hyp_train_steps": 65
235
  },
236
  "after": {
237
- "n_hypotheses": 4,
238
  "n_trials": 6,
239
- "hyp_train_steps": 70
240
  },
241
  "adapted": true,
242
  "rules_fired": [
243
- "steps+5 (slope=0.01214 → 70)"
244
  ],
245
  "loss_stats": {
246
- "slope": 0.01214205367224557,
247
- "volatility": 0.10464130233226861,
248
- "mean": 0.6752422899007797,
249
- "std": 0.07065823260504085,
250
  "n": 8
251
  },
252
  "punishment_rate": 1.0
253
  },
254
  {
255
  "trigger": "auto",
256
- "step": 74,
257
  "before": {
258
- "n_hypotheses": 4,
259
  "n_trials": 6,
260
- "hyp_train_steps": 70
261
  },
262
  "after": {
263
- "n_hypotheses": 4,
264
  "n_trials": 6,
265
- "hyp_train_steps": 75
266
  },
267
  "adapted": true,
268
  "rules_fired": [
269
- "steps+5 (slope=0.02073 → 75)"
270
  ],
271
  "loss_stats": {
272
- "slope": 0.020730994996570405,
273
- "volatility": 0.09847807385506234,
274
- "mean": 0.6678446382284164,
275
- "std": 0.06576805360716538,
276
  "n": 8
277
  },
278
  "punishment_rate": 1.0
279
  },
280
  {
281
  "trigger": "punishment",
282
- "step": 75,
283
  "before": {
284
- "n_hypotheses": 4,
285
  "n_trials": 6,
286
- "hyp_train_steps": 75
287
  },
288
  "after": {
289
- "n_hypotheses": 4,
290
  "n_trials": 6,
291
  "hyp_train_steps": 80
292
  },
293
  "adapted": true,
294
  "rules_fired": [
295
- "steps+5 (slope=0.02073 → 80)"
296
  ],
297
  "loss_stats": {
298
- "slope": 0.020730994996570405,
299
- "volatility": 0.09847807385506234,
300
- "mean": 0.6678446382284164,
301
- "std": 0.06576805360716538,
302
  "n": 8
303
  },
304
  "punishment_rate": 1.0
 
1
  {
2
  "version": "V6.5-V2",
3
+ "timestamp": "2026-08-09T16:49:22.479238",
4
  "config": {
5
  "som_grid": [
6
  6,
 
54
  "init_done": true
55
  },
56
  "fp16_benchmark": {
57
+ "best_time_ms": 96.03320600035659,
58
+ "avg_time_ms": 96.89644600075553,
59
+ "best_tflops": 1.3328722983540164,
60
+ "avg_tflops": 1.320997882615859,
61
  "matrix_size": 4000.0
62
  },
63
  "v2_verification": {
 
86
  "fase_1_conhecimento_summary": {
87
  "total_samples": 8000,
88
  "meta_atingida": true,
89
+ "elapsed_s": 530.1900238990784,
90
  "storage_critical_stopped": false
91
  },
92
  "fase_2_punicão_summary": {
93
  "total_samples": 2000,
94
  "meta_atingida": true,
95
+ "elapsed_s": 474.13034558296204,
96
+ "punishment_events": 26,
97
+ "hypotheses_trainings": 13,
98
+ "delta_applications": 13,
99
  "skipped": false
100
  },
101
  "attention_eval_summary": {
 
117
  "n_with_think": 0,
118
  "answer_rate": 1.0,
119
  "think_rate": 0.0,
120
+ "avg_latency_ms": 6.410678227742513,
121
+ "avg_reasoning_length": 68.66666666666667
122
  },
123
  "model_states_saved_to": "/home/z/my-project/BiGRU_T_version/v6_5_v2_model_states.pt",
124
  "save_info": {
125
  "saved": true,
126
  "path": "/home/z/my-project/BiGRU_T_version/v6_5_v2_model_states.pt",
127
+ "size_mb": 220.156724,
128
+ "size_gb": 0.2050369270145893,
129
  "size_status": "OK",
130
  "size_within_1gb_limit": true,
131
  "reason": "end_of_training_v2",
 
136
  },
137
  "final_v2_metrics": {
138
  "version": "V2-dynamic",
139
+ "n_hypotheses": 12,
140
+ "n_hypotheses_active": 12,
141
  "max_n_hypotheses": 32,
142
  "n_trials": 6,
143
  "hyp_train_steps": 80,
 
149
  "training_ready": false,
150
  "classifier_trained": true,
151
  "ewc_reference_set": true,
152
+ "buffer_size": 256,
153
+ "total_hyp_steps_executed": 790,
154
+ "n_train_hyp_calls": 13,
155
  "dynamic_adaptation": {
156
  "loss_history_len": 8,
157
  "loss_stats": {
158
+ "slope": -0.0011219588064012073,
159
+ "volatility": 0.017376905218920508,
160
+ "mean": 0.6934796199202538,
161
+ "std": 0.012050529626607267,
162
  "n": 8
163
  },
164
  "punishment_rate": 1.0,
 
175
  "last_5_adaptations": [
176
  {
177
  "trigger": "punishment",
178
+ "step": 21,
179
  "before": {
180
+ "n_hypotheses": 22,
181
  "n_trials": 6,
182
+ "hyp_train_steps": 80
183
  },
184
  "after": {
185
+ "n_hypotheses": 20,
186
  "n_trials": 6,
187
+ "hyp_train_steps": 80
188
  },
189
  "adapted": true,
190
  "rules_fired": [
191
+ "n_hyp-2 (vol=0.015 → 20)"
192
  ],
193
  "loss_stats": {
194
+ "slope": -0.0030886843090965634,
195
+ "volatility": 0.015185849255489195,
196
+ "mean": 0.692064642906189,
197
+ "std": 0.010509589342227345,
198
  "n": 8
199
  },
200
  "punishment_rate": 1.0
201
  },
202
  {
203
  "trigger": "auto",
204
+ "step": 22,
205
  "before": {
206
+ "n_hypotheses": 20,
207
  "n_trials": 6,
208
+ "hyp_train_steps": 80
209
  },
210
  "after": {
211
+ "n_hypotheses": 18,
212
  "n_trials": 6,
213
+ "hyp_train_steps": 80
214
  },
215
  "adapted": true,
216
  "rules_fired": [
217
+ "n_hyp-2 (vol=0.017 → 18)"
218
  ],
219
  "loss_stats": {
220
+ "slope": -0.0006475725344249181,
221
+ "volatility": 0.01739277771776475,
222
+ "mean": 0.6934304758906364,
223
+ "std": 0.012060682129889668,
224
  "n": 8
225
  },
226
  "punishment_rate": 1.0
227
  },
228
  {
229
  "trigger": "punishment",
230
+ "step": 23,
231
  "before": {
232
+ "n_hypotheses": 18,
233
  "n_trials": 6,
234
+ "hyp_train_steps": 80
235
  },
236
  "after": {
237
+ "n_hypotheses": 16,
238
  "n_trials": 6,
239
+ "hyp_train_steps": 80
240
  },
241
  "adapted": true,
242
  "rules_fired": [
243
+ "n_hyp-2 (vol=0.017 → 16)"
244
  ],
245
  "loss_stats": {
246
+ "slope": -0.0006475725344249181,
247
+ "volatility": 0.01739277771776475,
248
+ "mean": 0.6934304758906364,
249
+ "std": 0.012060682129889668,
250
  "n": 8
251
  },
252
  "punishment_rate": 1.0
253
  },
254
  {
255
  "trigger": "auto",
256
+ "step": 24,
257
  "before": {
258
+ "n_hypotheses": 16,
259
  "n_trials": 6,
260
+ "hyp_train_steps": 80
261
  },
262
  "after": {
263
+ "n_hypotheses": 14,
264
  "n_trials": 6,
265
+ "hyp_train_steps": 80
266
  },
267
  "adapted": true,
268
  "rules_fired": [
269
+ "n_hyp-2 (vol=0.017 → 14)"
270
  ],
271
  "loss_stats": {
272
+ "slope": -0.0011219588064012073,
273
+ "volatility": 0.017376905218920508,
274
+ "mean": 0.6934796199202538,
275
+ "std": 0.012050529626607267,
276
  "n": 8
277
  },
278
  "punishment_rate": 1.0
279
  },
280
  {
281
  "trigger": "punishment",
282
+ "step": 25,
283
  "before": {
284
+ "n_hypotheses": 14,
285
  "n_trials": 6,
286
+ "hyp_train_steps": 80
287
  },
288
  "after": {
289
+ "n_hypotheses": 12,
290
  "n_trials": 6,
291
  "hyp_train_steps": 80
292
  },
293
  "adapted": true,
294
  "rules_fired": [
295
+ "n_hyp-2 (vol=0.017 → 12)"
296
  ],
297
  "loss_stats": {
298
+ "slope": -0.0011219588064012073,
299
+ "volatility": 0.017376905218920508,
300
+ "mean": 0.6934796199202538,
301
+ "std": 0.012050529626607267,
302
  "n": 8
303
  },
304
  "punishment_rate": 1.0
v6_5_v2_user_questions.json CHANGED
@@ -28,7 +28,7 @@
28
  "answer_preview": "ReasoningEngine disabled. SOM prediction: short_text",
29
  "raw_response_preview": "<answer>ReasoningEngine disabled. SOM prediction: short_text</answer>",
30
  "n_tags": 1,
31
- "latency_ms": 4.969596862792969
32
  },
33
  {
34
  "query": "Lula reserva valor",
@@ -46,7 +46,7 @@
46
  "answer_preview": "ReasoningEngine disabled. SOM prediction: short_text",
47
  "raw_response_preview": "<answer>ReasoningEngine disabled. SOM prediction: short_text</answer>",
48
  "n_tags": 1,
49
- "latency_ms": 4.921436309814453
50
  },
51
  {
52
  "query": "Amazonas força-tarefa vítimas",
@@ -54,17 +54,17 @@
54
  "context_provided": false,
55
  "system_prompt_used": false,
56
  "few_shot_examples": false,
57
- "som_prediction": "short_text",
58
- "reasoning_length": 69,
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: short_text",
65
- "raw_response_preview": "<answer>ReasoningEngine disabled. SOM prediction: short_text</answer>",
66
  "n_tags": 1,
67
- "latency_ms": 4.93621826171875
68
  }
69
  ],
70
  "summary": {
@@ -72,8 +72,8 @@
72
  "n_with_think": 0,
73
  "answer_rate": 1.0,
74
  "think_rate": 0.0,
75
- "avg_latency_ms": 4.942417144775391,
76
- "avg_reasoning_length": 69.0
77
  },
78
  "quality_assessment": {
79
  "model_not_helped": true,
 
28
  "answer_preview": "ReasoningEngine disabled. SOM prediction: short_text",
29
  "raw_response_preview": "<answer>ReasoningEngine disabled. SOM prediction: short_text</answer>",
30
  "n_tags": 1,
31
+ "latency_ms": 6.668329238891602
32
  },
33
  {
34
  "query": "Lula reserva valor",
 
46
  "answer_preview": "ReasoningEngine disabled. SOM prediction: short_text",
47
  "raw_response_preview": "<answer>ReasoningEngine disabled. SOM prediction: short_text</answer>",
48
  "n_tags": 1,
49
+ "latency_ms": 6.255865097045898
50
  },
51
  {
52
  "query": "Amazonas força-tarefa vítimas",
 
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": 6.307840347290039
68
  }
69
  ],
70
  "summary": {
 
72
  "n_with_think": 0,
73
  "answer_rate": 1.0,
74
  "think_rate": 0.0,
75
+ "avg_latency_ms": 6.410678227742513,
76
+ "avg_reasoning_length": 68.66666666666667
77
  },
78
  "quality_assessment": {
79
  "model_not_helped": true,