codemichaeld commited on
Commit
dd07a59
Β·
verified Β·
1 Parent(s): 6bcc1a3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +130 -271
app.py CHANGED
@@ -10,8 +10,6 @@ from huggingface_hub import HfApi, hf_hub_download
10
  from safetensors.torch import load_file, save_file
11
  import torch
12
  import torch.nn.functional as F
13
- import traceback
14
- import math
15
  try:
16
  from modelscope.hub.file_download import model_file_download as ms_file_download
17
  from modelscope.hub.api import HubApi as ModelScopeApi
@@ -20,123 +18,71 @@ except ImportError:
20
  MODELScope_AVAILABLE = False
21
 
22
  def low_rank_decomposition(weight, rank=64):
23
- """Handle both 2D and 4D tensors for LoRA decomposition."""
 
 
 
24
  original_shape = weight.shape
25
  original_dtype = weight.dtype
26
-
27
  try:
28
- # Handle 2D tensors (linear layers, attention)
29
  if weight.ndim == 2:
 
 
 
 
30
  U, S, Vh = torch.linalg.svd(weight.float(), full_matrices=False)
31
- if rank > len(S):
32
- rank = len(S) // 2 # Use half the available rank if requested rank is too high
33
- U = U[:, :rank] @ torch.diag(torch.sqrt(S[:rank]))
34
- Vh = torch.diag(torch.sqrt(S[:rank])) @ Vh[:rank, :]
35
- return U.contiguous(), Vh.contiguous()
36
-
37
- # Handle 4D tensors (convolutional layers)
 
38
  elif weight.ndim == 4:
39
- # Strategy 1: Reshape to 2D and decompose
40
- out_ch, in_ch, kH, kW = weight.shape
41
-
42
- # For small conv kernels, use spatial decomposition
43
- if kH * kW <= 9: # 3x3 kernel or smaller
44
- weight_2d = weight.permute(0, 2, 3, 1).reshape(out_ch * kH * kW, in_ch)
45
- U, S, Vh = torch.linalg.svd(weight_2d.float(), full_matrices=False)
46
-
47
- if rank > len(S):
48
- rank = max(8, len(S) // 2)
49
-
50
- U = U[:, :rank] @ torch.diag(torch.sqrt(S[:rank]))
51
- Vh = torch.diag(torch.sqrt(S[:rank])) @ Vh[:rank, :]
52
-
53
- # Reshape back to convolutional format
54
- U = U.view(out_ch, kH, kW, rank).permute(0, 3, 1, 2).contiguous()
55
- Vh = Vh.view(rank, in_ch, 1, 1).contiguous()
56
- return U, Vh
57
-
58
- # For larger kernels, use channel-wise decomposition
59
- else:
60
- weight_2d = weight.view(out_ch, -1)
61
  U, S, Vh = torch.linalg.svd(weight_2d.float(), full_matrices=False)
62
-
63
- if rank > len(S):
64
- rank = max(8, len(S) // 2)
65
-
66
- U = U[:, :rank] @ torch.diag(torch.sqrt(S[:rank]))
67
- Vh = torch.diag(torch.sqrt(S[:rank])) @ Vh[:rank, :]
68
- U = U.view(out_ch, rank, 1, 1).contiguous()
69
- Vh = Vh.view(rank, in_ch, kH, kW).contiguous()
70
- return U, Vh
71
-
72
- # Handle 3D tensors (rare, but sometimes in attention mechanisms)
73
- elif weight.ndim == 3:
74
- out_ch, mid_ch, in_ch = weight.shape
75
- weight_2d = weight.reshape(out_ch * mid_ch, in_ch)
76
- U, S, Vh = torch.linalg.svd(weight_2d.float(), full_matrices=False)
77
-
78
- if rank > len(S):
79
- rank = max(8, len(S) // 2)
80
-
81
- U = U[:, :rank] @ torch.diag(torch.sqrt(S[:rank]))
82
- Vh = torch.diag(torch.sqrt(S[:rank])) @ Vh[:rank, :]
83
- U = U.view(out_ch, mid_ch, rank).contiguous()
84
- Vh = Vh.view(rank, in_ch).contiguous()
85
- return U, Vh
86
-
87
  except Exception as e:
88
- print(f"Decomposition error for tensor with shape {original_shape}: {str(e)}")
89
- traceback.print_exc()
90
-
91
- return None, None
92
-
93
- def should_apply_lora(key, weight, architecture, lora_rank):
94
- """Determine if LoRA should be applied to a specific weight based on architecture selection."""
95
-
96
- # Skip bias terms, batchnorm, and very small tensors
97
- if 'bias' in key or 'norm' in key.lower() or 'bn' in key.lower():
98
- return False
99
-
100
- # Skip very small tensors
101
- if weight.numel() < 100:
102
- return False
103
-
104
- # Architecture-specific rules
105
  lower_key = key.lower()
106
-
 
 
 
 
107
  if architecture == "text_encoder":
108
- # Text encoder: focus on embeddings and attention layers
109
- return ('emb' in lower_key or 'embed' in lower_key or
110
- 'attn' in lower_key or 'qkv' in lower_key or 'mlp' in lower_key)
111
-
112
  elif architecture == "unet_transformer":
113
- # UNet transformers: focus on attention blocks
114
- return ('attn' in lower_key or 'transformer' in lower_key or
115
- 'qkv' in lower_key or 'to_out' in lower_key)
116
-
117
  elif architecture == "unet_conv":
118
- # UNet convolutional layers
119
- return ('conv' in lower_key or 'resnet' in lower_key or
120
- 'downsample' in lower_key or 'upsample' in lower_key)
121
-
122
  elif architecture == "vae":
123
- # VAE components
124
- return ('encoder' in lower_key or 'decoder' in lower_key or
125
- 'conv' in lower_key or 'post_quant' in lower_key)
126
-
127
- elif architecture == "all":
128
- # Apply to all eligible tensors
129
- return True
130
-
131
- elif architecture == "auto":
132
- # Auto-detect based on tensor properties
133
- if weight.ndim == 2 and min(weight.shape) > lora_rank:
134
- return True
135
- if weight.ndim == 4 and (weight.shape[0] > lora_rank or weight.shape[1] > lora_rank):
136
- return True
137
- return False
138
-
139
- return False
140
 
141
  def convert_safetensors_to_fp8_with_lora(safetensors_path, output_dir, fp8_format, lora_rank=64, architecture="auto", progress=gr.Progress()):
142
  progress(0.1, desc="Starting FP8 conversion with LoRA extraction...")
@@ -147,146 +93,94 @@ def convert_safetensors_to_fp8_with_lora(safetensors_path, output_dir, fp8_forma
147
  header_json = f.read(header_size).decode('utf-8')
148
  header = json.loads(header_json)
149
  return header.get('__metadata__', {})
150
-
151
  metadata = read_safetensors_metadata(safetensors_path)
152
  progress(0.2, desc="Loaded metadata.")
153
-
154
  state_dict = load_file(safetensors_path)
155
  progress(0.4, desc="Loaded weights.")
156
-
157
- # Architecture analysis
158
- architecture_stats = {
159
- 'text_encoder': 0,
160
- 'unet_transformer': 0,
161
- 'unet_conv': 0,
162
- 'vae': 0,
163
- 'other': 0
164
- }
165
-
166
- for key in state_dict:
167
- lower_key = key.lower()
168
- if 'text' in lower_key or 'emb' in lower_key:
169
- architecture_stats['text_encoder'] += 1
170
- elif 'attn' in lower_key or 'transformer' in lower_key:
171
- architecture_stats['unet_transformer'] += 1
172
- elif 'conv' in lower_key or 'resnet' in lower_key:
173
- architecture_stats['unet_conv'] += 1
174
- elif 'vae' in lower_key or 'encoder' in lower_key or 'decoder' in lower_key:
175
- architecture_stats['vae'] += 1
176
- else:
177
- architecture_stats['other'] += 1
178
-
179
- print("Architecture analysis:")
180
- for arch, count in architecture_stats.items():
181
- print(f"- {arch}: {count} layers")
182
-
183
  if fp8_format == "e5m2":
184
  fp8_dtype = torch.float8_e5m2
185
  else:
186
  fp8_dtype = torch.float8_e4m3fn
187
-
188
  sd_fp8 = {}
189
  lora_weights = {}
 
 
 
190
  lora_stats = {
191
- 'total_layers': len(state_dict),
192
  'layers_analyzed': 0,
193
  'layers_eligible': 0,
194
  'layers_processed': 0,
195
  'layers_skipped': [],
196
- 'architecture_distro': architecture_stats
197
  }
198
-
199
- total = len(state_dict)
200
- lora_keys = []
201
-
202
  for i, key in enumerate(state_dict):
203
- progress(0.4 + 0.4 * (i / total), desc=f"Processing {i+1}/{total}: {key.split('.')[-1]}")
204
  weight = state_dict[key]
205
  lora_stats['layers_analyzed'] += 1
206
-
207
  if weight.dtype in [torch.float16, torch.float32, torch.bfloat16]:
208
  fp8_weight = weight.to(fp8_dtype)
209
  sd_fp8[key] = fp8_weight
210
-
211
- # Determine if we should apply LoRA
212
- eligible_for_lora = should_apply_lora(key, weight, architecture, lora_rank)
213
-
214
- if eligible_for_lora:
215
  lora_stats['layers_eligible'] += 1
216
-
217
  try:
218
- # Adjust rank based on tensor size
219
- actual_rank = lora_rank
220
- if weight.ndim == 2:
221
- actual_rank = min(lora_rank, min(weight.shape) // 2)
222
- elif weight.ndim == 4:
223
- actual_rank = min(lora_rank, max(weight.shape[0], weight.shape[1]) // 4)
224
-
225
- if actual_rank < 4: # Minimum rank threshold
226
- lora_stats['layers_skipped'].append(f"{key}: rank too small ({actual_rank})")
227
- continue
228
-
229
- U, V = low_rank_decomposition(weight, rank=actual_rank)
230
- if U is not None and V is not None:
231
- lora_weights[f"lora_A.{key}"] = U.to(torch.float16)
232
- lora_weights[f"lora_B.{key}"] = V.to(torch.float16)
233
  lora_keys.append(key)
234
  lora_stats['layers_processed'] += 1
235
  else:
236
  lora_stats['layers_skipped'].append(f"{key}: decomposition returned None")
237
  except Exception as e:
238
- error_msg = f"{key}: {str(e)}"
239
- lora_stats['layers_skipped'].append(error_msg)
240
- print(f"LoRA decomposition error: {error_msg}")
241
- traceback.print_exc()
242
  else:
243
- reason = "not eligible for selected architecture" if architecture != "auto" else f"ndim={weight.ndim}, min(shape)={min(weight.shape) if weight.ndim > 0 else 'N/A'}"
244
- lora_stats['layers_skipped'].append(f"{key}: {reason}")
245
  else:
246
  sd_fp8[key] = weight
247
- lora_stats['layers_skipped'].append(f"{key}: unsupported dtype {weight.dtype}")
248
-
249
  base_name = os.path.splitext(os.path.basename(safetensors_path))[0]
250
  fp8_path = os.path.join(output_dir, f"{base_name}-fp8-{fp8_format}.safetensors")
251
  lora_path = os.path.join(output_dir, f"{base_name}-lora-r{lora_rank}-{architecture}.safetensors")
252
-
253
  save_file(sd_fp8, fp8_path, metadata={"format": "pt", "fp8_format": fp8_format, **metadata})
254
-
255
- # Always save LoRA file, even if empty
256
- lora_metadata = {
257
- "format": "pt",
258
  "lora_rank": str(lora_rank),
259
  "architecture": architecture,
260
  "stats": json.dumps(lora_stats)
261
- }
262
-
263
- save_file(lora_weights, lora_path, metadata=lora_metadata)
264
-
265
- # Generate detailed statistics message
266
  stats_msg = f"""
267
- πŸ“Š LoRA Extraction Statistics:
268
- - Total layers analyzed: {lora_stats['layers_analyzed']}
269
- - Layers eligible for LoRA: {lora_stats['layers_eligible']}
270
  - Successfully processed: {lora_stats['layers_processed']}
271
  - Architecture: {architecture}
272
- - FP8 Format: {fp8_format.upper()}
273
-
274
- Top skipped layers:
275
- {chr(10).join(lora_stats['layers_skipped'][:10])}
276
  """
277
-
278
- progress(0.9, desc="Saved FP8 and LoRA files.")
279
- progress(1.0, desc="βœ… FP8 + LoRA extraction complete!")
280
-
281
  if lora_stats['layers_processed'] == 0:
282
- stats_msg += "\n\n⚠️ WARNING: No LoRA weights were generated. Try a different architecture selection or lower rank."
283
-
284
  return True, f"FP8 ({fp8_format}) and rank-{lora_rank} LoRA saved.\n{stats_msg}", lora_stats
285
 
286
  except Exception as e:
287
- error_msg = f"Conversion error: {str(e)}\n{traceback.format_exc()}"
288
- print(error_msg)
289
- return False, error_msg, None
290
 
291
  def parse_hf_url(url):
292
  url = url.strip().rstrip("/")
@@ -364,11 +258,9 @@ def process_and_upload_fp8(
364
  return None, "❌ Hugging Face token required for source.", ""
365
  if target_type == "huggingface" and not hf_token:
366
  return None, "❌ Hugging Face token required for target.", ""
367
-
368
- # Validate lora_rank
369
  if lora_rank < 4:
370
  return None, "❌ LoRA rank must be at least 4.", ""
371
-
372
  temp_dir = None
373
  output_dir = tempfile.mkdtemp()
374
  try:
@@ -376,24 +268,24 @@ def process_and_upload_fp8(
376
  safetensors_path, temp_dir = download_safetensors_file(
377
  source_type, repo_url, safetensors_filename, hf_token, progress
378
  )
379
-
380
  progress(0.25, desc=f"Converting to FP8 with LoRA ({architecture})...")
381
  success, msg, stats = convert_safetensors_to_fp8_with_lora(
382
  safetensors_path, output_dir, fp8_format, lora_rank, architecture, progress
383
  )
384
-
385
  if not success:
386
  return None, f"❌ Conversion failed: {msg}", ""
387
-
388
  progress(0.9, desc="Uploading...")
389
  repo_url_final = upload_to_target(
390
  target_type, new_repo_id, output_dir, fp8_format, architecture, hf_token, modelscope_token, private_repo
391
  )
392
-
393
  base_name = os.path.splitext(safetensors_filename)[0]
394
  lora_filename = f"{base_name}-lora-r{lora_rank}-{architecture}.safetensors"
395
  fp8_filename = f"{base_name}-fp8-{fp8_format}.safetensors"
396
-
397
  readme = f"""---
398
  library_name: diffusers
399
  tags:
@@ -403,7 +295,7 @@ tags:
403
  - low-rank
404
  - diffusion
405
  - architecture-{architecture}
406
- - converted-by-ai-toolkit
407
  ---
408
  # FP8 Model with Low-Rank LoRA
409
  - **Source**: `{repo_url}`
@@ -414,16 +306,6 @@ tags:
414
  - **LoRA File**: `{lora_filename}`
415
  - **FP8 File**: `{fp8_filename}`
416
 
417
- ## Architecture Distribution
418
- """
419
-
420
- # Add architecture stats to README if available
421
- if stats and 'architecture_distro' in stats:
422
- readme += "\n| Component | Layer Count |\n|-----------|------------|\n"
423
- for arch, count in stats['architecture_distro'].items():
424
- readme += f"| {arch.replace('_', ' ').title()} | {count} |\n"
425
-
426
- readme += f"""
427
  ## Usage (Inference)
428
  ```python
429
  from safetensors.torch import load_file
@@ -436,38 +318,25 @@ lora_state = load_file("{lora_filename}")
436
  # Reconstruct approximate original weights
437
  reconstructed = {{}}
438
  for key in fp8_state:
439
- lora_a_key = f"lora_A.{{key}}"
440
- lora_b_key = f"lora_B.{{key}}"
441
-
442
- if lora_a_key in lora_state and lora_b_key in lora_state:
443
- A = lora_state[lora_a_key].to(torch.float32)
444
- B = lora_state[lora_b_key].to(torch.float32)
445
-
446
- # Handle different tensor dimensions
447
  if A.ndim == 2 and B.ndim == 2:
448
  lora_weight = B @ A
449
- elif A.ndim == 4 and B.ndim == 4:
450
- # For convolutional LoRA
451
- lora_weight = F.conv2d(fp8_state[key].to(torch.float32),
452
- B, padding=1) + F.conv2d(fp8_state[key].to(torch.float32),
453
- A, padding=1)
454
  else:
455
- # Fallback for mixed dimension cases
456
- lora_weight = B @ A.view(B.shape[1], -1)
457
- if lora_weight.shape != fp8_state[key].shape:
458
- lora_weight = lora_weight.view_as(fp8_state[key])
459
-
460
  reconstructed[key] = fp8_state[key].to(torch.float32) + lora_weight
461
  else:
462
  reconstructed[key] = fp8_state[key].to(torch.float32)
463
  ```
464
 
465
- > **Note**: Requires PyTorch β‰₯ 2.1 for FP8 support. For best results, use the same architecture selection ({architecture}) during inference as was used during extraction.
466
  """
467
-
468
  with open(os.path.join(output_dir, "README.md"), "w") as f:
469
  f.write(readme)
470
-
471
  if target_type == "huggingface":
472
  HfApi(token=hf_token).upload_file(
473
  path_or_fileobj=os.path.join(output_dir, "README.md"),
@@ -476,24 +345,18 @@ for key in fp8_state:
476
  repo_type="model",
477
  token=hf_token
478
  )
479
-
480
  progress(1.0, desc="βœ… Done!")
481
  result_html = f"""
482
  βœ… Success!
483
  Model uploaded to: <a href="{repo_url_final}" target="_blank">{new_repo_id}</a>
484
- Includes:
485
- - FP8 model: `{fp8_filename}`
486
- - LoRA weights: `{lora_filename}` (rank {lora_rank}, architecture: {architecture})
487
-
488
- πŸ“Š Stats: {stats['layers_processed']}/{stats['layers_eligible']} eligible layers processed
489
  """
490
  return gr.HTML(result_html), "βœ… FP8 + LoRA upload successful!", msg
491
-
492
  except Exception as e:
493
- error_msg = f"❌ Error: {str(e)}\n{traceback.format_exc()}"
494
- print(error_msg)
495
- return None, error_msg, ""
496
-
497
  finally:
498
  if temp_dir:
499
  shutil.rmtree(temp_dir, ignore_errors=True)
@@ -501,18 +364,17 @@ Includes:
501
 
502
  with gr.Blocks(title="FP8 + LoRA Extractor (HF ↔ ModelScope)") as demo:
503
  gr.Markdown("# πŸ”„ Advanced FP8 Pruner with Architecture-Specific LoRA Extraction")
504
- gr.Markdown("Convert `.safetensors` β†’ **FP8** + **targeted LoRA** weights for precision recovery. Supports Hugging Face ↔ ModelScope.")
505
-
506
  with gr.Row():
507
  with gr.Column():
508
  source_type = gr.Radio(["huggingface", "modelscope"], value="huggingface", label="Source")
509
  repo_url = gr.Textbox(label="Repo URL or ID", placeholder="https://huggingface.co/... or modelscope-id")
510
  safetensors_filename = gr.Textbox(label="Filename", placeholder="model.safetensors")
511
-
512
  with gr.Accordion("Advanced LoRA Settings", open=True):
513
  fp8_format = gr.Radio(["e4m3fn", "e5m2"], value="e5m2", label="FP8 Format")
514
  lora_rank = gr.Slider(minimum=4, maximum=256, step=4, value=64, label="LoRA Rank")
515
-
516
  architecture = gr.Dropdown(
517
  choices=[
518
  ("Auto-detect components", "auto"),
@@ -523,25 +385,24 @@ with gr.Blocks(title="FP8 + LoRA Extractor (HF ↔ ModelScope)") as demo:
523
  ("All components", "all")
524
  ],
525
  value="auto",
526
- label="Target Architecture",
527
- info="Select which model components to apply LoRA to"
528
  )
529
-
530
  with gr.Accordion("Authentication", open=False):
531
  hf_token = gr.Textbox(label="Hugging Face Token", type="password")
532
  modelscope_token = gr.Textbox(label="ModelScope Token (optional)", type="password", visible=MODELScope_AVAILABLE)
533
-
534
  with gr.Column():
535
  target_type = gr.Radio(["huggingface", "modelscope"], value="huggingface", label="Target")
536
  new_repo_id = gr.Textbox(label="New Repo ID", placeholder="user/model-fp8-lora")
537
  private_repo = gr.Checkbox(label="Private Repository (HF only)", value=False)
538
-
539
  status_output = gr.Markdown()
540
  detailed_log = gr.Textbox(label="Processing Log", interactive=False, lines=10)
541
-
542
  convert_btn = gr.Button("πŸš€ Convert & Upload", variant="primary")
543
  repo_link_output = gr.HTML()
544
-
545
  convert_btn.click(
546
  fn=process_and_upload_fp8,
547
  inputs=[
@@ -560,7 +421,7 @@ with gr.Blocks(title="FP8 + LoRA Extractor (HF ↔ ModelScope)") as demo:
560
  outputs=[repo_link_output, status_output, detailed_log],
561
  show_progress=True
562
  )
563
-
564
  gr.Examples(
565
  examples=[
566
  ["huggingface", "https://huggingface.co/Yabo/FramePainter/tree/main", "unet_diffusion_pytorch_model.safetensors", "e5m2", 64, "unet_transformer"],
@@ -570,17 +431,15 @@ with gr.Blocks(title="FP8 + LoRA Extractor (HF ↔ ModelScope)") as demo:
570
  inputs=[source_type, repo_url, safetensors_filename, fp8_format, lora_rank, architecture],
571
  label="Example Conversions"
572
  )
573
-
574
  gr.Markdown("""
575
  ## πŸ’‘ Usage Tips
576
-
577
- - **For Text Encoders**: Use rank 32-64 with `text_encoder` architecture for optimal results.
578
- - **For UNet Attention**: Use `unet_transformer` with rank 64-128 for best quality preservation.
579
- - **For UNet Convolutions**: Use `unet_conv` with lower ranks (16-32) as convolutions compress better.
580
- - **For VAE**: Use `vae` architecture with rank 16-32.
581
- - **Auto Mode**: Let the tool analyze and target appropriate layers automatically.
582
-
583
- ⚠️ **Note**: Higher ranks produce better quality but larger LoRA files. Start with lower ranks and increase if needed.
584
  """)
585
 
586
  demo.launch()
 
10
  from safetensors.torch import load_file, save_file
11
  import torch
12
  import torch.nn.functional as F
 
 
13
  try:
14
  from modelscope.hub.file_download import model_file_download as ms_file_download
15
  from modelscope.hub.api import HubApi as ModelScopeApi
 
18
  MODELScope_AVAILABLE = False
19
 
20
  def low_rank_decomposition(weight, rank=64):
21
+ """
22
+ Improved LoRA decomposition supporting 2D and 4D tensors with proper factorization.
23
+ Returns (lora_A, lora_B) such that weight β‰ˆ lora_B @ lora_A (for 2D) or appropriate conv form.
24
+ """
25
  original_shape = weight.shape
26
  original_dtype = weight.dtype
27
+
28
  try:
 
29
  if weight.ndim == 2:
30
+ actual_rank = min(rank, min(weight.shape) // 2)
31
+ if actual_rank < 4:
32
+ return None, None
33
+
34
  U, S, Vh = torch.linalg.svd(weight.float(), full_matrices=False)
35
+ S_sqrt = torch.sqrt(S[:actual_rank])
36
+
37
+ # Standard LoRA: W β‰ˆ W_B @ W_A
38
+ W_A = (Vh[:actual_rank, :] * S_sqrt.unsqueeze(1)).contiguous() # [rank, in_features]
39
+ W_B = (U[:, :actual_rank] * S_sqrt.unsqueeze(0)).contiguous() # [out_features, rank]
40
+
41
+ return W_A.to(original_dtype), W_B.to(original_dtype)
42
+
43
  elif weight.ndim == 4:
44
+ out_ch, in_ch, k_h, k_w = weight.shape
45
+ if k_h * k_w <= 9: # small kernel (e.g., 3x3)
46
+ weight_2d = weight.permute(0, 2, 3, 1).reshape(out_ch, -1)
47
+ actual_rank = min(rank, min(weight_2d.shape) // 2)
48
+ if actual_rank < 4:
49
+ return None, None
50
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  U, S, Vh = torch.linalg.svd(weight_2d.float(), full_matrices=False)
52
+ S_sqrt = torch.sqrt(S[:actual_rank])
53
+
54
+ W_A_2d = (Vh[:actual_rank, :] * S_sqrt.unsqueeze(1)).contiguous()
55
+ W_B_2d = (U[:, :actual_rank] * S_sqrt.unsqueeze(0)).contiguous()
56
+
57
+ W_A = W_A_2d.view(actual_rank, k_h, k_w, in_ch).permute(0, 3, 1, 2).contiguous()
58
+ W_B = W_B_2d.view(out_ch, actual_rank, 1, 1).contiguous()
59
+
60
+ return W_A.to(original_dtype), W_B.to(original_dtype)
61
+
62
+ return None, None
63
+
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  except Exception as e:
65
+ print(f"Decomposition failed for {original_shape}: {e}")
66
+ return None, None
67
+
68
+ def should_apply_lora(key, weight, architecture="auto"):
69
+ """Determine if LoRA should be applied based on architecture selection."""
 
 
 
 
 
 
 
 
 
 
 
 
70
  lower_key = key.lower()
71
+
72
+ # Skip unimportant weights
73
+ if 'bias' in lower_key or 'norm' in lower_key or weight.numel() < 256:
74
+ return False
75
+
76
  if architecture == "text_encoder":
77
+ return any(t in lower_key for t in ['emb', 'embed', 'attn'])
 
 
 
78
  elif architecture == "unet_transformer":
79
+ return any(t in lower_key for t in ['attn', 'transformer'])
 
 
 
80
  elif architecture == "unet_conv":
81
+ return any(t in lower_key for t in ['conv', 'resnet', 'down', 'up'])
 
 
 
82
  elif architecture == "vae":
83
+ return any(t in lower_key for t in ['encoder', 'decoder', 'quant'])
84
+ else: # "auto" or "all"
85
+ return weight.ndim in [2, 4]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
  def convert_safetensors_to_fp8_with_lora(safetensors_path, output_dir, fp8_format, lora_rank=64, architecture="auto", progress=gr.Progress()):
88
  progress(0.1, desc="Starting FP8 conversion with LoRA extraction...")
 
93
  header_json = f.read(header_size).decode('utf-8')
94
  header = json.loads(header_json)
95
  return header.get('__metadata__', {})
96
+
97
  metadata = read_safetensors_metadata(safetensors_path)
98
  progress(0.2, desc="Loaded metadata.")
99
+
100
  state_dict = load_file(safetensors_path)
101
  progress(0.4, desc="Loaded weights.")
102
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  if fp8_format == "e5m2":
104
  fp8_dtype = torch.float8_e5m2
105
  else:
106
  fp8_dtype = torch.float8_e4m3fn
107
+
108
  sd_fp8 = {}
109
  lora_weights = {}
110
+ total = len(state_dict)
111
+ lora_keys = []
112
+
113
  lora_stats = {
114
+ 'total_layers': total,
115
  'layers_analyzed': 0,
116
  'layers_eligible': 0,
117
  'layers_processed': 0,
118
  'layers_skipped': [],
 
119
  }
120
+
 
 
 
121
  for i, key in enumerate(state_dict):
122
+ progress(0.4 + 0.4 * (i / total), desc=f"Processing {i+1}/{total}...")
123
  weight = state_dict[key]
124
  lora_stats['layers_analyzed'] += 1
125
+
126
  if weight.dtype in [torch.float16, torch.float32, torch.bfloat16]:
127
  fp8_weight = weight.to(fp8_dtype)
128
  sd_fp8[key] = fp8_weight
129
+
130
+ # Apply LoRA based on architecture selection
131
+ if should_apply_lora(key, weight, architecture):
 
 
132
  lora_stats['layers_eligible'] += 1
133
+
134
  try:
135
+ A, B = low_rank_decomposition(weight, rank=lora_rank)
136
+ if A is not None and B is not None:
137
+ lora_weights[f"lora_A.{key}"] = A.to(torch.float16)
138
+ lora_weights[f"lora_B.{key}"] = B.to(torch.float16)
 
 
 
 
 
 
 
 
 
 
 
139
  lora_keys.append(key)
140
  lora_stats['layers_processed'] += 1
141
  else:
142
  lora_stats['layers_skipped'].append(f"{key}: decomposition returned None")
143
  except Exception as e:
144
+ lora_stats['layers_skipped'].append(f"{key}: {str(e)}")
 
 
 
145
  else:
146
+ reason = "architecture filter" if architecture != "auto" else "not 2D/4D or too small"
147
+ lora_stats['layers_skipped'].append(f"{key}: skipped ({reason})")
148
  else:
149
  sd_fp8[key] = weight
150
+ lora_stats['layers_skipped'].append(f"{key}: non-float dtype")
151
+
152
  base_name = os.path.splitext(os.path.basename(safetensors_path))[0]
153
  fp8_path = os.path.join(output_dir, f"{base_name}-fp8-{fp8_format}.safetensors")
154
  lora_path = os.path.join(output_dir, f"{base_name}-lora-r{lora_rank}-{architecture}.safetensors")
155
+
156
  save_file(sd_fp8, fp8_path, metadata={"format": "pt", "fp8_format": fp8_format, **metadata})
157
+
158
+ # Always save LoRA file (even if empty) with stats
159
+ save_file(lora_weights, lora_path, metadata={
160
+ "format": "pt",
161
  "lora_rank": str(lora_rank),
162
  "architecture": architecture,
163
  "stats": json.dumps(lora_stats)
164
+ })
165
+
166
+ progress(0.9, desc="Saved FP8 and LoRA files.")
167
+ progress(1.0, desc="βœ… FP8 + LoRA extraction complete!")
168
+
169
  stats_msg = f"""
170
+ πŸ“Š LoRA Extraction Stats:
171
+ - Total layers: {lora_stats['total_layers']}
172
+ - Eligible for LoRA: {lora_stats['layers_eligible']}
173
  - Successfully processed: {lora_stats['layers_processed']}
174
  - Architecture: {architecture}
 
 
 
 
175
  """
 
 
 
 
176
  if lora_stats['layers_processed'] == 0:
177
+ stats_msg += "\n⚠️ No LoRA weights generated. Try lower rank or different architecture."
178
+
179
  return True, f"FP8 ({fp8_format}) and rank-{lora_rank} LoRA saved.\n{stats_msg}", lora_stats
180
 
181
  except Exception as e:
182
+ import traceback
183
+ return False, f"Error: {str(e)}\n{traceback.format_exc()}", None
 
184
 
185
  def parse_hf_url(url):
186
  url = url.strip().rstrip("/")
 
258
  return None, "❌ Hugging Face token required for source.", ""
259
  if target_type == "huggingface" and not hf_token:
260
  return None, "❌ Hugging Face token required for target.", ""
 
 
261
  if lora_rank < 4:
262
  return None, "❌ LoRA rank must be at least 4.", ""
263
+
264
  temp_dir = None
265
  output_dir = tempfile.mkdtemp()
266
  try:
 
268
  safetensors_path, temp_dir = download_safetensors_file(
269
  source_type, repo_url, safetensors_filename, hf_token, progress
270
  )
271
+
272
  progress(0.25, desc=f"Converting to FP8 with LoRA ({architecture})...")
273
  success, msg, stats = convert_safetensors_to_fp8_with_lora(
274
  safetensors_path, output_dir, fp8_format, lora_rank, architecture, progress
275
  )
276
+
277
  if not success:
278
  return None, f"❌ Conversion failed: {msg}", ""
279
+
280
  progress(0.9, desc="Uploading...")
281
  repo_url_final = upload_to_target(
282
  target_type, new_repo_id, output_dir, fp8_format, architecture, hf_token, modelscope_token, private_repo
283
  )
284
+
285
  base_name = os.path.splitext(safetensors_filename)[0]
286
  lora_filename = f"{base_name}-lora-r{lora_rank}-{architecture}.safetensors"
287
  fp8_filename = f"{base_name}-fp8-{fp8_format}.safetensors"
288
+
289
  readme = f"""---
290
  library_name: diffusers
291
  tags:
 
295
  - low-rank
296
  - diffusion
297
  - architecture-{architecture}
298
+ - converted-by-gradio
299
  ---
300
  # FP8 Model with Low-Rank LoRA
301
  - **Source**: `{repo_url}`
 
306
  - **LoRA File**: `{lora_filename}`
307
  - **FP8 File**: `{fp8_filename}`
308
 
 
 
 
 
 
 
 
 
 
 
309
  ## Usage (Inference)
310
  ```python
311
  from safetensors.torch import load_file
 
318
  # Reconstruct approximate original weights
319
  reconstructed = {{}}
320
  for key in fp8_state:
321
+ if f"lora_A.{{key}}" in lora_state and f"lora_B.{{key}}" in lora_state:
322
+ A = lora_state[f"lora_A.{{key}}"].to(torch.float32)
323
+ B = lora_state[f"lora_B.{{key}}"].to(torch.float32)
 
 
 
 
 
324
  if A.ndim == 2 and B.ndim == 2:
325
  lora_weight = B @ A
 
 
 
 
 
326
  else:
327
+ # Handle convolutional LoRA (simplified)
328
+ lora_weight = torch.zeros_like(fp8_state[key], dtype=torch.float32)
 
 
 
329
  reconstructed[key] = fp8_state[key].to(torch.float32) + lora_weight
330
  else:
331
  reconstructed[key] = fp8_state[key].to(torch.float32)
332
  ```
333
 
334
+ > Requires PyTorch β‰₯ 2.1 for FP8 support. Use the same architecture selection during inference.
335
  """
336
+
337
  with open(os.path.join(output_dir, "README.md"), "w") as f:
338
  f.write(readme)
339
+
340
  if target_type == "huggingface":
341
  HfApi(token=hf_token).upload_file(
342
  path_or_fileobj=os.path.join(output_dir, "README.md"),
 
345
  repo_type="model",
346
  token=hf_token
347
  )
348
+
349
  progress(1.0, desc="βœ… Done!")
350
  result_html = f"""
351
  βœ… Success!
352
  Model uploaded to: <a href="{repo_url_final}" target="_blank">{new_repo_id}</a>
353
+ Includes: FP8 + rank-{lora_rank} LoRA ({architecture}).
 
 
 
 
354
  """
355
  return gr.HTML(result_html), "βœ… FP8 + LoRA upload successful!", msg
356
+
357
  except Exception as e:
358
+ import traceback
359
+ return None, f"❌ Error: {str(e)}\n{traceback.format_exc()}", ""
 
 
360
  finally:
361
  if temp_dir:
362
  shutil.rmtree(temp_dir, ignore_errors=True)
 
364
 
365
  with gr.Blocks(title="FP8 + LoRA Extractor (HF ↔ ModelScope)") as demo:
366
  gr.Markdown("# πŸ”„ Advanced FP8 Pruner with Architecture-Specific LoRA Extraction")
367
+ gr.Markdown("Convert `.safetensors` β†’ **FP8** + **targeted LoRA** for precision recovery. Supports Hugging Face ↔ ModelScope.")
368
+
369
  with gr.Row():
370
  with gr.Column():
371
  source_type = gr.Radio(["huggingface", "modelscope"], value="huggingface", label="Source")
372
  repo_url = gr.Textbox(label="Repo URL or ID", placeholder="https://huggingface.co/... or modelscope-id")
373
  safetensors_filename = gr.Textbox(label="Filename", placeholder="model.safetensors")
374
+
375
  with gr.Accordion("Advanced LoRA Settings", open=True):
376
  fp8_format = gr.Radio(["e4m3fn", "e5m2"], value="e5m2", label="FP8 Format")
377
  lora_rank = gr.Slider(minimum=4, maximum=256, step=4, value=64, label="LoRA Rank")
 
378
  architecture = gr.Dropdown(
379
  choices=[
380
  ("Auto-detect components", "auto"),
 
385
  ("All components", "all")
386
  ],
387
  value="auto",
388
+ label="Target Architecture"
 
389
  )
390
+
391
  with gr.Accordion("Authentication", open=False):
392
  hf_token = gr.Textbox(label="Hugging Face Token", type="password")
393
  modelscope_token = gr.Textbox(label="ModelScope Token (optional)", type="password", visible=MODELScope_AVAILABLE)
394
+
395
  with gr.Column():
396
  target_type = gr.Radio(["huggingface", "modelscope"], value="huggingface", label="Target")
397
  new_repo_id = gr.Textbox(label="New Repo ID", placeholder="user/model-fp8-lora")
398
  private_repo = gr.Checkbox(label="Private Repository (HF only)", value=False)
399
+
400
  status_output = gr.Markdown()
401
  detailed_log = gr.Textbox(label="Processing Log", interactive=False, lines=10)
402
+
403
  convert_btn = gr.Button("πŸš€ Convert & Upload", variant="primary")
404
  repo_link_output = gr.HTML()
405
+
406
  convert_btn.click(
407
  fn=process_and_upload_fp8,
408
  inputs=[
 
421
  outputs=[repo_link_output, status_output, detailed_log],
422
  show_progress=True
423
  )
424
+
425
  gr.Examples(
426
  examples=[
427
  ["huggingface", "https://huggingface.co/Yabo/FramePainter/tree/main", "unet_diffusion_pytorch_model.safetensors", "e5m2", 64, "unet_transformer"],
 
431
  inputs=[source_type, repo_url, safetensors_filename, fp8_format, lora_rank, architecture],
432
  label="Example Conversions"
433
  )
434
+
435
  gr.Markdown("""
436
  ## πŸ’‘ Usage Tips
437
+ - **Text Encoder**: Use rank 32–64 with `text_encoder` architecture
438
+ - **UNet Attention**: Use `unet_transformer` with rank 64–128
439
+ - **UNet Convolutions**: Use `unet_conv` with rank 16–32
440
+ - **VAE**: Use `vae` with rank 16–32
441
+ - **Auto Mode**: Let the tool analyze and select layers automatically
442
+ - Higher ranks = better quality but larger LoRA files
 
 
443
  """)
444
 
445
  demo.launch()