Neural networks with zero multiplications at inference. AdderNet + HDC for embedded systems.
Project description
AdderNet
Biblioteca de machine learning que não usa multiplicação na inferência. Zero.
O que é?
AdderNet tem duas camadas:
- AdderNet — funções de uma variável, lookup table, zero multiplicação
- AdderNet-HDC — múltiplas variáveis, Hyperdimensional Computing, generalização por bundle, criatividade com temperatura
Instalação
pip install addernet
Ou do código-fonte:
git clone ...
cd addernet_lib
make
pip install -e .
Uso — Uma variável
from addernet import AdderNetLayer
# Criar a rede
rede = AdderNetLayer(size=256, bias=50, input_min=-50, input_max=200, lr=0.1)
# Dados de treino: Celsius -> Fahrenheit
celsius = [0, 10, 20, 25, 30, 37, 50, 80, 100]
fahrenheit = [32, 50, 68, 77, 86, 98.6, 122, 176, 212]
# Treinar
rede.train(celsius, fahrenheit)
# Prever
print(rede.predict(37)) # 98.60
print(rede.predict(100)) # 212.00
Salvar e carregar
rede.save("meu_modelo.bin")
rede = AdderNetLayer.load("meu_modelo.bin")
print(rede.predict(37)) # 98.60
Previsão em lote (numpy)
import numpy as np
entradas = np.array([0, 25, 37, 100], dtype=np.float64)
saidas = rede.predict_batch(entradas)
# array([32.0, 77.0, 98.6, 212.0])
Uso — AdderNet-HDC (múltiplas variáveis)
import sys
sys.path.insert(0, 'python')
from addernet_hdc import AdderNetHDC
import numpy as np
from sklearn.datasets import load_iris
# Carregar dados
iris = load_iris()
X, y = iris.data, iris.target
# Criar modelo (4 variáveis, 3 classes)
model = AdderNetHDC(n_vars=4, n_classes=3, table_size=256, seed=42)
# Treinar
model.train(X, y)
# Prever
pred = model.predict(X[0])
print(f"Classe predita: {pred}")
# Batch com múltiplas threads
model.set_threads(4)
preds = model.predict_batch(X)
# Ativar cache para máxima velocidade
model.warm_cache()
preds = model.predict_batch(X) # ~3x mais rápido
# Salvar e carregar
model.save("iris_model.bin")
model = AdderNetHDC.load("iris_model.bin")
Generalização e criatividade
# Misturar dois conceitos — gera algo novo sem ver dados
roupa_nova = model.bundle_classes([0, 4]) # camiseta + casaco
# Temperatura — variações controladas
for temp in [0.0, 0.1, 0.2, 0.3, 0.5]:
variacao = model.add_noise(model.codebook[0], temp)
print(f"temp={temp} → {model.classify_hv(variacao)}")
Otimizações disponíveis
from addernet import AdderNetHDC, hdc_detect_backend
print(hdc_detect_backend()) # 'AVX2', 'NEON', ou 'SCALAR'
model.set_threads(8) # multithreading
model.warm_cache() # pré-computar hipervectors
model.set_cache(False) # desligar cache (hardware com pouca RAM)
Performance
AdderNet (uma variável):
C lote numpy: ~247M pred/s
AdderNet-HDC (múltiplas variáveis, Iris):
Baseline (1 thread): ~13.779 pred/s
Cache + 4 threads: ~31.947 pred/s
Cache + 8 threads: ~38.704 pred/s
mulsd em inferência: 0
Acurácia Iris: 80.0%
Memória do modelo: 128KB (D=5000)
Para melhor performance em Python, use predict_batch() com arrays numpy.
Casos de uso
- Sensores industriais com hardware limitado (sem FPU)
- Classificação em tempo real embarcada (ESP32, STM32, RPi)
- Privacidade: dados originais não precisam ser guardados pós-treino
- One-shot learning: aprende classe nova com uma única amostra
Exemplos prontos
cd addernet_lib
# Celsius -> Fahrenheit (uma variável)
python3 examples/basic/celsius_fahrenheit.py
# AdderNet-HDC com Iris
python3 examples/hdc/iris_hdc.py
# Benchmark HDC
python3 examples/hdc/benchmark_hdc.py
# Benchmark otimizações
python3 examples/hdc/benchmark_otimizado.py
Estrutura de arquivos
addernet_lib/
├── src/ ← código C otimizado (AVX2, NEON)
├── python/ ← bindings Python
├── tests/
├── examples/
│ ├── basic/ ← AdderNet básica
│ ├── hdc/ ← AdderNet-HDC
│ └── creativity/
├── build/
└── Makefile ← detecção automática de plataforma
Limitações
- AdderNet básica: só uma variável de entrada
- AdderNet-HDC: acurácia inferior a MLP em datasets complexos (~80% vs ~98%)
- Contexto sequencial ainda não implementado (LLM embarcado em desenvolvimento)
- D muito pequeno (< 1000) colapsa a acurácia
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distributions
No source distribution files available for this release.See tutorial on generating distribution archives.
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
addernet-1.0.1-py3-none-any.whl
(55.8 kB
view details)
File details
Details for the file addernet-1.0.1-py3-none-any.whl.
File metadata
- Download URL: addernet-1.0.1-py3-none-any.whl
- Upload date:
- Size: 55.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
96d8d53819c3439acb5e24a71b334134a5292ff2a1a371c0b61f3b1c8263a76d
|
|
| MD5 |
ea7f0bc55d6f8a89d6cab17f9c878697
|
|
| BLAKE2b-256 |
95f3c9491252ba8af86013187c63d4384953778fdbf285467f10f81eed49d424
|