nazneen commited on
Commit
505c984
β€’
1 Parent(s): c0e5866
Files changed (1) hide show
  1. assets/notebooks/seal_imdb.ipynb +542 -0
assets/notebooks/seal_imdb.ipynb ADDED
@@ -0,0 +1,542 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 13,
6
+ "metadata": {},
7
+ "outputs": [],
8
+ "source": [
9
+ "import pandas as pd\n",
10
+ "pd.set_option('display.max_colwidth', 0)\n",
11
+ "import numpy as np\n",
12
+ "import torch\n",
13
+ "import math\n",
14
+ "import openai\n",
15
+ "from collections import defaultdict\n",
16
+ "from tqdm import tqdm\n",
17
+ "from transformers import AutoTokenizer\n",
18
+ "import nltk\n",
19
+ "from nltk.cluster import KMeansClusterer\n",
20
+ "import scipy.spatial.distance as sdist\n",
21
+ "from scipy.spatial import distance_matrix\n",
22
+ "import matplotlib.pyplot as plt\n",
23
+ "from datasets import load_dataset\n"
24
+ ]
25
+ },
26
+ {
27
+ "cell_type": "code",
28
+ "execution_count": 9,
29
+ "metadata": {},
30
+ "outputs": [],
31
+ "source": [
32
+ "import sys\n",
33
+ "sys.path.append('../../seal/')\n",
34
+ "from run_inference import run_inference"
35
+ ]
36
+ },
37
+ {
38
+ "cell_type": "code",
39
+ "execution_count": 5,
40
+ "metadata": {},
41
+ "outputs": [],
42
+ "source": [
43
+ "dataset = 'imdb'\n",
44
+ "model = 'lvwerra/distilbert-imdb'"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 14,
50
+ "metadata": {},
51
+ "outputs": [],
52
+ "source": [
53
+ "tokenizer = AutoTokenizer.from_pretrained(model)"
54
+ ]
55
+ },
56
+ {
57
+ "cell_type": "code",
58
+ "execution_count": 15,
59
+ "metadata": {},
60
+ "outputs": [
61
+ {
62
+ "name": "stderr",
63
+ "output_type": "stream",
64
+ "text": [
65
+ "2022-08-09 21:41:20.800 WARNING datasets.builder: Reusing dataset imdb (/Users/nazneenrajani/.cache/huggingface/datasets/imdb/plain_text/1.0.0/2fdd8b9bcadd6e7055e742a706876ba43f19faee861df134affd7a3f60fc38a1)\n"
66
+ ]
67
+ },
68
+ {
69
+ "ename": "ValueError",
70
+ "evalue": "Connection error, and we cannot find the requested files in the cached path. Please try again or make sure your Internet connection is on.",
71
+ "output_type": "error",
72
+ "traceback": [
73
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
74
+ "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)",
75
+ "\u001b[1;32m/Users/nazneenrajani/workspace/spaces/seal/assets/notebooks/seal_imdb.ipynb Cell 5\u001b[0m in \u001b[0;36m<cell line: 1>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> <a href='vscode-notebook-cell:/Users/nazneenrajani/workspace/spaces/seal/assets/notebooks/seal_imdb.ipynb#ch0000024?line=0'>1</a>\u001b[0m run_inference(dataset\u001b[39m=\u001b[39;49mdataset,model\u001b[39m=\u001b[39;49mmodel,split\u001b[39m=\u001b[39;49m\u001b[39m'\u001b[39;49m\u001b[39mtest\u001b[39;49m\u001b[39m'\u001b[39;49m)\n",
76
+ "File \u001b[0;32m~/workspace/spaces/seal/assets/notebooks/../../seal/run_inference.py:38\u001b[0m, in \u001b[0;36mrun_inference\u001b[0;34m(dataset, model, split, output_path)\u001b[0m\n\u001b[1;32m 37\u001b[0m \u001b[39mdef\u001b[39;00m \u001b[39mrun_inference\u001b[39m(dataset\u001b[39m=\u001b[39m\u001b[39m'\u001b[39m\u001b[39myelp_polarity\u001b[39m\u001b[39m'\u001b[39m, model\u001b[39m=\u001b[39m\u001b[39m'\u001b[39m\u001b[39mtextattack/albert-base-v2-yelp-polarity\u001b[39m\u001b[39m'\u001b[39m, split\u001b[39m=\u001b[39m\u001b[39m'\u001b[39m\u001b[39mtest\u001b[39m\u001b[39m'\u001b[39m, output_path\u001b[39m=\u001b[39m\u001b[39m'\u001b[39m\u001b[39m./assets/data/inference_results\u001b[39m\u001b[39m'\u001b[39m):\n\u001b[0;32m---> 38\u001b[0m tokenizer, dataloader \u001b[39m=\u001b[39m load_session(dataset,model,split)\n\u001b[1;32m 39\u001b[0m hook, hidden_layers \u001b[39m=\u001b[39m model\u001b[39m.\u001b[39mclassifier\u001b[39m.\u001b[39mregister_forward_hook(get_input(\u001b[39m'\u001b[39m\u001b[39mlast_layer\u001b[39m\u001b[39m'\u001b[39m))\n\u001b[1;32m 40\u001b[0m \u001b[39m# Run inference on entire dataset\u001b[39;00m\n",
77
+ "File \u001b[0;32m~/workspace/spaces/seal/assets/notebooks/../../seal/run_inference.py:24\u001b[0m, in \u001b[0;36mload_session\u001b[0;34m(dataset, model, split)\u001b[0m\n\u001b[1;32m 18\u001b[0m dataloader \u001b[39m=\u001b[39m DataLoader(\n\u001b[1;32m 19\u001b[0m dataset,\n\u001b[1;32m 20\u001b[0m batch_size\u001b[39m=\u001b[39m\u001b[39m256\u001b[39m, drop_last\u001b[39m=\u001b[39m\u001b[39mTrue\u001b[39;00m\n\u001b[1;32m 21\u001b[0m )\n\u001b[1;32m 23\u001b[0m model \u001b[39m=\u001b[39m AutoModelForSequenceClassification\u001b[39m.\u001b[39mfrom_pretrained(model)\n\u001b[0;32m---> 24\u001b[0m tokenizer \u001b[39m=\u001b[39m AutoTokenizer\u001b[39m.\u001b[39;49mfrom_pretrained(model)\n\u001b[1;32m 25\u001b[0m model\u001b[39m.\u001b[39meval()\n\u001b[1;32m 26\u001b[0m model\u001b[39m.\u001b[39mto(\u001b[39m'\u001b[39m\u001b[39mcpu\u001b[39m\u001b[39m'\u001b[39m)\n",
78
+ "File \u001b[0;32m~/miniconda3/envs/autoeval/lib/python3.9/site-packages/transformers/models/auto/tokenization_auto.py:471\u001b[0m, in \u001b[0;36mAutoTokenizer.from_pretrained\u001b[0;34m(cls, pretrained_model_name_or_path, *inputs, **kwargs)\u001b[0m\n\u001b[1;32m 468\u001b[0m \u001b[39mreturn\u001b[39;00m tokenizer_class\u001b[39m.\u001b[39mfrom_pretrained(pretrained_model_name_or_path, \u001b[39m*\u001b[39minputs, \u001b[39m*\u001b[39m\u001b[39m*\u001b[39mkwargs)\n\u001b[1;32m 470\u001b[0m \u001b[39m# Next, let's try to use the tokenizer_config file to get the tokenizer class.\u001b[39;00m\n\u001b[0;32m--> 471\u001b[0m tokenizer_config \u001b[39m=\u001b[39m get_tokenizer_config(pretrained_model_name_or_path, \u001b[39m*\u001b[39;49m\u001b[39m*\u001b[39;49mkwargs)\n\u001b[1;32m 472\u001b[0m config_tokenizer_class \u001b[39m=\u001b[39m tokenizer_config\u001b[39m.\u001b[39mget(\u001b[39m\"\u001b[39m\u001b[39mtokenizer_class\u001b[39m\u001b[39m\"\u001b[39m)\n\u001b[1;32m 473\u001b[0m tokenizer_auto_map \u001b[39m=\u001b[39m \u001b[39mNone\u001b[39;00m\n",
79
+ "File \u001b[0;32m~/miniconda3/envs/autoeval/lib/python3.9/site-packages/transformers/models/auto/tokenization_auto.py:332\u001b[0m, in \u001b[0;36mget_tokenizer_config\u001b[0;34m(pretrained_model_name_or_path, cache_dir, force_download, resume_download, proxies, use_auth_token, revision, local_files_only, **kwargs)\u001b[0m\n\u001b[1;32m 263\u001b[0m \u001b[39mdef\u001b[39;00m \u001b[39mget_tokenizer_config\u001b[39m(\n\u001b[1;32m 264\u001b[0m pretrained_model_name_or_path: Union[\u001b[39mstr\u001b[39m, os\u001b[39m.\u001b[39mPathLike],\n\u001b[1;32m 265\u001b[0m cache_dir: Optional[Union[\u001b[39mstr\u001b[39m, os\u001b[39m.\u001b[39mPathLike]] \u001b[39m=\u001b[39m \u001b[39mNone\u001b[39;00m,\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 272\u001b[0m \u001b[39m*\u001b[39m\u001b[39m*\u001b[39mkwargs,\n\u001b[1;32m 273\u001b[0m ):\n\u001b[1;32m 274\u001b[0m \u001b[39m\"\"\"\u001b[39;00m\n\u001b[1;32m 275\u001b[0m \u001b[39m Loads the tokenizer configuration from a pretrained model tokenizer configuration.\u001b[39;00m\n\u001b[1;32m 276\u001b[0m \n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 330\u001b[0m \u001b[39m tokenizer_config = get_tokenizer_config(\"tokenizer-test\")\u001b[39;00m\n\u001b[1;32m 331\u001b[0m \u001b[39m ```\"\"\"\u001b[39;00m\n\u001b[0;32m--> 332\u001b[0m resolved_config_file \u001b[39m=\u001b[39m get_file_from_repo(\n\u001b[1;32m 333\u001b[0m pretrained_model_name_or_path,\n\u001b[1;32m 334\u001b[0m TOKENIZER_CONFIG_FILE,\n\u001b[1;32m 335\u001b[0m cache_dir\u001b[39m=\u001b[39;49mcache_dir,\n\u001b[1;32m 336\u001b[0m force_download\u001b[39m=\u001b[39;49mforce_download,\n\u001b[1;32m 337\u001b[0m resume_download\u001b[39m=\u001b[39;49mresume_download,\n\u001b[1;32m 338\u001b[0m proxies\u001b[39m=\u001b[39;49mproxies,\n\u001b[1;32m 339\u001b[0m use_auth_token\u001b[39m=\u001b[39;49muse_auth_token,\n\u001b[1;32m 340\u001b[0m revision\u001b[39m=\u001b[39;49mrevision,\n\u001b[1;32m 341\u001b[0m local_files_only\u001b[39m=\u001b[39;49mlocal_files_only,\n\u001b[1;32m 342\u001b[0m )\n\u001b[1;32m 343\u001b[0m \u001b[39mif\u001b[39;00m resolved_config_file \u001b[39mis\u001b[39;00m \u001b[39mNone\u001b[39;00m:\n\u001b[1;32m 344\u001b[0m logger\u001b[39m.\u001b[39minfo(\u001b[39m\"\u001b[39m\u001b[39mCould not locate the tokenizer configuration file, will try to use the model config instead.\u001b[39m\u001b[39m\"\u001b[39m)\n",
80
+ "File \u001b[0;32m~/miniconda3/envs/autoeval/lib/python3.9/site-packages/transformers/utils/hub.py:678\u001b[0m, in \u001b[0;36mget_file_from_repo\u001b[0;34m(path_or_repo, filename, cache_dir, force_download, resume_download, proxies, use_auth_token, revision, local_files_only)\u001b[0m\n\u001b[1;32m 674\u001b[0m resolved_file \u001b[39m=\u001b[39m hf_bucket_url(path_or_repo, filename\u001b[39m=\u001b[39mfilename, revision\u001b[39m=\u001b[39mrevision, mirror\u001b[39m=\u001b[39m\u001b[39mNone\u001b[39;00m)\n\u001b[1;32m 676\u001b[0m \u001b[39mtry\u001b[39;00m:\n\u001b[1;32m 677\u001b[0m \u001b[39m# Load from URL or cache if already cached\u001b[39;00m\n\u001b[0;32m--> 678\u001b[0m resolved_file \u001b[39m=\u001b[39m cached_path(\n\u001b[1;32m 679\u001b[0m resolved_file,\n\u001b[1;32m 680\u001b[0m cache_dir\u001b[39m=\u001b[39;49mcache_dir,\n\u001b[1;32m 681\u001b[0m force_download\u001b[39m=\u001b[39;49mforce_download,\n\u001b[1;32m 682\u001b[0m proxies\u001b[39m=\u001b[39;49mproxies,\n\u001b[1;32m 683\u001b[0m resume_download\u001b[39m=\u001b[39;49mresume_download,\n\u001b[1;32m 684\u001b[0m local_files_only\u001b[39m=\u001b[39;49mlocal_files_only,\n\u001b[1;32m 685\u001b[0m use_auth_token\u001b[39m=\u001b[39;49muse_auth_token,\n\u001b[1;32m 686\u001b[0m )\n\u001b[1;32m 688\u001b[0m \u001b[39mexcept\u001b[39;00m RepositoryNotFoundError:\n\u001b[1;32m 689\u001b[0m \u001b[39mraise\u001b[39;00m \u001b[39mEnvironmentError\u001b[39;00m(\n\u001b[1;32m 690\u001b[0m \u001b[39mf\u001b[39m\u001b[39m\"\u001b[39m\u001b[39m{\u001b[39;00mpath_or_repo\u001b[39m}\u001b[39;00m\u001b[39m is not a local folder and is not a valid model identifier \u001b[39m\u001b[39m\"\u001b[39m\n\u001b[1;32m 691\u001b[0m \u001b[39m\"\u001b[39m\u001b[39mlisted on \u001b[39m\u001b[39m'\u001b[39m\u001b[39mhttps://huggingface.co/models\u001b[39m\u001b[39m'\u001b[39m\u001b[39m\\n\u001b[39;00m\u001b[39mIf this is a private repository, make sure to \u001b[39m\u001b[39m\"\u001b[39m\n\u001b[1;32m 692\u001b[0m \u001b[39m\"\u001b[39m\u001b[39mpass a token having permission to this repo with `use_auth_token` or log in with \u001b[39m\u001b[39m\"\u001b[39m\n\u001b[1;32m 693\u001b[0m \u001b[39m\"\u001b[39m\u001b[39m`huggingface-cli login` and pass `use_auth_token=True`.\u001b[39m\u001b[39m\"\u001b[39m\n\u001b[1;32m 694\u001b[0m )\n",
81
+ "File \u001b[0;32m~/miniconda3/envs/autoeval/lib/python3.9/site-packages/transformers/utils/hub.py:282\u001b[0m, in \u001b[0;36mcached_path\u001b[0;34m(url_or_filename, cache_dir, force_download, proxies, resume_download, user_agent, extract_compressed_file, force_extract, use_auth_token, local_files_only)\u001b[0m\n\u001b[1;32m 278\u001b[0m local_files_only \u001b[39m=\u001b[39m \u001b[39mTrue\u001b[39;00m\n\u001b[1;32m 280\u001b[0m \u001b[39mif\u001b[39;00m is_remote_url(url_or_filename):\n\u001b[1;32m 281\u001b[0m \u001b[39m# URL, so get it from the cache (downloading if necessary)\u001b[39;00m\n\u001b[0;32m--> 282\u001b[0m output_path \u001b[39m=\u001b[39m get_from_cache(\n\u001b[1;32m 283\u001b[0m url_or_filename,\n\u001b[1;32m 284\u001b[0m cache_dir\u001b[39m=\u001b[39;49mcache_dir,\n\u001b[1;32m 285\u001b[0m force_download\u001b[39m=\u001b[39;49mforce_download,\n\u001b[1;32m 286\u001b[0m proxies\u001b[39m=\u001b[39;49mproxies,\n\u001b[1;32m 287\u001b[0m resume_download\u001b[39m=\u001b[39;49mresume_download,\n\u001b[1;32m 288\u001b[0m user_agent\u001b[39m=\u001b[39;49muser_agent,\n\u001b[1;32m 289\u001b[0m use_auth_token\u001b[39m=\u001b[39;49muse_auth_token,\n\u001b[1;32m 290\u001b[0m local_files_only\u001b[39m=\u001b[39;49mlocal_files_only,\n\u001b[1;32m 291\u001b[0m )\n\u001b[1;32m 292\u001b[0m \u001b[39melif\u001b[39;00m os\u001b[39m.\u001b[39mpath\u001b[39m.\u001b[39mexists(url_or_filename):\n\u001b[1;32m 293\u001b[0m \u001b[39m# File, and it exists.\u001b[39;00m\n\u001b[1;32m 294\u001b[0m output_path \u001b[39m=\u001b[39m url_or_filename\n",
82
+ "File \u001b[0;32m~/miniconda3/envs/autoeval/lib/python3.9/site-packages/transformers/utils/hub.py:545\u001b[0m, in \u001b[0;36mget_from_cache\u001b[0;34m(url, cache_dir, force_download, proxies, etag_timeout, resume_download, user_agent, use_auth_token, local_files_only)\u001b[0m\n\u001b[1;32m 539\u001b[0m \u001b[39mraise\u001b[39;00m \u001b[39mFileNotFoundError\u001b[39;00m(\n\u001b[1;32m 540\u001b[0m \u001b[39m\"\u001b[39m\u001b[39mCannot find the requested files in the cached path and outgoing traffic has been\u001b[39m\u001b[39m\"\u001b[39m\n\u001b[1;32m 541\u001b[0m \u001b[39m\"\u001b[39m\u001b[39m disabled. To enable model look-ups and downloads online, set \u001b[39m\u001b[39m'\u001b[39m\u001b[39mlocal_files_only\u001b[39m\u001b[39m'\u001b[39m\u001b[39m\"\u001b[39m\n\u001b[1;32m 542\u001b[0m \u001b[39m\"\u001b[39m\u001b[39m to False.\u001b[39m\u001b[39m\"\u001b[39m\n\u001b[1;32m 543\u001b[0m )\n\u001b[1;32m 544\u001b[0m \u001b[39melse\u001b[39;00m:\n\u001b[0;32m--> 545\u001b[0m \u001b[39mraise\u001b[39;00m \u001b[39mValueError\u001b[39;00m(\n\u001b[1;32m 546\u001b[0m \u001b[39m\"\u001b[39m\u001b[39mConnection error, and we cannot find the requested files in the cached path.\u001b[39m\u001b[39m\"\u001b[39m\n\u001b[1;32m 547\u001b[0m \u001b[39m\"\u001b[39m\u001b[39m Please try again or make sure your Internet connection is on.\u001b[39m\u001b[39m\"\u001b[39m\n\u001b[1;32m 548\u001b[0m )\n\u001b[1;32m 550\u001b[0m \u001b[39m# From now on, etag is not None.\u001b[39;00m\n\u001b[1;32m 551\u001b[0m \u001b[39mif\u001b[39;00m os\u001b[39m.\u001b[39mpath\u001b[39m.\u001b[39mexists(cache_path) \u001b[39mand\u001b[39;00m \u001b[39mnot\u001b[39;00m force_download:\n",
83
+ "\u001b[0;31mValueError\u001b[0m: Connection error, and we cannot find the requested files in the cached path. Please try again or make sure your Internet connection is on."
84
+ ]
85
+ }
86
+ ],
87
+ "source": [
88
+ "run_inference(dataset=dataset,model=model,split='test')"
89
+ ]
90
+ },
91
+ {
92
+ "cell_type": "code",
93
+ "execution_count": 2,
94
+ "metadata": {},
95
+ "outputs": [],
96
+ "source": [
97
+ "def kmeans(df, num_clusters=3):\n",
98
+ " X = np.array(df['embedding'].tolist())\n",
99
+ " kclusterer = KMeansClusterer(\n",
100
+ " num_clusters, distance=nltk.cluster.util.cosine_distance,\n",
101
+ " repeats=25,avoid_empty_clusters=True)\n",
102
+ " assigned_clusters = kclusterer.cluster(X, assign_clusters=True)\n",
103
+ " df['cluster'] = pd.Series(assigned_clusters, index=df.index).astype('int')\n",
104
+ " df['centroid'] = df['cluster'].apply(lambda x: kclusterer.means()[x])\n",
105
+ " return df"
106
+ ]
107
+ },
108
+ {
109
+ "cell_type": "code",
110
+ "execution_count": 3,
111
+ "metadata": {},
112
+ "outputs": [],
113
+ "source": [
114
+ "def cluster_errors(data_hl):\n",
115
+ " merged = pd.DataFrame()\n",
116
+ " ind=0\n",
117
+ " num_clusters=0 #cluster count so far\n",
118
+ " for df in data_hl:\n",
119
+ " if 'cluster' in df.columns:\n",
120
+ " df = df.drop(columns=['cluster','centroid'])\n",
121
+ " kmeans_df = kmeans(df,num_clusters=int(math.sqrt(len(df)/2)))\n",
122
+ " #print(kmeans_df.loc[kmeans_df['cluster'].idxmax()])\n",
123
+ " df['cluster'] = kmeans_df['cluster'] + num_clusters\n",
124
+ " num_clusters=num_clusters + int(math.sqrt(len(df)/2))\n",
125
+ " ind = ind+1\n",
126
+ " merged = pd.concat([merged, df], ignore_index=True)\n",
127
+ " return merged"
128
+ ]
129
+ },
130
+ {
131
+ "cell_type": "code",
132
+ "execution_count": 3,
133
+ "metadata": {},
134
+ "outputs": [],
135
+ "source": [
136
+ "from sklearn.metrics import accuracy_score\n",
137
+ "def generate_groups(merged):\n",
138
+ " clusters = merged.groupby('cluster')\n",
139
+ " groups = {x: clusters.get_group(x) for x in clusters.groups}\n",
140
+ " cluster_acc = {x: accuracy_score(clusters.get_group(x)['label'].values.tolist(), clusters.get_group(x)['pred'].values.tolist()) for x in clusters.groups}\n",
141
+ " return groups, cluster_acc\n",
142
+ "\n",
143
+ "def dict_zip(*dicts):\n",
144
+ " all_keys = {k for d in dicts for k in d.keys()}\n",
145
+ " return {k: [d[k] for d in dicts if k in d] for k in all_keys}\n",
146
+ "\n",
147
+ "def semantic_labeling(groups):\n",
148
+ " group_labels= {gidx: generate_group_label(cluster) for gidx, cluster in tqdm(groups.items())}\n",
149
+ " error_groups= dict_zip(group_labels,{k: [len(v), v.iloc[0].label] for k, v in groups.items()})\n",
150
+ " return error_groups\n",
151
+ "\n",
152
+ "def generate_group_label(cluster):\n",
153
+ " #instruction = \"In this task, we'll assign a short and precise label to a cluster of documents based on the topics or concepts most relevant to these documents. The documents are all subsets of a sentiment classification dataset. Here are some examples of high-quality labels:\\nDocuments:\\n - Like Clay P who posted before me, I too love pancakes. Though I love chocolate chip pancakes. But like Clay I did not love the ones that I got a the Original Pancake House. Typically, restaurants just don't do it the way I like them and I have come to expect that. Grading OPH on those terms, they did a respectable job. It is definitely a worthwhile destination for a pancake lover.\\n - Very small portions, but good food. Had a perfectly cooked fillet minion, but $60 and they could have served with a toothpick, it was so small. \\nSame for rest of our party. Excellent salmon, but maybe 5 bites again $60. \\nEverything is a la carte so sides extra. Thai papaya salad good, and key lime pie great.\\n - $65 per person to share ONE ribeye? Yes you read that correctly. We had our annual guys trip to vegas and we always try to visit a different steak house every time we visit. This year was Carnevino. We were surprised in order to order a ribeye or porterhouse, TWO people had to order it. We found it a bit odd but we had no problems with it. We found it even more odd the waiter suggested we have the steaks family style (they cut up the meat and put it on a plate for people to share). Anyways, a bunch us order different cuts of meat. NY Strip, Filet Mignon and the folks that wanted port.\\n - This place was a flop. Was visiting a friend in Chandler and found this place on mobile Yelp. Had 68-something reviews and 4/5 stars which almost always means it will be a good place. Boy I was wrong this time.\\n\\nI hate those lengthy reviews talking about unimportant things so I'll stick to the main point. The restaurant itself was clean and you can sit down comfortably.\\n\\nThe waiter highly recommended the pork avodovo plate, which is pork that is served doused with either a green or red sauce with beans and rice on the side. I cannot take spicy food, and the waiter insisted the red version\\n Label: overpriced and spicy food\"\n",
154
+ " instruction = \"In this task, we'll assign a short and precise label to a cluster of documents based on the topics or concepts most relevant to these documents. The documents are all subsets of a sentiment classification dataset.\\n\"\n",
155
+ " prompt = build_prompt(instruction, cluster)\n",
156
+ " resp = openai.Completion.create(\n",
157
+ " prompt=prompt,\n",
158
+ " engine='text-davinci-002',\n",
159
+ " #frequency_penalty = 1.2,\n",
160
+ " )\n",
161
+ " label = resp['choices'][0]['text']\n",
162
+ " return label.strip()\n",
163
+ "\n",
164
+ "#code to build prompt and query gpt3 for labeling\n",
165
+ "def build_prompt(instruction, cluster_df):\n",
166
+ " if len(cluster_df)>10:\n",
167
+ " content = cluster_df['content'].str[:600].tolist()\n",
168
+ " else:\n",
169
+ " content = cluster_df['content'].str[:1000].tolist()\n",
170
+ " examples = '\\n - '.join(content)\n",
171
+ " text = instruction + '- ' + examples+ '\\n Cluster label:'\n",
172
+ " return text.strip()"
173
+ ]
174
+ },
175
+ {
176
+ "cell_type": "code",
177
+ "execution_count": null,
178
+ "metadata": {},
179
+ "outputs": [],
180
+ "source": []
181
+ },
182
+ {
183
+ "cell_type": "code",
184
+ "execution_count": 6,
185
+ "metadata": {},
186
+ "outputs": [],
187
+ "source": [
188
+ "data_df_imdb = pd.read_parquet('./imdb_test_distillbert.parquet')\n",
189
+ "data_df_imdb = data_df_imdb.drop_duplicates(subset=['content'])\n",
190
+ "data_df_imdb['loss'] = data_df_imdb['loss'].astype(float)\n",
191
+ "losses = data_df_imdb['loss']\n",
192
+ "high_loss = losses.quantile(0.99)\n",
193
+ "data_df_imdb['slice'] = 'high-loss'\n",
194
+ "data_df_imdb['slice'] = data_df_imdb['slice'].where(data_df_imdb['loss'] > high_loss, 'low-loss')\n",
195
+ "data_hl_imdb = data_df_imdb.drop(data_df_imdb[data_df_imdb['slice'] == 'low-loss'].index)\n",
196
+ "data_ll_imdb = data_df_imdb.drop(data_df_imdb[data_df_imdb['slice'] == 'high-loss'].index) \n",
197
+ "df_list_imdb = [d for _, d in data_hl_imdb.groupby(['label'])]"
198
+ ]
199
+ },
200
+ {
201
+ "cell_type": "code",
202
+ "execution_count": 7,
203
+ "metadata": {},
204
+ "outputs": [],
205
+ "source": [
206
+ "tmp = data_df_imdb.drop_duplicates(subset=['content'])"
207
+ ]
208
+ },
209
+ {
210
+ "cell_type": "code",
211
+ "execution_count": 8,
212
+ "metadata": {},
213
+ "outputs": [],
214
+ "source": [
215
+ "data_df_imdb = tmp"
216
+ ]
217
+ },
218
+ {
219
+ "cell_type": "code",
220
+ "execution_count": 9,
221
+ "metadata": {},
222
+ "outputs": [
223
+ {
224
+ "data": {
225
+ "text/plain": [
226
+ "0.8622382730076287"
227
+ ]
228
+ },
229
+ "execution_count": 9,
230
+ "metadata": {},
231
+ "output_type": "execute_result"
232
+ }
233
+ ],
234
+ "source": [
235
+ "accuracy_score(data_df_imdb['label'],data_df_imdb['pred'])"
236
+ ]
237
+ },
238
+ {
239
+ "cell_type": "code",
240
+ "execution_count": 22,
241
+ "metadata": {},
242
+ "outputs": [],
243
+ "source": [
244
+ "merged_lvl0=cluster_errors(df_list_imdb)\n",
245
+ "groups_lvl0,acc_lvl0 = generate_groups(merged_lvl0)"
246
+ ]
247
+ },
248
+ {
249
+ "cell_type": "code",
250
+ "execution_count": 23,
251
+ "metadata": {},
252
+ "outputs": [],
253
+ "source": [
254
+ "merged_lvl1=cluster_errors(groups_lvl0.values())\n",
255
+ "groups_lvl1,acc_lvl1 = generate_groups(merged_lvl1)"
256
+ ]
257
+ },
258
+ {
259
+ "cell_type": "code",
260
+ "execution_count": 24,
261
+ "metadata": {},
262
+ "outputs": [
263
+ {
264
+ "name": "stdout",
265
+ "output_type": "stream",
266
+ "text": [
267
+ "32\n",
268
+ "33\n"
269
+ ]
270
+ }
271
+ ],
272
+ "source": [
273
+ "print(merged_lvl1['cluster'].max())\n",
274
+ "print(len(groups_lvl1))"
275
+ ]
276
+ },
277
+ {
278
+ "cell_type": "code",
279
+ "execution_count": 27,
280
+ "metadata": {},
281
+ "outputs": [
282
+ {
283
+ "name": "stderr",
284
+ "output_type": "stream",
285
+ "text": [
286
+ "100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 33/33 [00:41<00:00, 1.27s/it]\n"
287
+ ]
288
+ }
289
+ ],
290
+ "source": [
291
+ "cluster_labels= semantic_labeling(groups_lvl1)"
292
+ ]
293
+ },
294
+ {
295
+ "cell_type": "code",
296
+ "execution_count": 52,
297
+ "metadata": {},
298
+ "outputs": [
299
+ {
300
+ "name": "stdout",
301
+ "output_type": "stream",
302
+ "text": [
303
+ "43 0.6976744186046512\n"
304
+ ]
305
+ }
306
+ ],
307
+ "source": [
308
+ "match = data_df_imdb[data_df_imdb['content'].str.contains('hamlet' , case=False)]\n",
309
+ "print(len(match), accuracy_score(match['label'], match['pred']))"
310
+ ]
311
+ },
312
+ {
313
+ "cell_type": "code",
314
+ "execution_count": 51,
315
+ "metadata": {},
316
+ "outputs": [
317
+ {
318
+ "data": {
319
+ "text/plain": [
320
+ "6 5.065617\n",
321
+ "61 3.967897\n",
322
+ "143 4.062117\n",
323
+ "285 4.036336\n",
324
+ "313 4.622490\n",
325
+ " ... \n",
326
+ "24580 3.634398\n",
327
+ "24605 4.533525\n",
328
+ "24659 3.830003\n",
329
+ "24708 4.107304\n",
330
+ "24751 4.207838\n",
331
+ "Name: loss, Length: 493, dtype: float64"
332
+ ]
333
+ },
334
+ "execution_count": 51,
335
+ "metadata": {},
336
+ "output_type": "execute_result"
337
+ }
338
+ ],
339
+ "source": [
340
+ "losses.loc[losses>high_loss]"
341
+ ]
342
+ },
343
+ {
344
+ "cell_type": "code",
345
+ "execution_count": 37,
346
+ "metadata": {},
347
+ "outputs": [],
348
+ "source": [
349
+ "losses = data_df_imdb['loss']\n",
350
+ "high_loss = losses.quantile(0.98)\n",
351
+ "loss_weights = np.where(losses > high_loss,losses,0.0)\n",
352
+ "loss_weights = loss_weights / loss_weights.sum()"
353
+ ]
354
+ },
355
+ {
356
+ "cell_type": "code",
357
+ "execution_count": 50,
358
+ "metadata": {},
359
+ "outputs": [
360
+ {
361
+ "data": {
362
+ "text/plain": [
363
+ "24644"
364
+ ]
365
+ },
366
+ "execution_count": 50,
367
+ "metadata": {},
368
+ "output_type": "execute_result"
369
+ }
370
+ ],
371
+ "source": [
372
+ "len(data_df_imdb)"
373
+ ]
374
+ },
375
+ {
376
+ "cell_type": "code",
377
+ "execution_count": 14,
378
+ "metadata": {},
379
+ "outputs": [
380
+ {
381
+ "name": "stderr",
382
+ "output_type": "stream",
383
+ "text": [
384
+ "100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 24644/24644 [00:16<00:00, 1519.28it/s]\n"
385
+ ]
386
+ }
387
+ ],
388
+ "source": [
389
+ "unique_tokens = []\n",
390
+ "tokens = []\n",
391
+ "for row in tqdm(data_df_imdb['content']):\n",
392
+ " tokenized = tokenizer(row,padding=True, return_tensors='pt', truncation=True)\n",
393
+ " tokens.append(tokenized['input_ids'].flatten())\n",
394
+ " unique_tokens.append(torch.unique(tokenized['input_ids']))"
395
+ ]
396
+ },
397
+ {
398
+ "cell_type": "code",
399
+ "execution_count": 36,
400
+ "metadata": {},
401
+ "outputs": [
402
+ {
403
+ "data": {
404
+ "text/plain": [
405
+ "0 9.110757e-06\n",
406
+ "1 3.830380e-04\n",
407
+ "2 1.652545e-06\n",
408
+ "3 7.110300e-05\n",
409
+ "4 1.504268e-04\n",
410
+ " ... \n",
411
+ "24816 1.350308e-05\n",
412
+ "24828 2.056361e-06\n",
413
+ "24829 6.765310e-07\n",
414
+ "24830 6.537001e-07\n",
415
+ "24831 6.824863e-06\n",
416
+ "Name: loss, Length: 24644, dtype: float64"
417
+ ]
418
+ },
419
+ "execution_count": 36,
420
+ "metadata": {},
421
+ "output_type": "execute_result"
422
+ }
423
+ ],
424
+ "source": [
425
+ "loss_weights"
426
+ ]
427
+ },
428
+ {
429
+ "cell_type": "code",
430
+ "execution_count": 29,
431
+ "metadata": {},
432
+ "outputs": [
433
+ {
434
+ "data": {
435
+ "text/plain": [
436
+ "24644"
437
+ ]
438
+ },
439
+ "execution_count": 29,
440
+ "metadata": {},
441
+ "output_type": "execute_result"
442
+ }
443
+ ],
444
+ "source": [
445
+ "len(data_df_imdb)"
446
+ ]
447
+ },
448
+ {
449
+ "cell_type": "code",
450
+ "execution_count": 55,
451
+ "metadata": {},
452
+ "outputs": [],
453
+ "source": [
454
+ "def frequent_tokens(data, tokenizer, loss_quantile=0.98, top_k=200, smoothing=0.005):\n",
455
+ " unique_tokens = []\n",
456
+ " tokens = []\n",
457
+ " for row in tqdm(data['content']):\n",
458
+ " tokenized = tokenizer(row, padding=True, truncation=True, return_tensors='pt')\n",
459
+ " tokens.append(tokenized['input_ids'].flatten())\n",
460
+ " unique_tokens.append(torch.unique(tokenized['input_ids']))\n",
461
+ " losses = data['loss'].astype(float)\n",
462
+ " high_loss = losses.quantile(loss_quantile)\n",
463
+ " loss_weights = np.where(losses > high_loss,losses,0.0)\n",
464
+ " loss_weights = loss_weights / loss_weights.sum()\n",
465
+ "\n",
466
+ " token_frequencies = defaultdict(float)\n",
467
+ " token_frequencies_error = defaultdict(float)\n",
468
+ " weights_uniform = np.full_like(loss_weights, 1 / len(loss_weights))\n",
469
+ "\n",
470
+ " for i in tqdm(range(len(data))):\n",
471
+ " for token in unique_tokens[i]:\n",
472
+ " token_frequencies[token.item()] += weights_uniform[i]\n",
473
+ " token_frequencies_error[token.item()] += loss_weights[i]\n",
474
+ "\n",
475
+ " token_lrs = {k: (smoothing+token_frequencies_error[k]) / (\n",
476
+ " smoothing+token_frequencies[k]) for k in token_frequencies}\n",
477
+ " tokens_sorted = list(map(lambda x: x[0], sorted(\n",
478
+ " token_lrs.items(), key=lambda x: x[1])[::-1]))\n",
479
+ "\n",
480
+ " top_tokens = []\n",
481
+ " for i, (token) in enumerate(tokens_sorted[:top_k]):\n",
482
+ " top_tokens.append(['%10s' % (tokenizer.decode(token)), '%.4f' % (token_frequencies[token]), '%.4f' % (\n",
483
+ " token_frequencies_error[token]), '%4.2f' % (token_lrs[token])])\n",
484
+ " return pd.DataFrame(top_tokens, columns=['token', 'freq', 'error-freq', 'ratio'])"
485
+ ]
486
+ },
487
+ {
488
+ "cell_type": "code",
489
+ "execution_count": 56,
490
+ "metadata": {},
491
+ "outputs": [
492
+ {
493
+ "name": "stderr",
494
+ "output_type": "stream",
495
+ "text": [
496
+ "100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 24644/24644 [00:15<00:00, 1551.93it/s]\n",
497
+ "100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 24644/24644 [00:05<00:00, 4428.85it/s]\n"
498
+ ]
499
+ }
500
+ ],
501
+ "source": [
502
+ "commontokens = frequent_tokens(data_df_imdb,AutoTokenizer.from_pretrained('lvwerra/distilbert-imdb'))"
503
+ ]
504
+ },
505
+ {
506
+ "cell_type": "code",
507
+ "execution_count": 58,
508
+ "metadata": {},
509
+ "outputs": [],
510
+ "source": [
511
+ "commontokens.to_parquet('./assets/data/imdb_test_distillbert_tokens.parquet')"
512
+ ]
513
+ }
514
+ ],
515
+ "metadata": {
516
+ "kernelspec": {
517
+ "display_name": "Python 3.9.13 ('autoeval')",
518
+ "language": "python",
519
+ "name": "python3"
520
+ },
521
+ "language_info": {
522
+ "codemirror_mode": {
523
+ "name": "ipython",
524
+ "version": 3
525
+ },
526
+ "file_extension": ".py",
527
+ "mimetype": "text/x-python",
528
+ "name": "python",
529
+ "nbconvert_exporter": "python",
530
+ "pygments_lexer": "ipython3",
531
+ "version": "3.9.13"
532
+ },
533
+ "orig_nbformat": 4,
534
+ "vscode": {
535
+ "interpreter": {
536
+ "hash": "f312122f3ed45eefb96eb2533558f359e32fabfee58d97447889ae824b25bd02"
537
+ }
538
+ }
539
+ },
540
+ "nbformat": 4,
541
+ "nbformat_minor": 2
542
+ }