{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"machine_shape": "hm",
"gpuType": "V100",
"authorship_tag": "ABX9TyPXG8YN53SD54EwJ7vikFke",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
},
"accelerator": "GPU"
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"
"
]
},
{
"cell_type": "code",
"source": [
"from google.colab import drive\n",
"drive.mount('/content/drive')"
],
"metadata": {
"id": "S4Vqi5Ii3hF_",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "3b0bbe85-3c69-42ab-8071-2c1464515ec5"
},
"execution_count": 2,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Mounted at /content/drive\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"# importing the data\n",
"file_path = '/content/drive/MyDrive/big_data_v2.txt'\n",
"with open(file_path, 'r', encoding='utf-8') as file:\n",
" data = file.read()\n",
"total_no_of_words = len(data)\n",
"print(f\"{total_no_of_words/1e9} billion words\")"
],
"metadata": {
"id": "QbLkBa5S3pwl",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "ba920417-cc65-49cc-f60f-8b7843bce6b3"
},
"execution_count": 3,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"2.27416219 billion words\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"# total no of chars and vocab size\n",
"chars = sorted(list(set(data)))\n",
"vocab_size = len(chars)\n",
"# print(''.join(chars))\n",
"print('vocab size:', vocab_size)"
],
"metadata": {
"id": "aWU788nx3rhB",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "adc94b5b-f6fa-4525-9498-45a325358a6b"
},
"execution_count": 4,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"vocab size: 107363\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"# train-test split\n",
"\n",
"n = int(0.9*len(data)) # first 90% will be train, rest val\n",
"train_data = data[:n]\n",
"val_data = data[n:]"
],
"metadata": {
"id": "P7G65oTV3tma"
},
"execution_count": 5,
"outputs": []
},
{
"cell_type": "code",
"source": [
"print(f\"train data {len(train_data)}, val data {len(val_data)}\")"
],
"metadata": {
"id": "M0flKW6njg5m",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "37a19243-78c6-4aeb-f28a-f591d2cd1a46"
},
"execution_count": 6,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"train data 2046745971, val data 227416219\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"import timeit\n",
"start_time = timeit.default_timer()"
],
"metadata": {
"id": "6vOM85YE3vse"
},
"execution_count": 7,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# encoder and decoder of the text\n",
"string_to_index = { ch:i for i,ch in enumerate(chars) }\n",
"index_to_string = { i:ch for i,ch in enumerate(chars) }\n",
"\n",
"encode = lambda s: [string_to_index[c] for c in s]\n",
"decode = lambda l: ''.join([index_to_string[i] for i in l])\n",
"\n",
"print(encode('hello there'))\n",
"print(decode(encode('hello there')))"
],
"metadata": {
"id": "1jOagLL43ymD",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "14e8c75b-ba85-4c7a-9a6b-f9f94b706418"
},
"execution_count": 8,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"[96, 93, 100, 100, 103, 24, 108, 96, 93, 106, 93]\n",
"hello there\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"import torch\n",
"\n",
"# Convert to tensors\n",
"train_data = torch.tensor(encode(train_data), dtype=torch.long)\n",
"val_data = torch.tensor(encode(val_data), dtype=torch.long)"
],
"metadata": {
"id": "ZXimMdyR32wN"
},
"execution_count": 9,
"outputs": []
},
{
"cell_type": "code",
"source": [
"print(len(train_data)/1e6, 'million')\n",
"print(len(val_data)/1e6, 'million')"
],
"metadata": {
"id": "JKv8mswZIyYR",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "6a265df8-b67e-4342-f0a3-ad28cbf325c7"
},
"execution_count": 10,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"2046.745971 million\n",
"227.416219 million\n"
]
}
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"id": "hSbAd0fCl_nx",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 501
},
"outputId": "72ffab29-bc94-431a-c75c-6f64c3167fbb"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"148.185955 million\n"
]
},
{
"output_type": "error",
"ename": "OutOfMemoryError",
"evalue": "CUDA out of memory. Tried to allocate 26.21 GiB. GPU 0 has a total capacty of 15.77 GiB of which 13.89 GiB is free. Process 2283 has 1.88 GiB memory in use. Of the allocated memory 1.38 GiB is allocated by PyTorch, and 144.98 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting max_split_size_mb to avoid fragmentation. See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mOutOfMemoryError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 191\u001b[0m \u001b[0;31m# every once in a while evaluate the loss on train and val sets\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 192\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0miter\u001b[0m \u001b[0;34m%\u001b[0m \u001b[0meval_interval\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;36m0\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0miter\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0mmax_iters\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 193\u001b[0;31m \u001b[0mlosses\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mestimate_loss\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 194\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34mf\"step {iter}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f}\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 195\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.10/dist-packages/torch/utils/_contextlib.py\u001b[0m in \u001b[0;36mdecorate_context\u001b[0;34m(*args, **kwargs)\u001b[0m\n\u001b[1;32m 113\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mdecorate_context\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 114\u001b[0m \u001b[0;32mwith\u001b[0m \u001b[0mctx_factory\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 115\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mfunc\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 116\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 117\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mdecorate_context\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m\u001b[0m in \u001b[0;36mestimate_loss\u001b[0;34m()\u001b[0m\n\u001b[1;32m 38\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mk\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mrange\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0meval_iters\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 39\u001b[0m \u001b[0mX\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mY\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mget_batch\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0msplit\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 40\u001b[0;31m \u001b[0mlogits\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mloss\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mmodel\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mX\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mY\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 41\u001b[0m \u001b[0mlosses\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mk\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mloss\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mitem\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 42\u001b[0m \u001b[0mout\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0msplit\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mlosses\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmean\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py\u001b[0m in \u001b[0;36m_wrapped_call_impl\u001b[0;34m(self, *args, **kwargs)\u001b[0m\n\u001b[1;32m 1516\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_compiled_call_impl\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# type: ignore[misc]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1517\u001b[0m \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1518\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_call_impl\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 1519\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1520\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0m_call_impl\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py\u001b[0m in \u001b[0;36m_call_impl\u001b[0;34m(self, *args, **kwargs)\u001b[0m\n\u001b[1;32m 1525\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0m_global_backward_pre_hooks\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0m_global_backward_hooks\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1526\u001b[0m or _global_forward_hooks or _global_forward_pre_hooks):\n\u001b[0;32m-> 1527\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mforward_call\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 1528\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1529\u001b[0m \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m\u001b[0m in \u001b[0;36mforward\u001b[0;34m(self, idx, targets)\u001b[0m\n\u001b[1;32m 146\u001b[0m \u001b[0mx\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mblocks\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# (B,T,C)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 147\u001b[0m \u001b[0mx\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mln_f\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# (B,T,C)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 148\u001b[0;31m \u001b[0mlogits\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mlm_head\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# (B,T,vocab_size)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 149\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 150\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mtargets\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py\u001b[0m in \u001b[0;36m_wrapped_call_impl\u001b[0;34m(self, *args, **kwargs)\u001b[0m\n\u001b[1;32m 1516\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_compiled_call_impl\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# type: ignore[misc]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1517\u001b[0m \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1518\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_call_impl\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 1519\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1520\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0m_call_impl\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py\u001b[0m in \u001b[0;36m_call_impl\u001b[0;34m(self, *args, **kwargs)\u001b[0m\n\u001b[1;32m 1525\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0m_global_backward_pre_hooks\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0m_global_backward_hooks\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1526\u001b[0m or _global_forward_hooks or _global_forward_pre_hooks):\n\u001b[0;32m-> 1527\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mforward_call\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 1528\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1529\u001b[0m \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.10/dist-packages/torch/nn/modules/linear.py\u001b[0m in \u001b[0;36mforward\u001b[0;34m(self, input)\u001b[0m\n\u001b[1;32m 112\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 113\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mforward\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0minput\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0mTensor\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m->\u001b[0m \u001b[0mTensor\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 114\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mF\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mlinear\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0minput\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mweight\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mbias\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 115\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 116\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mextra_repr\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m->\u001b[0m \u001b[0mstr\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;31mOutOfMemoryError\u001b[0m: CUDA out of memory. Tried to allocate 26.21 GiB. GPU 0 has a total capacty of 15.77 GiB of which 13.89 GiB is free. Process 2283 has 1.88 GiB memory in use. Of the allocated memory 1.38 GiB is allocated by PyTorch, and 144.98 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting max_split_size_mb to avoid fragmentation. See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF"
]
}
],
"source": [
"import torch\n",
"import torch.nn as nn\n",
"from torch.nn import functional as F\n",
"\n",
"# hyperparameters\n",
"batch_size = 64 # independent sequences process in parallel\n",
"block_size = 1024 # maximum context length for predictions\n",
"max_iters = 10000\n",
"eval_interval = 1000\n",
"learning_rate = 3e-4\n",
"device = 'cuda' if torch.cuda.is_available() else 'cpu'\n",
"eval_iters = 200\n",
"n_embd = 512\n",
"n_head = 12\n",
"n_layer = 12\n",
"dropout = 0.2\n",
"norm_eps = 1e-05\n",
"# ------------\n",
"\n",
"torch.manual_seed(1400)\n",
"\n",
"# data loading\n",
"def get_batch(split):\n",
" # generate a small batch of data of inputs x and targets y\n",
" data = train_data if split == 'train' else val_data\n",
" ix = torch.randint(len(data) - block_size, (batch_size,))\n",
" x = torch.stack([data[i:i+block_size] for i in ix])\n",
" y = torch.stack([data[i+1:i+block_size+1] for i in ix])\n",
" x, y = x.to(device), y.to(device)\n",
" return x, y\n",
"\n",
"@torch.no_grad()\n",
"def estimate_loss():\n",
" out = {}\n",
" model.eval()\n",
" for split in ['train', 'val']:\n",
" losses = torch.zeros(eval_iters)\n",
" for k in range(eval_iters):\n",
" X, Y = get_batch(split)\n",
" logits, loss = model(X, Y)\n",
" losses[k] = loss.item()\n",
" out[split] = losses.mean()\n",
" model.train()\n",
" return out\n",
"\n",
"class Head(nn.Module):\n",
" \"\"\" one head of self-attention \"\"\"\n",
"\n",
" def __init__(self, head_size):\n",
" super().__init__()\n",
" self.key = nn.Linear(n_embd, head_size, bias=False)\n",
" self.query = nn.Linear(n_embd, head_size, bias=False)\n",
" self.value = nn.Linear(n_embd, head_size, bias=False)\n",
" self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size)))\n",
"\n",
" self.dropout = nn.Dropout(dropout)\n",
"\n",
" def forward(self, x):\n",
" # input of size (batch, time-step, channels)\n",
" # output of size (batch, time-step, head size)\n",
" B,T,C = x.shape\n",
" k = self.key(x) # (B,T,hs)\n",
" q = self.query(x) # (B,T,hs)\n",
" # compute attention scores (\"affinities\")\n",
" wei = q @ k.transpose(-2,-1) * k.shape[-1]**-0.5 # (B, T, hs) @ (B, hs, T) -> (B, T, T)\n",
" wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf')) # (B, T, T)\n",
" wei = F.softmax(wei, dim=-1) # (B, T, T)\n",
" wei = self.dropout(wei)\n",
" # perform the weighted aggregation of the values\n",
" v = self.value(x) # (B,T,hs)\n",
" out = wei @ v # (B, T, T) @ (B, T, hs) -> (B, T, hs)\n",
" return out\n",
"\n",
"class MultiHeadAttention(nn.Module):\n",
" \"\"\" multiple heads of self-attention in parallel \"\"\"\n",
"\n",
" def __init__(self, num_heads, head_size):\n",
" super().__init__()\n",
" self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])\n",
" self.proj = nn.Linear(head_size * num_heads, n_embd)\n",
" self.dropout = nn.Dropout(dropout)\n",
"\n",
" def forward(self, x):\n",
" out = torch.cat([h(x) for h in self.heads], dim=-1)\n",
" out = self.dropout(self.proj(out))\n",
" return out\n",
"\n",
"class FeedFoward(nn.Module):\n",
" \"\"\" a simple linear layer followed by a non-linearity \"\"\"\n",
"\n",
" def __init__(self, n_embd):\n",
" super().__init__()\n",
" self.net = nn.Sequential(\n",
" nn.Linear(n_embd, 4 * n_embd),\n",
" nn.ReLU(),\n",
" nn.Linear(4 * n_embd, n_embd),\n",
" nn.Dropout(dropout),\n",
" )\n",
"\n",
" def forward(self, x):\n",
" return self.net(x)\n",
"class Block(nn.Module):\n",
" \"\"\" Transformer block: communication followed by computation \"\"\"\n",
"\n",
" def __init__(self, n_embd, n_head):\n",
" # n_embd: embedding dimension, n_head: the number of heads we'd like\n",
" super().__init__()\n",
" head_size = n_embd // n_head\n",
" self.sa = MultiHeadAttention(n_head, head_size)\n",
" self.ffwd = FeedFoward(n_embd)\n",
" self.ln1 = nn.LayerNorm(n_embd, eps=norm_eps)\n",
" self.ln2 = nn.LayerNorm(n_embd, eps=norm_eps)\n",
"\n",
" def forward(self, x):\n",
" x = x + self.sa(self.ln1(x))\n",
" x = x + self.ffwd(self.ln2(x))\n",
" return x\n",
"\n",
"class GPTLanguageModel(nn.Module):\n",
"\n",
" def __init__(self):\n",
" super().__init__()\n",
" # each token directly reads off the logits for the next token from a lookup table\n",
" self.token_embedding_table = nn.Embedding(vocab_size, n_embd)\n",
" self.position_embedding_table = nn.Embedding(block_size, n_embd)\n",
" self.blocks = nn.Sequential(*[Block(n_embd, n_head=n_head) for _ in range(n_layer)])\n",
" self.ln_f = nn.LayerNorm(n_embd, eps=norm_eps) # final layer norm\n",
" self.lm_head = nn.Linear(n_embd, vocab_size)\n",
" self.apply(self._init_weights)\n",
"\n",
" def _init_weights(self, module):\n",
" if isinstance(module, nn.Linear):\n",
" torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)\n",
" if module.bias is not None:\n",
" torch.nn.init.zeros_(module.bias.data)\n",
" elif isinstance(module, nn.Embedding):\n",
" torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)\n",
"\n",
" def forward(self, idx, targets=None):\n",
" B, T = idx.shape\n",
"\n",
" # idx and targets are both (B,T) tensor of integers\n",
" tok_emb = self.token_embedding_table(idx) # (B,T,C)\n",
" pos_emb = self.position_embedding_table(torch.arange(T, device=device)) # (T,C)\n",
" x = tok_emb + pos_emb # (B,T,C)\n",
" x = self.blocks(x) # (B,T,C)\n",
" x = self.ln_f(x) # (B,T,C)\n",
" logits = self.lm_head(x) # (B,T,vocab_size)\n",
"\n",
" if targets is None:\n",
" loss = None\n",
" else:\n",
" B, T, C = logits.shape\n",
" logits = logits.view(B*T, C)\n",
" targets = targets.view(B*T)\n",
" loss = F.cross_entropy(logits, targets)\n",
"\n",
" return logits, loss\n",
"\n",
" def generate(self, idx, max_new_tokens):\n",
" # idx is (B, T) array of indices in the current context\n",
" for _ in range(max_new_tokens):\n",
" # crop idx to the last block_size tokens\n",
" idx_cond = idx[:, -block_size:]\n",
" # get the predictions\n",
" logits, loss = self(idx_cond)\n",
" # focus only on the last time step\n",
" logits = logits[:, -1, :] # becomes (B, C)\n",
" # apply softmax to get probabilities\n",
" probs = F.softmax(logits, dim=-1) # (B, C)\n",
" # sample from the distribution\n",
" idx_next = torch.multinomial(probs, num_samples=1) # (B, 1)\n",
" # append sampled index to the running sequence\n",
" idx = torch.cat((idx, idx_next), dim=1) # (B, T+1)\n",
" return idx\n",
"\n",
"model = GPTLanguageModel()\n",
"m = model.to(device)\n",
"# print the number of parameters in the model\n",
"n_param = sum(p.numel() for p in m.parameters())/1e6\n",
"print(n_param, 'million')\n",
"\n",
"# create a PyTorch optimizer\n",
"optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)\n",
"steps = []\n",
"train_losses = []\n",
"val_losses = []\n",
"\n",
"for iter in range(max_iters):\n",
"\n",
" # every once in a while evaluate the loss on train and val sets\n",
" if iter % eval_interval == 0 or iter == max_iters - 1:\n",
" losses = estimate_loss()\n",
" print(f\"step {iter}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f}\")\n",
"\n",
" # Store step and loss values for visualization\n",
" steps.append(iter)\n",
" train_losses.append(losses['train'])\n",
" val_losses.append(losses['val'])\n",
"\n",
" # sample a batch of data\n",
" xb, yb = get_batch('train')\n",
"\n",
" # evaluate the loss\n",
" logits, loss = model(xb, yb)\n",
" optimizer.zero_grad(set_to_none=True)\n",
" loss.backward()\n",
" optimizer.step()"
]
},
{
"cell_type": "code",
"source": [
"run_time = timeit.default_timer()\n",
"total_time = run_time - start_time"
],
"metadata": {
"id": "BdXl_pFb2RqL"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"input_from_user = \"people often lie about themselves but\"\n",
"token_input = encode(input_from_user)"
],
"metadata": {
"id": "79TNjWKC3Ut8"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# generate from the model\n",
"context = torch.tensor([token_input], dtype=torch.long, device=device)\n",
"generated_output = decode(m.generate(context, max_new_tokens=100)[0].tolist())"
],
"metadata": {
"id": "XSLsqXg03T3j"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"import matplotlib.pyplot as plt\n",
"\n",
"plt.figure(figsize=(10, 6))\n",
"plt.plot(steps, train_losses, label='Train Loss')\n",
"plt.plot(steps, val_losses, label='Validation Loss')\n",
"plt.title('Loss Over Steps')\n",
"plt.xlabel('Steps')\n",
"plt.ylabel('Loss')\n",
"plt.legend()\n",
"\n",
"plt.show()"
],
"metadata": {
"id": "vmjyuccN42pV"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# saving the model\n",
"torch.save(model.state_dict(), 'transformer_model.pth')"
],
"metadata": {
"id": "5bwKjvO_aBZ-"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"ffn_factor = 6\n",
"embedding_params = n_embd * vocab_size\n",
"attention_params = n_head * (n_embd // n_head * 2 * n_embd) * n_layer\n",
"\n",
"feedforward_params = n_embd * ffn_factor * n_layer * 2\n",
"total_params = embedding_params + attention_params + feedforward_params"
],
"metadata": {
"id": "60DleGHAgFcy"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# summary\n",
"print('//// Summary ////')\n",
"print(f\"total no of words in the file: {total_no_of_words / 1e6} million\")\n",
"print(f\"total predicted parameters: {total_params / 1e6} million\")\n",
"print(f\"actual no of parameters: {n_param} million\")\n",
"print(f\"total time taken to run the model was {total_time / 3600} hrs\")\n",
"print(f\"model ran for {max_iters} iterations and final val loss: {val_losses[-1]} and train loss: {train_losses[-1]}\")\n",
"print('\\n')\n",
"print(\"/// output ///\")\n",
"print(f\"I gave input text as: '{input_from_user}'\")\n",
"print(f\"generated output was {generated_output}\")"
],
"metadata": {
"id": "GWsCV-S72a1G"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"from google.colab import files\n",
"files.download('transformer_model.pth')"
],
"metadata": {
"id": "VfkCY1IPuege"
},
"execution_count": null,
"outputs": []
}
]
} |