omurberaisik commited on
Commit
5a63d3b
·
verified ·
1 Parent(s): d51097a

Upload notebook.ipynb

Browse files
Files changed (1) hide show
  1. notebook.ipynb +45 -4
notebook.ipynb CHANGED
@@ -45,8 +45,10 @@
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
  {
@@ -125,6 +127,46 @@
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",
@@ -136,8 +178,7 @@
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",
 
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
+ "\n",
49
+ "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",
50
+ "\n",
51
+ "The `HF_TOKEN` warnings are harmless for public repos."
52
  ]
53
  },
54
  {
 
127
  " walk(v.item() if v.dtype == object and v.ndim == 0 else v, k)\n",
128
  " return flat\n",
129
  "\n",
130
+ "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",
131
+ "\n",
132
+ "def _to_f32(a):\n",
133
+ " if a.dtype.kind == \"V\" and a.dtype.itemsize == 2: # bfloat16 ham baytlar\n",
134
+ " a = (a.view(np.uint16).astype(np.uint32) << 16).view(np.float32)\n",
135
+ " return np.ascontiguousarray(a, dtype=np.float32)\n",
136
+ "\n",
137
+ "def _load_positional(model, flat, targets):\n",
138
+ " \"\"\"JAX `tree_leaves` sırasıyla (sözlük anahtarları alfabetik, listeler sırayla) kaydedilmiş checkpoint.\"\"\"\n",
139
+ " skey = lambda n: tuple((0, int(p)) if p.isdigit() else (1, p) for p in n.split(\".\"))\n",
140
+ " order = sorted(targets, key=skey) # beklenen yaprak sırası (JAX adlarıyla)\n",
141
+ " want = [tuple(model.state_dict()[targets[t]].shape) for t in order]\n",
142
+ " keys = sorted(flat, key=lambda k: int(re.sub(r\"\\D\", \"\", k) or 0))\n",
143
+ " arrs = [flat[k] for k in keys]\n",
144
+ " shapes = [tuple(a.shape) for a in arrs]\n",
145
+ " n = len(order)\n",
146
+ " starts = [i for i in range(len(arrs) - n + 1) if shapes[i:i + n] == want]\n",
147
+ " if not starts:\n",
148
+ " raise RuntimeError(f\"npz içinde {n} yapraklık, modele uyan bir ağırlık dizisi bulunamadı \"\n",
149
+ " f\"(npz'de {len(arrs)} dizi var; ilk şekiller: {shapes[:6]}).\")\n",
150
+ " def stats(i):\n",
151
+ " g = [_to_f32(arrs[i + j]) for j, t in enumerate(order) if t.endswith(\"ln_g\")]\n",
152
+ " b = [_to_f32(arrs[i + j]) for j, t in enumerate(order) if t.endswith(\"ln_b\")]\n",
153
+ " return float(np.mean([x.mean() for x in g])), float(np.mean([np.abs(x).mean() for x in b]))\n",
154
+ " good = [i for i in starts if stats(i)[0] > 0.3] # optimizer momentleri: LN gain ≈ 1 olmaz\n",
155
+ " cands = good or starts\n",
156
+ " print(f\"adsız npz ({len(arrs)} dizi): {len(cands)} tam ağırlık seti bulundu, başlangıç indeksleri {cands}\")\n",
157
+ " if len(cands) > 1:\n",
158
+ " d = np.mean([np.abs(_to_f32(arrs[cands[0] + j]) - _to_f32(arrs[cands[1] + j])).mean() for j in range(n)])\n",
159
+ " print(f\" (ilk iki set arası ort. mutlak fark: {d:.2e} — biri EMA, diğeri ham parametre olabilir; \"\n",
160
+ " f\"değiştirmek için WEIGHT_PICK / NTLM_PICK ayarlayın)\")\n",
161
+ " start = cands[min(WEIGHT_PICK, len(cands) - 1)]\n",
162
+ " g, b = stats(start)\n",
163
+ " print(f\" kullanılan set: indeks {start} (LN gain ort. {g:.2f}, LN bias ort. |.| {b:.3f})\")\n",
164
+ " if not 0.3 < g < 3.0:\n",
165
+ " print(\" UYARI: LayerNorm değerleri beklenenden farklı — yanlış set seçilmiş olabilir.\")\n",
166
+ " state = {targets[t]: torch.from_numpy(_to_f32(arrs[start + j])) for j, t in enumerate(order)}\n",
167
+ " model.load_state_dict(state, strict=True)\n",
168
+ " return model\n",
169
+ "\n",
170
  "def load_npz_into(model, path):\n",
171
  " flat = _read_npz(path)\n",
172
  " jax_name = lambda n: n.replace(\"a_ls\", \"a_gamma\").replace(\".ls\", \".gamma\") # modeldeki ls -> JAX'teki gamma\n",
 
178
  " prefixes = ps if prefixes is None else prefixes & ps\n",
179
  " prefixes = sorted(prefixes or [])\n",
180
  " if not prefixes:\n",
181
+ " return _load_positional(model, flat, targets) # a00000, a00001, … gibi adsız anahtarlar\n",
 
182
  " bad = (\"opt\", \"mu\", \"nu\", \"mom\", \"adam\", \"grad\")\n",
183
  " def score(p):\n",
184
  " low = p.lower()\n",