Views
No views yet
1from diffusers import StableDiffusionPipeline
2import torch
3from torchvision.utils import save_image
4
5pipe = StableDiffusionPipeline.from_pretrained("benetraco/latent_finetuning", torch_dtype=torch.float32).to("cuda")
6pipe.scheduler.set_timesteps(999)
7
8def get_embeddings(prompt):
9 tokens = pipe.tokenizer(prompt, return_tensors="pt", padding="max_length", max_length=77).to("cuda")
10 return pipe.text_encoder(**tokens).last_hidden_state
11
12def sample(prompt, guidance_scale=2.0, seed=42):
13 torch.manual_seed(seed)
14 latent = torch.randn(1, 4, 32, 32).to("cuda") * pipe.scheduler.init_noise_sigma
15 text_emb = get_embeddings(prompt)
16 uncond_emb = get_embeddings("")
17
18 for t in pipe.scheduler.timesteps:
19 latent_in = pipe.scheduler.scale_model_input(latent, t)
20 with torch.no_grad():
21 noise_uncond = pipe.unet(latent_in, t, encoder_hidden_states=uncond_emb).sample
22 noise_text = pipe.unet(latent_in, t, encoder_hidden_states=text_emb).sample
23 noise = noise_uncond + guidance_scale * (noise_text - noise_uncond)
24 latent = pipe.scheduler.step(noise, t, latent).prev_sample
25
26 latent /= pipe.vae.config.scaling_factor
27 with torch.no_grad():
28 decoded = pipe.vae.decode(latent).sample
29 image = (decoded + 1.0) / 2.0
30 image = image.clamp(0, 1)
31 save_image(image, f"{prompt.replace(' ', '_')}_g{guidance_scale}.png")
32
33sample("SHIFTS FLAIR MRI", guidance_scale=5.0)