なぜローカルLLMは実際より賢くないように感じるのか
Why your local LLM feels dumber than it is (forum.level1techs.com)
要約
ローカル環境で実行される大規模言語モデル(LLM)が、期待される性能を発揮しないように感じられるのは、ハードウェアやソフトウェアの実装の違いによるものが大きいと論じています。特に、推論エンジンの複雑なソフトウェアスタックや、GPUの命令セットの違いなどが、モデルの出力に微妙な差異を生じさせ、それが性能低下のように感じられる原因となります。記事では、これらの差異を理解し、ベンチマークの重要性を説いています。
全文翻訳
なぜローカルLLMは実際よりも賢くないように感じるのか
Part 3.14 - 無限の級数
問題点について、そしてその「何」について話しました。次に、その「なぜ」を深く掘り下げていきます。
次の手として、50ドルを消してみせましょう!(冗談ではありません。実験のためにH200とB200のレンタルを借りました笑)
このフォローアップでは、より興味深い結果の一部を検討のために提示します。H200カード(異なるクラウドプロバイダーから)、B200カード、そしてSM120 RTX 6kで完全に再現可能なテストを実行するとどうなるでしょうか?
誰も正しくないとき、みんな間違っている
問題は、客観的な「正しい」答えがないことです。モデルのハードウェア/ソフトウェア設定は、どれほど精密で調整されていても、それぞれ異なります。
Alibabaは、「このプロンプトに基づき、あなたのセットアップが生成すべき正確なロジットはこちらです」というデータセットを公開していません。
では、異なる答えの無限の連続体の中で「正しさ」をどのように定義するのでしょうか?このビデオがレンダリングされることを願っています。
この図には単位がないことに注意してください。これは物事がどれだけ異なるかの絶対的な視点ではありません。すべては相対的です。SM120 vs B200 vs H200でのFlash Attention 2はどれくらい異なりますか?三角形を描いてください。単一のH200カードでのFlash Attention 2とFlash Inference、Triton Attentionはどれくらい異なりますか?別の三角形を描いてください。三角形を相互接続することで、3次元の領域が得られます。そして、その領域の中心からみんながどれだけ離れているかをプロットできます。では、誰が中心に最も近いでしょうか?
この結果は、いくつかの理由で非常に興味深いです。明らかに、計算はプロンプト固有なので、発散を計算するために多くのコンテキスト深度にわたる最も広いデータ選択を使用しました。
| メッセージ | 深さ | トークン | 内容 |
|---|---|---|---|
| SP01-M001 | 6,335 | 108 | text+tool_calls |
| SP01-M002 | 13,319 | 118 | text+tool_calls |
| SP01-M003 | 13,765 | 185 | text+tool_calls |
| SP03-M010 | 19,873 | 331 | text |
| SP03-M027 | 29,634 | 389 | text plus four parallel CLI tool calls |
| SP03-M046 | 67,144 | 505 | text plus five parallel CLI tool calls |
| SP03-M054 | 79,488 | 627 | text plus four parallel tool calls, including a mutation retry |
| SP03-M073 | 94,146 | 225 | text plus one exact remote CLI command |
| SP03-097 | 122,863 | 698 | text plus one confirmed switch-configuration apply |
| SP04-M018 | 19,548 | 145 | text+tool_calls |
| SP04-M026 | 31,058 | 376 | text+tool_calls |
| SP04-M031 | 39,292 | 202 | tool_calls |
| SP04-M046 | 52,085 | 130 | tool_calls |
| SP04-M081 | 76,659 | 342 | text+tool_calls |
| SP04-M106 | 94,962 | 340 | text+tool_calls |
| SP06-M008 | 18,829 | 389 | diagnostic prose plus three parallel host/container tool calls |
| SP06-M010 | 27,525 | 936 | diagnostic prose plus three parallel shell/Python/SQLite tool calls |
| SP06-M018 | 42,192 | 347 | migration plan plus one mutating Podman tool call |
| SP06-M019 | 42,769 | 270 | brief recovery prose plus one corrected Podman tool call |
| SP06-M023 | 48,626 | 1,570 | prose plus a complete Python SQLite-to-PostgreSQL migration script in a remote-write call |
| SP06-M042 | 73,149 | 330 | prose plus two parallel code-inspection tool calls |
| SP06-M050 | 83,233 | 497 | architectural recommendation in prose with Mermaid and exact configuration names |
| 合計 | 9,060 | 22 レンジ |
多数の長いプロンプトが9000以上の位置をサンプリングしました。
「アテンションがあれば何でもできる」しかし…どの種類?
このケースでは、3つの異なるプラグ可能なアテンションバックエンドをテストしています。FA2、FI、TRT。
モデルの入力、重み、キー/バリューキャッシュ、および出力ロジットは、bfloat16を使用しました。これは、32ビット浮動小数点数よりも大幅に精度は低いものの、広い数値範囲を維持する16ビット浮動小数点フォーマットです。
各ハードウェア/ソフトウェア座標は非常に再現性がありました。H200の結果は2つのプロバイダー間でバイト単位で同一であり、B200とローカルSM120の繰り返しもバイト単位で同一でした。したがって、違いはランダムな実行ごとのノイズではなく、異なる算術プログラムの安定した結果のように見えます。
通常の単純化に関する免責事項が適用されます。
図中のオレンジ色のボックスは、32ビット数値が16ビットbfloat16に丸められる場所です。青色のボックスは32ビット状態を保持します。紫色のボックスは、入力トークンが並列ワークグループにどのように分割されるかを示しています。
!!! 警告 !!!
[[画像: a5d06761d4d3fed9158d034359c934b4]]
長くて退屈な数学の時間です!目をそらしてください!!!
このセクションは完全に@splifingateのせいです。彼は私に数学の方法を教えてくれたので、皆さんには苦しんでもらいます。また、私の数学はGPUの精度と同じくらい正確です。[画像: :stuck_out_tongue:]
アテンションが計算しようとしていること
新しいトークン1つに対して、モデルはクエリベクトルを構築します。これは、現在探している情報です。以前の各トークンにはキーベクトルがあり、そのトークンがどれだけ関連しているかを測定するために使用され、バリューベクトルには、そのトークンが重みを受け取った場合に取得される情報が含まれています。
以前のトークン番号 token について、理想的な実数値計算は次のようになります。
\text{attention score}{\text{token}} = \text{scale} \times \operatorname{dot}(\text{query},\text{key}{\text{token}}),
\text{unnormalized weight}{\text{token}} = \exp(\text{attention score}{\text{token}}),
\text{normalized weight}{\text{token}} = \frac{\text{unnormalized weight}{\text{token}}} {\sum{\text{earlier tokens}}},\text{unnormalized weight}},
\text{attention output} = \sum{\text{earlier tokens}}} \text{normalized weight}{\text{token}} \times \text{value}{\text{token}} .
Qwenはアテンションヘッドごとに256個の数値を使用するため、そのスコアスケールは
\text{scale}=\frac{1}{\sqrt{256}}=\frac{1}{16}=2^{-4}.
そのスケールはバイナリで正確に表現されます。違いは、ドット積、指数関数、合計、中間丸め、および並列結合がどのように実行されるかから生じます。
計算がグループに分割される理由
27,525トークンの履歴は、1つのGPUワークブロックには大きすぎます。各アテンション実装は、履歴をグループに分割し、各グループの部分的な答えを計算し、その後で部分的な答えを結合します。
1つのグループについて、カーネルはまずローカル最大スコアを見つけます。これは、そのグループ内の最大のアテンションスコアを意味します。これを差し引くことで、指数関数がオーバーフローするのを防ぎます。
\text{local exponential weight}{\text{token}} = \exp( \text{attention score}{\text{token}} - \text{local maximum score} ).
正確な算術では、最終的な結合中にスケールファクターがキャンセルされるため、異なるローカル最大値を差し引いても最終結果は変わりません。実際のbfloat16パスでは、FlashAttention 2は次のような構造を使用します。
\text{partial weighted value sum} = \operatorname{float32_sum} \left( \operatorname{round to bfloat16} (\text{local exponential weight}) \times \text{value} \right),
一方、その正規化合計は、丸められていない32ビット指数重みを使用します。
\text{partial normalization sum} = \operatorname{float32 sum} (\text{local exponential weight}).
丸めはスケーリングと可換ではありません。一般に、
\operatorname{round to bfloat16}(e^{x-c}) \ne e^{-c} \operatorname{round to bfloat16}(e^x).
したがって、グループ境界を変更すると、ローカル最大値、各重みがbfloat16数値グリッド上のどこに着地するか、その重み付きバリュー合計、および最終的な結合ツリーの形状が変わる可能性があります。
FlashAttention 2が54、62、または87グループを選択する理由
FlashAttention 2は、このQwenデコードでは64トークンのキー/バリューブロックで動作します。27,525トークンの場合、ブロック数は次のようになります。
\text{key value block count} = \left\lceil\frac{27{,}525}{64}\right\rceil =431.
ストリーミングマルチプロセッサは、GPUの並列処理ユニットの1つです。H200は132、B200は148、テストされたSM120カードは188です。ピン留めされたFlashAttention 2のヒューリスティックは、デバイス容量を次のように推定します。
\text{device capacity} = 2\times\text{streaming multiprocessor count}.
Qwenは、グループ化クエリのリシェイプ後に4つのキー/バリューヘッドを持つため、候補となる分割数は次のようにスコアリングされます。
\text{work ratio} = \frac{4\times\text{candidate split count}} {\text{device capacity}},
\text{estimated efficiency} = \frac{\text{work ratio}}{\lceil\text{work ratio}\rceil}.
ソースは、推定効率が最高の候補の85%以上である最小の適格な分割数を選択します。これにより、次のようになります。
| プラットフォーム | GPU処理ユニット数 | 選択されたグループ数 | グループあたりの64トークンブロック数 | 最大正規グループ範囲 |
|---|---|---|---|---|
| H200 | 132 | 54 | 8 | 512 トークン |
| B200 | 148 | 62 | 7 | 448 トークン |
| SM120 | 188 | 87 | 5 | 320 トークン |
H200の境界はトークン0、512、1,024などから始まります。B200の境界は0、448、896から始まります。SM120の境界は0、320、640から始まります。したがって、同じトークンが各GPUで異なる隣接トークンと一緒に正規化されます。
実際の数値の代入
付属のPythonプログラムは、決定論的な27,525トークンの教育用入力を生成します。これらは合成スコアとバリューであり、キャプチャされたQwenアクティベーションではありませんが、プログラムは実際の64トークンブロックと実際の54/62/87分割数を使用します。
理想的な実数値出力は次のようになります。
\text{exact real number output}=1.325056137248.
スカラーFlashAttention-2ライクな計算は次を生成します。
| プラットフォーム | 分割数 | 最初のグループサイズ | 最初のローカル最大値 | 最終丸め前の32ビット出力 | 最終bfloat16出力 |
|---|---|---|---|---|---|
| H200 | 54 | 512 トークン | 1.875 | 1.3241630793 | 1.3203125 |
| B200 | 62 | 448 トークン | 1.750 | 1.3242336512 | 1.3281250 |
| SM120 | 87 | 320 トークン | 1.500 | 1.3242592812 | 1.3281250 |
このFlashAttention 2の例では、プラットフォーム選択のグルーピングのみが変更されました。H200の結果は1つのbfloat16値に収束しますが、B200とSM120の結果は次の値に丸められます。この例は境界を露出させるために意図的に選択されており、一般的に1つの分割数がより正確であるとは限りません。
バイブコードAIスロップをお楽しみください:
#!/usr/bin/env python3
"""Plain-language, dependency-free attention arithmetic walkthrough.
This is an educational scalar simulator, not a bit-for-bit CUDA emulator.
It uses the real partition geometry selected for the 27,525-token Qwen decode
example, while replacing 256-dimensional vectors and GPU reduction trees with
one scalar value per token and explicit float32 operations.
Run:
python attention_algorithms_walkthrough.py
python attention_algorithms_walkthrough.py --show-first-partitions 2
"""
from __future__ import annotations
import argparse
import math
import struct
from dataclasses import dataclass
TOKENS_PER_FLASH_ATTENTION_BLOCK = 64
TOKENS_PER_XQA_WORK_TILE = 256
TOKENS_PER_TENSOR_RT_LLM_WORK_TILE = 128
TRITON_SEGMENT_COUNT = 16
@dataclass(frozen=True)
class PlatformDetails:
platform_name: str
streaming_multiprocessor_count: int
@dataclass
class LocalAttentionSummary:
token_count: int
local_maximum_score: float
normalization_sum: float
weighted_value_sum: float
normalized_partial_output: float
log_sum_of_exponentials: float
@dataclass
class AttentionResult:
platform_name: str
algorithm_name: str
partition_count: int
float32_output_before_final_rounding: float
bfloat16_output: float
first_partition_summaries: list[LocalAttentionSummary]
qualification: str = ""
H200 = PlatformDetails("NVIDIA H200 (SM90 architecture)", 132)
B200 = PlatformDetails("NVIDIA B200 (SM100 architecture)", 148)
SM120 = PlatformDetails("NVIDIA SM120 card", 188)
def round_to_float32(number: float) -> float:
"""Round a Python number to IEEE float32."""
return struct.unpack("<f", struct.pack("<f", number))[0]
def round_to_bfloat16(number: float) -> float:
"""Round float32 to bfloat16, ties to even, then return it as a float."""
float32_bits = struct.unpack("<I", struct.pack("<f", round_to_float32(number)))[0]
tie_to_even_bias = 0x7FFF + ((float32_bits >> 16) & 1)
bfloat16_bits = (float32_bits + tie_to_even_bias) & 0xFFFF0000
return struct.unpack("<f", struct.pack("<I", bfloat16_bits))[0]
def add_as_float32(left_number: float, right_number: float) -> float:
return round_to_float32(round_to_float32(left_number) + round_to_float32(right_number))
def multiply_as_float32(left_number: float, right_number: float) -> float:
return round_to_float32(round_to_float32(left_number) * round_to_float32(right_number))
def choose_flash_attention_two_split_count(
total_token_count: int,
streaming_multiprocessor_count: int,
) -> tuple[int, int, int]:
"""Implement the pinned FlashAttention 2 split-count heuristic.
Qwen has four key/value heads after its grouped-query reshape. The FA2
source treats each streaming multiprocessor as capacity for two of these
128-thread work blocks.
"""
key_value_block_count = math.ceil(
total_token_count / TOKENS_PER_FLASH_ATTENTION_BLOCK
)
effective_device_capacity = 2 * streaming_multiprocessor_count
workers_before_splitting = 4
largest_candidate = min(128, effective_device_capacity, key_value_block_count)
eligible_candidates: list[tuple[int, float]] = []
for candidate_split_count in range(1, largest_candidate + 1):
changes_blocks_per_split = candidate_split_count == 1 or math.ceil(
key_value_block_count / candidate_split_count
) != math.ceil(key_value_block_count / (candidate_split_count - 1))
if not changes_blocks_per_split:
continue
wave_count = (
workers_before_splitting
* candidate_split_count
/ effective_device_capacity
)
estimated_efficiency = wave_count / math.ceil(wave_count)
eligible_candidates.append((candidate_split_count, estimated_efficiency))
best_efficiency = max(efficiency for _, efficiency in eligible_candidates)
selected_split_count = next(
candidate
for candidate, efficiency in eligible_candidates
if efficiency >= 0.85 * best_efficiency
)
blocks_per_split = math.ceil(key_value_block_count / selected_split_count)
return selected_split_count, key_value_block_count, blocks_per_split
def make_triton_partitions(total_token_count: int) -> list[list[int]]:
"""Triton decode: 16 contiguous segments made from 16-token tiles."""
tokens_per_tile = 16
tiles_per_segment = math.ceil(
total_token_count / (TRITON_SEGMENT_COUNT * tokens_per_tile)
)
tokens_per_segment = tiles_per_segment * tokens_per_tile
return [
list(
range(
segment_number * tokens_per_segment,
min((segment_number + 1) * tokens_per_segment, total_token_count),
)
)
for segment_number in range(TRITON_SEGMENT_COUNT)
if segment_number * tokens_per_segment < total_token_count
]
def make_flash_attention_two_partitions(
total_token_count: int,
split_count: int,
) -> list[list[int]]:
"""FA2: contiguous 64-token blocks, visited backward inside each split."""
block_count = math.ceil(total_token_count / TOKENS_PER_FLASH_ATTENTION_BLOCK)
blocks_per_split = math.ceil(block_count / split_count)
partitions: list[list[int]] = []
for split_number in range(split_count):
first_block = split_number * blocks_per_split
one_past_last_block = min(first_block + blocks_per_split, block_count)
token_indices: list[int] = []
for block_number in range(one_past_last_block - 1, first_block - 1, -1):
first_token = block_number * TOKENS_PER_FLASH_ATTENTION_BLOCK
one_past_last_token = min(
first_token + TOKENS_PER_FLASH_ATTENTION_BLOCK,
total_token_count,
)
token_indices.extend(range(first_token, one_past_last_token))
if token_indices:
partitions.append(token_indices)
return partitions
def make_xqa_partitions(
total_token_count: int,
partition_count: int,
) -> list[list[int]]:
"""FlashInfer XQA: round-robin streams of 256-token GPU work tiles."""
tile_count = math.ceil(total_token_count / TOKENS_PER_XQA_WORK_TILE)
partitions: list[list[int]] = []
for partition_number in range(partition_count):
token_indices: list[int] = []
for tile_number in range(partition_number, tile_count, partition_count):
first_token = tile_number * TOKENS_PER_XQA_WORK_TILE
one_past_last_token = min(
first_token + TOKENS_PER_XQA_WORK_TILE,
total_token_count,
)
token_indices.extend(range(first_token, one_past_last_token))
if token_indices:
partitions.append(token_indices)
return partitions
def make_tensor_rt_llm_partitions(total_token_count: int) -> list[list[int]]:
"""Visible reducer geometry: one partial for each 128-token work tile."""
return [
list(range(first_token, min(first_token + TOKENS_PER_TENSOR_RT_LLM_WORK_TILE, total_token_count)))
for first_token in range(0, total_token_count, TOKENS_PER_TENSOR_RT_LLM_WORK_TILE)
]
def calculate_local_attention_summary(
attention_scores: list[float],
scalar_values: list[float],
token_indices: list[int],
*,
normalization_uses_bfloat16_weights: bool,
partial_output_is_stored_as_bfloat16: bool,
) -> LocalAttentionSummary:
"""Calculate one partition with explicit datatype boundaries.
The input `attention_scores` are already-scaled query-key dot products.
Each `scalar_value` stands in for one component of a real 256-component
value vector.
"""
local_maximum_score = round_to_float32(
max(attention_scores[token_index] for token_index in token_indices)
)
normalization_sum = round_to_float32(0.0)
weighted_value_sum = round_to_float32(0.0)
for token_index in token_indices:
score_minus_local_maximum = round_to_float32(
attention_scores[token_index] - local_maximum_score
)
exponential_weight_float32 = round_to_float32(
math.exp(score_minus_local_maximum)
)
exponential_weight_bfloat16 = round_to_bfloat16(
exponential_weight_float32
)
weight_used_by_normalization = (
exponential_weight_bfloat16
if normalization_uses_bfloat16_weights
else exponential_weight_float32
)
normalization_sum = add_as_float32(
normalization_sum,
weight_used_by_normalization,
)
input_value_bfloat16 = round_to_bfloat16(scalar_values[token_index])
weighted_value = multiply_as_float32(
exponential_weight_bfloat16,
input_value_bfloat16,
)
weighted_value_sum = add_as_float32(weighted_value_sum, weighted_value)
normalized_partial_output = round_to_float32(
weighted_value_sum / normalization_sum
)
if partial_output_is_stored_as_bfloat16:
normalized_partial_output = round_to_bfloat16(normalized_partial_output)
log_sum_of_exponentials = round_to_float32(
local_maximum_score
+ round_to_float32(math.log(normalization_sum))
)
return LocalAttentionSummary(
token_count=len(token_indices),
local_maximum_score=local_maximum_score,
normalization_sum=normalization_sum,
weighted_value_sum=weighted_value_sum,
normalized_partial_output=normalized_partial_output,
log_sum_of_exponentials=log_sum_of_exponentials,
)
def merge_float32_numerator_partials(
partial_summaries: list[LocalAttentionSummary],
) -> float:
"""Triton-style merge of float32 numerator, maximum, and normalizer."""
global_maximum_score = round_to_float32(
max(summary.local_maximum_score for summary in partial_summaries)
)
merged_normalization_sum = round_to_float32(0.0)
merged_weighted_value_sum = round_to_float32(0.0)
for summary in partial_summaries:
correction = round_to_float32(
math.exp(
round_to_float32(
summary.local_maximum_score - global_maximum_score
)
)
)
merged_normalization_sum = add_as_float32(
merged_normalization_sum,
multiply_as_float32(summary.normalization_sum, correction),
)
merged_weighted_value_sum = add_as_float32(
merged_weighted_value_sum,
multiply_as_float32(summary.weighted_value_sum, correction),
)
return round_to_float32(merged_weighted_value_sum / merged_normalization_sum)
def merge_normalized_outputs_using_log_sums(
partial_summaries: list[LocalAttentionSummary],
) -> float:
"""FA2-style merge of normalized float32 output and float32 log-sum-exp."""
global_log_sum_maximum = round_to_float32(
max(summary.log_sum_of_exponentials for summary in partial_summaries)
)
merged_weight_sum = round_to_float32(0.0)
merged_output_sum = round_to_float32(0.0)
for summary in partial_summaries:
merge_weight = round_to_float32(
math.exp(
round_to_float32(
summary.log_sum_of_exponentials - global_log_sum_maximum
)
)
)
merged_weight_sum = add_as_float32(merged_weight_sum, merge_weight)
merged_output_sum = add_as_float32(
merged_output_sum,
multiply_as_float32(summary.normalized_partial_output, merge_weight),
)
return round_to_float32(merged_output_sum / merged_weight_sum)
def merge_xqa_normalized_bfloat16_partials(
partial_summaries: list[LocalAttentionSummary],
) -> float:
"""XQA-style merge of bfloat16 normalized output plus float32 statistics."""
global_maximum_score = round_to_float32(
max(summary.local_maximum_score for summary in partial_summaries)
)
merged_normalization_sum = round_to_float32(0.0)
merged_output_sum = round_to_float32(0.0)
for summary in partial_summaries:
maximum_correction = round_to_float32(
math.exp(
round_to_float32(
summary.local_maximum_score - global_maximum_score
)
)
)
corrected_normalization = multiply_as_float32(
summary.normalization_sum,
maximum_correction,
)
merged_normalization_sum = add_as_float32(
merged_normalization_sum,
corrected_normalization,
)
merged_output_sum = add_as_float32(
merged_output_sum,
multiply_as_float32(
summary.normalized_partial_output,
corrected_normalization,
),
)
return round_to_float32(merged_output_sum / merged_normalization_sum)
def merge_tensor_rt_llm_bfloat16_numerators(
partial_summaries: list[LocalAttentionSummary],
) -> float:
"""Visible TensorRT-LLM reducer recurrence, with already-scaled scores."""
running_maximum_score = float("-inf")
running_normalization_sum = round_to_float32(0.0)
running_weighted_value_sum = round_to_float32(0.0)
for summary in partial_summaries:
new_maximum_score = max(
running_maximum_score,
summary.local_maximum_score,
)
previous_state_correction = (
round_to_float32(0.0)
if running_maximum_score == float("-inf")
else round_to_float32(
math.exp(
round_to_float32(
running_maximum_score - new_maximum_score
)
)
)
)
new_partial_correction = round_to_float32(
math.exp(
round_to_float32(
summary.local_maximum_score - new_maximum_score
)
)
)
running_normalization_sum = round_to_float32(
multiply_as_float32(
running_normalization_sum,
previous_state_correction,
)
+ multiply_as_float32(
summary.normalization_sum,
new_partial_correction,
)
)
partial_numerator_bfloat16 = round_to_bfloat16(
summary.weighted_value_sum
)
running_weighted_value_sum = round_to_float32(
multiply_as_float32(
running_weighted_value_sum,
previous_state_correction,
)
+ multiply_as_float32(
partial_numerator_bfloat16,
new_partial_correction,
)
)
running_maximum_score = new_maximum_score
return round_to_float32(
running_weighted_value_sum / running_normalization_sum
)
def calculate_partials(
attention_scores: list[float],
scalar_values: list[float],
partitions: list[list[int]],
*,
normalization_uses_bfloat16_weights: bool,
partial_output_is_stored_as_bfloat16: bool,
) -> list[LocalAttentionSummary]:
return [
calculate_local_attention_summary(
attention_scores,
scalar_values,
token_indices,
normalization_uses_bfloat16_weights=normalization_uses_bfloat16_weights,
partial_output_is_stored_as_bfloat16=partial_output_is_stored_as_bfloat16,
)
for token_indices in partitions
]
def simulate_triton(
platform: PlatformDetails,
attention_scores: list[float],
scalar_values: list[float],
) -> AttentionResult:
partitions = make_triton_partitions(len(attention_scores))
summaries = calculate_partials(
attention_scores,
scalar_values,
partitions,
normalization_uses_bfloat16_weights=False,
partial_output_is_stored_as_bfloat16=False,
)
output = merge_float32_numerator_partials(summaries)
return AttentionResult(
platform.platform_name,
"Triton attention: 16 contiguous segments, float32 split state",
len(partitions),
output,
round_to_bfloat16(output),
summaries,
"The source-level segment formula is common; target-specific machine code still differs.",
)
def simulate_flash_attention_two(
platform: PlatformDetails,
attention_scores: list[float],
scalar_values: list[float],
) -> AttentionResult:
split_count, _, _ = choose_flash_attention_two_split_count(
len(attention_scores),
platform.streaming_multiprocessor_count,
)
partitions = make_flash_attention_two_partitions(
len(attention_scores),
split_count,
)
summaries = calculate_partials(
attention_scores,
scalar_values,
partitions,
normalization_uses_bfloat16_weights=False,
partial_output_is_stored_as_bfloat16=False,
)
output = merge_normalized_outputs_using_log_sums(summaries)
return AttentionResult(
platform.platform_name,
"FlashAttention 2: platform-selected contiguous split count",
len(partitions),
output,
round_to_bfloat16(output),
summaries,
)
def simulate_xqa(
platform: PlatformDetails,
attention_scores: list[float],
scalar_values: list[float],
) -> AttentionResult:
key_value_head_count = 4
batch_size = 1
partition_count = min(
max(
1,
platform.streaming_multiprocessor_count
// (batch_size * key_value_head_count),
),
math.ceil(len(attention_scores) / TOKENS_PER_XQA_WORK_TILE),
)
partitions = make_xqa_partitions(len(attention_scores), partition_count)
summaries = calculate_partials(
attention_scores,
scalar_values,
partitions,
normalization_uses_bfloat16_weights=True,
partial_output_is_stored_as_bfloat16=True,
)
output = merge_xqa_normalized_bfloat16_partials(summaries)
return AttentionResult(
platform.platform_name,
'FlashInfer decoder named "XQA": round-robin work tiles and bfloat16 partial outputs',
len(partitions),
output,
round_to_bfloat16(output),
summaries,
)
def simulate_tensor_rt_llm_reducer(
platform: PlatformDetails,
attention_scores: list[float],
scalar_values: list[float],
) -> AttentionResult:
partitions = make_tensor_rt_llm_partitions(len(attention_scores))
summaries = calculate_partials(
attention_scores,
scalar_values,
partitions,
normalization_uses_bfloat16_weights=False,
partial_output_is_stored_as_bfloat16=False,
)
output = merge_tensor_rt_llm_bfloat16_numerators(summaries)
return AttentionResult(
platform.platform_name,
"TensorRT-LLM generation reducer: 128-token partials and ordered merge",
len(partitions),
output,
round_to_bfloat16(output),
summaries,
"The reducer is source-backed. The packaged main attention body is represented illustratively here.",
)
def make_synthetic_27_525_token_input() -> tuple[list[float], list[float]]:
"""Deterministic teaching input chosen to expose a one-bfloat16-ULP split."""
repeating_scores = [
0.5, 1.0, 0.75, -2.0, -1.25, -0.75, -0.5, -3.0, -0.25, -2.25, 0.75, 0.5,
]
repeating_values = [
1.875, 3.5, -0.5, 6.0, 0.0, -1.0, 5.5, -0.5, -3.5, 0.5, 4.0, -2.5,
]
attention_scores: list[float] = []
scalar_values: list[float] = []
for token_index in range(27_525):
repeating_position = token_index % len(repeating_scores)
key_value_block_number = token_index // TOKENS_PER_FLASH_ATTENTION_BLOCK
score_offset = (key_value_block_number % 9) * 0.125
attention_scores.append(
repeating_scores[repeating_position] + score_offset
)
scalar_values.append(repeating_values[repeating_position])
return attention_scores, scalar_values
def calculate_exact_real_number_reference(
attention_scores: list[float],
scalar_values: list[float],
) -> float:
largest_score = max(attention_scores)
exponential_weights = [
math.exp(score - largest_score) for score in attention_scores
]
return math.fsum(
weight * value
for weight, value in zip(exponential_weights, scalar_values)
) / math.fsum(exponential_weights)
def print_result(result: AttentionResult, partition_examples_to_show: int) -> None:
print(f"\n{result.platform_name}")
print(f" Algorithm: {result.algorithm_name}")
print(f" Number of partitions: {result.partition_count}")
print(
" Float32 output before final bfloat16 rounding: "
f"{result.float32_output_before_final_rounding:.10f}"
)
print(f" Final bfloat16 output: {result.bfloat16_output:.10f}")
if result.qualification:
print(f" Important qualification: {result.qualification}")
for partition_number, summary in enumerate(
result.first_partition_summaries[:partition_examples_to_show]
):
print(f" Partition {partition_number}:")
print(f" tokens processed: {summary.token_count}")
print(f" largest attention score in this partition: {summary.local_maximum_score:.7f}")
print(f" sum used to normalize the weights: {summary.normalization_sum:.7f}")
print(f" weighted-value sum before normalization: {summary.weighted_value_sum:.7f}")
print(f" normalized partial output stored for merge: {summary.normalized_partial_output:.7f}")
print(f" log of this partition's exponential sum: {summary.log_sum_of_exponentials:.7f}")
def demonstrate_target_specific_reduction_order() -> None:
half_of_one_float32_unit = 2.0 ** -24
left_associated = add_as_float32(
add_as_float32(1.0, half_of_one_float32_unit),
half_of_one_float32_unit,
)
right_associated = add_as_float32(
1.0,
add_as_float32(
half_of_one_float32_unit,
half_of_one_float32_unit,
),
)
print("Reduction-order example using the same three real numbers:")
print(f" Add left pair first: {left_associated:.10f}")
print(f" Add right pair first: {right_associated:.10f}")
print(" The second result is one float32 unit larger because the parenthesis tree changed.\n")
def main() -> None:
argument_parser = argparse.ArgumentParser()
argument_parser.add_argument(
"--show-first-partitions",
type=int,
default=1,
help="number of initial partition summaries to print for each algorithm",
)
arguments = argument_parser.parse_args()
demonstrate_target_specific_reduction_order()
attention_scores, scalar_values = make_synthetic_27_525_token_input()
exact_reference = calculate_exact_real_number_reference(
attention_scores,
scalar_values,
)
print("Synthetic 27,525-token teaching input (not captured Qwen activations)")
print(" Each attention score is an already-scaled query-key dot product.")
print(" Each scalar value represents one component of a 256-component value vector.")
print(f" Exact real-number softmax result: {exact_reference:.12f}")
print("\n=== Triton requested backend on all three platforms ===")
for platform in (H200, B200, SM120):
print_result(
simulate_triton(platform, attention_scores, scalar_values),
arguments.show_first_partitions,
)
print("\n=== Explicit FlashAttention 2 on all three platforms ===")
for platform in (H200, B200, SM120):
print_result(
simulate_flash_attention_two(
platform,
attention_scores,
scalar_values,
),
arguments.show_first_partitions,
)
print("\n=== FlashInfer requested backend resolves differently by platform ===")
print_result(
simulate_xqa(H200, attention_scores, scalar_values),
arguments.show_first_partitions,
)
print_result(
simulate_tensor_rt_llm_reducer(B200, attention_scores, scalar_values),
arguments.show_first_partitions,
)
print_result(
simulate_xqa(SM120, attention_scores, scalar_values),
arguments.show_first_partitions,
)
if __name__ == "__main__":
main()
上記の「スロップジェネレーター」は、各実装について local_maximum_score、normalization_sum、weighted_value_sum、normalized_partial_output のような説明的な中間名を出力します。
バックエンド名は4つのデコードアルゴリズムに展開される
スコアリングされたSP06ワークロードは、99.84%が1トークンずつのデコードであるため、デコードアルゴリズムが比較を支配します。
Triton Attention は常に16個の連続したトークングループを使用します。重み付きバリュー合計、ローカル最大値、正規化合計を32ビット浮動小数点数として格納し、最大16個のグループレコードを32ビット還元ツリーで結合します。
FlashAttention 2 は連続した64トークンブロックを使用しますが、その54/62/87のグループ数はプラットフォームの処理ユニット数に依存します。正規化された部分出力とそれに対応する対数正規化統計量を32ビット浮動小数点数として格納します。
FlashInferのデコーダー「XQA」 はH200とSM120で実行されます。XQA はソースのカーネルファミリー名です。H200では33、SM120では47のラウンドロビングループを使用し、256トークンのGPUワークタイルをそれらのグループ間で循環的に割り当てます。正規化合計と重み付きバリュー計算の両方にbfloat16指数重みを使用します。また、最終的な結合の前に、正規化された各グループ出力をbfloat16に丸めます。
B200上のFlashInfer は、代わりにTensorRT-LLMのジェネレーションアテンションカーネルを選択します。その可視レデューサーは、128トークンワークタイルごとに1つのbfloat16重み付きバリュー部分と32ビットの最大値および正規化統計量を消費し、それらの部分を順序付けられた実行中の再帰を使用して結合します。メインアテンションボディはパッケージ化されたマシンコードであるため、その内部確率丸めはカーネル起動トレースなしでは述べられません。
TritonにおけるGPU固有のローリング
Tritonソースには、「ドット積」や「合計」のような抽象的な操作が含まれています。ターゲット固有のGPUローリングは、特定のNVIDIAアーキテクチャがサポートするレーンレイアウト、テンソルコア命令、シャッフル操作、および還元ツリーにそれらの抽象操作をマッピングするコンパイラステージです。
Triton program:
-> common compiler representations
-> SM90, SM100, or SM120-specific layout
-> virtual GPU instructions
-> final machine code
ピン留めされたTritonアテンションソースは、すべてのプラットフォームで共通のLLVMコンパイラ表現を通じて同一ですが、ターゲットレイアウト、仮想命令、およびマシンコードバイナリは異なります。
浮動小数点括弧ツリーを変更するだけで結果が変わる可能性があります。1.0の場合、2^{-24}は次のfloat32数値までの距離の半分です。
\operatorname{round to float32} \left( \operatorname{round to float32}(1+2^{-24})+2^{-24} \right) =1,
しかし
\operatorname{round to float32} \left( 1+ \operatorname{round to float32}(2^{-24}+2^{-24}) \right) =1.0000001192092896.
両方の式には同じ3つの実数が含まれています。2番目の式は2つの小さな加算を先に実行するため、それらの結合値は丸めを生き残ります。
これは、どのローリングされた命令が最初に実際のQwenビットを変更するかを証明するものではありません。同一の高レベルソースが、同一の実行可能浮動小数点仕様ではない理由を説明しています。
さて、それでどうなるのか?
アテンションバックエンドは、表面上は重要ではないように見えますが、詳細に調査したかった可変性の1つの可視的なソースでした。膨大な実験結果の集計と解析を続け、次回はより面白いものを持ってきます。
編集:JW向け数学なしバージョン。これは面白すぎたので投稿せずにはいられませんでした。
さて、可愛い子、座って。クレヨンは片付けて。これは重要よ。
ママ行列とパパ行列がとても愛し合うと、ドット積が生まれます。さて、普通の家族では、それが物語の終わりだと思うでしょう。しかし、そうではありません。アテンションは、文中のすべての単語が他のすべての単語と手をつなぐことを望みます。すべてです。一度に。それは、学校全体を招待して、すべての子供が他のすべての子供に感謝の手紙を書かなければならない誕生日パーティーのようなものです。それはN二乗の手紙よ、ハニー。あなたの手は落ちるでしょう。
そして、本当に愚かな部分はこれです。GPUは、目の前の非常に小さくて超高速な机と、廊下の奥にある巨大で遅いクローゼットを持っています。古いアテンションは、すべての手紙を書き、その巨大な山全体を廊下に運び、クローゼットに押し込み、戻ってきて、「待てよ、それが必要だ」と言い、再び廊下を歩き、山を取り出し、戻ってきて、少し計算してから、ボールをどこに置いたか忘れたゴールデンレトリバーのように繰り返していました。GPUは考えるのが遅かったのではありません。クローゼットに歩いていくのが遅かったのです。本当に画期的なことです。
そこで、とても疲れた大人たちがFlash Attentionを発明しました。これは基本的に、先生が幼稚園の初日に言ったことと同じです。クレヨンを一度に数本だけ取り出すのです。巨大な山全体を作る代わりに、単語の小さなチャンクを掴み、そこでそのすべてを計算し、小さな答えだけを書き留め、次に別のチャンクを掴みます。大きな山を作ることはありません。大きな山は存在しません。クローゼットはほとんど関与しません。みんな幸せです。
「でも、まだみんなを見ていないのに、ソフトマックスをどうやって計算するの?」素晴らしい質問です。そして、なぜあなたはソフトマックスを知っているのですか、あなたは5歳なのに。答えは、おばあちゃんが一番好きな孫を何度も変えるときのように、小さな実行中の集計を維持することです。新しいチャンクが現れるたびに、以前の数値を少し修正します。これはオンラインソフトマックスと呼ばれ、このすべてが機能する理由であり、誰も十分に感謝していません。
最後のトリックはさらに愚かです。間違いから学ぶときが来ると、GPUは再びそれらの感謝の手紙を必要とします。クローゼットに戻るのでしょうか?いいえ。それは単に最初から計算をやり直すのです。なぜなら、宿題を2回やる方が、クローゼットに1回歩くよりも速いことが判明したからです。大人があなたに「一生懸命働くのではなく、賢く働け」と言うとき、それを考えてみてください。
それがFlash Attentionです。ほぼ同じ答え、ほぼ同じ計算、大きな山なし、歩く距離ははるかに少なく、そしてみんな、それは最初から明白だったかのように振る舞います。今すぐ友達に話して、彼らが気にしないのを見てください。