ideprado commited on
Commit
5260f7d
·
1 Parent(s): 18a325b

F-lite first trial

Browse files
Files changed (6) hide show
  1. .gitignore +74 -0
  2. app.py +23 -16
  3. pikigen/__init__.py +5 -0
  4. pikigen/model.py +455 -0
  5. pikigen/pipeline.py +296 -0
  6. requirements.txt +7 -4
.gitignore ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ build/
8
+ develop-eggs/
9
+ dist/
10
+ downloads/
11
+ eggs/
12
+ .eggs/
13
+ lib/
14
+ lib64/
15
+ parts/
16
+ sdist/
17
+ var/
18
+ wheels/
19
+ *.egg-info/
20
+ .installed.cfg
21
+ *.egg
22
+ MANIFEST
23
+
24
+ # Environments
25
+ .env
26
+ .venv
27
+ env/
28
+ venv/
29
+ ENV/
30
+ env.bak/
31
+ venv.bak/
32
+
33
+ # Distribution / packaging
34
+ .Python
35
+ env/
36
+ .coverage
37
+ htmlcov/
38
+
39
+ # IDE specific files
40
+ .idea/
41
+ .vscode/
42
+ *.swp
43
+ *.swo
44
+ .DS_Store
45
+
46
+ # Jupyter Notebook
47
+ .ipynb_checkpoints
48
+
49
+ # ML specific
50
+ *.onnx
51
+ *.pt
52
+ *.pth
53
+ *.bin
54
+ *.h5
55
+ *.hdf5
56
+ runs/
57
+ wandb/
58
+ checkpoints/
59
+ outputs/
60
+ logs/
61
+ models/
62
+
63
+ # Project specific
64
+ .pytest_cache/
65
+ .coverage
66
+ htmlcov/
67
+
68
+ # Large media files
69
+ *.mp4
70
+ *.tiff
71
+ *.avi
72
+ *.flv
73
+ *.mov
74
+ *.wmv
app.py CHANGED
@@ -2,26 +2,33 @@ import gradio as gr
2
  import numpy as np
3
  import random
4
 
5
- import spaces #[uncomment to use ZeroGPU]
6
- from diffusers import DiffusionPipeline
7
  import torch
 
 
 
 
 
 
8
 
9
  device = "cuda" if torch.cuda.is_available() else "cpu"
10
- model_repo_id = "stabilityai/sdxl-turbo" # Replace to the model you would like to use
11
 
12
  if torch.cuda.is_available():
13
- torch_dtype = torch.float16
14
  else:
15
  torch_dtype = torch.float32
16
 
17
- pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
18
- pipe = pipe.to(device)
 
 
19
 
20
  MAX_SEED = np.iinfo(np.int32).max
21
  MAX_IMAGE_SIZE = 1024
22
 
23
 
24
- @spaces.GPU #[uncomment to use ZeroGPU]
25
  def infer(
26
  prompt,
27
  negative_prompt,
@@ -52,9 +59,9 @@ def infer(
52
 
53
 
54
  examples = [
55
- "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
56
- "An astronaut riding a green horse",
57
- "A delicious ceviche cheesecake slice",
58
  ]
59
 
60
  css = """
@@ -66,7 +73,7 @@ css = """
66
 
67
  with gr.Blocks(css=css) as demo:
68
  with gr.Column(elem_id="col-container"):
69
- gr.Markdown(" # Text-to-Image Gradio Template")
70
 
71
  with gr.Row():
72
  prompt = gr.Text(
@@ -86,7 +93,7 @@ with gr.Blocks(css=css) as demo:
86
  label="Negative prompt",
87
  max_lines=1,
88
  placeholder="Enter a negative prompt",
89
- visible=False,
90
  )
91
 
92
  seed = gr.Slider(
@@ -105,7 +112,7 @@ with gr.Blocks(css=css) as demo:
105
  minimum=256,
106
  maximum=MAX_IMAGE_SIZE,
107
  step=32,
108
- value=1024, # Replace with defaults that work for your model
109
  )
110
 
111
  height = gr.Slider(
@@ -113,7 +120,7 @@ with gr.Blocks(css=css) as demo:
113
  minimum=256,
114
  maximum=MAX_IMAGE_SIZE,
115
  step=32,
116
- value=1024, # Replace with defaults that work for your model
117
  )
118
 
119
  with gr.Row():
@@ -122,7 +129,7 @@ with gr.Blocks(css=css) as demo:
122
  minimum=0.0,
123
  maximum=10.0,
124
  step=0.1,
125
- value=0.0, # Replace with defaults that work for your model
126
  )
127
 
128
  num_inference_steps = gr.Slider(
@@ -130,7 +137,7 @@ with gr.Blocks(css=css) as demo:
130
  minimum=1,
131
  maximum=50,
132
  step=1,
133
- value=2, # Replace with defaults that work for your model
134
  )
135
 
136
  gr.Examples(examples=examples, inputs=[prompt])
 
2
  import numpy as np
3
  import random
4
 
5
+ import spaces
 
6
  import torch
7
+ from pikigen import PikigenPipeline
8
+
9
+ # Trick required because it is not a native diffusers model
10
+ from diffusers.pipelines.pipeline_loading_utils import LOADABLE_CLASSES, ALL_IMPORTABLE_CLASSES
11
+ LOADABLE_CLASSES.setdefault("pikigen", {}).setdefault("DiT", []).extend(["save_pretrained", "from_pretrained"])
12
+ ALL_IMPORTABLE_CLASSES.setdefault("DiT", []).extend(["save_pretrained", "from_pretrained"])
13
 
14
  device = "cuda" if torch.cuda.is_available() else "cpu"
15
+ model_repo_id = "Freepik/Pikigen-test"
16
 
17
  if torch.cuda.is_available():
18
+ torch_dtype = torch.bfloat16
19
  else:
20
  torch_dtype = torch.float32
21
 
22
+ pipe = PikigenPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
23
+ pipe.enable_model_cpu_offload() # For less memory consumption
24
+ pipe.vae.enable_slicing()
25
+ pipe.vae.enable_tiling()
26
 
27
  MAX_SEED = np.iinfo(np.int32).max
28
  MAX_IMAGE_SIZE = 1024
29
 
30
 
31
+ @spaces.GPU
32
  def infer(
33
  prompt,
34
  negative_prompt,
 
59
 
60
 
61
  examples = [
62
+ "A photorealistic 3D render of a charming, mischievous young boy with long, floppy donkey ears and a small pink pig nose",
63
+ "A landscape photograph showing a serene mountain lake at sunset with reflections in crystal clear water",
64
+ "A detailed digital painting of a futuristic cyberpunk city with neon lights and flying vehicles",
65
  ]
66
 
67
  css = """
 
73
 
74
  with gr.Blocks(css=css) as demo:
75
  with gr.Column(elem_id="col-container"):
76
+ gr.Markdown(" # Pikigen Text-to-Image Demo")
77
 
78
  with gr.Row():
79
  prompt = gr.Text(
 
93
  label="Negative prompt",
94
  max_lines=1,
95
  placeholder="Enter a negative prompt",
96
+ visible=True,
97
  )
98
 
99
  seed = gr.Slider(
 
112
  minimum=256,
113
  maximum=MAX_IMAGE_SIZE,
114
  step=32,
115
+ value=1024,
116
  )
117
 
118
  height = gr.Slider(
 
120
  minimum=256,
121
  maximum=MAX_IMAGE_SIZE,
122
  step=32,
123
+ value=1024,
124
  )
125
 
126
  with gr.Row():
 
129
  minimum=0.0,
130
  maximum=10.0,
131
  step=0.1,
132
+ value=3.5,
133
  )
134
 
135
  num_inference_steps = gr.Slider(
 
137
  minimum=1,
138
  maximum=50,
139
  step=1,
140
+ value=30,
141
  )
142
 
143
  gr.Examples(examples=examples, inputs=[prompt])
pikigen/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from .pipeline import PikigenPipeline, PikigenPipelineOutput, APGConfig
2
+ from .model import DiT
3
+
4
+
5
+ __all__ = ["PikigenPipeline", "PikigenPipelineOutput", "APGConfig", "DiT"]
pikigen/model.py ADDED
@@ -0,0 +1,455 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DiT with cross attention
2
+
3
+ import math
4
+
5
+ import torch
6
+ import torch.nn.functional as F
7
+ import torch.utils.checkpoint
8
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
9
+ from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
10
+ from diffusers.models.modeling_utils import ModelMixin
11
+ from diffusers.utils.accelerate_utils import apply_forward_hook
12
+ from einops import rearrange
13
+ from peft import get_peft_model_state_dict, set_peft_model_state_dict
14
+ from torch import nn
15
+
16
+
17
+ def timestep_embedding(t, dim, max_period=10000):
18
+ half = dim // 2
19
+ freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(
20
+ device=t.device
21
+ )
22
+ args = t[:, None].float() * freqs[None]
23
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
24
+
25
+ return embedding
26
+
27
+
28
+ class RMSNorm(nn.Module):
29
+ def __init__(self, dim, eps=1e-6, trainable=False):
30
+ super().__init__()
31
+ self.eps = eps
32
+ if trainable:
33
+ self.weight = nn.Parameter(torch.ones(dim))
34
+ else:
35
+ self.weight = None
36
+
37
+ def forward(self, x):
38
+ x_dtype = x.dtype
39
+ x = x.float()
40
+ norm = torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
41
+ if self.weight is not None:
42
+ return (x * norm * self.weight).to(dtype=x_dtype)
43
+ else:
44
+ return (x * norm).to(dtype=x_dtype)
45
+
46
+
47
+ class QKNorm(nn.Module):
48
+ """Normalizing the query and the key independently, as Flux proposes"""
49
+
50
+ def __init__(self, dim, trainable=False):
51
+ super().__init__()
52
+ self.query_norm = RMSNorm(dim, trainable=trainable)
53
+ self.key_norm = RMSNorm(dim, trainable=trainable)
54
+
55
+ def forward(self, q, k):
56
+ q = self.query_norm(q)
57
+ k = self.key_norm(k)
58
+ return q, k
59
+
60
+
61
+ class Attention(nn.Module):
62
+ def __init__(
63
+ self,
64
+ dim,
65
+ num_heads=8,
66
+ qkv_bias=False,
67
+ is_self_attn=True,
68
+ cross_attn_input_size=None,
69
+ residual_v=False,
70
+ dynamic_softmax_temperature=False,
71
+ ):
72
+ super().__init__()
73
+ assert dim % num_heads == 0
74
+ self.num_heads = num_heads
75
+ self.head_dim = dim // num_heads
76
+ self.scale = self.head_dim**-0.5
77
+ self.is_self_attn = is_self_attn
78
+ self.residual_v = residual_v
79
+ self.dynamic_softmax_temperature = dynamic_softmax_temperature
80
+
81
+ if is_self_attn:
82
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
83
+ else:
84
+ self.q = nn.Linear(dim, dim, bias=qkv_bias)
85
+ self.context_kv = nn.Linear(cross_attn_input_size, dim * 2, bias=qkv_bias)
86
+
87
+ self.proj = nn.Linear(dim, dim, bias=False)
88
+
89
+ if residual_v:
90
+ self.lambda_param = nn.Parameter(torch.tensor(0.5).reshape(1))
91
+
92
+ self.qk_norm = QKNorm(self.head_dim)
93
+
94
+ def forward(self, x, context=None, v_0=None, rope=None):
95
+ if self.is_self_attn:
96
+ qkv = self.qkv(x)
97
+ qkv = rearrange(qkv, "b l (k h d) -> k b h l d", k=3, h=self.num_heads)
98
+ q, k, v = qkv.unbind(0)
99
+
100
+ if self.residual_v and v_0 is not None:
101
+ v = self.lambda_param * v + (1 - self.lambda_param) * v_0
102
+
103
+ if rope is not None:
104
+ # print(q.shape, rope[0].shape, rope[1].shape)
105
+ q = apply_rotary_emb(q, rope[0], rope[1])
106
+ k = apply_rotary_emb(k, rope[0], rope[1])
107
+
108
+ # https://arxiv.org/abs/2306.08645
109
+ # https://arxiv.org/abs/2410.01104
110
+ # ratioonale is that if tokens get larger, categorical distribution get more uniform
111
+ # so you want to enlargen entropy.
112
+
113
+ token_length = q.shape[2]
114
+ if self.dynamic_softmax_temperature:
115
+ ratio = math.sqrt(math.log(token_length) / math.log(1040.0)) # 1024 + 16
116
+ k = k * ratio
117
+ q, k = self.qk_norm(q, k)
118
+
119
+ else:
120
+ q = rearrange(self.q(x), "b l (h d) -> b h l d", h=self.num_heads)
121
+ kv = rearrange(
122
+ self.context_kv(context),
123
+ "b l (k h d) -> k b h l d",
124
+ k=2,
125
+ h=self.num_heads,
126
+ )
127
+ k, v = kv.unbind(0)
128
+ q, k = self.qk_norm(q, k)
129
+
130
+ x = F.scaled_dot_product_attention(q, k, v)
131
+ x = rearrange(x, "b h l d -> b l (h d)")
132
+ x = self.proj(x)
133
+ return x, v if self.is_self_attn else None
134
+
135
+
136
+ class DiTBlock(nn.Module):
137
+ def __init__(
138
+ self,
139
+ hidden_size,
140
+ cross_attn_input_size,
141
+ num_heads,
142
+ mlp_ratio=4.0,
143
+ qkv_bias=True,
144
+ residual_v=False,
145
+ dynamic_softmax_temperature=False,
146
+ ):
147
+ super().__init__()
148
+ self.hidden_size = hidden_size
149
+ self.norm1 = RMSNorm(hidden_size, trainable=qkv_bias)
150
+ self.self_attn = Attention(
151
+ hidden_size,
152
+ num_heads=num_heads,
153
+ qkv_bias=qkv_bias,
154
+ is_self_attn=True,
155
+ residual_v=residual_v,
156
+ dynamic_softmax_temperature=dynamic_softmax_temperature,
157
+ )
158
+
159
+ if cross_attn_input_size is not None:
160
+ self.norm2 = RMSNorm(hidden_size, trainable=qkv_bias)
161
+ self.cross_attn = Attention(
162
+ hidden_size,
163
+ num_heads=num_heads,
164
+ qkv_bias=qkv_bias,
165
+ is_self_attn=False,
166
+ cross_attn_input_size=cross_attn_input_size,
167
+ dynamic_softmax_temperature=dynamic_softmax_temperature,
168
+ )
169
+ else:
170
+ self.norm2 = None
171
+ self.cross_attn = None
172
+
173
+ self.norm3 = RMSNorm(hidden_size, trainable=qkv_bias)
174
+ mlp_hidden = int(hidden_size * mlp_ratio)
175
+ self.mlp = nn.Sequential(
176
+ nn.Linear(hidden_size, mlp_hidden),
177
+ nn.GELU(),
178
+ nn.Linear(mlp_hidden, hidden_size),
179
+ )
180
+
181
+ self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 9 * hidden_size, bias=True))
182
+
183
+ self.adaLN_modulation[-1].weight.data.zero_()
184
+ self.adaLN_modulation[-1].bias.data.zero_()
185
+
186
+ # @torch.compile(mode='reduce-overhead')
187
+ def forward(self, x, context, c, v_0=None, rope=None):
188
+ (
189
+ shift_sa,
190
+ scale_sa,
191
+ gate_sa,
192
+ shift_ca,
193
+ scale_ca,
194
+ gate_ca,
195
+ shift_mlp,
196
+ scale_mlp,
197
+ gate_mlp,
198
+ ) = self.adaLN_modulation(c).chunk(9, dim=1)
199
+
200
+ scale_sa = scale_sa[:, None, :]
201
+ scale_ca = scale_ca[:, None, :]
202
+ scale_mlp = scale_mlp[:, None, :]
203
+
204
+ shift_sa = shift_sa[:, None, :]
205
+ shift_ca = shift_ca[:, None, :]
206
+ shift_mlp = shift_mlp[:, None, :]
207
+
208
+ gate_sa = gate_sa[:, None, :]
209
+ gate_ca = gate_ca[:, None, :]
210
+ gate_mlp = gate_mlp[:, None, :]
211
+
212
+ norm_x = self.norm1(x.clone())
213
+ norm_x = norm_x * (1 + scale_sa) + shift_sa
214
+ attn_out, v = self.self_attn(norm_x, v_0=v_0, rope=rope)
215
+ x = x + attn_out * gate_sa
216
+
217
+ if self.norm2 is not None:
218
+ norm_x = self.norm2(x)
219
+ norm_x = norm_x * (1 + scale_ca) + shift_ca
220
+ x = x + self.cross_attn(norm_x, context)[0] * gate_ca
221
+
222
+ norm_x = self.norm3(x)
223
+ norm_x = norm_x * (1 + scale_mlp) + shift_mlp
224
+ x = x + self.mlp(norm_x) * gate_mlp
225
+
226
+ return x, v
227
+
228
+
229
+ class PatchEmbed(nn.Module):
230
+ def __init__(self, patch_size=16, in_channels=3, embed_dim=768):
231
+ super().__init__()
232
+ self.patch_proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
233
+ self.patch_size = patch_size
234
+
235
+ def forward(self, x):
236
+ B, C, H, W = x.shape
237
+ x = self.patch_proj(x)
238
+ x = rearrange(x, "b c h w -> b (h w) c")
239
+ return x
240
+
241
+
242
+ class TwoDimRotary(torch.nn.Module):
243
+ def __init__(self, dim, base=10000, h=256, w=256):
244
+ super().__init__()
245
+ self.inv_freq = torch.FloatTensor([1.0 / (base ** (i / dim)) for i in range(0, dim, 2)])
246
+ self.h = h
247
+ self.w = w
248
+
249
+ t_h = torch.arange(h, dtype=torch.float32)
250
+ t_w = torch.arange(w, dtype=torch.float32)
251
+
252
+ freqs_h = torch.outer(t_h, self.inv_freq).unsqueeze(1) # h, 1, d / 2
253
+ freqs_w = torch.outer(t_w, self.inv_freq).unsqueeze(0) # 1, w, d / 2
254
+ freqs_h = freqs_h.repeat(1, w, 1) # h, w, d / 2
255
+ freqs_w = freqs_w.repeat(h, 1, 1) # h, w, d / 2
256
+ freqs_hw = torch.cat([freqs_h, freqs_w], 2) # h, w, d
257
+
258
+ self.register_buffer("freqs_hw_cos", freqs_hw.cos())
259
+ self.register_buffer("freqs_hw_sin", freqs_hw.sin())
260
+
261
+ def forward(self, x, height_width=None, extend_with_register_tokens=0):
262
+ if height_width is not None:
263
+ this_h, this_w = height_width
264
+ else:
265
+ this_hw = x.shape[1]
266
+ this_h, this_w = int(this_hw**0.5), int(this_hw**0.5)
267
+
268
+ cos = self.freqs_hw_cos[0 : this_h, 0 : this_w]
269
+ sin = self.freqs_hw_sin[0 : this_h, 0 : this_w]
270
+
271
+ cos = cos.clone().reshape(this_h * this_w, -1)
272
+ sin = sin.clone().reshape(this_h * this_w, -1)
273
+
274
+ # append N of zero-attn tokens
275
+ if extend_with_register_tokens > 0:
276
+ cos = torch.cat(
277
+ [
278
+ torch.ones(extend_with_register_tokens, cos.shape[1]).to(cos.device),
279
+ cos,
280
+ ],
281
+ 0,
282
+ )
283
+ sin = torch.cat(
284
+ [
285
+ torch.zeros(extend_with_register_tokens, sin.shape[1]).to(sin.device),
286
+ sin,
287
+ ],
288
+ 0,
289
+ )
290
+
291
+ return cos[None, None, :, :], sin[None, None, :, :] # [1, 1, T + N, Attn-dim]
292
+
293
+
294
+ def apply_rotary_emb(x, cos, sin):
295
+ orig_dtype = x.dtype
296
+ x = x.to(dtype=torch.float32)
297
+ assert x.ndim == 4 # multihead attention
298
+ d = x.shape[3] // 2
299
+ x1 = x[..., :d]
300
+ x2 = x[..., d:]
301
+ y1 = x1 * cos + x2 * sin
302
+ y2 = x1 * (-sin) + x2 * cos
303
+ return torch.cat([y1, y2], 3).to(dtype=orig_dtype)
304
+
305
+
306
+ class DiT(ModelMixin, ConfigMixin, FromOriginalModelMixin, PeftAdapterMixin): # type: ignore[misc]
307
+ @register_to_config
308
+ def __init__(
309
+ self,
310
+ in_channels=4,
311
+ patch_size=2,
312
+ hidden_size=1152,
313
+ depth=28,
314
+ num_heads=16,
315
+ mlp_ratio=4.0,
316
+ cross_attn_input_size=128,
317
+ residual_v=False,
318
+ train_bias_and_rms=True,
319
+ use_rope=True,
320
+ gradient_checkpoint=False,
321
+ dynamic_softmax_temperature=False,
322
+ rope_base=10000,
323
+ ):
324
+ super().__init__()
325
+
326
+ self.patch_embed = PatchEmbed(patch_size, in_channels, hidden_size)
327
+
328
+ if use_rope:
329
+ self.rope = TwoDimRotary(hidden_size // (2 * num_heads), base=rope_base, h=512, w=512)
330
+ else:
331
+ self.positional_embedding = nn.Parameter(torch.zeros(1, 2048, hidden_size))
332
+
333
+ self.register_tokens = nn.Parameter(torch.randn(1, 16, hidden_size))
334
+
335
+ self.time_embed = nn.Sequential(
336
+ nn.Linear(hidden_size, 4 * hidden_size),
337
+ nn.SiLU(),
338
+ nn.Linear(4 * hidden_size, hidden_size),
339
+ )
340
+
341
+ self.blocks = nn.ModuleList(
342
+ [
343
+ DiTBlock(
344
+ hidden_size=hidden_size,
345
+ num_heads=num_heads,
346
+ mlp_ratio=mlp_ratio,
347
+ cross_attn_input_size=cross_attn_input_size,
348
+ residual_v=residual_v,
349
+ qkv_bias=train_bias_and_rms,
350
+ dynamic_softmax_temperature=dynamic_softmax_temperature,
351
+ )
352
+ for _ in range(depth)
353
+ ]
354
+ )
355
+
356
+ self.final_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True))
357
+
358
+ self.final_norm = RMSNorm(hidden_size, trainable=train_bias_and_rms)
359
+ self.final_proj = nn.Linear(hidden_size, patch_size * patch_size * in_channels)
360
+ nn.init.zeros_(self.final_modulation[-1].weight)
361
+ nn.init.zeros_(self.final_modulation[-1].bias)
362
+ nn.init.zeros_(self.final_proj.weight)
363
+ nn.init.zeros_(self.final_proj.bias)
364
+ self.paramstatus = {}
365
+ for n, p in self.named_parameters():
366
+ self.paramstatus[n] = {
367
+ "shape": p.shape,
368
+ "requires_grad": p.requires_grad,
369
+ }
370
+
371
+ def save_lora_weights(self, save_directory):
372
+ """Save LoRA weights to a file"""
373
+ lora_state_dict = get_peft_model_state_dict(self)
374
+ torch.save(lora_state_dict, f"{save_directory}/lora_weights.pt")
375
+
376
+ def load_lora_weights(self, load_directory):
377
+ """Load LoRA weights from a file"""
378
+ lora_state_dict = torch.load(f"{load_directory}/lora_weights.pt")
379
+ set_peft_model_state_dict(self, lora_state_dict)
380
+
381
+ @apply_forward_hook
382
+ def forward(self, x, context, timesteps):
383
+ b, c, h, w = x.shape
384
+ x = self.patch_embed(x) # b, T, d
385
+
386
+ x = torch.cat([self.register_tokens.repeat(b, 1, 1), x], 1) # b, T + N, d
387
+
388
+ if self.config.use_rope:
389
+ cos, sin = self.rope(
390
+ x,
391
+ extend_with_register_tokens=16,
392
+ height_width=(h // self.config.patch_size, w // self.config.patch_size),
393
+ )
394
+ else:
395
+ x = x + self.positional_embedding.repeat(b, 1, 1)[:, : x.shape[1], :]
396
+ cos, sin = None, None
397
+
398
+ t_emb = timestep_embedding(timesteps * 1000, self.config.hidden_size).to(x.device, dtype=x.dtype)
399
+ t_emb = self.time_embed(t_emb)
400
+
401
+ v_0 = None
402
+
403
+ for _idx, block in enumerate(self.blocks):
404
+ if self.config.gradient_checkpoint:
405
+ x, v = torch.utils.checkpoint.checkpoint(
406
+ block,
407
+ x,
408
+ context,
409
+ t_emb,
410
+ v_0,
411
+ (cos, sin),
412
+ use_reentrant=True,
413
+ )
414
+ else:
415
+ x, v = block(x, context, t_emb, v_0, (cos, sin))
416
+ if v_0 is None:
417
+ v_0 = v
418
+
419
+ x = x[:, 16:, :]
420
+ final_shift, final_scale = self.final_modulation(t_emb).chunk(2, dim=1)
421
+ x = self.final_norm(x)
422
+ x = x * (1 + final_scale[:, None, :]) + final_shift[:, None, :]
423
+ x = self.final_proj(x)
424
+
425
+ x = rearrange(
426
+ x,
427
+ "b (h w) (p1 p2 c) -> b c (h p1) (w p2)",
428
+ h=h // self.config.patch_size,
429
+ w=w // self.config.patch_size,
430
+ p1=self.config.patch_size,
431
+ p2=self.config.patch_size,
432
+ )
433
+ return x
434
+
435
+
436
+ if __name__ == "__main__":
437
+ model = DiT(
438
+ in_channels=4,
439
+ patch_size=2,
440
+ hidden_size=1152,
441
+ depth=28,
442
+ num_heads=16,
443
+ mlp_ratio=4.0,
444
+ cross_attn_input_size=128,
445
+ residual_v=False,
446
+ train_bias_and_rms=True,
447
+ use_rope=True,
448
+ ).cuda()
449
+ print(
450
+ model(
451
+ torch.randn(1, 4, 64, 64).cuda(),
452
+ torch.randn(1, 37, 128).cuda(),
453
+ torch.tensor([1.0]).cuda(),
454
+ )
455
+ )
pikigen/pipeline.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import math
3
+ from dataclasses import dataclass
4
+ from typing import Any, Dict, List, Optional, Tuple, Union
5
+
6
+ import numpy as np
7
+ import torch
8
+ from diffusers import AutoencoderKL, DiffusionPipeline
9
+ from diffusers.utils import BaseOutput
10
+ from diffusers.utils.torch_utils import randn_tensor
11
+ from PIL import Image
12
+ from torch import FloatTensor
13
+ from tqdm.auto import tqdm
14
+ from transformers import T5EncoderModel, T5TokenizerFast
15
+
16
+
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+
21
+ @dataclass
22
+ class APGConfig:
23
+ """APG (Augmented Parallel Guidance) configuration"""
24
+
25
+ enabled: bool = True
26
+ orthogonal_threshold: float = 0.03
27
+
28
+
29
+ @dataclass
30
+ class PikigenPipelineOutput(BaseOutput):
31
+ """
32
+ Output class for PikigenPipeline pipeline.
33
+ Args:
34
+ images (`List[PIL.Image.Image]` or `np.ndarray`)
35
+ List of denoised PIL images of length `batch_size` or numpy array of shape `(batch_size, height, width,
36
+ num_channels)`. PIL images or numpy array present the denoised images of the diffusion pipeline.
37
+ """
38
+
39
+ images: Union[List[Image.Image], np.ndarray]
40
+
41
+
42
+ class PikigenPipeline(DiffusionPipeline):
43
+ r"""
44
+ Pipeline for text-to-image generation using Pikigen model.
45
+ This model inherits from [`DiffusionPipeline`].
46
+ """
47
+
48
+ model_cpu_offload_seq = "text_encoder->dit_model->vae"
49
+
50
+ dit_model: torch.nn.Module
51
+ vae: AutoencoderKL
52
+ text_encoder: T5EncoderModel
53
+ tokenizer: T5TokenizerFast
54
+ _progress_bar_config: Dict[str, Any]
55
+
56
+ def __init__(
57
+ self, dit_model: torch.nn.Module, vae: AutoencoderKL, text_encoder: T5EncoderModel, tokenizer: T5TokenizerFast
58
+ ):
59
+ super().__init__()
60
+ # Register all modules for the pipeline
61
+ # Access DiffusionPipeline's register_modules directly to avoid mypy error
62
+ DiffusionPipeline.register_modules(
63
+ self, dit_model=dit_model, vae=vae, text_encoder=text_encoder, tokenizer=tokenizer
64
+ )
65
+
66
+ # Move models to channels last for better performance
67
+ # AutoencoderKL inherits from torch.nn.Module which has these methods
68
+ if hasattr(self.vae, "to"):
69
+ self.vae.to(memory_format=torch.channels_last)
70
+ if hasattr(self.vae, "requires_grad_"):
71
+ self.vae.requires_grad_(False)
72
+ if hasattr(self.text_encoder, "requires_grad_"):
73
+ self.text_encoder.requires_grad_(False)
74
+
75
+ # Constants
76
+ self.vae_scale_factor = 8
77
+ self.return_index = -8 # T5 hidden state index to use
78
+
79
+ def enable_vae_slicing(self):
80
+ """Enable VAE slicing for memory efficiency."""
81
+ if hasattr(self.vae, "enable_slicing"):
82
+ self.vae.enable_slicing()
83
+
84
+ def enable_vae_tiling(self):
85
+ """Enable VAE tiling for memory efficiency."""
86
+ if hasattr(self.vae, "enable_tiling"):
87
+ self.vae.enable_tiling()
88
+
89
+ def set_progress_bar_config(self, **kwargs):
90
+ """Set progress bar configuration."""
91
+ self._progress_bar_config = kwargs
92
+
93
+ def progress_bar(self, iterable=None, **kwargs):
94
+ """Create progress bar for iterations."""
95
+ self._progress_bar_config = getattr(self, "_progress_bar_config", None) or {}
96
+ config = {**self._progress_bar_config, **kwargs}
97
+ return tqdm(iterable, **config)
98
+
99
+ def encode_prompt(
100
+ self,
101
+ prompt: Union[str, List[str]],
102
+ negative_prompt: Optional[Union[str, List[str]]] = None,
103
+ device: Optional[torch.device] = None,
104
+ dtype: Optional[torch.dtype] = None,
105
+ max_sequence_length: int = 512,
106
+ return_index: int = -8,
107
+ ) -> Tuple[FloatTensor, FloatTensor]:
108
+ """Encodes the prompt and negative prompt."""
109
+ if isinstance(prompt, str):
110
+ prompt = [prompt]
111
+ device = device or self.text_encoder.device
112
+ # Text encoder forward pass
113
+ text_inputs = self.tokenizer(
114
+ prompt,
115
+ padding="max_length",
116
+ max_length=max_sequence_length,
117
+ truncation=True,
118
+ return_tensors="pt",
119
+ )
120
+ text_input_ids = text_inputs.input_ids.to(device)
121
+ prompt_embeds = self.text_encoder(text_input_ids, return_dict=True, output_hidden_states=True)
122
+ prompt_embeds_tensor = prompt_embeds.hidden_states[return_index]
123
+ if return_index != -1:
124
+ prompt_embeds_tensor = self.text_encoder.encoder.final_layer_norm(prompt_embeds_tensor)
125
+ prompt_embeds_tensor = self.text_encoder.encoder.dropout(prompt_embeds_tensor)
126
+
127
+ dtype = dtype or next(self.text_encoder.parameters()).dtype
128
+ prompt_embeds_tensor = prompt_embeds_tensor.to(dtype=dtype, device=device)
129
+
130
+ # Handle negative prompts
131
+ if negative_prompt is None:
132
+ negative_embeds = torch.zeros_like(prompt_embeds_tensor)
133
+ else:
134
+ if isinstance(negative_prompt, str):
135
+ negative_prompt = [negative_prompt]
136
+ negative_result = self.encode_prompt(
137
+ prompt=negative_prompt, device=device, dtype=dtype, return_index=return_index
138
+ )
139
+ negative_embeds = negative_result[0]
140
+
141
+ # Explicitly cast both tensors to FloatTensor for mypy
142
+ from typing import cast
143
+
144
+ prompt_tensor = cast(FloatTensor, prompt_embeds_tensor.to(dtype=dtype))
145
+ negative_tensor = cast(FloatTensor, negative_embeds.to(dtype=dtype))
146
+ return (prompt_tensor, negative_tensor)
147
+
148
+ def to(self, torch_device=None, torch_dtype=None, silence_dtype_warnings=False):
149
+ """Move pipeline components to specified device and dtype."""
150
+ if hasattr(self, "vae"):
151
+ self.vae.to(device=torch_device, dtype=torch_dtype)
152
+ if hasattr(self, "text_encoder"):
153
+ self.text_encoder.to(device=torch_device, dtype=torch_dtype)
154
+ if hasattr(self, "dit_model"):
155
+ self.dit_model.to(device=torch_device, dtype=torch_dtype)
156
+ return self
157
+
158
+ @torch.no_grad()
159
+ def __call__(
160
+ self,
161
+ prompt: Union[str, List[str]],
162
+ height: Optional[int] = 1024,
163
+ width: Optional[int] = 1024,
164
+ num_inference_steps: int = 30,
165
+ guidance_scale: float = 3.0,
166
+ negative_prompt: Optional[Union[str, List[str]]] = None,
167
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
168
+ dtype: Optional[torch.dtype] = None,
169
+ alpha: Optional[float] = None,
170
+ apg_config: Optional[APGConfig] = None,
171
+ **kwargs,
172
+ ):
173
+ """Generate images from text prompt."""
174
+ batch_size = 1 # TODO: Make this method support batch generation
175
+ # Ensure height and width are not None for calculation
176
+ if height is None:
177
+ height = 1024
178
+ if width is None:
179
+ width = 1024
180
+
181
+ dtype = dtype or next(self.dit_model.parameters()).dtype
182
+ apg_config = apg_config or APGConfig()
183
+
184
+ device = self._execution_device
185
+
186
+ # 2. Encode prompts
187
+ prompt_embeds, negative_embeds = self.encode_prompt(
188
+ prompt=prompt, negative_prompt=negative_prompt, device=self.text_encoder.device, dtype=dtype
189
+ )
190
+
191
+ # 3. Initialize latents
192
+ latent_height = height // self.vae_scale_factor
193
+ latent_width = width // self.vae_scale_factor
194
+
195
+ if isinstance(generator, list):
196
+ if len(generator) != batch_size:
197
+ raise ValueError(f"Got {len(generator)} generators for {batch_size} samples")
198
+
199
+ latents = randn_tensor((batch_size, 16, latent_height, latent_width), generator=generator, device=device, dtype=dtype)
200
+ acc_latents = latents.clone()
201
+
202
+ # 4. Calculate alpha if not provided
203
+ if alpha is None:
204
+ image_token_size = latent_height * latent_width
205
+ alpha = 2 * math.sqrt(image_token_size / (64 * 64))
206
+
207
+ # 6. Sampling loop
208
+ self.dit_model.eval()
209
+
210
+ # Check if guidance is needed
211
+ do_classifier_free_guidance = guidance_scale >= 1.0
212
+
213
+ for i in self.progress_bar(range(num_inference_steps, 0, -1)):
214
+ # Calculate timesteps
215
+ t = i / num_inference_steps
216
+ t_next = (i - 1) / num_inference_steps
217
+ # Scale timesteps according to alpha
218
+ t = t * alpha / (1 + (alpha - 1) * t)
219
+ t_next = t_next * alpha / (1 + (alpha - 1) * t_next)
220
+ dt = t - t_next
221
+
222
+ # Create tensor with proper device
223
+ t_tensor = torch.tensor([t] * batch_size, device=device, dtype=dtype)
224
+
225
+ if do_classifier_free_guidance:
226
+ # Duplicate latents for both conditional and unconditional inputs
227
+ latents_input = torch.cat([latents] * 2)
228
+ # Concatenate negative and positive prompt embeddings
229
+ context_input = torch.cat([negative_embeds, prompt_embeds])
230
+ # Duplicate timesteps for the batch
231
+ t_input = torch.cat([t_tensor] * 2)
232
+
233
+ # Get model predictions in a single pass
234
+ model_outputs = self.dit_model(latents_input, context_input, t_input)
235
+
236
+ # Split outputs back into unconditional and conditional predictions
237
+ uncond_output, cond_output = model_outputs.chunk(2)
238
+
239
+ if apg_config.enabled:
240
+ # Augmented Parallel Guidance
241
+ dy = cond_output
242
+ dd = cond_output - uncond_output
243
+ # Find parallel direction
244
+ parallel_direction = (dy * dd).sum() / (dy * dy).sum() * dy
245
+ orthogonal_direction = dd - parallel_direction
246
+ # Scale orthogonal component
247
+ orthogonal_std = orthogonal_direction.std()
248
+ orthogonal_scale = min(1, apg_config.orthogonal_threshold / orthogonal_std)
249
+ orthogonal_direction = orthogonal_direction * orthogonal_scale
250
+ model_output = dy + (guidance_scale - 1) * orthogonal_direction
251
+ else:
252
+ # Standard classifier-free guidance
253
+ model_output = uncond_output + guidance_scale * (cond_output - uncond_output)
254
+ else:
255
+ # If no guidance needed, just run the model normally
256
+ model_output = self.dit_model(latents, prompt_embeds, t_tensor)
257
+
258
+ # Update latents
259
+ acc_latents = acc_latents + dt * model_output.to(device)
260
+ latents = acc_latents.clone()
261
+
262
+ # 7. Decode latents
263
+ # These checks handle the case where mypy doesn't recognize these attributes
264
+ scaling_factor = getattr(self.vae.config, "scaling_factor", 0.18215) if hasattr(self.vae, "config") else 0.18215
265
+ shift_factor = getattr(self.vae.config, "shift_factor", 0) if hasattr(self.vae, "config") else 0
266
+
267
+ latents = latents / scaling_factor + shift_factor
268
+
269
+ vae_dtype = self.vae.dtype if hasattr(self.vae, "dtype") else dtype
270
+ decoded_images = self.vae.decode(latents.to(vae_dtype)).sample if hasattr(self.vae, "decode") else latents
271
+
272
+ # Offload all models
273
+ try:
274
+ self.maybe_free_model_hooks()
275
+ except AttributeError as e:
276
+ if "OptimizedModule" in str(e):
277
+ import warnings
278
+ warnings.warn(
279
+ "Encountered 'OptimizedModule' error when offloading models. "
280
+ "This issue might be fixed in the future by: "
281
+ "https://github.com/huggingface/diffusers/pull/10730"
282
+ )
283
+ else:
284
+ raise
285
+
286
+ # 8. Post-process images
287
+ images = (decoded_images / 2 + 0.5).clamp(0, 1)
288
+ # Convert to PIL Images
289
+ images = (images * 255).round().clamp(0, 255).to(torch.uint8).cpu()
290
+ pil_images = [Image.fromarray(img.permute(1, 2, 0).numpy()) for img in images]
291
+
292
+ return PikigenPipelineOutput(
293
+ images=pil_images,
294
+ )
295
+
296
+
requirements.txt CHANGED
@@ -1,6 +1,9 @@
1
- accelerate
2
  diffusers
3
- invisible_watermark
 
 
 
 
 
4
  torch
5
- transformers
6
- xformers
 
 
1
  diffusers
2
+ einops
3
+ jsonargparse
4
+ peft
5
+ protobuf
6
+ rich
7
+ sentencepiece
8
  torch
9
+ transformers