{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "eUS7fBrdXj9A" }, "source": [ "Ensures that Transformers and pytorch_lightning libraries are installed in the runtime." ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "id": "LF6cf_ijDNhp" }, "outputs": [], "source": [ "%%capture\n", "%pip install transformers\n", "%pip install pytorch_lightning\n" ] }, { "cell_type": "markdown", "metadata": { "id": "pf4Ch2xaXszi" }, "source": [ "Imports everything needed for creating the model" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "id": "pmd3-0J4_rnp" }, "outputs": [], "source": [ "import pandas as pd\n", "import numpy as np\n", "from torch.utils.data import Dataset\n", "import torch\n", "from transformers import AutoTokenizer\n", "import pytorch_lightning as pl\n", "from torch.utils.data import DataLoader\n", "from transformers import AutoModel, AdamW, get_cosine_schedule_with_warmup\n", "import torch.nn as nn\n", "import math\n", "from torchmetrics.functional.classification import auroc\n", "import torch.nn.functional as F\n", "from transformers import BertForMaskedLM, TFBertForMaskedLM" ] }, { "cell_type": "markdown", "metadata": { "id": "EyhmDzknX2k8" }, "source": [ "Defines class toxicity_dataset, which extends Dataset. __init__ takes a path to the csv file, a tokenizer, a list of attributes, a maximum length for the token which defaults to 128, and a size for sampling the data which defaults to 5000.\n", "\n", "The toxicity_dataset class prepares the data by sampling the csv file in _prepare_data, returns the length of the dataset with __len__, and can acess an item with an index and return its input ids, its attention mask, and its labels.\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "id": "vS6DHv5k_xZ5" }, "outputs": [], "source": [ "class toxicity_dataset(Dataset):\n", " def __init__(self,data_path,tokenizer,attributes,max_token_len= 128,sample = 5000):\n", " self.data_path=data_path\n", " self.tokenizer=tokenizer\n", " self.attributes=attributes\n", " self.max_token_len=max_token_len\n", " self.sample=sample\n", " self._prepare_data()\n", " def _prepare_data(self):\n", " data=pd.read_csv(self.data_path)\n", " if self.sample is not None:\n", " self.data=data.sample(self.sample,random_state=7)\n", " else:\n", " self.data=data\n", " def __len__(self):\n", " return(len(self.data))\n", " def __getitem__(self,index):\n", " item = self.data.iloc[index]\n", " comment = str(item.comment_text)\n", " attributes = torch.FloatTensor(item[self.attributes])\n", " tokens = self.tokenizer.encode_plus(comment,add_special_tokens=True,return_tensors=\"pt\",truncation=True,max_length=self.max_token_len,padding=\"max_length\",return_attention_mask=True)\n", " return{'input_ids':tokens.input_ids.flatten(),\"attention_mask\":tokens.attention_mask.flatten(),\"labels\":attributes}\n" ] }, { "cell_type": "markdown", "metadata": { "id": "w-Kmud4YZXH2" }, "source": [ "Defines Toxicity_Data_Module, which extends pytorch_lightnign.LightningDataModule.__init__ takes a path to the training data set and a testing set, a list of attributes, batch size, tax token length, and the name of the model. It has methods to create and return a dataloader for training, validation, and prediciton." ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "id": "Txrjrl1d_6UN" }, "outputs": [], "source": [ "class Toxcity_Data_Module(pl.LightningDataModule):\n", " def __init__(self,train_path,test_path,attributes,batch_size = 16, max_token_len = 128, model_name=\"roberta-base\"):\n", " super().__init__()\n", " self.train_path=train_path\n", " self.test_path=test_path\n", " self.attributes=attributes\n", " self.batch_size=batch_size\n", " self.max_token_len=max_token_len\n", " self.model_name=model_name\n", " self.tokenizer = AutoTokenizer.from_pretrained(model_name)\n", " def setup(self, stage = None):\n", " if stage in (None, \"fit\"):\n", " self.train_dataset=toxicity_dataset(self.train_path,self.tokenizer,self.attributes)\n", " self.test_dataset=toxicity_dataset(self.test_path,self.tokenizer,self.attributes, sample=None)\n", " if stage == \"predict\":\n", " self.val_dataset=toxicity_dataset(self.test_path,self.tokenizer,self.attributes)\n", " def train_dataloader(self):\n", " return DataLoader(self.train_dataset,batch_size=self.batch_size,shuffle=True, num_workers=12)\n", " def val_dataloader(self):\n", " return DataLoader(self.train_dataset,batch_size=self.batch_size,shuffle=False, num_workers=12)\n", " def predict_dataloader(self):\n", " return DataLoader(self.test_dataset,batch_size=self.batch_size,shuffle=False, num_workers=12)\n", " " ] }, { "cell_type": "markdown", "source": [ "Defines Toxic_Comment_Classifier, which is the actual model we are fine tuning, and extends pl.LightningModule. __init__ takes a dictionary storing model name, number of labels, batch size, learning rate, warmup, the size of the training set, weighted decay, and number of epochs. It's methods are never called explicitly in the code, and the class is instead used by a pytorch_lightning Trainer object." ], "metadata": { "id": "2XqQMdp1YahZ" } }, { "cell_type": "code", "execution_count": 6, "metadata": { "id": "7AhJvpKyADHJ" }, "outputs": [], "source": [ "class Toxic_Comment_Classifier(pl.LightningModule):\n", " def __init__(self, config: dict):\n", " super().__init__()\n", " self.config = config\n", " self.pretrained_model = AutoModel.from_pretrained(config['model_name'], return_dict = True)\n", " self.hidden = torch.nn.Linear(self.pretrained_model.config.hidden_size, self.pretrained_model.config.hidden_size)\n", " self.classifier = torch.nn.Linear(self.pretrained_model.config.hidden_size, self.config['n_labels'])\n", " torch.nn.init.xavier_uniform_(self.classifier.weight)\n", " self.loss_func = nn.BCEWithLogitsLoss(reduction='mean')\n", " self.dropout = nn.Dropout()\n", " \n", " def forward(self, input_ids, attention_mask=None, labels=None):\n", " # roberta layer\n", " output = self.pretrained_model(input_ids=input_ids, attention_mask=attention_mask)\n", " pooled_output = torch.mean(output.last_hidden_state, 1)\n", " # final logits\n", " pooled_output = self.dropout(pooled_output)\n", " pooled_output = self.hidden(pooled_output)\n", " pooled_output = F.relu(pooled_output)\n", " pooled_output = self.dropout(pooled_output)\n", " logits = self.classifier(pooled_output)\n", " # calculate loss\n", " loss = 0\n", " if labels is not None:\n", " loss = self.loss_func(logits.view(-1, self.config['n_labels']), labels.view(-1, self.config['n_labels']))\n", " return loss, logits\n", "\n", " def training_step(self, batch, batch_index):\n", " loss, outputs = self(**batch)\n", " self.log(\"train loss \", loss, prog_bar = True, logger=True)\n", " return {\"loss\":loss, \"predictions\":outputs, \"labels\": batch[\"labels\"]}\n", "\n", " def validation_step(self, batch, batch_index):\n", " loss, outputs = self(**batch)\n", " self.log(\"validation loss \", loss, prog_bar = True, logger=True)\n", " return {\"val_loss\": loss, \"predictions\":outputs, \"labels\": batch[\"labels\"]}\n", "\n", " def predict_step(self, batch, batch_index):\n", " loss, outputs = self(**batch)\n", " return outputs\n", "\n", " def configure_optimizers(self):\n", " optimizer = AdamW(self.parameters(), lr=self.config['lr'], weight_decay=self.config['w_decay'])\n", " total_steps = self.config['train_size']/self.config['bs']\n", " warmup_steps = math.floor(total_steps * self.config['warmup'])\n", " warmup_steps = math.floor(total_steps * self.config['warmup'])\n", " scheduler = get_cosine_schedule_with_warmup(optimizer, warmup_steps, total_steps)\n", " return [optimizer],[scheduler]" ] }, { "cell_type": "markdown", "source": [ "The variable, attributes, stores the list of labels used to classify the comments. toxicity_data_module is created and setup for later use." ], "metadata": { "id": "CRZVlU89boV5" } }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "VQwXmUnn_-co" }, "outputs": [], "source": [ "attributes=[\"toxic\",\"severe_toxic\",\"obscene\",\"threat\",\"insult\",\"identity_hate\"]\n", "\n", "toxicity_data_module=Toxcity_Data_Module(\"/content/sample_data/train.csv\",\"/content/sample_data/train.csv\",attributes)\n", "toxicity_data_module.setup()" ] }, { "cell_type": "markdown", "source": [ "Here, we define the config dictionary. the model we are fine tuning is the distilroberta-base model. We use attributes to get the number of labels. the batch size is 128, the learning rate is 0.0000015, and we're using 80 epochs for training." ], "metadata": { "id": "OTumKddHb6wB" } }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Q77QTZpUAFAS" }, "outputs": [], "source": [ "config = {\n", " 'model_name':\"distilroberta-base\",\n", " 'n_labels':len(attributes),\n", " 'bs':128,\n", " 'lr':1.5e-6,\n", " 'warmup':0.2,\n", " \"train_size\":len(toxicity_data_module.train_dataloader()),\n", " 'w_decay':0.001,\n", " 'n_epochs':80\n", "}\n" ] }, { "cell_type": "markdown", "source": [ "We recreated toxicity_data_module using the batch size from the config file, and set it up again. The variable trainer is created as a pytorch_lightning.Trainer object, taking the number of epochs and a number of sanity validation steps. The trainer object then fits the model using the model we created and the data module. torch.save() is called to save the model into a file called model.pt, which can be loaded for later use. This is how the model was loaded into the streamlit app without having to retrain it by scratch." ], "metadata": { "id": "raqYuS_Vepj1" } }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Mhk8fhgFAJNJ" }, "outputs": [], "source": [ "toxicity_data_module=Toxcity_Data_Module(\"/content/sample_data/train.csv\",\"/content/sample_data/test.csv\",attributes,batch_size=config['bs'])\n", "toxicity_data_module.setup()\n", "model = Toxic_Comment_Classifier(config)\n", "\n", "trainer = pl.Trainer(max_epochs=config['n_epochs'],num_sanity_val_steps=50)\n", "trainer.fit(model,toxicity_data_module)\n", "torch.save(model, \"/content/sample_data/model.pt\")" ] }, { "cell_type": "markdown", "source": [ "After all 80 epochs, the training and validatin loss are all very low, under 0.05. This shows that the model is pretty effective at determining the labels, and is not overfitting." ], "metadata": { "id": "pt-FyfFVqRdS" } }, { "cell_type": "markdown", "source": [ "Here we load the model file back into the model variable." ], "metadata": { "id": "3h4j9aqTgL1Q" } }, { "cell_type": "code", "execution_count": 11, "metadata": { "id": "dG_Z30QlQfSP" }, "outputs": [], "source": [ "model = torch.load(\"/content/sample_data/model.pt\")\n" ] }, { "cell_type": "markdown", "source": [ "The function predict_raw_comments() takes the model, and the data module, and gets predictions from the trainer in the form of logits." ], "metadata": { "id": "WxJWKhnViQjE" } }, { "cell_type": "code", "execution_count": 12, "metadata": { "id": "TiXWsKFZQmQs" }, "outputs": [], "source": [ "def predict_raw_comments(model, dm):\n", " predictions = trainer.predict(model,dm)\n", " logits = np.stack([torch.sigmoid(torch.Tensor(p)) for batch in predictions for p in batch])\n", " return logits" ] }, { "cell_type": "markdown", "source": [ "Below, we use the predict_raw_comments() function to get the predicted logits." ], "metadata": { "id": "ihy78y__iyQL" } }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "8ZkNo8u4Qmd7" }, "outputs": [], "source": [ "logits = predict_raw_comments(model,toxicity_data_module)\n" ] }, { "cell_type": "markdown", "source": [ "below, we convert the numpy array of logits retrieved into torch logits using torch.from_numpy(logits). We then use a softmax function to find the softmax probabilities for each label, and convert it back into a numpy array. " ], "metadata": { "id": "vk7FQY7ajCUJ" } }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Znq6JcNS8P7Z" }, "outputs": [], "source": [ "torch_logits = torch.from_numpy(logits)\n", "probabilities = F.softmax(torch_logits, dim = -1).numpy()\n" ] }, { "cell_type": "markdown", "source": [ "We can then load our testing data into a dataframe, and use a nested loop to loop through both the input dataframe and the probabilities dataframe to find the label with the maximum probability. We can store the comment, the most likely labe, and the probability of that label into a new dataframe called results_df." ], "metadata": { "id": "S7Ixxgo5jj00" } }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "KabNY9yrxsGn" }, "outputs": [], "source": [ "inputs=pd.read_csv(\"/content/sample_data/test.csv\")\n", "data=[]\n", "for i in range(20):\n", " max_prob = 0\n", " max_cat = 6\n", " \n", " prob=0\n", " for j in range(6):\n", " prob=probabilities[i][j]\n", " if(prob >= max_prob): \n", " max_prob = prob \n", " max_cat = j\n", " data.append([inputs[\"comment_text\"][i],attributes[max_cat],max_prob])\n", "results_df=pd.DataFrame(data,columns=[\"Comment Text\",\"Most Likely Classification\",\"Classification Probability\"])" ] } ], "metadata": { "accelerator": "GPU", "colab": { "machine_shape": "hm", "provenance": [] }, "gpuClass": "standard", "kernelspec": { "display_name": "Python 3", "name": "python3" }, "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 0 }