ACCC1380 commited on
Commit
7cc8356
1 Parent(s): acfa326

Upload lora-scripts/sd-scripts/networks/lora_interrogator.py with huggingface_hub

Browse files
lora-scripts/sd-scripts/networks/lora_interrogator.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ from tqdm import tqdm
4
+ from library import model_util
5
+ import library.train_util as train_util
6
+ import argparse
7
+ from transformers import CLIPTokenizer
8
+
9
+ import torch
10
+ from library.device_utils import init_ipex, get_preferred_device
11
+ init_ipex()
12
+
13
+ import library.model_util as model_util
14
+ import lora
15
+ from library.utils import setup_logging
16
+ setup_logging()
17
+ import logging
18
+ logger = logging.getLogger(__name__)
19
+
20
+ TOKENIZER_PATH = "openai/clip-vit-large-patch14"
21
+ V2_STABLE_DIFFUSION_PATH = "stabilityai/stable-diffusion-2" # ここからtokenizerだけ使う
22
+
23
+ DEVICE = get_preferred_device()
24
+
25
+
26
+ def interrogate(args):
27
+ weights_dtype = torch.float16
28
+
29
+ # いろいろ準備する
30
+ logger.info(f"loading SD model: {args.sd_model}")
31
+ args.pretrained_model_name_or_path = args.sd_model
32
+ args.vae = None
33
+ text_encoder, vae, unet, _ = train_util._load_target_model(args,weights_dtype, DEVICE)
34
+
35
+ logger.info(f"loading LoRA: {args.model}")
36
+ network, weights_sd = lora.create_network_from_weights(1.0, args.model, vae, text_encoder, unet)
37
+
38
+ # text encoder向けの重みがあるかチェックする:本当はlora側でやるのがいい
39
+ has_te_weight = False
40
+ for key in weights_sd.keys():
41
+ if 'lora_te' in key:
42
+ has_te_weight = True
43
+ break
44
+ if not has_te_weight:
45
+ logger.error("This LoRA does not have modules for Text Encoder, cannot interrogate / このLoRAはText Encoder向けのモジュールがないため調査できません")
46
+ return
47
+ del vae
48
+
49
+ logger.info("loading tokenizer")
50
+ if args.v2:
51
+ tokenizer: CLIPTokenizer = CLIPTokenizer.from_pretrained(V2_STABLE_DIFFUSION_PATH, subfolder="tokenizer")
52
+ else:
53
+ tokenizer: CLIPTokenizer = CLIPTokenizer.from_pretrained(TOKENIZER_PATH) # , model_max_length=max_token_length + 2)
54
+
55
+ text_encoder.to(DEVICE, dtype=weights_dtype)
56
+ text_encoder.eval()
57
+ unet.to(DEVICE, dtype=weights_dtype)
58
+ unet.eval() # U-Netは呼び出さないので不要だけど
59
+
60
+ # トークンをひとつひとつ当たっていく
61
+ token_id_start = 0
62
+ token_id_end = max(tokenizer.all_special_ids)
63
+ logger.info(f"interrogate tokens are: {token_id_start} to {token_id_end}")
64
+
65
+ def get_all_embeddings(text_encoder):
66
+ embs = []
67
+ with torch.no_grad():
68
+ for token_id in tqdm(range(token_id_start, token_id_end + 1, args.batch_size)):
69
+ batch = []
70
+ for tid in range(token_id, min(token_id_end + 1, token_id + args.batch_size)):
71
+ tokens = [tokenizer.bos_token_id, tid, tokenizer.eos_token_id]
72
+ # tokens = [tid] # こちらは結果がいまひとつ
73
+ batch.append(tokens)
74
+
75
+ # batch_embs = text_encoder(torch.tensor(batch).to(DEVICE))[0].to("cpu") # bos/eosも含めたほうが差が出るようだ [:, 1]
76
+ # clip skip対応
77
+ batch = torch.tensor(batch).to(DEVICE)
78
+ if args.clip_skip is None:
79
+ encoder_hidden_states = text_encoder(batch)[0]
80
+ else:
81
+ enc_out = text_encoder(batch, output_hidden_states=True, return_dict=True)
82
+ encoder_hidden_states = enc_out['hidden_states'][-args.clip_skip]
83
+ encoder_hidden_states = text_encoder.text_model.final_layer_norm(encoder_hidden_states)
84
+ encoder_hidden_states = encoder_hidden_states.to("cpu")
85
+
86
+ embs.extend(encoder_hidden_states)
87
+ return torch.stack(embs)
88
+
89
+ logger.info("get original text encoder embeddings.")
90
+ orig_embs = get_all_embeddings(text_encoder)
91
+
92
+ network.apply_to(text_encoder, unet, True, len(network.unet_loras) > 0)
93
+ info = network.load_state_dict(weights_sd, strict=False)
94
+ logger.info(f"Loading LoRA weights: {info}")
95
+
96
+ network.to(DEVICE, dtype=weights_dtype)
97
+ network.eval()
98
+
99
+ del unet
100
+
101
+ logger.info("You can ignore warning messages start with '_IncompatibleKeys' (LoRA model does not have alpha because trained by older script) / '_IncompatibleKeys'の警告は無視して構いません(以前のスクリプトで学習されたLoRAモデルのためalphaの定義がありません)")
102
+ logger.info("get text encoder embeddings with lora.")
103
+ lora_embs = get_all_embeddings(text_encoder)
104
+
105
+ # 比べる:とりあえず単純に差分の絶対値で
106
+ logger.info("comparing...")
107
+ diffs = {}
108
+ for i, (orig_emb, lora_emb) in enumerate(zip(orig_embs, tqdm(lora_embs))):
109
+ diff = torch.mean(torch.abs(orig_emb - lora_emb))
110
+ # diff = torch.mean(torch.cosine_similarity(orig_emb, lora_emb, dim=1)) # うまく検出できない
111
+ diff = float(diff.detach().to('cpu').numpy())
112
+ diffs[token_id_start + i] = diff
113
+
114
+ diffs_sorted = sorted(diffs.items(), key=lambda x: -x[1])
115
+
116
+ # 結果を表示する
117
+ print("top 100:")
118
+ for i, (token, diff) in enumerate(diffs_sorted[:100]):
119
+ # if diff < 1e-6:
120
+ # break
121
+ string = tokenizer.convert_tokens_to_string(tokenizer.convert_ids_to_tokens([token]))
122
+ print(f"[{i:3d}]: {token:5d} {string:<20s}: {diff:.5f}")
123
+
124
+
125
+ def setup_parser() -> argparse.ArgumentParser:
126
+ parser = argparse.ArgumentParser()
127
+
128
+ parser.add_argument("--v2", action='store_true',
129
+ help='load Stable Diffusion v2.x model / Stable Diffusion 2.xのモデルを読み込む')
130
+ parser.add_argument("--sd_model", type=str, default=None,
131
+ help="Stable Diffusion model to load: ckpt or safetensors file / 読み込むSDのモデル、ckptまたはsafetensors")
132
+ parser.add_argument("--model", type=str, default=None,
133
+ help="LoRA model to interrogate: ckpt or safetensors file / 調査するLoRAモデル、ckptまたはsafetensors")
134
+ parser.add_argument("--batch_size", type=int, default=16,
135
+ help="batch size for processing with Text Encoder / Text Encoderで処理するときのバッチサイズ")
136
+ parser.add_argument("--clip_skip", type=int, default=None,
137
+ help="use output of nth layer from back of text encoder (n>=1) / text encoderの後ろからn番目の層の出力を用いる(nは1以上)")
138
+
139
+ return parser
140
+
141
+
142
+ if __name__ == '__main__':
143
+ parser = setup_parser()
144
+
145
+ args = parser.parse_args()
146
+ interrogate(args)