Skip to content

Commit 607f4e3

Browse files
committed
Merge branch 'amd-member-shards' into dev3
2 parents 1abf719 + c93ffe3 commit 607f4e3

9 files changed

Lines changed: 322 additions & 46 deletions

File tree

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

Lines changed: 120 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -343,6 +343,7 @@ def shard_loads(body: Tuple[Stmt, ...], scratch: Callable[[], object], *,
343343
threads: int, fptype: Datatype, static: bool = True,
344344
stream: bool = False,
345345
aligns: Optional[Mapping[str, int]] = None,
346+
extents: Optional[Mapping[str, int]] = None,
346347
report: Optional[List[str]] = None) -> Tuple[Stmt, ...]:
347348
"""`body` with the shards that fit into `budget` elements of shared
348349
memory read from there.
@@ -357,8 +358,10 @@ def shard_loads(body: Tuple[Stmt, ...], scratch: Callable[[], object], *,
357358
every multiplication of the block takes together. Both are held under
358359
the one budget. `aligns` is what the caller proves of the operands'
359360
bases, in bytes, by the name of their binding: how wide the copies may
360-
read them. `report` collects a line per operand: `+` and how much of it
361-
is held, `-` and why nothing is.
361+
read them. `extents` is how many elements one of them is stored over,
362+
by the same name, where that is more than its binding's type says
363+
(`_extents`). `report` collects a line per operand: `+` and how much of
364+
it is held, `-` and why nothing is.
362365
"""
363366
def note(line: str) -> None:
364367
if report is not None:
@@ -371,10 +374,11 @@ def note(line: str) -> None:
371374
note(f'- {len(loops)} batch loops in the body, where one is held')
372375
return body
373376
at = loops[0]
374-
loads = (_candidates(body, at, threads, mults, fptype, note) if static
375-
else [])
377+
reach = _extents(body, extents or {})
378+
loads = (_candidates(body, at, threads, mults, fptype, reach, note)
379+
if static else [])
376380
if stream:
377-
loads += _streamed(body, at, threads, mults, fptype, note)
381+
loads += _streamed(body, at, threads, mults, fptype, reach, note)
378382
shards = _shards(loads)
379383
held = _choose(shards, budget, align)
380384
if not held:
@@ -408,8 +412,49 @@ def _first_reads(stmts: Tuple[Stmt, ...]) -> Dict[int, int]:
408412
return out
409413

410414

415+
def _extents(body: Tuple[Stmt, ...],
416+
extents: Mapping[str, int]) -> Dict[int, int]:
417+
"""How many elements the buffers in `body` are stored over, by value,
418+
where the caller knows better than their types: an operand bound ahead
419+
of the batch loop by the name of its binding (`extents`), and a pointer
420+
chosen among such operands -- a merged run's member, through its table --
421+
by the largest of them.
422+
423+
A binding is typed when it is bound, from the box, and a multiplication
424+
may store its operand in an order of its own after that
425+
(`storage_order`): two lead slots of a lane as a pair, the rows padded to
426+
the lanes, longer than the box. A shard clamped to the type would leave
427+
out what the loads read past it."""
428+
out: Dict[int, int] = {}
429+
for s in walk_stmts(body):
430+
if len(s.target) != 1 or not isinstance(s.target[0].type, BufferType):
431+
continue
432+
# A merged run's binding has a name of its own as well, the stand-in's,
433+
# whose box the members' orders do not reach the stand-in through.
434+
known = [extents[s.attr('extern')]] if s.attr('extern') in extents \
435+
else []
436+
sources = [a for a in s.args if isinstance(a, Value)
437+
and isinstance(a.type, BufferType)]
438+
if (s.op is Op.RAWEXPR and sources
439+
and all(a.id in out for a in sources)):
440+
known.append(max(out[a.id] for a in sources))
441+
if known:
442+
out[s.target[0].id] = max(known)
443+
return out
444+
445+
446+
def _within(buffer: Value, span: Tuple[int, int, bool],
447+
reach: Mapping[int, int]) -> Optional[Tuple[int, int]]:
448+
"""`span` clamped to what `buffer` is stored over -- the elements a load
449+
reads past it belong to lanes its guard leaves out -- or None where
450+
nothing of it is left."""
451+
last = max(buffer.type.volume, reach.get(buffer.id, 0)) - 1
452+
lo, hi = max(0, span[0]), min(span[1], last)
453+
return (lo, hi) if lo <= hi else None
454+
455+
411456
def _candidates(body, at: int, threads: int, mults: int, fptype: Datatype,
412-
note) -> List[_Load]:
457+
reach: Mapping[int, int], note) -> List[_Load]:
413458
"""The loads of the loop at `at` that read a batch-constant operand at
414459
an index known per thread and varying over the lanes, each with the
415460
span it reads."""
@@ -443,13 +488,17 @@ def _candidates(body, at: int, threads: int, mults: int, fptype: Datatype,
443488
continue
444489
if span is None:
445490
continue
491+
held = _within(buffer, span, reach)
492+
if held is None:
493+
why = 'an index past the end of the operand'
494+
refused[why] = refused.get(why, 0) + 1
495+
continue
446496
first = reads.get(id(stmts))
447497
if first is None:
448498
first = reads[id(stmts)] = _first_reads(stmts)
449499
cover = first.get(stmt.target[0].id, len(stmts)) - n - 1
450-
out.append(_Load(stmt, buffer, max(0, span[0]),
451-
min(span[1], buffer.type.volume - 1), cover,
452-
position, span[2]))
500+
out.append(_Load(stmt, buffer, held[0], held[1], cover, position,
501+
span[2]))
453502
for why, count in sorted(refused.items()):
454503
note(f'- {count} load(s): {why}')
455504
return out
@@ -492,7 +541,7 @@ def _members(trip: Stmt, bound: Mapping[int, Value],
492541

493542

494543
def _streamed(body, at: int, threads: int, mults: int, fptype: Datatype,
495-
note) -> List[_Load]:
544+
reach: Mapping[int, int], note) -> List[_Load]:
496545
"""The loads of a merged run's members (`_members`), each with the span
497546
one trip reads -- the same for every trip, since only the member moves.
498547
@@ -547,13 +596,17 @@ def _streamed(body, at: int, threads: int, mults: int, fptype: Datatype,
547596
continue
548597
if span is None:
549598
continue
599+
held = _within(buffer, span, reach)
600+
if held is None:
601+
why = 'an index past the end of the operand'
602+
refused[why] = refused.get(why, 0) + 1
603+
continue
550604
first = reads.get(id(stmts))
551605
if first is None:
552606
first = reads[id(stmts)] = _first_reads(stmts)
553607
cover = first.get(stmt.target[0].id, len(stmts)) - n - 1
554-
out.append(_Load(stmt, buffer, max(0, span[0]),
555-
min(span[1], buffer.type.volume - 1), cover,
556-
position, span[2], trip=trip))
608+
out.append(_Load(stmt, buffer, held[0], held[1], cover, position,
609+
span[2], trip=trip))
557610
for why, count in sorted(refused.items()):
558611
note(f'- {count} member load(s): {why}')
559612
return out
@@ -744,11 +797,24 @@ def _copies(placed: List[Tuple[_Shard, int]]) -> List[_Copy]:
744797
return out
745798

746799

800+
#: Passes over the block a copy is written out to rather than looped over
801+
#: (`_stage`). The loop runs by lane -- its trips are `flat`'s -- so the
802+
#: compiler cannot count the loads in flight and waits on each one before its
803+
#: store: a round trip to memory a pass, twelve at the head of every trip of
804+
#: SeisSol's order-8 `localFluxAll` on gfx942. Written out, the passes'
805+
#: loads are in flight together. Past this many the loop stays, its code
806+
#: size the bound.
807+
UNROLL = 16
808+
809+
747810
def _stage(b, operand: Value, buf: Value, copy: _Copy, flat: Value,
748811
block: int, width: int = 1) -> None:
749812
"""`copy` by the threads of the block, `flat` the thread's place among
750813
them: each thread its share of `block` accesses of `width` elements
751-
(`_width`), under a guard where the block covers the copy at once."""
814+
(`_width`), under a guard where the block covers the copy at once, and
815+
written out pass by pass where it takes up to `UNROLL` passes -- every
816+
load ahead of the stores, and the lanes past the end of the last pass on
817+
their access of the first."""
752818
def plus(a: Value, c, hint: str) -> Value:
753819
if isinstance(c, int) and c == 0:
754820
return a
@@ -768,29 +834,58 @@ def at(i: Value, k: Optional[Value], start: int, step: int,
768834
elem = operand.type.elem
769835
wide = ScalarType(elem, width) if width > 1 else None
770836

771-
def one(u: Value) -> None:
837+
nbytes = width * elem.size()
838+
839+
def place(u: Value) -> Tuple[Value, Value]:
772840
# Access `u` moves elements `width * u` on, which never straddle a
773841
# run: `width` divides every run's length.
774842
i = u if width == 1 else b.op('mul', INDEX, u, width, hint='e')
775843
k = (b.op('div', INDEX, i, copy.count, hint='k')
776844
if copy.times > 1 else None)
777-
src = at(i, k, copy.src, copy.src_step, 'g')
778-
dst = at(i, k, copy.dst, copy.dst_step, 'l')
845+
return (at(i, k, copy.src, copy.src_step, 'g'),
846+
at(i, k, copy.dst, copy.dst_step, 'l'))
847+
848+
def fetch(src: Value) -> Value:
849+
if wide is None:
850+
return b.load(operand, src, hint='sh')
851+
return b.load(operand, src, type_=wide, align=nbytes, hint='sh')
852+
853+
def put(dst: Value, value: Value) -> None:
779854
if wide is None:
780-
b.store(buf, b.load(operand, src, hint='sh'), dst)
781-
return
782-
nbytes = width * elem.size()
783-
b.store(buf, b.load(operand, src, type_=wide, align=nbytes,
784-
hint='sh'), dst, align=nbytes)
855+
b.store(buf, value, dst)
856+
else:
857+
b.store(buf, value, dst, align=nbytes)
858+
859+
def one(u: Value) -> None:
860+
src, dst = place(u)
861+
put(dst, fetch(src))
785862

786863
units = copy.total // width
787864
if units <= block:
788865
with b.if_(b.op('lt', BOOL, flat, units, hint='s')):
789866
one(flat)
790867
return
791-
with b.for_(flat, units, block, hint='s',
792-
uniform=Uniformity.LANE) as f:
793-
one(f.induction)
868+
passes = -(-units // block)
869+
if passes > UNROLL:
870+
with b.for_(flat, units, block, hint='s',
871+
uniform=Uniformity.LANE) as f:
872+
one(f.induction)
873+
return
874+
fetched = []
875+
for p in range(passes):
876+
u = plus(flat, p * block, 's')
877+
if (p + 1) * block > units:
878+
# The last pass, which some lanes are past the end of. They take
879+
# their access of the first pass again -- the same value to the
880+
# same place, by the same lane, so no other lane's write races it
881+
# -- rather than branch: a guard around the store would draw the
882+
# load in behind it and wait on it there.
883+
u = b.op('select', INDEX, b.op('lt', BOOL, u, units, hint='s'),
884+
u, flat, hint='s')
885+
src, dst = place(u)
886+
fetched.append((dst, fetch(src)))
887+
for dst, value in fetched:
888+
put(dst, value)
794889

795890

796891
def _alignments(body: Tuple[Stmt, ...], at: int,

‎src/tensorforge/backend/symbol.py‎

Lines changed: 61 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1704,21 +1704,35 @@ def _packed_index(self, writer, context, index):
17041704
f'{self.name}: a packed operand has rows of stride one and one '
17051705
f'scalar per element; this one is {view}')
17061706
lead = unwrap_lead(index[0])
1707+
row = None
17071708
if lead is None:
1708-
raise InternalError(f'{self.name}: packed rows need a lead index')
1709-
li, shift = lead
1710-
grain = int(packing.granule)
1711-
wide = int(li.width)
1712-
if li._value is not None or wide < 1 or grain % wide:
1713-
raise InternalError(
1714-
f'{self.name}: a packing at granule {grain} is read a divisor of '
1715-
f'{grain} rows to a lane at a named slot; this read is {li!r}')
1716-
base = li.nonlead()
1717-
if not isinstance(base, (int, np.integer)):
1718-
raise InternalError(
1719-
f'{self.name}: a packed read needs its slot as a number, not '
1720-
f'{base!r}')
1721-
block = li._block
1709+
# A row every lane reads alike, at a number: what a lead loop at a
1710+
# width leaves of a ragged extent to a body of its own (`_packed_row`).
1711+
row, shifted = index[0], 0
1712+
while isinstance(row, VarOffset):
1713+
shifted += row.offset
1714+
row = row.variable
1715+
if isinstance(row, Immediate):
1716+
row = row._value
1717+
if not isinstance(row, (int, np.integer)):
1718+
raise InternalError(
1719+
f'{self.name}: packed rows need a lead index or a number, not '
1720+
f'{index[0]!r}')
1721+
row = int(row) + shifted
1722+
else:
1723+
li, shift = lead
1724+
grain = int(packing.granule)
1725+
wide = int(li.width)
1726+
if li._value is not None or wide < 1 or grain % wide:
1727+
raise InternalError(
1728+
f'{self.name}: a packing at granule {grain} is read a divisor of '
1729+
f'{grain} rows to a lane at a named slot; this read is {li!r}')
1730+
base = li.nonlead()
1731+
if not isinstance(base, (int, np.integer)):
1732+
raise InternalError(
1733+
f'{self.name}: a packed read needs its slot as a number, not '
1734+
f'{base!r}')
1735+
block = li._block
17221736
# The column, as the packing numbers them: the non-lead axes flattened in
17231737
# F-order over the box, which is the unit `Packing` is built in.
17241738
column, extent, computed = 0, 1, None
@@ -1766,6 +1780,8 @@ def _packed_index(self, writer, context, index):
17661780
if computed is None and not 0 <= column < packing.columns:
17671781
raise InternalError(
17681782
f'{self.name}: packed column {column} of {packing.columns}')
1783+
if row is not None:
1784+
return self._packed_row(index, packing, column, computed, row, lower)
17691785
if computed is not None:
17701786
if packing.uniform:
17711787
return self._uniform_packed_index(writer, index, packing, computed,
@@ -1807,6 +1823,34 @@ def _packed_index(self, writer, context, index):
18071823
valid=valid, pad=False, first=first)
18081824
return [lead_index] + [lower[d] for d in range(1, len(index))]
18091825

1826+
def _packed_row(self, index, packing, column, computed, row, lower):
1827+
"""A read of a packed operand at a row every lane takes alike.
1828+
1829+
A lead loop at width `w` (`Options.lead_vectorize`) over a window whose
1830+
rows are no multiple of `w` reads the rows no whole vector covers in a
1831+
body of their own, at a number rather than a lane: SeisSol's `volume`
1832+
at order 6 reads row 53 of `kDivM` so. The slot is `off_c + r - start_c`
1833+
as for a lane, a number here as well, handed back in the coordinates of
1834+
the view as the lead index is. A row the column does not hold has no
1835+
slot: the number there is zero, and so is the read -- None, which is
1836+
what `load` hands its callers for a factor with no data.
1837+
"""
1838+
if computed is not None:
1839+
raise InternalError(
1840+
f'{self.name}: a packed read at row {row} needs its column as a '
1841+
f'number, not {computed!r}')
1842+
if packing.kind == 'bits':
1843+
# The slot is a population count of the column's rows below `row`,
1844+
# which the bitset holds and this does not read.
1845+
raise InternalError(
1846+
f'{self.name}: a bits packing is read at row {row}, which needs '
1847+
f'its population count')
1848+
start = packing.starts[column]
1849+
if not start <= row - lower[0] < start + packing.lengths[column]:
1850+
return None
1851+
return ([row + packing.offsets[column] - start]
1852+
+ [lower[d] for d in range(1, len(index))])
1853+
18101854
def _uniform_packed_index(self, writer, index, packing, computed, column,
18111855
li, shift, lower):
18121856
"""A packed read whose column the kernel computes rather than knows.
@@ -3472,6 +3516,9 @@ def load(self, writer, context: Context, variable, index: List[Union[str, int, I
34723516
or (self.stype is SymbolType.SharedMem
34733517
and getattr(self, 'verbatim', False)))):
34743518
read_index = self._packed_index(writer, context, read_index)
3519+
if read_index is None:
3520+
# A row the packing does not store (`_packed_row`): zero.
3521+
return None
34753522

34763523
if variable is None and self.stype in (
34773524
SymbolType.Register, SymbolType.Scratch, SymbolType.SharedMem,

‎src/tensorforge/generators/generator.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1835,8 +1835,23 @@ def _shard_spec(self, section) -> Optional[dict]:
18351835
threads=self._num_threads, fptype=self._context.fp_type,
18361836
static=self._context.get_user_options().preload_shards,
18371837
stream=section.streams, aligns=self._proven_alignments(),
1838+
extents=self._operand_extents(),
18381839
report=section.shard_report)
18391840

1841+
def _operand_extents(self) -> dict:
1842+
"""How many elements each batch-constant operand is stored over, by the
1843+
name of its binding (`Tensor.storage_volume`): an order a multiplication
1844+
chose for it reaches past its box, and the binding was typed from the
1845+
box before that."""
1846+
out = {}
1847+
for symbol in self._scopes.get_global_scope().values():
1848+
obj = symbol.obj
1849+
if (getattr(obj, 'addressing', None) == Addressing.NONE
1850+
and symbol.stype != SymbolType.Data):
1851+
out[f'{GeneralLexicon.GLOBAL_MEM_PREFIX}{symbol.name}'] = int(
1852+
obj.storage_volume())
1853+
return out
1854+
18401855
def _proven_alignments(self) -> dict:
18411856
"""What the frontend proves of the batch-constant operands' bases, in
18421857
bytes, by the name of their binding (`Symbol.linear_align_bytes`): how

‎src/tensorforge/reference/kernel_eval.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -742,6 +742,16 @@ def _vec_width(ty: str) -> int:
742742
+ e[m.end():j - 1] + ')')
743743
i = j
744744
e = ''.join(out)
745+
# A vector value-initialized inside an expression -- the zero a guarded
746+
# wide read selects where its guard fails, `g ? *(VectorT<float, 4>*)&p[i]
747+
# : tensorforge::VectorT<float, 4>{}` -- is that many zeros; with numbers
748+
# in the braces it is the literal below, its type said once more.
749+
e = re.sub(r'\btensorforge::Vector(?:Relaxed)?T\s*<[^<>]*?,\s*(\d+)\s*>'
750+
r'\s*\{\s*\}',
751+
lambda m: 'VEC(' + ', '.join(['0.0'] * int(m.group(1))) + ')',
752+
e)
753+
e = re.sub(r'\btensorforge::Vector(?:Relaxed)?T\s*<[^<>]*>\s*(?=\{)', '',
754+
e)
745755
# `{a, b}` in an expression is a vector literal. A bare `{}` is
746756
# zero-initialization and is handled by `_DECL`, so it never reaches here.
747757
e = re.sub(r'\{\s*([^{}]+?)\s*\}', r'VEC(\1)', e)

0 commit comments

Comments
 (0)