Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -10,18 +10,15 @@ from huggingface_hub import HfApi, hf_hub_download
|
|
| 10 |
from safetensors.torch import load_file, save_file
|
| 11 |
import torch
|
| 12 |
|
| 13 |
-
# Optional ModelScope integration
|
| 14 |
try:
|
| 15 |
-
from modelscope.hub.snapshot_download import snapshot_download as ms_snapshot_download
|
| 16 |
from modelscope.hub.file_download import model_file_download as ms_file_download
|
| 17 |
from modelscope.hub.api import HubApi as ModelScopeApi
|
| 18 |
MODELScope_AVAILABLE = True
|
| 19 |
except ImportError:
|
| 20 |
MODELScope_AVAILABLE = False
|
| 21 |
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
progress(0.1, desc="Starting FP8 conversion...")
|
| 25 |
|
| 26 |
try:
|
| 27 |
def read_safetensors_metadata(path):
|
|
@@ -32,76 +29,63 @@ def convert_safetensors_to_fp8(safetensors_path, output_dir, fp8_format, progres
|
|
| 32 |
return header.get('__metadata__', {})
|
| 33 |
|
| 34 |
metadata = read_safetensors_metadata(safetensors_path)
|
| 35 |
-
progress(0.
|
| 36 |
|
| 37 |
state_dict = load_file(safetensors_path)
|
| 38 |
-
progress(0.
|
| 39 |
|
| 40 |
if fp8_format == "e5m2":
|
| 41 |
fp8_dtype = torch.float8_e5m2
|
| 42 |
else:
|
| 43 |
fp8_dtype = torch.float8_e4m3fn
|
| 44 |
|
| 45 |
-
|
|
|
|
| 46 |
total = len(state_dict)
|
|
|
|
| 47 |
for i, key in enumerate(state_dict):
|
| 48 |
-
progress(0.
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
else:
|
| 52 |
-
|
| 53 |
|
| 54 |
base_name = os.path.splitext(os.path.basename(safetensors_path))[0]
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
|
|
|
|
|
|
| 58 |
|
| 59 |
-
progress(
|
| 60 |
-
|
|
|
|
| 61 |
|
| 62 |
except Exception as e:
|
| 63 |
return False, str(e)
|
| 64 |
|
| 65 |
-
# --- Parse HF URL with optional subfolder ---
|
| 66 |
def parse_hf_url(url):
|
| 67 |
-
"""
|
| 68 |
-
Parses a Hugging Face URL like:
|
| 69 |
-
- https://huggingface.co/username/repo
|
| 70 |
-
- https://huggingface.co/username/repo/tree/main/subfolder
|
| 71 |
-
Returns (repo_id, subfolder)
|
| 72 |
-
"""
|
| 73 |
url = url.strip().rstrip("/")
|
| 74 |
if not url.startswith("https://huggingface.co/"):
|
| 75 |
raise ValueError("URL must start with https://huggingface.co/")
|
| 76 |
path = url.replace("https://huggingface.co/", "")
|
| 77 |
parts = path.split("/")
|
| 78 |
-
|
| 79 |
if len(parts) < 2:
|
| 80 |
raise ValueError("Invalid repo format")
|
| 81 |
-
|
| 82 |
-
# repo_id is always first two parts
|
| 83 |
repo_id = "/".join(parts[:2])
|
| 84 |
-
|
| 85 |
-
# Check if "/tree/branch/" is present
|
| 86 |
subfolder = ""
|
| 87 |
if len(parts) > 3 and parts[2] == "tree":
|
| 88 |
-
# everything after branch is subfolder
|
| 89 |
subfolder = "/".join(parts[4:]) if len(parts) > 4 else ""
|
| 90 |
elif len(parts) > 2:
|
| 91 |
-
# old style: username/repo/subfolder (not standard, but support)
|
| 92 |
subfolder = "/".join(parts[2:])
|
| 93 |
-
|
| 94 |
return repo_id, subfolder
|
| 95 |
|
| 96 |
-
|
| 97 |
-
def download_safetensors_file(
|
| 98 |
-
source_type,
|
| 99 |
-
repo_url,
|
| 100 |
-
filename,
|
| 101 |
-
hf_token=None,
|
| 102 |
-
modelscope_token=None,
|
| 103 |
-
progress=gr.Progress()
|
| 104 |
-
):
|
| 105 |
temp_dir = tempfile.mkdtemp()
|
| 106 |
try:
|
| 107 |
if source_type == "huggingface":
|
|
@@ -116,79 +100,31 @@ def download_safetensors_file(
|
|
| 116 |
)
|
| 117 |
elif source_type == "modelscope":
|
| 118 |
if not MODELScope_AVAILABLE:
|
| 119 |
-
raise ImportError("ModelScope not installed
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
src_repo_id = "/".join(clean_url.split("/")[-2:])
|
| 123 |
-
else:
|
| 124 |
-
src_repo_id = repo_url.strip()
|
| 125 |
-
if modelscope_token:
|
| 126 |
-
os.environ["MODELSCOPE_CACHE"] = temp_dir
|
| 127 |
-
safetensors_path = ms_file_download(
|
| 128 |
-
model_id=src_repo_id,
|
| 129 |
-
file_path=filename,
|
| 130 |
-
token=modelscope_token
|
| 131 |
-
)
|
| 132 |
-
else:
|
| 133 |
-
safetensors_path = ms_file_download(
|
| 134 |
-
model_id=src_repo_id,
|
| 135 |
-
file_path=filename
|
| 136 |
-
)
|
| 137 |
else:
|
| 138 |
-
raise ValueError("Unknown source
|
| 139 |
-
|
| 140 |
return safetensors_path, temp_dir
|
| 141 |
except Exception as e:
|
| 142 |
shutil.rmtree(temp_dir, ignore_errors=True)
|
| 143 |
raise e
|
| 144 |
|
| 145 |
-
|
| 146 |
-
def upload_to_target(
|
| 147 |
-
target_type,
|
| 148 |
-
new_repo_id,
|
| 149 |
-
output_dir,
|
| 150 |
-
fp8_format,
|
| 151 |
-
hf_token=None,
|
| 152 |
-
modelscope_token=None,
|
| 153 |
-
private_repo=False,
|
| 154 |
-
progress=gr.Progress()
|
| 155 |
-
):
|
| 156 |
if target_type == "huggingface":
|
| 157 |
-
if not hf_token:
|
| 158 |
-
raise ValueError("Hugging Face token required")
|
| 159 |
api = HfApi(token=hf_token)
|
| 160 |
-
api.create_repo(
|
| 161 |
-
|
| 162 |
-
private=private_repo,
|
| 163 |
-
repo_type="model",
|
| 164 |
-
exist_ok=True
|
| 165 |
-
)
|
| 166 |
-
api.upload_folder(
|
| 167 |
-
repo_id=new_repo_id,
|
| 168 |
-
folder_path=output_dir,
|
| 169 |
-
repo_type="model",
|
| 170 |
-
token=hf_token,
|
| 171 |
-
commit_message=f"Upload FP8 ({fp8_format}) model"
|
| 172 |
-
)
|
| 173 |
return f"https://huggingface.co/{new_repo_id}"
|
| 174 |
-
|
| 175 |
elif target_type == "modelscope":
|
| 176 |
-
if not MODELScope_AVAILABLE:
|
| 177 |
-
raise ImportError("ModelScope not installed")
|
| 178 |
api = ModelScopeApi()
|
| 179 |
if modelscope_token:
|
| 180 |
api.login(modelscope_token)
|
| 181 |
-
api.push_model(
|
| 182 |
-
model_id=new_repo_id,
|
| 183 |
-
model_dir=output_dir,
|
| 184 |
-
commit_message=f"Upload FP8 ({fp8_format}) model"
|
| 185 |
-
)
|
| 186 |
return f"https://modelscope.cn/models/{new_repo_id}"
|
| 187 |
-
|
| 188 |
else:
|
| 189 |
-
raise ValueError("Unknown target
|
| 190 |
|
| 191 |
-
# --- Main Processing Function ---
|
| 192 |
def process_and_upload_fp8(
|
| 193 |
source_type,
|
| 194 |
repo_url,
|
|
@@ -201,79 +137,80 @@ def process_and_upload_fp8(
|
|
| 201 |
private_repo,
|
| 202 |
progress=gr.Progress()
|
| 203 |
):
|
| 204 |
-
required_fields = [repo_url, safetensors_filename, new_repo_id]
|
| 205 |
-
if source_type == "huggingface":
|
| 206 |
-
required_fields.append(hf_token)
|
| 207 |
-
if target_type == "huggingface":
|
| 208 |
-
required_fields.append(hf_token)
|
| 209 |
-
if target_type == "modelscope" and modelscope_token:
|
| 210 |
-
required_fields.append(modelscope_token)
|
| 211 |
-
|
| 212 |
-
if not all(required_fields):
|
| 213 |
-
return None, "β Error: Please fill in all required fields.", ""
|
| 214 |
-
|
| 215 |
if not re.match(r"^[a-zA-Z0-9._-]+/[a-zA-Z0-9._-]+$", new_repo_id):
|
| 216 |
-
return None, "β Invalid
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
|
| 218 |
temp_dir = None
|
| 219 |
output_dir = tempfile.mkdtemp()
|
| 220 |
|
| 221 |
try:
|
| 222 |
-
progress(0.05, desc="
|
| 223 |
safetensors_path, temp_dir = download_safetensors_file(
|
| 224 |
-
source_type
|
| 225 |
-
repo_url=repo_url,
|
| 226 |
-
filename=safetensors_filename,
|
| 227 |
-
hf_token=hf_token,
|
| 228 |
-
modelscope_token=modelscope_token,
|
| 229 |
-
progress=progress
|
| 230 |
)
|
| 231 |
-
progress(0.25, desc="Download complete.")
|
| 232 |
|
| 233 |
-
|
|
|
|
| 234 |
if not success:
|
| 235 |
return None, f"β Conversion failed: {msg}", ""
|
| 236 |
|
| 237 |
-
progress(0.
|
| 238 |
repo_url_final = upload_to_target(
|
| 239 |
-
target_type
|
| 240 |
-
new_repo_id=new_repo_id,
|
| 241 |
-
output_dir=output_dir,
|
| 242 |
-
fp8_format=fp8_format,
|
| 243 |
-
hf_token=hf_token,
|
| 244 |
-
modelscope_token=modelscope_token,
|
| 245 |
-
private_repo=private_repo,
|
| 246 |
-
progress=progress
|
| 247 |
)
|
| 248 |
|
| 249 |
base_name = os.path.splitext(safetensors_filename)[0]
|
| 250 |
-
fp8_filename = f"{base_name}-fp8-{fp8_format}.safetensors"
|
| 251 |
readme = f"""---
|
| 252 |
library_name: diffusers
|
| 253 |
tags:
|
| 254 |
- fp8
|
| 255 |
- safetensors
|
| 256 |
-
-
|
| 257 |
- diffusion
|
| 258 |
- converted-by-gradio
|
| 259 |
-
- fp8-{fp8_format}
|
| 260 |
---
|
| 261 |
|
| 262 |
-
# FP8
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 263 |
|
| 264 |
-
|
| 265 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 266 |
|
| 267 |
-
|
| 268 |
-
Converted on: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
|
| 269 |
"""
|
| 270 |
-
|
| 271 |
-
with open(readme_path, "w") as f:
|
| 272 |
f.write(readme)
|
| 273 |
|
| 274 |
if target_type == "huggingface":
|
| 275 |
HfApi(token=hf_token).upload_file(
|
| 276 |
-
path_or_fileobj=
|
| 277 |
path_in_repo="README.md",
|
| 278 |
repo_id=new_repo_id,
|
| 279 |
repo_type="model",
|
|
@@ -283,10 +220,10 @@ Converted on: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
|
|
| 283 |
progress(1.0, desc="β
Done!")
|
| 284 |
result_html = f"""
|
| 285 |
β
Success!
|
| 286 |
-
|
| 287 |
-
|
| 288 |
"""
|
| 289 |
-
return gr.HTML(result_html), "β
FP8
|
| 290 |
|
| 291 |
except Exception as e:
|
| 292 |
return None, f"β Error: {str(e)}", ""
|
|
@@ -295,59 +232,26 @@ Source: {source_type.title()} β Target: {target_type.title()}
|
|
| 295 |
shutil.rmtree(temp_dir, ignore_errors=True)
|
| 296 |
shutil.rmtree(output_dir, ignore_errors=True)
|
| 297 |
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
gr.Markdown("
|
| 301 |
-
gr.Markdown("Convert `.safetensors` models to **FP8** and upload to **Hugging Face** or **ModelScope**.")
|
| 302 |
-
gr.Markdown("Supports subfolders: e.g., `https://huggingface.co/lixiaowen/diffuEraser/tree/main/brushnet`")
|
| 303 |
|
| 304 |
with gr.Row():
|
| 305 |
with gr.Column():
|
| 306 |
-
source_type = gr.Radio(
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
)
|
| 311 |
-
|
| 312 |
-
label="Source Repository URL",
|
| 313 |
-
placeholder="https://huggingface.co/lixiaowen/diffuEraser/tree/main/brushnet",
|
| 314 |
-
info="Full URL including subfolder (if any)"
|
| 315 |
-
)
|
| 316 |
-
safetensors_filename = gr.Textbox(
|
| 317 |
-
label="Safetensors Filename",
|
| 318 |
-
placeholder="diffusion_pytorch_model.safetensors"
|
| 319 |
-
)
|
| 320 |
-
fp8_format = gr.Radio(
|
| 321 |
-
choices=["e4m3fn", "e5m2"],
|
| 322 |
-
value="e5m2",
|
| 323 |
-
label="FP8 Format"
|
| 324 |
-
)
|
| 325 |
-
hf_token = gr.Textbox(
|
| 326 |
-
label="Hugging Face Token (if using HF)",
|
| 327 |
-
type="password"
|
| 328 |
-
)
|
| 329 |
-
modelscope_token = gr.Textbox(
|
| 330 |
-
label="ModelScope Token (optional)",
|
| 331 |
-
type="password",
|
| 332 |
-
visible=MODELScope_AVAILABLE
|
| 333 |
-
)
|
| 334 |
with gr.Column():
|
| 335 |
-
target_type = gr.Radio(
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
label="Target Platform"
|
| 339 |
-
)
|
| 340 |
-
new_repo_id = gr.Textbox(
|
| 341 |
-
label="New Repository ID",
|
| 342 |
-
placeholder="your-username/my-model-fp8"
|
| 343 |
-
)
|
| 344 |
-
private_repo = gr.Checkbox(label="Make Private (HF only)", value=False)
|
| 345 |
|
| 346 |
convert_btn = gr.Button("π Convert & Upload", variant="primary")
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
status_output = gr.Markdown()
|
| 350 |
-
repo_link_output = gr.HTML()
|
| 351 |
|
| 352 |
convert_btn.click(
|
| 353 |
fn=process_and_upload_fp8,
|
|
@@ -368,7 +272,7 @@ with gr.Blocks(title="Safetensors β FP8 Pruner (HF + ModelScope)") as demo:
|
|
| 368 |
|
| 369 |
gr.Examples(
|
| 370 |
examples=[
|
| 371 |
-
["huggingface", "https://huggingface.co/
|
| 372 |
],
|
| 373 |
inputs=[source_type, repo_url, safetensors_filename, fp8_format, target_type]
|
| 374 |
)
|
|
|
|
| 10 |
from safetensors.torch import load_file, save_file
|
| 11 |
import torch
|
| 12 |
|
|
|
|
| 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
|
| 16 |
MODELScope_AVAILABLE = True
|
| 17 |
except ImportError:
|
| 18 |
MODELScope_AVAILABLE = False
|
| 19 |
|
| 20 |
+
def convert_safetensors_to_fp8_with_delta(safetensors_path, output_dir, fp8_format, progress=gr.Progress()):
|
| 21 |
+
progress(0.1, desc="Starting FP8 conversion with delta...")
|
|
|
|
| 22 |
|
| 23 |
try:
|
| 24 |
def read_safetensors_metadata(path):
|
|
|
|
| 29 |
return header.get('__metadata__', {})
|
| 30 |
|
| 31 |
metadata = read_safetensors_metadata(safetensors_path)
|
| 32 |
+
progress(0.2, desc="Loaded metadata.")
|
| 33 |
|
| 34 |
state_dict = load_file(safetensors_path)
|
| 35 |
+
progress(0.4, desc="Loaded weights.")
|
| 36 |
|
| 37 |
if fp8_format == "e5m2":
|
| 38 |
fp8_dtype = torch.float8_e5m2
|
| 39 |
else:
|
| 40 |
fp8_dtype = torch.float8_e4m3fn
|
| 41 |
|
| 42 |
+
sd_fp8 = {}
|
| 43 |
+
sd_delta = {}
|
| 44 |
total = len(state_dict)
|
| 45 |
+
|
| 46 |
for i, key in enumerate(state_dict):
|
| 47 |
+
progress(0.4 + 0.4 * (i / total), desc=f"Processing {i+1}/{total}...")
|
| 48 |
+
weight = state_dict[key]
|
| 49 |
+
if weight.dtype in [torch.float16, torch.float32, torch.bfloat16]:
|
| 50 |
+
fp8_weight = weight.to(fp8_dtype)
|
| 51 |
+
fp8_recon = fp8_weight.to(weight.dtype)
|
| 52 |
+
delta = weight - fp8_recon
|
| 53 |
+
sd_fp8[key] = fp8_weight
|
| 54 |
+
sd_delta[f"delta.{key}"] = delta
|
| 55 |
else:
|
| 56 |
+
sd_fp8[key] = weight
|
| 57 |
|
| 58 |
base_name = os.path.splitext(os.path.basename(safetensors_path))[0]
|
| 59 |
+
fp8_path = os.path.join(output_dir, f"{base_name}-fp8-{fp8_format}.safetensors")
|
| 60 |
+
delta_path = os.path.join(output_dir, f"{base_name}-fp8-delta.safetensors")
|
| 61 |
+
|
| 62 |
+
save_file(sd_fp8, fp8_path, metadata={"format": "pt", "fp8_format": fp8_format, **metadata})
|
| 63 |
+
save_file(sd_delta, delta_path, metadata={"format": "pt", "source": "fp8_delta", "fp8_format": fp8_format})
|
| 64 |
|
| 65 |
+
progress(0.9, desc="Saved FP8 and delta files.")
|
| 66 |
+
progress(1.0, desc="β
FP8 + delta generation complete!")
|
| 67 |
+
return True, f"FP8 ({fp8_format}) and delta saved."
|
| 68 |
|
| 69 |
except Exception as e:
|
| 70 |
return False, str(e)
|
| 71 |
|
|
|
|
| 72 |
def parse_hf_url(url):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
url = url.strip().rstrip("/")
|
| 74 |
if not url.startswith("https://huggingface.co/"):
|
| 75 |
raise ValueError("URL must start with https://huggingface.co/")
|
| 76 |
path = url.replace("https://huggingface.co/", "")
|
| 77 |
parts = path.split("/")
|
|
|
|
| 78 |
if len(parts) < 2:
|
| 79 |
raise ValueError("Invalid repo format")
|
|
|
|
|
|
|
| 80 |
repo_id = "/".join(parts[:2])
|
|
|
|
|
|
|
| 81 |
subfolder = ""
|
| 82 |
if len(parts) > 3 and parts[2] == "tree":
|
|
|
|
| 83 |
subfolder = "/".join(parts[4:]) if len(parts) > 4 else ""
|
| 84 |
elif len(parts) > 2:
|
|
|
|
| 85 |
subfolder = "/".join(parts[2:])
|
|
|
|
| 86 |
return repo_id, subfolder
|
| 87 |
|
| 88 |
+
def download_safetensors_file(source_type, repo_url, filename, hf_token=None, progress=gr.Progress()):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
temp_dir = tempfile.mkdtemp()
|
| 90 |
try:
|
| 91 |
if source_type == "huggingface":
|
|
|
|
| 100 |
)
|
| 101 |
elif source_type == "modelscope":
|
| 102 |
if not MODELScope_AVAILABLE:
|
| 103 |
+
raise ImportError("ModelScope not installed")
|
| 104 |
+
repo_id = repo_url.strip()
|
| 105 |
+
safetensors_path = ms_file_download(model_id=repo_id, file_path=filename)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
else:
|
| 107 |
+
raise ValueError("Unknown source")
|
|
|
|
| 108 |
return safetensors_path, temp_dir
|
| 109 |
except Exception as e:
|
| 110 |
shutil.rmtree(temp_dir, ignore_errors=True)
|
| 111 |
raise e
|
| 112 |
|
| 113 |
+
def upload_to_target(target_type, new_repo_id, output_dir, fp8_format, hf_token=None, modelscope_token=None, private_repo=False):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
if target_type == "huggingface":
|
|
|
|
|
|
|
| 115 |
api = HfApi(token=hf_token)
|
| 116 |
+
api.create_repo(repo_id=new_repo_id, private=private_repo, repo_type="model", exist_ok=True)
|
| 117 |
+
api.upload_folder(repo_id=new_repo_id, folder_path=output_dir, repo_type="model", token=hf_token)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
return f"https://huggingface.co/{new_repo_id}"
|
|
|
|
| 119 |
elif target_type == "modelscope":
|
|
|
|
|
|
|
| 120 |
api = ModelScopeApi()
|
| 121 |
if modelscope_token:
|
| 122 |
api.login(modelscope_token)
|
| 123 |
+
api.push_model(model_id=new_repo_id, model_dir=output_dir)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
return f"https://modelscope.cn/models/{new_repo_id}"
|
|
|
|
| 125 |
else:
|
| 126 |
+
raise ValueError("Unknown target")
|
| 127 |
|
|
|
|
| 128 |
def process_and_upload_fp8(
|
| 129 |
source_type,
|
| 130 |
repo_url,
|
|
|
|
| 137 |
private_repo,
|
| 138 |
progress=gr.Progress()
|
| 139 |
):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
if not re.match(r"^[a-zA-Z0-9._-]+/[a-zA-Z0-9._-]+$", new_repo_id):
|
| 141 |
+
return None, "β Invalid repo ID format. Use 'username/model-name'.", ""
|
| 142 |
+
|
| 143 |
+
if source_type == "huggingface" and not hf_token:
|
| 144 |
+
return None, "β Hugging Face token required for source.", ""
|
| 145 |
+
if target_type == "huggingface" and not hf_token:
|
| 146 |
+
return None, "β Hugging Face token required for target.", ""
|
| 147 |
|
| 148 |
temp_dir = None
|
| 149 |
output_dir = tempfile.mkdtemp()
|
| 150 |
|
| 151 |
try:
|
| 152 |
+
progress(0.05, desc="Downloading model...")
|
| 153 |
safetensors_path, temp_dir = download_safetensors_file(
|
| 154 |
+
source_type, repo_url, safetensors_filename, hf_token, progress
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
)
|
|
|
|
| 156 |
|
| 157 |
+
progress(0.25, desc="Converting to FP8 with delta...")
|
| 158 |
+
success, msg = convert_safetensors_to_fp8_with_delta(safetensors_path, output_dir, fp8_format, progress)
|
| 159 |
if not success:
|
| 160 |
return None, f"β Conversion failed: {msg}", ""
|
| 161 |
|
| 162 |
+
progress(0.9, desc="Uploading...")
|
| 163 |
repo_url_final = upload_to_target(
|
| 164 |
+
target_type, new_repo_id, output_dir, fp8_format, hf_token, modelscope_token, private_repo
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
)
|
| 166 |
|
| 167 |
base_name = os.path.splitext(safetensors_filename)[0]
|
|
|
|
| 168 |
readme = f"""---
|
| 169 |
library_name: diffusers
|
| 170 |
tags:
|
| 171 |
- fp8
|
| 172 |
- safetensors
|
| 173 |
+
- delta-compensation
|
| 174 |
- diffusion
|
| 175 |
- converted-by-gradio
|
|
|
|
| 176 |
---
|
| 177 |
|
| 178 |
+
# FP8 Model with Delta Compensation
|
| 179 |
+
|
| 180 |
+
- **Source**: `{repo_url}`
|
| 181 |
+
- **File**: `{safetensors_filename}`
|
| 182 |
+
- **FP8 Format**: `{fp8_format.upper()}`
|
| 183 |
+
- **Delta File**: `{base_name}-fp8-delta.safetensors`
|
| 184 |
+
|
| 185 |
+
## Usage (Inference)
|
| 186 |
+
|
| 187 |
+
To restore near-original precision:
|
| 188 |
+
|
| 189 |
+
```python
|
| 190 |
+
import torch
|
| 191 |
+
from safetensors.torch import load_file
|
| 192 |
+
|
| 193 |
+
fp8_state = load_file("{base_name}-fp8-{fp8_format}.safetensors")
|
| 194 |
+
delta_state = load_file("{base_name}-fp8-delta.safetensors")
|
| 195 |
|
| 196 |
+
restored_state = {{}}
|
| 197 |
+
for key in fp8_state:
|
| 198 |
+
if f"delta.{{key}}" in delta_state:
|
| 199 |
+
fp8_weight = fp8_state[key].to(torch.float32)
|
| 200 |
+
delta = delta_state[f"delta.{{key}}"]
|
| 201 |
+
restored_state[key] = fp8_weight + delta
|
| 202 |
+
else:
|
| 203 |
+
restored_state[key] = fp8_state[key].to(torch.float32)
|
| 204 |
+
```
|
| 205 |
|
| 206 |
+
> Requires PyTorch β₯ 2.1 for FP8 support.
|
|
|
|
| 207 |
"""
|
| 208 |
+
with open(os.path.join(output_dir, "README.md"), "w") as f:
|
|
|
|
| 209 |
f.write(readme)
|
| 210 |
|
| 211 |
if target_type == "huggingface":
|
| 212 |
HfApi(token=hf_token).upload_file(
|
| 213 |
+
path_or_fileobj=os.path.join(output_dir, "README.md"),
|
| 214 |
path_in_repo="README.md",
|
| 215 |
repo_id=new_repo_id,
|
| 216 |
repo_type="model",
|
|
|
|
| 220 |
progress(1.0, desc="β
Done!")
|
| 221 |
result_html = f"""
|
| 222 |
β
Success!
|
| 223 |
+
Model uploaded to: <a href="{repo_url_final}" target="_blank">{new_repo_id}</a>
|
| 224 |
+
Includes: FP8 model + delta compensation file.
|
| 225 |
"""
|
| 226 |
+
return gr.HTML(result_html), "β
FP8 + delta upload successful!", ""
|
| 227 |
|
| 228 |
except Exception as e:
|
| 229 |
return None, f"β Error: {str(e)}", ""
|
|
|
|
| 232 |
shutil.rmtree(temp_dir, ignore_errors=True)
|
| 233 |
shutil.rmtree(output_dir, ignore_errors=True)
|
| 234 |
|
| 235 |
+
with gr.Blocks(title="FP8 + Delta Converter (HF β ModelScope)") as demo:
|
| 236 |
+
gr.Markdown("# π FP8 Pruner with Delta Compensation")
|
| 237 |
+
gr.Markdown("Convert `.safetensors` β **FP8** + **delta file** for precision recovery. Supports Hugging Face β ModelScope.")
|
|
|
|
|
|
|
| 238 |
|
| 239 |
with gr.Row():
|
| 240 |
with gr.Column():
|
| 241 |
+
source_type = gr.Radio(["huggingface", "modelscope"], value="huggingface", label="Source")
|
| 242 |
+
repo_url = gr.Textbox(label="Repo URL or ID", placeholder="https://huggingface.co/... or modelscope-id")
|
| 243 |
+
safetensors_filename = gr.Textbox(label="Filename", placeholder="model.safetensors")
|
| 244 |
+
fp8_format = gr.Radio(["e4m3fn", "e5m2"], value="e5m2", label="FP8 Format")
|
| 245 |
+
hf_token = gr.Textbox(label="HF Token (only if using HF)", type="password")
|
| 246 |
+
modelscope_token = gr.Textbox(label="ModelScope Token (optional)", type="password", visible=MODELScope_AVAILABLE)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 247 |
with gr.Column():
|
| 248 |
+
target_type = gr.Radio(["huggingface", "modelscope"], value="huggingface", label="Target")
|
| 249 |
+
new_repo_id = gr.Textbox(label="New Repo ID", placeholder="user/model-fp8")
|
| 250 |
+
private_repo = gr.Checkbox(label="Private (HF only)", value=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 251 |
|
| 252 |
convert_btn = gr.Button("π Convert & Upload", variant="primary")
|
| 253 |
+
status_output = gr.Markdown()
|
| 254 |
+
repo_link_output = gr.HTML()
|
|
|
|
|
|
|
| 255 |
|
| 256 |
convert_btn.click(
|
| 257 |
fn=process_and_upload_fp8,
|
|
|
|
| 272 |
|
| 273 |
gr.Examples(
|
| 274 |
examples=[
|
| 275 |
+
["huggingface", "https://huggingface.co/Yabo/FramePainter/tree/main", "unet_diffusion_pytorch_model.safetensors", "e5m2", "modelscope"]
|
| 276 |
],
|
| 277 |
inputs=[source_type, repo_url, safetensors_filename, fp8_format, target_type]
|
| 278 |
)
|