{ "cells": [ { "cell_type": "markdown", "id": "9cc4ebd3", "metadata": {}, "source": [ "# NoTokenLM-ImageGen-Class-2.5 — Interactive Playground\n", "\n", "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", "\n", "This notebook lets you:\n", "- load the model straight from the Hugging Face Hub,\n", "- classify your own images (upload or URL) and see the top-k predictions,\n", "- compare 64 px and 128 px inference.\n", "\n", "Works on **Google Colab**, **Kaggle** and any Jupyter environment; a GPU is not needed." ] }, { "cell_type": "markdown", "id": "43df7492", "metadata": {}, "source": [ "## 1. Setup\n", "Does not touch `torch`, so Colab/Kaggle's pre-matched versions stay intact." ] }, { "cell_type": "code", "execution_count": null, "id": "0eb56d4d", "metadata": {}, "outputs": [], "source": [ "%pip install -q -U \"transformers>=4.44\" safetensors huggingface_hub pillow ipywidgets" ] }, { "cell_type": "markdown", "id": "3434ddf4", "metadata": {}, "source": [ "## 2. Load the model (from `latest.npz`)\n", "The weights are read from **`latest.npz`** instead of `model.safetensors`. Only `config.json` and the architecture code (`modeling_ntlm_class25.py`, …) are taken from `REPO_ID` (Hub repo or local folder); `model.safetensors` is never downloaded.\n", "\n", "`latest.npz` is looked up in this order: `NPZ_PATH` (env var `NTLM_NPZ`) → the model folder → `/content`, `/kaggle/working`, `/kaggle/input` → the Hub repo → (Colab) an upload prompt.\n", "\n", "Two npz layouts are supported: (a) named keys (any prefix such as `ema.` / `params.` is stripped, EMA preferred), and (b) the training checkpoint format with unnamed keys `a00000, a00001, …` (JAX `tree_leaves` order). In (b) the file holds params, EMA and optimizer state; the loader finds the full weight sets by matching tensor shapes and prints what it found. If it picked the raw parameters and you want the other set, set `NTLM_PICK=1`.\n", "\n", "The `HF_TOKEN` warnings are harmless for public repos." ] }, { "cell_type": "code", "execution_count": null, "id": "60718ea5", "metadata": {}, "outputs": [], "source": [ "import os, re, glob, torch, numpy as np\n", "from transformers import AutoConfig, AutoModelForImageClassification\n", "\n", "REPO_ID = os.environ.get(\"NTLM_REPO\", \"VeroLM/NoTokenLM-ImageGen-Class-2.5\") # config + mimari kodu için (veya yerel klasör)\n", "NPZ_PATH = os.environ.get(\"NTLM_NPZ\", \"latest.npz\") # ağırlıklar: latest.npz yolu\n", "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n", "\n", "try: # Colab Secrets varsa\n", " from google.colab import userdata\n", " token = userdata.get(\"HF_TOKEN\")\n", "except Exception:\n", " token = os.environ.get(\"HF_TOKEN\")\n", "\n", "# --- 1) Mimari: config.json + modeling_*.py (model.safetensors İNDİRİLMEZ) -------------------------------\n", "if os.path.isdir(REPO_ID):\n", " code_dir = REPO_ID\n", "else:\n", " from huggingface_hub import snapshot_download\n", " code_dir = snapshot_download(REPO_ID, token=token,\n", " allow_patterns=[\"config.json\", \"*.py\"]) # sadece config ve kod\n", "config = AutoConfig.from_pretrained(code_dir, trust_remote_code=True)\n", "model = AutoModelForImageClassification.from_config(config, trust_remote_code=True)\n", "\n", "# --- 2) latest.npz dosyasını bul ------------------------------------------------------------------------\n", "def find_npz(path):\n", " cands = [path, os.path.join(code_dir, \"latest.npz\"), \"/content/latest.npz\", \"/kaggle/working/latest.npz\"]\n", " cands += glob.glob(\"/kaggle/input/**/latest.npz\", recursive=True)\n", " for c in cands:\n", " if c and os.path.isfile(c):\n", " return c\n", " try: # Hub deposunda varsa oradan indir\n", " from huggingface_hub import hf_hub_download\n", " return hf_hub_download(REPO_ID, \"latest.npz\", token=token)\n", " except Exception:\n", " pass\n", " try: # Colab: elle yükle\n", " from google.colab import files\n", " print(\"latest.npz bulunamadı — lütfen yükleyin:\")\n", " up = files.upload()\n", " return next(iter(up))\n", " except Exception:\n", " raise FileNotFoundError(\"latest.npz bulunamadı. NPZ_PATH değişkenini dosyanın yoluna ayarlayın.\")\n", "\n", "# --- 3) npz anahtarlarını modelin parametre adlarına eşle -----------------------------------------------\n", "def _norm(k):\n", " k = re.sub(r\"\\[(\\d+)\\]\", r\".\\1\", k) # s1[0] -> s1.0\n", " k = re.sub(r\"\\[['\\\"]?([^\\]'\\\"]+)['\\\"]?\\]\", r\".\\1\", k)\n", " return k.replace(\"/\", \".\").replace(\"::\", \".\").strip(\".\")\n", "\n", "def _read_npz(path):\n", " try:\n", " z = np.load(path, allow_pickle=False)\n", " flat = {_norm(k): z[k] for k in z.files}\n", " except ValueError: # dict/pickle olarak kaydedilmişse\n", " z = np.load(path, allow_pickle=True)\n", " flat = {}\n", " def walk(o, pre):\n", " if isinstance(o, dict):\n", " for k, v in o.items(): walk(v, f\"{pre}.{k}\" if pre else str(k))\n", " elif isinstance(o, (list, tuple)):\n", " for i, v in enumerate(o): walk(v, f\"{pre}.{i}\" if pre else str(i))\n", " else:\n", " a = np.asarray(o)\n", " if a.dtype != object: flat[_norm(pre)] = a\n", " for k in z.files:\n", " v = z[k]\n", " walk(v.item() if v.dtype == object and v.ndim == 0 else v, k)\n", " return flat\n", "\n", "WEIGHT_PICK = int(os.environ.get(\"NTLM_PICK\", \"0\")) # adsız npz'de birden fazla tam ağırlık seti varsa hangisi (0 = ilk)\n", "\n", "def _to_f32(a):\n", " if a.dtype.kind == \"V\" and a.dtype.itemsize == 2: # bfloat16 ham baytlar\n", " a = (a.view(np.uint16).astype(np.uint32) << 16).view(np.float32)\n", " return np.ascontiguousarray(a, dtype=np.float32)\n", "\n", "def _load_positional(model, flat, targets):\n", " \"\"\"JAX `tree_leaves` sırasıyla (sözlük anahtarları alfabetik, listeler sırayla) kaydedilmiş checkpoint.\"\"\"\n", " skey = lambda n: tuple((0, int(p)) if p.isdigit() else (1, p) for p in n.split(\".\"))\n", " order = sorted(targets, key=skey) # beklenen yaprak sırası (JAX adlarıyla)\n", " want = [tuple(model.state_dict()[targets[t]].shape) for t in order]\n", " keys = sorted(flat, key=lambda k: int(re.sub(r\"\\D\", \"\", k) or 0))\n", " arrs = [flat[k] for k in keys]\n", " shapes = [tuple(a.shape) for a in arrs]\n", " n = len(order)\n", " starts = [i for i in range(len(arrs) - n + 1) if shapes[i:i + n] == want]\n", " if not starts:\n", " raise RuntimeError(f\"npz içinde {n} yapraklık, modele uyan bir ağırlık dizisi bulunamadı \"\n", " f\"(npz'de {len(arrs)} dizi var; ilk şekiller: {shapes[:6]}).\")\n", " def stats(i):\n", " g = [_to_f32(arrs[i + j]) for j, t in enumerate(order) if t.endswith(\"ln_g\")]\n", " b = [_to_f32(arrs[i + j]) for j, t in enumerate(order) if t.endswith(\"ln_b\")]\n", " return float(np.mean([x.mean() for x in g])), float(np.mean([np.abs(x).mean() for x in b]))\n", " good = [i for i in starts if stats(i)[0] > 0.3] # optimizer momentleri: LN gain ≈ 1 olmaz\n", " cands = good or starts\n", " print(f\"adsız npz ({len(arrs)} dizi): {len(cands)} tam ağırlık seti bulundu, başlangıç indeksleri {cands}\")\n", " if len(cands) > 1:\n", " d = np.mean([np.abs(_to_f32(arrs[cands[0] + j]) - _to_f32(arrs[cands[1] + j])).mean() for j in range(n)])\n", " print(f\" (ilk iki set arası ort. mutlak fark: {d:.2e} — biri EMA, diğeri ham parametre olabilir; \"\n", " f\"değiştirmek için WEIGHT_PICK / NTLM_PICK ayarlayın)\")\n", " start = cands[min(WEIGHT_PICK, len(cands) - 1)]\n", " g, b = stats(start)\n", " print(f\" kullanılan set: indeks {start} (LN gain ort. {g:.2f}, LN bias ort. |.| {b:.3f})\")\n", " if not 0.3 < g < 3.0:\n", " print(\" UYARI: LayerNorm değerleri beklenenden farklı — yanlış set seçilmiş olabilir.\")\n", " state = {targets[t]: torch.from_numpy(_to_f32(arrs[start + j])) for j, t in enumerate(order)}\n", " model.load_state_dict(state, strict=True)\n", " return model\n", "\n", "def load_npz_into(model, path):\n", " flat = _read_npz(path)\n", " jax_name = lambda n: n.replace(\"a_ls\", \"a_gamma\").replace(\".ls\", \".gamma\") # modeldeki ls -> JAX'teki gamma\n", " targets = {jax_name(n): n for n in model.state_dict()}\n", " # her hedef için aday önekleri bul (örn. \"ema\", \"params\", \"state.ema\" …)\n", " prefixes = None\n", " for t in targets:\n", " ps = {k[: -len(t)].rstrip(\".\") for k in flat if k == t or k.endswith(\".\" + t)}\n", " prefixes = ps if prefixes is None else prefixes & ps\n", " prefixes = sorted(prefixes or [])\n", " if not prefixes:\n", " return _load_positional(model, flat, targets) # a00000, a00001, … gibi adsız anahtarlar\n", " bad = (\"opt\", \"mu\", \"nu\", \"mom\", \"adam\", \"grad\")\n", " def score(p):\n", " low = p.lower()\n", " return ((\"ema\" in low) * 4 + (\"param\" in low) * 2 - any(b in low.split(\".\") for b in bad) * 8)\n", " best = max(prefixes, key=lambda p: (score(p), -len(p)))\n", " print(f\"npz öneki: '{best}'\" + (f\" (diğer adaylar: {[p for p in prefixes if p != best]})\" if len(prefixes) > 1 else \"\"))\n", " state = {}\n", " for t, own in targets.items():\n", " a = flat[f\"{best}.{t}\" if best else t]\n", " want = tuple(model.state_dict()[own].shape)\n", " if tuple(a.shape) != want:\n", " raise RuntimeError(f\"şekil uyuşmuyor: {t}: npz {tuple(a.shape)} ≠ model {want}\")\n", " state[own] = torch.from_numpy(np.ascontiguousarray(a)).float()\n", " model.load_state_dict(state, strict=True)\n", " return model\n", "\n", "npz_file = find_npz(NPZ_PATH)\n", "print(\"ağırlıklar:\", npz_file)\n", "model = load_npz_into(model, npz_file).to(device).eval()\n", "print(f\"{sum(p.numel() for p in model.parameters()):,} parameters on {device}\")" ] }, { "cell_type": "markdown", "id": "afbfea77", "metadata": {}, "source": [ "## 3. Classify\n", "`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`." ] }, { "cell_type": "code", "execution_count": null, "id": "9ed11046", "metadata": {}, "outputs": [], "source": [ "import io, urllib.request\n", "from PIL import Image\n", "\n", "def load_url(url):\n", " req = urllib.request.Request(url, headers={\"User-Agent\": \"ntlm-class25/1.0\"})\n", " with urllib.request.urlopen(req, timeout=30) as r:\n", " return Image.open(io.BytesIO(r.read())).convert(\"RGB\")\n", "\n", "# Example — edit and re-run\n", "# img = load_url(\"https://upload.wikimedia.org/wikipedia/commons/4/4d/Cat_November_2010-1a.jpg\")\n", "# for p in model.predict(img, top_k=5, resolution=128): print(f\"{p['score']*100:5.1f}% {p['label']}\")" ] }, { "cell_type": "markdown", "id": "b97736dd", "metadata": {}, "source": [ "## 4. Interactive panel\n", "Upload an image *or* paste a URL, pick the resolution and the number of predictions, then click **Classify**." ] }, { "cell_type": "code", "execution_count": null, "id": "05533744", "metadata": {}, "outputs": [], "source": [ "import base64, html\n", "import ipywidgets as widgets\n", "from IPython.display import display, clear_output, HTML\n", "\n", "upload = widgets.FileUpload(accept=\"image/*\", multiple=False, description=\"Upload image\")\n", "url_box = widgets.Text(placeholder=\"…or paste an image URL\", description=\"URL:\", layout=widgets.Layout(width=\"520px\"))\n", "res_dd = widgets.ToggleButtons(options=[(\"64 px\", 64), (\"128 px\", 128)], value=128, description=\"Resolution:\")\n", "topk_sl = widgets.IntSlider(value=5, min=1, max=10, description=\"Top-k:\")\n", "btn = widgets.Button(description=\"Classify\", button_style=\"primary\", icon=\"search\")\n", "out = widgets.Output()\n", "\n", "def show(img, results, res):\n", " thumb = img.copy(); thumb.thumbnail((256, 256))\n", " buf = io.BytesIO(); thumb.convert(\"RGB\").save(buf, \"PNG\")\n", " b64 = base64.b64encode(buf.getvalue()).decode()\n", " rows = \"\".join(\n", " f\"{html.escape(p['label'])}\"\n", " f\"
\"\n", " f\"{p['score']*100:.1f}%\" for p in results)\n", " display(HTML(f\"
\"\n", " f\"
{res} px input{rows}
\"))\n", "\n", "def classify(img, res, k):\n", " show(img, model.predict(img, top_k=k, resolution=res), res)\n", "\n", "def on_click(_):\n", " with out:\n", " clear_output(wait=True)\n", " try:\n", " if upload.value:\n", " f = upload.value[0] if isinstance(upload.value, (list, tuple)) else list(upload.value.values())[0]\n", " content = f[\"content\"] if isinstance(f, dict) else f.content\n", " img = Image.open(io.BytesIO(bytes(content))).convert(\"RGB\")\n", " elif url_box.value.strip():\n", " img = load_url(url_box.value.strip())\n", " else:\n", " print(\"Upload an image or paste a URL first.\"); return\n", " classify(img, res_dd.value, topk_sl.value)\n", " except Exception as e:\n", " print(f\"{type(e).__name__}: {e}\")\n", "\n", "btn.on_click(on_click)\n", "display(widgets.VBox([widgets.HBox([upload, url_box]), res_dd, topk_sl, btn, out]))" ] }, { "cell_type": "markdown", "id": "ece83c14", "metadata": {}, "source": [ "## 5. Several images / 64 px vs 128 px\n", "Run the same images at both resolutions to see how much the extra detail helps." ] }, { "cell_type": "code", "execution_count": null, "id": "4c6030f4", "metadata": {}, "outputs": [], "source": [ "def compare(images, k=3):\n", " for i, im in enumerate(images):\n", " for res in (64, 128):\n", " top = model.predict(im, top_k=k, resolution=res)\n", " print(f\"[{i}] {res:>3}px:\", \" | \".join(f\"{p['label']} {p['score']*100:.0f}%\" for p in top))\n", "\n", "# compare([load_url(\"https://…/a.jpg\"), \"local_photo.png\"])" ] }, { "cell_type": "markdown", "id": "17dfac4f", "metadata": {}, "source": [ "## About this model\n", "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." ] } ], "metadata": { "colab": { "name": "NoTokenLM-ImageGen-Class-2.5-Playground.ipynb", "provenance": [] }, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 5 }