| import os |
| from typing import Any, Dict |
|
|
| from diffusers import FluxPipeline, FluxTransformer2DModel, AutoencoderKL, TorchAoConfig |
| from PIL.Image import Image |
| import torch |
|
|
| import torch._dynamo |
| torch._dynamo.config.suppress_errors = True |
|
|
| |
|
|
| def compile_pipeline(pipe): |
| pipe.transformer.to(memory_format=torch.channels_last) |
| pipe.transformer = torch.compile(pipe.transformer, mode="reduce-overhead", fullgraph=False, dynamic=False, backend="inductor") |
| return pipe |
|
|
| class EndpointHandler: |
| def __init__(self, **kwargs: Any) -> None: |
| is_compile = False |
| |
| repo_id = "NoMoreCopyright/FLUX.1-dev-test" |
| dtype = torch.bfloat16 |
| quantization_config = TorchAoConfig("int4dq") |
| vae = AutoencoderKL.from_pretrained(repo_id, subfolder="vae", torch_dtype=dtype) |
| |
| self.pipeline = FluxPipeline.from_pretrained(repo_id, vae=vae, torch_dtype=dtype, quantization_config=quantization_config) |
| if is_compile: self.pipeline = compile_pipeline(self.pipeline) |
| self.pipeline.to("cuda") |
|
|
| @torch.inference_mode() |
| def __call__(self, data: Dict[str, Any]) -> Image: |
| |
|
|
| if "inputs" in data and isinstance(data["inputs"], str): |
| prompt = data.pop("inputs") |
| elif "prompt" in data and isinstance(data["prompt"], str): |
| prompt = data.pop("prompt") |
| else: |
| raise ValueError( |
| "Provided input body must contain either the key `inputs` or `prompt` with the" |
| " prompt to use for the image generation, and it needs to be a non-empty string." |
| ) |
|
|
| parameters = data.pop("parameters", {}) |
|
|
| num_inference_steps = parameters.get("num_inference_steps", 30) |
| width = parameters.get("width", 1024) |
| height = parameters.get("height", 768) |
| guidance_scale = parameters.get("guidance_scale", 3.5) |
|
|
| |
| seed = parameters.get("seed", 0) |
| generator = torch.manual_seed(seed) |
|
|
| return self.pipeline( |
| prompt, |
| height=height, |
| width=width, |
| guidance_scale=guidance_scale, |
| num_inference_steps=num_inference_steps, |
| generator=generator, |
| ).images[0] |