Skip to content

Commit 182aadb

Browse files
committed
Merge branch 'bf16x6-arith' into dev3
2 parents cc8cb09 + 1dd47c1 commit 182aadb

8 files changed

Lines changed: 1176 additions & 34 deletions

File tree

‎src/tensorforge/backend/pir/terms.py‎

Lines changed: 130 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,15 @@ class TermPlan:
117117
a product; `epilogue` how the partials become D; `accumulator` the
118118
format they hold. `name` says which plan it is where a body is read.
119119
120+
`restart`, one entry a partial where any is restarted: the blocks of K
121+
-- an instruction's K a block, all of a chain's members over it -- a
122+
partial lives before it is drained into a total of its own, F32 rounded
123+
to nearest, and starts again from nothing; 0 for one that lives over the
124+
whole contraction, which is every partial where `restart` is empty. At
125+
the end a restarted partial is its total plus what it holds. The
126+
drain is no product, and no part of a body `check_plans` reads: it is
127+
the path's (`reference.accumulation.evaluate` states it).
128+
120129
Frozen and hashable: a `MATRIX_MAC` carries it as an attribute
121130
(`IRBuilder.matrix_mac`'s `plan`), and the attributes of a statement are
122131
part of its identity to the passes."""
@@ -128,8 +137,24 @@ class TermPlan:
128137
partials: Tuple[int, ...]
129138
epilogue: Epilogue = Epilogue.NONE
130139
accumulator: Datatype = Datatype.F32
140+
restart: Tuple[int, ...] = ()
131141

132142
def __post_init__(self):
143+
self._check()
144+
if self.restart:
145+
if len(self.restart) != self.count:
146+
raise ValueError(f'{self.name}: a restart for '
147+
f'{len(self.restart)} partials of '
148+
f'{self.count}')
149+
if any(not isinstance(r, int) or isinstance(r, bool) or r < 0
150+
for r in self.restart):
151+
raise ValueError(f'{self.name}: restart {self.restart}: '
152+
f'blocks of K, 0 for none')
153+
if not any(self.restart):
154+
# No partial restarted is no restart: one plan, one value.
155+
object.__setattr__(self, 'restart', ())
156+
157+
def _check(self):
133158
if not self.products:
134159
raise ValueError(f'{self.name}: a plan of no products')
135160
if len(set(self.products)) != len(self.products):
@@ -167,6 +192,18 @@ def sequence(self, partial: int) -> Tuple[Tuple[int, int], ...]:
167192
return tuple(t for t, p in zip(self.products, self.partials)
168193
if p == partial)
169194

195+
def restarted(self, partial: int) -> int:
196+
"""The blocks of K partial `partial` lives between two drains
197+
(`restart`); 0 for one over the whole contraction."""
198+
return self.restart[partial] if self.restart else 0
199+
200+
@property
201+
def period(self) -> int:
202+
"""The longest a restarted partial lives, in blocks of K, 0 where
203+
none is restarted: what a plan's class is read by besides its name
204+
(`product_accuracy`)."""
205+
return max(self.restart, default=0)
206+
170207
def steps(self) -> Iterator[Tuple[int, Tuple[int, int], int]]:
171208
"""`(index, term, partial)` of every product, in the plan's order:
172209
for a path that interleaves the products of several accumulators,
@@ -179,12 +216,14 @@ def each(self) -> 'TermPlan':
179216
"""The same products, each into an accumulator of its own and
180217
summed behind them (`Epilogue.SUM`): what NVIDIA's `mma.sync`
181218
issues where a step has too few independent chains to hide an
182-
HMMA's latency (`nvidia.CHAINS_MIN`)."""
219+
HMMA's latency (`nvidia.CHAINS_MIN`). A product of a restarted
220+
partial keeps its partial's restart in its own."""
183221
if self.count == len(self.products):
184222
return self
185223
return TermPlan(f'{self.name}/each', self.a, self.b, self.products,
186224
tuple(range(len(self.products))), Epilogue.SUM,
187-
self.accumulator)
225+
self.accumulator,
226+
tuple(self.restarted(p) for p in self.partials))
188227

189228
def issue(self, mac: Callable, a_terms: Sequence, b_terms: Sequence,
190229
accs: Sequence) -> List:
@@ -225,6 +264,8 @@ def __repr__(self):
225264
else:
226265
where = (f'partials {"".join(str(p) for p in self.partials)}, '
227266
f'{self.epilogue.value}')
267+
if self.restart:
268+
where += '; restart ' + ','.join(str(r) for r in self.restart)
228269
return (f'TermPlan({self.name}: {self.a!r} by {self.b!r} into '
229270
f'{self.accumulator.name}: {terms}; {where})')
230271

@@ -244,6 +285,53 @@ def plan(name: str, a: Form, b: Form, *, keep: Optional[int] = None,
244285
accumulator)
245286

246287

288+
#: An F32 operand as the 6xBF16 plans take it: three BF16 terms, each
289+
#: rounded to nearest even and the remainder carried, whose sum is the value
290+
#: (`split.terms`; `common.matrix.forms.BF16_TRIPLE` makes them).
291+
BF16X3 = Form(Datatype.BF16, 3)
292+
293+
294+
def bf16x6(order: str = 'smallest', major: str = 'a', accumulators: int = 1,
295+
restart: int = 0) -> TermPlan:
296+
"""The 6xBF16 family: A and B in three BF16 terms each
297+
(`BF16X3`), the six products above F32's rounding (`split.products`),
298+
in `order`, a tie broken by `major`'s term.
299+
300+
One accumulator (`bf16x6`): the six into D. Two (`bf16x6/2`): the
301+
leading product, (0,0), into partial 0 and issued last -- so that where
302+
that partial is drained, the drain runs under the next block's other
303+
products -- and the other five into partial 1, the two added behind
304+
them (`Epilogue.SUM`). `restart`: the blocks of K partial 0 lives
305+
between two drains (`TermPlan.restart`), 0 for all of K. NVIDIA's
306+
engines truncate every sum they make, and it is the restart that puts
307+
the plan below FFMA's error there; DPAS rounds each step to nearest,
308+
and the second accumulator alone does it (`ACCURACY`).
309+
310+
NVIDIA issues the products largest first (`order='largest'`), Intel
311+
smallest first with B's term breaking a tie (`major='b'`, the plan named
312+
`/b` as Intel's `3xtf32/b`), AMD's stacked scheme smallest first
313+
(`stacked.BF16X6`, this with the defaults)."""
314+
if accumulators not in (1, 2):
315+
raise ValueError(f'a 6xBF16 plan of one or two accumulators, not '
316+
f'{accumulators!r}')
317+
if not isinstance(restart, int) or isinstance(restart, bool) \
318+
or restart < 0:
319+
raise ValueError(f'a restart of {restart!r}: blocks of K, 0 for none')
320+
name = ('bf16x6' + ('/2' if accumulators == 2 else '')
321+
+ ('/b' if major == 'b' else ''))
322+
pairs = plan(name, BF16X3, BF16X3, order=order, major=major).products
323+
if accumulators == 1:
324+
return TermPlan(name, BF16X3, BF16X3, pairs, (0,) * len(pairs),
325+
Epilogue.NONE, Datatype.F32,
326+
(restart,) if restart else ())
327+
lead = (0, 0)
328+
products = tuple(t for t in pairs if t != lead) + (lead,)
329+
return TermPlan(name, BF16X3, BF16X3, products,
330+
tuple(0 if t == lead else 1 for t in products),
331+
Epilogue.SUM, Datatype.F32,
332+
(restart, 0) if restart else ())
333+
334+
247335
# --------------------------------------------------------------------------- #
248336
# Reading the plans back off a body
249337
# --------------------------------------------------------------------------- #
@@ -365,11 +453,33 @@ def check_plans(body: Sequence[Stmt]) -> List[str]:
365453
#: Intel's DPAS adds in two interleaved chains, each step rounded to nearest:
366454
#: 3xTF32 0.87x to 1.44x FFMA's error, 3.45e-7 and 5.13e-7 measured at o6
367455
#: and o8. AMD's stacked BF16X6, 1e-7 measured on SeisSol's kernels.
368-
ACCURACY: Dict[Tuple[str, str], str] = {
456+
#:
457+
#: The 6xBF16 family (`bf16x6`) -- a plan with a restarted partial by the
458+
#: blocks of K it lives too (`TermPlan.period`, the key's third member) --
459+
#: by the models of those engines (`reference.accumulation`'s tz2 and pvc)
460+
#: on SeisSol's volume, o6 to o16, against FFMA's error at the order: on
461+
#: NVIDIA one accumulator 4.4x to 7.2x; two, (0,0)'s restarted every block
462+
#: 0.25x to 0.46x, every two 0.34x to 0.74x, every three 0.46x to 1.0x,
463+
#: never 1.0x (o6) to 3.1x (o16). On Intel one accumulator 0.88x to 1.53x
464+
#: (o4 on), two 0.57x to 0.60x, restarted every block 0.23x to 0.42x, every
465+
#: two 0.20x to 0.52x. On the hardware: two accumulators restarted every
466+
#: block 1.14e-7 at o8 on GH200, as modeled; on PVC 0.97e-7 and 1.03e-7 at
467+
#: o6 and o8, and without the restart 1.4e-7 against 3xTF32's 6.4e-7 on a
468+
#: dense 56 x 56 chain of eight.
469+
ACCURACY: Dict[tuple, str] = {
369470
('3xtf32', 'nvidia'): 'relaxed',
370471
('2xtf32', 'nvidia'): 'relaxed',
371472
('3xtf32/b', 'intel'): 'ffma',
372473
('bf16x6', 'amd'): 'ffma',
474+
('bf16x6', 'nvidia'): 'relaxed',
475+
('bf16x6/2', 'nvidia'): 'relaxed',
476+
('bf16x6/2', 'nvidia', 1): 'better',
477+
('bf16x6/2', 'nvidia', 2): 'better',
478+
('bf16x6/2', 'nvidia', 3): 'ffma',
479+
('bf16x6/b', 'intel'): 'ffma',
480+
('bf16x6/2/b', 'intel'): 'better',
481+
('bf16x6/2/b', 'intel', 1): 'better',
482+
('bf16x6/2/b', 'intel', 2): 'better',
373483
}
374484

375485

@@ -378,14 +488,27 @@ def product_accuracy(plan: Optional[TermPlan], vendor: Optional[str]) -> str:
378488
(`ACCURACY`): FFMA's for a product in full -- DFMA, DMMA, an MFMA on
379489
whole operands -- and a plan's own, one into an accumulator a product
380490
(`/each`) as its whole; `relaxed` for a plan the table does not name,
381-
whose rounding nobody measured."""
491+
whose rounding nobody measured. A plan with a restarted partial by its
492+
period too (`TermPlan.period`): one the table does not name, `relaxed`
493+
as well."""
382494
if plan is None:
383495
return 'ffma'
496+
if plan.period:
497+
return _restarted_accuracy(plan, vendor)
384498
name = plan.name[:-len('/each')] if plan.name.endswith('/each') \
385499
else plan.name
386500
return ACCURACY.get((name, vendor), 'relaxed')
387501

388502

503+
def _restarted_accuracy(plan: TermPlan, vendor: Optional[str]) -> str:
504+
"""`product_accuracy` of a plan with a restarted partial: by its name
505+
(one an accumulator a product as its whole), the vendor and its
506+
period."""
507+
name = plan.name[:-len('/each')] if plan.name.endswith('/each') \
508+
else plan.name
509+
return ACCURACY.get((name, vendor, plan.period), 'relaxed')
510+
511+
389512
def admits(asked: str, level: str) -> bool:
390513
"""Whether the class `asked` for (`Options.accuracy`) admits `level`:
391514
`level` as accurate or more."""
@@ -411,6 +534,6 @@ def body_accuracy(bodies: Sequence[Sequence[Stmt]], vendor: Optional[str]
411534
return worst, by
412535

413536

414-
__all__ = ['ACCURACY', 'ACCURACY_CLASSES', 'Epilogue', 'Form', 'Kind',
415-
'TermPlan', 'admits', 'body_accuracy', 'check_plans', 'plan',
416-
'product_accuracy']
537+
__all__ = ['ACCURACY', 'ACCURACY_CLASSES', 'BF16X3', 'Epilogue', 'Form',
538+
'Kind', 'TermPlan', 'admits', 'bf16x6', 'body_accuracy',
539+
'check_plans', 'plan', 'product_accuracy']

‎src/tensorforge/common/matrix/forms.py‎

Lines changed: 71 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
per-element side is always split at run time, by each target's routine
1515
(`device` names it); the form is the statement both sides are held to.
1616
17-
Three forms exist, each the arithmetic one path already had:
17+
Four forms exist, three of them the arithmetic one path already had:
1818
1919
* `TF32_STORED` -- the pair an operand read prepared is stored as on the
2020
multilinear path (`Tensor.storage_values`, the offering and
@@ -28,13 +28,19 @@
2828
* `BF16_TRIPLE` -- three BF16 terms, each rounded to nearest even and the
2929
remainder carried, whose sum is the value exactly (`prepare.split_bf16`,
3030
`splitFloatBF16` on HIP).
31+
* `BF16_PACKED` -- the same three terms held as the sixteen-bit numbers
32+
they are (`prepare.split_bf16_bits`): what NVIDIA's BF16 engines read
33+
through a descriptor, a core matrix's row eight terms of K, and DPAS's
34+
BF16 B, a dword two steps of K (`k_pairs`); 6 bytes an entry where the
35+
float-held triple, which AMD's stacked scheme reads, is 12.
3136
3237
A table of a form (`lay`) holds each part of a piece in a layout of its
33-
own, the parts one after the other -- the canonical K-major layout of the
34-
asynchronous engines (`canonical_k_major`), or planar or adjacent by a
35-
storage order (`DerivedForm.store`). Ozaki's slices with their scales and
36-
its residues are forms of the same kind, with integer parts and side
37-
tables.
38+
own, the parts one after the other, in the form's own element (`stored`:
39+
F32, or BF16's sixteen bits) -- the canonical K-major layout of the
40+
asynchronous engines (`canonical_k_major`, by the element's size), or
41+
planar or adjacent by a storage order (`DerivedForm.store`). Ozaki's
42+
slices with their scales and its residues are forms of the same kind, with
43+
integer parts and side tables.
3844
"""
3945

4046
from __future__ import annotations
@@ -47,7 +53,8 @@
4753

4854
from tensorforge.common.basic_types import Datatype
4955

50-
from .prepare import split_bf16, split_tf32, tf32_halves
56+
from .prepare import (bf16_bits, bf16_values, split_bf16, split_tf32,
57+
tf32_halves)
5158

5259

5360
class Rounding(Enum):
@@ -92,10 +99,22 @@ def derive(self, values) -> np.ndarray:
9299
f'values')
93100
return out
94101

102+
def encode(self, values) -> np.ndarray:
103+
"""`derive`'s parts in the element the form holds them in
104+
(`stored`): float32 where that is F32, the sixteen bits of each
105+
BF16 term (``uint16``) where it is BF16."""
106+
parts = self.derive(values)
107+
if self.stored == Datatype.BF16:
108+
return bf16_bits(parts)
109+
return parts
110+
95111
def combine(self, parts) -> np.ndarray:
96112
"""The parts summed, the smallest first, in double precision: the
97113
value back, where the form is exact (`BF16_TRIPLE`, the TF32 pairs'
98-
sums are the float32 value)."""
114+
sums are the float32 value). Parts held as sixteen bits
115+
(`encode`) are read as the BF16 numbers they are."""
116+
if np.asarray(parts).dtype == np.uint16:
117+
parts = bf16_values(parts)
99118
parts = np.asarray(parts, dtype=np.float64)
100119
total = np.zeros(parts.shape[1:])
101120
for row in parts[::-1]:
@@ -107,8 +126,9 @@ def store(self, values, planar: int = 0) -> np.ndarray:
107126
side by side, `[p0 v0, p1 v0, ..., p0 v1, ...]` -- or, `planar`, per
108127
group of `planar` values every part's run in turn: what
109128
`Tensor.storage_values` holds where an element is spread over
110-
several slots (`Tensor.storage_planar`)."""
111-
parts = self.derive(values)
129+
several slots (`Tensor.storage_planar`). In the form's element
130+
(`encode`)."""
131+
parts = self.encode(values)
112132
if planar:
113133
out = np.stack([p.reshape(-1, planar) for p in parts], axis=1)
114134
return np.ascontiguousarray(out.ravel())
@@ -139,6 +159,14 @@ def _bf16_triple(x):
139159
device=(('hip', 'tensorforge::splitFloatx4BF16'),),
140160
make=_bf16_triple)
141161

162+
#: `BF16_TRIPLE`'s terms held as sixteen bits (`split_bf16_bits`): two
163+
#: consecutive K a 32-bit word wherever K runs fastest in a part's run --
164+
#: the canonical layout of 16-bit elements (`canonical_k_major`), DPAS's B
165+
#: (`k_pairs`).
166+
BF16_PACKED = DerivedForm(
167+
'bf16 triple, packed', 3, Datatype.BF16, Rounding.EVEN, Rounding.EVEN,
168+
stored=Datatype.BF16, make=_bf16_triple)
169+
142170

143171
def tf32_device(ties: str) -> DerivedForm:
144172
"""The TF32 pair `splitFloatTF32` makes on NVIDIA (`tf32_halves`): the
@@ -166,34 +194,54 @@ def stored(parts: int) -> Optional[DerivedForm]:
166194
BF16_TRIPLE.parts: BF16_TRIPLE}.get(int(parts))
167195

168196

169-
def canonical_k_major(rows: int, width: int) -> np.ndarray:
197+
def canonical_k_major(rows: int, width: int, size: int = 4) -> np.ndarray:
170198
"""Where cell `(k, n)` of a piece of `rows` rows of K and `width` of N
171199
lies in the canonical K-major layout the asynchronous engines read
172-
through a descriptor: core matrices of eight rows of N by four of K,
173-
128 bytes apart along K and `rows` x 32 elements along N -- `(n / 8)
174-
rows 8 + (k / 4) 32 + (n % 8) 4 + k % 4` -- as an array over `k * width
175-
+ n`."""
200+
through a descriptor: core matrices of eight rows of N by sixteen bytes
201+
of K, 128 bytes apart along K and `rows` x 8 elements along N -- for
202+
elements of `size` bytes, `e = 16 / size` of them a row of a core
203+
matrix, `(n / 8) rows 8 + (k / e) 8 e + (n % 8) e + k % e` -- as an
204+
array over `k * width + n`, in elements. Four F32 or TF32 a row, eight
205+
BF16."""
206+
if size not in (2, 4):
207+
raise ValueError(f'elements of 2 or 4 bytes, not {size!r}')
208+
e = 16 // size
176209
k, n = np.divmod(np.arange(rows * width), width)
177-
return (n // 8) * rows * 8 + (k // 4) * 32 + (n % 8) * 4 + k % 4
210+
return (n // 8) * rows * 8 + (k // e) * 8 * e + (n % 8) * e + k % e
178211

179212

180213
def lay(form: DerivedForm, block, slots) -> np.ndarray:
181214
"""A piece of a table of `form`: `block`'s cells (any shape, read in
182215
C order) taken apart, each part laid out by `slots` -- the place of
183-
each cell in a part's run -- and the parts' runs one after the
184-
other."""
216+
each cell in a part's run -- and the parts' runs one after the other,
217+
in the form's element (`DerivedForm.encode`): float32, or the sixteen
218+
bits of BF16 terms."""
185219
values = np.asarray(block, dtype=np.float64).ravel()
186220
slots = np.asarray(slots).ravel()
187221
if slots.size != values.size:
188222
raise ValueError(f'{slots.size} slots for {values.size} cells')
189-
parts = form.derive(values)
223+
parts = form.encode(values)
190224
size = values.size
191-
laid = np.zeros(form.parts * size, dtype=np.float32)
225+
laid = np.zeros(form.parts * size, dtype=parts.dtype)
192226
for p in range(form.parts):
193227
laid[p * size + slots] = parts[p]
194228
return laid
195229

196230

197-
__all__ = ['BF16_TRIPLE', 'DerivedForm', 'Rounding', 'TF32_STORED',
198-
'canonical_k_major', 'lay', 'stored', 'tf32_device',
199-
'tf32_device_for']
231+
def k_pairs(halves) -> np.ndarray:
232+
"""Sixteen-bit numbers along K -- `halves`, K the first axis, an even
233+
count of it -- two consecutive K a 32-bit word, the even one in the low
234+
half: what a lane of DPAS holds of a BF16 B, a dword two steps of K of
235+
its column (measured on the Max 1550: lane n, dword j = B[2j][n] in the
236+
low half, B[2j + 1][n] in the high), and where K runs fastest, as in a
237+
core matrix's row, what two neighbouring terms are in memory."""
238+
h = np.asarray(halves, dtype=np.uint16)
239+
if h.shape[0] % 2:
240+
raise ValueError(f'{h.shape[0]} steps of K: pairs want an even '
241+
f'count')
242+
return h[0::2].astype(np.uint32) | (h[1::2].astype(np.uint32) << 16)
243+
244+
245+
__all__ = ['BF16_PACKED', 'BF16_TRIPLE', 'DerivedForm', 'Rounding',
246+
'TF32_STORED', 'canonical_k_major', 'k_pairs', 'lay', 'stored',
247+
'tf32_device', 'tf32_device_for']

0 commit comments

Comments
 (0)