ternaryai 1.0.0a1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ternaryai-1.0.0a1/LEEME.md +167 -0
- ternaryai-1.0.0a1/LICENSE +201 -0
- ternaryai-1.0.0a1/MANIFEST.in +7 -0
- ternaryai-1.0.0a1/Makefile +365 -0
- ternaryai-1.0.0a1/NOTICE +7 -0
- ternaryai-1.0.0a1/PKG-INFO +191 -0
- ternaryai-1.0.0a1/README.md +167 -0
- ternaryai-1.0.0a1/docs/MANUAL.en.md +631 -0
- ternaryai-1.0.0a1/docs/MANUAL.md +631 -0
- ternaryai-1.0.0a1/include/ternary_activation.h +39 -0
- ternaryai-1.0.0a1/include/ternary_avx512.h +226 -0
- ternaryai-1.0.0a1/include/ternary_conv2d.h +77 -0
- ternaryai-1.0.0a1/include/ternary_core.h +88 -0
- ternaryai-1.0.0a1/include/ternary_dataset.h +82 -0
- ternaryai-1.0.0a1/include/ternary_dense.h +274 -0
- ternaryai-1.0.0a1/include/ternary_dispatch.h +53 -0
- ternaryai-1.0.0a1/include/ternary_embedding.h +57 -0
- ternaryai-1.0.0a1/include/ternary_fexp.h +112 -0
- ternaryai-1.0.0a1/include/ternary_gpu_lib.h +84 -0
- ternaryai-1.0.0a1/include/ternary_gqa.h +219 -0
- ternaryai-1.0.0a1/include/ternary_head.h +85 -0
- ternaryai-1.0.0a1/include/ternary_image.h +35 -0
- ternaryai-1.0.0a1/include/ternary_infer.h +255 -0
- ternaryai-1.0.0a1/include/ternary_json.h +111 -0
- ternaryai-1.0.0a1/include/ternary_kernels.h +149 -0
- ternaryai-1.0.0a1/include/ternary_layer.h +271 -0
- ternaryai-1.0.0a1/include/ternary_loss.h +31 -0
- ternaryai-1.0.0a1/include/ternary_mem.h +27 -0
- ternaryai-1.0.0a1/include/ternary_model_io.h +55 -0
- ternaryai-1.0.0a1/include/ternary_neon.h +194 -0
- ternaryai-1.0.0a1/include/ternary_neon_policy.h +43 -0
- ternaryai-1.0.0a1/include/ternary_prof.h +28 -0
- ternaryai-1.0.0a1/include/ternary_residual.h +61 -0
- ternaryai-1.0.0a1/include/ternary_rmsnorm.h +51 -0
- ternaryai-1.0.0a1/include/ternary_rng.h +30 -0
- ternaryai-1.0.0a1/include/ternary_softmax.h +48 -0
- ternaryai-1.0.0a1/include/ternary_stack.h +185 -0
- ternaryai-1.0.0a1/include/ternary_swiglu.h +137 -0
- ternaryai-1.0.0a1/include/ternary_targets.h +48 -0
- ternaryai-1.0.0a1/include/ternary_tensor.h +88 -0
- ternaryai-1.0.0a1/include/ternary_tfile.h +94 -0
- ternaryai-1.0.0a1/include/ternary_threadpool.h +60 -0
- ternaryai-1.0.0a1/include/ternary_tokenizer.h +99 -0
- ternaryai-1.0.0a1/include/ternary_u8.h +50 -0
- ternaryai-1.0.0a1/include/ternary_vulkan.h +17 -0
- ternaryai-1.0.0a1/include/ternaryai.h +280 -0
- ternaryai-1.0.0a1/include/vulkan/vk_platform.h +84 -0
- ternaryai-1.0.0a1/include/vulkan/vk_video/_stdvideo_shim.h +53 -0
- ternaryai-1.0.0a1/include/vulkan/vk_video/vulkan_video_codec_av1std.h +1 -0
- ternaryai-1.0.0a1/include/vulkan/vk_video/vulkan_video_codec_av1std_decode.h +1 -0
- ternaryai-1.0.0a1/include/vulkan/vk_video/vulkan_video_codec_av1std_encode.h +1 -0
- ternaryai-1.0.0a1/include/vulkan/vk_video/vulkan_video_codec_h264std.h +1 -0
- ternaryai-1.0.0a1/include/vulkan/vk_video/vulkan_video_codec_h264std_decode.h +1 -0
- ternaryai-1.0.0a1/include/vulkan/vk_video/vulkan_video_codec_h264std_encode.h +1 -0
- ternaryai-1.0.0a1/include/vulkan/vk_video/vulkan_video_codec_h265std.h +1 -0
- ternaryai-1.0.0a1/include/vulkan/vk_video/vulkan_video_codec_h265std_decode.h +1 -0
- ternaryai-1.0.0a1/include/vulkan/vk_video/vulkan_video_codec_h265std_encode.h +1 -0
- ternaryai-1.0.0a1/include/vulkan/vk_video/vulkan_video_codec_vp9std.h +1 -0
- ternaryai-1.0.0a1/include/vulkan/vk_video/vulkan_video_codec_vp9std_decode.h +1 -0
- ternaryai-1.0.0a1/include/vulkan/vulkan_core.h +26938 -0
- ternaryai-1.0.0a1/pyproject.toml +34 -0
- ternaryai-1.0.0a1/python/ternaryai/__init__.py +68 -0
- ternaryai-1.0.0a1/python/ternaryai/_backend.py +232 -0
- ternaryai-1.0.0a1/python/ternaryai/_native.py +538 -0
- ternaryai-1.0.0a1/python/ternaryai/_registry.py +39 -0
- ternaryai-1.0.0a1/python/ternaryai/_spec.py +128 -0
- ternaryai-1.0.0a1/python/ternaryai/blocks.py +67 -0
- ternaryai-1.0.0a1/python/ternaryai/dataset.py +233 -0
- ternaryai-1.0.0a1/python/ternaryai/errors.py +21 -0
- ternaryai-1.0.0a1/python/ternaryai/infer.py +738 -0
- ternaryai-1.0.0a1/python/ternaryai/layers.py +135 -0
- ternaryai-1.0.0a1/python/ternaryai/model.py +651 -0
- ternaryai-1.0.0a1/python/ternaryai/reasoning.py +372 -0
- ternaryai-1.0.0a1/python/ternaryai/testing.py +182 -0
- ternaryai-1.0.0a1/python/ternaryai/tokenizer.py +253 -0
- ternaryai-1.0.0a1/python/ternaryai.egg-info/PKG-INFO +191 -0
- ternaryai-1.0.0a1/python/ternaryai.egg-info/SOURCES.txt +130 -0
- ternaryai-1.0.0a1/python/ternaryai.egg-info/dependency_links.txt +1 -0
- ternaryai-1.0.0a1/python/ternaryai.egg-info/requires.txt +1 -0
- ternaryai-1.0.0a1/python/ternaryai.egg-info/top_level.txt +1 -0
- ternaryai-1.0.0a1/setup.cfg +4 -0
- ternaryai-1.0.0a1/setup.py +84 -0
- ternaryai-1.0.0a1/src/engine_export.map +1 -0
- ternaryai-1.0.0a1/src/ternary_activation.c +22 -0
- ternaryai-1.0.0a1/src/ternary_avx512.c +1731 -0
- ternaryai-1.0.0a1/src/ternary_conv2d.c +234 -0
- ternaryai-1.0.0a1/src/ternary_core.c +184 -0
- ternaryai-1.0.0a1/src/ternary_dataset.c +469 -0
- ternaryai-1.0.0a1/src/ternary_dense.c +1332 -0
- ternaryai-1.0.0a1/src/ternary_dispatch.c +223 -0
- ternaryai-1.0.0a1/src/ternary_embedding.c +133 -0
- ternaryai-1.0.0a1/src/ternary_gqa.c +2043 -0
- ternaryai-1.0.0a1/src/ternary_head.c +368 -0
- ternaryai-1.0.0a1/src/ternary_image.c +21 -0
- ternaryai-1.0.0a1/src/ternary_infer_cache.c +105 -0
- ternaryai-1.0.0a1/src/ternary_infer_engine.c +809 -0
- ternaryai-1.0.0a1/src/ternary_infer_gen.c +547 -0
- ternaryai-1.0.0a1/src/ternary_infer_internal.h +207 -0
- ternaryai-1.0.0a1/src/ternary_infer_k_avx512.c +306 -0
- ternaryai-1.0.0a1/src/ternary_infer_k_neon.c +384 -0
- ternaryai-1.0.0a1/src/ternary_infer_k_scalar.c +88 -0
- ternaryai-1.0.0a1/src/ternary_infer_load.c +845 -0
- ternaryai-1.0.0a1/src/ternary_infer_ops.c +244 -0
- ternaryai-1.0.0a1/src/ternary_infer_ternam.c +260 -0
- ternaryai-1.0.0a1/src/ternary_json.c +552 -0
- ternaryai-1.0.0a1/src/ternary_layer.c +1383 -0
- ternaryai-1.0.0a1/src/ternary_loss.c +56 -0
- ternaryai-1.0.0a1/src/ternary_model_io.c +73 -0
- ternaryai-1.0.0a1/src/ternary_neon.c +142 -0
- ternaryai-1.0.0a1/src/ternary_neon_attn.c +527 -0
- ternaryai-1.0.0a1/src/ternary_neon_elem.c +377 -0
- ternaryai-1.0.0a1/src/ternary_neon_norm.c +364 -0
- ternaryai-1.0.0a1/src/ternary_neon_planes.c +12 -0
- ternaryai-1.0.0a1/src/ternary_neon_stubs.c +55 -0
- ternaryai-1.0.0a1/src/ternary_prof.c +106 -0
- ternaryai-1.0.0a1/src/ternary_residual.c +374 -0
- ternaryai-1.0.0a1/src/ternary_rmsnorm.c +158 -0
- ternaryai-1.0.0a1/src/ternary_rng.c +48 -0
- ternaryai-1.0.0a1/src/ternary_softmax.c +67 -0
- ternaryai-1.0.0a1/src/ternary_stack.c +938 -0
- ternaryai-1.0.0a1/src/ternary_swiglu.c +547 -0
- ternaryai-1.0.0a1/src/ternary_targets.c +83 -0
- ternaryai-1.0.0a1/src/ternary_tensor.c +98 -0
- ternaryai-1.0.0a1/src/ternary_tfile.c +429 -0
- ternaryai-1.0.0a1/src/ternary_threadpool.c +341 -0
- ternaryai-1.0.0a1/src/ternary_tokenizer.c +653 -0
- ternaryai-1.0.0a1/src/ternary_u8.c +112 -0
- ternaryai-1.0.0a1/src/ternary_vulkan.c +96 -0
- ternaryai-1.0.0a1/src/ternaryai.c +1208 -0
- ternaryai-1.0.0a1/tests/test_bits.py +104 -0
- ternaryai-1.0.0a1/tests/test_manual.py +72 -0
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
# TernaryAI
|
|
2
|
+
|
|
3
|
+
*English version: [README.md](README.md)* · *Referencia completa de la sintaxis: [docs/MANUAL.md](docs/MANUAL.md)*
|
|
4
|
+
|
|
5
|
+
Redes neuronales cuyos pesos son estrictamente **−1, 0 o +1**, con el cálculo en **C11** y una interfaz en Python (`import ternaryai`).
|
|
6
|
+
Pensada para dispositivos pequeños: entrena y genera en un dispositivo Android de gama baja de 2018 (ARMv7 de 32 bits, ~1 GB de RAM) y aprovecha
|
|
7
|
+
AVX-512 en x86-64 y NEON en ARM cuando están disponibles.
|
|
8
|
+
|
|
9
|
+
- **Pesos ternarios sin copia float por peso.** La regla de actualización R2 guarda por cada peso un contador de 8 bits con histéresis (no un peso
|
|
10
|
+
float "en la sombra" como en QAT o BitNet). Cada capa lleva una escala float final.
|
|
11
|
+
- **Entrenamiento y inferencia en el mismo paquete.** El motor de inferencia da logits idénticos bit a bit a `Model.predict`, y los núcleos
|
|
12
|
+
escalar, AVX-512 y NEON dan los mismos bits.
|
|
13
|
+
- **Modelos de lenguaje de punta a punta.** Tokenizador BPE a nivel de bytes con tokens especiales, lector de datasets (formato propio y los de
|
|
14
|
+
Hugging Face más usados), generación con razonamiento (`<|think|>…<|/think|>`), verificadores, pass@k y fine-tuning por rejection sampling.
|
|
15
|
+
- **Una sola dependencia de Python: NumPy**, y solo en la interfaz (arrays de entrada y salida). El cálculo no pasa por NumPy.
|
|
16
|
+
|
|
17
|
+
## Qué contiene
|
|
18
|
+
|
|
19
|
+
| Componente | Qué hace |
|
|
20
|
+
|---|---|
|
|
21
|
+
| Capas (`tn.Dense`, `Conv2D`, `Embedding`, `GQA`, `SwiGLU`, `RMSNorm`, `LMHead`, `Residual`) | Bloques para clasificadores y transformers (atención con consultas agrupadas, RoPE entera, ventana deslizante, activación SwiGLU o ReLU²) |
|
|
22
|
+
| `tn.Model` | `fit` (mini-lotes, máscara de pérdida, checkpoints), `predict`, `save` / `load`, `export` |
|
|
23
|
+
| `tn.Tokenizer` | BPE de bytes en C, con tokens especiales; `tn.CHAT_SPECIAL_TOKENS` trae los 13 de conversación y razonamiento |
|
|
24
|
+
| `tn.dataset` | `load`, `tokenize`, `targets`: formato propio `chat`, ChatML/OpenAI `messages`, ShareGPT `conversations`, `prompt`+`completion`, Alpaca y `text` |
|
|
25
|
+
| `tn.Engine` / `Session` | Inferencia con caché KV, muestreo (`temperature`, `top_k`, `top_p`, …), `reply`, `sample`, lotes de conversaciones, hilos |
|
|
26
|
+
| Exportación | `.ternam` (un solo archivo, carga con `mmap`), librería de solo motor (`build_engine_lib`) y librería fusionada con el modelo incrustado (`export_fused`) |
|
|
27
|
+
| `tn.reasoning` | Verificadores, `evaluate` (pass@k), `rejection_sample` y `rft` |
|
|
28
|
+
|
|
29
|
+
## Instalación
|
|
30
|
+
|
|
31
|
+
Hace falta Python ≥ 3.10 y NumPy ≥ 1.21.6. Esta es una versión alfa (1.0.0a1), así que `pip` necesita la opción `--pre`. Hay tres formas de instalar:
|
|
32
|
+
|
|
33
|
+
- **Desde PyPI:** `pip install --pre ternaryai`. En Linux x86-64 con glibc ≥ 2.34 instala un wheel ya compilado (incluye la librería nativa y las fuentes en C que necesita; no hace falta compilador). En otras plataformas, por ejemplo Termux en Android, pip lo compila desde el código fuente, y para eso hacen falta un compilador C11 y `make`.
|
|
34
|
+
- **Wheel desde GitHub:** descarga `ternaryai-1.0.0a1-py3-none-manylinux_2_34_x86_64.whl` desde la página de [Releases](https://github.com/FDeveloper-hub/Project-TernaryAI/releases) e instálalo con `pip install` seguido del nombre del archivo.
|
|
35
|
+
- **Desde el código fuente:** `pip install .` desde un clon de este repositorio. La instalación ejecuta el Makefile.
|
|
36
|
+
|
|
37
|
+
Para trabajar en la propia librería, se compila en el sitio y se usa el paquete desde el código fuente:
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
make libternaryai.so # compila la librería nativa (detecta AVX-512 / NEON en tiempo de ejecución)
|
|
41
|
+
export PYTHONPATH=$PWD/python # o: pip install -e .
|
|
42
|
+
python3 -c "import ternaryai as tn; print(tn.__name__, 'ok')"
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Probado en Linux x86-64 con Python 3.10, 3.11, 3.12 y 3.13 y NumPy 1.21.6, 1.24.4, 2.2.6, 2.4.6 y 2.5.5, y en ARMv7 (Termux en un dispositivo ARMv7 de 32 bits, y bajo qemu). No se ha probado en Windows ni en macOS.
|
|
46
|
+
`TERNARYAI_NO_AVX512=1` / `TERNARYAI_NO_NEON=1` fuerzan el núcleo escalar; `TERNARYAI_NO_VNNI=1` conserva AVX-512 pero no usa el forward entero con VNNI (el resultado es idéntico bit a bit).
|
|
47
|
+
|
|
48
|
+
## Ejemplo: de un dataset a un modelo que conversa
|
|
49
|
+
|
|
50
|
+
Un archivo `datos.jsonl` con una conversación por línea, en el formato propio (`user` / `model`):
|
|
51
|
+
|
|
52
|
+
```json
|
|
53
|
+
{"chat": [{"user": "Hola"}, {"model": "Hola, ¿en qué puedo ayudarte?"}]}
|
|
54
|
+
{"chat": [{"user": "¿Cuánto es 2+2?"}, {"model": "<think>2+2=4</think>Es 4."}]}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
import ternaryai as tn
|
|
59
|
+
|
|
60
|
+
examples, skipped = tn.dataset.load("datos.jsonl") # una cadena por conversación, con los marcadores de rol
|
|
61
|
+
tok = tn.Tokenizer(400, special_tokens=list(tn.CHAT_SPECIAL_TOKENS))
|
|
62
|
+
tok.train("\n".join(examples).encode())
|
|
63
|
+
x, y = tn.dataset.tokenize(examples, tok, seq_len=64) # ids + objetivos: solo se entrena lo que dice el asistente
|
|
64
|
+
|
|
65
|
+
model = tn.Model(64, [
|
|
66
|
+
tn.Embedding(tok.vocab_size, 48),
|
|
67
|
+
*tn.transformer_block(heads=4, hidden=96, kv_heads=2, gate_mode=2),
|
|
68
|
+
tn.RMSNorm(activation="uint8"),
|
|
69
|
+
tn.LMHead(tok.vocab_size),
|
|
70
|
+
])
|
|
71
|
+
model.fit(x, y, epochs=400)
|
|
72
|
+
|
|
73
|
+
engine = model.engine(tok) # motor de inferencia (instantánea del modelo)
|
|
74
|
+
r = engine.session().reply("¿Cuánto es 2+2?", max_new_tokens=40)
|
|
75
|
+
print(r.text, "|", r.thinking) # Es 4. | 2+2=4
|
|
76
|
+
print(engine.session().reply("Hola", max_new_tokens=40).text) # Hola, ¿en qué puedo ayudarte?
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
(Con 8 conversaciones de cada tipo repetidas, como en esta prueba; el resultado exacto depende de la semilla y del tamaño del modelo.)
|
|
80
|
+
|
|
81
|
+
Para guardar el modelo: `model.save(carpeta)` (con los contadores, para seguir entrenando) o `model.export(carpeta)` (solo inferencia);
|
|
82
|
+
`tn.export_ternam(carpeta, "modelo.ternam")` lo deja en un archivo autocontenido que `tn.Engine("modelo.ternam")` abre con `mmap`.
|
|
83
|
+
|
|
84
|
+
## Conversación y razonamiento
|
|
85
|
+
|
|
86
|
+
`Session.reply(mensajes, ...)` arma el prompt igual que el cargador de datasets (`<|rol|>\ntexto\n`) y se detiene en `<|end|>` y `<|user|>`.
|
|
87
|
+
Devuelve un `Reply` con `.text`, `.thinking`, `.stop` e `.ids`.
|
|
88
|
+
|
|
89
|
+
- El bloque `<|think|>…<|/think|>` va a `.thinking` y se quita de `.text`. Con `show_thinking=True` queda dentro de `.text`, con sus etiquetas,
|
|
90
|
+
para leer la cadena de pensamiento en su sitio.
|
|
91
|
+
- `think_budget=N` limita los tokens de razonamiento (al llegar se fuerza `<|/think|>`); `force_think=True` empieza ya dentro de `<|think|>`.
|
|
92
|
+
- `dataset.load(..., reasoning="keep" | "drop")` acepta `<think>…</think>` y los campos `reasoning_content`, `reasoning` y `thinking`.
|
|
93
|
+
- `Engine.chat_encode`, `Engine.split_thinking` y `Engine.special_id` sirven para construir y analizar secuencias a mano.
|
|
94
|
+
|
|
95
|
+
## Evaluación y fine-tuning por rejection sampling
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
R = tn.reasoning
|
|
99
|
+
tasks = [R.Task("¿Cuánto es 2+2?", reference=4), ("¿Cuánto es 3+5?", 8)]
|
|
100
|
+
ok = R.all_of(R.numeric(), R.has_thinking()) # correcta Y con razonamiento bien cerrado
|
|
101
|
+
print(R.evaluate(engine, tasks, ok, n=8, k=(1, 4), temperature=0.8, max_new_tokens=64).summary())
|
|
102
|
+
|
|
103
|
+
R.rft(model, tok, tasks, ok, rounds=3, n=8, epochs=2) # muestrea, conserva lo verificado y entrena con ello
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
- `Engine.sample(mensajes, n)` genera `n` respuestas a la misma conversación (el prompt se procesa una vez, las candidatas corren en un lote, la candidata
|
|
107
|
+
`i` usa la semilla `seed + i`).
|
|
108
|
+
- Los verificadores (`exact_match`, `contains`, `regex_match`, `numeric`, `has_thinking`, `all_of`, o cualquier función `verify(reply, task)`)
|
|
109
|
+
solo comparan texto: nunca ejecutan lo que genera el modelo.
|
|
110
|
+
- `evaluate` da pass@k (estimador sin sesgo), recompensa media, longitudes y motivos de parada. `rft` acepta `replay=(x, y)` para mezclar los datos de
|
|
111
|
+
entrenamiento originales y limitar el olvido.
|
|
112
|
+
|
|
113
|
+
## Rendimiento
|
|
114
|
+
|
|
115
|
+
Medido contra un modelo BitNet b1.58 QAT escrito en PyTorch (solo CPU, PyTorch 2.14.1), con la misma arquitectura y el mismo número de pesos.
|
|
116
|
+
Condiciones: 1 hilo en 1 núcleo (Xeon de 2,1 GHz, AVX-512 VNNI), 30 épocas, lote 8, contexto 64, texto a nivel de byte (`pydoc_data.topics`), una sola semilla.
|
|
117
|
+
El modelo de PyTorch mantiene pesos sombra en float, los ternariza con absmean y un estimador straight-through, usa activaciones int8 por token, Adam (lr 0,01),
|
|
118
|
+
y embedding y cabeza de salida ternarios. Picos medidos en ese núcleo: fp32 215 GFLOP/s, int8 VNNI 677 GOP/s, DRAM 16 GB/s.
|
|
119
|
+
|
|
120
|
+
| | d=96, TernaryAI | d=96, PyTorch QAT | d=640, TernaryAI | d=640, PyTorch QAT |
|
|
121
|
+
|---|---|---|---|---|
|
|
122
|
+
| Pesos | 307 mil | 307 mil | 11,8 M | 11,8 M |
|
|
123
|
+
| Entrenamiento (tokens/s) | 18.798 | 12.289 | 803 | 819 |
|
|
124
|
+
| Pérdida de evaluación | 1,833 | 1,801 | 2,681 | 2,376 |
|
|
125
|
+
| Precisión de evaluación | 53,1 % | 56,1 % | 35,9 % | 40,0 % |
|
|
126
|
+
| Prefill (tokens/s) | 150.216 | 26.211 | 8.678 | 3.427 |
|
|
127
|
+
| Decodificación, 1 conversación (tokens/s) | 115.199 | 990 | 3.869 | 291 |
|
|
128
|
+
| Decodificación, lote de 32 (tokens/s) | 117.854 | 14.678 | 6.075 | 1.560 |
|
|
129
|
+
| RAM pico del proceso (anónima) | 34 MB | 196 MB | 193 MB | 616 MB |
|
|
130
|
+
| RSS pico del proceso | 65 MB | 303 MB | 227 MB | 725 MB |
|
|
131
|
+
| Modelo exportado | 0,08 MB | 0,31 MB (int8) | 2,4 MB | 11,8 MB (int8) |
|
|
132
|
+
|
|
133
|
+
Cómo leerlo:
|
|
134
|
+
|
|
135
|
+
- **La velocidad de entrenamiento es equivalente.** TernaryAI es 1,5 veces más rápido en d=96 y empata en d=640 (803 contra 819 tokens/s).
|
|
136
|
+
- **La inferencia y la memoria son lo que gana la librería.** Con un lote de 32 conversaciones es 8 veces (d=96) y 3,9 veces (d=640) más rápido; el prefill es 5,7 y 2,5 veces más rápido;
|
|
137
|
+
el proceso usa entre 3 y 6 veces menos RAM, y el modelo exportado es de 4 a 5 veces más pequeño. Con un tope duro de 200 MB de RAM (sin swap) TernaryAI entrenó 11,8 M de pesos,
|
|
138
|
+
mientras que el QAT de PyTorch llegó solo a 307 mil, unas 38 veces menos.
|
|
139
|
+
- **Las cifras de una sola conversación están infladas.** El modelo de PyTorch corre en float, en modo eager, y con modelos tan pequeños su tiempo lo dominan Python y el
|
|
140
|
+
lanzamiento de operaciones. La fila del lote de 32 es la más fiable.
|
|
141
|
+
- **Calidad:** las pérdidas de evaluación son cercanas (1,833 contra 1,801 en d=96, 2,681 contra 2,376 en d=640); el QAT de PyTorch es algo mejor en ambos.
|
|
142
|
+
- **Límites de la medición:** una semilla, entrenamiento corto, modelos pequeños, y el QAT de PyTorch no tiene LayerNorm interna en su BitLinear (a diferencia del BitLinear original).
|
|
143
|
+
Además, las dos reglas de entrenamiento difieren (R2 sin pesos float contra Adam en float32).
|
|
144
|
+
- **Hilos** (`tn.set_threads(n)`, `tn.set_engine_threads(n)`): el resultado es idéntico bit a bit con cualquier cantidad.
|
|
145
|
+
- **Formato en memoria:** en disco un peso ocupa 1,6 bits (5 valores ternarios por byte); el motor mantiene los pesos a 2 bits y una caché KV compacta.
|
|
146
|
+
|
|
147
|
+
## Límites conocidos
|
|
148
|
+
|
|
149
|
+
- Todo se ha validado con modelos pequeños (hasta unos 0,5 M de pesos en los bloques). No hay resultados con modelos grandes.
|
|
150
|
+
- A igual número de pesos, un modelo float da mejor calidad que el ternario: en una prueba con novelas en español, a los 25 minutos el float tenía pérdida 4,32 contra 4,51 del ternario.
|
|
151
|
+
La ventaja del ternario está en la memoria, el tamaño en disco y la velocidad de inferencia, no en la calidad por peso.
|
|
152
|
+
Es lo esperado: un modelo ternario (1,58 bits por parámetro) tiene menos capacidad que uno float con el mismo número de parámetros. Los estudios de Microsoft sobre BitNet b1.58
|
|
153
|
+
([arXiv:2402.17764](https://arxiv.org/abs/2402.17764)) reportan que esa desventaja desaparece a partir de unos 3 mil millones de parámetros (frente a una base FP16, en perplejidad). Es un resultado
|
|
154
|
+
reportado por esos estudios, con una receta de entrenamiento distinta de la nuestra; no se ha reproducido con esta librería, que solo se ha validado con modelos pequeños.
|
|
155
|
+
- La atención a larga distancia pide subir `rope_base` (por defecto 10; con 1000 se validó a 512 tokens).
|
|
156
|
+
|
|
157
|
+
## Pruebas
|
|
158
|
+
|
|
159
|
+
```bash
|
|
160
|
+
make test # pruebas de C (≈15 min)
|
|
161
|
+
make test-python # pruebas de Python (compila antes la librería)
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
## Licencia
|
|
166
|
+
|
|
167
|
+
Apache License 2.0. Texto completo en [`LICENSE`](LICENSE) y avisos en [`NOTICE`](NOTICE). Copyright 2026 FDeveloper-hub.
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
include Makefile LICENSE NOTICE README.md LEEME.md
|
|
2
|
+
include docs/MANUAL.md docs/MANUAL.en.md tests/test_manual.py tests/test_bits.py
|
|
3
|
+
recursive-include src *.c *.h *.map
|
|
4
|
+
recursive-include include *.h
|
|
5
|
+
recursive-include python/ternaryai *.py
|
|
6
|
+
prune python/tests
|
|
7
|
+
global-exclude *.o *.so *.pyc __pycache__
|