yujiepan commited on
Commit
bb7473f
Β·
1 Parent(s): 58cfe8f

Add download progress logging and compact UI with tabs

Browse files
Files changed (1) hide show
  1. app.py +101 -55
app.py CHANGED
@@ -3,6 +3,10 @@ import tempfile
3
  import os
4
  import glob
5
  import shutil
 
 
 
 
6
 
7
  import gradio as gr
8
  import torch
@@ -10,13 +14,27 @@ from huggingface_hub import hf_hub_download, scan_cache_dir
10
  from safetensors import safe_open
11
 
12
 
13
- def get_param(model_id: str, param_key: str):
14
  """
15
  Download and return a specific parameter tensor from a Hugging Face model.
16
  """
17
  # Try to download the index file (for sharded models)
18
  try:
19
- index_path = hf_hub_download(model_id, "model.safetensors.index.json")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  with open(index_path, "r", encoding="utf-8") as f:
21
  index = json.load(f)
22
  weight_map = index["weight_map"]
@@ -25,13 +43,34 @@ def get_param(model_id: str, param_key: str):
25
  f"Parameter '{param_key}' not found in model. Available keys: {list(weight_map.keys())[:10]}..."
26
  )
27
  shard_file = weight_map[param_key]
28
- except Exception:
29
- shard_file = "model.safetensors"
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
- shard_path = hf_hub_download(model_id, shard_file)
 
 
32
 
 
 
 
 
33
  with safe_open(shard_path, framework="pt") as f:
34
  tensor = f.get_tensor(param_key)
 
 
35
 
36
  return tensor
37
 
@@ -67,16 +106,23 @@ def format_tensor_info(tensor: torch.Tensor) -> str:
67
  return "<br>".join(info)
68
 
69
 
70
- def fetch_param(model_id: str, param_key: str):
71
  """Fetch parameter and return formatted info and tensor preview."""
 
 
72
  if not model_id or not param_key:
73
- return "Please provide both model ID and parameter key.", "", None
74
 
75
  try:
76
- tensor = get_param(model_id, param_key)
 
 
 
 
77
  info = format_tensor_info(tensor)
78
 
79
  # Create tensor preview (first few elements)
 
80
  flat = tensor.flatten()
81
  preview_size = min(100, flat.numel())
82
  preview = flat[:preview_size].tolist()
@@ -86,14 +132,19 @@ def fetch_param(model_id: str, param_key: str):
86
  preview_str += f"\n\n... and {flat.numel() - preview_size:,} more values"
87
 
88
  # Save tensor for download
 
89
  temp_dir = tempfile.gettempdir()
90
  safe_param_key = param_key.replace("/", "_").replace(".", "_")
91
  download_path = os.path.join(temp_dir, f"{safe_param_key}.pt")
92
  torch.save(tensor, download_path)
 
93
 
94
- return info, preview_str, download_path
 
 
95
  except Exception as e:
96
- return f"**Error:** {str(e)}", "", None
 
97
 
98
 
99
  def list_keys(model_id: str):
@@ -123,7 +174,7 @@ def clear_temp_files():
123
  deleted_files.append(os.path.basename(file))
124
  except Exception:
125
  pass
126
-
127
  if deleted_files:
128
  files_list = "\n".join(deleted_files)
129
  return f"βœ… Cleared {count} temporary file(s):\n\n{files_list}"
@@ -139,10 +190,10 @@ def clear_hf_cache():
139
  cache_info = scan_cache_dir()
140
  total_size = cache_info.size_on_disk
141
  total_repos = len(cache_info.repos)
142
-
143
  if total_repos == 0:
144
  return "βœ… HuggingFace cache is already empty"
145
-
146
  # Get cache directory and clear it
147
  cache_dir = os.path.expanduser("~/.cache/huggingface/hub")
148
  if os.path.exists(cache_dir):
@@ -162,9 +213,10 @@ def get_cache_info():
162
  # Temp files
163
  temp_dir = tempfile.gettempdir()
164
  pt_files = glob.glob(os.path.join(temp_dir, "*.pt"))
165
- temp_size = sum(os.path.getsize(f) for f in pt_files if os.path.exists(f))
 
166
  temp_size_mb = temp_size / (1024 * 1024)
167
-
168
  # HF cache
169
  try:
170
  cache_info = scan_cache_dir()
@@ -173,7 +225,7 @@ def get_cache_info():
173
  except Exception:
174
  hf_size_mb = 0
175
  hf_repos = 0
176
-
177
  info = f"πŸ“Š Cache Info:\n\n"
178
  info += f"Temp .pt files: {len(pt_files)} file(s), {temp_size_mb:.2f} MB\n"
179
  info += f"HuggingFace cache: {hf_repos} repo(s), {hf_size_mb:.2f} MB\n"
@@ -188,31 +240,27 @@ custom_css = """
188
  * {
189
  font-family: Consolas, Monaco, 'Courier New', monospace !important;
190
  }
 
 
 
191
  """
192
 
193
  with gr.Blocks(title="HuggingFace Model Weight Inspector") as demo:
194
- gr.Markdown(
195
- """
196
- # πŸ” HuggingFace Model Weight Inspector
197
-
198
- Inspect specific parameter tensors from any HuggingFace model without downloading the entire model.
199
- """
200
- )
201
 
202
  with gr.Row():
203
  model_id_input = gr.Textbox(
204
  label="Model ID",
205
  placeholder="e.g., meta-llama/Llama-2-7b-hf",
206
  value="zai-org/GLM-5",
 
207
  )
208
-
209
- with gr.Row():
210
- list_keys_btn = gr.Button("πŸ“‹ List Available Keys", variant="secondary")
211
 
212
  keys_output = gr.Textbox(
213
  label="Available Parameter Keys",
214
- lines=5,
215
- max_lines=10,
216
  )
217
 
218
  with gr.Row():
@@ -220,30 +268,28 @@ with gr.Blocks(title="HuggingFace Model Weight Inspector") as demo:
220
  label="Parameter Key",
221
  placeholder="e.g., model.embed_tokens.weight",
222
  value="model.layers.5.mlp.gate.e_score_correction_bias",
 
223
  )
224
-
225
- with gr.Row():
226
- fetch_btn = gr.Button("πŸ”Ž Fetch Parameter", variant="primary")
227
-
228
- with gr.Row():
229
- with gr.Column():
230
- info_output = gr.Markdown(label="Tensor Info")
231
- with gr.Column():
232
- preview_output = gr.Markdown(label="Tensor Preview")
233
-
234
- with gr.Row():
235
- download_output = gr.File(label="Download Tensor (.pt file)")
236
-
237
- with gr.Row():
238
- with gr.Column():
239
- clear_temp_btn = gr.Button("πŸ—‘οΈ Clear Temp Files", variant="secondary")
240
- with gr.Column():
241
- clear_hf_btn = gr.Button("πŸ—‘οΈ Clear HF Cache", variant="secondary")
242
- with gr.Column():
243
- get_info_btn = gr.Button("πŸ“Š Get Cache Info", variant="secondary")
244
-
245
- with gr.Row():
246
- clear_status = gr.Textbox(label="Status", interactive=False, lines=5)
247
 
248
  # Event handlers
249
  list_keys_btn.click(
@@ -255,21 +301,21 @@ with gr.Blocks(title="HuggingFace Model Weight Inspector") as demo:
255
  fetch_btn.click(
256
  fn=fetch_param,
257
  inputs=[model_id_input, param_key_input],
258
- outputs=[info_output, preview_output, download_output],
259
  )
260
-
261
  clear_temp_btn.click(
262
  fn=clear_temp_files,
263
  inputs=[],
264
  outputs=[clear_status],
265
  )
266
-
267
  clear_hf_btn.click(
268
  fn=clear_hf_cache,
269
  inputs=[],
270
  outputs=[clear_status],
271
  )
272
-
273
  get_info_btn.click(
274
  fn=get_cache_info,
275
  inputs=[],
 
3
  import os
4
  import glob
5
  import shutil
6
+ import logging
7
+ import io
8
+ import sys
9
+ from contextlib import redirect_stdout, redirect_stderr
10
 
11
  import gradio as gr
12
  import torch
 
14
  from safetensors import safe_open
15
 
16
 
17
+ def get_param(model_id: str, param_key: str, log_buffer: io.StringIO, progress: gr.Progress):
18
  """
19
  Download and return a specific parameter tensor from a Hugging Face model.
20
  """
21
  # Try to download the index file (for sharded models)
22
  try:
23
+ log_buffer.write(f"πŸ“₯ Downloading index file for {model_id}...\n")
24
+ progress(0.1, desc="Downloading index...")
25
+
26
+ # Capture tqdm output from stderr
27
+ stderr_capture = io.StringIO()
28
+ with redirect_stderr(stderr_capture):
29
+ index_path = hf_hub_download(
30
+ model_id, "model.safetensors.index.json")
31
+
32
+ stderr_output = stderr_capture.getvalue()
33
+ if stderr_output:
34
+ log_buffer.write(stderr_output + "\n")
35
+
36
+ log_buffer.write(f"βœ“ Index file found: {index_path}\n")
37
+
38
  with open(index_path, "r", encoding="utf-8") as f:
39
  index = json.load(f)
40
  weight_map = index["weight_map"]
 
43
  f"Parameter '{param_key}' not found in model. Available keys: {list(weight_map.keys())[:10]}..."
44
  )
45
  shard_file = weight_map[param_key]
46
+ log_buffer.write(f"βœ“ Parameter found in shard: {shard_file}\n")
47
+ except Exception as e:
48
+ if "404" in str(e) or "not found" in str(e).lower():
49
+ log_buffer.write("ℹ️ No index file, trying single model file...\n")
50
+ shard_file = "model.safetensors"
51
+ else:
52
+ raise
53
+
54
+ log_buffer.write(f"πŸ“₯ Downloading shard: {shard_file}...\n")
55
+ progress(0.3, desc=f"Downloading {shard_file}...")
56
+
57
+ # Capture download progress
58
+ stderr_capture = io.StringIO()
59
+ with redirect_stderr(stderr_capture):
60
+ shard_path = hf_hub_download(model_id, shard_file)
61
 
62
+ stderr_output = stderr_capture.getvalue()
63
+ if stderr_output:
64
+ log_buffer.write(stderr_output + "\n")
65
 
66
+ log_buffer.write(f"βœ“ Shard downloaded: {shard_path}\n")
67
+ progress(0.7, desc="Loading tensor...")
68
+
69
+ log_buffer.write(f"πŸ” Loading tensor '{param_key}'...\n")
70
  with safe_open(shard_path, framework="pt") as f:
71
  tensor = f.get_tensor(param_key)
72
+ log_buffer.write(f"βœ“ Tensor loaded successfully\n")
73
+ progress(0.9, desc="Finalizing...")
74
 
75
  return tensor
76
 
 
106
  return "<br>".join(info)
107
 
108
 
109
+ def fetch_param(model_id: str, param_key: str, progress=gr.Progress()):
110
  """Fetch parameter and return formatted info and tensor preview."""
111
+ log_buffer = io.StringIO()
112
+
113
  if not model_id or not param_key:
114
+ return "Please provide both model ID and parameter key.", "", None, "❌ Missing required inputs"
115
 
116
  try:
117
+ log_buffer.write(f"πŸš€ Starting download for {model_id}\n")
118
+ log_buffer.write(f"🎯 Target parameter: {param_key}\n\n")
119
+ progress(0, desc="Initializing...")
120
+
121
+ tensor = get_param(model_id, param_key, log_buffer, progress)
122
  info = format_tensor_info(tensor)
123
 
124
  # Create tensor preview (first few elements)
125
+ log_buffer.write(f"\nπŸ“Š Creating preview...\n")
126
  flat = tensor.flatten()
127
  preview_size = min(100, flat.numel())
128
  preview = flat[:preview_size].tolist()
 
132
  preview_str += f"\n\n... and {flat.numel() - preview_size:,} more values"
133
 
134
  # Save tensor for download
135
+ log_buffer.write(f"πŸ’Ύ Saving tensor for download...\n")
136
  temp_dir = tempfile.gettempdir()
137
  safe_param_key = param_key.replace("/", "_").replace(".", "_")
138
  download_path = os.path.join(temp_dir, f"{safe_param_key}.pt")
139
  torch.save(tensor, download_path)
140
+ log_buffer.write(f"βœ“ Saved to: {download_path}\n")
141
 
142
+ progress(1.0, desc="Complete!")
143
+ log_buffer.write(f"\nβœ… All operations completed successfully!\n")
144
+ return info, preview_str, download_path, log_buffer.getvalue()
145
  except Exception as e:
146
+ log_buffer.write(f"\n❌ Error: {str(e)}\n")
147
+ return f"**Error:** {str(e)}", "", None, log_buffer.getvalue()
148
 
149
 
150
  def list_keys(model_id: str):
 
174
  deleted_files.append(os.path.basename(file))
175
  except Exception:
176
  pass
177
+
178
  if deleted_files:
179
  files_list = "\n".join(deleted_files)
180
  return f"βœ… Cleared {count} temporary file(s):\n\n{files_list}"
 
190
  cache_info = scan_cache_dir()
191
  total_size = cache_info.size_on_disk
192
  total_repos = len(cache_info.repos)
193
+
194
  if total_repos == 0:
195
  return "βœ… HuggingFace cache is already empty"
196
+
197
  # Get cache directory and clear it
198
  cache_dir = os.path.expanduser("~/.cache/huggingface/hub")
199
  if os.path.exists(cache_dir):
 
213
  # Temp files
214
  temp_dir = tempfile.gettempdir()
215
  pt_files = glob.glob(os.path.join(temp_dir, "*.pt"))
216
+ temp_size = sum(os.path.getsize(f)
217
+ for f in pt_files if os.path.exists(f))
218
  temp_size_mb = temp_size / (1024 * 1024)
219
+
220
  # HF cache
221
  try:
222
  cache_info = scan_cache_dir()
 
225
  except Exception:
226
  hf_size_mb = 0
227
  hf_repos = 0
228
+
229
  info = f"πŸ“Š Cache Info:\n\n"
230
  info += f"Temp .pt files: {len(pt_files)} file(s), {temp_size_mb:.2f} MB\n"
231
  info += f"HuggingFace cache: {hf_repos} repo(s), {hf_size_mb:.2f} MB\n"
 
240
  * {
241
  font-family: Consolas, Monaco, 'Courier New', monospace !important;
242
  }
243
+ .compact-row {
244
+ gap: 0.5rem !important;
245
+ }
246
  """
247
 
248
  with gr.Blocks(title="HuggingFace Model Weight Inspector") as demo:
249
+ gr.Markdown("# πŸ” HuggingFace Model Weight Inspector")
 
 
 
 
 
 
250
 
251
  with gr.Row():
252
  model_id_input = gr.Textbox(
253
  label="Model ID",
254
  placeholder="e.g., meta-llama/Llama-2-7b-hf",
255
  value="zai-org/GLM-5",
256
+ scale=4,
257
  )
258
+ list_keys_btn = gr.Button("πŸ“‹ List Keys", variant="secondary", scale=1)
 
 
259
 
260
  keys_output = gr.Textbox(
261
  label="Available Parameter Keys",
262
+ lines=3,
263
+ max_lines=8,
264
  )
265
 
266
  with gr.Row():
 
268
  label="Parameter Key",
269
  placeholder="e.g., model.embed_tokens.weight",
270
  value="model.layers.5.mlp.gate.e_score_correction_bias",
271
+ scale=4,
272
  )
273
+ fetch_btn = gr.Button("πŸ”Ž Fetch", variant="primary", scale=1)
274
+
275
+ with gr.Tabs():
276
+ with gr.Tab("Tensor Info"):
277
+ with gr.Row():
278
+ with gr.Column():
279
+ info_output = gr.Markdown()
280
+ with gr.Column():
281
+ preview_output = gr.Markdown()
282
+
283
+ with gr.Tab("Download & Logs"):
284
+ download_output = gr.File(label="Download Tensor (.pt file)")
285
+ log_output = gr.Textbox(label="πŸ“‹ Download Log", lines=6, interactive=False)
286
+
287
+ with gr.Tab("Cache Management"):
288
+ with gr.Row():
289
+ clear_temp_btn = gr.Button("πŸ—‘οΈ Temp", variant="secondary", scale=1)
290
+ clear_hf_btn = gr.Button("πŸ—‘οΈ HF Cache", variant="secondary", scale=1)
291
+ get_info_btn = gr.Button("πŸ“Š Info", variant="secondary", scale=1)
292
+ clear_status = gr.Textbox(label="Status", interactive=False, lines=4)
 
 
 
293
 
294
  # Event handlers
295
  list_keys_btn.click(
 
301
  fetch_btn.click(
302
  fn=fetch_param,
303
  inputs=[model_id_input, param_key_input],
304
+ outputs=[info_output, preview_output, download_output, log_output],
305
  )
306
+
307
  clear_temp_btn.click(
308
  fn=clear_temp_files,
309
  inputs=[],
310
  outputs=[clear_status],
311
  )
312
+
313
  clear_hf_btn.click(
314
  fn=clear_hf_cache,
315
  inputs=[],
316
  outputs=[clear_status],
317
  )
318
+
319
  get_info_btn.click(
320
  fn=get_cache_info,
321
  inputs=[],