Skip to content

Commit cd1eb9e

Browse files
davschnellerclaude
andcommitted
rolling: a merged run carries its temporaries through a rotation
A run that selects a temporary per iteration used to be refused before it became a loop, so SeisSol's anelastic time derivative -- whose whole shape is a chain of temporaries, each level read by the next -- was written out whatever the instruction cache said. `_rotatable` replaces that refusal. It asks what the run carries: a flow at a finite distance means the value a pass writes is read `distance` passes later and never after, so `distance + 1` buffers serve the whole chain and the members take them in turn. The fifth derivative is written where the third was, because by then nothing wants the third. Shapes within a family have to agree, since a slot is one buffer, and holes that overlap are one family: `dQane_1..4` read and `dQane_2..5` written are five tensors, not two sets of four. `Generator._rotate_members` hands out the slots, and `rotate_slots` is how many. The default is the carry's own depth; 1 is the far end of the trade, where a pass reads and writes one buffer -- correct because a multiplication accumulates in registers and the barrier between the read and the write is already there, and worth 27 kB of the block on the order 6 anelastic derivative. Three analyses had to learn the back edge the rotation rides on. A write that covers a buffer whole ends what was there, which is true of one pass and false of a loop, so a buffer the body reads *before* it writes is not killed inside it -- read before written and not read anywhere, or a staged operand would stop reusing the window its own barrier is there for. A table claims its shared members with the effect it has rather than the union of both, which at one position reads as a read before the write. And `layout_check` reads an access inside a merged run against the run's head, because the claim a table makes is a union over the trips pinned at the position the table was declared at, and the slot the first trip reads is written on the trip before by a statement standing after it. On the order 6 anelastic derivative of the new SeisSol master, sm_120 and single precision, the kernel that would not merge at all now does, at 17 112 lines against 39 163 written out and 3 112 spill stores against 7 624 -- for 71 680 B of shared memory against 34 816, or 53 248 B with `rotate_slots=1`. Validated against the written-out build sink by sink: 1.6e-10 worst relative on `dQ(5)`. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent 8a28ac4 commit cd1eb9e

5 files changed

Lines changed: 451 additions & 34 deletions

File tree

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

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,37 @@ def _names(body: Sequence[Stmt]) -> Dict[Any, str]:
167167
return out
168168

169169

170+
def _rolled_spans(body: Sequence[Stmt]) -> List[Tuple[int, int]]:
171+
"""The position ranges of the merged runs in this body.
172+
173+
A merged run reaches its members through a table of their addresses, so
174+
an access inside it names *every* member the table may hand over
175+
(`DeclareOperandTable._accesses`) -- the claim is a union over the
176+
trips, pinned at the position the table is declared at. Two tables of
177+
one rotated family therefore state the loop's read and its write in
178+
whichever order they were declared, which is not the order a trip
179+
touches them, and the slot the first trip reads is written on the trip
180+
before by a statement standing after it.
181+
182+
So a read inside one of these is read against the run's head rather
183+
than against its own position. Only inside: a clobber *within* the run
184+
still has to be answered by a write within the run before the read.
185+
"""
186+
out: List[Tuple[int, int]] = []
187+
188+
def walk(stmts: Sequence[Stmt], pos: List[int]) -> None:
189+
for stmt in stmts:
190+
pos[0] += 1
191+
start = pos[0]
192+
for region in stmt.regions:
193+
walk(region.body, pos)
194+
if stmt.op == Op.FOR and stmt.attr('rolled'):
195+
out.append((start, pos[0]))
196+
197+
walk(body, [0])
198+
return out
199+
200+
170201
def check_layout(body: Sequence[Stmt]) -> Tuple[List[Violation], List[Any]]:
171202
"""Buffers sharing bytes must not be read across each other's writes.
172203
@@ -181,6 +212,7 @@ def check_layout(body: Sequence[Stmt]) -> Tuple[List[Violation], List[Any]]:
181212
win, unplaced = windows(body)
182213
if len(win) < 2:
183214
return [], list(unplaced)
215+
spans = _rolled_spans(body)
184216
all_touches, opaque = touches(body, set(win))
185217
by_buffer: Dict[Any, List[Touch]] = {}
186218
for t in all_touches:
@@ -202,6 +234,13 @@ def check_layout(body: Sequence[Stmt]) -> Tuple[List[Violation], List[Any]]:
202234
other = b if t.buffer == a else a
203235
if t.reads and last_write[other] is not None:
204236
mine = last_write[t.buffer]
237+
# Written anywhere inside the merged run this read sits
238+
# in counts as written at its head -- see `_rolled_spans`.
239+
for lo, hi in spans:
240+
if lo <= t.position <= hi and any(
241+
u.writes and lo <= u.position <= hi
242+
for u in by_buffer.get(t.buffer, ())):
243+
mine = lo if mine is None else max(mine, lo)
205244
if mine is None or mine < last_write[other]:
206245
violations.append(Violation(
207246
names[t.buffer], t.position, names[other],

‎src/tensorforge/common/options.py‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -755,6 +755,31 @@ def __repr__(self):
755755
'on the same trips through the batch loop: the block is one group '
756756
'of `stage_group` multiplications.')
757757

758+
declare('rotate_slots',
759+
default=0,
760+
parse=parse_int,
761+
doc='Buffers a merged run\'s carried temporaries turn through, or 0 '
762+
'for one more than the distance the run carries over.\n'
763+
'A run that selects a temporary per iteration reaches it through '
764+
'a table of addresses, and a buffer per member would put all of '
765+
'them live at once -- 35 temporaries worth 89 kB a '
766+
'multiplication on SeisSol\'s anelastic derivative, which the '
767+
'allocator aliases down to 8 when the run is written out. The '
768+
'members take the buffers in turn instead, which needs as many '
769+
'as the carry is deep: the value a pass writes is read '
770+
'`distance` passes later and never after, so `distance + 1` '
771+
'suffice and the fifth derivative is written where the third '
772+
'was.\n'
773+
'Fewer than that is a trade, not an error, and 1 is the far end '
774+
'of it: a pass then reads and writes one buffer, which is '
775+
'correct wherever the read of a trip completes before its write '
776+
'-- a multiplication accumulates in registers, so it does -- and '
777+
'costs the barrier between them. On the order 6 anelastic '
778+
'derivative it took the block from 80 kB of shared memory to '
779+
'53 kB for two lines of code. More than `distance + 1` buys '
780+
'nothing and is allowed only because refusing it would be a '
781+
'rule with no case behind it.')
782+
758783
declare('stage_group',
759784
default=8,
760785
doc='Multiplications a block holds under `stage_members`, and so how '

‎src/tensorforge/generators/generator.py‎

Lines changed: 185 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
# SPDX-FileCopyrightText: 2026 SeisSol Group
22
#
33
# SPDX-License-Identifier: MIT
4-
from typing import List, Optional, Union, Type
4+
import os
5+
from typing import Dict, List, Optional, Union, Type
56
import copy
67
import functools
78
import hashlib
@@ -1264,7 +1265,10 @@ def _declare_buffers(self, section) -> None:
12641265

12651266
def tracked(sym) -> bool:
12661267
return (getattr(sym, 'stype', None) is SymbolType.SharedMem
1267-
and not isinstance(getattr(sym, 'obj', None), ShrMemObject))
1268+
and not isinstance(getattr(sym, 'obj', None), ShrMemObject)
1269+
# A merged run's rotated stand-in is a pointer into whichever
1270+
# slot its table selects, and the slots are tracked already.
1271+
and not getattr(sym, 'borrowed', False))
12681272

12691273
def block_wide(sym) -> bool:
12701274
first = sym.get_first_user()
@@ -1276,6 +1280,15 @@ def block_wide(sym) -> bool:
12761280
def windows(instrs):
12771281
for instr in instrs:
12781282
for sym in tuple(instr.defs()) + tuple(instr.uses()):
1283+
# A write through a rotated stand-in declares nothing -- the slot
1284+
# its table selects was declared where the slot was -- but it is
1285+
# as ready to emit as any other, and saying so is this pass's job
1286+
# for every shared write there is.
1287+
if getattr(sym, 'borrowed', False):
1288+
for user in sym.get_user_list():
1289+
if isinstance(user, AbstractShrMemWrite):
1290+
user.set_window(False, False)
1291+
continue
12791292
if not tracked(sym) or id(sym) in declared or block_wide(sym):
12801293
continue
12811294
declared.add(id(sym))
@@ -1287,22 +1300,57 @@ def windows(instrs):
12871300
for region in instr.regions():
12881301
windows(region)
12891302

1290-
def lifetimes(instrs, written=frozenset()):
1303+
def repeats(instr) -> bool:
1304+
"""Whether this instruction's regions run more than once.
1305+
1306+
The same question `pir.allocate` asks of a block it cannot read the
1307+
head of, and for the same reason: what a body carries around its
1308+
back edge is live where a single pass through it looks dead.
1309+
"""
1310+
from tensorforge.backend.instructions.batch_loop import BatchLoop
1311+
from tensorforge.backend.instructions.ptr_manip import VariantLoop
1312+
return isinstance(instr, (BatchLoop, VariantLoop))
1313+
1314+
def carried_in(instr) -> set:
1315+
"""Buffers this repeating body reads before it writes them.
1316+
1317+
A write that covers a buffer whole normally ends what was there --
1318+
nothing before it is wanted. Inside a loop that is true of one pass
1319+
and false of the loop: a merged run's rotation writes the slot the
1320+
*next* pass reads, and killing it at the write makes the stretch
1321+
from there to the read look free, which the allocator then hands to
1322+
another buffer (`pir.allocate`). SeisSol's anelastic chain shared a
1323+
rotation slot with a staged operand that way, and the kernel
1324+
computed with the operand's bytes.
1325+
1326+
Read *before* written, which is the question the loop instructions
1327+
already answer for their own operands (`VariantLoop.uses`), and not
1328+
read anywhere: a staged operand is copied in at the head of the body
1329+
and read below it, so a body that carries nothing would carry all of
1330+
them -- and the staged window would stop reusing the one the product
1331+
read the pass before, which is the reuse its barrier is there for.
1332+
"""
1333+
return {id(sym) for sym in instr.uses() if tracked(sym)}
1334+
1335+
def lifetimes(instrs, written=frozenset(), carried=frozenset()):
12911336
seen = set(written)
12921337
for instr in instrs:
12931338
if instr.regions():
12941339
entering = frozenset(seen)
1340+
inner = (carried | carried_in(instr)
1341+
if repeats(instr) else carried)
12951342
for region in instr.regions():
1296-
lifetimes(region, entering)
1343+
lifetimes(region, entering, inner)
12971344
seen.update(id(d) for d in instr.defs())
12981345
continue
12991346
kills = []
13001347
partial = {id(d) for d in instr.partial_defs()}
13011348
for sym in instr.defs():
13021349
if not tracked(sym) or block_wide(sym):
13031350
continue
1304-
if not isinstance(instr, LoadWait) and not (
1305-
id(sym) in partial and id(sym) in seen):
1351+
if (not isinstance(instr, LoadWait)
1352+
and id(sym) not in carried
1353+
and not (id(sym) in partial and id(sym) in seen)):
13061354
kills.append(sym)
13071355
seen.add(id(sym))
13081356
instr._kills = tuple(kills)
@@ -2555,7 +2603,8 @@ def _emit_ir(self, descr_list):
25552603
self._scopes.get_symbol(self._section.shr_mem_obj),
25562604
self._num_threads,
25572605
self._lead_width)
2558-
temporaries = Temporaries(self._context, self._scopes, self._num_threads)
2606+
temporaries = self._temporaries = Temporaries(
2607+
self._context, self._scopes, self._num_threads)
25592608
# Every register image this section allocates is blocked the same way, so
25602609
# the factory carries it rather than each caller passing it along.
25612610
temporaries._lead_width = self._lead_width
@@ -2678,6 +2727,7 @@ def _emit_variant_loop(self, loop, builders) -> None:
26782727
GetElementPtrBuilder
26792728

26802729
body, variants = loop.decompose()
2730+
self._rotate_members(loop, variants)
26812731
written = {id(d.writes().tensor) for d in body if d.writes() is not None}
26822732

26832733
# What the body threads through itself. A destination is not accumulated
@@ -2787,8 +2837,16 @@ def carries(tensor) -> bool:
27872837
addressing = Addressing.SCALAR
27882838
else:
27892839
addressing = Addressing.NONE if resolved else stand_in.obj.addressing
2840+
# Named after the stand-in *tensor* where that is not the symbol's
2841+
# own name. A rotated stand-in resolves to its family's first slot,
2842+
# so two holes of one family share a symbol -- the hole that reads
2843+
# `dQane_d` and the hole that writes `dQane_{d+1}` -- and both tables
2844+
# would be `s11Table`, which is one declaration of two things.
2845+
table_name = (variant.stand_in.tensor.name
2846+
if stand_in.obj is not variant.stand_in.tensor
2847+
else stand_in.name)
27902848
table = DeclareOperandTable(
2791-
self._context, f'{stand_in.name}Table', members,
2849+
self._context, f'{table_name}Table', members,
27922850
addressing,
27932851
stand_in.obj.datatype,
27942852
writable=id(variant.stand_in.tensor) in written,
@@ -2800,7 +2858,17 @@ def carries(tensor) -> bool:
28002858
if self._stages(stand_in, written):
28012859
region.extend(self._stage_member(stand_in, table, counter))
28022860
continue
2803-
pointers.build(stand_in, table=table, variant=counter)
2861+
# A rotated stand-in resolves to its family's first slot, so two
2862+
# holes of one family share a symbol and would name one pointer
2863+
# twice -- the hole that reads `dQane_d` and the hole that writes
2864+
# `dQane_{d+1}` are two bindings on the same pass. The stand-in
2865+
# tensor's own name (`v0`, `v1`) is what tells them apart, and it is
2866+
# the name a stand-in that is no temporary would have given anyway.
2867+
rotated = stand_in.obj is not variant.stand_in.tensor
2868+
pointers.build(stand_in, table=table, variant=counter,
2869+
name=(getattr(variant.stand_in.tensor, 'name', None)
2870+
if rotated else None),
2871+
obj=variant.stand_in.tensor if rotated else None)
28042872
region.extend(pointers.get_instructions())
28052873

28062874
before = {}
@@ -2979,6 +3047,114 @@ def _establish(self, body, builders, keys) -> bool:
29793047
self._section.ir.extend(emitted)
29803048
return True
29813049

3050+
def _rotate_members(self, loop, variants) -> None:
3051+
"""Give a run's temporary members one buffer per *slot*, not per member.
3052+
3053+
A merged run reaches its members through a table of their addresses, and
3054+
a temporary has none until an operation asks for its buffer -- so a run
3055+
that selects one per iteration used to be left written out
3056+
(`rolling._selects_a_temporary`). Handing each member a buffer of its
3057+
own would not do: SeisSol's anelastic derivative has 35 temporaries
3058+
worth 89 kB per multiplication, which the allocator aliases down to 8;
3059+
tabling them apart puts all 35 live at once and there is no such block.
3060+
3061+
What makes it work is that the run *carries* them. The dependence says
3062+
the value a pass writes is read `distance` passes later and never
3063+
after, so `distance + 1` buffers suffice and the members take them in
3064+
turn: the fifth derivative is written where the third was, because by
3065+
then nothing wants the third. Two buffers for the anelastic chain,
3066+
where five members would have been.
3067+
3068+
The ends need no special case, which is the point of rotating by the
3069+
member's own position. The value the peeled prologue leaves in member
3070+
one *is* slot zero, which the first pass reads; the last pass writes the
3071+
member the epilogue reads, in whichever slot that member sits. Both
3072+
fall out of the mapping rather than being arranged around it.
3073+
3074+
A hole and the hole it feeds are one family and must share the slots --
3075+
`dQane_1..4` read and `dQane_2..5` written are five tensors, not two
3076+
sets of four -- so the variants are merged wherever their members
3077+
overlap. Shapes within a family have to agree, since a slot is one
3078+
buffer: this refuses rather than letting two extents address one
3079+
allocation.
3080+
"""
3081+
from tensorforge.backend.instructions.memory.store import ReserveShrMem
3082+
distance = getattr(getattr(loop, 'dependence', None), 'distance', None)
3083+
if not distance or distance < 1:
3084+
return
3085+
from tensorforge.generators.rolling import rotation_families
3086+
families = rotation_families(
3087+
[[v.tensor for v in variant.members
3088+
if getattr(v.tensor, 'is_tmp', False)] for variant in variants])
3089+
3090+
for family in families:
3091+
# In the order the run names them, which is the order they are
3092+
# written in: the slot is the member's position in the chain.
3093+
shapes = {(tuple(int(x) for x in t.get_actual_shape()),
3094+
tuple(int(x) for x in t.get_bbox().lower()),
3095+
tuple(int(x) for x in t.get_bbox().upper())) for t in family}
3096+
if len(shapes) != 1:
3097+
raise InternalError(
3098+
f'a merged run rotates {len(family)} temporaries through '
3099+
f'{distance + 1} buffers, and they do not agree on a shape: '
3100+
f'{sorted(str(s) for s in shapes)}')
3101+
slots: Dict[int, Symbol] = {}
3102+
asked = self._context.get_user_options().rotate_slots
3103+
width = asked if asked else distance + 1
3104+
for position, tensor in enumerate(family):
3105+
slot = position % width
3106+
if self._scopes.get_symbol(tensor) is not None:
3107+
# Already placed -- by an earlier run over the same family, or
3108+
# because it is no temporary after all. Its buffer stands.
3109+
slots.setdefault(slot, self._scopes.get_symbol(tensor))
3110+
continue
3111+
owner = slots.get(slot)
3112+
if owner is None:
3113+
slots[slot] = self._temporaries.shared_symbol(tensor)
3114+
else:
3115+
self._scopes.alias_symbol(tensor, owner)
3116+
for symbol in slots.values():
3117+
# Marked, so that the binding declares *these* buffers occupied and
3118+
# no others: a table over staged members is shared too, and saying
3119+
# the same of those moves a fence the loop depends on.
3120+
symbol.rotation_slot = True
3121+
3122+
# A slot nobody else writes has no first user to declare its window,
3123+
# and every other buffer gets one from a store or a load
3124+
# (`temporaries`). The rotation introduces its own, which is the one
3125+
# thing that knows their size. A slot the peeled prologue already
3126+
# writes -- the family's first member, which is slot zero -- has a
3127+
# user and is left alone.
3128+
for slot, symbol in sorted(slots.items()):
3129+
if symbol.get_user_list():
3130+
continue
3131+
self._section.ir.append(ReserveShrMem(
3132+
self._context, symbol,
3133+
self._scopes.get_symbol(self._section.shr_mem_obj),
3134+
family[0].get_bbox()))
3135+
3136+
# The stand-in resolves to slot zero, and that is all it needs to be.
3137+
# `GetElementPtrBuilder` *reads* it and names a pointer of its own
3138+
# (`glb_s13`) which the loop rebinds from the table on every pass -- so
3139+
# what the stand-in has to be is a defined symbol of the family's shape,
3140+
# not a buffer. Slot zero is both, and the pointer's new name is why
3141+
# this is no circle: the table's entries are the slots, the binding is
3142+
# not one of them.
3143+
#
3144+
# A symbol of its own would be neither defined nor declared: nothing
3145+
# writes it, so the verifier would report a read with no definition,
3146+
# and nothing sizes it, so `_declare_buffers` would have no window.
3147+
for variant in variants:
3148+
tensor = variant.stand_in.tensor
3149+
if (not getattr(tensor, 'is_tmp', False)
3150+
or self._scopes.get_symbol(tensor) is not None):
3151+
continue
3152+
members = [v.tensor for v in variant.members]
3153+
family = next((f for f in families
3154+
if any(t is u for t in f for u in members)), None)
3155+
if family:
3156+
self._scopes.alias_symbol(tensor, self._scopes.get_symbol(family[0]))
3157+
29823158
def _member_symbol(self, view):
29833159
"""The symbol a merged run reaches an operand through.
29843160

0 commit comments

Comments
 (0)