id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
156,365 | import asyncio
import base64
import json
import logging
import math
import os
import re
import struct
from enum import Enum
from io import BytesIO
from pathlib import Path
from typing import Any, Callable, Coroutine, Dict, List, Optional, Tuple, Union
import requests
from PIL import Image
from requests.adapters import HTTPAdapter, Retry
from tqdm import tqdm
from core.thread import ThreadWithReturnValue
from core.types import ImageFormats, InferenceJob, PyTorchModelBase, PyTorchModelStage
def convert_base64_to_bytes(data: str):
"Convert a base64 string to bytes"
return BytesIO(base64.b64decode(data))
The provided code snippet includes necessary dependencies for implementing the `convert_to_image` function. Write a Python function `def convert_to_image( image: Union[Image.Image, bytes, str], convert_to_rgb: bool = True ) -> Image.Image` to solve the following problem:
Converts the image to a PIL Image if it is a base64 string or bytes
Here is the function:
def convert_to_image(
image: Union[Image.Image, bytes, str], convert_to_rgb: bool = True
) -> Image.Image:
"Converts the image to a PIL Image if it is a base64 string or bytes"
if isinstance(image, str):
b = convert_base64_to_bytes(image)
im = Image.open(b)
if convert_to_rgb:
im = im.convert("RGB")
return im
if isinstance(image, bytes):
im = Image.open(image)
if convert_to_rgb:
im = im.convert("RGB")
return im
if isinstance(image, Image.Image):
return image
raise ValueError(f"Type {type(image)} not supported yet") | Converts the image to a PIL Image if it is a base64 string or bytes |
156,366 | import asyncio
import base64
import json
import logging
import math
import os
import re
import struct
from enum import Enum
from io import BytesIO
from pathlib import Path
from typing import Any, Callable, Coroutine, Dict, List, Optional, Tuple, Union
import requests
from PIL import Image
from requests.adapters import HTTPAdapter, Retry
from tqdm import tqdm
from core.thread import ThreadWithReturnValue
from core.types import ImageFormats, InferenceJob, PyTorchModelBase, PyTorchModelStage
class ThreadWithReturnValue(Thread):
"A thread class that supports returning a value from the target function"
def __init__(
self,
target: Union[Callable[..., T], Coroutine[Any, Any, T]],
group=None,
name: Optional[str] = None,
args: Optional[Tuple] = None,
kwargs: Optional[Dict] = None,
):
if args is None:
args = ()
if kwargs is None:
kwargs = {}
super().__init__(group, target, name, args, kwargs, daemon=True) # type: ignore
self._return: Any = None
self._err: Optional[Exception] = None
def run(self):
target: Union[Callable, Coroutine] = self._target # type: ignore
if target is not None: # type: ignore
with torch.no_grad():
if isinstance(target, Callable):
logger.debug(
"Executing coroutine %s in %s", target.__name__, self.name
)
try:
self._return = target(*self._args, **self._kwargs) # type: ignore
except Exception as err:
self._err = err
else:
logger.debug(
"Executing coroutine %s in %s", target.__name__, self.name
)
try:
if asyncio_loop:
self._return = ensure_future(
target, loop=asyncio_loop
).result()
else:
raise Exception("Asyncio loop not found")
except Exception as err:
self._err = err
def join(self, *args) -> Tuple[Union[Any, None], Union[Exception, None]]:
Thread.join(self, *args)
return (self._return, self._err)
The provided code snippet includes necessary dependencies for implementing the `run_in_thread_async` function. Write a Python function `async def run_in_thread_async( func: Union[Callable[..., Any], Coroutine[Any, Any, Any]], args: Optional[Tuple] = None, kwarkgs: Optional[Dict] = None, ) -> Any` to solve the following problem:
Run a function in a separate thread
Here is the function:
async def run_in_thread_async(
func: Union[Callable[..., Any], Coroutine[Any, Any, Any]],
args: Optional[Tuple] = None,
kwarkgs: Optional[Dict] = None,
) -> Any:
"Run a function in a separate thread"
thread = ThreadWithReturnValue(target=func, args=args, kwargs=kwarkgs)
thread.start()
# wait for the thread to finish
while thread.is_alive():
await asyncio.sleep(0.1)
# get the value returned from the thread
value, exc = thread.join()
if exc:
raise exc
return value | Run a function in a separate thread |
156,367 | import asyncio
import base64
import json
import logging
import math
import os
import re
import struct
from enum import Enum
from io import BytesIO
from pathlib import Path
from typing import Any, Callable, Coroutine, Dict, List, Optional, Tuple, Union
import requests
from PIL import Image
from requests.adapters import HTTPAdapter, Retry
from tqdm import tqdm
from core.thread import ThreadWithReturnValue
from core.types import ImageFormats, InferenceJob, PyTorchModelBase, PyTorchModelStage
The provided code snippet includes necessary dependencies for implementing the `resize` function. Write a Python function `def resize(image: Image.Image, w: int, h: int)` to solve the following problem:
Preprocess an image for the img2img procedure
Here is the function:
def resize(image: Image.Image, w: int, h: int):
"Preprocess an image for the img2img procedure"
return image.resize((w, h), resample=Image.LANCZOS) | Preprocess an image for the img2img procedure |
156,368 | import asyncio
import base64
import json
import logging
import math
import os
import re
import struct
from enum import Enum
from io import BytesIO
from pathlib import Path
from typing import Any, Callable, Coroutine, Dict, List, Optional, Tuple, Union
import requests
from PIL import Image
from requests.adapters import HTTPAdapter, Retry
from tqdm import tqdm
from core.thread import ThreadWithReturnValue
from core.types import ImageFormats, InferenceJob, PyTorchModelBase, PyTorchModelStage
InferenceJob = Union[
Txt2ImgQueueEntry,
Img2ImgQueueEntry,
InpaintQueueEntry,
ControlNetQueueEntry,
]
def preprocess_job(job: InferenceJob):
return job | null |
156,369 | import functools
import logging
from typing import Any, Callable, Iterable, List, Optional
from asdff.utils import (
ADOutput,
bbox_padding,
composite,
mask_dilate,
mask_gaussian_blur,
)
from asdff.yolo import yolo_detector
from PIL import Image, ImageOps
from core.types import InpaintQueueEntry
from core.utils import convert_to_image
def ordinal(n: int) -> str:
d = {1: "st", 2: "nd", 3: "rd"}
return str(n) + ("th" if 11 <= n % 100 <= 13 else d.get(n % 10, "th")) | null |
156,370 | import gc
from typing import Optional
import numpy as np
import torch
def bgr_to_rgb(image: torch.Tensor) -> torch.Tensor:
def rgb_to_bgr(image: torch.Tensor) -> torch.Tensor:
# same operation as bgr_to_rgb(), flip image channels
return bgr_to_rgb(image) | null |
156,371 | import gc
from typing import Optional
import numpy as np
import torch
def bgra_to_rgba(image: torch.Tensor) -> torch.Tensor:
out: torch.Tensor = image[[2, 1, 0, 3], :, :]
return out
def rgba_to_bgra(image: torch.Tensor) -> torch.Tensor:
# same operation as bgra_to_rgba(), flip image channels
return bgra_to_rgba(image) | null |
156,372 | import gc
from typing import Optional
import numpy as np
import torch
def auto_split_upscale(
lr_img: np.ndarray,
upscale_function,
scale: int = 4,
overlap: int = 32,
max_depth: Optional[int] = None,
current_depth: int = 1,
):
# Attempt to upscale if unknown depth or if reached known max depth
if max_depth is None or max_depth == current_depth:
try:
result = upscale_function(lr_img)
return result, current_depth
except RuntimeError as e:
# Check to see if its actually the CUDA out of memory error
if "CUDA" in str(e):
# Collect garbage (clear VRAM)
torch.cuda.empty_cache()
gc.collect()
# Re-raise the exception if not an OOM error
else:
raise RuntimeError(e) from e
h, w, c = lr_img.shape
# Split image into 4ths
top_left = lr_img[: h // 2 + overlap, : w // 2 + overlap, :]
top_right = lr_img[: h // 2 + overlap, w // 2 - overlap :, :]
bottom_left = lr_img[h // 2 - overlap :, : w // 2 + overlap, :]
bottom_right = lr_img[h // 2 - overlap :, w // 2 - overlap :, :]
# Recursively upscale the quadrants
# After we go through the top left quadrant, we know the maximum depth and no longer need to test for out-of-memory
top_left_rlt, depth = auto_split_upscale(
top_left,
upscale_function,
scale=scale,
overlap=overlap,
max_depth=max_depth,
current_depth=current_depth + 1,
)
top_right_rlt, _ = auto_split_upscale(
top_right,
upscale_function,
scale=scale,
overlap=overlap,
max_depth=depth,
current_depth=current_depth + 1,
)
bottom_left_rlt, _ = auto_split_upscale(
bottom_left,
upscale_function,
scale=scale,
overlap=overlap,
max_depth=depth,
current_depth=current_depth + 1,
)
bottom_right_rlt, _ = auto_split_upscale(
bottom_right,
upscale_function,
scale=scale,
overlap=overlap,
max_depth=depth,
current_depth=current_depth + 1,
)
# Define output shape
out_h = h * scale
out_w = w * scale
# Create blank output image
output_img = np.zeros((out_h, out_w, c), np.uint8)
# Fill output image with tiles, cropping out the overlaps
output_img[: out_h // 2, : out_w // 2, :] = top_left_rlt[
: out_h // 2, : out_w // 2, :
]
output_img[: out_h // 2, -out_w // 2 :, :] = top_right_rlt[
: out_h // 2, -out_w // 2 :, :
]
output_img[-out_h // 2 :, : out_w // 2, :] = bottom_left_rlt[
-out_h // 2 :, : out_w // 2, :
]
output_img[-out_h // 2 :, -out_w // 2 :, :] = bottom_right_rlt[
-out_h // 2 :, -out_w // 2 :, :
]
return output_img, depth | null |
156,373 | from collections import OrderedDict
import torch
import torch.nn as nn
def conv1x1(in_planes, out_planes, stride=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) | null |
156,374 | from collections import OrderedDict
import torch
import torch.nn as nn
def act(act_type, inplace=True, neg_slope=0.2, n_prelu=1):
# helper selecting activation
# neg_slope: for leakyrelu and init of prelu
# n_prelu: for p_relu num_parameters
act_type = act_type.lower()
if act_type == "relu":
layer = nn.ReLU(inplace)
elif act_type == "leakyrelu":
layer = nn.LeakyReLU(neg_slope, inplace)
elif act_type == "prelu":
layer = nn.PReLU(num_parameters=n_prelu, init=neg_slope)
else:
raise NotImplementedError(
"activation layer [{:s}] is not found".format(act_type)
)
return layer
def norm(norm_type, nc):
# helper selecting normalization layer
norm_type = norm_type.lower()
if norm_type == "batch":
layer = nn.BatchNorm2d(nc, affine=True)
elif norm_type == "instance":
layer = nn.InstanceNorm2d(nc, affine=False)
else:
raise NotImplementedError(
"normalization layer [{:s}] is not found".format(norm_type)
)
return layer
def sequential(*args):
# Flatten Sequential. It unwraps nn.Sequential.
if len(args) == 1:
if isinstance(args[0], OrderedDict):
raise NotImplementedError("sequential does not support OrderedDict input.")
return args[0] # No sequential is needed.
modules = []
for module in args:
if isinstance(module, nn.Sequential):
for submodule in module.children():
modules.append(submodule)
elif isinstance(module, nn.Module):
modules.append(module)
return nn.Sequential(*modules)
def conv_block(
in_nc,
out_nc,
kernel_size,
stride=1,
dilation=1,
groups=1,
bias=True,
pad_type="zero",
norm_type=None,
act_type="relu",
mode="CNA",
c2x2=False,
):
"""
Conv layer with padding, normalization, activation
mode: CNA --> Conv -> Norm -> Act
NAC --> Norm -> Act --> Conv (Identity Mappings in Deep Residual Networks, ECCV16)
"""
if c2x2:
return conv_block_2c2(in_nc, out_nc, act_type=act_type)
assert mode in ["CNA", "NAC", "CNAC"], "Wrong conv mode [{:s}]".format(mode)
padding = get_valid_padding(kernel_size, dilation)
p = pad(pad_type, padding) if pad_type and pad_type != "zero" else None
padding = padding if pad_type == "zero" else 0
c = nn.Conv2d(
in_nc,
out_nc,
kernel_size=kernel_size,
stride=stride,
padding=padding,
dilation=dilation,
bias=bias,
groups=groups,
)
a = act(act_type) if act_type else None
if "CNA" in mode:
n = norm(norm_type, out_nc) if norm_type else None
return sequential(p, c, n, a)
elif mode == "NAC":
if norm_type is None and act_type is not None:
a = act(act_type, inplace=False)
# Important!
# input----ReLU(inplace)----Conv--+----output
# |________________________|
# inplace ReLU will modify the input, therefore wrong output
n = norm(norm_type, in_nc) if norm_type else None
return sequential(n, a, p, c)
The provided code snippet includes necessary dependencies for implementing the `pixelshuffle_block` function. Write a Python function `def pixelshuffle_block( in_nc, out_nc, upscale_factor=2, kernel_size=3, stride=1, bias=True, pad_type="zero", norm_type=None, act_type="relu", )` to solve the following problem:
Pixel shuffle layer (Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel Convolutional Neural Network, CVPR17)
Here is the function:
def pixelshuffle_block(
in_nc,
out_nc,
upscale_factor=2,
kernel_size=3,
stride=1,
bias=True,
pad_type="zero",
norm_type=None,
act_type="relu",
):
"""
Pixel shuffle layer
(Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel Convolutional
Neural Network, CVPR17)
"""
conv = conv_block(
in_nc,
out_nc * (upscale_factor**2),
kernel_size,
stride,
bias=bias,
pad_type=pad_type,
norm_type=None,
act_type=None, # type: ignore
)
pixel_shuffle = nn.PixelShuffle(upscale_factor)
n = norm(norm_type, out_nc) if norm_type else None
a = act(act_type) if act_type else None
return sequential(conv, pixel_shuffle, n, a) | Pixel shuffle layer (Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel Convolutional Neural Network, CVPR17) |
156,375 | from collections import OrderedDict
import torch
import torch.nn as nn
def sequential(*args):
# Flatten Sequential. It unwraps nn.Sequential.
if len(args) == 1:
if isinstance(args[0], OrderedDict):
raise NotImplementedError("sequential does not support OrderedDict input.")
return args[0] # No sequential is needed.
modules = []
for module in args:
if isinstance(module, nn.Sequential):
for submodule in module.children():
modules.append(submodule)
elif isinstance(module, nn.Module):
modules.append(module)
return nn.Sequential(*modules)
def conv_block(
in_nc,
out_nc,
kernel_size,
stride=1,
dilation=1,
groups=1,
bias=True,
pad_type="zero",
norm_type=None,
act_type="relu",
mode="CNA",
c2x2=False,
):
"""
Conv layer with padding, normalization, activation
mode: CNA --> Conv -> Norm -> Act
NAC --> Norm -> Act --> Conv (Identity Mappings in Deep Residual Networks, ECCV16)
"""
if c2x2:
return conv_block_2c2(in_nc, out_nc, act_type=act_type)
assert mode in ["CNA", "NAC", "CNAC"], "Wrong conv mode [{:s}]".format(mode)
padding = get_valid_padding(kernel_size, dilation)
p = pad(pad_type, padding) if pad_type and pad_type != "zero" else None
padding = padding if pad_type == "zero" else 0
c = nn.Conv2d(
in_nc,
out_nc,
kernel_size=kernel_size,
stride=stride,
padding=padding,
dilation=dilation,
bias=bias,
groups=groups,
)
a = act(act_type) if act_type else None
if "CNA" in mode:
n = norm(norm_type, out_nc) if norm_type else None
return sequential(p, c, n, a)
elif mode == "NAC":
if norm_type is None and act_type is not None:
a = act(act_type, inplace=False)
# Important!
# input----ReLU(inplace)----Conv--+----output
# |________________________|
# inplace ReLU will modify the input, therefore wrong output
n = norm(norm_type, in_nc) if norm_type else None
return sequential(n, a, p, c)
def upconv_block(
in_nc,
out_nc,
upscale_factor=2,
kernel_size=3,
stride=1,
bias=True,
pad_type="zero",
norm_type=None,
act_type="relu",
mode="nearest",
c2x2=False,
):
# Up conv
# described in https://distill.pub/2016/deconv-checkerboard/
upsample = nn.Upsample(scale_factor=upscale_factor, mode=mode)
conv = conv_block(
in_nc,
out_nc,
kernel_size,
stride,
bias=bias,
pad_type=pad_type,
norm_type=norm_type,
act_type=act_type,
c2x2=c2x2,
)
return sequential(upsample, conv) | null |
156,376 | import io
import json
import logging
import os
from functools import partial
from importlib.util import find_spec
from pathlib import Path
from typing import Any, Dict, Optional, Tuple, Union
import requests
import torch
from diffusers.models.autoencoder_kl import AutoencoderKL
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
from diffusers.pipelines.stable_diffusion.convert_from_ckpt import (
assign_to_checkpoint,
conv_attn_to_linear,
create_vae_diffusers_config,
renew_vae_attention_paths,
renew_vae_resnet_paths,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import (
StableDiffusionPipeline,
)
from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl import (
StableDiffusionXLPipeline,
)
from diffusers.schedulers.scheduling_utils import SCHEDULER_CONFIG_NAME
from diffusers.utils.constants import (
CONFIG_NAME,
DIFFUSERS_CACHE,
HUGGINGFACE_CO_RESOLVE_ENDPOINT,
ONNX_WEIGHTS_NAME,
WEIGHTS_NAME,
)
from diffusers.utils.hub_utils import HF_HUB_OFFLINE
from huggingface_hub import model_info
from huggingface_hub._snapshot_download import snapshot_download
from huggingface_hub.file_download import hf_hub_download
from huggingface_hub.hf_api import ModelInfo
from huggingface_hub.utils._errors import (
EntryNotFoundError,
RepositoryNotFoundError,
RevisionNotFoundError,
)
from omegaconf import OmegaConf
from packaging import version
from requests import HTTPError
from transformers.models.clip.modeling_clip import BaseModelOutput
from core.config import config
from core.files import get_full_model_path
from core.flags import HighResFixFlag
from core.optimizations import compile_sfast
from core.types import Job
from core.utils import determine_model_type
The provided code snippet includes necessary dependencies for implementing the `is_aitemplate_available` function. Write a Python function `def is_aitemplate_available()` to solve the following problem:
Checks whether AITemplate is available.
Here is the function:
def is_aitemplate_available():
"Checks whether AITemplate is available."
return find_spec("aitemplate") is not None | Checks whether AITemplate is available. |
156,377 | import io
import json
import logging
import os
from functools import partial
from importlib.util import find_spec
from pathlib import Path
from typing import Any, Dict, Optional, Tuple, Union
import requests
import torch
from diffusers.models.autoencoder_kl import AutoencoderKL
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
from diffusers.pipelines.stable_diffusion.convert_from_ckpt import (
assign_to_checkpoint,
conv_attn_to_linear,
create_vae_diffusers_config,
renew_vae_attention_paths,
renew_vae_resnet_paths,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import (
StableDiffusionPipeline,
)
from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl import (
StableDiffusionXLPipeline,
)
from diffusers.schedulers.scheduling_utils import SCHEDULER_CONFIG_NAME
from diffusers.utils.constants import (
CONFIG_NAME,
DIFFUSERS_CACHE,
HUGGINGFACE_CO_RESOLVE_ENDPOINT,
ONNX_WEIGHTS_NAME,
WEIGHTS_NAME,
)
from diffusers.utils.hub_utils import HF_HUB_OFFLINE
from huggingface_hub import model_info
from huggingface_hub._snapshot_download import snapshot_download
from huggingface_hub.file_download import hf_hub_download
from huggingface_hub.hf_api import ModelInfo
from huggingface_hub.utils._errors import (
EntryNotFoundError,
RepositoryNotFoundError,
RevisionNotFoundError,
)
from omegaconf import OmegaConf
from packaging import version
from requests import HTTPError
from transformers.models.clip.modeling_clip import BaseModelOutput
from core.config import config
from core.files import get_full_model_path
from core.flags import HighResFixFlag
from core.optimizations import compile_sfast
from core.types import Job
from core.utils import determine_model_type
The provided code snippet includes necessary dependencies for implementing the `is_onnxconverter_available` function. Write a Python function `def is_onnxconverter_available()` to solve the following problem:
Checks whether onnxconverter-common is installed. Onnxconverter-common can be installed using `pip install onnxconverter-common`
Here is the function:
def is_onnxconverter_available():
"Checks whether onnxconverter-common is installed. Onnxconverter-common can be installed using `pip install onnxconverter-common`"
return find_spec("onnxconverter_common") is not None | Checks whether onnxconverter-common is installed. Onnxconverter-common can be installed using `pip install onnxconverter-common` |
156,378 | import io
import json
import logging
import os
from functools import partial
from importlib.util import find_spec
from pathlib import Path
from typing import Any, Dict, Optional, Tuple, Union
import requests
import torch
from diffusers.models.autoencoder_kl import AutoencoderKL
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
from diffusers.pipelines.stable_diffusion.convert_from_ckpt import (
assign_to_checkpoint,
conv_attn_to_linear,
create_vae_diffusers_config,
renew_vae_attention_paths,
renew_vae_resnet_paths,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import (
StableDiffusionPipeline,
)
from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl import (
StableDiffusionXLPipeline,
)
from diffusers.schedulers.scheduling_utils import SCHEDULER_CONFIG_NAME
from diffusers.utils.constants import (
CONFIG_NAME,
DIFFUSERS_CACHE,
HUGGINGFACE_CO_RESOLVE_ENDPOINT,
ONNX_WEIGHTS_NAME,
WEIGHTS_NAME,
)
from diffusers.utils.hub_utils import HF_HUB_OFFLINE
from huggingface_hub import model_info
from huggingface_hub._snapshot_download import snapshot_download
from huggingface_hub.file_download import hf_hub_download
from huggingface_hub.hf_api import ModelInfo
from huggingface_hub.utils._errors import (
EntryNotFoundError,
RepositoryNotFoundError,
RevisionNotFoundError,
)
from omegaconf import OmegaConf
from packaging import version
from requests import HTTPError
from transformers.models.clip.modeling_clip import BaseModelOutput
from core.config import config
from core.files import get_full_model_path
from core.flags import HighResFixFlag
from core.optimizations import compile_sfast
from core.types import Job
from core.utils import determine_model_type
The provided code snippet includes necessary dependencies for implementing the `is_onnx_available` function. Write a Python function `def is_onnx_available()` to solve the following problem:
Checks whether onnx and onnxruntime is installed. Onnx can be installed using `pip install onnx onnxruntime`
Here is the function:
def is_onnx_available():
"Checks whether onnx and onnxruntime is installed. Onnx can be installed using `pip install onnx onnxruntime`"
return find_spec("onnx") is not None and find_spec("onnxruntime") is not None | Checks whether onnx and onnxruntime is installed. Onnx can be installed using `pip install onnx onnxruntime` |
156,379 | import io
import json
import logging
import os
from functools import partial
from importlib.util import find_spec
from pathlib import Path
from typing import Any, Dict, Optional, Tuple, Union
import requests
import torch
from diffusers.models.autoencoder_kl import AutoencoderKL
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
from diffusers.pipelines.stable_diffusion.convert_from_ckpt import (
assign_to_checkpoint,
conv_attn_to_linear,
create_vae_diffusers_config,
renew_vae_attention_paths,
renew_vae_resnet_paths,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import (
StableDiffusionPipeline,
)
from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl import (
StableDiffusionXLPipeline,
)
from diffusers.schedulers.scheduling_utils import SCHEDULER_CONFIG_NAME
from diffusers.utils.constants import (
CONFIG_NAME,
DIFFUSERS_CACHE,
HUGGINGFACE_CO_RESOLVE_ENDPOINT,
ONNX_WEIGHTS_NAME,
WEIGHTS_NAME,
)
from diffusers.utils.hub_utils import HF_HUB_OFFLINE
from huggingface_hub import model_info
from huggingface_hub._snapshot_download import snapshot_download
from huggingface_hub.file_download import hf_hub_download
from huggingface_hub.hf_api import ModelInfo
from huggingface_hub.utils._errors import (
EntryNotFoundError,
RepositoryNotFoundError,
RevisionNotFoundError,
)
from omegaconf import OmegaConf
from packaging import version
from requests import HTTPError
from transformers.models.clip.modeling_clip import BaseModelOutput
from core.config import config
from core.files import get_full_model_path
from core.flags import HighResFixFlag
from core.optimizations import compile_sfast
from core.types import Job
from core.utils import determine_model_type
The provided code snippet includes necessary dependencies for implementing the `is_onnxscript_available` function. Write a Python function `def is_onnxscript_available()` to solve the following problem:
Checks whether onnx-script is installed. Onnx-script can be installed with the instructions from https://github.com/microsoft/onnx-script#installing-onnx-script
Here is the function:
def is_onnxscript_available():
"Checks whether onnx-script is installed. Onnx-script can be installed with the instructions from https://github.com/microsoft/onnx-script#installing-onnx-script"
return find_spec("onnxscript") is not None | Checks whether onnx-script is installed. Onnx-script can be installed with the instructions from https://github.com/microsoft/onnx-script#installing-onnx-script |
156,380 | import io
import json
import logging
import os
from functools import partial
from importlib.util import find_spec
from pathlib import Path
from typing import Any, Dict, Optional, Tuple, Union
import requests
import torch
from diffusers.models.autoencoder_kl import AutoencoderKL
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
from diffusers.pipelines.stable_diffusion.convert_from_ckpt import (
assign_to_checkpoint,
conv_attn_to_linear,
create_vae_diffusers_config,
renew_vae_attention_paths,
renew_vae_resnet_paths,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import (
StableDiffusionPipeline,
)
from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl import (
StableDiffusionXLPipeline,
)
from diffusers.schedulers.scheduling_utils import SCHEDULER_CONFIG_NAME
from diffusers.utils.constants import (
CONFIG_NAME,
DIFFUSERS_CACHE,
HUGGINGFACE_CO_RESOLVE_ENDPOINT,
ONNX_WEIGHTS_NAME,
WEIGHTS_NAME,
)
from diffusers.utils.hub_utils import HF_HUB_OFFLINE
from huggingface_hub import model_info
from huggingface_hub._snapshot_download import snapshot_download
from huggingface_hub.file_download import hf_hub_download
from huggingface_hub.hf_api import ModelInfo
from huggingface_hub.utils._errors import (
EntryNotFoundError,
RepositoryNotFoundError,
RevisionNotFoundError,
)
from omegaconf import OmegaConf
from packaging import version
from requests import HTTPError
from transformers.models.clip.modeling_clip import BaseModelOutput
from core.config import config
from core.files import get_full_model_path
from core.flags import HighResFixFlag
from core.optimizations import compile_sfast
from core.types import Job
from core.utils import determine_model_type
The provided code snippet includes necessary dependencies for implementing the `is_onnxsim_available` function. Write a Python function `def is_onnxsim_available()` to solve the following problem:
Checks whether onnx-simplifier is available. Onnx-simplifier can be installed using `pip install onnxsim`
Here is the function:
def is_onnxsim_available():
"Checks whether onnx-simplifier is available. Onnx-simplifier can be installed using `pip install onnxsim`"
return find_spec("onnxsim") is not None | Checks whether onnx-simplifier is available. Onnx-simplifier can be installed using `pip install onnxsim` |
156,381 | import io
import json
import logging
import os
from functools import partial
from importlib.util import find_spec
from pathlib import Path
from typing import Any, Dict, Optional, Tuple, Union
import requests
import torch
from diffusers.models.autoencoder_kl import AutoencoderKL
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
from diffusers.pipelines.stable_diffusion.convert_from_ckpt import (
assign_to_checkpoint,
conv_attn_to_linear,
create_vae_diffusers_config,
renew_vae_attention_paths,
renew_vae_resnet_paths,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import (
StableDiffusionPipeline,
)
from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl import (
StableDiffusionXLPipeline,
)
from diffusers.schedulers.scheduling_utils import SCHEDULER_CONFIG_NAME
from diffusers.utils.constants import (
CONFIG_NAME,
DIFFUSERS_CACHE,
HUGGINGFACE_CO_RESOLVE_ENDPOINT,
ONNX_WEIGHTS_NAME,
WEIGHTS_NAME,
)
from diffusers.utils.hub_utils import HF_HUB_OFFLINE
from huggingface_hub import model_info
from huggingface_hub._snapshot_download import snapshot_download
from huggingface_hub.file_download import hf_hub_download
from huggingface_hub.hf_api import ModelInfo
from huggingface_hub.utils._errors import (
EntryNotFoundError,
RepositoryNotFoundError,
RevisionNotFoundError,
)
from omegaconf import OmegaConf
from packaging import version
from requests import HTTPError
from transformers.models.clip.modeling_clip import BaseModelOutput
from core.config import config
from core.files import get_full_model_path
from core.flags import HighResFixFlag
from core.optimizations import compile_sfast
from core.types import Job
from core.utils import determine_model_type
config_name = "model_index.json"
def load_config(
pretrained_model_name_or_path: Union[str, os.PathLike],
return_unused_kwargs=False,
**kwargs,
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
r"""
Instantiate a Python class from a config dictionary
Parameters:
pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*):
Can be either:
- A string, the *model id* of a model repo on huggingface.co. Valid model ids should have an
organization name, like `google/ddpm-celebahq-256`.
- A path to a *directory* containing model weights saved using [`~ConfigMixin.save_config`], e.g.,
`./my_model_directory/`.
cache_dir (`Union[str, os.PathLike]`, *optional*):
Path to a directory in which a downloaded pretrained model configuration should be cached if the
standard cache should not be used.
force_download (`bool`, *optional*, defaults to `False`):
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
cached versions if they exist.
resume_download (`bool`, *optional*, defaults to `False`):
Whether or not to delete incompletely received files. Will attempt to resume the download if such a
file exists.
proxies (`Dict[str, str]`, *optional*):
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
output_loading_info(`bool`, *optional*, defaults to `False`):
Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
local_files_only(`bool`, *optional*, defaults to `False`):
Whether or not to only look at local files (i.e., do not try to download the model).
use_auth_token (`str` or *bool*, *optional*):
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
when running `transformers-cli login` (stored in `~/.huggingface`).
revision (`str`, *optional*, defaults to `"main"`):
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
identifier allowed by git.
subfolder (`str`, *optional*, defaults to `""`):
In case the relevant files are located inside a subfolder of the model repo (either remote in
huggingface.co or downloaded locally), you can specify the folder name here.
<Tip>
It is required to be logged in (`huggingface-cli login`) when you want to use private or [gated
models](https://huggingface.co/docs/hub/models-gated#gated-models).
</Tip>
<Tip>
Activate the special ["offline-mode"](https://huggingface.co/transformers/installation.html#offline-mode) to
use this method in a firewalled environment.
</Tip>
"""
cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
force_download = kwargs.pop("force_download", False)
resume_download = kwargs.pop("resume_download", False)
proxies = kwargs.pop("proxies", None)
use_auth_token = kwargs.pop("use_auth_token", None)
local_files_only = kwargs.pop("local_files_only", False)
revision = kwargs.pop("revision", None)
_ = kwargs.pop("mirror", None)
subfolder = kwargs.pop("subfolder", None)
user_agent = {"file_type": "config"}
pretrained_model_name_or_path = str(pretrained_model_name_or_path)
if config_name is None:
raise ValueError(
"`self.config_name` is not defined. Note that one should not load a config from "
"`ConfigMixin`. Please make sure to define `config_name` in a class inheriting from `ConfigMixin`"
)
if os.path.isfile(pretrained_model_name_or_path):
config_file = pretrained_model_name_or_path
elif os.path.isdir(pretrained_model_name_or_path):
if os.path.isfile(os.path.join(pretrained_model_name_or_path, config_name)):
# Load from a PyTorch checkpoint
config_file = os.path.join(pretrained_model_name_or_path, config_name)
elif subfolder is not None and os.path.isfile(
os.path.join(pretrained_model_name_or_path, subfolder, config_name)
):
config_file = os.path.join(
pretrained_model_name_or_path, subfolder, config_name
)
else:
raise EnvironmentError(
f"Error no file named {config_name} found in directory {pretrained_model_name_or_path}."
)
else:
try:
# Load from URL or cache if already cached
config_file = hf_hub_download(
pretrained_model_name_or_path,
filename=config_name,
cache_dir=cache_dir,
force_download=force_download,
proxies=proxies,
resume_download=resume_download,
local_files_only=local_files_only,
token=use_auth_token,
user_agent=user_agent,
subfolder=subfolder,
revision=revision,
)
except RepositoryNotFoundError as err:
raise EnvironmentError(
f"{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier"
" listed on 'https://huggingface.co/models'\nIf this is a private repository, make sure to pass a"
" token having permission to this repo with `use_auth_token` or log in with `huggingface-cli"
" login`."
) from err
except RevisionNotFoundError as err:
raise EnvironmentError(
f"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for"
" this model name. Check the model page at"
f" 'https://huggingface.co/{pretrained_model_name_or_path}' for available revisions."
) from err
except EntryNotFoundError as err:
raise EnvironmentError(
f"{pretrained_model_name_or_path} does not appear to have a file named {config_name}."
) from err
except HTTPError as err:
raise EnvironmentError(
"There was a specific connection error when trying to load"
f" {pretrained_model_name_or_path}:\n{err}"
) from err
except ValueError as err:
raise EnvironmentError(
f"We couldn't connect to '{HUGGINGFACE_CO_RESOLVE_ENDPOINT}' to load this model, couldn't find it"
f" in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a"
f" directory containing a {config_name} file.\nCheckout your internet connection or see how to"
" run the library in offline mode at"
" 'https://huggingface.co/docs/diffusers/installation#offline-mode'."
) from err
except EnvironmentError as err:
raise EnvironmentError(
f"Can't load config for '{pretrained_model_name_or_path}'. If you were trying to load it from "
"'https://huggingface.co/models', make sure you don't have a local directory with the same name. "
f"Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory "
f"containing a {config_name} file"
) from err
try:
# Load config dict
assert config_file is not None
config_dict = dict_from_json_file(config_file)
except (json.JSONDecodeError, UnicodeDecodeError) as err:
raise EnvironmentError(
f"It looks like the config file at '{config_file}' is not a valid JSON file."
) from err
if return_unused_kwargs:
return config_dict, kwargs
return config_dict
def is_safetensors_compatible(info: ModelInfo) -> bool:
"Check if the model is compatible with safetensors"
filenames = set(sibling.rfilename for sibling in info.siblings)
pt_filenames = set(filename for filename in filenames if filename.endswith(".bin"))
safetensors_compatible = any(file.endswith(".safetensors") for file in filenames)
for pt_filename in pt_filenames:
prefix, raw = os.path.split(pt_filename)
if raw == "pytorch_model.bin":
# transformers specific
sf_filename = os.path.join(prefix, "model.safetensors")
else:
sf_filename = pt_filename[: -len(".bin")] + ".safetensors"
if safetensors_compatible and sf_filename not in filenames:
logger.warning(f"{sf_filename} not found")
safetensors_compatible = False
return safetensors_compatible
The provided code snippet includes necessary dependencies for implementing the `download_model` function. Write a Python function `def download_model( pretrained_model_name: str, cache_dir: Path = Path(DIFFUSERS_CACHE), resume_download: bool = True, revision: Optional[str] = None, local_files_only: bool = HF_HUB_OFFLINE, force_download: bool = False, )` to solve the following problem:
Download a model from the Hugging Face Hub
Here is the function:
def download_model(
pretrained_model_name: str,
cache_dir: Path = Path(DIFFUSERS_CACHE),
resume_download: bool = True,
revision: Optional[str] = None,
local_files_only: bool = HF_HUB_OFFLINE,
force_download: bool = False,
):
"Download a model from the Hugging Face Hub"
if not os.path.isdir(pretrained_model_name):
config_dict = load_config(
pretrained_model_name_or_path=pretrained_model_name,
cache_dir=cache_dir,
resume_download=resume_download,
force_download=force_download,
local_files_only=local_files_only,
revision=revision,
)
# make sure we only download sub-folders and `diffusers` filenames
folder_names = [k for k in config_dict.keys() if not k.startswith("_")] # type: ignore
allow_patterns = [os.path.join(k, "*") for k in folder_names]
allow_patterns += [
WEIGHTS_NAME,
SCHEDULER_CONFIG_NAME,
CONFIG_NAME,
ONNX_WEIGHTS_NAME,
config_name,
]
# # make sure we don't download flax weights
ignore_patterns = ["*.msgpack"]
if not local_files_only:
info = model_info(
repo_id=pretrained_model_name,
revision=revision,
)
if is_safetensors_compatible(info):
ignore_patterns.append("*.bin")
else:
# as a safety mechanism we also don't download safetensors if
# not all safetensors files are there
ignore_patterns.append("*.safetensors")
else:
ignore_patterns.append("*.safetensors")
snapshot_download(
repo_id=pretrained_model_name,
cache_dir=cache_dir,
resume_download=resume_download,
local_files_only=local_files_only,
revision=revision,
allow_patterns=allow_patterns,
ignore_patterns=ignore_patterns,
) | Download a model from the Hugging Face Hub |
156,382 | import io
import json
import logging
import os
from functools import partial
from importlib.util import find_spec
from pathlib import Path
from typing import Any, Dict, Optional, Tuple, Union
import requests
import torch
from diffusers.models.autoencoder_kl import AutoencoderKL
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
from diffusers.pipelines.stable_diffusion.convert_from_ckpt import (
assign_to_checkpoint,
conv_attn_to_linear,
create_vae_diffusers_config,
renew_vae_attention_paths,
renew_vae_resnet_paths,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import (
StableDiffusionPipeline,
)
from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl import (
StableDiffusionXLPipeline,
)
from diffusers.schedulers.scheduling_utils import SCHEDULER_CONFIG_NAME
from diffusers.utils.constants import (
CONFIG_NAME,
DIFFUSERS_CACHE,
HUGGINGFACE_CO_RESOLVE_ENDPOINT,
ONNX_WEIGHTS_NAME,
WEIGHTS_NAME,
)
from diffusers.utils.hub_utils import HF_HUB_OFFLINE
from huggingface_hub import model_info
from huggingface_hub._snapshot_download import snapshot_download
from huggingface_hub.file_download import hf_hub_download
from huggingface_hub.hf_api import ModelInfo
from huggingface_hub.utils._errors import (
EntryNotFoundError,
RepositoryNotFoundError,
RevisionNotFoundError,
)
from omegaconf import OmegaConf
from packaging import version
from requests import HTTPError
from transformers.models.clip.modeling_clip import BaseModelOutput
from core.config import config
from core.files import get_full_model_path
from core.flags import HighResFixFlag
from core.optimizations import compile_sfast
from core.types import Job
from core.utils import determine_model_type
def _custom_convert_ldm_vae_checkpoint(checkpoint, conf):
vae_state_dict = checkpoint
new_checkpoint = {}
new_checkpoint["encoder.conv_in.weight"] = vae_state_dict["encoder.conv_in.weight"]
new_checkpoint["encoder.conv_in.bias"] = vae_state_dict["encoder.conv_in.bias"]
new_checkpoint["encoder.conv_out.weight"] = vae_state_dict[
"encoder.conv_out.weight"
]
new_checkpoint["encoder.conv_out.bias"] = vae_state_dict["encoder.conv_out.bias"]
new_checkpoint["encoder.conv_norm_out.weight"] = vae_state_dict[
"encoder.norm_out.weight"
]
new_checkpoint["encoder.conv_norm_out.bias"] = vae_state_dict[
"encoder.norm_out.bias"
]
new_checkpoint["decoder.conv_in.weight"] = vae_state_dict["decoder.conv_in.weight"]
new_checkpoint["decoder.conv_in.bias"] = vae_state_dict["decoder.conv_in.bias"]
new_checkpoint["decoder.conv_out.weight"] = vae_state_dict[
"decoder.conv_out.weight"
]
new_checkpoint["decoder.conv_out.bias"] = vae_state_dict["decoder.conv_out.bias"]
new_checkpoint["decoder.conv_norm_out.weight"] = vae_state_dict[
"decoder.norm_out.weight"
]
new_checkpoint["decoder.conv_norm_out.bias"] = vae_state_dict[
"decoder.norm_out.bias"
]
new_checkpoint["quant_conv.weight"] = vae_state_dict["quant_conv.weight"]
new_checkpoint["quant_conv.bias"] = vae_state_dict["quant_conv.bias"]
new_checkpoint["post_quant_conv.weight"] = vae_state_dict["post_quant_conv.weight"]
new_checkpoint["post_quant_conv.bias"] = vae_state_dict["post_quant_conv.bias"]
# Retrieves the keys for the encoder down blocks only
num_down_blocks = len(
{
".".join(layer.split(".")[:3])
for layer in vae_state_dict
if "encoder.down" in layer
}
)
down_blocks = {
layer_id: [key for key in vae_state_dict if f"down.{layer_id}" in key]
for layer_id in range(num_down_blocks)
}
# Retrieves the keys for the decoder up blocks only
num_up_blocks = len(
{
".".join(layer.split(".")[:3])
for layer in vae_state_dict
if "decoder.up" in layer
}
)
up_blocks = {
layer_id: [key for key in vae_state_dict if f"up.{layer_id}" in key]
for layer_id in range(num_up_blocks)
}
for i in range(num_down_blocks):
resnets = [
key
for key in down_blocks[i]
if f"down.{i}" in key and f"down.{i}.downsample" not in key
]
if f"encoder.down.{i}.downsample.conv.weight" in vae_state_dict:
new_checkpoint[
f"encoder.down_blocks.{i}.downsamplers.0.conv.weight"
] = vae_state_dict.pop(f"encoder.down.{i}.downsample.conv.weight")
new_checkpoint[
f"encoder.down_blocks.{i}.downsamplers.0.conv.bias"
] = vae_state_dict.pop(f"encoder.down.{i}.downsample.conv.bias")
paths = renew_vae_resnet_paths(resnets)
meta_path = {"old": f"down.{i}.block", "new": f"down_blocks.{i}.resnets"}
assign_to_checkpoint(
paths,
new_checkpoint,
vae_state_dict,
additional_replacements=[meta_path],
config=conf,
)
mid_resnets = [key for key in vae_state_dict if "encoder.mid.block" in key]
num_mid_res_blocks = 2
for i in range(1, num_mid_res_blocks + 1):
resnets = [key for key in mid_resnets if f"encoder.mid.block_{i}" in key]
paths = renew_vae_resnet_paths(resnets)
meta_path = {"old": f"mid.block_{i}", "new": f"mid_block.resnets.{i - 1}"}
assign_to_checkpoint(
paths,
new_checkpoint,
vae_state_dict,
additional_replacements=[meta_path],
config=conf,
)
mid_attentions = [key for key in vae_state_dict if "encoder.mid.attn" in key]
paths = renew_vae_attention_paths(mid_attentions)
meta_path = {"old": "mid.attn_1", "new": "mid_block.attentions.0"}
assign_to_checkpoint(
paths,
new_checkpoint,
vae_state_dict,
additional_replacements=[meta_path],
config=conf,
)
conv_attn_to_linear(new_checkpoint)
for i in range(num_up_blocks):
block_id = num_up_blocks - 1 - i
resnets = [
key
for key in up_blocks[block_id]
if f"up.{block_id}" in key and f"up.{block_id}.upsample" not in key
]
if f"decoder.up.{block_id}.upsample.conv.weight" in vae_state_dict:
new_checkpoint[
f"decoder.up_blocks.{i}.upsamplers.0.conv.weight"
] = vae_state_dict[f"decoder.up.{block_id}.upsample.conv.weight"]
new_checkpoint[
f"decoder.up_blocks.{i}.upsamplers.0.conv.bias"
] = vae_state_dict[f"decoder.up.{block_id}.upsample.conv.bias"]
paths = renew_vae_resnet_paths(resnets)
meta_path = {"old": f"up.{block_id}.block", "new": f"up_blocks.{i}.resnets"}
assign_to_checkpoint(
paths,
new_checkpoint,
vae_state_dict,
additional_replacements=[meta_path],
config=conf,
)
mid_resnets = [key for key in vae_state_dict if "decoder.mid.block" in key]
num_mid_res_blocks = 2
for i in range(1, num_mid_res_blocks + 1):
resnets = [key for key in mid_resnets if f"decoder.mid.block_{i}" in key]
paths = renew_vae_resnet_paths(resnets)
meta_path = {"old": f"mid.block_{i}", "new": f"mid_block.resnets.{i - 1}"}
assign_to_checkpoint(
paths,
new_checkpoint,
vae_state_dict,
additional_replacements=[meta_path],
config=conf,
)
mid_attentions = [key for key in vae_state_dict if "decoder.mid.attn" in key]
paths = renew_vae_attention_paths(mid_attentions)
meta_path = {"old": "mid.attn_1", "new": "mid_block.attentions.0"}
assign_to_checkpoint(
paths,
new_checkpoint,
vae_state_dict,
additional_replacements=[meta_path],
config=conf,
)
conv_attn_to_linear(new_checkpoint)
return new_checkpoint
The provided code snippet includes necessary dependencies for implementing the `convert_vaept_to_diffusers` function. Write a Python function `def convert_vaept_to_diffusers(path: str) -> AutoencoderKL` to solve the following problem:
Convert a .pt/.bin/.satetensors VAE file into a diffusers AutoencoderKL
Here is the function:
def convert_vaept_to_diffusers(path: str) -> AutoencoderKL:
"Convert a .pt/.bin/.satetensors VAE file into a diffusers AutoencoderKL"
r = requests.get(
"https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml",
timeout=10,
)
io_obj = io.BytesIO(r.content)
original_config = OmegaConf.load(io_obj)
image_size = 512
device = "cuda" if torch.cuda.is_available() else "cpu"
if path.endswith("safetensors"):
from safetensors import safe_open
checkpoint = {}
with safe_open(path, framework="pt", device="cpu") as f: # type: ignore # weird import structure, seems to be replaced at runtime in the lib
for key in f.keys():
checkpoint[key] = f.get_tensor(key)
else:
checkpoint = torch.load(path, map_location=device)["state_dict"]
# Convert the VAE model.
vae_config = create_vae_diffusers_config(original_config, image_size=image_size)
converted_vae_checkpoint = _custom_convert_ldm_vae_checkpoint(
checkpoint, vae_config
)
vae = AutoencoderKL(**vae_config)
vae.load_state_dict(converted_vae_checkpoint)
return vae | Convert a .pt/.bin/.satetensors VAE file into a diffusers AutoencoderKL |
156,383 | import io
import json
import logging
import os
from functools import partial
from importlib.util import find_spec
from pathlib import Path
from typing import Any, Dict, Optional, Tuple, Union
import requests
import torch
from diffusers.models.autoencoder_kl import AutoencoderKL
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
from diffusers.pipelines.stable_diffusion.convert_from_ckpt import (
assign_to_checkpoint,
conv_attn_to_linear,
create_vae_diffusers_config,
renew_vae_attention_paths,
renew_vae_resnet_paths,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import (
StableDiffusionPipeline,
)
from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl import (
StableDiffusionXLPipeline,
)
from diffusers.schedulers.scheduling_utils import SCHEDULER_CONFIG_NAME
from diffusers.utils.constants import (
CONFIG_NAME,
DIFFUSERS_CACHE,
HUGGINGFACE_CO_RESOLVE_ENDPOINT,
ONNX_WEIGHTS_NAME,
WEIGHTS_NAME,
)
from diffusers.utils.hub_utils import HF_HUB_OFFLINE
from huggingface_hub import model_info
from huggingface_hub._snapshot_download import snapshot_download
from huggingface_hub.file_download import hf_hub_download
from huggingface_hub.hf_api import ModelInfo
from huggingface_hub.utils._errors import (
EntryNotFoundError,
RepositoryNotFoundError,
RevisionNotFoundError,
)
from omegaconf import OmegaConf
from packaging import version
from requests import HTTPError
from transformers.models.clip.modeling_clip import BaseModelOutput
from core.config import config
from core.files import get_full_model_path
from core.flags import HighResFixFlag
from core.optimizations import compile_sfast
from core.types import Job
from core.utils import determine_model_type
class HighResFixFlag(Flag, DataClassJsonMixin):
"Flag to fix high resolution images"
enabled: bool = False # For storing in json
scale: float = 2
mode: Literal["latent", "image"] = "latent"
# Image Upscaling
image_upscaler: str = "RealESRGAN_x4plus_anime_6B"
# Latent Upscaling
latent_scale_mode: LatentScaleModel = "bislerp"
antialiased: bool = False
# Img2img
strength: float = 0.7
steps: int = 50
class Job:
"Base class for all jobs"
data: Any
model: str
websocket_id: Union[str, None] = field(default=None)
save_image: Literal[True, False, "r2"] = True
flags: Dict[str, Dict] = field(default_factory=dict)
def get_output_type(job: Job):
return (
"latent"
if (
"highres_fix" in job.flags
and HighResFixFlag(**job.flags["highres_fix"]).mode == "latent"
)
else "pil"
) | null |
156,384 | import logging
from typing import Any, Dict, Sized
import torch
from core.config import config
from .utils import HookObject
def _rebuild_weight(module, orig_weight: torch.Tensor, dyn_dim: int = None) -> torch.Tensor: # type: ignore
output_shape: Sized
if module.__class__.__name__ == "LycoUpDownModule":
up = module.up_module.weight.to(orig_weight.device, dtype=orig_weight.dtype)
down = module.down_module.weight.to(orig_weight.device, dtype=orig_weight.dtype)
output_shape = [up.size(0), down.size(1)]
if (mid := module.mid_module) is not None:
# cp-decomposition
mid = mid.weight.to(orig_weight.device, dtype=orig_weight.dtype)
updown = _rebuild_cp_decomposition(up, down, mid)
output_shape += mid.shape[2:]
else:
if len(down.shape) == 4:
output_shape += down.shape[2:]
updown = _rebuild_conventional(up, down, output_shape, dyn_dim)
elif module.__class__.__name__ == "LycoHadaModule":
w1a = module.w1a.to(orig_weight.device, dtype=orig_weight.dtype)
w1b = module.w1b.to(orig_weight.device, dtype=orig_weight.dtype)
w2a = module.w2a.to(orig_weight.device, dtype=orig_weight.dtype)
w2b = module.w2b.to(orig_weight.device, dtype=orig_weight.dtype)
output_shape = [w1a.size(0), w1b.size(1)]
if module.t1 is not None:
output_shape = [w1a.size(1), w1b.size(1)]
t1 = module.t1.to(orig_weight.device, dtype=orig_weight.dtype)
updown1 = make_weight_cp(t1, w1a, w1b)
output_shape += t1.shape[2:]
else:
if len(w1b.shape) == 4:
output_shape += w1b.shape[2:]
updown1 = _rebuild_conventional(w1a, w1b, output_shape)
if module.t2 is not None:
t2 = module.t2.to(orig_weight.device, dtype=orig_weight.dtype)
updown2 = make_weight_cp(t2, w2a, w2b)
else:
updown2 = _rebuild_conventional(w2a, w2b, output_shape)
updown = updown1 * updown2
elif module.__class__.__name__ == "FullModule":
output_shape = module.weight.shape
updown = module.weight.to(orig_weight.device, dtype=orig_weight.dtype)
elif module.__class__.__name__ == "IA3Module":
output_shape = [module.w.size(0), orig_weight.size(1)]
if module.on_input:
output_shape.reverse()
else:
module.w = module.w.reshape(-1, 1)
updown = orig_weight * module.w.to(orig_weight.device, dtype=orig_weight.dtype)
elif module.__class__.__name__ == "LycoKronModule":
if module.w1 is not None:
w1 = module.w1.to(orig_weight.device, dtype=orig_weight.dtype)
else:
w1a = module.w1a.to(orig_weight.device, dtype=orig_weight.dtype)
w1b = module.w1b.to(orig_weight.device, dtype=orig_weight.dtype)
w1 = w1a @ w1b
if module.w2 is not None:
w2 = module.w2.to(orig_weight.device, dtype=orig_weight.dtype)
elif module.t2 is None:
w2a = module.w2a.to(orig_weight.device, dtype=orig_weight.dtype)
w2b = module.w2b.to(orig_weight.device, dtype=orig_weight.dtype)
w2 = w2a @ w2b
else:
t2 = module.t2.to(orig_weight.device, dtype=orig_weight.dtype)
w2a = module.w2a.to(orig_weight.device, dtype=orig_weight.dtype)
w2b = module.w2b.to(orig_weight.device, dtype=orig_weight.dtype)
w2 = make_weight_cp(t2, w2a, w2b)
output_shape = [w1.size(0) * w2.size(0), w1.size(1) * w2.size(1)]
if len(orig_weight.shape) == 4:
output_shape = orig_weight.shape
updown = make_kron(output_shape, w1, w2)
else:
raise NotImplementedError(
f"Unknown module type: {module.__class__.__name__}\n"
"If the type is one of "
"'LycoUpDownModule', 'LycoHadaModule', 'FullModule', 'IA3Module', 'LycoKronModule'"
"You may have other lyco extension that conflict with locon extension."
)
if hasattr(module, "bias") and module.bias is not None:
updown = updown.reshape(module.bias.shape)
updown += module.bias.to(orig_weight.device, dtype=orig_weight.dtype)
updown = updown.reshape(output_shape)
if len(output_shape) == 4:
updown = updown.reshape(output_shape) # type: ignore
if orig_weight.size().numel() == updown.size().numel():
updown = updown.reshape(orig_weight.shape)
return updown
def _lyco_calc_updown(lyco, module, target, multiplier):
updown = _rebuild_weight(module, target, lyco.dyn_dim)
if lyco.dyn_dim and module.dim:
dim = min(lyco.dyn_dim, module.dim)
elif lyco.dyn_dim:
dim = lyco.dyn_dim
elif module.dim:
dim = module.dim
else:
dim = None
scale = (
module.scale
if module.scale is not None
else module.alpha / dim
if dim is not None and module.alpha is not None
else 1.0
)
updown = updown * multiplier * scale
return updown | null |
156,385 | from copy import deepcopy
from diffusers.loaders import (
TextualInversionLoaderMixin,
load_textual_inversion_state_dicts,
)
import torch
from transformers import PreTrainedTokenizer, PreTrainedModel
def maybe_convert_prompt(prompt: str, tokenizer: PreTrainedTokenizer) -> str:
tokens = tokenizer.tokenize(prompt)
unique_tokens = set(tokens)
for token in unique_tokens:
if token in tokenizer.added_tokens_encoder:
replacement = token
i = 1
while f"{token}_{i}" in tokenizer.added_tokens_encoder:
replacement += f" {token}_{i}"
i += 1
prompt = prompt.replace(token, replacement)
return prompt | null |
156,386 | from copy import deepcopy
from diffusers.loaders import (
TextualInversionLoaderMixin,
load_textual_inversion_state_dicts,
)
import torch
from transformers import PreTrainedTokenizer, PreTrainedModel
import torch
torch.nn.Linear.old_forward = torch.nn.Linear.forward
def unload(token: str, tokenizer: PreTrainedTokenizer, text_encoder: PreTrainedModel):
load_map = text_encoder.change_map if hasattr(text_encoder, "change_map") else []
input_embedding: torch.Tensor = text_encoder.get_input_embeddings().weight
device, dtype = text_encoder.device, text_encoder.dtype
if token in load_map:
token_id: int = tokenizer.convert_tokens_to_ids(token) # type: ignore
tokenizer.added_tokens_encoder.pop(token)
input_embedding.data = torch.cat(
(input_embedding.data[:token_id], input_embedding.data[token_id + 1 :])
)
text_encoder.resize_token_embeddings(len(tokenizer))
load_map.remove(token)
input_embedding.to(device, dtype)
setattr(text_encoder, "change_map", load_map) | null |
156,387 | from copy import deepcopy
from diffusers.loaders import (
TextualInversionLoaderMixin,
load_textual_inversion_state_dicts,
)
import torch
from transformers import PreTrainedTokenizer, PreTrainedModel
import torch
torch.nn.Linear.old_forward = torch.nn.Linear.forward
def unload_all(tokenizer: PreTrainedTokenizer, text_encoder: PreTrainedModel):
load_map = text_encoder.change_map if hasattr(text_encoder, "change_map") else []
input_embedding: torch.Tensor = text_encoder.get_input_embeddings().weight
device, dtype = text_encoder.device, text_encoder.dtype
for token in deepcopy(load_map):
token_id: int = tokenizer.convert_tokens_to_ids(token) # type: ignore
tokenizer.added_tokens_encoder.pop(token)
input_embedding.data = torch.cat(
(input_embedding.data[:token_id], input_embedding.data[token_id + 1 :])
)
text_encoder.resize_token_embeddings(len(tokenizer))
load_map.remove(token)
input_embedding.to(device, dtype)
setattr(text_encoder, "change_map", load_map) | null |
156,388 | from copy import deepcopy
from diffusers.loaders import (
TextualInversionLoaderMixin,
load_textual_inversion_state_dicts,
)
import torch
from transformers import PreTrainedTokenizer, PreTrainedModel
import torch
torch.nn.Linear.old_forward = torch.nn.Linear.forward
def load(
model: str,
token: str,
tokenizer: PreTrainedTokenizer,
text_encoder: PreTrainedModel,
):
state_dicts = load_textual_inversion_state_dicts(model)
token, embeddings = TextualInversionLoaderMixin._retrieve_tokens_and_embeddings(
[token], state_dicts, tokenizer # type: ignore
)
tokens, embeddings = TextualInversionLoaderMixin._retrieve_tokens_and_embeddings(
token, embeddings, tokenizer
)
device, dtype = text_encoder.device, text_encoder.dtype
load_map = text_encoder.change_map if hasattr(text_encoder, "change_map") else []
input_embedding: torch.Tensor = text_encoder.get_input_embeddings().weight
def load(token, embedding):
tokenizer.add_tokens(token)
token_id = tokenizer.convert_tokens_to_ids(token)
input_embedding.data[token_id] = embedding
text_encoder.resize_token_embeddings(len(tokenizer))
load_map.append(token)
for _token, embedding in zip(tokens, embeddings):
load(_token, embedding)
input_embedding.to(device, dtype)
setattr(text_encoder, "change_map", load_map) | null |
156,389 | from typing import Callable
import torch
from .sag_utils import sag_masking, pred_epsilon, pred_x0
def pred_x0(pipe, sample, model_output, timestep):
"""
Modified from diffusers.schedulers.scheduling_ddim.DDIMScheduler.step
Note: there are some schedulers that clip or do not return x_0 (PNDMScheduler, DDIMScheduler, etc.)
"""
alpha_prod_t = pipe.scheduler.alphas_cumprod[
timestep.to(pipe.scheduler.alphas_cumprod.device, dtype=torch.int64)
]
beta_prod_t = 1 - alpha_prod_t
if pipe.scheduler.config["prediction_type"] == "epsilon":
pred_original_sample = (
sample - beta_prod_t ** (0.5) * model_output
) / alpha_prod_t ** (0.5)
elif pipe.scheduler.config["prediction_type"] == "sample":
pred_original_sample = model_output
elif pipe.scheduler.config["prediction_type"] == "v_prediction":
pred_original_sample = (alpha_prod_t**0.5) * sample - (
beta_prod_t**0.5
) * model_output
# predict V
model_output = (alpha_prod_t**0.5) * model_output + (
beta_prod_t**0.5
) * sample
else:
raise ValueError(
f"prediction_type given as {pipe.scheduler.config['prediction_type']} must be one of `epsilon`, `sample`,"
" or `v_prediction`"
)
return pred_original_sample
def sag_masking(pipe, original_latents, attn_map, map_size, t, eps):
"sag_masking"
# Same masking process as in SAG paper: https://arxiv.org/pdf/2210.00939.pdf
_, hw1, hw2 = attn_map.shape
b, latent_channel, latent_h, latent_w = original_latents.shape
h = pipe.unet.config.attention_head_dim
if isinstance(h, list):
h = h[-1]
# Produce attention mask
attn_map = attn_map.reshape(b, h, hw1, hw2)
attn_mask = attn_map.mean(1, keepdim=False).sum(1, keepdim=False) > 1.0
attn_mask = (
attn_mask.reshape(b, map_size[0], map_size[1])
.unsqueeze(1)
.repeat(1, latent_channel, 1, 1)
.type(attn_map.dtype)
)
attn_mask = F.interpolate(attn_mask, (latent_h, latent_w))
# Blur according to the self-attention mask
degraded_latents = simple_gaussian_2d(original_latents, kernel_size=9, sigma=1.0) # type: ignore
degraded_latents = degraded_latents * attn_mask + original_latents * (1 - attn_mask)
# Noise it again to match the noise level
if isinstance(eps, torch.Tensor):
degraded_latents = pipe.scheduler.add_noise(
degraded_latents, noise=eps, timesteps=torch.tensor([t])
)
return degraded_latents
def pred_epsilon(pipe, sample, model_output, timestep):
"pred_epsilon"
alpha_prod_t = pipe.scheduler.alphas_cumprod[
timestep.to(pipe.scheduler.alphas_cumprod.device, dtype=torch.int64)
]
beta_prod_t = 1 - alpha_prod_t
if pipe.scheduler.config["prediction_type"] == "epsilon":
pred_eps = model_output
elif pipe.scheduler.config["prediction_type"] == "sample":
pred_eps = (sample - (alpha_prod_t**0.5) * model_output) / (
beta_prod_t**0.5
)
elif pipe.scheduler.config["prediction_type"] == "v_prediction":
pred_eps = (beta_prod_t**0.5) * sample + (alpha_prod_t**0.5) * model_output
else:
raise ValueError(
f"prediction_type given as {pipe.scheduler.config['prediction_type']} must be one of `epsilon`, `sample`,"
" or `v_prediction`"
)
return pred_eps
def calculate_sag(
pipe,
call: Callable,
store_processor,
latent: torch.Tensor,
noise: torch.Tensor,
timestep: torch.IntTensor,
map_size: tuple,
text_embeddings: torch.Tensor,
scale: float,
cfg: float,
dtype: torch.dtype,
**additional_kwargs,
) -> torch.Tensor:
pred: torch.Tensor = pred_x0(pipe, latent, noise, timestep)
if cfg > 1:
cond_attn, _ = store_processor.attention_probs.chunk(2)
text_embeddings, _ = text_embeddings.chunk(2)
else:
cond_attn = store_processor.attention_probs
eps = pred_epsilon(pipe, latent, noise, timestep)
degraded: torch.Tensor = sag_masking(pipe, pred, cond_attn, map_size, timestep, eps)
degraded_prep = call(
degraded.to(dtype=dtype),
timestep,
cond=text_embeddings,
**additional_kwargs,
)
return scale * (noise - degraded_prep) | null |
156,390 | from typing import Callable
import torch
from .sag_utils import sag_masking
def sag_masking(pipe, original_latents, attn_map, map_size, t, eps):
"sag_masking"
# Same masking process as in SAG paper: https://arxiv.org/pdf/2210.00939.pdf
_, hw1, hw2 = attn_map.shape
b, latent_channel, latent_h, latent_w = original_latents.shape
h = pipe.unet.config.attention_head_dim
if isinstance(h, list):
h = h[-1]
# Produce attention mask
attn_map = attn_map.reshape(b, h, hw1, hw2)
attn_mask = attn_map.mean(1, keepdim=False).sum(1, keepdim=False) > 1.0
attn_mask = (
attn_mask.reshape(b, map_size[0], map_size[1])
.unsqueeze(1)
.repeat(1, latent_channel, 1, 1)
.type(attn_map.dtype)
)
attn_mask = F.interpolate(attn_mask, (latent_h, latent_w))
# Blur according to the self-attention mask
degraded_latents = simple_gaussian_2d(original_latents, kernel_size=9, sigma=1.0) # type: ignore
degraded_latents = degraded_latents * attn_mask + original_latents * (1 - attn_mask)
# Noise it again to match the noise level
if isinstance(eps, torch.Tensor):
degraded_latents = pipe.scheduler.add_noise(
degraded_latents, noise=eps, timesteps=torch.tensor([t])
)
return degraded_latents
def calculate_sag(
pipe,
call: Callable,
store_processor,
latent: torch.Tensor,
noise: torch.Tensor,
timestep: torch.IntTensor,
map_size: tuple,
text_embeddings: torch.Tensor,
scale: float,
cfg: float,
dtype: torch.dtype,
**additional_kwargs,
) -> torch.Tensor:
pred: torch.Tensor = noise # noise is already pred_x0 with kdiff
if cfg > 1:
cond_attn, _ = store_processor.attention_probs.chunk(2)
text_embeddings, _ = text_embeddings.chunk(2)
else:
cond_attn = store_processor.attention_probs
degraded: torch.Tensor = sag_masking(pipe, pred, cond_attn, map_size, timestep, 0)
# messed up the order of these two, spent half an hour looking for problems.
# Epsilon
compensation = noise - degraded
degraded = degraded - (noise - latent)
degraded_pred = call(
degraded.to(dtype=dtype),
timestep,
cond=text_embeddings,
**additional_kwargs,
)
return (noise - (degraded_pred + compensation)) * scale | null |
156,391 | import os
from pathlib import Path
from typing import Any, Union
The provided code snippet includes necessary dependencies for implementing the `init_ait_module` function. Write a Python function `def init_ait_module( model_name: str, workdir: Union[str, Path], ) -> Any` to solve the following problem:
Initialize a new AITemplate Module object
Here is the function:
def init_ait_module(
model_name: str,
workdir: Union[str, Path],
) -> Any:
"Initialize a new AITemplate Module object"
from aitemplate.compiler import Model
mod = Model(os.path.join(workdir, model_name, "test.so"))
return mod | Initialize a new AITemplate Module object |
156,392 | import importlib
import inspect
import logging
from typing import Dict, Optional, Union
import torch
from diffusers.schedulers.scheduling_ddim import DDIMScheduler
from diffusers.schedulers.scheduling_utils import (
KarrasDiffusionSchedulers,
SchedulerMixin,
)
from core import shared
from core.config import config
from core.inference.utilities.philox import PhiloxGenerator
from core.scheduling import KdiffusionSchedulerAdapter, create_sampler
from core.scheduling.custom.sasolver import SASolverScheduler
from core.types import PyTorchModelType, SigmaScheduler
from core.utils import unwrap_enum
config = load_config()
The provided code snippet includes necessary dependencies for implementing the `get_timesteps` function. Write a Python function `def get_timesteps( scheduler: SchedulerMixin, num_inference_steps: int, strength: float, device: torch.device, is_text2img: bool, )` to solve the following problem:
Get the amount of timesteps for the provided options
Here is the function:
def get_timesteps(
scheduler: SchedulerMixin,
num_inference_steps: int,
strength: float,
device: torch.device,
is_text2img: bool,
):
"Get the amount of timesteps for the provided options"
shared.current_done_steps = 0
if is_text2img:
shared.current_steps = num_inference_steps
return scheduler.timesteps.to(device), num_inference_steps # type: ignore
else:
# get the original timestep using init_timestep
offset = scheduler.config.get("steps_offset", 0) # type: ignore
init_timestep = int(num_inference_steps * strength) + offset
init_timestep = min(init_timestep, num_inference_steps)
t_start = max(num_inference_steps - init_timestep + offset, 0)
timesteps = scheduler.timesteps[t_start:].to(device) # type: ignore
shared.current_steps = num_inference_steps - t_start
return timesteps, num_inference_steps - t_start | Get the amount of timesteps for the provided options |
156,393 | import importlib
import inspect
import logging
from typing import Dict, Optional, Union
import torch
from diffusers.schedulers.scheduling_ddim import DDIMScheduler
from diffusers.schedulers.scheduling_utils import (
KarrasDiffusionSchedulers,
SchedulerMixin,
)
from core import shared
from core.config import config
from core.inference.utilities.philox import PhiloxGenerator
from core.scheduling import KdiffusionSchedulerAdapter, create_sampler
from core.scheduling.custom.sasolver import SASolverScheduler
from core.types import PyTorchModelType, SigmaScheduler
from core.utils import unwrap_enum
config = load_config()
class PhiloxGenerator:
"""RNG that produces same outputs as torch.randn(..., device='cuda') on CPU"""
def __init__(self, seed):
self._seed = seed
self.offset = 0
def seed(self):
return self._seed
def randn(self, shape):
"""Generate a sequence of n standard normal random variables using the Philox 4x32 random number generator and the Box-Muller transform."""
n = 1
for x in shape:
n *= x
counter = np.zeros((4, n), dtype=np.uint32)
counter[0] = self.offset
counter[2] = np.arange(
n, dtype=np.uint32
) # up to 2^32 numbers can be generated - if you want more you'd need to spill into counter[3]
self.offset += 1
key = np.empty(n, dtype=np.uint64)
key.fill(self._seed)
key = uint32(key)
g = philox4_32(counter, key)
return box_muller(g[0], g[1]).reshape(shape) # discard g[2] and g[3]
The provided code snippet includes necessary dependencies for implementing the `prepare_extra_step_kwargs` function. Write a Python function `def prepare_extra_step_kwargs( scheduler: SchedulerMixin, eta: Optional[float], generator: Union[PhiloxGenerator, torch.Generator], )` to solve the following problem:
prepare extra kwargs for the scheduler step, since not all schedulers have the same signature eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 and should be between [0, 1]
Here is the function:
def prepare_extra_step_kwargs(
scheduler: SchedulerMixin,
eta: Optional[float],
generator: Union[PhiloxGenerator, torch.Generator],
):
"""prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
and should be between [0, 1]"""
if isinstance(scheduler, KdiffusionSchedulerAdapter):
return {}
accepts_eta = "eta" in set(
inspect.signature(scheduler.step).parameters.keys() # type: ignore
)
extra_step_kwargs = {}
if accepts_eta:
extra_step_kwargs["eta"] = eta
# check if the scheduler accepts generator
accepts_generator = (
"generator"
in set(inspect.signature(scheduler.step).parameters.keys()) # type: ignore
and config.api.generator != "philox"
)
if accepts_generator:
extra_step_kwargs["generator"] = generator
return extra_step_kwargs | prepare extra kwargs for the scheduler step, since not all schedulers have the same signature eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 and should be between [0, 1] |
156,394 | import importlib
import inspect
import logging
from typing import Dict, Optional, Union
import torch
from diffusers.schedulers.scheduling_ddim import DDIMScheduler
from diffusers.schedulers.scheduling_utils import (
KarrasDiffusionSchedulers,
SchedulerMixin,
)
from core import shared
from core.config import config
from core.inference.utilities.philox import PhiloxGenerator
from core.scheduling import KdiffusionSchedulerAdapter, create_sampler
from core.scheduling.custom.sasolver import SASolverScheduler
from core.types import PyTorchModelType, SigmaScheduler
from core.utils import unwrap_enum
logger = logging.getLogger(__name__)
config = load_config()
class SASolverScheduler(SchedulerMixin, ConfigMixin):
"""
`SASolverScheduler` is a fast dedicated high-order solver for diffusion SDEs.
This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
methods the library implements for all schedulers such as loading and saving.
Args:
num_train_timesteps (`int`, defaults to 1000):
The number of diffusion steps to train the model.
beta_start (`float`, defaults to 0.0001):
The starting `beta` value of inference.
beta_end (`float`, defaults to 0.02):
The final `beta` value.
beta_schedule (`str`, defaults to `"linear"`):
The beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from
`linear`, `scaled_linear`, or `squaredcos_cap_v2`.
trained_betas (`np.ndarray`, *optional*):
Pass an array of betas directly to the constructor to bypass `beta_start` and `beta_end`.
predictor_order (`int`, defaults to 2):
The predictor order which can be `1` or `2` or `3` or '4'. It is recommended to use `predictor_order=2` for guided
sampling, and `predictor_order=3` for unconditional sampling.
corrector_order (`int`, defaults to 2):
The corrector order which can be `1` or `2` or `3` or '4'. It is recommended to use `corrector_order=2` for guided
sampling, and `corrector_order=3` for unconditional sampling.
predictor_corrector_mode (`str`, defaults to `PEC`):
The predictor-corrector mode can be `PEC` or 'PECE'. It is recommended to use `PEC` mode for fast
sampling, and `PECE` for high-quality sampling (PECE needs around twice model evaluations as PEC).
prediction_type (`str`, defaults to `epsilon`, *optional*):
Prediction type of the scheduler function; can be `epsilon` (predicts the noise of the diffusion process),
`sample` (directly predicts the noisy sample`) or `v_prediction` (see section 2.4 of [Imagen
Video](https://imagen.research.google/video/paper.pdf) paper).
thresholding (`bool`, defaults to `False`):
Whether to use the "dynamic thresholding" method. This is unsuitable for latent-space diffusion models such
as Stable Diffusion.
dynamic_thresholding_ratio (`float`, defaults to 0.995):
The ratio for the dynamic thresholding method. Valid only when `thresholding=True`.
sample_max_value (`float`, defaults to 1.0):
The threshold value for dynamic thresholding. Valid only when `thresholding=True` and
`algorithm_type="dpmsolver++"`.
algorithm_type (`str`, defaults to `data_prediction`):
Algorithm type for the solver; can be `data_prediction` or `noise_prediction`. It is recommended to use `data_prediction`
with `solver_order=2` for guided sampling like in Stable Diffusion.
lower_order_final (`bool`, defaults to `True`):
Whether to use lower-order solvers in the final steps. Default = True.
use_karras_sigmas (`bool`, *optional*, defaults to `False`):
Whether to use Karras sigmas for step sizes in the noise schedule during the sampling process. If `True`,
the sigmas are determined according to a sequence of noise levels {σi}.
lambda_min_clipped (`float`, defaults to `-inf`):
Clipping threshold for the minimum value of `lambda(t)` for numerical stability. This is critical for the
cosine (`squaredcos_cap_v2`) noise schedule.
variance_type (`str`, *optional*):
Set to "learned" or "learned_range" for diffusion models that predict variance. If set, the model's output
contains the predicted Gaussian variance.
timestep_spacing (`str`, defaults to `"linspace"`):
The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and
Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.
steps_offset (`int`, defaults to 0):
An offset added to the inference steps. You can use a combination of `offset=1` and
`set_alpha_to_one=False` to make the last step use step 0 for the previous alpha product like in Stable
Diffusion.
"""
_compatibles = [e.name for e in KarrasDiffusionSchedulers]
order = 1
def __init__(
self,
num_train_timesteps: int = 1000,
beta_start: float = 0.0001,
beta_end: float = 0.02,
beta_schedule: str = "linear",
trained_betas: Optional[Union[np.ndarray, List[float]]] = None,
predictor_order: int = 2,
corrector_order: int = 2,
predictor_corrector_mode: str = "PEC",
prediction_type: str = "epsilon",
tau_func: Callable = lambda t: 1 if t >= 200 and t <= 800 else 0,
thresholding: bool = False,
dynamic_thresholding_ratio: float = 0.995,
sample_max_value: float = 1.0,
algorithm_type: str = "data_prediction",
lower_order_final: bool = True,
use_karras_sigmas: Optional[bool] = False,
lambda_min_clipped: float = -float("inf"),
variance_type: Optional[str] = None,
timestep_spacing: str = "linspace",
steps_offset: int = 0,
):
if trained_betas is not None:
self.betas = torch.tensor(trained_betas, dtype=torch.float32)
elif beta_schedule == "linear":
self.betas = torch.linspace(
beta_start, beta_end, num_train_timesteps, dtype=torch.float32
)
elif beta_schedule == "scaled_linear":
# this schedule is very specific to the latent diffusion model.
self.betas = (
torch.linspace(
beta_start**0.5,
beta_end**0.5,
num_train_timesteps,
dtype=torch.float32,
)
** 2
)
elif beta_schedule == "squaredcos_cap_v2":
# Glide cosine schedule
self.betas = betas_for_alpha_bar(num_train_timesteps)
else:
raise NotImplementedError(
f"{beta_schedule} does is not implemented for {self.__class__}"
)
self.alphas = 1.0 - self.betas
self.alphas_cumprod = torch.cumprod(self.alphas, dim=0)
# Currently we only support VP-type noise schedule
self.alpha_t = torch.sqrt(self.alphas_cumprod)
self.sigma_t = torch.sqrt(1 - self.alphas_cumprod)
self.lambda_t = torch.log(self.alpha_t) - torch.log(self.sigma_t)
# standard deviation of the initial noise distribution
self.init_noise_sigma = 1.0
if algorithm_type not in ["data_prediction", "noise_prediction"]:
raise NotImplementedError(
f"{algorithm_type} does is not implemented for {self.__class__}"
)
# setable values
self.num_inference_steps = None
timesteps = np.linspace(
0, num_train_timesteps - 1, num_train_timesteps, dtype=np.float32
)[::-1].copy()
self.timesteps = torch.from_numpy(timesteps)
self.timestep_list = [None] * max(predictor_order, corrector_order - 1)
self.model_outputs = [None] * max(predictor_order, corrector_order - 1)
self.tau_func = tau_func
self.predict_x0 = algorithm_type == "data_prediction"
self.lower_order_nums = 0
self.last_sample = None
def set_timesteps(
self, num_inference_steps: int = None, device: Union[str, torch.device] = None
):
"""
Sets the discrete timesteps used for the diffusion chain (to be run before inference).
Args:
num_inference_steps (`int`):
The number of diffusion steps used when generating samples with a pre-trained model.
device (`str` or `torch.device`, *optional*):
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
"""
# Clipping the minimum of all lambda(t) for numerical stability.
# This is critical for cosine (squaredcos_cap_v2) noise schedule.
clipped_idx = torch.searchsorted(
torch.flip(self.lambda_t, [0]), self.config.lambda_min_clipped
)
last_timestep = ((self.config.num_train_timesteps - clipped_idx).numpy()).item()
# "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
if self.config.timestep_spacing == "linspace":
timesteps = (
np.linspace(0, last_timestep - 1, num_inference_steps + 1)
.round()[::-1][:-1]
.copy()
.astype(np.int64)
)
elif self.config.timestep_spacing == "leading":
step_ratio = last_timestep // (num_inference_steps + 1)
# creates integer timesteps by multiplying by ratio
# casting to int to avoid issues when num_inference_step is power of 3
timesteps = (
(np.arange(0, num_inference_steps + 1) * step_ratio)
.round()[::-1][:-1]
.copy()
.astype(np.int64)
)
timesteps += self.config.steps_offset
elif self.config.timestep_spacing == "trailing":
step_ratio = self.config.num_train_timesteps / num_inference_steps
# creates integer timesteps by multiplying by ratio
# casting to int to avoid issues when num_inference_step is power of 3
timesteps = (
np.arange(last_timestep, 0, -step_ratio).round().copy().astype(np.int64)
)
timesteps -= 1
else:
raise ValueError(
f"{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'."
)
sigmas = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5)
if self.config.use_karras_sigmas:
log_sigmas = np.log(sigmas)
sigmas = self._convert_to_karras(
in_sigmas=sigmas, num_inference_steps=num_inference_steps
)
timesteps = np.array(
[self._sigma_to_t(sigma, log_sigmas) for sigma in sigmas]
).round()
timesteps = np.flip(timesteps).copy().astype(np.int64)
self.sigmas = torch.from_numpy(sigmas)
# when num_inference_steps == num_train_timesteps, we can end up with
# duplicates in timesteps.
_, unique_indices = np.unique(timesteps, return_index=True)
timesteps = timesteps[np.sort(unique_indices)]
self.timesteps = torch.from_numpy(timesteps).to(device)
self.num_inference_steps = len(timesteps)
self.model_outputs = [
None,
] * max(self.config.predictor_order, self.config.corrector_order - 1)
self.lower_order_nums = 0
self.last_sample = None
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler._threshold_sample
def _threshold_sample(self, sample: torch.FloatTensor) -> torch.FloatTensor:
"""
"Dynamic thresholding: At each sampling step we set s to a certain percentile absolute pixel value in xt0 (the
prediction of x_0 at timestep t), and if s > 1, then we threshold xt0 to the range [-s, s] and then divide by
s. Dynamic thresholding pushes saturated pixels (those near -1 and 1) inwards, thereby actively preventing
pixels from saturation at each step. We find that dynamic thresholding results in significantly better
photorealism as well as better image-text alignment, especially when using very large guidance weights."
https://arxiv.org/abs/2205.11487
"""
dtype = sample.dtype
batch_size, channels, height, width = sample.shape
if dtype not in (torch.float32, torch.float64):
sample = (
sample.float()
) # upcast for quantile calculation, and clamp not implemented for cpu half
# Flatten sample for doing quantile calculation along each image
sample = sample.reshape(batch_size, channels * height * width)
abs_sample = sample.abs() # "a certain percentile absolute pixel value"
s = torch.quantile(abs_sample, self.config.dynamic_thresholding_ratio, dim=1)
s = torch.clamp(
s, min=1, max=self.config.sample_max_value
) # When clamped to min=1, equivalent to standard clipping to [-1, 1]
s = s.unsqueeze(1) # (batch_size, 1) because clamp will broadcast along dim=0
sample = (
torch.clamp(sample, -s, s) / s
) # "we threshold xt0 to the range [-s, s] and then divide by s"
sample = sample.reshape(batch_size, channels, height, width)
sample = sample.to(dtype)
return sample
# Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._sigma_to_t
def _sigma_to_t(self, sigma, log_sigmas):
# get log sigma
log_sigma = np.log(sigma)
# get distribution
dists = log_sigma - log_sigmas[:, np.newaxis]
# get sigmas range
low_idx = (
np.cumsum((dists >= 0), axis=0)
.argmax(axis=0)
.clip(max=log_sigmas.shape[0] - 2)
)
high_idx = low_idx + 1
low = log_sigmas[low_idx]
high = log_sigmas[high_idx]
# interpolate sigmas
w = (low - log_sigma) / (low - high)
w = np.clip(w, 0, 1)
# transform interpolation to time range
t = (1 - w) * low_idx + w * high_idx
t = t.reshape(sigma.shape)
return t
# Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._convert_to_karras
def _convert_to_karras(
self, in_sigmas: torch.FloatTensor, num_inference_steps
) -> torch.FloatTensor:
"""Constructs the noise schedule of Karras et al. (2022)."""
sigma_min: float = in_sigmas[-1].item()
sigma_max: float = in_sigmas[0].item()
rho = 7.0 # 7.0 is the value used in the paper
ramp = np.linspace(0, 1, num_inference_steps)
min_inv_rho = sigma_min ** (1 / rho)
max_inv_rho = sigma_max ** (1 / rho)
sigmas = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
return sigmas
def convert_model_output(
self, model_output: torch.FloatTensor, timestep: int, sample: torch.FloatTensor
) -> torch.FloatTensor:
"""
Convert the model output to the corresponding type the DPMSolver/DPMSolver++ algorithm needs. DPM-Solver is
designed to discretize an integral of the noise prediction model, and DPM-Solver++ is designed to discretize an
integral of the data prediction model.
<Tip>
The algorithm and model type are decoupled. You can use either DPMSolver or DPMSolver++ for both noise
prediction and data prediction models.
</Tip>
Args:
model_output (`torch.FloatTensor`):
The direct output from the learned diffusion model.
timestep (`int`):
The current discrete timestep in the diffusion chain.
sample (`torch.FloatTensor`):
A current instance of a sample created by the diffusion process.
Returns:
`torch.FloatTensor`:
The converted model output.
"""
# SA-Solver_data_prediction needs to solve an integral of the data prediction model.
if self.config.algorithm_type in ["data_prediction"]:
if self.config.prediction_type == "epsilon":
# SA-Solver only needs the "mean" output.
if self.config.variance_type in ["learned", "learned_range"]:
model_output = model_output[:, :3]
alpha_t, sigma_t = self.alpha_t[timestep], self.sigma_t[timestep]
x0_pred = (sample - sigma_t * model_output) / alpha_t
elif self.config.prediction_type == "sample":
x0_pred = model_output
elif self.config.prediction_type == "v_prediction":
alpha_t, sigma_t = self.alpha_t[timestep], self.sigma_t[timestep]
x0_pred = alpha_t * sample - sigma_t * model_output
else:
raise ValueError(
f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or"
" `v_prediction` for the SASolverScheduler."
)
if self.config.thresholding:
x0_pred = self._threshold_sample(x0_pred)
return x0_pred
# SA-Solver_noise_prediction needs to solve an integral of the noise prediction model.
elif self.config.algorithm_type in ["noise_prediction"]:
if self.config.prediction_type == "epsilon":
# SA-Solver only needs the "mean" output.
if self.config.variance_type in ["learned", "learned_range"]:
epsilon = model_output[:, :3]
else:
epsilon = model_output
elif self.config.prediction_type == "sample":
alpha_t, sigma_t = self.alpha_t[timestep], self.sigma_t[timestep]
epsilon = (sample - alpha_t * model_output) / sigma_t
elif self.config.prediction_type == "v_prediction":
alpha_t, sigma_t = self.alpha_t[timestep], self.sigma_t[timestep]
epsilon = alpha_t * model_output + sigma_t * sample
else:
raise ValueError(
f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or"
" `v_prediction` for the SASolverScheduler."
)
if self.config.thresholding:
alpha_t, sigma_t = self.alpha_t[timestep], self.sigma_t[timestep]
x0_pred = (sample - sigma_t * epsilon) / alpha_t
x0_pred = self._threshold_sample(x0_pred)
epsilon = (sample - alpha_t * x0_pred) / sigma_t
return epsilon
def get_coefficients_exponential_negative(
self, order, interval_start, interval_end
):
"""
Calculate the integral of exp(-x) * x^order dx from interval_start to interval_end
"""
assert order in [0, 1, 2, 3], "order is only supported for 0, 1, 2 and 3"
if order == 0:
return torch.exp(-interval_end) * (
torch.exp(interval_end - interval_start) - 1
)
elif order == 1:
return torch.exp(-interval_end) * (
(interval_start + 1) * torch.exp(interval_end - interval_start)
- (interval_end + 1)
)
elif order == 2:
return torch.exp(-interval_end) * (
(interval_start**2 + 2 * interval_start + 2)
* torch.exp(interval_end - interval_start)
- (interval_end**2 + 2 * interval_end + 2)
)
elif order == 3:
return torch.exp(-interval_end) * (
(interval_start**3 + 3 * interval_start**2 + 6 * interval_start + 6)
* torch.exp(interval_end - interval_start)
- (interval_end**3 + 3 * interval_end**2 + 6 * interval_end + 6)
)
def get_coefficients_exponential_positive(
self, order, interval_start, interval_end, tau
):
"""
Calculate the integral of exp(x(1+tau^2)) * x^order dx from interval_start to interval_end
"""
assert order in [0, 1, 2, 3], "order is only supported for 0, 1, 2 and 3"
# after change of variable(cov)
interval_end_cov = (1 + tau**2) * interval_end
interval_start_cov = (1 + tau**2) * interval_start
if order == 0:
return (
torch.exp(interval_end_cov)
* (1 - torch.exp(-(interval_end_cov - interval_start_cov)))
/ ((1 + tau**2))
)
elif order == 1:
return (
torch.exp(interval_end_cov)
* (
(interval_end_cov - 1)
- (interval_start_cov - 1)
* torch.exp(-(interval_end_cov - interval_start_cov))
)
/ ((1 + tau**2) ** 2)
)
elif order == 2:
return (
torch.exp(interval_end_cov)
* (
(interval_end_cov**2 - 2 * interval_end_cov + 2)
- (interval_start_cov**2 - 2 * interval_start_cov + 2)
* torch.exp(-(interval_end_cov - interval_start_cov))
)
/ ((1 + tau**2) ** 3)
)
elif order == 3:
return (
torch.exp(interval_end_cov)
* (
(
interval_end_cov**3
- 3 * interval_end_cov**2
+ 6 * interval_end_cov
- 6
)
- (
interval_start_cov**3
- 3 * interval_start_cov**2
+ 6 * interval_start_cov
- 6
)
* torch.exp(-(interval_end_cov - interval_start_cov))
)
/ ((1 + tau**2) ** 4)
)
def lagrange_polynomial_coefficient(self, order, lambda_list):
"""
Calculate the coefficient of lagrange polynomial
"""
assert order in [0, 1, 2, 3]
assert order == len(lambda_list) - 1
if order == 0:
return [[1]]
elif order == 1:
return [
[
1 / (lambda_list[0] - lambda_list[1]),
-lambda_list[1] / (lambda_list[0] - lambda_list[1]),
],
[
1 / (lambda_list[1] - lambda_list[0]),
-lambda_list[0] / (lambda_list[1] - lambda_list[0]),
],
]
elif order == 2:
denominator1 = (lambda_list[0] - lambda_list[1]) * (
lambda_list[0] - lambda_list[2]
)
denominator2 = (lambda_list[1] - lambda_list[0]) * (
lambda_list[1] - lambda_list[2]
)
denominator3 = (lambda_list[2] - lambda_list[0]) * (
lambda_list[2] - lambda_list[1]
)
return [
[
1 / denominator1,
(-lambda_list[1] - lambda_list[2]) / denominator1,
lambda_list[1] * lambda_list[2] / denominator1,
],
[
1 / denominator2,
(-lambda_list[0] - lambda_list[2]) / denominator2,
lambda_list[0] * lambda_list[2] / denominator2,
],
[
1 / denominator3,
(-lambda_list[0] - lambda_list[1]) / denominator3,
lambda_list[0] * lambda_list[1] / denominator3,
],
]
elif order == 3:
denominator1 = (
(lambda_list[0] - lambda_list[1])
* (lambda_list[0] - lambda_list[2])
* (lambda_list[0] - lambda_list[3])
)
denominator2 = (
(lambda_list[1] - lambda_list[0])
* (lambda_list[1] - lambda_list[2])
* (lambda_list[1] - lambda_list[3])
)
denominator3 = (
(lambda_list[2] - lambda_list[0])
* (lambda_list[2] - lambda_list[1])
* (lambda_list[2] - lambda_list[3])
)
denominator4 = (
(lambda_list[3] - lambda_list[0])
* (lambda_list[3] - lambda_list[1])
* (lambda_list[3] - lambda_list[2])
)
return [
[
1 / denominator1,
(-lambda_list[1] - lambda_list[2] - lambda_list[3]) / denominator1,
(
lambda_list[1] * lambda_list[2]
+ lambda_list[1] * lambda_list[3]
+ lambda_list[2] * lambda_list[3]
)
/ denominator1,
(-lambda_list[1] * lambda_list[2] * lambda_list[3]) / denominator1,
],
[
1 / denominator2,
(-lambda_list[0] - lambda_list[2] - lambda_list[3]) / denominator2,
(
lambda_list[0] * lambda_list[2]
+ lambda_list[0] * lambda_list[3]
+ lambda_list[2] * lambda_list[3]
)
/ denominator2,
(-lambda_list[0] * lambda_list[2] * lambda_list[3]) / denominator2,
],
[
1 / denominator3,
(-lambda_list[0] - lambda_list[1] - lambda_list[3]) / denominator3,
(
lambda_list[0] * lambda_list[1]
+ lambda_list[0] * lambda_list[3]
+ lambda_list[1] * lambda_list[3]
)
/ denominator3,
(-lambda_list[0] * lambda_list[1] * lambda_list[3]) / denominator3,
],
[
1 / denominator4,
(-lambda_list[0] - lambda_list[1] - lambda_list[2]) / denominator4,
(
lambda_list[0] * lambda_list[1]
+ lambda_list[0] * lambda_list[2]
+ lambda_list[1] * lambda_list[2]
)
/ denominator4,
(-lambda_list[0] * lambda_list[1] * lambda_list[2]) / denominator4,
],
]
def get_coefficients_fn(
self, order, interval_start, interval_end, lambda_list, tau
):
assert order in [1, 2, 3, 4]
assert order == len(
lambda_list
), "the length of lambda list must be equal to the order"
coefficients = []
lagrange_coefficient = self.lagrange_polynomial_coefficient(
order - 1, lambda_list
)
for i in range(order):
coefficient = 0
for j in range(order):
if self.predict_x0:
coefficient += lagrange_coefficient[i][
j
] * self.get_coefficients_exponential_positive(
order - 1 - j, interval_start, interval_end, tau
)
else:
coefficient += lagrange_coefficient[i][
j
] * self.get_coefficients_exponential_negative(
order - 1 - j, interval_start, interval_end
)
coefficients.append(coefficient)
assert (
len(coefficients) == order
), "the length of coefficients does not match the order"
return coefficients
def stochastic_adams_bashforth_update(
self,
model_output: torch.FloatTensor,
prev_timestep: int,
sample: torch.FloatTensor,
noise: torch.FloatTensor,
order: int,
tau: torch.FloatTensor,
) -> torch.FloatTensor:
"""
One step for the SA-Predictor.
Args:
model_output (`torch.FloatTensor`):
The direct output from the learned diffusion model at the current timestep.
prev_timestep (`int`):
The previous discrete timestep in the diffusion chain.
sample (`torch.FloatTensor`):
A current instance of a sample created by the diffusion process.
order (`int`):
The order of SA-Predictor at this timestep.
Returns:
`torch.FloatTensor`:
The sample tensor at the previous timestep.
"""
assert noise is not None
timestep_list = self.timestep_list
model_output_list = self.model_outputs
s0, t = self.timestep_list[-1], prev_timestep
lambda_t, lambda_s0 = self.lambda_t[t], self.lambda_t[s0]
alpha_t, alpha_s0 = self.alpha_t[t], self.alpha_t[s0]
sigma_t, sigma_s0 = self.sigma_t[t], self.sigma_t[s0]
gradient_part = torch.zeros_like(sample)
h = lambda_t - lambda_s0
lambda_list = []
for i in range(order):
lambda_list.append(self.lambda_t[timestep_list[-(i + 1)]])
gradient_coefficients = self.get_coefficients_fn(
order, lambda_s0, lambda_t, lambda_list, tau
)
x = sample
if self.predict_x0:
if (
order == 2
): ## if order = 2 we do a modification that does not influence the convergence order similar to unipc. Note: This is used only for few steps sampling.
# The added term is O(h^3). Empirically we find it will slightly improve the image quality.
# ODE case
# gradient_coefficients[0] += 1.0 * torch.exp(lambda_t) * (h ** 2 / 2 - (h - 1 + torch.exp(-h))) / (ns.marginal_lambda(t_prev_list[-1]) - ns.marginal_lambda(t_prev_list[-2]))
# gradient_coefficients[1] -= 1.0 * torch.exp(lambda_t) * (h ** 2 / 2 - (h - 1 + torch.exp(-h))) / (ns.marginal_lambda(t_prev_list[-1]) - ns.marginal_lambda(t_prev_list[-2]))
gradient_coefficients[0] += (
1.0
* torch.exp((1 + tau**2) * lambda_t)
* (
h**2 / 2
- (h * (1 + tau**2) - 1 + torch.exp((1 + tau**2) * (-h)))
/ ((1 + tau**2) ** 2)
)
/ (
self.lambda_t[timestep_list[-1]]
- self.lambda_t[timestep_list[-2]]
)
)
gradient_coefficients[1] -= (
1.0
* torch.exp((1 + tau**2) * lambda_t)
* (
h**2 / 2
- (h * (1 + tau**2) - 1 + torch.exp((1 + tau**2) * (-h)))
/ ((1 + tau**2) ** 2)
)
/ (
self.lambda_t[timestep_list[-1]]
- self.lambda_t[timestep_list[-2]]
)
)
for i in range(order):
if self.predict_x0:
gradient_part += (
(1 + tau**2)
* sigma_t
* torch.exp(-(tau**2) * lambda_t)
* gradient_coefficients[i]
* model_output_list[-(i + 1)]
)
else:
gradient_part += (
-(1 + tau**2)
* alpha_t
* gradient_coefficients[i]
* model_output_list[-(i + 1)]
)
if self.predict_x0:
noise_part = sigma_t * torch.sqrt(1 - torch.exp(-2 * tau**2 * h)) * noise
else:
noise_part = tau * sigma_t * torch.sqrt(torch.exp(2 * h) - 1) * noise
if self.predict_x0:
x_t = (
torch.exp(-(tau**2) * h) * (sigma_t / sigma_s0) * x
+ gradient_part
+ noise_part
)
else:
x_t = (alpha_t / alpha_s0) * x + gradient_part + noise_part
x_t = x_t.to(x.dtype)
return x_t
def stochastic_adams_moulton_update(
self,
this_model_output: torch.FloatTensor,
this_timestep: int,
last_sample: torch.FloatTensor,
last_noise: torch.FloatTensor,
this_sample: torch.FloatTensor,
order: int,
tau: torch.FloatTensor,
) -> torch.FloatTensor:
"""
One step for the SA-Corrector.
Args:
this_model_output (`torch.FloatTensor`):
The model outputs at `x_t`.
this_timestep (`int`):
The current timestep `t`.
last_sample (`torch.FloatTensor`):
The generated sample before the last predictor `x_{t-1}`.
this_sample (`torch.FloatTensor`):
The generated sample after the last predictor `x_{t}`.
order (`int`):
The order of SA-Corrector at this step.
Returns:
`torch.FloatTensor`:
The corrected sample tensor at the current timestep.
"""
assert last_noise is not None
timestep_list = self.timestep_list
model_output_list = self.model_outputs
s0, t = self.timestep_list[-1], this_timestep
lambda_t, lambda_s0 = self.lambda_t[t], self.lambda_t[s0]
alpha_t, alpha_s0 = self.alpha_t[t], self.alpha_t[s0]
sigma_t, sigma_s0 = self.sigma_t[t], self.sigma_t[s0]
gradient_part = torch.zeros_like(this_sample)
h = lambda_t - lambda_s0
t_list = timestep_list + [this_timestep]
lambda_list = []
for i in range(order):
lambda_list.append(self.lambda_t[t_list[-(i + 1)]])
model_prev_list = model_output_list + [this_model_output]
gradient_coefficients = self.get_coefficients_fn(
order, lambda_s0, lambda_t, lambda_list, tau
)
x = last_sample
if self.predict_x0:
if (
order == 2
): ## if order = 2 we do a modification that does not influence the convergence order similar to UniPC. Note: This is used only for few steps sampling.
# The added term is O(h^3). Empirically we find it will slightly improve the image quality.
# ODE case
# gradient_coefficients[0] += 1.0 * torch.exp(lambda_t) * (h / 2 - (h - 1 + torch.exp(-h)) / h)
# gradient_coefficients[1] -= 1.0 * torch.exp(lambda_t) * (h / 2 - (h - 1 + torch.exp(-h)) / h)
gradient_coefficients[0] += (
1.0
* torch.exp((1 + tau**2) * lambda_t)
* (
h / 2
- (h * (1 + tau**2) - 1 + torch.exp((1 + tau**2) * (-h)))
/ ((1 + tau**2) ** 2 * h)
)
)
gradient_coefficients[1] -= (
1.0
* torch.exp((1 + tau**2) * lambda_t)
* (
h / 2
- (h * (1 + tau**2) - 1 + torch.exp((1 + tau**2) * (-h)))
/ ((1 + tau**2) ** 2 * h)
)
)
for i in range(order):
if self.predict_x0:
gradient_part += (
(1 + tau**2)
* sigma_t
* torch.exp(-(tau**2) * lambda_t)
* gradient_coefficients[i]
* model_prev_list[-(i + 1)]
)
else:
gradient_part += (
-(1 + tau**2)
* alpha_t
* gradient_coefficients[i]
* model_prev_list[-(i + 1)]
)
if self.predict_x0:
noise_part = (
sigma_t * torch.sqrt(1 - torch.exp(-2 * tau**2 * h)) * last_noise
)
else:
noise_part = tau * sigma_t * torch.sqrt(torch.exp(2 * h) - 1) * last_noise
if self.predict_x0:
x_t = (
torch.exp(-(tau**2) * h) * (sigma_t / sigma_s0) * x
+ gradient_part
+ noise_part
)
else:
x_t = (alpha_t / alpha_s0) * x + gradient_part + noise_part
x_t = x_t.to(x.dtype)
return x_t
def step(
self,
model_output: torch.FloatTensor,
timestep: int,
sample: torch.FloatTensor,
generator=None,
return_dict: bool = True,
) -> Union[SchedulerOutput, Tuple]:
"""
Predict the sample from the previous timestep by reversing the SDE. This function propagates the sample with
the SA-Solver.
Args:
model_output (`torch.FloatTensor`):
The direct output from learned diffusion model.
timestep (`int`):
The current discrete timestep in the diffusion chain.
sample (`torch.FloatTensor`):
A current instance of a sample created by the diffusion process.
generator (`torch.Generator`, *optional*):
A random number generator.
return_dict (`bool`):
Whether or not to return a [`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`.
Returns:
[`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`:
If return_dict is `True`, [`~schedulers.scheduling_utils.SchedulerOutput`] is returned, otherwise a
tuple is returned where the first element is the sample tensor.
"""
if self.num_inference_steps is None:
raise ValueError(
"Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
)
if isinstance(timestep, torch.Tensor):
timestep = timestep.to(self.timesteps.device)
step_index = (self.timesteps == timestep).nonzero()
if len(step_index) == 0:
step_index = len(self.timesteps) - 1
else:
step_index = step_index.item()
use_corrector = step_index > 0 and self.last_sample is not None
model_output_convert = self.convert_model_output(model_output, timestep, sample)
if use_corrector:
current_tau = self.tau_func(self.timestep_list[-1])
sample = self.stochastic_adams_moulton_update(
this_model_output=model_output_convert,
this_timestep=timestep,
last_sample=self.last_sample,
last_noise=self.last_noise,
this_sample=sample,
order=self.this_corrector_order,
tau=current_tau,
)
prev_timestep = (
0
if step_index == len(self.timesteps) - 1
else self.timesteps[step_index + 1]
)
for i in range(
max(self.config.predictor_order, self.config.corrector_order - 1) - 1
):
self.model_outputs[i] = self.model_outputs[i + 1]
self.timestep_list[i] = self.timestep_list[i + 1]
self.model_outputs[-1] = model_output_convert
self.timestep_list[-1] = timestep
noise = randn_tensor(
model_output.shape,
generator=generator,
device=model_output.device,
dtype=model_output.dtype,
)
if self.config.lower_order_final:
this_predictor_order = min(
self.config.predictor_order, len(self.timesteps) - step_index
)
this_corrector_order = min(
self.config.corrector_order, len(self.timesteps) - step_index + 1
)
else:
this_predictor_order = self.config.predictor_order
this_corrector_order = self.config.corrector_order
self.this_predictor_order = min(
this_predictor_order, self.lower_order_nums + 1
) # warmup for multistep
self.this_corrector_order = min(
this_corrector_order, self.lower_order_nums + 2
) # warmup for multistep
assert self.this_predictor_order > 0
assert self.this_corrector_order > 0
self.last_sample = sample
self.last_noise = noise
current_tau = self.tau_func(self.timestep_list[-1])
prev_sample = self.stochastic_adams_bashforth_update(
model_output=model_output_convert,
prev_timestep=prev_timestep,
sample=sample,
noise=noise,
order=self.this_predictor_order,
tau=current_tau,
)
if self.lower_order_nums < max(
self.config.predictor_order, self.config.corrector_order - 1
):
self.lower_order_nums += 1
if not return_dict:
return (prev_sample,)
return SchedulerOutput(prev_sample=prev_sample)
def scale_model_input(
self, sample: torch.FloatTensor, *args, **kwargs
) -> torch.FloatTensor:
"""
Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
current timestep.
Args:
sample (`torch.FloatTensor`):
The input sample.
Returns:
`torch.FloatTensor`:
A scaled input sample.
"""
return sample
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.add_noise
def add_noise(
self,
original_samples: torch.FloatTensor,
noise: torch.FloatTensor,
timesteps: torch.IntTensor,
) -> torch.FloatTensor:
# Make sure alphas_cumprod and timestep have same device and dtype as original_samples
alphas_cumprod = self.alphas_cumprod.to(
device=original_samples.device, dtype=original_samples.dtype
)
timesteps = timesteps.to(original_samples.device)
sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5
sqrt_alpha_prod = sqrt_alpha_prod.flatten()
while len(sqrt_alpha_prod.shape) < len(original_samples.shape):
sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1)
sqrt_one_minus_alpha_prod = (1 - alphas_cumprod[timesteps]) ** 0.5
sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten()
while len(sqrt_one_minus_alpha_prod.shape) < len(original_samples.shape):
sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)
noisy_samples = (
sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise
)
return noisy_samples
def __len__(self):
return self.config.num_train_timesteps
SigmaScheduler = Literal["automatic", "karras", "exponential", "polyexponential", "vp"]
PyTorchModelType = Union[
DiffusionPipeline,
StableDiffusionImg2ImgPipeline,
StableDiffusionInpaintPipeline,
StableDiffusionPipeline,
StableDiffusionControlNetPipeline,
]
def unwrap_enum(possible_enum: Union[Enum, Any]) -> Any:
"Unwrap an enum to its value"
if isinstance(possible_enum, Enum):
return possible_enum.value
return possible_enum
The provided code snippet includes necessary dependencies for implementing the `change_scheduler` function. Write a Python function `def change_scheduler( model: Optional[PyTorchModelType], scheduler: Union[str, KarrasDiffusionSchedulers], configuration: Optional[Dict] = None, sigma_type: SigmaScheduler = "automatic", sampler_settings: Optional[Dict] = None, ) -> SchedulerMixin` to solve the following problem:
Change the scheduler of the model
Here is the function:
def change_scheduler(
model: Optional[PyTorchModelType],
scheduler: Union[str, KarrasDiffusionSchedulers],
configuration: Optional[Dict] = None,
sigma_type: SigmaScheduler = "automatic",
sampler_settings: Optional[Dict] = None,
) -> SchedulerMixin:
"Change the scheduler of the model"
configuration = model.scheduler.config # type: ignore
if (isinstance(scheduler, str) and scheduler.isdigit()) or isinstance(
scheduler, (int, KarrasDiffusionSchedulers)
):
scheduler = KarrasDiffusionSchedulers(int(unwrap_enum(scheduler)))
try:
new_scheduler = getattr(
importlib.import_module("diffusers"), scheduler.name
)
except AttributeError:
new_scheduler = model.scheduler # type: ignore
if scheduler.value in [10, 11]:
logger.debug(
f"Loading scheduler {new_scheduler.__class__.__name__} with config sigmas={sigma_type}"
)
new_scheduler = new_scheduler.from_config(config=configuration, use_karras_sigmas=sigma_type == "") # type: ignore
else:
new_scheduler = new_scheduler.from_config(config=configuration) # type: ignore
else:
sched = DDIMScheduler.from_pretrained("runwayml/stable-diffusion-v1-5", subfolder="scheduler") # type: ignore
if scheduler == "sasolver":
new_scheduler = SASolverScheduler.from_config(config=configuration) # type: ignore
else:
new_scheduler = create_sampler(
alphas_cumprod=sched.alphas_cumprod, # type: ignore
denoiser_enable_quantization=config.api.kdiffusers_quantization,
sampler=scheduler,
sigma_type=sigma_type,
eta_noise_seed_delta=0,
sigma_always_discard_next_to_last=False,
sigma_use_old_karras_scheduler=False,
device=torch.device(config.api.device), # type: ignore
dtype=config.api.load_dtype, # type: ignore
sampler_settings=sampler_settings,
)
model.scheduler = new_scheduler # type: ignore
return new_scheduler # type: ignore | Change the scheduler of the model |
156,395 | from contextlib import ExitStack
from typing import Callable, Optional
import numpy as np
import torch
from PIL import Image
from core import shared
from core.config import config
from core.optimizations import autocast, ensure_correct_device
taesd_model = None
def decode_latents(
decode_lambda: Callable[[torch.Tensor], torch.Tensor],
latents: torch.Tensor,
height: int,
width: int,
scaling_factor: float = 0.18215,
) -> np.ndarray:
"Decode latents"
latents = 1 / scaling_factor * latents
image = decode_lambda(latents) # type: ignore
image = (image / 2 + 0.5).clamp(0, 1)
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
image = image.cpu().permute(0, 2, 3, 1).float().numpy()
img = image[:, :height, :width, :]
return img
config = load_config()
def taesd(
samples: torch.Tensor, height: Optional[int] = None, width: Optional[int] = None
) -> np.ndarray:
global taesd_model
if taesd_model is None:
from diffusers.models.autoencoder_tiny import AutoencoderTiny
model = "madebyollin/taesd"
if shared.current_model == "SDXL":
model = "madebyollin/taesdxl"
taesd_model = AutoencoderTiny.from_pretrained(
model, torch_dtype=torch.float16
).to( # type: ignore
config.api.device
)
return decode_latents(
lambda sample: taesd_model.decode(sample).sample, # type: ignore
samples.to(torch.float16),
height=height or samples[0].shape[1] * 8,
width=width or samples[0].shape[2] * 8,
) | null |
156,396 | from contextlib import ExitStack
from typing import Callable, Optional
import numpy as np
import torch
from PIL import Image
from core import shared
from core.config import config
from core.optimizations import autocast, ensure_correct_device
The provided code snippet includes necessary dependencies for implementing the `cheap_approximation` function. Write a Python function `def cheap_approximation(sample: torch.Tensor) -> Image.Image` to solve the following problem:
Convert a tensor of latents to RGB
Here is the function:
def cheap_approximation(sample: torch.Tensor) -> Image.Image:
"Convert a tensor of latents to RGB"
# Credit to Automatic111 stable-diffusion-webui
# https://discuss.huggingface.co/t/decoding-latents-to-rgb-without-upscaling/23204/2
coeffs = [
[0.298, 0.207, 0.208],
[0.187, 0.286, 0.173],
[-0.158, 0.189, 0.264],
[-0.184, -0.271, -0.473],
]
if shared.current_model == "SDXL":
coeffs = [
[0.3448, 0.4168, 0.4395],
[-0.1953, -0.0290, 0.0250],
[0.1074, 0.0886, -0.0163],
[-0.3730, -0.2499, -0.2088],
]
coeffs = torch.tensor(coeffs, dtype=torch.float32, device="cpu")
decoded_rgb = torch.einsum(
"lxy,lr -> rxy", sample.to(torch.float32).to("cpu"), coeffs
)
decoded_rgb = torch.clamp((decoded_rgb + 1.0) / 2.0, min=0.0, max=1.0)
decoded_rgb = 255.0 * np.moveaxis(decoded_rgb.cpu().numpy(), 0, 2)
decoded_rgb = decoded_rgb.astype(np.uint8)
return Image.fromarray(decoded_rgb) | Convert a tensor of latents to RGB |
156,397 | from contextlib import ExitStack
from typing import Callable, Optional
import numpy as np
import torch
from PIL import Image
from core import shared
from core.config import config
from core.optimizations import autocast, ensure_correct_device
def decode_latents(
decode_lambda: Callable[[torch.Tensor], torch.Tensor],
latents: torch.Tensor,
height: int,
width: int,
scaling_factor: float = 0.18215,
) -> np.ndarray:
"Decode latents"
latents = 1 / scaling_factor * latents
image = decode_lambda(latents) # type: ignore
image = (image / 2 + 0.5).clamp(0, 1)
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
image = image.cpu().permute(0, 2, 3, 1).float().numpy()
img = image[:, :height, :width, :]
return img
config = load_config()
def full_vae(
samples: torch.Tensor,
vae,
height: Optional[int] = None,
width: Optional[int] = None,
) -> np.ndarray:
ensure_correct_device(vae)
def decode(sample):
with ExitStack() as gs:
if vae.config["force_upcast"] or config.api.upcast_vae:
gs.enter_context(autocast(dtype=torch.float32))
return vae.decode(sample, return_dict=False)[0]
return decode_latents(
decode, # type: ignore
samples,
height or samples[0].shape[1] * 8,
width or samples[0].shape[2] * 8,
) | null |
156,398 | from contextlib import ExitStack
from typing import Callable, Optional
import numpy as np
import torch
from PIL import Image
from core import shared
from core.config import config
from core.optimizations import autocast, ensure_correct_device
The provided code snippet includes necessary dependencies for implementing the `numpy_to_pil` function. Write a Python function `def numpy_to_pil(images: np.ndarray)` to solve the following problem:
Convert a numpy image or a batch of images to a PIL image.
Here is the function:
def numpy_to_pil(images: np.ndarray):
"""
Convert a numpy image or a batch of images to a PIL image.
"""
if images.ndim == 3:
images = images[None, ...]
images = (images * 255).round().astype(np.uint8)
pil_images = [Image.fromarray(image) for image in images]
return pil_images | Convert a numpy image or a batch of images to a PIL image. |
156,399 | from typing import Tuple, Optional
from functools import partial
from diffusers import UNet2DConditionModel
from diffusers.models.unet_2d_blocks import CrossAttnUpBlock2D, UpBlock2D
import torch
from core.flags import DeepshrinkFlag
from .latents import scale_latents
def nf(
self,
hidden_states: torch.FloatTensor,
res_hidden_states_tuple: Tuple[torch.FloatTensor, ...],
*args,
**kwargs,
) -> torch.FloatTensor:
mode = "bilinear"
if hasattr(self, "kohya_scaler"):
mode = self.kohya_scaler
if mode == "bislerp":
mode = "bilinear"
out = list(res_hidden_states_tuple)
for i, o in enumerate(out):
if o.shape[2] != hidden_states.shape[2]:
out[i] = torch.nn.functional.interpolate(
o,
(
hidden_states.shape[2],
hidden_states.shape[3],
),
mode=mode,
)
res_hidden_states_tuple = tuple(out)
return self.nn_forward(
*args,
hidden_states=hidden_states,
res_hidden_states_tuple=res_hidden_states_tuple,
**kwargs,
) | null |
156,400 | from typing import Tuple, Optional
from functools import partial
from diffusers import UNet2DConditionModel
from diffusers.models.unet_2d_blocks import CrossAttnUpBlock2D, UpBlock2D
import torch
from core.flags import DeepshrinkFlag
from .latents import scale_latents
def _round(x, y):
return y * round(x / y) | null |
156,401 | from typing import Tuple, Optional
from functools import partial
from diffusers import UNet2DConditionModel
from diffusers.models.unet_2d_blocks import CrossAttnUpBlock2D, UpBlock2D
import torch
from core.flags import DeepshrinkFlag
from .latents import scale_latents
step_limit = 0
class DeepshrinkFlag(Flag, DataClassJsonMixin):
"Flag for deepshrink"
enabled: bool = False # For storing in json
depth_1: int = 3 # -1 to 12; steps of 1
stop_at_1: float = 0.15 # 0 to 0.5; steps of 0.01
depth_2: int = 4 # -1 to 12; steps of 1
stop_at_2: float = 0.30 # 0 to 0.5; steps of 0.01
scaler: LatentScaleModel = "bislerp"
base_scale: float = 0.5 # 0.05 to 1.0; steps of 0.05
early_out: bool = False
def scale_latents(
latents: Union[torch.Tensor, torch.FloatTensor],
scale: float = 2.0,
latent_scale_mode: LatentScaleModel = "bilinear",
antialiased: bool = False,
):
"Interpolate the latents to the desired scale."
s = time()
logger.debug(f"Scaling latents with shape {list(latents.shape)}, scale: {scale}")
# Scale and round to multiple of 32
width_truncated = int(latents.shape[2] * scale)
height_truncated = int(latents.shape[3] * scale)
# Scale the latents
if latent_scale_mode == "bislerp":
interpolated = bislerp(latents, height_truncated, width_truncated)
else:
interpolated = F.interpolate(
latents,
size=(
width_truncated,
height_truncated,
),
mode=latent_scale_mode,
antialias=antialiased,
)
interpolated.to(latents.device, dtype=latents.dtype)
logger.debug(f"Took {(time() - s):.2f}s to process latent upscale")
logger.debug(f"Interpolated latents from {latents.shape} to {interpolated.shape}")
return interpolated
def modify_unet(
unet: UNet2DConditionModel,
step: int,
total_steps: int,
flag: Optional[DeepshrinkFlag] = None,
) -> UNet2DConditionModel:
if flag is None:
return unet
global step_limit
s1, s2 = flag.stop_at_1, flag.stop_at_2
if s1 > s2:
s2 = s1
p1 = (s1, flag.depth_1 - 1)
p2 = (s2, flag.depth_2 - 1)
if step < step_limit:
return unet
for s, d in [p1, p2]:
out_d = d if flag.early_out else -(d + 1)
out_d = min(out_d, len(unet.up_blocks) - 1)
if step < total_steps * s:
if not hasattr(unet.down_blocks[d], "kohya_scale"):
for block, scale in [
(unet.down_blocks[d], flag.base_scale),
(unet.up_blocks[out_d], 1.0 / flag.base_scale),
]:
setattr(block, "kohya_scale", scale)
setattr(block, "kohya_scaler", flag.scaler)
setattr(block, "_orignal_forawrd", block.forward)
def new_forawrd(self, hidden_states, *args, **kwargs):
hidden_states = scale_latents(
hidden_states,
self.kohya_scale,
self.kohya_scaler,
False,
)
if "scale" in kwargs:
kwargs.pop("scale")
return self._orignal_forawrd(hidden_states, *args, **kwargs)
block.forward = partial(new_forawrd, block)
# In case someone wants to work on smooth scaling
# The double comments are there 'cause of attempts made before
# else:
# scale_ratio = step / (total_steps * s)
# downscale = min(
# (1 - flag.base_scale) * scale_ratio + flag.base_scale,
# )
# # upscale = _round(
# upscale = (1.0 / flag.base_scale) * (flag.base_scale / downscale) #, 0.25
# # )
# unet.down_blocks[d].kohya_scale = downscale # _round(downscale, 0.2) # type: ignore
# unet.up_blocks[out_d].kohya_scale = upscale # type: ignore
# print(
# unet.down_blocks[d].kohya_scale, unet.up_blocks[out_d].kohya_scale
# )
return unet
elif hasattr(unet.down_blocks[d], "kohya_scale") and (
p1[1] != p2[1] or s == p2[0]
):
unet.down_blocks[d].forward = unet.down_blocks[d]._orignal_forawrd
if hasattr(unet.up_blocks[out_d], "_orignal_forawrd"):
unet.up_blocks[out_d].forward = unet.up_blocks[out_d]._orignal_forawrd
step_limit = step
return unet | null |
156,402 | from typing import Tuple, Optional
from functools import partial
from diffusers import UNet2DConditionModel
from diffusers.models.unet_2d_blocks import CrossAttnUpBlock2D, UpBlock2D
import torch
from core.flags import DeepshrinkFlag
from .latents import scale_latents
step_limit = 0
def post_process(unet: UNet2DConditionModel) -> UNet2DConditionModel:
for i, b in enumerate(unet.down_blocks):
if hasattr(b, "kohya_scale"):
unet.down_blocks[i].forward = b._orignal_forawrd
for i, b in enumerate(unet.up_blocks):
if hasattr(b, "kohya_scale"):
unet.up_blocks[i].forward = b._orignal_forawrd
global step_limit
step_limit = 0
return unet | null |
156,403 | from typing import Optional, Union
import torch
from torch import Generator as native
from core.config import config
from .philox import PhiloxGenerator
config = load_config()
class PhiloxGenerator:
def __init__(self, seed):
def seed(self):
def randn(self, shape): # discard g[2] and g[3]
def create_generator(seed: int) -> Union[PhiloxGenerator, torch.Generator]:
generator = config.api.generator
if generator == "device" and config.api.overwrite_generator:
generator = "cpu"
if generator == "philox":
return PhiloxGenerator(seed)
return native(config.api.device if generator == "device" else "cpu").manual_seed(
seed
) | null |
156,404 | from typing import Optional, Union
import torch
from torch import Generator as native
from core.config import config
from .philox import PhiloxGenerator
def randn(
shape,
generator: Union[PhiloxGenerator, torch.Generator],
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
) -> torch.Tensor:
if isinstance(generator, PhiloxGenerator):
return torch.asarray(generator.randn(shape), device=device, dtype=dtype)
return torch.randn(
shape,
generator=generator,
dtype=dtype,
device="cpu" if config.api.overwrite_generator else generator.device,
).to(device)
class PhiloxGenerator:
"""RNG that produces same outputs as torch.randn(..., device='cuda') on CPU"""
def __init__(self, seed):
self._seed = seed
self.offset = 0
def seed(self):
return self._seed
def randn(self, shape):
"""Generate a sequence of n standard normal random variables using the Philox 4x32 random number generator and the Box-Muller transform."""
n = 1
for x in shape:
n *= x
counter = np.zeros((4, n), dtype=np.uint32)
counter[0] = self.offset
counter[2] = np.arange(
n, dtype=np.uint32
) # up to 2^32 numbers can be generated - if you want more you'd need to spill into counter[3]
self.offset += 1
key = np.empty(n, dtype=np.uint64)
key.fill(self._seed)
key = uint32(key)
g = philox4_32(counter, key)
return box_muller(g[0], g[1]).reshape(shape) # discard g[2] and g[3]
def randn_like(
x: torch.Tensor,
generator: Union[PhiloxGenerator, torch.Generator],
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
) -> torch.Tensor:
return randn(x.shape, generator, device, dtype) | null |
156,405 | from copy import deepcopy
from dataclasses import dataclass
from typing import Dict, List, Optional, Tuple
import os
import yaml
import math
from pathlib import Path
from diffusers.models.unet_2d_condition import UNet2DConditionModel
import torch
import scipy
class ScalecrafterSettings:
inflate_tau: float
ndcfg_tau: float
dilate_tau: float
progressive: bool
dilation_settings: Dict[str, float]
ndcfg_dilate_settings: Dict[str, float]
disperse_list: List[str]
disperse: Optional[torch.Tensor]
height: int = 0
width: int = 0
base: str = "sd15"
SCALECRAFTER_CONFIG = list(map(read_settings, os.listdir(SCALECRAFTER_DIR / "configs")))
The provided code snippet includes necessary dependencies for implementing the `find_config_closest_to` function. Write a Python function `def find_config_closest_to( base: str, height: int, width: int, disperse: bool = False ) -> ScalecrafterSettings` to solve the following problem:
Find ScaleCrafter config for specified SDxx version closest to provided resolution.
Here is the function:
def find_config_closest_to(
base: str, height: int, width: int, disperse: bool = False
) -> ScalecrafterSettings:
"""Find ScaleCrafter config for specified SDxx version closest to provided resolution."""
# Normalize base to the format in SCALECRAFTER_CONFIG
base = base.replace(".", "").lower()
if base == "sd1x":
base = "sd15"
elif base == "sd2x":
base = "sd21"
resolutions = [
x
for x in SCALECRAFTER_CONFIG
if x.base == base and ((x.disperse is not None) == disperse)
]
# If there are no resolutions for said base, use default one.
if len(resolutions) == 0:
resolutions = [SCALECRAFTER_CONFIG[0]]
# Map resolutions to a tuple of (name, resolution -> h*w)
resolutions = [
(x, abs((x.height * x.width * 64) - (height * width))) for x in resolutions
]
# Read the settings of the one with the lowest resolution.
return min(resolutions, key=lambda x: x[1])[0] | Find ScaleCrafter config for specified SDxx version closest to provided resolution. |
156,406 | from copy import deepcopy
from dataclasses import dataclass
from typing import Dict, List, Optional, Tuple
import os
import yaml
import math
from pathlib import Path
from diffusers.models.unet_2d_condition import UNet2DConditionModel
import torch
import scipy
class ScalecrafterSettings:
inflate_tau: float
ndcfg_tau: float
dilate_tau: float
progressive: bool
dilation_settings: Dict[str, float]
ndcfg_dilate_settings: Dict[str, float]
disperse_list: List[str]
disperse: Optional[torch.Tensor]
height: int = 0
width: int = 0
base: str = "sd15"
_unet_inflate, _unet_inflate_vanilla = None, None
def inflate_kernels(
unet: UNet2DConditionModel,
inflate_conv_list: list,
inflation_transform: torch.Tensor,
) -> UNet2DConditionModel:
def replace_module(module: torch.nn.Module, name: List[str], index: list, value):
if len(name) == 1 and len(index) == 0:
setattr(module, name[0], value)
return module
current_name, next_name = name[0], name[1:]
current_index, next_index = int(index[0]), index[1:]
replace = getattr(module, current_name)
replace[current_index] = replace_module(
replace[current_index], next_name, next_index, value
)
setattr(module, current_name, replace)
return module
inflation_transform.to(dtype=unet.dtype, device=unet.device)
for name, module in unet.named_modules():
if name in inflate_conv_list:
weight, bias = module.weight.detach(), module.bias.detach()
(i, o, *_), kernel_size = (
weight.shape,
int(math.sqrt(inflation_transform.shape[0])),
)
transformed_weight = torch.einsum(
"mn, ion -> iom",
inflation_transform.to(dtype=weight.dtype),
weight.view(i, o, -1),
)
conv = torch.nn.Conv2d(
o,
i,
(kernel_size, kernel_size),
stride=module.stride,
padding=module.padding,
device=weight.device,
dtype=weight.dtype,
)
conv.weight.detach().copy_(
transformed_weight.view(i, o, kernel_size, kernel_size)
)
conv.bias.detach().copy_(bias) # type: ignore
sub_names = name.split(".")
if name.startswith("mid_block"):
names, indexes = sub_names[1::2], sub_names[2::2]
unet.mid_block = replace_module(unet.mid_block, names, indexes, conv) # type: ignore
else:
names, indexes = sub_names[0::2], sub_names[1::2]
replace_module(unet, names, indexes, conv)
return unet
def scale_setup(unet: UNet2DConditionModel, settings: Optional[ScalecrafterSettings]):
global _unet_inflate, _unet_inflate_vanilla
if _unet_inflate_vanilla is not None:
del _unet_inflate_vanilla, _unet_inflate
if settings is None:
return
if settings.disperse is not None:
if len(settings.disperse_list) != 0:
_unet_inflate = deepcopy(unet)
_unet_inflate = inflate_kernels(
_unet_inflate, settings.disperse_list, settings.disperse
)
if settings.ndcfg_tau > 0:
_unet_inflate_vanilla = deepcopy(unet)
_unet_inflate_vanilla = inflate_kernels(
_unet_inflate_vanilla, settings.disperse_list, settings.disperse
) | null |
156,407 | from copy import deepcopy
from dataclasses import dataclass
from typing import Dict, List, Optional, Tuple
import os
import yaml
import math
from pathlib import Path
from diffusers.models.unet_2d_condition import UNet2DConditionModel
import torch
import scipy
class ScalecrafterSettings:
inflate_tau: float
ndcfg_tau: float
dilate_tau: float
progressive: bool
dilation_settings: Dict[str, float]
ndcfg_dilate_settings: Dict[str, float]
disperse_list: List[str]
disperse: Optional[torch.Tensor]
height: int = 0
width: int = 0
base: str = "sd15"
_unet_inflate, _unet_inflate_vanilla = None, None
_backup_forwards = dict()
class ReDilateConvProcessor:
"Conv2d with support for up-/downscaling latents"
def __init__(
self,
module: torch.nn.Conv2d,
pf_factor: float = 1.0,
mode: str = "bilinear",
activate: bool = True,
):
self.dilation = math.ceil(pf_factor)
self.factor = float(self.dilation / pf_factor)
self.module = module
self.mode = mode
self.activate = activate
def __call__(
self, input: torch.Tensor, scale: float, *args, **kwargs
) -> torch.Tensor:
if len(args) > 0:
print(len(args))
print("".join(map(str, map(type, args))))
if self.activate:
ori_dilation, ori_padding = self.module.dilation, self.module.padding
inflation_kernel_size = (self.module.weight.shape[-1] - 3) // 2
self.module.dilation, self.module.padding = self.dilation, ( # type: ignore
self.dilation * (1 + inflation_kernel_size),
self.dilation * (1 + inflation_kernel_size),
)
ori_size, new_size = (
(
int(input.shape[-2] / self.module.stride[0]),
int(input.shape[-1] / self.module.stride[1]),
),
(
round(input.shape[-2] * self.factor),
round(input.shape[-1] * self.factor),
),
)
input = torch.nn.functional.interpolate(
input, size=new_size, mode=self.mode
)
input = self.module._conv_forward(
input, self.module.weight, self.module.bias
)
self.module.dilation, self.module.padding = ori_dilation, ori_padding
result = torch.nn.functional.interpolate(
input, size=ori_size, mode=self.mode
)
return result
else:
return self.module._conv_forward(
input, self.module.weight, self.module.bias
)
def scale(
unet: UNet2DConditionModel,
settings: Optional[ScalecrafterSettings],
step: int,
total_steps: int,
) -> UNet2DConditionModel:
if settings is None:
return unet
global _backup_forwards, _unet_inflate, _unet_inflate_vanilla
tau = step / total_steps
inflate = settings.inflate_tau < tau and settings.disperse is not None
if inflate:
unet = _unet_inflate # type: ignore
for name, module in unet.named_modules():
if settings.dilation_settings is not None:
if name in settings.dilation_settings.keys():
_backup_forwards[name] = module.forward
dilate = settings.dilation_settings[name]
if settings.progressive:
dilate = max(
math.ceil(
dilate * ((settings.dilate_tau - tau) / settings.dilate_tau)
),
2,
)
if tau < settings.inflate_tau and name in settings.disperse_list:
dilate = dilate / 2
module.forward = ReDilateConvProcessor( # type: ignore
module, dilate, mode="bilinear", activate=tau < settings.dilate_tau # type: ignore
)
return unet | null |
156,408 | from copy import deepcopy
from dataclasses import dataclass
from typing import Dict, List, Optional, Tuple
import os
import yaml
import math
from pathlib import Path
from diffusers.models.unet_2d_condition import UNet2DConditionModel
import torch
import scipy
class ScalecrafterSettings:
inflate_tau: float
ndcfg_tau: float
dilate_tau: float
progressive: bool
dilation_settings: Dict[str, float]
ndcfg_dilate_settings: Dict[str, float]
disperse_list: List[str]
disperse: Optional[torch.Tensor]
height: int = 0
width: int = 0
base: str = "sd15"
_backup_forwards = dict()
class ReDilateConvProcessor:
"Conv2d with support for up-/downscaling latents"
def __init__(
self,
module: torch.nn.Conv2d,
pf_factor: float = 1.0,
mode: str = "bilinear",
activate: bool = True,
):
self.dilation = math.ceil(pf_factor)
self.factor = float(self.dilation / pf_factor)
self.module = module
self.mode = mode
self.activate = activate
def __call__(
self, input: torch.Tensor, scale: float, *args, **kwargs
) -> torch.Tensor:
if len(args) > 0:
print(len(args))
print("".join(map(str, map(type, args))))
if self.activate:
ori_dilation, ori_padding = self.module.dilation, self.module.padding
inflation_kernel_size = (self.module.weight.shape[-1] - 3) // 2
self.module.dilation, self.module.padding = self.dilation, ( # type: ignore
self.dilation * (1 + inflation_kernel_size),
self.dilation * (1 + inflation_kernel_size),
)
ori_size, new_size = (
(
int(input.shape[-2] / self.module.stride[0]),
int(input.shape[-1] / self.module.stride[1]),
),
(
round(input.shape[-2] * self.factor),
round(input.shape[-1] * self.factor),
),
)
input = torch.nn.functional.interpolate(
input, size=new_size, mode=self.mode
)
input = self.module._conv_forward(
input, self.module.weight, self.module.bias
)
self.module.dilation, self.module.padding = ori_dilation, ori_padding
result = torch.nn.functional.interpolate(
input, size=ori_size, mode=self.mode
)
return result
else:
return self.module._conv_forward(
input, self.module.weight, self.module.bias
)
def post_scale(
unet: UNet2DConditionModel,
settings: Optional[ScalecrafterSettings],
step: int,
total_steps: int,
call,
*args,
**kwargs,
) -> Tuple[UNet2DConditionModel, Optional[torch.Tensor]]:
if settings is None:
return unet, None
global _backup_forwards
for name, module in unet.named_modules():
if name in _backup_forwards.keys():
module.forward = _backup_forwards[name]
_backup_forwards.clear()
tau = step / total_steps
noise_pred_vanilla = None
if tau < settings.ndcfg_tau:
inflate = settings.inflate_tau < tau and settings.disperse is not None
if inflate:
unet = _unet_inflate_vanilla # type: ignore
for name, module in unet.named_modules():
if name in settings.ndcfg_dilate_settings.keys():
_backup_forwards[name] = module.forward
dilate = settings.ndcfg_dilate_settings[name]
if settings.progressive:
dilate = max(
math.ceil(
dilate * ((settings.ndcfg_tau - tau) / settings.ndcfg_tau)
),
2,
)
if tau < settings.inflate_tau and name in settings.disperse_list:
dilate = dilate / 2
module.forward = ReDilateConvProcessor( # type: ignore
module, dilate, mode="bilinear", activate=tau < settings.ndcfg_tau # type: ignore
)
noise_pred_vanilla = call(*args, **kwargs)
for name, module in unet.named_modules():
if name in _backup_forwards.keys():
module.forward = _backup_forwards[name]
_backup_forwards.clear()
return unet, noise_pred_vanilla | null |
156,409 | from copy import deepcopy
from dataclasses import dataclass
from typing import Dict, List, Optional, Tuple
import os
import yaml
import math
from pathlib import Path
from diffusers.models.unet_2d_condition import UNet2DConditionModel
import torch
import scipy
class ScalecrafterSettings:
SCALECRAFTER_DIR = Path("data/scalecrafter")
def read_settings(config_name: str):
file = SCALECRAFTER_DIR / "configs" / config_name
with open(file, "r") as f:
config = yaml.safe_load(f)
# 0. Default height and width to unet
base = config_name.split("_")[0].strip().lower().replace(".", "")
steps = config["num_inference_steps"]
height = config["latent_height"]
width = config["latent_width"]
inflate_tau = config["inflate_tau"] / steps
ndcfg_tau = config["ndcfg_tau"] / steps
dilate_tau = config["dilate_tau"] / steps
progressive = config["progressive"]
dilate_settings = dict()
if config["dilate_settings"] is not None:
with open(os.path.join(SCALECRAFTER_DIR, config["dilate_settings"])) as f:
for line in f.readlines():
name, dilate = line.strip().split(":")
dilate_settings[name] = float(dilate)
ndcfg_dilate_settings = dict()
if config["ndcfg_dilate_settings"] is not None:
with open(os.path.join(SCALECRAFTER_DIR, config["ndcfg_dilate_settings"])) as f:
for line in f.readlines():
name, dilate = line.strip().split(":")
ndcfg_dilate_settings[name] = float(dilate)
inflate_settings = list()
if config["disperse_settings"] is not None:
with open(os.path.join(SCALECRAFTER_DIR, config["disperse_settings"])) as f:
inflate_settings = list(map(lambda x: x.strip(), f.readlines()))
disperse = None
if config["disperse_transform"] is not None:
disperse = scipy.io.loadmat(
os.path.join(SCALECRAFTER_DIR, config["disperse_transform"])
)["R"]
disperse = torch.tensor(disperse, device="cpu")
return ScalecrafterSettings(
inflate_tau,
ndcfg_tau,
dilate_tau,
# --
progressive,
# --
dilate_settings,
ndcfg_dilate_settings,
inflate_settings,
# --
disperse=disperse,
height=height,
width=width,
base=base,
) | null |
156,410 | from typing import Optional
import torch
import k_diffusion
from .anisotropic import adaptive_anisotropic_filter, unsharp_mask
from core.config import config
cfg_x0, cfg_s, cfg_cin, eps_record = None, None, None, None
k_diffusion.external.DiscreteEpsDDPMDenoiser.forward = patched_ddpm_denoiser_forward
k_diffusion.external.DiscreteVDDPMDenoiser.forward = patched_vddpm_denoiser_forward
def patched_ddpm_denoiser_forward(self, input, sigma, **kwargs):
global cfg_x0, cfg_s, cfg_cin, eps_record
c_out, c_in = [
k_diffusion.utils.append_dims(x, input.ndim) for x in self.get_scalings(sigma)
]
cfg_x0, cfg_s, cfg_cin = input, c_out, c_in
eps = self.get_eps(input * c_in, self.sigma_to_t(sigma), **kwargs)
if not isinstance(eps, torch.Tensor):
return eps
else:
if eps.shape != input.shape:
eps = torch.nn.functional.interpolate(
eps, (input.shape[2], input.shape[3]), mode="bilinear"
)
return eps * c_out + input | null |
156,411 | from typing import Optional
import torch
import k_diffusion
from .anisotropic import adaptive_anisotropic_filter, unsharp_mask
from core.config import config
cfg_x0, cfg_s, cfg_cin, eps_record = None, None, None, None
k_diffusion.external.DiscreteEpsDDPMDenoiser.forward = patched_ddpm_denoiser_forward
k_diffusion.external.DiscreteVDDPMDenoiser.forward = patched_vddpm_denoiser_forward
def patched_vddpm_denoiser_forward(self, input, sigma, **kwargs):
global cfg_x0, cfg_s, cfg_cin
c_skip, c_out, c_in = [
k_diffusion.utils.append_dims(x, input.ndim) for x in self.get_scalings(sigma)
]
cfg_x0, cfg_s, cfg_cin = input, c_out, c_in
v = self.get_v(input * c_in, self.sigma_to_t(sigma), **kwargs)
if not isinstance(v, torch.Tensor):
return v
else:
if v.shape != input.shape:
v = torch.nn.functional.interpolate(
v, (input.shape[2], input.shape[3]), mode="bilinear"
)
return v * c_out + input * c_skip | null |
156,412 | from typing import Optional
import torch
import k_diffusion
from .anisotropic import adaptive_anisotropic_filter, unsharp_mask
from core.config import config
cfg_x0, cfg_s, cfg_cin, eps_record = None, None, None, None
def unsharp_mask(
input: torch.Tensor,
kernel_size: Union[Tuple[int, int], int],
sigma: Union[Tuple[float, float], torch.Tensor],
) -> torch.Tensor:
data_blur: torch.Tensor = gaussian_blur2d(input, kernel_size, sigma)
data_sharpened: torch.Tensor = input + (input - data_blur)
return data_sharpened
def adaptive_anisotropic_filter(x, g=None):
if g is None:
g = x
s, m = torch.std_mean(g, dim=(1, 2, 3), keepdim=True)
s = s + 1e-5
guidance = (g - m) / s
y = _bilateral_blur(
x,
guidance,
kernel_size=(13, 13),
sigma_color=3.0,
sigma_space=3.0, # type: ignore
border_type="reflect",
color_distance_type="l1",
)
return y
config = load_config()
def calculate_cfg(
i: int,
cond: torch.Tensor,
uncond: torch.Tensor,
cfg: float,
timestep: torch.IntTensor,
additional_pred: Optional[torch.Tensor],
):
if config.api.apply_unsharp_mask:
cc = uncond + cfg * (cond - uncond)
MIX_FACTOR = 0.003
cond_scale_factor = min(0.02 * cfg, 0.65)
usm_sigma = torch.clamp(1 + timestep * cond_scale_factor, min=1e-6)
sharpened = unsharp_mask(cond, (3, 3), (usm_sigma, usm_sigma)) # type: ignore
return cc + (sharpened - cc) * MIX_FACTOR
if config.api.cfg_rescale_threshold == "off":
if additional_pred is not None:
additional_pred, _ = additional_pred.chunk(2)
uncond = additional_pred
return uncond + cfg * (cond - uncond)
if config.api.cfg_rescale_threshold <= cfg:
global cfg_x0, cfg_s
if cfg_x0.shape[0] == 2: # type: ignore
cfg_x0, _ = cfg_x0.chunk(2) # type: ignore
positive_x0 = cond * cfg_s + cfg_x0
t = 1.0 - (timestep / 999.0)[:, None, None, None].clone()
# Magic number: 2.0 is "sharpness"
alpha = 0.001 * 2.0 * t
positive_eps_degraded = adaptive_anisotropic_filter(x=cond, g=positive_x0)
cond = positive_eps_degraded * alpha + cond * (1.0 - alpha)
reps = (uncond + cfg * (cond - uncond)) * t
# Magic number: 0.7 is "base cfg"
mimicked = (uncond + 0.7 * (cond - uncond)) * (1 - t)
return reps + mimicked
if additional_pred is not None:
additional_pred, _ = additional_pred.chunk(2)
uncond = additional_pred
return uncond + cfg * (cond - uncond) | null |
156,413 | import logging
import math
from time import time
from typing import List, Optional, Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
from diffusers.models import vae as diffusers_vae
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import (
StableDiffusionPipeline,
)
from diffusers.utils.pil_utils import PIL_INTERPOLATION
from PIL import Image
from core.config import config
from core.flags import LatentScaleModel
from core.inference.utilities.philox import PhiloxGenerator
from .random import randn
class PhiloxGenerator:
"""RNG that produces same outputs as torch.randn(..., device='cuda') on CPU"""
def __init__(self, seed):
self._seed = seed
self.offset = 0
def seed(self):
return self._seed
def randn(self, shape):
"""Generate a sequence of n standard normal random variables using the Philox 4x32 random number generator and the Box-Muller transform."""
n = 1
for x in shape:
n *= x
counter = np.zeros((4, n), dtype=np.uint32)
counter[0] = self.offset
counter[2] = np.arange(
n, dtype=np.uint32
) # up to 2^32 numbers can be generated - if you want more you'd need to spill into counter[3]
self.offset += 1
key = np.empty(n, dtype=np.uint64)
key.fill(self._seed)
key = uint32(key)
g = philox4_32(counter, key)
return box_muller(g[0], g[1]).reshape(shape) # discard g[2] and g[3]
def randn(
shape,
generator: Union[PhiloxGenerator, torch.Generator],
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
) -> torch.Tensor:
if isinstance(generator, PhiloxGenerator):
return torch.asarray(generator.randn(shape), device=device, dtype=dtype)
return torch.randn(
shape,
generator=generator,
dtype=dtype,
device="cpu" if config.api.overwrite_generator else generator.device,
).to(device)
def _randn_tensor(
shape: Union[Tuple, List],
generator: Union[PhiloxGenerator, torch.Generator],
device: Optional["torch.device"] = None,
dtype: Optional["torch.dtype"] = None,
layout: Optional["torch.layout"] = None,
):
return randn(shape, generator, device, dtype) | null |
156,414 | import logging
import math
from time import time
from typing import List, Optional, Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
from diffusers.models import vae as diffusers_vae
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import (
StableDiffusionPipeline,
)
from diffusers.utils.pil_utils import PIL_INTERPOLATION
from PIL import Image
from core.config import config
from core.flags import LatentScaleModel
from core.inference.utilities.philox import PhiloxGenerator
from .random import randn
def pad_tensor(
tensor: torch.Tensor, multiple: int, size: Optional[Tuple[int, int]] = None
) -> torch.Tensor:
"Pad a tensors (NCHW) H and W dimension to the ceil(x / multiple)"
batch_size, channels, height, width = tensor.shape
new_height = math.ceil(height / multiple) * multiple
new_width = math.ceil(width / multiple) * multiple
hw = size or (new_height, new_width)
if size or (new_width != width or new_height != height):
nt = torch.zeros(
batch_size,
channels,
hw[0],
hw[1],
dtype=tensor.dtype,
device=tensor.device,
)
nt[:, :, :height, :width] = tensor
return nt
else:
return tensor
The provided code snippet includes necessary dependencies for implementing the `prepare_mask_and_masked_image` function. Write a Python function `def prepare_mask_and_masked_image( image, mask, height: int, width: int, return_image: bool = True ) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]` to solve the following problem:
The function resizes and converts input image and mask to PyTorch tensors, applies thresholding to mask tensor, obtains masked image tensor by multiplying image and mask tensors, and returns the resulting mask tensor, masked image tensor, and optionally the original image tensor.
Here is the function:
def prepare_mask_and_masked_image(
image, mask, height: int, width: int, return_image: bool = True
) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:
"""The function resizes and converts input image and mask to PyTorch tensors,
applies thresholding to mask tensor, obtains masked image tensor by multiplying image and mask tensors,
and returns the resulting mask tensor, masked image tensor, and optionally the original image tensor.
"""
if isinstance(image, torch.Tensor):
if not isinstance(mask, torch.Tensor):
mask = [mask]
mask = [i.resize((width, height), resample=Image.LANCZOS) for i in mask]
mask = np.concatenate(
[np.array(i.convert("L"))[None, None, :] for i in mask], axis=0
)
mask = torch.from_numpy(mask).to(device=image.device, dtype=image.dtype)
mask = pad_tensor(mask, 8)
if image.ndim == 3:
image = image.unsqueeze(0)
if mask.ndim == 2:
mask = mask.unsqueeze(0).unsqueeze(0)
if mask.ndim == 3:
if mask.shape[0] == 1:
mask = mask.unsqueeze(0)
else:
mask = mask.unsqueeze(1)
mask[mask < 0.5] = 0
mask[mask >= 0.5] = 1
# Image as float32
image = image.to(dtype=torch.float32)
image = pad_tensor(image, 8)
else:
image = [image]
mask = [mask]
image = [i.resize((width, height), resample=Image.LANCZOS) for i in image]
mask = [i.resize((width, height), resample=Image.LANCZOS) for i in mask]
image = [np.array(i.convert("RGB"))[None, :] for i in image]
mask = np.concatenate(
[np.array(i.convert("L"))[None, None, :] for i in mask], axis=0
)
image = np.concatenate(image, axis=0)
mask = mask.astype(np.float32) / 255.0
image = image.transpose(0, 3, 1, 2)
image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0
image = pad_tensor(image, 8)
mask[mask < 0.5] = 0
mask[mask >= 0.5] = 1
mask = torch.from_numpy(mask)
mask = pad_tensor(mask, 8)
masked_image = image * (mask < 0.5)
if return_image:
return mask, masked_image, image
return mask, masked_image, None | The function resizes and converts input image and mask to PyTorch tensors, applies thresholding to mask tensor, obtains masked image tensor by multiplying image and mask tensors, and returns the resulting mask tensor, masked image tensor, and optionally the original image tensor. |
156,415 | import logging
import math
from time import time
from typing import List, Optional, Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
from diffusers.models import vae as diffusers_vae
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import (
StableDiffusionPipeline,
)
from diffusers.utils.pil_utils import PIL_INTERPOLATION
from PIL import Image
from core.config import config
from core.flags import LatentScaleModel
from core.inference.utilities.philox import PhiloxGenerator
from .random import randn
class PhiloxGenerator:
"""RNG that produces same outputs as torch.randn(..., device='cuda') on CPU"""
def __init__(self, seed):
self._seed = seed
self.offset = 0
def seed(self):
return self._seed
def randn(self, shape):
"""Generate a sequence of n standard normal random variables using the Philox 4x32 random number generator and the Box-Muller transform."""
n = 1
for x in shape:
n *= x
counter = np.zeros((4, n), dtype=np.uint32)
counter[0] = self.offset
counter[2] = np.arange(
n, dtype=np.uint32
) # up to 2^32 numbers can be generated - if you want more you'd need to spill into counter[3]
self.offset += 1
key = np.empty(n, dtype=np.uint64)
key.fill(self._seed)
key = uint32(key)
g = philox4_32(counter, key)
return box_muller(g[0], g[1]).reshape(shape) # discard g[2] and g[3]
The provided code snippet includes necessary dependencies for implementing the `prepare_mask_latents` function. Write a Python function `def prepare_mask_latents( mask, masked_image, batch_size: int, height: int, width: int, dtype: torch.dtype, device: torch.device, do_classifier_free_guidance: bool, vae, vae_scale_factor: float, vae_scaling_factor: float, generator: Union[PhiloxGenerator, torch.Generator], ) -> Tuple[torch.Tensor, torch.Tensor]` to solve the following problem:
This function resizes and converts the input mask to a PyTorch tensor, encodes the input masked image to its latent representation, repeats the mask and masked image latents to match the batch size, concatenates the mask tensor if classifier-free guidance is enabled, and returns the resulting mask tensor and masked image latents.
Here is the function:
def prepare_mask_latents(
mask,
masked_image,
batch_size: int,
height: int,
width: int,
dtype: torch.dtype,
device: torch.device,
do_classifier_free_guidance: bool,
vae,
vae_scale_factor: float,
vae_scaling_factor: float,
generator: Union[PhiloxGenerator, torch.Generator],
) -> Tuple[torch.Tensor, torch.Tensor]:
"""This function resizes and converts the input mask to a PyTorch tensor,
encodes the input masked image to its latent representation,
repeats the mask and masked image latents to match the batch size,
concatenates the mask tensor if classifier-free guidance is enabled,
and returns the resulting mask tensor and masked image latents."""
mask = torch.nn.functional.interpolate(
mask, size=(height // vae_scale_factor, width // vae_scale_factor)
)
mask = mask.to(device=device, dtype=dtype)
masked_image = masked_image.to(device=device, dtype=vae.dtype)
masked_image_latents = vae_scaling_factor * vae.encode(
masked_image
).latent_dist.sample(generator=generator)
if mask.shape[0] < batch_size:
mask = mask.repeat(batch_size // mask.shape[0], 1, 1, 1)
if masked_image_latents.shape[0] < batch_size:
masked_image_latents = masked_image_latents.repeat(
batch_size // masked_image_latents.shape[0], 1, 1, 1
)
mask = torch.cat([mask] * 2) if do_classifier_free_guidance else mask
masked_image_latents = (
torch.cat([masked_image_latents] * 2)
if do_classifier_free_guidance
else masked_image_latents
)
masked_image_latents = masked_image_latents.to(device=device, dtype=dtype)
return mask, masked_image_latents | This function resizes and converts the input mask to a PyTorch tensor, encodes the input masked image to its latent representation, repeats the mask and masked image latents to match the batch size, concatenates the mask tensor if classifier-free guidance is enabled, and returns the resulting mask tensor and masked image latents. |
156,416 | import logging
import math
from time import time
from typing import List, Optional, Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
from diffusers.models import vae as diffusers_vae
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import (
StableDiffusionPipeline,
)
from diffusers.utils.pil_utils import PIL_INTERPOLATION
from PIL import Image
from core.config import config
from core.flags import LatentScaleModel
from core.inference.utilities.philox import PhiloxGenerator
from .random import randn
def preprocess_image(image):
# w, h = image.size
# w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32
# image = image.resize((w, h), resample=Image.LANCZOS)
image = np.array(image).astype(np.float32) / 255.0
image = image[None].transpose(0, 3, 1, 2)
image = torch.from_numpy(image)
return 2.0 * image - 1.0 | null |
156,417 | import logging
import math
from time import time
from typing import List, Optional, Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
from diffusers.models import vae as diffusers_vae
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import (
StableDiffusionPipeline,
)
from diffusers.utils.pil_utils import PIL_INTERPOLATION
from PIL import Image
from core.config import config
from core.flags import LatentScaleModel
from core.inference.utilities.philox import PhiloxGenerator
from .random import randn
The provided code snippet includes necessary dependencies for implementing the `prepare_image` function. Write a Python function `def prepare_image( image, width, height, batch_size, num_images_per_prompt, device, dtype )` to solve the following problem:
Prepare an image for controlnet 'consumption.
Here is the function:
def prepare_image(
image, width, height, batch_size, num_images_per_prompt, device, dtype
):
"Prepare an image for controlnet 'consumption.'"
if not isinstance(image, torch.Tensor):
if isinstance(image, Image.Image):
image = [image]
if isinstance(image[0], Image.Image):
image = [
np.array(
i.resize((width, height), resample=PIL_INTERPOLATION["lanczos"])
)[None, :]
for i in image
]
image = np.concatenate(image, axis=0)
image = np.array(image).astype(np.float32) / 255.0
image = image.transpose(0, 3, 1, 2)
image = torch.from_numpy(image)
elif isinstance(image[0], torch.Tensor):
image = torch.cat(image, dim=0) # type: ignore
image_batch_size = image.shape[0] # type: ignore
if image_batch_size == 1:
repeat_by = batch_size
else:
# image batch size is the same as prompt batch size
repeat_by = num_images_per_prompt
image = image.repeat_interleave(repeat_by, dim=0) # type: ignore
image = image.to(device=device, dtype=dtype)
return image | Prepare an image for controlnet 'consumption. |
156,418 | import logging
import math
from time import time
from typing import List, Optional, Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
from diffusers.models import vae as diffusers_vae
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import (
StableDiffusionPipeline,
)
from diffusers.utils.pil_utils import PIL_INTERPOLATION
from PIL import Image
from core.config import config
from core.flags import LatentScaleModel
from core.inference.utilities.philox import PhiloxGenerator
from .random import randn
def preprocess_adapter_image(image, height, width):
if isinstance(image, torch.Tensor):
return image
elif isinstance(image, Image.Image):
image = [image]
if isinstance(image[0], Image.Image):
image = [
np.array(i.resize((width, height), resample=PIL_INTERPOLATION["lanczos"]))
for i in image
]
image = [
i[None, ..., None] if i.ndim == 2 else i[None, ...] for i in image
] # expand [h, w] or [h, w, c] to [b, h, w, c]
image = np.concatenate(image, axis=0)
image = np.array(image).astype(np.float32) / 255.0
image = image.transpose(0, 3, 1, 2)
image = torch.from_numpy(image)
elif isinstance(image[0], torch.Tensor):
if image[0].ndim == 3: # type: ignore
image = torch.stack(image, dim=0) # type: ignore
elif image[0].ndim == 4: # type: ignore
image = torch.cat(image, dim=0) # type: ignore
else:
raise ValueError(
f"Invalid image tensor! Expecting image tensor with 3 or 4 dimension, but recive: {image[0].ndim}" # type: ignore
)
return image | null |
156,419 | import logging
import math
from time import time
from typing import List, Optional, Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
from diffusers.models import vae as diffusers_vae
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import (
StableDiffusionPipeline,
)
from diffusers.utils.pil_utils import PIL_INTERPOLATION
from PIL import Image
from core.config import config
from core.flags import LatentScaleModel
from core.inference.utilities.philox import PhiloxGenerator
from .random import randn
def preprocess_mask(mask):
mask = mask.convert("L")
# w, h = mask.size
# w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32
# mask = mask.resize(
# (w // scale_factor, h // scale_factor), resample=PIL_INTERPOLATION["nearest"]
# )
mask = np.array(mask).astype(np.float32) / 255.0
mask = np.tile(mask, (4, 1, 1))
# Gabe: same as mask.unsqueeze(0)
mask = mask[None].transpose(0, 1, 2, 3) # what does this step do?
mask = 1 - mask # repaint white, keep black
mask = torch.from_numpy(mask)
return mask | null |
156,420 | import logging
import math
from time import time
from typing import List, Optional, Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
from diffusers.models import vae as diffusers_vae
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import (
StableDiffusionPipeline,
)
from diffusers.utils.pil_utils import PIL_INTERPOLATION
from PIL import Image
from core.config import config
from core.flags import LatentScaleModel
from core.inference.utilities.philox import PhiloxGenerator
from .random import randn
logger = logging.getLogger(__name__)
logger.debug("Overwritten diffusers randn_tensor")
def pad_tensor(
tensor: torch.Tensor, multiple: int, size: Optional[Tuple[int, int]] = None
) -> torch.Tensor:
config = load_config()
class PhiloxGenerator:
def __init__(self, seed):
def seed(self):
def randn(self, shape): # discard g[2] and g[3]
def randn(
shape,
generator: Union[PhiloxGenerator, torch.Generator],
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
) -> torch.Tensor:
def prepare_latents(
pipe: StableDiffusionPipeline,
image: Optional[torch.Tensor],
timestep: torch.FloatTensor,
batch_size: int,
height: Optional[int],
width: Optional[int],
dtype: torch.dtype,
device: torch.device,
generator: Union[PhiloxGenerator, torch.Generator],
latents=None,
latent_channels: Optional[int] = None,
align_to: int = 1,
):
if image is None:
shape = (
batch_size,
pipe.unet.config.in_channels, # type: ignore
(math.ceil(height / align_to) * align_to) // pipe.vae_scale_factor, # type: ignore
(math.ceil(width / align_to) * align_to) // pipe.vae_scale_factor, # type: ignore
)
if latents is None:
# randn does not work reproducibly on mps
latents = randn(shape, generator, device=device, dtype=dtype) # type: ignore
else:
if latents.shape != shape:
raise ValueError(
f"Unexpected latents shape, got {latents.shape}, expected {shape}"
)
latents = latents.to(device)
# scale the initial noise by the standard deviation required by the scheduler
latents = latents * pipe.scheduler.init_noise_sigma # type: ignore
return latents, None, None
else:
if image.shape[1] != 4:
image = pad_tensor(image, pipe.vae_scale_factor)
init_latent_dist = pipe.vae.encode(image.to(config.api.device, dtype=pipe.vae.dtype)).latent_dist # type: ignore
init_latents = init_latent_dist.sample(generator=generator)
init_latents = 0.18215 * init_latents
init_latents = torch.cat([init_latents] * batch_size, dim=0) # type: ignore
else:
logger.debug("Skipping VAE encode, already have latents")
init_latents = image
# if isinstance(pipe.scheduler, KdiffusionSchedulerAdapter):
# init_latents = init_latents * pipe.scheduler.init_noise_sigma
init_latents_orig = init_latents
shape = init_latents.shape
if latent_channels is not None and latent_channels != shape[1]:
shape = (
batch_size,
latent_channels, # type: ignore
(math.ceil(height / align_to) * align_to) // pipe.vae_scale_factor, # type: ignore
(math.ceil(width / align_to) * align_to) // pipe.vae_scale_factor, # type: ignore
)
# add noise to latents using the timesteps
noise = randn(shape, generator, device=device, dtype=dtype)
latents = pipe.scheduler.add_noise(init_latents.to(device), noise.to(device), timestep.to(device)) # type: ignore
return latents, init_latents_orig, noise | null |
156,421 | import gc
import logging
from typing import Any, Tuple
import numpy as np
import torch
from controlnet_aux import (
CannyDetector,
HEDdetector,
LineartAnimeDetector,
LineartDetector,
MidasDetector,
MLSDdetector,
NormalBaeDetector,
OpenposeDetector,
)
from PIL import Image
from transformers.models.auto.image_processing_auto import AutoImageProcessor
from transformers.models.upernet import UperNetForSemanticSegmentation
from core.config import config
from core.types import ControlNetData
def _canny(
input_image: Image.Image, low_threshold: int = 100, high_threshold: int = 200
) -> Image.Image:
"Applies canny edge detection to an image"
from core import shared_dependent
if isinstance(shared_dependent.cached_controlnet_preprocessor, CannyDetector):
detector = shared_dependent.cached_controlnet_preprocessor
else:
_wipe_old()
detector = CannyDetector()
_cache_preprocessor(detector)
canny_image = detector(
img=input_image, low_threshold=low_threshold, high_threshold=high_threshold
)
return canny_image
def _midas(input_image: Image.Image) -> Image.Image:
"Applies depth estimation to an image"
from core import shared_dependent
if isinstance(shared_dependent.cached_controlnet_preprocessor, MidasDetector):
midas_detector = shared_dependent.cached_controlnet_preprocessor
else:
_wipe_old()
midas_detector = MidasDetector.from_pretrained("lllyasviel/Annotators")
_cache_preprocessor(midas_detector)
image = midas_detector(input_image)
if isinstance(image, tuple):
return image[0]
else:
return image
def _hed(
input_image: Image.Image, detect_resolution=512, image_resolution=512
) -> Image.Image:
"Applies hed edge detection to an image"
from core import shared_dependent
if isinstance(shared_dependent.cached_controlnet_preprocessor, HEDdetector):
hed_detector = shared_dependent.cached_controlnet_preprocessor
else:
_wipe_old()
hed_detector = HEDdetector.from_pretrained("lllyasviel/Annotators")
_cache_preprocessor(hed_detector)
image = hed_detector(
input_image,
detect_resolution=detect_resolution,
image_resolution=image_resolution,
)
assert isinstance(image, Image.Image)
return image
def _mlsd(
input_image: Image.Image,
resolution: int = 512,
score_thr: float = 0.1,
dist_thr: float = 20,
) -> Image.Image:
"Applies M-LSD edge detection to an image"
from core import shared_dependent
if isinstance(shared_dependent.cached_controlnet_preprocessor, MLSDdetector):
mlsd_detector = shared_dependent.cached_controlnet_preprocessor
else:
_wipe_old()
mlsd_detector = MLSDdetector.from_pretrained("lllyasviel/Annotators")
_cache_preprocessor(mlsd_detector)
image = mlsd_detector(
input_image,
thr_v=score_thr,
thr_d=dist_thr,
detect_resolution=resolution,
image_resolution=resolution,
)
assert isinstance(image, Image.Image)
return image
def _normal_bae(input_image: Image.Image) -> Image.Image:
"Applies normal estimation to an image"
from core import shared_dependent
if isinstance(shared_dependent.cached_controlnet_preprocessor, NormalBaeDetector):
normal_bae_detector = shared_dependent.cached_controlnet_preprocessor
else:
_wipe_old()
normal_bae_detector = NormalBaeDetector.from_pretrained("lllyasviel/Annotators")
_cache_preprocessor(normal_bae_detector)
image = normal_bae_detector(input_image, depth_and_normal=True) # type: ignore
return image
def _openpose(input_image: Image.Image) -> Image.Image:
"Applies openpose to an image"
from core import shared_dependent
if isinstance(shared_dependent.cached_controlnet_preprocessor, OpenposeDetector):
op_detector = shared_dependent.cached_controlnet_preprocessor
else:
_wipe_old()
op_detector = OpenposeDetector.from_pretrained("lllyasviel/Annotators")
_cache_preprocessor(op_detector)
image = op_detector(input_image, hand_and_face=True)
assert isinstance(image, Image.Image)
return image
def _segmentation(input_image: Image.Image) -> Image.Image:
"Applies segmentation to an image"
from core import shared_dependent
if isinstance(shared_dependent.cached_controlnet_preprocessor, Tuple):
(
image_processor,
image_segmentor,
) = shared_dependent.cached_controlnet_preprocessor
else:
_wipe_old()
image_processor = AutoImageProcessor.from_pretrained(
"openmmlab/upernet-convnext-small"
)
image_segmentor = UperNetForSemanticSegmentation.from_pretrained(
"openmmlab/upernet-convnext-small"
)
_cache_preprocessor((image_processor, image_segmentor))
pixel_values = image_processor(input_image, return_tensors="pt").pixel_values
assert isinstance(image_segmentor, UperNetForSemanticSegmentation)
with torch.no_grad():
outputs = image_segmentor(pixel_values)
seg = image_processor.post_process_semantic_segmentation(
outputs, target_sizes=[input_image.size[::-1]]
)[0]
color_seg = np.zeros(
(seg.shape[0], seg.shape[1], 3), dtype=np.uint8
) # height, width, 3
palette = np.array(_ade_palette())
for label, color in enumerate(palette):
color_seg[seg == label, :] = color
color_seg = color_seg.astype(np.uint8)
image = Image.fromarray(color_seg)
return image
class ControlNetData:
"Dataclass for the data of a control net request"
prompt: str
image: Union[bytes, str]
scheduler: Union[str, KarrasDiffusionSchedulers]
controlnet: str
id: str = field(default_factory=lambda: uuid4().hex)
negative_prompt: str = field(default="")
width: int = field(default=512)
height: int = field(default=512)
steps: int = field(default=25)
guidance_scale: float = field(default=7)
self_attention_scale: float = field(default=0.0)
sigmas: SigmaScheduler = field(default="automatic")
seed: int = field(default=0)
batch_size: int = field(default=1)
batch_count: int = field(default=1)
controlnet_conditioning_scale: float = field(default=1.0)
detection_resolution: int = field(default=512)
sampler_settings: Dict = field(default_factory=dict)
prompt_to_prompt_settings: Dict = field(default_factory=dict)
canny_low_threshold: int = field(default=100)
canny_high_threshold: int = field(default=200)
mlsd_thr_v: float = field(default=0.1)
mlsd_thr_d: float = field(default=0.1)
is_preprocessed: bool = field(default=False)
save_preprocessed: bool = field(default=False)
return_preprocessed: bool = field(default=True)
The provided code snippet includes necessary dependencies for implementing the `image_to_controlnet_input` function. Write a Python function `def image_to_controlnet_input( input_image: Image.Image, data: ControlNetData, ) -> Image.Image` to solve the following problem:
Converts an image to the format expected by the controlnet model
Here is the function:
def image_to_controlnet_input(
input_image: Image.Image,
data: ControlNetData,
) -> Image.Image:
"Converts an image to the format expected by the controlnet model"
model = data.controlnet.split("/")[-1]
if any(item in model for item in ["none", "scribble", "ip2p", "tile", "qrcode"]):
return input_image
elif "canny" in model:
return _canny(
input_image,
low_threshold=data.canny_low_threshold,
high_threshold=data.canny_low_threshold * 3,
)
elif "depth" in model:
return _midas(input_image)
elif any(item in model for item in ["hed", "softedge"]):
return _hed(
input_image,
detect_resolution=data.detection_resolution,
image_resolution=min(input_image.size),
)
elif "mlsd" in model:
return _mlsd(
input_image,
resolution=data.detection_resolution,
score_thr=data.mlsd_thr_v,
dist_thr=data.mlsd_thr_d,
)
elif "normal" in model:
return _normal_bae(input_image)
elif "openpose" in model:
return _openpose(input_image)
elif "seg" in model:
return _segmentation(input_image)
raise NotImplementedError | Converts an image to the format expected by the controlnet model |
156,422 | import gc
import logging
from typing import Any, Tuple
import numpy as np
import torch
from controlnet_aux import (
CannyDetector,
HEDdetector,
LineartAnimeDetector,
LineartDetector,
MidasDetector,
MLSDdetector,
NormalBaeDetector,
OpenposeDetector,
)
from PIL import Image
from transformers.models.auto.image_processing_auto import AutoImageProcessor
from transformers.models.upernet import UperNetForSemanticSegmentation
from core.config import config
from core.types import ControlNetData
def _wipe_old():
"Wipes old controlnet preprocessor from memory"
from core import shared_dependent
logger.debug("Did not find this controlnet preprocessor cached, wiping old ones")
shared_dependent.cached_controlnet_preprocessor = None
if "cuda" in config.api.device:
torch.cuda.empty_cache()
torch.cuda.ipc_collect()
gc.collect()
def _cache_preprocessor(preprocessor: Any):
"Caches controlnet preprocessor"
from core import shared_dependent
logger.debug(
f"Caching {preprocessor.__class__.__name__ if not isinstance(preprocessor, tuple) else preprocessor[0].__class__.__name__ + ' + ' + preprocessor[1].__class__.__name__} preprocessor"
)
shared_dependent.cached_controlnet_preprocessor = preprocessor
The provided code snippet includes necessary dependencies for implementing the `_lineart` function. Write a Python function `def _lineart(input_image: Image.Image) -> Image.Image` to solve the following problem:
Applies lineart to an image
Here is the function:
def _lineart(input_image: Image.Image) -> Image.Image:
"Applies lineart to an image"
from core import shared_dependent
if isinstance(shared_dependent.cached_controlnet_preprocessor, LineartDetector):
op_detector = shared_dependent.cached_controlnet_preprocessor
else:
_wipe_old()
op_detector = LineartDetector.from_pretrained("lllyasviel/Annotators")
_cache_preprocessor(op_detector)
image = op_detector(input_image)
assert isinstance(image, Image.Image)
return image | Applies lineart to an image |
156,423 | import gc
import logging
from typing import Any, Tuple
import numpy as np
import torch
from controlnet_aux import (
CannyDetector,
HEDdetector,
LineartAnimeDetector,
LineartDetector,
MidasDetector,
MLSDdetector,
NormalBaeDetector,
OpenposeDetector,
)
from PIL import Image
from transformers.models.auto.image_processing_auto import AutoImageProcessor
from transformers.models.upernet import UperNetForSemanticSegmentation
from core.config import config
from core.types import ControlNetData
def _wipe_old():
"Wipes old controlnet preprocessor from memory"
from core import shared_dependent
logger.debug("Did not find this controlnet preprocessor cached, wiping old ones")
shared_dependent.cached_controlnet_preprocessor = None
if "cuda" in config.api.device:
torch.cuda.empty_cache()
torch.cuda.ipc_collect()
gc.collect()
def _cache_preprocessor(preprocessor: Any):
"Caches controlnet preprocessor"
from core import shared_dependent
logger.debug(
f"Caching {preprocessor.__class__.__name__ if not isinstance(preprocessor, tuple) else preprocessor[0].__class__.__name__ + ' + ' + preprocessor[1].__class__.__name__} preprocessor"
)
shared_dependent.cached_controlnet_preprocessor = preprocessor
The provided code snippet includes necessary dependencies for implementing the `_lineart_anime` function. Write a Python function `def _lineart_anime(input_image: Image.Image) -> Image.Image` to solve the following problem:
Applies lineart_anime to an image
Here is the function:
def _lineart_anime(input_image: Image.Image) -> Image.Image:
"Applies lineart_anime to an image"
from core import shared_dependent
if isinstance(
shared_dependent.cached_controlnet_preprocessor, LineartAnimeDetector
):
op_detector = shared_dependent.cached_controlnet_preprocessor
else:
_wipe_old()
op_detector = LineartAnimeDetector.from_pretrained("lllyasviel/Annotators")
_cache_preprocessor(op_detector)
image = op_detector(input_image)
assert isinstance(image, Image.Image)
return image | Applies lineart_anime to an image |
156,424 | import logging
import re
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Union
import torch
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import (
StableDiffusionPipeline,
)
from core.utils import download_file
from ...config import config
from ...files import get_full_model_path
from .prompt_expansion import expand
logger = logging.getLogger(__name__)
def parse_prompt_special(
text: str,
) -> Tuple[str, Dict[str, List[Union[str, Tuple[str, float]]]]]:
"""
Replaces special tokens like <lora:more_details:0.7> with their correct format and outputs then into a dict.
>>> parse_prompt_special("This is a <ti:easynegative:0.7> example.")
'This is a (easynegative:0.7) example.'
>>> parse_prompt_special("This is a <lora:more_details:0.7> example.")
'This is a example.' (lora "more_details" gets loaded with a=0.7)
"""
load_map = {}
def replace(match):
type_: str = match.group(4) or match.group(1)
name = match.group(2)
strength = match.group(6) or match.group(3)
url: str = match.group(5)
if url:
filename = url.split("/")[-1]
file = Path("data/lora") / filename
name = file.stem
# Check if file exists
if not file.exists():
name = download_file(url, Path("data/lora"), add_filename=True).stem
else:
logger.debug(f"File {file} already cached")
load_map[type_] = load_map.get(type_, [])
if type_ == "ti":
load_map[type_].append(name)
return f"({name}:{strength if strength else '1.0'})"
# LoRAs don't really have trigger words, they all modify the UNet at least a bit
load_map[type_].append((name, float(strength) if strength else 1.0))
return "" if not config.api.huggingface_style_parsing else name
parsed = special_parser.sub(replace, text)
return (parsed, load_map)
def get_prompts_with_weights(tokenizer, prompt: List[str], max_length: int):
r"""
Tokenize a list of prompts and return its tokens with weights of each token.
No padding, starting or ending token is included.
"""
tokens = []
weights = []
truncated = False
for text in prompt:
texts_and_weights = parse_prompt_attention(text)
text_token = []
text_weight = []
for word, weight in texts_and_weights:
# tokenize and discard the starting and the ending token
token = tokenizer(word, max_length=max_length, truncation=True).input_ids[1:-1] # type: ignore
text_token += token
# copy the weight by length of token
text_weight += [weight] * len(token)
# stop if the text is too long (longer than truncation limit)
if len(text_token) > max_length:
truncated = True
break
# truncate
if len(text_token) > max_length:
truncated = True
text_token = text_token[:max_length]
text_weight = text_weight[:max_length]
tokens.append(text_token)
weights.append(text_weight)
if truncated:
logger.warning(
"Prompt was truncated. Try to shorten the prompt or increase max_embeddings_multiples"
)
return tokens, weights
def pad_tokens_and_weights(
tokens, weights, max_length, bos, eos, no_boseos_middle=True, chunk_length=77
):
r"""
Pad the tokens (with starting and ending tokens) and weights (with 1.0) to max_length.
"""
max_embeddings_multiples = (max_length - 2) // (chunk_length - 2)
weights_length = (
max_length if no_boseos_middle else max_embeddings_multiples * chunk_length
)
for i in range(len(tokens)):
tokens[i] = [bos] + tokens[i] + [eos] * (max_length - 1 - len(tokens[i]))
if no_boseos_middle:
weights[i] = [1.0] + weights[i] + [1.0] * (max_length - 1 - len(weights[i]))
else:
w = []
if len(weights[i]) == 0:
w = [1.0] * weights_length
else:
for j in range(max_embeddings_multiples):
w.append(1.0) # weight for starting token in this chunk
w += weights[i][
j
* (chunk_length - 2) : min(
len(weights[i]), (j + 1) * (chunk_length - 2)
)
]
w.append(1.0) # weight for ending token in this chunk
w += [1.0] * (weights_length - len(w))
weights[i] = w[:]
return tokens, weights
def get_unweighted_text_embeddings(
pipe: StableDiffusionPipeline,
text_input: torch.Tensor,
chunk_length: int,
no_boseos_middle: Optional[bool] = True,
text_encoder=None,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
When the length of tokens is a multiple of the capacity of the text encoder,
it should be split into chunks and sent to the text encoder individually.
"""
# TODO: when SDXL releases, refactor CLIP_stop_at_last_layer here.
max_embeddings_multiples = (text_input.shape[1] - 2) // (chunk_length - 2)
if not hasattr(pipe, "text_encoder_2"):
if max_embeddings_multiples > 1:
text_embeddings = []
for i in range(max_embeddings_multiples):
# extract the i-th chunk
text_input_chunk = text_input[
:, i * (chunk_length - 2) : (i + 1) * (chunk_length - 2) + 2
].clone()
# cover the head and the tail by the starting and the ending tokens
text_input_chunk[:, 0] = text_input[0, 0]
text_input_chunk[:, -1] = text_input[0, -1]
if hasattr(pipe, "clip_inference"):
text_embedding = pipe.clip_inference(text_input_chunk)
else:
text_embedding = pipe.text_encoder(text_input_chunk)[0] # type: ignore
if no_boseos_middle:
if i == 0:
# discard the ending token
text_embedding = text_embedding[:, :-1]
elif i == max_embeddings_multiples - 1:
# discard the starting token
text_embedding = text_embedding[:, 1:]
else:
# discard both starting and ending tokens
text_embedding = text_embedding[:, 1:-1]
text_embeddings.append(text_embedding)
text_embeddings = torch.concat(text_embeddings, axis=1) # type: ignore
else:
if hasattr(pipe, "clip_inference"):
text_embeddings = pipe.clip_inference(text_input)
else:
text_embeddings = pipe.text_encoder(text_input)[0] # type: ignore
return text_embeddings, None # type: ignore
else:
if max_embeddings_multiples > 1:
text_embeddings = []
hidden_states = []
for i in range(max_embeddings_multiples):
text_input_chunk = text_input[
:, i * (chunk_length - 2) : (i + 1) * (chunk_length - 2) + 2
].clone()
text_input_chunk[:, 0] = text_input[0, 0]
text_input_chunk[:, -1] = text_input[0, -1]
text_embedding = text_encoder( # type: ignore
text_input_chunk, output_hidden_states=True
)
if no_boseos_middle:
if i == 0:
text_embedding.hidden_states[-2] = text_embedding.hidden_states[
-2
][:, :-1]
elif i == max_embeddings_multiples - 1:
text_embedding.hidden_states[-2] = text_embedding.hidden_states[
-2
][:, 1:]
else:
text_embedding.hidden_states[-2] = text_embedding.hidden_states[
-2
][:, 1:-1]
text_embeddings.append(text_embedding)
text_embeddings = torch.concat([x.hidden_states[-2] for x in text_embeddings], axis=1) # type: ignore
# Temporary, but hey, at least it works :)
# TODO: try and fix this monstrosity :/
hidden_states = text_embeddings[-1][0].unsqueeze(0) # type: ignore
# text_embeddings = torch.Tensor(hidden_states.shape[0])
else:
text_embeddings = text_encoder(text_input, output_hidden_states=True) # type: ignore
hidden_states = text_embeddings[0]
text_embeddings = text_embeddings.hidden_states[-2]
logger.debug(f"{hidden_states.shape} {text_embeddings.shape}")
return text_embeddings, hidden_states
config = load_config()
def get_full_model_path(
repo_id: str,
revision: str = "main",
model_folder: str = "models",
force: bool = False,
diffusers_skip_ref_follow: bool = False,
) -> Path:
"Return the path to the actual model"
# Replace -- with / and remove the __dim part
repo_id = repo_id.replace("--", "/").split("__")[0]
repo_path = Path(repo_id)
# 1. Check for the exact path
if repo_path.exists():
logger.debug(f"Found model in {repo_path}")
return repo_path
# 2. Check if model is stored in local storage
alt_path = Path("data") / model_folder / repo_id
if alt_path.exists() or force or alt_path.is_symlink():
logger.debug(f"Found model in {alt_path}")
return alt_path
logger.debug(
f"Model not found in {repo_path} or {alt_path}, checking diffusers cache..."
)
# 3. Check if model is stored in diffusers cache
storage = diffusers_storage_name(repo_id)
ref = current_diffusers_ref(storage, revision)
if not ref:
raise ValueError(f"No ref found for {repo_id}")
if diffusers_skip_ref_follow:
return Path(storage)
return Path(storage) / "snapshots" / ref
def expand(prompt, seed, prompt_expansion_settings: Dict):
if prompt == "":
return ""
prompt_to_prompt_model = prompt_expansion_settings.pop(
"prompt_to_prompt_model", config.api.prompt_to_prompt_model
)
prompt_to_prompt_device = prompt_expansion_settings.pop(
"prompt_to_prompt_device", config.api.prompt_to_prompt_device
)
# Load in the model, or move to the necessary device.
_load(prompt_to_prompt_model, prompt_to_prompt_device)
seed = int(seed) % _seed_limit
set_seed(seed)
logger.debug(f"Using seed {seed}")
origin = _safe(prompt)
prompt = origin + _magic_split[seed % len(_magic_split)]
device, _ = _device_dtype(prompt_to_prompt_device)
tokenized_kwargs = _TOKENIZER(prompt, return_tensors="pt")
tokenized_kwargs.data["input_ids"] = tokenized_kwargs.data["input_ids"].to(
device=device
)
tokenized_kwargs.data["attention_mask"] = tokenized_kwargs.data[
"attention_mask"
].to(device=device)
current_token_length = int(tokenized_kwargs.data["input_ids"].shape[1])
max_token_length = 75 * int(math.ceil(float(current_token_length) / 75.0))
max_new_tokens = max_token_length - current_token_length
logits_processor = LogitsProcessorList([_logits_processor])
features = _GPT.generate(
**tokenized_kwargs, # type: ignore
num_beams=1,
max_new_tokens=max_new_tokens,
do_sample=True,
logits_processor=logits_processor,
)
result = _TOKENIZER.batch_decode(features, skip_special_tokens=True)
result = result[0]
result = _safe(result)
result = _remove_pattern(result, _dangerous_patterns)
return result
def install_lora_hook(pipe):
"Install LoRAHook to the pipe"
if hasattr(pipe, "lora_injector"):
return
injector = HookManager()
injector.install_hooks(pipe)
pipe.lora_injector = injector
The provided code snippet includes necessary dependencies for implementing the `get_weighted_text_embeddings` function. Write a Python function `def get_weighted_text_embeddings( pipe: StableDiffusionPipeline, prompt: Union[str, List[str]], uncond_prompt: Optional[Union[str, List[str]]] = None, max_embeddings_multiples: Optional[int] = 3, no_boseos_middle: Optional[bool] = False, skip_parsing: Optional[bool] = False, skip_weighting: Optional[bool] = False, seed: int = -1, prompt_expansion_settings: Optional[Dict] = None, text_encoder=None, tokenizer=None, )` to solve the following problem:
r""" Prompts can be assigned with local weights using brackets. For example, prompt 'A (very beautiful) masterpiece' highlights the words 'very beautiful', and the embedding tokens corresponding to the words get multiplied by a constant, 1.1. Also, to regularize of the embedding, the weighted embedding would be scaled to preserve the original mean. Args: pipe (`StableDiffusionPipeline`): Pipe to provide access to the tokenizer and the text encoder. prompt (`str` or `List[str]`): The prompt or prompts to guide the image generation. uncond_prompt (`str` or `List[str]`): The unconditional prompt or prompts for guide the image generation. If unconditional prompt is provided, the embeddings of prompt and uncond_prompt are concatenated. max_embeddings_multiples (`int`, *optional*, defaults to `3`): The max multiple length of prompt embeddings compared to the max output length of text encoder. no_boseos_middle (`bool`, *optional*, defaults to `False`): If the length of text token is multiples of the capacity of text encoder, whether reserve the starting and ending token in each of the chunk in the middle. skip_parsing (`bool`, *optional*, defaults to `False`): Skip the parsing of brackets. skip_weighting (`bool`, *optional*, defaults to `False`): Skip the weighting. When the parsing is skipped, it is forced True.
Here is the function:
def get_weighted_text_embeddings(
pipe: StableDiffusionPipeline,
prompt: Union[str, List[str]],
uncond_prompt: Optional[Union[str, List[str]]] = None,
max_embeddings_multiples: Optional[int] = 3,
no_boseos_middle: Optional[bool] = False,
skip_parsing: Optional[bool] = False,
skip_weighting: Optional[bool] = False,
seed: int = -1,
prompt_expansion_settings: Optional[Dict] = None,
text_encoder=None,
tokenizer=None,
):
r"""
Prompts can be assigned with local weights using brackets. For example,
prompt 'A (very beautiful) masterpiece' highlights the words 'very beautiful',
and the embedding tokens corresponding to the words get multiplied by a constant, 1.1.
Also, to regularize of the embedding, the weighted embedding would be scaled to preserve the original mean.
Args:
pipe (`StableDiffusionPipeline`):
Pipe to provide access to the tokenizer and the text encoder.
prompt (`str` or `List[str]`):
The prompt or prompts to guide the image generation.
uncond_prompt (`str` or `List[str]`):
The unconditional prompt or prompts for guide the image generation. If unconditional prompt
is provided, the embeddings of prompt and uncond_prompt are concatenated.
max_embeddings_multiples (`int`, *optional*, defaults to `3`):
The max multiple length of prompt embeddings compared to the max output length of text encoder.
no_boseos_middle (`bool`, *optional*, defaults to `False`):
If the length of text token is multiples of the capacity of text encoder, whether reserve the starting and
ending token in each of the chunk in the middle.
skip_parsing (`bool`, *optional*, defaults to `False`):
Skip the parsing of brackets.
skip_weighting (`bool`, *optional*, defaults to `False`):
Skip the weighting. When the parsing is skipped, it is forced True.
"""
prompt_expansion_settings = prompt_expansion_settings or {}
tokenizer = tokenizer or pipe.tokenizer
text_encoder = text_encoder or pipe.text_encoder
max_length = (tokenizer.model_max_length - 2) * max_embeddings_multiples + 2 # type: ignore
if isinstance(prompt, str):
prompt = [prompt]
if not hasattr(pipe, "clip_inference"):
loralist = []
for i, p in enumerate(prompt):
prompt[i], load_map = parse_prompt_special(p)
if len(load_map.keys()) != 0:
logger.debug(load_map)
if "lora" in load_map:
from ..injectables import install_lora_hook
install_lora_hook(pipe)
for lora, alpha in load_map["lora"]:
correct_path = get_full_model_path(
lora, model_folder="lora", force=True
)
for ext in [".safetensors", ".ckpt", ".bin", ".pt", ".pth"]:
path = get_full_model_path(
lora + ext, model_folder="lora", force=True
)
if path.exists():
correct_path = path
break
if not correct_path.exists():
correct_path = get_full_model_path(
lora, model_folder="lycoris", force=True
)
for ext in [".safetensors", ".ckpt", ".bin", ".pt", ".pth"]:
path = get_full_model_path(
lora + ext, model_folder="lycoris", force=True
)
if path.exists():
correct_path = path
break
if correct_path.exists():
loralist.append((correct_path, alpha, "lycoris"))
else:
logger.error(
f"Could not find any lora with the name {lora}"
)
else:
loralist.append((correct_path, alpha))
if "ti" in load_map:
# Disable TI for now as there's no reliable way to unload them
logger.info(
"Textual inversion via prompts is temporarily disabled."
)
if config.api.huggingface_style_parsing and hasattr(pipe, "lora_injector"):
for prompt_ in prompt:
old_l = loralist
loralist = list(
filter(
lambda x: Path(x[0]).stem.casefold() in prompt_.casefold(),
loralist,
)
)
for lora, weight in old_l:
if (lora, weight) not in loralist:
try:
pipe.remove_lora(Path(lora).name)
logger.debug(f"Unloading LoRA: {Path(lora).name}")
except KeyError:
pass
if hasattr(pipe, "lora_injector"):
remove_loras = pipe.unload_loras
remove_lycoris = pipe.unload_lycoris
logger.debug(f"{loralist}")
for ent in loralist:
lyco = len(ent) == 3
lora = ent[0]
alpha = ent[1]
name = Path(lora).name
if lyco:
if name not in remove_lycoris:
logger.debug(f"Adding LyCORIS {name} to the removal list")
remove_lycoris.append(name)
logger.debug(f"Applying LyCORIS {name} with strength {alpha}")
pipe.lora_injector.apply_lycoris(lora, alpha)
else:
if name not in remove_loras:
logger.debug(f"Adding LoRA {name} to the removal list")
remove_loras.append(name)
logger.debug(f"Applying LoRA {name} with strength {alpha}")
pipe.lora_injector.apply_lora(lora, alpha)
pipe.unload_lycoris = remove_lycoris
pipe.unload_loras = remove_loras
# Move after loras to purge <lora:...> and <ti:...>
if prompt_expansion_settings.pop("prompt_to_prompt", config.api.prompt_to_prompt):
for i, p in enumerate(prompt):
prompt[i] = expand(
p, seed, prompt_expansion_settings=prompt_expansion_settings
)
logger.info(f'Expanded prompt to "{prompt[i]}"')
if not skip_parsing:
prompt_tokens, prompt_weights = get_prompts_with_weights(
tokenizer, prompt, max_length - 2
)
if uncond_prompt is not None:
if isinstance(uncond_prompt, str):
uncond_prompt = [uncond_prompt]
uncond_tokens, uncond_weights = get_prompts_with_weights(
tokenizer, uncond_prompt, max_length - 2
)
else:
prompt_tokens = [
token[1:-1]
for token in tokenizer( # type: ignore
prompt, max_length=max_length, truncation=True
).input_ids
]
prompt_weights = [[1.0] * len(token) for token in prompt_tokens]
if uncond_prompt is not None:
if isinstance(uncond_prompt, str):
uncond_prompt = [uncond_prompt]
uncond_tokens = [
token[1:-1]
for token in tokenizer( # type: ignore
uncond_prompt, max_length=max_length, truncation=True
).input_ids
]
uncond_weights = [[1.0] * len(token) for token in uncond_tokens]
# round up the longest length of tokens to a multiple of (model_max_length - 2)
max_length = max([len(token) for token in prompt_tokens])
if uncond_prompt is not None:
max_length = max(max_length, max([len(token) for token in uncond_tokens])) # type: ignore
max_embeddings_multiples = min(
max_embeddings_multiples, # type: ignore
(max_length - 1) // (tokenizer.model_max_length - 2) + 1, # type: ignore
)
max_embeddings_multiples = max(1, max_embeddings_multiples) # type: ignore
max_length = (tokenizer.model_max_length - 2) * max_embeddings_multiples + 2 # type: ignore
# pad the length of tokens and weights
bos = tokenizer.bos_token_id # type: ignore
eos = tokenizer.eos_token_id # type: ignore
prompt_tokens, prompt_weights = pad_tokens_and_weights(
prompt_tokens,
prompt_weights,
max_length,
bos,
eos,
no_boseos_middle=no_boseos_middle, # type: ignore
chunk_length=tokenizer.model_max_length, # type: ignore
)
prompt_tokens = torch.tensor(
prompt_tokens, dtype=torch.long, device=pipe.device if hasattr(pipe, "clip_inference") else text_encoder.device # type: ignore
)
if uncond_prompt is not None:
uncond_tokens, uncond_weights = pad_tokens_and_weights(
uncond_tokens, # type: ignore
uncond_weights, # type: ignore
max_length,
bos,
eos,
no_boseos_middle=no_boseos_middle, # type: ignore
chunk_length=tokenizer.model_max_length, # type: ignore
)
uncond_tokens = torch.tensor(
uncond_tokens, dtype=torch.long, device=pipe.device if hasattr(pipe, "clip_inference") else text_encoder.device # type: ignore
)
# get the embeddings
text_embeddings, hidden_states = get_unweighted_text_embeddings(
pipe, # type: ignore
prompt_tokens,
tokenizer.model_max_length, # type: ignore
no_boseos_middle=no_boseos_middle,
text_encoder=text_encoder,
)
prompt_weights = torch.tensor(
prompt_weights, dtype=text_embeddings.dtype, device=pipe.device if hasattr(pipe, "clip_inference") else text_encoder.device # type: ignore
)
if uncond_prompt is not None:
uncond_embeddings, uncond_hidden_states = get_unweighted_text_embeddings(
pipe, # type: ignore
uncond_tokens, # type: ignore
tokenizer.model_max_length, # type: ignore
no_boseos_middle=no_boseos_middle,
text_encoder=text_encoder,
)
uncond_weights = torch.tensor(
uncond_weights, dtype=uncond_embeddings.dtype, device=pipe.device if hasattr(pipe, "clip_inference") else text_encoder.device # type: ignore
)
# assign weights to the prompts and normalize in the sense of mean
if (not skip_parsing) and (not skip_weighting):
previous_mean = (
text_embeddings.float().mean(axis=[-2, -1]).to(text_embeddings.dtype) # type: ignore
)
text_embeddings *= prompt_weights.unsqueeze(-1)
current_mean = (
text_embeddings.float().mean(axis=[-2, -1]).to(text_embeddings.dtype) # type: ignore
)
text_embeddings *= (previous_mean / current_mean).unsqueeze(-1).unsqueeze(-1)
if uncond_prompt is not None:
previous_mean = (
uncond_embeddings.float() # type: ignore
.mean(axis=[-2, -1])
.to(uncond_embeddings.dtype) # type: ignore
)
uncond_embeddings *= uncond_weights.unsqueeze(-1) # type: ignore
current_mean = (
uncond_embeddings.float() # type: ignore
.mean(axis=[-2, -1]) # type: ignore
.to(uncond_embeddings.dtype)
)
uncond_embeddings *= (
(previous_mean / current_mean).unsqueeze(-1).unsqueeze(-1)
)
if uncond_prompt is not None:
return text_embeddings, hidden_states, uncond_embeddings, uncond_hidden_states # type: ignore
return text_embeddings, hidden_states, None, None | r""" Prompts can be assigned with local weights using brackets. For example, prompt 'A (very beautiful) masterpiece' highlights the words 'very beautiful', and the embedding tokens corresponding to the words get multiplied by a constant, 1.1. Also, to regularize of the embedding, the weighted embedding would be scaled to preserve the original mean. Args: pipe (`StableDiffusionPipeline`): Pipe to provide access to the tokenizer and the text encoder. prompt (`str` or `List[str]`): The prompt or prompts to guide the image generation. uncond_prompt (`str` or `List[str]`): The unconditional prompt or prompts for guide the image generation. If unconditional prompt is provided, the embeddings of prompt and uncond_prompt are concatenated. max_embeddings_multiples (`int`, *optional*, defaults to `3`): The max multiple length of prompt embeddings compared to the max output length of text encoder. no_boseos_middle (`bool`, *optional*, defaults to `False`): If the length of text token is multiples of the capacity of text encoder, whether reserve the starting and ending token in each of the chunk in the middle. skip_parsing (`bool`, *optional*, defaults to `False`): Skip the parsing of brackets. skip_weighting (`bool`, *optional*, defaults to `False`): Skip the weighting. When the parsing is skipped, it is forced True. |
156,427 | import hashlib
import logging
import math
import os
from pathlib import Path
from typing import List, Optional, Union
import numpy as np
import torch
from diffusers.utils.import_utils import is_accelerate_available
from PIL import Image
from safetensors.numpy import load_file, save_file
from tqdm import tqdm
from transformers.modeling_utils import PreTrainedModel
from transformers.models.auto.modeling_auto import AutoModelForCausalLM
from transformers.models.auto.processing_auto import AutoProcessor
from transformers.models.blip.modeling_blip import BlipForConditionalGeneration
from transformers.models.blip_2 import Blip2ForConditionalGeneration
from transformers.utils import is_bitsandbytes_available
from core.config import config
from core.files import get_full_model_path
from core.interrogation.base_interrogator import InterrogationModel, InterrogationResult
from core.optimizations import autocast
from core.types import InterrogatorQueueEntry, Job
from core.utils import convert_to_image, download_file
class LabelTable:
"internal"
def __init__(self, labels: List[str], descriptor: str, interrogator):
self.ignore_on_merge = descriptor.startswith("ignore-")
if self.ignore_on_merge:
descriptor = descriptor.removeprefix("ignore-")
self.descriptor = descriptor
self.chunk_size = config.interrogator.chunk_size
self.cache_path = get_full_model_path("_cache", model_folder="clip", force=True)
self.device = interrogator.device
self.dtype = interrogator.dtype
self.embeds = []
self.labels = labels
self.tokenize = interrogator.tokenize
hash = hashlib.sha1(",".join(labels).encode()).hexdigest() # type: ignore pylint: disable=redefined-builtin
sanitized_name = config.interrogator.caption_model.replace("/", "_").replace(
"@", "_"
)
self._load_cached(descriptor, hash, sanitized_name)
if len(self.labels) != len(self.embeds):
self.embeds = []
chunks = np.array_split(self.labels, max(1, len(self.labels) / self.chunk_size)) # type: ignore
for chunk in tqdm(chunks, desc="CLIP"):
text_tokens = self.tokenize(chunk).to(self.device)
with torch.no_grad(), autocast(dtype=self.dtype): # type: ignore
text_features = interrogator.clip_model.encode_text(text_tokens)
text_features /= text_features.norm(dim=-1, keepdim=True)
# if no workie, put a half() before the cpu()
text_features = text_features.cpu().numpy()
for i in range(text_features.shape[0]):
self.embeds.append(text_features[i])
if descriptor and self.cache_path:
self.cache_path.mkdir(parents=True, exist_ok=True)
cache_file = self.cache_path.joinpath(
f"{sanitized_name}_{descriptor}.safetensors"
)
tensors = {
"embeds": np.stack(self.embeds),
"hash": np.array([ord(c) for c in hash], dtype=np.int8),
}
save_file(tensors, str(cache_file))
if is_cpu(self.device):
self.embeds = [e.astype(np.float32) for e in self.embeds]
def _load_cached(self, descriptor: str, hash_: str, sanitized_name: str) -> bool:
cached_safetensors = self.cache_path.joinpath(
f"{sanitized_name}_{descriptor}.safetensors"
)
if not cached_safetensors.exists():
download_url = CACHE_URL + f"{sanitized_name}_{descriptor}.safetensors"
self.cache_path.mkdir(parents=True, exist_ok=True)
download_file(download_url, cached_safetensors)
tensors = load_file(str(cached_safetensors))
if "hash" in tensors and "embeds" in tensors:
if np.array_equal(
tensors["hash"], np.array([ord(c) for c in hash_], dtype=np.int8)
):
self.embeds = tensors["embeds"]
if len(self.embeds.shape) == 2:
self.embeds = [self.embeds[i] for i in range(self.embeds.shape[0])]
return True
return False
def _rank(
self,
image_features: torch.Tensor,
text_embeds: torch.Tensor,
top_count: int = 1,
reverse: bool = False,
) -> str:
top_count = min(top_count, len(text_embeds))
text_embeds = torch.stack([torch.from_numpy(t) for t in text_embeds]).to(
self.device, dtype=self.dtype
)
with torch.no_grad(), autocast(dtype=self.dtype): # type: ignore
similarity = image_features @ text_embeds.T
if reverse:
similarity = -similarity
_, top_labels = similarity.float().cpu().topk(top_count, dim=-1)
return [top_labels[0][i].numpy() for i in range(top_count)] # type: ignore
def rank(
self, image_features: torch.Tensor, top_count: int = 1, reverse: bool = False
) -> List[str]:
"internal"
if len(self.labels) <= self.chunk_size:
tops = self._rank(image_features, self.embeds, top_count=top_count, reverse=reverse) # type: ignore
return [self.labels[i] for i in tops] # type: ignore
num_chunks = int(math.ceil(len(self.labels) / self.chunk_size))
keep_per_chunk = int(self.chunk_size / num_chunks)
top_labels, top_embeds = [], []
for chunk_idx in tqdm(range(num_chunks), desc="CLIP"):
start = chunk_idx * self.chunk_size
stop = min(start + self.chunk_size, len(self.embeds))
tops = self._rank(image_features, self.embeds[start:stop], top_count=keep_per_chunk, reverse=reverse) # type: ignore
top_labels.extend([self.labels[start + i] for i in tops]) # type: ignore
top_embeds.extend([self.embeds[start + i] for i in tops]) # type: ignore
tops = self._rank(image_features, top_embeds, top_count=top_count) # type: ignore
return [top_labels[i] for i in tops] # type: ignore
def _merge_tables(tables: List[LabelTable], ci) -> LabelTable:
m = LabelTable([], None, ci) # type: ignore
for table in tables:
if not table.ignore_on_merge:
m.labels.extend(table.labels)
m.embeds.extend(table.embeds) # type: ignore
return m | null |
156,428 | import hashlib
import logging
import math
import os
from pathlib import Path
from typing import List, Optional, Union
import numpy as np
import torch
from diffusers.utils.import_utils import is_accelerate_available
from PIL import Image
from safetensors.numpy import load_file, save_file
from tqdm import tqdm
from transformers.modeling_utils import PreTrainedModel
from transformers.models.auto.modeling_auto import AutoModelForCausalLM
from transformers.models.auto.processing_auto import AutoProcessor
from transformers.models.blip.modeling_blip import BlipForConditionalGeneration
from transformers.models.blip_2 import Blip2ForConditionalGeneration
from transformers.utils import is_bitsandbytes_available
from core.config import config
from core.files import get_full_model_path
from core.interrogation.base_interrogator import InterrogationModel, InterrogationResult
from core.optimizations import autocast
from core.types import InterrogatorQueueEntry, Job
from core.utils import convert_to_image, download_file
def _truncate_to_fit(text: str, tokenize) -> str:
parts = text.split(", ")
new_text = parts[0]
for part in parts[1:]:
if tokenize([new_text + part])[0][-1] != 0:
break
new_text += ", " + part
return new_text | null |
156,429 | import hashlib
import logging
import math
import os
from pathlib import Path
from typing import List, Optional, Union
import numpy as np
import torch
from diffusers.utils.import_utils import is_accelerate_available
from PIL import Image
from safetensors.numpy import load_file, save_file
from tqdm import tqdm
from transformers.modeling_utils import PreTrainedModel
from transformers.models.auto.modeling_auto import AutoModelForCausalLM
from transformers.models.auto.processing_auto import AutoProcessor
from transformers.models.blip.modeling_blip import BlipForConditionalGeneration
from transformers.models.blip_2 import Blip2ForConditionalGeneration
from transformers.utils import is_bitsandbytes_available
from core.config import config
from core.files import get_full_model_path
from core.interrogation.base_interrogator import InterrogationModel, InterrogationResult
from core.optimizations import autocast
from core.types import InterrogatorQueueEntry, Job
from core.utils import convert_to_image, download_file
The provided code snippet includes necessary dependencies for implementing the `_load_list` function. Write a Python function `def _load_list(data_path: str, filename: Optional[str] = None) -> List[str]` to solve the following problem:
Load a list of strings from a file.
Here is the function:
def _load_list(data_path: str, filename: Optional[str] = None) -> List[str]:
"""Load a list of strings from a file."""
if filename is not None:
data_path = os.path.join(data_path, filename)
with open(data_path, "r", encoding="utf-8", errors="replace") as f:
items = [line.strip() for line in f.readlines()]
return items | Load a list of strings from a file. |
156,430 | import hashlib
import logging
import math
import os
from pathlib import Path
from typing import List, Optional, Union
import numpy as np
import torch
from diffusers.utils.import_utils import is_accelerate_available
from PIL import Image
from safetensors.numpy import load_file, save_file
from tqdm import tqdm
from transformers.modeling_utils import PreTrainedModel
from transformers.models.auto.modeling_auto import AutoModelForCausalLM
from transformers.models.auto.processing_auto import AutoProcessor
from transformers.models.blip.modeling_blip import BlipForConditionalGeneration
from transformers.models.blip_2 import Blip2ForConditionalGeneration
from transformers.utils import is_bitsandbytes_available
from core.config import config
from core.files import get_full_model_path
from core.interrogation.base_interrogator import InterrogationModel, InterrogationResult
from core.optimizations import autocast
from core.types import InterrogatorQueueEntry, Job
from core.utils import convert_to_image, download_file
The provided code snippet includes necessary dependencies for implementing the `is_cpu` function. Write a Python function `def is_cpu(device: Union[str, torch.device]) -> bool` to solve the following problem:
Return whether a device is cpu
Here is the function:
def is_cpu(device: Union[str, torch.device]) -> bool:
"Return whether a device is cpu"
return device == "cpu" or device == torch.device("cpu") | Return whether a device is cpu |
156,431 | import time
from typing import List
import torch
from PIL import Image
from api import websocket_manager
from api.websockets.data import Data
from core import shared
from core.config import config
from core.errors import InferenceInterruptedError
from core.inference.utilities import cheap_approximation, numpy_to_pil, taesd
from core.utils import convert_images_to_base64_grid
last_image_time = time.time()
websocket_manager = WebSocketManager()
class Data:
"Data to be sent to the client"
def __init__(self, data: Union[Dict[Any, Any], List[Any]], data_type: str):
self.data = data
self.type = data_type
def to_json(self) -> Union[Dict[str, Any], List[Any]]:
"Converts the data to a JSON object"
return {"type": self.type, "data": self.data}
config = load_config()
class InferenceInterruptedError(Exception):
"Raised when the model is interrupted"
def convert_images_to_base64_grid(
images: List[Image.Image],
quality: int = 95,
image_format: ImageFormats = "png",
) -> str:
"Convert a list of images to a list of base64 strings"
return convert_image_to_base64(
image_grid(images), quality=quality, image_format=image_format
)
The provided code snippet includes necessary dependencies for implementing the `callback` function. Write a Python function `def callback(step: int, _timestep: int, tensor: torch.Tensor)` to solve the following problem:
Callback for all processes that have steps and partial images.
Here is the function:
def callback(step: int, _timestep: int, tensor: torch.Tensor):
"Callback for all processes that have steps and partial images."
global last_image_time
if shared.interrupt:
shared.interrupt = False
raise InferenceInterruptedError
shared.current_done_steps += 1
if step > shared.current_steps:
shared.current_steps = shared.current_done_steps
send_image = config.api.live_preview_method != "disabled" and (
(time.time() - last_image_time > config.api.live_preview_delay)
)
images: List[Image.Image] = []
if send_image:
last_image_time = time.time()
if config.api.live_preview_method == "approximation":
for t in range(tensor.shape[0]):
images.append(cheap_approximation(tensor[t]))
else:
for img in numpy_to_pil(taesd(tensor)):
images.append(img)
websocket_manager.broadcast_sync(
data=Data(
data_type=shared.current_method, # type: ignore
data={
"progress": int(
(shared.current_done_steps / shared.current_steps) * 100
),
"current_step": shared.current_done_steps,
"total_steps": shared.current_steps,
"image": convert_images_to_base64_grid(
images, quality=60, image_format="webp"
)
if send_image
else "",
},
)
) | Callback for all processes that have steps and partial images. |
156,432 | import copy
import json
import logging
from dataclasses import fields
from io import BytesIO
from os import makedirs
from pathlib import Path
from typing import List, Union
import piexif
import piexif.helper
from PIL import Image
from PIL.PngImagePlugin import PngInfo
from core.config import config
from core.types import (
ControlNetQueueEntry,
Img2ImgQueueEntry,
InpaintQueueEntry,
Txt2ImgQueueEntry,
UpscaleQueueEntry,
)
from core.utils import unwrap_enum_name
logger = logging.getLogger(__name__)
def create_metadata(
job: Union[
Txt2ImgQueueEntry,
Img2ImgQueueEntry,
InpaintQueueEntry,
ControlNetQueueEntry,
UpscaleQueueEntry,
],
index: int,
):
"Return image with metadata burned into it"
data = copy.copy(job.data)
text_metadata = PngInfo()
exif_meta_dict = {}
if not isinstance(job, UpscaleQueueEntry):
data.seed = str(job.data.seed) + (f"({index})" if index > 0 else "") # type: ignore Overwrite for sequencialy generated images
def write_metadata_text(key: str):
text_metadata.add_text(key, str(unwrap_enum_name(data.__dict__.get(key, ""))))
def write_metadata_exif(key: str):
exif_meta_dict[key] = str(unwrap_enum_name(data.__dict__.get(key, "")))
if config.api.image_extension == "png":
for key in fields(data):
if key.name not in ("image", "mask_image"):
write_metadata_text(key.name)
else:
for key in fields(data):
if key.name not in ("image", "mask_image"):
write_metadata_exif(key.name)
if isinstance(job, Txt2ImgQueueEntry):
procedure = "txt2img"
elif isinstance(job, Img2ImgQueueEntry):
procedure = "img2img"
elif isinstance(job, InpaintQueueEntry):
procedure = "inpainting"
elif isinstance(job, ControlNetQueueEntry):
procedure = "control_net"
elif isinstance(job, UpscaleQueueEntry):
procedure = "upscale"
else:
procedure = "unknown"
if config.api.image_extension == "png":
text_metadata.add_text("procedure", procedure)
text_metadata.add_text("model", job.model)
user_comment: bytes = b"" # for type checking
else:
exif_meta_dict["procedure"] = procedure
exif_meta_dict["model"] = job.model
user_comment = piexif.helper.UserComment.dump(
json.dumps(exif_meta_dict, ensure_ascii=False), encoding="unicode"
)
return text_metadata if config.api.image_extension == "png" else user_comment
config = load_config()
class Txt2ImgQueueEntry(Job):
"Dataclass for a text to image queue entry"
data: Txt2imgData
class Img2ImgQueueEntry(Job):
"Dataclass for an image to image queue entry"
data: Img2imgData
class InpaintQueueEntry(Job):
"Dataclass for an image to image queue entry"
data: InpaintData
class ControlNetQueueEntry(Job):
"Dataclass for a control net queue entry"
data: ControlNetData
class UpscaleQueueEntry(Job):
"Dataclass for a real esrgan job"
data: UpscaleData
r2: Optional["R2Bucket"] = None
The provided code snippet includes necessary dependencies for implementing the `save_images` function. Write a Python function `def save_images( images: List[Image.Image], job: Union[ Txt2ImgQueueEntry, Img2ImgQueueEntry, InpaintQueueEntry, ControlNetQueueEntry, UpscaleQueueEntry, ], )` to solve the following problem:
Save image to disk or r2
Here is the function:
def save_images(
images: List[Image.Image],
job: Union[
Txt2ImgQueueEntry,
Img2ImgQueueEntry,
InpaintQueueEntry,
ControlNetQueueEntry,
UpscaleQueueEntry,
],
):
"Save image to disk or r2"
if isinstance(
job,
(
Txt2ImgQueueEntry,
Img2ImgQueueEntry,
InpaintQueueEntry,
),
):
prompt = (
job.data.prompt[:30]
.strip()
.replace(",", "")
.replace("(", "")
.replace(")", "")
.replace("[", "")
.replace("]", "")
.replace("?", "")
.replace("!", "")
.replace(":", "")
.replace(";", "")
.replace("'", "")
.replace('"', "")
.replace(" ", "_")
.replace("<", "")
.replace(">", "")
)
else:
prompt = ""
urls: List[str] = []
for i, image in enumerate(images):
if isinstance(job, UpscaleQueueEntry):
folder = "extra"
elif isinstance(job, Txt2ImgQueueEntry):
folder = "txt2img"
else:
folder = "img2img"
metadata = create_metadata(job, i)
if job.save_image == "r2":
# Save into Cloudflare R2 bucket
from core.shared_dependent import r2
assert r2 is not None, "R2 is not configured, enable debug mode to see why"
filename = f"{job.data.id}-{i}.png"
image_bytes = BytesIO()
image.save(image_bytes, pnginfo=metadata, format=config.api.image_extension)
image_bytes.seek(0)
url = r2.upload_file(file=image_bytes, filename=filename)
if url:
logger.debug(f"Saved image to R2: {filename}")
urls.append(url)
else:
logger.debug("No provided Dev R2 URL, uploaded but returning empty URL")
else:
base_dir = Path("data/outputs")
extra_path = config.api.save_path_template.format(
**{
"prompt": prompt,
"id": job.data.id,
"folder": folder,
"seed": job.data.seed
if not isinstance(job, UpscaleQueueEntry)
else "0",
"index": i,
"extension": config.api.image_extension,
}
)
path = base_dir / extra_path
makedirs(path.parent, exist_ok=True)
with path.open("wb") as f:
logger.debug(f"Saving image to {path.as_posix()}")
if config.api.image_extension == "png":
image.save(f, pnginfo=metadata)
else:
# ! This is using 2 filesystem calls, find a way to save directly to disk with metadata properly inserted
# Save the image
image.save(f, quality=config.api.image_quality)
# Insert metadata
exif_metadata = {
"0th": {},
"Exif": Image.Exif(),
"GPS": {},
"Interop": {},
"1st": {},
}
exif_metadata["Exif"][piexif.ExifIFD.UserComment] = metadata
exif_bytes = piexif.dump(exif_metadata)
piexif.insert(exif_bytes, path.as_posix())
return urls | Save image to disk or r2 |
156,433 | import importlib.metadata
import importlib.util
import logging
import os
import platform
import subprocess
import sys
from dataclasses import dataclass
from importlib.metadata import PackageNotFoundError
from pathlib import Path
from typing import List, Optional, Union
def install_requirements(path_to_requirements: str = "requirements.txt"):
"Check if requirements are installed, if not, install them"
with open(path_to_requirements, encoding="utf-8", mode="r") as f:
requirements = {}
for line in [r.strip() for r in f.read().splitlines()]:
split = line.split(";")
i: str = split[0].strip()
if len(split) > 1:
check = split[1].strip()
else:
check = ""
if check == 'platform_system == "Linux"':
logger.debug("Install check for Linux only")
if platform.system() != "Linux":
continue
if "git+http" in i:
tmp = i.split("@")[0].split("/")[-1].replace(".git", "").strip()
version = i.split("#") if "#" in i else None
if version:
tmp += f"=={version[-1].strip()}"
logger.debug(f"Rewrote git requirement: {i} => {tmp}")
i = tmp
if "==" in i:
requirements[i.split("==")[0]] = i.replace(i.split("==")[0], "").strip()
elif ">=" in i:
requirements[i.split(">=")[0]] = i.replace(i.split(">=")[0], "").strip()
elif "<=" in i:
requirements[i.split("<=")[0]] = i.replace(i.split("<=")[0], "").strip()
else:
requirements[i] = None
try:
for requirement in requirements:
# Skip extra commands for pip and comments
if requirement.startswith("#") or requirement.startswith("--"):
continue
if requirement in renamed_requirements:
logger.debug(
f"Requirement {requirement} is renamed to {renamed_requirements[requirement]}"
)
requirement_name = renamed_requirements[requirement]
else:
requirement_name = requirement
logger.debug(f"Checking requirement: {requirement}")
fixed_name = requirement_name.replace("-", "_").lower()
if not is_installed(fixed_name, requirements[requirement]):
logger.debug(f"Requirement {requirement_name} is not installed")
raise ImportError
except ImportError as e:
logger.debug(
f"Installing requirements: {path_to_requirements}, because: {e} ({e.__class__.__name__})"
)
try:
subprocess.check_call(
[
sys.executable,
"-m",
"pip",
"install",
"-r",
path_to_requirements,
]
)
except subprocess.CalledProcessError:
logger.error(f"Failed to install requirements: {path_to_requirements}")
sys.exit(1)
The provided code snippet includes necessary dependencies for implementing the `install_bot` function. Write a Python function `def install_bot()` to solve the following problem:
Install necessary requirements for the discord bot
Here is the function:
def install_bot():
"Install necessary requirements for the discord bot"
install_requirements("requirements/bot.txt") | Install necessary requirements for the discord bot |
156,434 | import importlib.metadata
import importlib.util
import logging
import os
import platform
import subprocess
import sys
from dataclasses import dataclass
from importlib.metadata import PackageNotFoundError
from pathlib import Path
from typing import List, Optional, Union
The provided code snippet includes necessary dependencies for implementing the `is_up_to_date` function. Write a Python function `def is_up_to_date()` to solve the following problem:
Check if the virtual environment is up to date
Here is the function:
def is_up_to_date():
"Check if the virtual environment is up to date" | Check if the virtual environment is up to date |
156,435 | import logging
import os
from pathlib import Path
from typing import List, Union
from diffusers.utils.constants import DIFFUSERS_CACHE
from huggingface_hub.file_download import repo_folder_name
from core.types import ModelResponse
from core.utils import determine_model_type
The provided code snippet includes necessary dependencies for implementing the `is_valid_diffusers_vae` function. Write a Python function `def is_valid_diffusers_vae(model_path: Path) -> bool` to solve the following problem:
Check if the folder contains valid VAE files.
Here is the function:
def is_valid_diffusers_vae(model_path: Path) -> bool:
"Check if the folder contains valid VAE files."
files = ["config.json", "diffusion_pytorch_model.bin"]
is_valid = True
for file in files:
is_valid = is_valid and Path(os.path.join(model_path, file)).exists()
return is_valid | Check if the folder contains valid VAE files. |
156,436 | import logging
import os
from pathlib import Path
from typing import List, Union
from diffusers.utils.constants import DIFFUSERS_CACHE
from huggingface_hub.file_download import repo_folder_name
from core.types import ModelResponse
from core.utils import determine_model_type
The provided code snippet includes necessary dependencies for implementing the `is_valid_diffusers_model` function. Write a Python function `def is_valid_diffusers_model(model_path: Union[str, Path])` to solve the following problem:
Check if the folder contains valid diffusers files
Here is the function:
def is_valid_diffusers_model(model_path: Union[str, Path]):
"Check if the folder contains valid diffusers files"
binary_folders = ["text_encoder", "unet", "vae"]
files = [
"model_index.json",
"scheduler/scheduler_config.json",
"text_encoder/config.json",
"tokenizer/tokenizer_config.json",
"tokenizer/vocab.json",
"unet/config.json",
"vae/config.json",
]
is_valid = True
path = model_path if isinstance(model_path, Path) else Path(model_path)
# Check all the folders that should container at least one binary file
for folder in binary_folders:
# Check if the folder exists
if not os.path.exists(path / folder):
is_valid = False
break
# Check if there is at least one .bin file in the folder
has_binaries = True
found_files = os.listdir(path / folder)
if len([path / folder / i for i in found_files if i.endswith(".bin")]) < 1:
has_binaries = False
# Check if there is at least one .safetensors file in the folder
has_safetensors = True
found_files = os.listdir(path / folder)
if (
len([path / folder / i for i in found_files if i.endswith(".safetensors")])
< 1
):
has_safetensors = False
# If there is no binary or safetensor file, the model is not valid
if not has_binaries and not has_safetensors:
is_valid = False
# Check all the other files that should be present
for file in files:
if not os.path.exists(path / file):
is_valid = False
return is_valid | Check if the folder contains valid diffusers files |
156,437 | import logging
import os
from pathlib import Path
from typing import List, Union
from diffusers.utils.constants import DIFFUSERS_CACHE
from huggingface_hub.file_download import repo_folder_name
from core.types import ModelResponse
from core.utils import determine_model_type
The provided code snippet includes necessary dependencies for implementing the `is_valid_aitemplate_model` function. Write a Python function `def is_valid_aitemplate_model(model_path: Union[str, Path])` to solve the following problem:
Check if the folder contains valid AITemplate files
Here is the function:
def is_valid_aitemplate_model(model_path: Union[str, Path]):
"Check if the folder contains valid AITemplate files"
files = [
"AutoencoderKL/test.so",
"CLIPTextModel/test.so",
"UNet2DConditionModel/test.so",
]
is_valid = True
path = model_path if isinstance(model_path, Path) else Path(model_path)
# Check all the files that should be present
for file in files:
if not os.path.exists(path / file):
is_valid = False
return is_valid | Check if the folder contains valid AITemplate files |
156,438 | import logging
import os
from pathlib import Path
from typing import List, Union
from diffusers.utils.constants import DIFFUSERS_CACHE
from huggingface_hub.file_download import repo_folder_name
from core.types import ModelResponse
from core.utils import determine_model_type
def diffusers_storage_name(repo_id: str, repo_type: str = "model") -> str:
"Return the name of the folder where the diffusers model is stored"
return os.path.join(
DIFFUSERS_CACHE, repo_folder_name(repo_id=repo_id, repo_type=repo_type)
)
def current_diffusers_ref(path: str, revision: str = "main") -> str:
"Return the current ref of the diffusers model"
rev_path = os.path.join(path, "refs", revision)
snapshot_path = os.path.join(path, "snapshots")
if not os.path.exists(rev_path) or not os.path.exists(snapshot_path):
raise ValueError(
f"Ref path {rev_path} or snapshot path {snapshot_path} not found"
)
snapshots = os.listdir(snapshot_path)
with open(os.path.join(path, "refs", revision), "r", encoding="utf-8") as f:
ref = f.read().strip().split(":")[0]
for snapshot in snapshots:
if ref.startswith(snapshot):
return snapshot
raise ValueError(
f"Ref {ref} found in {snapshot_path} for revision {revision}, but ref path does not exist"
)
The provided code snippet includes necessary dependencies for implementing the `list_cached_model_folders` function. Write a Python function `def list_cached_model_folders(repo_id: str, full_path: bool = False)` to solve the following problem:
List all the folders in the cached model
Here is the function:
def list_cached_model_folders(repo_id: str, full_path: bool = False):
"List all the folders in the cached model"
storage = diffusers_storage_name(repo_id)
ref = current_diffusers_ref(storage)
if full_path:
return [
os.path.join(storage, "snapshots", ref, folder) # type: ignore
for folder in os.listdir(os.path.join(storage, "snapshots", ref)) # type: ignore
]
else:
return os.listdir(os.path.join(storage, "snapshots", ref)) # type: ignore | List all the folders in the cached model |
156,439 | import json
import logging
import os
import re
import threading
from io import BytesIO
from pathlib import Path
from typing import Dict, List, Union
import piexif
import piexif.helper
from fastapi import HTTPException
from fastapi.responses import Response
from PIL import Image
from requests import HTTPError
from core.config import config
from core.utils import convert_image_to_base64
The provided code snippet includes necessary dependencies for implementing the `debounce` function. Write a Python function `def debounce(wait_time: float)` to solve the following problem:
Decorator that will debounce a function so that it is called after wait_time seconds If it is called multiple times, will wait for the last call to be debounced and run only this one.
Here is the function:
def debounce(wait_time: float):
"""
Decorator that will debounce a function so that it is called after wait_time seconds
If it is called multiple times, will wait for the last call to be debounced and run only this one.
"""
def decorator(function):
def debounced(*args, **kwargs):
def call_function():
debounced._timer = None
return function(*args, **kwargs)
# if we already have a call to the function currently waiting to be executed, reset the timer
if debounced._timer is not None:
debounced._timer.cancel()
# after wait_time, call the function provided to the decorator with its arguments
debounced._timer = threading.Timer(wait_time, call_function)
debounced._timer.start()
debounced._timer = None
return debounced
return decorator | Decorator that will debounce a function so that it is called after wait_time seconds If it is called multiple times, will wait for the last call to be debounced and run only this one. |
156,440 | import logging
from dataclasses import Field, dataclass, field, fields
from dataclasses_json import CatchAll, DataClassJsonMixin, Undefined, dataclass_json
from core.config.samplers.sampler_config import SamplerConfig
from .api_settings import APIConfig
from .bot_settings import BotConfig
from .default_settings import (
AITemplateConfig,
ControlNetConfig,
Img2ImgConfig,
InpaintingConfig,
ONNXConfig,
Txt2ImgConfig,
UpscaleConfig,
)
from .flags_settings import FlagsConfig
from .frontend_settings import FrontendConfig
from .interrogator_settings import InterrogatorConfig
logger = logging.getLogger(__name__)
class Configuration(DataClassJsonMixin):
"Main configuration class for the application"
txt2img: Txt2ImgConfig = field(default_factory=Txt2ImgConfig)
img2img: Img2ImgConfig = field(default_factory=Img2ImgConfig)
inpainting: InpaintingConfig = field(default_factory=InpaintingConfig)
controlnet: ControlNetConfig = field(default_factory=ControlNetConfig)
upscale: UpscaleConfig = field(default_factory=UpscaleConfig)
api: APIConfig = field(default_factory=APIConfig)
interrogator: InterrogatorConfig = field(default_factory=InterrogatorConfig)
aitemplate: AITemplateConfig = field(default_factory=AITemplateConfig)
onnx: ONNXConfig = field(default_factory=ONNXConfig)
bot: BotConfig = field(default_factory=BotConfig)
frontend: FrontendConfig = field(default_factory=FrontendConfig)
sampler_config: SamplerConfig = field(default_factory=SamplerConfig)
flags: FlagsConfig = field(default_factory=FlagsConfig)
extra: CatchAll = field(default_factory=dict)
def save_config(config: Configuration):
"Save the configuration to a file"
logger.info("Saving configuration to data/settings.json")
with open("data/settings.json", "w", encoding="utf-8") as f:
f.write(config.to_json(ensure_ascii=False, indent=4))
The provided code snippet includes necessary dependencies for implementing the `load_config` function. Write a Python function `def load_config()` to solve the following problem:
Load the configuration from a file
Here is the function:
def load_config():
"Load the configuration from a file"
logger.info("Loading configuration from data/settings.json")
try:
with open("data/settings.json", "r", encoding="utf-8") as f:
config = Configuration.from_json(f.read())
logger.info("Configuration loaded from data/settings.json")
return config
except FileNotFoundError:
logger.info("data/settings.json not found, creating a new one")
config = Configuration()
save_config(config)
logger.info("Configuration saved to data/settings.json")
return config | Load the configuration from a file |
156,441 | import inspect
from logging import getLogger
from typing import Optional
import k_diffusion
import torch
from core.types import SigmaScheduler
from .types import Denoiser
sampling = k_diffusion.sampling
logger = getLogger(__name__)
SigmaScheduler = Literal["automatic", "karras", "exponential", "polyexponential", "vp"]
Denoiser = Union[CompVisVDenoiser, CompVisDenoiser]
The provided code snippet includes necessary dependencies for implementing the `build_sigmas` function. Write a Python function `def build_sigmas( steps: int, denoiser: Denoiser, discard_next_to_last_sigma: bool = False, scheduler: Optional[SigmaScheduler] = None, custom_rho: Optional[float] = None, custom_sigma_min: Optional[float] = None, custom_sigma_max: Optional[float] = None, ) -> torch.Tensor` to solve the following problem:
Build sigmas (timesteps) from custom values.
Here is the function:
def build_sigmas(
steps: int,
denoiser: Denoiser,
discard_next_to_last_sigma: bool = False,
scheduler: Optional[SigmaScheduler] = None,
custom_rho: Optional[float] = None,
custom_sigma_min: Optional[float] = None,
custom_sigma_max: Optional[float] = None,
) -> torch.Tensor:
"Build sigmas (timesteps) from custom values."
steps += 1 if discard_next_to_last_sigma else 0
if scheduler is None or scheduler == "automatic":
logger.debug("No optional scheduler provided. Using default.")
sigmas = denoiser.get_sigmas(steps)
else:
sigma_min, sigma_max = (denoiser.sigmas[0].item(), denoiser.sigmas[-1].item()) # type: ignore
rho = None
if scheduler == "polyexponential":
rho = 1
elif scheduler == "karras":
rho = 7
sigma_min = custom_sigma_min if custom_sigma_min is not None else sigma_min
sigma_max = custom_sigma_max if custom_sigma_max is not None else sigma_max
rho = custom_rho if custom_rho is not None else rho
arguments = {
"n": steps,
"sigma_min": sigma_min,
"sigma_max": sigma_max,
"rho": rho,
}
sigma_func = getattr(sampling, f"get_sigmas_{scheduler}")
params = inspect.signature(sigma_func).parameters.keys()
for arg, val in arguments.copy().items():
if arg not in params or val is None:
del arguments[arg]
logger.debug(f"Building sigmas with {arguments}")
sigmas = getattr(sampling, f"get_sigmas_{scheduler}")(**arguments)
if discard_next_to_last_sigma:
sigmas = torch.cat([sigmas[:-2], sigmas[-1:]])
return sigmas | Build sigmas (timesteps) from custom values. |
156,442 | import logging
from typing import Callable, Optional, Tuple, Union
import torch
from diffusers.schedulers.scheduling_utils import KarrasDiffusionSchedulers
from core.types import SigmaScheduler
from .adapter.k_adapter import KdiffusionSchedulerAdapter
from .adapter.unipc_adapter import UnipcSchedulerAdapter
from .custom.dpmpp_2m import sample_dpmpp_2mV2
from .custom.restart import restart_sampler
from .custom.heunpp import sample_heunpp2
from .custom.lcm import sample_lcm
from .denoiser import create_denoiser
logger = logging.getLogger(__name__)
def _get_sampler(
sampler: Union[str, KarrasDiffusionSchedulers]
) -> Union[None, Tuple[str, Union[Callable, str], dict]]:
if isinstance(sampler, KarrasDiffusionSchedulers):
sampler = samplers_diffusers.get(sampler, "Euler a") # type: ignore
return next(
(ksampler for ksampler in samplers_kdiffusion if ksampler[0] == sampler), None
)
SigmaScheduler = Literal["automatic", "karras", "exponential", "polyexponential", "vp"]
class KdiffusionSchedulerAdapter:
"Somewhat diffusers compatible scheduler-like K-diffusion adapter."
sampler_tuple: Sampler
denoiser: Denoiser
# diffusers compat
config: dict = {"steps_offset": 0, "prediction_type": "epsilon"}
# should really be "sigmas," but for compatibility with diffusers
# it's named timesteps.
timesteps: torch.Tensor # calculated sigmas
scheduler_name: Optional[SigmaScheduler]
alphas_cumprod: torch.Tensor
sigma_range: Tuple[float, float] = (0, 1.0)
sigma_rho: Optional[float] = None
sigma_always_discard_next_to_last: bool = False
sampler_eta: Optional[float] = None
sampler_churn: Optional[float] = None
sampler_trange: Tuple[float, float] = (0, 0)
sampler_noise: Optional[float] = None
steps: int = 50
eta_noise_seed_delta: float = 0
device: torch.device
dtype: torch.dtype
sampler_settings: dict
def __init__(
self,
alphas_cumprod: torch.Tensor,
scheduler_name: Optional[SigmaScheduler],
sampler_tuple: Sampler,
sigma_range: Tuple[float, float],
sigma_rho: float,
sigma_discard: bool,
sampler_eta: float,
sampler_churn: float,
sampler_trange: Tuple[float, float],
sampler_noise: float,
device: torch.device,
dtype: torch.dtype,
sampler_settings: dict,
) -> None:
self.alphas_cumprod = alphas_cumprod.to(device=device)
self.scheduler_name = scheduler_name
self.sampler_tuple = sampler_tuple
self.sigma_range = sigma_range
self.sampler_settings = sampler_settings
if self.sampler_settings:
for key, value in self.sampler_settings.copy().items():
if value is None:
del self.sampler_settings[key]
logger.debug(f"Sampler settings overwrite: {self.sampler_settings}")
self.sampler_eta = sampler_eta
if self.sampler_eta is None:
self.sampler_eta = self.sampler_tuple[2].get("default_eta", None)
self.sampler_churn = sampler_churn
self.sampler_trange = sampler_trange
self.sampler_noise = sampler_noise
self.device = device
self.dtype = dtype
self.sigma_rho = sigma_rho
self.sigma_always_discard_next_to_last = sigma_discard
def set_timesteps(
self,
steps: int,
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
) -> None:
"Initialize timesteps (sigmas) and set steps to correct amount."
self.steps = steps
self.timesteps = build_sigmas(
steps=steps,
denoiser=self.denoiser,
discard_next_to_last_sigma=self.sampler_tuple[2].get(
"discard_next_to_last_sigma", self.sigma_always_discard_next_to_last
),
scheduler=self.scheduler_name,
custom_rho=self.sigma_rho,
custom_sigma_min=self.sigma_range[0],
custom_sigma_max=self.sigma_range[1],
).to(device=device or self.device, dtype=dtype or self.dtype)
def scale_model_input(
self, sample: torch.FloatTensor, timestep: Optional[int] = None
) -> torch.FloatTensor:
"diffusers#scale_model_input"
return sample
def init_noise_sigma(self) -> torch.Tensor:
"diffusers#init_noise_sigma"
# SGM / ODE doesn't necessarily produce "better" images, it's here for feature parity with both A1111 and SGM.
return (
torch.sqrt(1.0 + self.timesteps[0] ** 2.0)
if config.api.sgm_noise_multiplier
else self.timesteps[0]
)
def do_inference(
self,
x: torch.Tensor,
call: Callable,
apply_model: Callable[
[
torch.Tensor,
torch.IntTensor,
Callable[..., torch.Tensor],
Callable[[Callable], None],
],
torch.Tensor,
],
generator: Union[PhiloxGenerator, torch.Generator],
callback,
callback_steps,
) -> torch.Tensor:
"Run inference function provided with denoiser."
def change_source(src):
self.denoiser.inner_model.callable = src
apply_model = functools.partial(apply_model, call=self.denoiser, change_source=change_source) # type: ignore
change_source(call)
def callback_func(data):
if callback is not None and data["i"] % callback_steps == 0:
callback(data["i"], data["sigma"], data["x"])
def create_noise_sampler():
if self.sampler_tuple[2].get("brownian_noise", False):
return k_diffusion.sampling.BrownianTreeNoiseSampler(
x,
self.timesteps[self.timesteps > 0].min(),
self.timesteps.max(),
)
def noiser(sigma=None, sigma_next=None):
from core.inference.utilities import randn_like
return randn_like(x, generator, device=x.device, dtype=x.dtype)
return noiser
sampler_args = {
"n": self.steps,
"model": apply_model,
"x": x,
"callback": callback_func,
"sigmas": self.timesteps,
"sigma_min": self.denoiser.sigmas[0].item(), # type: ignore
"sigma_max": self.denoiser.sigmas[-1].item(), # type: ignore
"noise_sampler": create_noise_sampler(),
"eta": self.sampler_eta,
"s_churn": self.sampler_churn,
"s_tmin": self.sampler_trange[0],
"s_tmax": self.sampler_trange[1],
"s_noise": self.sampler_noise,
"order": 2 if self.sampler_tuple[2].get("second_order", False) else None,
**self.sampler_settings,
}
k_diffusion.sampling.torch = TorchHijack(generator)
if isinstance(self.sampler_tuple[1], str):
sampler_func = getattr(sampling, self.sampler_tuple[1])
else:
sampler_func = self.sampler_tuple[1]
parameters = inspect.signature(sampler_func).parameters.keys()
for key, value in sampler_args.copy().items():
if key not in parameters or value is None:
del sampler_args[key]
return sampler_func(**sampler_args)
def add_noise(
self,
original_samples: torch.FloatTensor,
noise: torch.FloatTensor,
timesteps: torch.Tensor,
) -> torch.Tensor:
"diffusers#add_noise"
return original_samples + (noise * self.init_noise_sigma).to(
original_samples.device, original_samples.dtype
)
class UnipcSchedulerAdapter(KdiffusionSchedulerAdapter):
scheduler: NoiseScheduleVP
skip_type: SkipType
model_type: ModelType
variant: Variant
method: Method
order: int
lower_order_final: bool
timesteps: torch.Tensor
steps: int
def __init__(
self,
alphas_cumprod: torch.Tensor,
device: torch.device,
dtype: torch.dtype,
skip_type: SkipType = "time_uniform",
model_type: ModelType = "noise",
variant: Variant = "bh1",
method: Method = "multistep",
order: int = 3,
lower_order_final: bool = True,
) -> None:
super().__init__(
alphas_cumprod,
"karras",
("", "", {}),
(0, 0),
0,
False,
0,
0,
(0, 0),
0,
device,
dtype,
sampler_settings={},
)
self.skip_type = skip_type
self.model_type = model_type
self.variant = variant
self.method = method
self.order = order
self.lower_order_final = lower_order_final
self.scheduler = NoiseScheduleVP("discrete", alphas_cumprod=alphas_cumprod)
def set_timesteps(
self,
steps: int,
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
) -> None:
self.steps = steps
def get_time_steps(skip_type, t_T, t_0, N, device):
"""Compute the intermediate time steps for sampling."""
if skip_type == "logSNR":
lambda_T = self.scheduler.marginal_lambda(torch.tensor(t_T).to(device))
lambda_0 = self.scheduler.marginal_lambda(torch.tensor(t_0).to(device))
logSNR_steps = torch.linspace(
lambda_T.cpu().item(), lambda_0.cpu().item(), N + 1
).to(device)
return self.scheduler.inverse_lambda(logSNR_steps)
elif skip_type == "time_uniform":
return torch.linspace(t_T, t_0, N + 1).to(device)
elif skip_type == "time_quadratic":
t_order = 2
t = (
torch.linspace(
t_T ** (1.0 / t_order), t_0 ** (1.0 / t_order), N + 1
)
.pow(t_order)
.to(device)
)
return t
else:
raise ValueError(
f"Unsupported skip_type {skip_type}, need to be 'logSNR' or 'time_uniform' or 'time_quadratic'"
)
t_0 = 1.0 / self.scheduler.total_N
t_T = self.scheduler.T
self.timesteps = get_time_steps(
skip_type=self.skip_type,
t_T=t_T,
t_0=t_0,
N=self.steps,
device=device or self.device,
)
def do_inference(
self,
x,
call: Callable[..., Any], # type: ignore
apply_model: Callable[..., torch.Tensor],
generator: Union[PhiloxGenerator, torch.Generator],
callback,
callback_steps,
optional_device: Optional[torch.device] = None,
optional_dtype: Optional[torch.dtype] = None,
) -> torch.Tensor:
device = optional_device or call.device
dtype = optional_dtype or call.dtype
unet_or_controlnet = call
def noise_pred_fn(x, t_continuous, cond=None, **model_kwargs):
# Was originally get_model_input_time(t_continous)
# but "schedule" is ALWAYS "discrete," so we can skip it :)
t_input = (t_continuous - 1.0 / self.scheduler.total_N) * 1000
if cond is None:
output = unet_or_controlnet(
x.to(device=device, dtype=dtype),
t_input.to(device=device, dtype=dtype),
return_dict=False,
**model_kwargs,
)
if isinstance(unet_or_controlnet, UNet2DConditionModel):
output = output[0]
else:
output = unet_or_controlnet(
x.to(device=device, dtype=dtype),
t_input.to(device=device, dtype=dtype),
encoder_hidden_states=cond,
return_dict=False,
**model_kwargs,
)
if isinstance(unet_or_controlnet, UNet2DConditionModel):
output = output[0]
return output
def change_source(src):
nonlocal unet_or_controlnet
unet_or_controlnet = src
apply_model = functools.partial(
apply_model, call=noise_pred_fn, change_source=change_source
)
# predict_x0=True -> algorithm_type="data_prediction"
# predict_x0=False -> algorithm_type="noise_prediction"
uni_pc = UniPC(
model_fn=apply_model,
noise_schedule=self.scheduler,
algorithm_type="data_prediction",
variant=self.variant,
)
ret: torch.Tensor = uni_pc.sample( # type: ignore
x,
timesteps=self.timesteps,
steps=self.steps,
method=self.method,
order=self.order,
lower_order_final=self.lower_order_final,
callback=callback,
callback_steps=callback_steps,
)
return ret.to(dtype=self.dtype, device=self.device)
def create_denoiser(
alphas_cumprod: torch.Tensor,
prediction_type: str,
device: torch.device = torch.device("cuda"),
dtype: torch.dtype = torch.float16,
denoiser_enable_quantization: bool = False,
) -> Denoiser:
"Create a denoiser based on the provided prediction_type"
model = _ModelWrapper(alphas_cumprod)
model.alphas_cumprod = alphas_cumprod
if prediction_type == "v_prediction":
denoiser = CompVisVDenoiser(model, quantize=denoiser_enable_quantization)
else:
denoiser = CompVisDenoiser(model, quantize=denoiser_enable_quantization)
denoiser.sigmas = denoiser.sigmas.to(device, dtype)
denoiser.log_sigmas = denoiser.log_sigmas.to(device, dtype)
return denoiser
The provided code snippet includes necessary dependencies for implementing the `create_sampler` function. Write a Python function `def create_sampler( alphas_cumprod: torch.Tensor, sampler: Union[str, KarrasDiffusionSchedulers], device: torch.device, dtype: torch.dtype, eta_noise_seed_delta: Optional[float] = None, denoiser_enable_quantization: bool = False, sigma_type: SigmaScheduler = "automatic", sigma_use_old_karras_scheduler: bool = False, sigma_always_discard_next_to_last: bool = False, sigma_rho: Optional[float] = None, sigma_min: Optional[float] = None, sigma_max: Optional[float] = None, sampler_eta: Optional[float] = None, sampler_churn: Optional[float] = None, sampler_tmin: Optional[float] = None, sampler_tmax: Optional[float] = None, sampler_noise: Optional[float] = None, sampler_settings: Optional[dict] = None, )` to solve the following problem:
Helper function for figuring out and creating a KdiffusionSchedulerAdapter for the appropriate settings given.
Here is the function:
def create_sampler(
alphas_cumprod: torch.Tensor,
sampler: Union[str, KarrasDiffusionSchedulers],
device: torch.device,
dtype: torch.dtype,
eta_noise_seed_delta: Optional[float] = None,
denoiser_enable_quantization: bool = False,
sigma_type: SigmaScheduler = "automatic",
sigma_use_old_karras_scheduler: bool = False,
sigma_always_discard_next_to_last: bool = False,
sigma_rho: Optional[float] = None,
sigma_min: Optional[float] = None,
sigma_max: Optional[float] = None,
sampler_eta: Optional[float] = None,
sampler_churn: Optional[float] = None,
sampler_tmin: Optional[float] = None,
sampler_tmax: Optional[float] = None,
sampler_noise: Optional[float] = None,
sampler_settings: Optional[dict] = None,
):
"Helper function for figuring out and creating a KdiffusionSchedulerAdapter for the appropriate settings given."
sampler_tuple = _get_sampler(sampler)
sampler_settings = sampler_settings or {}
sigma_min = sampler_settings.pop("sigma_min", sigma_min)
sigma_max = sampler_settings.pop("sigma_max", sigma_max)
sigma_rho = sampler_settings.pop("sigma_rho", sigma_rho)
sigma_always_discard_next_to_last = sampler_settings.pop(
"sigma_discard", sigma_always_discard_next_to_last
)
sampler_tmin = sampler_settings.pop("sampler_tmin", sampler_tmin)
sampler_tmax = sampler_settings.pop("sampler_tmax", sampler_tmax)
sampler_noise = sampler_settings.pop("sampler_noise", sampler_noise)
if sampler_tuple is None:
raise ValueError("sampler_tuple is invalid")
if sampler_tuple[1] == "unipc":
adapter = UnipcSchedulerAdapter(
alphas_cumprod=alphas_cumprod,
device=device,
dtype=dtype,
**sampler_tuple[2],
)
else:
scheduler_name = sampler_tuple[2].get("scheduler", sigma_type)
if scheduler_name == "karras" and sigma_use_old_karras_scheduler:
sigma_min = 0.1
sigma_max = 10
prediction_type = sampler_tuple[2].get("prediction_type", "epsilon")
logger.debug(f"Selected scheduler: {sampler_tuple[0]}-{prediction_type}")
adapter = KdiffusionSchedulerAdapter(
alphas_cumprod=alphas_cumprod,
scheduler_name=scheduler_name,
sampler_tuple=sampler_tuple,
sigma_range=(sigma_min, sigma_max), # type: ignore
sigma_rho=sigma_rho, # type: ignore
sigma_discard=sigma_always_discard_next_to_last,
sampler_churn=sampler_churn, # type: ignore
sampler_eta=sampler_eta, # type: ignore
sampler_noise=sampler_noise, # type: ignore
sampler_trange=(sampler_tmin, sampler_tmax), # type: ignore
device=device,
dtype=dtype,
sampler_settings=sampler_settings,
)
adapter.eta_noise_seed_delta = eta_noise_seed_delta or 0
adapter.denoiser = create_denoiser(
alphas_cumprod=alphas_cumprod,
prediction_type=prediction_type,
denoiser_enable_quantization=denoiser_enable_quantization,
device=device,
dtype=dtype,
)
return adapter | Helper function for figuring out and creating a KdiffusionSchedulerAdapter for the appropriate settings given. |
156,443 | import math
from typing import List, Optional, Tuple, Union, Callable
import numpy as np
import torch
from diffusers.configuration_utils import ConfigMixin, register_to_config
from diffusers.utils.torch_utils import randn_tensor
from diffusers.schedulers.scheduling_utils import (
KarrasDiffusionSchedulers,
SchedulerMixin,
SchedulerOutput,
)
The provided code snippet includes necessary dependencies for implementing the `betas_for_alpha_bar` function. Write a Python function `def betas_for_alpha_bar( num_diffusion_timesteps, max_beta=0.999, alpha_transform_type="cosine", )` to solve the following problem:
Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of (1-beta) over time from t = [0,1]. Contains a function alpha_bar that takes an argument t and transforms it to the cumulative product of (1-beta) up to that part of the diffusion process. Args: num_diffusion_timesteps (`int`): the number of betas to produce. max_beta (`float`): the maximum beta to use; use values lower than 1 to prevent singularities. alpha_transform_type (`str`, *optional*, default to `cosine`): the type of noise schedule for alpha_bar. Choose from `cosine` or `exp` Returns: betas (`np.ndarray`): the betas used by the scheduler to step the model outputs
Here is the function:
def betas_for_alpha_bar(
num_diffusion_timesteps,
max_beta=0.999,
alpha_transform_type="cosine",
):
"""
Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of
(1-beta) over time from t = [0,1].
Contains a function alpha_bar that takes an argument t and transforms it to the cumulative product of (1-beta) up
to that part of the diffusion process.
Args:
num_diffusion_timesteps (`int`): the number of betas to produce.
max_beta (`float`): the maximum beta to use; use values lower than 1 to
prevent singularities.
alpha_transform_type (`str`, *optional*, default to `cosine`): the type of noise schedule for alpha_bar.
Choose from `cosine` or `exp`
Returns:
betas (`np.ndarray`): the betas used by the scheduler to step the model outputs
"""
if alpha_transform_type == "cosine":
def alpha_bar_fn(t):
return math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2
elif alpha_transform_type == "exp":
def alpha_bar_fn(t):
return math.exp(t * -12.0)
else:
raise ValueError(f"Unsupported alpha_tranform_type: {alpha_transform_type}")
betas = []
for i in range(num_diffusion_timesteps):
t1 = i / num_diffusion_timesteps
t2 = (i + 1) / num_diffusion_timesteps
betas.append(min(1 - alpha_bar_fn(t2) / alpha_bar_fn(t1), max_beta))
return torch.tensor(betas, dtype=torch.float32) | Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of (1-beta) over time from t = [0,1]. Contains a function alpha_bar that takes an argument t and transforms it to the cumulative product of (1-beta) up to that part of the diffusion process. Args: num_diffusion_timesteps (`int`): the number of betas to produce. max_beta (`float`): the maximum beta to use; use values lower than 1 to prevent singularities. alpha_transform_type (`str`, *optional*, default to `cosine`): the type of noise schedule for alpha_bar. Choose from `cosine` or `exp` Returns: betas (`np.ndarray`): the betas used by the scheduler to step the model outputs |
156,444 | import torch
from tqdm import trange
from k_diffusion.sampling import to_d
The provided code snippet includes necessary dependencies for implementing the `sample_heunpp2` function. Write a Python function `def sample_heunpp2( model, x, sigmas, extra_args=None, callback=None, disable=None, s_churn=0.0, s_tmin=0.0, s_tmax=float("inf"), s_noise=1.0, )` to solve the following problem:
Implements Algorithm 2 (Heun steps) from Karras et al. (2022).
Here is the function:
def sample_heunpp2(
model,
x,
sigmas,
extra_args=None,
callback=None,
disable=None,
s_churn=0.0,
s_tmin=0.0,
s_tmax=float("inf"),
s_noise=1.0,
):
"""Implements Algorithm 2 (Heun steps) from Karras et al. (2022)."""
# https://github.com/Carzit/sd-webui-samplers-scheduler-for-v1.6/blob/main/scripts/ksampler.py#L356
extra_args = {} if extra_args is None else extra_args
s_in = x.new_ones([x.shape[0]])
s_end = sigmas[-1]
for i in trange(len(sigmas) - 1, disable=disable):
gamma = (
min(s_churn / (len(sigmas) - 1), 2**0.5 - 1)
if s_tmin <= sigmas[i] <= s_tmax
else 0.0
)
eps = torch.randn_like(x) * s_noise
sigma_hat = sigmas[i] * (gamma + 1)
if gamma > 0:
x = x + eps * (sigma_hat**2 - sigmas[i] ** 2) ** 0.5
denoised = model(x, sigma_hat * s_in, **extra_args)
d = to_d(x, sigma_hat, denoised)
if callback is not None:
callback(
{
"x": x,
"i": i,
"sigma": sigmas[i],
"sigma_hat": sigma_hat,
"denoised": denoised,
}
)
dt = sigmas[i + 1] - sigma_hat
if sigmas[i + 1] == s_end:
# Euler method
x = x + d * dt
elif sigmas[i + 2] == s_end:
# Heun's method
x_2 = x + d * dt
denoised_2 = model(x_2, sigmas[i + 1] * s_in, **extra_args)
d_2 = to_d(x_2, sigmas[i + 1], denoised_2)
w = 2 * sigmas[0]
w2 = sigmas[i + 1] / w
w1 = 1 - w2
d_prime = d * w1 + d_2 * w2
x = x + d_prime * dt
else:
# Heun++
x_2 = x + d * dt
denoised_2 = model(x_2, sigmas[i + 1] * s_in, **extra_args)
d_2 = to_d(x_2, sigmas[i + 1], denoised_2)
dt_2 = sigmas[i + 2] - sigmas[i + 1]
x_3 = x_2 + d_2 * dt_2
denoised_3 = model(x_3, sigmas[i + 2] * s_in, **extra_args)
d_3 = to_d(x_3, sigmas[i + 2], denoised_3)
w = 3 * sigmas[0]
w2 = sigmas[i + 1] / w
w3 = sigmas[i + 2] / w
w1 = 1 - w2 - w3
d_prime = w1 * d + w2 * d_2 + w3 * d_3
x = x + d_prime * dt
return x | Implements Algorithm 2 (Heun steps) from Karras et al. (2022). |
156,445 | import torch
from tqdm import trange
The provided code snippet includes necessary dependencies for implementing the `sample_dpmpp_2mV2` function. Write a Python function `def sample_dpmpp_2mV2(model, x, sigmas, extra_args=None, callback=None, disable=None)` to solve the following problem:
DPM-Solver++(2M) V2.
Here is the function:
def sample_dpmpp_2mV2(model, x, sigmas, extra_args=None, callback=None, disable=None):
"""DPM-Solver++(2M) V2."""
extra_args = {} if extra_args is None else extra_args
s_in: torch.Tensor = x.new_ones([x.shape[0]])
sigma_fn = lambda t: t.neg().exp()
t_fn = lambda sigma: sigma.log().neg()
old_denoised = None
for i in trange(len(sigmas) - 1, disable=disable):
print(sigmas[i].item(), s_in.item(), (sigmas[i] * s_in).item())
denoised = model(x, sigmas[i] * s_in, **extra_args)
if callback is not None:
callback(
{
"x": x,
"i": i,
"sigma": sigmas[i],
"sigma_hat": sigmas[i],
"denoised": denoised,
}
)
t, t_next = t_fn(sigmas[i]), t_fn(sigmas[i + 1])
h = t_next - t
if old_denoised is None or sigmas[i + 1] == 0:
x = (sigma_fn(t_next) / sigma_fn(t)) * x - (-h).expm1() * denoised
else:
h_last = t - t_fn(sigmas[i - 1])
r = h_last / h
denoised_d = (1 + 1 / (2 * r)) * denoised - (1 / (2 * r)) * old_denoised
x = (sigma_fn(t_next) / sigma_fn(t)) * x - (-h).expm1() * denoised_d
sigma_progress = i / len(sigmas)
adjustment_factor = 1 + (0.15 * (sigma_progress * sigma_progress))
old_denoised = denoised * adjustment_factor
return x | DPM-Solver++(2M) V2. |
156,446 | import k_diffusion.sampling
import torch
import tqdm
The provided code snippet includes necessary dependencies for implementing the `restart_sampler` function. Write a Python function `def restart_sampler( model, x, sigmas, extra_args=None, callback=None, disable=None, s_noise=1.0, restart_list=None, )` to solve the following problem:
Implements restart sampling in Restart Sampling for Improving Generative Processes (2023) Restart_list format: {min_sigma: [ restart_steps, restart_times, max_sigma]} If restart_list is None: will choose restart_list automatically, otherwise will use the given restart_list
Here is the function:
def restart_sampler(
model,
x,
sigmas,
extra_args=None,
callback=None,
disable=None,
s_noise=1.0,
restart_list=None,
):
"""Implements restart sampling in Restart Sampling for Improving Generative Processes (2023)
Restart_list format: {min_sigma: [ restart_steps, restart_times, max_sigma]}
If restart_list is None: will choose restart_list automatically, otherwise will use the given restart_list
"""
og_dev = x.device
og_d = x.dtype
extra_args = {} if extra_args is None else extra_args
s_in = x.new_ones([x.shape[0]])
step_id = 0
from k_diffusion.sampling import get_sigmas_karras, to_d
def heun_step(x, old_sigma, new_sigma, second_order=True):
nonlocal step_id
denoised = model(x.to(og_d), (old_sigma * s_in).to(og_d), **extra_args)
d = to_d(x, old_sigma, denoised)
if callback is not None:
callback(
{
"x": x,
"i": step_id,
"sigma": new_sigma,
"sigma_hat": old_sigma,
"denoised": denoised,
}
)
dt = new_sigma - old_sigma
if new_sigma == 0 or not second_order:
# Euler method
x = x + d * dt
else:
# Heun's method
x_2 = x + d * dt
denoised_2 = model(x_2.to(og_d), (new_sigma * s_in).to(og_d), **extra_args)
d_2 = to_d(x_2, new_sigma, denoised_2)
d_prime = (d + d_2) / 2
x = x + d_prime * dt
step_id += 1
return x
steps = sigmas.shape[0] - 1
if restart_list is None:
if steps >= 20:
restart_steps = 9
restart_times = 1
if steps >= 36:
restart_steps = steps // 4
restart_times = 2
sigmas = get_sigmas_karras(
steps - restart_steps * restart_times,
sigmas[-2].item(),
sigmas[0].item(),
device=sigmas.device,
)
restart_list = {0.1: [restart_steps + 1, restart_times, 2]}
else:
restart_list = {}
restart_list = {
int(torch.argmin(abs(sigmas - key), dim=0)): value
for key, value in restart_list.items()
}
step_list = []
for i in range(len(sigmas) - 1):
step_list.append((sigmas[i], sigmas[i + 1]))
if i + 1 in restart_list:
restart_steps, restart_times, restart_max = restart_list[i + 1]
min_idx = i + 1
max_idx = int(torch.argmin(abs(sigmas - restart_max), dim=0))
if max_idx < min_idx:
sigma_restart = get_sigmas_karras(
restart_steps,
sigmas[min_idx].item(),
sigmas[max_idx].item(),
device=sigmas.device, # type: ignore
)[:-1]
while restart_times > 0:
restart_times -= 1
step_list.extend(
[
(old_sigma, new_sigma)
for (old_sigma, new_sigma) in zip(
sigma_restart[:-1], sigma_restart[1:]
)
]
)
last_sigma = None
for old_sigma, new_sigma in tqdm.tqdm(step_list, disable=disable):
if last_sigma is None:
last_sigma = old_sigma
elif last_sigma < old_sigma:
x = (
x
+ k_diffusion.sampling.torch.randn_like(x)
* s_noise
* (old_sigma**2 - last_sigma**2) ** 0.5
)
x = heun_step(x, old_sigma, new_sigma)
last_sigma = new_sigma
return x.to(dtype=og_d, device=og_dev) | Implements restart sampling in Restart Sampling for Improving Generative Processes (2023) Restart_list format: {min_sigma: [ restart_steps, restart_times, max_sigma]} If restart_list is None: will choose restart_list automatically, otherwise will use the given restart_list |
156,447 | from k_diffusion.sampling import default_noise_sampler
import torch
from tqdm import trange
def sample_lcm(
model,
x: torch.Tensor,
sigmas,
extra_args=None,
callback=None,
disable=None,
noise_sampler=None,
):
extra_args = {} if extra_args is None else extra_args
noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler
s_in = x.new_ones([x.shape[0]])
for i in trange(len(sigmas) - 1, disable=disable):
denoised = model(x, sigmas[i] * s_in, **extra_args)
if callback is not None:
callback(
{
"x": x,
"i": i,
"sigma": sigmas[i],
"sigma_hat": sigmas[i],
"denoised": denoised,
}
)
x = denoised
if sigmas[i + 1] > 0:
x += sigmas[i + 1] * noise_sampler(sigmas[i], sigmas[i + 1])
return x | null |
156,448 | import torch
The provided code snippet includes necessary dependencies for implementing the `interpolate_fn` function. Write a Python function `def interpolate_fn(x, xp, yp)` to solve the following problem:
A piecewise linear function y = f(x), using xp and yp as keypoints. We implement f(x) in a differentiable way (i.e. applicable for autograd). The function f(x) is well-defined for all x-axis. (For x beyond the bounds of xp, we use the outmost points of xp to define the linear function.) Args: x: PyTorch tensor with shape [N, C], where N is the batch size, C is the number of channels (we use C = 1 for DPM-Solver). xp: PyTorch tensor with shape [C, K], where K is the number of keypoints. yp: PyTorch tensor with shape [C, K]. Returns: The function values f(x), with shape [N, C].
Here is the function:
def interpolate_fn(x, xp, yp):
"""
A piecewise linear function y = f(x), using xp and yp as keypoints.
We implement f(x) in a differentiable way (i.e. applicable for autograd).
The function f(x) is well-defined for all x-axis. (For x beyond the bounds of xp, we use the outmost points of xp to define the linear function.)
Args:
x: PyTorch tensor with shape [N, C], where N is the batch size, C is the number of channels (we use C = 1 for DPM-Solver).
xp: PyTorch tensor with shape [C, K], where K is the number of keypoints.
yp: PyTorch tensor with shape [C, K].
Returns:
The function values f(x), with shape [N, C].
"""
N, K = x.shape[0], xp.shape[1]
all_x = torch.cat([x.unsqueeze(2), xp.unsqueeze(0).repeat((N, 1, 1))], dim=2)
sorted_all_x, x_indices = torch.sort(all_x, dim=2)
x_idx = torch.argmin(x_indices, dim=2)
cand_start_idx = x_idx - 1
start_idx = torch.where(
torch.eq(x_idx, 0),
torch.tensor(1, device=x.device),
torch.where(
torch.eq(x_idx, K),
torch.tensor(K - 2, device=x.device),
cand_start_idx,
),
)
end_idx = torch.where(
torch.eq(start_idx, cand_start_idx), start_idx + 2, start_idx + 1
)
start_x = torch.gather(sorted_all_x, dim=2, index=start_idx.unsqueeze(2)).squeeze(2)
end_x = torch.gather(sorted_all_x, dim=2, index=end_idx.unsqueeze(2)).squeeze(2)
start_idx2 = torch.where(
torch.eq(x_idx, 0),
torch.tensor(0, device=x.device),
torch.where(
torch.eq(x_idx, K),
torch.tensor(K - 2, device=x.device),
cand_start_idx,
),
)
y_positions_expanded = yp.unsqueeze(0).expand(N, -1, -1)
start_y = torch.gather(
y_positions_expanded, dim=2, index=start_idx2.unsqueeze(2)
).squeeze(2)
end_y = torch.gather(
y_positions_expanded, dim=2, index=(start_idx2 + 1).unsqueeze(2)
).squeeze(2)
cand = start_y + (x - start_x) * (end_y - start_y) / (end_x - start_x)
return cand | A piecewise linear function y = f(x), using xp and yp as keypoints. We implement f(x) in a differentiable way (i.e. applicable for autograd). The function f(x) is well-defined for all x-axis. (For x beyond the bounds of xp, we use the outmost points of xp to define the linear function.) Args: x: PyTorch tensor with shape [N, C], where N is the batch size, C is the number of channels (we use C = 1 for DPM-Solver). xp: PyTorch tensor with shape [C, K], where K is the number of keypoints. yp: PyTorch tensor with shape [C, K]. Returns: The function values f(x), with shape [N, C]. |
156,449 | import torch
The provided code snippet includes necessary dependencies for implementing the `expand_dims` function. Write a Python function `def expand_dims(v, dims)` to solve the following problem:
Expand the tensor `v` to the dim `dims`. Args: `v`: a PyTorch tensor with shape [N]. `dim`: a `int`. Returns: a PyTorch tensor with shape [N, 1, 1, ..., 1] and the total dimension is `dims`.
Here is the function:
def expand_dims(v, dims):
"""
Expand the tensor `v` to the dim `dims`.
Args:
`v`: a PyTorch tensor with shape [N].
`dim`: a `int`.
Returns:
a PyTorch tensor with shape [N, 1, 1, ..., 1] and the total dimension is `dims`.
"""
return v[(...,) + (None,) * (dims - 1)] | Expand the tensor `v` to the dim `dims`. Args: `v`: a PyTorch tensor with shape [N]. `dim`: a `int`. Returns: a PyTorch tensor with shape [N, 1, 1, ..., 1] and the total dimension is `dims`. |
156,450 | from typing_extensions import TYPE_CHECKING
from importlib.util import find_spec
from core.config import config as conf
def create_config() -> "CompilationConfig.Default":
from sfast.compilers.stable_diffusion_pipeline_compiler import CompilationConfig
config = CompilationConfig.Default()
config.enable_xformers = (
conf.api.sfast_xformers and find_spec("xformers") is not None
)
config.enable_triton = conf.api.sfast_triton and find_spec("triton") is not None
config.enable_cuda_graph = conf.api.sfast_cuda_graph
return config
def compile(model):
if conf.api.sfast_compile:
if hasattr(model, "sfast_compiled"):
return model
import sfast.jit.trace_helper
from sfast.compilers.stable_diffusion_pipeline_compiler import compile as comp
# stable-fast hijack since it seems to be break cuda graphs for now.
# functionality-wise should be the same, except that it skips UNet2DConditionalOutput
class BetterDictToDataClassConverter:
def __init__(self, clz):
self.clz = clz
def __call__(self, d):
try:
return self.clz(**d)
except TypeError:
return d
sfast.jit.trace_helper.DictToDataClassConverter = BetterDictToDataClassConverter
r = comp(model, create_config())
setattr(r, "sfast_compiled", True)
return r
return model | null |
156,451 | import contextlib
import importlib
from typing import Any, Optional
import torch
from core.config import config
def autocast(
dtype: torch.dtype,
disable: bool = False,
):
"Context manager to autocast tensors to desired dtype for all supported backends"
global _initialized_directml
if disable:
return contextlib.nullcontext()
if "privateuseone" in config.api.device:
if not _initialized_directml:
for p in _patch_list:
_patch(p)
_initialized_directml = True
return torch.dml.autocast(dtype=dtype, disable=False) # type: ignore
if "xpu" in config.api.device:
return torch.xpu.amp.autocast(enabled=True, dtype=dtype, cache_enabled=False) # type: ignore
if "cpu" in config.api.device:
return torch.cpu.amp.autocast(enabled=True, dtype=dtype, cache_enabled=False) # type: ignore
return torch.cuda.amp.autocast(enabled=True, dtype=dtype, cache_enabled=False) # type: ignore
class dml:
_autocast_enabled: bool = False
_autocast_dtype: torch.dtype = torch.float16
def set_autocast_enabled(value: bool = True): # type: ignore pylint: disable=no-self-argument
dml._autocast_enabled = value
def is_autocast_enabled() -> bool: # type: ignore pylint: disable=no-method-argument
return dml._autocast_enabled
def set_autocast_dtype(dtype: torch.dtype = torch.float16): # type: ignore pylint: disable=no-self-argument
dml._autocast_dtype = dtype
def get_autocast_dtype() -> torch.dtype: # type: ignore pylint: disable=no-method-argument
return dml._autocast_dtype
class autocast:
def __init__(
self,
dtype: Optional[torch.device] = None,
disable: bool = False,
):
self.prev = self.prev_d = None
self.dtype = dtype or torch.dml.get_autocast_dtype() # type: ignore
self.disable = disable
def __enter__(self):
if not self.disable:
self.prev = torch.dml.is_autocast_enabled() # type: ignore
self.prev_d = torch.dml.get_autocast_dtype() # type: ignore
torch.dml.set_autocast_enabled(True) # type: ignore
torch.dml.set_autocast_dtype(self.dtype) # type: ignore
def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any):
torch.dml.set_autocast_enabled(self.prev or False) # type: ignore
torch.dml.set_autocast_dtype(self.prev_d or torch.dml.get_autocast_dtype()) # type: ignore
torch.dml = dml
config = load_config()
The provided code snippet includes necessary dependencies for implementing the `without_autocast` function. Write a Python function `def without_autocast(disable: bool = False)` to solve the following problem:
Context manager to disable autocast
Here is the function:
def without_autocast(disable: bool = False):
"Context manager to disable autocast"
if disable:
return contextlib.nullcontext()
if "privateuseone" in config.api.device:
return torch.dml.autocast(disable=True) # type: ignore
if "xpu" in config.api.device:
return torch.xpu.amp.autocast(enabled=False, cache_enabled=False) # type: ignore
if "cpu" in config.api.device:
return torch.cpu.amp.autocast(enabled=False, cache_enabled=False) # type: ignore
return torch.cuda.amp.autocast(enabled=False, cache_enabled=False) # type: ignore | Context manager to disable autocast |
156,452 | from typing import Optional
import torch
from diffusers.models.attention_processor import Attention
class FlashAttentionStandardAttention(FlashAttentionBaseAttention):
# TODO: documentation
def do(
self,
attn: Attention,
hidden_states: torch.FloatTensor,
encoder_hidden_states: torch.FloatTensor,
query: Optional[torch.FloatTensor] = None,
) -> torch.FloatTensor:
key = attn.to_k(encoder_hidden_states) # type: ignore
value = attn.to_v(encoder_hidden_states) # type: ignore
query = query.unflatten(-1, (attn.heads, -1)) # type: ignore
key = key.unflatten(-1, (attn.heads, -1))
value = value.unflatten(-1, (attn.heads, -1))
from flash_attn import flash_attn_func
hidden_states = flash_attn_func(
query, key, value, dropout_p=0.0, causal=False # type: ignore
)
return hidden_states.to(query.dtype) # type: ignore
def to_q(
self, attn: Attention, hidden_states: torch.FloatTensor
) -> torch.FloatTensor:
return attn.to_q(hidden_states) # type: ignore
class FlashAttentionQkvAttention(FlashAttentionBaseAttention):
# TODO: documentation
def do(
self,
attn: Attention,
hidden_states: torch.FloatTensor,
encoder_hidden_states: torch.FloatTensor,
query: Optional[torch.FloatTensor] = None,
) -> torch.FloatTensor:
qkv = attn.to_qkv(hidden_states) # type: ignore
qkv = qkv.unflatten(-1, (3, attn.heads, -1))
from flash_attn import flash_attn_qkvpacked_func
hidden_states = flash_attn_qkvpacked_func(qkv, dropout_p=0.0, causal=False)
return hidden_states.to(qkv.dtype) # type: ignore
def apply_flash_attention(module: torch.nn.Module):
cross_attn = FlashAttentionStandardAttention()
self_attn = FlashAttentionQkvAttention()
def set(mod: torch.nn.Module) -> None:
if isinstance(mod, Attention):
if mod.to_k.in_features == mod.to_q.in_features: # type: ignore
mod.to_qkv = torch.nn.Linear(
mod.to_q.in_features,
mod.to_q.out_features * 3,
dtype=mod.to_q.weight.dtype,
device=mod.to_q.weight.data.device,
)
mod.to_qkv.weight.data = torch.cat(
[mod.to_q.weight, mod.to_k.weight, mod.to_v.weight] # type: ignore
).detach()
del mod.to_q, mod.to_k, mod.to_v
mod.set_processor(self_attn) # type: ignore
else:
mod.set_processor(cross_attn) # type: ignore
module.apply(set) | null |
156,453 | from typing import Optional
import torch
from diffusers.models.attention_processor import Attention
def _to_mha(ca: Attention) -> MultiheadAttention:
bias = ca.to_k.bias is not None # type: ignore
assert bias is False
mha = MultiheadAttention(
query_dim=ca.to_q.in_features,
cross_attention_dim=ca.to_k.in_features, # type: ignore
heads=ca.heads,
dim_head=ca.to_q.out_features // ca.heads,
dropout=ca.to_out[1].p, # type: ignore
bias=bias,
)
# is self-attention?
if ca.to_q.in_features == ca.to_k.in_features: # type: ignore
mha.get_parameter("in_proj_weight").data = torch.cat(
[ca.to_q.weight, ca.to_k.weight, ca.to_v.weight] # type: ignore
)
else:
mha.get_parameter("q_proj_weight").data = ca.to_q.weight
mha.get_parameter("k_proj_weight").data = ca.to_k.weight # type: ignore
mha.get_parameter("v_proj_weight").data = ca.to_v.weight # type: ignore
mha.out_proj.weight = ca.to_out[0].weight # type: ignore
mha.out_proj.bias = ca.to_out[0].bias # type: ignore
return mha
The provided code snippet includes necessary dependencies for implementing the `apply_multihead_attention` function. Write a Python function `def apply_multihead_attention(module: torch.nn.Module)` to solve the following problem:
Apply torch.nn.MultiheadAttention as attention processor.
Here is the function:
def apply_multihead_attention(module: torch.nn.Module):
"Apply torch.nn.MultiheadAttention as attention processor."
def mha_attn(module: torch.nn.Module) -> None:
for name, m in module.named_children():
if isinstance(m, Attention):
setattr(module, name, _to_mha(m))
module.apply(mha_attn) | Apply torch.nn.MultiheadAttention as attention processor. |
156,454 | import math
from functools import partial
from typing import List, NamedTuple, Optional, Protocol
import torch
from diffusers.models.attention_processor import Attention
class SubQuadraticCrossAttnProcessor:
"Taken from @Birch-sans fantastic diffusers-play repository."
query_chunk_size: int
kv_chunk_size: Optional[int]
kv_chunk_size_min: Optional[int]
chunk_threshold_bytes: Optional[int]
def __init__(
self,
query_chunk_size=1024,
kv_chunk_size: Optional[int] = None,
kv_chunk_size_min: Optional[int] = None,
chunk_threshold_bytes: Optional[int] = None,
):
r"""
Args:
query_chunk_size (`int`, *optional*, defaults to `1024`)
kv_chunk_size (`int`, *optional*, defaults to `None`): if None, sqrt(key_tokens) is used.
kv_chunk_size_min (`int`, *optional*, defaults to `None`): only considered when `kv_chunk_size is None`. changes `sqrt(key_tokens)` into `max(sqrt(key_tokens), kv_chunk_size_min)`, to ensure our chunk sizes don't get too small (smaller chunks = more chunks = less concurrent work done).
chunk_threshold_bytes (`int`, *optional*, defaults to `None`): if defined: only bother chunking if the self-attn matmul would allocate more bytes than this. whenever we can fit traditional attention into memory: we should prefer to do so, as the unchunked algorithm is faster.
"""
self.query_chunk_size = query_chunk_size
self.kv_chunk_size = kv_chunk_size
self.kv_chunk_size_min = kv_chunk_size_min
self.chunk_threshold_bytes = chunk_threshold_bytes
def __call__(
self,
attn: Attention,
hidden_states: torch.Tensor,
encoder_hidden_states: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
):
encoder_hidden_states = (
hidden_states if encoder_hidden_states is None else encoder_hidden_states
)
assert (
attention_mask is None
), "attention-mask not currently implemented for SubQuadraticCrossAttnProcessor."
# I don't know what test case can be used to determine whether softmax is computed at sufficient bit-width,
# but sub-quadratic attention has a pretty bespoke softmax (defers computation of the denominator) so this needs some thought.
assert (
not attn.upcast_softmax or torch.finfo(hidden_states.dtype).bits >= 32
), "upcast_softmax was requested, but is not implemented"
query = attn.to_q(hidden_states)
key = attn.to_k(encoder_hidden_states) # type: ignore
value = attn.to_v(encoder_hidden_states) # type: ignore
query = query.unflatten(-1, (attn.heads, -1)).transpose(1, 2).flatten(end_dim=1)
key_t = key.transpose(1, 2).unflatten(1, (attn.heads, -1)).flatten(end_dim=1)
del key
value = value.unflatten(-1, (attn.heads, -1)).transpose(1, 2).flatten(end_dim=1)
dtype = query.dtype
bytes_per_token = torch.finfo(query.dtype).bits // 8
batch_x_heads, q_tokens, _ = query.shape
_, _, k_tokens = key_t.shape
qk_matmul_size_bytes = batch_x_heads * bytes_per_token * q_tokens * k_tokens
query_chunk_size = self.query_chunk_size
kv_chunk_size = self.kv_chunk_size
if (
self.chunk_threshold_bytes is not None
and qk_matmul_size_bytes <= self.chunk_threshold_bytes
):
# the big matmul fits into our memory limit; do everything in 1 chunk,
# i.e. send it down the unchunked fast-path
query_chunk_size = q_tokens
kv_chunk_size = k_tokens
hidden_states = efficient_dot_product_attention(
query,
key_t,
value,
query_chunk_size=query_chunk_size,
kv_chunk_size=kv_chunk_size,
kv_chunk_size_min=self.kv_chunk_size_min,
use_checkpoint=attn.training,
)
hidden_states = hidden_states.to(dtype)
hidden_states = (
hidden_states.unflatten(0, (-1, attn.heads))
.transpose(1, 2)
.flatten(start_dim=2)
)
out_proj, dropout = attn.to_out
hidden_states = out_proj(hidden_states)
hidden_states = dropout(hidden_states)
return hidden_states
The provided code snippet includes necessary dependencies for implementing the `apply_subquadratic_attention` function. Write a Python function `def apply_subquadratic_attention( module: torch.nn.Module, query_chunk_size=1024, kv_chunk_size: Optional[int] = None, kv_chunk_size_min: Optional[int] = None, chunk_threshold_bytes: Optional[int] = None, )` to solve the following problem:
Applies subquadratic attention to all the cross-attention modules of the provided module.
Here is the function:
def apply_subquadratic_attention(
module: torch.nn.Module,
query_chunk_size=1024,
kv_chunk_size: Optional[int] = None,
kv_chunk_size_min: Optional[int] = None,
chunk_threshold_bytes: Optional[int] = None,
):
"Applies subquadratic attention to all the cross-attention modules of the provided module."
def subquad_attn(module: torch.nn.Module) -> None:
for m in module.children():
if isinstance(m, Attention):
processor = SubQuadraticCrossAttnProcessor(
query_chunk_size=query_chunk_size,
kv_chunk_size=kv_chunk_size,
kv_chunk_size_min=kv_chunk_size_min,
chunk_threshold_bytes=chunk_threshold_bytes,
)
m.set_processor(processor) # type: ignore
module.apply(subquad_attn) | Applies subquadratic attention to all the cross-attention modules of the provided module. |
156,455 | import math
from functools import partial
from typing import List, NamedTuple, Optional, Protocol
import torch
from diffusers.models.attention_processor import Attention
class SummarizeChunk(Protocol):
def __call__(
query: torch.Tensor,
key_t: torch.Tensor,
value: torch.Tensor,
) -> AttnChunk:
...
class ComputeQueryChunkAttn(Protocol):
def __call__(
query: torch.Tensor,
key_t: torch.Tensor,
value: torch.Tensor,
) -> torch.Tensor:
...
def _summarize_chunk(
query: torch.Tensor,
key_t: torch.Tensor,
value: torch.Tensor,
scale: float,
) -> AttnChunk:
attn_weights = torch.baddbmm(
torch.empty(1, 1, 1, device=query.device, dtype=query.dtype),
query,
key_t,
alpha=scale,
beta=0,
)
max_score, _ = torch.max(attn_weights, -1, keepdim=True)
max_score = max_score.detach()
exp_weights = torch.exp(attn_weights - max_score)
exp_values = torch.bmm(exp_weights, value)
max_score = max_score.squeeze(-1)
return AttnChunk(exp_values, exp_weights.sum(dim=-1), max_score)
def _query_chunk_attention(
query: torch.Tensor,
key_t: torch.Tensor,
value: torch.Tensor,
summarize_chunk: SummarizeChunk,
kv_chunk_size: int,
) -> torch.Tensor:
batch_x_heads, k_channels_per_head, k_tokens = key_t.shape
_, _, v_channels_per_head = value.shape
def chunk_scanner(chunk_idx: int) -> AttnChunk:
key_chunk = _dynamic_slice(
key_t,
(0, 0, chunk_idx), # type: ignore
(batch_x_heads, k_channels_per_head, kv_chunk_size), # type: ignore
)
value_chunk = _dynamic_slice(
value,
(0, chunk_idx, 0), # type: ignore
(batch_x_heads, kv_chunk_size, v_channels_per_head), # type: ignore
)
return summarize_chunk(query, key_chunk, value_chunk)
chunks: List[AttnChunk] = [
chunk_scanner(chunk) for chunk in torch.arange(0, k_tokens, kv_chunk_size) # type: ignore
]
acc_chunk = AttnChunk(*map(torch.stack, zip(*chunks)))
chunk_values, chunk_weights, chunk_max = acc_chunk
global_max, _ = torch.max(chunk_max, 0, keepdim=True)
max_diffs = torch.exp(chunk_max - global_max)
chunk_values *= torch.unsqueeze(max_diffs, -1)
chunk_weights *= max_diffs
all_values = chunk_values.sum(dim=0)
all_weights = torch.unsqueeze(chunk_weights, -1).sum(dim=0)
return all_values / all_weights
def _get_attention_scores_no_kv_chunking(
query: torch.Tensor,
key_t: torch.Tensor,
value: torch.Tensor,
scale: float,
) -> torch.Tensor:
attn_scores = torch.baddbmm(
torch.empty(1, 1, 1, device=query.device, dtype=query.dtype),
query,
key_t,
alpha=scale,
beta=0,
)
attn_probs = attn_scores.softmax(dim=-1)
del attn_scores
hidden_states_slice = torch.bmm(attn_probs, value)
return hidden_states_slice
def _dynamic_slice(
x: torch.Tensor,
starts: List[int],
sizes: List[int],
) -> torch.Tensor:
slicing = [slice(start, start + size) for start, size in zip(starts, sizes)]
return x[slicing]
The provided code snippet includes necessary dependencies for implementing the `efficient_dot_product_attention` function. Write a Python function `def efficient_dot_product_attention( query: torch.Tensor, key_t: torch.Tensor, value: torch.Tensor, query_chunk_size=1024, kv_chunk_size: Optional[int] = None, kv_chunk_size_min: Optional[int] = None, use_checkpoint=True, )` to solve the following problem:
Computes efficient dot-product attention given query, transposed key, and value. This is efficient version of attention presented in https://arxiv.org/abs/2112.05682v2 which comes with O(sqrt(n)) memory requirements. Args: query: queries for calculating attention with shape of `[batch * num_heads, tokens, channels_per_head]`. key_t: keys for calculating attention with shape of `[batch * num_heads, channels_per_head, tokens]`. value: values to be used in attention with shape of `[batch * num_heads, tokens, channels_per_head]`. query_chunk_size: int: query chunks size kv_chunk_size: Optional[int]: key/value chunks size. if None: defaults to sqrt(key_tokens) kv_chunk_size_min: Optional[int]: key/value minimum chunk size. only considered when kv_chunk_size is None. changes `sqrt(key_tokens)` into `max(sqrt(key_tokens), kv_chunk_size_min)`, to ensure our chunk sizes don't get too small (smaller chunks = more chunks = less concurrent work done). use_checkpoint: bool: whether to use checkpointing (recommended True for training, False for inference) Returns: Output of shape `[batch * num_heads, query_tokens, channels_per_head]`.
Here is the function:
def efficient_dot_product_attention(
query: torch.Tensor,
key_t: torch.Tensor,
value: torch.Tensor,
query_chunk_size=1024,
kv_chunk_size: Optional[int] = None,
kv_chunk_size_min: Optional[int] = None,
use_checkpoint=True,
):
"""Computes efficient dot-product attention given query, transposed key, and value.
This is efficient version of attention presented in
https://arxiv.org/abs/2112.05682v2 which comes with O(sqrt(n)) memory requirements.
Args:
query: queries for calculating attention with shape of
`[batch * num_heads, tokens, channels_per_head]`.
key_t: keys for calculating attention with shape of
`[batch * num_heads, channels_per_head, tokens]`.
value: values to be used in attention with shape of
`[batch * num_heads, tokens, channels_per_head]`.
query_chunk_size: int: query chunks size
kv_chunk_size: Optional[int]: key/value chunks size. if None: defaults to sqrt(key_tokens)
kv_chunk_size_min: Optional[int]: key/value minimum chunk size. only considered when kv_chunk_size is None. changes `sqrt(key_tokens)` into `max(sqrt(key_tokens), kv_chunk_size_min)`, to ensure our chunk sizes don't get too small (smaller chunks = more chunks = less concurrent work done).
use_checkpoint: bool: whether to use checkpointing (recommended True for training, False for inference)
Returns:
Output of shape `[batch * num_heads, query_tokens, channels_per_head]`.
"""
batch_x_heads, q_tokens, q_channels_per_head = query.shape
_, _, k_tokens = key_t.shape
scale = q_channels_per_head**-0.5
kv_chunk_size = min(kv_chunk_size or int(math.sqrt(k_tokens)), k_tokens)
if kv_chunk_size_min is not None:
kv_chunk_size = max(kv_chunk_size, kv_chunk_size_min)
def get_query_chunk(chunk_idx: int) -> torch.Tensor:
return _dynamic_slice(
query,
(0, chunk_idx, 0), # type: ignore
(batch_x_heads, min(query_chunk_size, q_tokens), q_channels_per_head), # type: ignore
)
summarize_chunk: SummarizeChunk = partial(_summarize_chunk, scale=scale)
summarize_chunk: SummarizeChunk = (
partial(torch.utils.checkpoint.checkpoint, summarize_chunk) # type: ignore
if use_checkpoint
else summarize_chunk
)
compute_query_chunk_attn: ComputeQueryChunkAttn = (
partial(_get_attention_scores_no_kv_chunking, scale=scale)
if k_tokens <= kv_chunk_size
else (
# fast-path for when there's just 1 key-value chunk per query chunk (this is just sliced attention btw)
partial(
_query_chunk_attention,
kv_chunk_size=kv_chunk_size,
summarize_chunk=summarize_chunk,
)
)
)
if q_tokens <= query_chunk_size:
# fast-path for when there's just 1 query chunk
return compute_query_chunk_attn(
query=query,
key_t=key_t,
value=value,
)
# TODO: maybe we should use torch.empty_like(query) to allocate storage in-advance,
# and pass slices to be mutated, instead of torch.cat()ing the returned slices
res = torch.cat(
[
compute_query_chunk_attn(
query=get_query_chunk(i * query_chunk_size),
key_t=key_t,
value=value,
)
for i in range(math.ceil(q_tokens / query_chunk_size))
],
dim=1,
)
return res | Computes efficient dot-product attention given query, transposed key, and value. This is efficient version of attention presented in https://arxiv.org/abs/2112.05682v2 which comes with O(sqrt(n)) memory requirements. Args: query: queries for calculating attention with shape of `[batch * num_heads, tokens, channels_per_head]`. key_t: keys for calculating attention with shape of `[batch * num_heads, channels_per_head, tokens]`. value: values to be used in attention with shape of `[batch * num_heads, tokens, channels_per_head]`. query_chunk_size: int: query chunks size kv_chunk_size: Optional[int]: key/value chunks size. if None: defaults to sqrt(key_tokens) kv_chunk_size_min: Optional[int]: key/value minimum chunk size. only considered when kv_chunk_size is None. changes `sqrt(key_tokens)` into `max(sqrt(key_tokens), kv_chunk_size_min)`, to ensure our chunk sizes don't get too small (smaller chunks = more chunks = less concurrent work done). use_checkpoint: bool: whether to use checkpointing (recommended True for training, False for inference) Returns: Output of shape `[batch * num_heads, query_tokens, channels_per_head]`. |
156,456 | from contextlib import ExitStack
import torch
from core.config import config
from .autocast_utils import autocast
from .hypertile import is_hypertile_available, hypertile
class InferenceContext(ExitStack):
"""inference context"""
unet: torch.nn.Module
vae: torch.nn.Module
config = load_config()
def autocast(
dtype: torch.dtype,
disable: bool = False,
):
"Context manager to autocast tensors to desired dtype for all supported backends"
global _initialized_directml
if disable:
return contextlib.nullcontext()
if "privateuseone" in config.api.device:
if not _initialized_directml:
for p in _patch_list:
_patch(p)
_initialized_directml = True
return torch.dml.autocast(dtype=dtype, disable=False) # type: ignore
if "xpu" in config.api.device:
return torch.xpu.amp.autocast(enabled=True, dtype=dtype, cache_enabled=False) # type: ignore
if "cpu" in config.api.device:
return torch.cpu.amp.autocast(enabled=True, dtype=dtype, cache_enabled=False) # type: ignore
return torch.cuda.amp.autocast(enabled=True, dtype=dtype, cache_enabled=False) # type: ignore
def is_hypertile_available():
"Checks whether hypertile is available"
return find_spec("hyper_tile") is not None
def hypertile(unet, height: int, width: int) -> ExitStack:
from hyper_tile import split_attention # noqa: F811
s = ExitStack()
s.enter_context(
split_attention(unet, height / width, tile_size=config.api.hypertile_unet_chunk)
)
return s
The provided code snippet includes necessary dependencies for implementing the `inference_context` function. Write a Python function `def inference_context(unet, vae, height, width) -> InferenceContext` to solve the following problem:
Helper function for centralizing context management
Here is the function:
def inference_context(unet, vae, height, width) -> InferenceContext:
"Helper function for centralizing context management"
s = InferenceContext()
s.unet = unet
s.vae = vae
s.enter_context(
autocast(
config.api.load_dtype,
disable=config.api.autocast and not unet.force_autocast,
)
)
if is_hypertile_available() and config.api.hypertile:
s.enter_context(hypertile(unet, height, width))
if config.api.torch_compile:
s.unet = torch.compile( # type: ignore
unet,
fullgraph=config.api.torch_compile_fullgraph,
dynamic=config.api.torch_compile_dynamic,
mode=config.api.torch_compile_mode,
)
return s | Helper function for centralizing context management |
156,457 | import logging
from typing import Optional, Tuple, Union
import torch
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import (
StableDiffusionPipeline,
)
from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl import (
StableDiffusionXLPipeline,
)
from core.config import config
from .attn import set_attention_processor
from .compile.trace_utils import trace_ipex, trace_model
from .dtype import cast
from .offload import set_offload
from .upcast import upcast_vae
logger = logging.getLogger(__name__)
def supports_tf32(device: Optional[torch.device] = None) -> bool:
"Checks if device is post-Ampere."
major, _ = torch.cuda.get_device_capability(device)
return major >= 8
def experimental_check_hardware_scheduling() -> Tuple[int, int, int]:
"When on windows check if user has hardware scheduling turned on"
import sys
if sys.platform != "win32":
return (-1, -1, -1)
import ctypes
from pathlib import Path
hardware_schedule_test = ctypes.WinDLL(
str(Path() / "libs" / "hardware-accel-test.dll")
).HwSchEnabled
hardware_schedule_test.restype = ctypes.POINTER(ctypes.c_int * 3)
return [x for x in hardware_schedule_test().contents] # type: ignore
def is_pytorch_pipe(pipe):
"Checks if the pipe is a pytorch pipe"
return issubclass(pipe.__class__, (DiffusionPipeline))
def optimize_vae(vae):
"Optimize a VAE according to config defined in data/settings.json"
vae = upcast_vae(vae)
if hasattr(vae, "enable_slicing") and config.api.vae_slicing:
vae.enable_slicing()
logger.info("Optimization: Enabled VAE slicing")
if config.api.vae_tiling and hasattr(vae, "enable_tiling"):
vae.enable_tiling()
logger.info("Optimization: Enabled VAE tiling")
return vae
config = load_config()
def set_attention_processor(pipe):
"Set attention processor to the first one available/the one set in the config"
res = False
try:
curr_processor = list(ATTENTION_PROCESSORS.keys()).index(
config.api.attention_processor
)
except ValueError:
curr_processor = 0
attention_processors_list = list(ATTENTION_PROCESSORS.items())
while not res:
res = attention_processors_list[curr_processor][1](pipe)
if res:
logger.info(
f"Optimization: Enabled {attention_processors_list[curr_processor][0]} attention"
)
curr_processor = (curr_processor + 1) % len(attention_processors_list)
def trace_ipex(
model: torch.nn.Module,
dtype: torch.dtype,
device: torch.device,
cpu: dict,
) -> Tuple[torch.nn.Module, bool]:
from core.inference.functions import is_ipex_available
if is_ipex_available():
import intel_extension_for_pytorch as ipex
logger.info("Optimization: Running IPEX optimizations")
if config.api.channels_last:
ipex.enable_auto_channels_last()
else:
ipex.disable_auto_channels_last()
ipex.enable_onednn_fusion(True)
ipex.set_fp32_math_mode(
ipex.FP32MathMode.BF32
if "AMD" not in cpu["VendorId"]
else ipex.FP32MathMode.FP32
)
model = ipex.optimize(
model, # type: ignore
dtype=dtype,
auto_kernel_selection=True,
sample_input=generate_inputs(dtype, device),
concat_linear=True,
graph_mode=True,
)
return model, True
else:
return model, False
def trace_model(
model: torch.nn.Module,
dtype: torch.dtype,
device: torch.device,
iterations: int = 25,
) -> torch.nn.Module:
"Traces the model for inference"
og = model
from functools import partial
if model.forward.__code__.co_argcount > 3:
model.forward = partial(model.forward, return_dict=False)
warmup(model, iterations, dtype, device)
if config.api.channels_last:
model.to(memory_format=torch.channels_last) # type: ignore
logger.debug("Starting trace")
with warnings.catch_warnings():
warnings.simplefilter("ignore")
if "cpu" in config.api.device:
torch.jit.enable_onednn_fusion(True)
model = torch.jit.trace(model, generate_inputs(dtype, device), check_trace=False) # type: ignore
model = torch.jit.freeze(model) # type: ignore
logger.debug("Tracing done")
warmup(model, iterations // 5, dtype, device)
model.in_channels = og.in_channels
model.dtype = og.dtype
model.device = og.device
model.config = og.config
rn = TracedUNet(model)
del og
return rn
def cast(
pipe: Union[StableDiffusionPipeline, StableDiffusionXLPipeline],
device: str,
dtype: torch.dtype,
offload: bool,
):
# Change the order of the channels to be more efficient for the GPU
# DirectML only supports contiguous memory format
# Disable for IPEX as well, they don't like torch's way of setting memory format
if config.api.channels_last:
if "privateuseone" in device:
logger.warn(
"Optimization: Skipping channels_last, since DirectML doesn't support it."
)
else:
if hasattr(pipe, "unet"):
pipe.unet.to(memory_format=torch.channels_last) # type: ignore
if hasattr(pipe, "vae"):
pipe.vae.to(memory_format=torch.channels_last) # type: ignore
logger.info("Optimization: Enabled channels_last memory format")
pipe.unet.force_autocast = dtype in force_autocast
if pipe.unet.force_autocast:
for m in [x.modules() for x in pipe.components.values() if hasattr(x, "modules")]: # type: ignore
if "CLIP" in m.__class__.__name__:
m.to(device=None if offload else device, dtype=config.api.load_dtype)
else:
for module in m:
if any(
[
x
for x in ["Conv", "Linear"] # 'cause LoRACompatibleConv
if x in module.__class__.__name__
]
):
if hasattr(module, "fp16_weight"):
del module.fp16_weight
if config.api.cache_fp16_weight:
module.fp16_weight = module.weight.clone().half()
module.to(device=None if offload else device, dtype=dtype)
else:
module.to(
device=None if offload else device,
dtype=config.api.load_dtype,
)
if not config.api.autocast:
logger.info("Optimization: Forcing autocast on due to float8 weights.")
else:
pipe.to(device=None if offload else device, dtype=dtype)
return pipe
def set_offload(module: torch.nn.Module, device: torch.device):
if config.api.offload == "module":
class_name = module.__class__.__name__
if "CLIP" not in class_name and "Autoencoder" not in class_name:
return cpu_offload(
module, device, offload_buffers=len(module._parameters) > 0
)
setattr(module, "v_offload_device", device)
return module
The provided code snippet includes necessary dependencies for implementing the `optimize_model` function. Write a Python function `def optimize_model( pipe: Union[StableDiffusionPipeline, StableDiffusionXLPipeline], device, is_for_aitemplate: bool = False, ) -> None` to solve the following problem:
Optimize the model for inference.
Here is the function:
def optimize_model(
pipe: Union[StableDiffusionPipeline, StableDiffusionXLPipeline],
device,
is_for_aitemplate: bool = False,
) -> None:
"Optimize the model for inference."
# Tuple[Supported, Enabled by default, Enabled]
hardware_scheduling = experimental_check_hardware_scheduling()
if hardware_scheduling[2] == 1 and not is_for_aitemplate:
logger.warning(
"Hardware accelerated scheduling is turned on! This will have a HUGE negative impact on performance"
)
if hardware_scheduling[1] == 1:
logger.warning(
"You most likely didn't even know this was turned on. Windows 11 enables it by default on NVIDIA devices"
)
logger.warning(
"You can read about this issue on https://github.com/AUTOMATIC1111/stable-diffusion-webui/discussions/3889"
)
logger.warning(
'You can disable it by going inside Graphics Settings → "Default Graphics Settings" and disabling "Hardware-accelerated GPU Scheduling"'
)
offload = (
config.api.offload != "disabled"
and is_pytorch_pipe(pipe)
and not is_for_aitemplate
)
can_offload = (
any(map(lambda x: x not in config.api.device, ["cpu", "vulkan", "mps"]))
and offload
)
pipe = cast(pipe, device, config.api.dtype, can_offload)
if "cuda" in config.api.device and not is_for_aitemplate:
supports_tf = supports_tf32(device)
if config.api.reduced_precision:
if supports_tf:
torch.set_float32_matmul_precision("medium")
logger.info("Optimization: Enabled all reduced precision operations")
else:
logger.warning(
"Optimization: Device capability is not higher than 8.0, skipping most of reduction"
)
logger.info(
"Optimization: Reduced precision operations enabled (fp16 only)"
)
torch.backends.cuda.matmul.allow_tf32 = config.api.reduced_precision and supports_tf # type: ignore
torch.backends.cudnn.allow_tf32 = config.api.reduced_precision and supports_tf # type: ignore
torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction = config.api.reduced_precision # type: ignore
torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction = config.api.reduced_precision and supports_tf # type: ignore
logger.info(
f"Optimization: CUDNN {'' if config.api.deterministic_generation else 'not '}using deterministic functions"
)
torch.backends.cudnn.deterministic = config.api.deterministic_generation # type: ignore
if config.api.cudnn_benchmark:
logger.info("Optimization: CUDNN benchmark enabled")
torch.backends.cudnn.benchmark = config.api.cudnn_benchmark # type: ignore
if is_pytorch_pipe(pipe):
pipe.vae = optimize_vae(pipe.vae)
# Attention slicing that should save VRAM (but is slower)
slicing = config.api.attention_slicing
if slicing != "disabled" and is_pytorch_pipe(pipe) and not is_for_aitemplate:
if slicing == "auto":
pipe.enable_attention_slicing()
logger.info("Optimization: Enabled attention slicing")
else:
pipe.enable_attention_slicing(slicing)
logger.info(f"Optimization: Enabled attention slicing ({slicing})")
# xFormers and SPDA
if not is_for_aitemplate:
set_attention_processor(pipe)
if config.api.autocast:
logger.info("Optimization: Enabled autocast")
if can_offload:
# Offload to CPU
for model_name in [
"text_encoder",
"text_encoder_2",
"unet",
"vae",
]:
cpu_offloaded_model = getattr(pipe, model_name, None)
if cpu_offloaded_model is not None:
cpu_offloaded_model = set_offload(cpu_offloaded_model, device)
setattr(pipe, model_name, cpu_offloaded_model)
logger.info("Optimization: Offloaded model parts to CPU.")
if config.api.free_u:
pipe.enable_freeu(
s1=config.api.free_u_s1,
s2=config.api.free_u_s2,
b1=config.api.free_u_b1,
b2=config.api.free_u_b2,
)
if config.api.use_tomesd and not is_for_aitemplate:
try:
import tomesd
tomesd.apply_patch(pipe.unet, ratio=config.api.tomesd_ratio, max_downsample=config.api.tomesd_downsample_layers) # type: ignore
logger.info("Optimization: Patched UNet for ToMeSD")
except ImportError:
logger.info(
"Optimization: ToMeSD patch failed, despite having it enabled. Please check installation"
)
ipexed = False
if "cpu" in config.api.device:
from cpufeature import CPUFeature as cpu
n = (cpu["num_virtual_cores"] // 4) * 3
torch.set_num_threads(n)
torch.set_num_interop_threads(n)
logger.info(
f"Running on an {cpu['VendorId']} device. Used threads: {torch.get_num_threads()}-{torch.get_num_interop_threads()} / {cpu['num_virtual_cores']}"
)
pipe.unet, ipexed = trace_ipex(pipe.unet, config.api.load_dtype, device, cpu)
if config.api.trace_model and not ipexed and not is_for_aitemplate:
logger.info("Optimization: Tracing model.")
logger.warning("This will break controlnet and loras!")
pipe.unet = trace_model(pipe.unet, config.api.load_dtype, device) # type: ignore
if config.api.torch_compile and not is_for_aitemplate:
if config.api.attention_processor == "xformers":
logger.warning(
"Skipping torchscript compilation because xformers used for attention processor. Please change to SDPA to enable torchscript compilation."
)
else:
logger.info(
"Optimization: Compiling model with: %s",
{
"fullgraph": config.api.torch_compile_fullgraph,
"dynamic": config.api.torch_compile_dynamic,
"backend": config.api.torch_compile_backend,
"mode": config.api.torch_compile_mode,
},
) | Optimize the model for inference. |
156,458 | import logging
from accelerate import cpu_offload
import torch
from core.config import config
_module: torch.nn.Module = None
def unload_all():
global _module
if _module is not None:
_module.cpu()
_module = None # type: ignore | null |
156,459 | import logging
from accelerate import cpu_offload
import torch
from core.config import config
logger = logging.getLogger(__name__)
_module: torch.nn.Module = None
config = load_config()
def ensure_correct_device(module: torch.nn.Module):
global _module
if _module is not None:
if module.__class__.__name__ == _module.__class__.__name__:
return
logger.debug(f"Transferring {_module.__class__.__name__} to cpu.")
_module.cpu()
_module = None # type: ignore
if hasattr(module, "v_offload_device"):
device = getattr(module, "v_offload_device", config.api.device)
logger.debug(f"Transferring {module.__class__.__name__} to {str(device)}.")
module.to(device=torch.device(device))
_module = module
else:
logger.debug(f"Don't need to do anything with {module.__class__.__name__}.") | null |
156,460 | from inspect import isfunction
from typing import Any, Optional
from aitemplate.compiler import ops
from aitemplate.frontend import Tensor, nn
from aitemplate.testing import detect_target
def default(val, d) -> Any:
if val is not None:
return val
return d() if isfunction(d) else d | null |
156,461 | from inspect import isfunction
from typing import Any, Optional
from aitemplate.compiler import ops
from aitemplate.frontend import Tensor, nn
from aitemplate.testing import detect_target
def Normalize(in_channels: int, dtype: str = "float16"):
return nn.GroupNorm(
num_groups=32, num_channels=in_channels, eps=1e-6, affine=True, dtype=dtype
) | null |
156,462 | from typing import Any, Optional, Tuple
from aitemplate.compiler import ops
from aitemplate.frontend import Tensor, nn
from .attention import AttentionBlock
from .clip import SpatialTransformer
from .resnet import Downsample2D, ResnetBlock2D, Upsample2D
class CrossAttnDownBlock2D(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
temb_channels: int,
dropout: float = 0.0,
num_layers: int = 1,
transformer_layers_per_block: int = 1,
resnet_eps: float = 1e-6,
resnet_time_scale_shift: str = "default",
resnet_act_fn: str = "swish",
resnet_groups: int = 32,
resnet_pre_norm: bool = True,
attn_num_head_channels=1,
cross_attention_dim=1280,
attention_type: str = "default",
output_scale_factor: float = 1.0,
downsample_padding: int = 1,
add_downsample: bool = True,
use_linear_projection: bool = False,
only_cross_attention: bool = False,
dtype: str = "float16",
) -> None:
super().__init__()
resnets = []
attentions = []
self.attention_type = attention_type
self.attn_num_head_channels = attn_num_head_channels
for i in range(num_layers):
in_channels = in_channels if i == 0 else out_channels
resnets.append(
ResnetBlock2D(
in_channels=in_channels,
out_channels=out_channels,
temb_channels=temb_channels,
eps=resnet_eps,
groups=resnet_groups,
dropout=dropout,
time_embedding_norm=resnet_time_scale_shift,
non_linearity=resnet_act_fn,
output_scale_factor=output_scale_factor,
pre_norm=resnet_pre_norm,
dtype=dtype,
)
)
attentions.append(
SpatialTransformer(
out_channels,
attn_num_head_channels,
out_channels // attn_num_head_channels,
depth=transformer_layers_per_block,
context_dim=cross_attention_dim,
use_linear_projection=use_linear_projection,
only_cross_attention=only_cross_attention,
dtype=dtype,
)
)
self.attentions = nn.ModuleList(attentions)
self.resnets = nn.ModuleList(resnets)
if add_downsample:
self.downsamplers = nn.ModuleList(
[
Downsample2D(
in_channels,
use_conv=True,
out_channels=out_channels,
padding=downsample_padding,
name="op",
dtype=dtype,
)
]
)
else:
self.downsamplers = None
def forward(
self,
hidden_states: Tensor,
temb: Optional[Tensor] = None,
encoder_hidden_states: Optional[Tensor] = None,
) -> Tuple[Tensor, Tuple[Tensor]]:
output_states = ()
for resnet, attn in zip(self.resnets, self.attentions):
hidden_states = resnet(hidden_states, temb)
hidden_states = attn(hidden_states, context=encoder_hidden_states)
output_states += (hidden_states,)
if self.downsamplers is not None:
for downsampler in self.downsamplers:
hidden_states = downsampler(hidden_states)
output_states += (hidden_states,)
return hidden_states, output_states # type: ignore
class DownBlock2D(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
temb_channels: int,
dropout: float = 0.0,
num_layers: int = 1,
resnet_eps: float = 1e-6,
resnet_time_scale_shift: str = "default",
resnet_act_fn: str = "swish",
resnet_groups: int = 32,
resnet_pre_norm: bool = True,
output_scale_factor: float = 1.0,
add_downsample: bool = True,
downsample_padding: int = 1,
dtype: str = "float16",
) -> None:
super().__init__()
resnets = []
for i in range(num_layers):
in_channels = in_channels if i == 0 else out_channels
resnets.append(
ResnetBlock2D(
in_channels=in_channels,
out_channels=out_channels,
temb_channels=temb_channels,
eps=resnet_eps,
groups=resnet_groups,
dropout=dropout,
time_embedding_norm=resnet_time_scale_shift,
non_linearity=resnet_act_fn,
output_scale_factor=output_scale_factor,
pre_norm=resnet_pre_norm,
dtype=dtype,
)
)
self.resnets = nn.ModuleList(resnets)
if add_downsample:
self.downsamplers = nn.ModuleList(
[
Downsample2D(
in_channels,
use_conv=True,
out_channels=out_channels,
padding=downsample_padding,
name="op",
dtype=dtype,
)
]
)
else:
self.downsamplers = None
def forward(
self, hidden_states: Tensor, temb: Optional[Tensor] = None
) -> Tuple[Tensor, Tuple[Tensor]]:
output_states = ()
for resnet in self.resnets:
hidden_states = resnet(hidden_states, temb)
output_states += (hidden_states,)
if self.downsamplers is not None:
for downsampler in self.downsamplers:
hidden_states = downsampler(hidden_states)
output_states += (hidden_states,)
return hidden_states, output_states # type: ignore
class DownEncoderBlock2D(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
dropout: float = 0.0,
num_layers: int = 1,
resnet_eps: float = 1e-6,
resnet_time_scale_shift: str = "default",
resnet_act_fn: str = "swish",
resnet_groups: int = 32,
resnet_pre_norm: bool = True,
output_scale_factor: float = 1.0,
add_downsample: bool = True,
downsample_padding: int = 1,
dtype: str = "float16",
) -> None:
super().__init__()
resnets = []
for i in range(num_layers):
in_channels = in_channels if i == 0 else out_channels
resnets.append(
ResnetBlock2D(
in_channels=in_channels,
out_channels=out_channels,
temb_channels=None,
eps=resnet_eps,
groups=resnet_groups,
dropout=dropout,
time_embedding_norm=resnet_time_scale_shift,
non_linearity=resnet_act_fn,
output_scale_factor=output_scale_factor,
pre_norm=resnet_pre_norm,
dtype=dtype,
)
)
self.resnets = nn.ModuleList(resnets)
if add_downsample:
self.downsamplers = nn.ModuleList(
[
Downsample2D(
out_channels,
use_conv=True,
out_channels=out_channels,
padding=downsample_padding,
name="op",
dtype=dtype,
)
]
)
else:
self.downsamplers = None
def forward(self, hidden_states: Tensor) -> Tensor:
for resnet in self.resnets:
hidden_states = resnet(hidden_states, temb=None)
if self.downsamplers is not None:
for downsampler in self.downsamplers:
hidden_states = downsampler(hidden_states)
return hidden_states
def get_down_block(
down_block_type: str,
num_layers: int,
in_channels: int,
out_channels: int,
temb_channels: int,
add_downsample: bool,
resnet_eps: float,
resnet_act_fn: str,
attn_num_head_channels: int,
transformer_layers_per_block: int = 1,
cross_attention_dim: Optional[int] = None,
downsample_padding: Optional[int] = None,
use_linear_projection: Optional[bool] = False,
only_cross_attention: Optional[bool] = False,
resnet_groups: int = 32,
dtype: str = "float16",
) -> Any:
down_block_type = (
down_block_type[7:]
if down_block_type.startswith("UNetRes")
else down_block_type
)
if down_block_type == "DownBlock2D":
return DownBlock2D(
num_layers=num_layers,
in_channels=in_channels,
out_channels=out_channels,
temb_channels=temb_channels,
add_downsample=add_downsample,
resnet_eps=resnet_eps,
resnet_act_fn=resnet_act_fn,
resnet_groups=resnet_groups,
downsample_padding=downsample_padding, # type: ignore
dtype=dtype,
)
elif down_block_type == "CrossAttnDownBlock2D":
if cross_attention_dim is None:
raise ValueError(
"cross_attention_dim must be specified for CrossAttnDownBlock2D"
)
return CrossAttnDownBlock2D(
num_layers=num_layers,
transformer_layers_per_block=transformer_layers_per_block,
in_channels=in_channels,
out_channels=out_channels,
temb_channels=temb_channels,
add_downsample=add_downsample,
resnet_eps=resnet_eps,
resnet_act_fn=resnet_act_fn,
resnet_groups=resnet_groups,
downsample_padding=downsample_padding, # type: ignore
cross_attention_dim=cross_attention_dim,
attn_num_head_channels=attn_num_head_channels,
use_linear_projection=use_linear_projection, # type: ignore
only_cross_attention=only_cross_attention, # type: ignore
dtype=dtype,
)
elif down_block_type == "DownEncoderBlock2D":
return DownEncoderBlock2D(
in_channels=in_channels,
out_channels=out_channels,
num_layers=num_layers,
resnet_eps=resnet_eps,
resnet_act_fn=resnet_act_fn,
resnet_groups=resnet_groups,
output_scale_factor=1.0,
add_downsample=add_downsample,
downsample_padding=downsample_padding, # type: ignore
dtype=dtype,
) | null |
156,463 | from typing import Any, Optional, Tuple
from aitemplate.compiler import ops
from aitemplate.frontend import Tensor, nn
from .attention import AttentionBlock
from .clip import SpatialTransformer
from .resnet import Downsample2D, ResnetBlock2D, Upsample2D
class CrossAttnUpBlock2D(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
prev_output_channel: int,
temb_channels: int,
dropout: float = 0.0,
num_layers: int = 1,
transformer_layers_per_block: int = 1,
resnet_eps: float = 1e-6,
resnet_time_scale_shift: str = "default",
resnet_act_fn: str = "swish",
resnet_groups: int = 32,
resnet_pre_norm: bool = True,
attn_num_head_channels: int = 1,
cross_attention_dim: int = 1280,
attention_type: str = "default",
output_scale_factor: float = 1.0,
downsample_padding: int = 1,
add_upsample: bool = True,
use_linear_projection: bool = False,
only_cross_attention: bool = False,
dtype: str = "float16",
) -> None:
def forward(
self,
hidden_states: Tensor,
res_hidden_states_tuple: Tuple[Tensor],
temb: Optional[Tensor] = None,
encoder_hidden_states: Optional[Tensor] = None,
) -> Tensor:
class UpBlock2D(nn.Module):
def __init__(
self,
in_channels: int,
prev_output_channel: int,
out_channels: int,
temb_channels: int,
dropout: float = 0.0,
num_layers: int = 1,
resnet_eps: float = 1e-6,
resnet_time_scale_shift: str = "default",
resnet_act_fn: str = "swish",
resnet_groups: int = 32,
resnet_pre_norm: bool = True,
output_scale_factor: float = 1.0,
add_upsample: bool = True,
dtype: str = "float16",
) -> None:
def forward(
self,
hidden_states: Tensor,
res_hidden_states_tuple: Tuple[Tensor],
temb: Optional[Tensor] = None,
):
class UpDecoderBlock2D(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
dropout: float = 0.0,
num_layers: int = 1,
resnet_eps: float = 1e-6,
resnet_time_scale_shift: str = "default",
resnet_act_fn: str = "swish",
resnet_groups: int = 32,
resnet_pre_norm: bool = True,
output_scale_factor: float = 1.0,
add_upsample: bool = True,
dtype: str = "float16",
) -> None:
def forward(self, hidden_states: Tensor) -> Tensor:
def get_up_block(
up_block_type: str,
num_layers: int,
in_channels: int,
out_channels: int,
prev_output_channel: Optional[int],
temb_channels: Optional[int],
add_upsample: bool,
resnet_eps: float,
resnet_act_fn: str,
attn_num_head_channels: Optional[int],
transformer_layers_per_block: int = 1,
cross_attention_dim: Optional[int] = None,
use_linear_projection: Optional[bool] = False,
only_cross_attention: bool = False,
dtype: str = "float16",
) -> Any:
up_block_type = (
up_block_type[7:] if up_block_type.startswith("UNetRes") else up_block_type
)
if up_block_type == "UpBlock2D":
return UpBlock2D(
num_layers=num_layers,
in_channels=in_channels,
out_channels=out_channels,
prev_output_channel=prev_output_channel, # type: ignore
temb_channels=temb_channels, # type: ignore
add_upsample=add_upsample,
resnet_eps=resnet_eps,
resnet_act_fn=resnet_act_fn,
dtype=dtype,
)
elif up_block_type == "CrossAttnUpBlock2D":
if cross_attention_dim is None:
raise ValueError(
"cross_attention_dim must be specified for CrossAttnUpBlock2D"
)
return CrossAttnUpBlock2D(
transformer_layers_per_block=transformer_layers_per_block,
num_layers=num_layers,
in_channels=in_channels,
out_channels=out_channels,
prev_output_channel=prev_output_channel, # type: ignore
temb_channels=temb_channels, # type: ignore
add_upsample=add_upsample,
resnet_eps=resnet_eps,
resnet_act_fn=resnet_act_fn,
cross_attention_dim=cross_attention_dim,
attn_num_head_channels=attn_num_head_channels, # type: ignore
use_linear_projection=use_linear_projection, # type: ignore
only_cross_attention=only_cross_attention,
dtype=dtype,
)
elif up_block_type == "UpDecoderBlock2D":
return UpDecoderBlock2D(
num_layers=num_layers,
in_channels=in_channels,
out_channels=out_channels,
add_upsample=add_upsample,
resnet_eps=resnet_eps,
resnet_act_fn=resnet_act_fn,
dtype=dtype,
)
raise ValueError(f"{up_block_type} does not exist.") | null |
156,464 | from typing import Any, Optional, Tuple
from aitemplate.compiler import ops
from aitemplate.frontend import Tensor, nn
from .attention import AttentionBlock
from .clip import SpatialTransformer
from .resnet import Downsample2D, ResnetBlock2D, Upsample2D
def shape_to_list(shape):
return [
sample["symbolic_value"] # type: ignore
if isinstance(sample, Tensor)
else sample._attrs["symbolic_value"]
for sample in shape
] | null |
156,465 | import torch
from transformers import CLIPTextConfig, CLIPTextModel
from ..common import torch_dtype_from_str
def torch_dtype_from_str(dtype: str):
def map_controlnet(pt_mod, dim=320, device="cuda", dtype="float16"):
if not isinstance(pt_mod, dict):
pt_params = dict(pt_mod.named_parameters())
else:
pt_params = pt_mod
params_ait = {}
for key, arr in pt_params.items():
arr = arr.to(device, dtype=torch_dtype_from_str(dtype))
if len(arr.shape) == 4:
arr = arr.permute((0, 2, 3, 1)).contiguous()
elif key.endswith("ff.net.0.proj.weight"):
w1, w2 = arr.chunk(2, dim=0)
params_ait[key.replace(".", "_")] = w1
params_ait[key.replace(".", "_").replace("proj", "gate")] = w2
continue
elif key.endswith("ff.net.0.proj.bias"):
w1, w2 = arr.chunk(2, dim=0)
params_ait[key.replace(".", "_")] = w1
params_ait[key.replace(".", "_").replace("proj", "gate")] = w2
continue
params_ait[key.replace(".", "_")] = arr
params_ait["controlnet_cond_embedding_conv_in_weight"] = torch.nn.functional.pad(
params_ait["controlnet_cond_embedding_conv_in_weight"], (0, 1, 0, 0, 0, 0, 0, 0)
)
params_ait["arange"] = (
torch.arange(start=0, end=dim // 2, dtype=torch.float32).cuda().half()
)
return params_ait | null |
156,466 | import math
from aitemplate.compiler import ops
from aitemplate.frontend import Tensor, nn
def get_timestep_embedding(
timesteps: Tensor,
embedding_dim: int,
flip_sin_to_cos: bool = False,
downscale_freq_shift: float = 1,
scale: float = 1,
max_period: int = 10000,
dtype: str = "float16",
arange_name: str = "arange",
) -> Tensor:
assert timesteps._rank() == 1, "Timesteps should be a 1d-array"
half_dim = embedding_dim // 2
exponent = (-math.log(max_period)) * Tensor(
shape=[half_dim], dtype=dtype, name=arange_name # type: ignore
)
exponent = exponent * (1.0 / (half_dim - downscale_freq_shift))
emb = ops.exp(exponent)
emb = ops.reshape()(timesteps, [-1, 1]) * ops.reshape()(emb, [1, -1])
emb = scale * emb
if flip_sin_to_cos:
emb = ops.concatenate()(
[ops.cos(emb), ops.sin(emb)],
dim=-1,
)
else:
emb = ops.concatenate()(
[ops.sin(emb), ops.cos(emb)],
dim=-1,
)
return emb # type: ignore | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.