{ "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('','').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'" ], "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" ] } ] } ] }