{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Requirement already satisfied: transformers in /usr/local/lib/python3.11/dist-packages (4.45.0.dev0)\n",
"Requirement already satisfied: datasets in /usr/local/lib/python3.11/dist-packages (2.21.0)\n",
"Requirement already satisfied: filelock in /usr/local/lib/python3.11/dist-packages (from transformers) (3.15.4)\n",
"Requirement already satisfied: huggingface-hub<1.0,>=0.23.2 in /usr/local/lib/python3.11/dist-packages (from transformers) (0.24.6)\n",
"Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.11/dist-packages (from transformers) (1.26.4)\n",
"Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.11/dist-packages (from transformers) (24.1)\n",
"Requirement already satisfied: pyyaml>=5.1 in /usr/local/lib/python3.11/dist-packages (from transformers) (6.0.2)\n",
"Requirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.11/dist-packages (from transformers) (2024.7.24)\n",
"Requirement already satisfied: requests in /usr/local/lib/python3.11/dist-packages (from transformers) (2.32.3)\n",
"Requirement already satisfied: tokenizers<0.20,>=0.19 in /usr/local/lib/python3.11/dist-packages (from transformers) (0.19.1)\n",
"Requirement already satisfied: safetensors>=0.4.1 in /usr/local/lib/python3.11/dist-packages (from transformers) (0.4.5)\n",
"Requirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.11/dist-packages (from transformers) (4.66.5)\n",
"Requirement already satisfied: pyarrow>=15.0.0 in /usr/local/lib/python3.11/dist-packages (from datasets) (17.0.0)\n",
"Requirement already satisfied: dill<0.3.9,>=0.3.0 in /usr/local/lib/python3.11/dist-packages (from datasets) (0.3.8)\n",
"Requirement already satisfied: pandas in /usr/local/lib/python3.11/dist-packages (from datasets) (2.2.2)\n",
"Requirement already satisfied: xxhash in /usr/local/lib/python3.11/dist-packages (from datasets) (3.5.0)\n",
"Requirement already satisfied: multiprocess in /usr/local/lib/python3.11/dist-packages (from datasets) (0.70.16)\n",
"Requirement already satisfied: fsspec<=2024.6.1,>=2023.1.0 in /usr/local/lib/python3.11/dist-packages (from fsspec[http]<=2024.6.1,>=2023.1.0->datasets) (2024.6.1)\n",
"Requirement already satisfied: aiohttp in /usr/local/lib/python3.11/dist-packages (from datasets) (3.10.5)\n",
"Requirement already satisfied: aiohappyeyeballs>=2.3.0 in /usr/local/lib/python3.11/dist-packages (from aiohttp->datasets) (2.4.0)\n",
"Requirement already satisfied: aiosignal>=1.1.2 in /usr/local/lib/python3.11/dist-packages (from aiohttp->datasets) (1.3.1)\n",
"Requirement already satisfied: attrs>=17.3.0 in /usr/local/lib/python3.11/dist-packages (from aiohttp->datasets) (24.2.0)\n",
"Requirement already satisfied: frozenlist>=1.1.1 in /usr/local/lib/python3.11/dist-packages (from aiohttp->datasets) (1.4.1)\n",
"Requirement already satisfied: multidict<7.0,>=4.5 in /usr/local/lib/python3.11/dist-packages (from aiohttp->datasets) (6.1.0)\n",
"Requirement already satisfied: yarl<2.0,>=1.0 in /usr/local/lib/python3.11/dist-packages (from aiohttp->datasets) (1.11.1)\n",
"Requirement already satisfied: typing-extensions>=3.7.4.3 in /usr/local/lib/python3.11/dist-packages (from huggingface-hub<1.0,>=0.23.2->transformers) (4.12.2)\n",
"Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.11/dist-packages (from requests->transformers) (3.3.2)\n",
"Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.11/dist-packages (from requests->transformers) (3.7)\n",
"Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.11/dist-packages (from requests->transformers) (2.2.2)\n",
"Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.11/dist-packages (from requests->transformers) (2024.7.4)\n",
"Requirement already satisfied: python-dateutil>=2.8.2 in /usr/local/lib/python3.11/dist-packages (from pandas->datasets) (2.9.0.post0)\n",
"Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.11/dist-packages (from pandas->datasets) (2024.1)\n",
"Requirement already satisfied: tzdata>=2022.7 in /usr/local/lib/python3.11/dist-packages (from pandas->datasets) (2024.1)\n",
"Requirement already satisfied: six>=1.5 in /usr/lib/python3/dist-packages (from python-dateutil>=2.8.2->pandas->datasets) (1.16.0)\n",
"\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager, possibly rendering your system unusable.It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv. Use the --root-user-action option if you know what you are doing and want to suppress this warning.\u001b[0m\u001b[33m\n",
"\u001b[0mCollecting git+https://github.com/huggingface/transformers.git\n",
" Cloning https://github.com/huggingface/transformers.git to /tmp/pip-req-build-sok4bqyk\n",
" Running command git clone --filter=blob:none --quiet https://github.com/huggingface/transformers.git /tmp/pip-req-build-sok4bqyk\n",
" Resolved https://github.com/huggingface/transformers.git to commit 96429e74a8191521bcb4b99f48ad1fbc8f9e6873\n",
" Installing build dependencies ... \u001b[?25ldone\n",
"\u001b[?25h Getting requirements to build wheel ... \u001b[?25ldone\n",
"\u001b[?25h Preparing metadata (pyproject.toml) ... \u001b[?25ldone\n",
"\u001b[?25hRequirement already satisfied: filelock in /usr/local/lib/python3.11/dist-packages (from transformers==4.45.0.dev0) (3.15.4)\n",
"Requirement already satisfied: huggingface-hub<1.0,>=0.23.2 in /usr/local/lib/python3.11/dist-packages (from transformers==4.45.0.dev0) (0.24.6)\n",
"Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.11/dist-packages (from transformers==4.45.0.dev0) (1.26.4)\n",
"Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.11/dist-packages (from transformers==4.45.0.dev0) (24.1)\n",
"Requirement already satisfied: pyyaml>=5.1 in /usr/local/lib/python3.11/dist-packages (from transformers==4.45.0.dev0) (6.0.2)\n",
"Requirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.11/dist-packages (from transformers==4.45.0.dev0) (2024.7.24)\n",
"Requirement already satisfied: requests in /usr/local/lib/python3.11/dist-packages (from transformers==4.45.0.dev0) (2.32.3)\n",
"Requirement already satisfied: tokenizers<0.20,>=0.19 in /usr/local/lib/python3.11/dist-packages (from transformers==4.45.0.dev0) (0.19.1)\n",
"Requirement already satisfied: safetensors>=0.4.1 in /usr/local/lib/python3.11/dist-packages (from transformers==4.45.0.dev0) (0.4.5)\n",
"Requirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.11/dist-packages (from transformers==4.45.0.dev0) (4.66.5)\n",
"Requirement already satisfied: fsspec>=2023.5.0 in /usr/local/lib/python3.11/dist-packages (from huggingface-hub<1.0,>=0.23.2->transformers==4.45.0.dev0) (2024.6.1)\n",
"Requirement already satisfied: typing-extensions>=3.7.4.3 in /usr/local/lib/python3.11/dist-packages (from huggingface-hub<1.0,>=0.23.2->transformers==4.45.0.dev0) (4.12.2)\n",
"Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.11/dist-packages (from requests->transformers==4.45.0.dev0) (3.3.2)\n",
"Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.11/dist-packages (from requests->transformers==4.45.0.dev0) (3.7)\n",
"Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.11/dist-packages (from requests->transformers==4.45.0.dev0) (2.2.2)\n",
"Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.11/dist-packages (from requests->transformers==4.45.0.dev0) (2024.7.4)\n",
"\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager, possibly rendering your system unusable.It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv. Use the --root-user-action option if you know what you are doing and want to suppress this warning.\u001b[0m\u001b[33m\n",
"\u001b[0m"
]
}
],
"source": [
"# Transformers installation\n",
"! pip install transformers datasets\n",
"# To install from source instead of the last release, comment the command above and uncomment the following one.\n",
"! pip install git+https://github.com/huggingface/transformers.git"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Requirement already satisfied: accelerate in /usr/local/lib/python3.11/dist-packages (0.34.2)\n",
"Requirement already satisfied: numpy<3.0.0,>=1.17 in /usr/local/lib/python3.11/dist-packages (from accelerate) (1.26.4)\n",
"Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.11/dist-packages (from accelerate) (24.1)\n",
"Requirement already satisfied: psutil in /usr/local/lib/python3.11/dist-packages (from accelerate) (6.0.0)\n",
"Requirement already satisfied: pyyaml in /usr/local/lib/python3.11/dist-packages (from accelerate) (6.0.2)\n",
"Requirement already satisfied: torch>=1.10.0 in /usr/local/lib/python3.11/dist-packages (from accelerate) (2.4.0)\n",
"Requirement already satisfied: huggingface-hub>=0.21.0 in /usr/local/lib/python3.11/dist-packages (from accelerate) (0.24.6)\n",
"Requirement already satisfied: safetensors>=0.4.3 in /usr/local/lib/python3.11/dist-packages (from accelerate) (0.4.5)\n",
"Requirement already satisfied: filelock in /usr/local/lib/python3.11/dist-packages (from huggingface-hub>=0.21.0->accelerate) (3.15.4)\n",
"Requirement already satisfied: fsspec>=2023.5.0 in /usr/local/lib/python3.11/dist-packages (from huggingface-hub>=0.21.0->accelerate) (2024.6.1)\n",
"Requirement already satisfied: requests in /usr/local/lib/python3.11/dist-packages (from huggingface-hub>=0.21.0->accelerate) (2.32.3)\n",
"Requirement already satisfied: tqdm>=4.42.1 in /usr/local/lib/python3.11/dist-packages (from huggingface-hub>=0.21.0->accelerate) (4.66.5)\n",
"Requirement already satisfied: typing-extensions>=3.7.4.3 in /usr/local/lib/python3.11/dist-packages (from huggingface-hub>=0.21.0->accelerate) (4.12.2)\n",
"Requirement already satisfied: sympy in /usr/local/lib/python3.11/dist-packages (from torch>=1.10.0->accelerate) (1.13.2)\n",
"Requirement already satisfied: networkx in /usr/local/lib/python3.11/dist-packages (from torch>=1.10.0->accelerate) (3.3)\n",
"Requirement already satisfied: jinja2 in /usr/local/lib/python3.11/dist-packages (from torch>=1.10.0->accelerate) (3.1.4)\n",
"Requirement already satisfied: nvidia-cuda-nvrtc-cu12==12.1.105 in /usr/local/lib/python3.11/dist-packages (from torch>=1.10.0->accelerate) (12.1.105)\n",
"Requirement already satisfied: nvidia-cuda-runtime-cu12==12.1.105 in /usr/local/lib/python3.11/dist-packages (from torch>=1.10.0->accelerate) (12.1.105)\n",
"Requirement already satisfied: nvidia-cuda-cupti-cu12==12.1.105 in /usr/local/lib/python3.11/dist-packages (from torch>=1.10.0->accelerate) (12.1.105)\n",
"Requirement already satisfied: nvidia-cudnn-cu12==9.1.0.70 in /usr/local/lib/python3.11/dist-packages (from torch>=1.10.0->accelerate) (9.1.0.70)\n",
"Requirement already satisfied: nvidia-cublas-cu12==12.1.3.1 in /usr/local/lib/python3.11/dist-packages (from torch>=1.10.0->accelerate) (12.1.3.1)\n",
"Requirement already satisfied: nvidia-cufft-cu12==11.0.2.54 in /usr/local/lib/python3.11/dist-packages (from torch>=1.10.0->accelerate) (11.0.2.54)\n",
"Requirement already satisfied: nvidia-curand-cu12==10.3.2.106 in /usr/local/lib/python3.11/dist-packages (from torch>=1.10.0->accelerate) (10.3.2.106)\n",
"Requirement already satisfied: nvidia-cusolver-cu12==11.4.5.107 in /usr/local/lib/python3.11/dist-packages (from torch>=1.10.0->accelerate) (11.4.5.107)\n",
"Requirement already satisfied: nvidia-cusparse-cu12==12.1.0.106 in /usr/local/lib/python3.11/dist-packages (from torch>=1.10.0->accelerate) (12.1.0.106)\n",
"Requirement already satisfied: nvidia-nccl-cu12==2.20.5 in /usr/local/lib/python3.11/dist-packages (from torch>=1.10.0->accelerate) (2.20.5)\n",
"Requirement already satisfied: nvidia-nvtx-cu12==12.1.105 in /usr/local/lib/python3.11/dist-packages (from torch>=1.10.0->accelerate) (12.1.105)\n",
"Requirement already satisfied: triton==3.0.0 in /usr/local/lib/python3.11/dist-packages (from torch>=1.10.0->accelerate) (3.0.0)\n",
"Requirement already satisfied: nvidia-nvjitlink-cu12 in /usr/local/lib/python3.11/dist-packages (from nvidia-cusolver-cu12==11.4.5.107->torch>=1.10.0->accelerate) (12.6.20)\n",
"Requirement already satisfied: MarkupSafe>=2.0 in /usr/local/lib/python3.11/dist-packages (from jinja2->torch>=1.10.0->accelerate) (2.1.5)\n",
"Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.11/dist-packages (from requests->huggingface-hub>=0.21.0->accelerate) (3.3.2)\n",
"Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.11/dist-packages (from requests->huggingface-hub>=0.21.0->accelerate) (3.7)\n",
"Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.11/dist-packages (from requests->huggingface-hub>=0.21.0->accelerate) (2.2.2)\n",
"Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.11/dist-packages (from requests->huggingface-hub>=0.21.0->accelerate) (2024.7.4)\n",
"Requirement already satisfied: mpmath<1.4,>=1.1.0 in /usr/local/lib/python3.11/dist-packages (from sympy->torch>=1.10.0->accelerate) (1.3.0)\n",
"\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager, possibly rendering your system unusable.It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv. Use the --root-user-action option if you know what you are doing and want to suppress this warning.\u001b[0m\u001b[33m\n",
"\u001b[0mRequirement already satisfied: transformers in /usr/local/lib/python3.11/dist-packages (4.45.0.dev0)\n",
"Requirement already satisfied: filelock in /usr/local/lib/python3.11/dist-packages (from transformers) (3.15.4)\n",
"Requirement already satisfied: huggingface-hub<1.0,>=0.23.2 in /usr/local/lib/python3.11/dist-packages (from transformers) (0.24.6)\n",
"Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.11/dist-packages (from transformers) (1.26.4)\n",
"Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.11/dist-packages (from transformers) (24.1)\n",
"Requirement already satisfied: pyyaml>=5.1 in /usr/local/lib/python3.11/dist-packages (from transformers) (6.0.2)\n",
"Requirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.11/dist-packages (from transformers) (2024.7.24)\n",
"Requirement already satisfied: requests in /usr/local/lib/python3.11/dist-packages (from transformers) (2.32.3)\n",
"Requirement already satisfied: tokenizers<0.20,>=0.19 in /usr/local/lib/python3.11/dist-packages (from transformers) (0.19.1)\n",
"Requirement already satisfied: safetensors>=0.4.1 in /usr/local/lib/python3.11/dist-packages (from transformers) (0.4.5)\n",
"Requirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.11/dist-packages (from transformers) (4.66.5)\n",
"Requirement already satisfied: fsspec>=2023.5.0 in /usr/local/lib/python3.11/dist-packages (from huggingface-hub<1.0,>=0.23.2->transformers) (2024.6.1)\n",
"Requirement already satisfied: typing-extensions>=3.7.4.3 in /usr/local/lib/python3.11/dist-packages (from huggingface-hub<1.0,>=0.23.2->transformers) (4.12.2)\n",
"Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.11/dist-packages (from requests->transformers) (3.3.2)\n",
"Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.11/dist-packages (from requests->transformers) (3.7)\n",
"Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.11/dist-packages (from requests->transformers) (2.2.2)\n",
"Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.11/dist-packages (from requests->transformers) (2024.7.4)\n",
"\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager, possibly rendering your system unusable.It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv. Use the --root-user-action option if you know what you are doing and want to suppress this warning.\u001b[0m\u001b[33m\n",
"\u001b[0m"
]
}
],
"source": [
"! pip install -U accelerate\n",
"! pip install -U transformers"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"# !pip install accelerate"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"# !pip install transformers[torch]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Causal language modeling"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There are two types of language modeling, causal and masked. This guide illustrates causal language modeling.\n",
"Causal language models are frequently used for text generation. You can use these models for creative applications like\n",
"choosing your own text adventure or an intelligent coding assistant like Copilot or CodeParrot."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"cellView": "form",
"hide_input": true
},
"outputs": [],
"source": [
"# #@title\n",
"# from IPython.display import HTML\n",
"\n",
"# HTML('')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Causal language modeling predicts the next token in a sequence of tokens, and the model can only attend to tokens on\n",
"the left. This means the model cannot see future tokens. GPT-2 is an example of a causal language model.\n",
"\n",
"This guide will show you how to:\n",
"\n",
"1. Finetune [DistilGPT2](https://huggingface.co/distilgpt2) on the [r/askscience](https://www.reddit.com/r/askscience/) subset of the [ELI5](https://huggingface.co/datasets/eli5) dataset.\n",
"2. Use your finetuned model for inference.\n",
"\n",
"\n",
"You can finetune other architectures for causal language modeling following the same steps in this guide.\n",
"Choose one of the following architectures:\n",
"\n",
"\n",
"[BART](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/bart), [BERT](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/bert), [Bert Generation](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/bert-generation), [BigBird](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/big_bird), [BigBird-Pegasus](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/bigbird_pegasus), [BioGpt](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/biogpt), [Blenderbot](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/blenderbot), [BlenderbotSmall](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/blenderbot-small), [BLOOM](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/bloom), [CamemBERT](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/camembert), [CodeGen](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/codegen), [CPM-Ant](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/cpmant), [CTRL](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/ctrl), [Data2VecText](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/data2vec-text), [ELECTRA](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/electra), [ERNIE](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/ernie), [GIT](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/git), [GPT-Sw3](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/gpt-sw3), [OpenAI GPT-2](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/gpt2), [GPTBigCode](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/gpt_bigcode), [GPT Neo](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/gpt_neo), [GPT NeoX](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/gpt_neox), [GPT NeoX Japanese](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/gpt_neox_japanese), [GPT-J](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/gptj), [LLaMA](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/llama), [Marian](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/marian), [mBART](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/mbart), [MEGA](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/mega), [Megatron-BERT](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/megatron-bert), [MVP](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/mvp), [OpenLlama](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/open-llama), [OpenAI GPT](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/openai-gpt), [OPT](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/opt), [Pegasus](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/pegasus), [PLBart](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/plbart), [ProphetNet](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/prophetnet), [QDQBert](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/qdqbert), [Reformer](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/reformer), [RemBERT](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/rembert), [RoBERTa](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/roberta), [RoBERTa-PreLayerNorm](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/roberta-prelayernorm), [RoCBert](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/roc_bert), [RoFormer](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/roformer), [RWKV](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/rwkv), [Speech2Text2](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/speech_to_text_2), [Transformer-XL](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/transfo-xl), [TrOCR](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/trocr), [XGLM](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/xglm), [XLM](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/xlm), [XLM-ProphetNet](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/xlm-prophetnet), [XLM-RoBERTa](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/xlm-roberta), [XLM-RoBERTa-XL](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/xlm-roberta-xl), [XLNet](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/xlnet), [X-MOD](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/xmod)\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"Before you begin, make sure you have all the necessary libraries installed:\n",
"\n",
"```bash\n",
"pip install transformers datasets evaluate\n",
"```\n",
"\n",
"We encourage you to log in to your Hugging Face account so you can upload and share your model with the community. When prompted, enter your token to log in:"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"# from huggingface_hub import notebook_login\n",
"\n",
"# notebook_login()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Load ELI5 dataset"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Start by loading a smaller subset of the r/askscience subset of the ELI5 dataset from the 🤗 Datasets library.\n",
" This'll give you a chance to experiment and make sure everything works before spending more time training on the full dataset."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"# from datasets import load_dataset\n",
"\n",
"# eli5 = load_dataset(\"eli5\", split=\"train_asks[:5000]\")"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"from datasets import load_dataset\n",
"# Falcon = load_dataset(\"csv\", data_files=\"FalconData.csv\")\n",
"Falcon = load_dataset('csv', data_files={\"train\": 'FalconData_train.csv', \"validation\": 'FalconData_validation.csv'})"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Split the dataset's `train_asks` split into a train and test set with the [train_test_split](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.train_test_split) method:"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"# Falcon = Falcon.train_test_split(test_size=0.10)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Then take a look at an example:"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'Text': 'Once the kind of organization is decided, right now is the time for the purpose of the huge talk with the parents. Additionally, you will have to credit your company while using the board. Right now there a few techniques which usually you can get started on the cellular phone restoration organization.\\nBecause you develop your organization, you can want to realize how to raise your skill sets and tactics. After formulating your firm notion and organizing the funds, the next idea to perform is to check out the organization. In addition , if occur to be certainly not in the automobile business yet work via the internet with consumers via the net and email, after that some of your suggestions you are going to see are certain to get the work performed to get you too.\\nWhat you will requirement for your company depends upon a great deal of factors, therefore is actually ideal to pay a visit to the Nevada Department of Insurance internet site to get detailed info. Once you wish to start up your unique enterprise, then simply it is important to apply entitlements of your have firm. The few males and ladies in little business want to know more and carry out more with a great deal fewer. For illustration, the ordinary organization runs the data centre 10 hours every day. Even more businesses experience began to take notice of the huge benefits of giving birth to a business program analyst in staff. As you take your small business to the world-wide market segments, it is going to become important to think about a lot a large number of things to ascertain the organization efficiently. Decide what kind of business being you desire to allocate to your panorama business.\\nRecuperate this will depend after the sort of assistance you give. Right now there are a lot of different varieties of Web service yet I will list the most typical types out there. Found in addition, you will need high-speed on the net service to mail and acquire job data files to your consumers.\\nMany people today are unsuccessful in organization given that they make avoidable mistakes! A put together organization is a great likelihood to communicate the fine art just the way that you like it. You can actually without difficulty control the company if it’s legitimate. While not efficient communication, the businesses could not discover the strategies to create the business and website link while using the all over the world clients and companions. A great excellent car shop tools business will make sure you experience all owners and parts manuals alongside one another with service plan directives for all of you heavy machines you purchase or perhaps let out.\\nIn case you blowing wind up going, where you began your company won’t change! It’s actually now possible to advertise your business to anybody anywhere for the purpose of practically no selling price. So you may absolutely cost-free to pay attention to different important things that matter to you such as growing your business and a lot more. If the service is mostly an operation product, you should supply a replicate within the operation contract. Websites like craigslist and or perhaps Tradelit That is certainly, in the event people are likely to build a company. Presently a days and nights Many businesses are unaware of the significance of SEO in improving the internet occurrence. If you expect to have carrying out a fee-for-service tutoring organization, then you might preference to think about signing up your company considering the state.\\nKind of organization Primarily based upon at the sort of business, you need to do business with a variety of organizations. Not only a single company are able to take advantage of a similar well-known. If an organization can better figure out their normal user’s requires, it will develop into a excellent less complicated to guarantee that every consumer has a confident knowledge in handling your business with regards to a entire. Even firms want a huge data stats official certifications prior to taking the help of a person. As a result, all of them over the world are inclined to take full advantage of technology, on particular, cordless devices and public hotspots. The organization should also be capable of offering any kind of teaching vital to buy and sell each machine safely. Daily, an increasing number of businesses are putting up or perhaps establishing an electronic business. For more info read right here whatsbakingsd.com .'}"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Falcon['train'][0]"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'Text': ', John Morris (19282003), historian\\nOxford Biography Index Number 101089999 [what is this?] Primary authority: Oxford DNB\\nColin Lucas, Roberts, John Morris (19282003), first published\\nJan 2007; online edn, Oct 2009, 1683 words, with portrait illustration\\n> View John Roberts complete biography [Oxford DNB subscription required; no subscription?]\\n> View John Roberts complete biography\\n[WWW subscription required; no subscription?]'}"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Falcon['validation'][0]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"While this may look like a lot, you're only really interested in the `text` field. What's cool about language modeling\n",
"tasks is you don't need labels (also known as an unsupervised task) because the next word *is* the label."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Preprocess"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"cellView": "form",
"hide_input": true
},
"outputs": [],
"source": [
"# #@title\n",
"# from IPython.display import HTML\n",
"\n",
"# HTML('')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The next step is to load a DistilGPT2 tokenizer to process the `text` subfield:"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/usr/local/lib/python3.11/dist-packages/transformers/tokenization_utils_base.py:1614: FutureWarning: `clean_up_tokenization_spaces` was not set. It will be set to `True` by default. This behavior will be deprecated in transformers v4.45, and will be then set to `False` by default. For more details check this issue: https://github.com/huggingface/transformers/issues/31884\n",
" warnings.warn(\n"
]
}
],
"source": [
"from transformers import AutoTokenizer, GPT2TokenizerFast\n",
"\n",
"tokenizer = AutoTokenizer.from_pretrained(\"distilgpt2\")\n",
"\n",
"\n",
"# tokenizer = GPT2TokenizerFast.from_pretrained(\"Xenova/gpt-4\")#, cache_dir=cache_dir)\n",
"tokenizer.pad_token = tokenizer.eos_token"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You'll notice from the example above, the `text` field is actually nested inside `answers`. This means you'll need to\n",
"extract the `text` subfield from its nested structure with the [`flatten`](https://huggingface.co/docs/datasets/process.html#flatten) method:"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'Text': 'Once the kind of organization is decided, right now is the time for the purpose of the huge talk with the parents. Additionally, you will have to credit your company while using the board. Right now there a few techniques which usually you can get started on the cellular phone restoration organization.\\nBecause you develop your organization, you can want to realize how to raise your skill sets and tactics. After formulating your firm notion and organizing the funds, the next idea to perform is to check out the organization. In addition , if occur to be certainly not in the automobile business yet work via the internet with consumers via the net and email, after that some of your suggestions you are going to see are certain to get the work performed to get you too.\\nWhat you will requirement for your company depends upon a great deal of factors, therefore is actually ideal to pay a visit to the Nevada Department of Insurance internet site to get detailed info. Once you wish to start up your unique enterprise, then simply it is important to apply entitlements of your have firm. The few males and ladies in little business want to know more and carry out more with a great deal fewer. For illustration, the ordinary organization runs the data centre 10 hours every day. Even more businesses experience began to take notice of the huge benefits of giving birth to a business program analyst in staff. As you take your small business to the world-wide market segments, it is going to become important to think about a lot a large number of things to ascertain the organization efficiently. Decide what kind of business being you desire to allocate to your panorama business.\\nRecuperate this will depend after the sort of assistance you give. Right now there are a lot of different varieties of Web service yet I will list the most typical types out there. Found in addition, you will need high-speed on the net service to mail and acquire job data files to your consumers.\\nMany people today are unsuccessful in organization given that they make avoidable mistakes! A put together organization is a great likelihood to communicate the fine art just the way that you like it. You can actually without difficulty control the company if it’s legitimate. While not efficient communication, the businesses could not discover the strategies to create the business and website link while using the all over the world clients and companions. A great excellent car shop tools business will make sure you experience all owners and parts manuals alongside one another with service plan directives for all of you heavy machines you purchase or perhaps let out.\\nIn case you blowing wind up going, where you began your company won’t change! It’s actually now possible to advertise your business to anybody anywhere for the purpose of practically no selling price. So you may absolutely cost-free to pay attention to different important things that matter to you such as growing your business and a lot more. If the service is mostly an operation product, you should supply a replicate within the operation contract. Websites like craigslist and or perhaps Tradelit That is certainly, in the event people are likely to build a company. Presently a days and nights Many businesses are unaware of the significance of SEO in improving the internet occurrence. If you expect to have carrying out a fee-for-service tutoring organization, then you might preference to think about signing up your company considering the state.\\nKind of organization Primarily based upon at the sort of business, you need to do business with a variety of organizations. Not only a single company are able to take advantage of a similar well-known. If an organization can better figure out their normal user’s requires, it will develop into a excellent less complicated to guarantee that every consumer has a confident knowledge in handling your business with regards to a entire. Even firms want a huge data stats official certifications prior to taking the help of a person. As a result, all of them over the world are inclined to take full advantage of technology, on particular, cordless devices and public hotspots. The organization should also be capable of offering any kind of teaching vital to buy and sell each machine safely. Daily, an increasing number of businesses are putting up or perhaps establishing an electronic business. For more info read right here whatsbakingsd.com .'}"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Falcon = Falcon.flatten()\n",
"Falcon[\"train\"][0]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Each subfield is now a separate column as indicated by the `answers` prefix, and the `text` field is a list now. Instead\n",
"of tokenizing each sentence separately, convert the list to a string so you can jointly tokenize them.\n",
"\n",
"Here is a first preprocessing function to join the list of strings for each example and tokenize the result:"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"def preprocess_function(examples):\n",
" return tokenizer([\" \".join(x) for x in examples[\"Text\"]])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To apply this preprocessing function over the entire dataset, use the 🤗 Datasets [map](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.map) method. You can speed up the `map` function by setting `batched=True` to process multiple elements of the dataset at once, and increasing the number of processes with `num_proc`. Remove any columns you don't need:"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [],
"source": [
"tokenized_Falcon = Falcon.map(\n",
" preprocess_function,\n",
" batched=True,\n",
" num_proc=4,\n",
" remove_columns=Falcon[\"train\"].column_names,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This dataset contains the token sequences, but some of these are longer than the maximum input length for the model.\n",
"\n",
"You can now use a second preprocessing function to\n",
"- concatenate all the sequences\n",
"- split the concatenated sequences into shorter chunks defined by `block_size`, which should be both shorter than the maximum input length and short enough for your GPU RAM."
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
"block_size = 1048\n",
"\n",
"\n",
"def group_texts(examples):\n",
" # Concatenate all texts.\n",
" concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()}\n",
" total_length = len(concatenated_examples[list(examples.keys())[0]])\n",
" # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can\n",
" # customize this part to your needs.\n",
" if total_length >= block_size:\n",
" total_length = (total_length // block_size) * block_size\n",
" # Split by chunks of block_size.\n",
" result = {\n",
" k: [t[i : i + block_size] for i in range(0, total_length, block_size)]\n",
" for k, t in concatenated_examples.items()\n",
" }\n",
" result[\"labels\"] = result[\"input_ids\"].copy()\n",
" return result"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Apply the `group_texts` function over the entire dataset:"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [],
"source": [
"lm_dataset = tokenized_Falcon.map(group_texts, batched=True, num_proc=4)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now create a batch of examples using [DataCollatorForLanguageModeling](https://huggingface.co/docs/transformers/main/en/main_classes/data_collator#transformers.DataCollatorForLanguageModeling). It's more efficient to *dynamically pad* the\n",
"sentences to the longest length in a batch during collation, instead of padding the whole dataset to the maximum length.\n",
"\n",
"Use the end-of-sequence token as the padding token and set `mlm=False`. This will use the inputs as labels shifted to the right by one element:"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [],
"source": [
"from transformers import DataCollatorForLanguageModeling\n",
"\n",
"tokenizer.pad_token = tokenizer.eos_token\n",
"data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Train"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"If you aren't familiar with finetuning a model with the [Trainer](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer), take a look at the [basic tutorial](https://huggingface.co/docs/transformers/main/en/tasks/../training#train-with-pytorch-trainer)!\n",
"\n",
"\n",
"\n",
"You're ready to start training your model now! Load DistilGPT2 with [AutoModelForCausalLM](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoModelForCausalLM):"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"from transformers import AutoModelForCausalLM, TrainingArguments, Trainer\n",
"import torch\n",
"model = AutoModelForCausalLM.from_pretrained(\"rwh/tinytoo\", torch_dtype=torch.bfloat16) "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"At this point, only three steps remain:\n",
"\n",
"1. Define your training hyperparameters in [TrainingArguments](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments). The only required parameter is `output_dir` which specifies where to save your model. You'll push this model to the Hub by setting `push_to_hub=True` (you need to be signed in to Hugging Face to upload your model).\n",
"2. Pass the training arguments to [Trainer](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer) along with the model, datasets, and data collator.\n",
"3. Call [train()](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer.train) to finetune your model."
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {},
"outputs": [],
"source": [
"import torch\n",
"torch.cuda.empty_cache()"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {},
"outputs": [],
"source": [
"import torch\n",
"import gc\n",
"\n",
"# del tensor_name # Delete the tensor\n",
"gc.collect() # Collect garbage\n",
"torch.cuda.empty_cache() # Clear cache"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [],
"source": [
"torch.cuda.empty_cache()"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
""
]
},
"execution_count": 45,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"torch.no_grad()"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"LlamaForCausalLM(\n",
" (model): LlamaModel(\n",
" (embed_tokens): Embedding(50257, 1408)\n",
" (layers): ModuleList(\n",
" (0-23): 24 x LlamaDecoderLayer(\n",
" (self_attn): LlamaSdpaAttention(\n",
" (q_proj): Linear(in_features=1408, out_features=1408, bias=False)\n",
" (k_proj): Linear(in_features=1408, out_features=1408, bias=False)\n",
" (v_proj): Linear(in_features=1408, out_features=1408, bias=False)\n",
" (o_proj): Linear(in_features=1408, out_features=1408, bias=False)\n",
" (rotary_emb): LlamaRotaryEmbedding()\n",
" )\n",
" (mlp): LlamaMLP(\n",
" (gate_proj): Linear(in_features=1408, out_features=4340, bias=False)\n",
" (up_proj): Linear(in_features=1408, out_features=4340, bias=False)\n",
" (down_proj): Linear(in_features=4340, out_features=1408, bias=False)\n",
" (act_fn): SiLU()\n",
" )\n",
" (input_layernorm): LlamaRMSNorm((1408,), eps=1e-05)\n",
" (post_attention_layernorm): LlamaRMSNorm((1408,), eps=1e-05)\n",
" )\n",
" )\n",
" (norm): LlamaRMSNorm((1408,), eps=1e-05)\n",
" (rotary_emb): LlamaRotaryEmbedding()\n",
" )\n",
" (lm_head): Linear(in_features=1408, out_features=50257, bias=False)\n",
")"
]
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"model.to('cuda')"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/usr/local/lib/python3.11/dist-packages/transformers/training_args.py:1541: FutureWarning: `evaluation_strategy` is deprecated and will be removed in version 4.46 of 🤗 Transformers. Use `eval_strategy` instead\n",
" warnings.warn(\n"
]
}
],
"source": [
"training_args = TrainingArguments(\n",
" output_dir=\"Fine-Tuned-S9\",\n",
" bf16=True,\n",
" # evaluation_strategy=\"epoch\",\n",
" evaluation_strategy=\"steps\",\n",
" learning_rate=2e-5,\n",
" weight_decay=0.01,\n",
" num_train_epochs=1,\n",
" per_device_train_batch_size=2,\n",
" per_device_eval_batch_size=2,\n",
" # lr_scheduler_type = 'cosine',\n",
" push_to_hub=False,\n",
" save_total_limit = 2,\n",
" # save_strategy = “no”\n",
" load_best_model_at_end=False\n",
")\n",
"\n",
"trainer = Trainer(\n",
" model=model,\n",
" args=training_args,\n",
" train_dataset=lm_dataset[\"train\"],\n",
" eval_dataset=lm_dataset[\"validation\"],\n",
" # eval_dataset=lm_dataset[\"test\"],\n",
" data_collator=data_collator,\n",
")\n",
"\n",
"# trainer.train()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"trainer.train()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Once training is completed, use the [evaluate()](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer.evaluate) method to evaluate your model and get its perplexity:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import math\n",
"\n",
"eval_results = trainer.evaluate()\n",
"print(f\"Perplexity: {math.exp(eval_results['eval_loss']):.2f}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Then share your model to the Hub with the [push_to_hub()](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer.push_to_hub) method so everyone can use your model:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# trainer.push_to_hub()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"For a more in-depth example of how to finetune a model for causal language modeling, take a look at the corresponding\n",
"[PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling.ipynb)\n",
"or [TensorFlow notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling-tf.ipynb).\n",
"\n",
""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Inference"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Great, now that you've finetuned a model, you can use it for inference!\n",
"\n",
"Come up with a prompt you'd like to generate text from:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# prompt = \"Somatic hypermutation allows the immune system to\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The simplest way to try out your finetuned model for inference is to use it in a [pipeline()](https://huggingface.co/docs/transformers/main/en/main_classes/pipelines#transformers.pipeline). Instantiate a `pipeline` for text generation with your model, and pass your text to it:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# from transformers import pipeline\n",
"# # checkpoint-4000\n",
"# generator = pipeline(\"text-generation\", model=\"Fine-Tuned-S9/checkpoint-4000\")\n",
"# generator(prompt)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Tokenize the text and return the `input_ids` as PyTorch tensors:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# from transformers import AutoTokenizer\n",
"\n",
"# tokenizer = AutoTokenizer.from_pretrained(\"Xenova/gpt-4\")\n",
"# inputs = tokenizer(prompt, return_tensors=\"pt\").input_ids"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Use the [generate()](https://huggingface.co/docs/transformers/main/en/main_classes/text_generation#transformers.GenerationMixin.generate) method to generate text.\n",
"For more details about the different text generation strategies and parameters for controlling generation, check out the [Text generation strategies](https://huggingface.co/docs/transformers/main/en/tasks/../generation_strategies) page."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# from transformers import AutoModelForCausalLM\n",
"\n",
"# model = AutoModelForCausalLM.from_pretrained(\"deepnet/SN6-BestLlama\")\n",
"# outputs = model.generate(inputs, max_new_tokens=100, do_sample=True, top_k=50, top_p=0.95)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Decode the generated token ids back into text:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# tokenizer.batch_decode(outputs, skip_special_tokens=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# tokenizer.batch_decode(outputs, skip_special_tokens=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"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.11.9"
}
},
"nbformat": 4,
"nbformat_minor": 4
}