Skip to content

Commit bf644fe

Browse files
committed
Merge branch 'pir-matrix-mac' into dev3
2 parents 391e2de + 2c48977 commit bf644fe

20 files changed

Lines changed: 1175 additions & 198 deletions

‎src/tensorforge/analysis/pipeline.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,9 @@
9191
'shared.store': 1.0, 'barrier': 2.0, 'branch': 1.67},
9292
}
9393

94-
#: Clocks one MFMA holds its SIMD for, by the shape its builtin names, measured
94+
#: Clocks one MFMA holds its SIMD for, by the shape its builtin names -- the
95+
#: instruction of its matrix op, whose category is `mfma.<shape>`
96+
#: (`pir.engines.mfma_category`) --, measured
9597
#: on gfx942 (MI300A, 2026-10-27; `~/tf-probe/mi300a/coissue.hip`: four
9698
#: independent accumulators, four waves a SIMD). The 64-lane entries that
9799
#: are not listed were not measured and take their nominal passes. The

‎src/tensorforge/backend/instructions/compute/primitives/amd/catalog.py‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
`NOT_MODELED` rather than passing over it.
4747
"""
4848

49+
import functools
4950
from dataclasses import dataclass
5051
from enum import Enum
5152
from typing import Optional
@@ -210,6 +211,24 @@ def fits(self, threads: int) -> bool:
210211
"""
211212
return threads == self.wave
212213

214+
def mac(self, writer, type_, a, b, c, cbsz: int = 0, abid: int = 0,
215+
blgp: int = 0):
216+
"""D = A * B + C as this instruction: the matrix op of engine `mfma`
217+
(`IRBuilder.matrix_mac`), A, B and C one register vector each -- the
218+
builtin's operands, in its order -- and D a new value of `type_`,
219+
which it returns: a link of an accumulator chain, in a variable of
220+
its own, its layout one nobody wrote down (`codegen.matmul32`).
221+
`cbsz`, `abid` and `blgp` are the broadcast and swizzle modifiers
222+
(`broadcast`), all three stated; the layouts the vendor has for A, B
223+
and D go along (`vendor_layouts`)."""
224+
return writer.matrix_mac(
225+
'mfma', (self.m, self.n, self.k),
226+
(self.a.dtype, self.b.dtype, self.d.dtype, self.d.dtype),
227+
(a,), (b,), (c,), result=type_, hint='acc',
228+
instruction=self.builtin,
229+
modifiers=(('cbsz', cbsz), ('abid', abid), ('blgp', blgp)),
230+
layouts=vendor_layouts(self))
231+
213232
def cbsz(self, threads: int) -> int:
214233
"""How many blocks share one A operand: the instruction's `cbsz`.
215234
@@ -483,6 +502,19 @@ def lane_batched_ops(dtype, ctx):
483502
}
484503

485504

505+
@functools.lru_cache(maxsize=None)
506+
def vendor_layouts(op: MatrixOp):
507+
"""The layouts of A, B and D the vendor states for `op` -- measured on
508+
the hardware or documented (`layouts.provenance`) -- as `BitLayout`s,
509+
None for an operand it states none of: what a matrix op of the
510+
instruction carries (`IRBuilder.matrix_mac`). A layout derived here
511+
from a precedent is TensorForge's inference, and stays out."""
512+
from .layouts import Provenance, fragment_layout, provenance
513+
stated = (Provenance.MEASURED, Provenance.DOCUMENTED)
514+
return tuple(fragment_layout(op, w) if provenance(op, w) in stated
515+
else None for w in 'ABD')
516+
517+
486518
@dataclass(frozen=True)
487519
class MfmaTile:
488520
"""One square K=1 MFMA tile: the intrinsic, and how its A operand is fed.

‎src/tensorforge/backend/instructions/compute/primitives/amd/codegen.py‎

Lines changed: 12 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -462,11 +462,9 @@ def step(acc, trueK, lead, blgp):
462462
kkkm = trueK % block
463463
_check_mfma_operand(tA[km][kkkm], threads, fn,
464464
tile)
465-
return writer.call(
466-
fn, vtype, tA[km][kkkm], lead, acc,
467-
scale, kkm, blgp,
468-
hint='acc', movable=False,
469-
materialize=True, layout=acclayout)
465+
return tile.op.mac(
466+
writer, vtype, tA[km][kkkm], lead, acc,
467+
scale, kkm, blgp)
470468

471469
# Two counts of the contraction meet here. The
472470
# shared matrix is transposed a block of lanes at
@@ -617,13 +615,10 @@ def step(acc, trueK, lead, blgp):
617615
# accumulator, so the chain is
618616
# naturally SSA -- each step reads the
619617
# previous result.
620-
acc = writer.call(
621-
fn, vtype,
618+
acc = tile.op.mac(
619+
writer, vtype,
622620
tA[km][kkkm], tB[kkk], acc,
623-
scale, kkm, 0,
624-
hint='acc', movable=False,
625-
materialize=True,
626-
layout=acclayout)
621+
scale, kkm, 0)
627622

628623
for jj in range(min(block, N - j)):
629624
C(writer, _column(writer, tile, acc, jj, ftype),
@@ -696,12 +691,10 @@ def write_wide(tile, start, end):
696691
_check_mfma_operand(a, threads, fn,
697692
tile)
698693
for h in range(width):
699-
accs[h] = writer.call(
700-
fn, vtype, a,
694+
accs[h] = tile.op.mac(
695+
writer, vtype, a,
701696
writer.extract(rows, h, ftype),
702-
accs[h], scale, t // block, 0,
703-
hint='acc', movable=False,
704-
materialize=True)
697+
accs[h], scale, t // block, 0)
705698
for jj in range(min(block, N - j)):
706699
C(writer, writer.pack(wtype, *(
707700
_column(writer, tile, acc, jj, ftype)
@@ -785,7 +778,6 @@ def matmulemu(writer: Writer, C, B, A, M, N, K, kx, threads, dtype, sparse,
785778
ftype = ScalarType(dtype)
786779
block = tile.block
787780
scale = tile.scale(threads)
788-
fn = op.callee
789781
# The split's outputs, and the instruction's operands. Not `dtype`:
790782
# that is what the accumulator keeps, and reaching it is the whole
791783
# reason there is more than one product.
@@ -848,12 +840,10 @@ def split4(regs, hint):
848840
kkm = kk // width
849841
for j in blocks:
850842
for ti, tj in products:
851-
accs[j] = writer.call(
852-
fn, vtype,
843+
accs[j] = op.mac(
844+
writer, vtype,
853845
aterms[(j, k // threads)][ti], bterms[tj],
854-
accs[j], scale, kkm, 0,
855-
hint='acc', movable=False,
856-
materialize=True, layout=acclayout)
846+
accs[j], scale, kkm, 0)
857847

858848
for j in blocks:
859849
for jj in range(min(block, N - j)):

‎src/tensorforge/backend/instructions/compute/primitives/amd/dpp_block.py‎

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@
7171
from typing import (Callable, Dict, Iterable, Iterator, List, Optional,
7272
Sequence, Tuple)
7373

74+
from tensorforge.backend.pir.engines import Hazard
7475
from tensorforge.common.basic_types import Datatype
7576
from tensorforge.common.options import DPP_WAITS
7677

@@ -101,13 +102,21 @@
101102
#: The wait in front of a block: two wait states.
102103
WAIT = 's_nop 1'
103104

104-
#: The wait behind a block, for a VALU write of its an MFMA reads next: two.
105-
WAIT_AFTER = 's_nop 1'
105+
#: The wait a VALU write owes a matrix instruction that reads it as its A or
106+
#: B, in the engines' terms: two wait states between the write and an MFMA
107+
#: (LLVM's `LegacyVALUNotDotWritesVGPRWaitStates`; measured on gfx942,
108+
#: 2026-11-15). The compiler keeps it behind a VALU instruction and not
109+
#: behind assembly, so a block keeps it itself, where a kernel issues one
110+
#: (`waits_behind`). The other way the hardware interlocks.
111+
HAZARD = Hazard(then='mfma', states=2)
112+
113+
#: The wait behind a block, for a VALU write of its an MFMA reads next.
114+
WAIT_AFTER = f's_nop {HAZARD.states - 1}'
106115

107116
_INSTRUCTION = {Datatype.F32: 'v_fmac_f32_dpp', Datatype.F64: 'v_fmac_f64_dpp'}
108117

109-
#: A matrix instruction, in the name of a builtin or the text of assembly:
110-
#: `__builtin_amdgcn_mfma_*`, `smfmac`, WMMA.
118+
#: A matrix instruction in text the IR does not see into, assembly or raw:
119+
#: `mfma`, `smfmac`, WMMA.
111120
_MATRIX = re.compile(r'mfma|smfmac|wmma', re.IGNORECASE)
112121

113122

@@ -217,14 +226,17 @@ def waits_in(run: Sequence) -> int:
217226

218227
def waits_behind(bodies: Iterable[Sequence]) -> bool:
219228
"""Whether a block of a kernel made of `bodies` waits behind itself: where
220-
any statement of them issues a matrix instruction -- a builtin by its
221-
name, assembly or raw text by what it spells."""
222-
from tensorforge.backend.pir.core import walk_stmts
229+
any statement of them is the matrix instruction its write owes a wait
230+
(`HAZARD`) -- a matrix op of that engine -- or assembly or raw text
231+
spells a matrix instruction."""
232+
from tensorforge.backend.pir.core import Op, walk_stmts
223233
for body in bodies:
224234
for stmt in walk_stmts(body):
225-
if any(_MATRIX.search(text) for text in (
226-
stmt.attr('callee') or '', stmt.attr('asm') or '',
227-
stmt.text or '')):
235+
if (stmt.op == Op.MATRIX_MAC
236+
and stmt.attr('engine') == HAZARD.then):
237+
return True
238+
if any(_MATRIX.search(text) for text in (stmt.attr('asm') or '',
239+
stmt.text or '')):
228240
return True
229241
return False
230242

‎src/tensorforge/backend/instructions/compute/primitives/amd/exchange_codegen.py‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -294,11 +294,9 @@ def matmul_exchange(writer, C, shared, lead, M, N, K, kx, threads, dtype,
294294
head, K)
295295
if built is None or built is False:
296296
return False
297-
acc[(i, g)] = writer.call(
298-
op.callee, acctype,
299-
fragments[group], built, acc[(i, g)],
300-
0, 0, 0, hint='acc', movable=False,
301-
materialize=True)
297+
acc[(i, g)] = op.mac(
298+
writer, acctype, fragments[group], built,
299+
acc[(i, g)])
302300

303301
for i in range(M):
304302
for column in range(min(ext, N - j)):

‎src/tensorforge/backend/instructions/compute/primitives/amd/stacked.py‎

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -635,10 +635,8 @@ def fetch(s0, live):
635635
if b is None:
636636
return False
637637
for c0 in tiles:
638-
acc[(rt, c0)] = writer.call(
639-
op.callee, acctype, frags[c0], b, acc[(rt, c0)],
640-
0, 0, 0, hint='acc', movable=False,
641-
materialize=True)
638+
acc[(rt, c0)] = op.mac(writer, acctype, frags[c0], b,
639+
acc[(rt, c0)])
642640
continue
643641
# The fragments of the step `depth` on, read before this step's
644642
# issues: their loads have the issues to land behind
@@ -651,10 +649,8 @@ def fetch(s0, live):
651649
frags, operators = got
652650
for rt in live:
653651
for c0 in tiles:
654-
acc[(rt, c0)] = writer.call(
655-
op.callee, acctype, frags[c0], operators[rt],
656-
acc[(rt, c0)], 0, 0, 0, hint='acc', movable=False,
657-
materialize=True)
652+
acc[(rt, c0)] = op.mac(writer, acctype, frags[c0],
653+
operators[rt], acc[(rt, c0)])
658654
if interleaved(ctx) and i + depth < len(steps_):
659655
_interleave(writer, len(live) * len(tiles))
660656
if chain is not None:
@@ -790,10 +786,9 @@ def operator_terms(rt, s0):
790786
return False
791787
for c0 in tiles:
792788
for i, j in pairs:
793-
acc[(rt, c0)] = writer.call(
794-
op.callee, acctype, frags[c0][i], b[j],
795-
acc[(rt, c0)], 0, 0, 0, hint='acc',
796-
movable=False, materialize=True)
789+
acc[(rt, c0)] = op.mac(writer, acctype,
790+
frags[c0][i], b[j],
791+
acc[(rt, c0)])
797792
if chain is not None:
798793
chain.state['accs'] = acc
799794
if chain.closes and chain.phase == 'all':

0 commit comments

Comments
 (0)