manbeast3b commited on
Commit
6c8b2aa
·
0 Parent(s):

Initial commit

Browse files
Files changed (6) hide show
  1. .gitattributes +37 -0
  2. pyproject.toml +44 -0
  3. src/ghanta.py +74 -0
  4. src/main.py +55 -0
  5. src/pipeline.py +590 -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,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ]
23
+
24
+ [[tool.edge-maxxing.models]]
25
+ repository = "black-forest-labs/FLUX.1-schnell"
26
+ revision = "741f7c3ce8b383c54771c7003378a50191e9efe9"
27
+ exclude = ["transformer"]
28
+
29
+ [[tool.edge-maxxing.models]]
30
+ repository = "RobertML/FLUX.1-schnell-int8wo"
31
+ revision = "307e0777d92df966a3c0f99f31a6ee8957a9857a"
32
+
33
+ [[tool.edge-maxxing.models]]
34
+ repository = "city96/t5-v1_1-xxl-encoder-bf16"
35
+ revision = "1b9c856aadb864af93c1dcdc226c2774fa67bc86"
36
+
37
+ [[tool.edge-maxxing.models]]
38
+ repository = "RobertML/FLUX.1-schnell-vae_e3m2"
39
+ revision = "da0d2cd7815792fb40d084dbd8ed32b63f153d8d"
40
+
41
+
42
+ [project.scripts]
43
+ start_inference = "main:main"
44
+
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,590 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import os
17
+ os.environ['PYTORCH_CUDA_ALLOC_CONF']="expandable_segments:True"
18
+
19
+ import torch
20
+ import math
21
+ from typing import Type, Dict, Any, Tuple, Callable, Optional, Union
22
+ import ghanta
23
+ import numpy as np
24
+ import torch
25
+ import torch.nn as nn
26
+ import torch.nn.functional as F
27
+
28
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
29
+ from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
30
+ from diffusers.models.attention import FeedForward
31
+ from diffusers.models.attention_processor import (
32
+ Attention,
33
+ AttentionProcessor,
34
+ FluxAttnProcessor2_0,
35
+ FusedFluxAttnProcessor2_0,
36
+ )
37
+ from diffusers.models.modeling_utils import ModelMixin
38
+ from diffusers.models.normalization import AdaLayerNormContinuous, AdaLayerNormZero, AdaLayerNormZeroSingle
39
+ from diffusers.utils import USE_PEFT_BACKEND, is_torch_version, logging, scale_lora_layers, unscale_lora_layers
40
+ from diffusers.utils.import_utils import is_torch_npu_available
41
+ from diffusers.utils.torch_utils import maybe_allow_in_graph
42
+ from diffusers.models.embeddings import CombinedTimestepGuidanceTextProjEmbeddings, CombinedTimestepTextProjEmbeddings, FluxPosEmbed
43
+ from diffusers.models.modeling_outputs import Transformer2DModelOutput
44
+
45
+ def inicializar_generador(dispositivo: torch.device, respaldo: torch.Generator = None):
46
+ if dispositivo.type == "cpu":
47
+ return torch.Generator(device="cpu").set_state(torch.get_rng_state())
48
+ elif dispositivo.type == "cuda":
49
+ return torch.Generator(device=dispositivo).set_state(torch.cuda.get_rng_state())
50
+ else:
51
+ if respaldo is None:
52
+ return inicializar_generador(torch.device("cpu"))
53
+ else:
54
+ return respaldo
55
+
56
+ def calcular_fusion(x: torch.Tensor, info_tome: Dict[str, Any]) -> Tuple[Callable, ...]:
57
+ alto_original, ancho_original = info_tome["size"]
58
+ tokens_originales = alto_original * ancho_original
59
+ submuestreo = int(math.ceil(math.sqrt(tokens_originales // x.shape[1])))
60
+ argumentos = info_tome["args"]
61
+ if submuestreo <= argumentos["down"]:
62
+ ancho = int(math.ceil(ancho_original / submuestreo))
63
+ alto = int(math.ceil(alto_original / submuestreo))
64
+ radio = int(x.shape[1] * argumentos["ratio"])
65
+
66
+ if argumentos["generator"] is None:
67
+ argumentos["generator"] = inicializar_generador(x.device)
68
+ elif argumentos["generator"].device != x.device:
69
+ argumentos["generator"] = inicializar_generador(x.device, respaldo=argumentos["generator"])
70
+
71
+ usar_aleatoriedad = argumentos["rando"]
72
+ fusion, desfusion = ghanta.emparejamiento_suave_aleatorio_2d(
73
+ x, ancho, alto, argumentos["sx"], argumentos["sy"], radio,
74
+ sin_aleatoriedad=not usar_aleatoriedad, generador=argumentos["generator"]
75
+ )
76
+ else:
77
+ fusion, desfusion = (hacer_nada, hacer_nada)
78
+ fusion_a, desfusion_a = (fusion, desfusion) if argumentos["m1"] else (hacer_nada, hacer_nada)
79
+ fusion_c, desfusion_c = (fusion, desfusion) if argumentos["m2"] else (hacer_nada, hacer_nada)
80
+ fusion_m, desfusion_m = (fusion, desfusion) if argumentos["m3"] else (hacer_nada, hacer_nada)
81
+ return fusion_a, fusion_c, fusion_m, desfusion_a, desfusion_c, desfusion_m
82
+
83
+ @maybe_allow_in_graph
84
+ class FluxSingleTransformerBlock(nn.Module):
85
+
86
+ def __init__(self, dim, num_attention_heads, attention_head_dim, mlp_ratio=4.0):
87
+ super().__init__()
88
+ self.mlp_hidden_dim = int(dim * mlp_ratio)
89
+
90
+ self.norm = AdaLayerNormZeroSingle(dim)
91
+ self.proj_mlp = nn.Linear(dim, self.mlp_hidden_dim)
92
+ self.act_mlp = nn.GELU(approximate="tanh")
93
+ self.proj_out = nn.Linear(dim + self.mlp_hidden_dim, dim)
94
+
95
+ processor = FluxAttnProcessor2_0()
96
+ self.attn = Attention(
97
+ query_dim=dim,
98
+ cross_attention_dim=None,
99
+ dim_head=attention_head_dim,
100
+ heads=num_attention_heads,
101
+ out_dim=dim,
102
+ bias=True,
103
+ processor=processor,
104
+ qk_norm="rms_norm",
105
+ eps=1e-6,
106
+ pre_only=True,
107
+ )
108
+
109
+ def forward(
110
+ self,
111
+ hidden_states: torch.FloatTensor,
112
+ temb: torch.FloatTensor,
113
+ image_rotary_emb=None,
114
+ joint_attention_kwargs=None,
115
+ tinfo: Dict[str, Any] = None,
116
+ ):
117
+ if tinfo is not None:
118
+ m_a, m_c, mom, u_a, u_c, u_m = calcular_fusion(hidden_states, tinfo)
119
+ else:
120
+ 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)
121
+
122
+ residual = hidden_states
123
+ norm_hidden_states, gate = self.norm(hidden_states, emb=temb)
124
+ norm_hidden_states = m_a(norm_hidden_states)
125
+ mlp_hidden_states = self.act_mlp(self.proj_mlp(norm_hidden_states))
126
+ joint_attention_kwargs = joint_attention_kwargs or {}
127
+ attn_output = self.attn(
128
+ hidden_states=norm_hidden_states,
129
+ image_rotary_emb=image_rotary_emb,
130
+ **joint_attention_kwargs,
131
+ )
132
+
133
+ hidden_states = torch.cat([attn_output, mlp_hidden_states], dim=2)
134
+ gate = gate.unsqueeze(1)
135
+ hidden_states = gate * self.proj_out(hidden_states)
136
+ hidden_states = u_a(residual + hidden_states)
137
+
138
+ return hidden_states
139
+
140
+
141
+ @maybe_allow_in_graph
142
+ class FluxTransformerBlock(nn.Module):
143
+
144
+ def __init__(self, dim, num_attention_heads, attention_head_dim, qk_norm="rms_norm", eps=1e-6):
145
+ super().__init__()
146
+
147
+ self.norm1 = AdaLayerNormZero(dim)
148
+
149
+ self.norm1_context = AdaLayerNormZero(dim)
150
+
151
+ if hasattr(F, "scaled_dot_product_attention"):
152
+ processor = FluxAttnProcessor2_0()
153
+ else:
154
+ raise ValueError(
155
+ "The current PyTorch version does not support the `scaled_dot_product_attention` function."
156
+ )
157
+ self.attn = Attention(
158
+ query_dim=dim,
159
+ cross_attention_dim=None,
160
+ added_kv_proj_dim=dim,
161
+ dim_head=attention_head_dim,
162
+ heads=num_attention_heads,
163
+ out_dim=dim,
164
+ context_pre_only=False,
165
+ bias=True,
166
+ processor=processor,
167
+ qk_norm=qk_norm,
168
+ eps=eps,
169
+ )
170
+
171
+ self.norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
172
+ self.ff = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
173
+
174
+ self.norm2_context = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
175
+ self.ff_context = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
176
+ self._chunk_size = None
177
+ self._chunk_dim = 0
178
+
179
+ def forward(
180
+ self,
181
+ hidden_states: torch.FloatTensor,
182
+ encoder_hidden_states: torch.FloatTensor,
183
+ temb: torch.FloatTensor,
184
+ image_rotary_emb=None,
185
+ joint_attention_kwargs=None,
186
+ tinfo: Dict[str, Any] = None, # Add tinfo parameter
187
+ ):
188
+ if tinfo is not None:
189
+ m_a, m_c, mom, u_a, u_c, u_m = calcular_fusion(hidden_states, tinfo)
190
+ else:
191
+ 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)
192
+
193
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(hidden_states, emb=temb)
194
+
195
+ norm_encoder_hidden_states, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = self.norm1_context(
196
+ encoder_hidden_states, emb=temb
197
+ )
198
+ joint_attention_kwargs = joint_attention_kwargs or {}
199
+ norm_hidden_states = m_a(norm_hidden_states)
200
+ norm_encoder_hidden_states = m_c(norm_encoder_hidden_states)
201
+
202
+ attn_output, context_attn_output = self.attn(
203
+ hidden_states=norm_hidden_states,
204
+ encoder_hidden_states=norm_encoder_hidden_states,
205
+ image_rotary_emb=image_rotary_emb,
206
+ **joint_attention_kwargs,
207
+ )
208
+
209
+ attn_output = gate_msa.unsqueeze(1) * attn_output
210
+ hidden_states = u_a(attn_output) + hidden_states
211
+
212
+ norm_hidden_states = self.norm2(hidden_states)
213
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
214
+
215
+ norm_hidden_states = mom(norm_hidden_states)
216
+
217
+ ff_output = self.ff(norm_hidden_states)
218
+ ff_output = gate_mlp.unsqueeze(1) * ff_output
219
+
220
+ hidden_states = u_m(ff_output) + hidden_states
221
+ context_attn_output = c_gate_msa.unsqueeze(1) * context_attn_output
222
+ encoder_hidden_states = u_c(context_attn_output) + encoder_hidden_states
223
+
224
+ norm_encoder_hidden_states = self.norm2_context(encoder_hidden_states)
225
+ norm_encoder_hidden_states = norm_encoder_hidden_states * (1 + c_scale_mlp[:, None]) + c_shift_mlp[:, None]
226
+
227
+ context_ff_output = self.ff_context(norm_encoder_hidden_states)
228
+ encoder_hidden_states = encoder_hidden_states + c_gate_mlp.unsqueeze(1) * context_ff_output
229
+
230
+ return encoder_hidden_states, hidden_states
231
+
232
+
233
+ class FluxTransformer2DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):
234
+
235
+ _supports_gradient_checkpointing = True
236
+ _no_split_modules = ["FluxTransformerBlock", "FluxSingleTransformerBlock"]
237
+
238
+ @register_to_config
239
+ def __init__(
240
+ self,
241
+ patch_size: int = 1,
242
+ in_channels: int = 64,
243
+ out_channels: Optional[int] = None,
244
+ num_layers: int = 19,
245
+ num_single_layers: int = 38,
246
+ attention_head_dim: int = 128,
247
+ num_attention_heads: int = 24,
248
+ joint_attention_dim: int = 4096,
249
+ pooled_projection_dim: int = 768,
250
+ guidance_embeds: bool = False,
251
+ axes_dims_rope: Tuple[int] = (16, 56, 56),
252
+ generator: Optional[torch.Generator] = None,
253
+ ):
254
+ super().__init__()
255
+ self.out_channels = out_channels or in_channels
256
+ self.inner_dim = self.config.num_attention_heads * self.config.attention_head_dim
257
+
258
+ self.pos_embed = FluxPosEmbed(theta=10000, axes_dim=axes_dims_rope)
259
+
260
+ text_time_guidance_cls = (
261
+ CombinedTimestepGuidanceTextProjEmbeddings if guidance_embeds else CombinedTimestepTextProjEmbeddings
262
+ )
263
+ self.time_text_embed = text_time_guidance_cls(
264
+ embedding_dim=self.inner_dim, pooled_projection_dim=self.config.pooled_projection_dim
265
+ )
266
+
267
+ self.context_embedder = nn.Linear(self.config.joint_attention_dim, self.inner_dim)
268
+ self.x_embedder = nn.Linear(self.config.in_channels, self.inner_dim)
269
+
270
+ self.transformer_blocks = nn.ModuleList(
271
+ [
272
+ FluxTransformerBlock(
273
+ dim=self.inner_dim,
274
+ num_attention_heads=self.config.num_attention_heads,
275
+ attention_head_dim=self.config.attention_head_dim,
276
+ )
277
+ for i in range(self.config.num_layers)
278
+ ]
279
+ )
280
+
281
+ self.single_transformer_blocks = nn.ModuleList(
282
+ [
283
+ FluxSingleTransformerBlock(
284
+ dim=self.inner_dim,
285
+ num_attention_heads=self.config.num_attention_heads,
286
+ attention_head_dim=self.config.attention_head_dim,
287
+ )
288
+ for i in range(self.config.num_single_layers)
289
+ ]
290
+ )
291
+
292
+ self.norm_out = AdaLayerNormContinuous(self.inner_dim, self.inner_dim, elementwise_affine=False, eps=1e-6)
293
+ self.proj_out = nn.Linear(self.inner_dim, patch_size * patch_size * self.out_channels, bias=True)
294
+ ratio: float = 0.2
295
+ down: int = 3
296
+ sx: int = 2
297
+ sy: int = 2
298
+ rando: bool = False
299
+ m1: bool = False
300
+ m2: bool = True
301
+ m3: bool = False
302
+
303
+ self.tinfo = {
304
+ "size": None,
305
+ "args": {
306
+ "ratio": ratio,
307
+ "down": down,
308
+ "sx": sx,
309
+ "sy": sy,
310
+ "rando": rando,
311
+ "m1": m1,
312
+ "m2": m2,
313
+ "m3": m3,
314
+ "generator": generator
315
+ }
316
+ }
317
+
318
+ self.gradient_checkpointing = False
319
+
320
+ @property
321
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
322
+ r"""
323
+ Returns:
324
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
325
+ indexed by its weight name.
326
+ """
327
+ processors = {}
328
+
329
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
330
+ if hasattr(module, "get_processor"):
331
+ processors[f"{name}.processor"] = module.get_processor()
332
+
333
+ for sub_name, child in module.named_children():
334
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
335
+
336
+ return processors
337
+
338
+ for name, module in self.named_children():
339
+ fn_recursive_add_processors(name, module, processors)
340
+
341
+ return processors
342
+
343
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
344
+ count = len(self.attn_processors.keys())
345
+
346
+ if isinstance(processor, dict) and len(processor) != count:
347
+ raise ValueError(
348
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
349
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
350
+ )
351
+
352
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
353
+ if hasattr(module, "set_processor"):
354
+ if not isinstance(processor, dict):
355
+ module.set_processor(processor)
356
+ else:
357
+ module.set_processor(processor.pop(f"{name}.processor"))
358
+
359
+ for sub_name, child in module.named_children():
360
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
361
+
362
+ for name, module in self.named_children():
363
+ fn_recursive_attn_processor(name, module, processor)
364
+
365
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections with FusedAttnProcessor2_0->FusedFluxAttnProcessor2_0
366
+ def fuse_qkv_projections(self):
367
+ self.original_attn_processors = None
368
+
369
+ for _, attn_processor in self.attn_processors.items():
370
+ if "Added" in str(attn_processor.__class__.__name__):
371
+ raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
372
+
373
+ self.original_attn_processors = self.attn_processors
374
+
375
+ for module in self.modules():
376
+ if isinstance(module, Attention):
377
+ module.fuse_projections(fuse=True)
378
+
379
+ self.set_attn_processor(FusedFluxAttnProcessor2_0())
380
+
381
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections
382
+ def unfuse_qkv_projections(self):
383
+ if self.original_attn_processors is not None:
384
+ self.set_attn_processor(self.original_attn_processors)
385
+
386
+ def _set_gradient_checkpointing(self, module, value=False):
387
+ if hasattr(module, "gradient_checkpointing"):
388
+ module.gradient_checkpointing = value
389
+
390
+ def forward(
391
+ self,
392
+ hidden_states: torch.Tensor,
393
+ encoder_hidden_states: torch.Tensor = None,
394
+ pooled_projections: torch.Tensor = None,
395
+ timestep: torch.LongTensor = None,
396
+ img_ids: torch.Tensor = None,
397
+ txt_ids: torch.Tensor = None,
398
+ guidance: torch.Tensor = None,
399
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
400
+ controlnet_block_samples=None,
401
+ controlnet_single_block_samples=None,
402
+ return_dict: bool = True,
403
+ controlnet_blocks_repeat: bool = False,
404
+ ) -> Union[torch.FloatTensor, Transformer2DModelOutput]:
405
+ if joint_attention_kwargs is not None:
406
+ joint_attention_kwargs = joint_attention_kwargs.copy()
407
+ lora_scale = joint_attention_kwargs.pop("scale", 1.0)
408
+ else:
409
+ lora_scale = 1.0
410
+
411
+ if USE_PEFT_BACKEND:
412
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
413
+ scale_lora_layers(self, lora_scale)
414
+ else:
415
+ if joint_attention_kwargs is not None and joint_attention_kwargs.get("scale", None) is not None:
416
+ logger.warning(
417
+ "Passing `scale` via `joint_attention_kwargs` when not using the PEFT backend is ineffective."
418
+ )
419
+
420
+ hidden_states = self.x_embedder(hidden_states)
421
+ if len(hidden_states.shape) == 4:
422
+ self.tinfo["size"] = (hidden_states.shape[2], hidden_states.shape[3])
423
+
424
+ timestep = timestep.to(hidden_states.dtype) * 1000
425
+ if guidance is not None:
426
+ guidance = guidance.to(hidden_states.dtype) * 1000
427
+ else:
428
+ guidance = None
429
+
430
+ temb = (
431
+ self.time_text_embed(timestep, pooled_projections)
432
+ if guidance is None
433
+ else self.time_text_embed(timestep, guidance, pooled_projections)
434
+ )
435
+ encoder_hidden_states = self.context_embedder(encoder_hidden_states)
436
+
437
+ if txt_ids.ndim == 3:
438
+ logger.warning(
439
+ "Passing `txt_ids` 3d torch.Tensor is deprecated."
440
+ "Please remove the batch dimension and pass it as a 2d torch Tensor"
441
+ )
442
+ txt_ids = txt_ids[0]
443
+ if img_ids.ndim == 3:
444
+ logger.warning(
445
+ "Passing `img_ids` 3d torch.Tensor is deprecated."
446
+ "Please remove the batch dimension and pass it as a 2d torch Tensor"
447
+ )
448
+ img_ids = img_ids[0]
449
+
450
+ ids = torch.cat((txt_ids, img_ids), dim=0)
451
+ image_rotary_emb = self.pos_embed(ids)
452
+
453
+ for index_block, block in enumerate(self.transformer_blocks):
454
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
455
+
456
+ def create_custom_forward(module, return_dict=None):
457
+ def custom_forward(*inputs):
458
+ if return_dict is not None:
459
+ return module(*inputs, return_dict=return_dict)
460
+ else:
461
+ return module(*inputs)
462
+
463
+ return custom_forward
464
+
465
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
466
+ encoder_hidden_states, hidden_states = torch.utils.checkpoint.checkpoint(
467
+ create_custom_forward(block),
468
+ hidden_states,
469
+ encoder_hidden_states,
470
+ temb,
471
+ image_rotary_emb,
472
+ **ckpt_kwargs,
473
+ )
474
+
475
+ else:
476
+ encoder_hidden_states, hidden_states = block(
477
+ hidden_states=hidden_states,
478
+ encoder_hidden_states=encoder_hidden_states,
479
+ temb=temb,
480
+ image_rotary_emb=image_rotary_emb,
481
+ joint_attention_kwargs=joint_attention_kwargs,
482
+ )
483
+
484
+ if controlnet_block_samples is not None:
485
+ interval_control = len(self.transformer_blocks) / len(controlnet_block_samples)
486
+ interval_control = int(np.ceil(interval_control))
487
+ if controlnet_blocks_repeat:
488
+ hidden_states = (
489
+ hidden_states + controlnet_block_samples[index_block % len(controlnet_block_samples)]
490
+ )
491
+ else:
492
+ hidden_states = hidden_states + controlnet_block_samples[index_block // interval_control]
493
+
494
+ hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
495
+
496
+ for index_block, block in enumerate(self.single_transformer_blocks):
497
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
498
+
499
+ def create_custom_forward(module, return_dict=None):
500
+ def custom_forward(*inputs):
501
+ if return_dict is not None:
502
+ return module(*inputs, return_dict=return_dict)
503
+ else:
504
+ return module(*inputs)
505
+
506
+ return custom_forward
507
+
508
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
509
+ hidden_states = torch.utils.checkpoint.checkpoint(
510
+ create_custom_forward(block),
511
+ hidden_states,
512
+ temb,
513
+ image_rotary_emb,
514
+ **ckpt_kwargs,
515
+ )
516
+
517
+ else:
518
+ hidden_states = block(
519
+ hidden_states=hidden_states,
520
+ temb=temb,
521
+ image_rotary_emb=image_rotary_emb,
522
+ joint_attention_kwargs=joint_attention_kwargs,
523
+ )
524
+
525
+ if controlnet_single_block_samples is not None:
526
+ interval_control = len(self.single_transformer_blocks) / len(controlnet_single_block_samples)
527
+ interval_control = int(np.ceil(interval_control))
528
+ hidden_states[:, encoder_hidden_states.shape[1] :, ...] = (
529
+ hidden_states[:, encoder_hidden_states.shape[1] :, ...]
530
+ + controlnet_single_block_samples[index_block // interval_control]
531
+ )
532
+
533
+ hidden_states = hidden_states[:, encoder_hidden_states.shape[1] :, ...]
534
+
535
+ hidden_states = self.norm_out(hidden_states, temb)
536
+ output = self.proj_out(hidden_states)
537
+
538
+ if USE_PEFT_BACKEND:
539
+ unscale_lora_layers(self, lora_scale)
540
+
541
+ if not return_dict:
542
+ return (output,)
543
+
544
+ return Transformer2DModelOutput(sample=output)
545
+
546
+ Pipeline = None
547
+ torch.backends.cuda.matmul.allow_tf32 = True
548
+ torch.backends.cudnn.enabled = True
549
+ torch.backends.cudnn.benchmark = True
550
+
551
+ ckpt_id = "black-forest-labs/FLUX.1-schnell"
552
+ ckpt_revision = "741f7c3ce8b383c54771c7003378a50191e9efe9"
553
+ def empty_cache():
554
+ gc.collect()
555
+ torch.cuda.empty_cache()
556
+ torch.cuda.reset_max_memory_allocated()
557
+ torch.cuda.reset_peak_memory_stats()
558
+
559
+ def load_pipeline() -> Pipeline:
560
+ empty_cache()
561
+
562
+ dtype, device = torch.bfloat16, "cuda"
563
+
564
+ text_encoder_2 = T5EncoderModel.from_pretrained(
565
+ "city96/t5-v1_1-xxl-encoder-bf16", revision = "1b9c856aadb864af93c1dcdc226c2774fa67bc86", torch_dtype=torch.bfloat16
566
+ ).to(memory_format=torch.channels_last)
567
+
568
+ vae = AutoencoderTiny.from_pretrained("RobertML/FLUX.1-schnell-vae_e3m2", revision="da0d2cd7815792fb40d084dbd8ed32b63f153d8d", torch_dtype=dtype)
569
+ path = os.path.join(HF_HUB_CACHE, "models--RobertML--FLUX.1-schnell-int8wo/snapshots/307e0777d92df966a3c0f99f31a6ee8957a9857a")
570
+ generator = torch.Generator(device=device)
571
+ model = FluxTransformer2DModel.from_pretrained(path, torch_dtype=dtype, use_safetensors=False, generator= generator).to(memory_format=torch.channels_last)
572
+ pipeline = DiffusionPipeline.from_pretrained(
573
+ ckpt_id,
574
+ vae=vae,
575
+ revision=ckpt_revision,
576
+ transformer=model,
577
+ text_encoder_2=text_encoder_2,
578
+ torch_dtype=dtype,
579
+ ).to(device)
580
+ for _ in range(3):
581
+ pipeline(prompt="blah blah waah waah oneshot oneshot gang gang", width=1024, height=1024, guidance_scale=0.0, num_inference_steps=4, max_sequence_length=256)
582
+
583
+ empty_cache()
584
+ return pipeline
585
+
586
+
587
+ @torch.no_grad()
588
+ def infer(request: TextToImageRequest, pipeline: Pipeline, generator: Generator) -> Image:
589
+ 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]
590
+ return image
uv.lock ADDED
The diff for this file is too large to render. See raw diff