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: 7,151 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 | """Данные: папка с `<имя>.jpg` + `<имя>.txt` → кэш латентов VAE (fp16 memmap).
Зачем кэш. VAE-энкод 256² стоит ~87 мс на 8 картинок в fp32, плюс декод JPEG и
ресайз в потоках — это сопоставимо с шагом обучения. Латент 32×32×32 в fp16
занимает 128 КБ, поэтому весь датасет кодируется один раз (~3 мин на 7.5k
картинок) и дальше цикл обучения не трогает ни диск, ни VAE.
Кропы: `crops` случайных кропов на картинку (короткая сторона → `size`), так
что модель видит разные части кадра, а не только центр.
"""
from __future__ import annotations
import json
import random
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import numpy as np
import torch
from PIL import Image
IMAGE_EXT = (".jpg", ".jpeg", ".png", ".webp")
def scan(root: Path) -> list[tuple[str, str]]:
"""→ [(путь к картинке, подпись)]; подпись лежит рядом в .txt."""
items = []
for p in sorted(root.rglob("*")):
if p.suffix.lower() in IMAGE_EXT:
cap = p.with_suffix(".txt")
if cap.exists():
items.append((str(p), cap.read_text().strip()))
if not items:
raise SystemExit(f"в {root} нет пар картинка+.txt")
return items
def _load(path: str, size: int, crop: str) -> np.ndarray:
"""картинка → (3, size, size) float32 в [-1, 1]."""
im = Image.open(path).convert("RGB")
w, h = im.size
sc = size / min(w, h)
if (w, h) != (round(w * sc), round(h * sc)):
im = im.resize((max(size, round(w * sc)), max(size, round(h * sc))), Image.LANCZOS)
w, h = im.size
if crop == "center":
left, top = (w - size) // 2, (h - size) // 2
else: # "r:<seed>" — воспроизводимый случайный кроп
rnd = random.Random(int(crop[2:]))
left, top = rnd.randrange(w - size + 1), rnd.randrange(h - size + 1)
im = im.crop((left, top, left + size, top + size))
return np.asarray(im, dtype=np.float32).transpose(2, 0, 1) / 127.5 - 1.0
def build_cache(root: Path, out: Path, vae, size: int = 256, crops: int = 2,
batch: int = 16, workers: int = 8, seed: int = 0, limit: int = 0) -> None:
"""Кодирует датасет в `out/latents.npy` (N, ch, lat, lat) fp16 + `out/meta.json`."""
items = scan(root)
if limit:
items = items[:limit]
tasks = [(path, "center" if crops == 1 else f"r:{seed * 100003 + i * 97 + c}")
for i, (path, _) in enumerate(items) for c in range(crops)]
caps = [cap for _, cap in items for _ in range(crops)]
out.mkdir(parents=True, exist_ok=True)
first = vae.encode(torch.zeros(2, 3, size, size, device=vae.device))
lat = first.shape[-1]
z = np.lib.format.open_memmap(out / "latents.npy", mode="w+", dtype=np.float16,
shape=(len(tasks), first.shape[1], lat, lat))
print(f"[cache] {len(items)} картинок × {crops} кропов = {len(tasks)} латентов "
f"{tuple(first.shape[1:])} fp16, {len(tasks) * first[0].numel() * 2 / 2**20:.0f} МБ", flush=True)
pool = ThreadPoolExecutor(max_workers=workers)
for start in range(0, len(tasks), batch):
chunk = tasks[start:start + batch]
arrs = list(pool.map(lambda t: _load(t[0], size, t[1]), chunk))
x = torch.from_numpy(np.stack(arrs)).to(vae.device, non_blocking=True)
z[start:start + len(chunk)] = vae.encode(x).float().cpu().numpy().astype(np.float16)
if (start // batch) % 20 == 0:
print(f" {start + len(chunk)}/{len(tasks)}", flush=True)
z.flush()
pool.shutdown()
(out / "meta.json").write_text(json.dumps(
{"captions": caps, "size": size, "latent": lat, "channels": int(first.shape[1]),
"source": str(root), "crops": crops, "seed": seed}, ensure_ascii=False))
print(f"[cache] готово: {out}/latents.npy", flush=True)
class Latents:
"""Кэш латентов + подписи. Батч — индексы без возвращения внутри эпохи."""
def __init__(self, cache: Path, subset: int = 0):
meta = json.loads((Path(cache) / "meta.json").read_text())
self.z = np.load(Path(cache) / "latents.npy", mmap_mode="r")
self.caps = meta["captions"]
self.size, self.latent = meta["latent"] * 8, meta["latent"]
self.crops = max(1, int(meta.get("crops", 1)))
self.n = len(self.caps)
if subset:
self.n = min(subset, self.n)
# отложенные 2% КАРТИНОК (все их кропы) — иначе кроп-сосед утекает в валидацию
n_val = max(1, self.n // 50)
self.val_idx = list(range(self.n - n_val, self.n))
val_items = {i // self.crops for i in self.val_idx}
self.train_idx = [i for i in range(self.n) if i // self.crops not in val_items]
self._order: list[int] = []
self._pos = 0
def batch(self, n: int, rng: random.Random):
if self._pos + n > len(self._order):
self._order = list(self.train_idx)
rng.shuffle(self._order)
self._pos = 0
idx = self._order[self._pos:self._pos + n]
self._pos += n
z = torch.from_numpy(np.asarray(self.z[np.asarray(idx)], dtype=np.float32)) # (n, ch, lat, lat)
return z, [self.caps[i] for i in idx]
def val_batch(self, n: int):
"""Отложенные картинки (детерминированно, без пересечения с обучением)."""
idx = self.val_idx[:n]
z = torch.from_numpy(np.asarray(self.z[np.asarray(idx)], dtype=np.float32))
return z, [self.caps[i] for i in idx]
class FakeLatents:
"""Случайные латенты — проверка запуска без данных."""
PROMPTS = [
"A photograph of a red fox sleeping on a mossy log in a misty forest at dawn.",
"A city made of glass where rivers of light flow between the towers, cinematic lighting.",
'A neon sign reading "hello world" mounted on a brick wall at night in the rain.',
"An impressionist oil painting of a woman with a parasol standing by a lake.",
]
def __init__(self, latent: int, ch: int, size: int = 256, n: int = 256):
self.latent, self.ch, self.size, self.n = latent, ch, size, n
self.caps = [self.PROMPTS[i % len(self.PROMPTS)] for i in range(n)]
def batch(self, n: int, rng: random.Random):
return torch.randn(n, self.ch, self.latent, self.latent), [rng.choice(self.caps) for _ in range(n)]
def val_batch(self, n: int):
return (torch.randn(n, self.ch, self.latent, self.latent),
[self.caps[i % len(self.caps)] for i in range(n)])
|