Portuguese
mamba
mamba-3
ssm
muon
muonclip
qk-clip
adamw
optimizer
nope
hybrid-architecture
activation-checkpointing
3d-vision-language
depth-perception
point-cloud
diffusion
stable-diffusion
mixture-of-experts
kohonen
som-attention
random-forest
deep-neural-network
knowledge-distillation
bidirectional-distillation
engram-memory
multimodal
multi-token-prediction
dpo
rlhf
hh-rlhf
pcgrad
long-context
lra-qvit
engineer-agent
integral-state
cython
jev-classifiers
gumbel-softmax
quantization
riemannian-optimization
stiefel-manifold
cython-kernels
gradient-accumulation
vector-quantization
grayscale-detection
joint-perception
self-regulation
signal-table
abmo
ciar
growing-som
pt-br
File size: 17,542 Bytes
546119a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 | # -*- coding: utf-8 -*-
"""24_teste_v19.py — TESTE REAL v19 (KHMAMBAJEPA, doc 31 §7).
Requisitos do usuário atendidos aqui:
• "acoplar as variantes JEPA aos encoders de produção com A/B pareado" —
dois braços com MESMA semente e MESMOS lotes (pareamento exato: a perda
JEPA usa gerador dedicado + modo eval — não consome o RNG do treino);
• "ativar SonicMoE no tronco (opt-in)" — braço B com sonicmoe.ativo=true;
micro-benchmark foco sônico×vetorial (wall-clock + equivalência + IO);
• "rodar testes de datasets reais" — corpus REAL (LeRobot frames, GSM8K/
matemática, wikitext) + coleta FRESCA opcional com orçamento.
Braços (UMA variante por processo — cada modelo completo):
A) baseline_v18 — jepa_acoplado λ=0, sonicmoe off (v18 EXATO)
B) v19_completo — jepa_acoplado λ=0.3 (imagem+audio) + sonicmoe ON
C) v19_lambda_baixo — idêntico a B com λ=0.1 (prescrição Teo 28.7-ii:
razão auxiliar/CE ≤ 0.3 — o λ alto desvia capacidade da CE)
Uso:
python3 scripts/24_teste_v19.py --coletar # 1× (dados frescos)
python3 scripts/24_teste_v19.py --variante baseline_v18 --passos 140
python3 scripts/24_teste_v19.py --variante v19_completo --passos 140
python3 scripts/24_teste_v19.py --variante v19_lambda_baixo --passos 96
python3 scripts/24_teste_v19.py --relatorio # consolida o par
"""
from __future__ import annotations
import argparse
import base64
import importlib.util
import json
import os
import sys
import time
RAIZ = os.environ.get("KHTST_RAIZ", "/home/z/my-project/workspace/repo_src")
sys.path.insert(0, os.path.join(RAIZ, "src"))
CORPUS = os.path.join(RAIZ, "cache_dados", "corpus_v16.jsonl")
TOKENIZADOR = os.path.join(RAIZ, "cache_dados", "tokenizador_v16.json")
TOK_ANTIGO = os.path.join(RAIZ, "cache_dados", "tokenizador.json")
TELEMETRIA = os.path.join(RAIZ, "telemetria_out")
V19_SCRIPT = os.path.join(RAIZ, "scripts", "19_teste_v16.py")
def carregar_registros(caminho: str) -> list[dict]:
registros = []
if not os.path.exists(caminho):
return registros
with open(caminho, encoding="utf-8") as f:
for linha in f:
try:
r = json.loads(linha)
except Exception:
continue
if isinstance(r.get("imagem"), str):
try:
r["imagem"] = base64.b64decode(r["imagem"])
except Exception:
r["imagem"] = None
if isinstance(r.get("audio"), str):
try:
r["audio"] = base64.b64decode(r["audio"])
except Exception:
r["audio"] = None
registros.append(r)
return registros
def coletar_fresco() -> dict:
"""Coleta FRESCA com orçamento (datasets reais; reusa o coletor v16)."""
spec = importlib.util.spec_from_file_location("teste_v16", V19_SCRIPT)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod.coletar(max_por_fonte=8, orcamento_s=50.0)
def _estado_rng() -> dict:
import random
import numpy as np
import torch
return {"torch": torch.get_rng_state(),
"random": random.getstate(),
"numpy": np.random.get_state()}
def _restaurar_rng(est: dict) -> None:
import random
import numpy as np
import torch
torch.set_rng_state(est["torch"])
random.setstate(est["random"])
np.random.set_state(est["numpy"])
def rodar_variante(nome: str, v19: bool, passos: int, parte: int = 0,
lambda_jac: float = 0.3) -> dict:
import gc
import random
import numpy as np
import torch
# CPU sandbox: limitar intraop threads (sem isto o env ignora OMP_NUM_
# THREADS herdado e o passo fica 2× mais lento por thrashing)
if not (torch.cuda.is_available() or torch.xpu.is_available()):
torch.set_num_threads(int(os.environ.get("OMP_NUM_THREADS", "2")))
from khtst.config import Config
from khtst.dados.tokenizador import TokenizadorKHTST
from khtst.memoria.orquestrador import OrquestradorSOM
from khtst.nucleo.modelo import KHTSTModel
from khtst.telemetria.hub import TelemetryHub
from khtst.treino.treinador import TreinadorExtensao
SEED = 2026
cfg = Config()
cfg.dados.semente = SEED
cfg.treino.warmup = 8
cfg.treino.lote = 4
cfg.treino.lote_efetivo = 1 # protocolo v16 exato (RAM 4 GiB)
cfg.treino.qat_ultimos_passos = 0
cfg.treino.ensemble["a_cada"] = 24 # RF menos frequente (RAM)
cfg.modelo.escalacao["ativo"] = False
if v19:
# REQUISITO v19: JEPA ACOPLADA aos encoders de produção + SonicMoE
cfg.treino.jepa_acoplado["lambda"] = lambda_jac
cfg.treino.jepa_acoplado["variantes"] = ["imagem", "audio"]
cfg.treino.jepa_acoplado["pred_hidden"] = 256
cfg.modelo.sonicmoe["ativo"] = True
cfg.modelo.sonicmoe["tile_m"] = 32
else:
cfg.treino.jepa_acoplado["lambda"] = 0.0
cfg.modelo.sonicmoe["ativo"] = False
os.makedirs(TELEMETRIA, exist_ok=True)
hub = TelemetryHub(os.path.join(TELEMETRIA, f"treino_v19_{nome}.jsonl"))
tk = TokenizadorKHTST(TOKENIZADOR if os.path.exists(TOKENIZADOR)
else TOK_ANTIGO)
registros = carregar_registros(CORPUS)
modelo = KHTSTModel(cfg, usar_multimodal=True)
orquestrador = OrquestradorSOM(cfg.modelo.d_modelo, cfg.som, hub=hub,
cfg_atencao=None)
treinar = TreinadorExtensao(cfg, modelo, tk, hub, registros,
orquestrador_som=orquestrador)
# PAREAMENTO EXATO (Teo 31.7): re-seed APÓS construir modelo+treinador
# (a construção consome RNG de init — os dois braços partem do MESMO
# estado aqui; a perda JEPA não consome o RNG global: gerador dedicado
# + eval). Braço A não tem conselho — o fluxo de lotes é idêntico.
_restaurar_rng(est_padrao(SEED))
# ---- retomada por PARTES (RAM sandbox: o processo morre entre chamadas;
# v19 salva TUDO que afeta o pareamento: pesos, otimizador, conselho,
# contagem de passos, perdas e os 3 estados de RNG)
ckpt = os.path.join(TELEMETRIA, f"ckpt_v19_{nome}.pt")
perdas: list[float] = []
tel_jepa_ac: list[dict] = []
passo_inicial = 0
if parte and os.path.exists(ckpt):
est = torch.load(ckpt, map_location="cpu", weights_only=False)
modelo.load_state_dict(est["modelo"])
treinar.otimizador.load_state_dict(est["otimizador"])
if treinar.conselho_acoplado is not None and est.get("conselho"):
treinar.conselho_acoplado.load_state_dict(est["conselho"])
treinar.passo_global = est["passo_global"]
perdas = est["perdas"]
tel_jepa_ac = est.get("tel_jepa_ac", [])
torch.set_rng_state(est["rng_torch"])
random.setstate(est["rng_py"])
np.random.set_state(est["rng_np"])
passo_inicial = est["passo_global"]
print(f"[retomada] passo_global={est['passo_global']} perdas={len(perdas)}",
flush=True)
# drift dos encoders de produção (medida de treino REAL dos encoders)
im0 = torch.zeros(0)
au0 = torch.zeros(0)
if getattr(modelo, "enc_imagem", None) is not None:
im0 = modelo.enc_imagem.proj.weight.data.detach().clone()
if getattr(modelo, "enc_audio", None) is not None:
au0 = modelo.enc_audio.conv1.weight.data.detach().clone()
if parte and os.path.exists(ckpt):
est = torch.load(ckpt, map_location="cpu", weights_only=False)
im0 = est["im0"]
au0 = est["au0"]
t0 = time.time()
alvo = min(passos, passo_inicial + parte) if parte else passos
while treinar.passo_global < alvo:
tp = time.time()
perda = treinar._passo()
if perda == perda:
perdas.append(perda)
if parte:
print(f"[passo {treinar.passo_global} {time.time()-tp:.1f}s "
f"perda {perda:.3f}]", flush=True)
if treinar.conselho_acoplado is not None:
tel = getattr(treinar, "ultima_tel_jac", {})
if tel:
tel_jepa_ac.append(
{k: (float(v) if torch.is_tensor(v) else v)
for k, v in tel.items()
if k in ("loss", "ativas", "imagem/loss", "imagem/mse",
"audio/loss")})
tempo_s = time.time() - t0
if parte:
torch.save({"modelo": modelo.state_dict(),
"otimizador": treinar.otimizador.state_dict(),
"conselho": (treinar.conselho_acoplado.state_dict()
if treinar.conselho_acoplado is not None else None),
"passo_global": treinar.passo_global,
"perdas": perdas, "tel_jepa_ac": tel_jepa_ac,
"rng_torch": torch.get_rng_state(),
"rng_py": random.getstate(),
"rng_np": np.random.get_state(),
"im0": im0, "au0": au0}, ckpt)
if treinar.passo_global < passos:
return {"parcial": True, "passos": treinar.passo_global}
res = {
"variante": nome, "v19": v19, "passos": len(perdas),
"lote": cfg.treino.lote,
"perda_media_inicial": round(sum(perdas[:8]) / max(1, len(perdas[:8])), 4),
"perda_media_final": round(sum(perdas[-8:]) / max(1, len(perdas[-8:])), 4),
"perda_min": round(min(perdas), 4),
"perdas_finitas": all(p == p for p in perdas),
"tempo_s": round(tempo_s, 1),
"tempo_ms_por_passo": round(1000 * tempo_s / max(1, len(perdas)), 1),
"n_registros_corpus": len(registros),
"perdas_por_passo": perdas,
}
if getattr(modelo, "enc_imagem", None) is not None and im0.numel():
res["drift_encoder_imagem"] = float(
(modelo.enc_imagem.proj.weight.data - im0).abs().max())
if getattr(modelo, "enc_audio", None) is not None and au0.numel():
res["drift_encoder_audio"] = float(
(modelo.enc_audio.conv1.weight.data - au0).abs().max())
# ---- SONICMOE micro-benchmark (foco): sônico × vetorial, MESMOS pesos --
if v19:
import torch as _t
moes = [b.moe for b in modelo.blocos
if getattr(b, "moe", None) is not None]
if moes:
modelo.eval()
modelo.definir_fase_moe("foco")
# lote sintético do próprio espaço (h do tronco: (B,T,d))
B, T, d = 2, 32, int(cfg.modelo.d_modelo)
x = _t.randn(B, T, d)
# vetorial
for m in moes:
m.modo_sonico = False
_t.manual_seed(SEED)
_t.cuda.manual_seed_all(SEED)
t0v = time.time()
ys = [m(x) for m in moes for _ in range(10)]
tv = (time.time() - t0v) / 10
# sônico (mesmos pesos)
for m in moes:
m.modo_sonico = True
_t.manual_seed(SEED)
_t.cuda.manual_seed_all(SEED)
t0s = time.time()
ysn = [m(x) for m in moes for _ in range(10)]
ts = (time.time() - t0s) / 10
dy = max(float((a - b).abs().max()) for a, b in zip(ys, ysn))
io = moes[0].ultimo_io
res["sonicmoe"] = {
"n_camadas": len(moes),
"tempo_vetorial_ms": round(1000 * tv, 2),
"tempo_sonico_ms": round(1000 * ts, 2),
"speedup_wallclock": round(tv / max(ts, 1e-9), 3),
"delta_y_max": dy,
"ganho_io_modelado": round(io.get("ganho_io", 0.0), 3),
"pilha_evitada_bytes": io.get("pilha_evitada_bytes", 0),
"fator_trabalho": round(io.get("fator_trabalho", 0.0), 3),
"tile_m": io.get("tile_m", 0)}
# conselho — curva da perda JEPA acoplada (aprendizado real)
if tel_jepa_ac:
ini = [t["loss"] for t in tel_jepa_ac[:8]]
fim = [t["loss"] for t in tel_jepa_ac[-8:]]
res["jepa_acoplada"] = {
"passos_com_perda": len(tel_jepa_ac),
"perda_inicial": round(sum(ini) / max(1, len(ini)), 4),
"perda_final": round(sum(fim) / max(1, len(fim)), 4),
"drift_alvo_ema_imagem": float((
treinar.conselho_acoplado.variantes["imagem"]
.target.stem.enc.proj.weight.data
- treinar.conselho_acoplado.variantes["imagem"]
.stem.enc.proj.weight.data).abs().max())
if "imagem" in treinar.conselho_acoplado.variantes else None}
del treinar, modelo, orquestrador, hub
gc.collect()
return res
def est_padrao(seed: int) -> dict:
"""Estado RNG padrão reconstrutível (mesma semente nos dois braços)."""
import random
import numpy as np
import torch
torch.manual_seed(seed)
random.seed(seed)
np.random.seed(seed)
return {"torch": torch.get_rng_state(), "random": random.getstate(),
"numpy": np.random.get_state()}
def relatorio() -> int:
braços = ["baseline_v18", "v19_completo", "v19_lambda_baixo"]
dados = {}
for nome in braços:
p = os.path.join(TELEMETRIA, f"v19_{nome}.json")
if os.path.exists(p):
with open(p) as f:
dados[nome] = json.load(f)
if "baseline_v18" not in dados or "v19_completo" not in dados:
print("faltam resultados dos braços A/B")
return 1
a = dados["baseline_v18"]
print("=== TESTE REAL v19 — A/B/C PAREADO (doc 31 §7) ===")
print(f"registros reais: {a['n_registros_corpus']} | passos: {a['passos']}"
f" | lote: {a['lote']}")
pa = a["perdas_por_passo"]
for nome, rotulo in (("baseline_v18", "A baseline_v18 "),
("v19_completo", "B v19_completo "),
("v19_lambda_baixo", "C v19_lambda_baixo ")):
if nome not in dados:
continue
r = dados[nome]
print(f"{rotulo}: {r['perda_media_inicial']} → "
f"{r['perda_media_final']} ({r.get('melhoria_x', '—')}×)")
if nome != "baseline_v18":
pb = r["perdas_por_passo"]
n = min(len(pa), len(pb))
deltas = [pb[i] - pa[i] for i in range(n)]
half = n // 2
media = sum(deltas) / n
print(f" ΔCE pareado vs A: {media:+.4f} | 1ª metade "
f"{sum(deltas[:half]) / max(1, half):+.4f} | 2ª metade "
f"{sum(deltas[half:]) / max(1, n - half):+.4f}")
if "jepa_acoplada" in r:
j = r["jepa_acoplada"]
print(f" JEPA acoplada: {j['perda_inicial']} → {j['perda_final']}"
f" | drift alvo EMA imagem {j['drift_alvo_ema_imagem']:.2e}")
if "sonicmoe" in r:
s = r["sonicmoe"]
print(f" SonicMoE: Δy {s['delta_y_max']:.1e} | ganho_io "
f"{s['ganho_io_modelado']}× | pilha evitada "
f"{s['pilha_evitada_bytes'] / 1e6:.2f} MB/forward | "
f"wallclock {s['speedup_wallclock']}× (CPU, escala pequena)")
for k in ("drift_encoder_imagem", "drift_encoder_audio"):
linha = " ".join(f"{nome.split('_')[-1]}={dados[nome].get(k, 0):.2e}"
for nome in dados)
print(f"{k}: {linha}")
saida = {"braços": {n: {k: v for k, v in r.items()
if k != "perdas_por_passo"}
for n, r in dados.items()}}
with open(os.path.join(TELEMETRIA, "v19_relatorio_ab.json"), "w",
encoding="utf-8") as f:
json.dump(saida, f, ensure_ascii=False, indent=2)
print("salvo: telemetria_out/v19_relatorio_ab.json")
return 0
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--coletar", action="store_true")
ap.add_argument("--variante", choices=["baseline_v18", "v19_completo",
"v19_lambda_baixo"])
ap.add_argument("--passos", type=int, default=140)
ap.add_argument("--lambda_jac", type=float, default=0.3)
ap.add_argument("--parte", type=int, default=0,
help="passos nesta chamada (retomada por checkpoint)")
ap.add_argument("--relatorio", action="store_true")
args = ap.parse_args()
if args.coletar:
print(json.dumps(coletar_fresco(), ensure_ascii=False)[:400])
return 0
if args.relatorio:
return relatorio()
if not args.variante:
print("--variante obrigatória (ou --coletar / --relatorio)")
return 1
v19 = args.variante != "baseline_v18"
res = rodar_variante(args.variante, v19, args.passos, parte=args.parte,
lambda_jac=args.lambda_jac)
if res.get("parcial"):
print(json.dumps(res))
return 0
res["melhoria_x"] = round(res["perda_media_inicial"]
/ max(res["perda_media_final"], 1e-9), 3)
caminho = os.path.join(TELEMETRIA, f"v19_{args.variante}.json")
with open(caminho, "w", encoding="utf-8") as f:
json.dump(res, f, ensure_ascii=False, indent=2)
print(json.dumps({k: v for k, v in res.items()
if k not in ("perdas_por_passo",)}, ensure_ascii=False))
return 0
if __name__ == "__main__":
raise SystemExit(main())
|