File size: 58,339 Bytes
44eca84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1028385
 
 
16db48a
 
 
1028385
 
 
 
 
44eca84
 
 
70d7fbb
44eca84
 
 
 
 
f22aece
1028385
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19fa3ec
 
a78db43
 
1028385
 
a78db43
1028385
 
a407d29
 
1028385
 
 
19fa3ec
a78db43
19fa3ec
 
 
 
 
abc0b46
 
551a5a7
 
 
abc0b46
a78db43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44eca84
 
38a8e51
a78db43
70d7fbb
44eca84
70d7fbb
 
44eca84
16db48a
 
 
 
 
 
 
540a0c2
 
16db48a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a78db43
16db48a
540a0c2
 
16db48a
 
 
540a0c2
 
 
 
16db48a
 
 
 
 
 
 
 
 
 
 
 
 
a78db43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16db48a
 
 
 
 
 
 
a78db43
16db48a
 
a78db43
 
 
 
16db48a
540a0c2
16db48a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
540a0c2
16db48a
 
 
 
 
 
 
 
a78db43
16db48a
a78db43
 
 
16db48a
 
 
 
 
 
 
 
a78db43
16db48a
 
 
 
 
 
70d7fbb
 
16db48a
 
 
 
04ba1c9
 
 
 
 
540a0c2
04ba1c9
 
 
 
 
 
 
 
 
 
 
 
540a0c2
04ba1c9
 
 
 
 
 
 
 
 
 
 
 
 
70d7fbb
 
540a0c2
 
 
 
 
 
 
70d7fbb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
540a0c2
70d7fbb
540a0c2
70d7fbb
540a0c2
70d7fbb
540a0c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70d7fbb
540a0c2
04ba1c9
 
 
 
16db48a
 
 
 
 
 
 
 
 
44eca84
 
 
19fa3ec
1028385
 
fa58912
811a69b
fa58912
1028385
 
8833bbc
19fa3ec
 
 
 
 
 
 
04ba1c9
 
19fa3ec
e754fde
16db48a
19fa3ec
 
 
 
 
 
8833bbc
 
fa58912
 
 
 
 
 
 
 
 
 
 
19fa3ec
 
 
1028385
 
04ba1c9
 
1028385
e754fde
19fa3ec
8833bbc
1028385
 
 
19fa3ec
8833bbc
abc0b46
8833bbc
44eca84
551a5a7
 
 
 
 
 
 
 
fa58912
8833bbc
 
 
 
 
 
 
fa58912
 
 
 
 
 
 
 
 
 
 
8833bbc
 
 
fa58912
8833bbc
 
eabd9f8
8833bbc
 
 
fa58912
8833bbc
551a5a7
8833bbc
 
38a8e51
04ba1c9
 
8833bbc
e754fde
 
8833bbc
 
 
 
 
19fa3ec
8833bbc
1028385
 
 
 
44eca84
33824cf
 
1028385
44eca84
fa58912
 
 
 
 
 
 
 
 
1028385
 
8833bbc
fa58912
8833bbc
fa58912
8833bbc
551a5a7
 
 
44eca84
 
38a8e51
04ba1c9
 
44eca84
e754fde
 
38a8e51
 
 
 
 
 
 
44eca84
1028385
 
 
19fa3ec
9fb003c
 
 
 
8833bbc
9fb003c
1028385
811a69b
9fb003c
 
 
 
 
 
 
551a5a7
 
 
1028385
 
8833bbc
04ba1c9
 
1028385
e754fde
 
1028385
44eca84
 
 
551a5a7
19fa3ec
8ad9fee
44eca84
 
8ad9fee
44eca84
551a5a7
 
 
44eca84
 
38a8e51
04ba1c9
 
19fa3ec
e754fde
 
19fa3ec
2b7496e
 
 
 
 
16db48a
2b7496e
 
 
16db48a
2b7496e
16db48a
2b7496e
 
 
16db48a
2b7496e
 
 
 
 
 
 
 
 
 
 
16db48a
2b7496e
16db48a
2b7496e
16db48a
2b7496e
16db48a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b7496e
19fa3ec
 
16db48a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19fa3ec
70d7fbb
 
 
2b7496e
 
 
 
44eca84
 
 
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "This Notebook is a Stable-diffusion tool which allows you to find similiar tokens from the SD 1.5 vocab.json that you can use for text-to-image generation. Try this Free online SD 1.5 generator with the results: https://perchance.org/fusion-ai-image-generator\n",
        "\n",
        "Scroll to the bottom of the notebook to see the guide for how this works."
      ],
      "metadata": {
        "id": "L7JTcbOdBPfh"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# @title ✳️ Load/initialize values\n",
        "# Load the tokens into the colab\n",
        "!git clone https://huggingface.co/datasets/codeShare/sd_tokens\n",
        "import torch\n",
        "from torch import linalg as LA\n",
        "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
        "%cd /content/sd_tokens\n",
        "token = torch.load('sd15_tensors.pt', map_location=device, weights_only=True)\n",
        "#-----#\n",
        "\n",
        "#Import the vocab.json\n",
        "import json\n",
        "import pandas as pd\n",
        "with open('vocab.json', 'r') as f:\n",
        "    data = json.load(f)\n",
        "\n",
        "_df = pd.DataFrame({'count': data})['count']\n",
        "\n",
        "vocab = {\n",
        "    value: key for key, value in _df.items()\n",
        "}\n",
        "#-----#\n",
        "\n",
        "# Define functions/constants\n",
        "NUM_TOKENS = 49407\n",
        "\n",
        "def absolute_value(x):\n",
        "    return max(x, -x)\n",
        "\n",
        "\n",
        "def token_similarity(A, B):\n",
        "\n",
        "  #Vector length#\n",
        "  _A = LA.vector_norm(A, ord=2)\n",
        "  _B = LA.vector_norm(B, ord=2)\n",
        "\n",
        "  #----#\n",
        "  result = torch.dot(A,B)/(_A*_B)\n",
        "  #similarity_pcnt = absolute_value(result.item()*100)\n",
        "  similarity_pcnt = result.item()*100\n",
        "  similarity_pcnt_aprox = round(similarity_pcnt, 3)\n",
        "  result = f'{similarity_pcnt_aprox} %'\n",
        "  return result\n",
        "\n",
        "\n",
        "def similarity(id_A , id_B):\n",
        "  #Tensors\n",
        "  A = token[id_A]\n",
        "  B = token[id_B]\n",
        "  return token_similarity(A, B)\n",
        "#----#\n",
        "\n",
        "#print(vocab[8922]) #the vocab item for ID 8922\n",
        "#print(token[8922].shape)  #dimension of the token\n",
        "\n",
        "mix_with = \"\"\n",
        "mix_method = \"None\"\n",
        "\n",
        "#-------------#\n",
        "# UNUSED\n",
        "\n",
        "# Get the 10 lowest values from a tensor as a string\n",
        "def get_valleys (A):\n",
        "  sorted, indices = torch.sort(A,dim=0 , descending=False)\n",
        "  result = \"{\"\n",
        "  for index in range(10):\n",
        "    id = indices[index].item()\n",
        "    result = result + f\"{id}\"\n",
        "    if(index<9):\n",
        "      result = result + \",\"\n",
        "  result = result + \"}\"\n",
        "  return result\n",
        "\n",
        "# Get the 10 highest values from a tensor as a string\n",
        "def get_peaks (A):\n",
        "  sorted, indices = torch.sort(A,dim=0 , descending=True)\n",
        "  result = \"{\"\n",
        "  for index in range(10):\n",
        "    id = indices[index].item()\n",
        "    result = result + f\"{id}\"\n",
        "    if(index<9):\n",
        "      result = result + \",\"\n",
        "  result = result + \"}\"\n",
        "  return result"
      ],
      "metadata": {
        "id": "Ch9puvwKH1s3",
        "collapsed": true,
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# @title ⚡ Get similiar tokens\n",
        "from transformers import AutoTokenizer\n",
        "tokenizer = AutoTokenizer.from_pretrained(\"openai/clip-vit-large-patch14\", clean_up_tokenization_spaces = False)\n",
        "\n",
        "# @markdown Write name of token to match against\n",
        "prompt= \"banana\" # @param {type:'string',\"placeholder\":\"leave empty for random value token\"}\n",
        "\n",
        "tokenizer_output = tokenizer(text = prompt)\n",
        "input_ids = tokenizer_output['input_ids']\n",
        "print(input_ids)\n",
        "\n",
        "\n",
        "#The prompt will be enclosed with the <|start-of-text|> and <|end-of-text|> tokens, which is why output will be [49406, ... , 49407].\n",
        "\n",
        "#You can leave the 'prompt' field empty to get a random value tensor. Since the tensor is random value, it will not correspond to any tensor in the vocab.json list , and this it will have no ID.\n",
        "\n",
        "id_A = input_ids[1]\n",
        "A = token[id_A]\n",
        "_A = LA.vector_norm(A, ord=2)\n",
        "\n",
        "#if no imput exists we just randomize the entire thing\n",
        "if (prompt == \"\"):\n",
        "  id_A = -1\n",
        "  print(\"Tokenized prompt tensor A is a random valued tensor with no ID\")\n",
        "  R = torch.rand(768)\n",
        "  _R =  LA.vector_norm(R, ord=2)\n",
        "  A = R*(_A/_R)\n",
        "  name_A = 'random_A'\n",
        "\n",
        "# @markdown (optional) Mix the token with something else\n",
        "mix_with = \"\" # @param {\"type\":\"string\",\"placeholder\":\"leave empty for random value token\"}\n",
        "mix_method = \"None\" # @param [\"None\" , \"Average\", \"Subtract\"] {allow-input: true}\n",
        "w = 0.5 # @param {type:\"slider\", min:0, max:1, step:0.01}\n",
        "\n",
        "# @markdown Limit char size of included token\n",
        "min_char_size = 3 # @param {type:\"slider\", min:0, max: 50, step:1}\n",
        "char_range = 5 # @param {type:\"slider\", min:0, max: 50, step:1}\n",
        "\n",
        "tokenizer_output = tokenizer(text = mix_with)\n",
        "input_ids = tokenizer_output['input_ids']\n",
        "id_C = input_ids[1]\n",
        "C = token[id_C]\n",
        "_C = LA.vector_norm(C, ord=2)\n",
        "\n",
        "#if no imput exists we just randomize the entire thing\n",
        "if (mix_with == \"\"):\n",
        "  id_C = -1\n",
        "  print(\"Tokenized prompt  'mix_with' tensor C is a random valued tensor with no ID\")\n",
        "  R = torch.rand(768)\n",
        "  _R =  LA.vector_norm(R, ord=2)\n",
        "  C = R*(_C/_R)\n",
        "  name_C = 'random_C'\n",
        "\n",
        "name_A = \"A of random type\"\n",
        "if (id_A>-1):\n",
        "  name_A = vocab[id_A]\n",
        "\n",
        "name_C = \"token C of random type\"\n",
        "if (id_C>-1):\n",
        "  name_C = vocab[id_C]\n",
        "\n",
        "# Peaks feature\n",
        "#peaks_A = get_valleys(A)\n",
        "#peaks_C = get_valleys(C)\n",
        "#print(f\"The elementwise top 10 highest values for A is at indices {peaks_A}\")\n",
        "#print(\"-------\")\n",
        "#print(f\"The elementwise top 10 highest values for C is at indices {peaks_C}\")\n",
        "#print(\"-------\")\n",
        "#//------//\n",
        "\n",
        "print(f\"The similarity between A '{name_A}' and C '{name_C}' is {token_similarity(A, C)}\")\n",
        "\n",
        "if (mix_method ==  \"None\"):\n",
        "  print(\"No operation\")\n",
        "\n",
        "if (mix_method ==  \"Average\"):\n",
        "  A = w*A + (1-w)*C\n",
        "  _A = LA.vector_norm(A, ord=2)\n",
        "  print(f\"Tokenized prompt tensor A '{name_A}' token has been recalculated as A = w*A + (1-w)*C , where C is '{name_C}' token , for w = {w}  \")\n",
        "\n",
        "if (mix_method ==  \"Subtract\"):\n",
        "  tmp =  w*A - (1-w)*C\n",
        "  _tmp =  LA.vector_norm(tmp, ord=2)\n",
        "  A = (_A/_tmp)*tmp\n",
        "  #//---//\n",
        "  _A = LA.vector_norm(A, ord=2)\n",
        "  print(f\"Tokenized prompt tensor A '{name_A}' token has been recalculated as A = _A*norm(w*A  - (1-w)*C) , where C is '{name_C}' token , for w = {w} \")\n",
        "\n",
        "#OPTIONAL : Add/subtract + normalize above result with another token. Leave field empty to get a random value tensor\n",
        "\n",
        "dots = torch.zeros(NUM_TOKENS)\n",
        "for index in range(NUM_TOKENS):\n",
        "  id_B = index\n",
        "  B = token[id_B]\n",
        "  _B = LA.vector_norm(B, ord=2)\n",
        "  result = torch.dot(A,B)/(_A*_B)\n",
        "  #result = absolute_value(result.item())\n",
        "  result = result.item()\n",
        "  dots[index] = result\n",
        "\n",
        "\n",
        "sorted, indices = torch.sort(dots,dim=0 , descending=True)\n",
        "#----#\n",
        "if (mix_method ==  \"Average\"):\n",
        "  print(f'Calculated all cosine-similarities between the average of token {name_A} and {name_C} with Id_A = {id_A} and mixed Id_C = {id_C} as a 1x{sorted.shape[0]} tensor')\n",
        "if (mix_method ==  \"Subtract\"):\n",
        "  print(f'Calculated all cosine-similarities between the subtract of token {name_A} and {name_C} with Id_A = {id_A} and mixed Id_C = {id_C} as a 1x{sorted.shape[0]} tensor')\n",
        "if (mix_method ==  \"None\"):\n",
        "  print(f'Calculated all cosine-similarities between the token {name_A} with Id_A = {id_A} with the the rest of the {NUM_TOKENS} tokens as a 1x{sorted.shape[0]} tensor')\n",
        "\n",
        "#Produce a list id IDs that are most similiar to the prompt ID at positiion 1 based on above result\n",
        "\n",
        "# @markdown Set print options\n",
        "list_size = 100 # @param {type:'number'}\n",
        "print_ID = False # @param {type:\"boolean\"}\n",
        "print_Similarity = True # @param {type:\"boolean\"}\n",
        "print_Name = True # @param {type:\"boolean\"}\n",
        "print_Divider = True # @param {type:\"boolean\"}\n",
        "\n",
        "\n",
        "if (print_Divider):\n",
        "  print('//---//')\n",
        "\n",
        "print('')\n",
        "print('Here is the result : ')\n",
        "print('')\n",
        "\n",
        "for index in range(list_size):\n",
        "  id = indices[index].item()\n",
        "  if (print_Name):\n",
        "    print(f'{vocab[id]}') # vocab item\n",
        "  if (print_ID):\n",
        "    print(f'ID = {id}') # IDs\n",
        "  if (print_Similarity):\n",
        "    print(f'similiarity = {round(sorted[index].item()*100,2)} %')\n",
        "  if (print_Divider):\n",
        "    print('--------')\n",
        "\n",
        "#Print the sorted list from above result"
      ],
      "metadata": {
        "id": "iWeFnT1gAx6A",
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# @title 💫 Compare Text encodings\n",
        "\n",
        "prompt_A = \"banana\" # @param {\"type\":\"string\",\"placeholder\":\"Write a prompt\"}\n",
        "prompt_B = \"\" # @param {\"type\":\"string\",\"placeholder\":\"Write a prompt\"}\n",
        "use_token_padding = True # @param {type:\"boolean\"}\n",
        "\n",
        "from transformers import  CLIPProcessor, CLIPModel\n",
        "\n",
        "processor = CLIPProcessor.from_pretrained(\"openai/clip-vit-large-patch14\" , clean_up_tokenization_spaces = True)\n",
        "\n",
        "model = CLIPModel.from_pretrained(\"openai/clip-vit-large-patch14\")\n",
        "\n",
        "ids_A = processor.tokenizer(text=prompt_A, padding=use_token_padding, return_tensors=\"pt\")\n",
        "text_encoding_A = model.get_text_features(**ids_A)\n",
        "\n",
        "\n",
        "ids_B = processor.tokenizer(text=prompt_B, padding=use_token_padding, return_tensors=\"pt\")\n",
        "text_encoding_B = model.get_text_features(**ids_B)\n",
        "\n",
        "similarity_str =  'The similarity between the text_encoding for A:\"' + prompt_A + '\" and B: \"' + prompt_B +'\" is ' +  token_similarity(text_encoding_A[0] , text_encoding_B[0])\n",
        "\n",
        "\n",
        "print(similarity_str)\n",
        "#outputs = model(**inputs)\n",
        "#logits_per_image = outputs.logits_per_image # this is the image-text similarity score\n",
        "#probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities"
      ],
      "metadata": {
        "id": "QQOjh5BvnG8M",
        "collapsed": true,
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# @title 🪐🖼️ -> 📝 Image to prompt : Add single token to existing prompt to match image\n",
        "from google.colab import files\n",
        "def getLocalFiles():\n",
        "    _files = files.upload()\n",
        "    if len(_files) >0:\n",
        "       for k,v in _files.items():\n",
        "         open(k,'wb').write(v)\n",
        "\n",
        "#Get image\n",
        "# You can use \"http://images.cocodataset.org/val2017/000000039769.jpg\" for testing\n",
        "url = \"http://images.cocodataset.org/val2017/000000039769.jpg\" # @param {\"type\":\"string\",\"placeholder\":\"leave empty for local upload\"}\n",
        "from PIL import Image\n",
        "import requests\n",
        "if url == \"\":\n",
        "  image_A = getLocalFiles()\n",
        "else:\n",
        "  image_A = Image.open(requests.get(url, stream=True).raw)\n",
        "\n",
        "\n",
        "# Get image features\n",
        "from transformers import  CLIPProcessor, CLIPModel\n",
        "processor = CLIPProcessor.from_pretrained(\"openai/clip-vit-large-patch14\" , clean_up_tokenization_spaces = True)\n",
        "model = CLIPModel.from_pretrained(\"openai/clip-vit-large-patch14\")\n",
        "inputs = processor(images=image_A, return_tensors=\"pt\")\n",
        "image_features = model.get_image_features(**inputs)\n",
        "text_encoding_A = image_features\n",
        "A =  text_encoding_A[0]\n",
        "_A = LA.vector_norm(A, ord=2)\n",
        "prompt_A = \"the image\"\n",
        "name_A = prompt_A\n",
        "#-----#\n",
        "\n",
        "# @markdown Set conditions for the output\n",
        "must_start_with = \"\" # @param {\"type\":\"string\",\"placeholder\":\"write a text\"}\n",
        "must_contain = \"\" # @param {\"type\":\"string\",\"placeholder\":\"write a text\"}\n",
        "must_end_with = \"\" # @param {\"type\":\"string\",\"placeholder\":\"write a text\"}\n",
        "token_B = must_contain\n",
        "\n",
        "# @markdown Limit the search\n",
        "use_token_padding = True # @param {type:\"boolean\"}\n",
        "start_search_at_ID = 12500 # @param {type:\"slider\", min:0, max: 49407, step:100}\n",
        "search_range = 500 # @param {type:\"slider\", min:0, max: 2000, step:100}\n",
        "restrictions = 'Suffix only' # @param [\"None\", \"Suffix only\", \"Prefix only\"]\n",
        "\n",
        "# @markdown Limit char size of included token\n",
        "min_char_size = 3 # @param {type:\"slider\", min:0, max: 50, step:1}\n",
        "char_range = 5 # @param {type:\"slider\", min:0, max: 50, step:1}\n",
        "\n",
        "#Tokenize input B\n",
        "from transformers import AutoTokenizer\n",
        "tokenizer = AutoTokenizer.from_pretrained(\"openai/clip-vit-large-patch14\", clean_up_tokenization_spaces = False)\n",
        "tokenizer_output = tokenizer(text = token_B)\n",
        "input_ids = tokenizer_output['input_ids']\n",
        "#-----#\n",
        "name_B = must_contain\n",
        "#-----#\n",
        "\n",
        "START = start_search_at_ID\n",
        "RANGE =  min(search_range , 49407 - start_search_at_ID)\n",
        "\n",
        "dots = torch.zeros(RANGE)\n",
        "is_BC = torch.zeros(RANGE)\n",
        "for index in range(RANGE):\n",
        "  id_C = START + index\n",
        "  C = token[id_C]\n",
        "  _C = LA.vector_norm(C, ord=2)\n",
        "  name_C = vocab[id_C]\n",
        "\n",
        "  # Decide if we should process prefix/suffix tokens\n",
        "  if name_C.find('</w>')<=-1:\n",
        "    if restrictions != \"Prefix only\":\n",
        "      continue\n",
        "  else:\n",
        "    if restrictions == \"Prefix only\":\n",
        "      continue\n",
        "  #-----#\n",
        "\n",
        "  # Decide if char-size is within range\n",
        "  if len(name_C) < min_char_size:\n",
        "    continue\n",
        "  if len(name_C) > min_char_size + char_range:\n",
        "    continue\n",
        "  #-----#\n",
        "\n",
        "  name_CB = must_start_with + name_C + name_B + must_end_with\n",
        "  if restrictions == \"Prefix only\":\n",
        "    name_CB = must_start_with +  name_C + '-' + name_B + must_end_with\n",
        "  #-----#\n",
        "  ids_CB = processor.tokenizer(text=name_CB, padding=use_token_padding, return_tensors=\"pt\")\n",
        "  text_encoding_CB = model.get_text_features(**ids_CB)\n",
        "  CB = text_encoding_CB[0]\n",
        "  _CB =  LA.vector_norm(CB, ord=2)\n",
        "  sim_CB = torch.dot(A,CB)/(_A*_CB)\n",
        "  #-----#\n",
        "  if restrictions == \"Prefix only\":\n",
        "    result = sim_CB\n",
        "    result = result.item()\n",
        "    dots[index] = result\n",
        "    continue\n",
        "  #-----#\n",
        "  name_BC = must_start_with + name_B + name_C + must_end_with\n",
        "  ids_BC = processor.tokenizer(text=name_BC, padding=use_token_padding, return_tensors=\"pt\")\n",
        "  text_encoding_BC = model.get_text_features(**ids_BC)\n",
        "  BC = text_encoding_BC[0]\n",
        "  _BC =  LA.vector_norm(BC, ord=2)\n",
        "  sim_BC = torch.dot(A,BC)/(_A*_BC)\n",
        "  #-----#\n",
        "\n",
        "  result = sim_CB\n",
        "  if(sim_BC > sim_CB):\n",
        "    is_BC[index] = 1\n",
        "    result = sim_BC\n",
        "\n",
        "  #result = absolute_value(result.item())\n",
        "  result = result.item()\n",
        "  dots[index] = result\n",
        "#----#\n",
        "\n",
        "sorted, indices = torch.sort(dots,dim=0 , descending=True)\n",
        "\n",
        "# @markdown Print options\n",
        "list_size = 100 # @param {type:'number'}\n",
        "print_ID = False # @param {type:\"boolean\"}\n",
        "print_Similarity = True # @param {type:\"boolean\"}\n",
        "print_Name = True # @param {type:\"boolean\"}\n",
        "print_Divider = True # @param {type:\"boolean\"}\n",
        "\n",
        "\n",
        "if (print_Divider):\n",
        "  print('//---//')\n",
        "\n",
        "print('')\n",
        "print(f'These token pairings within the range ID = {START} to ID = {START + RANGE} most closely match the text_encoding for {prompt_A} : ')\n",
        "print('')\n",
        "\n",
        "for index in range(min(list_size,RANGE)):\n",
        "  id = START + indices[index].item()\n",
        "  if (print_Name):\n",
        "    if(is_BC[index]>0):\n",
        "      print(must_start_with +  name_B + vocab[id] + must_end_with)\n",
        "    else:\n",
        "      if restrictions == \"Prefix only\":\n",
        "        print(must_start_with +   vocab[id] + '-'  + name_B + must_end_with)\n",
        "      else:\n",
        "        print(must_start_with +   vocab[id] + name_B + must_end_with)\n",
        "  if (print_ID):\n",
        "    print(f'ID = {id}') # IDs\n",
        "  if (print_Similarity):\n",
        "    print(f'similiarity = {round(sorted[index].item()*100,2)} %')\n",
        "  if (print_Divider):\n",
        "    print('--------')\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "\n"
      ],
      "metadata": {
        "collapsed": true,
        "cellView": "form",
        "id": "fi0jRruI0-tu",
        "outputId": "6d7e8c39-a117-4b35-acfe-2a128c65aeb7",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "execution_count": 9,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "//---//\n",
            "\n",
            "These token pairings within the range ID = 12500 to ID = 13000 most closely match the text_encoding for the prompt \"the image\" : \n",
            "\n",
            "sits</w>yellow\n",
            "similiarity = 23.02 %\n",
            "--------\n",
            "neys</w>yellow\n",
            "similiarity = 19.74 %\n",
            "--------\n",
            "cody</w>yellow\n",
            "similiarity = 18.61 %\n",
            "--------\n",
            "wns</w>yellow\n",
            "similiarity = 18.43 %\n",
            "--------\n",
            "java</w>yellow\n",
            "similiarity = 18.15 %\n",
            "--------\n",
            "jj</w>yellow\n",
            "similiarity = 18.03 %\n",
            "--------\n",
            "eno</w>yellow\n",
            "similiarity = 17.87 %\n",
            "--------\n",
            "cled</w>yellow\n",
            "similiarity = 17.85 %\n",
            "--------\n",
            "nom</w>yellow\n",
            "similiarity = 17.75 %\n",
            "--------\n",
            "dads</w>yellow\n",
            "similiarity = 17.5 %\n",
            "--------\n",
            "mil</w>yellow\n",
            "similiarity = 17.47 %\n",
            "--------\n",
            "whom</w>yellow\n",
            "similiarity = 17.37 %\n",
            "--------\n",
            "itv</w>yellow\n",
            "similiarity = 17.34 %\n",
            "--------\n",
            "vibe</w>yellow\n",
            "similiarity = 17.2 %\n",
            "--------\n",
            "noir</w>yellow\n",
            "similiarity = 17.14 %\n",
            "--------\n",
            "yellowarel</w>\n",
            "similiarity = 17.1 %\n",
            "--------\n",
            "#âĢ¦</w>yellow\n",
            "similiarity = 17.04 %\n",
            "--------\n",
            "maya</w>yellow\n",
            "similiarity = 17.03 %\n",
            "--------\n",
            "yellowbam</w>\n",
            "similiarity = 17.01 %\n",
            "--------\n",
            "erts</w>yellow\n",
            "similiarity = 17.01 %\n",
            "--------\n",
            "xc</w>yellow\n",
            "similiarity = 16.98 %\n",
            "--------\n",
            "mob</w>yellow\n",
            "similiarity = 16.89 %\n",
            "--------\n",
            "dees</w>yellow\n",
            "similiarity = 16.87 %\n",
            "--------\n",
            "icc</w>yellow\n",
            "similiarity = 16.75 %\n",
            "--------\n",
            "aly</w>yellow\n",
            "similiarity = 16.63 %\n",
            "--------\n",
            "lis</w>yellow\n",
            "similiarity = 16.63 %\n",
            "--------\n",
            "yellowturf</w>\n",
            "similiarity = 16.62 %\n",
            "--------\n",
            "yellowbaba</w>\n",
            "similiarity = 16.58 %\n",
            "--------\n",
            ":*</w>yellow\n",
            "similiarity = 16.42 %\n",
            "--------\n",
            "inho</w>yellow\n",
            "similiarity = 16.39 %\n",
            "--------\n",
            "yellowhes</w>\n",
            "similiarity = 16.37 %\n",
            "--------\n",
            "nity</w>yellow\n",
            "similiarity = 16.3 %\n",
            "--------\n",
            "lust</w>yellow\n",
            "similiarity = 16.3 %\n",
            "--------\n",
            "ikh</w>yellow\n",
            "similiarity = 16.26 %\n",
            "--------\n",
            "nyt</w>yellow\n",
            "similiarity = 16.24 %\n",
            "--------\n",
            "(+</w>yellow\n",
            "similiarity = 16.11 %\n",
            "--------\n",
            "foto</w>yellow\n",
            "similiarity = 16.11 %\n",
            "--------\n",
            "stl</w>yellow\n",
            "similiarity = 16.06 %\n",
            "--------\n",
            "mick</w>yellow\n",
            "similiarity = 16.06 %\n",
            "--------\n",
            "...@</w>yellow\n",
            "similiarity = 16.05 %\n",
            "--------\n",
            "ugh</w>yellow\n",
            "similiarity = 16.05 %\n",
            "--------\n",
            "gro</w>yellow\n",
            "similiarity = 16.01 %\n",
            "--------\n",
            "wski</w>yellow\n",
            "similiarity = 16.01 %\n",
            "--------\n",
            "ðŁĴ«</w>yellow\n",
            "similiarity = 15.74 %\n",
            "--------\n",
            "deen</w>yellow\n",
            "similiarity = 15.73 %\n",
            "--------\n",
            "assy</w>yellow\n",
            "similiarity = 15.72 %\n",
            "--------\n",
            "mtv</w>yellow\n",
            "similiarity = 15.72 %\n",
            "--------\n",
            "yellowðŁĺ»</w>\n",
            "similiarity = 15.72 %\n",
            "--------\n",
            "yellowfrm</w>\n",
            "similiarity = 15.65 %\n",
            "--------\n",
            "moss</w>yellow\n",
            "similiarity = 15.64 %\n",
            "--------\n",
            "bart</w>yellow\n",
            "similiarity = 15.61 %\n",
            "--------\n",
            "tw</w>yellow\n",
            "similiarity = 15.51 %\n",
            "--------\n",
            "yellowplug</w>\n",
            "similiarity = 15.46 %\n",
            "--------\n",
            "jen</w>yellow\n",
            "similiarity = 15.45 %\n",
            "--------\n",
            "pst</w>yellow\n",
            "similiarity = 15.43 %\n",
            "--------\n",
            "omfg</w>yellow\n",
            "similiarity = 15.43 %\n",
            "--------\n",
            "dine</w>yellow\n",
            "similiarity = 15.38 %\n",
            "--------\n",
            "vern</w>yellow\n",
            "similiarity = 15.33 %\n",
            "--------\n",
            "reno</w>yellow\n",
            "similiarity = 15.25 %\n",
            "--------\n",
            "yellow´</w>\n",
            "similiarity = 15.14 %\n",
            "--------\n",
            "omic</w>yellow\n",
            "similiarity = 15.14 %\n",
            "--------\n",
            "łï¸ı</w>yellow\n",
            "similiarity = 15.11 %\n",
            "--------\n",
            "yellowgis</w>\n",
            "similiarity = 15.06 %\n",
            "--------\n",
            "aunt</w>yellow\n",
            "similiarity = 15.0 %\n",
            "--------\n",
            "joan</w>yellow\n",
            "similiarity = 14.96 %\n",
            "--------\n",
            "anas</w>yellow\n",
            "similiarity = 14.92 %\n",
            "--------\n",
            "ðŁĴĵ</w>yellow\n",
            "similiarity = 14.9 %\n",
            "--------\n",
            "chad</w>yellow\n",
            "similiarity = 14.89 %\n",
            "--------\n",
            "yellowsake</w>\n",
            "similiarity = 14.88 %\n",
            "--------\n",
            "gues</w>yellow\n",
            "similiarity = 14.84 %\n",
            "--------\n",
            "gian</w>yellow\n",
            "similiarity = 14.84 %\n",
            "--------\n",
            "asi</w>yellow\n",
            "similiarity = 14.83 %\n",
            "--------\n",
            "yellowoven</w>\n",
            "similiarity = 14.82 %\n",
            "--------\n",
            "jury</w>yellow\n",
            "similiarity = 14.79 %\n",
            "--------\n",
            "blvd</w>yellow\n",
            "similiarity = 14.75 %\n",
            "--------\n",
            "omez</w>yellow\n",
            "similiarity = 14.72 %\n",
            "--------\n",
            "yellowyang</w>\n",
            "similiarity = 14.7 %\n",
            "--------\n",
            "gu</w>yellow\n",
            "similiarity = 14.48 %\n",
            "--------\n",
            "yellowova</w>\n",
            "similiarity = 14.45 %\n",
            "--------\n",
            "yellowinez</w>\n",
            "similiarity = 14.44 %\n",
            "--------\n",
            "pei</w>yellow\n",
            "similiarity = 14.44 %\n",
            "--------\n",
            "ãĢIJ</w>yellow\n",
            "similiarity = 14.43 %\n",
            "--------\n",
            "ãĢij</w>yellow\n",
            "similiarity = 14.43 %\n",
            "--------\n",
            "ðŁĮŀ</w>yellow\n",
            "similiarity = 14.36 %\n",
            "--------\n",
            "ðŁĺĿ</w>yellow\n",
            "similiarity = 14.27 %\n",
            "--------\n",
            "troy</w>yellow\n",
            "similiarity = 14.16 %\n",
            "--------\n",
            "pale</w>yellow\n",
            "similiarity = 14.14 %\n",
            "--------\n",
            "boi</w>yellow\n",
            "similiarity = 14.11 %\n",
            "--------\n",
            "nn</w>yellow\n",
            "similiarity = 14.08 %\n",
            "--------\n",
            "âı°</w>yellow\n",
            "similiarity = 14.01 %\n",
            "--------\n",
            "ooth</w>yellow\n",
            "similiarity = 13.93 %\n",
            "--------\n",
            "pied</w>yellow\n",
            "similiarity = 13.9 %\n",
            "--------\n",
            "bola</w>yellow\n",
            "similiarity = 13.79 %\n",
            "--------\n",
            "âŀ¡</w>yellow\n",
            "similiarity = 13.77 %\n",
            "--------\n",
            "rena</w>yellow\n",
            "similiarity = 13.75 %\n",
            "--------\n",
            "dley</w>yellow\n",
            "similiarity = 13.73 %\n",
            "--------\n",
            "evan</w>yellow\n",
            "similiarity = 13.67 %\n",
            "--------\n",
            "pony</w>yellow\n",
            "similiarity = 13.63 %\n",
            "--------\n",
            "rene</w>yellow\n",
            "similiarity = 13.62 %\n",
            "--------\n",
            "mock</w>yellow\n",
            "similiarity = 13.57 %\n",
            "--------\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# @title 🪐📝 Prompt to prompt : Add single token to existing prompt to match another prompt\n",
        "# @markdown Write a text to match against...\n",
        "prompt_A = \"photo of a banana\" # @param {\"type\":\"string\",\"placeholder\":\"Write a prompt\"}\n",
        "\n",
        "# @markdown Set conditions for the output\n",
        "must_start_with = \"\" # @param {\"type\":\"string\",\"placeholder\":\"write a text\"}\n",
        "must_contain = \"yellow\" # @param {\"type\":\"string\",\"placeholder\":\"write a text\"}\n",
        "must_end_with = \"\" # @param {\"type\":\"string\",\"placeholder\":\"write a text\"}\n",
        "token_B = must_contain\n",
        "\n",
        "# @markdown Limit the search\n",
        "use_token_padding = True # @param {type:\"boolean\"}\n",
        "start_search_at_ID = 12500 # @param {type:\"slider\", min:0, max: 49407, step:100}\n",
        "search_range = 500 # @param {type:\"slider\", min:0, max: 2000, step:100}\n",
        "restrictions = 'Suffix only' # @param [\"None\", \"Suffix only\", \"Prefix only\"]\n",
        "\n",
        "# @markdown Limit char size of included token\n",
        "min_char_size = 3 # @param {type:\"slider\", min:0, max: 50, step:1}\n",
        "char_range = 5 # @param {type:\"slider\", min:0, max: 50, step:1}\n",
        "\n",
        "#Tokenize input B\n",
        "from transformers import AutoTokenizer\n",
        "tokenizer = AutoTokenizer.from_pretrained(\"openai/clip-vit-large-patch14\", clean_up_tokenization_spaces = False)\n",
        "tokenizer_output = tokenizer(text = token_B)\n",
        "input_ids = tokenizer_output['input_ids']\n",
        "#-----#\n",
        "name_B = must_contain\n",
        "#-----#\n",
        "\n",
        "from transformers import  CLIPProcessor, CLIPModel\n",
        "processor = CLIPProcessor.from_pretrained(\"openai/clip-vit-large-patch14\" , clean_up_tokenization_spaces = True)\n",
        "model = CLIPModel.from_pretrained(\"openai/clip-vit-large-patch14\")\n",
        "#-------#\n",
        "ids_A = processor.tokenizer(text=prompt_A, padding=use_token_padding, return_tensors=\"pt\")\n",
        "text_encoding_A = model.get_text_features(**ids_A)\n",
        "A =  text_encoding_A[0]\n",
        "_A = LA.vector_norm(A, ord=2)\n",
        "name_A = prompt_A\n",
        "print(f'a text_encoding was created for the prompt \"{prompt_A}\" ')\n",
        "print('')\n",
        "#----#\n",
        "\n",
        "START = start_search_at_ID\n",
        "RANGE =  min(search_range , 49407 - start_search_at_ID)\n",
        "\n",
        "dots = torch.zeros(RANGE)\n",
        "is_BC = torch.zeros(RANGE)\n",
        "for index in range(RANGE):\n",
        "  id_C = START + index\n",
        "  C = token[id_C]\n",
        "  _C = LA.vector_norm(C, ord=2)\n",
        "  name_C = vocab[id_C]\n",
        "\n",
        "  # Decide if we should process prefix/suffix tokens\n",
        "  if name_C.find('</w>')<=-1:\n",
        "    if restrictions != \"Prefix only\":\n",
        "      continue\n",
        "  else:\n",
        "    if restrictions == \"Prefix only\":\n",
        "      continue\n",
        "  #-----#\n",
        "\n",
        "  # Decide if char-size is within range\n",
        "  if len(name_C) < min_char_size:\n",
        "    continue\n",
        "  if len(name_C) > min_char_size + char_range:\n",
        "    continue\n",
        "  #-----#\n",
        "\n",
        "  name_CB = must_start_with + name_C + name_B + must_end_with\n",
        "  if restrictions == \"Prefix only\":\n",
        "    name_CB = must_start_with +  name_C + '-' + name_B + must_end_with\n",
        "  #-----#\n",
        "  ids_CB = processor.tokenizer(text=name_CB, padding=use_token_padding, return_tensors=\"pt\")\n",
        "  text_encoding_CB = model.get_text_features(**ids_CB)\n",
        "  CB = text_encoding_CB[0]\n",
        "  _CB =  LA.vector_norm(CB, ord=2)\n",
        "  sim_CB = torch.dot(A,CB)/(_A*_CB)\n",
        "  #-----#\n",
        "  if restrictions == \"Prefix only\":\n",
        "    result = sim_CB\n",
        "    result = result.item()\n",
        "    dots[index] = result\n",
        "    continue\n",
        "  #-----#\n",
        "  name_BC = must_start_with + name_B + name_C + must_end_with\n",
        "  ids_BC = processor.tokenizer(text=name_BC, padding=use_token_padding, return_tensors=\"pt\")\n",
        "  text_encoding_BC = model.get_text_features(**ids_BC)\n",
        "  BC = text_encoding_BC[0]\n",
        "  _BC =  LA.vector_norm(BC, ord=2)\n",
        "  sim_BC = torch.dot(A,BC)/(_A*_BC)\n",
        "  #-----#\n",
        "\n",
        "  result = sim_CB\n",
        "  if(sim_BC > sim_CB):\n",
        "    is_BC[index] = 1\n",
        "    result = sim_BC\n",
        "\n",
        "  #result = absolute_value(result.item())\n",
        "  result = result.item()\n",
        "  dots[index] = result\n",
        "#----#\n",
        "\n",
        "sorted, indices = torch.sort(dots,dim=0 , descending=True)\n",
        "\n",
        "# @markdown Print options\n",
        "list_size = 100 # @param {type:'number'}\n",
        "print_ID = False # @param {type:\"boolean\"}\n",
        "print_Similarity = True # @param {type:\"boolean\"}\n",
        "print_Name = True # @param {type:\"boolean\"}\n",
        "print_Divider = True # @param {type:\"boolean\"}\n",
        "\n",
        "\n",
        "if (print_Divider):\n",
        "  print('//---//')\n",
        "\n",
        "print('')\n",
        "print(f'These token pairings within the range ID = {START} to ID = {START + RANGE} most closely match the text_encoding for the prompt \"{prompt_A}\" : ')\n",
        "print('')\n",
        "\n",
        "for index in range(min(list_size,RANGE)):\n",
        "  id = START + indices[index].item()\n",
        "  if (print_Name):\n",
        "    if(is_BC[index]>0):\n",
        "      print(must_start_with +  name_B + vocab[id] + must_end_with)\n",
        "    else:\n",
        "      if restrictions == \"Prefix only\":\n",
        "        print(must_start_with +   vocab[id] + '-'  + name_B + must_end_with)\n",
        "      else:\n",
        "        print(must_start_with +   vocab[id] + name_B + must_end_with)\n",
        "  if (print_ID):\n",
        "    print(f'ID = {id}') # IDs\n",
        "  if (print_Similarity):\n",
        "    print(f'similiarity = {round(sorted[index].item()*100,2)} %')\n",
        "  if (print_Divider):\n",
        "    print('--------')"
      ],
      "metadata": {
        "cellView": "form",
        "id": "uDtcm-l8UCJk"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "#  ↓ Sub modules (use these to build your own projects) ↓"
      ],
      "metadata": {
        "id": "_d8WtPgtAymM"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# @title 📝 -> 🆔 Tokenize prompt into IDs\n",
        "from transformers import AutoTokenizer\n",
        "tokenizer = AutoTokenizer.from_pretrained(\"openai/clip-vit-large-patch14\", clean_up_tokenization_spaces = False)\n",
        "\n",
        "prompt= \"banana\" # @param {type:'string'}\n",
        "\n",
        "tokenizer_output = tokenizer(text = prompt)\n",
        "input_ids = tokenizer_output['input_ids']\n",
        "print(input_ids)\n",
        "\n",
        "\n",
        "#The prompt will be enclosed with the <|start-of-text|> and <|end-of-text|> tokens, which is why output will be [49406, ... , 49407].\n",
        "\n",
        "#You can leave the 'prompt' field empty to get a random value tensor. Since the tensor is random value, it will not correspond to any tensor in the vocab.json list , and this it will have no ID."
      ],
      "metadata": {
        "id": "RPdkYzT2_X85",
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# @title 🆔->🥢 Take the ID at index 1 from above result and get its corresponding tensor value\n",
        "\n",
        "id_A = input_ids[1]\n",
        "A = token[id_A]\n",
        "_A = LA.vector_norm(A, ord=2)\n",
        "\n",
        "#if no imput exists we just randomize the entire thing\n",
        "if (prompt == \"\"):\n",
        "  id_A = -1\n",
        "  print(\"Tokenized prompt tensor A is a random valued tensor with no ID\")\n",
        "  R = torch.rand(768)\n",
        "  _R =  LA.vector_norm(R, ord=2)\n",
        "  A = R*(_A/_R)\n",
        "\n",
        "#Save a copy of the tensor A\n",
        "id_P = id_A\n",
        "P = A\n",
        "_P = LA.vector_norm(A, ord=2)\n"
      ],
      "metadata": {
        "id": "YqdiF8DIz9Wu",
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# @title 🥢 -> 🥢🔀 Take the ID at index 1 from above result and modify it (optional)\n",
        "mix_with = \"\" # @param {type:'string'}\n",
        "mix_method = \"None\" # @param [\"None\" , \"Average\", \"Subtract\"] {allow-input: true}\n",
        "w = 0.5 # @param {type:\"slider\", min:0, max:1, step:0.01}\n",
        "\n",
        "#------#\n",
        "#If set to TRUE , this will use the output of this cell , tensor A, as the input of this cell the 2nd time we run it. Use this feature to mix many tokens into A\n",
        "re_iterate_tensor_A = True # @param {\"type\":\"boolean\"}\n",
        "if (re_iterate_tensor_A == False) :\n",
        "  #prevent re-iterating A by reading from stored copy\n",
        "  id_A = id_P\n",
        "  A = P\n",
        "  _A = _P\n",
        "#----#\n",
        "\n",
        "tokenizer_output = tokenizer(text = mix_with)\n",
        "input_ids = tokenizer_output['input_ids']\n",
        "id_C = input_ids[1]\n",
        "C = token[id_C]\n",
        "_C = LA.vector_norm(C, ord=2)\n",
        "\n",
        "#if no imput exists we just randomize the entire thing\n",
        "if (mix_with == \"\"):\n",
        "  id_C = -1\n",
        "  print(\"Tokenized prompt  'mix_with' tensor C is a random valued tensor with no ID\")\n",
        "  R = torch.rand(768)\n",
        "  _R =  LA.vector_norm(R, ord=2)\n",
        "  C = R*(_C/_R)\n",
        "\n",
        "if (mix_method ==  \"None\"):\n",
        "  print(\"No operation\")\n",
        "\n",
        "if (mix_method ==  \"Average\"):\n",
        "  A = w*A + (1-w)*C\n",
        "  _A = LA.vector_norm(A, ord=2)\n",
        "  print(\"Tokenized prompt tensor A has been recalculated as A = w*A + (1-w)*C , where C is the tokenized prompt  'mix_with' tensor C\")\n",
        "\n",
        "if (mix_method ==  \"Subtract\"):\n",
        "  tmp = (A/_A) - (C/_C)\n",
        "  _tmp = LA.vector_norm(tmp, ord=2)\n",
        "  A = tmp*((w*_A + (1-w)*_C)/_tmp)\n",
        "  _A = LA.vector_norm(A, ord=2)\n",
        "  print(\"Tokenized prompt tensor A has been recalculated as A = (w*_A + (1-w)*_C) * norm(w*A - (1-w)*C) , where C is the tokenized prompt 'mix_with' tensor C\")\n",
        "\n",
        "#OPTIONAL : Add/subtract + normalize above result with another token. Leave field empty to get a random value tensor"
      ],
      "metadata": {
        "id": "oXbNSRSKPgRr",
        "collapsed": true,
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "\n",
        "# @title 🥢->🧾🥢 Find Similiar Tokens to ID at index 1 from above result\n",
        "dots = torch.zeros(NUM_TOKENS)\n",
        "for index in range(NUM_TOKENS):\n",
        "  id_B = index\n",
        "  B = token[id_B]\n",
        "  _B = LA.vector_norm(B, ord=2)\n",
        "  result = torch.dot(A,B)/(_A*_B)\n",
        "  #result = absolute_value(result.item())\n",
        "  result = result.item()\n",
        "  dots[index] = result\n",
        "\n",
        "name_A = \"A of random type\"\n",
        "if (id_A>-1):\n",
        "  name_A = vocab[id_A]\n",
        "\n",
        "name_C = \"token C of random type\"\n",
        "if (id_C>-1):\n",
        "  name_C = vocab[id_C]\n",
        "\n",
        "\n",
        "sorted, indices = torch.sort(dots,dim=0 , descending=True)\n",
        "#----#\n",
        "if (mix_method ==  \"Average\"):\n",
        "  print(f'Calculated all cosine-similarities between the average of token {name_A} and {name_C} with Id_A = {id_A} and mixed Id_C = {id_C} as a 1x{sorted.shape[0]} tensor')\n",
        "if (mix_method ==  \"Subtract\"):\n",
        "  print(f'Calculated all cosine-similarities between the subtract of token {name_A} and {name_C} with Id_A = {id_A} and mixed Id_C = {id_C} as a 1x{sorted.shape[0]} tensor')\n",
        "if (mix_method ==  \"None\"):\n",
        "  print(f'Calculated all cosine-similarities between the token {name_A} with Id_A = {id_A} with the the rest of the {NUM_TOKENS} tokens as a 1x{sorted.shape[0]} tensor')\n",
        "\n",
        "#Produce a list id IDs that are most similiar to the prompt ID at positiion 1 based on above result"
      ],
      "metadata": {
        "id": "juxsvco9B0iV",
        "collapsed": true,
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [],
      "metadata": {
        "id": "cYYu5C5C6MHH"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# @title 🥢🧾 -> 🖨️ Print Result from the 'Similiar Tokens' list from above result\n",
        "list_size = 100 # @param {type:'number'}\n",
        "print_ID = False # @param {type:\"boolean\"}\n",
        "print_Similarity = True # @param {type:\"boolean\"}\n",
        "print_Name = True # @param {type:\"boolean\"}\n",
        "print_Divider = True # @param {type:\"boolean\"}\n",
        "\n",
        "for index in range(list_size):\n",
        "  id = indices[index].item()\n",
        "  if (print_Name):\n",
        "    print(f'{vocab[id]}') # vocab item\n",
        "  if (print_ID):\n",
        "    print(f'ID = {id}') # IDs\n",
        "  if (print_Similarity):\n",
        "    print(f'similiarity = {round(sorted[index].item()*100,2)} %') # % value\n",
        "  if (print_Divider):\n",
        "    print('--------')\n",
        "\n",
        "#Print the sorted list from above result"
      ],
      "metadata": {
        "id": "YIEmLAzbHeuo",
        "collapsed": true,
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "\n",
        "# @title 🆔 Get similarity % of two token IDs\n",
        "id_for_token_A = 4567 # @param {type:'number'}\n",
        "id_for_token_B = 4343 # @param {type:'number'}\n",
        "\n",
        "similarity_str =  'The similarity between tokens A and B is ' + similarity(id_for_token_A , id_for_token_B)\n",
        "\n",
        "print(similarity_str)\n",
        "\n",
        "#Valid ID ranges for id_for_token_A / id_for_token_B are between 0 and 49407"
      ],
      "metadata": {
        "id": "MwmOdC9cNZty",
        "collapsed": true,
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "\n",
        "\n",
        "# How does this notebook work?\n",
        "\n",
        "Similiar vectors = similiar output in the SD 1.5 / SDXL / FLUX model\n",
        "\n",
        "CLIP converts the prompt text to vectors (“tensors”) , with float32 values usually ranging from -1 to 1.\n",
        "\n",
        "Dimensions are \\[ 1x768 ] tensors for SD 1.5 , and a \\[ 1x768 , 1x1024 ] tensor for SDXL and FLUX.\n",
        "\n",
        "The SD models and FLUX converts these vectors to an image.\n",
        "\n",
        "This notebook takes an input string , tokenizes it and matches the first token against the 49407 token vectors in the vocab.json : [https://huggingface.co/black-forest-labs/FLUX.1-dev/tree/main/tokenizer](https://www.google.com/url?q=https%3A%2F%2Fhuggingface.co%2Fblack-forest-labs%2FFLUX.1-dev%2Ftree%2Fmain%2Ftokenizer)\n",
        "\n",
        "It finds the “most similiar tokens” in the list. Similarity is the theta angle between the token vectors.\n",
        "\n",
        "<div>\n",
        "<img src=\"https://huggingface.co/datasets/codeShare/sd_tokens/resolve/main/cosine.jpeg\" width=\"300\"/>\n",
        "</div>\n",
        "\n",
        "The angle is calculated using cosine similarity , where 1 = 100% similarity (parallell vectors) , and 0 = 0% similarity (perpendicular vectors).\n",
        "\n",
        "Negative similarity is also possible.\n",
        "\n",
        "# How can I use it?\n",
        "\n",
        "If you are bored of prompting “girl” and want something similiar you can run this notebook and use the “chick” token at 21.88% similarity , for example\n",
        "\n",
        "You can also run a mixed search , like “cute+girl”/2 , where for example “kpop” has a 16.71% similarity\n",
        "\n",
        "There are some strange tokens further down the list you go. Example: tokens similiar to the token \"pewdiepie</w>\" (yes this is an actual token that exists in CLIP)\n",
        "\n",
        "<div>\n",
        "<img src=\"https://lemmy.world/pictrs/image/a1cd284e-3341-4284-9949-5f8b58d3bd1f.jpeg\" width=\"300\"/>\n",
        "</div>\n",
        "\n",
        "Each of these correspond to a unique 1x768 token vector.\n",
        "\n",
        "The higher the ID value , the less often the token appeared in the CLIP training data.\n",
        "\n",
        "To reiterate; this is the CLIP model training data , not the SD-model training data.\n",
        "\n",
        "So for certain models , tokens with high ID can give very consistent results , if the SD model is trained to handle them.\n",
        "\n",
        "Example of this can be anime models , where japanese artist names can affect the output greatly.  \n",
        "\n",
        "Tokens with high ID will often give the \"fun\" output when used in very short prompts.\n",
        "\n",
        "# What about token vector length?\n",
        "\n",
        "If you are wondering about token magnitude,\n",
        "Prompt weights like (banana:1.2) will scale the magnitude of the corresponding 1x768 tensor(s) by 1.2 . So thats how prompt token magnitude works.\n",
        "\n",
        "Source: [https://huggingface.co/docs/diffusers/main/en/using-diffusers/weighted\\_prompts](https://www.google.com/url?q=https%3A%2F%2Fhuggingface.co%2Fdocs%2Fdiffusers%2Fmain%2Fen%2Fusing-diffusers%2Fweighted_prompts)\\*\n",
        "\n",
        "So TLDR; vector direction = “what to generate” , vector magnitude = “prompt weights”\n",
        "\n",
        "# How prompting works (technical summary)\n",
        "\n",
        " 1. There is no correct way to prompt.\n",
        "\n",
        "2. Stable diffusion reads your prompt left to right, one token at a time, finding association _from_ the previous token _to_ the current token _and to_ the image generated thus far (Cross Attention Rule)\n",
        "\n",
        "3. Stable Diffusion is an optimization problem that seeks to maximize similarity to prompt and minimize similarity to negatives  (Optimization Rule)\n",
        "\n",
        "Reference material (covers entire SD , so not good source material really, but the info is there)  : https://youtu.be/sFztPP9qPRc?si=ge2Ty7wnpPGmB0gi\n",
        "\n",
        "# The SD pipeline\n",
        "\n",
        "For every step (20 in total by default) for SD1.5 :\n",
        "\n",
        "1. Prompt text =>  (tokenizer)\n",
        "2. => Nx768 token vectors =>(CLIP model) =>\n",
        "3. 1x768 encoding => ( the SD model / Unet ) =>\n",
        "4. => _Desired_ image per Rule 3 => ( sampler)\n",
        "5. => Paint a section of the image => (image)\n",
        "\n",
        "# Disclaimer /Trivia\n",
        "\n",
        "This notebook should be seen as a \"dictionary search tool\"  for the vocab.json , which is the same for SD1.5 , SDXL and FLUX. Feel free to verify this by checking the 'tokenizer' folder under each model.\n",
        "\n",
        "vocab.json in the FLUX model , for example (1 of 2 copies) : https://huggingface.co/black-forest-labs/FLUX.1-dev/tree/main/tokenizer\n",
        "\n",
        "I'm using Clip-vit-large-patch14 , which is used in SD 1.5 , and is one among the two tokenizers for SDXL and FLUX  : https://huggingface.co/openai/clip-vit-large-patch14/blob/main/README.md\n",
        "\n",
        "This set of tokens has dimension 1x768.  \n",
        "\n",
        "SDXL and FLUX uses an additional set of tokens of dimension 1x1024.\n",
        "\n",
        "These are not included in this notebook. Feel free to include them yourselves (I would appreciate that).\n",
        "\n",
        "To do so, you will have to download a FLUX and/or SDXL model\n",
        "\n",
        ", and copy the 49407x1024 tensor list that is stored within the model and then save it as a .pt file.\n",
        "\n",
        "//---//\n",
        "\n",
        "I am aware it is actually the 1x768 text_encoding being processed into an image for the SD models + FLUX.\n",
        "\n",
        "As such , I've included text_encoding comparison at the bottom of the Notebook.\n",
        "\n",
        "I am also aware thar SDXL and FLUX uses additional encodings , which are not included in this notebook.\n",
        "\n",
        "* Clip-vit-bigG for SDXL: https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k/blob/main/README.md\n",
        "\n",
        "* And the T5 text encoder for FLUX. I have 0% understanding of FLUX T5 text_encoder.\n",
        "\n",
        "//---//\n",
        "\n",
        "If you want them , feel free to include them yourself and share the results (cuz I probably won't)  :)!\n",
        "\n",
        "That being said , being an encoding , I reckon the CLIP Nx768 => 1x768 should be \"linear\" (or whatever one might call it)\n",
        "\n",
        "So exchange a few tokens in the Nx768 for something similiar , and the resulting 1x768 ought to be kinda similar to 1x768 we had earlier. Hopefully.\n",
        "\n",
        "I feel its important to mention this , in case some wonder why the token-token similarity don't match the text-encoding to text-encoding similarity.\n",
        "\n",
        "# Note regarding CLIP text encoding vs. token\n",
        "\n",
        "*To make this disclaimer clear; Token-to-token similarity is not the same as text_encoding similarity.*\n",
        "\n",
        "I have to say this , since it will  otherwise get (even more) confusing , as both the individual tokens , and the text_encoding have dimensions 1x768.\n",
        "\n",
        "They are separate things. Separate results. etc.\n",
        "\n",
        "As such , you will not get anything useful if you start comparing similarity between a token , and a text-encoding. So don't do that :)!\n",
        "\n",
        "# What about the CLIP image encoding?\n",
        "\n",
        "The CLIP model can also do an image_encoding of an image, where the output will be a 1x768 tensor. These _can_ be compared with the text_encoding.\n",
        "\n",
        "Comparing CLIP image_encoding with the CLIP text_encoding for a bunch of random prompts until you find the \"highest similarity\" , is a method used in the CLIP interrogator : https://huggingface.co/spaces/pharmapsychotic/CLIP-Interrogator\n",
        "\n",
        "List of random prompts for CLIP interrogator  can be found here, for reference : https://github.com/pharmapsychotic/clip-interrogator/tree/main/clip_interrogator/data\n",
        "\n",
        "The CLIP image_encoding is not included in this Notebook.\n",
        "\n",
        "If you spot errors / ideas for improvememts; feel free to fix the code in your own notebook and post the results.\n",
        "\n",
        "I'd appreciate that over people saying \"your math is wrong you n00b!\" with no constructive feedback.\n",
        "\n",
        "//---//\n",
        "\n",
        "Regarding output\n",
        "\n",
        "# What are the </w> symbols?\n",
        "\n",
        "The whitespace symbol indicate if the tokenized item ends with whitespace ( the suffix \"banana</w>\" => \"banana \" )  or not (the prefix  \"post\"  in \"post-apocalyptic \")\n",
        "\n",
        "For ease of reference , I call them prefix-tokens and suffix-tokens.\n",
        "\n",
        "Sidenote:\n",
        "\n",
        "Prefix tokens have the unique property in that they \"mutate\" suffix tokens\n",
        "\n",
        "Example:  \"photo of a #prefix#-banana\"\n",
        "\n",
        "where #prefix# is a randomly selected prefix-token from the vocab.json\n",
        "\n",
        "The hyphen \"-\" exists to guarantee the tokenized text splits into the written #prefix# and #suffix# token respectively.  The \"-\" hypen symbol can be replaced by any other special character of your choosing.\n",
        "\n",
        " Capital letters work too , e.g \"photo of a #prefix#Abanana\" since the capital letters A-Z are only listed once in the entire vocab.json.\n",
        "\n",
        "You can also choose to omit any separator and just rawdog it with the prompt \"photo of a #prefix#banana\" , however know that  this may , on occasion , be tokenized as completely different tokens of lower ID:s.\n",
        "\n",
        "Curiously , common NSFW terms found online have in the CLIP model have been purposefully fragmented into separate #prefix# and #suffix# counterparts in the vocab.json. Likely for PR-reasons.\n",
        "\n",
        "You can verify the results using this online tokenizer: https://sd-tokenizer.rocker.boo/\n",
        "\n",
        "<div>\n",
        "<img src=\"https://lemmy.world/pictrs/image/43467d75-7406-4a13-93ca-cdc469f944fc.jpeg\" width=\"300\"/>\n",
        "<img src=\"https://lemmy.world/pictrs/image/c0411565-0cb3-47b1-a788-b368924d6f17.jpeg\" width=\"300\"/>\n",
        "<img src=\"https://lemmy.world/pictrs/image/c27c6550-a88b-4543-9bd7-067dff016be2.jpeg\" width=\"300\"/>\n",
        "</div>\n",
        "\n",
        "# What is that gibberish tokens that show up?\n",
        "\n",
        "The gibberish tokens like \"ðŁĺħ\\</w>\" are actually emojis!\n",
        "\n",
        "Try writing some emojis in this online tokenizer to see the results: https://sd-tokenizer.rocker.boo/\n",
        "\n",
        "It is a bit borked as it can't process capital letters properly.\n",
        "\n",
        "Also note that this is not reversible.\n",
        "\n",
        "If tokenization \"😅\" => ðŁĺħ</w>\n",
        "\n",
        "Then you  can't prompt \"ðŁĺħ\" and expect to get the same result as the tokenized original emoji , \"😅\".\n",
        "\n",
        "SD 1.5 models actually have training for Emojis.\n",
        "\n",
        "But you have to set CLIP skip to 1 for this to work is intended.\n",
        "\n",
        "For example, this is the result from \"photo of a 🧔🏻‍♂️\"\n",
        "\n",
        "\n",
        "<div>\n",
        "<img src=\"https://lemmy.world/pictrs/image/e2b51aea-6960-4ad0-867e-8ce85f2bd51e.jpeg\" width=\"300\"/>\n",
        "</div>\n",
        "\n",
        "A tutorial on stuff you can do with the vocab.list concluded.\n",
        "\n",
        "Anyways, have fun with the notebook.\n",
        "\n",
        "There might be some updates in the future with features not mentioned here.\n",
        "\n",
        "//---//\n",
        "\n",
        "https://codeandlife.com/2023/01/26/mastering-the-huggingface-clip-model-how-to-extract-embeddings-and-calculate-similarity-for-text-and-images/"
      ],
      "metadata": {
        "id": "njeJx_nSSA8H"
      }
    }
  ]
}