laboratório v0.22-lab: auditoria executável, correção do laço de regulação (lab-A1, opt-in) e medições em dados reais (wiki PT-BR + digits)
Browse filesGates L1..L7 verdes (7/7). Inventário: 20 componentes presentes, 36 ausentes na branch publicada. Bancadas: MAPA (absoluto/relativo/histerese), laço de regulação (tautologia × correção), LeJEPA-lab f64 (T-L7/T-L8/G3/T-L9 com controles não-vácuos), SOM EQ/TE Moore/Mahalanobis. Docs: ESTRUTURA, AUTOCRITICA, r-65, equivalências, patches v0.22. Token não incluído (higiene L7).
This view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +2 -0
- laboratorio/.gitattributes +370 -0
- laboratorio/AUTOCRITICA.md +219 -0
- laboratorio/Cargo.lock +1813 -0
- laboratorio/Cargo.toml +54 -0
- laboratorio/ESTRUTURA.md +95 -0
- laboratorio/LICENSE +1 -0
- laboratorio/README.md +75 -0
- laboratorio/arquivo_split_v100/LEIA-ME.md +12 -0
- laboratorio/arquivo_split_v100/checkpoint.rs +353 -0
- laboratorio/arquivo_split_v100/jepa/mascaras.rs +173 -0
- laboratorio/arquivo_split_v100/jepa/mod.rs +61 -0
- laboratorio/arquivo_split_v100/jepa/nucleo.rs +211 -0
- laboratorio/arquivo_split_v100/jepa/patches.rs +150 -0
- laboratorio/arquivo_split_v100/jepa/replay_ssm.rs +107 -0
- laboratorio/arquivo_split_v100/jepa/sonic_moe.rs +155 -0
- laboratorio/arquivo_split_v100/jepa/testes.rs +212 -0
- laboratorio/arquivo_split_v100/jepa/variantes.rs +476 -0
- laboratorio/arquivo_split_v100/moe_redirecionavel/atencao.rs +63 -0
- laboratorio/arquivo_split_v100/moe_redirecionavel/mod.rs +57 -0
- laboratorio/arquivo_split_v100/moe_redirecionavel/nucleo.rs +431 -0
- laboratorio/arquivo_split_v100/moe_redirecionavel/teste_integrado.rs +26 -0
- laboratorio/arquivo_split_v100/moe_redirecionavel/testes.rs +209 -0
- laboratorio/arquivo_split_v100/moe_redirecionavel/treino.rs +463 -0
- laboratorio/arquivo_split_v100/pensamento/combinador.rs +73 -0
- laboratorio/arquivo_split_v100/pensamento/mod.rs +71 -0
- laboratorio/arquivo_split_v100/pensamento/motor.rs +549 -0
- laboratorio/arquivo_split_v100/pensamento/quebra_cabeca.rs +233 -0
- laboratorio/arquivo_split_v100/pensamento/testes.rs +303 -0
- laboratorio/arquivo_split_v100/python.rs +0 -0
- laboratorio/arquivo_split_v100/python/calibracao.rs +134 -0
- laboratorio/arquivo_split_v100/python/demos_qwen.rs +359 -0
- laboratorio/arquivo_split_v100/python/fnh_arvore.rs +344 -0
- laboratorio/arquivo_split_v100/python/jepa_treinos.rs +251 -0
- laboratorio/arquivo_split_v100/python/mod.rs +145 -0
- laboratorio/arquivo_split_v100/python/moe.rs +190 -0
- laboratorio/arquivo_split_v100/python/nlp_nlg.rs +69 -0
- laboratorio/arquivo_split_v100/python/nucleo.rs +239 -0
- laboratorio/arquivo_split_v100/python/pensamento_demos.rs +367 -0
- laboratorio/arquivo_split_v100/python/som.rs +180 -0
- laboratorio/arquivo_split_v100/python/treino_fases.rs +228 -0
- laboratorio/arquivo_split_v100/tipos.rs +209 -0
- laboratorio/build.rs +6 -0
- laboratorio/configs/base_laboratorio.json +70 -0
- laboratorio/configs/base_rust.json +106 -0
- laboratorio/configs/base_rust_b800.json +106 -0
- laboratorio/configs/base_rust_gumbel.json +106 -0
- laboratorio/configs/base_rust_gumbel800.json +106 -0
- laboratorio/dados/bpe.json +0 -0
- laboratorio/dados/shard_treino.jsonl +0 -0
.gitattributes
CHANGED
|
@@ -368,3 +368,5 @@ target/release/libkhtst_rust.rlib filter=lfs diff=lfs merge=lfs -text
|
|
| 368 |
target/wheels/khtst_rust-0.6.0-cp310-abi3-manylinux_2_39_x86_64.whl filter=lfs diff=lfs merge=lfs -text
|
| 369 |
target/wheels/khtst_rust-0.7.0-cp310-abi3-manylinux_2_39_x86_64.whl filter=lfs diff=lfs merge=lfs -text
|
| 370 |
resultados/gerador_aritmetica.json filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 368 |
target/wheels/khtst_rust-0.6.0-cp310-abi3-manylinux_2_39_x86_64.whl filter=lfs diff=lfs merge=lfs -text
|
| 369 |
target/wheels/khtst_rust-0.7.0-cp310-abi3-manylinux_2_39_x86_64.whl filter=lfs diff=lfs merge=lfs -text
|
| 370 |
resultados/gerador_aritmetica.json filter=lfs diff=lfs merge=lfs -text
|
| 371 |
+
laboratorio/resultados/figuras/bancada_jepa.png filter=lfs diff=lfs merge=lfs -text
|
| 372 |
+
laboratorio/resultados/figuras/bancada_limiar.png filter=lfs diff=lfs merge=lfs -text
|
laboratorio/.gitattributes
ADDED
|
@@ -0,0 +1,370 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip 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 |
+
resultados/gerador_conceitos.json filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
resultados/tokenizador_conceitos.json filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
target/release/build/ahash-83fe43707d427afc/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
target/release/build/ahash-83fe43707d427afc/build_script_build-83fe43707d427afc filter=lfs diff=lfs merge=lfs -text
|
| 40 |
+
target/release/build/anyhow-c133e46889c468bb/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
target/release/build/anyhow-c133e46889c468bb/build_script_build-c133e46889c468bb filter=lfs diff=lfs merge=lfs -text
|
| 42 |
+
target/release/build/crc32fast-465b5d165116b989/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 43 |
+
target/release/build/crc32fast-465b5d165116b989/build_script_build-465b5d165116b989 filter=lfs diff=lfs merge=lfs -text
|
| 44 |
+
target/release/build/crossbeam-deque-e1955f67cf9b20db/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 45 |
+
target/release/build/crossbeam-deque-e1955f67cf9b20db/build_script_build-e1955f67cf9b20db filter=lfs diff=lfs merge=lfs -text
|
| 46 |
+
target/release/build/crossbeam-epoch-dd3bd9e18c79c031/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 47 |
+
target/release/build/crossbeam-epoch-dd3bd9e18c79c031/build_script_build-dd3bd9e18c79c031 filter=lfs diff=lfs merge=lfs -text
|
| 48 |
+
target/release/build/crossbeam-utils-d60d63eb60bf7c48/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 49 |
+
target/release/build/crossbeam-utils-d60d63eb60bf7c48/build_script_build-d60d63eb60bf7c48 filter=lfs diff=lfs merge=lfs -text
|
| 50 |
+
target/release/build/esaxx-rs-f1aa57a0937aea82/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 51 |
+
target/release/build/esaxx-rs-f1aa57a0937aea82/build_script_build-f1aa57a0937aea82 filter=lfs diff=lfs merge=lfs -text
|
| 52 |
+
target/release/build/getrandom-a0ce2225bd8ad810/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 53 |
+
target/release/build/getrandom-a0ce2225bd8ad810/build_script_build-a0ce2225bd8ad810 filter=lfs diff=lfs merge=lfs -text
|
| 54 |
+
target/release/build/getrandom-b59cf53baa4733ea/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 55 |
+
target/release/build/getrandom-b59cf53baa4733ea/build_script_build-b59cf53baa4733ea filter=lfs diff=lfs merge=lfs -text
|
| 56 |
+
target/release/build/khtst-rust-1c61e50109ccb8b3/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 57 |
+
target/release/build/khtst-rust-1c61e50109ccb8b3/build_script_build-1c61e50109ccb8b3 filter=lfs diff=lfs merge=lfs -text
|
| 58 |
+
target/release/build/khtst-rust-9b131ce6630f5e9f/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 59 |
+
target/release/build/khtst-rust-9b131ce6630f5e9f/build_script_build-9b131ce6630f5e9f filter=lfs diff=lfs merge=lfs -text
|
| 60 |
+
target/release/build/libc-cda79ff38737910e/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 61 |
+
target/release/build/libc-cda79ff38737910e/build_script_build-cda79ff38737910e filter=lfs diff=lfs merge=lfs -text
|
| 62 |
+
target/release/build/libm-0eaa3a21ce902dcb/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 63 |
+
target/release/build/libm-0eaa3a21ce902dcb/build_script_build-0eaa3a21ce902dcb filter=lfs diff=lfs merge=lfs -text
|
| 64 |
+
target/release/build/matrixmultiply-bd474dd77cb4d223/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 65 |
+
target/release/build/matrixmultiply-bd474dd77cb4d223/build_script_build-bd474dd77cb4d223 filter=lfs diff=lfs merge=lfs -text
|
| 66 |
+
target/release/build/memoffset-5448580e27d366d0/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 67 |
+
target/release/build/memoffset-5448580e27d366d0/build_script_build-5448580e27d366d0 filter=lfs diff=lfs merge=lfs -text
|
| 68 |
+
target/release/build/num-traits-278da1b462e148db/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 69 |
+
target/release/build/num-traits-278da1b462e148db/build_script_build-278da1b462e148db filter=lfs diff=lfs merge=lfs -text
|
| 70 |
+
target/release/build/onig_sys-0fd7e148290bb4ae/out/532c78c9447d119f-regcomp.o filter=lfs diff=lfs merge=lfs -text
|
| 71 |
+
target/release/build/onig_sys-0fd7e148290bb4ae/out/532c78c9447d119f-regparse.o filter=lfs diff=lfs merge=lfs -text
|
| 72 |
+
target/release/build/onig_sys-0fd7e148290bb4ae/out/532c78c9447d119f-unicode.o filter=lfs diff=lfs merge=lfs -text
|
| 73 |
+
target/release/build/onig_sys-0fd7e148290bb4ae/out/libonig.a filter=lfs diff=lfs merge=lfs -text
|
| 74 |
+
target/release/build/onig_sys-87e9df94ef1c8246/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 75 |
+
target/release/build/onig_sys-87e9df94ef1c8246/build_script_build-87e9df94ef1c8246 filter=lfs diff=lfs merge=lfs -text
|
| 76 |
+
target/release/build/paste-3fe37c2f0dbe8869/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 77 |
+
target/release/build/paste-3fe37c2f0dbe8869/build_script_build-3fe37c2f0dbe8869 filter=lfs diff=lfs merge=lfs -text
|
| 78 |
+
target/release/build/proc-macro2-ec1fa8d2755b1122/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 79 |
+
target/release/build/proc-macro2-ec1fa8d2755b1122/build_script_build-ec1fa8d2755b1122 filter=lfs diff=lfs merge=lfs -text
|
| 80 |
+
target/release/build/pulp-a8d2cd4c62f4f66c/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 81 |
+
target/release/build/pulp-a8d2cd4c62f4f66c/build_script_build-a8d2cd4c62f4f66c filter=lfs diff=lfs merge=lfs -text
|
| 82 |
+
target/release/build/pyo3-33b58f96cbfa0a45/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 83 |
+
target/release/build/pyo3-33b58f96cbfa0a45/build_script_build-33b58f96cbfa0a45 filter=lfs diff=lfs merge=lfs -text
|
| 84 |
+
target/release/build/pyo3-a85d60f9400a5558/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 85 |
+
target/release/build/pyo3-a85d60f9400a5558/build_script_build-a85d60f9400a5558 filter=lfs diff=lfs merge=lfs -text
|
| 86 |
+
target/release/build/pyo3-build-config-b4dc14c4de1196c9/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 87 |
+
target/release/build/pyo3-build-config-b4dc14c4de1196c9/build_script_build-b4dc14c4de1196c9 filter=lfs diff=lfs merge=lfs -text
|
| 88 |
+
target/release/build/pyo3-build-config-e72b3918ac6bcb4f/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 89 |
+
target/release/build/pyo3-build-config-e72b3918ac6bcb4f/build_script_build-e72b3918ac6bcb4f filter=lfs diff=lfs merge=lfs -text
|
| 90 |
+
target/release/build/pyo3-ffi-71b4547d70909fe1/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 91 |
+
target/release/build/pyo3-ffi-71b4547d70909fe1/build_script_build-71b4547d70909fe1 filter=lfs diff=lfs merge=lfs -text
|
| 92 |
+
target/release/build/pyo3-ffi-a8eeb2e5f87885d4/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 93 |
+
target/release/build/pyo3-ffi-a8eeb2e5f87885d4/build_script_build-a8eeb2e5f87885d4 filter=lfs diff=lfs merge=lfs -text
|
| 94 |
+
target/release/build/pyo3-macros-backend-e40371485de2549a/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 95 |
+
target/release/build/pyo3-macros-backend-e40371485de2549a/build_script_build-e40371485de2549a filter=lfs diff=lfs merge=lfs -text
|
| 96 |
+
target/release/build/pyo3-macros-backend-fa3b3939dff2c14c/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 97 |
+
target/release/build/pyo3-macros-backend-fa3b3939dff2c14c/build_script_build-fa3b3939dff2c14c filter=lfs diff=lfs merge=lfs -text
|
| 98 |
+
target/release/build/quote-2165c0071fef8d8b/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 99 |
+
target/release/build/quote-2165c0071fef8d8b/build_script_build-2165c0071fef8d8b filter=lfs diff=lfs merge=lfs -text
|
| 100 |
+
target/release/build/rayon-core-8fac0e817c725ea3/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 101 |
+
target/release/build/rayon-core-8fac0e817c725ea3/build_script_build-8fac0e817c725ea3 filter=lfs diff=lfs merge=lfs -text
|
| 102 |
+
target/release/build/rustix-3c55faff44887a3b/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 103 |
+
target/release/build/rustix-3c55faff44887a3b/build_script_build-3c55faff44887a3b filter=lfs diff=lfs merge=lfs -text
|
| 104 |
+
target/release/build/rustversion-2c0c5f4841a48194/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 105 |
+
target/release/build/rustversion-2c0c5f4841a48194/build_script_build-2c0c5f4841a48194 filter=lfs diff=lfs merge=lfs -text
|
| 106 |
+
target/release/build/serde-28b63f47db6fcec9/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 107 |
+
target/release/build/serde-28b63f47db6fcec9/build_script_build-28b63f47db6fcec9 filter=lfs diff=lfs merge=lfs -text
|
| 108 |
+
target/release/build/serde_core-92a2e2dcc440674f/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 109 |
+
target/release/build/serde_core-92a2e2dcc440674f/build_script_build-92a2e2dcc440674f filter=lfs diff=lfs merge=lfs -text
|
| 110 |
+
target/release/build/serde_json-880e74b6dc64e5b3/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 111 |
+
target/release/build/serde_json-880e74b6dc64e5b3/build_script_build-880e74b6dc64e5b3 filter=lfs diff=lfs merge=lfs -text
|
| 112 |
+
target/release/build/syn-a9cf107caca67a56/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 113 |
+
target/release/build/syn-a9cf107caca67a56/build_script_build-a9cf107caca67a56 filter=lfs diff=lfs merge=lfs -text
|
| 114 |
+
target/release/build/target-lexicon-3648bc0fe04f40ce/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 115 |
+
target/release/build/target-lexicon-3648bc0fe04f40ce/build_script_build-3648bc0fe04f40ce filter=lfs diff=lfs merge=lfs -text
|
| 116 |
+
target/release/build/thiserror-5c9142bad2887cbd/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 117 |
+
target/release/build/thiserror-5c9142bad2887cbd/build_script_build-5c9142bad2887cbd filter=lfs diff=lfs merge=lfs -text
|
| 118 |
+
target/release/build/zerocopy-fc0886eb7471bb11/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 119 |
+
target/release/build/zerocopy-fc0886eb7471bb11/build_script_build-fc0886eb7471bb11 filter=lfs diff=lfs merge=lfs -text
|
| 120 |
+
target/release/build/zmij-a75537cd80fe769f/build-script-build filter=lfs diff=lfs merge=lfs -text
|
| 121 |
+
target/release/build/zmij-a75537cd80fe769f/build_script_build-a75537cd80fe769f filter=lfs diff=lfs merge=lfs -text
|
| 122 |
+
target/release/deps/khtst_rust-ad0b08449c30cde6 filter=lfs diff=lfs merge=lfs -text
|
| 123 |
+
target/release/deps/khtst_rust-f02b0491b8d999f8 filter=lfs diff=lfs merge=lfs -text
|
| 124 |
+
target/release/deps/libahash-1239384bf8e0b488.rlib filter=lfs diff=lfs merge=lfs -text
|
| 125 |
+
target/release/deps/libahash-1239384bf8e0b488.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 126 |
+
target/release/deps/libaho_corasick-9c569f153f8a1f1f.rlib filter=lfs diff=lfs merge=lfs -text
|
| 127 |
+
target/release/deps/libaho_corasick-9c569f153f8a1f1f.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 128 |
+
target/release/deps/liballocator_api2-403fd32973be6ae7.rlib filter=lfs diff=lfs merge=lfs -text
|
| 129 |
+
target/release/deps/liballocator_api2-403fd32973be6ae7.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 130 |
+
target/release/deps/libanyhow-04c9675e4b0fe7fd.rlib filter=lfs diff=lfs merge=lfs -text
|
| 131 |
+
target/release/deps/libanyhow-04c9675e4b0fe7fd.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 132 |
+
target/release/deps/libarc_swap-9a54241e9f9fcb4f.rlib filter=lfs diff=lfs merge=lfs -text
|
| 133 |
+
target/release/deps/libarc_swap-9a54241e9f9fcb4f.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 134 |
+
target/release/deps/libautocfg-a37330238752ec3b.rlib filter=lfs diff=lfs merge=lfs -text
|
| 135 |
+
target/release/deps/libbase64-7a0bdfb5a661f6ff.rlib filter=lfs diff=lfs merge=lfs -text
|
| 136 |
+
target/release/deps/libbase64-7a0bdfb5a661f6ff.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 137 |
+
target/release/deps/libbitflags-ec102962704ab1c9.rlib filter=lfs diff=lfs merge=lfs -text
|
| 138 |
+
target/release/deps/libbitflags-ec102962704ab1c9.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 139 |
+
target/release/deps/libbuilt-2491b390afab542e.rlib filter=lfs diff=lfs merge=lfs -text
|
| 140 |
+
target/release/deps/libbuilt-2491b390afab542e.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 141 |
+
target/release/deps/libbytemuck-23a688db2fb1a21e.rlib filter=lfs diff=lfs merge=lfs -text
|
| 142 |
+
target/release/deps/libbytemuck-23a688db2fb1a21e.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 143 |
+
target/release/deps/libbyteorder-f4533d6e39b2fd29.rlib filter=lfs diff=lfs merge=lfs -text
|
| 144 |
+
target/release/deps/libbyteorder-f4533d6e39b2fd29.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 145 |
+
target/release/deps/libcandle_core-c7894ac84a719255.rlib filter=lfs diff=lfs merge=lfs -text
|
| 146 |
+
target/release/deps/libcandle_core-c7894ac84a719255.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 147 |
+
target/release/deps/libcandle_nn-296be1f09a897e88.rlib filter=lfs diff=lfs merge=lfs -text
|
| 148 |
+
target/release/deps/libcandle_nn-296be1f09a897e88.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 149 |
+
target/release/deps/libcc-cf6777f38d824725.rlib filter=lfs diff=lfs merge=lfs -text
|
| 150 |
+
target/release/deps/libcc-cf6777f38d824725.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 151 |
+
target/release/deps/libcompact_str-7ac41cd2fb3fc39a.rlib filter=lfs diff=lfs merge=lfs -text
|
| 152 |
+
target/release/deps/libcompact_str-7ac41cd2fb3fc39a.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 153 |
+
target/release/deps/libcrossbeam_channel-bc96073f9b9ac85c.rlib filter=lfs diff=lfs merge=lfs -text
|
| 154 |
+
target/release/deps/libcrossbeam_channel-bc96073f9b9ac85c.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 155 |
+
target/release/deps/libcrossbeam_deque-3dc832c237a8f156.rlib filter=lfs diff=lfs merge=lfs -text
|
| 156 |
+
target/release/deps/libcrossbeam_deque-3dc832c237a8f156.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 157 |
+
target/release/deps/libcrossbeam_epoch-e6e776959b0552fa.rlib filter=lfs diff=lfs merge=lfs -text
|
| 158 |
+
target/release/deps/libcrossbeam_epoch-e6e776959b0552fa.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 159 |
+
target/release/deps/libcrossbeam_utils-d347ad423d0a1960.rlib filter=lfs diff=lfs merge=lfs -text
|
| 160 |
+
target/release/deps/libcrossbeam_utils-d347ad423d0a1960.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 161 |
+
target/release/deps/libdarling_core-3294eb772aa14eae.rlib filter=lfs diff=lfs merge=lfs -text
|
| 162 |
+
target/release/deps/libdarling_core-3294eb772aa14eae.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 163 |
+
target/release/deps/libdary_heap-49c3eec03a7a27c2.rlib filter=lfs diff=lfs merge=lfs -text
|
| 164 |
+
target/release/deps/libdary_heap-49c3eec03a7a27c2.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 165 |
+
target/release/deps/libderive_builder_core-723835328ba4eff3.rlib filter=lfs diff=lfs merge=lfs -text
|
| 166 |
+
target/release/deps/libderive_builder_core-723835328ba4eff3.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 167 |
+
target/release/deps/libdyn_stack-98498042e26e30b1.rlib filter=lfs diff=lfs merge=lfs -text
|
| 168 |
+
target/release/deps/libdyn_stack-98498042e26e30b1.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 169 |
+
target/release/deps/libeither-b381e519513ad3f3.rlib filter=lfs diff=lfs merge=lfs -text
|
| 170 |
+
target/release/deps/libeither-b381e519513ad3f3.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 171 |
+
target/release/deps/libfastrand-4256e106befb5387.rlib filter=lfs diff=lfs merge=lfs -text
|
| 172 |
+
target/release/deps/libfastrand-4256e106befb5387.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 173 |
+
target/release/deps/libfind_msvc_tools-d4d852696ef06732.rlib filter=lfs diff=lfs merge=lfs -text
|
| 174 |
+
target/release/deps/libfloat8-a9b5bdd4c7dcc206.rlib filter=lfs diff=lfs merge=lfs -text
|
| 175 |
+
target/release/deps/libfloat8-a9b5bdd4c7dcc206.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 176 |
+
target/release/deps/libfoldhash-732ec22ff2993426.rlib filter=lfs diff=lfs merge=lfs -text
|
| 177 |
+
target/release/deps/libfutures_channel-3c29037c78e41cd8.rlib filter=lfs diff=lfs merge=lfs -text
|
| 178 |
+
target/release/deps/libfutures_channel-3c29037c78e41cd8.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 179 |
+
target/release/deps/libfutures_executor-b80971572de7b0fe.rlib filter=lfs diff=lfs merge=lfs -text
|
| 180 |
+
target/release/deps/libfutures_task-fece3fcddbc91fb5.rlib filter=lfs diff=lfs merge=lfs -text
|
| 181 |
+
target/release/deps/libfutures_task-fece3fcddbc91fb5.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 182 |
+
target/release/deps/libfutures_util-456983c566aa7c23.rlib filter=lfs diff=lfs merge=lfs -text
|
| 183 |
+
target/release/deps/libfutures_util-456983c566aa7c23.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 184 |
+
target/release/deps/libgemm_c32-8e52f24dcc852200.rlib filter=lfs diff=lfs merge=lfs -text
|
| 185 |
+
target/release/deps/libgemm_c32-8e52f24dcc852200.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 186 |
+
target/release/deps/libgemm_c64-bc21de9a30c85187.rlib filter=lfs diff=lfs merge=lfs -text
|
| 187 |
+
target/release/deps/libgemm_c64-bc21de9a30c85187.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 188 |
+
target/release/deps/libgemm_common-4aecfbf04a1ae322.rlib filter=lfs diff=lfs merge=lfs -text
|
| 189 |
+
target/release/deps/libgemm_common-4aecfbf04a1ae322.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 190 |
+
target/release/deps/libgemm_f16-7b2bad80914b2060.rlib filter=lfs diff=lfs merge=lfs -text
|
| 191 |
+
target/release/deps/libgemm_f16-7b2bad80914b2060.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 192 |
+
target/release/deps/libgemm_f32-847e933e950448e7.rlib filter=lfs diff=lfs merge=lfs -text
|
| 193 |
+
target/release/deps/libgemm_f32-847e933e950448e7.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 194 |
+
target/release/deps/libgemm_f64-6569e07fe3a6827a.rlib filter=lfs diff=lfs merge=lfs -text
|
| 195 |
+
target/release/deps/libgemm_f64-6569e07fe3a6827a.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 196 |
+
target/release/deps/libgetrandom-6d031a9bcac2e9f6.rlib filter=lfs diff=lfs merge=lfs -text
|
| 197 |
+
target/release/deps/libgetrandom-898236ee65570365.rlib filter=lfs diff=lfs merge=lfs -text
|
| 198 |
+
target/release/deps/libhalf-f2da7ee38ed1ba40.rlib filter=lfs diff=lfs merge=lfs -text
|
| 199 |
+
target/release/deps/libhalf-f2da7ee38ed1ba40.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 200 |
+
target/release/deps/libhashbrown-cb6d85574ed0ab41.rlib filter=lfs diff=lfs merge=lfs -text
|
| 201 |
+
target/release/deps/libhashbrown-cb6d85574ed0ab41.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 202 |
+
target/release/deps/libhashbrown-f8013dccd2499316.rlib filter=lfs diff=lfs merge=lfs -text
|
| 203 |
+
target/release/deps/libhashbrown-f8013dccd2499316.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 204 |
+
target/release/deps/libheck-819adfa2f80b239e.rlib filter=lfs diff=lfs merge=lfs -text
|
| 205 |
+
target/release/deps/libindexmap-85569621185bcbfa.rlib filter=lfs diff=lfs merge=lfs -text
|
| 206 |
+
target/release/deps/libindexmap-85569621185bcbfa.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 207 |
+
target/release/deps/libitertools-158aa78af8eeb36d.rlib filter=lfs diff=lfs merge=lfs -text
|
| 208 |
+
target/release/deps/libitertools-158aa78af8eeb36d.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 209 |
+
target/release/deps/libkhtst_rust.rlib filter=lfs diff=lfs merge=lfs -text
|
| 210 |
+
target/release/deps/liblibc-34e983634f114512.rlib filter=lfs diff=lfs merge=lfs -text
|
| 211 |
+
target/release/deps/liblibc-34e983634f114512.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 212 |
+
target/release/deps/liblibm-6f21bd35f919340d.rlib filter=lfs diff=lfs merge=lfs -text
|
| 213 |
+
target/release/deps/liblibm-6f21bd35f919340d.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 214 |
+
target/release/deps/liblinux_raw_sys-b29eaaeae92cd74a.rlib filter=lfs diff=lfs merge=lfs -text
|
| 215 |
+
target/release/deps/liblinux_raw_sys-b29eaaeae92cd74a.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 216 |
+
target/release/deps/liblog-ae01615bfdda4fb3.rlib filter=lfs diff=lfs merge=lfs -text
|
| 217 |
+
target/release/deps/liblog-ae01615bfdda4fb3.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 218 |
+
target/release/deps/libmatrixmultiply-2144fe0ef1f0a94e.rlib filter=lfs diff=lfs merge=lfs -text
|
| 219 |
+
target/release/deps/libmatrixmultiply-2144fe0ef1f0a94e.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 220 |
+
target/release/deps/libmemchr-1327ba4db5966aa6.rlib filter=lfs diff=lfs merge=lfs -text
|
| 221 |
+
target/release/deps/libmemchr-1327ba4db5966aa6.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 222 |
+
target/release/deps/libmemmap2-99b77237eba3bfe3.rlib filter=lfs diff=lfs merge=lfs -text
|
| 223 |
+
target/release/deps/libmemmap2-99b77237eba3bfe3.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 224 |
+
target/release/deps/libminimal_lexical-325bc3dff105b620.rlib filter=lfs diff=lfs merge=lfs -text
|
| 225 |
+
target/release/deps/libminimal_lexical-325bc3dff105b620.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 226 |
+
target/release/deps/libmonostate-04574c1c38f3033c.rlib filter=lfs diff=lfs merge=lfs -text
|
| 227 |
+
target/release/deps/libmonostate-04574c1c38f3033c.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 228 |
+
target/release/deps/libndarray-4122255e939b68c7.rlib filter=lfs diff=lfs merge=lfs -text
|
| 229 |
+
target/release/deps/libndarray-4122255e939b68c7.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 230 |
+
target/release/deps/libnom-58cccbc0e4af3eff.rlib filter=lfs diff=lfs merge=lfs -text
|
| 231 |
+
target/release/deps/libnom-58cccbc0e4af3eff.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 232 |
+
target/release/deps/libnum_complex-14f7072ab28faa00.rlib filter=lfs diff=lfs merge=lfs -text
|
| 233 |
+
target/release/deps/libnum_complex-14f7072ab28faa00.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 234 |
+
target/release/deps/libnum_integer-96c1ae66ba4da6cd.rlib filter=lfs diff=lfs merge=lfs -text
|
| 235 |
+
target/release/deps/libnum_integer-96c1ae66ba4da6cd.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 236 |
+
target/release/deps/libnum_traits-64717d2b01611c30.rlib filter=lfs diff=lfs merge=lfs -text
|
| 237 |
+
target/release/deps/libnum_traits-64717d2b01611c30.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 238 |
+
target/release/deps/libnumpy-a34ba85ba073baff.rlib filter=lfs diff=lfs merge=lfs -text
|
| 239 |
+
target/release/deps/libnumpy-a34ba85ba073baff.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 240 |
+
target/release/deps/libnumpy-fcbc094b01af2e7f.rlib filter=lfs diff=lfs merge=lfs -text
|
| 241 |
+
target/release/deps/libnumpy-fcbc094b01af2e7f.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 242 |
+
target/release/deps/libonce_cell-092a5a354564873d.rlib filter=lfs diff=lfs merge=lfs -text
|
| 243 |
+
target/release/deps/libonce_cell-092a5a354564873d.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 244 |
+
target/release/deps/libonce_cell-1d0b9bf1c4babec6.rlib filter=lfs diff=lfs merge=lfs -text
|
| 245 |
+
target/release/deps/libonce_cell-1d0b9bf1c4babec6.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 246 |
+
target/release/deps/libonig-033e694079f8d894.rlib filter=lfs diff=lfs merge=lfs -text
|
| 247 |
+
target/release/deps/libonig-033e694079f8d894.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 248 |
+
target/release/deps/libonig_sys-637377a0e1421cfd.rlib filter=lfs diff=lfs merge=lfs -text
|
| 249 |
+
target/release/deps/libonig_sys-637377a0e1421cfd.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 250 |
+
target/release/deps/libpkg_config-1bcf4b49cdb82f89.rlib filter=lfs diff=lfs merge=lfs -text
|
| 251 |
+
target/release/deps/libppv_lite86-cd4c2ed2cefd17e5.rlib filter=lfs diff=lfs merge=lfs -text
|
| 252 |
+
target/release/deps/libppv_lite86-cd4c2ed2cefd17e5.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 253 |
+
target/release/deps/libproc_macro2-dae466aba027a5dd.rlib filter=lfs diff=lfs merge=lfs -text
|
| 254 |
+
target/release/deps/libproc_macro2-dae466aba027a5dd.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 255 |
+
target/release/deps/libpulp-af73edfb36811c3d.rlib filter=lfs diff=lfs merge=lfs -text
|
| 256 |
+
target/release/deps/libpulp-af73edfb36811c3d.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 257 |
+
target/release/deps/libpyo3-54a5729ee52c55da.rlib filter=lfs diff=lfs merge=lfs -text
|
| 258 |
+
target/release/deps/libpyo3-54a5729ee52c55da.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 259 |
+
target/release/deps/libpyo3-da9a906ae35181aa.rlib filter=lfs diff=lfs merge=lfs -text
|
| 260 |
+
target/release/deps/libpyo3-da9a906ae35181aa.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 261 |
+
target/release/deps/libpyo3_async_runtimes-d02a64b7f5142d3d.rlib filter=lfs diff=lfs merge=lfs -text
|
| 262 |
+
target/release/deps/libpyo3_async_runtimes-d02a64b7f5142d3d.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 263 |
+
target/release/deps/libpyo3_async_runtimes-ebe36f6963ea826b.rlib filter=lfs diff=lfs merge=lfs -text
|
| 264 |
+
target/release/deps/libpyo3_async_runtimes-ebe36f6963ea826b.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 265 |
+
target/release/deps/libpyo3_build_config-a60b839caa31d2c2.rlib filter=lfs diff=lfs merge=lfs -text
|
| 266 |
+
target/release/deps/libpyo3_build_config-a60b839caa31d2c2.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 267 |
+
target/release/deps/libpyo3_build_config-c03bf73aec6614ef.rlib filter=lfs diff=lfs merge=lfs -text
|
| 268 |
+
target/release/deps/libpyo3_build_config-c03bf73aec6614ef.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 269 |
+
target/release/deps/libpyo3_ffi-8b9a14b765161e18.rlib filter=lfs diff=lfs merge=lfs -text
|
| 270 |
+
target/release/deps/libpyo3_ffi-8b9a14b765161e18.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 271 |
+
target/release/deps/libpyo3_ffi-b0a4f805e7777b9c.rlib filter=lfs diff=lfs merge=lfs -text
|
| 272 |
+
target/release/deps/libpyo3_ffi-b0a4f805e7777b9c.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 273 |
+
target/release/deps/libpyo3_log-59ef075694aed336.rlib filter=lfs diff=lfs merge=lfs -text
|
| 274 |
+
target/release/deps/libpyo3_log-f1f61ec3bb287df9.rlib filter=lfs diff=lfs merge=lfs -text
|
| 275 |
+
target/release/deps/libpyo3_macros_backend-b6cebfaa749f5701.rlib filter=lfs diff=lfs merge=lfs -text
|
| 276 |
+
target/release/deps/libpyo3_macros_backend-b6cebfaa749f5701.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 277 |
+
target/release/deps/libpyo3_macros_backend-c3d78a70a11e7f3f.rlib filter=lfs diff=lfs merge=lfs -text
|
| 278 |
+
target/release/deps/libpyo3_macros_backend-c3d78a70a11e7f3f.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 279 |
+
target/release/deps/libpythonize-5e9e42961559132c.rlib filter=lfs diff=lfs merge=lfs -text
|
| 280 |
+
target/release/deps/libpythonize-5e9e42961559132c.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 281 |
+
target/release/deps/libpythonize-d82f642ebe84297a.rlib filter=lfs diff=lfs merge=lfs -text
|
| 282 |
+
target/release/deps/libpythonize-d82f642ebe84297a.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 283 |
+
target/release/deps/libquote-0b8b9fbcbb9ecc80.rlib filter=lfs diff=lfs merge=lfs -text
|
| 284 |
+
target/release/deps/libquote-0b8b9fbcbb9ecc80.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 285 |
+
target/release/deps/librand-1293731dbe0fce26.rlib filter=lfs diff=lfs merge=lfs -text
|
| 286 |
+
target/release/deps/librand-1293731dbe0fce26.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 287 |
+
target/release/deps/librand-78648a5bb1388ba1.rlib filter=lfs diff=lfs merge=lfs -text
|
| 288 |
+
target/release/deps/librand-78648a5bb1388ba1.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 289 |
+
target/release/deps/librand_chacha-0fc4568892e1aaa3.rlib filter=lfs diff=lfs merge=lfs -text
|
| 290 |
+
target/release/deps/librand_chacha-0fc4568892e1aaa3.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 291 |
+
target/release/deps/librand_chacha-3dc17ff20da80a27.rlib filter=lfs diff=lfs merge=lfs -text
|
| 292 |
+
target/release/deps/librand_chacha-3dc17ff20da80a27.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 293 |
+
target/release/deps/librand_core-b251d9fe42275948.rlib filter=lfs diff=lfs merge=lfs -text
|
| 294 |
+
target/release/deps/librand_core-b251d9fe42275948.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 295 |
+
target/release/deps/librand_core-bb541346dab4b398.rlib filter=lfs diff=lfs merge=lfs -text
|
| 296 |
+
target/release/deps/librand_core-bb541346dab4b398.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 297 |
+
target/release/deps/librand_distr-6b1419f877559059.rlib filter=lfs diff=lfs merge=lfs -text
|
| 298 |
+
target/release/deps/librand_distr-6b1419f877559059.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 299 |
+
target/release/deps/libraw_cpuid-4d74c741aa6589ff.rlib filter=lfs diff=lfs merge=lfs -text
|
| 300 |
+
target/release/deps/libraw_cpuid-4d74c741aa6589ff.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 301 |
+
target/release/deps/librayon-f1d78b313d00bcb0.rlib filter=lfs diff=lfs merge=lfs -text
|
| 302 |
+
target/release/deps/librayon-f1d78b313d00bcb0.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 303 |
+
target/release/deps/librayon_cond-991be180e9bf6444.rlib filter=lfs diff=lfs merge=lfs -text
|
| 304 |
+
target/release/deps/librayon_cond-991be180e9bf6444.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 305 |
+
target/release/deps/librayon_core-a2245c1ec44824ba.rlib filter=lfs diff=lfs merge=lfs -text
|
| 306 |
+
target/release/deps/librayon_core-a2245c1ec44824ba.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 307 |
+
target/release/deps/libregex-6df57f04fe28fb7c.rlib filter=lfs diff=lfs merge=lfs -text
|
| 308 |
+
target/release/deps/libregex-6df57f04fe28fb7c.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 309 |
+
target/release/deps/libregex_automata-948ecf613b927248.rlib filter=lfs diff=lfs merge=lfs -text
|
| 310 |
+
target/release/deps/libregex_automata-948ecf613b927248.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 311 |
+
target/release/deps/libregex_syntax-a853c2d17579d940.rlib filter=lfs diff=lfs merge=lfs -text
|
| 312 |
+
target/release/deps/libregex_syntax-a853c2d17579d940.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 313 |
+
target/release/deps/librustix-85d9580427f7d48c.rlib filter=lfs diff=lfs merge=lfs -text
|
| 314 |
+
target/release/deps/librustix-85d9580427f7d48c.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 315 |
+
target/release/deps/libsafetensors-802474d77e35d21e.rlib filter=lfs diff=lfs merge=lfs -text
|
| 316 |
+
target/release/deps/libsafetensors-802474d77e35d21e.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 317 |
+
target/release/deps/libserde-5e190e09fdf840b7.rlib filter=lfs diff=lfs merge=lfs -text
|
| 318 |
+
target/release/deps/libserde-5e190e09fdf840b7.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 319 |
+
target/release/deps/libserde_core-3f6c00be05b224b8.rlib filter=lfs diff=lfs merge=lfs -text
|
| 320 |
+
target/release/deps/libserde_core-3f6c00be05b224b8.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 321 |
+
target/release/deps/libserde_json-68e61042eed28f96.rlib filter=lfs diff=lfs merge=lfs -text
|
| 322 |
+
target/release/deps/libserde_json-68e61042eed28f96.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 323 |
+
target/release/deps/libshlex-bf8bee87fecfaea1.rlib filter=lfs diff=lfs merge=lfs -text
|
| 324 |
+
target/release/deps/libslab-c2d2eee2552bf77b.rlib filter=lfs diff=lfs merge=lfs -text
|
| 325 |
+
target/release/deps/libslab-c2d2eee2552bf77b.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 326 |
+
target/release/deps/libsmallvec-537eb425f7bd9c11.rlib filter=lfs diff=lfs merge=lfs -text
|
| 327 |
+
target/release/deps/libsmallvec-537eb425f7bd9c11.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 328 |
+
target/release/deps/libspm_precompiled-a00550294348b361.rlib filter=lfs diff=lfs merge=lfs -text
|
| 329 |
+
target/release/deps/libstrsim-b0bd691c0b318082.rlib filter=lfs diff=lfs merge=lfs -text
|
| 330 |
+
target/release/deps/libsyn-94a18812adc54943.rlib filter=lfs diff=lfs merge=lfs -text
|
| 331 |
+
target/release/deps/libsyn-94a18812adc54943.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 332 |
+
target/release/deps/libsyn-a16cfe9e8cd27f95.rlib filter=lfs diff=lfs merge=lfs -text
|
| 333 |
+
target/release/deps/libsyn-a16cfe9e8cd27f95.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 334 |
+
target/release/deps/libsyn-b7e800457ad5c032.rlib filter=lfs diff=lfs merge=lfs -text
|
| 335 |
+
target/release/deps/libsyn-b7e800457ad5c032.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 336 |
+
target/release/deps/libsynstructure-cfd57601ecf6fa90.rlib filter=lfs diff=lfs merge=lfs -text
|
| 337 |
+
target/release/deps/libsynstructure-cfd57601ecf6fa90.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 338 |
+
target/release/deps/libtarget_lexicon-63c01f916360ba73.rlib filter=lfs diff=lfs merge=lfs -text
|
| 339 |
+
target/release/deps/libtarget_lexicon-63c01f916360ba73.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 340 |
+
target/release/deps/libtempfile-cb48782ba1f029a6.rlib filter=lfs diff=lfs merge=lfs -text
|
| 341 |
+
target/release/deps/libtempfile-cb48782ba1f029a6.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 342 |
+
target/release/deps/libtokenizers-a80d431e14fc5472.rlib filter=lfs diff=lfs merge=lfs -text
|
| 343 |
+
target/release/deps/libtokenizers-a80d431e14fc5472.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 344 |
+
target/release/deps/libtokio-0177c9a6ea740cb1.rlib filter=lfs diff=lfs merge=lfs -text
|
| 345 |
+
target/release/deps/libtokio-0177c9a6ea740cb1.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 346 |
+
target/release/deps/libtyped_path-5c38177fff2cb715.rlib filter=lfs diff=lfs merge=lfs -text
|
| 347 |
+
target/release/deps/libtyped_path-5c38177fff2cb715.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 348 |
+
target/release/deps/libunicode_categories-de2ed4d19ed1239f.rlib filter=lfs diff=lfs merge=lfs -text
|
| 349 |
+
target/release/deps/libunicode_categories-de2ed4d19ed1239f.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 350 |
+
target/release/deps/libunicode_normalization_alignments-339d249e26b7f50d.rlib filter=lfs diff=lfs merge=lfs -text
|
| 351 |
+
target/release/deps/libunicode_normalization_alignments-339d249e26b7f50d.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 352 |
+
target/release/deps/libunicode_segmentation-f5bf08cf6949d3eb.rlib filter=lfs diff=lfs merge=lfs -text
|
| 353 |
+
target/release/deps/libunicode_segmentation-f5bf08cf6949d3eb.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 354 |
+
target/release/deps/libversion_check-bb21ec76f396fc8b.rlib filter=lfs diff=lfs merge=lfs -text
|
| 355 |
+
target/release/deps/libyoke-8c1910b2050ece59.rlib filter=lfs diff=lfs merge=lfs -text
|
| 356 |
+
target/release/deps/libyoke-8c1910b2050ece59.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 357 |
+
target/release/deps/libzerocopy-8a95324b3c3f6140.rlib filter=lfs diff=lfs merge=lfs -text
|
| 358 |
+
target/release/deps/libzerocopy-8a95324b3c3f6140.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 359 |
+
target/release/deps/libzip-a0638e421b366569.rlib filter=lfs diff=lfs merge=lfs -text
|
| 360 |
+
target/release/deps/libzip-a0638e421b366569.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 361 |
+
target/release/deps/libzmij-1f3def37de6d9ad3.rlib filter=lfs diff=lfs merge=lfs -text
|
| 362 |
+
target/release/deps/libzmij-1f3def37de6d9ad3.rmeta filter=lfs diff=lfs merge=lfs -text
|
| 363 |
+
target/release/deps/provas-96ef8f7f6fc2b09e filter=lfs diff=lfs merge=lfs -text
|
| 364 |
+
target/release/deps/provas-ea5bd8f23aaf7755 filter=lfs diff=lfs merge=lfs -text
|
| 365 |
+
target/release/examples/debug_polar filter=lfs diff=lfs merge=lfs -text
|
| 366 |
+
target/release/examples/debug_polar-8022405e1ceccb44 filter=lfs diff=lfs merge=lfs -text
|
| 367 |
+
target/release/libkhtst_rust.rlib filter=lfs diff=lfs merge=lfs -text
|
| 368 |
+
target/wheels/khtst_rust-0.6.0-cp310-abi3-manylinux_2_39_x86_64.whl filter=lfs diff=lfs merge=lfs -text
|
| 369 |
+
target/wheels/khtst_rust-0.7.0-cp310-abi3-manylinux_2_39_x86_64.whl filter=lfs diff=lfs merge=lfs -text
|
| 370 |
+
resultados/gerador_aritmetica.json filter=lfs diff=lfs merge=lfs -text
|
laboratorio/AUTOCRITICA.md
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# AUTOCRITICA — ciclo v0.22-lab
|
| 2 |
+
|
| 3 |
+
> Autocritique explícita, exigida pelo ciclo: análise do repositório
|
| 4 |
+
> publicado (`PowerMachine/khtst-rust`, branch `main`) e dos arquivos dos
|
| 5 |
+
> ciclos v0.18–v0.21, combinando **matemática, física, física matemática,
|
| 6 |
+
> lógica e programação**. Convenção do projeto: leitura honesta — achados
|
| 7 |
+
> próprios e alheios, sem omitir o que não fecha.
|
| 8 |
+
|
| 9 |
+
## §1 ACHADO CENTRAL — lab-A1: a tautologia no laço de regulação
|
| 10 |
+
|
| 11 |
+
**Achado (matemática + lógica + programação).** Na integração v0.21
|
| 12 |
+
(`src/v021/memoria_crescente.rs::passo_regulacao`), a lei de equações
|
| 13 |
+
`θ ← Π(θ + K·(r − y))` foi chamada com `y = r` (o próprio setpoint como
|
| 14 |
+
medição): `self.limiar.regular(self.alvo_qualidade())` seguido de
|
| 15 |
+
`erro = self.limiar.referencia() − self.alvo_qualidade()`. O erro é
|
| 16 |
+
**identicamente nulo por construção** — o laço de controle está aberto.
|
| 17 |
+
A telemetria publicada confirma: em `resultados/suite_v021.json`,
|
| 18 |
+
`erro_limiar_serie = [1e-12, 0, 0, …, 0]` nos 12 passos,
|
| 19 |
+
`movimentos_aceitos = 0`, `movimentos_recusados = 0`, limiar congelado
|
| 20 |
+
em `1e-6`, enquanto `serie_penalidade` subiu de 0,151 para 0,280 sem
|
| 21 |
+
qualquer resposta do regulador. **Errata ao r-63/r-64**: o texto afirma
|
| 22 |
+
"as propostas foram rejeitadas" (Achado 4); a telemetria mostra que não
|
| 23 |
+
houve propostas — 12 passos de regulação sem um único movimento
|
| 24 |
+
avaliado. Em termos de lógica: a afirmação "a lei propõe e o ensaio
|
| 25 |
+
dispõe" era **vacuamente verdadeira** (quantificador sobre conjunto
|
| 26 |
+
vazio de propostas).
|
| 27 |
+
|
| 28 |
+
**Correção (v0.22-lab, opt-in).** `lab/autorregulacao.py` separa o
|
| 29 |
+
contrato (`r` = setpoint, `y` = medição, unidades iguais pela guarda
|
| 30 |
+
tipada); `lab/memoria_crescente.py` aplica `proposta = Π(θ + K·(r − y))`
|
| 31 |
+
com `y` = pior célula held-out; o ensaio-compromisso avalia CADA
|
| 32 |
+
proposta. Medido em dados reais (wiki PT-BR): 11 propostas reais
|
| 33 |
+
(2 aceitas, 9 recusadas) contra 0/0 do caminho publicado — reproduzido
|
| 34 |
+
bit-a-bit como paridade (`lei_corrigida=False`).
|
| 35 |
+
|
| 36 |
+
**Segunda correção de escala.** O limiar publicado nasce em `1e-6` —
|
| 37 |
+
degenerado no regime real, onde os QE por célula são O(0,1–2). É a
|
| 38 |
+
mesma família do erro de unidades do Achado 3 do r-64 (a guarda de
|
| 39 |
+
unidade pega a unidade; faltava a guarda de ESCALA). No caminho opt-in
|
| 40 |
+
o limiar nasce no setpoint (mediana das células refináveis — "resolução
|
| 41 |
+
típica suficiente").
|
| 42 |
+
|
| 43 |
+
## §2 Matemática
|
| 44 |
+
|
| 45 |
+
**§2.1 O que está correto nos ciclos auditados.** A prova de
|
| 46 |
+
não-degeneração do `prior_nivel1` (I_som_variantes §3, por contradição:
|
| 47 |
+
softmax estritamente positivo ⇒ suporte completo) é correta e elegante;
|
| 48 |
+
a monotonicidade do EQ por atribuição ótima + mediana geométrica
|
| 49 |
+
(T-V18-9) e a divisão conservadora (T-V19-6) estão corretas — reproduzidas
|
| 50 |
+
aqui como T-L1/T-L2 com falsificação executável
|
| 51 |
+
(`lab/mapa_som.py::testes`: EQ 2,46530 → 2,46530−ε no lote real);
|
| 52 |
+
a distinção EQ (distância quadrada) × QE (norma L2) do r-64 é correta.
|
| 53 |
+
|
| 54 |
+
**§2.2 Falha encontrada — o critério relativo torna o limiar
|
| 55 |
+
matematicamente inócuo.** Com `alvo_relativo = k`, a divisão exige
|
| 56 |
+
`qe_i > θ` **E** `qe_i > k·m̄`. Como `m̄` (média dos QE refináveis) é
|
| 57 |
+
tipicamente ≫ θ em qualquer escala de dado, o termo absoluto NUNCA liga:
|
| 58 |
+
o limiar regulado é um segundo predicado estritamente mais fraco que o
|
| 59 |
+
primeiro — matematicamente inócuo (medido: `digits/relativo`, limiar
|
| 60 |
+
1,4429; `k·m̄` ≫ 1,44; resultado idêntico ao publicado célula a célula).
|
| 61 |
+
O limiar só é governador de fato no regime ABSOLUTO (sem `alvo_relativo`)
|
| 62 |
+
— onde o modo de falha publicado (crescimento desgovernado) vive. É
|
| 63 |
+
exatamente lá que a correção lab-A1 produz ganho mensurável: **215 → 75
|
| 64 |
+
células com EQ held-out 2,318 → 2,101** (digits reais). Lição: um
|
| 65 |
+
parâmetro regulado precisa de um canal em que sua variação mude a
|
| 66 |
+
decisão; caso contrário o laço é vivo e inútil (a correção do erro não
|
| 67 |
+
basta — falta a análise de RELEVÂNCIA do atuador).
|
| 68 |
+
|
| 69 |
+
**§2.3 Entropia do prior.** O `I_som_variantes` reporta
|
| 70 |
+
H = 2,0774 nats contra ln 8 = 2,0794 — prior quase uniforme. Leitura
|
| 71 |
+
crítica: com vetores de texto praticamente ortogonais (QE ≈ 0), a
|
| 72 |
+
"massa" `m_j` é quase uniforme POR CONSTRUÇÃO do dado, não porque o
|
| 73 |
+
modelo aprendeu algo; um prior quase-uniforme sobre códigos é
|
| 74 |
+
informacionalmente vazio. O laboratório mede a ortogonalidade real da
|
| 75 |
+
featurização: |cos| médio = 0,334 (mais denso que o regime do repo,
|
| 76 |
+
porque o featurizador determinístico do lab não é bit-a-bit o deles —
|
| 77 |
+
declarado).
|
| 78 |
+
|
| 79 |
+
**§2.4 Números do laboratório (todos medidos, nada estimado).**
|
| 80 |
+
- MAPA (wiki, 246 artigos, 12 lotes): absoluto 15→100 células
|
| 81 |
+
(85 divisões); relativo 15→21 (6); relativo+histerese 15→15 (0) com
|
| 82 |
+
EQ held-out 0,8102 (melhor que 0,8124) e pior célula 0,9198 (melhor
|
| 83 |
+
que 0,9352).
|
| 84 |
+
- LAÇO (digits, 300 vetores reais): absoluto publicado 19→215 células,
|
| 85 |
+
EQ held-out 2,3177; absoluto corrigido 19→75, EQ held-out 2,1014.
|
| 86 |
+
- SOM (digits, 1000 amostras, grade 10×10): TE Moore 0,9470 → 0,0960
|
| 87 |
+
(auto-organização observada — paridade do padrão 0,9453 → 0,0469 do
|
| 88 |
+
som.rs §5.1); EQ 23,86 → 1,47; Mahalanobis na própria métrica
|
| 89 |
+
36,30 → 34,25.
|
| 90 |
+
- JEPA (digits, 300 amostras, f64): perda de treino 2,573 → 0,742;
|
| 91 |
+
T-L8 erro autograd × diferenças finitas centrais = 3,6e-11 (tolerância
|
| 92 |
+
1e-6), primeira ordem = 4,5e-02 (controle não-vácuo, 9 ordens);
|
| 93 |
+
T-L7 resíduo KKT 47,2 → 0,0222 com L̂ = 1,241 medido; controle η×4
|
| 94 |
+
→ 6,25 (não converge); T-L9 entrada constante: std 0,00 → 0,05 = ε.
|
| 95 |
+
|
| 96 |
+
## §3 Física
|
| 97 |
+
|
| 98 |
+
**§3.1 Polarização–variância como troca entalpia–entropia.** O Achado 2
|
| 99 |
+
do r-64 ("a penalidade held-out pode PIORAR com o crescimento") é, em
|
| 100 |
+
física estatística, a competição clássica entalpia-entropia: dividir
|
| 101 |
+
células baixa a energia de quantização (QE, "entalpia" do mapa) e
|
| 102 |
+
aumenta a "entropia" de memorização (o protótipo de 1 amostra memoriza).
|
| 103 |
+
O ensaio-compromisso é o critério de estilo libre-energy: só aceita o
|
| 104 |
+
movimento se a grandeza protegida (held-out) melhorar — o análogo de
|
| 105 |
+
aceitar/rejeitar por ΔF < 0. O laboratório mediu o efeito nos dois
|
| 106 |
+
sentidos: no digits, conter o crescimento melhorou o EQ held-out
|
| 107 |
+
(2,318 → 2,101) — menos memorização; na wiki, o ensaio recusou as
|
| 108 |
+
descidas (crescer não pagava).
|
| 109 |
+
|
| 110 |
+
**§3.2 Recozimento e o papel de σ(t).** O decaimento linear
|
| 111 |
+
σ: 1,5 → 0,5 (som.rs) é um protocolo de recozimento: alta "temperatura"
|
| 112 |
+
organiza (TE cai), baixa quantiza (EQ cai) — medido na bancada 34
|
| 113 |
+
(curva completa em `bancada_som.json`). A fase em que o EQ SOBE antes
|
| 114 |
+
de cair (som.rs §5.1) é o transiente de reorganização — coerente com o
|
| 115 |
+
protocolo.
|
| 116 |
+
|
| 117 |
+
**§3.3 O colapso como transição de fase.** O colapso multimodal do JEPA
|
| 118 |
+
(todas as direções convergindo) é uma transição de fase de ordem
|
| 119 |
+
dinâmica: o parâmetro de ordem é a menor variância `min_j std_j(z)`.
|
| 120 |
+
O G3 (perdas no objetivo) é o campo externo que impede a fase colapsada;
|
| 121 |
+
o piso ε é a restrição dura (como um campo molecular que impede a
|
| 122 |
+
condensação). Sob pressão de alinhamento (λ_align = 50), o laboratório
|
| 123 |
+
mede: objetivo std 0,0121 × diagnóstico 0,0120, L_var 0,2205 × 0,2208 —
|
| 124 |
+
o campo resiste, o diagnóstico só observa. Efeito pequeno mas
|
| 125 |
+
consistentemente no mesmo sentido nos dois regimes (benigno e sob
|
| 126 |
+
pressão) — e o piso dura (0,05 = ε) é exato.
|
| 127 |
+
|
| 128 |
+
## §4 Física matemática
|
| 129 |
+
|
| 130 |
+
**§4.1 O equilíbrio como gradiente flow dissipativo.** O laço
|
| 131 |
+
`z_{k+1} = z_k − η∇E(z_k|c)` é a discretização de `ż = −∇E` — um
|
| 132 |
+
sistema dissipativo com E como função de Lyapunov. A descent lemma
|
| 133 |
+
(T-V21-7) É o teorema de Lyapunov: `E(z_{k+1}) ≤ E(z_k) − (η/2)‖∇E‖²`.
|
| 134 |
+
O laboratório mede a monotonicidade do RESÍDUO (não da energia):
|
| 135 |
+
47,2 → 0,0222, decrescente passo a passo (`residuos_decrescentes: true`).
|
| 136 |
+
|
| 137 |
+
**§4.2 A condição η·L ≤ 1 é uma condição de Courant.** A condição de
|
| 138 |
+
descida `η·L_eff ≤ 1` tem a mesma forma estrutural do CFL de esquemas
|
| 139 |
+
explícitos: o passo admissível é razão inversa da maior "velocidade de
|
| 140 |
+
propagação" (aqui a constante de Lipschitz do gradiente, medida L̂ = 1,24;
|
| 141 |
+
o confinamento κ contribui exatamente κ ao Hessiano — como um potencial
|
| 142 |
+
harmônico que garante estados ligados: sem κ, a MLP de energia pode
|
| 143 |
+
produzir equilíbrios indefinidos; com κ, o Hessiano ≽ κI garante
|
| 144 |
+
convexidade forte e equilíbrio único na região). O controle (η×4)
|
| 145 |
+
rompe o CFL: resíduo 6,25 e o sintético explode a 4,2e30 — a
|
| 146 |
+
instabilidade explícita prevista pela teoria, agora observada.
|
| 147 |
+
|
| 148 |
+
**§4.3 KKT como condição de equilíbrio mecânico.** O resíduo de KKT
|
| 149 |
+
`‖∇_z E(ẑ|c)‖ ≤ tol` é a condição de equilíbrio de forças; a flag
|
| 150 |
+
`equilibrio_convergido` é o critério de parada de um solver de equilíbrio.
|
| 151 |
+
O que o v0.21 adicionou — e o laboratório reproduz em f64 — é o
|
| 152 |
+
meta-gradiente EXATO através do equilíbrio (T-L8): o autograd ao longo
|
| 153 |
+
do laço desenrolado inclui os termos de segunda ordem (∂∇E/∂z e ∂∇E/∂θ)
|
| 154 |
+
que a primeira ordem descarta; a diferença finita central confirma com
|
| 155 |
+
erro 3,6e-11, e o modo de primeira ordem erra 4,5e-02 — a física do
|
| 156 |
+
"adjoin exato × adjoin congelado" (o adjunto congelado ignora a
|
| 157 |
+
dependência da dinâmica nos parâmetros, erro de ordem da própria
|
| 158 |
+
dinâmica).
|
| 159 |
+
|
| 160 |
+
## §5 Lógica e programação
|
| 161 |
+
|
| 162 |
+
**§5.1 Falsificabilidade (Popper) como arquitetura.** A doutrina do repo
|
| 163 |
+
(tríplice prova com condição de falsificação) é Popper operacionalizado.
|
| 164 |
+
O laboratório aplica o padrão mais duro: **controle não-vácuo** — todo
|
| 165 |
+
teste positivo tem um braço que DEVE falhar (T-L7: passo ×4 deve diverger;
|
| 166 |
+
T-L8: 1ª ordem deve errar; T-L9: sem piso deve colapsar). Um teste cujo
|
| 167 |
+
braço de controle passa junto é um teste vácuo — a lição D-A/D-B/D-C do
|
| 168 |
+
v0.20 (testes que só exercitavam o caminho feliz) é a mesma falha em
|
| 169 |
+
outra roupagem.
|
| 170 |
+
|
| 171 |
+
**§5.2 O teste que não falha onde deve é especioso.** Errata registrada
|
| 172 |
+
contra o próprio laboratório: a primeira versão da bancada G3 comparou
|
| 173 |
+
os dois braços com o PISO LIGADO nos dois — std = ε mecânico nos dois
|
| 174 |
+
braços, diferença nula por construção (o teste não podia falhar). Corrigido:
|
| 175 |
+
piso desligado nos dois braços da comparação + braço de pressão
|
| 176 |
+
(λ_align = 50). O gate L3 só passou depois que o braço de controle pôde
|
| 177 |
+
falhar de verdade.
|
| 178 |
+
|
| 179 |
+
**§5.3 Contradição entre narrativa e telemetria.** r-63 Achado 4 ("as
|
| 180 |
+
propostas foram rejeitadas") × suite_v021.json (0 propostas): a
|
| 181 |
+
documentação afirma mais do que o artefato sustenta. Lição: telemetria é
|
| 182 |
+
a fonte primária; narrativa é hipótese. O laboratório publica ambos
|
| 183 |
+
sempre (`serie_decisao` + contadores no mesmo JSON).
|
| 184 |
+
|
| 185 |
+
**§5.4 O caminho real tem de ser testado.** Os 3 defeitos do v0.20
|
| 186 |
+
(D-A máscara comparada com modalidades em vez de tokens; D-B cache lendo
|
| 187 |
+
cabeças como tokens; D-C níveis por modalidade em vez de por token) só
|
| 188 |
+
apareceram com máscara + cache — o caminho de produção. No laboratório,
|
| 189 |
+
os análogos: máscaras determinísticas por época (`gerar_mascara` com
|
| 190 |
+
piso de 2 patches de contexto), held-out disjunto por construção
|
| 191 |
+
(T-L4), e reexecução bit-a-bit (L5) em vez de confiar em "passou uma vez".
|
| 192 |
+
|
| 193 |
+
**§5.5 Higiene operacional.** A convenção do repo (`lib.rs`: token
|
| 194 |
+
EXCLUSIVAMENTE em `HF_TOKEN`, apagado após uso) virou TESTE (gate L7:
|
| 195 |
+
regex `hf_[A-Za-z0-9]{20,}` sobre todo o projeto). Publicação em COMMIT
|
| 196 |
+
ÚNICO (o HF bloqueia envios parciais em sequência curta — exigência do
|
| 197 |
+
ciclo). Sem `thread_rng`, sem relógio, sem iteração de hash-map nos
|
| 198 |
+
caminhos medidos (determinismo L5 verificado por reexecução bit-a-bit
|
| 199 |
+
nas bancadas 31 e 34).
|
| 200 |
+
|
| 201 |
+
## §6 Limitações do próprio laboratório (declaradas)
|
| 202 |
+
|
| 203 |
+
1. **Paridade semântica, não bit-a-bit**: o featurizador do lab
|
| 204 |
+
(hashing de 1–2 gramas) não é o do repo (não publicado) — os números
|
| 205 |
+
absolutos diferem (ex.: relativo 15→21 células aqui vs 15→35 no r-64);
|
| 206 |
+
os REGIMES reproduzem (desgovernado/estabilizado/contido).
|
| 207 |
+
2. **Escala de demonstração**: LeJEPA-lab usa d_emb=8, K=24, 24 épocas —
|
| 208 |
+
as propriedades (T-L7/T-L8/T-L9) são invariantes de escala, mas o
|
| 209 |
+
aprendizado em escala real não é afirmado aqui.
|
| 210 |
+
3. **Efeito G3 pequeno**: sob dados reais diversos, o colapso não é o
|
| 211 |
+
modo dominante; a diferença objetivo × diagnóstico é consistente mas
|
| 212 |
+
de poucos milésimos. O piso dura é o mecanismo de garantia; o objetivo
|
| 213 |
+
é o mecanismo de forma.
|
| 214 |
+
4. **Rust sem cargo**: os patches v0.22 são fonte rotulada, NÃO
|
| 215 |
+
compilados neste ambiente (cargo ausente) — a validação numérica
|
| 216 |
+
equivalente está nas bancadas Python.
|
| 217 |
+
5. **Um só featurizador de texto**: a wiki é representada por UM mapa
|
| 218 |
+
de hashing; outro featurizador pode deslocar os números absolutos
|
| 219 |
+
(os regimes e as ordens de grandeza são o que se afirma).
|
laboratorio/Cargo.lock
ADDED
|
@@ -0,0 +1,1813 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is automatically @generated by Cargo.
|
| 2 |
+
# It is not intended for manual editing.
|
| 3 |
+
version = 4
|
| 4 |
+
|
| 5 |
+
[[package]]
|
| 6 |
+
name = "ahash"
|
| 7 |
+
version = "0.8.12"
|
| 8 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 9 |
+
checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
|
| 10 |
+
dependencies = [
|
| 11 |
+
"cfg-if",
|
| 12 |
+
"getrandom 0.3.4",
|
| 13 |
+
"once_cell",
|
| 14 |
+
"serde",
|
| 15 |
+
"version_check",
|
| 16 |
+
"zerocopy",
|
| 17 |
+
]
|
| 18 |
+
|
| 19 |
+
[[package]]
|
| 20 |
+
name = "aho-corasick"
|
| 21 |
+
version = "1.1.5"
|
| 22 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 23 |
+
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
|
| 24 |
+
dependencies = [
|
| 25 |
+
"memchr",
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
[[package]]
|
| 29 |
+
name = "allocator-api2"
|
| 30 |
+
version = "0.2.21"
|
| 31 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 32 |
+
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
|
| 33 |
+
|
| 34 |
+
[[package]]
|
| 35 |
+
name = "anyhow"
|
| 36 |
+
version = "1.0.104"
|
| 37 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 38 |
+
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
| 39 |
+
|
| 40 |
+
[[package]]
|
| 41 |
+
name = "arc-swap"
|
| 42 |
+
version = "1.9.3"
|
| 43 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 44 |
+
checksum = "380962b3d93b99642e50b9febf72c071e97e8b32d86eae9cf4ef582bb960ae6e"
|
| 45 |
+
dependencies = [
|
| 46 |
+
"rustversion",
|
| 47 |
+
]
|
| 48 |
+
|
| 49 |
+
[[package]]
|
| 50 |
+
name = "autocfg"
|
| 51 |
+
version = "1.5.1"
|
| 52 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 53 |
+
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
| 54 |
+
|
| 55 |
+
[[package]]
|
| 56 |
+
name = "base64"
|
| 57 |
+
version = "0.13.1"
|
| 58 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 59 |
+
checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"
|
| 60 |
+
|
| 61 |
+
[[package]]
|
| 62 |
+
name = "bitflags"
|
| 63 |
+
version = "2.13.2"
|
| 64 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 65 |
+
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
| 66 |
+
|
| 67 |
+
[[package]]
|
| 68 |
+
name = "built"
|
| 69 |
+
version = "0.8.1"
|
| 70 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 71 |
+
checksum = "5c0e531d93d39c34eef561e929e8a7f86d77a5af08aac4f6d6e39976c51858e9"
|
| 72 |
+
|
| 73 |
+
[[package]]
|
| 74 |
+
name = "bytemuck"
|
| 75 |
+
version = "1.25.2"
|
| 76 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 77 |
+
checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
|
| 78 |
+
dependencies = [
|
| 79 |
+
"bytemuck_derive",
|
| 80 |
+
]
|
| 81 |
+
|
| 82 |
+
[[package]]
|
| 83 |
+
name = "bytemuck_derive"
|
| 84 |
+
version = "1.12.1"
|
| 85 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 86 |
+
checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"
|
| 87 |
+
dependencies = [
|
| 88 |
+
"proc-macro2",
|
| 89 |
+
"quote",
|
| 90 |
+
"syn 3.0.9",
|
| 91 |
+
]
|
| 92 |
+
|
| 93 |
+
[[package]]
|
| 94 |
+
name = "byteorder"
|
| 95 |
+
version = "1.5.0"
|
| 96 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 97 |
+
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
|
| 98 |
+
|
| 99 |
+
[[package]]
|
| 100 |
+
name = "candle-core"
|
| 101 |
+
version = "0.11.0"
|
| 102 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 103 |
+
checksum = "5ecb245093b0f791b89d3420c3df9c6d49c60ab63ba54db896bf8a3baf486706"
|
| 104 |
+
dependencies = [
|
| 105 |
+
"byteorder",
|
| 106 |
+
"float8",
|
| 107 |
+
"gemm",
|
| 108 |
+
"half",
|
| 109 |
+
"libc",
|
| 110 |
+
"libm",
|
| 111 |
+
"memmap2",
|
| 112 |
+
"num-traits",
|
| 113 |
+
"num_cpus",
|
| 114 |
+
"rand 0.9.5",
|
| 115 |
+
"rand_distr",
|
| 116 |
+
"rayon",
|
| 117 |
+
"safetensors",
|
| 118 |
+
"thiserror 2.0.21",
|
| 119 |
+
"tokenizers",
|
| 120 |
+
"yoke",
|
| 121 |
+
"zerocopy",
|
| 122 |
+
"zip",
|
| 123 |
+
]
|
| 124 |
+
|
| 125 |
+
[[package]]
|
| 126 |
+
name = "candle-nn"
|
| 127 |
+
version = "0.11.0"
|
| 128 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 129 |
+
checksum = "eaa10b6ccc365b33210ce404fbf45e60d3e0bdac1004463cf1052e6ee1c1739a"
|
| 130 |
+
dependencies = [
|
| 131 |
+
"candle-core",
|
| 132 |
+
"half",
|
| 133 |
+
"libc",
|
| 134 |
+
"num-traits",
|
| 135 |
+
"rayon",
|
| 136 |
+
"safetensors",
|
| 137 |
+
"serde",
|
| 138 |
+
"thiserror 2.0.21",
|
| 139 |
+
]
|
| 140 |
+
|
| 141 |
+
[[package]]
|
| 142 |
+
name = "castaway"
|
| 143 |
+
version = "0.2.4"
|
| 144 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 145 |
+
checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a"
|
| 146 |
+
dependencies = [
|
| 147 |
+
"rustversion",
|
| 148 |
+
]
|
| 149 |
+
|
| 150 |
+
[[package]]
|
| 151 |
+
name = "cc"
|
| 152 |
+
version = "1.9.0"
|
| 153 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 154 |
+
checksum = "877bf67ac8e52449eb2f9e98a344ea163beb70dd1f9eebe3cc5357dcfeaee4df"
|
| 155 |
+
dependencies = [
|
| 156 |
+
"find-msvc-tools",
|
| 157 |
+
"shlex",
|
| 158 |
+
]
|
| 159 |
+
|
| 160 |
+
[[package]]
|
| 161 |
+
name = "cfg-if"
|
| 162 |
+
version = "1.0.5"
|
| 163 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 164 |
+
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
| 165 |
+
|
| 166 |
+
[[package]]
|
| 167 |
+
name = "compact_str"
|
| 168 |
+
version = "0.9.1"
|
| 169 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 170 |
+
checksum = "9dfdd1c2274d9aa354115b09dc9a901d6c5576818cdf70d14cae2bdb47df00ab"
|
| 171 |
+
dependencies = [
|
| 172 |
+
"castaway",
|
| 173 |
+
"cfg-if",
|
| 174 |
+
"itoa",
|
| 175 |
+
"rustversion",
|
| 176 |
+
"ryu",
|
| 177 |
+
"serde",
|
| 178 |
+
"static_assertions",
|
| 179 |
+
]
|
| 180 |
+
|
| 181 |
+
[[package]]
|
| 182 |
+
name = "crc32fast"
|
| 183 |
+
version = "1.5.3"
|
| 184 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 185 |
+
checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055"
|
| 186 |
+
dependencies = [
|
| 187 |
+
"cfg-if",
|
| 188 |
+
]
|
| 189 |
+
|
| 190 |
+
[[package]]
|
| 191 |
+
name = "crossbeam-channel"
|
| 192 |
+
version = "0.5.17"
|
| 193 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 194 |
+
checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1"
|
| 195 |
+
dependencies = [
|
| 196 |
+
"crossbeam-utils",
|
| 197 |
+
]
|
| 198 |
+
|
| 199 |
+
[[package]]
|
| 200 |
+
name = "crossbeam-deque"
|
| 201 |
+
version = "0.8.8"
|
| 202 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 203 |
+
checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"
|
| 204 |
+
dependencies = [
|
| 205 |
+
"crossbeam-epoch",
|
| 206 |
+
"crossbeam-utils",
|
| 207 |
+
]
|
| 208 |
+
|
| 209 |
+
[[package]]
|
| 210 |
+
name = "crossbeam-epoch"
|
| 211 |
+
version = "0.9.21"
|
| 212 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 213 |
+
checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"
|
| 214 |
+
dependencies = [
|
| 215 |
+
"crossbeam-utils",
|
| 216 |
+
]
|
| 217 |
+
|
| 218 |
+
[[package]]
|
| 219 |
+
name = "crossbeam-utils"
|
| 220 |
+
version = "0.8.23"
|
| 221 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 222 |
+
checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
|
| 223 |
+
|
| 224 |
+
[[package]]
|
| 225 |
+
name = "crunchy"
|
| 226 |
+
version = "0.2.4"
|
| 227 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 228 |
+
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
|
| 229 |
+
|
| 230 |
+
[[package]]
|
| 231 |
+
name = "darling"
|
| 232 |
+
version = "0.20.11"
|
| 233 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 234 |
+
checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee"
|
| 235 |
+
dependencies = [
|
| 236 |
+
"darling_core",
|
| 237 |
+
"darling_macro",
|
| 238 |
+
]
|
| 239 |
+
|
| 240 |
+
[[package]]
|
| 241 |
+
name = "darling_core"
|
| 242 |
+
version = "0.20.11"
|
| 243 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 244 |
+
checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e"
|
| 245 |
+
dependencies = [
|
| 246 |
+
"fnv",
|
| 247 |
+
"ident_case",
|
| 248 |
+
"proc-macro2",
|
| 249 |
+
"quote",
|
| 250 |
+
"strsim",
|
| 251 |
+
"syn 2.0.119",
|
| 252 |
+
]
|
| 253 |
+
|
| 254 |
+
[[package]]
|
| 255 |
+
name = "darling_macro"
|
| 256 |
+
version = "0.20.11"
|
| 257 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 258 |
+
checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead"
|
| 259 |
+
dependencies = [
|
| 260 |
+
"darling_core",
|
| 261 |
+
"quote",
|
| 262 |
+
"syn 2.0.119",
|
| 263 |
+
]
|
| 264 |
+
|
| 265 |
+
[[package]]
|
| 266 |
+
name = "dary_heap"
|
| 267 |
+
version = "0.3.9"
|
| 268 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 269 |
+
checksum = "8b1e3a325bc115f096c8b77bbf027a7c2592230e70be2d985be950d3d5e60ebe"
|
| 270 |
+
dependencies = [
|
| 271 |
+
"serde",
|
| 272 |
+
]
|
| 273 |
+
|
| 274 |
+
[[package]]
|
| 275 |
+
name = "derive_builder"
|
| 276 |
+
version = "0.20.2"
|
| 277 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 278 |
+
checksum = "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947"
|
| 279 |
+
dependencies = [
|
| 280 |
+
"derive_builder_macro",
|
| 281 |
+
]
|
| 282 |
+
|
| 283 |
+
[[package]]
|
| 284 |
+
name = "derive_builder_core"
|
| 285 |
+
version = "0.20.2"
|
| 286 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 287 |
+
checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8"
|
| 288 |
+
dependencies = [
|
| 289 |
+
"darling",
|
| 290 |
+
"proc-macro2",
|
| 291 |
+
"quote",
|
| 292 |
+
"syn 2.0.119",
|
| 293 |
+
]
|
| 294 |
+
|
| 295 |
+
[[package]]
|
| 296 |
+
name = "derive_builder_macro"
|
| 297 |
+
version = "0.20.2"
|
| 298 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 299 |
+
checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c"
|
| 300 |
+
dependencies = [
|
| 301 |
+
"derive_builder_core",
|
| 302 |
+
"syn 2.0.119",
|
| 303 |
+
]
|
| 304 |
+
|
| 305 |
+
[[package]]
|
| 306 |
+
name = "dict_derive"
|
| 307 |
+
version = "0.5.1"
|
| 308 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 309 |
+
checksum = "846a520b3b7937dcfe564d9674d2d26da9e3cd0f8f1bbef51ca42fd6b7bb4f4a"
|
| 310 |
+
dependencies = [
|
| 311 |
+
"proc-macro2",
|
| 312 |
+
"quote",
|
| 313 |
+
"syn 1.0.109",
|
| 314 |
+
]
|
| 315 |
+
|
| 316 |
+
[[package]]
|
| 317 |
+
name = "dyn-stack"
|
| 318 |
+
version = "0.13.2"
|
| 319 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 320 |
+
checksum = "1c4713e43e2886ba72b8271aa66c93d722116acf7a75555cce11dcde84388fe8"
|
| 321 |
+
dependencies = [
|
| 322 |
+
"bytemuck",
|
| 323 |
+
"dyn-stack-macros",
|
| 324 |
+
]
|
| 325 |
+
|
| 326 |
+
[[package]]
|
| 327 |
+
name = "dyn-stack-macros"
|
| 328 |
+
version = "0.1.3"
|
| 329 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 330 |
+
checksum = "e1d926b4d407d372f141f93bb444696142c29d32962ccbd3531117cf3aa0bfa9"
|
| 331 |
+
|
| 332 |
+
[[package]]
|
| 333 |
+
name = "either"
|
| 334 |
+
version = "1.19.0"
|
| 335 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 336 |
+
checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
|
| 337 |
+
|
| 338 |
+
[[package]]
|
| 339 |
+
name = "enum-as-inner"
|
| 340 |
+
version = "0.6.1"
|
| 341 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 342 |
+
checksum = "a1e6a265c649f3f5979b601d26f1d05ada116434c87741c9493cb56218f76cbc"
|
| 343 |
+
dependencies = [
|
| 344 |
+
"heck",
|
| 345 |
+
"proc-macro2",
|
| 346 |
+
"quote",
|
| 347 |
+
"syn 2.0.119",
|
| 348 |
+
]
|
| 349 |
+
|
| 350 |
+
[[package]]
|
| 351 |
+
name = "equivalent"
|
| 352 |
+
version = "1.0.3"
|
| 353 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 354 |
+
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
|
| 355 |
+
|
| 356 |
+
[[package]]
|
| 357 |
+
name = "errno"
|
| 358 |
+
version = "0.3.14"
|
| 359 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 360 |
+
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
| 361 |
+
dependencies = [
|
| 362 |
+
"libc",
|
| 363 |
+
"windows-sys",
|
| 364 |
+
]
|
| 365 |
+
|
| 366 |
+
[[package]]
|
| 367 |
+
name = "esaxx-rs"
|
| 368 |
+
version = "0.1.10"
|
| 369 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 370 |
+
checksum = "d817e038c30374a4bcb22f94d0a8a0e216958d4c3dcde369b1439fec4bdda6e6"
|
| 371 |
+
|
| 372 |
+
[[package]]
|
| 373 |
+
name = "fastrand"
|
| 374 |
+
version = "2.5.0"
|
| 375 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 376 |
+
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
|
| 377 |
+
|
| 378 |
+
[[package]]
|
| 379 |
+
name = "find-msvc-tools"
|
| 380 |
+
version = "0.1.15"
|
| 381 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 382 |
+
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
|
| 383 |
+
|
| 384 |
+
[[package]]
|
| 385 |
+
name = "float8"
|
| 386 |
+
version = "0.7.0"
|
| 387 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 388 |
+
checksum = "c2d1f04709a8ac06e8e8042875a3c466cc4832d3c1a18dbcb9dba3c6e83046bc"
|
| 389 |
+
dependencies = [
|
| 390 |
+
"half",
|
| 391 |
+
"num-traits",
|
| 392 |
+
"rand 0.9.5",
|
| 393 |
+
"rand_distr",
|
| 394 |
+
]
|
| 395 |
+
|
| 396 |
+
[[package]]
|
| 397 |
+
name = "fnv"
|
| 398 |
+
version = "1.0.7"
|
| 399 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 400 |
+
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
|
| 401 |
+
|
| 402 |
+
[[package]]
|
| 403 |
+
name = "foldhash"
|
| 404 |
+
version = "0.2.0"
|
| 405 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 406 |
+
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
|
| 407 |
+
|
| 408 |
+
[[package]]
|
| 409 |
+
name = "futures"
|
| 410 |
+
version = "0.3.34"
|
| 411 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 412 |
+
checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3"
|
| 413 |
+
dependencies = [
|
| 414 |
+
"futures-channel",
|
| 415 |
+
"futures-core",
|
| 416 |
+
"futures-executor",
|
| 417 |
+
"futures-io",
|
| 418 |
+
"futures-sink",
|
| 419 |
+
"futures-task",
|
| 420 |
+
"futures-util",
|
| 421 |
+
]
|
| 422 |
+
|
| 423 |
+
[[package]]
|
| 424 |
+
name = "futures-channel"
|
| 425 |
+
version = "0.3.34"
|
| 426 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 427 |
+
checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"
|
| 428 |
+
dependencies = [
|
| 429 |
+
"futures-core",
|
| 430 |
+
"futures-sink",
|
| 431 |
+
]
|
| 432 |
+
|
| 433 |
+
[[package]]
|
| 434 |
+
name = "futures-core"
|
| 435 |
+
version = "0.3.34"
|
| 436 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 437 |
+
checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
|
| 438 |
+
|
| 439 |
+
[[package]]
|
| 440 |
+
name = "futures-executor"
|
| 441 |
+
version = "0.3.34"
|
| 442 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 443 |
+
checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432"
|
| 444 |
+
dependencies = [
|
| 445 |
+
"futures-core",
|
| 446 |
+
"futures-task",
|
| 447 |
+
"futures-util",
|
| 448 |
+
]
|
| 449 |
+
|
| 450 |
+
[[package]]
|
| 451 |
+
name = "futures-io"
|
| 452 |
+
version = "0.3.34"
|
| 453 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 454 |
+
checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"
|
| 455 |
+
|
| 456 |
+
[[package]]
|
| 457 |
+
name = "futures-macro"
|
| 458 |
+
version = "0.3.34"
|
| 459 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 460 |
+
checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"
|
| 461 |
+
dependencies = [
|
| 462 |
+
"proc-macro2",
|
| 463 |
+
"quote",
|
| 464 |
+
"syn 3.0.9",
|
| 465 |
+
]
|
| 466 |
+
|
| 467 |
+
[[package]]
|
| 468 |
+
name = "futures-sink"
|
| 469 |
+
version = "0.3.34"
|
| 470 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 471 |
+
checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d"
|
| 472 |
+
|
| 473 |
+
[[package]]
|
| 474 |
+
name = "futures-task"
|
| 475 |
+
version = "0.3.34"
|
| 476 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 477 |
+
checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
|
| 478 |
+
|
| 479 |
+
[[package]]
|
| 480 |
+
name = "futures-util"
|
| 481 |
+
version = "0.3.34"
|
| 482 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 483 |
+
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
|
| 484 |
+
dependencies = [
|
| 485 |
+
"futures-channel",
|
| 486 |
+
"futures-core",
|
| 487 |
+
"futures-io",
|
| 488 |
+
"futures-macro",
|
| 489 |
+
"futures-sink",
|
| 490 |
+
"futures-task",
|
| 491 |
+
"memchr",
|
| 492 |
+
"pin-project-lite",
|
| 493 |
+
"slab",
|
| 494 |
+
]
|
| 495 |
+
|
| 496 |
+
[[package]]
|
| 497 |
+
name = "gemm"
|
| 498 |
+
version = "0.19.0"
|
| 499 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 500 |
+
checksum = "aa0673db364b12263d103b68337a68fbecc541d6f6b61ba72fe438654709eacb"
|
| 501 |
+
dependencies = [
|
| 502 |
+
"dyn-stack",
|
| 503 |
+
"gemm-c32",
|
| 504 |
+
"gemm-c64",
|
| 505 |
+
"gemm-common",
|
| 506 |
+
"gemm-f16",
|
| 507 |
+
"gemm-f32",
|
| 508 |
+
"gemm-f64",
|
| 509 |
+
"num-complex",
|
| 510 |
+
"num-traits",
|
| 511 |
+
"paste",
|
| 512 |
+
"raw-cpuid",
|
| 513 |
+
"seq-macro",
|
| 514 |
+
]
|
| 515 |
+
|
| 516 |
+
[[package]]
|
| 517 |
+
name = "gemm-c32"
|
| 518 |
+
version = "0.19.0"
|
| 519 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 520 |
+
checksum = "086936dbdcb99e37aad81d320f98f670e53c1e55a98bee70573e83f95beb128c"
|
| 521 |
+
dependencies = [
|
| 522 |
+
"dyn-stack",
|
| 523 |
+
"gemm-common",
|
| 524 |
+
"num-complex",
|
| 525 |
+
"num-traits",
|
| 526 |
+
"paste",
|
| 527 |
+
"raw-cpuid",
|
| 528 |
+
"seq-macro",
|
| 529 |
+
]
|
| 530 |
+
|
| 531 |
+
[[package]]
|
| 532 |
+
name = "gemm-c64"
|
| 533 |
+
version = "0.19.0"
|
| 534 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 535 |
+
checksum = "20c8aeeeec425959bda4d9827664029ba1501a90a0d1e6228e48bef741db3a3f"
|
| 536 |
+
dependencies = [
|
| 537 |
+
"dyn-stack",
|
| 538 |
+
"gemm-common",
|
| 539 |
+
"num-complex",
|
| 540 |
+
"num-traits",
|
| 541 |
+
"paste",
|
| 542 |
+
"raw-cpuid",
|
| 543 |
+
"seq-macro",
|
| 544 |
+
]
|
| 545 |
+
|
| 546 |
+
[[package]]
|
| 547 |
+
name = "gemm-common"
|
| 548 |
+
version = "0.19.0"
|
| 549 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 550 |
+
checksum = "88027625910cc9b1085aaaa1c4bc46bb3a36aad323452b33c25b5e4e7c8e2a3e"
|
| 551 |
+
dependencies = [
|
| 552 |
+
"bytemuck",
|
| 553 |
+
"dyn-stack",
|
| 554 |
+
"half",
|
| 555 |
+
"libm",
|
| 556 |
+
"num-complex",
|
| 557 |
+
"num-traits",
|
| 558 |
+
"once_cell",
|
| 559 |
+
"paste",
|
| 560 |
+
"pulp",
|
| 561 |
+
"raw-cpuid",
|
| 562 |
+
"rayon",
|
| 563 |
+
"seq-macro",
|
| 564 |
+
"sysctl",
|
| 565 |
+
]
|
| 566 |
+
|
| 567 |
+
[[package]]
|
| 568 |
+
name = "gemm-f16"
|
| 569 |
+
version = "0.19.0"
|
| 570 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 571 |
+
checksum = "e3df7a55202e6cd6739d82ae3399c8e0c7e1402859b30e4cb780e61525d9486e"
|
| 572 |
+
dependencies = [
|
| 573 |
+
"dyn-stack",
|
| 574 |
+
"gemm-common",
|
| 575 |
+
"gemm-f32",
|
| 576 |
+
"half",
|
| 577 |
+
"num-complex",
|
| 578 |
+
"num-traits",
|
| 579 |
+
"paste",
|
| 580 |
+
"raw-cpuid",
|
| 581 |
+
"rayon",
|
| 582 |
+
"seq-macro",
|
| 583 |
+
]
|
| 584 |
+
|
| 585 |
+
[[package]]
|
| 586 |
+
name = "gemm-f32"
|
| 587 |
+
version = "0.19.0"
|
| 588 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 589 |
+
checksum = "02e0b8c9da1fbec6e3e3ab2ce6bc259ef18eb5f6f0d3e4edf54b75f9fd41a81c"
|
| 590 |
+
dependencies = [
|
| 591 |
+
"dyn-stack",
|
| 592 |
+
"gemm-common",
|
| 593 |
+
"num-complex",
|
| 594 |
+
"num-traits",
|
| 595 |
+
"paste",
|
| 596 |
+
"raw-cpuid",
|
| 597 |
+
"seq-macro",
|
| 598 |
+
]
|
| 599 |
+
|
| 600 |
+
[[package]]
|
| 601 |
+
name = "gemm-f64"
|
| 602 |
+
version = "0.19.0"
|
| 603 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 604 |
+
checksum = "056131e8f2a521bfab322f804ccd652520c79700d81209e9d9275bbdecaadc6a"
|
| 605 |
+
dependencies = [
|
| 606 |
+
"dyn-stack",
|
| 607 |
+
"gemm-common",
|
| 608 |
+
"num-complex",
|
| 609 |
+
"num-traits",
|
| 610 |
+
"paste",
|
| 611 |
+
"raw-cpuid",
|
| 612 |
+
"seq-macro",
|
| 613 |
+
]
|
| 614 |
+
|
| 615 |
+
[[package]]
|
| 616 |
+
name = "getrandom"
|
| 617 |
+
version = "0.2.17"
|
| 618 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 619 |
+
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
|
| 620 |
+
dependencies = [
|
| 621 |
+
"cfg-if",
|
| 622 |
+
"libc",
|
| 623 |
+
"wasi",
|
| 624 |
+
]
|
| 625 |
+
|
| 626 |
+
[[package]]
|
| 627 |
+
name = "getrandom"
|
| 628 |
+
version = "0.3.4"
|
| 629 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 630 |
+
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
|
| 631 |
+
dependencies = [
|
| 632 |
+
"cfg-if",
|
| 633 |
+
"libc",
|
| 634 |
+
"r-efi 5.3.0",
|
| 635 |
+
"wasip2",
|
| 636 |
+
]
|
| 637 |
+
|
| 638 |
+
[[package]]
|
| 639 |
+
name = "getrandom"
|
| 640 |
+
version = "0.4.3"
|
| 641 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 642 |
+
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
|
| 643 |
+
dependencies = [
|
| 644 |
+
"cfg-if",
|
| 645 |
+
"libc",
|
| 646 |
+
"r-efi 6.0.0",
|
| 647 |
+
]
|
| 648 |
+
|
| 649 |
+
[[package]]
|
| 650 |
+
name = "half"
|
| 651 |
+
version = "2.7.1"
|
| 652 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 653 |
+
checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
|
| 654 |
+
dependencies = [
|
| 655 |
+
"bytemuck",
|
| 656 |
+
"cfg-if",
|
| 657 |
+
"crunchy",
|
| 658 |
+
"num-traits",
|
| 659 |
+
"rand 0.9.5",
|
| 660 |
+
"rand_distr",
|
| 661 |
+
"zerocopy",
|
| 662 |
+
]
|
| 663 |
+
|
| 664 |
+
[[package]]
|
| 665 |
+
name = "hashbrown"
|
| 666 |
+
version = "0.16.1"
|
| 667 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 668 |
+
checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
|
| 669 |
+
dependencies = [
|
| 670 |
+
"allocator-api2",
|
| 671 |
+
"equivalent",
|
| 672 |
+
"foldhash",
|
| 673 |
+
"serde",
|
| 674 |
+
"serde_core",
|
| 675 |
+
]
|
| 676 |
+
|
| 677 |
+
[[package]]
|
| 678 |
+
name = "hashbrown"
|
| 679 |
+
version = "0.17.1"
|
| 680 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 681 |
+
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
| 682 |
+
|
| 683 |
+
[[package]]
|
| 684 |
+
name = "heck"
|
| 685 |
+
version = "0.5.0"
|
| 686 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 687 |
+
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
| 688 |
+
|
| 689 |
+
[[package]]
|
| 690 |
+
name = "hermit-abi"
|
| 691 |
+
version = "0.5.3"
|
| 692 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 693 |
+
checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"
|
| 694 |
+
|
| 695 |
+
[[package]]
|
| 696 |
+
name = "ident_case"
|
| 697 |
+
version = "1.0.1"
|
| 698 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 699 |
+
checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
|
| 700 |
+
|
| 701 |
+
[[package]]
|
| 702 |
+
name = "indexmap"
|
| 703 |
+
version = "2.14.2"
|
| 704 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 705 |
+
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
|
| 706 |
+
dependencies = [
|
| 707 |
+
"equivalent",
|
| 708 |
+
"hashbrown 0.17.1",
|
| 709 |
+
]
|
| 710 |
+
|
| 711 |
+
[[package]]
|
| 712 |
+
name = "indoc"
|
| 713 |
+
version = "2.0.8"
|
| 714 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 715 |
+
checksum = "a37b2691796cffeb8a8cd305ac66e65841559f147f4e63231d0eafa4db5384d1"
|
| 716 |
+
dependencies = [
|
| 717 |
+
"rustversion",
|
| 718 |
+
]
|
| 719 |
+
|
| 720 |
+
[[package]]
|
| 721 |
+
name = "itertools"
|
| 722 |
+
version = "0.14.0"
|
| 723 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 724 |
+
checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
|
| 725 |
+
dependencies = [
|
| 726 |
+
"either",
|
| 727 |
+
]
|
| 728 |
+
|
| 729 |
+
[[package]]
|
| 730 |
+
name = "itoa"
|
| 731 |
+
version = "1.0.18"
|
| 732 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 733 |
+
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
| 734 |
+
|
| 735 |
+
[[package]]
|
| 736 |
+
name = "khtst-rust"
|
| 737 |
+
version = "0.16.0"
|
| 738 |
+
dependencies = [
|
| 739 |
+
"anyhow",
|
| 740 |
+
"built",
|
| 741 |
+
"candle-core",
|
| 742 |
+
"candle-nn",
|
| 743 |
+
"crossbeam-channel",
|
| 744 |
+
"dict_derive",
|
| 745 |
+
"log",
|
| 746 |
+
"numpy",
|
| 747 |
+
"pyo3",
|
| 748 |
+
"pyo3-async-runtimes",
|
| 749 |
+
"pyo3-built",
|
| 750 |
+
"pyo3-log",
|
| 751 |
+
"pythonize",
|
| 752 |
+
"rand 0.8.8",
|
| 753 |
+
"rayon",
|
| 754 |
+
"serde",
|
| 755 |
+
"serde_json",
|
| 756 |
+
"thiserror 2.0.21",
|
| 757 |
+
"tokio",
|
| 758 |
+
]
|
| 759 |
+
|
| 760 |
+
[[package]]
|
| 761 |
+
name = "libc"
|
| 762 |
+
version = "0.2.191"
|
| 763 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 764 |
+
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
| 765 |
+
|
| 766 |
+
[[package]]
|
| 767 |
+
name = "libm"
|
| 768 |
+
version = "0.2.16"
|
| 769 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 770 |
+
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
|
| 771 |
+
|
| 772 |
+
[[package]]
|
| 773 |
+
name = "linux-raw-sys"
|
| 774 |
+
version = "0.12.1"
|
| 775 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 776 |
+
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
|
| 777 |
+
|
| 778 |
+
[[package]]
|
| 779 |
+
name = "log"
|
| 780 |
+
version = "0.4.34"
|
| 781 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 782 |
+
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
|
| 783 |
+
|
| 784 |
+
[[package]]
|
| 785 |
+
name = "macro_rules_attribute"
|
| 786 |
+
version = "0.2.3"
|
| 787 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 788 |
+
checksum = "b3ae8f6d608c795738406608304d30a2dfbdc8e58e44f7ba43236da5208ded3c"
|
| 789 |
+
dependencies = [
|
| 790 |
+
"macro_rules_attribute-proc_macro",
|
| 791 |
+
"pastey",
|
| 792 |
+
]
|
| 793 |
+
|
| 794 |
+
[[package]]
|
| 795 |
+
name = "macro_rules_attribute-proc_macro"
|
| 796 |
+
version = "0.2.3"
|
| 797 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 798 |
+
checksum = "fc04a4c58212d57930a24bf47d3fa87485264a3a054e9c10e042eb373573ad3c"
|
| 799 |
+
|
| 800 |
+
[[package]]
|
| 801 |
+
name = "matrixmultiply"
|
| 802 |
+
version = "0.3.11"
|
| 803 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 804 |
+
checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7"
|
| 805 |
+
dependencies = [
|
| 806 |
+
"autocfg",
|
| 807 |
+
"rawpointer",
|
| 808 |
+
]
|
| 809 |
+
|
| 810 |
+
[[package]]
|
| 811 |
+
name = "memchr"
|
| 812 |
+
version = "2.8.3"
|
| 813 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 814 |
+
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
| 815 |
+
|
| 816 |
+
[[package]]
|
| 817 |
+
name = "memmap2"
|
| 818 |
+
version = "0.9.11"
|
| 819 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 820 |
+
checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0"
|
| 821 |
+
dependencies = [
|
| 822 |
+
"libc",
|
| 823 |
+
"stable_deref_trait",
|
| 824 |
+
]
|
| 825 |
+
|
| 826 |
+
[[package]]
|
| 827 |
+
name = "memoffset"
|
| 828 |
+
version = "0.9.1"
|
| 829 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 830 |
+
checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
|
| 831 |
+
dependencies = [
|
| 832 |
+
"autocfg",
|
| 833 |
+
]
|
| 834 |
+
|
| 835 |
+
[[package]]
|
| 836 |
+
name = "minimal-lexical"
|
| 837 |
+
version = "0.2.1"
|
| 838 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 839 |
+
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
|
| 840 |
+
|
| 841 |
+
[[package]]
|
| 842 |
+
name = "monostate"
|
| 843 |
+
version = "0.1.18"
|
| 844 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 845 |
+
checksum = "3341a273f6c9d5bef1908f17b7267bbab0e95c9bf69a0d4dcf8e9e1b2c76ef67"
|
| 846 |
+
dependencies = [
|
| 847 |
+
"monostate-impl",
|
| 848 |
+
"serde",
|
| 849 |
+
"serde_core",
|
| 850 |
+
]
|
| 851 |
+
|
| 852 |
+
[[package]]
|
| 853 |
+
name = "monostate-impl"
|
| 854 |
+
version = "0.1.18"
|
| 855 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 856 |
+
checksum = "e4db6d5580af57bf992f59068d4ea26fd518574ff48d7639b255a36f9de6e7e9"
|
| 857 |
+
dependencies = [
|
| 858 |
+
"proc-macro2",
|
| 859 |
+
"quote",
|
| 860 |
+
"syn 2.0.119",
|
| 861 |
+
]
|
| 862 |
+
|
| 863 |
+
[[package]]
|
| 864 |
+
name = "ndarray"
|
| 865 |
+
version = "0.16.1"
|
| 866 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 867 |
+
checksum = "882ed72dce9365842bf196bdeedf5055305f11fc8c03dee7bb0194a6cad34841"
|
| 868 |
+
dependencies = [
|
| 869 |
+
"matrixmultiply",
|
| 870 |
+
"num-complex",
|
| 871 |
+
"num-integer",
|
| 872 |
+
"num-traits",
|
| 873 |
+
"portable-atomic",
|
| 874 |
+
"portable-atomic-util",
|
| 875 |
+
"rawpointer",
|
| 876 |
+
]
|
| 877 |
+
|
| 878 |
+
[[package]]
|
| 879 |
+
name = "nom"
|
| 880 |
+
version = "7.1.3"
|
| 881 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 882 |
+
checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
|
| 883 |
+
dependencies = [
|
| 884 |
+
"memchr",
|
| 885 |
+
"minimal-lexical",
|
| 886 |
+
]
|
| 887 |
+
|
| 888 |
+
[[package]]
|
| 889 |
+
name = "num-complex"
|
| 890 |
+
version = "0.4.6"
|
| 891 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 892 |
+
checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
|
| 893 |
+
dependencies = [
|
| 894 |
+
"bytemuck",
|
| 895 |
+
"num-traits",
|
| 896 |
+
]
|
| 897 |
+
|
| 898 |
+
[[package]]
|
| 899 |
+
name = "num-integer"
|
| 900 |
+
version = "0.1.47"
|
| 901 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 902 |
+
checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
|
| 903 |
+
dependencies = [
|
| 904 |
+
"num-traits",
|
| 905 |
+
]
|
| 906 |
+
|
| 907 |
+
[[package]]
|
| 908 |
+
name = "num-traits"
|
| 909 |
+
version = "0.2.19"
|
| 910 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 911 |
+
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
| 912 |
+
dependencies = [
|
| 913 |
+
"autocfg",
|
| 914 |
+
"libm",
|
| 915 |
+
]
|
| 916 |
+
|
| 917 |
+
[[package]]
|
| 918 |
+
name = "num_cpus"
|
| 919 |
+
version = "1.17.0"
|
| 920 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 921 |
+
checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b"
|
| 922 |
+
dependencies = [
|
| 923 |
+
"hermit-abi",
|
| 924 |
+
"libc",
|
| 925 |
+
]
|
| 926 |
+
|
| 927 |
+
[[package]]
|
| 928 |
+
name = "numpy"
|
| 929 |
+
version = "0.23.0"
|
| 930 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 931 |
+
checksum = "b94caae805f998a07d33af06e6a3891e38556051b8045c615470a71590e13e78"
|
| 932 |
+
dependencies = [
|
| 933 |
+
"libc",
|
| 934 |
+
"ndarray",
|
| 935 |
+
"num-complex",
|
| 936 |
+
"num-integer",
|
| 937 |
+
"num-traits",
|
| 938 |
+
"pyo3",
|
| 939 |
+
"rustc-hash",
|
| 940 |
+
]
|
| 941 |
+
|
| 942 |
+
[[package]]
|
| 943 |
+
name = "once_cell"
|
| 944 |
+
version = "1.21.4"
|
| 945 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 946 |
+
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
| 947 |
+
|
| 948 |
+
[[package]]
|
| 949 |
+
name = "onig"
|
| 950 |
+
version = "6.5.3"
|
| 951 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 952 |
+
checksum = "0cc3cbf698f9438986c11a880c90a6d04b9de27575afd28bbf45b154b6c709e2"
|
| 953 |
+
dependencies = [
|
| 954 |
+
"bitflags",
|
| 955 |
+
"libc",
|
| 956 |
+
"once_cell",
|
| 957 |
+
"onig_sys",
|
| 958 |
+
]
|
| 959 |
+
|
| 960 |
+
[[package]]
|
| 961 |
+
name = "onig_sys"
|
| 962 |
+
version = "69.9.3"
|
| 963 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 964 |
+
checksum = "1e68317604e77e53b85896388e1a803c1d21b74c899ec9e5e1112db90735edd7"
|
| 965 |
+
dependencies = [
|
| 966 |
+
"cc",
|
| 967 |
+
"pkg-config",
|
| 968 |
+
]
|
| 969 |
+
|
| 970 |
+
[[package]]
|
| 971 |
+
name = "paste"
|
| 972 |
+
version = "1.0.15"
|
| 973 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 974 |
+
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
|
| 975 |
+
|
| 976 |
+
[[package]]
|
| 977 |
+
name = "pastey"
|
| 978 |
+
version = "0.2.3"
|
| 979 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 980 |
+
checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
|
| 981 |
+
|
| 982 |
+
[[package]]
|
| 983 |
+
name = "pin-project-lite"
|
| 984 |
+
version = "0.2.17"
|
| 985 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 986 |
+
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
| 987 |
+
|
| 988 |
+
[[package]]
|
| 989 |
+
name = "pkg-config"
|
| 990 |
+
version = "0.3.34"
|
| 991 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 992 |
+
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
|
| 993 |
+
|
| 994 |
+
[[package]]
|
| 995 |
+
name = "portable-atomic"
|
| 996 |
+
version = "1.15.0"
|
| 997 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 998 |
+
checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
|
| 999 |
+
|
| 1000 |
+
[[package]]
|
| 1001 |
+
name = "portable-atomic-util"
|
| 1002 |
+
version = "0.2.8"
|
| 1003 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1004 |
+
checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715"
|
| 1005 |
+
dependencies = [
|
| 1006 |
+
"portable-atomic",
|
| 1007 |
+
]
|
| 1008 |
+
|
| 1009 |
+
[[package]]
|
| 1010 |
+
name = "ppv-lite86"
|
| 1011 |
+
version = "0.2.21"
|
| 1012 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1013 |
+
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
|
| 1014 |
+
dependencies = [
|
| 1015 |
+
"zerocopy",
|
| 1016 |
+
]
|
| 1017 |
+
|
| 1018 |
+
[[package]]
|
| 1019 |
+
name = "proc-macro2"
|
| 1020 |
+
version = "1.0.107"
|
| 1021 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1022 |
+
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
| 1023 |
+
dependencies = [
|
| 1024 |
+
"unicode-ident",
|
| 1025 |
+
]
|
| 1026 |
+
|
| 1027 |
+
[[package]]
|
| 1028 |
+
name = "pulp"
|
| 1029 |
+
version = "0.22.3"
|
| 1030 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1031 |
+
checksum = "046aa45b989642ec2e4717c8e72d677b13edd831a4d3b6cf37d9a3e54912496a"
|
| 1032 |
+
dependencies = [
|
| 1033 |
+
"bytemuck",
|
| 1034 |
+
"cfg-if",
|
| 1035 |
+
"libm",
|
| 1036 |
+
"num-complex",
|
| 1037 |
+
"paste",
|
| 1038 |
+
"pulp-wasm-simd-flag",
|
| 1039 |
+
"raw-cpuid",
|
| 1040 |
+
"reborrow",
|
| 1041 |
+
"version_check",
|
| 1042 |
+
]
|
| 1043 |
+
|
| 1044 |
+
[[package]]
|
| 1045 |
+
name = "pulp-wasm-simd-flag"
|
| 1046 |
+
version = "0.1.1"
|
| 1047 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1048 |
+
checksum = "1d8f70e07b9c3962945a74e59ca1c511bba65b6419468acc217c457d93f3c740"
|
| 1049 |
+
|
| 1050 |
+
[[package]]
|
| 1051 |
+
name = "pyo3"
|
| 1052 |
+
version = "0.23.5"
|
| 1053 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1054 |
+
checksum = "7778bffd85cf38175ac1f545509665d0b9b92a198ca7941f131f85f7a4f9a872"
|
| 1055 |
+
dependencies = [
|
| 1056 |
+
"cfg-if",
|
| 1057 |
+
"indoc",
|
| 1058 |
+
"libc",
|
| 1059 |
+
"memoffset",
|
| 1060 |
+
"once_cell",
|
| 1061 |
+
"portable-atomic",
|
| 1062 |
+
"pyo3-build-config",
|
| 1063 |
+
"pyo3-ffi",
|
| 1064 |
+
"pyo3-macros",
|
| 1065 |
+
"unindent",
|
| 1066 |
+
]
|
| 1067 |
+
|
| 1068 |
+
[[package]]
|
| 1069 |
+
name = "pyo3-async-runtimes"
|
| 1070 |
+
version = "0.23.0"
|
| 1071 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1072 |
+
checksum = "977dc837525cfd22919ba6a831413854beb7c99a256c03bf8624ad707e45810e"
|
| 1073 |
+
dependencies = [
|
| 1074 |
+
"futures",
|
| 1075 |
+
"once_cell",
|
| 1076 |
+
"pin-project-lite",
|
| 1077 |
+
"pyo3",
|
| 1078 |
+
"tokio",
|
| 1079 |
+
]
|
| 1080 |
+
|
| 1081 |
+
[[package]]
|
| 1082 |
+
name = "pyo3-build-config"
|
| 1083 |
+
version = "0.23.5"
|
| 1084 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1085 |
+
checksum = "94f6cbe86ef3bf18998d9df6e0f3fc1050a8c5efa409bf712e661a4366e010fb"
|
| 1086 |
+
dependencies = [
|
| 1087 |
+
"once_cell",
|
| 1088 |
+
"target-lexicon",
|
| 1089 |
+
]
|
| 1090 |
+
|
| 1091 |
+
[[package]]
|
| 1092 |
+
name = "pyo3-built"
|
| 1093 |
+
version = "0.5.0"
|
| 1094 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1095 |
+
checksum = "35ee655adc94166665a1d714b439e27857dd199b947076891d6a17d32d396cde"
|
| 1096 |
+
|
| 1097 |
+
[[package]]
|
| 1098 |
+
name = "pyo3-ffi"
|
| 1099 |
+
version = "0.23.5"
|
| 1100 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1101 |
+
checksum = "e9f1b4c431c0bb1c8fb0a338709859eed0d030ff6daa34368d3b152a63dfdd8d"
|
| 1102 |
+
dependencies = [
|
| 1103 |
+
"libc",
|
| 1104 |
+
"pyo3-build-config",
|
| 1105 |
+
]
|
| 1106 |
+
|
| 1107 |
+
[[package]]
|
| 1108 |
+
name = "pyo3-log"
|
| 1109 |
+
version = "0.12.4"
|
| 1110 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1111 |
+
checksum = "45192e5e4a4d2505587e27806c7b710c231c40c56f3bfc19535d0bb25df52264"
|
| 1112 |
+
dependencies = [
|
| 1113 |
+
"arc-swap",
|
| 1114 |
+
"log",
|
| 1115 |
+
"pyo3",
|
| 1116 |
+
]
|
| 1117 |
+
|
| 1118 |
+
[[package]]
|
| 1119 |
+
name = "pyo3-macros"
|
| 1120 |
+
version = "0.23.5"
|
| 1121 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1122 |
+
checksum = "fbc2201328f63c4710f68abdf653c89d8dbc2858b88c5d88b0ff38a75288a9da"
|
| 1123 |
+
dependencies = [
|
| 1124 |
+
"proc-macro2",
|
| 1125 |
+
"pyo3-macros-backend",
|
| 1126 |
+
"quote",
|
| 1127 |
+
"syn 2.0.119",
|
| 1128 |
+
]
|
| 1129 |
+
|
| 1130 |
+
[[package]]
|
| 1131 |
+
name = "pyo3-macros-backend"
|
| 1132 |
+
version = "0.23.5"
|
| 1133 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1134 |
+
checksum = "fca6726ad0f3da9c9de093d6f116a93c1a38e417ed73bf138472cf4064f72028"
|
| 1135 |
+
dependencies = [
|
| 1136 |
+
"heck",
|
| 1137 |
+
"proc-macro2",
|
| 1138 |
+
"pyo3-build-config",
|
| 1139 |
+
"quote",
|
| 1140 |
+
"syn 2.0.119",
|
| 1141 |
+
]
|
| 1142 |
+
|
| 1143 |
+
[[package]]
|
| 1144 |
+
name = "pythonize"
|
| 1145 |
+
version = "0.23.0"
|
| 1146 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1147 |
+
checksum = "91a6ee7a084f913f98d70cdc3ebec07e852b735ae3059a1500db2661265da9ff"
|
| 1148 |
+
dependencies = [
|
| 1149 |
+
"pyo3",
|
| 1150 |
+
"serde",
|
| 1151 |
+
]
|
| 1152 |
+
|
| 1153 |
+
[[package]]
|
| 1154 |
+
name = "quote"
|
| 1155 |
+
version = "1.0.47"
|
| 1156 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1157 |
+
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
| 1158 |
+
dependencies = [
|
| 1159 |
+
"proc-macro2",
|
| 1160 |
+
]
|
| 1161 |
+
|
| 1162 |
+
[[package]]
|
| 1163 |
+
name = "r-efi"
|
| 1164 |
+
version = "5.3.0"
|
| 1165 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1166 |
+
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
|
| 1167 |
+
|
| 1168 |
+
[[package]]
|
| 1169 |
+
name = "r-efi"
|
| 1170 |
+
version = "6.0.0"
|
| 1171 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1172 |
+
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
|
| 1173 |
+
|
| 1174 |
+
[[package]]
|
| 1175 |
+
name = "rand"
|
| 1176 |
+
version = "0.8.8"
|
| 1177 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1178 |
+
checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c"
|
| 1179 |
+
dependencies = [
|
| 1180 |
+
"libc",
|
| 1181 |
+
"rand_chacha 0.3.1",
|
| 1182 |
+
"rand_core 0.6.4",
|
| 1183 |
+
]
|
| 1184 |
+
|
| 1185 |
+
[[package]]
|
| 1186 |
+
name = "rand"
|
| 1187 |
+
version = "0.9.5"
|
| 1188 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1189 |
+
checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
|
| 1190 |
+
dependencies = [
|
| 1191 |
+
"rand_chacha 0.9.0",
|
| 1192 |
+
"rand_core 0.9.5",
|
| 1193 |
+
]
|
| 1194 |
+
|
| 1195 |
+
[[package]]
|
| 1196 |
+
name = "rand_chacha"
|
| 1197 |
+
version = "0.3.1"
|
| 1198 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1199 |
+
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
|
| 1200 |
+
dependencies = [
|
| 1201 |
+
"ppv-lite86",
|
| 1202 |
+
"rand_core 0.6.4",
|
| 1203 |
+
]
|
| 1204 |
+
|
| 1205 |
+
[[package]]
|
| 1206 |
+
name = "rand_chacha"
|
| 1207 |
+
version = "0.9.0"
|
| 1208 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1209 |
+
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
|
| 1210 |
+
dependencies = [
|
| 1211 |
+
"ppv-lite86",
|
| 1212 |
+
"rand_core 0.9.5",
|
| 1213 |
+
]
|
| 1214 |
+
|
| 1215 |
+
[[package]]
|
| 1216 |
+
name = "rand_core"
|
| 1217 |
+
version = "0.6.4"
|
| 1218 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1219 |
+
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
|
| 1220 |
+
dependencies = [
|
| 1221 |
+
"getrandom 0.2.17",
|
| 1222 |
+
]
|
| 1223 |
+
|
| 1224 |
+
[[package]]
|
| 1225 |
+
name = "rand_core"
|
| 1226 |
+
version = "0.9.5"
|
| 1227 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1228 |
+
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
|
| 1229 |
+
dependencies = [
|
| 1230 |
+
"getrandom 0.3.4",
|
| 1231 |
+
]
|
| 1232 |
+
|
| 1233 |
+
[[package]]
|
| 1234 |
+
name = "rand_distr"
|
| 1235 |
+
version = "0.5.1"
|
| 1236 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1237 |
+
checksum = "6a8615d50dcf34fa31f7ab52692afec947c4dd0ab803cc87cb3b0b4570ff7463"
|
| 1238 |
+
dependencies = [
|
| 1239 |
+
"num-traits",
|
| 1240 |
+
"rand 0.9.5",
|
| 1241 |
+
]
|
| 1242 |
+
|
| 1243 |
+
[[package]]
|
| 1244 |
+
name = "raw-cpuid"
|
| 1245 |
+
version = "11.6.0"
|
| 1246 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1247 |
+
checksum = "498cd0dc59d73224351ee52a95fee0f1a617a2eae0e7d9d720cc622c73a54186"
|
| 1248 |
+
dependencies = [
|
| 1249 |
+
"bitflags",
|
| 1250 |
+
]
|
| 1251 |
+
|
| 1252 |
+
[[package]]
|
| 1253 |
+
name = "rawpointer"
|
| 1254 |
+
version = "0.2.1"
|
| 1255 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1256 |
+
checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3"
|
| 1257 |
+
|
| 1258 |
+
[[package]]
|
| 1259 |
+
name = "rayon"
|
| 1260 |
+
version = "1.12.0"
|
| 1261 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1262 |
+
checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"
|
| 1263 |
+
dependencies = [
|
| 1264 |
+
"either",
|
| 1265 |
+
"rayon-core",
|
| 1266 |
+
]
|
| 1267 |
+
|
| 1268 |
+
[[package]]
|
| 1269 |
+
name = "rayon-cond"
|
| 1270 |
+
version = "0.4.0"
|
| 1271 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1272 |
+
checksum = "2964d0cf57a3e7a06e8183d14a8b527195c706b7983549cd5462d5aa3747438f"
|
| 1273 |
+
dependencies = [
|
| 1274 |
+
"either",
|
| 1275 |
+
"itertools",
|
| 1276 |
+
"rayon",
|
| 1277 |
+
]
|
| 1278 |
+
|
| 1279 |
+
[[package]]
|
| 1280 |
+
name = "rayon-core"
|
| 1281 |
+
version = "1.13.0"
|
| 1282 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1283 |
+
checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
|
| 1284 |
+
dependencies = [
|
| 1285 |
+
"crossbeam-deque",
|
| 1286 |
+
"crossbeam-utils",
|
| 1287 |
+
]
|
| 1288 |
+
|
| 1289 |
+
[[package]]
|
| 1290 |
+
name = "reborrow"
|
| 1291 |
+
version = "0.5.5"
|
| 1292 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1293 |
+
checksum = "03251193000f4bd3b042892be858ee50e8b3719f2b08e5833ac4353724632430"
|
| 1294 |
+
|
| 1295 |
+
[[package]]
|
| 1296 |
+
name = "regex"
|
| 1297 |
+
version = "1.13.1"
|
| 1298 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1299 |
+
checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
|
| 1300 |
+
dependencies = [
|
| 1301 |
+
"aho-corasick",
|
| 1302 |
+
"memchr",
|
| 1303 |
+
"regex-automata",
|
| 1304 |
+
"regex-syntax",
|
| 1305 |
+
]
|
| 1306 |
+
|
| 1307 |
+
[[package]]
|
| 1308 |
+
name = "regex-automata"
|
| 1309 |
+
version = "0.4.18"
|
| 1310 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1311 |
+
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
|
| 1312 |
+
dependencies = [
|
| 1313 |
+
"aho-corasick",
|
| 1314 |
+
"memchr",
|
| 1315 |
+
"regex-syntax",
|
| 1316 |
+
]
|
| 1317 |
+
|
| 1318 |
+
[[package]]
|
| 1319 |
+
name = "regex-syntax"
|
| 1320 |
+
version = "0.8.11"
|
| 1321 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1322 |
+
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
|
| 1323 |
+
|
| 1324 |
+
[[package]]
|
| 1325 |
+
name = "rustc-hash"
|
| 1326 |
+
version = "2.1.3"
|
| 1327 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1328 |
+
checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
|
| 1329 |
+
|
| 1330 |
+
[[package]]
|
| 1331 |
+
name = "rustix"
|
| 1332 |
+
version = "1.1.5"
|
| 1333 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1334 |
+
checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"
|
| 1335 |
+
dependencies = [
|
| 1336 |
+
"bitflags",
|
| 1337 |
+
"errno",
|
| 1338 |
+
"libc",
|
| 1339 |
+
"linux-raw-sys",
|
| 1340 |
+
"windows-sys",
|
| 1341 |
+
]
|
| 1342 |
+
|
| 1343 |
+
[[package]]
|
| 1344 |
+
name = "rustversion"
|
| 1345 |
+
version = "1.0.23"
|
| 1346 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1347 |
+
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
| 1348 |
+
|
| 1349 |
+
[[package]]
|
| 1350 |
+
name = "ryu"
|
| 1351 |
+
version = "1.0.23"
|
| 1352 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1353 |
+
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
|
| 1354 |
+
|
| 1355 |
+
[[package]]
|
| 1356 |
+
name = "safetensors"
|
| 1357 |
+
version = "0.8.0"
|
| 1358 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1359 |
+
checksum = "79b079b829cb27a1c3c374341345ed2e8b2c0c839034522cee576c140bd7f846"
|
| 1360 |
+
dependencies = [
|
| 1361 |
+
"hashbrown 0.16.1",
|
| 1362 |
+
"libc",
|
| 1363 |
+
"serde",
|
| 1364 |
+
"serde_json",
|
| 1365 |
+
"tempfile",
|
| 1366 |
+
]
|
| 1367 |
+
|
| 1368 |
+
[[package]]
|
| 1369 |
+
name = "same-file"
|
| 1370 |
+
version = "1.0.6"
|
| 1371 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1372 |
+
checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
|
| 1373 |
+
dependencies = [
|
| 1374 |
+
"winapi-util",
|
| 1375 |
+
]
|
| 1376 |
+
|
| 1377 |
+
[[package]]
|
| 1378 |
+
name = "seq-macro"
|
| 1379 |
+
version = "0.3.6"
|
| 1380 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1381 |
+
checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc"
|
| 1382 |
+
|
| 1383 |
+
[[package]]
|
| 1384 |
+
name = "serde"
|
| 1385 |
+
version = "1.0.229"
|
| 1386 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1387 |
+
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
| 1388 |
+
dependencies = [
|
| 1389 |
+
"serde_core",
|
| 1390 |
+
"serde_derive",
|
| 1391 |
+
]
|
| 1392 |
+
|
| 1393 |
+
[[package]]
|
| 1394 |
+
name = "serde_core"
|
| 1395 |
+
version = "1.0.229"
|
| 1396 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1397 |
+
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
| 1398 |
+
dependencies = [
|
| 1399 |
+
"serde_derive",
|
| 1400 |
+
]
|
| 1401 |
+
|
| 1402 |
+
[[package]]
|
| 1403 |
+
name = "serde_derive"
|
| 1404 |
+
version = "1.0.229"
|
| 1405 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1406 |
+
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
| 1407 |
+
dependencies = [
|
| 1408 |
+
"proc-macro2",
|
| 1409 |
+
"quote",
|
| 1410 |
+
"syn 3.0.9",
|
| 1411 |
+
]
|
| 1412 |
+
|
| 1413 |
+
[[package]]
|
| 1414 |
+
name = "serde_json"
|
| 1415 |
+
version = "1.0.154"
|
| 1416 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1417 |
+
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
|
| 1418 |
+
dependencies = [
|
| 1419 |
+
"itoa",
|
| 1420 |
+
"memchr",
|
| 1421 |
+
"serde",
|
| 1422 |
+
"serde_core",
|
| 1423 |
+
"zmij",
|
| 1424 |
+
]
|
| 1425 |
+
|
| 1426 |
+
[[package]]
|
| 1427 |
+
name = "shlex"
|
| 1428 |
+
version = "2.0.1"
|
| 1429 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1430 |
+
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
| 1431 |
+
|
| 1432 |
+
[[package]]
|
| 1433 |
+
name = "slab"
|
| 1434 |
+
version = "0.4.12"
|
| 1435 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1436 |
+
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
|
| 1437 |
+
|
| 1438 |
+
[[package]]
|
| 1439 |
+
name = "smallvec"
|
| 1440 |
+
version = "1.16.3"
|
| 1441 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1442 |
+
checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b"
|
| 1443 |
+
|
| 1444 |
+
[[package]]
|
| 1445 |
+
name = "spm_precompiled"
|
| 1446 |
+
version = "0.1.4"
|
| 1447 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1448 |
+
checksum = "5851699c4033c63636f7ea4cf7b7c1f1bf06d0cc03cfb42e711de5a5c46cf326"
|
| 1449 |
+
dependencies = [
|
| 1450 |
+
"base64",
|
| 1451 |
+
"nom",
|
| 1452 |
+
"serde",
|
| 1453 |
+
"unicode-segmentation",
|
| 1454 |
+
]
|
| 1455 |
+
|
| 1456 |
+
[[package]]
|
| 1457 |
+
name = "stable_deref_trait"
|
| 1458 |
+
version = "1.2.1"
|
| 1459 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1460 |
+
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
|
| 1461 |
+
|
| 1462 |
+
[[package]]
|
| 1463 |
+
name = "static_assertions"
|
| 1464 |
+
version = "1.1.0"
|
| 1465 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1466 |
+
checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
|
| 1467 |
+
|
| 1468 |
+
[[package]]
|
| 1469 |
+
name = "strsim"
|
| 1470 |
+
version = "0.11.1"
|
| 1471 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1472 |
+
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
|
| 1473 |
+
|
| 1474 |
+
[[package]]
|
| 1475 |
+
name = "syn"
|
| 1476 |
+
version = "1.0.109"
|
| 1477 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1478 |
+
checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
|
| 1479 |
+
dependencies = [
|
| 1480 |
+
"proc-macro2",
|
| 1481 |
+
"quote",
|
| 1482 |
+
"unicode-ident",
|
| 1483 |
+
]
|
| 1484 |
+
|
| 1485 |
+
[[package]]
|
| 1486 |
+
name = "syn"
|
| 1487 |
+
version = "2.0.119"
|
| 1488 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1489 |
+
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
|
| 1490 |
+
dependencies = [
|
| 1491 |
+
"proc-macro2",
|
| 1492 |
+
"quote",
|
| 1493 |
+
"unicode-ident",
|
| 1494 |
+
]
|
| 1495 |
+
|
| 1496 |
+
[[package]]
|
| 1497 |
+
name = "syn"
|
| 1498 |
+
version = "3.0.9"
|
| 1499 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1500 |
+
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
|
| 1501 |
+
dependencies = [
|
| 1502 |
+
"proc-macro2",
|
| 1503 |
+
"quote",
|
| 1504 |
+
"unicode-ident",
|
| 1505 |
+
]
|
| 1506 |
+
|
| 1507 |
+
[[package]]
|
| 1508 |
+
name = "synstructure"
|
| 1509 |
+
version = "0.14.0"
|
| 1510 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1511 |
+
checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"
|
| 1512 |
+
dependencies = [
|
| 1513 |
+
"proc-macro2",
|
| 1514 |
+
"quote",
|
| 1515 |
+
"syn 3.0.9",
|
| 1516 |
+
]
|
| 1517 |
+
|
| 1518 |
+
[[package]]
|
| 1519 |
+
name = "sysctl"
|
| 1520 |
+
version = "0.6.0"
|
| 1521 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1522 |
+
checksum = "01198a2debb237c62b6826ec7081082d951f46dbb64b0e8c7649a452230d1dfc"
|
| 1523 |
+
dependencies = [
|
| 1524 |
+
"bitflags",
|
| 1525 |
+
"byteorder",
|
| 1526 |
+
"enum-as-inner",
|
| 1527 |
+
"libc",
|
| 1528 |
+
"thiserror 1.0.69",
|
| 1529 |
+
"walkdir",
|
| 1530 |
+
]
|
| 1531 |
+
|
| 1532 |
+
[[package]]
|
| 1533 |
+
name = "target-lexicon"
|
| 1534 |
+
version = "0.12.16"
|
| 1535 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1536 |
+
checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"
|
| 1537 |
+
|
| 1538 |
+
[[package]]
|
| 1539 |
+
name = "tempfile"
|
| 1540 |
+
version = "3.27.0"
|
| 1541 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1542 |
+
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
| 1543 |
+
dependencies = [
|
| 1544 |
+
"fastrand",
|
| 1545 |
+
"getrandom 0.4.3",
|
| 1546 |
+
"once_cell",
|
| 1547 |
+
"rustix",
|
| 1548 |
+
"windows-sys",
|
| 1549 |
+
]
|
| 1550 |
+
|
| 1551 |
+
[[package]]
|
| 1552 |
+
name = "thiserror"
|
| 1553 |
+
version = "1.0.69"
|
| 1554 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1555 |
+
checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
|
| 1556 |
+
dependencies = [
|
| 1557 |
+
"thiserror-impl 1.0.69",
|
| 1558 |
+
]
|
| 1559 |
+
|
| 1560 |
+
[[package]]
|
| 1561 |
+
name = "thiserror"
|
| 1562 |
+
version = "2.0.21"
|
| 1563 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1564 |
+
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
|
| 1565 |
+
dependencies = [
|
| 1566 |
+
"thiserror-impl 2.0.21",
|
| 1567 |
+
]
|
| 1568 |
+
|
| 1569 |
+
[[package]]
|
| 1570 |
+
name = "thiserror-impl"
|
| 1571 |
+
version = "1.0.69"
|
| 1572 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1573 |
+
checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
|
| 1574 |
+
dependencies = [
|
| 1575 |
+
"proc-macro2",
|
| 1576 |
+
"quote",
|
| 1577 |
+
"syn 2.0.119",
|
| 1578 |
+
]
|
| 1579 |
+
|
| 1580 |
+
[[package]]
|
| 1581 |
+
name = "thiserror-impl"
|
| 1582 |
+
version = "2.0.21"
|
| 1583 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1584 |
+
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
|
| 1585 |
+
dependencies = [
|
| 1586 |
+
"proc-macro2",
|
| 1587 |
+
"quote",
|
| 1588 |
+
"syn 3.0.9",
|
| 1589 |
+
]
|
| 1590 |
+
|
| 1591 |
+
[[package]]
|
| 1592 |
+
name = "tokenizers"
|
| 1593 |
+
version = "0.22.2"
|
| 1594 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1595 |
+
checksum = "b238e22d44a15349529690fb07bd645cf58149a1b1e44d6cb5bd1641ff1a6223"
|
| 1596 |
+
dependencies = [
|
| 1597 |
+
"ahash",
|
| 1598 |
+
"aho-corasick",
|
| 1599 |
+
"compact_str",
|
| 1600 |
+
"dary_heap",
|
| 1601 |
+
"derive_builder",
|
| 1602 |
+
"esaxx-rs",
|
| 1603 |
+
"getrandom 0.3.4",
|
| 1604 |
+
"itertools",
|
| 1605 |
+
"log",
|
| 1606 |
+
"macro_rules_attribute",
|
| 1607 |
+
"monostate",
|
| 1608 |
+
"onig",
|
| 1609 |
+
"paste",
|
| 1610 |
+
"rand 0.9.5",
|
| 1611 |
+
"rayon",
|
| 1612 |
+
"rayon-cond",
|
| 1613 |
+
"regex",
|
| 1614 |
+
"regex-syntax",
|
| 1615 |
+
"serde",
|
| 1616 |
+
"serde_json",
|
| 1617 |
+
"spm_precompiled",
|
| 1618 |
+
"thiserror 2.0.21",
|
| 1619 |
+
"unicode-normalization-alignments",
|
| 1620 |
+
"unicode-segmentation",
|
| 1621 |
+
"unicode_categories",
|
| 1622 |
+
]
|
| 1623 |
+
|
| 1624 |
+
[[package]]
|
| 1625 |
+
name = "tokio"
|
| 1626 |
+
version = "1.54.0"
|
| 1627 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1628 |
+
checksum = "a0c168a474b95bfecfe908a65d4bdffc523144b649a74c09c286afb35d53e0bc"
|
| 1629 |
+
dependencies = [
|
| 1630 |
+
"pin-project-lite",
|
| 1631 |
+
]
|
| 1632 |
+
|
| 1633 |
+
[[package]]
|
| 1634 |
+
name = "typed-path"
|
| 1635 |
+
version = "0.12.4"
|
| 1636 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1637 |
+
checksum = "54ec2755506471f54baf5e4bb5499d8e510cc1caf271270e778a736bd2d7336c"
|
| 1638 |
+
|
| 1639 |
+
[[package]]
|
| 1640 |
+
name = "unicode-ident"
|
| 1641 |
+
version = "1.0.27"
|
| 1642 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1643 |
+
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
| 1644 |
+
|
| 1645 |
+
[[package]]
|
| 1646 |
+
name = "unicode-normalization-alignments"
|
| 1647 |
+
version = "0.1.12"
|
| 1648 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1649 |
+
checksum = "43f613e4fa046e69818dd287fdc4bc78175ff20331479dab6e1b0f98d57062de"
|
| 1650 |
+
dependencies = [
|
| 1651 |
+
"smallvec",
|
| 1652 |
+
]
|
| 1653 |
+
|
| 1654 |
+
[[package]]
|
| 1655 |
+
name = "unicode-segmentation"
|
| 1656 |
+
version = "1.13.3"
|
| 1657 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1658 |
+
checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
|
| 1659 |
+
|
| 1660 |
+
[[package]]
|
| 1661 |
+
name = "unicode_categories"
|
| 1662 |
+
version = "0.1.1"
|
| 1663 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1664 |
+
checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e"
|
| 1665 |
+
|
| 1666 |
+
[[package]]
|
| 1667 |
+
name = "unindent"
|
| 1668 |
+
version = "0.2.4"
|
| 1669 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1670 |
+
checksum = "7264e107f553ccae879d21fbea1d6724ac785e8c3bfc762137959b5802826ef3"
|
| 1671 |
+
|
| 1672 |
+
[[package]]
|
| 1673 |
+
name = "version_check"
|
| 1674 |
+
version = "0.9.5"
|
| 1675 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1676 |
+
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
| 1677 |
+
|
| 1678 |
+
[[package]]
|
| 1679 |
+
name = "walkdir"
|
| 1680 |
+
version = "2.5.0"
|
| 1681 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1682 |
+
checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
|
| 1683 |
+
dependencies = [
|
| 1684 |
+
"same-file",
|
| 1685 |
+
"winapi-util",
|
| 1686 |
+
]
|
| 1687 |
+
|
| 1688 |
+
[[package]]
|
| 1689 |
+
name = "wasi"
|
| 1690 |
+
version = "0.11.1+wasi-snapshot-preview1"
|
| 1691 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1692 |
+
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
|
| 1693 |
+
|
| 1694 |
+
[[package]]
|
| 1695 |
+
name = "wasip2"
|
| 1696 |
+
version = "1.0.4+wasi-0.2.12"
|
| 1697 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1698 |
+
checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"
|
| 1699 |
+
dependencies = [
|
| 1700 |
+
"wit-bindgen",
|
| 1701 |
+
]
|
| 1702 |
+
|
| 1703 |
+
[[package]]
|
| 1704 |
+
name = "winapi-util"
|
| 1705 |
+
version = "0.1.11"
|
| 1706 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1707 |
+
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
| 1708 |
+
dependencies = [
|
| 1709 |
+
"windows-sys",
|
| 1710 |
+
]
|
| 1711 |
+
|
| 1712 |
+
[[package]]
|
| 1713 |
+
name = "windows-link"
|
| 1714 |
+
version = "0.2.1"
|
| 1715 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1716 |
+
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
| 1717 |
+
|
| 1718 |
+
[[package]]
|
| 1719 |
+
name = "windows-sys"
|
| 1720 |
+
version = "0.61.2"
|
| 1721 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1722 |
+
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
|
| 1723 |
+
dependencies = [
|
| 1724 |
+
"windows-link",
|
| 1725 |
+
]
|
| 1726 |
+
|
| 1727 |
+
[[package]]
|
| 1728 |
+
name = "wit-bindgen"
|
| 1729 |
+
version = "0.57.1"
|
| 1730 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1731 |
+
checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
|
| 1732 |
+
|
| 1733 |
+
[[package]]
|
| 1734 |
+
name = "yoke"
|
| 1735 |
+
version = "0.8.3"
|
| 1736 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1737 |
+
checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"
|
| 1738 |
+
dependencies = [
|
| 1739 |
+
"stable_deref_trait",
|
| 1740 |
+
"yoke-derive",
|
| 1741 |
+
"zerofrom",
|
| 1742 |
+
]
|
| 1743 |
+
|
| 1744 |
+
[[package]]
|
| 1745 |
+
name = "yoke-derive"
|
| 1746 |
+
version = "0.8.4"
|
| 1747 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1748 |
+
checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"
|
| 1749 |
+
dependencies = [
|
| 1750 |
+
"proc-macro2",
|
| 1751 |
+
"quote",
|
| 1752 |
+
"syn 3.0.9",
|
| 1753 |
+
"synstructure",
|
| 1754 |
+
]
|
| 1755 |
+
|
| 1756 |
+
[[package]]
|
| 1757 |
+
name = "zerocopy"
|
| 1758 |
+
version = "0.8.63"
|
| 1759 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1760 |
+
checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8"
|
| 1761 |
+
dependencies = [
|
| 1762 |
+
"zerocopy-derive",
|
| 1763 |
+
]
|
| 1764 |
+
|
| 1765 |
+
[[package]]
|
| 1766 |
+
name = "zerocopy-derive"
|
| 1767 |
+
version = "0.8.63"
|
| 1768 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1769 |
+
checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f"
|
| 1770 |
+
dependencies = [
|
| 1771 |
+
"proc-macro2",
|
| 1772 |
+
"quote",
|
| 1773 |
+
"syn 2.0.119",
|
| 1774 |
+
]
|
| 1775 |
+
|
| 1776 |
+
[[package]]
|
| 1777 |
+
name = "zerofrom"
|
| 1778 |
+
version = "0.1.8"
|
| 1779 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1780 |
+
checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
|
| 1781 |
+
dependencies = [
|
| 1782 |
+
"zerofrom-derive",
|
| 1783 |
+
]
|
| 1784 |
+
|
| 1785 |
+
[[package]]
|
| 1786 |
+
name = "zerofrom-derive"
|
| 1787 |
+
version = "0.1.8"
|
| 1788 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1789 |
+
checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"
|
| 1790 |
+
dependencies = [
|
| 1791 |
+
"proc-macro2",
|
| 1792 |
+
"quote",
|
| 1793 |
+
"syn 3.0.9",
|
| 1794 |
+
"synstructure",
|
| 1795 |
+
]
|
| 1796 |
+
|
| 1797 |
+
[[package]]
|
| 1798 |
+
name = "zip"
|
| 1799 |
+
version = "8.6.0"
|
| 1800 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1801 |
+
checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b"
|
| 1802 |
+
dependencies = [
|
| 1803 |
+
"crc32fast",
|
| 1804 |
+
"indexmap",
|
| 1805 |
+
"memchr",
|
| 1806 |
+
"typed-path",
|
| 1807 |
+
]
|
| 1808 |
+
|
| 1809 |
+
[[package]]
|
| 1810 |
+
name = "zmij"
|
| 1811 |
+
version = "1.0.23"
|
| 1812 |
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1813 |
+
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
laboratorio/Cargo.toml
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[package]
|
| 2 |
+
name = "khtst-rust"
|
| 3 |
+
version = "0.21.0"
|
| 4 |
+
edition = "2021"
|
| 5 |
+
description = "KHTST_RUST v0.16 (r-52): TC com features quadraticas (classe contem o otimo gaussiano, convexo), enxame adaptativo por dificuldade + gatilho de degradacao, gate por banda, codebooks compartilhados (EMA de Gram), foco JEPA (movimento/contraste), gate de atencao autoajustado, resolucao do nao-determinismo por variantes simultaneas com CRN + selecao pessimista contextual, painel de metricas completo — defaults bit-a-bit v0.14 preservados"
|
| 6 |
+
license = "Apache-2.0"
|
| 7 |
+
|
| 8 |
+
[lib]
|
| 9 |
+
name = "khtst_rust"
|
| 10 |
+
crate-type = ["cdylib", "rlib"]
|
| 11 |
+
|
| 12 |
+
[dependencies]
|
| 13 |
+
pyo3 = { version = "0.23", features = ["abi3-py310"] }
|
| 14 |
+
numpy = "0.23"
|
| 15 |
+
pythonize = "0.23"
|
| 16 |
+
pyo3-log = "0.12"
|
| 17 |
+
dict_derive = "0.5"
|
| 18 |
+
pyo3-built = "0.5"
|
| 19 |
+
pyo3-async-runtimes = { version = "0.23", optional = true, features = ["tokio-runtime"] }
|
| 20 |
+
tokio = { version = "1", features = ["rt-multi-thread"], optional = true }
|
| 21 |
+
candle-core = "0.11"
|
| 22 |
+
candle-nn = "0.11"
|
| 23 |
+
crossbeam-channel = "0.5"
|
| 24 |
+
rayon = "1"
|
| 25 |
+
serde = { version = "1", features = ["derive"] }
|
| 26 |
+
serde_json = "1"
|
| 27 |
+
anyhow = "1"
|
| 28 |
+
thiserror = "2"
|
| 29 |
+
log = "0.4"
|
| 30 |
+
rand = "0.8"
|
| 31 |
+
|
| 32 |
+
[build-dependencies]
|
| 33 |
+
built = "0.8"
|
| 34 |
+
|
| 35 |
+
[features]
|
| 36 |
+
default = ["ponte_async"]
|
| 37 |
+
ponte_async = ["pyo3-async-runtimes", "tokio"]
|
| 38 |
+
|
| 39 |
+
[profile.release]
|
| 40 |
+
opt-level = 3
|
| 41 |
+
debug = false
|
| 42 |
+
|
| 43 |
+
# ---------------------------------------------------------------------------
|
| 44 |
+
# WORKSPACE DO LABORATÓRIO (ciclo lab-01)
|
| 45 |
+
#
|
| 46 |
+
# O laboratório adiciona o membro `laboratorio-core`: núcleo de verificação
|
| 47 |
+
# SEM candle/pyo3 (std + serde_json), que compila e roda em qualquer máquina
|
| 48 |
+
# e sustenta as bancadas com dados reais (bins `bancada_memoria` e
|
| 49 |
+
# `laboratorio_ab`). O pacote raiz (khtst-rust) permanece intacto — a
|
| 50 |
+
# integração é opt-in e não altera o caminho publicado.
|
| 51 |
+
# ---------------------------------------------------------------------------
|
| 52 |
+
[workspace]
|
| 53 |
+
members = ["laboratorio-core"]
|
| 54 |
+
resolver = "2"
|
laboratorio/ESTRUTURA.md
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ESTRUTURA — inventário de componentes e FALTAS verificadas
|
| 2 |
+
|
| 3 |
+
> Método: existência real de arquivo + conteúdo verificado
|
| 4 |
+
> (`scripts/10_verificar_componentes.py`, saída em
|
| 5 |
+
> `resultados/inventario_componentes.json`). Nada por estimativa.
|
| 6 |
+
> Análise executada sobre a branch publicada `main`
|
| 7 |
+
> (sha `abec05391f506831c9cb760bb61a182544820a6e`, 2026-11-16,
|
| 8 |
+
> 361 entradas, 7,2 MB) e sobre este laboratório.
|
| 9 |
+
|
| 10 |
+
## 1. O que a branch publicada TEM (20 componentes verificados)
|
| 11 |
+
|
| 12 |
+
- **Núcleo Rust completo v0.13–v0.17**: `src/lib.rs` (com a convenção
|
| 13 |
+
"token EXCLUSIVAMENTE em HF_TOKEN apagado após uso"), `src/treino.rs`,
|
| 14 |
+
`src/gerador.rs`, `src/tronco.rs` (5 ADBA + 1 SSD), `src/memoria.rs`,
|
| 15 |
+
`src/som4d.rs`, `src/pensamento/`, `src/python/` (PyO3), ASM/intrínsecos
|
| 16 |
+
(`src/asm.rs`, `src/asm_x86.rs`, `src/simd.rs`), `src/v013..v017`.
|
| 17 |
+
- **Suítes e scripts 39–90** (coleta controlada, treino, gates, publicação).
|
| 18 |
+
- **Memórias r-00..r-55** + `memoria-ncm-khtst/` + `docs/referencias/`.
|
| 19 |
+
- **Dados reais**: `dados/shard_treino.jsonl` (246 artigos Wikipédia PT-BR),
|
| 20 |
+
`shard_validacao.jsonl` (27), `bpe.json`.
|
| 21 |
+
- **Infra**: `Cargo.toml`, `Cargo.lock`, `build.rs`, `pyproject.toml`,
|
| 22 |
+
`python/khtst_rust/`, `tests/provas.rs`, `LICENSE` (Apache-2.0),
|
| 23 |
+
`README.md` (v0.17), `configs/` (4), `resultados/` (63 artefatos),
|
| 24 |
+
`arquivo_split_v100/` (34 arquivos — árvore futura dividida).
|
| 25 |
+
|
| 26 |
+
## 2. O que a branch publicada NÃO TEM (36 faltas verificadas)
|
| 27 |
+
|
| 28 |
+
### 2.1 Módulos dos ciclos v0.18–v0.21 (documentados nos anexos r-63/r-64, ausentes no repo)
|
| 29 |
+
|
| 30 |
+
| componente | estado | evidência |
|
| 31 |
+
|---|---|---|
|
| 32 |
+
| `src/v018/capacidade.rs` | **AUSENTE** | sem `src/v018/` |
|
| 33 |
+
| `src/v018/roteamento_ot.rs` | **AUSENTE** | idem |
|
| 34 |
+
| `src/v019/mapa_som.rs` | **AUSENTE** | sem `src/v019/` |
|
| 35 |
+
| `src/v019/autorregulacao.rs` | **AUSENTE** | idem |
|
| 36 |
+
| `src/v019/jepa_variantes.rs` | **AUSENTE** | idem |
|
| 37 |
+
| `src/v019/ponte_bidirecional.rs` | **AUSENTE** | idem |
|
| 38 |
+
| `src/v019/crescimento.rs` | **AUSENTE** | idem |
|
| 39 |
+
| `src/v020/atencao_multimodal.rs` | **AUSENTE** | sem `src/v020/` |
|
| 40 |
+
| `src/v021/memoria_crescente.rs` | **AUSENTE** | sem `src/v021/` |
|
| 41 |
+
| `src/v021/treino_autorregulado.rs` | **AUSENTE** | idem |
|
| 42 |
+
| `src/v021/jepa_pleno.rs` | **AUSENTE** | idem |
|
| 43 |
+
| `src/v021/tronco_crescente.rs` | **AUSENTE** | idem |
|
| 44 |
+
| `src/v021/provas_*.rs` (4 arquivos) | **AUSENTE** | idem |
|
| 45 |
+
| `src/bin/memoria_v021.rs` | **AUSENTE** | `src/bin/` só tem `bench_v011/bench_v090` |
|
| 46 |
+
|
| 47 |
+
### 2.2 Suítes, memórias e documentação
|
| 48 |
+
|
| 49 |
+
| componente | estado | evidência |
|
| 50 |
+
|---|---|---|
|
| 51 |
+
| `scripts/91..96` (suites v0.18–v0.21, incl. `96_suite_v021.py`, `95_execucao_segura.py`) | **AUSENTE** | maior script = `90_publicar_v016.py` |
|
| 52 |
+
| `docs/memorias/r-56..r-64` (incl. r-63 provas e r-64 resultados v0.21) | **AUSENTE** | maior memória = r-55 |
|
| 53 |
+
| banner **DIVERGENTE** em `docs/referencias/*.md` | **AUSENTE** | `grep DIVERGENTE` → 0 nos 6 arquivos |
|
| 54 |
+
| quadro de equivalências no repo | **AUSENTE** | idem |
|
| 55 |
+
|
| 56 |
+
### 2.3 Consistência e infraestrutura
|
| 57 |
+
|
| 58 |
+
| componente | estado | evidência |
|
| 59 |
+
|---|---|---|
|
| 60 |
+
| `Cargo.toml` version = README | **INCONSISTENTE** | Cargo `0.16.0` × README "v0.17.0" |
|
| 61 |
+
| demos Python das fases (r-64 §7: "integração no Python PARCIAL") | **PARCIAL** | `python/khtst_rust/` só tem binding |
|
| 62 |
+
| CI / teste de regressão automática | **AUSENTE** | nenhum workflow no repo |
|
| 63 |
+
| teste do caminho REAL (máscara + cache) da atenção | **AUSENTE** | os 3 defeitos D-A/D-B/D-C do v0.20 só foram pegos no v0.21 porque os testes do v0.20 exercitavam o caminho feliz |
|
| 64 |
+
|
| 65 |
+
## 3. Como o laboratório fecha as faltas (nível executável)
|
| 66 |
+
|
| 67 |
+
| falta | fechamento no laboratório |
|
| 68 |
+
|---|---|
|
| 69 |
+
| `v019/mapa_som.rs` + critério relativo | `lab/mapa_som.py` (paridade semântica + histerese nova) |
|
| 70 |
+
| `v021/memoria_crescente.rs` | `lab/memoria_crescente.py` (paridade + lei corrigida opt-in) |
|
| 71 |
+
| `v019/autorregulacao.rs` + `v020/ciclo_limite` | `lab/autorregulacao.py` |
|
| 72 |
+
| `v021/jepa_pleno.rs` | `lab/jepa.py` (energia + equilíbrio desenrolado + anti-colapso no objetivo, torch f64) |
|
| 73 |
+
| `scripts/96_suite_v021.py` | `scripts/90_suite_laboratorio.py` (gates L1..L7) |
|
| 74 |
+
| `src/bin/memoria_v021.rs` | `scripts/31_bancada_mapa.py` (a mesma bancada, dados reais) |
|
| 75 |
+
| banner divergente + equivalências | `docs/equivalencias.md` + banners aqui |
|
| 76 |
+
| memórias r-63/r-64 | `docs/r-65-laboratorio.md` (registro do ciclo, formato r-XX) |
|
| 77 |
+
| teste do caminho real | bancadas com máscaras determinísticas, held-out disjunto e controles não-vácuos (T-L7 controle de passo, T-L8 controle de 1ª ordem, T-L9 controle de colapso) |
|
| 78 |
+
| consistência de versão | `README.md` e configs do laboratório declarados `0.22.0-lab` |
|
| 79 |
+
| `39_coletar_dados.py` depende de `datasets` (indisponível) | `scripts/20_dados_reais.py` consome o shard REAL já publicado + digits offline (sem dependência nova de rede) |
|
| 80 |
+
|
| 81 |
+
## 4. O que o laboratório NÃO fecha (declarado, não omitido)
|
| 82 |
+
|
| 83 |
+
1. **Código Rust dos ciclos v0.18–v0.21**: o laboratório reproduz a
|
| 84 |
+
MATEMÁTICA em Python com paridade semântica; os módulos Rust originais
|
| 85 |
+
continuam na árvore divergente. `rust/patches-v022/` propõe os três
|
| 86 |
+
patches de correção para o repo principal (fonte rotulada — `cargo`
|
| 87 |
+
não existe neste ambiente, o que está declarado em cada patch).
|
| 88 |
+
2. **Paridade bit-a-bit com o Rust**: impossível sem o mesmo RNG
|
| 89 |
+
(`StdRng`); a paridade é SEMÂNTICA (mesmas grandezas, unidades e
|
| 90 |
+
contratos).
|
| 91 |
+
3. **ADBA/tronco/ponte/PyO3**: fora do escopo do laboratório (a bancada
|
| 92 |
+
de atenção com máscara+cache exigiria o `candle`; a lição D-A/D-B/D-C
|
| 93 |
+
está registrada em AUTOCRITICA §5.4 e nos testes não-vácuos aqui).
|
| 94 |
+
4. **Verificação de unidade no código Rust publicado**: proposta como
|
| 95 |
+
patch; sem `cargo` nada é compilado aqui.
|
laboratorio/LICENSE
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Apache License 2.0 — ver https://www.apache.org/licenses/LICENSE-2.0
|
laboratorio/README.md
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LABORATÓRIO v0.22-lab — khtst-rust
|
| 2 |
+
|
| 3 |
+
> **O que é.** Um projeto novo, auto-contido e EXECUTÁVEL, que (1) audita
|
| 4 |
+
> a branch publicada de `PowerMachine/khtst-rust`, (2) reproduz em Python
|
| 5 |
+
> a matemática central dos ciclos v0.18–v0.21 com paridade semântica,
|
| 6 |
+
> (3) fecha a dívida de integração lab-A1 (o laço de regulação tautológico)
|
| 7 |
+
> com correção **opt-in** e (4) mede cada aprimoramento sobre **dados reais**
|
| 8 |
+
> — os mesmos 246 artigos da Wikipédia PT-BR do ciclo v0.21 e 1797 dígitos
|
| 9 |
+
> manuscritos reais. Nenhum número aqui vem de estimativa: cada afirmação
|
| 10 |
+
> tem um JSON de resultado e um teste que o recusa.
|
| 11 |
+
|
| 12 |
+
## Como rodar (ordem canônica)
|
| 13 |
+
|
| 14 |
+
```bash
|
| 15 |
+
python3 -m lab.rng # T-L14: determinismo e Box–Muller
|
| 16 |
+
python3 -m lab.mapa_som # T-L1/T-L2: não-crescência e divisão conservadora
|
| 17 |
+
python3 -m lab.memoria_crescente # T-L4: conjuntos disjuntos + guarda de unidades
|
| 18 |
+
python3 -m lab.som # auto-organização observada (TE Moore)
|
| 19 |
+
python3 -m lab.jepa # T-L7/T-L9 (equilíbrio + piso)
|
| 20 |
+
|
| 21 |
+
python3 scripts/10_verificar_componentes.py [raiz_do_repo] # inventário e FALTAS
|
| 22 |
+
python3 scripts/20_dados_reais.py # dados reais → vetores
|
| 23 |
+
python3 scripts/31_bancada_mapa.py # absoluto × relativo × histerese
|
| 24 |
+
python3 scripts/32_bancada_limiar.py # laço morto × laço corrigido
|
| 25 |
+
python3 scripts/33_bancada_jepa.py # T-L7/T-L8/G3/T-L9 (torch f64)
|
| 26 |
+
python3 scripts/34_bancada_som.py # EQ/TE/Mahalanobis
|
| 27 |
+
python3 scripts/90_suite_laboratorio.py # gates L1..L7
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
Dependências: `numpy`, `scipy`, `scikit-learn`, `matplotlib`, `torch` (CPU, f64) —
|
| 31 |
+
`requirements.txt`.
|
| 32 |
+
|
| 33 |
+
## Mapa do projeto
|
| 34 |
+
|
| 35 |
+
| caminho | conteúdo |
|
| 36 |
+
|---|---|
|
| 37 |
+
| `lab/rng.py` | RNG determinístico (xorshift64* + Box–Muller exato; lição r-17 §3.4) |
|
| 38 |
+
| `lab/metricas.py` | EQ (distância quadrada) × QE (norma L2) × TE (Moore) com **unidade declarada** + guarda tipada |
|
| 39 |
+
| `lab/autorregulacao.py` | lei de equações (v0.19) + ensaio-compromisso (v0.20) com o contrato `r × y` explícito |
|
| 40 |
+
| `lab/mapa_som.py` | família MAPA: mediana geométrica (Weiszfeld), critério relativo, **histerese** |
|
| 41 |
+
| `lab/memoria_crescente.py` | memória crescente: penalidade held-out honesta + **lei corrigida opt-in** (lab-A1) |
|
| 42 |
+
| `lab/som.py` | SOM de grade em lote, Euclidiana × Mahalanobis (Cholesky) |
|
| 43 |
+
| `lab/jepa.py` | LeJEPA-lab: energia aprendida + equilíbrio desenrolado + anti-colapso no objetivo (torch f64) |
|
| 44 |
+
| `lab/suite.py` | gates L1..L7 |
|
| 45 |
+
| `scripts/` | bancadas (20/31/32/33/34) + inventário (10) + suíte (90) |
|
| 46 |
+
| `resultados/` | JSONs medidos + figuras |
|
| 47 |
+
| `docs/` | registro do ciclo (r-65) + quadro de equivalências |
|
| 48 |
+
| `rust/patches-v022/` | patches propostos para o repo principal (fonte, rotulados) |
|
| 49 |
+
| `ESTRUTURA.md` | inventário de componentes + **faltas verificadas** |
|
| 50 |
+
| `AUTOCRITICA.md` | autocritique em 5 eixos (matemática, física, física matemática, lógica, programação) |
|
| 51 |
+
|
| 52 |
+
## Resultados medidos (resumo; detalhes em `docs/r-65-laboratorio.md`)
|
| 53 |
+
|
| 54 |
+
| achado | publicado (v0.21) | laboratório (v0.22-lab) | dado real |
|
| 55 |
+
|---|---|---|---|
|
| 56 |
+
| laço de regulação | morto: erro ≡ 0, **0 propostas** em 12 passos, limiar congelado em 1e-6 | vivo: 11–12 propostas reais registradas, ensaio a cada passo | wiki PT-BR + digits |
|
| 57 |
+
| crescimento absoluto desgovernado | 19 → **215 células** (199 divisões) | **19 → 75 células** (59 divisões) com EQ held-out **2,318 → 2,101** | digits |
|
| 58 |
+
| histerese (novo) | — | 6 divisões → 0, EQ held-out 0,8124 → **0,8102**, pior célula 0,9352 → **0,9198** | wiki PT-BR |
|
| 59 |
+
| meta-gradiente exato | T-V21-8 (prova em Rust) | erro autograd × diferenças finitas **3,6e-11**; 1ª ordem (controle) **4,5e-02** | digits |
|
| 60 |
+
| equilíbrio (T-V21-7) | resíduo KKT decai | resíduo **47,2 → 0,022** (η·L_eff ≤ 1, L̂ medido); controle η×4 → 6,25 | digits |
|
| 61 |
+
| anti-colapso no objetivo | diagnóstico apenas | L_var sempre menor no objetivo (0,2072 × 0,2085 benigno; 0,2205 × 0,2208 sob pressão) | digits |
|
| 62 |
+
| piso duro (T-V21-9) | std ≥ ε | entrada constante: std 0,00 → **0,05 = ε** | mecânico |
|
| 63 |
+
|
| 64 |
+
## Doutrina herdada
|
| 65 |
+
|
| 66 |
+
- **Flags opt-in**: `lei_corrigida=False` por padrão — o caminho padrão
|
| 67 |
+
reproduz o comportamento publicado (não-regressão, como G6/L6 do v0.21).
|
| 68 |
+
- **Leitura honesta**: paridade SEMÂNTICA, não bit-a-bit (o `StdRng` do
|
| 69 |
+
`rand` não é reproduzível em Python — declarado, não omitido).
|
| 70 |
+
- **Tríplice prova**: teoremas T-L* com ∎, condição de falsificação
|
| 71 |
+
executável e medição em dados reais.
|
| 72 |
+
- **Unidades declaradas**: a correção de unidades do v0.21 (r-64, Achado 3)
|
| 73 |
+
é formalizada como guarda tipada em `lab/metricas.py`.
|
| 74 |
+
- **Higiene de credenciais**: token EXCLUSIVAMENTE em `HF_TOKEN`, apagado
|
| 75 |
+
após uso (convenção de `src/lib.rs`); o gate L7 torna isso teste.
|
laboratorio/arquivo_split_v100/LEIA-ME.md
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# arquivo_split_v100 — ramo morto do split SRP (C-batch)
|
| 2 |
+
|
| 3 |
+
Experimento de 30/out (split_monolitos_v100.py): dividir os monólitos
|
| 4 |
+
`src/{jepa,pensamento,moe_redirecionavel,python}.rs` em subdiretórios.
|
| 5 |
+
|
| 6 |
+
**Por que foi arquivado:** a sessão de 01/nov (análise DeepSeek, r-35..r-42)
|
| 7 |
+
continuou o trabalho nos arquivos PLANOS (linha canônica rastreada pelo git);
|
| 8 |
+
este ramo ficou defasado (renomeações `fwd`→`forward` etc.) e nunca compilou
|
| 9 |
+
junto com os planos (E0761). Nenhum símbolo exclusivo além de renomeações.
|
| 10 |
+
|
| 11 |
+
**Decisão:** canon = arquivos planos; o split SRP permanece DÉBITO documentado
|
| 12 |
+
(worklog Task 8; r-43 §tratamento). Regenerável a partir daqui se retomado.
|
laboratorio/arquivo_split_v100/checkpoint.rs
ADDED
|
@@ -0,0 +1,353 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! Checkpoints atômicos com prova de integridade criptográfica (v0.10.0).
|
| 2 |
+
//!
|
| 3 |
+
//! **Crítica Qwen3.8 lote 3, nº 3 ("Checkpointing Não-Atômico") — ACEITA
|
| 4 |
+
//! COM CORREÇÕES (r-35 §4).** A proposta original tinha três falhas:
|
| 5 |
+
//!
|
| 6 |
+
//! 1. **Destruição do estado anterior:** `File::create(caminho_pesos)`
|
| 7 |
+
//! trunca o checkpoint ANTERIOR antes de escrever o novo — uma queda
|
| 8 |
+
//! de energia no meio da escrita perde AMBOS. A atomicidade real exige
|
| 9 |
+
//! escrita em `.tmp` + `rename(2)` (o POSIX garante troca atômica).
|
| 10 |
+
//! 2. **Manifesto sem barreira:** `fs::write(caminho_meta, ...)` sem
|
| 11 |
+
//! `sync_all` — o manifesto pode não atingir o disco quando os pesos
|
| 12 |
+
//! já atingiram (ou vice-versa), violando a própria ordenação alegada.
|
| 13 |
+
//! 3. **Dependência nova (bincode) + `unwrap()`** em caminho de I/O.
|
| 14 |
+
//!
|
| 15 |
+
//! Esta implementação: SHA-256 **puro em Rust** (FIPS 180-4, sem crates
|
| 16 |
+
//! externas — crates.io inacessível no ambiente), escrita tmp→fsync→
|
| 17 |
+
//! rename→fsync(dir) para AMBOS os arquivos, e manifesto lado-a-lado
|
| 18 |
+
//! `{caminho}.manifest.json` com hash + tamanho.
|
| 19 |
+
//!
|
| 20 |
+
//! **Teo CP-1 (atomicidade da troca).** `rename(2)` é atômico em relação
|
| 21 |
+
//! a leitores concorrentes e crashes: em qualquer instante o caminho
|
| 22 |
+
//! resolve OU para o arquivo antigo OU para o novo, nunca uma mistura.
|
| 23 |
+
//! Logo um crash em qualquer ponto deixa o caminho final = checkpoint
|
| 24 |
+
//! antigo (crash antes do rename) ou novo (depois). ∎ (garantia POSIX)
|
| 25 |
+
//!
|
| 26 |
+
//! **Teo CP-2 (durabilidade ordenada).** Com a disciplina
|
| 27 |
+
//! `write(W.tmp) → fsync(W.tmp) → rename(W) → write(M.tmp) →
|
| 28 |
+
//! fsync(M.tmp) → rename(M) → fsync(dir)`, após reboot: se `M` existe,
|
| 29 |
+
//! então o rename de `W` foi durável (executado e journalizado antes) e
|
| 30 |
+
//! os blocos de dados de `W` foram forçados por `fsync(W.tmp)` — portanto
|
| 31 |
+
//! `SHA-256(W) = M.hash` (a menos de colisão, CP-3). Se `M` não existe,
|
| 32 |
+
//! o estado é tratado como INVÁLIDO (não silenciosamente errado). ∎
|
| 33 |
+
//!
|
| 34 |
+
//! **Teo CP-3 (detecção de corrupção).** Para W' ≠ W com |W'| = |W|,
|
| 35 |
+
//! `P[SHA-256(W') = SHA-256(W)] ≤ 2^-256` (ataque direto) e, para
|
| 36 |
+
//! qualquer par distinto, ≤ 2^-128 (limite de aniversário). Truncamentos
|
| 37 |
+
//! e gravações parciais são capturados DETERMINISTICAMENTE pelo campo
|
| 38 |
+
//! `tamanho`. Nota honesta: a alegação original "matematicamente
|
| 39 |
+
//! idêntico" é exagerada — o correto é indistinguibilidade computacional
|
| 40 |
+
//! com probabilidade de colisão ≤ 2^-128. ∎
|
| 41 |
+
//!
|
| 42 |
+
//! **Compatibilidade (regra da casa: nada é removido):** checkpoints da
|
| 43 |
+
//! v0.9.0 (sem manifesto) continuam carregáveis pelos `carregar` legados;
|
| 44 |
+
//! `carregar_verificado` exige manifesto e recusa o contrário.
|
| 45 |
+
|
| 46 |
+
use candle_core::Result;
|
| 47 |
+
use std::fs::File;
|
| 48 |
+
use std::io::Write;
|
| 49 |
+
use std::path::Path;
|
| 50 |
+
|
| 51 |
+
pub const VERSAO_CHECKPOINT: &str = "0.10.0";
|
| 52 |
+
|
| 53 |
+
// ---------------------------------------------------------------------------
|
| 54 |
+
// SHA-256 — FIPS 180-4, implementação autocontida (sem dependências)
|
| 55 |
+
// ---------------------------------------------------------------------------
|
| 56 |
+
|
| 57 |
+
const K_SHA256: [u32; 64] = [
|
| 58 |
+
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
|
| 59 |
+
0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
|
| 60 |
+
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
|
| 61 |
+
0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
| 62 |
+
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
|
| 63 |
+
0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
|
| 64 |
+
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
|
| 65 |
+
0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
| 66 |
+
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
|
| 67 |
+
0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
|
| 68 |
+
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
| 69 |
+
];
|
| 70 |
+
|
| 71 |
+
/// SHA-256 de `dados` — 32 bytes (FIPS 180-4 §6.2.2).
|
| 72 |
+
pub fn sha256(dados: &[u8]) -> [u8; 32] {
|
| 73 |
+
let mut h: [u32; 8] = [
|
| 74 |
+
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
|
| 75 |
+
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
|
| 76 |
+
];
|
| 77 |
+
// padding: 0x80, zeros, comprimento de bit big-endian em 64 bits
|
| 78 |
+
let bitlen = (dados.len() as u64).wrapping_mul(8);
|
| 79 |
+
let mut msg = dados.to_vec();
|
| 80 |
+
msg.push(0x80);
|
| 81 |
+
while msg.len() % 64 != 56 {
|
| 82 |
+
msg.push(0);
|
| 83 |
+
}
|
| 84 |
+
msg.extend_from_slice(&bitlen.to_be_bytes());
|
| 85 |
+
|
| 86 |
+
for bloco in msg.chunks_exact(64) {
|
| 87 |
+
let mut w = [0u32; 64];
|
| 88 |
+
for (i, j) in (0..64).step_by(4).enumerate() {
|
| 89 |
+
w[i] = u32::from_be_bytes([bloco[j], bloco[j + 1], bloco[j + 2], bloco[j + 3]]);
|
| 90 |
+
}
|
| 91 |
+
for t in 16..64 {
|
| 92 |
+
let s0 = w[t - 15].rotate_right(7) ^ w[t - 15].rotate_right(18) ^ (w[t - 15] >> 3);
|
| 93 |
+
let s1 = w[t - 2].rotate_right(17) ^ w[t - 2].rotate_right(19) ^ (w[t - 2] >> 10);
|
| 94 |
+
w[t] = w[t - 16]
|
| 95 |
+
.wrapping_add(s0)
|
| 96 |
+
.wrapping_add(w[t - 7])
|
| 97 |
+
.wrapping_add(s1);
|
| 98 |
+
}
|
| 99 |
+
let (mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh) =
|
| 100 |
+
(h[0], h[1], h[2], h[3], h[4], h[5], h[6], h[7]);
|
| 101 |
+
for t in 0..64 {
|
| 102 |
+
let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
|
| 103 |
+
let ch = (e & f) ^ ((!e) & g);
|
| 104 |
+
let t1 = hh
|
| 105 |
+
.wrapping_add(s1)
|
| 106 |
+
.wrapping_add(ch)
|
| 107 |
+
.wrapping_add(K_SHA256[t])
|
| 108 |
+
.wrapping_add(w[t]);
|
| 109 |
+
let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
|
| 110 |
+
let maj = (a & b) ^ (a & c) ^ (b & c);
|
| 111 |
+
let t2 = s0.wrapping_add(maj);
|
| 112 |
+
hh = g; g = f; f = e; e = d.wrapping_add(t1);
|
| 113 |
+
d = c; c = b; b = a; a = t1.wrapping_add(t2);
|
| 114 |
+
}
|
| 115 |
+
h[0] = h[0].wrapping_add(a); h[1] = h[1].wrapping_add(b);
|
| 116 |
+
h[2] = h[2].wrapping_add(c); h[3] = h[3].wrapping_add(d);
|
| 117 |
+
h[4] = h[4].wrapping_add(e); h[5] = h[5].wrapping_add(f);
|
| 118 |
+
h[6] = h[6].wrapping_add(g); h[7] = h[7].wrapping_add(hh);
|
| 119 |
+
}
|
| 120 |
+
let mut saida = [0u8; 32];
|
| 121 |
+
for (i, x) in h.iter().enumerate() {
|
| 122 |
+
saida[i * 4..i * 4 + 4].copy_from_slice(&x.to_be_bytes());
|
| 123 |
+
}
|
| 124 |
+
saida
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
/// SHA-256 em hexadecimal minúsculo (64 caracteres).
|
| 128 |
+
pub fn sha256_hex(dados: &[u8]) -> String {
|
| 129 |
+
sha256(dados).iter().map(|b| format!("{b:02x}")).collect()
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
// ---------------------------------------------------------------------------
|
| 133 |
+
// salva / carrega atômicos
|
| 134 |
+
// ---------------------------------------------------------------------------
|
| 135 |
+
|
| 136 |
+
/// Caminho do manifesto lado-a-lado de `caminho`.
|
| 137 |
+
pub fn caminho_manifesto(caminho: &str) -> String {
|
| 138 |
+
format!("{caminho}.manifest.json")
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
fn err_io(e: std::io::Error, ctx: &str) -> candle_core::Error {
|
| 142 |
+
candle_core::Error::Msg(format!("{ctx}: {e}"))
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
/// fsync de um diretório (durabilidade do rename — POSIX). Unix apenas;
|
| 146 |
+
/// em outras plataformas é no-op documentado.
|
| 147 |
+
fn fsync_dir(dir: &Path) -> std::io::Result<()> {
|
| 148 |
+
#[cfg(unix)]
|
| 149 |
+
{
|
| 150 |
+
let d = File::open(dir)?;
|
| 151 |
+
d.sync_all()?;
|
| 152 |
+
}
|
| 153 |
+
#[cfg(not(unix))]
|
| 154 |
+
{
|
| 155 |
+
let _ = dir;
|
| 156 |
+
}
|
| 157 |
+
Ok(())
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
/// Escrita atômica de `conteudo` em `caminho` com fsync + rename e
|
| 161 |
+
/// manifesto `{caminho}.manifest.json` (hash SHA-256 + tamanho).
|
| 162 |
+
///
|
| 163 |
+
/// Ordem (Teo CP-2): write(tmp) → fsync(tmp) → rename(final) para o
|
| 164 |
+
/// conteúdo e para o manifesto; fsync(dir) ao final.
|
| 165 |
+
pub fn salvar_atomico(caminho: &str, conteudo: &str) -> Result<()> {
|
| 166 |
+
let dados = conteudo.as_bytes();
|
| 167 |
+
let hash = sha256_hex(dados);
|
| 168 |
+
let tmp = format!("{caminho}.tmp");
|
| 169 |
+
|
| 170 |
+
// 1) conteúdo: tmp → fsync → rename (Teo CP-1: troca atômica)
|
| 171 |
+
{
|
| 172 |
+
let mut f = File::create(&tmp).map_err(|e| err_io(e, "checkpoint: criar tmp"))?;
|
| 173 |
+
f.write_all(dados).map_err(|e| err_io(e, "checkpoint: escrever tmp"))?;
|
| 174 |
+
f.sync_all().map_err(|e| err_io(e, "checkpoint: fsync tmp"))?;
|
| 175 |
+
}
|
| 176 |
+
std::fs::rename(&tmp, caminho).map_err(|e| err_io(e, "checkpoint: rename"))?;
|
| 177 |
+
|
| 178 |
+
// 2) manifesto: mesma disciplina (a proposta original usava fs::write
|
| 179 |
+
// simples — sem barreira, o manifesto pode perder-se sozinho)
|
| 180 |
+
let manifest = serde_json::json!({
|
| 181 |
+
"versao": VERSAO_CHECKPOINT,
|
| 182 |
+
"algoritmo": "sha256",
|
| 183 |
+
"hash_sha256": hash,
|
| 184 |
+
"tamanho": dados.len(),
|
| 185 |
+
});
|
| 186 |
+
let mtxt = serde_json::to_string(&manifest)
|
| 187 |
+
.map_err(|e| candle_core::Error::Msg(format!("serde: {e}")))?;
|
| 188 |
+
let mtmp = format!("{}.manifest.json.tmp", caminho);
|
| 189 |
+
{
|
| 190 |
+
let mut f = File::create(&mtmp).map_err(|e| err_io(e, "manifesto: criar tmp"))?;
|
| 191 |
+
f.write_all(mtxt.as_bytes()).map_err(|e| err_io(e, "manifesto: escrever tmp"))?;
|
| 192 |
+
f.sync_all().map_err(|e| err_io(e, "manifesto: fsync tmp"))?;
|
| 193 |
+
}
|
| 194 |
+
std::fs::rename(&mtmp, caminho_manifesto(caminho))
|
| 195 |
+
.map_err(|e| err_io(e, "manifesto: rename"))?;
|
| 196 |
+
|
| 197 |
+
// 3) durabilidade dos renames (POSIX: rename journalizado no dir)
|
| 198 |
+
if let Some(pai) = Path::new(caminho).parent() {
|
| 199 |
+
fsync_dir(pai).map_err(|e| err_io(e, "checkpoint: fsync dir"))?;
|
| 200 |
+
}
|
| 201 |
+
Ok(())
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
/// Lê `caminho` verificando o manifesto (hash + tamanho). Recusa
|
| 205 |
+
/// manifesto ausente ou divergente — Teo CP-3.
|
| 206 |
+
pub fn carregar_verificado(caminho: &str) -> Result<String> {
|
| 207 |
+
let dados = std::fs::read(caminho).map_err(|e| err_io(e, "checkpoint: ler"))?;
|
| 208 |
+
let mtxt = std::fs::read_to_string(caminho_manifesto(caminho))
|
| 209 |
+
.map_err(|_| candle_core::Error::Msg(format!(
|
| 210 |
+
"checkpoint sem manifesto (legado v0.9.0?): {caminho}")))?;
|
| 211 |
+
let m: serde_json::Value = serde_json::from_str(&mtxt)
|
| 212 |
+
.map_err(|e| candle_core::Error::Msg(format!("manifesto ilegível: {e}")))?;
|
| 213 |
+
let hash_esp = m["hash_sha256"].as_str().unwrap_or("");
|
| 214 |
+
let tam_esp = m["tamanho"].as_u64().unwrap_or(u64::MAX);
|
| 215 |
+
let hash_rec = sha256_hex(&dados);
|
| 216 |
+
if (dados.len() as u64) != tam_esp {
|
| 217 |
+
candle_core::bail!(
|
| 218 |
+
"checkpoint corrompido: tamanho {} ��� manifesto {} ({caminho})",
|
| 219 |
+
dados.len(), tam_esp);
|
| 220 |
+
}
|
| 221 |
+
if hash_rec != hash_esp {
|
| 222 |
+
candle_core::bail!(
|
| 223 |
+
"checkpoint corrompido: SHA-256 divergente ({caminho})");
|
| 224 |
+
}
|
| 225 |
+
String::from_utf8(dados)
|
| 226 |
+
.map_err(|e| candle_core::Error::Msg(format!("utf8: {e}")))
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
/// Verificação sem exceção (para uso em Python/CLI antes de resume).
|
| 230 |
+
pub fn validar(caminho: &str) -> bool {
|
| 231 |
+
carregar_verificado(caminho).is_ok()
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
#[cfg(test)]
|
| 235 |
+
mod testes_checkpoint {
|
| 236 |
+
use super::*;
|
| 237 |
+
|
| 238 |
+
fn tmp_dir(nome: &str) -> std::path::PathBuf {
|
| 239 |
+
let d = std::env::temp_dir().join(format!("khtst_cp_{nome}_{}", std::process::id()));
|
| 240 |
+
let _ = std::fs::remove_dir_all(&d);
|
| 241 |
+
std::fs::create_dir_all(&d).unwrap();
|
| 242 |
+
d
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
/// CP-0a — SHA-256 contra os vetores oficiais FIPS 180-4.
|
| 246 |
+
#[test]
|
| 247 |
+
fn cp0a_sha256_vetores_fips() {
|
| 248 |
+
assert_eq!(
|
| 249 |
+
sha256_hex(b""),
|
| 250 |
+
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
|
| 251 |
+
assert_eq!(
|
| 252 |
+
sha256_hex(b"abc"),
|
| 253 |
+
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
|
| 254 |
+
assert_eq!(
|
| 255 |
+
sha256_hex(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"),
|
| 256 |
+
"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1");
|
| 257 |
+
// vetor de 4 blocos (256 bytes) — exercita o laço de blocos
|
| 258 |
+
let longo = "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn".repeat(4);
|
| 259 |
+
assert_eq!(sha256_hex(longo.as_bytes()).len(), 64);
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
/// CP-1a — salvar produz final + manifesto; tmp não permanece;
|
| 263 |
+
/// carregar_verificado devolve o conteúdo bit-a-bit.
|
| 264 |
+
#[test]
|
| 265 |
+
fn cp1a_salvar_carregar_roundtrip() {
|
| 266 |
+
let d = tmp_dir("rt");
|
| 267 |
+
let p = d.join("ck.json");
|
| 268 |
+
salvar_atomico(p.to_str().unwrap(), "{\"v0\":[1.0,2.0]}").unwrap();
|
| 269 |
+
assert!(p.exists());
|
| 270 |
+
assert!(d.join("ck.json.manifest.json").exists());
|
| 271 |
+
assert!(!d.join("ck.json.tmp").exists());
|
| 272 |
+
assert!(!d.join("ck.json.manifest.json.tmp").exists());
|
| 273 |
+
assert_eq!(carregar_verificado(p.to_str().unwrap()).unwrap(),
|
| 274 |
+
"{\"v0\":[1.0,2.0]}");
|
| 275 |
+
let _ = std::fs::remove_dir_all(&d);
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
/// CP-3a — adulteração de 1 byte é detectada (hash divergente).
|
| 279 |
+
#[test]
|
| 280 |
+
fn cp3a_adulteracao_detectada() {
|
| 281 |
+
let d = tmp_dir("t");
|
| 282 |
+
let p = d.join("ck.json");
|
| 283 |
+
salvar_atomico(p.to_str().unwrap(), "conteudo original").unwrap();
|
| 284 |
+
std::fs::write(&p, "conteudo originalX").unwrap();
|
| 285 |
+
assert!(carregar_verificado(p.to_str().unwrap()).is_err());
|
| 286 |
+
assert!(!validar(p.to_str().unwrap()));
|
| 287 |
+
let _ = std::fs::remove_dir_all(&d);
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
/// CP-3b — truncamento detectado pelo tamanho (determinístico).
|
| 291 |
+
#[test]
|
| 292 |
+
fn cp3b_truncamento_detectado() {
|
| 293 |
+
let d = tmp_dir("tr");
|
| 294 |
+
let p = d.join("ck.json");
|
| 295 |
+
salvar_atomico(p.to_str().unwrap(), "0123456789").unwrap();
|
| 296 |
+
std::fs::write(&p, "0123").unwrap();
|
| 297 |
+
assert!(carregar_verificado(p.to_str().unwrap()).is_err());
|
| 298 |
+
let _ = std::fs::remove_dir_all(&d);
|
| 299 |
+
}
|
| 300 |
+
|
| 301 |
+
/// CP-4a — manifesto ausente ⇒ recusa (estado legado é do `carregar`).
|
| 302 |
+
#[test]
|
| 303 |
+
fn cp4a_manifesto_ausente_recusado() {
|
| 304 |
+
let d = tmp_dir("leg");
|
| 305 |
+
let p = d.join("ck.json");
|
| 306 |
+
salvar_atomico(p.to_str().unwrap(), "x").unwrap();
|
| 307 |
+
std::fs::remove_file(d.join("ck.json.manifest.json")).unwrap();
|
| 308 |
+
assert!(carregar_verificado(p.to_str().unwrap()).is_err());
|
| 309 |
+
let _ = std::fs::remove_dir_all(&d);
|
| 310 |
+
}
|
| 311 |
+
|
| 312 |
+
/// CP-1b — falha de escrita PRESERVA o checkpoint anterior
|
| 313 |
+
/// (atomicidade prática: dir somente-leitura impede o create do tmp).
|
| 314 |
+
#[test]
|
| 315 |
+
fn cp1b_falha_preserva_anterior() {
|
| 316 |
+
let d = tmp_dir("fa");
|
| 317 |
+
let p = d.join("ck.json");
|
| 318 |
+
salvar_atomico(p.to_str().unwrap(), "estado_bom").unwrap();
|
| 319 |
+
// dir somente-leitura: File::create(tmp) falha
|
| 320 |
+
let mut perms = std::fs::metadata(&d).unwrap().permissions();
|
| 321 |
+
#[allow(clippy::unnecessary_cast)]
|
| 322 |
+
{
|
| 323 |
+
use std::os::unix::fs::PermissionsExt;
|
| 324 |
+
perms.set_mode(0o555);
|
| 325 |
+
}
|
| 326 |
+
std::fs::set_permissions(&d, perms).unwrap();
|
| 327 |
+
let r = salvar_atomico(p.to_str().unwrap(), "estado_novo");
|
| 328 |
+
let mut perms2 = std::fs::metadata(&d).unwrap().permissions();
|
| 329 |
+
#[allow(clippy::unnecessary_cast)]
|
| 330 |
+
{
|
| 331 |
+
use std::os::unix::fs::PermissionsExt;
|
| 332 |
+
perms2.set_mode(0o755);
|
| 333 |
+
}
|
| 334 |
+
std::fs::set_permissions(&d, perms2).unwrap();
|
| 335 |
+
assert!(r.is_err(), "escrita deveria falhar em dir somente-leitura");
|
| 336 |
+
// o anterior permanece ÍNTEGRO e válido (Teo CP-1)
|
| 337 |
+
assert_eq!(carregar_verificado(p.to_str().unwrap()).unwrap(), "estado_bom");
|
| 338 |
+
let _ = std::fs::remove_dir_all(&d);
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
/// CP-5a — manifesto trocado entre arquivos (hash de outro) recusa.
|
| 342 |
+
#[test]
|
| 343 |
+
fn cp5a_manifesto_de_outro_recusado() {
|
| 344 |
+
let d = tmp_dir("sw");
|
| 345 |
+
let a = d.join("a.json");
|
| 346 |
+
let b = d.join("b.json");
|
| 347 |
+
salvar_atomico(a.to_str().unwrap(), "AAAA").unwrap();
|
| 348 |
+
salvar_atomico(b.to_str().unwrap(), "BBBB").unwrap();
|
| 349 |
+
std::fs::copy(d.join("b.json.manifest.json"), d.join("a.json.manifest.json")).unwrap();
|
| 350 |
+
assert!(carregar_verificado(a.to_str().unwrap()).is_err());
|
| 351 |
+
let _ = std::fs::remove_dir_all(&d);
|
| 352 |
+
}
|
| 353 |
+
}
|
laboratorio/arquivo_split_v100/jepa/mascaras.rs
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! `jepa::mascaras` — extraído do monólito na v0.10.0
|
| 2 |
+
//! (divisão SRP, crítica Qwen3.8 lote 3 nº 1; r-35 §2).
|
| 3 |
+
|
| 4 |
+
use super::*;
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
// ---------------------------------------------------------------------------
|
| 8 |
+
// Parte 2 — máscaras
|
| 9 |
+
// ---------------------------------------------------------------------------
|
| 10 |
+
|
| 11 |
+
/// Máscara de blocos 2D (Image-JEPA): grade (h, w) de patches; sorteia
|
| 12 |
+
/// `n_blocos` retângulos aleatórios com fração alvo `frac` de patches.
|
| 13 |
+
pub fn mascara_blocos_2d(h: usize, w: usize, n_blocos: usize, frac: f64, rng: &mut RngDeterministico) -> Vec<bool> {
|
| 14 |
+
let total = h * w;
|
| 15 |
+
let alvo = (total as f64 * frac) as usize;
|
| 16 |
+
let mut masc = vec![false; total];
|
| 17 |
+
let mut coberto = 0usize;
|
| 18 |
+
for _ in 0..n_blocos.max(1) {
|
| 19 |
+
if coberto >= alvo {
|
| 20 |
+
break;
|
| 21 |
+
}
|
| 22 |
+
let bh = 1 + rng.inteiro(h.min(4));
|
| 23 |
+
let bw = 1 + rng.inteiro(w.min(4));
|
| 24 |
+
let y0 = rng.inteiro(h + 1 - bh);
|
| 25 |
+
let x0 = rng.inteiro(w + 1 - bw);
|
| 26 |
+
for y in y0..y0 + bh {
|
| 27 |
+
for x in x0..x0 + bw {
|
| 28 |
+
let i = y * w + x;
|
| 29 |
+
if !masc[i] {
|
| 30 |
+
masc[i] = true;
|
| 31 |
+
coberto += 1;
|
| 32 |
+
}
|
| 33 |
+
}
|
| 34 |
+
}
|
| 35 |
+
}
|
| 36 |
+
masc
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
/// Máscara de tubos 3D (V-JEPA 2): grade (t, h, w); tubos = retângulos que
|
| 40 |
+
/// atravessam o tempo.
|
| 41 |
+
pub fn mascara_tubos_3d(t: usize, h: usize, w: usize, n_tubos: usize, frac: f64, rng: &mut RngDeterministico) -> Vec<bool> {
|
| 42 |
+
let total = t * h * w;
|
| 43 |
+
let alvo = (total as f64 * frac) as usize;
|
| 44 |
+
let mut masc = vec![false; total];
|
| 45 |
+
let mut coberto = 0usize;
|
| 46 |
+
for _ in 0..n_tubos.max(1) {
|
| 47 |
+
if coberto >= alvo {
|
| 48 |
+
break;
|
| 49 |
+
}
|
| 50 |
+
let bh = 1 + rng.inteiro(h.min(3));
|
| 51 |
+
let bw = 1 + rng.inteiro(w.min(3));
|
| 52 |
+
let y0 = rng.inteiro(h + 1 - bh);
|
| 53 |
+
let x0 = rng.inteiro(w + 1 - bw);
|
| 54 |
+
for tt in 0..t {
|
| 55 |
+
for y in y0..y0 + bh {
|
| 56 |
+
for x in x0..x0 + bw {
|
| 57 |
+
let i = (tt * h + y) * w + x;
|
| 58 |
+
if !masc[i] {
|
| 59 |
+
masc[i] = true;
|
| 60 |
+
coberto += 1;
|
| 61 |
+
}
|
| 62 |
+
}
|
| 63 |
+
}
|
| 64 |
+
}
|
| 65 |
+
}
|
| 66 |
+
masc
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
/// Máscara de bandas (Audio-JEPA): grade (f, tau) — bandas de frequência
|
| 70 |
+
/// horizontais com extensão temporal.
|
| 71 |
+
pub fn mascara_bandas(f: usize, tau: usize, n_bandas: usize, frac: f64, rng: &mut RngDeterministico) -> Vec<bool> {
|
| 72 |
+
mascara_blocos_2d(f, tau, n_bandas, frac, rng) // blocos na grade (f, tau)
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
/// Máscara de blocos 3D (3D-JEPA): grade (x, y, z) de voxels.
|
| 76 |
+
pub fn mascara_blocos_3d(x: usize, y: usize, z: usize, n_blocos: usize, frac: f64, rng: &mut RngDeterministico) -> Vec<bool> {
|
| 77 |
+
mascara_tubos_3d(x, y, z, n_blocos, frac, rng)
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
/// Máscara de segmentos canal×tempo (Brain-JEPA): canais inteiros OU
|
| 81 |
+
/// janelas temporais (aleatório por chamada).
|
| 82 |
+
pub fn mascara_segmentos(c: usize, t: usize, frac: f64, rng: &mut RngDeterministico) -> Vec<bool> {
|
| 83 |
+
let total = c * t;
|
| 84 |
+
let alvo = (total as f64 * frac) as usize;
|
| 85 |
+
let mut masc = vec![false; total];
|
| 86 |
+
if rng.inteiro(2) == 0 {
|
| 87 |
+
// canais inteiros
|
| 88 |
+
let mut coberto = 0;
|
| 89 |
+
let mut canais: Vec<usize> = (0..c).collect();
|
| 90 |
+
// embaralhar
|
| 91 |
+
for i in (1..canais.len()).rev() {
|
| 92 |
+
let j = rng.inteiro(i + 1);
|
| 93 |
+
canais.swap(i, j);
|
| 94 |
+
}
|
| 95 |
+
for &ch in canais.iter() {
|
| 96 |
+
if coberto >= alvo {
|
| 97 |
+
break;
|
| 98 |
+
}
|
| 99 |
+
for tt in 0..t {
|
| 100 |
+
masc[ch * t + tt] = true;
|
| 101 |
+
coberto += 1;
|
| 102 |
+
}
|
| 103 |
+
}
|
| 104 |
+
} else {
|
| 105 |
+
// janelas temporais
|
| 106 |
+
let mut coberto = 0;
|
| 107 |
+
let mut t0 = 0;
|
| 108 |
+
while coberto < alvo && t0 < t {
|
| 109 |
+
let len = 1 + rng.inteiro((t / 4).max(1));
|
| 110 |
+
for ch in 0..c {
|
| 111 |
+
for tt in t0..(t0 + len).min(t) {
|
| 112 |
+
masc[ch * t + tt] = true;
|
| 113 |
+
coberto += 1;
|
| 114 |
+
}
|
| 115 |
+
}
|
| 116 |
+
t0 += len + 1;
|
| 117 |
+
}
|
| 118 |
+
}
|
| 119 |
+
masc
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
/// Máscara 1D (T-JEPA): intervalos contíguos em n posições.
|
| 123 |
+
pub fn mascara_intervalos_1d(n: usize, frac: f64, rng: &mut RngDeterministico) -> Vec<bool> {
|
| 124 |
+
let alvo = (n as f64 * frac) as usize;
|
| 125 |
+
let mut masc = vec![false; n];
|
| 126 |
+
let mut coberto = 0;
|
| 127 |
+
while coberto < alvo {
|
| 128 |
+
let len = 1 + rng.inteiro((n / 8).max(1));
|
| 129 |
+
let i0 = rng.inteiro(n);
|
| 130 |
+
for i in i0..(i0 + len).min(n) {
|
| 131 |
+
if !masc[i] {
|
| 132 |
+
masc[i] = true;
|
| 133 |
+
coberto += 1;
|
| 134 |
+
}
|
| 135 |
+
}
|
| 136 |
+
}
|
| 137 |
+
masc
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
/// Amostragem dos pontos mais distantes (FPS) para Point-JEPA.
|
| 141 |
+
pub fn pontos_mais_distantes(pontos: &[Vec<f64>], k: usize, rng: &mut RngDeterministico) -> Vec<usize> {
|
| 142 |
+
let n = pontos.len();
|
| 143 |
+
if n == 0 || k == 0 {
|
| 144 |
+
return vec![];
|
| 145 |
+
}
|
| 146 |
+
let k = k.min(n);
|
| 147 |
+
let mut centros = vec![rng.inteiro(n)];
|
| 148 |
+
let mut dist_min: Vec<f64> = pontos
|
| 149 |
+
.iter()
|
| 150 |
+
.map(|p| distancia_eucl(p, &pontos[centros[0]]))
|
| 151 |
+
.collect();
|
| 152 |
+
while centros.len() < k {
|
| 153 |
+
let prox = dist_min
|
| 154 |
+
.iter()
|
| 155 |
+
.enumerate()
|
| 156 |
+
.filter(|(i, _)| !centros.contains(i))
|
| 157 |
+
.max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
|
| 158 |
+
.map(|(i, _)| i)
|
| 159 |
+
.unwrap_or(0);
|
| 160 |
+
centros.push(prox);
|
| 161 |
+
for (i, p) in pontos.iter().enumerate() {
|
| 162 |
+
let d = distancia_eucl(p, &pontos[prox]);
|
| 163 |
+
if d < dist_min[i] {
|
| 164 |
+
dist_min[i] = d;
|
| 165 |
+
}
|
| 166 |
+
}
|
| 167 |
+
}
|
| 168 |
+
centros
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
pub(crate) fn distancia_eucl(a: &[f64], b: &[f64]) -> f64 {
|
| 172 |
+
a.iter().zip(b).map(|(x, y)| (x - y) * (x - y)).sum::<f64>().sqrt()
|
| 173 |
+
}
|
laboratorio/arquivo_split_v100/jepa/mod.rs
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! Suíte JEPA — módulos: núcleo, máscaras, patches, variantes,
|
| 2 |
+
//! SonicMoE, ReplaySSM (divisão SRP v0.10.0 — r-35 §2).
|
| 3 |
+
|
| 4 |
+
//! Suíte JEPA v0.5.0 — núcleo unificado + 12 variantes + SonicMoE + ReplaySSM.
|
| 5 |
+
//!
|
| 6 |
+
//! **Núcleo (todas as variantes compartilham):**
|
| 7 |
+
//! - codificador `E_θ` (MLp SiLU), preditor `P_φ` (condicionado por posição/
|
| 8 |
+
//! ação/edição), codificador-alvo EMA `E_ξ` com `ξ ← m·ξ + (1−m)·θ`
|
| 9 |
+
//! (gradiente cortado — alvo nunca recebe gradiente);
|
| 10 |
+
//! - regularizador variância-covariância (VICReg-lite) anti-colapso:
|
| 11 |
+
//! `V(z) = Σ_j max(0, γ − std(z_j))²` + fora-diagonal da covariância.
|
| 12 |
+
//! - perda: `L = Σ_b ‖P(z_ctx, pos_b) − sg(ẑ_b)‖²/B + λ_vc·V`.
|
| 13 |
+
//!
|
| 14 |
+
//! **Prova J-1 (impossibilidade de colapso, em r-20):** se todas as
|
| 15 |
+
//! incorporações colapsam para constante, `std(z_j) = 0 ∀j` ⇒ `V = d·γ² > 0`;
|
| 16 |
+
//! logo o colapso total NÃO é minimizador com `λ_vc > 0`.
|
| 17 |
+
//!
|
| 18 |
+
//! **Prova J-2 (EMA = stop-grad + ponto fixo):** `∂L/∂ξ = 0` (detach); se
|
| 19 |
+
//! `θ_t → θ*` então `ξ_t → θ*` (recursão linear contratante com `m < 1`).
|
| 20 |
+
//!
|
| 21 |
+
//! **Prova J-3 (decomposição de informação):** com `P` suficientemente
|
| 22 |
+
//! rico, `min_P L = Σ_b Var(ẑ_b | z_ctx)` — a perda retém só o componentes
|
| 23 |
+
//! previsíveis do alvo dado o contexto.
|
| 24 |
+
//!
|
| 25 |
+
//! **Variantes** (esquema de máscara + adaptador de modalidade):
|
| 26 |
+
//! Image-JEPA (blocos 2D) · V-JEPA 2 (tubos 3D + cond. de ação) · MC-JEPA
|
| 27 |
+
//! (cruz-modal, dois codificadores) · Audio-JEPA (bandas de espectrograma) ·
|
| 28 |
+
//! Point-JEPA (grupos FPS) · 3D-JEPA (voxels) · Brain-JEPA (canal×tempo) ·
|
| 29 |
+
//! T-JEPA (série temporal canal-independente) · LeJEPA (edição-condicionado) ·
|
| 30 |
+
//! BJEPA (bidirecional com consistência de ciclo).
|
| 31 |
+
//!
|
| 32 |
+
//! **SonicMoE** — MoE com roteamento top-k, capacidade por especialista
|
| 33 |
+
//! (tile-aware) e perda auxiliar de balanceamento (argumento Switch:
|
| 34 |
+
//! `L_aux = E·Σ f_e·p_e ≥ 1` com igualdade sse uniforme).
|
| 35 |
+
//!
|
| 36 |
+
//! **ReplaySSM** — SSM de porta diagonal (`h_t = σ(a)⊙h_{t−1} +
|
| 37 |
+
//! (1−σ(a))⊙(Bx_t)`, estabilidade herdada do Teo S-2') + replay de experiências
|
| 38 |
+
//! para aprendizado continuado (interpolação de gradientes limita o
|
| 39 |
+
//! esquecimento — Teo R-1).
|
| 40 |
+
|
| 41 |
+
use candle_core::{Device, Result, Tensor, Var};
|
| 42 |
+
use crate::camadas::Linear;
|
| 43 |
+
use crate::rng::RngDeterministico;
|
| 44 |
+
|
| 45 |
+
// ---- divisão SRP v0.10.0 (r-35 §2): submódulos + re-exports ----
|
| 46 |
+
#[cfg(test)]
|
| 47 |
+
mod testes;
|
| 48 |
+
mod mascaras;
|
| 49 |
+
mod nucleo;
|
| 50 |
+
mod patches;
|
| 51 |
+
mod replay_ssm;
|
| 52 |
+
mod sonic_moe;
|
| 53 |
+
mod variantes;
|
| 54 |
+
|
| 55 |
+
pub use mascaras::*;
|
| 56 |
+
pub use nucleo::*;
|
| 57 |
+
pub use patches::*;
|
| 58 |
+
pub use replay_ssm::*;
|
| 59 |
+
pub use sonic_moe::*;
|
| 60 |
+
pub use variantes::*;
|
| 61 |
+
|
laboratorio/arquivo_split_v100/jepa/nucleo.rs
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! `jepa::nucleo` — extraído do monólito na v0.10.0
|
| 2 |
+
//! (divisão SRP, crítica Qwen3.8 lote 3 nº 1; r-35 §2).
|
| 3 |
+
|
| 4 |
+
use super::*;
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
// ---------------------------------------------------------------------------
|
| 8 |
+
// Parte 1 — núcleo
|
| 9 |
+
// ---------------------------------------------------------------------------
|
| 10 |
+
|
| 11 |
+
/// MLP 2 camadas com SiLU (d → h → d_saida).
|
| 12 |
+
pub struct MlpJepa {
|
| 13 |
+
pub l1: Linear,
|
| 14 |
+
pub l2: Linear,
|
| 15 |
+
pub d_entrada: usize,
|
| 16 |
+
pub d_saida: usize,
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
impl MlpJepa {
|
| 20 |
+
pub fn novo(d_entrada: usize, d_oculta: usize, d_saida: usize, dev: &Device) -> Result<Self> {
|
| 21 |
+
let s1 = (1.0 / (d_entrada as f64).sqrt()) * 0.9;
|
| 22 |
+
let s2 = (1.0 / (d_oculta as f64).sqrt()) * 0.9;
|
| 23 |
+
Ok(Self {
|
| 24 |
+
l1: Linear::sem_vies(d_entrada, d_oculta, s1, dev)?,
|
| 25 |
+
l2: Linear::sem_vies(d_oculta, d_saida, s2, dev)?,
|
| 26 |
+
d_entrada,
|
| 27 |
+
d_saida,
|
| 28 |
+
})
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
pub fn fwd(&self, x: &Tensor) -> Result<Tensor> {
|
| 32 |
+
let h = candle_nn::ops::silu(&self.l1.fwd(x)?)?;
|
| 33 |
+
self.l2.fwd(&h)
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
pub fn vars(&self) -> Vec<Var> {
|
| 37 |
+
[self.l1.vars(), self.l2.vars()].concat()
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
/// EMA: `self ← m·self + (1−m)·outro` (usado no codificador-alvo).
|
| 41 |
+
pub fn ema_de(&mut self, outro: &MlpJepa, m: f64) -> Result<()> {
|
| 42 |
+
for (a, b) in self.vars().iter().zip(outro.vars().iter()) {
|
| 43 |
+
let novo = (a.as_tensor().affine(m, 0.0)? + b.as_tensor().affine(1.0 - m, 0.0)?)?;
|
| 44 |
+
a.set(&novo)?;
|
| 45 |
+
}
|
| 46 |
+
Ok(())
|
| 47 |
+
}
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
/// Núcleo JEPA: codificador + preditor + alvo EMA + regularizador VC.
|
| 51 |
+
pub struct NucleoJepa {
|
| 52 |
+
pub encoder: MlpJepa,
|
| 53 |
+
pub preditor: MlpJepa,
|
| 54 |
+
pub alvo: MlpJepa,
|
| 55 |
+
/// tabela de posições (blocos) — entrada extra do preditor.
|
| 56 |
+
pub pos: Var,
|
| 57 |
+
pub d_emb: usize,
|
| 58 |
+
pub d_cond: usize,
|
| 59 |
+
pub m: f64,
|
| 60 |
+
pub lambda_vc: f64,
|
| 61 |
+
pub gamma_vc: f64,
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
impl NucleoJepa {
|
| 65 |
+
pub fn novo(
|
| 66 |
+
d_patch: usize,
|
| 67 |
+
d_emb: usize,
|
| 68 |
+
d_cond: usize,
|
| 69 |
+
n_pos: usize,
|
| 70 |
+
m: f64,
|
| 71 |
+
lambda_vc: f64,
|
| 72 |
+
gamma_vc: f64,
|
| 73 |
+
dev: &Device,
|
| 74 |
+
) -> Result<Self> {
|
| 75 |
+
let encoder = MlpJepa::novo(d_patch, 2 * d_emb, d_emb, dev)?;
|
| 76 |
+
let preditor = MlpJepa::novo(d_emb + d_cond + d_emb, 2 * d_emb, d_emb, dev)?;
|
| 77 |
+
// alvo nasce IGUAL ao encoder (ponto de partida do EMA)
|
| 78 |
+
let mut alvo = MlpJepa::novo(d_patch, 2 * d_emb, d_emb, dev)?;
|
| 79 |
+
for (va, vb) in alvo.vars().iter().zip(encoder.vars().iter()) {
|
| 80 |
+
va.set(vb.as_tensor())?;
|
| 81 |
+
}
|
| 82 |
+
let pos_t = Tensor::randn(0f32, 0.02, (n_pos.max(1), d_emb), dev)?;
|
| 83 |
+
Ok(Self {
|
| 84 |
+
encoder,
|
| 85 |
+
preditor,
|
| 86 |
+
alvo,
|
| 87 |
+
pos: Var::from_tensor(&pos_t)?,
|
| 88 |
+
d_emb,
|
| 89 |
+
d_cond,
|
| 90 |
+
m,
|
| 91 |
+
lambda_vc,
|
| 92 |
+
gamma_vc,
|
| 93 |
+
})
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
pub fn vars(&self) -> Vec<Var> {
|
| 97 |
+
let mut v = self.encoder.vars();
|
| 98 |
+
v.extend(self.preditor.vars());
|
| 99 |
+
v.push(self.pos.clone());
|
| 100 |
+
v // NOTA: alvo NÃO entra — é buffer EMA
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
pub fn ema_passo(&mut self) -> Result<()> {
|
| 104 |
+
self.alvo.ema_de(&self.encoder, self.m)
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
/// Codifica um conjunto de patches (n, d_patch) → (n, d_emb).
|
| 108 |
+
pub fn codificar(&self, patches: &Tensor) -> Result<Tensor> {
|
| 109 |
+
self.encoder.fwd(patches)
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
/// Codifica com o alvo EMA — SEM gradiente (detach por construção: as
|
| 113 |
+
/// vars do alvo não estão no otimizador e o tensor é desconectado).
|
| 114 |
+
pub fn alvo_codificar(&self, patches: &Tensor) -> Result<Tensor> {
|
| 115 |
+
Ok(self.alvo.fwd(patches)?.detach())
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
/// Prediz o embedding do bloco `i_pos` a partir do contexto `z_ctx`
|
| 119 |
+
/// (d_emb) e da condição `cond` (d_cond; zeros se None).
|
| 120 |
+
pub fn predizer(&self, z_ctx: &Tensor, i_pos: usize, cond: Option<&Tensor>) -> Result<Tensor> {
|
| 121 |
+
// z_ctx: (b, d_emb) ou (d_emb,)
|
| 122 |
+
let b = z_ctx.dim(0).unwrap_or(1);
|
| 123 |
+
let dev = z_ctx.device();
|
| 124 |
+
let pos = self.pos.as_tensor().get(i_pos.min(self.pos.dim(0)?.saturating_sub(1)))?;
|
| 125 |
+
let pos_b = pos.broadcast_as((b, self.d_emb))?;
|
| 126 |
+
let cond_b = match cond {
|
| 127 |
+
Some(c) => {
|
| 128 |
+
if c.dims().len() == 1 && b > 1 {
|
| 129 |
+
c.broadcast_as((b, self.d_cond))?
|
| 130 |
+
} else {
|
| 131 |
+
c.clone()
|
| 132 |
+
}
|
| 133 |
+
}
|
| 134 |
+
None => Tensor::zeros((b, self.d_cond), candle_core::DType::F32, dev)?,
|
| 135 |
+
};
|
| 136 |
+
let entrada = Tensor::cat(&[z_ctx, &pos_b, &cond_b], candle_core::D::Minus1)?;
|
| 137 |
+
self.preditor.fwd(&entrada)
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
/// Regularizador variância-covariância do lote de incorporações z (n, d).
|
| 141 |
+
///
|
| 142 |
+
/// **J-1:** no colapso total `z_i = c ∀i` ⇒ `std_j = 0` ⇒ `V = d·γ²`.
|
| 143 |
+
pub fn perda_vc(&self, z: &Tensor) -> Result<Tensor> {
|
| 144 |
+
let n = z.dim(0)? as f64;
|
| 145 |
+
let d = self.d_emb;
|
| 146 |
+
let media = z.mean_keepdim(0)?; // (1, d)
|
| 147 |
+
let centr = z.broadcast_sub(&media)?;
|
| 148 |
+
let var = (centr.sqr()?.sum(0)? / n)?; // (d,)
|
| 149 |
+
let std = var.sqrt()?;
|
| 150 |
+
// dobradiça: max(0, γ − std)²
|
| 151 |
+
let gamma_t =
|
| 152 |
+
Tensor::new(self.gamma_vc as f32, z.device())?.broadcast_as(std.dims())?;
|
| 153 |
+
let gap = gamma_t.broadcast_sub(&std)?.clamp(0.0, f64::INFINITY)?;
|
| 154 |
+
let v = gap.sqr()?.sum_all()?;
|
| 155 |
+
// covariância fora-diagonal: C = centrᵀ·centr/n; perda = ‖C − diag‖²_F/(2d)
|
| 156 |
+
let cov = (centr.transpose(0, 1)?.matmul(¢r)? / n)?; // (d, d)
|
| 157 |
+
let mask_diag = {
|
| 158 |
+
let mut m = vec![0f32; d * d];
|
| 159 |
+
for i in 0..d {
|
| 160 |
+
m[i * d + i] = 1.0;
|
| 161 |
+
}
|
| 162 |
+
Tensor::from_vec(m, (d, d), z.device())?
|
| 163 |
+
};
|
| 164 |
+
let fora = ((&cov * &mask_diag)?.sqr()?.sum_all()? / (2.0 * d.max(1) as f64))?;
|
| 165 |
+
let v_norm = (v / d.max(1) as f64)?;
|
| 166 |
+
Ok((v_norm + fora)?)
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
/// Perda JEPA padrão para UM lote: contexto (número variável de patches),
|
| 170 |
+
/// lista de blocos-alvo (posições), condição opcional.
|
| 171 |
+
///
|
| 172 |
+
/// `z_ctx` = incorporação agregada do contexto (b, d_emb);
|
| 173 |
+
/// `alvos`: para cada elemento do lote, Vec<(i_pos, patches_alvo)>.
|
| 174 |
+
pub fn perda_lote(
|
| 175 |
+
&self,
|
| 176 |
+
z_ctx: &Tensor,
|
| 177 |
+
alvos: &[Vec<(usize, Tensor)>],
|
| 178 |
+
cond: Option<&Tensor>,
|
| 179 |
+
z_ctx_todos: &Tensor,
|
| 180 |
+
) -> Result<(Tensor, f64, f64)> {
|
| 181 |
+
let b = z_ctx.dim(0)?;
|
| 182 |
+
let dev = z_ctx.device();
|
| 183 |
+
let mut perdas: Vec<Tensor> = Vec::new();
|
| 184 |
+
let mut n_alvos = 0usize;
|
| 185 |
+
for (i, blocos) in alvos.iter().enumerate() {
|
| 186 |
+
for (i_pos, patches_alvo) in blocos {
|
| 187 |
+
// ẑ_b = média das incorporações-alvo dos patches do bloco
|
| 188 |
+
let zt = self.alvo_codificar(patches_alvo)?; // (m, d_emb)
|
| 189 |
+
let zt_m = zt.mean(0)?; // (d_emb,)
|
| 190 |
+
let zt_b = zt_m.broadcast_as((1, self.d_emb))?;
|
| 191 |
+
let zc = z_ctx.get(i)?.broadcast_as((1, self.d_emb))?;
|
| 192 |
+
let c_i = cond.map(|c| c.get(i)?.broadcast_as((1, self.d_cond))).transpose()?;
|
| 193 |
+
let pred = self.predizer(&zc, *i_pos, c_i.as_ref())?;
|
| 194 |
+
let dif = (&pred - &zt_b)?;
|
| 195 |
+
let l = (dif.sqr()?.sum_all()? / self.d_emb as f64)?;
|
| 196 |
+
perdas.push(l);
|
| 197 |
+
n_alvos += 1;
|
| 198 |
+
}
|
| 199 |
+
}
|
| 200 |
+
let l_pred = if perdas.is_empty() {
|
| 201 |
+
Tensor::zeros((), candle_core::DType::F32, &dev)?
|
| 202 |
+
} else {
|
| 203 |
+
(Tensor::stack(&perdas, 0)?.sum_all()? / n_alvos.max(1) as f64)?
|
| 204 |
+
};
|
| 205 |
+
let l_vc = self.perda_vc(z_ctx_todos)?;
|
| 206 |
+
let total = (l_pred.affine(1.0, 0.0)? + l_vc.affine(self.lambda_vc, 0.0)?)?;
|
| 207 |
+
let lp = l_pred.to_scalar::<f32>()? as f64;
|
| 208 |
+
let lv = l_vc.to_scalar::<f32>()? as f64;
|
| 209 |
+
Ok((total, lp, lv))
|
| 210 |
+
}
|
| 211 |
+
}
|
laboratorio/arquivo_split_v100/jepa/patches.rs
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! `jepa::patches` — extraído do monólito na v0.10.0
|
| 2 |
+
//! (divisão SRP, crítica Qwen3.8 lote 3 nº 1; r-35 §2).
|
| 3 |
+
|
| 4 |
+
use super::*;
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
// ---------------------------------------------------------------------------
|
| 8 |
+
// Parte 3 — adaptadores de modalidade
|
| 9 |
+
// ---------------------------------------------------------------------------
|
| 10 |
+
|
| 11 |
+
/// (C, H, W) → patches (H/ph · W/pw, C·ph·pw) — Image-JEPA.
|
| 12 |
+
pub fn em_patches_2d(img: &Tensor, ph: usize, pw: usize) -> Result<Tensor> {
|
| 13 |
+
let (c, h, w) = (img.dim(0)?, img.dim(1)?, img.dim(2)?);
|
| 14 |
+
let dev = img.device();
|
| 15 |
+
let mut linhas: Vec<Tensor> = Vec::new();
|
| 16 |
+
for y in (0..h).step_by(ph) {
|
| 17 |
+
for x in (0..w).step_by(pw) {
|
| 18 |
+
let hh = ph.min(h - y);
|
| 19 |
+
let ww = pw.min(w - x);
|
| 20 |
+
let patch = img.narrow(0, 0, c)?.narrow(1, y, hh)?.narrow(2, x, ww)?;
|
| 21 |
+
// padding para (C, ph, pw) se borda
|
| 22 |
+
let patch = if hh < ph || ww < pw {
|
| 23 |
+
let mut buf = patch.flatten_all()?.to_vec1::<f32>()?;
|
| 24 |
+
let falta = c * ph * pw - buf.len();
|
| 25 |
+
buf.extend(std::iter::repeat(0f32).take(falta));
|
| 26 |
+
Tensor::from_vec(buf, (c * ph * pw,), &dev)?
|
| 27 |
+
} else {
|
| 28 |
+
patch.flatten_all()?
|
| 29 |
+
};
|
| 30 |
+
linhas.push(patch);
|
| 31 |
+
}
|
| 32 |
+
}
|
| 33 |
+
Ok(Tensor::stack(&linhas, 0)?)
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
/// (T, H, W) → tubos (T/pt · H/ph · W/pw, pt·ph·pw) — V-JEPA 2.
|
| 37 |
+
pub fn em_tubos_3d(vid: &Tensor, pt: usize, ph: usize, pw: usize) -> Result<Tensor> {
|
| 38 |
+
let (t, h, w) = (vid.dim(0)?, vid.dim(1)?, vid.dim(2)?);
|
| 39 |
+
let dev = vid.device();
|
| 40 |
+
let mut linhas: Vec<Tensor> = Vec::new();
|
| 41 |
+
for tt in (0..t).step_by(pt) {
|
| 42 |
+
let tl = pt.min(t - tt);
|
| 43 |
+
for y in (0..h).step_by(ph) {
|
| 44 |
+
for x in (0..w).step_by(pw) {
|
| 45 |
+
let hh = ph.min(h - y);
|
| 46 |
+
let ww = pw.min(w - x);
|
| 47 |
+
let tubo = vid
|
| 48 |
+
.narrow(0, tt, tl)?
|
| 49 |
+
.narrow(1, y, hh)?
|
| 50 |
+
.narrow(2, x, ww)?
|
| 51 |
+
.flatten_all()?;
|
| 52 |
+
let mut buf = tubo.to_vec1::<f32>()?;
|
| 53 |
+
let falta = pt * ph * pw - buf.len();
|
| 54 |
+
buf.extend(std::iter::repeat(0f32).take(falta));
|
| 55 |
+
linhas.push(Tensor::from_vec(buf, (pt * ph * pw,), &dev)?);
|
| 56 |
+
}
|
| 57 |
+
}
|
| 58 |
+
}
|
| 59 |
+
Ok(Tensor::stack(&linhas, 0)?)
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
/// (F, τ) → patches (F/pf · τ/pt, pf·pt) — Audio-JEPA.
|
| 63 |
+
pub fn em_patches_espectrograma(spec: &Tensor, pf: usize, pt: usize) -> Result<Tensor> {
|
| 64 |
+
let (f, tau) = (spec.dim(0)?, spec.dim(1)?);
|
| 65 |
+
let dev = spec.device();
|
| 66 |
+
let mut linhas: Vec<Tensor> = Vec::new();
|
| 67 |
+
for i in (0..f).step_by(pf) {
|
| 68 |
+
for j in (0..tau).step_by(pt) {
|
| 69 |
+
let ff = pf.min(f - i);
|
| 70 |
+
let tt = pt.min(tau - j);
|
| 71 |
+
let p = spec.narrow(0, i, ff)?.narrow(1, j, tt)?.flatten_all()?;
|
| 72 |
+
let mut buf = p.to_vec1::<f32>()?;
|
| 73 |
+
let falta = pf * pt - buf.len();
|
| 74 |
+
buf.extend(std::iter::repeat(0f32).take(falta));
|
| 75 |
+
linhas.push(Tensor::from_vec(buf, (pf * pt,), &dev)?);
|
| 76 |
+
}
|
| 77 |
+
}
|
| 78 |
+
Ok(Tensor::stack(&linhas, 0)?)
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
/// (C, T) → patches canal-independentes (C · T/pt, pt) — T-JEPA/Brain-JEPA.
|
| 82 |
+
pub fn em_patches_serie(ts: &Tensor, pt: usize) -> Result<Tensor> {
|
| 83 |
+
let (c, t) = (ts.dim(0)?, ts.dim(1)?);
|
| 84 |
+
let dev = ts.device();
|
| 85 |
+
let mut linhas: Vec<Tensor> = Vec::new();
|
| 86 |
+
for ch in 0..c {
|
| 87 |
+
for j in (0..t).step_by(pt) {
|
| 88 |
+
let tt = pt.min(t - j);
|
| 89 |
+
let p = ts.narrow(0, ch, 1)?.narrow(1, j, tt)?.flatten_all()?;
|
| 90 |
+
let mut buf = p.to_vec1::<f32>()?;
|
| 91 |
+
let falta = pt - buf.len();
|
| 92 |
+
buf.extend(std::iter::repeat(0f32).take(falta));
|
| 93 |
+
linhas.push(Tensor::from_vec(buf, (pt,), &dev)?);
|
| 94 |
+
}
|
| 95 |
+
}
|
| 96 |
+
Ok(Tensor::stack(&linhas, 0)?)
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
/// (X, Y, Z) → voxels (X/px · Y/py · Z/pz, px·py·pz) — 3D-JEPA.
|
| 100 |
+
pub fn em_voxels(vol: &Tensor, px: usize, py: usize, pz: usize) -> Result<Tensor> {
|
| 101 |
+
let (x, y, z) = (vol.dim(0)?, vol.dim(1)?, vol.dim(2)?);
|
| 102 |
+
let dev = vol.device();
|
| 103 |
+
let mut linhas: Vec<Tensor> = Vec::new();
|
| 104 |
+
for i in (0..x).step_by(px) {
|
| 105 |
+
for j in (0..y).step_by(py) {
|
| 106 |
+
for k in (0..z).step_by(pz) {
|
| 107 |
+
let lx = px.min(x - i);
|
| 108 |
+
let ly = py.min(y - j);
|
| 109 |
+
let lz = pz.min(z - k);
|
| 110 |
+
let p = vol.narrow(0, i, lx)?.narrow(1, j, ly)?.narrow(2, k, lz)?.flatten_all()?;
|
| 111 |
+
let mut buf = p.to_vec1::<f32>()?;
|
| 112 |
+
let falta = px * py * pz - buf.len();
|
| 113 |
+
buf.extend(std::iter::repeat(0f32).take(falta));
|
| 114 |
+
linhas.push(Tensor::from_vec(buf, (px * py * pz,), &dev)?);
|
| 115 |
+
}
|
| 116 |
+
}
|
| 117 |
+
}
|
| 118 |
+
Ok(Tensor::stack(&linhas, 0)?)
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
/// Nuvem de pontos (n, d) → grupos FPS (k, m·d): k centros por FPS, cada
|
| 122 |
+
/// grupo = os m vizinhos mais próximos do centro (concatenados) — Point-JEPA.
|
| 123 |
+
pub fn em_grupos_pontos(pc: &Tensor, k: usize, m: usize, rng: &mut RngDeterministico) -> Result<Tensor> {
|
| 124 |
+
let n = pc.dim(0)?;
|
| 125 |
+
let d = pc.dim(1)?;
|
| 126 |
+
let coords = pc.to_vec2::<f32>()?;
|
| 127 |
+
let coords_f: Vec<Vec<f64>> = coords.iter().map(|r| r.iter().map(|&v| v as f64).collect()).collect();
|
| 128 |
+
let centros = pontos_mais_distantes(&coords_f, k, rng);
|
| 129 |
+
let dev = pc.device();
|
| 130 |
+
let mut linhas: Vec<Tensor> = Vec::new();
|
| 131 |
+
for &ci in ¢ros {
|
| 132 |
+
// m vizinhos mais próximos do centro ci (incluindo ele próprio)
|
| 133 |
+
let mut ord: Vec<usize> = (0..n).collect();
|
| 134 |
+
ord.sort_by(|&a, &b| {
|
| 135 |
+
let da = distancia_eucl(&coords_f[a], &coords_f[ci]);
|
| 136 |
+
let db = distancia_eucl(&coords_f[b], &coords_f[ci]);
|
| 137 |
+
da.partial_cmp(&db).unwrap()
|
| 138 |
+
});
|
| 139 |
+
let mut buf: Vec<f32> = Vec::with_capacity(m * d);
|
| 140 |
+
for &idx in ord.iter().take(m) {
|
| 141 |
+
for j in 0..d {
|
| 142 |
+
buf.push(coords[idx][j]);
|
| 143 |
+
}
|
| 144 |
+
}
|
| 145 |
+
let falta = m * d - buf.len();
|
| 146 |
+
buf.extend(std::iter::repeat(0f32).take(falta));
|
| 147 |
+
linhas.push(Tensor::from_vec(buf, (m * d,), &dev)?);
|
| 148 |
+
}
|
| 149 |
+
Ok(Tensor::stack(&linhas, 0)?)
|
| 150 |
+
}
|
laboratorio/arquivo_split_v100/jepa/replay_ssm.rs
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! `jepa::replay_ssm` — extraído do monólito na v0.10.0
|
| 2 |
+
//! (divisão SRP, crítica Qwen3.8 lote 3 nº 1; r-35 §2).
|
| 3 |
+
|
| 4 |
+
use super::*;
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
// ---------------------------------------------------------------------------
|
| 8 |
+
// Parte 6 — ReplaySSM
|
| 9 |
+
// ---------------------------------------------------------------------------
|
| 10 |
+
|
| 11 |
+
/// SSM de porta diagonal com replay para aprendizado continuado.
|
| 12 |
+
///
|
| 13 |
+
/// Recorrência: `h_t = σ(a) ⊙ h_{t−1} + (1 − σ(a)) ⊙ (B x_t)`.
|
| 14 |
+
///
|
| 15 |
+
/// **Prova R-1 (estabilidade):** `|σ(a)| < 1` ⇒ perturbações de `h_0`
|
| 16 |
+
/// decaem geometricamente (mesma estrutura do Teo S-2' do SSD-Δ).
|
| 17 |
+
///
|
| 18 |
+
/// **Prova R-2 (limite de esquecimento):** o passo de treino mistura
|
| 19 |
+
/// gradientes `(1−α)·∇L_novo + α·∇L_replay`; para `L_antiga` μ-fortemente
|
| 20 |
+
/// convexa com gradientes novos limitados por `G`, o afastamento do ótimo
|
| 21 |
+
/// antigo por passo é `≤ (1−α)·η·G` (sem replay: `≤ η·G`) — o replay
|
| 22 |
+
/// contrai o drift por um fator `1/(1−α)` no regime linear.
|
| 23 |
+
pub struct ReplaySsm {
|
| 24 |
+
pub a: Var, // (d,) — porta (sigmoid no uso)
|
| 25 |
+
pub b: Var, // (d_in, d) — projeção de entrada
|
| 26 |
+
pub d: usize,
|
| 27 |
+
pub alpha_replay: f64,
|
| 28 |
+
pub buffer: Vec<Tensor>,
|
| 29 |
+
pub capacidade_buffer: usize,
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
impl ReplaySsm {
|
| 33 |
+
pub fn novo(d_in: usize, d: usize, alpha_replay: f64, capacidade_buffer: usize, dev: &Device) -> Result<Self> {
|
| 34 |
+
let a_t = Tensor::randn(0f32, 0.5, (d,), dev)?;
|
| 35 |
+
let b_t = Tensor::randn(0f32, 0.1, (d_in, d), dev)?;
|
| 36 |
+
Ok(Self {
|
| 37 |
+
a: Var::from_tensor(&a_t)?,
|
| 38 |
+
b: Var::from_tensor(&b_t)?,
|
| 39 |
+
d,
|
| 40 |
+
alpha_replay,
|
| 41 |
+
buffer: Vec::new(),
|
| 42 |
+
capacidade_buffer,
|
| 43 |
+
})
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
pub fn vars(&self) -> Vec<Var> {
|
| 47 |
+
vec![self.a.clone(), self.b.clone()]
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
/// Scan: x (T, d_in) → h (T, d). Diferenciável (candle autograd).
|
| 51 |
+
pub fn scan(&self, x: &Tensor) -> Result<Tensor> {
|
| 52 |
+
let t = x.dim(0)?;
|
| 53 |
+
let dev = x.device();
|
| 54 |
+
let porta = candle_nn::ops::sigmoid(&self.a.as_tensor().broadcast_as((1, self.d))?)?; // (1, d)
|
| 55 |
+
let um_menos = porta.affine(-1.0, 1.0)?; // 1 − σ(a)
|
| 56 |
+
let entrada = x.matmul(&self.b.as_tensor())?; // (T, d)
|
| 57 |
+
let mut h = Tensor::zeros((1, self.d), candle_core::DType::F32, &dev)?;
|
| 58 |
+
let mut saidas: Vec<Tensor> = Vec::with_capacity(t);
|
| 59 |
+
for i in 0..t {
|
| 60 |
+
let xt = entrada.narrow(0, i, 1)?;
|
| 61 |
+
h = ((&porta * &h)? + (&um_menos * &xt)?)?;
|
| 62 |
+
saidas.push(h.clone());
|
| 63 |
+
}
|
| 64 |
+
Ok(Tensor::stack(&saidas, 0)?)
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
/// Empurra uma janela de treino no buffer (FIFO).
|
| 68 |
+
pub fn guardar(&mut self, x: &Tensor) {
|
| 69 |
+
if self.buffer.len() >= self.capacidade_buffer {
|
| 70 |
+
self.buffer.remove(0);
|
| 71 |
+
}
|
| 72 |
+
self.buffer.push(x.detach());
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
/// Um passo de treino no lote novo (com mistura de replay).
|
| 76 |
+
/// Devolve (perda_total, perda_novo, perda_replay).
|
| 77 |
+
pub fn passo_treino(
|
| 78 |
+
&mut self,
|
| 79 |
+
x: &Tensor,
|
| 80 |
+
alvo: &Tensor,
|
| 81 |
+
otimizador: &mut crate::treino::AdamWManual,
|
| 82 |
+
) -> Result<(f64, f64, f64)> {
|
| 83 |
+
// perda nova
|
| 84 |
+
let h = self.scan(x)?;
|
| 85 |
+
let dif = (&h - alvo)?;
|
| 86 |
+
let perda_novo = dif.sqr()?.mean_all()?;
|
| 87 |
+
// replay
|
| 88 |
+
let mut perda_total = perda_novo.clone();
|
| 89 |
+
let mut p_r = 0.0;
|
| 90 |
+
if !self.buffer.is_empty() {
|
| 91 |
+
let idx = self.buffer.len() - 1;
|
| 92 |
+
let antigo = self.buffer[idx].clone();
|
| 93 |
+
let hr = self.scan(&antigo)?;
|
| 94 |
+
// alvo do replay: manter a dinâmica aprendida estável (magnitudes
|
| 95 |
+
// finitas) — auto-supervisão de estabilidade
|
| 96 |
+
let dr = hr.sqr()?.mean_all()?;
|
| 97 |
+
perda_total = (perda_total.affine(1.0 - self.alpha_replay, 0.0)?
|
| 98 |
+
+ dr.affine(self.alpha_replay, 0.0)?)?;
|
| 99 |
+
p_r = dr.to_scalar::<f32>()? as f64;
|
| 100 |
+
}
|
| 101 |
+
let pn = perda_novo.to_scalar::<f32>()? as f64;
|
| 102 |
+
otimizador.passo(crate::treino::grads_achatados(&perda_total, &self.vars())?);
|
| 103 |
+
self.guardar(x);
|
| 104 |
+
let pt = perda_total.to_scalar::<f32>()? as f64;
|
| 105 |
+
Ok((pt, pn, p_r))
|
| 106 |
+
}
|
| 107 |
+
}
|
laboratorio/arquivo_split_v100/jepa/sonic_moe.rs
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! `jepa::sonic_moe` — extraído do monólito na v0.10.0
|
| 2 |
+
//! (divisão SRP, crítica Qwen3.8 lote 3 nº 1; r-35 §2).
|
| 3 |
+
|
| 4 |
+
use super::*;
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
// ---------------------------------------------------------------------------
|
| 8 |
+
// Parte 5 — SonicMoE (IO/tile-aware)
|
| 9 |
+
// ---------------------------------------------------------------------------
|
| 10 |
+
|
| 11 |
+
/// MoE top-k com capacidade por especialista e perda de balanceamento.
|
| 12 |
+
///
|
| 13 |
+
/// **Prova SM-1 (limite de capacidade):** o roteamento tile-aware mantém no
|
| 14 |
+
/// máximo `C` tokens por especialista por ladrilho — o drop é determinístico
|
| 15 |
+
/// (ordem de chegada) e o nº de tokens descartados é `Σ_e max(0, load_e − C)`.
|
| 16 |
+
///
|
| 17 |
+
/// **Prova SM-2 (balanceamento):** `L_aux = E·Σ_e f_e·p_e`; com roteamento
|
| 18 |
+
/// auto-consistente (`f = p`), `L_aux = E·Σ p_e² ≥ 1` com igualdade sse
|
| 19 |
+
/// `p_e = 1/E` (Cauchy–Schchwarz) — o mínimo força o roteador uniforme.
|
| 20 |
+
pub struct SonicMoe {
|
| 21 |
+
pub roteador: Linear, // d → E
|
| 22 |
+
pub especialistas: Vec<MlpJepa>, // E experts d → d
|
| 23 |
+
pub n_top: usize,
|
| 24 |
+
pub capacidade: usize,
|
| 25 |
+
pub lambda_aux: f64,
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
pub struct SaidaMoe {
|
| 29 |
+
pub saida: Tensor,
|
| 30 |
+
pub perda_aux: Tensor,
|
| 31 |
+
pub carga: Vec<usize>, // tokens efetivamente processados por especialista
|
| 32 |
+
pub descartados: usize, // tokens com especialistas cortados pela capacidade
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
impl SonicMoe {
|
| 36 |
+
pub fn novo(d: usize, n_expertos: usize, n_top: usize, capacidade: usize, dev: &Device) -> Result<Self> {
|
| 37 |
+
let roteador = Linear::sem_vies(d, n_expertos, 0.1, dev)?;
|
| 38 |
+
let especialistas = (0..n_expertos)
|
| 39 |
+
.map(|_| MlpJepa::novo(d, 2 * d, d, dev))
|
| 40 |
+
.collect::<Result<Vec<_>>>()?;
|
| 41 |
+
Ok(Self { roteador, especialistas, n_top, capacidade, lambda_aux: 0.01 })
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
pub fn vars(&self) -> Vec<Var> {
|
| 45 |
+
let mut v = self.roteador.vars();
|
| 46 |
+
for e in &self.especialistas {
|
| 47 |
+
v.extend(e.vars());
|
| 48 |
+
}
|
| 49 |
+
v
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
/// Forward tile-aware: (n, d) → (n, d).
|
| 53 |
+
pub fn fwd(&self, x: &Tensor) -> Result<SaidaMoe> {
|
| 54 |
+
let n = x.dim(0)?;
|
| 55 |
+
let d = x.dim(1)?;
|
| 56 |
+
let e = self.especialistas.len();
|
| 57 |
+
let dev = x.device();
|
| 58 |
+
let logits = self.roteador.fwd(x)?; // (n, E)
|
| 59 |
+
let probs = candle_nn::ops::softmax(&logits, candle_core::D::Minus1)?;
|
| 60 |
+
|
| 61 |
+
// top-k por token (não diferenciável — pesos do top-k são dif. via probs)
|
| 62 |
+
let probs_v = probs.to_vec2::<f32>()?;
|
| 63 |
+
let mut carga = vec![0usize; e];
|
| 64 |
+
let mut descartados = 0usize;
|
| 65 |
+
// acumulador de saída (n, d) — construído por soma de contribuições
|
| 66 |
+
let mut saida = Tensor::zeros((n, d), candle_core::DType::F32, &dev)?;
|
| 67 |
+
let mut peso_total = Tensor::zeros((n, 1), candle_core::DType::F32, &dev)?;
|
| 68 |
+
// por especialista (tile): tokens cujo top-k contém e e com carga < C
|
| 69 |
+
for ei in 0..e {
|
| 70 |
+
// candidatos: tokens ordenados por prob do especialista ei
|
| 71 |
+
let mut cand: Vec<(usize, f32)> = (0..n)
|
| 72 |
+
.map(|i| (i, probs_v[i][ei]))
|
| 73 |
+
.collect();
|
| 74 |
+
cand.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
|
| 75 |
+
let mut escolhidos: Vec<usize> = Vec::new();
|
| 76 |
+
for (i, _) in cand {
|
| 77 |
+
if carga[ei] >= self.capacidade {
|
| 78 |
+
break;
|
| 79 |
+
}
|
| 80 |
+
// verifica se ei está no top-k do token i
|
| 81 |
+
let mut ordem: Vec<(f32, usize)> =
|
| 82 |
+
(0..e).map(|k| (probs_v[i][k], k)).collect();
|
| 83 |
+
ordem.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap());
|
| 84 |
+
let top: Vec<usize> = ordem.iter().rev().take(self.n_top).map(|(_, k)| *k).collect();
|
| 85 |
+
if top.contains(&ei) {
|
| 86 |
+
escolhidos.push(i);
|
| 87 |
+
carga[ei] += 1;
|
| 88 |
+
}
|
| 89 |
+
}
|
| 90 |
+
if escolhidos.is_empty() {
|
| 91 |
+
continue;
|
| 92 |
+
}
|
| 93 |
+
// tile do especialista: uma única passagem em lote
|
| 94 |
+
let idx: Vec<u32> = escolhidos.iter().map(|&i| i as u32).collect();
|
| 95 |
+
let n_e = idx.len();
|
| 96 |
+
let idx_t = Tensor::from_vec(idx, (n_e,), &dev)?;
|
| 97 |
+
let tile = x.index_select(&idx_t, 0)?;
|
| 98 |
+
let y = self.especialistas[ei].fwd(&tile)?; // (m, d)
|
| 99 |
+
// pesos: prob do especialista ei para cada token escolhido
|
| 100 |
+
let w: Vec<f32> = escolhidos.iter().map(|&i| probs_v[i][ei]).collect();
|
| 101 |
+
let n_w = escolhidos.len();
|
| 102 |
+
let w_t = Tensor::from_vec(w.clone(), (n_w, 1), &dev)?;
|
| 103 |
+
let contrib = y.broadcast_mul(&w_t)?;
|
| 104 |
+
// scatter-add: acumula nas posições
|
| 105 |
+
let mut buf = saida.to_vec2::<f32>()?;
|
| 106 |
+
let contrib_v = contrib.to_vec2::<f32>()?;
|
| 107 |
+
for (k, &i) in escolhidos.iter().enumerate() {
|
| 108 |
+
for j in 0..d {
|
| 109 |
+
buf[i][j] += contrib_v[k][j];
|
| 110 |
+
}
|
| 111 |
+
}
|
| 112 |
+
saida = Tensor::from_vec(
|
| 113 |
+
buf.into_iter().flatten().collect::<Vec<f32>>(),
|
| 114 |
+
(n, d),
|
| 115 |
+
&dev,
|
| 116 |
+
)?;
|
| 117 |
+
let mut pt = peso_total.to_vec2::<f32>()?;
|
| 118 |
+
for (k, &i) in escolhidos.iter().enumerate() {
|
| 119 |
+
pt[i][0] += w[k];
|
| 120 |
+
}
|
| 121 |
+
peso_total = Tensor::from_vec(
|
| 122 |
+
pt.into_iter().flatten().collect::<Vec<f32>>(),
|
| 123 |
+
(n, 1),
|
| 124 |
+
&dev,
|
| 125 |
+
)?;
|
| 126 |
+
}
|
| 127 |
+
// tokens sem especialista (todos cortados) → descartados; saída 0
|
| 128 |
+
let pt_v = peso_total.to_vec2::<f32>()?;
|
| 129 |
+
for i in 0..n {
|
| 130 |
+
if pt_v[i][0] == 0.0 {
|
| 131 |
+
descartados += 1;
|
| 132 |
+
}
|
| 133 |
+
}
|
| 134 |
+
// renormaliza pelo peso efetivo (evita viés da capacidade)
|
| 135 |
+
let denom = peso_total.clamp(1e-6, f64::INFINITY)?;
|
| 136 |
+
let saida = saida.broadcast_div(&denom)?;
|
| 137 |
+
|
| 138 |
+
// perda auxiliar: E·Σ f_e·p_e (f = fração de tokens cujo top-1 é e)
|
| 139 |
+
let mut f = vec![0f32; e];
|
| 140 |
+
for i in 0..n {
|
| 141 |
+
let (mut melhor, mut mp) = (0usize, f32::NEG_INFINITY);
|
| 142 |
+
for k in 0..e {
|
| 143 |
+
if probs_v[i][k] > mp {
|
| 144 |
+
mp = probs_v[i][k];
|
| 145 |
+
melhor = k;
|
| 146 |
+
}
|
| 147 |
+
}
|
| 148 |
+
f[melhor] += 1.0 / n as f32;
|
| 149 |
+
}
|
| 150 |
+
let f_t = Tensor::from_vec(f, (e,), &dev)?;
|
| 151 |
+
let p_media = probs.mean(0)?; // (E,)
|
| 152 |
+
let perda_aux = ((&f_t * &p_media)?.sum_all()? * (e as f64))?;
|
| 153 |
+
Ok(SaidaMoe { saida, perda_aux, carga, descartados })
|
| 154 |
+
}
|
| 155 |
+
}
|
laboratorio/arquivo_split_v100/jepa/testes.rs
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! `jepa::testes` — extraído do monólito na v0.10.0
|
| 2 |
+
//! (divisão SRP, crítica Qwen3.8 lote 3 nº 1; r-35 §2).
|
| 3 |
+
|
| 4 |
+
use super::*;
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
#[cfg(test)]
|
| 8 |
+
mod testes {
|
| 9 |
+
use super::*;
|
| 10 |
+
|
| 11 |
+
fn tensor_2d(dados: &[Vec<f64>], dev: &Device) -> Tensor {
|
| 12 |
+
let flat: Vec<f32> = dados.iter().flat_map(|v| v.iter().map(|&x| x as f32)).collect();
|
| 13 |
+
Tensor::from_vec(flat, (dados.len(), dados[0].len()), dev).unwrap()
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
#[test]
|
| 17 |
+
fn teste_mascaras_validas() {
|
| 18 |
+
// fração respeitada ±, particionamento contexto/alvo não-vazio
|
| 19 |
+
let mut rng = RngDeterministico::novo(1);
|
| 20 |
+
let m2 = mascara_blocos_2d(8, 8, 4, 0.3, &mut rng);
|
| 21 |
+
assert_eq!(m2.len(), 64);
|
| 22 |
+
let frac = m2.iter().filter(|&&b| b).count() as f64 / 64.0;
|
| 23 |
+
assert!(frac >= 0.15 && frac <= 0.55, "frac 2d = {frac}");
|
| 24 |
+
assert!(m2.iter().any(|&b| !b), "contexto vazio");
|
| 25 |
+
|
| 26 |
+
let m3 = mascara_tubos_3d(4, 6, 6, 3, 0.3, &mut rng);
|
| 27 |
+
assert_eq!(m3.len(), 144);
|
| 28 |
+
let f3 = m3.iter().filter(|&&b| b).count() as f64 / 144.0;
|
| 29 |
+
assert!(f3 >= 0.15 && f3 <= 0.6, "frac 3d = {f3}");
|
| 30 |
+
|
| 31 |
+
let ms = mascara_segmentos(4, 32, 0.25, &mut rng);
|
| 32 |
+
assert_eq!(ms.len(), 128);
|
| 33 |
+
assert!(ms.iter().any(|&b| b) && ms.iter().any(|&b| !b));
|
| 34 |
+
|
| 35 |
+
let m1 = mascara_intervalos_1d(64, 0.3, &mut rng);
|
| 36 |
+
let f1 = m1.iter().filter(|&&b| b).count() as f64 / 64.0;
|
| 37 |
+
assert!(f1 >= 0.25 && f1 <= 0.45, "frac 1d = {f1}");
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
#[test]
|
| 41 |
+
fn teste_fps_cobre() {
|
| 42 |
+
let mut rng = RngDeterministico::novo(2);
|
| 43 |
+
let pontos: Vec<Vec<f64>> = (0..40)
|
| 44 |
+
.map(|i| {
|
| 45 |
+
let a = i as f64 * 0.1;
|
| 46 |
+
vec![a.cos() * 3.0, a.sin() * 3.0, (i % 7) as f64 * 0.3]
|
| 47 |
+
})
|
| 48 |
+
.collect();
|
| 49 |
+
let centros = pontos_mais_distantes(&pontos, 6, &mut rng);
|
| 50 |
+
assert_eq!(centros.len(), 6);
|
| 51 |
+
// centros distintos
|
| 52 |
+
let mut s = centros.clone();
|
| 53 |
+
s.sort();
|
| 54 |
+
s.dedup();
|
| 55 |
+
assert_eq!(s.len(), 6);
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
#[test]
|
| 59 |
+
fn teste_j1_colapso_impossivel() {
|
| 60 |
+
// No colapso total (z constante), a perda VC = γ² > 0 — verificando a
|
| 61 |
+
// fórmula implementada com um lote constante.
|
| 62 |
+
let dev = Device::Cpu;
|
| 63 |
+
let nucleo = NucleoJepa::novo(4, 8, 0, 4, 0.99, 1.0, 1.0, &dev).unwrap();
|
| 64 |
+
let z = Tensor::from_vec(vec![0.5f32; 8 * 8], (8, 8), &dev).unwrap();
|
| 65 |
+
let lvc = nucleo.perda_vc(&z).unwrap();
|
| 66 |
+
let v = lvc.to_scalar::<f32>().unwrap() as f64;
|
| 67 |
+
// std=0 ⇒ dobradiça = γ = 1 ⇒ V/d = 1; cov = 0
|
| 68 |
+
assert!(v > 0.9, "perda VC no colapso = {v} (deveria ser ~1)");
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
#[test]
|
| 72 |
+
fn teste_j2_ema_ponto_fixo() {
|
| 73 |
+
// encoder congelado ⇒ após muitas passadas EMA, alvo = encoder
|
| 74 |
+
let dev = Device::Cpu;
|
| 75 |
+
let mut nucleo = NucleoJepa::novo(4, 8, 0, 4, 0.5, 0.1, 1.0, &dev).unwrap();
|
| 76 |
+
for _ in 0..40 {
|
| 77 |
+
nucleo.ema_passo().unwrap();
|
| 78 |
+
}
|
| 79 |
+
let a = nucleo.alvo.vars()[0].as_tensor().flatten_all().unwrap().to_vec1::<f32>().unwrap();
|
| 80 |
+
let b = nucleo.encoder.vars()[0].as_tensor().flatten_all().unwrap().to_vec1::<f32>().unwrap();
|
| 81 |
+
let dif: f32 = a.iter().zip(&b).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max);
|
| 82 |
+
assert!(dif < 1e-5, "EMA não convergiu: dif máx = {dif}");
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
#[test]
|
| 86 |
+
fn teste_jepa_aprende_latente_previsivel() {
|
| 87 |
+
// J-3: com alvo previsível (função determinística do contexto), a
|
| 88 |
+
// perda pred must cair substancialmente e o std das incorporações
|
| 89 |
+
// NÃO colapsa (J-1).
|
| 90 |
+
let dev = Device::Cpu;
|
| 91 |
+
let mut rng = RngDeterministico::novo(3);
|
| 92 |
+
// patches = 64 vetores 8-D em 4 grupos (estrutura previsível)
|
| 93 |
+
let mut dados: Vec<Vec<f64>> = Vec::new();
|
| 94 |
+
for g in 0..4 {
|
| 95 |
+
let c = g as f64 * 2.0;
|
| 96 |
+
for _ in 0..16 {
|
| 97 |
+
dados.push((0..8).map(|k| c + rng.normal(0.0, 0.3) + (k as f64) * 0.05).collect());
|
| 98 |
+
}
|
| 99 |
+
}
|
| 100 |
+
let patches = tensor_2d(&dados, &dev);
|
| 101 |
+
let cfg = CfgJepa { d_emb: 16, epocas: 40, lr: 5e-3, ..Default::default() };
|
| 102 |
+
let rel = treinar_variante(
|
| 103 |
+
&patches,
|
| 104 |
+
&|n, r| mascara_intervalos_1d(n, 0.3, r),
|
| 105 |
+
&cfg,
|
| 106 |
+
VarianteJepa::TJepa,
|
| 107 |
+
None,
|
| 108 |
+
&dev,
|
| 109 |
+
)
|
| 110 |
+
.unwrap();
|
| 111 |
+
assert!(
|
| 112 |
+
rel.perda_final < rel.perda_inicial * 0.8,
|
| 113 |
+
"perda deveria cair: {} → {}",
|
| 114 |
+
rel.perda_inicial,
|
| 115 |
+
rel.perda_final
|
| 116 |
+
);
|
| 117 |
+
assert!(
|
| 118 |
+
rel.std_emb_final > 0.05,
|
| 119 |
+
"sem colapso: std_final = {}",
|
| 120 |
+
rel.std_emb_final
|
| 121 |
+
);
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
#[test]
|
| 125 |
+
fn teste_adaptadores_formas() {
|
| 126 |
+
let dev = Device::Cpu;
|
| 127 |
+
let img = Tensor::randn(0f32, 1.0, (3, 16, 16), &dev).unwrap();
|
| 128 |
+
let p = em_patches_2d(&img, 4, 4).unwrap();
|
| 129 |
+
assert_eq!(p.dims().to_vec(), vec![16, 48]);
|
| 130 |
+
|
| 131 |
+
let vid = Tensor::randn(0f32, 1.0, (4, 8, 8), &dev).unwrap();
|
| 132 |
+
let t3 = em_tubos_3d(&vid, 2, 4, 4).unwrap();
|
| 133 |
+
assert_eq!(t3.dims().to_vec(), vec![8, 32]);
|
| 134 |
+
|
| 135 |
+
let spec = Tensor::randn(0f32, 1.0, (16, 32), &dev).unwrap();
|
| 136 |
+
let ps = em_patches_espectrograma(&spec, 4, 8).unwrap();
|
| 137 |
+
assert_eq!(ps.dims().to_vec(), vec![16, 32]);
|
| 138 |
+
|
| 139 |
+
let ts = Tensor::randn(0f32, 1.0, (4, 32), &dev).unwrap();
|
| 140 |
+
let pt_ = em_patches_serie(&ts, 8).unwrap();
|
| 141 |
+
assert_eq!(pt_.dims().to_vec(), vec![16, 8]);
|
| 142 |
+
|
| 143 |
+
let vol = Tensor::randn(0f32, 1.0, (8, 8, 8), &dev).unwrap();
|
| 144 |
+
let vx = em_voxels(&vol, 4, 4, 4).unwrap();
|
| 145 |
+
assert_eq!(vx.dims().to_vec(), vec![8, 64]);
|
| 146 |
+
|
| 147 |
+
let pc = Tensor::randn(0f32, 1.0, (50, 3), &dev).unwrap();
|
| 148 |
+
let mut rng = RngDeterministico::novo(5);
|
| 149 |
+
let gr = em_grupos_pontos(&pc, 6, 4, &mut rng).unwrap();
|
| 150 |
+
assert_eq!(gr.dims().to_vec(), vec![6, 12]);
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
#[test]
|
| 154 |
+
fn teste_sonic_moe_capacidade_e_balanceamento() {
|
| 155 |
+
// SM-1: carga por especialista ≤ capacidade; SM-2: aux ≥ ~1 quando
|
| 156 |
+
// roteador é ~uniforme (início).
|
| 157 |
+
let dev = Device::Cpu;
|
| 158 |
+
let moe = SonicMoe::novo(8, 4, 2, 6, &dev).unwrap();
|
| 159 |
+
let x = Tensor::randn(0f32, 1.0, (20, 8), &dev).unwrap();
|
| 160 |
+
let s = moe.fwd(&x).unwrap();
|
| 161 |
+
for (e, c) in s.carga.iter().enumerate() {
|
| 162 |
+
assert!(*c <= 6, "especialista {e} com carga {c} > capacidade 6");
|
| 163 |
+
}
|
| 164 |
+
assert_eq!(s.saida.dims().to_vec(), vec![20, 8]);
|
| 165 |
+
let aux = s.perda_aux.to_scalar::<f32>().unwrap() as f64;
|
| 166 |
+
// com roteador quase uniforme, aux ≈ E·Σ (1/E)·(1/E) = 1
|
| 167 |
+
assert!(aux > 0.5 && aux < 3.0, "aux = {aux}");
|
| 168 |
+
// cada token processado por ≤ n_top especialistas
|
| 169 |
+
let total_carga: usize = s.carga.iter().sum();
|
| 170 |
+
assert!(total_carga <= 20 * 2, "carga total {total_carga} > n·topk");
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
#[test]
|
| 174 |
+
fn teste_replay_ssm_estabilidade_e_replay() {
|
| 175 |
+
// R-1: estados finitos e limitados; R-2: com replay α>0, após treinar
|
| 176 |
+
// a tarefa nova, a dinâmica antiga (magnitude do estado) permanece
|
| 177 |
+
// estável (não diverge).
|
| 178 |
+
let dev = Device::Cpu;
|
| 179 |
+
let mut ssm = ReplaySsm::novo(4, 6, 0.5, 8, &dev).unwrap();
|
| 180 |
+
let vars = ssm.vars();
|
| 181 |
+
let mut otim = crate::treino::AdamWManual::novo(vars, 1e-2, 0.0);
|
| 182 |
+
|
| 183 |
+
// tarefa "antiga": sinal constante 1.0
|
| 184 |
+
let x_antigo = Tensor::from_vec(vec![1.0f32; 16 * 4], (16, 4), &dev).unwrap();
|
| 185 |
+
for _ in 0..30 {
|
| 186 |
+
let h = ssm.scan(&x_antigo).unwrap();
|
| 187 |
+
let alvo = h.detach();
|
| 188 |
+
ssm.passo_treino(&x_antigo, &alvo, &mut otim).unwrap();
|
| 189 |
+
}
|
| 190 |
+
// estado após treino antigo: finito
|
| 191 |
+
let h1 = ssm.scan(&x_antigo).unwrap();
|
| 192 |
+
let m1 = h1.abs().unwrap().max_all().unwrap().to_scalar::<f32>().unwrap();
|
| 193 |
+
assert!(m1.is_finite() && m1 < 50.0, "estado explodiu: {m1}");
|
| 194 |
+
|
| 195 |
+
// tarefa "nova": sinal −1.0 — treino com replay
|
| 196 |
+
let x_novo = Tensor::from_vec(vec![-1.0f32; 16 * 4], (16, 4), &dev).unwrap();
|
| 197 |
+
for _ in 0..30 {
|
| 198 |
+
let h = ssm.scan(&x_novo).unwrap();
|
| 199 |
+
let alvo = h.detach();
|
| 200 |
+
ssm.passo_treino(&x_novo, &alvo, &mut otim).unwrap();
|
| 201 |
+
}
|
| 202 |
+
// a dinâmica antiga continua estável (sem explosão)
|
| 203 |
+
let h2 = ssm.scan(&x_antigo).unwrap();
|
| 204 |
+
let m2 = h2.abs().unwrap().max_all().unwrap().to_scalar::<f32>().unwrap();
|
| 205 |
+
assert!(m2.is_finite() && m2 < 50.0, "estado antigo explodiu: {m2}");
|
| 206 |
+
// portas dentro de (0,1)
|
| 207 |
+
let a = ssm.a.as_tensor().to_vec1::<f32>().unwrap();
|
| 208 |
+
for v in a {
|
| 209 |
+
assert!(v.is_finite());
|
| 210 |
+
}
|
| 211 |
+
}
|
| 212 |
+
}
|
laboratorio/arquivo_split_v100/jepa/variantes.rs
ADDED
|
@@ -0,0 +1,476 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! `jepa::variantes` — extraído do monólito na v0.10.0
|
| 2 |
+
//! (divisão SRP, crítica Qwen3.8 lote 3 nº 1; r-35 §2).
|
| 3 |
+
|
| 4 |
+
use super::*;
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
// ---------------------------------------------------------------------------
|
| 8 |
+
// Parte 4 — variantes e treino unificado
|
| 9 |
+
// ---------------------------------------------------------------------------
|
| 10 |
+
|
| 11 |
+
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
| 12 |
+
pub enum VarianteJepa {
|
| 13 |
+
ImageJepa,
|
| 14 |
+
VJepa2,
|
| 15 |
+
McJepa,
|
| 16 |
+
AudioJepa,
|
| 17 |
+
PointJepa,
|
| 18 |
+
Jepa3D,
|
| 19 |
+
BrainJepa,
|
| 20 |
+
TJepa,
|
| 21 |
+
LeJepa,
|
| 22 |
+
BJepa,
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
impl VarianteJepa {
|
| 26 |
+
pub fn nome(&self) -> &'static str {
|
| 27 |
+
match self {
|
| 28 |
+
Self::ImageJepa => "Image-JEPA",
|
| 29 |
+
Self::VJepa2 => "V-JEPA 2",
|
| 30 |
+
Self::McJepa => "MC-JEPA",
|
| 31 |
+
Self::AudioJepa => "Audio-JEPA",
|
| 32 |
+
Self::PointJepa => "Point-JEPA",
|
| 33 |
+
Self::Jepa3D => "3D-JEPA",
|
| 34 |
+
Self::BrainJepa => "Brain-JEPA",
|
| 35 |
+
Self::TJepa => "T-JEPA",
|
| 36 |
+
Self::LeJepa => "LeJEPA",
|
| 37 |
+
Self::BJepa => "BJEPA",
|
| 38 |
+
}
|
| 39 |
+
}
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
#[derive(Debug, Clone)]
|
| 43 |
+
pub struct CfgJepa {
|
| 44 |
+
pub d_emb: usize,
|
| 45 |
+
pub epocas: usize,
|
| 46 |
+
pub lr: f64,
|
| 47 |
+
pub m: f64, // EMA
|
| 48 |
+
pub lambda_vc: f64,
|
| 49 |
+
pub gamma_vc: f64,
|
| 50 |
+
pub frac_mascara: f64,
|
| 51 |
+
pub semente: u64,
|
| 52 |
+
/// tamanho do bloco-alvo (nº de patches por bloco).
|
| 53 |
+
pub tam_bloco: usize,
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
impl Default for CfgJepa {
|
| 57 |
+
fn default() -> Self {
|
| 58 |
+
Self {
|
| 59 |
+
d_emb: 32,
|
| 60 |
+
epocas: 60,
|
| 61 |
+
lr: 1.5e-3,
|
| 62 |
+
m: 0.99,
|
| 63 |
+
lambda_vc: 0.5,
|
| 64 |
+
gamma_vc: 1.0,
|
| 65 |
+
frac_mascara: 0.35,
|
| 66 |
+
semente: 42,
|
| 67 |
+
tam_bloco: 2,
|
| 68 |
+
}
|
| 69 |
+
}
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
/// Relatório de treino de uma variante.
|
| 73 |
+
#[derive(Debug, Clone)]
|
| 74 |
+
pub struct RelatorioJepa {
|
| 75 |
+
pub variante: String,
|
| 76 |
+
pub perda_inicial: f64,
|
| 77 |
+
pub perda_final: f64,
|
| 78 |
+
/// perda PREDITIVA isolada (sem o regularizador VC) — critério de
|
| 79 |
+
/// aprendizado honesto (a VC pode crescer legitimamente ao empurrar o
|
| 80 |
+
/// std das incorporações para cima).
|
| 81 |
+
pub perda_pred_inicial: f64,
|
| 82 |
+
pub perda_pred_final: f64,
|
| 83 |
+
/// desvio-padrão médio por dimensão das incorporações (monitor de
|
| 84 |
+
/// colapso: → 0 = colapso).
|
| 85 |
+
pub std_emb_final: f64,
|
| 86 |
+
pub std_emb_inicial: f64,
|
| 87 |
+
pub n_patches: usize,
|
| 88 |
+
pub d_patch: usize,
|
| 89 |
+
pub epocas: usize,
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
/// Treina uma variante JEPA sobre patches já extraídos `(n, d_patch)` com
|
| 93 |
+
/// um esquema de máscara fornecido (padrão: intervalos 1D).
|
| 94 |
+
///
|
| 95 |
+
/// Máscara=true ⇒ patch é ALVO (bloco); false ⇒ CONTEXTO.
|
| 96 |
+
pub fn treinar_variante(
|
| 97 |
+
patches: &Tensor,
|
| 98 |
+
mascara: &dyn Fn(usize, &mut RngDeterministico) -> Vec<bool>,
|
| 99 |
+
cfg: &CfgJepa,
|
| 100 |
+
variante: VarianteJepa,
|
| 101 |
+
cond: Option<&Tensor>,
|
| 102 |
+
dev: &Device,
|
| 103 |
+
) -> Result<RelatorioJepa> {
|
| 104 |
+
let n = patches.dim(0)?;
|
| 105 |
+
let d_patch = patches.dim(1)?;
|
| 106 |
+
let mut rng = RngDeterministico::novo(cfg.semente);
|
| 107 |
+
let mut nucleo = NucleoJepa::novo(
|
| 108 |
+
d_patch,
|
| 109 |
+
cfg.d_emb,
|
| 110 |
+
if cond.is_some() { cond.unwrap().dim(1)? } else { 0 },
|
| 111 |
+
n,
|
| 112 |
+
cfg.m,
|
| 113 |
+
cfg.lambda_vc,
|
| 114 |
+
cfg.gamma_vc,
|
| 115 |
+
dev,
|
| 116 |
+
)?;
|
| 117 |
+
let otimo_vars = nucleo.vars();
|
| 118 |
+
let mut otimizador = crate::treino::AdamWManual::novo(otimo_vars, cfg.lr, 0.01);
|
| 119 |
+
|
| 120 |
+
// métricas iniciais
|
| 121 |
+
let z0 = nucleo.codificar(patches)?;
|
| 122 |
+
let std0 = std_por_dim(&z0)?;
|
| 123 |
+
|
| 124 |
+
let mut perda_inicial = f64::NAN;
|
| 125 |
+
let mut perda_final = f64::NAN;
|
| 126 |
+
let mut pred_inicial = f64::NAN;
|
| 127 |
+
let mut pred_final = f64::NAN;
|
| 128 |
+
let mut vc_final = f64::NAN;
|
| 129 |
+
for epoca in 0..cfg.epocas {
|
| 130 |
+
// máscara fresca a cada época (com proteção contra máscara degenerada:
|
| 131 |
+
// se contexto ou alvo ficar vazio, repete com fração menor — a época
|
| 132 |
+
// NUNCA é pulada, a perda sempre é computada)
|
| 133 |
+
let (ctx_idx, blocos) = loop {
|
| 134 |
+
let mut masc = mascara(n, &mut rng);
|
| 135 |
+
// defensivo: máscara menor que n => o resto é contexto
|
| 136 |
+
if masc.len() < n {
|
| 137 |
+
masc.resize(n, false);
|
| 138 |
+
}
|
| 139 |
+
masc.truncate(n);
|
| 140 |
+
let ctx: Vec<u32> = (0..n).filter(|&i| !masc[i]).map(|i| i as u32).collect();
|
| 141 |
+
let alvos: Vec<usize> = (0..n).filter(|&i| masc[i]).collect();
|
| 142 |
+
if !ctx.is_empty() && !alvos.is_empty() {
|
| 143 |
+
break (ctx, alvos);
|
| 144 |
+
}
|
| 145 |
+
};
|
| 146 |
+
// agrupa alvos em blocos de tam_bloco
|
| 147 |
+
let grupos: Vec<Vec<usize>> = blocos
|
| 148 |
+
.chunks(cfg.tam_bloco.max(1))
|
| 149 |
+
.map(|c| c.to_vec())
|
| 150 |
+
.collect();
|
| 151 |
+
if ctx_idx.is_empty() || grupos.is_empty() {
|
| 152 |
+
continue;
|
| 153 |
+
}
|
| 154 |
+
let dev2 = patches.device();
|
| 155 |
+
let n_ctx = ctx_idx.len();
|
| 156 |
+
let idx_t = Tensor::from_vec(ctx_idx, (n_ctx,), &dev2)?;
|
| 157 |
+
let ctx_patches = patches.index_select(&idx_t, 0)?;
|
| 158 |
+
let z_ctx_todos = nucleo.codificar(&ctx_patches)?; // (n_ctx, d_emb)
|
| 159 |
+
let z_ctx = z_ctx_todos.mean_keepdim(0)?; // (1, d_emb)
|
| 160 |
+
// alvos por grupo
|
| 161 |
+
let mut alvos: Vec<Vec<(usize, Tensor)>> = Vec::new();
|
| 162 |
+
for g in &grupos {
|
| 163 |
+
let idx: Vec<u32> = g.iter().map(|&i| i as u32).collect();
|
| 164 |
+
let n_g = idx.len();
|
| 165 |
+
let it = Tensor::from_vec(idx, (n_g,), &dev2)?;
|
| 166 |
+
alvos.push(vec![(g[0], patches.index_select(&it, 0)?)]);
|
| 167 |
+
}
|
| 168 |
+
// condição por amostra — broadcast (o lote é 1 aqui: o conjunto todo)
|
| 169 |
+
let (perda, lp, lv) = nucleo.perda_lote(&z_ctx, &[alvos_concat(&alvos)], cond, &z_ctx_todos)?;
|
| 170 |
+
let p = perda.to_scalar::<f32>()? as f64;
|
| 171 |
+
if p.is_finite() {
|
| 172 |
+
if epoca == 0 {
|
| 173 |
+
perda_inicial = p;
|
| 174 |
+
pred_inicial = lp;
|
| 175 |
+
}
|
| 176 |
+
perda_final = p;
|
| 177 |
+
pred_final = lp;
|
| 178 |
+
vc_final = lv;
|
| 179 |
+
}
|
| 180 |
+
// decaimento cosseno do lr + clipping de gradiente (estabilidade)
|
| 181 |
+
let frac = epoca as f64 / cfg.epocas.max(1) as f64;
|
| 182 |
+
let lr_t = cfg.lr * 0.5 * (1.0 + (std::f64::consts::PI * frac).cos());
|
| 183 |
+
otimizador.set_lr(lr_t);
|
| 184 |
+
let mut grads = crate::treino::grads_achatados(&perda, &nucleo.vars())?;
|
| 185 |
+
crate::treino::AdamWManual::clipar(&mut grads, 1.0);
|
| 186 |
+
otimizador.passo(grads);
|
| 187 |
+
nucleo.ema_passo()?;
|
| 188 |
+
}
|
| 189 |
+
let z1 = nucleo.codificar(patches)?;
|
| 190 |
+
let std1 = std_por_dim(&z1)?;
|
| 191 |
+
let _ = (pred_inicial, vc_final);
|
| 192 |
+
Ok(RelatorioJepa {
|
| 193 |
+
variante: variante.nome().to_string(),
|
| 194 |
+
perda_inicial,
|
| 195 |
+
perda_final,
|
| 196 |
+
perda_pred_inicial: pred_inicial,
|
| 197 |
+
perda_pred_final: pred_final,
|
| 198 |
+
std_emb_final: std1,
|
| 199 |
+
std_emb_inicial: std0,
|
| 200 |
+
n_patches: n,
|
| 201 |
+
d_patch,
|
| 202 |
+
epocas: cfg.epocas,
|
| 203 |
+
})
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
fn alvos_concat(alvos: &[Vec<(usize, Tensor)>]) -> Vec<(usize, Tensor)> {
|
| 207 |
+
alvos.iter().flatten().cloned().collect()
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
fn std_por_dim(z: &Tensor) -> Result<f64> {
|
| 211 |
+
let n = z.dim(0)? as f64;
|
| 212 |
+
let media = z.mean_keepdim(0)?;
|
| 213 |
+
let centr = z.broadcast_sub(&media)?;
|
| 214 |
+
let var = (centr.sqr()?.sum(0)? / n)?;
|
| 215 |
+
Ok(var.sqrt()?.mean_all()?.to_scalar::<f32>()? as f64)
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
// ---------------------------------------------------------------------------
|
| 220 |
+
// Variantes especiais: LeJEPA (edição-condicionado), MC-JEPA (cruz-modal),
|
| 221 |
+
// BJEPA (bidirecional com consistência de ciclo)
|
| 222 |
+
// ---------------------------------------------------------------------------
|
| 223 |
+
|
| 224 |
+
/// **LeJEPA** — predição latente condicionada por EDIÇÃO: contexto = E(x),
|
| 225 |
+
/// condição = instrução de edição `e` (vetor de baixa dimensão), alvo =
|
| 226 |
+
/// `E_ξ(edit_e(x))`. A condição é a INSTRUÇÃO (não o resultado — sem
|
| 227 |
+
/// vazamento: `e` não contém `edit(x)`).
|
| 228 |
+
pub fn treinar_lejepa(
|
| 229 |
+
dados: &Tensor, // (n, d_patch) — originais
|
| 230 |
+
edits: &Tensor, // (n, d_cond) — instruções de edição
|
| 231 |
+
editados: &Tensor, // (n, d_patch) — resultados das edições
|
| 232 |
+
cfg: &CfgJepa,
|
| 233 |
+
dev: &Device,
|
| 234 |
+
) -> Result<RelatorioJepa> {
|
| 235 |
+
let n = dados.dim(0)?;
|
| 236 |
+
let d_patch = dados.dim(1)?;
|
| 237 |
+
let d_cond = edits.dim(1)?;
|
| 238 |
+
let mut rng = RngDeterministico::novo(cfg.semente);
|
| 239 |
+
let mut nucleo = NucleoJepa::novo(
|
| 240 |
+
d_patch, cfg.d_emb, d_cond, 1, cfg.m, cfg.lambda_vc, cfg.gamma_vc, dev,
|
| 241 |
+
)?;
|
| 242 |
+
let mut otim = crate::treino::AdamWManual::novo(nucleo.vars(), cfg.lr, 0.01);
|
| 243 |
+
let mut perda_inicial = f64::NAN;
|
| 244 |
+
let mut perda_final = f64::NAN;
|
| 245 |
+
let z0 = nucleo.codificar(dados)?;
|
| 246 |
+
let std0 = std_por_dim(&z0)?;
|
| 247 |
+
for epoca in 0..cfg.epocas {
|
| 248 |
+
// subamostra do lote
|
| 249 |
+
let idx = rng.amostra_k_de_n(n.min(64), n);
|
| 250 |
+
let sel: Vec<u32> = idx.iter().map(|&i| i as u32).collect();
|
| 251 |
+
let it = Tensor::from_vec(sel.clone(), (sel.len(),), dev)?;
|
| 252 |
+
let xb = dados.index_select(&it, 0)?;
|
| 253 |
+
let eb = edits.index_select(&it, 0)?;
|
| 254 |
+
let yb = editados.index_select(&it, 0)?;
|
| 255 |
+
let z_ctx = nucleo.codificar(&xb)?; // (m, d_emb)
|
| 256 |
+
let mut perdas: Vec<Tensor> = Vec::new();
|
| 257 |
+
for i in 0..xb.dim(0)? {
|
| 258 |
+
let zc = z_ctx.get(i)?.broadcast_as((1, cfg.d_emb))?;
|
| 259 |
+
let e_i = eb.get(i)?.broadcast_as((1, d_cond))?;
|
| 260 |
+
let yt = yb.get(i)?.broadcast_as((1, d_patch))?;
|
| 261 |
+
let zt = nucleo
|
| 262 |
+
.alvo_codificar(&yt)?
|
| 263 |
+
.mean(0)?
|
| 264 |
+
.broadcast_as((1, cfg.d_emb))?;
|
| 265 |
+
let pred = nucleo.predizer(&zc, 0, Some(&e_i))?;
|
| 266 |
+
let dif = (&pred - &zt)?;
|
| 267 |
+
perdas.push((dif.sqr()?.sum_all()? / cfg.d_emb as f64)?);
|
| 268 |
+
}
|
| 269 |
+
let l_pred = (Tensor::stack(&perdas, 0)?.sum_all()? / perdas.len() as f64)?;
|
| 270 |
+
let l_vc = nucleo.perda_vc(&z_ctx)?;
|
| 271 |
+
let total = (l_pred.affine(1.0, 0.0)? + l_vc.affine(cfg.lambda_vc, 0.0)?)?;
|
| 272 |
+
let p = total.to_scalar::<f32>()? as f64;
|
| 273 |
+
if p.is_finite() {
|
| 274 |
+
if epoca == 0 {
|
| 275 |
+
perda_inicial = p;
|
| 276 |
+
}
|
| 277 |
+
perda_final = p;
|
| 278 |
+
}
|
| 279 |
+
let mut grads = crate::treino::grads_achatados(&total, &nucleo.vars())?;
|
| 280 |
+
crate::treino::AdamWManual::clipar(&mut grads, 1.0);
|
| 281 |
+
otim.passo(grads);
|
| 282 |
+
nucleo.ema_passo()?;
|
| 283 |
+
}
|
| 284 |
+
let z1 = nucleo.codificar(dados)?;
|
| 285 |
+
Ok(RelatorioJepa {
|
| 286 |
+
variante: "LeJEPA".into(),
|
| 287 |
+
perda_inicial,
|
| 288 |
+
perda_final,
|
| 289 |
+
perda_pred_inicial: perda_inicial,
|
| 290 |
+
perda_pred_final: perda_final,
|
| 291 |
+
std_emb_final: std_por_dim(&z1)?,
|
| 292 |
+
std_emb_inicial: std0,
|
| 293 |
+
n_patches: n,
|
| 294 |
+
d_patch,
|
| 295 |
+
epocas: cfg.epocas,
|
| 296 |
+
})
|
| 297 |
+
}
|
| 298 |
+
|
| 299 |
+
/// **MC-JEPA** — cruz-modal: dois codificadores, predição nos DOIS sentidos
|
| 300 |
+
/// (A→B e B→A) com preditores separados e alvos EMA dos dois lados.
|
| 301 |
+
pub fn treinar_mcjepa(
|
| 302 |
+
mod_a: &Tensor, // (n, d_a)
|
| 303 |
+
mod_b: &Tensor, // (n, d_b)
|
| 304 |
+
cfg: &CfgJepa,
|
| 305 |
+
dev: &Device,
|
| 306 |
+
) -> Result<RelatorioJepa> {
|
| 307 |
+
let n = mod_a.dim(0)?;
|
| 308 |
+
let d_a = mod_a.dim(1)?;
|
| 309 |
+
let d_b = mod_b.dim(1)?;
|
| 310 |
+
// núcleo A→B e núcleo B→A (compartilham apenas a estrutura)
|
| 311 |
+
let mut nb = NucleoJepa::novo(d_a, cfg.d_emb, 0, 1, cfg.m, cfg.lambda_vc, cfg.gamma_vc, dev)?;
|
| 312 |
+
let mut na = NucleoJepa::novo(d_b, cfg.d_emb, 0, 1, cfg.m, cfg.lambda_vc, cfg.gamma_vc, dev)?;
|
| 313 |
+
let mut otim = crate::treino::AdamWManual::novo(
|
| 314 |
+
[nb.vars(), na.vars()].concat(),
|
| 315 |
+
cfg.lr,
|
| 316 |
+
0.01,
|
| 317 |
+
);
|
| 318 |
+
let mut rng = RngDeterministico::novo(cfg.semente);
|
| 319 |
+
let mut perda_inicial = f64::NAN;
|
| 320 |
+
let mut perda_final = f64::NAN;
|
| 321 |
+
for epoca in 0..cfg.epocas {
|
| 322 |
+
let idx = rng.amostra_k_de_n(n.min(64), n);
|
| 323 |
+
let sel: Vec<u32> = idx.iter().map(|&i| i as u32).collect();
|
| 324 |
+
let it = Tensor::from_vec(sel, (idx.len(),), dev)?;
|
| 325 |
+
let xa = mod_a.index_select(&it, 0)?;
|
| 326 |
+
let xb = mod_b.index_select(&it, 0)?;
|
| 327 |
+
// z_a = E_a(x_a) prevê ẑ_b; z_b = E_b(x_b) prevê ẑ_a
|
| 328 |
+
let z_a = nb.codificar(&xa)?; // (m, d_emb)
|
| 329 |
+
let z_b = na.codificar(&xb)?;
|
| 330 |
+
let t_a = na.alvo_codificar(&xa)?; // alvo EMA do lado A
|
| 331 |
+
let t_b = nb.alvo_codificar(&xb)?; // alvo EMA do lado B
|
| 332 |
+
let m_ = xa.dim(0)?;
|
| 333 |
+
let mut perdas: Vec<Tensor> = Vec::new();
|
| 334 |
+
for i in 0..m_ {
|
| 335 |
+
// A → B
|
| 336 |
+
let zc = z_a.get(i)?.broadcast_as((1, cfg.d_emb))?;
|
| 337 |
+
let zt = t_b.get(i)?.broadcast_as((1, cfg.d_emb))?;
|
| 338 |
+
let pred = nb.predizer(&zc, 0, None)?;
|
| 339 |
+
let dif = (&pred - &zt)?;
|
| 340 |
+
perdas.push((dif.sqr()?.sum_all()? / cfg.d_emb as f64)?);
|
| 341 |
+
// B → A
|
| 342 |
+
let zc2 = z_b.get(i)?.broadcast_as((1, cfg.d_emb))?;
|
| 343 |
+
let zt2 = t_a.get(i)?.broadcast_as((1, cfg.d_emb))?;
|
| 344 |
+
let pred2 = na.predizer(&zc2, 0, None)?;
|
| 345 |
+
let dif2 = (&pred2 - &zt2)?;
|
| 346 |
+
perdas.push((dif2.sqr()?.sum_all()? / cfg.d_emb as f64)?);
|
| 347 |
+
}
|
| 348 |
+
let l_pred = (Tensor::stack(&perdas, 0)?.sum_all()? / perdas.len() as f64)?;
|
| 349 |
+
let l_vc = (nb.perda_vc(&z_a)? + na.perda_vc(&z_b)?)?;
|
| 350 |
+
let total = (l_pred.affine(1.0, 0.0)? + l_vc.affine(cfg.lambda_vc, 0.0)?)?;
|
| 351 |
+
let p = total.to_scalar::<f32>()? as f64;
|
| 352 |
+
if p.is_finite() {
|
| 353 |
+
if epoca == 0 {
|
| 354 |
+
perda_inicial = p;
|
| 355 |
+
}
|
| 356 |
+
perda_final = p;
|
| 357 |
+
}
|
| 358 |
+
let mut grads = crate::treino::grads_achatados(&total, &[nb.vars(), na.vars()].concat())?;
|
| 359 |
+
crate::treino::AdamWManual::clipar(&mut grads, 1.0);
|
| 360 |
+
otim.passo(grads);
|
| 361 |
+
nb.ema_passo()?;
|
| 362 |
+
na.ema_passo()?;
|
| 363 |
+
}
|
| 364 |
+
let z1 = nb.codificar(mod_a)?;
|
| 365 |
+
Ok(RelatorioJepa {
|
| 366 |
+
variante: "MC-JEPA".into(),
|
| 367 |
+
perda_inicial,
|
| 368 |
+
perda_final,
|
| 369 |
+
perda_pred_inicial: perda_inicial,
|
| 370 |
+
perda_pred_final: perda_final,
|
| 371 |
+
std_emb_final: std_por_dim(&z1)?,
|
| 372 |
+
std_emb_inicial: std_por_dim(&nb.codificar(mod_a)?)?,
|
| 373 |
+
n_patches: n,
|
| 374 |
+
d_patch: d_a.max(d_b),
|
| 375 |
+
epocas: cfg.epocas,
|
| 376 |
+
})
|
| 377 |
+
}
|
| 378 |
+
|
| 379 |
+
/// **BJEPA** — bidirecional: preditor causal (z_t → z̃_{t+1}), anti-causal
|
| 380 |
+
/// (z_{t+1} → z̃_t) e consistência de ciclo
|
| 381 |
+
/// `‖P_b(P_f(z_t)) − sg(z_t)‖²` — a volta deve reconstruir o presente.
|
| 382 |
+
pub fn treinar_bjepa(patches: &Tensor, cfg: &CfgJepa, dev: &Device) -> Result<RelatorioJepa> {
|
| 383 |
+
let n = patches.dim(0)?;
|
| 384 |
+
let d_patch = patches.dim(1)?;
|
| 385 |
+
let mut nucleo = NucleoJepa::novo(
|
| 386 |
+
d_patch, cfg.d_emb, 0, 2, cfg.m, cfg.lambda_vc, cfg.gamma_vc, dev,
|
| 387 |
+
)?;
|
| 388 |
+
// preditor anti-causal: núcleo separado
|
| 389 |
+
let mut ninv = NucleoJepa::novo(
|
| 390 |
+
d_patch, cfg.d_emb, 0, 2, cfg.m, cfg.lambda_vc, cfg.gamma_vc, dev,
|
| 391 |
+
)?;
|
| 392 |
+
let mut otim =
|
| 393 |
+
crate::treino::AdamWManual::novo([nucleo.vars(), ninv.vars()].concat(), cfg.lr, 0.01);
|
| 394 |
+
let mut perda_inicial = f64::NAN;
|
| 395 |
+
let mut perda_final = f64::NAN;
|
| 396 |
+
for epoca in 0..cfg.epocas {
|
| 397 |
+
let z = nucleo.codificar(patches)?; // (n, d_emb)
|
| 398 |
+
let zt = nucleo.alvo_codificar(patches)?; // alvos EMA (stop-grad)
|
| 399 |
+
let mut perdas: Vec<Tensor> = Vec::new();
|
| 400 |
+
for t in 0..n.saturating_sub(1) {
|
| 401 |
+
let zc = z.get(t)?.broadcast_as((1, cfg.d_emb))?;
|
| 402 |
+
let z_prox = zt.get(t + 1)?.broadcast_as((1, cfg.d_emb))?;
|
| 403 |
+
// causal: z_t → z̃_{t+1} (pos 0 = "próximo")
|
| 404 |
+
let pf = nucleo.predizer(&zc, 0, None)?;
|
| 405 |
+
let dif = (&pf - &z_prox)?;
|
| 406 |
+
perdas.push((dif.sqr()?.sum_all()? / cfg.d_emb as f64)?);
|
| 407 |
+
// anti-causal: z_{t+1} → z̃_t (pos 1 = "anterior")
|
| 408 |
+
let zb = z.get(t + 1)?.broadcast_as((1, cfg.d_emb))?;
|
| 409 |
+
let z_ant = zt.get(t)?.broadcast_as((1, cfg.d_emb))?;
|
| 410 |
+
let pb = ninv.predizer(&zb, 1, None)?;
|
| 411 |
+
let dif2 = (&pb - &z_ant)?;
|
| 412 |
+
perdas.push((dif2.sqr()?.sum_all()? / cfg.d_emb as f64)?);
|
| 413 |
+
// ciclo: P_b(P_f(z_t)) ≈ sg(z_t)
|
| 414 |
+
let pf_sg = nucleo.predizer(&zc, 0, None)?.detach();
|
| 415 |
+
let pciclo = ninv.predizer(&pf_sg.broadcast_as((1, cfg.d_emb))?, 1, None)?;
|
| 416 |
+
let zt_sg = zt.get(t)?.broadcast_as((1, cfg.d_emb))?;
|
| 417 |
+
let dif3 = (&pciclo - &zt_sg)?;
|
| 418 |
+
perdas.push((dif3.sqr()?.sum_all()? / cfg.d_emb as f64)?);
|
| 419 |
+
}
|
| 420 |
+
let l_pred = (Tensor::stack(&perdas, 0)?.sum_all()? / perdas.len().max(1) as f64)?;
|
| 421 |
+
let l_vc = nucleo.perda_vc(&z)?;
|
| 422 |
+
let total = (l_pred.affine(1.0, 0.0)? + l_vc.affine(cfg.lambda_vc, 0.0)?)?;
|
| 423 |
+
let p = total.to_scalar::<f32>()? as f64;
|
| 424 |
+
if p.is_finite() {
|
| 425 |
+
if epoca == 0 {
|
| 426 |
+
perda_inicial = p;
|
| 427 |
+
}
|
| 428 |
+
perda_final = p;
|
| 429 |
+
}
|
| 430 |
+
let mut grads = crate::treino::grads_achatados(&total, &[nucleo.vars(), ninv.vars()].concat())?;
|
| 431 |
+
crate::treino::AdamWManual::clipar(&mut grads, 1.0);
|
| 432 |
+
otim.passo(grads);
|
| 433 |
+
nucleo.ema_passo()?;
|
| 434 |
+
ninv.ema_passo()?;
|
| 435 |
+
}
|
| 436 |
+
let z1 = nucleo.codificar(patches)?;
|
| 437 |
+
Ok(RelatorioJepa {
|
| 438 |
+
variante: "BJEPA".into(),
|
| 439 |
+
perda_inicial,
|
| 440 |
+
perda_final,
|
| 441 |
+
perda_pred_inicial: perda_inicial,
|
| 442 |
+
perda_pred_final: perda_final,
|
| 443 |
+
std_emb_final: std_por_dim(&z1)?,
|
| 444 |
+
std_emb_inicial: std_por_dim(&nucleo.codificar(patches)?)?,
|
| 445 |
+
n_patches: n,
|
| 446 |
+
d_patch,
|
| 447 |
+
epocas: cfg.epocas,
|
| 448 |
+
})
|
| 449 |
+
}
|
| 450 |
+
|
| 451 |
+
/// Esquema de máscara por variante a partir da grade de patches.
|
| 452 |
+
pub fn mascara_por_variante(
|
| 453 |
+
variante: VarianteJepa,
|
| 454 |
+
grid: &[usize],
|
| 455 |
+
frac: f64,
|
| 456 |
+
rng: &mut RngDeterministico,
|
| 457 |
+
) -> Vec<bool> {
|
| 458 |
+
match variante {
|
| 459 |
+
VarianteJepa::ImageJepa => mascara_blocos_2d(grid[0], grid.get(1).copied().unwrap_or(1), 4, frac, rng),
|
| 460 |
+
VarianteJepa::VJepa2 | VarianteJepa::Jepa3D => mascara_tubos_3d(
|
| 461 |
+
grid[0],
|
| 462 |
+
grid.get(1).copied().unwrap_or(1),
|
| 463 |
+
grid.get(2).copied().unwrap_or(1),
|
| 464 |
+
3,
|
| 465 |
+
frac,
|
| 466 |
+
rng,
|
| 467 |
+
),
|
| 468 |
+
VarianteJepa::AudioJepa => mascara_bandas(grid[0], grid.get(1).copied().unwrap_or(1), 3, frac, rng),
|
| 469 |
+
VarianteJepa::BrainJepa => mascara_segmentos(grid[0], grid.get(1).copied().unwrap_or(1), frac, rng),
|
| 470 |
+
_ => mascara_intervalos_1d(grid.iter().product::<usize>().max(1), frac, rng),
|
| 471 |
+
}
|
| 472 |
+
}
|
| 473 |
+
|
| 474 |
+
pub fn versao() -> &'static str {
|
| 475 |
+
"jepa-0.5.0"
|
| 476 |
+
}
|
laboratorio/arquivo_split_v100/moe_redirecionavel/atencao.rs
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! `moe_redirecionavel::atencao` — extraído do monólito na v0.10.0
|
| 2 |
+
//! (divisão SRP, crítica Qwen3.8 lote 3 nº 1; r-35 §2).
|
| 3 |
+
|
| 4 |
+
use super::*;
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
// ---------------------------------------------------------------------------
|
| 8 |
+
// Atenção própria (independente e paralela à ADBA do tronco)
|
| 9 |
+
// ---------------------------------------------------------------------------
|
| 10 |
+
|
| 11 |
+
pub struct AtencaoPropria {
|
| 12 |
+
pub q: Linear,
|
| 13 |
+
pub k: Linear,
|
| 14 |
+
pub v: Linear,
|
| 15 |
+
pub o: Linear,
|
| 16 |
+
/// gate escalar — nasce ZERO (M-R2: neutralidade no nascimento).
|
| 17 |
+
pub gate: Var,
|
| 18 |
+
pub n_cabecas: usize,
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
impl AtencaoPropria {
|
| 22 |
+
pub fn novo(d: usize, n_cabecas: usize, dev: &Device) -> Result<Self> {
|
| 23 |
+
let desvio = 1.0 / ((d * 2) as f64).sqrt();
|
| 24 |
+
let mk = || Linear::sem_vies(d, d, desvio, dev);
|
| 25 |
+
let gate = Tensor::zeros((), candle_core::DType::F32, dev)?;
|
| 26 |
+
Ok(AtencaoPropria {
|
| 27 |
+
q: mk()?, k: mk()?, v: mk()?, o: mk()?,
|
| 28 |
+
gate: Var::from_tensor(&gate)?,
|
| 29 |
+
n_cabecas,
|
| 30 |
+
})
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
/// x (n, d) → y = x + g·attn(x) — multi-cabeça compacta (sem máscara:
|
| 34 |
+
/// atenção plena entre os tokens da entrada do MoE).
|
| 35 |
+
pub fn fwd(&self, x: &Tensor) -> Result<Tensor> {
|
| 36 |
+
let d = x.dim(candle_core::D::Minus1)?;
|
| 37 |
+
let d_cab = d / self.n_cabecas;
|
| 38 |
+
let n = x.dim(0)?;
|
| 39 |
+
let forma = (self.n_cabecas, n, d_cab);
|
| 40 |
+
let q = self.q.fwd(x)?.reshape(forma)?;
|
| 41 |
+
let k = self.k.fwd(x)?.reshape(forma)?;
|
| 42 |
+
let v = self.v.fwd(x)?.reshape(forma)?;
|
| 43 |
+
let scores = q.matmul(&k.transpose(1, 2)?)?.affine(1.0 / (d_cab as f64).sqrt(), 0.0)?;
|
| 44 |
+
let attn = candle_nn::ops::softmax(&scores, candle_core::D::Minus1)?;
|
| 45 |
+
let ctx = attn.matmul(&v)?; // (h, n, d_cab)
|
| 46 |
+
let ctx = ctx.reshape((n, d))?;
|
| 47 |
+
let saida = self.o.fwd(&ctx)?;
|
| 48 |
+
// y = x + g·saida (g=0 no nascimento ⇒ y = x — M-R2)
|
| 49 |
+
let g = self.gate.as_tensor();
|
| 50 |
+
let forma: Vec<usize> = saida.dims().to_vec();
|
| 51 |
+
let delta = saida.broadcast_mul(&g.broadcast_as(forma)?)?;
|
| 52 |
+
Ok((x + &delta)?)
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
pub fn vars(&self) -> Vec<Var> {
|
| 56 |
+
let mut v = self.q.vars();
|
| 57 |
+
v.extend(self.k.vars());
|
| 58 |
+
v.extend(self.v.vars());
|
| 59 |
+
v.extend(self.o.vars());
|
| 60 |
+
v.push(self.gate.clone());
|
| 61 |
+
v
|
| 62 |
+
}
|
| 63 |
+
}
|
laboratorio/arquivo_split_v100/moe_redirecionavel/mod.rs
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! MoE redirecionável — módulos: atenção própria, núcleo,
|
| 2 |
+
//! treinos JEPA/SOM (divisão SRP v0.10.0 — r-35 §2).
|
| 3 |
+
|
| 4 |
+
//! **MoEs de codificação/decodificação REDIRECIONÁVEIS com Mecanismo de
|
| 5 |
+
//! Atenção próprio e independente (paralelo)** (v0.6.0 — pedido do usuário).
|
| 6 |
+
//!
|
| 7 |
+
//! Cada `MoeRedirecionavel` possui:
|
| 8 |
+
//! - um roteador aprendido `d → E`;
|
| 9 |
+
//! - E especialistas `MlpJepa`, cada um com um PAPEL (Codificador ou
|
| 10 |
+
//! Decodificador) — o conjunto de papéis é REDIRECIONÁVEL em tempo de
|
| 11 |
+
//! execução (permutação), sem reconstrução do modelo;
|
| 12 |
+
//! - uma ATENÇÃO PRÓPRIA independente da atenção ADBA do tronco, com gate
|
| 13 |
+
//! escalar nascido em ZERO (neutralidade no nascimento);
|
| 14 |
+
//! - capacidade por especialista e perda auxiliar de balanceamento.
|
| 15 |
+
//!
|
| 16 |
+
//! **Provas completas em `docs/memorias/r-25-*`; síntese:**
|
| 17 |
+
//! - **M-R1 (invariância sob redirecionamento):** o redirecionamento é uma
|
| 18 |
+
//! permutação π dos papéis; o multiconjunto de atribuições
|
| 19 |
+
//! (especialista, token) numa passada por papel é levado ao multiconjunto
|
| 20 |
+
//! da passada π(papel) — a capacidade total e a perda auxiliar de
|
| 21 |
+
//! balanceamento E·Σ f_e·p_e são invariantes (soma sobre todos os e).
|
| 22 |
+
//! - **M-R2 (neutralidade da atenção própria no nascimento):** com
|
| 23 |
+
//! `g = 0`, `y = x` bit-a-bit; a perturbação é limitada por
|
| 24 |
+
//! `‖Δy‖ ≤ L_soft·|g|·‖W_o·V‖` (Lipschitz do softmax com constante
|
| 25 |
+
//! L_soft = 1 em probabilidade; estrutura idêntica ao T-P5).
|
| 26 |
+
//! - **M-R3 (paralelismo dos dois caminhos):** numa mesma entrada, as
|
| 27 |
+
//! passadas Codificador e Decodificador tocam conjuntos DISJUNTOS de
|
| 28 |
+
//! especialistas e compartilham apenas leitura — o DAG de computação tem
|
| 29 |
+
//! duas sub-DAGs independentes ⇒ tempo paralelo (2 processadores) =
|
| 30 |
+
//! max(T_enc, T_dec) + sobrecarga < T_enc + T_dec = tempo sequencial
|
| 31 |
+
//! (modelo PRAM; medido empiricamente com threads).
|
| 32 |
+
//! - **M-R4 (fechamento da classe de funções):** redirecionar equivale a
|
| 33 |
+
//! permutar colunas do roteador e re-rotular papéis; a classe de funções
|
| 34 |
+
//! implementáveis é fechada sob π ⇒ expressividade inalterada.
|
| 35 |
+
//! - **M-R5 (water-filling por QE — Cauchy–Schwarz):** dadas capacidades
|
| 36 |
+
//! totais C e erros por célula q_i, a alocação `c_i ∝ q_i` minimiza
|
| 37 |
+
//! `Σ q_i²/c_i ≥ (Σq_i)²/C`, cota superior do erro refinado ponderado.
|
| 38 |
+
|
| 39 |
+
use candle_core::{Device, Result, Tensor, Var};
|
| 40 |
+
use crate::camadas::Linear;
|
| 41 |
+
use crate::jepa::MlpJepa;
|
| 42 |
+
use crate::rng::RngDeterministico;
|
| 43 |
+
use crate::treino::AdamWManual;
|
| 44 |
+
|
| 45 |
+
// ---- divisão SRP v0.10.0 (r-35 §2): submódulos + re-exports ----
|
| 46 |
+
#[cfg(test)]
|
| 47 |
+
mod testes;
|
| 48 |
+
#[cfg(test)]
|
| 49 |
+
mod teste_integrado;
|
| 50 |
+
mod atencao;
|
| 51 |
+
mod nucleo;
|
| 52 |
+
mod treino;
|
| 53 |
+
|
| 54 |
+
pub use atencao::*;
|
| 55 |
+
pub use nucleo::*;
|
| 56 |
+
pub use treino::*;
|
| 57 |
+
|
laboratorio/arquivo_split_v100/moe_redirecionavel/nucleo.rs
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! `moe_redirecionavel::nucleo` — extraído do monólito na v0.10.0
|
| 2 |
+
//! (divisão SRP, crítica Qwen3.8 lote 3 nº 1; r-35 §2).
|
| 3 |
+
|
| 4 |
+
use super::*;
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
// ---------------------------------------------------------------------------
|
| 8 |
+
// MoE redirecionável
|
| 9 |
+
// ---------------------------------------------------------------------------
|
| 10 |
+
|
| 11 |
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
| 12 |
+
pub enum Papel {
|
| 13 |
+
Codificador,
|
| 14 |
+
Decodificador,
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
impl Papel {
|
| 18 |
+
pub fn nome(&self) -> &'static str {
|
| 19 |
+
match self { Papel::Codificador => "codificador", Papel::Decodificador => "decodificador" }
|
| 20 |
+
}
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
pub struct SaidaMoeR {
|
| 24 |
+
pub saida: Tensor,
|
| 25 |
+
pub perda_aux: Tensor,
|
| 26 |
+
pub carga: Vec<usize>,
|
| 27 |
+
pub descartados: usize,
|
| 28 |
+
/// especialistas efetivamente usados nesta passada (índices globais).
|
| 29 |
+
pub usados: Vec<usize>,
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
pub struct MoeRedirecionavel {
|
| 33 |
+
pub roteador: Linear, // d → E
|
| 34 |
+
pub especialistas: Vec<MlpJepa>, // E experts d → d
|
| 35 |
+
pub papeis: Vec<Papel>, // papel corrente de cada especialista
|
| 36 |
+
pub atencao: AtencaoPropria, // atenção PRÓPRIA (M-R2/M-R3)
|
| 37 |
+
pub n_top: usize,
|
| 38 |
+
pub capacidade: usize,
|
| 39 |
+
pub lambda_aux: f64,
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
impl MoeRedirecionavel {
|
| 43 |
+
pub fn novo(d: usize, n_expertos: usize, n_top: usize, capacidade: usize, dev: &Device) -> Result<Self> {
|
| 44 |
+
let roteador = Linear::sem_vies(d, n_expertos, 0.1, dev)?;
|
| 45 |
+
let especialistas = (0..n_expertos)
|
| 46 |
+
.map(|_| MlpJepa::novo(d, 2 * d, d, dev))
|
| 47 |
+
.collect::<Result<Vec<_>>>()?;
|
| 48 |
+
// papéis iniciais alternados (metade cod, metade dec)
|
| 49 |
+
let papeis = (0..n_expertos)
|
| 50 |
+
.map(|i| if i % 2 == 0 { Papel::Codificador } else { Papel::Decodificador })
|
| 51 |
+
.collect();
|
| 52 |
+
Ok(MoeRedirecionavel {
|
| 53 |
+
roteador,
|
| 54 |
+
especialistas,
|
| 55 |
+
papeis,
|
| 56 |
+
atencao: AtencaoPropria::novo(d, 2, dev)?,
|
| 57 |
+
n_top: n_top.max(1),
|
| 58 |
+
capacidade,
|
| 59 |
+
lambda_aux: 0.01,
|
| 60 |
+
})
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
pub fn vars(&self) -> Vec<Var> {
|
| 64 |
+
let mut v = self.roteador.vars();
|
| 65 |
+
for e in &self.especialistas {
|
| 66 |
+
v.extend(e.vars());
|
| 67 |
+
}
|
| 68 |
+
v.extend(self.atencao.vars());
|
| 69 |
+
v
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
/// **M-R1/M-R4:** redireciona os papéis segundo a permutação `permuta`
|
| 73 |
+
/// (novo_papel[i] = papel_anterior[permuta[i]]). `redirecionar_todos`
|
| 74 |
+
/// troca Codificador ↔ Decodificador.
|
| 75 |
+
pub fn redirecionar(&mut self, permuta: &[usize]) {
|
| 76 |
+
let antigos = self.papeis.clone();
|
| 77 |
+
for (i, &p) in permuta.iter().enumerate() {
|
| 78 |
+
if p < antigos.len() {
|
| 79 |
+
self.papeis[i] = antigos[p];
|
| 80 |
+
}
|
| 81 |
+
}
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
pub fn redirecionar_todos(&mut self) {
|
| 85 |
+
for p in self.papeis.iter_mut() {
|
| 86 |
+
*p = match *p {
|
| 87 |
+
Papel::Codificador => Papel::Decodificador,
|
| 88 |
+
Papel::Decodificador => Papel::Codificador,
|
| 89 |
+
};
|
| 90 |
+
}
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
fn indices_do_papel(&self, papel: Papel) -> Vec<usize> {
|
| 94 |
+
self.papeis.iter().enumerate().filter(|(_, p)| **p == papel).map(|(i, _)| i).collect()
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
/// Passada por papel: atenção própria → roteamento top-k DENTRO do
|
| 98 |
+
/// subconjunto de especialistas do papel → capacidade → soma ponderada.
|
| 99 |
+
///
|
| 100 |
+
/// ⚠️ **DEPRECIADA na v0.9.0 (crítica Qwen3.8 nº 2b / r-34 §4):**
|
| 101 |
+
/// **bug v080-1 catalogado (r-33 §5)** — esta versão materializa os
|
| 102 |
+
/// valores com `to_vec2`/`from_vec` no acúmulo, o que SECCIONA o grafo
|
| 103 |
+
/// de autograd: especialistas e roteador NÃO recebem gradiente por
|
| 104 |
+
/// esta saída (só a atenção própria treina). Fora da superfície
|
| 105 |
+
/// pública (`pub(crate)`) desde a v0.9.0 — mantida EXCLUSIVAMENTE como
|
| 106 |
+
/// oráculo dos testes M-R6 (equivalência de valores) e M-R7 (prova do
|
| 107 |
+
/// bug); o caminho de treino canônico é [`MoeRedirecionavel::forward`].
|
| 108 |
+
#[deprecated(since = "0.9.0", note = "bug v080-1: secciona o grafo de autograd — use forward()")]
|
| 109 |
+
pub(crate) fn fwd(&self, x: &Tensor, papel: Papel) -> Result<SaidaMoeR> {
|
| 110 |
+
let y = self.atencao.fwd(x)?; // (n, d) — atenção própria independente
|
| 111 |
+
let n = y.dim(0)?;
|
| 112 |
+
let d = y.dim(1)?;
|
| 113 |
+
let dev = y.device();
|
| 114 |
+
let do_papel = self.indices_do_papel(papel);
|
| 115 |
+
let e_local = do_papel.len();
|
| 116 |
+
let mut descartados = 0usize;
|
| 117 |
+
let mut saida = Tensor::zeros((n, d), candle_core::DType::F32, &dev)?;
|
| 118 |
+
let mut peso_total = Tensor::zeros((n, 1), candle_core::DType::F32, &dev)?;
|
| 119 |
+
// probs de roteamento só sobre especialistas do papel (mascarado)
|
| 120 |
+
let logits_todos = self.roteador.fwd(&y)?; // (n, E)
|
| 121 |
+
let mut probs_v: Vec<Vec<f32>> = logits_todos.to_vec2::<f32>()?;
|
| 122 |
+
for linha in probs_v.iter_mut() {
|
| 123 |
+
// máscara: -inf fora do papel
|
| 124 |
+
for (e, lv) in linha.iter_mut().enumerate() {
|
| 125 |
+
if !do_papel.contains(&e) {
|
| 126 |
+
*lv = f32::NEG_INFINITY;
|
| 127 |
+
}
|
| 128 |
+
}
|
| 129 |
+
}
|
| 130 |
+
// softmax manual por linha (com -inf → 0)
|
| 131 |
+
let probs: Vec<Vec<f32>> = probs_v
|
| 132 |
+
.iter()
|
| 133 |
+
.map(|linha| {
|
| 134 |
+
let m = linha.iter().copied().fold(f32::NEG_INFINITY, f32::max);
|
| 135 |
+
let exps: Vec<f32> = linha.iter().map(|v| (v - m).exp()).collect();
|
| 136 |
+
let s: f32 = exps.iter().sum();
|
| 137 |
+
if s <= 0.0 {
|
| 138 |
+
vec![0.0; linha.len()]
|
| 139 |
+
} else {
|
| 140 |
+
exps.iter().map(|e| e / s).collect()
|
| 141 |
+
}
|
| 142 |
+
})
|
| 143 |
+
.collect();
|
| 144 |
+
// seleção top-k com capacidade (código extraído — MESMA semântica
|
| 145 |
+
// de desempate da v0.6.0, compartilhada com forward)
|
| 146 |
+
let (designacao, carga) = selecionar_com_capacidade(
|
| 147 |
+
&probs,
|
| 148 |
+
&do_papel,
|
| 149 |
+
n,
|
| 150 |
+
self.n_top,
|
| 151 |
+
self.capacidade,
|
| 152 |
+
self.especialistas.len(),
|
| 153 |
+
);
|
| 154 |
+
let usados: Vec<usize> = designacao.iter().map(|(ei, _)| *ei).collect();
|
| 155 |
+
for (ei, escolhidos) in designacao {
|
| 156 |
+
let idx: Vec<u32> = escolhidos.iter().map(|&i| i as u32).collect();
|
| 157 |
+
let n_e = idx.len();
|
| 158 |
+
let idx_t = Tensor::from_vec(idx, (n_e,), &dev)?;
|
| 159 |
+
let tile = y.index_select(&idx_t, 0)?;
|
| 160 |
+
let y_e = self.especialistas[ei].fwd(&tile)?;
|
| 161 |
+
let w: Vec<f32> = escolhidos.iter().map(|&i| probs[i][ei]).collect();
|
| 162 |
+
let w_t = Tensor::from_vec(w.clone(), (n_e, 1), &dev)?;
|
| 163 |
+
let contrib = y_e.broadcast_mul(&w_t)?;
|
| 164 |
+
let mut buf = saida.to_vec2::<f32>()?;
|
| 165 |
+
let contrib_v = contrib.to_vec2::<f32>()?;
|
| 166 |
+
for (kk, &i) in escolhidos.iter().enumerate() {
|
| 167 |
+
for j in 0..d {
|
| 168 |
+
buf[i][j] += contrib_v[kk][j];
|
| 169 |
+
}
|
| 170 |
+
}
|
| 171 |
+
saida = Tensor::from_vec(buf.into_iter().flatten().collect::<Vec<f32>>(), (n, d), &dev)?;
|
| 172 |
+
let mut pt = peso_total.to_vec2::<f32>()?;
|
| 173 |
+
for (kk, &i) in escolhidos.iter().enumerate() {
|
| 174 |
+
pt[i][0] += w[kk];
|
| 175 |
+
}
|
| 176 |
+
peso_total = Tensor::from_vec(pt.into_iter().flatten().collect::<Vec<f32>>(), (n, 1), &dev)?;
|
| 177 |
+
}
|
| 178 |
+
let pt_v = peso_total.to_vec2::<f32>()?;
|
| 179 |
+
for i in 0..n {
|
| 180 |
+
if pt_v[i][0] == 0.0 {
|
| 181 |
+
descartados += 1;
|
| 182 |
+
}
|
| 183 |
+
}
|
| 184 |
+
let denom = peso_total.clamp(1e-6, f64::INFINITY)?;
|
| 185 |
+
let saida = saida.broadcast_div(&denom)?;
|
| 186 |
+
// saída residual: y + roteamento (atenção já embutida em y)
|
| 187 |
+
let saida = (&y + &saida)?;
|
| 188 |
+
// perda auxiliar sobre o SUBCONJUNTO do papel (invariante global — M-R1)
|
| 189 |
+
let mut f = vec![0f32; e_local.max(1)];
|
| 190 |
+
let mut m = 0usize;
|
| 191 |
+
for i in 0..n {
|
| 192 |
+
let (mut melhor, mut mp) = (0usize, f32::NEG_INFINITY);
|
| 193 |
+
for (li, &g) in do_papel.iter().enumerate() {
|
| 194 |
+
if probs[i][g] > mp {
|
| 195 |
+
mp = probs[i][g];
|
| 196 |
+
melhor = li;
|
| 197 |
+
}
|
| 198 |
+
}
|
| 199 |
+
f[melhor] += 1.0;
|
| 200 |
+
m += 1;
|
| 201 |
+
}
|
| 202 |
+
if m > 0 && e_local > 0 {
|
| 203 |
+
for v in f.iter_mut() {
|
| 204 |
+
*v /= m as f32;
|
| 205 |
+
}
|
| 206 |
+
}
|
| 207 |
+
let f_t = Tensor::from_vec(f, (e_local.max(1),), &dev)?;
|
| 208 |
+
let p_media_local: Vec<f32> = (0..e_local)
|
| 209 |
+
.map(|li| {
|
| 210 |
+
let g = do_papel[li];
|
| 211 |
+
(0..n).map(|i| probs[i][g]).sum::<f32>() / n.max(1) as f32
|
| 212 |
+
})
|
| 213 |
+
.collect();
|
| 214 |
+
let p_t = Tensor::from_vec(p_media_local, (e_local.max(1),), &dev)?;
|
| 215 |
+
let perda_aux = ((&f_t * &p_t)?.sum_all()? * (e_local.max(1) as f64))?;
|
| 216 |
+
Ok(SaidaMoeR { saida, perda_aux, carga, descartados, usados })
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
/// **M-R6 (v0.8.0):** passada VETORIZADA — roteamento, acúmulo e perda
|
| 220 |
+
/// auxiliar em OPERAÇÕES DE TENSOR rastreadas (proposta Qwen-3.8 nº 4
|
| 221 |
+
/// IMPLEMENTADA de verdade: o esboço original terminava em
|
| 222 |
+
/// `unimplemented!()`; a fórmula da perda auxiliar `E·Σ f_e·p̄_e`
|
| 223 |
+
/// estava CORRETA — Switch Transformer — e é mantida).
|
| 224 |
+
///
|
| 225 |
+
/// **Caminho canônico desde a v0.9.0 (antes `fwd_vetorizado`):**
|
| 226 |
+
/// correção do bug v080-1 — a acumulação usa `index_add` (op
|
| 227 |
+
/// rastreada pelo autograd do candle — `IndexAdd` em op.rs) em vez do
|
| 228 |
+
/// round-trip `to_vec2`/`from_vec`; os pesos de roteamento saem do
|
| 229 |
+
/// PRÓPRIO tensor `probs` (vivo até o roteador); a perda auxiliar usa
|
| 230 |
+
/// `p̄` do tensor vivo com `f` constante (padrão Switch: argmax é
|
| 231 |
+
/// não-diferenciável, a média de probs carrega o gradiente). O
|
| 232 |
+
/// gradiente flui por TODOS os caminhos (teste M-R7) com VALORES
|
| 233 |
+
/// idênticos aos da referência `fwd` (mesma seleção — teste M-R6).
|
| 234 |
+
pub fn forward(&self, x: &Tensor, papel: Papel) -> Result<SaidaMoeR> {
|
| 235 |
+
let y = self.atencao.fwd(x)?; // (n, d)
|
| 236 |
+
let n = y.dim(0)?;
|
| 237 |
+
let d = y.dim(1)?;
|
| 238 |
+
let dev = y.device();
|
| 239 |
+
let e_total = self.especialistas.len();
|
| 240 |
+
let do_papel = self.indices_do_papel(papel);
|
| 241 |
+
let e_local = do_papel.len();
|
| 242 |
+
// 1) máscara do papel + softmax EM TENSOR — grafo VIVO até o roteador
|
| 243 |
+
let mut mascara_v = vec![f32::NEG_INFINITY; e_total];
|
| 244 |
+
for &e in &do_papel {
|
| 245 |
+
mascara_v[e] = 0.0;
|
| 246 |
+
}
|
| 247 |
+
let mascara = Tensor::from_vec(mascara_v, (1, e_total), &dev)?;
|
| 248 |
+
let logits = self.roteador.fwd(&y)?;
|
| 249 |
+
let mascarados = logits.broadcast_add(&mascara)?;
|
| 250 |
+
let probs = candle_nn::ops::softmax(&mascarados, candle_core::D::Minus1)?; // (n, E) VIVO
|
| 251 |
+
// 2) seleção discreta (única materialização — o roteamento duro é
|
| 252 |
+
// não-diferenciável por natureza; os PESOS ficam vivos no passo 3)
|
| 253 |
+
let probs_v = probs.to_vec2::<f32>()?;
|
| 254 |
+
let (designacao, carga) =
|
| 255 |
+
selecionar_com_capacidade(&probs_v, &do_papel, n, self.n_top, self.capacidade, e_total);
|
| 256 |
+
let usados: Vec<usize> = designacao.iter().map(|(ei, _)| *ei).collect();
|
| 257 |
+
// 3) acúmulo VIVO: index_add é rastreada — especialistas recebem
|
| 258 |
+
// gradiente pelas contribuições, e o roteador pelos pesos w
|
| 259 |
+
let mut saida = Tensor::zeros((n, d), candle_core::DType::F32, &dev)?;
|
| 260 |
+
let mut peso_total = Tensor::zeros((n, 1), candle_core::DType::F32, &dev)?;
|
| 261 |
+
for (ei, escolhidos) in &designacao {
|
| 262 |
+
let idx: Vec<u32> = escolhidos.iter().map(|&i| i as u32).collect();
|
| 263 |
+
let n_e = idx.len();
|
| 264 |
+
let idx_t = Tensor::from_vec(idx, (n_e,), &dev)?;
|
| 265 |
+
let tile = y.index_select(&idx_t, 0)?; // VIVO
|
| 266 |
+
let y_e = self.especialistas[*ei].fwd(&tile)?; // VIVO (gradiente!)
|
| 267 |
+
// w = probs[i][ei] VIVO: gradiente flui ao roteador
|
| 268 |
+
let linhas = probs.index_select(&idx_t, 0)?; // (n_e, E) VIVO
|
| 269 |
+
let w_t = linhas.narrow(1, *ei, 1)?.contiguous()?; // (n_e, 1) VIVO
|
| 270 |
+
let contrib = y_e.broadcast_mul(&w_t)?; // (n_e, d) VIVO
|
| 271 |
+
saida = saida.index_add(&idx_t, &contrib, 0)?; // VIVO (M-R6)
|
| 272 |
+
peso_total = peso_total.index_add(&idx_t, &w_t, 0)?; // VIVO
|
| 273 |
+
}
|
| 274 |
+
// 4) normalização idêntica à fwd (clamp 1e-6 nos descartados)
|
| 275 |
+
let pt_v = peso_total.to_vec2::<f32>()?; // estatística apenas
|
| 276 |
+
let mut descartados = 0usize;
|
| 277 |
+
for i in 0..n {
|
| 278 |
+
if pt_v[i][0] == 0.0 {
|
| 279 |
+
descartados += 1;
|
| 280 |
+
}
|
| 281 |
+
}
|
| 282 |
+
let denom = peso_total.clamp(1e-6, f64::INFINITY)?;
|
| 283 |
+
let saida = saida.broadcast_div(&denom)?;
|
| 284 |
+
let saida = (&y + &saida)?; // residual — como a fwd
|
| 285 |
+
// 5) perda auxiliar EM TENSOR (fórmula M-R1/Switch: e_local·Σ f_e·p̄_e)
|
| 286 |
+
let cols: Vec<u32> = do_papel.iter().map(|&e| e as u32).collect();
|
| 287 |
+
let cols_t = Tensor::from_vec(cols, (e_local.max(1),), &dev)?;
|
| 288 |
+
let probs_local = probs.index_select(&cols_t, 1)?; // (n, e_local) VIVO
|
| 289 |
+
let argmax_v = probs_local.argmax(candle_core::D::Minus1)?.to_vec1::<u32>()?;
|
| 290 |
+
let mut f = vec![0f32; e_local.max(1)];
|
| 291 |
+
for &a in &argmax_v {
|
| 292 |
+
f[a as usize] += 1.0;
|
| 293 |
+
}
|
| 294 |
+
if n > 0 {
|
| 295 |
+
for v in f.iter_mut() {
|
| 296 |
+
*v /= n as f32;
|
| 297 |
+
}
|
| 298 |
+
}
|
| 299 |
+
let f_t = Tensor::from_vec(f, (e_local.max(1),), &dev)?;
|
| 300 |
+
let p_barra = probs_local.mean_keepdim(0)?.flatten_all()?; // (e_local,) VIVO
|
| 301 |
+
let perda_aux = ((&f_t * &p_barra)?.sum_all()? * (e_local.max(1) as f64))?;
|
| 302 |
+
Ok(SaidaMoeR { saida, perda_aux, carga, descartados, usados })
|
| 303 |
+
}
|
| 304 |
+
|
| 305 |
+
/// **M-R3:** passadas Codificador e Decodificador em DUAS THREADS
|
| 306 |
+
/// (DAGs independentes — especialistas disjuntos por papel). Devolve
|
| 307 |
+
/// (enc, dec, tempo_paralelo_s, tempo_sequencial_s, speedup).
|
| 308 |
+
pub fn fwd_ambos_par(&self, x: &Tensor) -> Result<(SaidaMoeR, SaidaMoeR, f64, f64, f64)> {
|
| 309 |
+
use std::time::Instant;
|
| 310 |
+
// sequencial (medição)
|
| 311 |
+
let t0 = Instant::now();
|
| 312 |
+
let enc_seq = self.forward(x, Papel::Codificador)?;
|
| 313 |
+
let dec_seq = self.forward(x, Papel::Decodificador)?;
|
| 314 |
+
let t_seq = t0.elapsed().as_secs_f64();
|
| 315 |
+
// paralelo (2 threads com escopo — referências compartilhadas)
|
| 316 |
+
let t0 = Instant::now();
|
| 317 |
+
let (enc, dec) = {
|
| 318 |
+
let xref = &x;
|
| 319 |
+
let sref = &self;
|
| 320 |
+
std::thread::scope(|sc| {
|
| 321 |
+
let h1 = sc.spawn(move || sref.forward(xref, Papel::Codificador));
|
| 322 |
+
let h2 = sc.spawn(move || sref.forward(xref, Papel::Decodificador));
|
| 323 |
+
let r1 = h1.join().unwrap_or_else(|_| Err(candle_core::Error::Msg("thread enc".into())));
|
| 324 |
+
let r2 = h2.join().unwrap_or_else(|_| Err(candle_core::Error::Msg("thread dec".into())));
|
| 325 |
+
(r1, r2)
|
| 326 |
+
})
|
| 327 |
+
};
|
| 328 |
+
let (enc, dec) = (enc?, dec?);
|
| 329 |
+
let t_par = t0.elapsed().as_secs_f64();
|
| 330 |
+
// determinismo: paralelo == sequencial (mesmas entradas, especialistas disjuntos)
|
| 331 |
+
let dif = (&enc.saida - &enc_seq.saida)?.sqr()?.sum_all()?.to_scalar::<f32>()? as f64
|
| 332 |
+
+ (&dec.saida - &dec_seq.saida)?.sqr()?.sum_all()?.to_scalar::<f32>()? as f64;
|
| 333 |
+
assert!(dif < 1e-9, "paralelo deve ser bit-a-bit igual ao sequencial (dif={dif})");
|
| 334 |
+
let speedup = t_seq / t_par.max(1e-12);
|
| 335 |
+
Ok((enc, dec, t_par, t_seq, speedup))
|
| 336 |
+
}
|
| 337 |
+
}
|
| 338 |
+
|
| 339 |
+
// ---------------------------------------------------------------------------
|
| 340 |
+
// M-R5 — alocação water-filling por QE
|
| 341 |
+
// ---------------------------------------------------------------------------
|
| 342 |
+
|
| 343 |
+
/// Seleção top-k com capacidade por especialista (v0.8.0 — extraída
|
| 344 |
+
/// VERBATIM do loop da `fwd` v0.6.0: mesma ordem de candidatos, mesmos
|
| 345 |
+
/// desempates estáveis de `sort_by`). Compartilhada por `fwd` e
|
| 346 |
+
/// `forward` ⇒ as duas atribuem EXATAMENTE os mesmos tokens aos
|
| 347 |
+
/// mesmos especialistas (base do teste M-R6 — equivalência de valores).
|
| 348 |
+
/// Devolve (designação por especialista, carga global por especialista).
|
| 349 |
+
fn selecionar_com_capacidade(
|
| 350 |
+
probs: &[Vec<f32>],
|
| 351 |
+
do_papel: &[usize],
|
| 352 |
+
n: usize,
|
| 353 |
+
n_top: usize,
|
| 354 |
+
capacidade: usize,
|
| 355 |
+
n_especialistas: usize,
|
| 356 |
+
) -> (Vec<(usize, Vec<usize>)>, Vec<usize>) {
|
| 357 |
+
let mut carga = vec![0usize; n_especialistas];
|
| 358 |
+
let mut designacao: Vec<(usize, Vec<usize>)> = Vec::new();
|
| 359 |
+
for &ei in do_papel.iter() {
|
| 360 |
+
// candidatos ordenados por prob do especialista ei (desc)
|
| 361 |
+
let mut cand: Vec<(usize, f32)> = (0..n).map(|i| (i, probs[i][ei])).collect();
|
| 362 |
+
cand.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
|
| 363 |
+
let mut escolhidos: Vec<usize> = Vec::new();
|
| 364 |
+
for (i, _) in cand {
|
| 365 |
+
if carga[ei] >= capacidade {
|
| 366 |
+
break;
|
| 367 |
+
}
|
| 368 |
+
// ei está no top-k(papel) do token i?
|
| 369 |
+
let mut ordem: Vec<(f32, usize)> =
|
| 370 |
+
do_papel.iter().map(|&g| (probs[i][g], g)).collect();
|
| 371 |
+
ordem.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
|
| 372 |
+
let top: Vec<usize> = ordem.iter().rev().take(n_top).map(|(_, g)| *g).collect();
|
| 373 |
+
if top.contains(&ei) {
|
| 374 |
+
escolhidos.push(i);
|
| 375 |
+
carga[ei] += 1;
|
| 376 |
+
}
|
| 377 |
+
}
|
| 378 |
+
if escolhidos.is_empty() {
|
| 379 |
+
continue;
|
| 380 |
+
}
|
| 381 |
+
designacao.push((ei, escolhidos));
|
| 382 |
+
}
|
| 383 |
+
(designacao, carga)
|
| 384 |
+
}
|
| 385 |
+
|
| 386 |
+
/// Aloca `capacidade_total` especialistas entre células com QE `qes`
|
| 387 |
+
/// proporcionalmente ao QE (Cauchy–Schwarz: minimiza Σ q_i²/c_i).
|
| 388 |
+
/// Devolve c_i ≥ 1 com Σ c_i = capacidade_total (se capacidade ≥ células).
|
| 389 |
+
pub fn alocar_por_qe(qes: &[f64], capacidade_total: usize) -> Vec<usize> {
|
| 390 |
+
let m = qes.len();
|
| 391 |
+
if m == 0 {
|
| 392 |
+
return Vec::new();
|
| 393 |
+
}
|
| 394 |
+
let soma: f64 = qes.iter().sum::<f64>().max(1e-12);
|
| 395 |
+
let mut c: Vec<usize> = qes
|
| 396 |
+
.iter()
|
| 397 |
+
.map(|q| ((q / soma) * capacidade_total as f64).round() as usize)
|
| 398 |
+
.collect();
|
| 399 |
+
// garante mínimo 1 e corrige a soma por maior resíduo
|
| 400 |
+
for ci in c.iter_mut() {
|
| 401 |
+
*ci = (*ci).max(1);
|
| 402 |
+
}
|
| 403 |
+
let mut total: usize = c.iter().sum();
|
| 404 |
+
while total > capacidade_total.max(m) {
|
| 405 |
+
// remove da maior alocação
|
| 406 |
+
let (mut imax, mut vmax) = (0usize, 0usize);
|
| 407 |
+
for (i, &v) in c.iter().enumerate() {
|
| 408 |
+
if v > vmax {
|
| 409 |
+
vmax = v;
|
| 410 |
+
imax = i;
|
| 411 |
+
}
|
| 412 |
+
}
|
| 413 |
+
if c[imax] > 1 {
|
| 414 |
+
c[imax] -= 1;
|
| 415 |
+
}
|
| 416 |
+
total -= 1;
|
| 417 |
+
}
|
| 418 |
+
while total < capacidade_total {
|
| 419 |
+
let (mut imax, mut vmax) = (0usize, 0.0f64);
|
| 420 |
+
for (i, (&v, &q)) in c.iter().zip(qes.iter()).enumerate() {
|
| 421 |
+
let res = q / (v as f64);
|
| 422 |
+
if res > vmax {
|
| 423 |
+
vmax = res;
|
| 424 |
+
imax = i;
|
| 425 |
+
}
|
| 426 |
+
}
|
| 427 |
+
c[imax] += 1;
|
| 428 |
+
total += 1;
|
| 429 |
+
}
|
| 430 |
+
c
|
| 431 |
+
}
|
laboratorio/arquivo_split_v100/moe_redirecionavel/teste_integrado.rs
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! `moe_redirecionavel::teste_integrado` — extraído do monólito na v0.10.0
|
| 2 |
+
//! (divisão SRP, crítica Qwen3.8 lote 3 nº 1; r-35 §2).
|
| 3 |
+
|
| 4 |
+
use super::*;
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
#[cfg(test)]
|
| 8 |
+
mod teste_som_moe_integrado {
|
| 9 |
+
use super::*;
|
| 10 |
+
|
| 11 |
+
#[test]
|
| 12 |
+
fn debug_som_com_moe_caminho() {
|
| 13 |
+
let dev = Device::Cpu;
|
| 14 |
+
let dados_v: Vec<Vec<f64>> = (0..32).map(|i| (0..16).map(|j| (i * 7 + j * 3) as f64 / 100.0).collect()).collect();
|
| 15 |
+
let (n, d) = (dados_v.len(), 16);
|
| 16 |
+
let t = Tensor::from_vec(dados_v.into_iter().flatten().collect::<Vec<f64>>(), (n, d), &dev).unwrap()
|
| 17 |
+
.to_dtype(candle_core::DType::F32).unwrap();
|
| 18 |
+
let cfg = crate::som4d::CfgSom4D { nx: 2, ny: 2, nz: 2, nt: 2, ..Default::default() };
|
| 19 |
+
let som = crate::som4d::treinar_som4d(&t, &cfg, &dev).unwrap();
|
| 20 |
+
let centroides = som.prototipos.clone();
|
| 21 |
+
let r = refinar_som_com_moe(&t, ¢roides, 30, 1).unwrap();
|
| 22 |
+
println!("qe {} -> {} (wf) | uniforme {}", r.qe_antes, r.qe_depois, r.qe_alocacao_uniforme);
|
| 23 |
+
assert!(r.qe_depois < r.qe_antes, "corretor MoE reduz o QE");
|
| 24 |
+
assert!(r.mse_decodificador < r.qe_antes.powi(2), "redirect decodifica");
|
| 25 |
+
}
|
| 26 |
+
}
|
laboratorio/arquivo_split_v100/moe_redirecionavel/testes.rs
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! `moe_redirecionavel::testes` — extraído do monólito na v0.10.0
|
| 2 |
+
//! (divisão SRP, crítica Qwen3.8 lote 3 nº 1; r-35 §2).
|
| 3 |
+
|
| 4 |
+
use super::*;
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
#[cfg(test)]
|
| 8 |
+
#[allow(deprecated)] // testes usam o oráculo fwd (bug v080-1) de propósito
|
| 9 |
+
mod testes {
|
| 10 |
+
use super::*;
|
| 11 |
+
|
| 12 |
+
fn dados_sinteticos(n: usize, d: usize, semente: u64) -> Tensor {
|
| 13 |
+
let mut rng = crate::rng::RngDeterministico::novo(semente);
|
| 14 |
+
let v: Vec<f32> = (0..n * d).map(|_| rng.normal(0.0, 1.0) as f32).collect();
|
| 15 |
+
Tensor::from_vec(v, (n, d), &Device::Cpu).unwrap()
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
#[test]
|
| 19 |
+
fn mr1_invariancia_sob_redirecionamento() {
|
| 20 |
+
let dev = Device::Cpu;
|
| 21 |
+
let x = dados_sinteticos(64, 16, 3);
|
| 22 |
+
let mut moe = MoeRedirecionavel::novo(16, 6, 2, 64, &dev).unwrap();
|
| 23 |
+
let s1 = moe.fwd(&x, Papel::Codificador).unwrap();
|
| 24 |
+
let perda_antes = s1.perda_aux.to_scalar::<f32>().unwrap() as f64;
|
| 25 |
+
let carga_antes: usize = s1.carga.iter().sum();
|
| 26 |
+
moe.redirecionar_todos();
|
| 27 |
+
// após trocar TODOS os papéis, a passada Decodificador usa os
|
| 28 |
+
// especialistas que eram do codificador — a perda auxiliar do
|
| 29 |
+
// SUBCONJUNTO é comparável (mesma distribuição de roteamento)
|
| 30 |
+
let s2 = moe.fwd(&x, Papel::Decodificador).unwrap();
|
| 31 |
+
let perda_depois = s2.perda_aux.to_scalar::<f32>().unwrap() as f64;
|
| 32 |
+
let carga_depois: usize = s2.carga.iter().sum();
|
| 33 |
+
assert_eq!(carga_antes, carga_depois, "capacidade total conservada (M-R1)");
|
| 34 |
+
assert!(
|
| 35 |
+
(perda_antes - perda_depois).abs() < 2.0 + 1e-6,
|
| 36 |
+
"perda auxiliar da família conservada: {perda_antes:.4} vs {perda_depois:.4}"
|
| 37 |
+
);
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
#[test]
|
| 41 |
+
fn mr2_neutralidade_no_nascimento() {
|
| 42 |
+
let dev = Device::Cpu;
|
| 43 |
+
let x = dados_sinteticos(32, 8, 5);
|
| 44 |
+
let moe = MoeRedirecionavel::novo(8, 4, 2, 32, &dev).unwrap();
|
| 45 |
+
let g = moe.atencao.gate.as_tensor().to_scalar::<f32>().unwrap();
|
| 46 |
+
assert!(g == 0.0, "gate nasce zero");
|
| 47 |
+
let y = moe.atencao.fwd(&x).unwrap();
|
| 48 |
+
let dif = (&y - &x).unwrap().sqr().unwrap().sum_all().unwrap().to_scalar::<f32>().unwrap();
|
| 49 |
+
assert!(dif == 0.0, "y = x bit-a-bit no nascimento (dif={dif})");
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
#[test]
|
| 53 |
+
fn mr3_paralelismo_e_determinismo() {
|
| 54 |
+
let dev = Device::Cpu;
|
| 55 |
+
let x = dados_sinteticos(96, 24, 7);
|
| 56 |
+
let moe = MoeRedirecionavel::novo(24, 8, 2, 96, &dev).unwrap();
|
| 57 |
+
let (_enc, _dec, t_par, t_seq, speedup) = moe.fwd_ambos_par(&x).unwrap();
|
| 58 |
+
// determinismo já garantido por assert interno; speedup registrado
|
| 59 |
+
assert!(t_par > 0.0 && t_seq > 0.0);
|
| 60 |
+
let _ = speedup;
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
#[test]
|
| 64 |
+
fn mr5_water_filling_minimiza_cota() {
|
| 65 |
+
// cota Σ q_i²/c_i: water-filling ≤ uniforme (Cauchy–Schwarz)
|
| 66 |
+
let qes = vec![0.2, 0.5, 1.0, 0.3];
|
| 67 |
+
let c_wf = alocar_por_qe(&qes, 8);
|
| 68 |
+
let c_un = vec![2usize; 4];
|
| 69 |
+
let f = |c: &[usize]| qes.iter().zip(c).map(|(q, ci)| q * q / *ci as f64).sum::<f64>();
|
| 70 |
+
assert!(
|
| 71 |
+
f(&c_wf) <= f(&c_un) + 1e-9,
|
| 72 |
+
"water-filling {c_wf:?} (cota {:.4}) deve ≤ uniforme (cota {:.4})",
|
| 73 |
+
f(&c_wf), f(&c_un)
|
| 74 |
+
);
|
| 75 |
+
assert_eq!(c_wf.iter().sum::<usize>(), 8);
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
#[test]
|
| 79 |
+
fn jepa_moe_aprende() {
|
| 80 |
+
let x = dados_sinteticos(64, 12, 11);
|
| 81 |
+
let r = treinar_jepa_com_moe(&x, "moe", 60, 0.5, 42).unwrap();
|
| 82 |
+
assert!(r.perda_pred_final < r.perda_pred_inicial, "perda preditiva cai");
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
/// **M-R6 (v0.8.0):** equivalência de VALORES entre `fwd` e
|
| 86 |
+
/// `forward` — mesma seleção (auxiliar compartilhado), mesma
|
| 87 |
+
/// saída, mesma perda auxiliar, mesma carga/descartados.
|
| 88 |
+
#[test]
|
| 89 |
+
fn mr6_equivalencia_de_valores() {
|
| 90 |
+
let dev = Device::Cpu;
|
| 91 |
+
for (n, d, e, k, cap, seed) in [
|
| 92 |
+
(64usize, 16usize, 6usize, 2usize, 64usize, 3u64),
|
| 93 |
+
(96, 24, 8, 2, 96, 5),
|
| 94 |
+
(48, 12, 4, 1, 24, 9), // capacidade apertada: força descartados
|
| 95 |
+
] {
|
| 96 |
+
let x = dados_sinteticos(n, d, seed);
|
| 97 |
+
let moe = MoeRedirecionavel::novo(d, e, k, cap, &dev).unwrap();
|
| 98 |
+
let s_ref = moe.fwd(&x, Papel::Codificador).unwrap();
|
| 99 |
+
let s_vet = moe.forward(&x, Papel::Codificador).unwrap();
|
| 100 |
+
assert_eq!(s_ref.carga, s_vet.carga, "M-R6: mesma carga (n={n})");
|
| 101 |
+
assert_eq!(s_ref.usados, s_vet.usados, "M-R6: mesmos usados");
|
| 102 |
+
assert_eq!(s_ref.descartados, s_vet.descartados, "M-R6: mesmos descartados");
|
| 103 |
+
let dif = (&s_ref.saida - &s_vet.saida).unwrap()
|
| 104 |
+
.abs().unwrap().max_all().unwrap().to_scalar::<f32>().unwrap();
|
| 105 |
+
assert!(dif < 1e-4, "M-R6: max|Δsaída| = {dif} (n={n}, cap={cap})");
|
| 106 |
+
let pa = s_ref.perda_aux.to_scalar::<f32>().unwrap();
|
| 107 |
+
let pb = s_vet.perda_aux.to_scalar::<f32>().unwrap();
|
| 108 |
+
assert!(
|
| 109 |
+
(pa - pb).abs() < 1e-4,
|
| 110 |
+
"M-R6: perda auxiliar {pa:.6} vs {pb:.6} (n={n})"
|
| 111 |
+
);
|
| 112 |
+
}
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
/// **M-R7 (v0.8.0):** restauração do fluxo de gradiente — bug v080-1.
|
| 116 |
+
/// Com a `fwd` (referência de valores) os especialistas e o roteador
|
| 117 |
+
/// NÃO recebem gradiente (grafo seccionado por to_vec2/from_vec); com
|
| 118 |
+
/// a `forward` TODOS recebem (index_add/index_select vivos).
|
| 119 |
+
#[test]
|
| 120 |
+
fn mr7_restauracao_do_gradiente() {
|
| 121 |
+
let dev = Device::Cpu;
|
| 122 |
+
let x = dados_sinteticos(48, 12, 13);
|
| 123 |
+
let moe = MoeRedirecionavel::novo(12, 6, 2, 48, &dev).unwrap();
|
| 124 |
+
let norma_grads = |vetorizada: bool| -> (f64, f64) {
|
| 125 |
+
let s = if vetorizada {
|
| 126 |
+
moe.forward(&x, Papel::Codificador).unwrap()
|
| 127 |
+
} else {
|
| 128 |
+
moe.fwd(&x, Papel::Codificador).unwrap()
|
| 129 |
+
};
|
| 130 |
+
let perda = s.saida.sqr().unwrap().sum_all().unwrap();
|
| 131 |
+
let grads = perda.backward().unwrap();
|
| 132 |
+
let mut n_roteador = 0.0f64;
|
| 133 |
+
for v in moe.roteador.vars() {
|
| 134 |
+
if let Some(g) = grads.get(&v) {
|
| 135 |
+
n_roteador += g.sqr().unwrap().sum_all().unwrap()
|
| 136 |
+
.to_scalar::<f32>().unwrap() as f64;
|
| 137 |
+
}
|
| 138 |
+
}
|
| 139 |
+
let mut n_experts = 0.0f64;
|
| 140 |
+
for e in &moe.especialistas {
|
| 141 |
+
for v in e.vars() {
|
| 142 |
+
if let Some(g) = grads.get(&v) {
|
| 143 |
+
n_experts += g.sqr().unwrap().sum_all().unwrap()
|
| 144 |
+
.to_scalar::<f32>().unwrap() as f64;
|
| 145 |
+
}
|
| 146 |
+
}
|
| 147 |
+
}
|
| 148 |
+
(n_roteador, n_experts)
|
| 149 |
+
};
|
| 150 |
+
// (a) o bug v080-1 é REAL: na fwd, roteador e especialistas têm
|
| 151 |
+
// gradiente ZERO (grafo seccionado) — documentado, não corrigido na
|
| 152 |
+
// fwd (referência de valores preservada por decisão de projeto)
|
| 153 |
+
let (r_ref, e_ref) = norma_grads(false);
|
| 154 |
+
assert!(
|
| 155 |
+
r_ref == 0.0 && e_ref == 0.0,
|
| 156 |
+
"M-R7: bug v080-1 documentado — fwd secciona o grafo (roteador {r_ref}, experts {e_ref})"
|
| 157 |
+
);
|
| 158 |
+
// (b) a correção: na vetorizada, TODOS recebem gradiente
|
| 159 |
+
let (r_vet, e_vet) = norma_grads(true);
|
| 160 |
+
assert!(
|
| 161 |
+
r_vet > 0.0,
|
| 162 |
+
"M-R7: roteador recebe gradiente na vetorizada ({r_vet})"
|
| 163 |
+
);
|
| 164 |
+
assert!(
|
| 165 |
+
e_vet > 0.0,
|
| 166 |
+
"M-R7: especialistas recebem gradiente na vetorizada ({e_vet})"
|
| 167 |
+
);
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
/// **M-R8 (v0.8.0):** fim-a-fim — com a vetorizada, o treino REALMENTE
|
| 171 |
+
/// atualiza os pesos dos especialistas (regressão do bug v080-1: antes
|
| 172 |
+
/// só a atenção própria treinava no braço MoE).
|
| 173 |
+
#[test]
|
| 174 |
+
fn mr8_treino_atualiza_especialistas() {
|
| 175 |
+
let dev = Device::Cpu;
|
| 176 |
+
let x = dados_sinteticos(48, 12, 17);
|
| 177 |
+
let moe = MoeRedirecionavel::novo(12, 6, 2, 48, &dev).unwrap();
|
| 178 |
+
// snapshot com dados PRÓPRIOS (to_vec1) — detach() compartilha o
|
| 179 |
+
// storage e o set() do otimizador sobrescreveria a "cópia"
|
| 180 |
+
let snapshot: Vec<Vec<f32>> = moe
|
| 181 |
+
.especialistas
|
| 182 |
+
.iter()
|
| 183 |
+
.map(|e| {
|
| 184 |
+
e.vars()[0].as_tensor().flatten_all().unwrap().to_vec1::<f32>().unwrap()
|
| 185 |
+
})
|
| 186 |
+
.collect();
|
| 187 |
+
// treino curto com gradiente fluindo
|
| 188 |
+
let vars = moe.vars();
|
| 189 |
+
let mut opt = crate::treino::AdamWManual::novo(vars.clone(), 3e-3, 0.0);
|
| 190 |
+
for _ in 0..5 {
|
| 191 |
+
let s = moe.forward(&x, Papel::Codificador).unwrap();
|
| 192 |
+
let perda = s.saida.sqr().unwrap().sum_all().unwrap();
|
| 193 |
+
let grads = crate::treino::grads_achatados(&perda, &vars).unwrap();
|
| 194 |
+
opt.passo(grads);
|
| 195 |
+
}
|
| 196 |
+
let mut delta_max = 0.0f64;
|
| 197 |
+
for (e, antes) in moe.especialistas.iter().zip(snapshot.iter()) {
|
| 198 |
+
let agora = e.vars()[0].as_tensor().flatten_all().unwrap()
|
| 199 |
+
.to_vec1::<f32>().unwrap();
|
| 200 |
+
let dif = agora.iter().zip(antes.iter()).map(|(a, b)| (a - b).abs()).fold(0f32, f32::max);
|
| 201 |
+
delta_max = delta_max.max(dif as f64);
|
| 202 |
+
}
|
| 203 |
+
let _ = &vars;
|
| 204 |
+
assert!(
|
| 205 |
+
delta_max > 0.0,
|
| 206 |
+
"M-R8: especialistas devem mudar no treino (delta_max={delta_max})"
|
| 207 |
+
);
|
| 208 |
+
}
|
| 209 |
+
}
|
laboratorio/arquivo_split_v100/moe_redirecionavel/treino.rs
ADDED
|
@@ -0,0 +1,463 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! `moe_redirecionavel::treino` — extraído do monólito na v0.10.0
|
| 2 |
+
//! (divisão SRP, crítica Qwen3.8 lote 3 nº 1; r-35 §2).
|
| 3 |
+
|
| 4 |
+
use super::*;
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
// ---------------------------------------------------------------------------
|
| 8 |
+
// Aplicação JEPA — codificador/preditor redirecionáveis com MoE
|
| 9 |
+
// ---------------------------------------------------------------------------
|
| 10 |
+
|
| 11 |
+
pub struct RelatorioJepaMoe {
|
| 12 |
+
pub modo: &'static str,
|
| 13 |
+
pub perda_pred_inicial: f64,
|
| 14 |
+
pub perda_pred_final: f64,
|
| 15 |
+
pub perda_vc_final: f64,
|
| 16 |
+
pub std_emb: f64,
|
| 17 |
+
pub carga_max: usize,
|
| 18 |
+
pub descartados: usize,
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
/// Treino JEPA compacto com três braços (ablação honesta):
|
| 22 |
+
/// - `"pequena"`: codificador/preditor MLP simples (baseline);
|
| 23 |
+
/// - `"densa"`: MLP com o TOTAL de parâmetros dos especialistas (capacidade
|
| 24 |
+
/// equiparada, SEM roteamento — isola o ganho do roteamento);
|
| 25 |
+
/// - `"moe"`: `MoeRedirecionavel` nos dois caminhos (Codificador no
|
| 26 |
+
/// codificador, Decodificador no preditor) com atenção própria.
|
| 27 |
+
pub fn treinar_jepa_com_moe(
|
| 28 |
+
patches: &Tensor,
|
| 29 |
+
modo: &'static str,
|
| 30 |
+
passos: usize,
|
| 31 |
+
frac_mascara: f64,
|
| 32 |
+
semente: u64,
|
| 33 |
+
) -> Result<RelatorioJepaMoe> {
|
| 34 |
+
let dev = patches.device();
|
| 35 |
+
let n = patches.dim(0)?;
|
| 36 |
+
let d = patches.dim(1)?;
|
| 37 |
+
let mut rng = RngDeterministico::novo(semente);
|
| 38 |
+
// alvo = patches originais (detach); contexto = patches mascarados
|
| 39 |
+
let alvo = patches.detach();
|
| 40 |
+
let contexto = {
|
| 41 |
+
let mut v = patches.flatten_all()?.to_vec1::<f32>()?;
|
| 42 |
+
for x in v.iter_mut() {
|
| 43 |
+
if rng.uniforme() < frac_mascara {
|
| 44 |
+
*x = 0.0;
|
| 45 |
+
}
|
| 46 |
+
}
|
| 47 |
+
Tensor::from_vec(v, (n, d), &dev)?
|
| 48 |
+
};
|
| 49 |
+
let e = 4usize; // especialistas por papel no braço moe
|
| 50 |
+
let n_top = 2;
|
| 51 |
+
let capacidade = n;
|
| 52 |
+
|
| 53 |
+
// braços
|
| 54 |
+
enum Braco {
|
| 55 |
+
Pequena(MlpJepa, MlpJepa),
|
| 56 |
+
Densa(MlpJepa, MlpJepa),
|
| 57 |
+
Moe(MoeRedirecionavel),
|
| 58 |
+
}
|
| 59 |
+
let braco = match modo {
|
| 60 |
+
"pequena" => Braco::Pequena(
|
| 61 |
+
MlpJepa::novo(d, 2 * d, d, &dev)?,
|
| 62 |
+
MlpJepa::novo(d, 2 * d, d, &dev)?,
|
| 63 |
+
),
|
| 64 |
+
"densa" => {
|
| 65 |
+
// capacidade equiparada: oculta = soma das ocultas dos especialistas
|
| 66 |
+
let d_oculta = 2 * d * e;
|
| 67 |
+
Braco::Densa(
|
| 68 |
+
MlpJepa::novo(d, d_oculta, d, &dev)?,
|
| 69 |
+
MlpJepa::novo(d, d_oculta, d, &dev)?,
|
| 70 |
+
)
|
| 71 |
+
}
|
| 72 |
+
_ => Braco::Moe(MoeRedirecionavel::novo(d, 2 * e, n_top, capacidade, &dev)?),
|
| 73 |
+
};
|
| 74 |
+
|
| 75 |
+
let perda_de = |b: &Braco, x: &Tensor| -> Result<(Tensor, Tensor, usize)> {
|
| 76 |
+
match b {
|
| 77 |
+
Braco::Pequena(e1, p1) => {
|
| 78 |
+
let z = e1.fwd(x)?;
|
| 79 |
+
let yh = p1.fwd(&z)?;
|
| 80 |
+
let dif = (&yh - &alvo)?;
|
| 81 |
+
Ok(((dif.sqr()?.sum_all()? / (n as f64 * d as f64))?,
|
| 82 |
+
z.sqr()?.mean_all()?, 0))
|
| 83 |
+
}
|
| 84 |
+
Braco::Densa(e1, p1) => {
|
| 85 |
+
let z = e1.fwd(x)?;
|
| 86 |
+
let yh = p1.fwd(&z)?;
|
| 87 |
+
let dif = (&yh - &alvo)?;
|
| 88 |
+
Ok(((dif.sqr()?.sum_all()? / (n as f64 * d as f64))?,
|
| 89 |
+
z.sqr()?.mean_all()?, 0))
|
| 90 |
+
}
|
| 91 |
+
Braco::Moe(m) => {
|
| 92 |
+
// v0.9.0: forward (ex-fwd_vetorizado) — gradiente flui aos
|
| 93 |
+
// especialistas e ao roteador (a fwd seccionava o grafo)
|
| 94 |
+
let s_enc = m.forward(x, Papel::Codificador)?;
|
| 95 |
+
let s_dec = m.forward(&s_enc.saida, Papel::Decodificador)?;
|
| 96 |
+
let dif = (&s_dec.saida - &alvo)?;
|
| 97 |
+
let lp = (dif.sqr()?.sum_all()? / (n as f64 * d as f64))?;
|
| 98 |
+
// perda total = preditiva + aux balanceamento (ambos papéis)
|
| 99 |
+
let lt = (lp.affine(1.0, 0.0)? + s_enc.perda_aux.affine(m.lambda_aux, 0.0)?
|
| 100 |
+
+ s_dec.perda_aux.affine(m.lambda_aux, 0.0)?)?;
|
| 101 |
+
let carga_max = s_enc.carga.iter().copied().fold(0, usize::max)
|
| 102 |
+
.max(s_dec.carga.iter().copied().fold(0, usize::max));
|
| 103 |
+
Ok((lt, lp, carga_max))
|
| 104 |
+
}
|
| 105 |
+
}
|
| 106 |
+
};
|
| 107 |
+
|
| 108 |
+
let (mut opt, vars): (AdamWManual, Vec<Var>) = match &braco {
|
| 109 |
+
Braco::Pequena(a, b) => {
|
| 110 |
+
let v = [a.vars(), b.vars()].concat();
|
| 111 |
+
(AdamWManual::novo(v.clone(), 3e-3, 0.0), v)
|
| 112 |
+
}
|
| 113 |
+
Braco::Densa(a, b) => {
|
| 114 |
+
let v = [a.vars(), b.vars()].concat();
|
| 115 |
+
(AdamWManual::novo(v.clone(), 3e-3, 0.0), v)
|
| 116 |
+
}
|
| 117 |
+
Braco::Moe(m) => (AdamWManual::novo(m.vars(), 3e-3, 0.0), m.vars()),
|
| 118 |
+
};
|
| 119 |
+
// atenção própria: gate nasce 0; sobe 1 passo em 8 (aquecimento honesto
|
| 120 |
+
// do mecanismo — T-P5 análogo: neutralidade no nascimento, gradiente flui)
|
| 121 |
+
if let Braco::Moe(m) = &braco {
|
| 122 |
+
let g0 = m.atencao.gate.as_tensor().to_scalar::<f32>()? as f64;
|
| 123 |
+
let _ = g0;
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
let (l0, _, _) = perda_de(&braco, &contexto)?;
|
| 127 |
+
let perda_inicial = l0.to_scalar::<f32>()? as f64;
|
| 128 |
+
let mut perda_final = perda_inicial;
|
| 129 |
+
let mut vc_final = 0.0;
|
| 130 |
+
let mut carga_max = 0usize;
|
| 131 |
+
let mut descartados = 0usize;
|
| 132 |
+
let mut std_emb = 0.0;
|
| 133 |
+
for passo in 0..passos {
|
| 134 |
+
let (lt, lp, cm) = perda_de(&braco, &contexto)?;
|
| 135 |
+
if let Braco::Moe(m) = &braco {
|
| 136 |
+
// abre o gate gradualmente (0 → 1 em 25% dos passos)
|
| 137 |
+
let alvo_g = ((passo as f64 / (passos as f64 / 4.0).max(1.0)).min(1.0)) as f32;
|
| 138 |
+
let g_atual = m.atencao.gate.as_tensor().to_scalar::<f32>()? as f64;
|
| 139 |
+
if (alvo_g as f64 - g_atual).abs() > 1e-9 {
|
| 140 |
+
m.atencao.gate.set(&Tensor::new(alvo_g, &dev)?)?;
|
| 141 |
+
}
|
| 142 |
+
}
|
| 143 |
+
let grads = crate::treino::grads_achatados(<, &vars)?;
|
| 144 |
+
AdamWManual::clipar(&mut grads.clone(), 1.0);
|
| 145 |
+
let mut g2 = grads;
|
| 146 |
+
AdamWManual::clipar(&mut g2, 5.0);
|
| 147 |
+
opt.passo(g2);
|
| 148 |
+
perda_final = lp.to_scalar::<f32>()? as f64;
|
| 149 |
+
carga_max = cm;
|
| 150 |
+
// VC / std do embedding (para o relatório)
|
| 151 |
+
let (_, vc, _) = perda_de(&braco, &contexto)?;
|
| 152 |
+
vc_final = vc.to_scalar::<f32>()? as f64;
|
| 153 |
+
std_emb = {
|
| 154 |
+
let z = match &braco {
|
| 155 |
+
Braco::Pequena(a, _) => a.fwd(&contexto)?,
|
| 156 |
+
Braco::Densa(a, _) => a.fwd(&contexto)?,
|
| 157 |
+
Braco::Moe(m) => m.forward(&contexto, Papel::Codificador)?.saida,
|
| 158 |
+
};
|
| 159 |
+
z.flatten_all()?.to_vec1::<f32>()?.iter().map(|x| *x as f64).collect::<Vec<f64>>()
|
| 160 |
+
.chunks(n).map(|c| {
|
| 161 |
+
let m = c.iter().sum::<f64>() / c.len() as f64;
|
| 162 |
+
(c.iter().map(|x| (x - m).powi(2)).sum::<f64>() / c.len() as f64).sqrt()
|
| 163 |
+
}).sum::<f64>() / n as f64
|
| 164 |
+
};
|
| 165 |
+
}
|
| 166 |
+
if let Braco::Moe(m) = &braco {
|
| 167 |
+
let s = m.forward(&contexto, Papel::Codificador)?;
|
| 168 |
+
descartados = s.descartados;
|
| 169 |
+
}
|
| 170 |
+
Ok(RelatorioJepaMoe {
|
| 171 |
+
modo,
|
| 172 |
+
perda_pred_inicial: perda_inicial,
|
| 173 |
+
perda_pred_final: perda_final,
|
| 174 |
+
perda_vc_final: vc_final,
|
| 175 |
+
std_emb,
|
| 176 |
+
carga_max,
|
| 177 |
+
descartados,
|
| 178 |
+
})
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
// ---------------------------------------------------------------------------
|
| 182 |
+
// Aplicação SOM — refinamento residual com alocação por QE (M-R5)
|
| 183 |
+
// ---------------------------------------------------------------------------
|
| 184 |
+
|
| 185 |
+
pub struct RelatorioSomMoe {
|
| 186 |
+
pub qe_antes: f64,
|
| 187 |
+
pub qe_depois: f64,
|
| 188 |
+
pub qe_alocacao_uniforme: f64,
|
| 189 |
+
pub carga_por_celula: Vec<usize>,
|
| 190 |
+
pub tempo_treino_s: f64,
|
| 191 |
+
/// qualidade da DECODIFICAÇÃO após redirecionamento (mse w_bmu → x).
|
| 192 |
+
pub mse_decodificador: f64,
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
/// Refina um SOM 4D treinado com um MoE redirecionável:
|
| 196 |
+
/// 1. aloca especialistas por célula ∝ QE (water-filling — M-R5);
|
| 197 |
+
/// 2. treina o papel Codificador como corretor residual
|
| 198 |
+
/// `x̂ = w_bmu(x) + E(x)`;
|
| 199 |
+
/// 3. mede QE′; repete com alocação uniforme (ablação do water-filling);
|
| 200 |
+
/// 4. REDIRECIONA os especialistas para Decodificador e treina
|
| 201 |
+
/// `x̂ = E(w_bmu)` (reconstrução a partir do código) — mede o MSE.
|
| 202 |
+
pub fn refinar_som_com_moe(
|
| 203 |
+
dados: &Tensor,
|
| 204 |
+
centroides: &[Vec<f64>],
|
| 205 |
+
passos: usize,
|
| 206 |
+
semente: u64,
|
| 207 |
+
) -> Result<RelatorioSomMoe> {
|
| 208 |
+
use std::time::Instant;
|
| 209 |
+
let t0 = Instant::now();
|
| 210 |
+
let dev = dados.device();
|
| 211 |
+
let n = dados.dim(0)?;
|
| 212 |
+
let d = dados.dim(1)?;
|
| 213 |
+
let m = centroides.len();
|
| 214 |
+
// BMU + QE por célula (tolera F32/F64)
|
| 215 |
+
let dados_v: Vec<Vec<f64>> = match dados.to_vec2::<f64>() {
|
| 216 |
+
Ok(v) => v,
|
| 217 |
+
Err(_) => dados
|
| 218 |
+
.to_vec2::<f32>()?
|
| 219 |
+
.iter()
|
| 220 |
+
.map(|l| l.iter().map(|x| *x as f64).collect())
|
| 221 |
+
.collect(),
|
| 222 |
+
};
|
| 223 |
+
let bmu: Vec<usize> = dados_v
|
| 224 |
+
.iter()
|
| 225 |
+
.map(|x| {
|
| 226 |
+
centroides
|
| 227 |
+
.iter()
|
| 228 |
+
.enumerate()
|
| 229 |
+
.min_by(|(i, a), (j, b)| {
|
| 230 |
+
let da: f64 = a.iter().zip(x).map(|(w, v)| (w - v).powi(2)).sum();
|
| 231 |
+
let db: f64 = b.iter().zip(x).map(|(w, v)| (w - v).powi(2)).sum();
|
| 232 |
+
da.partial_cmp(&db).unwrap_or(std::cmp::Ordering::Equal).then(i.cmp(j))
|
| 233 |
+
})
|
| 234 |
+
.map(|(i, _)| i)
|
| 235 |
+
.unwrap_or(0)
|
| 236 |
+
})
|
| 237 |
+
.collect();
|
| 238 |
+
let mut qe_cel = vec![0f64; m];
|
| 239 |
+
let mut cont_cel = vec![0usize; m];
|
| 240 |
+
for (i, b) in bmu.iter().enumerate() {
|
| 241 |
+
let dist: f64 = centroides[*b].iter().zip(&dados_v[i]).map(|(w, v)| (w - v).powi(2)).sum();
|
| 242 |
+
qe_cel[*b] += dist.sqrt();
|
| 243 |
+
cont_cel[*b] += 1;
|
| 244 |
+
}
|
| 245 |
+
for i in 0..m {
|
| 246 |
+
if cont_cel[i] > 0 {
|
| 247 |
+
qe_cel[i] /= cont_cel[i] as f64;
|
| 248 |
+
}
|
| 249 |
+
}
|
| 250 |
+
let qe_antes: f64 = dados_v
|
| 251 |
+
.iter()
|
| 252 |
+
.enumerate()
|
| 253 |
+
.map(|(i, b)| {
|
| 254 |
+
let w = ¢roides[bmu[i]];
|
| 255 |
+
(w.iter().zip(b).map(|(a, v)| (a - v).powi(2)).sum::<f64>()).sqrt()
|
| 256 |
+
})
|
| 257 |
+
.sum::<f64>()
|
| 258 |
+
/ n as f64;
|
| 259 |
+
|
| 260 |
+
// ---------- braço water-filling ----------
|
| 261 |
+
// capacidade = m células + 8 especialistas EXTRA distribuídos ∝ QE
|
| 262 |
+
// (com C < m o water-filling degenera em uniforme — mínimo 1 por célula)
|
| 263 |
+
let capacidade_total = m + 8;
|
| 264 |
+
let aloca_wf = alocar_por_qe(&qe_cel, capacidade_total);
|
| 265 |
+
let qe_wf = treinar_corretor(dados, centroides, &bmu, &aloca_wf, passos, semente, &dev)?;
|
| 266 |
+
// ---------- braço uniforme (ablação: MESMO total e MESMA semente —
|
| 267 |
+
// única diferença é a alocação; round-robin soma exatamente C) ----------
|
| 268 |
+
let aloca_un = {
|
| 269 |
+
let mut a = vec![1usize; m];
|
| 270 |
+
let mut i = 0usize;
|
| 271 |
+
while a.iter().sum::<usize>() < capacidade_total {
|
| 272 |
+
a[i % m] += 1;
|
| 273 |
+
i += 1;
|
| 274 |
+
}
|
| 275 |
+
a
|
| 276 |
+
};
|
| 277 |
+
let qe_un = treinar_corretor(dados, centroides, &bmu, &aloca_un, passos, semente, &dev)?;
|
| 278 |
+
|
| 279 |
+
// ---------- redirecionamento → decodificador ----------
|
| 280 |
+
// mesma pool de especialistas, agora aprendendo w_bmu → x
|
| 281 |
+
let mse_dec = treinar_decodificador(dados, centroides, &bmu, &aloca_wf, passos, semente + 2, &dev)?;
|
| 282 |
+
|
| 283 |
+
Ok(RelatorioSomMoe {
|
| 284 |
+
qe_antes,
|
| 285 |
+
qe_depois: qe_wf,
|
| 286 |
+
qe_alocacao_uniforme: qe_un,
|
| 287 |
+
carga_por_celula: aloca_wf,
|
| 288 |
+
tempo_treino_s: t0.elapsed().as_secs_f64(),
|
| 289 |
+
mse_decodificador: mse_dec,
|
| 290 |
+
})
|
| 291 |
+
}
|
| 292 |
+
|
| 293 |
+
/// Corretor residual: x̂ = w_bmu + E_{célula}(x). Treina com AdamW.
|
| 294 |
+
fn treinar_corretor(
|
| 295 |
+
dados: &Tensor,
|
| 296 |
+
centroides: &[Vec<f64>],
|
| 297 |
+
bmu: &[usize],
|
| 298 |
+
alocacao: &[usize],
|
| 299 |
+
passos: usize,
|
| 300 |
+
semente: u64,
|
| 301 |
+
dev: &Device,
|
| 302 |
+
) -> Result<f64> {
|
| 303 |
+
let n = dados.dim(0)?;
|
| 304 |
+
let d = dados.dim(1)?;
|
| 305 |
+
// um "especialista" = MlpJepa por CÉLULA (capacidade alocada = nº de
|
| 306 |
+
// especialistas extra treinados nessa célula, somados em ensemble)
|
| 307 |
+
let n_esp_tot: usize = alocacao.iter().sum();
|
| 308 |
+
let mut ensembles: Vec<Vec<MlpJepa>> = Vec::with_capacity(centroides.len());
|
| 309 |
+
for c in alocacao {
|
| 310 |
+
let mut v = Vec::new();
|
| 311 |
+
for _ in 0..(*c).max(1) {
|
| 312 |
+
v.push(MlpJepa::novo(d, 4 * d, d, dev)?);
|
| 313 |
+
}
|
| 314 |
+
ensembles.push(v);
|
| 315 |
+
}
|
| 316 |
+
let mut vars: Vec<Var> = Vec::new();
|
| 317 |
+
for ens in &ensembles {
|
| 318 |
+
for e in ens {
|
| 319 |
+
vars.extend(e.vars());
|
| 320 |
+
}
|
| 321 |
+
}
|
| 322 |
+
let mut opt = AdamWManual::novo(vars.clone(), 3e-3, 0.0);
|
| 323 |
+
// tensores de apoio
|
| 324 |
+
let w_bmu = {
|
| 325 |
+
let v: Vec<f32> = (0..n).flat_map(|i| centroides[bmu[i]].iter().map(|x| *x as f32).collect::<Vec<f32>>()).collect();
|
| 326 |
+
Tensor::from_vec(v, (n, d), dev)?
|
| 327 |
+
};
|
| 328 |
+
let alvo_res = (dados - &w_bmu)?;
|
| 329 |
+
for _ in 0..passos {
|
| 330 |
+
let mut soma = Tensor::zeros((), candle_core::DType::F32, dev)?;
|
| 331 |
+
for (i, ens) in ensembles.iter().enumerate() {
|
| 332 |
+
// tokens da célula i
|
| 333 |
+
let idx: Vec<u32> = (0..n).filter(|&k| bmu[k] == i).map(|k| k as u32).collect();
|
| 334 |
+
if idx.is_empty() {
|
| 335 |
+
continue;
|
| 336 |
+
}
|
| 337 |
+
let m_idx = idx.len();
|
| 338 |
+
let it = Tensor::from_vec(idx, (m_idx,), dev)?;
|
| 339 |
+
let x_c = dados.index_select(&it, 0)?;
|
| 340 |
+
let r_c = alvo_res.index_select(&it, 0)?;
|
| 341 |
+
// ensemble: média das saídas
|
| 342 |
+
let mut y = Tensor::zeros((m_idx, d), candle_core::DType::F32, dev)?;
|
| 343 |
+
for e in ens {
|
| 344 |
+
y = (y.affine(1.0, 0.0)? + e.fwd(&x_c)?.affine(1.0, 0.0)?)?;
|
| 345 |
+
}
|
| 346 |
+
let k = ens.len() as f64;
|
| 347 |
+
let yh = y.affine(1.0 / k, 0.0)?;
|
| 348 |
+
let dif = (&yh - &r_c)?;
|
| 349 |
+
soma = (soma.affine(1.0, 0.0)? + dif.sqr()?.sum_all()?.affine(1.0 / (n as f64 * d as f64), 0.0)?)?;
|
| 350 |
+
}
|
| 351 |
+
let _ = n_esp_tot;
|
| 352 |
+
let grads = crate::treino::grads_achatados(&soma, &vars)?;
|
| 353 |
+
let mut g = grads;
|
| 354 |
+
AdamWManual::clipar(&mut g, 5.0);
|
| 355 |
+
opt.passo(g);
|
| 356 |
+
}
|
| 357 |
+
// QE refinado
|
| 358 |
+
let mut qe = 0f64;
|
| 359 |
+
for (i, ens) in ensembles.iter().enumerate() {
|
| 360 |
+
let idx: Vec<u32> = (0..n).filter(|&k| bmu[k] == i).map(|k| k as u32).collect();
|
| 361 |
+
if idx.is_empty() {
|
| 362 |
+
continue;
|
| 363 |
+
}
|
| 364 |
+
let m_idx = idx.len();
|
| 365 |
+
let it = Tensor::from_vec(idx, (m_idx,), dev)?;
|
| 366 |
+
let x_c = dados.index_select(&it, 0)?;
|
| 367 |
+
let mut y = Tensor::zeros((m_idx, d), candle_core::DType::F32, dev)?;
|
| 368 |
+
for e in ens {
|
| 369 |
+
y = (y.affine(1.0, 0.0)? + e.fwd(&x_c)?.affine(1.0, 0.0)?)?;
|
| 370 |
+
}
|
| 371 |
+
let k = ens.len() as f64;
|
| 372 |
+
let yh = y.affine(1.0 / k, 0.0)?;
|
| 373 |
+
let xhat = (w_bmu.index_select(&it, 0)? + &yh)?;
|
| 374 |
+
let dif = (&x_c - &xhat)?;
|
| 375 |
+
qe += dif.sqr()?.sum_all()?.to_scalar::<f32>()? as f64;
|
| 376 |
+
}
|
| 377 |
+
Ok((qe / (n as f64 * d as f64)).sqrt() * (d as f64).sqrt()) // QE médio por ponto (norma L2)
|
| 378 |
+
}
|
| 379 |
+
|
| 380 |
+
/// Decodificador (pós-redirecionamento): x̂ = E(w_bmu) — reconstrução
|
| 381 |
+
/// a partir apenas do código (centróide). Mede o MSE final.
|
| 382 |
+
fn treinar_decodificador(
|
| 383 |
+
dados: &Tensor,
|
| 384 |
+
centroides: &[Vec<f64>],
|
| 385 |
+
bmu: &[usize],
|
| 386 |
+
alocacao: &[usize],
|
| 387 |
+
passos: usize,
|
| 388 |
+
semente: u64,
|
| 389 |
+
dev: &Device,
|
| 390 |
+
) -> Result<f64> {
|
| 391 |
+
let _ = semente;
|
| 392 |
+
let n = dados.dim(0)?;
|
| 393 |
+
let d = dados.dim(1)?;
|
| 394 |
+
let mut ensembles: Vec<Vec<MlpJepa>> = Vec::with_capacity(centroides.len());
|
| 395 |
+
for c in alocacao {
|
| 396 |
+
let mut v = Vec::new();
|
| 397 |
+
for _ in 0..(*c).max(1) {
|
| 398 |
+
v.push(MlpJepa::novo(d, 4 * d, d, dev)?);
|
| 399 |
+
}
|
| 400 |
+
ensembles.push(v);
|
| 401 |
+
}
|
| 402 |
+
let mut vars: Vec<Var> = Vec::new();
|
| 403 |
+
for ens in &ensembles {
|
| 404 |
+
for e in ens {
|
| 405 |
+
vars.extend(e.vars());
|
| 406 |
+
}
|
| 407 |
+
}
|
| 408 |
+
let mut opt = AdamWManual::novo(vars.clone(), 3e-3, 0.0);
|
| 409 |
+
let w_bmu = {
|
| 410 |
+
let v: Vec<f32> = (0..n).flat_map(|i| centroides[bmu[i]].iter().map(|x| *x as f32).collect::<Vec<f32>>()).collect();
|
| 411 |
+
Tensor::from_vec(v, (n, d), dev)?
|
| 412 |
+
};
|
| 413 |
+
for _ in 0..passos {
|
| 414 |
+
let mut soma = Tensor::zeros((), candle_core::DType::F32, dev)?;
|
| 415 |
+
for (i, ens) in ensembles.iter().enumerate() {
|
| 416 |
+
let idx: Vec<u32> = (0..n).filter(|&k| bmu[k] == i).map(|k| k as u32).collect();
|
| 417 |
+
if idx.is_empty() {
|
| 418 |
+
continue;
|
| 419 |
+
}
|
| 420 |
+
let m_idx = idx.len();
|
| 421 |
+
let it = Tensor::from_vec(idx, (m_idx,), dev)?;
|
| 422 |
+
let w_c = w_bmu.index_select(&it, 0)?;
|
| 423 |
+
let x_c = dados.index_select(&it, 0)?;
|
| 424 |
+
let mut y = Tensor::zeros((m_idx, d), candle_core::DType::F32, dev)?;
|
| 425 |
+
for e in ens {
|
| 426 |
+
y = (y.affine(1.0, 0.0)? + e.fwd(&w_c)?.affine(1.0, 0.0)?)?;
|
| 427 |
+
}
|
| 428 |
+
let k = ens.len() as f64;
|
| 429 |
+
let yh = y.affine(1.0 / k, 0.0)?;
|
| 430 |
+
let dif = (&yh - &x_c)?;
|
| 431 |
+
soma = (soma.affine(1.0, 0.0)? + dif.sqr()?.sum_all()?.affine(1.0 / (n as f64 * d as f64), 0.0)?)?;
|
| 432 |
+
}
|
| 433 |
+
let grads = crate::treino::grads_achatados(&soma, &vars)?;
|
| 434 |
+
let mut g = grads;
|
| 435 |
+
AdamWManual::clipar(&mut g, 5.0);
|
| 436 |
+
opt.passo(g);
|
| 437 |
+
}
|
| 438 |
+
// MSE final do decodificador
|
| 439 |
+
let mut mse = 0f64;
|
| 440 |
+
for (i, ens) in ensembles.iter().enumerate() {
|
| 441 |
+
let idx: Vec<u32> = (0..n).filter(|&k| bmu[k] == i).map(|k| k as u32).collect();
|
| 442 |
+
if idx.is_empty() {
|
| 443 |
+
continue;
|
| 444 |
+
}
|
| 445 |
+
let m_idx = idx.len();
|
| 446 |
+
let it = Tensor::from_vec(idx, (m_idx,), dev)?;
|
| 447 |
+
let w_c = w_bmu.index_select(&it, 0)?;
|
| 448 |
+
let x_c = dados.index_select(&it, 0)?;
|
| 449 |
+
let mut y = Tensor::zeros((m_idx, d), candle_core::DType::F32, dev)?;
|
| 450 |
+
for e in ens {
|
| 451 |
+
y = (y.affine(1.0, 0.0)? + e.fwd(&w_c)?.affine(1.0, 0.0)?)?;
|
| 452 |
+
}
|
| 453 |
+
let k = ens.len() as f64;
|
| 454 |
+
let yh = y.affine(1.0 / k, 0.0)?;
|
| 455 |
+
let dif = (&yh - &x_c)?;
|
| 456 |
+
mse += dif.sqr()?.sum_all()?.to_scalar::<f32>()? as f64;
|
| 457 |
+
}
|
| 458 |
+
Ok(mse / (n as f64 * d as f64))
|
| 459 |
+
}
|
| 460 |
+
|
| 461 |
+
pub fn versao() -> &'static str {
|
| 462 |
+
"moe-redirecionavel-0.6.0"
|
| 463 |
+
}
|
laboratorio/arquivo_split_v100/pensamento/combinador.rs
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! `pensamento::combinador` — extraído do monólito na v0.10.0
|
| 2 |
+
//! (divisão SRP, crítica Qwen3.8 lote 3 nº 1; r-35 §2).
|
| 3 |
+
|
| 4 |
+
use super::*;
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
// ---------------------------------------------------------------------------
|
| 8 |
+
// Combinador algébrico (T-P3 — projeção ridge, Teo V-1' portado)
|
| 9 |
+
// ---------------------------------------------------------------------------
|
| 10 |
+
|
| 11 |
+
/// Projeção ridge: `r* = (WᵀW + εI)^{−1} Wᵀ r_alvo` — minimizador de
|
| 12 |
+
/// `‖W r − r_alvo‖² + ε‖r‖²` (o montador algébrico do "re-encaixe de peças").
|
| 13 |
+
///
|
| 14 |
+
/// **Prova (T-P3):** a função é quadrática estritamente convexa (ε > 0);
|
| 15 |
+
/// o gradiente anula-se exatamente em `r*` acima; o resíduo mínimo é
|
| 16 |
+
/// `‖(I − W(WᵀW+εI)^{−1}Wᵀ) r_alvo‖` — análogo direto do Teo V-1'.
|
| 17 |
+
pub fn projetar_ridge(w: &Tensor, r_alvo: &Tensor, eps: f64) -> Result<Tensor> {
|
| 18 |
+
// w: (m, n), r_alvo: (m, d) ⇒ r*: (n, d)
|
| 19 |
+
let n = w.dim(1)?;
|
| 20 |
+
let dev = w.device();
|
| 21 |
+
let wt = w.transpose(0, 1)?;
|
| 22 |
+
let wtw = wt.matmul(w)?;
|
| 23 |
+
let ident = Tensor::eye(n, candle_core::DType::F32, &dev)?.affine(eps, 0.0)?;
|
| 24 |
+
let m = (&wtw + &ident)?;
|
| 25 |
+
let rhs = wt.matmul(r_alvo)?;
|
| 26 |
+
resolver_simetrica(&m, &rhs)
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
/// Resolve `M x = B` para M simétrica (n, n) por eliminação de Gauss com
|
| 30 |
+
/// pivoteamento parcial (Cholesky não assumido — M pode ser só PSD+εI).
|
| 31 |
+
pub fn resolver_simetrica(m: &Tensor, b: &Tensor) -> Result<Tensor> {
|
| 32 |
+
let n = m.dim(0)?;
|
| 33 |
+
let d = b.dim(1)?;
|
| 34 |
+
let dev = m.device();
|
| 35 |
+
let mut a = m.to_vec2::<f32>()?;
|
| 36 |
+
let mut rhs = b.to_vec2::<f32>()?;
|
| 37 |
+
for col in 0..n {
|
| 38 |
+
// pivoteamento parcial
|
| 39 |
+
let (mut pivo, mut linha_p) = (a[col][col].abs(), col);
|
| 40 |
+
for r in col + 1..n {
|
| 41 |
+
if a[r][col].abs() > pivo {
|
| 42 |
+
pivo = a[r][col].abs();
|
| 43 |
+
linha_p = r;
|
| 44 |
+
}
|
| 45 |
+
}
|
| 46 |
+
if pivo < 1e-12 {
|
| 47 |
+
candle_core::bail!("matriz singular (pivo ~ 0 na coluna {col})");
|
| 48 |
+
}
|
| 49 |
+
a.swap(col, linha_p);
|
| 50 |
+
rhs.swap(col, linha_p);
|
| 51 |
+
for r in col + 1..n {
|
| 52 |
+
let f = a[r][col] / a[col][col];
|
| 53 |
+
for c in col..n {
|
| 54 |
+
a[r][c] -= f * a[col][c];
|
| 55 |
+
}
|
| 56 |
+
for c in 0..d {
|
| 57 |
+
rhs[r][c] -= f * rhs[col][c];
|
| 58 |
+
}
|
| 59 |
+
}
|
| 60 |
+
}
|
| 61 |
+
let mut x = vec![vec![0f32; d]; n];
|
| 62 |
+
for r in (0..n).rev() {
|
| 63 |
+
for c in 0..d {
|
| 64 |
+
let mut s = rhs[r][c];
|
| 65 |
+
for k in r + 1..n {
|
| 66 |
+
s -= a[r][k] * x[k][c];
|
| 67 |
+
}
|
| 68 |
+
x[r][c] = s / a[r][r];
|
| 69 |
+
}
|
| 70 |
+
}
|
| 71 |
+
let flat: Vec<f32> = x.into_iter().flatten().collect();
|
| 72 |
+
Ok(Tensor::from_vec(flat, (n, d), &dev)?)
|
| 73 |
+
}
|
laboratorio/arquivo_split_v100/pensamento/mod.rs
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! Tecnologia Pensamento — módulos: motor, combinador ridge,
|
| 2 |
+
//! quebra-cabeça pós-treino (divisão SRP v0.10.0 — r-35 §2).
|
| 3 |
+
|
| 4 |
+
//! Tecnologia **Pensamento** v0.5.0 — N-redes neurais flexíveis paralelizadas
|
| 5 |
+
//! integradas ao NCM, conectadas ao Mecanismo de Atenção, com raciocínio
|
| 6 |
+
//! temporal-estratégico (item d = a + b + c).
|
| 7 |
+
//!
|
| 8 |
+
//! **O que é (motivação do usuário):** Pensamento é semelhante ao
|
| 9 |
+
//! pós-treinamento — N-redes paralelas de tentativas cooperativas para
|
| 10 |
+
//! resolver o problema do item c (requisição do usuário) quando a
|
| 11 |
+
//! informação tem POUCA CONFIANÇA para gerar novo conhecimento (fora dos
|
| 12 |
+
//! padrões comuns), a partir de:
|
| 13 |
+
//! - **a)** conhecimento aprendido durante o treinamento;
|
| 14 |
+
//! - **b)** estado de inferência corrente;
|
| 15 |
+
//! - **c)** a requisição (prompt) do usuário;
|
| 16 |
+
//! e da ativação de **difusores** (exploração estocástica) e
|
| 17 |
+
//! **combinadores/montadores** (re-encaixe de peças por projeção algébrica).
|
| 18 |
+
//!
|
| 19 |
+
//! **Ciclo d (raciocínio temporal-estratégico):**
|
| 20 |
+
//! `planejamento → construção de etapas e distribuição/desmembramento de
|
| 21 |
+
//! competências → volta ao planejamento OU envio da resposta ao usuário`.
|
| 22 |
+
//!
|
| 23 |
+
//! **Provas (completas em `docs/memorias/r-21-provas-pensamento-v050.md`):**
|
| 24 |
+
//! - **T-P1 (gatilho mensurável e causal):** o gatilho
|
| 25 |
+
//! `1{conf(p) < τ_c}` com `conf = 1 − H(p)/log K` é função apenas da
|
| 26 |
+
//! distribuição preditiva CORRENTE — não transporta informação do futuro,
|
| 27 |
+
//! preservando a causalidade (mesma estrutura do gate G1 do NCM).
|
| 28 |
+
//! - **T-P2 (tentativas paralelas — auto-consistência):** com N tentativas
|
| 29 |
+
//! independentes, cada uma correta com prob. `p > 1/2`, a votação por
|
| 30 |
+
//! maioria tem `P(erro) ≤ exp(−2N(p−1/2)²)` (Hoeffding); com seleção
|
| 31 |
+
//! best-of-N por verificador exato, `P(sucesso) ≥ 1−(1−p)^N`.
|
| 32 |
+
//! - **T-P3 (combinador ótimo):** o montador por mínimos quadrados com
|
| 33 |
+
//! regularização ridge resolve `r* = (WᵀW+εI)^{−1}Wᵀr_alvo` — o resíduo é
|
| 34 |
+
//! o MÍNIMO possível na norma (pseudo-inversa, Teo V-1' do outro agente).
|
| 35 |
+
//! - **T-P4 (terminação e soundness do planejador):** o potencial
|
| 36 |
+
//! `Φ(k) = B − k` decresce estritamente a cada iteração do ciclo d ⇒ o
|
| 37 |
+
//! loop termina em ≤ B iterações (indução bem-fundada); a resposta só é
|
| 38 |
+
//! emitida com confiança ≥ τ_c OU com orçamento esgotado (declaração
|
| 39 |
+
//! honesta de queda de confiança na telemetria).
|
| 40 |
+
//! - **T-P5 (neutralidade no nascimento na atenção):** com o gate de
|
| 41 |
+
//! atenção das tentativas inicializado em ZERO, a saída da atenção é
|
| 42 |
+
//! bit-a-bit a da atenção base; a perturbação é limitada por
|
| 43 |
+
//! `‖Δy‖ ≤ L·|g|·‖W_k z‖` (Lipschitz com constante L do softmax).
|
| 44 |
+
//! - **T-P6 (composição d = a + b + c):** o condicionamento de cada
|
| 45 |
+
//! tentativa é `cond = [a; b; c]` — a estrutura de independência
|
| 46 |
+
//! condicional `p(resposta | a, b, c)` fatoriza pelo estado conjunto; as
|
| 47 |
+
//! tentativas só veem o PASSADO (causalidade preservada).
|
| 48 |
+
|
| 49 |
+
use candle_core::{Device, Result, Tensor, Var};
|
| 50 |
+
use crate::camadas::Linear;
|
| 51 |
+
use crate::jepa::MlpJepa;
|
| 52 |
+
use crate::rng::RngDeterministico;
|
| 53 |
+
use std::collections::HashMap;
|
| 54 |
+
|
| 55 |
+
// ---- divisão SRP v0.10.0 (r-35 §2): submódulos + re-exports ----
|
| 56 |
+
#[cfg(test)]
|
| 57 |
+
mod testes;
|
| 58 |
+
mod combinador;
|
| 59 |
+
mod motor;
|
| 60 |
+
mod quebra_cabeca;
|
| 61 |
+
|
| 62 |
+
pub use combinador::*;
|
| 63 |
+
pub use motor::*;
|
| 64 |
+
pub use quebra_cabeca::*;
|
| 65 |
+
|
| 66 |
+
// ---- itens mantidos no próprio mod.rs ----
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
pub fn versao() -> &'static str {
|
| 70 |
+
"pensamento-0.7.0"
|
| 71 |
+
}
|
laboratorio/arquivo_split_v100/pensamento/motor.rs
ADDED
|
@@ -0,0 +1,549 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! `pensamento::motor` — extraído do monólito na v0.10.0
|
| 2 |
+
//! (divisão SRP, crítica Qwen3.8 lote 3 nº 1; r-35 §2).
|
| 3 |
+
|
| 4 |
+
use super::*;
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
// ---------------------------------------------------------------------------
|
| 8 |
+
// Confiança e gatilho (T-P1)
|
| 9 |
+
// ---------------------------------------------------------------------------
|
| 10 |
+
|
| 11 |
+
/// Confiança da distribuição preditiva: `conf = 1 − H(softmax(z))/log K`.
|
| 12 |
+
///
|
| 13 |
+
/// **T-P1:** conf é função mensurável de `z` (diferenciável exceto em
|
| 14 |
+
/// medida zero), invariante a translação dos logits e satisfaz
|
| 15 |
+
/// `conf = 1` na massa de Dirac e `conf = 0` na uniforme — gatilho correto
|
| 16 |
+
/// para "pouca confiança".
|
| 17 |
+
pub fn confianca_de_logits(logits: &Tensor) -> Result<f64> {
|
| 18 |
+
let p = candle_nn::ops::softmax(logits, candle_core::D::Minus1)?;
|
| 19 |
+
let logp = p.log()?;
|
| 20 |
+
let entropia = (&p * &logp)?.sum_all()?.to_scalar::<f32>()? as f64 * -1.0;
|
| 21 |
+
let k = logits.dim(candle_core::D::Minus1)? as f64;
|
| 22 |
+
if k <= 1.0 {
|
| 23 |
+
return Ok(1.0);
|
| 24 |
+
}
|
| 25 |
+
Ok(1.0 - entropia / k.ln())
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
// ---------------------------------------------------------------------------
|
| 29 |
+
// Motor de Pensamento
|
| 30 |
+
// ---------------------------------------------------------------------------
|
| 31 |
+
|
| 32 |
+
pub struct MotorPensamento {
|
| 33 |
+
/// N redes de tentativa (flexíveis: heterogêneas por semente de
|
| 34 |
+
/// inicialização e por ruído de exploração).
|
| 35 |
+
pub tentativas: Vec<MlpJepa>,
|
| 36 |
+
/// Montador/combinador: concatena as N saídas → resposta agregada.
|
| 37 |
+
pub combinador: Linear,
|
| 38 |
+
/// Gate de atenção (T-P5): inicializado em ZERO (neutralidade no
|
| 39 |
+
/// nascimento). Escalar multiplicativo sobre a contribuição das
|
| 40 |
+
/// tentativas na atenção.
|
| 41 |
+
pub gate_atencao: Var,
|
| 42 |
+
pub n: usize,
|
| 43 |
+
pub d_cond: usize,
|
| 44 |
+
pub d_saida: usize,
|
| 45 |
+
/// limiar de confiança para emitir resposta (T-P4 soundness).
|
| 46 |
+
pub limiar_conf: f64,
|
| 47 |
+
/// orçamento de iterações do ciclo d (T-P4 terminação).
|
| 48 |
+
pub orcamento: usize,
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
#[derive(Debug, Clone)]
|
| 52 |
+
pub enum EventoCiclo {
|
| 53 |
+
Planejamento { iteracao: usize, temperatura: f64 },
|
| 54 |
+
DistribuicaoCompetencias { por_tentativa: Vec<f64> },
|
| 55 |
+
RePlanejamento { motivo: String },
|
| 56 |
+
Resposta { confianca: f64, iteracoes: usize },
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
#[derive(Debug, Clone)]
|
| 60 |
+
pub struct ResultadoPensamento {
|
| 61 |
+
/// resposta agregada (d_saida,).
|
| 62 |
+
pub resposta: Option<Tensor>,
|
| 63 |
+
/// candidatos das N tentativas na última iteração (n, d_saida).
|
| 64 |
+
pub candidatos: Tensor,
|
| 65 |
+
/// pesos do combinador na agregação final (positivos, soma ~1).
|
| 66 |
+
pub pesos: Vec<f64>,
|
| 67 |
+
/// confiança do verificador na resposta emitida (ou da última tentativa).
|
| 68 |
+
pub confianca: f64,
|
| 69 |
+
/// nº de iterações do ciclo d executadas.
|
| 70 |
+
pub iteracoes: usize,
|
| 71 |
+
pub trajetoria: Vec<EventoCiclo>,
|
| 72 |
+
pub telemetria: HashMap<String, f64>,
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
impl MotorPensamento {
|
| 76 |
+
/// Cria o motor com N tentativas. `d_cond` = dim(a) + dim(b) + dim(c).
|
| 77 |
+
pub fn novo(
|
| 78 |
+
d_cond: usize,
|
| 79 |
+
d_saida: usize,
|
| 80 |
+
n: usize,
|
| 81 |
+
limiar_conf: f64,
|
| 82 |
+
orcamento: usize,
|
| 83 |
+
dev: &Device,
|
| 84 |
+
) -> Result<Self> {
|
| 85 |
+
let n = n.max(1);
|
| 86 |
+
let tentativas = (0..n)
|
| 87 |
+
.map(|i| {
|
| 88 |
+
let mut m = MlpJepa::novo(d_cond, 2 * d_saida, d_saida, dev)?;
|
| 89 |
+
// heterogeneidade: re-semeia cada tentativa
|
| 90 |
+
let _ = i;
|
| 91 |
+
Ok(m)
|
| 92 |
+
})
|
| 93 |
+
.collect::<Result<Vec<_>>>()?;
|
| 94 |
+
let combinador = Linear::sem_vies(d_saida * n, d_saida, 0.05, dev)?;
|
| 95 |
+
let gate = Tensor::zeros((), candle_core::DType::F32, dev)?;
|
| 96 |
+
Ok(Self {
|
| 97 |
+
tentativas,
|
| 98 |
+
combinador,
|
| 99 |
+
gate_atencao: Var::from_tensor(&gate)?,
|
| 100 |
+
n,
|
| 101 |
+
d_cond,
|
| 102 |
+
d_saida,
|
| 103 |
+
limiar_conf,
|
| 104 |
+
orcamento,
|
| 105 |
+
})
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
pub fn vars(&self) -> Vec<Var> {
|
| 109 |
+
let mut v: Vec<Var> = Vec::new();
|
| 110 |
+
for t in &self.tentativas {
|
| 111 |
+
v.extend(t.vars());
|
| 112 |
+
}
|
| 113 |
+
v.extend(self.combinador.vars());
|
| 114 |
+
v.push(self.gate_atencao.clone());
|
| 115 |
+
v
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
/// Re-semeia a tentativa `i` com ruído (heterogeneidade estrutural —
|
| 119 |
+
/// "redes flexíveis"): injeta perturbação gaussiana nos pesos.
|
| 120 |
+
pub fn flexibilizar(&mut self, i: usize, amplitude: f64, rng: &mut RngDeterministico) -> Result<()> {
|
| 121 |
+
let t = &mut self.tentativas[i];
|
| 122 |
+
for v in t.vars() {
|
| 123 |
+
let forma: Vec<usize> = v.dims().to_vec();
|
| 124 |
+
let total: usize = forma.iter().product();
|
| 125 |
+
let ruido: Vec<f32> = (0..total).map(|_| rng.normal(0.0, amplitude) as f32).collect();
|
| 126 |
+
let rt = Tensor::from_vec(ruido, forma, v.device())?;
|
| 127 |
+
v.set(&(v.as_tensor().affine(1.0, 0.0)? + rt.affine(1.0, 0.0)?)?)?;
|
| 128 |
+
}
|
| 129 |
+
Ok(())
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
/// Candidatos das N tentativas para o condicionamento `cond` (d_cond,)
|
| 133 |
+
/// com temperatura de difusor `temp` (ruído exploratório nas saídas).
|
| 134 |
+
///
|
| 135 |
+
/// **T-P6:** `cond = [a; b; c]` — as tentativas veem exatamente a união
|
| 136 |
+
/// dos três estados; nada do futuro entra.
|
| 137 |
+
pub fn candidatos(&self, cond: &Tensor, temp: f64, rng: &mut RngDeterministico) -> Result<Tensor> {
|
| 138 |
+
let dev = cond.device();
|
| 139 |
+
let mut saidas: Vec<Tensor> = Vec::with_capacity(self.n);
|
| 140 |
+
let cond_b = if cond.dims().len() == 1 {
|
| 141 |
+
cond.broadcast_as((1, self.d_cond))?
|
| 142 |
+
} else {
|
| 143 |
+
cond.clone()
|
| 144 |
+
};
|
| 145 |
+
for t in &self.tentativas {
|
| 146 |
+
let o = t.fwd(&cond_b)?;
|
| 147 |
+
let o = if temp > 0.0 {
|
| 148 |
+
let total = self.d_saida;
|
| 149 |
+
let ruido: Vec<f32> =
|
| 150 |
+
(0..total).map(|_| rng.normal(0.0, temp as f64) as f32).collect();
|
| 151 |
+
let rt = Tensor::from_vec(ruido, (1, self.d_saida), &dev)?;
|
| 152 |
+
(o.clone() + rt.affine(1.0, 0.0)?)?
|
| 153 |
+
} else {
|
| 154 |
+
o
|
| 155 |
+
};
|
| 156 |
+
saidas.push(o);
|
| 157 |
+
}
|
| 158 |
+
Ok(Tensor::cat(&saidas, 0)?) // (n, d_saida)
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
/// **Combinador/montador (T-P3):** agregação por pesos de coerência —
|
| 162 |
+
/// tentativas que concordam com o consenso recebem mais peso (voto
|
| 163 |
+
/// contínuo), seguido da projeção linear aprendida do combinador.
|
| 164 |
+
pub fn agregar(&self, candidatos: &Tensor) -> Result<(Tensor, Vec<f64>)> {
|
| 165 |
+
let consenso = candidatos.mean_keepdim(0)?; // (1, d)
|
| 166 |
+
// pesos de coerência: similaridade de cosseno com o consenso
|
| 167 |
+
let dot = candidatos.matmul(&consenso.transpose(0, 1)?)?; // (n, 1)
|
| 168 |
+
let nc = candidatos.sqr()?.sum_keepdim(candle_core::D::Minus1)?.sqrt()?;
|
| 169 |
+
let ncs = consenso.sqr()?.sum_keepdim(candle_core::D::Minus1)?.sqrt()?;
|
| 170 |
+
let cos = dot.broadcast_div(&nc.broadcast_mul(&ncs)?)?; // (n, 1)
|
| 171 |
+
let cos_v = cos.flatten_all()?.to_vec1::<f32>()?;
|
| 172 |
+
let exps: Vec<f64> = cos_v.iter().map(|c| (*c as f64 * 4.0).exp()).collect();
|
| 173 |
+
let soma: f64 = exps.iter().sum();
|
| 174 |
+
let pesos: Vec<f64> = exps.iter().map(|e| e / soma).collect();
|
| 175 |
+
// média ponderada = "peças re-encaixadas"
|
| 176 |
+
let mut media = Tensor::zeros((1, self.d_saida), candle_core::DType::F32, candidatos.device())?;
|
| 177 |
+
for (i, p) in pesos.iter().enumerate() {
|
| 178 |
+
let linha = candidatos.get(i)?.broadcast_as((1, self.d_saida))?;
|
| 179 |
+
media = (media.affine(1.0, 0.0)? + linha.affine(*p, 0.0)?)?;
|
| 180 |
+
}
|
| 181 |
+
// montagem final pelo combinador aprendido
|
| 182 |
+
let concat = candidatos.flatten_all()?.broadcast_as((1, self.d_saida * self.n))?;
|
| 183 |
+
let montado = self.combinador.fwd(&concat)?;
|
| 184 |
+
// mistura 50/50: montagem aprendida + consenso ponderado (o
|
| 185 |
+
// combinador pode especializar-se; o consenso dá robustez T-P2)
|
| 186 |
+
let resposta = (montado.affine(0.5, 0.0)? + media.affine(0.5, 0.0)?)?;
|
| 187 |
+
Ok((resposta, pesos))
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
/// **Ciclo d completo (T-P4):** planejar → distribuir → agregar →
|
| 191 |
+
/// avaliar → (re-planejar | responder). O verificador externo devolve a
|
| 192 |
+
/// confiança `[0,1]` de uma resposta candidata.
|
| 193 |
+
pub fn raciocinar(
|
| 194 |
+
&mut self,
|
| 195 |
+
cond: &Tensor,
|
| 196 |
+
verificador: &dyn Fn(&Tensor) -> f64,
|
| 197 |
+
rng: &mut RngDeterministico,
|
| 198 |
+
) -> Result<ResultadoPensamento> {
|
| 199 |
+
let mut trajetoria = Vec::new();
|
| 200 |
+
let mut telemetria: HashMap<String, f64> = HashMap::new();
|
| 201 |
+
let mut temperatura = 0.1f64;
|
| 202 |
+
let mut melhor = (None::<Tensor>, -1.0f64, Vec::<f64>::new());
|
| 203 |
+
let mut iteracoes = 0usize;
|
| 204 |
+
let mut candidatos_final = Tensor::zeros(
|
| 205 |
+
(self.n, self.d_saida),
|
| 206 |
+
candle_core::DType::F32,
|
| 207 |
+
cond.device(),
|
| 208 |
+
)?;
|
| 209 |
+
|
| 210 |
+
loop {
|
| 211 |
+
iteracoes += 1;
|
| 212 |
+
// (1) PLANEJAMENTO: gerar candidatos com a temperatura corrente
|
| 213 |
+
trajetoria.push(EventoCiclo::Planejamento { iteracao: iteracoes, temperatura });
|
| 214 |
+
let candidatos = self.candidatos(cond, temperatura, rng)?;
|
| 215 |
+
candidatos_final = candidatos.clone();
|
| 216 |
+
// (2) DISTRIBUIÇÃO/DESMEMBRAMENTO DE COMPETÊNCIAS: pesos por
|
| 217 |
+
// coerência (quem concorda mais lidera a montagem)
|
| 218 |
+
let (resposta, pesos) = self.agregar(&candidatos)?;
|
| 219 |
+
trajetoria.push(EventoCiclo::DistribuicaoCompetencias { por_tentativa: pesos.clone() });
|
| 220 |
+
// (3) AVALIAÇÃO pelo verificador
|
| 221 |
+
let conf = verificador(&resposta);
|
| 222 |
+
telemetria.insert(format!("conf_iter_{}", iteracoes), conf);
|
| 223 |
+
if conf > melhor.1 {
|
| 224 |
+
melhor = (Some(resposta), conf, pesos.clone());
|
| 225 |
+
}
|
| 226 |
+
// (4) DECISÃO: responder ou re-planejar
|
| 227 |
+
if conf >= self.limiar_conf {
|
| 228 |
+
trajetoria.push(EventoCiclo::Resposta { confianca: conf, iteracoes });
|
| 229 |
+
telemetria.insert("iteracoes".into(), iteracoes as f64);
|
| 230 |
+
telemetria.insert("confianca_final".into(), conf);
|
| 231 |
+
telemetria.insert("temperatura_final".into(), temperatura);
|
| 232 |
+
return Ok(ResultadoPensamento {
|
| 233 |
+
resposta: melhor.0,
|
| 234 |
+
candidatos: candidatos_final,
|
| 235 |
+
pesos: melhor.2,
|
| 236 |
+
confianca: conf,
|
| 237 |
+
iteracoes,
|
| 238 |
+
trajetoria,
|
| 239 |
+
telemetria,
|
| 240 |
+
});
|
| 241 |
+
}
|
| 242 |
+
if iteracoes >= self.orcamento {
|
| 243 |
+
// Φ = B − k atingiu 0: termina SEM confiança — honestidade
|
| 244 |
+
trajetoria.push(EventoCiclo::Resposta { confianca: melhor.1, iteracoes });
|
| 245 |
+
telemetria.insert("iteracoes".into(), iteracoes as f64);
|
| 246 |
+
telemetria.insert("confianca_final".into(), melhor.1);
|
| 247 |
+
telemetria.insert("temperatura_final".into(), temperatura);
|
| 248 |
+
telemetria.insert("orcamento_esgotado".into(), 1.0);
|
| 249 |
+
return Ok(ResultadoPensamento {
|
| 250 |
+
resposta: melhor.0,
|
| 251 |
+
candidatos: candidatos_final,
|
| 252 |
+
pesos: melhor.2,
|
| 253 |
+
confianca: melhor.1,
|
| 254 |
+
iteracoes,
|
| 255 |
+
trajetoria,
|
| 256 |
+
telemetria,
|
| 257 |
+
});
|
| 258 |
+
}
|
| 259 |
+
// (5) RE-PLANEJAMENTO: aumenta a exploração (difusor mais quente)
|
| 260 |
+
temperatura = (temperatura * 1.6).min(2.0);
|
| 261 |
+
trajetoria.push(EventoCiclo::RePlanejamento {
|
| 262 |
+
motivo: format!("confiança {conf:.3} < limiar {}", self.limiar_conf),
|
| 263 |
+
});
|
| 264 |
+
}
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
/// **Perda de treino das tentativas + combinador (item a):** treino
|
| 268 |
+
/// cooperativo — cada tentativa minimiza sua perda contra o alvo E o
|
| 269 |
+
/// combinador minimiza a perda da agregação (o gradiente flui para
|
| 270 |
+
/// todos através do concat).
|
| 271 |
+
pub fn perda_treino(&self, cond: &Tensor, alvo: &Tensor) -> Result<Tensor> {
|
| 272 |
+
// cond (b, d_cond), alvo (b, d_saida)
|
| 273 |
+
let b = cond.dim(0)?;
|
| 274 |
+
let mut perdas: Vec<Tensor> = Vec::new();
|
| 275 |
+
let mut saidas: Vec<Tensor> = Vec::with_capacity(self.n);
|
| 276 |
+
for t in &self.tentativas {
|
| 277 |
+
let o = t.fwd(cond)?;
|
| 278 |
+
let dif = (&o - alvo)?;
|
| 279 |
+
perdas.push((dif.sqr()?.sum_all()? / (self.d_saida as f64 * b as f64))?);
|
| 280 |
+
saidas.push(o);
|
| 281 |
+
}
|
| 282 |
+
let concat = Tensor::cat(&saidas, candle_core::D::Minus1)?; // (b, n·d)
|
| 283 |
+
let montado = self.combinador.fwd(&concat)?;
|
| 284 |
+
let dif_m = (&montado - alvo)?;
|
| 285 |
+
perdas.push((dif_m.sqr()?.sum_all()? / (self.d_saida as f64 * b as f64))?);
|
| 286 |
+
// soma das perdas (cooperação: todas as redes + montador)
|
| 287 |
+
let mut total = perdas[0].clone();
|
| 288 |
+
for p in perdas.iter().skip(1) {
|
| 289 |
+
total = (total + p.clone())?;
|
| 290 |
+
}
|
| 291 |
+
Ok(total)
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
/// **Integração com o mecanismo de atenção (T-P5):** anexa as saídas das
|
| 295 |
+
/// tentativas como chaves/valores extra com gate escalar.
|
| 296 |
+
///
|
| 297 |
+
/// Com `gate = 0` (nascimento): saída IDÊNTICA à atenção base
|
| 298 |
+
/// (neutralidade); o gradiente flui pelo gate (não-degenerado).
|
| 299 |
+
pub fn atencao_integrada(
|
| 300 |
+
&self,
|
| 301 |
+
q: &Tensor,
|
| 302 |
+
k_base: &Tensor,
|
| 303 |
+
v_base: &Tensor,
|
| 304 |
+
candidatos: &Tensor,
|
| 305 |
+
) -> Result<Tensor> {
|
| 306 |
+
// q (b, n_q, d), k_base (b, n_kv, d), v_base (b, n_kv, d_v),
|
| 307 |
+
// candidatos (n_tent, d) — projetados para d e d_v
|
| 308 |
+
let dev = q.device();
|
| 309 |
+
let d = k_base.dim(candle_core::D::Minus1)?;
|
| 310 |
+
let d_v = v_base.dim(candle_core::D::Minus1)?;
|
| 311 |
+
let b = q.dim(0)?;
|
| 312 |
+
// projeta candidatos (média simples — sem parâmetros extra): os
|
| 313 |
+
// candidatos têm d_saida; se d == d_saida usa direto, senão padding/
|
| 314 |
+
// truncamento honesto
|
| 315 |
+
let cand = if self.d_saida == d {
|
| 316 |
+
candidatos.clone()
|
| 317 |
+
} else if self.d_saida > d {
|
| 318 |
+
let v = candidatos
|
| 319 |
+
.flatten_all()?
|
| 320 |
+
.to_vec1::<f32>()?
|
| 321 |
+
.chunks(self.d_saida)
|
| 322 |
+
.map(|c| c[..d].to_vec())
|
| 323 |
+
.flatten()
|
| 324 |
+
.collect::<Vec<f32>>();
|
| 325 |
+
Tensor::from_vec(v, (self.n, d), &dev)?
|
| 326 |
+
} else {
|
| 327 |
+
let mut v = candidatos.flatten_all()?.to_vec1::<f32>()?;
|
| 328 |
+
let mut linhas = Vec::new();
|
| 329 |
+
for i in 0..self.n {
|
| 330 |
+
let mut linha = v[i * self.d_saida..(i + 1) * self.d_saida].to_vec();
|
| 331 |
+
linha.extend(std::iter::repeat(0f32).take(d - self.d_saida));
|
| 332 |
+
linhas.push(linha);
|
| 333 |
+
}
|
| 334 |
+
v = linhas.into_iter().flatten().collect();
|
| 335 |
+
Tensor::from_vec(v, (self.n, d), &dev)?
|
| 336 |
+
};
|
| 337 |
+
let k_extra = cand.broadcast_as((b, self.n, d))?;
|
| 338 |
+
let v_extra = if d_v == d {
|
| 339 |
+
k_extra.clone()
|
| 340 |
+
} else {
|
| 341 |
+
// projeção simples por média de colunas quando d_v != d
|
| 342 |
+
let media = k_extra.mean_keepdim(candle_core::D::Minus1)?;
|
| 343 |
+
media.broadcast_as((b, self.n, d_v))?
|
| 344 |
+
};
|
| 345 |
+
// atenção sobre [base; extra]
|
| 346 |
+
let k = Tensor::cat(&[k_base.clone(), k_extra], 1)?;
|
| 347 |
+
let v = Tensor::cat(&[v_base.clone(), v_extra], 1)?;
|
| 348 |
+
let scores = (q.matmul(&k.transpose(1, 2)?)? / (d as f64).sqrt())?;
|
| 349 |
+
let attn = candle_nn::ops::softmax(&scores, candle_core::D::Minus1)?;
|
| 350 |
+
let y_base_e_extra = attn.matmul(&v)?;
|
| 351 |
+
// atenção apenas-base (para neutralidade: gate = 0 ⇒ saída = base)
|
| 352 |
+
let scores_base = (q.matmul(&k_base.transpose(1, 2)?)? / (d as f64).sqrt())?;
|
| 353 |
+
let attn_base = candle_nn::ops::softmax(&scores_base, candle_core::D::Minus1)?;
|
| 354 |
+
let y_base = attn_base.matmul(v_base)?;
|
| 355 |
+
// mistura: y = y_base + gate·(y_completo − y_base)
|
| 356 |
+
let g = self.gate_atencao.as_tensor();
|
| 357 |
+
let delta = (&y_base_e_extra - &y_base)?;
|
| 358 |
+
let forma: Vec<usize> = delta.dims().to_vec();
|
| 359 |
+
let delta = (delta.affine(1.0, 0.0)? * g.broadcast_as(forma)?)?;
|
| 360 |
+
Ok((&y_base + &delta)?)
|
| 361 |
+
}
|
| 362 |
+
|
| 363 |
+
// -----------------------------------------------------------------------
|
| 364 |
+
// v0.6.0 — verificador NCM (sem oráculo) + tentativas PARALELAS
|
| 365 |
+
// -----------------------------------------------------------------------
|
| 366 |
+
|
| 367 |
+
/// Candidatos das N tentativas em PARALELO (rayon) — as N redes têm
|
| 368 |
+
/// parâmetros disjuntos e entradas idênticas ⇒ N sub-DAGs independentes
|
| 369 |
+
/// no grafo de computação (mesma estrutura da prova M-R3): tempo
|
| 370 |
+
/// paralelo = max_i T_i + sobrecarga de agendamento.
|
| 371 |
+
/// Determinismo: o ruído da tentativa i usa a semente `semente + i`
|
| 372 |
+
/// (fluxos independentes por construção — reprodutível em qualquer
|
| 373 |
+
/// nº de threads).
|
| 374 |
+
pub fn candidatos_par(
|
| 375 |
+
&self,
|
| 376 |
+
cond: &Tensor,
|
| 377 |
+
temp: f64,
|
| 378 |
+
semente: u64,
|
| 379 |
+
) -> Result<(Tensor, f64)> {
|
| 380 |
+
use rayon::prelude::*;
|
| 381 |
+
let dev = cond.device();
|
| 382 |
+
let cond_b = if cond.dims().len() == 1 {
|
| 383 |
+
cond.broadcast_as((1, self.d_cond))?
|
| 384 |
+
} else {
|
| 385 |
+
cond.clone()
|
| 386 |
+
};
|
| 387 |
+
let t0 = std::time::Instant::now();
|
| 388 |
+
let saidas: Vec<Tensor> = self
|
| 389 |
+
.tentativas
|
| 390 |
+
.par_iter()
|
| 391 |
+
.enumerate()
|
| 392 |
+
.map(|(i, t)| -> Result<Tensor> {
|
| 393 |
+
let o = t.fwd(&cond_b)?;
|
| 394 |
+
if temp > 0.0 {
|
| 395 |
+
let mut rng = RngDeterministico::novo(semente + i as u64);
|
| 396 |
+
let ruido: Vec<f32> =
|
| 397 |
+
(0..self.d_saida).map(|_| rng.normal(0.0, temp) as f32).collect();
|
| 398 |
+
let rt = Tensor::from_vec(ruido, (1, self.d_saida), &dev)?;
|
| 399 |
+
Ok((&o + &rt.affine(1.0, 0.0)?)?)
|
| 400 |
+
} else {
|
| 401 |
+
Ok(o)
|
| 402 |
+
}
|
| 403 |
+
})
|
| 404 |
+
.collect::<Result<Vec<_>>>()?;
|
| 405 |
+
let dt = t0.elapsed().as_secs_f64();
|
| 406 |
+
Ok((Tensor::cat(&saidas, 0)?, dt)) // (n, d_saida), tempo paralelo
|
| 407 |
+
}
|
| 408 |
+
|
| 409 |
+
/// **Variante em LOTE (v0.6.0 — fase C):** cond (b, d_cond) →
|
| 410 |
+
/// candidatos (b, n, d_saida) — as N tentativas processam o lote
|
| 411 |
+
/// inteiro (paralelas entre si; ruído por (linha, tentativa) com
|
| 412 |
+
/// semente determinística `semente + i`).
|
| 413 |
+
pub fn candidatos_lote(&self, cond: &Tensor, temp: f64, semente: u64) -> Result<Tensor> {
|
| 414 |
+
let b = cond.dim(0)?;
|
| 415 |
+
let dev = cond.device();
|
| 416 |
+
let mut saidas: Vec<Tensor> = Vec::with_capacity(self.n);
|
| 417 |
+
for (i, t) in self.tentativas.iter().enumerate() {
|
| 418 |
+
let o = t.fwd(cond)?; // (b, d_saida)
|
| 419 |
+
let o = if temp > 0.0 {
|
| 420 |
+
let mut rng = RngDeterministico::novo(semente + i as u64);
|
| 421 |
+
let ruido: Vec<f32> = (0..b * self.d_saida)
|
| 422 |
+
.map(|_| rng.normal(0.0, temp) as f32)
|
| 423 |
+
.collect();
|
| 424 |
+
let rt = Tensor::from_vec(ruido, (b, self.d_saida), &dev)?;
|
| 425 |
+
(&o + &rt)?
|
| 426 |
+
} else {
|
| 427 |
+
o
|
| 428 |
+
};
|
| 429 |
+
saidas.push(o.unsqueeze(1)?); // (b, 1, d_saida)
|
| 430 |
+
}
|
| 431 |
+
Ok(Tensor::cat(&saidas, 1)?) // (b, n, d_saida)
|
| 432 |
+
}
|
| 433 |
+
|
| 434 |
+
/// **Agregação em LOTE (v0.6.0):** candidatos (b, n, d) → resposta
|
| 435 |
+
/// (b, d) — mesma mistura 50/50 (montagem aprendida + consenso
|
| 436 |
+
/// ponderado por coerência) da versão 1-D, VETORIZADA e totalmente
|
| 437 |
+
/// diferenciável (gradiente flui pelos DOIS caminhos). Devolve também
|
| 438 |
+
/// os pesos médios (telemetria).
|
| 439 |
+
pub fn agregar_lote(&self, candidatos: &Tensor) -> Result<(Tensor, Vec<f64>)> {
|
| 440 |
+
let b = candidatos.dim(0)?;
|
| 441 |
+
let n = candidatos.dim(1)?;
|
| 442 |
+
let d = candidatos.dim(2)?;
|
| 443 |
+
let dev = candidatos.device();
|
| 444 |
+
// consenso (b, d)
|
| 445 |
+
let consenso = candidatos.mean(1)?;
|
| 446 |
+
// cosseno por (b, n): ⟨cand_i, consenso⟩ / (‖cand_i‖·‖consenso‖)
|
| 447 |
+
let dot = candidatos.matmul(&consenso.unsqueeze(2)?)?; // (b, n, 1)
|
| 448 |
+
let nc = candidatos.sqr()?.sum_keepdim(candle_core::D::Minus1)?.sqrt()?; // (b, n, 1)
|
| 449 |
+
let ncs = consenso.sqr()?.sum_keepdim(candle_core::D::Minus1)?.sqrt()?.unsqueeze(1)?; // (b, 1, 1)
|
| 450 |
+
let cos = dot.broadcast_div(&nc.broadcast_mul(&ncs)?)?; // (b, n, 1)
|
| 451 |
+
// pesos softmax de coerência (b, n, 1) — tensor puro (grafo intacto)
|
| 452 |
+
let exps = cos.affine(4.0, 0.0)?.exp()?;
|
| 453 |
+
let soma = exps.sum_keepdim(1)?; // (b, 1, 1)
|
| 454 |
+
let pesos = exps.broadcast_div(&soma)?; // (b, n, 1)
|
| 455 |
+
// média ponderada: Σ_n pesos·cand → (b, d)
|
| 456 |
+
let media = candidatos.broadcast_mul(&pesos)?.sum(1)?; // (b, d)
|
| 457 |
+
// montagem aprendida: concat sobre n → combinador
|
| 458 |
+
let concat = candidatos.reshape((b, n * d))?;
|
| 459 |
+
let montado = self.combinador.fwd(&concat)?; // (b, d)
|
| 460 |
+
let resposta = (montado.affine(0.5, 0.0)? + media.affine(0.5, 0.0)?)?;
|
| 461 |
+
// pesos médios para telemetria (leitura — não afeta o grafo)
|
| 462 |
+
let pesos_v = pesos.flatten_all()?.to_vec1::<f32>()?;
|
| 463 |
+
let mut pesos_medios = vec![0f64; n];
|
| 464 |
+
for (k, p) in pesos_v.iter().enumerate() {
|
| 465 |
+
pesos_medios[k % n] += *p as f64 / b as f64;
|
| 466 |
+
}
|
| 467 |
+
let _ = d;
|
| 468 |
+
let _ = dev;
|
| 469 |
+
Ok((resposta, pesos_medios))
|
| 470 |
+
}
|
| 471 |
+
|
| 472 |
+
/// **Ciclo d com o VERIFICADOR NCM (v0.6.0 — fecha o débito r-21 §3.1).**
|
| 473 |
+
///
|
| 474 |
+
/// `logits_fn` mapeia uma resposta candidata (1, d_saida) → logits da
|
| 475 |
+
/// distribuição preditiva do BACKBONE condicionada à correção (passada
|
| 476 |
+
/// corrente — V-4 causal). O verificador calibrado devolve a confiança;
|
| 477 |
+
/// NENHUM acesso ao alvo verdadeiro (o oráculo morre aqui).
|
| 478 |
+
pub fn raciocinar_ncm(
|
| 479 |
+
&mut self,
|
| 480 |
+
cond: &Tensor,
|
| 481 |
+
verificador: &crate::verificador::VerificadorNcm,
|
| 482 |
+
logits_fn: &dyn Fn(&Tensor) -> Result<Tensor>,
|
| 483 |
+
rng: &mut RngDeterministico,
|
| 484 |
+
) -> Result<ResultadoPensamento> {
|
| 485 |
+
let mut trajetoria = Vec::new();
|
| 486 |
+
let mut telemetria: HashMap<String, f64> = HashMap::new();
|
| 487 |
+
let mut temperatura = 0.1f64;
|
| 488 |
+
let mut melhor = (None::<Tensor>, -1.0f64, Vec::<f64>::new());
|
| 489 |
+
let mut iteracoes = 0usize;
|
| 490 |
+
let mut candidatos_final = Tensor::zeros(
|
| 491 |
+
(self.n, self.d_saida),
|
| 492 |
+
candle_core::DType::F32,
|
| 493 |
+
cond.device(),
|
| 494 |
+
)?;
|
| 495 |
+
loop {
|
| 496 |
+
iteracoes += 1;
|
| 497 |
+
trajetoria.push(EventoCiclo::Planejamento { iteracao: iteracoes, temperatura });
|
| 498 |
+
let candidatos = self.candidatos(cond, temperatura, rng)?;
|
| 499 |
+
candidatos_final = candidatos.clone();
|
| 500 |
+
let (resposta, pesos) = self.agregar(&candidatos)?;
|
| 501 |
+
trajetoria.push(EventoCiclo::DistribuicaoCompetencias { por_tentativa: pesos.clone() });
|
| 502 |
+
// AVALIAÇÃO pelo VERIFICADOR NCM (sem oráculo): confiança
|
| 503 |
+
// calibrada da distribuição preditiva do backbone
|
| 504 |
+
let logits = logits_fn(&resposta)?;
|
| 505 |
+
let conf = verificador.confianca_1d(&logits)?;
|
| 506 |
+
telemetria.insert(format!("conf_iter_{}", iteracoes), conf);
|
| 507 |
+
if conf > melhor.1 {
|
| 508 |
+
melhor = (Some(resposta), conf, pesos.clone());
|
| 509 |
+
}
|
| 510 |
+
if conf >= self.limiar_conf {
|
| 511 |
+
trajetoria.push(EventoCiclo::Resposta { confianca: conf, iteracoes });
|
| 512 |
+
telemetria.insert("iteracoes".into(), iteracoes as f64);
|
| 513 |
+
telemetria.insert("confianca_final".into(), conf);
|
| 514 |
+
telemetria.insert("temperatura_final".into(), temperatura);
|
| 515 |
+
telemetria.insert("verificador".into(), 1.0); // ncm (sem oráculo)
|
| 516 |
+
return Ok(ResultadoPensamento {
|
| 517 |
+
resposta: melhor.0,
|
| 518 |
+
candidatos: candidatos_final,
|
| 519 |
+
pesos: melhor.2,
|
| 520 |
+
confianca: conf,
|
| 521 |
+
iteracoes,
|
| 522 |
+
trajetoria,
|
| 523 |
+
telemetria,
|
| 524 |
+
});
|
| 525 |
+
}
|
| 526 |
+
if iteracoes >= self.orcamento {
|
| 527 |
+
trajetoria.push(EventoCiclo::Resposta { confianca: melhor.1, iteracoes });
|
| 528 |
+
telemetria.insert("iteracoes".into(), iteracoes as f64);
|
| 529 |
+
telemetria.insert("confianca_final".into(), melhor.1);
|
| 530 |
+
telemetria.insert("temperatura_final".into(), temperatura);
|
| 531 |
+
telemetria.insert("orcamento_esgotado".into(), 1.0);
|
| 532 |
+
telemetria.insert("verificador".into(), 1.0);
|
| 533 |
+
return Ok(ResultadoPensamento {
|
| 534 |
+
resposta: melhor.0,
|
| 535 |
+
candidatos: candidatos_final,
|
| 536 |
+
pesos: melhor.2,
|
| 537 |
+
confianca: melhor.1,
|
| 538 |
+
iteracoes,
|
| 539 |
+
trajetoria,
|
| 540 |
+
telemetria,
|
| 541 |
+
});
|
| 542 |
+
}
|
| 543 |
+
temperatura = (temperatura * 1.6).min(2.0);
|
| 544 |
+
trajetoria.push(EventoCiclo::RePlanejamento {
|
| 545 |
+
motivo: format!("conf NCM {conf:.3} < limiar {}", self.limiar_conf),
|
| 546 |
+
});
|
| 547 |
+
}
|
| 548 |
+
}
|
| 549 |
+
}
|
laboratorio/arquivo_split_v100/pensamento/quebra_cabeca.rs
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! `pensamento::quebra_cabeca` — extraído do monólito na v0.10.0
|
| 2 |
+
//! (divisão SRP, crítica Qwen3.8 lote 3 nº 1; r-35 §2).
|
| 3 |
+
|
| 4 |
+
use super::*;
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
// ---------------------------------------------------------------------------
|
| 8 |
+
// QUEBRA-CABEÇA pós-treinamento (v0.7.0 — inovação com o conhecimento
|
| 9 |
+
// treinado; requisito do usuário; provas Q-1..Q-6 em r-31)
|
| 10 |
+
// ---------------------------------------------------------------------------
|
| 11 |
+
|
| 12 |
+
/// Configuração do quebra-cabeça (r-28 §4.3).
|
| 13 |
+
#[derive(Clone, Copy, Debug)]
|
| 14 |
+
pub struct ConfigQuebraCabeca {
|
| 15 |
+
/// K peças em que o conhecimento é quebrado.
|
| 16 |
+
pub n_pecas: usize,
|
| 17 |
+
/// orçamento B de rodadas (terminação Q-4).
|
| 18 |
+
pub n_rodadas_max: usize,
|
| 19 |
+
/// limiar de validade (mesmo τ_c calibrado do verificador — Q-2).
|
| 20 |
+
pub tau_c: f64,
|
| 21 |
+
/// teto do ajuste por componente na árvore (regulação).
|
| 22 |
+
pub delta_max: f64,
|
| 23 |
+
/// remonta as peças com mistura ORTOGONAL por peça (rotação/ortogonalidade).
|
| 24 |
+
pub rotacao_ortogonal: bool,
|
| 25 |
+
/// para a execução após este nº de rodadas consecutivas sem aceite.
|
| 26 |
+
pub paciencia: usize,
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
impl Default for ConfigQuebraCabeca {
|
| 30 |
+
fn default() -> Self {
|
| 31 |
+
ConfigQuebraCabeca {
|
| 32 |
+
n_pecas: 4,
|
| 33 |
+
n_rodadas_max: 12,
|
| 34 |
+
tau_c: 0.55,
|
| 35 |
+
delta_max: 0.05,
|
| 36 |
+
rotacao_ortogonal: true,
|
| 37 |
+
paciencia: 5,
|
| 38 |
+
}
|
| 39 |
+
}
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
impl ConfigQuebraCabeca {
|
| 43 |
+
pub fn novo(n_pecas: usize, n_rodadas: usize, tau_c: f64) -> Self {
|
| 44 |
+
ConfigQuebraCabeca {
|
| 45 |
+
n_pecas,
|
| 46 |
+
n_rodadas_max: n_rodadas,
|
| 47 |
+
tau_c,
|
| 48 |
+
delta_max: 0.05,
|
| 49 |
+
rotacao_ortogonal: true,
|
| 50 |
+
paciencia: (n_rodadas / 2).max(2),
|
| 51 |
+
}
|
| 52 |
+
}
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
/// Uma rodada do quebra-cabeça.
|
| 56 |
+
#[derive(Debug, Clone)]
|
| 57 |
+
pub struct RodadaQuebraCabeca {
|
| 58 |
+
pub rodada: usize,
|
| 59 |
+
/// permutação das peças aplicada na remontagem (reordenação).
|
| 60 |
+
pub permutacao_pecas: Vec<usize>,
|
| 61 |
+
/// confiança NCM do candidato remontado (reavaliação).
|
| 62 |
+
pub confianca: f64,
|
| 63 |
+
/// conf ≥ τ_c ⇒ VÁLIDO (ajusta a árvore); senão PUNIDO (descarta).
|
| 64 |
+
pub aceito: bool,
|
| 65 |
+
/// delta aplicado na árvore (0 quando descartado).
|
| 66 |
+
pub delta_aplicado: f64,
|
| 67 |
+
/// rotações ortogonais usadas (quando ativas) — por peça.
|
| 68 |
+
pub usou_rotacao: bool,
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
/// Resultado consolidado do quebra-cabeça.
|
| 72 |
+
#[derive(Debug, Clone)]
|
| 73 |
+
pub struct ResultadoQuebraCabeca {
|
| 74 |
+
pub rodadas: Vec<RodadaQuebraCabeca>,
|
| 75 |
+
pub aceitos: usize,
|
| 76 |
+
pub rejeitados: usize,
|
| 77 |
+
pub confianca_base: f64,
|
| 78 |
+
pub confianca_melhor: f64,
|
| 79 |
+
pub telemetria: HashMap<String, f64>,
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
/// **Quebra-cabeça de inovação pós-treinamento** (r-28 §4.3):
|
| 83 |
+
/// 1. quebra o conhecimento treinado `conceitos` (m, d) em K peças por
|
| 84 |
+
/// permutação aleatória das linhas (Fisher–Yates com RNG determinístico);
|
| 85 |
+
/// 2. remonta as peças em nova ordem (e com mistura ortogonal por peça
|
| 86 |
+
/// quando `rotacao_ortogonal`) — "descobrir novas possibilidades";
|
| 87 |
+
/// 3. reavalia cada remontagem pelo verificador NCM (calibrado — V-2);
|
| 88 |
+
/// VÁLIDO (conf ≥ τ_c) ⇒ ajuste regulado na árvore de pesos indexada
|
| 89 |
+
/// (nó "pensamento", crédito fundo-topo); PUNIDO ⇒ descarta e o incremento
|
| 90 |
+
/// de punição sobe no nó (alimenta o gate do FNH — integração v0.7.0);
|
| 91 |
+
/// 4. repete até o orçamento B ou a paciência esgotar (Q-4).
|
| 92 |
+
///
|
| 93 |
+
/// **Provas (r-31):** Q-1 cobertura (permutações uniformes ⇒ S_K no suporte;
|
| 94 |
+
/// rotações varrem O(d)); Q-2 soundness herdada (mesmo limiar calibrado do
|
| 95 |
+
/// verificador — P(aceite inválido) ≤ 1−τ_c+ECE); Q-3 potencial monotônico
|
| 96 |
+
/// (Φ_r = Σ conf dos aceitos é não-decrescente; rejeições não tocam Φ);
|
| 97 |
+
/// Q-4 terminação (B finito, rodadas O(m·d)); Q-5 invariantes da árvore
|
| 98 |
+
/// preservadas (ajustes só tocam métricas, nunca a estrutura — T-A1 intacto;
|
| 99 |
+
/// agregação pós-ajuste mantém T-A2); Q-6 causalidade (permutação e confiança
|
| 100 |
+
/// medidas antes do ajuste — filtração F_r).
|
| 101 |
+
pub fn quebra_cabeca_inovar(
|
| 102 |
+
conceitos: &Tensor,
|
| 103 |
+
verificador: &crate::verificador::VerificadorNcm,
|
| 104 |
+
logits_fn: &dyn Fn(&Tensor) -> Result<Tensor>,
|
| 105 |
+
arvore: &mut crate::arvore_pesos::ArvorePesos,
|
| 106 |
+
cfg: &ConfigQuebraCabeca,
|
| 107 |
+
rng: &mut RngDeterministico,
|
| 108 |
+
) -> Result<ResultadoQuebraCabeca> {
|
| 109 |
+
let dev = conceitos.device().clone();
|
| 110 |
+
let (m, d) = (conceitos.dims()[0], conceitos.dims()[1]);
|
| 111 |
+
let k = cfg.n_pecas.clamp(1, m);
|
| 112 |
+
let no_pens = arvore.no("pensamento").unwrap_or(0);
|
| 113 |
+
|
| 114 |
+
// linha de base: confiança do conhecimento original (agregado médio)
|
| 115 |
+
let base_agg = conceitos.mean(0)?;
|
| 116 |
+
let conf_base = {
|
| 117 |
+
let lg = logits_fn(&base_agg)?;
|
| 118 |
+
verificador.confianca_1d(&lg)?
|
| 119 |
+
};
|
| 120 |
+
|
| 121 |
+
let mut rodadas = Vec::new();
|
| 122 |
+
let mut aceitos = 0usize;
|
| 123 |
+
let mut rejeitados = 0usize;
|
| 124 |
+
let mut conf_melhor = conf_base;
|
| 125 |
+
let mut sem_aceite = 0usize;
|
| 126 |
+
|
| 127 |
+
for r in 1..=cfg.n_rodadas_max {
|
| 128 |
+
if sem_aceite >= cfg.paciencia {
|
| 129 |
+
break;
|
| 130 |
+
}
|
| 131 |
+
// (1) QUEBRA: permutação de linhas Fisher–Yates (Q-6: amostrada ANTES)
|
| 132 |
+
let mut perm: Vec<usize> = (0..m).collect();
|
| 133 |
+
for i in (1..m).rev() {
|
| 134 |
+
let j = rng.inteiro(i + 1);
|
| 135 |
+
perm.swap(i, j);
|
| 136 |
+
}
|
| 137 |
+
// fatia em K peças contíguas (tamanhos quase iguais)
|
| 138 |
+
let tamanho = (m + k - 1) / k;
|
| 139 |
+
let mut pecas = Vec::with_capacity(k);
|
| 140 |
+
let mut ini = 0usize;
|
| 141 |
+
while ini < m {
|
| 142 |
+
let fim = (ini + tamanho).min(m);
|
| 143 |
+
let idx: Vec<u32> = perm[ini..fim].iter().map(|&x| x as u32).collect();
|
| 144 |
+
let pedaco = conceitos.index_select(&Tensor::from_vec(idx, (fim - ini,), &dev)?, 0)?;
|
| 145 |
+
pecas.push(pedaco);
|
| 146 |
+
ini = fim;
|
| 147 |
+
}
|
| 148 |
+
// (2) REMONTA: nova ordem aleatória das peças (permutação de peças)
|
| 149 |
+
let mut perm_pecas: Vec<usize> = (0..pecas.len()).collect();
|
| 150 |
+
for i in (1..pecas.len()).rev() {
|
| 151 |
+
let j = rng.inteiro(i + 1);
|
| 152 |
+
perm_pecas.swap(i, j);
|
| 153 |
+
}
|
| 154 |
+
let mut remontada = Vec::with_capacity(pecas.len());
|
| 155 |
+
for &pi in &perm_pecas {
|
| 156 |
+
let mut pedaco = pecas[pi].clone();
|
| 157 |
+
if cfg.rotacao_ortogonal && d >= 2 {
|
| 158 |
+
// mistura ortogonal da peça: Q ∈ O(d) via polar de gaussiana
|
| 159 |
+
// do RNG determinístico (preserva normas — ‖xQ‖_F = ‖x‖_F)
|
| 160 |
+
let q = q_ortogonal_deterministica(d, rng, &dev)?;
|
| 161 |
+
pedaco = pedaco.matmul(&q)?;
|
| 162 |
+
}
|
| 163 |
+
remontada.push(pedaco);
|
| 164 |
+
}
|
| 165 |
+
let candidata = Tensor::cat(&remontada, 0)?; // (m, d) remontado
|
| 166 |
+
// (3) REAVALIAÇÃO pelo verificador NCM (Q-2: mesmo limiar calibrado)
|
| 167 |
+
let agg = candidata.mean(0)?;
|
| 168 |
+
let lg = logits_fn(&agg)?;
|
| 169 |
+
let conf = verificador.confianca_1d(&lg)?;
|
| 170 |
+
let aceito = conf >= cfg.tau_c;
|
| 171 |
+
let delta = if aceito {
|
| 172 |
+
// VÁLIDO: ajusta a árvore bidirecional (indexada, com teto)
|
| 173 |
+
let escalado = (conf - cfg.tau_c).min(cfg.delta_max);
|
| 174 |
+
arvore.aplicar_ajuste_indexado(no_pens, "confianca", escalado, cfg.delta_max)
|
| 175 |
+
} else {
|
| 176 |
+
// PUNIDO: descarta; a punição sobe no nó (sinal para o gate FNH)
|
| 177 |
+
rejeitados += 1;
|
| 178 |
+
sem_aceite += 1;
|
| 179 |
+
arvore.aplicar_ajuste_indexado(no_pens, "punicao", cfg.delta_max * 0.5, cfg.delta_max);
|
| 180 |
+
0.0
|
| 181 |
+
};
|
| 182 |
+
if aceito {
|
| 183 |
+
aceitos += 1;
|
| 184 |
+
sem_aceite = 0;
|
| 185 |
+
conf_melhor = conf_melhor.max(conf);
|
| 186 |
+
}
|
| 187 |
+
rodadas.push(RodadaQuebraCabeca {
|
| 188 |
+
rodada: r,
|
| 189 |
+
permutacao_pecas: perm_pecas,
|
| 190 |
+
confianca: conf,
|
| 191 |
+
aceito,
|
| 192 |
+
delta_aplicado: delta,
|
| 193 |
+
usou_rotacao: cfg.rotacao_ortogonal,
|
| 194 |
+
});
|
| 195 |
+
}
|
| 196 |
+
// crédito fundo-topo após todas as rodadas (T-A2)
|
| 197 |
+
arvore.agregar_fundo_topo("confianca");
|
| 198 |
+
arvore.agregar_fundo_topo("punicao");
|
| 199 |
+
|
| 200 |
+
let n_rod = rodadas.len();
|
| 201 |
+
let mut telemetria = HashMap::new();
|
| 202 |
+
telemetria.insert("rodadas".into(), n_rod as f64);
|
| 203 |
+
telemetria.insert("aceitos".into(), aceitos as f64);
|
| 204 |
+
telemetria.insert("rejeitados".into(), rejeitados as f64);
|
| 205 |
+
telemetria.insert("confianca_base".into(), conf_base);
|
| 206 |
+
telemetria.insert("confianca_melhor".into(), conf_melhor);
|
| 207 |
+
telemetria.insert(
|
| 208 |
+
"taxa_aceitacao".into(),
|
| 209 |
+
if n_rod > 0 { aceitos as f64 / n_rod as f64 } else { 0.0 },
|
| 210 |
+
);
|
| 211 |
+
telemetria.insert("rotacao_ativa".into(), if cfg.rotacao_ortogonal { 1.0 } else { 0.0 });
|
| 212 |
+
Ok(ResultadoQuebraCabeca {
|
| 213 |
+
rodadas,
|
| 214 |
+
aceitos,
|
| 215 |
+
rejeitados,
|
| 216 |
+
confianca_base: conf_base,
|
| 217 |
+
confianca_melhor: conf_melhor,
|
| 218 |
+
telemetria,
|
| 219 |
+
})
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
/// Q ∈ O(d) determinística: gaussiana do RNG próprio → retração polar.
|
| 223 |
+
/// Ortogonal EXATA (δ_ort ≤ 1e-6) e reprodutível (mesma semente ⇒ mesmo Q).
|
| 224 |
+
pub fn q_ortogonal_deterministica(
|
| 225 |
+
d: usize,
|
| 226 |
+
rng: &mut RngDeterministico,
|
| 227 |
+
dev: &Device,
|
| 228 |
+
) -> Result<Tensor> {
|
| 229 |
+
let n = d * d;
|
| 230 |
+
let v: Vec<f32> = (0..n).map(|_| rng.normal_padrao() as f32).collect();
|
| 231 |
+
let g = Tensor::from_vec(v, (d, d), dev)?;
|
| 232 |
+
crate::stiefel::retrair_polar_frobenius(&g, 90)
|
| 233 |
+
}
|
laboratorio/arquivo_split_v100/pensamento/testes.rs
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! `pensamento::testes` — extraído do monólito na v0.10.0
|
| 2 |
+
//! (divisão SRP, crítica Qwen3.8 lote 3 nº 1; r-35 §2).
|
| 3 |
+
|
| 4 |
+
use super::*;
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
#[cfg(test)]
|
| 9 |
+
mod testes {
|
| 10 |
+
use super::*;
|
| 11 |
+
|
| 12 |
+
#[test]
|
| 13 |
+
fn teste_confianca_extremos() {
|
| 14 |
+
// T-P1: Dirac ⇒ conf = 1; uniforme ⇒ conf = 0
|
| 15 |
+
let dev = Device::Cpu;
|
| 16 |
+
let dirac = Tensor::from_vec(vec![100.0f32, 0.0, 0.0, 0.0], (1, 4), &dev).unwrap();
|
| 17 |
+
let uniforme = Tensor::from_vec(vec![0.0f32; 4], (1, 4), &dev).unwrap();
|
| 18 |
+
let c1 = confianca_de_logits(&dirac).unwrap();
|
| 19 |
+
let c0 = confianca_de_logits(&uniforme).unwrap();
|
| 20 |
+
assert!(c1 > 0.999, "conf dirac = {c1}");
|
| 21 |
+
assert!(c0 < 0.001, "conf uniforme = {c0}");
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
#[test]
|
| 25 |
+
fn teste_tp3_projetar_ridge_minimiza() {
|
| 26 |
+
// T-P3: r* da projeção ridge tem resíduo ≤ qualquer perturbação
|
| 27 |
+
let dev = Device::Cpu;
|
| 28 |
+
let w = Tensor::randn(0f32, 1.0, (8, 3), &dev).unwrap();
|
| 29 |
+
let r_alvo = Tensor::randn(0f32, 1.0, (8, 5), &dev).unwrap();
|
| 30 |
+
let r = projetar_ridge(&w, &r_alvo, 1e-6).unwrap();
|
| 31 |
+
let residuo = |rr: &Tensor| {
|
| 32 |
+
let d = (w.matmul(rr).unwrap() - &r_alvo).unwrap();
|
| 33 |
+
d.sqr().unwrap().sum_all().unwrap().to_scalar::<f32>().unwrap() as f64
|
| 34 |
+
};
|
| 35 |
+
let f0 = residuo(&r);
|
| 36 |
+
let mut rng = RngDeterministico::novo(1);
|
| 37 |
+
for _ in 0..30 {
|
| 38 |
+
let pert: Vec<f32> = (0..15).map(|_| rng.normal(0.0, 0.1) as f32).collect();
|
| 39 |
+
let rp = (Tensor::from_vec(pert, (3, 5), &dev).unwrap() + &r).unwrap();
|
| 40 |
+
let fp = residuo(&rp);
|
| 41 |
+
assert!(f0 <= fp + 1e-6, "residuo r* = {f0} > perturbado {fp}");
|
| 42 |
+
}
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
#[test]
|
| 46 |
+
fn teste_tp4_terminacao_e_orcamento() {
|
| 47 |
+
// o ciclo d SEMPRE termina em ≤ orçamento iterações (potencial
|
| 48 |
+
// Φ = B − k); com verificador impossível, termina com
|
| 49 |
+
// orcamento_esgotado = 1.
|
| 50 |
+
let dev = Device::Cpu;
|
| 51 |
+
let mut motor = MotorPensamento::novo(6, 4, 3, 0.99, 5, &dev).unwrap();
|
| 52 |
+
let cond = Tensor::randn(0f32, 1.0, (6,), &dev).unwrap();
|
| 53 |
+
let mut rng = RngDeterministico::novo(2);
|
| 54 |
+
let res = motor
|
| 55 |
+
.raciocinar(&cond, &|_| 0.0, &mut rng) // verificador sempre 0
|
| 56 |
+
.unwrap();
|
| 57 |
+
assert!(res.iteracoes <= 5, "iterações = {} > orçamento", res.iteracoes);
|
| 58 |
+
assert_eq!(res.telemetria.get("orcamento_esgotado"), Some(&1.0));
|
| 59 |
+
assert!(res.resposta.is_some(), "melhor candidato ainda é retornado");
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
#[test]
|
| 63 |
+
fn teste_tp5_neutralidade_no_nascimento() {
|
| 64 |
+
// gate = 0 ⇒ saída da atenção integrada é BIT-A-BIT a da base
|
| 65 |
+
let dev = Device::Cpu;
|
| 66 |
+
let motor = MotorPensamento::novo(8, 8, 3, 0.5, 3, &dev).unwrap();
|
| 67 |
+
let q = Tensor::randn(0f32, 1.0, (1, 4, 8), &dev).unwrap();
|
| 68 |
+
let k = Tensor::randn(0f32, 1.0, (1, 6, 8), &dev).unwrap();
|
| 69 |
+
let v = Tensor::randn(0f32, 1.0, (1, 6, 8), &dev).unwrap();
|
| 70 |
+
let cand = Tensor::randn(0f32, 1.0, (3, 8), &dev).unwrap();
|
| 71 |
+
let y_int = motor.atencao_integrada(&q, &k, &v, &cand).unwrap();
|
| 72 |
+
// atenção base pura
|
| 73 |
+
let scores = (q.matmul(&k.transpose(1, 2).unwrap()).unwrap() / (8f64).sqrt()).unwrap();
|
| 74 |
+
let attn = candle_nn::ops::softmax(&scores, candle_core::D::Minus1).unwrap();
|
| 75 |
+
let y_base = attn.matmul(&v).unwrap();
|
| 76 |
+
let dif = (&y_int - &y_base).unwrap().abs().unwrap().max_all().unwrap().to_scalar::<f32>().unwrap();
|
| 77 |
+
assert!(dif == 0.0, "gate=0 deveria dar bit-a-bit, dif = {dif}");
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
#[test]
|
| 81 |
+
fn teste_treino_cooperativo_e_agregacao() {
|
| 82 |
+
// item a: as tentativas + combinador APRENDEM a função alvo; a
|
| 83 |
+
// agregação converge para o alvo melhor que uma tentativa isolada
|
| 84 |
+
// no pior caso (verificação numérica honesta em escala pequena).
|
| 85 |
+
let dev = Device::Cpu;
|
| 86 |
+
let mut motor = MotorPensamento::novo(6, 4, 3, 0.5, 3, &dev).unwrap();
|
| 87 |
+
let vars = motor.vars();
|
| 88 |
+
let mut otim = crate::treino::AdamWManual::novo(vars, 5e-3, 0.0);
|
| 89 |
+
let mut rng = RngDeterministico::novo(4);
|
| 90 |
+
// alvo: função não-linear determinística de cond
|
| 91 |
+
let dados: Vec<(Vec<f32>, Vec<f32>)> = (0..256)
|
| 92 |
+
.map(|_| {
|
| 93 |
+
let c: Vec<f32> = (0..6).map(|_| rng.normal(0.0, 1.0) as f32).collect();
|
| 94 |
+
let a: Vec<f32> = (0..4)
|
| 95 |
+
.map(|j| {
|
| 96 |
+
(c[j % 6] * 0.5 + (c[(j + 1) % 6] * c[(j + 2) % 6]) * 0.3 + 0.1) as f32
|
| 97 |
+
})
|
| 98 |
+
.collect();
|
| 99 |
+
(c, a)
|
| 100 |
+
})
|
| 101 |
+
.collect();
|
| 102 |
+
let cs: Vec<f32> = dados.iter().flat_map(|(c, _)| c.clone()).collect();
|
| 103 |
+
let as_: Vec<f32> = dados.iter().flat_map(|(_, a)| a.clone()).collect();
|
| 104 |
+
let cond = Tensor::from_vec(cs, (256, 6), &dev).unwrap();
|
| 105 |
+
let alvo = Tensor::from_vec(as_, (256, 4), &dev).unwrap();
|
| 106 |
+
let mut perda0 = f64::NAN;
|
| 107 |
+
let mut perda1 = f64::NAN;
|
| 108 |
+
for passo in 0..200 {
|
| 109 |
+
let perda = motor.perda_treino(&cond, &alvo).unwrap();
|
| 110 |
+
if passo == 0 {
|
| 111 |
+
perda0 = perda.to_scalar::<f32>().unwrap() as f64;
|
| 112 |
+
}
|
| 113 |
+
perda1 = perda.to_scalar::<f32>().unwrap() as f64;
|
| 114 |
+
otim.passo(crate::treino::grads_achatados(&perda, &motor.vars()).unwrap());
|
| 115 |
+
}
|
| 116 |
+
assert!(perda1 < perda0 * 0.5, "treino cooperativo: {perda0} → {perda1}");
|
| 117 |
+
// agregação: verificador = negativo do erro quadrático médio
|
| 118 |
+
let mut rng2 = RngDeterministico::novo(9);
|
| 119 |
+
let cand = motor.candidatos(&cond.get(0).unwrap(), 0.0, &mut rng2).unwrap();
|
| 120 |
+
let (resp, pesos) = motor.agregar(&cand).unwrap();
|
| 121 |
+
assert_eq!(resp.dims().to_vec(), vec![1, 4]);
|
| 122 |
+
let soma: f64 = pesos.iter().sum();
|
| 123 |
+
assert!((soma - 1.0).abs() < 1e-9, "pesos somam {soma}");
|
| 124 |
+
assert!(pesos.iter().all(|&p| p >= 0.0));
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
#[test]
|
| 128 |
+
fn teste_tp2_auto_consistencia_numérica() {
|
| 129 |
+
// T-P2 numérico: N tentativas com viés comum pequeno; a média
|
| 130 |
+
// agregada tem erro menor que a tentativa mediana (redução de
|
| 131 |
+
// variância) na maioria das repetições.
|
| 132 |
+
let dev = Device::Cpu;
|
| 133 |
+
let mut rng = RngDeterministico::novo(6);
|
| 134 |
+
let alvo = [1.0f64, 2.0, -1.0, 0.5];
|
| 135 |
+
let mut venceu = 0;
|
| 136 |
+
let reps = 200;
|
| 137 |
+
for _ in 0..reps {
|
| 138 |
+
let n = 7;
|
| 139 |
+
let erros: Vec<f64> = (0..n)
|
| 140 |
+
.map(|_| {
|
| 141 |
+
alvo
|
| 142 |
+
.iter()
|
| 143 |
+
.map(|&a| {
|
| 144 |
+
let ruido = rng.normal(0.0, 1.0);
|
| 145 |
+
(a + ruido - a).abs()
|
| 146 |
+
})
|
| 147 |
+
.sum::<f64>()
|
| 148 |
+
})
|
| 149 |
+
.collect();
|
| 150 |
+
let media: Vec<f64> = (0..4)
|
| 151 |
+
.map(|j| {
|
| 152 |
+
(0..n).map(|i| alvo[j] + rng.normal(0.0, 1.0)).sum::<f64>() / n as f64
|
| 153 |
+
})
|
| 154 |
+
.collect();
|
| 155 |
+
let erro_media: f64 = media.iter().zip(alvo.iter()).map(|(m, a)| (m - a).abs()).sum();
|
| 156 |
+
let mut ordenado = erros.clone();
|
| 157 |
+
ordenado.sort_by(|a, b| a.partial_cmp(b).unwrap());
|
| 158 |
+
let mediana = ordenado[n / 2];
|
| 159 |
+
if erro_media <= mediana {
|
| 160 |
+
venceu += 1;
|
| 161 |
+
}
|
| 162 |
+
}
|
| 163 |
+
// a média vence a mediana na grande maioria dos casos (E[erro da
|
| 164 |
+
// média] = σ/√n < σ = E[erro de UMA tentativa])
|
| 165 |
+
assert!(
|
| 166 |
+
venceu as f64 / reps as f64 >= 0.6,
|
| 167 |
+
"auto-consistência venceu só {}/{}",
|
| 168 |
+
venceu,
|
| 169 |
+
reps
|
| 170 |
+
);
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
// ------------------------------------------------------------------
|
| 174 |
+
// Quebra-cabeça (v0.7.0) — gates Q-1..Q-6 (provas r-31)
|
| 175 |
+
// ------------------------------------------------------------------
|
| 176 |
+
|
| 177 |
+
fn cenario_quebra_cabeca()
|
| 178 |
+
-> (Tensor, crate::verificador::VerificadorNcm, crate::arvore_pesos::ArvorePesos) {
|
| 179 |
+
let dev = Device::Cpu;
|
| 180 |
+
let mut rng = RngDeterministico::novo(777);
|
| 181 |
+
// "conhecimento treinado": 12 conceitos (d=8) com estrutura
|
| 182 |
+
let m = 12usize;
|
| 183 |
+
let d = 8usize;
|
| 184 |
+
let v: Vec<f32> = (0..m * d).map(|i| rng.normal_padrao() as f32).collect();
|
| 185 |
+
let conceitos = Tensor::from_vec(v, (m, d), &dev).unwrap();
|
| 186 |
+
// verificador calibrado com um "verificador" sintético: logits
|
| 187 |
+
// favoráveis ao agregado médio dos conceitos
|
| 188 |
+
let mut verif = crate::verificador::VerificadorNcm::novo();
|
| 189 |
+
let _ = &mut verif;
|
| 190 |
+
let mut arvore = crate::arvore_pesos::ArvorePesos::nova(&std::collections::HashMap::new());
|
| 191 |
+
let _ = &mut arvore;
|
| 192 |
+
(conceitos, verif, arvore)
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
fn logits_fn_exemplo(x: &Tensor) -> Result<Tensor> {
|
| 196 |
+
// logits determinísticos correlacionados com a norma do agregado —
|
| 197 |
+
// quanto mais "concentrado" o agregado, maior a confiança
|
| 198 |
+
let norma = x.sqr()?.sum_all()?.to_scalar::<f32>()? as f64;
|
| 199 |
+
let base = (norma * 2.0).min(8.0);
|
| 200 |
+
let v: Vec<f32> = vec![base as f32, 0.5, 0.2, 0.1];
|
| 201 |
+
Ok(Tensor::from_vec(v, (4,), x.device())?)
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
/// Q-2/Q-3: todo ACEITO tem conf ≥ τ_c; rejeições não aplicam delta;
|
| 205 |
+
/// potencial monotônico (confiança acumulada só cresce nos aceites).
|
| 206 |
+
#[test]
|
| 207 |
+
fn quebra_cabeca_soundness_e_potencial() -> Result<()> {
|
| 208 |
+
let (conceitos, verif, mut arvore) = cenario_quebra_cabeca();
|
| 209 |
+
let cfg = ConfigQuebraCabeca::novo(4, 10, 0.55);
|
| 210 |
+
let mut rng = RngDeterministico::novo(4242);
|
| 211 |
+
let r = quebra_cabeca_inovar(&conceitos, &verif, &logits_fn_exemplo, &mut arvore, &cfg, &mut rng)?;
|
| 212 |
+
for rod in &r.rodadas {
|
| 213 |
+
if rod.aceito {
|
| 214 |
+
assert!(
|
| 215 |
+
rod.confianca >= cfg.tau_c,
|
| 216 |
+
"Q-2: aceito com conf {} < τ_c {}",
|
| 217 |
+
rod.confianca,
|
| 218 |
+
cfg.tau_c
|
| 219 |
+
);
|
| 220 |
+
assert!(rod.delta_aplicado > 0.0, "aceite aplica delta > 0");
|
| 221 |
+
} else {
|
| 222 |
+
assert_eq!(rod.delta_aplicado, 0.0, "Q-3: rejeitado não aplica delta");
|
| 223 |
+
}
|
| 224 |
+
}
|
| 225 |
+
// potencial monotônico: Σ conf dos aceitos ≤ Σ max(conf, τ_c) das rodadas
|
| 226 |
+
let pot: f64 = r.rodadas.iter().filter(|x| x.aceito).map(|x| x.confianca).sum();
|
| 227 |
+
assert!(pot >= 0.0);
|
| 228 |
+
// Q-5: invariantes da árvore preservadas
|
| 229 |
+
arvore.invariantes_ok().expect("Q-5: invariantes T-A1 preservadas");
|
| 230 |
+
Ok(())
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
/// Q-4: terminação — nunca excede n_rodadas_max nem roda sem parar.
|
| 234 |
+
#[test]
|
| 235 |
+
fn quebra_cabeca_termina() -> Result<()> {
|
| 236 |
+
let (conceitos, verif, mut arvore) = cenario_quebra_cabeca();
|
| 237 |
+
let cfg = ConfigQuebraCabeca::novo(3, 6, 0.99); // τ inalcançável
|
| 238 |
+
let mut rng = RngDeterministico::novo(1);
|
| 239 |
+
let r = quebra_cabeca_inovar(&conceitos, &verif, &logits_fn_exemplo, &mut arvore, &cfg, &mut rng)?;
|
| 240 |
+
assert!(r.rodadas.len() <= 6, "Q-4: orçamento respeitado");
|
| 241 |
+
assert_eq!(r.aceitos, 0, "τ inalcançável ⇒ nenhum aceite");
|
| 242 |
+
assert!(r.rejeitados > 0);
|
| 243 |
+
Ok(())
|
| 244 |
+
}
|
| 245 |
+
|
| 246 |
+
/// Q-4b: rejeições incrementam a PUNIÇÃO no nó pensamento (sinal FNH).
|
| 247 |
+
#[test]
|
| 248 |
+
fn quebra_cabeca_punicao_sobe() -> Result<()> {
|
| 249 |
+
let (conceitos, verif, mut arvore) = cenario_quebra_cabeca();
|
| 250 |
+
let no_pens = arvore.no("pensamento").unwrap();
|
| 251 |
+
let antes = arvore.nos[no_pens].metricas.get("punicao").copied().unwrap_or(0.0);
|
| 252 |
+
let cfg = ConfigQuebraCabeca::novo(3, 5, 0.999);
|
| 253 |
+
let mut rng = RngDeterministico::novo(9);
|
| 254 |
+
let _ = quebra_cabeca_inovar(&conceitos, &verif, &logits_fn_exemplo, &mut arvore, &cfg, &mut rng)?;
|
| 255 |
+
let depois = arvore.nos[no_pens].metricas.get("punicao").copied().unwrap_or(0.0);
|
| 256 |
+
assert!(depois > antes, "punição {depois} deve > {antes} após rejeições");
|
| 257 |
+
Ok(())
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
/// Rotação/ortogonalidade: ‖xQ‖_F = ‖x‖_F (preserva energia) e a
|
| 261 |
+
/// remontagem com rotação difere da sem rotação (exploração real).
|
| 262 |
+
#[test]
|
| 263 |
+
fn quebra_cabeca_rotacao_preserva_norma() -> Result<()> {
|
| 264 |
+
let dev = Device::Cpu;
|
| 265 |
+
let mut rng = RngDeterministico::novo(31);
|
| 266 |
+
let v: Vec<f32> = (0..5 * 6).map(|_| rng.normal_padrao() as f32).collect();
|
| 267 |
+
let x = Tensor::from_vec(v, (5, 6), &dev)?;
|
| 268 |
+
let q = q_ortogonal_deterministica(6, &mut rng, &dev)?;
|
| 269 |
+
let xq = x.matmul(&q)?;
|
| 270 |
+
let nx = x.sqr()?.sum_all()?.to_scalar::<f32>()?;
|
| 271 |
+
let nxq = xq.sqr()?.sum_all()?.to_scalar::<f32>()?;
|
| 272 |
+
assert!(
|
| 273 |
+
(nx - nxq).abs() / nx < 1e-4,
|
| 274 |
+
"‖xQ‖_F = {nxq} deve ≈ ‖x‖_F = {nx} (ortogonalidade)"
|
| 275 |
+
);
|
| 276 |
+
// Q é ortogonal exato
|
| 277 |
+
let delta = crate::stiefel::erro_ortogonalidade(&q)?;
|
| 278 |
+
assert!(delta < 1e-6, "δ_ort(Q) = {delta}");
|
| 279 |
+
// remontagem COM rotação difere da SEM rotação
|
| 280 |
+
let d2 = (&xq - &x)?.abs()?.max_all()?.to_scalar::<f32>()?;
|
| 281 |
+
assert!(d2 > 1e-3, "rotação deve explorar (dif = {d2})");
|
| 282 |
+
Ok(())
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
/// Determinismo: mesma semente ⇒ mesmas rodadas (reprodutibilidade).
|
| 286 |
+
#[test]
|
| 287 |
+
fn quebra_cabeca_deterministico() -> Result<()> {
|
| 288 |
+
let (c1, v1, mut a1) = cenario_quebra_cabeca();
|
| 289 |
+
let (_, v2, mut a2) = cenario_quebra_cabeca();
|
| 290 |
+
let cfg = ConfigQuebraCabeca::novo(4, 8, 0.5);
|
| 291 |
+
let mut r1 = RngDeterministico::novo(123);
|
| 292 |
+
let mut r2 = RngDeterministico::novo(123);
|
| 293 |
+
let q1 = quebra_cabeca_inovar(&c1, &v1, &logits_fn_exemplo, &mut a1, &cfg, &mut r1)?;
|
| 294 |
+
let q2 = quebra_cabeca_inovar(&c1, &v2, &logits_fn_exemplo, &mut a2, &cfg, &mut r2)?;
|
| 295 |
+
assert_eq!(q1.rodadas.len(), q2.rodadas.len());
|
| 296 |
+
for (x, y) in q1.rodadas.iter().zip(q2.rodadas.iter()) {
|
| 297 |
+
assert_eq!(x.permutacao_pecas, y.permutacao_pecas, "mesma semente ⇒ mesma remontagem");
|
| 298 |
+
assert!((x.confianca - y.confianca).abs() < 1e-12);
|
| 299 |
+
assert_eq!(x.aceito, y.aceito);
|
| 300 |
+
}
|
| 301 |
+
Ok(())
|
| 302 |
+
}
|
| 303 |
+
}
|
laboratorio/arquivo_split_v100/python.rs
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
laboratorio/arquivo_split_v100/python/calibracao.rs
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! `python::calibracao` — extraído do monólito na v0.10.0
|
| 2 |
+
//! (divisão SRP, crítica Qwen3.8 lote 3 nº 1; r-35 §2).
|
| 3 |
+
|
| 4 |
+
use super::*;
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
/// **V-1..V-3:** calibra o verificador NCM em logits retidos e devolve
|
| 8 |
+
/// temperatura, ECE antes/depois, NLL antes/depois e o τ_c por quantil DKW.
|
| 9 |
+
#[pyfunction]
|
| 10 |
+
pub(crate) fn calibrar_verificador(
|
| 11 |
+
logits: Vec<Vec<f32>>,
|
| 12 |
+
alvos: Vec<usize>,
|
| 13 |
+
epsilon: f64,
|
| 14 |
+
) -> PyResult<PyObject> {
|
| 15 |
+
Python::with_gil(|py| {
|
| 16 |
+
let dev = candle_core::Device::Cpu;
|
| 17 |
+
let (n, k) = (logits.len(), logits.first().map(|l| l.len()).unwrap_or(1));
|
| 18 |
+
let flat: Vec<f32> = logits.into_iter().flatten().collect();
|
| 19 |
+
let lt = candle_core::Tensor::from_vec(flat, (n, k), &dev)
|
| 20 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 21 |
+
let at = candle_core::Tensor::from_vec(
|
| 22 |
+
alvos.iter().map(|&a| a as u32).collect::<Vec<u32>>(), (n,), &dev)
|
| 23 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 24 |
+
let mut v = verificador::VerificadorNcm::novo();
|
| 25 |
+
let (e_antes, e_depois) = v.ajustar(<, &at)
|
| 26 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 27 |
+
let confs: Vec<f64> = verificador::confianca_por_linha(<)
|
| 28 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?
|
| 29 |
+
.flatten_all().map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?
|
| 30 |
+
.to_vec1::<f32>().map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?
|
| 31 |
+
.iter().map(|x| *x as f64).collect();
|
| 32 |
+
let tau_c = verificador::limiar_por_erro(&confs, epsilon);
|
| 33 |
+
let d_ = serde_json::json!({
|
| 34 |
+
"temperatura": v.temperatura, "ece_antes": e_antes, "ece_depois": e_depois,
|
| 35 |
+
"nll_antes": v.n_ll_antes, "nll_depois": v.n_ll_depois,
|
| 36 |
+
"tau_c": tau_c, "epsilon": epsilon, "n": n,
|
| 37 |
+
});
|
| 38 |
+
Ok(pythonize::pythonize(py, &d_)?.into())
|
| 39 |
+
})
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
/// **Demo do verificador NCM substituindo o oráculo** (r-21 §3.1): treina
|
| 44 |
+
/// um classificador pequeno, calibra T* em dados retidos, mede ECE, τ_c
|
| 45 |
+
/// (DKW) e a soundness empírica `P(erro|aceito) ≤ 1−τ_c+ECE`; compara com
|
| 46 |
+
/// o ORÁCULO (que usa o alvo — impossível em produção) no mesmo problema.
|
| 47 |
+
#[pyfunction]
|
| 48 |
+
pub(crate) fn demo_verificador_ncm(n: usize, k: usize, semente: u64) -> PyResult<PyObject> {
|
| 49 |
+
Python::with_gil(|py| {
|
| 50 |
+
let dev = candle_core::Device::Cpu;
|
| 51 |
+
crate::rng::definir_semente(semente);
|
| 52 |
+
let mut rng = crate::rng::RngDeterministico::novo(semente);
|
| 53 |
+
// dados sintéticos com DRIFT (treino ≠ consulta — força OOD leve)
|
| 54 |
+
let gerar = |rng: &mut crate::rng::RngDeterministico, m: usize, desloc: f64|
|
| 55 |
+
-> (candle_core::Tensor, Vec<usize>) {
|
| 56 |
+
let mut l = Vec::with_capacity(m * k);
|
| 57 |
+
let mut a = Vec::with_capacity(m);
|
| 58 |
+
for _ in 0..m {
|
| 59 |
+
let alvo = rng.inteiro(k);
|
| 60 |
+
a.push(alvo);
|
| 61 |
+
for j in 0..k {
|
| 62 |
+
let base = if j == alvo { 2.5 } else { 0.0 };
|
| 63 |
+
l.push((base + rng.normal(0.0, 1.2) as f32 + desloc as f32) as f32);
|
| 64 |
+
}
|
| 65 |
+
}
|
| 66 |
+
let lt = candle_core::Tensor::from_vec(l, (m, k), &dev).unwrap();
|
| 67 |
+
(lt, a)
|
| 68 |
+
};
|
| 69 |
+
let (lt_tre, alvos_tre) = gerar(&mut rng, n, 0.0);
|
| 70 |
+
let (lt_val, alvos_val) = gerar(&mut rng, n / 2, 0.3);
|
| 71 |
+
// mini-classificador: matriz W (k, k) treinada por softmax-CE
|
| 72 |
+
let w = candle_core::Tensor::randn(0f32, 0.1, (k, k), &dev)
|
| 73 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 74 |
+
let w_var = candle_core::Var::from_tensor(&w)
|
| 75 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 76 |
+
let at_t = candle_core::Tensor::from_vec(
|
| 77 |
+
alvos_tre.iter().map(|&a| a as u32).collect::<Vec<u32>>(), (n,), &dev)
|
| 78 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 79 |
+
let mut otim = treino::AdamWManual::novo(vec![w_var.clone()], 0.05, 0.0);
|
| 80 |
+
for _ in 0..120 {
|
| 81 |
+
let logits = lt_tre.matmul(&w_var.as_tensor().transpose(0, 1).unwrap()).unwrap();
|
| 82 |
+
let ce = candle_nn::loss::cross_entropy(&logits, &at_t).unwrap();
|
| 83 |
+
let g = treino::grads_achatados(&ce, &[w_var.clone()]).unwrap();
|
| 84 |
+
otim.passo(g);
|
| 85 |
+
}
|
| 86 |
+
// logits de validação com o modelo treinado
|
| 87 |
+
let logits_val = lt_val.matmul(&w_var.as_tensor().transpose(0, 1).unwrap()).unwrap();
|
| 88 |
+
let at_v = candle_core::Tensor::from_vec(
|
| 89 |
+
alvos_val.iter().map(|&a| a as u32).collect::<Vec<u32>>(), (n / 2,), &dev)
|
| 90 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 91 |
+
// calibração (V-1) + soundness (V-2) + quantil (V-3)
|
| 92 |
+
let mut v = verificador::VerificadorNcm::novo();
|
| 93 |
+
let (ece_antes, ece_depois) = v.ajustar(&logits_val, &at_v)
|
| 94 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 95 |
+
let confs: Vec<f64> = v.confianca(&logits_val).unwrap()
|
| 96 |
+
.flatten_all().unwrap().to_vec1::<f32>().unwrap().iter().map(|x| *x as f64).collect();
|
| 97 |
+
let corretos: Vec<bool> = logits_val.argmax(candle_core::D::Minus1).unwrap()
|
| 98 |
+
.eq(&at_v).unwrap().to_dtype(candle_core::DType::U32).unwrap()
|
| 99 |
+
.flatten_all().unwrap().to_vec1::<u32>().unwrap()
|
| 100 |
+
.iter().map(|x| *x == 1).collect();
|
| 101 |
+
let tau_c = verificador::limiar_por_erro(&confs, 0.25);
|
| 102 |
+
let (mut erro_aceito, mut n_aceito) = (0usize, 0usize);
|
| 103 |
+
for (c, ok) in confs.iter().zip(corretos.iter()) {
|
| 104 |
+
if *c >= tau_c {
|
| 105 |
+
n_aceito += 1;
|
| 106 |
+
if !ok {
|
| 107 |
+
erro_aceito += 1;
|
| 108 |
+
}
|
| 109 |
+
}
|
| 110 |
+
}
|
| 111 |
+
let p_erro = erro_aceito as f64 / n_aceito.max(1) as f64;
|
| 112 |
+
let cota = (1.0 - tau_c) + ece_depois + 0.06;
|
| 113 |
+
// ORÁCULO no mesmo problema (usa o alvo — só para contraste)
|
| 114 |
+
let acerto_oraculo = corretos.iter().filter(|c| **c).count() as f64 / corretos.len() as f64;
|
| 115 |
+
let d_ = serde_json::json!({
|
| 116 |
+
"versao": verificador::versao(), "n": n, "k": k,
|
| 117 |
+
"temperatura_calibrada": v.temperatura,
|
| 118 |
+
"ece_antes": ece_antes, "ece_depois": ece_depois,
|
| 119 |
+
"nll_antes": v.n_ll_antes, "nll_depois": v.n_ll_depois,
|
| 120 |
+
"tau_c_dkw": tau_c,
|
| 121 |
+
"p_erro_aceito": p_erro, "cota_soundness": cota,
|
| 122 |
+
"soundness_ok": p_erro <= cota,
|
| 123 |
+
"calibracao_melhorou": ece_depois < ece_antes,
|
| 124 |
+
"acerto_oraculo_referencia": acerto_oraculo,
|
| 125 |
+
"verificador_sem_oraculo": true,
|
| 126 |
+
"gates": {
|
| 127 |
+
"gate_v1_calibracao": ece_depois < ece_antes,
|
| 128 |
+
"gate_v2_soundness": p_erro <= cota,
|
| 129 |
+
"gate_v3_tau_positivo": tau_c > 0.0 && tau_c < 1.0,
|
| 130 |
+
},
|
| 131 |
+
});
|
| 132 |
+
Ok(pythonize::pythonize(py, &d_)?.into())
|
| 133 |
+
})
|
| 134 |
+
}
|
laboratorio/arquivo_split_v100/python/demos_qwen.rs
ADDED
|
@@ -0,0 +1,359 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! `python::demos_qwen` — extraído do monólito na v0.10.0
|
| 2 |
+
//! (divisão SRP, crítica Qwen3.8 lote 3 nº 1; r-35 §2).
|
| 3 |
+
|
| 4 |
+
use super::*;
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
/// **v0.8.0 — análise/prova/teste das 4 propostas Qwen3.8** (r-33): mede
|
| 8 |
+
/// custo e exatidão de (1) Newton analítico vs golden-section (verificador),
|
| 9 |
+
/// (2) Cayley vs polar (FNH), (3) árvore pós-ordem iterativa vs recursiva,
|
| 10 |
+
/// (4) MoE vetorizada vs referência (valores + gradiente restaurado — bug
|
| 11 |
+
/// v080-1), e re-executa a ablação JEPA de 3 braços com a correção.
|
| 12 |
+
#[pyfunction]
|
| 13 |
+
#[allow(deprecated)] // mede o bug v080-1 intencionalmente (fwd = oráculo)
|
| 14 |
+
pub(crate) fn demo_qwen_v080(py: Python) -> PyResult<PyObject> {
|
| 15 |
+
use candle_core::{Device, Tensor};
|
| 16 |
+
use std::time::Instant;
|
| 17 |
+
let dev = Device::Cpu;
|
| 18 |
+
|
| 19 |
+
// ---------- (1) Newton vs golden-section (verificador) ----------
|
| 20 |
+
let mut rng = crate::rng::RngDeterministico::novo(808);
|
| 21 |
+
let (n, k) = (1024usize, 32usize);
|
| 22 |
+
let mut lv = Vec::with_capacity(n * k);
|
| 23 |
+
let mut av = Vec::with_capacity(n);
|
| 24 |
+
for _ in 0..n {
|
| 25 |
+
let alvo = rng.inteiro(k) as u32;
|
| 26 |
+
av.push(alvo);
|
| 27 |
+
for j in 0..k {
|
| 28 |
+
let base = if j as u32 == alvo { 3.0 } else { 0.0 };
|
| 29 |
+
lv.push(base + rng.normal(0.0, 1.0) as f32);
|
| 30 |
+
}
|
| 31 |
+
}
|
| 32 |
+
let lt = Tensor::from_vec(lv, (n, k), &dev).unwrap();
|
| 33 |
+
let at = Tensor::from_vec(av, (n,), &dev).unwrap();
|
| 34 |
+
let t0 = Instant::now();
|
| 35 |
+
let (t_g, _, nll_g) = verificador::calibrar_temperatura(<, &at).unwrap();
|
| 36 |
+
let tempo_golden = t0.elapsed().as_secs_f64();
|
| 37 |
+
let t0 = Instant::now();
|
| 38 |
+
let (t_n, _, nll_n, n_aval) =
|
| 39 |
+
verificador::calibrar_temperatura_newton(<, &at, 40).unwrap();
|
| 40 |
+
let tempo_newton = t0.elapsed().as_secs_f64();
|
| 41 |
+
|
| 42 |
+
// ---------- (2) Cayley vs polar (FNH) ----------
|
| 43 |
+
let n_rot = 16usize;
|
| 44 |
+
let r = fnh::RotacaoSkew::nova(n_rot, &dev).unwrap();
|
| 45 |
+
let th: Vec<f32> = (0..n_rot * (n_rot - 1) / 2)
|
| 46 |
+
.map(|i| ((i as f32) * 0.11) % 0.5)
|
| 47 |
+
.collect();
|
| 48 |
+
r.theta
|
| 49 |
+
.set(&Tensor::from_vec(th, (n_rot * (n_rot - 1) / 2,), &dev).unwrap())
|
| 50 |
+
.unwrap();
|
| 51 |
+
let rep = 25usize;
|
| 52 |
+
let t0 = Instant::now();
|
| 53 |
+
let mut delta_polar = 0.0;
|
| 54 |
+
for _ in 0..rep {
|
| 55 |
+
delta_polar = crate::stiefel::erro_ortogonalidade(&r.rotacao_polar().unwrap()).unwrap();
|
| 56 |
+
}
|
| 57 |
+
let tempo_polar = t0.elapsed().as_secs_f64() / rep as f64;
|
| 58 |
+
let t0 = Instant::now();
|
| 59 |
+
let mut delta_cayley = 0.0;
|
| 60 |
+
for _ in 0..rep {
|
| 61 |
+
delta_cayley = crate::stiefel::erro_ortogonalidade(&r.rotacao_cayley().unwrap()).unwrap();
|
| 62 |
+
}
|
| 63 |
+
let tempo_cayley = t0.elapsed().as_secs_f64() / rep as f64;
|
| 64 |
+
|
| 65 |
+
// ---------- (3) árvore iterativa vs recursiva ----------
|
| 66 |
+
let mut arv = arvore_pesos::ArvorePesos::nova(&std::collections::HashMap::new());
|
| 67 |
+
let mut pai = 1usize;
|
| 68 |
+
for i in 0..20_000u32 {
|
| 69 |
+
pai = arv.anexar_filho(pai, &format!("c{i}"), 1);
|
| 70 |
+
}
|
| 71 |
+
arv.nos[pai].metricas.insert("m".into(), 1.0);
|
| 72 |
+
let t0 = Instant::now();
|
| 73 |
+
let total_it = arv.agregar_fundo_topo("m");
|
| 74 |
+
let tempo_arv_it = t0.elapsed().as_secs_f64();
|
| 75 |
+
// repõe TODAS as métricas locais (a agregação sobrescreveu com os
|
| 76 |
+
// agregados) — só a folha tem valor; o resto volta a 0 — e roda a
|
| 77 |
+
// recursiva (profundidade 20k ok na thread principal do Python)
|
| 78 |
+
for no in arv.nos.iter_mut() {
|
| 79 |
+
no.metricas.insert("m".into(), 0.0);
|
| 80 |
+
}
|
| 81 |
+
arv.nos[pai].metricas.insert("m".into(), 1.0);
|
| 82 |
+
let t0 = Instant::now();
|
| 83 |
+
let total_rec = arv.agregar_fundo_topo_rec("m");
|
| 84 |
+
let tempo_arv_rec = t0.elapsed().as_secs_f64();
|
| 85 |
+
|
| 86 |
+
// ---------- (4) MoE vetorizada: valores + gradiente + custo ----------
|
| 87 |
+
let (nm, dm, em) = (256usize, 32usize, 8usize);
|
| 88 |
+
let xv: Vec<f32> = (0..nm * dm).map(|_| rng.normal(0.0, 1.0) as f32).collect();
|
| 89 |
+
let x = Tensor::from_vec(xv, (nm, dm), &dev).unwrap();
|
| 90 |
+
let moe = moe_redirecionavel::MoeRedirecionavel::novo(dm, em, 2, nm, &dev).unwrap();
|
| 91 |
+
let s_ref = moe.fwd(&x, moe_redirecionavel::Papel::Codificador).unwrap();
|
| 92 |
+
let s_vet = moe.forward(&x, moe_redirecionavel::Papel::Codificador).unwrap();
|
| 93 |
+
let dif_moe = (&s_ref.saida - &s_vet.saida)
|
| 94 |
+
.unwrap()
|
| 95 |
+
.abs()
|
| 96 |
+
.unwrap()
|
| 97 |
+
.max_all()
|
| 98 |
+
.unwrap()
|
| 99 |
+
.to_scalar::<f32>()
|
| 100 |
+
.unwrap() as f64;
|
| 101 |
+
let rep_moe = 10usize;
|
| 102 |
+
let t0 = Instant::now();
|
| 103 |
+
for _ in 0..rep_moe {
|
| 104 |
+
let _ = moe.fwd(&x, moe_redirecionavel::Papel::Codificador).unwrap();
|
| 105 |
+
}
|
| 106 |
+
let tempo_moe_ref = t0.elapsed().as_secs_f64() / rep_moe as f64;
|
| 107 |
+
let t0 = Instant::now();
|
| 108 |
+
for _ in 0..rep_moe {
|
| 109 |
+
let _ = moe.forward(&x, moe_redirecionavel::Papel::Codificador).unwrap();
|
| 110 |
+
}
|
| 111 |
+
let tempo_moe_vet = t0.elapsed().as_secs_f64() / rep_moe as f64;
|
| 112 |
+
// normas de gradiente (bug v080-1: fwd = 0; vetorizada > 0)
|
| 113 |
+
let norma = |vet: bool| -> (f64, f64) {
|
| 114 |
+
let s = if vet {
|
| 115 |
+
moe.forward(&x, moe_redirecionavel::Papel::Codificador).unwrap()
|
| 116 |
+
} else {
|
| 117 |
+
moe.fwd(&x, moe_redirecionavel::Papel::Codificador).unwrap()
|
| 118 |
+
};
|
| 119 |
+
let perda = s.saida.sqr().unwrap().sum_all().unwrap();
|
| 120 |
+
let gs = perda.backward().unwrap();
|
| 121 |
+
let mut nr = 0.0;
|
| 122 |
+
for v in moe.roteador.vars() {
|
| 123 |
+
if let Some(g) = gs.get(&v) {
|
| 124 |
+
nr += g.sqr().unwrap().sum_all().unwrap().to_scalar::<f32>().unwrap() as f64;
|
| 125 |
+
}
|
| 126 |
+
}
|
| 127 |
+
let mut ne = 0.0;
|
| 128 |
+
for e in &moe.especialistas {
|
| 129 |
+
for v in e.vars() {
|
| 130 |
+
if let Some(g) = gs.get(&v) {
|
| 131 |
+
ne += g.sqr().unwrap().sum_all().unwrap().to_scalar::<f32>().unwrap() as f64;
|
| 132 |
+
}
|
| 133 |
+
}
|
| 134 |
+
}
|
| 135 |
+
(nr, ne)
|
| 136 |
+
};
|
| 137 |
+
let (grad_ref_r, grad_ref_e) = norma(false);
|
| 138 |
+
let (grad_vet_r, grad_vet_e) = norma(true);
|
| 139 |
+
|
| 140 |
+
// ---------- (5) re-ablação JEPA 3 braços (gradiente restaurado) ----------
|
| 141 |
+
let xv: Vec<f32> = (0..64 * 12).map(|_| rng.normal(0.0, 1.0) as f32).collect();
|
| 142 |
+
let xj = Tensor::from_vec(xv, (64, 12), &dev).unwrap();
|
| 143 |
+
let mut ablac = serde_json::Map::new();
|
| 144 |
+
for modo in ["pequena", "densa", "moe"] {
|
| 145 |
+
let rj = moe_redirecionavel::treinar_jepa_com_moe(&xj, modo, 120, 0.5, 42).unwrap();
|
| 146 |
+
ablac.insert(
|
| 147 |
+
modo.into(),
|
| 148 |
+
serde_json::json!({
|
| 149 |
+
"perda_inicial": rj.perda_pred_inicial,
|
| 150 |
+
"perda_final": rj.perda_pred_final,
|
| 151 |
+
"queda_pct": 100.0 * (1.0 - rj.perda_pred_final / rj.perda_pred_inicial.max(1e-9)),
|
| 152 |
+
}),
|
| 153 |
+
);
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
let d_ = serde_json::json!({
|
| 157 |
+
"versao": "qwen-v080-1.0",
|
| 158 |
+
"newton_vs_golden": {
|
| 159 |
+
"t_golden": t_g, "t_newton": t_n, "dif_t": (t_g - t_n).abs(),
|
| 160 |
+
"nll_golden": nll_g, "nll_newton": nll_n,
|
| 161 |
+
"nll_dif": (nll_g - nll_n).abs(),
|
| 162 |
+
"n_aval_newton": n_aval,
|
| 163 |
+
"tempo_golden_s": tempo_golden, "tempo_newton_s": tempo_newton,
|
| 164 |
+
"speedup": tempo_golden / tempo_newton.max(1e-9),
|
| 165 |
+
"gates": {
|
| 166 |
+
"mesmo_t": (t_g - t_n).abs() < 1e-3,
|
| 167 |
+
"nll_nao_piora": nll_n <= nll_g + 1e-4,
|
| 168 |
+
"menos_avaliacoes": n_aval < 36,
|
| 169 |
+
},
|
| 170 |
+
},
|
| 171 |
+
"cayley_vs_polar": {
|
| 172 |
+
"delta_ort_polar": delta_polar, "delta_ort_cayley": delta_cayley,
|
| 173 |
+
"tempo_polar_s": tempo_polar, "tempo_cayley_s": tempo_cayley,
|
| 174 |
+
"speedup": tempo_polar / tempo_cayley.max(1e-9),
|
| 175 |
+
"gates": {
|
| 176 |
+
"ambos_exatos": delta_polar < 1e-6 && delta_cayley < 1e-6,
|
| 177 |
+
"cayley_mais_rapido": tempo_cayley < tempo_polar,
|
| 178 |
+
},
|
| 179 |
+
},
|
| 180 |
+
"arvore_iter_vs_rec": {
|
| 181 |
+
"n_nos": arv.n_nos(),
|
| 182 |
+
"total_iter": total_it, "total_rec": total_rec,
|
| 183 |
+
"bit_a_bit": total_it.to_bits() == total_rec.to_bits(),
|
| 184 |
+
"tempo_iter_s": tempo_arv_it, "tempo_rec_s": tempo_arv_rec,
|
| 185 |
+
"gates": { "iguais_bit_a_bit": total_it == total_rec },
|
| 186 |
+
},
|
| 187 |
+
"moe_vetorizada": {
|
| 188 |
+
"max_dif_valores": dif_moe,
|
| 189 |
+
"tempo_ref_s": tempo_moe_ref, "tempo_vet_s": tempo_moe_vet,
|
| 190 |
+
"grad_roteador_ref": grad_ref_r, "grad_especialistas_ref": grad_ref_e,
|
| 191 |
+
"grad_roteador_vet": grad_vet_r, "grad_especialistas_vet": grad_vet_e,
|
| 192 |
+
"gates": {
|
| 193 |
+
"valores_iguais": dif_moe < 1e-4,
|
| 194 |
+
"bug_v080_1_confirmado": grad_ref_r == 0.0 && grad_ref_e == 0.0,
|
| 195 |
+
"gradiente_restaurado": grad_vet_r > 0.0 && grad_vet_e > 0.0,
|
| 196 |
+
},
|
| 197 |
+
},
|
| 198 |
+
"ablacao_jepa_3_bracos_v080": ablac,
|
| 199 |
+
});
|
| 200 |
+
Ok(pythonize::pythonize(py, &d_)?.into())
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
/// **v0.9.0 — veredito executável das críticas Qwen3.8 (r-34):** mede os
|
| 205 |
+
/// aprimoramentos contra as referências v0.8.0 (oráculos preservados):
|
| 206 |
+
/// (1) skew O(n²) via index_add — bit-a-bit + tempo + memória analítica;
|
| 207 |
+
/// (2) calibrar vetorial — bit-a-bit em 3 passos EMA + tempo;
|
| 208 |
+
/// (3) forward canônico (ex-fwd_vetorizado) — regressão de valores e
|
| 209 |
+
/// gradiente;
|
| 210 |
+
/// (4) newtypes de domínio — rejeição de fora-de-domínio.
|
| 211 |
+
#[pyfunction]
|
| 212 |
+
pub(crate) fn demo_criticas_v090(py: Python) -> PyResult<PyObject> {
|
| 213 |
+
use candle_core::{Device, Tensor};
|
| 214 |
+
use std::time::Instant;
|
| 215 |
+
let dev = Device::Cpu;
|
| 216 |
+
let mut rng = crate::rng::RngDeterministico::novo(909);
|
| 217 |
+
|
| 218 |
+
// ---------- (1) skew: index_add O(n²) vs matmul de seleção O(n⁴) ----------
|
| 219 |
+
let mut skew_rel = serde_json::Map::new();
|
| 220 |
+
let mut bits_todos = true;
|
| 221 |
+
for &n in &[16usize, 64, 128] {
|
| 222 |
+
let r = fnh::RotacaoSkew::nova(n, &dev).unwrap();
|
| 223 |
+
let m = n * (n - 1) / 2;
|
| 224 |
+
let th: Vec<f32> = (0..m).map(|_| rng.uniforme_intervalo(-0.9, 0.9) as f32).collect();
|
| 225 |
+
r.theta.set(&Tensor::from_vec(th, (m,), &dev).unwrap()).unwrap();
|
| 226 |
+
// bit-a-bit (F-13)
|
| 227 |
+
let an = r.skew().unwrap().flatten_all().unwrap().to_vec1::<f32>().unwrap();
|
| 228 |
+
let ar = r.skew_matmul_referencia().unwrap().flatten_all().unwrap().to_vec1::<f32>().unwrap();
|
| 229 |
+
let bits_iguais = an.iter().zip(ar.iter()).all(|(a, b)| a.to_bits() == b.to_bits());
|
| 230 |
+
bits_todos &= bits_iguais;
|
| 231 |
+
// tempo (referência esquentada 1×; média de 5)
|
| 232 |
+
let _ = r.skew_matmul_referencia().unwrap();
|
| 233 |
+
let t0 = Instant::now();
|
| 234 |
+
for _ in 0..5 { let _ = r.skew_matmul_referencia().unwrap(); }
|
| 235 |
+
let t_ref = t0.elapsed().as_secs_f64() / 5.0;
|
| 236 |
+
let _ = r.skew().unwrap();
|
| 237 |
+
let t0 = Instant::now();
|
| 238 |
+
for _ in 0..5 { let _ = r.skew().unwrap(); }
|
| 239 |
+
let t_novo = t0.elapsed().as_secs_f64() / 5.0;
|
| 240 |
+
let bytes_ref = (m * n * n * 4) as f64;
|
| 241 |
+
let bytes_novo = ((n * n + 3 * m) * 4 + 2 * m * 4) as f64;
|
| 242 |
+
skew_rel.insert(
|
| 243 |
+
format!("n_{n}"),
|
| 244 |
+
serde_json::json!({
|
| 245 |
+
"tempo_ref_s": t_ref, "tempo_novo_s": t_novo,
|
| 246 |
+
"speedup": t_ref / t_novo.max(1e-12),
|
| 247 |
+
"bytes_ref_selecao": bytes_ref, "bytes_novo": bytes_novo,
|
| 248 |
+
"razao_memoria": bytes_ref / bytes_novo,
|
| 249 |
+
"bits_iguais": bits_iguais,
|
| 250 |
+
}),
|
| 251 |
+
);
|
| 252 |
+
}
|
| 253 |
+
|
| 254 |
+
// ---------- (2) calibrar: tensor vs laços nativos ----------
|
| 255 |
+
let (d_out, d_in, n_lin) = (512usize, 512usize, 4096usize);
|
| 256 |
+
let wv: Vec<f32> = (0..d_out * d_in).map(|_| rng.uniforme_intervalo(-2.0, 2.0) as f32).collect();
|
| 257 |
+
let w = Tensor::from_vec(wv, (d_out, d_in), &dev).unwrap();
|
| 258 |
+
let xv: Vec<f32> = (0..n_lin * d_in).map(|_| rng.uniforme_intervalo(-3.0, 3.0) as f32).collect();
|
| 259 |
+
let x = Tensor::from_vec(xv, (n_lin, d_in), &dev).unwrap();
|
| 260 |
+
let mut s_novo = fnh::SuavizadorQuant::novo(0.5, 0.98);
|
| 261 |
+
let mut s_tens = fnh::SuavizadorQuant::novo(0.5, 0.98);
|
| 262 |
+
let mut s_ref = fnh::SuavizadorQuant::novo(0.5, 0.98);
|
| 263 |
+
let mut bits_cal = true;
|
| 264 |
+
for _ in 0..3 {
|
| 265 |
+
s_novo.calibrar(&w, &x).unwrap();
|
| 266 |
+
s_tens.calibrar_tensor(&w, &x).unwrap();
|
| 267 |
+
s_ref.calibrar_referencia(&w, &x).unwrap();
|
| 268 |
+
for (a, b) in s_novo.w_max.as_ref().unwrap().iter().zip(s_ref.w_max.as_ref().unwrap()) {
|
| 269 |
+
bits_cal &= a.to_bits() == b.to_bits();
|
| 270 |
+
}
|
| 271 |
+
for (a, b) in s_novo.x_max.as_ref().unwrap().iter().zip(s_ref.x_max.as_ref().unwrap()) {
|
| 272 |
+
bits_cal &= a.to_bits() == b.to_bits();
|
| 273 |
+
}
|
| 274 |
+
}
|
| 275 |
+
// tempo (esquentadas 1×; média de 5)
|
| 276 |
+
let _ = s_ref.calibrar_referencia(&w, &x);
|
| 277 |
+
let t0 = Instant::now();
|
| 278 |
+
for _ in 0..5 { s_ref.calibrar_referencia(&w, &x).unwrap(); }
|
| 279 |
+
let t_cal_ref = t0.elapsed().as_secs_f64() / 5.0;
|
| 280 |
+
let _ = s_novo.calibrar(&w, &x);
|
| 281 |
+
let t0 = Instant::now();
|
| 282 |
+
for _ in 0..5 { s_novo.calibrar(&w, &x).unwrap(); }
|
| 283 |
+
let t_cal_novo = t0.elapsed().as_secs_f64() / 5.0;
|
| 284 |
+
let _ = s_tens.calibrar_tensor(&w, &x);
|
| 285 |
+
let t0 = Instant::now();
|
| 286 |
+
for _ in 0..5 { s_tens.calibrar_tensor(&w, &x).unwrap(); }
|
| 287 |
+
let t_cal_tens = t0.elapsed().as_secs_f64() / 5.0;
|
| 288 |
+
|
| 289 |
+
// ---------- (3) forward: regressão de valores + gradiente ----------
|
| 290 |
+
let (nm, dm, em) = (256usize, 32usize, 8usize);
|
| 291 |
+
let xv2: Vec<f32> = (0..nm * dm).map(|_| rng.normal(0.0, 1.0) as f32).collect();
|
| 292 |
+
let x2 = Tensor::from_vec(xv2, (nm, dm), &dev).unwrap();
|
| 293 |
+
#[allow(deprecated)] // oráculo do bug v080-1 (r-33 §5)
|
| 294 |
+
let moe = moe_redirecionavel::MoeRedirecionavel::novo(dm, em, 2, nm, &dev).unwrap();
|
| 295 |
+
#[allow(deprecated)]
|
| 296 |
+
let s_refm = moe.fwd(&x2, moe_redirecionavel::Papel::Codificador).unwrap();
|
| 297 |
+
let s_fwd = moe.forward(&x2, moe_redirecionavel::Papel::Codificador).unwrap();
|
| 298 |
+
let dif_moe = (&s_refm.saida - &s_fwd.saida).unwrap().abs().unwrap()
|
| 299 |
+
.max_all().unwrap().to_scalar::<f32>().unwrap() as f64;
|
| 300 |
+
let perda = s_fwd.saida.sqr().unwrap().sum_all().unwrap();
|
| 301 |
+
let gs = perda.backward().unwrap();
|
| 302 |
+
let mut gr = 0.0f64;
|
| 303 |
+
for v in moe.roteador.vars() {
|
| 304 |
+
if let Some(g) = gs.get(&v) {
|
| 305 |
+
gr += g.sqr().unwrap().sum_all().unwrap().to_scalar::<f32>().unwrap() as f64;
|
| 306 |
+
}
|
| 307 |
+
}
|
| 308 |
+
let mut ge = 0.0f64;
|
| 309 |
+
for e in &moe.especialistas {
|
| 310 |
+
for v in e.vars() {
|
| 311 |
+
if let Some(g) = gs.get(&v) {
|
| 312 |
+
ge += g.sqr().unwrap().sum_all().unwrap().to_scalar::<f32>().unwrap() as f64;
|
| 313 |
+
}
|
| 314 |
+
}
|
| 315 |
+
}
|
| 316 |
+
|
| 317 |
+
// ---------- (4) newtypes de domínio (T-V1) ----------
|
| 318 |
+
let rejeita = crate::tipos::Probabilidade::novo(7.0).is_err()
|
| 319 |
+
&& crate::tipos::Probabilidade::novo(-0.5).is_err()
|
| 320 |
+
&& crate::tipos::Probabilidade::novo(f64::NAN).is_err()
|
| 321 |
+
&& crate::tipos::GateAtivacao::novo(1.5).is_err();
|
| 322 |
+
let aceita = crate::tipos::Probabilidade::novo(0.37).unwrap().valor() == 0.37;
|
| 323 |
+
let gate_tipado = fnh::GatePunicao::default()
|
| 324 |
+
.valor_tipado(&crate::tipos::Probabilidade::novo(0.9).unwrap())
|
| 325 |
+
.valor();
|
| 326 |
+
|
| 327 |
+
let d_ = serde_json::json!({
|
| 328 |
+
"versao": "criticas-v090-1.0",
|
| 329 |
+
"skew_index_add": {
|
| 330 |
+
"por_n": skew_rel,
|
| 331 |
+
"gates": {
|
| 332 |
+
"bits_iguais_todos_n": bits_todos,
|
| 333 |
+
},
|
| 334 |
+
},
|
| 335 |
+
"calibrar_zero_copia": {
|
| 336 |
+
"bits_iguais_3_passos": bits_cal,
|
| 337 |
+
"tempo_ref_s": t_cal_ref, "tempo_novo_s": t_cal_novo,
|
| 338 |
+
"tempo_tensor_s": t_cal_tens,
|
| 339 |
+
"speedup_zero_copia": t_cal_ref / t_cal_novo.max(1e-12),
|
| 340 |
+
"razao_tensor_vs_zero_copia": t_cal_tens / t_cal_novo.max(1e-12),
|
| 341 |
+
"gates": { "bit_a_bit": bits_cal, "nao_regride": t_cal_novo <= t_cal_ref * 1.05 },
|
| 342 |
+
},
|
| 343 |
+
"forward_canonico": {
|
| 344 |
+
"max_dif_valores_vs_oraculo": dif_moe,
|
| 345 |
+
"grad_roteador": gr, "grad_especialistas": ge,
|
| 346 |
+
"gates": {
|
| 347 |
+
"valores_iguais": dif_moe < 1e-4,
|
| 348 |
+
"gradiente_ativo": gr > 0.0 && ge > 0.0,
|
| 349 |
+
},
|
| 350 |
+
},
|
| 351 |
+
"newtypes_dominio": {
|
| 352 |
+
"rejeita_fora_do_dominio": rejeita,
|
| 353 |
+
"aceita_dentro": aceita,
|
| 354 |
+
"gate_tipado_em_0_9": gate_tipado,
|
| 355 |
+
"gates": { "fronteira_validada": rejeita && aceita },
|
| 356 |
+
},
|
| 357 |
+
});
|
| 358 |
+
Ok(pythonize::pythonize(py, &d_)?.into())
|
| 359 |
+
}
|
laboratorio/arquivo_split_v100/python/fnh_arvore.rs
ADDED
|
@@ -0,0 +1,344 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! `python::fnh_arvore` — extraído do monólito na v0.10.0
|
| 2 |
+
//! (divisão SRP, crítica Qwen3.8 lote 3 nº 1; r-35 §2).
|
| 3 |
+
|
| 4 |
+
use super::*;
|
| 5 |
+
|
| 6 |
+
use super::nucleo::ConfigPy;
|
| 7 |
+
use super::treino_fases::{carregar_gerador, carregar_tokenizador};
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
// ---------------------------------------------------------------------------
|
| 12 |
+
// v0.7.0 — bindings dos módulos novos (FNH, árvore, quebra-cabeça, NLP/NLG)
|
| 13 |
+
// ---------------------------------------------------------------------------
|
| 14 |
+
|
| 15 |
+
/// Árvore de pesos indexada (arestas duplas) exposta ao Python.
|
| 16 |
+
#[pyclass(name = "ArvorePesos")]
|
| 17 |
+
pub(crate) struct ArvorePesosPy {
|
| 18 |
+
arvore: arvore_pesos::ArvorePesos,
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
#[pymethods]
|
| 22 |
+
impl ArvorePesosPy {
|
| 23 |
+
#[staticmethod]
|
| 24 |
+
#[pyo3(signature = (contagens=None))]
|
| 25 |
+
fn nova(contagens: Option<std::collections::HashMap<String, usize>>) -> Self {
|
| 26 |
+
let c = contagens.unwrap_or_default();
|
| 27 |
+
ArvorePesosPy { arvore: arvore_pesos::ArvorePesos::nova(&c) }
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
fn invariantes_ok(&self) -> bool {
|
| 31 |
+
self.arvore.invariantes_ok().is_ok()
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
fn agregar(&mut self, metrica: &str) -> f64 {
|
| 35 |
+
self.arvore.agregar_fundo_topo(metrica)
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
fn aplicar_ajuste(
|
| 39 |
+
&mut self,
|
| 40 |
+
no: &str,
|
| 41 |
+
metrica: &str,
|
| 42 |
+
delta: f64,
|
| 43 |
+
delta_max: f64,
|
| 44 |
+
) -> PyResult<f64> {
|
| 45 |
+
let idx = self
|
| 46 |
+
.arvore
|
| 47 |
+
.no(no)
|
| 48 |
+
.ok_or_else(|| pyo3::exceptions::PyKeyError::new_err(format!("nó '{no}' inexistente")))?;
|
| 49 |
+
Ok(self.arvore.aplicar_ajuste_indexado(idx, metrica, delta, delta_max))
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
fn definir_metrica(&mut self, no: &str, metrica: &str, valor: f64) -> PyResult<()> {
|
| 53 |
+
let idx = self
|
| 54 |
+
.arvore
|
| 55 |
+
.no(no)
|
| 56 |
+
.ok_or_else(|| pyo3::exceptions::PyKeyError::new_err(format!("nó '{no}' inexistente")))?;
|
| 57 |
+
self.arvore.nos[idx].metricas.insert(metrica.to_string(), valor);
|
| 58 |
+
Ok(())
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
fn metrica(&self, no: &str, metrica: &str) -> PyResult<f64> {
|
| 62 |
+
let idx = self
|
| 63 |
+
.arvore
|
| 64 |
+
.no(no)
|
| 65 |
+
.ok_or_else(|| pyo3::exceptions::PyKeyError::new_err(format!("nó '{no}' inexistente")))?;
|
| 66 |
+
Ok(self.arvore.nos[idx].metricas.get(metrica).copied().unwrap_or(0.0))
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
fn regular(&mut self, origem: &str, delta: f64, lambda: f64) -> PyResult<()> {
|
| 70 |
+
let idx = self
|
| 71 |
+
.arvore
|
| 72 |
+
.no(origem)
|
| 73 |
+
.ok_or_else(|| pyo3::exceptions::PyKeyError::new_err(format!("nó '{origem}' inexistente")))?;
|
| 74 |
+
self.arvore.regular_topo_fundo(idx, delta, lambda);
|
| 75 |
+
Ok(())
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
fn dump(&self) -> PyResult<PyObject> {
|
| 79 |
+
Python::with_gil(|py| {
|
| 80 |
+
let nos: Vec<serde_json::Value> = self
|
| 81 |
+
.arvore
|
| 82 |
+
.nos
|
| 83 |
+
.iter()
|
| 84 |
+
.map(|no| {
|
| 85 |
+
serde_json::json!({
|
| 86 |
+
"nome": no.nome, "ini": no.ini, "fim": no.fim,
|
| 87 |
+
"profundidade": no.profundidade,
|
| 88 |
+
"metricas": no.metricas,
|
| 89 |
+
})
|
| 90 |
+
})
|
| 91 |
+
.collect();
|
| 92 |
+
let d = serde_json::json!({
|
| 93 |
+
"n_nos": self.arvore.n_nos(),
|
| 94 |
+
"n_params": self.arvore.n_params,
|
| 95 |
+
"invariantes_ok": self.arvore.invariantes_ok().is_ok(),
|
| 96 |
+
"nos": nos,
|
| 97 |
+
});
|
| 98 |
+
Ok(pythonize::pythonize(py, &d)?.into())
|
| 99 |
+
})
|
| 100 |
+
}
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
/// Demo/gate da camada FNH sobre o backbone: mede o efeito do gate de
|
| 105 |
+
/// punição nas rotações aprendíveis (ablação: π baixa vs π alta).
|
| 106 |
+
#[pyfunction]
|
| 107 |
+
#[pyo3(signature = (d_in=8, d_out=6, passos=60, seed=42))]
|
| 108 |
+
pub(crate) fn demo_fnh(py: Python, d_in: usize, d_out: usize, passos: usize, seed: u64) -> PyResult<PyObject> {
|
| 109 |
+
let dev = candle_core::Device::Cpu;
|
| 110 |
+
let mut rng = rng::RngDeterministico::novo(seed);
|
| 111 |
+
let mut camada = fnh::CamadaFNH::nova(d_in, d_out, &dev)
|
| 112 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("fnh: {e}")))?;
|
| 113 |
+
let x: Vec<f32> = (0..4 * d_in).map(|_| rng.normal_padrao() as f32).collect();
|
| 114 |
+
let xt = candle_core::Tensor::from_vec(x, (4, d_in), &dev)
|
| 115 |
+
.map_err(py_err)?;
|
| 116 |
+
camada
|
| 117 |
+
.suavizador
|
| 118 |
+
.calibrar(camada.base.w.as_tensor(), &xt)
|
| 119 |
+
.map_err(py_err)?;
|
| 120 |
+
// treino curto com punição ALTA (gate abre) vs BAIXA (gate fechado)
|
| 121 |
+
let mut resumo = serde_json::Map::new();
|
| 122 |
+
for (rotulo, punicao) in [("baixa", 0.1f64), ("alta", 0.95)] {
|
| 123 |
+
let mut cam = fnh::CamadaFNH::nova(d_in, d_out, &dev).map_err(py_err)?;
|
| 124 |
+
// mesma semente de pesos: copia os valores
|
| 125 |
+
let _ = &mut cam;
|
| 126 |
+
let mut hub = telemetria::TelemetryHub::novo(None);
|
| 127 |
+
let mut perdas = Vec::new();
|
| 128 |
+
for p in 0..passos {
|
| 129 |
+
// ruído no x a cada passo (regime não-estacionário leve)
|
| 130 |
+
let ruido: Vec<f32> = (0..4 * d_in)
|
| 131 |
+
.map(|_| (rng.normal(0.0, 0.05)) as f32)
|
| 132 |
+
.collect();
|
| 133 |
+
let xt2 = (&xt
|
| 134 |
+
+ &candle_core::Tensor::from_vec(ruido, (4, d_in), &dev).map_err(py_err)?)
|
| 135 |
+
.map_err(py_err)?;
|
| 136 |
+
let y = cam.forward(&xt2, punicao).map_err(py_err)?;
|
| 137 |
+
// alvo: saída da camada base (auto-referência: regular para W)
|
| 138 |
+
let z_ref = cam.linear_sem_bias(&xt2, cam.base.w.as_tensor()).map_err(py_err)?;
|
| 139 |
+
let perda = (&y).sub(&z_ref).map_err(py_err)?.sqr().map_err(py_err)?.sum_all().map_err(py_err)?;
|
| 140 |
+
perdas.push(perda.to_scalar::<f32>().map_err(py_err)? as f64);
|
| 141 |
+
let grads = perda.backward().map_err(py_err)?;
|
| 142 |
+
// gradiente descendente manual simples nos θ das rotações
|
| 143 |
+
if let Some(g) = grads.get(&cam.r_wp.theta) {
|
| 144 |
+
let gv = g.flatten_all().map_err(py_err)?.to_vec1::<f32>().map_err(py_err)?;
|
| 145 |
+
let th = cam.r_wp.theta.as_tensor().flatten_all().map_err(py_err)?.to_vec1::<f32>().map_err(py_err)?;
|
| 146 |
+
let novo: Vec<f32> = th.iter().zip(gv.iter()).map(|(t, g_)| t - 0.05 * g_).collect();
|
| 147 |
+
cam.r_wp
|
| 148 |
+
.theta
|
| 149 |
+
.set(&candle_core::Tensor::from_vec(novo, th.len(), &dev).map_err(py_err)?)
|
| 150 |
+
.map_err(py_err)?;
|
| 151 |
+
}
|
| 152 |
+
hub.registrar("fnh_gate", cam.gate_ultimo);
|
| 153 |
+
hub.registrar("fnh_punicao", punicao);
|
| 154 |
+
hub.registrar("perda", perdas[p]);
|
| 155 |
+
let _ = p;
|
| 156 |
+
}
|
| 157 |
+
let theta_norma: f64 = cam
|
| 158 |
+
.r_wp
|
| 159 |
+
.theta
|
| 160 |
+
.as_tensor()
|
| 161 |
+
.flatten_all()
|
| 162 |
+
.map_err(py_err)?
|
| 163 |
+
.to_vec1::<f32>()
|
| 164 |
+
.map_err(py_err)?
|
| 165 |
+
.iter()
|
| 166 |
+
.map(|v| (*v as f64).powi(2))
|
| 167 |
+
.sum::<f64>()
|
| 168 |
+
.sqrt();
|
| 169 |
+
let delta_ort = cam.r_wp.erro_ortogonalidade().map_err(py_err)?;
|
| 170 |
+
resumo.insert(
|
| 171 |
+
format!("punicao_{rotulo}"),
|
| 172 |
+
serde_json::json!({
|
| 173 |
+
"gate_final": cam.gate_ultimo,
|
| 174 |
+
"theta_norma": theta_norma,
|
| 175 |
+
"delta_ort": delta_ort,
|
| 176 |
+
"perda_inicial": perdas[0],
|
| 177 |
+
"perda_final": perdas[perdas.len() - 1],
|
| 178 |
+
}),
|
| 179 |
+
);
|
| 180 |
+
}
|
| 181 |
+
let _ = &mut camada;
|
| 182 |
+
let d = serde_json::json!({
|
| 183 |
+
"versao": "fnh-0.7.0",
|
| 184 |
+
"resumo": resumo,
|
| 185 |
+
});
|
| 186 |
+
Ok(pythonize::pythonize(py, &d)?.into())
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
/// **Quebra-cabeça sobre o conhecimento TREINADO REAL** (script 63):
|
| 191 |
+
/// carrega o tokenizador (codebook do nível `nivel` — o conhecimento
|
| 192 |
+
/// aprendido dos dados reais) e o gerador (a cabeça real como logits_fn
|
| 193 |
+
/// do verificador); executa o protocolo completo de r-30 Q-AD.
|
| 194 |
+
#[pyfunction]
|
| 195 |
+
#[pyo3(signature = (cfg, caminho_tokenizador, caminho_gerador, n_pecas=4, n_rodadas=12, tau_c=0.4, nivel=0, seed=777))]
|
| 196 |
+
pub(crate) fn quebra_cabeca_real(
|
| 197 |
+
cfg: &ConfigPy,
|
| 198 |
+
caminho_tokenizador: &str,
|
| 199 |
+
caminho_gerador: &str,
|
| 200 |
+
n_pecas: usize,
|
| 201 |
+
n_rodadas: usize,
|
| 202 |
+
tau_c: f64,
|
| 203 |
+
nivel: usize,
|
| 204 |
+
seed: u64,
|
| 205 |
+
) -> PyResult<PyObject> {
|
| 206 |
+
Python::with_gil(|py| {
|
| 207 |
+
let dev = candle_core::Device::Cpu;
|
| 208 |
+
crate::rng::definir_semente(seed);
|
| 209 |
+
let mut rng = rng::RngDeterministico::novo(seed);
|
| 210 |
+
let mut tok = tokenizador::TokenizadorConceitos::novo(&cfg.cfg, &dev)
|
| 211 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("tok: {e}")))?;
|
| 212 |
+
carregar_tokenizador(&mut tok, caminho_tokenizador)
|
| 213 |
+
.map_err(pyo3::exceptions::PyRuntimeError::new_err)?;
|
| 214 |
+
let mut ger = gerador::GeradorConceitos::novo(&cfg.cfg, &dev)
|
| 215 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("ger: {e}")))?;
|
| 216 |
+
ger.carregar(caminho_gerador)
|
| 217 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("ger carregar: {e}")))?;
|
| 218 |
+
let nivel = nivel.min(tok.quants.len().saturating_sub(1));
|
| 219 |
+
// conhecimento treinado REAL: codebook Stiefel (K, d_lat)
|
| 220 |
+
let codebook = tok
|
| 221 |
+
.quants[nivel]
|
| 222 |
+
.codebook()
|
| 223 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("codebook: {e}")))?;
|
| 224 |
+
let d_lat = codebook.dims()[1];
|
| 225 |
+
let k = ger.k;
|
| 226 |
+
// δ_ort REAL do codebook treinado (rotação Stiefel em treino — A2)
|
| 227 |
+
let delta_ort_codebook = tok.quants[nivel]
|
| 228 |
+
.delta_ort()
|
| 229 |
+
.unwrap_or(1.0);
|
| 230 |
+
// logits_fn REAL: agregado (d_lat,) → proj_entrada → norm → cabeça
|
| 231 |
+
let proj = &ger.proj_entrada;
|
| 232 |
+
let norm = &ger.norm_entrada;
|
| 233 |
+
let cabeca = &ger.cabeca.cabecas[nivel];
|
| 234 |
+
let logits_fn = move |x: &candle_core::Tensor| -> candle_core::Result<candle_core::Tensor> {
|
| 235 |
+
let h = proj.fwd(&x.reshape((1, d_lat))?)?;
|
| 236 |
+
let h = norm.fwd(&h)?;
|
| 237 |
+
let lg = cabeca.fwd(&h)?;
|
| 238 |
+
lg.reshape((k,))
|
| 239 |
+
};
|
| 240 |
+
// verificador com temperatura calibrada pela fase C quando
|
| 241 |
+
// disponível; default 1,0 (a cota V-2 aplica-se com ECE medido)
|
| 242 |
+
let verif = verificador::VerificadorNcm::novo();
|
| 243 |
+
let mut arvore = arvore_pesos::ArvorePesos::nova(&std::collections::HashMap::new());
|
| 244 |
+
let cfg_qc = pensamento::ConfigQuebraCabeca::novo(n_pecas, n_rodadas, tau_c);
|
| 245 |
+
let r = pensamento::quebra_cabeca_inovar(&codebook, &verif, &logits_fn, &mut arvore, &cfg_qc, &mut rng)
|
| 246 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("qc: {e}")))?;
|
| 247 |
+
let rodadas: Vec<serde_json::Value> = r
|
| 248 |
+
.rodadas
|
| 249 |
+
.iter()
|
| 250 |
+
.map(|x| {
|
| 251 |
+
serde_json::json!({
|
| 252 |
+
"rodada": x.rodada, "confianca": x.confianca,
|
| 253 |
+
"aceito": x.aceito, "delta": x.delta_aplicado,
|
| 254 |
+
})
|
| 255 |
+
})
|
| 256 |
+
.collect();
|
| 257 |
+
let d_ = serde_json::json!({
|
| 258 |
+
"versao": "quebra-cabeca-real-0.7.0",
|
| 259 |
+
"nivel": nivel,
|
| 260 |
+
"delta_ort_codebook": delta_ort_codebook,
|
| 261 |
+
"n_conceitos": codebook.dims()[0],
|
| 262 |
+
"d_lat": d_lat,
|
| 263 |
+
"aceitos": r.aceitos,
|
| 264 |
+
"rejeitados": r.rejeitados,
|
| 265 |
+
"confianca_base": r.confianca_base,
|
| 266 |
+
"confianca_melhor": r.confianca_melhor,
|
| 267 |
+
"telemetria": r.telemetria,
|
| 268 |
+
"rodadas": rodadas,
|
| 269 |
+
"arvore_invariantes": arvore.invariantes_ok().is_ok(),
|
| 270 |
+
"punicao_no_pensamento": arvore
|
| 271 |
+
.no("pensamento")
|
| 272 |
+
.and_then(|i| arvore.nos[i].metricas.get("punicao").copied())
|
| 273 |
+
.unwrap_or(0.0),
|
| 274 |
+
});
|
| 275 |
+
Ok(pythonize::pythonize(py, &d_)?.into())
|
| 276 |
+
})
|
| 277 |
+
}
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
/// Demo/gate do quebra-cabeça sobre conceitos SINTÉTICOS estruturados
|
| 281 |
+
/// (validação de mecanismo; a avaliação com dados reais vive no script 63).
|
| 282 |
+
#[pyfunction]
|
| 283 |
+
#[pyo3(signature = (m=24, d=8, n_pecas=4, n_rodadas=12, tau_c=0.35, seed=777))]
|
| 284 |
+
pub(crate) fn demo_quebra_cabeca(
|
| 285 |
+
py: Python,
|
| 286 |
+
m: usize,
|
| 287 |
+
d: usize,
|
| 288 |
+
n_pecas: usize,
|
| 289 |
+
n_rodadas: usize,
|
| 290 |
+
tau_c: f64,
|
| 291 |
+
seed: u64,
|
| 292 |
+
) -> PyResult<PyObject> {
|
| 293 |
+
let dev = candle_core::Device::Cpu;
|
| 294 |
+
let mut rng = rng::RngDeterministico::novo(seed);
|
| 295 |
+
// conceitos estruturados: cluster dominante +1 (média direcional) com
|
| 296 |
+
// 25% de outliers fracos — o agregado TEM direção (sem cancelamento)
|
| 297 |
+
let mut v = Vec::with_capacity(m * d);
|
| 298 |
+
for i in 0..m {
|
| 299 |
+
let centro = if i < m / 4 { 0.2 } else { 1.0 };
|
| 300 |
+
for j in 0..d {
|
| 301 |
+
v.push((centro + rng.normal(0.0, 0.25)) as f32);
|
| 302 |
+
}
|
| 303 |
+
}
|
| 304 |
+
let conceitos = candle_core::Tensor::from_vec(v, (m, d), &dev).map_err(py_err)?;
|
| 305 |
+
// logits_fn ASSIMÉTRICO: projeção fixa W_proj (rotação-sensível — a
|
| 306 |
+
// agregação simétrica seria invariante sob permutação/rotação, e o
|
| 307 |
+
// backbone real é exatamente o avaliador NÃO-invariente da prática).
|
| 308 |
+
let mut wv = Vec::with_capacity(d * 4);
|
| 309 |
+
for _ in 0..d * 4 {
|
| 310 |
+
wv.push((rng.normal_padrao() as f32) * 2.5);
|
| 311 |
+
}
|
| 312 |
+
let w_proj = candle_core::Tensor::from_vec(wv, (d, 4), &dev).map_err(py_err)?;
|
| 313 |
+
// verificador com temperatura padrão
|
| 314 |
+
let verif = verificador::VerificadorNcm::novo();
|
| 315 |
+
let logits_fn = |x: &candle_core::Tensor| -> candle_core::Result<candle_core::Tensor> {
|
| 316 |
+
// logits = xᵀ·W_proj (4,) — sensível à direção do agregado
|
| 317 |
+
x.reshape((1, d))?.matmul(&w_proj)?.reshape((4,))
|
| 318 |
+
};
|
| 319 |
+
let mut arvore = arvore_pesos::ArvorePesos::nova(&std::collections::HashMap::new());
|
| 320 |
+
let cfg = pensamento::ConfigQuebraCabeca::novo(n_pecas, n_rodadas, tau_c);
|
| 321 |
+
let r = pensamento::quebra_cabeca_inovar(&conceitos, &verif, &logits_fn, &mut arvore, &cfg, &mut rng)
|
| 322 |
+
.map_err(py_err)?;
|
| 323 |
+
let rodadas: Vec<serde_json::Value> = r
|
| 324 |
+
.rodadas
|
| 325 |
+
.iter()
|
| 326 |
+
.map(|x| {
|
| 327 |
+
serde_json::json!({
|
| 328 |
+
"rodada": x.rodada, "confianca": x.confianca,
|
| 329 |
+
"aceito": x.aceito, "delta": x.delta_aplicado,
|
| 330 |
+
})
|
| 331 |
+
})
|
| 332 |
+
.collect();
|
| 333 |
+
let d_ = serde_json::json!({
|
| 334 |
+
"versao": "quebra-cabeca-0.7.0",
|
| 335 |
+
"aceitos": r.aceitos,
|
| 336 |
+
"rejeitados": r.rejeitados,
|
| 337 |
+
"confianca_base": r.confianca_base,
|
| 338 |
+
"confianca_melhor": r.confianca_melhor,
|
| 339 |
+
"telemetria": r.telemetria,
|
| 340 |
+
"rodadas": rodadas,
|
| 341 |
+
"arvore_invariantes": arvore.invariantes_ok().is_ok(),
|
| 342 |
+
});
|
| 343 |
+
Ok(pythonize::pythonize(py, &d_)?.into())
|
| 344 |
+
}
|
laboratorio/arquivo_split_v100/python/jepa_treinos.rs
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! `python::jepa_treinos` — extraído do monólito na v0.10.0
|
| 2 |
+
//! (divisão SRP, crítica Qwen3.8 lote 3 nº 1; r-35 §2).
|
| 3 |
+
|
| 4 |
+
use super::*;
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
/// Treina uma variante JEPA (7 variantes por máscara; lejepa/mcjepa/bjepa
|
| 8 |
+
/// têm funções próprias) sobre patches (n, d) com grade dada.
|
| 9 |
+
#[pyfunction]
|
| 10 |
+
pub(crate) fn treinar_jepa(py: Python, dados: Vec<Vec<f64>>, grid: Vec<usize>, variante: String, cfg: Option<String>) -> PyResult<PyObject> {
|
| 11 |
+
let dev = candle_core::Device::Cpu;
|
| 12 |
+
let t = tensor_de_2d(dados, &dev).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 13 |
+
let mut c = jepa::CfgJepa::default();
|
| 14 |
+
if let Some(js) = &cfg {
|
| 15 |
+
if let Ok(v) = serde_json::from_str::<serde_json::Value>(js) {
|
| 16 |
+
if let Some(o) = v.as_object() {
|
| 17 |
+
for (k, val) in o {
|
| 18 |
+
match k.as_str() {
|
| 19 |
+
"d_emb" => c.d_emb = val.as_u64().unwrap_or(32) as usize,
|
| 20 |
+
"epocas" => c.epocas = val.as_u64().unwrap_or(60) as usize,
|
| 21 |
+
"lr" => c.lr = val.as_f64().unwrap_or(3e-3),
|
| 22 |
+
"m" => c.m = val.as_f64().unwrap_or(0.99),
|
| 23 |
+
"lambda_vc" => c.lambda_vc = val.as_f64().unwrap_or(0.5),
|
| 24 |
+
"gamma_vc" => c.gamma_vc = val.as_f64().unwrap_or(1.0),
|
| 25 |
+
"frac_mascara" => c.frac_mascara = val.as_f64().unwrap_or(0.35),
|
| 26 |
+
"semente" => c.semente = val.as_u64().unwrap_or(42),
|
| 27 |
+
_ => {}
|
| 28 |
+
}
|
| 29 |
+
}
|
| 30 |
+
}
|
| 31 |
+
}
|
| 32 |
+
}
|
| 33 |
+
let var = match variante.as_str() {
|
| 34 |
+
"image" => jepa::VarianteJepa::ImageJepa,
|
| 35 |
+
"vjepa2" => jepa::VarianteJepa::VJepa2,
|
| 36 |
+
"audio" => jepa::VarianteJepa::AudioJepa,
|
| 37 |
+
"point" => jepa::VarianteJepa::PointJepa,
|
| 38 |
+
"jepa3d" => jepa::VarianteJepa::Jepa3D,
|
| 39 |
+
"brain" => jepa::VarianteJepa::BrainJepa,
|
| 40 |
+
"tjepa" => jepa::VarianteJepa::TJepa,
|
| 41 |
+
_ => jepa::VarianteJepa::TJepa,
|
| 42 |
+
};
|
| 43 |
+
let grid2 = if grid.is_empty() { vec![t.dim(0).unwrap_or(1)] } else { grid };
|
| 44 |
+
let rel = jepa::treinar_variante(
|
| 45 |
+
&t,
|
| 46 |
+
&|_n, r| jepa::mascara_por_variante(var, &grid2, c.frac_mascara, r),
|
| 47 |
+
&c,
|
| 48 |
+
var,
|
| 49 |
+
None,
|
| 50 |
+
&dev,
|
| 51 |
+
)
|
| 52 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 53 |
+
let d = serde_json::json!({
|
| 54 |
+
"versao": jepa::versao(),
|
| 55 |
+
"variante": rel.variante,
|
| 56 |
+
"perda_inicial": rel.perda_inicial,
|
| 57 |
+
"perda_final": rel.perda_final,
|
| 58 |
+
"perda_pred_inicial": rel.perda_pred_inicial,
|
| 59 |
+
"perda_pred_final": rel.perda_pred_final,
|
| 60 |
+
"queda_pct": if rel.perda_pred_inicial.is_finite() && rel.perda_pred_inicial > 0.0 {
|
| 61 |
+
100.0 * (1.0 - rel.perda_pred_final / rel.perda_pred_inicial)
|
| 62 |
+
} else { 0.0 },
|
| 63 |
+
"std_emb_inicial": rel.std_emb_inicial,
|
| 64 |
+
"std_emb_final": rel.std_emb_final,
|
| 65 |
+
"colapso_evitado": rel.std_emb_final > 0.05,
|
| 66 |
+
"n_patches": rel.n_patches,
|
| 67 |
+
"epocas": rel.epocas,
|
| 68 |
+
});
|
| 69 |
+
Ok(pythonize::pythonize(py, &d)?.into())
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
/// Treina LeJEPA (edição-condicionado): dados + instruções + editados.
|
| 74 |
+
#[pyfunction]
|
| 75 |
+
pub(crate) fn treinar_lejepa(py: Python, dados: Vec<Vec<f64>>, edits: Vec<Vec<f64>>, editados: Vec<Vec<f64>>, cfg: Option<String>) -> PyResult<PyObject> {
|
| 76 |
+
let dev = candle_core::Device::Cpu;
|
| 77 |
+
let t = tensor_de_2d(dados, &dev).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 78 |
+
let e = tensor_de_2d(edits, &dev).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 79 |
+
let y = tensor_de_2d(editados, &dev).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 80 |
+
let mut c = jepa::CfgJepa::default();
|
| 81 |
+
if let Some(js) = &cfg {
|
| 82 |
+
if let Ok(v) = serde_json::from_str::<serde_json::Value>(js) {
|
| 83 |
+
if let Some(o) = v.as_object() {
|
| 84 |
+
if let Some(x) = o.get("epocas") { c.epocas = x.as_u64().unwrap_or(60) as usize; }
|
| 85 |
+
if let Some(x) = o.get("d_emb") { c.d_emb = x.as_u64().unwrap_or(32) as usize; }
|
| 86 |
+
if let Some(x) = o.get("lr") { c.lr = x.as_f64().unwrap_or(3e-3); }
|
| 87 |
+
if let Some(x) = o.get("semente") { c.semente = x.as_u64().unwrap_or(42); }
|
| 88 |
+
}
|
| 89 |
+
}
|
| 90 |
+
}
|
| 91 |
+
let rel = jepa::treinar_lejepa(&t, &e, &y, &c, &dev)
|
| 92 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 93 |
+
let d = serde_json::json!({
|
| 94 |
+
"variante": rel.variante, "perda_inicial": rel.perda_inicial,
|
| 95 |
+
"perda_final": rel.perda_final, "std_emb_final": rel.std_emb_final,
|
| 96 |
+
"colapso_evitado": rel.std_emb_final > 0.05,
|
| 97 |
+
});
|
| 98 |
+
Ok(pythonize::pythonize(py, &d)?.into())
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
/// Treina MC-JEPA (cruz-modal): duas modalidades pareadas.
|
| 103 |
+
#[pyfunction]
|
| 104 |
+
pub(crate) fn treinar_mcjepa(py: Python, mod_a: Vec<Vec<f64>>, mod_b: Vec<Vec<f64>>, cfg: Option<String>) -> PyResult<PyObject> {
|
| 105 |
+
let dev = candle_core::Device::Cpu;
|
| 106 |
+
let a = tensor_de_2d(mod_a, &dev).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 107 |
+
let b = tensor_de_2d(mod_b, &dev).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 108 |
+
let mut c = jepa::CfgJepa::default();
|
| 109 |
+
if let Some(js) = &cfg {
|
| 110 |
+
if let Ok(v) = serde_json::from_str::<serde_json::Value>(js) {
|
| 111 |
+
if let Some(o) = v.as_object() {
|
| 112 |
+
if let Some(x) = o.get("epocas") { c.epocas = x.as_u64().unwrap_or(60) as usize; }
|
| 113 |
+
if let Some(x) = o.get("d_emb") { c.d_emb = x.as_u64().unwrap_or(32) as usize; }
|
| 114 |
+
if let Some(x) = o.get("lr") { c.lr = x.as_f64().unwrap_or(3e-3); }
|
| 115 |
+
}
|
| 116 |
+
}
|
| 117 |
+
}
|
| 118 |
+
let rel = jepa::treinar_mcjepa(&a, &b, &c, &dev)
|
| 119 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 120 |
+
let d = serde_json::json!({
|
| 121 |
+
"variante": rel.variante, "perda_inicial": rel.perda_inicial,
|
| 122 |
+
"perda_final": rel.perda_final, "std_emb_final": rel.std_emb_final,
|
| 123 |
+
"colapso_evitado": rel.std_emb_final > 0.05,
|
| 124 |
+
});
|
| 125 |
+
Ok(pythonize::pythonize(py, &d)?.into())
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
/// Treina BJEPA (bidirecional com consistência de ciclo) sobre sequência.
|
| 130 |
+
#[pyfunction]
|
| 131 |
+
pub(crate) fn treinar_bjepa(py: Python, serie: Vec<Vec<f64>>, cfg: Option<String>) -> PyResult<PyObject> {
|
| 132 |
+
let dev = candle_core::Device::Cpu;
|
| 133 |
+
let t = tensor_de_2d(serie, &dev).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 134 |
+
let mut c = jepa::CfgJepa::default();
|
| 135 |
+
if let Some(js) = &cfg {
|
| 136 |
+
if let Ok(v) = serde_json::from_str::<serde_json::Value>(js) {
|
| 137 |
+
if let Some(o) = v.as_object() {
|
| 138 |
+
if let Some(x) = o.get("epocas") { c.epocas = x.as_u64().unwrap_or(60) as usize; }
|
| 139 |
+
if let Some(x) = o.get("d_emb") { c.d_emb = x.as_u64().unwrap_or(32) as usize; }
|
| 140 |
+
if let Some(x) = o.get("lr") { c.lr = x.as_f64().unwrap_or(3e-3); }
|
| 141 |
+
}
|
| 142 |
+
}
|
| 143 |
+
}
|
| 144 |
+
let rel = jepa::treinar_bjepa(&t, &c, &dev)
|
| 145 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 146 |
+
let d = serde_json::json!({
|
| 147 |
+
"variante": rel.variante, "perda_inicial": rel.perda_inicial,
|
| 148 |
+
"perda_final": rel.perda_final, "std_emb_final": rel.std_emb_final,
|
| 149 |
+
"colapso_evitado": rel.std_emb_final > 0.05,
|
| 150 |
+
});
|
| 151 |
+
Ok(pythonize::pythonize(py, &d)?.into())
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
/// Demo SonicMoE: roteamento top-k com capacidade e perda de balanceamento.
|
| 156 |
+
#[pyfunction]
|
| 157 |
+
pub(crate) fn demo_sonic_moe(py: Python, n: usize, d: usize, n_expertos: usize, top_k: usize, capacidade: usize) -> PyResult<PyObject> {
|
| 158 |
+
let dev = candle_core::Device::Cpu;
|
| 159 |
+
let moe = jepa::SonicMoe::novo(d, n_expertos, top_k, capacidade, &dev)
|
| 160 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 161 |
+
let x = candle_core::Tensor::randn(0f32, 1.0, (n, d), &dev)
|
| 162 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 163 |
+
let s = moe.fwd(&x).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 164 |
+
let aux = s.perda_aux.to_scalar::<f32>().map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))? as f64;
|
| 165 |
+
let d_ = serde_json::json!({
|
| 166 |
+
"versao": jepa::versao(),
|
| 167 |
+
"carga_por_especialista": s.carga,
|
| 168 |
+
"descartados": s.descartados,
|
| 169 |
+
"perda_aux": aux,
|
| 170 |
+
"capacidade_respeitada": s.carga.iter().all(|&c| c <= capacidade),
|
| 171 |
+
"saida_forma": s.saida.dims().to_vec(),
|
| 172 |
+
});
|
| 173 |
+
Ok(pythonize::pythonize(py, &d_)?.into())
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
/// Demo ReplaySSM: estabilidade + replay em cenário de troca de tarefa.
|
| 178 |
+
#[pyfunction]
|
| 179 |
+
pub(crate) fn demo_replay_ssm(py: Python, passos: usize, alpha: f64) -> PyResult<PyObject> {
|
| 180 |
+
let dev = candle_core::Device::Cpu;
|
| 181 |
+
let mut ssm = jepa::ReplaySsm::novo(4, 6, alpha, 8, &dev)
|
| 182 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 183 |
+
let mut otim = crate::treino::AdamWManual::novo(ssm.vars(), 1e-2, 0.0);
|
| 184 |
+
let x_antigo = candle_core::Tensor::from_vec(vec![1.0f32; 16 * 4], (16, 4), &dev)
|
| 185 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 186 |
+
let mut hist = Vec::new();
|
| 187 |
+
for _ in 0..passos {
|
| 188 |
+
let h = ssm.scan(&x_antigo).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 189 |
+
let alvo = h.detach();
|
| 190 |
+
let (pt, pn, pr) = ssm.passo_treino(&x_antigo, &alvo, &mut otim)
|
| 191 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 192 |
+
hist.push(serde_json::json!({"total": pt, "novo": pn, "replay": pr}));
|
| 193 |
+
}
|
| 194 |
+
let x_novo = candle_core::Tensor::from_vec(vec![-1.0f32; 16 * 4], (16, 4), &dev)
|
| 195 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 196 |
+
for _ in 0..passos {
|
| 197 |
+
let h = ssm.scan(&x_novo).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 198 |
+
let alvo = h.detach();
|
| 199 |
+
let _ = ssm.passo_treino(&x_novo, &alvo, &mut otim)
|
| 200 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 201 |
+
}
|
| 202 |
+
let h_fin = ssm.scan(&x_antigo).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 203 |
+
let mag = h_fin.sqr().map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?
|
| 204 |
+
.max_all().map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?
|
| 205 |
+
.to_scalar::<f32>().map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))? as f64;
|
| 206 |
+
let d_ = serde_json::json!({
|
| 207 |
+
"versao": jepa::versao(),
|
| 208 |
+
"alpha_replay": alpha,
|
| 209 |
+
"historico": hist,
|
| 210 |
+
"magnitudes_finitas": mag.is_finite(),
|
| 211 |
+
"magnitude_max_pos_troca": mag,
|
| 212 |
+
});
|
| 213 |
+
Ok(pythonize::pythonize(py, &d_)?.into())
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
/// Extrai patches 2D de uma imagem achatada (C, H, W) — adaptador Image-JEPA.
|
| 218 |
+
#[pyfunction]
|
| 219 |
+
pub(crate) fn patches_2d(img: Vec<f32>, c: usize, h: usize, w: usize, ph: usize, pw: usize) -> PyResult<Vec<Vec<f32>>> {
|
| 220 |
+
let dev = candle_core::Device::Cpu;
|
| 221 |
+
let t = candle_core::Tensor::from_vec(img, (c, h, w), &dev)
|
| 222 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 223 |
+
let p = jepa::em_patches_2d(&t, ph, pw)
|
| 224 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 225 |
+
p.to_vec2::<f32>().map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
/// Extrai patches canal-independentes de série temporal (C, T) — T-JEPA.
|
| 230 |
+
#[pyfunction]
|
| 231 |
+
pub(crate) fn patches_serie(ts: Vec<f32>, c: usize, t: usize, pt: usize) -> PyResult<Vec<Vec<f32>>> {
|
| 232 |
+
let dev = candle_core::Device::Cpu;
|
| 233 |
+
let tt = candle_core::Tensor::from_vec(ts, (c, t), &dev)
|
| 234 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 235 |
+
let p = jepa::em_patches_serie(&tt, pt)
|
| 236 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 237 |
+
p.to_vec2::<f32>().map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
/// Extrai grupos FPS de nuvem de pontos (n, d) — Point-JEPA.
|
| 242 |
+
#[pyfunction]
|
| 243 |
+
pub(crate) fn grupos_pontos(pc: Vec<Vec<f64>>, k: usize, m: usize, semente: u64) -> PyResult<Vec<Vec<f64>>> {
|
| 244 |
+
let dev = candle_core::Device::Cpu;
|
| 245 |
+
let t = tensor_de_2d(pc, &dev).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 246 |
+
let mut rng = crate::rng::RngDeterministico::novo(semente);
|
| 247 |
+
let g = jepa::em_grupos_pontos(&t, k, m, &mut rng)
|
| 248 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 249 |
+
let out = g.to_vec2::<f32>().map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 250 |
+
Ok(out.into_iter().map(|l| l.into_iter().map(|v| v as f64).collect()).collect())
|
| 251 |
+
}
|
laboratorio/arquivo_split_v100/python/mod.rs
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! FFI Python (PyO3) — dividida por domínio (v0.10.0, r-35 §2).
|
| 2 |
+
|
| 3 |
+
//! FFI Python (PyO3) do KHTST_RUST — todo o `#[pymodule]`, os
|
| 4 |
+
//! `#[pyfunction]`/`#[pyclass]` e a cola Python (conversões,
|
| 5 |
+
//! callbacks, demos) vivem AQUI desde a v0.9.0 (antes: lib.rs,
|
| 6 |
+
//! ~105 kB — crítica "God Object" do agente Qwen3.8, r-34 §5).
|
| 7 |
+
//! A lógica de domínio (src/*.rs) não importa pyo3: `cargo test
|
| 8 |
+
//! --no-default-features` executa a suíte SEM linkar o Python.
|
| 9 |
+
//!
|
| 10 |
+
//! Regra da casa mantida: nenhuma funcionalidade da superfície
|
| 11 |
+
//! Python foi removida — os mesmos símbolos são registrados no
|
| 12 |
+
//! `nucleo_rust`.
|
| 13 |
+
|
| 14 |
+
use pyo3::prelude::*;
|
| 15 |
+
|
| 16 |
+
use crate::*;
|
| 17 |
+
|
| 18 |
+
// ---- divisão SRP v0.10.0 (r-35 §2): submódulos + re-exports ----
|
| 19 |
+
mod calibracao;
|
| 20 |
+
mod demos_qwen;
|
| 21 |
+
mod fnh_arvore;
|
| 22 |
+
mod jepa_treinos;
|
| 23 |
+
mod moe;
|
| 24 |
+
mod nlp_nlg;
|
| 25 |
+
mod nucleo;
|
| 26 |
+
mod pensamento_demos;
|
| 27 |
+
mod som;
|
| 28 |
+
mod treino_fases;
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
// ---- itens mantidos no próprio mod.rs ----
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
/// Adaptador FFI→domínio (v0.9.0): embrulha um callable Python no tipo de
|
| 36 |
+
/// domínio `treino::CallbackTreino` — `treino.rs` não importa pyo3.
|
| 37 |
+
fn callback_treino_de_py(callback: Option<pyo3::Bound<'_, pyo3::PyAny>>) -> treino::CallbackTreino {
|
| 38 |
+
use std::sync::Arc;
|
| 39 |
+
match callback {
|
| 40 |
+
None => None,
|
| 41 |
+
Some(c) => {
|
| 42 |
+
let f: pyo3::Py<pyo3::PyAny> = c.unbind();
|
| 43 |
+
let g: Arc<dyn Fn(&serde_json::Value) + Send + Sync> =
|
| 44 |
+
Arc::new(move |dados: &serde_json::Value| {
|
| 45 |
+
pyo3::Python::with_gil(|py| {
|
| 46 |
+
if let Ok(obj) = pythonize::pythonize(py, dados) {
|
| 47 |
+
let _ = f.call1(py, (obj,));
|
| 48 |
+
}
|
| 49 |
+
});
|
| 50 |
+
});
|
| 51 |
+
Some(g)
|
| 52 |
+
}
|
| 53 |
+
}
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
// ===========================================================================
|
| 58 |
+
// v0.5.0 — suíte SOM 4D, suíte JEPA, Pensamento, telemetria robusta
|
| 59 |
+
// ===========================================================================
|
| 60 |
+
|
| 61 |
+
fn tensor_de_2d(dados: Vec<Vec<f64>>, dev: &candle_core::Device) -> candle_core::Result<candle_core::Tensor> {
|
| 62 |
+
let d = dados.first().map(|r| r.len()).unwrap_or(1).max(1);
|
| 63 |
+
let n = dados.len();
|
| 64 |
+
let flat: Vec<f32> = dados.into_iter().flat_map(|r| r.into_iter().map(|x| x as f32).collect::<Vec<_>>()).collect();
|
| 65 |
+
candle_core::Tensor::from_vec(flat, (n, d), dev)
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
// ---------------------------------------------------------------------------
|
| 70 |
+
// v0.6.0 — verificador NCM (sem oráculo), fase C, MoE redirecionável,
|
| 71 |
+
// acoplador duplex e autoajuste
|
| 72 |
+
// ---------------------------------------------------------------------------
|
| 73 |
+
|
| 74 |
+
/// Converte matriz f64 → Tensor (n, d) F32.
|
| 75 |
+
fn tensor_f64_2d(v: &[Vec<f64>], dev: &candle_core::Device) -> candle_core::Result<candle_core::Tensor> {
|
| 76 |
+
let (n, d) = (v.len(), v.first().map(|l| l.len()).unwrap_or(0));
|
| 77 |
+
candle_core::Tensor::from_vec(v.iter().flatten().cloned().collect(), (n, d), dev)
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
fn py_err(e: candle_core::Error) -> pyo3::PyErr {
|
| 82 |
+
pyo3::exceptions::PyRuntimeError::new_err(format!("{e}"))
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
#[pymodule]
|
| 87 |
+
fn nucleo_rust(m: &Bound<'_, PyModule>) -> PyResult<()> {
|
| 88 |
+
pyo3_log::init();
|
| 89 |
+
m.add_function(wrap_pyfunction!(nucleo::versao, m)?)?;
|
| 90 |
+
m.add_function(wrap_pyfunction!(nucleo::info_build, m)?)?;
|
| 91 |
+
m.add_function(wrap_pyfunction!(nucleo::lint_config, m)?)?;
|
| 92 |
+
m.add_function(wrap_pyfunction!(treino_fases::treinar_fase_a, m)?)?;
|
| 93 |
+
m.add_function(wrap_pyfunction!(treino_fases::treinar_fase_b, m)?)?;
|
| 94 |
+
m.add_function(wrap_pyfunction!(treino_fases::gerar_amostras, m)?)?;
|
| 95 |
+
m.add_function(wrap_pyfunction!(nucleo::verificar_mascara, m)?)?;
|
| 96 |
+
m.add_function(wrap_pyfunction!(nucleo::verificar_stiefel, m)?)?;
|
| 97 |
+
// v0.10.0 — checkpoints atômicos com prova de integridade
|
| 98 |
+
m.add_function(wrap_pyfunction!(nucleo::checkpoint_valido, m)?)?;
|
| 99 |
+
m.add_function(wrap_pyfunction!(nucleo::checkpoint_manifesto, m)?)?;
|
| 100 |
+
m.add_function(wrap_pyfunction!(nucleo::sha256_arquivo, m)?)?;
|
| 101 |
+
// v0.5.0 — SOM 4D / JEPA / Pensamento
|
| 102 |
+
m.add_function(wrap_pyfunction!(som::treinar_som4d, m)?)?;
|
| 103 |
+
m.add_function(wrap_pyfunction!(som::treinar_gng, m)?)?;
|
| 104 |
+
m.add_function(wrap_pyfunction!(som::treinar_hsom, m)?)?;
|
| 105 |
+
m.add_function(wrap_pyfunction!(som::demo_tsom, m)?)?;
|
| 106 |
+
m.add_function(wrap_pyfunction!(jepa_treinos::treinar_jepa, m)?)?;
|
| 107 |
+
m.add_function(wrap_pyfunction!(jepa_treinos::treinar_lejepa, m)?)?;
|
| 108 |
+
m.add_function(wrap_pyfunction!(jepa_treinos::treinar_mcjepa, m)?)?;
|
| 109 |
+
m.add_function(wrap_pyfunction!(jepa_treinos::treinar_bjepa, m)?)?;
|
| 110 |
+
m.add_function(wrap_pyfunction!(jepa_treinos::demo_sonic_moe, m)?)?;
|
| 111 |
+
m.add_function(wrap_pyfunction!(jepa_treinos::demo_replay_ssm, m)?)?;
|
| 112 |
+
m.add_function(wrap_pyfunction!(pensamento_demos::classificar_erro, m)?)?;
|
| 113 |
+
m.add_function(wrap_pyfunction!(pensamento_demos::confianca_de_logits, m)?)?;
|
| 114 |
+
m.add_function(wrap_pyfunction!(pensamento_demos::projetar_ridge, m)?)?;
|
| 115 |
+
m.add_function(wrap_pyfunction!(pensamento_demos::demo_pensamento, m)?)?;
|
| 116 |
+
m.add_function(wrap_pyfunction!(jepa_treinos::patches_2d, m)?)?;
|
| 117 |
+
m.add_function(wrap_pyfunction!(jepa_treinos::patches_serie, m)?)?;
|
| 118 |
+
m.add_function(wrap_pyfunction!(jepa_treinos::grupos_pontos, m)?)?;
|
| 119 |
+
// v0.6.0
|
| 120 |
+
m.add_function(wrap_pyfunction!(calibracao::calibrar_verificador, m)?)?;
|
| 121 |
+
m.add_function(wrap_pyfunction!(calibracao::demo_verificador_ncm, m)?)?;
|
| 122 |
+
m.add_function(wrap_pyfunction!(treino_fases::treinar_fase_c, m)?)?;
|
| 123 |
+
m.add_function(wrap_pyfunction!(moe::demo_moe_redirecionavel, m)?)?;
|
| 124 |
+
m.add_function(wrap_pyfunction!(moe::jepa_com_moe, m)?)?;
|
| 125 |
+
m.add_function(wrap_pyfunction!(moe::som_com_moe, m)?)?;
|
| 126 |
+
m.add_function(wrap_pyfunction!(moe::demo_acoplador_duplo, m)?)?;
|
| 127 |
+
m.add_function(wrap_pyfunction!(pensamento_demos::demo_pensamento_ncm, m)?)?;
|
| 128 |
+
m.add_function(wrap_pyfunction!(pensamento_demos::demo_autoajuste, m)?)?;
|
| 129 |
+
m.add_function(wrap_pyfunction!(fnh_arvore::demo_fnh, m)?)?;
|
| 130 |
+
m.add_function(wrap_pyfunction!(fnh_arvore::demo_quebra_cabeca, m)?)?;
|
| 131 |
+
m.add_function(wrap_pyfunction!(fnh_arvore::quebra_cabeca_real, m)?)?;
|
| 132 |
+
m.add_function(wrap_pyfunction!(nlp_nlg::demo_nlp_nlg, m)?)?;
|
| 133 |
+
m.add_function(wrap_pyfunction!(som::demo_autoajuste_som, m)?)?;
|
| 134 |
+
// v0.8.0 — análise/prova/teste das propostas Qwen3.8
|
| 135 |
+
m.add_function(wrap_pyfunction!(demos_qwen::demo_qwen_v080, m)?)?;
|
| 136 |
+
// v0.9.0 — veredito executável das críticas Qwen3.8 (r-34)
|
| 137 |
+
m.add_function(wrap_pyfunction!(demos_qwen::demo_criticas_v090, m)?)?;
|
| 138 |
+
m.add_class::<nucleo::BpePy>()?;
|
| 139 |
+
m.add_class::<nucleo::ConfigPy>()?;
|
| 140 |
+
m.add_class::<nucleo::PonteDuplaPy>()?;
|
| 141 |
+
#[cfg(feature = "ponte_async")]
|
| 142 |
+
m.add_class::<nucleo::PonteAsyncPy>()?;
|
| 143 |
+
m.add_class::<fnh_arvore::ArvorePesosPy>()?;
|
| 144 |
+
Ok(())
|
| 145 |
+
}
|
laboratorio/arquivo_split_v100/python/moe.rs
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! `python::moe` — extraído do monólito na v0.10.0
|
| 2 |
+
//! (divisão SRP, crítica Qwen3.8 lote 3 nº 1; r-35 §2).
|
| 3 |
+
|
| 4 |
+
use super::*;
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
/// **MoE redirecionável — demo completa (M-R1..M-R5):** neutralidade da
|
| 8 |
+
/// atenção própria (M-R2), invariância de capacidade/perda auxiliar sob
|
| 9 |
+
/// redirecionamento (M-R1), paralelismo medido (M-R3), water-filling por
|
| 10 |
+
/// QE vs uniforme (M-R5) e fechamento da classe (M-R4 — via permutação).
|
| 11 |
+
#[pyfunction]
|
| 12 |
+
pub(crate) fn demo_moe_redirecionavel(d: usize, n: usize, semente: u64) -> PyResult<PyObject> {
|
| 13 |
+
Python::with_gil(|py| {
|
| 14 |
+
let dev = candle_core::Device::Cpu;
|
| 15 |
+
crate::rng::definir_semente(semente);
|
| 16 |
+
let mut rng = crate::rng::RngDeterministico::novo(semente);
|
| 17 |
+
let x: Vec<f32> = (0..n * d).map(|_| rng.normal(0.0, 1.0) as f32).collect();
|
| 18 |
+
let x = candle_core::Tensor::from_vec(x, (n, d), &dev)
|
| 19 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 20 |
+
let mut moe = moe_redirecionavel::MoeRedirecionavel::novo(d, 8, 2, n, &dev)
|
| 21 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 22 |
+
// M-R2: neutralidade no nascimento
|
| 23 |
+
let g0 = moe.atencao.gate.as_tensor().to_scalar::<f32>().unwrap();
|
| 24 |
+
let y0 = moe.atencao.fwd(&x).unwrap();
|
| 25 |
+
let dif0 = (&y0 - &x).unwrap().sqr().unwrap().sum_all().unwrap()
|
| 26 |
+
.to_scalar::<f32>().unwrap() as f64;
|
| 27 |
+
// abre o gate (mecanismo ativo)
|
| 28 |
+
moe.atencao.gate.set(&candle_core::Tensor::new(1.0f32, &dev).unwrap()).unwrap();
|
| 29 |
+
// M-R1: invariância sob redirecionamento
|
| 30 |
+
let s_enc = moe.forward(&x, moe_redirecionavel::Papel::Codificador).unwrap();
|
| 31 |
+
let carga_antes: usize = s_enc.carga.iter().sum();
|
| 32 |
+
let perda_antes = s_enc.perda_aux.to_scalar::<f32>().unwrap() as f64;
|
| 33 |
+
let permuta: Vec<usize> = (0..8).map(|i| (i + 1) % 8).collect();
|
| 34 |
+
moe.redirecionar(&permuta);
|
| 35 |
+
let s_enc2 = moe.forward(&x, moe_redirecionavel::Papel::Codificador).unwrap();
|
| 36 |
+
let carga_depois: usize = s_enc2.carga.iter().sum();
|
| 37 |
+
let perda_depois = s_enc2.perda_aux.to_scalar::<f32>().unwrap() as f64;
|
| 38 |
+
// M-R3: paralelismo medido (enc ∥ dec em 2 threads)
|
| 39 |
+
let (_e, _dc, t_par, t_seq, speedup) = moe.fwd_ambos_par(&x).unwrap();
|
| 40 |
+
// M-R5: water-filling vs uniforme (cota analítica)
|
| 41 |
+
let qes: Vec<f64> = vec![0.15, 0.4, 1.0, 0.25, 0.6, 0.1, 0.35, 0.5];
|
| 42 |
+
let c_wf = moe_redirecionavel::alocar_por_qe(&qes, 16);
|
| 43 |
+
let c_un = vec![2usize; 8];
|
| 44 |
+
let cota = |c: &[usize]| qes.iter().zip(c).map(|(q, ci)| q * q / *ci as f64).sum::<f64>();
|
| 45 |
+
let (cota_wf, cota_un) = (cota(&c_wf), cota(&c_un));
|
| 46 |
+
let d_ = serde_json::json!({
|
| 47 |
+
"versao": moe_redirecionavel::versao(), "d": d, "n": n,
|
| 48 |
+
"valor_gate_no_nascimento": g0, "neutralidade_dif": dif0,
|
| 49 |
+
"carga_antes": carga_antes, "carga_depois": carga_depois,
|
| 50 |
+
"perda_aux_antes": perda_antes, "perda_aux_depois": perda_depois,
|
| 51 |
+
"t_paralelo_s": t_par, "t_sequencial_s": t_seq, "speedup": speedup,
|
| 52 |
+
"alocacao_water_filling": c_wf, "cota_wf": cota_wf, "cota_uniforme": cota_un,
|
| 53 |
+
"gates": {
|
| 54 |
+
"gate_mr1_capacidade": carga_antes == carga_depois,
|
| 55 |
+
"gate_mr1_perda_aux": (perda_antes - perda_depois).abs() < 2.0 + 1e-6,
|
| 56 |
+
"gate_mr2_neutralidade": dif0 == 0.0 && g0 == 0.0,
|
| 57 |
+
"gate_mr3_paralelismo": t_par < t_seq,
|
| 58 |
+
"gate_mr5_water_filling": cota_wf <= cota_un + 1e-9,
|
| 59 |
+
},
|
| 60 |
+
});
|
| 61 |
+
Ok(pythonize::pythonize(py, &d_)?.into())
|
| 62 |
+
})
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
/// **JEPA com MoE redirecionável (ablação de 3 braços):** `modo` ∈
|
| 67 |
+
/// {"pequena", "densa", "moe"} — o braço "densa" tem a capacidade TOTAL dos
|
| 68 |
+
/// especialistas SEM roteamento (isola o ganho do roteamento em si).
|
| 69 |
+
#[pyfunction]
|
| 70 |
+
pub(crate) fn jepa_com_moe(
|
| 71 |
+
patches: Vec<Vec<f32>>,
|
| 72 |
+
modo: String,
|
| 73 |
+
passos: usize,
|
| 74 |
+
frac_mascara: f64,
|
| 75 |
+
semente: u64,
|
| 76 |
+
) -> PyResult<PyObject> {
|
| 77 |
+
Python::with_gil(|py| {
|
| 78 |
+
let dev = candle_core::Device::Cpu;
|
| 79 |
+
let t = tensor_f64_2d(&patches.into_iter().map(|l| l.into_iter().map(|x| x as f64).collect()).collect::<Vec<Vec<f64>>>(), &dev)
|
| 80 |
+
.and_then(|t| t.to_dtype(candle_core::DType::F32))
|
| 81 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 82 |
+
let modo: &'static str = match modo.as_str() {
|
| 83 |
+
"pequena" => "pequena",
|
| 84 |
+
"densa" => "densa",
|
| 85 |
+
_ => "moe",
|
| 86 |
+
};
|
| 87 |
+
let r = moe_redirecionavel::treinar_jepa_com_moe(&t, modo, passos, frac_mascara, semente)
|
| 88 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 89 |
+
let d_ = serde_json::json!({
|
| 90 |
+
"modo": r.modo, "perda_pred_inicial": r.perda_pred_inicial,
|
| 91 |
+
"perda_pred_final": r.perda_pred_final, "perda_vc_final": r.perda_vc_final,
|
| 92 |
+
"std_emb": r.std_emb, "carga_max": r.carga_max, "descartados": r.descartados,
|
| 93 |
+
"queda_abs": r.perda_pred_inicial - r.perda_pred_final,
|
| 94 |
+
"aprendeu": r.perda_pred_final < r.perda_pred_inicial,
|
| 95 |
+
});
|
| 96 |
+
Ok(pythonize::pythonize(py, &d_)?.into())
|
| 97 |
+
})
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
/// **SOM refinado por MoE com water-filling (M-R5) + redirecionamento
|
| 102 |
+
/// para decodificador:** treina um 4D-SOM, refina com MoE (QE′ < QE),
|
| 103 |
+
/// compara com alocação uniforme e mede a decodificação pós-redirect.
|
| 104 |
+
#[pyfunction]
|
| 105 |
+
pub(crate) fn som_com_moe(
|
| 106 |
+
dados: Vec<Vec<f64>>,
|
| 107 |
+
lado: usize,
|
| 108 |
+
passos: usize,
|
| 109 |
+
semente: u64,
|
| 110 |
+
) -> PyResult<PyObject> {
|
| 111 |
+
Python::with_gil(|py| {
|
| 112 |
+
let dev = candle_core::Device::Cpu;
|
| 113 |
+
let t = tensor_f64_2d(&dados, &dev)
|
| 114 |
+
.and_then(|t| t.to_dtype(candle_core::DType::F32))
|
| 115 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 116 |
+
// treina o 4D-SOM (r-19: S4-1/S4-2/S4-3) — som4d opera em F32
|
| 117 |
+
let cfg_som = som4d::CfgSom4D { nx: lado, ny: lado, nz: lado, nt: lado, ..Default::default() };
|
| 118 |
+
let som = som4d::treinar_som4d(&t, &cfg_som, &dev)
|
| 119 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 120 |
+
let centroides: Vec<Vec<f64>> = som.prototipos.clone();
|
| 121 |
+
// refinamento MoE (mesmo tensor F32; centroides seguem em f64)
|
| 122 |
+
let r = moe_redirecionavel::refinar_som_com_moe(&t, ¢roides, passos, semente)
|
| 123 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 124 |
+
let d_ = serde_json::json!({
|
| 125 |
+
"qe_antes": r.qe_antes, "qe_depois_water_filling": r.qe_depois,
|
| 126 |
+
"qe_depois_uniforme": r.qe_alocacao_uniforme,
|
| 127 |
+
"carga_por_celula": r.carga_por_celula,
|
| 128 |
+
"tempo_treino_s": r.tempo_treino_s,
|
| 129 |
+
"mse_decodificador_pos_redirect": r.mse_decodificador,
|
| 130 |
+
"reducao_qe_pct": 100.0 * (r.qe_antes - r.qe_depois) / r.qe_antes.max(1e-12),
|
| 131 |
+
"gates": {
|
| 132 |
+
"gate_moe_refina": r.qe_depois < r.qe_antes,
|
| 133 |
+
"gate_wf_melhor_uniforme": r.qe_depois <= r.qe_alocacao_uniforme * 1.02,
|
| 134 |
+
"gate_redirect_decodifica": r.mse_decodificador < r.qe_antes.powi(2),
|
| 135 |
+
},
|
| 136 |
+
});
|
| 137 |
+
Ok(pythonize::pythonize(py, &d_)?.into())
|
| 138 |
+
})
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
/// **AcopladorDuplo — demo do protocolo lag-1 síncrono** (AC-1/AC-2):
|
| 143 |
+
/// rodadas duplex Pensamento↔backbone com correções decaindo (co-adaptação)
|
| 144 |
+
/// e confiança subindo; zero deadlocks/timeouts (P.1/P.2 herdados).
|
| 145 |
+
#[pyfunction]
|
| 146 |
+
pub(crate) fn demo_acoplador_duplo(rodadas: usize, timeout_ms: u64) -> PyResult<PyObject> {
|
| 147 |
+
Python::with_gil(|py| {
|
| 148 |
+
let mut ac = acoplador::AcopladorDuplo::nova(16, timeout_ms);
|
| 149 |
+
let mut rng = crate::rng::RngDeterministico::novo(77);
|
| 150 |
+
let mut conf = 0.05f64;
|
| 151 |
+
let mut traj = Vec::new();
|
| 152 |
+
for k in 0..rodadas {
|
| 153 |
+
let estado = acoplador::EstadoModelo {
|
| 154 |
+
a: vec![0.1 * (k % 7) as f32; 16],
|
| 155 |
+
b: vec![rng.normal(0.0, 0.3) as f32; 16],
|
| 156 |
+
c: vec![0.05; 8],
|
| 157 |
+
confianca: conf,
|
| 158 |
+
nivel: k % 7,
|
| 159 |
+
passo: k,
|
| 160 |
+
};
|
| 161 |
+
let _ = ac.rodada(estado).map_err(|e|
|
| 162 |
+
pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 163 |
+
// correção fresca: decaindo com a confiança (co-adaptação)
|
| 164 |
+
let amplitude = (1.0 - conf).max(0.05);
|
| 165 |
+
let delta: Vec<f32> = (0..16).map(|i| amplitude as f32 * ((i % 5) as f32 - 2.0) * 0.1).collect();
|
| 166 |
+
ac.registrar_correcao(acoplador::Correcao {
|
| 167 |
+
delta, acordo: 0.6 + 0.3 * conf, confianca_agregada: conf,
|
| 168 |
+
iteracao: k, pesos: vec![0.25; 4],
|
| 169 |
+
});
|
| 170 |
+
traj.push(conf);
|
| 171 |
+
conf = (conf + 0.04 + rng.uniforme() * 0.02).min(0.99);
|
| 172 |
+
}
|
| 173 |
+
let t = &ac.telemetria;
|
| 174 |
+
let p = ac.estatisticas();
|
| 175 |
+
let d_ = serde_json::json!({
|
| 176 |
+
"versao": acoplador::versao(), "rodadas": t.rodadas,
|
| 177 |
+
"timeouts": t.timeouts, "tempo_total_ms": t.tempo_total_ms,
|
| 178 |
+
"soma_norma_delta": t.soma_norma_delta,
|
| 179 |
+
"conf_final": traj.last(), "conf_trajetoria_len": traj.len(),
|
| 180 |
+
"envios_a_para_b": p.envios_a_para_b, "envios_b_para_a": p.envios_b_para_a,
|
| 181 |
+
"maior_sobreposicao_us": t.maior_sobreposicao_us,
|
| 182 |
+
"gates": {
|
| 183 |
+
"gate_terminou": t.rodadas == rodadas as u64,
|
| 184 |
+
"gate_sem_timeout": t.timeouts == 0,
|
| 185 |
+
"gate_duplex_simultaneo": p.envios_a_para_b == p.envios_b_para_a && p.envios_a_para_b == rodadas as u64,
|
| 186 |
+
},
|
| 187 |
+
});
|
| 188 |
+
Ok(pythonize::pythonize(py, &d_)?.into())
|
| 189 |
+
})
|
| 190 |
+
}
|
laboratorio/arquivo_split_v100/python/nlp_nlg.rs
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! `python::nlp_nlg` — extraído do monólito na v0.10.0
|
| 2 |
+
//! (divisão SRP, crítica Qwen3.8 lote 3 nº 1; r-35 §2).
|
| 3 |
+
|
| 4 |
+
use super::*;
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
/// Demo/gate das unidades NLP/NLG sobre estados ocultos sintéticos
|
| 8 |
+
/// (nascimento neutro + gates + coerência de bigramas + especulativo).
|
| 9 |
+
#[pyfunction]
|
| 10 |
+
#[pyo3(signature = (d=32, t=6, seed=11))]
|
| 11 |
+
pub(crate) fn demo_nlp_nlg(py: Python, d: usize, t: usize, seed: u64) -> PyResult<PyObject> {
|
| 12 |
+
let dev = candle_core::Device::Cpu;
|
| 13 |
+
let mut rng = rng::RngDeterministico::novo(seed);
|
| 14 |
+
let v: Vec<f32> = (0..2 * t * d).map(|_| rng.normal_padrao() as f32).collect();
|
| 15 |
+
let h = candle_core::Tensor::from_vec(v, (2, t, d), &dev).map_err(py_err)?;
|
| 16 |
+
// NLP: enriquecimento aditivo — neutro no nascimento
|
| 17 |
+
let mut nlp = nlp::UnidadeNlp::nova(d, &dev).map_err(|e| {
|
| 18 |
+
pyo3::exceptions::PyRuntimeError::new_err(format!("nlp (d%4): {e}"))
|
| 19 |
+
})?;
|
| 20 |
+
let h_enr = nlp.enriquecer(&h).map_err(py_err)?;
|
| 21 |
+
let dif_nlp = (&h).sub(&h_enr).map_err(py_err)?.abs().map_err(py_err)?.max_all().map_err(py_err)?.to_scalar::<f32>().map_err(py_err)? as f64;
|
| 22 |
+
// intenção
|
| 23 |
+
let (intencoes, confs) = nlp.intencao_argmax(&h).map_err(py_err)?;
|
| 24 |
+
// NLG: plano + condicionamento neutro + coerência
|
| 25 |
+
let mut nlg = nlg::UnidadeNlg::nova(d, 4096, &dev).map_err(py_err)?;
|
| 26 |
+
let plano = nlg.plano(&h).map_err(py_err)?;
|
| 27 |
+
let p8 = candle_core::Tensor::randn(0f32, 1f32, (nlg::N_EIXOS_ESTILO,), &dev).map_err(py_err)?;
|
| 28 |
+
let p01 = candle_nn::ops::sigmoid(&p8).map_err(py_err)?;
|
| 29 |
+
let h_cond = nlg.condicionar(&h, Some(&p01)).map_err(py_err)?;
|
| 30 |
+
let dif_nlg = (&h).sub(&h_cond).map_err(py_err)?.abs().map_err(py_err)?.max_all().map_err(py_err)?.to_scalar::<f32>().map_err(py_err)? as f64;
|
| 31 |
+
// coerência: contexto observado vs candidato novo
|
| 32 |
+
let ctx = vec![5u32, 6, 7, 8, 9];
|
| 33 |
+
nlg.observar_contexto(&ctx);
|
| 34 |
+
let s_mesmo = nlg.score_coerencia(&ctx);
|
| 35 |
+
let s_novo = nlg.score_coerencia(&[50u32, 51, 52, 53]);
|
| 36 |
+
// especulativo: aceitação típica + stats
|
| 37 |
+
let mut espec = nlg::DecodificadorEspeculativo::novo(4, 0.95, 10);
|
| 38 |
+
let logits = candle_core::Tensor::from_vec(vec![3.0f32, 0.2, 0.1, 0.05], (4,), &dev)
|
| 39 |
+
.map_err(py_err)?;
|
| 40 |
+
let mut aceites = 0usize;
|
| 41 |
+
for _ in 0..30 {
|
| 42 |
+
let (_, ok) = espec.verificar_e_corrigir(&logits, &[0, 1]).map_err(py_err)?;
|
| 43 |
+
if ok {
|
| 44 |
+
aceites += 1;
|
| 45 |
+
}
|
| 46 |
+
}
|
| 47 |
+
let d_ = serde_json::json!({
|
| 48 |
+
"versao": "nlp-nlg-0.7.0",
|
| 49 |
+
"nlp_gate_medio": nlp.gate_medio,
|
| 50 |
+
"nlp_dif_nascimento": dif_nlp,
|
| 51 |
+
"nlp_intencoes": intencoes,
|
| 52 |
+
"nlp_confiancas": confs,
|
| 53 |
+
"nlg_plano_forma": plano.dims(),
|
| 54 |
+
"nlg_dif_nascimento": dif_nlg,
|
| 55 |
+
"nlg_coerencia_mesmo": s_mesmo,
|
| 56 |
+
"nlg_coerencia_novo": s_novo,
|
| 57 |
+
"espec_aceitacao_media": espec.stats.aceitacao_media,
|
| 58 |
+
"espec_speedup": espec.stats.speedup_estimado,
|
| 59 |
+
"espec_aceites_30": aceites,
|
| 60 |
+
"gates": {
|
| 61 |
+
"nlp_neutro": dif_nlp == 0.0,
|
| 62 |
+
"nlg_neutro": dif_nlg == 0.0,
|
| 63 |
+
"gate_medio_ok": (nlp.gate_medio - 0.119).abs() < 0.05,
|
| 64 |
+
"coerencia_ok": s_mesmo > 0.9 && s_novo < 0.1,
|
| 65 |
+
"espec_ok": espec.stats.aceitacao_media > 0.8,
|
| 66 |
+
},
|
| 67 |
+
});
|
| 68 |
+
Ok(pythonize::pythonize(py, &d_)?.into())
|
| 69 |
+
}
|
laboratorio/arquivo_split_v100/python/nucleo.rs
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! `python::nucleo` — extraído do monólito na v0.10.0
|
| 2 |
+
//! (divisão SRP, crítica Qwen3.8 lote 3 nº 1; r-35 §2).
|
| 3 |
+
|
| 4 |
+
use super::*;
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
#[pyfunction]
|
| 8 |
+
pub(crate) fn versao() -> &'static str {
|
| 9 |
+
concat!("khtst-rust-", env!("CARGO_PKG_VERSION"))
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
#[pyfunction]
|
| 14 |
+
pub(crate) fn info_build() -> String {
|
| 15 |
+
format!(
|
| 16 |
+
"rustc={}; perfil={}; features={}; alvo={}",
|
| 17 |
+
build_info::RUSTC_VERSION,
|
| 18 |
+
build_info::PROFILE,
|
| 19 |
+
build_info::FEATURES_STR,
|
| 20 |
+
build_info::TARGET,
|
| 21 |
+
)
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
/// Lint de config com sugestões por Levenshtein (diagnóstico de digitação).
|
| 26 |
+
#[pyfunction]
|
| 27 |
+
pub(crate) fn lint_config(py: Python, caminho: &str) -> PyResult<PyObject> {
|
| 28 |
+
let txt = std::fs::read_to_string(caminho)
|
| 29 |
+
.map_err(|e| pyo3::exceptions::PyIOError::new_err(format!("{caminho}: {e}")))?;
|
| 30 |
+
let v: serde_json::Value = serde_json::from_str(&txt)
|
| 31 |
+
.map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("JSON inválido: {e}")))?;
|
| 32 |
+
let achatado = diagnostico::achatar(&v);
|
| 33 |
+
let avisos = diagnostico::lint_chaves(&achatado);
|
| 34 |
+
let saida: Vec<serde_json::Value> = avisos
|
| 35 |
+
.iter()
|
| 36 |
+
.map(|a| serde_json::json!({
|
| 37 |
+
"chave": a.chave, "sugestao": a.sugestao, "causa": a.causa, "correcao": a.correcao,
|
| 38 |
+
}))
|
| 39 |
+
.collect();
|
| 40 |
+
Ok(pythonize::pythonize(py, &serde_json::json!(saida))?.into())
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
#[pyclass(name = "Bpe")]
|
| 45 |
+
pub(crate) struct BpePy {
|
| 46 |
+
bpe: tokens::Bpe,
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
#[pymethods]
|
| 50 |
+
impl BpePy {
|
| 51 |
+
#[staticmethod]
|
| 52 |
+
fn treinar(textos: Vec<String>, vocab_alvo: usize) -> PyResult<Self> {
|
| 53 |
+
Ok(BpePy { bpe: tokens::Bpe::treinar(&textos, vocab_alvo) })
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
#[staticmethod]
|
| 57 |
+
fn carregar(caminho: &str) -> PyResult<Self> {
|
| 58 |
+
let txt = std::fs::read_to_string(caminho)
|
| 59 |
+
.map_err(|e| pyo3::exceptions::PyIOError::new_err(format!("{e}")))?;
|
| 60 |
+
let v: serde_json::Value = serde_json::from_str(&txt)
|
| 61 |
+
.map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("JSON inválido: {e}")))?;
|
| 62 |
+
let bpe = tokens::Bpe::de_json(&v)
|
| 63 |
+
.ok_or_else(|| pyo3::exceptions::PyValueError::new_err("formato BPE inválido"))?;
|
| 64 |
+
Ok(BpePy { bpe })
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
fn codificar(&mut self, texto: &str) -> Vec<u32> {
|
| 68 |
+
self.bpe.codificar(texto)
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
fn decodificar(&self, ids: Vec<u32>) -> String {
|
| 72 |
+
self.bpe.decodificar(&ids)
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
fn salvar(&self, caminho: &str) -> PyResult<()> {
|
| 76 |
+
let txt = serde_json::to_string(&self.bpe.para_json()).unwrap();
|
| 77 |
+
crate::checkpoint::salvar_atomico(caminho, &txt)
|
| 78 |
+
.map_err(|e| pyo3::exceptions::PyIOError::new_err(format!("{e}")))?;
|
| 79 |
+
Ok(())
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
#[getter]
|
| 83 |
+
fn n_vocab(&self) -> usize {
|
| 84 |
+
self.bpe.n_vocab()
|
| 85 |
+
}
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
#[pyclass(name = "Config")]
|
| 90 |
+
pub(crate) struct ConfigPy {
|
| 91 |
+
pub(crate) cfg: config::ConfigKhtst,
|
| 92 |
+
caminho: Option<String>,
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
#[pymethods]
|
| 96 |
+
impl ConfigPy {
|
| 97 |
+
#[new]
|
| 98 |
+
#[allow(never_type_fallback)]
|
| 99 |
+
#[pyo3(signature = (caminho=None))]
|
| 100 |
+
fn new(caminho: Option<String>) -> PyResult<Self> {
|
| 101 |
+
let cfg = match &caminho {
|
| 102 |
+
Some(c) => {
|
| 103 |
+
let txt = std::fs::read_to_string(c)
|
| 104 |
+
.map_err(|e| pyo3::exceptions::PyIOError::new_err(format!("{c}: {e}")))?;
|
| 105 |
+
let v: serde_json::Value = serde_json::from_str(&txt)
|
| 106 |
+
.map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("JSON inválido: {e}")))?;
|
| 107 |
+
serde_json::from_value(v)
|
| 108 |
+
.map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("config: {e}")))?
|
| 109 |
+
}
|
| 110 |
+
None => config::ConfigKhtst::default(),
|
| 111 |
+
};
|
| 112 |
+
cfg.validar().map_err(pyo3::exceptions::PyValueError::new_err)?;
|
| 113 |
+
Ok(ConfigPy { cfg, caminho })
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
fn validar(&self) -> PyResult<()> {
|
| 117 |
+
self.cfg.validar().map_err(pyo3::exceptions::PyValueError::new_err)
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
fn checar_orcamento_cache(&self) -> PyResult<usize> {
|
| 121 |
+
self.cfg.checar_orcamento_cache().map_err(pyo3::exceptions::PyValueError::new_err)
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
fn resumo(&self) -> String {
|
| 125 |
+
format!(
|
| 126 |
+
"modelo(vocab={}, d={}, camadas={}, ctx={}) ncm(L={}, niveis={:?}, K={}, d_lat={}, modo={}, ativo={})",
|
| 127 |
+
self.cfg.modelo.vocab, self.cfg.modelo.d_modelo, self.cfg.modelo.n_camadas,
|
| 128 |
+
self.cfg.modelo.comprimento_ctx, self.cfg.l_niveis(), self.cfg.ncm.niveis,
|
| 129 |
+
self.cfg.ncm.k_por_nivel, self.cfg.ncm.d_lat, self.cfg.ncm.modo_quantizacao, self.cfg.ncm.ativo,
|
| 130 |
+
)
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
#[getter]
|
| 134 |
+
fn l_niveis(&self) -> usize {
|
| 135 |
+
self.cfg.l_niveis()
|
| 136 |
+
}
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
#[pyclass(name = "PonteDupla")]
|
| 141 |
+
pub(crate) struct PonteDuplaPy {
|
| 142 |
+
ponte: ponte::PonteDupla,
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
#[pymethods]
|
| 146 |
+
impl PonteDuplaPy {
|
| 147 |
+
#[new]
|
| 148 |
+
#[pyo3(signature = (capacidade=64, timeout_ms=2000))]
|
| 149 |
+
fn new(capacidade: usize, timeout_ms: u64) -> Self {
|
| 150 |
+
PonteDuplaPy { ponte: ponte::PonteDupla::nova(capacidade, timeout_ms) }
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
fn rodada(&self, carga_a: Vec<f32>, carga_b: Vec<f32>, nivel: usize) -> PyResult<(Vec<f32>, Vec<f32>)> {
|
| 154 |
+
let (ma, mb) = self.ponte.rodada(carga_a, carga_b, nivel)
|
| 155 |
+
.map_err(pyo3::exceptions::PyRuntimeError::new_err)?;
|
| 156 |
+
Ok((ma.carga, mb.carga))
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
fn demo_professor_aluno(&self, rodadas: usize, dim: usize) -> PyResult<PyObject> {
|
| 160 |
+
let inicio: Vec<f32> = (0..dim).map(|i| (i as f32) * 0.01).collect();
|
| 161 |
+
let stats = ponte::demo_professor_aluno(&self.ponte, rodadas, inicio, &|a, _| {
|
| 162 |
+
a.iter().map(|x| x * 1.05).collect()
|
| 163 |
+
})
|
| 164 |
+
.map_err(pyo3::exceptions::PyRuntimeError::new_err)?;
|
| 165 |
+
Python::with_gil(|py| {
|
| 166 |
+
Ok(pythonize::pythonize(py, &serde_json::to_value(&stats).unwrap())?.into())
|
| 167 |
+
})
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
fn estatisticas(&self) -> PyResult<PyObject> {
|
| 171 |
+
let s = self.ponte.estatisticas();
|
| 172 |
+
Python::with_gil(|py| {
|
| 173 |
+
Ok(pythonize::pythonize(py, &serde_json::to_value(&s).unwrap())?.into())
|
| 174 |
+
})
|
| 175 |
+
}
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
#[cfg(feature = "ponte_async")]
|
| 180 |
+
#[pyclass(name = "PonteAsync")]
|
| 181 |
+
pub(crate) struct PonteAsyncPy {
|
| 182 |
+
interna: std::sync::Arc<ponte::assincrona::PonteAsync>,
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
#[cfg(feature = "ponte_async")]
|
| 186 |
+
#[pymethods]
|
| 187 |
+
impl PonteAsyncPy {
|
| 188 |
+
#[new]
|
| 189 |
+
#[pyo3(signature = (capacidade=64, timeout_ms=2000))]
|
| 190 |
+
fn new(capacidade: usize, timeout_ms: u64) -> Self {
|
| 191 |
+
PonteAsyncPy { interna: std::sync::Arc::new(ponte::assincrona::PonteAsync::nova(capacidade, timeout_ms)) }
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
/// Corrotina: `await ponte.trocar(a, b, nivel)` — duplex simultânea.
|
| 195 |
+
fn trocar<'p>(&self, py: Python<'p>, carga_a: Vec<f32>, carga_b: Vec<f32>, nivel: usize) -> PyResult<Bound<'p, PyAny>> {
|
| 196 |
+
let p = self.interna.clone();
|
| 197 |
+
pyo3_async_runtimes::tokio::future_into_py(py, async move {
|
| 198 |
+
let (ma, mb) = p.rodada_async(carga_a, carga_b, nivel)
|
| 199 |
+
.await
|
| 200 |
+
.map_err(pyo3::exceptions::PyRuntimeError::new_err)?;
|
| 201 |
+
Ok::<_, PyErr>((ma.carga, mb.carga))
|
| 202 |
+
})
|
| 203 |
+
}
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
/// Utilitários de prova expostos ao Python (V-série da suíte).
|
| 208 |
+
#[pyfunction]
|
| 209 |
+
pub(crate) fn verificar_mascara(cfg: &ConfigPy) -> PyResult<usize> {
|
| 210 |
+
let dev = candle_core::Device::Cpu;
|
| 211 |
+
let m = mascaras::mascara_block_causal(&cfg.cfg.ncm.niveis, gerador::N_PREFIXO, &dev)
|
| 212 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 213 |
+
mascaras::contar_vazamentos(&cfg.cfg.ncm.niveis, gerador::N_PREFIXO, &m)
|
| 214 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
#[pyfunction]
|
| 219 |
+
pub(crate) fn verificar_stiefel(k: usize, d: usize) -> PyResult<f64> {
|
| 220 |
+
let dev = candle_core::Device::Cpu;
|
| 221 |
+
let c = stiefel::init_stiefel(k, d, &dev)
|
| 222 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 223 |
+
stiefel::erro_ortogonalidade(&c.transpose(0, 1).unwrap()).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
#[pyfunction]
|
| 227 |
+
pub(crate) fn checkpoint_valido(caminho: &str) -> bool {
|
| 228 |
+
crate::checkpoint::validar(caminho)
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
#[pyfunction]
|
| 232 |
+
pub(crate) fn checkpoint_manifesto(caminho: &str) -> Option<String> {
|
| 233 |
+
std::fs::read_to_string(crate::checkpoint::caminho_manifesto(caminho)).ok()
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
#[pyfunction]
|
| 237 |
+
pub(crate) fn sha256_arquivo(caminho: &str) -> Option<String> {
|
| 238 |
+
std::fs::read(caminho).ok().map(|d| crate::checkpoint::sha256_hex(&d))
|
| 239 |
+
}
|
laboratorio/arquivo_split_v100/python/pensamento_demos.rs
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! `python::pensamento_demos` — extraído do monólito na v0.10.0
|
| 2 |
+
//! (divisão SRP, crítica Qwen3.8 lote 3 nº 1; r-35 §2).
|
| 3 |
+
|
| 4 |
+
use super::*;
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
/// Classificação de erro por taxonomia (diagnóstico de refatoração).
|
| 8 |
+
#[pyfunction]
|
| 9 |
+
pub(crate) fn classificar_erro(msg: String) -> Vec<(String, String, String)> {
|
| 10 |
+
diagnostico::classificar_erro(&msg)
|
| 11 |
+
.into_iter()
|
| 12 |
+
.map(|(a, b, c)| (a.to_string(), b.to_string(), c.to_string()))
|
| 13 |
+
.collect()
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
/// Confiança de uma distribuição (T-P1): `1 − H(softmax(z))/log K`.
|
| 18 |
+
#[pyfunction]
|
| 19 |
+
pub(crate) fn confianca_de_logits(logits: Vec<f32>) -> PyResult<f64> {
|
| 20 |
+
let dev = candle_core::Device::Cpu;
|
| 21 |
+
let k = logits.len();
|
| 22 |
+
let t = candle_core::Tensor::from_vec(logits, (1, k), &dev)
|
| 23 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 24 |
+
pensamento::confianca_de_logits(&t).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
/// Projeção ridge (T-P3 — montador algébrico): `r* = (WᵀW+εI)⁻¹Wᵀr`.
|
| 29 |
+
#[pyfunction]
|
| 30 |
+
pub(crate) fn projetar_ridge(w: Vec<Vec<f64>>, r_alvo: Vec<Vec<f64>>, eps: f64) -> PyResult<Vec<Vec<f64>>> {
|
| 31 |
+
let dev = candle_core::Device::Cpu;
|
| 32 |
+
let wt = tensor_de_2d(w, &dev).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 33 |
+
let rt = tensor_de_2d(r_alvo, &dev).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 34 |
+
let r = pensamento::projetar_ridge(&wt, &rt, eps)
|
| 35 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 36 |
+
let out = r.to_vec2::<f32>().map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 37 |
+
Ok(out.into_iter().map(|l| l.into_iter().map(|v| v as f64).collect()).collect())
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
/// Demo completa da tecnologia Pensamento: treino cooperativo das N redes
|
| 42 |
+
/// (item a) + ciclo d com verificador externo simulado + telemetria.
|
| 43 |
+
#[pyfunction]
|
| 44 |
+
pub(crate) fn demo_pensamento(
|
| 45 |
+
py: Python,
|
| 46 |
+
d_cond: usize,
|
| 47 |
+
d_saida: usize,
|
| 48 |
+
n_tentativas: usize,
|
| 49 |
+
passos_treino: usize,
|
| 50 |
+
limiar_conf: f64,
|
| 51 |
+
orcamento: usize,
|
| 52 |
+
semente: u64,
|
| 53 |
+
) -> PyResult<PyObject> {
|
| 54 |
+
use candle_core::Tensor;
|
| 55 |
+
let dev = candle_core::Device::Cpu;
|
| 56 |
+
crate::rng::definir_semente(semente);
|
| 57 |
+
let mut motor = pensamento::MotorPensamento::novo(d_cond, d_saida, n_tentativas, limiar_conf, orcamento, &dev)
|
| 58 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 59 |
+
let mut otim = crate::treino::AdamWManual::novo(motor.vars(), 5e-3, 0.0);
|
| 60 |
+
let mut rng = crate::rng::RngDeterministico::novo(semente);
|
| 61 |
+
|
| 62 |
+
// dados sintéticos: alvo = função determinística não-linear de cond (d=a+b+c)
|
| 63 |
+
let n_dados = 256usize;
|
| 64 |
+
let conds: Vec<Vec<f32>> = (0..n_dados)
|
| 65 |
+
.map(|_| (0..d_cond).map(|_| rng.normal(0.0, 1.0) as f32).collect())
|
| 66 |
+
.collect();
|
| 67 |
+
let alvos: Vec<Vec<f32>> = conds
|
| 68 |
+
.iter()
|
| 69 |
+
.map(|c| {
|
| 70 |
+
(0..d_saida)
|
| 71 |
+
.map(|j| {
|
| 72 |
+
let cj = c[j % d_cond];
|
| 73 |
+
let ck = c[(j + 1) % d_cond];
|
| 74 |
+
0.5 * cj + 0.3 * cj * ck + 0.1
|
| 75 |
+
})
|
| 76 |
+
.collect()
|
| 77 |
+
})
|
| 78 |
+
.collect();
|
| 79 |
+
let cond_t = Tensor::from_vec(conds.into_iter().flatten().collect(), (n_dados, d_cond), &dev)
|
| 80 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 81 |
+
let alvo_t = Tensor::from_vec(alvos.into_iter().flatten().collect(), (n_dados, d_saida), &dev)
|
| 82 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 83 |
+
|
| 84 |
+
// item a: treino cooperativo
|
| 85 |
+
let mut perda_hist = Vec::new();
|
| 86 |
+
for passo in 0..passos_treino {
|
| 87 |
+
let perda = motor.perda_treino(&cond_t, &alvo_t)
|
| 88 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 89 |
+
perda_hist.push(perda.to_scalar::<f32>().map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))? as f64);
|
| 90 |
+
otim.passo(crate::treino::grads_achatados(&perda, &motor.vars())
|
| 91 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?);
|
| 92 |
+
let _ = passo;
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
// item c+d: consulta fora do padrão (OOD) — confiança baixa ⇒ Pensamento
|
| 96 |
+
let consulta: Vec<f32> = (0..d_cond).map(|j| 3.0 + (j as f32) * 0.1).collect();
|
| 97 |
+
let consulta_t = Tensor::from_vec(consulta, (d_cond,), &dev)
|
| 98 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 99 |
+
// verificador externo: negativo do MSE contra o alvo verdadeiro da consulta
|
| 100 |
+
let alvo_verdadeiro: Vec<f32> = (0..d_saida)
|
| 101 |
+
.map(|j| {
|
| 102 |
+
let cj = 3.0 + (j % d_cond) as f32 * 0.1;
|
| 103 |
+
let ck = 3.0 + ((j + 1) % d_cond) as f32 * 0.1;
|
| 104 |
+
0.5 * cj + 0.3 * cj * ck + 0.1
|
| 105 |
+
})
|
| 106 |
+
.collect();
|
| 107 |
+
let alvo_verd = Tensor::from_vec(alvo_verdadeiro.clone(), (d_saida,), &dev)
|
| 108 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 109 |
+
let verifica = |resp: &Tensor| -> f64 {
|
| 110 |
+
// confiança = 1/(1+10·MSE) — medível e causaL (só da resposta)
|
| 111 |
+
let dif = (resp.broadcast_as((1, d_saida)).unwrap() - &alvo_verd.broadcast_as((1, d_saida)).unwrap()).unwrap();
|
| 112 |
+
let mse = dif.sqr().unwrap().mean_all().unwrap().to_scalar::<f32>().unwrap() as f64;
|
| 113 |
+
1.0 / (1.0 + 10.0 * mse)
|
| 114 |
+
};
|
| 115 |
+
let mut rng2 = crate::rng::RngDeterministico::novo(semente + 1);
|
| 116 |
+
let res = motor.raciocinar(&consulta_t, &verifica, &mut rng2)
|
| 117 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 118 |
+
|
| 119 |
+
// linha de base SEM pensamento: uma tentativa isolada, sem agregação
|
| 120 |
+
let base = motor.tentativas[0].fwd(&consulta_t.broadcast_as((1, d_cond)).unwrap())
|
| 121 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 122 |
+
let conf_base = verifica(&base);
|
| 123 |
+
let conf_pensamento = res.confianca;
|
| 124 |
+
|
| 125 |
+
let d_ = serde_json::json!({
|
| 126 |
+
"versao": pensamento::versao(),
|
| 127 |
+
"n_tentativas": n_tentativas,
|
| 128 |
+
"perda_treino_inicial": perda_hist.first(),
|
| 129 |
+
"perda_treino_final": perda_hist.last(),
|
| 130 |
+
"treino_aprendeu": perda_hist.last().copied().unwrap_or(f64::INFINITY) < perda_hist.first().copied().map(|p| p * 0.5).unwrap_or(f64::INFINITY),
|
| 131 |
+
"iteracoes_ciclo_d": res.iteracoes,
|
| 132 |
+
"confianca_base_1_rede": conf_base,
|
| 133 |
+
"confianca_pensamento": conf_pensamento,
|
| 134 |
+
"ganho_confianca": conf_pensamento - conf_base,
|
| 135 |
+
"orcamento_esgotado": res.telemetria.get("orcamento_esgotado").copied().unwrap_or(0.0),
|
| 136 |
+
"telemetria": res.telemetria,
|
| 137 |
+
"eventos_ciclo": res.trajetoria.iter().map(|e| match e {
|
| 138 |
+
pensamento::EventoCiclo::Planejamento { iteracao, temperatura } =>
|
| 139 |
+
serde_json::json!({"tipo": "planejamento", "iteracao": iteracao, "temperatura": temperatura}),
|
| 140 |
+
pensamento::EventoCiclo::DistribuicaoCompetencias { por_tentativa } =>
|
| 141 |
+
serde_json::json!({"tipo": "distribuicao", "pesos": por_tentativa}),
|
| 142 |
+
pensamento::EventoCiclo::RePlanejamento { motivo } =>
|
| 143 |
+
serde_json::json!({"tipo": "replanejamento", "motivo": motivo}),
|
| 144 |
+
pensamento::EventoCiclo::Resposta { confianca, iteracoes } =>
|
| 145 |
+
serde_json::json!({"tipo": "resposta", "confianca": confianca, "iteracoes": iteracoes}),
|
| 146 |
+
}).collect::<Vec<_>>(),
|
| 147 |
+
});
|
| 148 |
+
Ok(pythonize::pythonize(py, &d_)?.into())
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
/// **Ciclo d do Pensamento com o VERIFICADOR NCM** (produção, sem oráculo):
|
| 153 |
+
/// backbone CABEÇA TREINADA (alvo → classes) + verificador calibrado em
|
| 154 |
+
/// dados retidos; N tentativas agregadas; ganho medido em consultas retidas
|
| 155 |
+
/// EM DISTRIBUIÇÃO (onde a calibração vale — V-2) e OOD reportado à parte.
|
| 156 |
+
#[pyfunction]
|
| 157 |
+
pub(crate) fn demo_pensamento_ncm(
|
| 158 |
+
d_cond: usize,
|
| 159 |
+
d_saida: usize,
|
| 160 |
+
n_tentativas: usize,
|
| 161 |
+
passos_treino: usize,
|
| 162 |
+
limiar_conf: f64,
|
| 163 |
+
orcamento: usize,
|
| 164 |
+
semente: u64,
|
| 165 |
+
) -> PyResult<PyObject> {
|
| 166 |
+
Python::with_gil(|py| {
|
| 167 |
+
use candle_core::Tensor;
|
| 168 |
+
let dev = candle_core::Device::Cpu;
|
| 169 |
+
crate::rng::definir_semente(semente);
|
| 170 |
+
let mut motor = pensamento::MotorPensamento::novo(
|
| 171 |
+
d_cond, d_saida, n_tentativas, limiar_conf, orcamento, &dev)
|
| 172 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 173 |
+
let mut otim = treino::AdamWManual::novo(motor.vars(), 5e-3, 0.0);
|
| 174 |
+
let mut rng = crate::rng::RngDeterministico::novo(semente);
|
| 175 |
+
// ---- dados sintéticos (item a: treino cooperativo) ----
|
| 176 |
+
let n_dados = 320usize;
|
| 177 |
+
let conds: Vec<Vec<f32>> = (0..n_dados)
|
| 178 |
+
.map(|_| (0..d_cond).map(|_| rng.normal(0.0, 1.0) as f32).collect())
|
| 179 |
+
.collect();
|
| 180 |
+
let alvos: Vec<Vec<f32>> = conds.iter().map(|c| {
|
| 181 |
+
(0..d_saida).map(|j| {
|
| 182 |
+
let cj = c[j % d_cond];
|
| 183 |
+
let ck = c[(j + 1) % d_cond];
|
| 184 |
+
0.5 * cj + 0.3 * cj * ck + 0.1
|
| 185 |
+
}).collect()
|
| 186 |
+
}).collect();
|
| 187 |
+
let mk = |c: &[f32], j: usize| -> f32 {
|
| 188 |
+
let cj = c[j % d_cond];
|
| 189 |
+
let ck = c[(j + 1) % d_cond];
|
| 190 |
+
0.5 * cj + 0.3 * cj * ck + 0.1
|
| 191 |
+
};
|
| 192 |
+
let cond_t = Tensor::from_vec(conds.iter().flatten().cloned().collect(), (n_dados, d_cond), &dev)
|
| 193 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 194 |
+
let alvo_t = Tensor::from_vec(alvos.iter().flatten().cloned().collect(), (n_dados, d_saida), &dev)
|
| 195 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 196 |
+
// ---- BACKBONE (cabeça treinada): alvo → classes K ----
|
| 197 |
+
// classe = faixa do 1º componente do alvo (aprendível, mensurável)
|
| 198 |
+
let k_classes = 12usize;
|
| 199 |
+
let classes: Vec<u32> = alvos
|
| 200 |
+
.iter()
|
| 201 |
+
.map(|a| {
|
| 202 |
+
let v = a[0];
|
| 203 |
+
let f = (((v + 2.0) / 4.0) * (k_classes as f32)).floor();
|
| 204 |
+
(f.clamp(0.0, (k_classes - 1) as f32)) as u32
|
| 205 |
+
})
|
| 206 |
+
.collect();
|
| 207 |
+
let cabeca = crate::jepa::MlpJepa::novo(d_saida, 4 * d_saida, k_classes, &dev)
|
| 208 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 209 |
+
let classe_t = Tensor::from_vec(classes.clone(), (n_dados,), &dev)
|
| 210 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 211 |
+
let mut otim_cab = treino::AdamWManual::novo(cabeca.vars(), 1e-2, 0.0);
|
| 212 |
+
for _ in 0..200 {
|
| 213 |
+
let logits = cabeca.fwd(&alvo_t)
|
| 214 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 215 |
+
let ce = candle_nn::loss::cross_entropy(&logits, &classe_t)
|
| 216 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 217 |
+
otim_cab.passo(treino::grads_achatados(&ce, &cabeca.vars())
|
| 218 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?);
|
| 219 |
+
}
|
| 220 |
+
// ---- VERIFICADOR calibrado em RETIDOS (metade final) ----
|
| 221 |
+
let n_ret = n_dados / 2;
|
| 222 |
+
let (alvo_ret, clas_ret) = (
|
| 223 |
+
alvo_t.narrow(0, n_ret, n_dados - n_ret).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?,
|
| 224 |
+
classe_t.narrow(0, n_ret, n_dados - n_ret).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?,
|
| 225 |
+
);
|
| 226 |
+
let logits_ret = cabeca.fwd(&alvo_ret).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 227 |
+
let mut verif = verificador::VerificadorNcm::novo();
|
| 228 |
+
let (ece_antes, ece_depois) = verif.ajustar(&logits_ret, &clas_ret)
|
| 229 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 230 |
+
// logits_fn: resposta (1, d_saida) → logits do backbone (1, K)
|
| 231 |
+
let logits_fn = |resp: &Tensor| -> candle_core::Result<Tensor> {
|
| 232 |
+
cabeca.fwd(resp)
|
| 233 |
+
};
|
| 234 |
+
// ---- treino cooperativo do motor (item a) ----
|
| 235 |
+
let cond_tr = cond_t.narrow(0, 0, n_ret).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 236 |
+
let alvo_tr = alvo_t.narrow(0, 0, n_ret).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 237 |
+
let mut hist = Vec::new();
|
| 238 |
+
for _ in 0..passos_treino {
|
| 239 |
+
let perda = motor.perda_treino(&cond_tr, &alvo_tr)
|
| 240 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 241 |
+
let pv = perda.to_scalar::<f32>()
|
| 242 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))? as f64;
|
| 243 |
+
hist.push(pv);
|
| 244 |
+
otim.passo(treino::grads_achatados(&perda, &motor.vars())
|
| 245 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?);
|
| 246 |
+
}
|
| 247 |
+
// ---- consultas RETIDAS em distribuição (ganho medido AQUI) ----
|
| 248 |
+
let n_consultas = 8usize;
|
| 249 |
+
let mut confs_base = Vec::new();
|
| 250 |
+
let mut confs_pens = Vec::new();
|
| 251 |
+
let mut iteracoes = Vec::new();
|
| 252 |
+
for qi in 0..n_consultas {
|
| 253 |
+
let consulta: Vec<f32> = conds[n_ret + qi].clone();
|
| 254 |
+
let consulta_t = Tensor::from_vec(consulta, (d_cond,), &dev)
|
| 255 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 256 |
+
let mut rng2 = crate::rng::RngDeterministico::novo(semente + 1 + qi as u64);
|
| 257 |
+
let res = motor.raciocinar_ncm(&consulta_t, &verif, &logits_fn, &mut rng2)
|
| 258 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 259 |
+
// base: 1 tentativa isolada, mesma verificação NCM
|
| 260 |
+
let base = motor.tentativas[0]
|
| 261 |
+
.fwd(&consulta_t.broadcast_as((1, d_cond)).unwrap()).unwrap();
|
| 262 |
+
let conf_base = verif.confianca_1d(&logits_fn(&base).unwrap()).unwrap();
|
| 263 |
+
confs_base.push(conf_base);
|
| 264 |
+
confs_pens.push(res.confianca);
|
| 265 |
+
iteracoes.push(res.iteracoes);
|
| 266 |
+
}
|
| 267 |
+
let media = |v: &[f64]| v.iter().sum::<f64>() / v.len().max(1) as f64;
|
| 268 |
+
let (conf_base_m, conf_pens_m) = (media(&confs_base), media(&confs_pens));
|
| 269 |
+
let iteracoes_media = iteracoes.iter().sum::<usize>() as f64 / iteracoes.len().max(1) as f64;
|
| 270 |
+
// ---- consulta OOD (reporte honesto — sem gate de ganho) ----
|
| 271 |
+
let consulta_ood: Vec<f32> = (0..d_cond).map(|j| 3.0 + (j as f32) * 0.1).collect();
|
| 272 |
+
let consulta_ood_t = Tensor::from_vec(consulta_ood, (d_cond,), &dev)
|
| 273 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 274 |
+
let mut rng3 = crate::rng::RngDeterministico::novo(semente + 99);
|
| 275 |
+
let res_ood = motor.raciocinar_ncm(&consulta_ood_t, &verif, &logits_fn, &mut rng3)
|
| 276 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 277 |
+
let base_ood = motor.tentativas[0]
|
| 278 |
+
.fwd(&consulta_ood_t.broadcast_as((1, d_cond)).unwrap()).unwrap();
|
| 279 |
+
let conf_base_ood = verif.confianca_1d(&logits_fn(&base_ood).unwrap()).unwrap();
|
| 280 |
+
let _ = mk;
|
| 281 |
+
let d_ = serde_json::json!({
|
| 282 |
+
"versao": "pensamento-0.6.0-ncm",
|
| 283 |
+
"n_tentativas": n_tentativas,
|
| 284 |
+
"perda_treino_inicial": hist.first(), "perda_treino_final": hist.last(),
|
| 285 |
+
"treino_aprendeu": hist.last().copied() < hist.first().map(|p| p * 0.5),
|
| 286 |
+
"ece_verificador_antes": ece_antes, "ece_verificador_depois": ece_depois,
|
| 287 |
+
"temperatura_calibrada": verif.temperatura,
|
| 288 |
+
"iteracoes_ciclo_d_media": iteracoes_media,
|
| 289 |
+
"confianca_base_1_rede": conf_base_m,
|
| 290 |
+
"confianca_pensamento": conf_pens_m,
|
| 291 |
+
"ganho_confianca": conf_pens_m - conf_base_m,
|
| 292 |
+
"confianca_ood_base": conf_base_ood,
|
| 293 |
+
"confianca_ood_pensamento": res_ood.confianca,
|
| 294 |
+
"iteracoes_ood": res_ood.iteracoes,
|
| 295 |
+
"orcamento_esgotado_ood": res_ood.telemetria.get("orcamento_esgotado").copied().unwrap_or(0.0),
|
| 296 |
+
"verificador": "ncm-calibrado (sem oraculo)",
|
| 297 |
+
"gates": {
|
| 298 |
+
"gate_verificador_sem_oraculo": true,
|
| 299 |
+
"gate_calibrado": ece_depois <= ece_antes,
|
| 300 |
+
"gate_ganho_nao_negativo": conf_pens_m >= conf_base_m - 1e-3,
|
| 301 |
+
"gate_terminou": iteracoes_media <= orcamento as f64,
|
| 302 |
+
},
|
| 303 |
+
});
|
| 304 |
+
Ok(pythonize::pythonize(py, &d_)?.into())
|
| 305 |
+
})
|
| 306 |
+
}
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
/// **Autoajuste do Pensamento por telemetria (A-1..A-5) — demo:** alimenta
|
| 311 |
+
/// o controlador com sinais sintéticos medidos e verifica cada regra.
|
| 312 |
+
#[pyfunction]
|
| 313 |
+
pub(crate) fn demo_autoajuste(semente: u64) -> PyResult<PyObject> {
|
| 314 |
+
Python::with_gil(|py| {
|
| 315 |
+
let mut hub = telemetria::TelemetryHub::novo(None);
|
| 316 |
+
let mut rng = crate::rng::RngDeterministico::novo(semente);
|
| 317 |
+
let mut auto = controlador::AutoAjustePensamento::novo(0.5, 8, 2);
|
| 318 |
+
// A-1: confianças com mistura (60% altas ~0.85–0.95, 40% baixas ~0.25–0.40)
|
| 319 |
+
// ⇒ quantil 0.75 cai no grupo alto (posições 0.6–1.0) ≈ 0.85+0.375·0.1 ≈ 0.89
|
| 320 |
+
for _ in 0..200 {
|
| 321 |
+
let c = if rng.uniforme() < 0.6 { 0.85 + rng.uniforme() * 0.1 } else { 0.25 + rng.uniforme() * 0.15 };
|
| 322 |
+
auto.confs_retidas.push(c);
|
| 323 |
+
}
|
| 324 |
+
let tau = auto.ajustar_tau_c(0.25, &mut hub);
|
| 325 |
+
// A-3: acordos altos (0.88 ⇒ p̂ = (1+√0.76)/2 ≈ 0.936 ⇒ N = ln(20)/(2·0.436²) ≈ 7.9 ⇒ 8)
|
| 326 |
+
for _ in 0..32 {
|
| 327 |
+
auto.acordos.push(0.88);
|
| 328 |
+
}
|
| 329 |
+
let n_ajustado = auto.ajustar_n(0.05, 16, &mut hub);
|
| 330 |
+
// A-5: ganhos estáveis positivos (n=64 ⇒ 3º termo Bernstein ≈ 0.14 < 0.30) ⇒ gate sobe
|
| 331 |
+
for _ in 0..64 {
|
| 332 |
+
auto.ajustar_gate(0.30, 0.05, &mut hub);
|
| 333 |
+
}
|
| 334 |
+
let g_final = auto.gate_g;
|
| 335 |
+
// A-2: ganhos decaindo geometricamente
|
| 336 |
+
for k in 0..12 {
|
| 337 |
+
auto.ganhos_por_iteracao.push(0.25 * 0.6f64.powi(k));
|
| 338 |
+
}
|
| 339 |
+
let b_ajustado = auto.ajustar_orcamento(0.02, &mut hub);
|
| 340 |
+
// A-4: UCB1 com 3 braços
|
| 341 |
+
let mut u = controlador::Ucb1::novo(vec!["n1".into(), "n4_moe".into(), "n4".into()]);
|
| 342 |
+
for _ in 0..200 {
|
| 343 |
+
let braco = u.escolher();
|
| 344 |
+
let media = match braco { 0 => 0.35, 1 => 0.80, _ => 0.55 };
|
| 345 |
+
let r = (media + rng.normal(0.0, 0.06) as f64).clamp(0.0, 1.0);
|
| 346 |
+
u.registrar(braco, r);
|
| 347 |
+
}
|
| 348 |
+
let medias = u.medias();
|
| 349 |
+
let melhor = medias.iter().enumerate().max_by(|a, b| a.1.partial_cmp(b.1).unwrap()).map(|(i, _)| i).unwrap_or(0);
|
| 350 |
+
let d_ = serde_json::json!({
|
| 351 |
+
"versao": "autoajuste-0.6.0",
|
| 352 |
+
"tau_c_final": tau, "n_tentativas_final": n_ajustado,
|
| 353 |
+
"gate_final": g_final, "orcamento_b_final": b_ajustado,
|
| 354 |
+
"ajustes_auditados": hub.eventos_ajuste.len(),
|
| 355 |
+
"ucb1_medias": medias, "ucb1_melhor_braco": u.nomes[melhor],
|
| 356 |
+
"ucb1_arrependimento_medio": u.arrependimento_empirico() / 200.0,
|
| 357 |
+
"gates": {
|
| 358 |
+
"gate_a1_tau_quantil": (tau - 0.89).abs() < 0.08,
|
| 359 |
+
"gate_a3_n_reduzido": n_ajustado <= 8,
|
| 360 |
+
"gate_a5_gate_subiu": g_final > 0.0,
|
| 361 |
+
"gate_a2_b_finito": b_ajustado >= 1 && b_ajustado <= 16,
|
| 362 |
+
"gate_a4_ucb1_achou": u.nomes[melhor] == "n4_moe",
|
| 363 |
+
},
|
| 364 |
+
});
|
| 365 |
+
Ok(pythonize::pythonize(py, &d_)?.into())
|
| 366 |
+
})
|
| 367 |
+
}
|
laboratorio/arquivo_split_v100/python/som.rs
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! `python::som` — extraído do monólito na v0.10.0
|
| 2 |
+
//! (divisão SRP, crítica Qwen3.8 lote 3 nº 1; r-35 §2).
|
| 3 |
+
|
| 4 |
+
use super::*;
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
/// Treina um 4D-SOM e devolve telemetria completa (EQ/TE/massa/cobertura).
|
| 8 |
+
#[pyfunction]
|
| 9 |
+
pub(crate) fn treinar_som4d(py: Python, dados: Vec<Vec<f64>>, cfg: Option<String>) -> PyResult<PyObject> {
|
| 10 |
+
let dev = candle_core::Device::Cpu;
|
| 11 |
+
let t = tensor_de_2d(dados, &dev).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 12 |
+
let mut c = som4d::CfgSom4D::default();
|
| 13 |
+
if let Some(js) = &cfg {
|
| 14 |
+
if let Ok(v) = serde_json::from_str::<serde_json::Value>(js) {
|
| 15 |
+
if let Some(o) = v.as_object() {
|
| 16 |
+
for (k, val) in o {
|
| 17 |
+
match k.as_str() {
|
| 18 |
+
"nx" => c.nx = val.as_u64().unwrap_or(4) as usize,
|
| 19 |
+
"ny" => c.ny = val.as_u64().unwrap_or(4) as usize,
|
| 20 |
+
"nz" => c.nz = val.as_u64().unwrap_or(4) as usize,
|
| 21 |
+
"nt" => c.nt = val.as_u64().unwrap_or(4) as usize,
|
| 22 |
+
"epocas" => c.epocas = val.as_u64().unwrap_or(50) as usize,
|
| 23 |
+
"sigma0" => c.sigma0 = val.as_f64().unwrap_or(2.0),
|
| 24 |
+
"sigma1" => c.sigma1 = val.as_f64().unwrap_or(0.5),
|
| 25 |
+
"eta0" => c.eta0 = val.as_f64().unwrap_or(0.5),
|
| 26 |
+
"eta1" => c.eta1 = val.as_f64().unwrap_or(0.05),
|
| 27 |
+
"semente" => c.semente = val.as_u64().unwrap_or(42),
|
| 28 |
+
"espalhada" => {
|
| 29 |
+
c.inicializacao = if val.as_bool().unwrap_or(false) {
|
| 30 |
+
som4d::Inicializacao4D::Espalhada
|
| 31 |
+
} else {
|
| 32 |
+
som4d::Inicializacao4D::Dados
|
| 33 |
+
}
|
| 34 |
+
}
|
| 35 |
+
_ => {}
|
| 36 |
+
}
|
| 37 |
+
}
|
| 38 |
+
}
|
| 39 |
+
}
|
| 40 |
+
}
|
| 41 |
+
let som = som4d::treinar_som4d(&t, &c, &dev)
|
| 42 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 43 |
+
let d = serde_json::json!({
|
| 44 |
+
"versao": som4d::versao(),
|
| 45 |
+
"celulas": som.n_celulas(),
|
| 46 |
+
"grade": [som.nx, som.ny, som.nz, som.nt],
|
| 47 |
+
"eq_inicial": som.eq_inicial,
|
| 48 |
+
"eq_final": som.eq_final,
|
| 49 |
+
"te_final": som.te_final,
|
| 50 |
+
"historico_eq_te": som.historia,
|
| 51 |
+
"massa_soma": som.massa.iter().sum::<f64>(),
|
| 52 |
+
});
|
| 53 |
+
Ok(pythonize::pythonize(py, &d)?.into())
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
/// Treina um GNG e devolve telemetria (vértices, arestas, componentes, EQ).
|
| 58 |
+
#[pyfunction]
|
| 59 |
+
pub(crate) fn treinar_gng(py: Python, dados: Vec<Vec<f64>>, cfg: Option<String>) -> PyResult<PyObject> {
|
| 60 |
+
let dev = candle_core::Device::Cpu;
|
| 61 |
+
let t = tensor_de_2d(dados, &dev).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 62 |
+
let mut c = som4d::CfgGng::default();
|
| 63 |
+
if let Some(js) = &cfg {
|
| 64 |
+
if let Ok(v) = serde_json::from_str::<serde_json::Value>(js) {
|
| 65 |
+
if let Some(o) = v.as_object() {
|
| 66 |
+
for (k, val) in o {
|
| 67 |
+
match k.as_str() {
|
| 68 |
+
"passos" => c.passos = val.as_u64().unwrap_or(4000) as usize,
|
| 69 |
+
"max_vertices" => c.max_vertices = val.as_u64().unwrap_or(60) as usize,
|
| 70 |
+
"lambda" => c.lambda = val.as_u64().unwrap_or(50) as usize,
|
| 71 |
+
"eps_b" => c.eps_b = val.as_f64().unwrap_or(0.05),
|
| 72 |
+
"eps_n" => c.eps_n = val.as_f64().unwrap_or(0.006),
|
| 73 |
+
"idade_max" => c.idade_max = val.as_u64().unwrap_or(50) as u32,
|
| 74 |
+
"semente" => c.semente = val.as_u64().unwrap_or(42),
|
| 75 |
+
_ => {}
|
| 76 |
+
}
|
| 77 |
+
}
|
| 78 |
+
}
|
| 79 |
+
}
|
| 80 |
+
}
|
| 81 |
+
let g = som4d::treinar_gng(&t, &c)
|
| 82 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 83 |
+
let d = serde_json::json!({
|
| 84 |
+
"versao": som4d::versao(),
|
| 85 |
+
"vertices": g.vertices.len(),
|
| 86 |
+
"arestas": g.arestas.len(),
|
| 87 |
+
"componentes_conexas": g.n_componentes_conexas(),
|
| 88 |
+
"insercoes": g.insercoes,
|
| 89 |
+
"eq_medio": g.eq_medio,
|
| 90 |
+
});
|
| 91 |
+
Ok(pythonize::pythonize(py, &d)?.into())
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
/// Treina um H-SOM e devolve a decomposição hierárquica (Teo H-1).
|
| 96 |
+
#[pyfunction]
|
| 97 |
+
pub(crate) fn treinar_hsom(py: Python, dados: Vec<Vec<f64>>, cfg: Option<String>) -> PyResult<PyObject> {
|
| 98 |
+
let dev = candle_core::Device::Cpu;
|
| 99 |
+
let t = tensor_de_2d(dados, &dev).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 100 |
+
let mut c = som4d::CfgHSom::default();
|
| 101 |
+
if let Some(js) = &cfg {
|
| 102 |
+
if let Ok(v) = serde_json::from_str::<serde_json::Value>(js) {
|
| 103 |
+
if let Some(o) = v.as_object() {
|
| 104 |
+
if let Some(x) = o.get("celulas_finas") {
|
| 105 |
+
c.celulas_finas = x.as_u64().unwrap_or(9) as usize;
|
| 106 |
+
}
|
| 107 |
+
if let Some(x) = o.get("epocas_finas") {
|
| 108 |
+
c.epocas_finas = x.as_u64().unwrap_or(20) as usize;
|
| 109 |
+
}
|
| 110 |
+
}
|
| 111 |
+
}
|
| 112 |
+
}
|
| 113 |
+
let h = som4d::treinar_hsom(&t, &c, &dev)
|
| 114 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 115 |
+
let cota = h.eq_grosso + 2.0 * h.r_fino + 2.0 * (h.eq_grosso * h.r_fino).sqrt();
|
| 116 |
+
let d = serde_json::json!({
|
| 117 |
+
"versao": som4d::versao(),
|
| 118 |
+
"eq_hierarquico": h.eq_hierarquico,
|
| 119 |
+
"eq_grosso": h.eq_grosso,
|
| 120 |
+
"r_fino": h.r_fino,
|
| 121 |
+
"cota_teo_h1": cota,
|
| 122 |
+
"cota_respeitada": h.eq_hierarquico <= cota + 1e-9,
|
| 123 |
+
});
|
| 124 |
+
Ok(pythonize::pythonize(py, &d)?.into())
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
/// Demo T-SOM: streaming com deriva controlada — rastreio (Teo T-1).
|
| 129 |
+
#[pyfunction]
|
| 130 |
+
pub(crate) fn demo_tsom(py: Python, dados_iniciais: Vec<Vec<f64>>, janela: Vec<Vec<f64>>, passos: usize, gamma: f64) -> PyResult<PyObject> {
|
| 131 |
+
let dev = candle_core::Device::Cpu;
|
| 132 |
+
let t0 = tensor_de_2d(dados_iniciais, &dev).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 133 |
+
let cfg = som4d::CfgTSom {
|
| 134 |
+
cfg_grade: som4d::CfgSom4D { nx: 3, ny: 3, nz: 2, nt: 2, epocas: 15, ..Default::default() },
|
| 135 |
+
gamma,
|
| 136 |
+
janela: janela.len(),
|
| 137 |
+
};
|
| 138 |
+
let mut ts = som4d::TSom4D::novo(&t0, &cfg, &dev)
|
| 139 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 140 |
+
let mut historico = Vec::new();
|
| 141 |
+
for _ in 0..passos {
|
| 142 |
+
let eq = ts.passo(&janela);
|
| 143 |
+
historico.push(eq);
|
| 144 |
+
}
|
| 145 |
+
let d = serde_json::json!({
|
| 146 |
+
"versao": som4d::versao(),
|
| 147 |
+
"gamma": gamma,
|
| 148 |
+
"eq_temporal_historico": historico,
|
| 149 |
+
"t_passos": ts.t,
|
| 150 |
+
});
|
| 151 |
+
Ok(pythonize::pythonize(py, &d)?.into())
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
/// Demo/gate do auto-ajuste SOM com tetos (S-AB/S-SL).
|
| 156 |
+
#[pyfunction]
|
| 157 |
+
pub(crate) fn demo_autoajuste_som(py: Python) -> PyResult<PyObject> {
|
| 158 |
+
let mut a = controlador::AutoAjusteSom::novo(0.5, 1.0);
|
| 159 |
+
let (al_qe, _) = a.passo(1.0, 0.0, 0.0);
|
| 160 |
+
let (al_cross, sg_cross) = a.passo(0.0, 0.0, 1.0);
|
| 161 |
+
let (al_max, sg_max) = a.passo(1.0, 1.0, 1.0);
|
| 162 |
+
let mut parou_5chunks = false;
|
| 163 |
+
for _ in 0..5 {
|
| 164 |
+
parou_5chunks = a.avaliar_parada(0.95, 0.1, 0.1, false, true, false, false);
|
| 165 |
+
}
|
| 166 |
+
let d_ = serde_json::json!({
|
| 167 |
+
"versao": "som-autoadjust-0.7.0",
|
| 168 |
+
"alfa_qe_alta": al_qe, "alfa_crossing": al_cross, "sigma_crossing": sg_cross,
|
| 169 |
+
"alfa_max": al_max, "sigma_max": sg_max,
|
| 170 |
+
"parou_5chunks": parou_5chunks,
|
| 171 |
+
"motivo": a.motivo_parada,
|
| 172 |
+
"gates": {
|
| 173 |
+
"tetos_ok": al_max <= 1.0 + 1e-9 && sg_max <= 2.0 + 1e-9,
|
| 174 |
+
"piso_ok": al_cross >= 0.5 - 1e-9,
|
| 175 |
+
"qe_sobe": al_qe > 0.5,
|
| 176 |
+
"stop_dispara": parou_5chunks,
|
| 177 |
+
},
|
| 178 |
+
});
|
| 179 |
+
Ok(pythonize::pythonize(py, &d_)?.into())
|
| 180 |
+
}
|
laboratorio/arquivo_split_v100/python/treino_fases.rs
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! `python::treino_fases` — extraído do monólito na v0.10.0
|
| 2 |
+
//! (divisão SRP, crítica Qwen3.8 lote 3 nº 1; r-35 §2).
|
| 3 |
+
|
| 4 |
+
use super::*;
|
| 5 |
+
|
| 6 |
+
use super::nucleo::ConfigPy;
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
/// Treina a fase A (tokenizador). Devolve dict com resumo + telemetria.
|
| 10 |
+
#[pyfunction]
|
| 11 |
+
#[pyo3(signature = (cfg, sequencias, caminho_telemetria=None, caminho_checkpoint=None, callback=None, teto_seg=None))]
|
| 12 |
+
pub(crate) fn treinar_fase_a(
|
| 13 |
+
cfg: &ConfigPy,
|
| 14 |
+
sequencias: Vec<Vec<u32>>,
|
| 15 |
+
caminho_telemetria: Option<String>,
|
| 16 |
+
caminho_checkpoint: Option<String>,
|
| 17 |
+
callback: Option<Bound<'_, PyAny>>,
|
| 18 |
+
teto_seg: Option<f64>,
|
| 19 |
+
) -> PyResult<PyObject> {
|
| 20 |
+
let cb = callback_treino_de_py(callback);
|
| 21 |
+
let mut hub = telemetria::TelemetryHub::novo(caminho_telemetria);
|
| 22 |
+
let dados = treino::DadosTreino::novo(sequencias, cfg.cfg.modelo.comprimento_ctx);
|
| 23 |
+
let mut resumo = treino::treinar_fase_a(&cfg.cfg, &dados, &mut hub, &cb, caminho_checkpoint.as_deref(), teto_seg)
|
| 24 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("fase A: {e}")))?;
|
| 25 |
+
let _ = &mut resumo;
|
| 26 |
+
Python::with_gil(|py| {
|
| 27 |
+
let dados = serde_json::json!({
|
| 28 |
+
"resumo": {
|
| 29 |
+
"passos": resumo.passos, "perda_inicial": resumo.perda_inicial,
|
| 30 |
+
"perda_final": resumo.perda_final, "acc_recon": resumo.acc_recon,
|
| 31 |
+
"delta_ort_max": resumo.delta_ort_max,
|
| 32 |
+
"perplexidade_codebook": resumo.perplexidade_codebook,
|
| 33 |
+
"monotonia_prefixo": resumo.monotonia_prefixo,
|
| 34 |
+
"escore_aprendizado": resumo.escore_aprendizado,
|
| 35 |
+
},
|
| 36 |
+
"telemetria": hub.dump(),
|
| 37 |
+
});
|
| 38 |
+
Ok(pythonize::pythonize(py, &dados)?.into())
|
| 39 |
+
})
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
/// Treina a fase B (gerador) com tokenizador congelado carregado de checkpoint.
|
| 44 |
+
#[pyfunction]
|
| 45 |
+
#[pyo3(signature = (cfg, sequencias, caminho_tokenizador, caminho_telemetria=None, caminho_checkpoint=None, callback=None, teto_seg=None))]
|
| 46 |
+
pub(crate) fn treinar_fase_b(
|
| 47 |
+
cfg: &ConfigPy,
|
| 48 |
+
sequencias: Vec<Vec<u32>>,
|
| 49 |
+
caminho_tokenizador: &str,
|
| 50 |
+
caminho_telemetria: Option<String>,
|
| 51 |
+
caminho_checkpoint: Option<String>,
|
| 52 |
+
callback: Option<Bound<'_, PyAny>>,
|
| 53 |
+
teto_seg: Option<f64>,
|
| 54 |
+
) -> PyResult<PyObject> {
|
| 55 |
+
let cb = callback_treino_de_py(callback);
|
| 56 |
+
let mut hub = telemetria::TelemetryHub::novo(caminho_telemetria);
|
| 57 |
+
let dados = treino::DadosTreino::novo(sequencias, cfg.cfg.modelo.comprimento_ctx);
|
| 58 |
+
// carrega o tokenizador congelado
|
| 59 |
+
let dev = candle_core::Device::Cpu;
|
| 60 |
+
let mut tok = tokenizador::TokenizadorConceitos::novo(&cfg.cfg, &dev)
|
| 61 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("construção: {e}")))?;
|
| 62 |
+
carregar_tokenizador(&mut tok, caminho_tokenizador)
|
| 63 |
+
.map_err(pyo3::exceptions::PyRuntimeError::new_err)?;
|
| 64 |
+
let resumo = treino::treinar_fase_b(&cfg.cfg, &tok, &dados, &mut hub, &cb, caminho_checkpoint.as_deref(), teto_seg)
|
| 65 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("fase B: {e}")))?;
|
| 66 |
+
Python::with_gil(|py| {
|
| 67 |
+
let dados = serde_json::json!({
|
| 68 |
+
"resumo": {
|
| 69 |
+
"passos": resumo.passos, "perda_inicial": resumo.perda_inicial,
|
| 70 |
+
"perda_final": resumo.perda_final, "acc_conceitos": resumo.acc_recon,
|
| 71 |
+
"escore_aprendizado": resumo.escore_aprendizado,
|
| 72 |
+
},
|
| 73 |
+
"telemetria": hub.dump(),
|
| 74 |
+
});
|
| 75 |
+
Ok(pythonize::pythonize(py, &dados)?.into())
|
| 76 |
+
})
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
pub(crate) fn carregar_tokenizador(tok: &mut tokenizador::TokenizadorConceitos, caminho: &str) -> Result<(), String> {
|
| 81 |
+
let txt = std::fs::read_to_string(caminho).map_err(|e| format!("{e}"))?;
|
| 82 |
+
let v: serde_json::Value = serde_json::from_str(&txt).map_err(|e| format!("{e}"))?;
|
| 83 |
+
let obj = v.as_object().ok_or("formato de checkpoint inválido")?;
|
| 84 |
+
let vars = tok.vars();
|
| 85 |
+
for (i, var) in vars.iter().enumerate() {
|
| 86 |
+
if let Some(entrada) = obj.get(&format!("v{i}")) {
|
| 87 |
+
let forma: Vec<usize> = entrada["forma"].as_array().map(|a| a.iter().filter_map(|x| x.as_u64().map(|y| y as usize)).collect()).unwrap_or_default();
|
| 88 |
+
let dados: Vec<f32> = entrada["dados"].as_array().map(|a| a.iter().filter_map(|x| x.as_f64().map(|y| y as f32)).collect()).unwrap_or_default();
|
| 89 |
+
if forma.is_empty() || dados.is_empty() {
|
| 90 |
+
continue;
|
| 91 |
+
}
|
| 92 |
+
let dev = candle_core::Device::Cpu;
|
| 93 |
+
let t2 = candle_core::Tensor::from_vec(dados, forma.clone(), &dev)
|
| 94 |
+
.and_then(|t| t.reshape(forma))
|
| 95 |
+
.map_err(|e| format!("{e}"))?;
|
| 96 |
+
var.set(&t2).map_err(|e| format!("{e}"))?;
|
| 97 |
+
}
|
| 98 |
+
}
|
| 99 |
+
Ok(())
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
/// Gera amostras com NFE = L e devolve textos decodificados (modo conceitos).
|
| 104 |
+
#[pyfunction]
|
| 105 |
+
#[pyo3(signature = (cfg, caminho_tokenizador, caminho_gerador, n_amostras=2, parar_no_nivel=None, greedy=true))]
|
| 106 |
+
pub(crate) fn gerar_amostras(
|
| 107 |
+
cfg: &ConfigPy,
|
| 108 |
+
caminho_tokenizador: &str,
|
| 109 |
+
caminho_gerador: &str,
|
| 110 |
+
n_amostras: usize,
|
| 111 |
+
parar_no_nivel: Option<usize>,
|
| 112 |
+
greedy: bool,
|
| 113 |
+
) -> PyResult<PyObject> {
|
| 114 |
+
let dev = candle_core::Device::Cpu;
|
| 115 |
+
let mut tok = tokenizador::TokenizadorConceitos::novo(&cfg.cfg, &dev)
|
| 116 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 117 |
+
carregar_tokenizador(&mut tok, caminho_tokenizador)
|
| 118 |
+
.map_err(pyo3::exceptions::PyRuntimeError::new_err)?;
|
| 119 |
+
let mut ger = gerador::GeradorConceitos::novo(&cfg.cfg, &dev)
|
| 120 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 121 |
+
carregar_gerador(&mut ger, caminho_gerador)
|
| 122 |
+
.map_err(pyo3::exceptions::PyRuntimeError::new_err)?;
|
| 123 |
+
let mut amostrador = amostrador::AmostradorConceitos::novo(
|
| 124 |
+
&mut ger, &tok, cfg.cfg.ncm.cfg_scale, cfg.cfg.ncm.temperaturas.limites, cfg.cfg.ncm.temperaturas.entropia_alvo,
|
| 125 |
+
);
|
| 126 |
+
let mut rng = <rand::prelude::StdRng as rand::SeedableRng>::seed_from_u64(4242);
|
| 127 |
+
let inicio = std::time::Instant::now();
|
| 128 |
+
let (codigos, nfe) = amostrador.gerar(n_amostras.max(1), &dev, &mut rng, parar_no_nivel, greedy)
|
| 129 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("amostragem: {e}")))?;
|
| 130 |
+
let tempo_ms = inicio.elapsed().as_secs_f64() * 1000.0;
|
| 131 |
+
// decodifica: ẑ final → decoder AR greedy → tokens
|
| 132 |
+
let nivel_final = codigos.len();
|
| 133 |
+
let zhats = tok.reconstruir_de_codigos(&codigos, nivel_final, n_amostras.max(1), &dev)
|
| 134 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 135 |
+
let textos_ids = decodificar_textos(&tok, zhats.last(), n_amostras.max(1))
|
| 136 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{e}")))?;
|
| 137 |
+
Python::with_gil(|py| {
|
| 138 |
+
let d = serde_json::json!({
|
| 139 |
+
"nfe": nfe, "l": cfg.cfg.l_niveis(), "tempo_ms": tempo_ms,
|
| 140 |
+
"niveis_usados": nivel_final, "ids_tokens": textos_ids,
|
| 141 |
+
"temperaturas": amostrador.temperaturas,
|
| 142 |
+
});
|
| 143 |
+
Ok(pythonize::pythonize(py, &d)?.into())
|
| 144 |
+
})
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
fn decodificar_textos(tok: &tokenizador::TokenizadorConceitos, zhat: Option<&candle_core::Tensor>, b: usize) -> Result<Vec<Vec<u32>>, String> {
|
| 149 |
+
let Some(z) = zhat else { return Ok(vec![vec![]; b]) };
|
| 150 |
+
tok.decodificar_livre(z, 48).map_err(|e| format!("{e}"))
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
pub(crate) fn carregar_gerador(ger: &mut gerador::GeradorConceitos, caminho: &str) -> Result<(), String> {
|
| 155 |
+
let txt = std::fs::read_to_string(caminho).map_err(|e| format!("{e}"))?;
|
| 156 |
+
let v: serde_json::Value = serde_json::from_str(&txt).map_err(|e| format!("{e}"))?;
|
| 157 |
+
let obj = v.as_object().ok_or("formato inválido")?;
|
| 158 |
+
let vars = ger.vars();
|
| 159 |
+
for (i, var) in vars.iter().enumerate() {
|
| 160 |
+
if let Some(entrada) = obj.get(&format!("v{i}")) {
|
| 161 |
+
let forma: Vec<usize> = entrada["forma"].as_array().map(|a| a.iter().filter_map(|x| x.as_u64().map(|y| y as usize)).collect()).unwrap_or_default();
|
| 162 |
+
let dados: Vec<f32> = entrada["dados"].as_array().map(|a| a.iter().filter_map(|x| x.as_f64().map(|y| y as f32)).collect()).unwrap_or_default();
|
| 163 |
+
if forma.is_empty() || dados.is_empty() {
|
| 164 |
+
continue;
|
| 165 |
+
}
|
| 166 |
+
let dev = candle_core::Device::Cpu;
|
| 167 |
+
let t = candle_core::Tensor::from_vec(dados, forma.clone(), &dev)
|
| 168 |
+
.and_then(|t| t.reshape(forma))
|
| 169 |
+
.map_err(|e| format!("{e}"))?;
|
| 170 |
+
var.set(&t).map_err(|e| format!("{e}"))?;
|
| 171 |
+
}
|
| 172 |
+
}
|
| 173 |
+
Ok(())
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
/// **FASE C — treino conjunto Pensamento↔backbone** (dados reais).
|
| 178 |
+
#[pyfunction]
|
| 179 |
+
pub(crate) fn treinar_fase_c(
|
| 180 |
+
cfg: &ConfigPy,
|
| 181 |
+
sequencias: Vec<Vec<u32>>,
|
| 182 |
+
caminho_tokenizador: &str,
|
| 183 |
+
passos: usize,
|
| 184 |
+
caminho_gerador: Option<String>,
|
| 185 |
+
caminho_telemetria: Option<String>,
|
| 186 |
+
callback: Option<Bound<'_, PyAny>>,
|
| 187 |
+
teto_seg: Option<f64>,
|
| 188 |
+
) -> PyResult<PyObject> {
|
| 189 |
+
let cb = callback_treino_de_py(callback);
|
| 190 |
+
let mut hub = telemetria::TelemetryHub::novo(caminho_telemetria);
|
| 191 |
+
let dados = treino::DadosTreino::novo(sequencias, cfg.cfg.modelo.comprimento_ctx);
|
| 192 |
+
let dev = candle_core::Device::Cpu;
|
| 193 |
+
let mut tok = tokenizador::TokenizadorConceitos::novo(&cfg.cfg, &dev)
|
| 194 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("construção: {e}")))?;
|
| 195 |
+
carregar_tokenizador(&mut tok, caminho_tokenizador)
|
| 196 |
+
.map_err(pyo3::exceptions::PyRuntimeError::new_err)?;
|
| 197 |
+
let resumo = treino::treinar_fase_c(&cfg.cfg, &tok, &dados, &mut hub, &cb, teto_seg, passos, caminho_gerador.as_deref())
|
| 198 |
+
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("fase C: {e}")))?;
|
| 199 |
+
Python::with_gil(|py| {
|
| 200 |
+
let dados = serde_json::json!({
|
| 201 |
+
"resumo": {
|
| 202 |
+
"passos": resumo.passos,
|
| 203 |
+
"ce_inicial": resumo.ce_inicial,
|
| 204 |
+
"ce_final": resumo.ce_final,
|
| 205 |
+
"ce_gatilhada_sem_correcao": resumo.ce_gatilhada_sem_correcao,
|
| 206 |
+
"ce_gatilhada_com_correcao": resumo.ce_gatilhada_com_correcao,
|
| 207 |
+
"confianca_media_inicial": resumo.confianca_media_inicial,
|
| 208 |
+
"confianca_media_final": resumo.confianca_media_final,
|
| 209 |
+
"confianca_pos_correcao": resumo.confianca_pos_correcao,
|
| 210 |
+
"taxa_gatilho": resumo.taxa_gatilho,
|
| 211 |
+
"ece_antes": resumo.ece_antes,
|
| 212 |
+
"ece_depois": resumo.ece_depois,
|
| 213 |
+
"temperatura_calibrada": resumo.temperatura_calibrada,
|
| 214 |
+
"tau_c": resumo.tau_c,
|
| 215 |
+
"taxa_conflito_pcgrad": resumo.taxa_conflito_pcgrad,
|
| 216 |
+
"decaimento_delta": resumo.decaimento_delta,
|
| 217 |
+
"acordos_medios": resumo.acordos_medios,
|
| 218 |
+
"escore_aprendizado": resumo.escore_aprendizado,
|
| 219 |
+
"rodadas_acoplador": resumo.rodadas_acoplador,
|
| 220 |
+
"timeouts_acoplador": resumo.timeouts_acoplador,
|
| 221 |
+
"maior_sobreposicao_us": resumo.maior_sobreposicao_us,
|
| 222 |
+
},
|
| 223 |
+
"painel_v060": hub.painel_v060(),
|
| 224 |
+
"telemetria": hub.dump(),
|
| 225 |
+
});
|
| 226 |
+
Ok(pythonize::pythonize(py, &dados)?.into())
|
| 227 |
+
})
|
| 228 |
+
}
|
laboratorio/arquivo_split_v100/tipos.rs
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! Tipos de domínio com invariantes no sistema de tipos (v0.9.0).
|
| 2 |
+
//!
|
| 3 |
+
//! **Aprimoramento 5 da crítica Qwen3.8 (r-34 §6), CORRIGIDO:** a proposta
|
| 4 |
+
//! original declarava `pub struct Probabilidade(pub f64)` alegando "garante
|
| 5 |
+
//! semanticamente [0, 1]" — o que é **FALSO**: um campo público permite
|
| 6 |
+
//! `Probabilidade(7.0)` em qualquer ponto do código, e o verificador de
|
| 7 |
+
//! tipos não impede nada. A garantia só existe com (a) campo **privado** e
|
| 8 |
+
//! (b) construtor **validado** (`novo`), que recusa valores fora do domínio
|
| 9 |
+
//! uma única vez, na fronteira. Este módulo implementa a forma correta.
|
| 10 |
+
//!
|
| 11 |
+
//! **Prova lógica (T-V1):** todo valor de `Probabilidade` acessível fora
|
| 12 |
+
//! deste módulo é obtido por `novo` (campo privado ⇒ construção só via
|
| 13 |
+
//! construtor) ou por `de_unchecked` (marcado `unsafe`-semântico, visível
|
| 14 |
+
//! apenas `pub(crate)` para hot paths já verificados). `novo` devolve
|
| 15 |
+
//! `Err` para `v ∉ [0,1] ∪ {NaN}` ⇒ por indução estrutural sobre as
|
| 16 |
+
//! operações do tipo (nenhuma muta o campo), **todo** `Probabilidade`
|
| 17 |
+
//! Viveiro satisfaz `0 ≤ v ≤ 1`. ∎
|
| 18 |
+
//!
|
| 19 |
+
//! **Kani (verificação formal):** registrado como débito — o ganho marginal
|
| 20 |
+
//! sobre construtor-validado + testes de propriedade é pequeno para
|
| 21 |
+
//! invariantes de intervalo escalar; as provas estruturais continuam nos
|
| 22 |
+
//! markdown (r-XX) como exige a regra da casa.
|
| 23 |
+
|
| 24 |
+
use candle_core::Result;
|
| 25 |
+
|
| 26 |
+
/// Probabilidade — domínio fechado [0, 1].
|
| 27 |
+
#[derive(Clone, Copy, Debug, PartialEq)]
|
| 28 |
+
pub struct Probabilidade(f64);
|
| 29 |
+
|
| 30 |
+
impl Probabilidade {
|
| 31 |
+
/// Construtor validado: recusa `v` fora de [0, 1] (incluindo NaN).
|
| 32 |
+
pub fn novo(v: f64) -> Result<Self> {
|
| 33 |
+
if v.is_nan() || v < 0.0 || v > 1.0 {
|
| 34 |
+
candle_core::bail!("Probabilidade fora de [0,1]: {v}");
|
| 35 |
+
}
|
| 36 |
+
Ok(Probabilidade(v))
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
/// Valor do domínio (o campo privado garante que passou por `novo`).
|
| 40 |
+
pub fn valor(&self) -> f64 {
|
| 41 |
+
self.0
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
/// Complemento `1 − p` — preserva o domínio (fechamento).
|
| 45 |
+
pub fn complemento(&self) -> Probabilidade {
|
| 46 |
+
Probabilidade(1.0 - self.0)
|
| 47 |
+
}
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
/// Ativação de gate — domínio fechado [0, 1] (saída de `GatePunicao`).
|
| 51 |
+
#[derive(Clone, Copy, Debug, PartialEq)]
|
| 52 |
+
pub struct GateAtivacao(f64);
|
| 53 |
+
|
| 54 |
+
impl GateAtivacao {
|
| 55 |
+
pub fn novo(v: f64) -> Result<Self> {
|
| 56 |
+
if v.is_nan() || v < 0.0 || v > 1.0 {
|
| 57 |
+
candle_core::bail!("GateAtivacao fora de [0,1]: {v}");
|
| 58 |
+
}
|
| 59 |
+
Ok(GateAtivacao(v))
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
pub fn valor(&self) -> f64 {
|
| 63 |
+
self.0
|
| 64 |
+
}
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
/// Temperatura inversa γ = 1/T — domínio aberto (0, +∞).
|
| 69 |
+
///
|
| 70 |
+
/// **Crítica Qwen3.8 lote 3, nº 4 / proposta 2 (v0.10.0, r-35 §5).** A
|
| 71 |
+
/// proposta `pub struct TemperaturaInversa(f64)` com construtor validado
|
| 72 |
+
/// é a forma CORRETA do padrão newtype — mas a alegação "garante em tempo
|
| 73 |
+
/// de COMPILAÇÃO que T > 0" é **FALSA** e já constava como errata na
|
| 74 |
+
/// r-34 §6: o construtor é uma checagem de RUNTIME na fronteira única
|
| 75 |
+
/// (o campo privado impede construção fora dela; nada é verificado pelo
|
| 76 |
+
/// verificador de tipos). O ganho real: validação em ponto único +
|
| 77 |
+
/// contrato visível na assinatura + fechamento sob as operações.
|
| 78 |
+
///
|
| 79 |
+
/// **Prova lógica (T-V3):** todo `TemperaturaInversa` acessível fora do
|
| 80 |
+
/// módulo vem de `nova`/`de_gamma` (campo privado) ou `de_unchecked`
|
| 81 |
+
/// (`pub(crate)`, hot paths já verificados). Ambos os construtores
|
| 82 |
+
/// recusam γ ∉ (0, +∞) — incluindo T subnormal com 1/T = +∞ — e nenhuma
|
| 83 |
+
/// operação do tipo muta o campo; por indução estrutural, todo valor
|
| 84 |
+
/// carrega γ finito e positivo. Como γ > 0 é EXATAMENTE a pré-condição
|
| 85 |
+
/// da convexidade estrita de L̃(γ) = NLL(softmax(γ·z)) (Teo N-2, r-33:
|
| 86 |
+
/// L̃'' = γ²·Var_p(z) ≥ 0), o tipo CARREGA a pré-condição do teorema. ∎
|
| 87 |
+
#[derive(Clone, Copy, Debug, PartialEq)]
|
| 88 |
+
pub struct TemperaturaInversa(f64);
|
| 89 |
+
|
| 90 |
+
impl TemperaturaInversa {
|
| 91 |
+
/// Construtor validado a partir da temperatura T: exige T > 0, T
|
| 92 |
+
/// finito e γ = 1/T finito (rejeita T subnormal, onde 1/T = +∞).
|
| 93 |
+
pub fn nova(temperatura: f64) -> Result<Self> {
|
| 94 |
+
if !(temperatura > 0.0) || !temperatura.is_finite() {
|
| 95 |
+
candle_core::bail!(
|
| 96 |
+
"Temperatura deve ser > 0 e finita (recebido {temperatura}) \
|
| 97 |
+
— pré-condição da convexidade N-2");
|
| 98 |
+
}
|
| 99 |
+
let gamma = 1.0 / temperatura;
|
| 100 |
+
if !gamma.is_finite() {
|
| 101 |
+
candle_core::bail!("1/T estourou para +∞ (T={temperatura} subnormal)");
|
| 102 |
+
}
|
| 103 |
+
Ok(TemperaturaInversa(gamma))
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
/// Construtor validado a partir de γ diretamente.
|
| 107 |
+
pub fn de_gamma(gamma: f64) -> Result<Self> {
|
| 108 |
+
if !(gamma > 0.0) || !gamma.is_finite() {
|
| 109 |
+
candle_core::bail!("γ deve ser > 0 e finito (recebido {gamma})");
|
| 110 |
+
}
|
| 111 |
+
Ok(TemperaturaInversa(gamma))
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
/// Valor de γ = 1/T (passou pela validação).
|
| 115 |
+
pub fn valor(&self) -> f64 {
|
| 116 |
+
self.0
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
/// Temperatura T = 1/γ (passou pela validação).
|
| 120 |
+
pub fn temperatura(&self) -> f64 {
|
| 121 |
+
1.0 / self.0
|
| 122 |
+
}
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
#[cfg(test)]
|
| 126 |
+
mod testes_tipos {
|
| 127 |
+
use super::*;
|
| 128 |
+
|
| 129 |
+
/// T-V1a — `novo` recusa valores fora do domínio (fronteira única).
|
| 130 |
+
#[test]
|
| 131 |
+
fn tv1a_construtor_recusa_fora_do_dominio() {
|
| 132 |
+
for v in [-1e-12, -0.5, 1.0 + 1e-12, 7.0, f64::NAN, f64::INFINITY] {
|
| 133 |
+
assert!(Probabilidade::novo(v).is_err(), "deveria recusar {v}");
|
| 134 |
+
assert!(GateAtivacao::novo(v).is_err(), "deveria recusar {v}");
|
| 135 |
+
}
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
/// T-V1b — `novo` aceita exatamente o fechamento [0, 1].
|
| 139 |
+
#[test]
|
| 140 |
+
fn tv1b_construtor_aceita_o_fechamento() {
|
| 141 |
+
for v in [0.0, 1e-9, 0.25, 0.5, 0.999, 1.0] {
|
| 142 |
+
let p = Probabilidade::novo(v).unwrap();
|
| 143 |
+
assert_eq!(p.valor(), v);
|
| 144 |
+
let g = GateAtivacao::novo(v).unwrap();
|
| 145 |
+
assert_eq!(g.valor(), v);
|
| 146 |
+
}
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
/// T-V1c — fechamento do complemento: p ∈ [0,1] ⇒ 1−p ∈ [0,1].
|
| 150 |
+
#[test]
|
| 151 |
+
fn tv1c_complemento_preserva_dominio() {
|
| 152 |
+
for v in [0.0, 0.1, 0.5, 0.9, 1.0] {
|
| 153 |
+
let p = Probabilidade::novo(v).unwrap();
|
| 154 |
+
let q = p.complemento();
|
| 155 |
+
assert!((0.0..=1.0).contains(&q.valor()));
|
| 156 |
+
}
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
/// T-V2 — o gate tipado produz GateAtivacao válido em TODO o domínio
|
| 160 |
+
/// (varredura densa — a prova estrutural é F-3; esta é a regressão).
|
| 161 |
+
#[test]
|
| 162 |
+
fn tv2_gate_tipado_dominio_valido() {
|
| 163 |
+
use crate::fnh::GatePunicao;
|
| 164 |
+
let gate = GatePunicao::default();
|
| 165 |
+
let mut n = 0usize;
|
| 166 |
+
let mut soma = 0.0f64;
|
| 167 |
+
for i in 0..=2000 {
|
| 168 |
+
let p = Probabilidade::novo(i as f64 / 2000.0).unwrap();
|
| 169 |
+
let g = gate.valor_tipado(&p);
|
| 170 |
+
assert!((0.0..=1.0).contains(&g.valor()), "gate fora de [0,1]: {}", g.valor());
|
| 171 |
+
soma += g.valor();
|
| 172 |
+
n += 1;
|
| 173 |
+
}
|
| 174 |
+
assert_eq!(n, 2001);
|
| 175 |
+
// integral do gate ≈ área da sigmoide retificada (> 0, < 1·domínio)
|
| 176 |
+
assert!(soma > 0.0 && soma < 2001.0);
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
/// T-V3a — construtores recusam γ ∉ (0, +∞): T ≤ 0, NaN, ±∞ e o
|
| 180 |
+
/// caso subnormal T = 5e-324 (1/T = +∞ em f64).
|
| 181 |
+
#[test]
|
| 182 |
+
fn tv3a_construtores_recusam_fora_do_dominio() {
|
| 183 |
+
for t_mau in [0.0, -1e-9, -5.0, f64::NAN, f64::INFINITY, 5e-324] {
|
| 184 |
+
assert!(TemperaturaInversa::nova(t_mau).is_err(), "nova devia recusar {t_mau}");
|
| 185 |
+
}
|
| 186 |
+
for g_mau in [0.0, -1e-9, -3.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
|
| 187 |
+
assert!(TemperaturaInversa::de_gamma(g_mau).is_err(), "de_gamma devia recusar {g_mau}");
|
| 188 |
+
}
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
/// T-V3b — fechamento: nova(T).temperatura() = T e
|
| 192 |
+
/// nova(T).valor() = 1/T para T representável.
|
| 193 |
+
#[test]
|
| 194 |
+
fn tv3b_fechamento_inversao() {
|
| 195 |
+
for t_bom in [1.0, 0.125, 8.0, 1e-6, 1e6, 0.373] {
|
| 196 |
+
let ti = TemperaturaInversa::nova(t_bom).unwrap();
|
| 197 |
+
assert!((ti.temperatura() - t_bom).abs() < 1e-12);
|
| 198 |
+
assert!((ti.valor() - 1.0 / t_bom).abs() < 1e-12);
|
| 199 |
+
}
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
/// T-V3c — de_gamma/nova concordam (mesma família paramétrica).
|
| 203 |
+
#[test]
|
| 204 |
+
fn tv3c_de_gamma_concorda() {
|
| 205 |
+
let a = TemperaturaInversa::nova(2.0).unwrap();
|
| 206 |
+
let b = TemperaturaInversa::de_gamma(0.5).unwrap();
|
| 207 |
+
assert_eq!(a, b);
|
| 208 |
+
}
|
| 209 |
+
}
|
laboratorio/build.rs
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fn main() {
|
| 2 |
+
// built 0.8: write_built_file() gera OUT_DIR/built.rs
|
| 3 |
+
if let Err(e) = built::write_built_file() {
|
| 4 |
+
println!("cargo:warning=falha ao gerar metadados built: {e}");
|
| 5 |
+
}
|
| 6 |
+
}
|
laboratorio/configs/base_laboratorio.json
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"laboratorio": {
|
| 3 |
+
"versao": "0.22.0-lab",
|
| 4 |
+
"fonte_dados": "dados/shard_treino.jsonl (246 artigos REAIS da Wikipédia PT-BR, os MESMOS do ciclo v0.21)",
|
| 5 |
+
"dados_wiki": {
|
| 6 |
+
"dimensao": 64,
|
| 7 |
+
"n_grama_min": 1,
|
| 8 |
+
"n_grama_max": 2,
|
| 9 |
+
"lotes": 12,
|
| 10 |
+
"semente": 42
|
| 11 |
+
},
|
| 12 |
+
"dados_digits": {
|
| 13 |
+
"conjunto": "sklearn.datasets.load_digits (1797 amostras reais, 64-D)",
|
| 14 |
+
"n_treino": 300,
|
| 15 |
+
"n_som": 1000,
|
| 16 |
+
"semente": 42
|
| 17 |
+
},
|
| 18 |
+
"mapa": {
|
| 19 |
+
"celulas_iniciais": 16,
|
| 20 |
+
"max_celulas": 256,
|
| 21 |
+
"alvo_relativo": 2.0,
|
| 22 |
+
"histerese_publicada": 1,
|
| 23 |
+
"histerese_lab": 2,
|
| 24 |
+
"eta": 1.0
|
| 25 |
+
},
|
| 26 |
+
"memoria": {
|
| 27 |
+
"frac_validacao": 0.25,
|
| 28 |
+
"alvo_qe_inicial": 1e-6,
|
| 29 |
+
"ganho": 0.35,
|
| 30 |
+
"taxa_max": 0.05,
|
| 31 |
+
"banda_morta": 1e-4,
|
| 32 |
+
"piso_adaptativo_q": 0.25,
|
| 33 |
+
"margem_teto": 1.5,
|
| 34 |
+
"lei_corrigida": false,
|
| 35 |
+
"lei_corrigida_nota": "flag OPT-IN: false reproduz o laço tautológico publicado (não-regressão); true aplica a correção lab-A1"
|
| 36 |
+
},
|
| 37 |
+
"jepa": {
|
| 38 |
+
"d_patch": 8,
|
| 39 |
+
"n_patches": 8,
|
| 40 |
+
"d_emb": 8,
|
| 41 |
+
"d_oculta": 16,
|
| 42 |
+
"d_oculta_energia": 16,
|
| 43 |
+
"kappa": 1.0,
|
| 44 |
+
"passos_energia": 24,
|
| 45 |
+
"eta_energia": 0.25,
|
| 46 |
+
"tol_kkt": 1e-3,
|
| 47 |
+
"lambda_align": 1.0,
|
| 48 |
+
"lambda_v": 1.0,
|
| 49 |
+
"lambda_c": 0.25,
|
| 50 |
+
"gamma_v": 0.5,
|
| 51 |
+
"eps_v": 0.05,
|
| 52 |
+
"frac_mascara": 0.35,
|
| 53 |
+
"m_ema": 0.99,
|
| 54 |
+
"epocas": 24,
|
| 55 |
+
"lr": 0.01,
|
| 56 |
+
"semente": 42,
|
| 57 |
+
"anticolapso_no_objetivo": true,
|
| 58 |
+
"piso_variancia": true
|
| 59 |
+
},
|
| 60 |
+
"som": {
|
| 61 |
+
"linhas": 10,
|
| 62 |
+
"lado": 10,
|
| 63 |
+
"epocas": 60,
|
| 64 |
+
"sigma0": 1.5,
|
| 65 |
+
"sigma1": 0.5,
|
| 66 |
+
"taxa": 0.5,
|
| 67 |
+
"eps_cov": 1e-4
|
| 68 |
+
}
|
| 69 |
+
}
|
| 70 |
+
}
|
laboratorio/configs/base_rust.json
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"modelo": {
|
| 3 |
+
"vocab": 16384,
|
| 4 |
+
"d_modelo": 192,
|
| 5 |
+
"n_camadas": 6,
|
| 6 |
+
"n_cabecas": 4,
|
| 7 |
+
"d_ff": 512,
|
| 8 |
+
"comprimento_ctx": 256,
|
| 9 |
+
"janela_sliding": 192,
|
| 10 |
+
"kv_cache_max": 2048,
|
| 11 |
+
"usar_atencao_arvore": true,
|
| 12 |
+
"mtp": {
|
| 13 |
+
"ativo": true,
|
| 14 |
+
"k_cabecas": 2,
|
| 15 |
+
"beta_entropia": 0.05,
|
| 16 |
+
"k_adaptativo": true
|
| 17 |
+
}
|
| 18 |
+
},
|
| 19 |
+
"ncm": {
|
| 20 |
+
"ativo": true,
|
| 21 |
+
"niveis": [
|
| 22 |
+
4,
|
| 23 |
+
8,
|
| 24 |
+
16,
|
| 25 |
+
32,
|
| 26 |
+
64,
|
| 27 |
+
128,
|
| 28 |
+
256
|
| 29 |
+
],
|
| 30 |
+
"d_lat": 64,
|
| 31 |
+
"k_por_nivel": 64,
|
| 32 |
+
"ema_codebook": 0.99,
|
| 33 |
+
"beta_commit": 0.25,
|
| 34 |
+
"nested_dropout": {
|
| 35 |
+
"tipo": "uniforme"
|
| 36 |
+
},
|
| 37 |
+
"corrupcao_cond": 0.15,
|
| 38 |
+
"dropout_cfg": 0.1,
|
| 39 |
+
"cfg_scale": 1.0,
|
| 40 |
+
"gsq": {
|
| 41 |
+
"tau0": 1.0,
|
| 42 |
+
"tau_min": 0.5,
|
| 43 |
+
"t_alvo": 400
|
| 44 |
+
},
|
| 45 |
+
"pesos_nivel": "uniforme",
|
| 46 |
+
"lambdas": {
|
| 47 |
+
"conceito": 0.0,
|
| 48 |
+
"rec": 1.0,
|
| 49 |
+
"rho_ancora": 0.05
|
| 50 |
+
},
|
| 51 |
+
"temperaturas": {
|
| 52 |
+
"auto": true,
|
| 53 |
+
"entropia_alvo": null,
|
| 54 |
+
"limites": [
|
| 55 |
+
0.5,
|
| 56 |
+
1.5
|
| 57 |
+
]
|
| 58 |
+
},
|
| 59 |
+
"mbr": {
|
| 60 |
+
"n_cand": 1
|
| 61 |
+
},
|
| 62 |
+
"escala_r": "ema_projecao",
|
| 63 |
+
"modo_quantizacao": "gsq_rco",
|
| 64 |
+
"niveis_token": false
|
| 65 |
+
},
|
| 66 |
+
"adba": {
|
| 67 |
+
"ativo": true,
|
| 68 |
+
"gamma_ancora": 1.0,
|
| 69 |
+
"reponderacao_nivel": true,
|
| 70 |
+
"temperatura_nivel": true
|
| 71 |
+
},
|
| 72 |
+
"ponte": {
|
| 73 |
+
"ativo": true,
|
| 74 |
+
"capacidade": 64,
|
| 75 |
+
"timeout_ms": 2000,
|
| 76 |
+
"rodadas_demo": 24
|
| 77 |
+
},
|
| 78 |
+
"treino": {
|
| 79 |
+
"lr": 0.003,
|
| 80 |
+
"aquecimento": 40,
|
| 81 |
+
"passos_fase_a": 400,
|
| 82 |
+
"passos_fase_b": 400,
|
| 83 |
+
"lote": 4,
|
| 84 |
+
"clip": 1.0,
|
| 85 |
+
"peso_decaimento": 0.01,
|
| 86 |
+
"telemetria_a_cada": 25
|
| 87 |
+
},
|
| 88 |
+
"telemetria": {
|
| 89 |
+
"jsonl": true,
|
| 90 |
+
"deteccao_aprendizado": true,
|
| 91 |
+
"ajuste_automatico": true,
|
| 92 |
+
"paciencia_plateau": 120,
|
| 93 |
+
"fator_lr_plateau": 0.6
|
| 94 |
+
},
|
| 95 |
+
"dados": {
|
| 96 |
+
"shard_treino": "dados/shard_treino.jsonl",
|
| 97 |
+
"shard_validacao": "dados/shard_validacao.jsonl",
|
| 98 |
+
"max_artigos": 1200,
|
| 99 |
+
"max_bytes": 6000000
|
| 100 |
+
},
|
| 101 |
+
"memoria": {
|
| 102 |
+
"som_lado": 16,
|
| 103 |
+
"lambda_jepa": 0.1,
|
| 104 |
+
"rm_dois_tempos": true
|
| 105 |
+
}
|
| 106 |
+
}
|
laboratorio/configs/base_rust_b800.json
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"modelo": {
|
| 3 |
+
"vocab": 16384,
|
| 4 |
+
"d_modelo": 192,
|
| 5 |
+
"n_camadas": 6,
|
| 6 |
+
"n_cabecas": 4,
|
| 7 |
+
"d_ff": 512,
|
| 8 |
+
"comprimento_ctx": 256,
|
| 9 |
+
"janela_sliding": 192,
|
| 10 |
+
"kv_cache_max": 2048,
|
| 11 |
+
"usar_atencao_arvore": true,
|
| 12 |
+
"mtp": {
|
| 13 |
+
"ativo": true,
|
| 14 |
+
"k_cabecas": 2,
|
| 15 |
+
"beta_entropia": 0.05,
|
| 16 |
+
"k_adaptativo": true
|
| 17 |
+
}
|
| 18 |
+
},
|
| 19 |
+
"ncm": {
|
| 20 |
+
"ativo": true,
|
| 21 |
+
"niveis": [
|
| 22 |
+
4,
|
| 23 |
+
8,
|
| 24 |
+
16,
|
| 25 |
+
32,
|
| 26 |
+
64,
|
| 27 |
+
128,
|
| 28 |
+
256
|
| 29 |
+
],
|
| 30 |
+
"d_lat": 64,
|
| 31 |
+
"k_por_nivel": 64,
|
| 32 |
+
"ema_codebook": 0.99,
|
| 33 |
+
"beta_commit": 0.25,
|
| 34 |
+
"nested_dropout": {
|
| 35 |
+
"tipo": "uniforme"
|
| 36 |
+
},
|
| 37 |
+
"corrupcao_cond": 0.15,
|
| 38 |
+
"dropout_cfg": 0.1,
|
| 39 |
+
"cfg_scale": 1.0,
|
| 40 |
+
"gsq": {
|
| 41 |
+
"tau0": 1.0,
|
| 42 |
+
"tau_min": 0.5,
|
| 43 |
+
"t_alvo": 400
|
| 44 |
+
},
|
| 45 |
+
"pesos_nivel": "uniforme",
|
| 46 |
+
"lambdas": {
|
| 47 |
+
"conceito": 0.0,
|
| 48 |
+
"rec": 1.0,
|
| 49 |
+
"rho_ancora": 0.05
|
| 50 |
+
},
|
| 51 |
+
"temperaturas": {
|
| 52 |
+
"auto": true,
|
| 53 |
+
"entropia_alvo": null,
|
| 54 |
+
"limites": [
|
| 55 |
+
0.5,
|
| 56 |
+
1.5
|
| 57 |
+
]
|
| 58 |
+
},
|
| 59 |
+
"mbr": {
|
| 60 |
+
"n_cand": 1
|
| 61 |
+
},
|
| 62 |
+
"escala_r": "ema_projecao",
|
| 63 |
+
"modo_quantizacao": "gsq_rco",
|
| 64 |
+
"niveis_token": false
|
| 65 |
+
},
|
| 66 |
+
"adba": {
|
| 67 |
+
"ativo": true,
|
| 68 |
+
"gamma_ancora": 1.0,
|
| 69 |
+
"reponderacao_nivel": true,
|
| 70 |
+
"temperatura_nivel": true
|
| 71 |
+
},
|
| 72 |
+
"ponte": {
|
| 73 |
+
"ativo": true,
|
| 74 |
+
"capacidade": 64,
|
| 75 |
+
"timeout_ms": 2000,
|
| 76 |
+
"rodadas_demo": 24
|
| 77 |
+
},
|
| 78 |
+
"treino": {
|
| 79 |
+
"lr": 0.003,
|
| 80 |
+
"aquecimento": 40,
|
| 81 |
+
"passos_fase_a": 400,
|
| 82 |
+
"passos_fase_b": 800,
|
| 83 |
+
"lote": 4,
|
| 84 |
+
"clip": 1.0,
|
| 85 |
+
"peso_decaimento": 0.01,
|
| 86 |
+
"telemetria_a_cada": 25
|
| 87 |
+
},
|
| 88 |
+
"telemetria": {
|
| 89 |
+
"jsonl": true,
|
| 90 |
+
"deteccao_aprendizado": true,
|
| 91 |
+
"ajuste_automatico": true,
|
| 92 |
+
"paciencia_plateau": 120,
|
| 93 |
+
"fator_lr_plateau": 0.6
|
| 94 |
+
},
|
| 95 |
+
"dados": {
|
| 96 |
+
"shard_treino": "dados/shard_treino.jsonl",
|
| 97 |
+
"shard_validacao": "dados/shard_validacao.jsonl",
|
| 98 |
+
"max_artigos": 1200,
|
| 99 |
+
"max_bytes": 6000000
|
| 100 |
+
},
|
| 101 |
+
"memoria": {
|
| 102 |
+
"som_lado": 16,
|
| 103 |
+
"lambda_jepa": 0.1,
|
| 104 |
+
"rm_dois_tempos": true
|
| 105 |
+
}
|
| 106 |
+
}
|
laboratorio/configs/base_rust_gumbel.json
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"modelo": {
|
| 3 |
+
"vocab": 16384,
|
| 4 |
+
"d_modelo": 192,
|
| 5 |
+
"n_camadas": 6,
|
| 6 |
+
"n_cabecas": 4,
|
| 7 |
+
"d_ff": 512,
|
| 8 |
+
"comprimento_ctx": 256,
|
| 9 |
+
"janela_sliding": 192,
|
| 10 |
+
"kv_cache_max": 2048,
|
| 11 |
+
"usar_atencao_arvore": true,
|
| 12 |
+
"mtp": {
|
| 13 |
+
"ativo": true,
|
| 14 |
+
"k_cabecas": 2,
|
| 15 |
+
"beta_entropia": 0.05,
|
| 16 |
+
"k_adaptativo": true
|
| 17 |
+
}
|
| 18 |
+
},
|
| 19 |
+
"ncm": {
|
| 20 |
+
"ativo": true,
|
| 21 |
+
"niveis": [
|
| 22 |
+
4,
|
| 23 |
+
8,
|
| 24 |
+
16,
|
| 25 |
+
32,
|
| 26 |
+
64,
|
| 27 |
+
128,
|
| 28 |
+
256
|
| 29 |
+
],
|
| 30 |
+
"d_lat": 64,
|
| 31 |
+
"k_por_nivel": 64,
|
| 32 |
+
"ema_codebook": 0.99,
|
| 33 |
+
"beta_commit": 0.25,
|
| 34 |
+
"nested_dropout": {
|
| 35 |
+
"tipo": "uniforme"
|
| 36 |
+
},
|
| 37 |
+
"corrupcao_cond": 0.15,
|
| 38 |
+
"dropout_cfg": 0.1,
|
| 39 |
+
"cfg_scale": 1.0,
|
| 40 |
+
"gsq": {
|
| 41 |
+
"tau0": 1.0,
|
| 42 |
+
"tau_min": 0.5,
|
| 43 |
+
"t_alvo": 400
|
| 44 |
+
},
|
| 45 |
+
"pesos_nivel": "uniforme",
|
| 46 |
+
"lambdas": {
|
| 47 |
+
"conceito": 0.0,
|
| 48 |
+
"rec": 1.0,
|
| 49 |
+
"rho_ancora": 0.05
|
| 50 |
+
},
|
| 51 |
+
"temperaturas": {
|
| 52 |
+
"auto": true,
|
| 53 |
+
"entropia_alvo": null,
|
| 54 |
+
"limites": [
|
| 55 |
+
0.5,
|
| 56 |
+
1.5
|
| 57 |
+
]
|
| 58 |
+
},
|
| 59 |
+
"mbr": {
|
| 60 |
+
"n_cand": 1
|
| 61 |
+
},
|
| 62 |
+
"escala_r": "ema_projecao",
|
| 63 |
+
"modo_quantizacao": "gumbel_st",
|
| 64 |
+
"niveis_token": false
|
| 65 |
+
},
|
| 66 |
+
"adba": {
|
| 67 |
+
"ativo": true,
|
| 68 |
+
"gamma_ancora": 1.0,
|
| 69 |
+
"reponderacao_nivel": true,
|
| 70 |
+
"temperatura_nivel": true
|
| 71 |
+
},
|
| 72 |
+
"ponte": {
|
| 73 |
+
"ativo": true,
|
| 74 |
+
"capacidade": 64,
|
| 75 |
+
"timeout_ms": 2000,
|
| 76 |
+
"rodadas_demo": 24
|
| 77 |
+
},
|
| 78 |
+
"treino": {
|
| 79 |
+
"lr": 0.003,
|
| 80 |
+
"aquecimento": 40,
|
| 81 |
+
"passos_fase_a": 400,
|
| 82 |
+
"passos_fase_b": 400,
|
| 83 |
+
"lote": 4,
|
| 84 |
+
"clip": 1.0,
|
| 85 |
+
"peso_decaimento": 0.01,
|
| 86 |
+
"telemetria_a_cada": 25
|
| 87 |
+
},
|
| 88 |
+
"telemetria": {
|
| 89 |
+
"jsonl": true,
|
| 90 |
+
"deteccao_aprendizado": true,
|
| 91 |
+
"ajuste_automatico": true,
|
| 92 |
+
"paciencia_plateau": 120,
|
| 93 |
+
"fator_lr_plateau": 0.6
|
| 94 |
+
},
|
| 95 |
+
"dados": {
|
| 96 |
+
"shard_treino": "dados/shard_treino.jsonl",
|
| 97 |
+
"shard_validacao": "dados/shard_validacao.jsonl",
|
| 98 |
+
"max_artigos": 1200,
|
| 99 |
+
"max_bytes": 6000000
|
| 100 |
+
},
|
| 101 |
+
"memoria": {
|
| 102 |
+
"som_lado": 16,
|
| 103 |
+
"lambda_jepa": 0.1,
|
| 104 |
+
"rm_dois_tempos": true
|
| 105 |
+
}
|
| 106 |
+
}
|
laboratorio/configs/base_rust_gumbel800.json
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"modelo": {
|
| 3 |
+
"vocab": 16384,
|
| 4 |
+
"d_modelo": 192,
|
| 5 |
+
"n_camadas": 6,
|
| 6 |
+
"n_cabecas": 4,
|
| 7 |
+
"d_ff": 512,
|
| 8 |
+
"comprimento_ctx": 256,
|
| 9 |
+
"janela_sliding": 192,
|
| 10 |
+
"kv_cache_max": 2048,
|
| 11 |
+
"usar_atencao_arvore": true,
|
| 12 |
+
"mtp": {
|
| 13 |
+
"ativo": true,
|
| 14 |
+
"k_cabecas": 2,
|
| 15 |
+
"beta_entropia": 0.05,
|
| 16 |
+
"k_adaptativo": true
|
| 17 |
+
}
|
| 18 |
+
},
|
| 19 |
+
"ncm": {
|
| 20 |
+
"ativo": true,
|
| 21 |
+
"niveis": [
|
| 22 |
+
4,
|
| 23 |
+
8,
|
| 24 |
+
16,
|
| 25 |
+
32,
|
| 26 |
+
64,
|
| 27 |
+
128,
|
| 28 |
+
256
|
| 29 |
+
],
|
| 30 |
+
"d_lat": 64,
|
| 31 |
+
"k_por_nivel": 64,
|
| 32 |
+
"ema_codebook": 0.99,
|
| 33 |
+
"beta_commit": 0.25,
|
| 34 |
+
"nested_dropout": {
|
| 35 |
+
"tipo": "uniforme"
|
| 36 |
+
},
|
| 37 |
+
"corrupcao_cond": 0.15,
|
| 38 |
+
"dropout_cfg": 0.1,
|
| 39 |
+
"cfg_scale": 1.0,
|
| 40 |
+
"gsq": {
|
| 41 |
+
"tau0": 1.0,
|
| 42 |
+
"tau_min": 0.5,
|
| 43 |
+
"t_alvo": 400
|
| 44 |
+
},
|
| 45 |
+
"pesos_nivel": "uniforme",
|
| 46 |
+
"lambdas": {
|
| 47 |
+
"conceito": 0.0,
|
| 48 |
+
"rec": 1.0,
|
| 49 |
+
"rho_ancora": 0.05
|
| 50 |
+
},
|
| 51 |
+
"temperaturas": {
|
| 52 |
+
"auto": true,
|
| 53 |
+
"entropia_alvo": null,
|
| 54 |
+
"limites": [
|
| 55 |
+
0.5,
|
| 56 |
+
1.5
|
| 57 |
+
]
|
| 58 |
+
},
|
| 59 |
+
"mbr": {
|
| 60 |
+
"n_cand": 1
|
| 61 |
+
},
|
| 62 |
+
"escala_r": "ema_projecao",
|
| 63 |
+
"modo_quantizacao": "gumbel_st",
|
| 64 |
+
"niveis_token": false
|
| 65 |
+
},
|
| 66 |
+
"adba": {
|
| 67 |
+
"ativo": true,
|
| 68 |
+
"gamma_ancora": 1.0,
|
| 69 |
+
"reponderacao_nivel": true,
|
| 70 |
+
"temperatura_nivel": true
|
| 71 |
+
},
|
| 72 |
+
"ponte": {
|
| 73 |
+
"ativo": true,
|
| 74 |
+
"capacidade": 64,
|
| 75 |
+
"timeout_ms": 2000,
|
| 76 |
+
"rodadas_demo": 24
|
| 77 |
+
},
|
| 78 |
+
"treino": {
|
| 79 |
+
"lr": 0.003,
|
| 80 |
+
"aquecimento": 40,
|
| 81 |
+
"passos_fase_a": 400,
|
| 82 |
+
"passos_fase_b": 800,
|
| 83 |
+
"lote": 4,
|
| 84 |
+
"clip": 1.0,
|
| 85 |
+
"peso_decaimento": 0.01,
|
| 86 |
+
"telemetria_a_cada": 25
|
| 87 |
+
},
|
| 88 |
+
"telemetria": {
|
| 89 |
+
"jsonl": true,
|
| 90 |
+
"deteccao_aprendizado": true,
|
| 91 |
+
"ajuste_automatico": true,
|
| 92 |
+
"paciencia_plateau": 120,
|
| 93 |
+
"fator_lr_plateau": 0.6
|
| 94 |
+
},
|
| 95 |
+
"dados": {
|
| 96 |
+
"shard_treino": "dados/shard_treino.jsonl",
|
| 97 |
+
"shard_validacao": "dados/shard_validacao.jsonl",
|
| 98 |
+
"max_artigos": 1200,
|
| 99 |
+
"max_bytes": 6000000
|
| 100 |
+
},
|
| 101 |
+
"memoria": {
|
| 102 |
+
"som_lado": 16,
|
| 103 |
+
"lambda_jepa": 0.1,
|
| 104 |
+
"rm_dois_tempos": true
|
| 105 |
+
}
|
| 106 |
+
}
|
laboratorio/dados/bpe.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
laboratorio/dados/shard_treino.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|