{ "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.

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.

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.

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\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", "
\n", " \n", " \n", " [ 3/1563 00:17 < 7:33:36, 0.06 it/s, Epoch 0.00/1]\n", "
\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
EpochTraining LossValidation Loss

" ], "text/plain": [ "" ] }, "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 }