Published
-
LLM Principles, Explained: From Tokenization to Context Length

Photo by Bozhin Karaivanov on Unsplash
1. Executive Summary
An LLM may look as if it reads text directly, but in practice it receives a sequence of tokens and computes probabilities for the next likely token. It is more accurate to think of it as a large probabilistic model that generates continuations matching the context than as a system that directly understands the world like a human. 出典: Attention Is All You Need presents Transformer as a sequence model centered on attention, and Language Models are Few-Shot Learners pushes large autoregressive models into practical use as context-conditioned generators.
The easiest way to understand the pipeline is to split it into tokenization, embedding, contextualization with Transformer self-attention, and next-token prediction. The “knowledge” inside an LLM is not stored like a dictionary of explicit facts; it is distributed across learned weights. That said, the model can also memorize passages verbatim. 出典: Neural Machine Translation with Byte-Level Subwords covers subword tokenization, and Attention Is All You Need combines input embeddings with positional information. Memorization and extractability are shown in Extracting Training Data from Large Language Models and Scalable Extraction of Training Data from (Production) Language Models.
For practical work, the important question is not whether the model is “smart,” but which inputs, external references, and verification steps you give it. Context length is useful, but it is not a magic fix, and longer inputs do not automatically make a model more reliable. LLM use should therefore be treated as system design: prompt design, retrieval, permissions, auditing, and review all matter. 出典: Long-context models still miss information or over-focus on certain regions, as shown in Lost in the Middle: How Language Models Use Long Contexts. The standard idea of combining retrieval with generation comes from Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks and REALM: Retrieval-Augmented Language Model Pre-Training.
2. The Big Picture
An LLM does not “understand the whole sentence” in one step. It first splits the input into smaller units, maps them into numeric representations, computes which words should matter to each other in context, and then ranks output candidates. The core idea is not to look up a meaning dictionary, but to produce a probability distribution over continuations. 出典: Attention Is All You Need and Language Models are Few-Shot Learners describe the autoregressive generation setup that underlies Transformer LLMs.
The pipeline can be sketched like this.
flowchart LR
A["Text"] --> B["Tokenization"]
B --> C["Embedding"]
C --> D["Self-attention"]
D --> E["Next-token probability"]
E --> F["Generated text"]
This diagram is simplified, but it is good enough as a map for a first reading. In real models, the flow includes multiple Transformer blocks, normalization, feed-forward layers, and a learned output head. 出典: Attention Is All You Need defines Transformer as a stacked sequence-to-sequence architecture built from attention and feed-forward layers.
3. Tokenization and Embeddings
Tokenization breaks text into units that the model can process more easily. In practice, those units are usually subwords rather than full words or characters, because subwords handle rare words and symbols more robustly. So the model does not memorize raw strings as-is; it learns reusable pieces. 出典: Neural Machine Translation with Byte-Level Subwords discusses byte-level subword tokenization, and Language Models are Few-Shot Learners assumes token sequences as the basic input format.
Embeddings map each token into a high-dimensional vector. You can think of that vector as a coordinate in a semantic space, where tokens used in similar ways tend to end up near each other. Because order matters, position information is added as well. Transformer combines token embeddings with positional encoding to process sequences. 出典: Attention Is All You Need explicitly includes input embeddings and positional encoding. Embeddings are best understood as distributed representations shaped by co-occurrence and usage, not as dictionary definitions.
In plain language, the model does not hold “meaning” directly; it holds numbers that capture how text is used. That is why the same word can end up represented differently in different contexts, and why words with similar roles can be close together. 出典: This is a summary of how contextual representations are produced by embeddings plus self-attention in Attention Is All You Need.
4. Transformer and Self-Attention
The center of Transformer is self-attention. Each token decides which other tokens in the sentence it should pay attention to, and how much. Pronouns, conditions, and references often need to connect to distant words. Transformer computes those links through attention weights rather than through sequential recurrence. 出典: Attention Is All You Need showed that sequence transformation can be done with attention alone, without recurrence or convolution.
Self-attention often uses the terms Q, K, and V. It helps to think of them as the question, the thing being matched against, and the information being collected. Each token compares itself with others, decides which ones matter, and then pulls in the context it needs. Multi-head attention repeats this process in parallel. 出典: Q, K, and V are the implementation roles defined by Transformer self-attention, and Attention Is All You Need provides the basic structure.
flowchart TD
A["Input tokens"] --> B["Q/K/V"]
B --> C["Relevance scoring"]
C --> D["Context aggregation"]
D --> E["Representation update"]
E --> F["Next layer"]
Self-attention is powerful because it can pick up the relevant clue wherever it appears in the context. At the same time, the attention weights themselves should not be treated as a full explanation, and the actual basis for a model’s answer still needs separate verification. 出典: The practical lesson from Transformer is that attention helps model context, but output verification must be handled in the surrounding system design.
5. Pretraining and Next-Token Prediction
Most LLMs are built first through pretraining. Pretraining means reading huge amounts of text and code and repeatedly practicing the task of predicting the next token. Instead of manually labeling every example, the model learns from the text itself by turning continuation into a prediction problem. GPT-3 showed that scaling this autoregressive setup produces behavior that generalizes to unseen tasks through context. 出典: Language Models are Few-Shot Learners reports that large autoregressive language models exhibit few-shot behavior.
At this stage, the model absorbs grammar, phrasing, factual fragments, code patterns, article structure, and dialogue flow. But this is closer to building a broad pattern compressor than to building a knowledge base. Pretraining is not magical understanding; it is a way to learn generally useful statistical regularities. 出典: Language Models are Few-Shot Learners and BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding show how pretraining creates transferable representations.
After that, extra training is often added for instruction following and safety. Human feedback and principle-based methods are both used in practice. But these methods do not mean the model has ethics built into it; they only shift output behavior. Responsibility, approval, and audit still belong in the system. 出典: Training language models to follow instructions with human feedback and Constitutional AI: Harmlessness from AI Feedback show the post-pretraining direction.
6. Inference and Context Length
Inference here does not mean human-style deliberation or mathematical proof. At runtime, the learned weights stay fixed, and the model selects one token after another from the prompt and its current context. Different temperatures or sampling rules can produce different outputs from the same input because generation is probabilistic. LLM inference is best understood as reusing learned patterns at runtime. 出典: Attention Is All You Need and Language Models are Few-Shot Learners both assume autoregressive generation. Here, “inference” refers to machine-learning inference.
Context length is the maximum number of tokens the model can directly condition on at once. If you give it a long document, it does not see every part with equal strength, and it can lose track of important material as the input gets longer. Long context helps, but it is not a cure-all. 出典: Lost in the Middle: How Language Models Use Long Contexts shows that models may underuse information in the middle of long inputs.
So it is risky to think that choosing the longest-context model will solve everything. In many cases, it is better to summarize the relevant parts, retrieve only the documents that matter, and keep structured data outside the prompt. 出典: The basic retrieval-plus-generation idea comes from Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks and REALM: Retrieval-Augmented Language Model Pre-Training.
7. What “Storing Knowledge” Really Means
Saying that an LLM stores knowledge is partly right and partly misleading. It is right in the sense that facts and patterns are distributed across the learned weights and can help the model respond. It is misleading if you imagine a human-like understanding or a database-style lookup table hidden inside the model. 出典: Extracting Training Data from Large Language Models and Scalable Extraction of Training Data from (Production) Language Models show that models can sometimes memorize and reveal training data.
The key point is that “the model remembers something” and “the model can retrieve it correctly” are different claims. It may behave plausibly in one context and fail when conditions change slightly. It may also complete facts correctly from learned regularities even when the exact passage was never memorized. So LLM knowledge should be treated as a mix of memory, generalization, completion, and confusion. 出典: This is the practical synthesis of memorization research and scaling results from Extracting Training Data from Large Language Models and Language Models are Few-Shot Learners.
That is why production systems should not expect the model alone to be the source of truth. If you need the canonical answer, connect the model to search, SQL, APIs, rule engines, audit logs, and approval flows. LLMs are strong at drafting and summarization, but they are not the final authority for correctness. 出典: The retrieval-augmented design logic in RAG and REALM is the right starting point.
8. Common Questions
Q1. Does an LLM really “understand”?
Strictly speaking, it is hard to say that it understands in the same sense as a human. The model’s core job is next-token prediction conditioned on context. So even if its behavior looks like understanding, it is too early to equate that behavior with human understanding. 出典: This answer is a practical inference from autoregressive training and memorization research in Language Models are Few-Shot Learners and Extracting Training Data from Large Language Models.
Q2. Why does an LLM make mistakes so confidently?
Because it is not trained as a truth-checking engine. It is optimized first to produce the most plausible continuation, so ambiguity, data bias, and weak context can lead to plausible but wrong answers. 出典: Language Models are Few-Shot Learners describes the autoregressive setup, and Training language models to follow instructions with human feedback explains why extra alignment steps are needed.
Q3. Does longer context always improve accuracy?
No. Longer context gives the model more material to work with, but it can also hide important facts or make the middle of the input less useful. In many cases, it is better to extract the essentials and feed only the relevant sources. 出典: Lost in the Middle: How Language Models Use Long Contexts shows the position-dependent weakness of long-context use.
Q4. Can an LLM replace search?
Not completely. Search is good at finding evidence, while an LLM is good at reorganizing and explaining what it found. The best pattern is to use both, not to force one tool to do both jobs. 出典: RAG and REALM show the basic structure for connecting external evidence to generation RAG REALM.
9. How to Use LLMs Safely
In practice, it is better to decide first what the model should see every time than what it should “remember.” Fast-changing information, high-accuracy information, and responsibility-bearing information should be passed in as external data rather than trusted as internal memory. 出典: This follows from the combination of broad generalization and training-data memorization shown in Language Models are Few-Shot Learners and Extracting Training Data from Large Language Models.
Next, the output should not be used raw. Route it through retrieval, rules, computation, and review. LLMs are strong at explanations, drafts, summaries, and classification, but final correctness should come from other mechanisms. In short, an LLM should be embedded as a component that proposes candidates from context, not as an isolated thinking subject. 出典: The retrieval-augmented generation literature and long-context studies support the view that the model should be connected to stable external facts rather than used alone RAG Lost in the Middle.
Finally, do not confuse the model’s strengths and weaknesses. Its strengths are handling vague input, turning it into text, and consolidating related information. Its weaknesses are truth guarantees, permanent memory, responsible agency, and self-management over long tasks. If you keep that distinction clear, LLMs become a very useful tool. 出典: This summary integrates autoregressive generation, long-context limits, and memorization research Attention Is All You Need Lost in the Middle Scalable Extraction of Training Data from (Production) Language Models.
1. エグゼクティブサマリー
LLMは、文章をそのまま読んでいるように見えて、実際にはトークン列を受け取り、次に来そうなトークンの確率を計算しているモデルである。人間のように世界を直接理解していると考えるより、「巨大な確率モデルが、文脈に合う続きを生成している」と捉える方が正確である。 出典: Attention Is All You Need はTransformerを注意機構中心の系列モデルとして示し、Language Models are Few-Shot Learners は大規模自己回帰モデルが文脈に応じて次の出力を作る枠組みを実務に押し上げた。
理解の順番としては、まずトークン化で文字列を部品に分け、埋め込みで数値ベクトルにし、Transformerの自己注意で文脈上の関係を重み付けし、最後に次トークン予測として出力する、と分けるとよい。LLMの「知識」は辞書のように明示的に保存されるのではなく、学習された重みの中に分布的に埋め込まれる。ただし、その知識はときに文面を丸ごと覚える形でも残る。 出典: Neural Machine Translation with Byte-Level Subwords はサブワード型のトークン化を扱い、Attention Is All You Need は入力埋め込みと位置情報を組み合わせる。LLMの訓練データの記憶と抽出可能性は Extracting Training Data from Large Language Models と Scalable Extraction of Training Data from (Production) Language Models が示している。
利用設計で重要なのは、LLMを「賢い回答装置」として評価するより、どの入力を与え、どの外部情報を検索し、どの検証手段を通すかで性能を設計することにある。文脈長は万能ではなく、長くすればするほど自動的に賢くなるわけでもない。したがって、LLMの活用は、モデル単体の理解ではなく、入力設計、外部参照、権限、監査、再確認を含むシステム設計として考えるべきである。 出典: 長文脈でも情報の取りこぼしや位置依存が残ることは Lost in the Middle: How Language Models Use Long Contexts が示している。外部検索を組み合わせる基本発想は Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks と REALM: Retrieval-Augmented Language Model Pre-Training に沿う。
2. まず全体像をつかむ
LLMは、入力を受けた瞬間に「文全体の意味」を一気に理解するわけではない。実際には、入力を短い単位に切り、順番に数値表現へ変え、文脈の中でどの語がどの語に結びつくかを計算し、出力候補を並べる。ここでの本質は、意味の辞書を引くことではなく、次に続く表現の確率分布を作ることである。 出典: Attention Is All You Need と Language Models are Few-Shot Learners は、Transformer系LLMが自己回帰的に出力を積み上げる枠組みを明示している。
この仕組みを一枚で見ると、次の流れになる。
flowchart LR
A["文章"] --> B["トークン化"]
B --> C["埋め込み"]
C --> D["自己注意"]
D --> E["次トークン確率"]
E --> F["生成文"]
この図は単純化しているが、LLMを理解する最初の地図としては十分である。実際のモデルでは、この流れの中に多層のTransformerブロック、正規化、フィードフォワード層、学習済みの出力ヘッドが入る。 出典: Attention Is All You Need は、Transformerを複数層の注意機構とフィードフォワード層で構成する系列変換器として定義している。
3. トークン化と埋め込み
トークン化は、文章をモデルが扱いやすい単位に分割する作業である。文字単位でも単語単位でもなく、実務でよく使われるのはサブワード単位で、見慣れない単語や記号でも分解して扱えるようにする。つまりLLMは、原文をそのまま丸暗記するのではなく、再利用しやすい部品へ分けて学習する。 出典: Neural Machine Translation with Byte-Level Subwords は byte-level のサブワード化を扱い、Language Models are Few-Shot Learners は大規模言語モデルがトークン列を入力として扱う前提で設計されている。
埋め込みは、各トークンを数百次元のような高次元ベクトルに写す層である。ここでベクトルは「意味の座標」のようなもので、似た使われ方をするトークンほど近い場所に置かれやすい。加えて、文章は順番が大事なので、位置情報も足される。Transformerは、入力埋め込みと位置エンコーディングを組み合わせて系列を処理する。 出典: Attention Is All You Need は入力埋め込みと positional encoding を明示している。埋め込みは辞書的な定義ではなく、学習データ中の共起と使用法を反映した分布的表現として理解するのが適切である。
埋め込みまでを直感で言い換えると、LLMは「単語の意味」を直接持っているのではなく、「使われ方の近さ」を数字で持っている。だから同じ語でも文脈が変わると表現が変わり、似た働きをする語は近づく。 出典: この説明は、Transformerの埋め込み表現と自己注意が文脈依存表現を作るという設計からの要約である Attention Is All You Need。
4. Transformerと自己注意
Transformerの中心は自己注意である。自己注意は、各トークンが文中の他のどのトークンをどの程度参照するかを決める仕組みだと思えばよい。たとえば「彼」「それ」「この条件」のような参照語は、近くの単語だけでなく、離れた場所の名詞や条件文とも結びつく必要がある。その結びつきを、RNNのような逐次処理ではなく、注意の重みとして一度に計算する。 出典: Attention Is All You Need は、再帰や畳み込みを使わず attention のみで系列変換を行えることを示した。
自己注意では、よくQ, K, Vと呼ばれる三つの役割を使う。問いかける側、照合される側、集められた情報だと思うと分かりやすい。各トークンは、他のトークンとの相性を見て重みを決め、必要な文脈を引き寄せる。これを複数の「頭」で同時に行うのが多頭注意である。 出典: Q, K, V の表現は Transformer で定式化された自己注意の実装上の役割であり、Attention Is All You Need がその基本構造を与えている。
flowchart TD
A["入力トークン"] --> B["Q/K/V化"]
B --> C["関連度計算"]
C --> D["文脈を集約"]
D --> E["表現を更新"]
E --> F["次層へ"]
自己注意が強いのは、文脈のどこに重要な手掛かりがあるかを柔軟に拾えるからである。一方で、注意の重みをそのまま「説明」とみなすのは危険であり、モデルが何を根拠にしているかは別途検証が必要になる。 出典: Transformerの設計上の強みは文脈関係の学習にあるが、モデルの出力を説明可能性と同一視してはいけないという注意は、注意機構の実装そのものよりも、出力を検証する利用設計から出てくる。
5. 事前学習と次トークン予測
LLMの大半は、まず事前学習で作られる。事前学習とは、大量のテキストやコードを読み込み、次に来るトークンを当てる練習を繰り返すことだと考えてよい。ここでは正解ラベルを人が細かく付けるのではなく、データそのものから「続きを予測する」課題を作る。GPT-3は、この自己回帰的な学習を大規模化すると、未知のタスクでも文脈に応じて振る舞えることを示した。 出典: Language Models are Few-Shot Learners は、自己回帰言語モデルを大規模化すると few-shot 性能が現れることを報告している。
この段階でモデルは、文法、言い回し、事実の断片、コードの定型、文章の構成、会話の流れを広く吸収する。ただし、それは「知識ベースを作る」というより、「次の語を当てるために役立つパターンを広く学ぶ」ことに近い。つまり、事前学習は万能な理解の付与ではなく、汎用性のある圧縮を作る工程である。 出典: Language Models are Few-Shot Learners と BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding は、事前学習が下流タスクへの汎用化を生む基本構造を示している。
その後に、指示追従や安全性のための追加学習が入る。たとえば人間のフィードバックを使う方法や、原則に従わせる方法がある。だが、こうした追加学習は「モデルに倫理が宿る」ことを意味しない。出力傾向を調整しているだけであり、実務での責任、承認、監査は別に必要である。 出典: Training language models to follow instructions with human feedback と Constitutional AI: Harmlessness from AI Feedback は、事前学習のあとに指示追従と安全性を整える方向を示している。
6. 推論と文脈長
ここでいう推論は、数学の証明や人間の熟考と同義ではない。実行時には、学習済みの重みが固定され、与えられたプロンプトと文脈をもとに、次のトークン候補を順に選ぶ。温度やサンプリング方法を変えると、同じ入力からでも違う文が出るのはこのためである。LLMの推論は、学習で得たパターンをその場で再利用する工程だと考えるとよい。 出典: Attention Is All You Need と Language Models are Few-Shot Learners は、自己回帰的な生成が前提であることを示している。ここでの「推論」は、機械学習の inference を指す。
文脈長は、モデルが一度に直接見られるトークン数の上限である。長い文書を渡しても、その全部が同じ強さで見えるわけではないし、長くなるほどどこに重要情報があるかを取りこぼすこともある。長文脈は有効だが、万能ではない。 出典: Lost in the Middle: How Language Models Use Long Contexts は、長文脈でも中央付近の情報が使われにくい場合があることを示している。
したがって、「文脈長が長いモデルを選べばすべて解決する」と考えるのは危険である。長い入力を入れる前に、どの情報を要約し、どの情報を外部検索に回し、どの情報を構造化データとして別に持つかを決める方が重要だ。 出典: 外部検索と生成を組み合わせる基本発想は Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks と REALM: Retrieval-Augmented Language Model Pre-Training にある。
7. 「知識を保存している」の正確さと限界
LLMが知識を保存している、という言い方は半分正しく、半分不正確である。正しい部分は、学習を通じて事実やパターンが重みの中に分布的に保持され、応答に役立つことである。不正確な部分は、そこに人間のような意味理解や、データベースのような明示的検索がそのまま入っていると考えることだ。 出典: Extracting Training Data from Large Language Models と Scalable Extraction of Training Data from (Production) Language Models は、モデルが訓練データを部分的に記憶しうることを示している。
この点で重要なのは、LLMが「覚えている」ことと「正しく取り出せる」ことは別だということだ。似た文脈ではもっともらしく振る舞えても、少し条件が変わると誤ることがある。逆に、記憶していないはずの情報でも、学習済みの規則性からうまく補完することがある。つまり、LLMの知識は、記憶、一般化、補完、混同が入り混じったものとして扱う必要がある。 出典: 記憶と抽出の問題は Extracting Training Data from Large Language Models に、一般化とスケールの利点は Language Models are Few-Shot Learners に対応する。
だから実務では、LLM単体に「正しい知識の所在」を期待しない方がよい。正本が必要なら、検索、SQL、API、ルールエンジン、監査ログ、承認フローとつなぐべきである。LLMは文章化と要約に強く、根拠の固定化と最終判断には向かない。 出典: 検索拡張の設計思想は RAG と REALM が出発点になる。
8. よくある誤解Q&A
Q1. LLMは本当に「理解」しているのか
厳密には、人間と同じ意味で理解していると断言するのは難しい。少なくとも、LLMがやっている中心作業は、文脈に応じた次トークン予測である。だから、理解に見える振る舞いは出せても、それをそのまま人間の理解と同一視するのは早い。 出典: この回答は、自己回帰的な学習目標と訓練データ記憶の研究を踏まえた設計上の推論である Language Models are Few-Shot Learners Extracting Training Data from Large Language Models。
Q2. なぜLLMは平気で間違うのか
LLMは、真偽を照合する装置として訓練されているわけではない。まずはもっともらしい続きを出すことに最適化されているので、入力の曖昧さ、訓練データの偏り、文脈不足があると、もっともらしい誤りを出しやすい。 出典: Language Models are Few-Shot Learners は自己回帰的生成の枠組みを示し、Training language models to follow instructions with human feedback は追加学習が必要な理由を説明している。
Q3. 文脈長を長くすれば精度は必ず上がるのか
上がるとは限らない。長い文脈は参照できる材料を増やすが、長すぎると重要情報が埋もれたり、中央部の情報が使われにくくなったりする。長く入れるより、要点を抽出し、必要な資料だけを渡す方が強い場合がある。 出典: Lost in the Middle: How Language Models Use Long Contexts は、長文脈の位置依存を示している。
Q4. LLMは検索エンジンの代わりになるのか
完全な代わりにはならない。検索は根拠を見つけるのが得意で、LLMは見つけた材料を読みやすくまとめるのが得意である。両者を組み合わせると、調査と要約の分業ができる。 出典: RAG と REALM は、外部知識を生成に接続する基本構造を示している RAG REALM。
9. 実務でどう使うか
LLMを実務で使うなら、まず「何を覚えさせるか」より「何を毎回見せるか」を決める方がよい。頻繁に変わる情報、正確さが重要な情報、責任が伴う情報は、モデル内部の記憶に頼らず、外部データとして渡す方がよい。 出典: この方針は、自己回帰モデルの一般化能力と訓練データ記憶の両方を踏まえた設計上の帰結である Language Models are Few-Shot Learners Extracting Training Data from Large Language Models。
次に、出力をそのまま採用せず、検索、ルール、計算、レビューを通す。LLMは説明文、候補案、下書き、要約、分類には強いが、最終的な正確性保証は別の仕組みが担うべきである。LLMは「考える主体」ではなく、「文脈を受けて候補を出す部品」として組み込むのがよい。 出典: 検索拡張生成と長文脈研究は、LLMを単体で使うより、外部の確定情報を接続する方が設計上有効であることを示している RAG Lost in the Middle。
最後に、LLMの強みと弱みを混同しないことが大事である。強みは、あいまいな入力を扱い、文章の形にして返し、関連情報をまとめることにある。弱みは、真偽保証、恒久記憶、責任主体性、長い作業の自己管理にある。ここを取り違えなければ、LLMはかなり有用な道具になる。 出典: このまとめは、Transformerの自己回帰生成、長文脈の限界、訓練データ記憶の研究を統合した設計上の整理である Attention Is All You Need Lost in the Middle Scalable Extraction of Training Data from (Production) Language Models。