SadikNawazAI's picture
Add model card, config, training logs, samples and join script
f40cc92 verified
Raw History Blame Contribute Delete
6.79 kB
"""Standalone sampler for SadikNawazAI/sadik-image-ai-tiny-ddpm.
This file intentionally has no dependency on the SADIK IMAGE AI application.
It loads the published checkpoint, its tokenizer and its architecture config.
pip install torch diffusers pillow
python sample.py --prompt "a cyan star on a deep purple background" --out star.png
The model is a 64x64 pixel-space DDPM trained from scratch. It is a demo of a
complete training pipeline, not a photorealistic image model.
"""
from __future__ import annotations
import argparse
import json
import re
from pathlib import Path
import torch
from diffusers import DDIMScheduler, DDPMScheduler, UNet2DConditionModel
from PIL import Image
from torch import nn
class TinyTextToImage(nn.Module):
def __init__(self, vocab_size: int, sample_size: int = 64, cross_dim: int = 192,
block_out_channels: tuple[int, ...] = (64, 128, 256)):
super().__init__()
self.sample_size = int(sample_size)
self.cross_dim = int(cross_dim)
self.unet = UNet2DConditionModel(
sample_size=sample_size,
in_channels=3,
out_channels=3,
layers_per_block=1,
block_out_channels=tuple(block_out_channels),
down_block_types=("DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D"),
up_block_types=("AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D"),
cross_attention_dim=cross_dim,
attention_head_dim=8,
norm_num_groups=32,
)
self.token_embedding = nn.Embedding(vocab_size, cross_dim)
self.embed_norm = nn.LayerNorm(cross_dim)
def forward(self, sample: torch.Tensor, timestep: torch.Tensor, input_ids: torch.Tensor) -> torch.Tensor:
mask = (input_ids != 0).float().unsqueeze(-1)
embeddings = self.embed_norm(self.token_embedding(input_ids)) * mask
return self.unet(sample, timestep, encoder_hidden_states=embeddings, return_dict=False)[0]
class SimpleTokenizer:
TOKEN_RE = re.compile(r"[a-z0-9']+")
PAD, UNK, BOS, EOS = "<pad>", "<unk>", "<bos>", "<eos>"
def __init__(self, data: dict):
self.vocab: dict[str, int] = data["vocab"]
self.max_length = int(data.get("max_length", 32))
@classmethod
def load(cls, path: Path) -> "SimpleTokenizer":
return cls(json.loads(path.read_text(encoding="utf-8")))
def encode(self, text: str) -> list[int]:
words = self.TOKEN_RE.findall((text or "").lower())[: self.max_length - 2]
ids = (
[self.vocab[self.BOS]]
+ [self.vocab.get(word, self.vocab[self.UNK]) for word in words]
+ [self.vocab[self.EOS]]
)
return ids + [self.vocab[self.PAD]] * (self.max_length - len(ids))
def join_parts(checkpoint: Path) -> Path:
"""Join the published checkpoint parts into tiny_model.pt if needed."""
target = checkpoint / "tiny_model.pt"
if target.is_file():
return target
parts = sorted(checkpoint.glob("tiny_model.pt.part*"))
if not parts:
raise FileNotFoundError(f"No tiny_model.pt or parts found in {checkpoint}")
temporary = target.with_name("tiny_model.pt.joining")
with temporary.open("wb") as out:
for part in parts:
out.write(part.read_bytes())
temporary.replace(target)
print(f"joined {len(parts)} checkpoint parts into {target}")
return target
def find_checkpoint(folder: Path) -> Path:
candidates = [folder, folder / "final"]
candidates += sorted(folder.glob("checkpoint-*"))
for candidate in candidates:
if (candidate / "tiny_model.pt").is_file() or any(candidate.glob("tiny_model.pt.part*")):
join_parts(candidate)
return candidate
raise FileNotFoundError(f"No tiny_model.pt or checkpoint parts found in {folder}")
def generate(
checkpoint: Path,
prompt: str,
steps: int = 400,
seed: int = 1234,
sampler: str = "ddpm",
) -> Image.Image:
config = json.loads((checkpoint / "model_config.json").read_text(encoding="utf-8"))
tokenizer = SimpleTokenizer.load(checkpoint / "tokenizer.json")
model = TinyTextToImage(
vocab_size=int(config["vocab_size"]),
sample_size=int(config.get("sample_size", 64)),
cross_dim=int(config.get("cross_dim", 192)),
block_out_channels=tuple(config.get("block_out_channels", [64, 128, 256])),
)
state = torch.load(checkpoint / "tiny_model.pt", map_location="cpu", weights_only=False)
model.load_state_dict(state["state_dict"])
model.eval()
if sampler == "ddim":
scheduler = DDIMScheduler(
num_train_timesteps=1000,
beta_start=0.0001,
beta_end=0.02,
beta_schedule="linear",
clip_sample=True,
set_alpha_to_one=False,
)
else:
scheduler = DDPMScheduler(
num_train_timesteps=1000,
beta_start=0.0001,
beta_end=0.02,
beta_schedule="linear",
prediction_type="epsilon",
)
scheduler.set_timesteps(max(2, min(1000, int(steps))))
generator = torch.Generator(device="cpu").manual_seed(int(seed))
size = int(config.get("sample_size", 64))
sample = torch.randn((1, 3, size, size), generator=generator)
ids = torch.tensor([tokenizer.encode(prompt)], dtype=torch.long)
with torch.inference_mode():
for timestep in scheduler.timesteps:
prediction = model(sample, torch.tensor([int(timestep)], dtype=torch.long), ids)
sample = scheduler.step(prediction, timestep, sample).prev_sample
sample = (sample.clamp(-1, 1) + 1.0) / 2.0
array = sample[0].mul(255).round().byte().permute(1, 2, 0).numpy()
return Image.fromarray(array, mode="RGB")
def main() -> int:
parser = argparse.ArgumentParser(description="Sample the SADIK Tiny DDPM checkpoint")
parser.add_argument("--checkpoint", default=str(Path(__file__).resolve().parent))
parser.add_argument("--prompt", required=True)
parser.add_argument("--steps", type=int, default=400)
parser.add_argument("--sampler", choices=("ddpm", "ddim"), default="ddpm")
parser.add_argument("--seed", type=int, default=1234)
parser.add_argument("--out", default="sample.png")
args = parser.parse_args()
checkpoint = find_checkpoint(Path(args.checkpoint))
image = generate(checkpoint, args.prompt, args.steps, args.seed, args.sampler)
target = Path(args.out)
target.parent.mkdir(parents=True, exist_ok=True)
image.save(target)
print(
f"saved {target} ({image.width}x{image.height}) from {checkpoint} "
f"with {args.sampler.upper()} {args.steps} steps"
)
return 0
if __name__ == "__main__":
raise SystemExit(main())