K00B404 commited on
Commit
14f59fd
Β·
verified Β·
1 Parent(s): a1adff2

Create poc.py

Browse files
Files changed (1) hide show
  1. poc.py +656 -0
poc.py ADDED
@@ -0,0 +1,656 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ """
3
+ Flexible Batch I2V Generator with Temporal Consistency
4
+ Generates N frames at a time (1, 2, 3, etc.) while maintaining temporal consistency
5
+ Optimized for Image-to-Video models with reference frame initialization
6
+ """
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+ from typing import List, Optional, Tuple, Dict, Any, Union
12
+ import numpy as np
13
+ from collections import deque
14
+ import math
15
+ from PIL import Image
16
+ import torchvision.transforms as transforms
17
+
18
+ class TemporalConsistencyBuffer:
19
+ """Enhanced temporal buffer for flexible batch generation"""
20
+
21
+ def __init__(self, buffer_size: int = 8, feature_dim: int = 512):
22
+ self.buffer_size = buffer_size
23
+ self.feature_dim = feature_dim
24
+ self.frame_features = deque(maxlen=buffer_size)
25
+ self.frame_latents = deque(maxlen=buffer_size)
26
+ self.frame_images = deque(maxlen=buffer_size) # Store actual frames for I2V
27
+ self.motion_vectors = deque(maxlen=buffer_size-1)
28
+ self.temporal_weights = deque(maxlen=buffer_size) # Importance weights
29
+
30
+ def add_frames(self, features: torch.Tensor, latents: torch.Tensor, images: Optional[torch.Tensor] = None, batch_size: int = 1):
31
+ """Add batch of frames to temporal buffer"""
32
+ for i in range(batch_size):
33
+ frame_feat = features[i:i+1] if features.dim() > 3 else features
34
+ frame_lat = latents[i:i+1] if latents.dim() > 3 else latents
35
+ frame_img = images[i:i+1] if images is not None and images.dim() > 3 else images
36
+
37
+ # Calculate motion vector if we have previous frames
38
+ if len(self.frame_features) > 0:
39
+ motion = frame_feat - self.frame_features[-1]
40
+ self.motion_vectors.append(motion)
41
+
42
+ self.frame_features.append(frame_feat)
43
+ self.frame_latents.append(frame_lat)
44
+ if frame_img is not None:
45
+ self.frame_images.append(frame_img)
46
+
47
+ # Weight newer frames more heavily
48
+ weight = 1.0 / (len(self.frame_features) + 1)
49
+ self.temporal_weights.append(weight)
50
+
51
+ def get_reference_frame(self) -> Optional[torch.Tensor]:
52
+ """Get the most recent frame as reference for I2V"""
53
+ if len(self.frame_images) > 0:
54
+ return self.frame_images[-1]
55
+ elif len(self.frame_latents) > 0:
56
+ return self.frame_latents[-1]
57
+ return None
58
+
59
+ def get_temporal_context(self, num_context_frames: int = 4) -> Dict[str, torch.Tensor]:
60
+ """Get weighted temporal context for next frame batch"""
61
+ if len(self.frame_features) == 0:
62
+ return {"has_context": False}
63
+
64
+ # Get most recent frames up to num_context_frames
65
+ context_size = min(num_context_frames, len(self.frame_features))
66
+ recent_features = list(self.frame_features)[-context_size:]
67
+ recent_latents = list(self.frame_latents)[-context_size:]
68
+ recent_weights = list(self.temporal_weights)[-context_size:]
69
+
70
+ # Stack with attention to batch dimension
71
+ stacked_features = torch.cat(recent_features, dim=0) # [T, C, H, W]
72
+ stacked_latents = torch.cat(recent_latents, dim=0)
73
+ weights = torch.tensor(recent_weights, device=stacked_features.device)
74
+
75
+ # Predict motion for next frames
76
+ predicted_motions = []
77
+ if len(self.motion_vectors) >= 2:
78
+ # Multi-step motion prediction
79
+ recent_motions = list(self.motion_vectors)[-3:] # Last 3 motions
80
+ for step in range(1, 4): # Predict up to 3 steps ahead
81
+ if len(recent_motions) >= 2:
82
+ # Weighted motion extrapolation
83
+ motion_pred = (
84
+ recent_motions[-1] * 1.5 -
85
+ recent_motions[-2] * 0.5
86
+ )
87
+ if len(recent_motions) >= 3:
88
+ motion_pred += recent_motions[-3] * 0.1
89
+ else:
90
+ motion_pred = recent_motions[-1] if recent_motions else None
91
+ predicted_motions.append(motion_pred)
92
+
93
+ return {
94
+ "has_context": True,
95
+ "frame_features": stacked_features,
96
+ "frame_latents": stacked_latents,
97
+ "temporal_weights": weights,
98
+ "predicted_motions": predicted_motions,
99
+ "sequence_length": len(self.frame_features),
100
+ "reference_frame": self.get_reference_frame()
101
+ }
102
+
103
+ class FlexibleTemporalAttention(nn.Module):
104
+ """Flexible attention that handles variable batch sizes"""
105
+
106
+ def __init__(self, dim: int, num_heads: int = 8, max_frames: int = 16):
107
+ super().__init__()
108
+ self.dim = dim
109
+ self.num_heads = num_heads
110
+ self.head_dim = dim // num_heads
111
+ self.scale = self.head_dim ** -0.5
112
+ self.max_frames = max_frames
113
+
114
+ self.qkv = nn.Linear(dim, dim * 3, bias=False)
115
+ self.proj = nn.Linear(dim, dim)
116
+
117
+ # Learnable temporal positional embeddings
118
+ self.temporal_pos_embed = nn.Parameter(torch.randn(1, max_frames, dim) * 0.02)
119
+ self.frame_type_embed = nn.Parameter(torch.randn(3, dim) * 0.02) # past, current, future
120
+
121
+ # Cross-frame interaction
122
+ self.cross_frame_norm = nn.LayerNorm(dim)
123
+ self.cross_frame_mlp = nn.Sequential(
124
+ nn.Linear(dim, dim * 2),
125
+ nn.GELU(),
126
+ nn.Linear(dim * 2, dim)
127
+ )
128
+
129
+ def forward(self, current_frames: torch.Tensor, temporal_context: Dict[str, Any], num_current_frames: int = 1):
130
+ """
131
+ current_frames: [B*N, H*W, C] where N is number of frames being generated
132
+ temporal_context: dict with past frame information
133
+ """
134
+ B_times_N, HW, C = current_frames.shape
135
+ B = B_times_N // num_current_frames
136
+
137
+ if not temporal_context.get("has_context", False):
138
+ return current_frames
139
+
140
+ # Reshape current frames
141
+ current = current_frames.view(B, num_current_frames, HW, C)
142
+
143
+ # Get temporal context
144
+ past_features = temporal_context["frame_features"] # [T, C, H, W]
145
+ T, _, H, W = past_features.shape
146
+ past_features = past_features.view(T, C, H*W).permute(0, 2, 1) # [T, H*W, C]
147
+ past_features = past_features.unsqueeze(0).expand(B, -1, -1, -1) # [B, T, H*W, C]
148
+
149
+ # Combine all frames (past + current)
150
+ all_frames = torch.cat([past_features, current], dim=1) # [B, T+N, H*W, C]
151
+ total_frames = T + num_current_frames
152
+
153
+ # Add positional embeddings
154
+ pos_ids = torch.arange(total_frames, device=current_frames.device)
155
+ pos_embed = self.temporal_pos_embed[:, :total_frames] # [1, T+N, C]
156
+
157
+ # Add frame type embeddings (past=0, current=1, future=2)
158
+ frame_type_ids = torch.cat([
159
+ torch.zeros(T, device=current_frames.device), # past frames
160
+ torch.ones(num_current_frames, device=current_frames.device) # current frames
161
+ ]).long()
162
+ type_embed = self.frame_type_embed[frame_type_ids] # [T+N, C]
163
+
164
+ # Apply embeddings
165
+ all_frames = all_frames + pos_embed.unsqueeze(2) + type_embed.unsqueeze(0).unsqueeze(2)
166
+
167
+ # Flatten for attention
168
+ all_frames_flat = all_frames.view(B, total_frames * HW, C)
169
+
170
+ # Multi-head attention
171
+ qkv = self.qkv(all_frames_flat).reshape(B, -1, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4)
172
+ q, k, v = qkv[0], qkv[1], qkv[2]
173
+
174
+ # Temporal attention with causality mask for current frames
175
+ attn = (q @ k.transpose(-2, -1)) * self.scale
176
+
177
+ # Create causal mask - current frames can see past + themselves, but not future
178
+ mask = torch.triu(torch.ones(total_frames * HW, total_frames * HW, device=current_frames.device), diagonal=1)
179
+ mask = mask.bool()
180
+ attn = attn.masked_fill(mask.unsqueeze(0).unsqueeze(0), float('-inf'))
181
+
182
+ attn = attn.softmax(dim=-1)
183
+ out = (attn @ v).transpose(1, 2).reshape(B, total_frames * HW, C)
184
+
185
+ # Extract only current frame features
186
+ current_start = T * HW
187
+ enhanced_current = out[:, current_start:] # [B, N*H*W, C]
188
+ enhanced_current = self.proj(enhanced_current)
189
+
190
+ # Cross-frame interaction within current batch
191
+ if num_current_frames > 1:
192
+ enhanced_current = enhanced_current.view(B, num_current_frames, HW, C)
193
+ for i in range(num_current_frames):
194
+ frame_i = enhanced_current[:, i] # [B, H*W, C]
195
+
196
+ # Interact with other frames in current batch
197
+ other_frames = torch.cat([
198
+ enhanced_current[:, :i],
199
+ enhanced_current[:, i+1:]
200
+ ], dim=1) if num_current_frames > 1 else None
201
+
202
+ if other_frames is not None:
203
+ cross_context = other_frames.mean(dim=1) # [B, H*W, C]
204
+ frame_i_norm = self.cross_frame_norm(frame_i + cross_context)
205
+ frame_i = frame_i + self.cross_frame_mlp(frame_i_norm)
206
+ enhanced_current[:, i] = frame_i
207
+
208
+ enhanced_current = enhanced_current.view(B * num_current_frames, HW, C)
209
+
210
+ return enhanced_current
211
+
212
+ class FlexibleI2VDiffuser(nn.Module):
213
+ """Flexible I2V diffusion model that generates N frames at a time"""
214
+
215
+ def __init__(
216
+ self,
217
+ base_diffusion_model,
218
+ feature_dim: int = 512,
219
+ temporal_buffer_size: int = 8,
220
+ num_attention_heads: int = 8,
221
+ max_batch_frames: int = 3
222
+ ):
223
+ super().__init__()
224
+ self.base_model = base_diffusion_model
225
+ self.feature_dim = feature_dim
226
+ self.temporal_buffer_size = temporal_buffer_size
227
+ self.max_batch_frames = max_batch_frames
228
+
229
+ # Enhanced feature extraction for I2V
230
+ self.image_encoder = nn.Sequential(
231
+ nn.Conv2d(3, feature_dim // 4, 7, padding=3),
232
+ nn.GroupNorm(8, feature_dim // 4),
233
+ nn.SiLU(),
234
+ nn.Conv2d(feature_dim // 4, feature_dim // 2, 3, padding=1, stride=2),
235
+ nn.GroupNorm(8, feature_dim // 2),
236
+ nn.SiLU(),
237
+ nn.Conv2d(feature_dim // 2, feature_dim, 3, padding=1, stride=2),
238
+ nn.GroupNorm(8, feature_dim),
239
+ nn.SiLU()
240
+ )
241
+
242
+ self.latent_encoder = nn.Conv2d(
243
+ base_diffusion_model.in_channels, feature_dim, 3, padding=1
244
+ )
245
+
246
+ # Flexible temporal attention
247
+ self.temporal_attention = FlexibleTemporalAttention(
248
+ feature_dim, num_attention_heads, max_batch_frames * 4
249
+ )
250
+
251
+ # I2V specific components
252
+ self.reference_adapter = nn.Sequential(
253
+ nn.Conv2d(feature_dim * 2, feature_dim, 1),
254
+ nn.GroupNorm(8, feature_dim),
255
+ nn.SiLU()
256
+ )
257
+
258
+ self.motion_conditioner = nn.Sequential(
259
+ nn.Linear(feature_dim, feature_dim * 2),
260
+ nn.GELU(),
261
+ nn.Linear(feature_dim * 2, feature_dim)
262
+ )
263
+
264
+ # Multi-frame consistency
265
+ self.frame_consistency_net = nn.Sequential(
266
+ nn.Conv3d(feature_dim, feature_dim, (3, 3, 3), padding=(1, 1, 1)),
267
+ nn.GroupNorm(8, feature_dim),
268
+ nn.SiLU(),
269
+ nn.Conv3d(feature_dim, feature_dim, (1, 3, 3), padding=(0, 1, 1))
270
+ )
271
+
272
+
273
+ # Initialize temporal buffer
274
+ self.temporal_buffer = TemporalConsistencyBuffer(temporal_buffer_size, feature_dim)
275
+
276
+ def encode_reference_image(self, image: torch.Tensor) -> torch.Tensor:
277
+ """Encode reference image for I2V conditioning"""
278
+ if image.shape[1] == 3: # RGB image
279
+ return self.image_encoder(image)
280
+ else: # Already encoded latent
281
+ return self.latent_encoder(image)
282
+
283
+ def apply_i2v_conditioning(
284
+ self,
285
+ current_latents: torch.Tensor, # [B*N, C, H, W]
286
+ temporal_context: Dict[str, Any],
287
+ num_frames: int = 1
288
+ ) -> torch.Tensor:
289
+ """Apply I2V conditioning with flexible frame count"""
290
+
291
+ B_times_N, C, H, W = current_latents.shape
292
+ B = B_times_N // num_frames
293
+
294
+ # Extract features from current latents
295
+ current_features = self.latent_encoder(current_latents) # [B*N, F, H, W]
296
+
297
+ if not temporal_context.get("has_context", False):
298
+ return current_latents
299
+
300
+ # Apply temporal attention
301
+ current_flat = current_features.flatten(2).transpose(1, 2) # [B*N, H*W, F]
302
+ enhanced_features = self.temporal_attention(current_flat, temporal_context, num_frames)
303
+ enhanced_features = enhanced_features.transpose(1, 2).reshape(B_times_N, -1, H, W)
304
+
305
+ # Reference frame conditioning for I2V
306
+ if temporal_context.get("reference_frame") is not None:
307
+ ref_frame = temporal_context["reference_frame"]
308
+ ref_features = self.encode_reference_image(ref_frame)
309
+
310
+ # Broadcast reference to all current frames
311
+ ref_features = ref_features.repeat(num_frames, 1, 1, 1)
312
+
313
+ # Combine with current features
314
+ combined_features = torch.cat([enhanced_features, ref_features], dim=1)
315
+ conditioned_features = self.reference_adapter(combined_features)
316
+ else:
317
+ conditioned_features = enhanced_features
318
+
319
+ # Multi-frame consistency for batch generation
320
+ if num_frames > 1:
321
+ # Reshape for 3D convolution
322
+ batch_features = conditioned_features.view(B, num_frames, -1, H, W)
323
+ batch_features = batch_features.permute(0, 2, 1, 3, 4) # [B, C, T, H, W]
324
+
325
+ # Apply 3D consistency
326
+ consistent_features = self.frame_consistency_net(batch_features)
327
+ consistent_features = consistent_features.permute(0, 2, 1, 3, 4) # [B, T, C, H, W]
328
+ conditioned_features = consistent_features.reshape(B_times_N, -1, H, W)
329
+
330
+ # Motion conditioning
331
+ if temporal_context.get("predicted_motions"):
332
+ motions = temporal_context["predicted_motions"][:num_frames]
333
+ for i, motion in enumerate(motions):
334
+ if motion is not None:
335
+ frame_idx = i * B + torch.arange(B, device=current_latents.device)
336
+ motion_flat = motion.flatten(2).transpose(1, 2).mean(dim=1) # [B, F]
337
+ motion_cond = self.motion_conditioner(motion_flat) # [B, F]
338
+ motion_cond = motion_cond.unsqueeze(-1).unsqueeze(-1) # [B, F, 1, 1]
339
+ conditioned_features[frame_idx] += motion_cond
340
+
341
+ # Blend with original latents
342
+ alpha = 0.4 # I2V conditioning strength
343
+ enhanced_latents = current_latents + alpha * conditioned_features
344
+
345
+ return enhanced_latents
346
+
347
+ def forward(
348
+ self,
349
+ noisy_latents: torch.Tensor, # [B*N, C, H, W]
350
+ timestep: torch.Tensor,
351
+ text_embeddings: torch.Tensor,
352
+ num_frames: int = 1,
353
+ use_temporal_consistency: bool = True
354
+ ) -> torch.Tensor:
355
+ """Forward pass with flexible frame count"""
356
+
357
+ if use_temporal_consistency:
358
+ # Get temporal context
359
+ temporal_context = self.temporal_buffer.get_temporal_context()
360
+
361
+ # Apply I2V conditioning
362
+ enhanced_latents = self.apply_i2v_conditioning(
363
+ noisy_latents, temporal_context, num_frames
364
+ )
365
+ else:
366
+ enhanced_latents = noisy_latents
367
+
368
+ # Expand text embeddings for multiple frames
369
+ if text_embeddings.shape[0] != enhanced_latents.shape[0]:
370
+ text_embeddings = text_embeddings.repeat(num_frames, 1, 1)
371
+
372
+ # Run base diffusion model
373
+ noise_pred = self.base_model(enhanced_latents, timestep, text_embeddings)
374
+
375
+ return noise_pred
376
+
377
+ def update_temporal_buffer(self, latents: torch.Tensor, images: Optional[torch.Tensor] = None, num_frames: int = 1):
378
+ """Update temporal buffer with generated frames"""
379
+ with torch.no_grad():
380
+ features = self.latent_encoder(latents)
381
+ self.temporal_buffer.add_frames(features, latents, images, num_frames)
382
+
383
+ class FlexibleI2VGenerator:
384
+ """High-level generator with configurable frame batch sizes"""
385
+
386
+ def __init__(
387
+ self,
388
+ diffusion_model: FlexibleI2VDiffuser,
389
+ scheduler,
390
+ vae, # For encoding/decoding images
391
+ device: str = "cuda"
392
+ ):
393
+ self.model = diffusion_model
394
+ self.scheduler = scheduler
395
+ self.vae = vae
396
+ self.device = device
397
+
398
+ # Image preprocessing
399
+ self.image_transform = transforms.Compose([
400
+ transforms.Resize((512, 512)),
401
+ transforms.ToTensor(),
402
+ transforms.Normalize([0.5], [0.5])
403
+ ])
404
+
405
+ def encode_image(self, image: Union[Image.Image, torch.Tensor]) -> torch.Tensor:
406
+ """Encode PIL image or tensor to latent space"""
407
+ if isinstance(image, Image.Image):
408
+ image = self.image_transform(image).unsqueeze(0).to(self.device)
409
+
410
+ with torch.no_grad():
411
+ latent = self.vae.encode(image).latent_dist.sample()
412
+ latent = latent * self.vae.config.scaling_factor
413
+
414
+ return latent
415
+
416
+ def decode_latents(self, latents: torch.Tensor) -> torch.Tensor:
417
+ """Decode latents to images"""
418
+ with torch.no_grad():
419
+ latents = latents / self.vae.config.scaling_factor
420
+ images = self.vae.decode(latents).sample
421
+ images = (images + 1.0) / 2.0
422
+ images = torch.clamp(images, 0.0, 1.0)
423
+ return images
424
+
425
+ @torch.no_grad()
426
+ def generate_i2v_sequence(
427
+ self,
428
+ reference_image: Union[Image.Image, torch.Tensor],
429
+ prompt: str,
430
+ text_encoder,
431
+ tokenizer,
432
+ num_frames: int = 16,
433
+ frames_per_batch: int = 2, # This is the key parameter!
434
+ num_inference_steps: int = 20,
435
+ guidance_scale: float = 7.5,
436
+ generator: Optional[torch.Generator] = None,
437
+ callback=None
438
+ ) -> List[torch.Tensor]:
439
+ """Generate I2V sequence with configurable batch size"""
440
+
441
+ print(f"🎬 Generating {num_frames} frames in batches of {frames_per_batch}")
442
+
443
+ # Encode reference image
444
+ ref_latent = self.encode_image(reference_image)
445
+ ref_image_tensor = reference_image if isinstance(reference_image, torch.Tensor) else \
446
+ self.image_transform(reference_image).unsqueeze(0).to(self.device)
447
+
448
+ # Encode text prompt
449
+ text_inputs = tokenizer(
450
+ prompt,
451
+ padding="max_length",
452
+ max_length=tokenizer.model_max_length,
453
+ truncation=True,
454
+ return_tensors="pt"
455
+ )
456
+ text_embeddings = text_encoder(text_inputs.input_ids.to(self.device))[0]
457
+
458
+ # Prepare unconditional embeddings
459
+ uncond_tokens = [""]
460
+ uncond_inputs = tokenizer(
461
+ uncond_tokens,
462
+ padding="max_length",
463
+ max_length=tokenizer.model_max_length,
464
+ return_tensors="pt"
465
+ )
466
+ uncond_embeddings = text_encoder(uncond_inputs.input_ids.to(self.device))[0]
467
+
468
+ # Reset temporal buffer and add reference frame
469
+ self.model.temporal_buffer = TemporalConsistencyBuffer(
470
+ self.model.temporal_buffer_size,
471
+ self.model.feature_dim
472
+ )
473
+ self.model.update_temporal_buffer(ref_latent, ref_image_tensor, 1)
474
+
475
+ generated_frames = [ref_latent]
476
+ latent_shape = ref_latent.shape
477
+
478
+ # Generate in flexible batches
479
+ frames_generated = 1 # Start with reference frame
480
+
481
+ while frames_generated < num_frames:
482
+ # Calculate current batch size
483
+ remaining_frames = num_frames - frames_generated
484
+ current_batch_size = min(frames_per_batch, remaining_frames)
485
+
486
+ print(f"🎯 Generating frames {frames_generated+1}-{frames_generated+current_batch_size}")
487
+
488
+ # Initialize noise for current batch
489
+ batch_latents = torch.randn(
490
+ (current_batch_size, *latent_shape[1:]),
491
+ generator=generator,
492
+ device=self.device,
493
+ dtype=text_embeddings.dtype
494
+ )
495
+
496
+ # Prepare embeddings for batch
497
+ batch_text_embeddings = torch.cat([
498
+ uncond_embeddings.repeat(current_batch_size, 1, 1),
499
+ text_embeddings.repeat(current_batch_size, 1, 1)
500
+ ])
501
+
502
+ # Set scheduler timesteps
503
+ self.scheduler.set_timesteps(num_inference_steps, device=self.device)
504
+ timesteps = self.scheduler.timesteps
505
+
506
+ # Denoising loop for current batch
507
+ for i, t in enumerate(timesteps):
508
+ # Expand for classifier-free guidance
509
+ latent_model_input = torch.cat([batch_latents] * 2)
510
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
511
+
512
+ # Predict noise with temporal consistency
513
+ noise_pred = self.model(
514
+ latent_model_input,
515
+ t,
516
+ batch_text_embeddings,
517
+ num_frames=current_batch_size,
518
+ use_temporal_consistency=True
519
+ )
520
+
521
+ # Classifier-free guidance
522
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
523
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
524
+
525
+ # Scheduler step
526
+ batch_latents = self.scheduler.step(noise_pred, t, batch_latents).prev_sample
527
+
528
+ if callback:
529
+ callback(i, t, batch_latents)
530
+
531
+ # Update temporal buffer with generated batch
532
+ batch_images = self.decode_latents(batch_latents)
533
+ self.model.update_temporal_buffer(batch_latents, batch_images, current_batch_size)
534
+
535
+ # Add to results
536
+ for j in range(current_batch_size):
537
+ generated_frames.append(batch_latents[j:j+1])
538
+
539
+ frames_generated += current_batch_size
540
+ print(f"βœ… Generated {current_batch_size} frames")
541
+
542
+ return generated_frames
543
+
544
+ def generate_with_stepping_strategy(
545
+ self,
546
+ reference_image: Union[Image.Image, torch.Tensor],
547
+ prompt: str,
548
+ text_encoder,
549
+ tokenizer,
550
+ total_frames: int = 24,
551
+ stepping_pattern: List[int] = [1, 2, 3, 2, 1], # Variable batch sizes
552
+ **kwargs
553
+ ) -> List[torch.Tensor]:
554
+ """Generate with dynamic stepping pattern"""
555
+
556
+ all_frames = []
557
+ frames_generated = 0
558
+ step_idx = 0
559
+
560
+ while frames_generated < total_frames:
561
+ # Get current step size
562
+ current_step = stepping_pattern[step_idx % len(stepping_pattern)]
563
+ remaining = total_frames - frames_generated
564
+ actual_step = min(current_step, remaining)
565
+
566
+ print(f"πŸ“Š Step {step_idx + 1}: Generating {actual_step} frames")
567
+
568
+ # Generate batch
569
+ if frames_generated == 0:
570
+ # First generation includes reference
571
+ frames = self.generate_i2v_sequence(
572
+ reference_image=reference_image,
573
+ prompt=prompt,
574
+ text_encoder=text_encoder,
575
+ tokenizer=tokenizer,
576
+ num_frames=actual_step + 1, # +1 for reference
577
+ frames_per_batch=actual_step,
578
+ **kwargs
579
+ )
580
+ all_frames.extend(frames)
581
+ frames_generated += len(frames)
582
+ else:
583
+ # Continue from last frame
584
+ last_frame_latent = all_frames[-1]
585
+ last_frame_image = self.decode_latents(last_frame_latent)
586
+
587
+ frames = self.generate_i2v_sequence(
588
+ reference_image=last_frame_image,
589
+ prompt=prompt,
590
+ text_encoder=text_encoder,
591
+ tokenizer=tokenizer,
592
+ num_frames=actual_step + 1,
593
+ frames_per_batch=actual_step,
594
+ **kwargs
595
+ )
596
+ all_frames.extend(frames[1:]) # Skip reference (duplicate)
597
+ frames_generated += len(frames) - 1
598
+
599
+ step_idx += 1
600
+
601
+ return all_frames[:total_frames] # Ensure exact frame count
602
+
603
+ # Example usage
604
+ def example_usage():
605
+ """Example of flexible I2V generation"""
606
+
607
+ # Load your models (example)
608
+ #
609
+ base_model, scheduler, vae, text_encoder, tokenizer = load_models()
610
+
611
+ # Create flexible I2V model
612
+ i2v_model = FlexibleI2VDiffuser(
613
+ base_diffusion_model=i2v_model,
614
+ feature_dim=512,
615
+ temporal_buffer_size=8,
616
+ max_batch_frames=3
617
+ )
618
+
619
+ # Create generator
620
+ generator = FlexibleI2VGenerator(
621
+ diffusion_model=i2v_model,
622
+ scheduler=scheduler,
623
+ vae=vae,
624
+ device="cuda"
625
+ )
626
+
627
+ # Load reference image
628
+ reference_image = Image.open("reference.jpg")
629
+
630
+ # Strategy 1: Fixed batch size
631
+ frames_fixed = generator.generate_i2v_sequence(
632
+ reference_image=reference_image,
633
+ prompt="A cat walking in a garden",
634
+ text_encoder=text_encoder,
635
+ tokenizer=tokenizer,
636
+ num_frames=16,
637
+ frames_per_batch=2, # Generate 2 frames at a time
638
+ num_inference_steps=20
639
+ )
640
+
641
+ # Strategy 2: Variable stepping pattern
642
+ frames_variable = generator.generate_with_stepping_strategy(
643
+ reference_image=reference_image,
644
+ prompt="A cat walking in a garden",
645
+ text_encoder=text_encoder,
646
+ tokenizer=tokenizer,
647
+ total_frames=24,
648
+ stepping_pattern=[1, 2, 3, 2, 1], # Start slow, ramp up, slow down
649
+ num_inference_steps=20
650
+ )
651
+
652
+ print(f"πŸŽ‰ Generated {len(frames_fixed)} frames with fixed batching")
653
+ print(f"πŸŽ‰ Generated {len(frames_variable)} frames with variable stepping")
654
+
655
+ if __name__ == "__main__":
656
+ example_usage()