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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import math
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from huggingface_hub import hf_hub_download
|
| 7 |
+
from PIL import Image
|
| 8 |
+
|
| 9 |
+
# Otimizações para CPU no servidor do Hugging Face
|
| 10 |
+
torch.set_num_threads(4)
|
| 11 |
+
torch.backends.mkldnn.enabled = True
|
| 12 |
+
|
| 13 |
+
# ───────────────────────────────────────────────
|
| 14 |
+
# 1. Configuração e Arquitetura da U-Net (Cópia do seu treino)
|
| 15 |
+
# ───────────────────────────────────────────────
|
| 16 |
+
@dataclass
|
| 17 |
+
class Config:
|
| 18 |
+
image_size: int = 64
|
| 19 |
+
in_channels: int = 3
|
| 20 |
+
base_channels: int = 64
|
| 21 |
+
channel_mults: tuple = (1, 2, 4)
|
| 22 |
+
num_res_blocks: int = 1
|
| 23 |
+
attention_resolutions: tuple = (16,)
|
| 24 |
+
timesteps: int = 1000
|
| 25 |
+
beta_start: float = 1e-4
|
| 26 |
+
beta_end: float = 0.02
|
| 27 |
+
dtype: torch.dtype = torch.float32
|
| 28 |
+
|
| 29 |
+
class SinusoidalEmbedding(nn.Module):
|
| 30 |
+
def __init__(self, dim: int):
|
| 31 |
+
super().__init__()
|
| 32 |
+
self.dim = dim
|
| 33 |
+
def forward(self, t: torch.Tensor) -> torch.Tensor:
|
| 34 |
+
half = self.dim // 2
|
| 35 |
+
dtype = t.dtype
|
| 36 |
+
freqs = torch.exp(-math.log(10000) * torch.arange(half, device=t.device, dtype=dtype) / (half - 1))
|
| 37 |
+
args = t[:, None] * freqs[None]
|
| 38 |
+
return torch.cat([args.sin(), args.cos()], dim=-1)
|
| 39 |
+
|
| 40 |
+
class ResBlock(nn.Module):
|
| 41 |
+
def __init__(self, in_ch: int, out_ch: int, time_dim: int):
|
| 42 |
+
super().__init__()
|
| 43 |
+
self.norm1 = nn.GroupNorm(8, in_ch)
|
| 44 |
+
self.conv1 = nn.Conv2d(in_ch, out_ch, 3, padding=1)
|
| 45 |
+
self.norm2 = nn.GroupNorm(8, out_ch)
|
| 46 |
+
self.conv2 = nn.Conv2d(out_ch, out_ch, 3, padding=1)
|
| 47 |
+
self.time_proj = nn.Linear(time_dim, out_ch)
|
| 48 |
+
self.skip = nn.Conv2d(in_ch, out_ch, 1) if in_ch != out_ch else nn.Identity()
|
| 49 |
+
self.act = nn.SiLU()
|
| 50 |
+
def forward(self, x: torch.Tensor, t_emb: torch.Tensor) -> torch.Tensor:
|
| 51 |
+
h = self.act(self.norm1(x))
|
| 52 |
+
h = self.conv1(h)
|
| 53 |
+
h = h + self.time_proj(self.act(t_emb))[:, :, None, None]
|
| 54 |
+
h = self.act(self.norm2(h))
|
| 55 |
+
h = self.conv2(h)
|
| 56 |
+
return h + self.skip(x)
|
| 57 |
+
|
| 58 |
+
class AttentionBlock(nn.Module):
|
| 59 |
+
def __init__(self, channels: int, heads: int = 4):
|
| 60 |
+
super().__init__()
|
| 61 |
+
self.norm = nn.GroupNorm(8, channels)
|
| 62 |
+
self.attn = nn.MultiheadAttention(channels, heads, batch_first=True)
|
| 63 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 64 |
+
B, C, H, W = x.shape
|
| 65 |
+
h = self.norm(x).view(B, C, H * W).transpose(1, 2)
|
| 66 |
+
h, _ = self.attn(h, h, h)
|
| 67 |
+
return x + h.transpose(1, 2).view(B, C, H, W)
|
| 68 |
+
|
| 69 |
+
class DownBlock(nn.Module):
|
| 70 |
+
def __init__(self, in_ch, out_ch, time_dim, use_attn=False, n_res=1):
|
| 71 |
+
super().__init__()
|
| 72 |
+
self.res = nn.ModuleList([ResBlock(in_ch if i == 0 else out_ch, out_ch, time_dim) for i in range(n_res)])
|
| 73 |
+
self.attn = AttentionBlock(out_ch) if use_attn else nn.Identity()
|
| 74 |
+
self.down = nn.Conv2d(out_ch, out_ch, 3, stride=2, padding=1)
|
| 75 |
+
def forward(self, x, t_emb):
|
| 76 |
+
for r in self.res:
|
| 77 |
+
x = r(x, t_emb)
|
| 78 |
+
x = self.attn(x)
|
| 79 |
+
skip = x
|
| 80 |
+
x = self.down(x)
|
| 81 |
+
return x, skip
|
| 82 |
+
|
| 83 |
+
class UpBlock(nn.Module):
|
| 84 |
+
def __init__(self, in_ch, out_ch, time_dim, use_attn=False, n_res=1):
|
| 85 |
+
super().__init__()
|
| 86 |
+
self.up = nn.ConvTranspose2d(in_ch, in_ch, 2, stride=2)
|
| 87 |
+
self.res = nn.ModuleList([ResBlock(in_ch + out_ch if i == 0 else out_ch, out_ch, time_dim) for i in range(n_res)])
|
| 88 |
+
self.attn = AttentionBlock(out_ch) if use_attn else nn.Identity()
|
| 89 |
+
def forward(self, x, skip, t_emb):
|
| 90 |
+
x = self.up(x)
|
| 91 |
+
x = torch.cat([x, skip], dim=1)
|
| 92 |
+
for r in self.res:
|
| 93 |
+
x = r(x, t_emb)
|
| 94 |
+
x = self.attn(x)
|
| 95 |
+
return x
|
| 96 |
+
|
| 97 |
+
class StudentUNet(nn.Module):
|
| 98 |
+
def __init__(self, cfg: Config):
|
| 99 |
+
super().__init__()
|
| 100 |
+
ch, mults, time_dim, n_res, attn_res = cfg.base_channels, cfg.channel_mults, cfg.base_channels * 4, cfg.num_res_blocks, cfg.attention_resolutions
|
| 101 |
+
self.time_embed = nn.Sequential(SinusoidalEmbedding(ch), nn.Linear(ch, time_dim), nn.SiLU(), nn.Linear(time_dim, time_dim))
|
| 102 |
+
self.input_conv = nn.Conv2d(cfg.in_channels, ch, 3, padding=1)
|
| 103 |
+
self.downs = nn.ModuleList()
|
| 104 |
+
in_ch, res = ch, cfg.image_size
|
| 105 |
+
self.skip_channels = []
|
| 106 |
+
for mult in mults:
|
| 107 |
+
out_ch = ch * mult
|
| 108 |
+
self.downs.append(DownBlock(in_ch, out_ch, time_dim, res in attn_res, n_res))
|
| 109 |
+
self.skip_channels.append(out_ch)
|
| 110 |
+
in_ch = out_ch; res //= 2
|
| 111 |
+
self.mid_res1 = ResBlock(in_ch, in_ch, time_dim)
|
| 112 |
+
self.mid_attn = AttentionBlock(in_ch)
|
| 113 |
+
self.mid_res2 = ResBlock(in_ch, in_ch, time_dim)
|
| 114 |
+
self.ups = nn.ModuleList()
|
| 115 |
+
for mult in reversed(mults):
|
| 116 |
+
out_ch = ch * mult
|
| 117 |
+
self.ups.append(UpBlock(in_ch, out_ch, time_dim, res in attn_res, n_res))
|
| 118 |
+
in_ch = out_ch; res *= 2
|
| 119 |
+
self.out_norm = nn.GroupNorm(8, in_ch)
|
| 120 |
+
self.out_conv = nn.Conv2d(in_ch, cfg.in_channels, 3, padding=1)
|
| 121 |
+
self.act = nn.SiLU()
|
| 122 |
+
|
| 123 |
+
def forward(self, x: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
|
| 124 |
+
target_dtype = self.input_conv.weight.dtype
|
| 125 |
+
x = x.to(target_dtype)
|
| 126 |
+
t_emb = self.time_embed(t.to(target_dtype))
|
| 127 |
+
h = self.input_conv(x)
|
| 128 |
+
skips = []
|
| 129 |
+
for down in self.downs:
|
| 130 |
+
h, skip = down(h, t_emb)
|
| 131 |
+
skips.append(skip)
|
| 132 |
+
h = self.mid_res1(h, t_emb)
|
| 133 |
+
h = self.mid_attn(h)
|
| 134 |
+
h = self.mid_res2(h, t_emb)
|
| 135 |
+
for up, skip in zip(self.ups, reversed(skips)):
|
| 136 |
+
h = up(h, skip, t_emb)
|
| 137 |
+
h = self.act(self.out_norm(h))
|
| 138 |
+
return self.out_conv(h)
|
| 139 |
+
|
| 140 |
+
class DDPMScheduler:
|
| 141 |
+
def __init__(self, timesteps=1000, beta_start=1e-4, beta_end=0.02):
|
| 142 |
+
self.T = timesteps
|
| 143 |
+
betas = torch.linspace(beta_start, beta_end, timesteps)
|
| 144 |
+
alphas = 1.0 - betas
|
| 145 |
+
self.alpha_bar = torch.cumprod(alphas, dim=0)
|
| 146 |
+
|
| 147 |
+
def predict_x0(self, xt: torch.Tensor, noise_pred: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
|
| 148 |
+
ab = self.alpha_bar[t].view(-1, 1, 1, 1).to(xt.dtype)
|
| 149 |
+
return (xt - (1 - ab).sqrt() * noise_pred) / ab.sqrt()
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
# ───────────────────────────────────────────────
|
| 153 |
+
# 2. Carregando o Modelo do seu Repositório
|
| 154 |
+
# ───────────────────────────────────────────────
|
| 155 |
+
REPO_ID = "AxionLab-Co/PokePixels1-9M"
|
| 156 |
+
FILENAME = "model.pt" # ← Substitua se o nome exato do arquivo no seu repo for outro (ex: checkpoint_epoch100.pt)
|
| 157 |
+
|
| 158 |
+
print("Baixando e carregando o modelo...")
|
| 159 |
+
model_path = hf_hub_download(repo_id=REPO_ID, filename=FILENAME)
|
| 160 |
+
|
| 161 |
+
cfg = Config()
|
| 162 |
+
model = StudentUNet(cfg)
|
| 163 |
+
ckpt = torch.load(model_path, map_location="cpu")
|
| 164 |
+
|
| 165 |
+
# Trata se você salvou apenas o state_dict ou o dicionário inteiro de treino
|
| 166 |
+
if "model_state" in ckpt:
|
| 167 |
+
model.load_state_dict(ckpt["model_state"])
|
| 168 |
+
else:
|
| 169 |
+
model.load_state_dict(ckpt)
|
| 170 |
+
|
| 171 |
+
model.eval()
|
| 172 |
+
scheduler = DDPMScheduler(cfg.timesteps, cfg.beta_start, cfg.beta_end)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
# ───────────────────────────────────────────────
|
| 176 |
+
# 3. Lógica de Geração com Barra de Progresso Gradio
|
| 177 |
+
# ───────────────────────────────────────────────
|
| 178 |
+
@torch.no_grad()
|
| 179 |
+
def generate_fakemons(num_images, progress=gr.Progress()):
|
| 180 |
+
device = "cpu"
|
| 181 |
+
x = torch.randn(num_images, 3, cfg.image_size, cfg.image_size, device=device)
|
| 182 |
+
|
| 183 |
+
# Passa pelos 1000 passos e atualiza a barra na tela do usuário
|
| 184 |
+
for t_val in progress.tqdm(reversed(range(scheduler.T)), total=scheduler.T, desc="Removendo ruído (DDPM)"):
|
| 185 |
+
t = torch.full((num_images,), t_val, device=device, dtype=torch.long)
|
| 186 |
+
noise_pred = model(x, t)
|
| 187 |
+
|
| 188 |
+
if t_val > 0:
|
| 189 |
+
ab = scheduler.alpha_bar[t_val].to(x.dtype)
|
| 190 |
+
ab_prev = scheduler.alpha_bar[t_val - 1].to(x.dtype)
|
| 191 |
+
beta_t = 1.0 - (ab / ab_prev)
|
| 192 |
+
alpha_t = 1.0 - beta_t
|
| 193 |
+
|
| 194 |
+
mean = (1.0 / alpha_t.sqrt()) * (x - (beta_t / (1.0 - ab).sqrt()) * noise_pred)
|
| 195 |
+
sigma = beta_t.sqrt()
|
| 196 |
+
x = mean + sigma * torch.randn_like(x)
|
| 197 |
+
else:
|
| 198 |
+
x = scheduler.predict_x0(x, noise_pred, t)
|
| 199 |
+
|
| 200 |
+
# Converte o Tensor para uma lista de imagens PIL para o Gradio
|
| 201 |
+
x = x.clamp(-1, 1)
|
| 202 |
+
x = (x + 1) / 2
|
| 203 |
+
x = (x * 255).to(torch.uint8).permute(0, 2, 3, 1).cpu().numpy()
|
| 204 |
+
|
| 205 |
+
images = [Image.fromarray(img) for img in x]
|
| 206 |
+
return images
|
| 207 |
+
|
| 208 |
+
# ───────────────────────────────────────────────
|
| 209 |
+
# 4. Interface Web (Gradio)
|
| 210 |
+
# ───────────────────────────────────────────────
|
| 211 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 212 |
+
gr.Markdown("# ⚡ PokePixels 1.9M (Unconditional)")
|
| 213 |
+
gr.Markdown("Gerador de 'Fakemons' criado do zero e treinado inteiramente em uma CPU (Ryzen 5 5600G) por **AxionLab-Co**. Como é um modelo incondicional de Difusão, ele inventa criaturas baseadas em ruído puro usando 1000 passos (DDPM).")
|
| 214 |
+
|
| 215 |
+
with gr.Row():
|
| 216 |
+
with gr.Column(scale=1):
|
| 217 |
+
num_slider = gr.Slider(minimum=1, maximum=4, step=1, value=2, label="Quantidade de Fakemons", info="Mais imagens demoram mais tempo na CPU.")
|
| 218 |
+
gen_btn = gr.Button("Gerar Fakemons! 🚀", variant="primary")
|
| 219 |
+
gr.Markdown("*Nota: O servidor gratuito do Hugging Face roda em CPU. Gerar imagens pode levar de 30 a 60 segundos.*")
|
| 220 |
+
|
| 221 |
+
with gr.Column(scale=2):
|
| 222 |
+
gallery = gr.Gallery(label="Fakemons Gerados", show_label=True, elem_id="gallery", columns=[2], rows=[2], object_fit="contain", height="auto")
|
| 223 |
+
|
| 224 |
+
gen_btn.click(fn=generate_fakemons, inputs=num_slider, outputs=gallery)
|
| 225 |
+
|
| 226 |
+
demo.launch()
|