{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "98ce61eb-4c8d-469d-8659-4111a327e201", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/home/jue@together.xyz/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/jue@together.xyz/.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/jue@together.xyz/.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 }