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d64a03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe9cdc7
3d64a03
 
fe9cdc7
 
 
 
 
3d64a03
fe9cdc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d64a03
 
 
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
{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "code",
      "source": [
        "# NOTE : although they have 1x768 dimension , these are not text_encodings , but token vectors\n",
        "import json\n",
        "import pandas as pd\n",
        "import os\n",
        "import shelve\n",
        "import torch\n",
        "from safetensors.torch import save_file , load_file\n",
        "import json\n",
        "\n",
        "home_directory = '/content/'\n",
        "using_Kaggle = os.environ.get('KAGGLE_URL_BASE','')\n",
        "if using_Kaggle : home_directory = '/kaggle/working/'\n",
        "%cd {home_directory}\n",
        "#-------#\n",
        "\n",
        "# Load the data if not already loaded\n",
        "try:\n",
        "    loaded\n",
        "except:\n",
        "    %cd {home_directory}\n",
        "    !git clone https://huggingface.co/datasets/codeShare/text-to-image-prompts\n",
        "    loaded = True\n",
        "#--------#\n",
        "\n",
        "def getPrompts(_path, separator):\n",
        "  path = _path + '/text'\n",
        "  path_vec = _path + '/token_vectors'\n",
        "  _file_name = 'vocab'\n",
        "  #-----#\n",
        "  index = 0\n",
        "  prompts = {}\n",
        "  text_encodings = {}\n",
        "  #-----#\n",
        "  for filename in os.listdir(f'{path}'):\n",
        "    print(f'reading {filename}....')\n",
        "    _index = 0\n",
        "    %cd {path}\n",
        "    with open(f'{filename}', 'r') as f:\n",
        "      data = json.load(f)\n",
        "    #------#\n",
        "    _df = pd.DataFrame({'count': data})['count']\n",
        "    prompts = {\n",
        "        key : value for key, value in _df.items()\n",
        "    }\n",
        "\n",
        "    for key in prompts:\n",
        "      index = index + 1\n",
        "    #------#\n",
        "    NUM_ITEMS = index -1\n",
        "    #------#\n",
        "    %cd {path_vec}\n",
        "    text_encodings = load_file(f'{_file_name}.safetensors')\n",
        "    continue\n",
        "  #----------#\n",
        "  return prompts , text_encodings , NUM_ITEMS\n",
        "#--------#\n",
        "\n",
        "def append_from_url(dictA, tensA , nA , url , separator):\n",
        "  dictB , tensB, nB = getPrompts(url, separator)\n",
        "  dictAB = dictA\n",
        "  tensAB = tensA\n",
        "  nAB = nA\n",
        "  for key in dictB:\n",
        "    nAB = nAB + 1\n",
        "    dictAB[f'{nA + int(key)}'] = dictB[key]\n",
        "    tensAB[f'{nA + int(key)}'] = tensB[key]\n",
        "  #-----#\n",
        "  return dictAB, tensAB , nAB-1\n",
        "#-------#"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "V-1DrszLqEVj",
        "outputId": "8788d8fc-59ce-4cba-9867-4860291afcb2"
      },
      "execution_count": 5,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "/content\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# @title Fetch the json + .safetensor pair\n",
        "\n",
        "#------#\n",
        "vocab = {}\n",
        "tokens = {}\n",
        "nA = 0\n",
        "#--------#\n",
        "\n",
        "if True:\n",
        "  url = '/content/text-to-image-prompts/vocab'\n",
        "  vocab , tokens, nA = append_from_url(vocab , tokens, nA , url , '')\n",
        "#-------#\n",
        "NUM_TOKENS = nA\n",
        "#--------#\n",
        "\n",
        "if False:\n",
        "  print(NUM_TOKENS)  # NUM_TOKENS = 49407\n",
        "  print(vocab['8922']) #ID for banana is 8922"
      ],
      "metadata": {
        "id": "EDCd1IGEqj3-"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# @title Compare similiarity between tokens\n",
        "\n",
        "import torch\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",
        "token_name = \"banana\" # @param {type:'string',\"placeholder\":\"leave empty for random value token\"}\n",
        "\n",
        "prompt = token_name\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",
        "# @markdown Limit char size of included token\n",
        "\n",
        "min_char_size = 0 # param {type:\"slider\", min:0, max: 50, step:1}\n",
        "char_range = 50 # param {type:\"slider\", min:0, max: 50, step:1}\n",
        "\n",
        "tokenizer_output = tokenizer(text = prompt)\n",
        "input_ids = tokenizer_output['input_ids']\n",
        "id_A = input_ids[1]\n",
        "A = torch.tensor(tokens[f'{id_A}'])\n",
        "A = A/A.norm(p=2, dim=-1, keepdim=True)\n",
        "#-----#\n",
        "tokenizer_output = tokenizer(text = mix_with)\n",
        "input_ids = tokenizer_output['input_ids']\n",
        "id_C = input_ids[1]\n",
        "C = torch.tensor(tokens[f'{id_C}'])\n",
        "C = C/C.norm(p=2, dim=-1, keepdim=True)\n",
        "#-----#\n",
        "sim_AC = torch.dot(A,C)\n",
        "#-----#\n",
        "print(input_ids)\n",
        "#-----#\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(A.shape)\n",
        "  R = R/R.norm(p=2, dim=-1, keepdim=True)\n",
        "  A = R\n",
        "  name_A = 'random_A'\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(A.shape)\n",
        "  R = R/R.norm(p=2, dim=-1, keepdim=True)\n",
        "  C = R\n",
        "  name_C = 'random_C'\n",
        "\n",
        "name_A = \"A of random type\"\n",
        "if (id_A>-1):\n",
        "  name_A = vocab[f'{id_A}']\n",
        "\n",
        "name_C = \"token C of random type\"\n",
        "if (id_C>-1):\n",
        "  name_C = vocab[f'{id_C}']\n",
        "\n",
        "print(f\"The similarity between A '{name_A}' and C '{name_C}' is {round(sim_AC.item()*100,2)} %\")\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 = A.norm(p=2, dim=-1, keepdim=True)\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 = tmp/tmp.norm(p=2, dim=-1, keepdim=True)\n",
        "  A = tmp\n",
        "  #//---//\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 = torch.tensor(tokens[f'{id_B}'])\n",
        "  B = B/B.norm(p=2, dim=-1, keepdim=True)\n",
        "  sim_AB = torch.dot(A,B)\n",
        "  dots[index] = sim_AB\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(vocab[f'{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\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",
        "# Save results as .db file\n",
        "import shelve\n",
        "VOCAB_FILENAME = 'tokens_most_similiar_to_' + name_A.replace('</w>','').strip()\n",
        "d = shelve.open(VOCAB_FILENAME)\n",
        "#NUM TOKENS == 49407\n",
        "for index in range(NUM_TOKENS):\n",
        "  #print(d[f'{index}']) #<-----Use this to read values from the .db file\n",
        "  d[f'{index}']= vocab[f'{indices[index].item()}'] #<---- write values to .db file\n",
        "#----#\n",
        "d.close() #close the file\n",
        "# See this link for additional stuff to do with shelve: https://docs.python.org/3/library/shelve.html"
      ],
      "metadata": {
        "id": "ZwGqg9R5s1QS"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "Below is code used to create the .safetensor + json files for the notebook"
      ],
      "metadata": {
        "id": "dGb1KgP_p4_w"
      }
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "AyhYBlP2pYyI",
        "outputId": "9e2fc730-23ee-4b05-9957-6fb2db82f2cf"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "/content\n",
            "/content\n",
            "/content/text-to-image-prompts/vocab/raw\n",
            "/content/text-to-image-prompts/vocab/raw\n",
            "/content/output/vocab/token_vectors\n",
            "/content/output/vocab/text\n"
          ]
        }
      ],
      "source": [
        "# @title Process the raw vocab into json + .safetensor pair\n",
        "\n",
        "# NOTE : although they have 1x768 dimension , these are not text_encodings , but token vectors\n",
        "import json\n",
        "import pandas as pd\n",
        "import os\n",
        "import shelve\n",
        "import torch\n",
        "from safetensors.torch import save_file , load_file\n",
        "import json\n",
        "\n",
        "home_directory = '/content/'\n",
        "using_Kaggle = os.environ.get('KAGGLE_URL_BASE','')\n",
        "if using_Kaggle : home_directory = '/kaggle/working/'\n",
        "%cd {home_directory}\n",
        "#-------#\n",
        "\n",
        "# Load the data if not already loaded\n",
        "try:\n",
        "    loaded\n",
        "except:\n",
        "    %cd {home_directory}\n",
        "    !git clone https://huggingface.co/datasets/codeShare/text-to-image-prompts\n",
        "    loaded = True\n",
        "#--------#\n",
        "\n",
        "# User input\n",
        "target = home_directory + 'text-to-image-prompts/vocab/'\n",
        "root_output_folder = home_directory + 'output/'\n",
        "output_folder = root_output_folder  + 'vocab/'\n",
        "root_filename = 'vocab'\n",
        "NUM_FILES = 1\n",
        "#--------#\n",
        "\n",
        "# Setup environment\n",
        "def my_mkdirs(folder):\n",
        "    if os.path.exists(folder)==False:\n",
        "        os.makedirs(folder)\n",
        "#--------#\n",
        "output_folder_text = output_folder + 'text/'\n",
        "output_folder_text = output_folder + 'text/'\n",
        "output_folder_token_vectors = output_folder + 'token_vectors/'\n",
        "target_raw = target + 'raw/'\n",
        "%cd {home_directory}\n",
        "my_mkdirs(output_folder)\n",
        "my_mkdirs(output_folder_text)\n",
        "my_mkdirs(output_folder_token_vectors)\n",
        "#-------#\n",
        "\n",
        "%cd {target_raw}\n",
        "model = torch.load(f'{root_filename}.pt' , weights_only=True)\n",
        "tokens = model.clone().detach()\n",
        "\n",
        "\n",
        "%cd {target_raw}\n",
        "with open(f'{root_filename}.json', 'r') as f:\n",
        "    data = json.load(f)\n",
        "_df = pd.DataFrame({'count': data})['count']\n",
        "#reverse key and value in the dict\n",
        "vocab = {\n",
        "    value : key for key, value in _df.items()\n",
        "}\n",
        "#------#\n",
        "\n",
        "\n",
        "tensors = {}\n",
        "names = {}\n",
        "for key in vocab:\n",
        "  token = tokens[int(key)]\n",
        "  tensors[f'{key}'] = token\n",
        "  names[f'{key}'] = vocab[key]\n",
        "#-----#\n",
        "\n",
        "%cd {output_folder_token_vectors}\n",
        "save_file(tensors, \"vocab.safetensors\")\n",
        "\n",
        "%cd {output_folder_text}\n",
        "with open('vocab.json', 'w') as f:\n",
        "    json.dump(names, f)\n"
      ]
    },
    {
      "cell_type": "code",
      "source": [],
      "metadata": {
        "id": "W_Ig4ZGH18hX",
        "outputId": "5f2c0a6e-9b6e-4135-d7de-900673f34e1c",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 35
        }
      },
      "execution_count": 4,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'banana</w>'"
            ],
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            }
          },
          "metadata": {},
          "execution_count": 4
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Determine if this notebook is running on Colab or Kaggle\n",
        "#Use https://www.kaggle.com/ if Google Colab GPU is busy\n",
        "home_directory = '/content/'\n",
        "using_Kaggle = os.environ.get('KAGGLE_URL_BASE','')\n",
        "if using_Kaggle : home_directory = '/kaggle/working/'\n",
        "%cd {home_directory}\n",
        "#-------#\n",
        "\n",
        "# @title Download the vocab as .zip\n",
        "import os\n",
        "%cd {home_directory}\n",
        "#os.remove(f'{home_directory}results.zip')\n",
        "root_output_folder = home_directory + 'output/'\n",
        "zip_dest = f'{home_directory}results.zip'\n",
        "!zip -r {zip_dest} {root_output_folder}"
      ],
      "metadata": {
        "id": "9uIDf9IUpzh2",
        "outputId": "949f95c8-7657-42dd-d70a-d3cc7da2c72f",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "execution_count": 6,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "/content\n",
            "/content\n",
            "  adding: content/output/ (stored 0%)\n",
            "  adding: content/output/vocab/ (stored 0%)\n",
            "  adding: content/output/vocab/text/ (stored 0%)\n",
            "  adding: content/output/vocab/text/vocab.json (deflated 71%)\n",
            "  adding: content/output/vocab/text/.ipynb_checkpoints/ (stored 0%)\n",
            "  adding: content/output/vocab/token_vectors/ (stored 0%)\n",
            "  adding: content/output/vocab/token_vectors/vocab.safetensors (deflated 9%)\n",
            "  adding: content/output/vocab/token_vectors/.ipynb_checkpoints/ (stored 0%)\n"
          ]
        }
      ]
    }
  ]
}