File size: 14,309 Bytes
20672ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d5bd51
 
 
 
20672ab
 
1d5bd51
 
 
 
20672ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -*- coding: utf-8 -*-
"""SUITE v21 — verificação doc 33 (refatorações do usuário + hot-paths
Cython + tabela v17 + normalização espectral + imagem adaptativa).

Seções:
  §1 IPC — fonte única de layout (Teos 33.1/33.2) + remoção do Rust (DRY)
  §2 Newton–Schulz — normalização espectral certificada (Teos 33.3–33.6)
  §3 Imagem — redimensionamento adaptativo (Teos 33.7–33.10)
  §4 Hot-paths Cython — conv fundida + top-k do roteador (Teos 33.11–33.13)
  §5 Tabela v17 — fechamento do laço no treinador (Teo 33.14)
  §6 indicadores — janela cheia funciona (nota de auditoria doc 33 §6)
"""
import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src",
                                "khtst", "acelerado"))

import torch  # noqa: E402

RAIZ = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
_OK = 0
_FALHAS = []


def check(nome, cond, detalhe=""):
    global _OK
    if cond:
        _OK += 1
        print(f"  ✓ {nome}")
    else:
        _FALHAS.append(nome)
        print(f"  ✗ {nome} {detalhe}")


def main():
    torch.manual_seed(21)
    print("=" * 72)
    print("SUITE v21 — fonte única IPC, NS espectral, imagem adaptativa,")
    print("hot-paths Cython, tabela v17")
    print("=" * 72)

    # ====================== §1 IPC — fonte única (Teos 33.1/33.2) ==========
    print("§1 IPC: layout com verificação compile-time + import-time:")
    from khtst.ipc import layout, framing, KHTSTCanal, MOTOR_IPC
    check("Teo 33.2: binário Cython auditado contra layout.py no import",
          MOTOR_IPC == "cython")
    check("layout: header 256 B com offsets de cache line (fonte única)",
          layout.HEADER_SIZE == 256 and layout.OFF_HEAD == 64
          and layout.OFF_TAIL == 128 and layout.OFF_DROPPED == 192)
    check("Teo 33.1: _Static_asserts presentes no C gerado (compile-time)",
          open(os.path.join(RAIZ, "src", "khtst", "ipc", "khtst_ipc.c"),
               encoding="utf-8").read().count("_Static_assert") >= 8)
    check("fallback herda as constantes da FONTE ÚNICA (zero duplicação)",
          "from khtst.ipc.layout import" in open(
              os.path.join(RAIZ, "src", "khtst", "ipc", "_fallback.py"),
              encoding="utf-8").read())
    check("framing: struct 24 B auditada contra layout.FR_HEADER_SIZE",
          framing.HEADER_SIZE == layout.FR_HEADER_SIZE == 24
          and framing.TIPO_PEDIDO == layout.TIPO_PEDIDO)
    check("R21.1: crate Rust REMOVIDO (DRY — única implementação é Cython)",
          not os.path.isdir(os.path.join(RAIZ, "src", "khtst", "ipc", "rust")))
    # fórmula da capacidade — fonte única
    check("capacidade_ring: fórmula única (next_pow2(total−256)/2)",
          layout.capacidade_ring(4 * 1024 * 1024) ==
          (lambda x: (1 << (x - 1).bit_length() if x > 1 else 1) // 2)
          (4 * 1024 * 1024 - 256))
    c1 = KHTSTCanal(b"v21_suite", 1024 * 1024)
    c2 = KHTSTCanal.anexar(c1.fd, 1024 * 1024)
    c1.enviar_frame(layout.TIPO_PEDIDO, b"fonte-unica", seq=21)
    cab, pay = c2.receber_frame()
    check("canal funcional pós-refatoração (frame round-trip)",
          pay == b"fonte-unica" and cab["seq"] == 21)

    # ====================== §2 NS espectral (Teos 33.3–33.6) ===============
    print("§2 Newton–Schulz: normalização espectral certificada:")
    from khtst.treino.otimizadores import (newton_schulz5, TETO_ESPECTRAL)
    check("TETO < borda do basin (1.255) com folga p/ bf16",
          1.0 < TETO_ESPECTRAL <= 1.21)

    def com_espectro(vals, m=512, n=256):
        U, _ = torch.linalg.qr(torch.randn(m, n))
        return U @ torch.diag(vals)

    def erro_ort(X):
        Xf = X.float()
        G = Xf @ Xf.mT
        n = G.size(-1)
        return (G - torch.eye(n, dtype=G.dtype)).norm().item() / (n ** 0.5)

    def ns_frob_v20(G, iters=5):
        a, b, c = 3.4445, -4.7750, 2.0315
        X = G.bfloat16()
        if G.size(-2) > G.size(-1):
            X = X.mT
        X = X / (X.norm(dim=(-2, -1), keepdim=True) + 1e-7)
        for _ in range(iters):
            A = X @ X.mT
            B = b * A + c * (A @ A)
            X = a * X + B @ X
        return X.mT if G.size(-2) > G.size(-1) else X

    perfis = {
        "pico": com_espectro(torch.tensor([1.0] + [0.02] * 255)),
        "exp0.9": com_espectro(torch.tensor([0.9 ** i for i in range(256)])),
        "plano": com_espectro(torch.ones(256)),
        "mp": com_espectro(torch.linspace(1.0, 0.3, 256)),
    }
    ganhos = {}
    for nome, G in perfis.items():
        G = G.bfloat16()
        Xv = newton_schulz5(G)
        Xf = ns_frob_v20(G)
        check(f"Teo 33.5-i: {nome} — sem NaN/Inf (janela invariante)",
              bool(torch.isfinite(Xv.float()).all()))
        sv = torch.linalg.matrix_norm(Xv.float(), 2).item()
        sf = torch.linalg.matrix_norm(Xf.float(), 2).item()
        ganhos[nome] = sv
        check(f"Teo 33.5-ii: {nome} — σ̃max v21 ≥ v20/1.2 (nunca pior)",
              sv >= sf / 1.2 - 0.05, f"v21={sv:.3f} v20={sf:.3f}")
    check("Teo 33.5: escala de partida melhora nos perfis espalhados",
          ganhos["mp"] > ganhos["plano"] or
          ganhos["exp0.9"] > 0.5, str({k: round(v, 2) for k, v in ganhos.items()}))
    # caminho fp32 (Teo 30.4 preservado)
    Gq = torch.randn(32, 16) * 1e-4
    Xq = newton_schulz5(Gq)
    check("Teo 30.4 preservado: matriz quase-nula ⟹ fp32 sem NaN",
          bool(torch.isfinite(Xq).all()))
    # lote (ndim=3) — broadcast das cotas
    Gb = torch.randn(3, 64, 32).bfloat16()
    Xb = newton_schulz5(Gb)
    check("lote (3,64,32): broadcast das cotas por item, sem NaN",
          Xb.shape == Gb.shape and bool(torch.isfinite(Xb.float()).all()))

    # ====================== §3 imagem adaptativa (Teos 33.7–33.10) =========
    print("§3 Imagem: redimensionamento adaptativo:")
    import io
    import numpy as np
    from PIL import Image
    from khtst.percepcao.redimensionar import (imagem_para_tensor,
                                               redimensionar_adaptativo,
                                               janela_saliente)
    arr = np.zeros((400, 2000), dtype=np.uint8)
    for x in range(0, 2000, 6):
        arr[:, x:x + 2] = 255
    img = Image.fromarray(arr).convert("RGB")
    buf = io.BytesIO()
    img.save(buf, "JPEG")
    jpeg = buf.getvalue()
    t1 = imagem_para_tensor(jpeg)
    t2 = imagem_para_tensor(jpeg)
    check("Teo 33.10: determinístico (mesmo JPEG ⟹ mesmo tensor)",
          torch.equal(t1, t2) and t1.shape == (3, 96, 96))
    brilho = t1.mean(0)
    linhas = (brilho.max(1).values > 0.05).nonzero().flatten()
    alt = int(linhas.max() - linhas.min() + 1) if linhas.numel() else 0
    check("Teo 33.7: letterbox preserva a razão (conteúdo ~20px, não 96)",
          14 <= alt <= 26, f"alt={alt}")
    t20 = imagem_para_tensor(jpeg, letterbox=False)
    ref20 = torch.from_numpy(
        np.asarray(img.resize((96, 96)), dtype=np.float32) / 255.0
    ).permute(2, 0, 1)
    check("kill-switch: letterbox=False ⟹ stretch v20 EXATO",
          torch.equal(t20, ref20))
    # janela saliente
    arr2 = np.zeros((300, 1200), dtype=np.uint8)
    arr2[:, 300:900] = 255
    for x in range(300, 900, 6):
        arr2[:, x:x + 2] = 0
    crop = janela_saliente(Image.fromarray(arr2).convert("RGB"), 96)
    check("Teo 33.9: janela saliente corta 2.5·H alinhada ao texto",
          crop.size == (750, 300), f"size={crop.size}")
    # fonte única dos encoders (R21.4)
    for mod, trecho in [("treino/treinador.py", "redimensionar"),
                        ("treino/jepa_mundo.py", "redimensionar_adaptativo"),
                        ("geracao/difusao.py", "redimensionar_adaptativo")]:
        s = open(os.path.join(RAIZ, "src", "khtst", mod),
                 encoding="utf-8").read()
        check(f"R21.4: {mod} usa a fonte única",
              trecho in s and ".resize((96, 96))" not in s)

    # ====================== §4 hot-paths Cython (Teos 33.11–33.13) =========
    print("§4 Hot-paths Cython:")
    import mamba3hot as hot
    import torch.nn.functional as F
    B, L, D, K = 4, 96, 128, 4
    u = torch.randn(B, L, D)
    conv = torch.nn.Conv1d(D, D, K, padding=0, groups=D)
    uc_ref = conv(F.pad(u.transpose(1, 2), (K - 1, 0))).transpose(1, 2)
    uc_hot = torch.from_numpy(hot.conv1d_causal_profunda(
        u.numpy(), conv.weight.squeeze(1).detach().numpy(),
        conv.bias.detach().numpy()))
    check("Teo 33.11: conv fundida ≡ caminho torch (max|Δ| < 1e-5)",
          float((uc_ref - uc_hot).abs().max()) < 1e-5)
    # gradiente analítico vs autograd
    u2 = torch.randn(B, L, D, requires_grad=True)
    w2 = conv.weight.squeeze(1).detach().clone().requires_grad_(True)
    b2 = conv.bias.detach().clone().requires_grad_(True)
    uc2 = F.conv1d(F.pad(u2.transpose(1, 2), (K - 1, 0)), w2.unsqueeze(1),
                   b2, groups=D).transpose(1, 2)
    g = torch.randn(B, L, D)
    uc2.backward(g)
    gu = torch.from_numpy(hot.conv1d_grad_u(g.numpy(), w2.detach().numpy()))
    gw = torch.from_numpy(hot.conv1d_grad_w2(g.numpy(), u2.detach().numpy(), K))
    gb = torch.from_numpy(hot.conv1d_grad_b(g.numpy()))
    rel_w = float((w2.grad - gw).abs().max() / w2.grad.abs().max())
    check("Teo 33.11-ii: gradiente analítico ≡ autograd (u/b exatos, w<1e-5)",
          float((u2.grad - gu).abs().max()) < 1e-4 and rel_w < 1e-5
          and float((b2.grad - gb).abs().max()) < 1e-4)
    # Mamba3Camada integra os dois caminhos
    import khtst.mamba3.kernel as k3
    from khtst.mamba3.hybrid import Mamba3Camada
    cam = Mamba3Camada(d_modelo=64, d_estado=8, rank_mimo=2, kernel_conv=4)
    x = torch.randn(2, 24, 64)
    k3.set_conv_cython(True)
    y1 = cam(x)
    k3.set_conv_cython(False)
    y2 = cam(x)
    k3.set_conv_cython(True)
    check("Teo 33.12: Mamba3Camada — Cython ON ≡ OFF (kill-switch)",
          float((y1 - y2).abs().max()) < 1e-5)
    # topk
    s = torch.randn(256, 32)
    v_ref, i_ref = torch.topk(s, 4, dim=-1)
    v_h, i_h = hot.topk_desc(s.numpy(), 4)
    check("Teo 33.13: top-k Cython — VALORES idênticos ao torch.topk",
          torch.equal(v_ref, torch.from_numpy(v_h)))
    check("Teo 33.13: índices exatos (sem empate no corte)",
          bool((i_ref == torch.from_numpy(i_h)).all()))
    from khtst.percepcao import moe as M
    from khtst.percepcao.moe import MoEAgrupavel
    moe = MoEAgrupavel(d=48, n_grupos=3, experts_por_grupo=2, d_ff_expert=32,
                       top_k=2, n_tarefas=4, margem_foco=0.5)
    xg = torch.randn(2, 6, 48)
    M.set_topk_cython(True)
    _, g1, m1 = moe._computar_gate(xg, "gener")
    M.set_topk_cython(False)
    _, g2, m2 = moe._computar_gate(xg, "gener")
    M.set_topk_cython(True)
    check("Teo 33.13: gate do MoE — topk Cython ≡ torch (g e máscara)",
          float((g1 - g2).abs().max()) < 1e-6 and torch.equal(m1, m2))

    # ====================== §5 tabela v17 (Teo 33.14) ======================
    print("§5 Tabela v17 de 18 sinais no treinador:")
    from khtst.aprimoramento.autorregulacao_estendida import (
        AutorreguladorEstendido)
    from khtst.aprimoramento.controlador_hibrido import ControladorHibrido
    areg = AutorreguladorEstendido({"ativo": True, "a_cada": 1}, hub=None)
    check("Teo 29.16: 18 controladores registrados",
          len(areg._controladores) == 18, f"{len(areg._controladores)}")
    check("nascimento neutro: centros = constantes de produção",
          abs(areg._valor("muon_momentum") - 0.95) < 1e-9
          and abs(areg._valor("tau_qk") - 100.0) < 1e-9)
    vals0 = areg.registrar({})
    check("sem sinais ⟹ nada move (robustez a chaves ausentes)",
          abs(vals0["adamw_beta1"] - 0.90) < 1e-9)
    vals = areg.registrar({"var_grad_norm": 1.5, "taxa_acerto_trust": 0.75,
                           "razao_clip": 0.3, "razao_moe_ce": 0.6,
                           "delta_perda_passo": 0.03, "logit_max": 150.0})
    check("sinais reais ⟹ controladores movem (dentro dos limites)",
          all(0.80 <= vals["adamw_beta1"] <= 0.95
              and 80.0 <= vals["tau_qk"] <= 120.0 for _ in [0]),
          f"b1={vals['adamw_beta1']:.4f} τ={vals['tau_qk']:.2f}")
    # nascimento neutro no TREINADOR (opt-in desligado ⟹ None)
    check("config: treino.autorreg_v17 existe (ativo=False default)",
          hasattr(__import__("khtst.config", fromlist=["Config"]).Config()
                  .treino, "autorreg_v17"))
    # produtores documentados (honestidade §11) — v22 moveu o ciclo VERBATIM
    # ao mixin treino/treinador_v22.py (Teo 34.11): a checagem de FONTE cobre
    # treinador.py + treinador_v22.py (o produtor real continua no código de
    # treino; erro de regressão da mudança do mixin, corrigido no v23)
    src = open(os.path.join(RAIZ, "src", "khtst", "treino", "treinador.py"),
               encoding="utf-8").read()
    _cam = os.path.join(RAIZ, "src", "khtst", "treino", "treinador_v22.py")
    if os.path.exists(_cam):
        src += open(_cam, encoding="utf-8").read()
    check("Teo 33.14: produtores reais no ciclo autorreg v17 (treinador+mixin)",
          "_ciclo_autorreg_v17" in src and "var_grad_norm" in src
          and "razao_moe_ce" in src and "taxa_acerto_trust" in src)

    # ====================== §6 indicadores (nota doc 33 §6) ================
    print("§6 indicadores — janela cheia (nota de auditoria):")
    from khtst.telemetria.indicadores import estagnado, avaliar
    check("estagnado com janela cheia executa e decide (auditoria v21: a "
          "suspeita de typo `etade` era artefato de exibição — o código "
          "real usa `metade`, conferido por dump octal)",
          estagnado([2.0, 1.9, 1.8, 1.7, 1.7, 1.75, 1.7, 1.72]) is True
          and estagnado([2.0, 1.9, 1.8, 1.7, 1.6, 1.4, 1.2, 1.0]) is False)

    # ======================================================================
    print("=" * 72)
    if _FALHAS:
        print(f"SUITE v21: {_OK} ok, {len(_FALHAS)} FALHAS:")
        for f in _FALHAS:
            print(f"   ✗ {f}")
        sys.exit(1)
    print(f"SUITE v21: {_OK}/{_OK} verificações verdes — TODAS VERDES ✓")


if __name__ == "__main__":
    main()