Delete src/bigru_t/model/kohonen_refactored/kohonen_learning_system.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671"""kohonen_learning_system.py — V6.4 (refatoração matemática completa)
Implementação CANÔNICA do Sistema de Aprendizado Kohonen 4D fornecida pelousuário, com análise matemática formal e 2 correções de bugs críticos.
============================================================================ANÁLISE MATEMÁTICA FORMAL============================================================================
1) text_to_4d_vector(text, ..., time_step, T_max): ----------------------------------------------- Tokenização BBPE: ids = BBPE_encode(text, max_len=seq_len) → [seq_len] Embedding: E = Embedding(ids) → [seq_len, D] PE sinusoidal: PE = sin/cos(pos · exp(-2k·log(10000)/D)) Fusão: F = E + PE → [seq_len, D] Centralização: F_c = F - mean(F, dim=0) → [seq_len, D] SVD: F_c = U · S · V^T (V: [D, D] ortogonal) Projeção 3D: coords_3d = F_c · V[:3,:]^T → [seq_len, 3] Centróide: xyz = mean(coords_3d, dim=0) → [3] Coordenada temporal: w = time_step / T_max ∈ [0, 1] (LINEAR) Saída: vec_4d = [x, y, z, w] → [4]
Nota (V6.4): w é LINEAR no tempo (diferente de sigmoid(||xyz||)). Isto permite que o SOM organize neurônios ao longo do eixo temporal, capturando a sequência absoluta de amostras — útil para deteção de drift e consolidação incremental (EWC).
2) KohonenSOM4D: -------------- Grid: W ∈ ℝ^(I×J×K×L×4), default (6,6,6,4) = 864 neurônios BMU: bmu = argmin_{i,j,k,l} ||W[i,j,k,l] - x||² (Euclidiana ℝ⁴) Vizinhança (Gaussiana 4D): Λ(d, σ) = exp(-d² / (2σ²)) d² = Δi² + Δj² + Δk² + Δl² (distância quadrada no grid 4D) Update (Kohonen): ΔW = α · Λ · (x - W) (competitivo + cooperativo) Decaimento: σ_t = σ₀ · exp(-t/1000) (vizinhança encolhe rápido) α_t = α₀ · exp(-t/2000) (LR decai mais lento) EWC (apenas na 4ª dimensão w): L_ewc = (λ/2) · Σ F_i · (W_w,i - W*_w,i)² ∂L_ewc/∂W_w = λ · F · (W_w - W*_w) Aplicado como: update[..., 3] -= λ · F · (W_w - W*_w) Fisher (aproximação como erro quadrado): F_i = mean((x_w - W_w,i)²) sobre samples pré-punição Acumulado apenas quando: (a) punishment_count == 0 (b) old_weights_w is None (ainda não consolidado) (c) Λ > 0.1 (neurônios próximos ao BMU)
3) HypothesisClassifier: ---------------------- 8 camadas FC: [in → 512 → 256 → 128 → 64 → 32 → 16 → 8] + ReLU Output: 8 → 1 (logit) Loss: BCEWithLogitsLoss Optimizer: Adam, lr=0.001 Epochs: 50 (sobre o buffer atual) Input: vetor de ativação SOM = distâncias ao grid flatten (864-dim para grid (6,6,6,4))
4) Punishment Protocol: --------------------- Histograma: bucketiza vec_4d[dim_choice] (default 'y', idx=1) check_training_start: max(histogram.values()) >= N_start → ready Avaliação: acc = correct / len(buffer) (correct = pred==label) Se acc < 1.0: punishment_count += 1 success_count = 0 Se punishment_count == 1: activate_hypothesis() (treina classifier) Se punishment_count == 2: set_ewc_reference() (consolida w via Fisher) required_new_samples = success_count * N (ou N se success==0) reset: training_ready=False, punishment=0, success=0, histogram cleared, buffers cleared Se acc == 1.0: punishment_count = 0 success_count += 1
5) PGVector NÃO É MAIS NECESSÁRIO (V6.4): --------------------------------------- O método find_bmu realiza a busca nearest-neighbor sobre o grid 4D, substituindo qualquer lookup pgvector externo. O SOM interno já armazena todo o conhecimento como pesos 4D, e find_bmu retorna o neurônio mais próximo em O(I·J·K·L) — equivalente a uma busca pgvector com indexação flat. Consequentemente, hyp_t.py NÃO consulta mais pgvector — a decisão de aplicar punição é delegada ao KohonenLearningSystem.
============================================================================BUGS CORRIGIDOS (V6.3 → mantidos em V6.4)============================================================================
BUG 1 (find_bmu): V6.3 corrigiu return prematuro com Ellipsis. V6.4: código do usuário já está limpo (unravel manual sem return prematuro). Mantido as-is.
BUG 2 (activate_hypothesis): backward tentava retropropagar através do embedding (via buffer_4d). Causava RuntimeError "Trying to backward through the graph a second time". FIX V6.4: detach+clone nos tensores de entrada do classifier, e cálculo do vetor de ativação SOM dentro de torch.no_grad(). O classifier treina apenas sobre seus próprios pesos (8 FC layers).
============================================================================"""from __future__ import annotations
import osimport mathimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom collections import defaultdict, Counterfrom typing import List, Tuple, Optional
# ============================================================================# Configuração da CPU – núcleos físicos# ============================================================================try: import psutil N_CORES = psutil.cpu_count(logical=False)except ImportError: N_CORES = os.cpu_count() // 2 if os.cpu_count() else 4if N_CORES: try: torch.set_num_threads(N_CORES) torch.set_num_interop_threads(N_CORES) except RuntimeError: pass # already initialized
# ============================================================================# Tokenizador BBPE simplificado# ============================================================================class SimpleBBPETokenizer: """Tokenizador BPE simplificado (nível de palavra).
Vocabulário especial: pad=0, eos=1, unk=2. Tokens comuns mapeados a partir do índice 3. """
def __init__(self, vocab_size: int = 16384): self.vocab_size = vocab_size self.token_to_id = {} self.id_to_token = {} self.pad_token = "<pad>" self.eos_token = "<eos>" self.unk_token = "<unk>" self.pad_id = 0 self.eos_id = 1 self.unk_id = 2 self._init_special_tokens()
def _init_special_tokens(self): self.token_to_id[self.pad_token] = self.pad_id self.token_to_id[self.eos_token] = self.eos_id self.token_to_id[self.unk_token] = self.unk_id self.id_to_token[self.pad_id] = self.pad_token self.id_to_token[self.eos_id] = self.eos_token self.id_to_token[self.unk_id] = self.unk_token
def fit(self, texts: List[str]): """Constrói vocabulário por frequência (top vocab_size-3 palavras).""" word_counts = Counter() for text in texts: words = text.split() word_counts.update(words) sorted_words = [w for w, _ in word_counts.most_common(self.vocab_size - 3)] for idx, word in enumerate(sorted_words, start=3): self.token_to_id[word] = idx self.id_to_token[idx] = word
def encode(self, text: str, max_length: int = 8) -> List[int]: """Encoda + append EOS + pad/trunca para max_length.""" words = text.split() ids = [self.token_to_id.get(w, self.unk_id) for w in words] ids.append(self.eos_id) if len(ids) > max_length: ids = ids[:max_length] else: ids += [self.pad_id] * (max_length - len(ids)) return ids
# ============================================================================# Codificação posicional e conversão texto → vetor 4D (com w temporal)# ============================================================================def positional_encoding(seq_len: int, hidden_dim: int) -> torch.Tensor: """PE sinusoidal clássico: PE[pos, 2k] = sin(pos·exp(-2k·log(10000)/D)), PE[pos, 2k+1] = cos(pos·exp(-2k·log(10000)/D)). """ pe = torch.zeros(seq_len, hidden_dim) position = torch.arange(0, seq_len, dtype=torch.float).unsqueeze(1) div_term = torch.exp( torch.arange(0, hidden_dim, 2).float() * (-math.log(10000.0) / hidden_dim) ) pe[:, 0::2] = torch.sin(position * div_term) pe[:, 1::2] = torch.cos(position * div_term) return pe
def text_to_4d_vector( text: str, tokenizer: SimpleBBPETokenizer, embedding: nn.Embedding, hidden_dim: int, seq_len: int, time_step: int, T_max: int = 10000,) -> torch.Tensor: """Converte sentença em vetor 4D (x, y, z, w), onde w = time_step / T_max.
Pipeline matemático: ids → Embedding → +PE → SVD(proj top-3) → centróide xyz w = time_step / T_max (LINEAR no tempo) vec_4d = concat(xyz, w) → [4] """ ids = tokenizer.encode(text, max_length=seq_len) input_ids = torch.tensor(ids).unsqueeze(0) word_emb = embedding(input_ids).squeeze(0) # (L, D) pe = positional_encoding(seq_len, hidden_dim) fused = word_emb + pe # (L, D)
# SVD para 3D mean_centered = fused - fused.mean(dim=0, keepdim=True) U, S, V = torch.linalg.svd(mean_centered, full_matrices=False) coords_3d = torch.mm(mean_centered, V[:3, :].t()) # (L, 3)
xyz_mean = coords_3d.mean(dim=0) # (3,) w = torch.tensor(time_step / T_max, dtype=torch.float) # valor temporal vec_4d = torch.cat([xyz_mean, w.unsqueeze(0)]).contiguous() return vec_4d
# ============================================================================# Mapa de Kohonen 4D com EWC (Fisher para w não-nulo)# ============================================================================class KohonenSOM4D: """Mapa Auto-Organizável 4D com EWC apenas na 4ª dimensão (w temporal).
Args: grid_shape: (I, J, K, L) — dimensões do grid 4D. alpha0: taxa de aprendizado inicial (α₀). sigma0: largura inicial da vizinhança (σ₀). lambda_ewc: peso da penalidade EWC (λ).
Atributos: weights: W ∈ ℝ^(I×J×K×L×4) — pesos dos neurônios. old_weights_w: W*_w ∈ ℝ^(I×J×K×L) — referência EWC (apenas w). fisher_w: F ∈ ℝ^(I×J×K×L) — informação de Fisher por neurônio (w). fisher_accum / fisher_count: acumuladores para cálculo de F. """
def __init__( self, grid_shape: Tuple[int, int, int, int], alpha0: float = 0.1, sigma0: float = 1.0, lambda_ewc: float = 0.01, ): self.I, self.J, self.K, self.L = grid_shape self.alpha0 = alpha0 self.sigma0 = sigma0 self.lambda_ewc = lambda_ewc self.t = 0
self.weights = torch.randn(self.I, self.J, self.K, self.L, 4) self.old_weights_w = None self.fisher_w = None self.fisher_accum = torch.zeros(self.I, self.J, self.K, self.L) self.fisher_count = torch.zeros(self.I, self.J, self.K, self.L)
def _neighborhood(self, bmu_idx): """Vizinhança Gaussiana 4D: d² = Δi² + Δj² + Δk² + Δl².""" i, j, k, l = bmu_idx II, JJ, KK, LL = torch.meshgrid( torch.arange(self.I).float(), torch.arange(self.J).float(), torch.arange(self.K).float(), torch.arange(self.L).float(), indexing="ij", ) dist_sq = (II - i) ** 2 + (JJ - j) ** 2 + (KK - k) ** 2 + (LL - l) ** 2 return dist_sq
def find_bmu(self, x: torch.Tensor) -> Tuple[int, int, int, int]: """Best Matching Unit: argmin ||W - x||² em ℝ⁴.
Substitui pgvector_lookup — busca nearest-neighbor flat sobre o grid. """ dist = torch.sum((self.weights - x.view(1, 1, 1, 1, 4)) ** 2, dim=-1) flat_idx = torch.argmin(dist).item() i = flat_idx // (self.J * self.K * self.L) rest = flat_idx % (self.J * self.K * self.L) j = rest // (self.K * self.L) rest = rest % (self.K * self.L) k = rest // self.L l = rest % self.L return (i, j, k, l)
def update_weights(self, x: torch.Tensor, bmu_idx, accumulate_fisher=False): """Update Kohonen: ΔW = α·Λ·(x - W) + penalidade EWC em w.
Args: x: tensor [4] — amostra 4D. bmu_idx: (i, j, k, l) — índice do BMU. accumulate_fisher: se True, acumula (x_w - W_w)² nos Fisher accumulators. """ dist_sq = self._neighborhood(bmu_idx) sigma = self.sigma0 * math.exp(-self.t / 1000) alpha = self.alpha0 * math.exp(-self.t / 2000) h = torch.exp(-dist_sq / (2 * sigma ** 2))
delta = x - self.weights update = alpha * h.unsqueeze(-1) * delta
if self.old_weights_w is not None and self.fisher_w is not None: # Penalidade EWC apenas na 4ª dimensão (w) # ∂L_ewc/∂W_w = λ · F · (W_w - W*_w) → subtraído do update ewc_penalty = self.lambda_ewc * self.fisher_w * ( self.weights[..., 3] - self.old_weights_w ) update[..., 3] = update[..., 3] - ewc_penalty
self.weights = self.weights + update
if accumulate_fisher: # Acumula Fisher apenas em neurônios próximos ao BMU (Λ > 0.1) mask = h > 0.1 if mask.any(): diff_sq = (x[3] - self.weights[mask][..., 3]) ** 2 self.fisher_accum[mask] += diff_sq self.fisher_count[mask] += 1
self.t += 1
def finalize_fisher(self): """Fisher = mean((x_w - W_w)²) sobre samples acumuladas.""" cnt = self.fisher_count.clamp(min=1e-8) self.fisher_w = self.fisher_accum / cnt
def set_ewc_reference(self): """Consolida W_w como referência EWC e finaliza Fisher.""" self.old_weights_w = self.weights[..., 3].clone() self.finalize_fisher() self.fisher_accum.zero_() self.fisher_count.zero_()
# ------------------------------------------------------------------ # Métricas para monitoramento (V6.4) # ------------------------------------------------------------------ def get_metrics(self) -> dict: """Retorna métricas atuais do SOM para monitoramento.""" sigma_t = self.sigma0 * math.exp(-self.t / 1000) alpha_t = self.alpha0 * math.exp(-self.t / 2000) return { "t": int(self.t), "sigma_t": float(sigma_t), "alpha_t": float(alpha_t), "sigma0": float(self.sigma0), "alpha0": float(self.alpha0), "lambda_ewc": float(self.lambda_ewc), "grid_shape": [int(self.I), int(self.J), int(self.K), int(self.L)], "n_neurons": int(self.I * self.J * self.K * self.L), "has_ewc_reference": self.old_weights_w is not None, "fisher_w_mean": ( float(self.fisher_w.mean().item()) if self.fisher_w is not None else 0.0 ), "fisher_w_max": ( float(self.fisher_w.max().item()) if self.fisher_w is not None else 0.0 ), "fisher_accum_count": int(self.fisher_count.sum().item()), "weights_norm": float(self.weights.norm().item()), "weights_w_mean": float(self.weights[..., 3].mean().item()), }
# ============================================================================# Classificador de hipótese (8 camadas FC)# ============================================================================class HypothesisClassifier(nn.Module): """Classificador de hipótese: 8 camadas FC + ReLU + output logit.
Arquitetura: [input → 512 → 256 → 128 → 64 → 32 → 16 → 8] + ReLU + [8 → 1] (logit) Loss: BCEWithLogitsLoss """
def __init__(self, input_dim, hidden_dims=[512, 256, 128, 64, 32, 16, 8]): super().__init__() layers = [] prev = input_dim for h in hidden_dims: layers.append(nn.Linear(prev, h)) layers.append(nn.ReLU()) prev = h layers.append(nn.Linear(prev, 1)) self.net = nn.Sequential(*layers)
def forward(self, x): return self.net(x).squeeze(-1)
# ============================================================================# Sistema de aprendizado completo (com w temporal e condição de início por N)# ============================================================================class KohonenLearningSystem: """Pipeline integrado: tokenizer + embedding + SOM4D + classifier + punishment.
Args: vocab_size: tamanho do vocabulário BBPE (default 16384). hidden_dim: dimensão do embedding (default 1024). seq_len: comprimento máximo da sequência (default 8). som_grid: (I, J, K, L) — grid 4D do SOM (default (6, 6, 6, 4) = 864). alpha0, sigma0: hiperparâmetros do SOM. lambda_ewc: peso da penalidade EWC. N_start: threshold do histograma para iniciar treino. dim_choice: 'x' | 'y' | 'z' — dimensão usada no histograma. hypothesis_hidden: arquitetura do HypothesisClassifier. T_max: normalização temporal (w = time_step / T_max). """
def __init__( self, vocab_size=16384, hidden_dim=1024, seq_len=8, som_grid=(6, 6, 6, 4), alpha0=0.1, sigma0=1.5, lambda_ewc=0.02, N_start=10, dim_choice="y", hypothesis_hidden=[512, 256, 128, 64, 32, 16, 8], T_max=10000, ): self.tokenizer = SimpleBBPETokenizer(vocab_size) self.embedding = nn.Embedding(vocab_size, hidden_dim) self.hidden_dim = hidden_dim self.seq_len = seq_len self.T_max = T_max self.time_counter = 0 # contador global de amostras processadas
self.som = KohonenSOM4D(som_grid, alpha0, sigma0, lambda_ewc) self.som_grid = som_grid self.som_neuron_count = ( som_grid[0] * som_grid[1] * som_grid[2] * som_grid[3] )
self.classifier: Optional[HypothesisClassifier] = None self.hypothesis_hidden = hypothesis_hidden self.classifier_trained = False
self.buffer_4d = [] self.buffer_labels = [] self.training_ready = False self.N = N_start self.dim_choice = dim_choice self.dim_index = {"x": 0, "y": 1, "z": 2}[dim_choice]
self.punishment_count = 0 self.success_count = 0 self.histogram = Counter()
self.required_new_samples = 0
def add_data(self, sentences: List[str], labels: List[int]): """Adiciona amostras: text → 4D vector + atualiza histograma.""" for sent, lab in zip(sentences, labels): self.time_counter += 1 vec = text_to_4d_vector( sent, self.tokenizer, self.embedding, self.hidden_dim, self.seq_len, self.time_counter, self.T_max, ) self.buffer_4d.append(vec) self.buffer_labels.append(lab) dim_val = round(vec[self.dim_index].item(), 2) self.histogram[dim_val] += 1
def check_training_start(self) -> bool: """Inicia treino quando algum bucket do histograma atinge N.""" if ( not self.training_ready and max(self.histogram.values(), default=0) >= self.N ): self.training_ready = True return True return False
def train_som_on_buffer(self): """Treina SOM por 5 épocas sobre o buffer atual (com Fisher accum).""" if not self.buffer_4d: return data = torch.stack(self.buffer_4d) for _ in range(5): # épocas de treino rápido perm = torch.randperm(len(data)) for idx in perm: x = data[idx] bmu = self.som.find_bmu(x) acc_fisher = ( self.punishment_count == 0 and self.som.old_weights_w is None ) self.som.update_weights(x, bmu, accumulate_fisher=acc_fisher)
def _som_activation(self, x): """Vetor de ativação SOM: distâncias de x a todos os neurônios (flatten).""" dist = torch.sum((self.som.weights - x.view(1, 1, 1, 1, 4)) ** 2, dim=-1) return dist.flatten()
def _label_neurons(self): """Rotula neurônios por votação majoritária sobre o buffer.""" self.neuron_label = {} if not self.buffer_4d: return data = torch.stack(self.buffer_4d) labels = torch.tensor(self.buffer_labels) votes = defaultdict(lambda: [0, 0]) for i in range(len(data)): bmu = self.som.find_bmu(data[i]) votes[bmu][int(labels[i].item())] += 1 for bmu, v in votes.items(): self.neuron_label[bmu] = 1.0 if v[1] > v[0] else 0.0
def evaluate_classification(self) -> float: """Acurácia sobre o buffer atual.""" if not self.buffer_4d: return 1.0 data = torch.stack(self.buffer_4d) labels = torch.tensor(self.buffer_labels).float() correct = 0 for i in range(len(data)): pred = self._predict_single(data[i]) if (pred > 0.5) == (labels[i] > 0.5): correct += 1 return correct / len(data)
def _predict_single(self, x): """Prediz: classifier (se treinado) ou voto do BMU.""" if self.classifier is not None and self.classifier_trained: with torch.no_grad(): act = self._som_activation(x).unsqueeze(0) logit = self.classifier(act) return torch.sigmoid(logit).item() else: if not hasattr(self, "neuron_label"): self._label_neurons() bmu = self.som.find_bmu(x) return self.neuron_label.get(bmu, 0.5)
def activate_hypothesis(self): """Treina o HypothesisClassifier (8 FC layers) por 50 epochs.
BUG FIX (V6.3→V6.4): buffer_4d contém tensores que carregam o grafo de computação do embedding. Para evitar "Trying to backward through the graph a second time", fazemos detach+clone e calculamos as ativações SOM dentro de torch.no_grad(). O classifier treina apenas sobre seus próprios pesos. """ if self.classifier is None: self.classifier = HypothesisClassifier( self.som_neuron_count, self.hypothesis_hidden ) # FIX: detach+clone para isolar do grafo do embedding data = torch.stack(self.buffer_4d).detach().clone() labels = torch.tensor(self.buffer_labels).float() # FIX: ativações SEM gradiente (não queremos treinar SOM/embedding aqui) with torch.no_grad(): X = torch.stack([self._som_activation(data[i]) for i in range(len(data))]) optimizer = torch.optim.Adam(self.classifier.parameters(), lr=0.001) criterion = nn.BCEWithLogitsLoss() for _ in range(50): optimizer.zero_grad() loss = criterion(self.classifier(X), labels) loss.backward() optimizer.step() self.classifier_trained = True
def process_batch(self, sentences: List[str], labels: List[int]): """Processa batch: adiciona dados, treina SOM se ready, aplica punishment.
Returns: True se o protocolo de punishment completou um ciclo (2ª punição → set_ewc_reference + reset). False caso contrário. """ self.add_data(sentences, labels)
if self.check_training_start(): self.train_som_on_buffer() self._label_neurons()
if self.training_ready: acc = self.evaluate_classification() if acc < 1.0: self.punishment_count += 1 self.success_count = 0 if self.punishment_count == 1: self.activate_hypothesis() elif self.punishment_count == 2: self.som.set_ewc_reference() self.required_new_samples = ( self.success_count * self.N if self.success_count > 0 else self.N ) self.training_ready = False self.punishment_count = 0 self.success_count = 0 self.histogram.clear() self.buffer_4d.clear() self.buffer_labels.clear() return True else: self.punishment_count = 0 self.success_count += 1 return False
def predict(self, sentence: str) -> str: """Prediz rótulo textual ("gato" se prob ≤ 0.5, "cachorro" caso contrário).""" self.time_counter += 1 # mantém coerência temporal vec = text_to_4d_vector( sentence, self.tokenizer, self.embedding, self.hidden_dim, self.seq_len, self.time_counter, self.T_max, ) prob = self._predict_single(vec) return "gato" if prob <= 0.5 else "cachorro"
# ------------------------------------------------------------------ # API de monitoramento (V6.4) # ------------------------------------------------------------------ def get_state_metrics(self) -> dict: """Retorna métricas completas do sistema para monitoramento.""" som_metrics = self.som.get_metrics() return { "som": som_metrics, "kls": { "time_counter": int(self.time_counter), "T_max": int(self.T_max), "buffer_size": int(len(self.buffer_4d)), "training_ready": bool(self.training_ready), "punishment_count": int(self.punishment_count), "success_count": int(self.success_count), "classifier_trained": bool(self.classifier_trained), "histogram_size": int(len(self.histogram)), "histogram_max": int(max(self.histogram.values(), default=0)), "N_start": int(self.N), "dim_choice": str(self.dim_choice), "som_neuron_count": int(self.som_neuron_count), "required_new_samples": int(self.required_new_samples), "has_classifier": self.classifier is not None, "vocab_size": int(self.tokenizer.vocab_size), "hidden_dim": int(self.hidden_dim), "seq_len": int(self.seq_len), }, }src/bigru_t/model/kohonen_refactored/kohonen_learning_system.pyDeleted-671