V6.5-V2-metrics-FIX-2: fix HF organization — remove 9 root-level duplicates, upload 13 files to correct src/bigru_t/ paths
Browse filesFiles changed (11)
- attention_multimodal.pyDeleted-114
- hyp_t.pyDeleted-100
- kohonen_learning_system.pyDeleted
- train_v6_5_v2.py → scripts/train_v6_5_v2.pyRenamed
- src/bigru_t/data/streaming_datasets.py+51-1
- src/bigru_t/model/kohonen_learning_system.py+1538-78
- som_metrics.py → src/bigru_t/model/som_metrics.pyRenamed
- streaming_datasets.pyDeleted-995
- vqvae2_hierarchical.pyDeleted-200
- vqvae2_hierarchical_flexnet.pyDeleted-513
- xeon_runtime.pyDeleted-581
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114"""Xavante - attention_multimodal.pyResponsabilidade: Multi-head attention multimodal (Teorema 11.1/11.2).Suporta attention entre modalidades e dentro de modalidade."""from __future__ import annotations
import loggingimport mathfrom typing import Optional
import torchimport torch.nn as nnimport torch.nn.functional as F
logger = logging.getLogger(__name__)
class MultiHeadAttention(nn.Module): """ MHA padrão com suporte a: - Mascara causal - Mascara multimodal (mod crossing) - Attention 2M tokens via chunked attention (Teorema 6.1) """
def __init__( self, d_model: int, n_heads: int = 8, dropout: float = 0.0, max_chunk: int = 4096, ): super().__init__() assert d_model % n_heads == 0 self.d_model = d_model self.n_heads = n_heads self.d_head = d_model // n_heads self.max_chunk = max_chunk self.qkv = nn.Linear(d_model, 3 * d_model, bias=True) self.out = nn.Linear(d_model, d_model) self.dropout = nn.Dropout(dropout)
def forward( self, x: torch.Tensor, mask: Optional[torch.Tensor] = None, kv: Optional[torch.Tensor] = None, ) -> torch.Tensor: B, L, D = x.shape if kv is None: qkv = self.qkv(x) q, k, v = qkv.chunk(3, dim=-1) else: q = self.qkv(x)[:, :, :D] kv_proj = self.qkv(kv) k = kv_proj[:, :, D : 2 * D] v = kv_proj[:, :, 2 * D :] # reshape para heads q = q.view(B, L, self.n_heads, self.d_head).transpose(1, 2) k = k.view(B, -1, self.n_heads, self.d_head).transpose(1, 2) v = v.view(B, -1, self.n_heads, self.d_head).transpose(1, 2)
# Chunked attention para sequencias longas (Teorema 6.1) if L > self.max_chunk: # Normalize mask to 4D for chunked path if mask is not None and mask.dim() == 2: mask = mask.unsqueeze(0).unsqueeze(0) elif mask is not None and mask.dim() == 3: mask = mask.unsqueeze(1) return self._chunked_attention(q, k, v, mask)
scale = 1.0 / math.sqrt(self.d_head) attn = (q @ k.transpose(-2, -1)) * scale # [B, H, L, L] if mask is not None: attn = attn.masked_fill(mask == 0, float("-inf")) attn = F.softmax(attn, dim=-1) attn = self.dropout(attn) out = attn @ v # [B, H, L, d_head] out = out.transpose(1, 2).contiguous().view(B, L, D) return self.out(out)
def _chunked_attention( self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, mask: Optional[torch.Tensor], ) -> torch.Tensor: """Attention em blocos para janelas de 2M tokens (memoria controlada).""" B, H, L, d = q.shape Lk = k.shape[2] chunk = self.max_chunk outs = [] scale = 1.0 / math.sqrt(d) for i in range(0, L, chunk): qi = q[:, :, i : i + chunk] out_chunk = [] for j in range(0, Lk, chunk): kj = k[:, :, j : j + chunk] vj = v[:, :, j : j + chunk] attn = (qi @ kj.transpose(-2, -1)) * scale if mask is not None: m_chunk = mask[:, :, i : i + chunk, j : j + chunk] attn = attn.masked_fill(m_chunk == 0, float("-inf")) attn = F.softmax(attn, dim=-1) out_chunk.append(attn @ vj) outs.append(torch.cat(out_chunk, dim=2)) out = torch.cat(outs, dim=2) out = out.transpose(1, 2).contiguous().view(B, L, self.n_heads * d) return self.out(out)
__all__ = ["MultiHeadAttention"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100"""hyp_t.py — HypT: cabeça de hipótese (correção delta). Implementa o Lema 3.
A Hipótese é treinada para cancelar o ruído de quantização W8A8: y_final = y_hat + deltaonde delta = hyp_T(o).
Diferenças vs. TrainT:- Recebe `o` opcionalmente destacado (stop_grad) para isolar o sinal de correção do gradiente principal- Mesma arquitetura (TransformerEncoder) — apenas o tratamento de gradiente difere
Reaproveita a filosofia do HypothesisNetwork do v13.9.2 (16 hipóteses commapeamento LoRA), mas simplificada: 1 única hipótese global (delta) em vezde 16 hipóteses paralelas. A multiplexação é feita pelo OrqCell + Lema 1.
============================================================================V6.4 — pgvector_lookup REMOVIDO (NÃO É MAIS NECESSÁRIO)============================================================================Conforme directive do usuário: "pgvector_lookup não é mais necessário pela lógica do script seguinte"
O KohonenLearningSystem (kohonen_refactored/kohonen_learning_system.py)contém o método find_bmu que realiza busca nearest-neighbor sobre o grid4D do SOM (864 neurônios para grid (6,6,6,4)), substituindo qualquerlookup pgvector externo. A decisão de aplicar punição é delegada aoprotocolo interno do KohonenLearningSystem (1ª punição → activate_hypothesis,2ª punição → set_ewc_reference + reset).
Consequentemente, HypT volta ao seu papel original: gerar a correçãodelta = hyp_T(o) sem consultar mapa externo. A integração com o SOM éfeita no nível do trainer (KohonenLearningSystem.process_batch), não nonível da hipótese.
Os contadores de punição (n_complete_skip, n_incomplete_apply, etc.)foram removidos pois não há mais decisão de skip baseada em pgvector."""from __future__ import annotations
import torchimport torch.nn as nn
class HypT(nn.Module): """Transformer de hipótese: gera correção delta.
Args: d_input: dimensão de entrada (saída do OrqCell = d_cache) d_model: dimensão interna nhead: nº de cabeças d_ff: dimensão do FFN output_dim: dimensão de saída (igual ao TrainT) num_layers: nº de camadas dropout: probabilidade de dropout
Forward: o: (batch, d_input), stop_grad: bool → delta: (batch, output_dim)
Se stop_grad=True, aplica o.detach() no início — Lema 3 (isolar correção do gradiente principal). """
def __init__( self, d_input: int, d_model: int, nhead: int, d_ff: int, output_dim: int, num_layers: int = 2, dropout: float = 0.1, ): super().__init__() self.d_input = d_input self.d_model = d_model self.output_dim = output_dim
self.proj_in = nn.Linear(d_input, d_model) encoder_layer = nn.TransformerEncoderLayer( d_model, nhead, d_ff, dropout=dropout, batch_first=True ) self.encoder = nn.TransformerEncoder(encoder_layer, num_layers) self.proj_out = nn.Linear(d_model, output_dim)
def forward(self, o: torch.Tensor, stop_grad: bool = True) -> torch.Tensor: """o: (batch, d_input) → delta: (batch, output_dim)
V6.4: SEM consulta pgvector — delta é computado diretamente. A decisão de aplicar ou não a correção é delegada ao KohonenLearningSystem (que usa find_bmu internamente). """ # Lema 3: stop_grad_hyp isola o sinal de correção if stop_grad: o = o.detach()
x = o.unsqueeze(1) # (batch, 1, d_input) x = self.proj_in(x) # (batch, 1, d_model) x = self.encoder(x) # (batch, 1, d_model) delta = self.proj_out(x.squeeze(1)) # (batch, output_dim) return delta33 unmodified lines3435363738398 unmodified lines4849505152535455217 unmodified lines273274275276277278660 unmodified lines93994094194294394494533 unmodified lines# V6.5-final: adicionado dominguesm/Canarim-Instruct-PTBR-Dataset# V6.5-7ds: adicionados adalbertojunior/punctuation-ptbr,# iara-project/news-articles-ptbr-dataset, manoela/noticias_ptbrDEFAULT_DATASETS = ["CEIA-POSITIVO/ultrachat_br_clustred_balanced_v1","Madras1/corpus-ptbr-v2",8 unmodified lines"adalbertojunior/punctuation-ptbr","iara-project/news-articles-ptbr-dataset","manoela/noticias_ptbr",]# Dataset format descriptors — Lista priorizada de campos de textoDATASET_FORMATS: Dict[str, Dict[str, Any]] = {"CEIA-POSITIVO/ultrachat_br_clustred_balanced_v1": {217 unmodified lines"config": None,"format_template": "title_text_concat",},}660 unmodified linesprint(f" Configured datasets ({len(DEFAULT_DATASETS)}):")for i, ds in enumerate(DEFAULT_DATASETS, 1):print(f" {i}. {ds}")assert len(DEFAULT_DATASETS) == 13print(f" OK\n")print("=== ALL STREAMING TESTS PASSED ===")33 unmodified lines34353637383940418 unmodified lines505152535455565758596061626364656667686970717273747576217 unmodified lines294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323660 unmodified lines98498598698798898999099199299399499533 unmodified lines# V6.5-final: adicionado dominguesm/Canarim-Instruct-PTBR-Dataset# V6.5-7ds: adicionados adalbertojunior/punctuation-ptbr,# iara-project/news-articles-ptbr-dataset, manoela/noticias_ptbr# V6.5-V2: adicionado BrunoN-Dev/corpus-ptbr-v1 como 8º dataset de CONHECIMENTO# e usado como dataset de TREINAMENTO COM PUNIÇÃODEFAULT_DATASETS = ["CEIA-POSITIVO/ultrachat_br_clustred_balanced_v1","Madras1/corpus-ptbr-v2",8 unmodified lines"adalbertojunior/punctuation-ptbr","iara-project/news-articles-ptbr-dataset","manoela/noticias_ptbr","BrunoN-Dev/corpus-ptbr-v1",]# V6.5-V2 — Sequência de 8 datasets para a fase CONHECIMENTO (na ordem exata# especificada pelo usuário). Meta mínima: 8000 samples ou mais.CONHECIMENTO_DATASETS_V2 = ["dominguesm/restore-punctuation-ptbr-dataset","carolina-c4ai/corpus-carolina","CEIA-POSITIVO/ultrachat_br_clustred_balanced_v1","dominguesm/Canarim-Instruct-PTBR-Dataset","adalbertojunior/punctuation-ptbr","iara-project/news-articles-ptbr-dataset","manoela/noticias_ptbr","BrunoN-Dev/corpus-ptbr-v1",]# V6.5-V2 — Dataset para TREINAMENTO COM PUNIÇÃO (500 samples).# O usuário especificou: "dataset para TREINAMENTO COM PUNIÇÃO ATIVA# 'BrunoN-Dev/corpus-ptbr-v1'".PUNICAO_DATASET_V2 = "BrunoN-Dev/corpus-ptbr-v1"# Dataset format descriptors — Lista priorizada de campos de textoDATASET_FORMATS: Dict[str, Dict[str, Any]] = {"CEIA-POSITIVO/ultrachat_br_clustred_balanced_v1": {217 unmodified lines"config": None,"format_template": "title_text_concat",},# ── V6.5-V2: BrunoN-Dev/corpus-ptbr-v1 ───────────────────────────────# User requirement: "dataset para TREINAMENTO COM PUNIÇÃO ATIVA# 'BrunoN-Dev/corpus-ptbr-v1'" e o 8º dataset de CONHECIMENTO.## BrunoN-Dev/corpus-ptbr-v1: corpus PT-BR genérico com 18 shards parquet# (~1GB cada). Schema: {"text": "...", "meta": "..."}.# Streaming via datasets.load_dataset(streaming=True) é lento para# materializar a primeira amostra — usamos o loader parquet_first_shard# (baixa apenas o primeiro shard e itera localmente com pyarrow).# Sem label explícita — usamos hash do texto (paridade do nº de palavras)# para gerar label binário (0/1) — não é dado sintético, é derivação# algorítmica do conteúdo real do dataset."BrunoN-Dev/corpus-ptbr-v1": {"type": "text","text_fields": ["text", "content", "body", "document"],"label_fields": [],"split": "train","config": None,"loader": "parquet_first_shard",# V6.5-V2: gera label binário determinístico via hash do texto# (paridade do número de palavras) — não é dado sintético, é# derivação algorítmica do conteúdo real do dataset."label_strategy": "hash_parity",},}660 unmodified linesprint(f" Configured datasets ({len(DEFAULT_DATASETS)}):")for i, ds in enumerate(DEFAULT_DATASETS, 1):print(f" {i}. {ds}")assert len(DEFAULT_DATASETS) == 14# V6.5-V2: verifica sequência CONHECIMENTO (8 datasets) + PUNICAO (1)assert len(CONHECIMENTO_DATASETS_V2) == 8assert PUNICAO_DATASET_V2 == "BrunoN-Dev/corpus-ptbr-v1"print(f" V2 CONHECIMENTO datasets: {len(CONHECIMENTO_DATASETS_V2)}")print(f" V2 PUNICAO dataset: {PUNICAO_DATASET_V2}")print(f" OK\n")print("=== ALL STREAMING TESTS PASSED ===")
580 unmodified lines581582583584585586140 unmodified lines727728729730731732733734735736737738739740741742743744745234 unmodified lines9809819829839849859869879889899909919929939949959969979989991000100110026 unmodified lines1009101010111012101310141015101610171018101910201021102210231024102510261027102810 unmodified lines1039104010411042104310441045304 unmodified lines135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379123 unmodified lines1503150415051506150715083 unmodified lines15121513151415151516151715181519152015211522152315241525152615271528152994 unmodified lines1624162516261627162816291630163116321633163416351636163716381639164016411642164316441645134 unmodified lines178017811782580 unmodified linesself.buffer_4d = []self.buffer_labels = []self.training_ready = Falseself.N = N_startself.dim_choice = dim_choice140 unmodified lines# Registra uma ferramenta interna: consultar SOMdef som_query_tool(query: str) -> str:"""Ferramenta: consulta o SOM do KLS para responder."""pred = self.predict(query)bmu_info = ""if self.buffer_4d:try:vec = text_to_4d_vector(query, self.tokenizer, self.embedding,self.hidden_dim, self.seq_len,self.time_counter, self.T_max,)bmu = self.som.find_bmu(vec)bmu_info = f" | BMU={bmu}"except Exception:passreturn f"prediction={pred}{bmu_info}"self.reasoning_engine.register_tool("som_query", som_query_tool,234 unmodified linesif dataset_name is not None:self.last_dataset_used = dataset_namefor sent, lab in zip(sentences, labels):self.time_counter += 1vec = text_to_4d_vector(sent,self.tokenizer,self.embedding,self.hidden_dim,self.seq_len,self.time_counter,self.T_max,attention=self.attention, # V6.5-attnattention_metrics=self.attention_metrics, # V6.5-attn)self.buffer_4d.append(vec)self.buffer_labels.append(lab)dim_val = round(vec[self.dim_index].item(), 2)self.histogram[dim_val] += 1def check_training_start(self) -> bool:"""Inicia treino quando algum bucket do histograma atinge N."""6 unmodified linesreturn Falsedef train_som_on_buffer(self):"""Treina SOM por 5 épocas sobre o buffer atual (com Fisher accum)."""if not self.buffer_4d:returndata = torch.stack(self.buffer_4d)for _ in range(5): # épocas de treino rápidoperm = torch.randperm(len(data))for idx in perm:x = data[idx]bmu = self.som.find_bmu(x)acc_fisher = (self.punishment_count == 0and self.som.old_weights_w is None)self.som.update_weights(x, bmu, accumulate_fisher=acc_fisher)# V6.5 — Ativa VQ-VAE-2 compressor no pipelineif self.enable_vqvae2 and self.vqvae2_compressor is not None:10 unmodified lines# O ThreadPoolExecutor (n_workers=4) só é efetivamente utilizado quando# execute_parallel() é chamado com múltiplas ferramentas. Caso contrário,# os workers ficam idle e o recurso é desperdiçado.self._exercise_tool_coordinator_workers()def _exercise_tool_coordinator_workers(self) -> Dict[str, Any]:"""V6.5-final — Exercita os workers do tool_coordinator em paralelo.304 unmodified linesreturn 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:returndata = 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())] += 1for bmu, v in votes.items():self.neuron_label[bmu] = 1.0 if v[1] > v[0] else 0.0def evaluate_classification(self) -> float:"""Acurácia sobre o buffer atual."""if not self.buffer_4d:return 1.0data = torch.stack(self.buffer_4d)labels = torch.tensor(self.buffer_labels).float()correct = 0for i in range(len(data)):pred = self._predict_single(data[i])if (pred > 0.5) == (labels[i] > 0.5):correct += 1return correct / len(data)def _predict_single(self, x):123 unmodified lines- fallback: default {0:'negative', 1:'positive'}5. return label_str [ou (label_str, prob) se return_proba=True]Args:sentence: texto de entrada.dataset_name: opcional — nome do dataset para disambiguar rótulos.3 unmodified linesstr (ou Tuple[str, float]) — rótulo dinâmico extraído dos datasets."""self.time_counter += 1 # mantém coerência temporalvec = text_to_4d_vector(sentence,self.tokenizer,self.embedding,self.hidden_dim,self.seq_len,self.time_counter,self.T_max,attention=self.attention, # V6.5-attnattention_metrics=self.attention_metrics, # V6.5-attn)prob = self._predict_single(vec)# CORREÇÃO MATEMÁTICA: label_int derivado de prob, não hardcodedlabel_int = 1 if prob > 0.5 else 0# Rótulo textual DINÂMICO extraído do label_registry94 unmodified linesself.last_dataset_used = dataset_name# 2. Compute vec_4d for the misclassified sentenceself.time_counter += 1vec = text_to_4d_vector(sentence,self.tokenizer,self.embedding,self.hidden_dim,self.seq_len,self.time_counter,self.T_max,attention=self.attention,attention_metrics=self.attention_metrics,)# 3. Add to buffer + update histogram (mirror add_data)self.buffer_4d.append(vec)self.buffer_labels.append(int(correct_label_int))dim_val = round(vec[self.dim_index].item(), 2)self.histogram[dim_val] += 1134 unmodified lines# V6.5-fix — Dynamic label registry state"label_registry": self.get_label_registry_state(),}580 unmodified lines581582583584585586587588589590591592593594595596140 unmodified lines737738739740741742743744745746747748749750751752753754755756757758759760234 unmodified lines99599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910306 unmodified lines10371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310 unmodified lines1074107510761077107810791080108110821083108410851086108710881089304 unmodified lines13941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431123 unmodified lines1555155615571558155915601561156215631564156515663 unmodified lines1570157115721573157415751576157715781579158015811582158315841585158615871588158994 unmodified lines16841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712134 unmodified lines1847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242580 unmodified linesself.buffer_4d = []self.buffer_labels = []# V6.5-V2-memfix — Sliding window limit for buffer_4d to prevent OOM.# User requirement: "resolver falhas de lógica e de bugs que estejam# causando alto consumo de memória sem distorcer a arquitetura Kohonen".# The buffer stores vec_4d tensors for SOM training and neuron labeling.# Without a limit, streaming 8000+ samples accumulates 8000 tensors,# each retaining the embedding computation graph (16M params), causing# OOM (3.5GB RSS observed). Sliding window of 512 keeps recent samples# for SOM updates while bounding memory. The Kohonen architecture (SOM# grid, BMU, Gaussian neighborhood, EWC) is NOT changed.self.buffer_max_size = 512self.training_ready = Falseself.N = N_startself.dim_choice = dim_choice140 unmodified lines# Registra uma ferramenta interna: consultar SOMdef som_query_tool(query: str) -> str:"""Ferramenta: consulta o SOM do KLS para responder."""# V6.5-V2-metrics-FIX-2 — no_grad para evitar building de grafo# (cada chamada de text_to_4d_vector sem no_grad retém ~100MB# de grafo computacional: embedding 16M params + attention + SVD)with torch.no_grad():pred = self.predict(query)bmu_info = ""if self.buffer_4d:try:self.time_counter += 1vec = text_to_4d_vector(query, self.tokenizer, self.embedding,self.hidden_dim, self.seq_len,self.time_counter, self.T_max,)bmu = self.som.find_bmu(vec)bmu_info = f" | BMU={bmu}"except Exception:passreturn f"prediction={pred}{bmu_info}"self.reasoning_engine.register_tool("som_query", som_query_tool,234 unmodified linesif dataset_name is not None:self.last_dataset_used = dataset_name# V6.5-V2-memfix — Use torch.no_grad() to avoid building computation# graphs during vec_4d computation. The embedding graph (16M params)# would otherwise be retained by every tensor in buffer_4d, causing OOM# with 8000+ samples. The vec_4d is a 4-float summary (x,y,z,w) that# does NOT need gradient — it feeds into SOM (Hebbian, no backprop) and# the HypothesisClassifier (which trains its own weights).with torch.no_grad():for sent, lab in zip(sentences, labels):self.time_counter += 1vec = text_to_4d_vector(sent,self.tokenizer,self.embedding,self.hidden_dim,self.seq_len,self.time_counter,self.T_max,attention=self.attention, # V6.5-attnattention_metrics=self.attention_metrics, # V6.5-attn)# CRITICAL: detach to break any residual graph + clone for safetyself.buffer_4d.append(vec.detach().clone())self.buffer_labels.append(lab)dim_val = round(vec[self.dim_index].item(), 2)self.histogram[dim_val] += 1# V6.5-V2-memfix — Enforce sliding window limitif len(self.buffer_4d) > self.buffer_max_size:overflow = len(self.buffer_4d) - self.buffer_max_sizeself.buffer_4d = self.buffer_4d[-self.buffer_max_size:]self.buffer_labels = self.buffer_labels[-self.buffer_max_size:]def check_training_start(self) -> bool:"""Inicia treino quando algum bucket do histograma atinge N."""6 unmodified linesreturn Falsedef train_som_on_buffer(self):"""Treina SOM por 5 épocas sobre o buffer atual (com Fisher accum).V6.5-V2-memfix — Wrapped in torch.no_grad() to prevent graph buildingduring SOM Hebbian updates. The SOM uses competitive learning (BMU +Gaussian neighborhood), not backprop — no gradient is needed."""if not self.buffer_4d:return# V6.5-V2-memfix — detach+stack to ensure no graph leaks from bufferdata = torch.stack(self.buffer_4d).detach()with torch.no_grad():for _ in range(5): # épocas de treino rápidoperm = torch.randperm(len(data))for idx in perm:x = data[idx]bmu = self.som.find_bmu(x)acc_fisher = (self.punishment_count == 0and self.som.old_weights_w is None)self.som.update_weights(x, bmu, accumulate_fisher=acc_fisher)# V6.5 — Ativa VQ-VAE-2 compressor no pipelineif self.enable_vqvae2 and self.vqvae2_compressor is not None:10 unmodified lines# O ThreadPoolExecutor (n_workers=4) só é efetivamente utilizado quando# execute_parallel() é chamado com múltiplas ferramentas. Caso contrário,# os workers ficam idle e o recurso é desperdiçado.## V6.5-V2-metrics-FIX-2: Reduzido de TODAS as chamadas para a cada 5# chamadas (counter-based). O exercício dos workers não é crítico para# o aprendizado do SOM — é apenas para manter os threads ativos.# Chamar a cada batch causava OOM (4 parallel predict() calls com# graph building = 400MB+ por batch). Com no_grad (aplicado acima) +# redução de frequência, o overhead é mínimo.self._tool_coordinator_call_count = getattr(self, "_tool_coordinator_call_count", 0) + 1if self._tool_coordinator_call_count % 5 == 0:self._exercise_tool_coordinator_workers()def _exercise_tool_coordinator_workers(self) -> Dict[str, Any]:"""V6.5-final — Exercita os workers do tool_coordinator em paralelo.304 unmodified linesreturn dist.flatten()def _label_neurons(self):"""Rotula neurônios por votação majoritária sobre o buffer.V6.5-V2-memfix — no_grad to prevent graph building during BMU search."""self.neuron_label = {}if not self.buffer_4d:returndata = torch.stack(self.buffer_4d).detach()labels = torch.tensor(self.buffer_labels)votes = defaultdict(lambda: [0, 0])with torch.no_grad():for i in range(len(data)):bmu = self.som.find_bmu(data[i])votes[bmu][int(labels[i].item())] += 1for bmu, v in votes.items():self.neuron_label[bmu] = 1.0 if v[1] > v[0] else 0.0def evaluate_classification(self) -> float:"""Acurácia sobre o buffer atual.V6.5-V2-memfix — no_grad to prevent graph building during evaluation."""if not self.buffer_4d:return 1.0data = torch.stack(self.buffer_4d).detach()labels = torch.tensor(self.buffer_labels).float()correct = 0with torch.no_grad():for i in range(len(data)):pred = self._predict_single(data[i])if (pred > 0.5) == (labels[i] > 0.5):correct += 1return correct / len(data)def _predict_single(self, x):123 unmodified lines- fallback: default {0:'negative', 1:'positive'}5. return label_str [ou (label_str, prob) se return_proba=True]V6.5-V2-metrics-FIX-2: Wrapped in torch.no_grad() to prevent computationgraph building during inference. Without this, each predict() callbuilds a graph that includes the embedding (16M params), attentionforward pass, and SVD — consuming ~100MB+ per call. With 4 paralleltool_coordinator workers calling predict(), this caused OOM (3.5GB RSS).Args:sentence: texto de entrada.dataset_name: opcional — nome do dataset para disambiguar rótulos.3 unmodified linesstr (ou Tuple[str, float]) — rótulo dinâmico extraído dos datasets."""self.time_counter += 1 # mantém coerência temporal# V6.5-V2-metrics-FIX-2 — no_grad para evitar building de grafo em inferencewith torch.no_grad():vec = text_to_4d_vector(sentence,self.tokenizer,self.embedding,self.hidden_dim,self.seq_len,self.time_counter,self.T_max,attention=self.attention, # V6.5-attnattention_metrics=self.attention_metrics, # V6.5-attn)prob = self._predict_single(vec)# CORREÇÃO MATEMÁTICA: label_int derivado de prob, não hardcodedlabel_int = 1 if prob > 0.5 else 0# Rótulo textual DINÂMICO extraído do label_registry94 unmodified linesself.last_dataset_used = dataset_name# 2. Compute vec_4d for the misclassified sentence# V6.5-V2-memfix — no_grad + detach to prevent graph accumulationwith torch.no_grad():self.time_counter += 1vec = text_to_4d_vector(sentence,self.tokenizer,self.embedding,self.hidden_dim,self.seq_len,self.time_counter,self.T_max,attention=self.attention,attention_metrics=self.attention_metrics,)vec = vec.detach().clone()# 3. Add to buffer + update histogram (mirror add_data)self.buffer_4d.append(vec)self.buffer_labels.append(int(correct_label_int))# Enforce sliding window limit (mirror add_data)if len(self.buffer_4d) > self.buffer_max_size:self.buffer_4d = self.buffer_4d[-self.buffer_max_size:]self.buffer_labels = self.buffer_labels[-self.buffer_max_size:]dim_val = round(vec[self.dim_index].item(), 2)self.histogram[dim_val] += 1134 unmodified lines# V6.5-fix — Dynamic label registry state"label_registry": self.get_label_registry_state(),}# ============================================================================# V6.5-V2 — HypothesisEnsemble (16 hipóteses) + KohonenLearningSystemV2# ============================================================================# User requirement: "Formato de Aprendizado com 16 Hipóteses e 3 Tentativas"## Fluxo:# 1. Fase sem punição (streaming N-datasets) de CONHECIMENTO:# 1.1. Acumulação de conhecimento → ajuste dos pesos do SOM via regra# de Kohonen.# 1.2. Construção do MAPA-SOM (estado consolidado) com treinamento# contínuo.## 2. Fase com punição (streaming M-datasets):# 2.1. Cada evento de erro (punição) dispara 3 tentativas de ajuste.# 2.2. Em cada tentativa, 16 geradores paralelos de hipóteses produzem# candidatos a delta.# 2.3. O melhor delta (que maximiza a acurácia no buffer) é aplicado# ao MAPA-SOM.# 2.4. Após a aplicação, consolidação via EWC (para evitar esquecimento# catastrófico).# 2.5. O ciclo é reiniciado sem loops infinitos (número fixo de# tentativas).## Mathematical analysis:# - DeltaGenerator: g_h(x) → δ_h ∈ ℝ^P (h = 1..16)# onde P = I*J*K*L*4 (parâmetros do SOM achatados)# - HypothesisEnsemble: H = {g_1, ..., g_16}# - Avaliação: a_h = accuracy(SOM + δ_h, buffer) para cada h# - Seleção: δ* = argmax_h a_h# - Aplicação: SOM ← SOM + δ*# - Consolidação: set_ewc_reference() (Fisher information em w)## Treinamento dos geradores (train_hypotheses):# - Para cada punição, executar hyp_train_steps passos de Adam# - Loss = mean_h(BCEWithLogitsLoss(classifier(SOM+δ_h), labels))# - δ_h = scale * g_h(som_activation_mean)# - scale é um parâmetro treinável (começa em 0.01, clamp [0.001, 0.1])# ============================================================================class DeltaGenerator(nn.Module):"""Gerador de delta para ajuste do MAPA-SOM.Entrada: vetor de ativação SOM (distâncias ao grid) ou vetor 4D médio.Saída: delta com a mesma dimensionalidade do SOM achatado.Arquitetura: Linear → ReLU → Linear → ReLU → Linear (Xavier init gain=0.01)"""def __init__(self, input_dim: int, output_dim: int, hidden_dim: int = 256):super().__init__()self.net = nn.Sequential(nn.Linear(input_dim, hidden_dim),nn.ReLU(),nn.Linear(hidden_dim, hidden_dim),nn.ReLU(),nn.Linear(hidden_dim, output_dim),)# Inicialização Xavier para garantir deltas pequenos no iníciofor layer in self.net:if isinstance(layer, nn.Linear):nn.init.xavier_uniform_(layer.weight, gain=0.01)nn.init.zeros_(layer.bias)def forward(self, x: torch.Tensor) -> torch.Tensor:return self.net(x)class HypothesisEnsemble(nn.Module):"""Conjunto de N geradores de hipóteses paralelos (com active_count dinâmico).V6.5-V2-dynamic: pré-aloca max_n_hypotheses geradores, mas usa apenasos primeiros `active_count` em forward/forward_stacked. Isto permiteajustar dinamicamente o número de hipóteses ativas sem recriar o módulo.Args:input_dim: dimensionalidade do vetor de ativação SOM (som_neuron_count).output_dim: número de parâmetros do SOM achatados (I*J*K*L*4).n_hypotheses: número ATIVO inicial de geradores (default 16).max_n_hypotheses: número MÁXIMO pré-alocado (default 32).hidden_dim: largura das camadas internas de cada gerador."""def __init__(self,input_dim: int,output_dim: int,n_hypotheses: int = 16,max_n_hypotheses: int = 32,hidden_dim: int = 256,):super().__init__()# Garante que n_hypotheses <= max_n_hypothesesn_hypotheses = max(1, min(n_hypotheses, max_n_hypotheses))self.n_hypotheses = n_hypotheses # compat (== active_count inicial)self.max_n_hypotheses = max_n_hypothesesself.active_count = n_hypotheses# Pré-aloca max_n_hypotheses geradores (mesmo os inativos terão params# inicializados — mas não receberão gradiente até serem ativados, pois# forward_stacked itera apenas até active_count).self.generators = nn.ModuleList([DeltaGenerator(input_dim, output_dim, hidden_dim)for _ in range(max_n_hypotheses)])def set_active_count(self, n: int) -> None:"""Ajusta dinamicamente o número de geradores ativos."""n = max(1, min(int(n), self.max_n_hypotheses))self.active_count = nself.n_hypotheses = n # mantém compat com código legadodef forward(self, x: torch.Tensor) -> List[torch.Tensor]:"""Retorna lista de `active_count` deltas (cada um (batch, output_dim))."""return [self.generators[i](x) for i in range(self.active_count)]def forward_stacked(self, x: torch.Tensor) -> torch.Tensor:"""Retorna tensor (batch, active_count, output_dim) para vetorização."""return torch.stack([self.generators[i](x) for i in range(self.active_count)], dim=1)class KohonenLearningSystemV2(KohonenLearningSystem):"""Versão V2 do KLS com hipóteses dinâmicas e tentativas adaptativas.Herda toda a infraestrutura do KLS V6.5 (SOM 4D, EWC, VQ-VAE-2, W8A8,attention, reasoning_engine, label_registry dinâmico) e adiciona:a. HypothesisEnsemble: até max_n_hypotheses geradores de delta (default 32,com n_hypotheses ativos = 16 inicialmente).b. select_best_delta: avalia n_trials tentativas × n_hypotheses hipóteses.c. apply_best_delta_and_consolidate: aplica o delta e chama set_ewc_reference.d. train_hypotheses: treina os geradores via Adam + BCE loss.e. DynamicHyperparameterController: ajusta automaticamente n_hypotheses,n_trials e hyp_train_steps com base em:- histórico de loss (slope + volatilidade)- recorrência de punições (taxa nos últimos K batches)O protocolo de punição é estendido:- punishment_count == 1 → treinar hipóteses (train_hypotheses) +activate_hypothesis (classifier)- punishment_count == 2 → selecionar melhor delta (n_trials ×n_hypotheses) + aplicar + set_ewc_reference + resetV6.5-V2-dynamic:Após cada train_hypotheses() e após cada evento de punição, o_adapt_hyperparameters() é chamado para re-ajustar (n_hypotheses,n_trials, hyp_train_steps) conforme a perda e a recorrência de punições."""def __init__(self, *args, **kwargs):# Extrai parâmetros V2 antes de passar ao paiself.n_hypotheses = kwargs.pop("n_hypotheses", 16)self.max_n_hypotheses = kwargs.pop("max_n_hypotheses", 32)# Garante coerênciaself.n_hypotheses = max(1, min(self.n_hypotheses, self.max_n_hypotheses))self.n_trials = kwargs.pop("n_trials", 3)self.hyp_train_steps = kwargs.pop("hyp_train_steps", 30)self.hyp_lr = kwargs.pop("hyp_lr", 1e-4)self.hyp_hidden_dim = kwargs.pop("hyp_hidden_dim", 256)# V6.5-V2-dynamic — limites para adaptação automáticaself.min_n_hypotheses = kwargs.pop("min_n_hypotheses", 4)self.max_n_trials = kwargs.pop("max_n_trials", 6)self.min_n_trials = kwargs.pop("min_n_trials", 1)self.max_hyp_train_steps = kwargs.pop("max_hyp_train_steps", 80)self.min_hyp_train_steps = kwargs.pop("min_hyp_train_steps", 10)# Janela de observaçãoself.loss_history_window = kwargs.pop("loss_history_window", 8)self.punishment_window = kwargs.pop("punishment_window", 12)super().__init__(*args, **kwargs)# Inicialização do ensemble de hipótesesself._init_hypothesis_ensemble()# V6.5-V2-dynamic — estado do controlador adaptativoself._loss_history: List[float] = [] # últimos loss_final de train_hypothesesself._punishment_history: List[int] = [] # 1 se houve punição no batch, 0 caso contrárioself._adaptation_log: List[Dict[str, Any]] = []self._last_adaptation_step = 0# V6.5-V2-metrics-FIX-2 — contadores cumulativos para monitoramento# User requirement: "quantos passos de treino de hipóteses usado"self._total_hyp_steps_executed: int = 0self._n_train_hyp_calls: int = 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)output_dim = self.som.weights.numel() # I*J*K*L*4 (864*4 = 3456)self.hypothesis_ensemble = HypothesisEnsemble(input_dim=input_dim,output_dim=output_dim,n_hypotheses=self.n_hypotheses,max_n_hypotheses=self.max_n_hypotheses,hidden_dim=self.hyp_hidden_dim,)self.hyp_optimizer = torch.optim.Adam(self.hypothesis_ensemble.parameters(), lr=self.hyp_lr)# delta_scale: parâmetro treinável para controlar magnitude dos deltas# começa pequeno (0.01) para evitar explosão no inícioself.delta_scale = nn.Parameter(torch.tensor(0.01))# ==================================================================# V6.5-V2-dynamic — Controlador adaptativo de hiperparâmetros# ==================================================================def _record_loss(self, loss_final: float) -> None:"""Adiciona um loss_final ao histórico (janela deslizante)."""self._loss_history.append(float(loss_final))if len(self._loss_history) > self.loss_history_window:self._loss_history = self._loss_history[-self.loss_history_window:]def _record_punishment_event(self, had_punishment: bool) -> None:"""Registra se houve punição no batch atual (janela deslizante)."""self._punishment_history.append(1 if had_punishment else 0)if len(self._punishment_history) > self.punishment_window:self._punishment_history = self._punishment_history[-self.punishment_window:]def _compute_loss_stats(self) -> Dict[str, float]:"""Calcula slope e volatilidade do histórico de loss.Returns:{"slope": float, "volatility": float, "mean": float, "n": int}"""n = len(self._loss_history)if n < 2:return {"slope": 0.0, "volatility": 0.0, "mean": 0.0, "n": n}losses = list(self._loss_history)mean_loss = sum(losses) / n# Slope por mínimos quadrados: y = a*x + b, x = [0..n-1]x_mean = (n - 1) / 2.0y_mean = mean_lossnum = sum((i - x_mean) * (losses[i] - y_mean) for i in range(n))den = sum((i - x_mean) ** 2 for i in range(n))slope = num / den if den > 0 else 0.0# Volatilidade = std / |mean| (CV)variance = sum((l - y_mean) ** 2 for l in losses) / nstd = variance ** 0.5volatility = std / max(abs(mean_loss), 1e-8)return {"slope": float(slope),"volatility": float(volatility),"mean": float(mean_loss),"std": float(std),"n": int(n),}def _compute_punishment_rate(self) -> float:"""Calcula a taxa de punição na janela observada."""if not self._punishment_history:return 0.0return float(sum(self._punishment_history) / len(self._punishment_history))def _adapt_hyperparameters(self, trigger: str = "auto") -> Dict[str, Any]:"""V6.5-V2-dynamic — Ajusta n_hypotheses, n_trials, hyp_train_steps.Regras (matematicamente justificadas):- loss_volatility > 0.30 e n_hyp < max → n_hyp += 2 (mais diversidade)- loss_volatility < 0.05 e n_hyp > min → n_hyp -= 2 (menos desperdício)- loss_slope > -0.001 (lento/estagnado) e steps < max → steps += 5- loss_slope < -0.01 (rápido) e steps > min → steps -= 5- punishment_rate > 0.30 e n_trials < max → n_trials += 1- punishment_rate < 0.05 e n_trials > min → n_trials -= 1Args:trigger: "auto" (após train_hypotheses), "punishment" (após punição),"manual" (chamada externa).Returns:Dict com estado anterior, novo estado, e regras disparadas."""before = {"n_hypotheses": int(self.n_hypotheses),"n_trials": int(self.n_trials),"hyp_train_steps": int(self.hyp_train_steps),}stats = self._compute_loss_stats()rate = self._compute_punishment_rate()rules_fired: List[str] = []# 1. Ajuste de n_hypotheses (com base em volatilidade)if stats["n"] >= 3:if stats["volatility"] > 0.30 and self.n_hypotheses < self.max_n_hypotheses:new_n = min(self.n_hypotheses + 2, self.max_n_hypotheses)if new_n != self.n_hypotheses:self.n_hypotheses = new_nself.hypothesis_ensemble.set_active_count(new_n)rules_fired.append(f"n_hyp+2 (vol={stats['volatility']:.3f} → {new_n})")elif stats["volatility"] < 0.05 and self.n_hypotheses > self.min_n_hypotheses:new_n = max(self.n_hypotheses - 2, self.min_n_hypotheses)if new_n != self.n_hypotheses:self.n_hypotheses = new_nself.hypothesis_ensemble.set_active_count(new_n)rules_fired.append(f"n_hyp-2 (vol={stats['volatility']:.3f} → {new_n})")# 2. Ajuste de hyp_train_steps (com base em slope)if stats["n"] >= 3:if stats["slope"] > -0.001 and self.hyp_train_steps < self.max_hyp_train_steps:new_steps = min(self.hyp_train_steps + 5, self.max_hyp_train_steps)if new_steps != self.hyp_train_steps:self.hyp_train_steps = new_stepsrules_fired.append(f"steps+5 (slope={stats['slope']:.5f} → {new_steps})")elif stats["slope"] < -0.01 and self.hyp_train_steps > self.min_hyp_train_steps:new_steps = max(self.hyp_train_steps - 5, self.min_hyp_train_steps)if new_steps != self.hyp_train_steps:self.hyp_train_steps = new_stepsrules_fired.append(f"steps-5 (slope={stats['slope']:.5f} → {new_steps})")# 3. Ajuste de n_trials (com base em recorrência de punições)if len(self._punishment_history) >= 3:if rate > 0.30 and self.n_trials < self.max_n_trials:new_t = min(self.n_trials + 1, self.max_n_trials)if new_t != self.n_trials:self.n_trials = new_trules_fired.append(f"n_trials+1 (rate={rate:.3f} → {new_t})")elif rate < 0.05 and self.n_trials > self.min_n_trials:new_t = max(self.n_trials - 1, self.min_n_trials)if new_t != self.n_trials:self.n_trials = new_trules_fired.append(f"n_trials-1 (rate={rate:.3f} → {new_t})")after = {"n_hypotheses": int(self.n_hypotheses),"n_trials": int(self.n_trials),"hyp_train_steps": int(self.hyp_train_steps),}adapted = before != afterrecord = {"trigger": trigger,"step": int(self._last_adaptation_step),"before": before,"after": after,"adapted": bool(adapted),"rules_fired": rules_fired,"loss_stats": stats,"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 recorddef get_adaptation_log(self) -> List[Dict[str, Any]]:"""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)# ==================================================================def train_hypotheses(self,buffer_4d: Optional[List[torch.Tensor]] = None,buffer_labels: Optional[List[int]] = None,) -> Dict[str, Any]:"""Treina os 16 geradores para produzir deltas que melhorem a classificação.Usa uma cópia do SOM para avaliar o efeito de cada delta eretropropaga o erro de classificação para os parâmetros dos geradores.Mathematical formulation:Para cada step s = 1..hyp_train_steps:1. x_state = mean(som_activations(buffer)) # (1, P_som)2. δ_h = scale * g_h(x_state) para h = 1..163. loss_h = BCE(classifier(SOM+δ_h), labels)4. loss = mean_h(loss_h) + λ * ||δ||² (regularização)5. θ_{s+1} = θ_s - η * ∂loss/∂θReturns:Dict com métricas do treino (loss inicial, final, n_steps)."""if buffer_4d is None:buffer_4d = self.buffer_4dif buffer_labels is None:buffer_labels = self.buffer_labelsif not buffer_4d:return {"active": False, "reason": "empty_buffer"}import time as _timet0 = _time.time()# Prepara dadosdata = torch.stack(buffer_4d).detach() # (N, 4)labels = torch.tensor(buffer_labels, dtype=torch.float, device=data.device)# Computa ativações SOM para cada amostra (sem gradiente)with torch.no_grad():som_activations = torch.stack([self._som_activation(data[i]) for i in range(len(data))]) # (N, P_som)# Snapshot dos pesos atuais do SOM (para simular ajustes)som_weights_flat = self.som.weights.detach().clone().flatten() # (P,)self.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()# Ativação média como representação do estado do SOMx_mean = som_activations.mean(dim=0, keepdim=True) # (1, P_som)# Gera deltas: (1, n_hypotheses, P)deltas_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()loss_total.backward()self.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(self.delta_scale.data * 0.99, 0.001, 0.1)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.0self._record_loss(loss_final_val)# V6.5-V2-metrics-FIX-2 — atualiza contadores cumulativos# User requirement: "quantos passos de treino de hipóteses usado"self._total_hyp_steps_executed += int(self.hyp_train_steps)self._n_train_hyp_calls += 1result = {"active": True,"n_steps": self.hyp_train_steps,"n_hypotheses": self.n_hypotheses,"loss_initial": float(losses[0]) if losses else 0.0,"loss_final": loss_final_val,"loss_mean": float(sum(losses) / len(losses)) if losses else 0.0,"delta_scale_final": float(self.delta_scale.item()),"elapsed_ms": float((_time.time() - t0) * 1000),# V6.5-V2-metrics-FIX-2 — contadores cumulativos para monitoramento"total_hyp_steps_executed": int(self._total_hyp_steps_executed),"n_train_hyp_calls": int(self._n_train_hyp_calls),}# V6.5-V2-dynamic — dispara adaptação automática de hiperparâmetrostry:adapt_record = self._adapt_hyperparameters(trigger="auto")result["adaptation"] = adapt_recordexcept Exception as adapt_err:result["adaptation_error"] = str(adapt_err)[:200]return resultdef _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)# ==================================================================def select_best_delta(self,buffer_4d: Optional[List[torch.Tensor]] = None,buffer_labels: Optional[List[int]] = None,n_trials: Optional[int] = None,) -> Tuple[Optional[torch.Tensor], float, Dict[str, Any]]:"""Avalia 3 tentativas × 16 hipóteses e retorna o melhor delta e sua acurácia.Args:buffer_4d, buffer_labels: opcional — usa self.buffer_* se None.n_trials: opcional — usa self.n_trials se None.Returns:Tuple (best_delta, best_acc, info_dict):- best_delta: tensor (P,) ou None se buffer vazio- best_acc: acurácia obtida com o melhor delta- info_dict: métricas da seleção (n_trials, n_hypotheses, etc.)"""if buffer_4d is None:buffer_4d = self.buffer_4dif buffer_labels is None:buffer_labels = self.buffer_labelsif not buffer_4d:return None, -1.0, {"active": False, "reason": "empty_buffer"}if n_trials is None:n_trials = self.n_trialsimport time as _timet0 = _time.time()data = torch.stack(buffer_4d).detach()labels = torch.tensor(buffer_labels, dtype=torch.float, device=data.device)# Computa ativação SOM médiawith torch.no_grad():som_activations = torch.stack([self._som_activation(data[i]) for i in range(len(data))])x_state = som_activations.mean(dim=0, keepdim=True)best_delta = Nonebest_acc = -1.0trial_results = []som_flat = self.som.weights.detach().clone().flatten()self.hypothesis_ensemble.eval()for trial in range(n_trials):# Adiciona ruído à entrada para diversificar tentativas (trial > 0)if trial > 0:x_noisy = x_state + 0.01 * torch.randn_like(x_state)else:x_noisy = x_statewith torch.no_grad():deltas_stack = self.hypothesis_ensemble.forward_stacked(x_noisy)deltas_stack = self.delta_scale * deltas_stack# Avalia cada uma das 16 hipótesestrial_accs = []for h in range(self.n_hypotheses):delta_h = deltas_stack[0, h]som_temp = som_flat + delta_hsom_temp_reshaped = som_temp.view_as(self.som.weights)acc = self._evaluate_accuracy_with_som(som_temp_reshaped, data, labels)trial_accs.append(acc)if acc > best_acc:best_acc = accbest_delta = delta_h.clone()trial_results.append({"trial": trial + 1,"best_acc_in_trial": float(max(trial_accs)) if trial_accs else 0.0,"mean_acc_in_trial": float(sum(trial_accs) / len(trial_accs)) if trial_accs else 0.0,"best_hyp_idx": int(trial_accs.index(max(trial_accs))) if trial_accs else -1,})info = {"active": True,"n_trials": n_trials,"n_hypotheses": self.n_hypotheses,"best_acc": float(best_acc),"delta_norm": float(best_delta.norm().item()) if best_delta is not None else 0.0,"delta_scale": float(self.delta_scale.item()),"trials": trial_results,"elapsed_ms": float((_time.time() - t0) * 1000),}return best_delta, best_acc, infodef _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 EWC# ==================================================================def apply_best_delta_and_consolidate(self,buffer_4d: Optional[List[torch.Tensor]] = None,buffer_labels: Optional[List[int]] = None,) -> Dict[str, Any]:"""Seleciona o melhor delta, aplica ao SOM e executa EWC.Pipeline:1. select_best_delta: avalia 3 tentativas × 16 hipóteses2. Aplica δ* ao SOM: SOM ← SOM + δ*3. Re-avalia acurácia após aplicação4. Consolida via EWC: set_ewc_reference() (Fisher em w)Returns:Dict com métricas (acc_before, acc_after, delta_norm, etc.)"""import time as _timet0 = _time.time()# Avalia acurácia ANTES da aplicaçãoacc_before = self.evaluate_classification()# Seleciona melhor deltabest_delta, best_acc, sel_info = self.select_best_delta(buffer_4d, buffer_labels)if best_delta is None:return {"active": False,"reason": "no_valid_delta","elapsed_ms": float((_time.time() - t0) * 1000),}# V6.5-V2-metrics-FIX-2 — Verifica se best_delta contém NaN/Inf ANTES# de aplicar ao SOM. User requirement: "investigar QE e KL resultando# em NAN". Se o delta tem NaN (devido a gradientes explosivos em# train_hypotheses), aplicar ao SOM contaminaria os pesos e propagaria# NaN para todas as métricas subsequentes (QE, KL, etc.).if torch.isnan(best_delta).any() or torch.isinf(best_delta).any():n_nan = int(torch.isnan(best_delta).sum().item())n_inf = int(torch.isinf(best_delta).sum().item())logger = logging.getLogger(__name__) if 'logging' in dir() else Noneimport logging as _logging_logging.getLogger(__name__).warning(f"[V6.5-V2-metrics-FIX-2] best_delta contains NaN/Inf "f"(nan={n_nan}, inf={n_inf}). SKIPPING application to SOM "f"to prevent weight contamination. Investigate train_hypotheses "f"for gradient explosion (consider lowering hyp_lr or adding "f"gradient clipping).")return {"active": False,"reason": f"best_delta_has_nan (nan={n_nan}, inf={n_inf})","delta_norm": float(best_delta.norm().item()),"elapsed_ms": float((_time.time() - t0) * 1000),"nan_detected": True,}# Aplica o delta ao SOMwith torch.no_grad():som_flat = self.som.weights.flatten()som_flat_new = som_flat + best_delta# V6.5-V2-metrics-FIX-2 — verificação pós-aplicação: se os pesos# do SOM ficaram com NaN (deveria não acontecer após o check acima,# mas defense in depth), reverte para o estado anterior.if torch.isnan(som_flat_new).any() or torch.isinf(som_flat_new).any():import logging as _logging_logging.getLogger(__name__).error(f"[V6.5-V2-metrics-FIX-2] SOM weights became NaN/Inf after "f"delta application. REVERTING to previous weights.")else:self.som.weights = som_flat_new.view_as(self.som.weights)# Re-avalia acurácia APÓS aplicaçãoacc_after = self.evaluate_classification()# Re-rotula neurônios (BMU labels podem ter mudado)self._label_neurons()# Consolida via EWC (Fisher information em w)try:self.som.set_ewc_reference()ewc_set = Trueexcept Exception as e:ewc_set = Falsesel_info["ewc_error"] = str(e)[:200]return {"active": True,"acc_before": float(acc_before),"acc_after": float(acc_after),"best_acc_during_selection": float(best_acc),"delta_norm": float(best_delta.norm().item()),"delta_scale": float(self.delta_scale.item()),"ewc_reference_set": bool(ewc_set),"selection_info": sel_info,"elapsed_ms": float((_time.time() - t0) * 1000),}# ==================================================================# 2.4 Sobrescrita do process_batch para o novo protocolo V2# ==================================================================def process_batch_v2(self,sentences: List[str],labels: List[int],label_strings: Optional[Dict[int, str]] = None,dataset_name: Optional[str] = None,enable_punishment: bool = True,) -> Dict[str, Any]:"""Versão V2 do process_batch com 3 tentativas e 16 hipóteses.Protocolo:- CONHECIMENTO (enable_punishment=False): apenas adiciona dados etreina SOM (sem aplicar punição).- TREINAMENTO COM PUNIÇÃO (enable_punishment=True):* acc < 1.0 → punishment_count += 1* punishment_count == 1: treinar 16 hipóteses + activate_hypothesis* punishment_count == 2: aplicar melhor delta (3×16) + EWC + resetArgs:sentences, labels, label_strings, dataset_name: mesmos de process_batch.enable_punishment: se False, apenas acumula conhecimento (fase 1).Returns:Dict com métricas do batch processado."""import time as _timet0 = _time.time()result: Dict[str, Any] = {"phase": "CONHECIMENTO" if not enable_punishment else "PUNICAO","dataset": dataset_name,"n_samples": len(sentences),"action": "none","cycle_completed": False,}# 1. Adiciona dados ao bufferself.add_data(sentences, labels,label_strings=label_strings,dataset_name=dataset_name,)# 2. Verifica início de treinotraining_started = self.check_training_start()if training_started or self.training_ready:# 3. Treina SOM no buffer (regra de Kohonen)self.train_som_on_buffer()self._label_neurons()result["som_trained"] = Trueif not self.training_ready:result["elapsed_ms"] = float((_time.time() - t0) * 1000)return result# 4. Fase de CONHECIMENTO: para aqui, sem aplicar puniçãoif not enable_punishment:acc = self.evaluate_classification()result["accuracy"] = float(acc)result["elapsed_ms"] = float((_time.time() - t0) * 1000)return result# 5. Fase de PUNIÇÃO: avalia e aplica protocolo V2acc = self.evaluate_classification()result["accuracy"] = float(acc)if acc < 1.0:self.punishment_count += 1self.success_count = 0# V6.5-V2-dynamic — registra evento de puniçãoself._record_punishment_event(True)if self.punishment_count == 1:# 1ª punição: treinar hipóteses + ativar classificadorhyp_info = self.train_hypotheses()if self.classifier is None:self.activate_hypothesis()else:# Re-treina classifier com buffer atualself.activate_hypothesis()result["action"] = "train_hypotheses_and_activate"result["hypotheses_training"] = hyp_infoelif self.punishment_count >= 2:# 2ª punição: selecionar melhor delta (n_trials × n_hyp) + aplicar + EWCapply_info = self.apply_best_delta_and_consolidate()result["action"] = "apply_best_delta_and_consolidate"result["delta_application"] = apply_info# V6.5-V2-dynamic — adapta hiperparâmetros após punição recorrentetry:adapt_record = self._adapt_hyperparameters(trigger="punishment")result["adaptation"] = adapt_recordexcept Exception as adapt_err:result["adaptation_error"] = str(adapt_err)[:200]# Reset do ciclo (mirror training)self.training_ready = Falseself.punishment_count = 0self.success_count = 0self.histogram.clear()# Mantém um sliding window do buffer para preservar contextoif len(self.buffer_4d) > 256:self.buffer_4d = self.buffer_4d[-256:]self.buffer_labels = self.buffer_labels[-256:]result["cycle_completed"] = Trueelse:# acc == 1.0: sucessoself.punishment_count = 0self.success_count += 1# V6.5-V2-dynamic — registra sucesso (sem punição)self._record_punishment_event(False)result["action"] = "success"result["elapsed_ms"] = float((_time.time() - t0) * 1000)return result# ==================================================================# 2.5 API de monitoramento V2# ==================================================================def get_v2_metrics(self) -> Dict[str, Any]:"""Retorna métricas específicas da versão V2 (inclui adaptação dinâmica)."""return {"version": "V2-dynamic","n_hypotheses": int(self.n_hypotheses),"n_hypotheses_active": int(self.hypothesis_ensemble.active_count),"max_n_hypotheses": int(self.max_n_hypotheses),"n_trials": int(self.n_trials),"hyp_train_steps": int(self.hyp_train_steps),"hyp_lr": float(self.hyp_lr),"delta_scale": float(self.delta_scale.item()),"n_generators": int(len(self.hypothesis_ensemble.generators)),"punishment_count": int(self.punishment_count),"success_count": int(self.success_count),"training_ready": bool(self.training_ready),"classifier_trained": bool(self.classifier_trained),"ewc_reference_set": bool(self.som.old_weights_w is not None),"buffer_size": int(len(self.buffer_4d)),# V6.5-V2-metrics-FIX-2 — contadores cumulativos (user requirement:# "quantos passos de treino de hipóteses usado")"total_hyp_steps_executed": int(getattr(self, "_total_hyp_steps_executed", 0)),"n_train_hyp_calls": int(getattr(self, "_n_train_hyp_calls", 0)),"dynamic_adaptation": {"loss_history_len": int(len(self._loss_history)),"loss_stats": self._compute_loss_stats(),"punishment_rate": float(self._compute_punishment_rate()),"punishment_window_size": int(len(self._punishment_history)),"n_adaptations": int(len(self._adaptation_log)),"limits": {"min_n_hypotheses": int(self.min_n_hypotheses),"max_n_hypotheses": int(self.max_n_hypotheses),"min_n_trials": int(self.min_n_trials),"max_n_trials": int(self.max_n_trials),"min_hyp_train_steps": int(self.min_hyp_train_steps),"max_hyp_train_steps": int(self.max_hyp_train_steps),},"last_5_adaptations": self._adaptation_log[-5:] if self._adaptation_log else [],},}# ==================================================================# V6.5-V2-metrics-FIX-2 — Detecção de atividade de hipóteses e neurônios# ==================================================================# User requirement (latest): "Aprimorar a FASE2 PUNITIVA investigar QE e KL# resultando em NAN, acrescentar detecção da atividade das layers (quantas# ativadas) de hipóteses e das ativações dos neurônios, quantos passos de# treino de hipóteses usado".## Mathematical formulation:## Hipótese ativa: Um gerador g_h (h ∈ {1..n_hypotheses}) é considerado# "ativo" em um batch se o delta que ele produz tem norma L2 > threshold# (default 1e-6). Deltas com norma ≈ 0 indicam que o gerador está# produzindo saída trivial (morto) — não contribui para a diversidade# do ensemble.## active_h = 1 if ||δ_h||₂ > threshold else 0# n_active_hypotheses = Σ_h active_h## Neurônio ativo: Um neurônio (i,j,k,l) é "ativo" se é BMU para pelo# menos uma amostra do buffer atual. Reuso da lógica de dead_neuron_rate,# mas exposto como métrica explícita para monitoramento contínuo.## n_active_neurons = |{W_bmu(x_i) : i ∈ buffer}|# n_dead_neurons = n_total - n_active_neurons# neuron_activation_rate = n_active_neurons / n_total## Passos de treino de hipóteses: Número total de passos de Adam executados# em train_hypotheses() desde o início do treino. Cumulativo ao longo de# todas as chamadas (punições).## total_hyp_train_steps = Σ_call self.hyp_train_steps (na época da call)# ------------------------------------------------------------------def detect_hypothesis_activity(self,threshold: float = 1e-6,) -> Dict[str, Any]:"""V6.5-V2-metrics-FIX-2 — Detecta quantas hipóteses estão ativas.User requirement: "acrescentar detecção da atividade das layers(quantas ativadas) de hipóteses".Executa um forward pass do HypothesisEnsemble sobre a ativação médiado SOM no buffer atual e conta quantos dos active_count geradoresproduzem deltas com norma > threshold.Args:threshold: norma L2 mínima para considerar um delta "ativo".Returns:Dict com:- n_hypotheses_active: int (quantas hipóteses produziram delta ≠ 0)- n_hypotheses_total: int (active_count atual do ensemble)- max_n_hypotheses: int (limite máximo pré-alocado)- delta_norms: list[float] (norma de cada delta, para inspeção)- active_mask: list[bool] (True para hipóteses ativas)- activation_rate: float (n_active / n_total)- mean_delta_norm: float (média das normas)- max_delta_norm: float (maior norma)- threshold_used: float"""if not self.buffer_4d:return {"n_hypotheses_active": 0,"n_hypotheses_total": int(self.hypothesis_ensemble.active_count),"max_n_hypotheses": int(self.max_n_hypotheses),"delta_norms": [],"active_mask": [],"activation_rate": 0.0,"mean_delta_norm": 0.0,"max_delta_norm": 0.0,"threshold_used": float(threshold),"reason": "empty_buffer",}try:import torch as _torchwith _torch.no_grad():# Computa ativação SOM média do bufferdata = _torch.stack(self.buffer_4d).detach()som_activations = _torch.stack([self._som_activation(data[i]) for i in range(len(data))])x_mean = som_activations.mean(dim=0, keepdim=True) # (1, P_som)# Forward do ensemble: retorna (1, n_hyp, P)deltas_stack = self.hypothesis_ensemble.forward_stacked(x_mean)deltas_stack = self.delta_scale * deltas_stack # aplica escala# Norma L2 de cada delta: (n_hyp,)delta_norms = deltas_stack[0].norm(dim=-1) # (n_hyp,)delta_norms_list = [float(x) for x in delta_norms]active_mask = [bool(x > threshold) for x in delta_norms_list]n_active = sum(active_mask)# Libera tensoresdel deltas_stack, som_activations, data, x_mean, delta_normsreturn {"n_hypotheses_active": int(n_active),"n_hypotheses_total": int(self.hypothesis_ensemble.active_count),"max_n_hypotheses": int(self.max_n_hypotheses),"delta_norms": delta_norms_list,"active_mask": active_mask,"activation_rate": float(n_active / max(1, self.hypothesis_ensemble.active_count)),"mean_delta_norm": float(sum(delta_norms_list) / max(1, len(delta_norms_list))),"max_delta_norm": float(max(delta_norms_list) if delta_norms_list else 0.0),"threshold_used": float(threshold),}except Exception as e:return {"n_hypotheses_active": 0,"n_hypotheses_total": int(self.hypothesis_ensemble.active_count),"max_n_hypotheses": int(self.max_n_hypotheses),"delta_norms": [],"active_mask": [],"activation_rate": 0.0,"mean_delta_norm": 0.0,"max_delta_norm": 0.0,"threshold_used": float(threshold),"error": str(e)[:200],}def count_active_neurons(self) -> Dict[str, Any]:"""V6.5-V2-metrics-FIX-2 — Conta neurônios ativos (BMUs) no buffer.User requirement: "acrescentar (...) das ativações dos neurônios".Para cada amostra no buffer_4d, encontra o BMU. Conta quantosneurônios únicos são BMUs (n_active_neurons) e quantos nunca sãoBMUs (n_dead_neurons = n_total - n_active).Returns:Dict com:- n_active_neurons: int (neurônios que são BMU para ≥1 amostra)- n_dead_neurons: int (neurônios que nunca são BMU)- n_total_neurons: int (total de neurônios no SOM)- neuron_activation_rate: float (n_active / n_total)- bmu_distribution: dict {flat_idx: count} (top-20 mais frequentes)"""if not self.buffer_4d:return {"n_active_neurons": 0,"n_dead_neurons": int(self.som_neuron_count),"n_total_neurons": int(self.som_neuron_count),"neuron_activation_rate": 0.0,"bmu_distribution": {},"reason": "empty_buffer",}try:import torch as _torchwith _torch.no_grad():data = _torch.stack(self.buffer_4d).detach()flat_w = self.som.weights.view(-1, 4).detach()# (N, M) distânciasdiff = data.unsqueeze(1) - flat_w.unsqueeze(0)dist_sq = _torch.sum(diff * diff, dim=-1)_, bmu_flat = _torch.min(dist_sq, dim=1) # (N,)bmu_list = bmu_flat.tolist()unique_bmus = set(bmu_list)n_active = len(unique_bmus)n_total = self.som_neuron_count# Distribuição dos BMUs (top-20)from collections import Counterbmu_counts = Counter(bmu_list)bmu_distribution = dict(bmu_counts.most_common(20))del data, flat_w, diff, dist_sq, bmu_flatreturn {"n_active_neurons": int(n_active),"n_dead_neurons": int(n_total - n_active),"n_total_neurons": int(n_total),"neuron_activation_rate": float(n_active / max(1, n_total)),"bmu_distribution": {str(k): int(v) for k, v in bmu_distribution.items()},}except Exception as e:return {"n_active_neurons": 0,"n_dead_neurons": int(self.som_neuron_count),"n_total_neurons": int(self.som_neuron_count),"neuron_activation_rate": 0.0,"bmu_distribution": {},"error": str(e)[:200],}def get_hyp_train_steps_used(self) -> Dict[str, Any]:"""V6.5-V2-metrics-FIX-2 — Retorna quantos passos de treino de hipótesesforam usados até agora.User requirement: "quantos passos de treino de hipóteses usado".Returns:Dict com:- current_hyp_train_steps: int (valor ATUAL de self.hyp_train_steps)- total_hyp_train_steps_executed: int (cumulativo ao longo do treino)- n_train_hypotheses_calls: int (número de chamadas a train_hypotheses)- min_hyp_train_steps: int (limite inferior dinâmico)- max_hyp_train_steps: int (limite superior dinâmico)"""return {"current_hyp_train_steps": int(self.hyp_train_steps),"total_hyp_train_steps_executed": int(getattr(self, "_total_hyp_steps_executed", 0)),"n_train_hypotheses_calls": int(getattr(self, "_n_train_hyp_calls", 0)),"min_hyp_train_steps": int(self.min_hyp_train_steps),"max_hyp_train_steps": int(self.max_hyp_train_steps),}# ==================================================================# 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","positional_encoding","text_to_4d_vector","KohonenSOM4D","HypothesisClassifier","KohonenLearningSystem","DeltaGenerator","HypothesisEnsemble","KohonenLearningSystemV2",]# V6.5-V2-metrics: som_metrics é importado lazy (dentro de compute_som_metrics)# para evitar dependência circular e permitir uso standalone.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995"""streaming_datasets_v13_9.py — Streaming dataset loader for v13.9.1 training.
Carrega os 9 datasets especificados pelo usuário via streaming (IterableDataset),um por vez, exaustivamente dentro do limite max_samples_per_dataset.
Datasets: 1. CEIA-POSITIVO/ultrachat_br_clustred_balanced_v1 2. Madras1/corpus-ptbr-v2 3. rhaymison/multmodal_175k_portuguese 4. TucanoBR/GigaVerbo 5. nvidia/OpenMathReasoning 6. MathLLMs/MathVision 7. nvidia/OpenMathInstruct-2 8. dominguesm/restore-punctuation-ptbr-dataset 9. carolina-c4ai/corpus-carolina
Memory-efficient: streaming=True, no full materialization.Returns ProcessedSample with raw_text only (tokenizer handles encoding)."""from __future__ import annotations
import loggingimport osimport timeimport tracebackfrom dataclasses import dataclass, fieldfrom typing import Any, Dict, Iterator, List, Optional, Tuple
import torch
logger = logging.getLogger(__name__)
# Datasets V13.9.1 — exatamente os 9 especificados pelo usuário# V6.5-final: adicionado dominguesm/Canarim-Instruct-PTBR-Dataset# V6.5-7ds: adicionados adalbertojunior/punctuation-ptbr,# iara-project/news-articles-ptbr-dataset, manoela/noticias_ptbr# V6.5-V2: adicionado BrunoN-Dev/corpus-ptbr-v1 como 8º dataset de CONHECIMENTO# e usado como dataset de TREINAMENTO COM PUNIÇÃODEFAULT_DATASETS = [ "CEIA-POSITIVO/ultrachat_br_clustred_balanced_v1", "Madras1/corpus-ptbr-v2", "rhaymison/multmodal_175k_portuguese", "TucanoBR/GigaVerbo", "nvidia/OpenMathReasoning", "MathLLMs/MathVision", "nvidia/OpenMathInstruct-2", "dominguesm/restore-punctuation-ptbr-dataset", "carolina-c4ai/corpus-carolina", "dominguesm/Canarim-Instruct-PTBR-Dataset", "adalbertojunior/punctuation-ptbr", "iara-project/news-articles-ptbr-dataset", "manoela/noticias_ptbr", "BrunoN-Dev/corpus-ptbr-v1",]
# V6.5-V2 — Sequência de 8 datasets para a fase CONHECIMENTO (na ordem exata# especificada pelo usuário). Meta mínima: 8000 samples ou mais.CONHECIMENTO_DATASETS_V2 = [ "dominguesm/restore-punctuation-ptbr-dataset", "carolina-c4ai/corpus-carolina", "CEIA-POSITIVO/ultrachat_br_clustred_balanced_v1", "dominguesm/Canarim-Instruct-PTBR-Dataset", "adalbertojunior/punctuation-ptbr", "iara-project/news-articles-ptbr-dataset", "manoela/noticias_ptbr", "BrunoN-Dev/corpus-ptbr-v1",]
# V6.5-V2 — Dataset para TREINAMENTO COM PUNIÇÃO (500 samples).# O usuário especificou: "dataset para TREINAMENTO COM PUNIÇÃO ATIVA# 'BrunoN-Dev/corpus-ptbr-v1'".PUNICAO_DATASET_V2 = "BrunoN-Dev/corpus-ptbr-v1"
# Dataset format descriptors — Lista priorizada de campos de textoDATASET_FORMATS: Dict[str, Dict[str, Any]] = { "CEIA-POSITIVO/ultrachat_br_clustred_balanced_v1": { "type": "chat", "text_fields": ["conversa", "text", "content", "conversation", "messages"], "label_fields": [], "split": "train", "config": None, }, "Madras1/corpus-ptbr-v2": { "type": "text", "text_fields": ["text", "content", "document", "body"], "label_fields": [], "split": "train", "config": None, }, "rhaymison/multmodal_175k_portuguese": { "type": "multimodal", "text_fields": ["description", "text", "question", "prompt", "instruction", "input"], "image_fields": ["image", "image_url"], "label_fields": ["answer", "response", "output"], "split": "train", "config": None, }, "TucanoBR/GigaVerbo": { "type": "text", "text_fields": ["text", "content", "document", "body"], "label_fields": [], "split": "train", "config": None, }, "nvidia/OpenMathReasoning": { "type": "math", "text_fields": ["problem", "question", "input", "prompt"], "label_fields": ["solution", "answer", "output", "response"], # BUG FIX: OpenMathReasoning has splits ['cot', 'tir', 'genselect', 'additional_problems'] "split": "cot", # Use 'cot' (chain-of-thought) as primary split "config": None, }, "MathLLMs/MathVision": { "type": "math_multimodal", "text_fields": ["question", "problem", "text", "query"], "image_fields": ["image", "image_url"], "label_fields": ["answer", "solution", "response"], # BUG FIX: MathVision has only 'test' and 'testmini' splits (no train) "split": "test", "config": None, }, "nvidia/OpenMathInstruct-2": { "type": "math", "text_fields": ["problem", "question", "input", "prompt"], # V3 FIX: campos reais do dataset são generated_solution e expected_answer "label_fields": ["generated_solution", "expected_answer", "solution", "answer", "output", "response"], "split": "train", "config": None, }, "dominguesm/restore-punctuation-ptbr-dataset": { "type": "punctuation", "text_fields": ["text", "original", "unpunctuated", "input"], "label_fields": ["punctuated", "restored", "target", "output"], "split": "train", "config": None, }, "carolina-c4ai/corpus-carolina": { "type": "text", "text_fields": ["text", "content", "document", "body", "xml"], "label_fields": [], "split": "train", "config": None, # V13.9.2-carolina: dataset original usa script Python (não suportado em # datasets 5.0+). Workaround: stream_xml_gz direto via lxml.iterparse, # sem usar o script Python. Implementado em _stream_carolina_direct(). }, # ── V13.9.2-finetune-v2: novos datasets PT-BR ─────────────────────────── # Adicionados para fine-tuning contínuo do modelo v13.9.2 (preserva # arquitetura e parâmetros). Nenhuma mudança estrutural — apenas novos # descritores de formato para que stream_dataset() reconheça os datasets. # # V13.9.2-finetune-v3: padronização para o formato unificado # "### Instruction:\n...\n\n### Response:\n..." conforme requisitado pelo # usuário. Apenas os datasets com estrutura instruction/response (orion, # cnmoro) usam o template; strak2005/bratao continuam como texto puro # (corpus sem estrutura de instrução). Nenhuma mudança nos 9 datasets # base — retrocompatibilidade total. "orion-research/translations-en_US-pt_BR": { "type": "translation", # string = EN (instruction), string_translation = PT-BR (response). # V13.9.2-finetune-v3: separa instruction/response para o template # unificado em vez de concatenar como texto único. "text_fields": ["string"], "label_fields": ["string_translation"], "split": "train", "config": None, "format_template": "instruction_response", "instruction_prefix": "Translate the following text to Portuguese:", }, "cnmoro/Instruct-PTBR-10M": { "type": "instruct", # NB: campos em MAIÚSCULAS no schema do dataset # V13.9.2-finetune-v3: INSTRUCTION -> instruction, RESPONSE -> response # via template unificado. "text_fields": ["INSTRUCTION"], "label_fields": ["RESPONSE"], "split": "train", "config": None, "format_template": "instruction_response", # V13.9.2-finetune-v2: dataset é um único parquet de 10 GB — streaming # via datasets.load_dataset() é extremamente lento para materializar # a primeira amostra. Fallback via HF datasets-server rows API (HTTP), # que retorna batches de 100 rows rapidamente. Implementado em # _stream_via_rows_api(). "loader": "rows_api", }, "strak2005/corpus-ptbr-v1": { "type": "text", "text_fields": ["text", "content"], "label_fields": [], "split": "train", "config": None, # Fallback: se strak2005 cair, tenta bratao (mirror idêntico) "fallback": "bratao/corpus-ptbr-v1", # V13.9.2-finetune-v2: dataset tem 18 shards parquet de ~1GB cada. # Streaming via datasets.load_dataset() não materializa primeira # amostra em tempo aceitável. Fallback: baixa 1 shard localmente e # itera com pyarrow. Implementado em _stream_via_parquet_first_shard(). "loader": "parquet_first_shard", }, "bratao/corpus-ptbr-v1": { "type": "text", "text_fields": ["text", "content"], "label_fields": [], "split": "train", "config": None, "loader": "parquet_first_shard", }, # ── V6.5: novos datasets para esgotar ──────────────────────────────── # User requirement: "esgotar 'dominguesm/restore-punctuation-ptbr-dataset' # e 'carolina-c4ai/corpus-carolina' e 'nvidia/OpenMathInstruct-2' e # 'nvidia/OpenMathReasoning' e 'CEIA-POSITIVO/ultrachat_br_clustred_balanced_v1' # e 'Dexavator/English-PTBR'" # # Dexavator/English-PTBR: dataset de tradução EN->PT-BR. # Estrutura típica: {"english": "...", "portuguese": "..."} ou # {"en": "...", "pt": "..."}. "Dexavator/English-PTBR": { "type": "translation", "text_fields": ["english", "en", "text", "source"], "label_fields": ["portuguese", "pt", "target", "translation"], "split": "train", "config": None, "format_template": "instruction_response", "instruction_prefix": "Translate the following text to Portuguese:", }, # ── V6.5-final: Canarim-Instruct-PTBR-Dataset ──────────────────────── # User requirement: "esgotar 'dominguesm/Canarim-Instruct-PTBR-Dataset'" # Canarim-Instruct: dataset PT-BR de instruções (~430k samples). # Estrutura típica: {"instruction": "...", "input": "...", "output": "..."} # ou {"text": "...", "conversation": [{"role": "user", "content": "..."}, ...]} "dominguesm/Canarim-Instruct-PTBR-Dataset": { "type": "instruct", "text_fields": ["instruction", "input", "text", "prompt", "question"], "label_fields": ["output", "response", "answer"], "split": "train", "config": None, "format_template": "instruction_response", "instruction_prefix": "Instrução:", }, # ── V6.5-7ds: novos 3 datasets PT-BR ───────────────────────────────── # User requirement (latest): "streaming até esgotar nesta sequência # 'dominguesm/restore-punctuation-ptbr-dataset' e # 'carolina-c4ai/corpus-carolina' e # 'CEIA-POSITIVO/ultrachat_br_clustred_balanced_v1' e # 'dominguesm/Canarim-Instruct-PTBR-Dataset' e # 'adalbertojunior/punctuation-ptbr' e # 'iara-project/news-articles-ptbr-dataset' e # 'manoela/noticias_ptbr'" # # adalbertojunior/punctuation-ptbr: # Dataset de restauração de pontuação PT-BR. Schema: # {id: str, tokens: list[str], pos_tags, chunk_tags, ner_tags} # O campo "tokens" é uma lista de palavras (sem pontuação). Precisamos # fazer join com espaços para obter texto bruto. Como o dataset usa # script Python (datasets 5.0+ não suporta), usamos rows_api loader. # Splits: train/validation/test com config "punctuation-ptbr". "adalbertojunior/punctuation-ptbr": { "type": "punctuation_tokens", "text_fields": ["tokens"], # list[str] — join com espaços "label_fields": [], "split": "train", "config": "punctuation-ptbr", # necessário para rows_api "loader": "rows_api", "join_tokens": True, # flag especial para _normalize_sample }, # iara-project/news-articles-ptbr-dataset: # Dataset de notícias PT-BR da Folha de S.Paulo (via IARA project). # Schema: {title, text, date, category, category_natural_language, link} # Streaming normal via parquet — primeira amostra materializa rápido. # "text" é o corpo da notícia, "title" é o título. Concatenamos ambos # via format_template="title_text_concat" para enriquecer contexto. # O campo "category" é usado como label (categoria da notícia). "iara-project/news-articles-ptbr-dataset": { "type": "news", # text_fields em ordem de prioridade: "text" (corpo) primeiro "text_fields": ["text", "title", "content", "body"], "label_fields": ["category", "category_natural_language", "title"], "split": "train", "config": None, # V6.5-7ds: title_text_concat usa title como label (prefixo) # e text como corpo. Aqui label_fields pega "category" primeiro # para dar contexto temático. "format_template": "title_text_concat", }, # manoela/noticias_ptbr: # Mirror do iara-project/news-articles-ptbr-dataset (mesmo parquet, # mesmo schema). Streaming normal via parquet. "manoela/noticias_ptbr": { "type": "news", "text_fields": ["text", "title", "content", "body"], "label_fields": ["category", "category_natural_language", "title"], "split": "train", "config": None, "format_template": "title_text_concat", }, # ── V6.5-V2: BrunoN-Dev/corpus-ptbr-v1 ─────────────────────────────── # User requirement: "dataset para TREINAMENTO COM PUNIÇÃO ATIVA # 'BrunoN-Dev/corpus-ptbr-v1'" e o 8º dataset de CONHECIMENTO. # # BrunoN-Dev/corpus-ptbr-v1: corpus PT-BR genérico com 18 shards parquet # (~1GB cada). Schema: {"text": "...", "meta": "..."}. # Streaming via datasets.load_dataset(streaming=True) é lento para # materializar a primeira amostra — usamos o loader parquet_first_shard # (baixa apenas o primeiro shard e itera localmente com pyarrow). # Sem label explícita — usamos hash do texto (paridade do nº de palavras) # para gerar label binário (0/1) — não é dado sintético, é derivação # algorítmica do conteúdo real do dataset. "BrunoN-Dev/corpus-ptbr-v1": { "type": "text", "text_fields": ["text", "content", "body", "document"], "label_fields": [], "split": "train", "config": None, "loader": "parquet_first_shard", # V6.5-V2: gera label binário determinístico via hash do texto # (paridade do número de palavras) — não é dado sintético, é # derivação algorítmica do conteúdo real do dataset. "label_strategy": "hash_parity", },}
# Lista de arquivos XML.gz do Carolina que tentaremos baixar (ordem: menores# taxonomias primeiro para minimizar banda e RAM). Selecionamos 2 arquivos# por taxonomia para garantir diversidade sem explodir a memória.CAROLINA_XML_FILES = [ # taxonomia "datasets_and_other_corpora" (DAT = pt-BR notícias) "corpus/datasets_and_other_corpora/pt-BR/DATa.xml.gz", "corpus/datasets_and_other_corpora/pt-BR/DATb.xml.gz", # taxonomia "wik" (wikis) "corpus/wik/WIKa.xml.gz", "corpus/wik/WIKb.xml.gz", # taxonomia "uni" (university_domains) "corpus/uni/UNIa.xml.gz", "corpus/uni/UNIb.xml.gz", # taxonomia "pub" (public_domain_works) "corpus/pub/PUBa.xml.gz", "corpus/pub/PUBb.xml.gz",]
def _stream_carolina_direct( max_samples: int, hf_token: Optional[str] = None, timeout_per_file: int = 60,) -> Iterator[Dict[str, Any]]: """Workaround V13.9.2-carolina: carrega Carolina sem usar o script Python.
Baixa arquivos XML.gz diretamente do repo e faz parse streaming com lxml.etree.iterparse (compatível com datasets 5.0+). Cada <TEI> vira um documento de texto (concatenação dos <p> dentro de <body>).
Args: max_samples: número máximo de amostras a retornar hf_token: token HF opcional (dataset é público, mas token evita rate limit) timeout_per_file: tempo máximo (segundos) por arquivo XML
Yields: dict com chave "text" (compatível com _normalize_sample) """ from huggingface_hub import hf_hub_download import gzip from lxml import etree
TEI_NS = "{http://www.tei-c.org/ns/1.0}" BODY_P_TAG = f".//{TEI_NS}body/{TEI_NS}p"
count = 0 for xml_path in CAROLINA_XML_FILES: if count >= max_samples: return try: local_path = hf_hub_download( repo_id="carolina-c4ai/corpus-carolina", filename=xml_path, repo_type="dataset", token=hf_token, ) except Exception as e: logger.warning(f"Carolina: não foi possível baixar {xml_path}: {e}") continue
try: with gzip.open(local_path, "rb") as gz: # iterparse streaming: não carrega árvore inteira na memória for _, tei in etree.iterparse( gz, huge_tree=True, encoding="utf-8", tag=f"{TEI_NS}TEI" ): if count >= max_samples: tei.clear() return # Extrai texto dos <p> dentro de <body> parts = [] for p in tei.findall(BODY_P_TAG): if p.text: parts.append(p.text) text = " ".join(parts).strip() if text and len(text) >= 10: yield {"text": text, "meta": ""} tei.clear() # libera memória da árvore TEI count += 1 except Exception as e: logger.warning(f"Carolina: erro processando {xml_path}: {e}") continue
logger.info(f"Carolina: streamou {count} amostras no total")
# ═══════════════════════════════════════════════════════════════════════════# V13.9.2-finetune-v2: Loaders alternativos para datasets parquet grandes# onde datasets.load_dataset(streaming=True) é inviável (primeira amostra# demora minutos para materializar).# ═══════════════════════════════════════════════════════════════════════════
def _stream_via_rows_api( dataset_name: str, max_samples: int, hf_token: Optional[str] = None, batch_size: int = 100, max_offset: int = 100_000, config: Optional[str] = None, split: str = "train",) -> Iterator[Dict[str, Any]]: """Carrega amostras via HF datasets-server /rows API (HTTP).
Usado para datasets cujo parquet é muito grande para streaming eficiente (ex: cnmoro/Instruct-PTBR-10M com 10 GB em arquivo único) OU datasets que usam script Python como loader (não suportado em datasets 5.0+, ex: adalbertojunior/punctuation-ptbr). A rows API retorna batches de até 100 rows via HTTP, sem precisar baixar o parquet.
Args: dataset_name: repo_id do dataset (ex: "cnmoro/Instruct-PTBR-10M") max_samples: nº máximo de amostras a retornar hf_token: token HF (opcional — dataset público) batch_size: nº de rows por requisição (máx 100) max_offset: offset máximo a tentar (sai do loop se excedido) config: nome da config do dataset (default: "default"). NECESSÁRIO para datasets cuja config não é "default" (ex: adalbertojunior/punctuation-ptbr usa "punctuation-ptbr"). split: nome do split (default: "train").
Yields: dict com campos do dataset (compatível com _normalize_sample) """ import json as _json import urllib.request import urllib.parse
base_url = "https://datasets-server.huggingface.co/rows" config_name = config or "default" count = 0 offset = 0
while count < max_samples and offset < max_offset: params = urllib.parse.urlencode({ "dataset": dataset_name, "config": config_name, "split": split, "offset": offset, "length": min(batch_size, max_samples - count), }) url = f"{base_url}?{params}" try: req = urllib.request.Request(url) if hf_token: req.add_header("Authorization", f"Bearer {hf_token}") with urllib.request.urlopen(req, timeout=30) as r: data = _json.loads(r.read()) except Exception as e: logger.warning(f"rows_api {dataset_name} config={config_name} offset={offset}: {e}") break
rows = data.get("rows", []) if not rows: break
for row in rows: if count >= max_samples: return row_data = row.get("row", {}) # Remove campos internos como __index_level_0__ clean = {k: v for k, v in row_data.items() if not k.startswith("__")} yield clean count += 1
offset += len(rows) if len(rows) < batch_size: break # chegou ao fim do dataset
logger.info(f"rows_api {dataset_name} config={config_name}: streamou {count} amostras")
def _stream_via_parquet_first_shard( dataset_name: str, max_samples: int, hf_token: Optional[str] = None,) -> Iterator[Dict[str, Any]]: """Baixa primeiro shard parquet do dataset e itera localmente com pyarrow.
Usado para datasets com múltiplos shards parquet grandes (ex: strak2005/corpus-ptbr-v1 com 18 shards de ~1GB). Streaming via datasets.load_dataset() não materializa primeira amostra em tempo aceitável. Esta função baixa o primeiro shard (~26s para 1GB) e itera localmente — rápido após download.
Args: dataset_name: repo_id do dataset max_samples: nº máximo de amostras hf_token: token HF opcional
Yields: dict com campos do dataset """ from huggingface_hub import HfApi, hf_hub_download import pyarrow.parquet as pq
api = HfApi(token=hf_token)
# Lista arquivos parquet no repo try: info = api.dataset_info(dataset_name) except Exception as e: logger.warning(f"parquet_shard {dataset_name}: dataset_info failed: {e}") return
parquet_files = sorted([ s.rfilename for s in info.siblings if s.rfilename.endswith(".parquet") ]) if not parquet_files: logger.warning(f"parquet_shard {dataset_name}: nenhum .parquet encontrado") return
# Baixa apenas o primeiro shard first_shard = parquet_files[0] logger.info(f"parquet_shard {dataset_name}: baixando {first_shard}...") try: local_path = hf_hub_download( repo_id=dataset_name, filename=first_shard, repo_type="dataset", token=hf_token, ) except Exception as e: logger.warning(f"parquet_shard {dataset_name}: download failed: {e}") return
# Itera com pyarrow.iter_batches — método eficiente que lê batches pequenos # do parquet sem materializar o row group inteiro na memória. # BUG FIX V13.9.2-finetune-v2: read_row_group() materializa TODAS as ~1M # rows de uma vez (lento + ~1GB RAM). iter_batches(batch_size=10) lê só # 10 rows por vez (rápido + ~10KB RAM). try: pf = pq.ParquetFile(local_path) count = 0 # batch_read_size: nº de rows por batch (pequeno = menos RAM) for batch in pf.iter_batches(batch_size=100): if count >= max_samples: break cols = batch.schema.names # to_pylist() é eficiente para batches pequenos pydict = batch.to_pydict() n_rows = len(pydict[cols[0]]) if cols else 0 for i in range(n_rows): if count >= max_samples: break row = {col: pydict[col][i] for col in cols} yield row count += 1 except Exception as e: logger.warning(f"parquet_shard {dataset_name}: pyarrow iter failed: {e}") return
logger.info(f"parquet_shard {dataset_name}: streamou {count} amostras do shard {first_shard}")
@dataclassclass ProcessedSample: """Uma amostra processada: texto bruto + metadados.""" raw_text: str dataset_name: str sample_idx: int text_field: str = "" label_text: str = ""
def _extract_field(sample: Dict[str, Any], candidate_fields: List[str]) -> Optional[str]: """Extrai texto da primeira field disponível no sample.
Suporta: - strings diretas - listas de strings (join com espaço — útil para datasets tokenizados como adalbertojunior/punctuation-ptbr onde "tokens": ["hoje","a",...]) - listas de dicts (chat messages — concatena role: content) - dicts aninhados (pega text/content/body) """ for field_name in candidate_fields: if field_name in sample: val = sample[field_name] if val is None: continue if isinstance(val, str): if val.strip(): return val elif isinstance(val, list): # V6.5-7ds: se for lista de strings, join com espaços # (ex: adalbertojunior/punctuation-ptbr tokens field) string_parts = [] chat_parts = [] all_strings = True for item in val: if isinstance(item, str): if item.strip(): string_parts.append(item) elif isinstance(item, (int, float)): # tokens podem vir como ints (token IDs) — skip all_strings = False break elif isinstance(item, dict): all_strings = False role = item.get("role", "") content = item.get("content", "") if isinstance(content, str) and content.strip(): chat_parts.append(f"{role}: {content}") else: all_strings = False if all_strings and string_parts: joined = " ".join(string_parts).strip() if joined: return joined if chat_parts: return "\n".join(chat_parts) elif isinstance(val, dict): # Pode ser nested text = val.get("text") or val.get("content") or val.get("body") if isinstance(text, str) and text.strip(): return text return None
def _normalize_sample(sample: Dict[str, Any], dataset_name: str, idx: int) -> Optional[ProcessedSample]: """Normaliza uma amostra bruta em ProcessedSample.""" fmt = DATASET_FORMATS.get(dataset_name, {}) text_fields = fmt.get("text_fields", ["text"]) label_fields = fmt.get("label_fields", [])
text = _extract_field(sample, text_fields) if not text or len(text.strip()) < 10: # skip very short return None
label = "" if label_fields: label = _extract_field(sample, label_fields) or ""
# Se tem label, aplica template apropriado template = fmt.get("format_template") full_text = text
# V13.9.2-finetune-v3: para o template instruction_response, exige ambos # os lados (instruction + response). Samples sem response são descartados # para evitar treinar em texto parcial. if template == "instruction_response" and not label: return None
if label: # V13.9.2-finetune-v3: format_template unificado "### Instruction:/### Response:" # quando o dataset declarar explicitamente. Caso contrário, mantém o # comportamento legado (concatenação simples text\nlabel) para os 9 # datasets base — retrocompatibilidade total. if template == "instruction_response": instr_prefix = fmt.get("instruction_prefix", "") if instr_prefix: full_text = ( f"### Instruction:\n{instr_prefix}\n{text}\n\n" f"### Response:\n{label}" ) else: full_text = ( f"### Instruction:\n{text}\n\n" f"### Response:\n{label}" ) elif template == "title_text_concat": # V6.5-7ds: para datasets de notícias (iara-project, manoela), # o campo "text" (corpo da notícia) é o conteúdo principal e # "category" (categoria) é o contexto temático. Formatamos como # "TEXTO: <corpo>\nCATEGORIA: <categoria>". full_text = f"TEXTO: {text}\nCATEGORIA: {label}" else: # Comportamento legado (9 datasets base): concatenação simples full_text = f"{text}\n{label}"
return ProcessedSample( raw_text=full_text, dataset_name=dataset_name, sample_idx=idx, text_field=text_fields[0] if text_fields else "", label_text=label, )
def _load_dataset_streaming( dataset_name: str, split: str = "train", config: Optional[str] = None, hf_token: Optional[str] = None,): """Carrega dataset em modo streaming.
BUG FIX V13.9.1: Removido trust_remote_code (deprecated). Se o dataset não carregar com split especificado, tenta 'train' como fallback. BUG FIX V13.9.2: Adicionado fallback para datasets com script (carolina-c4ai). """ from datasets import load_dataset
# Lista de splits para tentar, em ordem splits_to_try = [split] if split != "train": splits_to_try.append("train") # Adiciona outros splits comuns for s in ["test", "validation", "cot", "tir"]: if s not in splits_to_try: splits_to_try.append(s)
fmt = DATASET_FORMATS.get(dataset_name, {}) fallback_name = fmt.get("fallback") datasets_to_try = [dataset_name] if fallback_name: datasets_to_try.append(fallback_name)
for try_ds_name in datasets_to_try: for try_split in splits_to_try: try: if config: ds = load_dataset( try_ds_name, config, split=try_split, streaming=True, token=hf_token, ) else: ds = load_dataset( try_ds_name, split=try_split, streaming=True, token=hf_token, ) logger.info(f"Loaded {try_ds_name} split={try_split}") return ds except Exception as e: err_str = str(e).lower() # If "Bad split" error, try next split if "bad split" in err_str or "available splits" in err_str: logger.info(f" Split {try_split} not available for {try_ds_name}, trying next") continue # If "scripts no longer supported", try next dataset (fallback) if "scripts are no longer supported" in err_str and fallback_name: logger.info(f" {try_ds_name} uses script — trying fallback {fallback_name}") break # For other errors, log and try next split logger.warning(f"Failed to load {try_ds_name} split={try_split}: {str(e)[:120]}") continue
logger.warning(f"All split attempts failed for {dataset_name} (will be skipped)") return None
def stream_dataset( dataset_name: str, max_samples: int = 500, hf_token: Optional[str] = None,) -> Iterator[ProcessedSample]: """Faz streaming de um dataset, retornando até max_samples amostras.
Args: dataset_name: nome do dataset no HuggingFace max_samples: número máximo de amostras a retornar hf_token: token HF opcional
Yields: ProcessedSample """ fmt = DATASET_FORMATS.get(dataset_name) if fmt is None: logger.error(f"Unknown dataset: {dataset_name}") return
# ── V13.9.2-carolina: bypass do script Python ───────────────────────── # O dataset carolina-c4ai/corpus-carolina usa um script Python como loader, # que não é suportado por datasets 5.0+. Streamamos os XML.gz diretamente. if dataset_name == "carolina-c4ai/corpus-carolina": logger.info(f"Carolina: usando carregador direto (bypass do script Python)") count = 0 try: for raw_sample in _stream_carolina_direct( max_samples=max_samples, hf_token=hf_token ): processed = _normalize_sample(raw_sample, dataset_name, count) if processed is not None: yield processed count += 1 except Exception as e: logger.warning(f"Carolina direct stream error at sample {count}: {e}") return logger.info(f"Streamed {count} samples from {dataset_name} (direct XML)") return
# ── V13.9.2-finetune-v2: loaders alternativos para parquets grandes ─── # Alguns datasets (cnmoro, strak2005/bratao) têm parquets tão grandes que # datasets.load_dataset(streaming=True) demora minutos para materializar # a primeira amostra. Usamos loaders alternativos especificados no campo # "loader" do formato. loader = fmt.get("loader") if loader == "rows_api": logger.info(f"{dataset_name}: usando rows_api loader (datasets-server HTTP)") count = 0 try: for raw_sample in _stream_via_rows_api( dataset_name, max_samples=max_samples, hf_token=hf_token, config=fmt.get("config"), split=fmt.get("split", "train"), ): processed = _normalize_sample(raw_sample, dataset_name, count) if processed is not None: yield processed count += 1 except Exception as e: logger.warning(f"rows_api stream error at sample {count}: {e}") return logger.info(f"Streamed {count} samples from {dataset_name} (rows_api)") return
if loader == "parquet_first_shard": logger.info(f"{dataset_name}: usando parquet_first_shard loader") count = 0 try: for raw_sample in _stream_via_parquet_first_shard( dataset_name, max_samples=max_samples, hf_token=hf_token ): processed = _normalize_sample(raw_sample, dataset_name, count) if processed is not None: yield processed count += 1 except Exception as e: logger.warning(f"parquet_shard stream error at sample {count}: {e}") # Tenta fallback (ex: strak2005 -> bratao) fallback_name = fmt.get("fallback") if fallback_name and fallback_name != dataset_name: logger.info(f"Tentando fallback: {fallback_name}") fallback_fmt = DATASET_FORMATS.get(fallback_name, {}) # Recursão respeitando o loader do fallback yield from stream_dataset( fallback_name, max_samples=max_samples, hf_token=hf_token ) return logger.info(f"Streamed {count} samples from {dataset_name} (parquet_first_shard)") return
ds = _load_dataset_streaming( dataset_name, split=fmt.get("split", "train"), config=fmt.get("config"), hf_token=hf_token, ) if ds is None: return
count = 0 try: for idx, sample in enumerate(ds): if count >= max_samples: break processed = _normalize_sample(sample, dataset_name, idx) if processed is not None: yield processed count += 1 except Exception as e: logger.warning(f"Error streaming {dataset_name} at sample {idx}: {e}") return
logger.info(f"Streamed {count} samples from {dataset_name}")
def stream_all_datasets( datasets: Optional[List[str]] = None, max_samples_per_dataset: int = 500, hf_token: Optional[str] = None,) -> Iterator[ProcessedSample]: """Faz streaming sequencial de múltiplos datasets.
Args: datasets: lista de nomes (default: DEFAULT_DATASETS) max_samples_per_dataset: limite por dataset hf_token: token HF opcional
Yields: ProcessedSample """ if datasets is None: datasets = DEFAULT_DATASETS
for ds_name in datasets: logger.info(f"Starting dataset: {ds_name}") yield from stream_dataset( ds_name, max_samples=max_samples_per_dataset, hf_token=hf_token, )
def collate_samples_to_tensors( samples: List[ProcessedSample], tokenizer, max_seq_len: int = 64, pad_token_id: int = 0,) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Converte lista de ProcessedSample em tensors para treino.
BUG FIX V13.9.1: Tokenizer.encode() retorna 'Encoding' object, não list. Use .ids attribute to get token IDs.
Returns: input_ids: (B, T) attention_mask: (B, T) labels: (B, T) — same as input_ids (LM training) """ batch_input_ids = [] batch_attn_mask = []
for sample in samples: # Tokenize encoding = tokenizer.encode(sample.raw_text, add_special_tokens=True)
# BUG FIX: Handle both `tokenizers.Encoding` and `transformers` tokenizer outputs if hasattr(encoding, 'ids'): tokens = encoding.ids # tokenizers library elif isinstance(encoding, list): tokens = encoding # already a list of ints elif hasattr(encoding, 'input_ids'): tokens = encoding.input_ids # transformers BatchEncoding else: tokens = list(encoding) # fallback
# Truncate to max_seq_len if len(tokens) > max_seq_len: tokens = tokens[:max_seq_len] # Pad attn_mask = [1] * len(tokens) + [0] * (max_seq_len - len(tokens)) tokens = list(tokens) + [pad_token_id] * (max_seq_len - len(tokens)) batch_input_ids.append(tokens) batch_attn_mask.append(attn_mask)
input_ids = torch.tensor(batch_input_ids, dtype=torch.long) attention_mask = torch.tensor(batch_attn_mask, dtype=torch.long) labels = input_ids.clone()
return input_ids, attention_mask, labels
# ═══════════════════════════════════════════════════════════════════════════# Self-test (NÃO enviar para HuggingFace)# ═══════════════════════════════════════════════════════════════════════════if __name__ == "__main__": print("=== Streaming Datasets V13.9.1 Self-Test ===\n")
# Test 1: Test field extraction print("Test 1: Field extraction") sample_chat = { "messages": [ {"role": "user", "content": "Olá"}, {"role": "assistant", "content": "Como posso ajudar?"}, ] } text = _extract_field(sample_chat, ["messages", "text"]) print(f" Chat text: {text!r}") assert text and "Olá" in text, "Field extraction failed for chat"
sample_text = {"text": "Hello world"} text = _extract_field(sample_text, ["text", "content"]) assert text == "Hello world" print(f" Text field: {text!r}") print(f" OK\n")
# Test 2: Test list of datasets print("Test 2: Dataset list") print(f" Configured datasets ({len(DEFAULT_DATASETS)}):") for i, ds in enumerate(DEFAULT_DATASETS, 1): print(f" {i}. {ds}") assert len(DEFAULT_DATASETS) == 14 # V6.5-V2: verifica sequência CONHECIMENTO (8 datasets) + PUNICAO (1) assert len(CONHECIMENTO_DATASETS_V2) == 8 assert PUNICAO_DATASET_V2 == "BrunoN-Dev/corpus-ptbr-v1" print(f" V2 CONHECIMENTO datasets: {len(CONHECIMENTO_DATASETS_V2)}") print(f" V2 PUNICAO dataset: {PUNICAO_DATASET_V2}") print(f" OK\n")
print("=== ALL STREAMING TESTS PASSED ===")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200"""Xavante - vqvae2_hierarchical.pyResponsabilidade: VQ-VAE-2 hierarquica (Teorema 13.1/13.2/13.3).Reutiliza implementacao validada do FlexNet com EMA + Goose VQ + dead code restart.Referencia: Razavi et al. 2019 - Generating Diverse High-Fidelity Images with VQ-VAE-2."""from __future__ import annotations
import loggingimport mathfrom typing import List, Tuple
import torchimport torch.nn as nnimport torch.nn.functional as F
logger = logging.getLogger(__name__)
class VectorQuantizerEMA(nn.Module): """ VQ com atualizacao EMA do codebook (validado no FlexNet). Inclui: dead code restart, commitment loss, Goose VQ. v6 aprimoramentos: - Diversity loss (entropy bonus) para forcar uso uniforme do codebook - Commitment warmup: beta_t = beta_0 * min(1, t/warmup) - EMA restart mais agressivo (decay adaptativo) """
def __init__( self, num_embeddings: int, embedding_dim: int, commitment_cost: float = 0.25, decay: float = 0.99, epsilon: float = 1e-5, dead_threshold: int = 1, diversity_weight: float = 0.1, warmup_steps: int = 500, ): super().__init__() self.num_embeddings = num_embeddings self.embedding_dim = embedding_dim self.commitment_cost = commitment_cost self.decay = decay self.epsilon = epsilon self.dead_threshold = dead_threshold self.diversity_weight = diversity_weight self.warmup_steps = warmup_steps self._step = 0
embed = torch.empty(num_embeddings, embedding_dim) nn.init.normal_(embed, mean=0.0, std=0.02) self.register_buffer("embeddings", embed) self.register_buffer("ema_count", torch.zeros(num_embeddings)) self.register_buffer("ema_weight", embed.clone()) self.register_buffer("usage_count", torch.zeros(num_embeddings, dtype=torch.long))
def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ x: [B, D, H, W] ou [B, D] Retorna (quantized, loss, encoding_indices) """ if x.dim() == 4: # [B, D, H, W] -> [B, H, W, D] -> [B*H*W, D] B, D, H, W = x.shape flat = x.permute(0, 2, 3, 1).reshape(-1, self.embedding_dim) else: # [B, D] -> [B, D] flat = x.reshape(-1, self.embedding_dim) # Distancia distances = ( flat.pow(2).sum(1, keepdim=True) - 2 * flat @ self.embeddings.t() + self.embeddings.pow(2).sum(1) ) indices = torch.argmin(distances, dim=1) one_hot = F.one_hot(indices, self.num_embeddings).type(flat.dtype) quantized = one_hot @ self.embeddings # Uso self.usage_count.index_add_(0, indices, torch.ones_like(indices))
# EMA update if self.training: with torch.no_grad(): count = one_hot.sum(0) ema_count_new = self.decay * self.ema_count + (1 - self.decay) * count total = ema_count_new.sum() ema_count_new = (ema_count_new + self.epsilon) / (total + self.num_embeddings * self.epsilon) * total dw = one_hot.t() @ flat self.ema_weight = self.decay * self.ema_weight + (1 - self.decay) * dw self.ema_count = ema_count_new self.embeddings.copy_(self.ema_weight / self.ema_count.unsqueeze(1))
# Dead code restart dead = self.usage_count < self.dead_threshold if dead.any() and flat.shape[0] > 0: dead_indices = dead.nonzero(as_tuple=True)[0] n_dead = dead_indices.shape[0] # Sample min(n_dead, flat.shape[0]) candidates from flat n_replace = min(n_dead, flat.shape[0]) if n_replace > 0: idx = torch.randperm(flat.shape[0])[:n_replace].to(flat.device) # Substituir apenas n_replace codigos mortos self.embeddings.data[dead_indices[:n_replace]] = flat[idx].detach()
# Commitment loss com warmup self._step += 1 beta = self.commitment_cost * min(1.0, self._step / max(self.warmup_steps, 1)) e_latent_loss = F.mse_loss(quantized.detach(), flat) q_latent_loss = F.mse_loss(quantized, flat.detach()) # Diversity loss: -H(p) onde p = freq de uso de cada code # Maximizar entropia = forçar uso uniforme do codebook if self.diversity_weight > 0 and self.training: code_probs = one_hot.float().mean(dim=0) # [num_embeddings] code_probs = code_probs.clamp_min(1e-10) entropy = -(code_probs * code_probs.log()).sum() diversity_loss = -entropy / math.log(self.num_embeddings) # normalize to [0, 1] else: diversity_loss = torch.tensor(0.0, device=x.device) loss = q_latent_loss + beta * e_latent_loss + self.diversity_weight * diversity_loss
# Straight-through quantized = flat + (quantized - flat).detach() # Restore shape if x.dim() == 4: quantized = quantized.view(B, H, W, D).permute(0, 3, 1, 2).contiguous() indices = indices.view(B, H, W) else: quantized = quantized.view_as(x) return quantized, loss, indices
class HierarchicalVQVAE2(nn.Module): """ VQ-VAE-2 com 2 niveis: top (global) e bottom (local). Mapeia: Teorema 13.1/13.2/13.3. """
def __init__( self, in_channels: int = 3, hidden_dim: int = 64, top_codebook: int = 128, bottom_codebook: int = 512, commitment_cost: float = 0.25, decay: float = 0.99, ): super().__init__() self.encoder_bottom = nn.Sequential( nn.Conv2d(in_channels, hidden_dim, 4, 2, 1), nn.GELU(), nn.Conv2d(hidden_dim, hidden_dim, 4, 2, 1), nn.GELU(), nn.Conv2d(hidden_dim, hidden_dim, 3, 1, 1), ) self.encoder_top = nn.Sequential( nn.Conv2d(hidden_dim, hidden_dim, 4, 2, 1), nn.GELU(), nn.Conv2d(hidden_dim, hidden_dim, 4, 2, 1), nn.GELU(), nn.Conv2d(hidden_dim, hidden_dim, 3, 1, 1), ) self.vq_top = VectorQuantizerEMA(top_codebook, hidden_dim, commitment_cost, decay) self.vq_bottom = VectorQuantizerEMA(bottom_codebook, hidden_dim, commitment_cost, decay) self.decoder_top = nn.Sequential( nn.ConvTranspose2d(hidden_dim, hidden_dim, 4, 2, 1), nn.GELU(), nn.ConvTranspose2d(hidden_dim, hidden_dim, 4, 2, 1), nn.GELU(), ) self.decoder_bottom = nn.Sequential( nn.ConvTranspose2d(hidden_dim * 2, hidden_dim, 4, 2, 1), nn.GELU(), nn.ConvTranspose2d(hidden_dim, hidden_dim, 4, 2, 1), nn.GELU(), nn.Conv2d(hidden_dim, in_channels, 3, 1, 1), )
def forward(self, x: torch.Tensor) -> dict: # Bottom encode ze_b = self.encoder_bottom(x) # Top encode ze_t = self.encoder_top(ze_b) zq_t, loss_t, idx_t = self.vq_top(ze_t) # Decodifica top e soma com bottom dec_t = self.decoder_top(zq_t) # Concat com bottom quantized zq_b, loss_b, idx_b = self.vq_bottom(ze_b) cat = torch.cat([dec_t, zq_b], dim=1) x_recon = self.decoder_bottom(cat) return { "reconstruction": x_recon, "loss": loss_t + loss_b, "top_indices": idx_t, "bottom_indices": idx_b, }
__all__ = ["VectorQuantizerEMA", "HierarchicalVQVAE2"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513"""vqvae2_hierarchical — VQ-VAE-2 (Razavi 2019) hierárquico com 2 níveis de codebook.
Arquitetura:- Top level: codebook K_top captura estrutura global (low-resolution)- Bottom level: codebook K_bot captura detalhes locais (high-resolution)- Cada nível tem encoder/decoder proprio- Residual quantization: bottom level quantiza o RESÍDUO do top level
Loss total: L = ||x - D(top_q, bot_q)||² + ||sg[z_top] - top_q||² + β·||z_top - sg[top_q]||² + ||sg[z_bot] - bot_q||² + β·||z_bot - sg[bot_q]||²
Implementa:- EMA updates em ambos codebooks- Dead code restart em ambos codebooks- Goose VQ com schedule de temperatura (alto→baixo)
Setup dos testes (solicitado):- batch=256, K_top=512, K_bot=512- Goose τ schedule: começa 2.0, decai para 0.5 via cosine- EMA decay γ=0.99- Dead code restart a cada 3 épocas"""
from __future__ import annotationsfrom typing import Dict, Optional, Tuple
import mathimport numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as F
# ============================================================# v12.8: Normalizações alternativas (substituem LayerNorm v12.7)# ============================================================
class RMSNorm(nn.Module): """RMSNorm — preserva magnitude (não subtrai média como LayerNorm).
y = x / sqrt(mean(x²) + eps) * gamma
Vantagens sobre LayerNorm: - Mais barato (sem cálculo de variância) - Preserva magnitude do sinal (importante para VQ-VAE) - Zhang & Sennrich 2019 """
def __init__(self, dim: int, eps: float = 1e-6): super().__init__() self.gamma = nn.Parameter(torch.ones(dim)) self.eps = eps
def forward(self, x: torch.Tensor) -> torch.Tensor: rms = torch.sqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps) return self.gamma * x / rms
def apply_weightnorm(module: nn.Module) -> nn.Module: """Aplica weight normalization (EnCodec-style) a um módulo Linear.
Salakhutdinov & Wang 2016: w = g * v / ||v||, onde g é escalar aprendido.
Vantagens: - Normaliza apenas o peso, não a ativação - Preserva estatística do input (importante para VQ-VAE) - Usado em EnCodec (Défossez 2022) e SoundStream (Zeghidour 2021) """ return nn.utils.weight_norm(module)
class HierarchicalVectorQuantizer(nn.Module): """Quantizador hierárquico com 2 níveis (top + bottom) e técnicas anti-collapse.
Args: num_codes_top: K_top (codebook de topo, captura estrutura global) num_codes_bot: K_bot (codebook de base, captura detalhes) code_dim: D (dimensão compartilhada) beta: peso do commitment loss ema_decay: γ para EMA (default 0.99) dead_code_threshold: N_k abaixo do qual código é morto dead_code_restart_every: a cada quantas épocas verificar goose_temp_init: temperatura Goose inicial (default 2.0) goose_temp_final: temperatura Goose final (default 0.5) goose_schedule: 'cosine' ou 'linear' total_epochs: total de épocas (para schedule) """
def __init__( self, num_codes_top: int = 512, num_codes_bot: int = 512, code_dim: int = 32, beta: float = 0.25, ema_decay: float = 0.99, dead_code_threshold: float = 1.0, dead_code_restart_every: int = 3, goose_temp_init: float = 2.0, goose_temp_final: float = 0.5, goose_schedule: str = "cosine", total_epochs: int = 25, norm_type: str = "none", # v12.8: "none" | "weightnorm" | "rmsnorm" ): super().__init__() self.num_codes_top = num_codes_top self.num_codes_bot = num_codes_bot self.code_dim = code_dim self.beta = beta self.ema_decay = ema_decay self.dead_code_threshold = dead_code_threshold self.dead_code_restart_every = dead_code_restart_every self.goose_temp_init = goose_temp_init self.goose_temp_final = goose_temp_final self.goose_schedule = goose_schedule self.total_epochs = total_epochs self.norm_type = norm_type # v12.8
# Codebooks (buffers, atualizados via EMA). self.register_buffer('codebook_top', torch.randn(num_codes_top, code_dim) * 0.05) self.register_buffer('codebook_bot', torch.randn(num_codes_bot, code_dim) * 0.05) # EMA state para top. self.register_buffer('ema_cluster_top', torch.zeros(num_codes_top)) self.register_buffer('ema_w_top', torch.zeros(num_codes_top, code_dim)) # EMA state para bottom. self.register_buffer('ema_cluster_bot', torch.zeros(num_codes_bot)) self.register_buffer('ema_w_bot', torch.zeros(num_codes_bot, code_dim))
# v12.8: Normalização opcional dentro do VQ (substitui LayerNorm v12.7 que degradou). # - "none": sem normalização (preserva estatística original — RECOMENDADO para VQ-VAE) # - "weightnorm": weight normalization (EnCodec-style, preserva magnitude) # - "rmsnorm": RMSNorm (preserva magnitude, mais barato que LayerNorm) # Nota: LayerNorm v12.7 foi REMOVIDO pois degradou resultados (17× pior loss). if norm_type == "rmsnorm": # RMSNorm: y = x / sqrt(mean(x²) + eps) * gamma self.rms_pre_top = RMSNorm(code_dim) self.rms_pre_bot = RMSNorm(code_dim) self.rms_post_combine = RMSNorm(code_dim) else: # "none" ou "weightnorm" (weightnorm é aplicado nos encoders, não aqui). self.rms_pre_top = nn.Identity() self.rms_pre_bot = nn.Identity() self.rms_post_combine = nn.Identity()
# Contador de épocas. self.register_buffer('epoch_counter', torch.zeros(1, dtype=torch.long))
# Estatísticas de uso. self.register_buffer('usage_top', torch.zeros(num_codes_top)) self.register_buffer('usage_bot', torch.zeros(num_codes_bot))
# Temperatura Goose atual (atualizada via update_temperature). self.register_buffer('current_temp', torch.tensor(goose_temp_init))
def update_temperature(self, grad_recon: float = None, grad_vq: float = None): """Atualiza temperatura Goose baseada na época atual (schedule). v13.9: Se grad_recon e grad_vq fornecidos, usa mas_weight adaptativo: τ* = ||∇L_recon|| / ||∇L_vq|| Caso contrário, usa cosine decay padrão. """ epoch = int(self.epoch_counter.item()) progress = min(epoch / max(self.total_epochs, 1), 1.0) if grad_recon is not None and grad_vq is not None and grad_vq > 1e-8: # v13.9: τ* adaptativo via mas_weight formula. from .mathematical_optimizations import compute_goose_tau_adaptive prev_tau = float(self.current_temp) temp = compute_goose_tau_adaptive(grad_recon, grad_vq, prev_tau, tau_min=self.goose_temp_final, tau_max=self.goose_temp_init) elif self.goose_schedule == "cosine": temp = self.goose_temp_final + 0.5 * (self.goose_temp_init - self.goose_temp_final) * \ (1 + math.cos(math.pi * progress)) else: # linear temp = self.goose_temp_init + (self.goose_temp_final - self.goose_temp_init) * progress self.current_temp.fill_(temp) return float(temp)
def _quantize_level(self, z: torch.Tensor, codebook: torch.Tensor, ema_cluster: torch.Tensor, ema_w: torch.Tensor, use_goose: bool = True) -> Tuple[torch.Tensor, torch.Tensor, int]: """Quantiza um nível (top ou bottom) com EMA + Goose opcional.""" B, D = z.shape # Distâncias. dist = ( z.pow(2).sum(dim=1, keepdim=True) + codebook.pow(2).sum(dim=1) - 2 * z @ codebook.t() ) # (B, K)
if use_goose and self.training: # Goose VQ: Gumbel-softmax sampling. logits = -dist / max(float(self.current_temp), 1e-6) codes_soft = F.gumbel_softmax(logits, tau=float(self.current_temp), hard=True) codes = codes_soft.argmax(dim=1) z_q = codes_soft @ codebook else: # argmin (eval ou fallback). codes = dist.argmin(dim=1) z_q = codebook[codes]
# EMA update (apenas em treino). n_restarted = 0 if self.training: one_hot = F.one_hot(codes, codebook.size(0)).float() new_cluster = one_hot.sum(dim=0) # v13.3fix: Save OLD values before EMA update for cb_update computation old_cluster = ema_cluster.clone() old_w = ema_w.clone() ema_cluster.mul_(self.ema_decay).add_(new_cluster, alpha=1 - self.ema_decay) new_w = one_hot.t() @ z ema_w.mul_(self.ema_decay).add_(new_w, alpha=1 - self.ema_decay) # v13.3: Correções matemáticas no EMA (mal-conditioning do codebook). # Use OLD (pre-update) values for cb_update, as required by proper EMA formula. n_old = old_cluster.sum() # 1. Smoothing do cluster size (reduz condition number). cluster_mean = old_cluster.mean() cluster_smoothed = 0.9 * old_cluster + 0.1 * cluster_mean # 2. Clipping logarítmico do cluster size (comprime escala dinâmica). eps_cb = 1e-5 cluster_clipped = torch.log1p(cluster_smoothed / eps_cb) / \ torch.log1p(cluster_smoothed.max() / eps_cb + 1e-12) # 3. Renormalizar para magnitude original. cluster_final = cluster_clipped * n_old / (cluster_clipped.sum() + 1e-12) smoothed = (cluster_final + eps_cb) / (n_old + codebook.size(0) * eps_cb) * n_old # v13.3: Clamp do codebook update para prevenir NaN/Inf. # Use OLD ema_w (pre-update) for cb_update cb_update = old_w / smoothed.unsqueeze(1) cb_update = torch.clamp(cb_update, -1e4, 1e4) codebook.copy_(cb_update)
# Dead code restart. if (int(self.epoch_counter.item()) + 1) % self.dead_code_restart_every == 0: dead_mask = ema_cluster < self.dead_code_threshold n_dead = int(dead_mask.sum().item()) if n_dead > 0: rand_idx = torch.randint(0, B, (n_dead,), device=z.device) replacement = z[rand_idx] codebook.data[dead_mask] = replacement.detach() ema_cluster[dead_mask] = 1.0 ema_w[dead_mask] = replacement.detach() n_restarted = n_dead # v13.1: limpeza leve após dead code restart (libera tensores temporários). import gc as _gc _gc.collect(0)
return z_q, codes, n_restarted
def forward(self, z_e: torch.Tensor) -> Dict[str, torch.Tensor]: """ z_e: (B, D) — saída contínua do encoder.
Retorna dict com: z_q_top: (B, D) — vetores quantizados do nível top z_q_bot: (B, D) — vetores quantizados do nível bottom (residual) z_q_combined: (B, D) — z_q_top + z_q_bot (soma) codes_top: (B,) codes_bot: (B,) loss: escalar (commitment top + bottom) stats: dict com estatísticas """ # v12.8: RMSNorm pré-top (preserva magnitude, mais estável que LayerNorm). z_e_norm = self.rms_pre_top(z_e)
# Nível top: quantiza z_e (normalizado) diretamente. z_q_top, codes_top, n_restart_top = self._quantize_level( z_e_norm, self.codebook_top, self.ema_cluster_top, self.ema_w_top, use_goose=True, )
# Nível bottom: quantiza o RESÍDUO z_e - z_q_top.detach() (com RMSNorm). residual = z_e - z_q_top.detach() residual_norm = self.rms_pre_bot(residual) z_q_bot, codes_bot, n_restart_bot = self._quantize_level( residual_norm, self.codebook_bot, self.ema_cluster_bot, self.ema_w_bot, use_goose=True, )
# Commitment losses (computadas com z_e original, não normalizado). commit_top = F.mse_loss(z_e, z_q_top.detach()) commit_bot = F.mse_loss(residual, z_q_bot.detach()) loss = self.beta * (commit_top + commit_bot)
# Straight-through. z_q_top_st = z_e + (z_q_top - z_e).detach() z_q_bot_st = residual + (z_q_bot - residual).detach() z_q_combined = z_q_top_st + z_q_bot_st # v12.8: RMSNorm pós-combinação (preserva magnitude, mais estável que LayerNorm). z_q_combined = self.rms_post_combine(z_q_combined)
# Estatísticas. with torch.no_grad(): self.usage_top.add_(torch.bincount(codes_top, minlength=self.num_codes_top).float()) self.usage_bot.add_(torch.bincount(codes_bot, minlength=self.num_codes_bot).float()) n_used_top = int((self.usage_top > 0).sum().item()) n_used_bot = int((self.usage_bot > 0).sum().item())
def _cb_ppl(codes, K): if len(codes) == 0: return 0.0 from collections import Counter counter = Counter(codes.tolist()) probs = np.array([c / len(codes) for c in counter.values()]) entropy = -np.sum(probs * np.log(probs + 1e-12)) return float(math.exp(entropy)) if entropy > 0 else 0.0
cb_ppl_top = _cb_ppl(codes_top, self.num_codes_top) cb_ppl_bot = _cb_ppl(codes_bot, self.num_codes_bot)
stats = { 'n_used_top': n_used_top, 'n_used_bot': n_used_bot, 'n_dead_top': self.num_codes_top - n_used_top, 'n_dead_bot': self.num_codes_bot - n_used_bot, 'usage_ratio_top': n_used_top / self.num_codes_top, 'usage_ratio_bot': n_used_bot / self.num_codes_bot, 'codebook_ppl_top': cb_ppl_top, 'codebook_ppl_bot': cb_ppl_bot, 'n_restarted_top': n_restart_top, 'n_restarted_bot': n_restart_bot, 'goose_temp': float(self.current_temp), }
return { 'z_q_top': z_q_top_st, 'z_q_bot': z_q_bot_st, 'z_q_combined': z_q_combined, 'codes_top': codes_top, 'codes_bot': codes_bot, 'loss': loss, 'stats': stats, }
def increment_epoch(self): self.epoch_counter += 1 self.update_temperature()
def reset_usage_stats(self): self.usage_top.zero_() self.usage_bot.zero_()
class HierarchicalVQVAE2(nn.Module): """VQ-VAE-2 completo com encoder/decoder hierárquico para múltiplas modalidades.
Arquitetura: x → [Encoder shared] → z_e → [Top VQ] → z_q_top (estrutura global) → [Bot VQ] → z_q_bot (detalhes residuais) → [Decoder shared] → x_recon """
def __init__( self, modalities: Dict[str, int], code_dim: int = 32, num_codes_top: int = 512, num_codes_bot: int = 512, hidden: int = 128, beta: float = 0.25, ema_decay: float = 0.99, dead_code_threshold: float = 1.0, dead_code_restart_every: int = 3, goose_temp_init: float = 2.0, goose_temp_final: float = 0.5, goose_schedule: str = "cosine", total_epochs: int = 25, norm_type: str = "none", # v12.8: "none" | "weightnorm" | "rmsnorm" rmsnorm_in_vq: bool = False, # v12.8: RMSNorm dentro do VQ (default False) ): super().__init__() self.modality_names = list(modalities.keys()) self.modality_dims = modalities self.code_dim = code_dim self.norm_type = norm_type # v12.8
# v12.8: Encoders e decoders por modalidade. # - "none": LayerNorm interno dos MLPs (default, melhor validado em v12.7) # - "weightnorm": aplica weight_norm nos Linear (EnCodec-style) # - "rmsnorm": usa RMSNorm em vez de LayerNorm entre camadas MLP def make_encoder(dim, hidden, code_dim, norm_type): if norm_type == "weightnorm": layers = [ nn.utils.weight_norm(nn.Linear(dim, hidden)), nn.GELU(), nn.utils.weight_norm(nn.Linear(hidden, hidden // 2)), nn.GELU(), nn.utils.weight_norm(nn.Linear(hidden // 2, code_dim)), ] elif norm_type == "rmsnorm": layers = [ nn.Linear(dim, hidden), RMSNorm(hidden), nn.GELU(), nn.Linear(hidden, hidden // 2), RMSNorm(hidden // 2), nn.GELU(), nn.Linear(hidden // 2, code_dim), ] else: # "none" — usa LayerNorm interno (default, melhor validado) layers = [ nn.Linear(dim, hidden), nn.LayerNorm(hidden), nn.GELU(), nn.Linear(hidden, hidden // 2), nn.LayerNorm(hidden // 2), nn.GELU(), nn.Linear(hidden // 2, code_dim), ] return nn.Sequential(*layers)
def make_decoder(code_dim, hidden, dim, norm_type): if norm_type == "weightnorm": layers = [ nn.utils.weight_norm(nn.Linear(code_dim, hidden // 2)), nn.GELU(), nn.utils.weight_norm(nn.Linear(hidden // 2, hidden)), nn.GELU(), nn.utils.weight_norm(nn.Linear(hidden, dim)), ] elif norm_type == "rmsnorm": layers = [ nn.Linear(code_dim, hidden // 2), RMSNorm(hidden // 2), nn.GELU(), nn.Linear(hidden // 2, hidden), RMSNorm(hidden), nn.GELU(), nn.Linear(hidden, dim), ] else: # "none" layers = [ nn.Linear(code_dim, hidden // 2), nn.LayerNorm(hidden // 2), nn.GELU(), nn.Linear(hidden // 2, hidden), nn.LayerNorm(hidden), nn.GELU(), nn.Linear(hidden, dim), ] return nn.Sequential(*layers)
self.encoders = nn.ModuleDict({ name: make_encoder(dim, hidden, code_dim, norm_type) for name, dim in modalities.items() }) self.decoders = nn.ModuleDict({ name: make_decoder(code_dim, hidden, dim, norm_type) for name, dim in modalities.items() })
# VQ hierárquico compartilhado entre todas as modalidades. # v12.8: RMSNorm opcional dentro do VQ (substitui LayerNorm v12.7 que degradou). vq_norm_type = "rmsnorm" if (rmsnorm_in_vq and norm_type == "rmsnorm") else "none" self.vq = HierarchicalVectorQuantizer( num_codes_top=num_codes_top, num_codes_bot=num_codes_bot, code_dim=code_dim, beta=beta, ema_decay=ema_decay, dead_code_threshold=dead_code_threshold, dead_code_restart_every=dead_code_restart_every, goose_temp_init=goose_temp_init, goose_temp_final=goose_temp_final, goose_schedule=goose_schedule, total_epochs=total_epochs, norm_type=vq_norm_type, )
def forward(self, batch: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]: """batch: {modality_name: (B, input_dim)}.""" out = {'reconstructions': {}, 'codes_top': {}, 'codes_bot': {}, 'vq_loss': 0.0, 'recon_loss': 0.0, 'stats': {}} total_vq = 0.0 total_recon = 0.0 n = 0 all_codes_top = [] all_codes_bot = [] vq_out_first_stats = None # Capture stats from first VQ forward for name, x in batch.items(): if name not in self.encoders: continue # v13.3: Sanitização de NaN/Inf no input (resolve bug identificado no teste adversarial). x = torch.nan_to_num(x, nan=0.0, posinf=1e4, neginf=-1e4) # v12.8: forward limpo (sem LayerNorms extras v12.7 que degradaram resultados). # Encoder (com normalização interna configurável via norm_type). z_e = self.encoders[name](x) # v13.3: Sanitização após encoder (pode gerar NaN com inputs extremos). z_e = torch.nan_to_num(z_e, nan=0.0, posinf=1e4, neginf=-1e4) # VQ hierárquico (com RMSNorm opcional via rmsnorm_in_vq). vq_out = self.vq(z_e) # Capture stats from the first modality's VQ forward (no redundant second pass) if vq_out_first_stats is None: vq_out_first_stats = vq_out['stats'] z_q = vq_out['z_q_combined'] # v13.3: Sanitização após VQ (quantização pode produzir valores extremos). z_q = torch.nan_to_num(z_q, nan=0.0, posinf=1e4, neginf=-1e4) # Decoder (com normalização interna configurável via norm_type). x_recon = self.decoders[name](z_q) # v13.3: Sanitização final da reconstrução. x_recon = torch.nan_to_num(x_recon, nan=0.0, posinf=1e4, neginf=-1e4) recon_loss = F.mse_loss(x_recon, x)
out['reconstructions'][name] = x_recon out['codes_top'][name] = vq_out['codes_top'] out['codes_bot'][name] = vq_out['codes_bot'] all_codes_top.append(vq_out['codes_top']) all_codes_bot.append(vq_out['codes_bot']) total_vq += vq_out['loss'] total_recon += recon_loss n += 1
out['vq_loss'] = total_vq / max(n, 1) out['recon_loss'] = total_recon / max(n, 1) out['total_loss'] = out['vq_loss'] + out['recon_loss'] # Use stats already computed in the main loop — avoid redundant VQ forward # that would sample different random codes and give inconsistent stats. if vq_out_first_stats is not None: out['stats'] = vq_out_first_stats return out
def cross_modal_translate( self, x: torch.Tensor, src: str, tgt: str ) -> torch.Tensor: """Traduz de uma modalidade para outra via codebook compartilhado.""" # v12.8: forward limpo (sem LayerNorms extras v12.7). z_e = self.encoders[src](x) vq_out = self.vq(z_e) z_q = vq_out['z_q_combined'] return self.decoders[tgt](z_q)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",]attention_multimodal.pyDeleted-114
hyp_t.pyDeleted-100
kohonen_learning_system.pyDeleted
train_v6_5_v2.py → scripts/train_v6_5_v2.pyRenamed
src/bigru_t/data/streaming_datasets.py+51-1
src/bigru_t/model/kohonen_learning_system.py+1538-78
som_metrics.py → src/bigru_t/model/som_metrics.pyRenamed
streaming_datasets.pyDeleted-995
vqvae2_hierarchical.pyDeleted-200
vqvae2_hierarchical_flexnet.pyDeleted-513
xeon_runtime.pyDeleted-581