Instructions to use recoilme/ra4 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusers
How to use recoilme/ra4 with Diffusers:
pip install -U diffusers transformers accelerate
import torch from diffusers import DiffusionPipeline # switch to "mps" for apple devices pipe = DiffusionPipeline.from_pretrained("recoilme/ra4", dtype=torch.bfloat16, device_map="cuda") prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k" image = pipe(prompt).images[0] - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- Draw Things
- DiffusionBee
File size: 9,476 Bytes
eb8084e | 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 | #!/usr/bin/env python3
"""Оценка чекпойнта: вклад подписи по бакетам t, сетки при разных cfg/шагах.
python3 src/eval.py --model tmp/run1/last.pt --cache tmp/allphoto --out tmp/eval
Числа:
* gain по бакетам t — 1 − MSE(текст)/MSE(пусто) при фиксированных z0 и t.
Вблизи шума (t<0.3) подпись — единственная информация о содержании, поэтому
именно там виде�� вклад текста; усреднение по всей t-сетке его размывает;
* dx — расстояние между латентами, снятыми с ОДНИМ шумом и разными подписями
(если модель игнорирует текст, dx → 0);
* detail — средний |∇| картинки против настоящих картинок из кэша.
"""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
import torch
import torch.nn.functional as F
from PIL import Image
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(Path(__file__).resolve().parent))
from data import Latents # noqa: E402
from model import DEV, x_to_v # noqa: E402
from sample import load # noqa: E402
from text import ClipText # noqa: E402
from train import detail_score, null_rows # noqa: E402
from vae_adapter import VAE # noqa: E402
PROMPTS = [
"A young woman with blonde hair holding a white teacup in a restaurant.",
"A close-up photo of a blue butterfly on a yellow flower, sharp focus.",
"A wooden cabin in a snowy forest at night, warm light in the windows.",
"An oil painting of a fishing boat on a calm sea at sunrise.",
"A crowd of people crossing a busy city street in the rain, neon reflections.",
"A bowl of ripe red strawberries on a white marble table, soft light.",
]
def decode(ae, z, chunk: int = 4):
out = [ae.decode_raw(z[i:i + chunk] * ae.latent_std + ae.latent_mean) for i in range(0, z.shape[0], chunk)]
return torch.cat(out, 0).clamp(-1, 1)
def retrieval(m, enc, data, t_values=(0.2, 0.5, 0.8), n=16, seed=0) -> None:
"""Работает ли подпись: своя подпись против среднего по чужим, по каждой картинке.
Топ-1 «какая подпись от этой картинки» для этого не годится: если сигнал текста
мал (а он мал на ранних шагах), ранжирование картинок определяется самими
картинками, и метрика показывает ровно случайный уровень для любой модели.
Здесь считается delta_j = mse(своя подпись) − mean(mse(чужие)) на картинку j.
delta < 0 означает, что модель действительно опирается на подпись.
"""
z0, caps = data.val_batch(n)
z0 = z0.to(DEV)
hs, mk = enc.encode(list(caps), pad_to_len=enc.max_len)
txt = m.encode_text(hs)
g = torch.Generator(DEV).manual_seed(seed)
print(f"\nработает ли подпись ({n} картинок; delta<0 = своя подпись лучше; SE в скобках)")
print(f" {'t':>4s} {'delta':>11s} {'SE':>9s} {'сигма':>6s} {'своя лучше':>11s}")
for t_val in t_values:
eb = torch.randn(z0.shape, generator=g, device=DEV)
xt = (1 - t_val) * eb + t_val * z0
target = z0 - eb
t = torch.full((n,), t_val, device=DEV)
mse = torch.zeros(n, n, device=DEV)
with torch.no_grad(), torch.autocast(DEV, torch.bfloat16, enabled=DEV == "cuda"):
for i in range(n):
pred = m.body(xt, t, txt[i:i + 1].expand(n, -1, -1), mk[i:i + 1].expand(n, -1))
if m.cfg.predict == "x":
pred = x_to_v(pred.float(), xt, t)
mse[i] = (pred.float() - target).pow(2).mean(dim=(1, 2, 3))
own = mse.diag()
other = (mse.sum(0) - own) / (n - 1)
delta = own - other
se = float(delta.std()) / n ** 0.5
print(f" {t_val:4.1f} {float(delta.mean()):+11.5f} {se:9.5f} "
f"{abs(float(delta.mean())) / max(se, 1e-12):6.1f} "
f"{float((delta < 0).float().mean()):11.0%}")
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--model", required=True)
ap.add_argument("--cache", default="")
ap.add_argument("--out", default=str(ROOT / "tmp" / "eval"))
ap.add_argument("--vae", default=str(ROOT / "vae"))
ap.add_argument("--text", default=str(ROOT / "text_encoder"))
ap.add_argument("--text-len", type=int, default=192)
ap.add_argument("--shift", type=float, default=0.3)
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--retrieval", action="store_true", help="тест «какая подпись от этой картинки»")
a = ap.parse_args()
out = Path(a.out)
out.mkdir(parents=True, exist_ok=True)
ae = VAE.from_pretrained(a.vae, DEV)
enc = ClipText(a.text, DEV, max_len=a.text_len)
m, sd = load(Path(a.model))
m.to(DEV).eval()
lat = 32
# ---- вклад подписи по бакетам t
if a.cache:
d = Latents(a.cache)
if a.retrieval:
retrieval(m, enc, d)
z0, caps = d.val_batch(48)
z0 = z0.to(DEV)
hs, mk = enc.encode(list(caps), pad_to_len=a.text_len)
txt = m.encode_text(hs)
nt, nm = null_rows(txt, mk, m.null_text)
print(f"\nвклад подписи (48 отложенных пар, фиксированные z0 и t):")
print(f" {'бакет t':12s} {'mse(текст)':>11s} {'mse(пусто)':>11s} {'gain':>8s} {'базовая':>9s}")
g = torch.Generator(DEV).manual_seed(a.seed)
for name, lo, hi in (("t < 0.3", 0.0, 0.3), ("0.3-0.7", 0.3, 0.7), ("t > 0.7", 0.7, 1.0)):
t = lo + (hi - lo) * torch.rand(z0.shape[0], generator=g, device=DEV)
eb = torch.randn(z0.shape, generator=g, device=DEV)
xt = (1 - t[:, None, None, None]) * eb + t[:, None, None, None] * z0
with torch.no_grad(), torch.autocast(DEV, torch.bfloat16, enabled=DEV == "cuda"):
x1 = m.body(xt, t, txt, mk).float()
x2 = m.body(xt, t, nt, nm).float()
if m.cfg.predict == "x":
# см. train.evaluate: для x-prediction мерим в x, иначе 1/(1−t)² врёт
mse, mse_n = F.mse_loss(x1, z0).item(), F.mse_loss(x2, z0).item()
else:
mse = F.mse_loss(x1, (z0 - eb)).item()
mse_n = F.mse_loss(x2, (z0 - eb)).item()
base = float(((xt - z0) if m.cfg.predict == "x" else (z0 - eb)).pow(2).mean())
print(f" {name:12s} {mse:11.4f} {mse_n:11.4f} {1 - mse / mse_n:+8.1%} {base:9.4f}")
with torch.no_grad():
print(f" detail настоящих картинок: {detail_score(decode(ae, z0[:4].float())):.4f}")
# ---- сетки: один шум на все промпты
hs, mk = enc.encode(PROMPTS, pad_to_len=a.text_len)
txt = m.encode_text(hs)
noise = torch.randn(1, m.cfg.latent_ch, lat, lat, generator=torch.Generator(DEV).manual_seed(a.seed),
device=DEV)
for i, p_ in enumerate(PROMPTS, 1):
print(f" {i}: {p_[:80]}")
print(f"\nсэмплы (один шум на все подписи; сетка 3 столбца × 2 строки, номер — на плитке):")
print(f" {'cfg':>4s} {'шагов':>6s} {'detail':>8s} {'dx median':>10s} {'dx min':>8s}")
for steps, cfg in ((24, 1.0), (24, 1.5), (24, 2.0), (24, 3.0), (48, 1.5)):
with torch.no_grad(), torch.autocast(DEV, torch.bfloat16, enabled=DEV == "cuda"):
z = m.sample(txt, mk, lat, lat, steps=steps, cfg_scale=cfg, shift=a.shift, noise=noise)
imgs = decode(ae, z.float())
dx = sorted(float((z[i] - z[j]).pow(2).mean().sqrt())
for i in range(len(PROMPTS)) for j in range(i + 1, len(PROMPTS)))
print(f" {cfg:4.1f} {steps:6d} {detail_score(imgs):8.4f} {dx[len(dx) // 2]:10.3f} {dx[0]:8.3f}")
tiles = [Image.fromarray(((imgs[i] + 1) * 127.5).byte().permute(1, 2, 0).cpu().numpy())
for i in range(len(PROMPTS))]
w, h = tiles[0].size
cols = 3 # та же раскладка, что в train.grid
rows = (len(tiles) + cols - 1) // cols
sheet = Image.new("RGB", (w * cols, h * rows), "black")
from PIL import ImageDraw
for i, t_ in enumerate(tiles):
sheet.paste(t_, ((i % cols) * w, (i // cols) * h))
dr = ImageDraw.Draw(sheet)
x0, y0 = (i % cols) * w, (i // cols) * h
dr.rectangle([x0 + 4, y0 + 4, x0 + 34, y0 + 26], fill=(0, 0, 0))
dr.text((x0 + 10, y0 + 8), str(i + 1), fill=(255, 255, 255))
sheet.save(out / f"grid_cfg{cfg:g}_s{steps}.png")
print(f" → {out / f'grid_cfg{cfg:g}_s{steps}.png'}")
if __name__ == "__main__":
main()
|