{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# New Notes:\n\n- Forked https://www.kaggle.com/yeayates21/xlm-roberta-augmentation-ssl-0-9417-pub-lb\n- Added https://www.kaggle.com/vecxoz/jplu-tf-xlm-roberta-large so we can run without internet\n- Revised to score Jigsaw Severity test set\n\n# Old Notes:\n\n**Kaggle Sources**\n - https://www.kaggle.com/xhlulu/jigsaw-tpu-xlm-roberta\n     - forked this notebook\n - https://www.kaggle.com/shonenkov/tpu-training-super-fast-xlmroberta\n     - grabed external data from this notebook, i.e. https://www.kaggle.com/shonenkov/open-subtitles-toxic-pseudo-labeling\n     \n**External Sources and More Additions**\n - Used [eda_nlp](https://github.com/jasonwei20/eda_nlp) to create an augmented version of the unintended bias dataset, then downsampled this data to have balanced dataset.  More information can be found here (minus the downsampling):  https://www.kaggle.com/yeayates21/jigsaw-bias-toxicity-eda-nlp-aug16-alpha005\n - pickled encoded data for faster runtime\n - some light manual hyperparameter tuning\n - scored the test set with each \"model.fit\" run as \"checkpoint predictions\" and blended the checkpoint predictions (I didn't checkpoint the models, but that could be easily added).\n\n-----------------------------------------------------------------------\n\n#### Acknowledgements\n\n - [@alexshonenkov](https://www.kaggle.com/shonenkov)\n - [@xhlulu](https://www.kaggle.com/xhlulu)\n","metadata":{}},{"cell_type":"code","source":"import os\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom tensorflow.keras.layers import Dense, Input\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.callbacks import ModelCheckpoint\nfrom kaggle_datasets import KaggleDatasets\nimport transformers\nfrom transformers import TFAutoModel, AutoTokenizer\nfrom tqdm.notebook import tqdm\nfrom tokenizers import Tokenizer, models, pre_tokenizers, decoders, processors\nimport pickle\nimport matplotlib.pyplot as plt\n%matplotlib inline","metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","execution":{"iopub.status.busy":"2021-11-11T23:04:47.655999Z","iopub.execute_input":"2021-11-11T23:04:47.65628Z","iopub.status.idle":"2021-11-11T23:04:47.67449Z","shell.execute_reply.started":"2021-11-11T23:04:47.656255Z","shell.execute_reply":"2021-11-11T23:04:47.673784Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Helper Functions","metadata":{}},{"cell_type":"code","source":"def build_model(transformer, max_len=512):\n    \"\"\"\n    https://www.kaggle.com/xhlulu/jigsaw-tpu-distilbert-with-huggingface-and-keras\n    \"\"\"\n    input_word_ids = Input(shape=(max_len,), dtype=tf.int32, name=\"input_word_ids\")\n    sequence_output = transformer(input_word_ids)[0]\n    cls_token = sequence_output[:, 0, :]\n    out = Dense(1, activation='sigmoid')(cls_token)\n    \n    model = Model(inputs=input_word_ids, outputs=out)\n    model.compile(Adam(lr=0.000009), loss='binary_crossentropy', metrics=['accuracy'])\n    \n    return model","metadata":{"execution":{"iopub.status.busy":"2021-11-11T22:07:23.880387Z","iopub.execute_input":"2021-11-11T22:07:23.88065Z","iopub.status.idle":"2021-11-11T22:07:23.891495Z","shell.execute_reply.started":"2021-11-11T22:07:23.880594Z","shell.execute_reply":"2021-11-11T22:07:23.890585Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Configs","metadata":{}},{"cell_type":"code","source":"# Detect hardware, return appropriate distribution strategy\ntry:\n    # TPU detection. No parameters necessary if TPU_NAME environment variable is\n    # set: this is always the case on Kaggle.\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    # Default distribution strategy in Tensorflow. Works on CPU and single GPU.\n    strategy = tf.distribute.get_strategy()\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","metadata":{"execution":{"iopub.status.busy":"2021-11-11T22:07:23.893506Z","iopub.execute_input":"2021-11-11T22:07:23.894595Z","iopub.status.idle":"2021-11-11T22:07:32.12222Z","shell.execute_reply.started":"2021-11-11T22:07:23.894553Z","shell.execute_reply":"2021-11-11T22:07:32.12137Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"AUTO = tf.data.experimental.AUTOTUNE\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\nMAX_LEN = 192\nMODEL = '/kaggle/input/jplu-tf-xlm-roberta-large'","metadata":{"execution":{"iopub.status.busy":"2021-11-11T22:07:32.123456Z","iopub.execute_input":"2021-11-11T22:07:32.124059Z","iopub.status.idle":"2021-11-11T22:07:32.128881Z","shell.execute_reply.started":"2021-11-11T22:07:32.124011Z","shell.execute_reply":"2021-11-11T22:07:32.128047Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Tokenizer","metadata":{}},{"cell_type":"code","source":"# First load the real tokenizer\ntokenizer = AutoTokenizer.from_pretrained(MODEL)","metadata":{"execution":{"iopub.status.busy":"2021-11-11T22:07:32.131837Z","iopub.execute_input":"2021-11-11T22:07:32.132097Z","iopub.status.idle":"2021-11-11T22:07:34.509307Z","shell.execute_reply.started":"2021-11-11T22:07:32.132068Z","shell.execute_reply":"2021-11-11T22:07:34.508537Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load Data","metadata":{}},{"cell_type":"code","source":"!ls /kaggle/input/jigsawtpuxlmrobertacopypickledata","metadata":{"execution":{"iopub.status.busy":"2021-11-11T22:07:34.510414Z","iopub.execute_input":"2021-11-11T22:07:34.510637Z","iopub.status.idle":"2021-11-11T22:07:35.313232Z","shell.execute_reply.started":"2021-11-11T22:07:34.510613Z","shell.execute_reply":"2021-11-11T22:07:35.312203Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def regular_encode(texts, tokenizer, maxlen=512):\n    enc_di = tokenizer.batch_encode_plus(\n        texts, # text to tokenize\n        return_token_type_ids=False, # https://huggingface.co/transformers/glossary.html#token-type-ids\n        pad_to_max_length=True, # add padding\n        max_length=maxlen # set max length\n    )\n    \n    return np.array(enc_di['input_ids'])","metadata":{"execution":{"iopub.status.busy":"2021-11-11T22:07:35.314687Z","iopub.execute_input":"2021-11-11T22:07:35.314931Z","iopub.status.idle":"2021-11-11T22:07:35.320783Z","shell.execute_reply.started":"2021-11-11T22:07:35.314902Z","shell.execute_reply":"2021-11-11T22:07:35.319975Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\nfilename = \"/kaggle/input/jigsawtpuxlmrobertacopypickledata/jigsaw_multilingual_x_train.pkl\"\nx_train = pickle.load(open(filename, 'rb')) # load data \nfilename = \"/kaggle/input/jigsawtpuxlmrobertacopypickledata/jigsaw_multilingual_x_trainOA.pkl\"\nx_trainOA = pickle.load(open(filename, 'rb')) # load data \nfilename = \"/kaggle/input/jigsawtpuxlmrobertacopypickledata/jigsaw_multilingual_x_trainA.pkl\"\nx_trainA = pickle.load(open(filename, 'rb')) # load data \nfilename = \"/kaggle/input/jigsawtpuxlmrobertacopypickledata/jigsaw_multilingual_x_valid.pkl\"\nx_valid = pickle.load(open(filename, 'rb')) # load data \nfilename = \"../input/jigsaw-toxic-severity-rating/comments_to_score.csv\"\nx_test_df = pd.read_csv(filename) # load data \nx_test = regular_encode(x_test_df.text.values.tolist(), tokenizer, maxlen=MAX_LEN)\n\nfilename = \"/kaggle/input/jigsawtpuxlmrobertacopypickledata/jigsaw_multilingual_y_train.pkl\"\ny_train = pickle.load(open(filename, 'rb')) # load data \nfilename = \"/kaggle/input/jigsawtpuxlmrobertacopypickledata/jigsaw_multilingual_y_trainOA.pkl\"\ny_trainOA = pickle.load(open(filename, 'rb')) # load data \nfilename = \"/kaggle/input/jigsawtpuxlmrobertacopypickledata/jigsaw_multilingual_y_trainA.pkl\"\ny_trainA = pickle.load(open(filename, 'rb')) # load data \nfilename = \"/kaggle/input/jigsawtpuxlmrobertacopypickledata/jigsaw_multilingual_y_valid.pkl\"\ny_valid = pickle.load(open(filename, 'rb')) # load data ","metadata":{"execution":{"iopub.status.busy":"2021-11-11T22:07:35.322048Z","iopub.execute_input":"2021-11-11T22:07:35.322436Z","iopub.status.idle":"2021-11-11T22:07:39.248459Z","shell.execute_reply.started":"2021-11-11T22:07:35.322396Z","shell.execute_reply":"2021-11-11T22:07:39.247582Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# TF Datasets","metadata":{}},{"cell_type":"code","source":"train_dataset = (\n    tf.data.Dataset\n    .from_tensor_slices((x_train, y_train))\n    .repeat()\n    .shuffle(2048)\n    .batch(BATCH_SIZE)\n    .prefetch(AUTO)\n)\n\ntrain_datasetOA = (\n    tf.data.Dataset\n    .from_tensor_slices((x_trainOA, y_trainOA))\n    .repeat()\n    .shuffle(x_trainOA.shape[0])\n    .batch(BATCH_SIZE)\n    .prefetch(AUTO)\n)\n\ntrain_datasetA = (\n    tf.data.Dataset\n    .from_tensor_slices((x_trainA, y_trainA))\n    .repeat()\n    .shuffle(x_trainOA.shape[0])\n    .batch(BATCH_SIZE)\n    .prefetch(AUTO)\n)\n\nvalid_dataset = (\n    tf.data.Dataset\n    .from_tensor_slices((x_valid, y_valid))\n    .batch(BATCH_SIZE)\n    .cache()\n    .prefetch(AUTO)\n)\n\ntest_dataset = (\n    tf.data.Dataset\n    .from_tensor_slices(x_test)\n    .batch(BATCH_SIZE)\n)","metadata":{"execution":{"iopub.status.busy":"2021-11-11T22:07:39.250153Z","iopub.execute_input":"2021-11-11T22:07:39.250562Z","iopub.status.idle":"2021-11-11T22:07:44.031198Z","shell.execute_reply.started":"2021-11-11T22:07:39.25052Z","shell.execute_reply":"2021-11-11T22:07:44.030478Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load Model","metadata":{}},{"cell_type":"code","source":"%%time\nwith strategy.scope():\n    transformer_layer = TFAutoModel.from_pretrained(MODEL)\n    model = build_model(transformer_layer, max_len=MAX_LEN)\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2021-11-11T22:07:44.032355Z","iopub.execute_input":"2021-11-11T22:07:44.032705Z","iopub.status.idle":"2021-11-11T22:08:54.035998Z","shell.execute_reply.started":"2021-11-11T22:07:44.032679Z","shell.execute_reply":"2021-11-11T22:08:54.035017Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Train","metadata":{}},{"cell_type":"markdown","source":"#### Train on English training data","metadata":{}},{"cell_type":"code","source":"n_steps = x_train.shape[0] // BATCH_SIZE\n\nmodel.fit(\n    train_dataset,\n    steps_per_epoch=n_steps,\n    validation_data=valid_dataset,\n    epochs=1\n)","metadata":{"execution":{"iopub.status.busy":"2021-11-11T22:08:54.037275Z","iopub.execute_input":"2021-11-11T22:08:54.03752Z","iopub.status.idle":"2021-11-11T22:31:19.400114Z","shell.execute_reply.started":"2021-11-11T22:08:54.037494Z","shell.execute_reply":"2021-11-11T22:31:19.399329Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"checkpointPredictions1 = model.predict(test_dataset, verbose=1)\nprint(checkpointPredictions1[:10])","metadata":{"execution":{"iopub.status.busy":"2021-11-11T22:31:19.402589Z","iopub.execute_input":"2021-11-11T22:31:19.40301Z","iopub.status.idle":"2021-11-11T22:31:52.396747Z","shell.execute_reply.started":"2021-11-11T22:31:19.402948Z","shell.execute_reply":"2021-11-11T22:31:52.395842Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Train on augmented english data","metadata":{}},{"cell_type":"code","source":"n_steps = x_trainA.shape[0] // BATCH_SIZE\n\nmodel.fit(\n    train_datasetA,\n    steps_per_epoch=n_steps,\n    validation_data=valid_dataset,\n    epochs=1\n)","metadata":{"execution":{"iopub.status.busy":"2021-11-11T22:31:52.398101Z","iopub.execute_input":"2021-11-11T22:31:52.398567Z","iopub.status.idle":"2021-11-11T22:40:57.372453Z","shell.execute_reply.started":"2021-11-11T22:31:52.398531Z","shell.execute_reply":"2021-11-11T22:40:57.371634Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"checkpointPredictions2 = model.predict(test_dataset, verbose=1)\nprint(checkpointPredictions2[:10])","metadata":{"execution":{"iopub.status.busy":"2021-11-11T22:40:57.3765Z","iopub.execute_input":"2021-11-11T22:40:57.376745Z","iopub.status.idle":"2021-11-11T22:41:02.74897Z","shell.execute_reply.started":"2021-11-11T22:40:57.376717Z","shell.execute_reply":"2021-11-11T22:41:02.748321Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Train on multilingual validation training data","metadata":{}},{"cell_type":"code","source":"n_steps = x_valid.shape[0] // BATCH_SIZE\n\nmodel.fit(\n    valid_dataset.repeat(),\n    steps_per_epoch=n_steps,\n    epochs=2\n)","metadata":{"execution":{"iopub.status.busy":"2021-11-11T22:41:02.750028Z","iopub.execute_input":"2021-11-11T22:41:02.750377Z","iopub.status.idle":"2021-11-11T22:43:10.45618Z","shell.execute_reply.started":"2021-11-11T22:41:02.75035Z","shell.execute_reply":"2021-11-11T22:43:10.455283Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"checkpointPredictions3 = model.predict(test_dataset, verbose=1)\nprint(checkpointPredictions3[:10])","metadata":{"execution":{"iopub.status.busy":"2021-11-11T22:43:10.457626Z","iopub.execute_input":"2021-11-11T22:43:10.458023Z","iopub.status.idle":"2021-11-11T22:43:15.654131Z","shell.execute_reply.started":"2021-11-11T22:43:10.457981Z","shell.execute_reply":"2021-11-11T22:43:15.65331Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Train on multilingual external data (created using SSL techniques)","metadata":{}},{"cell_type":"code","source":"n_steps = x_trainOA.shape[0]  // BATCH_SIZE\n\nmodel.fit(\n    train_datasetOA,\n    steps_per_epoch=n_steps,\n    epochs=1\n)","metadata":{"execution":{"iopub.status.busy":"2021-11-11T22:43:15.655281Z","iopub.execute_input":"2021-11-11T22:43:15.655607Z","iopub.status.idle":"2021-11-11T22:52:15.242779Z","shell.execute_reply.started":"2021-11-11T22:43:15.655576Z","shell.execute_reply":"2021-11-11T22:52:15.241756Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"checkpointPredictions4 = model.predict(test_dataset, verbose=1)\nprint(checkpointPredictions4[:10])","metadata":{"execution":{"iopub.status.busy":"2021-11-11T22:52:15.244171Z","iopub.execute_input":"2021-11-11T22:52:15.244497Z","iopub.status.idle":"2021-11-11T22:52:20.672196Z","shell.execute_reply.started":"2021-11-11T22:52:15.244458Z","shell.execute_reply":"2021-11-11T22:52:20.671182Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Submission","metadata":{}},{"cell_type":"code","source":"sub = pd.read_csv('../input/jigsaw-toxic-severity-rating/sample_submission.csv')\nsub['score'] = (checkpointPredictions1*0.05)+(checkpointPredictions2*0.10)+(checkpointPredictions3*0.76)+(checkpointPredictions4*0.09)\nsub.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2021-11-11T22:52:20.673626Z","iopub.execute_input":"2021-11-11T22:52:20.673879Z","iopub.status.idle":"2021-11-11T22:52:20.731816Z","shell.execute_reply.started":"2021-11-11T22:52:20.67385Z","shell.execute_reply":"2021-11-11T22:52:20.73084Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.hist(sub.score.values)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-11-11T23:04:58.505673Z","iopub.execute_input":"2021-11-11T23:04:58.50595Z","iopub.status.idle":"2021-11-11T23:04:58.785185Z","shell.execute_reply.started":"2021-11-11T23:04:58.505922Z","shell.execute_reply":"2021-11-11T23:04:58.784256Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub.head(30)","metadata":{"execution":{"iopub.status.busy":"2021-11-11T23:05:22.566498Z","iopub.execute_input":"2021-11-11T23:05:22.567057Z","iopub.status.idle":"2021-11-11T23:05:22.578612Z","shell.execute_reply.started":"2021-11-11T23:05:22.567024Z","shell.execute_reply":"2021-11-11T23:05:22.577722Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}