jokerbit commited on
Commit
fee50b7
·
verified ·
1 Parent(s): daed4ce

Upload folder using huggingface_hub

Browse files
Files changed (7) hide show
  1. .gitattributes +1 -0
  2. .gitignore +9 -0
  3. README.md +19 -0
  4. pyproject.toml +30 -0
  5. src/main.py +50 -0
  6. src/pipeline.py +165 -0
  7. uv.lock +0 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ sample.png filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ **/.cache
2
+ **/__pycache__
3
+ **/*.egg-info
4
+ *.safetensors
5
+ **/.venv
6
+ .venv
7
+ .git
8
+ *.png
9
+ *.jpeg
README.md ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flux-schnell-edge-inference
2
+
3
+ This holds the baseline for the FLUX Schnel NVIDIA GeForce RTX 4090 contest, which can be forked freely and optimized
4
+
5
+ Some recommendations are as follows:
6
+ - Installing dependencies should be done in `pyproject.toml`, including git dependencies
7
+ - HuggingFace models should be specified in the `models` array in the `pyproject.toml` file, and will be downloaded before benchmarking
8
+ - The pipeline does **not** have internet access so all dependencies and models must be included in the `pyproject.toml`
9
+ - Compiled models should be hosted on HuggingFace and included in the `models` array in the `pyproject.toml` (rather than compiling during loading). Loading time matters far more than file sizes
10
+ - Avoid changing `src/main.py`, as that includes mostly protocol logic. Most changes should be in `models` and `src/pipeline.py`
11
+ - Ensure the entire repository (excluding dependencies and HuggingFace models) is under 16MB
12
+
13
+ For testing, you need a docker container with pytorch and ubuntu 22.04.
14
+ You can download your listed dependencies with `uv`, installed with:
15
+ ```bash
16
+ pipx ensurepath
17
+ pipx install uv
18
+ ```
19
+ You can then relock with `uv lock`, and then run with `uv run start_inference`
pyproject.toml ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools >= 75.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "flux-schnell-edge-inference"
7
+ description = "An edge-maxxing model submission for the 4090 Flux contest"
8
+ requires-python = ">=3.10,<3.13"
9
+ version = "8"
10
+ dependencies = [
11
+ "diffusers==0.31.0",
12
+ "transformers==4.46.2",
13
+ "accelerate==1.1.0",
14
+ "omegaconf==2.3.0",
15
+ "torch==2.5.1",
16
+ "protobuf==5.28.3",
17
+ "sentencepiece==0.2.0",
18
+ "hf_transfer==0.1.8",
19
+ "edge-maxxing-pipelines @ git+https://github.com/womboai/edge-maxxing@7c760ac54f6052803dadb3ade8ebfc9679a94589#subdirectory=pipelines",
20
+ "torchao>=0.6.1",
21
+ "ipython>=8.29.0",
22
+ "setuptools >= 75.0"
23
+ ]
24
+
25
+ [tool.edge-maxxing]
26
+ repository = "jokerbit/flux.1-schnell-Robert-int8wo"
27
+ revision = "5ef0012f11a863e5111ec56540302a023bc8587b"
28
+
29
+ [project.scripts]
30
+ start_inference = "main:main"
src/main.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from io import BytesIO
2
+ from multiprocessing.connection import Listener
3
+ from os import chmod, remove
4
+ from os.path import abspath, exists
5
+ from pathlib import Path
6
+
7
+ from PIL.JpegImagePlugin import JpegImageFile
8
+ from pipelines.models import TextToImageRequest
9
+
10
+ from pipeline import load_pipeline, infer
11
+
12
+ SOCKET = abspath(Path(__file__).parent.parent / "inferences.sock")
13
+
14
+
15
+ def main():
16
+ print(f"Loading pipeline")
17
+ pipeline = load_pipeline()
18
+
19
+ print(f"Pipeline loaded, creating socket at '{SOCKET}'")
20
+
21
+ if exists(SOCKET):
22
+ remove(SOCKET)
23
+
24
+ with Listener(SOCKET) as listener:
25
+ chmod(SOCKET, 0o777)
26
+
27
+ print(f"Awaiting connections")
28
+ with listener.accept() as connection:
29
+ print(f"Connected")
30
+
31
+ while True:
32
+ try:
33
+ request = TextToImageRequest.model_validate_json(connection.recv_bytes().decode("utf-8"))
34
+ except EOFError:
35
+ print(f"Inference socket exiting")
36
+
37
+ return
38
+
39
+ image = infer(request, pipeline)
40
+
41
+ data = BytesIO()
42
+ image.save(data, format=JpegImageFile.format)
43
+
44
+ packet = data.getvalue()
45
+
46
+ connection.send_bytes(packet)
47
+
48
+
49
+ if __name__ == '__main__':
50
+ main()
src/pipeline.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from diffusers import FluxPipeline, AutoencoderKL, FluxTransformer2DModel
3
+ from diffusers.image_processor import VaeImageProcessor
4
+ from transformers import T5EncoderModel, T5TokenizerFast, CLIPTokenizer, CLIPTextModel, CLIPTextConfig, T5Config
5
+ import torch
6
+ import gc
7
+ from PIL.Image import Image
8
+ from pipelines.models import TextToImageRequest
9
+ from torch import Generator
10
+ from torchao.quantization import quantize_, int8_weight_only
11
+ from time import perf_counter
12
+
13
+
14
+ HOME = os.environ["HOME"]
15
+ QUANTIZED_MODEL = ["text_encoder_2"]
16
+ os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:False,garbage_collection_threshold:0.01"
17
+ FLUX_CHECKPOINT = "jokerbit/flux.1-schnell-Robert-int8wo"
18
+ FLUX_CACHE = os.path.join(HOME, ".cache/huggingface/hub/models--jokerbit--flux.1-schnell-Robert-int8wo/snapshots/5ef0012f11a863e5111ec56540302a023bc8587b")
19
+ torch.backends.cudnn.benchmark = True
20
+ torch.backends.cuda.matmul.allow_tf32 = True
21
+ torch.cuda.set_per_process_memory_fraction(0.99)
22
+
23
+ QUANT_CONFIG = int8_weight_only()
24
+ DTYPE = torch.bfloat16
25
+ NUM_STEPS = 4
26
+ PROMPT = 'martyr, semiconformity, peregrination, quip, twineless, emotionless, tawa, depickle'
27
+
28
+
29
+ def empty_cache():
30
+ gc.collect()
31
+ torch.cuda.empty_cache()
32
+ torch.cuda.reset_max_memory_allocated()
33
+ torch.cuda.reset_peak_memory_stats()
34
+
35
+
36
+ def quantize(pipe, config):
37
+ if "text_encoder" in QUANTIZED_MODEL:
38
+ quantize_(pipe.text_encoder, config)
39
+ if "text_encoder_2" in QUANTIZED_MODEL:
40
+ quantize_(pipe.text_encoder_2, config)
41
+ if "transformer" in QUANTIZED_MODEL:
42
+ quantize_(pipe.transformer, config, device="cuda")
43
+ if "vae" in QUANTIZED_MODEL:
44
+ quantize_(pipe.vae, config)
45
+ return pipe
46
+
47
+
48
+ def load_pipeline() -> FluxPipeline:
49
+ empty_cache()
50
+ transformer = FluxTransformer2DModel.from_pretrained(os.path.join(FLUX_CACHE, "transformer"), use_safetensors=False, torch_dtype=DTYPE)
51
+ pipe = FluxPipeline.from_pretrained(FLUX_CHECKPOINT,
52
+ transformer=transformer,
53
+ torch_dtype=DTYPE)
54
+ pipe.vae.enable_tiling()
55
+ pipe.vae.enable_slicing()
56
+ quantize(pipe, QUANT_CONFIG)
57
+ pipe.to("cuda")
58
+ request = TextToImageRequest(prompt=PROMPT, height=1024, width=1024, seed=666)
59
+ infer(request, pipe)
60
+ # pipe.enable_model_cpu_offload()
61
+ return pipe
62
+
63
+
64
+ def encode_prompt(_pipeline, prompt: str):
65
+ pipeline = FluxPipeline.from_pipe(
66
+ _pipeline,
67
+ transformer=None,
68
+ vae=None,
69
+ ).to("cuda")
70
+ with torch.no_grad():
71
+ outputs = pipeline.encode_prompt(
72
+ prompt=prompt,
73
+ prompt_2=None,
74
+ max_sequence_length=256)
75
+ del pipeline
76
+ empty_cache()
77
+ return outputs
78
+
79
+
80
+ def infer_latents(_pipeline, prompt_embeds, pooled_prompt_embeds, width: int | None, height: int | None, seed: int | None):
81
+ pipeline = FluxPipeline.from_pipe(
82
+ _pipeline,
83
+ text_encoder=None,
84
+ text_encoder_2=None,
85
+ tokenizer=None,
86
+ tokenizer_2=None,
87
+ vae=None,
88
+ ).to("cuda")
89
+
90
+ if seed is None:
91
+ generator = None
92
+ else:
93
+ generator = Generator(pipeline.device).manual_seed(seed)
94
+ outputs = pipeline(
95
+ prompt_embeds=prompt_embeds,
96
+ pooled_prompt_embeds=pooled_prompt_embeds,
97
+ num_inference_steps=4,
98
+ guidance_scale=0.0,
99
+ width=width,
100
+ height=height,
101
+ generator=generator,
102
+ output_type="latent",
103
+ ).images
104
+ del pipeline
105
+ empty_cache()
106
+ return outputs
107
+
108
+
109
+ def decode_latents(vae, latents, width, height):
110
+ vae.to("cuda")
111
+ vae_scale_factor = 2 ** (len(vae.config.block_out_channels))
112
+ width = width or 64 * vae_scale_factor
113
+ height = height or 64 * vae_scale_factor
114
+ image_processor = VaeImageProcessor(vae_scale_factor=vae_scale_factor)
115
+ with torch.no_grad():
116
+ latents = FluxPipeline._unpack_latents(latents, height, width, vae_scale_factor)
117
+ latents = (latents / vae.config.scaling_factor) + vae.config.shift_factor
118
+ image = vae.decode(latents, return_dict=False)[0]
119
+ return image_processor.postprocess(image, output_type="pil")[0]
120
+
121
+
122
+ # def infer(request: TextToImageRequest, _pipeline: FluxPipeline) -> Image:
123
+ # prompt_embeds, pooled_prompt_embeds, text_ids = encode_prompt(_pipeline, request.prompt)
124
+ # latents = infer_latents(_pipeline, prompt_embeds, pooled_prompt_embeds, request.width, request.height, request.seed)
125
+ # del prompt_embeds
126
+ # del pooled_prompt_embeds
127
+ # del text_ids
128
+ # # _pipeline.transformer.to("cpu")
129
+ # image = decode_latents(_pipeline.vae, latents, request.width, request.height)
130
+ # torch.cuda.reset_peak_memory_stats()
131
+ # return image
132
+
133
+
134
+ def infer(request: TextToImageRequest, _pipeline: FluxPipeline) -> Image:
135
+ if request.seed is None:
136
+ generator = None
137
+ else:
138
+ generator = Generator(device="cuda").manual_seed(request.seed)
139
+ torch.cuda.reset_peak_memory_stats()
140
+ image = _pipeline(prompt=request.prompt,
141
+ width=request.width,
142
+ height=request.height,
143
+ guidance_scale=0.0,
144
+ generator=generator,
145
+ output_type="pil",
146
+ max_sequence_length=256,
147
+ num_inference_steps=NUM_STEPS).images[0]
148
+ return image
149
+
150
+ if __name__ == "__main__":
151
+ request = TextToImageRequest(prompt=PROMPT,
152
+ height=None,
153
+ width=None,
154
+ seed=666)
155
+ start_time = perf_counter()
156
+ pipe_ = load_pipeline()
157
+ stop_time = perf_counter()
158
+ print(f"Pipeline is loaded in {stop_time - start_time}s")
159
+ for _ in range(4):
160
+ start_time = perf_counter()
161
+ infer(request, pipe_)
162
+ stop_time = perf_counter()
163
+ print(f"Request in {stop_time - start_time}s")
164
+
165
+ # pipe("cat holding a womboai sign", num_inference_steps=4, guidance_scale=0, generator=torch.Generator(pipe.device).manual_seed(666)).images[0].save("sample.png")
uv.lock ADDED
The diff for this file is too large to render. See raw diff