Zero Labs
Industry News / AI

Beyond Words: The Secret Math Behind How LLMs “Read”

Source · Towards AI By Gaurav Bhardwaj

From the publisher’s feed, collected in the ZeroLabs newsroom.

Ever wondered how an LLM like ChatGPT transforms a simple sentence into a sophisticated response? It doesn’t see “words” — it sees a multidimensional universe of numbers. If you want to build an AI from scratch, you first have to master the Input Pipeline.Here is the step-by-step journey of a word from raw text to a high-powered vector.Step 1: The Shredder (Smart Tokenization)Machines can’t process a paragraph all at once. We must break text into “tokens.” While simple tokens are just words, modern LLMs use Byte Pair Encoding (BPE). This ensures that even if the AI sees a new word (like “Cyber-Quantum-Engine”), it can break it down into pieces it understands rather than crashing.import re# Slicing text into words and punctuation# (Note: Modern models use complex BPE libraries, but this regex shows the logic)input_text = "AI is evolving; are you?"tokens = re.split(r'([,.:;?_!"()\']|--|\s)', input_text)cleaned_tokens = [item.strip() for item in tokens if item.strip()]print(cleaned_tokens)# Result: ['AI', 'is', 'evolving', ';', 'are', 'you', '?']Step 2: The Digital Key (Vocabulary Mapping)Once we have our list of tokens, we need a “Dictionary.” We cannot pass strings like “AI” into a neural network. Every unique token must be assigned a unique integer ID.This transforms our sequence of text pieces into a sequence of numbers. Crucially, this is also where we inject Special Tokens. These are not words found in a sentence, but control signals for the model:[BOS] / : Marks the Beginning of Sequence (or document end).[PAD]: Used for padding sequences to the same length (vital for batching).[UNK]: A fallback for a token completely missing from the vocabulary.A visual map showing how tokens are assigned unique numerical keys.Here is what this mapping logic looks like:# A slightly simplified view of a real vocabulary pipelineinput_text = "AI is evolving; are you?"# 1. Tokenize (Assuming simplified BPE for this example)cleaned_tokens = ['AI', 'is', 'ev', 'olv', 'ing', ';', 'are', 'you', '?']# 2. Add Special Tokens manually to our master vocab listspecial_tokens = ["", "[PAD]", "[UNK]"]unique_tokens = special_tokens + sorted(list(set(cleaned_tokens)))# 3. Define the Mapping: Token String -> Unique IDtoken_to_id = {token: i for i, token in enumerate(unique_tokens)}# 4. Text to numbers:numeric_sequence = [token_to_id[t] for t in cleaned_tokens]print(f"Vocab Size: {len(token_to_id)}")print(f"Tokens: {cleaned_tokens}")print(f"IDs: {numeric_sequence}")# Result: IDs: [3, 6, 5, 7, 10, 0, 4, 11, 1] # (IDs are example values; BOS/PAD are likely 0, 1, etc.)Step 3: The Concept Space (Embeddings)This is the main event. A raw integer like ID 101 (e.g., "Robot") has no meaningful connection to ID 102 (e.g., "Human"). To the computer, they are just independent numbers.Embeddings are the secret sauce that injects meaning.Each integer ID is converted into a high-dimensional vector (a list of floating-point coordinates). A modern LLM might embed a single word into 768 or even 4096 dimensions.In this structured mathematical universe, concepts that are semantically similar (like “King” and “Queen”) will have vectors that are physically close to each other. Their vectors point in roughly the same direction.A 3D visualization of the vast “Concept Space.” Similar words cluster together in this high-dimensional coordinate system.Here is how we create this concept space using PyTorch:import torchimport torch.nn as nn# Parameters for our Embedding layervocab_size = 1000 # Let's say we have 1000 unique tokensembed_dim = 128 # Each token becomes a 128-dimensional vector# This layer is initialized with random numbers and *learns*# the correct coordinates during training.embedding_layer = nn.Embedding(vocab_size, embed_dim)# Input: A few token IDs from our vocabularytoken_ids = torch.tensor([10, 20, 30])# Output: The model retrieves the vector representation for each ID.vector_representation = embedding_layer(token_ids)print(f"Input Shape: {token_ids.shape}")print(f"Output Shape: {vector_representation.shape}")# Result: torch.Size([3, 128]) -> 3 words, each with 128 coordinates.The resulting vector_representation is now a raw semantic signature of those tokens. But there is one final problem.Step 4: The Timestamp (Positional Encoding)This is a subtle but absolutely essential step.LLMs (specifically Transformers) process all words in a single sentence simultaneously. This parallelism makes them fast, but it leaves them word-order blind. The model naturally would see the sentence “The dog bit the man” and “The man bit the dog” and treat them identically.To fix this, we introduce Positional Encoding. This is a special, manually constructed set of vectors where each vector represents a timestamp (e.g., “position 1,” “position 2,” etc.).We physically add this Positional Vector to the semantic Embedding Vector (from Step 3).The Embedding Vector says: “I am the concept of ‘dog’.”The Positional Vector says: “This is the 2nd token in the sentence.”The resulting sum is a new vector that carries both the definition of the token and its precise location in the input string.A technical schematic demonstrating how the “Semantic Vector” (blue) is physically added to the “Position Vector” (gold) to create the complete “Input Vector.” The mathematical addition retains the distinct visual signature of both.With Position injected, our input pipeline is complete.Step 5: The Learning Loop: Tensors, Batching, and the Sliding WindowThis is where the pipeline meets the training floor. Your single sentence is now a sequence of vectors, but the model doesn’t just process one sequence at a time. It uses Tensors (multi-dimensional grids of numbers) to handle stacks of sequences simultaneously.This is called Batching, and it is crucial for computational efficiency. The final “Input Tensor” for a model might look like this: [Batch Size x Sequence Length x Embedding Dimension].A visualization of a massive, layered 3D tensor grid. Four streams of sentence data vectors flow in, are structured into the grid, and are highlighted by a luminous white “Sliding Window” moving continuously across the data.To train the model to “predict the next token,” we use a Sliding Window approach (often called the Context Window).Look: We take a batch of complete vector sequences.Slide: We move our white sliding window ([Batch Size x Context Length x Embedding Dimension]) over a specific part of that data.Predict: The model looks only inside that window. It is shown the first four tokens of a sentence (Input $X$) and tasked with guessing the fifth token (Target $Y$).We do this millions of times, sliding the window across your data to generate millions of tiny “guess-the-next-word” puzzles.Here is what the code looks like:import torch# Our sample input: "AI is evolving; are you?" -> [3, 6, 5, 7, 10, 0, 4, 11, 1]# Assume we have expanded this into a tensor batch of vector sequences.# Final Input shape: [Batch_Size, Max_Sequence_Length, Embed_Dim]# Parameters for the sliding window/contextbatch_size = 12max_length = 512 # Context/Window Sizeembed_dim = 768# Example Training data (Dummy Batch)# A tensor filled with token databatch_input = torch.randn(batch_size, max_length, embed_dim)# The Sliding Window Operation is implicit during training:# We slice a smaller context window out of the larger sequence.context_length = 128training_window = batch_input[:, :context_length, :] # Looks at first 128 vectors in the batch# The 'Next-Token' puzzle:# Input (x): Vectors 1-127 (context) -> Target (y): Vector 128 (next word)train_x = training_window[:, :-1, :] # The first 127 vectorstrain_y = training_window[:, 1:, :] # The shifted targets (vectors 2-128)print(f"Batch Tensor Input Shape: {batch_input.shape}")print(f"Training Window Shape: {training_window.shape}")print(f"Input Data for Model (X): {train_x.shape}")print(f"Target Data for Model (Y): {train_y.shape}")ConclusionBuilding the input pipeline is 50% of the battle in modern AI development. When you understand how messy human language is shred into sub-units, indexed with a unique key, projected into semantically rich high-dimensional coordinates, stamped with a timestamp, and finally batched into massive tensor grids, you have demystified the process.This chain of transformation is the secret mathematical foundation upon which large language models are built. We give them the coordinate system they need to generate human-like text.Beyond Words: The Secret Math Behind How LLMs “Read” was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.