{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4e0898c7-f05d-44b6-97b8-37693a9b2792",
   "metadata": {},
   "source": [
    "## Exercise 5.4\n",
    "After saving the weights, load the model and optimizer in a new Python session or Jupyter notebook file and continue pretraining it for one more epoch using the `train_model_simple` function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "037c2933-603c-45ef-9581-f3d5c79a17a3",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "357d6d56-b32a-438e-94d6-f400e2dfdfe9",
   "metadata": {},
   "outputs": [],
   "source": [
    "class LayerNorm(nn.Module):\n",
    "    def __init__(self, embed_dim):\n",
    "        super().__init__()\n",
    "        self.epsilon = 1e-5 # Prevents divide-by-zero errors.\n",
    "\n",
    "        # These trainable parameters allow the model to scale and\n",
    "        # shift this layers output beyond strict normalization if\n",
    "        # that improves model performance.\n",
    "        self.scale = nn.Parameter(torch.ones(embed_dim))\n",
    "        self.shift = nn.Parameter(torch.zeros(embed_dim))\n",
    "\n",
    "    def forward(self, X):\n",
    "        mean = X.mean(dim=-1, keepdim=True)\n",
    "\n",
    "        # We use a biased variance because in practice embedding\n",
    "        # dimensions are so large that the difference is negligible,\n",
    "        # plus this ensures compatibility with historical open-weight\n",
    "        # GPT models.\n",
    "        var = X.var(dim=-1, keepdim=True, unbiased=False)\n",
    "\n",
    "        normed_X = (X - mean) / torch.sqrt(var + self.epsilon)\n",
    "        normed_X = normed_X * self.scale + self.shift\n",
    "        return normed_X"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "745fb486-ec47-4854-8fd3-a28d9bb366f0",
   "metadata": {},
   "outputs": [],
   "source": [
    "class GELU(nn.Module):\n",
    "    def __init__(self):\n",
    "        super().__init__()\n",
    "\n",
    "    def forward(self, X):\n",
    "        sqrt_2_over_pi = torch.sqrt(torch.tensor(2 / torch.pi))\n",
    "        result = 0.5 * X * (1 + torch.tanh(sqrt_2_over_pi * (X + 0.044715 * torch.pow(X,3))))\n",
    "        return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "78cf4300-b2b7-43ca-8b0e-bed44d6b5986",
   "metadata": {},
   "outputs": [],
   "source": [
    "class FeedForward(nn.Module):\n",
    "    def __init__(self, cfg):\n",
    "        super().__init__()\n",
    "        embed_dim = cfg[\"emb_dim\"]\n",
    "        embed_dim_x4 = embed_dim * 4\n",
    "        self.layers = nn.Sequential(\n",
    "            nn.Linear(embed_dim, embed_dim_x4),\n",
    "            GELU(),\n",
    "            nn.Linear(embed_dim_x4, embed_dim)\n",
    "        )\n",
    "\n",
    "    def forward(self, X):\n",
    "        result = self.layers(X)\n",
    "        return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "28eb8060-9af3-4770-93b9-848665f35f0e",
   "metadata": {},
   "outputs": [],
   "source": [
    "class MultiHeadAttention(nn.Module):\n",
    "    def __init__(self, input_dim, output_dim, context_length, dropout_pct, num_heads, use_bias=False):\n",
    "        super().__init__()\n",
    "\n",
    "        assert output_dim % num_heads == 0, \"output_dim must be a multiple of num_heads\"\n",
    "        self.num_heads = num_heads\n",
    "        self.head_dim = output_dim // num_heads\n",
    "        self.output_dim = output_dim\n",
    "        \n",
    "        self.W_q = nn.Linear(input_dim, output_dim, bias=use_bias)\n",
    "        self.W_k = nn.Linear(input_dim, output_dim, bias=use_bias)\n",
    "        self.W_v = nn.Linear(input_dim, output_dim, bias=use_bias)\n",
    "        self.output_proj = nn.Linear(output_dim, output_dim)\n",
    "        \n",
    "        self.dropout = torch.nn.Dropout(dropout_pct)\n",
    "        ones = torch.ones(context_length, context_length)\n",
    "        self.register_buffer(\"mask\", torch.triu(ones, diagonal=1).bool())\n",
    "\n",
    "    def forward(self, batch):\n",
    "        num_samples, num_tokens, token_dim = batch.shape\n",
    "        queries = self.W_q(batch)\n",
    "        keys = self.W_k(batch)\n",
    "        values = self.W_v(batch)\n",
    "\n",
    "        queries = queries.view(num_samples, num_tokens, self.num_heads, self.head_dim).transpose(1, 2)\n",
    "        keys = keys.view(num_samples, num_tokens, self.num_heads, self.head_dim).transpose(1, 2)\n",
    "        values = values.view(num_samples, num_tokens, self.num_heads, self.head_dim).transpose(1, 2)\n",
    "        \n",
    "        attn_scores = queries @ keys.transpose(2, 3)\n",
    "        attn_scores.masked_fill_(self.mask[:num_tokens, :num_tokens], -torch.inf)\n",
    "        \n",
    "        attn_weights = torch.softmax(attn_scores / keys.shape[-1]**0.5, dim=-1)\n",
    "        attn_weights = self.dropout(attn_weights)\n",
    "        \n",
    "        context_vectors = attn_weights @ values\n",
    "        context_vectors = context_vectors.transpose(1, 2)\n",
    "        context_vectors = context_vectors.contiguous().view(num_samples, num_tokens, self.output_dim)\n",
    "        \n",
    "        output = self.output_proj(context_vectors)\n",
    "        return output"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "d1ce5685-c599-4dcf-9b08-1f38010bbd00",
   "metadata": {},
   "outputs": [],
   "source": [
    "class TransformerBlock(nn.Module):\n",
    "    def __init__(self, config):\n",
    "        super().__init__()\n",
    "        self.attention = MultiHeadAttention(\n",
    "            input_dim      = config[\"emb_dim\"],\n",
    "            output_dim     = config[\"emb_dim\"],\n",
    "            context_length = config[\"context_length\"],\n",
    "            num_heads      = config[\"n_heads\"],\n",
    "            dropout_pct    = config[\"drop_rate\"],\n",
    "            use_bias       = config[\"qkv_bias\"]\n",
    "        )\n",
    "        self.feed_forward = FeedForward(config)\n",
    "        self.norm1 = LayerNorm(config[\"emb_dim\"])\n",
    "        self.norm2 = LayerNorm(config[\"emb_dim\"])\n",
    "        self.dropout = nn.Dropout(config[\"drop_rate\"])\n",
    "\n",
    "    def forward(self, batch):\n",
    "        shortcut = batch\n",
    "        output = self.norm1(batch)\n",
    "        output = self.attention(output)\n",
    "        output = self.dropout(output)\n",
    "        output = output + shortcut\n",
    "\n",
    "        shortcut = output\n",
    "        output = self.norm2(output)\n",
    "        output = self.feed_forward(output)\n",
    "        output = self.dropout(output)\n",
    "        output = output + shortcut\n",
    "\n",
    "        return output"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "686dd8ce-bffd-4540-aa99-0898a9438c19",
   "metadata": {},
   "outputs": [],
   "source": [
    "class GPTModel(nn.Module):\n",
    "    def __init__(self, cfg):\n",
    "        super().__init__()\n",
    "        self.tok_emb = nn.Embedding(cfg[\"vocab_size\"], cfg[\"emb_dim\"])\n",
    "        self.pos_emb = nn.Embedding(cfg[\"context_length\"], cfg[\"emb_dim\"])\n",
    "        self.dropout = nn.Dropout(cfg[\"drop_rate\"])\n",
    "        self.xform_blocks = nn.Sequential(\n",
    "            *[TransformerBlock(cfg) for _ in range(cfg[\"n_layers\"])]\n",
    "        )\n",
    "        self.final_norm = LayerNorm(cfg[\"emb_dim\"])\n",
    "        self.out_head = nn.Linear(cfg[\"emb_dim\"], cfg[\"vocab_size\"], bias = False)\n",
    "\n",
    "    def forward(self, input_tokens):\n",
    "        batch_size, num_tokens = input_tokens.shape\n",
    "\n",
    "        token_embeds = self.tok_emb(input_tokens)\n",
    "        pos_embeds = self.pos_emb(torch.arange(num_tokens, device=input_tokens.device))\n",
    "        X = token_embeds + pos_embeds\n",
    "        X = self.dropout(X)\n",
    "        X = self.xform_blocks(X)\n",
    "        X = self.final_norm(X)\n",
    "\n",
    "        logits = self.out_head(X)\n",
    "        return logits"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "96677988-0e56-45e4-adb3-23bb03823e55",
   "metadata": {},
   "outputs": [],
   "source": [
    "GPT_CONFIG_124M = {\n",
    "    \"vocab_size\": 50257,\n",
    "    \"context_length\": 256, # Reduced for training ease on local hardware.\n",
    "    \"emb_dim\": 768,\n",
    "    \"n_heads\": 12,\n",
    "    \"n_layers\": 12, \n",
    "    \"drop_rate\": 0.1,\n",
    "    \"qkv_bias\": False\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "26bc7bfd-2e55-4b35-8474-538f59a2acea",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Data set and data loader from chapter 2.\n",
    "from torch.utils.data import Dataset, DataLoader\n",
    "\n",
    "class GPTDatasetV1(Dataset):\n",
    "    def __init__(self, txt, tokenizer, max_length, stride):\n",
    "        self.input_samples = []\n",
    "        self.target_samples = []\n",
    "\n",
    "        tokens = tokenizer.encode(txt)\n",
    "        num_tokens = len(tokens)\n",
    "        max_length_plus = max_length + 1\n",
    "        assert max_length_plus <= num_tokens, \"Need at least one more token than max length.\"\n",
    "        \n",
    "        self.num_samples = 0\n",
    "        idx = 0\n",
    "        while idx + max_length_plus <= num_tokens:\n",
    "        #for i in range(0, num_tokens - max_length, stride):\n",
    "            #j = i + 1\n",
    "            #input_sample = tokens[i:i+max_length]\n",
    "            #target_sample = tokens[j:j+max_length]\n",
    "            input_sample = tokens[idx:idx+max_length]\n",
    "            jdx = idx + 1\n",
    "            target_sample = tokens[jdx:jdx+max_length]\n",
    "            self.input_samples.append(torch.tensor(input_sample))\n",
    "            self.target_samples.append(torch.tensor(target_sample))\n",
    "            self.num_samples += 1\n",
    "            idx += stride\n",
    "\n",
    "    def __len__(self):\n",
    "        return self.num_samples\n",
    "\n",
    "    def __getitem__(self, idx):\n",
    "        return self.input_samples[idx], self.target_samples[idx]\n",
    "\n",
    "def create_dataloader_v1(txt, batch_size=4, max_length=256,\n",
    "                         stride=128, shuffle=True, drop_last=True,\n",
    "                         num_workers=0):\n",
    "    tokenizer = tiktoken.get_encoding(\"gpt2\")\n",
    "    dataset = GPTDatasetV1(txt, tokenizer, max_length, stride)\n",
    "    dataloader = DataLoader(\n",
    "        dataset=dataset,\n",
    "        batch_size=batch_size,\n",
    "        shuffle=shuffle,\n",
    "        drop_last=drop_last,\n",
    "        num_workers=num_workers\n",
    "    )\n",
    "\n",
    "    return dataloader"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "5294275f-3c4c-4099-93cf-6a731c34410c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "# chars: 20479\n",
      "# tokens: 5145\n",
      "Training data length: 18431\n",
      "Test data length: 2048\n"
     ]
    }
   ],
   "source": [
    "import tiktoken\n",
    "tokenizer_gpt2 = tiktoken.get_encoding(\"gpt2\")\n",
    "\n",
    "# Load the verdict.\n",
    "with open('the-verdict.txt', 'r', encoding='utf8') as f:\n",
    "  text_data = f.read()\n",
    "\n",
    "# Count characters and tokens.\n",
    "print(\"# chars:\", len(text_data))\n",
    "print(\"# tokens:\", len(tokenizer_gpt2.encode(text_data)))\n",
    "\n",
    "# Split data (not tokens) 90/10 into training and validation sets.\n",
    "split = len(text_data) * 9 // 10\n",
    "train_data = text_data[:split]\n",
    "val_data = text_data[split:]\n",
    "print(\"Training data length:\", len(train_data))\n",
    "print(\"Test data length:\", len(val_data))\n",
    "assert len(train_data) + len(val_data) == len(text_data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "081253c7-a65d-45e3-90ae-dd3f408f2218",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Use chapter 2 data loaders to create training and validation data loaders.\n",
    "# Training loader should drop last and shuffle, validation loader shouldn't.\n",
    "# Both should have a batch size of 2. Max length and stride length should be\n",
    "# equal and come from the config dict.\n",
    "\n",
    "train_loader = create_dataloader_v1(\n",
    "    train_data,\n",
    "    batch_size=2,\n",
    "    max_length=GPT_CONFIG_124M[\"context_length\"],\n",
    "    stride=GPT_CONFIG_124M[\"context_length\"],\n",
    "    shuffle=True,\n",
    "    drop_last=True,\n",
    "    num_workers=0,\n",
    ")\n",
    "\n",
    "val_loader = create_dataloader_v1(\n",
    "    val_data,\n",
    "    batch_size=2,\n",
    "    max_length=GPT_CONFIG_124M[\"context_length\"],\n",
    "    stride=GPT_CONFIG_124M[\"context_length\"],\n",
    "    shuffle=False,\n",
    "    drop_last=False,\n",
    "    num_workers=0,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "a52d4b03-df8c-4ac1-8649-4319b6e162a1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create a function to calculate the cross entropy loss, given an input batch, a target batch,\n",
    "# a model, and the device. We move the batches to the device first to allow for GPU training.\n",
    "def get_batch_loss(input_batch, target_batch, model, device):\n",
    "    # Note that these are not in-place operations!\n",
    "    input_batch = input_batch.to(device)\n",
    "    target_batch = target_batch.to(device)\n",
    "\n",
    "    logits = model(input_batch)\n",
    "    flat_logits = logits.flatten(0, 1)\n",
    "    flat_targets = target_batch.flatten(0, 1)\n",
    "\n",
    "    loss = torch.nn.functional.cross_entropy(flat_logits, flat_targets)\n",
    "    return loss"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "f6462e13-092b-4b13-8f38-3d624877154e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Use the previous function to calculate loss for all data in a loader, given a model, a device,\n",
    "# and an optional number of batches. If a batch number isn't provided, use all available batches\n",
    "# in the loader (if the loader is empty the result is `nan`), otherwise use whichever is less:\n",
    "# the available batches or the requested batches. The result is the average of loss across\n",
    "# all batches.\n",
    "def get_loader_loss(loader, model, device, num_batches=None):\n",
    "    if len(loader) == 0:\n",
    "        return float('nan')\n",
    "\n",
    "    if num_batches is None:\n",
    "        num_batches = len(loader)\n",
    "    else:\n",
    "        num_batches = min(num_batches, len(loader))\n",
    "\n",
    "    total_loss = 0\n",
    "    #for input_batch, target_batch in loader:\n",
    "    #    loss = get_batch_loss(input_batch, target_batch, model, device)\n",
    "    #    total_loss += loss\n",
    "    data_iter = iter(loader)\n",
    "    for _ in range(num_batches):\n",
    "        input_batch, target_batch = next(data_iter)\n",
    "        loss = get_batch_loss(input_batch, target_batch, model, device)\n",
    "        total_loss += loss\n",
    "\n",
    "    avg_loss = total_loss / num_batches\n",
    "    return avg_loss"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "362f7bbb-d6c0-4bd4-95a5-776f1c296c77",
   "metadata": {},
   "outputs": [],
   "source": [
    "# This is a helper function for testing purposes. It takes\n",
    "# some text and returns the tokens wrapped up within a\n",
    "# batch. This makes it easy to use little bits of test\n",
    "# text with functions that expect to receive a batch of\n",
    "# tokenized samples.\n",
    "def text_to_token_ids(text, tokenizer):\n",
    "    encoded = tokenizer.encode(text, allowed_special={'<|endoftext|>'})\n",
    "    \n",
    "    # unsqueeze() wraps the tokens in a batch.\n",
    "    encoded_tensor = torch.tensor(encoded).unsqueeze(0)\n",
    "    return encoded_tensor\n",
    "\n",
    "# This is the same id as the preceding function, just\n",
    "# in the other direction. It takes a batch of tokens\n",
    "# and returns a string.\n",
    "def token_ids_to_text(tokens, tokenizer):\n",
    "     # squeeze() removes the first dimension which represents the batch.\n",
    "    decoded_text = tokenizer.decode(tokens.squeeze(0).tolist())\n",
    "    return decoded_text"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "13760f7d-a18c-49f7-9641-cc603e070b1e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Returns the training loss and validation loss of the model using the\n",
    "# provided loaders and device. The evaluation iteration is a number\n",
    "# specifying how many batches to evaluate in each loader. Uses the model\n",
    "# in evaluation mode (so without things like dropout) for stability\n",
    "# and reproducibility.\n",
    "def evaluate_model(model, train_loader, val_loader, device, eval_iter):\n",
    "    model.eval()\n",
    "    with torch.no_grad():\n",
    "        train_loss = get_loader_loss(train_loader, model, device, eval_iter)\n",
    "        val_loss = get_loader_loss(val_loader, model, device, eval_iter)\n",
    "    model.train()\n",
    "    return train_loss, val_loss"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "5bf5cc4d-6fb9-4822-aba2-0632c474b47d",
   "metadata": {},
   "outputs": [],
   "source": [
    "def generate_text_simple(model, tokens, max_output_tokens, max_context_length):\n",
    "    for _ in range(max_output_tokens):\n",
    "        # Crop tokens to maximum context length and get logits.\n",
    "        tokens_context = tokens[:, -max_context_length:]\n",
    "        logits = model(tokens_context)\n",
    "\n",
    "        # Go from [batch_size, num_tokens, embed_dim] to [batch_size, embed_dim],\n",
    "        # only retaining the last token from each batch.\n",
    "        logits = logits[:, -1, :]\n",
    "\n",
    "        # Determine the next token and append it.\n",
    "        probas = torch.softmax(logits, dim=-1)\n",
    "        next_tokens = torch.argmax(probas, dim=-1, keepdim=True)\n",
    "        tokens = torch.cat([tokens, next_tokens], dim=-1)\n",
    "\n",
    "    return tokens"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "00e67799-f704-461f-809c-820d71d674fe",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Given a starting context, generates and prints sample output using the provided\n",
    "# model, tokenizer, and device. Temporarily disables dropout and gradient calculation\n",
    "# for stability and efficiency. Use the simple text generator, with the context size\n",
    "# being the max supported by the model (determined by the shape of the position embeddings\n",
    "# tensor). On print-out, newlines will be replaced with spaces for clarity.\n",
    "def generate_and_print_sample(model, tokenizer, device, start_context, max_output_tokens=50):\n",
    "    model.eval()\n",
    "    context_size = model.pos_emb.weight.shape[0]\n",
    "    tokens = text_to_token_ids(start_context, tokenizer)\n",
    "    tokens = tokens.to(device)\n",
    "    with torch.no_grad():\n",
    "        output_tokens = generate_text_simple(model, tokens, max_output_tokens, context_size)\n",
    "    model.train()\n",
    "    output_text = token_ids_to_text(output_tokens, tokenizer)\n",
    "    output_text = output_text.replace(\"\\n\", \" \")\n",
    "    print(output_text)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "ee26c982-d378-4155-951a-7ffdc9532be9",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Now we train the model. We will train the model for a specified number of epochs.\n",
    "# Each epoch sets the model to training mode, then iterates through the training\n",
    "# batches and does the typical loop: zero out the optimizer's gradient's, get the model's\n",
    "# loss on a forward pass, perform a backward pass, and update the model's weights by stepping\n",
    "# the optimizer. Based on the evaluation frequency, the model will also be evaluated\n",
    "# against the validation data, and progress will be printed out.\n",
    "def train_model_simple(model, train_loader, val_loader,\n",
    "                       optimizer, device, num_epochs,\n",
    "                       eval_freq, eval_iter, start_context, tokenizer):\n",
    "    train_losses, val_losses, tokens_seen = [], [], []\n",
    "    current_step = -1\n",
    "    num_tokens_seen = 0\n",
    "    \n",
    "    for epoch in range(num_epochs):\n",
    "        current_epoch = epoch + 1\n",
    "        model.train()\n",
    "        for input_batch, target_batch in train_loader:\n",
    "            optimizer.zero_grad()\n",
    "            loss = get_batch_loss(input_batch, target_batch, model, device)\n",
    "            loss.backward()\n",
    "            optimizer.step()\n",
    "            current_step += 1\n",
    "            num_tokens_seen += input_batch.numel()\n",
    "\n",
    "            if current_step % eval_freq == 0:\n",
    "                train_loss, val_loss = evaluate_model(model, train_loader, val_loader, device, eval_iter)\n",
    "                print(f\"Epoch {current_epoch:03}, Step {current_step:05}\\n\\tTraining loss: {train_loss}\\n\\tValidation loss: {val_loss}\\t\")\n",
    "                train_losses.append(train_loss)\n",
    "                val_losses.append(val_loss)\n",
    "                tokens_seen.append(num_tokens_seen)\n",
    "\n",
    "        # Print sample output once per epoch\n",
    "        print()\n",
    "        generate_and_print_sample(model, tokenizer, device, start_context)\n",
    "        print()\n",
    "\n",
    "    return train_losses, val_losses, tokens_seen"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "f0b855da-b6bb-4899-9bd7-89d8e30e5635",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model parameters: 162419712\n"
     ]
    }
   ],
   "source": [
    "# Load model and optimizer state.\n",
    "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
    "model_and_optimizer_state = torch.load(\"model_and_optimizer.pth\", map_location=device)\n",
    "model = GPTModel(GPT_CONFIG_124M)\n",
    "model.to(device)\n",
    "model.load_state_dict(model_and_optimizer_state[\"model_state_dict\"])\n",
    "optimizer = torch.optim.AdamW(model.parameters(), lr=0.0004, weight_decay=0.1)\n",
    "optimizer.load_state_dict(model_and_optimizer_state[\"optimizer_state_dict\"])\n",
    "model.train() # Get ready for additional training.\n",
    "print(\"Model parameters:\", sum([p.numel() for p in model.parameters()]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "27c4fa3b-48f0-469f-a760-5bfb0e877732",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 001, Step 00000\n",
      "\tTraining loss: 0.2516915798187256\n",
      "\tValidation loss: 6.532669544219971\t\n",
      "Epoch 001, Step 00005\n",
      "\tTraining loss: 0.25435277819633484\n",
      "\tValidation loss: 6.63294792175293\t\n",
      "\n",
      "Every effort moves you?\"     I glanced after him, and uncertain. Stroud so when she began to stammer something about her poverty. I remember getting off a prodigious phrase about the sketch of the donkey. \"There were days when I\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Now we can actually train our model! Note that this will produce slightly different\n",
    "# output than Raschka obtained if it runs on CUDA because of a different RNG stream.\n",
    "# NOTE: For this exercise, we train for just one more run.\n",
    "num_epochs=1\n",
    "eval_freq=5\n",
    "eval_iter=5\n",
    "start_context=\"Every effort moves you\"\n",
    "tokenizer = tiktoken.get_encoding(\"gpt2\")\n",
    "train_losses, val_losses, tokens_seen = train_model_simple(\n",
    "    model, train_loader, val_loader, optimizer, \n",
    "    device, num_epochs, eval_freq, eval_iter,\n",
    "    start_context, tokenizer\n",
    ")"
   ]
  }
 ],
 "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.14.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
