Delete slimshard_gui.py
Browse files- slimshard_gui.py +0 -1423
slimshard_gui.py
DELETED
|
@@ -1,1423 +0,0 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
"""Graphical User Interface for HPC-Quantize V2 SlimShard & CheckFree Recovery.
|
| 3 |
-
|
| 4 |
-
Launch::
|
| 5 |
-
|
| 6 |
-
python3 -m hpc_quantize_v2.slimshard gui
|
| 7 |
-
# or:
|
| 8 |
-
python3 -m hpc_quantize_v2.slimshard_gui
|
| 9 |
-
|
| 10 |
-
Supports any Hugging Face safetensors model architecture (Llama, Qwen2/3,
|
| 11 |
-
Mistral, Mixtral, DeepSeek, Gemma, Phi, GPT-NeoX, Raon, etc.):
|
| 12 |
-
|
| 13 |
-
1. **CheckFree Single-Shard Recovery (`recover`)**:
|
| 14 |
-
Reconstructs a complete runnable HF model from a single surviving
|
| 15 |
-
``.safetensors`` shard (with optional ``model.safetensors.index.json`` and
|
| 16 |
-
``config.json``), using CheckFree depth interpolation, per-expert MXFP8/FP16
|
| 17 |
-
interpolation, and causal forward-calibrated embedding/LM-head synthesis.
|
| 18 |
-
2. **SlimShard Compression (`build`)**:
|
| 19 |
-
Compresses any multi-shard HF model into a single self-contained SlimShard
|
| 20 |
-
(``mixed``, ``q2_k``, ``q4_0``, or ``exact`` + SlimMoE expert clustering).
|
| 21 |
-
3. **SlimShard Regeneration (`regenerate`)**:
|
| 22 |
-
Restores a standard HF ``.safetensors`` checkpoint from a SlimShard file.
|
| 23 |
-
4. **Live Model Prompt Tester**:
|
| 24 |
-
Runs any prompt (raw or chat-templated) on the recovered model directly
|
| 25 |
-
inside the GUI.
|
| 26 |
-
"""
|
| 27 |
-
|
| 28 |
-
from __future__ import annotations
|
| 29 |
-
|
| 30 |
-
import datetime as dt
|
| 31 |
-
import queue
|
| 32 |
-
import shlex
|
| 33 |
-
import sys
|
| 34 |
-
import threading
|
| 35 |
-
import time
|
| 36 |
-
import tkinter as tk
|
| 37 |
-
from pathlib import Path
|
| 38 |
-
from tkinter import filedialog, messagebox, ttk
|
| 39 |
-
|
| 40 |
-
import numpy as np
|
| 41 |
-
|
| 42 |
-
if __package__ in (None, ""):
|
| 43 |
-
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
| 44 |
-
__package__ = "hpc_quantize_v2"
|
| 45 |
-
|
| 46 |
-
from .cuda_backend import cuda_device_name, cuda_is_available
|
| 47 |
-
from .slimshard import (
|
| 48 |
-
HPCConfig,
|
| 49 |
-
_resolve_shard_paths,
|
| 50 |
-
build_slimshard,
|
| 51 |
-
export_hf_bundle,
|
| 52 |
-
export_safetensors_to_gguf,
|
| 53 |
-
fetch_minimum_shards_from_hf,
|
| 54 |
-
inspect_recovery_plan,
|
| 55 |
-
parse_hf_repo_url,
|
| 56 |
-
plan_minimum_shards_from_hf,
|
| 57 |
-
recover_from_shard,
|
| 58 |
-
regenerate,
|
| 59 |
-
run_deepseek_v41_generate,
|
| 60 |
-
slimshard_info,
|
| 61 |
-
)
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
def _ts() -> str:
|
| 65 |
-
return dt.datetime.now().strftime("%H:%M:%S.%f")[:-3]
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
def _fmt_eta(seconds: float) -> str:
|
| 69 |
-
if not np.isfinite(seconds) or seconds <= 0.0:
|
| 70 |
-
return "0s"
|
| 71 |
-
s = int(round(seconds))
|
| 72 |
-
if s < 60:
|
| 73 |
-
return f"{seconds:.1f}s"
|
| 74 |
-
m, sec = divmod(s, 60)
|
| 75 |
-
if m < 60:
|
| 76 |
-
return f"{m}m{sec:02d}s"
|
| 77 |
-
h, m = divmod(m, 60)
|
| 78 |
-
return f"{h}h{m:02d}m{sec:02d}s"
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
class SlimShardGUI:
|
| 82 |
-
def __init__(self, root: tk.Tk | tk.Toplevel) -> None:
|
| 83 |
-
self.root = root
|
| 84 |
-
self.root.title(
|
| 85 |
-
"HPC-Quantize V2 — SlimShard & CheckFree Universal Single-Shard LLM Recovery"
|
| 86 |
-
)
|
| 87 |
-
self.root.geometry("1280x920")
|
| 88 |
-
self.root.minsize(1040, 740)
|
| 89 |
-
|
| 90 |
-
self._queue: queue.Queue[tuple[str, object]] = queue.Queue()
|
| 91 |
-
self._stop_event = threading.Event()
|
| 92 |
-
self._worker: threading.Thread | None = None
|
| 93 |
-
self._start_time: float | None = None
|
| 94 |
-
self._plan_rows: list[dict] = []
|
| 95 |
-
|
| 96 |
-
self._init_vars()
|
| 97 |
-
self._apply_theme()
|
| 98 |
-
self._build_layout()
|
| 99 |
-
self._auto_populate_defaults()
|
| 100 |
-
self._update_cli_preview()
|
| 101 |
-
self.root.after(80, self._poll_queue)
|
| 102 |
-
|
| 103 |
-
def _init_vars(self) -> None:
|
| 104 |
-
self.op_mode_var = tk.StringVar(value="recover")
|
| 105 |
-
self.hf_url_var = tk.StringVar(
|
| 106 |
-
value="https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash-1017/tree/main"
|
| 107 |
-
)
|
| 108 |
-
self.hf_fetch_mode_var = tk.StringVar(value="surgical")
|
| 109 |
-
self.num_anchor_layers_var = tk.IntVar(value=3)
|
| 110 |
-
self.anchor_layers_var = tk.StringVar(value="")
|
| 111 |
-
self.shard_var = tk.StringVar()
|
| 112 |
-
self.index_var = tk.StringVar()
|
| 113 |
-
self.config_var = tk.StringVar()
|
| 114 |
-
self.model_dir_var = tk.StringVar()
|
| 115 |
-
self.output_var = tk.StringVar()
|
| 116 |
-
self.export_dir_var = tk.StringVar()
|
| 117 |
-
self.auto_bundle_var = tk.BooleanVar(value=True)
|
| 118 |
-
|
| 119 |
-
self.device_var = tk.StringVar(value="auto")
|
| 120 |
-
self.quant_format_var = tk.StringVar(value="mixed")
|
| 121 |
-
self.expert_keep_var = tk.DoubleVar(value=1.0)
|
| 122 |
-
self.target_params_b_var = tk.DoubleVar(value=30.0)
|
| 123 |
-
self.max_experts_var = tk.IntVar(value=0)
|
| 124 |
-
|
| 125 |
-
self.filter_action_var = tk.StringVar(value="ALL")
|
| 126 |
-
self.search_var = tk.StringVar()
|
| 127 |
-
|
| 128 |
-
# Live telemetry variables
|
| 129 |
-
self.arch_summary_var = tk.StringVar(value="No shard inspected yet.")
|
| 130 |
-
self.layers_summary_var = tk.StringVar(value="Surviving layers: -- | Missing layers: --")
|
| 131 |
-
self.tele_tensor_var = tk.StringVar(value="Idle")
|
| 132 |
-
self.tele_action_var = tk.StringVar(value="Waiting")
|
| 133 |
-
self.tele_progress_text_var = tk.StringVar(value="0 / 0")
|
| 134 |
-
self.tele_breakdown_var = tk.StringVar(
|
| 135 |
-
value="present=0 | layer_interp=0 | expert_interp=0 | synth=0"
|
| 136 |
-
)
|
| 137 |
-
self.tele_speed_var = tk.StringVar(value="0.0 ten/s (ETA --)")
|
| 138 |
-
self.tele_elapsed_var = tk.StringVar(value="0.0s")
|
| 139 |
-
self.progress_var = tk.DoubleVar(value=0.0)
|
| 140 |
-
self.status_var = tk.StringVar(value="Ready.")
|
| 141 |
-
self.cli_preview_var = tk.StringVar()
|
| 142 |
-
|
| 143 |
-
# Prompt test variables
|
| 144 |
-
self.test_model_dir_var = tk.StringVar()
|
| 145 |
-
self.test_prompt_var = tk.StringVar(value="hello")
|
| 146 |
-
self.test_chat_mode_var = tk.BooleanVar(value=False)
|
| 147 |
-
self.test_max_tokens_var = tk.IntVar(value=24)
|
| 148 |
-
|
| 149 |
-
for v in (
|
| 150 |
-
self.op_mode_var,
|
| 151 |
-
self.hf_url_var,
|
| 152 |
-
self.hf_fetch_mode_var,
|
| 153 |
-
self.num_anchor_layers_var,
|
| 154 |
-
self.anchor_layers_var,
|
| 155 |
-
self.shard_var,
|
| 156 |
-
self.index_var,
|
| 157 |
-
self.config_var,
|
| 158 |
-
self.model_dir_var,
|
| 159 |
-
self.output_var,
|
| 160 |
-
self.export_dir_var,
|
| 161 |
-
self.auto_bundle_var,
|
| 162 |
-
self.device_var,
|
| 163 |
-
self.quant_format_var,
|
| 164 |
-
self.expert_keep_var,
|
| 165 |
-
self.target_params_b_var,
|
| 166 |
-
self.max_experts_var,
|
| 167 |
-
):
|
| 168 |
-
v.trace_add("write", lambda *_: self._update_cli_preview())
|
| 169 |
-
|
| 170 |
-
def _apply_theme(self) -> None:
|
| 171 |
-
style = ttk.Style(self.root)
|
| 172 |
-
if "clam" in style.theme_names():
|
| 173 |
-
style.theme_use("clam")
|
| 174 |
-
bg = "#141820"
|
| 175 |
-
panel = "#1c222d"
|
| 176 |
-
fg = "#e6edf3"
|
| 177 |
-
accent = "#3b82f6"
|
| 178 |
-
self.root.configure(bg=bg)
|
| 179 |
-
style.configure(".", background=bg, foreground=fg, fieldbackground=panel)
|
| 180 |
-
style.configure("TFrame", background=bg)
|
| 181 |
-
style.configure("TLabelframe", background=bg, foreground=fg)
|
| 182 |
-
style.configure(
|
| 183 |
-
"TLabelframe.Label",
|
| 184 |
-
background=bg,
|
| 185 |
-
foreground="#93c5fd",
|
| 186 |
-
font=("Sans", 10, "bold"),
|
| 187 |
-
)
|
| 188 |
-
style.configure("TLabel", background=bg, foreground=fg)
|
| 189 |
-
style.configure(
|
| 190 |
-
"TeleKey.TLabel", background=bg, foreground="#9ca3af", font=("Sans", 9)
|
| 191 |
-
)
|
| 192 |
-
style.configure(
|
| 193 |
-
"TeleVal.TLabel",
|
| 194 |
-
background=bg,
|
| 195 |
-
foreground="#60a5fa",
|
| 196 |
-
font=("Monospace", 9, "bold"),
|
| 197 |
-
)
|
| 198 |
-
style.configure("TCheckbutton", background=bg, foreground=fg)
|
| 199 |
-
style.configure("TRadiobutton", background=bg, foreground=fg)
|
| 200 |
-
style.configure("TButton", background=panel, foreground=fg, padding=(10, 5))
|
| 201 |
-
style.map("TButton", background=[("active", accent)])
|
| 202 |
-
style.configure(
|
| 203 |
-
"Accent.TButton",
|
| 204 |
-
background=accent,
|
| 205 |
-
foreground="#ffffff",
|
| 206 |
-
font=("Sans", 10, "bold"),
|
| 207 |
-
)
|
| 208 |
-
style.configure(
|
| 209 |
-
"Treeview",
|
| 210 |
-
background=panel,
|
| 211 |
-
fieldbackground=panel,
|
| 212 |
-
foreground=fg,
|
| 213 |
-
rowheight=23,
|
| 214 |
-
)
|
| 215 |
-
style.configure(
|
| 216 |
-
"Treeview.Heading",
|
| 217 |
-
background="#262f3f",
|
| 218 |
-
foreground=fg,
|
| 219 |
-
font=("Sans", 9, "bold"),
|
| 220 |
-
)
|
| 221 |
-
style.map("Treeview", background=[("selected", accent)])
|
| 222 |
-
|
| 223 |
-
def _build_layout(self) -> None:
|
| 224 |
-
outer = ttk.Frame(self.root)
|
| 225 |
-
outer.pack(fill=tk.BOTH, expand=True)
|
| 226 |
-
outer.rowconfigure(0, weight=1)
|
| 227 |
-
outer.columnconfigure(0, weight=1)
|
| 228 |
-
|
| 229 |
-
self._canvas = tk.Canvas(outer, bg="#141820", highlightthickness=0)
|
| 230 |
-
v_scroll = ttk.Scrollbar(outer, orient=tk.VERTICAL, command=self._canvas.yview)
|
| 231 |
-
h_scroll = ttk.Scrollbar(
|
| 232 |
-
outer, orient=tk.HORIZONTAL, command=self._canvas.xview
|
| 233 |
-
)
|
| 234 |
-
self._canvas.configure(yscrollcommand=v_scroll.set, xscrollcommand=h_scroll.set)
|
| 235 |
-
|
| 236 |
-
self._canvas.grid(row=0, column=0, sticky=tk.NSEW)
|
| 237 |
-
v_scroll.grid(row=0, column=1, sticky=tk.NS)
|
| 238 |
-
h_scroll.grid(row=1, column=0, sticky=tk.EW)
|
| 239 |
-
|
| 240 |
-
main = ttk.Frame(self._canvas, padding=10)
|
| 241 |
-
self._canvas_win = self._canvas.create_window((0, 0), window=main, anchor=tk.NW)
|
| 242 |
-
|
| 243 |
-
def _on_frame_configure(_event=None) -> None:
|
| 244 |
-
self._canvas.configure(scrollregion=self._canvas.bbox("all"))
|
| 245 |
-
|
| 246 |
-
def _on_canvas_configure(event) -> None:
|
| 247 |
-
req_w = max(event.width, main.winfo_reqwidth())
|
| 248 |
-
req_h = max(event.height, main.winfo_reqheight())
|
| 249 |
-
self._canvas.itemconfigure(self._canvas_win, width=req_w, height=req_h)
|
| 250 |
-
|
| 251 |
-
main.bind("<Configure>", _on_frame_configure)
|
| 252 |
-
self._canvas.bind("<Configure>", _on_canvas_configure)
|
| 253 |
-
|
| 254 |
-
# 1. Mode & File Paths Card
|
| 255 |
-
io_frame = ttk.LabelFrame(
|
| 256 |
-
main,
|
| 257 |
-
text=" 1. Operation Mode & Model Paths (Works on Any HF Model Architecture) ",
|
| 258 |
-
padding=10,
|
| 259 |
-
)
|
| 260 |
-
io_frame.pack(fill=tk.X, pady=(0, 8))
|
| 261 |
-
io_frame.columnconfigure(1, weight=1)
|
| 262 |
-
|
| 263 |
-
mode_bar = ttk.Frame(io_frame)
|
| 264 |
-
mode_bar.grid(row=0, column=0, columnspan=3, sticky=tk.W, pady=(0, 8))
|
| 265 |
-
ttk.Label(mode_bar, text="Workflow:", font=("Sans", 9, "bold")).pack(
|
| 266 |
-
side=tk.LEFT, padx=(0, 10)
|
| 267 |
-
)
|
| 268 |
-
ttk.Radiobutton(
|
| 269 |
-
mode_bar,
|
| 270 |
-
text="CheckFree Multi/Single-Shard Recovery (Shards -> Full Model)",
|
| 271 |
-
variable=self.op_mode_var,
|
| 272 |
-
value="recover",
|
| 273 |
-
).pack(side=tk.LEFT, padx=(0, 14))
|
| 274 |
-
ttk.Radiobutton(
|
| 275 |
-
mode_bar,
|
| 276 |
-
text="Retrieve Minimum Shards from HF Link",
|
| 277 |
-
variable=self.op_mode_var,
|
| 278 |
-
value="fetch-hf",
|
| 279 |
-
).pack(side=tk.LEFT, padx=(0, 14))
|
| 280 |
-
ttk.Radiobutton(
|
| 281 |
-
mode_bar,
|
| 282 |
-
text="Build Self-Contained SlimShard (Multi-Shard -> 1 SlimShard)",
|
| 283 |
-
variable=self.op_mode_var,
|
| 284 |
-
value="build",
|
| 285 |
-
).pack(side=tk.LEFT, padx=(0, 14))
|
| 286 |
-
ttk.Radiobutton(
|
| 287 |
-
mode_bar,
|
| 288 |
-
text="Regenerate from SlimShard",
|
| 289 |
-
variable=self.op_mode_var,
|
| 290 |
-
value="regenerate",
|
| 291 |
-
).pack(side=tk.LEFT, padx=(0, 14))
|
| 292 |
-
ttk.Radiobutton(
|
| 293 |
-
mode_bar,
|
| 294 |
-
text="Export SafeTensors to GGUF (Q2_K / Q4_0 / BF16)",
|
| 295 |
-
variable=self.op_mode_var,
|
| 296 |
-
value="export-gguf",
|
| 297 |
-
).pack(side=tk.LEFT)
|
| 298 |
-
|
| 299 |
-
# Hugging Face Link Minimum-Shard Retriever Bar
|
| 300 |
-
hf_bar = ttk.Frame(io_frame)
|
| 301 |
-
hf_bar.grid(row=1, column=0, columnspan=3, sticky=tk.EW, pady=(0, 6))
|
| 302 |
-
hf_bar.columnconfigure(1, weight=1)
|
| 303 |
-
ttk.Label(
|
| 304 |
-
hf_bar, text="Hugging Face Link / Repo:", font=("Sans", 9, "bold")
|
| 305 |
-
).grid(row=0, column=0, sticky=tk.W, padx=(0, 6))
|
| 306 |
-
ttk.Entry(hf_bar, textvariable=self.hf_url_var).grid(
|
| 307 |
-
row=0, column=1, sticky=tk.EW, padx=(0, 8)
|
| 308 |
-
)
|
| 309 |
-
ttk.Combobox(
|
| 310 |
-
hf_bar,
|
| 311 |
-
textvariable=self.hf_fetch_mode_var,
|
| 312 |
-
values=("surgical", "full_shards"),
|
| 313 |
-
width=12,
|
| 314 |
-
state="readonly",
|
| 315 |
-
).grid(row=0, column=2, padx=(0, 6))
|
| 316 |
-
ttk.Button(
|
| 317 |
-
hf_bar, text="Analyze Min Shards", command=self._analyze_hf_min_shards
|
| 318 |
-
).grid(row=0, column=3, padx=(0, 6))
|
| 319 |
-
ttk.Button(
|
| 320 |
-
hf_bar,
|
| 321 |
-
text="Retrieve Min Shards",
|
| 322 |
-
style="Accent.TButton",
|
| 323 |
-
command=self._retrieve_hf_min_shards,
|
| 324 |
-
).grid(row=0, column=4)
|
| 325 |
-
|
| 326 |
-
self._add_path_row(
|
| 327 |
-
io_frame,
|
| 328 |
-
2,
|
| 329 |
-
"Surviving Shard(s) / Input (.safetensors, comma-sep):",
|
| 330 |
-
self.shard_var,
|
| 331 |
-
self._pick_shard,
|
| 332 |
-
)
|
| 333 |
-
self._add_path_row(
|
| 334 |
-
io_frame,
|
| 335 |
-
3,
|
| 336 |
-
"Index JSON (optional, auto-inferred if omitted):",
|
| 337 |
-
self.index_var,
|
| 338 |
-
self._pick_index,
|
| 339 |
-
)
|
| 340 |
-
self._add_path_row(
|
| 341 |
-
io_frame,
|
| 342 |
-
4,
|
| 343 |
-
"Config JSON (auto-detected from folder):",
|
| 344 |
-
self.config_var,
|
| 345 |
-
self._pick_config,
|
| 346 |
-
)
|
| 347 |
-
self._add_path_row(
|
| 348 |
-
io_frame,
|
| 349 |
-
5,
|
| 350 |
-
"Source / Download Model Dir:",
|
| 351 |
-
self.model_dir_var,
|
| 352 |
-
self._pick_model_dir,
|
| 353 |
-
)
|
| 354 |
-
self._add_path_row(
|
| 355 |
-
io_frame,
|
| 356 |
-
6,
|
| 357 |
-
"Output .safetensors / .gguf File:",
|
| 358 |
-
self.output_var,
|
| 359 |
-
self._pick_output,
|
| 360 |
-
)
|
| 361 |
-
self._add_path_row(
|
| 362 |
-
io_frame,
|
| 363 |
-
7,
|
| 364 |
-
"Export Ready-to-Run HF Bundle Dir:",
|
| 365 |
-
self.export_dir_var,
|
| 366 |
-
self._pick_export_dir,
|
| 367 |
-
)
|
| 368 |
-
|
| 369 |
-
# 2. Options & Execution Controls
|
| 370 |
-
opt_frame = ttk.LabelFrame(
|
| 371 |
-
main, text=" 2. CheckFree / SlimShard Engine Parameters ", padding=10
|
| 372 |
-
)
|
| 373 |
-
opt_frame.pack(fill=tk.X, pady=(0, 8))
|
| 374 |
-
|
| 375 |
-
row_opt = ttk.Frame(opt_frame)
|
| 376 |
-
row_opt.pack(fill=tk.X)
|
| 377 |
-
|
| 378 |
-
gpu_lbl = (
|
| 379 |
-
f"CUDA ({cuda_device_name()})" if cuda_is_available() else "CPU only"
|
| 380 |
-
)
|
| 381 |
-
ttk.Label(row_opt, text=f"Compute Device [{gpu_lbl}]:").pack(
|
| 382 |
-
side=tk.LEFT, padx=(0, 6)
|
| 383 |
-
)
|
| 384 |
-
ttk.Combobox(
|
| 385 |
-
row_opt,
|
| 386 |
-
textvariable=self.device_var,
|
| 387 |
-
values=("auto", "cuda", "cpu"),
|
| 388 |
-
width=8,
|
| 389 |
-
state="readonly",
|
| 390 |
-
).pack(side=tk.LEFT, padx=(0, 16))
|
| 391 |
-
|
| 392 |
-
ttk.Label(row_opt, text="Format:").pack(side=tk.LEFT, padx=(0, 6))
|
| 393 |
-
ttk.Combobox(
|
| 394 |
-
row_opt,
|
| 395 |
-
textvariable=self.quant_format_var,
|
| 396 |
-
values=("mixed", "q2_k", "q4_0", "bf16", "exact"),
|
| 397 |
-
width=9,
|
| 398 |
-
state="readonly",
|
| 399 |
-
).pack(side=tk.LEFT, padx=(0, 16))
|
| 400 |
-
|
| 401 |
-
ttk.Label(row_opt, text="Target Params (B, 0=full):").pack(
|
| 402 |
-
side=tk.LEFT, padx=(0, 6)
|
| 403 |
-
)
|
| 404 |
-
ttk.Spinbox(
|
| 405 |
-
row_opt,
|
| 406 |
-
from_=0.0,
|
| 407 |
-
to=600.0,
|
| 408 |
-
increment=1.0,
|
| 409 |
-
textvariable=self.target_params_b_var,
|
| 410 |
-
width=6,
|
| 411 |
-
).pack(side=tk.LEFT, padx=(0, 14))
|
| 412 |
-
|
| 413 |
-
ttk.Label(row_opt, text="Max Experts/Layer (0=auto):").pack(
|
| 414 |
-
side=tk.LEFT, padx=(0, 6)
|
| 415 |
-
)
|
| 416 |
-
ttk.Spinbox(
|
| 417 |
-
row_opt,
|
| 418 |
-
from_=0,
|
| 419 |
-
to=512,
|
| 420 |
-
increment=1,
|
| 421 |
-
textvariable=self.max_experts_var,
|
| 422 |
-
width=5,
|
| 423 |
-
).pack(side=tk.LEFT, padx=(0, 14))
|
| 424 |
-
|
| 425 |
-
ttk.Label(row_opt, text="# Anchor Layers:").pack(
|
| 426 |
-
side=tk.LEFT, padx=(0, 4)
|
| 427 |
-
)
|
| 428 |
-
ttk.Spinbox(
|
| 429 |
-
row_opt,
|
| 430 |
-
from_=1,
|
| 431 |
-
to=128,
|
| 432 |
-
increment=1,
|
| 433 |
-
textvariable=self.num_anchor_layers_var,
|
| 434 |
-
width=4,
|
| 435 |
-
).pack(side=tk.LEFT, padx=(0, 10))
|
| 436 |
-
|
| 437 |
-
ttk.Label(row_opt, text="Anchor Layers (e.g. 0,14,39):").pack(
|
| 438 |
-
side=tk.LEFT, padx=(0, 4)
|
| 439 |
-
)
|
| 440 |
-
ttk.Entry(
|
| 441 |
-
row_opt,
|
| 442 |
-
textvariable=self.anchor_layers_var,
|
| 443 |
-
width=12,
|
| 444 |
-
).pack(side=tk.LEFT, padx=(0, 12))
|
| 445 |
-
|
| 446 |
-
ttk.Label(row_opt, text="SlimMoE Keep Ratio:").pack(
|
| 447 |
-
side=tk.LEFT, padx=(0, 6)
|
| 448 |
-
)
|
| 449 |
-
ttk.Spinbox(
|
| 450 |
-
row_opt,
|
| 451 |
-
from_=0.10,
|
| 452 |
-
to=1.00,
|
| 453 |
-
increment=0.05,
|
| 454 |
-
textvariable=self.expert_keep_var,
|
| 455 |
-
width=6,
|
| 456 |
-
).pack(side=tk.LEFT, padx=(0, 14))
|
| 457 |
-
|
| 458 |
-
ttk.Checkbutton(
|
| 459 |
-
row_opt,
|
| 460 |
-
text="Export HF Bundle Dir",
|
| 461 |
-
variable=self.auto_bundle_var,
|
| 462 |
-
).pack(side=tk.LEFT, padx=(0, 8))
|
| 463 |
-
|
| 464 |
-
btn_bar = ttk.Frame(opt_frame)
|
| 465 |
-
btn_bar.pack(fill=tk.X, pady=(8, 0))
|
| 466 |
-
ttk.Button(
|
| 467 |
-
btn_bar,
|
| 468 |
-
text="Inspect Shard & Recovery Plan",
|
| 469 |
-
command=self._inspect_plan,
|
| 470 |
-
).pack(side=tk.LEFT, padx=(0, 8))
|
| 471 |
-
self.run_btn = ttk.Button(
|
| 472 |
-
btn_bar,
|
| 473 |
-
text="Run Recovery / Build",
|
| 474 |
-
style="Accent.TButton",
|
| 475 |
-
command=self._start_run,
|
| 476 |
-
)
|
| 477 |
-
self.run_btn.pack(side=tk.LEFT, padx=(0, 8))
|
| 478 |
-
self.stop_btn = ttk.Button(
|
| 479 |
-
btn_bar, text="Stop", command=self._stop_run, state=tk.DISABLED
|
| 480 |
-
)
|
| 481 |
-
self.stop_btn.pack(side=tk.LEFT, padx=(0, 14))
|
| 482 |
-
ttk.Entry(btn_bar, textvariable=self.cli_preview_var, state="readonly").pack(
|
| 483 |
-
side=tk.LEFT, fill=tk.X, expand=True
|
| 484 |
-
)
|
| 485 |
-
|
| 486 |
-
# 3. Telemetry Dashboard
|
| 487 |
-
tele = ttk.LabelFrame(main, text=" 3. Real-Time Telemetry ", padding=10)
|
| 488 |
-
tele.pack(fill=tk.X, pady=(0, 8))
|
| 489 |
-
tele.columnconfigure(1, weight=1)
|
| 490 |
-
tele.columnconfigure(3, weight=1)
|
| 491 |
-
|
| 492 |
-
ttk.Label(tele, text="Architecture:", style="TeleKey.TLabel").grid(
|
| 493 |
-
row=0, column=0, sticky=tk.W
|
| 494 |
-
)
|
| 495 |
-
ttk.Label(tele, textvariable=self.arch_summary_var, style="TeleVal.TLabel").grid(
|
| 496 |
-
row=0, column=1, columnspan=3, sticky=tk.W, padx=(6, 0)
|
| 497 |
-
)
|
| 498 |
-
|
| 499 |
-
ttk.Label(tele, text="Layer Coverage:", style="TeleKey.TLabel").grid(
|
| 500 |
-
row=1, column=0, sticky=tk.W, pady=(3, 0)
|
| 501 |
-
)
|
| 502 |
-
ttk.Label(
|
| 503 |
-
tele, textvariable=self.layers_summary_var, style="TeleVal.TLabel"
|
| 504 |
-
).grid(row=1, column=1, columnspan=3, sticky=tk.W, padx=(6, 0), pady=(3, 0))
|
| 505 |
-
|
| 506 |
-
ttk.Label(tele, text="Active Tensor:", style="TeleKey.TLabel").grid(
|
| 507 |
-
row=2, column=0, sticky=tk.W, pady=(3, 0)
|
| 508 |
-
)
|
| 509 |
-
ttk.Label(tele, textvariable=self.tele_tensor_var, style="TeleVal.TLabel").grid(
|
| 510 |
-
row=2, column=1, sticky=tk.W, padx=(6, 0), pady=(3, 0)
|
| 511 |
-
)
|
| 512 |
-
ttk.Label(tele, text="Stage / Action:", style="TeleKey.TLabel").grid(
|
| 513 |
-
row=2, column=2, sticky=tk.W, pady=(3, 0)
|
| 514 |
-
)
|
| 515 |
-
ttk.Label(tele, textvariable=self.tele_action_var, style="TeleVal.TLabel").grid(
|
| 516 |
-
row=2, column=3, sticky=tk.W, padx=(6, 0), pady=(3, 0)
|
| 517 |
-
)
|
| 518 |
-
|
| 519 |
-
ttk.Label(tele, text="Progress:", style="TeleKey.TLabel").grid(
|
| 520 |
-
row=3, column=0, sticky=tk.W, pady=(3, 0)
|
| 521 |
-
)
|
| 522 |
-
ttk.Label(
|
| 523 |
-
tele, textvariable=self.tele_progress_text_var, style="TeleVal.TLabel"
|
| 524 |
-
).grid(row=3, column=1, sticky=tk.W, padx=(6, 0), pady=(3, 0))
|
| 525 |
-
ttk.Label(tele, text="Throughput / ETA:", style="TeleKey.TLabel").grid(
|
| 526 |
-
row=3, column=2, sticky=tk.W, pady=(3, 0)
|
| 527 |
-
)
|
| 528 |
-
ttk.Label(tele, textvariable=self.tele_speed_var, style="TeleVal.TLabel").grid(
|
| 529 |
-
row=3, column=3, sticky=tk.W, padx=(6, 0), pady=(3, 0)
|
| 530 |
-
)
|
| 531 |
-
|
| 532 |
-
ttk.Label(tele, text="Breakdown:", style="TeleKey.TLabel").grid(
|
| 533 |
-
row=4, column=0, sticky=tk.W, pady=(3, 0)
|
| 534 |
-
)
|
| 535 |
-
ttk.Label(
|
| 536 |
-
tele, textvariable=self.tele_breakdown_var, style="TeleVal.TLabel"
|
| 537 |
-
).grid(row=4, column=1, sticky=tk.W, padx=(6, 0), pady=(3, 0))
|
| 538 |
-
ttk.Label(tele, text="Elapsed:", style="TeleKey.TLabel").grid(
|
| 539 |
-
row=4, column=2, sticky=tk.W, pady=(3, 0)
|
| 540 |
-
)
|
| 541 |
-
ttk.Label(
|
| 542 |
-
tele, textvariable=self.tele_elapsed_var, style="TeleVal.TLabel"
|
| 543 |
-
).grid(row=4, column=3, sticky=tk.W, padx=(6, 0), pady=(3, 0))
|
| 544 |
-
|
| 545 |
-
ttk.Progressbar(
|
| 546 |
-
tele, variable=self.progress_var, maximum=100.0, mode="determinate"
|
| 547 |
-
).grid(row=5, column=0, columnspan=4, sticky=tk.EW, pady=(8, 0))
|
| 548 |
-
|
| 549 |
-
# 4. Tensor Recovery Plan Table
|
| 550 |
-
tbl_frame = ttk.LabelFrame(
|
| 551 |
-
main, text=" 4. Tensor Recovery Plan & Status ", padding=10
|
| 552 |
-
)
|
| 553 |
-
tbl_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 8))
|
| 554 |
-
|
| 555 |
-
fbar = ttk.Frame(tbl_frame)
|
| 556 |
-
fbar.pack(fill=tk.X, pady=(0, 6))
|
| 557 |
-
ttk.Label(fbar, text="Filter Action:").pack(side=tk.LEFT, padx=(0, 6))
|
| 558 |
-
cb_filter = ttk.Combobox(
|
| 559 |
-
fbar,
|
| 560 |
-
textvariable=self.filter_action_var,
|
| 561 |
-
values=(
|
| 562 |
-
"ALL",
|
| 563 |
-
"PRESENT",
|
| 564 |
-
"CHECKFREE_LAYER",
|
| 565 |
-
"CHECKFREE_EXPERT",
|
| 566 |
-
"SYNTHESIZE_CALIBRATED",
|
| 567 |
-
"SUFFIX_PRIOR",
|
| 568 |
-
),
|
| 569 |
-
width=22,
|
| 570 |
-
state="readonly",
|
| 571 |
-
)
|
| 572 |
-
cb_filter.pack(side=tk.LEFT, padx=(0, 14))
|
| 573 |
-
cb_filter.bind("<<ComboboxSelected>>", lambda *_: self._refresh_table())
|
| 574 |
-
|
| 575 |
-
ttk.Label(fbar, text="Search Tensor:").pack(side=tk.LEFT, padx=(0, 6))
|
| 576 |
-
ent_search = ttk.Entry(fbar, textvariable=self.search_var, width=32)
|
| 577 |
-
ent_search.pack(side=tk.LEFT, padx=(0, 8))
|
| 578 |
-
ent_search.bind("<KeyRelease>", lambda *_: self._refresh_table())
|
| 579 |
-
|
| 580 |
-
cols = ("idx", "name", "layer", "role", "shard", "action", "dtype", "status")
|
| 581 |
-
self.tree = ttk.Treeview(
|
| 582 |
-
tbl_frame, columns=cols, show="headings", height=10, selectmode="browse"
|
| 583 |
-
)
|
| 584 |
-
headers = {
|
| 585 |
-
"idx": ("#", 55),
|
| 586 |
-
"name": ("Tensor Name", 410),
|
| 587 |
-
"layer": ("Layer", 65),
|
| 588 |
-
"role": ("Role", 150),
|
| 589 |
-
"shard": ("Original Shard", 210),
|
| 590 |
-
"action": ("Recovery Strategy", 170),
|
| 591 |
-
"dtype": ("Dtype", 80),
|
| 592 |
-
"status": ("Status", 95),
|
| 593 |
-
}
|
| 594 |
-
for c, (label, w) in headers.items():
|
| 595 |
-
self.tree.heading(c, text=label)
|
| 596 |
-
self.tree.column(c, width=w, anchor=tk.W if c != "idx" else tk.E)
|
| 597 |
-
|
| 598 |
-
t_scroll = ttk.Scrollbar(tbl_frame, orient=tk.VERTICAL, command=self.tree.yview)
|
| 599 |
-
self.tree.configure(yscrollcommand=t_scroll.set)
|
| 600 |
-
self.tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
|
| 601 |
-
t_scroll.pack(side=tk.RIGHT, fill=tk.Y)
|
| 602 |
-
|
| 603 |
-
# 5. Universal Recovered Model Prompt Tester + Log
|
| 604 |
-
bottom_pane = ttk.PanedWindow(main, orient=tk.HORIZONTAL)
|
| 605 |
-
bottom_pane.pack(fill=tk.BOTH, expand=True)
|
| 606 |
-
|
| 607 |
-
test_frame = ttk.LabelFrame(
|
| 608 |
-
bottom_pane,
|
| 609 |
-
text=" 5. Test Recovered Model (Works on Any HF CausalLM) ",
|
| 610 |
-
padding=10,
|
| 611 |
-
)
|
| 612 |
-
bottom_pane.add(test_frame, weight=1)
|
| 613 |
-
|
| 614 |
-
t_row1 = ttk.Frame(test_frame)
|
| 615 |
-
t_row1.pack(fill=tk.X, pady=(0, 4))
|
| 616 |
-
ttk.Label(t_row1, text="Model Dir:").pack(side=tk.LEFT, padx=(0, 6))
|
| 617 |
-
ttk.Entry(t_row1, textvariable=self.test_model_dir_var).pack(
|
| 618 |
-
side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 6)
|
| 619 |
-
)
|
| 620 |
-
ttk.Button(t_row1, text="Browse", command=self._pick_test_dir).pack(
|
| 621 |
-
side=tk.LEFT
|
| 622 |
-
)
|
| 623 |
-
|
| 624 |
-
t_row2 = ttk.Frame(test_frame)
|
| 625 |
-
t_row2.pack(fill=tk.X, pady=(0, 4))
|
| 626 |
-
ttk.Label(t_row2, text="Prompt:").pack(side=tk.LEFT, padx=(0, 6))
|
| 627 |
-
ttk.Entry(t_row2, textvariable=self.test_prompt_var).pack(
|
| 628 |
-
side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 8)
|
| 629 |
-
)
|
| 630 |
-
ttk.Checkbutton(
|
| 631 |
-
t_row2, text="Chat Template", variable=self.test_chat_mode_var
|
| 632 |
-
).pack(side=tk.LEFT, padx=(0, 8))
|
| 633 |
-
ttk.Label(t_row2, text="Max Tokens:").pack(side=tk.LEFT, padx=(0, 4))
|
| 634 |
-
ttk.Spinbox(
|
| 635 |
-
t_row2, from_=1, to=256, textvariable=self.test_max_tokens_var, width=5
|
| 636 |
-
).pack(side=tk.LEFT, padx=(0, 8))
|
| 637 |
-
self.test_btn = ttk.Button(
|
| 638 |
-
t_row2,
|
| 639 |
-
text="Run Prompt",
|
| 640 |
-
style="Accent.TButton",
|
| 641 |
-
command=self._run_prompt_test,
|
| 642 |
-
)
|
| 643 |
-
self.test_btn.pack(side=tk.LEFT)
|
| 644 |
-
|
| 645 |
-
self.test_out_text = tk.Text(
|
| 646 |
-
test_frame,
|
| 647 |
-
height=8,
|
| 648 |
-
bg="#0f131a",
|
| 649 |
-
fg="#a7f3d0",
|
| 650 |
-
insertbackground="#ffffff",
|
| 651 |
-
font=("Monospace", 9),
|
| 652 |
-
wrap=tk.WORD,
|
| 653 |
-
)
|
| 654 |
-
self.test_out_text.pack(fill=tk.BOTH, expand=True)
|
| 655 |
-
|
| 656 |
-
log_frame = ttk.LabelFrame(bottom_pane, text=" 6. Event Log ", padding=10)
|
| 657 |
-
bottom_pane.add(log_frame, weight=1)
|
| 658 |
-
self.log_text = tk.Text(
|
| 659 |
-
log_frame,
|
| 660 |
-
height=8,
|
| 661 |
-
bg="#0f131a",
|
| 662 |
-
fg="#e6edf3",
|
| 663 |
-
insertbackground="#ffffff",
|
| 664 |
-
font=("Monospace", 9),
|
| 665 |
-
wrap=tk.WORD,
|
| 666 |
-
)
|
| 667 |
-
self.log_text.pack(fill=tk.BOTH, expand=True)
|
| 668 |
-
|
| 669 |
-
def _add_path_row(
|
| 670 |
-
self, parent: ttk.Frame, row: int, label: str, var: tk.StringVar, cmd
|
| 671 |
-
) -> None:
|
| 672 |
-
ttk.Label(parent, text=label).grid(row=row, column=0, sticky=tk.W, pady=2)
|
| 673 |
-
ttk.Entry(parent, textvariable=var).grid(
|
| 674 |
-
row=row, column=1, sticky=tk.EW, padx=6, pady=2
|
| 675 |
-
)
|
| 676 |
-
ttk.Button(parent, text="Browse...", command=cmd).grid(
|
| 677 |
-
row=row, column=2, sticky=tk.E, pady=2
|
| 678 |
-
)
|
| 679 |
-
|
| 680 |
-
def _auto_populate_defaults(self) -> None:
|
| 681 |
-
repo_root = Path(__file__).resolve().parent.parent
|
| 682 |
-
for base in (Path.cwd(), repo_root):
|
| 683 |
-
raon_shard = base / "Raon-1-mini-preview" / "model-00001-of-00007.safetensors"
|
| 684 |
-
if raon_shard.exists():
|
| 685 |
-
self._set_shard_and_companions(raon_shard)
|
| 686 |
-
return
|
| 687 |
-
shards = sorted(base.glob("*/*.safetensors"))
|
| 688 |
-
if shards:
|
| 689 |
-
self._set_shard_and_companions(shards[0])
|
| 690 |
-
return
|
| 691 |
-
|
| 692 |
-
def _set_shard_and_companions(self, shard_path: Path) -> None:
|
| 693 |
-
self.shard_var.set(str(shard_path))
|
| 694 |
-
parent = shard_path.parent
|
| 695 |
-
self.model_dir_var.set(str(parent))
|
| 696 |
-
idx = parent / "model.safetensors.index.json"
|
| 697 |
-
if idx.exists():
|
| 698 |
-
self.index_var.set(str(idx))
|
| 699 |
-
cfg = parent / "config.json"
|
| 700 |
-
if cfg.exists():
|
| 701 |
-
self.config_var.set(str(cfg))
|
| 702 |
-
if not self.output_var.get():
|
| 703 |
-
self.output_var.set(str(Path.cwd() / f"{parent.name}-recovered.safetensors"))
|
| 704 |
-
if not self.export_dir_var.get():
|
| 705 |
-
self.export_dir_var.set(str(Path.cwd() / f"recovered_{parent.name.lower().replace('-', '_')}"))
|
| 706 |
-
self.test_model_dir_var.set(self.export_dir_var.get())
|
| 707 |
-
|
| 708 |
-
def _pick_shard(self) -> None:
|
| 709 |
-
ps = filedialog.askopenfilenames(
|
| 710 |
-
title="Select Surviving .safetensors Shard(s) (Multi-Select Supported)",
|
| 711 |
-
filetypes=[("SafeTensors", "*.safetensors"), ("All files", "*.*")],
|
| 712 |
-
)
|
| 713 |
-
if ps:
|
| 714 |
-
paths = [Path(p) for p in ps]
|
| 715 |
-
self._set_shard_and_companions(paths[0])
|
| 716 |
-
self.shard_var.set(", ".join(str(p) for p in paths))
|
| 717 |
-
self._inspect_plan()
|
| 718 |
-
|
| 719 |
-
def _analyze_hf_min_shards(self) -> None:
|
| 720 |
-
url = self.hf_url_var.get().strip()
|
| 721 |
-
if not url:
|
| 722 |
-
messagebox.showwarning("SlimShard", "Please enter a Hugging Face link or repo ID first.")
|
| 723 |
-
return
|
| 724 |
-
try:
|
| 725 |
-
tp = float(self.target_params_b_var.get())
|
| 726 |
-
except Exception:
|
| 727 |
-
tp = 0.0
|
| 728 |
-
try:
|
| 729 |
-
me = int(self.max_experts_var.get())
|
| 730 |
-
except Exception:
|
| 731 |
-
me = 0
|
| 732 |
-
try:
|
| 733 |
-
n_anc = int(self.num_anchor_layers_var.get())
|
| 734 |
-
except Exception:
|
| 735 |
-
n_anc = 3
|
| 736 |
-
anc_str = self.anchor_layers_var.get().strip() or None
|
| 737 |
-
|
| 738 |
-
self._log(f"Analyzing minimum shards on Hugging Face for {url}...")
|
| 739 |
-
try:
|
| 740 |
-
plan = plan_minimum_shards_from_hf(
|
| 741 |
-
url,
|
| 742 |
-
target_params_b=tp if tp > 0.0 else None,
|
| 743 |
-
max_experts=me if me > 0 else None,
|
| 744 |
-
num_anchor_layers=n_anc,
|
| 745 |
-
anchor_layers=anc_str,
|
| 746 |
-
)
|
| 747 |
-
except Exception as exc:
|
| 748 |
-
self._log(f"HF Analyze Failed: {exc}")
|
| 749 |
-
messagebox.showerror("HF Minimum Shards Analysis Failed", str(exc))
|
| 750 |
-
return
|
| 751 |
-
|
| 752 |
-
repo_name = plan["repo_id"].split("/")[-1]
|
| 753 |
-
if not self.model_dir_var.get().strip():
|
| 754 |
-
self.model_dir_var.set(str(Path.cwd() / repo_name))
|
| 755 |
-
if not self.output_var.get().strip():
|
| 756 |
-
self.output_var.set(str(Path.cwd() / repo_name / "model.safetensors"))
|
| 757 |
-
if not self.export_dir_var.get().strip():
|
| 758 |
-
self.export_dir_var.set(str(Path.cwd() / f"recovered_{repo_name.lower().replace('-', '_')}"))
|
| 759 |
-
|
| 760 |
-
min_sh = plan["minimum_shards"]
|
| 761 |
-
tot_sh = plan["total_repo_shards"]
|
| 762 |
-
anchors = plan["anchor_layers"]
|
| 763 |
-
archs = ",".join(plan["architectures"]) or plan["model_type"]
|
| 764 |
-
self.arch_summary_var.set(
|
| 765 |
-
f"{plan['repo_id']} ({archs} | ~{plan['estimated_params_b']}B target | "
|
| 766 |
-
f"layers={plan['num_hidden_layers']}, experts={plan['kept_experts']}/{plan['orig_num_experts']})"
|
| 767 |
-
)
|
| 768 |
-
self.layers_summary_var.set(
|
| 769 |
-
f"Minimum Shards Needed: {len(min_sh)} / {tot_sh} ({', '.join(min_sh)}) | "
|
| 770 |
-
f"Anchor Layers ({len(anchors)}): {anchors}"
|
| 771 |
-
)
|
| 772 |
-
self.tele_breakdown_var.set(
|
| 773 |
-
f"min_shards={len(min_sh)}/{tot_sh} | surgical_tensors={plan['surgical_tensor_count']} | "
|
| 774 |
-
f"full_repo={plan['total_repo_size_gb']} GB"
|
| 775 |
-
)
|
| 776 |
-
roles_lines = [
|
| 777 |
-
f" - {sh}: {', '.join(plan['shard_roles'].get(sh, []))}" for sh in min_sh
|
| 778 |
-
]
|
| 779 |
-
msg = (
|
| 780 |
-
f"HF Repo: {plan['repo_id']}@{plan['revision']}\n"
|
| 781 |
-
f"Minimum Shards Required: {len(min_sh)} of {tot_sh} shards\n"
|
| 782 |
-
f"Selected Anchor Layers: {anchors}\n"
|
| 783 |
-
f"Surgical Tensor Count: {plan['surgical_tensor_count']} tensors\n"
|
| 784 |
-
+ "\n".join(roles_lines)
|
| 785 |
-
)
|
| 786 |
-
self._log(msg)
|
| 787 |
-
|
| 788 |
-
def _retrieve_hf_min_shards(self) -> None:
|
| 789 |
-
self.op_mode_var.set("fetch-hf")
|
| 790 |
-
if not self.model_dir_var.get().strip():
|
| 791 |
-
try:
|
| 792 |
-
repo_id, _ = parse_hf_repo_url(self.hf_url_var.get().strip())
|
| 793 |
-
self.model_dir_var.set(str(Path.cwd() / repo_id.split("/")[-1]))
|
| 794 |
-
except Exception:
|
| 795 |
-
self.model_dir_var.set(str(Path.cwd() / "hf_min_shards"))
|
| 796 |
-
if not self.output_var.get().strip():
|
| 797 |
-
self.output_var.set(str(Path(self.model_dir_var.get().strip()) / "model.safetensors"))
|
| 798 |
-
self._start_run()
|
| 799 |
-
|
| 800 |
-
def _pick_index(self) -> None:
|
| 801 |
-
p = filedialog.askopenfilename(
|
| 802 |
-
title="Select model.safetensors.index.json",
|
| 803 |
-
filetypes=[("JSON", "*.json"), ("All files", "*.*")],
|
| 804 |
-
)
|
| 805 |
-
if p:
|
| 806 |
-
self.index_var.set(p)
|
| 807 |
-
|
| 808 |
-
def _pick_config(self) -> None:
|
| 809 |
-
p = filedialog.askopenfilename(
|
| 810 |
-
title="Select config.json",
|
| 811 |
-
filetypes=[("JSON", "*.json"), ("All files", "*.*")],
|
| 812 |
-
)
|
| 813 |
-
if p:
|
| 814 |
-
self.config_var.set(p)
|
| 815 |
-
|
| 816 |
-
def _pick_model_dir(self) -> None:
|
| 817 |
-
p = filedialog.askdirectory(title="Select HF Model Directory")
|
| 818 |
-
if p:
|
| 819 |
-
self.model_dir_var.set(p)
|
| 820 |
-
|
| 821 |
-
def _pick_output(self) -> None:
|
| 822 |
-
p = filedialog.asksaveasfilename(
|
| 823 |
-
title="Select Output .safetensors Path",
|
| 824 |
-
defaultextension=".safetensors",
|
| 825 |
-
filetypes=[("SafeTensors", "*.safetensors"), ("All files", "*.*")],
|
| 826 |
-
)
|
| 827 |
-
if p:
|
| 828 |
-
self.output_var.set(p)
|
| 829 |
-
|
| 830 |
-
def _pick_export_dir(self) -> None:
|
| 831 |
-
p = filedialog.askdirectory(title="Select Export HF Bundle Directory")
|
| 832 |
-
if p:
|
| 833 |
-
self.export_dir_var.set(p)
|
| 834 |
-
self.test_model_dir_var.set(p)
|
| 835 |
-
|
| 836 |
-
def _pick_test_dir(self) -> None:
|
| 837 |
-
p = filedialog.askdirectory(title="Select Recovered HF Model Directory")
|
| 838 |
-
if p:
|
| 839 |
-
self.test_model_dir_var.set(p)
|
| 840 |
-
|
| 841 |
-
def _update_cli_preview(self) -> None:
|
| 842 |
-
mode = self.op_mode_var.get()
|
| 843 |
-
cmd = ["python3", "-m", "hpc_quantize_v2.slimshard", mode]
|
| 844 |
-
if mode == "recover":
|
| 845 |
-
if self.shard_var.get():
|
| 846 |
-
cmd += ["--shard", self.shard_var.get()]
|
| 847 |
-
if self.index_var.get():
|
| 848 |
-
cmd += ["--index", self.index_var.get()]
|
| 849 |
-
if self.config_var.get():
|
| 850 |
-
cmd += ["--config", self.config_var.get()]
|
| 851 |
-
if self.output_var.get():
|
| 852 |
-
cmd += ["--output", self.output_var.get()]
|
| 853 |
-
if self.auto_bundle_var.get() and self.export_dir_var.get():
|
| 854 |
-
cmd += ["--export-hf-dir", self.export_dir_var.get()]
|
| 855 |
-
try:
|
| 856 |
-
tp = float(self.target_params_b_var.get())
|
| 857 |
-
if tp > 0.0:
|
| 858 |
-
cmd += ["--target-params-b", f"{tp:g}"]
|
| 859 |
-
except Exception:
|
| 860 |
-
pass
|
| 861 |
-
try:
|
| 862 |
-
me = int(self.max_experts_var.get())
|
| 863 |
-
if me > 0:
|
| 864 |
-
cmd += ["--max-experts", str(me)]
|
| 865 |
-
except Exception:
|
| 866 |
-
pass
|
| 867 |
-
if self.anchor_layers_var.get().strip():
|
| 868 |
-
cmd += ["--anchor-layers", self.anchor_layers_var.get().strip()]
|
| 869 |
-
cmd += ["--device", self.device_var.get()]
|
| 870 |
-
elif mode == "fetch-hf":
|
| 871 |
-
if self.hf_url_var.get().strip():
|
| 872 |
-
cmd += ["--repo", self.hf_url_var.get().strip()]
|
| 873 |
-
if self.model_dir_var.get().strip():
|
| 874 |
-
cmd += ["--output-dir", self.model_dir_var.get().strip()]
|
| 875 |
-
try:
|
| 876 |
-
tp = float(self.target_params_b_var.get())
|
| 877 |
-
if tp > 0.0:
|
| 878 |
-
cmd += ["--target-params-b", f"{tp:g}"]
|
| 879 |
-
except Exception:
|
| 880 |
-
pass
|
| 881 |
-
try:
|
| 882 |
-
me = int(self.max_experts_var.get())
|
| 883 |
-
if me > 0:
|
| 884 |
-
cmd += ["--max-experts", str(me)]
|
| 885 |
-
except Exception:
|
| 886 |
-
pass
|
| 887 |
-
try:
|
| 888 |
-
na = int(self.num_anchor_layers_var.get())
|
| 889 |
-
cmd += ["--num-anchor-layers", str(na)]
|
| 890 |
-
except Exception:
|
| 891 |
-
pass
|
| 892 |
-
if self.anchor_layers_var.get().strip():
|
| 893 |
-
cmd += ["--anchor-layers", self.anchor_layers_var.get().strip()]
|
| 894 |
-
cmd += ["--mode", self.hf_fetch_mode_var.get()]
|
| 895 |
-
elif mode == "build":
|
| 896 |
-
if self.model_dir_var.get():
|
| 897 |
-
cmd += ["--model-dir", self.model_dir_var.get()]
|
| 898 |
-
if self.output_var.get():
|
| 899 |
-
cmd += ["--output", self.output_var.get()]
|
| 900 |
-
cmd += [
|
| 901 |
-
"--format",
|
| 902 |
-
self.quant_format_var.get(),
|
| 903 |
-
"--expert-keep-ratio",
|
| 904 |
-
f"{self.expert_keep_var.get():.2f}",
|
| 905 |
-
"--device",
|
| 906 |
-
self.device_var.get(),
|
| 907 |
-
]
|
| 908 |
-
else:
|
| 909 |
-
if self.shard_var.get():
|
| 910 |
-
cmd += ["--input", self.shard_var.get()]
|
| 911 |
-
if self.output_var.get():
|
| 912 |
-
cmd += ["--output", self.output_var.get()]
|
| 913 |
-
self.cli_preview_var.set(" ".join(shlex.quote(x) for x in cmd))
|
| 914 |
-
|
| 915 |
-
def _log(self, msg: str) -> None:
|
| 916 |
-
self.log_text.insert(tk.END, f"[{_ts()}] {msg}\n")
|
| 917 |
-
self.log_text.see(tk.END)
|
| 918 |
-
|
| 919 |
-
def _inspect_plan(self) -> None:
|
| 920 |
-
shard = self.shard_var.get().strip()
|
| 921 |
-
try:
|
| 922 |
-
resolved = _resolve_shard_paths(shard) if shard else []
|
| 923 |
-
except Exception:
|
| 924 |
-
resolved = []
|
| 925 |
-
if not resolved:
|
| 926 |
-
messagebox.showwarning("SlimShard", "Please select one or more valid .safetensors shards first.")
|
| 927 |
-
return
|
| 928 |
-
try:
|
| 929 |
-
tp = float(self.target_params_b_var.get())
|
| 930 |
-
except Exception:
|
| 931 |
-
tp = 0.0
|
| 932 |
-
try:
|
| 933 |
-
me = int(self.max_experts_var.get())
|
| 934 |
-
except Exception:
|
| 935 |
-
me = 0
|
| 936 |
-
try:
|
| 937 |
-
plan = inspect_recovery_plan(
|
| 938 |
-
shard,
|
| 939 |
-
index=self.index_var.get().strip() or None,
|
| 940 |
-
config=self.config_var.get().strip() or None,
|
| 941 |
-
target_params_b=tp if tp > 0.0 else None,
|
| 942 |
-
max_experts=me if me > 0 else None,
|
| 943 |
-
anchor_layers=self.anchor_layers_var.get().strip() or None,
|
| 944 |
-
)
|
| 945 |
-
except Exception as exc:
|
| 946 |
-
messagebox.showerror("Inspect Failed", str(exc))
|
| 947 |
-
return
|
| 948 |
-
|
| 949 |
-
archs = ",".join(plan["architectures"]) or plan["model_type"]
|
| 950 |
-
orig_e = plan.get("orig_num_experts", plan["num_experts"])
|
| 951 |
-
exp_str = (
|
| 952 |
-
f"{plan['num_experts']}/{orig_e}"
|
| 953 |
-
if plan["num_experts"] != orig_e
|
| 954 |
-
else str(plan["num_experts"])
|
| 955 |
-
)
|
| 956 |
-
self.arch_summary_var.set(
|
| 957 |
-
f"{archs} (~{plan.get('estimated_params_b', 0)}B params | type={plan['model_type']}, "
|
| 958 |
-
f"hidden={plan['hidden_size']}, layers={plan['num_hidden_layers']}, "
|
| 959 |
-
f"experts={exp_str}, vocab={plan['vocab_size']}, tensors={plan['total_tensors']})"
|
| 960 |
-
)
|
| 961 |
-
surv = plan["surviving_layers"]
|
| 962 |
-
miss = plan["missing_layers"]
|
| 963 |
-
self.layers_summary_var.set(
|
| 964 |
-
f"Surviving across {len(resolved)} shard(s) ({len(surv)}): {surv[:12]}{'...' if len(surv) > 12 else ''} | "
|
| 965 |
-
f"Missing to CheckFree-reconstruct ({len(miss)}): {miss[:12]}{'...' if len(miss) > 12 else ''}"
|
| 966 |
-
)
|
| 967 |
-
c = plan["counts"]
|
| 968 |
-
self.tele_breakdown_var.set(
|
| 969 |
-
f"present={c.get('PRESENT', 0)} | layer_interp={c.get('CHECKFREE_LAYER', 0)} | "
|
| 970 |
-
f"expert_interp={c.get('CHECKFREE_EXPERT', 0)} | synth={c.get('SYNTHESIZE_CALIBRATED', 0)}"
|
| 971 |
-
)
|
| 972 |
-
self._plan_rows = plan["rows"]
|
| 973 |
-
self._refresh_table()
|
| 974 |
-
self._log(
|
| 975 |
-
f"Inspected {len(resolved)} shard(s): {plan['present_tensors']}/{plan['total_tensors']} present, "
|
| 976 |
-
f"{len(surv)} anchor layers, {len(miss)} layers to reconstruct via CheckFree."
|
| 977 |
-
)
|
| 978 |
-
|
| 979 |
-
def _refresh_table(self) -> None:
|
| 980 |
-
self.tree.delete(*self.tree.get_children())
|
| 981 |
-
f_act = self.filter_action_var.get()
|
| 982 |
-
q = self.search_var.get().strip().lower()
|
| 983 |
-
shown = 0
|
| 984 |
-
for idx, r in enumerate(self._plan_rows, 1):
|
| 985 |
-
if f_act != "ALL" and r["action"] != f_act:
|
| 986 |
-
continue
|
| 987 |
-
if q and q not in r["name"].lower() and q not in r["role"].lower():
|
| 988 |
-
continue
|
| 989 |
-
self.tree.insert(
|
| 990 |
-
"",
|
| 991 |
-
tk.END,
|
| 992 |
-
iid=r["name"],
|
| 993 |
-
values=(
|
| 994 |
-
idx,
|
| 995 |
-
r["name"],
|
| 996 |
-
r["layer"],
|
| 997 |
-
r["role"],
|
| 998 |
-
r["shard"],
|
| 999 |
-
r["action"],
|
| 1000 |
-
r["dtype"],
|
| 1001 |
-
"Planned",
|
| 1002 |
-
),
|
| 1003 |
-
)
|
| 1004 |
-
shown += 1
|
| 1005 |
-
if shown >= 1500:
|
| 1006 |
-
break
|
| 1007 |
-
|
| 1008 |
-
def _start_run(self) -> None:
|
| 1009 |
-
if self._worker is not None and self._worker.is_alive():
|
| 1010 |
-
return
|
| 1011 |
-
mode = self.op_mode_var.get()
|
| 1012 |
-
out = self.output_var.get().strip()
|
| 1013 |
-
if mode != "fetch-hf" and not out:
|
| 1014 |
-
messagebox.showwarning("SlimShard", "Please specify an output .safetensors path.")
|
| 1015 |
-
return
|
| 1016 |
-
|
| 1017 |
-
self._stop_event.clear()
|
| 1018 |
-
self._start_time = time.time()
|
| 1019 |
-
self.progress_var.set(0.0)
|
| 1020 |
-
self.run_btn.configure(state=tk.DISABLED)
|
| 1021 |
-
self.stop_btn.configure(state=tk.NORMAL)
|
| 1022 |
-
|
| 1023 |
-
def progress_cb(done: int, total: int, tname: str, action: str, stats: dict) -> None:
|
| 1024 |
-
self._queue.put(("progress", (done, total, tname, action, dict(stats))))
|
| 1025 |
-
|
| 1026 |
-
def worker() -> None:
|
| 1027 |
-
try:
|
| 1028 |
-
if mode == "recover":
|
| 1029 |
-
shard = self.shard_var.get().strip()
|
| 1030 |
-
idx = self.index_var.get().strip() or None
|
| 1031 |
-
cfg = self.config_var.get().strip() or None
|
| 1032 |
-
exp_dir = (
|
| 1033 |
-
self.export_dir_var.get().strip()
|
| 1034 |
-
if self.auto_bundle_var.get() and self.export_dir_var.get().strip()
|
| 1035 |
-
else None
|
| 1036 |
-
)
|
| 1037 |
-
try:
|
| 1038 |
-
tp = float(self.target_params_b_var.get())
|
| 1039 |
-
except Exception:
|
| 1040 |
-
tp = 0.0
|
| 1041 |
-
try:
|
| 1042 |
-
me = int(self.max_experts_var.get())
|
| 1043 |
-
except Exception:
|
| 1044 |
-
me = 0
|
| 1045 |
-
res = recover_from_shard(
|
| 1046 |
-
shard,
|
| 1047 |
-
idx,
|
| 1048 |
-
out,
|
| 1049 |
-
config=cfg,
|
| 1050 |
-
device=self.device_var.get(),
|
| 1051 |
-
verbose=False,
|
| 1052 |
-
progress_cb=progress_cb,
|
| 1053 |
-
stop_event=self._stop_event,
|
| 1054 |
-
export_hf_dir=exp_dir,
|
| 1055 |
-
target_params_b=tp if tp > 0.0 else None,
|
| 1056 |
-
max_experts=me if me > 0 else None,
|
| 1057 |
-
anchor_layers=self.anchor_layers_var.get().strip() or None,
|
| 1058 |
-
)
|
| 1059 |
-
if exp_dir:
|
| 1060 |
-
self._queue.put(("set_test_dir", exp_dir))
|
| 1061 |
-
self._queue.put(("done", ("CheckFree Recovery Complete", res)))
|
| 1062 |
-
elif mode == "fetch-hf":
|
| 1063 |
-
url = self.hf_url_var.get().strip()
|
| 1064 |
-
mdir = self.model_dir_var.get().strip() or str(Path.cwd() / "hf_min_shards")
|
| 1065 |
-
try:
|
| 1066 |
-
tp = float(self.target_params_b_var.get())
|
| 1067 |
-
except Exception:
|
| 1068 |
-
tp = 0.0
|
| 1069 |
-
try:
|
| 1070 |
-
me = int(self.max_experts_var.get())
|
| 1071 |
-
except Exception:
|
| 1072 |
-
me = 0
|
| 1073 |
-
try:
|
| 1074 |
-
na = int(self.num_anchor_layers_var.get())
|
| 1075 |
-
except Exception:
|
| 1076 |
-
na = 3
|
| 1077 |
-
res = fetch_minimum_shards_from_hf(
|
| 1078 |
-
url,
|
| 1079 |
-
mdir,
|
| 1080 |
-
target_params_b=tp if tp > 0.0 else None,
|
| 1081 |
-
max_experts=me if me > 0 else None,
|
| 1082 |
-
num_anchor_layers=na,
|
| 1083 |
-
anchor_layers=self.anchor_layers_var.get().strip() or None,
|
| 1084 |
-
mode=self.hf_fetch_mode_var.get(),
|
| 1085 |
-
verbose=False,
|
| 1086 |
-
progress_cb=progress_cb,
|
| 1087 |
-
stop_event=self._stop_event,
|
| 1088 |
-
)
|
| 1089 |
-
self._queue.put(("hf_fetched", (mdir, res)))
|
| 1090 |
-
self._queue.put(("done", ("HF Minimum Shards Retrieved", res)))
|
| 1091 |
-
elif mode == "build":
|
| 1092 |
-
mdir = self.model_dir_var.get().strip()
|
| 1093 |
-
cfg_obj = HPCConfig(device=self.device_var.get(), verbose=False).validate()
|
| 1094 |
-
res = build_slimshard(
|
| 1095 |
-
mdir,
|
| 1096 |
-
out,
|
| 1097 |
-
cfg=cfg_obj,
|
| 1098 |
-
quant_format=self.quant_format_var.get(),
|
| 1099 |
-
expert_keep_ratio=float(self.expert_keep_var.get()),
|
| 1100 |
-
verbose=False,
|
| 1101 |
-
progress_cb=progress_cb,
|
| 1102 |
-
stop_event=self._stop_event,
|
| 1103 |
-
)
|
| 1104 |
-
self._queue.put(("done", ("SlimShard Build Complete", res)))
|
| 1105 |
-
elif mode == "export-gguf":
|
| 1106 |
-
shard = self.shard_var.get().strip()
|
| 1107 |
-
cfg = self.config_var.get().strip() or None
|
| 1108 |
-
fmt = self.quant_format_var.get()
|
| 1109 |
-
if fmt == "exact":
|
| 1110 |
-
fmt = "bf16"
|
| 1111 |
-
res = export_safetensors_to_gguf(
|
| 1112 |
-
shard,
|
| 1113 |
-
out,
|
| 1114 |
-
config=cfg,
|
| 1115 |
-
quant_format=fmt,
|
| 1116 |
-
device=self.device_var.get(),
|
| 1117 |
-
verbose=False,
|
| 1118 |
-
progress_cb=progress_cb,
|
| 1119 |
-
stop_event=self._stop_event,
|
| 1120 |
-
)
|
| 1121 |
-
self._queue.put(("done", ("GGUF Export Complete", res)))
|
| 1122 |
-
else:
|
| 1123 |
-
shard = self.shard_var.get().strip()
|
| 1124 |
-
res = regenerate(
|
| 1125 |
-
shard,
|
| 1126 |
-
out,
|
| 1127 |
-
verbose=False,
|
| 1128 |
-
progress_cb=progress_cb,
|
| 1129 |
-
stop_event=self._stop_event,
|
| 1130 |
-
)
|
| 1131 |
-
self._queue.put(("done", ("SlimShard Regeneration Complete", res)))
|
| 1132 |
-
except Exception as exc:
|
| 1133 |
-
self._queue.put(("error", str(exc)))
|
| 1134 |
-
|
| 1135 |
-
self._worker = threading.Thread(target=worker, daemon=True)
|
| 1136 |
-
self._worker.start()
|
| 1137 |
-
self._log(f"Started {mode} -> {out}")
|
| 1138 |
-
|
| 1139 |
-
def _stop_run(self) -> None:
|
| 1140 |
-
self._stop_event.set()
|
| 1141 |
-
self._log("Cancellation requested...")
|
| 1142 |
-
|
| 1143 |
-
def _run_prompt_test(self) -> None:
|
| 1144 |
-
mdir = self.test_model_dir_var.get().strip() or self.export_dir_var.get().strip()
|
| 1145 |
-
if not mdir or not Path(mdir).exists():
|
| 1146 |
-
messagebox.showwarning(
|
| 1147 |
-
"Model Tester",
|
| 1148 |
-
"Please specify a valid Recovered HF Model Directory first.",
|
| 1149 |
-
)
|
| 1150 |
-
return
|
| 1151 |
-
prompt = self.test_prompt_var.get()
|
| 1152 |
-
use_chat = bool(self.test_chat_mode_var.get())
|
| 1153 |
-
max_new = int(self.test_max_tokens_var.get())
|
| 1154 |
-
|
| 1155 |
-
self.test_btn.configure(state=tk.DISABLED)
|
| 1156 |
-
self.test_out_text.delete("1.0", tk.END)
|
| 1157 |
-
self.test_out_text.insert(
|
| 1158 |
-
tk.END, f"Loading {mdir} and running prompt {prompt!r}...\n"
|
| 1159 |
-
)
|
| 1160 |
-
|
| 1161 |
-
def test_worker() -> None:
|
| 1162 |
-
try:
|
| 1163 |
-
import json
|
| 1164 |
-
import torch
|
| 1165 |
-
import torch.nn.functional as F
|
| 1166 |
-
from safetensors.torch import safe_open
|
| 1167 |
-
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
|
| 1168 |
-
|
| 1169 |
-
t0 = time.time()
|
| 1170 |
-
mpath = Path(mdir)
|
| 1171 |
-
if mpath.is_file() and mpath.suffix == ".safetensors":
|
| 1172 |
-
st_file = mpath
|
| 1173 |
-
base_dir = mpath.parent
|
| 1174 |
-
else:
|
| 1175 |
-
base_dir = mpath
|
| 1176 |
-
st_file = base_dir / "model.safetensors"
|
| 1177 |
-
if not st_file.exists():
|
| 1178 |
-
cands = sorted(base_dir.glob("*.safetensors"))
|
| 1179 |
-
if cands:
|
| 1180 |
-
st_file = cands[0]
|
| 1181 |
-
|
| 1182 |
-
cfg_file = base_dir / "config.json"
|
| 1183 |
-
raw_cfg = json.loads(cfg_file.read_text()) if cfg_file.exists() else {}
|
| 1184 |
-
if raw_cfg.get("model_type") == "deepseek_v41":
|
| 1185 |
-
decoded, out_list = run_deepseek_v41_generate(
|
| 1186 |
-
st_file,
|
| 1187 |
-
cfg_file,
|
| 1188 |
-
base_dir,
|
| 1189 |
-
prompt=prompt,
|
| 1190 |
-
max_new_tokens=max_new,
|
| 1191 |
-
use_chat_template=use_chat,
|
| 1192 |
-
device=self.device_var.get(),
|
| 1193 |
-
)
|
| 1194 |
-
dt_s = time.time() - t0
|
| 1195 |
-
self._queue.put(
|
| 1196 |
-
(
|
| 1197 |
-
"test_done",
|
| 1198 |
-
f"Completed in {dt_s:.2f}s:\n{decoded}\n\nToken IDs: {out_list}",
|
| 1199 |
-
)
|
| 1200 |
-
)
|
| 1201 |
-
return
|
| 1202 |
-
|
| 1203 |
-
tok = AutoTokenizer.from_pretrained(
|
| 1204 |
-
str(base_dir), trust_remote_code=True, local_files_only=True
|
| 1205 |
-
)
|
| 1206 |
-
cfg = AutoConfig.from_pretrained(
|
| 1207 |
-
str(base_dir), trust_remote_code=True, local_files_only=True
|
| 1208 |
-
)
|
| 1209 |
-
dev = "cuda:0" if torch.cuda.is_available() else "cpu"
|
| 1210 |
-
|
| 1211 |
-
# Fast on-demand expert streaming for MXFP8 MoE models, or standard load for generic models
|
| 1212 |
-
q_cfg = getattr(cfg, "quantization_config", None) or {}
|
| 1213 |
-
is_mxfp8 = (
|
| 1214 |
-
isinstance(q_cfg, dict) and q_cfg.get("quant_method") == "mxfp8"
|
| 1215 |
-
) or getattr(q_cfg, "quant_method", None) == "mxfp8"
|
| 1216 |
-
|
| 1217 |
-
if is_mxfp8 and st_file.exists():
|
| 1218 |
-
with torch.device("meta"):
|
| 1219 |
-
model = AutoModelForCausalLM.from_config(
|
| 1220 |
-
cfg, trust_remote_code=True, dtype=torch.bfloat16
|
| 1221 |
-
)
|
| 1222 |
-
sf = safe_open(str(st_file), framework="pt", device="cpu")
|
| 1223 |
-
for name, _ in list(model.named_parameters()):
|
| 1224 |
-
if ".moe.experts." in name:
|
| 1225 |
-
continue
|
| 1226 |
-
parts = name.split(".")
|
| 1227 |
-
mod = model
|
| 1228 |
-
for p in parts[:-1]:
|
| 1229 |
-
mod = getattr(mod, p)
|
| 1230 |
-
t = sf.get_tensor(name).to(device=dev)
|
| 1231 |
-
if t.dtype == torch.float32 and "e_score_correction_bias" not in name:
|
| 1232 |
-
t = t.to(torch.bfloat16)
|
| 1233 |
-
setattr(mod, parts[-1], torch.nn.Parameter(t, requires_grad=False))
|
| 1234 |
-
|
| 1235 |
-
moe_layer = next(
|
| 1236 |
-
(l for l in model.model.layers if getattr(l, "is_moe", False)),
|
| 1237 |
-
None,
|
| 1238 |
-
)
|
| 1239 |
-
if moe_layer is not None:
|
| 1240 |
-
mod_cls = type(moe_layer.moe)
|
| 1241 |
-
raon_mod = __import__(
|
| 1242 |
-
mod_cls.__module__, fromlist=["dequantize_mxfp8", "situ_glu"]
|
| 1243 |
-
)
|
| 1244 |
-
dequantize_mxfp8 = raon_mod.dequantize_mxfp8
|
| 1245 |
-
situ_glu = raon_mod.situ_glu
|
| 1246 |
-
for lidx, layer in enumerate(model.model.layers):
|
| 1247 |
-
if getattr(layer, "is_moe", False):
|
| 1248 |
-
layer.moe._layer_idx = lidx
|
| 1249 |
-
|
| 1250 |
-
def fast_moe_forward(self_moe, hidden: torch.Tensor) -> torch.Tensor:
|
| 1251 |
-
batch, seq, dim = hidden.shape
|
| 1252 |
-
flat = hidden.reshape(-1, dim)
|
| 1253 |
-
top, probs = self_moe.gate(flat)
|
| 1254 |
-
out = torch.zeros(
|
| 1255 |
-
flat.shape[0], dim, dtype=torch.float32, device=flat.device
|
| 1256 |
-
)
|
| 1257 |
-
hit = torch.bincount(
|
| 1258 |
-
top.flatten(), minlength=self_moe.num_experts
|
| 1259 |
-
)
|
| 1260 |
-
prefix = f"model.layers.{self_moe._layer_idx}.moe.experts"
|
| 1261 |
-
for expert_idx in hit.nonzero().flatten().tolist():
|
| 1262 |
-
rows, slot = torch.where(top == expert_idx)
|
| 1263 |
-
x = flat.index_select(0, rows)
|
| 1264 |
-
ep = f"{prefix}.{expert_idx}"
|
| 1265 |
-
gw = dequantize_mxfp8(
|
| 1266 |
-
sf.get_tensor(f"{ep}.gate_proj.weight").to(dev, non_blocking=True),
|
| 1267 |
-
sf.get_tensor(f"{ep}.gate_proj.weight_scale_inv").to(dev, non_blocking=True),
|
| 1268 |
-
x.dtype,
|
| 1269 |
-
)
|
| 1270 |
-
uw = dequantize_mxfp8(
|
| 1271 |
-
sf.get_tensor(f"{ep}.up_proj.weight").to(dev, non_blocking=True),
|
| 1272 |
-
sf.get_tensor(f"{ep}.up_proj.weight_scale_inv").to(dev, non_blocking=True),
|
| 1273 |
-
x.dtype,
|
| 1274 |
-
)
|
| 1275 |
-
dw = dequantize_mxfp8(
|
| 1276 |
-
sf.get_tensor(f"{ep}.down_proj.weight").to(dev, non_blocking=True),
|
| 1277 |
-
sf.get_tensor(f"{ep}.down_proj.weight_scale_inv").to(dev, non_blocking=True),
|
| 1278 |
-
x.dtype,
|
| 1279 |
-
)
|
| 1280 |
-
act = situ_glu(
|
| 1281 |
-
F.linear(x, gw),
|
| 1282 |
-
F.linear(x, uw),
|
| 1283 |
-
self_moe.gate_beta,
|
| 1284 |
-
self_moe.value_beta,
|
| 1285 |
-
).to(x.dtype)
|
| 1286 |
-
out.index_add_(
|
| 1287 |
-
0,
|
| 1288 |
-
rows,
|
| 1289 |
-
F.linear(act, dw).float()
|
| 1290 |
-
* probs[rows, slot].unsqueeze(-1),
|
| 1291 |
-
)
|
| 1292 |
-
out = out.to(hidden.dtype)
|
| 1293 |
-
if self_moe.shared_experts is not None:
|
| 1294 |
-
out = out + self_moe.shared_experts(flat)
|
| 1295 |
-
return out.reshape(batch, seq, dim)
|
| 1296 |
-
|
| 1297 |
-
mod_cls.forward = fast_moe_forward
|
| 1298 |
-
else:
|
| 1299 |
-
model = AutoModelForCausalLM.from_pretrained(
|
| 1300 |
-
mdir,
|
| 1301 |
-
trust_remote_code=True,
|
| 1302 |
-
local_files_only=True,
|
| 1303 |
-
dtype="auto",
|
| 1304 |
-
device_map="auto",
|
| 1305 |
-
)
|
| 1306 |
-
|
| 1307 |
-
model.eval()
|
| 1308 |
-
with torch.no_grad():
|
| 1309 |
-
if use_chat and getattr(tok, "chat_template", None):
|
| 1310 |
-
inputs = tok.apply_chat_template(
|
| 1311 |
-
[{"role": "user", "content": prompt}],
|
| 1312 |
-
add_generation_prompt=True,
|
| 1313 |
-
tokenize=True,
|
| 1314 |
-
return_dict=True,
|
| 1315 |
-
return_tensors="pt",
|
| 1316 |
-
enable_thinking=False,
|
| 1317 |
-
).to(dev)
|
| 1318 |
-
in_len = inputs["input_ids"].shape[-1]
|
| 1319 |
-
out_ids = model.generate(
|
| 1320 |
-
**inputs,
|
| 1321 |
-
max_new_tokens=max_new,
|
| 1322 |
-
do_sample=False,
|
| 1323 |
-
use_cache=True,
|
| 1324 |
-
pad_token_id=tok.eos_token_id,
|
| 1325 |
-
)
|
| 1326 |
-
decoded = tok.decode(out_ids[0][in_len:], skip_special_tokens=False)
|
| 1327 |
-
else:
|
| 1328 |
-
ids = tok(prompt, return_tensors="pt")["input_ids"].to(dev)
|
| 1329 |
-
out_ids = model.generate(
|
| 1330 |
-
ids,
|
| 1331 |
-
max_new_tokens=max_new,
|
| 1332 |
-
do_sample=False,
|
| 1333 |
-
use_cache=True,
|
| 1334 |
-
pad_token_id=tok.eos_token_id,
|
| 1335 |
-
)
|
| 1336 |
-
decoded = tok.decode(out_ids[0], skip_special_tokens=False)
|
| 1337 |
-
|
| 1338 |
-
dt_s = time.time() - t0
|
| 1339 |
-
self._queue.put(
|
| 1340 |
-
(
|
| 1341 |
-
"test_done",
|
| 1342 |
-
f"Completed in {dt_s:.2f}s:\n{decoded}\n\nToken IDs: {out_ids[0].tolist()}",
|
| 1343 |
-
)
|
| 1344 |
-
)
|
| 1345 |
-
except Exception as exc:
|
| 1346 |
-
self._queue.put(("test_done", f"Error: {exc}"))
|
| 1347 |
-
|
| 1348 |
-
threading.Thread(target=test_worker, daemon=True).start()
|
| 1349 |
-
|
| 1350 |
-
def _poll_queue(self) -> None:
|
| 1351 |
-
try:
|
| 1352 |
-
while True:
|
| 1353 |
-
kind, payload = self._queue.get_nowait()
|
| 1354 |
-
if kind == "progress":
|
| 1355 |
-
done, total, tname, action, stats = payload
|
| 1356 |
-
pct = 100.0 * float(done) / float(max(total, 1))
|
| 1357 |
-
self.progress_var.set(pct)
|
| 1358 |
-
self.tele_tensor_var.set(tname)
|
| 1359 |
-
self.tele_action_var.set(action)
|
| 1360 |
-
self.tele_progress_text_var.set(f"{done} / {total} ({pct:.1f}%)")
|
| 1361 |
-
elapsed = max(time.time() - (self._start_time or time.time()), 1.0e-3)
|
| 1362 |
-
rate = float(done) / elapsed
|
| 1363 |
-
eta = float(max(total - done, 0)) / max(rate, 1.0e-6)
|
| 1364 |
-
self.tele_speed_var.set(f"{rate:.1f} ten/s (ETA {_fmt_eta(eta)})")
|
| 1365 |
-
self.tele_elapsed_var.set(_fmt_eta(elapsed))
|
| 1366 |
-
if "present" in stats:
|
| 1367 |
-
self.tele_breakdown_var.set(
|
| 1368 |
-
f"present={stats.get('present', 0)} | "
|
| 1369 |
-
f"layer_interp={stats.get('checkfree_interpolated', 0)} | "
|
| 1370 |
-
f"expert_interp={stats.get('expert_interpolated', 0)} | "
|
| 1371 |
-
f"synth={stats.get('synthesized', 0)}"
|
| 1372 |
-
)
|
| 1373 |
-
if self.tree.exists(tname):
|
| 1374 |
-
vals = list(self.tree.item(tname, "values"))
|
| 1375 |
-
vals[-1] = "Done"
|
| 1376 |
-
self.tree.item(tname, values=vals)
|
| 1377 |
-
elif kind == "set_test_dir":
|
| 1378 |
-
self.test_model_dir_var.set(str(payload))
|
| 1379 |
-
elif kind == "hf_fetched":
|
| 1380 |
-
mdir, res = payload
|
| 1381 |
-
sh_paths = res.get("shard_paths", [])
|
| 1382 |
-
if sh_paths:
|
| 1383 |
-
self._set_shard_and_companions(Path(sh_paths[0]))
|
| 1384 |
-
self.shard_var.set(", ".join(str(p) for p in sh_paths))
|
| 1385 |
-
self.op_mode_var.set("recover")
|
| 1386 |
-
self._inspect_plan()
|
| 1387 |
-
elif kind == "done":
|
| 1388 |
-
title, stats = payload
|
| 1389 |
-
elapsed = time.time() - (self._start_time or time.time())
|
| 1390 |
-
self.progress_var.set(100.0)
|
| 1391 |
-
self.tele_action_var.set("Completed")
|
| 1392 |
-
self.tele_elapsed_var.set(_fmt_eta(elapsed))
|
| 1393 |
-
self.run_btn.configure(state=tk.NORMAL)
|
| 1394 |
-
self.stop_btn.configure(state=tk.DISABLED)
|
| 1395 |
-
self._log(f"{title} in {_fmt_eta(elapsed)}: {stats}")
|
| 1396 |
-
elif kind == "error":
|
| 1397 |
-
self.tele_action_var.set("Error / Stopped")
|
| 1398 |
-
self.run_btn.configure(state=tk.NORMAL)
|
| 1399 |
-
self.stop_btn.configure(state=tk.DISABLED)
|
| 1400 |
-
self._log(f"ERROR: {payload}")
|
| 1401 |
-
messagebox.showerror("SlimShard Error", str(payload))
|
| 1402 |
-
elif kind == "test_done":
|
| 1403 |
-
self.test_btn.configure(state=tk.NORMAL)
|
| 1404 |
-
self.test_out_text.delete("1.0", tk.END)
|
| 1405 |
-
self.test_out_text.insert(tk.END, str(payload))
|
| 1406 |
-
self._log("Prompt evaluation finished.")
|
| 1407 |
-
except queue.Empty:
|
| 1408 |
-
pass
|
| 1409 |
-
self.root.after(80, self._poll_queue)
|
| 1410 |
-
|
| 1411 |
-
|
| 1412 |
-
def launch_slimshard_gui(parent: tk.Tk | None = None) -> SlimShardGUI:
|
| 1413 |
-
if parent is not None:
|
| 1414 |
-
win = tk.Toplevel(parent)
|
| 1415 |
-
return SlimShardGUI(win)
|
| 1416 |
-
root = tk.Tk()
|
| 1417 |
-
app = SlimShardGUI(root)
|
| 1418 |
-
root.mainloop()
|
| 1419 |
-
return app
|
| 1420 |
-
|
| 1421 |
-
|
| 1422 |
-
if __name__ == "__main__":
|
| 1423 |
-
launch_slimshard_gui()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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