refactor all control processors to support unload and offload

This commit is contained in:
Vladimir Mandic
2024-01-25 11:45:47 -05:00
parent c19f95141a
commit 7aa6876759
27 changed files with 154 additions and 350 deletions
+5 -21
View File
@@ -1,7 +1,5 @@
import os
import types
import warnings
import cv2
import numpy as np
import torch
@@ -9,7 +7,8 @@ import torchvision.transforms as transforms
from einops import rearrange
from huggingface_hub import hf_hub_download
from PIL import Image
from modules import devices
from modules.shared import opts
from modules.control.util import HWC3, resize_image
from .nets.NNET import NNET
@@ -25,7 +24,6 @@ def load_checkpoint(fpath, model):
load_dict[k_] = v
else:
load_dict[k] = v
model.load_state_dict(load_dict)
return model
@@ -37,12 +35,10 @@ class NormalBaeDetector:
@classmethod
def from_pretrained(cls, pretrained_model_or_path, filename=None, cache_dir=None):
filename = filename or "scannet.pt"
if os.path.isdir(pretrained_model_or_path):
model_path = os.path.join(pretrained_model_or_path, filename)
else:
model_path = hf_hub_download(pretrained_model_or_path, filename, cache_dir=cache_dir)
args = types.SimpleNamespace()
args.mode = 'client'
args.architecture = 'BN'
@@ -52,7 +48,6 @@ class NormalBaeDetector:
model = NNET(args)
model = load_checkpoint(model_path, model)
model.eval()
return cls(model)
def to(self, device):
@@ -61,14 +56,7 @@ class NormalBaeDetector:
def __call__(self, input_image, detect_resolution=512, image_resolution=512, output_type="pil", **kwargs):
if "return_pil" in kwargs:
warnings.warn("return_pil is deprecated. Use output_type instead.", DeprecationWarning)
output_type = "pil" if kwargs["return_pil"] else "np"
if type(output_type) is bool:
warnings.warn("Passing `True` or `False` to `output_type` is deprecated and will raise an error in future versions")
if output_type:
output_type = "pil"
self.model.to(devices.device)
device = next(iter(self.model.parameters())).device
if not isinstance(input_image, np.ndarray):
input_image = np.array(input_image, dtype=np.uint8)
@@ -89,19 +77,15 @@ class NormalBaeDetector:
# d = torch.maximum(d, torch.ones_like(d) * 1e-5)
# normal /= d
normal = ((normal + 1) * 0.5).clip(0, 1)
normal = rearrange(normal[0], 'c h w -> h w c').cpu().numpy()
normal_image = (normal * 255.0).clip(0, 255).astype(np.uint8)
detected_map = normal_image
detected_map = HWC3(detected_map)
img = resize_image(input_image, image_resolution)
H, W, _C = img.shape
detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_LINEAR)
if output_type == "pil":
detected_map = Image.fromarray(detected_map)
if opts.control_move_processor:
self.model.to('cpu')
return detected_map