File size: 10,817 Bytes
3ed0796 |
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 |
import gradio as gr
import spaces # type: ignore - ZeroGPU spaces library
import numpy as np
import random
import torch
import functools
from pathlib import Path
from PIL import Image
from omegaconf import OmegaConf # type: ignore - YAML configuration library
from tim.schedulers.transition import TransitionSchedule
from tim.utils.misc_utils import instantiate_from_config, init_from_ckpt
from tim.models.vae import get_sd_vae, get_dc_ae, sd_vae_decode, dc_ae_decode
from tim.models.utils.text_encoders import load_text_encoder, encode_prompt
# from kernels import get_kernel
# Configuration
dtype = torch.bfloat16
device = "cuda" if torch.cuda.is_available() else "cpu"
MAX_SEED = np.iinfo(np.int32).max
MAX_IMAGE_SIZE = 2048
# Global variables to store loaded components
model = None
scheduler = None
decode_func = None
config = None
text_encoder = None
tokenizer = None
def load_model_components(device: str = "cuda"):
"""Load all model components once at startup"""
global model, scheduler, decode_func, config, text_encoder, tokenizer
try:
# Load configuration
config_path = "configs/t2i/tim_xl_p1_t2i.yaml"
from huggingface_hub import hf_hub_download
ckpt_path = hf_hub_download(
repo_id="blanchon/TiM-checkpoints", filename="t2i_model.bin"
)
if not Path(config_path).exists():
raise FileNotFoundError(f"Config file not found: {config_path}")
if not Path(ckpt_path).exists():
raise FileNotFoundError(f"Checkpoint file not found: {ckpt_path}")
print("Loading configuration...")
config = OmegaConf.load(config_path)
model_config = config.model
print("Loading VAE...")
# Load VAE
if "dc-ae" in model_config.vae_dir:
dc_ae = get_dc_ae(model_config.vae_dir, dtype=torch.float32, device=device)
dc_ae.enable_tiling(2560, 2560, 2560, 2560)
decode_func = functools.partial(dc_ae_decode, dc_ae, slice_vae=True)
elif "sd-vae" in model_config.vae_dir:
sd_vae = get_sd_vae(
model_config.vae_dir, dtype=torch.float32, device=device
)
decode_func = functools.partial(sd_vae_decode, sd_vae, slice_vae=True)
else:
raise ValueError("Unsupported VAE type")
# Load text encoder
text_encoder, tokenizer = load_text_encoder(
text_encoder_dir=config.model.text_encoder_dir,
device=device,
weight_dtype=dtype,
)
print("Loading main model...")
# Load main model
model = instantiate_from_config(model_config.network).to(
device=device, dtype=dtype
)
init_from_ckpt(model, checkpoint_dir=ckpt_path, ignore_keys=None, verbose=True)
model.eval()
print("Loading scheduler...")
# Load scheduler
transport = instantiate_from_config(model_config.transport)
scheduler = TransitionSchedule(
transport=transport, **OmegaConf.to_container(model_config.transition_loss)
)
print("All components loaded successfully!")
except Exception as e:
print(f"Error loading model components: {e}")
raise e
@spaces.GPU(duration=60)
def generate_image(
prompt,
seed=42,
randomize_seed=False,
width=1024,
height=1024,
guidance_scale=2.5,
num_inference_steps=16,
progress=gr.Progress(track_tqdm=True),
):
"""Generate image from text prompt"""
try:
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Using device: {device}")
# Validate inputs
if not prompt or len(prompt.strip()) == 0:
raise ValueError("Please enter a valid prompt")
if model is None or scheduler is None:
raise RuntimeError("Model components not loaded. Please check the setup.")
# Validate dimensions
if (
width < 256
or width > MAX_IMAGE_SIZE
or height < 256
or height > MAX_IMAGE_SIZE
):
raise ValueError(
f"Image dimensions must be between 256 and {MAX_IMAGE_SIZE}"
)
if width % 32 != 0 or height % 32 != 0:
raise ValueError("Image dimensions must be divisible by 32")
if randomize_seed:
seed = random.randint(0, MAX_SEED)
generator = torch.Generator(device=device).manual_seed(seed)
# Calculate latent dimensions
spatial_downsample = 32 if "dc-ae" in config.model.vae_dir else 8
latent_h = int(height / spatial_downsample)
latent_w = int(width / spatial_downsample)
progress(0.1, desc="Generating random latent...")
# Generate random latent
z = torch.randn(
(1, model.in_channels, latent_h, latent_w),
device=device,
dtype=dtype,
generator=generator,
)
progress(0.1, desc="Loading text encoder...")
# Load text encoder
text_encoder.set_attn_implementation("flash_attention_2")
text_encoder.to(device)
# Encode prompt
cap_features, cap_mask = encode_prompt(
tokenizer,
text_encoder.model,
device,
dtype,
[prompt],
config.model.use_last_hidden_state,
max_seq_length=config.model.max_seq_length,
)
# Encode null caption for CFG
null_cap_feat, null_cap_mask = encode_prompt(
tokenizer,
text_encoder.model,
device,
dtype,
[""],
config.model.use_last_hidden_state,
max_seq_length=config.model.max_seq_length,
)
cur_max_seq_len = cap_mask.sum(dim=-1).max()
y = cap_features[:, :cur_max_seq_len]
y_null = null_cap_feat[:, :cur_max_seq_len]
y_null = y_null.expand(y.shape[0], cur_max_seq_len, null_cap_feat.shape[-1])
# Generate image
with torch.no_grad():
samples = scheduler.sample(
model,
y,
y_null,
z,
T_max=1.0,
T_min=0.0,
num_steps=num_inference_steps,
cfg_scale=guidance_scale,
cfg_low=0.0,
cfg_high=1.0,
stochasticity_ratio=0.0,
sample_type="transition",
step_callback=lambda step: progress(
0.1 + 0.9 * (step / num_inference_steps), desc="Generating image..."
),
)[-1]
samples = samples.to(torch.float32)
# Decode to image
images = decode_func(samples)
images = (
torch.clamp(127.5 * images + 128.0, 0, 255)
.permute(0, 2, 3, 1)
.to(torch.uint8)
.contiguous()
)
image = Image.fromarray(images[0].cpu().numpy())
progress(1.0, desc="Complete!")
return image, seed
except Exception as e:
print(f"Error during image generation: {e}")
# Return a placeholder image or error message
error_img = Image.new("RGB", (512, 512), color="red")
return error_img, seed
# Example prompts
examples = [
["a tiny astronaut hatching from an egg on the moon"],
["πΆ Wearing πΆ flying on the π"],
["an anime illustration of a wiener schnitzel"],
["a photorealistic landscape of mountains at sunset"],
["a majestic lion in a golden savanna at sunset"],
["a futuristic city with flying cars and neon lights"],
["a cozy cabin in a snowy forest with smoke coming from the chimney"],
["a beautiful mermaid swimming in crystal clear water"],
]
# CSS styling
css = """
#col-container {
margin: 0 auto;
max-width: 520px;
}
"""
# Initialize model components
try:
# flash_attn = get_kernel("kernels-community/flash-attn")
load_model_components(device)
print("Model components loaded successfully!")
except Exception as e:
print(f"Error loading model components: {e}")
print("Please ensure config and checkpoint files are available")
# Create Gradio interface
with gr.Blocks(css=css) as demo:
with gr.Column(elem_id="col-container"):
gr.Markdown("# TiM Text-to-Image Generator")
gr.Markdown(
"Generate high-quality images from text prompts using the TiM (Transition in Matching) model"
)
with gr.Row():
prompt = gr.Text(
label="Prompt",
show_label=False,
max_lines=1,
placeholder="Enter your prompt",
container=False,
)
run_button = gr.Button("Generate", scale=0)
result = gr.Image(label="Result", show_label=False)
with gr.Accordion("Advanced Settings", open=False):
seed = gr.Slider(
label="Seed",
minimum=0,
maximum=MAX_SEED,
step=1,
value=0,
)
randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
with gr.Row():
width = gr.Slider(
label="Width",
minimum=256,
maximum=MAX_IMAGE_SIZE,
step=32,
value=1024,
)
height = gr.Slider(
label="Height",
minimum=256,
maximum=MAX_IMAGE_SIZE,
step=32,
value=1024,
)
with gr.Row():
guidance_scale = gr.Slider(
label="Guidance Scale",
minimum=1,
maximum=15,
step=0.1,
value=2.5,
)
num_inference_steps = gr.Slider(
label="Number of inference steps",
minimum=1,
maximum=50,
step=1,
value=16,
)
gr.Examples(
examples=examples,
fn=generate_image,
inputs=[prompt],
outputs=[result, seed],
cache_examples=True,
cache_mode="lazy",
)
gr.on(
triggers=[run_button.click, prompt.submit],
fn=generate_image,
inputs=[
prompt,
seed,
randomize_seed,
width,
height,
guidance_scale,
num_inference_steps,
],
outputs=[result, seed],
)
if __name__ == "__main__":
demo.launch()
|