omurberaisik commited on
Commit
377e8b9
·
verified ·
1 Parent(s): 78d0c6d

Upload 9 files

Browse files
Files changed (9) hide show
  1. README.md +154 -1
  2. config.json +2040 -0
  3. configuration_ntlm_class25.py +35 -0
  4. evaluate.py +81 -0
  5. inference.py +60 -0
  6. modeling_ntlm_class25.py +308 -0
  7. notebook.ipynb +213 -0
  8. ntlm_core.py +340 -0
  9. requirements.txt +7 -0
README.md CHANGED
@@ -1,3 +1,156 @@
1
  ---
2
- license: apache-2.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ license: other
3
+ library_name: transformers
4
+ pipeline_tag: image-classification
5
+ datasets:
6
+ - ILSVRC/imagenet-1k
7
+ tags:
8
+ - image-classification
9
+ - imagenet-1k
10
+ - jax
11
+ - tpu
12
+ - muon
13
+ - convnext
14
+ - hybrid
15
+ - custom_code
16
+ - notokenlm
17
  ---
18
+
19
+ # NoTokenLM-ImageGen-Class-2.5
20
+
21
+ **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.
22
+
23
+ | | |
24
+ |---|---|
25
+ | Parameters | **6,479,016** |
26
+ | Input | RGB image, any size (prepared to 64 or 128 px, see [Preprocessing](#preprocessing)) |
27
+ | Output | logits over the 1,000 ImageNet-1k classes |
28
+ | Training | **112,097 steps**, 64 px → 128 px progressive schedule |
29
+ | Optimizer | Muon (matrix weights) + AdamW, EMA weights |
30
+ | Hardware | 1 × TPU v5e-1 (Google Colab) |
31
+ | Weights | EMA weights, fp32 (`model.safetensors`) |
32
+ | Framework | trained in JAX (`ntlm_core.py`); PyTorch inference code included |
33
+
34
+ ## Architecture
35
+
36
+ ```
37
+ image (H×W×3, 0..255) ─► (x − 127.5) / 127.5
38
+ ─► stem: 4×4 space-to-depth (48 ch) ─► 3×3 conv ─► LayerNorm stride 4 64 ch
39
+ ─► stage 1: 2 × Fused-MBConv (LN · 3×3 conv ×4 · GELU · 1×1 · layer-scale) stride 4 64 ch
40
+ ─► down 1: LN ─► 2×2 conv, stride 2
41
+ ─► stage 2: 3 × ConvNeXt block (7×7 depthwise · LN · MLP ×4 · layer-scale) stride 8 128 ch
42
+ ─► down 2: LN ─► 2×2 conv, stride 2
43
+ ─► stage 3: 3 × ConvNeXt block (MLP ×4) stride 16 256 ch
44
+ ─► down 3: LN ─► 1×1 projection
45
+ ─► stage 4: 2 × ConvNeXt block (MLP ×3); the last one is followed by 4-head global self-attention stride 16 384 ch
46
+ ─► global average pool ─► LN ─► Linear(384→1024) ─► GELU ─► Linear(1024→1000)
47
+ ```
48
+
49
+ 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.
50
+
51
+ ## Quick start
52
+
53
+ Requires `torch`, `transformers`, `safetensors`, `pillow`. `trust_remote_code=True` is needed because the architecture ships with the weights.
54
+
55
+ ```python
56
+ from transformers import AutoModelForImageClassification
57
+
58
+ model = AutoModelForImageClassification.from_pretrained(
59
+ "VeroLM/NoTokenLM-ImageGen-Class-2.5", trust_remote_code=True).eval()
60
+
61
+ for p in model.predict("cat.jpg", top_k=5, resolution=128):
62
+ print(f"{p['score'] * 100:5.1f}% {p['label']}")
63
+ ```
64
+
65
+ `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)).
66
+
67
+ Using the raw forward pass:
68
+
69
+ ```python
70
+ import torch
71
+
72
+ x = model.preprocess(["a.jpg", "b.png"], resolution=128) # float32 (N, 3, 128, 128), values 0..255
73
+ with torch.no_grad():
74
+ logits = model(x).logits # (N, 1000)
75
+ ```
76
+
77
+ ### Command line
78
+
79
+ ```bash
80
+ pip install -r requirements.txt
81
+ python inference.py cat.jpg dog.png https://example.com/photo.jpg --res 128 --topk 5
82
+ python inference.py photo.jpg --res 64 --json # machine-readable output
83
+ python inference.py photo.jpg --model ./local_folder # local copy of this repo
84
+ ```
85
+
86
+ Options: `--device cpu|cuda`, `--dtype float32|bfloat16`, `--token` (or the `HF_TOKEN` variable, only needed for private repos).
87
+
88
+ ### Notebook
89
+
90
+ [`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.
91
+
92
+ ### Reproduce the validation accuracy
93
+
94
+ ```bash
95
+ python evaluate.py --res 128 # downloads benjamin-paine/imagenet-1k-128x128 (gated, needs HF_TOKEN)
96
+ python evaluate.py --res 64 --limit 5000 # quick check
97
+ python evaluate.py --res 128 --parquet val-00000-of-00002.parquet val-00001-of-00002.parquet
98
+ ```
99
+
100
+ ## Preprocessing
101
+
102
+ 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.
103
+
104
+ Supported resolutions: any multiple of 16. The model was trained at 64 px and 128 px only; other sizes run but are untested.
105
+
106
+ ## Results
107
+
108
+ ImageNet-1k validation set (50,000 images), EMA weights, single centre view, no test-time augmentation. Produced with `evaluate.py`.
109
+
110
+ | Input resolution | Top-1 | Top-5 |
111
+ |---|---|---|
112
+ | 64 px | TBD | TBD |
113
+ | 128 px | TBD | TBD |
114
+
115
+ ## Training
116
+
117
+ | Phase | Resolution | Data | Batch | Steps |
118
+ |---|---|---|---|---|
119
+ | `A_64` | 64 px | full ImageNet-1k train (1,281,167 images), 40 epochs | 512 | 100,080 |
120
+ | `B_128` | 128 px | class-balanced subset, 300 images per class (300,000), 10 epochs | 256 | 11,710 |
121
+ | `C_128` | 128 px | the remaining 981,167 training images, planned as a single pass (3,832 steps) | 256 | training stopped at step 112,097 in total |
122
+
123
+ * **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.
124
+ * **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.
125
+ * **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.
126
+ * **EMA:** decay up to 0.9999 (0.999 during `C_128`); the EMA weights are what `model.safetensors` contains.
127
+ * **Numerics:** bfloat16 activations with fp32 parameters and fp32 LayerNorm/softmax.
128
+ * **Hardware:** one TPU v5e-1; training survived session restarts through checkpoints that were resumed from the Hub.
129
+
130
+ ## PyTorch vs. JAX
131
+
132
+ 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.
133
+
134
+ ## Intended use and limitations
135
+
136
+ * **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.
137
+ * **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.
138
+ * Low input resolution (64–128 px) limits accuracy on small or fine-grained details compared with models evaluated at 224 px and above.
139
+ * ImageNet carries the biases, label noise and gaps of its source data; the model inherits them.
140
+
141
+ ## Repository contents
142
+
143
+ | File | What it is |
144
+ |---|---|
145
+ | `model.safetensors` | EMA weights (fp32), JAX tensor names/shapes (conv kernels HWIO, dense kernels in×out) |
146
+ | `config.json` | architecture hyper-parameters and the 1,000 class names (`id2label`) |
147
+ | `configuration_ntlm_class25.py`, `modeling_ntlm_class25.py` | PyTorch / `transformers` implementation (inference) and image preprocessing |
148
+ | `ntlm_core.py` | original JAX model, Muon optimizer and augmentation code used for training |
149
+ | `inference.py` | command-line classifier |
150
+ | `evaluate.py` | ImageNet-1k validation-accuracy script |
151
+ | `notebook.ipynb` | interactive playground |
152
+ | `requirements.txt` | Python dependencies |
153
+
154
+ ## License and data
155
+
156
+ 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`.
config.json ADDED
@@ -0,0 +1,2040 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "ntlm_class25",
3
+ "architectures": [
4
+ "NTLMClass25ForImageClassification"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_ntlm_class25.NTLMClass25Config",
8
+ "AutoModelForImageClassification": "modeling_ntlm_class25.NTLMClass25ForImageClassification"
9
+ },
10
+ "widths": [
11
+ 64,
12
+ 128,
13
+ 256,
14
+ 384
15
+ ],
16
+ "depths": [
17
+ 2,
18
+ 3,
19
+ 3,
20
+ 2
21
+ ],
22
+ "ratios": [
23
+ 4,
24
+ 4,
25
+ 4,
26
+ 3
27
+ ],
28
+ "heads": 4,
29
+ "head_dim": 1024,
30
+ "num_classes": 1000,
31
+ "dw_k": 7,
32
+ "ls_init": 0.01,
33
+ "drop_path": 0.1,
34
+ "default_resolution": 128,
35
+ "id2label": {
36
+ "0": "tench",
37
+ "1": "goldfish",
38
+ "2": "great white shark",
39
+ "3": "tiger shark",
40
+ "4": "hammerhead",
41
+ "5": "electric ray",
42
+ "6": "stingray",
43
+ "7": "cock",
44
+ "8": "hen",
45
+ "9": "ostrich",
46
+ "10": "brambling",
47
+ "11": "goldfinch",
48
+ "12": "house finch",
49
+ "13": "junco",
50
+ "14": "indigo bunting",
51
+ "15": "robin",
52
+ "16": "bulbul",
53
+ "17": "jay",
54
+ "18": "magpie",
55
+ "19": "chickadee",
56
+ "20": "water ouzel",
57
+ "21": "kite",
58
+ "22": "bald eagle",
59
+ "23": "vulture",
60
+ "24": "great grey owl",
61
+ "25": "European fire salamander",
62
+ "26": "common newt",
63
+ "27": "eft",
64
+ "28": "spotted salamander",
65
+ "29": "axolotl",
66
+ "30": "bullfrog",
67
+ "31": "tree frog",
68
+ "32": "tailed frog",
69
+ "33": "loggerhead",
70
+ "34": "leatherback turtle",
71
+ "35": "mud turtle",
72
+ "36": "terrapin",
73
+ "37": "box turtle",
74
+ "38": "banded gecko",
75
+ "39": "common iguana",
76
+ "40": "American chameleon",
77
+ "41": "whiptail",
78
+ "42": "agama",
79
+ "43": "frilled lizard",
80
+ "44": "alligator lizard",
81
+ "45": "Gila monster",
82
+ "46": "green lizard",
83
+ "47": "African chameleon",
84
+ "48": "Komodo dragon",
85
+ "49": "African crocodile",
86
+ "50": "American alligator",
87
+ "51": "triceratops",
88
+ "52": "thunder snake",
89
+ "53": "ringneck snake",
90
+ "54": "hognose snake",
91
+ "55": "green snake",
92
+ "56": "king snake",
93
+ "57": "garter snake",
94
+ "58": "water snake",
95
+ "59": "vine snake",
96
+ "60": "night snake",
97
+ "61": "boa constrictor",
98
+ "62": "rock python",
99
+ "63": "Indian cobra",
100
+ "64": "green mamba",
101
+ "65": "sea snake",
102
+ "66": "horned viper",
103
+ "67": "diamondback",
104
+ "68": "sidewinder",
105
+ "69": "trilobite",
106
+ "70": "harvestman",
107
+ "71": "scorpion",
108
+ "72": "black and gold garden spider",
109
+ "73": "barn spider",
110
+ "74": "garden spider",
111
+ "75": "black widow",
112
+ "76": "tarantula",
113
+ "77": "wolf spider",
114
+ "78": "tick",
115
+ "79": "centipede",
116
+ "80": "black grouse",
117
+ "81": "ptarmigan",
118
+ "82": "ruffed grouse",
119
+ "83": "prairie chicken",
120
+ "84": "peacock",
121
+ "85": "quail",
122
+ "86": "partridge",
123
+ "87": "African grey",
124
+ "88": "macaw",
125
+ "89": "sulphur-crested cockatoo",
126
+ "90": "lorikeet",
127
+ "91": "coucal",
128
+ "92": "bee eater",
129
+ "93": "hornbill",
130
+ "94": "hummingbird",
131
+ "95": "jacamar",
132
+ "96": "toucan",
133
+ "97": "drake",
134
+ "98": "red-breasted merganser",
135
+ "99": "goose",
136
+ "100": "black swan",
137
+ "101": "tusker",
138
+ "102": "echidna",
139
+ "103": "platypus",
140
+ "104": "wallaby",
141
+ "105": "koala",
142
+ "106": "wombat",
143
+ "107": "jellyfish",
144
+ "108": "sea anemone",
145
+ "109": "brain coral",
146
+ "110": "flatworm",
147
+ "111": "nematode",
148
+ "112": "conch",
149
+ "113": "snail",
150
+ "114": "slug",
151
+ "115": "sea slug",
152
+ "116": "chiton",
153
+ "117": "chambered nautilus",
154
+ "118": "Dungeness crab",
155
+ "119": "rock crab",
156
+ "120": "fiddler crab",
157
+ "121": "king crab",
158
+ "122": "American lobster",
159
+ "123": "spiny lobster",
160
+ "124": "crayfish",
161
+ "125": "hermit crab",
162
+ "126": "isopod",
163
+ "127": "white stork",
164
+ "128": "black stork",
165
+ "129": "spoonbill",
166
+ "130": "flamingo",
167
+ "131": "little blue heron",
168
+ "132": "American egret",
169
+ "133": "bittern",
170
+ "134": "crane bird",
171
+ "135": "limpkin",
172
+ "136": "European gallinule",
173
+ "137": "American coot",
174
+ "138": "bustard",
175
+ "139": "ruddy turnstone",
176
+ "140": "red-backed sandpiper",
177
+ "141": "redshank",
178
+ "142": "dowitcher",
179
+ "143": "oystercatcher",
180
+ "144": "pelican",
181
+ "145": "king penguin",
182
+ "146": "albatross",
183
+ "147": "grey whale",
184
+ "148": "killer whale",
185
+ "149": "dugong",
186
+ "150": "sea lion",
187
+ "151": "Chihuahua",
188
+ "152": "Japanese spaniel",
189
+ "153": "Maltese dog",
190
+ "154": "Pekinese",
191
+ "155": "Shih-Tzu",
192
+ "156": "Blenheim spaniel",
193
+ "157": "papillon",
194
+ "158": "toy terrier",
195
+ "159": "Rhodesian ridgeback",
196
+ "160": "Afghan hound",
197
+ "161": "basset",
198
+ "162": "beagle",
199
+ "163": "bloodhound",
200
+ "164": "bluetick",
201
+ "165": "black-and-tan coonhound",
202
+ "166": "Walker hound",
203
+ "167": "English foxhound",
204
+ "168": "redbone",
205
+ "169": "borzoi",
206
+ "170": "Irish wolfhound",
207
+ "171": "Italian greyhound",
208
+ "172": "whippet",
209
+ "173": "Ibizan hound",
210
+ "174": "Norwegian elkhound",
211
+ "175": "otterhound",
212
+ "176": "Saluki",
213
+ "177": "Scottish deerhound",
214
+ "178": "Weimaraner",
215
+ "179": "Staffordshire bullterrier",
216
+ "180": "American Staffordshire terrier",
217
+ "181": "Bedlington terrier",
218
+ "182": "Border terrier",
219
+ "183": "Kerry blue terrier",
220
+ "184": "Irish terrier",
221
+ "185": "Norfolk terrier",
222
+ "186": "Norwich terrier",
223
+ "187": "Yorkshire terrier",
224
+ "188": "wire-haired fox terrier",
225
+ "189": "Lakeland terrier",
226
+ "190": "Sealyham terrier",
227
+ "191": "Airedale",
228
+ "192": "cairn",
229
+ "193": "Australian terrier",
230
+ "194": "Dandie Dinmont",
231
+ "195": "Boston bull",
232
+ "196": "miniature schnauzer",
233
+ "197": "giant schnauzer",
234
+ "198": "standard schnauzer",
235
+ "199": "Scotch terrier",
236
+ "200": "Tibetan terrier",
237
+ "201": "silky terrier",
238
+ "202": "soft-coated wheaten terrier",
239
+ "203": "West Highland white terrier",
240
+ "204": "Lhasa",
241
+ "205": "flat-coated retriever",
242
+ "206": "curly-coated retriever",
243
+ "207": "golden retriever",
244
+ "208": "Labrador retriever",
245
+ "209": "Chesapeake Bay retriever",
246
+ "210": "German short-haired pointer",
247
+ "211": "vizsla",
248
+ "212": "English setter",
249
+ "213": "Irish setter",
250
+ "214": "Gordon setter",
251
+ "215": "Brittany spaniel",
252
+ "216": "clumber",
253
+ "217": "English springer",
254
+ "218": "Welsh springer spaniel",
255
+ "219": "cocker spaniel",
256
+ "220": "Sussex spaniel",
257
+ "221": "Irish water spaniel",
258
+ "222": "kuvasz",
259
+ "223": "schipperke",
260
+ "224": "groenendael",
261
+ "225": "malinois",
262
+ "226": "briard",
263
+ "227": "kelpie",
264
+ "228": "komondor",
265
+ "229": "Old English sheepdog",
266
+ "230": "Shetland sheepdog",
267
+ "231": "collie",
268
+ "232": "Border collie",
269
+ "233": "Bouvier des Flandres",
270
+ "234": "Rottweiler",
271
+ "235": "German shepherd",
272
+ "236": "Doberman",
273
+ "237": "miniature pinscher",
274
+ "238": "Greater Swiss Mountain dog",
275
+ "239": "Bernese mountain dog",
276
+ "240": "Appenzeller",
277
+ "241": "EntleBucher",
278
+ "242": "boxer",
279
+ "243": "bull mastiff",
280
+ "244": "Tibetan mastiff",
281
+ "245": "French bulldog",
282
+ "246": "Great Dane",
283
+ "247": "Saint Bernard",
284
+ "248": "Eskimo dog",
285
+ "249": "malamute",
286
+ "250": "Siberian husky",
287
+ "251": "dalmatian",
288
+ "252": "affenpinscher",
289
+ "253": "basenji",
290
+ "254": "pug",
291
+ "255": "Leonberg",
292
+ "256": "Newfoundland",
293
+ "257": "Great Pyrenees",
294
+ "258": "Samoyed",
295
+ "259": "Pomeranian",
296
+ "260": "chow",
297
+ "261": "keeshond",
298
+ "262": "Brabancon griffon",
299
+ "263": "Pembroke",
300
+ "264": "Cardigan",
301
+ "265": "toy poodle",
302
+ "266": "miniature poodle",
303
+ "267": "standard poodle",
304
+ "268": "Mexican hairless",
305
+ "269": "timber wolf",
306
+ "270": "white wolf",
307
+ "271": "red wolf",
308
+ "272": "coyote",
309
+ "273": "dingo",
310
+ "274": "dhole",
311
+ "275": "African hunting dog",
312
+ "276": "hyena",
313
+ "277": "red fox",
314
+ "278": "kit fox",
315
+ "279": "Arctic fox",
316
+ "280": "grey fox",
317
+ "281": "tabby",
318
+ "282": "tiger cat",
319
+ "283": "Persian cat",
320
+ "284": "Siamese cat",
321
+ "285": "Egyptian cat",
322
+ "286": "cougar",
323
+ "287": "lynx",
324
+ "288": "leopard",
325
+ "289": "snow leopard",
326
+ "290": "jaguar",
327
+ "291": "lion",
328
+ "292": "tiger",
329
+ "293": "cheetah",
330
+ "294": "brown bear",
331
+ "295": "American black bear",
332
+ "296": "ice bear",
333
+ "297": "sloth bear",
334
+ "298": "mongoose",
335
+ "299": "meerkat",
336
+ "300": "tiger beetle",
337
+ "301": "ladybug",
338
+ "302": "ground beetle",
339
+ "303": "long-horned beetle",
340
+ "304": "leaf beetle",
341
+ "305": "dung beetle",
342
+ "306": "rhinoceros beetle",
343
+ "307": "weevil",
344
+ "308": "fly",
345
+ "309": "bee",
346
+ "310": "ant",
347
+ "311": "grasshopper",
348
+ "312": "cricket",
349
+ "313": "walking stick",
350
+ "314": "cockroach",
351
+ "315": "mantis",
352
+ "316": "cicada",
353
+ "317": "leafhopper",
354
+ "318": "lacewing",
355
+ "319": "dragonfly",
356
+ "320": "damselfly",
357
+ "321": "admiral",
358
+ "322": "ringlet",
359
+ "323": "monarch",
360
+ "324": "cabbage butterfly",
361
+ "325": "sulphur butterfly",
362
+ "326": "lycaenid",
363
+ "327": "starfish",
364
+ "328": "sea urchin",
365
+ "329": "sea cucumber",
366
+ "330": "wood rabbit",
367
+ "331": "hare",
368
+ "332": "Angora",
369
+ "333": "hamster",
370
+ "334": "porcupine",
371
+ "335": "fox squirrel",
372
+ "336": "marmot",
373
+ "337": "beaver",
374
+ "338": "guinea pig",
375
+ "339": "sorrel",
376
+ "340": "zebra",
377
+ "341": "hog",
378
+ "342": "wild boar",
379
+ "343": "warthog",
380
+ "344": "hippopotamus",
381
+ "345": "ox",
382
+ "346": "water buffalo",
383
+ "347": "bison",
384
+ "348": "ram",
385
+ "349": "bighorn",
386
+ "350": "ibex",
387
+ "351": "hartebeest",
388
+ "352": "impala",
389
+ "353": "gazelle",
390
+ "354": "Arabian camel",
391
+ "355": "llama",
392
+ "356": "weasel",
393
+ "357": "mink",
394
+ "358": "polecat",
395
+ "359": "black-footed ferret",
396
+ "360": "otter",
397
+ "361": "skunk",
398
+ "362": "badger",
399
+ "363": "armadillo",
400
+ "364": "three-toed sloth",
401
+ "365": "orangutan",
402
+ "366": "gorilla",
403
+ "367": "chimpanzee",
404
+ "368": "gibbon",
405
+ "369": "siamang",
406
+ "370": "guenon",
407
+ "371": "patas",
408
+ "372": "baboon",
409
+ "373": "macaque",
410
+ "374": "langur",
411
+ "375": "colobus",
412
+ "376": "proboscis monkey",
413
+ "377": "marmoset",
414
+ "378": "capuchin",
415
+ "379": "howler monkey",
416
+ "380": "titi",
417
+ "381": "spider monkey",
418
+ "382": "squirrel monkey",
419
+ "383": "Madagascar cat",
420
+ "384": "indri",
421
+ "385": "Indian elephant",
422
+ "386": "African elephant",
423
+ "387": "lesser panda",
424
+ "388": "giant panda",
425
+ "389": "barracouta",
426
+ "390": "eel",
427
+ "391": "coho",
428
+ "392": "rock beauty",
429
+ "393": "anemone fish",
430
+ "394": "sturgeon",
431
+ "395": "gar",
432
+ "396": "lionfish",
433
+ "397": "puffer",
434
+ "398": "abacus",
435
+ "399": "abaya",
436
+ "400": "academic gown",
437
+ "401": "accordion",
438
+ "402": "acoustic guitar",
439
+ "403": "aircraft carrier",
440
+ "404": "airliner",
441
+ "405": "airship",
442
+ "406": "altar",
443
+ "407": "ambulance",
444
+ "408": "amphibian",
445
+ "409": "analog clock",
446
+ "410": "apiary",
447
+ "411": "apron",
448
+ "412": "ashcan",
449
+ "413": "assault rifle",
450
+ "414": "backpack",
451
+ "415": "bakery",
452
+ "416": "balance beam",
453
+ "417": "balloon",
454
+ "418": "ballpoint",
455
+ "419": "Band Aid",
456
+ "420": "banjo",
457
+ "421": "bannister",
458
+ "422": "barbell",
459
+ "423": "barber chair",
460
+ "424": "barbershop",
461
+ "425": "barn",
462
+ "426": "barometer",
463
+ "427": "barrel",
464
+ "428": "barrow",
465
+ "429": "baseball",
466
+ "430": "basketball",
467
+ "431": "bassinet",
468
+ "432": "bassoon",
469
+ "433": "bathing cap",
470
+ "434": "bath towel",
471
+ "435": "bathtub",
472
+ "436": "beach wagon",
473
+ "437": "beacon",
474
+ "438": "beaker",
475
+ "439": "bearskin",
476
+ "440": "beer bottle",
477
+ "441": "beer glass",
478
+ "442": "bell cote",
479
+ "443": "bib",
480
+ "444": "bicycle-built-for-two",
481
+ "445": "bikini",
482
+ "446": "binder",
483
+ "447": "binoculars",
484
+ "448": "birdhouse",
485
+ "449": "boathouse",
486
+ "450": "bobsled",
487
+ "451": "bolo tie",
488
+ "452": "bonnet",
489
+ "453": "bookcase",
490
+ "454": "bookshop",
491
+ "455": "bottlecap",
492
+ "456": "bow",
493
+ "457": "bow tie",
494
+ "458": "brass",
495
+ "459": "brassiere",
496
+ "460": "breakwater",
497
+ "461": "breastplate",
498
+ "462": "broom",
499
+ "463": "bucket",
500
+ "464": "buckle",
501
+ "465": "bulletproof vest",
502
+ "466": "bullet train",
503
+ "467": "butcher shop",
504
+ "468": "cab",
505
+ "469": "caldron",
506
+ "470": "candle",
507
+ "471": "cannon",
508
+ "472": "canoe",
509
+ "473": "can opener",
510
+ "474": "cardigan",
511
+ "475": "car mirror",
512
+ "476": "carousel",
513
+ "477": "carpenter's kit",
514
+ "478": "carton",
515
+ "479": "car wheel",
516
+ "480": "cash machine",
517
+ "481": "cassette",
518
+ "482": "cassette player",
519
+ "483": "castle",
520
+ "484": "catamaran",
521
+ "485": "CD player",
522
+ "486": "cello",
523
+ "487": "cellular telephone",
524
+ "488": "chain",
525
+ "489": "chainlink fence",
526
+ "490": "chain mail",
527
+ "491": "chain saw",
528
+ "492": "chest",
529
+ "493": "chiffonier",
530
+ "494": "chime",
531
+ "495": "china cabinet",
532
+ "496": "Christmas stocking",
533
+ "497": "church",
534
+ "498": "cinema",
535
+ "499": "cleaver",
536
+ "500": "cliff dwelling",
537
+ "501": "cloak",
538
+ "502": "clog",
539
+ "503": "cocktail shaker",
540
+ "504": "coffee mug",
541
+ "505": "coffeepot",
542
+ "506": "coil",
543
+ "507": "combination lock",
544
+ "508": "computer keyboard",
545
+ "509": "confectionery",
546
+ "510": "container ship",
547
+ "511": "convertible",
548
+ "512": "corkscrew",
549
+ "513": "cornet",
550
+ "514": "cowboy boot",
551
+ "515": "cowboy hat",
552
+ "516": "cradle",
553
+ "517": "crane",
554
+ "518": "crash helmet",
555
+ "519": "crate",
556
+ "520": "crib",
557
+ "521": "Crock Pot",
558
+ "522": "croquet ball",
559
+ "523": "crutch",
560
+ "524": "cuirass",
561
+ "525": "dam",
562
+ "526": "desk",
563
+ "527": "desktop computer",
564
+ "528": "dial telephone",
565
+ "529": "diaper",
566
+ "530": "digital clock",
567
+ "531": "digital watch",
568
+ "532": "dining table",
569
+ "533": "dishrag",
570
+ "534": "dishwasher",
571
+ "535": "disk brake",
572
+ "536": "dock",
573
+ "537": "dogsled",
574
+ "538": "dome",
575
+ "539": "doormat",
576
+ "540": "drilling platform",
577
+ "541": "drum",
578
+ "542": "drumstick",
579
+ "543": "dumbbell",
580
+ "544": "Dutch oven",
581
+ "545": "electric fan",
582
+ "546": "electric guitar",
583
+ "547": "electric locomotive",
584
+ "548": "entertainment center",
585
+ "549": "envelope",
586
+ "550": "espresso maker",
587
+ "551": "face powder",
588
+ "552": "feather boa",
589
+ "553": "file",
590
+ "554": "fireboat",
591
+ "555": "fire engine",
592
+ "556": "fire screen",
593
+ "557": "flagpole",
594
+ "558": "flute",
595
+ "559": "folding chair",
596
+ "560": "football helmet",
597
+ "561": "forklift",
598
+ "562": "fountain",
599
+ "563": "fountain pen",
600
+ "564": "four-poster",
601
+ "565": "freight car",
602
+ "566": "French horn",
603
+ "567": "frying pan",
604
+ "568": "fur coat",
605
+ "569": "garbage truck",
606
+ "570": "gasmask",
607
+ "571": "gas pump",
608
+ "572": "goblet",
609
+ "573": "go-kart",
610
+ "574": "golf ball",
611
+ "575": "golfcart",
612
+ "576": "gondola",
613
+ "577": "gong",
614
+ "578": "gown",
615
+ "579": "grand piano",
616
+ "580": "greenhouse",
617
+ "581": "grille",
618
+ "582": "grocery store",
619
+ "583": "guillotine",
620
+ "584": "hair slide",
621
+ "585": "hair spray",
622
+ "586": "half track",
623
+ "587": "hammer",
624
+ "588": "hamper",
625
+ "589": "hand blower",
626
+ "590": "hand-held computer",
627
+ "591": "handkerchief",
628
+ "592": "hard disc",
629
+ "593": "harmonica",
630
+ "594": "harp",
631
+ "595": "harvester",
632
+ "596": "hatchet",
633
+ "597": "holster",
634
+ "598": "home theater",
635
+ "599": "honeycomb",
636
+ "600": "hook",
637
+ "601": "hoopskirt",
638
+ "602": "horizontal bar",
639
+ "603": "horse cart",
640
+ "604": "hourglass",
641
+ "605": "iPod",
642
+ "606": "iron",
643
+ "607": "jack-o'-lantern",
644
+ "608": "jean",
645
+ "609": "jeep",
646
+ "610": "jersey",
647
+ "611": "jigsaw puzzle",
648
+ "612": "jinrikisha",
649
+ "613": "joystick",
650
+ "614": "kimono",
651
+ "615": "knee pad",
652
+ "616": "knot",
653
+ "617": "lab coat",
654
+ "618": "ladle",
655
+ "619": "lampshade",
656
+ "620": "laptop",
657
+ "621": "lawn mower",
658
+ "622": "lens cap",
659
+ "623": "letter opener",
660
+ "624": "library",
661
+ "625": "lifeboat",
662
+ "626": "lighter",
663
+ "627": "limousine",
664
+ "628": "liner",
665
+ "629": "lipstick",
666
+ "630": "Loafer",
667
+ "631": "lotion",
668
+ "632": "loudspeaker",
669
+ "633": "loupe",
670
+ "634": "lumbermill",
671
+ "635": "magnetic compass",
672
+ "636": "mailbag",
673
+ "637": "mailbox",
674
+ "638": "maillot",
675
+ "639": "maillot tank suit",
676
+ "640": "manhole cover",
677
+ "641": "maraca",
678
+ "642": "marimba",
679
+ "643": "mask",
680
+ "644": "matchstick",
681
+ "645": "maypole",
682
+ "646": "maze",
683
+ "647": "measuring cup",
684
+ "648": "medicine chest",
685
+ "649": "megalith",
686
+ "650": "microphone",
687
+ "651": "microwave",
688
+ "652": "military uniform",
689
+ "653": "milk can",
690
+ "654": "minibus",
691
+ "655": "miniskirt",
692
+ "656": "minivan",
693
+ "657": "missile",
694
+ "658": "mitten",
695
+ "659": "mixing bowl",
696
+ "660": "mobile home",
697
+ "661": "Model T",
698
+ "662": "modem",
699
+ "663": "monastery",
700
+ "664": "monitor",
701
+ "665": "moped",
702
+ "666": "mortar",
703
+ "667": "mortarboard",
704
+ "668": "mosque",
705
+ "669": "mosquito net",
706
+ "670": "motor scooter",
707
+ "671": "mountain bike",
708
+ "672": "mountain tent",
709
+ "673": "mouse",
710
+ "674": "mousetrap",
711
+ "675": "moving van",
712
+ "676": "muzzle",
713
+ "677": "nail",
714
+ "678": "neck brace",
715
+ "679": "necklace",
716
+ "680": "nipple",
717
+ "681": "notebook",
718
+ "682": "obelisk",
719
+ "683": "oboe",
720
+ "684": "ocarina",
721
+ "685": "odometer",
722
+ "686": "oil filter",
723
+ "687": "organ",
724
+ "688": "oscilloscope",
725
+ "689": "overskirt",
726
+ "690": "oxcart",
727
+ "691": "oxygen mask",
728
+ "692": "packet",
729
+ "693": "paddle",
730
+ "694": "paddlewheel",
731
+ "695": "padlock",
732
+ "696": "paintbrush",
733
+ "697": "pajama",
734
+ "698": "palace",
735
+ "699": "panpipe",
736
+ "700": "paper towel",
737
+ "701": "parachute",
738
+ "702": "parallel bars",
739
+ "703": "park bench",
740
+ "704": "parking meter",
741
+ "705": "passenger car",
742
+ "706": "patio",
743
+ "707": "pay-phone",
744
+ "708": "pedestal",
745
+ "709": "pencil box",
746
+ "710": "pencil sharpener",
747
+ "711": "perfume",
748
+ "712": "Petri dish",
749
+ "713": "photocopier",
750
+ "714": "pick",
751
+ "715": "pickelhaube",
752
+ "716": "picket fence",
753
+ "717": "pickup",
754
+ "718": "pier",
755
+ "719": "piggy bank",
756
+ "720": "pill bottle",
757
+ "721": "pillow",
758
+ "722": "ping-pong ball",
759
+ "723": "pinwheel",
760
+ "724": "pirate",
761
+ "725": "pitcher",
762
+ "726": "plane",
763
+ "727": "planetarium",
764
+ "728": "plastic bag",
765
+ "729": "plate rack",
766
+ "730": "plow",
767
+ "731": "plunger",
768
+ "732": "Polaroid camera",
769
+ "733": "pole",
770
+ "734": "police van",
771
+ "735": "poncho",
772
+ "736": "pool table",
773
+ "737": "pop bottle",
774
+ "738": "pot",
775
+ "739": "potter's wheel",
776
+ "740": "power drill",
777
+ "741": "prayer rug",
778
+ "742": "printer",
779
+ "743": "prison",
780
+ "744": "projectile",
781
+ "745": "projector",
782
+ "746": "puck",
783
+ "747": "punching bag",
784
+ "748": "purse",
785
+ "749": "quill",
786
+ "750": "quilt",
787
+ "751": "racer",
788
+ "752": "racket",
789
+ "753": "radiator",
790
+ "754": "radio",
791
+ "755": "radio telescope",
792
+ "756": "rain barrel",
793
+ "757": "recreational vehicle",
794
+ "758": "reel",
795
+ "759": "reflex camera",
796
+ "760": "refrigerator",
797
+ "761": "remote control",
798
+ "762": "restaurant",
799
+ "763": "revolver",
800
+ "764": "rifle",
801
+ "765": "rocking chair",
802
+ "766": "rotisserie",
803
+ "767": "rubber eraser",
804
+ "768": "rugby ball",
805
+ "769": "rule",
806
+ "770": "running shoe",
807
+ "771": "safe",
808
+ "772": "safety pin",
809
+ "773": "saltshaker",
810
+ "774": "sandal",
811
+ "775": "sarong",
812
+ "776": "sax",
813
+ "777": "scabbard",
814
+ "778": "scale",
815
+ "779": "school bus",
816
+ "780": "schooner",
817
+ "781": "scoreboard",
818
+ "782": "screen",
819
+ "783": "screw",
820
+ "784": "screwdriver",
821
+ "785": "seat belt",
822
+ "786": "sewing machine",
823
+ "787": "shield",
824
+ "788": "shoe shop",
825
+ "789": "shoji",
826
+ "790": "shopping basket",
827
+ "791": "shopping cart",
828
+ "792": "shovel",
829
+ "793": "shower cap",
830
+ "794": "shower curtain",
831
+ "795": "ski",
832
+ "796": "ski mask",
833
+ "797": "sleeping bag",
834
+ "798": "slide rule",
835
+ "799": "sliding door",
836
+ "800": "slot",
837
+ "801": "snorkel",
838
+ "802": "snowmobile",
839
+ "803": "snowplow",
840
+ "804": "soap dispenser",
841
+ "805": "soccer ball",
842
+ "806": "sock",
843
+ "807": "solar dish",
844
+ "808": "sombrero",
845
+ "809": "soup bowl",
846
+ "810": "space bar",
847
+ "811": "space heater",
848
+ "812": "space shuttle",
849
+ "813": "spatula",
850
+ "814": "speedboat",
851
+ "815": "spider web",
852
+ "816": "spindle",
853
+ "817": "sports car",
854
+ "818": "spotlight",
855
+ "819": "stage",
856
+ "820": "steam locomotive",
857
+ "821": "steel arch bridge",
858
+ "822": "steel drum",
859
+ "823": "stethoscope",
860
+ "824": "stole",
861
+ "825": "stone wall",
862
+ "826": "stopwatch",
863
+ "827": "stove",
864
+ "828": "strainer",
865
+ "829": "streetcar",
866
+ "830": "stretcher",
867
+ "831": "studio couch",
868
+ "832": "stupa",
869
+ "833": "submarine",
870
+ "834": "suit",
871
+ "835": "sundial",
872
+ "836": "sunglass",
873
+ "837": "sunglasses",
874
+ "838": "sunscreen",
875
+ "839": "suspension bridge",
876
+ "840": "swab",
877
+ "841": "sweatshirt",
878
+ "842": "swimming trunks",
879
+ "843": "swing",
880
+ "844": "switch",
881
+ "845": "syringe",
882
+ "846": "table lamp",
883
+ "847": "tank",
884
+ "848": "tape player",
885
+ "849": "teapot",
886
+ "850": "teddy",
887
+ "851": "television",
888
+ "852": "tennis ball",
889
+ "853": "thatch",
890
+ "854": "theater curtain",
891
+ "855": "thimble",
892
+ "856": "thresher",
893
+ "857": "throne",
894
+ "858": "tile roof",
895
+ "859": "toaster",
896
+ "860": "tobacco shop",
897
+ "861": "toilet seat",
898
+ "862": "torch",
899
+ "863": "totem pole",
900
+ "864": "tow truck",
901
+ "865": "toyshop",
902
+ "866": "tractor",
903
+ "867": "trailer truck",
904
+ "868": "tray",
905
+ "869": "trench coat",
906
+ "870": "tricycle",
907
+ "871": "trimaran",
908
+ "872": "tripod",
909
+ "873": "triumphal arch",
910
+ "874": "trolleybus",
911
+ "875": "trombone",
912
+ "876": "tub",
913
+ "877": "turnstile",
914
+ "878": "typewriter keyboard",
915
+ "879": "umbrella",
916
+ "880": "unicycle",
917
+ "881": "upright",
918
+ "882": "vacuum",
919
+ "883": "vase",
920
+ "884": "vault",
921
+ "885": "velvet",
922
+ "886": "vending machine",
923
+ "887": "vestment",
924
+ "888": "viaduct",
925
+ "889": "violin",
926
+ "890": "volleyball",
927
+ "891": "waffle iron",
928
+ "892": "wall clock",
929
+ "893": "wallet",
930
+ "894": "wardrobe",
931
+ "895": "warplane",
932
+ "896": "washbasin",
933
+ "897": "washer",
934
+ "898": "water bottle",
935
+ "899": "water jug",
936
+ "900": "water tower",
937
+ "901": "whiskey jug",
938
+ "902": "whistle",
939
+ "903": "wig",
940
+ "904": "window screen",
941
+ "905": "window shade",
942
+ "906": "Windsor tie",
943
+ "907": "wine bottle",
944
+ "908": "wing",
945
+ "909": "wok",
946
+ "910": "wooden spoon",
947
+ "911": "wool",
948
+ "912": "worm fence",
949
+ "913": "wreck",
950
+ "914": "yawl",
951
+ "915": "yurt",
952
+ "916": "web site",
953
+ "917": "comic book",
954
+ "918": "crossword puzzle",
955
+ "919": "street sign",
956
+ "920": "traffic light",
957
+ "921": "book jacket",
958
+ "922": "menu",
959
+ "923": "plate",
960
+ "924": "guacamole",
961
+ "925": "consomme",
962
+ "926": "hot pot",
963
+ "927": "trifle",
964
+ "928": "ice cream",
965
+ "929": "ice lolly",
966
+ "930": "French loaf",
967
+ "931": "bagel",
968
+ "932": "pretzel",
969
+ "933": "cheeseburger",
970
+ "934": "hotdog",
971
+ "935": "mashed potato",
972
+ "936": "head cabbage",
973
+ "937": "broccoli",
974
+ "938": "cauliflower",
975
+ "939": "zucchini",
976
+ "940": "spaghetti squash",
977
+ "941": "acorn squash",
978
+ "942": "butternut squash",
979
+ "943": "cucumber",
980
+ "944": "artichoke",
981
+ "945": "bell pepper",
982
+ "946": "cardoon",
983
+ "947": "mushroom",
984
+ "948": "Granny Smith",
985
+ "949": "strawberry",
986
+ "950": "orange",
987
+ "951": "lemon",
988
+ "952": "fig",
989
+ "953": "pineapple",
990
+ "954": "banana",
991
+ "955": "jackfruit",
992
+ "956": "custard apple",
993
+ "957": "pomegranate",
994
+ "958": "hay",
995
+ "959": "carbonara",
996
+ "960": "chocolate sauce",
997
+ "961": "dough",
998
+ "962": "meat loaf",
999
+ "963": "pizza",
1000
+ "964": "potpie",
1001
+ "965": "burrito",
1002
+ "966": "red wine",
1003
+ "967": "espresso",
1004
+ "968": "cup",
1005
+ "969": "eggnog",
1006
+ "970": "alp",
1007
+ "971": "bubble",
1008
+ "972": "cliff",
1009
+ "973": "coral reef",
1010
+ "974": "geyser",
1011
+ "975": "lakeside",
1012
+ "976": "promontory",
1013
+ "977": "sandbar",
1014
+ "978": "seashore",
1015
+ "979": "valley",
1016
+ "980": "volcano",
1017
+ "981": "ballplayer",
1018
+ "982": "groom",
1019
+ "983": "scuba diver",
1020
+ "984": "rapeseed",
1021
+ "985": "daisy",
1022
+ "986": "yellow lady's slipper",
1023
+ "987": "corn",
1024
+ "988": "acorn",
1025
+ "989": "hip",
1026
+ "990": "buckeye",
1027
+ "991": "coral fungus",
1028
+ "992": "agaric",
1029
+ "993": "gyromitra",
1030
+ "994": "stinkhorn",
1031
+ "995": "earthstar",
1032
+ "996": "hen-of-the-woods",
1033
+ "997": "bolete",
1034
+ "998": "ear",
1035
+ "999": "toilet tissue"
1036
+ },
1037
+ "label2id": {
1038
+ "tench": 0,
1039
+ "goldfish": 1,
1040
+ "great white shark": 2,
1041
+ "tiger shark": 3,
1042
+ "hammerhead": 4,
1043
+ "electric ray": 5,
1044
+ "stingray": 6,
1045
+ "cock": 7,
1046
+ "hen": 8,
1047
+ "ostrich": 9,
1048
+ "brambling": 10,
1049
+ "goldfinch": 11,
1050
+ "house finch": 12,
1051
+ "junco": 13,
1052
+ "indigo bunting": 14,
1053
+ "robin": 15,
1054
+ "bulbul": 16,
1055
+ "jay": 17,
1056
+ "magpie": 18,
1057
+ "chickadee": 19,
1058
+ "water ouzel": 20,
1059
+ "kite": 21,
1060
+ "bald eagle": 22,
1061
+ "vulture": 23,
1062
+ "great grey owl": 24,
1063
+ "European fire salamander": 25,
1064
+ "common newt": 26,
1065
+ "eft": 27,
1066
+ "spotted salamander": 28,
1067
+ "axolotl": 29,
1068
+ "bullfrog": 30,
1069
+ "tree frog": 31,
1070
+ "tailed frog": 32,
1071
+ "loggerhead": 33,
1072
+ "leatherback turtle": 34,
1073
+ "mud turtle": 35,
1074
+ "terrapin": 36,
1075
+ "box turtle": 37,
1076
+ "banded gecko": 38,
1077
+ "common iguana": 39,
1078
+ "American chameleon": 40,
1079
+ "whiptail": 41,
1080
+ "agama": 42,
1081
+ "frilled lizard": 43,
1082
+ "alligator lizard": 44,
1083
+ "Gila monster": 45,
1084
+ "green lizard": 46,
1085
+ "African chameleon": 47,
1086
+ "Komodo dragon": 48,
1087
+ "African crocodile": 49,
1088
+ "American alligator": 50,
1089
+ "triceratops": 51,
1090
+ "thunder snake": 52,
1091
+ "ringneck snake": 53,
1092
+ "hognose snake": 54,
1093
+ "green snake": 55,
1094
+ "king snake": 56,
1095
+ "garter snake": 57,
1096
+ "water snake": 58,
1097
+ "vine snake": 59,
1098
+ "night snake": 60,
1099
+ "boa constrictor": 61,
1100
+ "rock python": 62,
1101
+ "Indian cobra": 63,
1102
+ "green mamba": 64,
1103
+ "sea snake": 65,
1104
+ "horned viper": 66,
1105
+ "diamondback": 67,
1106
+ "sidewinder": 68,
1107
+ "trilobite": 69,
1108
+ "harvestman": 70,
1109
+ "scorpion": 71,
1110
+ "black and gold garden spider": 72,
1111
+ "barn spider": 73,
1112
+ "garden spider": 74,
1113
+ "black widow": 75,
1114
+ "tarantula": 76,
1115
+ "wolf spider": 77,
1116
+ "tick": 78,
1117
+ "centipede": 79,
1118
+ "black grouse": 80,
1119
+ "ptarmigan": 81,
1120
+ "ruffed grouse": 82,
1121
+ "prairie chicken": 83,
1122
+ "peacock": 84,
1123
+ "quail": 85,
1124
+ "partridge": 86,
1125
+ "African grey": 87,
1126
+ "macaw": 88,
1127
+ "sulphur-crested cockatoo": 89,
1128
+ "lorikeet": 90,
1129
+ "coucal": 91,
1130
+ "bee eater": 92,
1131
+ "hornbill": 93,
1132
+ "hummingbird": 94,
1133
+ "jacamar": 95,
1134
+ "toucan": 96,
1135
+ "drake": 97,
1136
+ "red-breasted merganser": 98,
1137
+ "goose": 99,
1138
+ "black swan": 100,
1139
+ "tusker": 101,
1140
+ "echidna": 102,
1141
+ "platypus": 103,
1142
+ "wallaby": 104,
1143
+ "koala": 105,
1144
+ "wombat": 106,
1145
+ "jellyfish": 107,
1146
+ "sea anemone": 108,
1147
+ "brain coral": 109,
1148
+ "flatworm": 110,
1149
+ "nematode": 111,
1150
+ "conch": 112,
1151
+ "snail": 113,
1152
+ "slug": 114,
1153
+ "sea slug": 115,
1154
+ "chiton": 116,
1155
+ "chambered nautilus": 117,
1156
+ "Dungeness crab": 118,
1157
+ "rock crab": 119,
1158
+ "fiddler crab": 120,
1159
+ "king crab": 121,
1160
+ "American lobster": 122,
1161
+ "spiny lobster": 123,
1162
+ "crayfish": 124,
1163
+ "hermit crab": 125,
1164
+ "isopod": 126,
1165
+ "white stork": 127,
1166
+ "black stork": 128,
1167
+ "spoonbill": 129,
1168
+ "flamingo": 130,
1169
+ "little blue heron": 131,
1170
+ "American egret": 132,
1171
+ "bittern": 133,
1172
+ "crane bird": 134,
1173
+ "limpkin": 135,
1174
+ "European gallinule": 136,
1175
+ "American coot": 137,
1176
+ "bustard": 138,
1177
+ "ruddy turnstone": 139,
1178
+ "red-backed sandpiper": 140,
1179
+ "redshank": 141,
1180
+ "dowitcher": 142,
1181
+ "oystercatcher": 143,
1182
+ "pelican": 144,
1183
+ "king penguin": 145,
1184
+ "albatross": 146,
1185
+ "grey whale": 147,
1186
+ "killer whale": 148,
1187
+ "dugong": 149,
1188
+ "sea lion": 150,
1189
+ "Chihuahua": 151,
1190
+ "Japanese spaniel": 152,
1191
+ "Maltese dog": 153,
1192
+ "Pekinese": 154,
1193
+ "Shih-Tzu": 155,
1194
+ "Blenheim spaniel": 156,
1195
+ "papillon": 157,
1196
+ "toy terrier": 158,
1197
+ "Rhodesian ridgeback": 159,
1198
+ "Afghan hound": 160,
1199
+ "basset": 161,
1200
+ "beagle": 162,
1201
+ "bloodhound": 163,
1202
+ "bluetick": 164,
1203
+ "black-and-tan coonhound": 165,
1204
+ "Walker hound": 166,
1205
+ "English foxhound": 167,
1206
+ "redbone": 168,
1207
+ "borzoi": 169,
1208
+ "Irish wolfhound": 170,
1209
+ "Italian greyhound": 171,
1210
+ "whippet": 172,
1211
+ "Ibizan hound": 173,
1212
+ "Norwegian elkhound": 174,
1213
+ "otterhound": 175,
1214
+ "Saluki": 176,
1215
+ "Scottish deerhound": 177,
1216
+ "Weimaraner": 178,
1217
+ "Staffordshire bullterrier": 179,
1218
+ "American Staffordshire terrier": 180,
1219
+ "Bedlington terrier": 181,
1220
+ "Border terrier": 182,
1221
+ "Kerry blue terrier": 183,
1222
+ "Irish terrier": 184,
1223
+ "Norfolk terrier": 185,
1224
+ "Norwich terrier": 186,
1225
+ "Yorkshire terrier": 187,
1226
+ "wire-haired fox terrier": 188,
1227
+ "Lakeland terrier": 189,
1228
+ "Sealyham terrier": 190,
1229
+ "Airedale": 191,
1230
+ "cairn": 192,
1231
+ "Australian terrier": 193,
1232
+ "Dandie Dinmont": 194,
1233
+ "Boston bull": 195,
1234
+ "miniature schnauzer": 196,
1235
+ "giant schnauzer": 197,
1236
+ "standard schnauzer": 198,
1237
+ "Scotch terrier": 199,
1238
+ "Tibetan terrier": 200,
1239
+ "silky terrier": 201,
1240
+ "soft-coated wheaten terrier": 202,
1241
+ "West Highland white terrier": 203,
1242
+ "Lhasa": 204,
1243
+ "flat-coated retriever": 205,
1244
+ "curly-coated retriever": 206,
1245
+ "golden retriever": 207,
1246
+ "Labrador retriever": 208,
1247
+ "Chesapeake Bay retriever": 209,
1248
+ "German short-haired pointer": 210,
1249
+ "vizsla": 211,
1250
+ "English setter": 212,
1251
+ "Irish setter": 213,
1252
+ "Gordon setter": 214,
1253
+ "Brittany spaniel": 215,
1254
+ "clumber": 216,
1255
+ "English springer": 217,
1256
+ "Welsh springer spaniel": 218,
1257
+ "cocker spaniel": 219,
1258
+ "Sussex spaniel": 220,
1259
+ "Irish water spaniel": 221,
1260
+ "kuvasz": 222,
1261
+ "schipperke": 223,
1262
+ "groenendael": 224,
1263
+ "malinois": 225,
1264
+ "briard": 226,
1265
+ "kelpie": 227,
1266
+ "komondor": 228,
1267
+ "Old English sheepdog": 229,
1268
+ "Shetland sheepdog": 230,
1269
+ "collie": 231,
1270
+ "Border collie": 232,
1271
+ "Bouvier des Flandres": 233,
1272
+ "Rottweiler": 234,
1273
+ "German shepherd": 235,
1274
+ "Doberman": 236,
1275
+ "miniature pinscher": 237,
1276
+ "Greater Swiss Mountain dog": 238,
1277
+ "Bernese mountain dog": 239,
1278
+ "Appenzeller": 240,
1279
+ "EntleBucher": 241,
1280
+ "boxer": 242,
1281
+ "bull mastiff": 243,
1282
+ "Tibetan mastiff": 244,
1283
+ "French bulldog": 245,
1284
+ "Great Dane": 246,
1285
+ "Saint Bernard": 247,
1286
+ "Eskimo dog": 248,
1287
+ "malamute": 249,
1288
+ "Siberian husky": 250,
1289
+ "dalmatian": 251,
1290
+ "affenpinscher": 252,
1291
+ "basenji": 253,
1292
+ "pug": 254,
1293
+ "Leonberg": 255,
1294
+ "Newfoundland": 256,
1295
+ "Great Pyrenees": 257,
1296
+ "Samoyed": 258,
1297
+ "Pomeranian": 259,
1298
+ "chow": 260,
1299
+ "keeshond": 261,
1300
+ "Brabancon griffon": 262,
1301
+ "Pembroke": 263,
1302
+ "Cardigan": 264,
1303
+ "toy poodle": 265,
1304
+ "miniature poodle": 266,
1305
+ "standard poodle": 267,
1306
+ "Mexican hairless": 268,
1307
+ "timber wolf": 269,
1308
+ "white wolf": 270,
1309
+ "red wolf": 271,
1310
+ "coyote": 272,
1311
+ "dingo": 273,
1312
+ "dhole": 274,
1313
+ "African hunting dog": 275,
1314
+ "hyena": 276,
1315
+ "red fox": 277,
1316
+ "kit fox": 278,
1317
+ "Arctic fox": 279,
1318
+ "grey fox": 280,
1319
+ "tabby": 281,
1320
+ "tiger cat": 282,
1321
+ "Persian cat": 283,
1322
+ "Siamese cat": 284,
1323
+ "Egyptian cat": 285,
1324
+ "cougar": 286,
1325
+ "lynx": 287,
1326
+ "leopard": 288,
1327
+ "snow leopard": 289,
1328
+ "jaguar": 290,
1329
+ "lion": 291,
1330
+ "tiger": 292,
1331
+ "cheetah": 293,
1332
+ "brown bear": 294,
1333
+ "American black bear": 295,
1334
+ "ice bear": 296,
1335
+ "sloth bear": 297,
1336
+ "mongoose": 298,
1337
+ "meerkat": 299,
1338
+ "tiger beetle": 300,
1339
+ "ladybug": 301,
1340
+ "ground beetle": 302,
1341
+ "long-horned beetle": 303,
1342
+ "leaf beetle": 304,
1343
+ "dung beetle": 305,
1344
+ "rhinoceros beetle": 306,
1345
+ "weevil": 307,
1346
+ "fly": 308,
1347
+ "bee": 309,
1348
+ "ant": 310,
1349
+ "grasshopper": 311,
1350
+ "cricket": 312,
1351
+ "walking stick": 313,
1352
+ "cockroach": 314,
1353
+ "mantis": 315,
1354
+ "cicada": 316,
1355
+ "leafhopper": 317,
1356
+ "lacewing": 318,
1357
+ "dragonfly": 319,
1358
+ "damselfly": 320,
1359
+ "admiral": 321,
1360
+ "ringlet": 322,
1361
+ "monarch": 323,
1362
+ "cabbage butterfly": 324,
1363
+ "sulphur butterfly": 325,
1364
+ "lycaenid": 326,
1365
+ "starfish": 327,
1366
+ "sea urchin": 328,
1367
+ "sea cucumber": 329,
1368
+ "wood rabbit": 330,
1369
+ "hare": 331,
1370
+ "Angora": 332,
1371
+ "hamster": 333,
1372
+ "porcupine": 334,
1373
+ "fox squirrel": 335,
1374
+ "marmot": 336,
1375
+ "beaver": 337,
1376
+ "guinea pig": 338,
1377
+ "sorrel": 339,
1378
+ "zebra": 340,
1379
+ "hog": 341,
1380
+ "wild boar": 342,
1381
+ "warthog": 343,
1382
+ "hippopotamus": 344,
1383
+ "ox": 345,
1384
+ "water buffalo": 346,
1385
+ "bison": 347,
1386
+ "ram": 348,
1387
+ "bighorn": 349,
1388
+ "ibex": 350,
1389
+ "hartebeest": 351,
1390
+ "impala": 352,
1391
+ "gazelle": 353,
1392
+ "Arabian camel": 354,
1393
+ "llama": 355,
1394
+ "weasel": 356,
1395
+ "mink": 357,
1396
+ "polecat": 358,
1397
+ "black-footed ferret": 359,
1398
+ "otter": 360,
1399
+ "skunk": 361,
1400
+ "badger": 362,
1401
+ "armadillo": 363,
1402
+ "three-toed sloth": 364,
1403
+ "orangutan": 365,
1404
+ "gorilla": 366,
1405
+ "chimpanzee": 367,
1406
+ "gibbon": 368,
1407
+ "siamang": 369,
1408
+ "guenon": 370,
1409
+ "patas": 371,
1410
+ "baboon": 372,
1411
+ "macaque": 373,
1412
+ "langur": 374,
1413
+ "colobus": 375,
1414
+ "proboscis monkey": 376,
1415
+ "marmoset": 377,
1416
+ "capuchin": 378,
1417
+ "howler monkey": 379,
1418
+ "titi": 380,
1419
+ "spider monkey": 381,
1420
+ "squirrel monkey": 382,
1421
+ "Madagascar cat": 383,
1422
+ "indri": 384,
1423
+ "Indian elephant": 385,
1424
+ "African elephant": 386,
1425
+ "lesser panda": 387,
1426
+ "giant panda": 388,
1427
+ "barracouta": 389,
1428
+ "eel": 390,
1429
+ "coho": 391,
1430
+ "rock beauty": 392,
1431
+ "anemone fish": 393,
1432
+ "sturgeon": 394,
1433
+ "gar": 395,
1434
+ "lionfish": 396,
1435
+ "puffer": 397,
1436
+ "abacus": 398,
1437
+ "abaya": 399,
1438
+ "academic gown": 400,
1439
+ "accordion": 401,
1440
+ "acoustic guitar": 402,
1441
+ "aircraft carrier": 403,
1442
+ "airliner": 404,
1443
+ "airship": 405,
1444
+ "altar": 406,
1445
+ "ambulance": 407,
1446
+ "amphibian": 408,
1447
+ "analog clock": 409,
1448
+ "apiary": 410,
1449
+ "apron": 411,
1450
+ "ashcan": 412,
1451
+ "assault rifle": 413,
1452
+ "backpack": 414,
1453
+ "bakery": 415,
1454
+ "balance beam": 416,
1455
+ "balloon": 417,
1456
+ "ballpoint": 418,
1457
+ "Band Aid": 419,
1458
+ "banjo": 420,
1459
+ "bannister": 421,
1460
+ "barbell": 422,
1461
+ "barber chair": 423,
1462
+ "barbershop": 424,
1463
+ "barn": 425,
1464
+ "barometer": 426,
1465
+ "barrel": 427,
1466
+ "barrow": 428,
1467
+ "baseball": 429,
1468
+ "basketball": 430,
1469
+ "bassinet": 431,
1470
+ "bassoon": 432,
1471
+ "bathing cap": 433,
1472
+ "bath towel": 434,
1473
+ "bathtub": 435,
1474
+ "beach wagon": 436,
1475
+ "beacon": 437,
1476
+ "beaker": 438,
1477
+ "bearskin": 439,
1478
+ "beer bottle": 440,
1479
+ "beer glass": 441,
1480
+ "bell cote": 442,
1481
+ "bib": 443,
1482
+ "bicycle-built-for-two": 444,
1483
+ "bikini": 445,
1484
+ "binder": 446,
1485
+ "binoculars": 447,
1486
+ "birdhouse": 448,
1487
+ "boathouse": 449,
1488
+ "bobsled": 450,
1489
+ "bolo tie": 451,
1490
+ "bonnet": 452,
1491
+ "bookcase": 453,
1492
+ "bookshop": 454,
1493
+ "bottlecap": 455,
1494
+ "bow": 456,
1495
+ "bow tie": 457,
1496
+ "brass": 458,
1497
+ "brassiere": 459,
1498
+ "breakwater": 460,
1499
+ "breastplate": 461,
1500
+ "broom": 462,
1501
+ "bucket": 463,
1502
+ "buckle": 464,
1503
+ "bulletproof vest": 465,
1504
+ "bullet train": 466,
1505
+ "butcher shop": 467,
1506
+ "cab": 468,
1507
+ "caldron": 469,
1508
+ "candle": 470,
1509
+ "cannon": 471,
1510
+ "canoe": 472,
1511
+ "can opener": 473,
1512
+ "cardigan": 474,
1513
+ "car mirror": 475,
1514
+ "carousel": 476,
1515
+ "carpenter's kit": 477,
1516
+ "carton": 478,
1517
+ "car wheel": 479,
1518
+ "cash machine": 480,
1519
+ "cassette": 481,
1520
+ "cassette player": 482,
1521
+ "castle": 483,
1522
+ "catamaran": 484,
1523
+ "CD player": 485,
1524
+ "cello": 486,
1525
+ "cellular telephone": 487,
1526
+ "chain": 488,
1527
+ "chainlink fence": 489,
1528
+ "chain mail": 490,
1529
+ "chain saw": 491,
1530
+ "chest": 492,
1531
+ "chiffonier": 493,
1532
+ "chime": 494,
1533
+ "china cabinet": 495,
1534
+ "Christmas stocking": 496,
1535
+ "church": 497,
1536
+ "cinema": 498,
1537
+ "cleaver": 499,
1538
+ "cliff dwelling": 500,
1539
+ "cloak": 501,
1540
+ "clog": 502,
1541
+ "cocktail shaker": 503,
1542
+ "coffee mug": 504,
1543
+ "coffeepot": 505,
1544
+ "coil": 506,
1545
+ "combination lock": 507,
1546
+ "computer keyboard": 508,
1547
+ "confectionery": 509,
1548
+ "container ship": 510,
1549
+ "convertible": 511,
1550
+ "corkscrew": 512,
1551
+ "cornet": 513,
1552
+ "cowboy boot": 514,
1553
+ "cowboy hat": 515,
1554
+ "cradle": 516,
1555
+ "crane": 517,
1556
+ "crash helmet": 518,
1557
+ "crate": 519,
1558
+ "crib": 520,
1559
+ "Crock Pot": 521,
1560
+ "croquet ball": 522,
1561
+ "crutch": 523,
1562
+ "cuirass": 524,
1563
+ "dam": 525,
1564
+ "desk": 526,
1565
+ "desktop computer": 527,
1566
+ "dial telephone": 528,
1567
+ "diaper": 529,
1568
+ "digital clock": 530,
1569
+ "digital watch": 531,
1570
+ "dining table": 532,
1571
+ "dishrag": 533,
1572
+ "dishwasher": 534,
1573
+ "disk brake": 535,
1574
+ "dock": 536,
1575
+ "dogsled": 537,
1576
+ "dome": 538,
1577
+ "doormat": 539,
1578
+ "drilling platform": 540,
1579
+ "drum": 541,
1580
+ "drumstick": 542,
1581
+ "dumbbell": 543,
1582
+ "Dutch oven": 544,
1583
+ "electric fan": 545,
1584
+ "electric guitar": 546,
1585
+ "electric locomotive": 547,
1586
+ "entertainment center": 548,
1587
+ "envelope": 549,
1588
+ "espresso maker": 550,
1589
+ "face powder": 551,
1590
+ "feather boa": 552,
1591
+ "file": 553,
1592
+ "fireboat": 554,
1593
+ "fire engine": 555,
1594
+ "fire screen": 556,
1595
+ "flagpole": 557,
1596
+ "flute": 558,
1597
+ "folding chair": 559,
1598
+ "football helmet": 560,
1599
+ "forklift": 561,
1600
+ "fountain": 562,
1601
+ "fountain pen": 563,
1602
+ "four-poster": 564,
1603
+ "freight car": 565,
1604
+ "French horn": 566,
1605
+ "frying pan": 567,
1606
+ "fur coat": 568,
1607
+ "garbage truck": 569,
1608
+ "gasmask": 570,
1609
+ "gas pump": 571,
1610
+ "goblet": 572,
1611
+ "go-kart": 573,
1612
+ "golf ball": 574,
1613
+ "golfcart": 575,
1614
+ "gondola": 576,
1615
+ "gong": 577,
1616
+ "gown": 578,
1617
+ "grand piano": 579,
1618
+ "greenhouse": 580,
1619
+ "grille": 581,
1620
+ "grocery store": 582,
1621
+ "guillotine": 583,
1622
+ "hair slide": 584,
1623
+ "hair spray": 585,
1624
+ "half track": 586,
1625
+ "hammer": 587,
1626
+ "hamper": 588,
1627
+ "hand blower": 589,
1628
+ "hand-held computer": 590,
1629
+ "handkerchief": 591,
1630
+ "hard disc": 592,
1631
+ "harmonica": 593,
1632
+ "harp": 594,
1633
+ "harvester": 595,
1634
+ "hatchet": 596,
1635
+ "holster": 597,
1636
+ "home theater": 598,
1637
+ "honeycomb": 599,
1638
+ "hook": 600,
1639
+ "hoopskirt": 601,
1640
+ "horizontal bar": 602,
1641
+ "horse cart": 603,
1642
+ "hourglass": 604,
1643
+ "iPod": 605,
1644
+ "iron": 606,
1645
+ "jack-o'-lantern": 607,
1646
+ "jean": 608,
1647
+ "jeep": 609,
1648
+ "jersey": 610,
1649
+ "jigsaw puzzle": 611,
1650
+ "jinrikisha": 612,
1651
+ "joystick": 613,
1652
+ "kimono": 614,
1653
+ "knee pad": 615,
1654
+ "knot": 616,
1655
+ "lab coat": 617,
1656
+ "ladle": 618,
1657
+ "lampshade": 619,
1658
+ "laptop": 620,
1659
+ "lawn mower": 621,
1660
+ "lens cap": 622,
1661
+ "letter opener": 623,
1662
+ "library": 624,
1663
+ "lifeboat": 625,
1664
+ "lighter": 626,
1665
+ "limousine": 627,
1666
+ "liner": 628,
1667
+ "lipstick": 629,
1668
+ "Loafer": 630,
1669
+ "lotion": 631,
1670
+ "loudspeaker": 632,
1671
+ "loupe": 633,
1672
+ "lumbermill": 634,
1673
+ "magnetic compass": 635,
1674
+ "mailbag": 636,
1675
+ "mailbox": 637,
1676
+ "maillot": 638,
1677
+ "maillot tank suit": 639,
1678
+ "manhole cover": 640,
1679
+ "maraca": 641,
1680
+ "marimba": 642,
1681
+ "mask": 643,
1682
+ "matchstick": 644,
1683
+ "maypole": 645,
1684
+ "maze": 646,
1685
+ "measuring cup": 647,
1686
+ "medicine chest": 648,
1687
+ "megalith": 649,
1688
+ "microphone": 650,
1689
+ "microwave": 651,
1690
+ "military uniform": 652,
1691
+ "milk can": 653,
1692
+ "minibus": 654,
1693
+ "miniskirt": 655,
1694
+ "minivan": 656,
1695
+ "missile": 657,
1696
+ "mitten": 658,
1697
+ "mixing bowl": 659,
1698
+ "mobile home": 660,
1699
+ "Model T": 661,
1700
+ "modem": 662,
1701
+ "monastery": 663,
1702
+ "monitor": 664,
1703
+ "moped": 665,
1704
+ "mortar": 666,
1705
+ "mortarboard": 667,
1706
+ "mosque": 668,
1707
+ "mosquito net": 669,
1708
+ "motor scooter": 670,
1709
+ "mountain bike": 671,
1710
+ "mountain tent": 672,
1711
+ "mouse": 673,
1712
+ "mousetrap": 674,
1713
+ "moving van": 675,
1714
+ "muzzle": 676,
1715
+ "nail": 677,
1716
+ "neck brace": 678,
1717
+ "necklace": 679,
1718
+ "nipple": 680,
1719
+ "notebook": 681,
1720
+ "obelisk": 682,
1721
+ "oboe": 683,
1722
+ "ocarina": 684,
1723
+ "odometer": 685,
1724
+ "oil filter": 686,
1725
+ "organ": 687,
1726
+ "oscilloscope": 688,
1727
+ "overskirt": 689,
1728
+ "oxcart": 690,
1729
+ "oxygen mask": 691,
1730
+ "packet": 692,
1731
+ "paddle": 693,
1732
+ "paddlewheel": 694,
1733
+ "padlock": 695,
1734
+ "paintbrush": 696,
1735
+ "pajama": 697,
1736
+ "palace": 698,
1737
+ "panpipe": 699,
1738
+ "paper towel": 700,
1739
+ "parachute": 701,
1740
+ "parallel bars": 702,
1741
+ "park bench": 703,
1742
+ "parking meter": 704,
1743
+ "passenger car": 705,
1744
+ "patio": 706,
1745
+ "pay-phone": 707,
1746
+ "pedestal": 708,
1747
+ "pencil box": 709,
1748
+ "pencil sharpener": 710,
1749
+ "perfume": 711,
1750
+ "Petri dish": 712,
1751
+ "photocopier": 713,
1752
+ "pick": 714,
1753
+ "pickelhaube": 715,
1754
+ "picket fence": 716,
1755
+ "pickup": 717,
1756
+ "pier": 718,
1757
+ "piggy bank": 719,
1758
+ "pill bottle": 720,
1759
+ "pillow": 721,
1760
+ "ping-pong ball": 722,
1761
+ "pinwheel": 723,
1762
+ "pirate": 724,
1763
+ "pitcher": 725,
1764
+ "plane": 726,
1765
+ "planetarium": 727,
1766
+ "plastic bag": 728,
1767
+ "plate rack": 729,
1768
+ "plow": 730,
1769
+ "plunger": 731,
1770
+ "Polaroid camera": 732,
1771
+ "pole": 733,
1772
+ "police van": 734,
1773
+ "poncho": 735,
1774
+ "pool table": 736,
1775
+ "pop bottle": 737,
1776
+ "pot": 738,
1777
+ "potter's wheel": 739,
1778
+ "power drill": 740,
1779
+ "prayer rug": 741,
1780
+ "printer": 742,
1781
+ "prison": 743,
1782
+ "projectile": 744,
1783
+ "projector": 745,
1784
+ "puck": 746,
1785
+ "punching bag": 747,
1786
+ "purse": 748,
1787
+ "quill": 749,
1788
+ "quilt": 750,
1789
+ "racer": 751,
1790
+ "racket": 752,
1791
+ "radiator": 753,
1792
+ "radio": 754,
1793
+ "radio telescope": 755,
1794
+ "rain barrel": 756,
1795
+ "recreational vehicle": 757,
1796
+ "reel": 758,
1797
+ "reflex camera": 759,
1798
+ "refrigerator": 760,
1799
+ "remote control": 761,
1800
+ "restaurant": 762,
1801
+ "revolver": 763,
1802
+ "rifle": 764,
1803
+ "rocking chair": 765,
1804
+ "rotisserie": 766,
1805
+ "rubber eraser": 767,
1806
+ "rugby ball": 768,
1807
+ "rule": 769,
1808
+ "running shoe": 770,
1809
+ "safe": 771,
1810
+ "safety pin": 772,
1811
+ "saltshaker": 773,
1812
+ "sandal": 774,
1813
+ "sarong": 775,
1814
+ "sax": 776,
1815
+ "scabbard": 777,
1816
+ "scale": 778,
1817
+ "school bus": 779,
1818
+ "schooner": 780,
1819
+ "scoreboard": 781,
1820
+ "screen": 782,
1821
+ "screw": 783,
1822
+ "screwdriver": 784,
1823
+ "seat belt": 785,
1824
+ "sewing machine": 786,
1825
+ "shield": 787,
1826
+ "shoe shop": 788,
1827
+ "shoji": 789,
1828
+ "shopping basket": 790,
1829
+ "shopping cart": 791,
1830
+ "shovel": 792,
1831
+ "shower cap": 793,
1832
+ "shower curtain": 794,
1833
+ "ski": 795,
1834
+ "ski mask": 796,
1835
+ "sleeping bag": 797,
1836
+ "slide rule": 798,
1837
+ "sliding door": 799,
1838
+ "slot": 800,
1839
+ "snorkel": 801,
1840
+ "snowmobile": 802,
1841
+ "snowplow": 803,
1842
+ "soap dispenser": 804,
1843
+ "soccer ball": 805,
1844
+ "sock": 806,
1845
+ "solar dish": 807,
1846
+ "sombrero": 808,
1847
+ "soup bowl": 809,
1848
+ "space bar": 810,
1849
+ "space heater": 811,
1850
+ "space shuttle": 812,
1851
+ "spatula": 813,
1852
+ "speedboat": 814,
1853
+ "spider web": 815,
1854
+ "spindle": 816,
1855
+ "sports car": 817,
1856
+ "spotlight": 818,
1857
+ "stage": 819,
1858
+ "steam locomotive": 820,
1859
+ "steel arch bridge": 821,
1860
+ "steel drum": 822,
1861
+ "stethoscope": 823,
1862
+ "stole": 824,
1863
+ "stone wall": 825,
1864
+ "stopwatch": 826,
1865
+ "stove": 827,
1866
+ "strainer": 828,
1867
+ "streetcar": 829,
1868
+ "stretcher": 830,
1869
+ "studio couch": 831,
1870
+ "stupa": 832,
1871
+ "submarine": 833,
1872
+ "suit": 834,
1873
+ "sundial": 835,
1874
+ "sunglass": 836,
1875
+ "sunglasses": 837,
1876
+ "sunscreen": 838,
1877
+ "suspension bridge": 839,
1878
+ "swab": 840,
1879
+ "sweatshirt": 841,
1880
+ "swimming trunks": 842,
1881
+ "swing": 843,
1882
+ "switch": 844,
1883
+ "syringe": 845,
1884
+ "table lamp": 846,
1885
+ "tank": 847,
1886
+ "tape player": 848,
1887
+ "teapot": 849,
1888
+ "teddy": 850,
1889
+ "television": 851,
1890
+ "tennis ball": 852,
1891
+ "thatch": 853,
1892
+ "theater curtain": 854,
1893
+ "thimble": 855,
1894
+ "thresher": 856,
1895
+ "throne": 857,
1896
+ "tile roof": 858,
1897
+ "toaster": 859,
1898
+ "tobacco shop": 860,
1899
+ "toilet seat": 861,
1900
+ "torch": 862,
1901
+ "totem pole": 863,
1902
+ "tow truck": 864,
1903
+ "toyshop": 865,
1904
+ "tractor": 866,
1905
+ "trailer truck": 867,
1906
+ "tray": 868,
1907
+ "trench coat": 869,
1908
+ "tricycle": 870,
1909
+ "trimaran": 871,
1910
+ "tripod": 872,
1911
+ "triumphal arch": 873,
1912
+ "trolleybus": 874,
1913
+ "trombone": 875,
1914
+ "tub": 876,
1915
+ "turnstile": 877,
1916
+ "typewriter keyboard": 878,
1917
+ "umbrella": 879,
1918
+ "unicycle": 880,
1919
+ "upright": 881,
1920
+ "vacuum": 882,
1921
+ "vase": 883,
1922
+ "vault": 884,
1923
+ "velvet": 885,
1924
+ "vending machine": 886,
1925
+ "vestment": 887,
1926
+ "viaduct": 888,
1927
+ "violin": 889,
1928
+ "volleyball": 890,
1929
+ "waffle iron": 891,
1930
+ "wall clock": 892,
1931
+ "wallet": 893,
1932
+ "wardrobe": 894,
1933
+ "warplane": 895,
1934
+ "washbasin": 896,
1935
+ "washer": 897,
1936
+ "water bottle": 898,
1937
+ "water jug": 899,
1938
+ "water tower": 900,
1939
+ "whiskey jug": 901,
1940
+ "whistle": 902,
1941
+ "wig": 903,
1942
+ "window screen": 904,
1943
+ "window shade": 905,
1944
+ "Windsor tie": 906,
1945
+ "wine bottle": 907,
1946
+ "wing": 908,
1947
+ "wok": 909,
1948
+ "wooden spoon": 910,
1949
+ "wool": 911,
1950
+ "worm fence": 912,
1951
+ "wreck": 913,
1952
+ "yawl": 914,
1953
+ "yurt": 915,
1954
+ "web site": 916,
1955
+ "comic book": 917,
1956
+ "crossword puzzle": 918,
1957
+ "street sign": 919,
1958
+ "traffic light": 920,
1959
+ "book jacket": 921,
1960
+ "menu": 922,
1961
+ "plate": 923,
1962
+ "guacamole": 924,
1963
+ "consomme": 925,
1964
+ "hot pot": 926,
1965
+ "trifle": 927,
1966
+ "ice cream": 928,
1967
+ "ice lolly": 929,
1968
+ "French loaf": 930,
1969
+ "bagel": 931,
1970
+ "pretzel": 932,
1971
+ "cheeseburger": 933,
1972
+ "hotdog": 934,
1973
+ "mashed potato": 935,
1974
+ "head cabbage": 936,
1975
+ "broccoli": 937,
1976
+ "cauliflower": 938,
1977
+ "zucchini": 939,
1978
+ "spaghetti squash": 940,
1979
+ "acorn squash": 941,
1980
+ "butternut squash": 942,
1981
+ "cucumber": 943,
1982
+ "artichoke": 944,
1983
+ "bell pepper": 945,
1984
+ "cardoon": 946,
1985
+ "mushroom": 947,
1986
+ "Granny Smith": 948,
1987
+ "strawberry": 949,
1988
+ "orange": 950,
1989
+ "lemon": 951,
1990
+ "fig": 952,
1991
+ "pineapple": 953,
1992
+ "banana": 954,
1993
+ "jackfruit": 955,
1994
+ "custard apple": 956,
1995
+ "pomegranate": 957,
1996
+ "hay": 958,
1997
+ "carbonara": 959,
1998
+ "chocolate sauce": 960,
1999
+ "dough": 961,
2000
+ "meat loaf": 962,
2001
+ "pizza": 963,
2002
+ "potpie": 964,
2003
+ "burrito": 965,
2004
+ "red wine": 966,
2005
+ "espresso": 967,
2006
+ "cup": 968,
2007
+ "eggnog": 969,
2008
+ "alp": 970,
2009
+ "bubble": 971,
2010
+ "cliff": 972,
2011
+ "coral reef": 973,
2012
+ "geyser": 974,
2013
+ "lakeside": 975,
2014
+ "promontory": 976,
2015
+ "sandbar": 977,
2016
+ "seashore": 978,
2017
+ "valley": 979,
2018
+ "volcano": 980,
2019
+ "ballplayer": 981,
2020
+ "groom": 982,
2021
+ "scuba diver": 983,
2022
+ "rapeseed": 984,
2023
+ "daisy": 985,
2024
+ "yellow lady's slipper": 986,
2025
+ "corn": 987,
2026
+ "acorn": 988,
2027
+ "hip": 989,
2028
+ "buckeye": 990,
2029
+ "coral fungus": 991,
2030
+ "agaric": 992,
2031
+ "gyromitra": 993,
2032
+ "stinkhorn": 994,
2033
+ "earthstar": 995,
2034
+ "hen-of-the-woods": 996,
2035
+ "bolete": 997,
2036
+ "ear": 998,
2037
+ "toilet tissue": 999
2038
+ },
2039
+ "dtype": "float32"
2040
+ }
configuration_ntlm_class25.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Configuration for NoTokenLM-ImageGen-Class-2.5 (hybrid conv/attention ImageNet-1k classifier)."""
2
+ from transformers import PretrainedConfig
3
+
4
+
5
+ class NTLMClass25Config(PretrainedConfig):
6
+ """Architecture hyper-parameters. Field names mirror the JAX training code (`ntlm_core.Cfg`)."""
7
+
8
+ model_type = "ntlm_class25"
9
+
10
+ def __init__(
11
+ self,
12
+ widths=(64, 128, 256, 384), # channels of the 4 stages
13
+ depths=(2, 3, 3, 2), # blocks per stage (stage 1 = Fused-MBConv, stages 2-4 = ConvNeXt-style)
14
+ ratios=(4, 4, 4, 3), # MLP / expansion ratio per stage
15
+ heads=4, # attention heads (global attention, last block of stage 4)
16
+ head_dim=1024, # width of the hidden layer of the classification head
17
+ num_classes=1000,
18
+ dw_k=7, # depthwise kernel size of the ConvNeXt blocks
19
+ ls_init=1e-2, # layer-scale init (irrelevant at inference)
20
+ drop_path=0.1, # stochastic depth rate (training only, unused here)
21
+ default_resolution=128, # resolution the final training stages used
22
+ **kwargs,
23
+ ):
24
+ self.widths = list(widths)
25
+ self.depths = list(depths)
26
+ self.ratios = list(ratios)
27
+ self.heads = heads
28
+ self.head_dim = head_dim
29
+ self.num_classes = num_classes
30
+ self.dw_k = dw_k
31
+ self.ls_init = ls_init
32
+ self.drop_path = drop_path
33
+ self.default_resolution = default_resolution
34
+ kwargs.setdefault("num_labels", num_classes)
35
+ super().__init__(**kwargs)
evaluate.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Reproduce the ImageNet-1k validation accuracy (50,000 images) at 64 px or 128 px.
3
+
4
+ python evaluate.py --res 128 # uses benjamin-paine/imagenet-1k-128x128 (gated: accept the terms, set HF_TOKEN)
5
+ python evaluate.py --res 64 --limit 5000 # quick check on the first 5,000 images
6
+ python evaluate.py --res 128 --parquet val-0.parquet val-1.parquet # already-downloaded validation parquet files
7
+ """
8
+ import argparse, io, os, time
9
+
10
+ import numpy as np
11
+ import pyarrow.parquet as pq
12
+ import torch
13
+ from PIL import Image
14
+ from transformers import AutoModelForImageClassification
15
+
16
+ DEFAULT_REPO = "VeroLM/NoTokenLM-ImageGen-Class-2.5"
17
+
18
+
19
+ def parquet_files(res, token):
20
+ from huggingface_hub import HfApi, hf_hub_download
21
+ repo = f"benjamin-paine/imagenet-1k-{res}x{res}"
22
+ names = sorted(f for f in HfApi(token=token).list_repo_files(repo, repo_type="dataset")
23
+ if f.startswith("data/validation-") and f.endswith(".parquet"))
24
+ return [hf_hub_download(repo, n, repo_type="dataset", token=token) for n in names]
25
+
26
+
27
+ def main():
28
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
29
+ ap.add_argument("--model", default=DEFAULT_REPO)
30
+ ap.add_argument("--res", type=int, choices=[64, 128], default=128)
31
+ ap.add_argument("--batch", type=int, default=250)
32
+ ap.add_argument("--limit", type=int, default=0, help="evaluate only the first N images (0 = all)")
33
+ ap.add_argument("--parquet", nargs="*", help="local validation parquet files instead of downloading")
34
+ ap.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
35
+ ap.add_argument("--dtype", choices=["float32", "bfloat16"], default="float32")
36
+ ap.add_argument("--token", default=os.environ.get("HF_TOKEN"))
37
+ a = ap.parse_args()
38
+
39
+ model = AutoModelForImageClassification.from_pretrained(
40
+ a.model, trust_remote_code=True, token=a.token, dtype=getattr(torch, a.dtype)).to(a.device).eval()
41
+ files = a.parquet or parquet_files(a.res, a.token)
42
+
43
+ n = c1 = c5 = 0
44
+ t0 = time.time()
45
+ xs, ys = [], []
46
+
47
+ def flush():
48
+ nonlocal n, c1, c5, xs, ys
49
+ if not xs:
50
+ return
51
+ x = torch.from_numpy(np.stack(xs)).permute(0, 3, 1, 2).float().to(a.device)
52
+ y = torch.tensor(ys, device=a.device)
53
+ with torch.no_grad():
54
+ top5 = model(x).logits.topk(5, -1).indices
55
+ c1 += (top5[:, 0] == y).sum().item()
56
+ c5 += (top5 == y[:, None]).any(-1).sum().item()
57
+ n += len(ys); xs, ys = [], []
58
+ print(f"\r{n:>6} images | top-1 {100 * c1 / n:.2f}% | top-5 {100 * c5 / n:.2f}% | {time.time() - t0:.0f}s", end="", flush=True)
59
+
60
+ done = False
61
+ for f in files:
62
+ pf = pq.ParquetFile(f)
63
+ for rg in range(pf.num_row_groups):
64
+ tbl = pf.read_row_group(rg, columns=["image", "label"]).to_pydict()
65
+ for img, lab in zip(tbl["image"], tbl["label"]):
66
+ im = Image.open(io.BytesIO(img["bytes"])).convert("RGB")
67
+ if im.size != (a.res, a.res):
68
+ im = im.resize((a.res, a.res), Image.LANCZOS)
69
+ xs.append(np.asarray(im)); ys.append(int(lab))
70
+ if len(xs) == a.batch:
71
+ flush()
72
+ if a.limit and n + len(xs) >= a.limit:
73
+ done = True; break
74
+ if done: break
75
+ if done: break
76
+ flush()
77
+ print(f"\n\nImageNet-1k val @ {a.res}px ({n:,} images): top-1 = {100 * c1 / n:.2f}% top-5 = {100 * c5 / n:.2f}%")
78
+
79
+
80
+ if __name__ == "__main__":
81
+ main()
inference.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Classify images with NoTokenLM-ImageGen-Class-2.5.
3
+
4
+ python inference.py cat.jpg dog.png https://example.com/x.jpg
5
+ python inference.py photo.jpg --res 64 --topk 10
6
+ python inference.py photo.jpg --model ./local_dir_with_weights --device cpu --json
7
+
8
+ Images are prepared exactly like the training data (centre square crop -> Lanczos 256 -> 128 -> --res).
9
+ """
10
+ import argparse, io, json, os, sys, urllib.request
11
+
12
+ import torch
13
+ from PIL import Image
14
+ from transformers import AutoModelForImageClassification
15
+
16
+ DEFAULT_REPO = "VeroLM/NoTokenLM-ImageGen-Class-2.5"
17
+
18
+
19
+ def load_image(src):
20
+ if src.startswith(("http://", "https://")):
21
+ req = urllib.request.Request(src, headers={"User-Agent": "ntlm-class25/1.0"})
22
+ with urllib.request.urlopen(req, timeout=30) as r:
23
+ return Image.open(io.BytesIO(r.read())).convert("RGB")
24
+ return Image.open(src).convert("RGB")
25
+
26
+
27
+ def main():
28
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
29
+ ap.add_argument("images", nargs="+", help="image file paths or http(s) URLs")
30
+ ap.add_argument("--model", default=DEFAULT_REPO, help="Hub repo id or local folder (default: %(default)s)")
31
+ ap.add_argument("--res", type=int, default=128, help="input resolution, multiple of 16 (trained at 64 and 128)")
32
+ ap.add_argument("--topk", type=int, default=5)
33
+ ap.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
34
+ ap.add_argument("--dtype", choices=["float32", "bfloat16"], default="float32",
35
+ help="float32 matches the reference exactly; bfloat16 matches the training numerics")
36
+ ap.add_argument("--token", default=os.environ.get("HF_TOKEN"), help="HF token (needed only for private repos)")
37
+ ap.add_argument("--json", action="store_true", help="print machine-readable JSON")
38
+ a = ap.parse_args()
39
+
40
+ model = AutoModelForImageClassification.from_pretrained(
41
+ a.model, trust_remote_code=True, token=a.token, dtype=getattr(torch, a.dtype)).to(a.device).eval()
42
+ imgs = []
43
+ for s in a.images:
44
+ try:
45
+ imgs.append(load_image(s))
46
+ except Exception as e:
47
+ sys.exit(f"cannot read '{s}': {e}")
48
+ results = model.predict(imgs, top_k=a.topk, resolution=a.res)
49
+
50
+ if a.json:
51
+ print(json.dumps({s: r for s, r in zip(a.images, results)}, indent=2, ensure_ascii=False))
52
+ return
53
+ for s, r in zip(a.images, results):
54
+ print(f"\n{s}")
55
+ for rank, p in enumerate(r, 1):
56
+ print(f" {rank}. {p['label']:<35} {p['score'] * 100:6.2f}% (class {p['id']})")
57
+
58
+
59
+ if __name__ == "__main__":
60
+ main()
modeling_ntlm_class25.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PyTorch inference implementation of NoTokenLM-ImageGen-Class-2.5.
2
+
3
+ Re-implementation of the JAX training code (`ntlm_core.py`, shipped in this repo). Parameter names and
4
+ shapes are identical to the JAX checkpoint (conv kernels stay in HWIO layout, dense kernels are
5
+ (in, out)), so `model.safetensors` is loaded as-is, without any conversion step.
6
+
7
+ Input : float tensor (N, 3, H, W), RGB, values 0..255 (normalisation happens inside the model);
8
+ H and W must be multiples of 16 (trained at 64 and 128 px).
9
+ Output: logits over the 1000 ImageNet-1k classes.
10
+ """
11
+ import math
12
+ import os
13
+ from typing import List, Optional, Sequence, Union
14
+
15
+ import numpy as np
16
+ import torch
17
+ import torch.nn as nn
18
+ import torch.nn.functional as F
19
+ from transformers import PreTrainedModel
20
+ from transformers.modeling_outputs import ImageClassifierOutput
21
+
22
+ from .configuration_ntlm_class25 import NTLMClass25Config
23
+
24
+ WEIGHTS_NAME = "model.safetensors"
25
+ _LN_EPS = 1e-6
26
+
27
+
28
+ # ------------------------------------------------------------------------------ helpers
29
+ def _trunc_normal(*shape, std=0.02):
30
+ return nn.Parameter(torch.nn.init.trunc_normal_(torch.empty(*shape), std=std, a=-2 * std, b=2 * std))
31
+
32
+
33
+ def _zeros(*shape):
34
+ return nn.Parameter(torch.zeros(*shape))
35
+
36
+
37
+ def _ones(*shape, value=1.0):
38
+ return nn.Parameter(torch.full(shape, float(value)))
39
+
40
+
41
+ def _ln(x, g, b):
42
+ """LayerNorm over the last dim, computed in fp32 (as in the JAX code)."""
43
+ return F.layer_norm(x.float(), (x.shape[-1],), g.float(), b.float(), _LN_EPS).to(x.dtype)
44
+
45
+
46
+ def _dense(x, w, b):
47
+ return torch.matmul(x, w.to(x.dtype)) + b.to(x.dtype)
48
+
49
+
50
+ def _conv(x, w_hwio, b, stride=1, padding=0, groups=1):
51
+ """x: (N,H,W,C) NHWC, w: HWIO (as in JAX). Returns NHWC."""
52
+ y = F.conv2d(x.permute(0, 3, 1, 2), w_hwio.permute(3, 2, 0, 1).to(x.dtype), b.to(x.dtype),
53
+ stride=stride, padding=padding, groups=groups)
54
+ return y.permute(0, 2, 3, 1)
55
+
56
+
57
+ def _gelu(x):
58
+ return F.gelu(x, approximate="tanh")
59
+
60
+
61
+ def _space_to_depth(x, r=4):
62
+ n, h, w, c = x.shape
63
+ x = x.reshape(n, h // r, r, w // r, r, c).permute(0, 1, 3, 2, 4, 5)
64
+ return x.reshape(n, h // r, w // r, r * r * c)
65
+
66
+
67
+ # ------------------------------------------------------------------------------ blocks
68
+ class _Stem(nn.Module):
69
+ def __init__(self, cout):
70
+ super().__init__()
71
+ self.conv_w, self.conv_b = _trunc_normal(3, 3, 48, cout), _zeros(cout)
72
+ self.ln_g, self.ln_b = _ones(cout), _zeros(cout)
73
+
74
+ def forward(self, x):
75
+ x = _conv(_space_to_depth(x, 4), self.conv_w, self.conv_b, padding=1)
76
+ return _ln(x, self.ln_g, self.ln_b)
77
+
78
+
79
+ class _FusedBlock(nn.Module):
80
+ def __init__(self, c, e, ls_init):
81
+ super().__init__()
82
+ self.ln_g, self.ln_b = _ones(c), _zeros(c)
83
+ self.conv_w, self.conv_b = _trunc_normal(3, 3, c, c * e), _zeros(c * e)
84
+ self.pw_w, self.pw_b = _trunc_normal(c * e, c), _zeros(c)
85
+ self.ls = _ones(c, value=ls_init) # `gamma` in the JAX checkpoint
86
+
87
+ def forward(self, x):
88
+ y = _ln(x, self.ln_g, self.ln_b)
89
+ y = _gelu(_conv(y, self.conv_w, self.conv_b, padding=1))
90
+ y = _dense(y, self.pw_w, self.pw_b)
91
+ return x + self.ls.to(x.dtype) * y
92
+
93
+
94
+ class _ConvNeXtBlock(nn.Module):
95
+ def __init__(self, c, r, k, heads, ls_init, attn=False):
96
+ super().__init__()
97
+ self.heads, self.k, self.has_attn = heads, k, attn
98
+ self.dw_w, self.dw_b = _trunc_normal(k, k, 1, c), _zeros(c)
99
+ self.ln_g, self.ln_b = _ones(c), _zeros(c)
100
+ self.pw1_w, self.pw1_b = _trunc_normal(c, c * r), _zeros(c * r)
101
+ self.pw2_w, self.pw2_b = _trunc_normal(c * r, c), _zeros(c)
102
+ self.ls = _ones(c, value=ls_init) # `gamma`
103
+ if attn:
104
+ self.a_ln_g, self.a_ln_b = _ones(c), _zeros(c)
105
+ self.qkv_w, self.qkv_b = _trunc_normal(c, 3 * c), _zeros(3 * c)
106
+ self.proj_w, self.proj_b = _trunc_normal(c, c), _zeros(c)
107
+ self.a_ls = _ones(c, value=ls_init) # `a_gamma`
108
+
109
+ def _attention(self, x):
110
+ n, h, w, c = x.shape
111
+ hd = c // self.heads
112
+ y = _ln(x, self.a_ln_g, self.a_ln_b).reshape(n, h * w, c)
113
+ qkv = _dense(y, self.qkv_w, self.qkv_b).reshape(n, h * w, 3, self.heads, hd)
114
+ q, k, v = qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2]
115
+ s = torch.einsum("nqhd,nkhd->nhqk", q, k) * hd ** -0.5
116
+ a = torch.softmax(s.float(), -1).to(y.dtype)
117
+ o = torch.einsum("nhqk,nkhd->nqhd", a, v).reshape(n, h * w, c)
118
+ o = _dense(o, self.proj_w, self.proj_b).reshape(n, h, w, c)
119
+ return x + self.a_ls.to(x.dtype) * o
120
+
121
+ def forward(self, x):
122
+ y = _conv(x, self.dw_w, self.dw_b, padding=self.k // 2, groups=x.shape[-1])
123
+ y = _ln(y, self.ln_g, self.ln_b)
124
+ y = _gelu(_dense(y, self.pw1_w, self.pw1_b))
125
+ y = _dense(y, self.pw2_w, self.pw2_b)
126
+ x = x + self.ls.to(x.dtype) * y
127
+ return self._attention(x) if self.has_attn else x
128
+
129
+
130
+ class _Down(nn.Module):
131
+ """Stages 1->2 and 2->3: LN + 2x2 stride-2 conv. Stage 3->4: LN + 1x1 projection (no spatial change)."""
132
+ def __init__(self, cin, cout, conv: bool):
133
+ super().__init__()
134
+ self.is_conv = conv
135
+ self.ln_g, self.ln_b = _ones(cin), _zeros(cin)
136
+ if conv:
137
+ self.conv_w, self.conv_b = _trunc_normal(2, 2, cin, cout), _zeros(cout)
138
+ else:
139
+ self.pw_w, self.pw_b = _trunc_normal(cin, cout), _zeros(cout)
140
+
141
+ def forward(self, x):
142
+ x = _ln(x, self.ln_g, self.ln_b)
143
+ if self.is_conv:
144
+ return _conv(x, self.conv_w, self.conv_b, stride=2, padding=0)
145
+ return _dense(x, self.pw_w, self.pw_b)
146
+
147
+
148
+ class _Head(nn.Module):
149
+ def __init__(self, c, hidden, num_classes):
150
+ super().__init__()
151
+ self.ln_g, self.ln_b = _ones(c), _zeros(c)
152
+ self.pw_w, self.pw_b = _trunc_normal(c, hidden), _zeros(hidden)
153
+ self.cls_w, self.cls_b = _trunc_normal(hidden, num_classes), _zeros(num_classes)
154
+
155
+ def forward(self, x):
156
+ x = _ln(x.mean((1, 2)), self.ln_g, self.ln_b)
157
+ x = _gelu(_dense(x, self.pw_w, self.pw_b))
158
+ return _dense(x, self.cls_w, self.cls_b)
159
+
160
+
161
+ # ------------------------------------------------------------------------------ preprocessing
162
+ ImageLike = Union[str, os.PathLike, "PIL.Image.Image", np.ndarray]
163
+
164
+
165
+ def preprocess_images(images: Union[ImageLike, Sequence[ImageLike]], resolution: int = 128) -> torch.Tensor:
166
+ """Reproduces the training-data pipeline (the `benjamin-paine/imagenet-1k-*` repacks):
167
+ centre-crop to a square on the short side -> Lanczos to 256 -> Lanczos to 128 -> Lanczos to `resolution`.
168
+ Returns a float32 tensor (N, 3, resolution, resolution) with values in 0..255."""
169
+ from PIL import Image
170
+
171
+ if isinstance(images, (str, os.PathLike, Image.Image, np.ndarray)):
172
+ images = [images]
173
+ if resolution % 16 != 0:
174
+ raise ValueError(f"resolution must be a multiple of 16 (got {resolution}).")
175
+ out = []
176
+ for im in images:
177
+ if isinstance(im, (str, os.PathLike)):
178
+ im = Image.open(im)
179
+ elif isinstance(im, np.ndarray):
180
+ im = Image.fromarray(im.astype(np.uint8))
181
+ im = im.convert("RGB")
182
+ w, h = im.size
183
+ s = min(w, h)
184
+ left, top = (w - s) // 2, (h - s) // 2
185
+ im = im.crop((left, top, left + s, top + s))
186
+ for r in (256, 128, resolution):
187
+ if im.size != (r, r):
188
+ im = im.resize((r, r), Image.LANCZOS)
189
+ out.append(np.asarray(im, dtype=np.uint8))
190
+ return torch.from_numpy(np.stack(out)).permute(0, 3, 1, 2).float().contiguous()
191
+
192
+
193
+ # ------------------------------------------------------------------------------ model
194
+ class NTLMClass25ForImageClassification(PreTrainedModel):
195
+ config_class = NTLMClass25Config
196
+ main_input_name = "pixel_values"
197
+ _supports_sdpa = False
198
+
199
+ def __init__(self, config: NTLMClass25Config):
200
+ super().__init__(config)
201
+ w, d, r = config.widths, config.depths, config.ratios
202
+ self.stem = _Stem(w[0])
203
+ self.s1 = nn.ModuleList([_FusedBlock(w[0], r[0], config.ls_init) for _ in range(d[0])])
204
+ for i in (1, 2, 3):
205
+ setattr(self, f"down{i}", _Down(w[i - 1], w[i], conv=(i < 3)))
206
+ setattr(self, f"s{i + 1}", nn.ModuleList([
207
+ _ConvNeXtBlock(w[i], r[i], config.dw_k, config.heads, config.ls_init,
208
+ attn=(i == 3 and j == d[i] - 1)) for j in range(d[i])]))
209
+ self.head = _Head(w[3], config.head_dim, config.num_classes)
210
+ self.post_init()
211
+
212
+ def _init_weights(self, module): # parameters are initialised in the block constructors
213
+ pass
214
+
215
+ # --------------------------------------------------------------- forward
216
+ def forward(self, pixel_values: torch.Tensor, labels: Optional[torch.Tensor] = None, return_dict: Optional[bool] = None):
217
+ if pixel_values.ndim != 4 or pixel_values.shape[1] != 3:
218
+ raise ValueError("pixel_values must have shape (N, 3, H, W), RGB, values 0..255.")
219
+ h, w = pixel_values.shape[-2:]
220
+ if h % 16 or w % 16:
221
+ raise ValueError(f"H and W must be multiples of 16 (got {h}x{w}).")
222
+ dtype = self.stem.conv_w.dtype
223
+ x = pixel_values.permute(0, 2, 3, 1).to(dtype) # NHWC
224
+ x = (x - 127.5) / 127.5
225
+ x = self.stem(x)
226
+ for blk in self.s1:
227
+ x = blk(x)
228
+ for i in (1, 2, 3):
229
+ x = getattr(self, f"down{i}")(x)
230
+ for blk in getattr(self, f"s{i + 1}"):
231
+ x = blk(x)
232
+ logits = self.head(x).float()
233
+ loss = F.cross_entropy(logits, labels) if labels is not None else None
234
+ if return_dict is False:
235
+ return (loss, logits) if loss is not None else (logits,)
236
+ return ImageClassifierOutput(loss=loss, logits=logits)
237
+
238
+ # --------------------------------------------------------------- convenience API
239
+ @staticmethod
240
+ def preprocess(images, resolution: int = 128) -> torch.Tensor:
241
+ """See `preprocess_images`: centre square crop -> Lanczos 256 -> 128 -> `resolution`; float32 (N,3,R,R), 0..255."""
242
+ return preprocess_images(images, resolution)
243
+
244
+ @torch.no_grad()
245
+ def predict(self, images, top_k: int = 5, resolution: Optional[int] = None, batch_size: int = 64):
246
+ """Classify PIL images / file paths / HxWx3 uint8 arrays.
247
+ Returns, per image, a list of `top_k` dicts: {"id", "label", "score"} (score = softmax probability)."""
248
+ single = isinstance(images, (str, os.PathLike, np.ndarray)) or hasattr(images, "convert")
249
+ images = [images] if single else list(images)
250
+ res = resolution or self.config.default_resolution
251
+ id2label = self.config.id2label
252
+ k = min(top_k, self.config.num_classes)
253
+ results = []
254
+ was_training = self.training
255
+ self.eval()
256
+ device = next(self.parameters()).device
257
+ for i in range(0, len(images), batch_size):
258
+ x = preprocess_images(images[i:i + batch_size], res).to(device)
259
+ probs = torch.softmax(self(x).logits, -1)
260
+ sc, ix = probs.topk(k, dim=-1)
261
+ for s_row, i_row in zip(sc.tolist(), ix.tolist()):
262
+ results.append([{"id": int(j), "label": id2label.get(int(j), f"LABEL_{j}"), "score": float(s)}
263
+ for s, j in zip(s_row, i_row)])
264
+ self.train(was_training)
265
+ return results[0] if single else results
266
+
267
+ # --------------------------------------------------------------- loading
268
+ @classmethod
269
+ def from_pretrained(cls, pretrained_model_name_or_path, *model_args, config=None, dtype=None,
270
+ torch_dtype=None, **kwargs):
271
+ """Loads `model.safetensors` exactly as exported by the JAX training notebook.
272
+
273
+ (The JAX checkpoint names the layer-scale vectors `gamma` / `a_gamma`; `transformers` silently renames
274
+ any key containing "gamma" while loading, which would break a standard load, so this model reads the
275
+ file itself and maps those two names to `ls` / `a_ls`.)"""
276
+ from safetensors.torch import load_file
277
+
278
+ hub_kw = {k: kwargs[k] for k in ("cache_dir", "force_download", "proxies", "token", "local_files_only",
279
+ "revision", "subfolder") if k in kwargs}
280
+ if "token" not in hub_kw and kwargs.get("use_auth_token") is not None:
281
+ hub_kw["token"] = kwargs["use_auth_token"]
282
+ path = str(pretrained_model_name_or_path)
283
+ if config is None:
284
+ config = cls.config_class.from_pretrained(path, **hub_kw)
285
+ if os.path.isdir(path):
286
+ sub = hub_kw.get("subfolder", "")
287
+ wfile = os.path.join(path, sub, WEIGHTS_NAME)
288
+ elif os.path.isfile(path):
289
+ wfile = path
290
+ else:
291
+ from huggingface_hub import hf_hub_download
292
+ wfile = hf_hub_download(path, WEIGHTS_NAME, **hub_kw)
293
+
294
+ model = cls(config)
295
+ own = set(model.state_dict().keys())
296
+ state = {}
297
+ for k, v in load_file(wfile).items():
298
+ state[k if k in own else k.replace("gamma", "ls")] = v
299
+ missing, unexpected = model.load_state_dict(state, strict=False)
300
+ if missing or unexpected:
301
+ raise RuntimeError(f"Checkpoint does not match the model config. missing={missing[:5]} "
302
+ f"unexpected={unexpected[:5]} (config widths/depths/ratios/head_dim correct?)")
303
+ dt = dtype or torch_dtype
304
+ if isinstance(dt, str) and dt != "auto":
305
+ dt = getattr(torch, dt)
306
+ if isinstance(dt, torch.dtype):
307
+ model = model.to(dt)
308
+ return model.eval()
notebook.ipynb ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "9cc4ebd3",
6
+ "metadata": {},
7
+ "source": [
8
+ "# NoTokenLM-ImageGen-Class-2.5 — Interactive Playground\n",
9
+ "\n",
10
+ "A **6.48 M-parameter**, token-free hybrid convolution/attention **ImageNet-1k classifier** (Fused-MBConv + ConvNeXt-style blocks + one global-attention layer). Input: any image, prepared at **64 or 128 px**. Trained from scratch in JAX on a TPU v5e-1 (Muon + AdamW), 112,097 steps.\n",
11
+ "\n",
12
+ "This notebook lets you:\n",
13
+ "- load the model straight from the Hugging Face Hub,\n",
14
+ "- classify your own images (upload or URL) and see the top-k predictions,\n",
15
+ "- compare 64 px and 128 px inference.\n",
16
+ "\n",
17
+ "Works on **Google Colab**, **Kaggle** and any Jupyter environment; a GPU is not needed."
18
+ ]
19
+ },
20
+ {
21
+ "cell_type": "markdown",
22
+ "id": "43df7492",
23
+ "metadata": {},
24
+ "source": [
25
+ "## 1. Setup\n",
26
+ "Does not touch `torch`, so Colab/Kaggle's pre-matched versions stay intact."
27
+ ]
28
+ },
29
+ {
30
+ "cell_type": "code",
31
+ "execution_count": null,
32
+ "id": "0eb56d4d",
33
+ "metadata": {},
34
+ "outputs": [],
35
+ "source": [
36
+ "%pip install -q -U \"transformers>=4.44\" safetensors huggingface_hub pillow ipywidgets"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "markdown",
41
+ "id": "3434ddf4",
42
+ "metadata": {},
43
+ "source": [
44
+ "## 2. Load the model\n",
45
+ "`trust_remote_code=True` is required: the architecture (`modeling_ntlm_class25.py`) ships with the weights.\n",
46
+ "If the repo is private, set `HF_TOKEN` (Colab: 🔑 Secrets) or run `huggingface_hub.login()` first."
47
+ ]
48
+ },
49
+ {
50
+ "cell_type": "code",
51
+ "execution_count": null,
52
+ "id": "60718ea5",
53
+ "metadata": {},
54
+ "outputs": [],
55
+ "source": [
56
+ "import os, torch\n",
57
+ "from transformers import AutoModelForImageClassification\n",
58
+ "\n",
59
+ "REPO_ID = os.environ.get(\"NTLM_REPO\", \"VeroLM/NoTokenLM-ImageGen-Class-2.5\") # or a local folder\n",
60
+ "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
61
+ "\n",
62
+ "try: # Colab Secrets, if available\n",
63
+ " from google.colab import userdata\n",
64
+ " token = userdata.get(\"HF_TOKEN\")\n",
65
+ "except Exception:\n",
66
+ " token = os.environ.get(\"HF_TOKEN\")\n",
67
+ "\n",
68
+ "model = AutoModelForImageClassification.from_pretrained(REPO_ID, trust_remote_code=True, token=token).to(device).eval()\n",
69
+ "print(f\"{sum(p.numel() for p in model.parameters()):,} parameters on {device}\")"
70
+ ]
71
+ },
72
+ {
73
+ "cell_type": "markdown",
74
+ "id": "afbfea77",
75
+ "metadata": {},
76
+ "source": [
77
+ "## 3. Classify\n",
78
+ "`model.predict(images, top_k=5, resolution=128)` accepts PIL images, file paths or HxWx3 uint8 arrays, and returns `[{\"id\", \"label\", \"score\"}, ...]` per image. Preprocessing reproduces the training data: centre square crop → Lanczos 256 → 128 → `resolution`."
79
+ ]
80
+ },
81
+ {
82
+ "cell_type": "code",
83
+ "execution_count": null,
84
+ "id": "9ed11046",
85
+ "metadata": {},
86
+ "outputs": [],
87
+ "source": [
88
+ "import io, urllib.request\n",
89
+ "from PIL import Image\n",
90
+ "\n",
91
+ "def load_url(url):\n",
92
+ " req = urllib.request.Request(url, headers={\"User-Agent\": \"ntlm-class25/1.0\"})\n",
93
+ " with urllib.request.urlopen(req, timeout=30) as r:\n",
94
+ " return Image.open(io.BytesIO(r.read())).convert(\"RGB\")\n",
95
+ "\n",
96
+ "# Example — edit and re-run\n",
97
+ "# img = load_url(\"https://upload.wikimedia.org/wikipedia/commons/4/4d/Cat_November_2010-1a.jpg\")\n",
98
+ "# for p in model.predict(img, top_k=5, resolution=128): print(f\"{p['score']*100:5.1f}% {p['label']}\")"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "markdown",
103
+ "id": "b97736dd",
104
+ "metadata": {},
105
+ "source": [
106
+ "## 4. Interactive panel\n",
107
+ "Upload an image *or* paste a URL, pick the resolution and the number of predictions, then click **Classify**."
108
+ ]
109
+ },
110
+ {
111
+ "cell_type": "code",
112
+ "execution_count": null,
113
+ "id": "05533744",
114
+ "metadata": {},
115
+ "outputs": [],
116
+ "source": [
117
+ "import base64, html\n",
118
+ "import ipywidgets as widgets\n",
119
+ "from IPython.display import display, clear_output, HTML\n",
120
+ "\n",
121
+ "upload = widgets.FileUpload(accept=\"image/*\", multiple=False, description=\"Upload image\")\n",
122
+ "url_box = widgets.Text(placeholder=\"…or paste an image URL\", description=\"URL:\", layout=widgets.Layout(width=\"520px\"))\n",
123
+ "res_dd = widgets.ToggleButtons(options=[(\"64 px\", 64), (\"128 px\", 128)], value=128, description=\"Resolution:\")\n",
124
+ "topk_sl = widgets.IntSlider(value=5, min=1, max=10, description=\"Top-k:\")\n",
125
+ "btn = widgets.Button(description=\"Classify\", button_style=\"primary\", icon=\"search\")\n",
126
+ "out = widgets.Output()\n",
127
+ "\n",
128
+ "def show(img, results, res):\n",
129
+ " thumb = img.copy(); thumb.thumbnail((256, 256))\n",
130
+ " buf = io.BytesIO(); thumb.convert(\"RGB\").save(buf, \"PNG\")\n",
131
+ " b64 = base64.b64encode(buf.getvalue()).decode()\n",
132
+ " rows = \"\".join(\n",
133
+ " f\"<tr><td style='padding:2px 8px;white-space:nowrap'>{html.escape(p['label'])}</td>\"\n",
134
+ " f\"<td style='width:260px'><div style='background:#4c8bf5;height:14px;width:{p['score']*100:.1f}%;min-width:1px'></div></td>\"\n",
135
+ " f\"<td style='padding:2px 8px'>{p['score']*100:.1f}%</td></tr>\" for p in results)\n",
136
+ " display(HTML(f\"<div style='display:flex;gap:16px;align-items:flex-start'><img src='data:image/png;base64,{b64}'>\"\n",
137
+ " f\"<div><b>{res} px input</b><table>{rows}</table></div></div>\"))\n",
138
+ "\n",
139
+ "def classify(img, res, k):\n",
140
+ " show(img, model.predict(img, top_k=k, resolution=res), res)\n",
141
+ "\n",
142
+ "def on_click(_):\n",
143
+ " with out:\n",
144
+ " clear_output(wait=True)\n",
145
+ " try:\n",
146
+ " if upload.value:\n",
147
+ " f = upload.value[0] if isinstance(upload.value, (list, tuple)) else list(upload.value.values())[0]\n",
148
+ " content = f[\"content\"] if isinstance(f, dict) else f.content\n",
149
+ " img = Image.open(io.BytesIO(bytes(content))).convert(\"RGB\")\n",
150
+ " elif url_box.value.strip():\n",
151
+ " img = load_url(url_box.value.strip())\n",
152
+ " else:\n",
153
+ " print(\"Upload an image or paste a URL first.\"); return\n",
154
+ " classify(img, res_dd.value, topk_sl.value)\n",
155
+ " except Exception as e:\n",
156
+ " print(f\"{type(e).__name__}: {e}\")\n",
157
+ "\n",
158
+ "btn.on_click(on_click)\n",
159
+ "display(widgets.VBox([widgets.HBox([upload, url_box]), res_dd, topk_sl, btn, out]))"
160
+ ]
161
+ },
162
+ {
163
+ "cell_type": "markdown",
164
+ "id": "ece83c14",
165
+ "metadata": {},
166
+ "source": [
167
+ "## 5. Several images / 64 px vs 128 px\n",
168
+ "Run the same images at both resolutions to see how much the extra detail helps."
169
+ ]
170
+ },
171
+ {
172
+ "cell_type": "code",
173
+ "execution_count": null,
174
+ "id": "4c6030f4",
175
+ "metadata": {},
176
+ "outputs": [],
177
+ "source": [
178
+ "def compare(images, k=3):\n",
179
+ " for i, im in enumerate(images):\n",
180
+ " for res in (64, 128):\n",
181
+ " top = model.predict(im, top_k=k, resolution=res)\n",
182
+ " print(f\"[{i}] {res:>3}px:\", \" | \".join(f\"{p['label']} {p['score']*100:.0f}%\" for p in top))\n",
183
+ "\n",
184
+ "# compare([load_url(\"https://…/a.jpg\"), \"local_photo.png\"])"
185
+ ]
186
+ },
187
+ {
188
+ "cell_type": "markdown",
189
+ "id": "17dfac4f",
190
+ "metadata": {},
191
+ "source": [
192
+ "## About this model\n",
193
+ "Hybrid conv/attention classifier with ≈6.5 M parameters, no tokens, no patch-embedding transformer trunk: a 4×4 space-to-depth stem, two Fused-MBConv blocks, three ConvNeXt-style stages and a single 4-head global-attention layer in the last block. Trained with Muon (matrix weights) + AdamW, EMA weights are what is stored in the repo. See the [model card](https://huggingface.co/VeroLM/NoTokenLM-ImageGen-Class-2.5) for results and limitations."
194
+ ]
195
+ }
196
+ ],
197
+ "metadata": {
198
+ "colab": {
199
+ "name": "NoTokenLM-ImageGen-Class-2.5-Playground.ipynb",
200
+ "provenance": []
201
+ },
202
+ "kernelspec": {
203
+ "display_name": "Python 3",
204
+ "language": "python",
205
+ "name": "python3"
206
+ },
207
+ "language_info": {
208
+ "name": "python"
209
+ }
210
+ },
211
+ "nbformat": 4,
212
+ "nbformat_minor": 5
213
+ }
ntlm_core.py ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """NoTokenLM-ImageGen-Class-2.5 çekirdeği: model, Muon hibriti, cihaz-içi augmentation.
2
+
3
+ Saf JAX (Flax yok). Bu dosya eğitimi yapan notebook tarafından repoya da yüklenir.
4
+ Girdi: (N,H,W,3) görüntü, değerler 0..255 (uint8 ya da float). H,W 16'nın katı.
5
+ """
6
+ import math
7
+ from dataclasses import dataclass
8
+ from typing import Any, NamedTuple
9
+
10
+ import numpy as np
11
+ import jax
12
+ import jax.numpy as jnp
13
+ from jax import lax
14
+ import optax
15
+
16
+ BF16, F32 = jnp.bfloat16, jnp.float32
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class Cfg:
21
+ widths: tuple = (64, 128, 256, 384)
22
+ depths: tuple = (2, 3, 3, 2)
23
+ ratios: tuple = (4, 4, 4, 3)
24
+ heads: int = 4
25
+ head_dim: int = 1024
26
+ num_classes: int = 1000
27
+ dw_k: int = 7
28
+ ls_init: float = 1e-2
29
+ drop_path: float = 0.1
30
+
31
+
32
+ # ---------------------------------------------------------------- başlatma
33
+ def tn(key, shape, std=0.02):
34
+ return jax.random.truncated_normal(key, -2.0, 2.0, shape, F32) * std
35
+
36
+
37
+ def zeros(n):
38
+ return jnp.zeros((n,), F32)
39
+
40
+
41
+ def ln_p(c):
42
+ return {"ln_g": jnp.ones((c,), F32), "ln_b": zeros(c)}
43
+
44
+
45
+ def init_fused(key, c, e, cfg):
46
+ k1, k2 = jax.random.split(key)
47
+ return {**ln_p(c),
48
+ "conv_w": tn(k1, (3, 3, c, c * e)), "conv_b": zeros(c * e),
49
+ "pw_w": tn(k2, (c * e, c)), "pw_b": zeros(c),
50
+ "gamma": jnp.full((c,), cfg.ls_init, F32)}
51
+
52
+
53
+ def init_convnext(key, c, r, cfg, attn=False):
54
+ ks = jax.random.split(key, 5)
55
+ p = {"dw_w": tn(ks[0], (cfg.dw_k, cfg.dw_k, 1, c)), "dw_b": zeros(c),
56
+ **ln_p(c),
57
+ "pw1_w": tn(ks[1], (c, c * r)), "pw1_b": zeros(c * r),
58
+ "pw2_w": tn(ks[2], (c * r, c)), "pw2_b": zeros(c),
59
+ "gamma": jnp.full((c,), cfg.ls_init, F32)}
60
+ if attn:
61
+ p.update({"a_ln_g": jnp.ones((c,), F32), "a_ln_b": zeros(c),
62
+ "qkv_w": tn(ks[3], (c, 3 * c)), "qkv_b": zeros(3 * c),
63
+ "proj_w": tn(ks[4], (c, c)), "proj_b": zeros(c),
64
+ "a_gamma": jnp.full((c,), cfg.ls_init, F32)})
65
+ return p
66
+
67
+
68
+ def init_params(key, cfg):
69
+ ks = iter(jax.random.split(key, 256))
70
+ nk = lambda: next(ks)
71
+ w = cfg.widths
72
+ P = {"stem": {"conv_w": tn(nk(), (3, 3, 48, w[0])), "conv_b": zeros(w[0]), **ln_p(w[0])}}
73
+ P["s1"] = [init_fused(nk(), w[0], cfg.ratios[0], cfg) for _ in range(cfg.depths[0])]
74
+ for i in (1, 2, 3):
75
+ cin, cout = w[i - 1], w[i]
76
+ if i < 3:
77
+ P[f"down{i}"] = {**ln_p(cin), "conv_w": tn(nk(), (2, 2, cin, cout)), "conv_b": zeros(cout)}
78
+ else:
79
+ P["down3"] = {**ln_p(cin), "pw_w": tn(nk(), (cin, cout)), "pw_b": zeros(cout)}
80
+ P[f"s{i + 1}"] = [
81
+ init_convnext(nk(), cout, cfg.ratios[i], cfg,
82
+ attn=(i == 3 and j == cfg.depths[i] - 1))
83
+ for j in range(cfg.depths[i])]
84
+ P["head"] = {**ln_p(w[3]),
85
+ "pw_w": tn(nk(), (w[3], cfg.head_dim)), "pw_b": zeros(cfg.head_dim),
86
+ "cls_w": tn(nk(), (cfg.head_dim, cfg.num_classes)), "cls_b": zeros(cfg.num_classes)}
87
+ return P
88
+
89
+
90
+ def count(tree):
91
+ return int(sum(np.prod(a.shape) for a in jax.tree_util.tree_leaves(tree)))
92
+
93
+
94
+ def named_leaves(tree):
95
+ out = {}
96
+ for path, leaf in jax.tree_util.tree_flatten_with_path(tree)[0]:
97
+ name = ".".join(str(getattr(k, "key", getattr(k, "idx", k))) for k in path)
98
+ out[name] = np.asarray(leaf)
99
+ return out
100
+
101
+
102
+ # ---------------------------------------------------------------- model
103
+ def layer_norm(x, g, b, eps=1e-6):
104
+ xf = x.astype(F32)
105
+ mu = xf.mean(-1, keepdims=True)
106
+ var = ((xf - mu) ** 2).mean(-1, keepdims=True)
107
+ return (((xf - mu) * lax.rsqrt(var + eps)) * g + b).astype(x.dtype)
108
+
109
+
110
+ def dense(x, w, b):
111
+ return jnp.einsum("...c,cd->...d", x, w.astype(x.dtype)) + b.astype(x.dtype)
112
+
113
+
114
+ def conv(x, w, b, stride=1, padding="SAME", groups=1):
115
+ y = lax.conv_general_dilated(
116
+ x, w.astype(x.dtype), (stride, stride), padding,
117
+ dimension_numbers=("NHWC", "HWIO", "NHWC"), feature_group_count=groups)
118
+ return y + b.astype(x.dtype)
119
+
120
+
121
+ def dwconv(x, w, b):
122
+ return conv(x, w, b, groups=x.shape[-1])
123
+
124
+
125
+ def gelu(x):
126
+ return jax.nn.gelu(x, approximate=True)
127
+
128
+
129
+ def space_to_depth(x, r=4):
130
+ n, h, w, c = x.shape
131
+ x = x.reshape(n, h // r, r, w // r, r, c).transpose(0, 1, 3, 2, 4, 5)
132
+ return x.reshape(n, h // r, w // r, r * r * c)
133
+
134
+
135
+ def drop_path(y, rate, key):
136
+ if rate == 0.0 or key is None:
137
+ return y
138
+ keep = 1.0 - rate
139
+ m = jax.random.bernoulli(key, keep, (y.shape[0], 1, 1, 1)).astype(y.dtype)
140
+ return y * m / keep
141
+
142
+
143
+ def fused_block(x, p, rate=0.0, key=None):
144
+ y = layer_norm(x, p["ln_g"], p["ln_b"])
145
+ y = gelu(conv(y, p["conv_w"], p["conv_b"]))
146
+ y = dense(y, p["pw_w"], p["pw_b"])
147
+ return x + p["gamma"].astype(x.dtype) * drop_path(y, rate, key)
148
+
149
+
150
+ def attention(x, p, heads, rate=0.0, key=None):
151
+ n, h, w, c = x.shape
152
+ y = layer_norm(x, p["a_ln_g"], p["a_ln_b"]).reshape(n, h * w, c)
153
+ qkv = dense(y, p["qkv_w"], p["qkv_b"]).reshape(n, h * w, 3, heads, c // heads)
154
+ q, k, v = qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2]
155
+ s = jnp.einsum("nqhd,nkhd->nhqk", q, k) * (c // heads) ** -0.5
156
+ a = jax.nn.softmax(s.astype(F32), -1).astype(y.dtype)
157
+ o = jnp.einsum("nhqk,nkhd->nqhd", a, v).reshape(n, h * w, c)
158
+ o = dense(o, p["proj_w"], p["proj_b"]).reshape(n, h, w, c)
159
+ return x + p["a_gamma"].astype(x.dtype) * drop_path(o, rate, key)
160
+
161
+
162
+ def convnext_block(x, p, heads=4, rate=0.0, key=None):
163
+ y = dwconv(x, p["dw_w"], p["dw_b"])
164
+ y = layer_norm(y, p["ln_g"], p["ln_b"])
165
+ y = gelu(dense(y, p["pw1_w"], p["pw1_b"]))
166
+ y = dense(y, p["pw2_w"], p["pw2_b"])
167
+ k1 = jax.random.fold_in(key, 0) if key is not None else None
168
+ k2 = jax.random.fold_in(key, 1) if key is not None else None
169
+ x = x + p["gamma"].astype(x.dtype) * drop_path(y, rate, k1)
170
+ if "qkv_w" in p:
171
+ x = attention(x, p, heads, rate, k2)
172
+ return x
173
+
174
+
175
+ def apply(params, x, cfg, train=False, key=None):
176
+ """x: (N,H,W,3) 0..255. Dönüş: f32 logit."""
177
+ total = sum(cfg.depths)
178
+ rates = [cfg.drop_path * i / max(total - 1, 1) for i in range(total)] if train else [0.0] * total
179
+ bi = 0
180
+
181
+ def bkey():
182
+ return jax.random.fold_in(key, bi) if (train and key is not None) else None
183
+
184
+ x = (x.astype(BF16) - 127.5) / 127.5
185
+ with jax.named_scope("stem"):
186
+ p = params["stem"]
187
+ x = layer_norm(conv(space_to_depth(x, 4), p["conv_w"], p["conv_b"]), p["ln_g"], p["ln_b"])
188
+ with jax.named_scope("s1"):
189
+ for blk in params["s1"]:
190
+ x = fused_block(x, blk, rates[bi], bkey()); bi += 1
191
+ for i in (1, 2, 3):
192
+ with jax.named_scope(f"down{i}"):
193
+ p = params[f"down{i}"]
194
+ x = layer_norm(x, p["ln_g"], p["ln_b"])
195
+ x = conv(x, p["conv_w"], p["conv_b"], stride=2, padding="VALID") if i < 3 \
196
+ else dense(x, p["pw_w"], p["pw_b"])
197
+ with jax.named_scope(f"s{i + 1}"):
198
+ for blk in params[f"s{i + 1}"]:
199
+ x = convnext_block(x, blk, cfg.heads, rates[bi], bkey()); bi += 1
200
+ with jax.named_scope("head"):
201
+ p = params["head"]
202
+ x = layer_norm(x.mean((1, 2)), p["ln_g"], p["ln_b"])
203
+ x = gelu(dense(x, p["pw_w"], p["pw_b"]))
204
+ return dense(x, p["cls_w"], p["cls_b"]).astype(F32)
205
+
206
+
207
+ # ---------------------------------------------------------------- Muon
208
+ def newton_schulz(G, steps=5):
209
+ a, b, c = 3.4445, -4.7750, 2.0315
210
+ X = G.astype(BF16)
211
+ tr = X.shape[-2] > X.shape[-1]
212
+ if tr:
213
+ X = jnp.swapaxes(X, -1, -2)
214
+ nrm = jnp.linalg.norm(X.astype(F32), axis=(-2, -1), keepdims=True) + 1e-7
215
+ X = X / nrm.astype(BF16)
216
+ for _ in range(steps):
217
+ A = X @ jnp.swapaxes(X, -1, -2)
218
+ B = b * A + c * (A @ A)
219
+ X = a * X + B @ X
220
+ return jnp.swapaxes(X, -1, -2) if tr else X
221
+
222
+
223
+ def _ns_batched(leaves, steps):
224
+ canon, flags = [], []
225
+ for l in leaves:
226
+ t = l.shape[0] > l.shape[1]
227
+ canon.append(l.T if t else l)
228
+ flags.append(t)
229
+ groups = {}
230
+ for i, c in enumerate(canon):
231
+ groups.setdefault(c.shape, []).append(i)
232
+ out = [None] * len(leaves)
233
+ for _, idxs in groups.items():
234
+ res = newton_schulz(jnp.stack([canon[i] for i in idxs]), steps)
235
+ for j, i in enumerate(idxs):
236
+ out[i] = res[j].T if flags[i] else res[j]
237
+ return out
238
+
239
+
240
+ class MuonState(NamedTuple):
241
+ mu: Any
242
+
243
+
244
+ def scale_by_muon(beta=0.95, ns_steps=5, batched=True, rms_match=0.2):
245
+ def init_fn(params):
246
+ return MuonState(mu=jax.tree_util.tree_map(jnp.zeros_like, params))
247
+
248
+ def update_fn(updates, state, params=None):
249
+ del params
250
+ mu = jax.tree_util.tree_map(lambda m, g: beta * m + g, state.mu, updates)
251
+ u = jax.tree_util.tree_map(lambda m, g: g + beta * m, mu, updates) # Nesterov
252
+ leaves, treedef = jax.tree_util.tree_flatten(u)
253
+ outs = _ns_batched(leaves, ns_steps) if batched else \
254
+ [newton_schulz(l, ns_steps) for l in leaves]
255
+ outs = [o.astype(F32) * (rms_match * math.sqrt(max(l.shape))) for o, l in zip(outs, leaves)]
256
+ return treedef.unflatten(outs), MuonState(mu=mu)
257
+
258
+ return optax.GradientTransformation(init_fn, update_fn)
259
+
260
+
261
+ def label_tree(params):
262
+ def f(path, leaf):
263
+ name = path[-1].key
264
+ return "muon" if (name.endswith("_w") and leaf.ndim == 2 and name != "cls_w") else "adamw"
265
+ return jax.tree_util.tree_map_with_path(f, params)
266
+
267
+
268
+ def make_schedule(total_steps, warmup_steps, peak_lr, final_frac=0.01, ext=None):
269
+ """Ana program (0..total_steps) + isteğe bağlı uzatma parçaları.
270
+ ext: [dict(start, steps, peak, warmup, final_frac)]; start'tan itibaren yeni warmup+cosine geçerli olur."""
271
+ base = optax.warmup_cosine_decay_schedule(0.0, peak_lr, warmup_steps, total_steps,
272
+ end_value=peak_lr * final_frac)
273
+ if not ext:
274
+ return base
275
+ scheds, bounds = [base], []
276
+ for e in ext:
277
+ scheds.append(optax.warmup_cosine_decay_schedule(0.0, e["peak"], e["warmup"], e["steps"],
278
+ end_value=e["peak"] * e["final_frac"]))
279
+ bounds.append(e["start"])
280
+ return optax.join_schedules(scheds, bounds)
281
+
282
+
283
+ def make_optimizer(params, total_steps, warmup_steps, peak_lr, wd, final_frac=0.01, clip=1.0, ns_steps=5, ext=None):
284
+ sched = make_schedule(total_steps, warmup_steps, peak_lr, final_frac, ext)
285
+ wd_mask = jax.tree_util.tree_map(lambda x: x.ndim >= 2, params)
286
+ tx = optax.chain(
287
+ optax.clip_by_global_norm(clip),
288
+ optax.multi_transform({"muon": scale_by_muon(ns_steps=ns_steps, batched=True),
289
+ "adamw": optax.scale_by_adam()}, label_tree(params)),
290
+ optax.add_decayed_weights(wd, mask=wd_mask),
291
+ optax.scale_by_schedule(lambda c: -sched(c)),
292
+ )
293
+ return tx, sched
294
+
295
+
296
+ # ---------------------------------------------------------------- augmentation
297
+ def soft_targets(y, num_classes, smoothing):
298
+ oh = jax.nn.one_hot(y, num_classes)
299
+ return oh * (1.0 - smoothing) + smoothing / num_classes
300
+
301
+
302
+ def random_resized_crop_flip(key, imgs_u8, out_res, min_scale):
303
+ """Cihazda: RandomResizedCrop (alan [min_scale,1], oran [3/4,4/3]) + yatay çevirme."""
304
+ x = imgs_u8.astype(F32)
305
+ B, S = x.shape[0], x.shape[1]
306
+ k1, k2, k3, k4 = jax.random.split(key, 4)
307
+ area = jax.random.uniform(k1, (B,), minval=min_scale, maxval=1.0)
308
+ ar = jnp.exp(jax.random.uniform(k2, (B,), minval=math.log(3 / 4), maxval=math.log(4 / 3)))
309
+ w = jnp.clip(jnp.sqrt(area * ar), 0.05, 1.0)
310
+ h = jnp.clip(jnp.sqrt(area / ar), 0.05, 1.0)
311
+ u = jax.random.uniform(k3, (B, 2))
312
+ y0, x0 = u[:, 0] * (1 - h) * S, u[:, 1] * (1 - w) * S
313
+ sy, sx = out_res / (h * S), out_res / (w * S)
314
+
315
+ def one(img, sy, sx, ty, tx):
316
+ return jax.image.scale_and_translate(
317
+ img, (out_res, out_res, img.shape[-1]), (0, 1),
318
+ jnp.stack([sy, sx]), jnp.stack([ty, tx]), method="linear")
319
+
320
+ out = jax.vmap(one)(x, sy, sx, -y0 * sy, -x0 * sx)
321
+ flip = jax.random.bernoulli(k4, 0.5, (B, 1, 1, 1))
322
+ out = jnp.where(flip, out[:, :, ::-1], out)
323
+ return jnp.clip(out, 0.0, 255.0)
324
+
325
+
326
+ def cutmix(key, x, y_soft, alpha=1.0):
327
+ B, H, W, _ = x.shape
328
+ k1, k2, k3 = jax.random.split(key, 3)
329
+ lam = jax.random.beta(k1, alpha, alpha)
330
+ cut = jnp.sqrt(1.0 - lam)
331
+ ch, cw = (cut * H).astype(jnp.int32), (cut * W).astype(jnp.int32)
332
+ cy, cx = jax.random.randint(k2, (), 0, H), jax.random.randint(k3, (), 0, W)
333
+ y1, y2 = jnp.clip(cy - ch // 2, 0, H), jnp.clip(cy + ch // 2, 0, H)
334
+ x1, x2 = jnp.clip(cx - cw // 2, 0, W), jnp.clip(cx + cw // 2, 0, W)
335
+ ys, xs = jnp.arange(H)[:, None], jnp.arange(W)[None, :]
336
+ mask = ((ys >= y1) & (ys < y2) & (xs >= x1) & (xs < x2))[None, :, :, None]
337
+ perm = jnp.roll(jnp.arange(B), 1)
338
+ xm = jnp.where(mask, x[perm], x)
339
+ lam_adj = 1.0 - ((y2 - y1) * (x2 - x1)).astype(F32) / (H * W)
340
+ return xm, lam_adj * y_soft + (1.0 - lam_adj) * y_soft[perm]
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ torch>=2.1
2
+ transformers>=4.44
3
+ safetensors
4
+ huggingface_hub
5
+ pillow
6
+ numpy
7
+ pyarrow # only needed by evaluate.py