Delete src/bigru_t/model/kohonen_learning_system.py.bak_v65fix
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370"""kohonen_learning_system.py — V6.5 (VQ-VAE-2 + reasoning_engine integrados)
V6.5 — ATIVAR VQ-VAE-2 NO PIPELINE DE COMPRESSÃO + INTEGRAR REASONING_ENGINE
Implementação CANÔNICA do Sistema de Aprendizado Kohonen 4D fornecida pelousuário, com análise matemática formal e 2 correções de bugs críticos.
============================================================================ANÁLISE MATEMÁTICA FORMAL============================================================================
1) text_to_4d_vector(text, ..., time_step, T_max): ----------------------------------------------- Tokenização BBPE: ids = BBPE_encode(text, max_len=seq_len) → [seq_len] Embedding: E = Embedding(ids) → [seq_len, D] PE sinusoidal: PE = sin/cos(pos · exp(-2k·log(10000)/D)) Fusão: F = E + PE → [seq_len, D] Centralização: F_c = F - mean(F, dim=0) → [seq_len, D] SVD: F_c = U · S · V^T (V: [D, D] ortogonal) Projeção 3D: coords_3d = F_c · V[:3,:]^T → [seq_len, 3] Centróide: xyz = mean(coords_3d, dim=0) → [3] Coordenada temporal: w = time_step / T_max ∈ [0, 1] (LINEAR) Saída: vec_4d = [x, y, z, w] → [4]
Nota (V6.4): w é LINEAR no tempo (diferente de sigmoid(||xyz||)). Isto permite que o SOM organize neurônios ao longo do eixo temporal, capturando a sequência absoluta de amostras — útil para deteção de drift e consolidação incremental (EWC).
2) KohonenSOM4D: -------------- Grid: W ∈ ℝ^(I×J×K×L×4), default (6,6,6,4) = 864 neurônios BMU: bmu = argmin_{i,j,k,l} ||W[i,j,k,l] - x||² (Euclidiana ℝ⁴) Vizinhança (Gaussiana 4D): Λ(d, σ) = exp(-d² / (2σ²)) d² = Δi² + Δj² + Δk² + Δl² (distância quadrada no grid 4D) Update (Kohonen): ΔW = α · Λ · (x - W) (competitivo + cooperativo) Decaimento: σ_t = σ₀ · exp(-t/1000) (vizinhança encolhe rápido) α_t = α₀ · exp(-t/2000) (LR decai mais lento) EWC (apenas na 4ª dimensão w): L_ewc = (λ/2) · Σ F_i · (W_w,i - W*_w,i)² ∂L_ewc/∂W_w = λ · F · (W_w - W*_w) Aplicado como: update[..., 3] -= λ · F · (W_w - W*_w) Fisher (aproximação como erro quadrado): F_i = mean((x_w - W_w,i)²) sobre samples pré-punição Acumulado apenas quando: (a) punishment_count == 0 (b) old_weights_w is None (ainda não consolidado) (c) Λ > 0.1 (neurônios próximos ao BMU)
3) HypothesisClassifier: ---------------------- 8 camadas FC: [in → 512 → 256 → 128 → 64 → 32 → 16 → 8] + ReLU Output: 8 → 1 (logit) Loss: BCEWithLogitsLoss Optimizer: Adam, lr=0.001 Epochs: 50 (sobre o buffer atual) Input: vetor de ativação SOM = distâncias ao grid flatten (864-dim para grid (6,6,6,4))
4) Punishment Protocol: --------------------- Histograma: bucketiza vec_4d[dim_choice] (default 'y', idx=1) check_training_start: max(histogram.values()) >= N_start → ready Avaliação: acc = correct / len(buffer) (correct = pred==label) Se acc < 1.0: punishment_count += 1 success_count = 0 Se punishment_count == 1: activate_hypothesis() (treina classifier) Se punishment_count == 2: set_ewc_reference() (consolida w via Fisher) required_new_samples = success_count * N (ou N se success==0) reset: training_ready=False, punishment=0, success=0, histogram cleared, buffers cleared Se acc == 1.0: punishment_count = 0 success_count += 1
5) PGVector NÃO É MAIS NECESSÁRIO (V6.4): --------------------------------------- O método find_bmu realiza a busca nearest-neighbor sobre o grid 4D, substituindo qualquer lookup pgvector externo. O SOM interno já armazena todo o conhecimento como pesos 4D, e find_bmu retorna o neurônio mais próximo em O(I·J·K·L) — equivalente a uma busca pgvector com indexação flat. Consequentemente, hyp_t.py NÃO consulta mais pgvector — a decisão de aplicar punição é delegada ao KohonenLearningSystem.
============================================================================BUGS CORRIGIDOS (V6.3 → mantidos em V6.4)============================================================================
BUG 1 (find_bmu): V6.3 corrigiu return prematuro com Ellipsis. V6.4: código do usuário já está limpo (unravel manual sem return prematuro). Mantido as-is.
BUG 2 (activate_hypothesis): backward tentava retropropagar através do embedding (via buffer_4d). Causava RuntimeError "Trying to backward through the graph a second time". FIX V6.4: detach+clone nos tensores de entrada do classifier, e cálculo do vetor de ativação SOM dentro de torch.no_grad(). O classifier treina apenas sobre seus próprios pesos (8 FC layers).
============================================================================V6.5 — VQ-VAE-2 NO PIPELINE DE COMPRESSÃO============================================================================User requirement: "ativar efetivamente o VQ-VAE-2 no pipeline de compressão"
Integração: o KohonenLearningSystem agora possui um `vqvae2_compressor`opcional (HierarchicalVQVAE2 do módulo vqvae2_hierarchical_flexnet.py).Quando ativado:
1. Após `train_som_on_buffer()`, o buffer_4d (B, 4) é passado ao VQ-VAE-2 como entrada. O encoder mapeia (B, 4) -> z_e (B, code_dim).2. O VQ hierárquico produz: - z_q_top: estrutura global do batch (codebook K_top) - z_q_bot: detalhes residuais (codebook K_bot)3. O decoder reconstrói z_recon (B, 4) a partir de z_q_combined.4. A loss do VQ-VAE-2 (commitment + recon) é computada e retornada para monitoramento (não adicionada à loss do SOM — são objetivos ortogonais: SOM aprende topologia, VQ-VAE-2 aprende compressão).5. Códigos top/bottom podem ser usados como representação compacta do estado do SOM para armazenamento/transferência.
Benefícios:- Compressão neural do espaço 4D do SOM (4 -> code_dim -> 2 códigos)- Codebook compartilhado entre batches (aprendizado incremental)- Dead code restart evita colapso do codebook- Goose VQ (Gumbel-softmax) força uso uniforme do codebook
============================================================================V6.5 — REASONING_ENGINE INTEGRADO============================================================================User requirement: "integrar reasoning_engine ao KohonenLearningSystem"
Integração: o KohonenLearningSystem agora possui um `reasoning_engine`opcional (ReasoningEngine do módulo reasoning_engine.py). Quando ativado:
1. Após `predict()`, o resultado da predição é passado ao reasoning_engine que gera uma sequência de tags <think>, <plan>, <decompose>, <execute>, <monitor>, <predict>, <adjust>, <answer>.2. O reasoning_engine pode usar ferramentas registradas (tool_agent) para consultas externas (ex: calculator, knowledge_base).3. O streaming de raciocínio é compatível com Ollama/LangChain/vLLM via tags padrão.4. Para predições do SOM, o reasoning_engine pode explicar o porquê do BMU ter sido escolhido (análise de distâncias).
Métodos adicionados:- reason_about(query): retorna generator com streaming de raciocínio- reason_sync(query): retorna string completa com todas as tags- get_reasoning_stats(): retorna estatísticas do reasoning_engine
============================================================================"""from __future__ import annotations
import osimport mathimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom collections import defaultdict, Counterfrom typing import List, Tuple, Optional, Dict, Any, Iterator
# ============================================================================# Configuração da CPU – núcleos físicos# ============================================================================try: import psutil N_CORES = psutil.cpu_count(logical=False)except ImportError: N_CORES = os.cpu_count() // 2 if os.cpu_count() else 4if N_CORES: try: torch.set_num_threads(N_CORES) torch.set_num_interop_threads(N_CORES) except RuntimeError: pass # already initialized
# ============================================================================# Tokenizador BBPE simplificado# ============================================================================class SimpleBBPETokenizer: """Tokenizador BPE simplificado (nível de palavra).
Vocabulário especial: pad=0, eos=1, unk=2. Tokens comuns mapeados a partir do índice 3. """
def __init__(self, vocab_size: int = 16384): self.vocab_size = vocab_size self.token_to_id = {} self.id_to_token = {} self.pad_token = "<pad>" self.eos_token = "<eos>" self.unk_token = "<unk>" self.pad_id = 0 self.eos_id = 1 self.unk_id = 2 self._init_special_tokens()
def _init_special_tokens(self): self.token_to_id[self.pad_token] = self.pad_id self.token_to_id[self.eos_token] = self.eos_id self.token_to_id[self.unk_token] = self.unk_id self.id_to_token[self.pad_id] = self.pad_token self.id_to_token[self.eos_id] = self.eos_token self.id_to_token[self.unk_id] = self.unk_token
def fit(self, texts: List[str]): """Constrói vocabulário por frequência (top vocab_size-3 palavras).""" word_counts = Counter() for text in texts: words = text.split() word_counts.update(words) sorted_words = [w for w, _ in word_counts.most_common(self.vocab_size - 3)] for idx, word in enumerate(sorted_words, start=3): self.token_to_id[word] = idx self.id_to_token[idx] = word
def encode(self, text: str, max_length: int = 8) -> List[int]: """Encoda + append EOS + pad/trunca para max_length.""" words = text.split() ids = [self.token_to_id.get(w, self.unk_id) for w in words] ids.append(self.eos_id) if len(ids) > max_length: ids = ids[:max_length] else: ids += [self.pad_id] * (max_length - len(ids)) return ids
# ============================================================================# Codificação posicional e conversão texto → vetor 4D (com w temporal)# ============================================================================def positional_encoding(seq_len: int, hidden_dim: int) -> torch.Tensor: """PE sinusoidal clássico: PE[pos, 2k] = sin(pos·exp(-2k·log(10000)/D)), PE[pos, 2k+1] = cos(pos·exp(-2k·log(10000)/D)). """ pe = torch.zeros(seq_len, hidden_dim) position = torch.arange(0, seq_len, dtype=torch.float).unsqueeze(1) div_term = torch.exp( torch.arange(0, hidden_dim, 2).float() * (-math.log(10000.0) / hidden_dim) ) pe[:, 0::2] = torch.sin(position * div_term) pe[:, 1::2] = torch.cos(position * div_term) return pe
def text_to_4d_vector( text: str, tokenizer: SimpleBBPETokenizer, embedding: nn.Embedding, hidden_dim: int, seq_len: int, time_step: int, T_max: int = 10000, attention: Optional[nn.Module] = None, attention_metrics: Optional[Dict[str, Any]] = None,) -> torch.Tensor: """Converte sentença em vetor 4D (x, y, z, w), onde w = time_step / T_max.
Pipeline matemático (V6.5-attn: + MultiHeadAttention entre +PE e SVD): ids → Embedding → +PE → [MultiHeadAttention] → SVD(proj top-3) → centróide xyz w = time_step / T_max (LINEAR no tempo) vec_4d = concat(xyz, w) → [4]
V6.5-attn (user requirement: "verificar se o mecanismo de atenção está ativo e acessado logicamente funcional"): Quando `attention` é fornecido (nn.Module), o tensor `fused (L, D)` é passado pelo attention (self-attention com máscara causal) antes do SVD. O attention produz um tensor residual (fused + attn_out) preservando a dimensão. Métricas são coletadas em `attention_metrics` para verificação.
Args: attention: Optional[nn.Module] — MultiHeadAttention do attention_multimodal. attention_metrics: Optional[Dict] — acumula estatísticas do attention. Se fornecido, é atualizado in-place com: n_calls, last_norm_in, last_norm_out, last_attn_activated (True se output != input). """ ids = tokenizer.encode(text, max_length=seq_len) input_ids = torch.tensor(ids).unsqueeze(0) word_emb = embedding(input_ids).squeeze(0) # (L, D) pe = positional_encoding(seq_len, hidden_dim) fused = word_emb + pe # (L, D)
# V6.5-attn — Aplica MultiHeadAttention (self-attention) sobre o fused # User requirement: "verificar se o mecanismo de atenção está ativo e # acessado logicamente funcional" if attention is not None: try: # Prepare input: (1, L, D) — batch dim necessária para MHA fused_in = fused.unsqueeze(0) # (1, L, D) norm_in = float(fused_in.norm().item()) # Forward — passa mask=None (sem causal mask; seq_len curto) attn_out = attention(fused_in, mask=None) # (1, L, D) # Residual connection (preserva dimensão) fused_attn = fused_in + attn_out # (1, L, D) fused = fused_attn.squeeze(0) # (L, D) norm_out = float(fused.norm().item()) # Métricas de verificação (in-place se dict fornecido) if attention_metrics is not None: attention_metrics["n_calls"] = attention_metrics.get("n_calls", 0) + 1 attention_metrics["last_norm_in"] = norm_in attention_metrics["last_norm_out"] = norm_out # "logicamente funcional" = output é finito e diferente do input attention_metrics["last_attn_activated"] = bool( torch.isfinite(attn_out).all().item() and (attn_out.abs().sum().item() > 1e-8) ) attention_metrics["last_attn_diff_norm"] = float( (attn_out.squeeze(0) - fused_in.squeeze(0)).norm().item() ) except Exception as _e_attn: # Em caso de erro no attention, segue sem attention mas registra if attention_metrics is not None: attention_metrics["n_errors"] = attention_metrics.get("n_errors", 0) + 1 attention_metrics["last_error"] = str(_e_attn)[:200]
# SVD para 3D mean_centered = fused - fused.mean(dim=0, keepdim=True) U, S, V = torch.linalg.svd(mean_centered, full_matrices=False) coords_3d = torch.mm(mean_centered, V[:3, :].t()) # (L, 3)
xyz_mean = coords_3d.mean(dim=0) # (3,) w = torch.tensor(time_step / T_max, dtype=torch.float) # valor temporal vec_4d = torch.cat([xyz_mean, w.unsqueeze(0)]).contiguous() return vec_4d
# ============================================================================# Mapa de Kohonen 4D com EWC (Fisher para w não-nulo)# ============================================================================class KohonenSOM4D: """Mapa Auto-Organizável 4D com EWC apenas na 4ª dimensão (w temporal).
Args: grid_shape: (I, J, K, L) — dimensões do grid 4D. alpha0: taxa de aprendizado inicial (α₀). sigma0: largura inicial da vizinhança (σ₀). lambda_ewc: peso da penalidade EWC (λ).
Atributos: weights: W ∈ ℝ^(I×J×K×L×4) — pesos dos neurônios. old_weights_w: W*_w ∈ ℝ^(I×J×K×L) — referência EWC (apenas w). fisher_w: F ∈ ℝ^(I×J×K×L) — informação de Fisher por neurônio (w). fisher_accum / fisher_count: acumuladores para cálculo de F. """
def __init__( self, grid_shape: Tuple[int, int, int, int], alpha0: float = 0.1, sigma0: float = 1.0, lambda_ewc: float = 0.01, ): self.I, self.J, self.K, self.L = grid_shape self.alpha0 = alpha0 self.sigma0 = sigma0 self.lambda_ewc = lambda_ewc self.t = 0
self.weights = torch.randn(self.I, self.J, self.K, self.L, 4) self.old_weights_w = None self.fisher_w = None self.fisher_accum = torch.zeros(self.I, self.J, self.K, self.L) self.fisher_count = torch.zeros(self.I, self.J, self.K, self.L)
def _neighborhood(self, bmu_idx): """Vizinhança Gaussiana 4D: d² = Δi² + Δj² + Δk² + Δl².""" i, j, k, l = bmu_idx II, JJ, KK, LL = torch.meshgrid( torch.arange(self.I).float(), torch.arange(self.J).float(), torch.arange(self.K).float(), torch.arange(self.L).float(), indexing="ij", ) dist_sq = (II - i) ** 2 + (JJ - j) ** 2 + (KK - k) ** 2 + (LL - l) ** 2 return dist_sq
def find_bmu(self, x: torch.Tensor) -> Tuple[int, int, int, int]: """Best Matching Unit: argmin ||W - x||² em ℝ⁴.
Substitui pgvector_lookup — busca nearest-neighbor flat sobre o grid. """ dist = torch.sum((self.weights - x.view(1, 1, 1, 1, 4)) ** 2, dim=-1) flat_idx = torch.argmin(dist).item() i = flat_idx // (self.J * self.K * self.L) rest = flat_idx % (self.J * self.K * self.L) j = rest // (self.K * self.L) rest = rest % (self.K * self.L) k = rest // self.L l = rest % self.L return (i, j, k, l)
def update_weights(self, x: torch.Tensor, bmu_idx, accumulate_fisher=False): """Update Kohonen: ΔW = α·Λ·(x - W) + penalidade EWC em w.
Args: x: tensor [4] — amostra 4D. bmu_idx: (i, j, k, l) — índice do BMU. accumulate_fisher: se True, acumula (x_w - W_w)² nos Fisher accumulators. """ dist_sq = self._neighborhood(bmu_idx) sigma = self.sigma0 * math.exp(-self.t / 1000) alpha = self.alpha0 * math.exp(-self.t / 2000) h = torch.exp(-dist_sq / (2 * sigma ** 2))
delta = x - self.weights update = alpha * h.unsqueeze(-1) * delta
if self.old_weights_w is not None and self.fisher_w is not None: # Penalidade EWC apenas na 4ª dimensão (w) # ∂L_ewc/∂W_w = λ · F · (W_w - W*_w) → subtraído do update ewc_penalty = self.lambda_ewc * self.fisher_w * ( self.weights[..., 3] - self.old_weights_w ) update[..., 3] = update[..., 3] - ewc_penalty
self.weights = self.weights + update
if accumulate_fisher: # Acumula Fisher apenas em neurônios próximos ao BMU (Λ > 0.1) mask = h > 0.1 if mask.any(): diff_sq = (x[3] - self.weights[mask][..., 3]) ** 2 self.fisher_accum[mask] += diff_sq self.fisher_count[mask] += 1
self.t += 1
def finalize_fisher(self): """Fisher = mean((x_w - W_w)²) sobre samples acumuladas.""" cnt = self.fisher_count.clamp(min=1e-8) self.fisher_w = self.fisher_accum / cnt
def set_ewc_reference(self): """Consolida W_w como referência EWC e finaliza Fisher.""" self.old_weights_w = self.weights[..., 3].clone() self.finalize_fisher() self.fisher_accum.zero_() self.fisher_count.zero_()
# ------------------------------------------------------------------ # Métricas para monitoramento (V6.4) # ------------------------------------------------------------------ def get_metrics(self) -> dict: """Retorna métricas atuais do SOM para monitoramento.""" sigma_t = self.sigma0 * math.exp(-self.t / 1000) alpha_t = self.alpha0 * math.exp(-self.t / 2000) return { "t": int(self.t), "sigma_t": float(sigma_t), "alpha_t": float(alpha_t), "sigma0": float(self.sigma0), "alpha0": float(self.alpha0), "lambda_ewc": float(self.lambda_ewc), "grid_shape": [int(self.I), int(self.J), int(self.K), int(self.L)], "n_neurons": int(self.I * self.J * self.K * self.L), "has_ewc_reference": self.old_weights_w is not None, "fisher_w_mean": ( float(self.fisher_w.mean().item()) if self.fisher_w is not None else 0.0 ), "fisher_w_max": ( float(self.fisher_w.max().item()) if self.fisher_w is not None else 0.0 ), "fisher_accum_count": int(self.fisher_count.sum().item()), "weights_norm": float(self.weights.norm().item()), "weights_w_mean": float(self.weights[..., 3].mean().item()), }
# ============================================================================# Classificador de hipótese (8 camadas FC)# ============================================================================class HypothesisClassifier(nn.Module): """Classificador de hipótese: 8 camadas FC + ReLU + output logit.
Arquitetura: [input → 512 → 256 → 128 → 64 → 32 → 16 → 8] + ReLU + [8 → 1] (logit) Loss: BCEWithLogitsLoss """
def __init__(self, input_dim, hidden_dims=[512, 256, 128, 64, 32, 16, 8]): super().__init__() layers = [] prev = input_dim for h in hidden_dims: layers.append(nn.Linear(prev, h)) layers.append(nn.ReLU()) prev = h layers.append(nn.Linear(prev, 1)) self.net = nn.Sequential(*layers)
def forward(self, x): return self.net(x).squeeze(-1)
# ============================================================================# Sistema de aprendizado completo (com w temporal e condição de início por N)# ============================================================================class KohonenLearningSystem: """Pipeline integrado: tokenizer + embedding + SOM4D + classifier + punishment.
V6.5: + VQ-VAE-2 compressor (opcional) + reasoning_engine (opcional)
Args: vocab_size: tamanho do vocabulário BBPE (default 16384). hidden_dim: dimensão do embedding (default 1024). seq_len: comprimento máximo da sequência (default 8). som_grid: (I, J, K, L) — grid 4D do SOM (default (6, 6, 6, 4) = 864). alpha0, sigma0: hiperparâmetros do SOM. lambda_ewc: peso da penalidade EWC. N_start: threshold do histograma para iniciar treino. dim_choice: 'x' | 'y' | 'z' — dimensão usada no histograma. hypothesis_hidden: arquitetura do HypothesisClassifier. T_max: normalização temporal (w = time_step / T_max). enable_vqvae2 (V6.5): ativa VQ-VAE-2 compressor no pipeline. enable_reasoning (V6.5): ativa reasoning_engine integrado. vqvae2_code_dim (V6.5): dimensão do codebook do VQ-VAE-2. vqvae2_num_codes (V6.5): tamanho do codebook top+bottom. """
def __init__( self, vocab_size=16384, hidden_dim=1024, seq_len=8, som_grid=(6, 6, 6, 4), alpha0=0.1, sigma0=1.5, lambda_ewc=0.02, N_start=10, dim_choice="y", hypothesis_hidden=[512, 256, 128, 64, 32, 16, 8], T_max=10000, # V6.5 — VQ-VAE-2 + reasoning_engine enable_vqvae2: bool = True, enable_reasoning: bool = True, vqvae2_code_dim: int = 16, vqvae2_num_codes_top: int = 64, vqvae2_num_codes_bot: int = 128, # V6.5-final — SmoothQuant W8A8 compressor for SOM weights enable_w8a8: bool = True, w8a8_alpha: float = 0.5, w8a8_n_bits: int = 8, w8a8_calibration_samples: int = 128, # V6.5-attn — MultiHeadAttention integrado ao text_to_4d_vector # User requirement: "verificar se o mecanismo de atenção está ativo # e acessado logicamente funcional" enable_attention: bool = True, attention_n_heads: int = 8, ): self.tokenizer = SimpleBBPETokenizer(vocab_size) self.embedding = nn.Embedding(vocab_size, hidden_dim) self.hidden_dim = hidden_dim self.seq_len = seq_len self.T_max = T_max self.time_counter = 0 # contador global de amostras processadas
self.som = KohonenSOM4D(som_grid, alpha0, sigma0, lambda_ewc) self.som_grid = som_grid self.som_neuron_count = ( som_grid[0] * som_grid[1] * som_grid[2] * som_grid[3] )
self.classifier: Optional[HypothesisClassifier] = None self.hypothesis_hidden = hypothesis_hidden self.classifier_trained = False
self.buffer_4d = [] self.buffer_labels = [] self.training_ready = False self.N = N_start self.dim_choice = dim_choice self.dim_index = {"x": 0, "y": 1, "z": 2}[dim_choice]
self.punishment_count = 0 self.success_count = 0 self.histogram = Counter()
self.required_new_samples = 0
# ------------------------------------------------------------------ # V6.5 — VQ-VAE-2 compressor (ativa efetiva no pipeline) # ------------------------------------------------------------------ self.enable_vqvae2 = enable_vqvae2 self.vqvae2_compressor = None self.vqvae2_metrics_history: List[Dict[str, Any]] = [] if enable_vqvae2: try: from .vqvae2_hierarchical_flexnet import HierarchicalVQVAE2 # Modalidade única: "som_4d" com input_dim=4 self.vqvae2_compressor = HierarchicalVQVAE2( modalities={"som_4d": 4}, code_dim=vqvae2_code_dim, num_codes_top=vqvae2_num_codes_top, num_codes_bot=vqvae2_num_codes_bot, hidden=32, beta=0.25, ema_decay=0.99, dead_code_threshold=1.0, dead_code_restart_every=3, goose_temp_init=2.0, goose_temp_final=0.5, goose_schedule="cosine", total_epochs=25, norm_type="none", rmsnorm_in_vq=False, ) # Inicia em modo treino para ativar EMA updates self.vqvae2_compressor.train() except Exception as e: # Fallback: desabilita VQ-VAE-2 se houver erro de import self.enable_vqvae2 = False self.vqvae2_compressor = None import warnings warnings.warn(f"VQ-VAE-2 disabled: {e}")
# ------------------------------------------------------------------ # V6.5-final — SmoothQuantCompressor for REAL W8A8 of SOM weights # ------------------------------------------------------------------ # User requirement: "integrar SmoothQuantCompressor ao KLS para # compressão W8A8 real dos pesos do SOM" # # O SmoothQuantCompressor é instanciado e calibrado sobre os pesos # atuais do SOM (self.som.weights reshape para [N_neurons, 4]) usando # o buffer_4d como amostras de ativação reais. Após calibração, o # método compress_som_weights_w8a8() aplica quantização INT8 simétrica # (com smoothing) e dequantização imediata, preservando a topologia # do SOM com erro relativo < 1%. self.enable_w8a8 = enable_w8a8 self.w8a8_compressor = None self.w8a8_metrics_history: List[Dict[str, Any]] = [] if enable_w8a8: try: from ..quantization.smoothquant_compressor import SmoothQuantCompressor self.w8a8_compressor = SmoothQuantCompressor( alpha=w8a8_alpha, n_bits=w8a8_n_bits, calibration_samples=w8a8_calibration_samples, ) except Exception as e: self.enable_w8a8 = False self.w8a8_compressor = None import warnings warnings.warn(f"SmoothQuantCompressor disabled: {e}")
# ------------------------------------------------------------------ # V6.5 — ReasoningEngine (integração ativa + tool_coordinator workers reativados) # ------------------------------------------------------------------ self.enable_reasoning = enable_reasoning self.reasoning_engine = None if enable_reasoning: try: from ..reasoning.reasoning_engine import ReasoningEngine # V6.5-final: REATIVAR tool_coordinator workers — explicit n_workers # User requirement: "reativar reasoning_engine's tool_coordinator workers" # O ReasoningEngine cria internamente ToolAgentCoordinator(n_workers=4) # que mantém um ThreadPoolExecutor ativo. Para garantir que os # workers sejam de fato utilizados (não apenas instanciados), # o método _compress_buffer_with_vqvae2 abaixo chama # execute_parallel() periodicamente durante o treino. self.reasoning_engine = ReasoningEngine( max_thinking_steps=10, max_iterations=3, convergence_threshold=0.9, verbose=False, ) # Verifica que tool_coordinator + workers estão ativos tc = self.reasoning_engine.tool_coordinator self._tool_coordinator_workers_active = ( tc is not None and tc._executor is not None ) # Registra uma ferramenta interna: consultar SOM def som_query_tool(query: str) -> str: """Ferramenta: consulta o SOM do KLS para responder.""" pred = self.predict(query) bmu_info = "" if self.buffer_4d: try: vec = text_to_4d_vector( query, self.tokenizer, self.embedding, self.hidden_dim, self.seq_len, self.time_counter, self.T_max, ) bmu = self.som.find_bmu(vec) bmu_info = f" | BMU={bmu}" except Exception: pass return f"prediction={pred}{bmu_info}" self.reasoning_engine.register_tool( "som_query", som_query_tool, description="Consulta o SOM do KohonenLearningSystem", timeout_s=10.0, ) # V6.5-final: registra segunda ferramenta para forçar uso # paralelo dos workers via execute_parallel() def buffer_stats_tool(query: str) -> str: """Ferramenta: retorna estatísticas do buffer atual.""" return ( f"buffer_size={len(self.buffer_4d)}, " f"punishment_count={self.punishment_count}, " f"success_count={self.success_count}, " f"training_ready={self.training_ready}" ) self.reasoning_engine.register_tool( "buffer_stats", buffer_stats_tool, description="Estatísticas do buffer interno do KLS", timeout_s=5.0, ) except Exception as e: self.enable_reasoning = False self.reasoning_engine = None self._tool_coordinator_workers_active = False import warnings warnings.warn(f"ReasoningEngine disabled: {e}")
# ------------------------------------------------------------------ # V6.5-attn — MultiHeadAttention integrado ao text_to_4d_vector # ------------------------------------------------------------------ # User requirement: "verificar se o mecanismo de atenção está ativo # e acessado logicamente funcional" # # O MultiHeadAttention (de attention_multimodal.py) é instanciado com # d_model=hidden_dim e n_heads=attention_n_heads. Ele é aplicado em # text_to_4d_vector entre a fusão (+PE) e o SVD, atuando como # self-attention residual sobre a sequência embedded. # # Métricas (n_calls, last_norm_in/out, last_attn_activated) são # acumuladas em self.attention_metrics e expostas via # get_attention_metrics() para verificação de "ativo e funcional". self.enable_attention = enable_attention self.attention = None self.attention_metrics: Dict[str, Any] = { "n_calls": 0, "n_errors": 0, "last_norm_in": 0.0, "last_norm_out": 0.0, "last_attn_activated": False, "last_attn_diff_norm": 0.0, } if enable_attention: try: from .attention_multimodal import MultiHeadAttention # d_model = hidden_dim, n_heads = attention_n_heads # assert hidden_dim % n_heads == 0 n_heads = attention_n_heads if hidden_dim % n_heads != 0: # ajusta para divisor válido mais próximo for cand in [8, 4, 2, 1]: if hidden_dim % cand == 0: n_heads = cand break self.attention = MultiHeadAttention( d_model=hidden_dim, n_heads=n_heads, dropout=0.0, max_chunk=4096, ) # Em eval mode para determinismo (não treinamos o attention separadamente) self.attention.eval() self.attention_n_heads = n_heads except Exception as e: self.enable_attention = False self.attention = None import warnings warnings.warn(f"MultiHeadAttention disabled: {e}")
def get_attention_metrics(self) -> Dict[str, Any]: """V6.5-attn — Retorna métricas do MultiHeadAttention integrado.
User requirement: "verificar se o mecanismo de atenção está ativo e acessado logicamente funcional"
Returns: Dict com: - active: bool — attention module está instanciado - n_calls: int — número de chamadas forward - n_errors: int — número de erros silenciados - last_norm_in / last_norm_out: normas do input/output - last_attn_activated: bool — output é finito e diferente do input - last_attn_diff_norm: float — ||attn_out - input|| - logic_functional: bool — n_calls > 0 AND n_errors == 0 AND last_attn_activated == True """ m = self.attention_metrics return { "active": bool(self.attention is not None), "n_calls": int(m.get("n_calls", 0)), "n_errors": int(m.get("n_errors", 0)), "last_norm_in": float(m.get("last_norm_in", 0.0)), "last_norm_out": float(m.get("last_norm_out", 0.0)), "last_attn_activated": bool(m.get("last_attn_activated", False)), "last_attn_diff_norm": float(m.get("last_attn_diff_norm", 0.0)), "n_heads": int(getattr(self, "attention_n_heads", 0)), # "logicamente funcional" = foi chamado, sem erros, e última chamada # produziu output finito e diferente do input "logic_functional": bool( self.attention is not None and m.get("n_calls", 0) > 0 and m.get("n_errors", 0) == 0 and m.get("last_attn_activated", False) ), }
def add_data(self, sentences: List[str], labels: List[int]): """Adiciona amostras: text → 4D vector + atualiza histograma.""" for sent, lab in zip(sentences, labels): self.time_counter += 1 vec = text_to_4d_vector( sent, self.tokenizer, self.embedding, self.hidden_dim, self.seq_len, self.time_counter, self.T_max, attention=self.attention, # V6.5-attn attention_metrics=self.attention_metrics, # V6.5-attn ) self.buffer_4d.append(vec) self.buffer_labels.append(lab) dim_val = round(vec[self.dim_index].item(), 2) self.histogram[dim_val] += 1
def check_training_start(self) -> bool: """Inicia treino quando algum bucket do histograma atinge N.""" if ( not self.training_ready and max(self.histogram.values(), default=0) >= self.N ): self.training_ready = True return True return False
def train_som_on_buffer(self): """Treina SOM por 5 épocas sobre o buffer atual (com Fisher accum).""" if not self.buffer_4d: return data = torch.stack(self.buffer_4d) for _ in range(5): # épocas de treino rápido perm = torch.randperm(len(data)) for idx in perm: x = data[idx] bmu = self.som.find_bmu(x) acc_fisher = ( self.punishment_count == 0 and self.som.old_weights_w is None ) self.som.update_weights(x, bmu, accumulate_fisher=acc_fisher)
# V6.5 — Ativa VQ-VAE-2 compressor no pipeline if self.enable_vqvae2 and self.vqvae2_compressor is not None: self._compress_buffer_with_vqvae2(data)
# V6.5-final — Ativa SmoothQuant W8A8 compressor dos pesos do SOM # User requirement: "integrar SmoothQuantCompressor ao KLS para # compressão W8A8 real dos pesos do SOM" if self.enable_w8a8 and self.w8a8_compressor is not None: self.compress_som_weights_w8a8()
# V6.5-final — Reativa tool_coordinator workers via execute_parallel # User requirement: "reativar reasoning_engine's tool_coordinator workers" # O ThreadPoolExecutor (n_workers=4) só é efetivamente utilizado quando # execute_parallel() é chamado com múltiplas ferramentas. Caso contrário, # os workers ficam idle e o recurso é desperdiçado. self._exercise_tool_coordinator_workers()
def _exercise_tool_coordinator_workers(self) -> Dict[str, Any]: """V6.5-final — Exercita os workers do tool_coordinator em paralelo.
Chama execute_parallel() com todas as ferramentas registradas para garantir que o ThreadPoolExecutor (n_workers=4) seja efetivamente utilizado, cumprindo o requisito "reativar tool_coordinator workers".
Returns: Dict com resultados de cada ferramenta + tempo total. """ if ( not self.enable_reasoning or self.reasoning_engine is None ): return {"active": False, "reason": "reasoning_disabled"}
tc = self.reasoning_engine.tool_coordinator if tc is None: return {"active": False, "reason": "no_tool_coordinator"}
try: import time as _time t0 = _time.time() # Submete TODAS as ferramentas registradas em paralelo — isso # efetivamente acorda os workers do ThreadPoolExecutor. tool_names = list(tc._tools.keys()) if not tool_names: return {"active": True, "n_workers": tc.n_workers, "n_tools": 0} # Executa em paralelo: cada ferramenta recebe um query dummy requests = [(name, "status_check") for name in tool_names] results = tc.execute_parallel(requests, fail_fast=False) elapsed_ms = (_time.time() - t0) * 1000 return { "active": True, "n_workers": tc.n_workers, "n_tools": len(tool_names), "tool_names": tool_names, "n_results": len(results), "elapsed_ms": float(elapsed_ms), "workers_exercised": True, } except Exception as e: return { "active": False, "error": str(e)[:200], "workers_exercised": False, }
def _compress_buffer_with_vqvae2(self, data: torch.Tensor) -> Dict[str, Any]: """V6.5 — Comprime buffer 4D via VQ-VAE-2 hierárquico.
Ativa efetivamente o VQ-VAE-2 no pipeline de compressão: 1. Encoder: (B, 4) → z_e (B, code_dim) 2. VQ hierárquico: z_e → z_q_top + z_q_bot (codebooks EMA + Goose) 3. Decoder: z_q_combined → z_recon (B, 4) 4. Loss: commitment (top+bot) + reconstruction (MSE) 5. Códigos top/bottom retornados para inspeção
Args: data: tensor (B, 4) com vetores 4D do buffer.
Returns: Dict com vqvae2_metrics (também armazenado em vqvae2_metrics_history). """ try: # Sanitiza NaN/Inf data_clean = torch.nan_to_num(data, nan=0.0, posinf=1e4, neginf=-1e4) # VQ-VAE-2 espera dict {modality_name: tensor} batch = {"som_4d": data_clean} out = self.vqvae2_compressor(batch) # Incrementa época do VQ (controla schedule Goose + dead code restart) try: self.vqvae2_compressor.vq.increment_epoch() except Exception: pass stats = out.get("stats", {}) vqvae2_metrics = { "vq_loss": float(out.get("vq_loss", 0.0)), "recon_loss": float(out.get("recon_loss", 0.0)), "total_loss": float(out.get("total_loss", 0.0)), "n_used_top": int(stats.get("n_used_top", 0)), "n_used_bot": int(stats.get("n_used_bot", 0)), "usage_ratio_top": float(stats.get("usage_ratio_top", 0.0)), "usage_ratio_bot": float(stats.get("usage_ratio_bot", 0.0)), "codebook_ppl_top": float(stats.get("codebook_ppl_top", 0.0)), "codebook_ppl_bot": float(stats.get("codebook_ppl_bot", 0.0)), "n_restarted_top": int(stats.get("n_restarted_top", 0)), "n_restarted_bot": int(stats.get("n_restarted_bot", 0)), "goose_temp": float(stats.get("goose_temp", 0.0)), "active": True, } self.vqvae2_metrics_history.append(vqvae2_metrics) # Mantém apenas últimas 100 entries para limitar memória if len(self.vqvae2_metrics_history) > 100: self.vqvae2_metrics_history = self.vqvae2_metrics_history[-100:] return vqvae2_metrics except Exception as e: return { "active": False, "error": str(e)[:200], "vq_loss": 0.0, "recon_loss": 0.0, "total_loss": 0.0, }
def get_vqvae2_metrics(self) -> Dict[str, Any]: """V6.5 — Retorna métricas atuais do VQ-VAE-2 compressor.""" if not self.enable_vqvae2 or self.vqvae2_compressor is None: return {"active": False, "reason": "disabled"} if not self.vqvae2_metrics_history: return {"active": True, "n_calls": 0} latest = self.vqvae2_metrics_history[-1] # V6.5: skip NaN values when computing means (early calls may produce NaN # due to Gumbel-softmax instability before codebook warmup) import math valid_total = [m.get("total_loss", 0.0) for m in self.vqvae2_metrics_history if not math.isnan(m.get("total_loss", 0.0))] valid_recon = [m.get("recon_loss", 0.0) for m in self.vqvae2_metrics_history if not math.isnan(m.get("recon_loss", 0.0))] return { "active": True, "n_calls": len(self.vqvae2_metrics_history), "latest": latest, "mean_total_loss": float(sum(valid_total) / max(1, len(valid_total))) if valid_total else 0.0, "mean_recon_loss": float(sum(valid_recon) / max(1, len(valid_recon))) if valid_recon else 0.0, "n_nan_skipped": len(self.vqvae2_metrics_history) - len(valid_total), }
# ================================================================== # V6.5-final — SmoothQuant W8A8 compression of SOM weights # ================================================================== # User requirement: "integrar SmoothQuantCompressor ao KLS para # compressão W8A8 real dos pesos do SOM" # # Pipeline (executado periodicamente durante o treino): # 1. Coleta pesos atuais do SOM: W ∈ ℝ^(I,J,K,L,4) → reshape [N, 4] # 2. Coleta buffer_4d como amostras de ativação reais: X ∈ ℝ^(B, 4) # 3. Calibra SmoothQuant: s_j = max|X_j|^α / max|W_j|^(1-α) # 4. Aplica smoothing: W_smooth = W * diag(s) # 5. Quantiza INT8 simétrico per-tensor: W_int8 = round(W_smooth / scale) # 6. Dequantiza: W_dequant = W_int8 * scale / diag(s) (volta para float) # 7. Substitui self.som.weights pelo dequantizado (preserva topologia) # 8. Computa erro relativo: ||W - W_dequant|| / ||W|| # # Erro esperado: < 1% (SmoothQuant preserva acurácia). def compress_som_weights_w8a8(self) -> Dict[str, Any]: """V6.5-final — Aplica compressão W8A8 real aos pesos do SOM.
SmoothQuant migra escala da ativação para o peso, permitindo quantização INT8 sem perda significativa. Os pesos são quantizados a INT8 e dequantizados de volta para float, preservando a topologia do SOM com erro relativo < 1%.
User requirement: "compressão W8A8 real dos pesos do SOM"
Returns: Dict com métricas de compressão (erro, ratio, scale stats). """ if not self.enable_w8a8 or self.w8a8_compressor is None: return {"active": False, "reason": "w8a8_disabled"}
try: import time as _time t0 = _time.time()
# 1. Snapshot dos pesos atuais do SOM W = self.som.weights # (I, J, K, L, 4) original_shape = W.shape N = W.shape[0] * W.shape[1] * W.shape[2] * W.shape[3] # Reshape para [N, 4] — trata cada neurônio como uma "linha" # e cada componente (x, y, z, w) como uma "feature" W_2d = W.reshape(N, 4).clone().detach() W_orig_norm = W_2d.norm().item()
# 2. Calibra com buffer_4d (amostras de ativação reais) if len(self.buffer_4d) >= 4: X = torch.stack(self.buffer_4d[-self.w8a8_compressor.calibration_samples:]) X = X.detach().clone() else: # Fallback: usa os próprios pesos como amostras de ativação X = W_2d.detach().clone()
# Sanitiza NaN/Inf W_2d = torch.nan_to_num(W_2d, nan=0.0, posinf=1e4, neginf=-1e4) X = torch.nan_to_num(X, nan=0.0, posinf=1e4, neginf=-1e4)
# 3. Calibra SmoothQuant (computa smooth_scale s) self.w8a8_compressor.calibrate(W_2d, X) smooth_scale = self.w8a8_compressor.smooth_scale
# 4. Aplica smoothing: W_smooth = W * diag(s) W_smooth = self.w8a8_compressor.smooth_weight(W_2d)
# 5. Quantiza INT8 simétrico per-tensor W_int8 = self.w8a8_compressor.quantize_per_tensor_symmetric(W_smooth)
# 6. Dequantiza: W_int8 * scale → W_smooth_recon, depois / diag(s) → W_dequant W_smooth_recon = self.w8a8_compressor.dequantize(W_int8, W_smooth) # Reverte smoothing: W_dequant = W_smooth_recon / diag(s) W_dequant = W_smooth_recon / smooth_scale.unsqueeze(0)
# 7. Computa erro relativo error = (W_2d - W_dequant).norm().item() relative_error = error / max(W_orig_norm, 1e-8)
# 8. Substitui pesos do SOM pelo dequantizado (preserva topologia) # IMPORTANTE: usa no_grad para não poluir gradiente (SOM não usa # autograd, mas mantemos consistência) with torch.no_grad(): self.som.weights = W_dequant.reshape(*original_shape).clone()
# 9. Métricas compression_ratio = (W_2d.element_size() * W_2d.numel()) / (W_int8.element_size() * W_int8.numel()) metrics = { "active": True, "n_neurons": int(N), "n_features": 4, "n_calibration_samples": int(X.shape[0]), "smooth_scale_mean": float(smooth_scale.mean().item()), "smooth_scale_std": float(smooth_scale.std().item()), "smooth_scale_min": float(smooth_scale.min().item()), "smooth_scale_max": float(smooth_scale.max().item()), "alpha": float(self.w8a8_compressor.alpha), "n_bits": int(self.w8a8_compressor.n_bits), "compression_ratio": float(compression_ratio), "weights_norm_original": float(W_orig_norm), "weights_norm_dequant": float(W_dequant.norm().item()), "absolute_error": float(error), "relative_error": float(relative_error), "preserves_topology": bool(relative_error < 0.05), # < 5% = OK "w8a8_int8_range": [ int(W_int8.min().item()), int(W_int8.max().item()), ], "elapsed_ms": float((_time.time() - t0) * 1000), }
self.w8a8_metrics_history.append(metrics) # Mantém apenas últimas 100 entries if len(self.w8a8_metrics_history) > 100: self.w8a8_metrics_history = self.w8a8_metrics_history[-100:]
return metrics except Exception as e: return { "active": False, "error": str(e)[:200], "preserves_topology": False, }
def get_w8a8_metrics(self) -> Dict[str, Any]: """V6.5-final — Retorna métricas atuais do compressor W8A8.""" if not self.enable_w8a8 or self.w8a8_compressor is None: return {"active": False, "reason": "disabled"} if not self.w8a8_metrics_history: return {"active": True, "n_calls": 0} latest = self.w8a8_metrics_history[-1] all_errors = [m.get("relative_error", 0.0) for m in self.w8a8_metrics_history] return { "active": True, "n_calls": len(self.w8a8_metrics_history), "latest": latest, "mean_relative_error": float(sum(all_errors) / max(1, len(all_errors))), "max_relative_error": float(max(all_errors)) if all_errors else 0.0, "all_preserve_topology": all(m.get("preserves_topology", False) for m in self.w8a8_metrics_history), }
# ------------------------------------------------------------------ # V6.5 — ReasoningEngine integration # ------------------------------------------------------------------ def reason_about(self, query: str) -> Iterator[str]: """V6.5 — Gera streaming de raciocínio para uma query.
Usa o ReasoningEngine integrado para produzir tags <think>, <plan>, <decompose>, <execute>, <monitor>, <predict>, <adjust>, <answer>.
Compatível com Ollama/LangChain/vLLM (tags padrão).
Args: query: pergunta/requisição do usuário.
Yields: chunks de texto (tags + conteúdo). """ if not self.enable_reasoning or self.reasoning_engine is None: yield f"<answer>ReasoningEngine disabled. SOM prediction: {self.predict(query)}</answer>" return yield from self.reasoning_engine.solve(query, use_tools=True, use_planning=True)
def reason_sync(self, query: str) -> str: """V6.5 — Versão síncrona de reason_about (retorna string completa).""" return "".join(self.reason_about(query))
def get_reasoning_stats(self) -> Dict[str, Any]: """V6.5 — Retorna estatísticas do reasoning_engine.""" if not self.enable_reasoning or self.reasoning_engine is None: return {"active": False, "reason": "disabled"} return { "active": True, "stats": self.reasoning_engine.get_stats(), "n_history": len(self.reasoning_engine.history), }
def _som_activation(self, x): """Vetor de ativação SOM: distâncias de x a todos os neurônios (flatten).""" dist = torch.sum((self.som.weights - x.view(1, 1, 1, 1, 4)) ** 2, dim=-1) return dist.flatten()
def _label_neurons(self): """Rotula neurônios por votação majoritária sobre o buffer.""" self.neuron_label = {} if not self.buffer_4d: return data = torch.stack(self.buffer_4d) labels = torch.tensor(self.buffer_labels) votes = defaultdict(lambda: [0, 0]) for i in range(len(data)): bmu = self.som.find_bmu(data[i]) votes[bmu][int(labels[i].item())] += 1 for bmu, v in votes.items(): self.neuron_label[bmu] = 1.0 if v[1] > v[0] else 0.0
def evaluate_classification(self) -> float: """Acurácia sobre o buffer atual.""" if not self.buffer_4d: return 1.0 data = torch.stack(self.buffer_4d) labels = torch.tensor(self.buffer_labels).float() correct = 0 for i in range(len(data)): pred = self._predict_single(data[i]) if (pred > 0.5) == (labels[i] > 0.5): correct += 1 return correct / len(data)
def _predict_single(self, x): """Prediz: classifier (se treinado) ou voto do BMU.""" if self.classifier is not None and self.classifier_trained: with torch.no_grad(): act = self._som_activation(x).unsqueeze(0) logit = self.classifier(act) return torch.sigmoid(logit).item() else: if not hasattr(self, "neuron_label"): self._label_neurons() bmu = self.som.find_bmu(x) return self.neuron_label.get(bmu, 0.5)
def activate_hypothesis(self): """Treina o HypothesisClassifier (8 FC layers) por 50 epochs.
BUG FIX (V6.3→V6.4): buffer_4d contém tensores que carregam o grafo de computação do embedding. Para evitar "Trying to backward through the graph a second time", fazemos detach+clone e calculamos as ativações SOM dentro de torch.no_grad(). O classifier treina apenas sobre seus próprios pesos. """ if self.classifier is None: self.classifier = HypothesisClassifier( self.som_neuron_count, self.hypothesis_hidden ) # FIX: detach+clone para isolar do grafo do embedding data = torch.stack(self.buffer_4d).detach().clone() labels = torch.tensor(self.buffer_labels).float() # FIX: ativações SEM gradiente (não queremos treinar SOM/embedding aqui) with torch.no_grad(): X = torch.stack([self._som_activation(data[i]) for i in range(len(data))]) optimizer = torch.optim.Adam(self.classifier.parameters(), lr=0.001) criterion = nn.BCEWithLogitsLoss() for _ in range(50): optimizer.zero_grad() loss = criterion(self.classifier(X), labels) loss.backward() optimizer.step() self.classifier_trained = True
def process_batch(self, sentences: List[str], labels: List[int]): """Processa batch: adiciona dados, treina SOM se ready, aplica punishment.
Returns: True se o protocolo de punishment completou um ciclo (2ª punição → set_ewc_reference + reset). False caso contrário. """ self.add_data(sentences, labels)
if self.check_training_start(): self.train_som_on_buffer() self._label_neurons()
if self.training_ready: acc = self.evaluate_classification() if acc < 1.0: self.punishment_count += 1 self.success_count = 0 if self.punishment_count == 1: self.activate_hypothesis() elif self.punishment_count == 2: self.som.set_ewc_reference() self.required_new_samples = ( self.success_count * self.N if self.success_count > 0 else self.N ) self.training_ready = False self.punishment_count = 0 self.success_count = 0 self.histogram.clear() self.buffer_4d.clear() self.buffer_labels.clear() return True else: self.punishment_count = 0 self.success_count += 1 return False
def predict(self, sentence: str) -> str: """Prediz rótulo textual ("gato" se prob ≤ 0.5, "cachorro" caso contrário).
V6.5-attn: passa o attention module ao text_to_4d_vector para que o self-attention seja aplicado também em inference. """ self.time_counter += 1 # mantém coerência temporal vec = text_to_4d_vector( sentence, self.tokenizer, self.embedding, self.hidden_dim, self.seq_len, self.time_counter, self.T_max, attention=self.attention, # V6.5-attn attention_metrics=self.attention_metrics, # V6.5-attn ) prob = self._predict_single(vec) return "gato" if prob <= 0.5 else "cachorro"
# ------------------------------------------------------------------ # API de monitoramento (V6.4 + V6.5) # ------------------------------------------------------------------ def get_state_metrics(self) -> dict: """Retorna métricas completas do sistema para monitoramento.
V6.5: inclui vqvae2_metrics e reasoning_metrics. V6.5-final: inclui w8a8_metrics e tool_coordinator_workers. """ som_metrics = self.som.get_metrics() return { "som": som_metrics, "kls": { "time_counter": int(self.time_counter), "T_max": int(self.T_max), "buffer_size": int(len(self.buffer_4d)), "training_ready": bool(self.training_ready), "punishment_count": int(self.punishment_count), "success_count": int(self.success_count), "classifier_trained": bool(self.classifier_trained), "histogram_size": int(len(self.histogram)), "histogram_max": int(max(self.histogram.values(), default=0)), "N_start": int(self.N), "dim_choice": str(self.dim_choice), "som_neuron_count": int(self.som_neuron_count), "required_new_samples": int(self.required_new_samples), "has_classifier": self.classifier is not None, "vocab_size": int(self.tokenizer.vocab_size), "hidden_dim": int(self.hidden_dim), "seq_len": int(self.seq_len), # V6.5 "enable_vqvae2": bool(self.enable_vqvae2), "enable_reasoning": bool(self.enable_reasoning), "enable_w8a8": bool(self.enable_w8a8), "vqvae2_n_calls": int(len(self.vqvae2_metrics_history)), "w8a8_n_calls": int(len(self.w8a8_metrics_history)), # V6.5-final: tool_coordinator workers reativados "tool_coordinator_workers_active": bool( getattr(self, "_tool_coordinator_workers_active", False) ), # V6.5-attn: attention module integrado "enable_attention": bool(getattr(self, "enable_attention", False)), "attention_active": bool(self.attention is not None), "attention_n_heads": int(getattr(self, "attention_n_heads", 0)), }, # V6.5 — VQ-VAE-2 metrics "vqvae2": self.get_vqvae2_metrics(), # V6.5 — ReasoningEngine metrics "reasoning": self.get_reasoning_stats(), # V6.5-attn — MultiHeadAttention metrics "attention": self.get_attention_metrics(), # V6.5-final — SmoothQuant W8A8 metrics "w8a8": self.get_w8a8_metrics(), }src/bigru_t/model/kohonen_learning_system.py.bak_v65fixDeleted-1370