| from diffusers import FluxPipeline, AutoencoderKL, FluxTransformer2DModel |
| from diffusers.image_processor import VaeImageProcessor |
| from diffusers.schedulers import FlowMatchEulerDiscreteScheduler |
| import torch.nn.functional as F |
| from transformers import T5EncoderModel, T5TokenizerFast, CLIPTokenizer, CLIPTextModel |
| import torch |
| import torch._dynamo |
| import gc |
| from PIL import Image as img |
| from PIL.Image import Image |
| from pipelines.models import TextToImageRequest |
| from torch import Generator |
| import time |
| from diffusers import FluxTransformer2DModel, DiffusionPipeline |
| import torch.nn as nn |
| |
| import os |
| os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:False,garbage_collection_threshold:0.01" |
| os.environ["HUGGINGFACE_HUB_TOKEN"] = "" |
| Pipeline = None |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
|
|
| class W8A16LinearLayer(nn.Module): |
| def __init__(self, in_features, out_features, bias=True, dtype=torch.float32): |
| super().__init__() |
| self.weight = nn.Parameter(torch.randn(out_features, in_features, dtype=dtype)) |
| self.weight.requires_grad = False |
| if bias: |
| self.bias = nn.Parameter(torch.randn(1, out_features, dtype=dtype)) |
| self.scales = nn.Parameter(torch.randn(out_features, dtype=dtype)) |
|
|
| def quantize(self, weights): |
| w_fp32 = weights.clone().to(torch.float32) |
| scales = w_fp32.abs().max(dim=-1).values / 127 |
| scales = scales.to(weights.dtype) |
| self.weight.data = torch.round(weights/scales.unsqueeze(1)).to(torch.int8) |
| self.scales.data = scales |
|
|
| def forward(self, input): |
| casted_weights = self.weight.to(input.dtype) |
| output = F.linear(input, casted_weights) * self.scales |
| if self.bias is not None: |
| output = output + self.bias |
| return output |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
|
|
| def replace_linear_with_target_and_quantize(module, target_class, module_name_to_exclude): |
| |
| |
| for name in list(module._modules.keys()): |
| child = module._modules[name] |
| if isinstance(child, nn.Linear) and ( 'add_k_proj' in name or 'add_v_proj' in name or 'add_q_proj' in name ): |
| old_bias = child.bias |
| old_weight = child.weight |
| new_module = target_class(child.in_features, child.out_features, old_bias is not None, child.weight.dtype) |
| new_module.quantize(old_weight) |
| delattr(module, name) |
| setattr(module, name, new_module) |
| if old_bias is not None: |
| getattr(module, name).bias = old_bias |
|
|
| |
| |
| |
| |
| else: |
| |
| replace_linear_with_target_and_quantize(child, target_class, module_name_to_exclude) |
|
|
|
|
| ckpt_id = "black-forest-labs/FLUX.1-schnell" |
| def empty_cache(): |
| start = time.time() |
| gc.collect() |
| torch.cuda.empty_cache() |
| torch.cuda.reset_max_memory_allocated() |
| torch.cuda.reset_peak_memory_stats() |
|
|
| def load_pipeline() -> Pipeline: |
| empty_cache() |
| dtype, device = torch.bfloat16, "cuda" |
|
|
| text_encoder_2 = T5EncoderModel.from_pretrained( |
| "city96/t5-v1_1-xxl-encoder-bf16", torch_dtype=torch.bfloat16 |
| ) |
| vae=AutoencoderKL.from_pretrained(ckpt_id, subfolder="vae", torch_dtype=dtype) |
| |
| |
| pipeline = DiffusionPipeline.from_pretrained( |
| ckpt_id, |
| vae=vae, |
| text_encoder_2 = text_encoder_2, |
| |
| torch_dtype=dtype, |
| ) |
| |
| |
| torch.backends.cudnn.benchmark = True |
| torch.backends.cudnn.deterministic = False |
| |
| torch.backends.cuda.matmul.allow_tf32 = True |
| |
| torch.cuda.set_memory_growth(True) |
| torch.cuda.set_per_process_memory_fraction(0.99) |
| pipeline.text_encoder.to(memory_format=torch.channels_last) |
| pipeline.transformer.to(memory_format=torch.channels_last) |
| |
| |
| |
| |
|
|
| pipeline.vae.to(memory_format=torch.channels_last) |
| pipeline.vae = torch.compile(pipeline.vae) |
| |
| |
| |
| |
| |
| pipeline._exclude_from_cpu_offload = ["vae"] |
| pipeline.enable_sequential_cpu_offload() |
| for _ in range(2): |
| pipeline(prompt="onomancy, aftergo, spirantic, Platyhelmia, modificator, drupaceous, jobbernowl, hereness", width=1024, height=1024, guidance_scale=0.0, num_inference_steps=4, max_sequence_length=256) |
| |
| return pipeline |
|
|
|
|
| @torch.inference_mode() |
| def infer(request: TextToImageRequest, pipeline: Pipeline) -> Image: |
| torch.cuda.reset_peak_memory_stats() |
| generator = Generator("cuda").manual_seed(request.seed) |
| image=pipeline(request.prompt,generator=generator, guidance_scale=0.0, num_inference_steps=4, max_sequence_length=256, height=request.height, width=request.width, output_type="pil").images[0] |
| return(image) |
|
|