manbeast3b commited on
Commit
5f3f08c
·
0 Parent(s):

Initial commit

Browse files
Files changed (6) hide show
  1. .gitattributes +37 -0
  2. pyproject.toml +54 -0
  3. src/ghanta.py +74 -0
  4. src/main.py +55 -0
  5. src/pipeline.py +639 -0
  6. uv.lock +0 -0
.gitattributes ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz 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
+ RobertML.png filter=lfs diff=lfs merge=lfs -text
37
+ backup.png filter=lfs diff=lfs merge=lfs -text
pyproject.toml ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 by RobertML 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
+ "edge-maxxing-pipelines @ git+https://github.com/womboai/edge-maxxing@7c760ac54f6052803dadb3ade8ebfc9679a94589#subdirectory=pipelines",
19
+ "gitpython>=3.1.43",
20
+ "hf_transfer==0.1.8",
21
+ "torchao==0.6.1",
22
+ "setuptools>=75.3.0",
23
+ ]
24
+
25
+ [[tool.edge-maxxing.models]]
26
+ repository = "black-forest-labs/FLUX.1-schnell"
27
+ revision = "741f7c3ce8b383c54771c7003378a50191e9efe9"
28
+ exclude = ["transformer"]
29
+
30
+ [[tool.edge-maxxing.models]]
31
+ repository = "RobertML/FLUX.1-schnell-int8wo"
32
+ revision = "307e0777d92df966a3c0f99f31a6ee8957a9857a"
33
+
34
+ [[tool.edge-maxxing.models]]
35
+ repository = "city96/t5-v1_1-xxl-encoder-bf16"
36
+ revision = "1b9c856aadb864af93c1dcdc226c2774fa67bc86"
37
+
38
+ [[tool.edge-maxxing.models]]
39
+ repository = "RobertML/FLUX.1-schnell-vae_e3m2"
40
+ revision = "da0d2cd7815792fb40d084dbd8ed32b63f153d8d"
41
+
42
+ [[tool.edge-maxxing.models]]
43
+ repository = "madebyollin/taef1"
44
+ revision = "2d552378e58c9c94201075708d7de4e1163b2689"
45
+
46
+ [[tool.edge-maxxing.models]]
47
+ repository = "manbeast3b/flux.1-schnell-full1"
48
+ revision = "cb1b599b0d712b9aab2c4df3ad27b050a27ec146"
49
+
50
+
51
+
52
+ [project.scripts]
53
+ start_inference = "main:main"
54
+
src/ghanta.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from typing import Tuple, Callable
3
+ def hacer_nada(x: torch.Tensor, modo: str = None):
4
+ return x
5
+ def brujeria_mps(entrada, dim, indice):
6
+ if entrada.shape[-1] == 1:
7
+ return torch.gather(entrada.unsqueeze(-1), dim - 1 if dim < 0 else dim, indice.unsqueeze(-1)).squeeze(-1)
8
+ else:
9
+ return torch.gather(entrada, dim, indice)
10
+ def emparejamiento_suave_aleatorio_2d(
11
+ metrica: torch.Tensor,
12
+ ancho: int,
13
+ alto: int,
14
+ paso_x: int,
15
+ paso_y: int,
16
+ radio: int,
17
+ sin_aleatoriedad: bool = False,
18
+ generador: torch.Generator = None
19
+ ) -> Tuple[Callable, Callable]:
20
+ lote, num_nodos, _ = metrica.shape
21
+ if radio <= 0:
22
+ return hacer_nada, hacer_nada
23
+ recopilar = brujeria_mps if metrica.device.type == "mps" else torch.gather
24
+ with torch.no_grad():
25
+ alto_paso_y, ancho_paso_x = alto // paso_y, ancho // paso_x
26
+ if sin_aleatoriedad:
27
+ indice_aleatorio = torch.zeros(alto_paso_y, ancho_paso_x, 1, device=metrica.device, dtype=torch.int64)
28
+ else:
29
+ indice_aleatorio = torch.randint(paso_y * paso_x, size=(alto_paso_y, ancho_paso_x, 1), device=generador.device, generator=generador).to(metrica.device)
30
+ vista_buffer_indice = torch.zeros(alto_paso_y, ancho_paso_x, paso_y * paso_x, device=metrica.device, dtype=torch.int64)
31
+ vista_buffer_indice.scatter_(dim=2, index=indice_aleatorio, src=-torch.ones_like(indice_aleatorio, dtype=indice_aleatorio.dtype))
32
+ vista_buffer_indice = vista_buffer_indice.view(alto_paso_y, ancho_paso_x, paso_y, paso_x).transpose(1, 2).reshape(alto_paso_y * paso_y, ancho_paso_x * paso_x)
33
+ if (alto_paso_y * paso_y) < alto or (ancho_paso_x * paso_x) < ancho:
34
+ buffer_indice = torch.zeros(alto, ancho, device=metrica.device, dtype=torch.int64)
35
+ buffer_indice[:(alto_paso_y * paso_y), :(ancho_paso_x * paso_x)] = vista_buffer_indice
36
+ else:
37
+ buffer_indice = vista_buffer_indice
38
+ indice_aleatorio = buffer_indice.reshape(1, -1, 1).argsort(dim=1)
39
+ del buffer_indice, vista_buffer_indice
40
+ num_destino = alto_paso_y * ancho_paso_x
41
+ indices_a = indice_aleatorio[:, num_destino:, :]
42
+ indices_b = indice_aleatorio[:, :num_destino, :]
43
+ def dividir(x):
44
+ canales = x.shape[-1]
45
+ origen = recopilar(x, dim=1, index=indices_a.expand(lote, num_nodos - num_destino, canales))
46
+ destino = recopilar(x, dim=1, index=indices_b.expand(lote, num_destino, canales))
47
+ return origen, destino
48
+ metrica = metrica / metrica.norm(dim=-1, keepdim=True)
49
+ a, b = dividir(metrica)
50
+ puntuaciones = a @ b.transpose(-1, -2)
51
+ radio = min(a.shape[1], radio)
52
+ nodo_max, nodo_indice = puntuaciones.max(dim=-1)
53
+ indice_borde = nodo_max.argsort(dim=-1, descending=True)[..., None]
54
+ indice_no_emparejado = indice_borde[..., radio:, :]
55
+ indice_origen = indice_borde[..., :radio, :]
56
+ indice_destino = recopilar(nodo_indice[..., None], dim=-2, index=indice_origen)
57
+ def fusionar(x: torch.Tensor, modo="mean") -> torch.Tensor:
58
+ origen, destino = dividir(x)
59
+ n, t1, c = origen.shape
60
+ no_emparejado = recopilar(origen, dim=-2, index=indice_no_emparejado.expand(n, t1 - radio, c))
61
+ origen = recopilar(origen, dim=-2, index=indice_origen.expand(n, radio, c))
62
+ destino = destino.scatter_reduce(-2, indice_destino.expand(n, radio, c), origen, reduce=modo)
63
+ return torch.cat([no_emparejado, destino], dim=1)
64
+ def desfusionar(x: torch.Tensor) -> torch.Tensor:
65
+ longitud_no_emparejado = indice_no_emparejado.shape[1]
66
+ no_emparejado, destino = x[..., :longitud_no_emparejado, :], x[..., longitud_no_emparejado:, :]
67
+ _, _, c = no_emparejado.shape
68
+ origen = recopilar(destino, dim=-2, index=indice_destino.expand(lote, radio, c))
69
+ salida = torch.zeros(lote, num_nodos, c, device=x.device, dtype=x.dtype)
70
+ salida.scatter_(dim=-2, index=indices_b.expand(lote, num_destino, c), src=destino)
71
+ salida.scatter_(dim=-2, index=recopilar(indices_a.expand(lote, indices_a.shape[1], 1), dim=1, index=indice_no_emparejado).expand(lote, longitud_no_emparejado, c), src=no_emparejado)
72
+ salida.scatter_(dim=-2, index=recopilar(indices_a.expand(lote, indices_a.shape[1], 1), dim=1, index=indice_origen).expand(lote, radio, c), src=origen)
73
+ return salida
74
+ return fusionar, desfusionar
src/main.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import atexit
2
+ from io import BytesIO
3
+ from multiprocessing.connection import Listener
4
+ from os import chmod, remove
5
+ from os.path import abspath, exists
6
+ from pathlib import Path
7
+ from git import Repo
8
+ import torch
9
+
10
+ from PIL.JpegImagePlugin import JpegImageFile
11
+ from pipelines.models import TextToImageRequest
12
+ from pipeline import load_pipeline, infer
13
+ SOCKET = abspath(Path(__file__).parent.parent / "inferences.sock")
14
+
15
+
16
+ def at_exit():
17
+ torch.cuda.empty_cache()
18
+
19
+
20
+ def main():
21
+ atexit.register(at_exit)
22
+
23
+ print(f"Loading pipeline")
24
+ pipeline = load_pipeline()
25
+
26
+ print(f"Pipeline loaded, creating socket at '{SOCKET}'")
27
+
28
+ if exists(SOCKET):
29
+ remove(SOCKET)
30
+
31
+ with Listener(SOCKET) as listener:
32
+ chmod(SOCKET, 0o777)
33
+
34
+ print(f"Awaiting connections")
35
+ with listener.accept() as connection:
36
+ print(f"Connected")
37
+ generator = torch.Generator("cuda")
38
+ while True:
39
+ try:
40
+ request = TextToImageRequest.model_validate_json(connection.recv_bytes().decode("utf-8"))
41
+ except EOFError:
42
+ print(f"Inference socket exiting")
43
+
44
+ return
45
+ image = infer(request, pipeline, generator.manual_seed(request.seed))
46
+ data = BytesIO()
47
+ image.save(data, format=JpegImageFile.format)
48
+
49
+ packet = data.getvalue()
50
+
51
+ connection.send_bytes(packet )
52
+
53
+
54
+ if __name__ == '__main__':
55
+ main()
src/pipeline.py ADDED
@@ -0,0 +1,639 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from diffusers import FluxPipeline, AutoencoderKL, AutoencoderTiny
2
+ from diffusers.image_processor import VaeImageProcessor
3
+ from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
4
+ from huggingface_hub.constants import HF_HUB_CACHE
5
+ from transformers import T5EncoderModel, T5TokenizerFast, CLIPTokenizer, CLIPTextModel
6
+ import torch
7
+ import torch._dynamo
8
+ import gc
9
+ from PIL import Image as img
10
+ from PIL.Image import Image
11
+ from pipelines.models import TextToImageRequest
12
+ from torch import Generator
13
+ import time
14
+ from diffusers import DiffusionPipeline
15
+ from torchao.quantization import quantize_, int8_weight_only, fpx_weight_only
16
+
17
+ import torch
18
+ import math
19
+ from typing import Type, Dict, Any, Tuple, Callable, Optional, Union
20
+ import ghanta
21
+ import numpy as np
22
+ import torch
23
+ import torch.nn as nn
24
+ import torch.nn.functional as F
25
+
26
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
27
+ from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
28
+ from diffusers.models.attention import FeedForward
29
+ from diffusers.models.attention_processor import (
30
+ Attention,
31
+ AttentionProcessor,
32
+ FluxAttnProcessor2_0,
33
+ FusedFluxAttnProcessor2_0,
34
+ )
35
+ from diffusers.models.modeling_utils import ModelMixin
36
+ from diffusers.models.normalization import AdaLayerNormContinuous, AdaLayerNormZero, AdaLayerNormZeroSingle
37
+ from diffusers.utils import USE_PEFT_BACKEND, is_torch_version, logging, scale_lora_layers, unscale_lora_layers
38
+ from diffusers.utils.import_utils import is_torch_npu_available
39
+ from diffusers.utils.torch_utils import maybe_allow_in_graph
40
+ from diffusers.models.embeddings import CombinedTimestepGuidanceTextProjEmbeddings, CombinedTimestepTextProjEmbeddings, FluxPosEmbed
41
+ from diffusers.models.modeling_outputs import Transformer2DModelOutput
42
+
43
+ import os
44
+ os.environ['PYTORCH_CUDA_ALLOC_CONF']="expandable_segments:True"
45
+ os.environ["TOKENIZERS_PARALLELISM"] = "True"
46
+ torch._dynamo.config.suppress_errors = True
47
+
48
+ class BasicQuantization:
49
+ def __init__(self, bits=1):
50
+ self.bits = bits
51
+ self.qmin = -(2**(bits-1))
52
+ self.qmax = 2**(bits-1) - 1
53
+
54
+ def quantize_tensor(self, tensor):
55
+ scale = (tensor.max() - tensor.min()) / (self.qmax - self.qmin)
56
+ zero_point = self.qmin - torch.round(tensor.min() / scale)
57
+ qtensor = torch.round(tensor / scale + zero_point)
58
+ qtensor = torch.clamp(qtensor, self.qmin, self.qmax)
59
+ return (qtensor - zero_point) * scale, scale, zero_point
60
+
61
+ class ModelQuantization:
62
+ def __init__(self, model, bits=7):
63
+ self.model = model
64
+ self.quant = BasicQuantization(bits)
65
+
66
+ def quantize_model(self):
67
+ for name, module in self.model.named_modules():
68
+ if isinstance(module, torch.nn.Linear):
69
+ if hasattr(module, 'weightML'):
70
+ quantized_weight, _, _ = self.quant.quantize_tensor(module.weight)
71
+ module.weight = torch.nn.Parameter(quantized_weight)
72
+ if hasattr(module, 'bias') and module.bias is not None:
73
+ quantized_bias, _, _ = self.quant.quantize_tensor(module.bias)
74
+ module.bias = torch.nn.Parameter(quantized_bias)
75
+
76
+
77
+ def inicializar_generador(dispositivo: torch.device, respaldo: torch.Generator = None):
78
+ if dispositivo.type == "cpu":
79
+ return torch.Generator(device="cpu").set_state(torch.get_rng_state())
80
+ elif dispositivo.type == "cuda":
81
+ return torch.Generator(device=dispositivo).set_state(torch.cuda.get_rng_state())
82
+ else:
83
+ if respaldo is None:
84
+ return inicializar_generador(torch.device("cpu"))
85
+ else:
86
+ return respaldo
87
+
88
+ def calcular_fusion(x: torch.Tensor, info_tome: Dict[str, Any]) -> Tuple[Callable, ...]:
89
+ alto_original, ancho_original = info_tome["size"]
90
+ tokens_originales = alto_original * ancho_original
91
+ submuestreo = int(math.ceil(math.sqrt(tokens_originales // x.shape[1])))
92
+ argumentos = info_tome["args"]
93
+ if submuestreo <= argumentos["down"]:
94
+ ancho = int(math.ceil(ancho_original / submuestreo))
95
+ alto = int(math.ceil(alto_original / submuestreo))
96
+ radio = int(x.shape[1] * argumentos["ratio"])
97
+
98
+ if argumentos["generator"] is None:
99
+ argumentos["generator"] = inicializar_generador(x.device)
100
+ elif argumentos["generator"].device != x.device:
101
+ argumentos["generator"] = inicializar_generador(x.device, respaldo=argumentos["generator"])
102
+
103
+ usar_aleatoriedad = argumentos["rando"]
104
+ fusion, desfusion = ghanta.emparejamiento_suave_aleatorio_2d(
105
+ x, ancho, alto, argumentos["sx"], argumentos["sy"], radio,
106
+ sin_aleatoriedad=not usar_aleatoriedad, generador=argumentos["generator"]
107
+ )
108
+ else:
109
+ fusion, desfusion = (hacer_nada, hacer_nada)
110
+ fusion_a, desfusion_a = (fusion, desfusion) if argumentos["m1"] else (hacer_nada, hacer_nada)
111
+ fusion_c, desfusion_c = (fusion, desfusion) if argumentos["m2"] else (hacer_nada, hacer_nada)
112
+ fusion_m, desfusion_m = (fusion, desfusion) if argumentos["m3"] else (hacer_nada, hacer_nada)
113
+ return fusion_a, fusion_c, fusion_m, desfusion_a, desfusion_c, desfusion_m
114
+
115
+ @maybe_allow_in_graph
116
+ class FluxSingleTransformerBlock(nn.Module):
117
+
118
+ def __init__(self, dim, num_attention_heads, attention_head_dim, mlp_ratio=4.0):
119
+ super().__init__()
120
+ self.mlp_hidden_dim = int(dim * mlp_ratio)
121
+
122
+ self.norm = AdaLayerNormZeroSingle(dim)
123
+ self.proj_mlp = nn.Linear(dim, self.mlp_hidden_dim)
124
+ self.act_mlp = nn.GELU(approximate="tanh")
125
+ self.proj_out = nn.Linear(dim + self.mlp_hidden_dim, dim)
126
+
127
+ processor = FluxAttnProcessor2_0()
128
+ self.attn = Attention(
129
+ query_dim=dim,
130
+ cross_attention_dim=None,
131
+ dim_head=attention_head_dim,
132
+ heads=num_attention_heads,
133
+ out_dim=dim,
134
+ bias=True,
135
+ processor=processor,
136
+ qk_norm="rms_norm",
137
+ eps=1e-6,
138
+ pre_only=True,
139
+ )
140
+
141
+ def forward(
142
+ self,
143
+ hidden_states: torch.FloatTensor,
144
+ temb: torch.FloatTensor,
145
+ image_rotary_emb=None,
146
+ joint_attention_kwargs=None,
147
+ tinfo: Dict[str, Any] = None,
148
+ ):
149
+ if tinfo is not None:
150
+ m_a, m_c, mom, u_a, u_c, u_m = calcular_fusion(hidden_states, tinfo)
151
+ else:
152
+ m_a, m_c, mom, u_a, u_c, u_m = (ghanta.hacer_nada, ghanta.hacer_nada, ghanta.hacer_nada, ghanta.hacer_nada, ghanta.hacer_nada, ghanta.hacer_nada)
153
+
154
+ residual = hidden_states
155
+ norm_hidden_states, gate = self.norm(hidden_states, emb=temb)
156
+ norm_hidden_states = m_a(norm_hidden_states)
157
+ mlp_hidden_states = self.act_mlp(self.proj_mlp(norm_hidden_states))
158
+ joint_attention_kwargs = joint_attention_kwargs or {}
159
+ attn_output = self.attn(
160
+ hidden_states=norm_hidden_states,
161
+ image_rotary_emb=image_rotary_emb,
162
+ **joint_attention_kwargs,
163
+ )
164
+
165
+ hidden_states = torch.cat([attn_output, mlp_hidden_states], dim=2)
166
+ gate = gate.unsqueeze(1)
167
+ hidden_states = gate * self.proj_out(hidden_states)
168
+ hidden_states = u_a(residual + hidden_states)
169
+
170
+ return hidden_states
171
+
172
+
173
+ @maybe_allow_in_graph
174
+ class FluxTransformerBlock(nn.Module):
175
+
176
+ def __init__(self, dim, num_attention_heads, attention_head_dim, qk_norm="rms_norm", eps=1e-6):
177
+ super().__init__()
178
+
179
+ self.norm1 = AdaLayerNormZero(dim)
180
+
181
+ self.norm1_context = AdaLayerNormZero(dim)
182
+
183
+ if hasattr(F, "scaled_dot_product_attention"):
184
+ processor = FluxAttnProcessor2_0()
185
+ else:
186
+ raise ValueError(
187
+ "The current PyTorch version does not support the `scaled_dot_product_attention` function."
188
+ )
189
+ self.attn = Attention(
190
+ query_dim=dim,
191
+ cross_attention_dim=None,
192
+ added_kv_proj_dim=dim,
193
+ dim_head=attention_head_dim,
194
+ heads=num_attention_heads,
195
+ out_dim=dim,
196
+ context_pre_only=False,
197
+ bias=True,
198
+ processor=processor,
199
+ qk_norm=qk_norm,
200
+ eps=eps,
201
+ )
202
+
203
+ self.norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
204
+ self.ff = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
205
+
206
+ self.norm2_context = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
207
+ self.ff_context = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
208
+ self._chunk_size = None
209
+ self._chunk_dim = 0
210
+
211
+ def forward(
212
+ self,
213
+ hidden_states: torch.FloatTensor,
214
+ encoder_hidden_states: torch.FloatTensor,
215
+ temb: torch.FloatTensor,
216
+ image_rotary_emb=None,
217
+ joint_attention_kwargs=None,
218
+ tinfo: Dict[str, Any] = None, # Add tinfo parameter
219
+ ):
220
+ if tinfo is not None:
221
+ m_a, m_c, mom, u_a, u_c, u_m = calcular_fusion(hidden_states, tinfo)
222
+ else:
223
+ m_a, m_c, mom, u_a, u_c, u_m = (ghanta.hacer_nada, ghanta.hacer_nada, ghanta.hacer_nada, ghanta.hacer_nada, ghanta.hacer_nada, ghanta.hacer_nada)
224
+
225
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(hidden_states, emb=temb)
226
+
227
+ norm_encoder_hidden_states, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = self.norm1_context(
228
+ encoder_hidden_states, emb=temb
229
+ )
230
+ joint_attention_kwargs = joint_attention_kwargs or {}
231
+ norm_hidden_states = m_a(norm_hidden_states)
232
+ norm_encoder_hidden_states = m_c(norm_encoder_hidden_states)
233
+
234
+ attn_output, context_attn_output = self.attn(
235
+ hidden_states=norm_hidden_states,
236
+ encoder_hidden_states=norm_encoder_hidden_states,
237
+ image_rotary_emb=image_rotary_emb,
238
+ **joint_attention_kwargs,
239
+ )
240
+
241
+ attn_output = gate_msa.unsqueeze(1) * attn_output
242
+ hidden_states = u_a(attn_output) + hidden_states
243
+
244
+ norm_hidden_states = self.norm2(hidden_states)
245
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
246
+
247
+ norm_hidden_states = mom(norm_hidden_states)
248
+
249
+ ff_output = self.ff(norm_hidden_states)
250
+ ff_output = gate_mlp.unsqueeze(1) * ff_output
251
+
252
+ hidden_states = u_m(ff_output) + hidden_states
253
+ context_attn_output = c_gate_msa.unsqueeze(1) * context_attn_output
254
+ encoder_hidden_states = u_c(context_attn_output) + encoder_hidden_states
255
+
256
+ norm_encoder_hidden_states = self.norm2_context(encoder_hidden_states)
257
+ norm_encoder_hidden_states = norm_encoder_hidden_states * (1 + c_scale_mlp[:, None]) + c_shift_mlp[:, None]
258
+
259
+ context_ff_output = self.ff_context(norm_encoder_hidden_states)
260
+ encoder_hidden_states = encoder_hidden_states + c_gate_mlp.unsqueeze(1) * context_ff_output
261
+
262
+ return encoder_hidden_states, hidden_states
263
+
264
+
265
+ class FluxTransformer2DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):
266
+
267
+ _supports_gradient_checkpointing = True
268
+ _no_split_modules = ["FluxTransformerBlock", "FluxSingleTransformerBlock"]
269
+
270
+ @register_to_config
271
+ def __init__(
272
+ self,
273
+ patch_size: int = 1,
274
+ in_channels: int = 64,
275
+ out_channels: Optional[int] = None,
276
+ num_layers: int = 19,
277
+ num_single_layers: int = 38,
278
+ attention_head_dim: int = 128,
279
+ num_attention_heads: int = 24,
280
+ joint_attention_dim: int = 4096,
281
+ pooled_projection_dim: int = 768,
282
+ guidance_embeds: bool = False,
283
+ axes_dims_rope: Tuple[int] = (16, 56, 56),
284
+ generator: Optional[torch.Generator] = None,
285
+ ):
286
+ super().__init__()
287
+ self.out_channels = out_channels or in_channels
288
+ self.inner_dim = self.config.num_attention_heads * self.config.attention_head_dim
289
+
290
+ self.pos_embed = FluxPosEmbed(theta=10000, axes_dim=axes_dims_rope)
291
+
292
+ text_time_guidance_cls = (
293
+ CombinedTimestepGuidanceTextProjEmbeddings if guidance_embeds else CombinedTimestepTextProjEmbeddings
294
+ )
295
+ self.time_text_embed = text_time_guidance_cls(
296
+ embedding_dim=self.inner_dim, pooled_projection_dim=self.config.pooled_projection_dim
297
+ )
298
+
299
+ self.context_embedder = nn.Linear(self.config.joint_attention_dim, self.inner_dim)
300
+ self.x_embedder = nn.Linear(self.config.in_channels, self.inner_dim)
301
+
302
+ self.transformer_blocks = nn.ModuleList(
303
+ [
304
+ FluxTransformerBlock(
305
+ dim=self.inner_dim,
306
+ num_attention_heads=self.config.num_attention_heads,
307
+ attention_head_dim=self.config.attention_head_dim,
308
+ )
309
+ for i in range(self.config.num_layers)
310
+ ]
311
+ )
312
+
313
+ self.single_transformer_blocks = nn.ModuleList(
314
+ [
315
+ FluxSingleTransformerBlock(
316
+ dim=self.inner_dim,
317
+ num_attention_heads=self.config.num_attention_heads,
318
+ attention_head_dim=self.config.attention_head_dim,
319
+ )
320
+ for i in range(self.config.num_single_layers)
321
+ ]
322
+ )
323
+
324
+ self.norm_out = AdaLayerNormContinuous(self.inner_dim, self.inner_dim, elementwise_affine=False, eps=1e-6)
325
+ self.proj_out = nn.Linear(self.inner_dim, patch_size * patch_size * self.out_channels, bias=True)
326
+ ratio: float = 0.3
327
+ down: int = 1
328
+ sx: int = 2
329
+ sy: int = 2
330
+ rando: bool = False
331
+ m1: bool = False
332
+ m2: bool = True
333
+ m3: bool = False
334
+
335
+ self.tinfo = {
336
+ "size": None,
337
+ "args": {
338
+ "ratio": ratio,
339
+ "down": down,
340
+ "sx": sx,
341
+ "sy": sy,
342
+ "rando": rando,
343
+ "m1": m1,
344
+ "m2": m2,
345
+ "m3": m3,
346
+ "generator": generator
347
+ }
348
+ }
349
+
350
+ self.gradient_checkpointing = False
351
+
352
+ @property
353
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
354
+ r"""
355
+ Returns:
356
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
357
+ indexed by its weight name.
358
+ """
359
+ processors = {}
360
+
361
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
362
+ if hasattr(module, "get_processor"):
363
+ processors[f"{name}.processor"] = module.get_processor()
364
+
365
+ for sub_name, child in module.named_children():
366
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
367
+
368
+ return processors
369
+
370
+ for name, module in self.named_children():
371
+ fn_recursive_add_processors(name, module, processors)
372
+
373
+ return processors
374
+
375
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
376
+ count = len(self.attn_processors.keys())
377
+
378
+ if isinstance(processor, dict) and len(processor) != count:
379
+ raise ValueError(
380
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
381
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
382
+ )
383
+
384
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
385
+ if hasattr(module, "set_processor"):
386
+ if not isinstance(processor, dict):
387
+ module.set_processor(processor)
388
+ else:
389
+ module.set_processor(processor.pop(f"{name}.processor"))
390
+
391
+ for sub_name, child in module.named_children():
392
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
393
+
394
+ for name, module in self.named_children():
395
+ fn_recursive_attn_processor(name, module, processor)
396
+
397
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections with FusedAttnProcessor2_0->FusedFluxAttnProcessor2_0
398
+ def fuse_qkv_projections(self):
399
+ self.original_attn_processors = None
400
+
401
+ for _, attn_processor in self.attn_processors.items():
402
+ if "Added" in str(attn_processor.__class__.__name__):
403
+ raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
404
+
405
+ self.original_attn_processors = self.attn_processors
406
+
407
+ for module in self.modules():
408
+ if isinstance(module, Attention):
409
+ module.fuse_projections(fuse=True)
410
+
411
+ self.set_attn_processor(FusedFluxAttnProcessor2_0())
412
+
413
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections
414
+ def unfuse_qkv_projections(self):
415
+ if self.original_attn_processors is not None:
416
+ self.set_attn_processor(self.original_attn_processors)
417
+
418
+ def _set_gradient_checkpointing(self, module, value=False):
419
+ if hasattr(module, "gradient_checkpointing"):
420
+ module.gradient_checkpointing = value
421
+
422
+ def forward(
423
+ self,
424
+ hidden_states: torch.Tensor,
425
+ encoder_hidden_states: torch.Tensor = None,
426
+ pooled_projections: torch.Tensor = None,
427
+ timestep: torch.LongTensor = None,
428
+ img_ids: torch.Tensor = None,
429
+ txt_ids: torch.Tensor = None,
430
+ guidance: torch.Tensor = None,
431
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
432
+ controlnet_block_samples=None,
433
+ controlnet_single_block_samples=None,
434
+ return_dict: bool = True,
435
+ controlnet_blocks_repeat: bool = False,
436
+ ) -> Union[torch.FloatTensor, Transformer2DModelOutput]:
437
+ if joint_attention_kwargs is not None:
438
+ joint_attention_kwargs = joint_attention_kwargs.copy()
439
+ lora_scale = joint_attention_kwargs.pop("scale", 1.0)
440
+ else:
441
+ lora_scale = 1.0
442
+
443
+ if USE_PEFT_BACKEND:
444
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
445
+ scale_lora_layers(self, lora_scale)
446
+ else:
447
+ if joint_attention_kwargs is not None and joint_attention_kwargs.get("scale", None) is not None:
448
+ logger.warning(
449
+ "Passing `scale` via `joint_attention_kwargs` when not using the PEFT backend is ineffective."
450
+ )
451
+
452
+ hidden_states = self.x_embedder(hidden_states)
453
+ if len(hidden_states.shape) == 4:
454
+ self.tinfo["size"] = (hidden_states.shape[2], hidden_states.shape[3])
455
+
456
+ timestep = timestep.to(hidden_states.dtype) * 1000
457
+ if guidance is not None:
458
+ guidance = guidance.to(hidden_states.dtype) * 1000
459
+ else:
460
+ guidance = None
461
+
462
+ temb = (
463
+ self.time_text_embed(timestep, pooled_projections)
464
+ if guidance is None
465
+ else self.time_text_embed(timestep, guidance, pooled_projections)
466
+ )
467
+ encoder_hidden_states = self.context_embedder(encoder_hidden_states)
468
+
469
+ if txt_ids.ndim == 3:
470
+ logger.warning(
471
+ "Passing `txt_ids` 3d torch.Tensor is deprecated."
472
+ "Please remove the batch dimension and pass it as a 2d torch Tensor"
473
+ )
474
+ txt_ids = txt_ids[0]
475
+ if img_ids.ndim == 3:
476
+ logger.warning(
477
+ "Passing `img_ids` 3d torch.Tensor is deprecated."
478
+ "Please remove the batch dimension and pass it as a 2d torch Tensor"
479
+ )
480
+ img_ids = img_ids[0]
481
+
482
+ ids = torch.cat((txt_ids, img_ids), dim=0)
483
+ image_rotary_emb = self.pos_embed(ids)
484
+
485
+ for index_block, block in enumerate(self.transformer_blocks):
486
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
487
+
488
+ def create_custom_forward(module, return_dict=None):
489
+ def custom_forward(*inputs):
490
+ if return_dict is not None:
491
+ return module(*inputs, return_dict=return_dict)
492
+ else:
493
+ return module(*inputs)
494
+
495
+ return custom_forward
496
+
497
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
498
+ encoder_hidden_states, hidden_states = torch.utils.checkpoint.checkpoint(
499
+ create_custom_forward(block),
500
+ hidden_states,
501
+ encoder_hidden_states,
502
+ temb,
503
+ image_rotary_emb,
504
+ **ckpt_kwargs,
505
+ )
506
+
507
+ else:
508
+ encoder_hidden_states, hidden_states = block(
509
+ hidden_states=hidden_states,
510
+ encoder_hidden_states=encoder_hidden_states,
511
+ temb=temb,
512
+ image_rotary_emb=image_rotary_emb,
513
+ joint_attention_kwargs=joint_attention_kwargs,
514
+ )
515
+
516
+ if controlnet_block_samples is not None:
517
+ interval_control = len(self.transformer_blocks) / len(controlnet_block_samples)
518
+ interval_control = int(np.ceil(interval_control))
519
+ if controlnet_blocks_repeat:
520
+ hidden_states = (
521
+ hidden_states + controlnet_block_samples[index_block % len(controlnet_block_samples)]
522
+ )
523
+ else:
524
+ hidden_states = hidden_states + controlnet_block_samples[index_block // interval_control]
525
+
526
+ hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
527
+
528
+ for index_block, block in enumerate(self.single_transformer_blocks):
529
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
530
+
531
+ def create_custom_forward(module, return_dict=None):
532
+ def custom_forward(*inputs):
533
+ if return_dict is not None:
534
+ return module(*inputs, return_dict=return_dict)
535
+ else:
536
+ return module(*inputs)
537
+
538
+ return custom_forward
539
+
540
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
541
+ hidden_states = torch.utils.checkpoint.checkpoint(
542
+ create_custom_forward(block),
543
+ hidden_states,
544
+ temb,
545
+ image_rotary_emb,
546
+ **ckpt_kwargs,
547
+ )
548
+
549
+ else:
550
+ hidden_states = block(
551
+ hidden_states=hidden_states,
552
+ temb=temb,
553
+ image_rotary_emb=image_rotary_emb,
554
+ joint_attention_kwargs=joint_attention_kwargs,
555
+ )
556
+
557
+ if controlnet_single_block_samples is not None:
558
+ interval_control = len(self.single_transformer_blocks) / len(controlnet_single_block_samples)
559
+ interval_control = int(np.ceil(interval_control))
560
+ hidden_states[:, encoder_hidden_states.shape[1] :, ...] = (
561
+ hidden_states[:, encoder_hidden_states.shape[1] :, ...]
562
+ + controlnet_single_block_samples[index_block // interval_control]
563
+ )
564
+
565
+ hidden_states = hidden_states[:, encoder_hidden_states.shape[1] :, ...]
566
+
567
+ hidden_states = self.norm_out(hidden_states, temb)
568
+ output = self.proj_out(hidden_states)
569
+
570
+ if USE_PEFT_BACKEND:
571
+ unscale_lora_layers(self, lora_scale)
572
+
573
+ if not return_dict:
574
+ return (output,)
575
+
576
+ return Transformer2DModelOutput(sample=output)
577
+
578
+ from diffusers import FluxPipeline, FluxTransformer2DModel
579
+ Pipeline = None
580
+ torch.backends.cuda.matmul.allow_tf32 = True
581
+ torch.backends.cudnn.enabled = True
582
+ torch.backends.cudnn.benchmark = True
583
+
584
+ ckpt_id = "black-forest-labs/FLUX.1-schnell"
585
+ ckpt_revision = "741f7c3ce8b383c54771c7003378a50191e9efe9"
586
+
587
+ TinyVAE = "madebyollin/taef1"
588
+ TinyVAE_REV = "2d552378e58c9c94201075708d7de4e1163b2689"
589
+
590
+
591
+ def empty_cache():
592
+ gc.collect()
593
+ torch.cuda.empty_cache()
594
+ torch.cuda.reset_max_memory_allocated()
595
+ torch.cuda.reset_peak_memory_stats()
596
+
597
+ def load_pipeline() -> Pipeline:
598
+ empty_cache()
599
+ test = "Pneumonoultramicroscopicsilicovolcanoconiosis, Floccinaucinihilipilification, Pseudopseudohypoparathyroidism, Antidisestablishmentarianism, Supercalifragilisticexpialidocious, Honorificabilitudinitatibus"
600
+
601
+ dtype, device = torch.bfloat16, "cuda"
602
+ text_encoder_2 = T5EncoderModel.from_pretrained(
603
+ "city96/t5-v1_1-xxl-encoder-bf16", revision = "1b9c856aadb864af93c1dcdc226c2774fa67bc86", torch_dtype=torch.bfloat16
604
+ ).to(memory_format=torch.channels_last)
605
+ path = os.path.join(HF_HUB_CACHE, "models--manbeast3b--flux.1-schnell-full1/snapshots/cb1b599b0d712b9aab2c4df3ad27b050a27ec146/transformer")
606
+ model = FluxTransformer2DModel.from_pretrained(path, torch_dtype=dtype, use_safetensors=False, local_files_only=True)
607
+ vae = AutoencoderTiny.from_pretrained(
608
+ TinyVAE,
609
+ revision=TinyVAE_REV,
610
+ local_files_only=True,
611
+ torch_dtype=torch.bfloat16)
612
+ pipeline = FluxPipeline.from_pretrained(
613
+ ckpt_id,
614
+ revision=ckpt_revision,
615
+ transformer=model,
616
+ vae=vae,
617
+ # text_encoder_2=text_encoder_2,
618
+ torch_dtype=dtype,
619
+ )
620
+ pipeline.transformer.to(memory_format=torch.channels_last)
621
+ pipeline.vae.to(memory_format=torch.channels_last)
622
+ quantize_(pipeline.vae, int8_weight_only())
623
+ pipeline.vae = torch.compile(pipeline.vae, mode="reduce-overhead", fullgraph=True)
624
+ pipeline.to(device)
625
+ # pipeline.transformer = torch.compile(pipeline.transformer, mode="max-autotune")
626
+ for _ in range(2):
627
+ pipeline(prompt=test, width=1024, height=1024, guidance_scale=0.0, num_inference_steps=4, max_sequence_length=256)
628
+
629
+ return pipeline
630
+
631
+ sample = None
632
+ @torch.no_grad()
633
+ def infer(request: TextToImageRequest, pipeline: Pipeline, generator: Generator) -> Image:
634
+ global sample
635
+ if not sample:
636
+ sample=1
637
+ empty_cache()
638
+ 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]
639
+ return image
uv.lock ADDED
The diff for this file is too large to render. See raw diff