# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3.9 (tensorflow)
#     language: python
#     name: tensorflow
# ---

# + [markdown] id="3CF2edFAI4Uj"
# <a href="https://colab.research.google.com/github/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_11_02_tokenizers.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
#

# + [markdown] id="RvbM-RwHI4Ul"
# # T81-558: Applications of Deep Neural Networks
# **Module 11: Natural Language Processing with Hugging Face**
# * Instructor: [<NAME>](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx)
# * For more information visit the [class website](https://sites.wustl.edu/jeffheaton/t81-558/).

# + [markdown] id="5dE7A-0aI4Ul"
# # Module 11 Material
#
# * Part 11.1: Introduction to Hugging Face [[Video]](https://www.youtube.com/watch?v=1IHXSbz02XM&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_11_01_huggingface.ipynb)
# * **Part 11.2: Hugging Face Tokenizers** [[Video]](https://www.youtube.com/watch?v=U-EGU1RyChg&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_11_02_tokenizers.ipynb)
# * Part 11.3: Hugging Face Datasets [[Video]](https://www.youtube.com/watch?v=Mq5ODegT17M&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_11_03_hf_datasets.ipynb)
# * Part 11.4: Training Hugging Face Models [[Video]](https://www.youtube.com/watch?v=https://www.youtube.com/watch?v=l69ov6b7DOM&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_11_04_hf_train.ipynb)
# * Part 11.5: What are Embedding Layers in Keras [[Video]](https://www.youtube.com/watch?v=OuNH5kT-aD0list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN&index=58) [[Notebook]](https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_11_05_embedding.ipynb)

# + [markdown] id="9Z4A091yI4Um"
# # Google CoLab Instructions
#
# The following code ensures that Google CoLab is running the correct version of TensorFlow.

# + colab={"base_uri": "https://localhost:8080/"} id="RJmzbge9I4Um" outputId="4685a76c-cc37-490a-d589-db16eb6e9c4c"
try:
    # %tensorflow_version 2.x
    COLAB = True
    print("Note: using Google CoLab")
except:
    print("Note: not using Google CoLab")
    COLAB = False

# + [markdown] id="vdNN6e45I4Un"
# # Part 11.2: Hugging Face Tokenizers
#
# Tokenization is the task of chopping it up into pieces, called tokens, perhaps at the same time throwing away certain characters, such as punctuation. Consider how the program might break up the following sentences into words.
#
# * This is a test.
# * Ok, but what about this?
# * Is U.S.A. the same as USA.?
# * What is the best data-set to use?
# * I think I will do this-no wait; I will do that.
#
# The hugging face includes tokenizers that can break these sentences into words and subwords. Because English, and some other languages, are made up of common word parts, we tokenize subwords. For example, a gerund word, such as "sleeping," will be tokenized into "sleep" and "##ing".
#
# We begin by installing Hugging Face if needed.
#

# + colab={"base_uri": "https://localhost:8080/"} id="3jGET2abMjcl" outputId="35b8be0f-bc7e-42d0-f177-ee097d4a076c"
# HIDE OUTPUT
# !pip install transformers
# !pip install transformers[sentencepiece]

# + [markdown] id="Wa1ncodn8y0r"
# First, we create a Hugging Face tokenizer. There are several different tokenizers available from the Hugging Face hub. For this example, we will make use of the following tokenizer:
#
# * distilbert-base-uncased
#
# This tokenizer is based on BERT and assumes case-insensitive English text.

# + id="kSGtW0E7xcK9"
from transformers import AutoTokenizer
model = "distilbert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(model)


# + [markdown] id="YofjyJw59U2x"
# We can now tokenize a sample sentence.

# + colab={"base_uri": "https://localhost:8080/"} id="NVCmyao2zLQ3" outputId="6b33031a-8667-4431-aae2-26595195d69d"
encoded = tokenizer('Tokenizing text is easy.')
print(encoded)


# + [markdown] id="4QgmlpyezhMy"
# The result of this tokenization contains two elements:
# * input_ids - The individual subword indexes, each index uniquely identifies a subword.
# * attention_mask - Which values in *input_ids* are meaningful and not  padding.
# This sentence had no padding, so all elements have an attention mask of "1". Later, we will request the output to be of a fixed length, introducing padding, which always has an attention mask of "0". Though each tokenizer can be implemented differently, the attention mask of a tokenizer is generally either "0" or "1". 
#
# Due to subwords and special tokens, the number of tokens may not match the number of words in the source string. We can see the meanings of the individual tokens by converting these IDs back to strings.

# + colab={"base_uri": "https://localhost:8080/"} id="Ww3XPc-i2Y6c" outputId="6179b416-61cd-4142-fa15-ae2296e9eab7"
tokenizer.convert_ids_to_tokens(encoded.input_ids)


# + [markdown] id="7KM7VRJECoGU"
# As you can see, there are two special tokens placed at the beginning and end of each sequence. We will soon see how we can include or exclude these special tokens. These special tokens can vary per tokenizer; however, [CLS] begins a sequence for this tokenizer, and [SEP] ends a sequence. You will also see that the gerund "tokening" is broken into "token" and "*ing".
#
# For this tokenizer, the special tokens occur between 100 and 103. Most Hugging Face tokenizers use this approximate range for special tokens. The value zero (0) typically represents padding. We can display all special tokens with this command.
#
#

# + colab={"base_uri": "https://localhost:8080/"} id="EtQiOmSl2rXt" outputId="6f5f2aef-d718-4675-d0a5-9c6c9d960c87"
tokenizer.convert_ids_to_tokens([0, 100, 101, 102, 103])


# + [markdown] id="1nQ-r6bz3ESN"
# This tokenizer supports these common tokens:
#
# * \[CLS\] - Sequence beginning.
# * \[SEP\] - Sequence end.
# * \[PAD\] - Padding.
# * \[UNK\] - Unknown token.
# * \[MASK\] - Mask out tokens for a neural network to predict. Not used in this book, see [MLM paper](https://arxiv.org/abs/2109.01819). 
#
# It is also possible to tokenize lists of sequences. We can pad and truncate sequences to achieve a standard length by tokenizing many sequences at once.
#
#

# + colab={"base_uri": "https://localhost:8080/"} id="TI4RZXhc4v9k" outputId="2ae7f2f9-3d8a-421e-c9b9-4dd933817cd3"
text = [
    "This movie was great!",
    "I hated this move, waste of time!",
    "Epic?"
]

encoded = tokenizer(text, padding=True, add_special_tokens=True)

print("**Input IDs**")
for a in encoded.input_ids:
    print(a)

print("**Attention Mask**")
for a in encoded.attention_mask:
    print(a)


# + [markdown] id="1rIF8TEEF9C-"
# Notice the **input_id**'s for the three movie review text sequences. Each of these sequences begins with 101 and we pad with zeros. Just before the padding, each group of IDs ends with 102. The attention masks also have zeros for each of the padding entries. 
#
# We used two parameters to the tokenizer to control the tokenization process. Some other useful [parameters](https://huggingface.co/docs/transformers/main_classes/tokenizer) include:
#
# * add_special_tokens (defaults to True) Whether or not to encode the sequences with the special tokens relative to their model.
# * padding (defaults to False) Activates and controls truncation.
# * max_length (optional) Controls the maximum length to use by one of the truncation/padding parameters.
# -



StarcoderdataJupyterScriptsDedupFiltered