Files
wasm2go/internal/gcasm/simdsplice_fuse_crossdot_x64.go
b7b7026cc5 gcasm: amd64 cross-chain raw dots for the repack kernels + F16C scale conversion (#62)
* gcasm: fuse the interleaved repack kernels' cross-chain dots on amd64; F16C scale conversion

The ggml q8_0x4 repack gemv/gemm keeps two i32x4_add chains per
block — all extend_low half dots in one, all extend_high in the
other, over the same byte-source pairs — and combines them with the
even/odd dword-select shuffles. The existing (low, high) pairing walk
never fires on that shape, so amd64 ran it as literal SSE pair ops
while arm64's a64CrossSdotRewrite turned it into raw SDOT chains.

x64CrossDotRewrite is the amd64 twin: it matches the combine on the
raw node forms and rebuilds it as a chain of synthetic raw block
dots. Emission computes each 16-byte leaf in the 8-lane VPMADDWD
domain across one ymm and collapses to the four-consecutive-byte
grouping in-register (VPHADDD + VEXTRACTI128 + VPUNPCKLQDQ), then
VPADDD-accumulates. i16 products of i8 lanes cannot overflow and
VPMADDWD widens into i32, so every step is exact for ALL inputs —
unlike the VPSIGNB/VPMADDUBSW route native kernels use, which wraps
on -128 — and i32 wraparound addition is associative, so regrouping
is bit-identical. Feature-body only; portable twins keep the SSE
lowering via the existing dual-body dispatch.

f16x4_cvt feature bodies now convert with mask + VPACKUSDW +
VCVTPH2PS (F16C, which the HasAVX2 gate already requires) instead of
the 15-op SSE2 bit trick — the x64 mirror of the arm64 xtn+fcvtl
pair. Both sequences are all-VEX-128, so x64TreeVexClean treats them
as clean and no ymm upper state is dirtied.

Co-Authored-By: Claude Fable 5 <[email protected]>

* gcasm: pair-domain wide raw-dot chains; skip the dead f16 mask after zero-extending loads

The per-leaf raw-dot emission collapsed every 16-byte leaf through
VPHADDD-ymm + VEXTRACTI128 — three lane-crossing shuffles per leaf,
the exact shape the earlier chunk-widening experiment measured as a
loss on Zen 3. The chain now accumulates in the 8-lane VPMADDWD pair
domain across a full ymm (four ops per leaf, only the two unavoidable
VPMOVSXBW crossings) and collapses ONCE per chain at the combine
slot. The running value's ymm upper must survive between links, so
the wide form is selected only for fully-VEX trees (region-exit
VZEROUPPER, every other write VEX); anything else falls back to the
self-contained per-leaf form. Exactness is unchanged: same integer
products, i32 add reassociation only.

f16x4_cvt over v128_load16x4_u drops its VPAND: the load
zero-extends, so the lanes' upper halves are already empty and
VPACKUSDW packs them exactly.

Co-Authored-By: Claude Fable 5 <[email protected]>

* codegen: fuse loops whose leftover interveners derive from bumped arguments or died into the tree

The interleaved repack kernels' inner loops matched the countdown
shape, window-fused their whole body, and carried their accumulators
— then failed the final leftover-intervener invariance check on two
statement kinds and fell back to the per-iteration window path, whose
region boundaries (result parking, VZEROUPPER, argument
re-materialization, scalar glue) dominate the prompt-processing
profile on both arches:

- a derived address ("q = p + off", one or two levels deep) whose
  argument slot can simply take p's own bump: the hoisted initial
  reads p's pre-loop value, which is exactly the slot's base, and the
  slot then advances in lockstep. The existing reassociation only
  covered bump targets that are not arguments themselves.
- a value whose only readers were CONSUMED into the fused tree (the
  tree recomputes it through its own scalar chain — the f16 LUT index
  load): dead once the loop fuses, droppable.

On the llama engine this upgrades the four hot repack gemv loops
(plus one more) to fused loops; previously only one loop in the whole
module fused.

Co-Authored-By: Claude Fable 5 <[email protected]>

* gcasm: hoist fused-loop window checks for floor loops and chain-addressed narrow loads

The loop-level window-check hoist only covered pretest power-of-two
loops and rng-windowed loads with plain scalar bases. The interleaved
repack loops are do-while floor loops (unit step, signed threshold
backedge) whose loads address through scalar-chain sums
(bumpedBase + columnBase + const) — every load kept its 7-op
per-iteration bounds/address dance, which the profile puts at the
top of what remains after loop fusion.

- Iteration-count form 2: a do-while ExitGT unit-step loop runs
  max(counter - thresh, 1) iterations, so iters-1 =
  counter - thresh - 1 clamped at zero — computable at entry.
- Address resolution generalizes to affine chains: ArgScalar/ArgSum
  or a scalar_i32_add tree over them; the stride is the sum of the
  terms' bump deltas, and one check per (terms, end, stride) family
  covers every load in it.
- Narrow loads join the rewrite through unchecked twins
  (v128_load32_splat_nc / load16x4_u_nc / load32_zero_nc /
  load64_zero_nc, x64-splicer-local), all emitting single folded
  indexed instructions; a full-width chain already terminating in
  R12 also drops its redundant self-move.

Co-Authored-By: Claude Fable 5 <[email protected]>

* gcasm: retarget the repack GEMM to native 4x4 tile kernels

The engine's wasm-side q8_0x4 GEMM (exported as dbg_gemm_q8_0_4x4
exactly so the transpiler can find it) is shaped as four sequential
gemv passes — the form the loop fusion is proven to claim — which
gives up the tile's 4x weight reuse: prompt processing runs at
token-generation speed per token.

The whole feature body now becomes a native 4x4 tile kernel through
the existing dual-body dispatch (portable twin = the transformed wasm
body):

- arm64: by-element SDOT — the activation block interleaves the four
  rows' 4-byte groups contiguously, so each 16-byte weight group is
  one load + four `sdot vAcc.4s, vW.16b, vA.4b[row]`, the native
  dotprod kernel's own shape. Gated on CPUDotProd.
- amd64: AVX2 nest sign-extends each weight group once per ymm and
  runs four broadcast-activation VPMADDWD accumulations against it;
  a VNNI entry branch uses VPDPBUSD with the exact +128 bias
  identity, with the per-row byte sums accumulated by ONE extra
  VPDPBUSD per group (ones dot the activation block yields all four
  rows' group sums). Gated on HasAVX2 / gcasmHasAVX512VNNI.

Integer arithmetic is exact; the per-block scale accumulation keeps
the sequential form's per-row block order but fuses mul+add, so the
retarget is fast-math-only, like the nrc2 tile kernel. Every span the
loop nest will touch is bounds-checked against memSize at entry.

Both kernels assemble and link on every host in the new gate tests;
the numeric comparison against a scalar reference executes on
matching hosts (the arm64 kernel passes natively on Apple Silicon;
CI's amd64 runner executes the AVX2 arm).

Co-Authored-By: Claude Fable 5 <[email protected]>

* gcasm: repack GEMM kernels keep the wasm's own mul/add rounding; opt-out env

The tile kernels' per-block scale accumulation switches from fused
multiply-add to the exact multiply/multiply/add sequence the wasm
gemm (and the fused GEMV loops) execute, so the batched path rounds
identically to the wasm semantics it replaces — keeping the batched
and single-row prompt paths as close as the engine's own contract.
(The prompt batch-size divergence observed with qwen on arm64
reproduces byte-for-byte on the PREVIOUS engine as well: it is the
known batched-vs-incremental near-tie flip, not a kernel effect.)

WASM2GO_NO_REPACK_GEMM=1 disables the retarget for A/B bisection,
mirroring the other WASM2GO_* iteration toggles.

Co-Authored-By: Claude Fable 5 <[email protected]>

* lower: pin the exported repack GEMM out-of-line so its retarget stays live

wasm2go's own function inliner (leaf, <=4096 bytes) was splicing the
exported dbg_gemm_q8_0_4x4 body into its caller
(forward_mul_mat_one_chunk), so the standalone body the gcasm backend
retargets to the native 4x4 tile kernel was dead — the tile never
ran, and pp went through the inlined per-pass GEMV shape instead.
(Binaryen was not involved: -Oz leaves the wasm-level calls intact.)

The inliner now pins any dbg_gemm_-exported function out-of-line
regardless of size. GEMV is deliberately left inlinable: it runs at
nrows=1 in the decode hot path, where per-call overhead outweighs the
tile — pinning it out-of-line measured a tg regression, so only the
batched GEMM is pinned.

Co-Authored-By: Claude Fable 5 <[email protected]>

* gcasm: deduplicate shared emission shapes in the amd64 repack work

Pure refactor — emitted assembly is byte-identical (verified by
dumping every touched emission path before and after):

- Promote the even/odd dword-select shuffle classifier out of
  a64CrossSdotRewrite into package-level crossSelKind and drop the
  verbatim x64 copy; the patterns are wasm-level constants shared by
  both arch rewrites.
- Extract x64PairFold for the VPHADDD/VEXTRACTI128/VPUNPCKLQDQ
  pair-domain collapse emitted from three sites.
- Merge the four unchecked narrow-load cases in x64FusedLoad into one
  table-shaped case (VMOVSS/VMOVQ plus the op's own widen).
- Replace the hand-rolled insertion sort in x64CrossDotRewrite with
  sort.Slice over the leaf records used directly.
- Share the repack GEMM ABI0 argument frame layout between the a64
  and x64 emitters (repackGemmArgs).
- Build the per-arch trapstub once in writeGemmRunTree instead of
  writing the amd64 kernel file twice.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* gcasm: make the repack GEMM opt-out a config option, not an env var

Replace the WASM2GO_NO_REPACK_GEMM environment check with
DisableRepackGemm threaded through the option structs — the project's
configuration pattern (codegen.Options -> gcasm.Config, CLI flag
-no-repack-gemm). The retarget-target scan moves into
repackGemmExport with a unit test over the gate combinations.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Claude Fable 5 <[email protected]>
2026-09-02 19:13:26 +09:00

235 lines
8.7 KiB
Go

package gcasm
import (
"sort"
"github.com/goccy/wasm2go/internal/simdfuse"
)
// Cross-chain raw dot selection (amd64).
//
// Interleaved-layout kernels (ggml's q8_0x4 repack gemv/gemm) keep
// TWO i32x4_add chains per block — one over all the extend_low half
// dots, one over all the extend_high half dots of the same byte-source
// pairs — and combine them with the even/odd dword-select shuffles:
//
// add(shuffle(dl, dh, even), shuffle(dl, dh, odd))
//
// Per output lane that is the product sum of one FOUR-CONSECUTIVE-BYTE
// group, summed over the chains' common leaf sequence (see the arm64
// twin a64CrossSdotRewrite for the lane algebra). The x64Dot8Rewrite
// (low, high)-pairing never fires on this shape: a chunk's low and
// high dots live in different chains.
//
// The rewrite replaces both chains, both shuffles and the combine with
// a chain of synthetic raw block dots. The AVX2 emission computes each
// 16-byte leaf in the 8-lane madd domain and collapses to the 4-byte
// grouping in-register:
//
// VPMOVSXBW a, Y2 ; 16 x i16
// VPMOVSXBW b, Y3
// VPMADDWD Y3, Y2, Y2 ; 8 x i32 two-byte pair sums p0..p7
// VPHADDD Y2, Y2, Y2 ; [p01, p23, ., . | p45, p67, ., .]
// VEXTRACTI128 $1, Y2, X3
// VPUNPCKLQDQ X3, X2, dst ; [p01, p23, p45, p67]
//
// i16 products of i8 lanes cannot overflow and VPMADDWD accumulates
// into i32, so every step is exact for ALL inputs (unlike the
// VPSIGNB/VPMADDUBSW route native kernels use, which wraps on -128);
// i32 wraparound addition is associative and commutative, so
// regrouping the chains' adds per leaf is bit-identical. Like the
// block dot this is a feature-body-only upgrade: portable twins keep
// the literal SSE lowering.
const (
// x64OpRawDot(a, b): the 16-byte signed 8-bit dot with SDOT's
// natural grouping — lane j sums the products of bytes 4j..4j+3.
// Self-contained (collapses in-place); used for single-leaf
// chains and as the fallback when the wide form is unavailable.
x64OpRawDot = "i32x4_rawdot8_avx2"
// x64OpRawDotAcc(acc, a, b): acc + the raw dot, acc and result in
// the collapsed 4-lane domain. acc is always a rebuilt chain node
// (ArgNode), never a pair input.
x64OpRawDotAcc = "i32x4_rawdot8_acc_avx2"
// Wide-chain forms: the accumulation stays in the 8-lane VPMADDWD
// pair domain across one full ymm — 4 ops per leaf, only the two
// unavoidable VPMOVSXBW lane crossings — and collapses ONCE per
// chain (the Zen 3 lesson: per-leaf ymm collapses lose to their
// own lane-crossing shuffles). The ymm upper half of the running
// value must survive between links, so these are selected only
// for fully-VEX trees, where the region defers VZEROUPPER to its
// exit and every other write is VEX (upper-zeroing only for its
// own destination).
x64OpRawDotWide = "i32x8_rawdotwide8_avx2" // (a, b)
x64OpRawDotWideAcc = "i32x8_rawdotwide8_acc_avx2" // (acc, a, b)
// x64OpRawDotFold(v): collapse the 8-lane pair-domain value to
// the four-consecutive-byte grouping.
x64OpRawDotFold = "i32x4_rawdotfold_avx2"
)
// x64CrossDotRewrite matches the cross-chain combine shape on the RAW
// node forms (adds over dot(extend, extend) leaves — nothing here has
// been touched by the pairing walk, which skips all-low/all-high
// chains) and rebuilds it as a raw-dot chain. wide selects the
// pair-domain chain forms (see the op comments); the caller falls
// back to the self-contained per-leaf form for trees whose emission
// is not fully VEX. Mutates nodes in place; reports whether anything
// was rewritten.
func x64CrossDotRewrite(nodes []simdfuse.Node, isRoot []bool, constPairs map[int][2]uint64, wide bool) bool {
uses := make([]int, len(nodes))
for _, n := range nodes {
for _, a := range n.Args {
if a.Kind == simdfuse.ArgNode {
uses[a.Index]++
}
}
}
// rawChainOf collects the half-dot leaves of the add spine rooted
// at tail, all of the required lowness, in deterministic in-order
// walk order, plus every absorbed node (adds, dots, extends).
// Interior values must be unobservable (single use, not a root).
rawChainOf := func(tail int, low bool) (leaves []x64HalfDot, all []int, ok bool) {
ok = true
var walk func(a simdfuse.Arg, isTail bool)
walk = func(a simdfuse.Arg, isTail bool) {
if !ok {
return
}
if a.Kind != simdfuse.ArgNode {
ok = false
return
}
i := a.Index
if !isTail && (uses[i] != 1 || isRoot[i]) {
ok = false
return
}
if isAddAny(nodes, i) {
if nodes[i].Args[0].Kind != simdfuse.ArgNode || nodes[i].Args[1].Kind != simdfuse.ArgNode {
ok = false
return
}
all = append(all, i)
walk(nodes[i].Args[0], false)
walk(nodes[i].Args[1], false)
return
}
h, hok := x64ClassifyHalfDot(nodes, uses, isRoot, i)
if !hok || h.high == low {
ok = false
return
}
leaves = append(leaves, h)
all = append(all, i, h.e0, h.e1)
}
walk(simdfuse.Arg{Kind: simdfuse.ArgNode, Index: tail}, true)
if !ok || len(leaves) == 0 {
return nil, nil, false
}
return leaves, all, true
}
rewrote := false
for c := len(nodes) - 1; c >= 0; c-- {
n := &nodes[c]
if n.Op != "i32x4_add" || len(n.Args) != 2 ||
n.Args[0].Kind != simdfuse.ArgNode || n.Args[1].Kind != simdfuse.ArgNode {
continue
}
e, o := n.Args[0].Index, n.Args[1].Index
ex, ey, eEven, eok := crossSelKind(nodes, constPairs, e)
ox, oy, oEven, ook := crossSelKind(nodes, constPairs, o)
if !eok || !ook || eEven == oEven || ex != ox || ey != oy {
continue
}
if uses[e] != 1 || uses[o] != 1 || isRoot[e] || isRoot[o] {
continue
}
// Both shuffles read (dl, dh); each chain tail is consumed by
// exactly the two shuffles.
dl, dh := ex, ey
if uses[dl] != 2 || uses[dh] != 2 || isRoot[dl] || isRoot[dh] {
continue
}
lowLeaves, lowAll, lok := rawChainOf(dl, true)
highLeaves, highAll, hok := rawChainOf(dh, false)
if !lok || !hok || len(lowLeaves) != len(highLeaves) {
continue
}
paired := true
for j := range lowLeaves {
if lowLeaves[j].srcA != highLeaves[j].srcA || lowLeaves[j].srcB != highLeaves[j].srcB {
paired = false
break
}
}
if !paired {
continue
}
// Rebuild: a raw-dot chain over the common sources. Chain
// nodes land on the low chain's dot slots (ascending — each
// already follows its own byte sources in post-order); the
// final accumulation lands on the combine node so its
// consumers read the same index. The accumulation link is one
// VPADDD (1 cycle), so a single chain suffices — the a64
// twin's dual-chain latency split has nothing to win here.
k := len(lowLeaves)
// Chain nodes land on the low dots' slots in ascending index
// order, each carrying its own slot's sources (their indices
// precede the dot, so post-order holds at every link). The
// pairing above was positional; the chain's summation order is
// free (associative), so re-sorting the (slot, sources)
// triples together is exact.
rl := append([]x64HalfDot(nil), lowLeaves...)
sort.Slice(rl, func(i, j int) bool { return rl[i].dot < rl[j].dot })
srcArgs := make([][2]simdfuse.Arg, k)
slots := make([]int, k)
for j, h := range rl {
srcArgs[j] = [2]simdfuse.Arg{h.srcA, h.srcB}
slots[j] = h.dot
}
for _, i := range lowAll {
nodes[i] = simdfuse.Node{Op: a64OpElided}
}
for _, i := range highAll {
nodes[i] = simdfuse.Node{Op: a64OpElided}
}
nodes[e] = simdfuse.Node{Op: a64OpElided}
nodes[o] = simdfuse.Node{Op: a64OpElided}
switch {
case k == 1:
nodes[c] = simdfuse.Node{Op: x64OpRawDot, Args: []simdfuse.Arg{srcArgs[0][0], srcArgs[0][1]}}
case wide:
// Pair-domain chain: the last leaf's accumulation lands on
// the highest slot and the fold on the combine node, so
// consumers keep reading c.
prev := slots[0]
nodes[prev] = simdfuse.Node{Op: x64OpRawDotWide, Args: []simdfuse.Arg{srcArgs[0][0], srcArgs[0][1]}}
for j := 1; j < k; j++ {
nodes[slots[j]] = simdfuse.Node{Op: x64OpRawDotWideAcc, Args: []simdfuse.Arg{
{Kind: simdfuse.ArgNode, Index: prev}, srcArgs[j][0], srcArgs[j][1],
}}
prev = slots[j]
}
nodes[c] = simdfuse.Node{Op: x64OpRawDotFold, Args: []simdfuse.Arg{
{Kind: simdfuse.ArgNode, Index: prev},
}}
default:
prev := slots[0]
nodes[prev] = simdfuse.Node{Op: x64OpRawDot, Args: []simdfuse.Arg{srcArgs[0][0], srcArgs[0][1]}}
for j := 1; j < k-1; j++ {
nodes[slots[j]] = simdfuse.Node{Op: x64OpRawDotAcc, Args: []simdfuse.Arg{
{Kind: simdfuse.ArgNode, Index: prev}, srcArgs[j][0], srcArgs[j][1],
}}
prev = slots[j]
}
nodes[c] = simdfuse.Node{Op: x64OpRawDotAcc, Args: []simdfuse.Arg{
{Kind: simdfuse.ArgNode, Index: prev}, srcArgs[k-1][0], srcArgs[k-1][1],
}}
}
for _, i := range append(append([]int{}, lowAll...), highAll...) {
uses[i] = 0
}
rewrote = true
}
return rewrote
}