2023-04-15 22:46:58 +00:00
|
|
|
from comfy import sd1_clip
|
2023-01-03 06:53:32 +00:00
|
|
|
import torch
|
2023-02-05 19:36:28 +00:00
|
|
|
import os
|
2023-01-03 06:53:32 +00:00
|
|
|
|
2023-02-05 19:36:28 +00:00
|
|
|
class SD2ClipModel(sd1_clip.SD1ClipModel):
|
|
|
|
def __init__(self, arch="ViT-H-14", device="cpu", max_length=77, freeze=True, layer="penultimate", layer_idx=None):
|
|
|
|
textmodel_json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "sd2_clip_config.json")
|
|
|
|
super().__init__(device=device, freeze=freeze, textmodel_json_config=textmodel_json_config)
|
2023-01-03 06:53:32 +00:00
|
|
|
self.empty_tokens = [[49406] + [49407] + [0] * 75]
|
2023-02-05 19:36:28 +00:00
|
|
|
if layer == "last":
|
2023-02-05 20:20:18 +00:00
|
|
|
pass
|
2023-02-05 19:36:28 +00:00
|
|
|
elif layer == "penultimate":
|
2023-02-05 20:20:18 +00:00
|
|
|
layer_idx = -1
|
|
|
|
self.clip_layer(layer_idx)
|
2023-01-03 06:53:32 +00:00
|
|
|
elif self.layer == "hidden":
|
|
|
|
assert layer_idx is not None
|
|
|
|
assert abs(layer_idx) < 24
|
2023-02-05 20:20:18 +00:00
|
|
|
self.clip_layer(layer_idx)
|
2023-01-03 06:53:32 +00:00
|
|
|
else:
|
|
|
|
raise NotImplementedError()
|
2023-02-05 20:20:18 +00:00
|
|
|
|
|
|
|
def clip_layer(self, layer_idx):
|
|
|
|
if layer_idx < 0:
|
|
|
|
layer_idx -= 1 #The real last layer of SD2.x clip is the penultimate one. The last one might contain garbage.
|
|
|
|
if abs(layer_idx) >= 24:
|
|
|
|
self.layer = "hidden"
|
|
|
|
self.layer_idx = -2
|
|
|
|
else:
|
|
|
|
self.layer = "hidden"
|
|
|
|
self.layer_idx = layer_idx
|
2023-01-03 06:53:32 +00:00
|
|
|
|
|
|
|
class SD2Tokenizer(sd1_clip.SD1Tokenizer):
|
2023-02-05 20:49:03 +00:00
|
|
|
def __init__(self, tokenizer_path=None, embedding_directory=None):
|
2023-06-22 17:03:50 +00:00
|
|
|
super().__init__(tokenizer_path, pad_with_end=False, embedding_directory=embedding_directory, embedding_size=1024)
|