← Back to Reading
ByteByteGo 2026-10-13

How the Math Used in 19th-Century Heat Physics Helps LLMs Understand Sentences

In the early nineteenth century, Joseph Fourier developed methods using sine and cosine functions to mathematically represent complex patterns, such as heat distribution across materials. These sinusoidal functions enable the decomposition of intricate spatial or temporal variations into simpler, repeating components. In modern machine learning, large language models (LLMs) employ this same mathematical principle for positional encoding. Instead of physical space or time, positional encodings map the positions of tokens in a sequence using combinations of trigonometric waves. Word order conveys critical semantic information that individual vocabulary terms cannot provide on their own. In both natural language and programming expressions, rearranging identical components fundamentally alters meaning and results. Therefore, language models require access to both token identities and their specific positions to interpret sequences accurately. This positional differentiation is especially crucial when distinguishing repeated occurrences of the same word within a sequence. Neural networks process text by first converting it into numerical data through tokenization, where text is split into fragments such as words or subwords. Each token is assigned a unique identifier that is used to look up a corresponding learned vector called an embedding. Although these vector values are optimized during model training, the initial embedding lookup yields identical vectors regardless of token position. Consequently, language models rely on subsequent layers to incorporate context and link token identities to their specific sequence locations.

Read the original ↗
Contents 12 sections
  1. 01The Physics Behind Heat Measurement and LLMs
  2. 02How Word Order Carries Information
  3. 03How Does a Model Understand Words
  4. 04How the Attention Mechanism Makes Sense of the Order
  5. 05How Location of the Words is Made Available to the Model
  6. 06The Use of Sine and Cosine Functions
  7. 07Why Multiple Rotation Speeds Are A Better Choice
  8. 08How is the Position Code Used
  9. 09How Training Uses the Position Information
  10. 10How Rotary Position Embeddings Work?
  11. 11Other Methods Apart from Sine and Cosine Functions
  12. 12Conclusion

The Physics Behind Heat Measurement and LLMs

In the early nineteenth century, Joseph Fourier developed methods using sine and cosine functions to mathematically represent complex patterns, such as heat distribution across materials. These sinusoidal functions enable the decomposition of intricate spatial or temporal variations into simpler, repeating components. In modern machine learning, large language models (LLMs) employ this same mathematical principle for positional encoding. Instead of physical space or time, positional encodings map the positions of tokens in a sequence using combinations of trigonometric waves.

  • Joseph Fourier developed techniques to represent complex patterns by combining sine and cosine functions to model heat diffusion.
  • Sinusoidal combinations allow representation of both broad, slowly changing variations and small, fast fluctuations across space or time.
  • In large language models, the same mathematical concepts represent a token's position within a sequence rather than physical dimensions.
  • Positional encoding in LLMs is directly rooted in the same family of mathematical physics established through Fourier's work.

How Word Order Carries Information

Word order conveys critical semantic information that individual vocabulary terms cannot provide on their own. In both natural language and programming expressions, rearranging identical components fundamentally alters meaning and results. Therefore, language models require access to both token identities and their specific positions to interpret sequences accurately. This positional differentiation is especially crucial when distinguishing repeated occurrences of the same word within a sequence.

  • Word order provides semantic information beyond what individual word identities convey.
  • Rearranging identical elements in natural language or code expressions can drastically change the resulting meaning or output.
  • A language model must capture both which tokens are present and how they are positioned.
  • Distinguishing repeated instances of the same token requires tracking positional context.

How Does a Model Understand Words

Neural networks process text by first converting it into numerical data through tokenization, where text is split into fragments such as words or subwords. Each token is assigned a unique identifier that is used to look up a corresponding learned vector called an embedding. Although these vector values are optimized during model training, the initial embedding lookup yields identical vectors regardless of token position. Consequently, language models rely on subsequent layers to incorporate context and link token identities to their specific sequence locations.

  • Neural networks require text to undergo tokenization to convert text fragments into numerical identifiers.
  • A token can consist of a whole word, part of a word, punctuation, or another text fragment depending on the tokenizer.
  • Token identifiers are used to look up learned numerical vectors known as embeddings.
  • Individual numbers within an embedding vector do not map to clean, human-interpretable meanings.
  • At the initial lookup stage, identical token identifiers produce the exact same embedding regardless of position in the sequence.
  • Later model layers are responsible for building representations that incorporate sequence context and location.

How the Attention Mechanism Makes Sense of the Order

Transformers rely fundamentally on the attention mechanism to weight contributions across tokens, but basic attention does not inherently account for sequence order. In its simplest form, attention processes tokens without positional features, meaning it cannot distinguish grammatical relationships altered by reordering words like 'Alice' and 'Bob'. Although tokens occupy distinct array indices, array layout does not inherently function as a computational input feature. Consequently, positional representations are required to enable sequence order to affect attention calculations.

  • Attention allows tokens to gather information from other tokens via weighted contributions, but basic attention does not inherently use token order.
  • Without positional information, reordering input tokens merely reorders output representations without recognizing new grammatical relationships.
  • Array indices do not automatically act as input features in neural network computations, similar to how summing an array yields the same result regardless of element order.
  • Positional representations are necessary to ensure that sequence structure directly affects attention calculations in Transformers.

How Location of the Words is Made Available to the Model

Positional encoding is a technique that provides sequence location data to a model by converting sequence positions into numerical representations. While raw integers contain basic ordering information, directly adding large scalar values can overwhelm token embeddings and forces the model to derive its own positional features. Utilizing sine and cosine waves provides structured, bounded features directly without adding novel information. These trigonometric components vary at different rates across positions, preserving token identity while effectively distinguishing word order.

  • Positional encoding converts sequence locations into numerical representations so models can distinguish word order.
  • Words retain their token identity regardless of changes in their positional assignment.
  • Directly using integer scalars can overwhelm existing embedding values and requires the model to construct positional features independently.
  • Sine and cosine functions do not introduce new information beyond the position number, but rather format the data into a useful numerical structure.
  • A collection of sine and cosine values supplies bounded features that vary at different rates across sequence positions.

The Use of Sine and Cosine Functions

Sine and cosine functions can be intuitively understood through a rotating hand around a unit circle, where horizontal and vertical coordinates represent cosine and sine values respectively. In the context of sequence modeling, advancing each step in a token sequence corresponds to rotating the hand by a fixed angle to assign coordinate pairs to positions. Both coordinates are necessary because vertical height alone can map to two distinct positions on the circle, which cosine disambiguates. However, this approach introduces periodicity, as values repeat after completing a full turn.

  • Sine corresponds to the vertical coordinate and cosine corresponds to the horizontal coordinate of a rotating hand on a unit circle.
  • Both sine and cosine values remain bounded between -1 and 1.
  • Advancing steps in a token sequence can be mapped to fixed angular rotations to represent positional coordinates.
  • Using both sine and cosine is required because a single coordinate can correspond to two distinct points on a circle.
  • Coordinates repeat after one full rotation, requiring additional mechanisms to handle sequences beyond a single cycle.

Why Multiple Rotation Speeds Are A Better Choice

Using multiple rotation speeds creates a richer positional encoding that prevents identical readings across repeating cycles. When multiple rotating hands with different frequencies are combined, their paired sine and cosine coordinates maintain uniqueness even when the fastest hand resets. The original Transformer architecture relies on this multi-frequency construction to represent positions across varying scales of sequence distance. While finite frequency sets and numerical precision bound overall distinguishability, the design effectively supports sequence representation across typical target lengths.

  • A single periodic rotation cannot distinguish positions separated by a full cycle, causing identical readings at repeating intervals.
  • Combining multiple hands at different speeds creates unique multi-coordinate representations across positions.
  • Each rotation speed contributes a sine and a cosine coordinate, forming a rich multi-scale numerical pattern for each position.
  • Fast-changing components capture fine-grained local differences, whereas slow-changing components differentiate broader spans.
  • The original Transformer utilizes this principle with a defined mathematical schedule of frequencies.
  • Positional encodings remain constrained in range and precision by their choice of frequencies and numerical precision limits.

How is the Position Code Used

In the original Transformer architecture introduced in the 2017 paper 'Attention Is All You Need', positional encodings are directly added element-wise to token embeddings before entering the model layers. This addition blends word identity with location, enabling the model to learn representations influenced by both factors simultaneously. A primary benefit of using sinusoidal functions for positional encodings is that a fixed positional offset corresponds to a fixed rotation angle, allowing relative shifts to be expressed as linear transformations. Consequently, the network receives a regular, learnable numerical framework for capturing relative distance independent of absolute sequence position.

  • The original Transformer combines token embeddings and position encodings via element-wise addition before feeding the sequence into Transformer layers.
  • Position encoding has the same dimensionality as the token embedding.
  • Although adding vectors mixes token identity and positional data, the model adapts during training to utilize the fused signal.
  • Advancing by a fixed number of positions rotates sinusoidal encoding pairs by a fixed angle, ensuring consistent representation of relative offsets.
  • A fixed linear transformation can map a sinusoidal position code to the code at a fixed offset, aligning naturally with neural network operations.
  • Sinusoidal encodings do not enforce built-in grammar rules, but provide a consistent mathematical structure that the model can learn to exploit.

How Training Uses the Position Information

Training enables language models to transform raw positional information into meaningful linguistic understanding. By repeatedly predicting text and updating parameters when errors occur, models learn to combine token identities, sequence positions, and context to capture syntactic and semantic dependencies. Positional encoding provides sequence order while attention links relevant tokens, allowing language-agnostic positional schemes to acquire language-specific grammar entirely through training.

  • Token position alone is insufficient to convey meaning without considering word forms and surrounding context.
  • Language model training adjusts parameters via text prediction to learn patterns combining token identity, position, and context.
  • Models learn relationships across both adjacent tokens and tokens separated by long spans of text.
  • Positional encoding supplies sequence order to the model, while attention mechanisms connect relevant tokens.
  • Positional encoding schemes can support multiple languages because grammar patterns are acquired through training rather than embedded in the encoding.

How Rotary Position Embeddings Work?

Rotary Position Embedding (RoPE) is an influential positional encoding method that integrates positional information directly into attention representations. Instead of adding a static position vector to input embeddings, RoPE pairs components of queries and keys and rotates them according to token position using sine and cosine functions. When the attention mechanism computes inner products between rotated queries and keys, the result naturally reflects their relative position through the difference in their rotations. Different pairs of components rotate at distinct speeds, enabling position encoding across multiple frequencies.

  • Traditional positional encoding adds a position vector directly to the input embedding, whereas RoPE injects position into query and key representations.
  • RoPE pairs components of query and key vectors and rotates them based on token position using sine and cosine functions.
  • The positional interaction in attention depends on the relative rotation difference between queries and keys, capturing relative token distance.
  • Different component pairs rotate at different speeds to represent position through multiple frequencies.

Other Methods Apart from Sine and Cosine Functions

Transformers can represent positional information through several alternatives to fixed sine and cosine functions. Learned positional embeddings assign a trainable vector to each position, optimizing it directly during model training. ALiBi applies distance-based penalties directly to attention scores to favor nearby tokens without modifying token embeddings. Additionally, causal masking inherently provides structural order information by restricting tokens to attending only to preceding prefixes, enabling causal transformers to learn positional behavior without explicit positional encodings.

  • Learned positional embeddings assign trainable vectors to each supported position rather than relying on fixed trigonometric calculations.
  • ALiBi biases attention toward nearby context by penalizing attention scores based on the distance between tokens.
  • ALiBi does not require adding positional vectors to input token embeddings.
  • Causal masking restricts tokens from attending to subsequent tokens, exposing different prefix lengths at each position.
  • Causal transformers can acquire positional awareness implicitly from the causal mask structure even without explicit positional encodings.

Conclusion

Calculating positional encodings for extremely large indices does not guarantee that a model can understand long documents effectively. Even when mathematical formulas scale to positions of one million, models face compute and memory limits and lack experience relating tokens across such long contexts. Classical mathematical formulations using sine and cosine functions provide a bounded, multiscale language for position, which models subsequently learn to align with language semantics during training.

  • Calculating position encodings for extreme lengths does not inherently enable a model to understand arbitrarily long documents.
  • Models are constrained by memory, compute limits, and a lack of training experience across massive token distances.
  • Sine and cosine functions yield bounded values, multiple scales, and shift-invariant consistency for sequence positions.
  • Training allows the model to learn how numerical positional representations interact with linguistic content.