Spaces:
Sleeping
Sleeping
File size: 22,224 Bytes
0f8d59f 987fa23 0f8d59f 987fa23 0f8d59f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 | import gradio as gr
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import matplotlib.pyplot as plt
from PIL import Image
import io
import time
import math
# Configuration (same as training)
img_size = 32
img_channels = 3
clip_min = -1.0
clip_max = 1.0
total_timesteps = 1000
first_conv_channels = 64
channel_multiplier = [1, 2, 4, 8]
widths = [first_conv_channels * mult for mult in channel_multiplier]
has_attention = [False, False, True, True]
num_res_blocks = 2
norm_groups = 8
num_classes = 4
class_names = ["Airplane", "Automobile", "Bird", "Cat"]
# All the necessary classes and functions from the training script
class GaussianDiffusion:
def __init__(
self,
beta_start=1e-4,
beta_end=0.02,
timesteps=1000,
clip_min=-1.0,
clip_max=1.0,
):
self.beta_start = beta_start
self.beta_end = beta_end
self.timesteps = timesteps
self.clip_min = clip_min
self.clip_max = clip_max
# Define the linear variance schedule
self.betas = betas = np.linspace(
beta_start, beta_end, timesteps, dtype=np.float64
)
self.num_timesteps = int(timesteps)
alphas = 1.0 - betas
alphas_cumprod = np.cumprod(alphas, axis=0)
alphas_cumprod_prev = np.append(1.0, alphas_cumprod[:-1])
self.betas = tf.constant(betas, dtype=tf.float32)
self.alphas_cumprod = tf.constant(alphas_cumprod, dtype=tf.float32)
self.alphas_cumprod_prev = tf.constant(alphas_cumprod_prev, dtype=tf.float32)
self.sqrt_alphas_cumprod = tf.constant(
np.sqrt(alphas_cumprod), dtype=tf.float32
)
self.sqrt_one_minus_alphas_cumprod = tf.constant(
np.sqrt(1.0 - alphas_cumprod), dtype=tf.float32
)
self.log_one_minus_alphas_cumprod = tf.constant(
np.log(1.0 - alphas_cumprod), dtype=tf.float32
)
self.sqrt_recip_alphas_cumprod = tf.constant(
np.sqrt(1.0 / alphas_cumprod), dtype=tf.float32
)
self.sqrt_recipm1_alphas_cumprod = tf.constant(
np.sqrt(1.0 / alphas_cumprod - 1), dtype=tf.float32
)
posterior_variance = (
betas * (1.0 - alphas_cumprod_prev) / (1.0 - alphas_cumprod)
)
self.posterior_variance = tf.constant(posterior_variance, dtype=tf.float32)
self.posterior_log_variance_clipped = tf.constant(
np.log(np.maximum(posterior_variance, 1e-20)), dtype=tf.float32
)
self.posterior_mean_coef1 = tf.constant(
betas * np.sqrt(alphas_cumprod_prev) / (1.0 - alphas_cumprod),
dtype=tf.float32,
)
self.posterior_mean_coef2 = tf.constant(
(1.0 - alphas_cumprod_prev) * np.sqrt(alphas) / (1.0 - alphas_cumprod),
dtype=tf.float32,
)
def _extract(self, a, t, x_shape):
batch_size = x_shape[0]
out = tf.gather(a, t)
return tf.reshape(out, [batch_size, 1, 1, 1])
def predict_start_from_noise(self, x_t, t, noise):
x_t_shape = tf.shape(x_t)
return (
self._extract(self.sqrt_recip_alphas_cumprod, t, x_t_shape) * x_t
- self._extract(self.sqrt_recipm1_alphas_cumprod, t, x_t_shape) * noise
)
def q_posterior(self, x_start, x_t, t):
x_t_shape = tf.shape(x_t)
posterior_mean = (
self._extract(self.posterior_mean_coef1, t, x_t_shape) * x_start
+ self._extract(self.posterior_mean_coef2, t, x_t_shape) * x_t
)
posterior_variance = self._extract(self.posterior_variance, t, x_t_shape)
posterior_log_variance_clipped = self._extract(
self.posterior_log_variance_clipped, t, x_t_shape
)
return posterior_mean, posterior_variance, posterior_log_variance_clipped
def p_mean_variance(self, pred_noise, x, t, clip_denoised=True):
x_recon = self.predict_start_from_noise(x, t=t, noise=pred_noise)
if clip_denoised:
x_recon = tf.clip_by_value(x_recon, self.clip_min, self.clip_max)
model_mean, posterior_variance, posterior_log_variance = self.q_posterior(
x_start=x_recon, x_t=x, t=t
)
return model_mean, posterior_variance, posterior_log_variance
def p_sample(self, pred_noise, x, t, clip_denoised=True):
model_mean, _, model_log_variance = self.p_mean_variance(
pred_noise, x=x, t=t, clip_denoised=clip_denoised
)
noise = tf.random.normal(shape=x.shape, dtype=x.dtype)
nonzero_mask = tf.reshape(
1 - tf.cast(tf.equal(t, 0), tf.float32), [tf.shape(x)[0], 1, 1, 1]
)
return model_mean + nonzero_mask * tf.exp(0.5 * model_log_variance) * noise
def kernel_init(scale):
scale = max(scale, 1e-10)
return keras.initializers.VarianceScaling(
scale, mode="fan_avg", distribution="uniform"
)
class AttentionBlock(layers.Layer):
def __init__(self, units, groups=8, **kwargs):
self.units = units
self.groups = groups
super().__init__(**kwargs)
self.norm = layers.GroupNormalization(groups=groups)
self.query = layers.Dense(units, kernel_initializer=kernel_init(1.0))
self.key = layers.Dense(units, kernel_initializer=kernel_init(1.0))
self.value = layers.Dense(units, kernel_initializer=kernel_init(1.0))
self.proj = layers.Dense(units, kernel_initializer=kernel_init(0.0))
def call(self, inputs):
batch_size = tf.shape(inputs)[0]
height = tf.shape(inputs)[1]
width = tf.shape(inputs)[2]
scale = tf.cast(self.units, tf.float32) ** (-0.5)
inputs = self.norm(inputs)
q = self.query(inputs)
k = self.key(inputs)
v = self.value(inputs)
attn_score = tf.einsum("bhwc, bHWc->bhwHW", q, k) * scale
attn_score = tf.reshape(attn_score, [batch_size, height, width, height * width])
attn_score = tf.nn.softmax(attn_score, -1)
attn_score = tf.reshape(attn_score, [batch_size, height, width, height, width])
proj = tf.einsum("bhwHW,bHWc->bhwc", attn_score, v)
proj = self.proj(proj)
return inputs + proj
class TimeEmbedding(layers.Layer):
def __init__(self, dim, **kwargs):
super().__init__(**kwargs)
self.dim = dim
self.half_dim = dim // 2
self.emb = math.log(10000) / (self.half_dim - 1)
self.emb = tf.exp(tf.range(self.half_dim, dtype=tf.float32) * -self.emb)
def call(self, inputs):
inputs = tf.cast(inputs, dtype=tf.float32)
emb = inputs[:, None] * self.emb[None, :]
emb = tf.concat([tf.sin(emb), tf.cos(emb)], axis=-1)
return emb
class ClassEmbedding(layers.Layer):
def __init__(self, num_classes, dim, **kwargs):
super().__init__(**kwargs)
self.num_classes = num_classes
self.dim = dim
self.embedding = layers.Embedding(num_classes, dim)
def call(self, inputs):
return self.embedding(inputs)
def ResidualBlock(width, groups=8, activation_fn=keras.activations.swish):
def apply(inputs):
x, t, c = inputs
input_width = x.shape[3]
if input_width == width:
residual = x
else:
residual = layers.Conv2D(
width, kernel_size=1, kernel_initializer=kernel_init(1.0)
)(x)
temb = activation_fn(t)
temb = layers.Dense(width, kernel_initializer=kernel_init(1.0))(temb)[
:, None, None, :
]
cemb = activation_fn(c)
cemb = layers.Dense(width, kernel_initializer=kernel_init(1.0))(cemb)[
:, None, None, :
]
x = layers.GroupNormalization(groups=groups)(x)
x = activation_fn(x)
x = layers.Conv2D(
width, kernel_size=3, padding="same", kernel_initializer=kernel_init(1.0)
)(x)
x = layers.Add()([x, temb, cemb])
x = layers.GroupNormalization(groups=groups)(x)
x = activation_fn(x)
x = layers.Conv2D(
width, kernel_size=3, padding="same", kernel_initializer=kernel_init(0.0)
)(x)
x = layers.Add()([x, residual])
return x
return apply
def DownSample(width):
def apply(x):
x = layers.Conv2D(
width, kernel_size=3, strides=2, padding="same",
kernel_initializer=kernel_init(1.0)
)(x)
return x
return apply
def UpSample(width, interpolation="nearest"):
def apply(x):
x = layers.UpSampling2D(size=2, interpolation=interpolation)(x)
x = layers.Conv2D(
width, kernel_size=3, padding="same", kernel_initializer=kernel_init(1.0)
)(x)
return x
return apply
def TimeMLP(units, activation_fn=keras.activations.swish):
def apply(inputs):
temb = layers.Dense(
units, activation=activation_fn, kernel_initializer=kernel_init(1.0)
)(inputs)
temb = layers.Dense(units, kernel_initializer=kernel_init(1.0))(temb)
return temb
return apply
def build_model(
img_size, img_channels, num_classes, widths, has_attention,
num_res_blocks=2, norm_groups=8, interpolation="nearest",
activation_fn=keras.activations.swish,
):
image_input = layers.Input(
shape=(img_size, img_size, img_channels), name="image_input"
)
time_input = keras.Input(shape=(), dtype=tf.int64, name="time_input")
class_input = keras.Input(shape=(), dtype=tf.int64, name="class_input")
x = layers.Conv2D(
first_conv_channels, kernel_size=(3, 3), padding="same",
kernel_initializer=kernel_init(1.0),
)(image_input)
temb = TimeEmbedding(dim=first_conv_channels * 4)(time_input)
temb = TimeMLP(units=first_conv_channels * 4, activation_fn=activation_fn)(temb)
cemb = ClassEmbedding(num_classes, dim=first_conv_channels * 4)(class_input)
cemb = TimeMLP(units=first_conv_channels * 4, activation_fn=activation_fn)(cemb)
skips = [x]
# DownBlock
for i in range(len(widths)):
for _ in range(num_res_blocks):
x = ResidualBlock(
widths[i], groups=norm_groups, activation_fn=activation_fn
)([x, temb, cemb])
if has_attention[i]:
x = AttentionBlock(widths[i], groups=norm_groups)(x)
skips.append(x)
if widths[i] != widths[-1]:
x = DownSample(widths[i])(x)
skips.append(x)
# MiddleBlock
x = ResidualBlock(widths[-1], groups=norm_groups, activation_fn=activation_fn)(
[x, temb, cemb]
)
x = AttentionBlock(widths[-1], groups=norm_groups)(x)
x = ResidualBlock(widths[-1], groups=norm_groups, activation_fn=activation_fn)(
[x, temb, cemb]
)
# UpBlock
for i in reversed(range(len(widths))):
for _ in range(num_res_blocks + 1):
x = layers.Concatenate(axis=-1)([x, skips.pop()])
x = ResidualBlock(
widths[i], groups=norm_groups, activation_fn=activation_fn
)([x, temb, cemb])
if has_attention[i]:
x = AttentionBlock(widths[i], groups=norm_groups)(x)
if i != 0:
x = UpSample(widths[i], interpolation=interpolation)(x)
# End block
x = layers.GroupNormalization(groups=norm_groups)(x)
x = activation_fn(x)
x = layers.Conv2D(3, (3, 3), padding="same", kernel_initializer=kernel_init(0.0))(x)
return keras.Model([image_input, time_input, class_input], x, name="conditional_unet")
# Initialize model and load weights
def load_model():
"""Load the trained model"""
try:
# Build model
network = build_model(
img_size=img_size,
img_channels=img_channels,
num_classes=num_classes,
widths=widths,
has_attention=has_attention,
num_res_blocks=num_res_blocks,
norm_groups=norm_groups,
activation_fn=keras.activations.swish,
)
# Try to load weights (adjust path as needed)
try:
network.load_weights("final_ema_network.h5")
print("β
Loaded final EMA model")
except:
print("No model found")
# Initialize diffusion utilities
gdf_util = GaussianDiffusion(timesteps=total_timesteps)
return network, gdf_util
except Exception as e:
print(f"β Error loading model: {e}")
return None, None
# Global variables
model_network, gdf_util = load_model()
def tensor_to_pil(tensor):
"""Convert tensor to PIL Image"""
# Convert from [-1, 1] to [0, 255]
tensor = tf.clip_by_value(tensor * 127.5 + 127.5, 0.0, 255.0)
tensor = tf.cast(tensor, tf.uint8)
# Convert to numpy and then PIL
numpy_img = tensor.numpy()
if len(numpy_img.shape) == 4: # Batch dimension
numpy_img = numpy_img[0]
return Image.fromarray(numpy_img)
def generate_step_by_step(class_choice, show_every_n_steps=50):
"""Generate image step by step showing the denoising process"""
if model_network is None or gdf_util is None:
yield "β Model not loaded. Please ensure the model is trained and weights are available.", None
return
class_id = class_names.index(class_choice)
# Start with pure noise
sample = tf.random.normal(shape=(1, img_size, img_size, img_channels), dtype=tf.float32)
class_tensor = tf.constant([class_id], dtype=tf.int64)
yield f"π² Starting generation for: {class_choice}...", tensor_to_pil(sample)
# Reverse diffusion process
for step, t in enumerate(reversed(range(0, total_timesteps))):
tt = tf.cast(tf.fill(1, t), dtype=tf.int64)
# Predict noise
pred_noise = model_network([sample, tt, class_tensor], training=False)
# Denoise one step
sample = gdf_util.p_sample(pred_noise, sample, tt, clip_denoised=True)
# Show progress every N steps
if step % show_every_n_steps == 0 or t == 0:
progress = ((total_timesteps - t) / total_timesteps) * 100
status = f"π Denoising... Step {step+1}/{total_timesteps} ({progress:.1f}%)"
if t == 0:
status = f"β
IMAGE READY! Generated {class_choice} in {step+1} steps"
yield status, tensor_to_pil(sample)
# Final result
yield f"π **IMAGE READY!** Final {class_choice} generated successfully!", tensor_to_pil(sample)
def generate_batch_images(class_choice, num_images=4):
"""Generate multiple images at once (final result only)"""
if model_network is None or gdf_util is None:
return "β Model not loaded.", None
class_id = class_names.index(class_choice)
# Generate multiple samples
samples = tf.random.normal(
shape=(num_images, img_size, img_size, img_channels), dtype=tf.float32
)
class_tensor = tf.constant([class_id] * num_images, dtype=tf.int64)
# Full reverse diffusion (no intermediate steps shown)
for t in reversed(range(0, total_timesteps)):
tt = tf.cast(tf.fill(num_images, t), dtype=tf.int64)
pred_noise = model_network([samples, tt, class_tensor], training=False)
samples = gdf_util.p_sample(pred_noise, samples, tt, clip_denoised=True)
# Create a grid of images
samples_np = tf.clip_by_value(samples * 127.5 + 127.5, 0.0, 255.0)
samples_np = tf.cast(samples_np, tf.uint8).numpy()
# Create 2x2 grid
grid_size = int(np.sqrt(num_images))
if grid_size * grid_size < num_images:
grid_size += 1
fig, axes = plt.subplots(grid_size, grid_size, figsize=(8, 8))
fig.suptitle(f'Generated {class_choice} Images', fontsize=16)
for i in range(num_images):
row, col = i // grid_size, i % grid_size
if grid_size == 1:
axes.imshow(samples_np[i])
axes.axis('off')
else:
axes[row, col].imshow(samples_np[i])
axes[row, col].axis('off')
# Hide empty subplots
for i in range(num_images, grid_size * grid_size):
row, col = i // grid_size, i % grid_size
if grid_size > 1:
axes[row, col].axis('off')
plt.tight_layout()
# Convert matplotlib figure to PIL Image
buf = io.BytesIO()
plt.savefig(buf, format='png', bbox_inches='tight', dpi=100)
buf.seek(0)
grid_image = Image.open(buf)
plt.close()
return f"β
Generated {num_images} {class_choice} images!", grid_image
# Create Gradio interface
def create_interface():
with gr.Blocks(title="Conditional DDPM - CIFAR-10 Generator", theme=gr.themes.Soft()) as demo:
gr.Markdown("""
# π¨ Conditional DDPM Image Generator
### CIFAR-10 Classes: Airplane, Automobile, Bird, Cat
Choose between **Step-by-Step** generation (watch the denoising process) or **Batch** generation (multiple images at once).
""")
with gr.Tabs():
# Tab 1: Step-by-step generation
with gr.TabItem("π Step-by-Step Generation"):
gr.Markdown("Watch the model denoise step by step!")
with gr.Row():
with gr.Column(scale=1):
class_input1 = gr.Dropdown(
choices=class_names,
value="Airplane",
label="Choose Class",
info="Select what you want to generate"
)
step_interval = gr.Slider(
minimum=10,
maximum=100,
value=50,
step=10,
label="Show Every N Steps",
info="How often to update the image (lower = more updates)"
)
generate_btn1 = gr.Button("π² Generate Step-by-Step", variant="primary", size="lg")
with gr.Column(scale=2):
status_text = gr.Textbox(
label="Generation Status",
interactive=False,
max_lines=2
)
output_image1 = gr.Image(
label="Generated Image",
type="pil",
height=400,
width=400
)
generate_btn1.click(
fn=generate_step_by_step,
inputs=[class_input1, step_interval],
outputs=[status_text, output_image1],
show_progress=True
)
# Tab 2: Batch generation
with gr.TabItem("π― Batch Generation"):
gr.Markdown("Generate multiple images at once (faster)!")
with gr.Row():
with gr.Column(scale=1):
class_input2 = gr.Dropdown(
choices=class_names,
value="Airplane",
label="Choose Class"
)
num_images = gr.Slider(
minimum=1,
maximum=9,
value=4,
step=1,
label="Number of Images",
info="How many images to generate"
)
generate_btn2 = gr.Button("π Generate Batch", variant="primary", size="lg")
with gr.Column(scale=2):
batch_status = gr.Textbox(
label="Status",
interactive=False
)
output_image2 = gr.Image(
label="Generated Images Grid",
type="pil",
height=500,
width=500
)
generate_btn2.click(
fn=generate_batch_images,
inputs=[class_input2, num_images],
outputs=[batch_status, output_image2],
show_progress=True
)
# Footer
gr.Markdown("""
---
**Note:** Make sure you have trained the model and the weights are available in the `conditional_ddmp_cifar10/` directory.
- **Step-by-Step**: Shows the denoising process in real-time with enlarged images (32x32 β 256x256)
- **Batch**: Generates multiple images quickly with enhanced grid display
- **Image Quality**: Images are upscaled using nearest-neighbor interpolation to preserve pixel details
π **Tip**: Use lower step intervals (10-20) for smoother real-time updates, higher intervals (50-100) for faster generation.
""")
return demo
if __name__ == "__main__":
# Check if model is loaded
if model_network is None:
print("β οΈ WARNING: Model not loaded. Make sure you have:")
print(" 1. Trained the conditional DDPM model")
print(" 2. Model weights saved in 'conditional_ddpm_cifar10/' directory")
print(" 3. Either 'final_ema_network.h5' or epoch checkpoints available")
print("\nπ Starting Gradio app anyway (will show error messages)...")
else:
print("β
Model loaded successfully!")
print("π Starting Gradio app...")
# Create and launch the interface
demo = create_interface()
demo.launch(
share=False, # Set to True if you want a public link
server_name="0.0.0.0",
server_port=7860,
show_error=True
) |