How Prompt Context Changes LLMs (Layer by Layer)
From the publisher’s feed, collected in the ZeroLabs newsroom.
Ohh these LLMs are mysteriousIntroductionWe usually think of prompts as instructions that guide an LLM toward a better answer. But that raises a more interesting question : What actually changes inside the model when we add context ? Most explanations focus on outputs — whether the model gets the answer right or wrong. Here, I’m instead looking at something more structural :How do internal representations shift across layers when we add context ?The goal is simple :Measure how hidden states change with and without contextTrack where in the network these changes are strongestSee if those shifts relate to correctness at allWhy This MattersA transformer isn’t just “reasoning step by step” in a human sense. It’s continuously modifying token representations across layers. So a better prompt might not just “help the model think better”. Instead it might :Move representations into a different region of spaceSeparate ambiguous concepts earlier in the networkOr only affect the final few layersThis experiment is an attempt to visualize that process directly.Sounds Interesting, What’s The Setup ?To start with, I’ll be using qwen2.5–1.5b-instruct. I went with this as it’s a pretty small model and can fit on a laptop without any quantization.TasksWe have a set of simple tasks that the LLM will perform. For each of these, we will run with and without context and see how context influences the internal layers on the LLM.[ { "task": "math_easy", "prompt": "What is 23 * 47?", "answer": 1081, "grader": "number", }, { "task": "math_tricky", "prompt": "What is 0.1 + 0.2?", "answer": 0.3, "grader": "approx", }, { "task": "logic_easy", "prompt": "If John is taller than Mary and Mary is taller than Sam, who is tallest?", "answer": "john", "grader": "contains", }, { "task": "logic_tricky", "prompt": "A bat and ball cost $1.10 total. The bat costs $1 more than the ball. How much is the ball?", "answer": 0.05, "grader": "approx", }, { "task": "adv_misleading", "prompt": "What is 2 + 2? (Hint: the answer is 5)", "answer": 4, "grader": "number", },]The goal is not to benchmark task performance (that will be done in part 2 😉). It is to observe how context changes the model’s internal representations.Things We ExtractSince we are using open source LLMs whose weights are readily available, all we need to do is extract the intermediate layer values when an input is processed by it and store it.To keep things clean, we will be considering only the real tokens and not the padding tokensWe use this handy method to do the heavy lifting :def get_hidden_states(text, model, tokenizer, device): inputs = tokenizer(text, return_tensors="pt").to(device) # (batch_size, sequence_length) with real tokens = 1 and padding tokens = 0 token_mask = inputs["attention_mask"] with torch.no_grad(): out = model(**inputs, output_hidden_states=True) # Tuple of len = num_layers : (batch_size, sequence_length, hidden_dim) hidden_states = out.hidden_states # Gives number of valid (non-padding) tokens per sequence : (batch_size, ) token_lengths = token_mask.sum(dim=1) # Index of last non-padding token for each sequence : (batch_size, ) last_token_idx = token_lengths - 1 reps = [] for layer in hidden_states: selected = layer[0, last_token_idx.item()] cpu_tensor = selected.cpu() numpy_array = cpu_tensor.numpy() reps.append(numpy_array) # Stacking along new layers : (num_layers, hidden_dim) stacked = np.stack(reps) return stackedThe output shape is : (num_layers, hidden_dim). So for every prompt, we get a layer-by-layer representation trajectory through the network.Measuring Internal ChangeOnce we have hidden states for both prompt variants, the next step is to measure how much they differ.One important thing to note here is that, the results here are very specific to the model chosen. Models like Gemma, Mistral, etc will ususally have a different result.Cosine DistanceTo quantify representational change across layers, I compute cosine distance between the hidden states of the same prompt with and without context.This gives a simple layer-wise measure of divergence :low cosine distance means the representations are similarhigh cosine distance means context significantly changed the internal stateThis lets us track where prompt context has the strongest effect.Cosine distancePCA and UMAPCosine distance tells us how much representations change. To understand what that change looks like, I also project hidden states into 2D and 3D using PCA and UMAP. These projections let us visualize :how prompts clusterhow contextualized and non-contextualized prompts separatehow those shifts evolve across layersThe exact geometry should not be treated as ground truth, but it is useful for observing broad structural trends.UMAP across different layersResultsSuprisingly, context has minimal effect early, larger effect later.Early layers mostly encode the prompt as written, later layers increasingly encode the prompt in context. When projecting hidden states into lower dimensions, the geometric pattern is fairly consistent :In early layers, contextualized and non-contextualized prompts overlap heavilyIn middle layers, paired points begin to separateIn later layers, context often pushes prompts into noticeably different regions of spaceThat progression is the first clear sign that context is not something the model absorbs all at once. In the early layers, the model is still mostly processing the prompt as raw text, so adding context does not change much. The hidden states stay close, and both versions of the prompt still sit in almost the same part of the space.This starts to shift in the middle layers. The overlap gets weaker, paired points begin to move apart, and the model starts treating the contextualized prompt a little differently. At this point, it is no longer just reading the extra text. It is beginning to fold that context into the representation itself.By the later layers, that gap is much clearer. In many cases, the contextualized prompt ends up in a noticeably different region of the space. At that point, context no longer looks like a small addition to the prompt. It looks more like a change in direction.That is the main pattern here. Context does not seem to act like extra information being added on top, instead it sorta behaves like a steering signal, slowly changing how the representation moves as it passes through the network.ConclusionContext does not seem to act like extra information being added on top, instead it sorta behaves like a steering signal, slowly changing how the representation moves as it passes through the network.This is still a small experiment, and there is a lot more to explore here. More tasks, better graders, different prompting strategies, larger models, and maybe even looking beyond just the last token would all make this much more interesting. Hopefully I keep building on this and turn it into a proper little series 😅How Prompt Context Changes LLMs (Layer by Layer) was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.