CoolFace
Apppublic

GungnirAP/Youtube-Comments

sourceHugging Faceapache-2.0updated 3y agoView on Hugging Face
0likes
Training.ipynb2198 linesDownload Raw Back to root
1{2 "cells": [3  {4   "cell_type": "markdown",5   "id": "available-trauma",6   "metadata": {7    "id": "following-action"8   },9   "source": [10    "## Описание задачи"11   ]12  },13  {14   "cell_type": "markdown",15   "id": "express-warrant",16   "metadata": {17    "id": "vocal-corner"18   },19   "source": [20    "Задача: Сгенерировать youtube-комментарии по _ссылке_ на видео\n",21    "\n",22    "Всё просто, юзер постит ссылку на видео - вы его комментируете. Можно заранее обусловиться что видео только на английском или на русском. Нужно сочинить _несколько_ комментариев. Kudos если вместе с основным комментарием вы порождаете юзернеймы и-или ответы на него.\n",23    "\n",24    "\n",25    "Датасет для файнтюна можно [взять с kaggle](https://www.kaggle.com/tanmay111/youtube-comments-sentiment-analysis/data?select=UScomments.csv) или [собрать самостоятельно](https://towardsdatascience.com/how-to-build-your-own-dataset-of-youtube-comments-39a1e57aade).\n",26    "\n",27    "В качестве основной модели можно использовать [GPT-2 large](https://huggingface.co/gpt2-large). Вот как её файнтюнить: https://tinyurl.com/gpt2-finetune-colab. \n",28    "\n",29    "Если хотите больше - можно взять что-то из творчества https://huggingface.co/EleutherAI. Например, вот [тут](https://tinyurl.com/gpt-j-8bit) есть пример как файнтюнить GPT-J-6B (в 8 раз больше gpt2-large). Однако, этим стоит заниматься уже после того, как у вас заработал базовый сценарий с GPT2-large или даже base.\n",30    "\n",31    "В итоговом сервисе можно дать пользователю вариировать параметры генерации: \n",32    "- температура или top-p, если сэмплинг; \n",33    "- beam size и length penalty, если beam search; \n",34    "- сколько комментариев сгенерировать, etc. \n",35    "\n",36    "Отдельный респект если ваш код будет выводить комментарий по одному слову, прямо в процессе генерёжки - чтобы пользователь не ждал пока вы настругаете абзац целиком.\n",37    "\n",38    "\n",39    "\n"40   ]41  },42  {43   "cell_type": "markdown",44   "id": "deadly-sensitivity",45   "metadata": {46    "id": "RvtIWT89zQWX"47   },48   "source": [49    "# Подготовка датасета"50   ]51  },52  {53   "cell_type": "code",54   "execution_count": null,55   "id": "unnecessary-shame",56   "metadata": {57    "id": "final-liquid",58    "outputId": "07c50913-ce77-47c2-ec42-729016b020b9"59   },60   "outputs": [61    {62     "name": "stdout",63     "output_type": "stream",64     "text": [65      "Archive:  USvideos.csv.zip\n",66      "\n",67      "  inflating: USvideos.csv            \n"68     ]69    }70   ],71   "source": [72    "# !unzip UScomments.csv.zip\n",73    "# !unzip USvideos.csv.zip\n",74    "\n",75    "# !pip install datasets transformers\n",76    "# !pip install bitsandbytes\n",77    "# !pip install nltk\n",78    "# !pip install langdetect"79   ]80  },81  {82   "cell_type": "code",83   "execution_count": 118,84   "id": "clinical-beauty",85   "metadata": {86    "id": "excessive-ownership"87   },88   "outputs": [],89   "source": [90    "# import nltk\n",91    "# nltk.download('stopwords')\n",92    "# nltk.download('wordnet')"93   ]94  },95  {96   "cell_type": "code",97   "execution_count": 42,98   "id": "attended-friend",99   "metadata": {100    "id": "needed-bikini"101   },102   "outputs": [],103   "source": [104    "from tqdm import tqdm\n",105    "import pandas as pd\n",106    "import string\n",107    "import re\n",108    "\n",109    "import datasets\n",110    "import transformers\n",111    "from transformers import pipeline, set_seed\n",112    "\n",113    "from nltk.stem import WordNetLemmatizer\n",114    "from nltk.corpus import stopwords\n",115    "\n",116    "import torch\n",117    "from torch.utils.data import Dataset, DataLoader\n",118    "import bitsandbytes as bnb"119   ]120  },121  {122   "cell_type": "code",123   "execution_count": 43,124   "id": "decreased-processing",125   "metadata": {126    "id": "fifteen-instrument"127   },128   "outputs": [],129   "source": [130    "# generator = pipeline('text-generation', model='gpt2-large')\n",131    "# set_seed(42)\n",132    "# generator(\"The man worked as a\", max_length=10, num_return_sequences=5)"133   ]134  },135  {136   "cell_type": "markdown",137   "id": "monthly-growing",138   "metadata": {139    "id": "disturbed-banner"140   },141   "source": [142    "### Готовим комментарии"143   ]144  },145  {146   "cell_type": "code",147   "execution_count": 190,148   "id": "classified-olive",149   "metadata": {150    "colab": {151     "base_uri": "https://localhost:8080/"152    },153    "id": "bronze-distributor",154    "outputId": "20c0252b-28c1-4365-e813-b7df3df010de"155   },156   "outputs": [157    {158     "name": "stderr",159     "output_type": "stream",160     "text": [161      "<ipython-input-190-7f1bcf368402>:1: DtypeWarning: Columns (2,3) have mixed types. Specify dtype option on import or set low_memory=False.\n",162      "\n",163      "  df = pd.read_csv(\"UScomments.csv\", on_bad_lines='skip')\n",164      "\n",165      "<ipython-input-190-7f1bcf368402>:4: SettingWithCopyWarning: \n",166      "\n",167      "A value is trying to be set on a copy of a slice from a DataFrame.\n",168      "\n",169      "Try using .loc[row_indexer,col_indexer] = value instead\n",170      "\n",171      "\n",172      "\n",173      "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n",174      "\n",175      "  df['likes'] = df['likes'].astype(int)\n",176      "\n",177      "<ipython-input-190-7f1bcf368402>:5: SettingWithCopyWarning: \n",178      "\n",179      "A value is trying to be set on a copy of a slice from a DataFrame.\n",180      "\n",181      "Try using .loc[row_indexer,col_indexer] = value instead\n",182      "\n",183      "\n",184      "\n",185      "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n",186      "\n",187      "  df['replies'] = df['replies'].astype(int)\n"188     ]189    }190   ],191   "source": [192    "df = pd.read_csv(\"UScomments.csv\", on_bad_lines='skip')\n",193    "df.video_id = df.video_id.astype(\"str\")\n",194    "df = df[df['likes'] != \"likes\"]\n",195    "df['likes'] = df['likes'].astype(int)\n",196    "df['replies'] = df['replies'].astype(int)\n",197    "df.dropna(inplace=True)"198   ]199  },200  {201   "cell_type": "code",202   "execution_count": 191,203   "id": "distant-solid",204   "metadata": {205    "colab": {206     "base_uri": "https://localhost:8080/"207    },208    "id": "cognitive-registration",209    "outputId": "aede1178-b0c5-42d4-9a43-55eb06250d12"210   },211   "outputs": [212    {213     "name": "stderr",214     "output_type": "stream",215     "text": [216      "100%|██████████| 6/6 [00:24<00:00,  4.02s/it]\n"217     ]218    }219   ],220   "source": [221    "df['cleaned_txt'] = df['comment_text'].str.replace('#+', '#', regex=True).str.strip()\n",222    "normal_puncs = [\"!\", \"\\.\", \"?\", \",\", \":\", \";\"]\n",223    "for char in tqdm([\"!\", \"\\.\", \"?\", \",\", \":\", \";\"]):\n",224    "  char1 = char if char != \"\\.\" else \".\"\n",225    "  df['cleaned_txt'] = df['cleaned_txt'].str.replace(f'[\\s]*[{char}]+', f'{char1}', regex=True)\n",226    "\n",227    "df['cleaned_txt'] = df['cleaned_txt'].str.replace(\"[^a-zA-Z#'!?,\\.:;]\", \" \", regex=True)\n",228    "df['cleaned_txt'] = df['cleaned_txt'].str.replace(' +', ' ', regex=True)\n",229    "remove_short = lambda x: ' '.join([w for w in x.split() if len(w) > 1 or w in [\"I\", \"a\", \"A\", \"u\", \"U\"]])\n",230    "df['cleaned_txt'] = df['cleaned_txt'].apply(remove_short)\n",231    "df = df[~df['cleaned_txt'].str.startswith(\"https\")]\n",232    "df['cleaned_txt'] = df['cleaned_txt'].apply(lambda x: ' '.join([w for w in x.split() if len(w) < 30]))\n",233    "df = df[df['cleaned_txt'].str.len() > 1]\n",234    "\n",235    "df['num_of_words'] = df['cleaned_txt'].str.split().apply(lambda x: len(x))\n",236    "df = df[df.num_of_words < 50]\n",237    "df = df[df.num_of_words > 3].iloc[:, :-1]\n",238    "################################################################################################################\n",239    "# df['cleaned_txt'] = df['cleaned_txt'].apply(lambda x:x.lower())\n",240    "\n",241    "# wnl = WordNetLemmatizer()\n",242    "\n",243    "# tokenized_tweet = df['cleaned_txt'].apply(lambda x: x.split())\n",244    "# tokenized_tweet.apply(lambda x: [wnl.lemmatize(i) for i in x if i not in set(stopwords.words('english'))]) \n",245    "# for i in range(len(tokenized_tweet)):\n",246    "#     tokenized_tweet[i] = ' '.join(tokenized_tweet[i])\n",247    "# df['cleaned_txt'] = tokenized_tweet"248   ]249  },250  {251   "cell_type": "code",252   "execution_count": 165,253   "id": "looking-broadcast",254   "metadata": {255    "id": "according-midwest"256   },257   "outputs": [],258   "source": [259    "# from langdetect import detect, DetectorFactory\n",260    "\n",261    "# DetectorFactory.seed = 0\n",262    "\n",263    "# df_lang = df[df.groupby('video_id').cumcount().isin([0,1,2])]\n",264    "# texts = df_lang.cleaned_txt\n",265    "# results = []\n",266    "# for text in tqdm(texts):\n",267    "#     try:\n",268    "#         results.append(detect(text))\n",269    "#     except Exception:\n",270    "#         break\n",271    "# df_lang['lang'] = results"272   ]273  },274  {275   "cell_type": "markdown",276   "id": "secondary-floor",277   "metadata": {278    "id": "incorporated-count"279   },280   "source": [281    "### Приклеиваем инфо о видео"282   ]283  },284  {285   "cell_type": "code",286   "execution_count": 193,287   "id": "reserved-ultimate",288   "metadata": {289    "id": "checked-boxing"290   },291   "outputs": [],292   "source": [293    "videos = pd.read_csv(\"USvideos.csv\", on_bad_lines='skip')\n",294    "videos.video_id = videos.video_id.astype(str)\n",295    "videos.date = videos.date.astype(str).str.replace(\".1\", \".10\", regex=False)\n",296    "videos.date = pd.to_datetime(videos.date, format=\"%d.%m\")\n",297    "videos = videos.sort_values(by=[\"video_id\", \"date\"], ascending=[1, 0])\n",298    "videos = videos[videos.groupby(\"video_id\").cumcount(\"date\") == 0]"299   ]300  },301  {302   "cell_type": "code",303   "execution_count": 194,304   "id": "specialized-asset",305   "metadata": {306    "colab": {307     "base_uri": "https://localhost:8080/",308     "height": 206309    },310    "id": "numeric-groove",311    "outputId": "3c077cd6-1551-4b5d-f958-99711239d600"312   },313   "outputs": [314    {315     "data": {316      "text/html": [317       "\n",318       "  <div id=\"df-df806cae-3387-4f03-bdae-738a45dd3e06\">\n",319       "    <div class=\"colab-df-container\">\n",320       "      <div>\n",321       "<style scoped>\n",322       "    .dataframe tbody tr th:only-of-type {\n",323       "        vertical-align: middle;\n",324       "    }\n",325       "\n",326       "    .dataframe tbody tr th {\n",327       "        vertical-align: top;\n",328       "    }\n",329       "\n",330       "    .dataframe thead th {\n",331       "        text-align: right;\n",332       "    }\n",333       "</style>\n",334       "<table border=\"1\" class=\"dataframe\">\n",335       "  <thead>\n",336       "    <tr style=\"text-align: right;\">\n",337       "      <th></th>\n",338       "      <th>video_id</th>\n",339       "      <th>title</th>\n",340       "      <th>channel_title</th>\n",341       "      <th>comment_text</th>\n",342       "      <th>likes</th>\n",343       "      <th>replies</th>\n",344       "      <th>cleaned_txt</th>\n",345       "    </tr>\n",346       "  </thead>\n",347       "  <tbody>\n",348       "    <tr>\n",349       "      <th>0</th>\n",350       "      <td>--JinobXWPk</td>\n",351       "      <td>DANGEROUS Jungle Spider!</td>\n",352       "      <td>Brave Wilderness</td>\n",353       "      <td>I saw this wandering spider in our bathroom se...</td>\n",354       "      <td>0</td>\n",355       "      <td>0</td>\n",356       "      <td>I saw this wandering spider in our bathroom se...</td>\n",357       "    </tr>\n",358       "    <tr>\n",359       "      <th>1</th>\n",360       "      <td>--JinobXWPk</td>\n",361       "      <td>DANGEROUS Jungle Spider!</td>\n",362       "      <td>Brave Wilderness</td>\n",363       "      <td>Can't you just stick to small ants, and bees? ...</td>\n",364       "      <td>0</td>\n",365       "      <td>0</td>\n",366       "      <td>Can't you just stick to small ants, and bees? ...</td>\n",367       "    </tr>\n",368       "    <tr>\n",369       "      <th>2</th>\n",370       "      <td>--JinobXWPk</td>\n",371       "      <td>DANGEROUS Jungle Spider!</td>\n",372       "      <td>Brave Wilderness</td>\n",373       "      <td>Brazilian wandering spider is the deadliest sp...</td>\n",374       "      <td>0</td>\n",375       "      <td>0</td>\n",376       "      <td>Brazilian wandering spider is the deadliest sp...</td>\n",377       "    </tr>\n",378       "    <tr>\n",379       "      <th>3</th>\n",380       "      <td>--JinobXWPk</td>\n",381       "      <td>DANGEROUS Jungle Spider!</td>\n",382       "      <td>Brave Wilderness</td>\n",383       "      <td>Nothing a can of hairspray and lighter couldn'...</td>\n",384       "      <td>0</td>\n",385       "      <td>0</td>\n",386       "      <td>Nothing a can of hairspray and lighter couldn'...</td>\n",387       "    </tr>\n",388       "    <tr>\n",389       "      <th>4</th>\n",390       "      <td>--JinobXWPk</td>\n",391       "      <td>DANGEROUS Jungle Spider!</td>\n",392       "      <td>Brave Wilderness</td>\n",393       "      <td>Hey Coyote! Can you do an episode on the Japan...</td>\n",394       "      <td>0</td>\n",395       "      <td>0</td>\n",396       "      <td>Hey Coyote! Can you do an episode on the Japan...</td>\n",397       "    </tr>\n",398       "  </tbody>\n",399       "</table>\n",400       "</div>\n",401       "      <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-df806cae-3387-4f03-bdae-738a45dd3e06')\"\n",402       "              title=\"Convert this dataframe to an interactive table.\"\n",403       "              style=\"display:none;\">\n",404       "        \n",405       "  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n",406       "       width=\"24px\">\n",407       "    <path d=\"M0 0h24v24H0V0z\" fill=\"none\"/>\n",408       "    <path d=\"M18.56 5.44l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94zm-11 1L8.5 8.5l.94-2.06 2.06-.94-2.06-.94L8.5 2.5l-.94 2.06-2.06.94zm10 10l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94z\"/><path d=\"M17.41 7.96l-1.37-1.37c-.4-.4-.92-.59-1.43-.59-.52 0-1.04.2-1.43.59L10.3 9.45l-7.72 7.72c-.78.78-.78 2.05 0 2.83L4 21.41c.39.39.9.59 1.41.59.51 0 1.02-.2 1.41-.59l7.78-7.78 2.81-2.81c.8-.78.8-2.07 0-2.86zM5.41 20L4 18.59l7.72-7.72 1.47 1.35L5.41 20z\"/>\n",409       "  </svg>\n",410       "      </button>\n",411       "      \n",412       "  <style>\n",413       "    .colab-df-container {\n",414       "      display:flex;\n",415       "      flex-wrap:wrap;\n",416       "      gap: 12px;\n",417       "    }\n",418       "\n",419       "    .colab-df-convert {\n",420       "      background-color: #E8F0FE;\n",421       "      border: none;\n",422       "      border-radius: 50%;\n",423       "      cursor: pointer;\n",424       "      display: none;\n",425       "      fill: #1967D2;\n",426       "      height: 32px;\n",427       "      padding: 0 0 0 0;\n",428       "      width: 32px;\n",429       "    }\n",430       "\n",431       "    .colab-df-convert:hover {\n",432       "      background-color: #E2EBFA;\n",433       "      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",434       "      fill: #174EA6;\n",435       "    }\n",436       "\n",437       "    [theme=dark] .colab-df-convert {\n",438       "      background-color: #3B4455;\n",439       "      fill: #D2E3FC;\n",440       "    }\n",441       "\n",442       "    [theme=dark] .colab-df-convert:hover {\n",443       "      background-color: #434B5C;\n",444       "      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",445       "      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",446       "      fill: #FFFFFF;\n",447       "    }\n",448       "  </style>\n",449       "\n",450       "      <script>\n",451       "        const buttonEl =\n",452       "          document.querySelector('#df-df806cae-3387-4f03-bdae-738a45dd3e06 button.colab-df-convert');\n",453       "        buttonEl.style.display =\n",454       "          google.colab.kernel.accessAllowed ? 'block' : 'none';\n",455       "\n",456       "        async function convertToInteractive(key) {\n",457       "          const element = document.querySelector('#df-df806cae-3387-4f03-bdae-738a45dd3e06');\n",458       "          const dataTable =\n",459       "            await google.colab.kernel.invokeFunction('convertToInteractive',\n",460       "                                                     [key], {});\n",461       "          if (!dataTable) return;\n",462       "\n",463       "          const docLinkHtml = 'Like what you see? Visit the ' +\n",464       "            '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",465       "            + ' to learn more about interactive tables.';\n",466       "          element.innerHTML = '';\n",467       "          dataTable['output_type'] = 'display_data';\n",468       "          await google.colab.output.renderOutput(dataTable, element);\n",469       "          const docLink = document.createElement('div');\n",470       "          docLink.innerHTML = docLinkHtml;\n",471       "          element.appendChild(docLink);\n",472       "        }\n",473       "      </script>\n",474       "    </div>\n",475       "  </div>\n",476       "  "477      ],478      "text/plain": [479       "      video_id                     title     channel_title  \\\n",480       "0  --JinobXWPk  DANGEROUS Jungle Spider!  Brave Wilderness   \n",481       "1  --JinobXWPk  DANGEROUS Jungle Spider!  Brave Wilderness   \n",482       "2  --JinobXWPk  DANGEROUS Jungle Spider!  Brave Wilderness   \n",483       "3  --JinobXWPk  DANGEROUS Jungle Spider!  Brave Wilderness   \n",484       "4  --JinobXWPk  DANGEROUS Jungle Spider!  Brave Wilderness   \n",485       "\n",486       "                                        comment_text  likes  replies  \\\n",487       "0  I saw this wandering spider in our bathroom se...      0        0   \n",488       "1  Can't you just stick to small ants, and bees? ...      0        0   \n",489       "2  Brazilian wandering spider is the deadliest sp...      0        0   \n",490       "3  Nothing a can of hairspray and lighter couldn'...      0        0   \n",491       "4  Hey Coyote! Can you do an episode on the Japan...      0        0   \n",492       "\n",493       "                                         cleaned_txt  \n",494       "0  I saw this wandering spider in our bathroom se...  \n",495       "1  Can't you just stick to small ants, and bees? ...  \n",496       "2  Brazilian wandering spider is the deadliest sp...  \n",497       "3  Nothing a can of hairspray and lighter couldn'...  \n",498       "4  Hey Coyote! Can you do an episode on the Japan...  "499      ]500     },501     "execution_count": 194,502     "metadata": {},503     "output_type": "execute_result"504    }505   ],506   "source": [507    "df_full = videos[[\"video_id\", \"title\", \"channel_title\"]].merge(df, \n",508    "                                                               left_on='video_id', right_on='video_id')\n",509    "df_full[\"title\"] = df_full[\"title\"]#.str.lower()\n",510    "df_full[\"channel_title\"] = df_full[\"channel_title\"]#.str.lower()\n",511    "df_full[\"cleaned_txt\"] = df_full[\"cleaned_txt\"]#.str.lower()\n",512    "df_full.head()"513   ]514  },515  {516   "cell_type": "markdown",517   "id": "foreign-thomas",518   "metadata": {519    "id": "completed-constitution"520   },521   "source": [522    "Будем использовать zero-shot обучение со следующим prompt'ом:\n",523    "\n",524    "Train:  \n",525    "\\<BOS>CHANNEL: _channel_title_   \n",526    "VIDEO: _video_title_  \n",527    "COMMENTARY: _comment text_ \\<EOS>\n",528    "\n",529    "Test:  \n",530    "\\<BOS>CHANNEL: _channel_title_   \n",531    "VIDEO: _video_title_  \n",532    "COMMENTARY:"533   ]534  },535  {536   "cell_type": "code",537   "execution_count": 195,538   "id": "innocent-input",539   "metadata": {540    "id": "fleet-whole"541   },542   "outputs": [],543   "source": [544    "# prompts = \"<BOS>CHANNEL: \" + df_full[\"channel_title\"] + \\\n",545    "#           \" TITLE: \" + df_full[\"title\"] + \\\n",546    "#           \" COMMENT: \" + df_full[\"cleaned_txt\"] + \" <EOS>\"\n",547    "# print(prompts[0])"548   ]549  },550  {551   "cell_type": "code",552   "execution_count": 196,553   "id": "christian-bridge",554   "metadata": {555    "colab": {556     "base_uri": "https://localhost:8080/"557    },558    "id": "feyKViRnqJc0",559    "outputId": "2cc22150-c92e-4533-92da-1c9ffafbe7b6"560   },561   "outputs": [562    {563     "name": "stdout",564     "output_type": "stream",565     "text": [566      "<BOS> TOPIC: DANGEROUS Jungle Spider! COMMENT: I saw this wandering spider in our bathroom seriously I'm not lying. nPS I will never go to Costa Rica!: <EOS>\n"567     ]568    }569   ],570   "source": [571    "prompts = \"<BOS> TOPIC: \" + df_full[\"title\"] + \\\n",572    "          \" COMMENT: \" + df_full[\"cleaned_txt\"] + \" <EOS>\"\n",573    "print(prompts[0])"574   ]575  },576  {577   "cell_type": "code",578   "execution_count": 197,579   "id": "coordinate-dependence",580   "metadata": {581    "colab": {582     "base_uri": "https://localhost:8080/"583    },584    "id": "subsequent-elevation",585    "outputId": "7f4c87db-9ec3-40eb-f930-ca11c069dfe7"586   },587   "outputs": [588    {589     "name": "stdout",590     "output_type": "stream",591     "text": [592      "<BOS> TOPIC: Best Tom Petty Interview Ever COMMENT: Where are the other interviews Gary Chandling did? <EOS>\n"593     ]594    }595   ],596   "source": [597    "print(prompts[140])"598   ]599  },600  {601   "cell_type": "code",602   "execution_count": 198,603   "id": "speaking-province",604   "metadata": {605    "id": "french-accountability"606   },607   "outputs": [],608   "source": [609    "df_full[\"prompt\"] = prompts"610   ]611  },612  {613   "cell_type": "code",614   "execution_count": 199,615   "id": "dynamic-desperate",616   "metadata": {617    "id": "trained-seattle"618   },619   "outputs": [],620   "source": [621    "df_full.reset_index(inplace=True, drop=True)"622   ]623  },624  {625   "cell_type": "code",626   "execution_count": 200,627   "id": "polished-strike",628   "metadata": {629    "id": "bottom-knowing"630   },631   "outputs": [],632   "source": [633    "train_index = df_full.sample(int(df_full.shape[0] * 0.9), random_state=42).index\n",634    "df_full.loc[train_index].reset_index(drop=True).to_csv(\"prompts_train_02.csv\")\n",635    "\n",636    "test_index = list(set(df_full.index) - set(train_index))\n",637    "df_full.loc[test_index].reset_index(drop=True).to_csv(\"prompts_test_02.csv\")\n"638   ]639  },640  {641   "cell_type": "markdown",642   "id": "executive-coalition",643   "metadata": {644    "id": "exterior-cache"645   },646   "source": [647    "# Подготовка к обучению"648   ]649  },650  {651   "cell_type": "code",652   "execution_count": 1,653   "id": "simplified-tactics",654   "metadata": {655    "colab": {656     "base_uri": "https://localhost:8080/"657    },658    "execution": {659     "iopub.execute_input": "2023-04-12T20:14:52.485955Z",660     "iopub.status.busy": "2023-04-12T20:14:52.485487Z",661     "iopub.status.idle": "2023-04-12T20:14:52.517276Z",662     "shell.execute_reply": "2023-04-12T20:14:52.516185Z",663     "shell.execute_reply.started": "2023-04-12T20:14:52.485920Z"664    },665    "id": "3bV3N11hc0Al",666    "outputId": "93c03b10-28f5-4bdd-d6d7-20e71a9eb8e7"667   },668   "outputs": [],669   "source": [670    "# from google.colab import drive\n",671    "# drive.mount('/content/gdrive')"672   ]673  },674  {675   "cell_type": "code",676   "execution_count": 2,677   "id": "editorial-arbor",678   "metadata": {679    "colab": {680     "base_uri": "https://localhost:8080/"681    },682    "execution": {683     "iopub.execute_input": "2023-04-12T20:14:52.565111Z",684     "iopub.status.busy": "2023-04-12T20:14:52.564822Z",685     "iopub.status.idle": "2023-04-12T20:14:52.570092Z",686     "shell.execute_reply": "2023-04-12T20:14:52.568747Z",687     "shell.execute_reply.started": "2023-04-12T20:14:52.565083Z"688    },689    "id": "MWde5q5jdZc2",690    "outputId": "7865e7ff-45bc-474c-fa65-7f7e4e362a8a"691   },692   "outputs": [],693   "source": [694    "# %cd ./gdrive/MyDrive/Colab Notebooks/ml2"695   ]696  },697  {698   "cell_type": "code",699   "execution_count": 1,700   "id": "featured-stone",701   "metadata": {702    "execution": {703     "iopub.execute_input": "2023-04-13T07:37:44.002545Z",704     "iopub.status.busy": "2023-04-13T07:37:44.002222Z",705     "iopub.status.idle": "2023-04-13T07:37:45.096711Z",706     "shell.execute_reply": "2023-04-13T07:37:45.094948Z",707     "shell.execute_reply.started": "2023-04-13T07:37:44.002513Z"708    }709   },710   "outputs": [],711   "source": [712    "!mkdir ./chkp"713   ]714  },715  {716   "cell_type": "code",717   "execution_count": 2,718   "id": "starting-guide",719   "metadata": {720    "colab": {721     "base_uri": "https://localhost:8080/"722    },723    "collapsed": true,724    "execution": {725     "iopub.execute_input": "2023-04-13T07:37:45.107352Z",726     "iopub.status.busy": "2023-04-13T07:37:45.104451Z",727     "iopub.status.idle": "2023-04-13T07:38:15.679220Z",728     "shell.execute_reply": "2023-04-13T07:38:15.677863Z",729     "shell.execute_reply.started": "2023-04-13T07:37:45.107302Z"730    },731    "id": "NNYGCW1xdUsn",732    "outputId": "7475a204-3194-4961-d71c-16779fdaf981"733   },734   "outputs": [735    {736     "name": "stdout",737     "output_type": "stream",738     "text": [739      "Collecting bitsandbytes\n",740      "  Downloading bitsandbytes-0.38.1-py3-none-any.whl (104.3 MB)\n",741      "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m104.3/104.3 MB\u001b[0m \u001b[31m8.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m00:01\u001b[0m00:01\u001b[0m\n",742      "\u001b[?25hInstalling collected packages: bitsandbytes\n",743      "Successfully installed bitsandbytes-0.38.1\n",744      "\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",745      "\u001b[0mRequirement already satisfied: datasets in /opt/conda/lib/python3.7/site-packages (2.1.0)\n",746      "Requirement already satisfied: transformers in /opt/conda/lib/python3.7/site-packages (4.27.4)\n",747      "Requirement already satisfied: pandas in /opt/conda/lib/python3.7/site-packages (from datasets) (1.3.5)\n",748      "Requirement already satisfied: multiprocess in /opt/conda/lib/python3.7/site-packages (from datasets) (0.70.14)\n",749      "Requirement already satisfied: tqdm>=4.62.1 in /opt/conda/lib/python3.7/site-packages (from datasets) (4.64.1)\n",750      "Requirement already satisfied: xxhash in /opt/conda/lib/python3.7/site-packages (from datasets) (3.2.0)\n",751      "Requirement already satisfied: packaging in /opt/conda/lib/python3.7/site-packages (from datasets) (23.0)\n",752      "Requirement already satisfied: pyarrow>=5.0.0 in /opt/conda/lib/python3.7/site-packages (from datasets) (5.0.0)\n",753      "Requirement already satisfied: importlib-metadata in /opt/conda/lib/python3.7/site-packages (from datasets) (4.11.4)\n",754      "Requirement already satisfied: dill in /opt/conda/lib/python3.7/site-packages (from datasets) (0.3.6)\n",755      "Requirement already satisfied: responses<0.19 in /opt/conda/lib/python3.7/site-packages (from datasets) (0.18.0)\n",756      "Requirement already satisfied: fsspec[http]>=2021.05.0 in /opt/conda/lib/python3.7/site-packages (from datasets) (2023.1.0)\n",757      "Requirement already satisfied: requests>=2.19.0 in /opt/conda/lib/python3.7/site-packages (from datasets) (2.28.2)\n",758      "Requirement already satisfied: huggingface-hub<1.0.0,>=0.1.0 in /opt/conda/lib/python3.7/site-packages (from datasets) (0.13.3)\n",759      "Requirement already satisfied: aiohttp in /opt/conda/lib/python3.7/site-packages (from datasets) (3.8.3)\n",760      "Requirement already satisfied: numpy>=1.17 in /opt/conda/lib/python3.7/site-packages (from datasets) (1.21.6)\n",761      "Requirement already satisfied: filelock in /opt/conda/lib/python3.7/site-packages (from transformers) (3.9.0)\n",762      "Requirement already satisfied: pyyaml>=5.1 in /opt/conda/lib/python3.7/site-packages (from transformers) (6.0)\n",763      "Requirement already satisfied: tokenizers!=0.11.3,<0.14,>=0.11.1 in /opt/conda/lib/python3.7/site-packages (from transformers) (0.13.2)\n",764      "Requirement already satisfied: regex!=2019.12.17 in /opt/conda/lib/python3.7/site-packages (from transformers) (2021.11.10)\n",765      "Requirement already satisfied: charset-normalizer<3.0,>=2.0 in /opt/conda/lib/python3.7/site-packages (from aiohttp->datasets) (2.1.1)\n",766      "Requirement already satisfied: multidict<7.0,>=4.5 in /opt/conda/lib/python3.7/site-packages (from aiohttp->datasets) (6.0.4)\n",767      "Requirement already satisfied: yarl<2.0,>=1.0 in /opt/conda/lib/python3.7/site-packages (from aiohttp->datasets) (1.8.2)\n",768      "Requirement already satisfied: attrs>=17.3.0 in /opt/conda/lib/python3.7/site-packages (from aiohttp->datasets) (22.2.0)\n",769      "Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in /opt/conda/lib/python3.7/site-packages (from aiohttp->datasets) (4.0.2)\n",770      "Requirement already satisfied: asynctest==0.13.0 in /opt/conda/lib/python3.7/site-packages (from aiohttp->datasets) (0.13.0)\n",771      "Requirement already satisfied: aiosignal>=1.1.2 in /opt/conda/lib/python3.7/site-packages (from aiohttp->datasets) (1.3.1)\n",772      "Requirement already satisfied: frozenlist>=1.1.1 in /opt/conda/lib/python3.7/site-packages (from aiohttp->datasets) (1.3.3)\n",773      "Requirement already satisfied: typing-extensions>=3.7.4 in /opt/conda/lib/python3.7/site-packages (from aiohttp->datasets) (4.4.0)\n",774      "Requirement already satisfied: urllib3<1.27,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->datasets) (1.26.14)\n",775      "Requirement already satisfied: idna<4,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->datasets) (3.4)\n",776      "Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->datasets) (2022.12.7)\n",777      "Requirement already satisfied: zipp>=0.5 in /opt/conda/lib/python3.7/site-packages (from importlib-metadata->datasets) (3.11.0)\n",778      "Requirement already satisfied: python-dateutil>=2.7.3 in /opt/conda/lib/python3.7/site-packages (from pandas->datasets) (2.8.2)\n",779      "Requirement already satisfied: pytz>=2017.3 in /opt/conda/lib/python3.7/site-packages (from pandas->datasets) (2023.3)\n",780      "Requirement already satisfied: six>=1.5 in /opt/conda/lib/python3.7/site-packages (from python-dateutil>=2.7.3->pandas->datasets) (1.16.0)\n",781      "\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",782      "\u001b[0m"783     ]784    }785   ],786   "source": [787    "!pip install bitsandbytes\n",788    "!pip install datasets transformers"789   ]790  },791  {792   "cell_type": "code",793   "execution_count": 2,794   "id": "moral-tribute",795   "metadata": {796    "colab": {797     "base_uri": "https://localhost:8080/"798    },799    "execution": {800     "iopub.execute_input": "2023-04-13T07:38:15.685046Z",801     "iopub.status.busy": "2023-04-13T07:38:15.684565Z",802     "iopub.status.idle": "2023-04-13T07:38:26.677158Z",803     "shell.execute_reply": "2023-04-13T07:38:26.676012Z",804     "shell.execute_reply.started": "2023-04-13T07:38:15.685009Z"805    },806    "id": "x7B_tbh3dn_j",807    "outputId": "76ceff04-811c-4812-f1c4-f032dd894747"808   },809   "outputs": [810    {811     "name": "stdout",812     "output_type": "stream",813     "text": [814      "\n",815      "===================================BUG REPORT===================================\n",816      "Welcome to bitsandbytes. For bug reports, please submit your error trace to: https://github.com/TimDettmers/bitsandbytes/issues\n",817      "================================================================================\n",818      "CUDA SETUP: CUDA runtime path found: /usr/local/cuda/lib64/libcudart.so\n",819      "CUDA SETUP: Highest compute capability among GPUs detected: 6.1\n",820      "CUDA SETUP: Detected CUDA version 110\n",821      "CUDA SETUP: Loading binary /home/sapetrov/.local/lib/python3.8/site-packages/bitsandbytes/libbitsandbytes_cuda110_nocublaslt.so...\n"822     ]823    },824    {825     "name": "stderr",826     "output_type": "stream",827     "text": [828      "/home/sapetrov/.local/lib/python3.8/site-packages/bitsandbytes/cuda_setup/main.py:136: UserWarning: WARNING: The following directories listed in your path were found to be non-existent: {PosixPath('/usr/local/cuda/extras/CUPTI/lib64')}\n",829      "  warn(msg)\n",830      "/home/sapetrov/.local/lib/python3.8/site-packages/bitsandbytes/cuda_setup/main.py:136: UserWarning: WARNING: Compute capability < 7.5 detected! Only slow 8-bit matmul is supported for your GPU!\n",831      "  warn(msg)\n"832     ]833    }834   ],835   "source": [836    "# You can also adapt this script on your own causal language modeling task. Pointers for this are left as comments.\n",837    "\n",838    "import bitsandbytes as bnb\n",839    "import pandas as pd\n",840    "\n",841    "\n",842    "import argparse\n",843    "import logging\n",844    "import math\n",845    "import os\n",846    "import random\n",847    "from itertools import chain\n",848    "from pathlib import Path\n",849    "\n",850    "import datasets\n",851    "import torch\n",852    "from datasets import load_dataset\n",853    "from torch.utils.data import DataLoader, Dataset\n",854    "from tqdm.auto import tqdm\n",855    "\n",856    "import transformers\n",857    "from huggingface_hub import Repository\n",858    "from transformers import (\n",859    "    CONFIG_MAPPING,\n",860    "    MODEL_MAPPING,\n",861    "    AdamW,\n",862    "    AutoConfig,\n",863    "    AutoModelForCausalLM,\n",864    "    AutoTokenizer,\n",865    "    SchedulerType,\n",866    "    default_data_collator,\n",867    "    get_scheduler,\n",868    "    set_seed,\n",869    ")\n",870    "from transformers.file_utils import get_full_repo_name\n",871    "from transformers.utils.versions import require_version"872   ]873  },874  {875   "cell_type": "code",876   "execution_count": 3,877   "id": "oriental-assessment",878   "metadata": {879    "execution": {880     "iopub.execute_input": "2023-04-13T07:38:26.682977Z",881     "iopub.status.busy": "2023-04-13T07:38:26.680823Z",882     "iopub.status.idle": "2023-04-13T07:38:26.863443Z",883     "shell.execute_reply": "2023-04-13T07:38:26.862056Z",884     "shell.execute_reply.started": "2023-04-13T07:38:26.682937Z"885    },886    "id": "danish-blast"887   },888   "outputs": [],889   "source": [890    "logger = logging.getLogger(__name__)\n",891    "\n",892    "require_version(\"datasets>=1.16.1\", \"To fix: pip install -r examples/pytorch/language-modeling/requirements.txt\")\n",893    "\n",894    "MODEL_CONFIG_CLASSES = list(MODEL_MAPPING.keys())\n",895    "MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)\n",896    "\n",897    "\n",898    "def parse_args():\n",899    "    parser = argparse.ArgumentParser(description=\"Finetune a transformers model on a causal language modeling task\")\n",900    "    parser.add_argument(\n",901    "        \"--dataset_name\",\n",902    "        type=str,\n",903    "        default=None,\n",904    "        help=\"The name of the dataset to use (via the datasets library).\",\n",905    "    )\n",906    "    parser.add_argument(\n",907    "        \"--dataset_config_name\",\n",908    "        type=str,\n",909    "        default=None,\n",910    "        help=\"The configuration name of the dataset to use (via the datasets library).\",\n",911    "    )\n",912    "    parser.add_argument(\n",913    "        \"--text_column_name\",\n",914    "        type=str,\n",915    "        default=None,\n",916    "        help=\"The name of the column containing the text data.\",\n",917    "    )\n",918    "    parser.add_argument(\n",919    "        \"--dataset_streaming\",\n",920    "        action=\"store_true\",\n",921    "        help=\"If passed, will use dataset streaming (via the datasets library)\",\n",922    "    )\n",923    "    parser.add_argument(\n",924    "        \"--model_name_or_path\",\n",925    "        type=str,\n",926    "        help=\"Path to pretrained model or model identifier from huggingface.co/models.\",\n",927    "        required=False,\n",928    "    )\n",929    "    parser.add_argument(\n",930    "        \"--config_name\",\n",931    "        type=str,\n",932    "        default=None,\n",933    "        help=\"Pretrained config name or path if not the same as model_name\",\n",934    "    )\n",935    "    parser.add_argument(\n",936    "        \"--tokenizer_name\",\n",937    "        type=str,\n",938    "        default=None,\n",939    "        help=\"Pretrained tokenizer name or path if not the same as model_name\",\n",940    "    )\n",941    "    parser.add_argument(\n",942    "        \"--use_slow_tokenizer\",\n",943    "        action=\"store_true\",\n",944    "        help=\"If passed, will use a slow tokenizer (not backed by the 🤗 Tokenizers library).\",\n",945    "    )\n",946    "    parser.add_argument(\n",947    "        \"--per_device_train_batch_size\",\n",948    "        type=int,\n",949    "        default=1,\n",950    "        help=\"Batch size (per device) for the training dataloader.\",\n",951    "    )\n",952    "    parser.add_argument(\n",953    "        \"--learning_rate\",\n",954    "        type=float,\n",955    "        default=5e-5,\n",956    "        help=\"Initial learning rate (after the potential warmup period) to use.\",\n",957    "    )\n",958    "    parser.add_argument(\"--weight_decay\", type=float, default=0.0, help=\"Weight decay to use.\")\n",959    "    parser.add_argument(\"--num_train_epochs\", type=int, default=1, help=\"Total number of training epochs to perform.\")\n",960    "    parser.add_argument(\n",961    "        \"--max_train_steps\",\n",962    "        type=int,\n",963    "        default=None,\n",964    "        help=\"Total number of training steps to perform. If provided, overrides num_train_epochs.\",\n",965    "    )\n",966    "    parser.add_argument(\n",967    "        \"--gradient_accumulation_steps\",\n",968    "        type=int,\n",969    "        default=1,\n",970    "        help=\"Number of updates steps to accumulate before performing a backward/update pass.\",\n",971    "    )\n",972    "    parser.add_argument(\n",973    "        \"--lr_scheduler_type\",\n",974    "        type=SchedulerType,\n",975    "        default=\"linear\",\n",976    "        help=\"The scheduler type to use.\",\n",977    "        choices=[\"linear\", \"cosine\", \"cosine_with_restarts\", \"polynomial\", \"constant\", \"constant_with_warmup\"],\n",978    "    )\n",979    "    parser.add_argument(\n",980    "        \"--num_warmup_steps\", type=int, default=3000, help=\"Number of steps for the warmup in the lr scheduler.\"\n",981    "    )\n",982    "    parser.add_argument(\"--output_dir\", type=str, default=None, help=\"Where to store the final model.\")\n",983    "    parser.add_argument(\"--seed\", type=int, default=None, help=\"A seed for reproducible training.\")\n",984    "    parser.add_argument(\n",985    "        \"--model_type\",\n",986    "        type=str,\n",987    "        default=None,\n",988    "        help=\"Model type to use if training from scratch.\",\n",989    "        choices=MODEL_TYPES,\n",990    "    )\n",991    "    parser.add_argument(\n",992    "        \"--block_size\",\n",993    "        type=int,\n",994    "        default=None,\n",995    "        help=\"Optional input sequence length after tokenization. The training dataset will be truncated in block of this size for training. Default to the model max input length for single sentence inputs (take into account special tokens).\",\n",996    "    )\n",997    "    parser.add_argument(\n",998    "        \"--preprocessing_num_workers\",\n",999    "        type=int,\n",1000    "        default=None,\n",1001    "        help=\"The number of processes to use for the preprocessing.\",\n",1002    "    )\n",1003    "    parser.add_argument(\n",1004    "        \"--overwrite_cache\", type=bool, default=False, help=\"Overwrite the cached training and evaluation sets\"\n",1005    "    )\n",1006    "    parser.add_argument(\n",1007    "        \"--no_keep_linebreaks\", action=\"store_true\", help=\"Do not keep line breaks when using TXT files.\"\n",1008    "    )\n",1009    "    parser.add_argument(\"--push_to_hub\", action=\"store_true\", help=\"Whether or not to push the model to the Hub.\")\n",1010    "    parser.add_argument(\n",1011    "        \"--hub_model_id\", type=str, help=\"The name of the repository to keep in sync with the local `output_dir`.\"\n",1012    "    )\n",1013    "    parser.add_argument(\"--hub_token\", type=str, help=\"The token to use to push to the Model Hub.\")\n",1014    "    args = parser.parse_args(args=[])\n",1015    "\n",1016    "    if args.push_to_hub:\n",1017    "        assert args.output_dir is not None, \"Need an `output_dir` to create a repo when `--push_to_hub` is passed.\"\n",1018    "\n",1019    "    return args"1020   ]1021  },1022  {1023   "cell_type": "code",1024   "execution_count": 4,1025   "id": "operating-shape",1026   "metadata": {1027    "execution": {1028     "iopub.execute_input": "2023-04-13T07:38:26.865365Z",1029     "iopub.status.busy": "2023-04-13T07:38:26.865002Z",1030     "iopub.status.idle": "2023-04-13T07:38:26.877602Z",1031     "shell.execute_reply": "2023-04-13T07:38:26.876435Z",1032     "shell.execute_reply.started": "2023-04-13T07:38:26.865326Z"1033    },1034    "id": "colored-degree"1035   },1036   "outputs": [],1037   "source": [1038    "args = parse_args() # get default arguments\n",1039    "\n",1040    "# If passed along, set the training seed now.\n",1041    "if args.seed is not None:\n",1042    "    set_seed(args.seed)\n",1043    "\n",1044    "# args.dataset_name = 'c4'\n",1045    "# args.dataset_streaming = True\n",1046    "# args.dataset_config_name = \"en\"\n",1047    "args.text_column_name = \"prompt\"\n",1048    "args.model_name_or_path = 'gpt2'\n",1049    "args.block_size = 1024\n",1050    "args.max_train_steps = 1_000_000\n",1051    "args.log_loss_interval = 25\n"1052   ]1053  },1054  {1055   "cell_type": "code",1056   "execution_count": 5,1057   "id": "governing-token",1058   "metadata": {1059    "execution": {1060     "iopub.execute_input": "2023-04-13T07:38:26.879970Z",1061     "iopub.status.busy": "2023-04-13T07:38:26.879380Z",1062     "iopub.status.idle": "2023-04-13T07:38:26.886955Z",1063     "shell.execute_reply": "2023-04-13T07:38:26.885542Z",1064     "shell.execute_reply.started": "2023-04-13T07:38:26.879928Z"1065    },1066    "id": "NVd9O0h6eKPt"1067   },1068   "outputs": [],1069   "source": [1070    "device = torch.device('cuda:3' if torch.cuda.is_available() else 'cpu')"1071   ]1072  },1073  {1074   "cell_type": "code",1075   "execution_count": 6,1076   "id": "general-airline",1077   "metadata": {1078    "execution": {1079     "iopub.execute_input": "2023-04-13T07:38:26.889949Z",1080     "iopub.status.busy": "2023-04-13T07:38:26.888757Z",1081     "iopub.status.idle": "2023-04-13T07:38:28.977649Z",1082     "shell.execute_reply": "2023-04-13T07:38:28.976624Z",1083     "shell.execute_reply.started": "2023-04-13T07:38:26.889905Z"1084    },1085    "id": "geological-projector"1086   },1087   "outputs": [],1088   "source": [1089    "# CONFIG\n",1090    "\n",1091    "if args.config_name:\n",1092    "    config = AutoConfig.from_pretrained(args.config_name)\n",1093    "elif args.model_name_or_path:\n",1094    "    config = AutoConfig.from_pretrained(args.model_name_or_path)\n",1095    "else:\n",1096    "    config = CONFIG_MAPPING[args.model_type]()\n",1097    "    logger.warning(\"You are instantiating a new config instance from scratch.\")\n",1098    "\n",1099    "# TOKENIZER\n",1100    "if args.tokenizer_name:\n",1101    "    tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=not args.use_slow_tokenizer)\n",1102    "elif args.model_name_or_path:\n",1103    "    tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path, use_fast=not args.use_slow_tokenizer)\n",1104    "else:\n",1105    "    raise ValueError(\n",1106    "        \"You are instantiating a new tokenizer from scratch. This is not supported by this script.\"\n",1107    "        \"You can do it from another script, save it, and load it from here, using --tokenizer_name.\"\n",1108    "    )"1109   ]1110  },1111  {1112   "cell_type": "code",1113   "execution_count": 7,1114   "id": "voluntary-discrimination",1115   "metadata": {1116    "colab": {1117     "base_uri": "https://localhost:8080/"1118    },1119    "execution": {1120     "iopub.execute_input": "2023-04-13T07:38:28.979741Z",1121     "iopub.status.busy": "2023-04-13T07:38:28.979348Z",1122     "iopub.status.idle": "2023-04-13T07:38:33.942769Z",1123     "shell.execute_reply": "2023-04-13T07:38:33.941632Z",1124     "shell.execute_reply.started": "2023-04-13T07:38:28.979702Z"1125    },1126    "id": "bronze-missouri",1127    "outputId": "2db06a62-4049-44f3-92c2-a77a84cbf903"1128   },1129   "outputs": [1130    {1131     "name": "stdout",1132     "output_type": "stream",1133     "text": [1134      "CPU times: user 1 µs, sys: 2 µs, total: 3 µs\n",1135      "Wall time: 7.39 µs\n"1136     ]1137    }1138   ],1139   "source": [1140    "%time\n",1141    "# DATASET\n",1142    "\n",1143    "class Comments(Dataset):  \n",1144    "    def __init__(self, \n",1145    "                 filename, \n",1146    "                 truncate=False, \n",1147    "                 gpt2_type=args.model_name_or_path, \n",1148    "                 text_column_name=args.text_column_name,\n",1149    "                 max_length=1024, \n",1150    "                 tokenizer=None, \n",1151    "                 block_size=None):\n",1152    "        \n",1153    "        self.df_full = pd.read_csv(filename).iloc[:, 1:]\n",1154    "        self.texts = self.preprocess(self.df_full, block_size, text_column_name, tokenizer)\n",1155    "        self.count = self.df_full.shape[0]\n",1156    "        self.tokenizer = tokenizer\n",1157    "        \n",1158    "    def preprocess(self, data, block_size, text_column_name, tokenizer):\n",1159    "        texts = data[text_column_name].apply(lambda x: x[:block_size]+\" <EOS>\" if len(x) > block_size else x)\n",1160    "#         texts = texts.apply(tokenizer.encode)\n",1161    "        return texts\n",1162    "\n",1163    "    def __len__(self):\n",1164    "        return self.count\n",1165    "\n",1166    "    def __getitem__(self, item):\n",1167    "        output = torch.tensor(self.tokenizer.encode(self.texts[item]))\n",1168    "        return output \n",1169    "\n",1170    "\n",1171    "if args.block_size is None:\n",1172    "    block_size = tokenizer.model_max_length\n",1173    "    if block_size > 1024:\n",1174    "        logger.warning(\n",1175    "            f\"The tokenizer picked seems to have a very large `model_max_length` ({tokenizer.model_max_length}). \"\n",1176    "            \"Picking 1024 instead. You can change that default value by passing --block_size xxx.\"\n",1177    "        )\n",1178    "    block_size = 1024\n",1179    "else:\n",1180    "    if args.block_size > tokenizer.model_max_length:\n",1181    "        logger.warning(\n",1182    "            f\"The block_size passed ({args.block_size}) is larger than the maximum length for the model\"\n",1183    "            f\"({tokenizer.model_max_length}). Using block_size={tokenizer.model_max_length}.\"\n",1184    "        )\n",1185    "    block_size = min(args.block_size, tokenizer.model_max_length)\n",1186    "    \n",1187    "train_dataset = Comments(\"./prompts_train_02.csv\", \n",1188    "                           text_column_name=args.text_column_name, \n",1189    "                           tokenizer=tokenizer,\n",1190    "                           block_size=block_size)"1191   ]1192  },1193  {1194   "cell_type": "code",1195   "execution_count": 8,1196   "id": "macro-burke",1197   "metadata": {1198    "colab": {1199     "base_uri": "https://localhost:8080/"1200    },

Showing the first 1,200 of 2198 lines. Download the file for the rest.