File size: 5,547 Bytes
2dc44f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""72_suite_v090.py — v0.9.0: VEREDITO CONSOLIDADO das críticas Qwen3.8 (lote 2).

Executa demo_criticas_v090 TRÊS vezes (medições agregadas), herda os gates
da v0.8.0 (suite_v080_final.json) e adiciona os gates do treino REAL v0.9.0
(resultados/treino_v090.json — Wikipédia PT-BR, pipeline A/B/C completo).
Saída: resultados/suite_v090_final.json
"""
import json, os

def main():
    pasta = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    R = os.path.join(pasta, "resultados")
    rel = {"versao": "0.9.0", "blocos": {}, "gates": {}, "medicoes": {}}

    def carrega(arq):
        p = os.path.join(R, arq)
        return json.load(open(p)) if os.path.exists(p) else None

    # ---- legado v0.8.0
    legado = carrega("suite_v080_final.json")
    if legado:
        g_legado = legado.get("gates", legado)
        ok = sum(1 for v in g_legado.values() if v is True)
        rel["blocos"]["legado_v080"] = f"{ok}/{len(g_legado)}"
        for k, v in g_legado.items():
            rel["gates"][f"legado_{k}"] = v

    # ---- demos v0.9.0 (3 execuções — gates estáveis, tempos medianos)
    import khtst_rust as k
    execucoes = [k.demo_criticas_v090() for _ in range(3)]

    def mediana(chave, *sub):
        vals = []
        for e in execucoes:
            v = e[chave]
            for s in sub:
                v = v[s]
            vals.append(v)
        return sorted(vals)[1]

    # (1) skew O(n²) via index_add — F-13/F-14
    bits_todos = all(e["skew_index_add"]["gates"]["bits_iguais_todos_n"] for e in execucoes)
    rel["gates"]["q1_skew_bits_identicos"] = bits_todos
    rel["blocos"]["q1_skew_index_add"] = f"{int(bits_todos)}/1"
    rel["medicoes"]["q1_skew"] = {
        n: {
            "speedup": mediana("skew_index_add", "por_n", n, "speedup"),
            "razao_memoria": mediana("skew_index_add", "por_n", n, "razao_memoria"),
            "tempo_novo_s": mediana("skew_index_add", "por_n", n, "tempo_novo_s"),
            "tempo_ref_s": mediana("skew_index_add", "por_n", n, "tempo_ref_s"),
        }
        for n in ("n_16", "n_64", "n_128")
    }
    rel["gates"]["q1_skew_mais_rapido_n128"] = (
        rel["medicoes"]["q1_skew"]["n_128"]["speedup"] > 10.0)

    # (2) calibrar zero-cópia — F-15
    c0 = execucoes[0]["calibrar_zero_copia"]
    bits_cal = all(e["calibrar_zero_copia"]["bits_iguais_3_passos"] for e in execucoes)
    t_novo = mediana("calibrar_zero_copia", "tempo_novo_s")
    t_ref = mediana("calibrar_zero_copia", "tempo_ref_s")
    t_tens = mediana("calibrar_zero_copia", "tempo_tensor_s")
    rel["gates"]["q2_calibrar_bit_a_bit"] = bits_cal
    rel["gates"]["q2_calibrar_nao_regride"] = t_novo <= t_ref * 1.05
    rel["blocos"]["q2_calibrar_zero_copia"] = "2/2" if (bits_cal and t_novo <= t_ref * 1.05) else "0/2"
    rel["medicoes"]["q2_calibrar"] = {
        "tempo_ref_s": t_ref, "tempo_novo_s": t_novo, "tempo_tensor_s": t_tens,
        "speedup_zero_copia": t_ref / max(t_novo, 1e-12),
        "razao_tensor_vs_zero_copia": t_tens / max(t_novo, 1e-12),
    }

    # (3) forward canônico (bug v080-1 fora da API pública)
    fwd_ok = all(
        e["forward_canonico"]["gates"]["valores_iguais"]
        and e["forward_canonico"]["gates"]["gradiente_ativo"]
        for e in execucoes)
    rel["gates"]["q3_forward_valores_e_gradiente"] = fwd_ok
    rel["blocos"]["q3_forward_canonico"] = f"{int(fwd_ok)}/1"
    rel["medicoes"]["q3_forward"] = {
        "max_dif_valores_vs_oraculo": execucoes[0]["forward_canonico"]["max_dif_valores_vs_oraculo"],
        "grad_roteador": execucoes[0]["forward_canonico"]["grad_roteador"],
        "grad_especialistas": execucoes[0]["forward_canonico"]["grad_especialistas"],
    }

    # (4) newtypes de domínio — T-V1/T-V2
    nt_ok = all(
        e["newtypes_dominio"]["gates"]["fronteira_validada"] for e in execucoes)
    rel["gates"]["q4_newtypes_fronteira_validada"] = nt_ok
    rel["blocos"]["q4_newtypes"] = f"{int(nt_ok)}/1"

    # ---- treino REAL v0.9.0 (dados reais Wikipédia PT-BR)
    tr = carrega("treino_v090.json")
    if tr:
        g = tr.get("fnh", {}).get("gates", {})
        for nome, val in g.items():
            rel["gates"][f"real_{nome}"] = val
        okr = sum(1 for v in g.values() if v)
        rel["blocos"]["treino_real_v090"] = f"{okr}/{len(g)}"
        rel["medicoes"]["treino_real"] = {
            "sequencias": tr["dados"]["sequencias"],
            "fonte": tr["dados"]["fonte"],
            "ce_inicial": tr["fases"]["c"]["ce_inicial"],
            "ce_final": tr["fases"]["c"]["ce_final"],
            "build": tr.get("build"),
        }
        rel["gates"]["real_ce_decresce"] = tr["fases"]["c"]["ce_final"] < tr["fases"]["c"]["ce_inicial"]

    # ---- compilação (Aprimoramento 4): medição registrada pela telemetria
    tel = carrega("telemetria_v090.json")
    if tel and "compilacao" in tel:
        rel["gates"]["q5_compila_sem_python"] = tel["compilacao"].get("dominio_compila", False)
        rel["blocos"]["q5_split_ffi"] = "1/1" if tel["compilacao"].get("dominio_compila") else "0/1"
        rel["medicoes"]["q5_compilacao"] = tel["compilacao"]

    with open(os.path.join(R, "suite_v090_final.json"), "w") as f:
        json.dump(rel, f, indent=1, ensure_ascii=False)
    total = sum(1 for v in rel["gates"].values() if v is True)
    print(f"gates: {total}/{len(rel['gates'])}")
    for b, v in rel["blocos"].items():
        print(f"  {b}: {v}")
    print("OK: resultados/suite_v090_final.json")

if __name__ == "__main__":
    main()