omurberaisik's picture
Update README.md
e50d794 verified
|
Raw History Blame Contribute Delete
8.62 kB
---
license: other
library_name: transformers
pipeline_tag: image-classification
datasets:
- ILSVRC/imagenet-1k
tags:
- image-classification
- imagenet-1k
- jax
- tpu
- muon
- convnext
- hybrid
- custom_code
- notokenlm
---
# NoTokenLM-ImageGen-Class-2.5
**NoTokenLM-ImageGen-Class-2.5** is a small (**6.48 M parameters**) ImageNet-1k image classifier, trained from scratch in JAX on a single TPU v5e-1. It is a hybrid convolution / attention network: a 4×4 space-to-depth stem, Fused-MBConv and ConvNeXt-style stages, and a single global-attention layer in the last block. There are no tokens and no patch-embedding transformer trunk. It takes images at **64 px or 128 px** and predicts one of the 1,000 ImageNet-1k classes.
| | |
|---|---|
| Parameters | **6,479,016** |
| Input | RGB image, any size (prepared to 64 or 128 px, see [Preprocessing](#preprocessing)) |
| Output | logits over the 1,000 ImageNet-1k classes |
| Training | **112,097 steps**, 64 px → 128 px progressive schedule |
| Optimizer | Muon (matrix weights) + AdamW, EMA weights |
| Hardware | 1 × TPU v5e-1 (Google Colab) |
| Weights | EMA weights, fp32 (`model.safetensors`) |
| Framework | trained in JAX (`ntlm_core.py`); PyTorch inference code included |
## Architecture
```
image (H×W×3, 0..255) ─► (x − 127.5) / 127.5
─► stem: 4×4 space-to-depth (48 ch) ─► 3×3 conv ─► LayerNorm stride 4 64 ch
─► stage 1: 2 × Fused-MBConv (LN · 3×3 conv ×4 · GELU · 1×1 · layer-scale) stride 4 64 ch
─► down 1: LN ─► 2×2 conv, stride 2
─► stage 2: 3 × ConvNeXt block (7×7 depthwise · LN · MLP ×4 · layer-scale) stride 8 128 ch
─► down 2: LN ─► 2×2 conv, stride 2
─► stage 3: 3 × ConvNeXt block (MLP ×4) stride 16 256 ch
─► down 3: LN ─► 1×1 projection
─► stage 4: 2 × ConvNeXt block (MLP ×3); the last one is followed by 4-head global self-attention stride 16 384 ch
─► global average pool ─► LN ─► Linear(384→1024) ─► GELU ─► Linear(1024→1000)
```
The output stride is 16, so H and W must be multiples of 16. Stage 4 attends over 8×8 = 64 positions at 128 px (4×4 = 16 at 64 px). Layer-scale vectors, stochastic depth (0.1 at training time) and tanh-GELU are used throughout.
## Quick start
Requires `torch`, `transformers`, `safetensors`, `pillow`. `trust_remote_code=True` is needed because the architecture ships with the weights.
```python
from transformers import AutoModelForImageClassification
model = AutoModelForImageClassification.from_pretrained(
"VeroLM/NoTokenLM-ImageGen-Class-2.5", trust_remote_code=True).eval()
for p in model.predict("cat.jpg", top_k=5, resolution=128):
print(f"{p['score'] * 100:5.1f}% {p['label']}")
```
`model.predict(images, top_k=5, resolution=None)` accepts a PIL image, a file path, an `H×W×3` uint8 array, or a list of those, and returns `[{"id", "label", "score"}, …]` per image (`score` is the softmax probability). `resolution` defaults to 128; 64 also works (see [Results](#results)).
Using the raw forward pass:
```python
import torch
x = model.preprocess(["a.jpg", "b.png"], resolution=128) # float32 (N, 3, 128, 128), values 0..255
with torch.no_grad():
logits = model(x).logits # (N, 1000)
```
### Command line
```bash
pip install -r requirements.txt
python inference.py cat.jpg dog.png https://example.com/photo.jpg --res 128 --topk 5
python inference.py photo.jpg --res 64 --json # machine-readable output
python inference.py photo.jpg --model ./local_folder # local copy of this repo
```
Options: `--device cpu|cuda`, `--dtype float32|bfloat16`, `--token` (or the `HF_TOKEN` variable, only needed for private repos).
### Notebook
[`notebook.ipynb`](./notebook.ipynb) is an interactive playground for Colab / Kaggle / Jupyter: upload an image or paste a URL, choose 64 px or 128 px, and see the top-k predictions as bars.
### Reproduce the validation accuracy
```bash
python evaluate.py --res 128 # downloads benjamin-paine/imagenet-1k-128x128 (gated, needs HF_TOKEN)
python evaluate.py --res 64 --limit 5000 # quick check
python evaluate.py --res 128 --parquet val-00000-of-00002.parquet val-00001-of-00002.parquet
```
## Preprocessing
The model was trained on the `benjamin-paine/imagenet-1k-64x64` / `-128x128` repacks, which were built by centre-cropping each image to a square on its short side and then resizing with Lanczos (original → 256 → 128 → 64). `preprocess_images` (used by `predict`) reproduces exactly that chain: **centre square crop → Lanczos 256 → Lanczos 128 → Lanczos to the target resolution**. Pixel values stay in 0..255; normalisation is part of the model. If you use your own preprocessing, follow the same recipe, otherwise accuracy will drop.
Supported resolutions: any multiple of 16. The model was trained at 64 px and 128 px only; other sizes run but are untested.
## Training
The run totals **112,097 optimizer steps**, in three phases:
| Phase | Resolution | Data | Batch |
|---|---|---|---|
| `A_64` | 64 px | full ImageNet-1k train set (1,281,167 images) | 512 |
| `B_128` | 128 px | class-balanced subset, 300 images per class (300,000) | 256 |
| `C_128` | 128 px | the remaining training images | 256 |
* **Optimizer:** Muon (Newton-Schulz, 5 iterations, Nesterov, momentum 0.95) for all 2-D weight matrices except the classifier; AdamW-style updates for everything else (biases, norms, layer-scales, convolution kernels, classifier). Weight decay 0.05, global gradient-norm clip 1.0.
* **Schedule:** peak LR 2e-3, 2-epoch warm-up, cosine decay over `A_64` + `B_128`. `C_128` restarts with its own short warm-up (300 steps) to a peak LR of 5e-4.
* **Regularisation / augmentation:** random-resized-crop (scale 0.30–1.0, aspect 3/4–4/3) and horizontal flip computed on-device, label smoothing 0.1, stochastic depth 0.1. CutMix was available but turned off.
* **EMA:** decay up to 0.9999 (0.999 during `C_128`); the EMA weights are what `model.safetensors` contains.
* **Numerics:** bfloat16 activations with fp32 parameters and fp32 LayerNorm/softmax.
* **Hardware:** one TPU v5e-1; training survived session restarts through checkpoints that were resumed from the Hub.
## PyTorch vs. JAX
The PyTorch code was checked against the original JAX implementation on random weights of the full configuration (64 px and 128 px inputs): the maximum absolute logit difference is about 4e-5 when both run in fp32. Training used bfloat16 activations, so fp32 inference can differ slightly from the training-time numerics; `--dtype bfloat16` (or `model.to(torch.bfloat16)`) matches them more closely.
## Intended use and limitations
* **Intended for:** research and teaching on small, efficient image classifiers, a reference for Muon-trained hybrid conv/attention networks, and low-cost ImageNet-1k classification at low resolution.
* **Not for:** safety-critical or high-stakes decisions, face/person analysis, or any use that needs reliable behaviour outside ImageNet-1k's 1,000 classes. The model always outputs one of the 1,000 classes, even for images that match none of them.
* Low input resolution (64–128 px) limits accuracy on small or fine-grained details compared with models evaluated at 224 px and above.
* ImageNet carries the biases, label noise and gaps of its source data; the model inherits them.
## Repository contents
| File | What it is |
|---|---|
| `model.safetensors` | EMA weights (fp32), JAX tensor names/shapes (conv kernels HWIO, dense kernels in×out) |
| `config.json` | architecture hyper-parameters and the 1,000 class names (`id2label`) |
| `configuration_ntlm_class25.py`, `modeling_ntlm_class25.py` | PyTorch / `transformers` implementation (inference) and image preprocessing |
| `ntlm_core.py` | original JAX model, Muon optimizer and augmentation code used for training |
| `inference.py` | command-line classifier |
| `evaluate.py` | ImageNet-1k validation-accuracy script |
| `notebook.ipynb` | interactive playground |
| `requirements.txt` | Python dependencies |
## License and data
ImageNet-1k (ILSVRC 2012) is distributed under terms that permit non-commercial research and educational use only. The weights were trained on it (via the `benjamin-paine/imagenet-1k-64x64` and `-128x128` repacks), so please take those terms into account before using or redistributing the weights. The weights' license is therefore marked `other`.