Metadata-Version: 2.4
Name: r3alai
Version: 1.0.1
Summary: R3AL.ai vision ONNX quantization SDK (PTQ + QAT) — pip package r3alai
Project-URL: Homepage, https://github.com/R3AL-AI/SDK
Project-URL: Repository, https://github.com/R3AL-AI/SDK
Author: R3AL.ai
License-Expression: MIT
License-File: LICENSE
Keywords: onnx,ptq,quantization,runpod,vision,yolo
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Requires-Dist: numpy>=1.24.0
Requires-Dist: pydantic>=2.0
Requires-Dist: torch>=2.1.0
Provides-Extra: all
Requires-Dist: dill>=0.3.8; extra == 'all'
Requires-Dist: gitpython>=3.1.0; extra == 'all'
Requires-Dist: matplotlib>=3.3.0; extra == 'all'
Requires-Dist: onnx2torch>=1.5.0; extra == 'all'
Requires-Dist: onnx>=1.15.0; extra == 'all'
Requires-Dist: onnxruntime-gpu>=1.16.0; (sys_platform != 'darwin') and extra == 'all'
Requires-Dist: onnxruntime>=1.16.0; (sys_platform == 'darwin') and extra == 'all'
Requires-Dist: onnxscript>=0.1.0; extra == 'all'
Requires-Dist: opencv-python>=4.6.0; extra == 'all'
Requires-Dist: paddle2onnx>=1.3.0; extra == 'all'
Requires-Dist: paddlepaddle>=3.0.0; extra == 'all'
Requires-Dist: pandas>=1.1.0; extra == 'all'
Requires-Dist: pillow>=10.0.0; extra == 'all'
Requires-Dist: pyyaml>=5.3.1; extra == 'all'
Requires-Dist: scipy>=1.4.0; extra == 'all'
Requires-Dist: seaborn>=0.11.0; extra == 'all'
Requires-Dist: tensorflow>=2.12.0; extra == 'all'
Requires-Dist: tf2onnx>=1.16.0; extra == 'all'
Requires-Dist: tflite2onnx>=0.4.0; extra == 'all'
Requires-Dist: thop>=0.1.1; extra == 'all'
Requires-Dist: tqdm>=4.66.0; extra == 'all'
Requires-Dist: ultralytics>=8.4.0; extra == 'all'
Provides-Extra: dev
Requires-Dist: ruff>=0.1.0; extra == 'dev'
Provides-Extra: export-paddle
Requires-Dist: paddle2onnx>=1.3.0; extra == 'export-paddle'
Requires-Dist: paddlepaddle>=3.0.0; extra == 'export-paddle'
Provides-Extra: export-tf
Requires-Dist: tensorflow>=2.12.0; extra == 'export-tf'
Requires-Dist: tf2onnx>=1.16.0; extra == 'export-tf'
Provides-Extra: export-tflite
Requires-Dist: tflite2onnx>=0.4.0; extra == 'export-tflite'
Provides-Extra: vision
Requires-Dist: onnx2torch>=1.5.0; extra == 'vision'
Requires-Dist: onnx>=1.15.0; extra == 'vision'
Requires-Dist: onnxruntime-gpu>=1.16.0; (sys_platform != 'darwin') and extra == 'vision'
Requires-Dist: onnxruntime>=1.16.0; (sys_platform == 'darwin') and extra == 'vision'
Requires-Dist: onnxscript>=0.1.0; extra == 'vision'
Requires-Dist: pillow>=10.0.0; extra == 'vision'
Provides-Extra: yolo
Requires-Dist: dill>=0.3.8; extra == 'yolo'
Requires-Dist: gitpython>=3.1.0; extra == 'yolo'
Requires-Dist: matplotlib>=3.3.0; extra == 'yolo'
Requires-Dist: opencv-python>=4.6.0; extra == 'yolo'
Requires-Dist: pandas>=1.1.0; extra == 'yolo'
Requires-Dist: pyyaml>=5.3.1; extra == 'yolo'
Requires-Dist: scipy>=1.4.0; extra == 'yolo'
Requires-Dist: seaborn>=0.11.0; extra == 'yolo'
Requires-Dist: thop>=0.1.1; extra == 'yolo'
Requires-Dist: tqdm>=4.66.0; extra == 'yolo'
Requires-Dist: ultralytics>=8.4.0; extra == 'yolo'
Description-Content-Type: text/markdown

# R3AL.ai — r3alai

**R3AL.ai** is the library brand. **`r3alai`** is de Python package (`pip install r3alai`); import als **`r3alai`**.

Universele vision-model quantisatie, architectuur-onafhankelijk — niet enkel YOLO. Volledige round trip:

```
jouw_model (.pt/.h5/.tflite/...)  →  export naar ONNX  →  quantize (PTQ) of qat_pipeline  →  quantized .onnx
                                                                                            ↳  export_native=True → terug naar native .pt (torch.nn.Module, elke architectuur)
```

Geen vendor lock-in: exporteer vanuit PyTorch, TensorFlow/Keras, Ultralytics YOLO, TFLite, Paddle, of een kant-en-klaar ONNX-bestand — en na quantisatie kan het resultaat weer teruggebouwd worden naar een gewoon `.pt`-bestand, ongeacht de bron-architectuur (ResNet, EfficientNet, ViT, YOLO, willekeurig HuggingFace vision-model, ...).

## Benaming

| Laag | Naam | Voorbeeld |
|------|------|-----------|
| Merk / repo | **R3AL.ai** | documentatie, manifest `producer` |
| PyPI-package | **`r3alai`** | `pip install r3alai[vision]` |
| Python-module | **`r3alai`** (SDK in `r3alai.quant`) | `from r3alai.quant import Quantizer` |

## Export naar ONNX (elke architectuur)

`export_to_onnx` kiest automatisch de juiste adapter op basis van bestandsextensie, of forceer met `source=`:

| `source` | Input | Aliassen |
|----------|-------|----------|
| `ultralytics` | YOLO `.pt` | `yolo` |
| `pytorch` | opgeslagen `torch.nn.Module` (`.pt`/`.pth`, vereist `input_shape`) | `torch` |
| `tensorflow` | SavedModel-map, `.h5`, `.keras`, `.pb` | `tf`, `keras` |
| `paddle` | Paddle inference-model (`.pdmodel`/`.json` + `.pdiparams`) | `paddlepaddle` |
| `tflite` | `.tflite` | — |
| `onnx` | valideert/staged een bestaand `.onnx`-bestand | — |

```python
from r3alai.quant.export import export_to_onnx

export_to_onnx("yolo11n-pose.pt", output_dir="./out", source="ultralytics", imgsz=640)
export_to_onnx("resnet18.pt", output_dir="./out", source="pytorch", input_shape=[1, 3, 224, 224])
export_to_onnx("model.h5", output_dir="./out", source="tensorflow")
```

## Terug naar native `.pt` (na PTQ of QAT)

Elke PTQ-backend en QAT-pipeline ondersteunt `export_native=True`: de gequantiseerde ONNX-graph wordt via
[`onnx2torch`](https://github.com/ENOT-AutoDL/onnx2torch) teruggebouwd tot een gewone `torch.nn.Module` en
opgeslagen als `.pt` — architectuur-onafhankelijk, dus werkt voor elk model dat via bovenstaande adapters
geëxporteerd kon worden, niet enkel YOLO.

```python
result = Quantizer().quantize("resnet18.onnx", output_dir="./out", export_native=True)
# result.path bevat zowel de .quantized.onnx als een .pt terug-geconstrueerd model
```

Best-effort: als de reconstructie faalt (bv. exotische `QuantizeLinear`/`QLinear*` ops die onnx2torch niet
kent), faalt de quantisatie-job zelf niet — de fout wordt gerapporteerd in het manifest
(`native_export_error`) en de `.onnx`-deliverable blijft het primaire, altijd-geldige resultaat.

Voor PTQ-methodes die zelf geen echte int8-graph produceren (`weight_quant` herschrijft alleen
initializer-waardes in fp32; QAT vouwt getrainde `QuantConv2d`-lagen terug naar gewone fp32 `Conv2d`), zet
ook `int8_runtime=True` om er een echte ONNX Runtime static-int8 pass bovenop te draaien — dat levert een
apart, genuinely kleiner deliverable op (pad terug te vinden als `int8_runtime_output_model` in het
manifest / de API-response).

## Twee paradigma's

| Paradigma | Action | Input | Training | Wanneer |
|-----------|--------|-------|----------|---------|
| **PTQ** (post-training) | `quantize` | `.onnx` | Nee | Snel, geen dataset nodig (behalve `int8_static`) |
| **QAT** (quantization-aware training) | `qat_pipeline` | `.onnx` + beelden | Ja (`epochs`) | PTQ-accuracy niet goed genoeg, lage bit-width |

## PTQ-methodes (`action: quantize`)

| `method` | Voor | Levert echt kleinere int8-graph? |
|----------|------|-----------------------------------|
| **`weight_quant`** | Default — weight quantisatie (APoT/uniform) op elk ONNX vision model | Nee (fp32-opslag, accuracy-proxy) — gebruik `int8_runtime=True` |
| `int8_dynamic` | ONNX Runtime dynamic INT8 (MatMul/Gemm — Conv wordt bewust overgeslagen, geen betrouwbare ConvInteger-kernel) | Ja |
| `int8_static` | ONNX Runtime static INT8 QDQ (+ calibratiebeelden) | Ja |

`int8_static` gebruikt standaard `per_channel=True` en sluit automatisch ops dicht bij de graph-outputs uit
van quantisatie (bv. de Sigmoid/Concat van een detectiekop) — met weinig calibratiebeelden kunnen die
gevoelige eind-ops anders de accuracy volledig laten instorten (mAP ≈ 0). Override met `nodes_to_exclude`
of `per_channel=False` indien nodig.

Beide `int8_static` en `int8_dynamic` sluiten daarnaast standaard Softmax/LayerNormalization/Gelu/Erf
(plus de MatMul/Gemm die rechtstreeks in/uit een Softmax lopen) uit van quantisatie —
`exclude_attention_sensitive_ops=True` by default. Attention-softmax en LayerNorm-activaties hebben zeer
piekvormige/kleine-variantie waardebereiken die onder een lineaire int8-schaal verzadigen; op
transformer-achtige backbones (CLIP ViT, CLIPSeg-decoder e.d.) leidde dit zonder deze uitsluiting tot een
volledige instorting (pseudo mAP50/mAP50-95 == 0.0 voor élke echte int8-deliverable), niet slechts een
kleine accuracy-dip. Zet `exclude_attention_sensitive_ops=False` om dit uit te schakelen, of geef een
expliciete `nodes_to_exclude` mee om beide auto-detecties te overschrijven.

## QAT (`action: qat_pipeline`)

Universeel ONNX in → train met fake-quant layers → ONNX out. Geen aparte `method` — gebruik `wbit`, `abit`, `scheme`.

```json
{
  "input": {
    "action": "qat_pipeline",
    "model": "/runpod-volume/models/yolov8n.onnx",
    "calibration_data": ["/runpod-volume/images/img1.jpg"],
    "epochs": 1,
    "scheme": "apot",
    "wbit": 8,
    "abit": 8
  }
}
```

## Quick Start

```python
from r3alai.quant import Quantizer, QuantConfig

# PTQ — elk vision ONNX, met terug-export naar native .pt
Quantizer().quantize("efficientnet_b0.onnx", output_dir="./out", export_native=True)
Quantizer().quantize("yolov8n.onnx", scheme="apot", wbit=8)

# QAT — ONNX + training images (generieke pipeline)
Quantizer(QuantConfig(mode="qat")).train_qat(
    "yolov8n.onnx",
    calibration_data=["img1.jpg", "img2.jpg"],
    output_dir="./qat_out",
    epochs=3,
    export_native=True,
    int8_runtime=True,  # levert ook een echt gecomprimeerde int8-deliverable op
)

# QAT — native Ultralytics .pt in (behoudt de YOLO detectie/pose-kop intact)
Quantizer(QuantConfig(mode="qat")).train_qat(
    "yolo11n-pose.pt",
    calibration_data=["img1.jpg", "img2.jpg"],
    output_dir="./qat_out",
    source="ultralytics",
    epochs=3,
    export_native=True,  # gebruikt YOLO.save() -> normaal YOLO(path)-laadbaar checkpoint
)
```

## RunPod API

De RunPod serverless handler en deploy-tooling zitten niet in deze repo —
die leven in de aparte `r3alai-api` repo (`D:\R3al-API`), die
`r3alai` als dependency installeert en dezelfde `Quantizer`/`QuantConfig`
aanroept via een JSON job-payload, bv.:

```json
{
  "input": {
    "action": "quantize",
    "model": "/runpod-volume/models/jouw_model.onnx"
  }
}
```

Zie de `docs/API.md` en `docs/api-reference/` in de `r3alai-api` repo
voor de volledige API-referentie.

## Install

```bash
pip install r3alai[vision]        # PTQ + QAT op ONNX-modellen
pip install r3alai[vision,yolo]   # + Ultralytics YOLO support
pip install r3alai[all]           # alle export-adapters (TF, Paddle, TFLite)
```

Voor lokale ontwikkeling: `pip install -e ".[vision]"`.

QAT vereist `onnx2torch` (included in `[vision]`).

## Tests & benchmarks

Leven in de aparte `R3AL.ai Benchmarks SDK` map/repo (niet in deze repo) —
zie de README daar. Die installeert `r3alai` als editable path-dependency.

MIT
