Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions backends/cuda/BUCK
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ fbcode_target(
deps = [
":autotune",
":cuda_passes",
":triton_measured_routing",
":triton_replacement_pass",
"//caffe2:torch",
"//executorch/backends/aoti/passes:passes",
Expand Down Expand Up @@ -229,6 +230,22 @@ fbcode_target(
],
)

fbcode_target(
_kind = runtime.python_library,
name = "triton_measured_routing",
srcs = [
"triton/measured_routing.py",
],
visibility = [
"//executorch/backends/cuda/...",
],
deps = [
":autotune",
":triton_routing",
"//caffe2:torch",
],
)

fbcode_target(
_kind = runtime.python_library,
name = "triton_replacement_pass",
Expand All @@ -241,6 +258,7 @@ fbcode_target(
],
deps = [
":triton_kernels",
":triton_measured_routing",
":triton_routing",
"//caffe2:torch",
"//executorch/exir/dialects:lib",
Expand Down
8 changes: 7 additions & 1 deletion backends/cuda/autotune/cuda_graph_timing.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,12 @@ def time_with_cuda_graph_us(fn: Callable[[], Any]) -> float:
``fn`` must launch its work on the current stream, which must not be the
legacy default stream.
"""
return min(cuda_graph_call_times_us(fn))


def cuda_graph_call_times_us(fn: Callable[[], Any]) -> list[float]:
"""The device time of each of several ``fn()`` calls captured into one
CUDA graph, each with a cold L2, in microseconds."""
stream = torch.cuda.current_stream()
if stream.cuda_stream == 0:
raise RuntimeError("cannot capture on the legacy default CUDA stream")
Expand Down Expand Up @@ -168,7 +174,7 @@ def time_with_cuda_graph_us(fn: Callable[[], Any]) -> float:
call_end.record()
graph.replay()
events[-1][1].synchronize()
return min(s.elapsed_time(e) for s, e in events) * 1000.0
return [s.elapsed_time(e) * 1000.0 for s, e in events]
finally:
# A failed capture leaves nothing to release; that must not mask its error.
with contextlib.suppress(RuntimeError):
Expand Down
51 changes: 49 additions & 2 deletions backends/cuda/cuda_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import contextlib
import copy
import dataclasses
import functools
import logging
import math
Expand Down Expand Up @@ -58,6 +59,11 @@
)
from executorch.backends.cuda.target_smem import target_smem_context
from executorch.backends.cuda.triton.kernels import triton_mutation_cache
from executorch.backends.cuda.triton.measured_routing import (
ApplyChoicesPass,
MeasureChoicesPass,
MeasuredRoutingConfig,
)
from executorch.backends.cuda.triton.replacement_pass import (
ReplaceEdgeOpWithTritonOpPass,
)
Expand Down Expand Up @@ -768,6 +774,35 @@ def _on_off_compile_spec_value(spec: CompileSpec) -> bool:


CUDA_GRAPH_AUTOTUNE_TIMING_COMPILE_SPEC = "cuda_graph_autotune_timing"
MEASURED_ROUTING_COMPILE_SPEC = "measured_routing"
MEASURED_ROUTING_MARGIN_COMPILE_SPEC = "measured_routing_margin"
MEASURED_ROUTING_CACHE_DIR_COMPILE_SPEC = "measured_routing_cache_dir"


def _measured_routing_config(
compile_specs: List[CompileSpec],
) -> Optional[MeasuredRoutingConfig]:
"""The measured-routing settings (ON by default), or None when it is OFF:
calls several implementations can run then take their static choice."""
enabled, config = True, MeasuredRoutingConfig()
for spec in compile_specs:
if spec.key == MEASURED_ROUTING_COMPILE_SPEC:
enabled = _on_off_compile_spec_value(spec)
elif spec.key == MEASURED_ROUTING_MARGIN_COMPILE_SPEC:
value = spec.value.decode("utf-8")
try:
margin = float(value)
except ValueError:
margin = math.nan
if not 0 <= margin <= 1:
raise ValueError(
f"Invalid {spec.key}: {value!r}. Expected a number from 0 to 1."
)
config = dataclasses.replace(config, margin=margin)
elif spec.key == MEASURED_ROUTING_CACHE_DIR_COMPILE_SPEC:
config = dataclasses.replace(config, cache_dir=spec.value.decode("utf-8"))
return config if enabled else None


# The CUDA tensors `move_program_to_device` placed on the GPU for the compile on
# this thread: they can be parked on the CPU when an autotune capture runs out
Expand Down Expand Up @@ -1415,7 +1450,9 @@ def get_decomposition_table(cls) -> Dict[Any, Any]:
@classmethod
def get_custom_passes(cls, compile_specs: List[CompileSpec]) -> List[typing.Any]:
"""
Return CUDA-specific passes, ending with ReplaceEdgeOpWithTritonOpPass.
Return CUDA-specific passes, ending with ReplaceEdgeOpWithTritonOpPass
and, with measured routing on, the passes that measure the
implementations of the calls several can run and apply the choice.

The replacement pass uses Triton kernels for the calls they support and
leaves other calls to the regular lowering. The triton_kernel_mode
Expand Down Expand Up @@ -1462,7 +1499,17 @@ def get_custom_passes(cls, compile_specs: List[CompileSpec]) -> List[typing.Any]
passes.append(
LowerOffGraphKVPass(parse_offgraph_kv_manifest(spec.value))
)
passes.append(ReplaceEdgeOpWithTritonOpPass())
config = _measured_routing_config(compile_specs)
passes.append(
ReplaceEdgeOpWithTritonOpPass(measured_routing=config is not None)
)
if config is not None:
try:
method_name = cls.method_name_from_compile_specs(compile_specs)
except RuntimeError:
method_name = "method"
passes.append(MeasureChoicesPass(cls, compile_specs, config))
passes.append(ApplyChoicesPass(method_name, config))
return passes

@classmethod
Expand Down
27 changes: 27 additions & 0 deletions backends/cuda/tests/targets.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,33 @@ def define_common_targets(is_fbcode = False):
),
)

python_unittest_remote_gpu(
name = "test_measured_routing",
srcs = [
"test_measured_routing.py",
],
visibility = [
"//executorch/...",
],
deps = [
"//caffe2:torch",
"//executorch/backends/cuda:cuda_backend",
"//executorch/backends/cuda:cuda_partitioner",
"//executorch/backends/cuda:triton_measured_routing",
"//executorch/backends/cuda:triton_replacement_pass",
"//executorch/backends/cuda:triton_routing",
"//executorch/exir:lib",
"//executorch/exir/backend:compile_spec_schema",
"//executorch/exir/dialects:lib",
"//executorch/export:export_utils",
],
keep_gpu_sections = True,
remote_execution = re_test_utils.remote_execution(
platform = "gpu-remote-execution",
subplatform = "A100",
),
)

python_unittest_remote_gpu(
name = "test_triton_replacement",
srcs = [
Expand Down
24 changes: 23 additions & 1 deletion backends/cuda/tests/test_cuda_export.py
Original file line number Diff line number Diff line change
Expand Up @@ -1124,7 +1124,29 @@ def test_triton_kernel_mode_off(self):
[CompileSpec("triton_kernel_mode", b"OFF")]
)
self.assertEqual([type(p) for p in off], [type(p) for p in on])
self.assertIsInstance(off[-1], ReplaceEdgeOpWithTritonOpPass)
self.assertIn(ReplaceEdgeOpWithTritonOpPass, [type(p) for p in off])

def test_measured_routing_is_on_by_default(self):
"""Without the compile spec, the passes that measure the calls several
implementations can run follow the replacement pass; OFF leaves them
out."""
from executorch.backends.cuda.triton.measured_routing import (
ApplyChoicesPass,
MeasureChoicesPass,
)

default = [type(p) for p in CudaBackend.get_custom_passes([])]
off = [
type(p)
for p in CudaBackend.get_custom_passes(
[CompileSpec("measured_routing", b"OFF")]
)
]
self.assertEqual(
default[-3:],
[ReplaceEdgeOpWithTritonOpPass, MeasureChoicesPass, ApplyChoicesPass],
)
self.assertEqual(off, default[:-2])

def test_missing_scatter_kernel_fails_at_export(self):
"""The scatter fallback writes its kernel call itself, and the check for
Expand Down
Loading