Instructions to use AiArtLab/sdxs-1b with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusers
How to use AiArtLab/sdxs-1b with Diffusers:
pip install -U diffusers transformers accelerate
import torch from diffusers import DiffusionPipeline # switch to "mps" for apple devices pipe = DiffusionPipeline.from_pretrained("AiArtLab/sdxs-1b", dtype=torch.bfloat16, device_map="cuda") prompt = "sdxs-1b" image = pipe(prompt).images[0] - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- Draw Things
- DiffusionBee
2602
Browse files- pipeline_sdxs-Copy2.py +369 -0
- pipeline_sdxs.py +1 -1
- samples/unet_320x640_0.jpg +2 -2
- samples/unet_352x640_0.jpg +2 -2
- samples/unet_384x640_0.jpg +2 -2
- samples/unet_416x640_0.jpg +2 -2
- samples/unet_448x640_0.jpg +2 -2
- samples/unet_480x640_0.jpg +2 -2
- samples/unet_512x640_0.jpg +2 -2
- samples/unet_544x640_0.jpg +2 -2
- samples/unet_576x640_0.jpg +2 -2
- samples/unet_608x640_0.jpg +2 -2
- samples/unet_640x320_0.jpg +2 -2
- samples/unet_640x352_0.jpg +2 -2
- samples/unet_640x384_0.jpg +2 -2
- samples/unet_640x416_0.jpg +2 -2
- samples/unet_640x448_0.jpg +2 -2
- samples/unet_640x480_0.jpg +2 -2
- samples/unet_640x512_0.jpg +2 -2
- samples/unet_640x544_0.jpg +2 -2
- samples/unet_640x576_0.jpg +2 -2
- samples/unet_640x608_0.jpg +2 -2
- samples/unet_640x640_0.jpg +2 -2
- unet/diffusion_pytorch_model.safetensors +1 -1
pipeline_sdxs-Copy2.py
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
import torch
|
| 2 |
+
import numpy as np
|
| 3 |
+
from PIL import Image
|
| 4 |
+
from typing import List, Union, Optional, Tuple
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
|
| 7 |
+
from diffusers import DiffusionPipeline
|
| 8 |
+
from diffusers.utils import BaseOutput
|
| 9 |
+
from tqdm import tqdm
|
| 10 |
+
from transformers import Qwen3ForCausalLM, Qwen2Tokenizer
|
| 11 |
+
|
| 12 |
+
@dataclass
|
| 13 |
+
class SdxsPipelineOutput(BaseOutput):
|
| 14 |
+
images: Union[List[Image.Image], np.ndarray]
|
| 15 |
+
prompt: Optional[Union[str, List[str]]] = None # Возврат улучшенного промпта
|
| 16 |
+
|
| 17 |
+
class SdxsPipeline(DiffusionPipeline):
|
| 18 |
+
def __init__(self, vae, text_encoder, text_encoder2, tokenizer, tokenizer2, unet, scheduler):
|
| 19 |
+
super().__init__()
|
| 20 |
+
self.register_modules(
|
| 21 |
+
vae=vae,
|
| 22 |
+
text_encoder=text_encoder,
|
| 23 |
+
text_encoder2=text_encoder2,
|
| 24 |
+
tokenizer=tokenizer,
|
| 25 |
+
tokenizer2=tokenizer2,
|
| 26 |
+
unet=unet,
|
| 27 |
+
scheduler=scheduler
|
| 28 |
+
)
|
| 29 |
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
| 30 |
+
|
| 31 |
+
def preprocess_image(self, image: Image.Image, width: int, height: int):
|
| 32 |
+
"""Ресайз и центрированный кроп изображения для асимметричного VAE."""
|
| 33 |
+
# Для энкодера с масштабом 8
|
| 34 |
+
target_height = ((height // self.vae_scale_factor) * self.vae_scale_factor)
|
| 35 |
+
target_width = ((width // self.vae_scale_factor) * self.vae_scale_factor)
|
| 36 |
+
|
| 37 |
+
w, h = image.size
|
| 38 |
+
aspect_ratio = target_width / target_height
|
| 39 |
+
|
| 40 |
+
if w / h > aspect_ratio:
|
| 41 |
+
new_w = int(h * aspect_ratio)
|
| 42 |
+
left = (w - new_w) // 2
|
| 43 |
+
image = image.crop((left, 0, left + new_w, h))
|
| 44 |
+
else:
|
| 45 |
+
new_h = int(w / aspect_ratio)
|
| 46 |
+
top = (h - new_h) // 2
|
| 47 |
+
image = image.crop((0, top, w, top + new_h))
|
| 48 |
+
|
| 49 |
+
image = image.resize((target_width, target_height), resample=Image.LANCZOS)
|
| 50 |
+
image = np.array(image).astype(np.float32) / 255.0
|
| 51 |
+
image = image[None].transpose(0, 3, 1, 2) # [1, C, H, W]
|
| 52 |
+
image = torch.from_numpy(image)
|
| 53 |
+
return 2.0 * image - 1.0 # [-1, 1]
|
| 54 |
+
|
| 55 |
+
@staticmethod
|
| 56 |
+
def _patchify_latents(latents):
|
| 57 |
+
batch_size, num_channels_latents, height, width = latents.shape
|
| 58 |
+
latents = latents.view(batch_size, num_channels_latents, height // 2, 2, width // 2, 2)
|
| 59 |
+
latents = latents.permute(0, 1, 3, 5, 2, 4)
|
| 60 |
+
latents = latents.reshape(batch_size, num_channels_latents * 4, height // 2, width // 2)
|
| 61 |
+
return latents
|
| 62 |
+
|
| 63 |
+
@staticmethod
|
| 64 |
+
def _unpatchify_latents(latents):
|
| 65 |
+
batch_size, num_channels_latents, height, width = latents.shape
|
| 66 |
+
latents = latents.reshape(batch_size, num_channels_latents // (2 * 2), 2, 2, height, width)
|
| 67 |
+
latents = latents.permute(0, 1, 4, 2, 5, 3)
|
| 68 |
+
latents = latents.reshape(batch_size, num_channels_latents // (2 * 2), height * 2, width * 2)
|
| 69 |
+
return latents
|
| 70 |
+
|
| 71 |
+
def flux_encode(self, latents):
|
| 72 |
+
# 1. Patchify
|
| 73 |
+
image_latents = self._patchify_latents(latents)
|
| 74 |
+
|
| 75 |
+
# 2. Normalization
|
| 76 |
+
bn_mean = self.vae.bn.running_mean.view(1, -1, 1, 1).to(image_latents.device, image_latents.dtype)
|
| 77 |
+
bn_var = self.vae.bn.running_var.view(1, -1, 1, 1).to(image_latents.device, image_latents.dtype)
|
| 78 |
+
eps = getattr(self.vae.config, "batch_norm_eps", 1e-5)
|
| 79 |
+
|
| 80 |
+
latents_bn_std = torch.sqrt(bn_var + eps)
|
| 81 |
+
latents = (image_latents - bn_mean) / latents_bn_std
|
| 82 |
+
|
| 83 |
+
# 3. Unpatchify
|
| 84 |
+
latents = self._unpatchify_latents(latents)
|
| 85 |
+
return latents
|
| 86 |
+
|
| 87 |
+
def flux_decode(self, latents):
|
| 88 |
+
# 1. Patchify
|
| 89 |
+
image_latents = self._patchify_latents(latents)
|
| 90 |
+
|
| 91 |
+
# 2. De-normalization
|
| 92 |
+
bn_mean = self.vae.bn.running_mean.view(1, -1, 1, 1).to(image_latents.device, image_latents.dtype)
|
| 93 |
+
bn_var = self.vae.bn.running_var.view(1, -1, 1, 1).to(image_latents.device, image_latents.dtype)
|
| 94 |
+
eps = getattr(self.vae.config, "batch_norm_eps", 1e-5)
|
| 95 |
+
|
| 96 |
+
latents_bn_std = torch.sqrt(bn_var + eps)
|
| 97 |
+
latents = image_latents * latents_bn_std + bn_mean
|
| 98 |
+
|
| 99 |
+
# 3. Unpatchify
|
| 100 |
+
latents = self._unpatchify_latents(latents)
|
| 101 |
+
return latents
|
| 102 |
+
|
| 103 |
+
def encode_prompt(self, prompt, negative_prompt, device, dtype):
|
| 104 |
+
def get_single_encode(texts):
|
| 105 |
+
if not texts:
|
| 106 |
+
texts = [""]
|
| 107 |
+
elif isinstance(texts, str):
|
| 108 |
+
texts = [texts]
|
| 109 |
+
|
| 110 |
+
with torch.no_grad():
|
| 111 |
+
toks = self.tokenizer(
|
| 112 |
+
texts,
|
| 113 |
+
padding="max_length",
|
| 114 |
+
max_length=self.text_encoder.config.max_position_embeddings,
|
| 115 |
+
truncation=True,
|
| 116 |
+
return_tensors="pt"
|
| 117 |
+
).to(device)
|
| 118 |
+
|
| 119 |
+
outputs = self.text_encoder(
|
| 120 |
+
input_ids=toks.input_ids,
|
| 121 |
+
attention_mask=toks.attention_mask,
|
| 122 |
+
output_hidden_states=True
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
# 1. Берем -2 слой [Batch, Seq, Dim]
|
| 126 |
+
hidden = outputs.hidden_states[-2]
|
| 127 |
+
|
| 128 |
+
# 2. Достаем pooled вектор (последний токен) [Batch, Dim]
|
| 129 |
+
seq_lens = toks.attention_mask.sum(dim=1) - 1
|
| 130 |
+
pooled = hidden[torch.arange(hidden.shape[0]), seq_lens.clamp(min=0)]
|
| 131 |
+
|
| 132 |
+
# 3. Нормализация
|
| 133 |
+
norm = self.text_encoder.text_model.final_layer_norm
|
| 134 |
+
hidden = norm(hidden)
|
| 135 |
+
pooled = norm(pooled)
|
| 136 |
+
|
| 137 |
+
# 4. Объединяем в матрицу: Пулед (как 1-й токен) + остальные токены
|
| 138 |
+
# pooled.unsqueeze(1) делает [Batch, 1, Dim]
|
| 139 |
+
embeds = torch.cat([pooled.unsqueeze(1), hidden], dim=1)
|
| 140 |
+
|
| 141 |
+
# 5. Расширяем маску для нового токена (добавляем единицы спереди)
|
| 142 |
+
ones = torch.ones((toks.attention_mask.shape[0], 1), dtype=toks.attention_mask.dtype, device=device)
|
| 143 |
+
mask = torch.cat([ones, toks.attention_mask], dim=1)
|
| 144 |
+
|
| 145 |
+
return embeds, mask
|
| 146 |
+
|
| 147 |
+
def get_pooled_encode(texts):
|
| 148 |
+
if texts is None:
|
| 149 |
+
texts = ""
|
| 150 |
+
|
| 151 |
+
if isinstance(texts, str):
|
| 152 |
+
texts = [texts]
|
| 153 |
+
|
| 154 |
+
with torch.no_grad():
|
| 155 |
+
# 1. Собираем текстовые промпты оборачивая их в Chat Template
|
| 156 |
+
formatted_prompts = []
|
| 157 |
+
for t in texts:
|
| 158 |
+
messages = [{"role": "user", "content": [{"type": "text", "text": t}]}]
|
| 159 |
+
res_text = self.tokenizer2.apply_chat_template(
|
| 160 |
+
messages,
|
| 161 |
+
add_generation_prompt=True,
|
| 162 |
+
tokenize=False
|
| 163 |
+
)
|
| 164 |
+
formatted_prompts.append(res_text)
|
| 165 |
+
|
| 166 |
+
# 2. Токенизируем, режем и добавляем паддинг за один раз
|
| 167 |
+
toks = self.tokenizer2(
|
| 168 |
+
formatted_prompts,
|
| 169 |
+
padding="max_length",
|
| 170 |
+
max_length=self.text_encoder.config.max_position_embeddings,
|
| 171 |
+
truncation=True, # Не забываем обрезать, если вдруг длиннее
|
| 172 |
+
return_tensors="pt"
|
| 173 |
+
).to(device)
|
| 174 |
+
|
| 175 |
+
# 3. Прогоняем через модель
|
| 176 |
+
outputs = self.text_encoder2(
|
| 177 |
+
input_ids=toks.input_ids,
|
| 178 |
+
attention_mask=toks.attention_mask,
|
| 179 |
+
output_hidden_states=True
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
layer_index = -2
|
| 183 |
+
last_hidden = outputs.hidden_states[layer_index]
|
| 184 |
+
seq_len = toks.attention_mask.sum(dim=1) - 1
|
| 185 |
+
pooled = last_hidden[torch.arange(len(last_hidden)), seq_len.clamp(min=0)]
|
| 186 |
+
|
| 187 |
+
return pooled
|
| 188 |
+
|
| 189 |
+
pos_embeds, pos_mask = get_single_encode(prompt)
|
| 190 |
+
neg_embeds, neg_mask = get_single_encode(negative_prompt)
|
| 191 |
+
pos_pooled = get_pooled_encode(prompt)
|
| 192 |
+
neg_pooled = get_pooled_encode(negative_prompt)
|
| 193 |
+
|
| 194 |
+
batch_size = pos_embeds.shape[0]
|
| 195 |
+
if neg_embeds.shape[0] != batch_size:
|
| 196 |
+
neg_embeds = neg_embeds.repeat(batch_size, 1, 1)
|
| 197 |
+
neg_mask = neg_mask.repeat(batch_size, 1)
|
| 198 |
+
neg_pooled = neg_pooled.repeat(batch_size, 1)
|
| 199 |
+
|
| 200 |
+
if pos_pooled.shape[0] != batch_size:
|
| 201 |
+
pos_pooled = pos_pooled.repeat(batch_size, 1)
|
| 202 |
+
|
| 203 |
+
text_embeddings = torch.cat([neg_embeds, pos_embeds], dim=0)
|
| 204 |
+
final_mask = torch.cat([neg_mask, pos_mask], dim=0)
|
| 205 |
+
pooled_embeds = torch.cat([neg_pooled, pos_pooled], dim=0)
|
| 206 |
+
|
| 207 |
+
return text_embeddings.to(dtype=dtype), final_mask.to(dtype=torch.int64), pooled_embeds.to(dtype=dtype)
|
| 208 |
+
|
| 209 |
+
@torch.no_grad()
|
| 210 |
+
def __call__(
|
| 211 |
+
self,
|
| 212 |
+
prompt: Union[str, List[str]],
|
| 213 |
+
image: Optional[Union[Image.Image, List[Image.Image]]] = None,
|
| 214 |
+
coef: float = 0.97, # ← strength (0.0 = оригинал, 1.0 = полный шум)
|
| 215 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 216 |
+
height: int = 1024,
|
| 217 |
+
width: int = 1024,
|
| 218 |
+
num_inference_steps: int = 40,
|
| 219 |
+
guidance_scale: float = 4.0,
|
| 220 |
+
generator: Optional[torch.Generator] = None,
|
| 221 |
+
seed: Optional[int] = None,
|
| 222 |
+
output_type: str = "pil",
|
| 223 |
+
return_dict: bool = True,
|
| 224 |
+
refine_prompt: bool = False, # Флаг рефайна!
|
| 225 |
+
# structure_preservation оставляем для совместимости, но теперь он почти не нужен
|
| 226 |
+
structure_preservation: float = 0.0, # 0.0 = стандартный линейный путь (лучше всего)
|
| 227 |
+
**kwargs,
|
| 228 |
+
):
|
| 229 |
+
device = self.device
|
| 230 |
+
dtype = self.unet.dtype
|
| 231 |
+
|
| 232 |
+
if generator is None and seed is not None:
|
| 233 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 234 |
+
|
| 235 |
+
# ==================== REFINE PROMPT (INLINE) ====================
|
| 236 |
+
if refine_prompt and prompt:
|
| 237 |
+
sys_msg = (
|
| 238 |
+
"You are a skilled text-to-image prompt engineer whose sole function is to transform the user's input into an aesthetically optimized, detailed, and visually descriptive three-sentence output. "
|
| 239 |
+
"**The primary subject (e.g., 'girl', 'dog', 'house') MUST be the main focus of the revised prompt and MUST be described in rich detail within the first sentence or two.** "
|
| 240 |
+
"Output **only** the final revised prompt in **English**, with absolutely no commentary.\n Don't use cliches like warm,soft,vibrant, wildflowers. Be creative "
|
| 241 |
+
"User input prompt: "
|
| 242 |
+
)
|
| 243 |
+
prompts_list = [prompt] if isinstance(prompt, str) else prompt
|
| 244 |
+
refined_list = []
|
| 245 |
+
|
| 246 |
+
for p in prompts_list:
|
| 247 |
+
messages = [{"role": "user", "content": [{"type": "text", "text": sys_msg + p}]}]
|
| 248 |
+
|
| 249 |
+
# Используем Qwen-Instruct формат (apply_chat_template сам подставит system/user/assistant токены)
|
| 250 |
+
inputs = self.tokenizer2.apply_chat_template(
|
| 251 |
+
messages,
|
| 252 |
+
tokenize=True,
|
| 253 |
+
add_generation_prompt=True,
|
| 254 |
+
return_dict=True,
|
| 255 |
+
return_tensors="pt"
|
| 256 |
+
).to(device)
|
| 257 |
+
|
| 258 |
+
generated_ids = self.text_encoder2.generate(
|
| 259 |
+
**inputs, max_new_tokens=self.text_encoder.config.max_position_embeddings, do_sample=True,temperature = 0.7
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
# Обрезаем входные токены из ответа
|
| 263 |
+
generated_ids_trimmed = [
|
| 264 |
+
out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
|
| 265 |
+
]
|
| 266 |
+
output_text = self.tokenizer2.decode(
|
| 267 |
+
generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
|
| 268 |
+
)
|
| 269 |
+
refined_list.append(output_text)
|
| 270 |
+
|
| 271 |
+
prompt = refined_list[0] if isinstance(prompt, str) else refined_list
|
| 272 |
+
|
| 273 |
+
# ==================== ENCODE PROMPTS ====================
|
| 274 |
+
text_embeddings, attention_mask, pooled_embeds = self.encode_prompt(
|
| 275 |
+
prompt, negative_prompt, device, dtype
|
| 276 |
+
)
|
| 277 |
+
batch_size = 1 if isinstance(prompt, str) else len(prompt)
|
| 278 |
+
|
| 279 |
+
# 2. Scheduler timesteps
|
| 280 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 281 |
+
timesteps = self.scheduler.timesteps
|
| 282 |
+
|
| 283 |
+
# ==================== IMG2IMG БЛОК (НОВАЯ ВЕРСИЯ) ====================
|
| 284 |
+
if image is not None:
|
| 285 |
+
# --- Подготовка изображения ---
|
| 286 |
+
if isinstance(image, Image.Image):
|
| 287 |
+
image_tensor = self.preprocess_image(image, width, height).to(device, self.vae.dtype)
|
| 288 |
+
else:
|
| 289 |
+
image_tensor = self.preprocess_image(image[0], width, height).to(device, self.vae.dtype)
|
| 290 |
+
|
| 291 |
+
# --- Кодируем в latent ---
|
| 292 |
+
latents_clean = self.vae.encode(image_tensor).latent_dist.sample(generator=generator)
|
| 293 |
+
vae_scaling_factor = getattr(self.vae.config, "scaling_factor", 1.0)
|
| 294 |
+
vae_shift_factor = getattr(self.vae.config, "shift_factor", 0.0)
|
| 295 |
+
latents_clean = (latents_clean - vae_shift_factor) / vae_scaling_factor
|
| 296 |
+
latents_clean = latents_clean.to(dtype)
|
| 297 |
+
|
| 298 |
+
# --- Добавляем шум по Rectified Flow формуле ---
|
| 299 |
+
noise = torch.randn_like(latents_clean)
|
| 300 |
+
|
| 301 |
+
# coef = strength (0.0 → оригинал, 1.0 → чистый шум)
|
| 302 |
+
sigma = coef # в Flow Matching sigma = t
|
| 303 |
+
if hasattr(self.scheduler, "sigma_shift"): # если есть shift (Flux-style)
|
| 304 |
+
sigma = self.scheduler.sigma_shift(sigma)
|
| 305 |
+
|
| 306 |
+
latents = (1.0 - sigma) * latents_clean + sigma * noise
|
| 307 |
+
|
| 308 |
+
# Обрезаем timesteps начиная с текущего sigma
|
| 309 |
+
init_timestep = int(num_inference_steps * coef)
|
| 310 |
+
t_start = max(num_inference_steps - init_timestep, 0)
|
| 311 |
+
timesteps = timesteps[t_start:]
|
| 312 |
+
|
| 313 |
+
else:
|
| 314 |
+
# txt2img — оставляем как было
|
| 315 |
+
vae_scaling_factor = getattr(self.vae.config, "scaling_factor", 1.0)
|
| 316 |
+
vae_shift_factor = getattr(self.vae.config, "shift_factor", 0.0)
|
| 317 |
+
latent_h = height // self.vae_scale_factor
|
| 318 |
+
latent_w = width // self.vae_scale_factor
|
| 319 |
+
|
| 320 |
+
latents = torch.randn(
|
| 321 |
+
(batch_size, self.unet.config.in_channels, latent_h, latent_w),
|
| 322 |
+
generator=generator, device=device, dtype=dtype
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
# ==================== DENOISING LOOP (одинаковый для txt2img и img2img) ====================
|
| 326 |
+
for i, t in enumerate(tqdm(timesteps, desc="Sampling")):
|
| 327 |
+
latent_model_input = torch.cat([latents] * 2) if guidance_scale > 1.0 else latents
|
| 328 |
+
|
| 329 |
+
added_cond_kwargs = {
|
| 330 |
+
"text_embeds": pooled_embeds,
|
| 331 |
+
}
|
| 332 |
+
|
| 333 |
+
model_out = self.unet(
|
| 334 |
+
latent_model_input,
|
| 335 |
+
t,
|
| 336 |
+
encoder_hidden_states=text_embeddings,
|
| 337 |
+
encoder_attention_mask=attention_mask,
|
| 338 |
+
added_cond_kwargs=added_cond_kwargs,
|
| 339 |
+
return_dict=False,
|
| 340 |
+
)[0]
|
| 341 |
+
|
| 342 |
+
if guidance_scale > 1.0:
|
| 343 |
+
flow_uncond, flow_cond = model_out.chunk(2)
|
| 344 |
+
model_out = flow_uncond + guidance_scale * (flow_cond - flow_uncond)
|
| 345 |
+
|
| 346 |
+
# Важно: используем scheduler.step — он сам знает, что делать с velocity
|
| 347 |
+
latents = self.scheduler.step(model_out, t, latents, return_dict=False)[0]
|
| 348 |
+
|
| 349 |
+
# ==================== DECODE ====================
|
| 350 |
+
if output_type == "latent":
|
| 351 |
+
if not return_dict: return (latents, prompt)
|
| 352 |
+
return SdxsPipelineOutput(images=latents, prompt=prompt)
|
| 353 |
+
|
| 354 |
+
latents = latents * vae_scaling_factor + vae_shift_factor
|
| 355 |
+
latents = self.flux_decode(latents)
|
| 356 |
+
|
| 357 |
+
image_output = self.vae.decode(latents.to(self.vae.dtype), return_dict=False)[0]
|
| 358 |
+
|
| 359 |
+
image_output = (image_output.clamp(-1, 1) + 1) / 2
|
| 360 |
+
image_np = image_output.cpu().permute(0, 2, 3, 1).float().numpy()
|
| 361 |
+
|
| 362 |
+
if output_type == "pil":
|
| 363 |
+
images = [(Image.fromarray((img * 255).round().astype("uint8"))) for img in image_np]
|
| 364 |
+
else:
|
| 365 |
+
images = image_np
|
| 366 |
+
|
| 367 |
+
if not return_dict:
|
| 368 |
+
return (images, prompt)
|
| 369 |
+
return SdxsPipelineOutput(images=images, prompt=prompt)
|
pipeline_sdxs.py
CHANGED
|
@@ -263,7 +263,7 @@ class SdxsPipeline(DiffusionPipeline):
|
|
| 263 |
generated_ids_trimmed = [
|
| 264 |
out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
|
| 265 |
]
|
| 266 |
-
output_text = self.tokenizer2.
|
| 267 |
generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
|
| 268 |
)
|
| 269 |
refined_list.append(output_text)
|
|
|
|
| 263 |
generated_ids_trimmed = [
|
| 264 |
out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
|
| 265 |
]
|
| 266 |
+
output_text = self.tokenizer2.batch_decode(
|
| 267 |
generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
|
| 268 |
)
|
| 269 |
refined_list.append(output_text)
|
samples/unet_320x640_0.jpg
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
samples/unet_352x640_0.jpg
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
samples/unet_384x640_0.jpg
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
samples/unet_416x640_0.jpg
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
samples/unet_448x640_0.jpg
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
samples/unet_480x640_0.jpg
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
samples/unet_512x640_0.jpg
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
samples/unet_544x640_0.jpg
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
samples/unet_576x640_0.jpg
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
samples/unet_608x640_0.jpg
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
samples/unet_640x320_0.jpg
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
samples/unet_640x352_0.jpg
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
samples/unet_640x384_0.jpg
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
samples/unet_640x416_0.jpg
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
samples/unet_640x448_0.jpg
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
samples/unet_640x480_0.jpg
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
samples/unet_640x512_0.jpg
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
samples/unet_640x544_0.jpg
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
samples/unet_640x576_0.jpg
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
samples/unet_640x608_0.jpg
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
samples/unet_640x640_0.jpg
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
unet/diffusion_pytorch_model.safetensors
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
size 5946605448
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:62f976ab8efb5653a2427158529b4b013b3b5034da08e15d18deedd0a42c9dd7
|
| 3 |
size 5946605448
|