Spaces:
Running on Zero
Running on Zero
File size: 14,306 Bytes
1119475 5b816dc 1119475 108ad3e 1119475 0229e1c 1119475 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 | import spaces # must come before torch / diffusers
import random
import threading
import types
import gradio as gr
import numpy as np
import torch
import torch.nn.functional as F
from diffusers import Krea2Pipeline
from diffusers.models.modeling_outputs import Transformer2DModelOutput
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import AutoProcessor
BASE_MODEL = "krea/Krea-2-Turbo"
SREF_REPO = "lyraaaa/krea2-sref-adapter"
SPACES = {"default": "sref_space.npz", "lg": "sref_space_lg.npz", "variant": "sref_space_variant.npz"}
IMAGE_FILE, IMAGE_SPACE = "sref_image.npz", "variant"
STYLE_SIZE = 540.0
SEARCH = 1_000_000
TOKENS, SUFFIX = 108, 5
LOOSEN_RAMP = (1.0, 0.5, 0.25)
MAX_CODE = 2**32 - 1
MAX_SEED = 2**31 - 1
RESOLUTIONS = {
"Square 1024×1024": (1024, 1024),
"Portrait 832×1216": (832, 1216),
"Landscape 1216×832": (1216, 832),
}
# ---------------------------------------------------------------- style spaces
_spaces = {}
for _name, _file in SPACES.items():
_f = np.load(hf_hub_download(SREF_REPO, _file), allow_pickle=False)
_spaces[_name] = (_f["basis"].astype(np.float32), _f["sd"].astype(np.float32))
_img = np.load(hf_hub_download(SREF_REPO, IMAGE_FILE), allow_pickle=False)
IMG_ENCODE = torch.from_numpy(_img["encode"].astype(np.float32)).reshape(64, -1)
IMG_BIAS = _img["bias"].astype(np.float32)
IMG_GRAM = _img["gram"].astype(np.float64)
def coords(code, name="default"):
_, sd = _spaces[name]
return np.random.default_rng(int(code)).standard_normal(len(sd)).astype(np.float32) * sd
def block_from_coords(z, strength, name="default"):
basis, _ = _spaces[name]
return torch.from_numpy(strength * np.tensordot(np.asarray(z, dtype=np.float32), basis, axes=1)) # [108, 6144]
# nearest-code search table for "style from image" (built in the background at startup)
_codes = {}
def _build_code_table():
w = np.linalg.cholesky(IMG_GRAM).T.astype(np.float32)
z = np.stack([coords(k, IMAGE_SPACE) for k in range(SEARCH)]) @ w.T
_codes.update(w=w, z=z / np.linalg.norm(z, axis=1, keepdims=True))
threading.Thread(target=_build_code_table, daemon=True).start()
def nearest_code(a):
if "z" not in _codes:
return None, None
q = _codes["w"] @ a
sims = _codes["z"] @ (q / np.linalg.norm(q))
k = int(sims.argmax())
return k, float(sims[k])
# ---------------------------------------------------------------- model
pipe = Krea2Pipeline.from_pretrained(BASE_MODEL, torch_dtype=torch.bfloat16)
pipe.to("cuda")
processor = AutoProcessor.from_pretrained("Qwen/Qwen3-VL-4B-Instruct")
# Per-call sref state read by the patched transformer forward.
STATE = {"block": None, "loosen": 0.0, "calls": 0, "per_step": 1}
def sref_forward(self, hidden_states, encoder_hidden_states, timestep, position_ids,
encoder_attention_mask=None, attention_kwargs=None, return_dict=True):
"""Krea2Transformer2DModel.forward with the sref block appended to the prompt tokens after
text fusion + projection (like the ComfyUI node's txtmlp wrapper), plus the optional 'loosen' bias."""
batch_size, image_seq_len, _ = hidden_states.shape
device = hidden_states.device
call = STATE["calls"]
STATE["calls"] += 1
step = call // STATE["per_step"]
is_cond = call % STATE["per_step"] == 0 # with CFG the pipeline runs the positive pass first
temb = self.time_embed(timestep, dtype=hidden_states.dtype)
temb_mod = self.time_mod_proj(F.gelu(temb, approximate="tanh"))
text_attention_mask = None if encoder_attention_mask is None else encoder_attention_mask[:, None, None, :]
enc = self.text_fusion(encoder_hidden_states, attention_mask=text_attention_mask)
enc = self.txt_in(enc)
text_len = enc.shape[1]
if encoder_attention_mask is None:
encoder_attention_mask = torch.ones(batch_size, text_len, dtype=torch.bool, device=device)
block = STATE["block"]
n_style = 0
if block is not None:
add = block.to(device=device, dtype=enc.dtype)[None].expand(batch_size, -1, -1)
if not is_cond: # style on the positive prompt only (ComfyUI zeroes it on the negative)
add = torch.zeros_like(add)
enc = torch.cat([enc, add], dim=1)
n_style = TOKENS
position_ids = torch.cat([position_ids.new_zeros(n_style, 3), position_ids], dim=0)
valid = torch.cat([
encoder_attention_mask,
encoder_attention_mask.new_ones(batch_size, n_style + image_seq_len),
], dim=1)
loosen = STATE["loosen"]
if loosen and step < len(LOOSEN_RAMP):
# Additive bias on the prompt's word tokens (not the 5 chat-suffix tokens, not the style tokens).
bias = torch.zeros(batch_size, valid.shape[1], device=device, dtype=hidden_states.dtype)
bias[:, : text_len - SUFFIX] = -loosen * LOOSEN_RAMP[step]
bias = bias.masked_fill(~valid, float("-inf"))
attention_mask = bias[:, None, None, :]
else:
attention_mask = valid[:, None, None, :]
x = self.img_in(hidden_states)
x = torch.cat([enc, x], dim=1)
rope = self.rotary_emb(position_ids)
for blk in self.transformer_blocks:
x = blk(x, temb_mod, rope, attention_mask)
x = x[:, text_len + n_style:]
out = self.final_layer(x, temb)
if not return_dict:
return (out,)
return Transformer2DModelOutput(sample=out)
pipe.transformer.forward = types.MethodType(sref_forward, pipe.transformer)
PICTURE = ("<|im_start|>system\nDescribe the image by detailing the color, shape, size, texture, quantity, text, spatial "
"relationships of the objects and background:<|im_end|>\n<|im_start|>user\nPicture 1: "
"<|vision_start|><|image_pad|><|vision_end|><|im_end|>\n<|im_start|>assistant\n")
@torch.no_grad()
def read_image_style(image: Image.Image):
"""64 style coordinates (variant space) read from an image, as in the ComfyUI 'Sref From Image' node."""
im = image.convert("RGB").resize((256, 384), Image.LANCZOS)
inputs = processor(text=[PICTURE], images=[im], return_tensors="pt").to("cuda")
ids = inputs["input_ids"][0].tolist()
starts = [i for i, t in enumerate(ids) if t == 151644] # <|im_start|>
begin = starts[1] + 3 # strip system turn + "<|im_start|>user\n"
enc_inputs = dict(inputs)
enc_inputs["pixel_values"] = enc_inputs["pixel_values"].to(torch.bfloat16)
out = pipe.text_encoder(**enc_inputs, output_hidden_states=True)
hs = torch.stack([out.hidden_states[i] for i in pipe.text_encoder_select_layers], dim=2)[:, begin:]
if hs.shape[1] != TOKENS:
raise gr.Error(f"Expected {TOKENS} tokens from the picture, got {hs.shape[1]}.")
tr = pipe.transformer
block = tr.txt_in(tr.text_fusion(hs.to(torch.bfloat16), attention_mask=None)).float()[0] # [108, 6144]
a = (IMG_ENCODE.to(block.device) @ block.reshape(-1)).cpu().numpy() - IMG_BIAS
return a
def _gpu_duration(prompt, code=0, style_image=None, style_source="Code", strength=6.0, space="default",
loosen=0.0, resolution="", seed=0, randomize_seed=False, steps=8, progress=None):
# measured ~1.2 s/step at 1024² + VAE/text encode; image reading adds a few seconds
return int(6 + 1.5 * int(steps) + (5 if style_source == "Image" else 0))
@spaces.GPU(duration=_gpu_duration)
def generate(
prompt: str,
code: float = 768519172,
style_image: Image.Image | None = None,
style_source: str = "Code",
strength: float = 6.0,
space: str = "default",
loosen: float = 0.0,
resolution: str = "Square 1024×1024",
seed: float = 0,
randomize_seed: bool = False,
steps: float = 8,
progress=gr.Progress(track_tqdm=True),
):
"""Generate an image with Krea 2 Turbo in a style chosen by a whole-number style code (sref) or read from an image.
Args:
prompt: Text prompt.
code: Style code, 0..4294967295. Same code = same style on any prompt and seed.
style_image: Reference image whose style is read (used when style_source is "Image").
style_source: "Code" or "Image".
strength: Style strength. 6 = full restyle, 3 = light, 0 = off; image styles may want 9-12.
space: Style space for codes: default, lg or variant.
loosen: Weakens the prompt's words for the first 3 steps so the style shapes the layout. 0 = off.
resolution: Output size preset.
seed: Noise seed.
randomize_seed: Pick a random seed.
steps: Denoising steps (8 for Turbo).
Returns:
The generated image, the seed used, and a short info string.
"""
prompt = (prompt or "").strip()
if randomize_seed:
seed = random.randint(0, MAX_SEED)
seed = int(seed)
code = int(code) % (MAX_CODE + 1)
strength = float(strength)
info = ""
if style_source == "Image":
if style_image is None:
raise gr.Error("Upload a style reference image, or switch the style source to Code.")
a = read_image_style(style_image)
size = float(np.sqrt(a @ IMG_GRAM @ a))
block = block_from_coords(a * (STYLE_SIZE / size), strength, IMAGE_SPACE) if strength else None
k, sim = nearest_code(a)
info = (f"Style read from image. Nearest code: {k} (space 'variant', similarity {sim:.3f})"
if k is not None else "Style read from image (nearest-code index still building).")
else:
block = block_from_coords(coords(code, space), strength, space) if strength else None
info = f"Code {code} · space '{space}' · strength {strength:g}"
width, height = RESOLUTIONS.get(resolution, (1024, 1024))
STATE.update(block=block, loosen=float(loosen), calls=0, per_step=1)
try:
image = pipe(
prompt=prompt,
width=width,
height=height,
num_inference_steps=int(steps),
guidance_scale=0.0, # Turbo: cfg 1 in ComfyUI terms
generator=torch.Generator("cuda").manual_seed(seed),
).images[0]
finally:
STATE.update(block=None, loosen=0.0, calls=0)
return image, seed, info
def random_code():
return random.randint(0, MAX_CODE)
CSS = "#col { max-width: 1200px; margin: 0 auto; }"
with gr.Blocks(title="Krea 2 Sref") as demo:
with gr.Column(elem_id="col"):
gr.Markdown(
"# Krea 2 Sref — style references as numbers\n"
"Every whole number is a style: [lyraaaa/krea2-sref-adapter](https://huggingface.co/lyraaaa/krea2-sref-adapter) "
"turns a code into 108 extra prompt tokens for [Krea 2 Turbo](https://huggingface.co/krea/Krea-2-Turbo). "
"The same code gives the same look on any prompt and seed. You can also read a style from an image."
)
with gr.Row():
with gr.Column():
prompt = gr.Textbox(label="Prompt", value="a lighthouse on a rocky coast", lines=2)
style_source = gr.Radio(["Code", "Image"], value="Code", label="Style source")
with gr.Row():
code = gr.Number(label="Style code (0 – 4294967295)", value=768519172, precision=0, scale=4)
dice = gr.Button("🎲 Random code", scale=1)
style_image = gr.Image(label="Style reference image (for 'Image' source)", type="pil", height=260)
strength = gr.Slider(0, 12, value=6.0, step=0.1, label="Strength",
info="6 full restyle · 3 light · 0 off · >10 overpowers the prompt")
run = gr.Button("Generate", variant="primary")
with gr.Accordion("Advanced", open=False):
space = gr.Dropdown(list(SPACES), value="default", label="Style space",
info="The same code is a different style in each space")
loosen = gr.Slider(0, 4, value=0.0, step=0.1, label="Loosen",
info="Prompt words count less in the first 3 steps so the style shapes the picture")
resolution = gr.Dropdown(list(RESOLUTIONS), value="Square 1024×1024", label="Resolution")
steps = gr.Slider(4, 16, value=8, step=1, label="Steps")
with gr.Row():
seed = gr.Number(label="Seed", value=0, precision=0)
randomize_seed = gr.Checkbox(label="Randomize seed", value=False)
with gr.Column():
result = gr.Image(label="Result", height=560)
seed_used = gr.Number(label="Seed used", interactive=False)
info = gr.Textbox(label="Info", interactive=False)
gr.Examples(
label="Style codes (from the author's sheets)",
examples=[
["a lighthouse on a rocky coast", 768519172],
["an astronaut riding a horse", 3395250012],
["an old man reading a newspaper in a cafe", 1569714666],
["a woman", 2212568278],
],
inputs=[prompt, code],
outputs=[result, seed_used, info],
fn=generate,
cache_examples=True,
cache_mode="lazy",
)
gr.Examples(
label="Style from an image",
examples=[
["a cat sitting on a windowsill", 768519172, "examples/van_gogh_starry_night.jpg", "Image"],
["a lighthouse on a rocky coast", 768519172, "examples/af_klint_ten_largest.jpg", "Image"],
["a cat sitting on a windowsill", 768519172, "examples/hokusai_red_fuji.jpg", "Image"],
["a lighthouse on a rocky coast", 768519172, "examples/mucha_job.jpg", "Image"],
],
inputs=[prompt, code, style_image, style_source],
outputs=[result, seed_used, info],
fn=generate,
cache_examples=True,
cache_mode="lazy",
)
dice.click(random_code, outputs=code)
inputs = [prompt, code, style_image, style_source, strength, space, loosen, resolution, seed, randomize_seed, steps]
gr.on([run.click, prompt.submit], generate, inputs=inputs, outputs=[result, seed_used, info])
if __name__ == "__main__":
demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)
|