Upload folder using huggingface_hub
Browse filesFiles changed (7)
- .gitattributes+1
- .gitignoreAdded+9
- README.mdAdded+19
- pyproject.tomlAdded+28
- src/main.pyAdded+59
- src/pipeline.pyAdded+133
- uv.lockAdded
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textsample.png filter=lfs diff=lfs merge=lfs -text
123456789**/.cache**/__pycache__**/*.egg-info*.safetensors**/.venv.venv.git*.png*.jpeg12345678910111213141516171819# flux-schnell-edge-inference
This holds the baseline for the FLUX Schnel NVIDIA GeForce RTX 4090 contest, which can be forked freely and optimized
Some recommendations are as follows:- Installing dependencies should be done in `pyproject.toml`, including git dependencies- HuggingFace models should be specified in the `models` array in the `pyproject.toml` file, and will be downloaded before benchmarking - The pipeline does **not** have internet access so all dependencies and models must be included in the `pyproject.toml` - 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- Avoid changing `src/main.py`, as that includes mostly protocol logic. Most changes should be in `models` and `src/pipeline.py`- Ensure the entire repository (excluding dependencies and HuggingFace models) is under 16MB
For testing, you need a docker container with pytorch and ubuntu 22.04.You can download your listed dependencies with `uv`, installed with:```bashpipx ensurepathpipx install uv```You can then relock with `uv lock`, and then run with `uv run start_inference`12345678910111213141516171819202122232425262728[build-system]requires = ["setuptools >= 75.0"]build-backend = "setuptools.build_meta"
[project]name = "flux-schnell-edge-inference"description = "An edge-maxxing model submission for the 4090 Flux contest"requires-python = ">=3.10,<3.13"version = "7"dependencies = [ "diffusers==0.31.0", "transformers==4.46.2", "accelerate==1.1.0", "omegaconf==2.3.0", "torch==2.5.1", "protobuf==5.28.3", "sentencepiece==0.2.0", "edge-maxxing-pipelines @ git+https://github.com/womboai/edge-maxxing@7c760ac54f6052803dadb3ade8ebfc9679a94589#subdirectory=pipelines", "torchao>=0.6.1", "ipython>=8.29.0", "setuptools >= 75.0"]
[tool.edge-maxxing]models = ["black-forest-labs/FLUX.1-schnell"]
[project.scripts]start_inference = "main:main"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859import atexitfrom io import BytesIOfrom multiprocessing.connection import Listenerfrom os import chmod, removefrom os.path import abspath, existsfrom pathlib import Path
import torch
from PIL.JpegImagePlugin import JpegImageFilefrom pipelines.models import TextToImageRequest
from pipeline import load_pipeline, infer
SOCKET = abspath(Path(__file__).parent.parent / "inferences.sock")
def at_exit(): torch.cuda.empty_cache()
def main(): atexit.register(at_exit)
print(f"Loading pipeline") pipeline = load_pipeline()
print(f"Pipeline loaded, creating socket at '{SOCKET}'")
if exists(SOCKET): remove(SOCKET)
with Listener(SOCKET) as listener: chmod(SOCKET, 0o777)
print(f"Awaiting connections") with listener.accept() as connection: print(f"Connected")
while True: try: request = TextToImageRequest.model_validate_json(connection.recv_bytes().decode("utf-8")) except EOFError: print(f"Inference socket exiting")
return
image = infer(request, pipeline)
data = BytesIO() image.save(data, format=JpegImageFile.format)
packet = data.getvalue()
connection.send_bytes(packet)
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133import osfrom diffusers import FluxPipeline, AutoencoderKL, FluxTransformer2DModelfrom diffusers.image_processor import VaeImageProcessorfrom transformers import T5EncoderModel, T5TokenizerFast, CLIPTokenizer, CLIPTextModel, CLIPTextConfig, T5Configimport torchimport gcfrom PIL.Image import Imagefrom pipelines.models import TextToImageRequestfrom torch import Generatorfrom torchao.quantization import quantize_, int8_weight_only, int8_dynamic_activation_int8_weightfrom time import perf_counter
HOME = os.environ["HOME"]os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"FLUX_CHECKPOINT = "black-forest-labs/FLUX.1-schnell"# QUANTIZED_MODEL = []QUANTIZED_MODEL = ["transformer", "text_encoder_2", "text_encoder", "vae"]
QUANT_CONFIG = int8_weight_only()DTYPE = torch.bfloat16NUM_STEPS = 4
def get_transformer(quantize: bool = True, quant_config = int8_weight_only(), quant_ckpt: str = None): if quant_ckpt is not None: config = FluxTransformer2DModel.load_config(FLUX_CHECKPOINT, subfolder="transformer") model = FluxTransformer2DModel.from_config(config).to(DTYPE) state_dict = torch.load(quant_ckpt, map_location="cpu") model.load_state_dict(state_dict, assign=True) print(f"Loaded {quant_ckpt}") return model model = FluxTransformer2DModel.from_pretrained( FLUX_CHECKPOINT, subfolder="transformer", torch_dtype=DTYPE ) if quantize: quantize_(model, quant_config) return model
def get_text_encoder(quantize: bool = True, quant_config = int8_weight_only(), quant_ckpt: str = None): if quant_ckpt is not None: config = CLIPTextConfig.from_pretrained(FLUX_CHECKPOINT, subfolder="text_encoder") model = CLIPTextModel(config).to(DTYPE) state_dict = torch.load(quant_ckpt, map_location="cpu") model.load_state_dict(state_dict, assign=True) print(f"Loaded {quant_ckpt}") return model model = CLIPTextModel.from_pretrained( FLUX_CHECKPOINT, subfolder="text_encoder", torch_dtype=DTYPE ) if quantize: quantize_(model, quant_config) return model
def get_text_encoder_2(quantize: bool = True, quant_config = int8_weight_only(), quant_ckpt: str = None): if quant_ckpt is not None: config = T5Config.from_pretrained(FLUX_CHECKPOINT, subfolder="text_encoder_2") model = T5EncoderModel(config).to(DTYPE) state_dict = torch.load(quant_ckpt, map_location="cpu") print(f"Loaded {quant_ckpt}") model.load_state_dict(state_dict, assign=True) return model model = T5EncoderModel.from_pretrained( FLUX_CHECKPOINT, subfolder="text_encoder_2", torch_dtype=DTYPE ) if quantize: quantize_(model, quant_config) return model
def get_vae(quantize: bool = True, quant_config = int8_weight_only(), quant_ckpt: str = None): if quant_ckpt is not None: config = AutoencoderKL.load_config(FLUX_CHECKPOINT, subfolder="vae") model = AutoencoderKL.from_config(config).to(DTYPE) state_dict = torch.load(quant_ckpt, map_location="cpu") model.load_state_dict(state_dict, assign=True) print(f"Loaded {quant_ckpt}") return model model = AutoencoderKL.from_pretrained( FLUX_CHECKPOINT, subfolder="vae", torch_dtype=DTYPE ) if quantize: quantize_(model, quant_config) return model
def empty_cache(): gc.collect() torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats()
def load_pipeline() -> FluxPipeline: empty_cache() pipe = FluxPipeline.from_pretrained(FLUX_CHECKPOINT, torch_dtype=DTYPE) pipe.transformer.to(memory_format=torch.channels_last) pipe.vae.to(memory_format=torch.channels_last) pipe.vae = torch.compile(pipe.vae) pipe._exclude_from_cpu_offload = ["vae"] pipe.enable_sequential_cpu_offload() empty_cache() pipe("cat", guidance_scale=0., max_sequence_length=256, num_inference_steps=4) return pipe
@torch.inference_mode()def infer(request: TextToImageRequest, _pipeline: FluxPipeline) -> Image: if request.seed is None: generator = None else: generator = Generator(device="cuda").manual_seed(request.seed)
empty_cache() image = _pipeline(prompt=request.prompt, width=request.width, height=request.height, guidance_scale=0.0, generator=generator, output_type="pil", max_sequence_length=256, num_inference_steps=NUM_STEPS).images[0] return image.gitattributes+1
.gitignoreAdded+9
README.mdAdded+19
pyproject.tomlAdded+28
src/main.pyAdded+59
src/pipeline.pyAdded+133
uv.lockAdded