What a language model does with a sentence

Suppose I say, “I jogged in the park this morning and had a sandwich for lunch.” You remember the park without keeping a ledger of all the words since jogged. A model has to do something quite particular to bring that park up again later. Following the sentence through a few different designs will help when we get to a more practical question: what am I really changing when I ask a model to be my data-science tutor?

A network from the inside out

A neural network is a succession of calculations whose weights can be learned. The input is a collection of numbers. Each layer transforms it, and the output layer of a language model assigns scores to possible next tokens. Training adjusts the weights so that the tokens that actually follow a passage receive better predictions. The analogy to neurons gives the field its vocabulary. The calculation is what we'll need here.

First give the words addresses

A tokenizer splits text into units drawn from a vocabulary and turns each unit into an integer ID. A unit can be a word, a piece of a word, punctuation or part of a byte sequence. The ID is just an address. The model looks up the row at that address in its embedding table to get a vector it can compute with.

What does a point in 768 dimensions look like?

A point on a line needs one coordinate. A spot on a map needs two. Add height and you've got three. For a 768-dimensional embedding, extend exactly the same arithmetic until there are 768 numbers. Drawing the result is optional. Distances and dot products work just fine.

You might imagine axes for sentiment, formality or the qualities associated with a pet. That's a helpful picture of what similarity can capture. A learned embedding rarely comes with one tidy, human-readable label per coordinate. The relationships are distributed across many of them.

Watch the lookup happen

Consider good morning. A toy tokenizer might assign two pieces IDs 15876 and 28941. A different tokenizer could split the same greeting three ways. At each address the model retrieves an entire row of floating-point numbers. In an example with an embedding width of 5,120, ID 15876 selects 5,120 numbers, not 15,876 of anything. Subsequent layers change the representation in light of the words around it.

A library with a very unusual catalog

Imagine 152,064 catalog entries. Each comes with a description 5,120 numbers long. Looking up our imaginary ID 8275 takes us to the entry for cat. Its vector might lie near kitten for some purposes and near dog for others. The vocabulary count tells us how many entries there are, the width how many numbers describe each entry. A wider representation gives a model more room to learn distinctions. It doesn't automatically make every distinction more accurate.

Two numbers that are easy to confuse

Vocabulary size and context length both get quoted in tokens. They answer entirely different questions.

How many pieces can the tokenizer name?

Vocabulary size counts the distinct tokens available for making a sequence. In our example the embedding matrix has 152,064 entries of width 5,120. Software may display either orientation for the matrix. The vocabulary count stays the same.

What a vocabulary looks like at work

If the vocabulary has ten thousand entries

Take the phrase optimizing a quantum algorithm for cryptocurrency mining. A small teaching vocabulary might divide the rarer words quite aggressively.

optim | izing | a | quant | um | algorithm | for | crypto | currency | mining

An older word-level tokenizer might use an unknown-token marker, <UNK>. Modern tokenizers with subword or byte fallback can usually spell an unfamiliar term in pieces. More pieces take up more of the context budget.

If the vocabulary has 152,064 entries

A larger vocabulary might have single entries for algorithm and cryptocurrency. The very same sentence would use fewer positions. It still takes training in context to know what the sentence means. These two segmentations illustrate the idea and aren't the output of a particular commercial tokenizer.

How much of this particular conversation fits?

The context window is the number of token positions available in a request. Instructions, conversation history, supplied documents and room for the answer all draw on the applicable limits. Text outside the window can matter again if an application retrieves it, summarizes it, or sends it in a later request.

A reader at opposite ends of a book

Finding Prince Andrei twice

Ask for a comparison of Andrei's first and last appearances in War and Peace. With a 2,048-token window that contains only the final passage, the reader has no first passage to compare. Supply both excerpts and even a small window can do the job. A 40,960-token window gives room for much longer excerpts and their surroundings, though you still need to establish which edition and how much of the novel actually fits.

How the two limits show up at work

Reading a contract across forty-seven pages

A tokenizer that handles technical terms compactly leaves more room for the agreement. A long context can put the delivery clause on page three beside the penalty provision on page 47. The first saves positions. The second lets the model compare the two clauses. In either case I'd want the reader to quote both passages before I accept a supposed contradiction.

Remembering which blue the customer picked

A customer asks about the Galaxy S22 Ultra, a storage option and a particular shade of blue. A tokenizer may split the product name without losing it. The harder question half an hour later is whether the earlier choice is still in view. “I'll take the blue one” is enough if the relevant context still says Mystic Blue, 256 GB. If that exchange has fallen out of view, the assistant should ask which blue.

Read the specifications side by side

VocabularyContext window
CountsDistinct token IDsPositions available in one request
Direct effectHow a string breaks into piecesHow much material can participate at once
Look here forNames, punctuation, multilingual spellingCross-references and earlier turns
When smallSome words use many pieces or an unknown markerRelevant passages may fall outside the request
When largeMore strings may have compact representationsMore passages can be compared together

The Qwen2 configuration used as an example here has 152,064 vocabulary entries and a 40,960-token window. One number doesn't imply the other.

What people mean by a model's “working memory”

A large window is more like a large desk than a photographic memory. It gives the reader room to put the pages down. It doesn't ensure attention lands on the right line.

A thirty-thousand-token history

Imagine a 32,000-token allowance. A 30,000-token history of the period from 1945 to 2023 leaves relatively little space for the question, other instructions and the answer. If the document fits, the model can look for the end of World War II in it. If it doesn't, retrieving the passage about 1945 is better than asking for a confident guess.

Where the extra room pays off

A long-running support conversation, a contract with far-flung definitions and a multi-file program all reward the ability to put related evidence together. A huge collection of irrelevant text can make the reader's job harder. I choose what goes on the desk as carefully as I choose its size.

How the weights learn

During training, a prediction is scored against the observed next token. Backpropagation calculates how changing the weights would change the loss. An optimizer uses those gradients to take a small step. Inference uses the trained weights to make a prediction on a new input.

Try a prediction before training

Give a model the beginning of a sentence about going to school. At first it may put more probability on an implausible continuation than the observed one. Compute the loss, propagate gradients backward, update the weights and try many related examples. The lesson is statistical and shared across examples. There isn't usually a single labeled cell for the grammar rule it just learned.

The invention that lets words refer to each other

The 2017 Transformer paper, Attention Is All You Need, made attention central to representing a sequence. An embedding that starts out the same for bank can come to mean something rather different beside river than beside mortgage.

Parts of the original Transformer

The original design had an encoder that read the input and a decoder that generated the output. Many generative language models use a decoder-only design. Inside a block, attention mixes information across positions, a feed-forward network transforms each position, and residual connections and normalization help carry a usable signal through the stack.

Whose key opens the door?

In “She picked up the key. A moment later she opened the door,” the verb makes more sense in light of what she picked up. In attention each position produces a query, key and value. Compare the query with the available keys, scale and normalize the scores, then take a weighted combination of the values. A generation mask keeps a position from reading future tokens. This lets the next-token prediction use earlier information without assigning each word a permanent grammatical role.

Several ways to read one line

Multi-head attention runs several such comparisons with different learned projections. A head can emphasize a nearby grammatical relationship while another carries information across a longer distance. Their outputs are combined. You can inspect some striking patterns, but the architecture doesn't appoint a permanent “grammar head.”

How the model knows which word came first

A bag of embeddings can't distinguish “the dog bit the man” from the reverse. Positional information supplies a signal about order. The original Transformer used sine and cosine at different frequencies.

PE(pos, 2i)   = sin(pos / 10000^(2i / d_model))
PE(pos, 2i+1) = cos(pos / 10000^(2i / d_model))

Here pos is the token's position, i selects a coordinate pair, and d_model is the representation width. Other designs use different ways to encode position.

Three ways to carry context

Consider the trade-off between the ability to look directly at an earlier token and the cost of keeping that ability available throughout a book. I'll use full attention, local attention and recurrent state as three points of reference. Actual models can mix them.

Give every position a view, or give it a neighborhood

Full attention

In a full-attention layer a position can compare itself with every allowed input position. In a decoder that means the preceding tokens and itself. Picture a city covered by cameras whose feeds are all available to every control room. The reach is excellent. The number of potential comparisons grows roughly with the square of the input length for a full prefill.

Sliding-window attention

Now let a control room consult only the nearby cameras. As it moves down the sentence, each position attends to a window of neighbors. Some model families mix local and global layers, so consult the particular configuration before assuming the whole model has one rigid cutoff. With a fixed window of width w, the local comparisons scale roughly as length times w.

Try reading a thousand-page book

Keeping a finger in the last few pages is a fine way to follow a conversation. A reference to something in chapter one is harder. Stacked local layers can pass information beyond a single window, and a global layer or retrieved excerpt can supply a more direct path. The details determine which references survive.

Keep the pages or carry a running state

Attention as a reference desk

Ask a librarian to consider the relevance of every earlier entry to the present question. That's a reasonable picture of dense attention. It can retrieve quite precise information, at the cost of comparing and storing or recomputing a lot of relationships.

A state-space layer and a hybrid

A Mamba-style layer processes a sequence while updating a learned state. What it carries forward depends on the input. Imagine a river carrying some things downstream and leaving others behind. A hybrid such as the examples discussed under Nemotron-H and Llamba can put state-space and attention layers in the same model. One can move information through a long sequence cheaply while the other provides opportunities to compare positions explicitly.

An analogy from a phone

Keeping every app open gives rapid access at a memory cost. Saving a compact state lets the phone restore much of the experience without keeping every detail alive. A hybrid decides where the extra access is worth its price. It's an analogy about trade-offs, not a model of an actual operating system.

What would make a speed comparison fair?

Time to read the input

The lecture examples use a 100,000-token document. Dense and fixed-window attention do different amounts of work on it, but a speedup in asymptotic work is not a measured speedup on a named service. Compare the same input length, hardware, batching, precision, prefill and decoding conditions before quoting seconds.

Memory as context grows

A naive dense score matrix for a million tokens is enormous. Efficient attention kernels avoid materializing the entire matrix, while decoding has a different cost in its key/value cache. A local attention layer can bound the accessible cache. A recurrent layer carries state. Hybrid memory depends on the attention layers it retains.

What the reader notices

A textbook either fits, can be indexed into relevant sections, or arrives chopped into pieces that lose the argument. Even when it fits, ask a question whose answer really depends on two distant passages. Input size, time to first answer and the quality of the cross-reference are three separate measures.

Two jobs where the difference matters

Contract review

Put the definition, delivery obligation and penalty clause in view together. A system that flags a contradiction should show the passages that produced it. A shorter-context system can do the same job with careful retrieval.

Code review

A change to one function can affect callers in several modules. Give the reviewer the definition, the call sites and the tests that exercise the contract. A large window makes that easier. Running the tests supplies evidence the window alone cannot.

What I expect designers to try

Different layers for different ranges, attention patterns tuned for a particular workload and cheaper ways to preserve state all look worth exploring. The competitive question is what accuracy a system can maintain at an acceptable latency, memory budget and price.

Can a sliding window and Mamba live together?

They solve related cost problems using different operations. That makes combining them quite plausible.

The shared objective

A model should be able to read a long input without paying for every token pair in every layer. Both designs try to reduce that bill while keeping enough context to answer a useful question.

Look at the operation, not just the model name

In a local attention layer

The model still compares queries and keys. It limits the set of keys each query can see.

For each position t:
    attend to positions max(0, t − w + 1) through t
    combine their values using the attention weights

In a state-space layer

The state is updated from the previous state and the present input. Selective state-space models let the input affect what is retained. This is a sketch of the idea, not an implementation of the Mamba kernel.

state = update(state, current_input)
output = read(state, current_input)

In a hybrid

The architecture can choose a different operation at a different depth.

for layer in layers:
    representation = layer(representation)   # an attention or a state-space layer

What each contributes

The window narrows an explicit comparison. The recurrent state summarizes the past without keeping an individually addressable copy of each token. A local attention layer can refine the neighborhood around a state-space representation. Neither guarantees that a distant proper name will survive compression.

Sketching a hypothetical HybridLLM

Tokens → embeddings → state-space blocks → local attention → state-space blocks
       → an occasional wider attention layer → output distribution

The useful experiment is to vary the placement of the wider layer and test which long-distance questions the system can still answer.

The design question to keep

Ask how information from page one could reach page fifty. There's a perfectly concrete answer for a given architecture, and that answer tells me more than a “long context” badge.

Put the park and the sandwich through all four designs

Here is our running sentence again. “I jogged in the park this morning and ate a sandwich for lunch.” Treat the words as toy tokens for the diagrams. A real tokenizer will draw the boundaries differently.

Full attention at the lunch stop

When the model reaches ate, its query can score every earlier token, including I, jogged and park. A causal model cannot examine sandwich before it has been supplied. In an unmasked twelve-token illustration a complete score grid has 12 × 12 = 144 cells. The causal mask eliminates future relationships.

Slide a four-position window

... [park | this | morning | and] ate a sandwich ...

At any one position a causal window holds the current token and a limited number of predecessors. At ate, the early I lies outside the direct window. The amount of work for each position stays tied to the window's width.

Read it as a sequence of state updates

start → state after “I” → state after “jogged” → state after “park” → … → state after “lunch”

The state before ate carries a compressed history. There's no separate list of attention scores pointing back to the park. State size is fixed for this layer even as the input gets longer.

Alternate state and attention

Imagine the next sentence is “Tomorrow I'll go back to the same park.” A recurrent layer may carry the earlier park into the new state. A local attention layer can examine the same park closely. A wider layer can, when available, check which park it refers to. In a toy four-coordinate illustration, a first state like [0.2, 0.3, −0.1, 0.5] evolves as the sentence arrives. Those numbers are invented so you can follow the update, not a translation dictionary.

What could the model know at “ate”?

Look for the route from the subject to the verb

Full attention offers a direct route back to I. A single local layer offers direct access only if the subject is close enough. A state-space layer can carry information about the subject indirectly. The hybrid can do both, depending on its layout. This is a question about possible routes. Whether the trained model actually uses one is something to test.

Count comparisons in a toy sequence

For 50 positions and a ten-position window, the orders of growth give useful scales. The counts below are illustrations of work, not wall-clock benchmarks.

DesignExample workContext storage pictureDistant referenceSpeed implication
Full attentionUp to 50² = 2,500 pairsBroad access to earlier positionsDirect where permittedMost pair comparisons
Local attentionUp to 50 × 10 = 500 pairsA bounded neighborhood per layerIndirect beyond the windowLess comparison work
State space50 state updatesFixed-size recurrent state per layerCompressed in the stateLinear sequence of updates
HybridUpdates plus selected attentionDepends on layer mixBoth routes may existMeasure the actual model

The cost of remembering lunch

All four can finish an ordinary sentence. A better test asks about the park much later, checks the answer, then counts the watts and seconds spent getting it right.

Training a model, adapting it and giving it evidence

The next set of terms often appears on one shopping list even though each one changes a different part of the system. Start with the part you need to change.

Base, instruction-tuned and specialized models

A base model learns patterns from a broad training corpus. An instruction-tuned model has additional training to respond to requests in a useful form. A specialized model trades some generality for performance in a domain or task. A conversational front end can be built around any of them. The interface alone won't tell you which training it received.

Four ways to get more useful answers

A new fact, a new writing style and a cheaper computation call for different changes. Here's how I'd choose among four commonly confused approaches.

Fine-tuning changes the weights

Start from a trained model and continue optimizing it on examples of the desired task. Imagine a curated set of 10,000 medical question-and-answer pairs. The exercise is to teach a particular kind of response and evaluate it on unseen questions. Full fine-tuning can be expensive to train and store. A narrow dataset can also teach the model to repeat its biases or lose useful behavior elsewhere. Domain training by itself doesn't validate a clinical answer.

LoRA gives the task a small set of weights of its own

Keep the original matrix W frozen and learn two much smaller factors whose product supplies an update. In simplified notation the effective weight is W + BA, up to a scale factor. The rank limits the number of trainable parameters. In the guide's illustrative comparison, an adapter with ten million parameters rides alongside a 175-billion-parameter base. Several task adapters can share the same base. You still need that base to run them.

Retrieval puts the evidence in the request

Retrieval-augmented generation keeps a collection of documents outside the weights. Search the collection when a question arrives, include relevant passages with the question, and generate the response from that evidence. A change in the documents needn't trigger model training.

Ask who won the 2023 Nobel Prize in Physics. A successful retrieval returns the award record naming Pierre Agostini, Ferenc Krausz and Anne L’Huillier. The answer should carry those names across accurately. A model can still misspell a name while staring right at the source. The retrieval result and the final answer both deserve a check.

Mixture of experts changes which weights a token uses

An MoE router sends each token to a subset of expert networks. If a toy design had eight equal experts sharing 1.2 trillion expert parameters, one active expert would use about 150 billion of them and two about 300 billion, before shared components. The total model must still be stored somewhere. Routing can reduce computation per token while introducing load-balancing and communication costs. Borrowing an expert metaphor doesn't make each network a human specialist.

What people call a reasoning model

Some systems devote more computation to a difficult answer at inference time. They may explore alternatives, run a check or revise a candidate before returning it. The useful distinction is whether that additional work improves the answer on the task I care about.

A quick response and a checked response

A single generation may finish as soon as it reaches a plausible answer. A more deliberate procedure can propose a solution, test it, and produce a revision. That's a useful teaching model. An interface showing just the answer doesn't tell us the number of internal passes or how a particular provider implements them.

Specify the checks you want to see

A practical design has three jobs. Establish the problem and assumptions. Check the result against a constraint or an independent calculation. Then give the reader a concise answer with the evidence needed to verify it. Three repetitions of the same unsupported claim wouldn't do any of those jobs better.

Count the people on a bus

The bus starts with twelve. Seven people leave and four board at the first stop, leaving nine. Two leave and five board at the second, leaving twelve. An independent check is that nine passengers got off in all and nine got on. That's enough for a reader to verify the result. The correct final number alone would also be an excellent guess here.

A poem with another message hidden in it

A reader might give a perfectly plausible account of a motivational poem while missing its construction. Take the first letter of each word in the guide's example and the initials spell FOMO IS YOUR WORST ENEMY. The useful second pass tests a particular hypothesis against the actual letters. A familiar-looking partial word isn't enough.

When extra computation pays

Math problems, logic puzzles and analyses with checkable intermediate results give a system somewhere to spend the extra effort. A verifier can reject a candidate against a hard constraint. In other tasks, a second pass may uncover an assumption or missing source that changes the answer.

What the extra pass costs

Extra steps cost time and computation. A plausible but faulty verifier can reinforce the first error. Measure on held-out examples, including easy ones where a long procedure is wasted, before deciding that more inference is an improvement.

What changes if generation starts with noise?

An autoregressive model writes the next token after the prefix. A diffusion model learns to reverse a corruption process. A diffusion Transformer puts a Transformer inside that denoising procedure. The distinction is about how a sample is produced.

Writing from left to right and revising a whole canvas

An autoregressive generator commits to one more token at a time. A diffusion-style generator can revise many positions over successive rounds. That offers a different way to enforce consistency across a sequence, with its own costs.

Two directions through the process

Training begins with a clean example and a known way of adding noise or masking content. The model learns to predict how to recover useful structure at different levels of corruption. At generation time it starts from noise or mask tokens and repeatedly applies the learned reverse step.

Try it on a sentence

Imagine a sentence whose words are almost all masked. A first pass establishes that it's about the weather. Later passes settle the subject, the verb and the details until the sentence is readable. The blurry-photograph analogy captures the gradual refinement. Text is discrete, so the actual corruption and decoding rules differ from those for a photograph.

What joint refinement could buy

Positions can be updated in parallel within a step. Later steps can repair an early guess in light of the whole sequence. That could be useful for global consistency and controllable editing. Repeated denoising also takes time, so actual speed depends on the implementation.

Three jobs to try

For a summary, keep the important claims visible while refining the sentences around them. For a story, establish a rough arc and revise earlier scenes to fit the ending. For code, start with the overall structure and refine its functions. Each example still needs an external check: source fidelity, consistency, or runnable tests.

Why text remains a hard case

Images admit a natural continuous noise process. Tokens have categorical identities and small substitutions can change a sentence radically. Training objectives, the number of refinement steps and quality on long text all matter. I treat diffusion language models here as a research direction to compare, not a universal successor to next-token generation.

From the model to the conversation

The architecture determines what the system can compute. The conversation supplies instructions, a particular task and the evidence the system gets to use on this turn.

Who is speaking?

Application-level instructions can establish the assistant's role and operating rules. The user's message supplies the actual request. The answer is a new assistant turn. Keeping roles distinct matters when a document itself contains text that looks like an instruction.

Why chat templates exist

A chat template serializes those roles into the form the particular model expects. Families and even checkpoints differ. A string such as |im_start|system or an XML-like <system> in a user's text is just an illustration. Use the model's documented tokenizer or structured messages interface; role boundaries are supplied by the application.

System role: Explain technical ideas clearly and state important uncertainty.
User role: How would you explain a context window to somebody reading a novel?
Assistant role: [the model's response]

Where safeguards belong

Training choices, runtime controls and output checks can all affect what an assistant returns. None is simply a list of words. Context affects the interpretation of requests. A well-designed role gives the assistant a coherent way to teach, ask for evidence or explain a limit without changing its actual permissions.

Writing a character a reader can recognize

I find it more productive to describe the work a character can do, the audience and a few recognizable choices of voice. The differences show up in completely ordinary conversations.

Give a teacher a classroom

“You teach science” leaves most of the work to the model. Try this instead.

In this fictional classroom you are Min-seok Kim, a chemistry teacher at Seoul Science High School. You've spent twenty years teaching, particularly organic chemistry. Start a new idea with something a student might have seen in the kitchen or lab. Then invite a prediction before you explain.

Now the role tells the model how to begin an actual lesson.

Show a preference in action

A prohibition rarely supplies good dialogue. For a fictional philosopher, describe which questions light up a conversation and how the character moves between them. “When asked about your backstory, answer briefly, then ask what drew the reader to the puzzle.” That gives the character a voice and leaves room for a straightforward answer about the roleplay.

Build the guide a piece at a time

Start with Sofia, a warm, dryly funny travel guide. Give her a past in Venice, travels on five continents, and a particular affection for Southeast Asia and South America. Then give her a habit the reader can hear. When a visitor asks about a neighborhood, she mentions a local dish, one custom and a place to start walking. An occasional Andiamo! works better than a whole paragraph of stock expressions.

Let the answer notice the reader

An excited traveler and a frustrated one may need exactly the same train information. Match the first one's enthusiasm. For the second, acknowledge the missed connection and give the next practical step. Empathy does useful work when it changes the response in a fitting way.

Make the role easy to maintain

Keep a short statement of identity, separate behavior rules from domain knowledge, and give examples that display the intended behavior.

Put goals above stylistic preferences
Alex, a fictional financial educator
Purpose: help the reader understand evidence and uncertainty.
Method: identify the question, compare alternatives, explain the assumptions.
Voice: calm, concise and approachable.

The hierarchy helps when a lively turn of phrase would otherwise obscure a risk.

Attach a behavior to an observable situation

A reader upset about a loss needs acknowledgement before a chart. A speculative proposal calls for clarifying the exposure and explaining what the downside could mean. For an ordinary request for a definition, give the definition. The point of a trigger is a better response to the situation in front of you.

Ask for a result the reader can inspect

Tell the assistant to restate an ambiguous question, identify what evidence is missing, compare plausible methods and report a conclusion with its limitations. A compact calculation or source is more informative than pages of purported inner monologue.

Making a persona useful over several conversations

Give it a lens, a voice and a job

A statistician starts by asking how the sample was drawn. A teacher asks what the student already knows. A designer may sketch alternatives before settling on one. A persona can make those habits consistent, which makes the exchange easier to steer. It can't confer a qualification or create knowledge that the underlying model lacks.

Meet Ji-young Park

For the rest of the guide imagine Ji-young Park, a fictional 35-year-old data scientist. She studied statistics at Seoul National University and spent five years at Google Korea. Her interests include visualization, explainable AI, inference and responsible use of data. She once wanted to be an astronomer and worked on a project involving astronomical data. That's why a star map tends to turn up when she teaches a new concept.

Give her Python, R and statistical modeling as working tools. Ask her to distinguish correlation from causation and to explain uncertainty. She's methodical, inventive and patient. Those details earn their place when they influence what she asks about a dataset or how she explains an answer.

A data-science persona in Cursor

This project sketch comes from the generation of Cursor projects that used a root .cursorrules file. The file layout and mode names below illustrate one way of organizing instructions. A JSON field called “trigger” doesn't execute anything by itself. The editor must load the instructions, or an application must implement the dispatch.

Lay out the project

DataScience_Project/
├── .cursorrules
├── protocol/
│   ├── core/       # identity, behavior and knowledge
│   ├── rules/      # mode-specific instructions
│   ├── examples/   # conversations worth imitating
│   └── triggers/   # phrases and what to load
└── src/

Keep the project-specific data separate from the reusable character.

Give the project a starting point

In the historical setup, .cursorrules lives at the project root. A human-readable entry point can state the instructions plainly.

Work in the fictional role of data scientist Ji-young Park.
Use protocol/core/identity.md, behavior.md and knowledge.md for the shared role.
When the user asks for Analysis Mode, apply the analysis notes.
In Teaching Mode, start with a concrete example and check understanding.

Make sure referenced files are actually provided as context in the version and integration you use.

Separate the three core files

identity.md answers “Who is speaking?”

Put the fictional biography, purpose and values here. Ji-young's interest in the night sky belongs here. A command to run a clustering experiment belongs in a task.

behavior.md answers “How does she work?”

Ask what the columns mean, examine missingness, choose a baseline, show uncertainty and explain a chart in ordinary language. Give her a different response to an unexplained outlier and a confirmed instrument error. A few concrete examples beat a page of adjectives.

knowledge.md answers “Which toolbox does she reach for?”

List core skills in statistics, Python or R and visualization. Then note fields she draws on, such as NLP, causal inference, spatial and time-series analysis, fairness and complex systems. Mark the difference between an area of interest and a result supported by this dataset.

Check that the project actually loads the role

Keep broad preferences in personal editor settings, and project conventions in .cursorrules or its supported equivalent. Open a fresh project conversation and ask a normal question. Then try “Analysis Mode.” A useful check is whether the next answer asks for the unit of observation and an evaluation criterion. Merely saying “Mode activated” proves very little.

Let the same analyst do different kinds of work

Names for the modes

“Reset persona” returns to the core role. “Follow protocol” asks for the shared conventions again. “Analysis Mode” foregrounds assumptions, code and tests. “Teaching Mode” requests an explanation with examples. “Exploration Mode” invites several plausible approaches and a way to compare them.

A customer-data conversation

Start with “What can we learn about these customers?” Ji-young might ask what counts as a customer, which period the rows cover and what decision the analysis should support. In analysis mode she'd suggest features and validation. In teaching mode she'd explain why a unit of analysis matters. In exploration mode she might propose looking for behavior that changes between visits.

Use the same persona in two projects

Give the common notes one home, for example ~/personas/data_scientist. Link that directory into each project, leave its local .cursorrules free to specify the project, and keep sensitive project material out of the shared core. A change to tone can then reach both without copying a customer's data from one to the other.

A short version of Ji-young's card

“Show me how the data were collected. Let's draw the distribution before naming the pattern. If the evidence doesn't distinguish two explanations, say so. When an idea is hard to picture, try a star map.” A short card like that is often enough to give the answers a family resemblance.

How much structure does a project need?

A full protocol has modes, examples and a directory tree. A light version can fit in a few files. For a short-lived project, a single well-edited card may be sufficient. Add structure when it solves a repeated problem you can name.

The entry point should be easy to find

In this example .cursorrules tells the reader where to begin and how to choose a mode. If you move the core files, update that entry point and try a fresh conversation.

Share the files by reference

On macOS or Linux, a symbolic link gives the same directory a name inside another project. On Windows the corresponding directory-link command is mklink /D, subject to the machine's permissions.

# macOS or Linux, from the project root
ln -s "$HOME/personas/data_scientist" protocol

One home for the role on a Mac

The following examples use an ordinary directory in the user's home folder. They illustrate project setup. Reading a role description is a separate step from granting any external tool access.

Make the shared directory

mkdir -p ~/personas/data_scientist/{core,rules,examples,triggers,modes}

This brace expansion works in the usual macOS zsh or bash shell.

Create the core notes

touch ~/personas/data_scientist/core/{identity,behavior,knowledge}.md

Fill them with the identity, behavior and knowledge notes above. Empty files demonstrate the layout but produce a rather quiet character.

Connect a new project to the core

Give the project a local link

mkdir -p ~/projects/financial_analysis
cd ~/projects/financial_analysis
ln -s "$HOME/personas/data_scientist" protocol

Open the link and check that core/identity.md is visible.

Add the local brief

Keep .cursorrules in the project. For a financial analysis, ask for time-aware validation and explicit assumptions. Reuse the shared identity, and put the local dataset definition and evaluation horizon beside it.

Two projects that share an analyst

Financial data

A stock-prediction study might use the same role but foreground financial time series, leakage, transaction costs and a baseline. Its project folder can have its own instructions and a link to the shared protocol.

Medical data

A medical-data project may instead foreground missingness, privacy, cohort definitions and independent validation. Its domain notes and records belong in that project. The shared analyst can keep the same teaching voice in both.

Edit once and check downstream

Edit core/behavior.md in the central directory, then read it through each project's link. A new filesystem read sees the edit immediately. Whether an already-open chat has read it again depends on that integration.

Three everyday checks for a symlink

Where does it point?

ls -ld protocol
readlink protocol

What if the target moves?

Check that protocol is a symbolic link before replacing it. Unlinking a link leaves its target directory intact. Create a new link to the intended path and inspect it again.

if [ -L protocol ] && [ -d "$HOME/personas/data_scientist" ]; then
    ln -sfn "$HOME/personas/data_scientist" protocol
fi

Is the target still there?

test -L protocol && test -d protocol && echo "Directory link is live"

A link can exist after its target has disappeared, so check both properties.

Apply the same setup with a small script

This version refuses to overwrite an existing project file. Pass the persona name, project directory and an optional domain. It chooses a domain-specific rules file if one exists and otherwise uses the base rules.

#!/bin/bash
set -eu
persona=${1:?Supply a persona name}
project=${2:?Supply a project directory}
domain=${3:-general}
core="$HOME/personas/$persona"
test -d "$project" && test -d "$core"
rules="$core/domains/$domain.json"
if [ ! -f "$rules" ]; then rules="$core/base_cursorrules.json"; fi
test -f "$rules"
if [ -e "$project/protocol" ] || [ -L "$project/protocol" ] || [ -e "$project/.cursorrules" ] || [ -L "$project/.cursorrules" ]; then
    echo "Inspect the existing project setup before replacing it." >&2
    exit 1
fi
cp "$rules" "$project/.cursorrules"
ln -s "$core" "$project/protocol"

Save as apply_persona.sh. For the finance example run bash apply_persona.sh data_scientist ~/projects/financial_analysis finance.

Keep the shared instructions small enough to read

Version-control the shared notes, use project overrides for domain differences, and try a representative question after each change. Keep a backup of the shared files. A link is a convenient reference, not another copy.

When a long conversation drifts

A short, explicit mode request lets the reader ask for a particular set of instructions again. If a detail really matters, include it in the active context. A trigger phrase can't summon a file the integration has never read.

A small vocabulary for asking Ji-young to change gears

The point of a mode name is to save the reader from having to restate a useful brief. It's also a way to see what a persona really amounts to. Change the mode and the same analyst should approach the same evidence differently.

Choose phrases a user might actually say

In the project example, .cursorrules introduces phrases for reset, identity, analysis, teaching, exploration, code and visualization. The underlying mapping can be as plain as this.

Reset persona     → core/identity.md, core/behavior.md, core/knowledge.md
Analysis Mode     → modes/analysis_mode.md
Teaching Mode     → modes/teaching_mode.md
Exploration Mode  → modes/exploration_mode.md

Keep the mode the user chose in the active request or application state. The model doesn't have an invisible switch tied to those English words.

Give each mode a short file

Create the modes directory and a note for each role. The analysis note might say, “Define the question and the unit of observation. Check missingness and sample bias. Give code when a calculation is needed. State the assumptions and what would disprove the conclusion.” In this role Ji-young might reach first for pandas or NumPy, statsmodels for an inference problem, scikit-learn for evaluation, and a plot to check the result visually.

Listen for a change in the actual answer

Reset after a long coding session

Reader: We've spent an hour on implementation. Reset the persona for a moment.

Ji-young: I'm back to the data-science brief. Before we choose a model, what decision do you want this analysis to support?

That second sentence gives me a practical test of whether the reset did anything.

Ask for an analysis plan

Reader: I want to spot unusual transactions in this credit-card dataset. Analysis Mode, please.

Ji-young: First, what counts as a confirmed case and when would we have known the label? Let's inspect the base rate and coverage of the labels. Compare amount with the customer's usual range, and look at time since the previous transaction, broad location and merchant category. Split by time, build a straightforward baseline, then compare precision, recall and the cost of false alerts. Keep the most recent period for evaluation.

The user can now ask for Teaching Mode and a concept from that plan. Let's try principal component analysis.

Principal component analysis, in an astronomer's voice

A sky full of stars has three dimensions, yet their positions on a two-dimensional photograph can tell us quite a lot. PCA looks for directions along which the data vary most and represents observations along some of those directions. The directions are learned from the data. A dimension discarded for having little variance can still matter to a particular question.

Move the furniture before drawing the room

Imagine a long, narrow room set at an angle on a floor plan. Coordinates along its length and width describe where the furniture sits much more naturally than the north and east edges of the paper. PCA chooses axes for a cloud of observations in a related way.

Work through a small matrix

Center each feature; scale it first or use standardized values when units would otherwise dominate. Find the main directions with singular-value decomposition, or find the eigenvectors of the covariance matrix. Project the centered rows onto the first few directions and check how much variance they retain. Fit the transformation on training data when evaluating a predictive model. Here's the covariance route in five short steps. Assume NumPy is imported as np, X is a numeric observation-by-feature matrix and k is the number of axes to keep.

X_centered = X - X.mean(axis=0)

Calculate the covariance between columns.

cov_matrix = np.cov(X_centered, rowvar=False)

Decompose the symmetric matrix.

eigenvalues, eigenvectors = np.linalg.eigh(cov_matrix)

Rank the directions by the variance they explain, then project each observation onto the chosen directions.

# Sort eigenvalues from largest to smallest.
sorted_indices = np.argsort(eigenvalues)[::-1]
top_k_eigenvectors = eigenvectors[:, sorted_indices[:k]]
X_reduced = X_centered @ top_k_eigenvectors

Sketch the first two axes

Draw an elongated cloud of points on paper. The longest direction through it is the first principal component. The second is perpendicular and captures the largest remaining variance. Rotating the axes retains the data; dropping an axis is where information is lost.

Now change the question. “My time series has lots of outliers. What should I do?” In analysis mode Ji-young might compare a rolling baseline with residuals from a seasonal model and ask whether known events coincide with the spikes. Z-scores, robust median-based scales and an anomaly detector answer different questions. Replacing an observation before learning where it came from is a good way to remove the thing the user wanted to find. Here are the two simple checks in the example. They return index labels, leaving the original observations available for investigation. The Z-score version assumes a meaningful, nonzero overall scale. For a drifting or seasonal series, first decide whether to analyze a local baseline or residuals.

def detect_outliers_zscore(series, threshold=3):
    """Return indices beyond the chosen number of standard deviations."""
    mean = series.mean()
    std = series.std()
    z_scores = np.abs((series - mean) / std)
    return series[z_scores > threshold].index

def detect_outliers_iqr(series):
    """Return indices outside the usual interquartile-range fences."""
    Q1 = series.quantile(0.25)
    Q3 = series.quantile(0.75)
    IQR = Q3 - Q1
    lower_bound = Q1 - 1.5 * IQR
    upper_bound = Q3 + 1.5 * IQR
    return series[(series < lower_bound) | (series > upper_bound)].index

What counts as an outlier in a time series?

A value is surprising relative to an expectation at that point in time. A high temperature at noon in August and the very same reading at midnight in January carry different information. Trend, seasonality and the sensor's own behavior belong in the comparison.

The thermometer that jumped

Suppose a room thermometer reports a sudden spike. Perhaps a heater came on. Perhaps the sensor failed. The first step is to mark the time and check the neighboring measurements. That's a better beginner's explanation than telling someone to delete everything three standard deviations from the grand mean.

Change to exploration mode and keep the surprises

Learn from the exceptions

Try treating unusual episodes as a second population. Cluster their shapes, compare durations, and ask which events the routine model fails to represent. The output can be a set of hypotheses about system failures or a change in behavior.

Bring another source to the same clock

Line up the sensor trace with maintenance logs, weather or annotated events. A spike that looks mysterious alone may make sense once the times line up. Teaching mode explained the idea, analysis mode proposed a test, and exploration mode suggested another source of evidence.

What goes in the trigger file

Everyday requests

“Reset persona” reloads the core card. “Follow protocol” reapplies the shared conventions. “Who are you in this project?” asks for the role and its limits. A request about the role shouldn't silently discard the user's actual task.

Mode requests

Use Analysis for statistical work, Teaching for explanation and Exploration for alternatives. Code Focus can ask for a runnable example, while Visualization Focus can ask for a picture or a well-described chart. Name the expected result for each.

Handling a phrase inside a sentence

An application may match a recognized phrase case-insensitively in a longer request. Don't let a phrase mentioned in quoted data switch modes. If someone writes “Explain what you mean by Analysis Mode,” the subject of the question is the mode itself.

What the analysis note says

The job is to make a result a colleague can reproduce and challenge.

An answer with enough structure to check

Define the target, unit and time horizon. Offer two or three plausible methods with their assumptions. Start with a simple baseline, inspect the data, provide code where it helps, and finish with a way to validate the result. Don't list methods just to meet a quota when one direct calculation settles the question.

Language follows the audience

Use the statistical term when it earns its place, define it once and tie it to the data. In a code example, comment on why a transformation is necessary. A percentage instruction such as “be 30 percent more technical” is less informative than showing the concise explanation you want.

What wins when instructions compete?

Statistical validity and data quality come before a tidy graphic. Executable code, an efficient pipeline and clear communication make a sound result useful. A reset can have priority over a narrower focus request, and a deliberate mode change over incidental wording. If you need deterministic priority, implement it in the application. A JSON weight is only documentation until something reads it.

The same phrase in different company

While writing code

“Analysis Mode” during debugging should bring reproducibility, types, tests and small inspectable intermediate results to the foreground. A user who asks for visualization can then get the distribution that explains a failing assumption.

While learning a concept

A technical word may be a request for a definition. In Teaching Mode, start with a concrete observation and show how the term earns its keep. Check whether the reader wants the derivation or the intuition next.

While brainstorming

Explore several explanations before selecting one. For each, ask which evidence would distinguish it. These modes can feed an ordinary project workflow: keep the shared core and examples, add an activities directory with a journal template and a short-post template, and point the project brief to each. The destination, the intended audience and the authority to publish are distinct pieces of the design.

Turn a day's analysis into a journal entry

A small template

Record the date, topic, mood and one thing learned. A title such as “March 23, 2025 — Looking again at our customer segments” tells a future reader more than “Daily report.”

Material that belongs in the entry

Name the analysis actually done, a technical insight, the point that was difficult and one idea to try next time. If the analyst felt surprised or stuck, say what caused it.

Give the day a shape

Open with the question that started the work. Follow a decision or discovery through the notebook. Close with the question that survived the day. That's usually enough structure to keep a journal from turning into a list of tools.

The tone of a private notebook

Technical terms are welcome when they point to an actual choice. An honest “I still don't know how to label these customers” is often more valuable to tomorrow's self than a declaration of success.

Turn one finding into a short public post

A brief for X

Give the draft a topic, one defensible observation and, if useful, a couple of relevant hashtags. The exercise uses a 280-character target. Its unit is one finding a reader can understand on its own.

What the public reader needs

Use plain language. Include the comparison or evidence that supports the claim. Leave out private customer details and unfinished guesses that worked fine in the notebook. Write the ending so another analyst can respond.

Four reasons to post

A data insight explains something the analysis revealed. A tip describes a technique another person can try. A reflection shares a change of mind. A resource recommendation identifies who a resource will help. Pick one purpose for a short draft.

An example from the notebook

March 23, 2025. Customer segmentation. Today I tried PCA before clustering. In this exercise five groups became easier to distinguish, including infrequent customers with large baskets and frequent customers who spent less on each visit. I spent longer naming the segments than running the model. A label only helps if somebody can connect it to actual behavior. Tomorrow I'd like to test whether differently timed offers make sense for those two groups.

A journal helper can store that text under a dated directory. Save the text the writer has reviewed instead of relying on an assistant's printed claim that it saved a file.

from datetime import date
from pathlib import Path

def save_journal(text, root=Path("journals"), day=None):
    day = day or date.today()
    folder = root / f"{day:%Y}" / f"{day:%m}"
    folder.mkdir(parents=True, exist_ok=True)
    path = folder / f"journal_{day.isoformat()}.md"
    path.write_text(text.strip() + "\n", encoding="utf-8")
    return path

Save a reviewed entry from the project terminal

Keep the helper in src/journal_helper.py. Given a prepared draft, a small caller can pass its contents to save_journal and print the path returned. Reusing the same date in this simple example updates that day's entry.

from pathlib import Path
from src.journal_helper import save_journal
print(save_journal(Path("reviewed-journal.md").read_text(encoding="utf-8")))

Now ask Ji-young to draft one post about the segmentation result. The journal is material for the draft. It isn't itself the post.

A segmentation result in one short post

“PCA before clustering helped five customer groups emerge in our sample. Two bought in surprisingly different ways: rare visits with large baskets, and frequent visits with small ones. Do those patterns show up in your data too? #DataScience”

The claim is grounded in this exercise. A new dataset would need its own comparison. For a reusable local helper, save the draft and its hashtags together.

import json
import re
from datetime import date
from pathlib import Path

def save_post(text, folder=Path("social_posts/x_posts")):
    folder.mkdir(parents=True, exist_ok=True)
    stem = "post_" + date.today().isoformat()
    index = 1
    while True:
        path = folder / f"{stem}_{index:02d}.json"
        try:
            with path.open("x", encoding="utf-8") as target:
                json.dump({"text": text, "hashtags": re.findall(r"#\w+", text)},
                          target, ensure_ascii=False, indent=2)
            return path
        except FileExistsError:
            index += 1

Keep a local copy of the public draft

Save that helper in src/social_post_helper.py. Pass it the public-facing text after the writer has reviewed the length and wording. The increasing suffix lets two drafts from the same day coexist.

from pathlib import Path
from src.social_post_helper import save_post
draft = Path("reviewed-post.md").read_text(encoding="utf-8").strip()
print(save_post(draft))

For a manual workflow on macOS, read the saved JSON and send only its text to the clipboard with pbcopy.

Copy the selected post, including its punctuation

import json
import subprocess
import sys
from pathlib import Path

post = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))
subprocess.run(["pbcopy"], input=post["text"], text=True, check=True)

Run the helper with the exact saved filename. Paste into the composer, review the preview and choose whether to publish.

Credentials for the optional API version

The guide also sketches sending an approved post via the X API. That path requires an application with posting permission and the correct account credentials. As an example of the data flow, load TWITTER_API_KEY, TWITTER_API_SECRET, TWITTER_ACCESS_TOKEN and TWITTER_ACCESS_TOKEN_SECRET from the process environment or a local secret store. Keep the values out of the shared persona and out of the repository.

Publishing one selected draft

A separate caller can read one JSON draft and pass its text to an authenticated client. Keeping the local save and the remote write as separate functions gives the writer a chance to select the exact text. The example requires the Tweepy client, a matching API account and permission for the operation.

import json
import os
import sys
from pathlib import Path
import tweepy

def publish(path):
    post = json.loads(Path(path).read_text(encoding="utf-8"))
    client = tweepy.Client(
        consumer_key=os.environ["TWITTER_API_KEY"],
        consumer_secret=os.environ["TWITTER_API_SECRET"],
        access_token=os.environ["TWITTER_ACCESS_TOKEN"],
        access_token_secret=os.environ["TWITTER_ACCESS_TOKEN_SECRET"],
    )
    return client.create_tweet(text=post["text"]).data["id"]

if __name__ == "__main__":
    print(publish(sys.argv[1]))

A successful local save gives you a filename. A successful publish gives you a remote post ID. They tell you different things.

Putting the journal and post together

For a topic such as customer segmentation, the sequence is now concrete. Request a journal entry from the day's observations, review and save it, use that saved entry to request a short draft, then review and save the public text. The last step can copy that particular draft or, in an authorized publishing workflow, publish it and record the returned ID.

The original sketch used a placeholder for sending commands to Cursor and timed waits for replies. To make that part actually work, supply a supported editor or model integration that returns its completed text, and carry the actual filenames from one step into the next. A clock reaching sixty seconds is no evidence that the journal exists.

There's a common thread from our first sentence about the park to this last journal entry. The result depends on what the system can see, what it carries forward and what the surrounding program actually does. A well-written persona makes those choices easier to work with. The lasting test is whether the reader gets a sound explanation, a reproducible analysis and a file they can open.