File size: 9,440 Bytes
6f73e46 |
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 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "98ce61eb-4c8d-469d-8659-4111a327e201",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/home/[email protected]/miniconda3/envs/nebula-fav2/lib/python3.10/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
" from .autonotebook import tqdm as notebook_tqdm\n"
]
}
],
"source": [
"import numpy as np\n",
"import json\n",
"import torch\n",
"import faiss\n",
"from faiss import write_index, read_index\n",
"from datasets import load_dataset\n",
"from transformers import AutoModelForCausalLM, AutoModel, AutoTokenizer\n",
"\n",
"def mean_pooling(token_embeddings, mask):\n",
" token_embeddings = token_embeddings.masked_fill(~mask[..., None].bool(), 0.)\n",
" sentence_embeddings = token_embeddings.sum(dim=1) / mask.sum(dim=1)[..., None]\n",
" return sentence_embeddings"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "094073a6-4bff-4b01-9113-155f61fffb2f",
"metadata": {},
"outputs": [],
"source": [
"tokenizer = AutoTokenizer.from_pretrained('facebook/contriever-msmarco')\n",
"model = AutoModel.from_pretrained('facebook/contriever-msmarco').bfloat16().to('cuda:6')"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "76218cd9-224d-41f1-9eab-45dea6344ba9",
"metadata": {
"scrolled": true
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Found cached dataset json (/home/[email protected]/.cache/huggingface/datasets/juewang___json/juewang--target-data-c3c1f1a2fb7fca38/0.0.0/8bb11242116d547c741b2e8a1f18598ffdd40a1d4f2a2872c7a28b697434bc96)\n"
]
}
],
"source": [
"dataset = load_dataset(\"juewang/target-data\", data_files='seed_data/*.jsonl', split='train')"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "5e476ab1-8ce4-4bb7-bcdc-c478deaad17c",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Found cached dataset json (/home/[email protected]/.cache/huggingface/datasets/json/default-708d018dd07be607/0.0.0/8bb11242116d547c741b2e8a1f18598ffdd40a1d4f2a2872c7a28b697434bc96)\n"
]
}
],
"source": [
"train_data = load_dataset('json', data_files='/var/cr01_data/danfu_data/rp_data_raw/wikipedia/wiki.jsonl', split='train')"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "e1aa498d-7efc-4bfb-84ee-2a4b218edadc",
"metadata": {},
"outputs": [],
"source": [
"index = read_index('../indexed_data/wiki.index')"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "bfe20b55-cc3e-44a7-8906-86236c3c7f6a",
"metadata": {},
"outputs": [],
"source": [
"def get_top_k_ids(text, model, tokenizer, dataset, index, k=10):\n",
" with torch.no_grad():\n",
" inputs = tokenizer(text, return_tensors=\"pt\", padding=True, truncation=True).to(model.device)\n",
" embeddings = model(**inputs)[0]\n",
" embeddings = mean_pooling(embeddings, inputs['attention_mask'])\n",
" query = embeddings.cpu().float().numpy()\n",
" _, ids = index.search(query, k=10)\n",
" ids = ids[0]\n",
" return ids\n",
"\n",
"def get_top_k_texts(text, model, tokenizer, dataset, index, k=10):\n",
" ids = get_top_k_ids(text, model, tokenizer, dataset, index, k)\n",
" return dataset[ids]['text']"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "9bcc1fa9-2e41-4cc3-aec1-73d2f2b05636",
"metadata": {},
"outputs": [],
"source": [
"text = dataset[100]['text']\n",
"text = \"Where is Zurich?\""
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "d530ae3c-4e7b-4efc-9bb4-41d2ee775b05",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([14544188, 9938757, 14601534, 14662044, 13195100, 13045513,\n",
" 8653245, 9002935, 9202244, 8153863])"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"get_top_k_ids(text, model, tokenizer, dataset, index, k=10)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "218954dc-fd29-4bf0-a1a1-7fbd2d200a54",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['Zurich',\n",
" 'Stadt Zürich may refer to:\\n\\n Zurich, a city in Switzerland\\n Stadt Zürich (ship, 1855), a Swiss paddle steamer\\n Stadt Zürich (ship, 1909), a Swiss paddle steamer',\n",
" 'Lausanne',\n",
" 'Lausanne',\n",
" 'Le district de Pfäffikon est un district du canton de Zurich en Suisse.\\n\\nCommunes\\n\\nNotes et références \\n\\nPfäffikon',\n",
" \"Rapperswil, commune suisse du canton de Berne.\\n Rapperswil, ancienne commune suisse du canton de Saint-Gall, aujourd'hui intégrée à Rapperswil-Jona.\",\n",
" 'Zürich Brunau () is a railway station in the Swiss city of Zürich. The station is on the Sihltal line which is operated by the Sihltal Zürich Uetliberg Bahn (SZU).\\n\\nThe station is served by the following passenger trains:\\n\\nReferences\\n\\nExternal links \\n \\n\\nBrunau',\n",
" 'Au railway station, or Au station, may refer to:\\n\\n Au SG railway station, in the Swiss canton of St. Gallen\\n Au ZH railway station, in the Swiss canton of Zürich\\n Au (Sieg) railway station, in the German state of North Rhine-Westphalia',\n",
" 'Lindenhof may refer to:\\n\\n Switzerland\\n Lindenhof (Rapperswil), a hill and historical core of Rapperswil.\\n Lindenhof (Zürich), district of that name in its correct name.\\n Lindenhof, district or geographical location of that name.\\n Lindenhof (quarter), district of that name, redirect to Altstadt (Zürich)\\n Lindenhof hill, geographical formation, moraine, and public hilltop square in Zürich\\n Oppidum Zürich-Lindenhof\\n Germany\\n Lindenhof locality in Hatzfeld\\n Theater Lindenhof nearby Burladingen',\n",
" 'Zürich Leimbach () is a railway station in the south-west of the Swiss city of Zürich, in the Leimbach quarter. The station is on the Sihltal line, which is operated by the Sihltal Zürich Uetliberg Bahn (SZU).\\n\\nThe station is served by the following passenger trains:\\n\\nReferences \\n\\nLeimbach']"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"get_top_k_texts(text, model, tokenizer, train_data, index, k=10)"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "153ee8cd-1885-468e-aa4d-207504cc8f1f",
"metadata": {},
"outputs": [],
"source": [
"import tqdm"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "7a3f05ad-7fb0-4173-86cf-91b3569bb052",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"109613"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"len(dataset)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6f143f0a-5915-4e9b-935e-3a3451b407bf",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
" 1%|█▎ | 901/109613 [00:07<14:06, 128.43it/s]"
]
}
],
"source": [
"ids_set = set()\n",
"for item in tqdm.tqdm(dataset):\n",
" text = item['text']\n",
" ids = get_top_k_ids(text, model, tokenizer, dataset, index, k=10).tolist()\n",
" ids_set.update(ids)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6e356e18-a038-464e-843b-949490781770",
"metadata": {},
"outputs": [],
"source": [
"with open('../train_data/from_wiki_k10.jsonl', 'w') as f:\n",
" for idx in tqdm.tqdm(ids_set):\n",
" item = train_data[idx]\n",
" text = item['text']\n",
" if len(text) < 16: # remove text that is too short\n",
" continue\n",
" f.write(\n",
" json.dumps({'text': text, 'source': 'wiki'}) + '\\n'\n",
" )"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "682bb8e0-8e21-4090-ad1c-ccb0b49ac9bb",
"metadata": {},
"outputs": [],
"source": [
"exit()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "fb09a384-453d-4519-be82-89019f859ce8",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "nebula-fav2",
"language": "python",
"name": "nebula-fav2"
},
"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.10.11"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|