{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# JACKET V1 のデータセットに wikipedia のコンテキストを追加したデータセットの作成\n", "\n", "- https://sites.google.com/view/project-aio/dataset?authuser=0\n", "\n", "の CC BY-SA 4.0 DEED 該当データをもとに、Wikipedia のコンテキスト追加した HuggingFace Dataset を作成する\n" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# JAQKET データセットを取得\n", "\n", "from dataclasses import dataclass\n", "import json\n", "import urllib.request\n", "import random\n", "\n", "random.seed(42)\n", "\n", "# https://sites.google.com/view/project-aio/dataset?authuser=0\n", "# 以下のURLのデータは、ライセンスが CC BY-SA 4.0 DEED\n", "\n", "jaqket_urls = [\n", " \"https://jaqket.s3.ap-northeast-1.amazonaws.com/data/aio_02/aio_01_dev.jsonl\",\n", " \"https://jaqket.s3.ap-northeast-1.amazonaws.com/data/aio_02/aio_01_test.jsonl\",\n", " \"https://jaqket.s3.ap-northeast-1.amazonaws.com/data/aio_02/aio_01_unused.jsonl\",\n", "]\n", "\n", "\n", "@dataclass\n", "class JaqketQuestion_:\n", " qid: str\n", " question: str\n", " original_question: str\n", " answer_entity: str\n", " answer_candidates: list[str]\n", " answer_candidates_shuffled: list[str]\n", " label: int\n", " original_answer: str | None = None\n", "\n", "\n", "@dataclass\n", "class JaqketQuestion:\n", " qid: str\n", " competition: str\n", " timestamp: str\n", " section: str\n", " number: str\n", " original_question: str\n", " original_answer: str | None\n", " original_additional_info: str | None\n", " question: str\n", " answers: list[str]\n", "\n", "\n", "def load_jaqket(urls: list[str]):\n", " res = []\n", " for url in urls:\n", " with urllib.request.urlopen(url) as f:\n", " # f は 1行ごとに処理\n", " data = [json.loads(line.decode(\"utf-8\")) for line in f]\n", " for d in data:\n", " try:\n", " res.append(JaqketQuestion(**d))\n", " except Exception as e:\n", " # d.keys\n", " print(d.keys())\n", " raise e\n", " return res\n", "\n", "\n", "jacket_data = load_jaqket(jaqket_urls)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(4600, 10)" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import pandas as pd\n", "\n", "jacket_df = pd.DataFrame(jacket_data)\n", "jacket_df.shape" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
qidcompetitiontimestampsectionnumberoriginal_questionoriginal_answeroriginal_additional_infoquestionanswersanswer
0QA20CAPR-0002第1回AI王2019/12/25開発データ問題 (dev1)2明治時代に西洋から伝わった「テーブル・ターニング」に起源を持つ占いの一種で、50音表などを記...コックリさん明治時代に西洋から伝わった「テーブル・ターニング」に起源を持つ占いの一種で、50音表などを記...[コックリさん]コックリさん
\n", "
" ], "text/plain": [ " qid competition timestamp section number \\\n", "0 QA20CAPR-0002 第1回AI王 2019/12/25 開発データ問題 (dev1) 2 \n", "\n", " original_question original_answer \\\n", "0 明治時代に西洋から伝わった「テーブル・ターニング」に起源を持つ占いの一種で、50音表などを記... コックリさん \n", "\n", " original_additional_info question \\\n", "0 明治時代に西洋から伝わった「テーブル・ターニング」に起源を持つ占いの一種で、50音表などを記... \n", "\n", " answers answer \n", "0 [コックリさん] コックリさん " ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# none は \"\" に変換\n", "jacket_df = jacket_df.fillna(\"\")\n", "# answers の最初の一つを入れる\n", "jacket_df.loc[:, \"answer\"] = jacket_df[\"answers\"].apply(lambda x: x[0])\n", "jacket_df.head(1)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "train_df = jacket_df" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/home/yu1/miniconda3/envs/llm-sc/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": [ "from datasets.download import DownloadManager\n", "from datasets import load_dataset\n", "from sentence_transformers import SentenceTransformer\n", "import faiss\n", "\n", "# wikipedia 日本語データセットのロード\n", "wikija_dataset = load_dataset(\n", " path=\"singletongue/wikipedia-utils\",\n", " name=\"passages-c400-jawiki-20230403\",\n", " split=\"train\",\n", ")\n", "# faiss index のダウンロード\n", "dm = DownloadManager()\n", "index_local_path = dm.download(\n", " f\"https://huggingface.co/datasets/hotchpotch/wikipedia-passages-jawiki-embeddings/resolve/main/faiss_indexes/passages-c400-jawiki-20230403/multilingual-e5-large-query/index_IVF2048_PQ256.faiss\"\n", ")\n", "# index_local_path = dm.download(\n", "# f\"https://huggingface.co/datasets/hotchpotch/wikipedia-passages-jawiki-embeddings/resolve/main/faiss_indexes/passages-c400-jawiki-20230403/multilingual-e5-large-passage/index_IVF2048_PQ256.faiss\"\n", "# )\n", "# faiss index のロード\n", "faiss_index = faiss.read_index(index_local_path)\n", "\n", "# embeddings へ変換するモデルのロード\n", "emb_model = SentenceTransformer(\"intfloat/multilingual-e5-large\", device=\"cuda\")\n", "emb_model.max_seq_length = 512" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(2, 1024)" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# embeddings へ変換\n", "def texts_to_embs(model, texts, prefix=\"query: \"):\n", " texts = [prefix + text for text in texts]\n", " return model.encode(texts, normalize_embeddings=True)\n", "\n", "\n", "texts_to_embs(emb_model, [\"こんにちは\", \"こんばんは\"]).shape" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(3919, 12)" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# wikipedia のデータから、RAG検索して Top-N に正解の単語が含まれているデータのみを抽出する\n", "\n", "\n", "def df_correct_answer_add_context(df, top_n=3):\n", " # faiss index で検索して、top-N に正解があれば、その context を追加してそのデータのみを返す\n", " df = df.copy().reset_index(drop=True)\n", " df[\"context\"] = None\n", " texts = df[\"question\"].tolist()\n", " embs = texts_to_embs(emb_model, texts)\n", " scores, indexes = faiss_index.search(embs, top_n)\n", " for pos, (score, index) in enumerate(zip(scores, indexes)):\n", " df_data = df.iloc[pos]\n", " answer = df_data[\"answer\"]\n", " target_texts = []\n", " for s, i in zip(score, index):\n", " data = wikija_dataset[int(i)] # type: ignore\n", " target_texts.append(data[\"title\"] + \" \" + data[\"text\"]) # type: ignore\n", " check_text = str(target_texts)\n", " # 検索結果に対象文字列を含むか\n", " if answer in check_text:\n", " df.at[pos, \"context\"] = target_texts\n", " # top3_text が None でないデータのみ返す\n", " return df[df[\"context\"].notnull()]\n", "\n", "\n", "train_df = df_correct_answer_add_context(train_df, 3)\n", "train_df.shape" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
qidquestionanswercontextanswerscompetitiontimestampsectionnumberoriginal_questionoriginal_answeroriginal_additional_info
0QA20CAPR-0002明治時代に西洋から伝わった「テーブル・ターニング」に起源を持つ占いの一種で、50音表などを記...コックリさん[コックリさん その起源は明確ではないが、レオナルド・ダ・ヴィンチが自著において「テーブル・...[コックリさん]第1回AI王2019/12/25開発データ問題 (dev1)2明治時代に西洋から伝わった「テーブル・ターニング」に起源を持つ占いの一種で、50音表などを記...コックリさん
\n", "
" ], "text/plain": [ " qid question answer \\\n", "0 QA20CAPR-0002 明治時代に西洋から伝わった「テーブル・ターニング」に起源を持つ占いの一種で、50音表などを記... コックリさん \n", "\n", " context answers competition \\\n", "0 [コックリさん その起源は明確ではないが、レオナルド・ダ・ヴィンチが自著において「テーブル・... [コックリさん] 第1回AI王 \n", "\n", " timestamp section number \\\n", "0 2019/12/25 開発データ問題 (dev1) 2 \n", "\n", " original_question original_answer \\\n", "0 明治時代に西洋から伝わった「テーブル・ターニング」に起源を持つ占いの一種で、50音表などを記... コックリさん \n", "\n", " original_additional_info \n", "0 " ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# qid, question, answer, context が先頭のカラムに来るように並び替える。過去のカラムも残す\n", "new_columns = [\"qid\", \"question\", \"answer\", \"context\", \"answers\"]\n", "new_columns.extend([c for c in train_df.columns if c not in new_columns])\n", "train_df = train_df[new_columns]\n", "train_df.head(1)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "import datasets\n", "\n", "# pandas to dataset\n", "train_dataset = datasets.Dataset.from_pandas(train_df)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "Dataset({\n", " features: ['qid', 'question', 'answer', 'context', 'answers', 'competition', 'timestamp', 'section', 'number', 'original_question', 'original_answer', 'original_additional_info', '__index_level_0__'],\n", " num_rows: 3919\n", "})" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "train_dataset" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "((2939, 12), (980, 12))" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 25% を validation にする\n", "valid_df = train_df.sample(frac=0.25, random_state=42)\n", "train_df = train_df.drop(valid_df.index)\n", "train_df = train_df.reset_index(drop=True)\n", "valid_df = valid_df.reset_index(drop=True)\n", "# shape\n", "train_df.shape, valid_df.shape" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "from datasets import Dataset\n", "\n", "train_ds = Dataset.from_pandas(train_df)\n", "valid_ds = Dataset.from_pandas(valid_df)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "dataset_hf_path = \"hotchpotch/jaqket_v1_qa_wikija_context\"" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Creating parquet from Arrow format: 100%|██████████| 3/3 [00:00<00:00, 116.44ba/s]\n", "Uploading the dataset shards: 100%|██████████| 1/1 [00:02<00:00, 2.39s/it]\n", "Creating parquet from Arrow format: 100%|██████████| 1/1 [00:00<00:00, 58.50ba/s]\n", "Uploading the dataset shards: 100%|██████████| 1/1 [00:01<00:00, 2.00s/it]\n", "README.md: 100%|██████████| 715/715 [00:00<00:00, 3.93MB/s]\n" ] } ], "source": [ "train_ds.push_to_hub(dataset_hf_path, split=\"train\")\n", "valid_ds.push_to_hub(dataset_hf_path, split=\"validation\")" ] } ], "metadata": { "kernelspec": { "display_name": "llm-sc", "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.10.12" } }, "nbformat": 4, "nbformat_minor": 2 }