AbstractPhil commited on
Commit
120062a
·
verified ·
1 Parent(s): a2ad788

Create inference.py

Browse files
Files changed (1) hide show
  1. inference.py +372 -0
inference.py ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================================
2
+ # TinyFlux Inference Cell - Euler Discrete Flow Matching
3
+ # ============================================================================
4
+ # Run the model cell before this one (defines TinyFlux, TinyFluxConfig)
5
+ # Loads from: AbstractPhil/tiny-flux or local checkpoint
6
+ # ============================================================================
7
+
8
+ import torch
9
+ from huggingface_hub import hf_hub_download
10
+ from safetensors.torch import load_file
11
+ from transformers import T5EncoderModel, T5Tokenizer, CLIPTextModel, CLIPTokenizer
12
+ from diffusers import AutoencoderKL
13
+ from PIL import Image
14
+ import numpy as np
15
+ import os
16
+
17
+ # ============================================================================
18
+ # CONFIG
19
+ # ============================================================================
20
+ DEVICE = "cuda"
21
+ DTYPE = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
22
+
23
+ # Model loading
24
+ HF_REPO = "AbstractPhil/tiny-flux"
25
+ LOAD_FROM = "hub" # "hub", "hub:step_1000", "local:/path/to/weights.safetensors"
26
+
27
+ # Generation settings
28
+ NUM_STEPS = 20 # Euler steps (20-50 typical)
29
+ GUIDANCE_SCALE = 3.5 # CFG scale (1.0 = no guidance, 3-7 typical)
30
+ HEIGHT = 512 # Output height
31
+ WIDTH = 512 # Output width
32
+ SEED = None # None for random
33
+
34
+ # ============================================================================
35
+ # LOAD TEXT ENCODERS
36
+ # ============================================================================
37
+ print("Loading text encoders...")
38
+ t5_tok = T5Tokenizer.from_pretrained("google/flan-t5-base")
39
+ t5_enc = T5EncoderModel.from_pretrained("google/flan-t5-base", torch_dtype=DTYPE).to(DEVICE).eval()
40
+
41
+ clip_tok = CLIPTokenizer.from_pretrained("openai/clip-vit-large-patch14")
42
+ clip_enc = CLIPTextModel.from_pretrained("openai/clip-vit-large-patch14", torch_dtype=DTYPE).to(DEVICE).eval()
43
+
44
+ # ============================================================================
45
+ # LOAD VAE
46
+ # ============================================================================
47
+ print("Loading Flux VAE...")
48
+ vae = AutoencoderKL.from_pretrained(
49
+ "black-forest-labs/FLUX.1-schnell",
50
+ subfolder="vae",
51
+ torch_dtype=DTYPE
52
+ ).to(DEVICE).eval()
53
+
54
+ # ============================================================================
55
+ # LOAD TINYFLUX MODEL
56
+ # ============================================================================
57
+ print(f"Loading TinyFlux from: {LOAD_FROM}")
58
+
59
+ config = TinyFluxConfig()
60
+ model = TinyFlux(config).to(DEVICE).to(DTYPE)
61
+
62
+ if LOAD_FROM == "hub":
63
+ # Load best model from hub
64
+ weights_path = hf_hub_download(repo_id=HF_REPO, filename="model.safetensors")
65
+ weights = load_file(weights_path)
66
+ model.load_state_dict(weights)
67
+ print(f"✓ Loaded from {HF_REPO}/model.safetensors")
68
+ elif LOAD_FROM.startswith("hub:"):
69
+ # Load specific checkpoint from hub
70
+ ckpt_name = LOAD_FROM[4:]
71
+ if not ckpt_name.endswith(".safetensors"):
72
+ ckpt_name = f"checkpoints/{ckpt_name}.safetensors"
73
+ weights_path = hf_hub_download(repo_id=HF_REPO, filename=ckpt_name)
74
+ weights = load_file(weights_path)
75
+ model.load_state_dict(weights)
76
+ print(f"✓ Loaded from {HF_REPO}/{ckpt_name}")
77
+ elif LOAD_FROM.startswith("local:"):
78
+ # Load local file
79
+ weights_path = LOAD_FROM[6:]
80
+ weights = load_file(weights_path)
81
+ model.load_state_dict(weights)
82
+ print(f"✓ Loaded from {weights_path}")
83
+ else:
84
+ raise ValueError(f"Unknown LOAD_FROM: {LOAD_FROM}")
85
+
86
+ model.eval()
87
+ print(f"Model params: {sum(p.numel() for p in model.parameters()):,}")
88
+
89
+ # ============================================================================
90
+ # ENCODING FUNCTIONS
91
+ # ============================================================================
92
+ @torch.no_grad()
93
+ def encode_prompt(prompt: str, max_length: int = 128):
94
+ """Encode prompt with flan-t5-base and CLIP-L."""
95
+ # T5 encoding (sequence)
96
+ t5_in = t5_tok(
97
+ prompt,
98
+ max_length=max_length,
99
+ padding="max_length",
100
+ truncation=True,
101
+ return_tensors="pt"
102
+ ).to(DEVICE)
103
+ t5_out = t5_enc(
104
+ input_ids=t5_in.input_ids,
105
+ attention_mask=t5_in.attention_mask
106
+ ).last_hidden_state # (1, L, 768)
107
+
108
+ # CLIP encoding (pooled)
109
+ clip_in = clip_tok(
110
+ prompt,
111
+ max_length=77,
112
+ padding="max_length",
113
+ truncation=True,
114
+ return_tensors="pt"
115
+ ).to(DEVICE)
116
+ clip_out = clip_enc(
117
+ input_ids=clip_in.input_ids,
118
+ attention_mask=clip_in.attention_mask
119
+ )
120
+ clip_pooled = clip_out.pooler_output # (1, 768)
121
+
122
+ return t5_out, clip_pooled
123
+
124
+ # ============================================================================
125
+ # EULER DISCRETE FLOW MATCHING SAMPLER
126
+ # ============================================================================
127
+ @torch.no_grad()
128
+ def euler_sample(
129
+ model,
130
+ prompt: str,
131
+ negative_prompt: str = "",
132
+ num_steps: int = 20,
133
+ guidance_scale: float = 3.5,
134
+ height: int = 512,
135
+ width: int = 512,
136
+ seed: int = None,
137
+ ):
138
+ """
139
+ Euler discrete sampler for flow matching.
140
+
141
+ Flow matching formulation:
142
+ x_t = (1 - t) * x_0 + t * x_1
143
+ where x_0 = noise, x_1 = data
144
+ velocity v = x_1 - x_0 = data - noise
145
+
146
+ Sampling (t: 0 -> 1, noise -> data):
147
+ x_{t+dt} = x_t + v_pred * dt
148
+
149
+ With Flux shift for improved sampling distribution.
150
+ """
151
+ # Set seed
152
+ if seed is not None:
153
+ torch.manual_seed(seed)
154
+ generator = torch.Generator(device=DEVICE).manual_seed(seed)
155
+ else:
156
+ generator = None
157
+
158
+ # Latent dimensions (VAE downscales by 8)
159
+ H_lat = height // 8 # 64 for 512
160
+ W_lat = width // 8 # 64 for 512
161
+ C_lat = 16 # Flux VAE channels
162
+
163
+ # Encode prompts
164
+ t5_cond, clip_cond = encode_prompt(prompt)
165
+ if guidance_scale > 1.0 and negative_prompt is not None:
166
+ t5_uncond, clip_uncond = encode_prompt(negative_prompt)
167
+ else:
168
+ t5_uncond, clip_uncond = None, None
169
+
170
+ # Start from pure noise (t=0 in flow matching convention)
171
+ # Shape: (1, H*W, C)
172
+ x = torch.randn(1, H_lat * W_lat, C_lat, device=DEVICE, dtype=DTYPE, generator=generator)
173
+
174
+ # Create image position IDs for RoPE
175
+ img_ids = TinyFlux.create_img_ids(1, H_lat, W_lat, DEVICE)
176
+
177
+ # Timesteps: 0 -> 1 (noise -> data)
178
+ # We use uniform spacing, model handles flux shift internally for training
179
+ # For inference, linear timesteps work well
180
+ timesteps = torch.linspace(0, 1, num_steps + 1, device=DEVICE, dtype=DTYPE)
181
+
182
+ print(f"Sampling with {num_steps} Euler steps...")
183
+
184
+ for i in range(num_steps):
185
+ t_curr = timesteps[i]
186
+ t_next = timesteps[i + 1]
187
+ dt = t_next - t_curr
188
+
189
+ t_batch = t_curr.unsqueeze(0) # (1,)
190
+
191
+ # Guidance embedding (used during training with random values 1-5)
192
+ guidance_embed = torch.tensor([guidance_scale], device=DEVICE, dtype=DTYPE)
193
+
194
+ # Conditional prediction
195
+ v_cond = model(
196
+ hidden_states=x,
197
+ encoder_hidden_states=t5_cond,
198
+ pooled_projections=clip_cond,
199
+ timestep=t_batch,
200
+ img_ids=img_ids,
201
+ guidance=guidance_embed,
202
+ )
203
+
204
+ # Classifier-free guidance
205
+ if guidance_scale > 1.0 and t5_uncond is not None:
206
+ v_uncond = model(
207
+ hidden_states=x,
208
+ encoder_hidden_states=t5_uncond,
209
+ pooled_projections=clip_uncond,
210
+ timestep=t_batch,
211
+ img_ids=img_ids,
212
+ guidance=guidance_embed,
213
+ )
214
+ v = v_uncond + guidance_scale * (v_cond - v_uncond)
215
+ else:
216
+ v = v_cond
217
+
218
+ # Euler step: x_{t+dt} = x_t + v * dt
219
+ x = x + v * dt
220
+
221
+ if (i + 1) % 5 == 0 or i == num_steps - 1:
222
+ print(f" Step {i+1}/{num_steps}, t={t_next.item():.3f}")
223
+
224
+ # Reshape to image format: (1, H*W, C) -> (1, C, H, W)
225
+ latents = x.reshape(1, H_lat, W_lat, C_lat).permute(0, 3, 1, 2)
226
+
227
+ return latents
228
+
229
+ # ============================================================================
230
+ # DECODE LATENTS TO IMAGE
231
+ # ============================================================================
232
+ @torch.no_grad()
233
+ def decode_latents(latents):
234
+ """Decode VAE latents to PIL Image."""
235
+ # Flux VAE scaling
236
+ latents = latents / vae.config.scaling_factor
237
+
238
+ # Decode
239
+ image = vae.decode(latents.float()).sample
240
+
241
+ # Normalize to [0, 1]
242
+ image = (image / 2 + 0.5).clamp(0, 1)
243
+
244
+ # To PIL
245
+ image = image[0].permute(1, 2, 0).cpu().numpy()
246
+ image = (image * 255).astype(np.uint8)
247
+
248
+ return Image.fromarray(image)
249
+
250
+ # ============================================================================
251
+ # MAIN GENERATION FUNCTION
252
+ # ============================================================================
253
+ def generate(
254
+ prompt: str,
255
+ negative_prompt: str = "",
256
+ num_steps: int = NUM_STEPS,
257
+ guidance_scale: float = GUIDANCE_SCALE,
258
+ height: int = HEIGHT,
259
+ width: int = WIDTH,
260
+ seed: int = SEED,
261
+ save_path: str = None,
262
+ ):
263
+ """
264
+ Generate an image from a text prompt.
265
+
266
+ Args:
267
+ prompt: Text description of desired image
268
+ negative_prompt: What to avoid (empty string for none)
269
+ num_steps: Number of Euler steps (20-50)
270
+ guidance_scale: CFG scale (1.0=none, 3-7 typical)
271
+ height: Output height in pixels (must be divisible by 8)
272
+ width: Output width in pixels (must be divisible by 8)
273
+ seed: Random seed (None for random)
274
+ save_path: Path to save image (None to skip saving)
275
+
276
+ Returns:
277
+ PIL.Image
278
+ """
279
+ print(f"\nGenerating: '{prompt}'")
280
+ print(f"Settings: {num_steps} steps, cfg={guidance_scale}, {width}x{height}, seed={seed}")
281
+
282
+ # Sample latents
283
+ latents = euler_sample(
284
+ model=model,
285
+ prompt=prompt,
286
+ negative_prompt=negative_prompt,
287
+ num_steps=num_steps,
288
+ guidance_scale=guidance_scale,
289
+ height=height,
290
+ width=width,
291
+ seed=seed,
292
+ )
293
+
294
+ # Decode to image
295
+ print("Decoding latents...")
296
+ image = decode_latents(latents)
297
+
298
+ # Save if requested
299
+ if save_path:
300
+ image.save(save_path)
301
+ print(f"✓ Saved to {save_path}")
302
+
303
+ print("✓ Done!")
304
+ return image
305
+
306
+ # ============================================================================
307
+ # BATCH GENERATION
308
+ # ============================================================================
309
+ def generate_batch(
310
+ prompts: list,
311
+ negative_prompt: str = "",
312
+ num_steps: int = NUM_STEPS,
313
+ guidance_scale: float = GUIDANCE_SCALE,
314
+ height: int = HEIGHT,
315
+ width: int = WIDTH,
316
+ seed: int = SEED,
317
+ output_dir: str = "./outputs",
318
+ ):
319
+ """Generate multiple images."""
320
+ os.makedirs(output_dir, exist_ok=True)
321
+ images = []
322
+
323
+ for i, prompt in enumerate(prompts):
324
+ # Increment seed for variety if seed is set
325
+ img_seed = seed + i if seed is not None else None
326
+
327
+ image = generate(
328
+ prompt=prompt,
329
+ negative_prompt=negative_prompt,
330
+ num_steps=num_steps,
331
+ guidance_scale=guidance_scale,
332
+ height=height,
333
+ width=width,
334
+ seed=img_seed,
335
+ save_path=os.path.join(output_dir, f"{i:03d}.png"),
336
+ )
337
+ images.append(image)
338
+
339
+ return images
340
+
341
+ # ============================================================================
342
+ # QUICK TEST
343
+ # ============================================================================
344
+ if __name__ == "__main__" or True: # Always run in Colab
345
+ print("\n" + "="*60)
346
+ print("TinyFlux Inference Ready!")
347
+ print("="*60)
348
+ print(f"""
349
+ Usage:
350
+ # Single image
351
+ image = generate("a photo of a cat")
352
+ image.show()
353
+
354
+ # With options
355
+ image = generate(
356
+ prompt="a beautiful sunset over mountains",
357
+ negative_prompt="blurry, low quality",
358
+ num_steps=30,
359
+ guidance_scale=4.0,
360
+ height=512,
361
+ width=512,
362
+ seed=42,
363
+ save_path="output.png"
364
+ )
365
+
366
+ # Batch generation
367
+ images = generate_batch([
368
+ "a red sports car",
369
+ "a blue ocean wave",
370
+ "a green forest path",
371
+ ], output_dir="./my_outputs")
372
+ """)