1つの内積を一度だけ書くと、SPYのリターン5,404個では、2レーンで13,514命令、16レーンで1,755命令です。ところが30要素だと順位が逆転し、4レーンは51命令、16レーンは85命令です。自分の幅を知らないカーネルは、何を正しく行わなければならないのでしょうか。
考え方をやさしい言葉で
ここまでの流れ。 前のトピックでは LaneSim にギャザーとスキャッターを加えました。最初からすべてのカーネルは sim.lanes に対して書かれていましたが、頭の中ではたいてい4レーンの1台のマシンを想定していました。実際のコードは幅を選べません。同じプログラムが、doubleの4レーンのノートPCでも、8レーンのサーバでも、16レーンのサーバでも動くことがあり、コンパイラは次のマシンがどれかを推測できません。その答えがポータブルSIMDで、C++26の std::simd、RustのポータブルSIMD(執筆時点では機能フラグの裏)、Highwayやxsimdといったライブラリのもとになっているのもこの考え方です。
カーネルは4・8・16を書きません。マシンにレーン数を尋ね、その分ずつデータを進み、すべての計算をベクトル型の演算子で行います。コンパイラやライブラリが、各演算子を対象が持つ1命令に変えます。
LaneSim でのポータブルな型が Vec です。レジスタを持ち、自分がどのマシンのものかを覚えています。x + y は vadd 1回、x * y は vmul 1回、Vec.load(sim, a, i) は vload 1回、acc.sum() は hsum 1回です。何も追加されず、カウントは手書き版とまったく同じで、そこが要点です。抽象化は無料で、マシン間で変わるのは幅だけです。
最小の例:1つの式、どんな幅でも
これが型の全体です。機械命令を1つ包むだけのメソッドはあらかじめ書かれていて、2つの演算子をあなたが書きます。__add__ と __mul__ を見てください。どちらも、2つのオペランドが同じマシンのものかを確かめてから、LaneSim をちょうど1回呼びます。4レーンのマシンのベクトルと8レーンのマシンのベクトルは足せません。コンパイラが simd<double, 4> と simd<double, 8> の混在を拒むのと同じです。
class Vec: """A register that remembers its machine, so a kernel can be written with + - * and never mention the lane count. This is the idea of C++26 `std::simd`, Rust's portable SIMD and libraries such as Highway: the width is a parameter of the type, not something the kernel code spells out. Every operation is still ONE instruction on the machine the vector came from. """ def __init__(self, sim, values): self.sim = sim self.values = list(values) @property def lanes(self): return self.sim.lanes @classmethod def load(cls, sim, mem, i): """The `lanes` numbers from mem[i]: one `vload`.""" return cls(sim, sim.vload(mem, i)) @classmethod def splat(cls, sim, x): """`x` in every lane: one `vsplat`.""" return cls(sim, sim.vsplat(x)) def store(self, mem, i): """Write the vector to mem[i:i + lanes]: one `vstore`.""" self.sim.vstore(mem, i, self.values) def sum(self): """Add all the lanes into one ordinary number with `hsum`.""" return self.sim.hsum(self.values) def __sub__(self, other): """Lane-wise difference as a new Vec: one `vsub`.""" return Vec(self.sim, self.sim.vsub(self.values, other.values)) def __add__(self, other): """Lane-wise sum as a new Vec: one `vadd`, on the machine both vectors share. If the two vectors come from different machines (`self.sim is not other.sim`) raise ValueError("vectors must come from the same machine") and count nothing. """ if self.sim is not other.sim: raise ValueError("vectors must come from the same machine") return Vec(self.sim, self.sim.vadd(self.values, other.values))1 def __mul__(self, other): """Lane-wise product as a new Vec: one `vmul`, on the machine both vectors share. If the two vectors come from different machines raise ValueError("vectors must come from the same machine") and count nothing. """ if self.sim is not other.sim: raise ValueError("vectors must come from the same machine") return Vec(self.sim, self.sim.vmul(self.values, other.values))
- 1マシンへの呼び出しは1回。抽象化が命令を増やすことはありません。
# One expression, three machines: the same code, different widthsfor width in (2, 4, 8): sim = LaneSim(width) x = Vec.load(sim, [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0], 0) y = Vec.splat(sim, 10.0) z = x * y + x print(width, z.values, sim.counts)
2 [11.0, 22.0] {'vload': 1, 'vsplat': 1, 'vmul': 1, 'vadd': 1}
4 [11.0, 22.0, 33.0, 44.0] {'vload': 1, 'vsplat': 1, 'vmul': 1, 'vadd': 1}
8 [11.0, 22.0, 33.0, 44.0, 55.0, 66.0, 77.0, 88.0] {'vload': 1, 'vsplat': 1, 'vmul': 1, 'vadd': 1}同じ x * y + x の1行が、3台のマシンで長さの違う3つのレジスタになり、毎回 vmul 1回と vadd 1回です。これがポータブルなコードの魅力で、カーネルは同じテキストのまま、各命令がどれだけの仕事をするかはマシンが決めます。
積み上げる:すべての幅での内積
ラボのカーネル portable_dot に進みます。これは過去のトピックの3つの部品を組み合わせたもので、最後に1回だけ縮約する部分和、余りの要素のためのスカラの端数処理、そして Vec の演算子です。幅が現れるのは、1回だけ読む sim.lanes だけです。ラボの規則はわざと厳しく、本体に4や8のリテラルがあるか、vadd を直接呼ぶと指摘されます。どちらもカーネルを特定のマシンに縛るからです。
def portable_dot(sim, a, b): """The dot product of two arrays of ANY length, written once for ANY lane count, with `Vec` and no lane-count constants. Let `body` be the largest multiple of `sim.lanes` that fits in the length. If `body` is not 0: a `Vec.splat` of 0.0 for the partial sums, then per pass `sim.loop()`, two `Vec.load`, and `acc = acc + x * y` (a `vmul` and a `vadd`), then `acc.sum()` once. The leftover elements after `body` are added one at a time: `sim.loop()`, two `sload`, `smul` and `sadd` into the running total. Empty arrays return 0.0 and count nothing. If the arrays differ in length raise ValueError("arrays must have the same length"). Do not call `vadd`, `vmul` or `vfma` directly, and write no lane count: `sim.lanes` is the only place the width appears. """ if len(a) != len(b): raise ValueError("arrays must have the same length") lanes = sim.lanes1 body = len(a) - len(a) % lanes total = 0.0 if body: acc = Vec.splat(sim, 0.0) for i in range(0, body, lanes): sim.loop() acc = acc + Vec.load(sim, a, i) * Vec.load(sim, b, i)2 total = acc.sum() for i in range(body, len(a)): sim.loop() total = sim.sadd(total, sim.smul(sim.sload(a, i), sim.sload(b, i))) return total
- 1幅が現れるのはここだけです。
- 2vadd と vmul ではなく、Vec の
+と*。
同じ10個の数に対して、すべての幅で同じ関数を実行します。答えは毎回同じ内積の385.0です。命令数は違ってきますが、レーン数から単純に予想される形にはなりません。
# The same kernel on ten numbers at every width: the answer, the instructions, and the scalar baseline of 50ten = [float(i) for i in range(1, 11)]for width in (2, 4, 8, 16): sim = LaneSim(width) print(f"{width:2} lanes: dot = {portable_dot(sim, ten, ten)}, {sim.total():2} instructions")1
2 lanes: dot = 385.0, 29 instructions 4 lanes: dot = 385.0, 26 instructions 8 lanes: dot = 385.0, 23 instructions 16 lanes: dot = 385.0, 50 instructions
- 116レーンは10個の数ではレジスタ1つも満たせず、すべて端数で50命令です。
この式がトレードオフを示します。幅の広いレジスタは第1項を小さくしますが、幅が2倍になるたびに縮約が1段階増え、端数も長くなりえます(最大 L - 1 要素で、各5命令)。長い配列では第1項が支配的で、いちばん広いマシンが勝ちます。短い配列では端数と固定コストが支配的になり、狭い幅が勝つことがあります。best_width は、この問いを推測ではなく数字で確かめる道具です。
# Which width wins, by array lengthfor n in (3, 10, 30, 100, 5404): counts = {} for width in (2, 4, 8, 16): sim = LaneSim(width) portable_dot(sim, [0.0] * n, [0.0] * n) counts[width] = sim.total() print(f"n = {n:4}: {counts} best {best_width(n, [2, 4, 8, 16])} scalar {5 * n}")1
n = 3: {2: 14, 4: 15, 8: 15, 16: 15} best (2, 14) scalar 15
n = 10: {2: 29, 4: 26, 8: 23, 16: 50} best (8, 23) scalar 50
n = 30: {2: 79, 4: 51, 8: 53, 16: 85} best (4, 51) scalar 150
n = 100: {2: 254, 4: 131, 8: 88, 16: 60} best (16, 60) scalar 500
n = 5404: {2: 13514, 4: 6761, 8: 3403, 16: 1755} best (16, 1755) scalar 27020- 1勝つのは n = 30 で4、n = 10 で8であり、いつも最も広い幅とは限りません。
- ポータブルなライブラリ幅の決め方
- std::simd<double, N> (C++26)N レーンの演算子付きベクトル型。指定しなければ N はマシンのネイティブ幅
- std::simd::f64x4 (Rust)固定幅のベクトル型。たとえばdouble 4個。幅は自分で選び、コンパイラがターゲットごとに変換
- Highway, xsimdソースは1つで、ターゲットごとの版を持つライブラリ。幅はビルド対象のターゲットから決まる
よくある間違い
幅を決め打ちで書く。 「うちのマシンは8レーン」と考えて8ずつ進むカーネルは、4レーンのマシンに出会うと、2つに1つのレジスタを飛ばして、黙って間違ったデータで動きます。個々の命令はどれも有効なので、エラーは出ません。下の壊れた版を、4レーンのマシンでポータブル版と並べて実行し、合計を比べてみましょう。
# A kernel that assumed 8 lanes, run on a 4-lane machine: it skips every second registerdef dot_for_eight(sim, a, b): acc = Vec.splat(sim, 0.0) for i in range(0, len(a), 8):1 acc = acc + Vec.load(sim, a, i) * Vec.load(sim, b, i) return acc.sum()four = LaneSim(4)ones = [1.0] * 16print(dot_for_eight(four, ones, ones), portable_dot(LaneSim(4), ones, ones))
8.0 16.0
- 18ずつ進むので、読むのは0と8で、4や12は読みません。
最も広いマシンがいちばん速いと思い込む。 上の表では、10要素や30要素で16レーンが負けています。縮約の固定コストと長い端数が、得を食いつぶすのです。クオンツのコードでは、数十銘柄の1日分のクロスセクションのように、短い配列がよく現れます。ポータブルなカーネルは仕事の半分にすぎず、配列の長さで幅を選ぶのがもう半分で、次のトピックではCPUの機能によってそれを行います。
# Vectors from machines of different widths cannot be mixedwide = Vec.splat(LaneSim(8), 1.0)narrow = Vec.splat(LaneSim(4), 1.0)wide + narrow
ValueError: vectors must come from the same machine
LaneSim のカウントは「はい」と答えます。実際のコンパイラでも、1命令に対応する演算子についてはそうですが、狭い命令セットでのギャザーのように、ターゲットにない演算は複数の命令でエミュレートされます。ポータブルなカーネルでも、遅い経路が隠れていることがあります。
タスクの内容
- タスクと関数やること
- Vec.__add__(self, other)両方のベクトルが同じマシンのものかを確かめ、
x + yをvadd1回で行います。vaddを呼ぶ - Vec.__mul__(self, other)
x * yをvmul1回で行い、同じマシン検査をします。vmulを呼ぶ - portable_dot(sim, a, b)任意の長さ・任意の幅の内積を
Vecで書き、端数はスカラで処理します。レーン数のリテラルもvaddの直接呼び出しもなし - best_width(n, widths)命令数が最小の
(width, instructions)。各幅はportable_dotを実行して測ります。同点なら広いほう
portable_dot は10要素で、16レーンでは50命令、8レーンでは23命令です。この差はどこから来ますか。次へ。 ポータブルなカーネルはどんな幅でも動きますが、実際に手元にあるマシンが提供する命令セットは1つです。AVX2でdouble 4個かもしれず、AVX-512で8個かもしれず、どちらでもないかもしれません。次のトピックは最終課題の前の最後の部品です。プログラムは一度ビルドされ、起動時にCPUが対応すると報告する内容に応じてどの版を実行するかを選び、チップにない命令の実行は丁寧に断る必要があります。
ラボ:採点される内容
4タスク · 100点Vec.__add__でx + yをvadd1回にする25点Vec.__mul__でx * yをvmul1回にする25点portable_dotで内積を一度だけ書く25点best_widthで幅を選ぶ25点