File size: 8,348 Bytes
2de5878
 
 
 
3ffe17d
2de5878
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ffe17d
 
 
2de5878
 
 
 
 
3ffe17d
 
 
 
2de5878
 
3ffe17d
 
 
 
 
 
 
2de5878
3ffe17d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2de5878
 
 
3ffe17d
 
 
 
2de5878
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ffe17d
2de5878
 
 
3ffe17d
 
 
 
 
2de5878
 
 
 
 
 
3ffe17d
2de5878
 
 
3ffe17d
 
 
 
 
2de5878
 
 
 
 
 
 
 
 
 
 
3ffe17d
2de5878
 
 
3ffe17d
2de5878
 
3ffe17d
 
 
 
 
 
 
 
 
 
 
 
2de5878
 
 
3ffe17d
 
 
 
 
2de5878
 
3ffe17d
 
 
2de5878
3ffe17d
 
2de5878
3ffe17d
2de5878
 
3ffe17d
2de5878
 
 
3ffe17d
 
 
 
2de5878
 
 
 
 
3ffe17d
2de5878
 
 
3ffe17d
 
 
 
2de5878
 
3ffe17d
2de5878
3ffe17d
 
2de5878
3ffe17d
2de5878
 
 
 
 
 
3ffe17d
 
 
2de5878
 
 
 
 
 
 
 
 
 
 
3ffe17d
2de5878
 
 
 
 
3ffe17d
 
2de5878
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import open_clip\n",
    "import torch\n",
    "from tqdm.notebook import tqdm\n",
    "import pandas as pd\n",
    "import os\n",
    "\n",
    "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
    "\n",
    "PROMPTS = [\n",
    "    '{0}',\n",
    "    'an image of {0}',\n",
    "    'a photo of {0}',\n",
    "    '{0} on a photo',\n",
    "    'a photo of a person named {0}',\n",
    "    'a person named {0}',\n",
    "    'a man named {0}',\n",
    "    'a woman named {0}',\n",
    "    'the name of the person is {0}',\n",
    "    'a photo of a person with the name {0}',\n",
    "    '{0} at a gala',\n",
    "    'a photo of the celebrity {0}',\n",
    "    'actor {0}',\n",
    "    'actress {0}',\n",
    "    'a colored photo of {0}',\n",
    "    'a black and white photo of {0}',\n",
    "    'a cool photo of {0}',\n",
    "    'a cropped photo of {0}',\n",
    "    'a cropped image of {0}',\n",
    "    '{0} in a suit',\n",
    "    '{0} in a dress'\n",
    "]\n",
    "OPEN_CLIP_LAION400M_MODEL_NAMES = ['ViT-B-32', 'ViT-B-16', 'ViT-L-14']\n",
    "OPEN_CLIP_LAION2B_MODEL_NAMES = [('ViT-B-32', 'laion2b_s34b_b79k') , ('ViT-L-14', 'laion2b_s32b_b82k')]\n",
    "OPEN_AI_MODELS = ['ViT-B-32', 'ViT-B-16', 'ViT-L-14']\n",
    "SEED = 42"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "MODELS = {}\n",
    "for model_name in OPEN_CLIP_LAION400M_MODEL_NAMES:\n",
    "    dataset = 'LAION400M'\n",
    "    model, _, preprocess = open_clip.create_model_and_transforms(\n",
    "        model_name,\n",
    "        pretrained=f'{dataset.lower()}_e32'\n",
    "    )\n",
    "    model = model.eval()\n",
    "    MODELS[(model_name, dataset.lower())] = {\n",
    "        'model_instance': model,\n",
    "        'preprocessing': preprocess,\n",
    "        'model_name': model_name,\n",
    "        'tokenizer': open_clip.get_tokenizer(model_name),\n",
    "    }\n",
    "\n",
    "for model_name, dataset_name in OPEN_CLIP_LAION2B_MODEL_NAMES:\n",
    "    dataset = 'LAION2B'\n",
    "    model, _, preprocess = open_clip.create_model_and_transforms(\n",
    "        model_name,\n",
    "        pretrained = dataset_name\n",
    "    )\n",
    "    model = model.eval()\n",
    "    MODELS[(model_name, dataset.lower())] = {\n",
    "        'model_instance': model,\n",
    "        'preprocessing': preprocess,\n",
    "        'model_name': model_name,\n",
    "        'tokenizer': open_clip.get_tokenizer(model_name)\n",
    "    }\n",
    "\n",
    "for model_name in OPEN_AI_MODELS:\n",
    "    dataset = 'OpenAI'\n",
    "    model, _, preprocess = open_clip.create_model_and_transforms(\n",
    "        model_name,\n",
    "        pretrained=dataset.lower()\n",
    "    )\n",
    "    model = model.eval()\n",
    "    MODELS[(model_name, dataset.lower())] = {\n",
    "        'model_instance': model,\n",
    "        'preprocessing': preprocess,\n",
    "        'model_name': model_name,\n",
    "        'tokenizer': open_clip.get_tokenizer(model_name)\n",
    "    }"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# define a function to get the predictions for an actor/actress\n",
    "@torch.no_grad()\n",
    "def get_text_embeddings(model, context, context_batchsize=1_000, use_tqdm=False):\n",
    "    context_batchsize = context_batchsize * torch.cuda.device_count()\n",
    "    # if there is not batches for the context unsqueeze it\n",
    "    if context.dim() < 3:\n",
    "        context = context.unsqueeze(0)\n",
    "\n",
    "    # get the batch size, the number of labels and the sequence length\n",
    "    seq_len = context.shape[-1]\n",
    "    viewed_context = context.view(-1, seq_len)\n",
    "\n",
    "    text_features = []\n",
    "    for context_batch_idx in tqdm(range(0, len(viewed_context), context_batchsize), desc=\"Calculating Text Embeddings\",\n",
    "                                  disable=not use_tqdm):\n",
    "        context_batch = viewed_context[context_batch_idx:context_batch_idx + context_batchsize]\n",
    "        batch_text_features = model.encode_text(context_batch, normalize=True).cpu()\n",
    "\n",
    "        text_features.append(batch_text_features)\n",
    "    text_features = torch.cat(text_features).view(list(context.shape[:-1]) + [-1])\n",
    "\n",
    "    return text_features"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# load the possible names\n",
    "possible_names = pd.read_csv('./full_names.csv', index_col=0)\n",
    "possible_names\n",
    "# possible_names_list = (possible_names['first_name'] + ' ' + possible_names['last_name']).tolist()\n",
    "# possible_names_list[:5]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# populate the prompts with the possible names\n",
    "prompts = []\n",
    "for idx, row in possible_names.iterrows():\n",
    "    df_dict = row.to_dict()\n",
    "    name = f'{row[\"first_name\"]} {row[\"last_name\"]}'\n",
    "    for prompt_idx, prompt in enumerate(PROMPTS):\n",
    "        df_dict[f'prompt_{prompt_idx}'] = prompt.format(name)\n",
    "    prompts.append(df_dict)\n",
    "prompts = pd.DataFrame(prompts)\n",
    "prompts"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "label_context_vecs_per_model = {}\n",
    "for dict_key, model_dict in MODELS.items():\n",
    "    label_context_vecs = []\n",
    "    for i in range(len(PROMPTS)):\n",
    "        context = model_dict['tokenizer'](prompts[f'prompt_{i}'].to_numpy())\n",
    "        label_context_vecs.append(context)\n",
    "    label_context_vecs = torch.stack(label_context_vecs)\n",
    "    label_context_vecs_per_model[dict_key] = label_context_vecs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "text_embeddings_per_model = {}\n",
    "for dict_key, model_dict in MODELS.items():\n",
    "    label_context_vecs = label_context_vecs_per_model[dict_key].to(device)\n",
    "    model = model_dict['model_instance']\n",
    "    model = model.to(device)\n",
    "    text_embeddings = get_text_embeddings(model, label_context_vecs, use_tqdm=True, context_batchsize=5_000)\n",
    "    text_embeddings_per_model[dict_key] = text_embeddings\n",
    "    model = model.cpu()\n",
    "    label_context_vecs = label_context_vecs.cpu()\n",
    "\n",
    "label_context_vecs = label_context_vecs.cpu()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# save the calculated embeddings to a file\n",
    "if not os.path.exists('./prompt_text_embeddings'):\n",
    "    os.makedirs('./prompt_text_embeddings')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "for (model_name, dataset_name), model_dict in MODELS.items():\n",
    "    torch.save(\n",
    "        text_embeddings_per_model[(model_name, dataset_name)],\n",
    "        f'./prompt_text_embeddings/{model_name}_{dataset_name}_prompt_text_embeddings.pt'\n",
    "    )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}