Image Classification
Transformers
JAX
ntlm_class25
imagenet-1k
tpu
muon
convnext
hybrid
custom_code
notokenlm
Instructions to use VeroLM/NoTokenLM-ImageGen-Class-2.5 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use VeroLM/NoTokenLM-ImageGen-Class-2.5 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-classification", model="VeroLM/NoTokenLM-ImageGen-Class-2.5", trust_remote_code=True) pipe("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/hub/parrots.png")# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForImageClassification model = AutoModelForImageClassification.from_pretrained("VeroLM/NoTokenLM-ImageGen-Class-2.5", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Upload notebook.ipynb
Browse files- notebook.ipynb +100 -9
notebook.ipynb
CHANGED
|
@@ -41,9 +41,12 @@
|
|
| 41 |
"id": "3434ddf4",
|
| 42 |
"metadata": {},
|
| 43 |
"source": [
|
| 44 |
-
"## 2. Load the model\n",
|
| 45 |
-
"`
|
| 46 |
-
"
|
|
|
|
|
|
|
|
|
|
| 47 |
]
|
| 48 |
},
|
| 49 |
{
|
|
@@ -53,19 +56,107 @@
|
|
| 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\") #
|
|
|
|
| 60 |
"device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
|
| 61 |
"\n",
|
| 62 |
-
"try: # Colab Secrets
|
| 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 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
"print(f\"{sum(p.numel() for p in model.parameters()):,} parameters on {device}\")"
|
| 70 |
]
|
| 71 |
},
|
|
@@ -210,4 +301,4 @@
|
|
| 210 |
},
|
| 211 |
"nbformat": 4,
|
| 212 |
"nbformat_minor": 5
|
| 213 |
-
}
|
|
|
|
| 41 |
"id": "3434ddf4",
|
| 42 |
"metadata": {},
|
| 43 |
"source": [
|
| 44 |
+
"## 2. Load the model (from `latest.npz`)\n",
|
| 45 |
+
"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",
|
| 46 |
+
"\n",
|
| 47 |
+
"`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",
|
| 48 |
+
"The loader strips any prefix in the npz keys (e.g. `ema.`, `params.`) and prefers the **EMA** weights when several sets are present; shapes are checked strictly.\n",
|
| 49 |
+
"If the repo is private, set `HF_TOKEN` (Colab: 🔑 Secrets)."
|
| 50 |
]
|
| 51 |
},
|
| 52 |
{
|
|
|
|
| 56 |
"metadata": {},
|
| 57 |
"outputs": [],
|
| 58 |
"source": [
|
| 59 |
+
"import os, re, glob, torch, numpy as np\n",
|
| 60 |
+
"from transformers import AutoConfig, AutoModelForImageClassification\n",
|
| 61 |
"\n",
|
| 62 |
+
"REPO_ID = os.environ.get(\"NTLM_REPO\", \"VeroLM/NoTokenLM-ImageGen-Class-2.5\") # config + mimari kodu için (veya yerel klasör)\n",
|
| 63 |
+
"NPZ_PATH = os.environ.get(\"NTLM_NPZ\", \"latest.npz\") # ağırlıklar: latest.npz yolu\n",
|
| 64 |
"device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
|
| 65 |
"\n",
|
| 66 |
+
"try: # Colab Secrets varsa\n",
|
| 67 |
" from google.colab import userdata\n",
|
| 68 |
" token = userdata.get(\"HF_TOKEN\")\n",
|
| 69 |
"except Exception:\n",
|
| 70 |
" token = os.environ.get(\"HF_TOKEN\")\n",
|
| 71 |
"\n",
|
| 72 |
+
"# --- 1) Mimari: config.json + modeling_*.py (model.safetensors İNDİRİLMEZ) -------------------------------\n",
|
| 73 |
+
"if os.path.isdir(REPO_ID):\n",
|
| 74 |
+
" code_dir = REPO_ID\n",
|
| 75 |
+
"else:\n",
|
| 76 |
+
" from huggingface_hub import snapshot_download\n",
|
| 77 |
+
" code_dir = snapshot_download(REPO_ID, token=token,\n",
|
| 78 |
+
" allow_patterns=[\"config.json\", \"*.py\"]) # sadece config ve kod\n",
|
| 79 |
+
"config = AutoConfig.from_pretrained(code_dir, trust_remote_code=True)\n",
|
| 80 |
+
"model = AutoModelForImageClassification.from_config(config, trust_remote_code=True)\n",
|
| 81 |
+
"\n",
|
| 82 |
+
"# --- 2) latest.npz dosyasını bul ------------------------------------------------------------------------\n",
|
| 83 |
+
"def find_npz(path):\n",
|
| 84 |
+
" cands = [path, os.path.join(code_dir, \"latest.npz\"), \"/content/latest.npz\", \"/kaggle/working/latest.npz\"]\n",
|
| 85 |
+
" cands += glob.glob(\"/kaggle/input/**/latest.npz\", recursive=True)\n",
|
| 86 |
+
" for c in cands:\n",
|
| 87 |
+
" if c and os.path.isfile(c):\n",
|
| 88 |
+
" return c\n",
|
| 89 |
+
" try: # Hub deposunda varsa oradan indir\n",
|
| 90 |
+
" from huggingface_hub import hf_hub_download\n",
|
| 91 |
+
" return hf_hub_download(REPO_ID, \"latest.npz\", token=token)\n",
|
| 92 |
+
" except Exception:\n",
|
| 93 |
+
" pass\n",
|
| 94 |
+
" try: # Colab: elle yükle\n",
|
| 95 |
+
" from google.colab import files\n",
|
| 96 |
+
" print(\"latest.npz bulunamadı — lütfen yükleyin:\")\n",
|
| 97 |
+
" up = files.upload()\n",
|
| 98 |
+
" return next(iter(up))\n",
|
| 99 |
+
" except Exception:\n",
|
| 100 |
+
" raise FileNotFoundError(\"latest.npz bulunamadı. NPZ_PATH değişkenini dosyanın yoluna ayarlayın.\")\n",
|
| 101 |
+
"\n",
|
| 102 |
+
"# --- 3) npz anahtarlarını modelin parametre adlarına eşle -----------------------------------------------\n",
|
| 103 |
+
"def _norm(k):\n",
|
| 104 |
+
" k = re.sub(r\"\\[(\\d+)\\]\", r\".\\1\", k) # s1[0] -> s1.0\n",
|
| 105 |
+
" k = re.sub(r\"\\[['\\\"]?([^\\]'\\\"]+)['\\\"]?\\]\", r\".\\1\", k)\n",
|
| 106 |
+
" return k.replace(\"/\", \".\").replace(\"::\", \".\").strip(\".\")\n",
|
| 107 |
+
"\n",
|
| 108 |
+
"def _read_npz(path):\n",
|
| 109 |
+
" try:\n",
|
| 110 |
+
" z = np.load(path, allow_pickle=False)\n",
|
| 111 |
+
" flat = {_norm(k): z[k] for k in z.files}\n",
|
| 112 |
+
" except ValueError: # dict/pickle olarak kaydedilmişse\n",
|
| 113 |
+
" z = np.load(path, allow_pickle=True)\n",
|
| 114 |
+
" flat = {}\n",
|
| 115 |
+
" def walk(o, pre):\n",
|
| 116 |
+
" if isinstance(o, dict):\n",
|
| 117 |
+
" for k, v in o.items(): walk(v, f\"{pre}.{k}\" if pre else str(k))\n",
|
| 118 |
+
" elif isinstance(o, (list, tuple)):\n",
|
| 119 |
+
" for i, v in enumerate(o): walk(v, f\"{pre}.{i}\" if pre else str(i))\n",
|
| 120 |
+
" else:\n",
|
| 121 |
+
" a = np.asarray(o)\n",
|
| 122 |
+
" if a.dtype != object: flat[_norm(pre)] = a\n",
|
| 123 |
+
" for k in z.files:\n",
|
| 124 |
+
" v = z[k]\n",
|
| 125 |
+
" walk(v.item() if v.dtype == object and v.ndim == 0 else v, k)\n",
|
| 126 |
+
" return flat\n",
|
| 127 |
+
"\n",
|
| 128 |
+
"def load_npz_into(model, path):\n",
|
| 129 |
+
" flat = _read_npz(path)\n",
|
| 130 |
+
" jax_name = lambda n: n.replace(\"a_ls\", \"a_gamma\").replace(\".ls\", \".gamma\") # modeldeki ls -> JAX'teki gamma\n",
|
| 131 |
+
" targets = {jax_name(n): n for n in model.state_dict()}\n",
|
| 132 |
+
" # her hedef için aday önekleri bul (örn. \"ema\", \"params\", \"state.ema\" …)\n",
|
| 133 |
+
" prefixes = None\n",
|
| 134 |
+
" for t in targets:\n",
|
| 135 |
+
" ps = {k[: -len(t)].rstrip(\".\") for k in flat if k == t or k.endswith(\".\" + t)}\n",
|
| 136 |
+
" prefixes = ps if prefixes is None else prefixes & ps\n",
|
| 137 |
+
" prefixes = sorted(prefixes or [])\n",
|
| 138 |
+
" if not prefixes:\n",
|
| 139 |
+
" sample = list(flat)[:8]\n",
|
| 140 |
+
" raise RuntimeError(f\"npz anahtarları modelle eşleşmedi. Örnek anahtarlar: {sample}\")\n",
|
| 141 |
+
" bad = (\"opt\", \"mu\", \"nu\", \"mom\", \"adam\", \"grad\")\n",
|
| 142 |
+
" def score(p):\n",
|
| 143 |
+
" low = p.lower()\n",
|
| 144 |
+
" return ((\"ema\" in low) * 4 + (\"param\" in low) * 2 - any(b in low.split(\".\") for b in bad) * 8)\n",
|
| 145 |
+
" best = max(prefixes, key=lambda p: (score(p), -len(p)))\n",
|
| 146 |
+
" print(f\"npz öneki: '{best}'\" + (f\" (diğer adaylar: {[p for p in prefixes if p != best]})\" if len(prefixes) > 1 else \"\"))\n",
|
| 147 |
+
" state = {}\n",
|
| 148 |
+
" for t, own in targets.items():\n",
|
| 149 |
+
" a = flat[f\"{best}.{t}\" if best else t]\n",
|
| 150 |
+
" want = tuple(model.state_dict()[own].shape)\n",
|
| 151 |
+
" if tuple(a.shape) != want:\n",
|
| 152 |
+
" raise RuntimeError(f\"şekil uyuşmuyor: {t}: npz {tuple(a.shape)} ≠ model {want}\")\n",
|
| 153 |
+
" state[own] = torch.from_numpy(np.ascontiguousarray(a)).float()\n",
|
| 154 |
+
" model.load_state_dict(state, strict=True)\n",
|
| 155 |
+
" return model\n",
|
| 156 |
+
"\n",
|
| 157 |
+
"npz_file = find_npz(NPZ_PATH)\n",
|
| 158 |
+
"print(\"ağırlıklar:\", npz_file)\n",
|
| 159 |
+
"model = load_npz_into(model, npz_file).to(device).eval()\n",
|
| 160 |
"print(f\"{sum(p.numel() for p in model.parameters()):,} parameters on {device}\")"
|
| 161 |
]
|
| 162 |
},
|
|
|
|
| 301 |
},
|
| 302 |
"nbformat": 4,
|
| 303 |
"nbformat_minor": 5
|
| 304 |
+
}
|