Skip to content

Commit 5dd47b6

Browse files
committed
feat: make CLC work on Blackwell
AI-generated. Model: Opus 5
1 parent 1dc7f78 commit 5dd47b6

7 files changed

Lines changed: 570 additions & 68 deletions

File tree

‎src/tensorforge/backend/instructions/batch_loop.py‎

Lines changed: 77 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,8 @@ def __init__(self,
5050
stride: str,
5151
region: List[AbstractInstruction],
5252
lookahead: int = 2,
53-
flags: FlagMode = FlagMode.OPTIONAL):
53+
flags: FlagMode = FlagMode.OPTIONAL,
54+
queue_depth: int = 1):
5455
super().__init__(context)
5556
self._section_index = section_index
5657
self._mode = mode
@@ -71,6 +72,18 @@ def __init__(self,
7172
self._stage_depth: Optional[int] = None
7273
# ids of leading region instructions emitted outside the flag guard
7374
self._unguarded: set = set()
75+
# `LAUNCHCTRL` only: how many cancel requests are kept in flight. One
76+
# is enough to hide the queue's own latency behind the body, because
77+
# the request for the next element is posted before the current one is
78+
# computed. It is *not* enough to prefetch the next element's data:
79+
# at depth one the next index arrives at the bottom of the iteration,
80+
# with no body left to overlap a transfer with. Two is the first
81+
# depth at which the index is known at the top.
82+
if mode is LoopMode.LAUNCHCTRL and queue_depth < 1:
83+
raise InternalError(
84+
f'the work queue needs at least one request in flight, '
85+
f'got {queue_depth}')
86+
self._queue_depth = queue_depth
7487
self._is_ready = True
7588

7689
# -- structure ------------------------------------------------------- #
@@ -116,8 +129,16 @@ def uniform_scope(self) -> BarrierScope:
116129
guard. The tail block skips the body entirely, so a grid barrier there
117130
deadlocks.
118131
119-
``LAUNCHCTRL``: the queue hands out work per block, and the size guard
120-
is the same.
132+
``LAUNCHCTRL``: the *loop* is the exception -- its trip count is
133+
block-uniform. Every thread reads the same cancel response out of
134+
shared memory behind a barrier, so all of them leave on the same
135+
iteration, and the hand-off itself contains a ``__syncthreads``. What
136+
is still only ``SIMD``-uniform is the size guard *inside* it, which is
137+
per element exactly as in the other two modes. Answering ``GROUP``
138+
here would license a block barrier that ``_emit_body`` may then place
139+
under that guard, so the loop keeps the conservative answer until the
140+
guard is a construct ``verify`` can see; the barrier the queue needs
141+
for itself sits outside the guard where the emission puts it.
121142
"""
122143
return BarrierScope.SIMD
123144

@@ -504,10 +525,30 @@ def gen_code(self, writer) -> None:
504525
def _structured_loop(self, writer) -> bool:
505526
"""Should this loop be an `Op.FOR` rather than Writer text?
506527
507-
`PERSISTENT` only, for now. `LAUNCHCTRL` is a `while` with a break and
508-
a queried successor, which is not a counted loop and wants its own
509-
design; the remaining mode has no loop at all, so there is nothing to
510-
put in the IR.
528+
`PERSISTENT` only, for now. The remaining mode has no loop at all, so
529+
there is nothing to put in the IR.
530+
531+
`LAUNCHCTRL` is the open one, and it is worth stating what it needs
532+
rather than that it needs something. Everything the IR would buy here
533+
hangs off one missing form: a loop whose successor is *queried*, not
534+
incremented. `for_` hands the body `loop.induction` because it
535+
computed it; the queue's next index is the result of a statement
536+
inside the body -- `cursor.next(queue)` -- and the loop ends when that
537+
statement answers -1. Give the builder that form and the rest follows
538+
at once: `batchId0` becomes a value, so the size guard becomes an
539+
`Op.IF` on it instead of `writer.If` over text and the body's reads of
540+
it are operands; the hand-off becomes an `Op.CALL` carrying
541+
`Effect.BARRIER` and its shared accesses, so the barrier it contains
542+
stops being invisible to every pass; and the region the passes walk
543+
becomes the whole loop rather than the part between the braces.
544+
545+
Without that form each of those is cosmetic, which is why this returns
546+
False rather than half of it. The cost is a name in `Op` -- a
547+
vocabulary deliberately closed -- plus the handle in `build.py`, the
548+
spelling and the `break` in `emit.py`, and the uniformity rule in
549+
`inspect.py`. Note also that the loop is *block*-uniform, which the
550+
counted loop is not, so the form can carry a stronger answer than
551+
`uniform_scope` gives today.
511552
512553
Not when a body is already open: `shared_body` nests, and a second
513554
one would put the loop inside the body it is meant to contain.
@@ -574,20 +615,41 @@ def gen_code_inner(self, writer) -> None:
574615
self._advance_stage_counter(writer)
575616
elif self._mode is LoopMode.LAUNCHCTRL:
576617
self._declare_stage_counter(writer)
577-
writer(f'__shared__ tensorforge::ClusterLaunchCtrl launchctrl;')
578-
writer(f'int phase = 0;')
579-
writer(f'launchctrl.init();')
618+
self._declare_windows_early(writer, list(self._region))
619+
depth = self._queue_depth
620+
writer(f'__shared__ tensorforge::ClusterLaunchQueue<{depth}> '
621+
f'launchQueue{self._section_index};')
622+
# The cursor is a *local*: it is per-thread state, and every thread
623+
# of the block advances it identically. In shared memory the
624+
# parity would be one word 128 threads flip, which is a race whose
625+
# symptom is a wait for a phase that has already gone past.
626+
writer(f'tensorforge::ClusterLaunchCursor<{depth}> '
627+
f'launchCursor{self._section_index};')
628+
writer(f'launchCursor{self._section_index}'
629+
f'.start(launchQueue{self._section_index});')
580630
writer(f'size_t {self._batch(0)} = {self._block_id()};')
581-
with writer.While(f'true'):
582-
writer('launchctrl.setupNext();')
631+
with writer.While('true'):
583632
with writer.If(self._size_guard()):
584633
self._emit_body(writer)
585634
self._advance_stage_counter(writer)
586-
writer('const auto nextBlock = launchctrl.queryNext(phase);')
587-
with writer.If('!nextBlock.has_value()'):
635+
# Outside the size guard, deliberately. `next` contains the
636+
# block barrier that separates one element's shared memory
637+
# from the next one's, and the guard is per element: the rows
638+
# of a block hold different elements, so a barrier inside it
639+
# is reached by some rows and not others. That does not
640+
# reliably deadlock -- `bar.sync` pairs arrivals by barrier
641+
# *number*, so the rows that skipped rendezvous at the next
642+
# one instead and the loop limps on one barrier out of step,
643+
# reusing the tile an iteration early. Measured both ways: a
644+
# block barrier under the guard hangs outright once a flag
645+
# mask makes the rows disagree persistently.
646+
writer(f'const int nextBlock{self._section_index} = '
647+
f'launchCursor{self._section_index}'
648+
f'.next(launchQueue{self._section_index});')
649+
with writer.If(f'nextBlock{self._section_index} < 0'):
588650
writer('break;')
589651
writer(f'{self._batch(0)} = '
590-
f'{self._block_id("nextBlock.value()")};')
652+
f'{self._block_id(f"nextBlock{self._section_index}")};')
591653
else:
592654
writer(f'const size_t {self._batch(0)} = {self._block_id()};')
593655
with writer.If(self._size_guard()):

‎src/tensorforge/backend/opt/wrap.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,17 @@ def _wrap_loop(self, loop: BatchLoop):
100100
# one iteration, so there is no next element to prefetch and no
101101
# back edge to wrap across
102102
return [], body
103+
if loop._mode is LoopMode.LAUNCHCTRL:
104+
# There *is* a next element, and this pass cannot name it. It
105+
# prefetches through `index_name(1)`, which the strided loop binds
106+
# as `batchId0 + stride`; the queue hands out whatever CTA the
107+
# launcher cancels, so that name is some other block's element.
108+
# The transfer would land in the buffer the next iteration reads
109+
# and every element after the first would be computed from the
110+
# wrong operands -- no crash, wrong numbers. `Generator` refuses
111+
# the combination outright, and the reason lives here because this
112+
# is what depends on it.
113+
return [], body
103114

104115
model = SlotModel(body).run()
105116
n = model.n

‎src/tensorforge/common/options.py‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,6 +373,43 @@ def __repr__(self):
373373
'only `Addressing.NONE` operands are eligible at all, so a case '
374374
'with none of them pays the question with nothing.')
375375

376+
declare('launch_control',
377+
default=False,
378+
parse=parse_bool,
379+
doc='Traverse the batch through Blackwell\'s cluster launch control '
380+
'instead of a grid-stride loop.\n'
381+
'`clusterlaunchcontrol.try_cancel` asks the launcher not to launch '
382+
'a CTA that has not started, and hands the caller its id, so a '
383+
'resident block drains the grid without an occupancy query and the '
384+
'tail is the hardware\'s problem. Needs `sm_100` or above; the '
385+
'CCCL wrappers gate on `__CUDA_ARCH__ >= 1000` and a lower target '
386+
'fails at link time with a named symbol.\n'
387+
'Off by default, and the reason is measured rather than cautious. '
388+
'On an sm_120 part the queue costs 11-28% against the grid-stride '
389+
'loop at every batch size from 600 to 262144, and the split says '
390+
'why. Timing the same traversal with one block barrier per '
391+
'element added accounts for 7-15% of that on its own; the queue '
392+
'adds about two points on top. The grid-stride loop needs no '
393+
'block barrier because the rows of a block hold independent '
394+
'elements, and the hand-off needs one because every thread has to '
395+
'read the response before the slot is reused. So the switch '
396+
'becomes interesting for a configuration that already '
397+
'synchronises block-wide, and for work whose cost varies per '
398+
'element -- not for the row-independent, uniform-cost kernels '
399+
'this generator emits today.')
400+
401+
declare('launch_control_depth',
402+
default=1,
403+
parse=parse_int,
404+
doc='Cancel requests kept in flight per block.\n'
405+
'One hides the queue\'s own latency behind the body. Two is the '
406+
'first depth at which the *next* element\'s index is known at the '
407+
'top of the iteration, which is what a data prefetch needs -- at '
408+
'depth one it arrives at the bottom, with no body left to overlap '
409+
'a transfer with. Beyond two a block reserves elements it has not '
410+
'started, which costs at the tail: depth 4 measured worse than '
411+
'depth 2 in every configuration.')
412+
376413
declare('wide_bodies',
377414
default=True,
378415
env='TF_IR_WIDE',

‎src/tensorforge/generators/generator.py‎

Lines changed: 82 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,30 @@ def flush(self) -> None:
158158
self._pending = []
159159

160160

161+
def _supports_launch_control(context) -> bool:
162+
"""Does this target have `clusterlaunchcontrol.try_cancel`?
163+
164+
PTX ISA 8.6, and the CCCL wrappers gate the instruction on
165+
`__CUDA_ARCH__ >= 1000`, so a lower target does not fail to compile -- it
166+
fails to *link*, against a stub named
167+
`__cuda_ptx_clusterlaunchcontrol_try_cancel_is_not_supported_before_SM_100__`.
168+
Which is a decent error to read and a bad one to reach from a switch, so the
169+
question is answered here.
170+
171+
The arch names are `sm_NN` throughout `hw_descr_db.yml`, two or three digits
172+
and no `a`/`f` suffix, so the numeric part orders them; `sm_120` answers yes
173+
and `sm_90` no, which is the split the instruction actually has. Verified on
174+
an sm_120 part: the plain target assembles it, no `sm_120a` needed.
175+
"""
176+
hw = context.get_vm().get_hw_descr()
177+
if hw.vendor != 'nvidia':
178+
return False
179+
model = hw.model
180+
if not model.startswith('sm_') or not model[3:].isdigit():
181+
return False
182+
return int(model[3:]) >= 100
183+
184+
161185
class Generator:
162186
NAME_ENCODING_LENGTH = 10
163187

@@ -239,8 +263,15 @@ def __init__(self,
239263

240264
self._name_operands(self.descr_list)
241265

242-
# launch control is (still) broken
243-
prefer_launchcontrol = False # context.get_vm().get_hw_descr().vendor == 'nvidia' and int(context.get_vm().get_hw_descr().model[3:]) >= 100
266+
# Asked for and unavailable is an error, not a fallback. A caller who
267+
# switched the traversal and silently got the other one would attribute
268+
# the grid-stride loop's numbers to the queue.
269+
if context.get_user_options().launch_control and not _supports_launch_control(context):
270+
hw = context.get_vm().get_hw_descr()
271+
raise GenerationError(
272+
f'launch_control needs `clusterlaunchcontrol`, which is sm_100 and '
273+
f'above; this target is {hw.vendor} {hw.model}')
274+
prefer_launchcontrol = context.get_user_options().launch_control
244275
prefer_persistent = context.get_vm().get_hw_descr().vendor in ['amd', 'nvidia'] and not prefer_launchcontrol
245276
# The vendor rule is the default and not the decision; it is carried by the
246277
# option's declaration, and a caller asking either way overrides it there,
@@ -252,6 +283,24 @@ def __init__(self,
252283
self._preload_globals = prefer_preload
253284

254285
self._clusterlaunchcontrol = prefer_launchcontrol
286+
self._launch_control_depth = context.get_user_options().launch_control_depth
287+
288+
if prefer_launchcontrol:
289+
# The queue answers with a CTA id nothing can predict, so `batchId1`,
290+
# which every prefetch pass reads, is `batchId_start + stride` and names
291+
# an element this block will never be handed. Nothing crashes: the
292+
# transfer lands in the buffer the next iteration reads, and every
293+
# element after the first is computed from another element's operands.
294+
# Refused rather than silently wrong, until the lookahead index comes
295+
# out of the queue instead of out of the stride.
296+
options = context.get_user_options()
297+
for name in ('enable_wrap_loads', 'enable_pipeline', 'enable_multibuffer'):
298+
if getattr(options, name):
299+
raise GenerationError(
300+
f'{name} prefetches element `batchId1 = batchId_start + stride`, '
301+
f'which under launch_control is not the element the queue hands '
302+
f'out next; the two cannot be combined until the lookahead index '
303+
f'is read from the queue (needs launch_control_depth >= 2)')
255304

256305
def set_kernel_name(self, name):
257306
self._base_kernel_name = name
@@ -442,7 +491,8 @@ def generate(self):
442491
start=start,
443492
stride=stride,
444493
region=self._section.ir,
445-
flags=self._flags)
494+
flags=self._flags,
495+
queue_depth=self._launch_control_depth)
446496

447497
# The prologue stays *out* of the rewritable stream. Its shared-memory
448498
# symbols are allocated by ShrMemObject.alloc_global, a separate bump
@@ -469,7 +519,13 @@ def generate(self):
469519
# one guards the next iteration's writes against the previous
470520
# iteration's reads -- a dependency across the back edge that the pass
471521
# does not model. Adding it before optimisation removes it again.
472-
if self._persistent_threading or self._clusterlaunchcontrol:
522+
#
523+
# `LAUNCHCTRL` is excluded, and not because it needs the separation less.
524+
# It gets it from the hand-off, which carries a block barrier outside the
525+
# size guard between one element's body and the next. Appending a second
526+
# one puts it *inside* that guard, where the rows of a block decide the
527+
# predicate differently and a barrier is reached by some of them only.
528+
if self._persistent_threading:
473529
loop.append(SyncThreads(self._context, self._num_threads))
474530

475531
self._deduce_mults_per_block()
@@ -649,7 +705,28 @@ def _generate_launcher(self):
649705

650706
writer(f'{lexic.kernel_range_object("block", f"{self._num_threads}, {mults_per_block}, 1")};')
651707
if not self._persistent_threading:
652-
assert not coop
708+
if coop:
709+
# Both remaining traversals launch one block per element rather than
710+
# one per worker, which is what a grid barrier cannot have: a
711+
# cooperative launch requires every block of the grid to be resident
712+
# at once, and this grid is sized by the batch.
713+
#
714+
# Under `launch_control` it is not a sizing question but a
715+
# structural one. The queue *works* by the launcher never starting
716+
# most of the grid -- a resident block cancels the CTAs it then
717+
# processes itself -- so the blocks a grid barrier would wait for
718+
# are precisely the ones that will not exist. Nor do the surviving
719+
# blocks agree on a count: each runs until its own cancel request
720+
# comes back empty.
721+
how = ('launch_control cancels most of the grid before it is '
722+
'launched, so the blocks a grid barrier waits for never '
723+
'run' if self._clusterlaunchcontrol else
724+
'one block per element does not fit on the device at once')
725+
raise GenerationError(
726+
f'this kernel has a grid-wide barrier, which needs a '
727+
f'cooperative launch over resident workers; {how}. Use the '
728+
f'grid-stride traversal for a section that synchronises '
729+
f'across the grid.')
653730
num_blocks = f'({GeneralLexicon.NUM_ELEMENTS}0 + {mults_per_block} - 1) / {mults_per_block}'
654731
else:
655732
writer(f'{lexic.get_launch_size(kernel_name, "block", shmemsize)}')

0 commit comments

Comments
 (0)