{"cells":[{"metadata":{},"cell_type":"markdown","source":"\n# 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","execution_count":null},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"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","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Helper Functions","execution_count":null},{"metadata":{"trusted":true},"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","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Configs","execution_count":null},{"metadata":{"trusted":true},"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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"AUTO = tf.data.experimental.AUTOTUNE\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\nMAX_LEN = 192\nMODEL = 'jplu/tf-xlm-roberta-large'","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Tokenizer","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# First load the real tokenizer\ntokenizer = AutoTokenizer.from_pretrained(MODEL)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Load Data","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"!ls /kaggle/input/jigsawtpuxlmrobertacopypickledata","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n\nfilename = \"/kaggle/input/jigsawtpuxlmrobertacopypickledata/jigsaw_multilingual_x_train.pkl\"\nx_train = pickle.load(open(filename, 'rb')) # load data example\nfilename = \"/kaggle/input/jigsawtpuxlmrobertacopypickledata/jigsaw_multilingual_x_trainOA.pkl\"\nx_trainOA = pickle.load(open(filename, 'rb')) # load data example\nfilename = \"/kaggle/input/jigsawtpuxlmrobertacopypickledata/jigsaw_multilingual_x_trainA.pkl\"\nx_trainA = pickle.load(open(filename, 'rb')) # load data example\nfilename = \"/kaggle/input/jigsawtpuxlmrobertacopypickledata/jigsaw_multilingual_x_valid.pkl\"\nx_valid = pickle.load(open(filename, 'rb')) # load data example\nfilename = \"/kaggle/input/jigsawtpuxlmrobertacopypickledata/jigsaw_multilingual_x_test.pkl\"\nx_test = pickle.load(open(filename, 'rb')) # load data example\n\nfilename = \"/kaggle/input/jigsawtpuxlmrobertacopypickledata/jigsaw_multilingual_y_train.pkl\"\ny_train = pickle.load(open(filename, 'rb')) # load data example\nfilename = \"/kaggle/input/jigsawtpuxlmrobertacopypickledata/jigsaw_multilingual_y_trainOA.pkl\"\ny_trainOA = pickle.load(open(filename, 'rb')) # load data example\nfilename = \"/kaggle/input/jigsawtpuxlmrobertacopypickledata/jigsaw_multilingual_y_trainA.pkl\"\ny_trainA = pickle.load(open(filename, 'rb')) # load data example\nfilename = \"/kaggle/input/jigsawtpuxlmrobertacopypickledata/jigsaw_multilingual_y_valid.pkl\"\ny_valid = pickle.load(open(filename, 'rb')) # load data example","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# TF Datasets","execution_count":null},{"metadata":{"trusted":true},"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)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Load Model","execution_count":null},{"metadata":{"trusted":true},"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()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Train","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"#### Train on English training data","execution_count":null},{"metadata":{"trusted":true},"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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"checkpointPredictions1 = model.predict(test_dataset, verbose=1)\nprint(checkpointPredictions1[:10])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Train on augmented english data","execution_count":null},{"metadata":{"trusted":true},"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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"checkpointPredictions2 = model.predict(test_dataset, verbose=1)\nprint(checkpointPredictions2[:10])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Train on multilingual validation training data","execution_count":null},{"metadata":{"trusted":true},"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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"checkpointPredictions3 = model.predict(test_dataset, verbose=1)\nprint(checkpointPredictions3[:10])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Train on multilingual external data (created using SSL techniques)","execution_count":null},{"metadata":{"trusted":true},"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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"checkpointPredictions4 = model.predict(test_dataset, verbose=1)\nprint(checkpointPredictions4[:10])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Submission","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"sub = pd.read_csv('/kaggle/input/jigsaw-multilingual-toxic-comment-classification/sample_submission.csv')\nsub['toxic'] = (checkpointPredictions1*0.05)+(checkpointPredictions2*0.10)+(checkpointPredictions3*0.76)+(checkpointPredictions4*0.09)\nsub.to_csv('submission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}