PowerMachine commited on
Commit
103b431
·
verified ·
1 Parent(s): 79f63e4

KHTST v9.1 — NÚCLEOS CYTHON+C PUBLICADOS: nucleos.pyx + nucleos.c + .so agora no repo (allow_patterns corrigido — v9 omitia os artefatos acelerados); Teo 19.25 verificado (Δw=0, ΔEQ=8.9e-16); suites v6/v7/v9 verdes (113 ✓); estado fase-v9 gate-aprovado preservado — sem novo treino (Retreino v9)

Browse files
.gitattributes CHANGED
@@ -34,3 +34,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  graficos/graf_ram.png filter=lfs diff=lfs merge=lfs -text
 
 
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  graficos/graf_ram.png filter=lfs diff=lfs merge=lfs -text
37
+ src/khtst/acelerado/nucleos.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -169,6 +169,17 @@ python3 scripts/08_graficos_card.py # gráficos + gates
169
  python3 scripts/06_publicar_hf.py # commit único (gate bloqueia estados)
170
  ```
171
 
 
 
 
 
 
 
 
 
 
 
 
172
  ## Estrutura
173
 
174
  `src/khtst/` — núcleo, percepção (atenção/microunidades/moe/vit_lra),
 
169
  python3 scripts/06_publicar_hf.py # commit único (gate bloqueia estados)
170
  ```
171
 
172
+ **Núcleos acelerados (Cython+C):** o repo inclui `nucleos.pyx` (fonte),
173
+ `nucleos.c` (C gerado) e o binário pré-compilado
174
+ `nucleos.cpython-312-x86_64-linux-gnu.so`. Sem binário compatível, recompile
175
+ ou use o fallback puro-torch (semântica idêntica, Teo 19.25):
176
+
177
+ ```bash
178
+ cd src/khtst/acelerado && python3 setup.py build_ext --inplace
179
+ python3 -c "from khtst.acelerado import status; print(status())"
180
+ # {'backend': 'cython_c', 'cython_disponivel': True}
181
+ ```
182
+
183
  ## Estrutura
184
 
185
  `src/khtst/` — núcleo, percepção (atenção/microunidades/moe/vit_lra),
scripts/06_publicar_hf.py CHANGED
@@ -108,7 +108,9 @@ def auditoria_segredos() -> list[str]:
108
  suspeitos = []
109
  for raiz, dirs, arquivos in os.walk(STAGE):
110
  for a in arquivos:
111
- if not a.endswith((".json", ".md", ".py", ".txt", ".yaml", ".yml")):
 
 
112
  continue
113
  caminho = os.path.join(raiz, a)
114
  try:
@@ -143,17 +145,23 @@ def main():
143
  api.create_repo(args.repo, repo_type="model", exist_ok=True, private=False)
144
 
145
  # PUBLICAÇÃO ÚNICA E COMPLETA: delete_patterns=["*"] remove no MESMO commit
146
- # qualquer arquivo antigo — nada de uploads parciais em sequência
 
 
 
 
147
  api.upload_folder(
148
  folder_path=STAGE, repo_id=args.repo, repo_type="model",
149
- commit_message="KHTST v9 — ESTADO INTEGRAL + AUTORREGULAÇÃO: snapshot fiel "
150
- "(modelo+roteador S-SOM+orquestrador, Teos 20.1–20.2), gate "
151
- "de fase com rollback (Teo 20.3), CIAR no lr (Teos 20.4–20.5); "
152
- "bug de persistência do v8 corrigido; estados antigos apagados; "
153
- "publicação condicionada ao gate vs AURORA",
 
154
  delete_patterns=["*"],
155
  allow_patterns=["*.py", "*.md", "*.json", "*.yaml", "*.yml",
156
- "*.txt", "*.png", "*.safetensors", "LICENSE*"])
 
157
  print("✓ PUBLICAÇÃO ÚNICA COMPLETA (1 commit; antigos removidos "
158
  "atomicamente)")
159
 
 
108
  suspeitos = []
109
  for raiz, dirs, arquivos in os.walk(STAGE):
110
  for a in arquivos:
111
+ # v9.1: .pyx e .c são texto e também são auditados
112
+ if not a.endswith((".json", ".md", ".py", ".txt", ".yaml", ".yml",
113
+ ".pyx", ".c")):
114
  continue
115
  caminho = os.path.join(raiz, a)
116
  try:
 
145
  api.create_repo(args.repo, repo_type="model", exist_ok=True, private=False)
146
 
147
  # PUBLICAÇÃO ÚNICA E COMPLETA: delete_patterns=["*"] remove no MESMO commit
148
+ # qualquer arquivo antigo — nada de uploads parciais em sequência.
149
+ # v9.1: allow_patterns agora INCLUI os artefatos do núcleo acelerado
150
+ # (Cython+C): *.pyx (fonte), *.c (C gerado) e *.so (binário pré-compilado
151
+ # cpython-312 linux x86_64) — na v9 o padrão omitia esses arquivos e o
152
+ # aprimoramento Cython/C++ não foi publicado (corrigido).
153
  api.upload_folder(
154
  folder_path=STAGE, repo_id=args.repo, repo_type="model",
155
+ commit_message="KHTST v9.1 — NÚCLEOS CYTHON+C PUBLICADOS: nucleos.pyx + "
156
+ "nucleos.c + .so agora no repo (allow_patterns corrigido — "
157
+ "v9 omitia os artefatos acelerados); Teo 19.25 verificado "
158
+ "(Δw=0, ΔEQ=8.9e-16); suites v6/v7/v9 verdes (113 ✓); "
159
+ "estado fase-v9 gate-aprovado preservado — sem novo treino "
160
+ "(Retreino v9)",
161
  delete_patterns=["*"],
162
  allow_patterns=["*.py", "*.md", "*.json", "*.yaml", "*.yml",
163
+ "*.txt", "*.png", "*.safetensors", "*.pyx", "*.c",
164
+ "*.so", "LICENSE*"])
165
  print("✓ PUBLICAÇÃO ÚNICA COMPLETA (1 commit; antigos removidos "
166
  "atomicamente)")
167
 
src/khtst/acelerado/nucleos.c ADDED
The diff for this file is too large to render. See raw diff
 
src/khtst/acelerado/nucleos.cpython-312-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9bc83dceec2d35965f45aa075a18d5c4180816d4eeaa0b608c9b28c4995db1d3
3
+ size 1325544
src/khtst/acelerado/nucleos.pyx ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Núcleos acelerados KHTST — Cython + C (v8, requisito de reescrita).
3
+
4
+ Hot-paths selecionados por PERFIL (onde o custo é laço Python, não GEMM):
5
+ 1. som_atualizar_lote — laço de Kohonen sequencial do roteador S-SOM
6
+ (O(B) iterações Python por passo de treino → C);
7
+ 2. contagens_entropia — contagens de contexto + entropia H e fator de
8
+ punição (eq. 10.8/10.9) por TOKEN GERADO (O(|ctx|) Python → C).
9
+
10
+ Teorema 19.25 (equivalência): cada núcleo C reproduz a SEMÂNTICA SEQUENCIAL
11
+ exata do laço original (mesma ordem de atualizações — Robbins–Monro depende
12
+ da ordem); o ganho é o overhead do interpretador: O(B) e O(T) operações
13
+ Python → 1 chamada C. Erro numérico = 0 (mesma aritmética em double).
14
+ """
15
+ # cython: language_level=3, boundscheck=False, wraparound=False, cdivision=True
16
+
17
+ import numpy as np
18
+ cimport numpy as cnp
19
+ cimport cython
20
+ from libc.math cimport exp, log
21
+
22
+ cnp.import_array()
23
+
24
+
25
+ def som_atualizar_lote(double[:, ::1] w, double[:, ::1] v,
26
+ double[::1] hit_ema, double[:, ::1] z,
27
+ long[::1] rotulos, double eta0,
28
+ double lambda_sup, long n_amostras):
29
+ """Kohonen + CE supervisionada (eq. 6.2) — SEMÂNTICA EXATA do laço do
30
+ RoteadorSSOM.atualizar. Atualiza w/v/hit_ema IN-PLACE; devolve (EQ, n)."""
31
+ cdef Py_ssize_t B = z.shape[0]
32
+ cdef Py_ssize_t K = w.shape[0]
33
+ cdef Py_ssize_t d = w.shape[1]
34
+ cdef Py_ssize_t C = v.shape[1]
35
+ cdef double eq_soma = 0.0
36
+ cdef Py_ssize_t i, j, c, t_arg
37
+ cdef double dist, melhor, eta, soma_p, acc
38
+ cdef double onehot, p_val
39
+ for i in range(B):
40
+ n_amostras += 1
41
+ # BMU
42
+ melhor = 1e300
43
+ c = 0
44
+ for j in range(K):
45
+ dist = 0.0
46
+ for t in range(d):
47
+ dist += (z[i, t] - w[j, t]) * (z[i, t] - w[j, t])
48
+ if dist < melhor:
49
+ melhor = dist
50
+ c = j
51
+ eq_soma += melhor
52
+ eta = eta0 / (1.0 + 0.001 * <double>n_amostras)
53
+ for t in range(d):
54
+ w[c, t] += eta * (z[i, t] - w[c, t])
55
+ # softmax de v[c] + update supervisionado (eq. 6.2)
56
+ soma_p = 0.0
57
+ for t in range(C):
58
+ soma_p += exp(v[c, t])
59
+ if soma_p <= 0.0:
60
+ soma_p = 1e-12
61
+ for t in range(C):
62
+ p_val = exp(v[c, t]) / soma_p
63
+ onehot = 1.0 if t == rotulos[i] else 0.0
64
+ v[c, t] += (lambda_sup * 0.1) * (onehot - p_val)
65
+ # hit EMA
66
+ for j in range(K):
67
+ hit_ema[j] *= 0.92
68
+ hit_ema[c] += 0.08
69
+ return eq_soma / max(B, 1), n_amostras
70
+
71
+
72
+ def contagens_entropia(long[::1] contextos, long vocab, double h_max,
73
+ double punicao_base):
74
+ """Contagens + entropia H_ctx + fator min(1, H/h_max) (eq. 10.8/10.9).
75
+ Devolve (contagens, H_ctx, fator)."""
76
+ cdef Py_ssize_t T = contextos.shape[0]
77
+ cdef cnp.ndarray[cnp.int64_t, ndim=1] cont = np.zeros(vocab, dtype=np.int64)
78
+ cdef long[::1] cont_v = cont
79
+ cdef Py_ssize_t i
80
+ cdef double p_nz_soma = 0.0, h = 0.0
81
+ for i in range(T):
82
+ if 0 <= contextos[i] < vocab:
83
+ cont_v[contextos[i]] += 1
84
+ for i in range(vocab):
85
+ if cont_v[i] > 0:
86
+ p_nz_soma += <double>cont_v[i]
87
+ for i in range(vocab):
88
+ if cont_v[i] > 0 and p_nz_soma > 0:
89
+ h -= (<double>cont_v[i] / p_nz_soma) * log(<double>cont_v[i] / p_nz_soma + 1e-8)
90
+ cdef double fator = min(1.0, h / max(h_max, 1e-6))
91
+ return cont, h, fator