Views
No views yet
bfloat16 precision for ultra-fast and memory-efficient inference.
runwayml/stable-diffusion-v1-5lambdalabs/naruto-blip-captionsbfloat16), you should use the FlaxStableDiffusionPipeline to run it.1import jax
2import jax.numpy as jnp
3from diffusers import FlaxStableDiffusionPipeline
4from flax.training import checkpoints
5from huggingface_hub import snapshot_download
6
7# 1. Download the fine-tuned weights
8repo_id = "NiceWang/sd-naruto-tpu"
9ckpt_dir = snapshot_download(repo_id=repo_id)
10
11# 2. Load the base Stable Diffusion v1.5 pipeline
12pipe, params = FlaxStableDiffusionPipeline.from_pretrained(
13 "runwayml/stable-diffusion-v1-5",
14 dtype=jnp.bfloat16,
15 from_pt=True,
16 safety_checker=None,
17)
18
19# 3. Replace the base UNet with our fine-tuned Naruto UNet
20from flax.core import unfreeze
21params = unfreeze(params)
22raw_ckpt = checkpoints.restore_checkpoint(ckpt_dir=ckpt_dir, target=None)
23params["unet"] = raw_ckpt["params"]
24
25# 4. Run Inference!
26prompt = "A drawing of Kakashi Hatake"
27prompt_ids = pipe.prepare_inputs([prompt])
28prng_seed = jax.random.PRNGKey(42)
29
30output = pipe(
31 prompt_ids=prompt_ids,
32 params=params,
33 prng_seed=prng_seed,
34 num_inference_steps=50,
35 guidance_scale=7.5,
36 jit=True,
37)
38
39# Convert to PIL Image
40import numpy as np
41images_np = np.asarray(output.images)
42images_pil = pipe.numpy_to_pil(images_np)
43images_pil[0].show()npz format for inference:1import os
2import jax
3import jax.numpy as jnp
4import numpy as np
5from diffusers import FlaxStableDiffusionPipeline
6from flax.core import unfreeze
7from huggingface_hub import hf_hub_download, snapshot_download
8
9# 1. Download the fine-tuned weights (npz format, no orbax dependency)
10npz_path = hf_hub_download(
11 repo_id="NiceWang/sd-naruto-tpu",
12 filename="unet_naruto_bf16.npz"
13)
14
15# 2. Load the base Stable Diffusion v1.5 pipeline
16pipe, params = FlaxStableDiffusionPipeline.from_pretrained(
17 "runwayml/stable-diffusion-v1-5",
18 dtype=jnp.bfloat16,
19 from_pt=True,
20 safety_checker=None,
21)
22
23# 3. Replace the base UNet with our fine-tuned Naruto UNet
24# Reconstruct nested param dict from flat npz keys (e.g. "a/b/c" -> {"a":{"b":{"c":...}}})
25def unflatten(flat):
26 result = {}
27 for key, val in flat.items():
28 parts = key.split("/")
29 d = result
30 for part in parts[:-1]:
31 d = d.setdefault(part, {})
32 d[parts[-1]] = val
33 return result
34
35data = np.load(npz_path)
36unet_np = unflatten(dict(data))
37
38params = unfreeze(params)
39params["unet"] = jax.tree_util.tree_map(
40 lambda x: jnp.array(x, dtype=jnp.bfloat16), unet_np
41)
42
43# 4. Run Inference!
44prompt = "A drawing of Kakashi Hatake"
45prompt_ids = pipe.prepare_inputs([prompt])
46prng_seed = jax.random.PRNGKey(42)
47
48output = pipe(
49 prompt_ids=prompt_ids,
50 params=params,
51 prng_seed=prng_seed,
52 num_inference_steps=50,
53 guidance_scale=7.5,
54 jit=True,
55)
56
57# Convert to PIL Image
58images_np = np.asarray(output.images)
59images_pil = pipe.numpy_to_pil(images_np)
60images_pil[0].show()1import torch
2import jax
3from diffusers import FlaxUNet2DConditionModel, UNet2DConditionModel, StableDiffusionPipeline
4from flax.training import checkpoints
5from huggingface_hub import snapshot_download
6from IPython.display import display
7
8BASE_REPO_ID = "stable-diffusion-v1-5/stable-diffusion-v1-5"
9
10# 1. Download raw Flax checkpoint from Hugging Face
11repo_id = "NiceWang/sd-naruto-tpu"
12print(f"Downloading raw Flax checkpoint from {repo_id}...")
13ckpt_dir = snapshot_download(repo_id=repo_id)
14
15# 2. Create A dummy target template
16print("Loading base UNet CONFIG to create a structural template...")
17config = FlaxUNet2DConditionModel.load_config(BASE_REPO_ID, subfolder="unet")
18flax_unet = FlaxUNet2DConditionModel.from_config(config)
19
20# Generate dummy parameters just to get the exact dictionary structure for Orbax
21key = jax.random.PRNGKey(0)
22dummy_params = flax_unet.init_weights(key)
23target_template = {"params": dummy_params}
24
25# 3. Restore and unshard fine-tuned weights using the dummy template
26print("Restoring sharded checkpoint into single-device memory...")
27raw_ckpt = checkpoints.restore_checkpoint(ckpt_dir=ckpt_dir, target=target_template)
28fine_tuned_unet_params = raw_ckpt["params"]
29
30# Save it to a temporary local folder with fine-tuned params
31print("Converting raw weights to standard Diffusers format...")
32temp_flax_dir = "./temp_flax_unet"
33flax_unet.save_pretrained(temp_flax_dir, params=fine_tuned_unet_params)
34
35# # 4. Load into PyTorch
36# print("Loading Flax weights into PyTorch UNet...")
37# pt_unet = UNet2DConditionModel.from_pretrained(
38# temp_flax_dir,
39# from_flax=True,
40# torch_dtype=torch.float16
41# )
42
43# 4. Load into PyTorch
44print("Loading Flax weights into PyTorch UNet manually...")
45
46from diffusers.models.modeling_pytorch_flax_utils import load_flax_checkpoint_in_pytorch_model
47
48# a. Initialize a blank PyTorch UNet using the structure from config
49pt_unet = UNet2DConditionModel.from_config(temp_flax_dir)
50
51# b. Use the internal Diffusers tool to safely inject the Flax .msgpack weights
52msgpack_file = f"{temp_flax_dir}/diffusion_flax_model.msgpack"
53pt_unet = load_flax_checkpoint_in_pytorch_model(pt_unet, msgpack_file)
54
55# c. Cast it to float16 for optimal GPU inference
56pt_unet = pt_unet.to(torch.float16)
57
58# 5. Run Inference on GPU using PyTorch
59print("Setting up PyTorch Stable Diffusion Pipeline on GPU...")
60pipe = StableDiffusionPipeline.from_pretrained(
61 BASE_REPO_ID,
62 torch_dtype=torch.float16,
63 safety_checker=None
64)
65pipe.unet = pt_unet
66pipe = pipe.to("cuda")
67
68prompt = "A drawing of Kakashi Hatake"
69print(f"Generating image for prompt: '{prompt}'...")
70
71image = pipe(prompt, num_inference_steps=50, guidance_scale=7.5).images[0]
72
73print("Done! Here is your PyTorch-generated image:")
74display(image)