<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
    <title>David Oniani</title>
    <subtitle>David Oniani&#39;s Website</subtitle>
    <link rel="self" type="application/atom+xml" href="https://oniani.org/atom.xml"/>
    <link rel="alternate" type="text/html" href="https://oniani.org"/>
    <generator uri="https://www.getzola.org/">Zola</generator>
    <updated>2026-09-27T00:00:00+00:00</updated>
    <id>https://oniani.org/atom.xml</id>
    <entry xml:lang="en">
        <title>The Foundations of LLMs, Part II: Supervised Fine-Tuning</title>
        <published>2026-09-27T00:00:00+00:00</published>
        <updated>2026-09-27T00:00:00+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://oniani.org/blog/the-foundations-of-llms-supervised-fine-tuning/"/>
        <id>https://oniani.org/blog/the-foundations-of-llms-supervised-fine-tuning/</id>
        
        <content type="html" xml:base="https://oniani.org/blog/the-foundations-of-llms-supervised-fine-tuning/">&lt;p&gt;This is the second installment in the series, &lt;em&gt;The Foundations of LLMs&lt;/em&gt;. In the &lt;a href=&quot;/blog/the-foundations-of-llms-pretraining-and-midtraining/&quot;&gt;previous
article&lt;/a&gt;, we built and pretrained a small transformer from scratch
in &lt;a rel=&quot;external&quot; href=&quot;https://pytorch.org/&quot;&gt;PyTorch&lt;/a&gt;. Pretraining and midtraining teach a model how language works by having it
read large amounts of text and play a simple game: guess the next token. Formally, for a sequence of
tokens \((x_1, \dots, x_T)\) of length \(T\), a model parameterized by weights \(\theta\)
minimizes the negative log-likelihood of each target token \(x_t\) given all preceding context
tokens \(x_{\lt t} = (x_1, \dots, x_{t-1})\):&lt;/p&gt;
&lt;p&gt;$$\mathcal{L}_{\text{pretrain}}(\theta) = -\sum_{t=1}^T \log P_{\theta}(x_{t} \mid x_{\lt t})$$&lt;/p&gt;
&lt;p&gt;While this game teaches the model grammar, facts, and reasoning, the resulting base model is still
just a text completer, not an assistant. When you type a question, the model does not know that you
want an answer, so it simply guesses what words would most likely follow your sentence in a book or
on a webpage. If you give it a homework question, it might reply with three more homework questions,
because questions on the internet frequently appear inside numbered worksheets and exam banks.&lt;/p&gt;
&lt;h3 id=&quot;the-sft-objective&quot;&gt;&lt;a class=&quot;zola-anchor&quot; href=&quot;#the-sft-objective&quot; aria-label=&quot;Anchor link for: the-sft-objective&quot;&gt;The SFT Objective&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;To turn this text completer into a helpful assistant, we use &lt;a rel=&quot;external&quot; href=&quot;https://arxiv.org/abs/2203.02155&quot;&gt;Supervised Fine-Tuning
(SFT)&lt;/a&gt;, also known as instruction tuning. In SFT, we train the model on curated
examples of a user asking a question (the prompt) and an assistant giving a helpful answer (the
response). The training objective looks almost identical to pretraining, with one critical change to
which token positions are summed:&lt;/p&gt;
&lt;p&gt;$$\mathcal{L}_{\text{SFT}}(\theta) = -\sum_{t \in \mathcal{T}_{\text{response}}} \log P_{\theta}(x_{t} \mid x_{\lt t})$$&lt;/p&gt;
&lt;p&gt;Here, \(\mathcal{T}_{\text{response}} \subset {1, \dots, T}\) is the subset of target token
positions that belong to the assistant&#39;s reply (including its closing end-of-turn marker). During
SFT, we only grade the model on the assistant&#39;s answer tokens and ignore its guesses on the user&#39;s
question so the model spends all of its capacity learning how to answer rather than imitating noisy
user prompts. Unlike the causal attention mask in Part I (which hides future tokens during the
forward pass), loss masking happens only at the end when scoring the output: the model still reads
and attends to the entire user question via \(x_{\lt t}\), but gradients are computed only on the
reply.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Completion vs. Instruction Following.&lt;/strong&gt; Because a base model is trained to continue arbitrary
documents, it treats a question as the start of a worksheet or article rather than a request to
fulfill. Conditioning the model on a dedicated assistant turn that is graded strictly on direct
answers shifts its behavior from document continuation to instruction following:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Answering a Question&lt;/strong&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Input:&lt;/strong&gt; &lt;code&gt;&quot;Why is the ocean salty?&quot;&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Pretrained Model:&lt;/strong&gt; &lt;code&gt;&quot;Why is the sky blue? Why do volcanoes erupt?&quot;&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;SFT Model:&lt;/strong&gt; &lt;code&gt;&quot;Rainwater erodes rocks and washes dissolved minerals into the ocean.&quot;&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Following an Instruction&lt;/strong&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Input:&lt;/strong&gt; &lt;code&gt;&quot;Write a Python function to reverse a string.&quot;&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Pretrained Model:&lt;/strong&gt; &lt;code&gt;&quot;...without using built-in methods. Problem 2: Write a function...&quot;&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;SFT Model:&lt;/strong&gt; &lt;code&gt;&quot;def reverse(s: str) -&amp;gt; str: return s[::-1]&quot;&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;
&lt;h3 id=&quot;chat-templates-and-sft-tensors&quot;&gt;&lt;a class=&quot;zola-anchor&quot; href=&quot;#chat-templates-and-sft-tensors&quot; aria-label=&quot;Anchor link for: chat-templates-and-sft-tensors&quot;&gt;Chat Templates and SFT Tensors&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;During pretraining, the model reads one long, unbroken stream of text. To have a back-and-forth
conversation, the model needs clear delimiters showing who is speaking and when each turn ends, a
structure called a &lt;strong&gt;chat template&lt;/strong&gt;. Production models with subword tokenizers reserve dedicated
special token IDs like &lt;code&gt;&quot;&amp;lt;|im_start|&amp;gt;user&quot;&lt;/code&gt;, &lt;code&gt;&quot;&amp;lt;|im_start|&amp;gt;assistant&quot;&lt;/code&gt;, and &lt;code&gt;&quot;&amp;lt;|im_end|&amp;gt;&quot;&lt;/code&gt; that the
tokenizer refuses to produce from raw user input, preventing a user from spoofing a turn boundary by
typing &lt;code&gt;&quot;Assistant:&quot;&lt;/code&gt; inside their prompt. In our character-level transformer from Part I, we format
each turn using plain text labels made of characters already in our vocabulary:
&lt;code&gt;&quot;\nUser: {prompt}\nAssistant: {response}\n&quot;&lt;/code&gt;. Here, &lt;code&gt;&quot;\nUser: &quot;&lt;/code&gt; marks the start of the human query,
&lt;code&gt;&quot;\nAssistant: &quot;&lt;/code&gt; signals that it is the model&#39;s turn to reply, and the closing newline &lt;code&gt;&quot;\n&quot;&lt;/code&gt; acts
as our end-of-turn marker.&lt;/p&gt;
&lt;p&gt;Recall from Part I that &lt;code&gt;Transformer.forward&lt;/code&gt; computes training loss using PyTorch&#39;s
&lt;a rel=&quot;external&quot; href=&quot;https://docs.pytorch.org/docs/stable/generated/torch.nn.functional.cross_entropy.html&quot;&gt;&lt;code&gt;F.cross_entropy&lt;/code&gt;&lt;/a&gt; via &lt;code&gt;F.cross_entropy(logits.view(B * T, -1), targets.view(-1))&lt;/code&gt;.
By default, &lt;code&gt;F.cross_entropy&lt;/code&gt; sets &lt;code&gt;ignore_index=-100&lt;/code&gt; and &lt;code&gt;reduction=&quot;mean&quot;&lt;/code&gt;: whenever a target
position equals &lt;code&gt;-100&lt;/code&gt;, PyTorch excludes that position from both the forward sum and the denominator,
dividing the total loss only by the number of unmasked response tokens
\(\lvert \mathcal{T}_{\text{response}} \rvert\) rather than \(B \times T\). Normalizing by
\(\lvert \mathcal{T}_{\text{response}} \rvert\) ensures that a long user prompt never dilutes the
gradient magnitude on a short assistant answer. To build a training example, we create an input
sequence &lt;code&gt;token_ids&lt;/code&gt; and a target sequence &lt;code&gt;targets&lt;/code&gt; shifted forward by one character, and set every
prompt target to &lt;code&gt;-100&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #E1E4E8; background-color: #24292E;&quot; &gt;&lt;code data-lang=&quot;python&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 1&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;def&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt; create_sft_tensors&lt;/span&gt;&lt;span&gt;(&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 2&lt;/span&gt;&lt;span&gt;    prompt:&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; str&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 3&lt;/span&gt;&lt;span&gt;    response:&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; str&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 4&lt;/span&gt;&lt;span&gt;    tokenizer: CharacterLevelTokenizer,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 5&lt;/span&gt;&lt;span&gt;    device: torch.device,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 6&lt;/span&gt;&lt;span&gt;) -&amp;gt;&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; tuple&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 7&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;    &amp;quot;&amp;quot;&amp;quot;Prepares aligned input and target tensors for Supervised Fine-Tuning.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 8&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 9&lt;/span&gt;&lt;span&gt;    formatted_prompt&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; = f&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;\n&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;User: &lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;{&lt;/span&gt;&lt;span&gt;prompt&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;}\n&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;Assistant: &amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;10&lt;/span&gt;&lt;span&gt;    full_text&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; = f&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;{&lt;/span&gt;&lt;span&gt;formatted_prompt&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;}{&lt;/span&gt;&lt;span&gt;response&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;}\n&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;11&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;12&lt;/span&gt;&lt;span&gt;    prompt_token_ids&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; tokenizer.encode(formatted_prompt)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;13&lt;/span&gt;&lt;span&gt;    full_token_ids&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; tokenizer.encode(full_text)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;14&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;15&lt;/span&gt;&lt;span&gt;    token_ids&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; torch.tensor(full_token_ids[:&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;-&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span&gt;],&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; device&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span&gt;device).reshape(&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; -&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;  # Input sequence&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;16&lt;/span&gt;&lt;span&gt;    targets&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; torch.tensor(full_token_ids[&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span&gt;:],&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; device&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span&gt;device).reshape(&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; -&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;     # Shifted by +1&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;17&lt;/span&gt;&lt;span&gt;    targets[:, :&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; len&lt;/span&gt;&lt;span&gt;(prompt_token_ids)&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; -&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 1&lt;/span&gt;&lt;span&gt;]&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; = -&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;100&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;                               # Mask prompt tokens&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;18&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;19&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;    return&lt;/span&gt;&lt;span&gt; token_ids, targets&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Let us verify both boundaries of this tensor slice. First, why do we mask up to
&lt;code&gt;len(prompt_token_ids) - 1&lt;/code&gt; instead of &lt;code&gt;len(prompt_token_ids)&lt;/code&gt;? Because &lt;code&gt;targets&lt;/code&gt; is shifted left by
one index (&lt;code&gt;full_token_ids[1:]&lt;/code&gt;), &lt;code&gt;targets[0, i]&lt;/code&gt; holds the character &lt;code&gt;full_token_ids[i + 1]&lt;/code&gt; that
&lt;code&gt;token_ids[0, i]&lt;/code&gt; must predict. At index &lt;code&gt;i = len(prompt_token_ids) - 1&lt;/code&gt;, &lt;code&gt;token_ids[0, i]&lt;/code&gt; is the
final character of &lt;code&gt;formatted_prompt&lt;/code&gt; (the trailing space in &lt;code&gt;&quot;\nAssistant: &quot;&lt;/code&gt;), and its target
&lt;code&gt;targets[0, i]&lt;/code&gt; is &lt;code&gt;full_token_ids[len(prompt_token_ids)]&lt;/code&gt;, which is the very first character of
&lt;code&gt;response&lt;/code&gt; and must therefore remain unmasked. Second, at the right boundary, &lt;code&gt;full_token_ids[:-1]&lt;/code&gt;
drops the closing newline &lt;code&gt;&quot;\n&quot;&lt;/code&gt; from &lt;code&gt;token_ids&lt;/code&gt; (since nothing is predicted after the turn ends),
while &lt;code&gt;full_token_ids[1:]&lt;/code&gt; keeps that closing &lt;code&gt;&quot;\n&quot;&lt;/code&gt; as the final unmasked target in &lt;code&gt;targets&lt;/code&gt; so
the model is explicitly graded on learning when to stop talking. This exact same rule extends to
multi-turn conversations by masking every user turn with &lt;code&gt;-100&lt;/code&gt; and leaving every assistant reply
unmasked.&lt;/p&gt;
&lt;h3 id=&quot;why-sft-works-with-so-little-data&quot;&gt;&lt;a class=&quot;zola-anchor&quot; href=&quot;#why-sft-works-with-so-little-data&quot; aria-label=&quot;Anchor link for: why-sft-works-with-so-little-data&quot;&gt;Why SFT Works with So Little Data&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;While pretraining processes trillions of tokens across thousands of GPU-hours to teach a model
language, world facts, and reasoning from random initialization, SFT can align that pretrained base
model into a conversational assistant using only a few thousand curated examples and a small
fraction of the compute budget. Two core dynamics explain this sample efficiency:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Teaching Manners, Not New Facts: As demonstrated in the &lt;a rel=&quot;external&quot; href=&quot;https://arxiv.org/abs/2305.11206&quot;&gt;LIMA (&lt;em&gt;Less Is More for Alignment&lt;/em&gt;)
paper&lt;/a&gt;, which fine-tuned a 65B-parameter base model on just 1,000 carefully curated
examples, a model acquires almost all of its factual knowledge during pretraining and midtraining
(the &lt;em&gt;Superficial Alignment Hypothesis&lt;/em&gt;). Pretraining is like spending years reading books in a
library, while SFT is a short lesson on how to answer questions politely, teaching the model how
to format and surface the knowledge it already has rather than memorizing new facts.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Gentle Weight Updates: In Part I, we paired &lt;code&gt;AdamW&lt;/code&gt; (&lt;code&gt;lr=3e-4&lt;/code&gt;) on 1D tensors with &lt;code&gt;Muon&lt;/code&gt;
(&lt;code&gt;lr=0.02&lt;/code&gt;) on 2D matrices so orthogonalized updates would move weights rapidly from random
initialization across all singular directions. In SFT, the weights already sit in a converged
pretrained basin, so large matrix-wide steps would cause catastrophic forgetting. We therefore
switch to a single &lt;a rel=&quot;external&quot; href=&quot;https://arxiv.org/abs/1711.05101&quot;&gt;&lt;code&gt;AdamW&lt;/code&gt;&lt;/a&gt; optimizer across all parameters at a much smaller learning
rate (&lt;code&gt;lr=5e-5&lt;/code&gt;), gently nudging the model&#39;s output style without erasing its pretrained features.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;preparing-the-frankenstein-dataset&quot;&gt;&lt;a class=&quot;zola-anchor&quot; href=&quot;#preparing-the-frankenstein-dataset&quot; aria-label=&quot;Anchor link for: preparing-the-frankenstein-dataset&quot;&gt;Preparing the &lt;em&gt;Frankenstein&lt;/em&gt; Dataset&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;Because SFT only formats knowledge the model already has, our training examples must match what our
Part I model read during pretraining: Mary Shelley&#39;s &lt;em&gt;Frankenstein&lt;/em&gt;. If we try to fine-tune that
tiny model on Python code or geography trivia, it will fail because those concepts do not exist in
its weights, and if a prompt contains any character absent from &lt;em&gt;Frankenstein&lt;/em&gt;,
&lt;code&gt;CharacterLevelTokenizer.encode&lt;/code&gt; will raise a &lt;code&gt;KeyError&lt;/code&gt;. In addition, because each formatted
question-and-answer turn in our dataset is 89 to 107 characters long, feeding it into Part I&#39;s
default &lt;code&gt;block_size=32&lt;/code&gt; model would immediately raise an &lt;code&gt;IndexError&lt;/code&gt; when indexing
&lt;code&gt;self.pos_emb_table(torch.arange(T))&lt;/code&gt; (and we cannot simply resize &lt;code&gt;pos_emb_table&lt;/code&gt; after pretraining
because rows &lt;code&gt;32&lt;/code&gt; through &lt;code&gt;127&lt;/code&gt; would contain untrained random noise). We therefore pretrain Part
I&#39;s &lt;code&gt;Config&lt;/code&gt; with &lt;code&gt;block_size=128&lt;/code&gt; and construct four in-domain question-and-answer pairs using
vocabulary drawn directly from Shelley&#39;s novel:&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #E1E4E8; background-color: #24292E;&quot; &gt;&lt;code data-lang=&quot;python&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 1&lt;/span&gt;&lt;span&gt;frankenstein_sft_data&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; [&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 2&lt;/span&gt;&lt;span&gt;    {&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 3&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;        &amp;quot;prompt&amp;quot;&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt; &amp;quot;Who created you?&amp;quot;&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 4&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;        &amp;quot;response&amp;quot;&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt; &amp;quot;Victor Frankenstein fashioned me in his laboratory.&amp;quot;&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 5&lt;/span&gt;&lt;span&gt;    },&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 6&lt;/span&gt;&lt;span&gt;    {&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 7&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;        &amp;quot;prompt&amp;quot;&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt; &amp;quot;Where were you brought to life?&amp;quot;&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 8&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;        &amp;quot;response&amp;quot;&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt; &amp;quot;In a solitary chamber at Ingolstadt, on a dreary night in November.&amp;quot;&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 9&lt;/span&gt;&lt;span&gt;    },&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;10&lt;/span&gt;&lt;span&gt;    {&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;11&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;        &amp;quot;prompt&amp;quot;&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt; &amp;quot;Why do you seek revenge?&amp;quot;&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;12&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;        &amp;quot;response&amp;quot;&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt; &amp;quot;Because mankind cast me out into solitude and misery.&amp;quot;&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;13&lt;/span&gt;&lt;span&gt;    },&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;14&lt;/span&gt;&lt;span&gt;    {&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;15&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;        &amp;quot;prompt&amp;quot;&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt; &amp;quot;What do you demand from your creator?&amp;quot;&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;16&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;        &amp;quot;response&amp;quot;&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt; &amp;quot;A companion of the same species to share my exile.&amp;quot;&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;17&lt;/span&gt;&lt;span&gt;    },&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;18&lt;/span&gt;&lt;span&gt;]&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;h3 id=&quot;the-training-loop&quot;&gt;&lt;a class=&quot;zola-anchor&quot; href=&quot;#the-training-loop&quot; aria-label=&quot;Anchor link for: the-training-loop&quot;&gt;The Training Loop&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;Because &lt;code&gt;create_sft_tensors&lt;/code&gt; already sets the prompt targets to &lt;code&gt;-100&lt;/code&gt;, we do not need to change a
single line of our &lt;code&gt;Transformer&lt;/code&gt; class from Part I. Notice that because each question-and-answer
pair has a different sequence length \(T\), we process one conversation at a time (&lt;code&gt;B = 1&lt;/code&gt;).
Batching multiple variable-length conversations together (&lt;code&gt;B &amp;gt; 1&lt;/code&gt;) in production pipelines requires
either right-padding shorter sequences (setting padded target positions to &lt;code&gt;-100&lt;/code&gt; and masking padded
positions in attention) or sequence packing (concatenating multiple conversations into a single
&lt;code&gt;block_size&lt;/code&gt; window with a block-diagonal attention mask so one conversation cannot attend to
another). Here, running 64 epochs over our 4 examples performs \(64 \times 4 = 256\) single-example
gradient steps (roughly 25,000 characters total, over 600 times less compute than Part I&#39;s
16.4-million-character pretraining run):&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #E1E4E8; background-color: #24292E;&quot; &gt;&lt;code data-lang=&quot;python&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 1&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;def&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt; train_sft&lt;/span&gt;&lt;span&gt;(&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 2&lt;/span&gt;&lt;span&gt;    model: Transformer,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 3&lt;/span&gt;&lt;span&gt;    dataset: list[dict[&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;str&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; str&lt;/span&gt;&lt;span&gt;]],&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 4&lt;/span&gt;&lt;span&gt;    tokenizer: CharacterLevelTokenizer,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 5&lt;/span&gt;&lt;span&gt;    optimizer: torch.optim.Optimizer,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 6&lt;/span&gt;&lt;span&gt;    device: torch.device,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 7&lt;/span&gt;&lt;span&gt;    epochs:&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; int&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 64&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 8&lt;/span&gt;&lt;span&gt;) -&amp;gt;&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; None&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 9&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;    &amp;quot;&amp;quot;&amp;quot;Fine-tunes the transformer on conversational instruction-response pairs.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;10&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;11&lt;/span&gt;&lt;span&gt;    model.train()&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;12&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;    for&lt;/span&gt;&lt;span&gt; epoch&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; in&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; range&lt;/span&gt;&lt;span&gt;(&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span&gt;, epochs&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; +&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 1&lt;/span&gt;&lt;span&gt;):&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;13&lt;/span&gt;&lt;span&gt;        total_loss&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 0.0&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;14&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;        for&lt;/span&gt;&lt;span&gt; item&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; in&lt;/span&gt;&lt;span&gt; dataset:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;15&lt;/span&gt;&lt;span&gt;            token_ids, targets&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; create_sft_tensors(item[&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;prompt&amp;quot;&lt;/span&gt;&lt;span&gt;], item[&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;response&amp;quot;&lt;/span&gt;&lt;span&gt;], tokenizer, device)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;16&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;17&lt;/span&gt;&lt;span&gt;            optimizer.zero_grad()&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;18&lt;/span&gt;&lt;span&gt;            _, loss&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; model(token_ids, targets)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;19&lt;/span&gt;&lt;span&gt;            loss.backward()&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;20&lt;/span&gt;&lt;span&gt;            optimizer.step()&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;21&lt;/span&gt;&lt;span&gt;            total_loss&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; +=&lt;/span&gt;&lt;span&gt; loss.item()&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;22&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;23&lt;/span&gt;&lt;span&gt;        avg_loss&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; total_loss&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; /&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; len&lt;/span&gt;&lt;span&gt;(dataset)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;24&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;        print&lt;/span&gt;&lt;span&gt;(&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;f&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;Epoch &lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;{&lt;/span&gt;&lt;span&gt;epoch&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;:2d&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;}&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;/&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;{&lt;/span&gt;&lt;span&gt;epochs&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;}&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt; | Average Loss: &lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;{&lt;/span&gt;&lt;span&gt;avg_loss&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;:.4f&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;}&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;25&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;26&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;# Assuming `model` (pretrained with `block_size=128`), `tokenizer`, and `device` are from Part I&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;27&lt;/span&gt;&lt;span&gt;optimizer&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; torch.optim.AdamW(model.parameters(),&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; lr&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;5e-5&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;28&lt;/span&gt;&lt;span&gt;train_sft(model, frankenstein_sft_data, tokenizer, optimizer, device)&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;h3 id=&quot;conversational-inference&quot;&gt;&lt;a class=&quot;zola-anchor&quot; href=&quot;#conversational-inference&quot; aria-label=&quot;Anchor link for: conversational-inference&quot;&gt;Conversational Inference&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;Once fine-tuning is finished, we can chat with our model using the &lt;code&gt;generate&lt;/code&gt; method from Part I.
To ask a question, we wrap the prompt in our template ending with &lt;code&gt;&quot;\nAssistant: &quot;&lt;/code&gt; and leave the
reply blank. Seeing &lt;code&gt;&quot;\nAssistant: &quot;&lt;/code&gt; cues the model to generate the assistant&#39;s answer, and we set
&lt;code&gt;max_new_token_ids=96&lt;/code&gt; so even our longest 67-character answer fits with room to spare. Because Part
I&#39;s minimal &lt;code&gt;generate&lt;/code&gt; loop always samples a fixed number of tokens without an early stop-token
check (whereas production inference engines pass an &lt;code&gt;eos_token_id&lt;/code&gt; to &lt;code&gt;break&lt;/code&gt; out of the loop as
soon as the end-of-turn token is sampled), the model will keep generating characters after emitting
its closing newline &lt;code&gt;&quot;\n&quot;&lt;/code&gt;, so we slice &lt;code&gt;.split(&quot;\n&quot;)[0]&lt;/code&gt; to return only the assistant&#39;s single
turn:&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #E1E4E8; background-color: #24292E;&quot; &gt;&lt;code data-lang=&quot;python&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 1&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;def&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt; ask_assistant&lt;/span&gt;&lt;span&gt;(&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 2&lt;/span&gt;&lt;span&gt;    prompt:&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; str&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 3&lt;/span&gt;&lt;span&gt;    model: Transformer,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 4&lt;/span&gt;&lt;span&gt;    tokenizer: CharacterLevelTokenizer,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 5&lt;/span&gt;&lt;span&gt;    device: torch.device,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 6&lt;/span&gt;&lt;span&gt;    max_new_token_ids:&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; int&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 96&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 7&lt;/span&gt;&lt;span&gt;) -&amp;gt;&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; str&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 8&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;    &amp;quot;&amp;quot;&amp;quot;Formats an evaluation prompt and generates an assistant response.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 9&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;10&lt;/span&gt;&lt;span&gt;    eval_prompt&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; = f&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;\n&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;User: &lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;{&lt;/span&gt;&lt;span&gt;prompt&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;}\n&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;Assistant: &amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;11&lt;/span&gt;&lt;span&gt;    token_ids&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; torch.tensor(tokenizer.encode(eval_prompt),&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; device&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span&gt;device).reshape(&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; -&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;12&lt;/span&gt;&lt;span&gt;    output&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; model.generate(token_ids,&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; max_new_token_ids&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span&gt;max_new_token_ids,&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; temperature&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;0.7&lt;/span&gt;&lt;span&gt;)[&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;0&lt;/span&gt;&lt;span&gt;]&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;13&lt;/span&gt;&lt;span&gt;    full_text&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; tokenizer.decode(output.tolist())&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;14&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;    return&lt;/span&gt;&lt;span&gt; full_text[&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;len&lt;/span&gt;&lt;span&gt;(eval_prompt) :].split(&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;\n&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;&lt;/span&gt;&lt;span&gt;)[&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;0&lt;/span&gt;&lt;span&gt;]&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;  # Stop at the closing newline&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;15&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;16&lt;/span&gt;&lt;span&gt;reply&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; ask_assistant(&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;Who created you?&amp;quot;&lt;/span&gt;&lt;span&gt;, model, tokenizer, device)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;17&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;print&lt;/span&gt;&lt;span&gt;(&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;f&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;Assistant: &lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;{&lt;/span&gt;&lt;span&gt;reply&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;}&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;On our 140K-parameter miniature model trained on 4 examples, querying one of the training prompts
recalls the target response (&lt;code&gt;&quot;Assistant: Victor Frankenstein fashioned me in his laboratory.&quot;&lt;/code&gt;),
while querying an unseen prompt produces the learned single-turn assistant format (terminating
cleanly at &lt;code&gt;&quot;\n&quot;&lt;/code&gt;) populated with blended &lt;em&gt;Frankenstein&lt;/em&gt; phrases, since a 140K character model lacks
the capacity to synthesize novel factual answers. On a frontier base model pretrained on trillions
of tokens, by contrast, fine-tuning on a small set of demonstrations generalizes the assistant
behavior to arbitrary unseen questions across any domain stored in the base weights.&lt;/p&gt;
&lt;h3 id=&quot;conclusion&quot;&gt;&lt;a class=&quot;zola-anchor&quot; href=&quot;#conclusion&quot; aria-label=&quot;Anchor link for: conclusion&quot;&gt;Conclusion&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;Supervised Fine-Tuning turns a raw next-token predictor into a helpful conversational assistant. By
wrapping text in clear &lt;code&gt;&quot;\nUser: &quot;&lt;/code&gt; and &lt;code&gt;&quot;\nAssistant: &quot;&lt;/code&gt; role markers and masking the user&#39;s
question from the loss function with &lt;code&gt;-100&lt;/code&gt;, we teach the model to answer questions directly without
changing a single line of our Part I transformer architecture. While our four-example &lt;em&gt;Frankenstein&lt;/em&gt;
dataset is a minimal demonstration, the exact same masked cross-entropy objective powers SFT across
frontier post-training pipelines. Still, SFT has a fundamental limitation: because it trains the
model via teacher forcing on positive reference answers only, it cannot show the model what &lt;em&gt;not&lt;/em&gt; to
say, penalize plausible-sounding hallucinations, or score the overall helpfulness and safety of a
complete response. To address this, frontier models follow SFT with preference alignment stages such
as &lt;a rel=&quot;external&quot; href=&quot;https://arxiv.org/abs/1909.08593&quot;&gt;Reinforcement Learning from Human Feedback (RLHF)&lt;/a&gt; (which trains a reward model on human
comparisons and optimizes the language model policy, meaning the probability distribution
\(P_{\theta}\) choosing each token action, via reinforcement learning) or &lt;a rel=&quot;external&quot; href=&quot;https://arxiv.org/abs/2305.18290&quot;&gt;Direct Preference
Optimization (DPO)&lt;/a&gt; (which directly increases the likelihood of preferred responses over
rejected responses in closed form).&lt;/p&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>The Foundations of LLMs, Part I: Pretraining and Midtraining</title>
        <published>2026-03-12T00:00:00+00:00</published>
        <updated>2026-03-12T00:00:00+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://oniani.org/blog/the-foundations-of-llms-pretraining-and-midtraining/"/>
        <id>https://oniani.org/blog/the-foundations-of-llms-pretraining-and-midtraining/</id>
        
        <content type="html" xml:base="https://oniani.org/blog/the-foundations-of-llms-pretraining-and-midtraining/">&lt;p&gt;I had been planning to make a &lt;a rel=&quot;external&quot; href=&quot;https://www.youtube.com/@davidoniani/videos&quot;&gt;YouTube video&lt;/a&gt; about this for quite some time. However, just as I
was preparing to release it, &lt;a rel=&quot;external&quot; href=&quot;https://www.youtube.com/watch?v=kCc8FmEb1nY&quot;&gt;Andrej Karpathy released an excellent video&lt;/a&gt; on the
topic, and it quickly went viral. After that, I decided to hold off on recording my version. I am
now turning the material into a written guide on the autoregressive transformer architecture, where
&lt;em&gt;autoregressive&lt;/em&gt; means that the model generates text one token at a time by feeding each new
prediction back into its own input to predict the next one. We will implement a GPT-like &lt;a rel=&quot;external&quot; href=&quot;https://en.wikipedia.org/wiki/Large_language_model&quot;&gt;Large
Language Model (LLM)&lt;/a&gt; from scratch in Python using &lt;a rel=&quot;external&quot; href=&quot;https://pytorch.org/&quot;&gt;PyTorch&lt;/a&gt; as the only dependency. I
assume basic familiarity with PyTorch, and for those new to it, &lt;a rel=&quot;external&quot; href=&quot;https://cs230.stanford.edu/blog/pytorch/&quot;&gt;Introduction to PyTorch Code
Examples from Stanford&lt;/a&gt; provides a helpful starting point before we build and train
our model end to end.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The complete code for the GPT-like autoregressive transformer implemented in this article is
available in this &lt;a rel=&quot;external&quot; href=&quot;https://gist.github.com/oniani/c15cc97b72fb479f05e7917fbce16823&quot;&gt;GitHub Gist&lt;/a&gt;. In 222 lines of self-contained Python, the script
automatically downloads Mary Shelley&#39;s &lt;em&gt;Frankenstein&lt;/em&gt;, builds a character-level tokenizer,
pretrains the transformer on a GPU or Apple Silicon chip, and samples new text from the trained
weights.&lt;/p&gt;
&lt;p&gt;Note that the model implemented and trained in this article, also referred to as the base model,
is a sentence completer rather than a chatbot. Converting it into a chatbot involves midtraining,
Supervised Fine-Tuning (SFT), and Reinforcement Learning (RL), which are beyond the scope of this
article. Still, a pretrained generative LLM is a powerful tool for sampling knowledge.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3 id=&quot;tokenization&quot;&gt;&lt;a class=&quot;zola-anchor&quot; href=&quot;#tokenization&quot; aria-label=&quot;Anchor link for: tokenization&quot;&gt;Tokenization&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;Given input text, our objective is to generate output text conditioned on that sequence. Neural
networks only operate on numbers, so in traditional transformer models, excluding &lt;a rel=&quot;external&quot; href=&quot;https://aclanthology.org/2025.acl-long.453/&quot;&gt;byte-latent
transformers&lt;/a&gt; that group raw UTF-8 bytes into dynamic patches without a fixed
vocabulary, the first stage is always &lt;a rel=&quot;external&quot; href=&quot;https://en.wikipedia.org/wiki/Large_language_model#Tokenization&quot;&gt;tokenization&lt;/a&gt;: converting a text string into a
sequence of integer IDs. This applies whether the architecture is encoder-only (such as
&lt;a rel=&quot;external&quot; href=&quot;https://arxiv.org/abs/1810.04805&quot;&gt;BERT&lt;/a&gt;, which reads an entire passage bidirectionally to classify or search text),
encoder-decoder (such as &lt;a rel=&quot;external&quot; href=&quot;https://jmlr.org/papers/v21/20-074.html&quot;&gt;T5&lt;/a&gt;, which encodes an input sequence and decodes a separate output
sequence for tasks like translation), or decoder-only (such as &lt;a rel=&quot;external&quot; href=&quot;https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf&quot;&gt;GPT-2&lt;/a&gt;, which predicts the
next token from left to right). The simplest method is character-level tokenization, where each
distinct character in the text corpus receives a unique integer ID:&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #E1E4E8; background-color: #24292E;&quot; &gt;&lt;code data-lang=&quot;python&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 1&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;import&lt;/span&gt;&lt;span&gt; string&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 2&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 3&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;class&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt; CharacterLevelTokenizer&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 4&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;    &amp;quot;&amp;quot;&amp;quot;A character-level tokenizer that treats individual characters as tokens.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 5&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 6&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;    def&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; __init__&lt;/span&gt;&lt;span&gt;(self, text:&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; str&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; string.printable) -&amp;gt;&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; None&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 7&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;        &amp;quot;&amp;quot;&amp;quot;Builds the vocabulary from the given text.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 8&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 9&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;        self&lt;/span&gt;&lt;span&gt;.vocab: list[&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;str&lt;/span&gt;&lt;span&gt;]&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; sorted&lt;/span&gt;&lt;span&gt;(&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;set&lt;/span&gt;&lt;span&gt;(text))&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;10&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;        self&lt;/span&gt;&lt;span&gt;.vocab_size:&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; int&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; len&lt;/span&gt;&lt;span&gt;(&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;self&lt;/span&gt;&lt;span&gt;.vocab)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;11&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;        self&lt;/span&gt;&lt;span&gt;.char_to_token: dict[&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;str&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; int&lt;/span&gt;&lt;span&gt;]&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; {char: idx&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; for&lt;/span&gt;&lt;span&gt; idx, char&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; in&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; enumerate&lt;/span&gt;&lt;span&gt;(&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;self&lt;/span&gt;&lt;span&gt;.vocab)}&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;12&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;13&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;    def&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt; encode&lt;/span&gt;&lt;span&gt;(self, text:&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; str&lt;/span&gt;&lt;span&gt;) -&amp;gt; list[&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;int&lt;/span&gt;&lt;span&gt;]:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;14&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;        &amp;quot;&amp;quot;&amp;quot;Converts a string into a list of token IDs.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;15&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;16&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;        return&lt;/span&gt;&lt;span&gt; [&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;self&lt;/span&gt;&lt;span&gt;.char_to_token[char]&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; for&lt;/span&gt;&lt;span&gt; char&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; in&lt;/span&gt;&lt;span&gt; text]&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;17&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;18&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;    def&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt; decode&lt;/span&gt;&lt;span&gt;(self, token_ids: list[&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;int&lt;/span&gt;&lt;span&gt;]) -&amp;gt;&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; str&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;19&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;        &amp;quot;&amp;quot;&amp;quot;Converts a list of token IDs back into a string.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;20&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;21&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;        return&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt; &amp;quot;&amp;quot;&lt;/span&gt;&lt;span&gt;.join(&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;self&lt;/span&gt;&lt;span&gt;.vocab[token_id]&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; for&lt;/span&gt;&lt;span&gt; token_id&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; in&lt;/span&gt;&lt;span&gt; token_ids)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;22&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;23&lt;/span&gt;&lt;span&gt;tokenizer&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; CharacterLevelTokenizer()&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;24&lt;/span&gt;&lt;span&gt;enc&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; tokenizer.encode(&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;robot&amp;quot;&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;    # -&amp;gt; [87, 84, 71, 84, 89]&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;25&lt;/span&gt;&lt;span&gt;dec&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; tokenizer.decode(enc)&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;        # -&amp;gt; &amp;quot;robot&amp;quot;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As shown above, &lt;code&gt;CharacterLevelTokenizer&lt;/code&gt; extracts the sorted set of unique characters from the
input text to build its vocabulary list &lt;code&gt;self.vocab&lt;/code&gt; of length &lt;code&gt;self.vocab_size&lt;/code&gt;. Calling &lt;code&gt;encode&lt;/code&gt;
looks up each character of &lt;code&gt;&quot;robot&quot;&lt;/code&gt; in &lt;code&gt;self.char_to_token&lt;/code&gt; to produce &lt;code&gt;[87, 84, 71, 84, 89]&lt;/code&gt;, and
calling &lt;code&gt;decode&lt;/code&gt; indexes back into &lt;code&gt;self.vocab&lt;/code&gt; to reconstruct &lt;code&gt;&quot;robot&quot;&lt;/code&gt; without losing information.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;While character-level tokenization keeps the vocabulary tiny and simple, production LLMs use
subword tokenizers so the model can read common words as single tokens rather than spelling every
word letter by letter. &lt;a rel=&quot;external&quot; href=&quot;https://en.wikipedia.org/wiki/Byte-pair_encoding&quot;&gt;Byte-Pair Encoding (BPE)&lt;/a&gt; starts with individual characters and
repeatedly merges the most frequent adjacent pair in the corpus (for example, merging &lt;code&gt;&quot;t&quot;&lt;/code&gt; and
&lt;code&gt;&quot;h&quot;&lt;/code&gt; into &lt;code&gt;&quot;th&quot;&lt;/code&gt;, and then &lt;code&gt;&quot;th&quot;&lt;/code&gt; and &lt;code&gt;&quot;e&quot;&lt;/code&gt; into &lt;code&gt;&quot;the&quot;&lt;/code&gt;), whereas &lt;a rel=&quot;external&quot; href=&quot;https://github.com/google-research/bert#tokenization&quot;&gt;WordPiece&lt;/a&gt; merges
pairs that maximize the likelihood of the training corpus under a unigram language model. In this
article, we use &lt;code&gt;CharacterLevelTokenizer&lt;/code&gt; so the entire pipeline runs with zero external libraries.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3 id=&quot;architecture&quot;&gt;&lt;a class=&quot;zola-anchor&quot; href=&quot;#architecture&quot; aria-label=&quot;Anchor link for: architecture&quot;&gt;Architecture&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;Before examining attention and feed-forward layers in isolation, let us inspect the top-level
&lt;code&gt;Config&lt;/code&gt; dataclass and &lt;code&gt;Transformer&lt;/code&gt; module. The &lt;code&gt;Config&lt;/code&gt; object stores seven hyperparameters:
&lt;code&gt;vocab_size&lt;/code&gt; (number of unique tokens), &lt;code&gt;block_size&lt;/code&gt; (maximum sequence length \(T\) the model can
read at once), &lt;code&gt;n_layer&lt;/code&gt; (number of stacked transformer blocks), &lt;code&gt;n_head&lt;/code&gt; (number of parallel
attention heads per block), &lt;code&gt;n_embd&lt;/code&gt; (width of each token&#39;s feature vector), &lt;code&gt;dropout&lt;/code&gt; (the
probability \(p\) of randomly zeroing neuron outputs during training so the network does not
memorize fixed pathways), and &lt;code&gt;bias&lt;/code&gt; (whether linear and normalization layers add a learnable offset
vector \(\mathbf{b}\) in \(\mathbf{y} = \mathbf{x}W^\top + \mathbf{b}\), which modern LLMs
disable to save memory and improve stability):&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #E1E4E8; background-color: #24292E;&quot; &gt;&lt;code data-lang=&quot;python&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 1&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;from&lt;/span&gt;&lt;span&gt; dataclasses&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; import&lt;/span&gt;&lt;span&gt; dataclass&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 2&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;import&lt;/span&gt;&lt;span&gt; torch&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 3&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;import&lt;/span&gt;&lt;span&gt; torch.nn&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; as&lt;/span&gt;&lt;span&gt; nn&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 4&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;import&lt;/span&gt;&lt;span&gt; torch.nn.functional&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; as&lt;/span&gt;&lt;span&gt; F&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 5&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 6&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt;@dataclass&lt;/span&gt;&lt;span&gt;(&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt;frozen&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;True&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;  # We like our dataclasses frozen!&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 7&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;class&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt; Config&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 8&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;    &amp;quot;&amp;quot;&amp;quot;Transformer config.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 9&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;10&lt;/span&gt;&lt;span&gt;    vocab_size:&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; int&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;  # Tokenizer vocabulary size&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;11&lt;/span&gt;&lt;span&gt;    block_size:&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; int&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;  # Max sequence length (context window)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;12&lt;/span&gt;&lt;span&gt;    n_layer:&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; int&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;     # Number of transformer layers&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;13&lt;/span&gt;&lt;span&gt;    n_head:&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; int&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;      # Attention heads per layer&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;14&lt;/span&gt;&lt;span&gt;    n_embd:&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; int&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;      # Embedding dimension (must be divisible by `n_head`)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;15&lt;/span&gt;&lt;span&gt;    dropout:&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; float&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;   # Dropout probability&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;16&lt;/span&gt;&lt;span&gt;    bias:&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; bool&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;       # Whether `nn.Linear` and `nn.LayerNorm` use bias&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;17&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;18&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt;    @&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;property&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;19&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;    def&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt; head_size&lt;/span&gt;&lt;span&gt;(self) -&amp;gt;&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; int&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;20&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;        &amp;quot;&amp;quot;&amp;quot;Returns the per-head dimension (embedding is split evenly across attention heads).&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;21&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;22&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;        return&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; self&lt;/span&gt;&lt;span&gt;.n_embd&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; //&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; self&lt;/span&gt;&lt;span&gt;.n_head&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;23&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;24&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;class&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt; Transformer&lt;/span&gt;&lt;span&gt;(&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt;nn&lt;/span&gt;&lt;span&gt;.&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt;Module&lt;/span&gt;&lt;span&gt;):&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;25&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;    &amp;quot;&amp;quot;&amp;quot;Autoregressive transformer language model.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;26&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;27&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;    def&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; __init__&lt;/span&gt;&lt;span&gt;(self, cfg: Config) -&amp;gt;&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; None&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;28&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;        &amp;quot;&amp;quot;&amp;quot;Initializes the building blocks of the transformer.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;29&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;30&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;        super&lt;/span&gt;&lt;span&gt;().&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;__init__&lt;/span&gt;&lt;span&gt;()&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;31&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;        self&lt;/span&gt;&lt;span&gt;.block_size&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; cfg.block_size&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;32&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;33&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;        self&lt;/span&gt;&lt;span&gt;.tok_emb_table&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; nn.Embedding(cfg.vocab_size, cfg.n_embd)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;34&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;        self&lt;/span&gt;&lt;span&gt;.pos_emb_table&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; nn.Embedding(cfg.block_size, cfg.n_embd)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;35&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;36&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;        self&lt;/span&gt;&lt;span&gt;.blocks&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; nn.Sequential(&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;*&lt;/span&gt;&lt;span&gt;[Block(cfg)&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; for&lt;/span&gt;&lt;span&gt; _&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; in&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; range&lt;/span&gt;&lt;span&gt;(cfg.n_layer)])&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;37&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;        self&lt;/span&gt;&lt;span&gt;.ln&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; nn.LayerNorm(cfg.n_embd,&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; bias&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span&gt;cfg.bias)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;38&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;        self&lt;/span&gt;&lt;span&gt;.proj&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; nn.Linear(cfg.n_embd, cfg.vocab_size)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;39&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;40&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;        # Weight tying: reduces the total number of parameters without degrading accuracy&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;41&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;        # Reference: https://arxiv.org/abs/1608.05859&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;42&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;        self&lt;/span&gt;&lt;span&gt;.proj.weight&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; self&lt;/span&gt;&lt;span&gt;.tok_emb_table.weight&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;43&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;44&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;    def&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt; forward&lt;/span&gt;&lt;span&gt;(self, token_ids: torch.Tensor, targets: torch.Tensor&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; |&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; None&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; None&lt;/span&gt;&lt;span&gt;) -&amp;gt;&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; tuple&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;45&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;        &amp;quot;&amp;quot;&amp;quot;Computes logits and optional loss.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;46&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;47&lt;/span&gt;&lt;span&gt;        B, T&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; token_ids.shape&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;48&lt;/span&gt;&lt;span&gt;        tok_emb&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; self&lt;/span&gt;&lt;span&gt;.tok_emb_table(token_ids)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;49&lt;/span&gt;&lt;span&gt;        pos_emb&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; self&lt;/span&gt;&lt;span&gt;.pos_emb_table(torch.arange(T,&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; device&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span&gt;token_ids.device))&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;50&lt;/span&gt;&lt;span&gt;        emb&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; tok_emb&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; +&lt;/span&gt;&lt;span&gt; pos_emb&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;51&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;52&lt;/span&gt;&lt;span&gt;        out&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; self&lt;/span&gt;&lt;span&gt;.ln(&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;self&lt;/span&gt;&lt;span&gt;.blocks(emb))&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;53&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;        if&lt;/span&gt;&lt;span&gt; targets&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; is&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; None&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;54&lt;/span&gt;&lt;span&gt;            logits&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; self&lt;/span&gt;&lt;span&gt;.proj(out[:, [&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;-&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span&gt;], :])&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;  # Last-token projection with time dimension&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;55&lt;/span&gt;&lt;span&gt;            loss&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; None&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;56&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;        else&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;57&lt;/span&gt;&lt;span&gt;            logits&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; self&lt;/span&gt;&lt;span&gt;.proj(out)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;58&lt;/span&gt;&lt;span&gt;            loss&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; F.cross_entropy(logits.view(B&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; *&lt;/span&gt;&lt;span&gt; T,&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; -&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span&gt;), targets.view(&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;-&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span&gt;))&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;59&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;60&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;        return&lt;/span&gt;&lt;span&gt; logits, loss&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;61&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;62&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt;    @torch.no_grad&lt;/span&gt;&lt;span&gt;()&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;63&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;    def&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt; generate&lt;/span&gt;&lt;span&gt;(&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;64&lt;/span&gt;&lt;span&gt;        self,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;65&lt;/span&gt;&lt;span&gt;        token_ids: torch.Tensor,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;66&lt;/span&gt;&lt;span&gt;        max_new_token_ids:&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; int&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;67&lt;/span&gt;&lt;span&gt;        temperature:&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; float&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 0.7&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;68&lt;/span&gt;&lt;span&gt;        top_k:&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; int&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; |&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; None&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; None&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;69&lt;/span&gt;&lt;span&gt;    ) -&amp;gt; torch.Tensor:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;70&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;        &amp;quot;&amp;quot;&amp;quot;Generates token IDs autoregressively.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;71&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;72&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;        self&lt;/span&gt;&lt;span&gt;.eval()&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;73&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;        for&lt;/span&gt;&lt;span&gt; _&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; in&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; range&lt;/span&gt;&lt;span&gt;(max_new_token_ids):&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;74&lt;/span&gt;&lt;span&gt;            logits, _&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; self&lt;/span&gt;&lt;span&gt;(token_ids[:,&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; -&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;self&lt;/span&gt;&lt;span&gt;.block_size :])&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;75&lt;/span&gt;&lt;span&gt;            logits&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; logits[:,&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; -&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span&gt;, :]&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; /&lt;/span&gt;&lt;span&gt; temperature&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;76&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;77&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;            if&lt;/span&gt;&lt;span&gt; top_k&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; is not&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; None&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;78&lt;/span&gt;&lt;span&gt;                k&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; min&lt;/span&gt;&lt;span&gt;(top_k, logits.size(&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;-&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span&gt;))&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;79&lt;/span&gt;&lt;span&gt;                threshold&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; torch.topk(logits, k).values[:, [&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;-&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span&gt;]]&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;80&lt;/span&gt;&lt;span&gt;                logits[logits&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; &amp;lt;&lt;/span&gt;&lt;span&gt; threshold]&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; = -&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;float&lt;/span&gt;&lt;span&gt;(&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;inf&amp;quot;&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;81&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;82&lt;/span&gt;&lt;span&gt;            probs&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; torch.softmax(logits,&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; dim&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=-&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;83&lt;/span&gt;&lt;span&gt;            next_token&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; torch.multinomial(probs,&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; num_samples&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;84&lt;/span&gt;&lt;span&gt;            token_ids&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; torch.cat((token_ids, next_token),&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; dim&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;85&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;        return&lt;/span&gt;&lt;span&gt; token_ids&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Let us trace &lt;code&gt;forward&lt;/code&gt; step by step. Its input &lt;code&gt;token_ids&lt;/code&gt; is a 2D integer tensor of shape &lt;code&gt;(B, T)&lt;/code&gt;,
where &lt;code&gt;B&lt;/code&gt; is the &lt;strong&gt;batch size&lt;/strong&gt; (how many independent text sequences we process in parallel) and &lt;code&gt;T&lt;/code&gt;
is the &lt;strong&gt;sequence length&lt;/strong&gt; (how many token positions are in each sequence, up to &lt;code&gt;block_size&lt;/code&gt;).
Looking up &lt;code&gt;token_ids&lt;/code&gt; in &lt;code&gt;self.tok_emb_table&lt;/code&gt; produces &lt;code&gt;tok_emb&lt;/code&gt; of shape &lt;code&gt;(B, T, n_embd)&lt;/code&gt;, which
assigns each token ID a learnable vector representing its identity. Because token embeddings alone
do not record word order, &lt;code&gt;self.pos_emb_table&lt;/code&gt; maps the position indices &lt;code&gt;0, 1, ..., T - 1&lt;/code&gt; (created
by &lt;code&gt;torch.arange(T, device=token_ids.device)&lt;/code&gt;) into a positional tensor &lt;code&gt;pos_emb&lt;/code&gt; of shape
&lt;code&gt;(T, n_embd)&lt;/code&gt; rather than using &lt;a rel=&quot;external&quot; href=&quot;https://kazemnejad.com/blog/transformer_architecture_positional_encoding/&quot;&gt;fixed sinusoidal encodings&lt;/a&gt;. Adding &lt;code&gt;tok_emb + pos_emb&lt;/code&gt;
uses PyTorch broadcasting to stretch &lt;code&gt;pos_emb&lt;/code&gt; across all &lt;code&gt;B&lt;/code&gt; batch items, yielding a combined
representation &lt;code&gt;emb&lt;/code&gt; of shape &lt;code&gt;(B, T, n_embd)&lt;/code&gt; that encodes both what each token is and where it
sits in the sequence.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Learned positional embeddings are simple to implement and work well within a fixed context window,
but they cannot extrapolate to positions \(t \ge \text{block_size}\) because those rows in
&lt;code&gt;pos_emb_table&lt;/code&gt; are never trained. Modern frontier architectures instead use &lt;a rel=&quot;external&quot; href=&quot;https://arxiv.org/abs/2104.09864&quot;&gt;Rotary Position
Embedding (RoPE)&lt;/a&gt;, which encodes position by rotating query and key vectors in 2D frequency
planes at angles proportional to their token index \(t\). Because the dot product between two
rotated vectors depends only on their relative distance \(t_1 - t_2\), RoPE generalizes more
naturally to longer sequences. We use learned positional embeddings here to keep the code minimal.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Next, &lt;code&gt;out = self.ln(self.blocks(emb))&lt;/code&gt; passes the embeddings through &lt;code&gt;self.blocks&lt;/code&gt;, a stack of
transformer blocks that mix information across tokens via Multi-Head Attention (MHA) and refine each
token&#39;s features via a Multilayer Perceptron (MLP). Afterward, &lt;code&gt;self.ln&lt;/code&gt; applies &lt;a rel=&quot;external&quot; href=&quot;https://docs.pytorch.org/docs/stable/generated/torch.nn.LayerNorm.html&quot;&gt;layer
normalization&lt;/a&gt;, which shifts and scales each token&#39;s &lt;code&gt;n_embd&lt;/code&gt; feature vector to have mean
&lt;code&gt;0.0&lt;/code&gt; and variance &lt;code&gt;1.0&lt;/code&gt; so activations stay well-behaved across deep stacks. Finally, &lt;code&gt;self.proj&lt;/code&gt;
projects the normalized features into &lt;strong&gt;logits&lt;/strong&gt;, which are raw, unnormalized scores for every token
in the vocabulary. Notice &lt;code&gt;self.proj.weight = self.tok_emb_table.weight&lt;/code&gt;: because both
&lt;code&gt;nn.Embedding(vocab_size, n_embd)&lt;/code&gt; and &lt;code&gt;nn.Linear(n_embd, vocab_size)&lt;/code&gt; store their weight matrix with
shape &lt;code&gt;(vocab_size, n_embd)&lt;/code&gt;, they can share the exact same underlying tensor in memory (&lt;strong&gt;weight
tying&lt;/strong&gt;), ensuring that tokens with similar input embeddings receive similar output logit scores
while reducing parameter count.&lt;/p&gt;
&lt;p&gt;At the end of &lt;code&gt;forward&lt;/code&gt;, execution branches based on whether ground-truth &lt;code&gt;targets&lt;/code&gt; are supplied.
During inference (&lt;code&gt;targets is None&lt;/code&gt;), we only need to predict the single token that comes after the
current sequence, so &lt;code&gt;out[:, [-1], :]&lt;/code&gt; slices only the final time step (using a single-element list
&lt;code&gt;[-1]&lt;/code&gt; to preserve the 3D shape &lt;code&gt;(B, 1, n_embd)&lt;/code&gt;) before projecting it to &lt;code&gt;(B, 1, vocab_size)&lt;/code&gt;
logits, saving unnecessary matrix multiplications on earlier positions. During training, &lt;code&gt;self.proj(out)&lt;/code&gt;
computes logits of shape &lt;code&gt;(B, T, vocab_size)&lt;/code&gt; for every position. Because PyTorch&#39;s
&lt;a rel=&quot;external&quot; href=&quot;https://docs.pytorch.org/docs/stable/generated/torch.nn.functional.cross_entropy.html&quot;&gt;&lt;code&gt;F.cross_entropy&lt;/code&gt;&lt;/a&gt; expects a 2D prediction matrix of shape &lt;code&gt;(N, vocab_size)&lt;/code&gt; and a
1D label vector of shape &lt;code&gt;(N,)&lt;/code&gt; where \(N = B \times T\), we reshape the tensors with
&lt;code&gt;logits.view(B * T, -1)&lt;/code&gt; (where &lt;code&gt;-1&lt;/code&gt; automatically infers &lt;code&gt;vocab_size&lt;/code&gt;) and &lt;code&gt;targets.view(-1)&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;This cross-entropy calculation implements the core objective of causal pretraining: next-token
prediction. By maximizing the probability assigned to the true next token at every position in the
training corpus, the model learns the statistical structure of language. Formally, we minimize the
negative log-likelihood of the sequence:&lt;/p&gt;
&lt;p&gt;$$\mathcal{L}_{\text{pretrain}}(\theta) = -\sum_{t=1}^T \log P_{\theta}(x_{t} \mid x_{\lt t})$$&lt;/p&gt;
&lt;p&gt;Here, \(P_{\theta}\) represents our transformer parameterized by weights \(\theta\), and
\(x_{t}\) is the true target token at position \(t\) given all preceding tokens
\(x_{\lt t} = (x_1, \dots, x_{t-1})\). Intuitively, if the model assigns a probability near
\(1.0\) to the true next character, \(-\log P_{\theta}\) is close to \(0.0\) and the loss
penalty is tiny. If the model assigns a tiny probability to the true character, \(-\log P_{\theta}\)
grows very large, creating a steep gradient signal that adjusts \(\theta\) to raise that
character&#39;s score on future steps.&lt;/p&gt;
&lt;h3 id=&quot;multi-head-attention-and-transformer-blocks&quot;&gt;&lt;a class=&quot;zola-anchor&quot; href=&quot;#multi-head-attention-and-transformer-blocks&quot; aria-label=&quot;Anchor link for: multi-head-attention-and-transformer-blocks&quot;&gt;Multi-Head Attention and Transformer Blocks&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;While the final projection and loss calculation define the training objective, the model&#39;s ability
to understand context comes from the repeated attention and feed-forward layers inside
&lt;code&gt;self.blocks&lt;/code&gt;. To see how tokens exchange information and build contextual meaning across a
sequence, let us unpack &lt;code&gt;self.blocks(emb)&lt;/code&gt; and examine &lt;code&gt;AttentionHead&lt;/code&gt;, &lt;code&gt;MultiHeadAttention&lt;/code&gt;, and
&lt;code&gt;Block&lt;/code&gt; at the tensor level:&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #E1E4E8; background-color: #24292E;&quot; &gt;&lt;code data-lang=&quot;python&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 1&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;class&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt; AttentionHead&lt;/span&gt;&lt;span&gt;(&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt;nn&lt;/span&gt;&lt;span&gt;.&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt;Module&lt;/span&gt;&lt;span&gt;):&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 2&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;    &amp;quot;&amp;quot;&amp;quot;A single causal self-attention head.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 3&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 4&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;    def&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; __init__&lt;/span&gt;&lt;span&gt;(self, cfg: Config) -&amp;gt;&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; None&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 5&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;        &amp;quot;&amp;quot;&amp;quot;Initializes QKV projection and dropout, and caches causal mask to avoid recomputing it.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 6&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 7&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;        super&lt;/span&gt;&lt;span&gt;().&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;__init__&lt;/span&gt;&lt;span&gt;()&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 8&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;        self&lt;/span&gt;&lt;span&gt;.qkv&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; nn.Linear(cfg.n_embd,&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 3&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; *&lt;/span&gt;&lt;span&gt; cfg.head_size,&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; bias&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span&gt;cfg.bias)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 9&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;        self&lt;/span&gt;&lt;span&gt;.dropout&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; nn.Dropout(cfg.dropout)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;10&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;        self&lt;/span&gt;&lt;span&gt;.register_buffer(&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;mask&amp;quot;&lt;/span&gt;&lt;span&gt;, torch.tril(torch.ones(cfg.block_size, cfg.block_size)))&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;11&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;12&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;    def&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt; forward&lt;/span&gt;&lt;span&gt;(self, x: torch.Tensor) -&amp;gt; torch.Tensor:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;13&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;        &amp;quot;&amp;quot;&amp;quot;Computes masked single-head self-attention for the input tensor.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;14&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;15&lt;/span&gt;&lt;span&gt;        _, T, D&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; x.shape&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;16&lt;/span&gt;&lt;span&gt;        q, k, v&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; self&lt;/span&gt;&lt;span&gt;.qkv(x).split(&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;self&lt;/span&gt;&lt;span&gt;.qkv.out_features&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; //&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 3&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; dim&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=-&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;17&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;18&lt;/span&gt;&lt;span&gt;        attn_scores&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; q&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; @&lt;/span&gt;&lt;span&gt; k.transpose(&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;-&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;2&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; -&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;19&lt;/span&gt;&lt;span&gt;        attn_scores&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; attn_scores&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; *&lt;/span&gt;&lt;span&gt; D&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;**-&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;0.5&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;  # Prevent softmax from blowing up&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;20&lt;/span&gt;&lt;span&gt;        attn_scores&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; attn_scores.masked_fill(&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;self&lt;/span&gt;&lt;span&gt;.mask[:T, :T]&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; ==&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 0&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; float&lt;/span&gt;&lt;span&gt;(&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;-inf&amp;quot;&lt;/span&gt;&lt;span&gt;))&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;  # Mask future tokens&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;21&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;22&lt;/span&gt;&lt;span&gt;        attn_weights&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; torch.softmax(attn_scores,&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; dim&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=-&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;23&lt;/span&gt;&lt;span&gt;        attn_weights&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; self&lt;/span&gt;&lt;span&gt;.dropout(attn_weights)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;24&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;        return&lt;/span&gt;&lt;span&gt; attn_weights&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; @&lt;/span&gt;&lt;span&gt; v&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;25&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;26&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;class&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt; MultiHeadAttention&lt;/span&gt;&lt;span&gt;(&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt;nn&lt;/span&gt;&lt;span&gt;.&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt;Module&lt;/span&gt;&lt;span&gt;):&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;27&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;    &amp;quot;&amp;quot;&amp;quot;A Multi-Head Attention (MHA).&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;28&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;29&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;    def&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; __init__&lt;/span&gt;&lt;span&gt;(self, cfg: Config) -&amp;gt;&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; None&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;30&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;        &amp;quot;&amp;quot;&amp;quot;Initializes multi-head self-attention with output projection and dropout.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;31&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;32&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;        super&lt;/span&gt;&lt;span&gt;().&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;__init__&lt;/span&gt;&lt;span&gt;()&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;33&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;        self&lt;/span&gt;&lt;span&gt;.heads&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; nn.ModuleList([AttentionHead(cfg)&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; for&lt;/span&gt;&lt;span&gt; _&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; in&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; range&lt;/span&gt;&lt;span&gt;(cfg.n_head)])&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;34&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;        self&lt;/span&gt;&lt;span&gt;.proj&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; nn.Linear(cfg.n_embd, cfg.n_embd)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;35&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;        self&lt;/span&gt;&lt;span&gt;.dropout&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; nn.Dropout(cfg.dropout)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;36&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;37&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;    def&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt; forward&lt;/span&gt;&lt;span&gt;(self, x: torch.Tensor) -&amp;gt; torch.Tensor:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;38&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;        &amp;quot;&amp;quot;&amp;quot;Computes masked multi-head self-attention for the input tensor.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;39&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;40&lt;/span&gt;&lt;span&gt;        out&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; torch.cat([head(x)&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; for&lt;/span&gt;&lt;span&gt; head&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; in&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; self&lt;/span&gt;&lt;span&gt;.heads],&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; dim&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=-&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;41&lt;/span&gt;&lt;span&gt;        out&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; self&lt;/span&gt;&lt;span&gt;.dropout(&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;self&lt;/span&gt;&lt;span&gt;.proj(out))&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;42&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;        return&lt;/span&gt;&lt;span&gt; out&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;43&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;44&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;class&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt; Block&lt;/span&gt;&lt;span&gt;(&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt;nn&lt;/span&gt;&lt;span&gt;.&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt;Module&lt;/span&gt;&lt;span&gt;):&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;45&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;    &amp;quot;&amp;quot;&amp;quot;Transformer block.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;46&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;47&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;    def&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; __init__&lt;/span&gt;&lt;span&gt;(self, cfg: Config) -&amp;gt;&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; None&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;48&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;        &amp;quot;&amp;quot;&amp;quot;Initializes a transformer block.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;49&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;50&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;        super&lt;/span&gt;&lt;span&gt;().&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;__init__&lt;/span&gt;&lt;span&gt;()&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;51&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;        self&lt;/span&gt;&lt;span&gt;.ln1&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; nn.LayerNorm(cfg.n_embd,&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; bias&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span&gt;cfg.bias)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;52&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;        self&lt;/span&gt;&lt;span&gt;.mha&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; MultiHeadAttention(cfg)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;53&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;        self&lt;/span&gt;&lt;span&gt;.ln2&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; nn.LayerNorm(cfg.n_embd,&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; bias&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span&gt;cfg.bias)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;54&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;        self&lt;/span&gt;&lt;span&gt;.mlp&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; nn.Sequential(&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;55&lt;/span&gt;&lt;span&gt;            nn.Linear(cfg.n_embd,&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 2&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; *&lt;/span&gt;&lt;span&gt; cfg.n_embd,&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; bias&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span&gt;cfg.bias),&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;  # Flexible: can change to e.g. `4 * cfg.n_embd`&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;56&lt;/span&gt;&lt;span&gt;            nn.GELU(),&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;57&lt;/span&gt;&lt;span&gt;            nn.Linear(&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;2&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; *&lt;/span&gt;&lt;span&gt; cfg.n_embd, cfg.n_embd,&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; bias&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span&gt;cfg.bias),&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;58&lt;/span&gt;&lt;span&gt;            nn.Dropout(cfg.dropout),&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;59&lt;/span&gt;&lt;span&gt;        )&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;60&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;61&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;    def&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt; forward&lt;/span&gt;&lt;span&gt;(self, x: torch.Tensor) -&amp;gt; torch.Tensor:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;62&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;        &amp;quot;&amp;quot;&amp;quot;Performs a forward pass: attention + MLP with residuals and layer norms.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;63&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;64&lt;/span&gt;&lt;span&gt;        x&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; x&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; +&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; self&lt;/span&gt;&lt;span&gt;.mha(&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;self&lt;/span&gt;&lt;span&gt;.ln1(x))&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;65&lt;/span&gt;&lt;span&gt;        x&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; x&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; +&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; self&lt;/span&gt;&lt;span&gt;.mlp(&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;self&lt;/span&gt;&lt;span&gt;.ln2(x))&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;66&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;        return&lt;/span&gt;&lt;span&gt; x&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;AttentionHead&lt;/code&gt; class implements a single causal self-attention head. Attention, introduced in
the &lt;a rel=&quot;external&quot; href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;Attention Is All You Need&lt;/a&gt; paper, is a directional communication mechanism that lets
each token in a sequence gather relevant context from earlier tokens. Rather than running three
separate matrix multiplications, &lt;code&gt;self.qkv(x)&lt;/code&gt; projects each token&#39;s &lt;code&gt;n_embd&lt;/code&gt; vector into a combined
vector of width &lt;code&gt;3 * cfg.head_size&lt;/code&gt;, and &lt;code&gt;.split(self.qkv.out_features // 3, dim=-1)&lt;/code&gt; slices that
last axis into three tensors &lt;code&gt;q&lt;/code&gt;, &lt;code&gt;k&lt;/code&gt;, and &lt;code&gt;v&lt;/code&gt; of shape &lt;code&gt;(B, T, head_size)&lt;/code&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Query (&lt;code&gt;q&lt;/code&gt;): Like asking a librarian a question such as &lt;code&gt;&quot;Which books talk about dinosaurs?&quot;&lt;/code&gt;. The
query vector represents what the current token at position \(i\) is looking for as it scans the
sequence for useful context, such as a verb searching for its subject or a pronoun searching for
the noun it refers to.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Key (&lt;code&gt;k&lt;/code&gt;): Like the title labels or catalog cards on the library shelves. Each token at position
\(j \le i\) advertises what kind of information it holds through its key vector, and the dot
product between token \(i\)&#39;s query and token \(j\)&#39;s key measures how closely the catalog
label matches the search request.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Value (&lt;code&gt;v&lt;/code&gt;): Like the actual pages inside each book. Once the query-key dot products determine
how much attention token \(i\) should pay to each earlier token \(j\), the head computes a
weighted sum of the value vectors to retrieve and blend the actual content from the matching
positions.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;To compute all pairwise query-key dot products in one operation, &lt;code&gt;k.transpose(-2, -1)&lt;/code&gt; swaps the
last two axes of &lt;code&gt;k&lt;/code&gt; from &lt;code&gt;(B, T, head_size)&lt;/code&gt; to &lt;code&gt;(B, head_size, T)&lt;/code&gt;, so the batched matrix
multiplication &lt;code&gt;q @ k.transpose(-2, -1)&lt;/code&gt; produces an &lt;code&gt;(B, T, T)&lt;/code&gt; grid of raw similarity scores
&lt;code&gt;attn_scores&lt;/code&gt;. Next, we scale &lt;code&gt;attn_scores&lt;/code&gt; by &lt;code&gt;D**-0.5&lt;/code&gt; (note that in this compact script &lt;code&gt;D&lt;/code&gt; is
unpacked from &lt;code&gt;x.shape&lt;/code&gt; as &lt;code&gt;cfg.n_embd&lt;/code&gt;, whereas standard multi-head formulations scale by
&lt;code&gt;cfg.head_size**-0.5&lt;/code&gt;). To enforce causality so token \(i\) can never peek at future tokens
\(j \gt i\), &lt;code&gt;__init__&lt;/code&gt; pre-builds a lower-triangular matrix of ones via
&lt;code&gt;torch.tril(torch.ones(cfg.block_size, cfg.block_size))&lt;/code&gt; and stores it with
&lt;code&gt;self.register_buffer(&quot;mask&quot;, ...)&lt;/code&gt;, which tells PyTorch to move the tensor to the GPU alongside
the model without treating it as a trainable parameter. During &lt;code&gt;forward&lt;/code&gt;,
&lt;code&gt;masked_fill(self.mask[:T, :T] == 0, float(&quot;-inf&quot;))&lt;/code&gt; replaces all upper-triangular future entries
(\(j \gt i\)) with \(-\infty\). Formally, for sequence length \(n\) and scaling dimension
\(d\), attention computes:&lt;/p&gt;
&lt;p&gt;$$\text{Attention}(Q, K, V) = \text{softmax}\big(\frac{Q K^\top}{\sqrt{d}}\big) V$$&lt;/p&gt;
&lt;p&gt;Dividing by \(\sqrt{d}\) keeps the variance of the dot products bounded as embedding dimensions
grow, preventing &lt;code&gt;softmax&lt;/code&gt; from saturating into extreme \(0.0\) or \(1.0\) probabilities where
gradients vanish. Because \(\exp(-\infty) = 0\), &lt;code&gt;torch.softmax(attn_scores, dim=-1)&lt;/code&gt; turns every
masked future position into an exact &lt;code&gt;0.0&lt;/code&gt; weight while normalizing the allowed past and present
positions in each row to sum to &lt;code&gt;1.0&lt;/code&gt;. Multiplying &lt;code&gt;attn_weights @ v&lt;/code&gt; then aggregates the value
vectors into an output of shape &lt;code&gt;(B, T, head_size)&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;In &lt;code&gt;MultiHeadAttention&lt;/code&gt;, we run &lt;code&gt;cfg.n_head&lt;/code&gt; independent &lt;code&gt;AttentionHead&lt;/code&gt; modules in parallel,
concatenate their &lt;code&gt;(B, T, head_size)&lt;/code&gt; outputs along the last axis (&lt;code&gt;dim=-1&lt;/code&gt;) to recover shape
&lt;code&gt;(B, T, n_embd)&lt;/code&gt;, and pass the result through the output projection &lt;code&gt;self.proj&lt;/code&gt;. Running multiple
heads in parallel lets the model attend to several types of relationships simultaneously, with one
head tracking local punctuation or syntax while another tracks long-range character names. Applying
&lt;code&gt;self.dropout&lt;/code&gt; to the projected output regularizes the layer so individual heads cannot co-adapt and
learn redundant patterns.&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;Block&lt;/code&gt; class pairs cross-token communication (&lt;code&gt;self.mha&lt;/code&gt;) with per-token computation
(&lt;code&gt;self.mlp&lt;/code&gt;). Before each sublayer, layer normalization (&lt;code&gt;self.ln1&lt;/code&gt; and &lt;code&gt;self.ln2&lt;/code&gt;) standardizes the
input features, and after each sublayer, a &lt;a rel=&quot;external&quot; href=&quot;https://arxiv.org/abs/1512.03385&quot;&gt;residual connection&lt;/a&gt; (&lt;code&gt;x = x + ...&lt;/code&gt;) adds the
sublayer&#39;s input directly to its output. Because the derivative of \(x + f(x)\) with respect to
\(x\) is \(1 + f&#39;(x)\), this residual addition creates an unimpeded highway that carries
gradients straight from the loss back to the earliest layers without vanishing. While &lt;code&gt;self.mha&lt;/code&gt;
mixes information across time steps, &lt;code&gt;self.mlp&lt;/code&gt; processes each token position independently: it
projects the &lt;code&gt;n_embd&lt;/code&gt; vector up to a wider hidden dimension (&lt;code&gt;2 * cfg.n_embd&lt;/code&gt;, chosen instead of the
standard &lt;code&gt;4 * cfg.n_embd&lt;/code&gt; to keep our miniature model compact at &lt;code&gt;140,127&lt;/code&gt; parameters), applies a
smooth nonlinear &lt;a rel=&quot;external&quot; href=&quot;https://arxiv.org/abs/1606.08415&quot;&gt;GELU&lt;/a&gt; (Gaussian Error Linear Unit) activation so the two linear layers do
not collapse into a single linear matrix multiply, and projects back down to &lt;code&gt;cfg.n_embd&lt;/code&gt;.&lt;/p&gt;
&lt;h3 id=&quot;autoregressive-generation&quot;&gt;&lt;a class=&quot;zola-anchor&quot; href=&quot;#autoregressive-generation&quot; aria-label=&quot;Anchor link for: autoregressive-generation&quot;&gt;Autoregressive Generation&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;During training, the model processes all \(T\) tokens of a sequence in parallel using &lt;a rel=&quot;external&quot; href=&quot;https://en.wikipedia.org/wiki/Teacher_forcing&quot;&gt;teacher
forcing&lt;/a&gt;, meaning the model always receives the true ground-truth tokens from the
dataset as context at every position even if its own prediction at the previous position was wrong.
At inference, however, future ground-truth tokens do not exist, so &lt;code&gt;Transformer.generate&lt;/code&gt; runs
sequentially: it first calls &lt;code&gt;self.eval()&lt;/code&gt; to disable random dropout layers (note that if you call
&lt;code&gt;generate&lt;/code&gt; in the middle of a training loop, you should call &lt;code&gt;model.train()&lt;/code&gt; afterward to re-enable
dropout), crops the running sequence to the trailing &lt;code&gt;self.block_size&lt;/code&gt; tokens via
&lt;code&gt;token_ids[:, -self.block_size :]&lt;/code&gt; so it never exceeds &lt;code&gt;pos_emb_table&lt;/code&gt;, and extracts the 2D slice of
final-position logits &lt;code&gt;logits[:, -1, :]&lt;/code&gt; of shape &lt;code&gt;(B, vocab_size)&lt;/code&gt; representing raw scores
\(\mathbf{z} \in \mathbb{R}^{\lvert \mathcal{V} \rvert}\) across the vocabulary \(\mathcal{V}\).
To balance coherence and creativity, we divide the logits by a temperature parameter
\(\tau \gt 0\) and optionally restrict sampling to the \(k\) highest-scoring candidate tokens
\(\mathcal{V}_k \subset \mathcal{V}\):&lt;/p&gt;
&lt;p&gt;$$P(x_{t} = v \mid x_{\lt t}) = \frac{\exp(z_{v} / \tau)}{\sum_{j \in \mathcal{V}_k} \exp(z_{j} / \tau)}$$&lt;/p&gt;
&lt;figure&gt;
  &lt;img src=&quot;temperature_grouped.webp&quot; alt=&quot;Effect of temperature on next-token probabilities&quot; width=&quot;1024&quot; height=&quot;614&quot; loading=&quot;lazy&quot;&gt;
  &lt;figcaption&gt;Effect of temperature on next-token probabilities for candidate continuations&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;The diagram above illustrates how temperature \(\tau\) reshapes the probability distribution for
the prompt &lt;code&gt;&quot;Artificial intelligence will transform the ...&quot;&lt;/code&gt;. Dividing logits by a small
temperature (\(\tau = 0.2\)) magnifies score differences fivefold before exponentiation,
concentrating 82% of the probability mass on the top candidate (&lt;code&gt;&quot;future&quot;&lt;/code&gt;) and driving tail options
near zero. This sharp distribution suits deterministic tasks like coding or math, whereas moderate
temperatures (\(\tau = 0.7\) and \(\tau = 1.0\)) give meaningful weight to plausible
alternatives like &lt;code&gt;&quot;world&quot;&lt;/code&gt; (22%) and &lt;code&gt;&quot;industry&quot;&lt;/code&gt; (16%), and high temperatures (\(\tau = 2.0\))
compress logit gaps to flatten the distribution across candidates.&lt;/p&gt;
&lt;p&gt;When &lt;code&gt;top_k&lt;/code&gt; is enabled in &lt;code&gt;generate&lt;/code&gt;, &lt;code&gt;torch.topk(logits, k).values[:, [-1]]&lt;/code&gt; finds the \(k\)-th
largest logit score in each row as a cutoff threshold, and &lt;code&gt;logits[logits &amp;lt; threshold] = -float(&quot;inf&quot;)&lt;/code&gt;
sets every token outside the top \(k\) to \(-\infty\) so &lt;code&gt;torch.softmax&lt;/code&gt; assigns them zero
probability. Rather than always picking the single highest-scoring token with &lt;code&gt;torch.argmax&lt;/code&gt; (greedy
decoding, which frequently gets stuck in repetitive loops), &lt;code&gt;torch.multinomial(probs, num_samples=1)&lt;/code&gt;
samples an index from the categorical distribution like spinning a weighted roulette wheel where each
token&#39;s slice of the wheel equals its probability:&lt;/p&gt;
&lt;p&gt;$$x_{t} \sim \text{Categorical}(P(x_{t} \mid x_{\lt t}))$$&lt;/p&gt;
&lt;p&gt;High-probability tokens are selected most often, while lower-probability tokens inside the
top-\(k\) set retain a controlled chance of being chosen, allowing natural variation across runs.
Each sampled token index &lt;code&gt;next_token&lt;/code&gt; of shape &lt;code&gt;(B, 1)&lt;/code&gt; is appended to &lt;code&gt;token_ids&lt;/code&gt; along the time
dimension via &lt;code&gt;torch.cat((token_ids, next_token), dim=1)&lt;/code&gt;, and the loop repeats until
&lt;code&gt;max_new_token_ids&lt;/code&gt; tokens have been generated.&lt;/p&gt;
&lt;h3 id=&quot;pretraining-loop&quot;&gt;&lt;a class=&quot;zola-anchor&quot; href=&quot;#pretraining-loop&quot; aria-label=&quot;Anchor link for: pretraining-loop&quot;&gt;Pretraining Loop&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;With the architecture in place, we can pretrain our model on Mary Shelley&#39;s &lt;em&gt;Frankenstein&lt;/em&gt;. In the
script below, &lt;code&gt;sample_batch&lt;/code&gt; picks &lt;code&gt;batch_size&lt;/code&gt; random starting indices in the tokenized book,
slices chunks of length &lt;code&gt;block_size&lt;/code&gt; as input &lt;code&gt;token_ids&lt;/code&gt;, and slices the same chunks shifted right
by one character (&lt;code&gt;idx + 1 : idx + block_size + 1&lt;/code&gt;) as &lt;code&gt;targets&lt;/code&gt;. Notice how we also split the
model&#39;s parameters by tensor dimension (&lt;code&gt;param.ndim &amp;lt; 2&lt;/code&gt;): 1D tensors (such as &lt;code&gt;LayerNorm&lt;/code&gt; scale
vectors and the default bias vectors on &lt;code&gt;self.proj&lt;/code&gt;) go to &lt;a rel=&quot;external&quot; href=&quot;https://arxiv.org/abs/1711.05101&quot;&gt;&lt;code&gt;AdamW&lt;/code&gt;&lt;/a&gt;, while 2D weight and
embedding matrices go to &lt;a rel=&quot;external&quot; href=&quot;https://arxiv.org/abs/2502.16982&quot;&gt;&lt;code&gt;Muon&lt;/code&gt;&lt;/a&gt;:&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #E1E4E8; background-color: #24292E;&quot; &gt;&lt;code data-lang=&quot;python&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 1&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;import&lt;/span&gt;&lt;span&gt; urllib.request&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 2&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 3&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;def&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt; sample_batch&lt;/span&gt;&lt;span&gt;(data: torch.Tensor, batch_size:&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; int&lt;/span&gt;&lt;span&gt;, block_size:&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; int&lt;/span&gt;&lt;span&gt;) -&amp;gt;&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; tuple&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 4&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;    &amp;quot;&amp;quot;&amp;quot;Randomly samples training sequences for Next-Token Prediction (NTP).&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 5&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 6&lt;/span&gt;&lt;span&gt;    idxs&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; torch.randint(&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;len&lt;/span&gt;&lt;span&gt;(data)&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; -&lt;/span&gt;&lt;span&gt; block_size, (batch_size,))&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;                    # Random starting positions&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 7&lt;/span&gt;&lt;span&gt;    token_ids&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; torch.stack([data[idx : idx&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; +&lt;/span&gt;&lt;span&gt; block_size]&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; for&lt;/span&gt;&lt;span&gt; idx&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; in&lt;/span&gt;&lt;span&gt; idxs])&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;        # Input sequences&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 8&lt;/span&gt;&lt;span&gt;    targets&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; torch.stack([data[idx&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; +&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 1&lt;/span&gt;&lt;span&gt; : idx&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; +&lt;/span&gt;&lt;span&gt; block_size&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; +&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 1&lt;/span&gt;&lt;span&gt;]&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; for&lt;/span&gt;&lt;span&gt; idx&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; in&lt;/span&gt;&lt;span&gt; idxs])&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;  # Same sequences shifted by +1 (NTP)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt; 9&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;    return&lt;/span&gt;&lt;span&gt; token_ids, targets&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;10&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;11&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;with&lt;/span&gt;&lt;span&gt; urllib.request.urlopen(&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;https://www.gutenberg.org/cache/epub/84/pg84.txt&amp;quot;&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; as&lt;/span&gt;&lt;span&gt; f:&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;  # Read Frankenstein&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;12&lt;/span&gt;&lt;span&gt;    text&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; f.read().decode(&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;utf-8&amp;quot;&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;13&lt;/span&gt;&lt;span&gt;tokenizer&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; CharacterLevelTokenizer(text)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;14&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;15&lt;/span&gt;&lt;span&gt;device&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; torch.device(&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;cuda:0&amp;quot;&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; if&lt;/span&gt;&lt;span&gt; torch.cuda.is_available()&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; else&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt; &amp;quot;mps&amp;quot;&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; if&lt;/span&gt;&lt;span&gt; torch.backends.mps.is_available()&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; else&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt; &amp;quot;cpu&amp;quot;&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;16&lt;/span&gt;&lt;span&gt;cfg&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; Config(&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt;vocab_size&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span&gt;tokenizer.vocab_size,&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; block_size&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;32&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; n_layer&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;4&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; n_head&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;4&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; n_embd&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;64&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; dropout&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;0.0&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; bias&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;False&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;17&lt;/span&gt;&lt;span&gt;max_steps, log_interval, batch_size, learning_rate&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 2_000&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 10&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 256&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 1e-3&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;18&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;19&lt;/span&gt;&lt;span&gt;data&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; torch.tensor(tokenizer.encode(text),&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; device&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span&gt;device)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;20&lt;/span&gt;&lt;span&gt;model&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; Transformer(cfg).to(device).train()&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;21&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;22&lt;/span&gt;&lt;span&gt;n_params, adamw_params, muon_params&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 0&lt;/span&gt;&lt;span&gt;, [], []&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;23&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;for&lt;/span&gt;&lt;span&gt; param&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; in&lt;/span&gt;&lt;span&gt; model.parameters():&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;24&lt;/span&gt;&lt;span&gt;    n_params&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; +=&lt;/span&gt;&lt;span&gt; param.numel()&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;25&lt;/span&gt;&lt;span&gt;    (adamw_params&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; if&lt;/span&gt;&lt;span&gt; param.ndim&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; &amp;lt;&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 2&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; else&lt;/span&gt;&lt;span&gt; muon_params).append(param)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;26&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;print&lt;/span&gt;&lt;span&gt;(&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;f&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;Model parameters: &lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;{&lt;/span&gt;&lt;span&gt;n_params&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;:,&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;}\n&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;27&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;28&lt;/span&gt;&lt;span&gt;adamw&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; torch.optim.AdamW(adamw_params,&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; lr&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;3e-4&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; betas&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span&gt;(&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;0.9&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 0.95&lt;/span&gt;&lt;span&gt;),&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; eps&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1e-8&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; weight_decay&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;0.01&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;29&lt;/span&gt;&lt;span&gt;muon&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; torch.optim.Muon(muon_params,&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; lr&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;0.02&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; momentum&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;0.95&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; weight_decay&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;0.1&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;30&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;for&lt;/span&gt;&lt;span&gt; step&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; in&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; range&lt;/span&gt;&lt;span&gt;(&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span&gt;, max_steps&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; +&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 1&lt;/span&gt;&lt;span&gt;):&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;31&lt;/span&gt;&lt;span&gt;    token_ids, targets&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; sample_batch(data, batch_size, cfg.block_size)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;32&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;33&lt;/span&gt;&lt;span&gt;    adamw.zero_grad()&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;34&lt;/span&gt;&lt;span&gt;    muon.zero_grad()&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;35&lt;/span&gt;&lt;span&gt;    _, loss&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; model(token_ids, targets)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;36&lt;/span&gt;&lt;span&gt;    loss.backward()&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;37&lt;/span&gt;&lt;span&gt;    adamw.step()&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;38&lt;/span&gt;&lt;span&gt;    muon.step()&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;39&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;40&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;    if&lt;/span&gt;&lt;span&gt; step&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; %&lt;/span&gt;&lt;span&gt; log_interval&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; ==&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 0&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;41&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;        print&lt;/span&gt;&lt;span&gt;(&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;f&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;\r&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;Step &lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;{&lt;/span&gt;&lt;span&gt;step&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;}&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;/&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;{&lt;/span&gt;&lt;span&gt;max_steps&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;}&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt; (&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;{&lt;/span&gt;&lt;span&gt;step&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; /&lt;/span&gt;&lt;span&gt; max_steps&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;:.2%&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;}&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;) | Loss: &lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;{&lt;/span&gt;&lt;span&gt;loss.item()&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;:.4f&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;}&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt; &amp;quot;&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; end&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;&amp;quot;&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; flush&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;True&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;42&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;43&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;# Seed the model with the prompt &amp;quot;I am&amp;quot; to kick off text generation&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;44&lt;/span&gt;&lt;span&gt;token_ids&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; torch.tensor(tokenizer.encode(&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;I am&amp;quot;&lt;/span&gt;&lt;span&gt;),&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; device&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span&gt;device).reshape(&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; -&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;45&lt;/span&gt;&lt;span&gt;output&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span&gt; model.generate(token_ids,&lt;/span&gt;&lt;span style=&quot;color: #FFAB70;&quot;&gt; max_new_token_ids&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;512&lt;/span&gt;&lt;span&gt;)[&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;0&lt;/span&gt;&lt;span&gt;]&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span aria-hidden=&quot;true&quot; class=&quot;giallo-ln&quot; style=&quot;color: #444D56;&quot;&gt;46&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;print&lt;/span&gt;&lt;span&gt;(&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;f&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;\n\n&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;OUTPUT:&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;\n\n{&lt;/span&gt;&lt;span&gt;tokenizer.decode(output.tolist())&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;}&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Why do we pair two different optimizers with different learning rates (&lt;code&gt;lr=3e-4&lt;/code&gt; for &lt;code&gt;AdamW&lt;/code&gt; and
&lt;code&gt;lr=0.02&lt;/code&gt; for &lt;code&gt;Muon&lt;/code&gt;, overriding the baseline &lt;code&gt;learning_rate = 1e-3&lt;/code&gt; constant)? &lt;code&gt;AdamW&lt;/code&gt; updates each
parameter coordinate independently by dividing a running average of the gradient (&lt;code&gt;betas[0]=0.9&lt;/code&gt;) by
the square root of a running average of squared gradients (&lt;code&gt;betas[1]=0.95&lt;/code&gt;, plus &lt;code&gt;eps=1e-8&lt;/code&gt; to
prevent division by zero) while gently shrinking weights toward zero at each step (&lt;code&gt;weight_decay=0.01&lt;/code&gt;).
For 2D weight matrices, however, raw gradients are often dominated by a few large singular
directions. &lt;code&gt;Muon&lt;/code&gt; accumulates gradient momentum (&lt;code&gt;momentum=0.95&lt;/code&gt;) and applies Newton-Schulz matrix
iterations to orthogonalize the 2D update matrix, equalizing the step size across all singular
directions so the spectral norm is normalized and a larger learning rate (&lt;code&gt;lr=0.02&lt;/code&gt;) can be taken
safely. Inside each step of the loop, &lt;code&gt;zero_grad()&lt;/code&gt; clears the previous step&#39;s gradients (since
PyTorch accumulates gradients by addition into &lt;code&gt;.grad&lt;/code&gt; buffers by default), &lt;code&gt;loss.backward()&lt;/code&gt; uses
the chain rule to compute gradients across the network, and &lt;code&gt;step()&lt;/code&gt; updates the weights.&lt;/p&gt;
&lt;h3 id=&quot;pretraining-results&quot;&gt;&lt;a class=&quot;zola-anchor&quot; href=&quot;#pretraining-results&quot; aria-label=&quot;Anchor link for: pretraining-results&quot;&gt;Pretraining Results&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;Running the 2,000-step pretraining loop takes under 40 seconds on a &lt;a rel=&quot;external&quot; href=&quot;https://en.wikipedia.org/wiki/MacBook_Pro_(Apple_silicon)&quot;&gt;MacBook Pro&lt;/a&gt; with
an &lt;a rel=&quot;external&quot; href=&quot;https://en.wikipedia.org/wiki/Apple_M4&quot;&gt;Apple M4 Pro&lt;/a&gt; chip. Over those 2,000 steps (processing
\(2{,}000 \times 256 \times 32 \approx 16.4\text{M}\) characters), the cross-entropy loss drops to
&lt;code&gt;1.3831&lt;/code&gt;, and our 140,127-parameter character model learns English word boundaries, punctuation, and
Shelley&#39;s vocabulary from raw character statistics:&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #E1E4E8; background-color: #24292E;&quot; &gt;&lt;code data-lang=&quot;plain&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;Model parameters: 140,127&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;Step 2000/2000 (100.00%) | Loss: 1.3831&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;OUTPUT:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;I am the forth which were on his stranger. The light of many our reasun alive in the enter of my&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;cottagers, there in the murderer, when I walked in&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;my enemy sat much of spring in its removed. I had not for my friend, and the cottager of the lack of&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;the wint on the lovely of cestant, and that the old man, but I was entered that&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;the eviner of my hands. My journey is many beauty will of compassins of the more spully appeared&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;with meaning a man work was not rease to be macking my own and a&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;gentle understand even&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;h3 id=&quot;midtraining&quot;&gt;&lt;a class=&quot;zola-anchor&quot; href=&quot;#midtraining&quot; aria-label=&quot;Anchor link for: midtraining&quot;&gt;Midtraining&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;In production pipelines, base pretraining on web-scale text provides broad world knowledge, but raw
web crawls are noisy and low in reasoning density. As analyzed in a recent &lt;a rel=&quot;external&quot; href=&quot;https://arxiv.org/abs/2510.06826&quot;&gt;survey on
midtraining&lt;/a&gt;, frontier LLMs bridge this gap through midtraining, also known as
continual pretraining. Midtraining optimizes the same autoregressive next-token prediction objective
over a higher-quality data mixture and an extended sequence length across three pillars:&lt;/p&gt;
&lt;p&gt;$$\mathcal{L}_{\text{midtrain}}(\theta) = -\sum_{t=1}^T \log P_{\theta}(x_{t} \mid x_{\lt t})$$&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;Targeted Data Distributions: Upsampling high-utility reasoning domains (such as code, STEM
mathematics, synthetic textbooks, step-by-step chain-of-thought traces, and fill-in-the-middle
data where a middle span of code is moved to the end so the model learns to infill missing code
given both prefix and suffix context) while retaining a replay buffer (typically 10% to 30%) of
general web tokens to prevent &lt;a rel=&quot;external&quot; href=&quot;https://en.wikipedia.org/wiki/Catastrophic_interference&quot;&gt;catastrophic forgetting&lt;/a&gt; (overwriting
previously learned general knowledge when adapting to a narrower distribution).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Learning Rate Annealing: Decaying the learning rate along a cooldown schedule such as cosine
decay (smoothly lowering the step size along a half-cosine curve) or warmup-stable-decay (holding
the learning rate constant during base pretraining and rapidly decaying it during midtraining).
Smaller gradient steps reduce mini-batch gradient noise variance and let the weights settle into
a sharper, lower-loss minimum on curated reasoning data.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Context Length Extension: Progressively expanding the context window &lt;code&gt;block_size&lt;/code&gt; (often from 4K
or 8K tokens up to 32K or 128K) by adapting positional encodings on a mixture of long and short
documents. Because &lt;a rel=&quot;external&quot; href=&quot;https://arxiv.org/abs/2104.09864&quot;&gt;RoPE&lt;/a&gt; represents token positions as rotation angles at different
frequencies (like clock hands moving at different speeds), rescaling those frequencies slows the
rotations so longer sequences fit inside the trained angular range, while &lt;a rel=&quot;external&quot; href=&quot;https://arxiv.org/abs/2309.00071&quot;&gt;YaRN&lt;/a&gt;
interpolates only the slow, low-frequency dimensions so sharp local token order is preserved.
Training on short sequences before expanding to long sequences acts as curriculum learning
(starting with easier examples before harder ones), &lt;a rel=&quot;external&quot; href=&quot;https://arxiv.org/abs/2208.01066&quot;&gt;which accelerates convergence and strengthens
in-context learning&lt;/a&gt; (the model&#39;s ability to learn a new task purely from examples
inside the prompt at inference time).&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id=&quot;conclusion&quot;&gt;&lt;a class=&quot;zola-anchor&quot; href=&quot;#conclusion&quot; aria-label=&quot;Anchor link for: conclusion&quot;&gt;Conclusion&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;In this article, we implemented and pretrained a GPT-like autoregressive transformer from scratch
using PyTorch, covering character-level tokenization, causal multi-head self-attention, residual
connections, next-token prediction with &lt;code&gt;AdamW&lt;/code&gt; and &lt;code&gt;Muon&lt;/code&gt;, and the foundations of midtraining. While
our 140K-parameter model produces only stylistic echoes of Shelley rather than fully coherent prose,
the underlying algorithmic blueprint is identical to the one powering frontier systems. At scale,
pretraining and midtraining establish broad world knowledge and structured reasoning, yielding
capable base models. However, raw base models remain open-ended text completers. Transforming a
next-token predictor into a helpful conversational assistant requires post-training, beginning with
Supervised Fine-Tuning (SFT), which we explore in &lt;a href=&quot;/blog/the-foundations-of-llms-supervised-fine-tuning/&quot;&gt;Part II&lt;/a&gt;.&lt;/p&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>The Foundations of LLMs</title>
        <published>2026-03-12T00:00:00+00:00</published>
        <updated>2026-03-12T00:00:00+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://oniani.org/tfol/"/>
        <id>https://oniani.org/tfol/</id>
        
        <content type="html" xml:base="https://oniani.org/tfol/">&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;/blog/the-foundations-of-llms-pretraining-and-midtraining/&quot;&gt;The Foundations of LLMs, Part I: Pretraining and Midtraining&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;/blog/the-foundations-of-llms-supervised-fine-tuning/&quot;&gt;The Foundations of LLMs, Part II: Supervised Fine-Tuning&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>COVID-19 and Transition Into Full-Time Summer Work</title>
        <published>2020-05-22T00:00:00+00:00</published>
        <updated>2020-05-22T00:00:00+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://oniani.org/blog/covid-19-and-transition-into-full-time-summer-work/"/>
        <id>https://oniani.org/blog/covid-19-and-transition-into-full-time-summer-work/</id>
        
        <content type="html" xml:base="https://oniani.org/blog/covid-19-and-transition-into-full-time-summer-work/">&lt;p&gt;A lot of things have happened in the last few months. The situation with COVID-19 has undoubtedly
posed new challenges for many of us. Schools have switched to online learning and I am now working
fully remotely.&lt;/p&gt;
&lt;p&gt;While what happened is certainly not favorable by any means, I do think that it gives us a lot of
essential and transferable skills. The ability to deal with high levels of stress and move on
despite the difficulties is one of the most important skills one could acquire. I think it is also
interesting to think about the pandemic from the technological perspective. The pandemic would have
hit a lot harder if it happened twenty or even ten years ago. Now that pretty much everyone owns a
computer and has access to the internet, it is manageable to maintain social life. In other words,
it is just physical distancing that we have been practicing and not necessarily social distancing.&lt;/p&gt;
&lt;figure&gt;
  &lt;img src=&quot;data_visualization_tool.webp&quot; alt=&quot;Data visualization tool&quot; width=&quot;512&quot; height=&quot;250&quot; loading=&quot;lazy&quot;&gt;
  &lt;figcaption&gt;Data visualization tool&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;In regard to my internship, as the pandemic started its rapid emergence, some of our projects got
postponed/delayed and we started working on projects related to COVID-19 right away. For the past
few months, we have been fully dedicated to the COVID-19-related research and development. In the
first few days, Dr. Yanshan Wang and I automated COVID-19 screening process for Mayo nurses and
physicians, which ultimately saved a lot of precious time for medical personnel. Additionally, I
have been working on two big/major projects.&lt;/p&gt;
&lt;p&gt;The first project I worked on (with Dr. Feichen Shen) leveraged the AI-driven graph mining
techniques to assist COVID-19 knowledge discovery, which has the potential value for innovative
COVID-19 drug discovery. We also built a user-friendly
&lt;a rel=&quot;external&quot; href=&quot;https://oniani.org/covid-19-network&quot;&gt;web-based tool&lt;/a&gt; to visualize the data as well as support
link/relation prediction. The project that Dr. Shen and I worked on yielded promising results and
our manuscript was accepted by Journal of the American Medical Informatics Association (JAMIA), the
most prestigious journal in the domain of medical informatics.&lt;/p&gt;
&lt;p&gt;The other project (with Dr. Yanshan Wang) revolved around building a chatbot that answers questions
related to COVID-19. Additionally, we have been testing a number of state-of-the-art models and
embedding-generation techniques for performance comparison. We have almost finished drafting the
paper and will soon submit it to one of the top biomedical informatics conferences.&lt;/p&gt;
&lt;p&gt;Finally, my mentors have expressed enthusiastic support for extending my internship into full-time
summer work, so I am planning to stay here over the summer.&lt;/p&gt;
&lt;p&gt;We will beat this pandemic and come out stronger than ever before!&lt;/p&gt;
&lt;p&gt;Stay safe and stay strong!&lt;/p&gt;
&lt;p&gt;The original blogpost is located on the &lt;a rel=&quot;external&quot; href=&quot;https://www2.luther.edu/long-term-blogs/rochester/?story_id=911867&quot;&gt;Luther College Rochester Blog&lt;/a&gt;.&lt;/p&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>Mayo Clinic: First Impressions</title>
        <published>2020-03-24T00:00:00+00:00</published>
        <updated>2020-03-24T00:00:00+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://oniani.org/blog/mayo-clinic-first-impressions/"/>
        <id>https://oniani.org/blog/mayo-clinic-first-impressions/</id>
        
        <content type="html" xml:base="https://oniani.org/blog/mayo-clinic-first-impressions/">&lt;p&gt;The first few weeks were full of orientations, trainings, mentor and supervisor meetings, and
project discussions. I got acquainted with some of the internal processes at Mayo, the general
employee workflow, and my workflow as a research and development intern. To maintain the quality
associated with the Mayo Clinic tradition, the clinic has a well-defined corporate culture. The work
environment is awesome. I am surrounded by really smart individuals who are passionate and
enthusiastic about the work that they do. I have learned a lot about both the history and the core
values of the clinic. As a side note, there is a wonderful documentary by Ken Burns that gives a
fascinating walk into the rich history of Mayo - it is titled The Mayo Clinic: Faith, Hope, Science.&lt;/p&gt;
&lt;figure&gt;
  &lt;img src=&quot;mayo_clinic_heritage_hall.webp&quot; alt=&quot;Mayo Clinic Heritage Hall&quot; width=&quot;512&quot; height=&quot;355&quot; loading=&quot;lazy&quot;&gt;
  &lt;figcaption&gt;Mayo Clinic Heritage Hall&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;My supervisor, Stephanie, has been very caring and supportive. Her comments and bits of advice have
been helpful and insightful, and she also does an excellent job of finding the right connections for
me. My mentors, Drs. Feichen Shen and Yanshan Wang, have been great learning resources and have
already made me familiar with several new artificial intelligence and informatics techniques. Per my
request, they got me engaged in two research projects. Since the projects involve state-of-the-art
approaches, I cannot disclose any further details at the time, but I hope to be able to reveal more
in the future.&lt;/p&gt;
&lt;p&gt;It is surprising how many of the research and development skills acquired at Luther are directly
applicable to my current work. I am thankful to professors Richard Merritt, Alan Zaring, and Roman
Yasinovskyy for their ardent support and help in building these skills. If you are a Luther student
reading this blog post, go find out about the exciting summer opportunities at Luther and do not
miss out on a wonderful journey called research!&lt;/p&gt;
&lt;p&gt;I am grateful for the opportunities that the program has provided to the students and am looking
forward to the new adventures to come!&lt;/p&gt;
&lt;p&gt;The original blogpost is located on the &lt;a rel=&quot;external&quot; href=&quot;https://www2.luther.edu/long-term-blogs/rochester/?story_id=905337&quot;&gt;Luther College Rochester Blog&lt;/a&gt;.&lt;/p&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>Privacy for the Web</title>
        <published>2020-01-03T00:00:00+00:00</published>
        <updated>2020-01-03T00:00:00+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://oniani.org/blog/privacy-for-the-web/"/>
        <id>https://oniani.org/blog/privacy-for-the-web/</id>
        
        <content type="html" xml:base="https://oniani.org/blog/privacy-for-the-web/">&lt;p&gt;Just wanted to make a few suggestions on improving the web privacy:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Lightweight Privacy (emphasis on usability and speed)
&lt;ul&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://www.mozilla.org/en-US/firefox/new/&quot;&gt;Firefox&lt;/a&gt; as the default browser
&lt;ul&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://bitwarden.com/&quot;&gt;Bitwarden&lt;/a&gt; for password management&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://ublockorigin.com/&quot;&gt;uBlock Origin&lt;/a&gt; to block ads (and other junk)&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://github.com/arkenfox/user.js&quot;&gt;arkenfox user.js&lt;/a&gt; for extra security&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://signal.org/&quot;&gt;Signal&lt;/a&gt; as a messenger&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://element.io/about&quot;&gt;Element&lt;/a&gt; for group chats and collaborations&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://protonmail.com/&quot;&gt;Protonmail&lt;/a&gt; for the email service&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Heavier Privacy (emphasis on privacy)
&lt;ul&gt;
&lt;li&gt;Use &lt;a rel=&quot;external&quot; href=&quot;https://www.torproject.org/&quot;&gt;Tor&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Super Advanced Privacy (stronger emphasis on privacy)
&lt;ul&gt;
&lt;li&gt;Do not use the web&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>The Essence of Programming: Functional Approach</title>
        <published>2018-11-25T00:00:00+00:00</published>
        <updated>2018-11-25T00:00:00+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://oniani.org/blog/the-essence-of-programming-functional-approach/"/>
        <id>https://oniani.org/blog/the-essence-of-programming-functional-approach/</id>
        
        <content type="html" xml:base="https://oniani.org/blog/the-essence-of-programming-functional-approach/">&lt;p&gt;This blogpost is a general overview of a rather underappreciated programming methodology called
functional programming. Throughout the blogpost, I will occasionally use the purely functional
programming language Haskell as well as an imperative-style programming language Python. I will be
assuming the knowledge of basic programming concepts such as variable assignment, arithmetic
operations, conditionals, functions, loops, and recursion.&lt;/p&gt;
&lt;p&gt;It is important to note that the blogpost is just an introduction to the paradigms in functional
programming and does not cover any of them in great detail.&lt;/p&gt;
&lt;h3 id=&quot;what-is-functional-programming&quot;&gt;&lt;a class=&quot;zola-anchor&quot; href=&quot;#what-is-functional-programming&quot; aria-label=&quot;Anchor link for: what-is-functional-programming&quot;&gt;What is Functional Programming?&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;As mentioned above, functional programming is just an approach to programming. Particularly, it
refers to programming using functions, hence the name &lt;strong&gt;functional programming&lt;/strong&gt;. To better
understand what it means for a programming language to be functional, let&#39;s make a short
side-by-side comparison of functional and, wildly popular, imperative style of programming languages
and then discuss the differences in more detail.&lt;/p&gt;
&lt;table&gt;&lt;thead&gt;&lt;tr&gt;&lt;th&gt;Imperative language&lt;/th&gt;&lt;th&gt;Functional language&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;Classes or structures are the first-class citizens&lt;/td&gt;&lt;td&gt;Functions are the first-class citizens&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;State changes are important&lt;/td&gt;&lt;td&gt;State changes are limited or non-existent&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Primary control flow: loops and conditionals&lt;/td&gt;&lt;td&gt;Primary control flow: function calls and recursion&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;h3 id=&quot;classes-vs-functions&quot;&gt;&lt;a class=&quot;zola-anchor&quot; href=&quot;#classes-vs-functions&quot; aria-label=&quot;Anchor link for: classes-vs-functions&quot;&gt;Classes VS Functions&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;The first comparison shows that, generally speaking, in the imperative languages (i.e., Python, C,
Java, etc.), variables (instances of classes or structures) dominate over all other objects. Thus,
imperative paradigm makes a clear distinction between variables and functions. On the other hand, in
functional programming languages, functions are the first-class citizens making virtually everything
else rank below them.&lt;/p&gt;
&lt;p&gt;Imperative programming languages treat variables as data, while functions are generally used just to
manipulate variables or generate data. When programming in a functional language, we say that
functions are very similar to variables. In fact, we say that they are no different than variables
as they not only manipulate the data, but also represent the data themselves. Thus, in the
functional world, we say that the piece of code like a function is also data.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;There is a term describing a language if a program written in it can be manipulated as data. This
quality is referred to as &lt;a rel=&quot;external&quot; href=&quot;https://en.wikipedia.org/wiki/Homoiconicity&quot;&gt;homoiconicity&lt;/a&gt; and such
languages are called homoiconic. One of such languages is
&lt;a rel=&quot;external&quot; href=&quot;https://en.wikipedia.org/wiki/Lisp_(programming_language)&quot;&gt;Lisp&lt;/a&gt;. And, based on our discussion
points, it is not very surprising that Lisp is a functional language.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;I will give you a concise proof of why functions are data. Remember the table representations of
functions we learned at some point in the elementary school? That&#39;s the proof! Any function can be
represented as a table of values. For instance, consider a function \( f(x) = 2x \). The following
will be a table representation of the function.&lt;/p&gt;
&lt;table&gt;&lt;thead&gt;&lt;tr&gt;&lt;th&gt;\(x\)&lt;/th&gt;&lt;th&gt;0&lt;/th&gt;&lt;th&gt;1&lt;/th&gt;&lt;th&gt;2&lt;/th&gt;&lt;th&gt;3&lt;/th&gt;&lt;th&gt;4&lt;/th&gt;&lt;th&gt;5&lt;/th&gt;&lt;th&gt;6&lt;/th&gt;&lt;th&gt;...&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;\(f(x)\)&lt;/td&gt;&lt;td&gt;0&lt;/td&gt;&lt;td&gt;1&lt;/td&gt;&lt;td&gt;4&lt;/td&gt;&lt;td&gt;6&lt;/td&gt;&lt;td&gt;8&lt;/td&gt;&lt;td&gt;10&lt;/td&gt;&lt;td&gt;12&lt;/td&gt;&lt;td&gt;...&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;p&gt;Looks more like data? That&#39;s because it is the data! We have effectively generated a 2-column table
where each of the cells has a certain value. And yes, this is very similar to SQL tables and pandas
data frames.&lt;/p&gt;
&lt;h3 id=&quot;natural-outcomes&quot;&gt;&lt;a class=&quot;zola-anchor&quot; href=&quot;#natural-outcomes&quot; aria-label=&quot;Anchor link for: natural-outcomes&quot;&gt;Natural Outcomes&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;Because functions are so important, there are natural outcomes which are shared among most of
functional languages.&lt;/p&gt;
&lt;p&gt;Let&#39;s write a Haskell function to find the factorial of a positive integer.&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #E1E4E8; background-color: #24292E;&quot; &gt;&lt;code data-lang=&quot;haskell&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;-- | A function to find the factorial of a positive integer&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;factorial x &lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span&gt; product [&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;..&lt;/span&gt;&lt;span&gt;x]&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;  -- easy as that&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The function builds a list of integers from 1 up to x and then calculates the product of these
elements. This way we effectively get a product \( 1 \times 2 \times 3 .. \times \ x \) which is
the same as \( x! \). Since we now have a function, we can call it with the actual parameters!&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #E1E4E8; background-color: #24292E;&quot; &gt;&lt;code data-lang=&quot;haskell&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;print (factorial &lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;  -- prints out 1&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;print (factorial &lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;6&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;  -- prints out 720&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;print (factorial &lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;9&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;  -- prints out 362880&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As shown above, something that in imperative languages would require importing modules, looping,
etc. is a single line in Haskell. This is one of the outcomes of functions being first-class
citizens. Most functional languages have a rich pool of built-in/predefined functions that help
manipulate data. In the example above, we also see a very interesting notation. Namely, &lt;code&gt;[1..x]&lt;/code&gt;
which builds up a list of integers from 1 up to \( x \) (\( x \) must also be an integer such
that \( x \geq 1 \)). Thus, another outcome is that data structures and collections can be created
very easily, usually just in a single line of code, leaving more time for the programmer to deal
with functions and the logic. These are some of the reasons why functional languages are so concise.&lt;/p&gt;
&lt;h3 id=&quot;math-sets-and-haskell&quot;&gt;&lt;a class=&quot;zola-anchor&quot; href=&quot;#math-sets-and-haskell&quot; aria-label=&quot;Anchor link for: math-sets-and-haskell&quot;&gt;Math, Sets, and Haskell&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;Notice that in the factorial function above, I excluded the case when the function is called with
\( 0 \) (\( 0! = 1 \)). It was done on purpose so that now we are able to add some other
notation and explain the whole function in detail. Below is a better and more complete version of
the function.&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #E1E4E8; background-color: #24292E;&quot; &gt;&lt;code data-lang=&quot;haskell&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;-- | A function to find the factorial of a number&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt;factorial&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; :: Integer -&amp;gt; Integer&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;factorial &lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;0&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 1&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;factorial x &lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span&gt; product [&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;..&lt;/span&gt;&lt;span&gt;x]&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;::&lt;/code&gt; - prompts that it is a function declaration&lt;/p&gt;
&lt;p&gt;&lt;code&gt;Integer&lt;/code&gt; - type that can hold any number no matter how big, up to the limit of the machine&#39;s
memory.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;-&amp;gt;&lt;/code&gt; - tells either what is the type of the next formal parameter or what is the type of the output&lt;/p&gt;
&lt;p&gt;Looks similar to something you have seen before? If you have taken any undergraduate math class,
there is a chance that you&#39;ve encountered the following notation:&lt;/p&gt;
&lt;p&gt;\[ f : A \rightarrow B : x \mapsto y \]&lt;/p&gt;
&lt;p&gt;The notation above describes a simple function that takes an input from set \( A \) and maps it to
the output in the set \( B \).&lt;/p&gt;
&lt;p&gt;Here is the complete definition of the factorial function that we saw above:&lt;/p&gt;
&lt;p&gt;\[ f : \mathbb{Z}^+ \cup \{ 0 \} \rightarrow \mathbb{Z}^+ : x \mapsto x! \]&lt;/p&gt;
&lt;p&gt;Haskell defines in the similar fashion.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;factorial :: Integer -&amp;gt; Integer&lt;/code&gt; says that &lt;code&gt;factorial&lt;/code&gt; is a function that takes an element from the
set of integers and maps it to some other element in the set of integers. As opposed to math,
however, Haskell does not use \( \mapsto \) notation and instead has the statements below the
definition.&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #E1E4E8; background-color: #24292E;&quot; &gt;&lt;code data-lang=&quot;haskell&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;factorial &lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;0&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 1&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;factorial x &lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span&gt; product [&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;..&lt;/span&gt;&lt;span&gt;x]&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The code above is equivalent to saying that if the element is 0, map it to 1 and in all other cases,
map it to the product from 1 up to the element.&lt;/p&gt;
&lt;h3 id=&quot;state-changes-and-functional-programming&quot;&gt;&lt;a class=&quot;zola-anchor&quot; href=&quot;#state-changes-and-functional-programming&quot; aria-label=&quot;Anchor link for: state-changes-and-functional-programming&quot;&gt;State Changes and Functional Programming&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;Functional languages have a limited notion of state and typically, avoid the shared mutable state at
any cost. &lt;strong&gt;Purely&lt;/strong&gt; (see &lt;a href=&quot;https://oniani.org/blog/the-essence-of-programming-functional-approach/#purely-functional-languages&quot;&gt;Purely Functional Languages&lt;/a&gt;) functional
languages like Haskell, do not have any state at all. Since there are no changes in state, there are
no mutable variables. Instead, functional languages offer functions and immutable variables.&lt;/p&gt;
&lt;p&gt;To make it clear, let&#39;s look at two examples below. One is from Python and the other is from
Haskell.&lt;/p&gt;
&lt;p&gt;Python example&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #E1E4E8; background-color: #24292E;&quot; &gt;&lt;code data-lang=&quot;python&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;# Define a variable &amp;#39;my_number&amp;#39; and assign it to 3&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;my_number&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 3&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;# Increment the variable &amp;#39;my_number&amp;#39; by 1 and reassign it to the result&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;my_number&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; +=&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 1&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;print&lt;/span&gt;&lt;span&gt;(my_number)&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;  # Prints out 4&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Let&#39;s repeat the same steps in Haskell.&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #E1E4E8; background-color: #24292E;&quot; &gt;&lt;code data-lang=&quot;haskell&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;myNumber &lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 3&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;    -- Define a variable &amp;#39;myNumber&amp;#39; and assign it to 3&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;myNumber &lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;+=&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 1&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;   -- Haskell gags here (infinite loop)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;print myNumber  &lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;-- This statement is not reachable&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Looking at the code above, you might have already noticed that Haskell does not allow for changing
the state of the program. Now, you might be wondering how could one increment variables.&lt;/p&gt;
&lt;p&gt;Here is a short answer:&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #E1E4E8; background-color: #24292E;&quot; &gt;&lt;code data-lang=&quot;haskell&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;myNumber &lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 3&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;                  -- Define a variable &amp;#39;myNumber&amp;#39; and assign it to 3&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;myOtherNumber &lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span&gt; myNumber &lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;+&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 1&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;  -- Define a variable &amp;#39;myOtherNumber&amp;#39; and assign it to &amp;#39;myNumber&amp;#39;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;myNumber &lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span&gt; myOtherNumber      &lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;-- Redefine &amp;#39;myNumber&amp;#39; and set it to &amp;#39;myOtherNumber&amp;#39;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;print myNumber                &lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;-- Prints out 4&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Longer and better answer&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;You do not really need such increments or decrements in functional programming languages. You can
easily overcome this hindrance through functions and recursion. Therefore, instead of mutating
objects, we use recursion to gradually get to the target.&lt;/p&gt;
&lt;p&gt;Here is the example of how one could translate a well-known accumulator pattern from Python to
Haskell.&lt;/p&gt;
&lt;p&gt;Here is a classic Python accumulator pattern:&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #E1E4E8; background-color: #24292E;&quot; &gt;&lt;code data-lang=&quot;python&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;# An accumulator pattern approach for finding&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;# the sum of the first 100 positive integers.&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;total&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 0&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;for&lt;/span&gt;&lt;span&gt; integer&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; in&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; range&lt;/span&gt;&lt;span&gt;(&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 101&lt;/span&gt;&lt;span&gt;):&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;    total&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; +=&lt;/span&gt;&lt;span&gt; integer&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;print&lt;/span&gt;&lt;span&gt;(total)&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;  # Prints out 5050&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here is what it looks like in Haskell:&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #E1E4E8; background-color: #24292E;&quot; &gt;&lt;code data-lang=&quot;haskell&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;accumulator &lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 1&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;                        -- The base case for the recursion&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;accumulator x &lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span&gt; x &lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;+&lt;/span&gt;&lt;span&gt; accumulator (x &lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;-&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 1&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;  -- The recursive case&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;main &lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span&gt; print (accumulator &lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;100&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;  -- Prints out 5050&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the code excerpt above, we did not use any loops. In fact, we could not use any loops because
functional languages do not support loops. Instead, we defined a function, used the recursion and
calculated the sum of the values through function calls.&lt;/p&gt;
&lt;blockquote&gt;
&lt;h4 id=&quot;side-note&quot;&gt;&lt;a class=&quot;zola-anchor&quot; href=&quot;#side-note&quot; aria-label=&quot;Anchor link for: side-note&quot;&gt;Side Note&lt;/a&gt;&lt;/h4&gt;
&lt;p&gt;In this particular case, we do not even need to implement the recursive accumulator pattern. All
we need to do is use the already predefined &lt;code&gt;sum&lt;/code&gt; function and so-called texas range list notation
that we have already seen (&lt;code&gt;[1..x]&lt;/code&gt;):&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #E1E4E8; background-color: #24292E;&quot; &gt;&lt;code data-lang=&quot;haskell&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;print (sum [&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;..&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;100&lt;/span&gt;&lt;span&gt;])&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;  -- Prints out 5050&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/blockquote&gt;
&lt;h3 id=&quot;control-flow&quot;&gt;&lt;a class=&quot;zola-anchor&quot; href=&quot;#control-flow&quot; aria-label=&quot;Anchor link for: control-flow&quot;&gt;Control Flow&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;As we have already seen, there are no for loops or while loops in functional programming languages
and there are good reasons why. Let&#39;s list a few of them and continue our discussion by elaborating
on those reasons.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Functional languages are declarative.&lt;/li&gt;
&lt;li&gt;Most of functional languages are heavily influenced by lambda calculus.&lt;/li&gt;
&lt;li&gt;If you were to implement a functional programming language,
you would yourself get rid of loops.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;functional-languages-are-declarative&quot;&gt;&lt;a class=&quot;zola-anchor&quot; href=&quot;#functional-languages-are-declarative&quot; aria-label=&quot;Anchor link for: functional-languages-are-declarative&quot;&gt;Functional Languages Are Declarative&lt;/a&gt;&lt;/h4&gt;
&lt;p&gt;For those who are new to the idea of declarative languages, let&#39;s first discuss what it means for a
language to be declarative. Here is a simple definition:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Declarative programming is a method of programming that abstracts away the control flow for logic
required for performing an action, and instead involves stating the task or desired outcome.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;The examples of declarative languages are SQL, Haskell, Prolog etc.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Example 1&lt;/strong&gt;: Consider the SQL querying language. In SQL, one doesn&#39;t describe what how to get the
data. One just tells SQL what data is needed, and SQL engine figures out the best way to get it.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Example 2&lt;/strong&gt;: A better example might be comparing two implementations of a simple function. Let&#39;s
implement them in both Python and Haskell.&lt;/p&gt;
&lt;p&gt;The function takes a list of integers and returns the sum of odd integers in it.&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #E1E4E8; background-color: #24292E;&quot; &gt;&lt;code data-lang=&quot;python&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;def&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt; odd_sum&lt;/span&gt;&lt;span&gt;(list_of_integers):&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;    &amp;quot;&amp;quot;&amp;quot;Returns the sum of all odd integers in the list.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;    total&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 0&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;    for&lt;/span&gt;&lt;span&gt; integer&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; in&lt;/span&gt;&lt;span&gt; list_of_integers:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;        if&lt;/span&gt;&lt;span&gt; integer&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; %&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 2&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; ==&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 1&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;            total&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; +=&lt;/span&gt;&lt;span&gt; integer&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;    return&lt;/span&gt;&lt;span&gt; total&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;print&lt;/span&gt;&lt;span&gt;(odd_sum([&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 2&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 3&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 4&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 5&lt;/span&gt;&lt;span&gt;]))&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;  # Prints out 9&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Let&#39;s do a shallow analysis of the &lt;code&gt;odd_sum&lt;/code&gt; function. As seen above, it starts by declaring a
variable &lt;code&gt;total&lt;/code&gt; which is initially set to 0. Then, we iterate over the list and through each
iteration, we check if the integer is odd and if it is, we add it to &lt;code&gt;total&lt;/code&gt;. In the end, we return
the &lt;code&gt;total&lt;/code&gt; variable.&lt;/p&gt;
&lt;p&gt;Now, that we have analyzed the function a bit, notice that in the for loop, through each iteration,
we are giving Python directions when to add the integer to &lt;code&gt;total&lt;/code&gt; (only if it is odd). Thus, &lt;strong&gt;we
tell Python what to do step-by-step&lt;/strong&gt;. This is an important characteristic that distinguishes
non-declarative languages from declarative ones.&lt;/p&gt;
&lt;p&gt;Let&#39;s now look at the Haskell example.&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #E1E4E8; background-color: #24292E;&quot; &gt;&lt;code data-lang=&quot;haskell&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;oddSum x &lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span&gt; sum (filter odd x)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;main &lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span&gt; print (oddSum [&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;2&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;3&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;4&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;5&lt;/span&gt;&lt;span&gt;])&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;  -- Prints out 9&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Notice what we did here. First we defined a function &lt;code&gt;oddSum&lt;/code&gt; which takes a list. Then we used the
function &lt;code&gt;filter&lt;/code&gt; (happened to be predefined) in conjunction with another predefined function &lt;code&gt;odd&lt;/code&gt;
(returns true if the value is odd an false otherwise) to get the list of odd integers. Finally, we
summed up all the odd integers and got the result.&lt;/p&gt;
&lt;p&gt;See the difference? In Python, we used a for loop and through each iteration, we told Python whether
to add the integer it to &lt;code&gt;total&lt;/code&gt; or not. In Haskell, however, we gave a whole list to the function
and told it to just remove all of the even integers from the list and then to sum up the rest (if
you eliminate all the even integers, you are obviously left with all the odd integers). In other
words, in the Haskell example, we do not care how the functions &lt;code&gt;sum&lt;/code&gt; and &lt;code&gt;filter&lt;/code&gt; work internally,
we only care about the fact that they do their job - sum up the odd numbers in the list and return
the value.&lt;/p&gt;
&lt;h4 id=&quot;functional-programming-and-lambda-calculus&quot;&gt;&lt;a class=&quot;zola-anchor&quot; href=&quot;#functional-programming-and-lambda-calculus&quot; aria-label=&quot;Anchor link for: functional-programming-and-lambda-calculus&quot;&gt;Functional Programming And Lambda Calculus&lt;/a&gt;&lt;/h4&gt;
&lt;p&gt;Lambda calculus (also written as \( \lambda \)-calculus) is a branch of mathematics which was
developed by &lt;a rel=&quot;external&quot; href=&quot;https://en.wikipedia.org/wiki/Alonzo_Church&quot;&gt;Alonzo Church&lt;/a&gt; in the 1930s. It is a
formal system for expressing computation and an alternative to what&#39;s called &lt;a rel=&quot;external&quot; href=&quot;https://en.wikipedia.org/wiki/Turing_machine&quot;&gt;Turing
machine&lt;/a&gt; which was introduced by &lt;a rel=&quot;external&quot; href=&quot;https://en.wikipedia.org/wiki/Alan_Turing&quot;&gt;Alan
Turing&lt;/a&gt;. Turing machines involve loops and other
non-declarative approaches (Turing machines are the inspiration for programming languages like Java,
Python, etc). A few years later, Church and Turing collaboratively wrote a paper which is now know
as the &lt;a rel=&quot;external&quot; href=&quot;https://en.wikipedia.org/wiki/Church%E2%80%93Turing_thesis&quot;&gt;computability thesis&lt;/a&gt; and proved
that all the computation that was done using Turing machines could effectively be done in lambda
calculus as well. Hence, simply put, lambda calculus has the power equivalent to that of Turing
machines. Not too long after, people decided to base programming languages on the ideas in lambda
calculus (it was just as powerful as Turing machines so why not?!). This led to shared
characteristics among functional languages such as lack of loops. Virtually all functional
programming languages have no loops because lambda calculus has no loops. One could certainly add
loops, but they would have been redundant. Instead, functional languages use a mathematical idea of
recursion. This is the part of the reason why loops are not that appreciated in the functional
world.&lt;/p&gt;
&lt;h4 id=&quot;getting-rid-of-loops&quot;&gt;&lt;a class=&quot;zola-anchor&quot; href=&quot;#getting-rid-of-loops&quot; aria-label=&quot;Anchor link for: getting-rid-of-loops&quot;&gt;Getting Rid of Loops&lt;/a&gt;&lt;/h4&gt;
&lt;p&gt;Despite the fact that sometimes they are very useful, loops must not be a part
of a functional programming language. There are several reasons for this.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Loops are imperative, prompting the language what to do.&lt;/li&gt;
&lt;li&gt;Loops usually involve mutating values which is, once again, against functional virtues.&lt;/li&gt;
&lt;li&gt;Even if we did not use it imperatively and not mutate values, it would create unnecessary
redundance in a language with the emphasis on recursion (which is just as powerful as a
regular loop!)&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id=&quot;purely-functional-languages&quot;&gt;&lt;a class=&quot;zola-anchor&quot; href=&quot;#purely-functional-languages&quot; aria-label=&quot;Anchor link for: purely-functional-languages&quot;&gt;Purely Functional Languages&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;You might have seen word &lt;strong&gt;pure&lt;/strong&gt; in the beginning of the blogpost where I mentioned that Haskell is
&lt;strong&gt;purely&lt;/strong&gt; functional programming language. However, I never defined what it means for a functional
language to be pure. So let&#39;s do it now!&lt;/p&gt;
&lt;p&gt;Those who read the &lt;a href=&quot;https://oniani.org/blog/the-essence-of-programming-functional-approach/#math-sets-and-haskell&quot;&gt;Math, Sets, and Haskell&lt;/a&gt;, remember the math notation for
functions? I will use them to take the mystery out of this concept of being &lt;strong&gt;pure&lt;/strong&gt;!&lt;/p&gt;
&lt;p&gt;Suppose we have a function \( f : \mathbb{Z} \rightarrow \mathbb{Z} \). Then by just looking at
the function, we see that it takes an input from a set of integers and its output is also in the set
of integers. In other words, function \( f \) cannot take inputs like -1.9, 0.2, 12.7 etc. as well
as it cannot give an output like 12.6, 71.9, -9.1 etc. Its input(s) and output(s) could &lt;strong&gt;only&lt;/strong&gt; be
integers.&lt;/p&gt;
&lt;p&gt;Now, let&#39;s actually make this dull function \( f \) do something. Consider the function \( f :
\mathbb{Z} \rightarrow \mathbb{Z} : x \mapsto 2x \). Thus, we have a function which does a fairly
straightforward thing: takes an integer and maps it to twice its value (which will also be an
integer). Let&#39;s now look at the Haskell implementation of this function&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #E1E4E8; background-color: #24292E;&quot; &gt;&lt;code data-lang=&quot;haskell&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;-- | A function that takes an input and outputs twice its value&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt;f&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; :: Integer -&amp;gt; Integer&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;f x &lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 2&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; *&lt;/span&gt;&lt;span&gt; x&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The function above says that the input (corresponds to the &lt;code&gt;Integer&lt;/code&gt; before the arrow) is always an
integer and the output (corresponds to the &lt;code&gt;integer&lt;/code&gt; after the arrow) is also an integer. &lt;strong&gt;Hence,
we always know what type is the input and what type is the output.&lt;/strong&gt; In fact, we also know that the
if we call a function with say 5, we will always get the same result. Namely, &lt;code&gt;f 5 = 10&lt;/code&gt;. Hence, we
got that input(s) and output(s) are always integers and the function called with same actual
parameters always return the same value! This is what makes Haskell a purely functional language.
&lt;strong&gt;At any given point in time, we always know what is the type of input and what is type of output.
Besides, we know that the function called with the same actual parameter(s), always returns the same
value&lt;/strong&gt;. Such functions virtually never produce side effects since we already know what to expect
for a given input. &lt;strong&gt;Such functions are called pure!&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;To further demystify this idea, let&#39;s look at the following piece of code:&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #E1E4E8; background-color: #24292E;&quot; &gt;&lt;code data-lang=&quot;python&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;An example of a function that is pretending to be pure.&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;import&lt;/span&gt;&lt;span&gt; random&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;def&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt; numgen&lt;/span&gt;&lt;span&gt;(val:&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; int&lt;/span&gt;&lt;span&gt;) -&amp;gt;&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; int&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;    &amp;quot;&amp;quot;&amp;quot;Generates a number.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;    return&lt;/span&gt;&lt;span&gt; val&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; +&lt;/span&gt;&lt;span&gt; random.randint(&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;1&lt;/span&gt;&lt;span&gt;, val)&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; %&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; 3&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;def&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt; main&lt;/span&gt;&lt;span&gt;() -&amp;gt;&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; None&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;    &amp;quot;&amp;quot;&amp;quot;Test the number generation.&amp;quot;&amp;quot;&amp;quot;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;    print&lt;/span&gt;&lt;span&gt;(&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;f&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;Returns &lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;{&lt;/span&gt;&lt;span&gt;numgen(&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;7&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;}&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;  # Prints out 8&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;    print&lt;/span&gt;&lt;span&gt;(&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;f&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;Returns &lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;{&lt;/span&gt;&lt;span&gt;numgen(&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;7&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;}&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;  # Prints out 8&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;    print&lt;/span&gt;&lt;span&gt;(&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;f&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;Returns &lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;{&lt;/span&gt;&lt;span&gt;numgen(&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;7&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;}&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt;&amp;quot;&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;  # Prints out 7&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt; __name__&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; ==&lt;/span&gt;&lt;span style=&quot;color: #9ECBFF;&quot;&gt; &amp;quot;__main__&amp;quot;&lt;/span&gt;&lt;span&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;    main()&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here, we defined a function that takes an integer value as an input and it seems like the output is
also an integer. We now might be lured into thinking that function &lt;code&gt;numgen&lt;/code&gt; gives the same output
for the same input, but that is clearly not the case here. Let&#39;s take a closer look at what the
function does. It takes an integer value and returns the value plus some random number which is 0, 1
or 2. When we first called the function with the actual parameter 7, we got 8 as an output. The
second time, we got 8 again. The third time however, we got 7. Hence, for the third time, the output
was not the same. Therefore, the function is not pure.&lt;/p&gt;
&lt;p&gt;You now might wondering why I could not do the same trick in Haskell. In fact, I certainly can.
However, in Haskell, such function would not have a type &lt;code&gt;Int&lt;/code&gt;. It would have a type &lt;code&gt;IO Int&lt;/code&gt;. &lt;code&gt;IO&lt;/code&gt;
is usually associated with file input / output and it is reasonable that it is associated with
functions that are not always &quot;truthful&quot; as File I/O could in fact be one of the nastiest
experiences for a programmer. So many things can go wrong! (e.g., writing to a file which was
deleted, reading from a file on a USB which was ejected, writing a file that was moved to some other
directory etc). Thus, when we deal with uncertainty (which usually comes with side effects), Haskell
warns us by using the &lt;code&gt;IO&lt;/code&gt; notation:&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #E1E4E8; background-color: #24292E;&quot; &gt;&lt;code data-lang=&quot;haskell&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;{-&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;Example of a function that if called with the same argument,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;does not always return the same result.&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;-}&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;import&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt; System.Random&lt;/span&gt;&lt;span&gt; (&lt;/span&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt;randomRIO&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #B392F0;&quot;&gt;notAPureFunction&lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt; :: Int -&amp;gt; IO Int&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;notAPureFunction value &lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;= do&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;    randomValue &lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;&amp;lt;-&lt;/span&gt;&lt;span&gt; randomRIO (&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;0&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;2&lt;/span&gt;&lt;span&gt;)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;    return (value &lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;+&lt;/span&gt;&lt;span&gt; randomValue)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;main &lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;= do&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;    x &lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;&amp;lt;-&lt;/span&gt;&lt;span&gt; notAPureFunction &lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;7&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;    print x                  &lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;-- Prints out 9&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;    x &lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;&amp;lt;-&lt;/span&gt;&lt;span&gt; notAPureFunction &lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;7&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;    print x                  &lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;-- Prints out 7&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;    x &lt;/span&gt;&lt;span style=&quot;color: #F97583;&quot;&gt;&amp;lt;-&lt;/span&gt;&lt;span&gt; notAPureFunction &lt;/span&gt;&lt;span style=&quot;color: #79B8FF;&quot;&gt;7&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;    print x                  &lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;-- Prints out 9&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Take a look at the Haskell code above. You can disregard all the notational fluff. Just look at the
return type of the function &lt;code&gt;notAPureFunction&lt;/code&gt;. It is &lt;code&gt;IO Int&lt;/code&gt;! In other words, Haskell informs us
that the function might have side effects.&lt;/p&gt;
&lt;p&gt;Finally, we can have a rough definition of a pure functional language:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;A functional language is pure if and only if the user is informed about all side effects or there
are no side effects at all.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;In fact, Haskell did not even allow random values back in 1990s when its development was first
launched. Furthermore, there was no notion of File IO either and writing to files was done using
shell redirection commands (i.e., &lt;code&gt;runhaskell Program.hs &amp;gt; out.txt&lt;/code&gt;). Because of this, Haskell was
considered useless for all practical purposes. Eventually, engineers and the Haskell committee
decided to change the direction of Haskell. In lieu of getting rid of all the side effects, they
decided to control the side effects and created a more &quot;regulated&quot; programming environment.&lt;/p&gt;
&lt;h3 id=&quot;conclusion&quot;&gt;&lt;a class=&quot;zola-anchor&quot; href=&quot;#conclusion&quot; aria-label=&quot;Anchor link for: conclusion&quot;&gt;Conclusion&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;Functional programming languages are different from imperative ones. Most of them are based on ideas
in lambda calculus. Functional languages are the proper subset of declarative languages. There are
no loops and recursion is used instead. Changes in state are non-existent and therefore, all the
variables are immutable. Functional languages usually have a lot of predefined functions to make it
easy for a programmer to solve problems. Most of functional languages are also very concise,
minimizing the time spent on coding and leaving more time for the logic. Pure functional languages
are the proper subset of functional languages. Purely functional languages go a long way to inform
the user about potential side effects.&lt;/p&gt;
&lt;h3 id=&quot;how-to-get-started-with-functional-programming&quot;&gt;&lt;a class=&quot;zola-anchor&quot; href=&quot;#how-to-get-started-with-functional-programming&quot; aria-label=&quot;Anchor link for: how-to-get-started-with-functional-programming&quot;&gt;How to Get Started with Functional Programming?&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;There are lots of functional languages. One will obviously have to decide which one to learn first.
My recommendation would be learning Haskell. It is a purely functional programming language which
has most of (if not all) functional ideas in it. Besides,
&lt;a rel=&quot;external&quot; href=&quot;https://en.wikipedia.org/wiki/Simon_Peyton_Jones&quot;&gt;SPJ&lt;/a&gt; dedicates most of his time on extending
the language and adding new features to it. So if there is something new and interesting in the
functional programming world, Haskell will likely adopt it.&lt;/p&gt;
&lt;p&gt;After learning one functional language, it is not all that difficult to transition to the other.
Being familiar with one functional language automatically makes one somewhat familiar with others.
Hence, a good understanding of Haskell will make it easy to learn languages such as Rust, Scheme,
etc.&lt;/p&gt;
&lt;p&gt;To get started, visit the &lt;a rel=&quot;external&quot; href=&quot;https://www.haskell.org/documentation&quot;&gt;Haskell Documentation&lt;/a&gt; page which
is full of various educational resources.&lt;/p&gt;
</content>
        
    </entry>
</feed>
