Spaces:
Running
on
Zero
Running
on
Zero
up
Browse files- README.md +1 -6
- aoti.py +15 -0
- app.py +33 -84
- hub_utils.py +0 -35
- optimization.py +0 -43
README.md
CHANGED
@@ -1,5 +1,5 @@
|
|
1 |
---
|
2 |
-
title: Flux.1-Dev Compiled Graph
|
3 |
emoji: 🖼️
|
4 |
colorFrom: yellow
|
5 |
colorTo: green
|
@@ -7,11 +7,6 @@ sdk: gradio
|
|
7 |
sdk_version: 5.39.0
|
8 |
app_file: app.py
|
9 |
pinned: false
|
10 |
-
hf_oauth: true
|
11 |
-
hf_oauth_scopes:
|
12 |
-
- read-repos
|
13 |
-
- write-repos
|
14 |
-
- manage-repos
|
15 |
---
|
16 |
|
17 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
1 |
---
|
2 |
+
title: Flux.1-Dev Use Compiled Graph
|
3 |
emoji: 🖼️
|
4 |
colorFrom: yellow
|
5 |
colorTo: green
|
|
|
7 |
sdk_version: 5.39.0
|
8 |
app_file: app.py
|
9 |
pinned: false
|
|
|
|
|
|
|
|
|
|
|
10 |
---
|
11 |
|
12 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
aoti.py
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from huggingface_hub import hf_hub_download
|
3 |
+
from spaces.zero.torch.aoti import ZeroGPUCompiledModel
|
4 |
+
from spaces.zero.torch.aoti import ZeroGPUWeights
|
5 |
+
from spaces.zero.torch.aoti import drain_module_parameters
|
6 |
+
|
7 |
+
|
8 |
+
def aoti_load_(module: torch.nn.Module, repo_id: str, filename: str):
|
9 |
+
compiled_graph_file = hf_hub_download(repo_id, filename)
|
10 |
+
state_dict = module.state_dict()
|
11 |
+
zerogpu_weights = ZeroGPUWeights({name: weight for name, weight in state_dict.items()})
|
12 |
+
compiled = ZeroGPUCompiledModel(compiled_graph_file, zerogpu_weights)
|
13 |
+
|
14 |
+
setattr(module, "forward", compiled)
|
15 |
+
drain_module_parameters(module)
|
app.py
CHANGED
@@ -1,90 +1,39 @@
|
|
1 |
-
|
|
|
|
|
2 |
import gradio as gr
|
|
|
3 |
import torch
|
4 |
-
from diffusers import
|
5 |
-
|
6 |
-
from
|
7 |
-
from huggingface_hub import whoami
|
8 |
-
import time
|
9 |
|
10 |
# --- Model Loading ---
|
11 |
dtype = torch.bfloat16
|
12 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
if not isinstance(out, str) and hasattr(out, "commit_url"):
|
40 |
-
commit_url = out.commit_url
|
41 |
-
return f"[{commit_url}]({commit_url})"
|
42 |
-
else:
|
43 |
-
return out
|
44 |
-
except Exception as e:
|
45 |
-
raise gr.Error(
|
46 |
-
f"""Oops, you forgot to login. Please use the loggin button on the top left to migrate your repo {e}"""
|
47 |
-
)
|
48 |
-
|
49 |
-
|
50 |
-
css = """
|
51 |
-
#col-container {
|
52 |
-
margin: 0 auto;
|
53 |
-
max-width: 520px;
|
54 |
-
}
|
55 |
-
"""
|
56 |
-
with gr.Blocks(css=css) as demo:
|
57 |
-
with gr.Column(elem_id="col-container"):
|
58 |
-
gr.Markdown(
|
59 |
-
"## Compile [Flux.1-Dev](https://hf.co/black-forest-labs/Flux.1-Dev) graph ahead of time & push to the Hub"
|
60 |
-
)
|
61 |
-
gr.Markdown(
|
62 |
-
"Enter a **repo_id** and **filename**. This repo automatically compiles the Flux.1-Dev model ahead of time. Read more about this in [this post](https://huggingface.co/blog/zerogpu-aoti)."
|
63 |
-
)
|
64 |
-
gr.Markdown("Depending on the model, it can take some time (2-10 mins) to compile.")
|
65 |
-
|
66 |
-
repo_id = gr.Textbox(label="repo_id", placeholder="e.g. sayakpaul/qwen-aot")
|
67 |
-
filename = gr.Textbox(label="filename", placeholder="e.g. compiled.pt2")
|
68 |
-
|
69 |
-
run = gr.Button("Push graph to Hub", variant="primary")
|
70 |
-
|
71 |
-
markdown_out = gr.Markdown()
|
72 |
-
|
73 |
-
run.click(push_to_hub, inputs=[repo_id, filename], outputs=[markdown_out])
|
74 |
-
|
75 |
-
|
76 |
-
def swap_visibilty(profile: gr.OAuthProfile | None):
|
77 |
-
return gr.update(elem_classes=["main_ui_logged_in"]) if profile else gr.update(elem_classes=["main_ui_logged_out"])
|
78 |
-
|
79 |
-
|
80 |
-
css_login = """
|
81 |
-
.main_ui_logged_out{opacity: 0.3; pointer-events: none; margin: 0 auto; max-width: 520px}
|
82 |
-
"""
|
83 |
-
with gr.Blocks(css=css_login) as demo_login:
|
84 |
-
gr.LoginButton()
|
85 |
-
with gr.Column(elem_classes="main_ui_logged_out") as main_ui:
|
86 |
-
demo.render()
|
87 |
-
demo_login.load(fn=swap_visibilty, outputs=main_ui)
|
88 |
-
|
89 |
-
demo_login.queue()
|
90 |
-
demo_login.launch()
|
|
|
1 |
+
|
2 |
+
from datetime import datetime
|
3 |
+
|
4 |
import gradio as gr
|
5 |
+
import spaces
|
6 |
import torch
|
7 |
+
from diffusers import FluxPipeline
|
8 |
+
|
9 |
+
from aoti import aoti_load
|
|
|
|
|
10 |
|
11 |
# --- Model Loading ---
|
12 |
dtype = torch.bfloat16
|
13 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
14 |
+
pipeline = FluxPipeline.from_pretrained(
|
15 |
+
"black-forest-labs/Flux.1-Dev", torch_dtype=torch.bfloat16
|
16 |
+
).to(device)
|
17 |
+
pipeline.transformer.fuse_qkv_projections()
|
18 |
+
aoti_load_(pipeline.transformer, "sayakpaul/flux-dev-aot", "flux-dev-aot.pt2")
|
19 |
+
|
20 |
+
|
21 |
+
@spaces.GPU
|
22 |
+
def generate_image(prompt: str, progress=gr.Progress(track_tqdm=True)):
|
23 |
+
generator = torch.Generator(device='cuda').manual_seed(42)
|
24 |
+
t0 = datetime.now()
|
25 |
+
output = pipeline(
|
26 |
+
prompt=prompt,
|
27 |
+
num_inference_steps=28,
|
28 |
+
generator=generator,
|
29 |
+
)
|
30 |
+
return [(output.images[0], f'{(datetime.now() - t0).total_seconds():.2f}s')]
|
31 |
+
|
32 |
+
|
33 |
+
gr.Interface(
|
34 |
+
fn=generate_image,
|
35 |
+
inputs=gr.Text(label="Prompt"),
|
36 |
+
outputs=gr.Gallery(),
|
37 |
+
examples=["A cat playing with a ball of yarn"],
|
38 |
+
cache_examples=False,
|
39 |
+
).launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
hub_utils.py
DELETED
@@ -1,35 +0,0 @@
|
|
1 |
-
from io import BytesIO
|
2 |
-
from huggingface_hub import create_repo, upload_file
|
3 |
-
import tempfile
|
4 |
-
import os
|
5 |
-
|
6 |
-
DEFAULT_ARCHIVE_FILENAME = "archived_graph.pt2"
|
7 |
-
|
8 |
-
|
9 |
-
def _push_compiled_graph_to_hub(archive: BytesIO, repo_id, **kwargs):
|
10 |
-
if not isinstance(archive, BytesIO):
|
11 |
-
raise NotImplementedError("Incorrect type of `archive` provided.")
|
12 |
-
|
13 |
-
commit_message = kwargs.pop("commit_message", "Uploaded from spaces.")
|
14 |
-
private = kwargs.pop("private", False)
|
15 |
-
path_in_repo = kwargs.pop("path_in_repo", DEFAULT_ARCHIVE_FILENAME)
|
16 |
-
token = kwargs.pop("token")
|
17 |
-
repo_id = create_repo(repo_id, private=private, exist_ok=True, token=token).repo_id
|
18 |
-
|
19 |
-
with tempfile.TemporaryDirectory() as tmpdir:
|
20 |
-
output_path = os.path.join(tmpdir, os.path.basename(path_in_repo))
|
21 |
-
with open(output_path, "wb") as f:
|
22 |
-
f.write(archive.getvalue())
|
23 |
-
|
24 |
-
try:
|
25 |
-
info = upload_file(
|
26 |
-
repo_id=repo_id,
|
27 |
-
path_or_fileobj=output_path,
|
28 |
-
path_in_repo=os.path.basename(path_in_repo),
|
29 |
-
commit_message=commit_message,
|
30 |
-
token=token,
|
31 |
-
)
|
32 |
-
return info
|
33 |
-
except Exception as e:
|
34 |
-
print(f"File couldn't be pushed to the Hub with the following error: {e}.")
|
35 |
-
return e
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
optimization.py
DELETED
@@ -1,43 +0,0 @@
|
|
1 |
-
import spaces
|
2 |
-
from typing import Any
|
3 |
-
from typing import Callable
|
4 |
-
from typing import ParamSpec
|
5 |
-
import torch
|
6 |
-
from torch.utils._pytree import tree_map
|
7 |
-
|
8 |
-
P = ParamSpec("P")
|
9 |
-
|
10 |
-
TRANSFORMER_HIDDEN_DIM = torch.export.Dim("hidden", min=4096, max=8212)
|
11 |
-
|
12 |
-
# Specific to Flux. More about this is available in
|
13 |
-
# https://huggingface.co/blog/zerogpu-aoti
|
14 |
-
TRANSFORMER_DYNAMIC_SHAPES = {
|
15 |
-
"hidden_states": {1: TRANSFORMER_HIDDEN_DIM},
|
16 |
-
"img_ids": {0: TRANSFORMER_HIDDEN_DIM},
|
17 |
-
}
|
18 |
-
|
19 |
-
INDUCTOR_CONFIGS = {
|
20 |
-
"conv_1x1_as_mm": True,
|
21 |
-
"epilogue_fusion": False,
|
22 |
-
"coordinate_descent_tuning": True,
|
23 |
-
"coordinate_descent_check_all_directions": True,
|
24 |
-
"max_autotune": True,
|
25 |
-
"triton.cudagraphs": True,
|
26 |
-
}
|
27 |
-
|
28 |
-
|
29 |
-
def compile_transformer(pipeline: Callable[P, Any], *args: P.args, **kwargs: P.kwargs):
|
30 |
-
def f():
|
31 |
-
with spaces.aoti_capture(pipeline.transformer) as call:
|
32 |
-
pipeline(*args, **kwargs)
|
33 |
-
|
34 |
-
dynamic_shapes = tree_map(lambda v: None, call.kwargs)
|
35 |
-
dynamic_shapes |= TRANSFORMER_DYNAMIC_SHAPES
|
36 |
-
|
37 |
-
exported = torch.export.export(
|
38 |
-
mod=pipeline.transformer, args=call.args, kwargs=call.kwargs, dynamic_shapes=dynamic_shapes
|
39 |
-
)
|
40 |
-
return spaces.aoti_compile(exported, INDUCTOR_CONFIGS)
|
41 |
-
|
42 |
-
compiled_transformer = f()
|
43 |
-
return compiled_transformer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|