codemichaeld commited on
Commit
6bb3534
Β·
verified Β·
1 Parent(s): 9310eed

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +749 -653
app.py CHANGED
@@ -1,709 +1,805 @@
1
-
2
  import gradio as gr
3
  import os
 
4
  import tempfile
5
  import shutil
6
  import re
7
  import json
8
- from pathlib import Path
9
- from huggingface_hub import HfApi, hf_hub_download, snapshot_download, list_repo_files
10
- from safetensors.torch import load_file, save_file
11
- import torch
12
- import torch.nn.functional as F
13
  import traceback
14
  import glob
15
- import time
 
16
  from concurrent.futures import ThreadPoolExecutor, as_completed
17
- try:
18
- from modelscope.hub.file_download import model_file_download as ms_file_download
19
- from modelscope.hub.api import HubApi as ModelScopeApi
20
- MODELScope_AVAILABLE = True
21
- except ImportError:
22
- MODELScope_AVAILABLE = False
23
-
24
- def load_model_files(model_paths, model_format="safetensors", progress_callback=None):
25
- """
26
- Load model weights from one or more files, supporting sharded safetensors and other formats.
27
- """
28
- state_dict = {}
29
-
30
- if model_format == "safetensors":
31
- # Handle sharded safetensors files
32
- for i, path in enumerate(model_paths):
33
- if progress_callback:
34
- progress_callback(f"Loading shard {i+1}/{len(model_paths)}: {os.path.basename(path)}")
35
- part_dict = load_file(path)
36
- state_dict.update(part_dict)
37
- elif model_format in ["pth", "pt"]:
38
- # PyTorch checkpoint files
39
- for i, path in enumerate(model_paths):
40
- if progress_callback:
41
- progress_callback(f"Loading checkpoint {i+1}/{len(model_paths)}: {os.path.basename(path)}")
42
- checkpoint = torch.load(path, map_location="cpu")
43
- if isinstance(checkpoint, dict):
44
- # Try to extract state dict from checkpoint
45
- if "state_dict" in checkpoint:
46
- state_dict.update(checkpoint["state_dict"])
47
- elif "model_state_dict" in checkpoint:
48
- state_dict.update(checkpoint["model_state_dict"])
49
- elif "model" in checkpoint and isinstance(checkpoint["model"], dict):
50
- state_dict.update(checkpoint["model"])
51
- else:
52
- # Assume the checkpoint itself is the state dict
53
- state_dict.update(checkpoint)
54
- elif model_format == "ckpt":
55
- # Checkpoint files (similar to pth)
56
- for i, path in enumerate(model_paths):
57
- if progress_callback:
58
- progress_callback(f"Loading checkpoint {i+1}/{len(model_paths)}: {os.path.basename(path)}")
59
- checkpoint = torch.load(path, map_location="cpu")
60
- if isinstance(checkpoint, dict):
61
- if "state_dict" in checkpoint:
62
- state_dict.update(checkpoint["state_dict"])
63
- elif "model_state_dict" in checkpoint:
64
- state_dict.update(checkpoint["model_state_dict"])
65
- elif "model" in checkpoint and isinstance(checkpoint["model"], dict):
66
- state_dict.update(checkpoint["model"])
67
- else:
68
- state_dict.update(checkpoint)
69
-
70
- return state_dict
71
-
72
- def read_model_metadata(model_paths, model_format="safetensors"):
73
- """Read metadata from model files."""
74
- metadata = {}
75
-
76
- if model_format == "safetensors":
77
- # Read metadata from the first safetensors file
78
- if model_paths:
79
- with open(model_paths[0], 'rb') as f:
80
- header_size = int.from_bytes(f.read(8), 'little')
81
- header_json = f.read(header_size).decode('utf-8')
82
- header = json.loads(header_json)
83
- metadata = header.get('__metadata__', {})
84
- elif model_format in ["pth", "pt", "ckpt"]:
85
- # Try to extract metadata from checkpoint files
86
- if model_paths:
87
- checkpoint = torch.load(model_paths[0], map_location="cpu")
88
- if isinstance(checkpoint, dict):
89
- # Look for common metadata keys
90
- for key in ["hyperparameters", "args", "config", "metadata"]:
91
- if key in checkpoint:
92
- metadata[key] = checkpoint[key]
93
-
94
- return metadata
95
-
96
- def extract_base_name_from_sharded_files(model_paths):
97
- """Extract a common base name from sharded files."""
98
- if not model_paths:
99
- return "model"
100
-
101
- if len(model_paths) == 1:
102
- # Single file case
103
- base_name = os.path.splitext(os.path.basename(model_paths[0]))[0]
104
- # Remove common suffixes
105
- for suffix in ["-fp8", "-fp16", "-bf16", "-32", "-16"]:
106
- if base_name.endswith(suffix):
107
- base_name = base_name[:-len(suffix)]
108
- return base_name
109
-
110
- # Multiple files case - find common prefix
111
- base_names = [os.path.splitext(os.path.basename(p))[0] for p in model_paths]
112
-
113
- # Handle Hugging Face pattern: model-00001-of-00002.safetensors
114
- # Extract the part before the shard numbering
115
- if all("-of-" in name for name in base_names):
116
- # All files follow the "model-XXXXX-of-YYYYY" pattern
117
- common_parts = []
118
- for name in base_names:
119
- # Split at the shard numbering
120
- parts = name.split("-")
121
- if len(parts) >= 3 and parts[-2].isdigit() and parts[-1].startswith("of"):
122
- # Remove the last two parts (shard number and total)
123
- common_part = "-".join(parts[:-2])
124
- common_parts.append(common_part)
125
- else:
126
- common_parts.append(name)
127
-
128
- # Use the most common base name
129
- from collections import Counter
130
- base_name = Counter(common_parts).most_common(1)[0][0]
131
- return base_name
132
-
133
- # Fallback: find common prefix
134
- common_prefix = ""
135
- for chars in zip(*base_names):
136
- if len(set(chars)) == 1:
137
- common_prefix += chars[0]
138
- else:
139
- break
140
-
141
- # Clean up the common prefix
142
- base_name = re.sub(r'[-_]+$', '', common_prefix)
143
- if not base_name:
144
- base_name = "model"
145
-
146
- return base_name
147
-
148
- def convert_model_to_fp8(model_paths, output_dir, fp8_format,
149
- model_format="safetensors", progress=gr.Progress()):
150
- """Simple and fast FP8 conversion without recovery strategies."""
151
- progress(0.05, desc=f"Starting FP8 conversion for {model_format}...")
152
- try:
153
- metadata = read_model_metadata(model_paths, model_format)
154
- progress(0.1, desc="Loaded metadata.")
155
-
156
- # Load model with progress tracking
157
- state_dict = load_model_files(
158
- model_paths,
159
- model_format,
160
- progress_callback=lambda msg: progress(0.15, desc=msg)
161
- )
162
- progress(0.25, desc=f"Loaded {len(model_paths)} model files with {len(state_dict)} tensors.")
163
-
164
- # Setup FP8 format
165
- fp8_dtype = torch.float8_e5m2 if fp8_format == "e5m2" else torch.float8_e4m3fn
166
-
167
- # Initialize outputs
168
- sd_fp8 = {}
169
- conversion_stats = {
170
- "total_tensors": len(state_dict),
171
- "converted_tensors": 0,
172
- "skipped_tensors": 0,
173
- "skipped_reasons": []
174
- }
175
-
176
- # Process each tensor
177
- total = len(state_dict)
178
- for i, key in enumerate(state_dict):
179
- if i % 100 == 0: # Update progress every 100 tensors for speed
180
- progress(0.3 + 0.6 * (i / total), desc=f"Converting {i}/{total} tensors...")
181
-
182
- weight = state_dict[key]
183
-
184
- # Convert only float tensors to FP8
185
- if weight.dtype in [torch.float16, torch.float32, torch.bfloat16]:
186
- fp8_weight = weight.to(fp8_dtype)
187
- sd_fp8[key] = fp8_weight
188
- conversion_stats["converted_tensors"] += 1
189
- else:
190
- # Keep non-float tensors as-is (e.g., ints, bools)
191
- sd_fp8[key] = weight
192
- conversion_stats["skipped_tensors"] += 1
193
- conversion_stats["skipped_reasons"].append(f"{key}: {weight.dtype}")
194
-
195
- # Extract base name for output files
196
- base_name = extract_base_name_from_sharded_files(model_paths)
197
-
198
- # Save FP8 model
199
- fp8_path = os.path.join(output_dir, f"{base_name}-fp8-{fp8_format}.safetensors")
200
- save_file(sd_fp8, fp8_path, metadata={
201
- "format": model_format,
202
- "fp8_format": fp8_format,
203
- "original_files": str(len(model_paths)),
204
- "conversion_stats": json.dumps(conversion_stats),
205
- **metadata
206
- })
207
-
208
- progress(0.95, desc="Saved FP8 file.")
209
-
210
- # Generate stats message
211
- stats_msg = f"βœ… FP8 ({fp8_format}) conversion complete!\n"
212
- stats_msg += f"- Total tensors: {conversion_stats['total_tensors']}\n"
213
- stats_msg += f"- Converted to FP8: {conversion_stats['converted_tensors']}\n"
214
- stats_msg += f"- Skipped (non-float): {conversion_stats['skipped_tensors']}\n"
215
- stats_msg += f"- Output file: {os.path.basename(fp8_path)}\n"
216
-
217
- if conversion_stats["skipped_tensors"] > 0:
218
- stats_msg += "\n⚠️ Some tensors were skipped (non-float types):\n"
219
- for i, reason in enumerate(conversion_stats["skipped_reasons"][:5]): # Show first 5
220
- stats_msg += f" - {reason}\n"
221
- if len(conversion_stats["skipped_reasons"]) > 5:
222
- stats_msg += f" - ... and {len(conversion_stats['skipped_reasons']) - 5} more\n"
223
-
224
- progress(1.0, desc="βœ… FP8 conversion complete!")
225
- return True, stats_msg, conversion_stats, fp8_path, None
226
 
227
- except Exception as e:
228
- traceback.print_exc()
229
- return False, str(e), None, None, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230
 
231
- def parse_hf_url(url):
 
 
 
 
232
  url = url.strip().rstrip("/")
233
- if not url.startswith("https://huggingface.co/"):
234
- raise ValueError("URL must start with https://huggingface.co/")
235
- path = url.replace("https://huggingface.co/", "")
 
 
236
  parts = path.split("/")
237
  if len(parts) < 2:
238
- raise ValueError("Invalid repo format")
239
  repo_id = "/".join(parts[:2])
240
  subfolder = ""
241
  if len(parts) > 3 and parts[2] == "tree":
242
- subfolder = "/".join(parts[4:]) if len(parts) > 4 else ""
243
  elif len(parts) > 2:
244
  subfolder = "/".join(parts[2:])
245
  return repo_id, subfolder
246
 
247
- def download_single_file(args):
248
- """Helper function for parallel downloads."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
249
  repo_id, filename, subfolder, cache_dir, token = args
250
  try:
251
- path = hf_hub_download(
252
  repo_id=repo_id,
253
  filename=filename,
254
- subfolder=subfolder,
255
  cache_dir=cache_dir,
256
  token=token,
257
- resume_download=True
258
  )
259
- return path, None
260
  except Exception as e:
261
  return None, str(e)
262
 
263
- def find_sharded_safetensors_files(repo_id, subfolder=None, hf_token=None, max_shards=50):
264
- """Find all sharded safetensors files in a repository."""
265
- try:
266
- # List all files in the repository
267
- repo_files = list_repo_files(repo_id, repo_type="model", token=hf_token)
268
-
269
- # Filter for safetensors files in the subfolder
270
- if subfolder:
271
- pattern = f"{subfolder}/" if not subfolder.endswith("/") else subfolder
272
- safetensors_files = [f for f in repo_files if f.endswith('.safetensors') and f.startswith(pattern)]
273
- # Remove subfolder prefix
274
- safetensors_files = [f[len(pattern):] for f in safetensors_files if len(f) > len(pattern)]
275
- else:
276
- safetensors_files = [f for f in repo_files if f.endswith('.safetensors')]
277
-
278
- # Check if files follow sharding pattern
279
- sharded_files = []
280
- single_files = []
281
-
282
- for f in safetensors_files:
283
- # Check for sharding pattern: model-XXXXX-of-YYYYY.safetensors
284
- match = re.search(r'-\d{5}-of-\d{5}\.safetensors$', f)
285
- if match:
286
- sharded_files.append(f)
287
- else:
288
- single_files.append(f)
289
-
290
- # If we have sharded files, return them sorted by shard number
291
- if sharded_files:
292
- # Sort by shard number for consistent ordering
293
- def extract_shard_num(filename):
294
- match = re.search(r'-(\d{5})-of-\d{5}\.safetensors$', filename)
295
- return int(match.group(1)) if match else 0
296
-
297
- sharded_files.sort(key=extract_shard_num)
298
- # Limit number of shards to prevent accidental downloads of huge models
299
- if len(sharded_files) > max_shards:
300
- raise ValueError(f"Too many shards found ({len(sharded_files)}). Maximum allowed is {max_shards}. "
301
- f"Please specify a more specific pattern.")
302
- return sharded_files
303
- elif single_files:
304
- # Return single files (non-sharded)
305
- return single_files
306
- else:
307
- return []
308
-
309
- except Exception as e:
310
- print(f"Error listing repository files: {e}")
311
- return []
312
 
313
- def download_model_files(source_type, repo_url, filename_pattern, model_format, hf_token=None, progress=gr.Progress()):
314
- temp_dir = tempfile.mkdtemp()
 
 
 
 
 
 
 
 
315
  try:
316
- if source_type == "huggingface":
317
- repo_id, subfolder = parse_hf_url(repo_url)
318
-
319
- if model_format == "safetensors":
320
- # Handle different patterns for safetensors
321
- if filename_pattern == "auto" or filename_pattern == "":
322
- # Auto-detect sharded files
323
- progress(0.1, desc="Discovering model files...")
324
- found_files = find_sharded_safetensors_files(repo_id, subfolder, hf_token)
325
- if not found_files:
326
- raise ValueError("No safetensors files found in repository")
327
-
328
- progress(0.2, desc=f"Found {len(found_files)} shard(s). Downloading...")
329
-
330
- # Download files in parallel for better performance
331
- model_paths = []
332
- download_args = [
333
- (repo_id, filename, subfolder, temp_dir, hf_token)
334
- for filename in found_files
335
- ]
336
-
337
- with ThreadPoolExecutor(max_workers=4) as executor:
338
- futures = {executor.submit(download_single_file, args): args[1] for args in download_args}
339
-
340
- for i, future in enumerate(as_completed(futures)):
341
- filename = futures[future]
342
- try:
343
- path, error = future.result()
344
- if error:
345
- raise Exception(f"Failed to download {filename}: {error}")
346
- model_paths.append(path)
347
- progress(0.2 + 0.6 * (i + 1) / len(futures),
348
- desc=f"Downloaded {i+1}/{len(futures)}: {filename}")
349
- except Exception as e:
350
- raise e
351
-
352
- return model_paths, temp_dir
353
-
354
- elif "*" in filename_pattern:
355
- # For wildcard patterns, download the entire directory and filter
356
- progress(0.1, desc="Downloading repository snapshot...")
357
- local_dir = os.path.join(temp_dir, "download")
358
- snapshot_download(
359
- repo_id=repo_id,
360
- subfolder=subfolder or None,
361
- local_dir=local_dir,
362
- token=hf_token,
363
- resume_download=True
364
- )
365
-
366
- # Find files matching the pattern
367
- if subfolder:
368
- pattern_dir = os.path.join(local_dir, subfolder)
369
- else:
370
- pattern_dir = local_dir
371
-
372
- model_files = glob.glob(os.path.join(pattern_dir, filename_pattern))
373
- if not model_files:
374
- raise ValueError(f"No files found matching pattern: {filename_pattern}")
375
-
376
- # Limit number of files
377
- if len(model_files) > 50:
378
- raise ValueError(f"Too many files found ({len(model_files)}). Please use a more specific pattern.")
379
-
380
- return model_files, temp_dir
381
- else:
382
- # SINGLE FILE SAFETENSORS - separate from shard discovery
383
- progress(0.2, desc=f"Downloading {filename_pattern}...")
384
- model_path = hf_hub_download(
385
- repo_id=repo_id,
386
- filename=filename_pattern,
387
- subfolder=subfolder or None,
388
- cache_dir=temp_dir,
389
- token=hf_token,
390
- resume_download=True
391
- )
392
- return [model_path], temp_dir
393
- else:
394
- # For non-safetensors formats
395
- if "*" in filename_pattern:
396
- raise ValueError("Wildcards only supported for safetensors format")
397
- progress(0.2, desc=f"Downloading {filename_pattern}...")
398
- model_path = hf_hub_download(
399
- repo_id=repo_id,
400
- filename=filename_pattern,
401
- subfolder=subfolder or None,
402
- cache_dir=temp_dir,
403
- token=hf_token,
404
- resume_download=True
405
  )
406
- return [model_path], temp_dir
407
-
408
- elif source_type == "modelscope":
409
- if not MODELScope_AVAILABLE:
410
- raise ImportError("ModelScope not installed")
411
- repo_id = repo_url.strip()
412
-
413
- if model_format == "safetensors" and "*" in filename_pattern:
414
- # For ModelScope, we need to handle sharded files differently
415
- # This is a simplified approach - in a real implementation, you might need to list files first
416
- raise NotImplementedError("Pattern matching for ModelScope sharded files not fully implemented")
417
- else:
418
- progress(0.2, desc=f"Downloading {filename_pattern}...")
419
- model_path = ms_file_download(model_id=repo_id, file_path=filename_pattern)
420
- return [model_path], temp_dir
 
421
  else:
422
- raise ValueError("Unknown source")
423
-
424
- except Exception as e:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
425
  shutil.rmtree(temp_dir, ignore_errors=True)
426
- raise e
427
-
428
- def upload_to_target(target_type, new_repo_id, output_dir, fp8_format, hf_token=None, modelscope_token=None, private_repo=False):
429
- if target_type == "huggingface":
430
- api = HfApi(token=hf_token)
431
- api.create_repo(repo_id=new_repo_id, private=private_repo, repo_type="model", exist_ok=True)
432
- api.upload_folder(repo_id=new_repo_id, folder_path=output_dir, repo_type="model", token=hf_token)
433
- return f"https://huggingface.co/{new_repo_id}"
434
- elif target_type == "modelscope":
435
- api = ModelScopeApi()
436
- if modelscope_token:
437
- api.login(modelscope_token)
438
- api.push_model(model_id=new_repo_id, model_dir=output_dir)
439
- return f"https://modelscope.cn/models/{new_repo_id}"
440
- else:
441
- raise ValueError("Unknown target")
442
-
443
- def process_and_upload_fp8(
444
- source_type,
445
- repo_url,
446
- filename_pattern,
447
- model_format,
448
- fp8_format,
449
- target_type,
450
- new_repo_id,
451
- hf_token,
452
- modelscope_token,
453
- private_repo,
454
- progress=gr.Progress()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
455
  ):
456
- if not re.match(r"^[a-zA-Z0-9._-]+/[a-zA-Z0-9._-]+$", new_repo_id):
457
- return None, "❌ Invalid repo ID format. Use 'username/model-name'.", "", ""
458
- if source_type == "huggingface" and not hf_token:
459
- return None, "❌ Hugging Face token required for source.", "", ""
460
- if target_type == "huggingface" and not hf_token:
461
- return None, "❌ Hugging Face token required for target.", "", ""
462
-
463
  temp_dir = None
464
- output_dir = tempfile.mkdtemp()
 
 
 
 
 
465
  try:
466
- progress(0.05, desc="Downloading model...")
467
- model_paths, temp_dir = download_model_files(
468
- source_type, repo_url, filename_pattern, model_format, hf_token, progress
 
469
  )
470
-
471
- progress(0.8, desc="Converting to FP8...")
472
- success, msg, stats, fp8_path, _ = convert_model_to_fp8(
473
- model_paths, output_dir, fp8_format, model_format, progress
 
 
 
 
 
 
474
  )
475
-
476
- if not success:
477
- return None, f"❌ Conversion failed: {msg}", "", ""
478
-
479
- progress(0.9, desc="Uploading...")
480
- repo_url_final = upload_to_target(
481
- target_type, new_repo_id, output_dir, fp8_format, hf_token, modelscope_token, private_repo
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
482
  )
483
-
484
- # Generate README
485
- if len(model_paths) == 1:
486
- original_filename = os.path.basename(model_paths[0])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
487
  else:
488
- original_filename = f"{len(model_paths)} sharded files"
489
- # Add the pattern if not auto
490
- if filename_pattern != "auto":
491
- original_filename += f" matching '{filename_pattern}'"
492
-
493
- fp8_filename = os.path.basename(fp8_path)
494
-
495
- readme = f"""---
496
- library_name: diffusers
497
- tags:
498
- - fp8
499
- - safetensors
500
- - converted-by-gradio
501
- ---
502
- # FP8 Model Conversion
503
- - **Source**: `{repo_url}`
504
- - **Original File(s)**: `{original_filename}`
505
- - **Original Format**: `{model_format}`
506
- - **FP8 Format**: `{fp8_format.upper()}`
507
- - **FP8 File**: `{fp8_filename}`
508
-
509
- ## Usage
510
- ```python
511
- from safetensors.torch import load_file
512
- import torch
513
 
514
- # Load FP8 model
515
- fp8_state = load_file("{fp8_filename}")
516
 
517
- # Convert tensors back to float32 for computation (auto-converted by PyTorch)
518
- model.load_state_dict(fp8_state)
519
- ```
520
 
521
- > **Note**: FP8 tensors are automatically converted to float32 when loaded in PyTorch.
522
- > Requires PyTorch β‰₯ 2.1 for FP8 support.
523
 
524
- ## Statistics
525
- - **Total tensors**: {stats['total_tensors']}
526
- - **Converted to FP8**: {stats['converted_tensors']}
527
- - **Skipped (non-float)**: {stats['skipped_tensors']}
 
 
 
 
 
528
  """
529
-
530
- with open(os.path.join(output_dir, "README.md"), "w") as f:
531
- f.write(readme)
532
-
533
- if target_type == "huggingface":
534
- HfApi(token=hf_token).upload_file(
535
- path_or_fileobj=os.path.join(output_dir, "README.md"),
536
- path_in_repo="README.md",
537
- repo_id=new_repo_id,
538
- repo_type="model",
539
- token=hf_token
540
- )
541
-
542
- progress(1.0, desc="βœ… Done!")
543
-
544
- # Generate result HTML
545
- result_html = f"""
546
- βœ… Success!
547
- Model uploaded to: <a href="{repo_url_final}" target="_blank">{new_repo_id}</a>
548
- - FP8 model: `{fp8_filename}`
549
- - Converted {stats['converted_tensors']} tensors to {fp8_format.upper()}
550
- """
551
-
552
- return (gr.HTML(result_html),
553
- "βœ… FP8 conversion successful!",
554
- msg,
555
- "")
556
 
557
  except Exception as e:
558
  traceback.print_exc()
559
- return None, f"❌ Error: {str(e)}", "", ""
560
-
561
  finally:
562
  if temp_dir:
563
  shutil.rmtree(temp_dir, ignore_errors=True)
564
- shutil.rmtree(output_dir, ignore_errors=True)
565
-
566
- with gr.Blocks(title="Fast FP8 Model Converter") as demo:
567
- gr.Markdown("# ⚑ Fast FP8 Model Converter")
568
- gr.Markdown("Convert model files (safetensors, pth, ckpt) β†’ **FP8**. Supports sharded files with auto-discovery. Simple and fast!")
569
-
570
- with gr.Row():
571
- with gr.Column():
572
- source_type = gr.Radio(["huggingface", "modelscope"], value="huggingface", label="Source")
573
- repo_url = gr.Textbox(label="Repo URL or ID", placeholder="https://huggingface.co/... or modelscope-id")
574
-
575
- with gr.Row():
576
- model_format = gr.Dropdown(
577
- choices=["safetensors", "pth", "pt", "ckpt"],
578
- value="safetensors",
579
- label="Model Format"
580
- )
581
- filename_pattern = gr.Textbox(
582
- label="Filename or Pattern",
583
- placeholder="auto (detects sharded files) or model-*.safetensors",
584
- value="auto"
585
- )
586
-
587
- with gr.Accordion("FP8 Settings", open=True):
588
- fp8_format = gr.Radio(["e4m3fn", "e5m2"], value="e5m2", label="FP8 Format")
589
-
590
- with gr.Accordion("Authentication", open=False):
591
- hf_token = gr.Textbox(label="Hugging Face Token", type="password")
592
- modelscope_token = gr.Textbox(label="ModelScope Token (optional)", type="password", visible=MODELScope_AVAILABLE)
593
-
594
- with gr.Column():
595
- target_type = gr.Radio(["huggingface", "modelscope"], value="huggingface", label="Target")
596
- new_repo_id = gr.Textbox(label="New Repo ID", placeholder="user/model-fp8")
597
- private_repo = gr.Checkbox(label="Private Repository (HF only)", value=False)
598
-
599
- status_output = gr.Markdown()
600
- detailed_log = gr.Textbox(label="Processing Log", interactive=False, lines=10)
601
- recovery_summary = gr.Textbox(label="Additional Info", interactive=False, lines=3)
602
-
603
- convert_btn = gr.Button("πŸš€ Convert & Upload", variant="primary")
604
- repo_link_output = gr.HTML()
605
-
606
- convert_btn.click(
607
- fn=process_and_upload_fp8,
608
- inputs=[
609
- source_type,
610
- repo_url,
611
- filename_pattern,
612
- model_format,
613
- fp8_format,
614
- target_type,
615
- new_repo_id,
616
- hf_token,
617
- modelscope_token,
618
- private_repo
619
- ],
620
- outputs=[repo_link_output, status_output, detailed_log, recovery_summary],
621
- show_progress=True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
622
  )
623
-
624
- gr.Examples(
625
- examples=[
626
- [
627
- "huggingface",
628
- "https://huggingface.co/stabilityai/sdxl-vae",
629
- "auto",
630
- "safetensors",
631
- "e4m3fn",
632
- "huggingface"
633
- ],
634
- [
635
- "huggingface",
636
- "https://huggingface.co/runwayml/stable-diffusion-v1-5/tree/main/text_encoder",
637
- "auto",
638
- "safetensors",
639
- "e5m2",
640
- "huggingface"
641
- ],
642
- [
643
- "huggingface",
644
- "https://huggingface.co/Yabo/FramePainter/tree/main",
645
- "auto",
646
- "safetensors",
647
- "e5m2",
648
- "huggingface"
649
- ],
650
- [
651
- "huggingface",
652
- "https://huggingface.co/stabilityai/stable-diffusion-2-1",
653
- "model-*.safetensors",
654
- "safetensors",
655
- "e5m2",
656
- "huggingface"
657
- ],
658
- [
659
- "huggingface",
660
- "https://huggingface.co/CompVis/stable-diffusion-v1-4",
661
- "sd-v1-4.ckpt",
662
- "ckpt",
663
- "e5m2",
664
- "huggingface"
665
- ]
666
- ],
667
- inputs=[source_type, repo_url, filename_pattern, model_format, fp8_format, target_type],
668
- label="Example Conversions",
669
- cache_examples=False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
670
  )
671
-
672
- gr.Markdown("""
673
- ## πŸ“ Fast FP8 Conversion Tool
674
-
675
- This tool provides **fast and simple FP8 conversion** for various model formats:
676
-
677
- ### **Supported Formats:**
678
- - **Safetensors**: Modern, secure format. Supports sharded files (e.g., `model-00001-of-00005.safetensors`)
679
- - **PTH/PT**: PyTorch checkpoint files
680
- - **CKPT**: Checkpoint files (commonly used for stable diffusion models)
681
-
682
- ### **Shard Support:**
683
- - **Unlimited Shards**: Supports any number of sharded files (2, 5, 10, 20+)
684
- - **Auto-Detection**: Automatically finds all shards when using "auto" pattern
685
- - **Parallel Downloads**: Downloads multiple shards simultaneously (up to 4 at once)
686
- - **Memory Efficient**: Processes files efficiently to manage memory
687
-
688
- ### **Performance Features:**
689
- - **Fast Conversion**: Simple dtype conversion without complex recovery strategies
690
- - **Batch Processing**: Processes tensors in batches for better performance
691
- - **Progress Tracking**: Shows detailed progress for each step
692
-
693
- ### **How It Works:**
694
- 1. **Discovery**: Automatically detects sharded files or uses your specified pattern
695
- 2. **Download**: Downloads files in parallel for maximum speed
696
- 3. **Conversion**: Converts float tensors to FP8, leaves other types unchanged
697
- 4. **Upload**: Uploads the converted model to your target repository
698
-
699
- ### **Usage Tips:**
700
- - Use "auto" pattern to automatically detect all sharded safetensors files
701
- - Use `model-*.safetensors` to match specific shard patterns
702
- - For single files, just enter the filename (e.g., `model.safetensors`)
703
- - FP8 conversion reduces model size by ~4x compared to FP32
704
- - FP8 tensors are automatically converted to float32 when loaded in PyTorch
705
-
706
- > **Note**: This is a simple conversion tool. For precision recovery options, use the advanced version.
707
- """)
708
-
709
- demo.launch()
 
 
1
  import gradio as gr
2
  import os
3
+ import sys
4
  import tempfile
5
  import shutil
6
  import re
7
  import json
8
+ import struct
9
+ import time
 
 
 
10
  import traceback
11
  import glob
12
+ from pathlib import Path
13
+ from collections import Counter, OrderedDict
14
  from concurrent.futures import ThreadPoolExecutor, as_completed
15
+ from typing import Optional, Dict, List, Tuple, Any
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
+ import torch
18
+ from safetensors.torch import save_file, load_file
19
+ from safetensors import safe_open
20
+
21
+ from huggingface_hub import (
22
+ HfApi,
23
+ hf_hub_download,
24
+ snapshot_download,
25
+ list_repo_files,
26
+ )
27
+
28
+ # ──────────────────────────────────────────────
29
+ # Optional: ComfyUI path detection
30
+ # ──────────────────────────────────────────────
31
+ COMFYUI_MODEL_DIRS = {
32
+ "checkpoints": "models/checkpoints",
33
+ "loras": "models/loras",
34
+ "vae": "models/vae",
35
+ "clip": "models/clip",
36
+ "controlnet": "models/controlnet",
37
+ "embeddings": "models/embeddings",
38
+ "unet": "models/unet",
39
+ "diffusion_models": "models/diffusion_models",
40
+ }
41
+
42
+ def find_comfyui_root() -> Optional[str]:
43
+ """Try to auto-detect a ComfyUI installation."""
44
+ candidates = [
45
+ os.environ.get("COMFYUI_PATH", ""),
46
+ os.path.expanduser("~/ComfyUI"),
47
+ os.path.expanduser("~/comfyui"),
48
+ "/workspace/ComfyUI",
49
+ os.path.join(os.getcwd(), "ComfyUI"),
50
+ ]
51
+ for c in candidates:
52
+ if c and os.path.isdir(os.path.join(c, "models")):
53
+ return c
54
+ return None
55
 
56
+ # ──────────────────────────────────────────────
57
+ # HuggingFace helpers
58
+ # ──────────────────────────────────────────────
59
+ def parse_hf_url(url: str) -> Tuple[str, str]:
60
+ """Return (repo_id, subfolder) from a HuggingFace URL or bare repo id."""
61
  url = url.strip().rstrip("/")
62
+ if url.startswith("https://huggingface.co/"):
63
+ path = url.replace("https://huggingface.co/", "")
64
+ else:
65
+ path = url # treat as bare repo_id[/subfolder]
66
+
67
  parts = path.split("/")
68
  if len(parts) < 2:
69
+ raise ValueError(f"Cannot parse repo id from: {url}")
70
  repo_id = "/".join(parts[:2])
71
  subfolder = ""
72
  if len(parts) > 3 and parts[2] == "tree":
73
+ subfolder = "/".join(parts[3:])
74
  elif len(parts) > 2:
75
  subfolder = "/".join(parts[2:])
76
  return repo_id, subfolder
77
 
78
+
79
+ def find_pickle_files(
80
+ repo_id: str,
81
+ subfolder: str = "",
82
+ token: Optional[str] = None,
83
+ max_files: int = 60,
84
+ ) -> List[str]:
85
+ """List all pickle-based model files (.bin, .pt, .pth, .ckpt) in a repo."""
86
+ repo_files = list_repo_files(repo_id, repo_type="model", token=token)
87
+ exts = (".bin", ".pt", ".pth", ".ckpt")
88
+
89
+ if subfolder:
90
+ prefix = subfolder.rstrip("/") + "/"
91
+ matched = [f for f in repo_files if f.startswith(prefix) and f.endswith(exts)]
92
+ matched = [f[len(prefix):] for f in matched]
93
+ else:
94
+ matched = [f for f in repo_files if f.endswith(exts)]
95
+
96
+ if not matched:
97
+ return []
98
+
99
+ # Separate sharded from single
100
+ sharded = sorted(
101
+ [f for f in matched if re.search(r"-\d{5}-of-\d{5}\.", f)],
102
+ key=lambda x: int(re.search(r"-(\d{5})-of-", x).group(1)),
103
+ )
104
+ singles = [f for f in matched if f not in sharded]
105
+
106
+ result = sharded if sharded else singles
107
+ if len(result) > max_files:
108
+ raise ValueError(
109
+ f"Found {len(result)} files (limit {max_files}). "
110
+ "Narrow the pattern or increase the limit."
111
+ )
112
+ return result
113
+
114
+
115
+ def download_single(args):
116
  repo_id, filename, subfolder, cache_dir, token = args
117
  try:
118
+ p = hf_hub_download(
119
  repo_id=repo_id,
120
  filename=filename,
121
+ subfolder=subfolder or None,
122
  cache_dir=cache_dir,
123
  token=token,
124
+ resume_download=True,
125
  )
126
+ return p, None
127
  except Exception as e:
128
  return None, str(e)
129
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
 
131
+ def download_model_files(
132
+ repo_url: str,
133
+ filename_pattern: str,
134
+ token: Optional[str],
135
+ progress: gr.Progress,
136
+ ) -> Tuple[List[str], str]:
137
+ """Download pickle files β†’ (list_of_local_paths, temp_dir)."""
138
+ repo_id, subfolder = parse_hf_url(repo_url)
139
+ temp_dir = tempfile.mkdtemp(prefix="pkl2st_")
140
+
141
  try:
142
+ if filename_pattern in ("auto", ""):
143
+ progress(0.05, desc="Discovering pickle files …")
144
+ files = find_pickle_files(repo_id, subfolder, token)
145
+ if not files:
146
+ raise FileNotFoundError(
147
+ f"No .bin/.pt/.pth/.ckpt files found in {repo_id}"
148
+ + (f"/{subfolder}" if subfolder else "")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
  )
150
+ progress(0.10, desc=f"Found {len(files)} file(s). Downloading …")
151
+ elif "*" in filename_pattern:
152
+ progress(0.05, desc="Downloading repo snapshot …")
153
+ local = os.path.join(temp_dir, "snap")
154
+ snapshot_download(
155
+ repo_id=repo_id,
156
+ subfolder=subfolder or None,
157
+ local_dir=local,
158
+ token=token,
159
+ resume_download=True,
160
+ )
161
+ base = os.path.join(local, subfolder) if subfolder else local
162
+ files = glob.glob(os.path.join(base, filename_pattern))
163
+ if not files:
164
+ raise FileNotFoundError(f"No files match '{filename_pattern}'")
165
+ return sorted(files), temp_dir
166
  else:
167
+ files = [filename_pattern]
168
+ progress(0.10, desc=f"Downloading {filename_pattern} …")
169
+
170
+ # Parallel download
171
+ paths: List[str] = []
172
+ dl_args = [
173
+ (repo_id, f, subfolder, temp_dir, token) for f in files
174
+ ]
175
+ with ThreadPoolExecutor(max_workers=4) as pool:
176
+ futs = {pool.submit(download_single, a): a[1] for a in dl_args}
177
+ for i, fut in enumerate(as_completed(futs)):
178
+ fname = futs[fut]
179
+ path, err = fut.result()
180
+ if err:
181
+ raise RuntimeError(f"Download failed for {fname}: {err}")
182
+ paths.append(path)
183
+ progress(
184
+ 0.10 + 0.25 * (i + 1) / len(futs),
185
+ desc=f"Downloaded {i+1}/{len(futs)}: {fname}",
186
+ )
187
+ return sorted(paths), temp_dir
188
+
189
+ except Exception:
190
  shutil.rmtree(temp_dir, ignore_errors=True)
191
+ raise
192
+
193
+
194
+ # ──────────────────────────────────────────────
195
+ # Core: load pickle β†’ flat state_dict
196
+ # ──────────────────────────────────────────────
197
+ def _unwrap_checkpoint(obj: Any) -> Dict[str, torch.Tensor]:
198
+ """
199
+ Given a loaded pickle object, drill into common wrapper keys
200
+ to find the actual tensor dict. Preserves key names exactly.
201
+ """
202
+ if not isinstance(obj, dict):
203
+ raise ValueError(f"Unexpected top-level type: {type(obj)}")
204
+
205
+ # Common wrapper keys used by various frameworks
206
+ for key in ("state_dict", "model_state_dict", "model", "module",
207
+ "state", "net", "network", "params", "weights"):
208
+ if key in obj and isinstance(obj[key], dict):
209
+ # Make sure it actually contains tensors
210
+ sample_vals = list(obj[key].values())[:5]
211
+ if all(isinstance(v, torch.Tensor) for v in sample_vals):
212
+ return obj[key]
213
+
214
+ # Check if the dict itself is a flat tensor dict
215
+ sample = list(obj.values())[:10]
216
+ if sample and all(isinstance(v, torch.Tensor) for v in sample):
217
+ return obj
218
+
219
+ # Last resort: return as-is, let save_file reject non-tensors
220
+ return obj
221
+
222
+
223
+ def load_pickle_state_dict(
224
+ paths: List[str],
225
+ progress_cb=None,
226
+ ) -> Dict[str, torch.Tensor]:
227
+ """
228
+ Load one or more pickle checkpoint files and merge into a single
229
+ ordered state_dict. Key names are preserved verbatim.
230
+ """
231
+ merged: OrderedDict[str, torch.Tensor] = OrderedDict()
232
+
233
+ for idx, p in enumerate(paths):
234
+ if progress_cb:
235
+ progress_cb(f"Loading {idx+1}/{len(paths)}: {os.path.basename(p)}")
236
+ ckpt = torch.load(p, map_location="cpu", weights_only=False)
237
+ sd = _unwrap_checkpoint(ckpt)
238
+
239
+ # Guard: make sure every value is a Tensor
240
+ bad = [k for k, v in sd.items() if not isinstance(v, torch.Tensor)]
241
+ if bad:
242
+ print(f" ⚠ Dropping {len(bad)} non-tensor keys: {bad[:8]}…")
243
+ sd = {k: v for k, v in sd.items() if isinstance(v, torch.Tensor)}
244
+
245
+ merged.update(sd)
246
+ del ckpt, sd # free memory
247
+
248
+ return merged
249
+
250
+
251
+ # ──────────────────────────────────────────────
252
+ # Safetensors writer with ComfyUI metadata
253
+ # ──────────────────────────────────────────────
254
+ def detect_model_type(state_dict: Dict[str, torch.Tensor]) -> str:
255
+ """Best-effort model-type detection from key names (for metadata)."""
256
+ keys = list(state_dict.keys())
257
+ joined = " ".join(keys[:200])
258
+
259
+ if any(k.startswith("model.diffusion_model.") for k in keys):
260
+ return "comfyui_checkpoint"
261
+ if any("lora_" in k for k in keys):
262
+ return "lora"
263
+ if any(k.startswith("first_stage_model.") for k in keys):
264
+ return "vae"
265
+ if any("text_model" in k or "cond_stage_model" in k for k in keys):
266
+ return "clip/text_encoder"
267
+ if any("control_model" in k for k in keys):
268
+ return "controlnet"
269
+ if any(k.startswith("model.") for k in keys):
270
+ return "checkpoint_wrapped"
271
+ return "generic"
272
+
273
+
274
+ def build_metadata(
275
+ state_dict: Dict[str, torch.Tensor],
276
+ source_files: List[str],
277
+ model_type: str,
278
+ ) -> Dict[str, str]:
279
+ """Build the __metadata__ dict that goes into the safetensors header."""
280
+ total_params = sum(t.numel() for t in state_dict.values())
281
+ dtypes = Counter(str(t.dtype) for t in state_dict.values())
282
+
283
+ meta = {
284
+ "format": "pt", # ComfyUI reads this
285
+ "source": "pickle_to_safetensors",
286
+ "model_type": model_type,
287
+ "total_tensors": str(len(state_dict)),
288
+ "total_parameters": str(total_params),
289
+ "dtypes": json.dumps(dict(dtypes)),
290
+ "original_files": json.dumps([os.path.basename(f) for f in source_files]),
291
+ "converted_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
292
+ "comfyui_compatible": "true",
293
+ }
294
+ return meta
295
+
296
+
297
+ def save_safetensors(
298
+ state_dict: Dict[str, torch.Tensor],
299
+ output_path: str,
300
+ metadata: Dict[str, str],
301
+ shard_size_gb: float = 0,
302
+ progress_cb=None,
303
+ ) -> List[str]:
304
+ """
305
+ Save state_dict to one or more .safetensors files.
306
+ shard_size_gb > 0 β†’ split into shards.
307
+ Returns list of written file paths.
308
+ """
309
+ if shard_size_gb <= 0:
310
+ if progress_cb:
311
+ progress_cb("Writing safetensors …")
312
+ save_file(state_dict, output_path, metadata=metadata)
313
+ return [output_path]
314
+
315
+ # ── sharded save ──
316
+ shard_bytes = int(shard_size_gb * (1024 ** 3))
317
+ shards: List[Dict[str, torch.Tensor]] = []
318
+ current: Dict[str, torch.Tensor] = {}
319
+ current_size = 0
320
+
321
+ for k, v in state_dict.items():
322
+ t_bytes = v.numel() * v.element_size()
323
+ if current_size + t_bytes > shard_bytes and current:
324
+ shards.append(current)
325
+ current = {}
326
+ current_size = 0
327
+ current[k] = v
328
+ current_size += t_bytes
329
+ if current:
330
+ shards.append(current)
331
+
332
+ base, ext = os.path.splitext(output_path)
333
+ total = len(shards)
334
+ written = []
335
+ for i, shard in enumerate(shards, 1):
336
+ fname = f"{base}-{i:05d}-of-{total:05d}{ext}"
337
+ if progress_cb:
338
+ progress_cb(f"Writing shard {i}/{total} …")
339
+ save_file(shard, fname, metadata=metadata)
340
+ written.append(fname)
341
+ return written
342
+
343
+
344
+ # ──────────────────────────────────────────────
345
+ # High-level conversion pipeline
346
+ # ──────────────────────────────────────────────
347
+ def convert_pickle_to_safetensors(
348
+ repo_url: str,
349
+ filename_pattern: str,
350
+ output_name: str,
351
+ output_dir: str,
352
+ shard_gb: float,
353
+ dtype_override: str,
354
+ hf_token: str,
355
+ comfyui_target: str,
356
+ progress: gr.Progress,
357
  ):
358
+ """Main conversion entry-point called by the Gradio button."""
359
+ t0 = time.time()
 
 
 
 
 
360
  temp_dir = None
361
+ log_lines: List[str] = []
362
+
363
+ def log(msg):
364
+ log_lines.append(msg)
365
+ print(msg)
366
+
367
  try:
368
+ # ── 1. Download ──
369
+ progress(0.02, desc="Downloading pickle files …")
370
+ paths, temp_dir = download_model_files(
371
+ repo_url, filename_pattern, hf_token or None, progress
372
  )
373
+ log(f"πŸ“₯ Downloaded {len(paths)} file(s):")
374
+ for p in paths:
375
+ size_mb = os.path.getsize(p) / 1e6
376
+ log(f" β€’ {os.path.basename(p)} ({size_mb:.1f} MB)")
377
+
378
+ # ── 2. Load ──
379
+ progress(0.35, desc="Loading pickle tensors …")
380
+ state_dict = load_pickle_state_dict(
381
+ paths,
382
+ progress_cb=lambda m: progress(0.40, desc=m),
383
  )
384
+ log(f"🧠 Loaded {len(state_dict)} tensors.")
385
+
386
+ # Show key sample
387
+ sample_keys = list(state_dict.keys())[:12]
388
+ log(" Key samples:")
389
+ for k in sample_keys:
390
+ t = state_dict[k]
391
+ log(f" {k} {list(t.shape)} {t.dtype}")
392
+ if len(state_dict) > 12:
393
+ log(f" … and {len(state_dict)-12} more")
394
+
395
+ # ── 3. Optional dtype cast ──
396
+ if dtype_override and dtype_override != "keep":
397
+ target_dt = getattr(torch, dtype_override)
398
+ progress(0.55, desc=f"Casting to {dtype_override} …")
399
+ cast_count = 0
400
+ for k in state_dict:
401
+ if state_dict[k].is_floating_point():
402
+ state_dict[k] = state_dict[k].to(target_dt)
403
+ cast_count += 1
404
+ log(f"πŸ”„ Cast {cast_count} float tensors β†’ {dtype_override}")
405
+
406
+ # ── 4. Metadata ──
407
+ model_type = detect_model_type(state_dict)
408
+ metadata = build_metadata(state_dict, paths, model_type)
409
+ log(f"🏷 Detected model type: {model_type}")
410
+
411
+ # ── 5. Save ──
412
+ if not output_name:
413
+ # Derive name from first file
414
+ base = os.path.splitext(os.path.basename(paths[0]))[0]
415
+ base = re.sub(r"-\d{5}-of-\d{5}$", "", base)
416
+ output_name = base
417
+ if not output_name.endswith(".safetensors"):
418
+ output_name += ".safetensors"
419
+
420
+ os.makedirs(output_dir, exist_ok=True)
421
+ out_path = os.path.join(output_dir, output_name)
422
+
423
+ progress(0.70, desc="Saving safetensors …")
424
+ written = save_safetensors(
425
+ state_dict,
426
+ out_path,
427
+ metadata,
428
+ shard_size_gb=shard_gb,
429
+ progress_cb=lambda m: progress(0.75, desc=m),
430
  )
431
+
432
+ total_mb = sum(os.path.getsize(f) for f in written) / 1e6
433
+ log(f"πŸ’Ύ Wrote {len(written)} safetensors file(s), {total_mb:.1f} MB total")
434
+ for f in written:
435
+ log(f" β†’ {f}")
436
+
437
+ # ── 6. Optionally copy into ComfyUI ──
438
+ if comfyui_target and comfyui_target != "none":
439
+ comfy_root = find_comfyui_root()
440
+ if comfy_root:
441
+ sub = COMFYUI_MODEL_DIRS.get(comfyui_target, comfyui_target)
442
+ dest_dir = os.path.join(comfy_root, sub)
443
+ os.makedirs(dest_dir, exist_ok=True)
444
+ for f in written:
445
+ dest = os.path.join(dest_dir, os.path.basename(f))
446
+ shutil.copy2(f, dest)
447
+ log(f"πŸ“ Copied β†’ {dest}")
448
+ else:
449
+ log("⚠ Could not auto-detect ComfyUI root. Files left in output dir.")
450
+
451
+ # ── 7. Verification round-trip ──
452
+ progress(0.90, desc="Verifying …")
453
+ verify_ok = True
454
+ verify_msg = ""
455
+ try:
456
+ if len(written) == 1:
457
+ check = load_file(written[0])
458
+ else:
459
+ check = {}
460
+ for f in written:
461
+ check.update(load_file(f))
462
+ if set(check.keys()) != set(state_dict.keys()):
463
+ verify_ok = False
464
+ verify_msg = "Key mismatch after round-trip!"
465
+ else:
466
+ for k in list(check.keys())[:20]:
467
+ if not torch.equal(check[k], state_dict[k]):
468
+ verify_ok = False
469
+ verify_msg = f"Tensor mismatch on key '{k}'"
470
+ break
471
+ del check
472
+ except Exception as ve:
473
+ verify_ok = False
474
+ verify_msg = str(ve)
475
+
476
+ if verify_ok:
477
+ log("βœ… Round-trip verification passed.")
478
  else:
479
+ log(f"❌ Verification issue: {verify_msg}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
480
 
481
+ elapsed = time.time() - t0
482
+ log(f"⏱ Done in {elapsed:.1f}s")
483
 
484
+ progress(1.0, desc="βœ… Complete")
 
 
485
 
486
+ # Build result summary
487
+ result_md = f"""### βœ… Conversion Complete
488
 
489
+ | Item | Value |
490
+ |---|---|
491
+ | **Tensors** | {len(state_dict):,} |
492
+ | **Parameters** | {sum(t.numel() for t in state_dict.values()):,} |
493
+ | **Model type** | `{model_type}` |
494
+ | **Output file(s)** | {', '.join(os.path.basename(f) for f in written)} |
495
+ | **Total size** | {total_mb:.1f} MB |
496
+ | **Verification** | {'βœ… Pass' if verify_ok else '❌ ' + verify_msg} |
497
+ | **Elapsed** | {elapsed:.1f}s |
498
  """
499
+ return result_md, "\n".join(log_lines), None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
500
 
501
  except Exception as e:
502
  traceback.print_exc()
503
+ return None, "\n".join(log_lines), f"❌ {e}"
504
+
505
  finally:
506
  if temp_dir:
507
  shutil.rmtree(temp_dir, ignore_errors=True)
508
+
509
+
510
+ # ──────────────────────────────────────────────
511
+ # Batch local conversion (no download)
512
+ # ──────────────────────────────────────────────
513
+ def convert_local_files(
514
+ files,
515
+ output_dir: str,
516
+ output_name: str,
517
+ shard_gb: float,
518
+ dtype_override: str,
519
+ comfyui_target: str,
520
+ progress: gr.Progress,
521
+ ):
522
+ """Convert locally uploaded pickle files."""
523
+ if not files:
524
+ return None, "", "No files uploaded."
525
+
526
+ paths = [f.name if hasattr(f, "name") else f for f in files]
527
+ log_lines = []
528
+
529
+ try:
530
+ progress(0.1, desc="Loading …")
531
+ state_dict = load_pickle_state_dict(
532
+ paths,
533
+ progress_cb=lambda m: progress(0.2, desc=m),
534
+ )
535
+ log_lines.append(f"Loaded {len(state_dict)} tensors from {len(paths)} file(s).")
536
+
537
+ if dtype_override and dtype_override != "keep":
538
+ target_dt = getattr(torch, dtype_override)
539
+ for k in state_dict:
540
+ if state_dict[k].is_floating_point():
541
+ state_dict[k] = state_dict[k].to(target_dt)
542
+
543
+ model_type = detect_model_type(state_dict)
544
+ metadata = build_metadata(state_dict, paths, model_type)
545
+
546
+ if not output_name:
547
+ output_name = os.path.splitext(os.path.basename(paths[0]))[0] + ".safetensors"
548
+ if not output_name.endswith(".safetensors"):
549
+ output_name += ".safetensors"
550
+
551
+ os.makedirs(output_dir, exist_ok=True)
552
+ out_path = os.path.join(output_dir, output_name)
553
+
554
+ progress(0.6, desc="Saving …")
555
+ written = save_safetensors(state_dict, out_path, metadata, shard_gb)
556
+
557
+ if comfyui_target and comfyui_target != "none":
558
+ comfy_root = find_comfyui_root()
559
+ if comfy_root:
560
+ sub = COMFYUI_MODEL_DIRS.get(comfyui_target, comfyui_target)
561
+ dest_dir = os.path.join(comfy_root, sub)
562
+ os.makedirs(dest_dir, exist_ok=True)
563
+ for f in written:
564
+ shutil.copy2(f, os.path.join(dest_dir, os.path.basename(f)))
565
+
566
+ total_mb = sum(os.path.getsize(f) for f in written) / 1e6
567
+ result_md = f"βœ… Saved {len(written)} file(s), {total_mb:.1f} MB β†’ `{output_dir}`"
568
+ progress(1.0, desc="Done")
569
+ return result_md, "\n".join(log_lines), None
570
+
571
+ except Exception as e:
572
+ traceback.print_exc()
573
+ return None, "\n".join(log_lines), str(e)
574
+
575
+
576
+ # ──────────────────────────────────────────────
577
+ # Inspect an existing safetensors / pickle file
578
+ # ──────────────────────────────────────────────
579
+ def inspect_file(file) -> str:
580
+ """Show key names, shapes, dtypes for a model file."""
581
+ if file is None:
582
+ return "Upload a file first."
583
+ path = file.name if hasattr(file, "name") else file
584
+ ext = os.path.splitext(path)[1].lower()
585
+
586
+ lines = [f"**File:** `{os.path.basename(path)}` ({os.path.getsize(path)/1e6:.1f} MB)\n"]
587
+
588
+ try:
589
+ if ext == ".safetensors":
590
+ with safe_open(path, framework="pt") as f:
591
+ meta = f.metadata() or {}
592
+ if meta:
593
+ lines.append("**Metadata:**")
594
+ for k, v in meta.items():
595
+ lines.append(f" `{k}`: {v}")
596
+ lines.append("")
597
+ keys = list(f.keys())
598
+ lines.append(f"**Tensors:** {len(keys)}\n")
599
+ lines.append("| Key | Shape | Dtype |")
600
+ lines.append("|-----|-------|-------|")
601
+ for k in keys[:80]:
602
+ t = f.get_tensor(k)
603
+ lines.append(f"| `{k}` | {list(t.shape)} | {t.dtype} |")
604
+ if len(keys) > 80:
605
+ lines.append(f"\n… and {len(keys)-80} more tensors")
606
+
607
+ elif ext in (".bin", ".pt", ".pth", ".ckpt"):
608
+ obj = torch.load(path, map_location="cpu", weights_only=False)
609
+ sd = _unwrap_checkpoint(obj)
610
+ lines.append(f"**Tensors:** {len(sd)}\n")
611
+ lines.append("| Key | Shape | Dtype |")
612
+ lines.append("|-----|-------|-------|")
613
+ for i, (k, v) in enumerate(sd.items()):
614
+ if i >= 80:
615
+ lines.append(f"\n… and {len(sd)-80} more tensors")
616
+ break
617
+ if isinstance(v, torch.Tensor):
618
+ lines.append(f"| `{k}` | {list(v.shape)} | {v.dtype} |")
619
+ else:
620
+ lines.append(f"| `{k}` | β€” | {type(v).__name__} |")
621
+ del obj, sd
622
+ else:
623
+ return f"Unsupported extension: {ext}"
624
+
625
+ except Exception as e:
626
+ lines.append(f"\n❌ Error: {e}")
627
+
628
+ return "\n".join(lines)
629
+
630
+
631
+ # ──────────────────────────────────────────────
632
+ # Gradio UI
633
+ # ──────────────────────────────────────────────
634
+ with gr.Blocks(
635
+ title="Pickle β†’ SafeTensors (ComfyUI)",
636
+ theme=gr.themes.Soft(),
637
+ ) as demo:
638
+
639
+ gr.Markdown(
640
+ "# πŸ”„ Pickle β†’ SafeTensors Converter\n"
641
+ "Convert `.bin` / `.pt` / `.pth` / `.ckpt` files from HuggingFace "
642
+ "(or local uploads) into `.safetensors` with full key-structure "
643
+ "preservation for **ComfyUI** compatibility."
644
  )
645
+
646
+ with gr.Tabs():
647
+ # ────────── TAB 1: HuggingFace download + convert ──────────
648
+ with gr.TabItem("🌐 From HuggingFace"):
649
+ with gr.Row():
650
+ with gr.Column(scale=1):
651
+ hf_url = gr.Textbox(
652
+ label="HuggingFace Repo URL",
653
+ placeholder="https://huggingface.co/org/model OR org/model",
654
+ )
655
+ hf_pattern = gr.Textbox(
656
+ label="Filename / Pattern",
657
+ value="auto",
658
+ info="auto = discover all pickle files. "
659
+ "Use *.bin, model.pt, etc. for specific files.",
660
+ )
661
+ hf_token = gr.Textbox(
662
+ label="HF Token (optional)",
663
+ type="password",
664
+ )
665
+ out_name_hf = gr.Textbox(
666
+ label="Output filename",
667
+ placeholder="leave blank to auto-name",
668
+ )
669
+ out_dir_hf = gr.Textbox(
670
+ label="Output directory",
671
+ value="./converted_models",
672
+ )
673
+ with gr.Row():
674
+ shard_gb = gr.Number(
675
+ label="Shard size (GB, 0 = single file)",
676
+ value=0, minimum=0, step=0.5,
677
+ )
678
+ dtype_sel = gr.Dropdown(
679
+ ["keep", "float16", "bfloat16", "float32"],
680
+ value="keep",
681
+ label="Dtype override",
682
+ )
683
+ comfy_target = gr.Dropdown(
684
+ ["none"] + list(COMFYUI_MODEL_DIRS.keys()),
685
+ value="none",
686
+ label="Copy to ComfyUI folder",
687
+ )
688
+ convert_btn = gr.Button("πŸš€ Convert", variant="primary")
689
+
690
+ with gr.Column(scale=1):
691
+ result_md = gr.Markdown(label="Result")
692
+ log_box = gr.Textbox(
693
+ label="Log", lines=18, interactive=False,
694
+ show_copy_button=True,
695
+ )
696
+ err_box = gr.Textbox(label="Error", visible=True, interactive=False)
697
+
698
+ convert_btn.click(
699
+ fn=convert_pickle_to_safetensors,
700
+ inputs=[
701
+ hf_url, hf_pattern, out_name_hf, out_dir_hf,
702
+ shard_gb, dtype_sel, hf_token, comfy_target,
703
+ ],
704
+ outputs=[result_md, log_box, err_box],
705
+ )
706
+
707
+ gr.Examples(
708
+ examples=[
709
+ [
710
+ "https://huggingface.co/runwayml/stable-diffusion-v1-5",
711
+ "auto", "", "./converted_models", 0, "keep", "", "none",
712
+ ],
713
+ [
714
+ "https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0",
715
+ "auto", "sdxl-base.safetensors", "./converted_models",
716
+ 4.0, "float16", "", "checkpoints",
717
+ ],
718
+ [
719
+ "https://huggingface.co/CompVis/stable-diffusion-v1-4",
720
+ "sd-v1-4.ckpt", "", "./converted_models", 0, "float16", "", "checkpoints",
721
+ ],
722
+ ],
723
+ inputs=[
724
+ hf_url, hf_pattern, out_name_hf, out_dir_hf,
725
+ shard_gb, dtype_sel, hf_token, comfy_target,
726
+ ],
727
+ label="Examples",
728
+ )
729
+
730
+ # ────────── TAB 2: Local file upload ──────────
731
+ with gr.TabItem("πŸ“‚ Local Files"):
732
+ with gr.Row():
733
+ with gr.Column():
734
+ local_files = gr.File(
735
+ label="Upload .bin / .pt / .pth / .ckpt",
736
+ file_count="multiple",
737
+ file_types=[".bin", ".pt", ".pth", ".ckpt"],
738
+ )
739
+ local_out_dir = gr.Textbox(
740
+ label="Output directory", value="./converted_models"
741
+ )
742
+ local_out_name = gr.Textbox(
743
+ label="Output filename", placeholder="auto"
744
+ )
745
+ with gr.Row():
746
+ local_shard = gr.Number(label="Shard GB (0=single)", value=0)
747
+ local_dtype = gr.Dropdown(
748
+ ["keep", "float16", "bfloat16", "float32"],
749
+ value="keep", label="Dtype",
750
+ )
751
+ local_comfy = gr.Dropdown(
752
+ ["none"] + list(COMFYUI_MODEL_DIRS.keys()),
753
+ value="none", label="Copy to ComfyUI folder",
754
+ )
755
+ local_btn = gr.Button("πŸš€ Convert", variant="primary")
756
+ with gr.Column():
757
+ local_result = gr.Markdown()
758
+ local_log = gr.Textbox(label="Log", lines=14, interactive=False)
759
+ local_err = gr.Textbox(label="Error", interactive=False)
760
+
761
+ local_btn.click(
762
+ fn=convert_local_files,
763
+ inputs=[
764
+ local_files, local_out_dir, local_out_name,
765
+ local_shard, local_dtype, local_comfy,
766
+ ],
767
+ outputs=[local_result, local_log, local_err],
768
+ )
769
+
770
+ # ────────── TAB 3: Inspector ──────────
771
+ with gr.TabItem("πŸ” Inspect File"):
772
+ inspect_upload = gr.File(
773
+ label="Upload .safetensors / .bin / .pt / .pth / .ckpt",
774
+ file_types=[".safetensors", ".bin", ".pt", ".pth", ".ckpt"],
775
+ )
776
+ inspect_btn = gr.Button("Inspect")
777
+ inspect_out = gr.Markdown()
778
+ inspect_btn.click(fn=inspect_file, inputs=inspect_upload, outputs=inspect_out)
779
+
780
+ gr.Markdown(
781
+ """
782
+ ---
783
+ ### ComfyUI Compatibility Notes
784
+
785
+ * **Key names are preserved 1-to-1.** No prefix stripping or renaming is done,
786
+ so whatever structure the pickle file had (e.g. `model.diffusion_model.*`,
787
+ `first_stage_model.*`, `lora_unet_*`) is kept intact.
788
+ * The safetensors header includes `"format": "pt"` and `"comfyui_compatible": "true"`
789
+ so ComfyUI's loader recognises the file immediately.
790
+ * For **sharded** outputs ComfyUI will load all `*-XXXXX-of-YYYYY.safetensors`
791
+ files that share the same base name in the same folder.
792
+ * If you set **Copy to ComfyUI folder**, the script auto-detects your ComfyUI
793
+ root (`~/ComfyUI` by default, override with `COMFYUI_PATH` env var) and
794
+ copies the output into the correct `models/<sub>` directory.
795
+
796
+ ### Supported pickle sources
797
+ | Extension | Typical origin |
798
+ |-----------|---------------|
799
+ | `.bin` | HuggingFace `pytorch_model.bin` / Diffusers |
800
+ | `.pt` / `.pth` | PyTorch `torch.save()` |
801
+ | `.ckpt` | Stable Diffusion v1/v2 original checkpoints |
802
+ """
803
  )
804
+
805
+ demo.launch(inbrowser=True)