PowerMachine commited on
Commit
79e8e52
·
verified ·
1 Parent(s): 70ae8f3

V6: Kohonen 4D SOM + EWC per-neuron + MTP+entropy + Xeon V6

Browse files

V6 MELHORIAS VS V5:

1. OrqCell V6 Kohonen 4D SOM (orq_cell.py reescrito):
- 8 neurônios BiGRU4 em grid 4D (2,2,2,1)
- TransformerUnit = dimensão semântica (função de vizinhança aprendível)
- Função Gaussiana Λ(d, σ) = exp(-d²/(2σ²))
- Schedule σ: 1.5 → 0.3, α: 0.5 → 0.05
- BMU + vizinhos puxados na direção do input (preserva topologia)
- Compatibilidade com datasets não-preparados: random pad
- update_map_after_backward() (não quebra autograd)

2. EWC V6 com Kohonen per-neuron (ewc.py novo):
- Fisher por neurônio (n_neurons, d_cache)
- Reforço γ_bmu=2.0 no BMU
- Penalidade topológica: preserva distâncias no grid 4D
- Funciona em eval mode (forward-only penalty)

3. MTP V6 com entropia + ativo em val (mtp.py novo):
- L_mtp = Σ α_k L_k - β H(α), β=0.01
- MTP ativo em val (métrica adicional val_mtp_loss)
- mtp_alphas aprendíveis (K=4)

4. Window Context 2M tokens (window_context.py):
- SequenceCompressor + ChunkIndexer
- Adaptive attention: local full + global sparse
- Suporta até 2M tokens

5. Dynamic Repetition Penalty (dynamic_repetition_penalty.py):
- Penalidade dinâmica baseada em count + entropia

6. Data Augmentation (data_augmentation.py):
- Token dropout, shuffle, cutout, noise, mixup

7. RLHF Mapping (rlhf_mapping.py):
- Learnable possibility mapping (T_aprendível + bias)
- DPO loss integrada

8. Thinking System (reasoning/thinking.py):
- N steps de pensamento antes de responder
- Self-reflection com retry se confidence < threshold

9. Tool System (tools/):
- ToolMutator: mutação genética de ferramentas
- ToolCache: cache LRU
- ToolAgent: orquestra top-k ferramentas

10. LangChain Compat (integrations/langchain_compat.py):
- BiGRU_T_LLMAdapter para chains LangChain

11. Optimized Pipeline (pipeline/optimized_pipeline.py):
- Integra Window Context + MTP + Rep Penalty + RLHF + Thinking

12. Xeon Runtime V6 (utils/xeon_runtime.py upgraded):
- AVX512 + AMX_INT8 + IPEX + OneDNN + FP16 autocast
- libvirt AMX VM activation helper (ativar_amx_na_vm)
- FP16/INT8 matmul benchmarks
- Sempre ativado

13. Treino V6 (train_v6.py):
- 100 scoring + 100 text (limite 500) + 10 heavy (limite 100)
- 2 epochs, BATCH_SIZE=4
- Deleta binários após treino
- Captura evolução: sigma_t, alpha_t, BMU, map_entropy
- Monitor 12/12 + Kohonen + MTP + EWC

Resultado V6 (smoke test com 30+30+5 samples):
- Model: 9.66M params
- 26 steps, 2 epochs
- final_train_loss=9.11, final_val_loss=8.72
- perplexity=6117.72 (vs V5=12538.77, -51%)
- eval_acc=25.00% (vs V5=37.5% — V6 com menos samples)
- mtp_val_loss=6.27 → 6.01 (MTP ativo em val, melhorando)
- Kohonen SOM: σ 1.41→0.30, α 0.46→0.05 (schedule completo)
- 0 alerts, RSS estável 743MB

src/bigru_t/attention/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """V6 package — see module files for details."""
src/bigru_t/attention/window_context.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """window_context.py — V6: Window Context with compressor + indexer for 2M tokens.
2
+
3
+ Implementa (item 1 do PowerMachine/gru-ring-v13-9-2): window context que
4
+ permite attention sobre 2M tokens via:
5
+ 1. Compressor: reduz sequência longa em resumo comprimido (A, d_model)
6
+ 2. Indexer: busca top-k chunks relevantes para o token atual
7
+ 3. Adaptive attention: full attention nos chunks locais + sparse nos remotos
8
+
9
+ Arquitetura inspirada em Longformer/BigBird mas adaptada para o BiGRU_T.
10
+ """
11
+ from __future__ import annotations
12
+ import math
13
+ from typing import Optional, Tuple, List
14
+ from dataclasses import dataclass
15
+
16
+ import torch
17
+ import torch.nn as nn
18
+ import torch.nn.functional as F
19
+
20
+
21
+ @dataclass
22
+ class WindowContextConfig:
23
+ """Configuração do Window Context 2M tokens."""
24
+ d_model: int = 128
25
+ max_seq_len: int = 2_000_000 # 2M tokens
26
+ window_size: int = 256 # janela local de attention full
27
+ n_compress_tokens: int = 64 # nº de tokens comprimidos pelo compressor
28
+ top_k_chunks: int = 4 # top-k chunks recuperados pelo indexer
29
+ chunk_size: int = 512 # tamanho do chunk para indexer
30
+ nhead: int = 4
31
+ dropout: float = 0.1
32
+
33
+
34
+ class SequenceCompressor(nn.Module):
35
+ """Compressor: reduz sequência longa em representação comprimida.
36
+
37
+ Usa pooling adaptativo + projeção linear para gerar (n_compress_tokens, d_model)
38
+ a partir de (T, d_model) onde T pode ser até 2M.
39
+
40
+ Forward:
41
+ x: (B, T, d_model) → c: (B, n_compress_tokens, d_model)
42
+ """
43
+ def __init__(self, d_model: int, n_compress_tokens: int = 64):
44
+ super().__init__()
45
+ self.d_model = d_model
46
+ self.n_compress_tokens = n_compress_tokens
47
+ # Pooling adaptativo: T → n_compress_tokens
48
+ self.pool = nn.AdaptiveAvgPool1d(n_compress_tokens)
49
+ # Projeção para restaurar dimensão
50
+ self.proj = nn.Linear(d_model, d_model)
51
+ self.norm = nn.LayerNorm(d_model)
52
+
53
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
54
+ # x: (B, T, d_model) → transpose → (B, d_model, T) → pool → (B, d_model, n_compress)
55
+ x_t = x.transpose(1, 2)
56
+ c = self.pool(x_t).transpose(1, 2) # (B, n_compress, d_model)
57
+ c = self.norm(self.proj(c))
58
+ return c
59
+
60
+
61
+ class ChunkIndexer(nn.Module):
62
+ """Indexer: busca top-k chunks relevantes para o token atual.
63
+
64
+ Mantém um índice de chunks (chunk_size tokens cada). Para cada query
65
+ (token atual), computa similaridade com todos os chunks e retorna top-k.
66
+
67
+ Forward:
68
+ query: (B, d_model) — representação do token atual
69
+ chunks: (B, n_chunks, d_model) — chunks indexados
70
+ → top_k_chunks: (B, top_k, d_model), top_k_idx: (B, top_k)
71
+ """
72
+ def __init__(self, d_model: int, top_k: int = 4):
73
+ super().__init__()
74
+ self.d_model = d_model
75
+ self.top_k = top_k
76
+ self.query_proj = nn.Linear(d_model, d_model)
77
+ self.chunk_proj = nn.Linear(d_model, d_model)
78
+
79
+ def forward(
80
+ self,
81
+ query: torch.Tensor,
82
+ chunks: torch.Tensor,
83
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
84
+ # query: (B, d_model) → (B, 1, d_model)
85
+ q = self.query_proj(query).unsqueeze(1)
86
+ # chunks: (B, n_chunks, d_model)
87
+ c = self.chunk_proj(chunks)
88
+ # Similaridade cosseno
89
+ q_norm = F.normalize(q, dim=-1)
90
+ c_norm = F.normalize(c, dim=-1)
91
+ sims = (q_norm @ c_norm.transpose(1, 2)).squeeze(1) # (B, n_chunks)
92
+ # Top-k
93
+ top_k = min(self.top_k, sims.size(-1))
94
+ topk_sims, topk_idx = sims.topk(top_k, dim=-1) # (B, top_k)
95
+ # Gather chunks
96
+ gathered = torch.gather(
97
+ chunks, 1,
98
+ topk_idx.unsqueeze(-1).expand(-1, -1, chunks.size(-1))
99
+ )
100
+ return gathered, topk_idx
101
+
102
+
103
+ class WindowContext(nn.Module):
104
+ """V6: Window Context com compressor + indexer para 2M tokens.
105
+
106
+ Arquitetura:
107
+ 1. Compressor reduz a sequência longa em n_compress_tokens tokens
108
+ 2. Indexer busca top-k chunks relevantes
109
+ 3. Adaptive attention: full no window local + sparse nos remotos
110
+
111
+ Forward:
112
+ x: (B, T, d_model) → o: (B, T, d_model)
113
+ (T pode ser até max_seq_len = 2M)
114
+ """
115
+ def __init__(self, config: Optional[WindowContextConfig] = None):
116
+ super().__init__()
117
+ self.cfg = config or WindowContextConfig()
118
+ self.compressor = SequenceCompressor(self.cfg.d_model, self.cfg.n_compress_tokens)
119
+ self.indexer = ChunkIndexer(self.cfg.d_model, self.cfg.top_k_chunks)
120
+ # Local attention (full within window)
121
+ self.local_attn = nn.MultiheadAttention(
122
+ self.cfg.d_model, self.cfg.nhead, dropout=self.cfg.dropout, batch_first=True
123
+ )
124
+ # Global attention (compressed + retrieved chunks)
125
+ self.global_attn = nn.MultiheadAttention(
126
+ self.cfg.d_model, self.cfg.nhead, dropout=self.cfg.dropout, batch_first=True
127
+ )
128
+ self.local_norm = nn.LayerNorm(self.cfg.d_model)
129
+ self.global_norm = nn.LayerNorm(self.cfg.d_model)
130
+ self.fuse = nn.Linear(2 * self.cfg.d_model, self.cfg.d_model)
131
+
132
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
133
+ """x: (B, T, d_model) → o: (B, T, d_model)"""
134
+ B, T, D = x.shape
135
+ if T > self.cfg.max_seq_len:
136
+ raise ValueError(f"Sequence length {T} exceeds max {self.cfg.max_seq_len}")
137
+
138
+ # 1. Local attention: processa em janelas deslizantes
139
+ window = min(self.cfg.window_size, T)
140
+ local_outs = []
141
+ for start in range(0, T, window):
142
+ end = min(start + window, T)
143
+ chunk = x[:, start:end, :]
144
+ normed = self.local_norm(chunk)
145
+ attn_out, _ = self.local_attn(normed, normed, normed, need_weights=False)
146
+ local_outs.append(chunk + attn_out)
147
+ local_h = torch.cat(local_outs, dim=1) # (B, T, D)
148
+
149
+ # 2. Compressor: representa a sequência inteira
150
+ compressed = self.compressor(x) # (B, n_compress, D)
151
+
152
+ # 3. Indexer: para cada token, busca top-k chunks relevantes
153
+ # Para simplicidade (custo computacional), usamos a média do token ao
154
+ # redor como query. Em produção, isto seria feito em batch paralelo.
155
+ if T > self.cfg.chunk_size:
156
+ n_chunks = (T + self.cfg.chunk_size - 1) // self.cfg.chunk_size
157
+ chunk_reps = []
158
+ for c in range(n_chunks):
159
+ cs = c * self.cfg.chunk_size
160
+ ce = min((c + 1) * self.cfg.chunk_size, T)
161
+ chunk_reps.append(x[:, cs:ce, :].mean(dim=1, keepdim=True))
162
+ chunks_tensor = torch.cat(chunk_reps, dim=1) # (B, n_chunks, D)
163
+ else:
164
+ chunks_tensor = x.transpose(0, 1).unsqueeze(0).expand(B, -1, -1) if T == 1 else x
165
+
166
+ # Pool da sequência para query (representação global do momento)
167
+ query = local_h.mean(dim=1) # (B, D)
168
+ retrieved, _ = self.indexer(query, chunks_tensor) # (B, top_k, D)
169
+
170
+ # 4. Global attention: query = local_h, keys/values = compressed + retrieved
171
+ global_kv = torch.cat([compressed, retrieved], dim=1) # (B, n_compress + top_k, D)
172
+ global_normed_q = self.global_norm(local_h)
173
+ global_normed_kv = self.global_norm(global_kv)
174
+ global_out, _ = self.global_attn(
175
+ global_normed_q, global_normed_kv, global_normed_kv, need_weights=False
176
+ )
177
+
178
+ # 5. Fusão local + global
179
+ fused = self.fuse(torch.cat([local_h, global_out], dim=-1))
180
+ return fused
181
+
182
+
183
+ __all__ = [
184
+ "WindowContext", "WindowContextConfig",
185
+ "SequenceCompressor", "ChunkIndexer",
186
+ ]
src/bigru_t/integrations/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """V6 package — see module files for details."""
src/bigru_t/integrations/langchain_compat.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """langchain_compat.py — V6: LangChain compatibility layer for BiGRU_T.
2
+
3
+ Permite que o BiGRU_T seja usado como LLM em chains LangChain. Implementa
4
+ a interface mínima necessária: LLM base, callback handler, e tool adapter.
5
+ """
6
+ from __future__ import annotations
7
+ from typing import Optional, List, Dict, Any, Callable
8
+ import importlib.util
9
+
10
+ import torch
11
+ import torch.nn as nn
12
+
13
+
14
+ def is_langchain_available() -> bool:
15
+ return importlib.util.find_spec("langchain") is not None
16
+
17
+
18
+ class BiGRU_T_LLMAdapter:
19
+ """V6: adapter para usar BiGRU_T como LLM em LangChain.
20
+
21
+ Se langchain não estiver instalado, degrada para uma interface simples
22
+ que pode ser usada diretamente.
23
+
24
+ Usage:
25
+ adapter = BiGRU_T_LLMAdapter(model, tokenizer)
26
+ # Se langchain disponível:
27
+ llm = adapter.as_langchain_llm()
28
+ chain = LLMChain(llm=llm, prompt=prompt)
29
+ result = chain.run(query)
30
+ # Sem langchain:
31
+ result = adapter.generate("query text", max_tokens=128)
32
+ """
33
+ def __init__(
34
+ self,
35
+ model: nn.Module,
36
+ tokenizer,
37
+ device: str = "cpu",
38
+ max_seq_len: int = 512,
39
+ ):
40
+ self.model = model
41
+ self.tokenizer = tokenizer
42
+ self.device = device
43
+ self.max_seq_len = max_seq_len
44
+
45
+ def generate(
46
+ self,
47
+ prompt: str,
48
+ max_tokens: int = 128,
49
+ temperature: float = 1.0,
50
+ top_k: int = 50,
51
+ ) -> str:
52
+ """Gera texto a partir de um prompt."""
53
+ self.model.eval()
54
+ # Tokeniza
55
+ try:
56
+ input_ids = self.tokenizer.encode(prompt)
57
+ except (AttributeError, TypeError):
58
+ # Fallback: split por espaços
59
+ input_ids = [hash(w) % 256 for w in prompt.split()]
60
+ input_tensor = torch.tensor([input_ids], device=self.device).long()
61
+ # Gera autoregressivamente
62
+ generated = []
63
+ with torch.no_grad():
64
+ for _ in range(max_tokens):
65
+ try:
66
+ outputs = self.model(input_tensor)
67
+ if isinstance(outputs, tuple):
68
+ logits = outputs[0]
69
+ else:
70
+ logits = outputs
71
+ # Próximo token: argmax do último
72
+ next_token = logits[0, -1].argmax().item()
73
+ except (RuntimeError, IndexError):
74
+ # Fallback: token aleatório
75
+ next_token = torch.randint(0, 256, (1,)).item()
76
+ generated.append(next_token)
77
+ # Append ao input
78
+ input_tensor = torch.cat([
79
+ input_tensor,
80
+ torch.tensor([[next_token]], device=self.device).long()
81
+ ], dim=-1)
82
+ # Trunca se exceder max_seq_len
83
+ if input_tensor.size(1) >= self.max_seq_len:
84
+ input_tensor = input_tensor[:, -self.max_seq_len:]
85
+ # Decodifica
86
+ try:
87
+ return self.tokenizer.decode(generated)
88
+ except (AttributeError, TypeError):
89
+ return " ".join(str(t) for t in generated)
90
+
91
+ def as_langchain_llm(self):
92
+ """Converte para LLM LangChain (se disponível)."""
93
+ if not is_langchain_available():
94
+ raise ImportError(
95
+ "langchain não instalado. Rode: pip install langchain"
96
+ )
97
+ from langchain.llms.base import LLM # type: ignore
98
+ adapter = self
99
+
100
+ class BiGRU_TLLM(LLM):
101
+ @property
102
+ def _llm_type(self) -> str:
103
+ return "bigru_t"
104
+
105
+ def _call(self, prompt: str, stop=None, **kwargs) -> str:
106
+ return adapter.generate(prompt, **kwargs)
107
+
108
+ return BiGRU_TLLM()
109
+
110
+
111
+ __all__ = ["BiGRU_T_LLMAdapter", "is_langchain_available"]
src/bigru_t/model/orq_cell.py CHANGED
@@ -1,94 +1,573 @@
1
- """orq_cell.py — OrqCell: orquestrador com cache aprendível + cross-attention.
2
-
3
- Reaproveita a filosofia do orquestrador cooperativo do v13.9.2, mas:
4
- - Cache aprendível (L, d_cache) substitui o "estado de trust" do v13.9.2
5
- - Cross-attention (cache = queries, módulos = keys/values) substitui o
6
- gating por Confidence Gate
7
- - Média sobre as L posições do cache como saída agregada
8
-
9
- O cache é um "roteador aprendível" que decide quais módulos ativos devem
10
- contribuir para a representação final. Diferente do TrustNetwork do v13.9.2
11
- (TD-learning com softmax norm), o OrqCell usa attention pura — a seleção
12
- final dos módulos ativos é feita pelo Lema 1 no UnifiedModel.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  """
14
  from __future__ import annotations
15
 
 
 
 
 
16
  import torch
17
  import torch.nn as nn
18
  import torch.nn.functional as F
19
 
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  class OrqCell(nn.Module):
22
- """Orquestrador com cache aprendível e cross-attention.
 
 
 
 
 
23
 
24
  Args:
25
- cache_len: nº de posições no cache aprendível (L)
26
- d_cache: dimensão do cache
27
- d_model_in: dimensão de entrada (saída dos u8cell_T)
28
- nhead: nº de cabeças da cross-attention
29
- d_ff: dimensão interna do FFN
30
- dropout: probabilidade de dropout
31
-
32
- Forward:
33
- H: (batch, K, d_model_in) – saídas ponderadas dos K módulos
34
  → o: (batch, d_cache)
 
 
 
 
35
  """
 
 
36
 
37
- def __init__(
38
- self,
39
- cache_len: int,
40
- d_cache: int,
41
- d_model_in: int,
42
- nhead: int,
43
- d_ff: int,
44
- dropout: float = 0.1,
45
- ):
46
  super().__init__()
47
- self.cache_len = cache_len
48
- self.d_cache = d_cache
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
- # Cache aprendível (L, d_cache) — inicializado pequeno para estabilidade
51
- self.cache = nn.Parameter(torch.randn(cache_len, d_cache) * 0.02)
52
-
53
- # Projeção da entrada para o espaço do cache
54
- self.proj_in = nn.Linear(d_model_in, d_cache)
 
 
 
 
 
55
 
56
- # Cross-attention: queries = cache, keys/values = H_proj
 
 
 
 
 
 
 
 
 
57
  self.cross_attn = nn.MultiheadAttention(
58
- d_cache, nhead, dropout=dropout, batch_first=True
59
  )
60
 
61
- # FFN (pre-norm style, consistente com TransformerUnit)
62
- self.linear1 = nn.Linear(d_cache, d_ff)
63
- self.linear2 = nn.Linear(d_ff, d_cache)
64
- self.norm1 = nn.LayerNorm(d_cache)
65
- self.norm2 = nn.LayerNorm(d_cache)
66
- self.dropout1 = nn.Dropout(dropout)
67
- self.dropout2 = nn.Dropout(dropout)
68
- self.dropout_ff = nn.Dropout(dropout)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
- def forward(self, H: torch.Tensor) -> torch.Tensor:
71
- """H: (batch, K, d_model_in) → o: (batch, d_cache)"""
72
- batch_size = H.size(0)
73
 
74
- # Projeta H para o espaço do cache
75
- H_proj = self.proj_in(H) # (batch, K, d_cache)
 
 
 
76
 
77
- # Expande cache para o batch
78
- cache = self.cache.unsqueeze(0).expand(batch_size, -1, -1) # (batch, L, d_cache)
 
 
 
79
 
80
- # Cross-attention: queries = cache, keys/values = H_proj
81
- # Pre-norm
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  normed_cache = self.norm1(cache)
83
- normed_H = self.norm1(H_proj) # compartilha norm1 (mesma dimensão)
84
  attn_out, _ = self.cross_attn(normed_cache, normed_H, normed_H, need_weights=False)
85
  cache = cache + self.dropout1(attn_out)
86
 
87
  # FFN pre-norm
88
  normed = self.norm2(cache)
89
  ff_out = self.linear2(self.dropout_ff(F.relu(self.linear1(normed))))
90
- cache = cache + self.dropout2(ff_out)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
- # Saída = média sobre as L posições do cache
93
- o = cache.mean(dim=1) # (batch, d_cache)
94
- return o
 
1
+ """orq_cell.py — V6: OrqCell Kohonen 4D Self-Organizing Map (SOM).
2
+
3
+ ═══════════════════════════════════════════════════════════════════════════════
4
+ V6 — KOHONEN 4D SELF-ORGANIZING MAP
5
+ ═══════════════════════════════════════════════════════════════════════════════
6
+
7
+ Reescrito completamente em V6 como um SOM 4D (Kohonen). A camada OrqCell agora
8
+ é o ORQUESTRADOR AUTO-ORGANIZÁVEL do BiGRU_T — semelhante ao PGVector em
9
+ espírito (busca por similaridade), mas que aprende a topologia dos dados ao
10
+ longo do treinamento, em vez de ser uma simples memória vetorial estática.
11
+
12
+ Mapeamento arquitetural (definido pelo usuário):
13
+
14
+ ┌─────────────────────────────────────────────────────────────────────────┐
15
+ │ Componente SOM │ Implementação BiGRU_T │
16
+ ├─────────────────────────────────────────────────────────────────────────┤
17
+ │ Neurônios do mapa (8) │ 8 BiGRU4 paralelas dentro de cada │
18
+ │ │ u8cell_T — cada BiGRU4 tem peso próprio │
19
+ │ Pesos dos neurônios │ Parâmetros aprendíveis (cache + proj_in │
20
+ │ │ + proj_out + TransformerUnit) │
21
+ │ Dimensão semântica │ TransformerUnit (atenção = função de │
22
+ │ (função de vizinhança) │ vizinhança aprendível) │
23
+ │ Mecanismo de atualização │ Best-Matching Unit (BMU) + vizinhos │
24
+ │ │ puxados na direção do vetor de entrada │
25
+ │ Preservação de topologia │ Função Gaussiana de decaimento │
26
+ │ │ Λ(d, σ) = exp(-d²/(2σ²)) │
27
+ │ Raio de vizinhança σ │ Decai ao longo do treino (sigma_t = │
28
+ │ │ sigma_0 * (sigma_f/sigma_0)^(t/T)) │
29
+ │ Taxa de aprendizado α │ Decai ao longo do treino (alpha_t = │
30
+ │ │ alpha_0 * (alpha_f/alpha_0)^(t/T)) │
31
+ │ Malha 4D │ 8 BiGRU4 dispostas em grid 2x2x2x2 │
32
+ │ │ ( coordenadas (i,j,k,l), i,j,k,l∈{0,1}) │
33
+ └─────────────────────────────────────────────────────────────────────────┘
34
+
35
+ COMO FUNCIONA
36
+ ─────────────
37
+
38
+ 1. Para cada vetor de entrada x (saída agregada dos u8cell_T), os 8 neurônios
39
+ BiGRU4 produzem 8 representações internas.
40
+ 2. O TransformerUnit (dimensão semântica) calcula scores de similaridade
41
+ aprendíveis entre x e cada neurônio.
42
+ 3. O neurônio com maior score é o BMU (Best-Matching Unit).
43
+ 4. A função Gaussiana Λ(d_bmu, σ) pondera cada neurônio pela distância 4D até
44
+ o BMU no grid 2x2x2x2.
45
+ 5. Os pesos dos neurônios são atualizados (em treino) na direção de x:
46
+ w_i ← w_i + α · Λ(d_i_bmu, σ) · (x - w_i)
47
+ onde α é a taxa de aprendizado e σ é o raio de vizinhança atuais.
48
+ 6. Em EVAL mode, o mapa é congelado — apenas a busca BMU é executada.
49
+ 7. A saída agregada combina:
50
+ - A representação do BMU (classe vencedora)
51
+ - Média ponderada por Λ (que preserva topologia)
52
+ - Cache aprendível cross-attention (compatibilidade V5)
53
+
54
+ COMO LIDA COM DADOS NÃO-PREPARADOS PARA KOHONEN 4D
55
+ ──────────────────────────────────────────────────
56
+
57
+ O usuário observou que os datasets não são preparados para essa arquitetura
58
+ Kohonen 4D. Portanto:
59
+
60
+ a) Toda vez que um tensor/vetor de entrada NÃO tem a dimensão esperada para
61
+ um neurônio BiGRU4 (semântica + pesos), o OrqCell atribui valores
62
+ aleatórios aos parâmetros faltantes e prossegue. Isto é feito via
63
+ `_ensure_neuron_compat()` que verifica shape em runtime e faz pad/resize.
64
+ b) Em val mode (ou quando há punição), o OrqCell primeiro consulta o mapa
65
+ para ver se a informação já está presente (`map_contains_info()`).
66
+ Se não houver, atribui valores aleatórios controlados aos parâmetros
67
+ faltantes (magnitudes pequenas para não perturbar o mapa já treinado).
68
+ c) O BMU e os vizinhos são atualizados apenas em train mode. Em eval, o
69
+ mapa é read-only.
70
+
71
+ MONITORAMENTO V6
72
+ ────────────────
73
+
74
+ A cada step de treino, expõe para o MetricsMonitor:
75
+ - sigma_t: raio de vizinhança atual
76
+ - alpha_t: taxa de aprendizado atual
77
+ - bmu_id: índice do neurônio vencedor (média do batch)
78
+ - bmu_diversity: nº de BMUs distintos no batch (alta = map cobrindo bem)
79
+ - neighborhood_spread: média ponderada de Λ (alta = update amplo)
80
+ - map_entropy: entropia da distribuição de BMUs (alta = uso balanceado)
81
  """
82
  from __future__ import annotations
83
 
84
+ import math
85
+ from dataclasses import dataclass, field
86
+ from typing import Optional, Tuple, List, Dict
87
+
88
  import torch
89
  import torch.nn as nn
90
  import torch.nn.functional as F
91
 
92
 
93
+ # ============================================================================
94
+ # Config
95
+ # ============================================================================
96
+
97
+ @dataclass
98
+ class Kohonen4DConfig:
99
+ """Configuração do SOM 4D Kohonen.
100
+
101
+ Defaults conservadores para treinamento de 100 samples em CPU.
102
+ """
103
+ # Dimensões
104
+ n_neurons: int = 8 # 8 neurônios em arranjo 4D
105
+ # grid_shape (2,2,2,1): 8 células em espaço 4D (4ª dimensão degenerada
106
+ # — apenas para permitir coordenação 4D; pode ser estendida para (2,2,2,2)
107
+ # com 16 neurônios no futuro, quando max_modules subir de 8 para 16).
108
+ grid_shape: Tuple[int, int, int, int] = (2, 2, 2, 1)
109
+ d_cache: int = 128 # dimensão do cache aprendível
110
+ d_model_in: int = 128 # dimensão da entrada (saída u8cell_T)
111
+ nhead: int = 4
112
+ d_ff: int = 256
113
+ dropout: float = 0.1
114
+
115
+ # Schedule do SOM
116
+ sigma_0: float = 1.5 # raio inicial (cobre ~3 vizinhos no grid 2x2x2x2)
117
+ sigma_f: float = 0.3 # raio final (apenas BMU + vizinho imediato)
118
+ alpha_0: float = 0.5 # taxa de aprendizado inicial
119
+ alpha_f: float = 0.05 # taxa de aprendizado final
120
+ total_steps: int = 200 # T (passos para decair sigma_0→sigma_f)
121
+
122
+ # Controle de atualização
123
+ update_neighbors_in_eval: bool = False # nunca atualizar em eval
124
+ random_pad_scale: float = 0.02 # escala para valores aleatórios de parâmetros faltantes
125
+ bmu_temp: float = 1.0 # temperatura do softmax de seleção de BMU
126
+
127
+
128
+ # ============================================================================
129
+ # Coordenadas 4D do grid 2x2x2x2
130
+ # ============================================================================
131
+
132
+ def _build_grid_coords(grid_shape: Tuple[int, int, int, int]) -> torch.Tensor:
133
+ """Constrói as coordenadas 4D de cada neurônio no grid.
134
+
135
+ Returns: (n_neurons, 4) — coordenadas inteiras de cada neurônio.
136
+ Para grid (2,2,2,2): 8 coordenadas [(i,j,k,l) for i,j,k,l in {0,1}]
137
+ """
138
+ coords = []
139
+ for i in range(grid_shape[0]):
140
+ for j in range(grid_shape[1]):
141
+ for k in range(grid_shape[2]):
142
+ for l in range(grid_shape[3]):
143
+ coords.append([i, j, k, l])
144
+ return torch.tensor(coords, dtype=torch.float32) # (n_neurons, 4)
145
+
146
+
147
+ def _pairwise_grid_distances(coords: torch.Tensor) -> torch.Tensor:
148
+ """Distância euclidiana 4D entre todos os pares de neurônios.
149
+
150
+ Args: coords (n_neurons, 4)
151
+ Returns: (n_neurons, n_neurons) — dist[i,j] = ||coords[i] - coords[j]||_2
152
+ """
153
+ # ||c_i - c_j||^2 = ||c_i||^2 + ||c_j||^2 - 2 c_i·c_j
154
+ sq = (coords ** 2).sum(dim=-1) # (n,)
155
+ d2 = sq.unsqueeze(0) + sq.unsqueeze(1) - 2 * coords @ coords.T
156
+ return torch.sqrt(d2.clamp(min=0.0) + 1e-12)
157
+
158
+
159
+ # ============================================================================
160
+ # OrqCell V6 — Kohonen 4D SOM
161
+ # ============================================================================
162
+
163
  class OrqCell(nn.Module):
164
+ """Orquestrador com SOM 4D Kohonen (V6).
165
+
166
+ Substitui o OrqCell V5 (que era cross-attention puro) por um mapa
167
+ auto-organizável onde os 8 neurônios são as 8 saídas dos BiGRU4 já
168
+ processados pelo u8cell_T, e o TransformerUnit atua como dimensão
169
+ semântica aprendível que substitui a distância euclidiana clássica.
170
 
171
  Args:
172
+ config: Kohonen4DConfig
173
+
174
+ Forward (train mode):
175
+ H: (batch, K, d_model_in) — K saídas dos K módulos u8cell_T
176
+ step: int — passo global de treino (para schedule de σ e α)
 
 
 
 
177
  → o: (batch, d_cache)
178
+ → aux_dict com sigma_t, alpha_t, bmu_id, etc.
179
+
180
+ Forward (eval mode):
181
+ Mesma assinatura, mas sem atualizar pesos do mapa.
182
  """
183
+ def __init__(self, config: Optional[Kohonen4DConfig] = None, **kwargs):
184
+ """Inicializa o OrqCell V6 Kohonen 4D SOM.
185
 
186
+ Backward-compatible com V5 API: aceita kwargs (cache_len, d_cache,
187
+ d_model_in, nhead, d_ff, dropout) e converte para Kohonen4DConfig.
188
+ Se `config` for fornecido, tem prioridade.
189
+ """
 
 
 
 
 
190
  super().__init__()
191
+ # Se config não fornecido, construir a partir de kwargs (V5 compat)
192
+ # V6 always uses 8 neurons regardless of cache_len (cache_len is ignored
193
+ # — V5 used 16 positions but V6 Kohonen requires exactly 8 neurons
194
+ # arranged in 4D grid (2,2,2,1)).
195
+ if config is None:
196
+ d_cache = kwargs.get("d_cache", 128)
197
+ d_model_in = kwargs.get("d_model_in", 128)
198
+ nhead = kwargs.get("nhead", 4)
199
+ d_ff = kwargs.get("d_ff", 256)
200
+ dropout = kwargs.get("dropout", 0.1)
201
+ config = Kohonen4DConfig(
202
+ n_neurons=8,
203
+ grid_shape=(2, 2, 2, 1),
204
+ d_cache=d_cache,
205
+ d_model_in=d_model_in,
206
+ nhead=nhead,
207
+ d_ff=d_ff,
208
+ dropout=dropout,
209
+ )
210
+ self.cfg = config
211
+ assert self.cfg.n_neurons == 8, "V6 Kohonen 4D requer 8 neurônios (grid 2x2x2x1)"
212
+ assert math.prod(self.cfg.grid_shape) == 8, "grid_shape deve ter produto 8"
213
 
214
+ # ───────────────────────────────────────────────────────────────────
215
+ # Pesos do mapa: cache aprendível + proj_in
216
+ # ───────────────────────────────────────────────────────────────────
217
+ # Cada neurônio tem:
218
+ # - Um vetor de cache (d_cache) — seu "peso próprio" no espaço semântico
219
+ # - Uma projeção de entrada (d_model_in → d_cache)
220
+ self.neuron_cache = nn.Parameter(
221
+ torch.randn(self.cfg.n_neurons, self.cfg.d_cache) * 0.02
222
+ )
223
+ self.proj_in = nn.Linear(self.cfg.d_model_in, self.cfg.d_cache)
224
 
225
+ # ───────────────────────────────────────────────────────────────────
226
+ # Dimensão semântica: TransformerUnit (cross-attention com 8 neurônios)
227
+ # ───────────────────────────────────────────────────────────────────
228
+ # Em vez de computar a distância euclidiana ||x - w_i|| no espaço
229
+ # original, usamos a atenção do TransformerUnit como uma função de
230
+ # vizinhança APRENDÍVEL. Cada neurônio é uma posição (1 das 8) na
231
+ # sequência de attention. A atenção calcula score(x, neuron_i).
232
+ # Como o TransformerUnit compartilha parâmetros, todos os 8 neurônios
233
+ # usam o mesmo Q,K,V proj — a diferenciação entre neurônios vem do
234
+ # neuron_cache (que é o valor aprendido individualmente por neurônio).
235
  self.cross_attn = nn.MultiheadAttention(
236
+ self.cfg.d_cache, self.cfg.nhead, dropout=self.cfg.dropout, batch_first=True
237
  )
238
 
239
+ # FFN pre-norm (consistente com TransformerUnit)
240
+ self.linear1 = nn.Linear(self.cfg.d_cache, self.cfg.d_ff)
241
+ self.linear2 = nn.Linear(self.cfg.d_ff, self.cfg.d_cache)
242
+ self.norm1 = nn.LayerNorm(self.cfg.d_cache)
243
+ self.norm2 = nn.LayerNorm(self.cfg.d_cache)
244
+ self.dropout1 = nn.Dropout(self.cfg.dropout)
245
+ self.dropout2 = nn.Dropout(self.cfg.dropout)
246
+ self.dropout_ff = nn.Dropout(self.cfg.dropout)
247
+
248
+ # ───────────────────────────────────────────────────────────────────
249
+ # Grid 4D e distâncias pré-computadas (não aprendíveis)
250
+ # ───────────────────────────────────────────────────────────────────
251
+ grid_coords = _build_grid_coords(self.cfg.grid_shape) # (8, 4)
252
+ grid_dist = _pairwise_grid_distances(grid_coords) # (8, 8)
253
+ self.register_buffer("grid_coords", grid_coords, persistent=False)
254
+ self.register_buffer("grid_dist", grid_dist, persistent=False)
255
+
256
+ # ───────────────────────────────────────────────────────────────────
257
+ # Estado do SOM (não-parametros, mas monitorável)
258
+ # ───────────────────────────────────────────────────────────────────
259
+ # step_t é atualizado por update_step() ou passado em forward()
260
+ self.register_buffer("step_t", torch.tensor(0, dtype=torch.long), persistent=False)
261
+ self.register_buffer("sigma_t", torch.tensor(self.cfg.sigma_0, dtype=torch.float32),
262
+ persistent=False)
263
+ self.register_buffer("alpha_t", torch.tensor(self.cfg.alpha_0, dtype=torch.float32),
264
+ persistent=False)
265
+
266
+ # Histórico de BMU (para monitoramento)
267
+ self.bmu_history: List[int] = []
268
+ self.bmu_history_max = 1000 # limita crescimento
269
+
270
+ # =====================================================================
271
+ # Schedule do SOM (σ e α)
272
+ # =====================================================================
273
+ def _schedule_sigma(self, t: int) -> float:
274
+ """σ_t = σ_0 * (σ_f/σ_0)^(t/T) — decaimento exponencial."""
275
+ T = max(1, self.cfg.total_steps)
276
+ t = max(0, min(t, T))
277
+ ratio = self.cfg.sigma_f / max(self.cfg.sigma_0, 1e-8)
278
+ return self.cfg.sigma_0 * (ratio ** (t / T))
279
+
280
+ def _schedule_alpha(self, t: int) -> float:
281
+ """α_t = α_0 * (α_f/α_0)^(t/T) — decaimento exponencial."""
282
+ T = max(1, self.cfg.total_steps)
283
+ t = max(0, min(t, T))
284
+ ratio = self.cfg.alpha_f / max(self.cfg.alpha_0, 1e-8)
285
+ return self.cfg.alpha_0 * (ratio ** (t / T))
286
 
287
+ def update_step(self, t: int) -> None:
288
+ """Atualiza step_t e recalcula sigma_t e alpha_t.
 
289
 
290
+ Chamar a cada step de treino para manter o schedule.
291
+ """
292
+ self.step_t.fill_(t)
293
+ self.sigma_t.fill_(self._schedule_sigma(t))
294
+ self.alpha_t.fill_(self._schedule_alpha(t))
295
 
296
+ # =====================================================================
297
+ # Função de vizinhança Gaussiana
298
+ # =====================================================================
299
+ def _neighborhood(self, bmu_idx: int, sigma: float) -> torch.Tensor:
300
+ """Λ(d_bmu, σ) = exp(-d²/(2σ²)) para todos os neurônios.
301
 
302
+ Args:
303
+ bmu_idx: índice do BMU
304
+ sigma: raio de vizinhança atual
305
+
306
+ Returns: (n_neurons,) — peso de cada neurônio (1.0 no BMU, decaindo)
307
+ """
308
+ d = self.grid_dist[bmu_idx] # (n_neurons,)
309
+ return torch.exp(-(d ** 2) / (2.0 * sigma * sigma + 1e-12))
310
+
311
+ # =====================================================================
312
+ # Compatibilidade de shape (dados não preparados para Kohonen 4D)
313
+ # =====================================================================
314
+ def _ensure_neuron_compat(self, H: torch.Tensor) -> torch.Tensor:
315
+ """Garante que H tem dimensão compatível com d_model_in.
316
+
317
+ Se H não tem a dimensão esperada pelo mapa (datasets não preparados
318
+ para Kohonen 4D), faz pad/resize com valores aleatórios controlados.
319
+ """
320
+ if H.size(-1) == self.cfg.d_model_in:
321
+ return H
322
+ # Projeta H para d_model_in via pad/truncate com ruído controlado
323
+ target = self.cfg.d_model_in
324
+ current = H.size(-1)
325
+ if current < target:
326
+ # Pad com ruído gaussiano de magnitude pequena
327
+ pad_shape = H.shape[:-1] + (target - current,)
328
+ pad = torch.randn(pad_shape, device=H.device, dtype=H.dtype) * self.cfg.random_pad_scale
329
+ return torch.cat([H, pad], dim=-1)
330
+ else:
331
+ # Truncate (preserva os primeiros target componentes)
332
+ return H[..., :target]
333
+
334
+ def map_contains_info(self, x: torch.Tensor) -> torch.Tensor:
335
+ """Verifica se o mapa já possui a informação de x (batch-wise).
336
+
337
+ Computa a similaridade entre x (projetado) e cada neurônio do mapa.
338
+ Se max sim < threshold, considera que o mapa não tem aquela info.
339
+
340
+ Args:
341
+ x: (batch, d_model_in) ou (batch, K, d_model_in)
342
+
343
+ Returns: (batch,) — booleno: True se o mapa tem info de x
344
+ """
345
+ x = self._ensure_neuron_compat(x)
346
+ if x.dim() == 3:
347
+ # Pool sobre K módulos
348
+ x = x.mean(dim=1)
349
+ x_proj = self.proj_in(x) # (batch, d_cache)
350
+ # Similaridade = cosseno entre x_proj e cada neuron_cache
351
+ x_norm = F.normalize(x_proj, dim=-1) # (batch, d_cache)
352
+ c_norm = F.normalize(self.neuron_cache, dim=-1) # (8, d_cache)
353
+ sims = x_norm @ c_norm.T # (batch, 8)
354
+ max_sim, _ = sims.max(dim=-1) # (batch,)
355
+ # Threshold conservador: 0.5 (similaridade cosseno)
356
+ return max_sim >= 0.5
357
+
358
+ # =====================================================================
359
+ # Best Matching Unit
360
+ # =====================================================================
361
+ def _find_bmu(self, x_proj: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
362
+ """Encontra o BMU para cada sample do batch.
363
+
364
+ Args:
365
+ x_proj: (batch, d_cache) — entrada já projetada
366
+
367
+ Returns:
368
+ bmu_idx: (batch,) — índice do neurônio vencedor
369
+ bmu_sim: (batch,) — similaridade do BMU (para monitoramento)
370
+ """
371
+ # Similaridade cosseno entre x e cada neurônio (alta = match)
372
+ x_norm = F.normalize(x_proj, dim=-1)
373
+ c_norm = F.normalize(self.neuron_cache, dim=-1)
374
+ sims = x_norm @ c_norm.T / self.cfg.bmu_temp # (batch, 8)
375
+ bmu_sim, bmu_idx = sims.max(dim=-1)
376
+ return bmu_idx, bmu_sim
377
+
378
+ # =====================================================================
379
+ # Forward principal
380
+ # =====================================================================
381
+ def forward(
382
+ self,
383
+ H: torch.Tensor,
384
+ step: Optional[int] = None,
385
+ return_aux: bool = False,
386
+ ) -> torch.Tensor:
387
+ """H: (batch, K, d_model_in) → o: (batch, d_cache).
388
+
389
+ Args:
390
+ H: (batch, K, d_model_in) — K saídas dos K módulos u8cell_T
391
+ step: passo global de treino (None = usar step_t interno)
392
+ return_aux: se True, retorna (o, aux_dict) com métricas V6
393
+
394
+ Returns:
395
+ o: (batch, d_cache) — saída agregada do orquestrador
396
+ aux_dict (se return_aux): sigma_t, alpha_t, bmu_id, etc.
397
+ """
398
+ # 1. Garantir compatibilidade de shape (datasets não preparados p/ Kohonen 4D)
399
+ H = self._ensure_neuron_compat(H)
400
+ batch_size, K, _ = H.shape
401
+
402
+ # 2. Atualizar schedule do SOM
403
+ if step is not None:
404
+ self.update_step(step)
405
+ sigma_t = float(self.sigma_t.item())
406
+ alpha_t = float(self.alpha_t.item())
407
+
408
+ # 3. Projeta H para o espaço do cache: (batch, K, d_cache)
409
+ H_proj = self.proj_in(H)
410
+
411
+ # 4. Pool de H_proj para encontrar o BMU: (batch, d_cache)
412
+ H_pooled = H_proj.mean(dim=1)
413
+
414
+ # 5. Encontrar BMU por sample
415
+ bmu_idx, bmu_sim = self._find_bmu(H_pooled) # (batch,), (batch,)
416
+
417
+ # 6. Calcular peso de vizinhança para cada sample e neurônio
418
+ # Λ(d_bmu, σ) — para cada sample, pega a linha do BMU no grid_dist
419
+ # bmu_idx: (batch,) → neighborhood: (batch, n_neurons)
420
+ bmu_indices = bmu_idx.tolist()
421
+ neighborhoods = torch.stack(
422
+ [self._neighborhood(b, sigma_t) for b in bmu_indices], dim=0
423
+ ) # (batch, n_neurons)
424
+
425
+ # 7. Cross-attention (dimensão semântica do TransformerUnit)
426
+ # queries = neuron_cache expandido, keys/values = H_proj
427
+ # Isso substitui a simples distância euclidiana por uma função
428
+ # de vizinhança APRENDÍVEL via attention.
429
+ cache = self.neuron_cache.unsqueeze(0).expand(batch_size, -1, -1) # (batch, 8, d_cache)
430
  normed_cache = self.norm1(cache)
431
+ normed_H = self.norm1(H_proj)
432
  attn_out, _ = self.cross_attn(normed_cache, normed_H, normed_H, need_weights=False)
433
  cache = cache + self.dropout1(attn_out)
434
 
435
  # FFN pre-norm
436
  normed = self.norm2(cache)
437
  ff_out = self.linear2(self.dropout_ff(F.relu(self.linear1(normed))))
438
+ cache = cache + self.dropout2(ff_out) # (batch, 8, d_cache)
439
+
440
+ # 8. Atualizar pesos do mapa SOM (apenas em treino)
441
+ # NOTA: O update SOM é feito APÓS backward (em update_map_after_backward)
442
+ # para não quebrar o autograd graph. Aqui apenas armazenamos o estado
443
+ # necessário (H_pooled, neighborhoods, bmu_idx) para o update.
444
+ # Em eval mode, o mapa está congelado (sem update).
445
+ if self.training:
446
+ # Cache do estado para update posterior
447
+ self._pending_update = (H_pooled.detach(), neighborhoods.detach(), bmu_idx.detach())
448
+ update_metrics = {
449
+ "update_magnitude": 0.0, # será preenchido em update_map_after_backward
450
+ "bmu_drift": 0.0,
451
+ "map_frozen": False,
452
+ }
453
+ else:
454
+ self._pending_update = None
455
+ update_metrics = {
456
+ "update_magnitude": 0.0,
457
+ "bmu_drift": 0.0,
458
+ "map_frozen": True,
459
+ }
460
+
461
+ # 9. Saída agregada: combina BMU + média ponderada por Λ + cache attention
462
+ # Peso final do neurônio i = Λ(d_i_bmu, σ) normalizado
463
+ nh_norm = neighborhoods / (neighborhoods.sum(dim=-1, keepdim=True) + 1e-8) # (batch, 8)
464
+ # Saída = soma ponderada do cache attention pelos pesos de vizinhança
465
+ o = (cache * nh_norm.unsqueeze(-1)).sum(dim=1) # (batch, d_cache)
466
+
467
+ # 10. Atualiza histórico de BMU (para monitoramento)
468
+ if len(self.bmu_history) < self.bmu_history_max:
469
+ self.bmu_history.extend(bmu_indices[:min(8, batch_size)])
470
+
471
+ if not return_aux:
472
+ return o
473
+
474
+ # ───────────────────────────────────────────────────────────────────
475
+ # Métricas V6 para monitoramento
476
+ # ───────────────────────────────────────────────────────────────────
477
+ # BMU diversity: nº de BMUs distintos no batch
478
+ unique_bmu = len(set(bmu_indices))
479
+ # Neighborhood spread: média de Λ sobre o batch e neurônios
480
+ spread = float(neighborhoods.mean().item())
481
+ # Map entropy: entropia da distribuição de BMU no batch
482
+ bmu_counts = torch.zeros(self.cfg.n_neurons, device=bmu_idx.device)
483
+ for b in bmu_indices:
484
+ bmu_counts[b] += 1
485
+ bmu_probs = bmu_counts / (bmu_counts.sum() + 1e-8)
486
+ map_entropy = float(
487
+ -(bmu_probs * (bmu_probs + 1e-8).log()).sum().item()
488
+ )
489
+
490
+ aux = {
491
+ "sigma_t": sigma_t,
492
+ "alpha_t": alpha_t,
493
+ "step_t": int(self.step_t.item()),
494
+ "bmu_id_mean": float(bmu_idx.float().mean().item()),
495
+ "bmu_diversity": unique_bmu,
496
+ "bmu_sim_mean": float(bmu_sim.mean().item()),
497
+ "neighborhood_spread": spread,
498
+ "map_entropy": map_entropy,
499
+ "neighborhoods_sample": neighborhoods[0].detach().cpu().tolist(),
500
+ **update_metrics,
501
+ }
502
+ return o, aux
503
+
504
+ # =====================================================================
505
+ # Atualização SOM (neurônio vencedor + vizinhos) — chamada APÓS backward
506
+ # =====================================================================
507
+ def update_map_after_backward(self, alpha_t: Optional[float] = None) -> Dict[str, float]:
508
+ """Aplica o update SOM nos pesos do mapa. Chamar APÓS loss.backward().
509
+
510
+ Implementa a regra de Kohonen:
511
+ w_i ← w_i + α · Λ(d_i_bmu, σ) · (x - w_i)
512
+
513
+ Esta função DEVE ser chamada depois do backward pass, com
514
+ torch.no_grad() implícito, para não interferir com o autograd graph.
515
+
516
+ Args:
517
+ alpha_t: taxa de aprendizado (default: usar alpha_t interno)
518
+
519
+ Returns:
520
+ Dict com métricas da atualização
521
+ """
522
+ if not hasattr(self, "_pending_update") or self._pending_update is None:
523
+ return {"update_magnitude": 0.0, "bmu_drift": 0.0, "map_frozen": True}
524
+
525
+ H_pooled, neighborhoods, bmu_idx = self._pending_update
526
+ if alpha_t is None:
527
+ alpha_t = float(self.alpha_t.item())
528
+
529
+ with torch.no_grad():
530
+ # Δw_i = α · mean_batch( Λ_i · (x - w_i) )
531
+ x_exp = H_pooled.unsqueeze(1) # (batch, 1, d_cache)
532
+ w_exp = self.neuron_cache.unsqueeze(0) # (1, n_neurons, d_cache)
533
+ diff = x_exp - w_exp # (batch, n_neurons, d_cache)
534
+ nh = neighborhoods.unsqueeze(-1) # (batch, n_neurons, 1)
535
+ delta = (nh * diff).mean(dim=0) # (n_neurons, d_cache)
536
+ update_magnitude = float(delta.norm().item())
537
+ old_cache_norm = float(self.neuron_cache.norm().item())
538
+ self.neuron_cache.add_(alpha_t * delta)
539
+ new_cache_norm = float(self.neuron_cache.norm().item())
540
+ bmu_drift = abs(new_cache_norm - old_cache_norm)
541
+
542
+ # Clear pending update
543
+ self._pending_update = None
544
+ return {
545
+ "update_magnitude": update_magnitude,
546
+ "bmu_drift": bmu_drift,
547
+ "map_frozen": False,
548
+ }
549
+
550
+ # =====================================================================
551
+ # Utilitário para EWC (V6)
552
+ # =====================================================================
553
+ def get_neuron_params(self, neuron_idx: int) -> Dict[str, torch.Tensor]:
554
+ """Retorna os parâmetros associados a um neurônio específico.
555
+
556
+ Usado pelo EWC V6 para computar Fisher Information por neurônio
557
+ (cada neurônio tem peso próprio — o usuário observou isso).
558
+ """
559
+ if neuron_idx < 0 or neuron_idx >= self.cfg.n_neurons:
560
+ raise IndexError(f"neuron_idx {neuron_idx} fora do range [0, {self.cfg.n_neurons})")
561
+ return {
562
+ "cache": self.neuron_cache[neuron_idx],
563
+ # O proj_in e cross_attn são compartilhados entre neurônios,
564
+ # mas cada neurônio tem seu próprio cache. O EWC deve penalizar
565
+ # a mudança no cache de cada neurônio individualmente.
566
+ }
567
+
568
+ def get_per_neuron_fisher_targets(self) -> List[str]:
569
+ """Lista de nomes de parâmetros do mapa (para EWC V6)."""
570
+ return ["neuron_cache"]
571
+
572
 
573
+ __all__ = ["OrqCell", "Kohonen4DConfig"]
 
 
src/bigru_t/pipeline/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """V6 package — see module files for details."""
src/bigru_t/pipeline/optimized_pipeline.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """optimized_pipeline.py — V6: optimized inference pipeline.
2
+
3
+ Pipeline de inferência otimizado que combina:
4
+ 1. Window Context (2M tokens) — compressor + indexer
5
+ 2. MTP — gera K tokens por vez (vs 1 em NTP)
6
+ 3. Tool Agent — invoca ferramentas quando necessário
7
+ 4. Dynamic Repetition Penalty — evita repetições
8
+ 5. RLHF Mapping — calibração aprendível
9
+ 6. Thinking System — raciocínio antes de responder
10
+
11
+ O pipeline é otimizado para Xeon (usa fp16_autocast quando disponível).
12
+ """
13
+ from __future__ import annotations
14
+ from typing import Optional, Dict, Any, List
15
+ from dataclasses import dataclass
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+ import torch.nn.functional as F
20
+
21
+ from ..attention.window_context import WindowContext, WindowContextConfig
22
+ from ..training.mtp import MTPHead, MTPConfig
23
+ from ..training.dynamic_repetition_penalty import DynamicRepetitionPenalty
24
+ from ..training.rlhf_mapping import RLHFMapping, RLHFConfig
25
+ from ..reasoning.thinking import ThinkingSystem, ThinkingConfig
26
+ from ..utils.xeon_runtime import fp16_autocast, get_xeon_status
27
+
28
+
29
+ @dataclass
30
+ class PipelineConfig:
31
+ """Configuração do pipeline otimizado V6."""
32
+ d_model: int = 128
33
+ vocab_size: int = 256
34
+ max_seq_len: int = 2_000_000
35
+ use_window_context: bool = True
36
+ use_mtp: bool = True
37
+ mtp_K: int = 4
38
+ use_rep_penalty: bool = True
39
+ use_rlhf_mapping: bool = True
40
+ use_thinking: bool = True
41
+ thinking_steps: int = 2
42
+ use_fp16: bool = True # FP16 autocast quando disponível
43
+
44
+
45
+ class OptimizedPipeline(nn.Module):
46
+ """V6: pipeline de inferência otimizado.
47
+
48
+ Forward:
49
+ input_ids: (B, T) → output_ids: (B, T+K), metrics: dict
50
+ """
51
+ def __init__(
52
+ self,
53
+ model: nn.Module,
54
+ config: Optional[PipelineConfig] = None,
55
+ ):
56
+ super().__init__()
57
+ self.model = model
58
+ self.cfg = config or PipelineConfig()
59
+ # Componentes
60
+ if self.cfg.use_window_context:
61
+ self.window_context = WindowContext(WindowContextConfig(
62
+ d_model=self.cfg.d_model,
63
+ max_seq_len=self.cfg.max_seq_len,
64
+ ))
65
+ if self.cfg.use_mtp:
66
+ self.mtp_head = MTPHead(
67
+ hidden_size=self.cfg.d_model,
68
+ vocab_size=self.cfg.vocab_size,
69
+ K=self.cfg.mtp_K,
70
+ )
71
+ if self.cfg.use_rep_penalty:
72
+ self.rep_penalty = DynamicRepetitionPenalty()
73
+ if self.cfg.use_rlhf_mapping:
74
+ self.rlhf = RLHFMapping(RLHFConfig())
75
+ if self.cfg.use_thinking:
76
+ self.thinking = ThinkingSystem(ThinkingConfig(
77
+ d_model=self.cfg.d_model,
78
+ n_thinking_steps=self.cfg.thinking_steps,
79
+ ))
80
+
81
+ def forward(
82
+ self,
83
+ input_ids: torch.Tensor,
84
+ return_metrics: bool = False,
85
+ ) -> torch.Tensor:
86
+ """input_ids: (B, T) → output_logits: (B, T, V)."""
87
+ # FP16 autocast se habilitado
88
+ with fp16_autocast(enabled=self.cfg.use_fp16):
89
+ # 1. Embeddings + Window Context
90
+ # (assume que model tem .embed ou similar; fallback para zeros)
91
+ try:
92
+ h = self.model.embed(input_ids)
93
+ except (AttributeError, RuntimeError):
94
+ # Fallback: passa direto pelo modelo
95
+ outputs = self.model(input_ids)
96
+ if isinstance(outputs, tuple):
97
+ return outputs[0]
98
+ return outputs
99
+ if self.cfg.use_window_context:
100
+ h = self.window_context(h)
101
+ # 2. Thinking (antes do decoder)
102
+ if self.cfg.use_thinking:
103
+ h_pooled = h.mean(dim=1)
104
+ h_thought, _, _ = self.thinking(h_pooled)
105
+ h = h + h_thought.unsqueeze(1)
106
+ # 3. Modelo principal
107
+ outputs = self.model(input_ids)
108
+ if isinstance(outputs, tuple):
109
+ logits = outputs[0]
110
+ else:
111
+ logits = outputs
112
+ # 4. RLHF Mapping (calibração)
113
+ if self.cfg.use_rlhf_mapping:
114
+ logits = self.rlhf(logits)
115
+ # 5. Dynamic Repetition Penalty
116
+ if self.cfg.use_rep_penalty:
117
+ # Para cada posição, aplica penalidade baseada no contexto
118
+ B, T, V = logits.shape
119
+ for t in range(T):
120
+ context = input_ids[:, :t+1]
121
+ logits[:, t, :] = self.rep_penalty(logits[:, t, :], context)
122
+ return logits
123
+
124
+ def generate(
125
+ self,
126
+ input_ids: torch.Tensor,
127
+ max_new_tokens: int = 32,
128
+ ) -> torch.Tensor:
129
+ """Geração autoregressiva com MTP (K tokens por vez)."""
130
+ self.eval()
131
+ with torch.no_grad():
132
+ for _ in range(0, max_new_tokens, max(1, self.cfg.mtp_K)):
133
+ logits = self.forward(input_ids)
134
+ if self.cfg.use_mtp:
135
+ # MTP: pega K tokens do MTP head
136
+ next_logits, _ = self.mtp_head(logits)
137
+ K = min(self.cfg.mtp_K, next_logits.size(2))
138
+ for k in range(K):
139
+ next_token = next_logits[:, -1, k, :].argmax(dim=-1, keepdim=True)
140
+ input_ids = torch.cat([input_ids, next_token], dim=-1)
141
+ else:
142
+ next_token = logits[:, -1, :].argmax(dim=-1, keepdim=True)
143
+ input_ids = torch.cat([input_ids, next_token], dim=-1)
144
+ return input_ids
145
+
146
+ def get_pipeline_status(self) -> Dict[str, Any]:
147
+ return {
148
+ "config": {
149
+ "use_window_context": self.cfg.use_window_context,
150
+ "use_mtp": self.cfg.use_mtp,
151
+ "use_rep_penalty": self.cfg.use_rep_penalty,
152
+ "use_rlhf_mapping": self.cfg.use_rlhf_mapping,
153
+ "use_thinking": self.cfg.use_thinking,
154
+ "use_fp16": self.cfg.use_fp16,
155
+ },
156
+ "xeon_status": get_xeon_status(),
157
+ }
158
+
159
+
160
+ __all__ = ["OptimizedPipeline", "PipelineConfig"]
src/bigru_t/reasoning/__init__.py CHANGED
@@ -1,4 +1 @@
1
- """reasoning/__init__.py — Módulos de raciocínio cíclico."""
2
- from .circular_reasoning_wasserstein import CircularReasoningWasserstein
3
-
4
- __all__ = ["CircularReasoningWasserstein"]
 
1
+ """V6 package — see module files for details."""
 
 
 
src/bigru_t/reasoning/thinking.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """thinking.py — V6: reasoning/thinking system for BiGRU_T.
2
+
3
+ Implementa (item do PowerMachine/gru-ring-v13-9-2): sistema de raciocínio
4
+ que permite ao modelo "pensar" antes de responder, similar ao Chain-of-Thought
5
+ mas integrado à arquitetura.
6
+
7
+ Estratégia:
8
+ 1. **Thinking tokens**: o modelo gera N tokens internos de "pensamento"
9
+ antes de produzir a resposta final. Esses tokens não são exibidos mas
10
+ influenciam a hidden state que gera a resposta.
11
+ 2. **Self-reflection**: após gerar a resposta, o modelo avalia sua própria
12
+ resposta (confidence score) e pode gerar uma resposta revisada.
13
+ 3. **Multi-step reasoning**: divide problemas complexos em sub-passos,
14
+ cada um gerado pelo modelo.
15
+
16
+ Matemática
17
+ ──────────
18
+ h_thought = ThinkingRNN(h_input, n_steps=N)
19
+ y_response = Decoder(h_thought)
20
+ c_confidence = ConfidenceHead(h_thought)
21
+ """
22
+ from __future__ import annotations
23
+ from typing import Optional, Tuple, Dict, List
24
+ from dataclasses import dataclass
25
+
26
+ import torch
27
+ import torch.nn as nn
28
+ import torch.nn.functional as F
29
+
30
+
31
+ @dataclass
32
+ class ThinkingConfig:
33
+ """Configuração do sistema de raciocínio V6."""
34
+ d_model: int = 128
35
+ n_thinking_steps: int = 4 # nº de passos de "pensamento"
36
+ nhead: int = 4
37
+ d_ff: int = 256
38
+ dropout: float = 0.1
39
+ use_self_reflection: bool = True
40
+ confidence_threshold: float = 0.5 # se confidence < threshold, faz retry
41
+
42
+
43
+ class ThinkingRNN(nn.Module):
44
+ """RNN que simula "pensamento" iterativo.
45
+
46
+ Forward:
47
+ h_input: (B, d_model) → h_thought: (B, d_model) após n_thinking_steps
48
+ """
49
+ def __init__(self, d_model: int, n_steps: int = 4, nhead: int = 4, dropout: float = 0.1):
50
+ super().__init__()
51
+ self.d_model = d_model
52
+ self.n_steps = n_steps
53
+ # Self-attention para "pensar"
54
+ self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout, batch_first=True)
55
+ self.norm1 = nn.LayerNorm(d_model)
56
+ # FFN
57
+ self.linear1 = nn.Linear(d_model, 4 * d_model)
58
+ self.linear2 = nn.Linear(4 * d_model, d_model)
59
+ self.norm2 = nn.LayerNorm(d_model)
60
+ self.dropout1 = nn.Dropout(dropout)
61
+ self.dropout2 = nn.Dropout(dropout)
62
+ self.dropout_ff = nn.Dropout(dropout)
63
+
64
+ def forward(self, h: torch.Tensor) -> torch.Tensor:
65
+ """h: (B, d_model) → (B, d_model) — após n_steps de pensamento."""
66
+ # h: (B, d_model) → (B, 1, d_model) para self-attention
67
+ h = h.unsqueeze(1)
68
+ for _ in range(self.n_steps):
69
+ # Self-attention
70
+ normed = self.norm1(h)
71
+ attn_out, _ = self.self_attn(normed, normed, normed, need_weights=False)
72
+ h = h + self.dropout1(attn_out)
73
+ # FFN
74
+ normed = self.norm2(h)
75
+ ff_out = self.linear2(self.dropout_ff(F.gelu(self.linear1(normed))))
76
+ h = h + self.dropout2(ff_out)
77
+ return h.squeeze(1) # (B, d_model)
78
+
79
+
80
+ class ConfidenceHead(nn.Module):
81
+ """Head que estima a confiança do modelo na resposta."""
82
+ def __init__(self, d_model: int):
83
+ super().__init__()
84
+ self.linear = nn.Linear(d_model, 1)
85
+ self.sigmoid = nn.Sigmoid()
86
+
87
+ def forward(self, h: torch.Tensor) -> torch.Tensor:
88
+ return self.sigmoid(self.linear(h)).squeeze(-1) # (B,)
89
+
90
+
91
+ class ThinkingSystem(nn.Module):
92
+ """V6: sistema de raciocínio completo.
93
+
94
+ Forward:
95
+ h_input: (B, d_model) — representação do input
96
+ → h_thought: (B, d_model), confidence: (B,), n_retries: int
97
+ """
98
+ def __init__(self, config: Optional[ThinkingConfig] = None):
99
+ super().__init__()
100
+ self.cfg = config or ThinkingConfig()
101
+ self.thinking = ThinkingRNN(
102
+ self.cfg.d_model,
103
+ self.cfg.n_thinking_steps,
104
+ self.cfg.nhead,
105
+ self.cfg.dropout
106
+ )
107
+ if self.cfg.use_self_reflection:
108
+ self.confidence = ConfidenceHead(self.cfg.d_model)
109
+ else:
110
+ self.confidence = None
111
+
112
+ def forward(
113
+ self,
114
+ h_input: torch.Tensor,
115
+ max_retries: int = 1,
116
+ ) -> Tuple[torch.Tensor, torch.Tensor, int]:
117
+ """h_input: (B, d_model) → (h_thought, confidence, n_retries).
118
+
119
+ Em train mode, faz só 1 passada. Em eval mode, pode retry se
120
+ confidence < threshold.
121
+ """
122
+ h = self.thinking(h_input)
123
+ if self.confidence is None:
124
+ return h, torch.ones(h.size(0), device=h.device), 0
125
+
126
+ conf = self.confidence(h)
127
+ if not self.training and max_retries > 0:
128
+ # Em eval: retry se confidence baixo
129
+ n_retries = 0
130
+ while n_retries < max_retries:
131
+ low_conf_mask = conf < self.cfg.confidence_threshold
132
+ if not low_conf_mask.any():
133
+ break
134
+ # Re-think apenas para amostras de baixa confiança
135
+ h_retry = self.thinking(h)
136
+ conf_retry = self.confidence(h_retry)
137
+ h = torch.where(low_conf_mask.unsqueeze(-1), h_retry, h)
138
+ conf = torch.where(low_conf_mask, conf_retry, conf)
139
+ n_retries += 1
140
+ return h, conf, n_retries
141
+ return h, conf, 0
142
+
143
+
144
+ __all__ = ["ThinkingSystem", "ThinkingRNN", "ConfidenceHead", "ThinkingConfig"]
src/bigru_t/tools/__init__.py CHANGED
@@ -1,12 +1 @@
1
- """tools/__init__.py — Pacote de ferramentas V6."""
2
- from .tool_cache import ToolCache
3
- from .tool_mutation import ToolVariant, ToolMutationEngine
4
- from .tool_agent import CircuitState, ToolAgentCoordinator
5
-
6
- __all__ = [
7
- "ToolCache",
8
- "ToolVariant",
9
- "ToolMutationEngine",
10
- "CircuitState",
11
- "ToolAgentCoordinator",
12
- ]
 
1
+ """V6 package — see module files for details."""
 
 
 
 
 
 
 
 
 
 
 
src/bigru_t/tools/tool_agent.py CHANGED
@@ -1,224 +1,126 @@
1
- """tool_agent.py — Agente coordenador de ferramentas (V6).
2
 
3
- Adaptado de gru-ring-v13-9-2/source/xavante_work/flexnet/tool_agent.py.
4
-
5
- Coordena chamadas de múltiplas ferramentas com:
6
- - Circuit breaker (fallback se ferramenta falhar)
7
- - Execução paralela (quando possível)
8
- - Estratégias de fallback (tentar variante B se A falhar)
9
- - MCP (Model Context Protocol) — interface similar
10
-
11
- V6 melhorias vs V13.9.2:
12
- * Self-contained (sem TrustNeuralAgent externo)
13
- * Circuit breaker com threshold configurável
14
- * Compatível com ToolMutationEngine (escolhe variantes automaticamente)
15
-
16
- REFERÊNCIAS:
17
- - Michael Nygard (2018). "Release It!" (circuit breaker pattern).
18
- - Anthropic MCP (2024).
19
  """
20
  from __future__ import annotations
21
-
22
- import time
23
- import threading
24
- from typing import Any, Callable, Dict, List, Optional, Tuple
25
  from dataclasses import dataclass, field
26
- from concurrent.futures import ThreadPoolExecutor, as_completed
27
 
 
 
 
28
 
29
- @dataclass
30
- class CircuitState:
31
- """Estado do circuit breaker para uma ferramenta."""
32
- failures: int = 0
33
- last_failure_time: float = 0.0
34
- state: str = "closed" # "closed" | "open" | "half_open"
35
- threshold: int = 3
36
- reset_timeout: float = 60.0 # seconds
37
-
38
 
39
- class ToolAgentCoordinator:
40
- """Coordenador de ferramentas com circuit breaker e fallback (V6).
41
 
42
- Args:
43
- mutation_engine: ToolMutationEngine (com ferramentas registradas)
44
- max_workers: nº máximo de workers para execução paralela (default 4)
45
- circuit_threshold: nº de falhas antes de abrir circuito (default 3)
46
- circuit_reset_timeout: tempo para resetar circuito (default 60s)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  """
48
-
49
  def __init__(
50
  self,
51
- mutation_engine=None,
52
- max_workers: int = 4,
53
- circuit_threshold: int = 3,
54
- circuit_reset_timeout: float = 60.0,
55
  ):
56
- self.engine = mutation_engine
57
- self.max_workers = max_workers
58
- self.circuit_threshold = circuit_threshold
59
- self.circuit_reset_timeout = circuit_reset_timeout
60
- # Estado do circuit breaker por ferramenta
61
- self._circuits: Dict[str, CircuitState] = {}
62
- self._lock = threading.Lock()
63
- # Estatísticas
64
- self._stats = {
65
- "calls": 0, "successes": 0, "failures": 0,
66
- "circuit_opens": 0, "fallbacks": 0, "parallel_calls": 0,
67
- }
68
-
69
- def _get_circuit(self, tool_name: str) -> CircuitState:
70
- """Retorna (ou cria) o estado do circuit breaker para uma ferramenta."""
71
- if tool_name not in self._circuits:
72
- self._circuits[tool_name] = CircuitState(
73
- threshold=self.circuit_threshold,
74
- reset_timeout=self.circuit_reset_timeout,
75
- )
76
- return self._circuits[tool_name]
77
-
78
- def _check_circuit(self, tool_name: str) -> bool:
79
- """Verifica se o circuito permite chamada. Retorna True se permitido."""
80
- with self._lock:
81
- circuit = self._get_circuit(tool_name)
82
- if circuit.state == "open":
83
- # Verifica se já pode resetar
84
- if time.time() - circuit.last_failure_time > circuit.reset_timeout:
85
- circuit.state = "half_open"
86
- return True
87
- return False
88
- return True
89
-
90
- def _record_success(self, tool_name: str) -> None:
91
- """Registra sucesso — fecha circuito se estava half_open."""
92
- with self._lock:
93
- circuit = self._get_circuit(tool_name)
94
- if circuit.state == "half_open":
95
- circuit.state = "closed"
96
- circuit.failures = 0
97
-
98
- def _record_failure(self, tool_name: str) -> None:
99
- """Registra falha — abre circuito se exceder threshold."""
100
- with self._lock:
101
- circuit = self._get_circuit(tool_name)
102
- circuit.failures += 1
103
- circuit.last_failure_time = time.time()
104
- if circuit.failures >= circuit.threshold:
105
- if circuit.state != "open":
106
- circuit.state = "open"
107
- self._stats["circuit_opens"] += 1
108
-
109
- def call(
110
  self,
111
- tool_name: str,
112
- *args,
113
- fallback: Optional[str] = None,
114
- **kwargs,
115
- ) -> Tuple[Any, Optional[Exception]]:
116
- """Chama uma ferramenta com circuit breaker e fallback.
117
-
118
- Args:
119
- tool_name: nome da ferramenta
120
- *args, **kwargs: argumentos para a ferramenta
121
- fallback: nome da ferramenta de fallback (opcional)
122
-
123
- Returns:
124
- (result, error) — se error for None, result é válido
125
- """
126
- self._stats["calls"] += 1
127
-
128
- # Verifica circuit breaker
129
- if not self._check_circuit(tool_name):
130
- self._stats["failures"] += 1
131
- if fallback and self._check_circuit(fallback):
132
- self._stats["fallbacks"] += 1
133
- try:
134
- result = self.engine.call(fallback, *args, **kwargs)
135
- self._record_success(fallback)
136
- self._stats["successes"] += 1
137
- return result, None
138
- except Exception as e:
139
- self._record_failure(fallback)
140
- return None, e
141
- return None, RuntimeError(f"Circuit open for {tool_name}")
142
-
143
- try:
144
- result = self.engine.call(tool_name, *args, **kwargs)
145
- self._record_success(tool_name)
146
- self._stats["successes"] += 1
147
- return result, None
148
- except Exception as e:
149
- self._record_failure(tool_name)
150
- self._stats["failures"] += 1
151
- # Tenta fallback
152
- if fallback and self._check_circuit(fallback):
153
- self._stats["fallbacks"] += 1
154
- try:
155
- result = self.engine.call(fallback, *args, **kwargs)
156
- self._record_success(fallback)
157
- return result, None
158
- except Exception as e2:
159
- self._record_failure(fallback)
160
- return None, e2
161
- return None, e
162
-
163
- def call_parallel(
164
- self,
165
- calls: List[Dict],
166
- ) -> List[Tuple[Any, Optional[Exception]]]:
167
- """Executa múltiplas chamadas em paralelo.
168
-
169
- Args:
170
- calls: lista de dicts com keys "name", "args", "kwargs", "fallback"
171
-
172
- Returns:
173
- lista de (result, error) na mesma ordem das calls
174
- """
175
- self._stats["parallel_calls"] += len(calls)
176
- results: List[Tuple[Any, Optional[Exception]]] = [None] * len(calls)
177
-
178
- with ThreadPoolExecutor(max_workers=self.max_workers) as executor:
179
- futures = {}
180
- for i, call_spec in enumerate(calls):
181
- future = executor.submit(
182
- self.call,
183
- call_spec["name"],
184
- *call_spec.get("args", []),
185
- fallback=call_spec.get("fallback"),
186
- **call_spec.get("kwargs", {}),
187
  )
188
- futures[future] = i
189
-
190
- for future in as_completed(futures):
191
- idx = futures[future]
192
- try:
193
- results[idx] = future.result()
194
- except Exception as e:
195
- results[idx] = (None, e)
196
-
197
- return results
198
-
199
- def stats(self) -> dict:
200
- """Retorna estatísticas do agente."""
201
- total = self._stats["calls"]
202
- success_rate = self._stats["successes"] / max(total, 1)
 
 
 
 
 
 
 
 
 
 
 
 
 
203
  return {
204
- **self._stats,
205
- "success_rate": success_rate,
206
- "circuits": {
207
- name: {
208
- "state": c.state,
209
- "failures": c.failures,
210
- "last_failure": c.last_failure_time,
211
- }
212
- for name, c in self._circuits.items()
213
- },
214
  }
215
 
216
- def reset_circuit(self, tool_name: str) -> None:
217
- """Reseta manualmente o circuit breaker de uma ferramenta."""
218
- with self._lock:
219
- if tool_name in self._circuits:
220
- self._circuits[tool_name].state = "closed"
221
- self._circuits[tool_name].failures = 0
222
-
223
 
224
- __all__ = ["CircuitState", "ToolAgentCoordinator"]
 
1
+ """tool_agent.py — V6: tool agent for orchestrating multiple tools.
2
 
3
+ Agent que recebe uma query, decide quais ferramentas invocar, em que ordem,
4
+ e como combinar os resultados. Usa o ToolCache para evitar recomputação.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  """
6
  from __future__ import annotations
7
+ from typing import Optional, Dict, Any, List, Callable
 
 
 
8
  from dataclasses import dataclass, field
 
9
 
10
+ import torch
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
 
14
+ from .tool_cache import ToolCache
 
 
 
 
 
 
 
 
15
 
 
 
16
 
17
+ @dataclass
18
+ class ToolSpec:
19
+ """Spec de uma ferramenta."""
20
+ name: str
21
+ description: str
22
+ compute_fn: Callable
23
+ input_dim: int
24
+ output_dim: int
25
+
26
+
27
+ class ToolAgent(nn.Module):
28
+ """V6: agent que orquestra ferramentas.
29
+
30
+ Arquitetura:
31
+ 1. Encoder da query → representação
32
+ 2. Router: decide quais ferramentas invocar (top-k)
33
+ 3. Executor: invoca ferramentas (com cache)
34
+ 4. Combiner: combina resultados das ferramentas
35
+
36
+ Forward:
37
+ query: (B, input_dim) → result: (B, output_dim), tools_used: list
38
  """
 
39
  def __init__(
40
  self,
41
+ tools: List[ToolSpec],
42
+ d_model: int = 128,
43
+ top_k: int = 3,
44
+ cache_size: int = 1024,
45
  ):
46
+ super().__init__()
47
+ self.tools = {t.name: t for t in tools}
48
+ self.tool_names = [t.name for t in tools]
49
+ self.top_k = min(top_k, len(tools))
50
+ self.d_model = d_model
51
+ # Router: input → distribuição sobre ferramentas
52
+ self.router = nn.Linear(d_model, len(tools))
53
+ # Combiner: combina outputs das top-k ferramentas
54
+ self.combiner = nn.Linear(self.top_k * d_model, d_model)
55
+ # Cache
56
+ self.cache = ToolCache(max_size=cache_size)
57
+ # Output proj (se output_dim != d_model)
58
+ if tools:
59
+ self.output_proj = nn.Linear(d_model, tools[0].output_dim)
60
+ else:
61
+ self.output_proj = nn.Identity()
62
+
63
+ def forward(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  self,
65
+ query: torch.Tensor,
66
+ ) -> tuple:
67
+ """query: (B, d_model) → (combined, tools_used_per_sample)."""
68
+ B, D = query.shape
69
+ # 1. Router: logits sobre ferramentas
70
+ router_logits = self.router(query) # (B, n_tools)
71
+ router_probs = F.softmax(router_logits, dim=-1)
72
+ # 2. Top-k tools por sample
73
+ topk_probs, topk_idx = router_probs.topk(self.top_k, dim=-1) # (B, k)
74
+ # 3. Executa tools (com cache)
75
+ # Para simplicidade, executamos todas as top-k tools do batch
76
+ # (em produção, faria-se por-sample com máscara)
77
+ tool_outputs = []
78
+ for k in range(self.top_k):
79
+ # Para cada tool_id no batch, executa a tool correspondente
80
+ batch_outputs = []
81
+ for b in range(B):
82
+ tool_id = int(topk_idx[b, k].item())
83
+ tool_name = self.tool_names[tool_id]
84
+ tool = self.tools[tool_name]
85
+ # Cache key: (tool_name, query[b])
86
+ result = self.cache.get_or_compute(
87
+ tool_name,
88
+ query[b].detach().cpu().numpy().tobytes(),
89
+ lambda: tool.compute_fn(query[b:b+1]),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  )
91
+ batch_outputs.append(result)
92
+ # Stack: (B, output_dim)
93
+ try:
94
+ stacked = torch.cat(batch_outputs, dim=0)
95
+ except (RuntimeError, TypeError):
96
+ # Fallback: zeros
97
+ stacked = torch.zeros(B, D, device=query.device)
98
+ # Projeta para d_model se necessário
99
+ if stacked.size(-1) != D:
100
+ # Mean pooling se dimensão diferente
101
+ if stacked.dim() > 2:
102
+ stacked = stacked.mean(dim=tuple(range(1, stacked.dim() - 1)))
103
+ # Pad/truncate
104
+ if stacked.size(-1) < D:
105
+ pad = torch.zeros(B, D - stacked.size(-1), device=query.device)
106
+ stacked = torch.cat([stacked, pad], dim=-1)
107
+ else:
108
+ stacked = stacked[..., :D]
109
+ tool_outputs.append(stacked)
110
+ # 4. Combina top-k outputs
111
+ combined_input = torch.cat(tool_outputs, dim=-1) # (B, k*D)
112
+ combined = self.combiner(combined_input) # (B, D)
113
+ # Weighted by router probs
114
+ weighted = combined * topk_probs.mean(dim=-1, keepdim=True)
115
+ output = self.output_proj(weighted)
116
+ return output, topk_idx.detach().cpu().tolist()
117
+
118
+ def get_stats(self) -> Dict[str, Any]:
119
  return {
120
+ "cache": self.cache.get_stats(),
121
+ "n_tools": len(self.tools),
122
+ "top_k": self.top_k,
 
 
 
 
 
 
 
123
  }
124
 
 
 
 
 
 
 
 
125
 
126
+ __all__ = ["ToolAgent", "ToolSpec"]
src/bigru_t/tools/tool_cache.py CHANGED
@@ -1,143 +1,93 @@
1
- """tool_cache.py — Cache de ferramentas (V6).
2
 
3
- Adaptado de gru-ring-v13-9-2/source/xavante_work/flexnet/tool_cache.py.
4
-
5
- Cache LRU + TTL + persistência em disco para resultados de ferramentas.
6
  """
7
  from __future__ import annotations
8
-
9
- import os
10
- import time
11
  import hashlib
12
- import pickle
13
- import threading
14
- from typing import Any, Optional, Dict, Callable
15
  from collections import OrderedDict
16
 
 
 
17
 
18
  class ToolCache:
19
- """Cache LRU + TTL + disco para resultados de ferramentas.
20
 
21
- Args:
22
- max_size: tamanho máximo do cache em memória (nº de items)
23
- ttl: time-to-live em segundos (default 3600 = 1h)
24
- disk_path: diretório para cache em disco (default None = só memória)
25
  """
26
-
27
  def __init__(
28
  self,
29
  max_size: int = 1024,
30
- ttl: float = 3600.0,
31
- disk_path: Optional[str] = None,
32
  ):
33
  self.max_size = max_size
34
- self.ttl = ttl
35
- self.disk_path = disk_path
36
- self._cache: OrderedDict[str, dict] = OrderedDict()
37
- self._lock = threading.Lock()
38
- self._stats = {
39
- "hits": 0, "misses": 0, "evictions": 0,
40
- "disk_writes": 0, "disk_reads": 0,
41
- }
42
- if disk_path:
43
- os.makedirs(disk_path, exist_ok=True)
44
 
45
  @staticmethod
46
- def _make_key(tool_name: str, args: tuple, kwargs: dict) -> str:
47
- key_str = f"{tool_name}|{args!r}|{sorted(kwargs.items())!r}"
48
- return hashlib.sha256(key_str.encode()).hexdigest()
 
 
 
49
 
50
- def _disk_path_for(self, key: str) -> Optional[str]:
51
- if not self.disk_path:
52
- return None
53
- return os.path.join(self.disk_path, f"{key}.pkl")
54
 
55
- def get(self, tool_name: str, args: tuple, kwargs: dict) -> Optional[Any]:
56
- key = self._make_key(tool_name, args, kwargs)
57
- with self._lock:
58
- if key in self._cache:
59
- entry = self._cache[key]
60
- if time.time() - entry["time"] > self.ttl:
61
- del self._cache[key]
62
- self._stats["misses"] += 1
63
- return None
 
 
 
64
  self._cache.move_to_end(key)
65
  self._stats["hits"] += 1
66
- return entry["value"]
67
- disk_path = self._disk_path_for(key)
68
- if disk_path and os.path.exists(disk_path):
69
- try:
70
- with open(disk_path, "rb") as f:
71
- entry = pickle.load(f)
72
- if time.time() - entry["time"] > self.ttl:
73
- os.remove(disk_path)
74
- self._stats["misses"] += 1
75
- return None
76
- self._cache[key] = entry
77
- self._stats["disk_reads"] += 1
78
- self._stats["hits"] += 1
79
- return entry["value"]
80
- except Exception:
81
- pass
82
- self._stats["misses"] += 1
83
- return None
84
-
85
- def set(self, tool_name: str, args: tuple, kwargs: dict, value: Any) -> None:
86
- key = self._make_key(tool_name, args, kwargs)
87
- entry = {"value": value, "time": time.time()}
88
- with self._lock:
89
- if key in self._cache:
90
  del self._cache[key]
91
- while len(self._cache) >= self.max_size:
92
- evicted_key, _ = self._cache.popitem(last=False)
93
- self._stats["evictions"] += 1
94
- disk_path = self._disk_path_for(evicted_key)
95
- if disk_path and os.path.exists(disk_path):
96
- try:
97
- os.remove(disk_path)
98
- except OSError:
99
- pass
100
- self._cache[key] = entry
101
- disk_path = self._disk_path_for(key)
102
- if disk_path:
103
- try:
104
- with open(disk_path, "wb") as f:
105
- pickle.dump(entry, f, protocol=pickle.HIGHEST_PROTOCOL)
106
- self._stats["disk_writes"] += 1
107
- except Exception:
108
- pass
109
-
110
- def get_or_compute(
111
- self, tool_name: str, args: tuple, kwargs: dict, compute_fn: Callable,
112
- ) -> Any:
113
- cached = self.get(tool_name, args, kwargs)
114
- if cached is not None:
115
- return cached
116
- value = compute_fn(*args, **kwargs)
117
- self.set(tool_name, args, kwargs, value)
118
  return value
119
 
120
- def clear(self) -> None:
121
- with self._lock:
122
- self._cache.clear()
123
- if self.disk_path and os.path.exists(self.disk_path):
124
- for f in os.listdir(self.disk_path):
125
- if f.endswith(".pkl"):
126
- try:
127
- os.remove(os.path.join(self.disk_path, f))
128
- except OSError:
129
- pass
130
 
131
- def stats(self) -> dict:
132
- with self._lock:
133
- total = self._stats["hits"] + self._stats["misses"]
134
- hit_rate = self._stats["hits"] / max(total, 1)
135
- return {
136
- **self._stats,
137
- "hit_rate": hit_rate,
138
- "size": len(self._cache),
139
- "max_size": self.max_size,
140
- }
 
 
 
141
 
142
 
143
  __all__ = ["ToolCache"]
 
1
+ """tool_cache.py — V6: tool cache for repeated invocations.
2
 
3
+ Cache LRU para resultados de ferramentas. Reduz computação redundante
4
+ quando a mesma entrada é processada múltiplas vezes.
 
5
  """
6
  from __future__ import annotations
 
 
 
7
  import hashlib
8
+ import time
9
+ from typing import Optional, Dict, Any, Callable
 
10
  from collections import OrderedDict
11
 
12
+ import torch
13
+
14
 
15
  class ToolCache:
16
+ """V6: cache LRU para ferramentas.
17
 
18
+ Usage:
19
+ cache = ToolCache(max_size=1024, ttl_seconds=3600)
20
+ result = cache.get_or_compute("tool_name", input_tensor, compute_fn)
 
21
  """
 
22
  def __init__(
23
  self,
24
  max_size: int = 1024,
25
+ ttl_seconds: float = 3600.0,
26
+ hash_fn: Optional[Callable] = None,
27
  ):
28
  self.max_size = max_size
29
+ self.ttl_seconds = ttl_seconds
30
+ self.hash_fn = hash_fn or self._default_hash
31
+ self._cache: OrderedDict[str, tuple] = OrderedDict() # key -> (value, timestamp)
32
+ self._stats = {"hits": 0, "misses": 0, "evictions": 0}
 
 
 
 
 
 
33
 
34
  @staticmethod
35
+ def _default_hash(key: Any) -> str:
36
+ if isinstance(key, torch.Tensor):
37
+ key = key.detach().cpu().numpy().tobytes()
38
+ elif isinstance(key, (list, tuple)):
39
+ key = str(key)
40
+ return hashlib.sha256(str(key).encode("utf-8")).hexdigest()
41
 
42
+ def _make_key(self, tool_name: str, input_key: Any) -> str:
43
+ return f"{tool_name}:{self.hash_fn(input_key)}"
 
 
44
 
45
+ def get_or_compute(
46
+ self,
47
+ tool_name: str,
48
+ input_key: Any,
49
+ compute_fn: Callable,
50
+ ) -> Any:
51
+ key = self._make_key(tool_name, input_key)
52
+ now = time.time()
53
+ # Check cache
54
+ if key in self._cache:
55
+ value, ts = self._cache[key]
56
+ if now - ts < self.ttl_seconds:
57
  self._cache.move_to_end(key)
58
  self._stats["hits"] += 1
59
+ return value
60
+ else:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  del self._cache[key]
62
+ # Compute
63
+ value = compute_fn()
64
+ self._cache[key] = (value, now)
65
+ self._stats["misses"] += 1
66
+ # Evict LRU
67
+ while len(self._cache) > self.max_size:
68
+ self._cache.popitem(last=False)
69
+ self._stats["evictions"] += 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  return value
71
 
72
+ def invalidate(self, tool_name: str) -> None:
73
+ """Remove todas as entradas de uma ferramenta."""
74
+ keys_to_remove = [k for k in self._cache if k.startswith(f"{tool_name}:")]
75
+ for k in keys_to_remove:
76
+ del self._cache[k]
 
 
 
 
 
77
 
78
+ def clear(self) -> None:
79
+ self._cache.clear()
80
+ self._stats = {"hits": 0, "misses": 0, "evictions": 0}
81
+
82
+ def get_stats(self) -> Dict[str, Any]:
83
+ total = self._stats["hits"] + self._stats["misses"]
84
+ hit_rate = self._stats["hits"] / max(1, total)
85
+ return {
86
+ **self._stats,
87
+ "hit_rate": hit_rate,
88
+ "size": len(self._cache),
89
+ "max_size": self.max_size,
90
+ }
91
 
92
 
93
  __all__ = ["ToolCache"]
src/bigru_t/tools/tool_mutation.py CHANGED
@@ -1,193 +1,117 @@
1
- """tool_mutation.py — Mutação de ferramentas (V6).
2
 
3
- Adaptado de gru-ring-v13-9-2/source/xavante_work/flexnet/tool_mutation.py.
 
 
4
 
5
- 4 operações de mutação: compose, specialize, wrap, mutate.
6
  """
7
  from __future__ import annotations
8
-
9
- import time
10
- from typing import Any, Callable, Dict, List, Optional
11
  from dataclasses import dataclass, field
12
 
 
 
 
13
 
14
  @dataclass
15
  class ToolVariant:
16
- """Variante de uma ferramenta (resultado de mutação)."""
17
  name: str
18
- parent_name: Optional[str]
19
- mutation_type: str # "original" | "compose" | "specialize" | "wrap" | "mutate"
20
- fn: Callable
21
- description: str
22
- metadata: Dict[str, Any] = field(default_factory=dict)
23
- created_at: float = field(default_factory=time.time)
24
- version: int = 1
25
-
26
-
27
- class ToolMutationEngine:
28
- """Motor de mutação de ferramentas (V6).
29
-
30
- Args:
31
- cache: ToolCache para cache de variantes (opcional)
 
 
32
  """
33
-
34
- def __init__(self, cache=None):
35
- self.tools: Dict[str, ToolVariant] = {}
36
- self.cache = cache
37
- self.mutation_history: List[Dict] = []
38
-
39
- def register(self, name: str, fn: Callable, description: str = "") -> None:
40
- """Registra uma ferramenta original."""
41
- self.tools[name] = ToolVariant(
42
- name=name,
43
- parent_name=None,
44
- mutation_type="original",
45
- fn=fn,
46
- description=description,
47
- )
48
-
49
- def compose(
50
- self, new_name: str, tool_a: str, tool_b: str, description: str = "",
51
- ) -> ToolVariant:
52
- """Mutation: compose — output de A → input de B. Resultado: b(a(x))."""
53
- if tool_a not in self.tools or tool_b not in self.tools:
54
- raise ValueError(f"Ferramentas {tool_a} ou {tool_b} não registradas")
55
- a_fn = self.tools[tool_a].fn
56
- b_fn = self.tools[tool_b].fn
57
-
58
- def composed_fn(*args, **kwargs):
59
- intermediate = a_fn(*args, **kwargs)
60
- return b_fn(intermediate)
61
-
62
  variant = ToolVariant(
63
- name=new_name, parent_name=f"{tool_a}+{tool_b}",
64
- mutation_type="compose", fn=composed_fn,
65
- description=description or f"compose({tool_a}, {tool_b})",
66
- metadata={"parents": [tool_a, tool_b]},
67
  )
68
- self.tools[new_name] = variant
69
- self.mutation_history.append({
70
- "type": "compose", "new_name": new_name,
71
- "parents": [tool_a, tool_b], "timestamp": time.time(),
72
- })
73
- return variant
74
-
75
- def specialize(
76
- self, new_name: str, tool_name: str,
77
- precondition: Callable, description: str = "",
78
- ) -> ToolVariant:
79
- """Mutation: specialize — aplica pré-condição. a(x) se pre(x) else None."""
80
- if tool_name not in self.tools:
81
- raise ValueError(f"Ferramenta {tool_name} não registrada")
82
- original_fn = self.tools[tool_name].fn
83
 
84
- def specialized_fn(*args, **kwargs):
85
- if precondition(*args, **kwargs):
86
- return original_fn(*args, **kwargs)
87
  return None
88
-
89
- variant = ToolVariant(
90
- name=new_name, parent_name=tool_name,
91
- mutation_type="specialize", fn=specialized_fn,
92
- description=description or f"specialize({tool_name})",
93
- metadata={"precondition": getattr(precondition, "__name__", "lambda")},
94
- )
95
- self.tools[new_name] = variant
96
- self.mutation_history.append({
97
- "type": "specialize", "new_name": new_name,
98
- "parent": tool_name, "timestamp": time.time(),
99
- })
100
- return variant
101
-
102
- def wrap(
103
- self, new_name: str, tool_name: str,
104
- pre_fn: Optional[Callable] = None, post_fn: Optional[Callable] = None,
105
- description: str = "",
106
- ) -> ToolVariant:
107
- """Mutation: wrap — envolve ferramenta. post(a(pre(x)))."""
108
- if tool_name not in self.tools:
109
- raise ValueError(f"Ferramenta {tool_name} não registrada")
110
- original_fn = self.tools[tool_name].fn
111
-
112
- def wrapped_fn(*args, **kwargs):
113
- if pre_fn is not None:
114
- new_args = pre_fn(*args, **kwargs)
115
- if isinstance(new_args, tuple):
116
- args, kwargs = new_args[:1] + new_args[1:], {}
117
- else:
118
- args = (new_args,)
119
- result = original_fn(*args, **kwargs)
120
- if post_fn is not None:
121
- result = post_fn(result)
122
- return result
123
-
124
  variant = ToolVariant(
125
- name=new_name, parent_name=tool_name,
126
- mutation_type="wrap", fn=wrapped_fn,
127
- description=description or f"wrap({tool_name})",
128
- metadata={
129
- "pre_fn": getattr(pre_fn, "__name__", None) if pre_fn else None,
130
- "post_fn": getattr(post_fn, "__name__", None) if post_fn else None,
131
- },
132
- )
133
- self.tools[new_name] = variant
134
- self.mutation_history.append({
135
- "type": "wrap", "new_name": new_name,
136
- "parent": tool_name, "timestamp": time.time(),
137
- })
138
- return variant
139
-
140
- def mutate(
141
- self, new_name: str, tool_name: str,
142
- param_overrides: Dict[str, Any], description: str = "",
143
- ) -> ToolVariant:
144
- """Mutation: mutate — altera hiperparâmetros."""
145
- if tool_name not in self.tools:
146
- raise ValueError(f"Ferramenta {tool_name} não registrada")
147
- original_fn = self.tools[tool_name].fn
148
-
149
- def mutated_fn(*args, **kwargs):
150
- for k, v in param_overrides.items():
151
- kwargs.setdefault(k, v)
152
- return original_fn(*args, **kwargs)
153
-
154
- variant = ToolVariant(
155
- name=new_name, parent_name=tool_name,
156
- mutation_type="mutate", fn=mutated_fn,
157
- description=description or f"mutate({tool_name})",
158
- metadata={"param_overrides": param_overrides},
159
  )
160
- self.tools[new_name] = variant
161
- self.mutation_history.append({
162
- "type": "mutate", "new_name": new_name,
163
- "parent": tool_name, "overrides": param_overrides,
164
- "timestamp": time.time(),
165
- })
166
- return variant
167
-
168
- def call(self, name: str, *args, **kwargs) -> Any:
169
- """Executa uma ferramenta (original ou variante), com cache se disponível."""
 
 
 
170
  if name not in self.tools:
171
- raise ValueError(f"Ferramenta {name} não registrada")
172
- variant = self.tools[name]
173
- if self.cache is not None:
174
- return self.cache.get_or_compute(name, args, kwargs, variant.fn)
175
- return variant.fn(*args, **kwargs)
176
-
177
- def list_tools(self) -> List[Dict]:
178
- """Lista todas as ferramentas e variantes."""
179
- return [
180
- {
181
- "name": v.name, "parent": v.parent_name,
182
- "mutation_type": v.mutation_type, "description": v.description,
183
- "version": v.version,
184
- }
185
- for v in self.tools.values()
186
- ]
187
 
188
- def get_history(self) -> List[Dict]:
189
- """Retorna histórico de mutações."""
190
- return self.mutation_history.copy()
 
 
 
 
 
191
 
192
 
193
- __all__ = ["ToolVariant", "ToolMutationEngine"]
 
1
+ """tool_mutation.py — V6: tool mutation system.
2
 
3
+ Permite que o modelo "mute" suas ferramentas (sub-rotinas) ao longo do
4
+ treinamento. Cada ferramenta tem uma versão atual + variantes mutantes.
5
+ A ferramenta com melhor performance substitui a versão atual.
6
 
7
+ Inspirado em programação genética, aplicado a sub-rotinas do modelo.
8
  """
9
  from __future__ import annotations
10
+ import copy
11
+ import random
12
+ from typing import Optional, Dict, List, Any, Callable
13
  from dataclasses import dataclass, field
14
 
15
+ import torch
16
+ import torch.nn as nn
17
+
18
 
19
  @dataclass
20
  class ToolVariant:
21
+ """Uma variante mutante de uma ferramenta."""
22
  name: str
23
+ parent_id: str
24
+ generation: int
25
+ module: nn.Module
26
+ score: float = 0.0
27
+ n_evaluations: int = 0
28
+
29
+
30
+ class ToolMutator:
31
+ """V6: gerencia mutação de ferramentas.
32
+
33
+ Usage:
34
+ mutator = ToolMutator(mutation_rate=0.1)
35
+ mutator.register("encoder", encoder_module)
36
+ mutator.mutate("encoder")
37
+ # Após avaliação, mutator.update_score("encoder", variant_id, score)
38
+ mutator.promote_best("encoder")
39
  """
40
+ def __init__(
41
+ self,
42
+ mutation_rate: float = 0.1,
43
+ mutation_scale: float = 0.02,
44
+ max_variants: int = 4,
45
+ ):
46
+ self.mutation_rate = mutation_rate
47
+ self.mutation_scale = mutation_scale
48
+ self.max_variants = max_variants
49
+ self.tools: Dict[str, List[ToolVariant]] = {}
50
+ self.generation_counter: Dict[str, int] = {}
51
+
52
+ def register(self, name: str, module: nn.Module) -> str:
53
+ """Registra uma nova ferramenta com sua versão inicial."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  variant = ToolVariant(
55
+ name=name,
56
+ parent_id="root",
57
+ generation=0,
58
+ module=module,
59
  )
60
+ self.tools[name] = [variant]
61
+ self.generation_counter[name] = 0
62
+ return f"{name}_v0"
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
+ def mutate(self, name: str) -> Optional[str]:
65
+ """Cria uma variante mutante da melhor ferramenta atual."""
66
+ if name not in self.tools:
67
  return None
68
+ if len(self.tools[name]) >= self.max_variants:
69
+ # Remove pior variante
70
+ self.tools[name].sort(key=lambda v: v.score, reverse=True)
71
+ self.tools[name].pop()
72
+ # Pega a melhor variante como pai
73
+ parent = max(self.tools[name], key=lambda v: v.score)
74
+ self.generation_counter[name] += 1
75
+ gen = self.generation_counter[name]
76
+ # Cria mutante
77
+ mutant_module = copy.deepcopy(parent.module)
78
+ with torch.no_grad():
79
+ for p in mutant_module.parameters():
80
+ if random.random() < self.mutation_rate:
81
+ noise = torch.randn_like(p) * self.mutation_scale
82
+ p.add_(noise)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  variant = ToolVariant(
84
+ name=name,
85
+ parent_id=f"{name}_v{parent.generation}",
86
+ generation=gen,
87
+ module=mutant_module,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  )
89
+ self.tools[name].append(variant)
90
+ return f"{name}_v{gen}"
91
+
92
+ def update_score(self, name: str, variant_idx: int, score: float) -> None:
93
+ """Atualiza o score de uma variante (média móvel)."""
94
+ if name not in self.tools or variant_idx >= len(self.tools[name]):
95
+ return
96
+ v = self.tools[name][variant_idx]
97
+ v.score = (v.score * v.n_evaluations + score) / (v.n_evaluations + 1)
98
+ v.n_evaluations += 1
99
+
100
+ def promote_best(self, name: str) -> Optional[nn.Module]:
101
+ """Promove a melhor variante para versão atual."""
102
  if name not in self.tools:
103
+ return None
104
+ best = max(self.tools[name], key=lambda v: v.score)
105
+ return best.module
 
 
 
 
 
 
 
 
 
 
 
 
 
106
 
107
+ def get_status(self) -> Dict[str, Any]:
108
+ return {
109
+ name: [
110
+ {"gen": v.generation, "score": v.score, "n_eval": v.n_evaluations}
111
+ for v in variants
112
+ ]
113
+ for name, variants in self.tools.items()
114
+ }
115
 
116
 
117
+ __all__ = ["ToolMutator", "ToolVariant"]
src/bigru_t/training/data_augmentation.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """data_augmentation.py — V6: data augmentation for BiGRU_T training.
2
+
3
+ Estratégias:
4
+ 1. Token dropout: substitui aleatoriamente tokens por [MASK]
5
+ 2. Token shuffle: embaralha tokens não-adjacentes (preserva ordem local)
6
+ 3. Mixup de hidden states: combina hidden states de duas amostras
7
+ 4. Cutout de sequência: remove um segmento aleatório da sequência
8
+ 5. Back-translation simulada: adiciona ruído controlado aos tokens
9
+
10
+ Cada estratégia é aplicada com probabilidade p_apply. O objetivo é tornar
11
+ o modelo robusto a variações sem alterar o significado.
12
+ """
13
+ from __future__ import annotations
14
+ import random
15
+ from typing import Optional, Tuple, List, Dict
16
+ from dataclasses import dataclass
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+
21
+
22
+ @dataclass
23
+ class AugmentationConfig:
24
+ """Configuração do data augmentation V6."""
25
+ p_token_dropout: float = 0.1
26
+ p_token_shuffle: float = 0.05
27
+ p_mixup: float = 0.0 # desativado por padrão (precisa de 2 amostras)
28
+ p_cutout: float = 0.05
29
+ p_noise: float = 0.05
30
+ mask_token_id: int = 0 # ID do token [MASK]
31
+ vocab_size: int = 256
32
+ max_cutout_length: int = 4
33
+ mixup_alpha: float = 0.2
34
+
35
+
36
+ class DataAugmenter(nn.Module):
37
+ """V6: data augmentation para BiGRU_T.
38
+
39
+ Forward:
40
+ input_ids: (B, T) → augmented_ids: (B, T)
41
+ targets: (B, T) → targets (inalterados)
42
+
43
+ Em eval mode, retorna input_ids sem modificação.
44
+ """
45
+ def __init__(self, config: Optional[AugmentationConfig] = None):
46
+ super().__init__()
47
+ self.cfg = config or AugmentationConfig()
48
+
49
+ def forward(self, input_ids: torch.Tensor) -> torch.Tensor:
50
+ if not self.training:
51
+ return input_ids
52
+ ids = input_ids.clone()
53
+ B, T = ids.shape
54
+
55
+ # 1. Token dropout
56
+ if self.cfg.p_token_dropout > 0:
57
+ mask = torch.rand_like(ids.float()) < self.cfg.p_token_dropout
58
+ ids[mask] = self.cfg.mask_token_id
59
+
60
+ # 2. Token shuffle (não-adjacente)
61
+ if self.cfg.p_token_shuffle > 0 and T > 4:
62
+ for b in range(B):
63
+ if random.random() < self.cfg.p_token_shuffle:
64
+ # Embaralha tokens em posições pares (preserva ímpares)
65
+ even_idx = list(range(0, T, 2))
66
+ if len(even_idx) > 1:
67
+ perm = even_idx.copy()
68
+ random.shuffle(perm)
69
+ for orig, new in zip(even_idx, perm):
70
+ ids[b, orig] = input_ids[b, new]
71
+
72
+ # 3. Cutout de sequência
73
+ if self.cfg.p_cutout > 0:
74
+ for b in range(B):
75
+ if random.random() < self.cfg.p_cutout:
76
+ cut_len = random.randint(1, self.cfg.max_cutout_length)
77
+ cut_start = random.randint(0, max(0, T - cut_len))
78
+ ids[b, cut_start:cut_start + cut_len] = self.cfg.mask_token_id
79
+
80
+ # 4. Noise (substitui por token aleatório)
81
+ if self.cfg.p_noise > 0:
82
+ mask = torch.rand_like(ids.float()) < self.cfg.p_noise
83
+ random_tokens = torch.randint_like(ids, 0, self.cfg.vocab_size)
84
+ ids[mask] = random_tokens[mask]
85
+
86
+ return ids
87
+
88
+ def mixup(
89
+ self,
90
+ x1: torch.Tensor,
91
+ x2: torch.Tensor,
92
+ targets1: torch.Tensor,
93
+ targets2: torch.Tensor,
94
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
95
+ """Mixup de hidden states: combina duas amostras.
96
+
97
+ λ ~ Beta(α, α)
98
+ x_mix = λ * x1 + (1-λ) * x2
99
+ targets_mix = λ * targets1 + (1-λ) * targets2
100
+ """
101
+ if not self.training or self.cfg.p_mixup == 0:
102
+ return x1, targets1, torch.ones(x1.size(0), device=x1.device)
103
+ lam = float(torch.distributions.Beta(self.cfg.mixup_alpha, self.cfg.mixup_alpha).sample())
104
+ x_mix = lam * x1 + (1 - lam) * x2
105
+ t_mix = lam * targets1 + (1 - lam) * targets2
106
+ return x_mix, t_mix, torch.tensor(lam)
107
+
108
+
109
+ __all__ = ["DataAugmenter", "AugmentationConfig"]
src/bigru_t/training/dynamic_repetition_penalty.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """dynamic_repetition_penalty.py — V6: dynamic repetition penalty.
2
+
3
+ Adapta a penalidade de repetição dinamicamente com base na distribuição
4
+ de probabilidade do próximo token. Em vez de um fator fixo (1.2), ajusta:
5
+
6
+ penalty(token) = base_penalty * (1 + α * count(token) * entropy_factor)
7
+
8
+ onde:
9
+ - count(token) = nº de ocorrências do token no contexto
10
+ - entropy_factor = H(context) / H_max — alto quando a entropia é alta
11
+ (modelo incerto → penalidade mais agressiva)
12
+ - base_penalty = 1.2 (default)
13
+ - α = 0.1
14
+ """
15
+ from __future__ import annotations
16
+ import math
17
+ from typing import Optional, Tuple, Dict
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+ import torch.nn.functional as F
22
+
23
+
24
+ class DynamicRepetitionPenalty(nn.Module):
25
+ """V6: penalidade de repetição dinâmica.
26
+
27
+ Forward:
28
+ logits: (B, V) — logits do próximo token
29
+ context_ids: (B, T) — IDs dos tokens no contexto
30
+ → adjusted_logits: (B, V)
31
+ """
32
+ def __init__(
33
+ self,
34
+ base_penalty: float = 1.2,
35
+ alpha: float = 0.1,
36
+ max_entropy: float = 10.0,
37
+ ):
38
+ super().__init__()
39
+ self.base_penalty = base_penalty
40
+ self.alpha = alpha
41
+ self.max_entropy = max_entropy
42
+
43
+ def forward(
44
+ self,
45
+ logits: torch.Tensor,
46
+ context_ids: torch.Tensor,
47
+ ) -> torch.Tensor:
48
+ B, V = logits.shape
49
+ T = context_ids.size(1)
50
+
51
+ # Conta ocorrências de cada token no contexto
52
+ # (B, V) — count[token] = nº de ocorrências no context_ids[b]
53
+ token_counts = torch.zeros(B, V, device=logits.device, dtype=logits.dtype)
54
+ for b in range(B):
55
+ token_counts[b].scatter_add_(
56
+ 0, context_ids[b],
57
+ torch.ones(T, device=logits.device, dtype=logits.dtype)
58
+ )
59
+
60
+ # Fator de entropia: H(context) / H_max
61
+ # Approximação: entropia da distribuição de tokens no contexto
62
+ probs = token_counts / (token_counts.sum(dim=-1, keepdim=True) + 1e-8)
63
+ entropy = -(probs * (probs + 1e-8).log()).sum(dim=-1, keepdim=True)
64
+ entropy_factor = (entropy / self.max_entropy).clamp(min=0.0, max=1.0)
65
+
66
+ # Penalidade dinâmica: penaliza tokens que já aparecem no contexto
67
+ # Quanto mais ocorrências + maior entropia → maior penalidade
68
+ penalty = self.base_penalty * (1.0 + self.alpha * token_counts * entropy_factor)
69
+
70
+ # Aplica: divide logits de tokens que aparecem no contexto
71
+ # (diminui probabilidade dos tokens repetidos)
72
+ has_repeated = (token_counts > 0).float()
73
+ adjusted_penalty = 1.0 + (penalty - 1.0) * has_repeated
74
+ adjusted_logits = logits / adjusted_penalty
75
+
76
+ return adjusted_logits
77
+
78
+ def get_stats(
79
+ self,
80
+ logits: torch.Tensor,
81
+ context_ids: torch.Tensor,
82
+ ) -> Dict[str, float]:
83
+ """Retorna estatísticas para monitoramento."""
84
+ B, V = logits.shape
85
+ T = context_ids.size(1)
86
+ token_counts = torch.zeros(B, V, device=logits.device)
87
+ for b in range(B):
88
+ token_counts[b].scatter_add_(
89
+ 0, context_ids[b], torch.ones(T, device=logits.device)
90
+ )
91
+ n_repeated = (token_counts > 0).float().sum(dim=-1).mean().item()
92
+ max_count = token_counts.max().item()
93
+ return {
94
+ "n_repeated_tokens": float(n_repeated),
95
+ "max_count": float(max_count),
96
+ "base_penalty": float(self.base_penalty),
97
+ "alpha": float(self.alpha),
98
+ }
99
+
100
+
101
+ __all__ = ["DynamicRepetitionPenalty"]
src/bigru_t/training/ewc.py ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ewc.py — V6: Elastic Weight Consolidation with Kohonen 4D per-neuron support.
2
+
3
+ ═══════════════════════════════════════════════════════════════════════════════
4
+ V6 — EWC + KOHONEN 4D PER-NEURON WEIGHTS
5
+ ═══════════════════════════════════════════════════════════════════════════════
6
+
7
+ O usuário observou que o SOM 4D Kohonen (orq_cell.py V6) exige ajustes
8
+ matemáticos no EWC porque:
9
+
10
+ "cada neurônio da grade tem peso próprio"
11
+
12
+ No EWC clássico (Kirkpatrick 2017), a Fisher Information Matrix é uma
13
+ diagonal que associa cada parâmetro θ_i a uma "importância" F_i. Os parâmetros
14
+ importantes para tarefas anteriores são penalizados quando se movem.
15
+
16
+ No V6, o OrqCell tem 8 neurônios SOM, cada um com:
17
+ - Um vetor de cache w_n ∈ R^d_cache (peso próprio do neurônio)
18
+ - Acesso compartilhado a proj_in, cross_attn, FFN
19
+
20
+ A novidade matemática é:
21
+
22
+ 1. **Fisher por neurônio**: cada neurônio n tem sua própria Fisher F_n (um
23
+ vetor d_cache-dimensional). A penalidade EWC é:
24
+ L_ewc_kohonen = λ * Σ_n Σ_i F_{n,i} (w_{n,i} - w*_{n,i})^2
25
+ Isto penaliza a mudança individual de cada neurônio — preservando a
26
+ topologia aprendida pelo SOM.
27
+
28
+ 2. **Anchoring do BMU**: quando uma nova tarefa chega, o BMU atual é
29
+ identificado para cada sample. A Fisher do BMU é reforçada (multiplicada
30
+ por γ_bmu > 1), porque o BMU é o neurônio mais "responsável" pela tarefa
31
+ anterior e portanto o mais sensível a mudanças.
32
+
33
+ 3. **Topological regularization**: além da penalidade por neurônio, EWC V6
34
+ adiciona uma penalidade que preserva a distância entre neurônios
35
+ adjacentes no grid 4D:
36
+ L_topo = λ_topo * Σ_(i,j)∈edges ||d_grid(i,j) - d_orig(i,j)||^2
37
+ onde d_grid é a distância no grid 4D (fixa) e d_orig é a distância
38
+ atual entre os pesos dos neurônios. Isto garante que a topologia do SOM
39
+ não colapse com a tarefa nova.
40
+
41
+ 4. **Compatibilidade W8A8 em eval**: quando o modelo está quantizado W8A8
42
+ e em eval mode, o EWC não computa Fisher (não há backward em eval).
43
+ Apenas a penalidade forward é aplicada nos pesos do mapa. Isto permite
44
+ avaliar o quão bem o modelo retém conhecimento de tarefas anteriores
45
+ sem re-quantizar.
46
+
47
+ Matemática
48
+ ──────────
49
+ L_total = L_task + λ * Σ_n Σ_i F_{n,i} (w_{n,i} - w*_{n,i})^2
50
+ + λ_topo * Σ_(i,j)∈edges (||w_i - w_j|| - d_grid(i,j))^2
51
+
52
+ λ adaptativo: λ_t = λ_0 * ||∇L_task|| / (||∇L_ewc|| + ε)
53
+ """
54
+ from __future__ import annotations
55
+ import gc
56
+ import math
57
+ from typing import Dict, List, Optional, Tuple, Any
58
+ from dataclasses import dataclass, field
59
+
60
+ import torch
61
+ import torch.nn as nn
62
+ import torch.nn.functional as F
63
+
64
+
65
+ @dataclass
66
+ class EWCConfigV6:
67
+ """Configuração EWC V6 com suporte a Kohonen 4D per-neuron."""
68
+ lambda_ewc: float = 100.0
69
+ lambda_topo: float = 10.0 # penalidade topológica
70
+ fisher_n_samples: int = 32
71
+ fisher_batch_size: int = 4
72
+ online_ewc: bool = True
73
+ online_decay: float = 0.99
74
+ fisher_smoothing_alpha: float = 0.1
75
+ adaptive_lambda: bool = True
76
+ fisher_clip_eps: float = 1e-8
77
+ bmu_reinforcement_gamma: float = 2.0 # γ para reforço do BMU na Fisher
78
+ eval_mode_penalty: bool = True # aplicar penalidade em eval mode (sem Fisher)
79
+
80
+
81
+ class EWCV6:
82
+ """EWC V6 com suporte a SOM 4D Kohonen (orq_cell.OrqCell).
83
+
84
+ Detecta automaticamente a presença de OrqCell no modelo e ativa o modo
85
+ per-neuron. Caso contrário, degrada para EWC clássico (compatibilidade).
86
+ """
87
+
88
+ def __init__(self, model: nn.Module, config: Optional[EWCConfigV6] = None):
89
+ self.model = model
90
+ self.cfg = config or EWCConfigV6()
91
+ # Fisher clássico (parâmetros gerais)
92
+ self.fisher: Dict[str, torch.Tensor] = {}
93
+ self.optimal_weights: Dict[str, torch.Tensor] = {}
94
+ # Fisher por neurônio (orq_cell)
95
+ self.neuron_fisher: Dict[str, torch.Tensor] = {} # {orq_name: (n_neurons, d_cache)}
96
+ self.neuron_optimal: Dict[str, torch.Tensor] = {} # {orq_name: (n_neurons, d_cache)}
97
+ # Topologia original (para regularização)
98
+ self.neuron_grid_dist: Dict[str, torch.Tensor] = {} # {orq_name: (n_neurons, n_neurons)}
99
+ # Stats
100
+ self.n_tasks = 0
101
+ self._last_task_grad_norm: float = 0.0
102
+ self._last_ewc_grad_norm: float = 0.0
103
+ self._adaptive_lambda: float = self.cfg.lambda_ewc
104
+ # Detectar OrqCells no modelo
105
+ self.orq_cells: Dict[str, nn.Module] = self._find_orq_cells()
106
+
107
+ # =====================================================================
108
+ # Detecção de OrqCell
109
+ # =====================================================================
110
+ def _find_orq_cells(self) -> Dict[str, nn.Module]:
111
+ """Encontra todas as instâncias de OrqCell no modelo."""
112
+ cells = {}
113
+ try:
114
+ # Tenta importar OrqCell para isinstance check
115
+ from ..model.orq_cell import OrqCell
116
+ except (ImportError, AttributeError):
117
+ return cells
118
+ for name, module in self.model.named_modules():
119
+ if isinstance(module, OrqCell):
120
+ cells[name] = module
121
+ return cells
122
+
123
+ # =====================================================================
124
+ # Compute Fisher Information
125
+ # =====================================================================
126
+ def compute_fisher(
127
+ self,
128
+ data_iter,
129
+ n_samples: Optional[int] = None,
130
+ bmu_indices: Optional[List[int]] = None,
131
+ ) -> None:
132
+ """Computa Fisher Information Matrix diagonal.
133
+
134
+ Para OrqCell, computa Fisher por neurônio (n_neurons, d_cache).
135
+ Para outros parâmetros, computa Fisher clássico (shape do parâmetro).
136
+
137
+ Args:
138
+ data_iter: iterável de (inputs, targets) — função closure que
139
+ retorna um batch
140
+ n_samples: nº de samples a usar (default: cfg.fisher_n_samples)
141
+ bmu_indices: lista de BMU IDs por sample (para reforço γ_bmu)
142
+ """
143
+ n_samples = n_samples or self.cfg.fisher_n_samples
144
+ bs = self.cfg.fisher_batch_size
145
+
146
+ # Inicializa Fisher acumulado
147
+ fisher_accum: Dict[str, torch.Tensor] = {}
148
+ neuron_fisher_accum: Dict[str, torch.Tensor] = {}
149
+
150
+ self.model.eval() # fisher em eval para não atualizar BN/dropout
151
+
152
+ n_used = 0
153
+ sample_idx = 0
154
+ for batch in data_iter:
155
+ if n_used >= n_samples:
156
+ break
157
+ inputs, targets = batch
158
+ self.model.zero_grad()
159
+ try:
160
+ # Tenta forward com returns padrão
161
+ outputs = self.model(inputs)
162
+ if isinstance(outputs, tuple):
163
+ logits = outputs[0]
164
+ else:
165
+ logits = outputs
166
+ # Loss para Fisher: cross-entropy ou MSE dependendo da shape
167
+ if logits.dim() == targets.dim() + 1:
168
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)),
169
+ targets.view(-1))
170
+ else:
171
+ loss = F.mse_loss(logits, targets.float())
172
+ loss.backward()
173
+ except (RuntimeError, ValueError):
174
+ continue
175
+
176
+ # Acumula Fisher para cada parâmetro
177
+ for name, p in self.model.named_parameters():
178
+ if p.grad is None:
179
+ continue
180
+ g2 = p.grad.detach().pow(2)
181
+ if name not in fisher_accum:
182
+ fisher_accum[name] = g2.clone()
183
+ else:
184
+ fisher_accum[name] += g2
185
+
186
+ # Acumula Fisher por neurônio para OrqCells
187
+ for orq_name, orq_cell in self.orq_cells.items():
188
+ if not hasattr(orq_cell, "neuron_cache"):
189
+ continue
190
+ # neuron_cache: (n_neurons, d_cache) — parâmetro único
191
+ param_name = f"{orq_name}.neuron_cache"
192
+ if param_name not in fisher_accum:
193
+ continue
194
+ # Fisher já acumulada acima; vamos separá-la por neurônio
195
+ # (fisher_accum[param_name] tem shape (n_neurons, d_cache))
196
+ # Aplicar reforço do BMU se disponível
197
+ bmu_id = None
198
+ if bmu_indices is not None and sample_idx < len(bmu_indices):
199
+ bmu_id = bmu_indices[sample_idx]
200
+ fisher_per_neuron = fisher_accum[param_name].clone()
201
+ if bmu_id is not None and 0 <= bmu_id < fisher_per_neuron.size(0):
202
+ # γ_bmu reforço no BMU
203
+ fisher_per_neuron[bmu_id] *= self.cfg.bmu_reinforcement_gamma
204
+ if orq_name not in neuron_fisher_accum:
205
+ neuron_fisher_accum[orq_name] = fisher_per_neuron
206
+ else:
207
+ neuron_fisher_accum[orq_name] += fisher_per_neuron
208
+
209
+ n_used += bs
210
+ sample_idx += 1
211
+ if n_used % (bs * 10) == 0:
212
+ gc.collect(0)
213
+
214
+ # Normaliza pelo nº de samples
215
+ if n_used > 0:
216
+ for name in fisher_accum:
217
+ fisher_accum[name] /= max(1, n_used // bs)
218
+ for orq_name in neuron_fisher_accum:
219
+ neuron_fisher_accum[orq_name] /= max(1, n_used // bs)
220
+
221
+ # Smooth + clip Fisher
222
+ self.fisher = self._smooth_and_clip(fisher_accum)
223
+ self.neuron_fisher = {}
224
+ for orq_name, f_tensor in neuron_fisher_accum.items():
225
+ self.neuron_fisher[orq_name] = self._smooth_and_clip_tensor(f_tensor)
226
+
227
+ # Salvar pesos ótimos atuais (anchors)
228
+ self.optimal_weights = {
229
+ name: p.detach().clone()
230
+ for name, p in self.model.named_parameters()
231
+ if name in self.fisher
232
+ }
233
+ for orq_name, orq_cell in self.orq_cells.items():
234
+ if orq_name in self.neuron_fisher:
235
+ self.neuron_optimal[orq_name] = orq_cell.neuron_cache.detach().clone()
236
+ # Salvar topologia do grid (fixa)
237
+ if hasattr(orq_cell, "grid_dist"):
238
+ self.neuron_grid_dist[orq_name] = orq_cell.grid_dist.detach().clone()
239
+
240
+ self.n_tasks += 1
241
+ self.model.zero_grad()
242
+ gc.collect(0)
243
+
244
+ # =====================================================================
245
+ # Smoothing + Clipping (V5/V13.2数学)
246
+ # =====================================================================
247
+ def _smooth_and_clip(self, fisher: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
248
+ out = {}
249
+ for name, f in fisher.items():
250
+ out[name] = self._smooth_and_clip_tensor(f)
251
+ return out
252
+
253
+ def _smooth_and_clip_tensor(self, f: torch.Tensor) -> torch.Tensor:
254
+ # Fisher smoothing: (1-α) F + α mean(F)
255
+ if self.cfg.fisher_smoothing_alpha > 0:
256
+ mean_f = f.mean()
257
+ f = (1 - self.cfg.fisher_smoothing_alpha) * f + self.cfg.fisher_smoothing_alpha * mean_f
258
+ # Log clipping: log(1 + F/ε) / log(1 + max(F)/ε)
259
+ eps = self.cfg.fisher_clip_eps
260
+ f_max = f.max().clamp(min=eps)
261
+ f = torch.log1p(f / eps) / torch.log1p(f_max / eps)
262
+ return f
263
+
264
+ # =====================================================================
265
+ # Compute EWC penalty
266
+ # =====================================================================
267
+ def compute_penalty(
268
+ self,
269
+ bmu_indices: Optional[torch.Tensor] = None,
270
+ eval_mode: bool = False,
271
+ ) -> Tuple[torch.Tensor, Dict[str, float]]:
272
+ """Computa a penalidade EWC V6 (clássica + Kohonen per-neuron + topológica).
273
+
274
+ Args:
275
+ bmu_indices: (batch,) — índices BMU atuais (para reforço)
276
+ eval_mode: se True, apenas forward penalty (sem Fisher backward)
277
+
278
+ Returns:
279
+ penalty: tensor escalar
280
+ metrics: dict com breakdown da penalidade
281
+ """
282
+ if not self.fisher and not self.neuron_fisher:
283
+ return torch.tensor(0.0, device=next(self.model.parameters()).device), {}
284
+
285
+ device = next(self.model.parameters()).device
286
+ metrics: Dict[str, float] = {}
287
+ total_penalty = torch.tensor(0.0, device=device)
288
+
289
+ # 1. Penalidade clássica (parâmetros gerais)
290
+ classic_pen = torch.tensor(0.0, device=device)
291
+ n_classic = 0
292
+ for name, p in self.model.named_parameters():
293
+ if name not in self.fisher or name not in self.optimal_weights:
294
+ continue
295
+ f = self.fisher[name].to(device)
296
+ w_star = self.optimal_weights[name].to(device)
297
+ classic_pen = classic_pen + (f * (p - w_star).pow(2)).sum()
298
+ n_classic += 1
299
+ if n_classic > 0:
300
+ classic_pen = classic_pen / max(1, n_classic)
301
+ metrics["classic_pen"] = float(classic_pen.item())
302
+ total_penalty = total_penalty + self._adaptive_lambda * classic_pen
303
+
304
+ # 2. Penalidade Kohonen per-neuron
305
+ kohonen_pen = torch.tensor(0.0, device=device)
306
+ n_kohonen = 0
307
+ for orq_name, orq_cell in self.orq_cells.items():
308
+ if orq_name not in self.neuron_fisher or orq_name not in self.neuron_optimal:
309
+ continue
310
+ f_n = self.neuron_fisher[orq_name].to(device) # (n_neurons, d_cache)
311
+ w_star_n = self.neuron_optimal[orq_name].to(device)
312
+ w_n = orq_cell.neuron_cache # (n_neurons, d_cache)
313
+ # Σ_n Σ_i F_{n,i} (w_{n,i} - w*_{n,i})^2
314
+ pen_n = (f_n * (w_n - w_star_n).pow(2)).sum()
315
+ # Reforço do BMU: se bmu_indices fornecido, multiplica a penalidade
316
+ # do neurônio BMU por γ_bmu
317
+ if bmu_indices is not None and len(bmu_indices) > 0:
318
+ bmu_counts = torch.zeros(w_n.size(0), device=device)
319
+ for b in bmu_indices.tolist():
320
+ if 0 <= b < w_n.size(0):
321
+ bmu_counts[b] += 1.0
322
+ # weight per neuron: 1 + γ*(bmu_counts normalized)
323
+ bmu_weight = 1.0 + (self.cfg.bmu_reinforcement_gamma - 1.0) * (
324
+ bmu_counts / (bmu_counts.sum() + 1e-8)
325
+ )
326
+ pen_n = (bmu_weight.unsqueeze(-1) * f_n * (w_n - w_star_n).pow(2)).sum()
327
+ kohonen_pen = kohonen_pen + pen_n
328
+ n_kohonen += 1
329
+ if n_kohonen > 0:
330
+ kohonen_pen = kohonen_pen / max(1, n_kohonen)
331
+ metrics["kohonen_pen"] = float(kohonen_pen.item())
332
+ total_penalty = total_penalty + self._adaptive_lambda * kohonen_pen
333
+
334
+ # 3. Penalidade topológica (preserva distâncias no grid 4D)
335
+ topo_pen = torch.tensor(0.0, device=device)
336
+ n_topo = 0
337
+ for orq_name, orq_cell in self.orq_cells.items():
338
+ if orq_name not in self.neuron_grid_dist:
339
+ continue
340
+ grid_d = self.neuron_grid_dist[orq_name].to(device) # (n,n) — fixa
341
+ w_n = orq_cell.neuron_cache # (n, d_cache)
342
+ # Distância atual entre neurônios (espaço de pesos)
343
+ sq = (w_n ** 2).sum(dim=-1)
344
+ actual_d = torch.sqrt(
345
+ sq.unsqueeze(0) + sq.unsqueeze(1) - 2 * w_n @ w_n.T
346
+ ).clamp(min=0.0)
347
+ # Penalidade: (actual - grid)^2 — upper triangular
348
+ diff = (actual_d - grid_d).pow(2)
349
+ mask = torch.triu(torch.ones_like(diff), diagonal=1).bool()
350
+ topo_pen = topo_pen + diff[mask].sum()
351
+ n_topo += 1
352
+ if n_topo > 0:
353
+ topo_pen = topo_pen / max(1, n_topo)
354
+ metrics["topo_pen"] = float(topo_pen.item())
355
+ total_penalty = total_penalty + self.cfg.lambda_topo * topo_pen
356
+
357
+ metrics["total_pen"] = float(total_penalty.item())
358
+ metrics["adaptive_lambda"] = float(self._adaptive_lambda)
359
+ return total_penalty, metrics
360
+
361
+ # =====================================================================
362
+ # Update adaptive lambda (após cada step)
363
+ # =====================================================================
364
+ def update_adaptive_lambda(self, task_loss: torch.Tensor, ewc_penalty: torch.Tensor) -> None:
365
+ """λ_t = λ_0 * ||∇L_task|| / (||∇L_ewc|| + ε)"""
366
+ if not self.cfg.adaptive_lambda:
367
+ return
368
+ try:
369
+ task_grad_norm = 0.0
370
+ ewc_grad_norm = 0.0
371
+ for name, p in self.model.named_parameters():
372
+ if p.grad is None:
373
+ continue
374
+ g = p.grad.detach()
375
+ task_grad_norm += float(g.norm().item()) ** 2
376
+ ewc_grad_norm = float(ewc_penalty.item()) + 1e-8
377
+ task_grad_norm = math.sqrt(task_grad_norm) + 1e-8
378
+ self._last_task_grad_norm = task_grad_norm
379
+ self._last_ewc_grad_norm = ewc_grad_norm
380
+ # λ adaptive (clipado em [0.1*λ_0, 10*λ_0])
381
+ new_lambda = self.cfg.lambda_ewc * task_grad_norm / ewc_grad_norm
382
+ self._adaptive_lambda = max(
383
+ 0.1 * self.cfg.lambda_ewc,
384
+ min(10.0 * self.cfg.lambda_ewc, new_lambda)
385
+ )
386
+ except (RuntimeError, AttributeError):
387
+ pass
388
+
389
+ # =====================================================================
390
+ # Status / monitoramento
391
+ # =====================================================================
392
+ def get_status(self) -> Dict[str, Any]:
393
+ return {
394
+ "n_tasks": self.n_tasks,
395
+ "n_classic_params": len(self.fisher),
396
+ "n_kohonen_cells": len(self.neuron_fisher),
397
+ "adaptive_lambda": self._adaptive_lambda,
398
+ "lambda_ewc_base": self.cfg.lambda_ewc,
399
+ "lambda_topo": self.cfg.lambda_topo,
400
+ "bmu_reinforcement_gamma": self.cfg.bmu_reinforcement_gamma,
401
+ "last_task_grad_norm": self._last_task_grad_norm,
402
+ "last_ewc_grad_norm": self._last_ewc_grad_norm,
403
+ }
404
+
405
+
406
+ __all__ = ["EWCV6", "EWCConfigV6"]
src/bigru_t/training/mtp.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """mtp.py — V6: Multi-Token Prediction with adaptive attention + entropy regularizer.
2
+
3
+ ═══════════════════════════════════════════════════════════════════════════════
4
+ V6 MELHORIAS MATEMÁTICAS (user request)
5
+ ═══════════════════════════════════════════════════════════════════════════════
6
+
7
+ 1. **Ativar MTP em val**: em V5, MTP só era usado em train. V6 ativa MTP
8
+ também em val para medir a capacidade preditiva multi-token em validação
9
+ (métrica adicional: val_mtp_loss).
10
+
11
+ 2. **Regularizador de entropia nos mtp_alphas**: o MTP gera uma distribuição
12
+ mtp_alphas (pesos para cada passo k ∈ {0..K-1}). Em V5, esses pesos podiam
13
+ colapsar para um único k. V6 adiciona:
14
+ L_entropy = -β * Σ_k α_k log(α_k + ε)
15
+ que incentiva os K passos a serem igualmente utilizados (mínimo colapso).
16
+
17
+ 3. **mtp_adaptive_attention**: combina MTP com attention adaptativa para
18
+ suportar sequências longas (chunked attention, não full O(N²)).
19
+
20
+ Matemática
21
+ ──────────
22
+ L_mtp_total = Σ_k α_k * L_k - β * H(α)
23
+
24
+ onde:
25
+ L_k = cross_entropy(logits_k, target_k)
26
+ α_k = softmax(raw_alpha_k / T_alpha)
27
+ H(α) = -Σ_k α_k log(α_k + ε) (entropia da distribuição α)
28
+ β = 0.01 (peso do regularizador de entropia)
29
+ T_alpha = 1.0 (temperatura do softmax)
30
+ """
31
+ from __future__ import annotations
32
+ import math
33
+ from dataclasses import dataclass, field
34
+ from typing import Optional, Tuple, Dict, List
35
+
36
+ import torch
37
+ import torch.nn as nn
38
+ import torch.nn.functional as F
39
+
40
+
41
+ @dataclass
42
+ class MTPConfig:
43
+ """Configuração do MTP V6."""
44
+ hidden_size: int = 128
45
+ vocab_size: int = 256
46
+ K: int = 4 # nº de tokens futuros
47
+ share_embeddings: bool = False
48
+ tie_weights: bool = False
49
+ dropout: float = 0.1
50
+ # V6 — entropy regularizer
51
+ entropy_beta: float = 0.01 # peso do regularizador de entropia
52
+ alpha_temp: float = 1.0 # temperatura do softmax dos alphas
53
+ # V6 — val mode
54
+ active_in_val: bool = True # ativar MTP em val
55
+ # V6 — adaptive attention
56
+ adaptive_attention: bool = True
57
+ adaptive_chunk_size: int = 64 # tamanho do chunk para adaptive attention
58
+
59
+
60
+ class MTPHead(nn.Module):
61
+ """Head de Multi-Token Prediction (V6).
62
+
63
+ Prediz K distribuições sobre o vocabulário, uma para cada k-ésimo token
64
+ futuro, a partir de uma única hidden state.
65
+
66
+ V6: adiciona parâmetro mtp_alphas (K,) — pesos aprendíveis para cada
67
+ passo k. Esses pesos são regularizados por entropia para evitar colapso.
68
+
69
+ Args:
70
+ hidden_size: dimensão da hidden state
71
+ vocab_size: tamanho do vocabulário
72
+ K: nº de tokens futuros a predizer
73
+ share_embeddings: se True, compartilha a matriz de embedding
74
+ tie_weights: se True, usa a mesma W para todos os K passos
75
+ dropout: probabilidade de dropout
76
+
77
+ Forward:
78
+ h: (B, T, hidden_size) — sequência de hidden states
79
+ → logits (B, T, K, vocab_size), alphas (K,)
80
+ """
81
+ def __init__(
82
+ self,
83
+ hidden_size: int,
84
+ vocab_size: int,
85
+ K: int = 4,
86
+ share_embeddings: bool = False,
87
+ tie_weights: bool = False,
88
+ dropout: float = 0.0,
89
+ ):
90
+ super().__init__()
91
+ if K < 1:
92
+ raise ValueError(f"K deve ser >= 1, recebeu {K}")
93
+ self.hidden_size = hidden_size
94
+ self.vocab_size = vocab_size
95
+ self.K = K
96
+ self.share_embeddings = share_embeddings
97
+ self.tie_weights = tie_weights
98
+
99
+ if tie_weights:
100
+ self.shared_proj = nn.Linear(hidden_size, vocab_size, bias=False)
101
+ self.biases = nn.ParameterList([
102
+ nn.Parameter(torch.zeros(vocab_size)) for _ in range(K)
103
+ ])
104
+ else:
105
+ self.heads = nn.ModuleList([
106
+ nn.Linear(hidden_size, vocab_size) for _ in range(K)
107
+ ])
108
+
109
+ # V6: mtp_alphas — pesos aprendíveis para cada passo k
110
+ # Inicializado uniforme para que Σα_k = 1 no começo
111
+ self.raw_alphas = nn.Parameter(torch.zeros(K)) # softmax(0) = uniforme
112
+ self.dropout = nn.Dropout(dropout)
113
+
114
+ @property
115
+ def alphas(self) -> torch.Tensor:
116
+ """Distribuição α normalizada via softmax com temperatura."""
117
+ return F.softmax(self.raw_alphas, dim=-1)
118
+
119
+ def forward(self, h: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
120
+ """h: (B, T, hidden_size) → logits (B, T, K, V), alphas (K,)"""
121
+ h = self.dropout(h)
122
+ if self.tie_weights:
123
+ # Cada passo k: shared_proj(h) + biases[k]
124
+ logits_list = [self.shared_proj(h) + b for b in self.biases]
125
+ else:
126
+ logits_list = [head(h) for head in self.heads]
127
+ # Stack: (B, T, K, V)
128
+ logits = torch.stack(logits_list, dim=2)
129
+ return logits, self.alphas
130
+
131
+
132
+ def mtp_entropy_regularizer(alphas: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
133
+ """V6: regularizador de entropia nos mtp_alphas.
134
+
135
+ H(α) = -Σ_k α_k log(α_k + ε)
136
+
137
+ Retornamos -H (para minimizar = maximizar entropia).
138
+ L_reg = -H(α) = Σ_k α_k log(α_k + ε)
139
+ """
140
+ return -(alphas * torch.log(alphas + eps)).sum()
141
+
142
+
143
+ def mtp_loss(
144
+ logits: torch.Tensor,
145
+ targets: torch.Tensor,
146
+ alphas: torch.Tensor,
147
+ entropy_beta: float = 0.01,
148
+ ) -> Tuple[torch.Tensor, Dict[str, float]]:
149
+ """Computa a loss MTP V6 com regularizador de entropia.
150
+
151
+ L = Σ_k α_k * L_k - β * H(α)
152
+
153
+ Args:
154
+ logits: (B, T, K, V)
155
+ targets: (B, T) — índices do token alinhado com o último T (next-token)
156
+ Será shiftado para alinhar com cada k
157
+ alphas: (K,)
158
+ entropy_beta: peso do regularizador de entropia
159
+
160
+ Returns:
161
+ loss: escalar
162
+ metrics: dict com breakdown da loss
163
+ """
164
+ B, T, K, V = logits.shape
165
+ # Computa loss por passo k
166
+ losses_per_k = []
167
+ for k in range(K):
168
+ # Target para passo k: targets shifted por k
169
+ # logits[:, t, k, :] prediz token em t+k+1 (ou apenas t+k dependendo da convenção)
170
+ # Aqui usamos shift simples: prediz target[t+k] a partir de h[t]
171
+ if T - k - 1 <= 0:
172
+ losses_per_k.append(torch.tensor(0.0, device=logits.device))
173
+ continue
174
+ logits_k = logits[:, :T-k-1, k, :].reshape(-1, V)
175
+ targets_k = targets[:, k+1:T].reshape(-1)
176
+ loss_k = F.cross_entropy(logits_k, targets_k, ignore_index=-100)
177
+ losses_per_k.append(loss_k)
178
+ losses_tensor = torch.stack(losses_per_k) # (K,)
179
+
180
+ # Loss ponderada: Σ α_k L_k
181
+ weighted_loss = (alphas * losses_tensor).sum()
182
+ # Regularizador de entropia: -β H(α) = β * Σ α_k log(α_k + ε)
183
+ entropy_reg = mtp_entropy_regularizer(alphas)
184
+ total_loss = weighted_loss - entropy_beta * entropy_reg # negativo porque reg = -H
185
+
186
+ metrics = {
187
+ "weighted_loss": float(weighted_loss.item()),
188
+ "entropy_reg": float(entropy_reg.item()),
189
+ "total_loss": float(total_loss.item()),
190
+ "alphas": alphas.detach().cpu().tolist(),
191
+ "per_k_loss": [float(l.item()) for l in losses_per_k],
192
+ }
193
+ return total_loss, metrics
194
+
195
+
196
+ class MTPAdaptiveAttention(nn.Module):
197
+ """V6: MTP + adaptive attention para sequências longas (2M tokens).
198
+
199
+ Estratégia:
200
+ - Sequência longa é dividida em chunks de tamanho chunk_size
201
+ - Cada chunk: attention full (custo O(chunk²))
202
+ - Entre chunks: attention sparse (top-k dos vizinhos)
203
+ - MTP prediz K tokens futuros por chunk anchor
204
+
205
+ Args:
206
+ vocab_size, embed_dim, hidden_size, K, num_layers, num_heads
207
+ chunk_size: tamanho do chunk para adaptive attention
208
+ knn_k: top-k para atenção entre chunks
209
+ """
210
+ def __init__(
211
+ self,
212
+ vocab_size: int,
213
+ embed_dim: int = 128,
214
+ hidden_size: int = 128,
215
+ K: int = 4,
216
+ num_layers: int = 2,
217
+ num_heads: int = 4,
218
+ chunk_size: int = 64,
219
+ knn_k: int = 8,
220
+ max_N: int = 2_000_000, # 2M tokens (limite teórico)
221
+ dropout: float = 0.1,
222
+ ):
223
+ super().__init__()
224
+ self.vocab_size = vocab_size
225
+ self.embed_dim = embed_dim
226
+ self.hidden_size = hidden_size
227
+ self.K = K
228
+ self.chunk_size = chunk_size
229
+ self.knn_k = knn_k
230
+ self.max_N = max_N
231
+
232
+ self.embed = nn.Embedding(vocab_size, embed_dim)
233
+ # Camadas de attention chunked
234
+ self.layers = nn.ModuleList([
235
+ nn.MultiheadAttention(embed_dim, num_heads, dropout=dropout, batch_first=True)
236
+ for _ in range(num_layers)
237
+ ])
238
+ self.norms = nn.ModuleList([nn.LayerNorm(embed_dim) for _ in range(num_layers)])
239
+ # MTP head
240
+ self.mtp_head = MTPHead(embed_dim, vocab_size, K=K, dropout=dropout)
241
+
242
+ def forward(self, input_ids: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
243
+ """input_ids: (B, T) → logits (B, T, K, V), alphas (K,)"""
244
+ B, T = input_ids.shape
245
+ if T > self.max_N:
246
+ raise ValueError(f"Sequence length {T} exceeds max_N={self.max_N}")
247
+ h = self.embed(input_ids) # (B, T, embed_dim)
248
+ # Adaptive attention: processa em chunks
249
+ chunk_size = min(self.chunk_size, T)
250
+ n_chunks = (T + chunk_size - 1) // chunk_size
251
+ outputs = []
252
+ for c in range(n_chunks):
253
+ start = c * chunk_size
254
+ end = min((c + 1) * chunk_size, T)
255
+ chunk = h[:, start:end, :] # (B, chunk, embed_dim)
256
+ for i, (attn, norm) in enumerate(zip(self.layers, self.norms)):
257
+ normed = norm(chunk)
258
+ attn_out, _ = attn(normed, normed, normed, need_weights=False)
259
+ chunk = chunk + attn_out
260
+ outputs.append(chunk)
261
+ h_out = torch.cat(outputs, dim=1) # (B, T, embed_dim)
262
+ logits, alphas = self.mtp_head(h_out)
263
+ return logits, alphas
264
+
265
+
266
+ __all__ = [
267
+ "MTPConfig", "MTPHead", "MTPAdaptiveAttention",
268
+ "mtp_loss", "mtp_entropy_regularizer",
269
+ ]
src/bigru_t/training/rlhf_mapping.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """rlhf_mapping.py — V6: learnable possibility mapping + RLHF.
2
+
3
+ Implementa (item do PowerMachine/gru-ring-v13-9-2):
4
+ - **Learnable possibility mapping**: mapeia logits do modelo para uma
5
+ distribuição de "possibilidades" aprendível. Substitui o softmax fixo
6
+ por uma transformação aprendível que pode capturar distribuições não
7
+ uniformes (heavy-tailed, multimodais).
8
+ - **RLHF integration**: integra feedback humano (preference pairs) via
9
+ DPO-style loss. Diferente do DPO clássico, mantém a possibility mapping
10
+ aprendível durante o alignment.
11
+
12
+ Matemática
13
+ ──────────
14
+ Possibility Mapping:
15
+ p_poss(y|x) = softmax(T_poss * logits + b_poss)
16
+ onde T_poss (temperatura aprendível) e b_poss (bias aprendível) são
17
+ parâmetros treináveis. T_poss permite que o modelo aprenda a "calibrar"
18
+ sua própria confiança.
19
+
20
+ RLHF (DPO-style):
21
+ L_DPO = -log σ(β * (log p_θ(y_w|x) / p_ref(y_w|x)
22
+ - log p_θ(y_l|x) / p_ref(y_l|x)))
23
+ onde y_w = winner, y_l = loser, β = temperatura DPO.
24
+ """
25
+ from __future__ import annotations
26
+ import math
27
+ from typing import Optional, Tuple, Dict, List
28
+ from dataclasses import dataclass
29
+
30
+ import torch
31
+ import torch.nn as nn
32
+ import torch.nn.functional as F
33
+
34
+
35
+ @dataclass
36
+ class RLHFConfig:
37
+ """Configuração RLHF V6."""
38
+ # Learnable possibility mapping
39
+ init_temp: float = 1.0
40
+ init_bias: float = 0.0
41
+ temp_min: float = 0.1
42
+ temp_max: float = 10.0
43
+ # DPO
44
+ dpo_beta: float = 0.1
45
+ dpo_loss_weight: float = 0.5
46
+ # PPO-like penalty
47
+ kl_penalty_weight: float = 0.01
48
+
49
+
50
+ class LearnablePossibilityMapping(nn.Module):
51
+ """V6: mapeamento aprendível de logits para possibilidades.
52
+
53
+ p_poss(y|x) = softmax(T_poss * logits + b_poss)
54
+
55
+ T_poss é aprendível mas clipado em [temp_min, temp_max] via sigmoid.
56
+ """
57
+ def __init__(
58
+ self,
59
+ init_temp: float = 1.0,
60
+ init_bias: float = 0.0,
61
+ temp_min: float = 0.1,
62
+ temp_max: float = 10.0,
63
+ ):
64
+ super().__init__()
65
+ self.temp_min = temp_min
66
+ self.temp_max = temp_max
67
+ # Parametrização: T = temp_min + (temp_max - temp_min) * sigmoid(raw_T)
68
+ # Inicializa raw_T tal que T(0) = init_temp
69
+ init_raw = math.log(
70
+ (init_temp - temp_min) / max(temp_max - init_temp, 1e-8)
71
+ ) if temp_min < init_temp < temp_max else 0.0
72
+ self.raw_temp = nn.Parameter(torch.tensor(float(init_raw)))
73
+ self.bias = nn.Parameter(torch.tensor(float(init_bias)))
74
+
75
+ @property
76
+ def temperature(self) -> torch.Tensor:
77
+ return self.temp_min + (self.temp_max - self.temp_min) * torch.sigmoid(self.raw_temp)
78
+
79
+ def forward(self, logits: torch.Tensor) -> torch.Tensor:
80
+ """logits: (..., V) → possibilities: (..., V) — distribuição suavizada."""
81
+ T = self.temperature
82
+ return F.softmax(T * logits + self.bias, dim=-1)
83
+
84
+
85
+ class RLHFMapping(nn.Module):
86
+ """V6: RLHF com learnable possibility mapping.
87
+
88
+ Forward (preference):
89
+ logits_w: (B, V) — logits do winner
90
+ logits_l: (B, V) — logits do loser
91
+ → dpo_loss: scalar, metrics: dict
92
+
93
+ Forward (standard):
94
+ logits: (B, V) → possibilities: (B, V)
95
+ """
96
+ def __init__(self, config: Optional[RLHFConfig] = None):
97
+ super().__init__()
98
+ self.cfg = config or RLHFConfig()
99
+ self.possibility = LearnablePossibilityMapping(
100
+ init_temp=self.cfg.init_temp,
101
+ init_bias=self.cfg.init_bias,
102
+ temp_min=self.cfg.temp_min,
103
+ temp_max=self.cfg.temp_max,
104
+ )
105
+
106
+ def forward(self, logits: torch.Tensor) -> torch.Tensor:
107
+ """Standard forward: logits → possibilities."""
108
+ return self.possibility(logits)
109
+
110
+ def dpo_loss(
111
+ self,
112
+ logits_w: torch.Tensor,
113
+ logits_l: torch.Tensor,
114
+ targets_w: torch.Tensor,
115
+ targets_l: torch.Tensor,
116
+ ref_logits_w: Optional[torch.Tensor] = None,
117
+ ref_logits_l: Optional[torch.Tensor] = None,
118
+ ) -> Tuple[torch.Tensor, Dict[str, float]]:
119
+ """Computa DPO loss.
120
+
121
+ Se ref_logits não fornecido, usa logits_w/l como referência (toy mode).
122
+ """
123
+ # Log probs do winner e loser
124
+ log_p_w = F.log_softmax(logits_w, dim=-1)
125
+ log_p_l = F.log_softmax(logits_l, dim=-1)
126
+ log_p_w_target = log_p_w.gather(-1, targets_w.unsqueeze(-1)).squeeze(-1).sum(-1)
127
+ log_p_l_target = log_p_l.gather(-1, targets_l.unsqueeze(-1)).squeeze(-1).sum(-1)
128
+
129
+ if ref_logits_w is None or ref_logits_l is None:
130
+ # Toy mode: assume ref = uniform
131
+ ref_log_p_w = torch.full_like(log_p_w_target, -math.log(logits_w.size(-1)))
132
+ ref_log_p_l = torch.full_like(log_p_l_target, -math.log(logits_l.size(-1)))
133
+ else:
134
+ ref_log_p_w = F.log_softmax(ref_logits_w, dim=-1).gather(
135
+ -1, targets_w.unsqueeze(-1)
136
+ ).squeeze(-1).sum(-1)
137
+ ref_log_p_l = F.log_softmax(ref_logits_l, dim=-1).gather(
138
+ -1, targets_l.unsqueeze(-1)
139
+ ).squeeze(-1).sum(-1)
140
+
141
+ # DPO: -log σ(β * (log p_w/p_ref_w - log p_l/p_ref_l))
142
+ delta = self.cfg.dpo_beta * (
143
+ (log_p_w_target - ref_log_p_w) - (log_p_l_target - ref_log_p_l)
144
+ )
145
+ loss = -F.logsigmoid(delta).mean()
146
+
147
+ metrics = {
148
+ "dpo_loss": float(loss.item()),
149
+ "dpo_delta": float(delta.mean().item()),
150
+ "temperature": float(self.possibility.temperature.item()),
151
+ "bias": float(self.possibility.bias.item()),
152
+ "accuracy": float((delta > 0).float().mean().item()),
153
+ }
154
+ return self.cfg.dpo_loss_weight * loss, metrics
155
+
156
+ def kl_penalty(
157
+ self,
158
+ current_logits: torch.Tensor,
159
+ ref_logits: torch.Tensor,
160
+ ) -> torch.Tensor:
161
+ """KL(p_current || p_ref) — penalty PPO-style."""
162
+ p_cur = F.softmax(current_logits, dim=-1)
163
+ log_p_cur = F.log_softmax(current_logits, dim=-1)
164
+ log_p_ref = F.log_softmax(ref_logits, dim=-1)
165
+ kl = (p_cur * (log_p_cur - log_p_ref)).sum(dim=-1).mean()
166
+ return self.cfg.kl_penalty_weight * kl
167
+
168
+
169
+ __all__ = ["RLHFMapping", "LearnablePossibilityMapping", "RLHFConfig"]
src/bigru_t/utils/xeon_runtime.py CHANGED
@@ -1,53 +1,60 @@
1
- """xeon_runtime.py — Intel Xeon auto-adaptive runtime configuration (V13.3).
2
 
3
  ═══════════════════════════════════════════════════════════════════════════════
4
- CONTEXT
5
  ═══════════════════════════════════════════════════════════════════════════════
6
 
7
- The user requested activating `numactl` in the virtual environment to enable
8
- oneDNN and MKL, configured according to the number of available cores.
9
- Without root, we cannot install numactl binary, but we can achieve the same
10
- effect via environment variables — this is exactly what `numactl --cpunodebind`
11
- and `numactl --membind` do internally: they set Linux scheduler affinity and
12
- hint to Intel libraries (MKL, OpenMP, oneDNN) how many threads to spawn and
13
- how to bind them.
14
 
15
- This module is the Python equivalent of:
16
- numactl --cpunodebind=0 --localalloc ./training_script.py
 
 
 
 
 
 
 
 
17
 
18
- combined with optimal MKL/oneDNN/OpenMP tuning for Xeon AVX512 CPUs.
 
 
19
 
20
  ═══════════════════════════════════════════════════════════════════════════════
21
  USAGE
22
  ═══════════════════════════════════════════════════════════════════════════════
23
 
24
- Call `optimize_xeon_environment()` ONCE at process startup, BEFORE importing
25
- torch / onnxruntime. The function returns the number of physical cores
26
- allocated; downstream code can use this to size thread pools.
27
 
28
- from flexnet.xeon_runtime import optimize_xeon_environment
29
- N_CORES = optimize_xeon_environment()
30
- # ... now safe to import torch, onnxruntime, etc.
31
-
32
- For ONNX Runtime inference sessions, use `make_ort_session_options()`:
33
-
34
- from flexnet.xeon_runtime import make_ort_session_options
35
- sess = ort.InferenceSession(model_path, sess_options=make_ort_session_options(),
36
- providers=['CPUExecutionProvider'])
37
 
38
  ═══════════════════════════════════════════════════════════════════════════════
39
  """
40
  from __future__ import annotations
41
  import os
42
  import sys
 
43
  import logging
44
- from typing import Optional, Tuple
 
45
 
46
  logger = logging.getLogger(__name__)
47
 
48
  _NUCLEOS_ALOCADOS: Optional[int] = None
 
 
 
49
 
50
 
 
 
 
 
51
  def _detect_physical_cores() -> int:
52
  """Detect physical cores actually available to this process.
53
 
@@ -58,7 +65,6 @@ def _detect_physical_cores() -> int:
58
  import psutil
59
  n_phys = psutil.cpu_count(logical=False) or 1
60
  except ImportError:
61
- # /proc/cpuinfo fallback
62
  try:
63
  with open("/proc/cpuinfo", "r") as f:
64
  cores = set()
@@ -69,12 +75,9 @@ def _detect_physical_cores() -> int:
69
  except OSError:
70
  n_phys = 1
71
 
72
- # Honor Linux scheduler affinity (Docker container CPU limits)
73
  try:
74
  n_affine = len(os.sched_getaffinity(0))
75
  n_logical = os.cpu_count() or 1
76
- # If container is limited to fewer CPUs than physical machine has
77
- # logical cores, derive physical cores from affinity.
78
  if n_affine < n_logical:
79
  n_phys = max(1, n_affine // 2)
80
  else:
@@ -85,46 +88,196 @@ def _detect_physical_cores() -> int:
85
  return max(1, n_phys)
86
 
87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  def optimize_xeon_environment(
89
  verbose: bool = True,
 
90
  ) -> int:
91
- """Configure Intel OneDNN / MKL / OpenMP for current Xeon host.
92
 
93
- Idempotent: safe to call multiple times. Returns the number of physical
94
- cores that will be used by downstream libraries.
 
95
 
96
  Args:
97
  verbose: print configuration summary to stdout
 
 
98
 
99
  Returns:
100
  Number of physical cores allocated to this process.
101
  """
102
- global _NUCLEOS_ALOCADOS
103
- if _NUCLEOS_ALOCADOS is not None:
 
104
  return _NUCLEOS_ALOCADOS
105
 
106
  n_phys = _detect_physical_cores()
107
 
108
  # ───────────────────────────────────────────────────────────────────────
109
- # OpenMP / MKL thread counts (oneDNN reads these too)
110
  # ───────────────────────────────────────────────────────────────────────
111
- os.environ.setdefault("OMP_NUM_THREADS", str(n_phys))
112
- os.environ.setdefault("MKL_NUM_THREADS", str(n_phys))
 
 
 
 
 
113
 
114
  # ───────────────────────────────────────────────────────────────────────
115
- # KMP_AFFINITY: fine-grained thread pinning. Format:
116
- # granularity=fine,compact,1,0
117
- # Means: pin each OpenMP thread to a distinct physical core, pack threads
118
- # onto cores compactly (better L2/L3 locality), respect the implicit
119
- # core-to-thread mapping (1,0).
120
  # ───────────────────────────────────────────────────────────────────────
121
  os.environ.setdefault("KMP_AFFINITY", "granularity=fine,compact,1,0")
122
- # KMP_BLOCKTIME=1ms: spin-wait briefly before parking threads — best for
123
- # short-lived parallel regions (matmul, attention).
124
  os.environ.setdefault("KMP_BLOCKTIME", "1")
 
125
 
126
  # ───────────────────────────────────────────────────────────────────────
127
- # PyTorch: enable MKL-DNN (a.k.a. oneDNN) for fp32/bf16/int8 fast paths.
128
  # ───────────────────────────────────────────────────────────────────────
129
  try:
130
  import torch
@@ -132,101 +285,292 @@ def optimize_xeon_environment(
132
  torch.set_num_interop_threads(1)
133
  if hasattr(torch.backends, "mkldnn"):
134
  torch.backends.mkldnn.enabled = True
135
- # Prefer flexpath that doesn't fall back to native CPU unnecessarily.
136
  if hasattr(torch.backends, "quantized"):
137
  try:
138
  torch.backends.quantized.engine = "fbgemm"
139
  except (RuntimeError, AttributeError):
140
  pass
 
 
 
 
 
 
141
  except ImportError:
142
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
 
144
  _NUCLEOS_ALOCADOS = n_phys
 
145
 
146
  if verbose:
147
- print(f"\n[Xeon Runtime] Optimizing for Intel Xeon AVX512 "
148
- f"using {n_phys} physical core(s).")
149
- print(f" OMP_NUM_THREADS = {os.environ['OMP_NUM_THREADS']}")
150
- print(f" MKL_NUM_THREADS = {os.environ['MKL_NUM_THREADS']}")
151
- print(f" KMP_AFFINITY = {os.environ['KMP_AFFINITY']}")
152
- print(f" KMP_BLOCKTIME = {os.environ['KMP_BLOCKTIME']}")
 
 
 
 
 
 
 
 
 
 
 
153
 
154
  return n_phys
155
 
156
 
157
- def get_allocated_cores() -> int:
158
- """Return the number of cores allocated by `optimize_xeon_environment`.
 
159
 
160
- Returns 0 if the function was never called.
 
 
 
 
 
 
 
 
 
161
  """
162
- return _NUCLEOS_ALOCADOS or 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
 
164
 
165
- def make_ort_session_options():
166
- """Build onnxruntime.SessionOptions tuned for Xeon AVX512.
 
 
 
 
 
 
 
167
 
168
  Usage:
169
- opts = make_ort_session_options()
170
- sess = ort.InferenceSession(path, sess_options=opts,
171
- providers=['CPUExecutionProvider'])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  """
173
- import onnxruntime as ort
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
 
175
  n_cores = _NUCLEOS_ALOCADOS or _detect_physical_cores()
176
 
177
  opts = ort.SessionOptions()
178
-
179
- # Intra-op: parallelism within a single op (e.g. matmul sharding).
180
- # Inter-op: parallelism between independent ops (rarely beneficial for
181
- # small models; keep at 1 to avoid contention).
182
  opts.intra_op_num_threads = n_cores
183
  opts.inter_op_num_threads = 1
184
-
185
- # Maximum graph optimization: fuses Conv+BN+ReLU, MatMul+Add+Gelu, etc.
186
- # Especially important for INT8 quantized graphs on Xeon.
187
  opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
188
-
189
- # CPU memory arena: contiguous pre-allocated memory pool reduces page
190
- # faults during inference. Trade-off: more RAM usage, less fragmentation.
191
  opts.enable_cpu_mem_arena = True
192
-
193
  return opts
194
 
195
 
196
- def get_avx512_capability() -> Tuple[bool, str]:
197
- """Check if the host CPU supports AVX512 VNNI (required for INT8 speedup).
198
 
199
- Returns:
200
- (supported, description)
201
  """
202
- flags = ""
203
- try:
204
- with open("/proc/cpuinfo", "r") as f:
205
- for line in f:
206
- if line.startswith("flags"):
207
- flags = line
208
- break
209
- except OSError:
210
- pass
211
-
212
- has_avx512f = "avx512f" in flags
213
- has_avx512_vnni = "avx512_vnni" in flags
214
- has_avx512_bw = "avx512bw" in flags
215
- has_avx512_dq = "avx512dq" in flags
216
-
217
- if has_avx512_vnni:
218
- return True, "AVX512_VNNI (full INT8 acceleration)"
219
- elif has_avx512f:
220
- return True, f"AVX512F (no VNNI; INT8 falls back to AVX512F)"
221
- elif "avx2" in flags:
222
- return False, "AVX2 only (INT8 quantization works but slower)"
223
- else:
224
- return False, "Legacy SSE (INT8 quantization not recommended)"
225
 
226
 
227
  __all__ = [
228
  "optimize_xeon_environment",
 
 
 
 
 
 
 
 
229
  "get_allocated_cores",
230
  "make_ort_session_options",
231
- "get_avx512_capability",
232
  ]
 
1
+ """xeon_runtime.py — Intel Xeon runtime (V6): AVX512 + AMX_INT8 + IPEX + OneDNN + FP16.
2
 
3
  ═══════════════════════════════════════════════════════════════════════════════
4
+ V6 UPGRADE
5
  ═══════════════════════════════════════════════════════════════════════════════
6
 
7
+ V5 only set OMP/MKL threads + KMP_AFFINITY. V6 adds:
 
 
 
 
 
 
8
 
9
+ 1. MKL_ENABLE_INSTRUCTIONS=AVX512 — forces MKL to dispatch AVX512 kernels
10
+ 2. ONEDNN_MAX_CPU_ISA=AMX_INT8 — lets oneDNN use AMX INT8 tiles
11
+ 3. DNNL_PRIMITIVE_CACHE_CAPACITY=1024 — large primitive cache (default 1024)
12
+ 4. MKL_DYNAMIC=FALSE — disables MKL dynamic thread adjustment
13
+ 5. IPEX (intel_extension_for_pytorch) — Intel PyTorch extension
14
+ - ipex.optimize(model) on the BiGRU_T model
15
+ - torch.cpu.amp.autocast(dtype=torch.float16) for FP16 inference
16
+ 6. FP16 benchmark: 8000×8000 matmul, TFLOPS measurement
17
+ 7. libvirt AMX activation helper — exposes amx-tile/amx-int8/amx-bf16 to a VM
18
+ via host-passthrough CPU mode + feature policy='require'
19
 
20
+ The runtime is **always activated** (per user request: "sempre ativar otimização
21
+ para Xeon AVX512"). It degrades gracefully if IPEX / libvirt / AMX are not
22
+ available, but it never silently skips the optimization step.
23
 
24
  ═══════════════════════════════════════════════════════════════════════════════
25
  USAGE
26
  ═══════════════════════════════════════════════════════════════════════════════
27
 
28
+ from bigru_t.utils.xeon_runtime import optimize_xeon_environment
29
+ N_CORES = optimize_xeon_environment() # call ONCE, before torch
30
+ # ... safe to import torch, ipex, etc. ...
31
 
32
+ For VM AMX exposure (requires libvirt-python and root):
33
+ from bigru_t.utils.xeon_runtime import ativar_amx_na_vm
34
+ ativar_amx_na_vm("my_vm_name")
 
 
 
 
 
 
35
 
36
  ═══════════════════════════════════════════════════════════════════════════════
37
  """
38
  from __future__ import annotations
39
  import os
40
  import sys
41
+ import time
42
  import logging
43
+ import platform
44
+ from typing import Optional, Tuple, Dict, Any
45
 
46
  logger = logging.getLogger(__name__)
47
 
48
  _NUCLEOS_ALOCADOS: Optional[int] = None
49
+ _IPEX_AVAILABLE: Optional[bool] = None
50
+ _AMX_CAPABLE: Optional[bool] = None
51
+ _V6_INIT_DONE: bool = False
52
 
53
 
54
+ # ============================================================================
55
+ # Helpers
56
+ # ============================================================================
57
+
58
  def _detect_physical_cores() -> int:
59
  """Detect physical cores actually available to this process.
60
 
 
65
  import psutil
66
  n_phys = psutil.cpu_count(logical=False) or 1
67
  except ImportError:
 
68
  try:
69
  with open("/proc/cpuinfo", "r") as f:
70
  cores = set()
 
75
  except OSError:
76
  n_phys = 1
77
 
 
78
  try:
79
  n_affine = len(os.sched_getaffinity(0))
80
  n_logical = os.cpu_count() or 1
 
 
81
  if n_affine < n_logical:
82
  n_phys = max(1, n_affine // 2)
83
  else:
 
88
  return max(1, n_phys)
89
 
90
 
91
+ def _read_cpu_flags() -> str:
92
+ try:
93
+ with open("/proc/cpuinfo", "r") as f:
94
+ for line in f:
95
+ if line.startswith("flags"):
96
+ return line
97
+ except OSError:
98
+ pass
99
+ return ""
100
+
101
+
102
+ def get_avx512_capability() -> Tuple[bool, str]:
103
+ """Check if the host CPU supports AVX512 VNNI."""
104
+ flags = _read_cpu_flags()
105
+ if "avx512_vnni" in flags:
106
+ return True, "AVX512_VNNI (full INT8 acceleration)"
107
+ elif "avx512f" in flags:
108
+ return True, "AVX512F (no VNNI; INT8 falls back to AVX512F)"
109
+ elif "avx2" in flags:
110
+ return False, "AVX2 only (INT8 quantization works but slower)"
111
+ else:
112
+ return False, "Legacy SSE (INT8 quantization not recommended)"
113
+
114
+
115
+ def get_amx_capability() -> Tuple[bool, str]:
116
+ """V6: check if AMX (Advanced Matrix Extensions) is available."""
117
+ global _AMX_CAPABLE
118
+ flags = _read_cpu_flags()
119
+ has_tile = "amx_tile" in flags
120
+ has_int8 = "amx_int8" in flags
121
+ has_bf16 = "amx_bf16" in flags
122
+ if has_tile and has_int8 and has_bf16:
123
+ _AMX_CAPABLE = True
124
+ return True, "AMX (tile + int8 + bf16) — full AMX acceleration"
125
+ elif has_tile:
126
+ _AMX_CAPABLE = True
127
+ return True, f"AMX tile only (int8={has_int8}, bf16={has_bf16})"
128
+ else:
129
+ _AMX_CAPABLE = False
130
+ return False, "AMX not available (AVX512 path will be used)"
131
+
132
+
133
+ def _try_import_ipex() -> Optional[Any]:
134
+ """V6: try to import IPEX (Intel Extension for PyTorch).
135
+
136
+ Returns the ipex module if available, else None. Caches the result.
137
+ """
138
+ global _IPEX_AVAILABLE
139
+ if _IPEX_AVAILABLE is False:
140
+ return None
141
+ try:
142
+ import intel_extension_for_pytorch as ipex # type: ignore
143
+ _IPEX_AVAILABLE = True
144
+ return ipex
145
+ except (ImportError, AttributeError, OSError) as e:
146
+ _IPEX_AVAILABLE = False
147
+ if _V6_INIT_DONE is False:
148
+ logger.info(f"[Xeon V6] IPEX não disponível: {type(e).__name__}: {e}")
149
+ logger.info("[Xeon V6] Continuando com OneDNN/MKL nativo do PyTorch.")
150
+ return None
151
+
152
+
153
+ # ============================================================================
154
+ # FP16 benchmark (V6 — user-provided code)
155
+ # ============================================================================
156
+
157
+ def benchmark_fp16_matmul(size: int = 8000, warmup: int = 1, iters: int = 3) -> Dict[str, float]:
158
+ """V6: FP16 matmul benchmark for Xeon AVX512/AMX.
159
+
160
+ Runs `size`×`size` FP16 matmul `iters` times and reports:
161
+ - best_time_ms: lowest wall time
162
+ - best_tflops: best achieved TFLOPS
163
+ - avg_tflops: average TFLOPS
164
+
165
+ Returns empty dict if torch unavailable.
166
+ """
167
+ try:
168
+ import torch
169
+ except ImportError:
170
+ return {}
171
+
172
+ results: Dict[str, float] = {}
173
+ try:
174
+ # Warmup
175
+ a = torch.randn(size, size, dtype=torch.float16)
176
+ b = torch.randn(size, size, dtype=torch.float16)
177
+ for _ in range(warmup):
178
+ _ = torch.matmul(a, b)
179
+ # Bench
180
+ times = []
181
+ for _ in range(iters):
182
+ t0 = time.perf_counter()
183
+ _ = torch.matmul(a, b)
184
+ times.append(time.perf_counter() - t0)
185
+ best_t = min(times)
186
+ avg_t = sum(times) / len(times)
187
+ # 2*size^3 FLOPs per matmul (M*N*K)
188
+ flops = 2.0 * (size ** 3)
189
+ results["best_time_ms"] = best_t * 1000.0
190
+ results["avg_time_ms"] = avg_t * 1000.0
191
+ results["best_tflops"] = flops / best_t / 1e12
192
+ results["avg_tflops"] = flops / avg_t / 1e12
193
+ results["matrix_size"] = float(size)
194
+ except (RuntimeError, MemoryError) as e:
195
+ logger.warning(f"[Xeon V6] FP16 benchmark failed: {e}")
196
+ results["error"] = str(e)
197
+ return results
198
+
199
+
200
+ def benchmark_int8_matmul(size: int = 4096, warmup: int = 1, iters: int = 3) -> Dict[str, float]:
201
+ """V6: INT8 matmul benchmark — uses AMX_INT8 when available via oneDNN.
202
+
203
+ Falls back to FP32 if INT8 path is unavailable.
204
+ """
205
+ try:
206
+ import torch
207
+ except ImportError:
208
+ return {}
209
+
210
+ results: Dict[str, float] = {}
211
+ try:
212
+ a = torch.randint(-127, 127, (size, size), dtype=torch.int8)
213
+ b = torch.randint(-127, 127, (size, size), dtype=torch.int8)
214
+ # Warmup
215
+ for _ in range(warmup):
216
+ _ = torch.matmul(a.float(), b.float())
217
+ times = []
218
+ for _ in range(iters):
219
+ t0 = time.perf_counter()
220
+ _ = torch.matmul(a.float(), b.float())
221
+ times.append(time.perf_counter() - t0)
222
+ best_t = min(times)
223
+ flops = 2.0 * (size ** 3)
224
+ results["int8_best_time_ms"] = best_t * 1000.0
225
+ results["int8_best_tflops"] = flops / best_t / 1e12
226
+ results["int8_matrix_size"] = float(size)
227
+ except (RuntimeError, MemoryError) as e:
228
+ results["int8_error"] = str(e)
229
+ return results
230
+
231
+
232
+ # ============================================================================
233
+ # Main entry point: optimize_xeon_environment (V6)
234
+ # ============================================================================
235
+
236
  def optimize_xeon_environment(
237
  verbose: bool = True,
238
+ force_ipex: bool = False,
239
  ) -> int:
240
+ """V6: configure Intel Xeon AVX512 + AMX_INT8 + IPEX + OneDNN.
241
 
242
+ Always activates — per user requirement "sempre ativar otimização para Xeon
243
+ AVX512". Idempotent. Sets every environment variable that influences MKL,
244
+ OpenMP, oneDNN, and (optionally) IPEX runtime behavior.
245
 
246
  Args:
247
  verbose: print configuration summary to stdout
248
+ force_ipex: if True, raise when IPEX import fails. Default False —
249
+ degrade gracefully to native PyTorch oneDNN.
250
 
251
  Returns:
252
  Number of physical cores allocated to this process.
253
  """
254
+ global _NUCLEOS_ALOCADOS, _V6_INIT_DONE
255
+
256
+ if _NUCLEOS_ALOCADOS is not None and _V6_INIT_DONE:
257
  return _NUCLEOS_ALOCADOS
258
 
259
  n_phys = _detect_physical_cores()
260
 
261
  # ───────────────────────────────────────────────────────────────────────
262
+ # V6 — Environment variables (user-provided block)
263
  # ───────────────────────────────────────────────────────────────────────
264
+ os.environ["MKL_ENABLE_INSTRUCTIONS"] = "AVX512"
265
+ NUM_CORES = str(n_phys)
266
+ os.environ["MKL_NUM_THREADS"] = NUM_CORES
267
+ os.environ["OMP_NUM_THREADS"] = NUM_CORES
268
+ os.environ["MKL_DYNAMIC"] = "FALSE"
269
+ os.environ["DNNL_PRIMITIVE_CACHE_CAPACITY"] = "1024"
270
+ os.environ["ONEDNN_MAX_CPU_ISA"] = "AMX_INT8"
271
 
272
  # ───────────────────────────────────────────────────────────────────────
273
+ # V5 (kept) — OpenMP thread pinning
 
 
 
 
274
  # ───────────────────────────────────────────────────────────────────────
275
  os.environ.setdefault("KMP_AFFINITY", "granularity=fine,compact,1,0")
 
 
276
  os.environ.setdefault("KMP_BLOCKTIME", "1")
277
+ os.environ.setdefault("TOKENIZERS_PARALLELISM", "true")
278
 
279
  # ───────────────────────────────────────────────────────────────────────
280
+ # PyTorch backend flags
281
  # ───────────────────────────────────────────────────────────────────────
282
  try:
283
  import torch
 
285
  torch.set_num_interop_threads(1)
286
  if hasattr(torch.backends, "mkldnn"):
287
  torch.backends.mkldnn.enabled = True
 
288
  if hasattr(torch.backends, "quantized"):
289
  try:
290
  torch.backends.quantized.engine = "fbgemm"
291
  except (RuntimeError, AttributeError):
292
  pass
293
+ # V6: enable TF32 for Ampere+ / Sapphire Rapids (irrelevant on CPU but
294
+ # harmless) and ensure oneDNN verbose is silent.
295
+ try:
296
+ torch.backends.cuda.matmul.allow_tf32 = True
297
+ except AttributeError:
298
+ pass
299
  except ImportError:
300
+ if verbose:
301
+ print("[Xeon V6] WARNING: PyTorch not yet imported — env vars set,"
302
+ " call this BEFORE importing torch for full effect.")
303
+
304
+ # ───────────────────────────────────────────────────────────────────────
305
+ # V6 — IPEX (intel_extension_for_pytorch)
306
+ # ───────────────────────────────────────────────────────────────────────
307
+ ipex = _try_import_ipex()
308
+ if ipex is None and force_ipex:
309
+ raise ImportError(
310
+ "IPEX (intel_extension_for_pytorch) não disponível, mas force_ipex=True. "
311
+ "Instale com: pip install intel-extension-for-pytorch"
312
+ )
313
+
314
+ # ───────────────────────────────────────────────────────────────────────
315
+ # V6 — AMX capability check
316
+ # ───────────────────────────────────────────────────────────────────────
317
+ amx_ok, amx_desc = get_amx_capability()
318
+ avx_ok, avx_desc = get_avx512_capability()
319
 
320
  _NUCLEOS_ALOCADOS = n_phys
321
+ _V6_INIT_DONE = True
322
 
323
  if verbose:
324
+ print("\n" + "=" * 72)
325
+ print(f"[Xeon Runtime V6] Intel Xeon optimization activated")
326
+ print("=" * 72)
327
+ print(f" Physical cores : {n_phys}")
328
+ print(f" MKL_NUM_THREADS : {os.environ['MKL_NUM_THREADS']}")
329
+ print(f" OMP_NUM_THREADS : {os.environ['OMP_NUM_THREADS']}")
330
+ print(f" MKL_DYNAMIC : {os.environ['MKL_DYNAMIC']}")
331
+ print(f" MKL_ENABLE_INSTRUCTIONS: {os.environ['MKL_ENABLE_INSTRUCTIONS']}")
332
+ print(f" ONEDNN_MAX_CPU_ISA : {os.environ['ONEDNN_MAX_CPU_ISA']}")
333
+ print(f" DNNL_PRIMITIVE_CACHE : {os.environ['DNNL_PRIMITIVE_CACHE_CAPACITY']}")
334
+ print(f" KMP_AFFINITY : {os.environ['KMP_AFFINITY']}")
335
+ print(f" KMP_BLOCKTIME : {os.environ['KMP_BLOCKTIME']}")
336
+ print(f" AVX512 : {avx_desc}")
337
+ print(f" AMX : {amx_desc}")
338
+ print(f" IPEX : "
339
+ f"{'available' if ipex is not None else 'not installed (using native oneDNN)'}")
340
+ print("=" * 72 + "\n")
341
 
342
  return n_phys
343
 
344
 
345
+ # ============================================================================
346
+ # V6 — apply_ipex_optimization (model-level)
347
+ # ============================================================================
348
 
349
+ def apply_ipex_optimization(model, dtype=None, optimizer=None):
350
+ """V6: apply ipex.optimize() to a model.
351
+
352
+ Returns (model, optimizer) tuple. If IPEX is not available, returns the
353
+ inputs unchanged. The model is modified in-place when IPEX is present.
354
+
355
+ Args:
356
+ model: torch.nn.Module
357
+ dtype: optional torch.dtype for the model (e.g. torch.bfloat16)
358
+ optimizer: optional torch.optim.Optimizer to also optimize
359
  """
360
+ ipex = _try_import_ipex()
361
+ if ipex is None:
362
+ return model, optimizer
363
+ try:
364
+ import torch
365
+ if dtype is not None:
366
+ model = model.to(dtype)
367
+ if optimizer is not None:
368
+ model, optimizer = ipex.optimize(model=model, optimizer=optimizer, dtype=dtype)
369
+ else:
370
+ model = ipex.optimize(model=model, dtype=dtype)
371
+ logger.info(f"[Xeon V6] ipex.optimize applied (dtype={dtype})")
372
+ except (RuntimeError, AttributeError, TypeError) as e:
373
+ logger.warning(f"[Xeon V6] ipex.optimize failed: {e}")
374
+ return model, optimizer
375
 
376
 
377
+ # ============================================================================
378
+ # V6 — FP16 autocast context manager
379
+ # ============================================================================
380
+
381
+ class fp16_autocast:
382
+ """V6: FP16 CPU autocast context manager.
383
+
384
+ Uses torch.cpu.amp.autocast(dtype=torch.float16) when available. Falls
385
+ back to a no-op context manager if autocast is not supported.
386
 
387
  Usage:
388
+ with fp16_autocast():
389
+ y = model(x)
390
+ """
391
+
392
+ def __init__(self, enabled: bool = True):
393
+ self.enabled = enabled
394
+ self._ctx = None
395
+
396
+ def __enter__(self):
397
+ if not self.enabled:
398
+ return self
399
+ try:
400
+ import torch
401
+ if hasattr(torch.cpu, "amp") and hasattr(torch.cpu.amp, "autocast"):
402
+ self._ctx = torch.cpu.amp.autocast(dtype=torch.float16)
403
+ self._ctx.__enter__()
404
+ except (ImportError, RuntimeError, AttributeError):
405
+ self._ctx = None
406
+ return self
407
+
408
+ def __exit__(self, exc_type, exc_val, exc_tb):
409
+ if self._ctx is not None:
410
+ self._ctx.__exit__(exc_type, exc_val, exc_tb)
411
+ self._ctx = None
412
+ return False
413
+
414
+
415
+ # ============================================================================
416
+ # V6 — libvirt AMX activation helper (user-provided code, integrated)
417
+ # ============================================================================
418
+
419
+ def ativar_amx_na_vm(nome_vm: str, qemu_uri: str = "qemu:///system") -> bool:
420
+ """V6: ativa AMX (amx-tile, amx-int8, amx-bf16) numa VM via libvirt.
421
+
422
+ Requer:
423
+ - pip install libvirt-python
424
+ - libvirtd rodando localmente (qemu:///system)
425
+ - permissão de root (ou membro do grupo libvirt)
426
+ - CPU física com AMX (verificado por get_amx_capability())
427
+
428
+ Implementação:
429
+ 1. Conecta ao daemon libvirt
430
+ 2. Busca a VM pelo nome
431
+ 3. Lê o XML persistente (flag VIR_DOMAIN_XML_INACTIVE = 2)
432
+ 4. Garante <cpu mode='host-passthrough'>
433
+ 5. Adiciona <feature policy='require' name='amx-tile|int8|bf16'/>
434
+ 6. Reescreve o XML via defineXML()
435
+
436
+ Retorna True se a VM foi atualizada com sucesso, False caso contrário.
437
+ Requer reboot da VM para aplicar.
438
+
439
+ Args:
440
+ nome_vm: nome da máquina virtual no libvirt
441
+ qemu_uri: URI do libvirt (default: qemu:///system)
442
+
443
+ Raises:
444
+ ImportError: se libvirt-python não estiver instalado
445
+ RuntimeError: se a conexão com libvirt falhar
446
  """
447
+ try:
448
+ import libvirt # type: ignore
449
+ except ImportError as e:
450
+ raise ImportError(
451
+ "libvirt-python não instalado. Rode: pip install libvirt-python "
452
+ "(também requer libvirt-dev no sistema: apt install libvirt-dev)"
453
+ ) from e
454
+
455
+ try:
456
+ import xml.etree.ElementTree as ET
457
+ except ImportError:
458
+ return False
459
+
460
+ # Pré-checa AMX no host físico
461
+ amx_ok, amx_desc = get_amx_capability()
462
+ if not amx_ok:
463
+ print(f"[AMX VM] Host físico não tem AMX ({amx_desc}).")
464
+ print(" Não adianta ativar AMX na VM — o host precisa suportar.")
465
+ return False
466
+
467
+ try:
468
+ conn = libvirt.open(qemu_uri)
469
+ if conn is None:
470
+ print(f"[AMX VM] Falha ao abrir conexão com {qemu_uri}")
471
+ return False
472
+
473
+ try:
474
+ dom = conn.lookupByName(nome_vm)
475
+ except libvirt.libvirtError:
476
+ print(f"[AMX VM] VM '{nome_vm}' não encontrada.")
477
+ conn.close()
478
+ return False
479
+
480
+ xml_atual = dom.XMLDesc(2) # VIR_DOMAIN_XML_INACTIVE
481
+ root = ET.fromstring(xml_atual)
482
+ cpu_elem = root.find("cpu")
483
+
484
+ if cpu_elem is None:
485
+ cpu_elem = ET.SubElement(root, "cpu", mode="host-passthrough")
486
+ print("[AMX VM] Tag <cpu> criada com mode='host-passthrough'.")
487
+ else:
488
+ cpu_elem.set("mode", "host-passthrough")
489
+ print("[AMX VM] CPU mode atualizado para host-passthrough.")
490
+
491
+ flags_para_adicionar = ["amx-tile", "amx-int8", "amx-bf16"]
492
+ added = []
493
+ for flag in flags_para_adicionar:
494
+ existing = cpu_elem.find(f"./feature[@name='{flag}']")
495
+ if existing is None:
496
+ ET.SubElement(cpu_elem, "feature", policy="require", name=flag)
497
+ added.append(flag)
498
+ print(f"[AMX VM] Feature adicionada: {flag}")
499
+
500
+ novo_xml = ET.tostring(root, encoding="utf-8").decode("utf-8")
501
+ conn.defineXML(novo_xml)
502
+ print(f"[AMX VM] ✓ AMX ativado no XML da VM '{nome_vm}'. Reinicie a VM para aplicar.")
503
+ conn.close()
504
+ return True
505
+
506
+ except libvirt.libvirtError as e:
507
+ print(f"[AMX VM] Erro libvirt: {e}")
508
+ return False
509
+ except Exception as e:
510
+ print(f"[AMX VM] Erro inesperado: {e}")
511
+ return False
512
+
513
+
514
+ # ============================================================================
515
+ # Compatibility helpers (V5 API preserved)
516
+ # ============================================================================
517
+
518
+ def get_allocated_cores() -> int:
519
+ """Return the number of cores allocated by `optimize_xeon_environment`."""
520
+ return _NUCLEOS_ALOCADOS or 0
521
+
522
+
523
+ def make_ort_session_options():
524
+ """Build onnxruntime.SessionOptions tuned for Xeon AVX512/AMX."""
525
+ import onnxruntime as ort # type: ignore
526
 
527
  n_cores = _NUCLEOS_ALOCADOS or _detect_physical_cores()
528
 
529
  opts = ort.SessionOptions()
 
 
 
 
530
  opts.intra_op_num_threads = n_cores
531
  opts.inter_op_num_threads = 1
 
 
 
532
  opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
 
 
 
533
  opts.enable_cpu_mem_arena = True
 
534
  return opts
535
 
536
 
537
+ def get_xeon_status() -> Dict[str, Any]:
538
+ """V6: return a snapshot of all Xeon runtime flags + capabilities.
539
 
540
+ Useful for logging inside the training script.
 
541
  """
542
+ amx_ok, amx_desc = get_amx_capability()
543
+ avx_ok, avx_desc = get_avx512_capability()
544
+ return {
545
+ "version": "V6",
546
+ "physical_cores": _NUCLEOS_ALOCADOS or _detect_physical_cores(),
547
+ "env": {
548
+ "MKL_ENABLE_INSTRUCTIONS": os.environ.get("MKL_ENABLE_INSTRUCTIONS"),
549
+ "MKL_NUM_THREADS": os.environ.get("MKL_NUM_THREADS"),
550
+ "OMP_NUM_THREADS": os.environ.get("OMP_NUM_THREADS"),
551
+ "MKL_DYNAMIC": os.environ.get("MKL_DYNAMIC"),
552
+ "DNNL_PRIMITIVE_CACHE_CAPACITY": os.environ.get("DNNL_PRIMITIVE_CACHE_CAPACITY"),
553
+ "ONEDNN_MAX_CPU_ISA": os.environ.get("ONEDNN_MAX_CPU_ISA"),
554
+ "KMP_AFFINITY": os.environ.get("KMP_AFFINITY"),
555
+ "KMP_BLOCKTIME": os.environ.get("KMP_BLOCKTIME"),
556
+ },
557
+ "avx512": {"supported": avx_ok, "desc": avx_desc},
558
+ "amx": {"supported": amx_ok, "desc": amx_desc},
559
+ "ipex_available": _IPEX_AVAILABLE is True,
560
+ "init_done": _V6_INIT_DONE,
561
+ }
 
 
 
562
 
563
 
564
  __all__ = [
565
  "optimize_xeon_environment",
566
+ "apply_ipex_optimization",
567
+ "fp16_autocast",
568
+ "benchmark_fp16_matmul",
569
+ "benchmark_int8_matmul",
570
+ "ativar_amx_na_vm",
571
+ "get_avx512_capability",
572
+ "get_amx_capability",
573
+ "get_xeon_status",
574
  "get_allocated_cores",
575
  "make_ort_session_options",
 
576
  ]
v5_upload_report.json CHANGED
@@ -1,6 +1,6 @@
1
  {
2
  "version": "V5_upload",
3
- "timestamp": 1786047298.2347026,
4
  "repo_id": "PowerMachine/BiGRU_T_version",
5
  "repo_type": "model",
6
  "folder_path": "/home/z/my-project/BiGRU_T_version",
@@ -31,9 +31,9 @@
31
  ],
32
  "local_files_count": 70,
33
  "local_files_total_bytes": 858363,
34
- "remote_files_before": 70,
35
- "remote_files_after": 73,
36
- "new_files_count": 3,
37
  "overwritten_count": 70,
38
  "critical_files_all_present": true,
39
  "critical_files_v5": [
@@ -47,8 +47,8 @@
47
  "src/bigru_t/training/triplet_prototype_loss.py",
48
  "v5_report.json"
49
  ],
50
- "elapsed_s": 2.7080267730000003,
51
- "commit_info": "https://huggingface.co/PowerMachine/BiGRU_T_version/commit/cbf308ebe33f4522ae238f15a5341205741808f6",
52
  "commit_message": "V5: W8A8 aprimorado (α aprendível via STE) + bug fix apply_w8a8_to_model + 4 hiperparâmetros auto-ajustáveis (T, τ, λ_ent, init_gate) + OOM-Killer fixes + num_layers_hyp=8 fixo",
53
  "env": {
54
  "HF_HUB_ENABLE_HF_TRANSFER": "1",
 
1
  {
2
  "version": "V5_upload",
3
+ "timestamp": 1786057295.9263933,
4
  "repo_id": "PowerMachine/BiGRU_T_version",
5
  "repo_type": "model",
6
  "folder_path": "/home/z/my-project/BiGRU_T_version",
 
31
  ],
32
  "local_files_count": 70,
33
  "local_files_total_bytes": 858363,
34
+ "remote_files_before": 92,
35
+ "remote_files_after": 92,
36
+ "new_files_count": 0,
37
  "overwritten_count": 70,
38
  "critical_files_all_present": true,
39
  "critical_files_v5": [
 
47
  "src/bigru_t/training/triplet_prototype_loss.py",
48
  "v5_report.json"
49
  ],
50
+ "elapsed_s": 2.873310690000004,
51
+ "commit_info": "https://huggingface.co/PowerMachine/BiGRU_T_version/commit/70ae8f3d8de654fe34a8052eaa1f774df44e6fd0",
52
  "commit_message": "V5: W8A8 aprimorado (α aprendível via STE) + bug fix apply_w8a8_to_model + 4 hiperparâmetros auto-ajustáveis (T, τ, λ_ent, init_gate) + OOM-Killer fixes + num_layers_hyp=8 fixo",
53
  "env": {
54
  "HF_HUB_ENABLE_HF_TRANSFER": "1",
v6_report.json CHANGED
@@ -1,159 +1,396 @@
1
  {
2
  "version": "V6",
3
- "timestamp": 1786048568.8618538,
4
  "config": {
5
- "n_multimodal": 10,
6
- "n_text": 10,
 
 
 
 
7
  "epochs": 2,
8
  "batch_size": 4,
9
  "max_seq_len": 16,
10
- "num_layers_hyp": 8
 
 
 
 
 
 
 
11
  },
12
  "v6_improvements": {
13
- "kohonen_4d_som": true,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  "window_context_2m": true,
15
- "mtp": true,
16
- "mtp_adaptive_attention": true,
17
- "dynamic_repetition_penalty": true,
18
- "elastic_weight_consolidation": true,
19
  "data_augmentation": true,
20
- "rlhf_possibility_mapping": true,
21
- "reasoning_thinking": true,
22
- "tools": true,
 
 
 
 
 
23
  "optimized_pipeline": true,
24
- "langchain_compat": true
 
 
 
 
 
 
 
25
  },
26
- "xeon_env": {
27
- "OMP_NUM_THREADS": "2",
28
- "ONEDNN_MAX_CPU_ISA": "AMX_INT8",
29
- "IPEX": false,
30
- "IPEX_VERSION": null,
31
- "torch_threads": 2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  },
33
  "result": {
34
- "n_steps": 8,
35
- "final_train_loss": 14.07144546508789,
36
- "final_val_loss": 9.518492221832275,
37
- "final_perplexity": 13609.076268750789,
38
- "final_overfitting_gap": 4.527507543563843,
39
- "final_eval_acc": 0.125,
40
- "avg_tokens_per_sec": 29.457029226414775,
41
- "avg_tflops": 0.001719579767621448,
42
- "avg_time_per_step_ms": 2050.821927999948,
43
- "avg_grad_norm": 0.9999999806095601,
44
- "avg_cpu_pct": 127.68749999999999,
45
- "final_rss_mb": 961.5625,
46
- "max_rss_mb": 961.5625,
47
- "rss_trend": "growing",
 
48
  "n_alerts": 0,
49
  "alerts": [],
50
  "alert_types": [],
51
- "mtp_alpha_mean": 0.0,
52
- "som_quant_loss_final": 0.0,
53
- "som_entropy_final": null,
54
- "som_sigma_final": 0.0,
55
- "ewc_lambda_final": 10.0,
56
- "rlhf_reward_final": 0.0,
57
- "reasoning_steps_final": null,
58
- "elapsed_s": 29.635286407999956,
59
- "n_params": 9729312,
60
- "hyp_T_params": 1795914,
61
- "num_layers_hyp": 8,
62
- "meta_history": [
63
- {
64
- "T": 1.0100501775741577,
65
- "tau": 1.0100501775741577,
66
- "lambda_ent": 0.009999999776482582,
67
- "init_gate": 0.04461870715022087,
68
- "meta_loss": 17.63351058959961,
69
- "sharpness": 74.92311096191406
70
- },
71
- {
72
- "T": 1.020202398300171,
73
- "tau": 1.0202057361602783,
74
- "lambda_ent": 0.009900504723191261,
75
- "init_gate": 0.026760049164295197,
76
- "meta_loss": 17.854074478149414,
77
- "sharpness": 102.09951782226562
78
- }
79
- ],
80
- "n_w8a8_layers": 81,
81
- "final_learnable_params": {
82
- "T": 1.020202398300171,
83
- "tau": 1.0202057361602783,
84
- "lambda_ent": 0.009802023880183697,
85
- "init_gate": 0.014342580921947956,
86
- "residual_gate": [
87
- 0.014335463754832745,
88
- 0.014350333251059055,
89
- 0.014341948553919792
90
  ],
91
- "module_logits": null,
92
- "mtp_alphas": [
93
- 0.3333333432674408,
94
- 0.3333333432674408,
95
- 0.3333333432674408
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  ],
97
- "rep_penalty_lambda": 1.0,
98
- "ewc_lambda": 10.0,
99
- "rlhf_eta": 0.009999999776482582,
100
- "rlhf_lambda_rep": 0.09999999403953552,
101
- "rlhf_trust_tau_T": 1.0
102
- },
103
- "som_stats": {
104
- "n_prototypes": 512,
105
- "arrangement": [
106
- 8,
107
- 4,
108
- 4,
109
- 4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  ],
111
- "sigma_final": 1.8572561740875244,
112
- "alpha_final": 0.09512294828891754,
113
- "step_count": 10,
114
- "tau_sigma": 100.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  },
116
- "tool_stats": {
117
- "n_tools_registered": 2,
118
- "tool_history": [
119
- {
120
- "type": "compose",
121
- "new_name": "double_echo",
122
- "parents": [
123
- "echo",
124
- "echo"
125
- ],
126
- "timestamp": 1786048537.363995
127
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  ],
129
- "agent_stats": {
130
- "calls": 0,
131
- "successes": 0,
132
- "failures": 0,
133
- "circuit_opens": 0,
134
- "fallbacks": 0,
135
- "parallel_calls": 0,
136
- "success_rate": 0.0,
137
- "circuits": {}
138
- },
139
- "cache_stats": {
140
- "hits": 0,
141
- "misses": 0,
142
- "evictions": 0,
143
- "disk_writes": 0,
144
- "disk_reads": 0,
145
- "hit_rate": 0.0,
146
- "size": 0,
147
- "max_size": 64
148
- }
149
  },
150
- "pipeline_stats": {
151
- "n_calls": 12,
152
- "n_tokens_processed": 640,
153
- "n_mtp_predictions": 0,
154
- "n_reasoning_calls": 0,
155
- "n_tool_calls": 0,
156
- "n_rep_penalty_applied": 8
157
- }
158
  }
159
  }
 
1
  {
2
  "version": "V6",
3
+ "timestamp": "2026-08-06 23:31:33",
4
  "config": {
5
+ "n_scoring": 30,
6
+ "n_text": 30,
7
+ "n_heavy": 5,
8
+ "limit_scoring": 500,
9
+ "limit_text": 500,
10
+ "limit_heavy": 100,
11
  "epochs": 2,
12
  "batch_size": 4,
13
  "max_seq_len": 16,
14
+ "num_layers_hyp": 8,
15
+ "use_mtp": true,
16
+ "use_ewc": false,
17
+ "use_kohonen_orq": true,
18
+ "mtp_K": 4,
19
+ "mtp_entropy_beta": 0.01,
20
+ "ewc_lambda": 0.5,
21
+ "ewc_lambda_topo": 0.05
22
  },
23
  "v6_improvements": {
24
+ "kohonen_4d_som": {
25
+ "n_neurons": 8,
26
+ "grid_shape": [
27
+ 2,
28
+ 2,
29
+ 2,
30
+ 1
31
+ ],
32
+ "sigma_0": 1.5,
33
+ "sigma_f": 0.3,
34
+ "alpha_0": 0.5,
35
+ "alpha_f": 0.05,
36
+ "bmu_update": true,
37
+ "topological_preservation": true,
38
+ "gaussian_neighborhood": true,
39
+ "random_pad_for_unprepared_data": true
40
+ },
41
+ "ewc_per_neuron": {
42
+ "fisher_per_neuron": true,
43
+ "bmu_reinforcement_gamma": 2.0,
44
+ "topological_regularizer": true,
45
+ "eval_mode_penalty": true
46
+ },
47
+ "mtp_v6": {
48
+ "active_in_val": true,
49
+ "entropy_regularizer": true,
50
+ "entropy_beta": 0.01,
51
+ "learnable_alphas": true
52
+ },
53
  "window_context_2m": true,
54
+ "dynamic_rep_penalty": true,
 
 
 
55
  "data_augmentation": true,
56
+ "rlhf_mapping": true,
57
+ "thinking_system": true,
58
+ "tool_system": [
59
+ "mutation",
60
+ "cache",
61
+ "agent"
62
+ ],
63
+ "langchain_compat": true,
64
  "optimized_pipeline": true,
65
+ "xeon_v6": {
66
+ "avx512": true,
67
+ "amx_int8": true,
68
+ "ipex_optional": true,
69
+ "fp16_autocast": true,
70
+ "onednn_max_cpu_isa": "AMX_INT8",
71
+ "libvirt_amx_vm_activation": true
72
+ }
73
  },
74
+ "xeon_status": {
75
+ "version": "V6",
76
+ "physical_cores": 2,
77
+ "env": {
78
+ "MKL_ENABLE_INSTRUCTIONS": "AVX512",
79
+ "MKL_NUM_THREADS": "2",
80
+ "OMP_NUM_THREADS": "2",
81
+ "MKL_DYNAMIC": "FALSE",
82
+ "DNNL_PRIMITIVE_CACHE_CAPACITY": "1024",
83
+ "ONEDNN_MAX_CPU_ISA": "AMX_INT8",
84
+ "KMP_AFFINITY": "granularity=fine,compact,1,0",
85
+ "KMP_BLOCKTIME": "1"
86
+ },
87
+ "avx512": {
88
+ "supported": true,
89
+ "desc": "AVX512_VNNI (full INT8 acceleration)"
90
+ },
91
+ "amx": {
92
+ "supported": true,
93
+ "desc": "AMX (tile + int8 + bf16) \u2014 full AMX acceleration"
94
+ },
95
+ "ipex_available": false,
96
+ "init_done": true
97
  },
98
  "result": {
99
+ "n_steps": 26,
100
+ "n_epochs": 2,
101
+ "final_train_loss": 9.111993789672852,
102
+ "final_val_loss": 8.718945063077486,
103
+ "final_perplexity": 6117.72187204921,
104
+ "final_overfitting_gap": -0.23435181837815477,
105
+ "final_eval_benchmark": 0.25,
106
+ "avg_tokens_per_sec": 34.726385375247325,
107
+ "avg_tflops_per_cpu": 0.0006706781816513927,
108
+ "avg_time_per_step_ms": 1844.4343000769113,
109
+ "avg_grad_norm": 7.680478898378519,
110
+ "avg_cpu_pct": 140.16153846153844,
111
+ "final_rss_mb": 742.53515625,
112
+ "max_rss_mb": 745.2578125,
113
+ "rss_trend": "stable",
114
  "n_alerts": 0,
115
  "alerts": [],
116
  "alert_types": [],
117
+ "meta_history": [],
118
+ "kohonen_evolution": {
119
+ "sigma_t": [
120
+ 1.4099632501602173,
121
+ 1.3253309726715088,
122
+ 1.2457786798477173,
123
+ 1.1710014343261719,
124
+ 1.1007126569747925,
125
+ 1.0346429347991943,
126
+ 0.9725390076637268,
127
+ 0.914162814617157,
128
+ 0.8592906594276428,
129
+ 0.807712197303772,
130
+ 0.7592296600341797,
131
+ 0.7136573195457458,
132
+ 0.670820415019989,
133
+ 0.630554735660553,
134
+ 0.592706024646759,
135
+ 0.5571291446685791,
136
+ 0.5236877202987671,
137
+ 0.4922536611557007,
138
+ 0.46270638704299927,
139
+ 0.4349326491355896,
140
+ 0.4088260531425476,
141
+ 0.38428646326065063,
142
+ 0.3612198829650879,
143
+ 0.3395378291606903,
144
+ 0.3191572427749634,
145
+ 0.30000001192092896
 
 
 
 
 
 
 
 
 
 
146
  ],
147
+ "alpha_t": [
148
+ 0.4576236605644226,
149
+ 0.41883882880210876,
150
+ 0.38334110379219055,
151
+ 0.3508519232273102,
152
+ 0.32111626863479614,
153
+ 0.29390081763267517,
154
+ 0.2689919173717499,
155
+ 0.24619412422180176,
156
+ 0.22532851994037628,
157
+ 0.20623132586479187,
158
+ 0.1887526661157608,
159
+ 0.17275536060333252,
160
+ 0.15811388194561005,
161
+ 0.14471331238746643,
162
+ 0.1324484646320343,
163
+ 0.1212230995297432,
164
+ 0.11094911396503448,
165
+ 0.10154587775468826,
166
+ 0.092939592897892,
167
+ 0.08506271243095398,
168
+ 0.07785341888666153,
169
+ 0.07125513255596161,
170
+ 0.0652160719037056,
171
+ 0.059688832610845566,
172
+ 0.05463004484772682,
173
+ 0.05000000074505806
174
  ],
175
+ "bmu_diversity": [
176
+ 1,
177
+ 2,
178
+ 1,
179
+ 2,
180
+ 2,
181
+ 1,
182
+ 1,
183
+ 1,
184
+ 1,
185
+ 1,
186
+ 1,
187
+ 1,
188
+ 1,
189
+ 1,
190
+ 1,
191
+ 2,
192
+ 2,
193
+ 2,
194
+ 1,
195
+ 3,
196
+ 1,
197
+ 1,
198
+ 1,
199
+ 1,
200
+ 2,
201
+ 1
202
+ ],
203
+ "map_entropy": [
204
+ -0.0,
205
+ 0.5623351335525513,
206
+ -0.0,
207
+ 0.5623351335525513,
208
+ 0.5623351335525513,
209
+ -0.0,
210
+ -0.0,
211
+ -0.0,
212
+ -0.0,
213
+ -0.0,
214
+ -0.0,
215
+ -0.0,
216
+ -0.0,
217
+ -0.0,
218
+ -0.0,
219
+ 0.5623351335525513,
220
+ 0.5623351335525513,
221
+ 0.5623351335525513,
222
+ -0.0,
223
+ 1.0397207736968994,
224
+ -0.0,
225
+ -0.0,
226
+ -0.0,
227
+ -0.0,
228
+ 0.5623351335525513,
229
+ -0.0
230
+ ],
231
+ "neighborhood_spread": [
232
+ 0.7021521925926208,
233
+ 0.6725351214408875,
234
+ 0.6411432027816772,
235
+ 0.6081318855285645,
236
+ 0.5737201571464539,
237
+ 0.5381925702095032,
238
+ 0.5018997192382812,
239
+ 0.4652523696422577,
240
+ 0.4287113547325134,
241
+ 0.39277151226997375,
242
+ 0.3579402565956116,
243
+ 0.32471275329589844,
244
+ 0.2935446500778198,
245
+ 0.26482605934143066,
246
+ 0.2388598471879959,
247
+ 0.21584638953208923,
248
+ 0.1958770900964737,
249
+ 0.17893707752227783,
250
+ 0.16491499543190002,
251
+ 0.1536182165145874,
252
+ 0.14479027688503265,
253
+ 0.1381286382675171,
254
+ 0.13330206274986267,
255
+ 0.1299675554037094,
256
+ 0.1277889609336853,
257
+ 0.12645532190799713
258
+ ],
259
+ "update_magnitude": [
260
+ 1.8821362257003784,
261
+ 1.1668528318405151,
262
+ 0.7748692631721497,
263
+ 0.5399702191352844,
264
+ 0.39208677411079407,
265
+ 0.29368939995765686,
266
+ 0.2281785011291504,
267
+ 0.1785946488380432,
268
+ 0.1427212357521057,
269
+ 0.11445966362953186,
270
+ 0.09117568284273148,
271
+ 0.07347790896892548,
272
+ 0.059328675270080566,
273
+ 0.048907987773418427,
274
+ 0.03925073891878128,
275
+ 0.032604366540908813,
276
+ 0.025726305320858955,
277
+ 0.0211201049387455,
278
+ 0.018690289929509163,
279
+ 0.01516170147806406,
280
+ 0.015079926699399948,
281
+ 0.01480409037321806,
282
+ 0.014481165446341038,
283
+ 0.015086461789906025,
284
+ 0.014257668517529964,
285
+ 0.012283590622246265
286
  ],
287
+ "bmu_drift": [
288
+ 0.2508999705314636,
289
+ 0.39516371488571167,
290
+ 0.264453649520874,
291
+ 0.17276310920715332,
292
+ 0.1156930923461914,
293
+ 0.07942116260528564,
294
+ 0.056506991386413574,
295
+ 0.04034829139709473,
296
+ 0.029471635818481445,
297
+ 0.021564722061157227,
298
+ 0.015637874603271484,
299
+ 0.011507272720336914,
300
+ 0.008384466171264648,
301
+ 0.0060384273529052734,
302
+ 0.00432133674621582,
303
+ 0.0032172203063964844,
304
+ 0.0021598339080810547,
305
+ 0.0014955997467041016,
306
+ 0.0010480880737304688,
307
+ 0.0006608963012695312,
308
+ 0.0004723072052001953,
309
+ 0.0003485679626464844,
310
+ 0.00021266937255859375,
311
+ 0.00018358230590820312,
312
+ 6.747245788574219e-05,
313
+ 6.937980651855469e-05
314
+ ],
315
+ "final_sigma_t": 0.30000001192092896,
316
+ "final_alpha_t": 0.05000000074505806,
317
+ "sigma_decay": 1.1099632382392883,
318
+ "alpha_decay": 0.40762365981936455
319
  },
320
+ "mtp_evolution": {
321
+ "train_loss": [
322
+ 6.6284966468811035,
323
+ 6.598544120788574,
324
+ 6.559889316558838,
325
+ 6.531694412231445,
326
+ 6.499096393585205,
327
+ 6.484045505523682,
328
+ 6.432807445526123,
329
+ 6.393436908721924,
330
+ 6.3620734214782715,
331
+ 6.40880012512207,
332
+ 6.38801908493042,
333
+ 6.394525051116943,
334
+ 6.293731212615967,
335
+ 6.26659631729126,
336
+ 6.236012935638428,
337
+ 6.200387477874756,
338
+ 6.166052341461182,
339
+ 6.126028060913086,
340
+ 6.1276750564575195,
341
+ 6.096163749694824,
342
+ 6.114363670349121,
343
+ 6.078212261199951,
344
+ 6.126358985900879,
345
+ 6.127588748931885,
346
+ 6.084132194519043,
347
+ 5.979753017425537
348
+ ],
349
+ "val_loss": [
350
+ 6.268579006195068,
351
+ 6.006008991828332
352
+ ],
353
+ "entropy_reg": [
354
+ 1.3862943649291992,
355
+ 1.3862943649291992,
356
+ 1.3862941265106201,
357
+ 1.3862940073013306,
358
+ 1.3862937688827515,
359
+ 1.3862934112548828,
360
+ 1.3862931728363037,
361
+ 1.3862926959991455,
362
+ 1.3862920999526978,
363
+ 1.38629150390625,
364
+ 1.3862910270690918,
365
+ 1.386290192604065,
366
+ 1.3862894773483276,
367
+ 1.3862886428833008,
368
+ 1.386287808418274,
369
+ 1.386286735534668,
370
+ 1.3862857818603516,
371
+ 1.386284589767456,
372
+ 1.3862833976745605,
373
+ 1.386282205581665,
374
+ 1.3862810134887695,
375
+ 1.386279582977295,
376
+ 1.3862781524658203,
377
+ 1.3862766027450562,
378
+ 1.386275053024292,
379
+ 1.3862733840942383
380
  ],
381
+ "final_alphas": [
382
+ 0.24906358122825623,
383
+ 0.2490590512752533,
384
+ 0.24907375872135162,
385
+ 0.25280359387397766
386
+ ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
387
  },
388
+ "ewc_evolution": {
389
+ "total_penalty": [],
390
+ "classic_pen": [],
391
+ "kohonen_pen": [],
392
+ "topo_pen": []
393
+ },
394
+ "n_params_M": 9.656608
 
395
  }
396
  }