Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

sd1_clip.py 20 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
  1. import os
  2. from transformers import CLIPTokenizer
  3. import ldm_patched.modules.ops
  4. import torch
  5. import traceback
  6. import zipfile
  7. from . import model_management
  8. import ldm_patched.modules.clip_model
  9. import json
  10. def gen_empty_tokens(special_tokens, length):
  11. start_token = special_tokens.get("start", None)
  12. end_token = special_tokens.get("end", None)
  13. pad_token = special_tokens.get("pad")
  14. output = []
  15. if start_token is not None:
  16. output.append(start_token)
  17. if end_token is not None:
  18. output.append(end_token)
  19. output += [pad_token] * (length - len(output))
  20. return output
  21. class ClipTokenWeightEncoder:
  22. def encode_token_weights(self, token_weight_pairs):
  23. to_encode = list()
  24. max_token_len = 0
  25. has_weights = False
  26. for x in token_weight_pairs:
  27. tokens = list(map(lambda a: a[0], x))
  28. max_token_len = max(len(tokens), max_token_len)
  29. has_weights = has_weights or not all(map(lambda a: a[1] == 1.0, x))
  30. to_encode.append(tokens)
  31. sections = len(to_encode)
  32. if has_weights or sections == 0:
  33. to_encode.append(gen_empty_tokens(self.special_tokens, max_token_len))
  34. out, pooled = self.encode(to_encode)
  35. if pooled is not None:
  36. first_pooled = pooled[0:1].to(model_management.intermediate_device())
  37. else:
  38. first_pooled = pooled
  39. output = []
  40. for k in range(0, sections):
  41. z = out[k:k+1]
  42. if has_weights:
  43. z_empty = out[-1]
  44. for i in range(len(z)):
  45. for j in range(len(z[i])):
  46. weight = token_weight_pairs[k][j][1]
  47. if weight != 1.0:
  48. z[i][j] = (z[i][j] - z_empty[j]) * weight + z_empty[j]
  49. output.append(z)
  50. if (len(output) == 0):
  51. return out[-1:].to(model_management.intermediate_device()), first_pooled
  52. return torch.cat(output, dim=-2).to(model_management.intermediate_device()), first_pooled
  53. class SDClipModel(torch.nn.Module, ClipTokenWeightEncoder):
  54. """Uses the CLIP transformer encoder for text (from huggingface)"""
  55. LAYERS = [
  56. "last",
  57. "pooled",
  58. "hidden"
  59. ]
  60. def __init__(self, version="openai/clip-vit-large-patch14", device="cpu", max_length=77,
  61. freeze=True, layer="last", layer_idx=None, textmodel_json_config=None, dtype=None, model_class=ldm_patched.modules.clip_model.CLIPTextModel,
  62. special_tokens={"start": 49406, "end": 49407, "pad": 49407}, layer_norm_hidden_state=True): # clip-vit-base-patch32
  63. super().__init__()
  64. assert layer in self.LAYERS
  65. if textmodel_json_config is None:
  66. textmodel_json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "sd1_clip_config.json")
  67. with open(textmodel_json_config) as f:
  68. config = json.load(f)
  69. self.transformer = model_class(config, dtype, device, ldm_patched.modules.ops.manual_cast)
  70. self.num_layers = self.transformer.num_layers
  71. self.max_length = max_length
  72. if freeze:
  73. self.freeze()
  74. self.layer = layer
  75. self.layer_idx = None
  76. self.special_tokens = special_tokens
  77. self.text_projection = torch.nn.Parameter(torch.eye(self.transformer.get_input_embeddings().weight.shape[1]))
  78. self.logit_scale = torch.nn.Parameter(torch.tensor(4.6055))
  79. self.enable_attention_masks = False
  80. self.layer_norm_hidden_state = layer_norm_hidden_state
  81. if layer == "hidden":
  82. assert layer_idx is not None
  83. assert abs(layer_idx) < self.num_layers
  84. self.clip_layer(layer_idx)
  85. self.layer_default = (self.layer, self.layer_idx)
  86. def freeze(self):
  87. self.transformer = self.transformer.eval()
  88. #self.train = disabled_train
  89. for param in self.parameters():
  90. param.requires_grad = False
  91. def clip_layer(self, layer_idx):
  92. if abs(layer_idx) > self.num_layers:
  93. self.layer = "last"
  94. else:
  95. self.layer = "hidden"
  96. self.layer_idx = layer_idx
  97. def reset_clip_layer(self):
  98. self.layer = self.layer_default[0]
  99. self.layer_idx = self.layer_default[1]
  100. def set_up_textual_embeddings(self, tokens, current_embeds):
  101. out_tokens = []
  102. next_new_token = token_dict_size = current_embeds.weight.shape[0] - 1
  103. embedding_weights = []
  104. for x in tokens:
  105. tokens_temp = []
  106. for y in x:
  107. if isinstance(y, int):
  108. if y == token_dict_size: #EOS token
  109. y = -1
  110. tokens_temp += [y]
  111. else:
  112. if y.shape[0] == current_embeds.weight.shape[1]:
  113. embedding_weights += [y]
  114. tokens_temp += [next_new_token]
  115. next_new_token += 1
  116. else:
  117. print("WARNING: shape mismatch when trying to apply embedding, embedding will be ignored", y.shape[0], current_embeds.weight.shape[1])
  118. while len(tokens_temp) < len(x):
  119. tokens_temp += [self.special_tokens["pad"]]
  120. out_tokens += [tokens_temp]
  121. n = token_dict_size
  122. if len(embedding_weights) > 0:
  123. new_embedding = torch.nn.Embedding(next_new_token + 1, current_embeds.weight.shape[1], device=current_embeds.weight.device, dtype=current_embeds.weight.dtype)
  124. new_embedding.weight[:token_dict_size] = current_embeds.weight[:-1]
  125. for x in embedding_weights:
  126. new_embedding.weight[n] = x
  127. n += 1
  128. new_embedding.weight[n] = current_embeds.weight[-1] #EOS embedding
  129. self.transformer.set_input_embeddings(new_embedding)
  130. processed_tokens = []
  131. for x in out_tokens:
  132. processed_tokens += [list(map(lambda a: n if a == -1 else a, x))] #The EOS token should always be the largest one
  133. return processed_tokens
  134. def forward(self, tokens):
  135. backup_embeds = self.transformer.get_input_embeddings()
  136. device = backup_embeds.weight.device
  137. tokens = self.set_up_textual_embeddings(tokens, backup_embeds)
  138. tokens = torch.LongTensor(tokens).to(device)
  139. attention_mask = None
  140. if self.enable_attention_masks:
  141. attention_mask = torch.zeros_like(tokens)
  142. max_token = self.transformer.get_input_embeddings().weight.shape[0] - 1
  143. for x in range(attention_mask.shape[0]):
  144. for y in range(attention_mask.shape[1]):
  145. attention_mask[x, y] = 1
  146. if tokens[x, y] == max_token:
  147. break
  148. outputs = self.transformer(tokens, attention_mask, intermediate_output=self.layer_idx, final_layer_norm_intermediate=self.layer_norm_hidden_state)
  149. self.transformer.set_input_embeddings(backup_embeds)
  150. if self.layer == "last":
  151. z = outputs[0]
  152. else:
  153. z = outputs[1]
  154. if outputs[2] is not None:
  155. pooled_output = outputs[2].float()
  156. else:
  157. pooled_output = None
  158. if self.text_projection is not None and pooled_output is not None:
  159. pooled_output = pooled_output.float().to(self.text_projection.device) @ self.text_projection.float()
  160. return z.float(), pooled_output
  161. def encode(self, tokens):
  162. return self(tokens)
  163. def load_sd(self, sd):
  164. if "text_projection" in sd:
  165. self.text_projection[:] = sd.pop("text_projection")
  166. if "text_projection.weight" in sd:
  167. self.text_projection[:] = sd.pop("text_projection.weight").transpose(0, 1)
  168. return self.transformer.load_state_dict(sd, strict=False)
  169. def parse_parentheses(string):
  170. result = []
  171. current_item = ""
  172. nesting_level = 0
  173. for char in string:
  174. if char == "(":
  175. if nesting_level == 0:
  176. if current_item:
  177. result.append(current_item)
  178. current_item = "("
  179. else:
  180. current_item = "("
  181. else:
  182. current_item += char
  183. nesting_level += 1
  184. elif char == ")":
  185. nesting_level -= 1
  186. if nesting_level == 0:
  187. result.append(current_item + ")")
  188. current_item = ""
  189. else:
  190. current_item += char
  191. else:
  192. current_item += char
  193. if current_item:
  194. result.append(current_item)
  195. return result
  196. def token_weights(string, current_weight):
  197. a = parse_parentheses(string)
  198. out = []
  199. for x in a:
  200. weight = current_weight
  201. if len(x) >= 2 and x[-1] == ')' and x[0] == '(':
  202. x = x[1:-1]
  203. xx = x.rfind(":")
  204. weight *= 1.1
  205. if xx > 0:
  206. try:
  207. weight = float(x[xx+1:])
  208. x = x[:xx]
  209. except:
  210. pass
  211. out += token_weights(x, weight)
  212. else:
  213. out += [(x, current_weight)]
  214. return out
  215. def escape_important(text):
  216. text = text.replace("\\)", "\0\1")
  217. text = text.replace("\\(", "\0\2")
  218. return text
  219. def unescape_important(text):
  220. text = text.replace("\0\1", ")")
  221. text = text.replace("\0\2", "(")
  222. return text
  223. def safe_load_embed_zip(embed_path):
  224. with zipfile.ZipFile(embed_path) as myzip:
  225. names = list(filter(lambda a: "data/" in a, myzip.namelist()))
  226. names.reverse()
  227. for n in names:
  228. with myzip.open(n) as myfile:
  229. data = myfile.read()
  230. number = len(data) // 4
  231. length_embed = 1024 #sd2.x
  232. if number < 768:
  233. continue
  234. if number % 768 == 0:
  235. length_embed = 768 #sd1.x
  236. num_embeds = number // length_embed
  237. embed = torch.frombuffer(data, dtype=torch.float)
  238. out = embed.reshape((num_embeds, length_embed)).clone()
  239. del embed
  240. return out
  241. def expand_directory_list(directories):
  242. dirs = set()
  243. for x in directories:
  244. dirs.add(x)
  245. for root, subdir, file in os.walk(x, followlinks=True):
  246. dirs.add(root)
  247. return list(dirs)
  248. def load_embed(embedding_name, embedding_directory, embedding_size, embed_key=None):
  249. if isinstance(embedding_directory, str):
  250. embedding_directory = [embedding_directory]
  251. embedding_directory = expand_directory_list(embedding_directory)
  252. valid_file = None
  253. for embed_dir in embedding_directory:
  254. embed_path = os.path.abspath(os.path.join(embed_dir, embedding_name))
  255. embed_dir = os.path.abspath(embed_dir)
  256. try:
  257. if os.path.commonpath((embed_dir, embed_path)) != embed_dir:
  258. continue
  259. except:
  260. continue
  261. if not os.path.isfile(embed_path):
  262. extensions = ['.safetensors', '.pt', '.bin']
  263. for x in extensions:
  264. t = embed_path + x
  265. if os.path.isfile(t):
  266. valid_file = t
  267. break
  268. else:
  269. valid_file = embed_path
  270. if valid_file is not None:
  271. break
  272. if valid_file is None:
  273. return None
  274. embed_path = valid_file
  275. embed_out = None
  276. try:
  277. if embed_path.lower().endswith(".safetensors"):
  278. import safetensors.torch
  279. embed = safetensors.torch.load_file(embed_path, device="cpu")
  280. else:
  281. if 'weights_only' in torch.load.__code__.co_varnames:
  282. try:
  283. embed = torch.load(embed_path, weights_only=True, map_location="cpu")
  284. except:
  285. embed_out = safe_load_embed_zip(embed_path)
  286. else:
  287. embed = torch.load(embed_path, map_location="cpu", weights_only=True)
  288. except Exception as e:
  289. print(traceback.format_exc())
  290. print()
  291. print("error loading embedding, skipping loading:", embedding_name)
  292. return None
  293. if embed_out is None:
  294. if 'string_to_param' in embed:
  295. values = embed['string_to_param'].values()
  296. embed_out = next(iter(values))
  297. elif isinstance(embed, list):
  298. out_list = []
  299. for x in range(len(embed)):
  300. for k in embed[x]:
  301. t = embed[x][k]
  302. if t.shape[-1] != embedding_size:
  303. continue
  304. out_list.append(t.reshape(-1, t.shape[-1]))
  305. embed_out = torch.cat(out_list, dim=0)
  306. elif embed_key is not None and embed_key in embed:
  307. embed_out = embed[embed_key]
  308. else:
  309. values = embed.values()
  310. embed_out = next(iter(values))
  311. return embed_out
  312. class SDTokenizer:
  313. def __init__(self, tokenizer_path=None, max_length=77, pad_with_end=True, embedding_directory=None, embedding_size=768, embedding_key='clip_l', tokenizer_class=CLIPTokenizer, has_start_token=True, pad_to_max_length=True):
  314. if tokenizer_path is None:
  315. tokenizer_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "sd1_tokenizer")
  316. self.tokenizer = tokenizer_class.from_pretrained(tokenizer_path)
  317. self.max_length = max_length
  318. empty = self.tokenizer('')["input_ids"]
  319. if has_start_token:
  320. self.tokens_start = 1
  321. self.start_token = empty[0]
  322. self.end_token = empty[1]
  323. else:
  324. self.tokens_start = 0
  325. self.start_token = None
  326. self.end_token = empty[0]
  327. self.pad_with_end = pad_with_end
  328. self.pad_to_max_length = pad_to_max_length
  329. vocab = self.tokenizer.get_vocab()
  330. self.inv_vocab = {v: k for k, v in vocab.items()}
  331. self.embedding_directory = embedding_directory
  332. self.max_word_length = 8
  333. self.embedding_identifier = "embedding:"
  334. self.embedding_size = embedding_size
  335. self.embedding_key = embedding_key
  336. def _try_get_embedding(self, embedding_name:str):
  337. '''
  338. Takes a potential embedding name and tries to retrieve it.
  339. Returns a Tuple consisting of the embedding and any leftover string, embedding can be None.
  340. '''
  341. embed = load_embed(embedding_name, self.embedding_directory, self.embedding_size, self.embedding_key)
  342. if embed is None:
  343. stripped = embedding_name.strip(',')
  344. if len(stripped) < len(embedding_name):
  345. embed = load_embed(stripped, self.embedding_directory, self.embedding_size, self.embedding_key)
  346. return (embed, embedding_name[len(stripped):])
  347. return (embed, "")
  348. def tokenize_with_weights(self, text:str, return_word_ids=False):
  349. '''
  350. Takes a prompt and converts it to a list of (token, weight, word id) elements.
  351. Tokens can both be integer tokens and pre computed CLIP tensors.
  352. Word id values are unique per word and embedding, where the id 0 is reserved for non word tokens.
  353. Returned list has the dimensions NxM where M is the input size of CLIP
  354. '''
  355. if self.pad_with_end:
  356. pad_token = self.end_token
  357. else:
  358. pad_token = 0
  359. text = escape_important(text)
  360. parsed_weights = token_weights(text, 1.0)
  361. #tokenize words
  362. tokens = []
  363. for weighted_segment, weight in parsed_weights:
  364. to_tokenize = unescape_important(weighted_segment).replace("\n", " ").split(' ')
  365. to_tokenize = [x for x in to_tokenize if x != ""]
  366. for word in to_tokenize:
  367. #if we find an embedding, deal with the embedding
  368. if word.startswith(self.embedding_identifier) and self.embedding_directory is not None:
  369. embedding_name = word[len(self.embedding_identifier):].strip('\n')
  370. embed, leftover = self._try_get_embedding(embedding_name)
  371. if embed is None:
  372. print(f"warning, embedding:{embedding_name} does not exist, ignoring")
  373. else:
  374. if len(embed.shape) == 1:
  375. tokens.append([(embed, weight)])
  376. else:
  377. tokens.append([(embed[x], weight) for x in range(embed.shape[0])])
  378. #if we accidentally have leftover text, continue parsing using leftover, else move on to next word
  379. if leftover != "":
  380. word = leftover
  381. else:
  382. continue
  383. #parse word
  384. tokens.append([(t, weight) for t in self.tokenizer(word)["input_ids"][self.tokens_start:-1]])
  385. #reshape token array to CLIP input size
  386. batched_tokens = []
  387. batch = []
  388. if self.start_token is not None:
  389. batch.append((self.start_token, 1.0, 0))
  390. batched_tokens.append(batch)
  391. for i, t_group in enumerate(tokens):
  392. #determine if we're going to try and keep the tokens in a single batch
  393. is_large = len(t_group) >= self.max_word_length
  394. while len(t_group) > 0:
  395. if len(t_group) + len(batch) > self.max_length - 1:
  396. remaining_length = self.max_length - len(batch) - 1
  397. #break word in two and add end token
  398. if is_large:
  399. batch.extend([(t,w,i+1) for t,w in t_group[:remaining_length]])
  400. batch.append((self.end_token, 1.0, 0))
  401. t_group = t_group[remaining_length:]
  402. #add end token and pad
  403. else:
  404. batch.append((self.end_token, 1.0, 0))
  405. if self.pad_to_max_length:
  406. batch.extend([(pad_token, 1.0, 0)] * (remaining_length))
  407. #start new batch
  408. batch = []
  409. if self.start_token is not None:
  410. batch.append((self.start_token, 1.0, 0))
  411. batched_tokens.append(batch)
  412. else:
  413. batch.extend([(t,w,i+1) for t,w in t_group])
  414. t_group = []
  415. #fill last batch
  416. batch.append((self.end_token, 1.0, 0))
  417. if self.pad_to_max_length:
  418. batch.extend([(pad_token, 1.0, 0)] * (self.max_length - len(batch)))
  419. if not return_word_ids:
  420. batched_tokens = [[(t, w) for t, w,_ in x] for x in batched_tokens]
  421. return batched_tokens
  422. def untokenize(self, token_weight_pair):
  423. return list(map(lambda a: (a, self.inv_vocab[a[0]]), token_weight_pair))
  424. class SD1Tokenizer:
  425. def __init__(self, embedding_directory=None, clip_name="l", tokenizer=SDTokenizer):
  426. self.clip_name = clip_name
  427. self.clip = "clip_{}".format(self.clip_name)
  428. setattr(self, self.clip, tokenizer(embedding_directory=embedding_directory))
  429. def tokenize_with_weights(self, text:str, return_word_ids=False):
  430. out = {}
  431. out[self.clip_name] = getattr(self, self.clip).tokenize_with_weights(text, return_word_ids)
  432. return out
  433. def untokenize(self, token_weight_pair):
  434. return getattr(self, self.clip).untokenize(token_weight_pair)
  435. class SD1ClipModel(torch.nn.Module):
  436. def __init__(self, device="cpu", dtype=None, clip_name="l", clip_model=SDClipModel, **kwargs):
  437. super().__init__()
  438. self.clip_name = clip_name
  439. self.clip = "clip_{}".format(self.clip_name)
  440. setattr(self, self.clip, clip_model(device=device, dtype=dtype, **kwargs))
  441. def clip_layer(self, layer_idx):
  442. getattr(self, self.clip).clip_layer(layer_idx)
  443. def reset_clip_layer(self):
  444. getattr(self, self.clip).reset_clip_layer()
  445. def encode_token_weights(self, token_weight_pairs):
  446. token_weight_pairs = token_weight_pairs[self.clip_name]
  447. out, pooled = getattr(self, self.clip).encode_token_weights(token_weight_pairs)
  448. return out, pooled
  449. def load_sd(self, sd):
  450. return getattr(self, self.clip).load_sd(sd)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...