Views
No views yet
| Hyperparameter | Value |
|---|---|
learning_rate | 1e-05 |
num_train_epochs | 40 |
train_batch_size | 2 |
gradient_accumulation_steps | 2 |
mixed_precision | "fp16" |
resolution | 512 |
max_grad_norm | 1 |
lr_scheduler | "constant" |
lr_warmup_steps | 0 |
checkpoints_total_limit | 1 |
use_ema | True |
use_8bit_adam | True |
center_crop | True |
random_flip | True |
gradient_checkpointing | True |
1import torch
2from PIL import Image
3import numpy as np
4from transformers import CLIPTextModel, CLIPTokenizer
5from diffusers import AutoencoderKL, UNet2DConditionModel, PNDMScheduler
6from tqdm import tqdm1# Configure device and data type
2device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
3dtype = torch.float16 if torch.cuda.is_available() else torch.float32
4
5# Model path
6model_name = "danhtran2mind/ghibli-fine-tuned-sd-2.1"
7
8# Load model components
9vae = AutoencoderKL.from_pretrained(model_name, subfolder="vae", torch_dtype=dtype).to(device)
10tokenizer = CLIPTokenizer.from_pretrained(model_name, subfolder="tokenizer")
11text_encoder = CLIPTextModel.from_pretrained(model_name, subfolder="text_encoder", torch_dtype=dtype).to(device)
12unet = UNet2DConditionModel.from_pretrained(model_name, subfolder="unet", torch_dtype=dtype).to(device)
13scheduler = PNDMScheduler.from_pretrained(model_name, subfolder="scheduler")1def generate_image(prompt, height=512, width=512, num_inference_steps=50, guidance_scale=3.5, seed=42):
2 """Generate a Ghibli-style image from a text prompt."""
3 # Set random seed for reproducibility
4 generator = torch.Generator(device=device).manual_seed(int(seed))
5
6 # Tokenize and encode the prompt
7 text_input = tokenizer(
8 [prompt], padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt"
9 )
10 with torch.no_grad():
11 text_embeddings = text_encoder(text_input.input_ids.to(device))[0].to(dtype=dtype)
12
13 # Encode an empty prompt for classifier-free guidance
14 uncond_input = tokenizer(
15 [""], padding="max_length", max_length=text_input.input_ids.shape[-1], return_tensors="pt"
16 )
17 with torch.no_grad():
18 uncond_embeddings = text_encoder(uncond_input.input_ids.to(device))[0].to(dtype=dtype)
19
20 text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
21
22 # Initialize latent representations
23 latents = torch.randn(
24 (1, unet.config.in_channels, height // 8, width // 8),
25 generator=generator,
26 dtype=dtype,
27 device=device
28 )
29
30 # Configure scheduler timesteps
31 scheduler.set_timesteps(num_inference_steps)
32 latents = latents * scheduler.init_noise_sigma
33
34 # Denoising loop
35 for t in tqdm(scheduler.timesteps, desc="Generating image"):
36 latent_model_input = torch.cat([latents] * 2)
37 latent_model_input = scheduler.scale_model_input(latent_model_input, t)
38
39 with torch.no_grad():
40 if device.type == "cuda":
41 with torch.autocast(device_type="cuda", dtype=torch.float16):
42 noise_pred = unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
43 else:
44 noise_pred = unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
45
46 # Apply classifier-free guidance
47 noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
48 noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
49 latents = scheduler.step(noise_pred, t, latents).prev_sample
50
51 # Decode latents to image
52 with torch.no_grad():
53 latents = latents / vae.config.scaling_factor
54 image = vae.decode(latents).sample
55
56 # Convert to PIL Image
57 image = (image / 2 + 0.5).clamp(0, 1)
58 image = image.detach().cpu().permute(0, 2, 3, 1).numpy()
59 image = (image * 255).round().astype("uint8")
60 return Image.fromarray(image[0])1# Example prompt
2prompt = "a serene landscape in Ghibli style"
3
4# Generate the image
5image = generate_image(
6 prompt=prompt,
7 height=512,
8 width=512,
9 num_inference_steps=50,
10 guidance_scale=3.5,
11 seed=42
12)
13
14# Display or save the image
15image.show() # Or image.save("ghibli_landscape.png")| Library | Version |
|---|---|
| huggingface-hub | 0.30.2 |
| accelerate | 1.3.0 |
| bitsandbytes | 0.45.5 |
| torch | 2.5.1 |
| Pillow | 11.1.0 |
| numpy | 1.26.4 |
| transformers | 4.51.1 |
| torchvision | 0.20.1 |
| diffusers | 0.33.1 |
| gradio | Latest |