Thanksgiving DealsAmazon USThanksgiving week: Black Friday picks start earlyAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCThanksgiving DealsAmazon USDo not wait for the rush - compare today's dealsAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog

Mini Transformer From Scratch in NumPy: A Shape-by-Shape Code Walkthrough

By Freedom251 Team · · 11 min read

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

A mini Transformer from scratch is best understood as a compact NumPy teaching model: it turns integer token IDs into vectors, computes one self-attention head, and applies a small feed-forward transformation. It does not train, generate text, or reproduce the complete Transformer architecture. The walkthrough is useful because every matrix is visible, but its randomly initialized parameters do not encode language.

This guide traces the data and shapes through the example, explains what each operation means, shows how to inspect the attention matrix with six tokens, and separates the toy computation from the full architecture introduced in Attention Is All You Need.

As an Amazon Associate I earn from qualifying purchases.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What does this mini Transformer code actually do?

The example starts with a sequence of five integer token IDs. Those integers index rows in an embedding matrix, producing one vector per token. The vectors are projected into queries, keys, and values; query–key dot products become attention scores; a scaled softmax turns each score row into weights; and those weights mix the value vectors. A small feed-forward block then transforms the result at each position.

With the example settings, the vocabulary contains 10 possible tokens and the model dimension is 8. A five-token input therefore becomes an output array with shape (5, 8). The numbers are illustrative. Changing the sequence length changes the first dimension, while changing the embedding/model width changes the second.

Popular on Amazon
Sale
Silkland 40Gbps USB C 90 Degree Right Angle Adapter 2 Pack, 240W USB4 | Male to Female Extender, 8K@60Hz, Thunderbolt 4/3, Steam Deck, ROG Ally, MacBook, Switch 2, iPhone 18/17/16/15, Quest 3 VR
  • 【90 Degree Full Function USB C Adapter】Supports the latest USB4 standard for up to 40Gbps of bandwidth, 8K video support, and up to 240W Fast charging; Support USB PD 3.1 Extended Power Range (EPR) including 140W, 180W and 240W. Your productivity is easily doubled. *Warm Tip: For the best fit, please make sure the USB-C port is fully exposed; thick or bulky cases may affect compatibility.
  • 【Reliable Quality】Made from high-quality, scratch-resistant aluminum alloy, delicate metal frame. get excellent wear resistance and heat dissipation. Non-Slip Design for easier insertion and removal.
  • 【Small and portable】Ultra thin size, ultra compact design, a petite physique that matches the minimalist design of your modern laptops. Coming with a slim figure that won't block the port next to the one it's plugged into.
  • 【Compatibility】Widely work with most usb c, thunderbolt 4/3 devices. Compatibilit for ROG Ally, Steam Deck, Switch, MacBook Pro, Quest 3 VR headset, Surface Book 2, iPhone 18/17/16/15, Samsung Galaxy S23/S22/S21, Note 20/10, Google Pixel, ChromeBook, etc.
  • 【Excellence Customer Support】If you experience any issues or cable failure, simply reach out to our dedicated customer service team. We provide a prompt response within 18 hours, providing you with the necessary technical support to resolve any concerns.

Because the matrices are manually created and no optimization step updates them, the output is only a demonstration of the computation. It may look “contextual” because every output position can combine information from every value vector, but it is not a prediction, a sentence completion, or a trained language representation.

What do you need before running the walkthrough?

You need Python and NumPy. The code is intended for a notebook or a small script; no GPU, dataset, tokenizer, optimizer, or model checkpoint is required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Install NumPy in the environment where you will run the script: python -m pip install numpy.
  • Use a recent Python 3 interpreter and import NumPy as np.
  • Keep the token IDs in the range 0 through vocab_size - 1; an out-of-range ID cannot index the embedding table.

The token IDs stand in for an earlier tokenization step. In a real language system, a tokenizer maps text to IDs. This teaching example begins after that mapping and therefore says nothing about vocabulary design, subwords, punctuation handling, or unknown tokens.

How does embedding lookup turn token IDs into vectors?

An embedding table is a matrix with one row per vocabulary item. For a vocabulary size of 10 and model dimension of 8, its shape is (10, 8). If the input is [2, 5, 1, 7, 3], selecting those rows yields a matrix of shape (5, 8).

import numpy as np

vocab_size = 10
model_dim = 8
token_ids = np.array([2, 5, 1, 7, 3])

# Random values make the lookup mechanics visible; they are not learned here.
embedding = np.random.randn(vocab_size, model_dim)
x = embedding[token_ids]
print(x.shape)  # (5, 8)

Each row of x is the representation associated with one input position. The lookup is not a mathematical conversion from the integer’s magnitude: token ID 7 is not “more” of a word than token ID 2. The integer is simply an index.

In a trained model, gradient descent would adjust the embedding rows so that they become useful for the task. Here, no loss function or optimizer is present, so describing these rows as learned language features would be incorrect.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How are queries, keys, and values constructed?

Self-attention uses three projections of the same input matrix. Query and key vectors determine how strongly positions interact; value vectors carry the information that will be mixed. With an input of shape (5, 8), each projection matrix can preserve the width at 8, producing Q, K, and V with shape (5, 8).

Also popular on Amazon
Sale
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display | 85W Max PD, 1 Powered USB-C 5Gbps & 2 Powered USB-A 3.0 5Gbps Data Ports, for MacBook Pro, MacBook Air, Dell and More (Black)
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
W_q = np.random.randn(model_dim, model_dim)
W_k = np.random.randn(model_dim, model_dim)
W_v = np.random.randn(model_dim, model_dim)

Q = x @ W_q
K = x @ W_k
V = x @ W_v

print(Q.shape, K.shape, V.shape)  # (5, 8) (5, 8) (5, 8)

The row at position i in Q asks what that position is looking for. The corresponding row in K describes what it can be matched on, while the row in V is the content available to other positions. These are roles in one calculation, not three separate token types.

The matrices above are deliberately simple. A production implementation usually combines parameters into larger tensors, initializes them with a controlled scheme, and manages batches and multiple heads. The educational version keeps one matrix per projection so the shape changes are easy to inspect.

How does self-attention calculate its score matrix?

Each query is compared with every key using a dot product. Matrix multiplication computes all pairwise comparisons at once:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
scores = Q @ K.T
print(scores.shape)  # (5, 5)

The row index identifies the querying position and the column index identifies the key being considered. A large value means that, under these particular random projections, the query and key point in similar directions. It is a compatibility score, not a probability and not a human-readable explanation of the sentence.

The scores are divided by the square root of the model dimension:

scores = (Q @ K.T) / np.sqrt(model_dim)

Scaling keeps dot products from becoming excessively large as the vector width grows. Without scaling, softmax can become extremely peaked, which makes numerical behavior and gradient-based learning more difficult in a trained model. In this untrained sketch, the same formula illustrates the standard scaled-dot-product operation.

How does softmax turn scores into attention weights?

Softmax is applied across each score row, so every querying position receives a distribution over the five key positions. A numerically stable implementation subtracts the row maximum before exponentiating:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Also popular on Amazon
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter | 85W Max PD, 2 USB 3.0 & 1 USBC Data Ports, SD/TF Card Reader, for Laptops/Mac and Other Type C Devices (Charger Not Included)
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
def softmax_rows(matrix):
    shifted = matrix - np.max(matrix, axis=-1, keepdims=True)
    exp_values = np.exp(shifted)
    return exp_values / np.sum(exp_values, axis=-1, keepdims=True)

attention = softmax_rows(scores)
print(attention.shape)  # (5, 5)
print(attention.sum(axis=-1))  # approximately [1, 1, 1, 1, 1]

Each attention row sums to approximately 1. The entry at row i, column j is the weight that position i assigns to the value at position j. A row with nearly equal values blends all positions; a concentrated row relies mostly on one or two positions.

Softmax does not discover a universally correct linguistic relationship in this example. Since the parameters are random, any apparent concentration is a consequence of those particular arrays. In a trained Transformer, the projections and resulting distributions are shaped by the training objective.

How are value vectors mixed into contextualized representations?

The weighted sum is another matrix multiplication:

context = attention @ V
print(context.shape)  # (5, 8)

Every output row is a weighted combination of all five value rows. This is why the representation at one position can depend on the entire sequence, even though the input was represented one token at a time. The operation is often described as making representations contextual: the vector at a position reflects information gathered from other positions according to its attention weights.

“Contextualized” does not mean “understands the sentence” here. There is no objective teaching the weights what a word means, no position signal, and no trained parameter set. The calculation demonstrates the information-mixing mechanism only.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What does the feed-forward block add?

After attention, the example applies the same small feed-forward transformation independently to each sequence position. A typical two-layer form expands to a hidden width, applies a nonlinearity, then projects back to the model width:

hidden_dim = 16
W_1 = np.random.randn(model_dim, hidden_dim)
b_1 = np.zeros(hidden_dim)
W_2 = np.random.randn(hidden_dim, model_dim)
b_2 = np.zeros(model_dim)

hidden = np.maximum(0, context @ W_1 + b_1)  # ReLU
output = hidden @ W_2 + b_2
print(output.shape)  # (5, 8)

Broadcasting applies each bias vector to every row. The ReLU keeps positive activations and replaces negative ones with zero. Unlike attention, this block does not mix sequence positions: each row is transformed on its own. Attention handles communication between positions; the feed-forward network supplies per-position nonlinear processing.

The exact hidden width is a teaching choice. It need not be 16, and the model dimension need not be 8. If you change the widths, make sure the matrix dimensions line up and that the final projection returns to the model dimension expected by later layers.

Also popular on Amazon
Sale
BENFEI USB C Hub 5-in-1 with 4K HDMI(Certified), 100W Power Delivery, 3 USB-A, Silicone Cable, Aluminum Case Compatible with MacBook Pro/Air, iPad Pro, iMac, iPhone 15 Pro/Pro Max, XPS, Thinkpad
  • Portable and powerful USB-C HUB: BENFEI USB Type-C HUB, with super-soft and knot-free silicone woven design cable, meets most mobile office needs. Compact, lightweight, stylish, and powerful portable USB C Hub equipped with 1 x HDMI port, 1 x 100W charging, and 3 x USB ports. 18-month warranty, 24-hour response, to ensure you feel at ease when using our product.
  • Design centered on comfort and reliability: Thanks to BENFEI's end-to-end in-house cable production capability, in-house PCBA and assembly capability, using the industry's most advanced silicone woven design and process, 20cm cable in length, no knots, super-soft, the HUB is easy to use in all scenarios: laptop, tablet, stand etc. Super-soft, 25000+ life cycles, to meet your daily carrying and office needs.
  • 100W Charging: Support up to 90W USB C pass-through charging via Type-C port to keep your laptop powered. 10W is reserved for other interface operations. No data and video function on the Type-C port.
  • 4K HDMI Display: The HDMI port supports media display at resolutions up to 4K 30Hz, keeping every incredible moment detailed and ultra vivid. Please note that the C port of the Host device needs to support video output.
  • Transfer Files in Seconds: Transfer files and from your laptop at speeds up to 10 Gbps with USB A 3.2 port. Extra 2 USB A 2.0 ports are perfectly for your keyboards and mouse.

What is missing from a full Transformer?

The mini implementation intentionally leaves out several components that matter in a complete architecture:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Training: There is no target data, loss function, backpropagation, optimizer, or checkpoint. Nothing learns from the input.
  • Multiple attention heads: The example has one set of Q, K, and V projections. Full Transformer layers commonly split the model width across several heads so different projections can model different relationships.
  • Positional encoding: No vector tells the model where a token occurs. Without positional information, the attention calculation has no explicit order signal.
  • Residual connections: The sketch replaces one representation with the next result instead of adding skip connections around sublayers.
  • Normalization: Layer normalization is absent, so the numerical behavior differs from a standard Transformer block.
  • Masking and batching: There is no padding mask, causal mask, batch dimension, or variable-length batch handling.
  • Output head and decoding: The result is not projected to vocabulary logits, converted to probabilities, or decoded into text.

These omissions are deliberate, not bugs to silently overlook. The original Transformer paper describes an encoder–decoder sequence-transduction architecture built solely around attention, without recurrence or convolution; its design and experiments are documented in the paper. The NumPy sketch is not evidence that it reproduces that architecture or its results.

How does the mini sketch differ from the original Transformer?

Aspect Mini NumPy sketch Original Transformer context
Purpose Expose embedding, one-head attention, and a feed-forward calculation Sequence transduction for tasks such as machine translation
Parameters Manually created random arrays; no updates Trained parameters optimized on data
Attention One self-attention head Multi-head attention in encoder and decoder blocks
Position information None Positional information is part of the model design
Block infrastructure No residual paths or normalization Full layers include the surrounding architectural components
Output An array shaped like (sequence length, model dimension) Task outputs produced after training and decoding
Evidence Illustrative mechanics Published experimental results in the 2017 paper

The paper reports 28.4 BLEU on WMT 2014 English-to-German and 41.8 BLEU on WMT 2014 English-to-French, including the latter after 3.5 days of training on eight GPUs. Those are historical, paper-reported results from trained systems, not measurements of this random NumPy program and not a current leaderboard.

How do you inspect attention with six token IDs?

Replace the five-token input with six valid IDs, rerun the forward pass, and print the attention matrix. The matrix should have shape (6, 6): six query rows and six key columns.

  1. Change the input line, for example: token_ids = np.array([2, 5, 1, 7, 3, 4]).
  2. Run the embedding lookup and all subsequent operations again. The embedding output and final output should now have shape (6, 8) with the same model width.
  3. Print the matrix with a readable precision: np.set_printoptions(precision=3, suppress=True); print(attention).
  4. Check the row sums: print(attention.sum(axis=1)). Each should be approximately 1.
  5. For each row, identify the largest column. That column is the position receiving the greatest weight for that query under this particular initialization.

Describe what you actually observe rather than predicting a linguistic pattern. With random matrices, one run may show a sharp preference, while another may be flatter or emphasize different positions. If you want repeatable output for teaching, set a seed before creating arrays, such as np.random.seed(0); the seed makes the random demonstration reproducible, but it does not make the parameters trained.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Also remember that the matrix has no built-in causal restriction. Every query can attend to every key, including positions later in the sequence. A decoder used for left-to-right generation would normally apply a causal mask so a position cannot use future tokens.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Why can the code look plausible while still being unable to generate text?

The final array has the right kind of two-dimensional shape for a sequence representation, and attention rows sum to one, so the computation can look like a functioning model. But generation requires more: trained parameters, a vocabulary output projection that produces logits, a decoding strategy, and usually a causal attention mask. None of those are supplied here.

Also popular on Amazon
𝟒𝐏𝐚𝐜𝐤 𝐔𝐩𝐠𝐫𝐚𝐝𝐞𝐝 USB to USB C Adapter,Type-C Female to A Male Charger Converter for iPhone 18 Charger,iWatch Ultra SE 9 10,iPhone 17 Pro Max 16 15 14,Samsung S25,AirPods,iPad,Car,Xbox
  • 【Read before You Buy】 Note: This adapter is USB 2.0 version and cannot transmit HDM, VGA, or other video signals. Nevertheless, they are fully capable of charging devices,duplicating files, and can be seamlessly integrated with USB-C earphones, wireless network adapters, and SD card adapters.
  • 【Easy to Use and Safe】Thanks to modern manufacturing techniques, we've made these adapters sufficiently compact so that they can remain inserted in your device without noticeable protrusion or inconvenience. This means you don't have to constantly plug and unplug them, reducing the likelihood of wear and misalignment, and making them more convenient to carry around.
  • 【Reliable Quality】Engineered for enhanced durability, durable aluminum alloy shell material,get excellent wear resistance and heat dissipation,the male USB C and female USB connectors & the male USB and female USB C connectors are designed to be plugged and unplugged up to 20000 times. Provides data transfer, device charging, memory space expansion, and additional computer peripherals.
  • 【Think more for you】Do you need to connect a USB-C-enabled device to an odd device that only has USB-A ports? Then these USB-A male to USB-C female adapters are made for you.Simply insert the adapter into the USB-A port on the device, and you can instantly connect your USB-C device to the device that originally didn't have the correct connection port.
  • 【Trusted xiwxi Quality and Service】As a responsible brand seller, you will receive xiwxi's 12-month Quality assurance and lifetime friendly customer service, you're not just buying a product,you're investing in peace of mind with all-round quality and exceptional customer service.

There is also no semantic guarantee in a random output. Two runs with different random arrays can produce different attention patterns and values. The safe interpretation is operational: “this row is a weighted sum of those value rows,” not “the model recognized a noun, copied a subject, or learned a dependency.”

What should you use for a larger implementation?

Once the matrix mechanics are clear, a framework implementation can add batching, automatic differentiation, masks, multiple heads, normalization, residual paths, and training utilities. PyTorch documentation includes a tutorial titled “Language Modeling with nn.Transformer and torchtext,” but that page is marked deprecated, so verify the current API and recommended data pipeline before using it as an implementation guide: check the documentation page.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Move to a framework for engineering convenience, not because the NumPy sketch is secretly a small language model. The sketch remains valuable as a reference: when a framework tensor has an unexpected shape or an attention mask behaves strangely, the five-stage path—lookup, project, score, normalize, mix—provides a compact mental model for debugging.

What are the most common mistakes in this walkthrough?

  • Using an invalid token ID: Ensure every ID is an integer index below vocab_size.
  • Softmax over the wrong axis: Normalize across keys for each query row, not across the entire matrix.
  • Forgetting the transpose: The score operation is Q @ K.T; without the transpose, the pairwise dimensions do not represent query–key comparisons.
  • Mixing up scores and weights: Raw scores can be negative and do not sum to one. Only the row-wise softmax output is an attention distribution.
  • Expecting fixed output values: Random initialization changes the numbers. Compare shapes and invariants unless you deliberately set a seed.
  • Calling the output predictions: The returned vectors are representations. There are no vocabulary logits or decoded tokens.
  • Assuming order is encoded: This version has no positional encoding, so do not infer that it has learned sequence order.

What should you remember from the code?

The entire teaching path can be summarized as:

  1. Integer IDs select rows from an embedding table.
  2. Three projections create queries, keys, and values.
  3. Query–key dot products produce a score for every pair of positions.
  4. Scaling and row-wise softmax convert scores into weights.
  5. Weights mix value vectors into sequence-length-by-model-width representations.
  6. A per-position feed-forward block transforms those representations.

That sequence makes the mechanics visible without pretending to be a complete Transformer. It is a small, honest laboratory for shapes and matrix operations; the full architecture, training process, and translation results belong to the larger system described by Vaswani and colleagues, not to this untrained example.

Frequently Asked Questions

Can I use arbitrary integers as token IDs in the example?

Only if each integer is a valid row index in the embedding table. The IDs have no inherent numeric meaning, so changing an ID selects a different row rather than producing a proportionally different token.

Why do two runs produce different attention matrices?

The projection and embedding arrays are randomly initialized. Set a NumPy random seed before creating them to reproduce one demonstration, but reproducibility does not turn the arrays into learned parameters.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Does adding positional encoding make this a complete Transformer?

No. Positional information addresses only one omission. A fuller implementation also needs trained parameters, residual connections, normalization, multi-head attention, masking where appropriate, and an output or task-specific head.

What does an attention value of 0.8 mean?

It means that, for that query row and under the current parameters, roughly 80 percent of the weighted value mixture comes from that key position. It is not automatically a confidence score, explanation, or proof of a linguistic relationship.

Why does the six-token attention matrix have six columns?

Each column represents one key/value position in the six-token input. Every query compares itself with all six positions, so the pairwise score and weight matrices are six by six.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply. Prices as of November 23, 2026 11:29 am GMT+0530.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.