Instructions to use TheHuggerFacer/Pyramid-Flow-100M with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use TheHuggerFacer/Pyramid-Flow-100M with Transformers:
# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("TheHuggerFacer/Pyramid-Flow-100M", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Publish Pyramid Flow inference weights and Transformers usage
#1
by TheHuggerFacer - opened
- README.md +38 -0
- config.json +8 -0
- configuration_pyramid_flow.py +8 -0
- model.safetensors +3 -0
- modeling_pyramid_flow.py +251 -0
- requirements.txt +6 -0
README.md
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
library_name: transformers
|
| 3 |
+
pipeline_tag: text-to-image
|
| 4 |
+
tags:
|
| 5 |
+
- text-to-image
|
| 6 |
+
- custom_code
|
| 7 |
+
---
|
| 8 |
+
|
| 9 |
+
# Pyramid Flow 100M
|
| 10 |
+
|
| 11 |
+
Pyramid Flow generates 256 × 256 RGB images from English prompts. The model runs on CPU or CUDA with Hugging Face Transformers. It uses the T5-base text encoder and the SD-VAE decoder, which download separately on first use.
|
| 12 |
+
|
| 13 |
+
## Generate an image
|
| 14 |
+
|
| 15 |
+
Install the dependencies in `requirements.txt`, then run the following Python example.
|
| 16 |
+
|
| 17 |
+
```python
|
| 18 |
+
import torch
|
| 19 |
+
from transformers import AutoModel
|
| 20 |
+
|
| 21 |
+
repo = "TheHuggerFacer/Pyramid-Flow-100M"
|
| 22 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 23 |
+
model = AutoModel.from_pretrained(repo, trust_remote_code=True).eval().to(device)
|
| 24 |
+
|
| 25 |
+
image = model.generate_image(
|
| 26 |
+
"A clockwork owl perched on a brass telescope, studio photograph",
|
| 27 |
+
seed=42,
|
| 28 |
+
num_inference_steps=20,
|
| 29 |
+
guidance_scale=4.0,
|
| 30 |
+
)[0]
|
| 31 |
+
image.save("clockwork-owl.png")
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
Pass a list of prompts to generate a batch. The method returns one PIL image per prompt. A fixed seed makes it easier to compare prompts on the same device. A guidance scale of 1 uses the conditional prediction directly. Object counts, spatial relations and fine details can be inconsistent.
|
| 35 |
+
|
| 36 |
+
The text encoder and decoder are distributed separately under their respective terms. [T5-base](https://huggingface.co/google-t5/t5-base) · [SD-VAE](https://huggingface.co/stabilityai/sd-vae-ft-mse)
|
| 37 |
+
|
| 38 |
+
The inference implementation uses attention, rotary embeddings and timestep components adapted from [tinydit](https://github.com/ivanmikhnenkov/tinydit).
|
config.json
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model_type": "pyramid_flow",
|
| 3 |
+
"architectures": ["PyramidFlowModel"],
|
| 4 |
+
"auto_map": {
|
| 5 |
+
"AutoConfig": "configuration_pyramid_flow.PyramidFlowConfig",
|
| 6 |
+
"AutoModel": "modeling_pyramid_flow.PyramidFlowModel"
|
| 7 |
+
}
|
| 8 |
+
}
|
configuration_pyramid_flow.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import PretrainedConfig
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class PyramidFlowConfig(PretrainedConfig):
|
| 5 |
+
model_type = "pyramid_flow"
|
| 6 |
+
|
| 7 |
+
def __init__(self, **kwargs):
|
| 8 |
+
super().__init__(**kwargs)
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f7f30f97d4a146ada03f4061481ba34c9ec0b696912d77e3465e948e16e03dcb
|
| 3 |
+
size 399085296
|
modeling_pyramid_flow.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Inference for Pyramid Flow."""
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from torch import nn
|
| 7 |
+
from torch.nn import functional as F
|
| 8 |
+
from transformers import PreTrainedModel
|
| 9 |
+
|
| 10 |
+
from .configuration_pyramid_flow import PyramidFlowConfig
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class RMSNorm(nn.Module):
|
| 14 |
+
"""nn.RMSNorm keeps fp32 weights; under bf16 autocast that mismatch falls back to an
|
| 15 |
+
unfused kernel (PyTorch warns). Casting the weight to the activation dtype fixes it."""
|
| 16 |
+
def __init__(self, dim: int, eps: float = 1e-6):
|
| 17 |
+
super().__init__()
|
| 18 |
+
self.eps = eps
|
| 19 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 20 |
+
|
| 21 |
+
def forward(self, x):
|
| 22 |
+
return F.rms_norm(x, (x.shape[-1],), self.weight.to(x.dtype), self.eps)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class TimestepEmbed(nn.Module):
|
| 26 |
+
def __init__(self, dim: int, freq_dim: int = 256):
|
| 27 |
+
super().__init__()
|
| 28 |
+
self.freq_dim = freq_dim
|
| 29 |
+
self.mlp = nn.Sequential(nn.Linear(freq_dim, dim), nn.SiLU(), nn.Linear(dim, dim))
|
| 30 |
+
|
| 31 |
+
def forward(self, t: torch.Tensor) -> torch.Tensor: # t: (B,) in [0,1]
|
| 32 |
+
half = self.freq_dim // 2
|
| 33 |
+
f = torch.exp(-math.log(10000) * torch.arange(half, device=t.device) / half)
|
| 34 |
+
a = t.float().reshape(-1, 1) * 1000.0 * f[None]
|
| 35 |
+
return self.mlp(torch.cat([a.cos(), a.sin()], dim=-1).to(self.mlp[0].weight.dtype))
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class CrossAttention(nn.Module):
|
| 39 |
+
def __init__(self, dim, heads, ctx_dim, n_null=2):
|
| 40 |
+
super().__init__()
|
| 41 |
+
self.h, self.dh, self.n_null = heads, dim // heads, n_null
|
| 42 |
+
self.q = nn.Linear(dim, dim, bias=False)
|
| 43 |
+
self.kv = nn.Linear(ctx_dim, 2 * dim, bias=False)
|
| 44 |
+
self.proj = nn.Linear(dim, dim, bias=False)
|
| 45 |
+
self.qn = RMSNorm(self.dh)
|
| 46 |
+
self.kn = RMSNorm(self.dh)
|
| 47 |
+
# learned null key/value slots, in projected space, always attendable
|
| 48 |
+
self.null_kv = nn.Parameter(torch.randn(2, n_null, dim) * 0.02) if n_null else None
|
| 49 |
+
nn.init.zeros_(self.proj.weight) # block starts as a no-op on the residual
|
| 50 |
+
|
| 51 |
+
def forward(self, x, ctx, ctx_mask):
|
| 52 |
+
B, N, _ = x.shape
|
| 53 |
+
k, v = self.kv(ctx).chunk(2, dim=-1)
|
| 54 |
+
if self.null_kv is not None:
|
| 55 |
+
nk, nv = self.null_kv.to(k.dtype).unsqueeze(1).expand(-1, B, -1, -1)
|
| 56 |
+
k, v = torch.cat([k, nk], 1), torch.cat([v, nv], 1)
|
| 57 |
+
if ctx_mask is not None:
|
| 58 |
+
ctx_mask = torch.cat([ctx_mask, ctx_mask.new_ones(B, self.n_null)], 1)
|
| 59 |
+
L = k.shape[1]
|
| 60 |
+
q = self.q(x).view(B, N, self.h, self.dh).transpose(1, 2)
|
| 61 |
+
k, v = (t.view(B, L, self.h, self.dh).transpose(1, 2) for t in (k, v))
|
| 62 |
+
q, k = self.qn(q), self.kn(k)
|
| 63 |
+
m = ctx_mask[:, None, None, :] if ctx_mask is not None else None
|
| 64 |
+
o = F.scaled_dot_product_attention(q, k, v, attn_mask=m)
|
| 65 |
+
return self.proj(o.transpose(1, 2).reshape(B, N, -1))
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def rotate(t: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
|
| 69 |
+
"""t: (B, heads, N, head_dim); cos/sin: (N, head_dim//2)"""
|
| 70 |
+
a, b = t.chunk(2, dim=-1)
|
| 71 |
+
cos = cos.to(t.dtype)[None, None]
|
| 72 |
+
sin = sin.to(t.dtype)[None, None]
|
| 73 |
+
return torch.cat([a * cos - b * sin, a * sin + b * cos], dim=-1)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class PyramidBlock(nn.Module):
|
| 77 |
+
def __init__(self, width, heads, hidden, modulation_width, *, xsa=False):
|
| 78 |
+
super().__init__()
|
| 79 |
+
self.heads = heads
|
| 80 |
+
self.head_width = width // heads
|
| 81 |
+
self.pre_attn = RMSNorm(width)
|
| 82 |
+
self.post_attn = RMSNorm(width)
|
| 83 |
+
self.pre_ffn = RMSNorm(width)
|
| 84 |
+
self.post_ffn = RMSNorm(width)
|
| 85 |
+
self.q_norm = RMSNorm(self.head_width)
|
| 86 |
+
self.k_norm = RMSNorm(self.head_width)
|
| 87 |
+
self.qkv = nn.Linear(width, 3 * width)
|
| 88 |
+
self.xsa = xsa
|
| 89 |
+
self.head_gate = nn.Linear(width, heads) if modulation_width is not None and not xsa else None
|
| 90 |
+
self.attn_out = nn.Linear(width, width)
|
| 91 |
+
self.ffn_in = nn.Linear(width, 2 * hidden, bias=False)
|
| 92 |
+
self.ffn_out = nn.Linear(hidden, width, bias=False)
|
| 93 |
+
self.modulation = None
|
| 94 |
+
if modulation_width is not None:
|
| 95 |
+
self.modulation = nn.Linear(modulation_width, 4 * width)
|
| 96 |
+
nn.init.zeros_(self.modulation.weight)
|
| 97 |
+
nn.init.zeros_(self.modulation.bias)
|
| 98 |
+
|
| 99 |
+
def forward(self, tokens, condition=None, mask=None, rotary=None):
|
| 100 |
+
x = self.pre_attn(tokens)
|
| 101 |
+
if self.modulation is not None:
|
| 102 |
+
scale_a, gate_a, scale_f, gate_f = self.modulation(condition)[:, None].chunk(4, dim=-1)
|
| 103 |
+
x = x * (1 + scale_a)
|
| 104 |
+
b, n, width = x.shape
|
| 105 |
+
q, k, v = self.qkv(x).reshape(b, n, 3, self.heads, self.head_width).permute(2, 0, 3, 1, 4)
|
| 106 |
+
q, k = self.q_norm(q), self.k_norm(k)
|
| 107 |
+
if rotary is not None:
|
| 108 |
+
q, k = rotate(q, *rotary), rotate(k, *rotary)
|
| 109 |
+
attn = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
|
| 110 |
+
if self.xsa:
|
| 111 |
+
own_value = F.normalize(v.float(), dim=-1)
|
| 112 |
+
attn_float = attn.float()
|
| 113 |
+
attn = (attn_float - (attn_float * own_value).sum(-1, keepdim=True) * own_value).to(attn.dtype)
|
| 114 |
+
attn = attn.transpose(1, 2)
|
| 115 |
+
if self.head_gate is not None:
|
| 116 |
+
attn = attn * self.head_gate(x).sigmoid().unsqueeze(-1)
|
| 117 |
+
attn_update = self.post_attn(self.attn_out(attn.reshape(b, n, width)))
|
| 118 |
+
tokens = tokens + (gate_a.tanh() * attn_update if self.modulation is not None else attn_update)
|
| 119 |
+
x = self.pre_ffn(tokens)
|
| 120 |
+
if self.modulation is not None:
|
| 121 |
+
x = x * (1 + scale_f)
|
| 122 |
+
value, gate = self.ffn_in(x).chunk(2, dim=-1)
|
| 123 |
+
ffn_update = self.post_ffn(self.ffn_out(F.silu(gate) * value))
|
| 124 |
+
return tokens + (gate_f.tanh() * ffn_update if self.modulation is not None else ffn_update)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class PixelReadout(nn.Module):
|
| 128 |
+
def __init__(self, width, patch, channels=3):
|
| 129 |
+
super().__init__()
|
| 130 |
+
self.patch = patch
|
| 131 |
+
self.channels = channels
|
| 132 |
+
self.norm = nn.LayerNorm(width)
|
| 133 |
+
self.modulation = nn.Parameter(torch.zeros(2, width))
|
| 134 |
+
self.out = nn.Linear(width, channels * patch * patch)
|
| 135 |
+
|
| 136 |
+
def forward(self, tokens, time_embedding, grid, grid_width=None):
|
| 137 |
+
modulation = self.modulation if time_embedding is None else time_embedding[:, None] + self.modulation
|
| 138 |
+
shift, scale = modulation.unbind(-2)
|
| 139 |
+
pixels = self.out(self.norm(tokens) * (1 + scale.unsqueeze(-2)) + shift.unsqueeze(-2))
|
| 140 |
+
p = self.patch
|
| 141 |
+
grid_width = grid if grid_width is None else grid_width
|
| 142 |
+
return pixels.reshape(-1, grid, grid_width, p, p, self.channels).permute(0, 5, 1, 3, 2, 4).reshape(
|
| 143 |
+
-1, self.channels, grid * p, grid_width * p)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
class PyramidFlowModel(PreTrainedModel):
|
| 147 |
+
"""256-pixel text-to-image denoiser. Forward returns velocity in normalized latent space."""
|
| 148 |
+
|
| 149 |
+
config_class = PyramidFlowConfig
|
| 150 |
+
main_input_name = "latents"
|
| 151 |
+
|
| 152 |
+
def __init__(self, config):
|
| 153 |
+
super().__init__(config)
|
| 154 |
+
width = 608
|
| 155 |
+
self.image_stem = nn.Linear(16, width)
|
| 156 |
+
self.text_stem = nn.Sequential(nn.LayerNorm(768), nn.Linear(768, width), nn.SiLU(), nn.Linear(width, width))
|
| 157 |
+
self.time = TimestepEmbed(width)
|
| 158 |
+
self.modulation = nn.Linear(width, 128)
|
| 159 |
+
self.stages = ((0, 4, 4), (4, 8, 8), (8, 16, 16))
|
| 160 |
+
shared = {i for first, end, _ in self.stages for i in range(first + 1, end - 1)}
|
| 161 |
+
self.blocks = nn.ModuleList(PyramidBlock(width, 8, 1568, 128, xsa=i in shared) for i in range(16))
|
| 162 |
+
self.cross_norms = nn.ModuleList(RMSNorm(width) for _ in self.blocks)
|
| 163 |
+
self.cross = nn.ModuleList(CrossAttention(width, 8, width, n_null=2) for _ in self.blocks)
|
| 164 |
+
self.full = PixelReadout(width, 2, channels=4)
|
| 165 |
+
self.child_offsets = nn.Parameter(torch.zeros(2, 2, 2, width))
|
| 166 |
+
for _, _, side in self.stages:
|
| 167 |
+
for name in ("cos", "sin"):
|
| 168 |
+
self.register_buffer(f"{name}_{side}", torch.empty(side * side, 38))
|
| 169 |
+
self.register_buffer("latent_mean", torch.empty(1, 256, 16))
|
| 170 |
+
self.register_buffer("latent_scale", torch.empty(1, 256, 16))
|
| 171 |
+
self.post_init()
|
| 172 |
+
|
| 173 |
+
@staticmethod
|
| 174 |
+
def _pack(spatial):
|
| 175 |
+
batch, channels, side, _ = spatial.shape
|
| 176 |
+
grid = side // 2
|
| 177 |
+
return spatial.reshape(batch, channels, grid, 2, grid, 2).permute(0, 2, 4, 1, 3, 5).reshape(batch, grid * grid, 16)
|
| 178 |
+
|
| 179 |
+
@staticmethod
|
| 180 |
+
def _unpack(latents):
|
| 181 |
+
return latents.reshape(-1, 16, 16, 4, 2, 2).permute(0, 3, 1, 4, 2, 5).reshape(-1, 4, 32, 32)
|
| 182 |
+
|
| 183 |
+
def forward(self, latents, noise_fraction, encoder_hidden_states, attention_mask):
|
| 184 |
+
dtype = self.image_stem.weight.dtype
|
| 185 |
+
spatial = self._unpack(latents.to(dtype))
|
| 186 |
+
text = self.text_stem(encoder_hidden_states.to(dtype))
|
| 187 |
+
embedding = self.time(1 - noise_fraction)
|
| 188 |
+
condition = self.modulation(F.silu(embedding))
|
| 189 |
+
for stage, (first, end, side) in enumerate(self.stages):
|
| 190 |
+
stage_input = self.image_stem(self._pack(F.avg_pool2d(spatial, 16 // side))) if side < 16 else self.image_stem(latents.to(dtype))
|
| 191 |
+
if stage == 0:
|
| 192 |
+
image = stage_input
|
| 193 |
+
else:
|
| 194 |
+
parents = image.reshape(len(latents), side // 2, side // 2, -1)
|
| 195 |
+
children = parents[:, :, None, :, None, :] + self.child_offsets[stage - 1].to(image.dtype)[None, None, :, None, :, :]
|
| 196 |
+
image = children.reshape_as(stage_input) + stage_input
|
| 197 |
+
rotary = getattr(self, f"cos_{side}"), getattr(self, f"sin_{side}")
|
| 198 |
+
order = [first] + list(range(first + 1, end - 1)) * 4 + [end - 1]
|
| 199 |
+
for i in order:
|
| 200 |
+
image = self.blocks[i](image, condition, rotary=rotary)
|
| 201 |
+
image = image + self.cross[i](self.cross_norms[i](image), text, attention_mask)
|
| 202 |
+
clean = self._pack(self.full(image, embedding, 16).float())
|
| 203 |
+
return (clean - latents.float()) / noise_fraction[:, None, None].clamp_min(1e-6)
|
| 204 |
+
|
| 205 |
+
@torch.inference_mode()
|
| 206 |
+
def generate_image(self, prompt, *, seed=0, num_inference_steps=20, guidance_scale=4.0,
|
| 207 |
+
tokenizer=None, text_encoder=None, vae=None):
|
| 208 |
+
"""Return a list of PIL RGB images for a string or list of strings."""
|
| 209 |
+
from diffusers import AutoencoderKL
|
| 210 |
+
from PIL import Image
|
| 211 |
+
from transformers import AutoTokenizer, T5EncoderModel
|
| 212 |
+
|
| 213 |
+
prompts = [prompt] if isinstance(prompt, str) else list(prompt)
|
| 214 |
+
if not prompts or not all(isinstance(p, str) for p in prompts):
|
| 215 |
+
raise ValueError("Supply a prompt or a nonempty list of prompts")
|
| 216 |
+
if not isinstance(num_inference_steps, int) or num_inference_steps < 1:
|
| 217 |
+
raise ValueError("num_inference_steps must be a positive integer")
|
| 218 |
+
device = self.image_stem.weight.device
|
| 219 |
+
t5 = "google-t5/t5-base"
|
| 220 |
+
revision = "a9723ea7f1b39c1eae772870f3b547bf6ef7e6c1"
|
| 221 |
+
if tokenizer is None:
|
| 222 |
+
tokenizer = AutoTokenizer.from_pretrained(t5, revision=revision)
|
| 223 |
+
if text_encoder is None:
|
| 224 |
+
text_encoder = T5EncoderModel.from_pretrained(t5, revision=revision)
|
| 225 |
+
if vae is None:
|
| 226 |
+
vae = AutoencoderKL.from_pretrained("stabilityai/sd-vae-ft-mse",
|
| 227 |
+
revision="31f26fdeee1355a5c34592e401dd41e45d25a493")
|
| 228 |
+
text_encoder = text_encoder.eval().to(device)
|
| 229 |
+
vae = vae.eval().to(device)
|
| 230 |
+
tokens = tokenizer(prompts, max_length=120, padding="max_length", truncation=True, return_tensors="pt").to(device)
|
| 231 |
+
mask = tokens.attention_mask.bool()
|
| 232 |
+
text = text_encoder(**tokens).last_hidden_state.masked_fill(~mask.unsqueeze(-1), 0)
|
| 233 |
+
null_mask = torch.zeros_like(mask)
|
| 234 |
+
null_mask[:, 0] = True
|
| 235 |
+
null_text = torch.zeros_like(text)
|
| 236 |
+
rng = torch.Generator(device=device).manual_seed(seed)
|
| 237 |
+
x = torch.randn(len(prompts), 256, 16, device=device, generator=rng)
|
| 238 |
+
tau = 1 - torch.linspace(0, 1, num_inference_steps + 1, device=device)
|
| 239 |
+
times = 1 - 2.8 * tau / (1 + 1.8 * tau)
|
| 240 |
+
with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda" and torch.cuda.is_bf16_supported()):
|
| 241 |
+
for start, end in zip(times[:-1], times[1:]):
|
| 242 |
+
t = (1 - start).expand(len(x))
|
| 243 |
+
velocity = self(x, t, text, mask)
|
| 244 |
+
if guidance_scale != 1:
|
| 245 |
+
null = self(x, t, null_text, null_mask)
|
| 246 |
+
velocity = null + guidance_scale * (velocity - null)
|
| 247 |
+
x = x + (end - start) * velocity
|
| 248 |
+
z = self._unpack(x.float() * self.latent_scale.float() + self.latent_mean.float())
|
| 249 |
+
rgb = vae.decode(z.to(vae.dtype) / vae.config.scaling_factor).sample.float()
|
| 250 |
+
pixels = (rgb.clamp(-1, 1).add(1).mul(127.5)).round().to(torch.uint8).permute(0, 2, 3, 1).cpu()
|
| 251 |
+
return [Image.fromarray(frame.numpy()) for frame in pixels]
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch>=2.6
|
| 2 |
+
transformers>=4.51.3,<5
|
| 3 |
+
diffusers>=0.33.1,<0.36
|
| 4 |
+
safetensors>=0.4.5
|
| 5 |
+
sentencepiece>=0.2
|
| 6 |
+
Pillow>=10
|