V6.5-V2-metrics-FIX: upload batch (scripts + modules) [7 files] — restored params + memory fixes
Browse filesFiles changed (5)
- kohonen_learning_system.py+335-87
- smoke_test_v65_v2_metrics_fix.pyAdded+320
- som_metrics.pyAdded+811
- train_v6_5_v2.py+593-118
- xeon_runtime.pyAdded+581
1963 unmodified lines196419651966196719681969155 unmodified lines2125212621272128212921301 unmodified line21322133213421352136213743 unmodified lines2181218221832184218521864 unmodified lines2191219221932194219521962197219821992200220122022203220422052206220722082209221022112 unmodified lines2214221522162217221822191 unmodified line22212222222322242225222622 unmodified lines2249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230493 unmodified lines23982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429223 unmodified lines2653265426552656265726586 unmodified lines2665266626671963 unmodified linesself._adaptation_log: List[Dict[str, Any]] = []self._last_adaptation_step = 0def _init_hypothesis_ensemble(self):"""Cria o ensemble de geradores + otimizador Adam."""input_dim = self.som_neuron_count # ativação SOM flatten (864)155 unmodified lines"punishment_rate": float(rate),}self._adaptation_log.append(record)self._last_adaptation_step += 1return record1 unmodified line"""Retorna o log de adaptações dinâmicas (para monitoramento)."""return list(self._adaptation_log)# ==================================================================# 2.1 Treinamento dos geradores (train_hypotheses)# ==================================================================43 unmodified linesself.hypothesis_ensemble.train()losses = []for step in range(self.hyp_train_steps):self.hyp_optimizer.zero_grad()4 unmodified linesdeltas_stack = self.hypothesis_ensemble.forward_stacked(x_mean)deltas_stack = self.delta_scale * deltas_stack # escala# Avalia cada delta: computa loss de classificaçãoif self.classifier is not None and self.classifier_trained:loss_per_hyp = []for h in range(self.n_hypotheses):delta_h = deltas_stack[0, h] # (P,)som_temp = som_weights_flat + delta_hsom_temp_reshaped = som_temp.view_as(self.som.weights)loss_h = self._compute_classification_loss_with_som(som_temp_reshaped, data, labels)loss_per_hyp.append(loss_h)loss_total = torch.stack(loss_per_hyp).mean()# Regularização L2 sobre os deltas (evita deltas grandes)reg_loss = 0.01 * deltas_stack.norm()loss_total = loss_total + reg_losselse:# Fallback: minimizar norma do delta (regulariza��ão pura)loss_total = deltas_stack.norm()2 unmodified linesself.hyp_optimizer.step()losses.append(float(loss_total.item()))# Atualiza a escala de delta (decai suavemente)with torch.no_grad():self.delta_scale.data = torch.clamp(1 unmodified line)self.hypothesis_ensemble.eval()# V6.5-V2-dynamic — registra loss_final no históricoloss_final_val = float(losses[-1]) if losses else 0.022 unmodified linesdef _compute_classification_loss_with_som(self, som_weights: torch.Tensor, data: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:"""Computa a perda de classificação usando um SOM temporário.Substitui temporariamente self.som.weights pelo som_weights fornecido,computa a loss, e restaura o SOM original. Usa detach no SOM temporáriopara evitar retropropagação através dos pesos do SOM (apenas os deltasdos geradores recebem gradiente)."""# Guarda o SOM originaloriginal_weights = self.som.weights# Substitui temporariamente (sem clone — som_weights já é um tensor# que carrega gradiente dos deltas)self.som.weights = som_weightstry:if self.classifier is not None and self.classifier_trained:# Computa ativações SOM (sem treinar SOM/embedding)with torch.no_grad():# Para permitir gradiente fluir pelos deltas, precisamos# das ativações SOM como função diferenciável de som_weights# Reimplementamos _som_activation com gradientedata_expanded = data.unsqueeze(0).unsqueeze(0).unsqueeze(0).unsqueeze(0)# (1, 1, 1, 1, N, 4) — para broadcast com (I, J, K, L, 4)# Mas self.som.weights é (I, J, K, L, 4) e data é (N, 4)# dist[i,j,k,l,n] = ||W[i,j,k,l] - data[n]||²# reshape: W (I*J*K*L, 4), data (N, 4) → dist (I*J*K*L, N)W_flat = som_weights.reshape(-1, 4) # (P_neurons, 4)# W_flat.requires_grad_(True) # já tem gradiente dos deltasdist = torch.cdist(W_flat, data) # (P_neurons, N)activations = dist.t() # (N, P_neurons)# Passa pelo classifierlogits = self.classifier(activations) # (N,)loss = F.binary_cross_entropy_with_logits(logits, labels)return losselse:# Fallback: votação BMU (não-diferenciável — usa heurística)with torch.no_grad():correct = 0for i in range(len(data)):bmu = self.som.find_bmu(data[i])pred = self.neuron_label.get(bmu, 0.5) if hasattr(self, "neuron_label") else 0.5if (pred > 0.5) == (labels[i].item() > 0.5):correct += 1return torch.tensor(1.0 - correct / max(1, len(data)),device=data.device,dtype=torch.float,)finally:# Restaura o SOM originalself.som.weights = original_weights# ==================================================================# 2.2 Seleção do melhor delta (3 tentativas × 16 hipóteses)93 unmodified linesdef _evaluate_accuracy_with_som(self, som_weights: torch.Tensor, data: torch.Tensor, labels: torch.Tensor) -> float:"""Calcula acurácia com um SOM temporário (sem modificar o original)."""original_weights = self.som.weightsself.som.weights = som_weightstry:if self.classifier is not None and self.classifier_trained:with torch.no_grad():activations = torch.stack([self._som_activation(data[i]) for i in range(len(data))])logits = self.classifier(activations)preds = (logits > 0.5).float()acc = (preds == labels).float().mean().item()else:# Votação BMUif not hasattr(self, "neuron_label"):self._label_neurons()correct = 0for i in range(len(data)):bmu = self.som.find_bmu(data[i])pred = self.neuron_label.get(bmu, 0.5)if (pred > 0.5) == (labels[i].item() > 0.5):correct += 1acc = correct / max(1, len(data))return float(acc)finally:self.som.weights = original_weights# ==================================================================# 2.3 Aplicação do melhor delta + consolidação via EWC223 unmodified lines},}__all__ = ["SimpleBBPETokenizer",6 unmodified lines"HypothesisEnsemble","KohonenLearningSystemV2",]1963 unmodified lines19641965196619671968196919701971197219731974155 unmodified lines21302131213221332134213521362137213821391 unmodified line214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223143 unmodified lines227522762277227822792280228122822283228422854 unmodified lines229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452 unmodified lines2348234923502351235223532354235523562357235823591 unmodified line236123622363236423652366236723682369237022 unmodified lines2393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247293 unmodified lines25662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612223 unmodified lines2836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329046 unmodified lines291129122913291429151963 unmodified linesself._adaptation_log: List[Dict[str, Any]] = []self._last_adaptation_step = 0# V6.5-V2-metrics — histórico de métricas SOM (QE, TE, KL, VE, Dead Neurons)# para detecção de Estagnação do QE e Cruzamento de Vizinhança.from bigru_t.model.som_metrics import SOMMetricHistoryself._som_metric_history: SOMMetricHistory = SOMMetricHistory()def _init_hypothesis_ensemble(self):"""Cria o ensemble de geradores + otimizador Adam."""input_dim = self.som_neuron_count # ativação SOM flatten (864)155 unmodified lines"punishment_rate": float(rate),}self._adaptation_log.append(record)# V6.5-V2-metrics-FIX: limita crescimento do log (era ilimitado, causando# crescimento de memória em treino longo). Mantém últimas 50 entradas.if len(self._adaptation_log) > 50:self._adaptation_log = self._adaptation_log[-50:]self._last_adaptation_step += 1return record1 unmodified line"""Retorna o log de adaptações dinâmicas (para monitoramento)."""return list(self._adaptation_log)# ==================================================================# V6.5-V2-metrics-FIX — Limpeza agressiva de memória RAM# ==================================================================# User requirement: "analisar e aprimorar (logicamente e matematicamente)# no projeto limpeza de memória RAM e de Armazenamento (ao concluir)".## Mathematical analysis:# A memória RAM consumida pelo KLS V2 tem 4 fontes principais:# 1. Pesos do SOM: I*J*K*L*4 floats = 864*4 = 3456 floats (~14KB)# → FIXO (não pode ser limpo sem destruir o modelo)# 2. HypothesisEnsemble: max_n_hypotheses * DeltaGenerator params# = 32 * (864*256 + 256*256 + 256*3456) = 32 * 1.16M = ~37M params# → ~148MB em float32. Os OTIMIZADORAS Adam guardam 2x esse valor# (momentum + variance) = ~296MB adicionais.# 3. HypothesisClassifier: 864*512 + 512*256 + ... = ~616K params (~2.5MB)# 4. buffer_4d: até MAX_BUFFER_SIZE amostras * 4 floats = ~4KB (mínimo)# MAS os tensores carregam gradiente do embedding se não forem detached.## A limpeza agressiva atua em:# - Zera gradientes acumulados nos otimizadores (Adam state)# - Chama gc.collect() para liberar ciclos Python# - Libera caches internos do PyTorch (oneDNN primitive cache)# - Trunca listas de histórico que crescem com o treino# ------------------------------------------------------------------def aggressive_cleanup(self) -> Dict[str, Any]:"""V6.5-V2-metrics-FIX — Limpeza agressiva de memória RAM do KLS.Retorna métricas antes/depois para confirmação. NÃO destroi pesos doSOM nem do classifier — apenas libera caches e gradientes acumulados.Returns:Dict com rss_before/after_mb, n_refs_collected, buffers_trimmed."""import gctry:import resourcerss_before = float(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss) / 1024.0except Exception:rss_before = 0.0# 1. Zera gradientes do otimizador Adam (libera momentum/variance state)try:if hasattr(self, "hyp_optimizer"):self.hyp_optimizer.zero_grad(set_to_none=True)except Exception:pass# 2. Trunca históricos que crescem com o treinoif len(self._adaptation_log) > 20:self._adaptation_log = self._adaptation_log[-20:]if len(self.inference_punishment_history) > 50:self.inference_punishment_history = self.inference_punishment_history[-50:]if len(self.vqvae2_metrics_history) > 30:self.vqvae2_metrics_history = self.vqvae2_metrics_history[-30:]if len(self.w8a8_metrics_history) > 30:self.w8a8_metrics_history = self.w8a8_metrics_history[-30:]# 3. gc.collect() em 2 passes (gerações 0+1 e 2)n_collected_0 = gc.collect(0)n_collected_1 = gc.collect(1)n_collected_2 = gc.collect(2)# 4. Libera caches CPU do PyTorch (oneDNN/MKL)try:import torchif hasattr(torch, "cuda") and torch.cuda.is_available():torch.cuda.empty_cache()except Exception:passtry:import resourcerss_after = float(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss) / 1024.0except Exception:rss_after = 0.0return {"rss_before_mb": float(rss_before),"rss_after_mb": float(rss_after),"freed_mb": max(0.0, rss_before - rss_after),"gc_collected": int(n_collected_0 + n_collected_1 + n_collected_2),"adaptation_log_trimmed": int(len(self._adaptation_log)),"timestamp": __import__("datetime").datetime.utcnow().isoformat() + "Z",}# ==================================================================# 2.1 Treinamento dos geradores (train_hypotheses)# ==================================================================43 unmodified linesself.hypothesis_ensemble.train()losses = []# V6.5-V2-metrics-FIX: pré-computa data_norm_sq uma única vez (N, 1)# para reuso em todos os steps — evita recomputação redundante.data_norm_sq = (data * data).sum(dim=-1, keepdim=True).t() # (1, N)labels_expanded = labels # (N,)for step in range(self.hyp_train_steps):self.hyp_optimizer.zero_grad()4 unmodified linesdeltas_stack = self.hypothesis_ensemble.forward_stacked(x_mean)deltas_stack = self.delta_scale * deltas_stack # escala# V6.5-V2-metrics-FIX: Avaliação VETORIZADA de todas as hipóteses# em paralelo (substitui loop que materializava 16 cópias do SOM).# Memória: (n_hyp, P, N) em vez de 16 * (P + 2*P*N).if self.classifier is not None and self.classifier_trained:# deltas_stack: (1, n_hyp, P) → (n_hyp, P, 4) reshapen_hyp = self.n_hypothesesP_neurons = self.som_neuron_count# som_weights_flat: (P, 4) detachedW_base = som_weights_flat.reshape(P_neurons, 4) # (P, 4)# delta_h: (n_hyp, P) → reshape para (n_hyp, P, 4)deltas_3d = deltas_stack[0].reshape(n_hyp, P_neurons, 4) # (n_hyp, P, 4)# W_new[h, p, d] = W_base[p, d] + deltas_3d[h, p, d]W_new = W_base.unsqueeze(0) + deltas_3d # (n_hyp, P, 4) — broadcast# dist²[h, p, n] = ||W_new[h, p] - data[n]||²# = ||W_new[h, p]||² + ||data[n]||² - 2*W_new[h, p]·data[n]W_new_norm_sq = (W_new * W_new).sum(dim=-1) # (n_hyp, P)# cross[h, p, n] = W_new[h, p] · data[n]cross = torch.matmul(W_new, data.t()) # (n_hyp, P, N)dist_sq = (W_new_norm_sq.unsqueeze(-1) # (n_hyp, P, 1)+ data_norm_sq # (1, N) → broadcast (n_hyp, P, N)- 2.0 * cross) # (n_hyp, P, N)dist_sq = torch.clamp(dist_sq, min=0.0)# activations[h, n, p] = dist_sq[h, p, n]activations = dist_sq.transpose(1, 2) # (n_hyp, N, P)# Classifier forward (congelado)classifier_params_were_grad = [p.requires_grad for p in self.classifier.parameters()]for p in self.classifier.parameters():p.requires_grad_(False)try:logits = self.classifier(activations.reshape(n_hyp * len(data), P_neurons)).reshape(n_hyp, len(data)) # (n_hyp, N)# BCE por hipótese, depois médialoss_per_hyp = F.binary_cross_entropy_with_logits(logits,labels_expanded.unsqueeze(0).expand(n_hyp, -1),reduction='none',).mean(dim=1) # (n_hyp,)loss_total = loss_per_hyp.mean()# Regularização L2 sobre os deltasreg_loss = 0.01 * deltas_stack.norm()loss_total = loss_total + reg_lossfinally:for p, was_grad in zip(self.classifier.parameters(),classifier_params_were_grad):p.requires_grad_(was_grad)else:# Fallback: minimizar norma do delta (regulariza��ão pura)loss_total = deltas_stack.norm()2 unmodified linesself.hyp_optimizer.step()losses.append(float(loss_total.item()))# V6.5-V2-metrics-FIX: libera tensores intermediários explicitamente# para reduzir pico de memória entre steps.del loss_total, deltas_stackif 'W_new' in dir():del W_new, cross, dist_sq, activations# Atualiza a escala de delta (decai suavemente)with torch.no_grad():self.delta_scale.data = torch.clamp(1 unmodified line)self.hypothesis_ensemble.eval()# V6.5-V2-metrics-FIX: libera som_activations e som_weights_flatdel som_activations, som_weights_flat, data, data_norm_sqimport gcgc.collect()# V6.5-V2-dynamic — registra loss_final no históricoloss_final_val = float(losses[-1]) if losses else 0.022 unmodified linesdef _compute_classification_loss_with_som(self, som_weights: torch.Tensor, data: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:"""V6.5-V2-metrics-FIX — Computa perda de classificação com SOM temporário.BUG CORRIGIDO (V6.5-V2-metrics-FIX):A versão anterior envolvia toda a computação em `torch.no_grad()`,o que matava o gradiente que deveria fluir dos deltas → SOM → loss.Resultado: train_hypotheses() não treinava os geradores de fato.CORREÇÃO: A computação das ativações SOM (squared distances) éfeita SEM no_grad, permitindo que o gradiente flua dos deltas(que pertencem ao HypothesisEnsemble) através do SOM temporárioaté a loss. Apenas o classifier é congelado (requires_grad=False)para que seu gradiente não seja atualizado por train_hypotheses.Mathematical formulation (squared Euclidean distance, consistente com_som_activation que usa ||W - x||^2, não ||W - x||):Para cada neurônio p e amostra n:dist²[p, n] = ||W[p] - x[n]||²= ||W[p]||² + ||x[n]||² - 2·W[p]·x[n]activations = dist².t() → (N, P_neurons)logits = classifier(activations) → (N,)loss = BCEWithLogitsLoss(logits, labels)Args:som_weights: tensor (I, J, K, L, 4) com gradiente (dos deltas).data: tensor (N, 4) — amostras 4D (detached).labels: tensor (N,) — rótulos binários.Returns:Scalar loss tensor (com gradiente fluindo para som_weights)."""if self.classifier is not None and self.classifier_trained:# NÃO usa torch.no_grad() — gradiente deve fluir dos deltas# através do SOM temporário até a loss.W_flat = som_weights.reshape(-1, 4) # (P_neurons, 4)# Identidade algébrica: ||W - x||^2 = ||W||^2 + ||x||^2 - 2*W·x# Evita materializar tensor (P, N, 4) — usa (P, N) direto.W_norm_sq = (W_flat * W_flat).sum(dim=-1, keepdim=True) # (P, 1)data_norm_sq = (data * data).sum(dim=-1, keepdim=True).t() # (1, N)cross = W_flat @ data.t() # (P, N) — matmul eficientedist_sq = W_norm_sq + data_norm_sq - 2.0 * cross # (P, N)dist_sq = torch.clamp(dist_sq, min=0.0) # estabilidade numéricaactivations = dist_sq.t() # (N, P_neurons) — gradiente fluindo!# Congela classifier durante train_hypotheses (não queremos# atualizar seus pesos — apenas os deltas dos geradores)classifier_params_were_grad = [p.requires_grad for p in self.classifier.parameters()]for p in self.classifier.parameters():p.requires_grad_(False)try:logits = self.classifier(activations) # (N,)loss = F.binary_cross_entropy_with_logits(logits, labels)finally:# Restaura requires_grad do classifierfor p, was_grad in zip(self.classifier.parameters(),classifier_params_were_grad):p.requires_grad_(was_grad)return losselse:# Fallback: votação BMU (não-diferenciável)with torch.no_grad():if not hasattr(self, "neuron_label"):self._label_neurons()correct = 0for i in range(len(data)):bmu = self.som.find_bmu(data[i])pred = self.neuron_label.get(bmu, 0.5)if (pred > 0.5) == (labels[i].item() > 0.5):correct += 1return torch.tensor(1.0 - correct / max(1, len(data)),device=data.device,dtype=torch.float,)# ==================================================================# 2.2 Seleção do melhor delta (3 tentativas × 16 hipóteses)93 unmodified linesdef _evaluate_accuracy_with_som(self, som_weights: torch.Tensor, data: torch.Tensor, labels: torch.Tensor) -> float:"""V6.5-V2-metrics-FIX — Calcula acurácia com SOM temporário (vetorizado).Substitui o loop que chamava _som_activation(data[i]) para cada amostrapor uma única operação matmul. Reduz tempo de O(N*P) para O(P*N) mascom paralelismo SIMD (single matmul vs N python iterations).Para o fallback (votação BMU), ainda precisa trocar self.som.weightstemporariamente pois find_bmu lê self.som.weights diretamente."""if self.classifier is not None and self.classifier_trained:with torch.no_grad():# Vetorizado: dist²[p, n] = ||W[p]||² + ||x[n]||² - 2*W[p]·x[n]W_flat = som_weights.reshape(-1, 4) # (P, 4)W_norm_sq = (W_flat * W_flat).sum(dim=-1, keepdim=True) # (P, 1)data_norm_sq = (data * data).sum(dim=-1, keepdim=True).t() # (1, N)cross = W_flat @ data.t() # (P, N)dist_sq = W_norm_sq + data_norm_sq - 2.0 * cross # (P, N)dist_sq = torch.clamp(dist_sq, min=0.0)activations = dist_sq.t() # (N, P)logits = self.classifier(activations) # (N,)preds = (logits > 0.5).float()acc = (preds == labels).float().mean().item()return float(acc)else:# Fallback: votação BMU — precisa trocar self.som.weightsoriginal_weights = self.som.weightsself.som.weights = som_weightstry:with torch.no_grad():if not hasattr(self, "neuron_label"):self._label_neurons()correct = 0for i in range(len(data)):bmu = self.som.find_bmu(data[i])pred = self.neuron_label.get(bmu, 0.5)if (pred > 0.5) == (labels[i].item() > 0.5):correct += 1acc = correct / max(1, len(data))return float(acc)finally:self.som.weights = original_weights# ==================================================================# 2.3 Aplicação do melhor delta + consolidação via EWC223 unmodified lines},}# ==================================================================# V6.5-V2-metrics — Integração das métricas SOM canônicas# (QE, TE, Kaski-Lagus, Variância Explicada, Dead Neurons,# Colapso Topológico, Estagnação QE, Cruzamento Vizinhança)# ==================================================================def compute_som_metrics(self) -> Dict[str, Any]:"""V6.5-V2-metrics — Computa todas as métricas SOM canônicas.User requirement: "ANALISAR matematicamente e logicamente e inserirmelhorias para os scripts das métricas de aprendizado e indicadoresde falha em Mapas Auto-Organizáveis (SOM / Redes de Kohonen)avaliam a fidelidade de representação dos dados e a preservação davizinhança topológica".Returns:Dict com 8 métricas:1. quantization_error (QE)2. topological_error (TE)3. kaski_lagus_error (KL)4. explained_variance_share (VE)5. topological_collapse (dict)6. dead_neuron_rate (dict)7. qe_stagnation (dict) — requer histórico8. neighborhood_crossing (dict) — requer históricoPlus: overall_health, failure_indicators"""from bigru_t.model.som_metrics import compute_all_metricsif not self.buffer_4d:return {"quantization_error": 0.0,"topological_error": 0.0,"kaski_lagus_error": 0.0,"explained_variance_share": 0.0,"topological_collapse": {"severity": "none", "effective_rank": 0.0},"dead_neuron_rate": {"dead_neuron_rate": 1.0, "n_dead": self.som_neuron_count,"n_active": 0, "n_total": self.som_neuron_count},"qe_stagnation": {"is_stagnant": False, "severity": "none"},"neighborhood_crossing": {"detected": False, "severity": "none"},"overall_health": "unknown","failure_indicators": ["no_buffer_data"],"n_failure_indicators": 1,"note": "buffer_4d vazio — métricas indisponíveis",}# Stack buffer em tensor (N, 4)data = torch.stack([v.detach().clone() if isinstance(v, torch.Tensor) else torch.tensor(v, dtype=torch.float)for v in self.buffer_4d]).float()weights = self.som.weights.detach()metrics = compute_all_metrics(data, weights, self._som_metric_history)# Registra no históricoself._som_metric_history.record(metrics)return metricsdef get_som_metric_history(self) -> Dict[str, Any]:"""Retorna histórico de métricas SOM (para análise temporal)."""return self._som_metric_history.to_dict()def reset_som_metric_history(self) -> None:"""Reseta o histórico de métricas SOM (início de nova fase)."""from bigru_t.model.som_metrics import SOMMetricHistoryself._som_metric_history = SOMMetricHistory()__all__ = ["SimpleBBPETokenizer",6 unmodified lines"HypothesisEnsemble","KohonenLearningSystemV2",]# V6.5-V2-metrics: som_metrics é importado lazy (dentro de compute_som_metrics)# para evitar dependência circular e permitir uso standalone.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320"""smoke_test_v65_v2_metrics_fix.py — Validação rápida das correções V6.5-V2-metrics-FIX.
Verifica:1. Importação do KohonenLearningSystemV2 com params restaurados (HIDDEN=1024, VOCAB=16384)2. Bug fix do _compute_classification_loss_with_som (gradiente flui)3. Vetorização do train_hypotheses (sem OOM)4. aggressive_cleanup() funciona5. SOM metrics (8 métricas) computam sem erro6. predict() retorna labels dinâmicos (não hardcoded)7. FASE1 + FASE2 logic (enable_punishment=False/True)"""from __future__ import annotations
import osimport sysimport timeimport tracebackfrom pathlib import Path
# Setup pathsPROJECT_ROOT = Path("/home/z/my-project")BIGRU_ROOT = PROJECT_ROOT / "BiGRU_T_version"SRC_ROOT = BIGRU_ROOT / "src"sys.path.insert(0, str(SRC_ROOT))
# Activate xeon_runtimeos.environ["V65_ENABLE_STREAMING"] = "1"
print("=" * 80)print("V6.5-V2-metrics-FIX SMOKE TEST")print("=" * 80)print()
# Test 1: Importprint("[Test 1] Import KohonenLearningSystemV2...")try: from bigru_t.model.kohonen_learning_system import ( KohonenLearningSystemV2, KohonenLearningSystem, KohonenSOM4D, HypothesisClassifier, HypothesisEnsemble, DeltaGenerator, SimpleBBPETokenizer, text_to_4d_vector, ) from bigru_t.model.som_metrics import ( SOMMetricHistory, compute_all_metrics, quantization_error, topological_error, kaski_lagus_error, explained_variance_share, topological_collapse, dead_neuron_rate, ) print(" PASS: All imports successful")except Exception as e: print(f" FAIL: Import error: {e}") traceback.print_exc() sys.exit(1)
# Test 2: Instantiate with restored (larger) parametersprint("\n[Test 2] Instantiate KLS V2 with restored params (HIDDEN=1024, VOCAB=16384)...")try: # Use smaller grid for smoke test (faster), but full HIDDEN_DIM/VOCAB_SIZE kls = KohonenLearningSystemV2( vocab_size=16384, # restored hidden_dim=1024, # restored seq_len=8, som_grid=(6, 6, 6, 4), # 864 neurons (Kohonen architecture preserved) 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, enable_vqvae2=False, # disabled to save RAM enable_reasoning=False, # disabled to save RAM enable_w8a8=False, # disabled to save RAM enable_attention=True, attention_n_heads=8, # V2-dynamic restored params n_hypotheses=16, # restored max_n_hypotheses=32, # restored min_n_hypotheses=4, n_trials=3, min_n_trials=1, max_n_trials=6, hyp_train_steps=30, # restored min_hyp_train_steps=10, max_hyp_train_steps=80, hyp_lr=1e-4, hyp_hidden_dim=256, # restored loss_history_window=8, punishment_window=12, ) assert kls.hidden_dim == 1024, f"hidden_dim={kls.hidden_dim}" assert kls.tokenizer.vocab_size == 16384, f"vocab={kls.tokenizer.vocab_size}" assert kls.n_hypotheses == 16, f"n_hyp={kls.n_hypotheses}" assert kls.max_n_hypotheses == 32, f"max_n_hyp={kls.max_n_hypotheses}" assert kls.hyp_train_steps == 30, f"hyp_steps={kls.hyp_train_steps}" assert kls.hyp_hidden_dim == 256, f"hyp_hidden={kls.hyp_hidden_dim}" assert hasattr(kls, "aggressive_cleanup"), "no aggressive_cleanup method" print(f" PASS: KLS V2 instantiated") print(f" hidden_dim={kls.hidden_dim}, vocab={kls.tokenizer.vocab_size}") print(f" n_hypotheses={kls.n_hypotheses}/{kls.max_n_hypotheses}") print(f" hyp_train_steps={kls.hyp_train_steps}, hyp_hidden_dim={kls.hyp_hidden_dim}") print(f" som_grid={kls.som_grid} ({kls.som_neuron_count} neurons)") print(f" has aggressive_cleanup: True")except Exception as e: print(f" FAIL: Instantiation error: {e}") traceback.print_exc() sys.exit(1)
# Test 3: Add data + train SOM (CONHECIMENTO phase)print("\n[Test 3] Add data + train SOM (CONHECIMENTO phase)...")try: kls.tokenizer.fit([ "o gato dorme", "a casa eh azul", "ele corre rapido", "ela canta uma musica", "o sol nasceu", "nos vamos viajar", "luva de pedreiro tavila", "lula reserva valor", "amazonas forca tarefa vitimas", ]) # Add 30 samples (more than N_start=10) for i in range(3): kls.add_data( ["o gato dorme", "o cachorro corre", "a menina brinca", "o passaro voa", "o peixe nada", "a arvore cresce", "o livro esta na mesa", "a musica toca", "o tempo passa", "o mundo gira"], [0, 1, 0, 1, 0, 1, 0, 1, 0, 1], label_strings={0: "negative_class", 1: "positive_class"}, dataset_name="test_ds", ) assert len(kls.buffer_4d) >= 10, f"buffer={len(kls.buffer_4d)}" print(f" PASS: Added {len(kls.buffer_4d)} samples") # Train SOM started = kls.check_training_start() print(f" training_ready: {kls.training_ready}") if kls.training_ready: kls.train_som_on_buffer() kls._label_neurons() print(f" SOM trained, weights norm={kls.som.weights.norm().item():.4f}")except Exception as e: print(f" FAIL: {e}") traceback.print_exc() sys.exit(1)
# Test 4: predict() returns dynamic labels (not gato/cachorro)print("\n[Test 4] predict() returns dynamic labels...")try: pred = kls.predict("o gato dorme", dataset_name="test_ds") assert pred in ["negative_class", "positive_class"], f"pred={pred}" assert pred != "gato" and pred != "cachorro", f"hardcoded: {pred}" print(f" PASS: predict returned '{pred}' (dynamic, not hardcoded)")except Exception as e: print(f" FAIL: {e}") traceback.print_exc() sys.exit(1)
# Test 5: activate_hypothesis (trains classifier)print("\n[Test 5] activate_hypothesis (train classifier)...")try: kls.activate_hypothesis() assert kls.classifier_trained, "classifier not trained" print(f" PASS: Classifier trained ({kls.classifier is not None})")except Exception as e: print(f" FAIL: {e}") traceback.print_exc() sys.exit(1)
# Test 6: train_hypotheses (memory-efficient vectorized version)print("\n[Test 6] train_hypotheses (memory-efficient vectorized)...")try: t0 = time.time() result = kls.train_hypotheses() elapsed_ms = (time.time() - t0) * 1000 assert result["active"], f"not active: {result}" assert result["n_steps"] == 30, f"n_steps={result['n_steps']}" print(f" PASS: train_hypotheses completed in {elapsed_ms:.0f}ms") print(f" n_steps={result['n_steps']}, n_hypotheses={result['n_hypotheses']}") print(f" loss_initial={result['loss_initial']:.4f}, loss_final={result['loss_final']:.4f}") print(f" delta_scale_final={result['delta_scale_final']:.6f}") if "adaptation" in result: adapt = result["adaptation"] print(f" adaptation: adapted={adapt['adapted']}, rules={adapt['rules_fired']}")except Exception as e: print(f" FAIL: {e}") traceback.print_exc() sys.exit(1)
# Test 7: SOM metrics (8 canonical metrics)print("\n[Test 7] SOM metrics (8 canonical)...")try: metrics = kls.compute_som_metrics() assert "quantization_error" in metrics assert "topological_error" in metrics assert "kaski_lagus_error" in metrics assert "explained_variance_share" in metrics assert "topological_collapse" in metrics assert "dead_neuron_rate" in metrics assert "qe_stagnation" in metrics assert "neighborhood_crossing" in metrics assert "overall_health" in metrics print(f" PASS: All 8 SOM metrics computed") print(f" QE={metrics['quantization_error']:.4f}") print(f" TE={metrics['topological_error']:.4f}") print(f" KL={metrics['kaski_lagus_error']:.4f}") print(f" VE={metrics['explained_variance_share']:.4f}") print(f" dead_neuron_rate={metrics['dead_neuron_rate'].get('dead_neuron_rate', 0):.3f}") print(f" collapse_severity={metrics['topological_collapse'].get('severity', '?')}") print(f" overall_health={metrics['overall_health']}") print(f" n_failure_indicators={metrics['n_failure_indicators']}")except Exception as e: print(f" FAIL: {e}") traceback.print_exc() sys.exit(1)
# Test 8: select_best_delta (vectorized)print("\n[Test 8] select_best_delta (3 trials × 16 hypotheses)...")try: t0 = time.time() best_delta, best_acc, info = kls.select_best_delta() elapsed_ms = (time.time() - t0) * 1000 assert info["active"], f"not active: {info}" assert info["n_trials"] == 3, f"n_trials={info['n_trials']}" assert info["n_hypotheses"] == 16, f"n_hyp={info['n_hypotheses']}" print(f" PASS: select_best_delta completed in {elapsed_ms:.0f}ms") print(f" best_acc={best_acc:.4f}") print(f" delta_norm={info['delta_norm']:.4f}") print(f" n_trials={info['n_trials']}, n_hypotheses={info['n_hypotheses']}")except Exception as e: print(f" FAIL: {e}") traceback.print_exc() sys.exit(1)
# Test 9: process_batch_v2 (CONHECIMENTO + PUNIÇÃO)print("\n[Test 9] process_batch_v2 (CONHECIMENTO + PUNIÇÃO)...")try: # CONHECIMENTO result_conh = kls.process_batch_v2( ["o gato dorme", "o cachorro corre"], [0, 1], label_strings={0: "negative_class", 1: "positive_class"}, dataset_name="test_ds", enable_punishment=False, ) assert result_conh["phase"] == "CONHECIMENTO" print(f" PASS: CONHECIMENTO phase works: {result_conh['phase']}")
# PUNIÇÃO result_pun = kls.process_batch_v2( ["o gato dorme", "o cachorro corre"], [0, 1], label_strings={0: "negative_class", 1: "positive_class"}, dataset_name="test_ds", enable_punishment=True, ) assert result_pun["phase"] == "PUNICAO" print(f" PASS: PUNIÇÃO phase works: {result_pun['phase']}") print(f" action: {result_pun.get('action', 'none')}")except Exception as e: print(f" FAIL: {e}") traceback.print_exc() sys.exit(1)
# Test 10: aggressive_cleanupprint("\n[Test 10] aggressive_cleanup()...")try: cleanup_result = kls.aggressive_cleanup() assert "rss_before_mb" in cleanup_result assert "rss_after_mb" in cleanup_result assert "gc_collected" in cleanup_result print(f" PASS: aggressive_cleanup() called") print(f" rss_before={cleanup_result['rss_before_mb']:.1f}MB") print(f" rss_after={cleanup_result['rss_after_mb']:.1f}MB") print(f" freed={cleanup_result['freed_mb']:.1f}MB") print(f" gc_collected={cleanup_result['gc_collected']}")except Exception as e: print(f" FAIL: {e}") traceback.print_exc() sys.exit(1)
# Test 11: get_v2_metricsprint("\n[Test 11] get_v2_metrics()...")try: v2_metrics = kls.get_v2_metrics() assert v2_metrics["version"] == "V2-dynamic" assert v2_metrics["n_hypotheses"] == 16 print(f" PASS: get_v2_metrics() works") print(f" version={v2_metrics['version']}") print(f" n_hypotheses={v2_metrics['n_hypotheses']}") print(f" n_trials={v2_metrics['n_trials']}") print(f" hyp_train_steps={v2_metrics['hyp_train_steps']}") print(f" buffer_size={v2_metrics['buffer_size']}") if "dynamic_adaptation" in v2_metrics: da = v2_metrics["dynamic_adaptation"] print(f" n_adaptations={da['n_adaptations']}") print(f" loss_stats: slope={da['loss_stats']['slope']:.6f}, vol={da['loss_stats']['volatility']:.3f}")except Exception as e: print(f" FAIL: {e}") traceback.print_exc() sys.exit(1)
# Summaryprint("\n" + "=" * 80)print("SMOKE TEST SUMMARY")print("=" * 80)print(" ALL TESTS PASSED")print(" - KLS V2 with restored params (HIDDEN=1024, VOCAB=16384) ✓")print(" - Memory-efficient train_hypotheses (vectorized) ✓")print(" - Bug fix: gradient flows through deltas → SOM → loss ✓")print(" - 8 SOM canonical metrics computed ✓")print(" - Dynamic labels (no hardcoded gato/cachorro) ✓")print(" - CONHECIMENTO + PUNIÇÃO phases ✓")print(" - aggressive_cleanup() works ✓")print("=" * 80)sys.exit(0)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811"""som_metrics.py — V6.5-V2-metrics: Métricas de aprendizado e indicadores defalha para Mapas Auto-Organizáveis (SOM / Redes de Kohonen).
============================================================================MÉTRICAS PRINCIPAIS DE APRENDIZADO============================================================================
1.1. Erro de Quantização (Quantization Error - QE) Média das distâncias euclidianas entre cada vetor de entrada e o vetor de pesos de seu neurônio vencedor (BMU). Mede a resolução ou ajuste fino do mapa aos dados.
QE = (1/N) * Σ_i ||x_i - W_BMU(x_i)||₂
1.2. Erro Topológico (Topological Error - TE) Percentual de vetores de entrada cujos primeiro e segundo neurônios mais próximos (BMU e segunda BMU) NÃO são vizinhos diretos na grade de saída. Avalia preservação das relações geométricas.
TE = (1/N) * Σ_i 𝟙[¬adjacent(BMU_1(x_i), BMU_2(x_i))]
1.3. Erro de Kaski-Lagus Combinação ponderada que penaliza tanto a falta de resolução do vetor de quantização quanto as quebras na continuidade topológica.
KL = α * QE_norm + β * TE onde α=0.5, β=0.5 (pesos padrão)
Variante implementada: KL = QE * (1 + TE) (penaliza QE quando TE é alto)
1.4. Variância Explicada (Share of Explained Variance) Fração da variabilidade total dos dados de entrada que é mapeada e representada pelos vetores de referência (pesos) dos nós da rede.
VarExplained = 1 - Var(residual) / Var(total) onde residual = x_i - W_BMU(x_i)
============================================================================INDICADORES DE NÃO APRENDIZADO OU FALHA============================================================================
2.1. Colapso Topológico (Topological Collapse) Ocorre quando todos os vetores de peso convergem para o mesmo ponto ou para uma linha reta. Indica perda total da dimensionalidade útil.
Detecção: - std(weights) por dimensão < threshold (colapso total) - rank(weights reshaped) < 2 (todos num ponto) - rank < 3 (todos numa linha)
2.2. Taxa de Neurônios Mortos (Dead Neurons) Percentual de neurônios que NUNCA se tornam BMU para nenhum vetor.
DeadRate = (n_neurons - n_active_neurons) / n_neurons
Threshold: DeadRate > 0.5 indica problema.
2.3. Estagnação do Erro de Quantização QE estabiliza em patamar elevado ao longo das épocas. A taxa de aprendizado decaiu rápido demais antes da fase de ordenação global.
Detecção: slope(QE) ≈ 0 E QE atual > 0.7 * max(QE histórico)
2.4. Cruzamento de Vizinhança (Neighborhood Crossing) Crescimento repentino ou oscilação crônica do TE nas épocas finais.
Detecção: - std(TE_final_5_epochs) > 2 * std(TE_initial_5_epochs) (oscilação) - TE[-1] > TE[-5] (crescimento no final)
============================================================================AUTOR: V6.5-V2-metrics============================================================================"""from __future__ import annotations
import mathimport loggingfrom collections import defaultdict, dequefrom dataclasses import dataclass, fieldfrom typing import Any, Dict, List, Optional, Tuple
import torchimport torch.nn.functional as F
logger = logging.getLogger(__name__)
# ============================================================================# Dataclass para armazenar histórico de métricas# ============================================================================@dataclassclass SOMMetricHistory: """Histórico deslizante de métricas SOM para detecção de estagnação e cruzamento de vizinhança.""" qe_history: deque = field(default_factory=lambda: deque(maxlen=50)) te_history: deque = field(default_factory=lambda: deque(maxlen=50)) kl_history: deque = field(default_factory=lambda: deque(maxlen=50)) var_explained_history: deque = field(default_factory=lambda: deque(maxlen=50)) dead_neuron_rate_history: deque = field(default_factory=lambda: deque(maxlen=50)) epoch: int = 0
def record(self, metrics: Dict[str, Any]) -> None: """Registra métricas de uma época.
Nota: `dead_neuron_rate` pode ser float (valor direto) ou Dict (saída de compute_all_metrics, com chave 'dead_neuron_rate'). """ self.qe_history.append(float(metrics.get("quantization_error", 0.0))) self.te_history.append(float(metrics.get("topological_error", 0.0))) self.kl_history.append(float(metrics.get("kaski_lagus_error", 0.0))) self.var_explained_history.append( float(metrics.get("explained_variance_share", 0.0)) ) # dead_neuron_rate pode ser float ou Dict dnr = metrics.get("dead_neuron_rate", 0.0) if isinstance(dnr, dict): dnr_val = float(dnr.get("dead_neuron_rate", 0.0)) else: dnr_val = float(dnr) self.dead_neuron_rate_history.append(dnr_val) self.epoch += 1
def to_dict(self) -> Dict[str, Any]: return { "epoch": int(self.epoch), "qe_history": list(self.qe_history), "te_history": list(self.te_history), "kl_history": list(self.kl_history), "var_explained_history": list(self.var_explained_history), "dead_neuron_rate_history": list(self.dead_neuron_rate_history), }
# ============================================================================# Funções auxiliares# ============================================================================def _grid_neighbors_set( idx: Tuple[int, int, int, int], grid_shape: Tuple[int, int, int, int],) -> set: """Retorna o conjunto de índices vizinhos diretos (6-connectivity em 4D) de um neurônio na grade.""" i, j, k, l = idx I, J, K, L = grid_shape neighbors = set() for di, dj, dk, dl in [ (1, 0, 0, 0), (-1, 0, 0, 0), (0, 1, 0, 0), (0, -1, 0, 0), (0, 0, 1, 0), (0, 0, -1, 0), (0, 0, 0, 1), (0, 0, 0, -1), ]: ni, nj, nk, nl = i + di, j + dj, k + dk, l + dl if 0 <= ni < I and 0 <= nj < J and 0 <= nk < K and 0 <= nl < L: neighbors.add((ni, nj, nk, nl)) return neighbors
def _find_bmu_and_second( x: torch.Tensor, weights: torch.Tensor) -> Tuple[Tuple[int, int, int, int], Tuple[int, int, int, int], float, float]: """Encontra BMU e 2ª BMU para um vetor x.
Args: x: tensor [4] — vetor 4D de entrada. weights: tensor [I, J, K, L, 4] — pesos do SOM.
Returns: (bmu_idx, second_bmu_idx, dist_bmu, dist_second) """ grid_shape = weights.shape[:-1] flat_w = weights.view(-1, 4) # (I*J*K*L, 4) diff = flat_w - x.view(1, 4) dist_sq = torch.sum(diff * diff, dim=-1) # (I*J*K*L,)
# Top-2 menores distâncias top2 = torch.topk(dist_sq, k=2, largest=False) flat_idx_bmu = int(top2.indices[0].item()) flat_idx_2nd = int(top2.indices[1].item())
# Unravel L = grid_shape[3] K = grid_shape[2] J = grid_shape[1]
def unravel(flat_idx: int) -> Tuple[int, int, int, int]: i = flat_idx // (J * K * L) r = flat_idx % (J * K * L) j = r // (K * L) r = r % (K * L) k = r // L l = r % L return (i, j, k, l)
bmu = unravel(flat_idx_bmu) second = unravel(flat_idx_2nd) dist_bmu = float(math.sqrt(max(top2.values[0].item(), 0.0))) dist_second = float(math.sqrt(max(top2.values[1].item(), 0.0))) return bmu, second, dist_bmu, dist_second
# ============================================================================# Métricas principais (1.1 - 1.4)# ============================================================================def quantization_error( data: torch.Tensor, weights: torch.Tensor) -> float: """1.1 Erro de Quantização (QE).
QE = (1/N) * Σ_i ||x_i - W_BMU(x_i)||₂
Args: data: tensor [N, 4] — vetores de entrada. weights: tensor [I, J, K, L, 4] — pesos do SOM.
Returns: QE (float). 0.0 se data vazio. """ if data.numel() == 0: return 0.0 flat_w = weights.view(-1, 4) # (M, 4) # distância de cada amostra a todos os neurônios # data: (N, 4), flat_w: (M, 4) -> (N, M) diff = data.unsqueeze(1) - flat_w.unsqueeze(0) dist_sq = torch.sum(diff * diff, dim=-1) # (N, M) min_dist_sq, _ = torch.min(dist_sq, dim=1) # (N,) qe = torch.mean(torch.sqrt(min_dist_sq.clamp(min=0.0))) return float(qe.item())
def topological_error( data: torch.Tensor, weights: torch.Tensor) -> float: """1.2 Erro Topológico (TE).
TE = (1/N) * Σ_i 𝟙[¬adjacent(BMU_1(x_i), BMU_2(x_i))]
Dois neurônios são adjacentes se differem em exatamente uma coordenada por ±1 (6-connectivity em 4D).
Args: data: tensor [N, 4] weights: tensor [I, J, K, L, 4]
Returns: TE ∈ [0, 1]. 0.0 se data vazio. """ if data.numel() == 0: return 0.0 grid_shape = weights.shape[:-1] flat_w = weights.view(-1, 4) diff = data.unsqueeze(1) - flat_w.unsqueeze(0) dist_sq = torch.sum(diff * diff, dim=-1) # (N, M)
# Top-2 BMUs para cada amostra top2 = torch.topk(dist_sq, k=2, largest=False, dim=1) flat_bmu = top2.indices[:, 0] # (N,) flat_2nd = top2.indices[:, 1] # (N,)
# Unravel L = grid_shape[3] K = grid_shape[2] J = grid_shape[1] I = grid_shape[0]
def unravel_batch(flat_idx: torch.Tensor) -> torch.Tensor: """Retorna tensor (N, 4) com (i, j, k, l).""" i = flat_idx // (J * K * L) r = flat_idx % (J * K * L) j = r // (K * L) r = r % (K * L) k = r // L l = r % L return torch.stack([i, j, k, l], dim=1).long()
bmu_idx = unravel_batch(flat_bmu) # (N, 4) second_idx = unravel_batch(flat_2nd) # (N, 4)
# Adjacência: |Δcoord| soma = 1 (apenas uma coordenada muda por ±1) delta = (bmu_idx - second_idx).abs() # (N, 4) is_adjacent = (delta.sum(dim=1) == 1) & (delta.max(dim=1).values == 1)
te = 1.0 - float(is_adjacent.float().mean().item()) return te
def kaski_lagus_error( data: torch.Tensor, weights: torch.Tensor, alpha: float = 0.5) -> float: """1.3 Erro de Kaski-Lagus.
Combinação ponderada de QE normalizado e TE.
Variante implementada (Kaski & Lagus, 1999): KL = α * MQE_norm + (1-α) * TE onde MQE_norm = QE / mean(||x||) (normalização por escala dos dados).
Uma variante alternativa multiplica: KL = QE * (1 + TE) que penaliza QE quando TE é alto (usada se use_multiplicative=True).
Args: data: tensor [N, 4] weights: tensor [I, J, K, L, 4] alpha: peso do QE normalizado (default 0.5)
Returns: KL (float). """ if data.numel() == 0: return 0.0 qe = quantization_error(data, weights) te = topological_error(data, weights) # Normalização: escala típica dos dados data_norm = float(torch.mean(torch.norm(data, dim=1)).item()) qe_norm = qe / max(data_norm, 1e-8) kl = alpha * qe_norm + (1.0 - alpha) * te return float(kl)
def explained_variance_share( data: torch.Tensor, weights: torch.Tensor) -> float: """1.4 Variância Explicada (Share of Explained Variance).
VarExplained = 1 - Var(residual) / Var(total) onde residual = x_i - W_BMU(x_i)
Implementação: computamos a variância total dos dados (soma das variâncias por dimensão) e a variância dos resíduos. A fração explicada é:
VE = 1 - Σ_d Var(residual_d) / Σ_d Var(data_d)
Returns: VE ∈ [0, 1]. Próximo de 1 = boa representação. """ if data.numel() == 0 or data.shape[0] < 2: return 0.0 flat_w = weights.view(-1, 4) diff = data.unsqueeze(1) - flat_w.unsqueeze(0) dist_sq = torch.sum(diff * diff, dim=-1) # (N, M) _, bmu_flat = torch.min(dist_sq, dim=1) # (N,) bmu_w = flat_w[bmu_flat] # (N, 4) residual = data - bmu_w # (N, 4)
# Variância por dimensão (sem viés, ddof=0) var_data = torch.var(data, dim=0, unbiased=False) # (4,) var_resid = torch.var(residual, dim=0, unbiased=False) # (4,)
total_var = float(torch.sum(var_data).item()) resid_var = float(torch.sum(var_resid).item()) if total_var < 1e-12: return 0.0 ve = 1.0 - (resid_var / total_var) return float(max(0.0, min(1.0, ve)))
# ============================================================================# Indicadores de falha (2.1 - 2.4)# ============================================================================def topological_collapse(weights: torch.Tensor) -> Dict[str, Any]: """2.1 Colapso Topológico (Topological Collapse).
Detecta se os pesos colapsaram para um ponto (rank < 1) ou para uma linha (rank < 2). Usa SVD sobre os pesos reshaped (M, 4).
Args: weights: tensor [I, J, K, L, 4]
Returns: Dict com: - collapsed_to_point: bool (todos iguais) - collapsed_to_line: bool (variação só em 1 direção) - effective_rank: float (rank efetivo via razão de singular values) - singular_values: list[float] - severity: str ("none" | "line" | "point") """ flat_w = weights.view(-1, 4).clone() # (M, 4) if flat_w.numel() == 0: return {"collapsed_to_point": False, "collapsed_to_line": False, "effective_rank": 0.0, "singular_values": [], "severity": "none"}
# Centraliza flat_w_centered = flat_w - flat_w.mean(dim=0, keepdim=True)
# V6.5-V2-metrics FIX: usa SVD com fallback robusto para matrizes # singulares/ill-conditioned. Se SVD falhar, usa np.linalg.eigh com # regularização (adiciona pequeno ruído diagonal). S_list: List[float] = [] try: # Tentativa 1: SVD direto (mais estável que eigh) U, S, V = torch.linalg.svd(flat_w_centered, full_matrices=False) S_list = [float(s.item()) for s in S] except Exception: # Tentativa 2: eigendecomposição da matriz de covariância com regularização try: cov = flat_w_centered.t() @ flat_w_centered # Regularização: adiciona pequeno valor diagonal para estabilizar n = cov.shape[0] reg = 1e-6 * float(cov.diag().max().item()) if n > 0 else 1e-6 cov_reg = cov + torch.eye(n) * reg S_eigh, _ = torch.linalg.eigh(cov_reg) S_eigh = S_eigh.flip(0) # descending order # Converte autovalores em "singular values" aproximados (sqrt) S_list = [float(math.sqrt(max(s.item(), 0.0))) for s in S_eigh] except Exception: # Tentativa 3: usa norma de Frobenius como aproximação s_frob = float(torch.norm(flat_w_centered).item()) S_list = [s_frob, 0.0, 0.0, 0.0]
if not S_list: return {"collapsed_to_point": False, "collapsed_to_line": False, "effective_rank": 0.0, "singular_values": [], "severity": "none"}
s_max = max(S_list[0] if S_list else 0.0, 1e-12)
# Effective rank: número de singular values > 1% do maior threshold = 0.01 * s_max n_significant = sum(1 for s in S_list if s > threshold) # Effective rank (float, via entropy) s_norm = [s / s_max for s in S_list] s_norm = [s for s in s_norm if s > 1e-10] if s_norm: p = torch.tensor(s_norm) p_norm = p / p.sum() entropy = -float(torch.sum(p_norm * torch.log(p_norm)).item()) effective_rank = math.exp(entropy) else: effective_rank = 0.0
collapsed_to_point = n_significant <= 1 and s_max < 1e-6 collapsed_to_line = n_significant == 1 and s_max >= 1e-6
if collapsed_to_point: severity = "point" elif collapsed_to_line: severity = "line" else: severity = "none"
return { "collapsed_to_point": bool(collapsed_to_point), "collapsed_to_line": bool(collapsed_to_line), "effective_rank": float(effective_rank), "singular_values": S_list, "severity": severity, }
def dead_neuron_rate( data: torch.Tensor, weights: torch.Tensor) -> Dict[str, Any]: """2.2 Taxa de Neurônios Mortos (Dead Neurons).
DeadRate = (n_neurons - n_active_neurons) / n_neurons
Um neurônio é "ativo" se é BMU para pelo menos uma amostra.
Args: data: tensor [N, 4] weights: tensor [I, J, K, L, 4]
Returns: Dict com: - dead_neuron_rate: float ∈ [0, 1] - n_dead: int - n_active: int - n_total: int - dead_indices: list de (i,j,k,l) """ n_total = weights.shape[0] * weights.shape[1] * weights.shape[2] * weights.shape[3] if data.numel() == 0: return {"dead_neuron_rate": 1.0, "n_dead": n_total, "n_active": 0, "n_total": n_total, "dead_indices": []}
flat_w = weights.view(-1, 4) diff = data.unsqueeze(1) - flat_w.unsqueeze(0) dist_sq = torch.sum(diff * diff, dim=-1) # (N, M) _, bmu_flat = torch.min(dist_sq, dim=1) # (N,)
active_mask = torch.zeros(n_total, dtype=torch.bool) active_mask[bmu_flat] = True n_active = int(active_mask.sum().item()) n_dead = n_total - n_active
# Coleta índices mortos dead_flat = (~active_mask).nonzero(as_tuple=True)[0] L_dim = weights.shape[3] K_dim = weights.shape[2] J_dim = weights.shape[1] dead_indices = [] for flat_idx in dead_flat.tolist(): i = flat_idx // (J_dim * K_dim * L_dim) r = flat_idx % (J_dim * K_dim * L_dim) j = r // (K_dim * L_dim) r = r % (K_dim * L_dim) k = r // L_dim l = r % L_dim dead_indices.append((i, j, k, l))
return { "dead_neuron_rate": float(n_dead / n_total) if n_total > 0 else 0.0, "n_dead": int(n_dead), "n_active": int(n_active), "n_total": int(n_total), "dead_indices": dead_indices[:50], # limita para não explodir JSON }
def quantization_error_stagnation( history: SOMMetricHistory, high_threshold_frac: float = 0.7, slope_tolerance: float = 1e-4, window_size: int = 5,) -> Dict[str, Any]: """2.3 Estagnação do Erro de Quantização.
Detecta se o QE estabilizou em patamar elevado: - |slope(QE)| < slope_tolerance (estável) - QE_atual > high_threshold_frac * max(QE_history) (alto)
Args: history: histórico de métricas SOM. high_threshold_frac: fração do QE máximo para considerar "alto". slope_tolerance: tolerância de slope para considerar "estável". window_size: nº de épocas recentes para regressão linear.
Returns: Dict com: - is_stagnant: bool - current_qe: float - max_qe: float - slope: float - severity: str ("none" | "mild" | "severe") """ qe_list = list(history.qe_history) if len(qe_list) < window_size + 2: return {"is_stagnant": False, "current_qe": 0.0, "max_qe": 0.0, "slope": 0.0, "severity": "none", "n_epochs": len(qe_list)}
# Regressão linear sobre as últimas window_size épocas recent = qe_list[-window_size:] n = len(recent) x_mean = (n - 1) / 2.0 y_mean = sum(recent) / n num = sum((i - x_mean) * (y - y_mean) for i, y in enumerate(recent)) den = sum((i - x_mean) ** 2 for i in range(n)) slope = num / den if den > 0 else 0.0
current_qe = float(qe_list[-1]) max_qe = float(max(qe_list)) is_high = current_qe > high_threshold_frac * max_qe is_stable = abs(slope) < slope_tolerance
is_stagnant = is_stable and is_high
if is_stagnant: if current_qe > 0.9 * max_qe: severity = "severe" else: severity = "mild" else: severity = "none"
return { "is_stagnant": bool(is_stagnant), "current_qe": current_qe, "max_qe": max_qe, "slope": float(slope), "severity": severity, "n_epochs": len(qe_list), }
def neighborhood_crossing( history: SOMMetricHistory, initial_window: int = 5, final_window: int = 5, growth_threshold: float = 1.5,) -> Dict[str, Any]: """2.4 Cruzamento de Vizinhança (Neighborhood Crossing).
Detecta crescimento repentino ou oscilação crônica do TE nas épocas finais: - std(TE_final) > growth_threshold * std(TE_initial) (oscilação cresceu) - TE[-1] > TE[-5] (crescimento no final)
Args: history: histórico de métricas SOM. initial_window: nº de épocas iniciais para baseline. final_window: nº de épocas finais para comparação. growth_threshold: razão de std para considerar "crescimento crônico".
Returns: Dict com: - detected: bool - te_initial_mean: float - te_final_mean: float - te_initial_std: float - te_final_std: float - std_ratio: float - is_oscillating: bool - is_growing: bool - severity: str ("none" | "mild" | "severe") """ te_list = list(history.te_history) if len(te_list) < initial_window + final_window: return {"detected": False, "te_initial_mean": 0.0, "te_final_mean": 0.0, "te_initial_std": 0.0, "te_final_std": 0.0, "std_ratio": 0.0, "is_oscillating": False, "is_growing": False, "severity": "none", "n_epochs": len(te_list)}
initial = te_list[:initial_window] final = te_list[-final_window:]
init_mean = sum(initial) / len(initial) final_mean = sum(final) / len(final) init_var = sum((x - init_mean) ** 2 for x in initial) / len(initial) final_var = sum((x - final_mean) ** 2 for x in final) / len(final) init_std = math.sqrt(init_var) final_std = math.sqrt(final_var)
std_ratio = final_std / max(init_std, 1e-8) is_oscillating = std_ratio > growth_threshold is_growing = final_mean > init_mean and (final_mean - init_mean) > 0.05
detected = is_oscillating or is_growing
if detected: if std_ratio > 2.0 * growth_threshold or is_growing: severity = "severe" else: severity = "mild" else: severity = "none"
return { "detected": bool(detected), "te_initial_mean": float(init_mean), "te_final_mean": float(final_mean), "te_initial_std": float(init_std), "te_final_std": float(final_std), "std_ratio": float(std_ratio), "is_oscillating": bool(is_oscillating), "is_growing": bool(is_growing), "severity": severity, "n_epochs": len(te_list), }
# ============================================================================# Função agregadora: compute_all_metrics# ============================================================================def compute_all_metrics( data: torch.Tensor, weights: torch.Tensor, history: Optional[SOMMetricHistory] = None,) -> Dict[str, Any]: """Computa todas as métricas SOM de uma vez.
Args: data: tensor [N, 4] — buffer de vetores 4D. weights: tensor [I, J, K, L, 4] — pesos do SOM. history: histórico de métricas (opcional, para estagnação e cruzamento).
Returns: Dict com: - quantization_error: float - topological_error: float - kaski_lagus_error: float - explained_variance_share: float - topological_collapse: Dict - dead_neuron_rate: Dict - quantization_error_stagnation: Dict (se history fornecido) - neighborhood_crossing: Dict (se history fornecido) - overall_health: str ("healthy" | "warning" | "critical") - failure_indicators: list[str] """ # V6.5-V2-metrics FIX: wrap entire computation in try/except para evitar # crashes fatais quando o SOM tem pesos degenerados (ex: todos iguais # após muito treinamento sem diversidade). Em caso de erro, retorna # métricas safe-default em vez de crashar o treino. try: return _compute_all_metrics_impl(data, weights, history) except Exception as e: logger.warning( f"[som_metrics] compute_all_metrics failed (using safe defaults): {e}" ) return { "quantization_error": 0.0, "topological_error": 0.0, "kaski_lagus_error": 0.0, "explained_variance_share": 0.0, "topological_collapse": { "collapsed_to_point": False, "collapsed_to_line": False, "effective_rank": 0.0, "singular_values": [], "severity": "none", "error": str(e)[:200], }, "dead_neuron_rate": { "dead_neuron_rate": 1.0, "n_dead": 0, "n_active": 0, "n_total": 0, "dead_indices": [], "error": str(e)[:200], }, "qe_stagnation": { "is_stagnant": False, "current_qe": 0.0, "max_qe": 0.0, "slope": 0.0, "severity": "none", "n_epochs": 0, }, "neighborhood_crossing": { "detected": False, "te_initial_mean": 0.0, "te_final_mean": 0.0, "te_initial_std": 0.0, "te_final_std": 0.0, "std_ratio": 0.0, "is_oscillating": False, "is_growing": False, "severity": "none", "n_epochs": 0, }, "overall_health": "unknown", "failure_indicators": [f"metrics_computation_error: {str(e)[:100]}"], "n_failure_indicators": 1, "error": str(e)[:300], }
def _compute_all_metrics_impl( data: torch.Tensor, weights: torch.Tensor, history: Optional[SOMMetricHistory] = None,) -> Dict[str, Any]: """Implementação interna de compute_all_metrics (sem try/except wrapper).""" metrics: Dict[str, Any] = {}
# 1.1 - 1.4: Métricas principais metrics["quantization_error"] = quantization_error(data, weights) metrics["topological_error"] = topological_error(data, weights) metrics["kaski_lagus_error"] = kaski_lagus_error(data, weights) metrics["explained_variance_share"] = explained_variance_share(data, weights)
# 2.1: Colapso topológico collapse = topological_collapse(weights) metrics["topological_collapse"] = collapse
# 2.2: Dead neurons dead = dead_neuron_rate(data, weights) metrics["dead_neuron_rate"] = dead
# 2.3: Estagnação do QE (requer histórico) if history is not None and len(history.qe_history) > 5: metrics["qe_stagnation"] = quantization_error_stagnation(history) else: metrics["qe_stagnation"] = { "is_stagnant": False, "current_qe": metrics["quantization_error"], "max_qe": metrics["quantization_error"], "slope": 0.0, "severity": "none", "n_epochs": 0, }
# 2.4: Cruzamento de vizinhança (requer histórico) if history is not None and len(history.te_history) > 10: metrics["neighborhood_crossing"] = neighborhood_crossing(history) else: metrics["neighborhood_crossing"] = { "detected": False, "te_initial_mean": 0.0, "te_final_mean": 0.0, "te_initial_std": 0.0, "te_final_std": 0.0, "std_ratio": 0.0, "is_oscillating": False, "is_growing": False, "severity": "none", "n_epochs": 0, }
# Avaliação de saúde geral failure_indicators: List[str] = [] if collapse["collapsed_to_point"]: failure_indicators.append("topological_collapse_point") elif collapse["collapsed_to_line"]: failure_indicators.append("topological_collapse_line") if dead["dead_neuron_rate"] > 0.5: failure_indicators.append(f"dead_neuron_rate_high_{dead['dead_neuron_rate']:.2f}") if metrics["qe_stagnation"]["is_stagnant"]: failure_indicators.append(f"qe_stagnant_{metrics['qe_stagnation']['severity']}") if metrics["neighborhood_crossing"]["detected"]: failure_indicators.append( f"neighborhood_crossing_{metrics['neighborhood_crossing']['severity']}" ) if metrics["explained_variance_share"] < 0.3: failure_indicators.append( f"low_explained_variance_{metrics['explained_variance_share']:.2f}" ) if metrics["topological_error"] > 0.5: failure_indicators.append( f"high_topological_error_{metrics['topological_error']:.2f}" )
if len(failure_indicators) >= 2: overall_health = "critical" elif len(failure_indicators) == 1: overall_health = "warning" else: overall_health = "healthy"
metrics["failure_indicators"] = failure_indicators metrics["overall_health"] = overall_health metrics["n_failure_indicators"] = len(failure_indicators)
return metrics
__all__ = [ "SOMMetricHistory", "quantization_error", "topological_error", "kaski_lagus_error", "explained_variance_share", "topological_collapse", "dead_neuron_rate", "quantization_error_stagnation", "neighborhood_crossing", "compute_all_metrics",]1234567891011121314151617181920212223242526272829303132333461 unmodified lines969798991001011021031041051061071081091101111 unmodified line113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153127 unmodified lines281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318109 unmodified lines4284294304314324334342 unmodified lines4374384394404414424434444453 unmodified lines449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502166 unmodified lines669670671672673674147 unmodified lines82282382482582682782882983023 unmodified lines8548558568578588595 unmodified lines8658668678688698708718728738748758768778789 unmodified lines8888898908918928933 unmodified lines897898899900901902102 unmodified lines10051006100710081009101013 unmodified lines10241025102610271028102922 unmodified lines105210531054105510561057534 unmodified lines15921593159415951596159715981599160016011602132 unmodified lines17351736173717381739174056 unmodified lines1797179817991800180118021803180418051806180718087 unmodified lines181618171818181918201821182218231824182518261827"""train_v6_5_v2.py — V6.5-V2-dynamic (Hiperparâmetros adaptativos + 2 Fases).═══════════════════════════════════════════════════════════════════════════════V6.5-V2-dynamic — HIPERPARÂMETROS V2 DINÂMICOS E AUTOMÁTICOS═══════════════════════════════════════════════════════════════════════════════User requirements (latest, V6.5-V2-dynamic):1. Atualizações HF em LOTE (sobrescrever antigos desatualizados).2. Limpar Armazenamento e worklog.3. HF_TOKEN apagada do ambiente virtual e dos scripts enviados ao HFapós uso.4. Usar streaming_datasets.py e ativar xeon_runtime.py.5. Analisar e aprimorar (lógica e matemática) — HIPERPARÂMETROS V2(n_hypotheses, n_trials, hyp_train_steps) DINÂMICOS e AUTOMÁTICOSconforme a loss e recorrência de punições.6. Corrigir erros e falhas.7. FASE 1 CONHECIMENTO (meta mínima 6000+ samples, 100 em 100) nasequência exata de 8 datasets.8. FASE 2 TREINAMENTO COM PUNIÇÃO ATIVA (meta mínima 1000+ samples,100 em 100) sobre BrunoN-Dev/corpus-ptbr-v1.9. Após concluir: enviar scripts+arquivos+estado do modelo testados eaprovados ao HF (sobrescrevendo antigos).V6.5-V2-dynamic (alterações vs V6.5-V2):- NOVO: Hiperparâmetros V2 dinâmicos (n_hypotheses ∈ [4, 32],n_trials ∈ [1, 6], hyp_train_steps ∈ [10, 80]) ajustadosautomaticamente após cada train_hypotheses e após cada punição.- NOVO: Meta CONHECIMENTO reduzida de 8000 → 6000 (8 × 800 = 6400).- NOVO: Meta PUNIÇÃO aumentada de 500 → 1000.- NOVO: Upload HF em LOTE ao final (scripts + estado + modelo).- NOVO: Limpeza de worklog e cache HF antes e depois do treino."""from __future__ import annotations61 unmodified lineslogger.info(f"[V6.5-V2] Xeon FP16 benchmark: {FP16_BENCH}")# ============================================================================# 2. Configurações V6.5-V2 (864 neurons, hidden/vocab reduzidos para caber em 4GB RAM)# ============================================================================BATCH_SIZE = 16MAX_SEQ_LEN = 8# V2-dynamic-memory: reduzido de 1024→256 e 16384→4096 para evitar OOM em 4GB RAM# (preserva funcionalidade; apenas reduz footprint de embedding)HIDDEN_DIM = 256VOCAB_SIZE = 4096SOM_GRID = (6, 6, 6, 4) # 864 neuronsT_MAX = 10000N_START = 10LAMBDA_EWC = 0.021 unmodified lineSIGMA0 = 1.5DIM_CHOICE = "y"# V2-dynamic — HypothesisEnsemble parameters (iniciais; serão adaptados)N_HYPOTHESES = 8 # inicial ativo (reduzido de 16 para economizar RAM)MAX_N_HYPOTHESES = 16 # pré-alocação máxima (reduzido de 32)MIN_N_HYPOTHESES = 4 # limite inferior dinâmicoN_TRIALS = 3 # inicialMIN_N_TRIALS = 1MAX_N_TRIALS = 6HYP_TRAIN_STEPS = 20 # inicial (reduzido de 30 para economizar CPU)MIN_HYP_TRAIN_STEPS = 5MAX_HYP_TRAIN_STEPS = 60HYP_LR = 1e-4HYP_HIDDEN_DIM = 128 # reduzido de 256 para economizar RAMLOSS_HISTORY_WINDOW = 8PUNISHMENT_WINDOW = 12# V2-dynamic-memory — Buffer sliding window (evita OOM em treino longo)# Após processar cada chunk, se buffer > MAX_BUFFER_SIZE, trunca para os# últimos MAX_BUFFER_SIZE amostras. Isto limita o crescimento de memória# sem perder o contexto recente. Os pesos do SOM já capturam o conhecimento# acumulado, então o buffer só precisa conter amostras recentes para ajuste fino.MAX_BUFFER_SIZE = 256# Streaming — User requirement: "streaming de 100 em 100 samples"STREAM_BATCH_SIZE = 100# V2-dynamic — Metas atualizadas: 6000 CONHECIMENTO + 1000 PUNIÇÃOMETA_MINIMA_CONHECIMENTO = 6000MAX_SAMPLES_PER_DATASET_CONHECIMENTO = 800 # 8 × 800 = 6400 ≥ 6000META_MINIMA_PUNICAO = 1000MAX_SAMPLES_PUNICAO = 1000# User requirement: "não reduzir tempo e não gerar dados sintéticos"INTER_BATCH_PAUSE_S = 0.3INTER_DATASET_PAUSE_S = 1.5INTER_STREAM_BATCH_PAUSE_S = 0.5# Storage criticalSTORAGE_CRITICAL_PCT = 90127 unmodified linesdef aggressive_memory_cleanup() -> Dict[str, Any]:gc.collect()gc.collect()try:import torchif torch.cuda.is_available():torch.cuda.empty_cache()except Exception:passreturn {"gc_called": True, "timestamp": datetime.now().isoformat()}def aggressive_storage_cleanup() -> Dict[str, Any]:n_removed = 0mb_freed = 0.0hf_cache = Path.home() / ".cache" / "huggingface"if hf_cache.exists():for f in hf_cache.rglob("*.lock"):try:sz = f.stat().st_sizef.unlink()n_removed += 1mb_freed += sz / 1e6except Exception:passfor f in hf_cache.rglob("*.incomplete"):try:sz = f.stat().st_sizef.unlink()n_removed += 1mb_freed += sz / 1e6except Exception:passreturn {"n_files_removed": n_removed,"mb_freed": float(mb_freed),109 unmodified lines# ============================================================================# 6. Streaming helper — chunks of 100 samples# ============================================================================def stream_dataset_in_chunks(dataset_name: str,2 unmodified lineshf_token: Optional[str] = None,timeout_per_chunk: int = 60,) -> Iterator[List[str]]:"""V6.5-V2 — Stream a dataset in chunks of `chunk_size` samples.User requirement: "streaming de 100 em 100 samples até esgotar""""try:from bigru_t.data.streaming_datasets import stream_dataset3 unmodified linesyielded_total = 0chunk_idx = 0while yielded_total < max_total:remaining = max_total - yielded_totalthis_chunk_target = min(chunk_size, remaining)seed_offset = yielded_totalchunk: List[str] = []t_start = time.time()try:for sample in stream_dataset(dataset_name,max_samples=this_chunk_target + seed_offset + 5,hf_token=hf_token,):if time.time() - t_start > timeout_per_chunk:logger.warning(f"[V6.5-V2] {dataset_name} chunk {chunk_idx+1} "f"timeout after {timeout_per_chunk}s "f"(collected {len(chunk)}/{this_chunk_target})")breakif sample.raw_text and len(sample.raw_text.strip()) > 0:if seed_offset > 0:seed_offset -= 1continuechunk.append(sample.raw_text.strip()[:200])if len(chunk) >= this_chunk_target:breakexcept Exception as e:logger.warning(f"[V6.5-V2] {dataset_name} chunk {chunk_idx+1} error: {e}")if chunk:yield chunkyielded_total += len(chunk)chunk_idx += 1breakif not chunk:logger.info(f"[V6.5-V2] {dataset_name} exhausted after {yielded_total} samples "f"({chunk_idx} chunks)")breakyield chunkyielded_total += len(chunk)chunk_idx += 1logger.info(f"[V6.5-V2] {dataset_name} chunk {chunk_idx} done: "f"{len(chunk)} samples (total: {yielded_total}/{max_total})")# ============================================================================166 unmodified lineschunk_idx_global = 0accuracies_log: List[Dict[str, Any]] = []attention_log: List[Dict[str, Any]] = []for ds_idx, dataset_name in enumerate(CONHECIMENTO_DATASETS):if storage_critical_stopped:147 unmodified linesf"[V6.5-V2] Buffer trimmed: -{overflow} → "f"{len(kls.buffer_4d)} samples (cap={MAX_BUFFER_SIZE})")# Aggressive memory cleanup between chunksif chunk_idx_global % 2 == 0:aggressive_memory_cleanup()except Exception as e:logger.error(f"[V6.5-V2] Dataset {dataset_name} failed: {e}")traceback.print_exc()23 unmodified lines"n_chunks": int(chunk_idx_global),"accuracies_log": accuracies_log[-50:], # últimos 50"attention_log": attention_log[-20:],"final_state": kls.get_v2_metrics(),}5 unmodified lineskls: KohonenLearningSystemV2,hf_token: Optional[str],) -> Dict[str, Any]:"""Fase 2 — TREINAMENTO COM PUNIÇÃO: streaming 500 samples + V2 protocol.User requirement: "dataset para TREINAMENTO COM PUNIÇÃO ATIVA'BrunoN-Dev/corpus-ptbr-v1'" + "meta mínima 500 para TREINAMENTO COMPUNIÇÃO" + "Cada evento de erro (punição) dispara 3 tentativas de ajuste.Em cada tentativa, 16 geradores paralelos de hipóteses produzem candidatosa delta. O melhor delta é aplicado ao MAPA-SOM. Após a aplicação,consolidação via EWC."Returns:Dict com métricas da fase TREINAMENTO COM PUNIÇÃO.9 unmodified lineslogger.info(f" hyp_train_steps: {HYP_TRAIN_STEPS}")logger.info("=" * 80 + "\n")step = 0t_start = time.time()samples_processed = 03 unmodified lineshypotheses_log: List[Dict[str, Any]] = []accuracies_log: List[Dict[str, Any]] = []delta_applications_log: List[Dict[str, Any]] = []try:chunk_iter = stream_dataset_in_chunks(102 unmodified lines"ewc_reference_set": bool(kls.som.old_weights_w is not None),})step += 1time.sleep(INTER_BATCH_PAUSE_S)except Exception as e:13 unmodified lines)if chunk_idx_global % 2 == 0:aggressive_memory_cleanup()except Exception as e:logger.error(f"[V6.5-V2] PUNIÇÃO dataset failed: {e}")traceback.print_exc()22 unmodified lines"hypotheses_trainings": hypotheses_log,"delta_applications": delta_applications_log,"accuracies_log": accuracies_log[-50:],"final_v2_state": kls.get_v2_metrics(),}534 unmodified linesaggressive_storage_cleanup()# ========================================================================# 14.5 FASE 2 — TREINAMENTO COM PUNIÇÃO (BrunoN-Dev/corpus-ptbr-v1, 500 samples)# ========================================================================if not conhecimento_result["storage_critical_stopped"]:logger.info("\n[V6.5-V2] Iniciando FASE 2 — TREINAMENTO COM PUNIÇÃO...")punicão_result = run_fase_punicão(kls, hf_token)# Atualiza V2_PHASES_EVAL_PATH com ambas as fasesphases_eval = {132 unmodified linesBIGRU_ROOT / "scripts" / "train_v6_5_v2.py",SRC_ROOT / "bigru_t" / "model" / "kohonen_learning_system.py",SRC_ROOT / "bigru_t" / "model" / "hyp_t.py",SRC_ROOT / "bigru_t" / "data" / "streaming_datasets.py",SRC_ROOT / "bigru_t" / "utils" / "xeon_runtime.py",]56 unmodified lines# ========================================================================# 14.11 LIMPEZA final de armazenamento e worklog# ========================================================================logger.info("\n[V6.5-V2] Limpeza final de armazenamento...")final_storage_cleanup = aggressive_storage_cleanup()aggressive_memory_cleanup()print("\n" + "=" * 80)print("V6.5-V2-dynamic — TREINAMENTO CONCLUÍDO")print("=" * 80)print(f" FASE 1 CONHECIMENTO : {conhecimento_result['total_samples']} samples "f"(meta: {conhecimento_result['meta_atingida']})")7 unmodified linesprint(f" HF upload : {hf_upload_result.get('uploaded', False)} "f"({hf_upload_result.get('n_files', 0)} files)")print(f" HF_TOKEN cleaned : True (env + scripts)")print(f" Storage cleanup : {final_storage_cleanup['n_files_removed']} files, "f"{final_storage_cleanup['mb_freed']:.1f}MB freed")print(f" Final n_hypotheses : {kls.n_hypotheses} (active={kls.hypothesis_ensemble.active_count})")print(f" Final n_trials : {kls.n_trials}")print(f" Final hyp_steps : {kls.hyp_train_steps}")print(f" N adaptations : {len(kls.get_adaptation_log())}")print("=" * 80 + "\n")return 01234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515261 unmodified lines1141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511 unmodified line153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193127 unmodified lines321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438109 unmodified lines5485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916922 unmodified lines6956966976986997007017027037047057067077087097107117127137143 unmodified lines718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785166 unmodified lines952953954955956957958959960961962963147 unmodified lines11111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116423 unmodified lines1188118911901191119211931194119511961197119811995 unmodified lines1205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712289 unmodified lines12381239124012411242124312441245124612471248124912503 unmodified lines12541255125612571258125912601261102 unmodified lines1364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141313 unmodified lines142714281429143014311432143314341435143614371438143922 unmodified lines146214631464146514661467146814691470147114721473534 unmodified lines20082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033132 unmodified lines216621672168216921702171217256 unmodified lines22292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922807 unmodified lines228822892290229122922293229422952296229722982299230023012302"""train_v6_5_v2.py — V6.5-V2-metrics (2 Fases + Métricas SOM canônicas).═══════════════════════════════════════════════════════════════════════════════V6.5-V2-metrics — MÉTRICAS SOM CANÔNICAS + 2 FASES + ESTADO FASE1→FASE2═══════════════════════════════════════════════════════════════════════════════User requirements (latest, V6.5-V2-metrics):1. Organização e não duplicidade de módulos (versões velhas → deprecados/).2. Atualizações HF em LOTE (sobrescrever antigos desatualizados).3. Limpar Armazenamento e worklog.4. HF_TOKEN apagada do ambiente virtual e dos scripts enviados ao HFapós uso.5. Usar streaming_datasets.py e ativar xeon_runtime.py.6. FASE 1 CONHECIMENTO (meta mínima 8000+ samples, 100 em 100) nasequência exata de 8 datasets.7. FASE 2 TREINAMENTO COM PUNIÇÃO ATIVA (meta mínima 2000+ samples,100 em 100) sobre BrunoN-Dev/corpus-ptbr-v1.8. FASE2 NUNCA acontece antes da FASE1. FASE2 carrega explicitamenteo estado do modelo concluído da FASE1.9. FASE2 deve treinar, ajustar dados e parâmetros do MAPA-SOM eINFORMAR MÉTRICAS DE APRENDIZADO do modelo.10. Métricas SOM canônicas (8 métricas) monitoradas especialmente naFASE2 PUNITIVA:10.1. Erro de Quantização (QE) — distância média ‖x_i - W_BMU(x_i)‖10.2. Erro Topológico (TE) — % de pares BMU/2ª-BMU não adjacentes10.3. Erro de Kaski-Lagus — combinação ponderada de QE + TE10.4. Variância Explicada — 1 - Var(residual)/Var(total)10.5. Colapso Topológico — pesos convergem para ponto ou linha10.6. Taxa de Neurônios Mortos — % de neurônios nunca BMU10.7. Estagnação do QE — slope ≈ 0 com QE em patamar elevado10.8. Cruzamento de Vizinhança — TE oscila ou cresce no final11. Limpeza de RAM e Armazenamento aprimorada (lógica + matemática).12. Não reduzir tempo, não gerar dados sintéticos.13. Após concluir: enviar scripts+arquivos+estado do modelo testados eaprovados ao HF (sobrescrevendo antigos).V6.5-V2-metrics (alterações vs V6.5-V2-dynamic):- NOVO: Módulo som_metrics.py com 8 métricas canônicas implementadas.- NOVO: KohonenLearningSystemV2.compute_som_metrics() integra as métricas.- NOVO: Histórico de métricas SOM (SOMMetricHistory) para detecçãode estagnação do QE e cruzamento de vizinhança.- NOVO: FASE1 computa métricas após cada chunk (8000 samples).- NOVO: FASE2 computa métricas após CADA BATCH (2000 samples, maisfrequentemente por ser fase punitiva).- NOVO: load_fase1_state_into_kls() — carrega explicitamente estadoda FASE1 antes de iniciar FASE2.- NOVO: aggressive_memory_cleanup() reporta RSS antes/depois.- NOVO: aggressive_storage_cleanup() limpa __pycache__ + .tmp + logs >7dias.- META: CONHECIMENTO 6000 → 8000; PUNIÇÃO 1000 → 2000."""from __future__ import annotations61 unmodified lineslogger.info(f"[V6.5-V2] Xeon FP16 benchmark: {FP16_BENCH}")# ============================================================================# 2. Configurações V6.5-V2-metrics-FIX (864 neurons, params restaurados a valores maiores)# ============================================================================# User requirement (latest): "ATENÇÃO: retornar os parâmetros do modelo para# os valores maiores e resolver falhas de lógica e de bugs que estejam causando# alto consumo de memória sem distorcer a arquitetura Kohonen."## Valores restaurados (V6.5-V2-metrics-FIX):# HIDDEN_DIM: 256 → 1024 (restaurado)# VOCAB_SIZE: 4096 → 16384 (restaurado)# N_HYPOTHESES: 8 → 16 (restaurado)# MAX_N_HYPOTHESES: 16 → 32 (restaurado)# HYP_TRAIN_STEPS: 20 → 30 (restaurado)# HYP_HIDDEN_DIM: 128 → 256 (restaurado)## Para compensar o aumento de memória (sem distorcer Kohonen):# 1. BUG FIX: _compute_classification_loss_with_som estava dentro de# torch.no_grad(), matando o gradiente dos deltas. Corrigido.# 2. VETORIZAÇÃO: train_hypotheses agora avalia 16 hipóteses em paralelo# via batched matmul (n_hyp, P, N) em vez de loop que materializava# 16 cópias do SOM.# 3. aggressive_cleanup(): zera gradientes Adam, trunca históricos,# gc.collect() em 3 passes.# 4. Buffer sliding window: MAX_BUFFER_SIZE = 256 (preserva contexto recente# sem crescer indefinidamente).# 5. VQ-VAE-2 e W8A8 desabilitados por padrão (não essenciais para Kohonen).BATCH_SIZE = 16MAX_SEQ_LEN = 8# V6.5-V2-metrics-FIX: restaurado para valores maiores (user requirement)HIDDEN_DIM = 1024 # restaurado de 256VOCAB_SIZE = 16384 # restaurado de 4096SOM_GRID = (6, 6, 6, 4) # 864 neurons (arquitetura Kohonen preservada)T_MAX = 10000N_START = 10LAMBDA_EWC = 0.021 unmodified lineSIGMA0 = 1.5DIM_CHOICE = "y"# V2-dynamic — HypothesisEnsemble parameters (restaurados a valores maiores)N_HYPOTHESES = 16 # restaurado de 8MAX_N_HYPOTHESES = 32 # restaurado de 16MIN_N_HYPOTHESES = 4 # limite inferior dinâmicoN_TRIALS = 3 # inicialMIN_N_TRIALS = 1MAX_N_TRIALS = 6HYP_TRAIN_STEPS = 30 # restaurado de 20MIN_HYP_TRAIN_STEPS = 10MAX_HYP_TRAIN_STEPS = 80HYP_LR = 1e-4HYP_HIDDEN_DIM = 256 # restaurado de 128LOSS_HISTORY_WINDOW = 8PUNISHMENT_WINDOW = 12# V2-dynamic-memory — Buffer sliding window (evita OOM em treino longo)MAX_BUFFER_SIZE = 256# Streaming — User requirement: "streaming de 100 em 100 samples"STREAM_BATCH_SIZE = 100# V2-dynamic — Metas atualizadas (V6.5-V2-metrics): 8000 CONHECIMENTO + 2000 PUNIÇÃOMETA_MINIMA_CONHECIMENTO = 8000MAX_SAMPLES_PER_DATASET_CONHECIMENTO = 1000 # 8 × 1000 = 8000 ≥ 8000META_MINIMA_PUNICAO = 2000MAX_SAMPLES_PUNICAO = 2000# User requirement: "não reduzir tempo e não gerar dados sintéticos" +# "todo streaming (FASE1 e da FASE2) deve ter pausa para dar tempo de conclusão# de processamento continuando após conclusão"INTER_BATCH_PAUSE_S = 0.5 # aumentado de 0.3 (mais tempo para processamento)INTER_DATASET_PAUSE_S = 2.0 # aumentado de 1.5INTER_STREAM_BATCH_PAUSE_S = 1.0 # aumentado de 0.5 (pausa entre chunks de 100)POST_PROCESSING_PAUSE_S = 1.5 # NOVO: pausa após processar cada chunk para# dar tempo de conclusão de processamento# Storage criticalSTORAGE_CRITICAL_PCT = 90127 unmodified linesdef aggressive_memory_cleanup() -> Dict[str, Any]:"""V6.5-V2-metrics — Limpeza agressiva de RAM.User requirement: "analisar e aprimorar (logicamente e matematicamente)no projeto limpeza de memória RAM e de Armazenamento (ao concluir)".Implementação:1. gc.collect() — 2 passes (gerações 0+1 e 2)2. torch.cuda.empty_cache() (se CUDA disponível)3. Limpa caches internos do PyTorch (MKL, oneDNN)4. Reporta RSS antes/depois para confirmação"""rss_before = get_process_rss_mb()gc.collect()gc.collect()try:import torchif torch.cuda.is_available():torch.cuda.empty_cache()# V6.5-V2-metrics: limpa caches CPU do PyTorchif hasattr(torch, "cpu"):try:# MKL/OneDNN primitive cache é limpo implicitamente por gcpassexcept Exception:passexcept Exception:passrss_after = get_process_rss_mb()freed_mb = max(0.0, rss_before - rss_after)return {"gc_called": True,"rss_before_mb": float(rss_before),"rss_after_mb": float(rss_after),"freed_mb": float(freed_mb),"timestamp": datetime.now().isoformat(),}def aggressive_storage_cleanup() -> Dict[str, Any]:"""V6.5-V2-metrics — Limpeza agressiva de Armazenamento.User requirement: "analisar e aprimorar (logicamente e matematicamente)no projeto limpeza de memória RAM e de Armazenamento (ao concluir)".Implementação:1. Limpa locks HF (*.lock)2. Limpa downloads incompletos (*.incomplete)3. Limpa __pycache__ recursivamente4. Limpa arquivos .tmp5. Limpa logs antigos (>7 dias, se existirem)6. Reporta MB liberados"""n_removed = 0mb_freed = 0.0# 1. HF cache locks e incompletoshf_cache = Path.home() / ".cache" / "huggingface"if hf_cache.exists():for pattern in ["*.lock", "*.incomplete", "*.tmp"]:for f in hf_cache.rglob(pattern):try:sz = f.stat().st_sizef.unlink()n_removed += 1mb_freed += sz / 1e6except Exception:pass# 2. __pycache__ recursivo no BiGRU_T_versionbigru_root = BIGRU_ROOTfor cache_dir in bigru_root.rglob("__pycache__"):if "deprecados" in str(cache_dir):continuetry:for f in cache_dir.iterdir():try:sz = f.stat().st_sizef.unlink()n_removed += 1mb_freed += sz / 1e6except Exception:passcache_dir.rmdir()except Exception:pass# 3. Arquivos .tmp no BiGRU_T_versionfor f in bigru_root.rglob("*.tmp"):if "deprecados" in str(f):continuetry:sz = f.stat().st_sizef.unlink()n_removed += 1mb_freed += sz / 1e6except Exception:pass# 4. Logs antigos (>7 dias) em logs/logs_dir = PROJECT_ROOT / "logs"if logs_dir.exists():cutoff = time.time() - 7 * 24 * 3600 # 7 diasfor f in logs_dir.glob("*.log"):try:if f.stat().st_mtime < cutoff:sz = f.stat().st_sizef.unlink()n_removed += 1mb_freed += sz / 1e6except Exception:passreturn {"n_files_removed": n_removed,"mb_freed": float(mb_freed),109 unmodified lines# ============================================================================# 5.5 Load FASE1 state into KLS (FASE2 must use FASE1's completed state)# ============================================================================def load_fase1_state_into_kls(kls: KohonenLearningSystemV2,state_path: Path,) -> Dict[str, Any]:"""V6.5-V2-metrics — Carrega estado do modelo concluído da FASE1 no KLS.User requirement: "esta FASE2 (nunca acontece antes da FASE1) deve usar doarquivo de Estado do MODELO concluído da FASE1 e a FASE2 tem função: detreinar, ajustar dados e os parâmetros do MAPA-SOM de redes Kohonen,informar métricas de aprendizado do modelo".Esta função é chamada explicitamente antes de iniciar a FASE 2, garantindoque a FASE 2 herde todo o conhecimento acumulado da FASE 1 (pesos do SOM,EWC references, classifier, hypothesis ensemble, delta_scale, label_registry).Args:kls: instância KohonenLearningSystemV2 (mesma usada na FASE1).state_path: caminho para o arquivo .pt salvo ao final da FASE1.Returns:Dict com status do carregamento."""import torchif not state_path.exists():logger.warning(f"[V6.5-V2-metrics] FASE1 state file not found: {state_path}. "f"FASE2 will run with the in-memory KLS state (already inherited "f"from FASE1 since same KLS instance is used).")return {"loaded": False,"reason": "state_file_not_found","path": str(state_path),"in_memory_state_used": True,}try:state = torch.load(state_path, map_location="cpu", weights_only=False)meta = state.get("_meta", {})logger.info(f"[V6.5-V2-metrics] Loading FASE1 state from {state_path}: "f"reason={meta.get('reason', '?')}, "f"step={meta.get('step', 0)}, "f"total_samples={meta.get('total_samples', 0)}, "f"timestamp={meta.get('timestamp', '?')}")# Carrega pesos do SOM (preserva o aprendizado da FASE1)if "som_weights" in state and state["som_weights"] is not None:kls.som.weights = state["som_weights"].clone().float()logger.info(f"[V6.5-V2-metrics] SOM weights loaded: "f"shape={tuple(kls.som.weights.shape)}, "f"norm={float(kls.som.weights.norm().item()):.4f}")# Carrega EWC references (se existirem da FASE1)if "som_old_weights_w" in state and state["som_old_weights_w"] is not None:kls.som.old_weights_w = state["som_old_weights_w"].clone().float()logger.info("[V6.5-V2-metrics] SOM EWC old_weights_w loaded.")if "som_fisher_w" in state and state["som_fisher_w"] is not None:kls.som.fisher_w = state["som_fisher_w"].clone().float()logger.info("[V6.5-V2-metrics] SOM EWC fisher_w loaded.")# Carrega embeddingif "embedding_state" in state and state["embedding_state"] is not None:kls.embedding.weight.data = state["embedding_state"]["weight"].clone().float()logger.info("[V6.5-V2-metrics] Embedding weights loaded.")# Carrega classifier (se treinado na FASE1)if "classifier_state" in state and state["classifier_state"] is not None:if kls.classifier is None:# Recria o classifier com a mesma arquiteturakls.classifier = HypothesisClassifier(input_dim=kls.som_neuron_count,hidden_dims=kls.hypothesis_hidden,)kls.classifier.load_state_dict(state["classifier_state"])kls.classifier_trained = Truelogger.info("[V6.5-V2-metrics] Classifier state loaded.")# Carrega HypothesisEnsembleif "hypothesis_ensemble_state" in state and state["hypothesis_ensemble_state"] is not None:kls.hypothesis_ensemble.load_state_dict(state["hypothesis_ensemble_state"])logger.info(f"[V6.5-V2-metrics] HypothesisEnsemble state loaded: "f"n_generators={len(kls.hypothesis_ensemble.generators)}, "f"active={kls.hypothesis_ensemble.active_count}")# Carrega delta_scaleif "delta_scale" in state and state["delta_scale"] is not None:kls.delta_scale.data = state["delta_scale"].clone().float()logger.info(f"[V6.5-V2-metrics] delta_scale loaded: {kls.delta_scale.item():.4f}")# Carrega label_registry (preserva mapeamentos dinâmicos)if "label_registry" in state and state["label_registry"] is not None:kls.label_registry = state["label_registry"]logger.info(f"[V6.5-V2-metrics] label_registry loaded: "f"{len(kls.label_registry)} datasets")# Restaura time_counter (preserva coordenada temporal absoluta)if "time_counter" in meta:kls.time_counter = int(meta["time_counter"])logger.info(f"[V6.5-V2-metrics] time_counter restored: {kls.time_counter}")logger.info(f"[V6.5-V2-metrics] ✓ FASE1 state loaded successfully. "f"KLS is now ready for FASE2 (PUNITIVE) training.")return {"loaded": True,"path": str(state_path),"meta": meta,"in_memory_state_used": False,}except Exception as e:logger.error(f"[V6.5-V2-metrics] Failed to load FASE1 state: {e}. "f"FASE2 will run with the in-memory KLS state (already inherited "f"from FASE1 since same KLS instance is used).")traceback.print_exc()return {"loaded": False,"reason": f"load_error: {str(e)[:200]}","path": str(state_path),"in_memory_state_used": True,}# ============================================================================# 6. Streaming helper — chunks of 100 samples (V6.5-V2-metrics: O(N) not O(N²))# ============================================================================def stream_dataset_in_chunks(dataset_name: str,2 unmodified lineshf_token: Optional[str] = None,timeout_per_chunk: int = 60,) -> Iterator[List[str]]:"""V6.5-V2-metrics — Stream a dataset in chunks of `chunk_size` samples.User requirement: "streaming de 100 em 100 samples até esgonar".V6.5-V2-metrics FIX: A versão anterior re-chamava stream_dataset() paracada chunk com seed_offset = yielded_total, fazendo com que o HFre-streaming recapitulasse todas as amostras anteriores a cada chunk(custo O(N²) em banda e cache). Esta versão cria UM ÚNICO iteradorpor dataset e vai colhendo chunks de `chunk_size` em `chunk_size`,sem recomeçar do zero. Isto reduz drasticamente o uso de memória(que antes crescia linearmente com o nº de chunks devido ao cacheacumulado de metadados parquet) e permite atingir as metas de8000 samples CONHECIMENTO + 2000 samples PUNIÇÃO dentro do limitede 4GB RAM do cgroup."""try:from bigru_t.data.streaming_datasets import stream_dataset3 unmodified linesyielded_total = 0chunk_idx = 0chunk: List[str] = []t_start = time.time()try:sample_iter = stream_dataset(dataset_name,max_samples=max_total,hf_token=hf_token,)for sample in sample_iter:if yielded_total >= max_total:break# Timeout check: se demorar demais, yield o que temos e continuaif time.time() - t_start > timeout_per_chunk * (chunk_idx + 1):logger.warning(f"[V6.5-V2] {dataset_name} chunk {chunk_idx+1} "f"timeout after {timeout_per_chunk}s "f"(collected {len(chunk)}/{chunk_size})")if chunk:yield chunkyielded_total += len(chunk)chunk_idx += 1chunk = []if time.time() - t_start > timeout_per_chunk * (chunk_idx + 2):# Segundo timeout consecutivo — desiste deste datasetlogger.warning(f"[V6.5-V2] {dataset_name} exhausted after {yielded_total} samples "f"({chunk_idx} chunks) due to repeated timeouts")returncontinueif sample.raw_text and len(sample.raw_text.strip()) > 0:chunk.append(sample.raw_text.strip()[:200])if len(chunk) >= chunk_size:yield chunkyielded_total += len(chunk)chunk_idx += 1logger.info(f"[V6.5-V2] {dataset_name} chunk {chunk_idx} done: "f"{len(chunk)} samples (total: {yielded_total}/{max_total})")chunk = []except Exception as e:logger.warning(f"[V6.5-V2] {dataset_name} streaming error: {e}")if chunk:yield chunkyielded_total += len(chunk)chunk_idx += 1return# Yield any remaining partial chunkif chunk:yield chunkyielded_total += len(chunk)chunk_idx += 1logger.info(f"[V6.5-V2] {dataset_name} exhausted after {yielded_total} samples "f"({chunk_idx} chunks)")# ============================================================================166 unmodified lineschunk_idx_global = 0accuracies_log: List[Dict[str, Any]] = []attention_log: List[Dict[str, Any]] = []# V6.5-V2-metrics — log de métricas SOM durante CONHECIMENTOsom_metrics_log: List[Dict[str, Any]] = []# V6.5-V2-metrics — reseta histórico de métricas SOM no início de CONHECIMENTOkls.reset_som_metric_history()logger.info("[V6.5-V2-metrics] Histórico de métricas SOM resetado para FASE 1.")for ds_idx, dataset_name in enumerate(CONHECIMENTO_DATASETS):if storage_critical_stopped:147 unmodified linesf"[V6.5-V2] Buffer trimmed: -{overflow} → "f"{len(kls.buffer_4d)} samples (cap={MAX_BUFFER_SIZE})")# V6.5-V2-metrics — Computa métricas SOM após cada chunk# (QE, TE, Kaski-Lagus, Variância Explicada, Dead Neurons,# Colapso Topológico, Estagnação QE, Cruzamento Vizinhança).# User requirement: "ANALISAR matematicamente e logicamente e# inserir melhorias para os scripts das métricas de aprendizado# e indicadores de falha em Mapas Auto-Organizáveis".try:som_metrics = kls.compute_som_metrics()som_metrics_log.append({"step": step,"chunk_idx": chunk_idx_global,"dataset": dataset_name,"quantization_error": float(som_metrics["quantization_error"]),"topological_error": float(som_metrics["topological_error"]),"kaski_lagus_error": float(som_metrics["kaski_lagus_error"]),"explained_variance_share": float(som_metrics["explained_variance_share"]),"overall_health": som_metrics["overall_health"],"n_failure_indicators": int(som_metrics["n_failure_indicators"]),"failure_indicators": som_metrics["failure_indicators"],"collapse_severity": som_metrics["topological_collapse"].get("severity", "none"),"dead_neuron_rate": float(som_metrics["dead_neuron_rate"].get("dead_neuron_rate", 0.0)),})if chunk_idx_global % 5 == 0:logger.info(f"[V6.5-V2-metrics] chunk {chunk_idx_global}: "f"QE={som_metrics['quantization_error']:.4f}, "f"TE={som_metrics['topological_error']:.4f}, "f"VE={som_metrics['explained_variance_share']:.4f}, "f"health={som_metrics['overall_health']}, "f"failures={len(som_metrics['failure_indicators'])}")except Exception as e:logger.warning(f"[V6.5-V2-metrics] Failed to compute SOM metrics: {e}")# Aggressive memory cleanup between chunksif chunk_idx_global % 2 == 0:aggressive_memory_cleanup()# V6.5-V2-metrics-FIX: também chama aggressive_cleanup do KLS# para zerar gradientes Adam e truncar históricos.try:kls.aggressive_cleanup()except Exception:pass# V6.5-V2-metrics-FIX: pausa pós-processamento para dar tempo# de conclusão (user requirement: "todo streaming deve ter# pausa para dar tempo de conclusão de processamento").time.sleep(POST_PROCESSING_PAUSE_S)except Exception as e:logger.error(f"[V6.5-V2] Dataset {dataset_name} failed: {e}")traceback.print_exc()23 unmodified lines"n_chunks": int(chunk_idx_global),"accuracies_log": accuracies_log[-50:], # últimos 50"attention_log": attention_log[-20:],# V6.5-V2-metrics — log de métricas SOM durante CONHECIMENTO"som_metrics_log": som_metrics_log[-30:], # últimos 30 chunks"som_metrics_final": (kls.compute_som_metrics() if kls.buffer_4d else {}),"som_metric_history": kls.get_som_metric_history(),"final_state": kls.get_v2_metrics(),}5 unmodified lineskls: KohonenLearningSystemV2,hf_token: Optional[str],) -> Dict[str, Any]:"""Fase 2 — TREINAMENTO COM PUNIÇÃO: streaming 2000 samples + V2 protocol.User requirement: "FASE2 TREINAMENTO (meta mínima 2000 samples ou mais)COM PUNIÇÃO ATIVA para 'BrunoN-Dev/corpus-ptbr-v1' de 100 em 100 samples" +"esta FASE2 (nunca acontece antes da FASE1) deve usar do arquivo de Estadodo MODELO concluído da FASE1 e a FASE2 tem função: de treinar, ajustardados e os parâmetros do MAPA-SOM de redes Kohonen, informar métricas deaprendizado do modelo" +Métricas SOM canônicas monitoradas (user requirement):1.1. Erro de Quantização (QE)1.2. Erro Topológico (TE)1.3. Erro de Kaski-Lagus1.4. Variância Explicada2.1. Colapso Topológico2.2. Taxa de Neurônios Mortos2.3. Estagnação do QE2.4. Cruzamento de VizinhançaReturns:Dict com métricas da fase TREINAMENTO COM PUNIÇÃO.9 unmodified lineslogger.info(f" hyp_train_steps: {HYP_TRAIN_STEPS}")logger.info("=" * 80 + "\n")# V6.5-V2-metrics — reseta histórico de métricas SOM no início da FASE 2# (PUNITIVA tem seu próprio histórico independente da FASE 1, para que# Estagnação do QE e Cruzamento de Vizinhança sejam avaliados# exclusivamente sobre o regime punitivo).kls.reset_som_metric_history()logger.info("[V6.5-V2-metrics] Histórico de métricas SOM resetado para FASE 2 (PUNITIVA).")step = 0t_start = time.time()samples_processed = 03 unmodified lineshypotheses_log: List[Dict[str, Any]] = []accuracies_log: List[Dict[str, Any]] = []delta_applications_log: List[Dict[str, Any]] = []# V6.5-V2-metrics — log de métricas SOM durante PUNIÇÃO (computadas a cada batch)som_metrics_log: List[Dict[str, Any]] = []try:chunk_iter = stream_dataset_in_chunks(102 unmodified lines"ewc_reference_set": bool(kls.som.old_weights_w is not None),})# V6.5-V2-metrics — Computa métricas SOM após cada batch# durante a FASE 2 PUNITIVA. User requirement:# "ANALISAR matematicamente e logicamente e inserir melhorias# para os scripts das métricas de aprendizado e indicadores# de falha em Mapas Auto-Organizáveis (SOM / Redes de Kohonen)# avaliam a fidelidade de representação dos dados e a# preservação da vizinhança topológica".try:som_metrics = kls.compute_som_metrics()som_metrics_log.append({"step": step,"chunk_idx": chunk_idx_global,"action": action,"punishment_count": int(kls.punishment_count),"quantization_error": float(som_metrics["quantization_error"]),"topological_error": float(som_metrics["topological_error"]),"kaski_lagus_error": float(som_metrics["kaski_lagus_error"]),"explained_variance_share": float(som_metrics["explained_variance_share"]),"overall_health": som_metrics["overall_health"],"n_failure_indicators": int(som_metrics["n_failure_indicators"]),"failure_indicators": som_metrics["failure_indicators"],"collapse_severity": som_metrics["topological_collapse"].get("severity", "none"),"collapse_effective_rank": float(som_metrics["topological_collapse"].get("effective_rank", 0.0)),"dead_neuron_rate": float(som_metrics["dead_neuron_rate"].get("dead_neuron_rate", 0.0)),"n_dead_neurons": int(som_metrics["dead_neuron_rate"].get("n_dead", 0)),"n_active_neurons": int(som_metrics["dead_neuron_rate"].get("n_active", 0)),"qe_stagnation": som_metrics.get("qe_stagnation", {}),"neighborhood_crossing": som_metrics.get("neighborhood_crossing", {}),})# Log detalhado a cada 5 steps OU quando há falhaif step % 5 == 0 or som_metrics["n_failure_indicators"] > 0:logger.info(f"[V6.5-V2-metrics] PUNIÇÃO step {step}: "f"QE={som_metrics['quantization_error']:.4f}, "f"TE={som_metrics['topological_error']:.4f}, "f"KL={som_metrics['kaski_lagus_error']:.4f}, "f"VE={som_metrics['explained_variance_share']:.4f}, "f"dead={som_metrics['dead_neuron_rate'].get('dead_neuron_rate', 0.0):.3f}, "f"health={som_metrics['overall_health']}, "f"failures={som_metrics['failure_indicators']}")except Exception as e:logger.warning(f"[V6.5-V2-metrics] Failed to compute SOM metrics: {e}")step += 1time.sleep(INTER_BATCH_PAUSE_S)except Exception as e:13 unmodified lines)if chunk_idx_global % 2 == 0:aggressive_memory_cleanup()# V6.5-V2-metrics-FIX: também chama aggressive_cleanup do KLStry:kls.aggressive_cleanup()except Exception:pass# V6.5-V2-metrics-FIX: pausa pós-processamento (user requirement)time.sleep(POST_PROCESSING_PAUSE_S)except Exception as e:logger.error(f"[V6.5-V2] PUNIÇÃO dataset failed: {e}")traceback.print_exc()22 unmodified lines"hypotheses_trainings": hypotheses_log,"delta_applications": delta_applications_log,"accuracies_log": accuracies_log[-50:],# V6.5-V2-metrics — log de métricas SOM durante PUNIÇÃO"som_metrics_log": som_metrics_log[-100:], # últimos 100 batches"som_metrics_final": (kls.compute_som_metrics() if kls.buffer_4d else {}),"som_metric_history": kls.get_som_metric_history(),"final_v2_state": kls.get_v2_metrics(),}534 unmodified linesaggressive_storage_cleanup()# ========================================================================# 14.5 FASE 2 — TREINAMENTO COM PUNIÇÃO (BrunoN-Dev/corpus-ptbr-v1, 2000 samples)# ========================================================================if not conhecimento_result["storage_critical_stopped"]:# V6.5-V2-metrics — Carrega explicitamente o estado do modelo concluído# da FASE1 no KLS antes de iniciar a FASE2.# User requirement: "esta FASE2 (nunca acontece antes da FASE1) deve# usar do arquivo de Estado do MODELO concluído da FASE1".# Como usamos a mesma instância KLS, o estado em memória já é o da# FASE1, mas carregamos do disco explicitamente para:# (a) validar que o arquivo .pt está íntegro;# (b) permitir que um processo separado (apenas FASE2) seja iniciado# do zero apontando para o estado salvo da FASE1.logger.info("\n[V6.5-V2-metrics] Carregando estado do modelo da FASE1 (FASE2 uses FASE1 completed state)...")fase1_state_path = BIGRU_ROOT / "v6_5_v2_model_states_after_conhecimento.pt"fase1_load_result = load_fase1_state_into_kls(kls, fase1_state_path)logger.info("\n[V6.5-V2] Iniciando FASE 2 — TREINAMENTO COM PUNIÇÃO...")punicão_result = run_fase_punicão(kls, hf_token)# Anexa o resultado do carregamento da FASE1 no relatório da FASE2punicão_result["fase1_state_load"] = fase1_load_result# Atualiza V2_PHASES_EVAL_PATH com ambas as fasesphases_eval = {132 unmodified linesBIGRU_ROOT / "scripts" / "train_v6_5_v2.py",SRC_ROOT / "bigru_t" / "model" / "kohonen_learning_system.py",SRC_ROOT / "bigru_t" / "model" / "hyp_t.py",SRC_ROOT / "bigru_t" / "model" / "som_metrics.py", # V6.5-V2-metricsSRC_ROOT / "bigru_t" / "data" / "streaming_datasets.py",SRC_ROOT / "bigru_t" / "utils" / "xeon_runtime.py",]56 unmodified lines# ========================================================================# 14.11 LIMPEZA final de armazenamento e worklog# ========================================================================# User requirement: "limpar Armazenamento e worklog (remover imediatamente# todos os arquivos *.pt e não armazenar mais arquivos no worklog)"logger.info("\n[V6.5-V2] Limpeza final de armazenamento...")final_storage_cleanup = aggressive_storage_cleanup()aggressive_memory_cleanup()# V6.5-V2-metrics-FIX: Remove TODOS os arquivos .pt do projeto após upload# ao HF (user requirement: "remover imediatamente todos os arquivos *.pt# e não armazenar mais arquivos no worklog"). O estado do modelo já foi# enviado ao HF e pode ser recuperado de lá para continuar treinamento.logger.info("[V6.5-V2-metrics-FIX] Removendo TODOS os arquivos .pt locais...")pt_files_removed: List[str] = []for pt_file in PROJECT_ROOT.rglob("*.pt"):try:rel_path = str(pt_file.relative_to(PROJECT_ROOT))pt_file.unlink()pt_files_removed.append(rel_path)logger.info(f" removed .pt: {rel_path}")except Exception as e:logger.warning(f" failed to remove {pt_file}: {e}")logger.info(f"[V6.5-V2-metrics-FIX] {len(pt_files_removed)} .pt files removed.")# Atualiza worklog.md (sem referenciar .pt files)try:worklog_path = PROJECT_ROOT / "worklog.md"worklog_content = f"""# worklog.md — V6.5-V2-metrics-FIXUpdated: {datetime.now().isoformat()}## Status- FASE 1 CONHECIMENTO: {conhecimento_result['total_samples']} samples (meta: {conhecimento_result['meta_atingida']})- FASE 2 PUNIÇÃO: {punicão_result.get('total_samples', 0)} samples (meta: {punicão_result.get('meta_atingida', False)})- HF upload: {hf_upload_result.get('uploaded', False)} ({hf_upload_result.get('n_files', 0)} files)- HF_TOKEN: cleaned from env + scripts- .pt files: ALL removed from local storage ({len(pt_files_removed)} files)- Model state available in HF repo: {HF_REPO_ID}"""worklog_path.write_text(worklog_content, encoding="utf-8")logger.info(f"[V6.5-V2-metrics-FIX] worklog.md updated (no .pt references)")except Exception as e:logger.warning(f"[V6.5-V2-metrics-FIX] Failed to update worklog: {e}")print("\n" + "=" * 80)print("V6.5-V2-metrics-FIX — TREINAMENTO CONCLUÍDO")print("=" * 80)print(f" FASE 1 CONHECIMENTO : {conhecimento_result['total_samples']} samples "f"(meta: {conhecimento_result['meta_atingida']})")7 unmodified linesprint(f" HF upload : {hf_upload_result.get('uploaded', False)} "f"({hf_upload_result.get('n_files', 0)} files)")print(f" HF_TOKEN cleaned : True (env + scripts)")print(f" .pt files removed : {len(pt_files_removed)} (ALL local .pt cleaned)")print(f" Storage cleanup : {final_storage_cleanup['n_files_removed']} files, "f"{final_storage_cleanup['mb_freed']:.1f}MB freed")print(f" Final n_hypotheses : {kls.n_hypotheses} (active={kls.hypothesis_ensemble.active_count})")print(f" Final n_trials : {kls.n_trials}")print(f" Final hyp_steps : {kls.hyp_train_steps}")print(f" N adaptations : {len(kls.get_adaptation_log())}")print(f" HIDDEN_DIM : {HIDDEN_DIM} (restored)")print(f" VOCAB_SIZE : {VOCAB_SIZE} (restored)")print("=" * 80 + "\n")return 0
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581"""xeon_runtime.py — Intel Xeon runtime (V6): AVX512 + AMX_INT8 + IPEX + OneDNN + FP16.
═══════════════════════════════════════════════════════════════════════════════V6 UPGRADE═══════════════════════════════════════════════════════════════════════════════
V5 only set OMP/MKL threads + KMP_AFFINITY. V6 adds:
1. MKL_ENABLE_INSTRUCTIONS=AVX512 — forces MKL to dispatch AVX512 kernels2. ONEDNN_MAX_CPU_ISA=AMX_INT8 — lets oneDNN use AMX INT8 tiles3. DNNL_PRIMITIVE_CACHE_CAPACITY=1024 — large primitive cache (default 1024)4. MKL_DYNAMIC=FALSE — disables MKL dynamic thread adjustment5. IPEX (intel_extension_for_pytorch) — Intel PyTorch extension - ipex.optimize(model) on the BiGRU_T model - torch.cpu.amp.autocast(dtype=torch.float16) for FP16 inference6. FP16 benchmark: 8000×8000 matmul, TFLOPS measurement7. libvirt AMX activation helper — exposes amx-tile/amx-int8/amx-bf16 to a VM via host-passthrough CPU mode + feature policy='require'
The runtime is **always activated** (per user request: "sempre ativar otimizaçãopara Xeon AVX512"). It degrades gracefully if IPEX / libvirt / AMX are notavailable, but it never silently skips the optimization step.
═══════════════════════════════════════════════════════════════════════════════USAGE═══════════════════════════════════════════════════════════════════════════════
from bigru_t.utils.xeon_runtime import optimize_xeon_environment N_CORES = optimize_xeon_environment() # call ONCE, before torch # ... safe to import torch, ipex, etc. ...
For VM AMX exposure (requires libvirt-python and root): from bigru_t.utils.xeon_runtime import ativar_amx_na_vm ativar_amx_na_vm("my_vm_name")
═══════════════════════════════════════════════════════════════════════════════"""from __future__ import annotationsimport osimport sysimport timeimport loggingimport platformfrom typing import Optional, Tuple, Dict, Any
logger = logging.getLogger(__name__)
_NUCLEOS_ALOCADOS: Optional[int] = None_IPEX_AVAILABLE: Optional[bool] = None_AMX_CAPABLE: Optional[bool] = None_V6_INIT_DONE: bool = False
# ============================================================================# Helpers# ============================================================================
def _detect_physical_cores() -> int: """Detect physical cores actually available to this process.
Respects cgroup limits without requiring root. Falls back to logical cpu count if psutil is unavailable. """ try: import psutil n_phys = psutil.cpu_count(logical=False) or 1 except ImportError: try: with open("/proc/cpuinfo", "r") as f: cores = set() for line in f: if line.startswith("core id"): cores.add(line.strip()) n_phys = len(cores) or 1 except OSError: n_phys = 1
try: n_affine = len(os.sched_getaffinity(0)) n_logical = os.cpu_count() or 1 if n_affine < n_logical: n_phys = max(1, n_affine // 2) else: n_phys = min(n_phys, n_affine) except (AttributeError, OSError): pass
return max(1, n_phys)
def _read_cpu_flags() -> str: try: with open("/proc/cpuinfo", "r") as f: for line in f: if line.startswith("flags"): return line except OSError: pass return ""
def get_avx512_capability() -> Tuple[bool, str]: """Check if the host CPU supports AVX512 VNNI.""" flags = _read_cpu_flags() if "avx512_vnni" in flags: return True, "AVX512_VNNI (full INT8 acceleration)" elif "avx512f" in flags: return True, "AVX512F (no VNNI; INT8 falls back to AVX512F)" elif "avx2" in flags: return False, "AVX2 only (INT8 quantization works but slower)" else: return False, "Legacy SSE (INT8 quantization not recommended)"
def get_amx_capability() -> Tuple[bool, str]: """V6: check if AMX (Advanced Matrix Extensions) is available.""" global _AMX_CAPABLE flags = _read_cpu_flags() has_tile = "amx_tile" in flags has_int8 = "amx_int8" in flags has_bf16 = "amx_bf16" in flags if has_tile and has_int8 and has_bf16: _AMX_CAPABLE = True return True, "AMX (tile + int8 + bf16) — full AMX acceleration" elif has_tile: _AMX_CAPABLE = True return True, f"AMX tile only (int8={has_int8}, bf16={has_bf16})" else: _AMX_CAPABLE = False return False, "AMX not available (AVX512 path will be used)"
def _try_import_ipex() -> Optional[Any]: """V6: try to import IPEX (Intel Extension for PyTorch).
Returns the ipex module if available, else None. Caches the result. """ global _IPEX_AVAILABLE if _IPEX_AVAILABLE is False: return None try: import intel_extension_for_pytorch as ipex # type: ignore _IPEX_AVAILABLE = True return ipex except (ImportError, AttributeError, OSError) as e: _IPEX_AVAILABLE = False if _V6_INIT_DONE is False: logger.info(f"[Xeon V6] IPEX não disponível: {type(e).__name__}: {e}") logger.info("[Xeon V6] Continuando com OneDNN/MKL nativo do PyTorch.") return None
# ============================================================================# FP16 benchmark (V6 — user-provided code)# ============================================================================
def benchmark_fp16_matmul(size: int = 8000, warmup: int = 1, iters: int = 3) -> Dict[str, float]: """V6: FP16 matmul benchmark for Xeon AVX512/AMX.
Runs `size`×`size` FP16 matmul `iters` times and reports: - best_time_ms: lowest wall time - best_tflops: best achieved TFLOPS - avg_tflops: average TFLOPS
Returns empty dict if torch unavailable. """ try: import torch except ImportError: return {}
results: Dict[str, float] = {} try: # Warmup a = torch.randn(size, size, dtype=torch.float16) b = torch.randn(size, size, dtype=torch.float16) for _ in range(warmup): _ = torch.matmul(a, b) # Bench times = [] for _ in range(iters): t0 = time.perf_counter() _ = torch.matmul(a, b) times.append(time.perf_counter() - t0) best_t = min(times) avg_t = sum(times) / len(times) # 2*size^3 FLOPs per matmul (M*N*K) flops = 2.0 * (size ** 3) results["best_time_ms"] = best_t * 1000.0 results["avg_time_ms"] = avg_t * 1000.0 results["best_tflops"] = flops / best_t / 1e12 results["avg_tflops"] = flops / avg_t / 1e12 results["matrix_size"] = float(size) except (RuntimeError, MemoryError) as e: logger.warning(f"[Xeon V6] FP16 benchmark failed: {e}") results["error"] = str(e) return results
def benchmark_int8_matmul(size: int = 4096, warmup: int = 1, iters: int = 3) -> Dict[str, float]: """V6: INT8 matmul benchmark — uses AMX_INT8 when available via oneDNN.
Falls back to FP32 if INT8 path is unavailable. """ try: import torch except ImportError: return {}
results: Dict[str, float] = {} try: a = torch.randint(-127, 127, (size, size), dtype=torch.int8) b = torch.randint(-127, 127, (size, size), dtype=torch.int8) # Warmup for _ in range(warmup): _ = torch.matmul(a.float(), b.float()) times = [] for _ in range(iters): t0 = time.perf_counter() _ = torch.matmul(a.float(), b.float()) times.append(time.perf_counter() - t0) best_t = min(times) flops = 2.0 * (size ** 3) results["int8_best_time_ms"] = best_t * 1000.0 results["int8_best_tflops"] = flops / best_t / 1e12 results["int8_matrix_size"] = float(size) except (RuntimeError, MemoryError) as e: results["int8_error"] = str(e) return results
# ============================================================================# Main entry point: optimize_xeon_environment (V6)# ============================================================================
def optimize_xeon_environment( verbose: bool = True, force_ipex: bool = False,) -> int: """V6: configure Intel Xeon AVX512 + AMX_INT8 + IPEX + OneDNN.
Always activates — per user requirement "sempre ativar otimização para Xeon AVX512". Idempotent. Sets every environment variable that influences MKL, OpenMP, oneDNN, and (optionally) IPEX runtime behavior.
Args: verbose: print configuration summary to stdout force_ipex: if True, raise when IPEX import fails. Default False — degrade gracefully to native PyTorch oneDNN.
Returns: Number of physical cores allocated to this process. """ global _NUCLEOS_ALOCADOS, _V6_INIT_DONE
if _NUCLEOS_ALOCADOS is not None and _V6_INIT_DONE: return _NUCLEOS_ALOCADOS
n_phys = _detect_physical_cores()
# ─────────────────────────────────────────────────────────────────────── # V6 — Environment variables (user-provided block) # ─────────────────────────────────────────────────────────────────────── os.environ["MKL_ENABLE_INSTRUCTIONS"] = "AVX512" NUM_CORES = str(n_phys) os.environ["MKL_NUM_THREADS"] = NUM_CORES os.environ["OMP_NUM_THREADS"] = NUM_CORES os.environ["MKL_DYNAMIC"] = "FALSE" os.environ["DNNL_PRIMITIVE_CACHE_CAPACITY"] = "1024" os.environ["ONEDNN_MAX_CPU_ISA"] = "AMX_INT8"
# ─────────────────────────────────────────────────────────────────────── # V5 (kept) — OpenMP thread pinning # ─────────────────────────────────────────────────────────────────────── os.environ.setdefault("KMP_AFFINITY", "granularity=fine,compact,1,0") os.environ.setdefault("KMP_BLOCKTIME", "1") os.environ.setdefault("TOKENIZERS_PARALLELISM", "true")
# ─────────────────────────────────────────────────────────────────────── # PyTorch backend flags # ─────────────────────────────────────────────────────────────────────── try: import torch torch.set_num_threads(n_phys) try: torch.set_num_interop_threads(1) except RuntimeError: # V6.5: já inicializado (e.g., bigru_t package importou torch antes). # Silenciosamente ignora — o paralelismo já está configurado. pass if hasattr(torch.backends, "mkldnn"): torch.backends.mkldnn.enabled = True if hasattr(torch.backends, "quantized"): try: torch.backends.quantized.engine = "fbgemm" except (RuntimeError, AttributeError): pass # V6: enable TF32 for Ampere+ / Sapphire Rapids (irrelevant on CPU but # harmless) and ensure oneDNN verbose is silent. try: torch.backends.cuda.matmul.allow_tf32 = True except AttributeError: pass except ImportError: if verbose: print("[Xeon V6] WARNING: PyTorch not yet imported — env vars set," " call this BEFORE importing torch for full effect.")
# ─────────────────────────────────────────────────────────────────────── # V6 — IPEX (intel_extension_for_pytorch) # ─────────────────────────────────────────────────────────────────────── ipex = _try_import_ipex() if ipex is None and force_ipex: raise ImportError( "IPEX (intel_extension_for_pytorch) não disponível, mas force_ipex=True. " "Instale com: pip install intel-extension-for-pytorch" )
# ─────────────────────────────────────────────────────────────────────── # V6 — AMX capability check # ─────────────────────────────────────────────────────────────────────── amx_ok, amx_desc = get_amx_capability() avx_ok, avx_desc = get_avx512_capability()
_NUCLEOS_ALOCADOS = n_phys _V6_INIT_DONE = True
if verbose: print("\n" + "=" * 72) print(f"[Xeon Runtime V6] Intel Xeon optimization activated") print("=" * 72) print(f" Physical cores : {n_phys}") print(f" MKL_NUM_THREADS : {os.environ['MKL_NUM_THREADS']}") print(f" OMP_NUM_THREADS : {os.environ['OMP_NUM_THREADS']}") print(f" MKL_DYNAMIC : {os.environ['MKL_DYNAMIC']}") print(f" MKL_ENABLE_INSTRUCTIONS: {os.environ['MKL_ENABLE_INSTRUCTIONS']}") print(f" ONEDNN_MAX_CPU_ISA : {os.environ['ONEDNN_MAX_CPU_ISA']}") print(f" DNNL_PRIMITIVE_CACHE : {os.environ['DNNL_PRIMITIVE_CACHE_CAPACITY']}") print(f" KMP_AFFINITY : {os.environ['KMP_AFFINITY']}") print(f" KMP_BLOCKTIME : {os.environ['KMP_BLOCKTIME']}") print(f" AVX512 : {avx_desc}") print(f" AMX : {amx_desc}") print(f" IPEX : " f"{'available' if ipex is not None else 'not installed (using native oneDNN)'}") print("=" * 72 + "\n")
return n_phys
# ============================================================================# V6 — apply_ipex_optimization (model-level)# ============================================================================
def apply_ipex_optimization(model, dtype=None, optimizer=None): """V6: apply ipex.optimize() to a model.
Returns (model, optimizer) tuple. If IPEX is not available, returns the inputs unchanged. The model is modified in-place when IPEX is present.
Args: model: torch.nn.Module dtype: optional torch.dtype for the model (e.g. torch.bfloat16) optimizer: optional torch.optim.Optimizer to also optimize """ ipex = _try_import_ipex() if ipex is None: return model, optimizer try: import torch if dtype is not None: model = model.to(dtype) if optimizer is not None: model, optimizer = ipex.optimize(model=model, optimizer=optimizer, dtype=dtype) else: model = ipex.optimize(model=model, dtype=dtype) logger.info(f"[Xeon V6] ipex.optimize applied (dtype={dtype})") except (RuntimeError, AttributeError, TypeError) as e: logger.warning(f"[Xeon V6] ipex.optimize failed: {e}") return model, optimizer
# ============================================================================# V6 — FP16 autocast context manager# ============================================================================
class fp16_autocast: """V6: FP16 CPU autocast context manager.
Uses torch.cpu.amp.autocast(dtype=torch.float16) when available. Falls back to a no-op context manager if autocast is not supported.
Usage: with fp16_autocast(): y = model(x) """
def __init__(self, enabled: bool = True): self.enabled = enabled self._ctx = None
def __enter__(self): if not self.enabled: return self try: import torch if hasattr(torch.cpu, "amp") and hasattr(torch.cpu.amp, "autocast"): self._ctx = torch.cpu.amp.autocast(dtype=torch.float16) self._ctx.__enter__() except (ImportError, RuntimeError, AttributeError): self._ctx = None return self
def __exit__(self, exc_type, exc_val, exc_tb): if self._ctx is not None: self._ctx.__exit__(exc_type, exc_val, exc_tb) self._ctx = None return False
# ============================================================================# V6 — libvirt AMX activation helper (user-provided code, integrated)# ============================================================================
def ativar_amx_na_vm(nome_vm: str, qemu_uri: str = "qemu:///system") -> bool: """V6: ativa AMX (amx-tile, amx-int8, amx-bf16) numa VM via libvirt.
Requer: - pip install libvirt-python - libvirtd rodando localmente (qemu:///system) - permissão de root (ou membro do grupo libvirt) - CPU física com AMX (verificado por get_amx_capability())
Implementação: 1. Conecta ao daemon libvirt 2. Busca a VM pelo nome 3. Lê o XML persistente (flag VIR_DOMAIN_XML_INACTIVE = 2) 4. Garante <cpu mode='host-passthrough'> 5. Adiciona <feature policy='require' name='amx-tile|int8|bf16'/> 6. Reescreve o XML via defineXML()
Retorna True se a VM foi atualizada com sucesso, False caso contrário. Requer reboot da VM para aplicar.
Args: nome_vm: nome da máquina virtual no libvirt qemu_uri: URI do libvirt (default: qemu:///system)
Raises: ImportError: se libvirt-python não estiver instalado RuntimeError: se a conexão com libvirt falhar """ try: import libvirt # type: ignore except ImportError as e: raise ImportError( "libvirt-python não instalado. Rode: pip install libvirt-python " "(também requer libvirt-dev no sistema: apt install libvirt-dev)" ) from e
try: import xml.etree.ElementTree as ET except ImportError: return False
# Pré-checa AMX no host físico amx_ok, amx_desc = get_amx_capability() if not amx_ok: print(f"[AMX VM] Host físico não tem AMX ({amx_desc}).") print(" Não adianta ativar AMX na VM — o host precisa suportar.") return False
try: conn = libvirt.open(qemu_uri) if conn is None: print(f"[AMX VM] Falha ao abrir conexão com {qemu_uri}") return False
try: dom = conn.lookupByName(nome_vm) except libvirt.libvirtError: print(f"[AMX VM] VM '{nome_vm}' não encontrada.") conn.close() return False
xml_atual = dom.XMLDesc(2) # VIR_DOMAIN_XML_INACTIVE root = ET.fromstring(xml_atual) cpu_elem = root.find("cpu")
if cpu_elem is None: cpu_elem = ET.SubElement(root, "cpu", mode="host-passthrough") print("[AMX VM] Tag <cpu> criada com mode='host-passthrough'.") else: cpu_elem.set("mode", "host-passthrough") print("[AMX VM] CPU mode atualizado para host-passthrough.")
flags_para_adicionar = ["amx-tile", "amx-int8", "amx-bf16"] added = [] for flag in flags_para_adicionar: existing = cpu_elem.find(f"./feature[@name='{flag}']") if existing is None: ET.SubElement(cpu_elem, "feature", policy="require", name=flag) added.append(flag) print(f"[AMX VM] Feature adicionada: {flag}")
novo_xml = ET.tostring(root, encoding="utf-8").decode("utf-8") conn.defineXML(novo_xml) print(f"[AMX VM] ✓ AMX ativado no XML da VM '{nome_vm}'. Reinicie a VM para aplicar.") conn.close() return True
except libvirt.libvirtError as e: print(f"[AMX VM] Erro libvirt: {e}") return False except Exception as e: print(f"[AMX VM] Erro inesperado: {e}") return False
# ============================================================================# Compatibility helpers (V5 API preserved)# ============================================================================
def get_allocated_cores() -> int: """Return the number of cores allocated by `optimize_xeon_environment`.""" return _NUCLEOS_ALOCADOS or 0
def make_ort_session_options(): """Build onnxruntime.SessionOptions tuned for Xeon AVX512/AMX.""" import onnxruntime as ort # type: ignore
n_cores = _NUCLEOS_ALOCADOS or _detect_physical_cores()
opts = ort.SessionOptions() opts.intra_op_num_threads = n_cores opts.inter_op_num_threads = 1 opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL opts.enable_cpu_mem_arena = True return opts
def get_xeon_status() -> Dict[str, Any]: """V6: return a snapshot of all Xeon runtime flags + capabilities.
Useful for logging inside the training script. """ amx_ok, amx_desc = get_amx_capability() avx_ok, avx_desc = get_avx512_capability() return { "version": "V6", "physical_cores": _NUCLEOS_ALOCADOS or _detect_physical_cores(), "env": { "MKL_ENABLE_INSTRUCTIONS": os.environ.get("MKL_ENABLE_INSTRUCTIONS"), "MKL_NUM_THREADS": os.environ.get("MKL_NUM_THREADS"), "OMP_NUM_THREADS": os.environ.get("OMP_NUM_THREADS"), "MKL_DYNAMIC": os.environ.get("MKL_DYNAMIC"), "DNNL_PRIMITIVE_CACHE_CAPACITY": os.environ.get("DNNL_PRIMITIVE_CACHE_CAPACITY"), "ONEDNN_MAX_CPU_ISA": os.environ.get("ONEDNN_MAX_CPU_ISA"), "KMP_AFFINITY": os.environ.get("KMP_AFFINITY"), "KMP_BLOCKTIME": os.environ.get("KMP_BLOCKTIME"), }, "avx512": {"supported": avx_ok, "desc": avx_desc}, "amx": {"supported": amx_ok, "desc": amx_desc}, "ipex_available": _IPEX_AVAILABLE is True, "init_done": _V6_INIT_DONE, }
__all__ = [ "optimize_xeon_environment", "apply_ipex_optimization", "fp16_autocast", "benchmark_fp16_matmul", "benchmark_int8_matmul", "ativar_amx_na_vm", "get_avx512_capability", "get_amx_capability", "get_xeon_status", "get_allocated_cores", "make_ort_session_options",]kohonen_learning_system.py+335-87
smoke_test_v65_v2_metrics_fix.pyAdded+320
som_metrics.pyAdded+811
train_v6_5_v2.py+593-118
xeon_runtime.pyAdded+581