Inferensys

Glossary

Attention Weights

Learned scalar values in a transformer model that determine the importance of different input tokens when computing a contextualized representation.
Engineer optimizing context window usage on laptop, token usage charts visible, technical work session.
TRANSFORMER MECHANICS

What is Attention Weights?

Attention weights are the learned, normalized scalar values within a transformer's self-attention mechanism that dictate the strength of interaction between every pair of tokens in a sequence, enabling the model to dynamically focus on contextually relevant information.

Attention weights are computed by taking the dot product of a token's query vector with the key vectors of all other tokens, followed by a softmax normalization. This process produces a probability distribution where higher weights signify greater contextual relevance, allowing the model to aggregate information from the most salient parts of the input sequence when constructing a token's output representation.

In diagnostic models, visualizing these weights provides a form of post-hoc explainability, highlighting which specific input tokens—such as gene expressions or clinical notes—most influenced a prediction. This transparency is critical for regulatory submissions, as it allows developers to verify that the model's reasoning aligns with established medical knowledge rather than relying on spurious correlations.

MECHANICS OF SELF-ATTENTION

Key Characteristics of Attention Weights

Attention weights are the learned, dynamic coefficients that govern how a transformer model selectively focuses on different parts of an input sequence when constructing a contextualized representation for each token.

01

Scaled Dot-Product Calculation

The foundational mechanism for computing attention weights involves three matrices: Query (Q), Key (K), and Value (V). The raw attention score between a query token and a key token is calculated as the dot product of their respective vectors. This score is then scaled down by the square root of the key dimension (√d_k) to prevent the softmax function from entering regions with extremely small gradients during training. The final attention weight is the softmax-normalized probability distribution over all keys for a given query.

  • Formula: Attention(Q,K,V) = softmax(QK^T / √d_k)V
  • Purpose of scaling: Mitigates vanishing gradients when d_k is large
  • Result: A probability distribution where all weights sum to 1.0 for each query
√d_k
Scaling Factor
02

Multi-Head Parallelism

Rather than computing a single set of attention weights, the transformer employs multiple attention heads in parallel. Each head projects Q, K, and V into a distinct, lower-dimensional subspace using its own learned linear projections. This allows the model to simultaneously attend to information from different representation subspaces at different positions. One head might focus on syntactic dependencies, while another captures semantic relatedness or positional proximity.

  • Typical configuration: 8 to 16 heads per layer
  • Head dimension: d_model / num_heads (e.g., 512 / 8 = 64)
  • Output: Concatenated head outputs are linearly projected back to d_model
8-16
Typical Heads per Layer
03

Causal Masking for Autoregression

In decoder-only architectures (e.g., GPT models), a causal mask is applied to the attention weights before the softmax operation. This mask sets all attention scores corresponding to future tokens to negative infinity (-∞), which forces their softmax probability to zero. This ensures that the prediction for token at position i can only depend on tokens at positions less than or equal to i, preserving the autoregressive property required for text generation.

  • Implementation: Upper triangular matrix of -∞ values
  • Effect: Prevents information leakage from future tokens
  • Contrast: Encoder models use bidirectional (unmasked) attention
04

Cross-Attention Mechanism

In encoder-decoder transformers, cross-attention layers allow the decoder to attend to the encoder's output. Here, the queries come from the decoder's previous layer, while the keys and values come from the encoder's final output. This is the critical bridge that lets the model align source and target sequences, such as mapping an English sentence to its French translation. The attention weights in cross-attention explicitly represent the alignment between input and output tokens.

  • Q source: Decoder hidden states
  • K and V source: Encoder output representations
  • Use case: Machine translation, sequence-to-sequence tasks
06

Sparse and Efficient Variants

Standard self-attention has O(n²) complexity in sequence length, which becomes prohibitive for long sequences. Sparse attention patterns reduce this by restricting each query to attend only to a subset of keys. Examples include sliding window attention (local context only), dilated sliding window (periodic gaps), and global attention on special tokens like [CLS]. These patterns drastically reduce memory footprint while maintaining performance on long-document tasks.

  • Longformer: Combines sliding window + global attention
  • BigBird: Adds random attention to the sparse mix
  • Benefit: Enables processing of sequences with 4,096+ tokens
INTERPRETABILITY

Frequently Asked Questions About Attention Weights

Attention weights are the core mechanism that makes transformer models interpretable. These FAQs address the most common questions from clinical AI developers and regulatory teams about how attention weights function, how they are visualized, and their role in FDA submissions for diagnostic models.

Attention weights are learned, normalized scalar values that determine how much focus a transformer model places on each input token when computing a contextualized representation for a given position. They are the output of a compatibility function—typically scaled dot-product attention—where the model computes the dot product between a query vector (representing the current token) and key vectors (representing all other tokens), then applies a softmax function to produce a probability distribution summing to 1. Each weight quantifies the relevance of a corresponding value vector to the current context. In multi-head attention, multiple sets of weights are learned in parallel, allowing the model to attend to different representational subspaces simultaneously. For a diagnostic model processing a patient's clinical notes, an attention weight of 0.73 from the token "troponin" to "elevated" indicates the model is strongly associating these concepts when forming its representation.

TRANSFORMER INTERPRETABILITY

Attention Weights for Model Explainability in Diagnostics

How learned scalar values in self-attention mechanisms are visualized and audited to validate the clinical reasoning of diagnostic AI models.

Attention weights are learned scalar values in a transformer model that determine the importance of different input tokens when computing a contextualized representation. In diagnostic applications, these weights quantify how much focus the model places on specific regions of an input—such as a nucleotide in a genomic sequence or a patch in a pathology slide—when generating a prediction, providing a built-in mechanism for post-hoc explainability.

For regulatory submissions, attention weight visualization serves as a saliency method to demonstrate that a model's predictions are grounded in clinically relevant biomarkers rather than spurious correlations. However, attention weights must be interpreted with caution: high weight does not guarantee causal importance, and rigorous evaluation using faithfulness metrics and correlation with established biomarker saliency is required to satisfy FDA expectations for Good Machine Learning Practice.

Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.