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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +353 -76
app.py CHANGED
@@ -10,7 +10,8 @@ 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
-
 
14
  try:
15
  from modelscope.hub.file_download import model_file_download as ms_file_download
16
  from modelscope.hub.api import HubApi as ModelScopeApi
@@ -19,16 +20,126 @@ except ImportError:
19
  MODELScope_AVAILABLE = False
20
 
21
  def low_rank_decomposition(weight, rank=64):
22
- if weight.ndim != 2:
23
- return None
24
- U, S, Vh = torch.linalg.svd(weight.float(), full_matrices=False)
25
- U = U[:, :rank] @ torch.diag(torch.sqrt(S[:rank]))
26
- Vh = torch.diag(torch.sqrt(S[:rank])) @ Vh[:rank, :]
27
- return U.contiguous(), Vh.contiguous()
28
-
29
- def convert_safetensors_to_fp8_with_lora(safetensors_path, output_dir, fp8_format, lora_rank=64, progress=gr.Progress()):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  progress(0.1, desc="Starting FP8 conversion with LoRA extraction...")
31
-
32
  try:
33
  def read_safetensors_metadata(path):
34
  with open(path, 'rb') as f:
@@ -36,57 +147,146 @@ def convert_safetensors_to_fp8_with_lora(safetensors_path, output_dir, fp8_forma
36
  header_json = f.read(header_size).decode('utf-8')
37
  header = json.loads(header_json)
38
  return header.get('__metadata__', {})
39
-
40
  metadata = read_safetensors_metadata(safetensors_path)
41
  progress(0.2, desc="Loaded metadata.")
42
-
43
  state_dict = load_file(safetensors_path)
44
  progress(0.4, desc="Loaded weights.")
45
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  if fp8_format == "e5m2":
47
  fp8_dtype = torch.float8_e5m2
48
  else:
49
  fp8_dtype = torch.float8_e4m3fn
50
-
51
  sd_fp8 = {}
52
  lora_weights = {}
 
 
 
 
 
 
 
 
 
53
  total = len(state_dict)
54
  lora_keys = []
55
-
56
  for i, key in enumerate(state_dict):
57
- progress(0.4 + 0.4 * (i / total), desc=f"Processing {i+1}/{total}...")
58
  weight = state_dict[key]
 
 
59
  if weight.dtype in [torch.float16, torch.float32, torch.bfloat16]:
60
  fp8_weight = weight.to(fp8_dtype)
61
  sd_fp8[key] = fp8_weight
62
-
63
- # Attempt LoRA decomposition only for 2D tensors
64
- if weight.ndim == 2 and min(weight.shape) > lora_rank:
 
 
 
 
65
  try:
66
- U, V = low_rank_decomposition(weight, rank=lora_rank)
 
 
 
 
 
 
 
 
 
 
 
67
  if U is not None and V is not None:
68
  lora_weights[f"lora_A.{key}"] = U.to(torch.float16)
69
  lora_weights[f"lora_B.{key}"] = V.to(torch.float16)
70
  lora_keys.append(key)
71
- except Exception:
72
- pass
 
 
 
 
 
 
 
 
 
73
  else:
74
  sd_fp8[key] = weight
75
-
 
76
  base_name = os.path.splitext(os.path.basename(safetensors_path))[0]
77
  fp8_path = os.path.join(output_dir, f"{base_name}-fp8-{fp8_format}.safetensors")
78
- lora_path = os.path.join(output_dir, f"{base_name}-lora-r{lora_rank}.safetensors")
79
-
80
  save_file(sd_fp8, fp8_path, metadata={"format": "pt", "fp8_format": fp8_format, **metadata})
81
- if lora_weights:
82
- save_file(lora_weights, lora_path, metadata={"format": "pt", "lora_rank": str(lora_rank)})
83
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  progress(0.9, desc="Saved FP8 and LoRA files.")
85
  progress(1.0, desc="βœ… FP8 + LoRA extraction complete!")
86
- return True, f"FP8 ({fp8_format}) and rank-{lora_rank} LoRA saved."
 
 
 
 
87
 
88
  except Exception as e:
89
- return False, str(e)
 
 
90
 
91
  def parse_hf_url(url):
92
  url = url.strip().rstrip("/")
@@ -129,7 +329,7 @@ def download_safetensors_file(source_type, repo_url, filename, hf_token=None, pr
129
  shutil.rmtree(temp_dir, ignore_errors=True)
130
  raise e
131
 
132
- def upload_to_target(target_type, new_repo_id, output_dir, fp8_format, hf_token=None, modelscope_token=None, private_repo=False):
133
  if target_type == "huggingface":
134
  api = HfApi(token=hf_token)
135
  api.create_repo(repo_id=new_repo_id, private=private_repo, repo_type="model", exist_ok=True)
@@ -150,6 +350,7 @@ def process_and_upload_fp8(
150
  safetensors_filename,
151
  fp8_format,
152
  lora_rank,
 
153
  target_type,
154
  new_repo_id,
155
  hf_token,
@@ -159,35 +360,40 @@ def process_and_upload_fp8(
159
  ):
160
  if not re.match(r"^[a-zA-Z0-9._-]+/[a-zA-Z0-9._-]+$", new_repo_id):
161
  return None, "❌ Invalid repo ID format. Use 'username/model-name'.", ""
162
-
163
  if source_type == "huggingface" and not hf_token:
164
  return None, "❌ Hugging Face token required for source.", ""
165
  if target_type == "huggingface" and not hf_token:
166
  return None, "❌ Hugging Face token required for target.", ""
167
-
 
 
 
 
168
  temp_dir = None
169
  output_dir = tempfile.mkdtemp()
170
-
171
  try:
172
  progress(0.05, desc="Downloading model...")
173
  safetensors_path, temp_dir = download_safetensors_file(
174
  source_type, repo_url, safetensors_filename, hf_token, progress
175
  )
176
-
177
- progress(0.25, desc="Converting to FP8 with LoRA extraction...")
178
- success, msg = convert_safetensors_to_fp8_with_lora(
179
- safetensors_path, output_dir, fp8_format, lora_rank, progress
180
  )
 
181
  if not success:
182
  return None, f"❌ Conversion failed: {msg}", ""
183
-
184
  progress(0.9, desc="Uploading...")
185
  repo_url_final = upload_to_target(
186
- target_type, new_repo_id, output_dir, fp8_format, hf_token, modelscope_token, private_repo
187
  )
188
-
189
  base_name = os.path.splitext(safetensors_filename)[0]
190
- lora_filename = f"{base_name}-lora-r{lora_rank}.safetensors"
 
 
191
  readme = f"""---
192
  library_name: diffusers
193
  tags:
@@ -196,45 +402,72 @@ tags:
196
  - lora
197
  - low-rank
198
  - diffusion
199
- - converted-by-gradio
 
200
  ---
201
-
202
  # FP8 Model with Low-Rank LoRA
203
-
204
  - **Source**: `{repo_url}`
205
  - **File**: `{safetensors_filename}`
206
  - **FP8 Format**: `{fp8_format.upper()}`
207
  - **LoRA Rank**: {lora_rank}
 
208
  - **LoRA File**: `{lora_filename}`
 
209
 
 
 
 
 
 
 
 
 
 
 
210
  ## Usage (Inference)
211
-
212
  ```python
213
  from safetensors.torch import load_file
214
  import torch
215
 
216
  # Load FP8 model
217
- fp8_state = load_file("{base_name}-fp8-{fp8_format}.safetensors")
218
  lora_state = load_file("{lora_filename}")
219
 
220
  # Reconstruct approximate original weights
221
  reconstructed = {{}}
222
  for key in fp8_state:
223
- if f"lora_A.{{key}}" in lora_state and f"lora_B.{{key}}" in lora_state:
224
- A = lora_state[f"lora_A.{{key}}"].to(torch.float32)
225
- B = lora_state[f"lora_B.{{key}}"].to(torch.float32)
226
- lora_weight = B @ A # (rank, out) @ (in, rank) -> (out, in)
227
- fp8_weight = fp8_state[key].to(torch.float32)
228
- reconstructed[key] = fp8_weight + lora_weight
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
  else:
230
  reconstructed[key] = fp8_state[key].to(torch.float32)
231
  ```
232
 
233
- > Requires PyTorch β‰₯ 2.1 for FP8 support.
234
  """
 
235
  with open(os.path.join(output_dir, "README.md"), "w") as f:
236
  f.write(readme)
237
-
238
  if target_type == "huggingface":
239
  HfApi(token=hf_token).upload_file(
240
  path_or_fileobj=os.path.join(output_dir, "README.md"),
@@ -243,44 +476,72 @@ for key in fp8_state:
243
  repo_type="model",
244
  token=hf_token
245
  )
246
-
247
  progress(1.0, desc="βœ… Done!")
248
  result_html = f"""
249
  βœ… Success!
250
  Model uploaded to: <a href="{repo_url_final}" target="_blank">{new_repo_id}</a>
251
- Includes: FP8 model + rank-{lora_rank} LoRA.
252
- """
253
- return gr.HTML(result_html), "βœ… FP8 + LoRA upload successful!", ""
254
 
 
 
 
 
255
  except Exception as e:
256
- return None, f"οΏ½οΏ½ Error: {str(e)}", ""
 
 
 
257
  finally:
258
  if temp_dir:
259
  shutil.rmtree(temp_dir, ignore_errors=True)
260
  shutil.rmtree(output_dir, ignore_errors=True)
261
 
262
  with gr.Blocks(title="FP8 + LoRA Extractor (HF ↔ ModelScope)") as demo:
263
- gr.Markdown("# πŸ”„ FP8 Pruner with Low-Rank LoRA Extraction")
264
- gr.Markdown("Convert `.safetensors` β†’ **FP8** + **compact LoRA** for precision recovery. Supports Hugging Face ↔ ModelScope.")
265
-
266
  with gr.Row():
267
  with gr.Column():
268
  source_type = gr.Radio(["huggingface", "modelscope"], value="huggingface", label="Source")
269
  repo_url = gr.Textbox(label="Repo URL or ID", placeholder="https://huggingface.co/... or modelscope-id")
270
  safetensors_filename = gr.Textbox(label="Filename", placeholder="model.safetensors")
271
- fp8_format = gr.Radio(["e4m3fn", "e5m2"], value="e5m2", label="FP8 Format")
272
- lora_rank = gr.Slider(minimum=8, maximum=256, step=8, value=64, label="LoRA Rank")
273
- hf_token = gr.Textbox(label="HF Token (only if using HF)", type="password")
274
- modelscope_token = gr.Textbox(label="ModelScope Token (optional)", type="password", visible=MODELScope_AVAILABLE)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
275
  with gr.Column():
276
  target_type = gr.Radio(["huggingface", "modelscope"], value="huggingface", label="Target")
277
- new_repo_id = gr.Textbox(label="New Repo ID", placeholder="user/model-fp8")
278
- private_repo = gr.Checkbox(label="Private (HF only)", value=False)
279
-
 
 
 
280
  convert_btn = gr.Button("πŸš€ Convert & Upload", variant="primary")
281
- status_output = gr.Markdown()
282
  repo_link_output = gr.HTML()
283
-
284
  convert_btn.click(
285
  fn=process_and_upload_fp8,
286
  inputs=[
@@ -289,21 +550,37 @@ with gr.Blocks(title="FP8 + LoRA Extractor (HF ↔ ModelScope)") as demo:
289
  safetensors_filename,
290
  fp8_format,
291
  lora_rank,
 
292
  target_type,
293
  new_repo_id,
294
  hf_token,
295
  modelscope_token,
296
  private_repo
297
  ],
298
- outputs=[repo_link_output, status_output],
299
  show_progress=True
300
  )
301
-
302
  gr.Examples(
303
  examples=[
304
- ["huggingface", "https://huggingface.co/Yabo/FramePainter/tree/main", "unet_diffusion_pytorch_model.safetensors", "e5m2", 64, "modelscope"]
 
 
305
  ],
306
- inputs=[source_type, repo_url, safetensors_filename, fp8_format, lora_rank, target_type]
 
307
  )
 
 
 
 
 
 
 
 
 
 
 
 
308
 
309
  demo.launch()
 
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
  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...")
 
143
  try:
144
  def read_safetensors_metadata(path):
145
  with open(path, 'rb') as f:
 
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("/")
 
329
  shutil.rmtree(temp_dir, ignore_errors=True)
330
  raise e
331
 
332
+ def upload_to_target(target_type, new_repo_id, output_dir, fp8_format, architecture, hf_token=None, modelscope_token=None, private_repo=False):
333
  if target_type == "huggingface":
334
  api = HfApi(token=hf_token)
335
  api.create_repo(repo_id=new_repo_id, private=private_repo, repo_type="model", exist_ok=True)
 
350
  safetensors_filename,
351
  fp8_format,
352
  lora_rank,
353
+ architecture,
354
  target_type,
355
  new_repo_id,
356
  hf_token,
 
360
  ):
361
  if not re.match(r"^[a-zA-Z0-9._-]+/[a-zA-Z0-9._-]+$", new_repo_id):
362
  return None, "❌ Invalid repo ID format. Use 'username/model-name'.", ""
 
363
  if source_type == "huggingface" and not hf_token:
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:
375
  progress(0.05, desc="Downloading model...")
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:
 
402
  - lora
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}`
410
  - **File**: `{safetensors_filename}`
411
  - **FP8 Format**: `{fp8_format.upper()}`
412
  - **LoRA Rank**: {lora_rank}
413
+ - **Architecture Target**: {architecture}
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
430
  import torch
431
 
432
  # Load FP8 model
433
+ fp8_state = load_file("{fp8_filename}")
434
  lora_state = load_file("{lora_filename}")
435
 
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
  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)
500
  shutil.rmtree(output_dir, ignore_errors=True)
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"),
519
+ ("Text Encoder (embeddings, attention)", "text_encoder"),
520
+ ("UNet Transformers (attention blocks)", "unet_transformer"),
521
+ ("UNet Convolutions (resnets, downsampling)", "unet_conv"),
522
+ ("VAE (encoder/decoder)", "vae"),
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=[
 
550
  safetensors_filename,
551
  fp8_format,
552
  lora_rank,
553
+ architecture,
554
  target_type,
555
  new_repo_id,
556
  hf_token,
557
  modelscope_token,
558
  private_repo
559
  ],
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"],
567
+ ["huggingface", "https://huggingface.co/stabilityai/sdxl-vae", "diffusion_pytorch_model.safetensors", "e4m3fn", 32, "vae"],
568
+ ["huggingface", "https://huggingface.co/runwayml/stable-diffusion-v1-5/tree/main/text_encoder", "model.safetensors", "e5m2", 48, "text_encoder"]
569
  ],
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()