v0.13.0: crítica provas_qwen4 → r-46/r-47 — RE-3″ por peça (greedy ótimo por matroide T-R2, distorção ponderada Hedge T-R1, bound composto T-R3), denoise James–Stein T-DN1, TC v2 com piso de detecção calibrado T-TC2, banco f16 RNE bit-a-bit T-F1 (erro 0,000481 ≤ 2⁻¹¹), enxame paralelo determinístico T-E, árvore binária ótima indexável T-AB, calibrador pareado CRN V-4 com τ_c por quantil, 15 parâmetros não-estáticos auditáveis; A/B real: conf 0,810→0,868 com τ_c 0,55→0,649, 24/24 sound — 22/22 gates, 184/184 cargo
7d5b244 verified Download scripts/79_treino_v013.py from PowerMachine/khtst-rust: direct link, hf CLI and curl.
- Browser
- Download file 9.16 kB
-
https://huggingface.co/PowerMachine/khtst-rust/resolve/main/scripts/79_treino_v013.py
- Command line
-
hf download hf://PowerMachine/khtst-rust/scripts/79_treino_v013.py
-
curl -L -o 79_treino_v013.py https://huggingface.co/PowerMachine/khtst-rust/resolve/main/scripts/79_treino_v013.py
9.16 kB
| #!/usr/bin/env python3 | |
| """79_treino_v013.py — AVALIAÇÃO COM DADOS REAIS da v0.13 (r-46/r-47). | |
| A/B controlado NO MESMO pipeline (raciocinio_elastico_residuos): | |
| - braço v0.12 (modo_v013=False): prefixo comum + busca binária (baseline); | |
| - braço v0.13 (modo_v013=True): RE-3″ por peça (greedy ótimo T-R2) + | |
| denoise James–Stein (T-DN1) + f16 (T-F1) + τ_c por quantil (V-4(iii)) + | |
| gate calibração PAREADA (V-4(i)/(ii)). | |
| Dados: Wikipédia PT-BR (273 artigos, script 39; janelas ctx 256, BPE 16384). | |
| Também roda: TC v2 com piso de detecção (T-TC2), demos dos módulos novos | |
| (gumbel/denoise/re3v2/f16/calibrador/enxame/árvore binária) e o PAINEL de | |
| telemetria v0.13 com a tabela de parâmetros RESOLVIDOS. | |
| Execução em PRIMEIRO PLANO (o fundo mata processos sem erro/OOM — | |
| confirmado de novo nesta sessão: rustup e builds mortos em silêncio). | |
| """ | |
| import json, os, sys, time | |
| import numpy as np | |
| def main(): | |
| pasta = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| sys.path.insert(0, pasta) | |
| os.makedirs(os.path.join(pasta, "resultados"), exist_ok=True) | |
| import khtst_rust as K | |
| cfg = K.Config(os.path.join(pasta, "configs", "base_rust.json")) | |
| ck_tok = os.path.join(pasta, "resultados", "tokenizador_conceitos.safetensors") | |
| cache = lambda nome: os.path.join(pasta, "resultados", f"cache_v013_{nome}.json") | |
| bpe = K.Bpe.carregar(os.path.join(pasta, "dados", "bpe.json")) | |
| seqs = [] | |
| with open(os.path.join(pasta, "dados", "shard_treino.jsonl")) as f: | |
| for linha in f: | |
| ids = bpe.codificar(json.loads(linha)["texto"]) | |
| for i in range(0, max(1, len(ids) - 256), 128): | |
| seqs.append(ids[i:i + 256]) | |
| seqs = seqs[:1400] | |
| PAD = 0 | |
| largura = max(len(s) for s in seqs) | |
| seqs_np = np.array([s + [PAD] * (largura - len(s)) for s in seqs], dtype=np.uint32) | |
| rel = { | |
| "versao": "0.13.0", | |
| "dados": {"sequencias": len(seqs), "fonte": "wikimedia/wikipedia 20231101.pt"}, | |
| } | |
| print(f"sequências: {len(seqs)} (ctx=256) | numpy {seqs_np.shape}", flush=True) | |
| # ---------------- fase A (latentes) — reusa checkpoint se presente ---- | |
| if not os.path.exists(ck_tok): | |
| print("=== FASE A — tokenizador (SAFETENSORS, teto 400s) ===", flush=True) | |
| t0 = time.time() | |
| saida = K.treinar_fase_a_np(cfg, seqs_np, None, ck_tok, None, 400.0) | |
| rel["fase_a"] = {**saida["resumo"], "tempo_s": round(time.time() - t0, 1)} | |
| json.dump(rel["fase_a"], open(cache("a"), "w")) | |
| print(json.dumps(rel["fase_a"], indent=1, ensure_ascii=False), flush=True) | |
| else: | |
| rel["fase_a"] = (json.load(open(cache("a"))) | |
| if os.path.exists(cache("a")) else {}) | |
| print("fase A: checkpoint presente", flush=True) | |
| print("=== LATENTES REAIS ===", flush=True) | |
| lat = K.codificar_latentes(cfg, ck_tok, seqs_np[:96]) | |
| nuvem_lat = lat.reshape(-1, lat.shape[-1]).astype(np.float32) | |
| print(f"latentes: {lat.shape} {lat.dtype} | nuvem {nuvem_lat.shape}", flush=True) | |
| # ---------------- A/B elástico: v0.12 (baseline) vs v0.13 ------------- | |
| print("=== A/B ELÁSTICO — v0.12 (prefixo comum) vs v0.13 (por peça) ===", | |
| flush=True) | |
| t0 = time.time() | |
| el12 = K.raciocinio_elastico_residuos( | |
| nuvem_lat, k=16, n_tentativas=3, passos_treino=240, | |
| tau_c=0.55, b_max=6, n_consultas=24, semente=42, modo_v013=False, | |
| ) | |
| el12["tempo_s"] = round(time.time() - t0, 1) | |
| print(f"[v0.12] conf {el12['elasticas']['conf_media']:.4f} | " | |
| f"aceites {el12['elasticas']['aceites']}/24 | " | |
| f"gate {el12['elasticas']['gate_calibrado']} | " | |
| f"τ_c {el12['tau_c_entrada']:.3f} | " | |
| f"{el12['tempo_s']}s", flush=True) | |
| r3_12 = el12["elasticas"].get("re3_prefixos", {}) | |
| print(f"[v0.12] RE-3: {r3_12.get('emitidos', 0)} certificados | " | |
| f"bits {r3_12.get('bits_antes', 0):.0f}→{r3_12.get('bits_depois', 0):.0f}", | |
| flush=True) | |
| t0 = time.time() | |
| el13 = K.raciocinio_elastico_residuos( | |
| nuvem_lat, k=16, n_tentativas=3, passos_treino=240, | |
| tau_c=0.55, b_max=6, n_consultas=24, semente=42, modo_v013=True, | |
| ) | |
| el13["tempo_s"] = round(time.time() - t0, 1) | |
| print(f"[v0.13] conf {el13['elasticas']['conf_media']:.4f} | " | |
| f"aceites {el13['elasticas']['aceites']}/24 | " | |
| f"gate {el13['elasticas']['gate_calibrado']} (pareado V-4) | " | |
| f"τ_c resolvido {el13['tau_c_resolvido']:.3f} " | |
| f"(entrada {el13['tau_c_entrada']:.3f}) | " | |
| f"{el13['tempo_s']}s", flush=True) | |
| r3_13 = el13["elasticas"].get("re3_prefixos", {}) | |
| print(f"[v0.13] RE-3″: {r3_13.get('emitidos', 0)} certificados | " | |
| f"bits {r3_13.get('bits_antes', 0):.0f}→{r3_13.get('bits_depois', 0):.0f} " | |
| f"| rollbacks {r3_13.get('rollbacks', 0)}", flush=True) | |
| rel["elastico_ab"] = {"v012": el12, "v013": el13} | |
| # comparação direta dos mecanismos de compressão | |
| rel["comparativo"] = { | |
| "conf_media": {"v012": el12["elasticas"]["conf_media"], | |
| "v013": el13["elasticas"]["conf_media"]}, | |
| "aceites": {"v012": el12["elasticas"]["aceites"], | |
| "v013": el13["elasticas"]["aceites"]}, | |
| "gate": {"v012": el12["elasticas"]["gate_calibrado"], | |
| "v013": el13["elasticas"]["gate_calibrado"]}, | |
| "tau_c": {"v012_entrada": el13["tau_c_entrada"], | |
| "v013_resolvido": el13["tau_c_resolvido"]}, | |
| "re3": { | |
| "v012": {k: r3_12.get(k) for k in | |
| ("emitidos", "l_medio", "bits_antes", "bits_depois", | |
| "rollbacks", "violacoes_entregues")}, | |
| "v013": {k: r3_13.get(k) for k in | |
| ("emitidos", "l_medio", "bits_antes", "bits_depois", | |
| "rollbacks", "violacoes_entregues")}, | |
| }, | |
| "economia_bits_extra_v013": | |
| (r3_12.get("bits_depois", 0) - r3_13.get("bits_depois", 0)) | |
| if r3_12.get("emitidos") and r3_13.get("emitidos") else 0, | |
| } | |
| # ---------------- TC v2 nos latentes REAIS + piso --------------------- | |
| print("=== TC v2 — latentes reais + piso de detecção calibrado ===", flush=True) | |
| tc_real = K.demo_tc_v2_v013(48, 512, 0.0, 42) # independência de referência | |
| tc_dep = K.demo_tc_v2_v013(48, 512, 0.5, 42) # dependência conhecida | |
| rel["tc_v2"] = { | |
| "independente": tc_real, | |
| "dependente_rho_050": tc_dep, | |
| "piso_deteccao": tc_real["piso_deteccao_medido"], | |
| "nota": "cópula gaussiana com TC fechado; latentes do projeto são " | |
| "efetivamente descorrelacionados (r-45 §3.7) — o piso " | |
| "QUALIFICA a afirmação 'TC ≈ 0'", | |
| } | |
| print(f" piso de detecção: {tc_real['piso_deteccao_medido']:.4f} nats | " | |
| f"ρ=0,5 estimado {tc_dep['tc_estimado_nats']:.4f} " | |
| f"(teórico {tc_dep['tc_teorico_fechado']:.4f})", flush=True) | |
| # ---------------- demos dos módulos v0.13 (mecanismos) ---------------- | |
| print("=== DEMOS v0.13 (mecanismos, telemetria) ===", flush=True) | |
| rel["gumbel"] = K.demo_gumbel_v013(256, 16, 7) | |
| rel["denoise"] = K.demo_denoise_v013(96, 64, 0.15, 9) | |
| rel["re3_v2"] = K.demo_re3_v2_v013() | |
| rel["f16"] = K.demo_f16_v013(64, 64, 3) | |
| rel["calibrador"] = K.demo_calibrador_v013(42) | |
| rel["enxame"] = K.demo_enxame_v013(4, 2, 21) | |
| rel["arvore_binaria"] = K.demo_arvore_binaria_v013(12, 0.7) | |
| rel["asm_ext"] = K.asm_ext_relatorio() | |
| for nome in ("gumbel", "denoise", "re3_v2", "f16", "calibrador", "enxame", | |
| "arvore_binaria"): | |
| g = rel[nome].get("gates", {}) | |
| ok = all(bool(v) for v in g.values()) if g else False | |
| print(f" {nome}: gates {'OK' if ok else 'FALHOU'} {g}", flush=True) | |
| # ---------------- painel v0.13 + parâmetros resolvidos ---------------- | |
| rel["parametros_resolvidos"] = K.parametros_resolvidos() | |
| rel["painel_v013"] = K.painel_v013() | |
| n_param = rel["parametros_resolvidos"]["n_parametros"] | |
| print(f" parâmetros NÃO-ESTÁTICOS resolvidos na tabela: {n_param}", flush=True) | |
| # ---------------- persistência ---------------------------------------- | |
| saida = os.path.join(pasta, "resultados", "treino_v013.json") | |
| json.dump(rel, open(saida, "w"), ensure_ascii=False, indent=1) | |
| print(f"salvo: {saida}", flush=True) | |
| # ---------------- telemetria jsonl (auditoria) ------------------------ | |
| tel = os.path.join(pasta, "resultados", "telemetria_v013.jsonl") | |
| with open(tel, "w") as f: | |
| f.write(json.dumps({"evento": "inicio_v013", "n_seqs": len(seqs)}, | |
| ensure_ascii=False) + "\n") | |
| f.write(json.dumps({"evento": "comparativo", **rel["comparativo"]}, | |
| ensure_ascii=False) + "\n") | |
| f.write(json.dumps({"evento": "tc_v2", "piso": tc_real["piso_deteccao_medido"]}, | |
| ensure_ascii=False) + "\n") | |
| print(f"telemetria: {tel}", flush=True) | |
| print("79_treino_v013 CONCLUÍDO", flush=True) | |
| if __name__ == "__main__": | |
| main() | |