File size: 10,431 Bytes
2efa5aa |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "90683dd2",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
" from .autonotebook import tqdm as notebook_tqdm\n"
]
}
],
"source": [
"import torch\n",
"\n",
"from datasets import load_dataset\n",
"from transformers import pipeline, AutoTokenizer\n",
"\n",
"from trl import PPOTrainer, PPOConfig, AutoModelForCausalLMWithValueHead\n",
"from trl.core import LengthSampler\n",
"\n",
"import os\n",
"os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\""
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "24fe6f33",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"DatasetDict({\n",
" train: Dataset({\n",
" features: ['text', 'label'],\n",
" num_rows: 25000\n",
" })\n",
" test: Dataset({\n",
" features: ['text', 'label'],\n",
" num_rows: 25000\n",
" })\n",
" unsupervised: Dataset({\n",
" features: ['text', 'label'],\n",
" num_rows: 50000\n",
" })\n",
"})"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"ds = load_dataset(\"imdb\")\n",
"ds"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "e68286f0",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'I rented I AM CURIOUS-YELLOW from my video store because of all the controversy that surrounded it when it was first released in 1967. I also heard that at first it was seized by U.S. customs if it ever tried to enter this country, therefore being a fan of films considered \"controversial\" I really had to see this for myself.<br /><br />The plot is centered around a young Swedish drama student named Lena who wants to learn everything she can about life. In particular she wants to focus her attentions to making some sort of documentary on what the average Swede thought about certain political issues such as the Vietnam War and race issues in the United States. In between asking politicians and ordinary denizens of Stockholm about their opinions on politics, she has sex with her drama teacher, classmates, and married men.<br /><br />What kills me about I AM CURIOUS-YELLOW is that 40 years ago, this was considered pornographic. Really, the sex and nudity scenes are few and far between, even then it\\'s not shot like some cheaply made porno. While my countrymen mind find it shocking, in reality sex and nudity are a major staple in Swedish cinema. Even Ingmar Bergman, arguably their answer to good old boy John Ford, had sex scenes in his films.<br /><br />I do commend the filmmakers for the fact that any sex shown in the film is shown for artistic purposes rather than just to shock people and make money to be shown in pornographic theaters in America. I AM CURIOUS-YELLOW is a good film for anyone wanting to study the meat and potatoes (no pun intended) of Swedish cinema. But really, this film doesn\\'t have much of a plot.'"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"ds['train'][0]['text']"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "2a8de66d",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Some weights of DistilBertForSequenceClassification were not initialized from the model checkpoint at distilbert-base-uncased and are newly initialized: ['classifier.bias', 'classifier.weight', 'pre_classifier.bias', 'pre_classifier.weight']\n",
"You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n"
]
}
],
"source": [
"from transformers import AutoModelForSequenceClassification, AutoTokenizer\n",
"\n",
"model_name = \"distilbert-base-uncased\"\n",
"model = AutoModelForSequenceClassification.from_pretrained(model_name)\n",
"tokenizer = AutoTokenizer.from_pretrained(model_name)"
]
},
{
"cell_type": "code",
"execution_count": 30,
"id": "33621a7b",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Map: 100%|ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ| 25000/25000 [00:24<00:00, 1014.20 examples/s]\n"
]
}
],
"source": [
"def tokenize(examples):\n",
" outputs = tokenizer(examples['text'], truncation=True)\n",
" return outputs\n",
"\n",
"tokenized_ds = ds.map(tokenize, batched=True)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "7c25e889",
"metadata": {},
"outputs": [],
"source": [
"from transformers import TrainingArguments, Trainer, DataCollatorWithPadding\n",
"\n",
"import numpy as np\n",
"\n",
"def compute_metrics(eval_preds):\n",
" metric = load_metric(\"accuracy\")\n",
" logits, labels = eval_preds\n",
" predictions = np.argmax(logits, axis=-1)\n",
" return metric.compute(predictions=predictions, references=labels)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "4423925c",
"metadata": {},
"outputs": [],
"source": [
"training_args = TrainingArguments(num_train_epochs=1,\n",
" output_dir=\"distilbert-imdb\",\n",
" push_to_hub=False,\n",
" per_device_train_batch_size=16,\n",
" per_device_eval_batch_size=16,\n",
" evaluation_strategy=\"epoch\")"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "f8b93ddf",
"metadata": {},
"outputs": [],
"source": [
"data_collator = DataCollatorWithPadding(tokenizer)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "3e7756b8",
"metadata": {},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'tokenized_ds' is not defined",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
"Input \u001b[0;32mIn [8]\u001b[0m, in \u001b[0;36m<cell line: 1>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m trainer \u001b[38;5;241m=\u001b[39m Trainer(model\u001b[38;5;241m=\u001b[39mmodel, tokenizer\u001b[38;5;241m=\u001b[39mtokenizer,\n\u001b[1;32m 2\u001b[0m data_collator\u001b[38;5;241m=\u001b[39mdata_collator,\n\u001b[1;32m 3\u001b[0m args\u001b[38;5;241m=\u001b[39mtraining_args,\n\u001b[0;32m----> 4\u001b[0m train_dataset\u001b[38;5;241m=\u001b[39m\u001b[43mtokenized_ds\u001b[49m[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mtrain\u001b[39m\u001b[38;5;124m\"\u001b[39m],\n\u001b[1;32m 5\u001b[0m eval_dataset\u001b[38;5;241m=\u001b[39mtokenized_ds[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mtest\u001b[39m\u001b[38;5;124m\"\u001b[39m], \n\u001b[1;32m 6\u001b[0m compute_metrics\u001b[38;5;241m=\u001b[39mcompute_metrics)\n",
"\u001b[0;31mNameError\u001b[0m: name 'tokenized_ds' is not defined"
]
}
],
"source": [
"trainer = Trainer(model=model, tokenizer=tokenizer,\n",
" data_collator=data_collator,\n",
" args=training_args,\n",
" train_dataset=tokenized_ds[\"train\"],\n",
" eval_dataset=tokenized_ds[\"test\"], \n",
" compute_metrics=compute_metrics)"
]
},
{
"cell_type": "code",
"execution_count": 35,
"id": "c4829ba0",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"\n",
" <div>\n",
" \n",
" <progress value='3' max='1563' style='width:300px; height:20px; vertical-align: middle;'></progress>\n",
" [ 3/1563 00:17 < 7:33:36, 0.06 it/s, Epoch 0.00/1]\n",
" </div>\n",
" <table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: left;\">\n",
" <th>Epoch</th>\n",
" <th>Training Loss</th>\n",
" <th>Validation Loss</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" </tbody>\n",
"</table><p>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"\n",
"KeyboardInterrupt\n",
"\n"
]
}
],
"source": [
"trainer.train()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2f919628",
"metadata": {},
"outputs": [],
"source": [
"trainer.push_to_hub()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6448feed",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"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.9.13"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|