CompressedGemma commited on
Commit
5856b1d
·
verified ·
1 Parent(s): 786693e

Upload slimshard.py

Browse files
Files changed (1) hide show
  1. slimshard.py +546 -9
slimshard.py CHANGED
@@ -145,10 +145,95 @@ def _is_head_key(name: str) -> bool:
145
  return name in _HEAD_NAMES or name.endswith(("lm_head.weight", "embed_out.weight"))
146
 
147
 
148
- def infer_weight_map_from_shard(shard_path: str | Path, arch: dict) -> dict[str, str]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
  """Infer a full model ``weight_map`` when ``model.safetensors.index.json`` is absent."""
150
- shard_path = Path(shard_path)
151
- sh_name = shard_path.name
152
  num_layers = int(arch.get("num_hidden_layers", 0))
153
  num_experts = int(arch.get("num_experts") or 0)
154
  first_dense = int(arch.get("first_k_dense_replace", 0))
@@ -156,7 +241,7 @@ def infer_weight_map_from_shard(shard_path: str | Path, arch: dict) -> dict[str,
156
  mla_set = {int(x) - 1 for x in rda_cfg.get("mla_layers", [])}
157
  rda_set = {int(x) - 1 for x in rda_cfg.get("rda_layers", [])}
158
 
159
- with safe_open(str(shard_path), framework="pt", device="cpu") as f:
160
  present = sorted(f.keys())
161
 
162
  if num_layers <= 0:
@@ -1712,15 +1797,466 @@ def _is_router_gate_tensor(name: str, orig_experts: int, shape: tuple[int, ...])
1712
  ) and ".experts." not in name
1713
 
1714
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1715
  def inspect_recovery_plan(
1716
- shard: str | Path,
1717
  index: str | Path | None = None,
1718
  config: str | Path | None = None,
1719
  target_params_b: float | None = None,
1720
  max_experts: int | None = None,
 
1721
  ) -> dict:
1722
- """Inspect a shard + index/config and return a full CheckFree recovery plan for the GUI."""
1723
- shard_path = Path(shard)
 
1724
  cfg_path = Path(config) if config else shard_path.parent / "config.json"
1725
  if not cfg_path.exists() and index:
1726
  cfg_path = Path(index).parent / "config.json"
@@ -1731,9 +2267,10 @@ def inspect_recovery_plan(
1731
  if index_path.exists():
1732
  raw_weight_map: dict[str, str] = json.loads(index_path.read_text())["weight_map"]
1733
  else:
1734
- raw_weight_map = infer_weight_map_from_shard(shard_path, arch)
1735
 
1736
- with safe_open(str(shard_path), framework="pt", device="cpu") as f:
 
1737
  meta = f.metadata() or {}
1738
  is_slimshard = meta.get("format") == SHARD_FORMAT
1739
  present = set(f.keys())
 
145
  return name in _HEAD_NAMES or name.endswith(("lm_head.weight", "embed_out.weight"))
146
 
147
 
148
+ def _resolve_shard_paths(shard: str | Path | list[str | Path] | tuple[str | Path, ...]) -> list[Path]:
149
+ """Resolve one shard path, comma/semicolon-separated shard paths, or a directory into a list of Paths."""
150
+ if isinstance(shard, (list, tuple)):
151
+ raw_items = [str(x).strip() for x in shard if str(x).strip()]
152
+ else:
153
+ s = str(shard).strip()
154
+ if "," in s or ";" in s:
155
+ raw_items = [p.strip() for p in re.split(r"[,;]", s) if p.strip()]
156
+ else:
157
+ raw_items = [s] if s else []
158
+
159
+ out: list[Path] = []
160
+ seen: set[Path] = set()
161
+ for item in raw_items:
162
+ p = Path(item).expanduser()
163
+ if p.is_dir():
164
+ numbered = sorted(p.glob("model-*-of-*.safetensors"))
165
+ cands = numbered if numbered else [
166
+ f for f in sorted(p.glob("*.safetensors"))
167
+ if not f.name.endswith("-recovered.safetensors")
168
+ ]
169
+ for c in cands:
170
+ rp = c.resolve()
171
+ if rp not in seen and c.exists():
172
+ seen.add(rp)
173
+ out.append(c)
174
+ elif p.exists():
175
+ rp = p.resolve()
176
+ if rp not in seen:
177
+ seen.add(rp)
178
+ out.append(p)
179
+ if not out:
180
+ raise FileNotFoundError(f"No valid .safetensors shard found for: {shard!r}")
181
+ return out
182
+
183
+
184
+ class _MultiShardReader:
185
+ """Unified safe_open reader across one or multiple .safetensors shards."""
186
+
187
+ def __init__(
188
+ self,
189
+ shard_paths: str | Path | list[str | Path] | tuple[str | Path, ...],
190
+ anchor_layers: set[int] | None = None,
191
+ ) -> None:
192
+ self.shard_paths = _resolve_shard_paths(shard_paths)
193
+ self.anchor_layers = set(anchor_layers) if anchor_layers else None
194
+ self._handles = []
195
+ self._key_to_handle: dict[str, object] = {}
196
+ self.key_to_shard_name: dict[str, str] = {}
197
+ self._meta: dict[str, str] = {}
198
+
199
+ def __enter__(self) -> "_MultiShardReader":
200
+ for p in self.shard_paths:
201
+ h = safe_open(str(p), framework="pt", device="cpu")
202
+ self._handles.append(h)
203
+ m = h.metadata() or {}
204
+ for mk, mv in m.items():
205
+ self._meta.setdefault(mk, mv)
206
+ for k in h.keys():
207
+ if self.anchor_layers is not None:
208
+ lm = LAYER_RE.match(k)
209
+ if lm and int(lm.group(2)) not in self.anchor_layers:
210
+ continue
211
+ if k not in self._key_to_handle:
212
+ self._key_to_handle[k] = h
213
+ self.key_to_shard_name[k] = p.name
214
+ return self
215
+
216
+ def __exit__(self, exc_type, exc, tb) -> None:
217
+ self._handles.clear()
218
+ self._key_to_handle.clear()
219
+
220
+ def metadata(self) -> dict[str, str]:
221
+ return self._meta
222
+
223
+ def keys(self) -> list[str]:
224
+ return list(self._key_to_handle.keys())
225
+
226
+ def get_slice(self, name: str):
227
+ return self._key_to_handle[name].get_slice(name)
228
+
229
+ def get_tensor(self, name: str):
230
+ return self._key_to_handle[name].get_tensor(name)
231
+
232
+
233
+ def infer_weight_map_from_shard(shard_path: str | Path | list[str | Path], arch: dict) -> dict[str, str]:
234
  """Infer a full model ``weight_map`` when ``model.safetensors.index.json`` is absent."""
235
+ paths = _resolve_shard_paths(shard_path)
236
+ sh_name = paths[0].name
237
  num_layers = int(arch.get("num_hidden_layers", 0))
238
  num_experts = int(arch.get("num_experts") or 0)
239
  first_dense = int(arch.get("first_k_dense_replace", 0))
 
241
  mla_set = {int(x) - 1 for x in rda_cfg.get("mla_layers", [])}
242
  rda_set = {int(x) - 1 for x in rda_cfg.get("rda_layers", [])}
243
 
244
+ with _MultiShardReader(paths) as f:
245
  present = sorted(f.keys())
246
 
247
  if num_layers <= 0:
 
1797
  ) and ".experts." not in name
1798
 
1799
 
1800
+ def _parse_anchor_layers(anchor_layers: list[int] | set[int] | str | None) -> set[int] | None:
1801
+ """Parse optional anchor layer specification (e.g. ``'0,4,20,39'`` or ``[0, 4, 20, 39]``)."""
1802
+ if anchor_layers is None:
1803
+ return None
1804
+ if isinstance(anchor_layers, (set, list, tuple)):
1805
+ out = {int(x) for x in anchor_layers}
1806
+ return out if out else None
1807
+ s = str(anchor_layers).strip()
1808
+ if not s:
1809
+ return None
1810
+ out: set[int] = set()
1811
+ for part in re.split(r"[,;\s]+", s):
1812
+ part = part.strip()
1813
+ if not part:
1814
+ continue
1815
+ if "-" in part and not part.startswith("-"):
1816
+ a_str, b_str = part.split("-", 1)
1817
+ for v in range(int(a_str), int(b_str) + 1):
1818
+ out.add(v)
1819
+ else:
1820
+ out.add(int(part))
1821
+ return out if out else None
1822
+
1823
+
1824
+ def parse_hf_repo_url(url_or_repo: str) -> tuple[str, str]:
1825
+ """Parse a Hugging Face repo URL or ``org/repo`` string into ``(repo_id, revision)``.
1826
+
1827
+ Examples::
1828
+
1829
+ https://huggingface.co/deepseek-ai/DeepSeek-V4-Pro/tree/main -> ('deepseek-ai/DeepSeek-V4-Pro', 'main')
1830
+ https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash-1017 -> ('deepseek-ai/DeepSeek-V4.1-Flash-1017', 'main')
1831
+ deepseek-ai/DeepSeek-V4-Pro -> ('deepseek-ai/DeepSeek-V4-Pro', 'main')
1832
+ """
1833
+ s = str(url_or_repo).strip()
1834
+ s = re.sub(r"^https?://(www\.)?huggingface\.co/", "", s)
1835
+ s = re.sub(r"^hf\.co/", "", s)
1836
+ s = s.strip("/")
1837
+ parts = [p for p in s.split("/") if p]
1838
+ if len(parts) < 2:
1839
+ raise ValueError(
1840
+ f"Invalid Hugging Face link or repo ID: {url_or_repo!r} (expected 'org/repo' or 'https://huggingface.co/org/repo/tree/main')"
1841
+ )
1842
+ repo_id = f"{parts[0]}/{parts[1]}"
1843
+ revision = "main"
1844
+ if len(parts) >= 4 and parts[2] in ("tree", "blob", "resolve"):
1845
+ revision = parts[3]
1846
+ return repo_id, revision
1847
+
1848
+
1849
+ def _hf_resolve_url(repo_id: str, revision: str, filename: str) -> str:
1850
+ return f"https://huggingface.co/{repo_id}/resolve/{revision}/{filename.lstrip('/')}"
1851
+
1852
+
1853
+ def _http_get_bytes(url: str, byte_range: tuple[int, int] | None = None, timeout: int = 120) -> bytes:
1854
+ import urllib.request
1855
+
1856
+ headers = {"User-Agent": "HPC-Quantize-SlimShard/2.0"}
1857
+ token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
1858
+ if token:
1859
+ headers["Authorization"] = f"Bearer {token}"
1860
+ if byte_range is not None:
1861
+ headers["Range"] = f"bytes={byte_range[0]}-{byte_range[1]}"
1862
+ req = urllib.request.Request(url, headers=headers)
1863
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
1864
+ return resp.read()
1865
+
1866
+
1867
+ def plan_minimum_shards_from_hf(
1868
+ url_or_repo: str,
1869
+ target_params_b: float | None = None,
1870
+ max_experts: int | None = None,
1871
+ num_anchor_layers: int = 3,
1872
+ anchor_layers: list[int] | set[int] | str | None = None,
1873
+ ) -> dict:
1874
+ """Analyze a Hugging Face repo link and determine the minimum shards & anchor layers needed for full reconstruction."""
1875
+ repo_id, revision = parse_hf_repo_url(url_or_repo)
1876
+ cfg_bytes = _http_get_bytes(_hf_resolve_url(repo_id, revision, "config.json"))
1877
+ raw_cfg = json.loads(cfg_bytes.decode("utf-8"))
1878
+ arch = _normalize_arch_config(raw_cfg)
1879
+
1880
+ try:
1881
+ idx_bytes = _http_get_bytes(_hf_resolve_url(repo_id, revision, "model.safetensors.index.json"))
1882
+ idx_obj = json.loads(idx_bytes.decode("utf-8"))
1883
+ raw_weight_map: dict[str, str] = idx_obj.get("weight_map", {})
1884
+ total_size_bytes = int(idx_obj.get("metadata", {}).get("total_size", 0))
1885
+ except Exception:
1886
+ raw_weight_map = {"model.embed_tokens.weight": "model.safetensors", "lm_head.weight": "model.safetensors"}
1887
+ total_size_bytes = 0
1888
+
1889
+ all_repo_shards = sorted(set(raw_weight_map.values()))
1890
+ # Strip optional vision/engram/mtp branches and prune experts to target budget
1891
+ filtered_wm, kept_experts, est_params_b = _filter_weight_map_for_target(
1892
+ raw_weight_map, set(), arch, target_params_b=target_params_b, max_experts=max_experts
1893
+ )
1894
+
1895
+ total_layers = int(arch.get("num_hidden_layers") or 0)
1896
+ layer_to_shards: dict[int, set[str]] = {}
1897
+ shard_to_layers: dict[str, set[int]] = {}
1898
+ for k, sh in filtered_wm.items():
1899
+ lm = LAYER_RE.match(k)
1900
+ if lm:
1901
+ lidx = int(lm.group(2))
1902
+ layer_to_shards.setdefault(lidx, set()).add(sh)
1903
+ shard_to_layers.setdefault(sh, set()).add(lidx)
1904
+ if total_layers <= 0 and layer_to_shards:
1905
+ total_layers = max(layer_to_shards) + 1
1906
+
1907
+ selected_shards: list[str] = []
1908
+ shard_roles: dict[str, list[str]] = {}
1909
+
1910
+ def _add_shard(sh: str, reason: str) -> None:
1911
+ if sh not in selected_shards:
1912
+ selected_shards.append(sh)
1913
+ roles = shard_roles.setdefault(sh, [])
1914
+ if reason not in roles:
1915
+ roles.append(reason)
1916
+
1917
+ # 1. Input embeddings + Output LM head + Final Norm + Output HC
1918
+ for k, sh in filtered_wm.items():
1919
+ if _is_embed_key(k):
1920
+ _add_shard(sh, f"Embedding ({k})")
1921
+ elif _is_head_key(k):
1922
+ _add_shard(sh, f"LM Head ({k})")
1923
+ elif k in _NORM_NAMES or (not LAYER_RE.match(k) and ("norm" in k or "hc_" in k)):
1924
+ _add_shard(sh, f"Final Norm/Head ({k})")
1925
+
1926
+ # 2. Choose multi-layer depth anchors across [0 .. total_layers - 1]
1927
+ explicit_anchors = _parse_anchor_layers(anchor_layers)
1928
+ first_dense = int(arch.get("first_k_dense_replace", 0))
1929
+ if explicit_anchors:
1930
+ target_anchors = sorted(l for l in explicit_anchors if l in layer_to_shards)
1931
+ else:
1932
+ n_anc = max(1, int(num_anchor_layers))
1933
+ already_layers = sorted(
1934
+ {
1935
+ l
1936
+ for sh in selected_shards
1937
+ for l in shard_to_layers.get(sh, set())
1938
+ if l >= first_dense
1939
+ }
1940
+ )
1941
+ target_anchors = []
1942
+ if first_dense > 0 and 0 in layer_to_shards:
1943
+ target_anchors.append(0)
1944
+ moe_start = min(first_dense, max(total_layers - 1, 0))
1945
+ if total_layers > 0:
1946
+ grid = np.linspace(moe_start, max(total_layers - 1, moe_start), max(n_anc, 2), dtype=int).tolist()
1947
+ for g_l in grid:
1948
+ # Prefer a nearby layer that lives in a single shard or already-selected shard
1949
+ best_l = int(g_l)
1950
+ best_cost = (999, 999)
1951
+ for cand_l in range(max(moe_start, int(g_l) - 3), min(total_layers, int(g_l) + 4)):
1952
+ if cand_l not in layer_to_shards:
1953
+ continue
1954
+ shs = layer_to_shards[cand_l]
1955
+ new_shs = len([s for s in shs if s not in selected_shards])
1956
+ cost = (new_shs, abs(cand_l - int(g_l)))
1957
+ if cost < best_cost:
1958
+ best_cost = cost
1959
+ best_l = cand_l
1960
+ if best_l not in target_anchors:
1961
+ target_anchors.append(best_l)
1962
+ for al in already_layers:
1963
+ if len(target_anchors) < n_anc and al not in target_anchors:
1964
+ target_anchors.append(al)
1965
+ target_anchors.sort()
1966
+
1967
+ for lidx in target_anchors:
1968
+ for sh in sorted(layer_to_shards.get(lidx, set())):
1969
+ _add_shard(sh, f"Anchor Layer {lidx}")
1970
+
1971
+ # 3. Ensure every non-layer and layer template suffix in filtered_wm has at least one anchor in selected_shards
1972
+ covered_keys = {k for k, sh in filtered_wm.items() if sh in selected_shards}
1973
+ covered_suffixes = {LAYER_RE.match(k).group(3) for k in covered_keys if LAYER_RE.match(k)}
1974
+ covered_exp_projs = {
1975
+ (EXPERT_RE.match(k).group(4), EXPERT_RE.match(k).group(5), EXPERT_RE.match(k).group(6))
1976
+ for k in covered_keys
1977
+ if EXPERT_RE.match(k)
1978
+ }
1979
+ for k, sh in filtered_wm.items():
1980
+ em = EXPERT_RE.match(k)
1981
+ if em:
1982
+ sig = (em.group(4), em.group(5), em.group(6))
1983
+ if sig not in covered_exp_projs:
1984
+ _add_shard(sh, f"Expert template e={em.group(4)}")
1985
+ covered_exp_projs.add(sig)
1986
+ continue
1987
+ lm = LAYER_RE.match(k)
1988
+ if lm:
1989
+ suf = lm.group(3)
1990
+ if suf not in covered_suffixes:
1991
+ _add_shard(sh, f"Layer template ({suf})")
1992
+ covered_suffixes.add(suf)
1993
+
1994
+ # Compute exact surgical tensors needed from selected_shards
1995
+ anchor_set = set(target_anchors)
1996
+ surgical_tensors: dict[str, str] = {}
1997
+ for k, sh in filtered_wm.items():
1998
+ if sh not in selected_shards:
1999
+ continue
2000
+ lm = LAYER_RE.match(k)
2001
+ if lm:
2002
+ if int(lm.group(2)) in anchor_set:
2003
+ surgical_tensors[k] = sh
2004
+ else:
2005
+ surgical_tensors[k] = sh
2006
+
2007
+ return {
2008
+ "repo_id": repo_id,
2009
+ "revision": revision,
2010
+ "model_type": arch.get("model_type", "unknown"),
2011
+ "architectures": arch.get("architectures", []),
2012
+ "num_hidden_layers": total_layers,
2013
+ "orig_num_experts": int(arch.get("num_experts") or 0),
2014
+ "kept_experts": kept_experts if kept_experts is not None else int(arch.get("num_experts") or 0),
2015
+ "estimated_params_b": round(est_params_b, 2),
2016
+ "total_repo_shards": len(all_repo_shards),
2017
+ "total_repo_size_gb": round(total_size_bytes / 1.0e9, 2) if total_size_bytes else 0.0,
2018
+ "minimum_shards": selected_shards,
2019
+ "shard_roles": shard_roles,
2020
+ "anchor_layers": target_anchors,
2021
+ "surgical_tensor_count": len(surgical_tensors),
2022
+ "surgical_tensors": surgical_tensors,
2023
+ "raw_config": raw_cfg,
2024
+ "raw_index": {"metadata": {"total_size": total_size_bytes}, "weight_map": raw_weight_map},
2025
+ }
2026
+
2027
+
2028
+ def fetch_minimum_shards_from_hf(
2029
+ url_or_repo: str,
2030
+ output_dir: str | Path,
2031
+ target_params_b: float | None = None,
2032
+ max_experts: int | None = None,
2033
+ num_anchor_layers: int = 3,
2034
+ anchor_layers: list[int] | set[int] | str | None = None,
2035
+ mode: str = "surgical",
2036
+ verbose: bool = True,
2037
+ progress_cb=None,
2038
+ stop_event=None,
2039
+ ) -> dict:
2040
+ """Retrieve the minimum shards (or surgical HTTP-Range seed shard) from a Hugging Face link.
2041
+
2042
+ * ``mode='surgical'`` (default): Uses HTTP Range requests to download only
2043
+ ``embed_tokens``, ``lm_head``, ``norm``, and the selected multi-layer
2044
+ anchors (with ``kept_experts`` experts) from the minimum shards into
2045
+ ``<output_dir>/minimal_seed.safetensors``.
2046
+ * ``mode='full_shards'``: Downloads the complete ``.safetensors`` files for
2047
+ the minimum shard set into ``<output_dir>/``.
2048
+ """
2049
+ out_dir = Path(output_dir).expanduser().resolve()
2050
+ out_dir.mkdir(parents=True, exist_ok=True)
2051
+
2052
+ plan = plan_minimum_shards_from_hf(
2053
+ url_or_repo,
2054
+ target_params_b=target_params_b,
2055
+ max_experts=max_experts,
2056
+ num_anchor_layers=num_anchor_layers,
2057
+ anchor_layers=anchor_layers,
2058
+ )
2059
+ repo_id = plan["repo_id"]
2060
+ revision = plan["revision"]
2061
+
2062
+ # 1. Save config.json, model.safetensors.index.json, and companion tokenizer files
2063
+ (out_dir / "config.json").write_text(json.dumps(plan["raw_config"], indent=2))
2064
+ (out_dir / "model.safetensors.index.json").write_text(json.dumps(plan["raw_index"], indent=2))
2065
+ for aux in ("tokenizer.json", "tokenizer_config.json", "chat_template.jinja", "special_tokens_map.json"):
2066
+ dst = out_dir / aux
2067
+ if dst.exists() and dst.stat().st_size > 0:
2068
+ continue
2069
+ try:
2070
+ raw_aux = _http_get_bytes(_hf_resolve_url(repo_id, revision, aux), timeout=60)
2071
+ dst.write_bytes(raw_aux)
2072
+ except Exception:
2073
+ pass
2074
+
2075
+ min_shards: list[str] = plan["minimum_shards"]
2076
+ stats = {
2077
+ "repo_id": repo_id,
2078
+ "minimum_shards": min_shards,
2079
+ "total_repo_shards": plan["total_repo_shards"],
2080
+ "anchor_layers": plan["anchor_layers"],
2081
+ "bytes_downloaded": 0,
2082
+ "tensors_fetched": 0,
2083
+ "shard_paths": [],
2084
+ }
2085
+
2086
+ if mode == "full_shards":
2087
+ import urllib.request
2088
+
2089
+ total_sh = len(min_shards)
2090
+ downloaded_paths: list[str] = []
2091
+ for idx_s, sh_name in enumerate(min_shards, 1):
2092
+ if stop_event is not None and stop_event.is_set():
2093
+ raise InterruptedError("Download cancelled by user.")
2094
+ dst_sh = out_dir / sh_name
2095
+ url = _hf_resolve_url(repo_id, revision, sh_name)
2096
+ headers = {"User-Agent": "HPC-Quantize-SlimShard/2.0"}
2097
+ token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
2098
+ if token:
2099
+ headers["Authorization"] = f"Bearer {token}"
2100
+ req = urllib.request.Request(url, headers=headers)
2101
+ with urllib.request.urlopen(req, timeout=300) as resp, dst_sh.open("wb") as fw:
2102
+ while True:
2103
+ if stop_event is not None and stop_event.is_set():
2104
+ raise InterruptedError("Download cancelled by user.")
2105
+ chunk = resp.read(4 * 1024 * 1024)
2106
+ if not chunk:
2107
+ break
2108
+ fw.write(chunk)
2109
+ stats["bytes_downloaded"] += len(chunk)
2110
+ if progress_cb is not None:
2111
+ progress_cb(
2112
+ idx_s - 1,
2113
+ total_sh,
2114
+ f"{sh_name} ({stats['bytes_downloaded'] / 1e9:.2f} GB)",
2115
+ "DOWNLOAD_SHARD",
2116
+ {"present": idx_s, "checkfree_interpolated": 0, "expert_interpolated": 0, "synthesized": 0},
2117
+ )
2118
+ downloaded_paths.append(str(dst_sh))
2119
+ if progress_cb is not None:
2120
+ progress_cb(
2121
+ idx_s,
2122
+ total_sh,
2123
+ sh_name,
2124
+ "DOWNLOAD_SHARD",
2125
+ {"present": idx_s, "checkfree_interpolated": 0, "expert_interpolated": 0, "synthesized": 0},
2126
+ )
2127
+ stats["shard_paths"] = downloaded_paths
2128
+ return stats
2129
+
2130
+ # Surgical HTTP-Range mode: fetch headers for each minimum shard, then range-fetch required tensors
2131
+ surgical_map: dict[str, str] = plan["surgical_tensors"]
2132
+ by_shard: dict[str, list[str]] = {}
2133
+ for tname, sh_name in surgical_map.items():
2134
+ by_shard.setdefault(sh_name, []).append(tname)
2135
+
2136
+ seed_path = out_dir / "minimal_seed.safetensors"
2137
+ writer = SafetensorsWriter(
2138
+ seed_path,
2139
+ metadata={
2140
+ "format": "pt",
2141
+ "hpc_source_repo": repo_id,
2142
+ "hpc_minimum_shards": ",".join(min_shards),
2143
+ "hpc_anchor_layers": ",".join(str(x) for x in plan["anchor_layers"]),
2144
+ },
2145
+ )
2146
+
2147
+ total_t = len(surgical_map)
2148
+ done_t = 0
2149
+ try:
2150
+ for sh_name in min_shards:
2151
+ t_list = by_shard.get(sh_name, [])
2152
+ if not t_list:
2153
+ continue
2154
+ local_sh = out_dir / sh_name
2155
+ if local_sh.exists():
2156
+ with safe_open(str(local_sh), framework="pt", device="cpu") as lf:
2157
+ lkeys = set(lf.keys())
2158
+ for tname in t_list:
2159
+ if stop_event is not None and stop_event.is_set():
2160
+ raise InterruptedError("Download cancelled by user.")
2161
+ if tname in lkeys:
2162
+ t = lf.get_tensor(tname)
2163
+ sl = lf.get_slice(tname)
2164
+ writer.add(tname, _payload_bytes(t), _safetensors_dtype(sl.get_dtype()), tuple(t.shape))
2165
+ done_t += 1
2166
+ stats["tensors_fetched"] += 1
2167
+ if progress_cb is not None and (done_t % 8 == 0 or done_t == total_t):
2168
+ progress_cb(
2169
+ done_t,
2170
+ total_t,
2171
+ tname,
2172
+ "LOCAL_SHARD_HIT",
2173
+ {"present": done_t, "checkfree_interpolated": 0, "expert_interpolated": 0, "synthesized": 0},
2174
+ )
2175
+ continue
2176
+
2177
+ url = _hf_resolve_url(repo_id, revision, sh_name)
2178
+ hdr_len_b = _http_get_bytes(url, byte_range=(0, 7), timeout=60)
2179
+ hdr_len = struct.unpack("<Q", hdr_len_b)[0]
2180
+ hdr_json_b = _http_get_bytes(url, byte_range=(8, 8 + hdr_len - 1), timeout=120)
2181
+ sh_hdr = json.loads(hdr_json_b.decode("utf-8"))
2182
+ data_base = 8 + hdr_len
2183
+
2184
+ # Sort tensors by file offset and coalesce adjacent byte ranges (up to 32 MB) for fast HTTP streaming
2185
+ req_items = []
2186
+ for tname in t_list:
2187
+ if tname not in sh_hdr:
2188
+ continue
2189
+ info = sh_hdr[tname]
2190
+ ofs = info["data_offsets"]
2191
+ req_items.append((int(ofs[0]), int(ofs[1]), tname, info["dtype"], tuple(int(x) for x in info["shape"])))
2192
+ req_items.sort(key=lambda x: x[0])
2193
+
2194
+ batches: list[list[tuple[int, int, str, str, tuple[int, ...]]]] = []
2195
+ for item in req_items:
2196
+ if (
2197
+ batches
2198
+ and item[0] == batches[-1][-1][1]
2199
+ and (item[1] - batches[-1][0][0]) <= 32 * 1024 * 1024
2200
+ ):
2201
+ batches[-1].append(item)
2202
+ else:
2203
+ batches.append([item])
2204
+
2205
+ for batch in batches:
2206
+ if stop_event is not None and stop_event.is_set():
2207
+ raise InterruptedError("Download cancelled by user.")
2208
+ b_start = data_base + batch[0][0]
2209
+ b_end = data_base + batch[-1][1] - 1
2210
+ if progress_cb is not None:
2211
+ progress_cb(
2212
+ done_t,
2213
+ total_t,
2214
+ f"{batch[0][2]} ({sh_name})",
2215
+ f"HTTP_RANGE ({(b_end - b_start + 1) / 1e6:.1f} MB)",
2216
+ {"present": done_t, "checkfree_interpolated": 0, "expert_interpolated": 0, "synthesized": 0},
2217
+ )
2218
+ blob = _http_get_bytes(url, byte_range=(b_start, b_end), timeout=600)
2219
+ stats["bytes_downloaded"] += len(blob)
2220
+ base_rel = batch[0][0]
2221
+ for s_off, e_off, tname, dt_str, shp in batch:
2222
+ sub = blob[s_off - base_rel : e_off - base_rel]
2223
+ writer.add(tname, sub, dt_str, shp)
2224
+ done_t += 1
2225
+ stats["tensors_fetched"] += 1
2226
+ if progress_cb is not None:
2227
+ progress_cb(
2228
+ done_t,
2229
+ total_t,
2230
+ batch[-1][2],
2231
+ "HTTP_RANGE_OK",
2232
+ {"present": done_t, "checkfree_interpolated": 0, "expert_interpolated": 0, "synthesized": 0},
2233
+ )
2234
+ except Exception:
2235
+ writer.close()
2236
+ raise
2237
+
2238
+ writer.close()
2239
+ stats["shard_paths"] = [str(seed_path)]
2240
+ if verbose:
2241
+ print(
2242
+ f"Fetched surgical seed shard -> {seed_path} "
2243
+ f"({stats['tensors_fetched']} tensors from {len(min_shards)}/{plan['total_repo_shards']} shards, "
2244
+ f"{stats['bytes_downloaded'] / 1e9:.2f} GB downloaded)"
2245
+ )
2246
+ return stats
2247
+
2248
+
2249
  def inspect_recovery_plan(
2250
+ shard: str | Path | list[str | Path],
2251
  index: str | Path | None = None,
2252
  config: str | Path | None = None,
2253
  target_params_b: float | None = None,
2254
  max_experts: int | None = None,
2255
+ anchor_layers: list[int] | set[int] | str | None = None,
2256
  ) -> dict:
2257
+ """Inspect one or more shards + index/config and return a full CheckFree recovery plan for the GUI."""
2258
+ shard_paths = _resolve_shard_paths(shard)
2259
+ shard_path = shard_paths[0]
2260
  cfg_path = Path(config) if config else shard_path.parent / "config.json"
2261
  if not cfg_path.exists() and index:
2262
  cfg_path = Path(index).parent / "config.json"
 
2267
  if index_path.exists():
2268
  raw_weight_map: dict[str, str] = json.loads(index_path.read_text())["weight_map"]
2269
  else:
2270
+ raw_weight_map = infer_weight_map_from_shard(shard_paths, arch)
2271
 
2272
+ parsed_anchors = _parse_anchor_layers(anchor_layers)
2273
+ with _MultiShardReader(shard_paths, anchor_layers=parsed_anchors) as f:
2274
  meta = f.metadata() or {}
2275
  is_slimshard = meta.get("format") == SHARD_FORMAT
2276
  present = set(f.keys())