Upload fusion_t2i_CLIP_interrogator.ipynb
Browse files176 unmodified lines1771781791801811821831 unmodified line1851861871881891901911921931941951961978 unmodified lines20620720820921021121255 unmodified lines26826927027127227363 unmodified lines337338339340341342120 unmodified lines463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565191 unmodified lines757758759760761762176 unmodified lines"print(f'Using settings SCALE = {SCALE} and ZERO_POINT = {ZERO_POINT} for visualizing the text_encoding')"],"metadata": {"id": "YDu8XlehhWID"},"execution_count": null,"outputs": []1 unmodified line{"cell_type": "markdown","source": ["**Feel free to skip these cells if you do not plan on using them**\n","\n"],"metadata": {"id": "Xf9zoq-Za3wi"}},{"cell_type": "code","source": [8 unmodified lines"try:prompt\n","except: prompt = ''\n","\n","# @markdown ๐ผ๏ธ+๐ Choose a pre-encoded reference (optional)\n","index = 596 # @param {type:\"slider\", min:0, max:1666, step:1}\n","PROMPT_INDEX = index\n","prompt = target_prompts[f'{PROMPT_INDEX}']\n",55 unmodified lines"execution_count": null,"outputs": []},{"cell_type": "code","source": [63 unmodified lines"execution_count": null,"outputs": []},{"cell_type": "code","source": [120 unmodified lines" #------#"],"metadata": {"id": "lOQuTPfBMK82"},"execution_count": null,"outputs": []},{"cell_type": "code","source": ["# @title โ Evaluate saved reference similarity to select items (optional)\n","EVAL = '' # @param {type:'string' ,placeholder:'item1 , item2 , ...'}\n","\n","# @markdown ๐ Enhance/Penalize Similarity and skip items containing word(s)\n","POS = '' # @param {type:'string' ,placeholder:'item1 , item2 , ...'}\n","NEG = ''# @param {type:'string' ,placeholder:'item1 , item2 , ...'}\n","# @markdown -----\n","# @markdown logarithmic prompt strength x for value 10^(x-1)\n","_POS = 0 # @param {type:\"slider\", min:-5, max:5, step:0.01}\n","_NEG = 0 # @param {type:\"slider\", min:-5, max:5, step:0.01}\n","\n","show_local_reference = True # @param {type:\"boolean\"}\n","show_encoding = True # @param {type:\"boolean\"}\n","\n","%cd /content/\n","_ref = load_file('reference.safetensors' )\n","ref = _ref['weights'].to(dot_dtype)\n","\n","if EVAL.strip() != '':\n"," print(\"Saved Reference:\\n\")\n"," for item in EVAL.split(','):\n"," if item.strip()=='':continue\n"," inputs = tokenizer(text = item.strip(), truncation = True , padding=True, return_tensors=\"pt\")\n"," test = model.get_text_features(**inputs)[0]\n"," test = test/test.norm(p=2 , dim = -1 , keepdim = True)\n"," ref= ref/ref.norm(p=2 , dim=-1 , keepdim=True)\n"," eval = torch.dot(ref , test)\n"," print(f'{item.strip()} : {round(eval.item()*100, 2)}%')\n"," #-----#\n","\n"," if(show_local_reference):\n"," print(\"\\n---------\\nLocal Reference with enchancements added :\\n\")\n","\n"," for _item in POS.split(','):\n"," item = _item.strip()\n"," if item == '':continue\n"," inputs = tokenizer(text = item.strip(), truncation = True , padding=True, return_tensors=\"pt\")\n"," ref = ref + math.pow(10,_POS-1) * model.get_text_features(**inputs)[0]\n"," #-------#\n","\n"," for _item in NEG.split(','):\n"," item = _item.strip()\n"," if item == '':continue\n"," inputs = tokenizer(text = item.strip(), truncation = True , padding=True, return_tensors=\"pt\")\n"," ref = ref + math.pow(10,_NEG-1) * model.get_text_features(**inputs)[0]\n"," #-------#\n","\n"," ref= ref/ref.norm(p=2 , dim=-1 , keepdim=True)\n"," for item in EVAL.split(','):\n"," if item.strip()=='':continue\n"," inputs = tokenizer(text = item.strip(), truncation = True , padding=True, return_tensors=\"pt\")\n"," test = model.get_text_features(**inputs)[0]\n"," test = test/test.norm(p=2 , dim = -1 , keepdim = True)\n"," eval = torch.dot(ref , test)\n"," print(f'{item.strip()} : {round(eval.item()*100, 2)}%')\n"," #-----#\n","\n"," if show_encoding:\n"," # create figure\n"," fig = plt.figure(figsize=(10*image_size, 10*image_size))\n"," fig.patch.set_facecolor((56/255,56/255,56/255))\n"," rows = 1\n"," columns = 3\n"," fig.add_subplot(rows, columns, 1)\n"," plt.imshow( visualize(ref))\n"," plt.axis('off')\n"," plt.title( \"Encoding (local variable)\", color='white', fontsize=round(20*image_size))\n"," if num_plots>1:\n"," fig.add_subplot(rows, columns, 2)\n"," plt.imshow( visualize( _ref['weights'].to(dot_dtype)))\n"," plt.axis('off')\n"," plt.title(\"Encoding (saved file)\", color='white', fontsize=round(20*image_size))\n","\n"," fig.add_subplot(rows, columns, 3)\n"," plt.imshow( visualize(ref - _ref['weights'].to(dot_dtype)))\n"," plt.axis('off')\n"," plt.title(\"Changes\", color='white', fontsize=round(20*image_size))\n"," #------#\n"],"metadata": {"id": "Oxi6nOyrUTAe"},"execution_count": null,"outputs": []},{"cell_type": "code","source": ["# @title โ Run the CLIP interrogator on the saved reference\n","LIST_SIZE = 1000 # @param {type:'number' , placeholder:'set how large the list should be'}\n","_START_AT = '0' # @param [\"0\", \"10000\", \"50000\"] {allow-input: true}\n","START_AT = 0\n",191 unmodified lines"execution_count": null,"outputs": []},{"cell_type": "code","source": [176 unmodified lines1771781791801811821831841 unmodified line1861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193208 unmodified lines32933033133233333433555 unmodified lines39139239339439539639739839940040140240340440563 unmodified lines469470471472473474475476477478479480481482483120 unmodified lines604605606607608609610611612613614615616617618619620621622623624625626627628629630191 unmodified lines822823824825826827828829830831832833834835836837838176 unmodified lines"print(f'Using settings SCALE = {SCALE} and ZERO_POINT = {ZERO_POINT} for visualizing the text_encoding')"],"metadata": {"id": "YDu8XlehhWID","cellView": "form"},"execution_count": null,"outputs": []1 unmodified line{"cell_type": "markdown","source": ["**Paste a prompt in the cell below to create an encoding**\n","\n"],"metadata": {"id": "Xf9zoq-Za3wi"}},{"cell_type": "code","source": ["\n","# @markdown ๐ Write a text prompt (this will overwrite any savefile already stored)\n","NEW_ENCODING = '' # @param {type:'string' ,placeholder:'write a prompt'}\n","enable = True # @param {type:\"boolean\"}\n","# @markdown -----\n","# @markdown ๐ Enhance/Penalize Similarity and skip items containing word(s)\n","POS = '' # @param {type:'string' ,placeholder:'item1 , item2 , ...'}\n","NEG = ''# @param {type:'string' ,placeholder:'item1 , item2 , ...'}\n","# @markdown -----\n","# @markdown logarithmic prompt strength x for value 10^(x-1)\n","_POS = 0 # @param {type:\"slider\", min:-5, max:5, step:0.01}\n","_NEG = 0 # @param {type:\"slider\", min:-5, max:5, step:0.01}\n","# @markdown -----\n","# @markdown Check similiarity for this encoding against any written prompt(s)\n","# @title โ Evaluate saved reference similarity to select items (optional)\n","EVAL = '' # @param {type:'string' ,placeholder:'item1 , item2 , ...'}\n","\n","show_local_reference = True # @param {type:\"boolean\"}\n","show_encoding = True # @param {type:\"boolean\"}\n","\n","try:\n"," %cd /content/\n"," _ref = load_file('reference.safetensors' )\n"," ref = _ref['weights'].to(dot_dtype)\n","except:\n"," ref = torch.zeros(dim).to(dtype = dot_dtype)\n"," _ref = {}\n"," _ref['weights'] = ref\n"," %cd /content/\n"," save_file(_ref, 'reference.safetensors')\n","#-----#\n","\n","if NEW_ENCODING.strip() != ''\n"," item = NEW_ENCODING.strip()\n"," inputs = tokenizer(text = item.strip(), truncation = True , padding=True, return_tensors=\"pt\")\n"," ref = model.get_text_features(**inputs)[0]\n"," ref= ref/ref.norm(p=2 , dim=-1 , keepdim=True)\n","#------#\n","\n","try: ref\n","except: ref = torch.zeros(dim).to(dtype = dot_dtype)\n","\n","if EVAL.strip() != '':\n"," print(\"Saved Reference:\\n\")\n"," for item in EVAL.split(','):\n"," if item.strip()=='':continue\n"," inputs = tokenizer(text = item.strip(), truncation = True , padding=True, return_tensors=\"pt\")\n"," test = model.get_text_features(**inputs)[0]\n"," test = test/test.norm(p=2 , dim = -1 , keepdim = True)\n"," ref= ref/ref.norm(p=2 , dim=-1 , keepdim=True)\n"," eval = torch.dot(ref , test)\n"," print(f'{item.strip()} : {round(eval.item()*100, 2)}%')\n"," #-----#\n"," if(show_local_reference):\n"," print(\"\\n---------\\nLocal Reference with enchancements added :\\n\")\n","\n"," for _item in POS.split(','):\n"," item = _item.strip()\n"," if item == '':continue\n"," inputs = tokenizer(text = item.strip(), truncation = True , padding=True, return_tensors=\"pt\")\n"," ref = ref + math.pow(10,_POS-1) * model.get_text_features(**inputs)[0]\n"," #-------#\n","\n"," for _item in NEG.split(','):\n"," item = _item.strip()\n"," if item == '':continue\n"," inputs = tokenizer(text = item.strip(), truncation = True , padding=True, return_tensors=\"pt\")\n"," ref = ref + math.pow(10,_NEG-1) * model.get_text_features(**inputs)[0]\n"," #-------#\n","\n"," ref= ref/ref.norm(p=2 , dim=-1 , keepdim=True)\n"," for item in EVAL.split(','):\n"," if item.strip()=='':continue\n"," inputs = tokenizer(text = item.strip(), truncation = True , padding=True, return_tensors=\"pt\")\n"," test = model.get_text_features(**inputs)[0]\n"," test = test/test.norm(p=2 , dim = -1 , keepdim = True)\n"," eval = torch.dot(ref , test)\n"," print(f'{item.strip()} : {round(eval.item()*100, 2)}%')\n"," #-----#\n","\n"," if show_encoding:\n"," # create figure\n"," fig = plt.figure(figsize=(10*image_size, 10*image_size))\n"," fig.patch.set_facecolor((56/255,56/255,56/255))\n"," rows = 1\n"," columns = 3\n"," fig.add_subplot(rows, columns, 1)\n"," plt.imshow( visualize(ref))\n"," plt.axis('off')\n"," plt.title( \"Encoding (local variable)\", color='white', fontsize=round(20*image_size))\n"," if num_plots>1:\n"," fig.add_subplot(rows, columns, 2)\n"," plt.imshow( visualize( _ref['weights'].to(dot_dtype)))\n"," plt.axis('off')\n"," plt.title(\"Encoding (saved file)\", color='white', fontsize=round(20*image_size))\n","\n"," fig.add_subplot(rows, columns, 3)\n"," plt.imshow( visualize(ref - _ref['weights'].to(dot_dtype)))\n"," plt.axis('off')\n"," plt.title(\"Changes\", color='white', fontsize=round(20*image_size))\n"," #------#\n","\n","\n"],"metadata": {"id": "Oxi6nOyrUTAe"},"execution_count": null,"outputs": []},{"cell_type": "markdown","source": ["**Use a pre-encoded image+prompt pair as reference (optional)**"],"metadata": {"id": "f9_AcquM7AYZ"}},{"cell_type": "code","source": [8 unmodified lines"try:prompt\n","except: prompt = ''\n","\n","# @markdown ๐ผ๏ธ+๐ Choose a pre-encoded reference (note: some results are NSFW!)\n","index = 596 # @param {type:\"slider\", min:0, max:1666, step:1}\n","PROMPT_INDEX = index\n","prompt = target_prompts[f'{PROMPT_INDEX}']\n",55 unmodified lines"execution_count": null,"outputs": []},{"cell_type": "markdown","source": ["**Use an image as a reference via URL (optional)**"],"metadata": {"id": "KI9Ho6CG7m3Z"}},{"cell_type": "code","source": [63 unmodified lines"execution_count": null,"outputs": []},{"cell_type": "markdown","source": ["**Use an image as a reference via uploading it to the /content/ folder (optional)**"],"metadata": {"id": "MBPi7F8S7tg3"}},{"cell_type": "code","source": [120 unmodified lines" #------#"],"metadata": {"id": "lOQuTPfBMK82","cellView": "form"},"execution_count": null,"outputs": []},{"cell_type": "markdown","source": ["**Run the interrogator**\n","\n"," Since the list of items is large (>1 million items) you will need to select a range within the sorted results to print."],"metadata": {"id": "ROKsoZrt7zMe"}},{"cell_type": "code","source": ["# @title โ CLIP Interrogator\n","LIST_SIZE = 1000 # @param {type:'number' , placeholder:'set how large the list should be'}\n","_START_AT = '0' # @param [\"0\", \"10000\", \"50000\"] {allow-input: true}\n","START_AT = 0\n",191 unmodified lines"execution_count": null,"outputs": []},{"cell_type": "markdown","source": ["**Evaluate Similarities**\n","\n","Run this cell to see how far down the list you can go before similarity to the reference is lost."],"metadata": {"id": "yl1DYzUn8YCC"}},{"cell_type": "code","source": [
Google Colab Jupyter Notebooks/fusion_t2i_CLIP_interrogator.ipynb+163-87