adityapanda2608112 commited on
Commit
b64dfca
·
verified ·
1 Parent(s): f0aad06

Upload scheduler/pipeline_panda_image.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scheduler/pipeline_panda_image.py +440 -0
scheduler/pipeline_panda_image.py ADDED
@@ -0,0 +1,440 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """MOSSImage modeling and text-to-image pipeline (no Motor/TorchTitan imports).
2
+
3
+ Dependencies: torch>=2.9, diffusers>=0.38, transformers>=5.3, safetensors,
4
+ accelerate, Pillow. Copy this file anywhere and import it normally.
5
+
6
+ import torch
7
+ # Import MOSSImagePipeline from this file for component-level loading.
8
+ pipe = MOSSImagePipeline.from_components_pretrained(
9
+ transformer_path="exported_transformer", # save_pretrained directory
10
+ text_encoder_path="Qwen/Qwen3.5-9B",
11
+ vae_path="black-forest-labs/FLUX.2-klein-4B",
12
+ ).to("cuda")
13
+ pipe("A cat", generator=torch.Generator("cuda").manual_seed(42)).images[0].save("cat.png")
14
+
15
+ Default guidance uses CFG 3 and skips block 22 only in the negative branch
16
+ (zero-based main DiT block indices; two forwards per sampling step):
17
+ pipe("A cat", guidance_scale=3.0, uncond_skip_layers=[22])
18
+ pipe("A cat", uncond_skip_layers=[]) # disable negative-branch skipping
19
+ Optional additional positive-branch SLG adds a third forward:
20
+ pipe("A cat", slg_layers=[24], slg_scale=3.0)
21
+ The additional SLG layer/scale above illustrates the API, not a quality-tuned setting.
22
+
23
+ For a consolidated training state dict, create MOSSImageTransformer and
24
+ call load_training_state_dict(state), then save_pretrained("exported_transformer").
25
+ Select raw or EMA weights explicitly before calling it; distributed checkpoint
26
+ shards/optimizer states are not model state dicts. Defaults match the finalized dense MOSSImage model,
27
+ not MoE, CFG-distilled, video, or reference-image variants. Prompt strings are
28
+ already-rendered captions (dataset-specific quality/domain tags are not added).
29
+
30
+ First-release defaults: bf16 DiT/text-encoder weights, fp32 RoPE frequencies
31
+ and phase/sin/cos calculation, then RoPE cast to the video activation dtype.
32
+ Initial Gaussian noise is sampled directly in fp32, including with bf16 weights.
33
+ CFG and Euler latent updates use fp32; VAE decoding defaults to fp32. Scheduler
34
+ shift defaults to 5.0. Exact numerical parity with the original fp32-master
35
+ inference pipeline is not a release requirement.
36
+ """
37
+ from __future__ import annotations
38
+
39
+ import math
40
+ from pathlib import Path
41
+
42
+ import torch
43
+ from torch import nn
44
+ from torch.nn import functional as F
45
+ from diffusers import AutoencoderKLFlux2, DiffusionPipeline, FlowMatchEulerDiscreteScheduler
46
+ from diffusers.schedulers.scheduling_utils import SchedulerMixin # Required by custom-component discovery.
47
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
48
+ from diffusers.image_processor import VaeImageProcessor
49
+ from diffusers.models.modeling_utils import ModelMixin
50
+ from diffusers.models.modeling_outputs import Transformer2DModelOutput
51
+ from diffusers.pipelines.pipeline_utils import ImagePipelineOutput
52
+ from diffusers.utils.torch_utils import randn_tensor
53
+ from transformers import AutoModel, AutoTokenizer
54
+
55
+
56
+ class _RMSNorm(nn.Module):
57
+ def __init__(self, dim):
58
+ super().__init__()
59
+ self.weight = nn.Parameter(torch.ones(dim))
60
+
61
+ def forward(self, x):
62
+ y = x.float() * torch.rsqrt(x.float().square().mean(-1, keepdim=True) + 1e-6)
63
+ return y.to(x.dtype) * self.weight
64
+
65
+
66
+ def _situ(hidden, gate):
67
+ return (4.0 * torch.tanh(gate / 4.0) * torch.sigmoid(gate)) * (25.0 * torch.tanh(hidden / 25.0))
68
+
69
+
70
+ def _validate_skip_layers(layers, depth, name='skip_layers'):
71
+ layers = () if layers is None else tuple(layers)
72
+ if any(type(index) is not int or not 0 <= index < depth for index in layers):
73
+ raise ValueError(f'{name} must contain integer block indices in [0, {depth}).')
74
+ return frozenset(layers)
75
+
76
+
77
+ def _rotate(x, rope):
78
+ sin, cos = rope.chunk(2, -1)
79
+ sin = torch.cat((sin, sin), -1).unsqueeze(-2)
80
+ cos = torch.cat((cos, cos), -1).unsqueeze(-2)
81
+ a, b = x.chunk(2, -1)
82
+ return x * cos + torch.cat((-b, a), -1) * sin
83
+
84
+
85
+ def _attention(q, k, v, rope, heads):
86
+ shape = (*q.shape[:2], heads, q.shape[-1] // heads)
87
+ q = _rotate(q.reshape(shape), rope).transpose(1, 2)
88
+ k = _rotate(k.reshape(shape), rope).transpose(1, 2)
89
+ v = v.reshape(shape).transpose(1, 2)
90
+ return F.scaled_dot_product_attention(q.to(v.dtype), k.to(v.dtype), v).transpose(1, 2).flatten(2)
91
+
92
+
93
+ class _TextBlock(nn.Module):
94
+ def __init__(self, dim, ffn_dim, heads):
95
+ super().__init__()
96
+ self.heads = heads
97
+ self.norm1, self.norm2 = _RMSNorm(dim), _RMSNorm(dim)
98
+ self.q_norm, self.k_norm = _RMSNorm(dim // heads), _RMSNorm(dim // heads)
99
+ self.qkv = nn.Linear(dim, 3 * dim)
100
+ self.proj = nn.Linear(dim, dim)
101
+ self.ffn_gate, self.ffn_up = nn.Linear(dim, ffn_dim), nn.Linear(dim, ffn_dim)
102
+ self.ffn_down = nn.Linear(ffn_dim, dim)
103
+
104
+ def forward(self, x, rope):
105
+ q, k, v = self.qkv(self.norm1(x)).chunk(3, -1)
106
+ q = self.q_norm(q.unflatten(-1, (self.heads, -1))).flatten(2)
107
+ k = self.k_norm(k.unflatten(-1, (self.heads, -1))).flatten(2)
108
+ x = x + self.proj(_attention(q, k, v, rope, self.heads))
109
+ y = self.norm2(x)
110
+ return x + self.ffn_down(_situ(self.ffn_up(y), self.ffn_gate(y)))
111
+
112
+
113
+ class _TextProjection(nn.Module):
114
+ def __init__(self, text_dim, dim, ffn_dim, heads):
115
+ super().__init__()
116
+ self.proj = nn.Linear(text_dim, dim)
117
+ self.blocks = nn.ModuleList([_TextBlock(dim, ffn_dim, heads) for _ in range(2)])
118
+
119
+ def forward(self, x, rope):
120
+ x = self.proj(x.to(self.proj.weight.dtype))
121
+ for block in self.blocks:
122
+ x = block(x, rope)
123
+ return x
124
+
125
+
126
+ class _Block(nn.Module):
127
+ def __init__(self, dim, ffn_dim, heads):
128
+ super().__init__()
129
+ self.heads = heads
130
+ self.norm1, self.norm2 = _RMSNorm(dim), _RMSNorm(dim)
131
+ self.q_norm, self.k_norm = _RMSNorm(dim // heads), _RMSNorm(dim // heads)
132
+ self.proj = nn.ModuleDict({
133
+ name: nn.Linear(dim, dim, bias=False) for name in ('q', 'k', 'v', 'o')
134
+ })
135
+ self.proj['ffn_up_gate'] = nn.Linear(dim, 2 * ffn_dim, bias=False)
136
+ self.proj['ffn_down'] = nn.Linear(ffn_dim, dim, bias=False)
137
+
138
+ def forward(self, x, rope, modulation):
139
+ shift_a, scale_a, gate_a, shift_f, scale_f, gate_f = modulation.unbind(1)
140
+ y = self.norm1(x) * (1 + scale_a[:, None]) + shift_a[:, None]
141
+ dtype = self.proj['q'].weight.dtype
142
+ y = y.to(dtype)
143
+ q = self.q_norm(self.proj['q'](y).unflatten(-1, (self.heads, -1))).flatten(2)
144
+ k = self.k_norm(self.proj['k'](y).unflatten(-1, (self.heads, -1))).flatten(2)
145
+ x = x + self.proj['o'](_attention(q, k, self.proj['v'](y), rope, self.heads)) * gate_a[:, None]
146
+ y = self.norm2(x) * (1 + scale_f[:, None]) + shift_f[:, None]
147
+ hidden, gate = self.proj['ffn_up_gate'](y.to(dtype)).chunk(2, -1)
148
+ return x + self.proj['ffn_down'](_situ(hidden, gate)) * gate_f[:, None]
149
+
150
+
151
+ class _RoPE(nn.Module):
152
+ def __init__(self, head_dim, base):
153
+ super().__init__()
154
+ self.num_bands = head_dim // 8
155
+ self.base = base
156
+ self.register_buffer('bands', self._default_bands(torch.device('cpu')))
157
+
158
+ def _default_bands(self, device):
159
+ # Match training's CPU fp32 construction, including under meta init.
160
+ exponent = torch.arange(self.num_bands, device='cpu', dtype=torch.float32) / self.num_bands
161
+ return (1 / (self.base ** exponent)).to(device)
162
+
163
+ def _apply(self, fn, recurse=True):
164
+ super()._apply(fn, recurse=recurse)
165
+ # .float() cannot recover frequencies already rounded by .to(bf16).
166
+ self.bands = self._default_bands(self.bands.device)
167
+ return self
168
+
169
+ def _load_from_state_dict(self, *args, **kwargs):
170
+ super()._load_from_state_dict(*args, **kwargs)
171
+ # Frequencies are derived constants; retain the key for checkpoint compatibility.
172
+ self.bands = self._default_bands(self.bands.device)
173
+
174
+ def forward(self, height, width, text_length, device):
175
+ # Diffusers/Accelerate can install tensors directly, bypassing load hooks.
176
+ if self.bands.dtype != torch.float32:
177
+ self.bands = self._default_bands(device)
178
+ # Coordinates: (r, f, h, w); sequence order is image followed by text.
179
+ h, w = torch.meshgrid(torch.arange(height, device=device), torch.arange(width, device=device), indexing='ij')
180
+ image = torch.stack((torch.zeros_like(h), torch.full_like(h, text_length), h, w), -1).flatten(0, 1).float()
181
+ image[:, 2] -= (height - 1) / 2
182
+ image[:, 3] -= (width - 1) / 2
183
+ text = torch.zeros(text_length, 4, device=device, dtype=torch.float32)
184
+ text[:, 1] = torch.arange(text_length, device=device)
185
+ phase = torch.cat((image, text), 0).unsqueeze(-1) * self.bands
186
+ return torch.cat((phase.sin(), phase.cos()), -2).flatten(-2).unsqueeze(0)
187
+
188
+
189
+ class MOSSImageTransformer(ModelMixin, ConfigMixin):
190
+ """MOSSImage DiT with training-compatible state-dict names and SDPA attention.
191
+
192
+ Each sample is evaluated at its true text length, including text refinement;
193
+ padded tokens cannot influence either text or joint attention.
194
+ """
195
+ @register_to_config
196
+ def __init__(self, dim=3072, ffn_dim=8192, num_heads=24, num_layers=42,
197
+ text_dim=4096, freq_dim=256, latent_channels=128, rope_base=10000.0):
198
+ super().__init__()
199
+ if dim % num_heads or (dim // num_heads) % 8 or freq_dim % 2:
200
+ raise ValueError('Require dim divisible by heads, head_dim divisible by 8, and even freq_dim.')
201
+ self.video_embedder = nn.Linear(latent_channels, dim)
202
+ self.text_embedder = _TextProjection(text_dim, dim, ffn_dim, num_heads)
203
+ self.rope = _RoPE(dim // num_heads, rope_base)
204
+ self.time_embedding = nn.Sequential(nn.Linear(freq_dim, dim), nn.SiLU(), nn.Linear(dim, dim))
205
+ self.shared_block_modulation = nn.Linear(dim, 6 * dim)
206
+ self.layers = nn.ModuleList([_Block(dim, ffn_dim, num_heads) for _ in range(num_layers)])
207
+ self.final_norm_video = _RMSNorm(dim)
208
+ self.final_linear_video = nn.Linear(dim, latent_channels, bias=False)
209
+ self.video_head_modulation = nn.Linear(dim, 2 * dim)
210
+
211
+ def load_training_state_dict(self, state_dict, *, prefix=''):
212
+ """Load a consolidated raw/EMA model mapping, strictly; no silent key drops."""
213
+ if prefix:
214
+ if any(not key.startswith(prefix) for key in state_dict):
215
+ raise ValueError('All keys must start with the explicit prefix.')
216
+ state_dict = {key[len(prefix):]: value for key, value in state_dict.items()}
217
+ return self.load_state_dict(state_dict, strict=True)
218
+
219
+ def forward(self, hidden_states, timestep, encoder_hidden_states,
220
+ encoder_attention_mask=None, return_dict=True, skip_layers=None):
221
+ skip_layers = _validate_skip_layers(skip_layers, len(self.layers))
222
+ if hidden_states.ndim != 4 or hidden_states.shape[1] != self.config.latent_channels:
223
+ raise ValueError('hidden_states must be [B, latent_channels, H, W].')
224
+ batch, _, height, width = hidden_states.shape
225
+ if encoder_hidden_states.ndim != 3 or encoder_hidden_states.shape[0] != batch:
226
+ raise ValueError('encoder_hidden_states must be [B, S, text_dim].')
227
+ mask = encoder_attention_mask
228
+ if mask is None:
229
+ mask = torch.ones(encoder_hidden_states.shape[:2], dtype=torch.bool, device=hidden_states.device)
230
+ if mask.shape != encoder_hidden_states.shape[:2] or not torch.all((mask == 0) | (mask == 1)):
231
+ raise ValueError('encoder_attention_mask must be a binary [B, S] mask.')
232
+ times = torch.as_tensor(timestep, device=hidden_states.device, dtype=torch.float32).reshape(-1)
233
+ times = times.expand(batch)
234
+ # Training computes the sinusoid in float64 and feeds float32 into its MLP.
235
+ half = self.config.freq_dim // 2
236
+ freq = 10000 ** (-torch.arange(half, device=times.device, dtype=torch.float64) / half)
237
+ phase = times.double()[:, None] * freq
238
+ embedding = torch.cat((phase.cos(), phase.sin()), -1).float()
239
+ time = self.time_embedding(embedding.to(self.time_embedding[0].weight.dtype)).float()
240
+ mod = self.shared_block_modulation(time.to(self.shared_block_modulation.weight.dtype)).view(batch, 6, -1)
241
+ head = self.video_head_modulation(time.to(self.video_head_modulation.weight.dtype)).view(batch, 2, -1)
242
+ outputs = []
243
+ for index in range(batch):
244
+ context = encoder_hidden_states[index:index + 1, mask[index].bool()]
245
+ if context.shape[1] == 0:
246
+ raise ValueError('Each sample needs at least one valid text token.')
247
+ video = hidden_states[index:index + 1].flatten(2).transpose(1, 2)
248
+ video = self.video_embedder(video.to(self.video_embedder.weight.dtype).contiguous())
249
+ # Match the reference activation dtype under fp32 weights + autocast.
250
+ rope = self.rope(height, width, context.shape[1], hidden_states.device).to(video.dtype)
251
+ text = self.text_embedder(context, rope[:, height * width:])
252
+ x = torch.cat((video, text), 1)
253
+ for layer_index, layer in enumerate(self.layers):
254
+ if layer_index not in skip_layers:
255
+ x = layer(x, rope, mod[index:index + 1])
256
+ x = self.final_norm_video(x[:, :height * width].to(self.final_norm_video.weight.dtype))
257
+ x = x * (1 + head[index:index + 1, 1, None]) + head[index:index + 1, 0, None]
258
+ x = self.final_linear_video(x.to(self.final_linear_video.weight.dtype))
259
+ outputs.append(x.transpose(1, 2).reshape(1, -1, height, width))
260
+ sample = torch.cat(outputs)
261
+ return Transformer2DModelOutput(sample=sample) if return_dict else (sample,)
262
+
263
+
264
+ class MOSSImageScheduler(FlowMatchEulerDiscreteScheduler):
265
+ """Euler integration using the training project's V2, nearest-grid schedule."""
266
+ @register_to_config
267
+ def __init__(self, num_train_timesteps=1000, shift=5.0, training_shift=1.0):
268
+ super().__init__(num_train_timesteps=num_train_timesteps, shift=1.0)
269
+ self.register_to_config(shift=shift, training_shift=training_shift)
270
+
271
+ def set_timesteps(self, num_inference_steps=50, device=None):
272
+ if num_inference_steps < 1 or self.config.shift <= 0 or self.config.training_shift <= 0:
273
+ raise ValueError('Steps and shifts must be positive.')
274
+ total = self.config.num_train_timesteps
275
+ def grid(count, shift):
276
+ lower = shift / (total + shift - 1)
277
+ values = torch.linspace(1, lower, count)
278
+ return shift * values / (1 + (shift - 1) * values)
279
+ sigmas = grid(num_inference_steps, self.config.shift)
280
+ training = grid(total, self.config.training_shift).flip(0)
281
+ upper = torch.searchsorted(training, sigmas).clamp(max=total - 1)
282
+ lower = (upper - 1).clamp(min=0)
283
+ nearest = torch.where((sigmas - training[lower]).abs() <= (training[upper] - sigmas).abs(), lower, upper)
284
+ sigmas = torch.unique_consecutive(training[nearest])
285
+ # Our sigmas have already been shifted and snapped. Avoid a second shift.
286
+ self._shift = 1.0
287
+ super().set_timesteps(device=device, sigmas=sigmas.tolist())
288
+
289
+
290
+ class PandaImagePipeline(DiffusionPipeline):
291
+ model_cpu_offload_seq = 'text_encoder->transformer->vae'
292
+ _optional_components = ['text_encoder', 'tokenizer', 'vae']
293
+
294
+ def __init__(self, transformer: MOSSImageTransformer,
295
+ scheduler: MOSSImageScheduler, text_encoder=None, tokenizer=None, vae=None):
296
+ super().__init__()
297
+ self.register_modules(transformer=transformer, scheduler=scheduler,
298
+ text_encoder=text_encoder, tokenizer=tokenizer, vae=vae)
299
+ self.image_processor = VaeImageProcessor(vae_scale_factor=16)
300
+
301
+ @classmethod
302
+ def from_components_pretrained(cls, transformer_path, text_encoder_path, vae_path,
303
+ torch_dtype=torch.bfloat16, vae_dtype=torch.float32,
304
+ local_files_only=False):
305
+ common = dict(local_files_only=local_files_only)
306
+ transformer = MOSSImageTransformer.from_pretrained(transformer_path, torch_dtype=torch_dtype, **common)
307
+ tokenizer = AutoTokenizer.from_pretrained(text_encoder_path, **common)
308
+ text_encoder = AutoModel.from_pretrained(text_encoder_path, dtype=torch_dtype, **common).eval()
309
+ subfolder = None if (Path(vae_path) / 'config.json').is_file() else 'vae'
310
+ vae = AutoencoderKLFlux2.from_pretrained(vae_path, subfolder=subfolder, torch_dtype=vae_dtype, **common).eval()
311
+ return cls(transformer.eval(), MOSSImageScheduler(), text_encoder, tokenizer, vae)
312
+
313
+ @torch.no_grad()
314
+ def encode_prompt(self, prompt, max_sequence_length=4096):
315
+ if self.text_encoder is None or self.tokenizer is None:
316
+ raise ValueError('Text encoder/tokenizer required for string prompts.')
317
+ prompts = [prompt] if isinstance(prompt, str) else list(prompt)
318
+ if not prompts or not all(isinstance(p, str) for p in prompts):
319
+ raise ValueError('prompt must be a string or a nonempty list of strings.')
320
+ rows = []
321
+ # Unpadded individual forwards also avoid padding effects in Qwen GDN.
322
+ for value in prompts:
323
+ formatted = self.tokenizer.apply_chat_template(
324
+ [{'role': 'user', 'content': value}], tokenize=False,
325
+ add_generation_prompt=True, enable_thinking=True)
326
+ inputs = self.tokenizer(formatted, return_tensors='pt', truncation=True,
327
+ max_length=max_sequence_length).to(self._execution_device)
328
+ output = self.text_encoder(**inputs, use_cache=False, return_dict=True)
329
+ rows.append(output.last_hidden_state[0])
330
+ length = max(row.shape[0] for row in rows)
331
+ embeds = rows[0].new_zeros(len(rows), length, rows[0].shape[-1])
332
+ mask = torch.zeros(len(rows), length, device=embeds.device, dtype=torch.bool)
333
+ for index, row in enumerate(rows):
334
+ embeds[index, :row.shape[0]] = row
335
+ mask[index, :row.shape[0]] = True
336
+ return embeds, mask
337
+
338
+ @torch.no_grad()
339
+ def __call__(self, prompt=None, *, height=1024, width=1024, num_inference_steps=50,
340
+ guidance_scale=3.0, negative_prompt='', num_images_per_prompt=1,
341
+ generator=None, latents=None, prompt_embeds=None, prompt_attention_mask=None,
342
+ negative_prompt_embeds=None, negative_prompt_attention_mask=None,
343
+ max_sequence_length=4096, output_type='pil', return_dict=True,
344
+ uncond_skip_layers=(22,), slg_layers=None, slg_scale=0.0,
345
+ slg_start=0.0, slg_stop=1.0):
346
+ """Generate images with optional full-block skipping (zero-based indices).
347
+
348
+ uncond_skip_layers defaults to (22,) and replaces CFG's negative-prompt
349
+ prediction with a skipped-block prediction, retaining two forwards per
350
+ step. Pass None or an empty sequence to disable skipping. slg_layers
351
+ adds a skipped positive-prompt forward and the fp32 correction
352
+ slg_scale * (cond - cond_skip) to CFG. With guidance_scale=1, active
353
+ SLG uses cond_skip + slg_scale * (cond - cond_skip), matching Diffusers'
354
+ default SkipLayerGuidance formulation, with two forwards and no negative
355
+ branch. Both options can combine. slg_scale=1 then gives normal cond.
356
+ Both uncond skipping and SLG are active where
357
+ slg_start <= step_index / num_steps < slg_stop;
358
+ the interval follows denoising order, from initial noise to final image.
359
+ Outside it, inference uses normal CFG without skipping.
360
+ slg_scale=0 or empty slg_layers disables the additional forward.
361
+ """
362
+ uncond_skip_layers = _validate_skip_layers(
363
+ uncond_skip_layers, len(self.transformer.layers), 'uncond_skip_layers')
364
+ slg_layers = _validate_skip_layers(slg_layers, len(self.transformer.layers), 'slg_layers')
365
+ if not math.isfinite(slg_scale) or slg_scale < 0:
366
+ raise ValueError('slg_scale must be finite and nonnegative.')
367
+ if not 0 <= slg_start <= slg_stop <= 1:
368
+ raise ValueError('Require 0 <= slg_start <= slg_stop <= 1.')
369
+ if height <= 0 or width <= 0 or height % 16 or width % 16:
370
+ raise ValueError('height and width must be positive multiples of 16.')
371
+ if output_type not in {'pil', 'np', 'pt', 'latent'}:
372
+ raise ValueError('output_type must be pil, np, pt or latent.')
373
+ if num_images_per_prompt < 1 or not math.isfinite(guidance_scale) or guidance_scale < 0:
374
+ raise ValueError('Invalid image count or guidance scale.')
375
+ if not 1 <= max_sequence_length <= 4096:
376
+ raise ValueError('max_sequence_length must be between 1 and 4096.')
377
+ if (prompt is None) == (prompt_embeds is None):
378
+ raise ValueError('Provide exactly one of prompt and prompt_embeds.')
379
+ device = self._execution_device
380
+ if prompt_embeds is None:
381
+ prompt_embeds, prompt_attention_mask = self.encode_prompt(prompt, max_sequence_length)
382
+ batch = prompt_embeds.shape[0]
383
+ def prepare(embeds, mask):
384
+ if embeds.ndim != 3 or embeds.shape[0] != batch:
385
+ raise ValueError('Prompt embeddings must be [B, S, C] with matching batch size.')
386
+ if mask is None:
387
+ mask = torch.ones(embeds.shape[:2], dtype=torch.bool, device=embeds.device)
388
+ return (embeds.to(device).repeat_interleave(num_images_per_prompt, 0),
389
+ mask.to(device).repeat_interleave(num_images_per_prompt, 0))
390
+ positive, positive_mask = prepare(prompt_embeds, prompt_attention_mask)
391
+ do_cfg = guidance_scale != 1.0
392
+ if do_cfg:
393
+ if negative_prompt_embeds is None:
394
+ negatives = [negative_prompt] * batch if isinstance(negative_prompt, str) else negative_prompt
395
+ if len(negatives) != batch:
396
+ raise ValueError('negative_prompt must match prompt batch size.')
397
+ negative_prompt_embeds, negative_prompt_attention_mask = self.encode_prompt(negatives, max_sequence_length)
398
+ negative, negative_mask = prepare(negative_prompt_embeds, negative_prompt_attention_mask)
399
+ shape = (batch * num_images_per_prompt, self.transformer.config.latent_channels, height // 16, width // 16)
400
+ if latents is None:
401
+ # Sample in fp32: promoting bf16 noise afterward cannot restore its precision.
402
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=torch.float32)
403
+ elif tuple(latents.shape) != shape:
404
+ raise ValueError(f'latents must have shape {shape}.')
405
+ else:
406
+ latents = latents.to(device=device, dtype=torch.float32)
407
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
408
+ num_steps = len(self.scheduler.timesteps)
409
+ for step_index, timestep in enumerate(self.progress_bar(self.scheduler.timesteps)):
410
+ skip_active = slg_start <= step_index / num_steps < slg_stop
411
+ # CFG must combine fp32 predictions, even when the DiT runs in bf16.
412
+ # Converting only the combined velocity would preserve rounding errors.
413
+ prediction = self.transformer(latents, timestep, positive, positive_mask).sample.float()
414
+ conditional = prediction
415
+ if do_cfg:
416
+ skip_kwargs = {'skip_layers': uncond_skip_layers} if uncond_skip_layers and skip_active else {}
417
+ uncond = self.transformer(latents, timestep, negative, negative_mask, **skip_kwargs).sample.float()
418
+ prediction = uncond + guidance_scale * (prediction - uncond)
419
+ if slg_layers and slg_scale > 0 and skip_active:
420
+ skipped = self.transformer(
421
+ latents, timestep, positive, positive_mask, skip_layers=slg_layers).sample.float()
422
+ if not do_cfg:
423
+ prediction = skipped
424
+ prediction = prediction + slg_scale * (conditional - skipped)
425
+ latents = self.scheduler.step(prediction, timestep, latents, return_dict=False)[0]
426
+ if output_type == 'latent':
427
+ images = latents
428
+ else:
429
+ if self.vae is None:
430
+ raise ValueError('A FLUX.2 VAE is required for decoded output.')
431
+ z = latents.to(dtype=self.vae.dtype)
432
+ bn = self.vae.bn
433
+ eps = self.vae.config.batch_norm_eps
434
+ z = z * (bn.running_var + eps).sqrt().to(z).view(1, -1, 1, 1) + bn.running_mean.to(z).view(1, -1, 1, 1)
435
+ b, c, h, w = z.shape
436
+ z = z.reshape(b, c // 4, 2, 2, h, w).permute(0, 1, 4, 2, 5, 3).reshape(b, c // 4, 2 * h, 2 * w)
437
+ images = self.vae.decode(z, return_dict=False)[0].clamp(-1, 1)
438
+ images = self.image_processor.postprocess(images, output_type=output_type)
439
+ self.maybe_free_model_hooks()
440
+ return ImagePipelineOutput(images=images) if return_dict else (images,)