mirror of
https://github.com/jafioti/luminal.git
synced 2026-06-01 21:49:47 +09:00
Compare commits
40 Commits
yolo-v11n
...
tucker/cub
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a45629cece | ||
|
|
4cd47ffa45 | ||
|
|
db72cf505c | ||
|
|
766db93b08 | ||
|
|
4e93f02725 | ||
|
|
25393a9fdd | ||
|
|
81ea750e6b | ||
|
|
f94335b1b8 | ||
|
|
f62e3c50d0 | ||
|
|
eeeabd7c20 | ||
|
|
0f02466f3d | ||
|
|
156fac518e | ||
|
|
a3df68bd43 | ||
|
|
7a95e56a8b | ||
|
|
e558ce6849 | ||
|
|
c898b7fd53 | ||
|
|
6cfbf538d0 | ||
|
|
966f6f8147 | ||
|
|
8ea9a71747 | ||
|
|
861c3f0419 | ||
|
|
8f17561094 | ||
|
|
d5e9001c8b | ||
|
|
6416ddb5f8 | ||
|
|
c9d4ce6217 | ||
|
|
1dcd0370ce | ||
|
|
6757a4e37b | ||
|
|
631451f8b8 | ||
|
|
70bdd75163 | ||
|
|
855f2bfd02 | ||
|
|
cf7fa2297c | ||
|
|
cd3f55a3a7 | ||
|
|
11653c6903 | ||
|
|
6d16bdba21 | ||
|
|
7bfd19fb72 | ||
|
|
42caa4750e | ||
|
|
1279dca4e6 | ||
|
|
53f7960130 | ||
|
|
5c3407c596 | ||
|
|
47530062a4 | ||
|
|
8524636d6f |
@@ -1,3 +1,6 @@
|
||||
[alias]
|
||||
examples = "run --release --bin examples-perf --"
|
||||
|
||||
[target.aarch64-unknown-linux-gnu]
|
||||
rustflags = [
|
||||
"-Ctarget-feature=+fp16,+fhm"
|
||||
|
||||
2
.github/workflows/modal-examples.yml
vendored
2
.github/workflows/modal-examples.yml
vendored
@@ -18,7 +18,7 @@ jobs:
|
||||
name: "${{ matrix.example }} (Modal ${{ matrix.gpu.type }})"
|
||||
runs-on: ubuntu-latest
|
||||
environment: Modal
|
||||
timeout-minutes: 70
|
||||
timeout-minutes: 120
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
|
||||
2
.github/workflows/test-core.yml
vendored
2
.github/workflows/test-core.yml
vendored
@@ -21,4 +21,4 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- name: Run tests
|
||||
run: cargo test --workspace --exclude luminal_cuda_lite --exclude luminal_metal --exclude luminal_bench --verbose
|
||||
run: cargo test --release -p luminal -p luminal_nn -p luminal_tracing -p luminal_python --verbose
|
||||
|
||||
2
.github/workflows/test-cuda.yml
vendored
2
.github/workflows/test-cuda.yml
vendored
@@ -18,7 +18,7 @@ jobs:
|
||||
name: Cuda Unit Tests
|
||||
runs-on: ubuntu-latest
|
||||
environment: Modal
|
||||
timeout-minutes: 30
|
||||
timeout-minutes: 120
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
67
.github/workflows/test-full-cuda.yml
vendored
Normal file
67
.github/workflows/test-full-cuda.yml
vendored
Normal file
@@ -0,0 +1,67 @@
|
||||
name: Test Full CUDA
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
branches: ["main"]
|
||||
types: [labeled, synchronize]
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
rust_cuda_ignored_tests:
|
||||
if: >-
|
||||
github.event_name == 'workflow_dispatch'
|
||||
|| (github.event_name == 'pull_request_target'
|
||||
&& contains(github.event.pull_request.labels.*.name, 'full-modal-ready'))
|
||||
name: Rust CUDA Ignored Tests
|
||||
runs-on: ubuntu-latest
|
||||
environment: Modal
|
||||
timeout-minutes: 300
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.11"
|
||||
- name: Install Modal
|
||||
run: pip install modal
|
||||
- name: Run ignored CUDA Rust tests on Modal
|
||||
env:
|
||||
MODAL_TOKEN_ID: ${{ secrets.MODAL_TOKEN_ID }}
|
||||
MODAL_TOKEN_SECRET: ${{ secrets.MODAL_TOKEN_SECRET }}
|
||||
GPU_TYPE: H100
|
||||
MODAL_TIMEOUT: "14400"
|
||||
CARGO_TEST_ARGS: "--ignored --test-threads=1"
|
||||
run: modal run ci/modal_cargo_test.py
|
||||
|
||||
python_cuda_slow_tests:
|
||||
if: >-
|
||||
github.event_name == 'workflow_dispatch'
|
||||
|| (github.event_name == 'pull_request_target'
|
||||
&& contains(github.event.pull_request.labels.*.name, 'full-modal-ready'))
|
||||
name: Python CUDA Slow Tests
|
||||
runs-on: ubuntu-latest
|
||||
environment: Modal
|
||||
timeout-minutes: 300
|
||||
defaults:
|
||||
run:
|
||||
working-directory: crates/luminal_python
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.11"
|
||||
- name: Install Modal
|
||||
run: pip install modal
|
||||
- name: Run slow pytest CUDA tests on Modal
|
||||
env:
|
||||
MODAL_TOKEN_ID: ${{ secrets.MODAL_TOKEN_ID }}
|
||||
MODAL_TOKEN_SECRET: ${{ secrets.MODAL_TOKEN_SECRET }}
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
||||
run: modal run modal_pytest_runner.py --gpu A100-80GB --timeout 14400 tests/ -v -s -m slow
|
||||
19
.github/workflows/test-metal.yml
vendored
19
.github/workflows/test-metal.yml
vendored
@@ -16,4 +16,21 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- name: Run Metal crate tests
|
||||
run: rustup update; cargo test -p luminal_metal --verbose -- --test-threads=1
|
||||
run: rustup update; cargo test --release -p luminal_metal --verbose -- --test-threads=1
|
||||
|
||||
llama_1b_metal_example:
|
||||
name: Llama 1B Metal Example
|
||||
runs-on: macos-14-xlarge
|
||||
timeout-minutes: 120
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- name: Print runner hardware
|
||||
run: system_profiler SPHardwareDataType SPDisplaysDataType
|
||||
- name: Cache Hugging Face models
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/huggingface
|
||||
key: llama-1b-metal-hf-${{ runner.os }}-${{ runner.arch }}-v1
|
||||
- name: Run Llama 1B Metal example and validate output
|
||||
run: rustup update; python3 ci/metal_llama_1b_example.py
|
||||
|
||||
4
.github/workflows/test-python-cuda.yml
vendored
4
.github/workflows/test-python-cuda.yml
vendored
@@ -18,7 +18,7 @@ jobs:
|
||||
name: Python CUDA Tests
|
||||
runs-on: ubuntu-latest
|
||||
environment: Modal
|
||||
timeout-minutes: 60
|
||||
timeout-minutes: 120
|
||||
defaults:
|
||||
run:
|
||||
working-directory: crates/luminal_python
|
||||
@@ -38,7 +38,7 @@ jobs:
|
||||
MODAL_TOKEN_ID: ${{ secrets.MODAL_TOKEN_ID }}
|
||||
MODAL_TOKEN_SECRET: ${{ secrets.MODAL_TOKEN_SECRET }}
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
||||
run: modal run modal_pytest_runner.py --gpu A100 --timeout 3300 --profile --profile-output-dir luminal_artifacts/pytest-profiling/github-${{ github.run_id }}-${{ github.run_attempt }} tests/ -v -s -m "not slow"
|
||||
run: modal run modal_pytest_runner.py --gpu A100 --timeout 7200 --profile --profile-output-dir luminal_artifacts/pytest-profiling/github-${{ github.run_id }}-${{ github.run_attempt }} tests/ -v -s -m "not slow"
|
||||
- name: Upload Modal pytest profiling artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
|
||||
2
.github/workflows/test-python-native.yml
vendored
2
.github/workflows/test-python-native.yml
vendored
@@ -23,6 +23,6 @@ jobs:
|
||||
- name: Update Rust toolchain
|
||||
run: rustup update
|
||||
- name: Build maturin extension
|
||||
run: uv run maturin develop --manifest-path rust/Cargo.toml
|
||||
run: uv run maturin develop --manifest-path rust/Cargo.toml --profile release
|
||||
- name: Run pytest
|
||||
run: uv run pytest tests/test_hlir_ops.py tests/test_unary.py -v -m "not slow"
|
||||
|
||||
12
AGENTS.md
12
AGENTS.md
@@ -8,4 +8,14 @@ All other functionality is split into crates in the `crates/` directory. For ins
|
||||
## Testing Instructions
|
||||
- Find the CI plan in the .github/workflows folder.
|
||||
- Currently running `cargo test` in luminal_metal and luminal_cuda_lite require access to an Apple and Nvidia GPU respectively.
|
||||
- PRs must have no clippy errors and `cargo fmt` must be ran before a PR is submitted.
|
||||
- PRs must have no clippy errors and `cargo fmt` must be ran before a PR is submitted.
|
||||
|
||||
## Debugging and Correctness
|
||||
- Treat model examples as specifications of the intended architecture. Do not change model code, prompt templates, weights, or example logic to hide compiler/runtime/search bugs unless the model code is demonstrably semantically wrong.
|
||||
- When outputs are incorrect, first root-cause the failing compiler/runtime path. Prefer isolating the bad LLIR/HLIR graph, rewrite, op lowering, shape/stride assumption, layout contract, or runtime implementation that caused the mismatch.
|
||||
- Avoid narrow special-case fixes. A fix should state and enforce the general invariant it relies on, or explicitly document why the affected operation is only valid for a restricted layout/shape and ensure rewrites enforce that restriction.
|
||||
- For e-graph/search issues, assume all selectable LLIR graphs are intended to be semantically equivalent. If two selectable graphs disagree, debug the equivalence violation rather than selecting around the bad graph.
|
||||
- Add regression tests at the level where the bug occurred. Prefer tests that compare against a semantic reference such as `NativeRuntime` or a small independent reference, and use fixed seeds for any randomized search/fuzz test so failures are reproducible.
|
||||
|
||||
## Compiler Rewrite Boundary
|
||||
- All graph pattern matching and op selection must be expressed in egglog rewrites. Do not add Rust-side LLIR graph post-passes that search for op patterns, fuse kernels, select backend ops, or otherwise rewrite extracted graphs after egglog. If a backend needs a fused/specialized op, add the match and rewrite in egglog and let extraction produce that op directly.
|
||||
|
||||
50
README.md
50
README.md
@@ -55,23 +55,27 @@ Luminal can run Q8 Llama 3 8B at ~80% of theoretical max performance on an H100.
|
||||
|
||||
The core of Luminal is and always will be minimal. It should be possible to understand the entire core library in an afternoon.
|
||||
|
||||
### PyTorch-native
|
||||
|
||||
Luminal directly integrates with PyTorch as a compiler backend. Simply do `torch.compile(model, backend=luminal_cuda)` to compile your PyTorch models. We also have an excellent tensor API in Rust.
|
||||
|
||||
### RISC-style architecture
|
||||
|
||||
Everything in Luminal boils down to 14 primitive ops:
|
||||
Everything in Luminal boils down to 15 primitive ops:
|
||||
|
||||
- Unary - `Log2, Exp2, Sin, Sqrt, Recip`
|
||||
- Binary - `Add, Mul, Mod, LessThan`
|
||||
- Other - `SumReduce, MaxReduce, Iota, Gather, Cast`
|
||||
- Other - `SumReduce, MaxReduce, Iota, Gather, Scatter, Cast`
|
||||
|
||||
These ops are enough to support transformers, convnets, and nearly every popular model.
|
||||
These ops are enough to support transformers, convnets, and nearly every popular model in the world.
|
||||
|
||||
### Search
|
||||
|
||||
The best heuristic is no heuristic. We try to search every possible decision to give the compiler the most flexibility to discover complex optimizations. This allows us to automatically derive Flash Attention and other similarly complex rewrites. It also allows us to stay extremely small long into the future and beat the performance of far larger frameworks with tons of handwritten kernels.
|
||||
The best heuristic is no heuristic. Luminal tries to search every possible decision to give the compiler the flexibility to discover complex optimizations. This allows us to automatically discover Flash Attention and other similarly complex optimizations without relying on hand-written operations or heuristics. It also allows us to stay extremely small and simple long into the future and beat the performance of far larger frameworks.
|
||||
|
||||
### Native
|
||||
|
||||
The current ML ecosystem is too fragmented, and the solution isn't another layer of abstraction. Luminal is written in rust, and interacts directly with the CUDA / Metal APIs. No indirections or abstractions, docker containers, or virtual environments. Just a statically-linked rust crate.
|
||||
The current ML ecosystem is too fragmented, and the solution isn't another layer of abstraction. Luminal is written in rust, and interacts directly with the accelerator APIs (CUDA, Metal, etc.). No indirections or abstractions, compatability layers, docker containers, or virtual environments. Just a statically-linked rust crate.
|
||||
|
||||
### Validated against Pytorch
|
||||
|
||||
@@ -85,39 +89,45 @@ Most deep learning libraries are eager-first, meaning each op call directly oper
|
||||
|
||||
However, this isn't great for performance. What makes sense for a developer doesn't work well for the machine, in the same way that no one writes assembly by hand. Most libraries try to fix this problem by tacking on operator fusion or JIT compilation to try to change the compilation flow to something better for the machine. Turns out this is [super](https://docs.pytorch.org/docs/stable/torch.compiler_dynamo_overview.html) [difficult](https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html) [even](https://pytorch.org/docs/stable/jit.html) [for](https://pytorch.org/docs/stable/fx.html#torch.fx.symbolic_trace) Pytorch!
|
||||
|
||||
### What about XLA?
|
||||
|
||||
XLA, torch.compile, TVM, and other traditional compiler stacks suffer from complexity explosion. They are made up of a very large set of destructive (one-direction) rewrite rules that lower and optimize a graph from a high-level representation to low-level machine code. But since these rules are destructive, they are required to only fire when it's certian that there's a performance benefit. This leads to the rules becoming very complex, special-cased, and numerous. Once additional hardware backends, model architectures, and new dtypes get thrown in, they suffer from the weight of their complexity and often produce very suboptimal code, requiring DSLs like Pallas or Triton to regain performance.
|
||||
|
||||
### Compile everything
|
||||
|
||||
A core tenet of Luminal is ahead-of-time compilation. Whenever possible, push everything to compile time and leave nothing to run time. Luminal takes an approach more similar to [XLA](https://www.tensorflow.org/xla), and [tinygrad](https://github.com/tinygrad/tinygrad). Everything's static here. When you write out an expression like `x + y`, no actual computation happens. The operation is recorded to a directed acyclic computation graph for execution later. Only once `graph.execute()` is ran does the computation happen. _But isn't that just lazy execution?_ Yes it is! But in luminal **everything is done this way**. All neural networks are built up as one or a few static computation graphs, compiled, and executed later.
|
||||
A core tenet of Luminal is ahead-of-time compilation. Whenever possible, push everything to compile time and leave nothing to run time. Luminal takes an approach more similar to [XLA](https://www.tensorflow.org/xla), and [tinygrad](https://github.com/tinygrad/tinygrad). Everything's static here. When you write out an expression like `x + y`, no actual computation happens. The operation is recorded to a directed acyclic computation graph for execution later. Only once `graph.execute()` is ran does the computation happen. _But isn't that just lazy execution?_ Yes it is! But in luminal **everything is done this way**. All neural networks are built up as a static computation graphs, compiled, and executed later.
|
||||
|
||||
### First-class dynamism
|
||||
|
||||
A fully-static world would be nice, but we live in a world of nessecary dynamism. So we model dynamic shapes natively, as symbolic dimensions. Luminal supports arbitrary symbolic dimensions, including complex expressions, to give us shapes like `(s, 4096)`, `(b, h, w + 3)`, etc. This rich representation gives the compiler full visibility into shapes and lets it still do aggressive specialization.
|
||||
|
||||
**But why?**
|
||||
|
||||
A consequence of this is that the actual computation that gets ran can be radically different than the code that was written. Since we have an entire neural network fully represented in a compute graph, our compilers have global knowledge. This means we can push most ML complexity to the compilers. For instance, devices, datatypes, and execution schedules are all handled by compliers. Even autograd is handled by a compiler!
|
||||
A consequence of this is that the actual computation that gets ran can be radically different than the code that was written. Since we have an entire neural network fully represented in a compute graph, Luminal has global knowledge. This means we can push most ML complexity to the compiler. For instance, devices, datatypes, and even autograd is modeled ahead of time and optimized by the compiler!
|
||||
|
||||
Now we can do:
|
||||
|
||||
- Aggressive kernel fusion
|
||||
- Shape-specific kernels compiled at runtime
|
||||
- Devices and Dtypes are handled through compilers (just run the CUDA compiler to convert the graph to use CUDA kernels, then the fp16 compiler to convert to half-precision kernels)
|
||||
- Networks can be written in generic code, but compiled and ran fast on hyper-specific architectures (try writing a PyTorch network that works with both TF32 dtypes and TPUs; get ready for if statement hell...)
|
||||
- Low-precision dtypes (mxfp4, nvfp4, fp8, etc.)
|
||||
- Complex mutli-device parallelism topologies, searched ahead-of-time
|
||||
- Networks can be written in generic code, but compiled and ran fast on hyper-specific architectures
|
||||
|
||||
## Where are we?
|
||||
|
||||
- Search is partially merged. We are between 1.0 and 2.0 (search), which will be completed within the next month or so.
|
||||
- Metal and Cuda are supported for running models on Macs and Nvidia GPUs respectively, in both full and half precision.
|
||||
- Full training support with graph-based autograd.
|
||||
- Llama 3, Phi 3, Whisper and Yolo v8 are implemented in `examples/`. See instructions above for running.
|
||||
- Native PyTorch support
|
||||
- Many kernel libraries supported in the search space (FlashInfer, cuBLASLt, etc.)
|
||||
- Many models implemented in our Rust tensor API in `examples/`.
|
||||
- We have a small library of NN modules in `luminal_nn`, including transformers.
|
||||
- A significant amount of high-level ops are implemented in `hl_ops`. We are aiming to match the most used ~80% of the pytorch api.
|
||||
|
||||
Some things on the roadmap:
|
||||
|
||||
- Expand the search space to utilize Tensor Cores more flexibly
|
||||
- Bring cuda to parity with Metal
|
||||
- Add Blackwell intrinsics, such as TMEM and TMA
|
||||
- Build a ROCm backend
|
||||
- Build benchmarking suite to test against other libs
|
||||
- Distributed data, pipeline and tensor parallel.
|
||||
- Beat PT 2.0 perf on LLM inference _and_ training
|
||||
- More fine-grained dialects supporting thread- and warp-level intrinsics like TMA and tcgen.05
|
||||
- ROCm backend
|
||||
- More public infernce accelerator backends (coming very soon...)
|
||||
- Public benchmarking suite
|
||||
- Automatically searched model parallelism (TP, PP, EPS, EPR, SP, etc.)
|
||||
- Write compiler for quantum photonic retro encabulator
|
||||
- Build dyson swarm
|
||||
|
||||
|
||||
85
ci/example_output.py
Normal file
85
ci/example_output.py
Normal file
@@ -0,0 +1,85 @@
|
||||
import re
|
||||
|
||||
ANSI_ESCAPE = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]")
|
||||
|
||||
EXPECTED_OUTPUT = {
|
||||
"gemma4_moe": [
|
||||
"city of romance, art and culture",
|
||||
],
|
||||
"whisper": [
|
||||
"ask not what your country can do for you",
|
||||
],
|
||||
}
|
||||
|
||||
EXPECTED_CONCEPTS = {
|
||||
"llama": [
|
||||
["layers"],
|
||||
["neurons", "nodes"],
|
||||
["learn", "learning", "adapt"],
|
||||
["data", "patterns", "features"],
|
||||
],
|
||||
"gemma": [
|
||||
["neural network", "neural networks"],
|
||||
["nodes", "neurons"],
|
||||
["layers"],
|
||||
["weights"],
|
||||
["training", "learn", "learns"],
|
||||
],
|
||||
"qwen": [
|
||||
["neural network", "neural networks"],
|
||||
["computational model", "computational system"],
|
||||
["brain"],
|
||||
["layers"],
|
||||
["neurons", "nodes"],
|
||||
["learn", "learning", "training"],
|
||||
],
|
||||
"qwen3_moe": [
|
||||
["capital"],
|
||||
["france"],
|
||||
["paris"],
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def normalize_output(output: str) -> str:
|
||||
output = ANSI_ESCAPE.sub("", output)
|
||||
output = output.replace("\r", "\n")
|
||||
return re.sub(r"\s+", " ", output).casefold()
|
||||
|
||||
|
||||
def validate_output(example: str, output: str):
|
||||
normalized_output = normalize_output(output)
|
||||
|
||||
expected_concepts = EXPECTED_CONCEPTS.get(example)
|
||||
if expected_concepts is not None:
|
||||
missing = [
|
||||
concept_group
|
||||
for concept_group in expected_concepts
|
||||
if not any(normalize_output(term) in normalized_output for term in concept_group)
|
||||
]
|
||||
if missing:
|
||||
expected = "\n - ".join(" / ".join(group) for group in expected_concepts)
|
||||
missing_terms = "\n - ".join(" / ".join(group) for group in missing)
|
||||
raise AssertionError(
|
||||
f"Output check failed for {example!r}.\n"
|
||||
f"Expected concept groups:\n - {expected}\n"
|
||||
f"Missing concept groups:\n - {missing_terms}"
|
||||
)
|
||||
|
||||
expected = ", ".join(" / ".join(group) for group in expected_concepts)
|
||||
print(f"\nOutput check passed for {example!r}: found concepts {expected}")
|
||||
return
|
||||
|
||||
expected_phrases = EXPECTED_OUTPUT.get(example)
|
||||
if expected_phrases is None:
|
||||
raise ValueError(f"No expected output phrases configured for example {example!r}")
|
||||
|
||||
for phrase in expected_phrases:
|
||||
if normalize_output(phrase) in normalized_output:
|
||||
print(f"\nOutput check passed for {example!r}: found {phrase!r}")
|
||||
return
|
||||
|
||||
expected = "\n - ".join(expected_phrases)
|
||||
raise AssertionError(
|
||||
f"Output check failed for {example!r}. Expected one of:\n - {expected}"
|
||||
)
|
||||
185
ci/examples_perf.py
Normal file
185
ci/examples_perf.py
Normal file
@@ -0,0 +1,185 @@
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from example_output import validate_output
|
||||
|
||||
|
||||
DEFAULT_EXAMPLES = ["llama", "gemma", "qwen", "qwen3_moe", "gemma4_moe", "whisper"]
|
||||
|
||||
EXAMPLE_CARGO_ARGS = {
|
||||
"llama": ["run", "--release", "-p", "llama"],
|
||||
"gemma": ["run", "--release", "-p", "gemma"],
|
||||
"qwen": ["run", "--release", "-p", "qwen", "--features", "cuda"],
|
||||
"qwen3_moe": ["run", "--release", "-p", "qwen3_moe"],
|
||||
"gemma4_moe": ["run", "--release", "-p", "gemma4_moe"],
|
||||
"whisper": ["run", "--release", "-p", "whisper"],
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Metrics:
|
||||
ttft_ms: float | None = None
|
||||
tpot_ms: float | None = None
|
||||
tps: float | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExampleResult:
|
||||
name: str
|
||||
ok: bool
|
||||
metrics: Metrics = field(default_factory=Metrics)
|
||||
wall_s: float = 0.0
|
||||
error: str | None = None
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = [arg for arg in sys.argv[1:] if arg != "--"]
|
||||
if any(arg in {"-h", "--help"} for arg in args):
|
||||
print_help()
|
||||
return
|
||||
if "--list" in args:
|
||||
print("\n".join(DEFAULT_EXAMPLES))
|
||||
return
|
||||
|
||||
examples = args or DEFAULT_EXAMPLES
|
||||
results = [run_example(example) for example in examples]
|
||||
print_table(results)
|
||||
if any(not result.ok for result in results):
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
def print_help() -> None:
|
||||
print(
|
||||
"Run validated Luminal examples, validate textual output, and summarize perf.\n"
|
||||
"\n"
|
||||
"Usage:\n"
|
||||
" cargo examples\n"
|
||||
" cargo examples llama qwen whisper\n"
|
||||
"\n"
|
||||
"Options:\n"
|
||||
" --list Print the default validated examples\n"
|
||||
" -h, --help\n"
|
||||
"\n"
|
||||
f"The default set matches the Modal examples CI: {', '.join(DEFAULT_EXAMPLES)}."
|
||||
)
|
||||
|
||||
|
||||
def run_example(example: str) -> ExampleResult:
|
||||
cargo_args = EXAMPLE_CARGO_ARGS.get(example)
|
||||
if cargo_args is None:
|
||||
known = ", ".join(DEFAULT_EXAMPLES)
|
||||
return ExampleResult(example, False, error=f"unknown example; known examples: {known}")
|
||||
|
||||
print(f"\n=== Running {example} ===")
|
||||
print(f"$ cargo {' '.join(cargo_args)}")
|
||||
started = time.monotonic()
|
||||
env = os.environ.copy()
|
||||
env.setdefault("CUDARC_CUDA_VERSION", "12080")
|
||||
process = subprocess.Popen(
|
||||
["cargo", *cargo_args],
|
||||
cwd=repo_root(),
|
||||
env=env,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
)
|
||||
assert process.stdout is not None
|
||||
|
||||
chunks: list[bytes] = []
|
||||
while True:
|
||||
chunk = process.stdout.read1(4096)
|
||||
if not chunk:
|
||||
break
|
||||
sys.stdout.buffer.write(chunk)
|
||||
sys.stdout.buffer.flush()
|
||||
chunks.append(chunk)
|
||||
|
||||
return_code = process.wait()
|
||||
output = b"".join(chunks).decode("utf-8", errors="replace")
|
||||
wall_s = time.monotonic() - started
|
||||
metrics = parse_metrics(output)
|
||||
|
||||
if return_code:
|
||||
return ExampleResult(
|
||||
example,
|
||||
False,
|
||||
metrics=metrics,
|
||||
wall_s=wall_s,
|
||||
error=f"process exited with code {return_code}",
|
||||
)
|
||||
|
||||
try:
|
||||
validate_output(example, output)
|
||||
except Exception as exc:
|
||||
return ExampleResult(example, False, metrics=metrics, wall_s=wall_s, error=str(exc))
|
||||
|
||||
return ExampleResult(example, True, metrics=metrics, wall_s=wall_s)
|
||||
|
||||
|
||||
def repo_root() -> str:
|
||||
return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
|
||||
def parse_metrics(output: str) -> Metrics:
|
||||
metrics = Metrics()
|
||||
for line in output.splitlines():
|
||||
if "TTFT:" in line:
|
||||
metrics.ttft_ms = parse_number_after(line, "TTFT:")
|
||||
if "TPOT:" in line:
|
||||
metrics.tpot_ms = parse_number_after(line, "TPOT:")
|
||||
if "tok/s" in line:
|
||||
metrics.tps = parse_tok_per_second(line)
|
||||
if metrics.tps is None and metrics.tpot_ms:
|
||||
metrics.tps = 1000.0 / metrics.tpot_ms
|
||||
return metrics
|
||||
|
||||
|
||||
def parse_number_after(line: str, marker: str) -> float | None:
|
||||
tail = line.split(marker, 1)[1].lstrip()
|
||||
chars = []
|
||||
for char in tail:
|
||||
if char.isdigit() or char == ".":
|
||||
chars.append(char)
|
||||
else:
|
||||
break
|
||||
if not chars:
|
||||
return None
|
||||
return float("".join(chars))
|
||||
|
||||
|
||||
def parse_tok_per_second(line: str) -> float | None:
|
||||
head = line.split("tok/s", 1)[0].rstrip(" (")
|
||||
parts = head.split()
|
||||
if not parts:
|
||||
return None
|
||||
try:
|
||||
return float(parts[-1])
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def print_table(results: list[ExampleResult]) -> None:
|
||||
print("\nSummary")
|
||||
print(f"{'example':<14} {'status':<8} {'TTFT ms':>10} {'TPOT ms':>10} {'tok/s':>10} {'wall s':>10}")
|
||||
print("-" * 68)
|
||||
for result in results:
|
||||
status = "ok" if result.ok else "failed"
|
||||
print(
|
||||
f"{result.name:<14} {status:<8} "
|
||||
f"{format_metric(result.metrics.ttft_ms):>10} "
|
||||
f"{format_metric(result.metrics.tpot_ms):>10} "
|
||||
f"{format_metric(result.metrics.tps):>10} "
|
||||
f"{result.wall_s:>10.1f}"
|
||||
)
|
||||
if result.error:
|
||||
print(f" error: {result.error}")
|
||||
|
||||
|
||||
def format_metric(value: float | None) -> str:
|
||||
return "-" if value is None else f"{value:.2f}"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
48
ci/metal_llama_1b_example.py
Normal file
48
ci/metal_llama_1b_example.py
Normal file
@@ -0,0 +1,48 @@
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
def run_and_capture(command: list[str], *, cwd: str, env: dict[str, str]) -> str:
|
||||
process = subprocess.Popen(
|
||||
command,
|
||||
cwd=cwd,
|
||||
env=env,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
)
|
||||
assert process.stdout is not None
|
||||
|
||||
chunks = []
|
||||
while True:
|
||||
chunk = process.stdout.read1(4096)
|
||||
if not chunk:
|
||||
break
|
||||
sys.stdout.buffer.write(chunk)
|
||||
sys.stdout.buffer.flush()
|
||||
chunks.append(chunk)
|
||||
|
||||
return_code = process.wait()
|
||||
output = b"".join(chunks).decode("utf-8", errors="replace")
|
||||
if return_code:
|
||||
raise subprocess.CalledProcessError(return_code, command, output=output)
|
||||
return output
|
||||
|
||||
|
||||
def main():
|
||||
repo_root = os.environ.get("GITHUB_WORKSPACE", os.getcwd())
|
||||
sys.path.insert(0, os.path.join(repo_root, "ci"))
|
||||
from example_output import validate_output
|
||||
|
||||
output = run_and_capture(
|
||||
["cargo", "run", "--release", "-p", "luminal_metal", "--example", "llama_1b"],
|
||||
cwd=repo_root,
|
||||
env=os.environ.copy(),
|
||||
)
|
||||
if "TTFT:" not in output or "TPOT:" not in output:
|
||||
raise AssertionError("Llama 1B Metal example did not complete generation")
|
||||
validate_output("llama", output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
46
ci/metal_qwen_example.py
Normal file
46
ci/metal_qwen_example.py
Normal file
@@ -0,0 +1,46 @@
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from example_output import validate_output
|
||||
|
||||
def run_and_capture(command: list[str], *, cwd: str, env: dict[str, str]) -> str:
|
||||
process = subprocess.Popen(
|
||||
command,
|
||||
cwd=cwd,
|
||||
env=env,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
)
|
||||
assert process.stdout is not None
|
||||
|
||||
chunks = []
|
||||
while True:
|
||||
chunk = process.stdout.read1(4096)
|
||||
if not chunk:
|
||||
break
|
||||
sys.stdout.buffer.write(chunk)
|
||||
sys.stdout.buffer.flush()
|
||||
chunks.append(chunk)
|
||||
|
||||
return_code = process.wait()
|
||||
output = b"".join(chunks).decode("utf-8", errors="replace")
|
||||
if return_code:
|
||||
raise subprocess.CalledProcessError(return_code, command, output=output)
|
||||
return output
|
||||
|
||||
|
||||
def main():
|
||||
repo_root = os.environ.get("GITHUB_WORKSPACE", os.getcwd())
|
||||
output = run_and_capture(
|
||||
["cargo", "run", "--release", "-p", "qwen", "--features", "metal"],
|
||||
cwd=repo_root,
|
||||
env=os.environ.copy(),
|
||||
)
|
||||
if "TTFT:" not in output or "TPOT:" not in output:
|
||||
raise AssertionError("qwen Metal example did not complete generation")
|
||||
validate_output("qwen", output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,8 +1,10 @@
|
||||
import modal
|
||||
import subprocess
|
||||
import os
|
||||
import shlex
|
||||
|
||||
gpu_type = os.environ.get("GPU_TYPE", "T4")
|
||||
modal_timeout = int(os.environ.get("MODAL_TIMEOUT", "7200"))
|
||||
CUDARC_CUDA_VERSION = "12080"
|
||||
|
||||
app = modal.App("luminal-ci-cargo-test")
|
||||
@@ -28,7 +30,7 @@ cuda_image = (
|
||||
@app.function(
|
||||
image=cuda_image,
|
||||
gpu=gpu_type,
|
||||
timeout=1800, # 30 minutes
|
||||
timeout=modal_timeout,
|
||||
)
|
||||
def run_cargo_test():
|
||||
"""Run cargo test for luminal_cuda_lite on a Modal GPU."""
|
||||
@@ -43,16 +45,20 @@ def run_cargo_test():
|
||||
)
|
||||
compute_cap = result.stdout.strip().replace(".", "")
|
||||
|
||||
test_args = shlex.split(os.environ.get("CARGO_TEST_ARGS", "--test-threads=1"))
|
||||
cmd = [
|
||||
"cargo",
|
||||
"test",
|
||||
"--release",
|
||||
"-p",
|
||||
"luminal_cuda_lite",
|
||||
"--verbose",
|
||||
"--",
|
||||
*test_args,
|
||||
]
|
||||
print("Running:", " ".join(cmd), flush=True)
|
||||
subprocess.run(
|
||||
[
|
||||
"cargo",
|
||||
"test",
|
||||
"-p",
|
||||
"luminal_cuda_lite",
|
||||
"--verbose",
|
||||
"--",
|
||||
"--test-threads=1",
|
||||
],
|
||||
cmd,
|
||||
cwd=WORKDIR,
|
||||
env={
|
||||
**os.environ,
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
@@ -21,28 +20,8 @@ hf_cache = modal.Volume.from_name(
|
||||
|
||||
WORKDIR = "/workspace/luminal"
|
||||
|
||||
ANSI_ESCAPE = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]")
|
||||
|
||||
EXPECTED_OUTPUT = {
|
||||
"llama": [
|
||||
"complex system modeled after the structure and function of the human brain",
|
||||
],
|
||||
"gemma": [
|
||||
"recognize pictures of cats",
|
||||
"little detectives looking for specific features",
|
||||
],
|
||||
"qwen": [
|
||||
"computational model inspired by the structure and function of the human brain",
|
||||
],
|
||||
"qwen3_moe": [
|
||||
"The capital of France is Paris",
|
||||
],
|
||||
"gemma4_moe": [
|
||||
"city of romance, art and culture",
|
||||
],
|
||||
"whisper": [
|
||||
"ask not what your country can do for you",
|
||||
],
|
||||
EXAMPLE_CARGO_ARGS = {
|
||||
"qwen": ["--features", "cuda"],
|
||||
}
|
||||
|
||||
|
||||
@@ -72,28 +51,6 @@ def run_and_capture(command: list[str], *, cwd: str, env: dict[str, str]) -> str
|
||||
return output
|
||||
|
||||
|
||||
def normalize_output(output: str) -> str:
|
||||
output = ANSI_ESCAPE.sub("", output)
|
||||
output = output.replace("\r", "\n")
|
||||
return re.sub(r"\s+", " ", output).casefold()
|
||||
|
||||
|
||||
def validate_output(example: str, output: str):
|
||||
expected_phrases = EXPECTED_OUTPUT.get(example)
|
||||
if expected_phrases is None:
|
||||
raise ValueError(f"No expected output phrases configured for example {example!r}")
|
||||
|
||||
normalized_output = normalize_output(output)
|
||||
for phrase in expected_phrases:
|
||||
if normalize_output(phrase) in normalized_output:
|
||||
print(f"\nOutput check passed for {example!r}: found {phrase!r}")
|
||||
return
|
||||
|
||||
expected = "\n - ".join(expected_phrases)
|
||||
raise AssertionError(
|
||||
f"Output check failed for {example!r}. Expected one of:\n - {expected}"
|
||||
)
|
||||
|
||||
cuda_image = (
|
||||
modal.Image.from_registry(
|
||||
"nvcr.io/nvidia/pytorch:25.03-py3"
|
||||
@@ -115,7 +72,7 @@ cuda_image = (
|
||||
@app.function(
|
||||
image=cuda_image,
|
||||
gpu=gpu_type,
|
||||
timeout=3600, # 60 minutes
|
||||
timeout=7200, # 2 hours
|
||||
volumes={
|
||||
HF_CACHE_PATH: hf_cache,
|
||||
},
|
||||
@@ -123,6 +80,8 @@ cuda_image = (
|
||||
def run_example(example: str):
|
||||
"""Build and run a luminal example on a Modal GPU."""
|
||||
subprocess.run(["nvidia-smi"], check=True)
|
||||
sys.path.insert(0, f"{WORKDIR}/ci")
|
||||
from example_output import validate_output
|
||||
|
||||
run_env = {
|
||||
**os.environ,
|
||||
@@ -130,7 +89,7 @@ def run_example(example: str):
|
||||
"HF_HOME": HF_CACHE_PATH,
|
||||
}
|
||||
output = run_and_capture(
|
||||
["cargo", "run", "--release"],
|
||||
["cargo", "run", "--release", *EXAMPLE_CARGO_ARGS.get(example, [])],
|
||||
cwd=f"{WORKDIR}/examples/{example}",
|
||||
env=run_env,
|
||||
)
|
||||
|
||||
@@ -39,7 +39,7 @@ fn run_metal_pattern_benchmark(
|
||||
let mut cx = Graph::default();
|
||||
pattern.build_graph(&mut cx, *size);
|
||||
|
||||
cx.build_search_space::<MetalRuntime>();
|
||||
cx.build_search_space::<MetalRuntime>(CompileOptions::default());
|
||||
let mut rt = MetalRuntime::initialize(());
|
||||
|
||||
let mut rng = rand::rng();
|
||||
@@ -50,7 +50,7 @@ fn run_metal_pattern_benchmark(
|
||||
}
|
||||
}
|
||||
|
||||
let mut rt = cx.search(rt, 5);
|
||||
let mut rt = cx.search(rt, CompileOptions::new(5));
|
||||
rt.allocate_intermediate_buffers(&cx.dyn_map);
|
||||
|
||||
let mut bench_metrics = None;
|
||||
|
||||
@@ -41,7 +41,7 @@ struct PreparedBench {
|
||||
|
||||
#[cfg(feature = "metal")]
|
||||
fn prepare_and_search(cx: &mut Graph, input_sizes: &[(NodeIndex, usize)]) -> Option<PreparedBench> {
|
||||
cx.build_search_space::<MetalRuntime>();
|
||||
cx.build_search_space::<MetalRuntime>(CompileOptions::default());
|
||||
let mut rt = MetalRuntime::initialize(());
|
||||
|
||||
let mut rng = rand::rng();
|
||||
@@ -50,7 +50,7 @@ fn prepare_and_search(cx: &mut Graph, input_sizes: &[(NodeIndex, usize)]) -> Opt
|
||||
rt.set_data(*node, &data);
|
||||
}
|
||||
|
||||
let rt = cx.search(rt, 5);
|
||||
let rt = cx.search(rt, CompileOptions::new(5));
|
||||
|
||||
Some(PreparedBench {
|
||||
rt,
|
||||
|
||||
@@ -41,7 +41,7 @@ mod metal_backend {
|
||||
const NAME: &'static str = "Metal";
|
||||
|
||||
fn build_search_space(cx: &mut Graph) {
|
||||
cx.build_search_space::<MetalRuntime>();
|
||||
cx.build_search_space::<MetalRuntime>(CompileOptions::default());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,8 @@ license = "MIT OR Apache-2.0"
|
||||
[dependencies]
|
||||
luminal = { path = "../.." }
|
||||
luminal_tracing = { path = "../luminal_tracing" }
|
||||
cudarc = {version="0.18.2", features=["cuda-version-from-build-system", "fallback-latest"]}
|
||||
cudarc = {version="0.19.4", features=["cuda-version-from-build-system", "fallback-latest"]}
|
||||
anyhow = "1.0"
|
||||
as-any = "0.3.2"
|
||||
itertools = "0.12.1"
|
||||
fixedbitset = "0.5.7"
|
||||
@@ -23,10 +24,12 @@ memmap2 = "0.9.9"
|
||||
uuid = {version="1.19.0", features=["v4"]}
|
||||
lru = "0.16.2"
|
||||
libc = "0.2"
|
||||
libloading = "0.8"
|
||||
colorize = "*"
|
||||
|
||||
[dev-dependencies]
|
||||
candle-core = { version = "0.9.2", features = ["cuda"] }
|
||||
luminal_nn = { path = "../luminal_nn" }
|
||||
proptest = "1.9.0"
|
||||
rand = "0.9.2"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
|
||||
@@ -231,7 +231,9 @@ fn build_qwen_moe(cx: &mut Graph) -> GraphTensor {
|
||||
.unsqueeze(2)
|
||||
.matmul(down_gathered.transpose(2, 3))
|
||||
.squeeze(2);
|
||||
(down_out * top_k_values.unsqueeze(top_k_values.dims().len())).sum(n - 1)
|
||||
let mut weights_exp = top_k_values.unsqueeze(top_k_values.dims().len());
|
||||
weights_exp.shape.expand(down_out.dims());
|
||||
(down_out * weights_exp).sum(n - 1)
|
||||
}
|
||||
|
||||
fn build_gemma_moe(cx: &mut Graph) -> GraphTensor {
|
||||
@@ -278,7 +280,9 @@ fn build_gemma_moe(cx: &mut Graph) -> GraphTensor {
|
||||
.unsqueeze(2)
|
||||
.matmul(down_gathered.transpose(2, 3))
|
||||
.squeeze(2);
|
||||
(down_out * top_k_weights.unsqueeze(top_k_weights.dims().len())).sum(n - 1)
|
||||
let mut weights_exp = top_k_weights.unsqueeze(top_k_weights.dims().len());
|
||||
weights_exp.shape.expand(down_out.dims());
|
||||
(down_out * weights_exp).sum(n - 1)
|
||||
}
|
||||
|
||||
fn gather_experts(
|
||||
|
||||
@@ -29,9 +29,21 @@ impl DynBackend for CudaLiteDynBackend {
|
||||
fn get_output_f32(&self, node: NodeIndex) -> Vec<f32> {
|
||||
self.runtime.get_f32(node)
|
||||
}
|
||||
fn get_output_f16(&self, node: NodeIndex) -> Vec<half::f16> {
|
||||
self.runtime.get_f16(node)
|
||||
}
|
||||
fn get_output_bf16(&self, node: NodeIndex) -> Vec<half::bf16> {
|
||||
self.runtime.get_bf16(node)
|
||||
}
|
||||
fn get_output_i32(&self, node: NodeIndex) -> Vec<i32> {
|
||||
self.runtime.get_i32(node)
|
||||
}
|
||||
fn get_output_i64(&self, node: NodeIndex) -> Vec<i64> {
|
||||
self.runtime.get_i64(node)
|
||||
}
|
||||
fn get_output_f64(&self, node: NodeIndex) -> Vec<f64> {
|
||||
self.runtime.get_f64(node)
|
||||
}
|
||||
fn get_output_bool(&self, node: NodeIndex) -> Vec<bool> {
|
||||
self.runtime.get_bool(node)
|
||||
}
|
||||
|
||||
@@ -1,258 +0,0 @@
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
use luminal::{
|
||||
egglog_utils::{
|
||||
api::{Rule, SortDef, sort},
|
||||
base::{EXPRESSION, OP_KIND, STRING},
|
||||
extract_expr,
|
||||
},
|
||||
op::{EgglogOp, LLIROp},
|
||||
prelude::{
|
||||
tracing::{Level, span, trace},
|
||||
*,
|
||||
},
|
||||
};
|
||||
|
||||
use crate::{
|
||||
cudarc::{
|
||||
cublas::{
|
||||
CudaBlas,
|
||||
sys::{cublasOperation_t, cublasSetStream_v2, cublasSgemm_v2, cublasStatus_t},
|
||||
},
|
||||
driver::{CudaSlice, CudaStream, DevicePtr},
|
||||
},
|
||||
host::HostOp,
|
||||
};
|
||||
|
||||
/// Global shared cuBLAS handle to avoid per-operation workspace allocation
|
||||
static SHARED_CUBLAS: OnceLock<Arc<CudaBlas>> = OnceLock::new();
|
||||
|
||||
/// Parse cuBLAS operation from egglog string (e.g., "\"T\"" -> CUBLAS_OP_T)
|
||||
pub fn parse_cublas_op(s: &str) -> cublasOperation_t {
|
||||
// Strip quotes if present (egglog strings are stored with quotes)
|
||||
let stripped = s.trim_matches('"');
|
||||
match stripped {
|
||||
"T" => cublasOperation_t::CUBLAS_OP_T,
|
||||
"N" => cublasOperation_t::CUBLAS_OP_N,
|
||||
"C" => cublasOperation_t::CUBLAS_OP_C,
|
||||
other => panic!("Unknown cuBLAS operation: '{other}' (original: '{s}')"),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[allow(dead_code)]
|
||||
pub struct CuBlasSgemmV2 {
|
||||
m: Expression,
|
||||
n: Expression,
|
||||
k: Expression,
|
||||
a_layout: cublasOperation_t,
|
||||
b_layout: cublasOperation_t,
|
||||
lda: Expression,
|
||||
ldb: Expression,
|
||||
ldc: Expression,
|
||||
/// Lazily initialized cuBLAS handle - created on first execute
|
||||
cublas: OnceLock<Arc<CudaBlas>>,
|
||||
}
|
||||
|
||||
// Useless default for IntoEgglogOp
|
||||
impl Default for CuBlasSgemmV2 {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
m: Expression::default(),
|
||||
n: Expression::default(),
|
||||
k: Expression::default(),
|
||||
a_layout: cublasOperation_t::CUBLAS_OP_N, // IGNORE NOT REAL
|
||||
b_layout: cublasOperation_t::CUBLAS_OP_T, // IGNORE NOT REAL
|
||||
lda: Expression::default(),
|
||||
ldb: Expression::default(),
|
||||
ldc: Expression::default(),
|
||||
cublas: OnceLock::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EgglogOp for CuBlasSgemmV2 {
|
||||
fn sort(&self) -> SortDef {
|
||||
sort(
|
||||
OP_KIND,
|
||||
"cublasSgemmV2",
|
||||
&[
|
||||
("m", EXPRESSION),
|
||||
("n", EXPRESSION),
|
||||
("k", EXPRESSION),
|
||||
("a_layout", STRING),
|
||||
("b_layout", STRING),
|
||||
("lda", EXPRESSION),
|
||||
("ldb", EXPRESSION),
|
||||
("ldc", EXPRESSION),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
fn n_inputs(&self) -> usize {
|
||||
2
|
||||
}
|
||||
|
||||
fn rewrites(&self) -> Vec<Rule> {
|
||||
vec![
|
||||
Rule::raw(include_str!["sgemm_v2_RmRm_rewrite.egg"]), // row row
|
||||
Rule::raw(include_str!["sgemm_v2_RmCm_rewrite.egg"]), // row col
|
||||
Rule::raw(include_str!["sgemm_v2_CmRm_rewrite.egg"]), // col row
|
||||
Rule::raw(include_str!["sgemm_v2_CmCm_rewrite.egg"]), // col col
|
||||
]
|
||||
}
|
||||
|
||||
#[allow(unused_variables)]
|
||||
fn extract<'a>(
|
||||
&'a self,
|
||||
egraph: &'a luminal::egglog_utils::SerializedEGraph,
|
||||
kind_children: &[&'a ENodeId],
|
||||
input_enodes: Vec<&'a ENodeId>,
|
||||
list_cache: &mut FxHashMap<&'a ENodeId, Vec<Expression>>,
|
||||
expr_cache: &mut FxHashMap<&'a ENodeId, Expression>,
|
||||
) -> (LLIROp, Vec<&'a ENodeId>) {
|
||||
// Extract dimensions from egglog
|
||||
let m = extract_expr(egraph, kind_children[0], expr_cache).unwrap();
|
||||
let n = extract_expr(egraph, kind_children[1], expr_cache).unwrap();
|
||||
let k = extract_expr(egraph, kind_children[2], expr_cache).unwrap();
|
||||
|
||||
// Extract layout strings from egglog
|
||||
let a_layout_str = &egraph.enodes[kind_children[3]].0;
|
||||
let b_layout_str = &egraph.enodes[kind_children[4]].0;
|
||||
let a_layout = parse_cublas_op(a_layout_str);
|
||||
let b_layout = parse_cublas_op(b_layout_str);
|
||||
|
||||
// Extract leading dimensions from egglog
|
||||
let lda = extract_expr(egraph, kind_children[5], expr_cache).unwrap();
|
||||
let ldb = extract_expr(egraph, kind_children[6], expr_cache).unwrap();
|
||||
let ldc = extract_expr(egraph, kind_children[7], expr_cache).unwrap();
|
||||
|
||||
let extracted_state = Self {
|
||||
m,
|
||||
n,
|
||||
k,
|
||||
a_layout,
|
||||
b_layout,
|
||||
lda,
|
||||
ldb,
|
||||
ldc,
|
||||
cublas: OnceLock::new(),
|
||||
};
|
||||
trace!(?extracted_state);
|
||||
|
||||
let extracted = LLIROp::new::<dyn HostOp>(Box::new(extracted_state) as Box<dyn HostOp>);
|
||||
|
||||
(extracted, input_enodes)
|
||||
}
|
||||
|
||||
fn cleanup(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
impl HostOp for CuBlasSgemmV2 {
|
||||
fn execute(
|
||||
&self,
|
||||
stream: &Arc<CudaStream>,
|
||||
self_node: NodeIndex,
|
||||
inputs: &[NodeIndex],
|
||||
buffers: &FxHashMap<NodeIndex, &CudaSlice<u8>>,
|
||||
dyn_map: &FxHashMap<char, usize>,
|
||||
) -> anyhow::Result<()> {
|
||||
// GEMM parameters
|
||||
let m = self.m.exec(dyn_map).unwrap() as i32;
|
||||
let n = self.n.exec(dyn_map).unwrap() as i32;
|
||||
let k = self.k.exec(dyn_map).unwrap() as i32;
|
||||
let a_layout = self.a_layout;
|
||||
let b_layout = self.b_layout;
|
||||
let lda = self.lda.exec(dyn_map).unwrap() as i32;
|
||||
let ldb = self.ldb.exec(dyn_map).unwrap() as i32;
|
||||
let ldc = self.ldc.exec(dyn_map).unwrap() as i32;
|
||||
|
||||
let alpha = 1.0f32;
|
||||
let beta = 0.0f32;
|
||||
|
||||
// Get buffers: output is self_node, inputs are from graph edges
|
||||
let c_buf = buffers[&self_node];
|
||||
let a_buf = buffers[&inputs[0]];
|
||||
let b_buf = buffers[&inputs[1]];
|
||||
|
||||
// Get device pointers
|
||||
let (a_ptr, _a_guard) = a_buf.device_ptr(stream);
|
||||
let (b_ptr, _b_guard) = b_buf.device_ptr(stream);
|
||||
let (c_ptr, _c_guard) = c_buf.device_ptr(stream);
|
||||
|
||||
// Debug: Check buffer sizes
|
||||
trace!(
|
||||
"buffer_validation {}=={},{}=={},{}=={}",
|
||||
a_buf.len(),
|
||||
m * k * 4,
|
||||
b_buf.len(),
|
||||
k * n * 4,
|
||||
c_buf.len(),
|
||||
m * n * 4
|
||||
);
|
||||
let _sgemm_span = span!(
|
||||
Level::TRACE,
|
||||
"cuBLAS_SGEMM_V2",
|
||||
m,
|
||||
n,
|
||||
k,
|
||||
alpha,
|
||||
beta,
|
||||
lda,
|
||||
ldb,
|
||||
ldc,
|
||||
?a_layout,
|
||||
?b_layout,
|
||||
)
|
||||
.entered();
|
||||
|
||||
// Use shared cuBLAS handle to avoid per-operation workspace allocation
|
||||
let cublas = SHARED_CUBLAS.get_or_init(|| Arc::new(CudaBlas::new(stream.clone()).unwrap()));
|
||||
|
||||
// Set the stream for this operation (cuBLAS handle can work with any stream)
|
||||
// The CUstream types from cublas::sys and driver::sys are compatible, just cast
|
||||
unsafe {
|
||||
cublasSetStream_v2(*cublas.handle(), stream.cu_stream() as _);
|
||||
}
|
||||
|
||||
let status = unsafe {
|
||||
cublasSgemm_v2(
|
||||
*cublas.handle(),
|
||||
a_layout,
|
||||
b_layout,
|
||||
m,
|
||||
n,
|
||||
k,
|
||||
&alpha as *const f32,
|
||||
a_ptr as *const f32,
|
||||
lda,
|
||||
b_ptr as *const f32,
|
||||
ldb,
|
||||
&beta as *const f32,
|
||||
c_ptr as *mut f32,
|
||||
ldc,
|
||||
)
|
||||
};
|
||||
stream.synchronize().unwrap();
|
||||
|
||||
if status != cublasStatus_t::CUBLAS_STATUS_SUCCESS {
|
||||
return Err(anyhow::anyhow!(
|
||||
"cuBLAS SGEMM TN failed with status: {:?}",
|
||||
status
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn output_size(&self) -> Expression {
|
||||
self.m * self.n
|
||||
}
|
||||
|
||||
fn output_bytes(&self) -> Expression {
|
||||
// CuBlasSgemmV2 is F32 only (Sgemm = Single precision)
|
||||
self.output_size() * 4
|
||||
}
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
; Column-major × Column-major matmul: C[m,n] = A[m,k] × B[k,n]
|
||||
; A[m,k] column-major → expand to [m, n, k] with strides [1, 0, m]
|
||||
; B[k,n] column-major → expand to [m, n, k] with strides [0, k, 1]
|
||||
;
|
||||
; Row-major viewed as column-major (swap trick):
|
||||
; Column-major A[m,k] is already column-major with lda=m
|
||||
; Column-major B[k,n] is already column-major with ldb=k
|
||||
; Row-major C[m,n] ≡ column-major C^T[n,m] with ldc=n
|
||||
;
|
||||
; C^T[n,m] = (A × B)^T = B^T[n,k] × A^T[k,m]
|
||||
; cuBLAS: cublasSgemm(OP_T, OP_T, n, m, k, α, B, k, A, m, β, C, n)
|
||||
(rule
|
||||
(
|
||||
; Match Mul node
|
||||
(= ?mul (Op (Mul ?mul_shape ?a_stride ?b_stride ?mul_out_stride) (ICons ?a (ICons ?b (INil)))))
|
||||
|
||||
; Match Sum that reduces the Mul (k dimension)
|
||||
(= ?sum (Op (Sum ?out_shape ?k ?sum_in_stride ?k_stride ?sum_out_stride) (ICons ?mul (INil))))
|
||||
|
||||
; Must be exactly 2D (no batch dims) — batched matmul uses CuBlasLt
|
||||
(= (len ?out_shape) 2)
|
||||
|
||||
; Get dimensions from output shape
|
||||
(= ?m (nth_from_end ?out_shape 1))
|
||||
(= ?n (nth_from_end ?out_shape 0))
|
||||
(!= ?m (MNum 0))
|
||||
(!= ?n (MNum 0))
|
||||
|
||||
; Get A strides in [m, n, k] space
|
||||
(= ?a_m_stride (nth_from_end ?a_stride 2))
|
||||
(= ?a_n_stride (nth_from_end ?a_stride 1))
|
||||
(= ?a_k_stride (nth_from_end ?a_stride 0))
|
||||
|
||||
; Get B strides in [m, n, k] space
|
||||
(= ?b_m_stride (nth_from_end ?b_stride 2))
|
||||
(= ?b_n_stride (nth_from_end ?b_stride 1))
|
||||
(= ?b_k_stride (nth_from_end ?b_stride 0))
|
||||
|
||||
; Assert contiguous k stride on output (required for reduction)
|
||||
(= ?k_stride (MIter))
|
||||
|
||||
; Assert A has strides [1, 0, m] (column-major A[m,k] broadcast to [m,n,k])
|
||||
(= ?a_m_stride (MIter))
|
||||
(= ?a_n_stride (MNum 0))
|
||||
(= ?a_k_stride (MMul (MIter) ?m))
|
||||
|
||||
; Assert B has strides [0, k, 1] (column-major B[k,n] broadcast to [m,n,k])
|
||||
(= ?b_m_stride (MNum 0))
|
||||
(= ?b_n_stride (MMul (MIter) ?k))
|
||||
(= ?b_k_stride (MIter))
|
||||
|
||||
(= (F32) (dtype ?a))
|
||||
(= (F32) (dtype ?b))
|
||||
)
|
||||
(
|
||||
; For column-major A × column-major B with cuBLAS:
|
||||
; C^T = B^T × A^T → cublasSgemm(OP_T, OP_T, n, m, k, α, B, k, A, m, β, C, n)
|
||||
(let ?sgemm (Op (cublasSgemmV2
|
||||
?n ; cuBLAS m = our n (swapped)
|
||||
?m ; cuBLAS n = our m (swapped)
|
||||
?k ; k unchanged
|
||||
"T" ; transa = Transpose (B is column-major [k,n], need B^T[n,k])
|
||||
"T" ; transb = Transpose (A is column-major [m,k], need A^T[k,m])
|
||||
?k ; lda = k (column-major B[k,n])
|
||||
?m ; ldb = m (column-major A[m,k])
|
||||
?n) ; ldc = n (row-major C[m,n] viewed as col-major [n,m])
|
||||
(ICons ?b (ICons ?a (INil)))))
|
||||
(union ?sum ?sgemm)
|
||||
(set (dtype ?sgemm) (F32))
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublas sgemm column-major × column-major"
|
||||
)
|
||||
@@ -1,73 +0,0 @@
|
||||
; Column-major × Row-major matmul: C[m,n] = A[m,k] × B[k,n]
|
||||
; A[m,k] column-major → expand to [m, n, k] with strides [1, 0, m]
|
||||
; B[k,n] row-major → permute to [n,k] then expand to [m, n, k] with strides [0, 1, n]
|
||||
;
|
||||
; Row-major viewed as column-major (swap trick):
|
||||
; Column-major A[m,k] is already column-major with lda=m
|
||||
; Row-major B[k,n] ≡ column-major B^T[n,k] with ldb=n
|
||||
; Row-major C[m,n] ≡ column-major C^T[n,m] with ldc=n
|
||||
;
|
||||
; C^T[n,m] = (A × B)^T = B^T[n,k] × A^T[k,m]
|
||||
; cuBLAS: cublasSgemm(OP_N, OP_T, n, m, k, α, B, n, A, m, β, C, n)
|
||||
(rule
|
||||
(
|
||||
; Match Mul node
|
||||
(= ?mul (Op (Mul ?mul_shape ?a_stride ?b_stride ?mul_out_stride) (ICons ?a (ICons ?b (INil)))))
|
||||
|
||||
; Match Sum that reduces the Mul (k dimension)
|
||||
(= ?sum (Op (Sum ?out_shape ?k ?sum_in_stride ?k_stride ?sum_out_stride) (ICons ?mul (INil))))
|
||||
|
||||
; Must be exactly 2D (no batch dims) — batched matmul uses CuBlasLt
|
||||
(= (len ?out_shape) 2)
|
||||
|
||||
; Get dimensions from output shape
|
||||
(= ?m (nth_from_end ?out_shape 1))
|
||||
(= ?n (nth_from_end ?out_shape 0))
|
||||
(!= ?m (MNum 0))
|
||||
(!= ?n (MNum 0))
|
||||
|
||||
; Get A strides in [m, n, k] space
|
||||
(= ?a_m_stride (nth_from_end ?a_stride 2))
|
||||
(= ?a_n_stride (nth_from_end ?a_stride 1))
|
||||
(= ?a_k_stride (nth_from_end ?a_stride 0))
|
||||
|
||||
; Get B strides in [m, n, k] space
|
||||
(= ?b_m_stride (nth_from_end ?b_stride 2))
|
||||
(= ?b_n_stride (nth_from_end ?b_stride 1))
|
||||
(= ?b_k_stride (nth_from_end ?b_stride 0))
|
||||
|
||||
; Assert contiguous k stride on output (required for reduction)
|
||||
(= ?k_stride (MIter))
|
||||
|
||||
; Assert A has strides [1, 0, m] (column-major A[m,k] broadcast to [m,n,k])
|
||||
(= ?a_m_stride (MIter))
|
||||
(= ?a_n_stride (MNum 0))
|
||||
(= ?a_k_stride (MMul (MIter) ?m))
|
||||
|
||||
; Assert B has strides [0, 1, n] (row-major B[k,n] permuted to [n,k] then broadcast to [m,n,k])
|
||||
(= ?b_m_stride (MNum 0))
|
||||
(= ?b_n_stride (MIter))
|
||||
(= ?b_k_stride (MMul (MIter) ?n))
|
||||
|
||||
(= (F32) (dtype ?a))
|
||||
(= (F32) (dtype ?b))
|
||||
)
|
||||
(
|
||||
; For column-major A × row-major B with cuBLAS:
|
||||
; C^T = B^T × A^T → cublasSgemm(OP_N, OP_T, n, m, k, α, B, n, A, m, β, C, n)
|
||||
(let ?sgemm (Op (cublasSgemmV2
|
||||
?n ; cuBLAS m = our n (swapped)
|
||||
?m ; cuBLAS n = our m (swapped)
|
||||
?k ; k unchanged
|
||||
"N" ; transa = No transpose (B is row-major, viewed as col-major [n,k])
|
||||
"T" ; transb = Transpose (A is column-major [m,k], need A^T[k,m])
|
||||
?n ; lda = n (row-major B[k,n] viewed as col-major [n,k])
|
||||
?m ; ldb = m (column-major A[m,k])
|
||||
?n) ; ldc = n (row-major C[m,n] viewed as col-major [n,m])
|
||||
(ICons ?b (ICons ?a (INil)))))
|
||||
(union ?sum ?sgemm)
|
||||
(set (dtype ?sgemm) (F32))
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublas sgemm column-major × row-major"
|
||||
)
|
||||
@@ -1,73 +0,0 @@
|
||||
; Row-major × Column-major matmul: C[m,n] = A[m,k] × B[k,n]
|
||||
; A[m,k] row-major → expand to [m, n, k] with strides [k, 0, 1]
|
||||
; B[k,n] column-major → expand to [m, n, k] with strides [0, k, 1]
|
||||
;
|
||||
; Row-major viewed as column-major (swap trick):
|
||||
; Row-major A[m,k] ≡ column-major A^T[k,m] with lda=k
|
||||
; Column-major B[k,n] is already column-major with ldb=k
|
||||
; Row-major C[m,n] ≡ column-major C^T[n,m] with ldc=n
|
||||
;
|
||||
; C^T[n,m] = (A × B)^T = B^T[n,k] × A^T[k,m]
|
||||
; cuBLAS: cublasSgemm(OP_T, OP_N, n, m, k, α, B, k, A, k, β, C, n)
|
||||
(rule
|
||||
(
|
||||
; Match Mul node
|
||||
(= ?mul (Op (Mul ?mul_shape ?a_stride ?b_stride ?mul_out_stride) (ICons ?a (ICons ?b (INil)))))
|
||||
|
||||
; Match Sum that reduces the Mul (k dimension)
|
||||
(= ?sum (Op (Sum ?out_shape ?k ?sum_in_stride ?k_stride ?sum_out_stride) (ICons ?mul (INil))))
|
||||
|
||||
; Must be exactly 2D (no batch dims) — batched matmul uses CuBlasLt
|
||||
(= (len ?out_shape) 2)
|
||||
|
||||
; Get dimensions from output shape
|
||||
(= ?m (nth_from_end ?out_shape 1))
|
||||
(= ?n (nth_from_end ?out_shape 0))
|
||||
(!= ?m (MNum 0))
|
||||
(!= ?n (MNum 0))
|
||||
|
||||
; Get A strides in [m, n, k] space
|
||||
(= ?a_m_stride (nth_from_end ?a_stride 2))
|
||||
(= ?a_n_stride (nth_from_end ?a_stride 1))
|
||||
(= ?a_k_stride (nth_from_end ?a_stride 0))
|
||||
|
||||
; Get B strides in [m, n, k] space
|
||||
(= ?b_m_stride (nth_from_end ?b_stride 2))
|
||||
(= ?b_n_stride (nth_from_end ?b_stride 1))
|
||||
(= ?b_k_stride (nth_from_end ?b_stride 0))
|
||||
|
||||
; Assert contiguous k stride on output (required for reduction)
|
||||
(= ?k_stride (MIter))
|
||||
|
||||
; Assert A has strides [k, 0, 1] (row-major A[m,k] broadcast to [m,n,k])
|
||||
(= ?a_m_stride (MMul (MIter) ?k))
|
||||
(= ?a_n_stride (MNum 0))
|
||||
(= ?a_k_stride (MIter))
|
||||
|
||||
; Assert B has strides [0, k, 1] (column-major B[k,n] broadcast to [m,n,k])
|
||||
(= ?b_m_stride (MNum 0))
|
||||
(= ?b_n_stride (MMul (MIter) ?k))
|
||||
(= ?b_k_stride (MIter))
|
||||
|
||||
(= (F32) (dtype ?a))
|
||||
(= (F32) (dtype ?b))
|
||||
)
|
||||
(
|
||||
; For row-major A × column-major B with cuBLAS:
|
||||
; C^T = B^T × A^T → cublasSgemm(OP_T, OP_N, n, m, k, α, B, k, A, k, β, C, n)
|
||||
(let ?sgemm (Op (cublasSgemmV2
|
||||
?n ; cuBLAS m = our n (swapped)
|
||||
?m ; cuBLAS n = our m (swapped)
|
||||
?k ; k unchanged
|
||||
"T" ; transa = Transpose (B is column-major, need B^T)
|
||||
"N" ; transb = No transpose
|
||||
?k ; lda = k (column-major B[k,n])
|
||||
?k ; ldb = k (row-major A[m,k] viewed as col-major [k,m])
|
||||
?n) ; ldc = n (row-major C[m,n] viewed as col-major [n,m])
|
||||
(ICons ?b (ICons ?a (INil)))))
|
||||
(union ?sum ?sgemm)
|
||||
(set (dtype ?sgemm) (F32))
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublas sgemm row-major × column-major"
|
||||
)
|
||||
@@ -1,73 +0,0 @@
|
||||
; Row-major matmul: C[m,n] = A[m,k] × B[k,n]
|
||||
; A[m,k] row-major → expand to [m, n, k] with strides [k, 0, 1]
|
||||
; B[k,n] row-major → permute to [n,k] then expand to [m, n, k] with strides [0, 1, n]
|
||||
;
|
||||
; Row-major viewed as column-major (swap trick):
|
||||
; Row-major A[m,k] ≡ column-major [k,m] with lda=k
|
||||
; Row-major B[k,n] ≡ column-major [n,k] with ldb=n
|
||||
; Row-major C[m,n] ≡ column-major [n,m] with ldc=n
|
||||
;
|
||||
; cuBLAS computes: C_col[n,m] = B_col[n,k] × A_col[k,m]
|
||||
; cublasSgemm(OP_N, OP_N, n, m, k, α, B, n, A, k, β, C, n)
|
||||
(rule
|
||||
(
|
||||
; Match Mul node
|
||||
(= ?mul (Op (Mul ?mul_shape ?a_stride ?b_stride ?mul_out_stride) (ICons ?a (ICons ?b (INil)))))
|
||||
|
||||
; Match Sum that reduces the Mul (k dimension)
|
||||
(= ?sum (Op (Sum ?out_shape ?k ?sum_in_stride ?k_stride ?sum_out_stride) (ICons ?mul (INil))))
|
||||
|
||||
; Must be exactly 2D (no batch dims) — batched matmul uses CuBlasLt
|
||||
(= (len ?out_shape) 2)
|
||||
|
||||
; Get dimensions from output shape
|
||||
(= ?m (nth_from_end ?out_shape 1))
|
||||
(= ?n (nth_from_end ?out_shape 0))
|
||||
(!= ?m (MNum 0))
|
||||
(!= ?n (MNum 0))
|
||||
|
||||
; Get A strides in [m, n, k] space
|
||||
(= ?a_m_stride (nth_from_end ?a_stride 2))
|
||||
(= ?a_n_stride (nth_from_end ?a_stride 1))
|
||||
(= ?a_k_stride (nth_from_end ?a_stride 0))
|
||||
|
||||
; Get B strides in [m, n, k] space
|
||||
(= ?b_m_stride (nth_from_end ?b_stride 2))
|
||||
(= ?b_n_stride (nth_from_end ?b_stride 1))
|
||||
(= ?b_k_stride (nth_from_end ?b_stride 0))
|
||||
|
||||
; Assert contiguous k stride on output (required for reduction)
|
||||
(= ?k_stride (MIter))
|
||||
|
||||
; Assert A has strides [k, 0, 1] (row-major A[m,k] broadcast to [m,n,k])
|
||||
(= ?a_m_stride (MMul (MIter) ?k))
|
||||
(= ?a_n_stride (MNum 0))
|
||||
(= ?a_k_stride (MIter))
|
||||
|
||||
; Assert B has strides [0, 1, n] (row-major B[k,n] permuted to [n,k] then broadcast to [m,n,k])
|
||||
(= ?b_m_stride (MNum 0))
|
||||
(= ?b_n_stride (MIter))
|
||||
(= ?b_k_stride (MMul (MIter) ?n))
|
||||
|
||||
(= (F32) (dtype ?a))
|
||||
(= (F32) (dtype ?b))
|
||||
)
|
||||
(
|
||||
; For row-major C = A × B with cuBLAS (column-major):
|
||||
; cublasSgemm(OP_N, OP_N, n, m, k, α, B, n, A, k, β, C, n)
|
||||
(let ?sgemm (Op (cublasSgemmV2
|
||||
?n ; cuBLAS m = our n (swapped)
|
||||
?m ; cuBLAS n = our m (swapped)
|
||||
?k ; k unchanged
|
||||
"N" ; transa = No transpose
|
||||
"N" ; transb = No transpose
|
||||
?n ; lda = n (row-major B[k,n] viewed as col-major [n,k])
|
||||
?k ; ldb = k (row-major A[m,k] viewed as col-major [k,m])
|
||||
?n) ; ldc = n (row-major C[m,n] viewed as col-major [n,m])
|
||||
(ICons ?b (ICons ?a (INil)))))
|
||||
(union ?sum ?sgemm)
|
||||
(set (dtype ?sgemm) (F32))
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublas sgemm row-major"
|
||||
)
|
||||
@@ -11,11 +11,13 @@
|
||||
; cuBLAS: cublasSgemm(OP_T, OP_T, n, m, k, α, B, k, A, m, β, C, n)
|
||||
(rule
|
||||
(
|
||||
; Match Mul node
|
||||
(= ?mul (Op (Mul ?mul_shape ?a_stride ?b_stride ?mul_out_stride) (ICons ?a (ICons ?b (INil)))))
|
||||
|
||||
; Match Sum that reduces the Mul (k dimension)
|
||||
(= ?sum (Op (Sum ?out_shape ?k ?sum_in_stride ?k_stride ?sum_out_stride) (ICons ?mul (INil))))
|
||||
; Match the generic matmul produced from Mul -> Sum.
|
||||
(= ?sum (Op (GenericMatmul
|
||||
?out_shape ?mul_shape ?k
|
||||
?a_stride ?b_stride
|
||||
?sum_in_stride ?k_stride ?sum_out_stride
|
||||
?matmul_dtype)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
|
||||
; Match exactly 2D output shape
|
||||
(= ?out_shape (ECons ?m (ECons ?n (ENil))))
|
||||
@@ -42,6 +44,7 @@
|
||||
|
||||
(= ?dt (dtype ?a))
|
||||
(= ?dt (dtype ?b))
|
||||
(cublaslt_base_dtype ?dt)
|
||||
)
|
||||
(
|
||||
; For column-major A × column-major B with cuBLAS:
|
||||
@@ -52,14 +55,17 @@
|
||||
?k ; k unchanged
|
||||
"T" ; transa = Transpose (B is column-major [k,n], need B^T[n,k])
|
||||
"T" ; transb = Transpose (A is column-major [m,k], need A^T[k,m])
|
||||
"COL" "COL" "COL" "COL" ; A/B/C/D matrix orders
|
||||
?b_n_stride ; lda = B's column stride (resolves to k after z→1)
|
||||
?a_k_stride ; ldb = A's column stride (resolves to m after z→1)
|
||||
?n ; ldc = n (row-major C[m,n] viewed as col-major [n,m])
|
||||
?n ; ldd = ldc for current row-major output rewrites
|
||||
(MNum 1) ; batch_count = 1
|
||||
(MNum 0) ; stride_a = 0
|
||||
(MNum 0) ; stride_b = 0
|
||||
(MNum 0) ; stride_c = 0
|
||||
?dt) ; dtype
|
||||
(MNum 0) ; stride_d = 0
|
||||
?dt ?dt ?dt ?dt "default" "default" 1.0 0.0 "DEFAULT") ; type tuple, alpha, beta
|
||||
(ICons ?b (ICons ?a (INil)))))
|
||||
(union ?sum ?sgemm)
|
||||
(set (dtype ?sgemm) ?dt)
|
||||
@@ -73,8 +79,12 @@
|
||||
; B column-major per batch: b_k_stride=MIter, b_m_stride=0
|
||||
(rule
|
||||
(
|
||||
(= ?mul (Op (Mul ?mul_shape ?a_stride ?b_stride ?mul_out_stride) (ICons ?a (ICons ?b (INil)))))
|
||||
(= ?sum (Op (Sum ?out_shape ?k ?sum_in_stride ?k_stride ?sum_out_stride) (ICons ?mul (INil))))
|
||||
(= ?sum (Op (GenericMatmul
|
||||
?out_shape ?mul_shape ?k
|
||||
?a_stride ?b_stride
|
||||
?sum_in_stride ?k_stride ?sum_out_stride
|
||||
?matmul_dtype)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
|
||||
(= ?batch (nth_from_end ?out_shape 2))
|
||||
(= ?m (nth_from_end ?out_shape 1))
|
||||
@@ -112,20 +122,24 @@
|
||||
|
||||
(= ?dt (dtype ?a))
|
||||
(= ?dt (dtype ?b))
|
||||
(cublaslt_base_dtype ?dt)
|
||||
)
|
||||
(
|
||||
; cuBLAS: cublas(OP_T, OP_T, n, m, k, B, lda=b_n_stride, A, ldb=a_k_stride, C, ldc=n)
|
||||
(let ?sgemm (Op (cublaslt
|
||||
?n ?m ?k
|
||||
"T" "T"
|
||||
"COL" "COL" "COL" "COL"
|
||||
?b_n_stride ; lda (cuBLAS A = our B, column stride)
|
||||
?a_k_stride ; ldb (cuBLAS B = our A, column stride)
|
||||
?n ; ldc
|
||||
?n ; ldd
|
||||
?batch
|
||||
?b_batch_stride ; stride_a (cuBLAS A = our B)
|
||||
?a_batch_stride ; stride_b (cuBLAS B = our A)
|
||||
(MMul ?m ?n) ; stride_c
|
||||
?dt)
|
||||
(MMul ?m ?n) ; stride_d
|
||||
?dt ?dt ?dt ?dt "default" "default" 1.0 0.0 "DEFAULT")
|
||||
(ICons ?b (ICons ?a (INil)))))
|
||||
(union ?sum ?sgemm)
|
||||
(set (dtype ?sgemm) ?dt)
|
||||
|
||||
@@ -11,11 +11,13 @@
|
||||
; cuBLAS: cublasSgemm(OP_N, OP_T, n, m, k, α, B, n, A, m, β, C, n)
|
||||
(rule
|
||||
(
|
||||
; Match Mul node
|
||||
(= ?mul (Op (Mul ?mul_shape ?a_stride ?b_stride ?mul_out_stride) (ICons ?a (ICons ?b (INil)))))
|
||||
|
||||
; Match Sum that reduces the Mul (k dimension)
|
||||
(= ?sum (Op (Sum ?out_shape ?k ?sum_in_stride ?k_stride ?sum_out_stride) (ICons ?mul (INil))))
|
||||
; Match the generic matmul produced from Mul -> Sum.
|
||||
(= ?sum (Op (GenericMatmul
|
||||
?out_shape ?mul_shape ?k
|
||||
?a_stride ?b_stride
|
||||
?sum_in_stride ?k_stride ?sum_out_stride
|
||||
?matmul_dtype)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
|
||||
; Match exactly 2D output shape
|
||||
(= ?out_shape (ECons ?m (ECons ?n (ENil))))
|
||||
@@ -42,6 +44,7 @@
|
||||
|
||||
(= ?dt (dtype ?a))
|
||||
(= ?dt (dtype ?b))
|
||||
(cublaslt_base_dtype ?dt)
|
||||
)
|
||||
(
|
||||
; For column-major A × row-major B with cuBLAS:
|
||||
@@ -52,14 +55,17 @@
|
||||
?k ; k unchanged
|
||||
"N" ; transa = No transpose (B is row-major, viewed as col-major [n,k])
|
||||
"T" ; transb = Transpose (A is column-major [m,k], need A^T[k,m])
|
||||
"COL" "COL" "COL" "COL" ; A/B/C/D matrix orders
|
||||
?b_k_stride ; lda = B's row stride (resolves to n after z→1)
|
||||
?a_k_stride ; ldb = A's column stride (resolves to m after z→1)
|
||||
?n ; ldc = n (row-major C[m,n] viewed as col-major [n,m])
|
||||
?n ; ldd = ldc for current row-major output rewrites
|
||||
(MNum 1) ; batch_count = 1
|
||||
(MNum 0) ; stride_a = 0
|
||||
(MNum 0) ; stride_b = 0
|
||||
(MNum 0) ; stride_c = 0
|
||||
?dt) ; dtype
|
||||
(MNum 0) ; stride_d = 0
|
||||
?dt ?dt ?dt ?dt "default" "default" 1.0 0.0 "DEFAULT") ; type tuple, alpha, beta
|
||||
(ICons ?b (ICons ?a (INil)))))
|
||||
(union ?sum ?sgemm)
|
||||
(set (dtype ?sgemm) ?dt)
|
||||
@@ -73,8 +79,12 @@
|
||||
; B row-major per batch: b_n_stride=MIter, b_m_stride=0
|
||||
(rule
|
||||
(
|
||||
(= ?mul (Op (Mul ?mul_shape ?a_stride ?b_stride ?mul_out_stride) (ICons ?a (ICons ?b (INil)))))
|
||||
(= ?sum (Op (Sum ?out_shape ?k ?sum_in_stride ?k_stride ?sum_out_stride) (ICons ?mul (INil))))
|
||||
(= ?sum (Op (GenericMatmul
|
||||
?out_shape ?mul_shape ?k
|
||||
?a_stride ?b_stride
|
||||
?sum_in_stride ?k_stride ?sum_out_stride
|
||||
?matmul_dtype)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
|
||||
(= ?batch (nth_from_end ?out_shape 2))
|
||||
(= ?m (nth_from_end ?out_shape 1))
|
||||
@@ -112,20 +122,24 @@
|
||||
|
||||
(= ?dt (dtype ?a))
|
||||
(= ?dt (dtype ?b))
|
||||
(cublaslt_base_dtype ?dt)
|
||||
)
|
||||
(
|
||||
; cuBLAS: cublas(OP_N, OP_T, n, m, k, B, lda=b_k_stride, A, ldb=a_k_stride, C, ldc=n)
|
||||
(let ?sgemm (Op (cublaslt
|
||||
?n ?m ?k
|
||||
"N" "T"
|
||||
"COL" "COL" "COL" "COL"
|
||||
?b_k_stride ; lda (cuBLAS A = our B, row stride)
|
||||
?a_k_stride ; ldb (cuBLAS B = our A, column stride)
|
||||
?n ; ldc
|
||||
?n ; ldd
|
||||
?batch
|
||||
?b_batch_stride ; stride_a (cuBLAS A = our B)
|
||||
?a_batch_stride ; stride_b (cuBLAS B = our A)
|
||||
(MMul ?m ?n) ; stride_c
|
||||
?dt)
|
||||
(MMul ?m ?n) ; stride_d
|
||||
?dt ?dt ?dt ?dt "default" "default" 1.0 0.0 "DEFAULT")
|
||||
(ICons ?b (ICons ?a (INil)))))
|
||||
(union ?sum ?sgemm)
|
||||
(set (dtype ?sgemm) ?dt)
|
||||
|
||||
@@ -11,11 +11,13 @@
|
||||
; cuBLAS: cublasSgemm(OP_T, OP_N, n, m, k, α, B, k, A, k, β, C, n)
|
||||
(rule
|
||||
(
|
||||
; Match Mul node
|
||||
(= ?mul (Op (Mul ?mul_shape ?a_stride ?b_stride ?mul_out_stride) (ICons ?a (ICons ?b (INil)))))
|
||||
|
||||
; Match Sum that reduces the Mul (k dimension)
|
||||
(= ?sum (Op (Sum ?out_shape ?k ?sum_in_stride ?k_stride ?sum_out_stride) (ICons ?mul (INil))))
|
||||
; Match the generic matmul produced from Mul -> Sum.
|
||||
(= ?sum (Op (GenericMatmul
|
||||
?out_shape ?mul_shape ?k
|
||||
?a_stride ?b_stride
|
||||
?sum_in_stride ?k_stride ?sum_out_stride
|
||||
?matmul_dtype)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
|
||||
; Match exactly 2D output shape
|
||||
(= ?out_shape (ECons ?m (ECons ?n (ENil))))
|
||||
@@ -42,6 +44,7 @@
|
||||
|
||||
(= ?dt (dtype ?a))
|
||||
(= ?dt (dtype ?b))
|
||||
(cublaslt_base_dtype ?dt)
|
||||
)
|
||||
(
|
||||
; For row-major A × column-major B with cuBLAS:
|
||||
@@ -52,14 +55,17 @@
|
||||
?k ; k unchanged
|
||||
"T" ; transa = Transpose (B is column-major, need B^T)
|
||||
"N" ; transb = No transpose
|
||||
"COL" "COL" "COL" "COL" ; A/B/C/D matrix orders
|
||||
?b_n_stride ; lda = B's column stride (resolves to k after z→1)
|
||||
?a_m_stride ; ldb = A's row stride (resolves to k after z→1)
|
||||
?n ; ldc = n (row-major C[m,n] viewed as col-major [n,m])
|
||||
?n ; ldd = ldc for current row-major output rewrites
|
||||
(MNum 1) ; batch_count = 1
|
||||
(MNum 0) ; stride_a = 0
|
||||
(MNum 0) ; stride_b = 0
|
||||
(MNum 0) ; stride_c = 0
|
||||
?dt) ; dtype
|
||||
(MNum 0) ; stride_d = 0
|
||||
?dt ?dt ?dt ?dt "default" "default" 1.0 0.0 "DEFAULT") ; type tuple, alpha, beta
|
||||
(ICons ?b (ICons ?a (INil)))))
|
||||
(union ?sum ?sgemm)
|
||||
(set (dtype ?sgemm) ?dt)
|
||||
@@ -73,8 +79,12 @@
|
||||
; B column-major per batch: b_k_stride=MIter, b_m_stride=0
|
||||
(rule
|
||||
(
|
||||
(= ?mul (Op (Mul ?mul_shape ?a_stride ?b_stride ?mul_out_stride) (ICons ?a (ICons ?b (INil)))))
|
||||
(= ?sum (Op (Sum ?out_shape ?k ?sum_in_stride ?k_stride ?sum_out_stride) (ICons ?mul (INil))))
|
||||
(= ?sum (Op (GenericMatmul
|
||||
?out_shape ?mul_shape ?k
|
||||
?a_stride ?b_stride
|
||||
?sum_in_stride ?k_stride ?sum_out_stride
|
||||
?matmul_dtype)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
|
||||
(= ?batch (nth_from_end ?out_shape 2))
|
||||
(= ?m (nth_from_end ?out_shape 1))
|
||||
@@ -112,20 +122,24 @@
|
||||
|
||||
(= ?dt (dtype ?a))
|
||||
(= ?dt (dtype ?b))
|
||||
(cublaslt_base_dtype ?dt)
|
||||
)
|
||||
(
|
||||
; cuBLAS: cublas(OP_T, OP_N, n, m, k, B, lda=b_n_stride, A, ldb=a_m_stride, C, ldc=n)
|
||||
(let ?sgemm (Op (cublaslt
|
||||
?n ?m ?k
|
||||
"T" "N"
|
||||
"COL" "COL" "COL" "COL"
|
||||
?b_n_stride ; lda (cuBLAS A = our B, column stride)
|
||||
?a_m_stride ; ldb (cuBLAS B = our A, row stride)
|
||||
?n ; ldc
|
||||
?n ; ldd
|
||||
?batch
|
||||
?b_batch_stride ; stride_a (cuBLAS A = our B)
|
||||
?a_batch_stride ; stride_b (cuBLAS B = our A)
|
||||
(MMul ?m ?n) ; stride_c
|
||||
?dt)
|
||||
(MMul ?m ?n) ; stride_d
|
||||
?dt ?dt ?dt ?dt "default" "default" 1.0 0.0 "DEFAULT")
|
||||
(ICons ?b (ICons ?a (INil)))))
|
||||
(union ?sum ?sgemm)
|
||||
(set (dtype ?sgemm) ?dt)
|
||||
|
||||
@@ -11,11 +11,13 @@
|
||||
; cublasSgemm(OP_N, OP_N, n, m, k, α, B, n, A, k, β, C, n)
|
||||
(rule
|
||||
(
|
||||
; Match Mul node
|
||||
(= ?mul (Op (Mul ?mul_shape ?a_stride ?b_stride ?mul_out_stride) (ICons ?a (ICons ?b (INil)))))
|
||||
|
||||
; Match Sum that reduces the Mul (k dimension)
|
||||
(= ?sum (Op (Sum ?out_shape ?k ?sum_in_stride ?k_stride ?sum_out_stride) (ICons ?mul (INil))))
|
||||
; Match the generic matmul produced from Mul -> Sum.
|
||||
(= ?sum (Op (GenericMatmul
|
||||
?out_shape ?mul_shape ?k
|
||||
?a_stride ?b_stride
|
||||
?sum_in_stride ?k_stride ?sum_out_stride
|
||||
?matmul_dtype)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
|
||||
; Match exactly 2D output shape
|
||||
(= ?out_shape (ECons ?m (ECons ?n (ENil))))
|
||||
@@ -42,6 +44,7 @@
|
||||
|
||||
(= ?dt (dtype ?a))
|
||||
(= ?dt (dtype ?b))
|
||||
(cublaslt_base_dtype ?dt)
|
||||
)
|
||||
(
|
||||
; For row-major C = A × B with cuBLAS (column-major):
|
||||
@@ -52,14 +55,17 @@
|
||||
?k ; k unchanged
|
||||
"N" ; transa = No transpose
|
||||
"N" ; transb = No transpose
|
||||
"COL" "COL" "COL" "COL" ; A/B/C/D matrix orders
|
||||
?b_k_stride ; lda = B's row stride (resolves to n after z→1)
|
||||
?a_m_stride ; ldb = A's row stride (resolves to k after z→1)
|
||||
?n ; ldc = n (row-major C[m,n] viewed as col-major [n,m])
|
||||
?n ; ldd = ldc for current row-major output rewrites
|
||||
(MNum 1) ; batch_count = 1
|
||||
(MNum 0) ; stride_a = 0
|
||||
(MNum 0) ; stride_b = 0
|
||||
(MNum 0) ; stride_c = 0
|
||||
?dt) ; dtype
|
||||
(MNum 0) ; stride_d = 0
|
||||
?dt ?dt ?dt ?dt "default" "default" 1.0 0.0 "DEFAULT") ; type tuple, alpha, beta
|
||||
(ICons ?b (ICons ?a (INil)))))
|
||||
(union ?sum ?sgemm)
|
||||
(set (dtype ?sgemm) ?dt)
|
||||
@@ -75,8 +81,12 @@
|
||||
; Leading dimensions may differ from k/n when batch slices are non-contiguous.
|
||||
(rule
|
||||
(
|
||||
(= ?mul (Op (Mul ?mul_shape ?a_stride ?b_stride ?mul_out_stride) (ICons ?a (ICons ?b (INil)))))
|
||||
(= ?sum (Op (Sum ?out_shape ?k ?sum_in_stride ?k_stride ?sum_out_stride) (ICons ?mul (INil))))
|
||||
(= ?sum (Op (GenericMatmul
|
||||
?out_shape ?mul_shape ?k
|
||||
?a_stride ?b_stride
|
||||
?sum_in_stride ?k_stride ?sum_out_stride
|
||||
?matmul_dtype)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
|
||||
; Output shape: [batch, m, n]
|
||||
(= ?batch (nth_from_end ?out_shape 2))
|
||||
@@ -117,6 +127,7 @@
|
||||
|
||||
(= ?dt (dtype ?a))
|
||||
(= ?dt (dtype ?b))
|
||||
(cublaslt_base_dtype ?dt)
|
||||
)
|
||||
(
|
||||
; cuBLAS swap: C^T[n,m] = B^T[n,k] × A^T[k,m] per batch
|
||||
@@ -124,14 +135,17 @@
|
||||
(let ?sgemm (Op (cublaslt
|
||||
?n ?m ?k
|
||||
"N" "N"
|
||||
"COL" "COL" "COL" "COL"
|
||||
?b_k_stride ; lda (cuBLAS A = our B, row stride)
|
||||
?a_m_stride ; ldb (cuBLAS B = our A, row stride)
|
||||
?n ; ldc (contiguous output per batch)
|
||||
?n ; ldd
|
||||
?batch ; batch_count
|
||||
?b_batch_stride ; stride_a (cuBLAS A = our B)
|
||||
?a_batch_stride ; stride_b (cuBLAS B = our A)
|
||||
(MMul ?m ?n) ; stride_c
|
||||
?dt)
|
||||
(MMul ?m ?n) ; stride_d
|
||||
?dt ?dt ?dt ?dt "default" "default" 1.0 0.0 "DEFAULT")
|
||||
(ICons ?b (ICons ?a (INil)))))
|
||||
(union ?sum ?sgemm)
|
||||
(set (dtype ?sgemm) ?dt)
|
||||
|
||||
@@ -0,0 +1,428 @@
|
||||
; Fuse a row-major Add on top of an existing cuBLASLt matmul into
|
||||
; D = alpha * A * B + beta * C.
|
||||
;
|
||||
; The existing matmul rewrites view Luminal's row-major output [m,n] as a
|
||||
; column-major cuBLASLt matrix [n,m]. A row-major C input with logical strides
|
||||
; [row_stride, 1] therefore maps to ldc=row_stride. This lets a C slice from a
|
||||
; wider parent tensor use a larger ldc while D keeps the matmul output layout.
|
||||
; cuBLASLt requires out-of-place C and D to have the same matrix order, so these
|
||||
; beta rules only fuse C layouts that map to the current COL-ordered D layout.
|
||||
(rule
|
||||
(
|
||||
(= ?matmul (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?matmul_c_order "COL"
|
||||
?lda ?ldb ?matmul_ldc ?ldd
|
||||
(MNum 1)
|
||||
?stride_a ?stride_b ?matmul_stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 ?epilogue)
|
||||
(ICons ?a (ICons ?b ?matmul_tail))))
|
||||
(!= ?epilogue "RELU")
|
||||
(!= ?epilogue "RELU_BIAS")
|
||||
(!= ?epilogue "GELU")
|
||||
(!= ?epilogue "GELU_BIAS")
|
||||
|
||||
(= ?add (Op (Add
|
||||
(ECons ?n (ECons ?m (ENil)))
|
||||
?matmul_add_strides
|
||||
?c_add_strides
|
||||
?add_out_strides)
|
||||
(ICons ?matmul (ICons ?c (INil)))))
|
||||
|
||||
(= ?matmul_add_strides (ECons ?d_row_stride (ECons ?d_col_stride (ENil))))
|
||||
(= ?c_add_strides (ECons ?c_row_stride (ECons ?c_col_stride (ENil))))
|
||||
(= ?add_out_strides (ECons ?d_row_stride (ECons ?d_col_stride (ENil))))
|
||||
(= ?c_col_stride (MIter))
|
||||
(!= ?c_row_stride (MNum 0))
|
||||
(= ?matmul_add_strides ?add_out_strides)
|
||||
(= ?c_dtype (dtype ?c))
|
||||
)
|
||||
(
|
||||
(let ?fused (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order "COL" "COL"
|
||||
?lda ?ldb ?c_row_stride ?ldd
|
||||
(MNum 1)
|
||||
?stride_a ?stride_b (MNum 0) ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 1.0 ?epilogue)
|
||||
(ICons ?a (ICons ?b (ICons ?c ?matmul_tail)))))
|
||||
(union ?add ?fused)
|
||||
(set (dtype ?fused) ?d_dtype)
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt 2d matmul plus c beta"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?matmul (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?matmul_c_order "COL"
|
||||
?lda ?ldb ?matmul_ldc ?ldd
|
||||
(MNum 1)
|
||||
?stride_a ?stride_b ?matmul_stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 ?epilogue)
|
||||
(ICons ?a (ICons ?b ?matmul_tail))))
|
||||
(!= ?epilogue "RELU")
|
||||
(!= ?epilogue "RELU_BIAS")
|
||||
(!= ?epilogue "GELU")
|
||||
(!= ?epilogue "GELU_BIAS")
|
||||
|
||||
(= ?add (Op (Add
|
||||
(ECons ?n (ECons ?m (ENil)))
|
||||
?c_add_strides
|
||||
?matmul_add_strides
|
||||
?add_out_strides)
|
||||
(ICons ?c (ICons ?matmul (INil)))))
|
||||
|
||||
(= ?matmul_add_strides (ECons ?d_row_stride (ECons ?d_col_stride (ENil))))
|
||||
(= ?c_add_strides (ECons ?c_row_stride (ECons ?c_col_stride (ENil))))
|
||||
(= ?add_out_strides (ECons ?d_row_stride (ECons ?d_col_stride (ENil))))
|
||||
(= ?c_col_stride (MIter))
|
||||
(!= ?c_row_stride (MNum 0))
|
||||
(= ?matmul_add_strides ?add_out_strides)
|
||||
(= ?c_dtype (dtype ?c))
|
||||
)
|
||||
(
|
||||
(let ?fused (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order "COL" "COL"
|
||||
?lda ?ldb ?c_row_stride ?ldd
|
||||
(MNum 1)
|
||||
?stride_a ?stride_b (MNum 0) ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 1.0 ?epilogue)
|
||||
(ICons ?a (ICons ?b (ICons ?c ?matmul_tail)))))
|
||||
(union ?add ?fused)
|
||||
(set (dtype ?fused) ?d_dtype)
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt 2d c plus matmul beta"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?matmul (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?matmul_c_order "COL"
|
||||
?lda ?ldb ?matmul_ldc ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?matmul_stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 ?epilogue)
|
||||
(ICons ?a (ICons ?b ?matmul_tail))))
|
||||
(!= ?epilogue "RELU")
|
||||
(!= ?epilogue "RELU_BIAS")
|
||||
(!= ?epilogue "GELU")
|
||||
(!= ?epilogue "GELU_BIAS")
|
||||
|
||||
(= ?add (Op (Add
|
||||
(ECons ?batch (ECons ?n (ECons ?m (ENil))))
|
||||
?matmul_add_strides
|
||||
?c_add_strides
|
||||
?add_out_strides)
|
||||
(ICons ?matmul (ICons ?c (INil)))))
|
||||
|
||||
(= ?matmul_add_strides (ECons ?d_batch_stride (ECons ?d_row_stride (ECons ?d_col_stride (ENil)))))
|
||||
(= ?c_add_strides (ECons ?c_batch_stride (ECons ?c_row_stride (ECons ?c_col_stride (ENil)))))
|
||||
(= ?add_out_strides (ECons ?d_batch_stride (ECons ?d_row_stride (ECons ?d_col_stride (ENil)))))
|
||||
(= ?c_col_stride (MIter))
|
||||
(!= ?c_row_stride (MNum 0))
|
||||
(= ?matmul_add_strides ?add_out_strides)
|
||||
(= ?c_dtype (dtype ?c))
|
||||
)
|
||||
(
|
||||
(let ?fused (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order "COL" "COL"
|
||||
?lda ?ldb ?c_row_stride ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?c_batch_stride ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 1.0 ?epilogue)
|
||||
(ICons ?a (ICons ?b (ICons ?c ?matmul_tail)))))
|
||||
(union ?add ?fused)
|
||||
(set (dtype ?fused) ?d_dtype)
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt batched matmul plus c beta"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?matmul (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?matmul_c_order "COL"
|
||||
?lda ?ldb ?matmul_ldc ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?matmul_stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 ?epilogue)
|
||||
(ICons ?a (ICons ?b ?matmul_tail))))
|
||||
(!= ?epilogue "RELU")
|
||||
(!= ?epilogue "RELU_BIAS")
|
||||
(!= ?epilogue "GELU")
|
||||
(!= ?epilogue "GELU_BIAS")
|
||||
|
||||
(= ?add (Op (Add
|
||||
(ECons ?batch (ECons ?n (ECons ?m (ENil))))
|
||||
?c_add_strides
|
||||
?matmul_add_strides
|
||||
?add_out_strides)
|
||||
(ICons ?c (ICons ?matmul (INil)))))
|
||||
|
||||
(= ?matmul_add_strides (ECons ?d_batch_stride (ECons ?d_row_stride (ECons ?d_col_stride (ENil)))))
|
||||
(= ?c_add_strides (ECons ?c_batch_stride (ECons ?c_row_stride (ECons ?c_col_stride (ENil)))))
|
||||
(= ?add_out_strides (ECons ?d_batch_stride (ECons ?d_row_stride (ECons ?d_col_stride (ENil)))))
|
||||
(= ?c_col_stride (MIter))
|
||||
(!= ?c_row_stride (MNum 0))
|
||||
(= ?matmul_add_strides ?add_out_strides)
|
||||
(= ?c_dtype (dtype ?c))
|
||||
)
|
||||
(
|
||||
(let ?fused (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order "COL" "COL"
|
||||
?lda ?ldb ?c_row_stride ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?c_batch_stride ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 1.0 ?epilogue)
|
||||
(ICons ?a (ICons ?b (ICons ?c ?matmul_tail)))))
|
||||
(union ?add ?fused)
|
||||
(set (dtype ?fused) ?d_dtype)
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt batched c plus matmul beta"
|
||||
)
|
||||
|
||||
; ROW-ordered D beta fusions. These pair with cublaslt_row_order_rewrite.egg,
|
||||
; where the cuBLASLt problem dimensions match Luminal's logical output [m,n].
|
||||
; A row-major C input with logical strides [row_stride, 1] maps directly to a
|
||||
; ROW-ordered cuBLASLt C[m,n] descriptor with ldc=row_stride.
|
||||
(rule
|
||||
(
|
||||
(= ?matmul (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?matmul_c_order "ROW"
|
||||
?lda ?ldb ?matmul_ldc ?ldd
|
||||
(MNum 1)
|
||||
?stride_a ?stride_b ?matmul_stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 ?epilogue)
|
||||
(ICons ?a (ICons ?b ?matmul_tail))))
|
||||
(!= ?epilogue "RELU")
|
||||
(!= ?epilogue "RELU_BIAS")
|
||||
(!= ?epilogue "GELU")
|
||||
(!= ?epilogue "GELU_BIAS")
|
||||
|
||||
(= ?add (Op (Add
|
||||
(ECons ?m (ECons ?n (ENil)))
|
||||
?matmul_add_strides
|
||||
?c_add_strides
|
||||
?add_out_strides)
|
||||
(ICons ?matmul (ICons ?c (INil)))))
|
||||
|
||||
(= ?matmul_add_strides (ECons ?d_row_stride (ECons ?d_col_stride (ENil))))
|
||||
(= ?c_add_strides (ECons ?c_row_stride (ECons ?c_col_stride (ENil))))
|
||||
(= ?add_out_strides (ECons ?d_row_stride (ECons ?d_col_stride (ENil))))
|
||||
(= ?c_col_stride (MIter))
|
||||
(!= ?c_row_stride (MNum 0))
|
||||
(= ?matmul_add_strides ?add_out_strides)
|
||||
(= ?c_dtype (dtype ?c))
|
||||
)
|
||||
(
|
||||
(let ?fused (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order "ROW" "ROW"
|
||||
?lda ?ldb ?c_row_stride ?ldd
|
||||
(MNum 1)
|
||||
?stride_a ?stride_b (MNum 0) ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 1.0 ?epilogue)
|
||||
(ICons ?a (ICons ?b (ICons ?c ?matmul_tail)))))
|
||||
(union ?add ?fused)
|
||||
(set (dtype ?fused) ?d_dtype)
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt row-order 2d matmul plus c beta"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?matmul (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?matmul_c_order "ROW"
|
||||
?lda ?ldb ?matmul_ldc ?ldd
|
||||
(MNum 1)
|
||||
?stride_a ?stride_b ?matmul_stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 ?epilogue)
|
||||
(ICons ?a (ICons ?b ?matmul_tail))))
|
||||
(!= ?epilogue "RELU")
|
||||
(!= ?epilogue "RELU_BIAS")
|
||||
(!= ?epilogue "GELU")
|
||||
(!= ?epilogue "GELU_BIAS")
|
||||
|
||||
(= ?add (Op (Add
|
||||
(ECons ?m (ECons ?n (ENil)))
|
||||
?c_add_strides
|
||||
?matmul_add_strides
|
||||
?add_out_strides)
|
||||
(ICons ?c (ICons ?matmul (INil)))))
|
||||
|
||||
(= ?matmul_add_strides (ECons ?d_row_stride (ECons ?d_col_stride (ENil))))
|
||||
(= ?c_add_strides (ECons ?c_row_stride (ECons ?c_col_stride (ENil))))
|
||||
(= ?add_out_strides (ECons ?d_row_stride (ECons ?d_col_stride (ENil))))
|
||||
(= ?c_col_stride (MIter))
|
||||
(!= ?c_row_stride (MNum 0))
|
||||
(= ?matmul_add_strides ?add_out_strides)
|
||||
(= ?c_dtype (dtype ?c))
|
||||
)
|
||||
(
|
||||
(let ?fused (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order "ROW" "ROW"
|
||||
?lda ?ldb ?c_row_stride ?ldd
|
||||
(MNum 1)
|
||||
?stride_a ?stride_b (MNum 0) ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 1.0 ?epilogue)
|
||||
(ICons ?a (ICons ?b (ICons ?c ?matmul_tail)))))
|
||||
(union ?add ?fused)
|
||||
(set (dtype ?fused) ?d_dtype)
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt row-order 2d c plus matmul beta"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?matmul (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?matmul_c_order "ROW"
|
||||
?lda ?ldb ?matmul_ldc ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?matmul_stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 ?epilogue)
|
||||
(ICons ?a (ICons ?b ?matmul_tail))))
|
||||
(!= ?epilogue "RELU")
|
||||
(!= ?epilogue "RELU_BIAS")
|
||||
(!= ?epilogue "GELU")
|
||||
(!= ?epilogue "GELU_BIAS")
|
||||
|
||||
(= ?add (Op (Add
|
||||
(ECons ?batch (ECons ?m (ECons ?n (ENil))))
|
||||
?matmul_add_strides
|
||||
?c_add_strides
|
||||
?add_out_strides)
|
||||
(ICons ?matmul (ICons ?c (INil)))))
|
||||
|
||||
(= ?matmul_add_strides (ECons ?d_batch_stride (ECons ?d_row_stride (ECons ?d_col_stride (ENil)))))
|
||||
(= ?c_add_strides (ECons ?c_batch_stride (ECons ?c_row_stride (ECons ?c_col_stride (ENil)))))
|
||||
(= ?add_out_strides (ECons ?d_batch_stride (ECons ?d_row_stride (ECons ?d_col_stride (ENil)))))
|
||||
(= ?c_col_stride (MIter))
|
||||
(!= ?c_row_stride (MNum 0))
|
||||
(= ?matmul_add_strides ?add_out_strides)
|
||||
(= ?c_dtype (dtype ?c))
|
||||
)
|
||||
(
|
||||
(let ?fused (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order "ROW" "ROW"
|
||||
?lda ?ldb ?c_row_stride ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?c_batch_stride ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 1.0 ?epilogue)
|
||||
(ICons ?a (ICons ?b (ICons ?c ?matmul_tail)))))
|
||||
(union ?add ?fused)
|
||||
(set (dtype ?fused) ?d_dtype)
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt row-order batched matmul plus c beta"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?matmul (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?matmul_c_order "ROW"
|
||||
?lda ?ldb ?matmul_ldc ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?matmul_stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 ?epilogue)
|
||||
(ICons ?a (ICons ?b ?matmul_tail))))
|
||||
(!= ?epilogue "RELU")
|
||||
(!= ?epilogue "RELU_BIAS")
|
||||
(!= ?epilogue "GELU")
|
||||
(!= ?epilogue "GELU_BIAS")
|
||||
|
||||
(= ?add (Op (Add
|
||||
(ECons ?batch (ECons ?m (ECons ?n (ENil))))
|
||||
?c_add_strides
|
||||
?matmul_add_strides
|
||||
?add_out_strides)
|
||||
(ICons ?c (ICons ?matmul (INil)))))
|
||||
|
||||
(= ?matmul_add_strides (ECons ?d_batch_stride (ECons ?d_row_stride (ECons ?d_col_stride (ENil)))))
|
||||
(= ?c_add_strides (ECons ?c_batch_stride (ECons ?c_row_stride (ECons ?c_col_stride (ENil)))))
|
||||
(= ?add_out_strides (ECons ?d_batch_stride (ECons ?d_row_stride (ECons ?d_col_stride (ENil)))))
|
||||
(= ?c_col_stride (MIter))
|
||||
(!= ?c_row_stride (MNum 0))
|
||||
(= ?matmul_add_strides ?add_out_strides)
|
||||
(= ?c_dtype (dtype ?c))
|
||||
)
|
||||
(
|
||||
(let ?fused (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order "ROW" "ROW"
|
||||
?lda ?ldb ?c_row_stride ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?c_batch_stride ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 1.0 ?epilogue)
|
||||
(ICons ?a (ICons ?b (ICons ?c ?matmul_tail)))))
|
||||
(union ?add ?fused)
|
||||
(set (dtype ?fused) ?d_dtype)
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt row-order batched c plus matmul beta"
|
||||
)
|
||||
@@ -0,0 +1,614 @@
|
||||
; cuBLASLt epilogue rewrites.
|
||||
;
|
||||
; ReLU in the frontend lowers through maximum_f32(0.0):
|
||||
;
|
||||
; (matmul < 0) * 0 + cast(cast((-cast(matmul < 0) + 1) as bool) as f32) * matmul
|
||||
;
|
||||
; These rules fuse that expression back into CUBLASLT_EPILOGUE_RELU.
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?matmul (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?c_order ?d_order
|
||||
?lda ?ldb ?ldc ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype (F32)
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 "DEFAULT")
|
||||
(ICons ?a (ICons ?b ?matmul_tail))))
|
||||
|
||||
(= ?zero (Op (Constant 0.0) (INil)))
|
||||
(= ?neg_one (Op (Constant -1.0) (INil)))
|
||||
(= ?one (Op (Constant 1.0) (INil)))
|
||||
|
||||
(= ?lt (Op (LessThan
|
||||
?shape
|
||||
?matmul_strides
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ENil)))
|
||||
?mask_strides)
|
||||
(ICons ?matmul (ICons ?zero (INil)))))
|
||||
(= ?lt_f32 (Op (Cast ?size (F32)) (ICons ?lt (INil))))
|
||||
|
||||
(= ?zeroed (Op (Mul
|
||||
?shape
|
||||
?mask_strides
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ENil)))
|
||||
?zeroed_strides)
|
||||
(ICons ?lt_f32 (ICons ?zero (INil)))))
|
||||
|
||||
(= ?neg_mask (Op (Mul
|
||||
?shape
|
||||
?mask_strides
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ENil)))
|
||||
?neg_mask_strides)
|
||||
(ICons ?lt_f32 (ICons ?neg_one (INil)))))
|
||||
(= ?not_mask_f32 (Op (Add
|
||||
?shape
|
||||
?neg_mask_strides
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ENil)))
|
||||
?not_mask_f32_strides)
|
||||
(ICons ?neg_mask (ICons ?one (INil)))))
|
||||
(= ?not_mask_bool (Op (Cast ?size (Bool)) (ICons ?not_mask_f32 (INil))))
|
||||
(= ?not_mask (Op (Cast ?size (F32)) (ICons ?not_mask_bool (INil))))
|
||||
|
||||
(= ?positive (Op (Mul
|
||||
?shape
|
||||
?not_mask_f32_strides
|
||||
?matmul_strides
|
||||
?positive_strides)
|
||||
(ICons ?not_mask (ICons ?matmul (INil)))))
|
||||
(= ?relu (Op (Add
|
||||
?shape
|
||||
?zeroed_strides
|
||||
?positive_strides
|
||||
?relu_strides)
|
||||
(ICons ?zeroed (ICons ?positive (INil)))))
|
||||
)
|
||||
(
|
||||
(let ?fused (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?c_order ?d_order
|
||||
?lda ?ldb ?ldc ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype (F32)
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 "RELU")
|
||||
(ICons ?a (ICons ?b ?matmul_tail))))
|
||||
(union ?relu ?fused)
|
||||
(set (dtype ?fused) (F32))
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt 2d relu epilogue"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?matmul (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?c_order ?d_order
|
||||
?lda ?ldb ?ldc ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype (F32)
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 "DEFAULT")
|
||||
(ICons ?a (ICons ?b ?matmul_tail))))
|
||||
|
||||
(= ?zero (Op (Constant 0.0) (INil)))
|
||||
(= ?neg_one (Op (Constant -1.0) (INil)))
|
||||
(= ?one (Op (Constant 1.0) (INil)))
|
||||
|
||||
(= ?lt (Op (LessThan
|
||||
?shape
|
||||
?matmul_strides
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ECons (MNum 0) (ENil))))
|
||||
?mask_strides)
|
||||
(ICons ?matmul (ICons ?zero (INil)))))
|
||||
(= ?lt_f32 (Op (Cast ?size (F32)) (ICons ?lt (INil))))
|
||||
|
||||
(= ?zeroed (Op (Mul
|
||||
?shape
|
||||
?mask_strides
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ECons (MNum 0) (ENil))))
|
||||
?zeroed_strides)
|
||||
(ICons ?lt_f32 (ICons ?zero (INil)))))
|
||||
|
||||
(= ?neg_mask (Op (Mul
|
||||
?shape
|
||||
?mask_strides
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ECons (MNum 0) (ENil))))
|
||||
?neg_mask_strides)
|
||||
(ICons ?lt_f32 (ICons ?neg_one (INil)))))
|
||||
(= ?not_mask_f32 (Op (Add
|
||||
?shape
|
||||
?neg_mask_strides
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ECons (MNum 0) (ENil))))
|
||||
?not_mask_f32_strides)
|
||||
(ICons ?neg_mask (ICons ?one (INil)))))
|
||||
(= ?not_mask_bool (Op (Cast ?size (Bool)) (ICons ?not_mask_f32 (INil))))
|
||||
(= ?not_mask (Op (Cast ?size (F32)) (ICons ?not_mask_bool (INil))))
|
||||
|
||||
(= ?positive (Op (Mul
|
||||
?shape
|
||||
?not_mask_f32_strides
|
||||
?matmul_strides
|
||||
?positive_strides)
|
||||
(ICons ?not_mask (ICons ?matmul (INil)))))
|
||||
(= ?relu (Op (Add
|
||||
?shape
|
||||
?zeroed_strides
|
||||
?positive_strides
|
||||
?relu_strides)
|
||||
(ICons ?zeroed (ICons ?positive (INil)))))
|
||||
)
|
||||
(
|
||||
(let ?fused (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?c_order ?d_order
|
||||
?lda ?ldb ?ldc ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype (F32)
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 "RELU")
|
||||
(ICons ?a (ICons ?b ?matmul_tail))))
|
||||
(union ?relu ?fused)
|
||||
(set (dtype ?fused) (F32))
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt batched relu epilogue"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?matmul (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?c_order ?d_order
|
||||
?lda ?ldb ?ldc ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype (F32)
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 "BIAS")
|
||||
(ICons ?a (ICons ?b ?matmul_tail))))
|
||||
|
||||
(= ?zero (Op (Constant 0.0) (INil)))
|
||||
(= ?neg_one (Op (Constant -1.0) (INil)))
|
||||
(= ?one (Op (Constant 1.0) (INil)))
|
||||
|
||||
(= ?lt (Op (LessThan
|
||||
?shape
|
||||
?matmul_strides
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ENil)))
|
||||
?mask_strides)
|
||||
(ICons ?matmul (ICons ?zero (INil)))))
|
||||
(= ?lt_f32 (Op (Cast ?size (F32)) (ICons ?lt (INil))))
|
||||
|
||||
(= ?zeroed (Op (Mul
|
||||
?shape
|
||||
?mask_strides
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ENil)))
|
||||
?zeroed_strides)
|
||||
(ICons ?lt_f32 (ICons ?zero (INil)))))
|
||||
|
||||
(= ?neg_mask (Op (Mul
|
||||
?shape
|
||||
?mask_strides
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ENil)))
|
||||
?neg_mask_strides)
|
||||
(ICons ?lt_f32 (ICons ?neg_one (INil)))))
|
||||
(= ?not_mask_f32 (Op (Add
|
||||
?shape
|
||||
?neg_mask_strides
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ENil)))
|
||||
?not_mask_f32_strides)
|
||||
(ICons ?neg_mask (ICons ?one (INil)))))
|
||||
(= ?not_mask_bool (Op (Cast ?size (Bool)) (ICons ?not_mask_f32 (INil))))
|
||||
(= ?not_mask (Op (Cast ?size (F32)) (ICons ?not_mask_bool (INil))))
|
||||
|
||||
(= ?positive (Op (Mul
|
||||
?shape
|
||||
?not_mask_f32_strides
|
||||
?matmul_strides
|
||||
?positive_strides)
|
||||
(ICons ?not_mask (ICons ?matmul (INil)))))
|
||||
(= ?relu (Op (Add
|
||||
?shape
|
||||
?zeroed_strides
|
||||
?positive_strides
|
||||
?relu_strides)
|
||||
(ICons ?zeroed (ICons ?positive (INil)))))
|
||||
)
|
||||
(
|
||||
(let ?fused (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?c_order ?d_order
|
||||
?lda ?ldb ?ldc ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype (F32)
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 "RELU_BIAS")
|
||||
(ICons ?a (ICons ?b ?matmul_tail))))
|
||||
(union ?relu ?fused)
|
||||
(set (dtype ?fused) (F32))
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt 2d relu bias epilogue"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?matmul (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?c_order ?d_order
|
||||
?lda ?ldb ?ldc ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype (F32)
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 "BIAS")
|
||||
(ICons ?a (ICons ?b ?matmul_tail))))
|
||||
|
||||
(= ?zero (Op (Constant 0.0) (INil)))
|
||||
(= ?neg_one (Op (Constant -1.0) (INil)))
|
||||
(= ?one (Op (Constant 1.0) (INil)))
|
||||
|
||||
(= ?lt (Op (LessThan
|
||||
?shape
|
||||
?matmul_strides
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ECons (MNum 0) (ENil))))
|
||||
?mask_strides)
|
||||
(ICons ?matmul (ICons ?zero (INil)))))
|
||||
(= ?lt_f32 (Op (Cast ?size (F32)) (ICons ?lt (INil))))
|
||||
|
||||
(= ?zeroed (Op (Mul
|
||||
?shape
|
||||
?mask_strides
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ECons (MNum 0) (ENil))))
|
||||
?zeroed_strides)
|
||||
(ICons ?lt_f32 (ICons ?zero (INil)))))
|
||||
|
||||
(= ?neg_mask (Op (Mul
|
||||
?shape
|
||||
?mask_strides
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ECons (MNum 0) (ENil))))
|
||||
?neg_mask_strides)
|
||||
(ICons ?lt_f32 (ICons ?neg_one (INil)))))
|
||||
(= ?not_mask_f32 (Op (Add
|
||||
?shape
|
||||
?neg_mask_strides
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ECons (MNum 0) (ENil))))
|
||||
?not_mask_f32_strides)
|
||||
(ICons ?neg_mask (ICons ?one (INil)))))
|
||||
(= ?not_mask_bool (Op (Cast ?size (Bool)) (ICons ?not_mask_f32 (INil))))
|
||||
(= ?not_mask (Op (Cast ?size (F32)) (ICons ?not_mask_bool (INil))))
|
||||
|
||||
(= ?positive (Op (Mul
|
||||
?shape
|
||||
?not_mask_f32_strides
|
||||
?matmul_strides
|
||||
?positive_strides)
|
||||
(ICons ?not_mask (ICons ?matmul (INil)))))
|
||||
(= ?relu (Op (Add
|
||||
?shape
|
||||
?zeroed_strides
|
||||
?positive_strides
|
||||
?relu_strides)
|
||||
(ICons ?zeroed (ICons ?positive (INil)))))
|
||||
)
|
||||
(
|
||||
(let ?fused (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?c_order ?d_order
|
||||
?lda ?ldb ?ldc ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype (F32)
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 "RELU_BIAS")
|
||||
(ICons ?a (ICons ?b ?matmul_tail))))
|
||||
(union ?relu ?fused)
|
||||
(set (dtype ?fused) (F32))
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt batched relu bias epilogue"
|
||||
)
|
||||
|
||||
; Canonical tanh-approx GELU can also appear directly as:
|
||||
;
|
||||
; x * sigmoid(1.5957691216 * x * (1 + 0.044715 * x * x))
|
||||
;
|
||||
; Match that sigmoid form and fuse it into the cuBLASLt GELU epilogues.
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?matmul (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?c_order ?d_order
|
||||
?lda ?ldb ?ldc ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype (F32)
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 "DEFAULT")
|
||||
(ICons ?a (ICons ?b ?matmul_tail))))
|
||||
|
||||
(= ?gelu_coeff_inner (Op (Constant 0.044715) (INil)))
|
||||
(= ?gelu_inner_scaled (Op (Mul ?gelu_inner_scaled_shape ?gelu_inner_scaled_a_stride ?gelu_inner_scaled_b_stride ?gelu_inner_scaled_out_stride) (ICons ?matmul (ICons ?gelu_coeff_inner (INil)))))
|
||||
(= ?gelu_inner_quad (Op (Mul ?gelu_inner_quad_shape ?gelu_inner_quad_a_stride ?gelu_inner_quad_b_stride ?gelu_inner_quad_out_stride) (ICons ?gelu_inner_scaled (ICons ?matmul (INil)))))
|
||||
(= ?gelu_one (Op (Constant 1.000000) (INil)))
|
||||
(= ?gelu_poly (Op (Add ?gelu_poly_shape ?gelu_poly_a_stride ?gelu_poly_b_stride ?gelu_poly_out_stride) (ICons ?gelu_inner_quad (ICons ?gelu_one (INil)))))
|
||||
(= ?gelu_coeff_outer (Op (Constant 1.595769) (INil)))
|
||||
(= ?gelu_outer_scaled (Op (Mul ?gelu_outer_scaled_shape ?gelu_outer_scaled_a_stride ?gelu_outer_scaled_b_stride ?gelu_outer_scaled_out_stride) (ICons ?matmul (ICons ?gelu_coeff_outer (INil)))))
|
||||
(= ?gelu_scaled (Op (Mul ?gelu_scaled_shape ?gelu_scaled_a_stride ?gelu_scaled_b_stride ?gelu_scaled_out_stride) (ICons ?gelu_outer_scaled (ICons ?gelu_poly (INil)))))
|
||||
(= ?neg1 (Op (Constant -1.000000) (INil)))
|
||||
(= ?gelu_neg (Op (Mul ?gelu_neg_shape ?gelu_neg_a_stride ?gelu_neg_b_stride ?gelu_neg_out_stride) (ICons ?gelu_scaled (ICons ?neg1 (INil)))))
|
||||
(= ?log2e (Op (Constant 1.442695) (INil)))
|
||||
(= ?gelu_exp_scaled (Op (Mul ?gelu_exp_scaled_shape ?gelu_exp_scaled_a_stride ?gelu_exp_scaled_b_stride ?gelu_exp_scaled_out_stride) (ICons ?gelu_neg (ICons ?log2e (INil)))))
|
||||
(= ?gelu_exp2_val (Op (Exp2 ?gelu_exp_shape ?gelu_exp_in_stride ?gelu_exp_out_stride) (ICons ?gelu_exp_scaled (INil))))
|
||||
(= ?gelu_plus1 (Op (Add ?gelu_plus1_shape ?gelu_plus1_a_stride ?gelu_plus1_b_stride ?gelu_plus1_out_stride) (ICons ?gelu_exp2_val (ICons ?gelu_one (INil)))))
|
||||
(= ?gelu_sigmoid (Op (Recip ?gelu_sigmoid_shape ?gelu_sigmoid_in_stride ?gelu_sigmoid_out_stride) (ICons ?gelu_plus1 (INil))))
|
||||
(= ?gelu_out (Op (Mul ?gelu_out_shape ?gelu_out_a_stride ?gelu_out_b_stride ?gelu_out_out_stride) (ICons ?matmul (ICons ?gelu_sigmoid (INil)))))
|
||||
)
|
||||
(
|
||||
(let ?fused (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?c_order ?d_order
|
||||
?lda ?ldb ?ldc ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype (F32)
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 "GELU")
|
||||
(ICons ?a (ICons ?b ?matmul_tail))))
|
||||
(union ?gelu_out ?fused)
|
||||
(set (dtype ?fused) (F32))
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt gelu epilogue"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?matmul (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?c_order ?d_order
|
||||
?lda ?ldb ?ldc ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype (F32)
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 "BIAS")
|
||||
(ICons ?a (ICons ?b ?matmul_tail))))
|
||||
|
||||
(= ?gelu_coeff_inner (Op (Constant 0.044715) (INil)))
|
||||
(= ?gelu_inner_scaled (Op (Mul ?gelu_inner_scaled_shape ?gelu_inner_scaled_a_stride ?gelu_inner_scaled_b_stride ?gelu_inner_scaled_out_stride) (ICons ?matmul (ICons ?gelu_coeff_inner (INil)))))
|
||||
(= ?gelu_inner_quad (Op (Mul ?gelu_inner_quad_shape ?gelu_inner_quad_a_stride ?gelu_inner_quad_b_stride ?gelu_inner_quad_out_stride) (ICons ?gelu_inner_scaled (ICons ?matmul (INil)))))
|
||||
(= ?gelu_one (Op (Constant 1.000000) (INil)))
|
||||
(= ?gelu_poly (Op (Add ?gelu_poly_shape ?gelu_poly_a_stride ?gelu_poly_b_stride ?gelu_poly_out_stride) (ICons ?gelu_inner_quad (ICons ?gelu_one (INil)))))
|
||||
(= ?gelu_coeff_outer (Op (Constant 1.595769) (INil)))
|
||||
(= ?gelu_outer_scaled (Op (Mul ?gelu_outer_scaled_shape ?gelu_outer_scaled_a_stride ?gelu_outer_scaled_b_stride ?gelu_outer_scaled_out_stride) (ICons ?matmul (ICons ?gelu_coeff_outer (INil)))))
|
||||
(= ?gelu_scaled (Op (Mul ?gelu_scaled_shape ?gelu_scaled_a_stride ?gelu_scaled_b_stride ?gelu_scaled_out_stride) (ICons ?gelu_outer_scaled (ICons ?gelu_poly (INil)))))
|
||||
(= ?neg1 (Op (Constant -1.000000) (INil)))
|
||||
(= ?gelu_neg (Op (Mul ?gelu_neg_shape ?gelu_neg_a_stride ?gelu_neg_b_stride ?gelu_neg_out_stride) (ICons ?gelu_scaled (ICons ?neg1 (INil)))))
|
||||
(= ?log2e (Op (Constant 1.442695) (INil)))
|
||||
(= ?gelu_exp_scaled (Op (Mul ?gelu_exp_scaled_shape ?gelu_exp_scaled_a_stride ?gelu_exp_scaled_b_stride ?gelu_exp_scaled_out_stride) (ICons ?gelu_neg (ICons ?log2e (INil)))))
|
||||
(= ?gelu_exp2_val (Op (Exp2 ?gelu_exp_shape ?gelu_exp_in_stride ?gelu_exp_out_stride) (ICons ?gelu_exp_scaled (INil))))
|
||||
(= ?gelu_plus1 (Op (Add ?gelu_plus1_shape ?gelu_plus1_a_stride ?gelu_plus1_b_stride ?gelu_plus1_out_stride) (ICons ?gelu_exp2_val (ICons ?gelu_one (INil)))))
|
||||
(= ?gelu_sigmoid (Op (Recip ?gelu_sigmoid_shape ?gelu_sigmoid_in_stride ?gelu_sigmoid_out_stride) (ICons ?gelu_plus1 (INil))))
|
||||
(= ?gelu_out (Op (Mul ?gelu_out_shape ?gelu_out_a_stride ?gelu_out_b_stride ?gelu_out_out_stride) (ICons ?matmul (ICons ?gelu_sigmoid (INil)))))
|
||||
)
|
||||
(
|
||||
(let ?fused (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?c_order ?d_order
|
||||
?lda ?ldb ?ldc ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype (F32)
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 "GELU_BIAS")
|
||||
(ICons ?a (ICons ?b ?matmul_tail))))
|
||||
(union ?gelu_out ?fused)
|
||||
(set (dtype ?fused) (F32))
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt gelu bias epilogue"
|
||||
)
|
||||
|
||||
; This first slice fuses column-bias adds into CUBLASLT_EPILOGUE_BIAS for the
|
||||
; older COL-ordered output view. In that view Luminal's logical [m,n] output is
|
||||
; represented as a cuBLASLt [n,m] matrix, so cuBLASLt's row-broadcast bias maps
|
||||
; to the common logical column bias of length n.
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?matmul (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?c_order "COL"
|
||||
?lda ?ldb ?ldc ?ldd
|
||||
(MNum 1)
|
||||
?stride_a ?stride_b ?stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 "DEFAULT")
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
|
||||
(= ?add (Op (Add
|
||||
(ECons ?n (ECons ?m (ENil)))
|
||||
?matmul_add_strides
|
||||
?bias_add_strides
|
||||
?add_out_strides)
|
||||
(ICons ?matmul (ICons ?bias (INil)))))
|
||||
|
||||
(= ?bias_add_strides (ECons (MNum 0) (ECons (MIter) (ENil))))
|
||||
(= ?matmul_add_strides ?add_out_strides)
|
||||
(= ?d_dtype (dtype ?bias))
|
||||
)
|
||||
(
|
||||
(let ?fused (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?c_order "COL"
|
||||
?lda ?ldb ?ldc ?ldd
|
||||
(MNum 1)
|
||||
?stride_a ?stride_b ?stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 "BIAS")
|
||||
(ICons ?a (ICons ?b (ICons ?bias (INil))))))
|
||||
(union ?add ?fused)
|
||||
(set (dtype ?fused) ?d_dtype)
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt 2d matmul plus column bias epilogue"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?matmul (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?c_order "COL"
|
||||
?lda ?ldb ?ldc ?ldd
|
||||
(MNum 1)
|
||||
?stride_a ?stride_b ?stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 "DEFAULT")
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
|
||||
(= ?add (Op (Add
|
||||
(ECons ?n (ECons ?m (ENil)))
|
||||
?bias_add_strides
|
||||
?matmul_add_strides
|
||||
?add_out_strides)
|
||||
(ICons ?bias (ICons ?matmul (INil)))))
|
||||
|
||||
(= ?bias_add_strides (ECons (MNum 0) (ECons (MIter) (ENil))))
|
||||
(= ?matmul_add_strides ?add_out_strides)
|
||||
(= ?d_dtype (dtype ?bias))
|
||||
)
|
||||
(
|
||||
(let ?fused (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?c_order "COL"
|
||||
?lda ?ldb ?ldc ?ldd
|
||||
(MNum 1)
|
||||
?stride_a ?stride_b ?stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 "BIAS")
|
||||
(ICons ?a (ICons ?b (ICons ?bias (INil))))))
|
||||
(union ?add ?fused)
|
||||
(set (dtype ?fused) ?d_dtype)
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt 2d column bias plus matmul epilogue"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?matmul (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?c_order "COL"
|
||||
?lda ?ldb ?ldc ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 "DEFAULT")
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
|
||||
(= ?add (Op (Add
|
||||
(ECons ?batch (ECons ?n (ECons ?m (ENil))))
|
||||
?matmul_add_strides
|
||||
?bias_add_strides
|
||||
?add_out_strides)
|
||||
(ICons ?matmul (ICons ?bias (INil)))))
|
||||
|
||||
(= ?bias_add_strides (ECons (MNum 0) (ECons (MNum 0) (ECons (MIter) (ENil)))))
|
||||
(= ?matmul_add_strides ?add_out_strides)
|
||||
(= ?d_dtype (dtype ?bias))
|
||||
)
|
||||
(
|
||||
(let ?fused (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?c_order "COL"
|
||||
?lda ?ldb ?ldc ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 "BIAS")
|
||||
(ICons ?a (ICons ?b (ICons ?bias (INil))))))
|
||||
(union ?add ?fused)
|
||||
(set (dtype ?fused) ?d_dtype)
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt batched matmul plus column bias epilogue"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?matmul (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?c_order "COL"
|
||||
?lda ?ldb ?ldc ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 "DEFAULT")
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
|
||||
(= ?add (Op (Add
|
||||
(ECons ?batch (ECons ?n (ECons ?m (ENil))))
|
||||
?bias_add_strides
|
||||
?matmul_add_strides
|
||||
?add_out_strides)
|
||||
(ICons ?bias (ICons ?matmul (INil)))))
|
||||
|
||||
(= ?bias_add_strides (ECons (MNum 0) (ECons (MNum 0) (ECons (MIter) (ENil)))))
|
||||
(= ?matmul_add_strides ?add_out_strides)
|
||||
(= ?d_dtype (dtype ?bias))
|
||||
)
|
||||
(
|
||||
(let ?fused (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?c_order "COL"
|
||||
?lda ?ldb ?ldc ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 "BIAS")
|
||||
(ICons ?a (ICons ?b (ICons ?bias (INil))))))
|
||||
(union ?add ?fused)
|
||||
(set (dtype ?fused) ?d_dtype)
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt batched column bias plus matmul epilogue"
|
||||
)
|
||||
@@ -0,0 +1,811 @@
|
||||
; FP8 support is narrower than "any FP8 x any FP8". cuBLASLt's regular FP8
|
||||
; matmul table supports these A/B descriptor pairs for F32 outputs:
|
||||
; E4M3 x E4M3
|
||||
; E4M3 x E5M2
|
||||
; E5M2 x E4M3
|
||||
; and requires TN format on Ada/Hopper-class GPUs. These rules therefore match
|
||||
; row-major x column-major Luminal matmuls, which the existing COL-order lowering
|
||||
; describes as descriptor A = logical B, descriptor B = logical A, transa=T,
|
||||
; transb=N.
|
||||
|
||||
(rule
|
||||
(
|
||||
; Match the scaled FP8 linear form directly before the unscaled FP8
|
||||
; matmul rewrite can hide the quantize/dequant scale structure.
|
||||
(= ?scaled_activation (Op (Mul
|
||||
?activation_shape
|
||||
?raw_activation_strides
|
||||
?recip_activation_strides
|
||||
?activation_out_strides)
|
||||
(ICons ?raw_activation (ICons ?recip_input_scale (INil)))))
|
||||
(= ?recip_input_scale (Op (Recip
|
||||
?activation_shape
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ENil)))
|
||||
?recip_out_strides)
|
||||
(ICons ?input_scale (INil))))
|
||||
(= ?a (Op (Cast ?a_size ?a_dtype) (ICons ?scaled_activation (INil))))
|
||||
|
||||
(= ?sum (Op (GenericMatmul
|
||||
?out_shape ?mul_shape ?k
|
||||
?a_stride ?b_stride
|
||||
?sum_in_stride ?k_stride ?sum_out_stride
|
||||
?matmul_dtype)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
(= ?cast (Op (Cast ?size (F32)) (ICons ?sum (INil))))
|
||||
(= ?scale_product (Op (Mul (ENil) (ENil) (ENil) (ENil))
|
||||
(ICons ?input_scale (ICons ?weight_scale (INil)))))
|
||||
(= ?scaled (Op (Mul
|
||||
?out_shape
|
||||
?cast_strides
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ENil)))
|
||||
?scaled_out_strides)
|
||||
(ICons ?cast (ICons ?scale_product (INil)))))
|
||||
(= ?cast_strides ?scaled_out_strides)
|
||||
|
||||
(= ?out_shape (ECons ?m (ECons ?n (ENil))))
|
||||
(!= ?m (MNum 0))
|
||||
(!= ?n (MNum 0))
|
||||
(!= ?k (MNum 1))
|
||||
|
||||
(= ?a_stride (ECons ?a_m_stride (ECons ?a_n_stride (ECons ?a_k_stride (ENil)))))
|
||||
(= ?b_stride (ECons ?b_m_stride (ECons ?b_n_stride (ECons ?b_k_stride (ENil)))))
|
||||
(= ?k_stride (MIter))
|
||||
|
||||
(= ?a_m_stride (MMul (MIter) ?k))
|
||||
(= ?a_n_stride (MNum 0))
|
||||
(= ?a_k_stride (MIter))
|
||||
|
||||
(= ?b_m_stride (MNum 0))
|
||||
(= ?b_n_stride (MMul (MIter) ?k))
|
||||
(= ?b_k_stride (MIter))
|
||||
|
||||
(= ?b_dtype (dtype ?b))
|
||||
(cublaslt_fp8_f32_output_pair ?a_dtype ?b_dtype)
|
||||
)
|
||||
(
|
||||
(let ?sgemm (Op (cublaslt_scaled
|
||||
?n ?m ?k
|
||||
"T" "N"
|
||||
"COL" "COL" "COL" "COL"
|
||||
?b_n_stride
|
||||
?a_m_stride
|
||||
?n
|
||||
?n
|
||||
(MNum 1)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
?b_dtype ?a_dtype (F32) (F32) "32F" "F32" 1.0 0.0 "DEFAULT")
|
||||
(ICons ?b (ICons ?a (ICons ?weight_scale (ICons ?input_scale (INil)))))))
|
||||
(union ?scaled ?sgemm)
|
||||
(set (dtype ?sgemm) (F32))
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt scaled fp8 row-major x column-major f32 output"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?scaled_activation (Op (Mul
|
||||
?activation_shape
|
||||
?raw_activation_strides
|
||||
?recip_activation_strides
|
||||
?activation_out_strides)
|
||||
(ICons ?raw_activation (ICons ?recip_input_scale (INil)))))
|
||||
(= ?recip_input_scale (Op (Recip
|
||||
?activation_shape
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ENil)))
|
||||
?recip_out_strides)
|
||||
(ICons ?input_scale (INil))))
|
||||
(= ?a (Op (Cast ?a_size ?a_dtype) (ICons ?scaled_activation (INil))))
|
||||
|
||||
(= ?sum (Op (GenericMatmul
|
||||
?out_shape ?mul_shape ?k
|
||||
?a_stride ?b_stride
|
||||
?sum_in_stride ?k_stride ?sum_out_stride
|
||||
?matmul_dtype)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
(= ?cast (Op (Cast ?size (F32)) (ICons ?sum (INil))))
|
||||
(= ?scale_product (Op (Mul (ENil) (ENil) (ENil) (ENil))
|
||||
(ICons ?input_scale (ICons ?weight_scale (INil)))))
|
||||
(= ?scaled (Op (Mul
|
||||
?out_shape
|
||||
?cast_strides
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ENil)))
|
||||
?scaled_out_strides)
|
||||
(ICons ?cast (ICons ?scale_product (INil)))))
|
||||
(= ?cast_strides ?scaled_out_strides)
|
||||
|
||||
(= ?out_shape (ECons ?m (ECons ?n (ENil))))
|
||||
(!= ?m (MNum 0))
|
||||
(!= ?n (MNum 0))
|
||||
(!= ?k (MNum 1))
|
||||
|
||||
(= ?a_stride (ECons ?a_m_stride (ECons ?a_n_stride (ECons ?a_k_stride (ENil)))))
|
||||
(= ?b_stride (ECons ?b_m_stride (ECons ?b_n_stride (ECons ?b_k_stride (ENil)))))
|
||||
(= ?k_stride (MIter))
|
||||
|
||||
(= ?a_m_stride (MMul (MIter) ?k))
|
||||
(= ?a_n_stride (MNum 0))
|
||||
(= ?a_k_stride (MIter))
|
||||
|
||||
(= ?b_m_stride (MNum 0))
|
||||
(= ?b_n_stride (MMul (MIter) ?k))
|
||||
(= ?b_k_stride (MIter))
|
||||
|
||||
(= ?b_dtype (dtype ?b))
|
||||
(cublaslt_fp8_f32_output_pair ?a_dtype ?b_dtype)
|
||||
(= ?scaled (Op (cublaslt_scaled
|
||||
?n ?m ?k
|
||||
"T" "N"
|
||||
"COL" "COL" "COL" "COL"
|
||||
?b_n_stride
|
||||
?a_m_stride
|
||||
?n
|
||||
?n
|
||||
(MNum 1)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
?b_dtype ?a_dtype (F32) (F32) "32F" "F32" 1.0 0.0 "DEFAULT")
|
||||
(ICons ?b (ICons ?a (ICons ?weight_scale (ICons ?input_scale (INil)))))))
|
||||
(= ?cast (Op (cublaslt
|
||||
?n ?m ?k
|
||||
"T" "N"
|
||||
"COL" "COL" "COL" "COL"
|
||||
?b_n_stride
|
||||
?a_m_stride
|
||||
?n
|
||||
?n
|
||||
(MNum 1)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
?b_dtype ?a_dtype (F32) (F32) "32F" "F32" 1.0 0.0 "DEFAULT")
|
||||
(ICons ?b (ICons ?a (INil)))))
|
||||
)
|
||||
(
|
||||
(delete (Op (Mul
|
||||
?out_shape
|
||||
?cast_strides
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ENil)))
|
||||
?scaled_out_strides)
|
||||
(ICons ?cast (ICons ?scale_product (INil)))))
|
||||
(delete (Op (cublaslt
|
||||
?n ?m ?k
|
||||
"T" "N"
|
||||
"COL" "COL" "COL" "COL"
|
||||
?b_n_stride
|
||||
?a_m_stride
|
||||
?n
|
||||
?n
|
||||
(MNum 1)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
?b_dtype ?a_dtype (F32) (F32) "32F" "F32" 1.0 0.0 "DEFAULT")
|
||||
(ICons ?b (ICons ?a (INil)))))
|
||||
)
|
||||
:ruleset cleanup
|
||||
:name "delete raw fp8 path when scaled cublaslt covers direct output scale"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
; Fusion growth can make the live path consume a raw FP8 cuBLASLt
|
||||
; candidate through an internal CudaBinaryElementwise scale multiply,
|
||||
; instead of the original HLIR output-scale Mul. The scalar scale
|
||||
; product is tensor-wide, so the two scalar factors can be passed as
|
||||
; cuBLASLt A/B scale inputs and the internal multiply can be bypassed.
|
||||
(= ?raw_gemm (Op (cublaslt
|
||||
?cm ?cn ?ck
|
||||
?cta ?ctb
|
||||
?cao ?cbo ?cco ?cdo
|
||||
?clda ?cldb ?cldc ?cldd
|
||||
?cbc ?csa ?csb ?csc ?csd
|
||||
?cadt ?cbdt ?ccdt ?cddt ?ccompute ?cscale ?calpha ?cbeta ?cepilogue)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
(cublaslt_fp8_f32_output_pair ?cadt ?cbdt)
|
||||
(= ?ccdt (F32))
|
||||
(= ?cddt (F32))
|
||||
(= ?cbeta 0.0)
|
||||
(= ?cepilogue "DEFAULT")
|
||||
|
||||
(= ?fs_cast (Op (FusionStart
|
||||
?out_shape
|
||||
?cast_strides
|
||||
(F32))
|
||||
(ICons ?raw_gemm (INil))))
|
||||
|
||||
(= ?out_shape (ECons ?out_m (ECons ?out_n (ENil))))
|
||||
(= ?scale_strides (ECons (MNum 0) (ECons (MNum 0) (ENil))))
|
||||
|
||||
(= ?fs_a_scale (Op (FusionStart (ENil) (ENil) (F32))
|
||||
(ICons ?a_scale (INil))))
|
||||
(= ?fs_b_scale (Op (FusionStart (ENil) (ENil) (F32))
|
||||
(ICons ?b_scale (INil))))
|
||||
(= ?scale_product_inner (Op (CudaBinaryElementwise
|
||||
"Mul"
|
||||
(ENil)
|
||||
(ENil)
|
||||
(ENil)
|
||||
(ENil)
|
||||
(F32))
|
||||
(ICons ?fs_a_scale (ICons ?fs_b_scale (INil)))))
|
||||
(= ?scale_product (Op (FusionEnd (ENil) (ENil) (F32))
|
||||
(ICons ?scale_product_inner (INil))))
|
||||
(= ?fs_scale (Op (FusionStart
|
||||
?out_shape
|
||||
?scale_strides
|
||||
(F32))
|
||||
(ICons ?scale_product (INil))))
|
||||
(= ?fused_scale (Op (CudaBinaryElementwise
|
||||
"Mul"
|
||||
?out_shape
|
||||
?cast_strides
|
||||
?scale_strides
|
||||
?scaled_out_strides
|
||||
(F32))
|
||||
(ICons ?fs_cast (ICons ?fs_scale (INil)))))
|
||||
(= ?cast_strides ?scaled_out_strides)
|
||||
)
|
||||
(
|
||||
(let ?sgemm (Op (cublaslt_scaled
|
||||
?cm ?cn ?ck
|
||||
?cta ?ctb
|
||||
?cao ?cbo ?cco ?cdo
|
||||
?clda ?cldb ?cldc ?cldd
|
||||
?cbc ?csa ?csb ?csc ?csd
|
||||
?cadt ?cbdt ?ccdt ?cddt ?ccompute ?cscale ?calpha ?cbeta ?cepilogue)
|
||||
(ICons ?a (ICons ?b (ICons ?a_scale (ICons ?b_scale (INil)))))))
|
||||
(let ?fs_sgemm (Op (FusionStart ?out_shape ?scaled_out_strides (F32))
|
||||
(ICons ?sgemm (INil))))
|
||||
(union ?fused_scale ?fs_sgemm)
|
||||
(set (dtype ?sgemm) (F32))
|
||||
(set (dtype ?fs_sgemm) (F32))
|
||||
)
|
||||
:ruleset fusion_grow
|
||||
:name "cublaslt scaled fp8 fused output-scale f32 output"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?raw_gemm (Op (cublaslt
|
||||
?cm ?cn ?ck
|
||||
?cta ?ctb
|
||||
?cao ?cbo ?cco ?cdo
|
||||
?clda ?cldb ?cldc ?cldd
|
||||
?cbc ?csa ?csb ?csc ?csd
|
||||
?cadt ?cbdt ?ccdt ?cddt ?ccompute ?cscale ?calpha ?cbeta ?cepilogue)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
(cublaslt_fp8_f32_output_pair ?cadt ?cbdt)
|
||||
(= ?ccdt (F32))
|
||||
(= ?cddt (F32))
|
||||
(= ?cbeta 0.0)
|
||||
(= ?cepilogue "DEFAULT")
|
||||
|
||||
(= ?fs_cast (Op (FusionStart
|
||||
?out_shape
|
||||
?cast_strides
|
||||
(F32))
|
||||
(ICons ?raw_gemm (INil))))
|
||||
|
||||
(= ?out_shape (ECons ?out_m (ECons ?out_n (ENil))))
|
||||
(= ?scale_strides (ECons (MNum 0) (ECons (MNum 0) (ENil))))
|
||||
|
||||
(= ?fs_a_scale (Op (FusionStart (ENil) (ENil) (F32))
|
||||
(ICons ?a_scale (INil))))
|
||||
(= ?fs_b_scale (Op (FusionStart (ENil) (ENil) (F32))
|
||||
(ICons ?b_scale (INil))))
|
||||
(= ?scale_product_inner (Op (CudaBinaryElementwise
|
||||
"Mul"
|
||||
(ENil)
|
||||
(ENil)
|
||||
(ENil)
|
||||
(ENil)
|
||||
(F32))
|
||||
(ICons ?fs_a_scale (ICons ?fs_b_scale (INil)))))
|
||||
(= ?scale_product (Op (FusionEnd (ENil) (ENil) (F32))
|
||||
(ICons ?scale_product_inner (INil))))
|
||||
(= ?fs_scale (Op (FusionStart
|
||||
?out_shape
|
||||
?scale_strides
|
||||
(F32))
|
||||
(ICons ?scale_product (INil))))
|
||||
(= ?fused_scale (Op (CudaBinaryElementwise
|
||||
"Mul"
|
||||
?out_shape
|
||||
?cast_strides
|
||||
?scale_strides
|
||||
?scaled_out_strides
|
||||
(F32))
|
||||
(ICons ?fs_cast (ICons ?fs_scale (INil)))))
|
||||
(= ?cast_strides ?scaled_out_strides)
|
||||
|
||||
(= ?sgemm (Op (cublaslt_scaled
|
||||
?cm ?cn ?ck
|
||||
?cta ?ctb
|
||||
?cao ?cbo ?cco ?cdo
|
||||
?clda ?cldb ?cldc ?cldd
|
||||
?cbc ?csa ?csb ?csc ?csd
|
||||
?cadt ?cbdt ?ccdt ?cddt ?ccompute ?cscale ?calpha ?cbeta ?cepilogue)
|
||||
(ICons ?a (ICons ?b (ICons ?a_scale (ICons ?b_scale (INil)))))))
|
||||
(= ?fused_scale (Op (FusionStart ?out_shape ?scaled_out_strides (F32))
|
||||
(ICons ?sgemm (INil))))
|
||||
)
|
||||
(
|
||||
(delete (Op (cublaslt
|
||||
?cm ?cn ?ck
|
||||
?cta ?ctb
|
||||
?cao ?cbo ?cco ?cdo
|
||||
?clda ?cldb ?cldc ?cldd
|
||||
?cbc ?csa ?csb ?csc ?csd
|
||||
?cadt ?cbdt ?ccdt ?cddt ?ccompute ?cscale ?calpha ?cbeta ?cepilogue)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
(delete (Op (CudaBinaryElementwise
|
||||
"Mul"
|
||||
?out_shape
|
||||
?cast_strides
|
||||
?scale_strides
|
||||
?scaled_out_strides
|
||||
(F32))
|
||||
(ICons ?fs_cast (ICons ?fs_scale (INil)))))
|
||||
)
|
||||
:ruleset cleanup
|
||||
:name "delete raw fp8 path when scaled cublaslt covers fused output scale"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
; Batched form of the scaled FP8 linear rewrite. The scale operands are
|
||||
; scalar tensors expanded across the last three output/activation axes.
|
||||
(= ?scaled_activation (Op (Mul
|
||||
?activation_shape
|
||||
?raw_activation_strides
|
||||
?recip_activation_strides
|
||||
?activation_out_strides)
|
||||
(ICons ?raw_activation (ICons ?recip_input_scale (INil)))))
|
||||
(= ?recip_input_scale (Op (Recip
|
||||
?activation_shape
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ECons (MNum 0) (ENil))))
|
||||
?recip_out_strides)
|
||||
(ICons ?input_scale (INil))))
|
||||
(= ?a (Op (Cast ?a_size ?a_dtype) (ICons ?scaled_activation (INil))))
|
||||
|
||||
(= ?sum (Op (GenericMatmul
|
||||
?out_shape ?mul_shape ?k
|
||||
?a_stride ?b_stride
|
||||
?sum_in_stride ?k_stride ?sum_out_stride
|
||||
?matmul_dtype)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
(= ?cast (Op (Cast ?size (F32)) (ICons ?sum (INil))))
|
||||
(= ?scale_product (Op (Mul (ENil) (ENil) (ENil) (ENil))
|
||||
(ICons ?input_scale (ICons ?weight_scale (INil)))))
|
||||
(= ?scaled (Op (Mul
|
||||
?out_shape
|
||||
?cast_strides
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ECons (MNum 0) (ENil))))
|
||||
?scaled_out_strides)
|
||||
(ICons ?cast (ICons ?scale_product (INil)))))
|
||||
(= ?cast_strides ?scaled_out_strides)
|
||||
|
||||
(= ?batch (nth_from_end ?out_shape 2))
|
||||
(= ?m (nth_from_end ?out_shape 1))
|
||||
(= ?n (nth_from_end ?out_shape 0))
|
||||
(!= ?m (MNum 0))
|
||||
(!= ?n (MNum 0))
|
||||
(!= ?k (MNum 1))
|
||||
(!= ?batch (MNum 0))
|
||||
|
||||
(= ?a_batch_stride (nth_from_end ?a_stride 3))
|
||||
(= ?a_m_stride (nth_from_end ?a_stride 2))
|
||||
(= ?a_n_stride (nth_from_end ?a_stride 1))
|
||||
(= ?a_k_stride (nth_from_end ?a_stride 0))
|
||||
|
||||
(= ?b_batch_stride (nth_from_end ?b_stride 3))
|
||||
(= ?b_m_stride (nth_from_end ?b_stride 2))
|
||||
(= ?b_n_stride (nth_from_end ?b_stride 1))
|
||||
(= ?b_k_stride (nth_from_end ?b_stride 0))
|
||||
|
||||
(= ?k_stride (MIter))
|
||||
|
||||
(= ?a_k_stride (MIter))
|
||||
(= ?a_n_stride (MNum 0))
|
||||
(= ?a_m_stride (MMul (MIter) ?k))
|
||||
|
||||
(= ?b_k_stride (MIter))
|
||||
(= ?b_m_stride (MNum 0))
|
||||
(= ?b_n_stride (MMul (MIter) ?k))
|
||||
|
||||
(= ?a_batch_stride (MMul ?m ?a_m_stride))
|
||||
(= ?b_batch_stride (MMul ?n ?b_n_stride))
|
||||
|
||||
(= ?b_dtype (dtype ?b))
|
||||
(cublaslt_fp8_f32_output_pair ?a_dtype ?b_dtype)
|
||||
)
|
||||
(
|
||||
(let ?sgemm (Op (cublaslt_scaled
|
||||
?n ?m ?k
|
||||
"T" "N"
|
||||
"COL" "COL" "COL" "COL"
|
||||
?b_n_stride
|
||||
?a_m_stride
|
||||
?n
|
||||
?n
|
||||
?batch
|
||||
?b_batch_stride
|
||||
?a_batch_stride
|
||||
(MMul ?m ?n)
|
||||
(MMul ?m ?n)
|
||||
?b_dtype ?a_dtype (F32) (F32) "32F" "F32" 1.0 0.0 "DEFAULT")
|
||||
(ICons ?b (ICons ?a (ICons ?weight_scale (ICons ?input_scale (INil)))))))
|
||||
(union ?scaled ?sgemm)
|
||||
(set (dtype ?sgemm) (F32))
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt scaled fp8 batched row-major x column-major f32 output"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?sum (Op (GenericMatmul
|
||||
?out_shape ?mul_shape ?k
|
||||
?a_stride ?b_stride
|
||||
?sum_in_stride ?k_stride ?sum_out_stride
|
||||
?matmul_dtype)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
(= ?cast (Op (Cast ?size (F32)) (ICons ?sum (INil))))
|
||||
|
||||
(= ?out_shape (ECons ?m (ECons ?n (ENil))))
|
||||
(!= ?m (MNum 0))
|
||||
(!= ?n (MNum 0))
|
||||
(!= ?k (MNum 1))
|
||||
|
||||
(= ?a_stride (ECons ?a_m_stride (ECons ?a_n_stride (ECons ?a_k_stride (ENil)))))
|
||||
(= ?b_stride (ECons ?b_m_stride (ECons ?b_n_stride (ECons ?b_k_stride (ENil)))))
|
||||
(= ?k_stride (MIter))
|
||||
|
||||
(= ?a_m_stride (MMul (MIter) ?k))
|
||||
(= ?a_n_stride (MNum 0))
|
||||
(= ?a_k_stride (MIter))
|
||||
|
||||
(= ?b_m_stride (MNum 0))
|
||||
(= ?b_n_stride (MMul (MIter) ?k))
|
||||
(= ?b_k_stride (MIter))
|
||||
|
||||
(= (F8E4M3) (dtype ?a))
|
||||
(= (F8E4M3) (dtype ?b))
|
||||
)
|
||||
(
|
||||
(let ?sgemm (Op (cublaslt
|
||||
?n ?m ?k
|
||||
"T" "N"
|
||||
"COL" "COL" "COL" "COL"
|
||||
?b_n_stride
|
||||
?a_m_stride
|
||||
?n
|
||||
?n
|
||||
(MNum 1)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(F8E4M3) (F8E4M3) (F32) (F32) "32F" "F32" 1.0 0.0 "DEFAULT")
|
||||
(ICons ?b (ICons ?a (INil)))))
|
||||
(union ?cast ?sgemm)
|
||||
(set (dtype ?sgemm) (F32))
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt fp8 e4m3/e4m3 row-major x column-major f32 output"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?sum (Op (GenericMatmul
|
||||
?out_shape ?mul_shape ?k
|
||||
?a_stride ?b_stride
|
||||
?sum_in_stride ?k_stride ?sum_out_stride
|
||||
?matmul_dtype)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
(= ?cast (Op (Cast ?size (F32)) (ICons ?sum (INil))))
|
||||
|
||||
(= ?out_shape (ECons ?m (ECons ?n (ENil))))
|
||||
(!= ?m (MNum 0))
|
||||
(!= ?n (MNum 0))
|
||||
(!= ?k (MNum 1))
|
||||
|
||||
(= ?a_stride (ECons ?a_m_stride (ECons ?a_n_stride (ECons ?a_k_stride (ENil)))))
|
||||
(= ?b_stride (ECons ?b_m_stride (ECons ?b_n_stride (ECons ?b_k_stride (ENil)))))
|
||||
(= ?k_stride (MIter))
|
||||
|
||||
(= ?a_m_stride (MMul (MIter) ?k))
|
||||
(= ?a_n_stride (MNum 0))
|
||||
(= ?a_k_stride (MIter))
|
||||
|
||||
(= ?b_m_stride (MNum 0))
|
||||
(= ?b_n_stride (MMul (MIter) ?k))
|
||||
(= ?b_k_stride (MIter))
|
||||
|
||||
(= (F8E4M3) (dtype ?a))
|
||||
(= (F8E5M2) (dtype ?b))
|
||||
)
|
||||
(
|
||||
(let ?sgemm (Op (cublaslt
|
||||
?n ?m ?k
|
||||
"T" "N"
|
||||
"COL" "COL" "COL" "COL"
|
||||
?b_n_stride
|
||||
?a_m_stride
|
||||
?n
|
||||
?n
|
||||
(MNum 1)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(F8E5M2) (F8E4M3) (F32) (F32) "32F" "F32" 1.0 0.0 "DEFAULT")
|
||||
(ICons ?b (ICons ?a (INil)))))
|
||||
(union ?cast ?sgemm)
|
||||
(set (dtype ?sgemm) (F32))
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt fp8 e5m2/e4m3 row-major x column-major f32 output"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?sum (Op (GenericMatmul
|
||||
?out_shape ?mul_shape ?k
|
||||
?a_stride ?b_stride
|
||||
?sum_in_stride ?k_stride ?sum_out_stride
|
||||
?matmul_dtype)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
(= ?cast (Op (Cast ?size (F32)) (ICons ?sum (INil))))
|
||||
|
||||
(= ?out_shape (ECons ?m (ECons ?n (ENil))))
|
||||
(!= ?m (MNum 0))
|
||||
(!= ?n (MNum 0))
|
||||
(!= ?k (MNum 1))
|
||||
|
||||
(= ?a_stride (ECons ?a_m_stride (ECons ?a_n_stride (ECons ?a_k_stride (ENil)))))
|
||||
(= ?b_stride (ECons ?b_m_stride (ECons ?b_n_stride (ECons ?b_k_stride (ENil)))))
|
||||
(= ?k_stride (MIter))
|
||||
|
||||
(= ?a_m_stride (MMul (MIter) ?k))
|
||||
(= ?a_n_stride (MNum 0))
|
||||
(= ?a_k_stride (MIter))
|
||||
|
||||
(= ?b_m_stride (MNum 0))
|
||||
(= ?b_n_stride (MMul (MIter) ?k))
|
||||
(= ?b_k_stride (MIter))
|
||||
|
||||
(= (F8E5M2) (dtype ?a))
|
||||
(= (F8E4M3) (dtype ?b))
|
||||
)
|
||||
(
|
||||
(let ?sgemm (Op (cublaslt
|
||||
?n ?m ?k
|
||||
"T" "N"
|
||||
"COL" "COL" "COL" "COL"
|
||||
?b_n_stride
|
||||
?a_m_stride
|
||||
?n
|
||||
?n
|
||||
(MNum 1)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(F8E4M3) (F8E5M2) (F32) (F32) "32F" "F32" 1.0 0.0 "DEFAULT")
|
||||
(ICons ?b (ICons ?a (INil)))))
|
||||
(union ?cast ?sgemm)
|
||||
(set (dtype ?sgemm) (F32))
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt fp8 e4m3/e5m2 row-major x column-major f32 output"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?sum (Op (GenericMatmul
|
||||
?out_shape ?mul_shape ?k
|
||||
?a_stride ?b_stride
|
||||
?sum_in_stride ?k_stride ?sum_out_stride
|
||||
?matmul_dtype)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
(= ?cast (Op (Cast ?size (F32)) (ICons ?sum (INil))))
|
||||
|
||||
(= ?batch (nth_from_end ?out_shape 2))
|
||||
(= ?m (nth_from_end ?out_shape 1))
|
||||
(= ?n (nth_from_end ?out_shape 0))
|
||||
(!= ?m (MNum 0))
|
||||
(!= ?n (MNum 0))
|
||||
(!= ?k (MNum 1))
|
||||
(!= ?batch (MNum 0))
|
||||
|
||||
(= ?a_batch_stride (nth_from_end ?a_stride 3))
|
||||
(= ?a_m_stride (nth_from_end ?a_stride 2))
|
||||
(= ?a_n_stride (nth_from_end ?a_stride 1))
|
||||
(= ?a_k_stride (nth_from_end ?a_stride 0))
|
||||
|
||||
(= ?b_batch_stride (nth_from_end ?b_stride 3))
|
||||
(= ?b_m_stride (nth_from_end ?b_stride 2))
|
||||
(= ?b_n_stride (nth_from_end ?b_stride 1))
|
||||
(= ?b_k_stride (nth_from_end ?b_stride 0))
|
||||
|
||||
(= ?k_stride (MIter))
|
||||
|
||||
(= ?a_k_stride (MIter))
|
||||
(= ?a_n_stride (MNum 0))
|
||||
(= ?a_m_stride (MMul (MIter) ?k))
|
||||
|
||||
(= ?b_k_stride (MIter))
|
||||
(= ?b_m_stride (MNum 0))
|
||||
(= ?b_n_stride (MMul (MIter) ?k))
|
||||
|
||||
(= ?a_batch_stride (MMul ?m ?a_m_stride))
|
||||
(= ?b_batch_stride (MMul ?n ?b_n_stride))
|
||||
|
||||
(= (F8E4M3) (dtype ?a))
|
||||
(= (F8E4M3) (dtype ?b))
|
||||
)
|
||||
(
|
||||
(let ?sgemm (Op (cublaslt
|
||||
?n ?m ?k
|
||||
"T" "N"
|
||||
"COL" "COL" "COL" "COL"
|
||||
?b_n_stride
|
||||
?a_m_stride
|
||||
?n
|
||||
?n
|
||||
?batch
|
||||
?b_batch_stride
|
||||
?a_batch_stride
|
||||
(MMul ?m ?n)
|
||||
(MMul ?m ?n)
|
||||
(F8E4M3) (F8E4M3) (F32) (F32) "32F" "F32" 1.0 0.0 "DEFAULT")
|
||||
(ICons ?b (ICons ?a (INil)))))
|
||||
(union ?cast ?sgemm)
|
||||
(set (dtype ?sgemm) (F32))
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt fp8 e4m3/e4m3 batched row-major x column-major f32 output"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?sum (Op (GenericMatmul
|
||||
?out_shape ?mul_shape ?k
|
||||
?a_stride ?b_stride
|
||||
?sum_in_stride ?k_stride ?sum_out_stride
|
||||
?matmul_dtype)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
(= ?cast (Op (Cast ?size (F32)) (ICons ?sum (INil))))
|
||||
|
||||
(= ?batch (nth_from_end ?out_shape 2))
|
||||
(= ?m (nth_from_end ?out_shape 1))
|
||||
(= ?n (nth_from_end ?out_shape 0))
|
||||
(!= ?m (MNum 0))
|
||||
(!= ?n (MNum 0))
|
||||
(!= ?k (MNum 1))
|
||||
(!= ?batch (MNum 0))
|
||||
|
||||
(= ?a_batch_stride (nth_from_end ?a_stride 3))
|
||||
(= ?a_m_stride (nth_from_end ?a_stride 2))
|
||||
(= ?a_n_stride (nth_from_end ?a_stride 1))
|
||||
(= ?a_k_stride (nth_from_end ?a_stride 0))
|
||||
|
||||
(= ?b_batch_stride (nth_from_end ?b_stride 3))
|
||||
(= ?b_m_stride (nth_from_end ?b_stride 2))
|
||||
(= ?b_n_stride (nth_from_end ?b_stride 1))
|
||||
(= ?b_k_stride (nth_from_end ?b_stride 0))
|
||||
|
||||
(= ?k_stride (MIter))
|
||||
|
||||
(= ?a_k_stride (MIter))
|
||||
(= ?a_n_stride (MNum 0))
|
||||
(= ?a_m_stride (MMul (MIter) ?k))
|
||||
|
||||
(= ?b_k_stride (MIter))
|
||||
(= ?b_m_stride (MNum 0))
|
||||
(= ?b_n_stride (MMul (MIter) ?k))
|
||||
|
||||
(= ?a_batch_stride (MMul ?m ?a_m_stride))
|
||||
(= ?b_batch_stride (MMul ?n ?b_n_stride))
|
||||
|
||||
(= (F8E4M3) (dtype ?a))
|
||||
(= (F8E5M2) (dtype ?b))
|
||||
)
|
||||
(
|
||||
(let ?sgemm (Op (cublaslt
|
||||
?n ?m ?k
|
||||
"T" "N"
|
||||
"COL" "COL" "COL" "COL"
|
||||
?b_n_stride
|
||||
?a_m_stride
|
||||
?n
|
||||
?n
|
||||
?batch
|
||||
?b_batch_stride
|
||||
?a_batch_stride
|
||||
(MMul ?m ?n)
|
||||
(MMul ?m ?n)
|
||||
(F8E5M2) (F8E4M3) (F32) (F32) "32F" "F32" 1.0 0.0 "DEFAULT")
|
||||
(ICons ?b (ICons ?a (INil)))))
|
||||
(union ?cast ?sgemm)
|
||||
(set (dtype ?sgemm) (F32))
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt fp8 e5m2/e4m3 batched row-major x column-major f32 output"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?sum (Op (GenericMatmul
|
||||
?out_shape ?mul_shape ?k
|
||||
?a_stride ?b_stride
|
||||
?sum_in_stride ?k_stride ?sum_out_stride
|
||||
?matmul_dtype)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
(= ?cast (Op (Cast ?size (F32)) (ICons ?sum (INil))))
|
||||
|
||||
(= ?batch (nth_from_end ?out_shape 2))
|
||||
(= ?m (nth_from_end ?out_shape 1))
|
||||
(= ?n (nth_from_end ?out_shape 0))
|
||||
(!= ?m (MNum 0))
|
||||
(!= ?n (MNum 0))
|
||||
(!= ?k (MNum 1))
|
||||
(!= ?batch (MNum 0))
|
||||
|
||||
(= ?a_batch_stride (nth_from_end ?a_stride 3))
|
||||
(= ?a_m_stride (nth_from_end ?a_stride 2))
|
||||
(= ?a_n_stride (nth_from_end ?a_stride 1))
|
||||
(= ?a_k_stride (nth_from_end ?a_stride 0))
|
||||
|
||||
(= ?b_batch_stride (nth_from_end ?b_stride 3))
|
||||
(= ?b_m_stride (nth_from_end ?b_stride 2))
|
||||
(= ?b_n_stride (nth_from_end ?b_stride 1))
|
||||
(= ?b_k_stride (nth_from_end ?b_stride 0))
|
||||
|
||||
(= ?k_stride (MIter))
|
||||
|
||||
(= ?a_k_stride (MIter))
|
||||
(= ?a_n_stride (MNum 0))
|
||||
(= ?a_m_stride (MMul (MIter) ?k))
|
||||
|
||||
(= ?b_k_stride (MIter))
|
||||
(= ?b_m_stride (MNum 0))
|
||||
(= ?b_n_stride (MMul (MIter) ?k))
|
||||
|
||||
(= ?a_batch_stride (MMul ?m ?a_m_stride))
|
||||
(= ?b_batch_stride (MMul ?n ?b_n_stride))
|
||||
|
||||
(= (F8E5M2) (dtype ?a))
|
||||
(= (F8E4M3) (dtype ?b))
|
||||
)
|
||||
(
|
||||
(let ?sgemm (Op (cublaslt
|
||||
?n ?m ?k
|
||||
"T" "N"
|
||||
"COL" "COL" "COL" "COL"
|
||||
?b_n_stride
|
||||
?a_m_stride
|
||||
?n
|
||||
?n
|
||||
?batch
|
||||
?b_batch_stride
|
||||
?a_batch_stride
|
||||
(MMul ?m ?n)
|
||||
(MMul ?m ?n)
|
||||
(F8E4M3) (F8E5M2) (F32) (F32) "32F" "F32" 1.0 0.0 "DEFAULT")
|
||||
(ICons ?b (ICons ?a (INil)))))
|
||||
(union ?cast ?sgemm)
|
||||
(set (dtype ?sgemm) (F32))
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt fp8 e4m3/e5m2 batched row-major x column-major f32 output"
|
||||
)
|
||||
@@ -0,0 +1,78 @@
|
||||
; Mixed output dtype rewrites for cuBLASLt.
|
||||
;
|
||||
; The first mixed mode we need for low-precision matmuls is:
|
||||
;
|
||||
; D[f32] = A[fp16/bf16] * B[fp16/bf16]
|
||||
;
|
||||
; Luminal graphs express this today as a Cast(F32) around a low-precision
|
||||
; matmul. cuBLASLt can write the f32 output directly, so expose that candidate
|
||||
; before beta fusion tries to consume an f32 C input.
|
||||
;
|
||||
; `?beta = 0.0` guard: with non-zero beta the same `?inputs` C is read at
|
||||
; F32 over a low-precision buffer. Repro: tests/test_bf16_chain_block.py.
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?matmul (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?c_order ?d_order
|
||||
?lda ?ldb ?ldc ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?stride_c ?stride_d
|
||||
(F16) (F16) (F16) (F16)
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 ?epilogue)
|
||||
?inputs))
|
||||
(= ?cast (Op (Cast ?size (F32)) (ICons ?matmul (INil))))
|
||||
)
|
||||
(
|
||||
(let ?fused (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout ?a_order ?b_order ?c_order ?d_order
|
||||
?lda ?ldb ?ldc ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?stride_c ?stride_d
|
||||
(F16) (F16) (F32) (F32)
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 ?epilogue)
|
||||
?inputs))
|
||||
(union ?cast ?fused)
|
||||
(set (dtype ?fused) (F32))
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt f16 matmul cast f32 output"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?matmul (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?c_order ?d_order
|
||||
?lda ?ldb ?ldc ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?stride_c ?stride_d
|
||||
(Bf16) (Bf16) (Bf16) (Bf16)
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 ?epilogue)
|
||||
?inputs))
|
||||
(= ?cast (Op (Cast ?size (F32)) (ICons ?matmul (INil))))
|
||||
)
|
||||
(
|
||||
(let ?fused (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout ?a_order ?b_order ?c_order ?d_order
|
||||
?lda ?ldb ?ldc ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?stride_c ?stride_d
|
||||
(Bf16) (Bf16) (F32) (F32)
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 ?epilogue)
|
||||
?inputs))
|
||||
(union ?cast ?fused)
|
||||
(set (dtype ?fused) (F32))
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt bf16 matmul cast f32 output"
|
||||
)
|
||||
@@ -0,0 +1,484 @@
|
||||
; Natural cuBLASLt row-order output rewrites. These keep Luminal's logical
|
||||
; output C[m,n] as a cuBLASLt ROW-ordered D[m,n] instead of using the older
|
||||
; swapped COL-ordered D[n,m] view. A and B orders mirror their matched logical
|
||||
; layouts, so this family is the legal base for future ROW-ordered beta fusions.
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?sum (Op (GenericMatmul
|
||||
?out_shape ?mul_shape ?k
|
||||
?a_stride ?b_stride
|
||||
?sum_in_stride ?k_stride ?sum_out_stride
|
||||
?matmul_dtype)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
|
||||
(= ?out_shape (ECons ?m (ECons ?n (ENil))))
|
||||
(!= ?m (MNum 0))
|
||||
(!= ?n (MNum 0))
|
||||
(!= ?k (MNum 1))
|
||||
|
||||
(= ?a_stride (ECons ?a_m_stride (ECons ?a_n_stride (ECons ?a_k_stride (ENil)))))
|
||||
(= ?b_stride (ECons ?b_m_stride (ECons ?b_n_stride (ECons ?b_k_stride (ENil)))))
|
||||
(= ?k_stride (MIter))
|
||||
|
||||
(= ?a_m_stride (MMul (MIter) ?k))
|
||||
(= ?a_n_stride (MNum 0))
|
||||
(= ?a_k_stride (MIter))
|
||||
|
||||
(= ?b_m_stride (MNum 0))
|
||||
(= ?b_n_stride (MIter))
|
||||
(= ?b_k_stride (MMul (MIter) ?n))
|
||||
|
||||
(= ?dt (dtype ?a))
|
||||
(= ?dt (dtype ?b))
|
||||
(cublaslt_base_dtype ?dt)
|
||||
)
|
||||
(
|
||||
(let ?sgemm (Op (cublaslt
|
||||
?m ?n ?k
|
||||
"N" "N"
|
||||
"ROW" "ROW" "ROW" "ROW"
|
||||
?a_m_stride
|
||||
?b_k_stride
|
||||
?n
|
||||
?n
|
||||
(MNum 1)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
?dt ?dt ?dt ?dt "default" "default" 1.0 0.0 "DEFAULT")
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
(union ?sum ?sgemm)
|
||||
(set (dtype ?sgemm) ?dt)
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt row-order row-major x row-major"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?sum (Op (GenericMatmul
|
||||
?out_shape ?mul_shape ?k
|
||||
?a_stride ?b_stride
|
||||
?sum_in_stride ?k_stride ?sum_out_stride
|
||||
?matmul_dtype)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
|
||||
(= ?out_shape (ECons ?m (ECons ?n (ENil))))
|
||||
(!= ?m (MNum 0))
|
||||
(!= ?n (MNum 0))
|
||||
(!= ?k (MNum 1))
|
||||
|
||||
(= ?a_stride (ECons ?a_m_stride (ECons ?a_n_stride (ECons ?a_k_stride (ENil)))))
|
||||
(= ?b_stride (ECons ?b_m_stride (ECons ?b_n_stride (ECons ?b_k_stride (ENil)))))
|
||||
(= ?k_stride (MIter))
|
||||
|
||||
(= ?a_m_stride (MMul (MIter) ?k))
|
||||
(= ?a_n_stride (MNum 0))
|
||||
(= ?a_k_stride (MIter))
|
||||
|
||||
(= ?b_m_stride (MNum 0))
|
||||
(= ?b_n_stride (MMul (MIter) ?k))
|
||||
(= ?b_k_stride (MIter))
|
||||
|
||||
(= ?dt (dtype ?a))
|
||||
(= ?dt (dtype ?b))
|
||||
(cublaslt_base_dtype ?dt)
|
||||
)
|
||||
(
|
||||
(let ?sgemm (Op (cublaslt
|
||||
?m ?n ?k
|
||||
"N" "N"
|
||||
"ROW" "COL" "ROW" "ROW"
|
||||
?a_m_stride
|
||||
?b_n_stride
|
||||
?n
|
||||
?n
|
||||
(MNum 1)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
?dt ?dt ?dt ?dt "default" "default" 1.0 0.0 "DEFAULT")
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
(union ?sum ?sgemm)
|
||||
(set (dtype ?sgemm) ?dt)
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt row-order row-major x column-major"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?sum (Op (GenericMatmul
|
||||
?out_shape ?mul_shape ?k
|
||||
?a_stride ?b_stride
|
||||
?sum_in_stride ?k_stride ?sum_out_stride
|
||||
?matmul_dtype)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
|
||||
(= ?out_shape (ECons ?m (ECons ?n (ENil))))
|
||||
(!= ?m (MNum 0))
|
||||
(!= ?n (MNum 0))
|
||||
(!= ?k (MNum 1))
|
||||
|
||||
(= ?a_stride (ECons ?a_m_stride (ECons ?a_n_stride (ECons ?a_k_stride (ENil)))))
|
||||
(= ?b_stride (ECons ?b_m_stride (ECons ?b_n_stride (ECons ?b_k_stride (ENil)))))
|
||||
(= ?k_stride (MIter))
|
||||
|
||||
(= ?a_m_stride (MIter))
|
||||
(= ?a_n_stride (MNum 0))
|
||||
(= ?a_k_stride (MMul (MIter) ?m))
|
||||
|
||||
(= ?b_m_stride (MNum 0))
|
||||
(= ?b_n_stride (MIter))
|
||||
(= ?b_k_stride (MMul (MIter) ?n))
|
||||
|
||||
(= ?dt (dtype ?a))
|
||||
(= ?dt (dtype ?b))
|
||||
(cublaslt_base_dtype ?dt)
|
||||
)
|
||||
(
|
||||
(let ?sgemm (Op (cublaslt
|
||||
?m ?n ?k
|
||||
"N" "N"
|
||||
"COL" "ROW" "ROW" "ROW"
|
||||
?a_k_stride
|
||||
?b_k_stride
|
||||
?n
|
||||
?n
|
||||
(MNum 1)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
?dt ?dt ?dt ?dt "default" "default" 1.0 0.0 "DEFAULT")
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
(union ?sum ?sgemm)
|
||||
(set (dtype ?sgemm) ?dt)
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt row-order column-major x row-major"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?sum (Op (GenericMatmul
|
||||
?out_shape ?mul_shape ?k
|
||||
?a_stride ?b_stride
|
||||
?sum_in_stride ?k_stride ?sum_out_stride
|
||||
?matmul_dtype)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
|
||||
(= ?out_shape (ECons ?m (ECons ?n (ENil))))
|
||||
(!= ?m (MNum 0))
|
||||
(!= ?n (MNum 0))
|
||||
(!= ?k (MNum 1))
|
||||
|
||||
(= ?a_stride (ECons ?a_m_stride (ECons ?a_n_stride (ECons ?a_k_stride (ENil)))))
|
||||
(= ?b_stride (ECons ?b_m_stride (ECons ?b_n_stride (ECons ?b_k_stride (ENil)))))
|
||||
(= ?k_stride (MIter))
|
||||
|
||||
(= ?a_m_stride (MIter))
|
||||
(= ?a_n_stride (MNum 0))
|
||||
(= ?a_k_stride (MMul (MIter) ?m))
|
||||
|
||||
(= ?b_m_stride (MNum 0))
|
||||
(= ?b_n_stride (MMul (MIter) ?k))
|
||||
(= ?b_k_stride (MIter))
|
||||
|
||||
(= ?dt (dtype ?a))
|
||||
(= ?dt (dtype ?b))
|
||||
(cublaslt_base_dtype ?dt)
|
||||
)
|
||||
(
|
||||
(let ?sgemm (Op (cublaslt
|
||||
?m ?n ?k
|
||||
"N" "N"
|
||||
"COL" "COL" "ROW" "ROW"
|
||||
?a_k_stride
|
||||
?b_n_stride
|
||||
?n
|
||||
?n
|
||||
(MNum 1)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
?dt ?dt ?dt ?dt "default" "default" 1.0 0.0 "DEFAULT")
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
(union ?sum ?sgemm)
|
||||
(set (dtype ?sgemm) ?dt)
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt row-order column-major x column-major"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?sum (Op (GenericMatmul
|
||||
?out_shape ?mul_shape ?k
|
||||
?a_stride ?b_stride
|
||||
?sum_in_stride ?k_stride ?sum_out_stride
|
||||
?matmul_dtype)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
|
||||
(= ?batch (nth_from_end ?out_shape 2))
|
||||
(= ?m (nth_from_end ?out_shape 1))
|
||||
(= ?n (nth_from_end ?out_shape 0))
|
||||
(!= ?m (MNum 0))
|
||||
(!= ?n (MNum 0))
|
||||
(!= ?k (MNum 1))
|
||||
(!= ?batch (MNum 0))
|
||||
|
||||
(= ?a_batch_stride (nth_from_end ?a_stride 3))
|
||||
(= ?a_m_stride (nth_from_end ?a_stride 2))
|
||||
(= ?a_n_stride (nth_from_end ?a_stride 1))
|
||||
(= ?a_k_stride (nth_from_end ?a_stride 0))
|
||||
|
||||
(= ?b_batch_stride (nth_from_end ?b_stride 3))
|
||||
(= ?b_m_stride (nth_from_end ?b_stride 2))
|
||||
(= ?b_n_stride (nth_from_end ?b_stride 1))
|
||||
(= ?b_k_stride (nth_from_end ?b_stride 0))
|
||||
|
||||
(= ?k_stride (MIter))
|
||||
|
||||
(= ?a_k_stride (MIter))
|
||||
(= ?a_n_stride (MNum 0))
|
||||
(= ?a_m_stride (MMul (MIter) ?k))
|
||||
|
||||
(= ?b_n_stride (MIter))
|
||||
(= ?b_m_stride (MNum 0))
|
||||
(= ?b_k_stride (MMul (MIter) ?n))
|
||||
|
||||
(= ?a_batch_stride (MMul ?m ?a_m_stride))
|
||||
(= ?b_batch_stride (MMul ?k ?b_k_stride))
|
||||
|
||||
(= ?dt (dtype ?a))
|
||||
(= ?dt (dtype ?b))
|
||||
(cublaslt_base_dtype ?dt)
|
||||
)
|
||||
(
|
||||
(let ?sgemm (Op (cublaslt
|
||||
?m ?n ?k
|
||||
"N" "N"
|
||||
"ROW" "ROW" "ROW" "ROW"
|
||||
?a_m_stride
|
||||
?b_k_stride
|
||||
?n
|
||||
?n
|
||||
?batch
|
||||
?a_batch_stride
|
||||
?b_batch_stride
|
||||
(MMul ?m ?n)
|
||||
(MMul ?m ?n)
|
||||
?dt ?dt ?dt ?dt "default" "default" 1.0 0.0 "DEFAULT")
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
(union ?sum ?sgemm)
|
||||
(set (dtype ?sgemm) ?dt)
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt row-order batched row-major x row-major"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?sum (Op (GenericMatmul
|
||||
?out_shape ?mul_shape ?k
|
||||
?a_stride ?b_stride
|
||||
?sum_in_stride ?k_stride ?sum_out_stride
|
||||
?matmul_dtype)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
|
||||
(= ?batch (nth_from_end ?out_shape 2))
|
||||
(= ?m (nth_from_end ?out_shape 1))
|
||||
(= ?n (nth_from_end ?out_shape 0))
|
||||
(!= ?m (MNum 0))
|
||||
(!= ?n (MNum 0))
|
||||
(!= ?k (MNum 1))
|
||||
(!= ?batch (MNum 0))
|
||||
|
||||
(= ?a_batch_stride (nth_from_end ?a_stride 3))
|
||||
(= ?a_m_stride (nth_from_end ?a_stride 2))
|
||||
(= ?a_n_stride (nth_from_end ?a_stride 1))
|
||||
(= ?a_k_stride (nth_from_end ?a_stride 0))
|
||||
|
||||
(= ?b_batch_stride (nth_from_end ?b_stride 3))
|
||||
(= ?b_m_stride (nth_from_end ?b_stride 2))
|
||||
(= ?b_n_stride (nth_from_end ?b_stride 1))
|
||||
(= ?b_k_stride (nth_from_end ?b_stride 0))
|
||||
|
||||
(= ?k_stride (MIter))
|
||||
|
||||
(= ?a_k_stride (MIter))
|
||||
(= ?a_n_stride (MNum 0))
|
||||
(= ?a_m_stride (MMul (MIter) ?k))
|
||||
|
||||
(= ?b_k_stride (MIter))
|
||||
(= ?b_m_stride (MNum 0))
|
||||
(= ?b_n_stride (MMul (MIter) ?k))
|
||||
|
||||
(= ?a_batch_stride (MMul ?m ?a_m_stride))
|
||||
(= ?b_batch_stride (MMul ?n ?b_n_stride))
|
||||
|
||||
(= ?dt (dtype ?a))
|
||||
(= ?dt (dtype ?b))
|
||||
(cublaslt_base_dtype ?dt)
|
||||
)
|
||||
(
|
||||
(let ?sgemm (Op (cublaslt
|
||||
?m ?n ?k
|
||||
"N" "N"
|
||||
"ROW" "COL" "ROW" "ROW"
|
||||
?a_m_stride
|
||||
?b_n_stride
|
||||
?n
|
||||
?n
|
||||
?batch
|
||||
?a_batch_stride
|
||||
?b_batch_stride
|
||||
(MMul ?m ?n)
|
||||
(MMul ?m ?n)
|
||||
?dt ?dt ?dt ?dt "default" "default" 1.0 0.0 "DEFAULT")
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
(union ?sum ?sgemm)
|
||||
(set (dtype ?sgemm) ?dt)
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt row-order batched row-major x column-major"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?sum (Op (GenericMatmul
|
||||
?out_shape ?mul_shape ?k
|
||||
?a_stride ?b_stride
|
||||
?sum_in_stride ?k_stride ?sum_out_stride
|
||||
?matmul_dtype)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
|
||||
(= ?batch (nth_from_end ?out_shape 2))
|
||||
(= ?m (nth_from_end ?out_shape 1))
|
||||
(= ?n (nth_from_end ?out_shape 0))
|
||||
(!= ?m (MNum 0))
|
||||
(!= ?n (MNum 0))
|
||||
(!= ?k (MNum 1))
|
||||
(!= ?batch (MNum 0))
|
||||
|
||||
(= ?a_batch_stride (nth_from_end ?a_stride 3))
|
||||
(= ?a_m_stride (nth_from_end ?a_stride 2))
|
||||
(= ?a_n_stride (nth_from_end ?a_stride 1))
|
||||
(= ?a_k_stride (nth_from_end ?a_stride 0))
|
||||
|
||||
(= ?b_batch_stride (nth_from_end ?b_stride 3))
|
||||
(= ?b_m_stride (nth_from_end ?b_stride 2))
|
||||
(= ?b_n_stride (nth_from_end ?b_stride 1))
|
||||
(= ?b_k_stride (nth_from_end ?b_stride 0))
|
||||
|
||||
(= ?k_stride (MIter))
|
||||
|
||||
(= ?a_m_stride (MIter))
|
||||
(= ?a_n_stride (MNum 0))
|
||||
(= ?a_k_stride (MMul (MIter) ?m))
|
||||
|
||||
(= ?b_n_stride (MIter))
|
||||
(= ?b_m_stride (MNum 0))
|
||||
(= ?b_k_stride (MMul (MIter) ?n))
|
||||
|
||||
(= ?a_batch_stride (MMul ?k ?a_k_stride))
|
||||
(= ?b_batch_stride (MMul ?k ?b_k_stride))
|
||||
|
||||
(= ?dt (dtype ?a))
|
||||
(= ?dt (dtype ?b))
|
||||
(cublaslt_base_dtype ?dt)
|
||||
)
|
||||
(
|
||||
(let ?sgemm (Op (cublaslt
|
||||
?m ?n ?k
|
||||
"N" "N"
|
||||
"COL" "ROW" "ROW" "ROW"
|
||||
?a_k_stride
|
||||
?b_k_stride
|
||||
?n
|
||||
?n
|
||||
?batch
|
||||
?a_batch_stride
|
||||
?b_batch_stride
|
||||
(MMul ?m ?n)
|
||||
(MMul ?m ?n)
|
||||
?dt ?dt ?dt ?dt "default" "default" 1.0 0.0 "DEFAULT")
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
(union ?sum ?sgemm)
|
||||
(set (dtype ?sgemm) ?dt)
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt row-order batched column-major x row-major"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?sum (Op (GenericMatmul
|
||||
?out_shape ?mul_shape ?k
|
||||
?a_stride ?b_stride
|
||||
?sum_in_stride ?k_stride ?sum_out_stride
|
||||
?matmul_dtype)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
|
||||
(= ?batch (nth_from_end ?out_shape 2))
|
||||
(= ?m (nth_from_end ?out_shape 1))
|
||||
(= ?n (nth_from_end ?out_shape 0))
|
||||
(!= ?m (MNum 0))
|
||||
(!= ?n (MNum 0))
|
||||
(!= ?k (MNum 1))
|
||||
(!= ?batch (MNum 0))
|
||||
|
||||
(= ?a_batch_stride (nth_from_end ?a_stride 3))
|
||||
(= ?a_m_stride (nth_from_end ?a_stride 2))
|
||||
(= ?a_n_stride (nth_from_end ?a_stride 1))
|
||||
(= ?a_k_stride (nth_from_end ?a_stride 0))
|
||||
|
||||
(= ?b_batch_stride (nth_from_end ?b_stride 3))
|
||||
(= ?b_m_stride (nth_from_end ?b_stride 2))
|
||||
(= ?b_n_stride (nth_from_end ?b_stride 1))
|
||||
(= ?b_k_stride (nth_from_end ?b_stride 0))
|
||||
|
||||
(= ?k_stride (MIter))
|
||||
|
||||
(= ?a_m_stride (MIter))
|
||||
(= ?a_n_stride (MNum 0))
|
||||
(= ?a_k_stride (MMul (MIter) ?m))
|
||||
|
||||
(= ?b_k_stride (MIter))
|
||||
(= ?b_m_stride (MNum 0))
|
||||
(= ?b_n_stride (MMul (MIter) ?k))
|
||||
|
||||
(= ?a_batch_stride (MMul ?k ?a_k_stride))
|
||||
(= ?b_batch_stride (MMul ?n ?b_n_stride))
|
||||
|
||||
(= ?dt (dtype ?a))
|
||||
(= ?dt (dtype ?b))
|
||||
(cublaslt_base_dtype ?dt)
|
||||
)
|
||||
(
|
||||
(let ?sgemm (Op (cublaslt
|
||||
?m ?n ?k
|
||||
"N" "N"
|
||||
"COL" "COL" "ROW" "ROW"
|
||||
?a_k_stride
|
||||
?b_n_stride
|
||||
?n
|
||||
?n
|
||||
?batch
|
||||
?a_batch_stride
|
||||
?b_batch_stride
|
||||
(MMul ?m ?n)
|
||||
(MMul ?m ?n)
|
||||
?dt ?dt ?dt ?dt "default" "default" 1.0 0.0 "DEFAULT")
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
(union ?sum ?sgemm)
|
||||
(set (dtype ?sgemm) ?dt)
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt row-order batched column-major x column-major"
|
||||
)
|
||||
@@ -0,0 +1,316 @@
|
||||
; Scalar alpha/beta rewrites for cuBLASLt. These rules target scalar constants
|
||||
; expanded across the matmul/add shape, i.e. zero strides on every logical axis.
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?matmul (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?c_order ?d_order
|
||||
?lda ?ldb ?ldc ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
1.0 0.0 "DEFAULT")
|
||||
(ICons ?a (ICons ?b ?matmul_tail))))
|
||||
|
||||
(= ?scale (Op (Constant ?alpha) (INil)))
|
||||
; alpha=1.0 hash-conses ?fused == ?matmul; the union merges Mul into ?matmul's eclass and saturate diverges.
|
||||
(!= ?alpha 1.0)
|
||||
(= ?scaled (Op (Mul ?shape
|
||||
?matmul_strides
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ENil)))
|
||||
?scaled_out_strides)
|
||||
(ICons ?matmul (ICons ?scale (INil)))))
|
||||
(= ?matmul_strides ?scaled_out_strides)
|
||||
)
|
||||
(
|
||||
(let ?fused (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?c_order ?d_order
|
||||
?lda ?ldb ?ldc ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 "DEFAULT")
|
||||
(ICons ?a (ICons ?b ?matmul_tail))))
|
||||
(union ?scaled ?fused)
|
||||
(set (dtype ?fused) ?d_dtype)
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt 2d alpha scale"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?matmul (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?c_order ?d_order
|
||||
?lda ?ldb ?ldc ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
1.0 0.0 "DEFAULT")
|
||||
(ICons ?a (ICons ?b ?matmul_tail))))
|
||||
|
||||
(= ?scale (Op (Constant ?alpha) (INil)))
|
||||
; See 2d alpha scale: alpha=1.0 makes (saturate ...) diverge.
|
||||
(!= ?alpha 1.0)
|
||||
(= ?scaled (Op (Mul ?shape
|
||||
?matmul_strides
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ECons (MNum 0) (ENil))))
|
||||
?scaled_out_strides)
|
||||
(ICons ?matmul (ICons ?scale (INil)))))
|
||||
(= ?matmul_strides ?scaled_out_strides)
|
||||
)
|
||||
(
|
||||
(let ?fused (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?c_order ?d_order
|
||||
?lda ?ldb ?ldc ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 "DEFAULT")
|
||||
(ICons ?a (ICons ?b ?matmul_tail))))
|
||||
(union ?scaled ?fused)
|
||||
(set (dtype ?fused) ?d_dtype)
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt batched alpha scale"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?matmul (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?matmul_c_order "ROW"
|
||||
?lda ?ldb ?matmul_ldc ?ldd
|
||||
(MNum 1)
|
||||
?stride_a ?stride_b ?matmul_stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 ?epilogue)
|
||||
(ICons ?a (ICons ?b ?matmul_tail))))
|
||||
|
||||
(= ?beta_node (Op (Constant ?beta) (INil)))
|
||||
(= ?scaled_c (Op (Mul
|
||||
(ECons ?m (ECons ?n (ENil)))
|
||||
?c_strides
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ENil)))
|
||||
?scaled_c_out_strides)
|
||||
(ICons ?c (ICons ?beta_node (INil)))))
|
||||
|
||||
(= ?add (Op (Add
|
||||
(ECons ?m (ECons ?n (ENil)))
|
||||
?matmul_add_strides
|
||||
?scaled_c_add_strides
|
||||
?add_out_strides)
|
||||
(ICons ?matmul (ICons ?scaled_c (INil)))))
|
||||
|
||||
(= ?matmul_add_strides (ECons ?d_row_stride (ECons ?d_col_stride (ENil))))
|
||||
(= ?c_strides (ECons ?c_row_stride (ECons ?c_col_stride (ENil))))
|
||||
(= ?add_out_strides (ECons ?d_row_stride (ECons ?d_col_stride (ENil))))
|
||||
(= ?scaled_c_add_strides ?scaled_c_out_strides)
|
||||
(= ?c_col_stride (MIter))
|
||||
(!= ?c_row_stride (MNum 0))
|
||||
(= ?matmul_add_strides ?add_out_strides)
|
||||
(= ?c_dtype (dtype ?c))
|
||||
)
|
||||
(
|
||||
(let ?fused (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order "ROW" "ROW"
|
||||
?lda ?ldb ?c_row_stride ?ldd
|
||||
(MNum 1)
|
||||
?stride_a ?stride_b (MNum 0) ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha ?beta ?epilogue)
|
||||
(ICons ?a (ICons ?b (ICons ?c ?matmul_tail)))))
|
||||
(union ?add ?fused)
|
||||
(set (dtype ?fused) ?d_dtype)
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt row-order 2d scaled c beta"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?matmul (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?matmul_c_order "ROW"
|
||||
?lda ?ldb ?matmul_ldc ?ldd
|
||||
(MNum 1)
|
||||
?stride_a ?stride_b ?matmul_stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 ?epilogue)
|
||||
(ICons ?a (ICons ?b ?matmul_tail))))
|
||||
|
||||
(= ?beta_node (Op (Constant ?beta) (INil)))
|
||||
(= ?scaled_c (Op (Mul
|
||||
(ECons ?m (ECons ?n (ENil)))
|
||||
?c_strides
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ENil)))
|
||||
?scaled_c_out_strides)
|
||||
(ICons ?c (ICons ?beta_node (INil)))))
|
||||
|
||||
(= ?add (Op (Add
|
||||
(ECons ?m (ECons ?n (ENil)))
|
||||
?scaled_c_add_strides
|
||||
?matmul_add_strides
|
||||
?add_out_strides)
|
||||
(ICons ?scaled_c (ICons ?matmul (INil)))))
|
||||
|
||||
(= ?matmul_add_strides (ECons ?d_row_stride (ECons ?d_col_stride (ENil))))
|
||||
(= ?c_strides (ECons ?c_row_stride (ECons ?c_col_stride (ENil))))
|
||||
(= ?add_out_strides (ECons ?d_row_stride (ECons ?d_col_stride (ENil))))
|
||||
(= ?scaled_c_add_strides ?scaled_c_out_strides)
|
||||
(= ?c_col_stride (MIter))
|
||||
(!= ?c_row_stride (MNum 0))
|
||||
(= ?matmul_add_strides ?add_out_strides)
|
||||
(= ?c_dtype (dtype ?c))
|
||||
)
|
||||
(
|
||||
(let ?fused (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order "ROW" "ROW"
|
||||
?lda ?ldb ?c_row_stride ?ldd
|
||||
(MNum 1)
|
||||
?stride_a ?stride_b (MNum 0) ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha ?beta ?epilogue)
|
||||
(ICons ?a (ICons ?b (ICons ?c ?matmul_tail)))))
|
||||
(union ?add ?fused)
|
||||
(set (dtype ?fused) ?d_dtype)
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt row-order 2d scaled c plus matmul beta"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?matmul (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?matmul_c_order "ROW"
|
||||
?lda ?ldb ?matmul_ldc ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?matmul_stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 ?epilogue)
|
||||
(ICons ?a (ICons ?b ?matmul_tail))))
|
||||
|
||||
(= ?beta_node (Op (Constant ?beta) (INil)))
|
||||
(= ?scaled_c (Op (Mul
|
||||
(ECons ?batch (ECons ?m (ECons ?n (ENil))))
|
||||
?c_strides
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ECons (MNum 0) (ENil))))
|
||||
?scaled_c_out_strides)
|
||||
(ICons ?c (ICons ?beta_node (INil)))))
|
||||
|
||||
(= ?add (Op (Add
|
||||
(ECons ?batch (ECons ?m (ECons ?n (ENil))))
|
||||
?matmul_add_strides
|
||||
?scaled_c_add_strides
|
||||
?add_out_strides)
|
||||
(ICons ?matmul (ICons ?scaled_c (INil)))))
|
||||
|
||||
(= ?matmul_add_strides (ECons ?d_batch_stride (ECons ?d_row_stride (ECons ?d_col_stride (ENil)))))
|
||||
(= ?c_strides (ECons ?c_batch_stride (ECons ?c_row_stride (ECons ?c_col_stride (ENil)))))
|
||||
(= ?add_out_strides (ECons ?d_batch_stride (ECons ?d_row_stride (ECons ?d_col_stride (ENil)))))
|
||||
(= ?scaled_c_add_strides ?scaled_c_out_strides)
|
||||
(= ?c_col_stride (MIter))
|
||||
(!= ?c_row_stride (MNum 0))
|
||||
(= ?matmul_add_strides ?add_out_strides)
|
||||
(= ?c_dtype (dtype ?c))
|
||||
)
|
||||
(
|
||||
(let ?fused (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order "ROW" "ROW"
|
||||
?lda ?ldb ?c_row_stride ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?c_batch_stride ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha ?beta ?epilogue)
|
||||
(ICons ?a (ICons ?b (ICons ?c ?matmul_tail)))))
|
||||
(union ?add ?fused)
|
||||
(set (dtype ?fused) ?d_dtype)
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt row-order batched scaled c beta"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?matmul (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order ?matmul_c_order "ROW"
|
||||
?lda ?ldb ?matmul_ldc ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?matmul_stride_c ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha 0.0 ?epilogue)
|
||||
(ICons ?a (ICons ?b ?matmul_tail))))
|
||||
|
||||
(= ?beta_node (Op (Constant ?beta) (INil)))
|
||||
(= ?scaled_c (Op (Mul
|
||||
(ECons ?batch (ECons ?m (ECons ?n (ENil))))
|
||||
?c_strides
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ECons (MNum 0) (ENil))))
|
||||
?scaled_c_out_strides)
|
||||
(ICons ?c (ICons ?beta_node (INil)))))
|
||||
|
||||
(= ?add (Op (Add
|
||||
(ECons ?batch (ECons ?m (ECons ?n (ENil))))
|
||||
?scaled_c_add_strides
|
||||
?matmul_add_strides
|
||||
?add_out_strides)
|
||||
(ICons ?scaled_c (ICons ?matmul (INil)))))
|
||||
|
||||
(= ?matmul_add_strides (ECons ?d_batch_stride (ECons ?d_row_stride (ECons ?d_col_stride (ENil)))))
|
||||
(= ?c_strides (ECons ?c_batch_stride (ECons ?c_row_stride (ECons ?c_col_stride (ENil)))))
|
||||
(= ?add_out_strides (ECons ?d_batch_stride (ECons ?d_row_stride (ECons ?d_col_stride (ENil)))))
|
||||
(= ?scaled_c_add_strides ?scaled_c_out_strides)
|
||||
(= ?c_col_stride (MIter))
|
||||
(!= ?c_row_stride (MNum 0))
|
||||
(= ?matmul_add_strides ?add_out_strides)
|
||||
(= ?c_dtype (dtype ?c))
|
||||
)
|
||||
(
|
||||
(let ?fused (Op (cublaslt
|
||||
?m ?n ?k
|
||||
?a_layout ?b_layout
|
||||
?a_order ?b_order "ROW" "ROW"
|
||||
?lda ?ldb ?c_row_stride ?ldd
|
||||
?batch
|
||||
?stride_a ?stride_b ?c_batch_stride ?stride_d
|
||||
?a_dtype ?b_dtype ?c_dtype ?d_dtype
|
||||
?compute_type ?scale_dtype
|
||||
?alpha ?beta ?epilogue)
|
||||
(ICons ?a (ICons ?b (ICons ?c ?matmul_tail)))))
|
||||
(union ?add ?fused)
|
||||
(set (dtype ?fused) ?d_dtype)
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "cublaslt row-order batched scaled c plus matmul beta"
|
||||
)
|
||||
File diff suppressed because it is too large
Load Diff
124
crates/luminal_cuda_lite/src/host/flashinfer/README.md
Normal file
124
crates/luminal_cuda_lite/src/host/flashinfer/README.md
Normal file
@@ -0,0 +1,124 @@
|
||||
# FlashInfer Integration
|
||||
|
||||
FlashInfer replaces the multi-op attention pattern (Q×K^T → scale → mask → softmax → ×V) with a single fused GPU kernel via [FlashInfer](https://github.com/flashinfer-ai/flashinfer)'s batch decode and batch prefill APIs.
|
||||
|
||||
## Current State
|
||||
|
||||
**Working:**
|
||||
- Egglog rewrite rule matches any GQA paged attention pattern (model-agnostic shapes)
|
||||
- GA search selects FlashInfer when it wins profiling — verified on Llama 3 8B (32 layers) and Qwen 3 4B (36 layers)
|
||||
- **BatchDecode** (s=1): fp32 natively — FlashInfer's decode kernel uses scalar vectorized dot products, no tensor cores
|
||||
- **BatchPrefill**: template-instantiated for fp16 but **not callable from fp32** — FlashInfer's prefill kernel requires tensor core MMA (`mma.sync.aligned.m16n8k16`) and `ldmatrix` which physically only operate on 16-bit types; the C API stubs return -1 for fp32; will be enabled when native fp16/bf16 pipeline is added
|
||||
- Decode handles all cases in the current fp32 pipeline (prefill uses cuBLAS attention via dim bucketing)
|
||||
- Indptr-based mask: `qo_indptr` and `kv_indptr` are computed in-graph so the egglog rule can see them in the same chunk as the attention ops
|
||||
|
||||
**Not yet implemented:**
|
||||
- Native fp16 / bf16 pipeline (would eliminate the cast overhead in prefill)
|
||||
- Page sizes > 1
|
||||
|
||||
---
|
||||
|
||||
## File Organization
|
||||
|
||||
```
|
||||
src/host/flashinfer/
|
||||
flashinfer_attention.egg — egglog rewrite rule (pattern match → FlashInferAttention)
|
||||
mod.rs — FlashInferAttention op (EgglogOp + HostOp impl)
|
||||
jit.rs — JIT compilation: nvcc wrapper.cu → .so, dlopen, fn pointers
|
||||
find_indptrs.rs — walks the mask e-graph node to locate qo_indptr / kv_indptr inputs
|
||||
wrapper.cu — CUDA: FlashInfer template instantiation + helper kernels
|
||||
wrapper.h — C API header for wrapper.cu
|
||||
README.md — this file
|
||||
```
|
||||
|
||||
## How It Works
|
||||
|
||||
### 1. Egglog Pattern Matching
|
||||
|
||||
The rule in `flashinfer_attention.egg` matches the structural pattern of paged GQA attention:
|
||||
|
||||
```
|
||||
Gather(K_cache, idx) → GQA broadcast (Mul×1.0) → Q×K^T → Sum → scale → mask Add → softmax → attn×V → Sum → output
|
||||
Gather(V_cache, idx) → GQA broadcast (Mul×1.0) ──────────────────────────────────────────→ attn×V → Sum → output
|
||||
```
|
||||
|
||||
Key anchors that prevent false matches on MLP or other ops:
|
||||
- Two Gather ops from 2D cache pools (MLP never uses Gather)
|
||||
- GQA broadcast via `Mul(gathered, Constant(1.0))` with all-zero strides
|
||||
- Mask Add with zero-stride broadcast in the first (nheads) dimension
|
||||
- Two sequential matmul+Sum pairs connected through softmax
|
||||
|
||||
Shape dimensions are egglog variables, not pinned constants — the rule works for any model with GQA (Llama, Qwen, Mistral, etc.). The structural invariants (dimension count, zero-stride positions, Gather from 2D) are enough to avoid combinatorial explosion during saturation.
|
||||
|
||||
When the rule fires, it unions `FlashInferAttention` with the original attention output, making it an equivalent alternative in the e-graph. The GA search then profiles both paths and picks the faster one.
|
||||
|
||||
### 2. Extraction: Finding Indptrs
|
||||
|
||||
During `extract()` (called when egglog selects the FlashInferAttention e-node), `find_indptrs.rs` walks backward from the mask node in the e-graph to locate the `qo_indptr` and `kv_indptr` Input nodes. It validates the mask structure by checking for the `Mul(allowed, Constant(1e10))` pattern that `compute_attn_mask()` produces.
|
||||
|
||||
The indptrs are appended as inputs 5 and 6 to the FlashInferAttention op, so the runtime can build the CSR page table directly without recomputing anything.
|
||||
|
||||
### 3. JIT Compilation
|
||||
|
||||
FlashInfer requires `HEAD_DIM` as a compile-time template parameter. Rather than baking it at `cargo build` time, `jit.rs` JIT-compiles `wrapper.cu` with the model's actual HEAD_DIM:
|
||||
|
||||
1. First call to `ensure_compiled(head_dim)` runs `nvcc` with `-DLUMINAL_HEAD_DIM=<N>`
|
||||
2. The compiled `.so` is cached at `~/.cache/luminal/flashinfer/libflashinfer_hd<N>_<arch>.so`
|
||||
3. Subsequent calls load the cached library via `dlopen`
|
||||
4. Function pointers (plan, run, transpose, etc.) are resolved and stored in a `static OnceLock`
|
||||
|
||||
Supported HEAD_DIM values: 64, 128, 256.
|
||||
|
||||
### 4. Runtime Execution
|
||||
|
||||
`FlashInferAttention::execute()` dispatches to decode or prefill based on `total_q_tokens vs batch_size`:
|
||||
|
||||
**Common steps:**
|
||||
1. **Extract kv_indices** — a helper kernel converts the flat gather index `(c, KV_DIM)` to slot indices `(c,)`
|
||||
2. **Read indptrs to host** — copied to CPU for the plan phase
|
||||
3. **Plan** — queries GPU occupancy and decides split-KV decomposition
|
||||
4. **Run** — the fused kernel writes `(total_q_tokens, num_qo_heads, head_dim)`
|
||||
5. **Transpose** — transposes to `(num_qo_heads, total_q_tokens, head_dim)` to match the Sum reduction layout
|
||||
|
||||
**Decode path** (current, fp32): Always used. Runs FlashInfer's BatchDecode directly on fp32 buffers.
|
||||
|
||||
**Prefill path** (future, fp16/bf16 only): The prefill kernel templates are compiled into the JIT .so for fp16 (CTA_TILE_Q=16/64/128, causal mask). The C API stubs currently return -1 since the pipeline is fp32. When native fp16/bf16 dtype support is added, `execute()` will dispatch to prefill when `total_q_tokens > batch_size`.
|
||||
|
||||
Global workspaces (`static OnceLock`) are shared across all FlashInferAttention instances to avoid ~4ms allocation overhead per GA profiling candidate. Without this, the GA never selects FlashInfer because the first-run allocation cost dwarfs the kernel time.
|
||||
|
||||
## How the Attention Mask Enables FlashInfer
|
||||
|
||||
For the egglog rule to fire, the `qo_indptr` and `kv_indptr` tensors must be visible in the same e-graph chunk as the attention ops. This is why the mask is computed *inside* each layer (via `compute_attn_mask()` in the model) rather than passed as a pre-computed input.
|
||||
|
||||
The mask computation uses a specific structure:
|
||||
```rust
|
||||
let allowed = same_request * causal;
|
||||
allowed * 1e10 - 1e10 // → 0.0 for allowed, -1e10 for blocked
|
||||
```
|
||||
|
||||
The `Mul(allowed, Constant(1e10))` pattern is the anchor that `find_indptrs.rs` uses to walk backward and locate the indptr inputs.
|
||||
|
||||
## Roadmap
|
||||
|
||||
Items listed in priority order. Checked items are done.
|
||||
|
||||
- [x] Model-agnostic egglog rule (shape variables instead of Llama-specific constants)
|
||||
- [x] bs>1 supersequence decode
|
||||
- [x] Indptr-based attention mask (replaces CPU-computed mask)
|
||||
- [x] Multi-model support (verified on Llama 3 8B and Qwen 3 4B)
|
||||
- [x] BatchPrefill kernel compiled for fp16 (causal mask, CTA_TILE_Q=16/64/128)
|
||||
- [ ] Native fp16 / bf16 pipeline (enables prefill, reduces memory, eliminates cuBLAS prefill fallback)
|
||||
- [ ] HEAD_DIM dispatch for 64, 96 (JIT supports 64/128/256; wrapper.cu needs 96 for Phi)
|
||||
- [ ] Page sizes > 1 (currently page_size=1; larger pages reduce CSR overhead)
|
||||
- [ ] Sliding window, ALiBi, logits soft cap (FlashInfer `AttentionVariant` templates)
|
||||
- [ ] MHA / MQA / arbitrary GQA ratios beyond {1, 2, 4, 8}
|
||||
|
||||
## Key Design Decisions
|
||||
|
||||
- **page_size=1**: Each KV cache slot is one "page". This simplifies the CSR page table (`kv_indices` = physical slot indices directly) and matches the flat `(num_slots, KV_DIM)` cache layout.
|
||||
|
||||
- **Pinned structural anchors**: The egglog rule pins the *structure* (number of dimensions, which dims are zero-stride, presence of Gather from 2D cache) but uses variables for the *values* (head counts, head_dim). This prevents saturation blowup while remaining model-agnostic.
|
||||
|
||||
- **Prefill requires fp16/bf16**: FlashInfer's prefill kernel uses tensor core MMA instructions (`mma.sync.aligned.m16n8k16`) and `ldmatrix` which physically require 16-bit inputs — there is no fp32 tensor core matmul instruction. The prefill kernel templates are compiled into the .so for fp16 but the C API returns -1 for fp32 callers. When native fp16/bf16 is added, prefill will be enabled automatically.
|
||||
|
||||
- **Global workspaces**: Float workspace (128 MiB), int workspace (8 MiB), and a page-locked host buffer are allocated once via `static OnceLock` and shared across all instances.
|
||||
328
crates/luminal_cuda_lite/src/host/flashinfer/find_indptrs.rs
Normal file
328
crates/luminal_cuda_lite/src/host/flashinfer/find_indptrs.rs
Normal file
@@ -0,0 +1,328 @@
|
||||
//! Walk the e-graph from the mask node to find qo_indptr and kv_indptr Input nodes.
|
||||
//!
|
||||
//! The mask is produced by `compute_attn_mask(q_pos, qo_indptr, kv_indptr)` using
|
||||
//! primitive HLIR ops. This module validates the mask's structure and extracts the
|
||||
//! indptr Input node IDs so FlashInfer can use them directly.
|
||||
|
||||
use luminal::egglog_utils::{ClassId, NodeId, SerializedEGraph};
|
||||
use luminal::prelude::FxHashSet;
|
||||
|
||||
/// Result of walking the mask computation chain.
|
||||
#[derive(Debug)]
|
||||
pub struct IndptrNodes<'a> {
|
||||
pub qo_indptr: &'a NodeId,
|
||||
pub kv_indptr: &'a NodeId,
|
||||
}
|
||||
|
||||
/// Find the qo_indptr and kv_indptr Input nodes by walking backwards from the mask.
|
||||
///
|
||||
/// Validates the mask structure: `allowed * 1e10 + (-1e10)`. Then does a BFS from
|
||||
/// the `allowed` subtree to find all reachable Input nodes with names containing
|
||||
/// "qo_indptr" and "kv_indptr".
|
||||
///
|
||||
/// Panics with a diagnostic message if the structure doesn't match or the
|
||||
/// indptr inputs can't be found.
|
||||
pub fn find_indptr_inputs<'a>(
|
||||
egraph: &'a SerializedEGraph,
|
||||
mask_node: &'a NodeId,
|
||||
) -> IndptrNodes<'a> {
|
||||
// Step 1: Validate mask = Add(scaled_allowed, neg_constant)
|
||||
let mask_inputs = logical_binary_inputs(egraph, mask_node, "Add").unwrap_or_else(|| {
|
||||
let (mask_label, mask_children) = &egraph.enodes[mask_node];
|
||||
assert!(
|
||||
mask_label == "Op",
|
||||
"find_indptr_inputs: mask node is not an Op (label={mask_label})"
|
||||
);
|
||||
let mask_kind = resolve_first_node(egraph, &mask_children[0]);
|
||||
let mask_kind_label = &egraph.enodes[mask_kind].0;
|
||||
panic!("find_indptr_inputs: mask is not an Add (kind={mask_kind_label})");
|
||||
});
|
||||
assert_eq!(
|
||||
mask_inputs.len(),
|
||||
2,
|
||||
"find_indptr_inputs: mask Add should have 2 inputs, got {}",
|
||||
mask_inputs.len()
|
||||
);
|
||||
|
||||
// Step 2: One of the inputs should be Mul(allowed, Constant(1e10))
|
||||
let (scaled_allowed, allowed_node) = find_1e10_mul(egraph, &mask_inputs);
|
||||
|
||||
// Step 3: BFS from `allowed` to find all reachable Input nodes
|
||||
let reachable_inputs = find_reachable_inputs(egraph, allowed_node);
|
||||
|
||||
// Step 4: Match by name
|
||||
let mut qo_indptr: Option<&NodeId> = None;
|
||||
let mut kv_indptr: Option<&NodeId> = None;
|
||||
|
||||
for (node_id, name) in &reachable_inputs {
|
||||
if name.contains("qo_indptr") {
|
||||
qo_indptr = Some(node_id);
|
||||
} else if name.contains("kv_indptr") {
|
||||
kv_indptr = Some(node_id);
|
||||
}
|
||||
}
|
||||
|
||||
let qo = qo_indptr.unwrap_or_else(|| {
|
||||
let found_names: Vec<&str> = reachable_inputs.iter().map(|(_, n)| n.as_str()).collect();
|
||||
panic!(
|
||||
"find_indptr_inputs: could not find 'qo_indptr' Input reachable from mask.\n\
|
||||
Found inputs: {:?}\n\
|
||||
Mask node: {:?}\n\
|
||||
Scaled allowed node: {:?}",
|
||||
found_names, mask_node, scaled_allowed
|
||||
);
|
||||
});
|
||||
|
||||
let kv = kv_indptr.unwrap_or_else(|| {
|
||||
let found_names: Vec<&str> = reachable_inputs.iter().map(|(_, n)| n.as_str()).collect();
|
||||
panic!(
|
||||
"find_indptr_inputs: could not find 'kv_indptr' Input reachable from mask.\n\
|
||||
Found inputs: {:?}\n\
|
||||
Mask node: {:?}\n\
|
||||
Scaled allowed node: {:?}",
|
||||
found_names, mask_node, scaled_allowed
|
||||
);
|
||||
});
|
||||
|
||||
IndptrNodes {
|
||||
qo_indptr: qo,
|
||||
kv_indptr: kv,
|
||||
}
|
||||
}
|
||||
|
||||
fn find_1e10_mul<'a>(
|
||||
egraph: &'a SerializedEGraph,
|
||||
mask_add_inputs: &[&'a NodeId],
|
||||
) -> (&'a NodeId, &'a NodeId) {
|
||||
for &input_node in mask_add_inputs {
|
||||
let Some(mul_inputs) = logical_binary_inputs(egraph, input_node, "Mul") else {
|
||||
continue;
|
||||
};
|
||||
if mul_inputs.len() != 2 {
|
||||
continue;
|
||||
}
|
||||
for (i, &inp) in mul_inputs.iter().enumerate() {
|
||||
if is_constant(egraph, inp, 1e10) {
|
||||
let other = mul_inputs[1 - i];
|
||||
return (input_node, other);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut debug_info = String::new();
|
||||
for (i, &input_node) in mask_add_inputs.iter().enumerate() {
|
||||
let (label, children) = &egraph.enodes[input_node];
|
||||
debug_info.push_str(&format!("\n input[{i}]: label={label}"));
|
||||
if label == "Op" && !children.is_empty() {
|
||||
let kind = resolve_first_node(egraph, &children[0]);
|
||||
let kind_label = &egraph.enodes[kind].0;
|
||||
debug_info.push_str(&format!(" kind={kind_label}"));
|
||||
for (j, kc) in egraph.enodes[kind].1.iter().enumerate() {
|
||||
let kc_node = resolve_first_node(egraph, kc);
|
||||
debug_info.push_str(&format!(" child[{j}]={}", egraph.enodes[kc_node].0));
|
||||
}
|
||||
if kind_label.contains("Mul") && children.len() >= 2 {
|
||||
let mul_inputs = walk_ilist_simple(egraph, &children[1]);
|
||||
for (j, &mi) in mul_inputs.iter().enumerate() {
|
||||
let (ml, mc) = &egraph.enodes[mi];
|
||||
debug_info.push_str(&format!("\n mul_input[{j}]: label={ml}"));
|
||||
if ml == "Op" && !mc.is_empty() {
|
||||
let mk = resolve_first_node(egraph, &mc[0]);
|
||||
debug_info.push_str(&format!(" kind={}", egraph.enodes[mk].0));
|
||||
for (k, mkc) in egraph.enodes[mk].1.iter().enumerate() {
|
||||
let mkc_node = resolve_first_node(egraph, mkc);
|
||||
debug_info.push_str(&format!(" ch[{k}]={}", egraph.enodes[mkc_node].0));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
panic!(
|
||||
"find_indptr_inputs: could not find Mul(allowed, Constant(1e10)) in mask Add inputs.{debug_info}"
|
||||
);
|
||||
}
|
||||
|
||||
fn is_constant(egraph: &SerializedEGraph, node: &NodeId, expected: f32) -> bool {
|
||||
let node = resolve_op_with_kind(egraph, node, "Constant").unwrap_or(node);
|
||||
let (label, children) = &egraph.enodes[node];
|
||||
if label != "Op" {
|
||||
return false;
|
||||
}
|
||||
let kind = resolve_first_node(egraph, &children[0]);
|
||||
let kind_label = &egraph.enodes[kind].0;
|
||||
if !kind_label.contains("Constant") {
|
||||
return false;
|
||||
}
|
||||
let val_children = &egraph.enodes[kind].1;
|
||||
if val_children.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let val_node = resolve_first_node(egraph, &val_children[0]);
|
||||
let val_str = &egraph.enodes[val_node].0;
|
||||
if let Ok(val) = val_str.parse::<f64>() {
|
||||
(val as f32 - expected).abs() < 1.0
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn find_reachable_inputs<'a>(
|
||||
egraph: &'a SerializedEGraph,
|
||||
start: &'a NodeId,
|
||||
) -> Vec<(&'a NodeId, String)> {
|
||||
let mut found = Vec::new();
|
||||
let mut visited = FxHashSet::default();
|
||||
let mut stack = vec![start];
|
||||
|
||||
while let Some(node) = stack.pop() {
|
||||
if !visited.insert(node) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let (label, children) = &egraph.enodes[node];
|
||||
|
||||
if label == "Input" {
|
||||
if children.len() >= 2 {
|
||||
let name_node = resolve_first_node(egraph, &children[1]);
|
||||
let name = egraph.enodes[name_node].0.trim_matches('"').to_string();
|
||||
found.push((node, name));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if label == "Op" && children.len() >= 2 {
|
||||
let ir_inputs = walk_ilist_simple(egraph, &children[1]);
|
||||
for inp in ir_inputs {
|
||||
stack.push(inp);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
found
|
||||
}
|
||||
|
||||
fn walk_ilist_simple<'a>(
|
||||
egraph: &'a SerializedEGraph,
|
||||
ilist_eclass: &'a ClassId,
|
||||
) -> Vec<&'a NodeId> {
|
||||
let mut inputs = Vec::new();
|
||||
let mut current = resolve_first_node(egraph, ilist_eclass);
|
||||
|
||||
loop {
|
||||
let (label, children) = &egraph.enodes[current];
|
||||
if label == "INil" {
|
||||
break;
|
||||
}
|
||||
if label != "ICons" {
|
||||
break;
|
||||
}
|
||||
let ir_node = resolve_first_ir_node(egraph, &children[0]);
|
||||
inputs.push(ir_node);
|
||||
current = resolve_first_node(egraph, &children[1]);
|
||||
}
|
||||
|
||||
inputs
|
||||
}
|
||||
|
||||
fn resolve_first_node<'a>(egraph: &'a SerializedEGraph, eclass: &ClassId) -> &'a NodeId {
|
||||
&egraph.eclasses[eclass].1[0]
|
||||
}
|
||||
|
||||
fn resolve_first_ir_node<'a>(egraph: &'a SerializedEGraph, eclass: &ClassId) -> &'a NodeId {
|
||||
let nodes = &egraph.eclasses[eclass].1;
|
||||
for node in nodes {
|
||||
let label = &egraph.enodes[node].0;
|
||||
if label == "Op" || label == "Input" {
|
||||
return node;
|
||||
}
|
||||
}
|
||||
&nodes[0]
|
||||
}
|
||||
|
||||
fn resolve_op_with_kind<'a>(
|
||||
egraph: &'a SerializedEGraph,
|
||||
node: &'a NodeId,
|
||||
kind_substr: &str,
|
||||
) -> Option<&'a NodeId> {
|
||||
let class = egraph.node_to_class.get(node)?;
|
||||
for candidate in &egraph.eclasses[class].1 {
|
||||
let (label, children) = &egraph.enodes[candidate];
|
||||
if label != "Op" || children.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let kind = resolve_first_node(egraph, &children[0]);
|
||||
if egraph.enodes[kind].0.contains(kind_substr) {
|
||||
return Some(candidate);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn logical_binary_inputs<'a>(
|
||||
egraph: &'a SerializedEGraph,
|
||||
node: &'a NodeId,
|
||||
op_name: &str,
|
||||
) -> Option<Vec<&'a NodeId>> {
|
||||
if let Some(op_node) = resolve_op_with_kind(egraph, node, op_name) {
|
||||
let (_, children) = &egraph.enodes[op_node];
|
||||
return Some(walk_ilist_simple(egraph, &children[1]));
|
||||
}
|
||||
|
||||
let (label, children) = &egraph.enodes[node];
|
||||
if label != "Op" || children.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
let kind = resolve_first_node(egraph, &children[0]);
|
||||
if egraph.enodes[kind].0.contains("CudaBinaryElementwise") {
|
||||
let opcode_class = egraph.enodes[kind].1.first()?;
|
||||
let opcode_node = resolve_first_node(egraph, opcode_class);
|
||||
if egraph.enodes[opcode_node].0.trim_matches('"') != op_name {
|
||||
return None;
|
||||
}
|
||||
return Some(
|
||||
walk_ilist_simple(egraph, &children[1])
|
||||
.into_iter()
|
||||
.map(|input| unwrap_fusion_start(egraph, input))
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
if !egraph.enodes[kind].0.contains("FusionEnd") {
|
||||
return None;
|
||||
}
|
||||
let fe_inputs = walk_ilist_simple(egraph, &children[1]);
|
||||
let elem = *fe_inputs.first()?;
|
||||
let (elem_label, elem_children) = &egraph.enodes[elem];
|
||||
if elem_label != "Op" || elem_children.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
let elem_kind = resolve_first_node(egraph, &elem_children[0]);
|
||||
if !egraph.enodes[elem_kind].0.contains("CudaBinaryElementwise") {
|
||||
return None;
|
||||
}
|
||||
let opcode_class = egraph.enodes[elem_kind].1.first()?;
|
||||
let opcode_node = resolve_first_node(egraph, opcode_class);
|
||||
if egraph.enodes[opcode_node].0.trim_matches('"') != op_name {
|
||||
return None;
|
||||
}
|
||||
Some(
|
||||
walk_ilist_simple(egraph, &elem_children[1])
|
||||
.into_iter()
|
||||
.map(|input| unwrap_fusion_start(egraph, input))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
fn unwrap_fusion_start<'a>(egraph: &'a SerializedEGraph, node: &'a NodeId) -> &'a NodeId {
|
||||
let (label, children) = &egraph.enodes[node];
|
||||
if label != "Op" || children.len() < 2 {
|
||||
return node;
|
||||
}
|
||||
let kind = resolve_first_node(egraph, &children[0]);
|
||||
if !egraph.enodes[kind].0.contains("FusionStart") {
|
||||
return node;
|
||||
}
|
||||
walk_ilist_simple(egraph, &children[1])
|
||||
.first()
|
||||
.copied()
|
||||
.unwrap_or(node)
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
; FlashInfer batch decode attention rewrite rule.
|
||||
;
|
||||
; Matches the paged attention pattern for ANY model with GQA:
|
||||
; Gather(K_cache) → GQA broadcast → Q*K^T matmul → scale → add mask → softmax → attn*V matmul
|
||||
; Gather(V_cache) → GQA broadcast ──────────────────────────────────────────→ attn*V matmul
|
||||
;
|
||||
; Structural anchors (prevent false matches on MLP/other ops):
|
||||
; - Gather ops from 2D cache pools (MLP never uses Gather)
|
||||
; - GQA broadcast via Mul(gathered, Constant(1.0)) with all-zero strides
|
||||
; - Scale Mul(QK, constant) connecting QK scores to mask Add
|
||||
; - Mask Add with zero-stride broadcast in first dim (nheads broadcast)
|
||||
; - Data flow: two sequential matmul+reduce pairs connected through softmax
|
||||
;
|
||||
; The egglog rule captures the mask as 5th input. During extract(), a Rust
|
||||
; function walks the mask's computation chain in the e-graph to locate the
|
||||
; qo_indptr and kv_indptr Input nodes (validated via the Constant(1e10) anchor
|
||||
; and structural checks). These are appended as inputs 5 and 6 so FlashInfer
|
||||
; can build the CSR page table directly — no runtime derivation needed.
|
||||
;
|
||||
; Shape dimensions are egglog variables, not pinned constants.
|
||||
; Dynamic dims "s" (batch/seq) and "c" (context) stay pinned as MVar.
|
||||
|
||||
(rule
|
||||
(
|
||||
; ── Second matmul: Mul(softmax_out, V_gqa) ──
|
||||
; Shape: (nheads, s, hdim, c) — 4D
|
||||
(= ?mul2 (Op (Mul
|
||||
(ECons ?nheads (ECons (MVar "s") (ECons ?hdim (ECons (MVar "c") (ENil)))))
|
||||
?mul2_a_strides
|
||||
?mul2_b_strides
|
||||
?mul2_out_strides)
|
||||
(ICons ?soft (ICons ?v_gqa (INil)))))
|
||||
|
||||
; ── Second matmul: Sum (reduction over c) → output ──
|
||||
; Shape: (nheads, s, hdim) — reduces c
|
||||
(= ?output (Op (Sum
|
||||
(ECons ?nheads2 (ECons (MVar "s") (ECons ?hdim2 (ENil))))
|
||||
(MVar "c")
|
||||
?out_in_strides
|
||||
(MIter)
|
||||
?out_out_strides)
|
||||
(ICons ?mul2 (INil))))
|
||||
|
||||
; ── V GQA broadcast: Mul(V_gathered, 1.0) with zero-stride constant ──
|
||||
; Shape: (nheads, c, hdim) — 3D
|
||||
(= ?v_gqa_const (Op (Constant 1.000000) (INil)))
|
||||
(= ?v_gqa (Op (Mul
|
||||
(ECons ?nheads3 (ECons (MVar "c") (ECons ?hdim3 (ENil))))
|
||||
?v_gqa_a_strides
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ECons (MNum 0) (ENil))))
|
||||
?v_gqa_out_strides)
|
||||
(ICons ?v_gathered (ICons ?v_gqa_const (INil)))))
|
||||
|
||||
; ── V Gather: rows from V_cache (2D) ──
|
||||
; Shape: (c, kvdim), Source: (num_slots, kvdim)
|
||||
(= ?v_gathered (Op (Gather
|
||||
(ECons (MVar "c") (ECons ?kvdim (ENil)))
|
||||
?v_gather_strides
|
||||
(ECons ?num_slots_v (ECons ?kvdim2 (ENil)))
|
||||
?v_src_strides)
|
||||
(ICons ?v_idx (ICons ?v_cache (INil)))))
|
||||
|
||||
; ── First matmul: Mul(Q, K_gqa) ──
|
||||
; Shape: (nheads, s, c, hdim) — 4D
|
||||
(= ?mul1 (Op (Mul
|
||||
(ECons ?nheads4 (ECons (MVar "s") (ECons (MVar "c") (ECons ?hdim4 (ENil)))))
|
||||
?mul1_a_strides
|
||||
?mul1_b_strides
|
||||
?mul1_out_strides)
|
||||
(ICons ?q (ICons ?k_gqa (INil)))))
|
||||
|
||||
; ── First matmul: Sum (reduction over hdim) → QK scores ──
|
||||
; Shape: (nheads, s, c) — reduces hdim
|
||||
(= ?qk (Op (Sum
|
||||
(ECons ?nheads5 (ECons (MVar "s") (ECons (MVar "c") (ENil))))
|
||||
?hdim5
|
||||
?qk_in_strides
|
||||
(MIter)
|
||||
?qk_out_strides)
|
||||
(ICons ?mul1 (INil))))
|
||||
|
||||
; ── Mask Add: Add(scaled_QK, mask) ──
|
||||
; Shape: (nheads, s, c) — 3D
|
||||
; Mask is broadcast from (s, c) via zero-stride in first dim (nheads).
|
||||
(= ?masked (Op (Add
|
||||
(ECons ?nheads8 (ECons (MVar "s") (ECons (MVar "c") (ENil))))
|
||||
?mask_add_a_strides
|
||||
(ECons (MNum 0) ?mask_rest_strides)
|
||||
?mask_add_out_strides)
|
||||
(ICons ?scaled_qk (ICons ?mask (INil)))))
|
||||
|
||||
; FlashInfer needs qo_indptr/kv_indptr to be recoverable from the mask
|
||||
; expression. Do not match examples that pass a precomputed mask Input.
|
||||
(= ?mask (Op (Add ?inner_mask_shape ?inner_mask_a_strides ?inner_mask_b_strides ?inner_mask_out_strides)
|
||||
(ICons ?mask_scaled_allowed (ICons ?mask_offset (INil)))))
|
||||
(= ?mask_scaled_allowed (Op (Mul ?allowed_shape ?allowed_strides ?scale_const_strides ?scaled_allowed_strides)
|
||||
(ICons ?mask_allowed (ICons ?mask_scale_const (INil)))))
|
||||
(= ?mask_scale_const (Op (Constant ?mask_scale_val) (INil)))
|
||||
(> ?mask_scale_val 9999999999.0)
|
||||
(< ?mask_scale_val 10000000001.0)
|
||||
|
||||
; ── K GQA broadcast: Mul(K_gathered, 1.0) with zero-stride constant ──
|
||||
; Shape: (nheads, hdim, c) — 3D
|
||||
(= ?k_gqa_const (Op (Constant 1.000000) (INil)))
|
||||
(= ?k_gqa (Op (Mul
|
||||
(ECons ?nheads6 (ECons ?hdim6 (ECons (MVar "c") (ENil))))
|
||||
?k_gqa_a_strides
|
||||
(ECons (MNum 0) (ECons (MNum 0) (ECons (MNum 0) (ENil))))
|
||||
?k_gqa_out_strides)
|
||||
(ICons ?k_gathered (ICons ?k_gqa_const (INil)))))
|
||||
|
||||
; ── K Gather: rows from K_cache (2D) ──
|
||||
; Shape: (c, kvdim), Source: (num_slots, kvdim)
|
||||
(= ?k_gathered (Op (Gather
|
||||
(ECons (MVar "c") (ECons ?kvdim3 (ENil)))
|
||||
?k_gather_strides
|
||||
(ECons ?num_slots_k (ECons ?kvdim4 (ENil)))
|
||||
?k_src_strides)
|
||||
(ICons ?k_idx (ICons ?k_cache (INil)))))
|
||||
|
||||
; ── Dtype consistency ──
|
||||
(= ?dt (dtype ?q))
|
||||
(= ?dt (dtype ?k_cache))
|
||||
(= ?dt (dtype ?v_cache))
|
||||
)
|
||||
(
|
||||
(let ?fi (Op (FlashInferAttention
|
||||
?nheads (MDiv ?kvdim ?hdim) ?hdim (MNum 1) (MVar "s"))
|
||||
(ICons ?q (ICons ?k_cache (ICons ?v_cache (ICons ?k_idx (ICons ?mask (INil))))))))
|
||||
(union ?output ?fi)
|
||||
(set (dtype ?fi) ?dt)
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name "FlashInfer batch decode attention"
|
||||
)
|
||||
504
crates/luminal_cuda_lite/src/host/flashinfer/jit.rs
Normal file
504
crates/luminal_cuda_lite/src/host/flashinfer/jit.rs
Normal file
@@ -0,0 +1,504 @@
|
||||
//! JIT compilation and dynamic loading of FlashInfer kernels.
|
||||
//!
|
||||
//! Everything runs at compile / profiling time — there is no `build.rs`.
|
||||
//! `wrapper.cu` and `wrapper.h` are embedded via `include_str!()` and
|
||||
//! extracted to the cache directory on first use. The FlashInfer + CUTLASS
|
||||
//! header trees are located by probing `LUMINAL_FLASHINFER_DIR`, a small set
|
||||
//! of default paths, and (as a last resort) by `git clone`-ing FlashInfer at
|
||||
//! a pinned commit into the cache. `nvcc` is then invoked with the model's
|
||||
//! actual `HEAD_DIM` and the resulting `.so` is `dlopen`'d.
|
||||
//!
|
||||
//! `ensure_compiled` is called from `FlashInferAttention::extract()`, i.e.
|
||||
//! during luminal's compile / GA-profiling phase, not from `execute()`. After
|
||||
//! the first call the `OnceLock` makes subsequent lookups free.
|
||||
|
||||
use std::{
|
||||
ffi::c_void,
|
||||
hash::{Hash, Hasher},
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
sync::OnceLock,
|
||||
};
|
||||
|
||||
// ── Function pointer types matching wrapper.h ──
|
||||
|
||||
pub type PlanFn = unsafe extern "C" fn(
|
||||
float_workspace: *mut c_void,
|
||||
float_ws_size: usize,
|
||||
int_workspace: *mut c_void,
|
||||
int_ws_size: usize,
|
||||
page_locked_int_workspace: *mut c_void,
|
||||
indptr_h: *mut i32,
|
||||
batch_size: i32,
|
||||
num_qo_heads: i32,
|
||||
num_kv_heads: i32,
|
||||
page_size: i32,
|
||||
head_dim: i32,
|
||||
stream: *mut c_void,
|
||||
plan_info_out: *mut i64,
|
||||
plan_info_len_out: *mut i32,
|
||||
) -> i32;
|
||||
|
||||
pub type RunFn = unsafe extern "C" fn(
|
||||
float_workspace: *mut c_void,
|
||||
float_ws_size: usize,
|
||||
int_workspace: *mut c_void,
|
||||
plan_info_vec: *mut i64,
|
||||
plan_info_len: i32,
|
||||
q: *mut f32,
|
||||
k_cache: *mut f32,
|
||||
v_cache: *mut f32,
|
||||
kv_indptr: *mut i32,
|
||||
kv_indices: *mut i32,
|
||||
kv_last_page_len: *mut i32,
|
||||
output: *mut f32,
|
||||
batch_size: i32,
|
||||
num_qo_heads: i32,
|
||||
num_kv_heads: i32,
|
||||
page_size: i32,
|
||||
head_dim: i32,
|
||||
stream: *mut c_void,
|
||||
) -> i32;
|
||||
|
||||
pub type ExtractFn = unsafe extern "C" fn(
|
||||
flat_idx: *const i32,
|
||||
out: *mut i32,
|
||||
c: i32,
|
||||
kv_dim: i32,
|
||||
stream: *mut c_void,
|
||||
);
|
||||
|
||||
pub type DeriveIndptrFn =
|
||||
unsafe extern "C" fn(mask: *const f32, indptr: *mut i32, s: i32, c: i32, stream: *mut c_void);
|
||||
|
||||
pub type TransposeOutputFn = unsafe extern "C" fn(
|
||||
src: *const f32,
|
||||
dst: *mut f32,
|
||||
batch: i32,
|
||||
heads: i32,
|
||||
dim: i32,
|
||||
stream: *mut c_void,
|
||||
);
|
||||
|
||||
pub type PrefillPlanFn = unsafe extern "C" fn(
|
||||
float_workspace: *mut c_void,
|
||||
float_ws_size: usize,
|
||||
int_workspace: *mut c_void,
|
||||
int_ws_size: usize,
|
||||
page_locked_int_workspace: *mut c_void,
|
||||
qo_indptr_h: *mut i32,
|
||||
kv_indptr_h: *mut i32,
|
||||
total_num_rows: i32,
|
||||
batch_size: i32,
|
||||
num_qo_heads: i32,
|
||||
num_kv_heads: i32,
|
||||
page_size: i32,
|
||||
head_dim: i32,
|
||||
stream: *mut c_void,
|
||||
plan_info_out: *mut i64,
|
||||
plan_info_len_out: *mut i32,
|
||||
) -> i32;
|
||||
|
||||
pub type PrefillRunFn = unsafe extern "C" fn(
|
||||
float_workspace: *mut c_void,
|
||||
float_ws_size: usize,
|
||||
int_workspace: *mut c_void,
|
||||
plan_info_vec: *mut i64,
|
||||
plan_info_len: i32,
|
||||
q: *mut f32,
|
||||
k_cache: *mut f32,
|
||||
v_cache: *mut f32,
|
||||
qo_indptr: *mut i32,
|
||||
kv_indptr: *mut i32,
|
||||
kv_indices: *mut i32,
|
||||
kv_last_page_len: *mut i32,
|
||||
output: *mut f32,
|
||||
total_num_rows: i32,
|
||||
batch_size: i32,
|
||||
num_qo_heads: i32,
|
||||
num_kv_heads: i32,
|
||||
page_size: i32,
|
||||
head_dim: i32,
|
||||
stream: *mut c_void,
|
||||
) -> i32;
|
||||
|
||||
// ── Embedded CUDA sources ──
|
||||
|
||||
const WRAPPER_CU: &str = include_str!("wrapper.cu");
|
||||
const WRAPPER_H: &str = include_str!("wrapper.h");
|
||||
|
||||
// ── Loaded library handle ──
|
||||
|
||||
pub struct FlashInferLib {
|
||||
// Keep the handle alive so the dlopen'd .so remains mapped.
|
||||
_lib: libloading::Library,
|
||||
pub plan: PlanFn,
|
||||
pub run: RunFn,
|
||||
pub extract_slot_indices: ExtractFn,
|
||||
pub derive_indptr_from_mask: DeriveIndptrFn,
|
||||
pub transpose_output: TransposeOutputFn,
|
||||
pub prefill_plan: PrefillPlanFn,
|
||||
pub prefill_run: PrefillRunFn,
|
||||
}
|
||||
|
||||
// SAFETY: The library handle and function pointers are valid for the lifetime
|
||||
// of the process. All functions are called with proper CUDA stream serialization.
|
||||
unsafe impl Send for FlashInferLib {}
|
||||
unsafe impl Sync for FlashInferLib {}
|
||||
|
||||
static FLASHINFER_LIB: OnceLock<FlashInferLib> = OnceLock::new();
|
||||
|
||||
/// Ensure the FlashInfer library is compiled and loaded for the given HEAD_DIM.
|
||||
/// Returns a reference to the loaded library. Thread-safe via OnceLock.
|
||||
pub fn ensure_compiled(head_dim: usize) -> &'static FlashInferLib {
|
||||
FLASHINFER_LIB.get_or_init(|| {
|
||||
assert!(
|
||||
matches!(head_dim, 64 | 128 | 256),
|
||||
"FlashInfer: unsupported HEAD_DIM={} (must be 64, 128, or 256 for f32)",
|
||||
head_dim
|
||||
);
|
||||
let so_path = compile_or_cache(head_dim);
|
||||
unsafe {
|
||||
FlashInferLib::load(&so_path)
|
||||
.unwrap_or_else(|e| panic!("Failed to load FlashInfer library: {e}"))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
impl FlashInferLib {
|
||||
/// Load a compiled FlashInfer .so and resolve function pointers.
|
||||
///
|
||||
/// # Safety
|
||||
/// The .so must be a valid FlashInfer wrapper compiled from wrapper.cu.
|
||||
unsafe fn load(path: &Path) -> Result<Self, libloading::Error> {
|
||||
let lib = unsafe { libloading::Library::new(path)? };
|
||||
let plan: PlanFn = unsafe { *lib.get::<PlanFn>(b"flashinfer_batch_decode_plan\0")? };
|
||||
let run: RunFn = unsafe { *lib.get::<RunFn>(b"flashinfer_batch_decode_run\0")? };
|
||||
let extract_slot_indices: ExtractFn =
|
||||
unsafe { *lib.get::<ExtractFn>(b"flashinfer_extract_slot_indices\0")? };
|
||||
let derive_indptr_from_mask: DeriveIndptrFn =
|
||||
unsafe { *lib.get::<DeriveIndptrFn>(b"flashinfer_derive_indptr_from_mask\0")? };
|
||||
let transpose_output: TransposeOutputFn =
|
||||
unsafe { *lib.get::<TransposeOutputFn>(b"flashinfer_transpose_output\0")? };
|
||||
let prefill_plan: PrefillPlanFn =
|
||||
unsafe { *lib.get::<PrefillPlanFn>(b"flashinfer_batch_prefill_plan\0")? };
|
||||
let prefill_run: PrefillRunFn =
|
||||
unsafe { *lib.get::<PrefillRunFn>(b"flashinfer_batch_prefill_run\0")? };
|
||||
Ok(Self {
|
||||
_lib: lib,
|
||||
plan,
|
||||
run,
|
||||
extract_slot_indices,
|
||||
derive_indptr_from_mask,
|
||||
transpose_output,
|
||||
prefill_plan,
|
||||
prefill_run,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Compile wrapper.cu for the given HEAD_DIM, or return cached .so path.
|
||||
fn compile_or_cache(head_dim: usize) -> PathBuf {
|
||||
let cache_dir = cache_directory();
|
||||
std::fs::create_dir_all(&cache_dir).expect("Failed to create FlashInfer cache directory");
|
||||
|
||||
// Extract bundled wrapper sources to the cache so nvcc can compile them.
|
||||
let (wrapper_cu_path, wrapper_h_dir) = extract_wrapper_sources(&cache_dir);
|
||||
|
||||
let arch = detect_cuda_arch();
|
||||
// Bake a hash of the embedded wrapper into the .so name so old caches are
|
||||
// discarded automatically when wrapper.cu or wrapper.h change.
|
||||
let wrapper_hash = wrapper_source_hash();
|
||||
let so_name = format!(
|
||||
"libflashinfer_hd{}_{}_w{:016x}.so",
|
||||
head_dim, arch, wrapper_hash
|
||||
);
|
||||
let so_path = cache_dir.join(&so_name);
|
||||
|
||||
if so_path.exists() {
|
||||
eprintln!(
|
||||
"FlashInfer: using cached library for HEAD_DIM={} ({})",
|
||||
head_dim,
|
||||
so_path.display()
|
||||
);
|
||||
return so_path;
|
||||
}
|
||||
|
||||
let Some((flashinfer_include, cutlass_include)) = locate_flashinfer_includes() else {
|
||||
panic!(
|
||||
"FlashInfer: could not locate header tree. Set LUMINAL_FLASHINFER_DIR to the \
|
||||
FlashInfer source root (the directory containing `include/` and \
|
||||
`3rdparty/cutlass/include/`)."
|
||||
);
|
||||
};
|
||||
|
||||
eprintln!(
|
||||
"FlashInfer: JIT compiling for HEAD_DIM={}, arch={} ...",
|
||||
head_dim, arch
|
||||
);
|
||||
let start = std::time::Instant::now();
|
||||
|
||||
let output = Command::new("nvcc")
|
||||
.args([
|
||||
"-shared",
|
||||
"-o",
|
||||
so_path.to_str().unwrap(),
|
||||
&format!("-DLUMINAL_HEAD_DIM={}", head_dim),
|
||||
wrapper_cu_path.to_str().unwrap(),
|
||||
"-I",
|
||||
flashinfer_include.to_str().unwrap(),
|
||||
"-I",
|
||||
cutlass_include.to_str().unwrap(),
|
||||
"-I",
|
||||
wrapper_h_dir.to_str().unwrap(),
|
||||
"-std=c++17",
|
||||
&format!("-arch={}", arch),
|
||||
"-O3",
|
||||
"--expt-relaxed-constexpr",
|
||||
"-w",
|
||||
"-rdc=true",
|
||||
"--compiler-options",
|
||||
"-fPIC",
|
||||
])
|
||||
.output()
|
||||
.expect("Failed to run nvcc. Is the CUDA toolkit installed?");
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let _ = std::fs::remove_file(&so_path);
|
||||
panic!(
|
||||
"FlashInfer JIT compilation failed (HEAD_DIM={}, arch={}):\nstdout: {}\nstderr: {}",
|
||||
head_dim, arch, stdout, stderr
|
||||
);
|
||||
}
|
||||
|
||||
let elapsed = start.elapsed();
|
||||
eprintln!(
|
||||
"FlashInfer: compiled in {:.1}s → {}",
|
||||
elapsed.as_secs_f64(),
|
||||
so_path.display()
|
||||
);
|
||||
|
||||
so_path
|
||||
}
|
||||
|
||||
/// Returns ~/.cache/luminal/flashinfer/
|
||||
fn cache_directory() -> PathBuf {
|
||||
let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".to_string());
|
||||
PathBuf::from(home)
|
||||
.join(".cache")
|
||||
.join("luminal")
|
||||
.join("flashinfer")
|
||||
}
|
||||
|
||||
/// Drop the embedded wrapper.cu/wrapper.h into the cache dir so nvcc has files
|
||||
/// on disk to compile. Returns (wrapper.cu path, directory containing wrapper.h).
|
||||
fn extract_wrapper_sources(cache_dir: &Path) -> (PathBuf, PathBuf) {
|
||||
let cu = cache_dir.join("wrapper.cu");
|
||||
let h = cache_dir.join("wrapper.h");
|
||||
write_if_changed(&cu, WRAPPER_CU.as_bytes());
|
||||
write_if_changed(&h, WRAPPER_H.as_bytes());
|
||||
(cu, cache_dir.to_path_buf())
|
||||
}
|
||||
|
||||
fn write_if_changed(path: &Path, contents: &[u8]) {
|
||||
if let Ok(existing) = std::fs::read(path)
|
||||
&& existing == contents
|
||||
{
|
||||
return;
|
||||
}
|
||||
std::fs::write(path, contents).unwrap_or_else(|e| {
|
||||
panic!(
|
||||
"FlashInfer: failed to write wrapper source to {}: {e}",
|
||||
path.display()
|
||||
)
|
||||
});
|
||||
}
|
||||
|
||||
fn wrapper_source_hash() -> u64 {
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
WRAPPER_CU.hash(&mut hasher);
|
||||
WRAPPER_H.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
// ── Pinned FlashInfer source ──
|
||||
//
|
||||
// Bumping this constant invalidates the cached source tree AND the cached .so
|
||||
// (the .so cache key incorporates the wrapper hash, which is rebuilt against
|
||||
// these headers, so different headers compile to a different .so file even at
|
||||
// the same head_dim). If you change `FLASHINFER_GIT_REV`, also re-check
|
||||
// `wrapper.cu` against the new FlashInfer API.
|
||||
|
||||
const FLASHINFER_GIT_URL: &str = "https://github.com/flashinfer-ai/flashinfer.git";
|
||||
const CUTLASS_GIT_URL: &str = "https://github.com/NVIDIA/cutlass.git";
|
||||
const FLASHINFER_GIT_REV: &str = "f1e6fdcb8f65104047697f022b5d055ef022d763";
|
||||
const CUTLASS_GIT_REV: &str = "f3fde58372d33e9a5650ba7b80fc48b3b49d40c8";
|
||||
|
||||
fn locate_flashinfer_includes() -> Option<(PathBuf, PathBuf)> {
|
||||
if let Ok(path) = std::env::var("LUMINAL_FLASHINFER_DIR")
|
||||
&& !path.is_empty()
|
||||
{
|
||||
let root = PathBuf::from(path);
|
||||
let inc = root.join("include");
|
||||
let cutlass = root.join("3rdparty/cutlass/include");
|
||||
if inc.exists() && cutlass.exists() {
|
||||
return Some((inc, cutlass));
|
||||
}
|
||||
eprintln!(
|
||||
"FlashInfer: LUMINAL_FLASHINFER_DIR={} did not contain include/ and \
|
||||
3rdparty/cutlass/include/ — falling back to default locations",
|
||||
root.display()
|
||||
);
|
||||
}
|
||||
|
||||
let home = std::env::var("HOME").unwrap_or_default();
|
||||
let candidates = [
|
||||
PathBuf::from(&home).join("luminal_cuda/crates/luminal_cuda/flashinfer"),
|
||||
PathBuf::from(&home).join("luminal_cuda/flashinfer"),
|
||||
PathBuf::from("/opt/luminal_cuda/crates/luminal_cuda/flashinfer"),
|
||||
];
|
||||
for root in candidates {
|
||||
let inc = root.join("include");
|
||||
let cutlass = root.join("3rdparty/cutlass/include");
|
||||
if inc.exists() && cutlass.exists() {
|
||||
return Some((inc, cutlass));
|
||||
}
|
||||
}
|
||||
|
||||
// Last resort: fetch the pinned commit into the cache directory.
|
||||
fetch_flashinfer_source().ok().map(|root| {
|
||||
let inc = root.join("include");
|
||||
let cutlass = root.join("3rdparty/cutlass/include");
|
||||
(inc, cutlass)
|
||||
})
|
||||
}
|
||||
|
||||
/// Clone FlashInfer at `FLASHINFER_GIT_REV` + CUTLASS at `CUTLASS_GIT_REV`
|
||||
/// into `~/.cache/luminal/flashinfer-src/<short_rev>/` if absent, then return
|
||||
/// the FlashInfer root directory. ~50 MB one-time download; subsequent calls
|
||||
/// short-circuit on the directory check.
|
||||
fn fetch_flashinfer_source() -> Result<PathBuf, String> {
|
||||
let short = &FLASHINFER_GIT_REV[..12];
|
||||
let cache_root = cache_directory().join("flashinfer-src").join(short);
|
||||
let inc = cache_root.join("include");
|
||||
let cutlass_inc = cache_root.join("3rdparty/cutlass/include");
|
||||
|
||||
if inc.exists() && cutlass_inc.exists() {
|
||||
return Ok(cache_root);
|
||||
}
|
||||
|
||||
let parent = cache_root.parent().unwrap();
|
||||
std::fs::create_dir_all(parent)
|
||||
.map_err(|e| format!("failed to create {}: {e}", parent.display()))?;
|
||||
|
||||
// Clone into a staging dir, then atomic rename. Protects against multiple
|
||||
// processes racing to fetch the same source.
|
||||
let staging = parent.join(format!(".staging-{}-{}", short, std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&staging);
|
||||
|
||||
eprintln!(
|
||||
"FlashInfer: cloning {FLASHINFER_GIT_URL} @ {short} into {} (one-time fetch, ~50 MB) …",
|
||||
cache_root.display()
|
||||
);
|
||||
|
||||
run_git(&[
|
||||
"clone",
|
||||
"--filter=blob:none",
|
||||
"--no-checkout",
|
||||
FLASHINFER_GIT_URL,
|
||||
staging.to_str().unwrap(),
|
||||
])?;
|
||||
run_git_in(&staging, &["checkout", FLASHINFER_GIT_REV])?;
|
||||
|
||||
// Init only the CUTLASS submodule (skip spdlog — we don't need it for kernels).
|
||||
let cutlass_path = staging.join("3rdparty/cutlass");
|
||||
let _ = std::fs::remove_dir_all(&cutlass_path);
|
||||
run_git(&[
|
||||
"clone",
|
||||
"--filter=blob:none",
|
||||
"--no-checkout",
|
||||
CUTLASS_GIT_URL,
|
||||
cutlass_path.to_str().unwrap(),
|
||||
])?;
|
||||
run_git_in(&cutlass_path, &["checkout", CUTLASS_GIT_REV])?;
|
||||
|
||||
if !staging.join("include").exists() {
|
||||
return Err(format!(
|
||||
"FlashInfer clone succeeded but include/ missing at {}",
|
||||
staging.display()
|
||||
));
|
||||
}
|
||||
if !staging.join("3rdparty/cutlass/include").exists() {
|
||||
return Err(format!(
|
||||
"CUTLASS clone succeeded but include/ missing at {}",
|
||||
staging.join("3rdparty/cutlass").display()
|
||||
));
|
||||
}
|
||||
|
||||
// Atomic-ish rename. If another process beat us to it, just keep theirs.
|
||||
match std::fs::rename(&staging, &cache_root) {
|
||||
Ok(()) => {}
|
||||
Err(_) if cache_root.exists() => {
|
||||
let _ = std::fs::remove_dir_all(&staging);
|
||||
}
|
||||
Err(e) => return Err(format!("rename to {} failed: {e}", cache_root.display())),
|
||||
}
|
||||
|
||||
Ok(cache_root)
|
||||
}
|
||||
|
||||
fn run_git(args: &[&str]) -> Result<(), String> {
|
||||
let out = Command::new("git")
|
||||
.args(args)
|
||||
.output()
|
||||
.map_err(|e| format!("failed to spawn `git`: {e}. Is git installed?"))?;
|
||||
if !out.status.success() {
|
||||
return Err(format!(
|
||||
"`git {}` failed: {}",
|
||||
args.join(" "),
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run_git_in(cwd: &Path, args: &[&str]) -> Result<(), String> {
|
||||
let out = Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(cwd)
|
||||
.output()
|
||||
.map_err(|e| format!("failed to spawn `git`: {e}"))?;
|
||||
if !out.status.success() {
|
||||
return Err(format!(
|
||||
"`git {}` in {} failed: {}",
|
||||
args.join(" "),
|
||||
cwd.display(),
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Detect CUDA arch via env override → nvidia-smi → default sm_80.
|
||||
fn detect_cuda_arch() -> String {
|
||||
if let Ok(arch) = std::env::var("FLASHINFER_CUDA_ARCH") {
|
||||
return arch;
|
||||
}
|
||||
|
||||
if let Ok(output) = Command::new("nvidia-smi")
|
||||
.args(["--query-gpu=compute_cap", "--format=csv,noheader"])
|
||||
.output()
|
||||
&& output.status.success()
|
||||
{
|
||||
let cap = String::from_utf8_lossy(&output.stdout);
|
||||
let cap = cap.trim().lines().next().unwrap_or("8.0");
|
||||
let sm = cap.replace('.', "");
|
||||
if !sm.is_empty() {
|
||||
return format!("sm_{}", sm);
|
||||
}
|
||||
}
|
||||
|
||||
"sm_80".to_string()
|
||||
}
|
||||
424
crates/luminal_cuda_lite/src/host/flashinfer/mod.rs
Normal file
424
crates/luminal_cuda_lite/src/host/flashinfer/mod.rs
Normal file
@@ -0,0 +1,424 @@
|
||||
pub mod find_indptrs;
|
||||
pub mod jit;
|
||||
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
|
||||
use luminal::{
|
||||
egglog_utils::{
|
||||
api::{Rule, SortDef, sort},
|
||||
base::{EXPRESSION, OP_KIND},
|
||||
extract_expr,
|
||||
},
|
||||
op::{EgglogOp, LLIROp},
|
||||
prelude::{
|
||||
tracing::{Level, span},
|
||||
*,
|
||||
},
|
||||
};
|
||||
|
||||
use crate::{
|
||||
cudarc::driver::{CudaSlice, CudaStream, DevicePtr, result},
|
||||
host::{DeviceBuffer, HostOp},
|
||||
};
|
||||
|
||||
/// FlashInfer attention op (batch decode, fp32).
|
||||
///
|
||||
/// Replaces the full paged-GQA attention pattern (gather → broadcast → Q*K^T →
|
||||
/// scale → mask → softmax → *V) with a single FlashInfer fused kernel.
|
||||
///
|
||||
/// Graph inputs (7): Q, K_pool, V_pool, flat_gather_idx, mask, qo_indptr, kv_indptr.
|
||||
/// The egglog rule captures the first 5; `extract()` appends qo/kv indptrs after
|
||||
/// walking the e-graph from the mask. `batch_size` is derived at runtime from the
|
||||
/// indptr length (= num_sequences + 1).
|
||||
#[derive(Debug)]
|
||||
pub struct FlashInferAttention {
|
||||
pub num_qo_heads: usize,
|
||||
pub num_kv_heads: usize,
|
||||
pub head_dim: usize,
|
||||
pub page_size: usize,
|
||||
pub batch_dim: Expression,
|
||||
|
||||
pub plan_info: Mutex<Vec<i64>>,
|
||||
}
|
||||
|
||||
// SAFETY: PAGE_LOCKED_WORKSPACE holds a raw pointer to page-locked CUDA memory
|
||||
// allocated once and serialized via the CUDA stream that owns it.
|
||||
unsafe impl Send for FlashInferAttention {}
|
||||
unsafe impl Sync for FlashInferAttention {}
|
||||
|
||||
const FLOAT_WORKSPACE_SIZE: usize = 128 * 1024 * 1024; // 128 MiB
|
||||
const INT_WORKSPACE_SIZE: usize = 8 * 1024 * 1024; // 8 MiB
|
||||
|
||||
static PAGE_LOCKED_WORKSPACE: OnceLock<PageLockedPtr> = OnceLock::new();
|
||||
|
||||
struct PageLockedPtr(*mut u8);
|
||||
|
||||
// SAFETY: The pointer is page-locked CUDA memory allocated once via
|
||||
// posix_memalign + cudaHostRegister and only mutated during OnceLock
|
||||
// initialization.
|
||||
unsafe impl Send for PageLockedPtr {}
|
||||
unsafe impl Sync for PageLockedPtr {}
|
||||
|
||||
impl std::fmt::Debug for PageLockedPtr {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "PageLockedPtr({:p})", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for FlashInferAttention {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
num_qo_heads: 0,
|
||||
num_kv_heads: 0,
|
||||
head_dim: 0,
|
||||
page_size: 0,
|
||||
batch_dim: Expression::default(),
|
||||
plan_info: Mutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EgglogOp for FlashInferAttention {
|
||||
fn sort(&self) -> SortDef {
|
||||
sort(
|
||||
OP_KIND,
|
||||
"FlashInferAttention",
|
||||
&[
|
||||
("num_qo_heads", EXPRESSION),
|
||||
("num_kv_heads", EXPRESSION),
|
||||
("head_dim", EXPRESSION),
|
||||
("page_size", EXPRESSION),
|
||||
("batch_dim", EXPRESSION),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
fn n_inputs(&self) -> usize {
|
||||
// Q, K_pool, V_pool, flat_gather_idx, mask (egglog IList).
|
||||
// extract() appends qo_indptr + kv_indptr → 7 actual inputs at runtime.
|
||||
5
|
||||
}
|
||||
|
||||
fn rewrites(&self) -> Vec<Rule> {
|
||||
vec![Rule::raw(include_str!["flashinfer_attention.egg"])]
|
||||
}
|
||||
|
||||
fn extract<'a>(
|
||||
&'a self,
|
||||
egraph: &'a luminal::egglog_utils::SerializedEGraph,
|
||||
kind_children: &[&'a ENodeId],
|
||||
input_enodes: Vec<&'a ENodeId>,
|
||||
_list_cache: &mut FxHashMap<&'a ENodeId, Vec<Expression>>,
|
||||
expr_cache: &mut FxHashMap<&'a ENodeId, Expression>,
|
||||
) -> (LLIROp, Vec<&'a ENodeId>) {
|
||||
let num_qo_heads = extract_expr(egraph, kind_children[0], expr_cache)
|
||||
.unwrap()
|
||||
.exec(&FxHashMap::default())
|
||||
.unwrap();
|
||||
let num_kv_heads = extract_expr(egraph, kind_children[1], expr_cache)
|
||||
.unwrap()
|
||||
.exec(&FxHashMap::default())
|
||||
.unwrap();
|
||||
let head_dim = extract_expr(egraph, kind_children[2], expr_cache)
|
||||
.unwrap()
|
||||
.exec(&FxHashMap::default())
|
||||
.unwrap();
|
||||
let page_size = extract_expr(egraph, kind_children[3], expr_cache)
|
||||
.unwrap()
|
||||
.exec(&FxHashMap::default())
|
||||
.unwrap();
|
||||
let batch_dim = extract_expr(egraph, kind_children[4], expr_cache).unwrap();
|
||||
|
||||
let extracted = Self {
|
||||
num_qo_heads,
|
||||
num_kv_heads,
|
||||
head_dim,
|
||||
page_size,
|
||||
batch_dim,
|
||||
plan_info: Mutex::new(Vec::new()),
|
||||
};
|
||||
|
||||
// Trigger JIT compilation (or .so cache hit) at extract time, not at
|
||||
// first execute. Pays the ~30s cold-cache nvcc cost during compile
|
||||
// rather than during the GA profiling loop, where it would dominate
|
||||
// the candidate's measured runtime and make the GA reject FlashInfer.
|
||||
let _ = jit::ensure_compiled(head_dim);
|
||||
|
||||
// Walk the mask e-graph chain to recover qo_indptr / kv_indptr Input nodes.
|
||||
// input_enodes: [Q, K_cache, V_cache, gather_idx, mask]
|
||||
let mask_node = input_enodes[4];
|
||||
let indptrs = find_indptrs::find_indptr_inputs(egraph, mask_node);
|
||||
|
||||
// Build final inputs: [Q, K_cache, V_cache, gather_idx, mask, qo_indptr, kv_indptr]
|
||||
let mut final_inputs = input_enodes;
|
||||
final_inputs.push(indptrs.qo_indptr);
|
||||
final_inputs.push(indptrs.kv_indptr);
|
||||
|
||||
let op = LLIROp::new::<dyn HostOp>(Box::new(extracted) as Box<dyn HostOp>);
|
||||
(op, final_inputs)
|
||||
}
|
||||
|
||||
fn cleanup(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
impl HostOp for FlashInferAttention {
|
||||
fn execute(
|
||||
&self,
|
||||
stream: &Arc<CudaStream>,
|
||||
self_node: NodeIndex,
|
||||
inputs: &[NodeIndex],
|
||||
buffers: &FxHashMap<NodeIndex, DeviceBuffer>,
|
||||
dyn_map: &FxHashMap<char, usize>,
|
||||
) -> anyhow::Result<()> {
|
||||
let lib = jit::ensure_compiled(self.head_dim);
|
||||
|
||||
let total_q_tokens = self
|
||||
.batch_dim
|
||||
.exec(dyn_map)
|
||||
.ok_or_else(|| anyhow::anyhow!("FlashInferAttention batch_dim is unresolved"))?;
|
||||
let c = *dyn_map
|
||||
.get(&'c')
|
||||
.ok_or_else(|| anyhow::anyhow!("FlashInferAttention requires dynamic dim 'c'"))?;
|
||||
let r = *dyn_map
|
||||
.get(&'r')
|
||||
.ok_or_else(|| anyhow::anyhow!("FlashInferAttention requires dynamic dim 'r'"))?;
|
||||
|
||||
if inputs.len() < 7 {
|
||||
anyhow::bail!(
|
||||
"FlashInferAttention expects 7 inputs (Q, K, V, flat_idx, mask, qo_indptr, kv_indptr), got {}",
|
||||
inputs.len()
|
||||
);
|
||||
}
|
||||
|
||||
let get_buf = |name: &str, node: NodeIndex| -> anyhow::Result<DeviceBuffer> {
|
||||
buffers.get(&node).copied().ok_or_else(|| {
|
||||
anyhow::anyhow!("FlashInferAttention missing {name} buffer for {node:?}")
|
||||
})
|
||||
};
|
||||
|
||||
let q_buf = get_buf("Q", inputs[0])?;
|
||||
let k_buf = get_buf("K_cache", inputs[1])?;
|
||||
let v_buf = get_buf("V_cache", inputs[2])?;
|
||||
let flat_idx_buf = get_buf("flat_gather_idx", inputs[3])?;
|
||||
// inputs[4] = mask (unused by FlashInfer — indptrs replace it)
|
||||
let kv_indptr_buf = get_buf("kv_indptr", inputs[6])?;
|
||||
let out_buf = get_buf("output", self_node)?;
|
||||
|
||||
// Derive batch_size (num sequences) from r = indptr length.
|
||||
let batch_size = r.saturating_sub(1);
|
||||
|
||||
let _span = span!(
|
||||
Level::TRACE,
|
||||
"FlashInferAttention",
|
||||
total_q_tokens,
|
||||
batch_size,
|
||||
self.num_qo_heads,
|
||||
self.num_kv_heads,
|
||||
self.head_dim,
|
||||
)
|
||||
.entered();
|
||||
|
||||
let kv_dim = self.num_kv_heads * self.head_dim;
|
||||
let cu_stream = stream.cu_stream() as *mut std::ffi::c_void;
|
||||
|
||||
// Extract slot indices (one per context page) from the flat gather index.
|
||||
let indices_buf = unsafe { stream.alloc::<u8>(c.max(1) * std::mem::size_of::<i32>())? };
|
||||
let (indices_ptr, _idx_guard) = indices_buf.device_ptr(stream);
|
||||
|
||||
if c > 0 {
|
||||
unsafe {
|
||||
(lib.extract_slot_indices)(
|
||||
flat_idx_buf.ptr() as *const i32,
|
||||
indices_ptr as *mut i32,
|
||||
c as i32,
|
||||
kv_dim as i32,
|
||||
cu_stream,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Read kv_indptr to host for the plan phase.
|
||||
let kv_indptr_bytes = r * 4;
|
||||
let mut kv_indptr_host_bytes = vec![0u8; kv_indptr_bytes];
|
||||
unsafe {
|
||||
result::memcpy_dtoh_async(
|
||||
&mut kv_indptr_host_bytes,
|
||||
kv_indptr_buf.ptr(),
|
||||
stream.cu_stream(),
|
||||
)?;
|
||||
}
|
||||
stream.synchronize()?;
|
||||
let kv_indptr_host: Vec<i32> = unsafe {
|
||||
let mut v = std::mem::ManuallyDrop::new(kv_indptr_host_bytes);
|
||||
Vec::from_raw_parts(v.as_mut_ptr() as *mut i32, r, r)
|
||||
};
|
||||
|
||||
// kv_last_page_len = [1; batch_size] when page_size=1.
|
||||
let last_page_host: Vec<i32> = vec![1; batch_size];
|
||||
let last_page_dev: CudaSlice<u8> = if batch_size > 0 {
|
||||
stream.clone_htod(unsafe {
|
||||
std::slice::from_raw_parts(
|
||||
last_page_host.as_ptr() as *const u8,
|
||||
last_page_host.len() * std::mem::size_of::<i32>(),
|
||||
)
|
||||
})?
|
||||
} else {
|
||||
unsafe { stream.alloc::<u8>(1)? }
|
||||
};
|
||||
let (last_page_ptr, _lp_guard) = last_page_dev.device_ptr(stream);
|
||||
|
||||
// Global shared workspaces (allocated once across all op instances to
|
||||
// amortize the ~4ms first-allocation cost during GA profiling).
|
||||
static FLOAT_WORKSPACE: OnceLock<CudaSlice<u8>> = OnceLock::new();
|
||||
static INT_WORKSPACE: OnceLock<CudaSlice<u8>> = OnceLock::new();
|
||||
let float_ws = FLOAT_WORKSPACE
|
||||
.get_or_init(|| unsafe { stream.alloc::<u8>(FLOAT_WORKSPACE_SIZE).unwrap() });
|
||||
let int_ws = INT_WORKSPACE
|
||||
.get_or_init(|| unsafe { stream.alloc::<u8>(INT_WORKSPACE_SIZE).unwrap() });
|
||||
let page_locked_ws = PAGE_LOCKED_WORKSPACE.get_or_init(|| unsafe {
|
||||
let mut ptr: *mut std::ffi::c_void = std::ptr::null_mut();
|
||||
let status = libc::posix_memalign(&mut ptr, 4096, INT_WORKSPACE_SIZE);
|
||||
assert_eq!(status, 0, "Failed to allocate page-locked workspace");
|
||||
let cuda_status = cuda_pin_memory(ptr, INT_WORKSPACE_SIZE);
|
||||
assert_eq!(cuda_status, 0, "Failed to pin memory");
|
||||
PageLockedPtr(ptr as *mut u8)
|
||||
});
|
||||
|
||||
let (float_ws_ptr, _fws_guard) = float_ws.device_ptr(stream);
|
||||
let (int_ws_ptr, _iws_guard) = int_ws.device_ptr(stream);
|
||||
|
||||
// FlashInfer decode writes (total_q_tokens, heads, dim);
|
||||
// luminal expects (heads, total_q_tokens, dim) — transpose at the end.
|
||||
let output_elems = total_q_tokens * self.num_qo_heads * self.head_dim;
|
||||
let temp_out_buf =
|
||||
unsafe { stream.alloc::<u8>(output_elems * std::mem::size_of::<f32>())? };
|
||||
let (temp_out_ptr, _tmp_guard) = temp_out_buf.device_ptr(stream);
|
||||
|
||||
// PrefillPlanInfo has 15 entries, DecodePlanInfo fewer — 16 is enough.
|
||||
let mut plan_info_buf = [0i64; 16];
|
||||
let mut plan_info_len: i32 = 0;
|
||||
|
||||
// ── BatchDecode path ──
|
||||
// Prefill kernels require fp16/bf16 tensor-core MMA; the C API returns -1
|
||||
// when called from the fp32 pipeline. We only use decode here.
|
||||
let plan_ret = unsafe {
|
||||
(lib.plan)(
|
||||
float_ws_ptr as *mut std::ffi::c_void,
|
||||
FLOAT_WORKSPACE_SIZE,
|
||||
int_ws_ptr as *mut std::ffi::c_void,
|
||||
INT_WORKSPACE_SIZE,
|
||||
page_locked_ws.0 as *mut std::ffi::c_void,
|
||||
kv_indptr_host.as_ptr() as *mut i32,
|
||||
batch_size as i32,
|
||||
self.num_qo_heads as i32,
|
||||
self.num_kv_heads as i32,
|
||||
self.page_size as i32,
|
||||
self.head_dim as i32,
|
||||
cu_stream,
|
||||
plan_info_buf.as_mut_ptr(),
|
||||
&mut plan_info_len,
|
||||
)
|
||||
};
|
||||
if plan_ret != 0 {
|
||||
return Err(anyhow::anyhow!(
|
||||
"FlashInfer decode plan failed with error code {plan_ret}"
|
||||
));
|
||||
}
|
||||
|
||||
let mut plan_info = self.plan_info.lock().unwrap();
|
||||
plan_info.clear();
|
||||
plan_info.extend_from_slice(&plan_info_buf[..plan_info_len as usize]);
|
||||
|
||||
let run_ret = unsafe {
|
||||
(lib.run)(
|
||||
float_ws_ptr as *mut std::ffi::c_void,
|
||||
FLOAT_WORKSPACE_SIZE,
|
||||
int_ws_ptr as *mut std::ffi::c_void,
|
||||
plan_info.as_mut_ptr(),
|
||||
plan_info.len() as i32,
|
||||
q_buf.ptr() as *mut f32,
|
||||
k_buf.ptr() as *mut f32,
|
||||
v_buf.ptr() as *mut f32,
|
||||
kv_indptr_buf.ptr() as *mut i32,
|
||||
indices_ptr as *mut i32,
|
||||
last_page_ptr as *mut i32,
|
||||
temp_out_ptr as *mut f32,
|
||||
batch_size as i32,
|
||||
self.num_qo_heads as i32,
|
||||
self.num_kv_heads as i32,
|
||||
self.page_size as i32,
|
||||
self.head_dim as i32,
|
||||
cu_stream,
|
||||
)
|
||||
};
|
||||
drop(plan_info);
|
||||
|
||||
if run_ret != 0 {
|
||||
return Err(anyhow::anyhow!(
|
||||
"FlashInfer decode run failed with error code {run_ret}"
|
||||
));
|
||||
}
|
||||
|
||||
// Transpose (total_q_tokens, heads, dim) → (heads, total_q_tokens, dim)
|
||||
unsafe {
|
||||
(lib.transpose_output)(
|
||||
temp_out_ptr as *const f32,
|
||||
out_buf.ptr() as *mut f32,
|
||||
total_q_tokens as i32,
|
||||
self.num_qo_heads as i32,
|
||||
self.head_dim as i32,
|
||||
cu_stream,
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn output_size(&self) -> Expression {
|
||||
self.batch_dim * self.num_qo_heads * self.head_dim
|
||||
}
|
||||
|
||||
fn output_bytes(&self) -> Expression {
|
||||
self.output_size() * 4
|
||||
}
|
||||
|
||||
fn stats_name(&self) -> Option<&'static str> {
|
||||
Some("FlashInferAttention")
|
||||
}
|
||||
}
|
||||
|
||||
/// Pin host memory for CUDA async memcpy.
|
||||
///
|
||||
/// `cudaHostRegister` lives in libcudart, which cudarc doesn't link to our
|
||||
/// binary. Resolve it via `dlopen`/`dlsym` so we don't need a build script or
|
||||
/// a `#[link]` directive — keeping the crate buildable without any nvcc-side
|
||||
/// dependencies.
|
||||
unsafe fn cuda_pin_memory(ptr: *mut std::ffi::c_void, size: usize) -> i32 {
|
||||
type HostRegisterFn = unsafe extern "C" fn(*mut std::ffi::c_void, usize, u32) -> i32;
|
||||
static FN: OnceLock<usize> = OnceLock::new();
|
||||
|
||||
let raw = *FN.get_or_init(|| unsafe {
|
||||
let lib = [
|
||||
"libcudart.so",
|
||||
"libcudart.so.13",
|
||||
"libcudart.so.12",
|
||||
"libcudart.so.11",
|
||||
]
|
||||
.iter()
|
||||
.find_map(|n| libloading::Library::new(*n).ok())
|
||||
.expect("FlashInfer: could not dlopen libcudart for cudaHostRegister");
|
||||
let sym: libloading::Symbol<HostRegisterFn> = lib
|
||||
.get(b"cudaHostRegister\0")
|
||||
.expect("FlashInfer: libcudart missing cudaHostRegister symbol");
|
||||
let ptr = *sym as *const () as usize;
|
||||
// Keep libcudart resident for the process lifetime so the function
|
||||
// pointer remains valid.
|
||||
std::mem::forget(lib);
|
||||
ptr
|
||||
});
|
||||
let f: HostRegisterFn = unsafe { std::mem::transmute(raw) };
|
||||
// cudaHostRegisterDefault = 0
|
||||
unsafe { f(ptr, size, 0) }
|
||||
}
|
||||
357
crates/luminal_cuda_lite/src/host/flashinfer/wrapper.cu
Normal file
357
crates/luminal_cuda_lite/src/host/flashinfer/wrapper.cu
Normal file
@@ -0,0 +1,357 @@
|
||||
// FlashInfer batch decode + prefill wrapper for luminal_cuda.
|
||||
// JIT-compiled at runtime with -DLUMINAL_HEAD_DIM=N.
|
||||
//
|
||||
// Decode: instantiated for f32 (scalar vectorized dot products, no tensor cores).
|
||||
// Prefill: instantiated for f16 (requires tensor core MMA + ldmatrix).
|
||||
// The C API accepts fp32 buffers; cast kernels convert fp32↔fp16 at the boundary.
|
||||
//
|
||||
// NHD layout. GQA group_size and page_size are runtime parameters.
|
||||
|
||||
#ifndef LUMINAL_HEAD_DIM
|
||||
#error "LUMINAL_HEAD_DIM must be defined (e.g. -DLUMINAL_HEAD_DIM=128)"
|
||||
#endif
|
||||
|
||||
// Include utils.cuh first to get the original DISPATCH_HEAD_DIM, then override it
|
||||
// to only instantiate our specific HEAD_DIM. This avoids a compile error in
|
||||
// cascade.cuh where HEAD_DIM=512 + f32 triggers vec_size=16, vec_bits=512
|
||||
// which exceeds cp_async's 256-bit limit.
|
||||
#include <flashinfer/utils.cuh>
|
||||
#undef DISPATCH_HEAD_DIM
|
||||
#define DISPATCH_HEAD_DIM(head_dim, HEAD_DIM, ...) \
|
||||
{ \
|
||||
constexpr size_t HEAD_DIM = LUMINAL_HEAD_DIM; \
|
||||
__VA_ARGS__ \
|
||||
}
|
||||
|
||||
#include <flashinfer/attention/scheduler.cuh>
|
||||
#include <flashinfer/attention/decode.cuh>
|
||||
#include <flashinfer/attention/default_decode_params.cuh>
|
||||
#include <flashinfer/attention/prefill.cuh>
|
||||
#include <flashinfer/attention/default_prefill_params.cuh>
|
||||
#include <flashinfer/attention/mask.cuh>
|
||||
#include <flashinfer/attention/variants.cuh>
|
||||
#include <flashinfer/page.cuh>
|
||||
#include <flashinfer/pos_enc.cuh>
|
||||
|
||||
#include "wrapper.h"
|
||||
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
#include <cuda_fp16.h>
|
||||
|
||||
using namespace flashinfer;
|
||||
|
||||
// ── Decode types (f32) ──
|
||||
using DTypeQ = float;
|
||||
using DTypeKV = float;
|
||||
using DTypeO = float;
|
||||
using IdType = int32_t;
|
||||
|
||||
// ── Prefill types (f16 compute, fp32 external interface) ──
|
||||
using PrefillDTypeQ = half;
|
||||
using PrefillDTypeKV = half;
|
||||
using PrefillDTypeO = half;
|
||||
|
||||
constexpr uint32_t HEAD_DIM = LUMINAL_HEAD_DIM;
|
||||
constexpr PosEncodingMode POS_ENCODING_MODE = PosEncodingMode::kNone;
|
||||
|
||||
// Attention variants
|
||||
using Variant = DefaultAttention</*use_custom_mask=*/false,
|
||||
/*use_sliding_window=*/false,
|
||||
/*use_logits_soft_cap=*/false,
|
||||
/*use_alibi=*/false>;
|
||||
|
||||
using CausalVariant = DefaultAttention</*use_custom_mask=*/false,
|
||||
/*use_sliding_window=*/false,
|
||||
/*use_logits_soft_cap=*/false,
|
||||
/*use_alibi=*/false>;
|
||||
|
||||
// Decode params (f32)
|
||||
using DecodeParams = BatchDecodeParams<DTypeQ, DTypeKV, DTypeO, IdType>;
|
||||
|
||||
// Prefill params (f16)
|
||||
using PrefillParams = BatchPrefillPagedParams<PrefillDTypeQ, PrefillDTypeKV, PrefillDTypeO, IdType>;
|
||||
|
||||
// Forward declarations
|
||||
namespace flashinfer {
|
||||
template <uint32_t HEAD_DIM, PosEncodingMode POS_ENCODING_MODE, typename AttentionVariant,
|
||||
typename Params>
|
||||
cudaError_t BatchDecodeWithPagedKVCacheDispatched(Params params, typename Params::DTypeO* tmp_v,
|
||||
float* tmp_s, bool enable_pdl,
|
||||
cudaStream_t stream);
|
||||
|
||||
template <uint32_t CTA_TILE_Q, uint32_t HEAD_DIM_QK, uint32_t HEAD_DIM_VO,
|
||||
PosEncodingMode POS_ENCODING_MODE, bool USE_FP16_QK_REDUCTION,
|
||||
MaskMode MASK_MODE, typename AttentionVariant, typename Params>
|
||||
cudaError_t BatchPrefillWithPagedKVCacheDispatched(Params params, typename Params::DTypeO* tmp_v,
|
||||
float* tmp_s, bool enable_pdl,
|
||||
cudaStream_t stream);
|
||||
}
|
||||
|
||||
// Explicit instantiation: decode kernel (f32)
|
||||
template cudaError_t flashinfer::BatchDecodeWithPagedKVCacheDispatched<
|
||||
HEAD_DIM, POS_ENCODING_MODE, Variant, DecodeParams>(
|
||||
DecodeParams params, DTypeO* tmp_v, float* tmp_s, bool enable_pdl, cudaStream_t stream);
|
||||
|
||||
// Explicit instantiation: prefill kernels (f16, causal mask, CTA_TILE_Q=16/64/128)
|
||||
template cudaError_t flashinfer::BatchPrefillWithPagedKVCacheDispatched<
|
||||
16, HEAD_DIM, HEAD_DIM, POS_ENCODING_MODE, false, MaskMode::kCausal, CausalVariant, PrefillParams>(
|
||||
PrefillParams params, PrefillDTypeO* tmp_v, float* tmp_s, bool enable_pdl, cudaStream_t stream);
|
||||
|
||||
template cudaError_t flashinfer::BatchPrefillWithPagedKVCacheDispatched<
|
||||
64, HEAD_DIM, HEAD_DIM, POS_ENCODING_MODE, false, MaskMode::kCausal, CausalVariant, PrefillParams>(
|
||||
PrefillParams params, PrefillDTypeO* tmp_v, float* tmp_s, bool enable_pdl, cudaStream_t stream);
|
||||
|
||||
template cudaError_t flashinfer::BatchPrefillWithPagedKVCacheDispatched<
|
||||
128, HEAD_DIM, HEAD_DIM, POS_ENCODING_MODE, false, MaskMode::kCausal, CausalVariant, PrefillParams>(
|
||||
PrefillParams params, PrefillDTypeO* tmp_v, float* tmp_s, bool enable_pdl, cudaStream_t stream);
|
||||
|
||||
// ── fp32 ↔ fp16 cast kernels ──
|
||||
|
||||
__global__ void cast_f32_to_f16_kernel(const float* src, half* dst, size_t n) {
|
||||
size_t i = (size_t)blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (i < n) dst[i] = __float2half(src[i]);
|
||||
}
|
||||
|
||||
__global__ void cast_f16_to_f32_kernel(const half* src, float* dst, size_t n) {
|
||||
size_t i = (size_t)blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (i < n) dst[i] = __half2float(src[i]);
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
|
||||
int flashinfer_batch_decode_plan(
|
||||
void* float_workspace, size_t float_ws_size,
|
||||
void* int_workspace, size_t int_ws_size,
|
||||
void* page_locked_int_workspace,
|
||||
int32_t* indptr_h, int batch_size,
|
||||
int num_qo_heads, int num_kv_heads, int page_size, int head_dim,
|
||||
cudaStream_t stream,
|
||||
int64_t* plan_info_out, int* plan_info_len_out)
|
||||
{
|
||||
(void)head_dim; // fixed at compile time
|
||||
|
||||
DecodePlanInfo plan_info;
|
||||
uint32_t group_size = num_qo_heads / num_kv_heads;
|
||||
|
||||
// We need to dispatch on GROUP_SIZE to get the right work estimation function
|
||||
cudaError_t status = cudaSuccess;
|
||||
|
||||
// Use a lambda to dispatch on group size
|
||||
auto do_plan = [&]<uint32_t GROUP_SIZE>() -> cudaError_t {
|
||||
auto work_estimation_func =
|
||||
BatchDecodeWithPagedKVCacheWorkEstimationDispatched<
|
||||
GROUP_SIZE, HEAD_DIM, POS_ENCODING_MODE, Variant, DecodeParams>;
|
||||
return DecodePlan<HEAD_DIM, POS_ENCODING_MODE, Variant, DecodeParams>(
|
||||
float_workspace, float_ws_size,
|
||||
int_workspace, page_locked_int_workspace,
|
||||
int_ws_size, plan_info, indptr_h,
|
||||
(uint32_t)batch_size, (uint32_t)num_qo_heads,
|
||||
(uint32_t)page_size, /*enable_cuda_graph=*/false,
|
||||
stream, work_estimation_func);
|
||||
};
|
||||
|
||||
switch (group_size) {
|
||||
case 1: status = do_plan.operator()<1>(); break;
|
||||
case 2: status = do_plan.operator()<2>(); break;
|
||||
case 4: status = do_plan.operator()<4>(); break;
|
||||
case 8: status = do_plan.operator()<8>(); break;
|
||||
default: return -1; // unsupported group size
|
||||
}
|
||||
|
||||
if (status != cudaSuccess) return (int)status;
|
||||
|
||||
auto vec = plan_info.ToVector();
|
||||
*plan_info_len_out = (int)vec.size();
|
||||
std::memcpy(plan_info_out, vec.data(), vec.size() * sizeof(int64_t));
|
||||
return 0;
|
||||
}
|
||||
|
||||
int flashinfer_batch_decode_run(
|
||||
void* float_workspace, size_t float_ws_size,
|
||||
void* int_workspace,
|
||||
int64_t* plan_info_vec, int plan_info_len,
|
||||
float* q,
|
||||
float* k_cache,
|
||||
float* v_cache,
|
||||
int32_t* kv_indptr,
|
||||
int32_t* kv_indices,
|
||||
int32_t* kv_last_page_len,
|
||||
float* output,
|
||||
int batch_size,
|
||||
int num_qo_heads, int num_kv_heads, int page_size, int head_dim,
|
||||
cudaStream_t stream)
|
||||
{
|
||||
(void)head_dim; // fixed at compile time
|
||||
|
||||
DecodePlanInfo plan_info;
|
||||
plan_info.FromVector(std::vector<int64_t>(plan_info_vec, plan_info_vec + plan_info_len));
|
||||
|
||||
// Construct paged_kv_t with NHD layout
|
||||
paged_kv_t<DTypeKV, IdType> paged_kv(
|
||||
(uint32_t)num_kv_heads,
|
||||
(uint32_t)page_size,
|
||||
HEAD_DIM,
|
||||
(uint32_t)batch_size,
|
||||
QKVLayout::kNHD,
|
||||
k_cache,
|
||||
v_cache,
|
||||
kv_indices,
|
||||
kv_indptr,
|
||||
kv_last_page_len);
|
||||
|
||||
DecodeParams params;
|
||||
params.q = q;
|
||||
params.q_rope_offset = nullptr;
|
||||
params.paged_kv = paged_kv;
|
||||
params.o = output;
|
||||
params.lse = nullptr;
|
||||
params.maybe_alibi_slopes = nullptr;
|
||||
params.padded_batch_size = plan_info.padded_batch_size;
|
||||
params.num_qo_heads = (uint32_t)num_qo_heads;
|
||||
// Q buffer is (batch, num_qo_heads * head_dim) flat — the graph's split_dims + transpose
|
||||
// are stride tricks, no data movement. So the actual memory layout is (batch, heads, dim).
|
||||
params.q_stride_n = num_qo_heads * HEAD_DIM;
|
||||
params.q_stride_h = HEAD_DIM;
|
||||
params.window_left = -1; // no sliding window
|
||||
params.logits_soft_cap = 0.0f;
|
||||
params.sm_scale = 1.0f / sqrtf((float)HEAD_DIM);
|
||||
params.rope_rcp_scale = 1.0f;
|
||||
params.rope_rcp_theta = 1.0f;
|
||||
|
||||
// Set plan info pointers
|
||||
params.request_indices =
|
||||
GetPtrFromBaseOffset<IdType>(int_workspace, plan_info.request_indices_offset);
|
||||
params.kv_tile_indices =
|
||||
GetPtrFromBaseOffset<IdType>(int_workspace, plan_info.kv_tile_indices_offset);
|
||||
params.o_indptr =
|
||||
GetPtrFromBaseOffset<IdType>(int_workspace, plan_info.o_indptr_offset);
|
||||
params.kv_chunk_size_ptr =
|
||||
GetPtrFromBaseOffset<IdType>(int_workspace, plan_info.kv_chunk_size_ptr_offset);
|
||||
params.block_valid_mask = nullptr;
|
||||
params.partition_kv = false;
|
||||
|
||||
DTypeO* tmp_v = nullptr;
|
||||
float* tmp_s = nullptr;
|
||||
|
||||
if (plan_info.split_kv) {
|
||||
tmp_v = GetPtrFromBaseOffset<DTypeO>(float_workspace, plan_info.v_offset);
|
||||
tmp_s = GetPtrFromBaseOffset<float>(float_workspace, plan_info.s_offset);
|
||||
if (plan_info.enable_cuda_graph) {
|
||||
params.block_valid_mask =
|
||||
GetPtrFromBaseOffset<bool>(int_workspace, plan_info.block_valid_mask_offset);
|
||||
}
|
||||
}
|
||||
|
||||
cudaError_t status =
|
||||
flashinfer::BatchDecodeWithPagedKVCacheDispatched<HEAD_DIM, POS_ENCODING_MODE, Variant>(
|
||||
params, tmp_v, tmp_s, /*enable_pdl=*/false, stream);
|
||||
|
||||
return (int)status;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════
|
||||
// BatchPrefill (fp16/bf16 only — tensor core MMA requires 16-bit inputs)
|
||||
// ═══════════════════════════════════════════════════════════
|
||||
//
|
||||
// The prefill kernel templates are instantiated above for fp16. These C API
|
||||
// functions accept fp32 pointers (matching the current luminal pipeline) but
|
||||
// return -1 to indicate that fp32 prefill is not supported. When native fp16
|
||||
// support is added, these will accept fp16 pointers and call through to the
|
||||
// instantiated templates.
|
||||
|
||||
int flashinfer_batch_prefill_plan(
|
||||
void*, size_t, void*, size_t, void*,
|
||||
int32_t*, int32_t*, int, int,
|
||||
int, int, int, int, cudaStream_t,
|
||||
int64_t*, int*)
|
||||
{
|
||||
return -1; // fp32 not supported — requires fp16/bf16
|
||||
}
|
||||
|
||||
int flashinfer_batch_prefill_run(
|
||||
void*, size_t, void*,
|
||||
int64_t*, int,
|
||||
float*, float*, float*,
|
||||
int32_t*, int32_t*, int32_t*, int32_t*,
|
||||
float*, int, int, int, int, int, int, cudaStream_t)
|
||||
{
|
||||
return -1; // fp32 not supported — requires fp16/bf16
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
|
||||
// ── Slot index extraction kernel (outside extern "C" for __global__) ──
|
||||
|
||||
__global__ void extract_slot_indices_kernel(
|
||||
const int32_t* flat_idx, int32_t* out, int c, int kv_dim) {
|
||||
int i = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (i < c) out[i] = flat_idx[i * kv_dim] / kv_dim;
|
||||
}
|
||||
|
||||
extern "C" void flashinfer_extract_slot_indices(
|
||||
const int32_t* flat_idx, int32_t* out, int c, int kv_dim,
|
||||
cudaStream_t stream) {
|
||||
if (c == 0) return;
|
||||
int threads = 256;
|
||||
int blocks = (c + threads - 1) / threads;
|
||||
extract_slot_indices_kernel<<<blocks, threads, 0, stream>>>(
|
||||
flat_idx, out, c, kv_dim);
|
||||
}
|
||||
|
||||
// ── Derive CSR indptr from attention mask ──
|
||||
// Mask is (s, c) f32. Entries > -1e9 are "valid" (0.0), rest are -inf.
|
||||
// Per-row count of valid entries = context length for that sequence.
|
||||
// Output: indptr[0..=s] with indptr[0]=0 and indptr[i+1] = indptr[i] + ctx_len[i].
|
||||
// Single thread is fine since s is tiny (batch_size during decode, typically 1-8).
|
||||
|
||||
__global__ void derive_indptr_kernel(
|
||||
const float* mask, int32_t* indptr, int s, int c) {
|
||||
if (threadIdx.x != 0 || blockIdx.x != 0) return;
|
||||
indptr[0] = 0;
|
||||
for (int i = 0; i < s; i++) {
|
||||
int count = 0;
|
||||
for (int j = 0; j < c; j++) {
|
||||
if (mask[i * c + j] > -1e9f) count++;
|
||||
}
|
||||
indptr[i + 1] = indptr[i] + count;
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" void flashinfer_derive_indptr_from_mask(
|
||||
const float* mask, int32_t* indptr, int s, int c,
|
||||
cudaStream_t stream) {
|
||||
if (s == 0) return;
|
||||
derive_indptr_kernel<<<1, 1, 0, stream>>>(mask, indptr, s, c);
|
||||
}
|
||||
|
||||
// ── Output transpose: (batch, heads, dim) → (heads, batch, dim) ──
|
||||
// FlashInfer writes output as (batch, heads, dim) but Luminal expects (heads, batch, dim).
|
||||
// For batch=1 these are identical; for batch>1 we need an explicit transpose.
|
||||
|
||||
__global__ void transpose_bhd_to_hbd_kernel(
|
||||
const float* src, float* dst, int batch, int heads, int dim) {
|
||||
int idx = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
int total = batch * heads * dim;
|
||||
if (idx >= total) return;
|
||||
|
||||
// Decompose linear index into (b, h, d) for src layout
|
||||
int d = idx % dim;
|
||||
int h = (idx / dim) % heads;
|
||||
int b = idx / (heads * dim);
|
||||
|
||||
// Write to (h, b, d) layout in dst
|
||||
dst[h * batch * dim + b * dim + d] = src[idx];
|
||||
}
|
||||
|
||||
extern "C" void flashinfer_transpose_output(
|
||||
const float* src, float* dst,
|
||||
int batch, int heads, int dim,
|
||||
cudaStream_t stream) {
|
||||
int total = batch * heads * dim;
|
||||
if (total == 0) return;
|
||||
int threads = 256;
|
||||
int blocks = (total + threads - 1) / threads;
|
||||
transpose_bhd_to_hbd_kernel<<<blocks, threads, 0, stream>>>(
|
||||
src, dst, batch, heads, dim);
|
||||
}
|
||||
93
crates/luminal_cuda_lite/src/host/flashinfer/wrapper.h
Normal file
93
crates/luminal_cuda_lite/src/host/flashinfer/wrapper.h
Normal file
@@ -0,0 +1,93 @@
|
||||
#pragma once
|
||||
|
||||
#include <cuda_runtime.h>
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
// Plan phase: CPU-side scheduling. Must call before each new batch config.
|
||||
// Returns 0 on success, non-zero on failure.
|
||||
int flashinfer_batch_decode_plan(
|
||||
void* float_workspace, size_t float_ws_size,
|
||||
void* int_workspace, size_t int_ws_size,
|
||||
void* page_locked_int_workspace,
|
||||
int32_t* indptr_h, int batch_size,
|
||||
int num_qo_heads, int num_kv_heads, int page_size, int head_dim,
|
||||
cudaStream_t stream,
|
||||
int64_t* plan_info_out, int* plan_info_len_out);
|
||||
|
||||
// Run phase: GPU kernel launch.
|
||||
// Returns 0 on success, non-zero on failure.
|
||||
int flashinfer_batch_decode_run(
|
||||
void* float_workspace, size_t float_ws_size,
|
||||
void* int_workspace,
|
||||
int64_t* plan_info_vec, int plan_info_len,
|
||||
float* q, // [batch_size, num_qo_heads, head_dim]
|
||||
float* k_cache, // [num_pages, page_size, num_kv_heads, head_dim] (NHD)
|
||||
float* v_cache, // same layout
|
||||
int32_t* kv_indptr, // [batch_size + 1]
|
||||
int32_t* kv_indices, // [total_pages]
|
||||
int32_t* kv_last_page_len, // [batch_size]
|
||||
float* output, // [batch_size, num_qo_heads, head_dim]
|
||||
int batch_size,
|
||||
int num_qo_heads, int num_kv_heads, int page_size, int head_dim,
|
||||
cudaStream_t stream);
|
||||
|
||||
// Extract slot indices from a flat gather index tensor.
|
||||
// flat_idx shape: (c, kv_dim) i32, out shape: (c,) i32.
|
||||
// out[i] = flat_idx[i * kv_dim] / kv_dim
|
||||
void flashinfer_extract_slot_indices(
|
||||
const int32_t* flat_idx, int32_t* out, int c, int kv_dim,
|
||||
cudaStream_t stream);
|
||||
|
||||
// Derive CSR indptr from attention mask.
|
||||
// mask shape: (s, c) f32. Entries > -1e9 are valid.
|
||||
// indptr shape: (s + 1,) i32. indptr[0] = 0, indptr[i+1] = cumsum of valid counts.
|
||||
void flashinfer_derive_indptr_from_mask(
|
||||
const float* mask, int32_t* indptr, int s, int c,
|
||||
cudaStream_t stream);
|
||||
|
||||
// Transpose output from (batch, heads, dim) to (heads, batch, dim).
|
||||
void flashinfer_transpose_output(
|
||||
const float* src, float* dst,
|
||||
int batch, int heads, int dim,
|
||||
cudaStream_t stream);
|
||||
|
||||
// ── BatchPrefill with Paged KV Cache ──
|
||||
|
||||
// Plan phase for batch prefill.
|
||||
// Returns 0 on success, non-zero on failure.
|
||||
int flashinfer_batch_prefill_plan(
|
||||
void* float_workspace, size_t float_ws_size,
|
||||
void* int_workspace, size_t int_ws_size,
|
||||
void* page_locked_int_workspace,
|
||||
int32_t* qo_indptr_h, int32_t* kv_indptr_h,
|
||||
int total_num_rows, int batch_size,
|
||||
int num_qo_heads, int num_kv_heads, int page_size, int head_dim,
|
||||
cudaStream_t stream,
|
||||
int64_t* plan_info_out, int* plan_info_len_out);
|
||||
|
||||
// Run phase for batch prefill.
|
||||
// Returns 0 on success, non-zero on failure.
|
||||
int flashinfer_batch_prefill_run(
|
||||
void* float_workspace, size_t float_ws_size,
|
||||
void* int_workspace,
|
||||
int64_t* plan_info_vec, int plan_info_len,
|
||||
float* q, // [total_num_rows, num_qo_heads, head_dim]
|
||||
float* k_cache, // [num_pages, page_size, num_kv_heads, head_dim] (NHD)
|
||||
float* v_cache, // same layout
|
||||
int32_t* qo_indptr, // [batch_size + 1] on GPU
|
||||
int32_t* kv_indptr, // [batch_size + 1] on GPU
|
||||
int32_t* kv_indices, // [total_pages]
|
||||
int32_t* kv_last_page_len, // [batch_size]
|
||||
float* output, // [total_num_rows, num_qo_heads, head_dim]
|
||||
int total_num_rows, int batch_size,
|
||||
int num_qo_heads, int num_kv_heads, int page_size, int head_dim,
|
||||
cudaStream_t stream);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -1,17 +1,127 @@
|
||||
use std::{fmt::Debug, sync::Arc};
|
||||
|
||||
use crate::cudarc::driver::{CudaSlice, CudaStream};
|
||||
use crate::cudarc::driver::{CudaStream, DriverError, result};
|
||||
use luminal::{op::EgglogOp, prelude::*};
|
||||
mod cublas;
|
||||
mod cublaslt;
|
||||
pub mod flashinfer;
|
||||
pub mod moe;
|
||||
|
||||
pub type Ops = (
|
||||
// cublas::CuBlasSgemmV2,
|
||||
cublaslt::CuBlasLt,
|
||||
cublaslt::CuBlasLtScaled,
|
||||
moe::GLUMoE,
|
||||
flashinfer::FlashInferAttention,
|
||||
);
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) type CublasLtTypeTuple = (
|
||||
luminal::dtype::DType,
|
||||
luminal::dtype::DType,
|
||||
luminal::dtype::DType,
|
||||
luminal::dtype::DType,
|
||||
&'static str,
|
||||
luminal::dtype::DType,
|
||||
);
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn cublaslt_type_tuple(op: &dyn HostOp) -> Option<CublasLtTypeTuple> {
|
||||
op.as_any()
|
||||
.downcast_ref::<cublaslt::CuBlasLt>()
|
||||
.map(cublaslt::CuBlasLt::type_tuple)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) type CublasLtScaleValues = (f64, f64);
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn cublaslt_scale_values(op: &dyn HostOp) -> Option<CublasLtScaleValues> {
|
||||
op.as_any()
|
||||
.downcast_ref::<cublaslt::CuBlasLt>()
|
||||
.map(cublaslt::CuBlasLt::scale_values)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn cublaslt_epilogue(op: &dyn HostOp) -> Option<&'static str> {
|
||||
op.as_any()
|
||||
.downcast_ref::<cublaslt::CuBlasLt>()
|
||||
.map(cublaslt::CuBlasLt::epilogue)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) type CublasLtMatrixOrders = (&'static str, &'static str, &'static str, &'static str);
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn cublaslt_matrix_orders(op: &dyn HostOp) -> Option<CublasLtMatrixOrders> {
|
||||
op.as_any()
|
||||
.downcast_ref::<cublaslt::CuBlasLt>()
|
||||
.map(cublaslt::CuBlasLt::matrix_orders)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) type CublasLtTransposeOps = (&'static str, &'static str);
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn cublaslt_transpose_ops(op: &dyn HostOp) -> Option<CublasLtTransposeOps> {
|
||||
op.as_any()
|
||||
.downcast_ref::<cublaslt::CuBlasLt>()
|
||||
.map(cublaslt::CuBlasLt::transpose_ops)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn cublaslt_c_d_layouts_match(op: &dyn HostOp) -> Option<bool> {
|
||||
op.as_any()
|
||||
.downcast_ref::<cublaslt::CuBlasLt>()
|
||||
.map(cublaslt::CuBlasLt::c_d_layouts_match)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) type CublasLtTensorScaleInputs = (bool, bool);
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn cublaslt_tensor_scale_inputs(op: &dyn HostOp) -> Option<CublasLtTensorScaleInputs> {
|
||||
op.as_any()
|
||||
.downcast_ref::<cublaslt::CuBlasLt>()
|
||||
.map(cublaslt::CuBlasLt::tensor_scale_inputs)
|
||||
}
|
||||
|
||||
/// Non-owning device buffer handle used by host operations.
|
||||
///
|
||||
/// Runtime-owned intermediates may be a whole `CudaSlice`, a subregion inside
|
||||
/// the reusable arena, or an external pointer. Host ops only need the pointer
|
||||
/// and the logical byte length.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct DeviceBuffer {
|
||||
ptr: u64,
|
||||
len: usize,
|
||||
}
|
||||
|
||||
impl DeviceBuffer {
|
||||
pub fn new(ptr: u64, len: usize) -> Self {
|
||||
Self { ptr, len }
|
||||
}
|
||||
|
||||
pub fn ptr(self) -> u64 {
|
||||
self.ptr
|
||||
}
|
||||
|
||||
pub fn len(self) -> usize {
|
||||
self.len
|
||||
}
|
||||
|
||||
pub fn is_empty(self) -> bool {
|
||||
self.len == 0
|
||||
}
|
||||
|
||||
pub fn clone_dtoh(self, stream: &Arc<CudaStream>) -> Result<Vec<u8>, DriverError> {
|
||||
let mut host = vec![0u8; self.len];
|
||||
unsafe {
|
||||
result::memcpy_dtoh_async(&mut host, self.ptr, stream.cu_stream())?;
|
||||
}
|
||||
stream.synchronize()?;
|
||||
Ok(host)
|
||||
}
|
||||
}
|
||||
|
||||
/// Host operations that execute on the CPU but orchestrate GPU work.
|
||||
///
|
||||
/// This includes operations like cuBLAS calls and CUDA graph executions.
|
||||
@@ -29,7 +139,7 @@ pub trait HostOp: Debug + as_any::AsAny + EgglogOp {
|
||||
stream: &Arc<CudaStream>,
|
||||
self_node: NodeIndex,
|
||||
inputs: &[NodeIndex],
|
||||
buffers: &FxHashMap<NodeIndex, &CudaSlice<u8>>,
|
||||
buffers: &FxHashMap<NodeIndex, DeviceBuffer>,
|
||||
dyn_map: &FxHashMap<char, usize>,
|
||||
) -> anyhow::Result<()>;
|
||||
|
||||
@@ -48,6 +158,15 @@ pub trait HostOp: Debug + as_any::AsAny + EgglogOp {
|
||||
vec![]
|
||||
}
|
||||
|
||||
/// Returns relative lifetimes for extra buffer nodes within this host op.
|
||||
///
|
||||
/// The tuple is `(node, first_step, last_step)`, where steps are local to
|
||||
/// this host op's execution. Returning `None` tells the runtime to treat
|
||||
/// every extra buffer as live for the whole host op.
|
||||
fn extra_buffer_lifetimes(&self) -> Option<Vec<(NodeIndex, usize, usize)>> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Returns buffer size requirements for extra nodes (node -> size in elements).
|
||||
///
|
||||
/// Called during buffer allocation to ensure all required buffers exist.
|
||||
|
||||
@@ -195,6 +195,10 @@
|
||||
(= ?swiglu_state (MkGLUMoESwiGLUState ?gate_up_state))
|
||||
(= ?gate_up_state (MkGLUMoEGateUpState ?gu_io ?gu_matmul_k ?gu_within_range ?x ?topk_idx ?gate_up_w))
|
||||
|
||||
(= ?topk_row_offsets (Op (Iota ?topk_row_offsets_expr ?topk_row_offsets_range) (INil)))
|
||||
(= ?topk_flat_idx (Op (Add ?topk_flat_idx_shape ?topk_flat_idx_a_stride ?topk_flat_idx_b_stride ?topk_flat_idx_out_stride) (ICons ?topk_row_offsets (ICons ?topk_idx (INil)))))
|
||||
(= ?topk_vals (Op (Gather ?topk_vals_gather_idx_shape ?topk_vals_gather_idx_stride ?topk_vals_gather_data_shape ?topk_vals_gather_data_stride) (ICons ?topk_flat_idx (ICons ?routing_weights (INil)))))
|
||||
|
||||
(= ?weighted (Op (Mul ?weighted_shape ?weighted_a_stride ?weighted_b_stride ?weighted_out_stride) (ICons ?dn_matmul (ICons ?topk_vals (INil)))))
|
||||
(= ?output (Op (Sum ?output_shape ?output_k ?output_in_stride ?output_k_stride ?output_out_stride) (ICons ?weighted (INil))))
|
||||
)
|
||||
@@ -211,6 +215,37 @@
|
||||
:name "GLUMoE fused expert computation (swiglu)"
|
||||
)
|
||||
|
||||
; ===== Final fusion: mode 2 (SwiGLU with row-normalized top-k weights) =====
|
||||
(rule
|
||||
(
|
||||
(= ?down_state (glumoe_swiglu_down ?dn_matmul))
|
||||
(= ?down_state (MkGLUMoESwiGLUDownState ?dn_io ?dn_matmul_k ?dn_within_range ?swiglu_state ?topk_idx ?down_w))
|
||||
(= ?swiglu_state (MkGLUMoESwiGLUState ?gate_up_state))
|
||||
(= ?gate_up_state (MkGLUMoEGateUpState ?gu_io ?gu_matmul_k ?gu_within_range ?x ?topk_idx ?gate_up_w))
|
||||
|
||||
(= ?topk_row_offsets (Op (Iota ?topk_row_offsets_expr ?topk_row_offsets_range) (INil)))
|
||||
(= ?topk_flat_idx (Op (Add ?topk_flat_idx_shape ?topk_flat_idx_a_stride ?topk_flat_idx_b_stride ?topk_flat_idx_out_stride) (ICons ?topk_row_offsets (ICons ?topk_idx (INil)))))
|
||||
(= ?topk_vals (Op (Gather ?topk_vals_gather_idx_shape ?topk_vals_gather_idx_stride ?topk_vals_gather_data_shape ?topk_vals_gather_data_stride) (ICons ?topk_flat_idx (ICons ?routing_weights (INil)))))
|
||||
(= ?topk_norm (Op (Sum ?topk_norm_shape ?output_k ?topk_norm_in_stride ?topk_norm_k_stride ?topk_norm_out_stride) (ICons ?topk_vals (INil))))
|
||||
(= ?topk_norm_factor (Op (Recip ?topk_norm_recip_shape ?topk_norm_recip_in_stride ?topk_norm_recip_out_stride) (ICons ?topk_norm (INil))))
|
||||
(= ?normed_topk (Op (Mul ?normed_topk_shape ?normed_topk_a_stride ?normed_topk_b_stride ?normed_topk_out_stride) (ICons ?topk_vals (ICons ?topk_norm_factor (INil)))))
|
||||
|
||||
(= ?weighted (Op (Mul ?weighted_shape ?weighted_a_stride ?weighted_b_stride ?weighted_out_stride) (ICons ?dn_matmul (ICons ?normed_topk (INil)))))
|
||||
(= ?output (Op (Sum ?output_shape ?output_k ?output_in_stride ?output_k_stride ?output_out_stride) (ICons ?weighted (INil))))
|
||||
)
|
||||
(
|
||||
(let ?glumoe (Op (GLUMoE
|
||||
?gu_io ?dn_io ?gu_matmul_k ?dn_matmul_k ?output_k
|
||||
?gu_within_range ?dn_within_range (MNum 2))
|
||||
(ICons ?x (ICons ?topk_idx (ICons ?topk_vals (ICons ?gate_up_w (ICons ?down_w (ICons ?topk_vals (INil)))))))))
|
||||
(union ?output ?glumoe)
|
||||
(subsume (Op (Sum ?output_shape ?output_k ?output_in_stride ?output_k_stride ?output_out_stride) (ICons ?weighted (INil))))
|
||||
(subsume (Op (KernelSum ?output_shape ?output_k ?output_in_stride ?output_k_stride ?output_out_stride (F32)) (ICons ?weighted (INil))))
|
||||
)
|
||||
:ruleset glumoe
|
||||
:name "GLUMoE fused expert computation (normalized swiglu)"
|
||||
)
|
||||
|
||||
; ===== Final fusion: mode 1 (Gemma GELU) =====
|
||||
(rule
|
||||
(
|
||||
|
||||
@@ -32,7 +32,7 @@ use crate::{
|
||||
CudaFunction, CudaModule, CudaSlice, CudaStream, DevicePtr, LaunchConfig, PushKernelArg,
|
||||
},
|
||||
},
|
||||
host::HostOp,
|
||||
host::{DeviceBuffer, HostOp},
|
||||
try_create_cublaslt,
|
||||
};
|
||||
|
||||
@@ -50,7 +50,7 @@ const WORKSPACE_SIZE: usize = 32 * 1024 * 1024; // 32 MiB
|
||||
/// 3: gate_up_w [E, gate_up_dim, hidden] BF16
|
||||
/// 4: down_w [E, hidden, intermediate] BF16
|
||||
/// 5: mode_aux
|
||||
/// - SwiGLU: ignored (rewriter wires `topk_values` again)
|
||||
/// - SwiGLU/SwiGLUNormalized: ignored (rewriter wires `topk_values` again)
|
||||
/// - GemmaGELU: per_expert_scale [E] F32
|
||||
///
|
||||
/// Output: [seq, hidden] F32
|
||||
@@ -78,6 +78,7 @@ pub struct GLUMoE {
|
||||
pub(crate) enum GLUMoEMode {
|
||||
SwiGLU,
|
||||
GemmaGELU,
|
||||
SwiGLUNormalized,
|
||||
}
|
||||
|
||||
impl GLUMoEMode {
|
||||
@@ -85,6 +86,7 @@ impl GLUMoEMode {
|
||||
match mode_id {
|
||||
0 => Self::SwiGLU,
|
||||
1 => Self::GemmaGELU,
|
||||
2 => Self::SwiGLUNormalized,
|
||||
other => {
|
||||
panic!("Unknown GLUMoE mode id: {other}");
|
||||
}
|
||||
@@ -93,7 +95,7 @@ impl GLUMoEMode {
|
||||
|
||||
fn activation_kernel_mode(self) -> i32 {
|
||||
match self {
|
||||
Self::SwiGLU => 0,
|
||||
Self::SwiGLU | Self::SwiGLUNormalized => 0,
|
||||
Self::GemmaGELU => 1,
|
||||
}
|
||||
}
|
||||
@@ -294,27 +296,140 @@ impl HostOp for GLUMoE {
|
||||
stream: &Arc<CudaStream>,
|
||||
self_node: NodeIndex,
|
||||
inputs: &[NodeIndex],
|
||||
buffers: &FxHashMap<NodeIndex, &CudaSlice<u8>>,
|
||||
buffers: &FxHashMap<NodeIndex, DeviceBuffer>,
|
||||
dyn_map: &FxHashMap<char, usize>,
|
||||
) -> anyhow::Result<()> {
|
||||
// Resolve dimensions
|
||||
let hidden = self.gu_matmul_k.exec(dyn_map).unwrap();
|
||||
let intermediate = self.dn_matmul_k.exec(dyn_map).unwrap();
|
||||
let top_k_expected = self.output_k.exec(dyn_map).unwrap();
|
||||
let gate_up_dim = self.gu_io.exec(dyn_map).unwrap() / hidden; // gate_up_dim = gu_io / hidden
|
||||
let num_experts = self.gu_within_range.exec(dyn_map).unwrap() / (gate_up_dim * hidden);
|
||||
if inputs.len() < 6 {
|
||||
anyhow::bail!("GLUMoE expected at least 6 inputs, got {}", inputs.len());
|
||||
}
|
||||
|
||||
// Derive seq from x buffer size: x is [seq, hidden] F32 → seq = len / (hidden * 4)
|
||||
let x_buf = buffers[&inputs[0]];
|
||||
let seq = x_buf.len() / (hidden * 4);
|
||||
// Resolve dimensions
|
||||
let hidden = self
|
||||
.gu_matmul_k
|
||||
.exec(dyn_map)
|
||||
.ok_or_else(|| anyhow::anyhow!("GLUMoE hidden dimension is unresolved"))?;
|
||||
let intermediate = self
|
||||
.dn_matmul_k
|
||||
.exec(dyn_map)
|
||||
.ok_or_else(|| anyhow::anyhow!("GLUMoE intermediate dimension is unresolved"))?;
|
||||
let top_k = self
|
||||
.output_k
|
||||
.exec(dyn_map)
|
||||
.ok_or_else(|| anyhow::anyhow!("GLUMoE top-k dimension is unresolved"))?;
|
||||
let gu_io = self
|
||||
.gu_io
|
||||
.exec(dyn_map)
|
||||
.ok_or_else(|| anyhow::anyhow!("GLUMoE gate/up stride is unresolved"))?;
|
||||
let dn_io = self
|
||||
.dn_io
|
||||
.exec(dyn_map)
|
||||
.ok_or_else(|| anyhow::anyhow!("GLUMoE down stride is unresolved"))?;
|
||||
|
||||
if hidden == 0 || intermediate == 0 {
|
||||
anyhow::bail!(
|
||||
"GLUMoE got zero-sized matmul dimensions: hidden={hidden}, intermediate={intermediate}"
|
||||
);
|
||||
}
|
||||
if top_k == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
if gu_io % hidden != 0 {
|
||||
anyhow::bail!("GLUMoE gate/up stride {gu_io} is not divisible by hidden {hidden}");
|
||||
}
|
||||
if dn_io % intermediate != 0 {
|
||||
anyhow::bail!(
|
||||
"GLUMoE down stride {dn_io} is not divisible by intermediate {intermediate}"
|
||||
);
|
||||
}
|
||||
|
||||
let gate_up_dim = gu_io / hidden; // gate_up_dim = 2 * intermediate for GLU
|
||||
let down_hidden = dn_io / intermediate;
|
||||
if gate_up_dim != intermediate * 2 {
|
||||
anyhow::bail!(
|
||||
"GLUMoE expected gate/up dim {} to equal 2 * intermediate {}",
|
||||
gate_up_dim,
|
||||
intermediate * 2
|
||||
);
|
||||
}
|
||||
if down_hidden != hidden {
|
||||
anyhow::bail!("GLUMoE down hidden {down_hidden} does not match hidden {hidden}");
|
||||
}
|
||||
|
||||
let output_bytes = self
|
||||
.output_bytes()
|
||||
.exec(dyn_map)
|
||||
.ok_or_else(|| anyhow::anyhow!("GLUMoE output byte size is unresolved"))?;
|
||||
if output_bytes % (hidden * 4) != 0 {
|
||||
anyhow::bail!(
|
||||
"GLUMoE output bytes {output_bytes} are not divisible by hidden bytes {}",
|
||||
hidden * 4
|
||||
);
|
||||
}
|
||||
let seq = output_bytes / (hidden * 4);
|
||||
if seq == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let get_buffer = |name: &str, node: NodeIndex| -> anyhow::Result<DeviceBuffer> {
|
||||
buffers.get(&node).copied().ok_or_else(|| {
|
||||
anyhow::anyhow!("GLUMoE missing {name} buffer for LLIR node {node:?}")
|
||||
})
|
||||
};
|
||||
|
||||
// Get input/output buffers
|
||||
let topk_idx_buf = buffers[&inputs[1]]; // [seq, k] Int
|
||||
let topk_vals_buf = buffers[&inputs[2]]; // [seq, k] F32
|
||||
let gate_up_buf = buffers[&inputs[3]]; // [E, gate_up_dim, hidden] BF16
|
||||
let down_buf = buffers[&inputs[4]]; // [E, hidden, intermediate] BF16
|
||||
let mode_aux_buf = buffers[&inputs[5]];
|
||||
let output_buf = buffers[&self_node]; // [seq, hidden] F32
|
||||
let x_buf = get_buffer("x", inputs[0])?; // [seq, hidden] F32
|
||||
let topk_idx_buf = get_buffer("topk indices", inputs[1])?; // [seq, k] Int
|
||||
let topk_vals_buf = get_buffer("topk values", inputs[2])?; // [seq, k] F32
|
||||
let gate_up_buf = get_buffer("gate/up weights", inputs[3])?; // [E, gate_up_dim, hidden] BF16
|
||||
let down_buf = get_buffer("down weights", inputs[4])?; // [E, hidden, intermediate] BF16
|
||||
let mode_aux_buf = get_buffer("mode aux", inputs[5])?;
|
||||
let output_buf = get_buffer("output", self_node)?; // [seq, hidden] F32
|
||||
|
||||
let min_topk_bytes = seq * top_k * 4;
|
||||
if x_buf.len() < output_bytes {
|
||||
anyhow::bail!(
|
||||
"GLUMoE x buffer too small: have {} bytes, need {output_bytes}",
|
||||
x_buf.len()
|
||||
);
|
||||
}
|
||||
if topk_idx_buf.len() < min_topk_bytes {
|
||||
anyhow::bail!(
|
||||
"GLUMoE topk index buffer too small: have {} bytes, need {min_topk_bytes}",
|
||||
topk_idx_buf.len()
|
||||
);
|
||||
}
|
||||
if topk_vals_buf.len() < min_topk_bytes {
|
||||
anyhow::bail!(
|
||||
"GLUMoE topk value buffer too small: have {} bytes, need {min_topk_bytes}",
|
||||
topk_vals_buf.len()
|
||||
);
|
||||
}
|
||||
if output_buf.len() < output_bytes {
|
||||
anyhow::bail!(
|
||||
"GLUMoE output buffer too small: have {} bytes, need {output_bytes}",
|
||||
output_buf.len()
|
||||
);
|
||||
}
|
||||
|
||||
let gu_stride_bytes = gate_up_dim * hidden * 2;
|
||||
let down_stride_bytes = hidden * intermediate * 2;
|
||||
if gu_stride_bytes == 0 || gate_up_buf.len() % gu_stride_bytes != 0 {
|
||||
anyhow::bail!(
|
||||
"GLUMoE gate/up weight buffer has {} bytes, not a multiple of per-expert stride {gu_stride_bytes}",
|
||||
gate_up_buf.len()
|
||||
);
|
||||
}
|
||||
let num_experts = gate_up_buf.len() / gu_stride_bytes;
|
||||
if num_experts == 0 {
|
||||
anyhow::bail!("GLUMoE has no expert weights");
|
||||
}
|
||||
if down_buf.len() < num_experts * down_stride_bytes {
|
||||
anyhow::bail!(
|
||||
"GLUMoE down weight buffer too small: have {} bytes, need {}",
|
||||
down_buf.len(),
|
||||
num_experts * down_stride_bytes
|
||||
);
|
||||
}
|
||||
|
||||
// Get raw device pointer addresses
|
||||
let x_ptr = buf_ptr(x_buf, stream);
|
||||
@@ -326,41 +441,101 @@ impl HostOp for GLUMoE {
|
||||
let (_, f32_to_bf16_fn, activation_fn) = self.get_kernels(stream);
|
||||
|
||||
// Read top-k routing values from GPU
|
||||
let topk_idx_host: Vec<u8> = stream.clone_dtoh(topk_idx_buf)?;
|
||||
let topk_idx_host: Vec<u8> = topk_idx_buf.clone_dtoh(stream)?;
|
||||
let topk_idx_i32: &[i32] = bytemuck::cast_slice(&topk_idx_host);
|
||||
let topk_vals_host: Vec<u8> = stream.clone_dtoh(topk_vals_buf)?;
|
||||
let topk_vals_host: Vec<u8> = topk_vals_buf.clone_dtoh(stream)?;
|
||||
let topk_vals_f32: &[f32] = bytemuck::cast_slice(&topk_vals_host);
|
||||
let idx_k = topk_idx_i32
|
||||
.len()
|
||||
.checked_div(seq)
|
||||
.unwrap_or(top_k_expected);
|
||||
let val_k = topk_vals_f32
|
||||
.len()
|
||||
.checked_div(seq)
|
||||
.unwrap_or(top_k_expected);
|
||||
let top_k = idx_k.min(val_k);
|
||||
if seq > 0 && top_k == 0 {
|
||||
return Ok(());
|
||||
|
||||
if !topk_idx_i32.len().is_multiple_of(seq) {
|
||||
anyhow::bail!(
|
||||
"GLUMoE topk index element count {} is not divisible by seq {seq}",
|
||||
topk_idx_i32.len()
|
||||
);
|
||||
}
|
||||
if !topk_vals_f32.len().is_multiple_of(seq) {
|
||||
anyhow::bail!(
|
||||
"GLUMoE topk value element count {} is not divisible by seq {seq}",
|
||||
topk_vals_f32.len()
|
||||
);
|
||||
}
|
||||
let topk_idx_row_stride = topk_idx_i32.len() / seq;
|
||||
let topk_vals_row_stride = topk_vals_f32.len() / seq;
|
||||
if topk_idx_row_stride < top_k {
|
||||
anyhow::bail!(
|
||||
"GLUMoE topk index row stride {topk_idx_row_stride} is smaller than top_k {top_k}"
|
||||
);
|
||||
}
|
||||
if topk_vals_row_stride < top_k {
|
||||
anyhow::bail!(
|
||||
"GLUMoE topk value row stride {topk_vals_row_stride} is smaller than top_k {top_k}"
|
||||
);
|
||||
}
|
||||
|
||||
let topk_idx_at = |token: usize, expert: usize| -> i32 {
|
||||
topk_idx_i32[token * topk_idx_row_stride + expert]
|
||||
};
|
||||
let topk_val_at = |token: usize, expert: usize| -> f32 {
|
||||
topk_vals_f32[token * topk_vals_row_stride + expert]
|
||||
};
|
||||
|
||||
for t in 0..seq {
|
||||
for i in 0..top_k {
|
||||
let expert_idx = topk_idx_at(t, i);
|
||||
if expert_idx < 0 || expert_idx as usize >= num_experts {
|
||||
anyhow::bail!(
|
||||
"GLUMoE expert index {expert_idx} at token {t} top-k position {i} out of bounds for {num_experts} experts"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Mode-dependent expert weights used for the final reduction:
|
||||
// - SwiGLU: direct topk values
|
||||
// - SwiGLUNormalized: normalize topk values row-wise
|
||||
// - GemmaGELU: normalize topk values and scale by per-expert factors
|
||||
let mut expert_weights_storage: Vec<f32> = Vec::new();
|
||||
let expert_weights_f32: &[f32] = match self.mode {
|
||||
GLUMoEMode::SwiGLU => topk_vals_f32,
|
||||
GLUMoEMode::GemmaGELU => {
|
||||
let per_expert_scale_host: Vec<u8> = stream.clone_dtoh(mode_aux_buf)?;
|
||||
let per_expert_scale_f32: &[f32] = bytemuck::cast_slice(&per_expert_scale_host);
|
||||
debug_assert!(per_expert_scale_f32.len() >= num_experts);
|
||||
GLUMoEMode::SwiGLU => {
|
||||
if topk_vals_row_stride == top_k {
|
||||
topk_vals_f32
|
||||
} else {
|
||||
expert_weights_storage.resize(seq * top_k, 0.0);
|
||||
for t in 0..seq {
|
||||
for i in 0..top_k {
|
||||
expert_weights_storage[t * top_k + i] = topk_val_at(t, i);
|
||||
}
|
||||
}
|
||||
&expert_weights_storage
|
||||
}
|
||||
}
|
||||
GLUMoEMode::SwiGLUNormalized => {
|
||||
expert_weights_storage.resize(seq * top_k, 0.0);
|
||||
for t in 0..seq {
|
||||
let base = t * top_k;
|
||||
let vals = &topk_vals_f32[base..base + top_k];
|
||||
let norm = vals.iter().copied().sum::<f32>();
|
||||
let norm = (0..top_k).map(|i| topk_val_at(t, i)).sum::<f32>();
|
||||
let inv_norm = if norm != 0.0 { norm.recip() } else { 0.0 };
|
||||
for i in 0..top_k {
|
||||
let expert_idx = topk_idx_i32[base + i] as usize;
|
||||
expert_weights_storage[t * top_k + i] = topk_val_at(t, i) * inv_norm;
|
||||
}
|
||||
}
|
||||
&expert_weights_storage
|
||||
}
|
||||
GLUMoEMode::GemmaGELU => {
|
||||
let per_expert_scale_host: Vec<u8> = mode_aux_buf.clone_dtoh(stream)?;
|
||||
let per_expert_scale_bytes = num_experts * 4;
|
||||
if per_expert_scale_host.len() < per_expert_scale_bytes {
|
||||
anyhow::bail!(
|
||||
"GLUMoE per-expert scale buffer too small: have {} bytes, need {per_expert_scale_bytes}",
|
||||
per_expert_scale_host.len()
|
||||
);
|
||||
}
|
||||
let per_expert_scale_f32: &[f32] =
|
||||
bytemuck::cast_slice(&per_expert_scale_host[..per_expert_scale_bytes]);
|
||||
expert_weights_storage.resize(seq * top_k, 0.0);
|
||||
for t in 0..seq {
|
||||
let norm = (0..top_k).map(|i| topk_val_at(t, i)).sum::<f32>();
|
||||
let inv_norm = if norm != 0.0 { norm.recip() } else { 0.0 };
|
||||
for i in 0..top_k {
|
||||
let expert_idx = topk_idx_at(t, i) as usize;
|
||||
if expert_idx >= per_expert_scale_f32.len() {
|
||||
anyhow::bail!(
|
||||
"GLUMoE Gemma mode expert index {} out of bounds {}",
|
||||
@@ -369,7 +544,8 @@ impl HostOp for GLUMoE {
|
||||
);
|
||||
}
|
||||
let scale = per_expert_scale_f32[expert_idx];
|
||||
expert_weights_storage[base + i] = vals[i] * inv_norm * scale;
|
||||
expert_weights_storage[t * top_k + i] =
|
||||
topk_val_at(t, i) * inv_norm * scale;
|
||||
}
|
||||
}
|
||||
&expert_weights_storage
|
||||
@@ -382,10 +558,10 @@ impl HostOp for GLUMoE {
|
||||
let hidden_tmp = unsafe { stream.alloc::<u8>(intermediate * 2)? }; // BF16
|
||||
let workspace = unsafe { stream.alloc::<u8>(WORKSPACE_SIZE)? };
|
||||
|
||||
let xbf16_ptr = buf_ptr(&x_bf16_buf, stream);
|
||||
let gu_out_ptr = buf_ptr(&gate_up_out_buf, stream);
|
||||
let hid_ptr = buf_ptr(&hidden_tmp, stream);
|
||||
let ws_ptr = buf_ptr(&workspace, stream);
|
||||
let xbf16_ptr = slice_ptr(&x_bf16_buf, stream);
|
||||
let gu_out_ptr = slice_ptr(&gate_up_out_buf, stream);
|
||||
let hid_ptr = slice_ptr(&hidden_tmp, stream);
|
||||
let ws_ptr = slice_ptr(&workspace, stream);
|
||||
|
||||
// Cast x F32 → BF16
|
||||
let n_cast = (seq * hidden) as i32;
|
||||
@@ -404,17 +580,15 @@ impl HostOp for GLUMoE {
|
||||
}
|
||||
|
||||
// Per-token expert computation
|
||||
let gu_stride = (gate_up_dim * hidden * 2) as u64; // bytes per expert gate_up (BF16)
|
||||
let down_stride = (hidden * intermediate * 2) as u64; // bytes per expert down (BF16)
|
||||
let gu_stride = gu_stride_bytes as u64; // bytes per expert gate_up (BF16)
|
||||
let down_stride = down_stride_bytes as u64; // bytes per expert down (BF16)
|
||||
|
||||
for t in 0..seq {
|
||||
let x_t_ptr = xbf16_ptr + (t * hidden * 2) as u64; // BF16
|
||||
let expert_indices = &topk_idx_i32[t * top_k..(t + 1) * top_k];
|
||||
let weights = &expert_weights_f32[t * top_k..(t + 1) * top_k];
|
||||
|
||||
for (i, (&expert_idx, &weight)) in expert_indices.iter().zip(weights.iter()).enumerate()
|
||||
{
|
||||
let expert_idx = expert_idx as usize;
|
||||
for (i, &weight) in weights.iter().enumerate() {
|
||||
let expert_idx = topk_idx_at(t, i) as usize;
|
||||
|
||||
// a. Gate+Up matmul (BF16 in, BF16 out)
|
||||
let expert_gu_ptr = gate_up_ptr + expert_idx as u64 * gu_stride;
|
||||
@@ -507,7 +681,11 @@ impl HostOp for GLUMoE {
|
||||
// Helpers
|
||||
// ============================================================
|
||||
|
||||
fn buf_ptr(buf: &CudaSlice<u8>, stream: &Arc<CudaStream>) -> u64 {
|
||||
fn buf_ptr(buf: DeviceBuffer, _stream: &Arc<CudaStream>) -> u64 {
|
||||
buf.ptr()
|
||||
}
|
||||
|
||||
fn slice_ptr(buf: &CudaSlice<u8>, stream: &Arc<CudaStream>) -> u64 {
|
||||
let (ptr, _guard) = buf.device_ptr(stream);
|
||||
ptr
|
||||
}
|
||||
|
||||
738
crates/luminal_cuda_lite/src/kernel/conv2d.rs
Normal file
738
crates/luminal_cuda_lite/src/kernel/conv2d.rs
Normal file
@@ -0,0 +1,738 @@
|
||||
//! CUDA conv2d-with-bias backend rewrite.
|
||||
//!
|
||||
//! `KernelConv2D` is selected by egglog from pure HLIR conv graphs and lowers
|
||||
//! to a one-thread-per-output CUDA kernel. It avoids materializing unfold/im2col
|
||||
//! intermediates while keeping model code free of custom ops.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use cudarc::driver::{CudaFunction, CudaModule, CudaSlice, CudaStream};
|
||||
use luminal::prelude::FxHashMap;
|
||||
use luminal::{
|
||||
dtype::DType,
|
||||
egglog_utils::{
|
||||
api::{Rule, SortDef, sort},
|
||||
base::{DTYPE, ELIST, EXPRESSION, OP_KIND},
|
||||
extract_dtype, extract_expr, extract_expr_list,
|
||||
},
|
||||
op::{EgglogOp, LLIROp},
|
||||
prelude::FxHashSet,
|
||||
shape::{Expression, flatten_strides},
|
||||
};
|
||||
|
||||
use crate::compile_module_image_for_current_device;
|
||||
use crate::kernel::{KernelOp, hlir::generate_dyn_dims_defines};
|
||||
|
||||
#[derive(Default, Debug, Clone)]
|
||||
pub struct KernelConv2D {
|
||||
out_shape: Vec<Expression>,
|
||||
input_shape: Vec<Expression>,
|
||||
input_stride: Vec<Expression>,
|
||||
weight_co_stride: Expression,
|
||||
weight_inner_stride: Expression,
|
||||
bias_c_stride: Expression,
|
||||
out_stride: Vec<Expression>,
|
||||
kernel_h: Expression,
|
||||
kernel_w: Expression,
|
||||
stride_h: Expression,
|
||||
stride_w: Expression,
|
||||
dilation_h: Expression,
|
||||
dilation_w: Expression,
|
||||
pad_h: Expression,
|
||||
pad_w: Expression,
|
||||
dtype: DType,
|
||||
}
|
||||
|
||||
impl EgglogOp for KernelConv2D {
|
||||
fn sort(&self) -> SortDef {
|
||||
sort(
|
||||
OP_KIND,
|
||||
"KernelConv2D",
|
||||
&[
|
||||
("out_shape", ELIST),
|
||||
("input_shape", ELIST),
|
||||
("input_stride", ELIST),
|
||||
("weight_co_stride", EXPRESSION),
|
||||
("weight_inner_stride", EXPRESSION),
|
||||
("bias_c_stride", EXPRESSION),
|
||||
("out_stride", ELIST),
|
||||
("kernel_h", EXPRESSION),
|
||||
("kernel_w", EXPRESSION),
|
||||
("stride_h", EXPRESSION),
|
||||
("stride_w", EXPRESSION),
|
||||
("dilation_h", EXPRESSION),
|
||||
("dilation_w", EXPRESSION),
|
||||
("pad_h", EXPRESSION),
|
||||
("pad_w", EXPRESSION),
|
||||
("dtype", DTYPE),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
fn n_inputs(&self) -> usize {
|
||||
3
|
||||
}
|
||||
|
||||
fn rewrites(&self) -> Vec<Rule> {
|
||||
vec![
|
||||
// 1x1 convs in Flux2's VAE are represented without `unfold`:
|
||||
//
|
||||
// input.permute([H,W,C]).merge(H,W)
|
||||
// -> matmul(weight.t())
|
||||
// -> split/permute back to [C_out,H,W]
|
||||
// -> + channel bias
|
||||
//
|
||||
// The lowered form is still the same Mul -> KernelSum -> Add
|
||||
// matmul skeleton, but the lhs FusionStart reads directly from the
|
||||
// original input instead of a KernelGather window tensor.
|
||||
Rule::raw(
|
||||
"(rule
|
||||
(
|
||||
(= ?out (Op (FusionEnd ?out_shape ?out_stride (F32)) (ICons ?add_elem (INil))))
|
||||
(= ?add_elem (Op (CudaBinaryElementwise \"Add\" ?out_shape ?sum_add_stride ?bias_add_stride ?out_stride (F32)) (ICons ?sum_fs (ICons ?bias_fs (INil)))))
|
||||
(= ?sum_fs (Op (FusionStart ?out_shape ?sum_add_stride (F32)) (ICons ?sum (INil))))
|
||||
(= ?bias_fs (Op (FusionStart ?out_shape ?bias_add_stride (F32)) (ICons ?bias (INil))))
|
||||
|
||||
(= ?sum (Op (KernelSum ?matmul_out_shape ?c_in ?sum_in_stride ?k_stride ?sum_out_stride (F32)) (ICons ?mul_fe (INil))))
|
||||
(= ?mul_fe (Op (FusionEnd ?mul_shape ?mul_out_stride (F32)) (ICons ?mul_elem (INil))))
|
||||
(= ?mul_elem (Op (CudaBinaryElementwise \"Mul\" ?mul_shape ?input_1x1_stride ?weight_stride ?mul_out_stride (F32)) (ICons ?input_fs (ICons ?weight_fs (INil)))))
|
||||
(= ?input_fs (Op (FusionStart ?mul_shape ?input_1x1_stride (F32)) (ICons ?input (INil))))
|
||||
(= ?weight_fs (Op (FusionStart ?mul_shape ?weight_stride (F32)) (ICons ?weight (INil))))
|
||||
|
||||
(= ?out_shape (ECons ?c_out (ECons ?h_out (ECons ?w_out (ENil)))))
|
||||
(= ?matmul_out_shape (ECons ?m (ECons ?c_out (ENil))))
|
||||
(= ?mul_shape (ECons ?m (ECons ?c_out (ECons ?c_in (ENil)))))
|
||||
(= ?input_1x1_stride (ECons ?flat_stride (ECons (MNum 0) (ECons ?input_c_stride (ENil)))))
|
||||
(= ?flat_stride (MIter))
|
||||
|
||||
(= ?k_stride (MIter))
|
||||
(= ?sum_in_stride (ECons ?sum_m_stride (ECons ?sum_c_stride (ENil))))
|
||||
(= ?sum_out_stride (ECons ?sum_out_m_stride (ECons ?sum_out_c_stride (ENil))))
|
||||
(= ?sum_add_stride (ECons ?sum_add_c_stride (ECons ?sum_add_h_stride (ECons ?sum_add_w_stride (ENil)))))
|
||||
(= ?weight_co_stride (nth_from_end ?weight_stride 1))
|
||||
(= ?weight_inner_stride (nth_from_end ?weight_stride 0))
|
||||
(= (MNum 0) (nth_from_end ?weight_stride 2))
|
||||
(= ?bias_add_stride (ECons ?bias_c_stride (ECons (MNum 0) (ECons (MNum 0) (ENil)))))
|
||||
)
|
||||
(
|
||||
(let ?conv (Op (KernelConv2D
|
||||
?out_shape
|
||||
(ECons ?c_in (ECons ?h_out (ECons ?w_out (ENil))))
|
||||
(ECons ?input_c_stride (ECons (MMul ?w_out ?flat_stride) (ECons ?flat_stride (ENil))))
|
||||
?weight_co_stride
|
||||
?weight_inner_stride
|
||||
?bias_c_stride
|
||||
?out_stride
|
||||
(MNum 1)
|
||||
(MNum 1)
|
||||
(MNum 1)
|
||||
(MNum 1)
|
||||
(MNum 1)
|
||||
(MNum 1)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(F32))
|
||||
(ICons ?input (ICons ?weight (ICons ?bias (INil))))))
|
||||
(union ?out ?conv)
|
||||
(subsume (Op (FusionEnd ?out_shape ?out_stride (F32)) (ICons ?add_elem (INil))))
|
||||
(set (dtype ?conv) (F32))
|
||||
)
|
||||
:ruleset kernel_lower
|
||||
:name \"kernel conv2d 1x1 from cuda lowered matmul bias\"
|
||||
)",
|
||||
),
|
||||
Rule::raw(
|
||||
"(rule
|
||||
(
|
||||
(= ?out (Op (FusionEnd ?out_shape ?out_stride (F32)) (ICons ?add_elem (INil))))
|
||||
(= ?add_elem (Op (CudaBinaryElementwise \"Add\" ?out_shape ?bias_add_stride ?sum_add_stride ?out_stride (F32)) (ICons ?bias_fs (ICons ?sum_fs (INil)))))
|
||||
(= ?sum_fs (Op (FusionStart ?out_shape ?sum_add_stride (F32)) (ICons ?sum (INil))))
|
||||
(= ?bias_fs (Op (FusionStart ?out_shape ?bias_add_stride (F32)) (ICons ?bias (INil))))
|
||||
|
||||
(= ?sum (Op (KernelSum ?matmul_out_shape ?c_in ?sum_in_stride ?k_stride ?sum_out_stride (F32)) (ICons ?mul_fe (INil))))
|
||||
(= ?mul_fe (Op (FusionEnd ?mul_shape ?mul_out_stride (F32)) (ICons ?mul_elem (INil))))
|
||||
(= ?mul_elem (Op (CudaBinaryElementwise \"Mul\" ?mul_shape ?input_1x1_stride ?weight_stride ?mul_out_stride (F32)) (ICons ?input_fs (ICons ?weight_fs (INil)))))
|
||||
(= ?input_fs (Op (FusionStart ?mul_shape ?input_1x1_stride (F32)) (ICons ?input (INil))))
|
||||
(= ?weight_fs (Op (FusionStart ?mul_shape ?weight_stride (F32)) (ICons ?weight (INil))))
|
||||
|
||||
(= ?out_shape (ECons ?c_out (ECons ?h_out (ECons ?w_out (ENil)))))
|
||||
(= ?matmul_out_shape (ECons ?m (ECons ?c_out (ENil))))
|
||||
(= ?mul_shape (ECons ?m (ECons ?c_out (ECons ?c_in (ENil)))))
|
||||
(= ?input_1x1_stride (ECons ?flat_stride (ECons (MNum 0) (ECons ?input_c_stride (ENil)))))
|
||||
(= ?flat_stride (MIter))
|
||||
|
||||
(= ?k_stride (MIter))
|
||||
(= ?sum_in_stride (ECons ?sum_m_stride (ECons ?sum_c_stride (ENil))))
|
||||
(= ?sum_out_stride (ECons ?sum_out_m_stride (ECons ?sum_out_c_stride (ENil))))
|
||||
(= ?sum_add_stride (ECons ?sum_add_c_stride (ECons ?sum_add_h_stride (ECons ?sum_add_w_stride (ENil)))))
|
||||
(= ?weight_co_stride (nth_from_end ?weight_stride 1))
|
||||
(= ?weight_inner_stride (nth_from_end ?weight_stride 0))
|
||||
(= (MNum 0) (nth_from_end ?weight_stride 2))
|
||||
(= ?bias_add_stride (ECons ?bias_c_stride (ECons (MNum 0) (ECons (MNum 0) (ENil)))))
|
||||
)
|
||||
(
|
||||
(let ?conv (Op (KernelConv2D
|
||||
?out_shape
|
||||
(ECons ?c_in (ECons ?h_out (ECons ?w_out (ENil))))
|
||||
(ECons ?input_c_stride (ECons (MMul ?w_out ?flat_stride) (ECons ?flat_stride (ENil))))
|
||||
?weight_co_stride
|
||||
?weight_inner_stride
|
||||
?bias_c_stride
|
||||
?out_stride
|
||||
(MNum 1)
|
||||
(MNum 1)
|
||||
(MNum 1)
|
||||
(MNum 1)
|
||||
(MNum 1)
|
||||
(MNum 1)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(F32))
|
||||
(ICons ?input (ICons ?weight (ICons ?bias (INil))))))
|
||||
(union ?out ?conv)
|
||||
(subsume (Op (FusionEnd ?out_shape ?out_stride (F32)) (ICons ?add_elem (INil))))
|
||||
(set (dtype ?conv) (F32))
|
||||
)
|
||||
:ruleset kernel_lower
|
||||
:name \"kernel conv2d 1x1 from cuda lowered bias matmul\"
|
||||
)",
|
||||
),
|
||||
// Match the same conv after generic CUDA lowering has normalized
|
||||
// the elementwise pieces into fusion regions:
|
||||
//
|
||||
// KernelGather(input windows)
|
||||
// -> CudaBinaryElementwise("Mul", weight)
|
||||
// -> KernelSum(reduce K)
|
||||
// -> CudaBinaryElementwise("Add", bias)
|
||||
//
|
||||
// This is the form that survives long enough for CUDA search in
|
||||
// real models. The KernelConv2D op consumes the pre-gather input
|
||||
// and avoids materializing both the im2col window tensor and the
|
||||
// elementwise product tensor.
|
||||
//
|
||||
// TODO(egglog-shapes): the current e-graph does not reliably prove
|
||||
// the derived arithmetic equalities for this chain after CUDA
|
||||
// normalization:
|
||||
// * `M == H_out * W_out`
|
||||
// * `K == C_in * KH * KW`
|
||||
// * separately-derived but structurally identical stride
|
||||
// expressions, e.g. the Mul output stride and KernelSum input
|
||||
// stride, belong to the same e-class.
|
||||
// Keep the rewrite anchored on the stable conv layout facts the
|
||||
// graph does carry today: six-axis unfold window shape, flattened
|
||||
// `[M, C_out, K]` product, reduction over `K`, the three-axis
|
||||
// `[C_out, H_out, W_out]` output view, and channel-only bias
|
||||
// broadcast. Once expression/list canonicalization can prove those
|
||||
// equalities, tighten this rule and its regression tests.
|
||||
Rule::raw(
|
||||
"(rule
|
||||
(
|
||||
(= ?out (Op (FusionEnd ?out_shape ?out_stride (F32)) (ICons ?add_elem (INil))))
|
||||
(= ?add_elem (Op (CudaBinaryElementwise \"Add\" ?out_shape ?sum_add_stride ?bias_add_stride ?out_stride (F32)) (ICons ?sum_fs (ICons ?bias_fs (INil)))))
|
||||
(= ?sum_fs (Op (FusionStart ?out_shape ?sum_add_stride (F32)) (ICons ?sum (INil))))
|
||||
(= ?bias_fs (Op (FusionStart ?out_shape ?bias_add_stride (F32)) (ICons ?bias (INil))))
|
||||
|
||||
(= ?sum (Op (KernelSum ?matmul_out_shape ?k_dim ?sum_in_stride ?k_stride ?sum_out_stride (F32)) (ICons ?mul_fe (INil))))
|
||||
(= ?mul_fe (Op (FusionEnd ?mul_shape ?mul_out_stride (F32)) (ICons ?mul_elem (INil))))
|
||||
(= ?mul_elem (Op (CudaBinaryElementwise \"Mul\" ?mul_shape ?patch_stride ?weight_stride ?mul_out_stride (F32)) (ICons ?patch_fs (ICons ?weight_fs (INil)))))
|
||||
(= ?patch_fs (Op (FusionStart ?mul_shape ?patch_stride (F32)) (ICons ?patches (INil))))
|
||||
(= ?weight_fs (Op (FusionStart ?mul_shape ?weight_stride (F32)) (ICons ?weight (INil))))
|
||||
(= ?patches (Op (KernelGather ?idx_shape ?idx_stride ?input_shape ?input_stride ?gather_out_stride (F32)) (ICons ?indices (ICons ?input (INil)))))
|
||||
|
||||
(= ?out_shape (ECons ?c_out (ECons ?h_out (ECons ?w_out (ENil)))))
|
||||
(= ?input_shape (ECons ?c_in (ECons ?h_in (ECons ?w_in (ENil)))))
|
||||
(= ?idx_shape (ECons ?c_in (ECons ?h_out (ECons ?w_out (ECons (MNum 1) (ECons ?kernel_h (ECons ?kernel_w (ENil))))))))
|
||||
(= ?matmul_out_shape (ECons ?m (ECons ?c_out (ENil))))
|
||||
(= ?mul_shape (ECons ?m (ECons ?c_out (ECons ?k_dim (ENil)))))
|
||||
|
||||
(= ?k_stride (MIter))
|
||||
(= ?sum_in_stride (ECons ?sum_m_stride (ECons ?sum_c_stride (ENil))))
|
||||
(= ?sum_out_stride (ECons ?sum_out_m_stride (ECons ?sum_out_c_stride (ENil))))
|
||||
(= ?sum_add_stride (ECons ?sum_add_c_stride (ECons ?sum_add_h_stride (ECons ?sum_add_w_stride (ENil)))))
|
||||
(= ?weight_co_stride (nth_from_end ?weight_stride 1))
|
||||
(= ?weight_inner_stride (nth_from_end ?weight_stride 0))
|
||||
(= (MNum 0) (nth_from_end ?weight_stride 2))
|
||||
(= ?bias_add_stride (ECons ?bias_c_stride (ECons (MNum 0) (ECons (MNum 0) (ENil)))))
|
||||
)
|
||||
(
|
||||
(let ?conv (Op (KernelConv2D
|
||||
?out_shape
|
||||
?input_shape
|
||||
?input_stride
|
||||
?weight_co_stride
|
||||
?weight_inner_stride
|
||||
?bias_c_stride
|
||||
?out_stride
|
||||
?kernel_h
|
||||
?kernel_w
|
||||
(MNum 1)
|
||||
(MNum 1)
|
||||
(MNum 1)
|
||||
(MNum 1)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(F32))
|
||||
(ICons ?input (ICons ?weight (ICons ?bias (INil))))))
|
||||
(union ?out ?conv)
|
||||
(subsume (Op (FusionEnd ?out_shape ?out_stride (F32)) (ICons ?add_elem (INil))))
|
||||
(set (dtype ?conv) (F32))
|
||||
)
|
||||
:ruleset kernel_lower
|
||||
:name \"kernel conv2d from cuda lowered unfold matmul bias\"
|
||||
)",
|
||||
),
|
||||
Rule::raw(
|
||||
"(rule
|
||||
(
|
||||
(= ?out (Op (FusionEnd ?out_shape ?out_stride (F32)) (ICons ?add_elem (INil))))
|
||||
(= ?add_elem (Op (CudaBinaryElementwise \"Add\" ?out_shape ?bias_add_stride ?sum_add_stride ?out_stride (F32)) (ICons ?bias_fs (ICons ?sum_fs (INil)))))
|
||||
(= ?sum_fs (Op (FusionStart ?out_shape ?sum_add_stride (F32)) (ICons ?sum (INil))))
|
||||
(= ?bias_fs (Op (FusionStart ?out_shape ?bias_add_stride (F32)) (ICons ?bias (INil))))
|
||||
|
||||
(= ?sum (Op (KernelSum ?matmul_out_shape ?k_dim ?sum_in_stride ?k_stride ?sum_out_stride (F32)) (ICons ?mul_fe (INil))))
|
||||
(= ?mul_fe (Op (FusionEnd ?mul_shape ?mul_out_stride (F32)) (ICons ?mul_elem (INil))))
|
||||
(= ?mul_elem (Op (CudaBinaryElementwise \"Mul\" ?mul_shape ?patch_stride ?weight_stride ?mul_out_stride (F32)) (ICons ?patch_fs (ICons ?weight_fs (INil)))))
|
||||
(= ?patch_fs (Op (FusionStart ?mul_shape ?patch_stride (F32)) (ICons ?patches (INil))))
|
||||
(= ?weight_fs (Op (FusionStart ?mul_shape ?weight_stride (F32)) (ICons ?weight (INil))))
|
||||
(= ?patches (Op (KernelGather ?idx_shape ?idx_stride ?input_shape ?input_stride ?gather_out_stride (F32)) (ICons ?indices (ICons ?input (INil)))))
|
||||
|
||||
(= ?out_shape (ECons ?c_out (ECons ?h_out (ECons ?w_out (ENil)))))
|
||||
(= ?input_shape (ECons ?c_in (ECons ?h_in (ECons ?w_in (ENil)))))
|
||||
(= ?idx_shape (ECons ?c_in (ECons ?h_out (ECons ?w_out (ECons (MNum 1) (ECons ?kernel_h (ECons ?kernel_w (ENil))))))))
|
||||
(= ?matmul_out_shape (ECons ?m (ECons ?c_out (ENil))))
|
||||
(= ?mul_shape (ECons ?m (ECons ?c_out (ECons ?k_dim (ENil)))))
|
||||
|
||||
(= ?k_stride (MIter))
|
||||
(= ?sum_in_stride (ECons ?sum_m_stride (ECons ?sum_c_stride (ENil))))
|
||||
(= ?sum_out_stride (ECons ?sum_out_m_stride (ECons ?sum_out_c_stride (ENil))))
|
||||
(= ?sum_add_stride (ECons ?sum_add_c_stride (ECons ?sum_add_h_stride (ECons ?sum_add_w_stride (ENil)))))
|
||||
(= ?weight_co_stride (nth_from_end ?weight_stride 1))
|
||||
(= ?weight_inner_stride (nth_from_end ?weight_stride 0))
|
||||
(= (MNum 0) (nth_from_end ?weight_stride 2))
|
||||
(= ?bias_add_stride (ECons ?bias_c_stride (ECons (MNum 0) (ECons (MNum 0) (ENil)))))
|
||||
)
|
||||
(
|
||||
(let ?conv (Op (KernelConv2D
|
||||
?out_shape
|
||||
?input_shape
|
||||
?input_stride
|
||||
?weight_co_stride
|
||||
?weight_inner_stride
|
||||
?bias_c_stride
|
||||
?out_stride
|
||||
?kernel_h
|
||||
?kernel_w
|
||||
(MNum 1)
|
||||
(MNum 1)
|
||||
(MNum 1)
|
||||
(MNum 1)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(F32))
|
||||
(ICons ?input (ICons ?weight (ICons ?bias (INil))))))
|
||||
(union ?out ?conv)
|
||||
(subsume (Op (FusionEnd ?out_shape ?out_stride (F32)) (ICons ?add_elem (INil))))
|
||||
(set (dtype ?conv) (F32))
|
||||
)
|
||||
:ruleset kernel_lower
|
||||
:name \"kernel conv2d from cuda lowered bias unfold matmul\"
|
||||
)",
|
||||
),
|
||||
// Match the im2col-style HLIR conv used by Flux2:
|
||||
//
|
||||
// input.unfold([1, kh, kw], [1, 1, 1], [1, 1, 1])
|
||||
// -> squeeze/permute/merge view
|
||||
// -> matmul(weight.t())
|
||||
// -> split/permute view
|
||||
// -> + bias.expand_dim(1, h_out).expand_dim(2, w_out)
|
||||
//
|
||||
// The kernel consumes the pre-unfold input directly. That input may
|
||||
// already be a padded HLIR tensor, so the rewrite is still correct
|
||||
// for Flux2's padded convs while removing the large patch matrix.
|
||||
Rule::raw(
|
||||
"(rule
|
||||
(
|
||||
(= ?add (Op (Add ?out_shape ?sum_add_stride ?bias_add_stride ?add_out_stride) (ICons ?sum (ICons ?bias (INil)))))
|
||||
(= ?sum (Op (Sum ?matmul_out_shape ?k_dim ?sum_in_stride ?k_stride ?sum_out_stride) (ICons ?mul (INil))))
|
||||
(= ?mul (Op (Mul ?mul_shape ?patch_stride ?weight_stride ?mul_out_stride) (ICons ?patches (ICons ?weight (INil)))))
|
||||
(= ?patches (Op (Gather ?idx_shape ?idx_stride ?input_shape ?input_stride) (ICons ?indices (ICons ?input (INil)))))
|
||||
|
||||
(= ?out_shape (ECons ?c_out (ECons ?h_out (ECons ?w_out (ENil)))))
|
||||
(= ?input_shape (ECons ?c_in (ECons ?h_in (ECons ?w_in (ENil)))))
|
||||
(= ?idx_shape (ECons ?c_in (ECons ?h_out (ECons ?w_out (ECons (MNum 1) (ECons ?kernel_h (ECons ?kernel_w (ENil))))))))
|
||||
(= ?matmul_out_shape (ECons ?m (ECons ?c_out (ENil))))
|
||||
|
||||
; This rewrite is for stride=1, dilation=1 over the
|
||||
; tensor passed to unfold. Padded HLIR inputs are already
|
||||
; represented as their own tensor, so padding is 0 here.
|
||||
(= ?h_out (MAdd (MSub ?h_in ?kernel_h) (MNum 1)))
|
||||
(= ?w_out (MAdd (MSub ?w_in ?kernel_w) (MNum 1)))
|
||||
(= ?m (MMul ?h_out ?w_out))
|
||||
(= ?k_dim (MMul ?c_in (MMul ?kernel_h ?kernel_w)))
|
||||
(= ?k_stride (MIter))
|
||||
|
||||
(= ?weight_co_stride (nth_from_end ?weight_stride 1))
|
||||
(= ?weight_inner_stride (nth_from_end ?weight_stride 0))
|
||||
(= (MNum 0) (nth_from_end ?weight_stride 2))
|
||||
|
||||
(= ?bias_add_stride (ECons ?bias_c_stride (ECons (MNum 0) (ECons (MNum 0) (ENil)))))
|
||||
|
||||
(= (F32) (dtype ?input))
|
||||
(= (F32) (dtype ?weight))
|
||||
(= (F32) (dtype ?bias))
|
||||
)
|
||||
(
|
||||
(let ?conv (Op (KernelConv2D
|
||||
?out_shape
|
||||
?input_shape
|
||||
?input_stride
|
||||
?weight_co_stride
|
||||
?weight_inner_stride
|
||||
?bias_c_stride
|
||||
?add_out_stride
|
||||
?kernel_h
|
||||
?kernel_w
|
||||
(MNum 1)
|
||||
(MNum 1)
|
||||
(MNum 1)
|
||||
(MNum 1)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(F32))
|
||||
(ICons ?input (ICons ?weight (ICons ?bias (INil))))))
|
||||
(union ?add ?conv)
|
||||
(subsume (Op (Add ?out_shape ?sum_add_stride ?bias_add_stride ?add_out_stride) (ICons ?sum (ICons ?bias (INil)))))
|
||||
(set (dtype ?conv) (F32))
|
||||
)
|
||||
:ruleset kernel_specialize
|
||||
:name \"kernel conv2d from unfold matmul bias\"
|
||||
)",
|
||||
),
|
||||
Rule::raw(
|
||||
"(rule
|
||||
(
|
||||
(= ?add (Op (Add ?out_shape ?bias_add_stride ?sum_add_stride ?add_out_stride) (ICons ?bias (ICons ?sum (INil)))))
|
||||
(= ?sum (Op (Sum ?matmul_out_shape ?k_dim ?sum_in_stride ?k_stride ?sum_out_stride) (ICons ?mul (INil))))
|
||||
(= ?mul (Op (Mul ?mul_shape ?patch_stride ?weight_stride ?mul_out_stride) (ICons ?patches (ICons ?weight (INil)))))
|
||||
(= ?patches (Op (Gather ?idx_shape ?idx_stride ?input_shape ?input_stride) (ICons ?indices (ICons ?input (INil)))))
|
||||
|
||||
(= ?out_shape (ECons ?c_out (ECons ?h_out (ECons ?w_out (ENil)))))
|
||||
(= ?input_shape (ECons ?c_in (ECons ?h_in (ECons ?w_in (ENil)))))
|
||||
(= ?idx_shape (ECons ?c_in (ECons ?h_out (ECons ?w_out (ECons (MNum 1) (ECons ?kernel_h (ECons ?kernel_w (ENil))))))))
|
||||
(= ?matmul_out_shape (ECons ?m (ECons ?c_out (ENil))))
|
||||
|
||||
(= ?h_out (MAdd (MSub ?h_in ?kernel_h) (MNum 1)))
|
||||
(= ?w_out (MAdd (MSub ?w_in ?kernel_w) (MNum 1)))
|
||||
(= ?m (MMul ?h_out ?w_out))
|
||||
(= ?k_dim (MMul ?c_in (MMul ?kernel_h ?kernel_w)))
|
||||
(= ?k_stride (MIter))
|
||||
|
||||
(= ?weight_co_stride (nth_from_end ?weight_stride 1))
|
||||
(= ?weight_inner_stride (nth_from_end ?weight_stride 0))
|
||||
(= (MNum 0) (nth_from_end ?weight_stride 2))
|
||||
|
||||
(= ?bias_add_stride (ECons ?bias_c_stride (ECons (MNum 0) (ECons (MNum 0) (ENil)))))
|
||||
|
||||
(= (F32) (dtype ?input))
|
||||
(= (F32) (dtype ?weight))
|
||||
(= (F32) (dtype ?bias))
|
||||
)
|
||||
(
|
||||
(let ?conv (Op (KernelConv2D
|
||||
?out_shape
|
||||
?input_shape
|
||||
?input_stride
|
||||
?weight_co_stride
|
||||
?weight_inner_stride
|
||||
?bias_c_stride
|
||||
?add_out_stride
|
||||
?kernel_h
|
||||
?kernel_w
|
||||
(MNum 1)
|
||||
(MNum 1)
|
||||
(MNum 1)
|
||||
(MNum 1)
|
||||
(MNum 0)
|
||||
(MNum 0)
|
||||
(F32))
|
||||
(ICons ?input (ICons ?weight (ICons ?bias (INil))))))
|
||||
(union ?add ?conv)
|
||||
(subsume (Op (Add ?out_shape ?bias_add_stride ?sum_add_stride ?add_out_stride) (ICons ?bias (ICons ?sum (INil)))))
|
||||
(set (dtype ?conv) (F32))
|
||||
)
|
||||
:ruleset kernel_specialize
|
||||
:name \"kernel conv2d from bias unfold matmul\"
|
||||
)",
|
||||
),
|
||||
Rule::raw(
|
||||
"(rule
|
||||
(
|
||||
(= ?add (Op (Add ?shape ?as ?bs ?os) ?inputs))
|
||||
(= ?add (Op (KernelConv2D ?out_shape ?input_shape ?input_stride ?wco ?wi ?bc ?out_stride ?kh ?kw ?sh ?sw ?dh ?dw ?ph ?pw ?dt) ?conv_inputs))
|
||||
)
|
||||
((delete (Op (Add ?shape ?as ?bs ?os) ?inputs)))
|
||||
:ruleset cleanup
|
||||
)",
|
||||
),
|
||||
Rule::raw(
|
||||
"(rule
|
||||
(
|
||||
(= ?fe (Op (FusionEnd ?shape ?os ?dt) ?inputs))
|
||||
(= ?fe (Op (KernelConv2D ?out_shape ?input_shape ?input_stride ?wco ?wi ?bc ?out_stride ?kh ?kw ?sh ?sw ?dh ?dw ?ph ?pw ?conv_dt) ?conv_inputs))
|
||||
)
|
||||
((delete (Op (FusionEnd ?shape ?os ?dt) ?inputs)))
|
||||
:ruleset cleanup
|
||||
)",
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
fn cleanup(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn extract<'a>(
|
||||
&'a self,
|
||||
egraph: &'a luminal::egglog_utils::SerializedEGraph,
|
||||
kind_children: &[&'a luminal::egglog_utils::NodeId],
|
||||
input_enodes: Vec<&'a luminal::egglog_utils::NodeId>,
|
||||
list_cache: &mut FxHashMap<&'a luminal::egglog_utils::NodeId, Vec<Expression>>,
|
||||
expr_cache: &mut FxHashMap<&'a luminal::egglog_utils::NodeId, Expression>,
|
||||
) -> (LLIROp, Vec<&'a luminal::egglog_utils::NodeId>) {
|
||||
(
|
||||
LLIROp::new::<dyn KernelOp>(Box::new(Self {
|
||||
out_shape: extract_expr_list(egraph, kind_children[0], list_cache, expr_cache)
|
||||
.unwrap(),
|
||||
input_shape: extract_expr_list(egraph, kind_children[1], list_cache, expr_cache)
|
||||
.unwrap(),
|
||||
input_stride: extract_expr_list(egraph, kind_children[2], list_cache, expr_cache)
|
||||
.unwrap(),
|
||||
weight_co_stride: extract_expr(egraph, kind_children[3], expr_cache).unwrap(),
|
||||
weight_inner_stride: extract_expr(egraph, kind_children[4], expr_cache).unwrap(),
|
||||
bias_c_stride: extract_expr(egraph, kind_children[5], expr_cache).unwrap(),
|
||||
out_stride: extract_expr_list(egraph, kind_children[6], list_cache, expr_cache)
|
||||
.unwrap(),
|
||||
kernel_h: extract_expr(egraph, kind_children[7], expr_cache).unwrap(),
|
||||
kernel_w: extract_expr(egraph, kind_children[8], expr_cache).unwrap(),
|
||||
stride_h: extract_expr(egraph, kind_children[9], expr_cache).unwrap(),
|
||||
stride_w: extract_expr(egraph, kind_children[10], expr_cache).unwrap(),
|
||||
dilation_h: extract_expr(egraph, kind_children[11], expr_cache).unwrap(),
|
||||
dilation_w: extract_expr(egraph, kind_children[12], expr_cache).unwrap(),
|
||||
pad_h: extract_expr(egraph, kind_children[13], expr_cache).unwrap(),
|
||||
pad_w: extract_expr(egraph, kind_children[14], expr_cache).unwrap(),
|
||||
dtype: extract_dtype(egraph, kind_children[15]),
|
||||
}) as Box<dyn KernelOp>),
|
||||
input_enodes,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl KernelOp for KernelConv2D {
|
||||
fn compile(
|
||||
&self,
|
||||
stream: &Arc<CudaStream>,
|
||||
compile_cache: &mut FxHashMap<String, (Arc<CudaModule>, CudaFunction)>,
|
||||
) -> (
|
||||
CudaFunction,
|
||||
Arc<CudaModule>,
|
||||
String,
|
||||
(Expression, Expression, Expression),
|
||||
(Expression, Expression, Expression),
|
||||
Expression,
|
||||
FxHashMap<char, CudaSlice<u8>>,
|
||||
) {
|
||||
assert_eq!(self.dtype, DType::F32, "KernelConv2D currently emits F32");
|
||||
|
||||
let vars: FxHashSet<char> = self
|
||||
.out_shape
|
||||
.iter()
|
||||
.chain(&self.input_shape)
|
||||
.chain(&self.input_stride)
|
||||
.chain(&self.out_stride)
|
||||
.flat_map(|e| e.dyn_vars())
|
||||
.chain(self.weight_co_stride.dyn_vars())
|
||||
.chain(self.weight_inner_stride.dyn_vars())
|
||||
.chain(self.bias_c_stride.dyn_vars())
|
||||
.chain(self.kernel_h.dyn_vars())
|
||||
.chain(self.kernel_w.dyn_vars())
|
||||
.chain(self.stride_h.dyn_vars())
|
||||
.chain(self.stride_w.dyn_vars())
|
||||
.chain(self.dilation_h.dyn_vars())
|
||||
.chain(self.dilation_w.dyn_vars())
|
||||
.chain(self.pad_h.dyn_vars())
|
||||
.chain(self.pad_w.dyn_vars())
|
||||
.collect();
|
||||
|
||||
let (dyn_defines, _sorted_dims) = generate_dyn_dims_defines(&vars);
|
||||
let dyn_dims_param = if vars.is_empty() {
|
||||
""
|
||||
} else {
|
||||
", const int* dyn_dims"
|
||||
};
|
||||
|
||||
let c_out = self.out_shape[0].to_kernel();
|
||||
let h_out = self.out_shape[1].to_kernel();
|
||||
let w_out = self.out_shape[2].to_kernel();
|
||||
let c_in = self.input_shape[0].to_kernel();
|
||||
let h_in = self.input_shape[1].to_kernel();
|
||||
let w_in = self.input_shape[2].to_kernel();
|
||||
let weight_co_stride = self
|
||||
.weight_co_stride
|
||||
.substitute('z', Expression::from(1))
|
||||
.simplify()
|
||||
.to_kernel();
|
||||
let weight_inner_stride = self
|
||||
.weight_inner_stride
|
||||
.substitute('z', Expression::from(1))
|
||||
.simplify()
|
||||
.to_kernel();
|
||||
let bias_c_stride = self
|
||||
.bias_c_stride
|
||||
.substitute('z', Expression::from(1))
|
||||
.simplify()
|
||||
.to_kernel();
|
||||
let kh = self.kernel_h.to_kernel();
|
||||
let kw = self.kernel_w.to_kernel();
|
||||
let stride_h = self.stride_h.to_kernel();
|
||||
let stride_w = self.stride_w.to_kernel();
|
||||
let dilation_h = self.dilation_h.to_kernel();
|
||||
let dilation_w = self.dilation_w.to_kernel();
|
||||
let pad_h = self.pad_h.to_kernel();
|
||||
let pad_w = self.pad_w.to_kernel();
|
||||
let out_idx = flatten_strides(&self.out_shape, &self.out_stride).to_kernel();
|
||||
let input_idx = flatten_strides(&self.input_shape, &self.input_stride)
|
||||
.to_kernel()
|
||||
.replace("const_z", "input_linear");
|
||||
let n_outputs: Expression = self.out_shape.iter().copied().product();
|
||||
|
||||
let kernel = format!(
|
||||
"
|
||||
{dyn_defines}
|
||||
extern \"C\" {{
|
||||
__global__ void generic_conv2d_bias(
|
||||
float* __restrict__ out,
|
||||
const float* __restrict__ input,
|
||||
const float* __restrict__ weight,
|
||||
const float* __restrict__ bias{dyn_dims_param}
|
||||
) {{
|
||||
long long const_z = (long long)blockIdx.x * blockDim.x + threadIdx.x;
|
||||
const long long total = {total};
|
||||
if (const_z >= total) return;
|
||||
|
||||
const long long COUT = {c_out};
|
||||
const long long HOUT = {h_out};
|
||||
const long long WOUT = {w_out};
|
||||
const long long CIN = {c_in};
|
||||
const long long HIN = {h_in};
|
||||
const long long WIN = {w_in};
|
||||
const long long KH = {kh};
|
||||
const long long KW = {kw};
|
||||
const long long SH = {stride_h};
|
||||
const long long SW = {stride_w};
|
||||
const long long DH = {dilation_h};
|
||||
const long long DW = {dilation_w};
|
||||
const long long PH = {pad_h};
|
||||
const long long PW = {pad_w};
|
||||
const long long W_CO_STRIDE = {weight_co_stride};
|
||||
const long long W_INNER_STRIDE = {weight_inner_stride};
|
||||
const long long BIAS_C_STRIDE = {bias_c_stride};
|
||||
|
||||
long long co = const_z / (HOUT * WOUT);
|
||||
long long rem = const_z - co * HOUT * WOUT;
|
||||
long long oh = rem / WOUT;
|
||||
long long ow = rem - oh * WOUT;
|
||||
|
||||
float acc = bias[co * BIAS_C_STRIDE];
|
||||
for (long long ci = 0; ci < CIN; ++ci) {{
|
||||
for (long long r = 0; r < KH; ++r) {{
|
||||
long long ih = oh * SH + r * DH - PH;
|
||||
if (ih < 0 || ih >= HIN) continue;
|
||||
for (long long s = 0; s < KW; ++s) {{
|
||||
long long iw = ow * SW + s * DW - PW;
|
||||
if (iw < 0 || iw >= WIN) continue;
|
||||
long long input_linear = (ci * HIN + ih) * WIN + iw;
|
||||
long long input_idx = {input_idx};
|
||||
long long inner = (ci * KH + r) * KW + s;
|
||||
long long weight_idx = co * W_CO_STRIDE + inner * W_INNER_STRIDE;
|
||||
acc += input[input_idx] * weight[weight_idx];
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
out[{out_idx}] = acc;
|
||||
}}
|
||||
}}",
|
||||
total = n_outputs.to_kernel(),
|
||||
);
|
||||
|
||||
let (module, func) = if let Some((module, func)) = compile_cache.get(&kernel) {
|
||||
(module.clone(), func.clone())
|
||||
} else {
|
||||
let ptx = compile_module_image_for_current_device(stream.context(), &kernel).unwrap();
|
||||
let module = stream.context().load_module(ptx).unwrap();
|
||||
let func = module.load_function("generic_conv2d_bias").unwrap();
|
||||
compile_cache.insert(kernel.clone(), (module.clone(), func.clone()));
|
||||
(module, func)
|
||||
};
|
||||
|
||||
(
|
||||
func,
|
||||
module,
|
||||
kernel,
|
||||
(n_outputs.ceil_div(256), 1.into(), 1.into()),
|
||||
(n_outputs.min(256), 1.into(), 1.into()),
|
||||
0.into(),
|
||||
FxHashMap::default(),
|
||||
)
|
||||
}
|
||||
|
||||
fn output_size(&self) -> Expression {
|
||||
self.out_shape.iter().copied().product()
|
||||
}
|
||||
|
||||
fn all_dyn_vars(&self) -> FxHashSet<char> {
|
||||
self.out_shape
|
||||
.iter()
|
||||
.chain(&self.input_shape)
|
||||
.chain(&self.input_stride)
|
||||
.chain(&self.out_stride)
|
||||
.flat_map(|e| e.dyn_vars())
|
||||
.chain(self.weight_co_stride.dyn_vars())
|
||||
.chain(self.weight_inner_stride.dyn_vars())
|
||||
.chain(self.bias_c_stride.dyn_vars())
|
||||
.chain(self.kernel_h.dyn_vars())
|
||||
.chain(self.kernel_w.dyn_vars())
|
||||
.chain(self.stride_h.dyn_vars())
|
||||
.chain(self.stride_w.dyn_vars())
|
||||
.chain(self.dilation_h.dyn_vars())
|
||||
.chain(self.dilation_w.dyn_vars())
|
||||
.chain(self.pad_h.dyn_vars())
|
||||
.chain(self.pad_w.dyn_vars())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn output_bytes(&self) -> Expression {
|
||||
self.output_size() * 4
|
||||
}
|
||||
|
||||
fn bytes_loaded(&self) -> Expression {
|
||||
let c_in = self.input_shape[0];
|
||||
self.output_size() * self.kernel_h * self.kernel_w * c_in * 2 * 4 + self.output_size() * 4
|
||||
}
|
||||
|
||||
fn bytes_stored(&self) -> Expression {
|
||||
self.output_size() * 4
|
||||
}
|
||||
|
||||
fn flops(&self) -> Expression {
|
||||
let c_in = self.input_shape[0];
|
||||
self.output_size() * self.kernel_h * self.kernel_w * c_in * 2
|
||||
}
|
||||
|
||||
fn output_dtype(&self) -> DType {
|
||||
self.dtype
|
||||
}
|
||||
|
||||
fn kernel_name(&self) -> &'static str {
|
||||
"GenericConv2D"
|
||||
}
|
||||
}
|
||||
@@ -498,8 +498,8 @@ mod tests {
|
||||
let data_b = random_f32_vec(size, 43, -0.5, 0.5);
|
||||
rt.set_data(a, data_a.clone());
|
||||
rt.set_data(b, data_b.clone());
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
rt = cx.search(rt, 5);
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
rt = cx.search(rt, CompileOptions::new(5));
|
||||
rt.execute(&cx.dyn_map);
|
||||
let result1 = rt.get_f32(c);
|
||||
rt.execute(&cx.dyn_map);
|
||||
@@ -530,8 +530,8 @@ mod tests {
|
||||
let data_b = random_f32_vec(size, 43, -0.5, 0.5);
|
||||
rt.set_data(a, data_a.clone());
|
||||
rt.set_data(b, data_b.clone());
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
rt = cx.search(rt, 5);
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
rt = cx.search(rt, CompileOptions::new(5));
|
||||
let mut results = Vec::new();
|
||||
for _ in 0..5 {
|
||||
rt.execute(&cx.dyn_map);
|
||||
@@ -568,8 +568,8 @@ mod tests {
|
||||
rt.set_data(a, data_a.clone());
|
||||
rt.set_data(b, data_b.clone());
|
||||
cx.set_dim('s', size);
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
rt = cx.search(rt, 5);
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
rt = cx.search(rt, CompileOptions::new(5));
|
||||
rt.execute(&cx.dyn_map);
|
||||
let expected: Vec<f32> = data_a
|
||||
.iter()
|
||||
@@ -610,8 +610,8 @@ mod tests {
|
||||
let data_b = random_f32_vec(size, 43, -0.5, 0.5);
|
||||
rt.set_data(a, data_a.clone());
|
||||
rt.set_data(b, data_b.clone());
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
rt = cx.search(rt, 5);
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
rt = cx.search(rt, CompileOptions::new(5));
|
||||
rt.execute(&cx.dyn_map);
|
||||
let expected: Vec<f32> = data_a.iter().zip(&data_b).map(|(a, b)| a + b).collect();
|
||||
let eps = dtype_epsilon(luminal::dtype::DType::F32);
|
||||
@@ -641,8 +641,8 @@ mod tests {
|
||||
let data_b = random_f32_vec(size, 43, -0.5, 0.5);
|
||||
rt.set_data(a, data_a.clone());
|
||||
rt.set_data(b, data_b.clone());
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
rt = cx.search(rt, 5);
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
rt = cx.search(rt, CompileOptions::new(5));
|
||||
for _ in 0..10 {
|
||||
rt.execute(&cx.dyn_map);
|
||||
}
|
||||
@@ -674,8 +674,8 @@ mod tests {
|
||||
let data_b = random_f32_vec(initial_size, 43, -0.5, 0.5);
|
||||
rt.set_data(a, data_a.clone());
|
||||
rt.set_data(b, data_b.clone());
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
rt = cx.search(rt, 5);
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
rt = cx.search(rt, CompileOptions::new(5));
|
||||
|
||||
// Initial execution
|
||||
rt.execute(&cx.dyn_map);
|
||||
|
||||
393
crates/luminal_cuda_lite/src/kernel/fusion/elementwise.rs
Normal file
393
crates/luminal_cuda_lite/src/kernel/fusion/elementwise.rs
Normal file
@@ -0,0 +1,393 @@
|
||||
// =========================================================================
|
||||
// Generic CUDA elementwise ops used inside FusionStart/FusionEnd regions.
|
||||
//
|
||||
// CUDA elementwise execution is represented as a FusionEnd-rooted region even
|
||||
// for a single op. These ops are therefore region-internal only; standalone
|
||||
// compilation is intentionally unsupported.
|
||||
// =========================================================================
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use cudarc::driver::{CudaFunction, CudaModule, CudaSlice, CudaStream};
|
||||
use luminal::{
|
||||
egglog_utils::{
|
||||
api::{Rule, SortDef, sort},
|
||||
base::{DTYPE, ELIST, OP_KIND, STRING},
|
||||
extract_dtype, extract_expr_list,
|
||||
},
|
||||
op::*,
|
||||
prelude::*,
|
||||
};
|
||||
|
||||
use crate::kernel::KernelOp;
|
||||
|
||||
pub type Ops = (CudaUnaryElementwise, CudaBinaryElementwise);
|
||||
|
||||
type CompileOut = (
|
||||
CudaFunction,
|
||||
Arc<CudaModule>,
|
||||
String,
|
||||
(Expression, Expression, Expression),
|
||||
(Expression, Expression, Expression),
|
||||
Expression,
|
||||
FxHashMap<char, CudaSlice<u8>>,
|
||||
);
|
||||
|
||||
fn extract_string_label(egraph: &SerializedEGraph, node: &ENodeId) -> String {
|
||||
egraph.enodes[node].0.trim_matches('"').to_string()
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone)]
|
||||
pub struct CudaUnaryElementwise {
|
||||
pub(crate) op: String,
|
||||
pub(crate) shape: Vec<Expression>,
|
||||
pub(crate) in_strides: Vec<Expression>,
|
||||
pub(crate) out_strides: Vec<Expression>,
|
||||
pub(crate) dtype: DType,
|
||||
}
|
||||
|
||||
impl EgglogOp for CudaUnaryElementwise {
|
||||
fn sort(&self) -> SortDef {
|
||||
sort(
|
||||
OP_KIND,
|
||||
"CudaUnaryElementwise",
|
||||
&[
|
||||
("op", STRING),
|
||||
("shape", ELIST),
|
||||
("strides", ELIST),
|
||||
("out_strides", ELIST),
|
||||
("dtype", DTYPE),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
fn n_inputs(&self) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
fn rewrites(&self) -> Vec<Rule> {
|
||||
let mut rules = Vec::new();
|
||||
for (hlir, opcode) in [
|
||||
("Sin", "Sin"),
|
||||
("Sqrt", "Sqrt"),
|
||||
("Exp2", "Exp2"),
|
||||
("Log2", "Log2"),
|
||||
("Recip", "Recip"),
|
||||
] {
|
||||
rules.push(Rule::raw(format!(
|
||||
"(rule (
|
||||
(= ?u (Op ({hlir} ?shape ?s ?out_s) (ICons ?x (INil))))
|
||||
(= ?dt (dtype ?u))
|
||||
) (
|
||||
(let ?fs (Op (FusionStart ?shape ?s ?dt) (ICons ?x (INil))))
|
||||
(let ?elem (Op (CudaUnaryElementwise \"{opcode}\" ?shape ?s ?out_s ?dt)
|
||||
(ICons ?fs (INil))))
|
||||
(let ?fe (Op (FusionEnd ?shape ?out_s ?dt) (ICons ?elem (INil))))
|
||||
(union ?u ?fe)
|
||||
(set (dtype ?fe) ?dt)
|
||||
) :ruleset kernel_lower :name \"cuda-elem-singleton-{hlir}\")"
|
||||
)));
|
||||
}
|
||||
|
||||
rules.push(Rule::raw(
|
||||
"(rule (
|
||||
(= ?sqrt (Op (Sqrt ?shape ?x_stride ?sqrt_stride) (ICons ?x (INil))))
|
||||
(= ?recip (Op (Recip ?shape ?sqrt_stride ?out_stride) (ICons ?sqrt (INil))))
|
||||
(= ?dt (dtype ?recip))
|
||||
) (
|
||||
(let ?fs (Op (FusionStart ?shape ?x_stride ?dt) (ICons ?x (INil))))
|
||||
(let ?elem (Op (CudaUnaryElementwise \"Rsqrt\" ?shape ?x_stride ?out_stride ?dt)
|
||||
(ICons ?fs (INil))))
|
||||
(let ?fe (Op (FusionEnd ?shape ?out_stride ?dt) (ICons ?elem (INil))))
|
||||
(union ?recip ?fe)
|
||||
(set (dtype ?fe) ?dt)
|
||||
) :ruleset kernel_lower :name \"cuda-elem-rsqrt-from-sqrt-recip\")",
|
||||
));
|
||||
|
||||
rules.push(Rule::raw(
|
||||
"(rule
|
||||
(
|
||||
(= ?mul (Op (Mul ?shape ?x_stride ?const_stride ?inter_stride) (ICons ?x (ICons ?exp_const (INil)))))
|
||||
(= ?exp2 (Op (Exp2 ?shape ?inter_stride ?out_stride) (ICons ?mul (INil))))
|
||||
(= ?dt (dtype ?x))
|
||||
(= ?cv (Op (Constant ?val) (INil)))
|
||||
(= ?exp_const ?cv)
|
||||
(> ?val 1.44)
|
||||
(< ?val 1.45)
|
||||
)
|
||||
(
|
||||
(let ?fs (Op (FusionStart ?shape ?x_stride ?dt) (ICons ?x (INil))))
|
||||
(let ?elem (Op (CudaUnaryElementwise \"Exp\" ?shape ?x_stride ?out_stride ?dt)
|
||||
(ICons ?fs (INil))))
|
||||
(let ?fe (Op (FusionEnd ?shape ?out_stride ?dt) (ICons ?elem (INil))))
|
||||
(union ?exp2 ?fe)
|
||||
(set (dtype ?fe) ?dt)
|
||||
)
|
||||
:ruleset direct_kernel
|
||||
:name \"direct-exp-region\"
|
||||
)",
|
||||
));
|
||||
|
||||
rules.push(Rule::raw(
|
||||
"(datatype*
|
||||
(CudaSigmoidScaledState
|
||||
(MkCudaSigmoidScaledState IR EList EList DType)
|
||||
)
|
||||
)
|
||||
(function cuda_sigmoid_scaled (IR) CudaSigmoidScaledState :merge new)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?neg1 (Op (Constant ?nv) (INil)))
|
||||
(< ?nv -0.99)
|
||||
(> ?nv -1.01)
|
||||
(= ?neg_x (Op (Mul ?shape ?x_stride ?neg_stride ?neg_out_stride) (ICons ?x (ICons ?neg1 (INil)))))
|
||||
(= ?log2e (Op (Constant ?lv) (INil)))
|
||||
(> ?lv 1.44)
|
||||
(< ?lv 1.45)
|
||||
(= ?scaled (Op (Mul ?shape ?neg_out_stride ?log2e_stride ?scaled_stride) (ICons ?neg_x (ICons ?log2e (INil)))))
|
||||
(= ?dt (dtype ?x))
|
||||
)
|
||||
(
|
||||
(set (cuda_sigmoid_scaled ?scaled)
|
||||
(MkCudaSigmoidScaledState ?x ?shape ?x_stride ?dt))
|
||||
)
|
||||
:ruleset direct_kernel
|
||||
:name \"direct-sigmoid-scaled-region-marker\"
|
||||
)
|
||||
|
||||
(rule
|
||||
(
|
||||
(= ?scaled_state (cuda_sigmoid_scaled ?scaled))
|
||||
(= ?scaled_state (MkCudaSigmoidScaledState ?x ?shape ?x_stride ?dt))
|
||||
(= ?exp2 (Op (Exp2 ?shape ?scaled_stride ?exp_stride) (ICons ?scaled (INil))))
|
||||
(= ?one (Op (Constant ?ov) (INil)))
|
||||
(> ?ov 0.99)
|
||||
(< ?ov 1.01)
|
||||
(= ?plus_one (Op (Add ?shape ?exp_stride ?one_stride ?add_stride) (ICons ?exp2 (ICons ?one (INil)))))
|
||||
(= ?sig_out (Op (Recip ?shape ?add_stride ?out_stride) (ICons ?plus_one (INil))))
|
||||
)
|
||||
(
|
||||
(let ?fs (Op (FusionStart ?shape ?x_stride ?dt) (ICons ?x (INil))))
|
||||
(let ?elem (Op (CudaUnaryElementwise \"Sigmoid\" ?shape ?x_stride ?out_stride ?dt)
|
||||
(ICons ?fs (INil))))
|
||||
(let ?fe (Op (FusionEnd ?shape ?out_stride ?dt) (ICons ?elem (INil))))
|
||||
(union ?sig_out ?fe)
|
||||
(set (dtype ?fe) ?dt)
|
||||
)
|
||||
:ruleset direct_kernel
|
||||
:name \"direct-sigmoid-region\"
|
||||
)",
|
||||
));
|
||||
|
||||
rules
|
||||
}
|
||||
|
||||
fn cleanup(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn extract<'a>(
|
||||
&'a self,
|
||||
egraph: &'a SerializedEGraph,
|
||||
kind_children: &[&'a ENodeId],
|
||||
input_enodes: Vec<&'a ENodeId>,
|
||||
list_cache: &mut FxHashMap<&'a ENodeId, Vec<Expression>>,
|
||||
expr_cache: &mut FxHashMap<&'a ENodeId, Expression>,
|
||||
) -> (LLIROp, Vec<&'a ENodeId>) {
|
||||
(
|
||||
LLIROp::new::<dyn KernelOp>(Box::new(Self {
|
||||
op: extract_string_label(egraph, kind_children[0]),
|
||||
shape: extract_expr_list(egraph, kind_children[1], list_cache, expr_cache).unwrap(),
|
||||
in_strides: extract_expr_list(egraph, kind_children[2], list_cache, expr_cache)
|
||||
.unwrap(),
|
||||
out_strides: extract_expr_list(egraph, kind_children[3], list_cache, expr_cache)
|
||||
.unwrap(),
|
||||
dtype: extract_dtype(egraph, kind_children[4]),
|
||||
})),
|
||||
input_enodes,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl KernelOp for CudaUnaryElementwise {
|
||||
fn compile(
|
||||
&self,
|
||||
_stream: &Arc<CudaStream>,
|
||||
_compile_cache: &mut FxHashMap<String, (Arc<CudaModule>, CudaFunction)>,
|
||||
) -> CompileOut {
|
||||
unreachable!("CudaUnaryElementwise must be compiled through fusion region codegen")
|
||||
}
|
||||
|
||||
fn output_size(&self) -> Expression {
|
||||
self.shape.iter().copied().product()
|
||||
}
|
||||
|
||||
fn output_bytes(&self) -> Expression {
|
||||
(self.output_size() * self.dtype.bits()).ceil_div(8)
|
||||
}
|
||||
|
||||
fn bytes_loaded(&self) -> Expression {
|
||||
self.output_bytes()
|
||||
}
|
||||
|
||||
fn bytes_stored(&self) -> Expression {
|
||||
self.output_bytes()
|
||||
}
|
||||
|
||||
fn flops(&self) -> Expression {
|
||||
self.output_size()
|
||||
}
|
||||
|
||||
fn output_dtype(&self) -> DType {
|
||||
self.dtype
|
||||
}
|
||||
|
||||
fn kernel_name(&self) -> &'static str {
|
||||
"CudaUnaryElementwise"
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone)]
|
||||
pub struct CudaBinaryElementwise {
|
||||
pub(crate) op: String,
|
||||
pub(crate) out_shape: Vec<Expression>,
|
||||
pub(crate) a_stride: Vec<Expression>,
|
||||
pub(crate) b_stride: Vec<Expression>,
|
||||
pub(crate) out_stride: Vec<Expression>,
|
||||
pub(crate) dtype: DType,
|
||||
}
|
||||
|
||||
impl EgglogOp for CudaBinaryElementwise {
|
||||
fn sort(&self) -> SortDef {
|
||||
sort(
|
||||
OP_KIND,
|
||||
"CudaBinaryElementwise",
|
||||
&[
|
||||
("op", STRING),
|
||||
("shape", ELIST),
|
||||
("a_strides", ELIST),
|
||||
("b_strides", ELIST),
|
||||
("out_strides", ELIST),
|
||||
("dtype", DTYPE),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
fn n_inputs(&self) -> usize {
|
||||
2
|
||||
}
|
||||
|
||||
fn rewrites(&self) -> Vec<Rule> {
|
||||
vec![
|
||||
Rule::raw(
|
||||
"(rule (
|
||||
(= ?bin (Op (Add ?shape ?a_s ?b_s ?out_s) (ICons ?a (ICons ?b (INil)))))
|
||||
(= ?dt (dtype ?bin))
|
||||
) (
|
||||
(let ?fs_a (Op (FusionStart ?shape ?a_s ?dt) (ICons ?a (INil))))
|
||||
(let ?fs_b (Op (FusionStart ?shape ?b_s ?dt) (ICons ?b (INil))))
|
||||
(let ?elem (Op (CudaBinaryElementwise \"Add\" ?shape ?a_s ?b_s ?out_s ?dt)
|
||||
(ICons ?fs_a (ICons ?fs_b (INil)))))
|
||||
(let ?fe (Op (FusionEnd ?shape ?out_s ?dt) (ICons ?elem (INil))))
|
||||
(union ?bin ?fe)
|
||||
(set (dtype ?fe) ?dt)
|
||||
) :ruleset kernel_lower :name \"cuda-elem-singleton-Add\")",
|
||||
),
|
||||
Rule::raw(
|
||||
"(rule (
|
||||
(= ?bin (Op (Mul ?shape ?a_s ?b_s ?out_s) (ICons ?a (ICons ?b (INil)))))
|
||||
(= ?dt (dtype ?a))
|
||||
) (
|
||||
(let ?fs_a (Op (FusionStart ?shape ?a_s ?dt) (ICons ?a (INil))))
|
||||
(let ?fs_b (Op (FusionStart ?shape ?b_s ?dt) (ICons ?b (INil))))
|
||||
(let ?elem (Op (CudaBinaryElementwise \"Mul\" ?shape ?a_s ?b_s ?out_s ?dt)
|
||||
(ICons ?fs_a (ICons ?fs_b (INil)))))
|
||||
(let ?fe (Op (FusionEnd ?shape ?out_s ?dt) (ICons ?elem (INil))))
|
||||
(union ?bin ?fe)
|
||||
(set (dtype ?fe) ?dt)
|
||||
) :ruleset kernel_lower :name \"cuda-elem-singleton-Mul\")",
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
fn cleanup(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn extract<'a>(
|
||||
&'a self,
|
||||
egraph: &'a SerializedEGraph,
|
||||
kind_children: &[&'a ENodeId],
|
||||
input_enodes: Vec<&'a ENodeId>,
|
||||
list_cache: &mut FxHashMap<&'a ENodeId, Vec<Expression>>,
|
||||
expr_cache: &mut FxHashMap<&'a ENodeId, Expression>,
|
||||
) -> (LLIROp, Vec<&'a ENodeId>) {
|
||||
let mut out_shape =
|
||||
extract_expr_list(egraph, kind_children[1], list_cache, expr_cache).unwrap();
|
||||
let mut a_stride =
|
||||
extract_expr_list(egraph, kind_children[2], list_cache, expr_cache).unwrap();
|
||||
let mut b_stride =
|
||||
extract_expr_list(egraph, kind_children[3], list_cache, expr_cache).unwrap();
|
||||
let mut out_stride =
|
||||
extract_expr_list(egraph, kind_children[4], list_cache, expr_cache).unwrap();
|
||||
let n = out_shape
|
||||
.len()
|
||||
.min(a_stride.len())
|
||||
.min(b_stride.len())
|
||||
.min(out_stride.len());
|
||||
out_shape.truncate(n);
|
||||
a_stride.truncate(n);
|
||||
b_stride.truncate(n);
|
||||
out_stride.truncate(n);
|
||||
(
|
||||
LLIROp::new::<dyn KernelOp>(Box::new(Self {
|
||||
op: extract_string_label(egraph, kind_children[0]),
|
||||
out_shape,
|
||||
a_stride,
|
||||
b_stride,
|
||||
out_stride,
|
||||
dtype: extract_dtype(egraph, kind_children[5]),
|
||||
})),
|
||||
input_enodes,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl KernelOp for CudaBinaryElementwise {
|
||||
fn compile(
|
||||
&self,
|
||||
_stream: &Arc<CudaStream>,
|
||||
_compile_cache: &mut FxHashMap<String, (Arc<CudaModule>, CudaFunction)>,
|
||||
) -> CompileOut {
|
||||
unreachable!("CudaBinaryElementwise must be compiled through fusion region codegen")
|
||||
}
|
||||
|
||||
fn output_size(&self) -> Expression {
|
||||
self.out_shape.iter().copied().product()
|
||||
}
|
||||
|
||||
fn output_bytes(&self) -> Expression {
|
||||
(self.output_size() * self.dtype.bits()).ceil_div(8)
|
||||
}
|
||||
|
||||
fn bytes_loaded(&self) -> Expression {
|
||||
self.output_bytes() * 2
|
||||
}
|
||||
|
||||
fn bytes_stored(&self) -> Expression {
|
||||
self.output_bytes()
|
||||
}
|
||||
|
||||
fn flops(&self) -> Expression {
|
||||
self.output_size()
|
||||
}
|
||||
|
||||
fn output_dtype(&self) -> DType {
|
||||
self.dtype
|
||||
}
|
||||
|
||||
fn kernel_name(&self) -> &'static str {
|
||||
"CudaBinaryElementwise"
|
||||
}
|
||||
}
|
||||
@@ -1,451 +0,0 @@
|
||||
// =========================================================================
|
||||
// Fused elementwise op variants used inside FusionStart/FusionEnd regions.
|
||||
//
|
||||
// Each `FusedX` struct mirrors its un-fused `KernelX` sibling field-for-field
|
||||
// and serves a single purpose: give the egglog rules a distinct sort to
|
||||
// rewrite into so a pair-fuse rule's RHS can never re-match its own LHS
|
||||
// pattern. Cascade prevention by typing.
|
||||
//
|
||||
// `compile()` is a *fallback* path. The fast path collapses each FE-rooted
|
||||
// region into one CUDA kernel inside `region_codegen` and FusedX/FS/FE
|
||||
// never reach kernel_to_host's compile loop. But extraction can produce
|
||||
// LLIR shapes the detector doesn't sweep into a region, so each FusedX's
|
||||
// standalone `compile()` falls back to emitting the same kernel its
|
||||
// un-fused KernelX sibling would — correct, just one launch per op.
|
||||
// =========================================================================
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use cudarc::driver::{CudaFunction, CudaModule, CudaSlice, CudaStream};
|
||||
use luminal::{
|
||||
egglog_utils::{
|
||||
api::{Rule, SortDef, sort},
|
||||
base::{DTYPE, ELIST, OP_KIND},
|
||||
extract_dtype, extract_expr_list,
|
||||
},
|
||||
op::*,
|
||||
prelude::*,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
compile_module_image_for_current_device, cuda_dtype,
|
||||
kernel::KernelOp,
|
||||
kernel::hlir::{dtype_includes, generate_dyn_dims_defines},
|
||||
};
|
||||
|
||||
pub type Ops = (
|
||||
FusedSin,
|
||||
FusedSqrt,
|
||||
FusedExp,
|
||||
FusedExp2,
|
||||
FusedLog2,
|
||||
FusedRecip,
|
||||
FusedAdd,
|
||||
FusedMul,
|
||||
);
|
||||
|
||||
// Standard `compile()` return tuple (matches the trait signature).
|
||||
type CompileOut = (
|
||||
CudaFunction,
|
||||
Arc<CudaModule>,
|
||||
String,
|
||||
(Expression, Expression, Expression),
|
||||
(Expression, Expression, Expression),
|
||||
Expression,
|
||||
FxHashMap<char, CudaSlice<u8>>,
|
||||
);
|
||||
|
||||
// =========================================================================
|
||||
// Fallback kernel templates — used when a FusedX op reaches
|
||||
// `kernel_to_host` standalone (region detection missed it). Same CUDA as
|
||||
// the matching un-fused KernelX would emit, parameterised by the per-op
|
||||
// body expression. The fast path goes through `region_codegen`.
|
||||
// =========================================================================
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn compile_unary_fallback(
|
||||
stream: &Arc<CudaStream>,
|
||||
compile_cache: &mut FxHashMap<String, (Arc<CudaModule>, CudaFunction)>,
|
||||
kernel_name: &str,
|
||||
body_expr: &str, // CUDA expression on `in[{in_idx}]`, e.g. "sinf(in[{in_idx}])"
|
||||
shape: &[Expression],
|
||||
in_strides: &[Expression],
|
||||
out_strides: &[Expression],
|
||||
dtype: DType,
|
||||
) -> CompileOut {
|
||||
let vars = shape
|
||||
.iter()
|
||||
.flat_map(|e| e.dyn_vars())
|
||||
.chain(in_strides.iter().flat_map(|e| e.dyn_vars()))
|
||||
.chain(out_strides.iter().flat_map(|e| e.dyn_vars()))
|
||||
.collect::<FxHashSet<_>>();
|
||||
let cuda_ty = cuda_dtype(dtype);
|
||||
let includes = dtype_includes(&[dtype]);
|
||||
let (dyn_defines, _sorted_dims) = generate_dyn_dims_defines(&vars);
|
||||
let dyn_dims_param = if vars.is_empty() {
|
||||
""
|
||||
} else {
|
||||
", const int* dyn_dims"
|
||||
};
|
||||
let n_elements = shape.iter().copied().product::<Expression>().to_kernel();
|
||||
let out_idx = flatten_strides(shape, out_strides).to_kernel();
|
||||
let in_idx = flatten_strides(shape, in_strides).to_kernel();
|
||||
let body = body_expr.replace("{in_idx}", &in_idx);
|
||||
let kernel = format!(
|
||||
"{includes}\n{dyn_defines}\nextern \"C\" {{\n\
|
||||
\x20 __global__ void {kernel_name}({cuda_ty} *out, const {cuda_ty} *in{dyn_dims_param}) {{\n\
|
||||
\x20 long long const_z = (long long)blockIdx.x * blockDim.x + threadIdx.x;\n\
|
||||
\x20 if (const_z >= {n_elements}) return;\n\
|
||||
\x20 out[{out_idx}] = {body};\n\
|
||||
\x20 }}\n}}"
|
||||
);
|
||||
let (module, func) = if let Some((m, f)) = compile_cache.get(&kernel) {
|
||||
(m.clone(), f.clone())
|
||||
} else {
|
||||
let ptx = compile_module_image_for_current_device(stream.context(), &kernel).unwrap();
|
||||
let module = stream.context().load_module(ptx).unwrap();
|
||||
let func = module.load_function(kernel_name).unwrap();
|
||||
compile_cache.insert(kernel.clone(), (module.clone(), func.clone()));
|
||||
(module, func)
|
||||
};
|
||||
let out_size = shape.iter().copied().product::<Expression>();
|
||||
(
|
||||
func,
|
||||
module,
|
||||
kernel,
|
||||
(out_size.ceil_div(256), 1.into(), 1.into()),
|
||||
(out_size.min(256), 1.into(), 1.into()),
|
||||
0.into(),
|
||||
FxHashMap::default(),
|
||||
)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn compile_binary_fallback(
|
||||
stream: &Arc<CudaStream>,
|
||||
compile_cache: &mut FxHashMap<String, (Arc<CudaModule>, CudaFunction)>,
|
||||
kernel_name: &str,
|
||||
op_str: &str, // CUDA infix operator, e.g. "+", "*"
|
||||
out_shape: &[Expression],
|
||||
a_stride: &[Expression],
|
||||
b_stride: &[Expression],
|
||||
out_stride: &[Expression],
|
||||
dtype: DType,
|
||||
) -> CompileOut {
|
||||
let vars = out_shape
|
||||
.iter()
|
||||
.flat_map(|e| e.dyn_vars())
|
||||
.chain(a_stride.iter().flat_map(|e| e.dyn_vars()))
|
||||
.chain(b_stride.iter().flat_map(|e| e.dyn_vars()))
|
||||
.chain(out_stride.iter().flat_map(|e| e.dyn_vars()))
|
||||
.collect::<FxHashSet<_>>();
|
||||
let cuda_ty = cuda_dtype(dtype);
|
||||
let includes = dtype_includes(&[dtype, dtype]);
|
||||
let (dyn_defines, _sorted_dims) = generate_dyn_dims_defines(&vars);
|
||||
let dyn_dims_param = if vars.is_empty() {
|
||||
""
|
||||
} else {
|
||||
", const int* dyn_dims"
|
||||
};
|
||||
let n_elements = out_shape
|
||||
.iter()
|
||||
.copied()
|
||||
.product::<Expression>()
|
||||
.to_kernel();
|
||||
let out_idx = flatten_strides(out_shape, out_stride).to_kernel();
|
||||
let a_idx = flatten_strides(out_shape, a_stride).to_kernel();
|
||||
let b_idx = flatten_strides(out_shape, b_stride).to_kernel();
|
||||
let kernel = format!(
|
||||
"{includes}\n{dyn_defines}\nextern \"C\" {{\n\
|
||||
\x20 __global__ void {kernel_name}({cuda_ty} *C, const {cuda_ty} *A, const {cuda_ty} *B{dyn_dims_param}) {{\n\
|
||||
\x20 long long const_z = (long long)blockIdx.x * blockDim.x + threadIdx.x;\n\
|
||||
\x20 if (const_z >= {n_elements}) return;\n\
|
||||
\x20 C[{out_idx}] = A[{a_idx}] {op_str} B[{b_idx}];\n\
|
||||
\x20 }}\n}}"
|
||||
);
|
||||
let (module, func) = if let Some((m, f)) = compile_cache.get(&kernel) {
|
||||
(m.clone(), f.clone())
|
||||
} else {
|
||||
let ptx = compile_module_image_for_current_device(stream.context(), &kernel).unwrap();
|
||||
let module = stream.context().load_module(ptx).unwrap();
|
||||
let func = module.load_function(kernel_name).unwrap();
|
||||
compile_cache.insert(kernel.clone(), (module.clone(), func.clone()));
|
||||
(module, func)
|
||||
};
|
||||
let out_size = out_shape.iter().copied().product::<Expression>();
|
||||
(
|
||||
func,
|
||||
module,
|
||||
kernel,
|
||||
(out_size.ceil_div(256), 1.into(), 1.into()),
|
||||
(out_size.min(256), 1.into(), 1.into()),
|
||||
0.into(),
|
||||
FxHashMap::default(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Generate `pub struct $Name { … unary fields … }` plus its `EgglogOp` and
|
||||
/// `KernelOp` impls. `$kernel_name` names the CUDA function (and the cache
|
||||
/// key); `$body` is the per-op CUDA expression, e.g. `"sinf(in[{in_idx}])"`.
|
||||
macro_rules! impl_fused_unary {
|
||||
($Name:ident, $sort:literal, $kernel_name:literal, $body:literal) => {
|
||||
#[derive(Default, Debug, Clone)]
|
||||
pub struct $Name {
|
||||
pub(crate) shape: Vec<Expression>,
|
||||
pub(crate) in_strides: Vec<Expression>,
|
||||
pub(crate) out_strides: Vec<Expression>,
|
||||
pub(crate) dtype: DType,
|
||||
}
|
||||
|
||||
impl EgglogOp for $Name {
|
||||
fn sort(&self) -> SortDef {
|
||||
sort(
|
||||
OP_KIND,
|
||||
$sort,
|
||||
&[
|
||||
("shape", ELIST),
|
||||
("strides", ELIST),
|
||||
("out_strides", ELIST),
|
||||
("dtype", DTYPE),
|
||||
],
|
||||
)
|
||||
}
|
||||
fn n_inputs(&self) -> usize {
|
||||
1
|
||||
}
|
||||
fn rewrites(&self) -> Vec<Rule> {
|
||||
Vec::new()
|
||||
}
|
||||
fn cleanup(&self) -> bool {
|
||||
false
|
||||
}
|
||||
fn extract<'a>(
|
||||
&'a self,
|
||||
egraph: &'a SerializedEGraph,
|
||||
kind_children: &[&'a ENodeId],
|
||||
input_enodes: Vec<&'a ENodeId>,
|
||||
list_cache: &mut FxHashMap<&'a ENodeId, Vec<Expression>>,
|
||||
expr_cache: &mut FxHashMap<&'a ENodeId, Expression>,
|
||||
) -> (LLIROp, Vec<&'a ENodeId>) {
|
||||
(
|
||||
LLIROp::new::<dyn KernelOp>(Box::new(Self {
|
||||
shape: extract_expr_list(egraph, kind_children[0], list_cache, expr_cache)
|
||||
.unwrap(),
|
||||
in_strides: extract_expr_list(
|
||||
egraph,
|
||||
kind_children[1],
|
||||
list_cache,
|
||||
expr_cache,
|
||||
)
|
||||
.unwrap(),
|
||||
out_strides: extract_expr_list(
|
||||
egraph,
|
||||
kind_children[2],
|
||||
list_cache,
|
||||
expr_cache,
|
||||
)
|
||||
.unwrap(),
|
||||
dtype: extract_dtype(egraph, kind_children[3]),
|
||||
})),
|
||||
input_enodes,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl KernelOp for $Name {
|
||||
fn compile(
|
||||
&self,
|
||||
stream: &Arc<CudaStream>,
|
||||
compile_cache: &mut FxHashMap<String, (Arc<CudaModule>, CudaFunction)>,
|
||||
) -> CompileOut {
|
||||
compile_unary_fallback(
|
||||
stream,
|
||||
compile_cache,
|
||||
$kernel_name,
|
||||
$body,
|
||||
&self.shape,
|
||||
&self.in_strides,
|
||||
&self.out_strides,
|
||||
self.dtype,
|
||||
)
|
||||
}
|
||||
fn output_size(&self) -> Expression {
|
||||
self.shape.iter().copied().product()
|
||||
}
|
||||
fn output_bytes(&self) -> Expression {
|
||||
(self.output_size() * self.dtype.bits()).ceil_div(8)
|
||||
}
|
||||
fn bytes_loaded(&self) -> Expression {
|
||||
self.output_bytes()
|
||||
}
|
||||
fn bytes_stored(&self) -> Expression {
|
||||
self.output_bytes()
|
||||
}
|
||||
fn flops(&self) -> Expression {
|
||||
self.shape.iter().copied().product()
|
||||
}
|
||||
fn output_dtype(&self) -> DType {
|
||||
self.dtype
|
||||
}
|
||||
fn kernel_name(&self) -> &'static str {
|
||||
$sort
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// As `impl_fused_unary!` but for binary ops: 5-field sort signature
|
||||
/// (shape + per-input strides + out_stride + dtype), n_inputs = 2.
|
||||
/// `$op_str` is the CUDA infix operator, e.g. `"+"`, `"*"`.
|
||||
macro_rules! impl_fused_binary {
|
||||
($Name:ident, $sort:literal, $kernel_name:literal, $op_str:literal) => {
|
||||
#[derive(Default, Debug, Clone)]
|
||||
pub struct $Name {
|
||||
pub(crate) out_shape: Vec<Expression>,
|
||||
pub(crate) a_stride: Vec<Expression>,
|
||||
pub(crate) b_stride: Vec<Expression>,
|
||||
pub(crate) out_stride: Vec<Expression>,
|
||||
pub(crate) dtype: DType,
|
||||
}
|
||||
|
||||
impl EgglogOp for $Name {
|
||||
fn sort(&self) -> SortDef {
|
||||
sort(
|
||||
OP_KIND,
|
||||
$sort,
|
||||
&[
|
||||
("shape", ELIST),
|
||||
("a_strides", ELIST),
|
||||
("b_strides", ELIST),
|
||||
("out_strides", ELIST),
|
||||
("dtype", DTYPE),
|
||||
],
|
||||
)
|
||||
}
|
||||
fn n_inputs(&self) -> usize {
|
||||
2
|
||||
}
|
||||
fn rewrites(&self) -> Vec<Rule> {
|
||||
Vec::new()
|
||||
}
|
||||
fn cleanup(&self) -> bool {
|
||||
false
|
||||
}
|
||||
fn extract<'a>(
|
||||
&'a self,
|
||||
egraph: &'a SerializedEGraph,
|
||||
kind_children: &[&'a ENodeId],
|
||||
input_enodes: Vec<&'a ENodeId>,
|
||||
list_cache: &mut FxHashMap<&'a ENodeId, Vec<Expression>>,
|
||||
expr_cache: &mut FxHashMap<&'a ENodeId, Expression>,
|
||||
) -> (LLIROp, Vec<&'a ENodeId>) {
|
||||
(
|
||||
LLIROp::new::<dyn KernelOp>(Box::new(Self {
|
||||
out_shape: extract_expr_list(
|
||||
egraph,
|
||||
kind_children[0],
|
||||
list_cache,
|
||||
expr_cache,
|
||||
)
|
||||
.unwrap(),
|
||||
a_stride: extract_expr_list(
|
||||
egraph,
|
||||
kind_children[1],
|
||||
list_cache,
|
||||
expr_cache,
|
||||
)
|
||||
.unwrap(),
|
||||
b_stride: extract_expr_list(
|
||||
egraph,
|
||||
kind_children[2],
|
||||
list_cache,
|
||||
expr_cache,
|
||||
)
|
||||
.unwrap(),
|
||||
out_stride: extract_expr_list(
|
||||
egraph,
|
||||
kind_children[3],
|
||||
list_cache,
|
||||
expr_cache,
|
||||
)
|
||||
.unwrap(),
|
||||
dtype: extract_dtype(egraph, kind_children[4]),
|
||||
})),
|
||||
input_enodes,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl KernelOp for $Name {
|
||||
fn compile(
|
||||
&self,
|
||||
stream: &Arc<CudaStream>,
|
||||
compile_cache: &mut FxHashMap<String, (Arc<CudaModule>, CudaFunction)>,
|
||||
) -> CompileOut {
|
||||
compile_binary_fallback(
|
||||
stream,
|
||||
compile_cache,
|
||||
$kernel_name,
|
||||
$op_str,
|
||||
&self.out_shape,
|
||||
&self.a_stride,
|
||||
&self.b_stride,
|
||||
&self.out_stride,
|
||||
self.dtype,
|
||||
)
|
||||
}
|
||||
fn output_size(&self) -> Expression {
|
||||
self.out_shape.iter().copied().product()
|
||||
}
|
||||
fn output_bytes(&self) -> Expression {
|
||||
(self.output_size() * self.dtype.bits()).ceil_div(8)
|
||||
}
|
||||
fn bytes_loaded(&self) -> Expression {
|
||||
let bytes = (self.output_size() * self.dtype.bits()).ceil_div(8);
|
||||
bytes + bytes
|
||||
}
|
||||
fn bytes_stored(&self) -> Expression {
|
||||
self.output_bytes()
|
||||
}
|
||||
fn flops(&self) -> Expression {
|
||||
self.out_shape.iter().copied().product()
|
||||
}
|
||||
fn output_dtype(&self) -> DType {
|
||||
self.dtype
|
||||
}
|
||||
fn kernel_name(&self) -> &'static str {
|
||||
$sort
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
impl_fused_unary!(FusedSin, "FusedSin", "fused_sin_k", "sinf(in[{in_idx}])");
|
||||
impl_fused_unary!(
|
||||
FusedSqrt,
|
||||
"FusedSqrt",
|
||||
"fused_sqrt_k",
|
||||
"sqrtf(in[{in_idx}])"
|
||||
);
|
||||
impl_fused_unary!(FusedExp, "FusedExp", "fused_exp_k", "expf(in[{in_idx}])");
|
||||
impl_fused_unary!(
|
||||
FusedExp2,
|
||||
"FusedExp2",
|
||||
"fused_exp2_k",
|
||||
"exp2f(in[{in_idx}])"
|
||||
);
|
||||
impl_fused_unary!(
|
||||
FusedLog2,
|
||||
"FusedLog2",
|
||||
"fused_log2_k",
|
||||
"log2f(in[{in_idx}])"
|
||||
);
|
||||
impl_fused_unary!(
|
||||
FusedRecip,
|
||||
"FusedRecip",
|
||||
"fused_recip_k",
|
||||
"1.0f / in[{in_idx}]"
|
||||
);
|
||||
|
||||
impl_fused_binary!(FusedAdd, "FusedAdd", "fused_add_k", "+");
|
||||
impl_fused_binary!(FusedMul, "FusedMul", "fused_mul_k", "*");
|
||||
@@ -9,8 +9,8 @@
|
||||
//
|
||||
// `FusionEnd::rewrites()` carries the seven rule families that build and
|
||||
// extend regions (pair-fuse / grow / merge); the actual single-kernel
|
||||
// codegen lives in `region_codegen`. Like FusedX, both markers'
|
||||
// `compile()` is `unreachable!()` — region codegen folds them away
|
||||
// codegen lives in `region_codegen`. Both markers' `compile()` is
|
||||
// `unreachable!()` — region codegen folds them away
|
||||
// before kernel_to_host's compile loop reaches an interior node.
|
||||
// =========================================================================
|
||||
|
||||
@@ -27,70 +27,7 @@ use luminal::{
|
||||
prelude::*,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
compile_module_image_for_current_device, cuda_dtype,
|
||||
kernel::KernelOp,
|
||||
kernel::hlir::{dtype_includes, generate_dyn_dims_defines},
|
||||
};
|
||||
|
||||
/// Identity-memcpy kernel used as a *fallback* when a FusionStart or
|
||||
/// FusionEnd reaches `kernel_to_host`'s compile loop standalone (i.e.,
|
||||
/// region detection didn't sweep it into a `CompileUnit::Region`). The
|
||||
/// fast path is region collapse, but model-fuzz extraction sometimes
|
||||
/// produces LLIR shapes the detector doesn't catch; this keeps
|
||||
/// execution correct in those cases.
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn compile_identity_kernel(
|
||||
stream: &Arc<CudaStream>,
|
||||
compile_cache: &mut FxHashMap<String, (Arc<CudaModule>, CudaFunction)>,
|
||||
kernel_name: &str,
|
||||
shape: &[Expression],
|
||||
strides: &[Expression],
|
||||
dtype: DType,
|
||||
) -> CompileOut {
|
||||
let vars = shape
|
||||
.iter()
|
||||
.flat_map(|e| e.dyn_vars())
|
||||
.chain(strides.iter().flat_map(|e| e.dyn_vars()))
|
||||
.collect::<FxHashSet<_>>();
|
||||
let cuda_ty = cuda_dtype(dtype);
|
||||
let includes = dtype_includes(&[dtype]);
|
||||
let (dyn_defines, _sorted_dims) = generate_dyn_dims_defines(&vars);
|
||||
let dyn_dims_param = if vars.is_empty() {
|
||||
""
|
||||
} else {
|
||||
", const int* dyn_dims"
|
||||
};
|
||||
let n_elements = shape.iter().copied().product::<Expression>().to_kernel();
|
||||
let idx = flatten_strides(shape, strides).to_kernel();
|
||||
let kernel = format!(
|
||||
"{includes}\n{dyn_defines}\nextern \"C\" {{\n\
|
||||
\x20 __global__ void {kernel_name}({cuda_ty} *out, const {cuda_ty} *in{dyn_dims_param}) {{\n\
|
||||
\x20 long long const_z = (long long)blockIdx.x * blockDim.x + threadIdx.x;\n\
|
||||
\x20 if (const_z >= {n_elements}) return;\n\
|
||||
\x20 out[{idx}] = in[{idx}];\n\
|
||||
\x20 }}\n}}"
|
||||
);
|
||||
let (module, func) = if let Some((m, f)) = compile_cache.get(&kernel) {
|
||||
(m.clone(), f.clone())
|
||||
} else {
|
||||
let ptx = compile_module_image_for_current_device(stream.context(), &kernel).unwrap();
|
||||
let module = stream.context().load_module(ptx).unwrap();
|
||||
let func = module.load_function(kernel_name).unwrap();
|
||||
compile_cache.insert(kernel.clone(), (module.clone(), func.clone()));
|
||||
(module, func)
|
||||
};
|
||||
let out_size = shape.iter().copied().product::<Expression>();
|
||||
(
|
||||
func,
|
||||
module,
|
||||
kernel,
|
||||
(out_size.ceil_div(256), 1.into(), 1.into()),
|
||||
(out_size.min(256), 1.into(), 1.into()),
|
||||
0.into(),
|
||||
FxHashMap::default(),
|
||||
)
|
||||
}
|
||||
use crate::kernel::KernelOp;
|
||||
|
||||
pub type Ops = (FusionStart, FusionEnd);
|
||||
|
||||
@@ -159,17 +96,10 @@ impl EgglogOp for FusionStart {
|
||||
impl KernelOp for FusionStart {
|
||||
fn compile(
|
||||
&self,
|
||||
stream: &Arc<CudaStream>,
|
||||
compile_cache: &mut FxHashMap<String, (Arc<CudaModule>, CudaFunction)>,
|
||||
_stream: &Arc<CudaStream>,
|
||||
_compile_cache: &mut FxHashMap<String, (Arc<CudaModule>, CudaFunction)>,
|
||||
) -> CompileOut {
|
||||
compile_identity_kernel(
|
||||
stream,
|
||||
compile_cache,
|
||||
"fusion_start_k",
|
||||
&self.shape,
|
||||
&self.strides,
|
||||
self.dtype,
|
||||
)
|
||||
unreachable!("FusionStart must be compiled through fusion region codegen")
|
||||
}
|
||||
fn output_size(&self) -> Expression {
|
||||
self.shape.iter().copied().product()
|
||||
@@ -183,6 +113,9 @@ impl KernelOp for FusionStart {
|
||||
fn kernel_name(&self) -> &'static str {
|
||||
"FusionStart"
|
||||
}
|
||||
fn output_aliases_input(&self) -> Option<usize> {
|
||||
Some(0)
|
||||
}
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
@@ -209,218 +142,164 @@ impl EgglogOp for FusionEnd {
|
||||
}
|
||||
|
||||
fn rewrites(&self) -> Vec<Rule> {
|
||||
// Seven rule families build and extend FE-bracketed regions. Each
|
||||
// pair-fuse rule's LHS pattern matches *un-fused* `KernelX` ops; the
|
||||
// RHS produces `FusedX` variants in a different egglog sort, so the
|
||||
// rule's own output cannot re-match its LHS — cascade is prevented
|
||||
// by typing rather than by a discriminator field.
|
||||
//
|
||||
// Stride compatibility is expressed by reusing variable names: a
|
||||
// unary inside a region matches `(KernelU ?shape ?s ?s ?dt)` (in =
|
||||
// out, no transpose); a binary feeding a downstream op binds the
|
||||
// binary's out-stride to the downstream op's in-stride along the
|
||||
// connecting side.
|
||||
// Generic region growth works directly from HLIR elementwise ops into
|
||||
// `Cuda*Elementwise` region nodes. The concrete HLIR op still appears in
|
||||
// the egraph, so fusion remains a normal nondestructive alternative, but
|
||||
// the region-internal representation is arity based instead of one
|
||||
// dedicated fused sort per operation.
|
||||
let mut rules = Vec::new();
|
||||
|
||||
// (KernelX kind, FusedX kind)
|
||||
let unaries: &[(&str, &str)] = &[
|
||||
("KernelSin", "FusedSin"),
|
||||
("KernelSqrt", "FusedSqrt"),
|
||||
("KernelExp", "FusedExp"),
|
||||
("KernelExp2", "FusedExp2"),
|
||||
("KernelLog2", "FusedLog2"),
|
||||
("KernelRecip", "FusedRecip"),
|
||||
];
|
||||
// (KernelX kind, FusedX kind, rule-name label)
|
||||
let binaries: &[(&str, &str, &str)] = &[
|
||||
("KernelAdd", "FusedAdd", "Add"),
|
||||
("KernelMul", "FusedMul", "Mul"),
|
||||
("Sin", "Sin"),
|
||||
("Sqrt", "Sqrt"),
|
||||
("Exp2", "Exp2"),
|
||||
("Log2", "Log2"),
|
||||
("Recip", "Recip"),
|
||||
];
|
||||
let binaries: &[(&str, &str)] = &[("Add", "Add"), ("Mul", "Mul")];
|
||||
|
||||
// 1. Pair-fuse U → U: U2(U1(x)) → FE(FU2(FU1(FS(x)))).
|
||||
for (ki1, fi1) in unaries {
|
||||
for (ko2, fo2) in unaries {
|
||||
rules.push(Rule::raw(format!(
|
||||
"(rule (
|
||||
(= ?u1 (Op ({ki1} ?shape ?s ?s ?dt) (ICons ?x (INil))))
|
||||
(= ?u2 (Op ({ko2} ?shape ?s ?s ?dt) (ICons ?u1 (INil))))
|
||||
) (
|
||||
(let ?fs (Op (FusionStart ?shape ?s ?dt) (ICons ?x (INil))))
|
||||
(let ?fu1 (Op ({fi1} ?shape ?s ?s ?dt) (ICons ?fs (INil))))
|
||||
(let ?fu2 (Op ({fo2} ?shape ?s ?s ?dt) (ICons ?fu1 (INil))))
|
||||
(let ?fe (Op (FusionEnd ?shape ?s ?dt) (ICons ?fu2 (INil))))
|
||||
(union ?u2 ?fe)
|
||||
) :ruleset fusion_pair :name \"pair-fuse-U-U-{ki1}-{ko2}\")"
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Pair-fuse B → U: U(B(a, b)) → FE(FU(FB(FS(a), FS(b)))).
|
||||
for (kb, fb, lb) in binaries {
|
||||
for (ku, fu) in unaries {
|
||||
rules.push(Rule::raw(format!(
|
||||
"(rule (
|
||||
(= ?bin (Op ({kb} ?shape ?a_s ?b_s ?o_s ?dt)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
(= ?u (Op ({ku} ?shape ?o_s ?o_s ?dt) (ICons ?bin (INil))))
|
||||
) (
|
||||
(let ?fs_a (Op (FusionStart ?shape ?a_s ?dt) (ICons ?a (INil))))
|
||||
(let ?fs_b (Op (FusionStart ?shape ?b_s ?dt) (ICons ?b (INil))))
|
||||
(let ?fbin (Op ({fb} ?shape ?a_s ?b_s ?o_s ?dt)
|
||||
(ICons ?fs_a (ICons ?fs_b (INil)))))
|
||||
(let ?fu (Op ({fu} ?shape ?o_s ?o_s ?dt) (ICons ?fbin (INil))))
|
||||
(let ?fe (Op (FusionEnd ?shape ?o_s ?dt) (ICons ?fu (INil))))
|
||||
(union ?u ?fe)
|
||||
) :ruleset fusion_pair :name \"pair-fuse-B-U-{lb}-{ku}\")"
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Pair-fuse U → B (lhs / rhs): unary feeds binary's A or B input.
|
||||
// LHS: B(U(a), b) → FE(FB(FU(FS(a)), FS(b))).
|
||||
// RHS: B(a, U(b)) → FE(FB(FS(a), FU(FS(b)))).
|
||||
for (ku, fu) in unaries {
|
||||
for (kb, fb, lb) in binaries {
|
||||
rules.push(Rule::raw(format!(
|
||||
"(rule (
|
||||
(= ?u (Op ({ku} ?shape ?u_s ?u_s ?dt) (ICons ?a (INil))))
|
||||
(= ?bin (Op ({kb} ?shape ?u_s ?b_s ?o_s ?dt)
|
||||
(ICons ?u (ICons ?b (INil)))))
|
||||
) (
|
||||
(let ?fs_a (Op (FusionStart ?shape ?u_s ?dt) (ICons ?a (INil))))
|
||||
(let ?fs_b (Op (FusionStart ?shape ?b_s ?dt) (ICons ?b (INil))))
|
||||
(let ?fu (Op ({fu} ?shape ?u_s ?u_s ?dt) (ICons ?fs_a (INil))))
|
||||
(let ?fbin (Op ({fb} ?shape ?u_s ?b_s ?o_s ?dt)
|
||||
(ICons ?fu (ICons ?fs_b (INil)))))
|
||||
(let ?fe (Op (FusionEnd ?shape ?o_s ?dt) (ICons ?fbin (INil))))
|
||||
(union ?bin ?fe)
|
||||
) :ruleset fusion_pair :name \"pair-fuse-U-B-lhs-{ku}-{lb}\")"
|
||||
)));
|
||||
rules.push(Rule::raw(format!(
|
||||
"(rule (
|
||||
(= ?u (Op ({ku} ?shape ?u_s ?u_s ?dt) (ICons ?b (INil))))
|
||||
(= ?bin (Op ({kb} ?shape ?a_s ?u_s ?o_s ?dt)
|
||||
(ICons ?a (ICons ?u (INil)))))
|
||||
) (
|
||||
(let ?fs_a (Op (FusionStart ?shape ?a_s ?dt) (ICons ?a (INil))))
|
||||
(let ?fs_b (Op (FusionStart ?shape ?u_s ?dt) (ICons ?b (INil))))
|
||||
(let ?fu (Op ({fu} ?shape ?u_s ?u_s ?dt) (ICons ?fs_b (INil))))
|
||||
(let ?fbin (Op ({fb} ?shape ?a_s ?u_s ?o_s ?dt)
|
||||
(ICons ?fs_a (ICons ?fu (INil)))))
|
||||
(let ?fe (Op (FusionEnd ?shape ?o_s ?dt) (ICons ?fbin (INil))))
|
||||
(union ?bin ?fe)
|
||||
) :ruleset fusion_pair :name \"pair-fuse-U-B-rhs-{ku}-{lb}\")"
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Pair-fuse B → B (lhs / rhs): inner binary feeds outer's A or B.
|
||||
for (kbi, fbi, lbi) in binaries {
|
||||
for (kbo, fbo, lbo) in binaries {
|
||||
rules.push(Rule::raw(format!(
|
||||
"(rule (
|
||||
(= ?bi (Op ({kbi} ?shape ?ai_s ?bi_s ?oi_s ?dt)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
(= ?bo (Op ({kbo} ?shape ?oi_s ?co_s ?oo_s ?dt)
|
||||
(ICons ?bi (ICons ?c (INil)))))
|
||||
) (
|
||||
(let ?fs_a (Op (FusionStart ?shape ?ai_s ?dt) (ICons ?a (INil))))
|
||||
(let ?fs_b (Op (FusionStart ?shape ?bi_s ?dt) (ICons ?b (INil))))
|
||||
(let ?fs_c (Op (FusionStart ?shape ?co_s ?dt) (ICons ?c (INil))))
|
||||
(let ?fbi (Op ({fbi} ?shape ?ai_s ?bi_s ?oi_s ?dt)
|
||||
(ICons ?fs_a (ICons ?fs_b (INil)))))
|
||||
(let ?fbo (Op ({fbo} ?shape ?oi_s ?co_s ?oo_s ?dt)
|
||||
(ICons ?fbi (ICons ?fs_c (INil)))))
|
||||
(let ?fe (Op (FusionEnd ?shape ?oo_s ?dt) (ICons ?fbo (INil))))
|
||||
(union ?bo ?fe)
|
||||
) :ruleset fusion_pair :name \"pair-fuse-B-B-lhs-{lbi}-{lbo}\")"
|
||||
)));
|
||||
rules.push(Rule::raw(format!(
|
||||
"(rule (
|
||||
(= ?bi (Op ({kbi} ?shape ?ai_s ?bi_s ?oi_s ?dt)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
(= ?bo (Op ({kbo} ?shape ?co_s ?oi_s ?oo_s ?dt)
|
||||
(ICons ?c (ICons ?bi (INil)))))
|
||||
) (
|
||||
(let ?fs_a (Op (FusionStart ?shape ?ai_s ?dt) (ICons ?a (INil))))
|
||||
(let ?fs_b (Op (FusionStart ?shape ?bi_s ?dt) (ICons ?b (INil))))
|
||||
(let ?fs_c (Op (FusionStart ?shape ?co_s ?dt) (ICons ?c (INil))))
|
||||
(let ?fbi (Op ({fbi} ?shape ?ai_s ?bi_s ?oi_s ?dt)
|
||||
(ICons ?fs_a (ICons ?fs_b (INil)))))
|
||||
(let ?fbo (Op ({fbo} ?shape ?co_s ?oi_s ?oo_s ?dt)
|
||||
(ICons ?fs_c (ICons ?fbi (INil)))))
|
||||
(let ?fe (Op (FusionEnd ?shape ?oo_s ?dt) (ICons ?fbo (INil))))
|
||||
(union ?bo ?fe)
|
||||
) :ruleset fusion_pair :name \"pair-fuse-B-B-rhs-{lbi}-{lbo}\")"
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Grow FE → U: U(FE(inner)) → FE(FU(inner)). No new FS.
|
||||
for (ku, fu) in unaries {
|
||||
// Grow FE → unary consumer: U(FE(inner)) → FE(CudaUnary(inner)).
|
||||
for (hlir, opcode) in unaries {
|
||||
rules.push(Rule::raw(format!(
|
||||
"(rule (
|
||||
(= ?fe (Op (FusionEnd ?shape ?s ?dt) (ICons ?inner (INil))))
|
||||
(= ?u (Op ({ku} ?shape ?s ?s ?dt) (ICons ?fe (INil))))
|
||||
(= ?u (Op ({hlir} ?shape ?s ?s) (ICons ?fe (INil))))
|
||||
) (
|
||||
(let ?fu (Op ({fu} ?shape ?s ?s ?dt) (ICons ?inner (INil))))
|
||||
(let ?new_fe (Op (FusionEnd ?shape ?s ?dt) (ICons ?fu (INil))))
|
||||
(let ?elem (Op (CudaUnaryElementwise \"{opcode}\" ?shape ?s ?s ?dt)
|
||||
(ICons ?inner (INil))))
|
||||
(let ?new_fe (Op (FusionEnd ?shape ?s ?dt) (ICons ?elem (INil))))
|
||||
(union ?u ?new_fe)
|
||||
) :ruleset fusion_grow :name \"grow-FE-U-{ku}\")"
|
||||
(set (dtype ?new_fe) ?dt)
|
||||
) :ruleset fusion_grow :name \"grow-FE-U-{hlir}\")"
|
||||
)));
|
||||
}
|
||||
|
||||
// 6. Grow FE → B (lhs / rhs): one input is the FE, the other external.
|
||||
for (kb, fb, lb) in binaries {
|
||||
// Grow FE → binary consumer, left and right orientations.
|
||||
for (hlir, opcode) in binaries {
|
||||
rules.push(Rule::raw(format!(
|
||||
"(rule (
|
||||
(= ?fe (Op (FusionEnd ?shape ?a_s ?dt) (ICons ?inner_a (INil))))
|
||||
(= ?bin (Op ({kb} ?shape ?a_s ?b_s ?o_s ?dt)
|
||||
(= ?bin (Op ({hlir} ?shape ?a_s ?b_s ?out_s)
|
||||
(ICons ?fe (ICons ?b (INil)))))
|
||||
) (
|
||||
(let ?fs_b (Op (FusionStart ?shape ?b_s ?dt) (ICons ?b (INil))))
|
||||
(let ?fbin (Op ({fb} ?shape ?a_s ?b_s ?o_s ?dt)
|
||||
(let ?elem (Op (CudaBinaryElementwise \"{opcode}\" ?shape ?a_s ?b_s ?out_s ?dt)
|
||||
(ICons ?inner_a (ICons ?fs_b (INil)))))
|
||||
(let ?new_fe (Op (FusionEnd ?shape ?o_s ?dt) (ICons ?fbin (INil))))
|
||||
(let ?new_fe (Op (FusionEnd ?shape ?out_s ?dt) (ICons ?elem (INil))))
|
||||
(union ?bin ?new_fe)
|
||||
) :ruleset fusion_grow :name \"grow-FE-B-lhs-{lb}\")"
|
||||
(set (dtype ?new_fe) ?dt)
|
||||
) :ruleset fusion_grow :name \"grow-FE-B-lhs-{hlir}\")"
|
||||
)));
|
||||
rules.push(Rule::raw(format!(
|
||||
"(rule (
|
||||
(= ?fe (Op (FusionEnd ?shape ?b_s ?dt) (ICons ?inner_b (INil))))
|
||||
(= ?bin (Op ({kb} ?shape ?a_s ?b_s ?o_s ?dt)
|
||||
(= ?bin (Op ({hlir} ?shape ?a_s ?b_s ?out_s)
|
||||
(ICons ?a (ICons ?fe (INil)))))
|
||||
) (
|
||||
(let ?fs_a (Op (FusionStart ?shape ?a_s ?dt) (ICons ?a (INil))))
|
||||
(let ?fbin (Op ({fb} ?shape ?a_s ?b_s ?o_s ?dt)
|
||||
(let ?elem (Op (CudaBinaryElementwise \"{opcode}\" ?shape ?a_s ?b_s ?out_s ?dt)
|
||||
(ICons ?fs_a (ICons ?inner_b (INil)))))
|
||||
(let ?new_fe (Op (FusionEnd ?shape ?o_s ?dt) (ICons ?fbin (INil))))
|
||||
(let ?new_fe (Op (FusionEnd ?shape ?out_s ?dt) (ICons ?elem (INil))))
|
||||
(union ?bin ?new_fe)
|
||||
) :ruleset fusion_grow :name \"grow-FE-B-rhs-{lb}\")"
|
||||
(set (dtype ?new_fe) ?dt)
|
||||
) :ruleset fusion_grow :name \"grow-FE-B-rhs-{hlir}\")"
|
||||
)));
|
||||
}
|
||||
|
||||
// 7. Merge two FEs at a binary: B(FE(ia), FE(ib)) → FE(FB(ia, ib)).
|
||||
//
|
||||
// This is destructive: after creating the larger region, subsume the
|
||||
// two smaller FusionEnd rows. Without that, independently-grown left
|
||||
// and right regions form a Cartesian product, then those alternatives
|
||||
// can merge again higher in the graph.
|
||||
for (kb, fb, lb) in binaries {
|
||||
// Absorb an elementwise producer through a FusionStart boundary. This
|
||||
// makes a region that initially treats `producer(...)` as an external
|
||||
// input able to pull that producer inside later.
|
||||
for (hlir, opcode) in unaries {
|
||||
rules.push(Rule::raw(format!(
|
||||
"(rule (
|
||||
(= ?u (Op ({hlir} ?shape ?s ?s) (ICons ?x (INil))))
|
||||
(= ?fs_u (Op (FusionStart ?shape ?s ?dt) (ICons ?u (INil))))
|
||||
) (
|
||||
(let ?fs_x (Op (FusionStart ?shape ?s ?dt) (ICons ?x (INil))))
|
||||
(let ?elem (Op (CudaUnaryElementwise \"{opcode}\" ?shape ?s ?s ?dt)
|
||||
(ICons ?fs_x (INil))))
|
||||
(union ?fs_u ?elem)
|
||||
) :ruleset fusion_grow :name \"grow-U-FS-{hlir}\")"
|
||||
)));
|
||||
rules.push(Rule::raw(format!(
|
||||
"(rule (
|
||||
(= ?inner_fe (Op (FusionEnd ?shape ?s ?dt) (ICons ?inner (INil))))
|
||||
(= ?bad_fs (Op (FusionStart ?shape ?s ?dt) (ICons ?inner_fe (INil))))
|
||||
(= ?bad_elem (Op (CudaUnaryElementwise \"{opcode}\" ?shape ?s ?s ?dt)
|
||||
(ICons ?bad_fs (INil))))
|
||||
(= ?bad_fe (Op (FusionEnd ?shape ?s ?dt) (ICons ?bad_elem (INil))))
|
||||
(= ?good_elem (Op (CudaUnaryElementwise \"{opcode}\" ?shape ?s ?s ?dt)
|
||||
(ICons ?inner (INil))))
|
||||
(= ?good_fe (Op (FusionEnd ?shape ?s ?dt) (ICons ?good_elem (INil))))
|
||||
(= ?bad_fe ?good_fe)
|
||||
) (
|
||||
(delete (Op (FusionStart ?shape ?s ?dt) (ICons ?inner_fe (INil))))
|
||||
) :ruleset cleanup :name \"cleanup-nested-FS-FE-unary-{hlir}\")"
|
||||
)));
|
||||
}
|
||||
for (hlir, opcode) in binaries {
|
||||
rules.push(Rule::raw(format!(
|
||||
"(rule (
|
||||
(= ?bin (Op ({hlir} ?shape ?a_s ?b_s ?out_s)
|
||||
(ICons ?a (ICons ?b (INil)))))
|
||||
(= ?fs_bin (Op (FusionStart ?shape ?out_s ?dt) (ICons ?bin (INil))))
|
||||
) (
|
||||
(let ?fs_a (Op (FusionStart ?shape ?a_s ?dt) (ICons ?a (INil))))
|
||||
(let ?fs_b (Op (FusionStart ?shape ?b_s ?dt) (ICons ?b (INil))))
|
||||
(let ?elem (Op (CudaBinaryElementwise \"{opcode}\" ?shape ?a_s ?b_s ?out_s ?dt)
|
||||
(ICons ?fs_a (ICons ?fs_b (INil)))))
|
||||
(union ?fs_bin ?elem)
|
||||
) :ruleset fusion_grow :name \"grow-B-FS-{hlir}\")"
|
||||
)));
|
||||
rules.push(Rule::raw(format!(
|
||||
"(rule (
|
||||
(= ?inner_fe (Op (FusionEnd ?shape ?a_s ?dt) (ICons ?inner_a (INil))))
|
||||
(= ?bad_fs (Op (FusionStart ?shape ?a_s ?dt) (ICons ?inner_fe (INil))))
|
||||
(= ?fs_b (Op (FusionStart ?shape ?b_s ?dt) (ICons ?b (INil))))
|
||||
(= ?bad_elem (Op (CudaBinaryElementwise \"{opcode}\" ?shape ?a_s ?b_s ?out_s ?dt)
|
||||
(ICons ?bad_fs (ICons ?fs_b (INil)))))
|
||||
(= ?bad_fe (Op (FusionEnd ?shape ?out_s ?dt) (ICons ?bad_elem (INil))))
|
||||
(= ?good_elem (Op (CudaBinaryElementwise \"{opcode}\" ?shape ?a_s ?b_s ?out_s ?dt)
|
||||
(ICons ?inner_a (ICons ?fs_b (INil)))))
|
||||
(= ?good_fe (Op (FusionEnd ?shape ?out_s ?dt) (ICons ?good_elem (INil))))
|
||||
(= ?bad_fe ?good_fe)
|
||||
) (
|
||||
(delete (Op (FusionStart ?shape ?a_s ?dt) (ICons ?inner_fe (INil))))
|
||||
) :ruleset cleanup :name \"cleanup-nested-FS-FE-binary-lhs-{hlir}\")"
|
||||
)));
|
||||
rules.push(Rule::raw(format!(
|
||||
"(rule (
|
||||
(= ?inner_fe (Op (FusionEnd ?shape ?b_s ?dt) (ICons ?inner_b (INil))))
|
||||
(= ?bad_fs (Op (FusionStart ?shape ?b_s ?dt) (ICons ?inner_fe (INil))))
|
||||
(= ?fs_a (Op (FusionStart ?shape ?a_s ?dt) (ICons ?a (INil))))
|
||||
(= ?bad_elem (Op (CudaBinaryElementwise \"{opcode}\" ?shape ?a_s ?b_s ?out_s ?dt)
|
||||
(ICons ?fs_a (ICons ?bad_fs (INil)))))
|
||||
(= ?bad_fe (Op (FusionEnd ?shape ?out_s ?dt) (ICons ?bad_elem (INil))))
|
||||
(= ?good_elem (Op (CudaBinaryElementwise \"{opcode}\" ?shape ?a_s ?b_s ?out_s ?dt)
|
||||
(ICons ?fs_a (ICons ?inner_b (INil)))))
|
||||
(= ?good_fe (Op (FusionEnd ?shape ?out_s ?dt) (ICons ?good_elem (INil))))
|
||||
(= ?bad_fe ?good_fe)
|
||||
) (
|
||||
(delete (Op (FusionStart ?shape ?b_s ?dt) (ICons ?inner_fe (INil))))
|
||||
) :ruleset cleanup :name \"cleanup-nested-FS-FE-binary-rhs-{hlir}\")"
|
||||
)));
|
||||
}
|
||||
|
||||
// Merge two FEs at a binary: B(FE(ia), FE(ib)) → FE(CudaBinary(ia, ib)).
|
||||
for (hlir, opcode) in binaries {
|
||||
rules.push(Rule::raw(format!(
|
||||
"(rule (
|
||||
(= ?fe_a (Op (FusionEnd ?shape ?a_s ?dt) (ICons ?inner_a (INil))))
|
||||
(= ?fe_b (Op (FusionEnd ?shape ?b_s ?dt) (ICons ?inner_b (INil))))
|
||||
(= ?bin (Op ({kb} ?shape ?a_s ?b_s ?o_s ?dt)
|
||||
(= ?bin (Op ({hlir} ?shape ?a_s ?b_s ?out_s)
|
||||
(ICons ?fe_a (ICons ?fe_b (INil)))))
|
||||
) (
|
||||
(let ?fbin (Op ({fb} ?shape ?a_s ?b_s ?o_s ?dt)
|
||||
(let ?elem (Op (CudaBinaryElementwise \"{opcode}\" ?shape ?a_s ?b_s ?out_s ?dt)
|
||||
(ICons ?inner_a (ICons ?inner_b (INil)))))
|
||||
(let ?new_fe (Op (FusionEnd ?shape ?o_s ?dt) (ICons ?fbin (INil))))
|
||||
(let ?new_fe (Op (FusionEnd ?shape ?out_s ?dt) (ICons ?elem (INil))))
|
||||
(union ?bin ?new_fe)
|
||||
(subsume (Op (FusionEnd ?shape ?a_s ?dt) (ICons ?inner_a (INil))))
|
||||
(subsume (Op (FusionEnd ?shape ?b_s ?dt) (ICons ?inner_b (INil))))
|
||||
) :ruleset fusion_merge :name \"merge-FE-FE-{lb}\")"
|
||||
(set (dtype ?new_fe) ?dt)
|
||||
) :ruleset fusion_merge :name \"merge-FE-FE-{hlir}\")"
|
||||
)));
|
||||
}
|
||||
|
||||
@@ -430,6 +309,61 @@ impl EgglogOp for FusionEnd {
|
||||
// `Cycle(NodeIndex(_))`. Grow rules already compose adjacent regions
|
||||
// correctly without dissolve.
|
||||
|
||||
rules.push(Rule::raw(
|
||||
"(rule (
|
||||
(= ?fe (Op (FusionEnd ?fe_shape ?fe_s ?dt) (ICons ?inner (INil))))
|
||||
(= ?inner (Op (CudaUnaryElementwise ?op ?inner_shape ?inner_in_s ?inner_s ?dt) ?inner_inputs))
|
||||
(!= ?fe_shape ?inner_shape)
|
||||
) (
|
||||
(delete (Op (FusionEnd ?fe_shape ?fe_s ?dt) (ICons ?inner (INil))))
|
||||
) :ruleset cleanup :name \"delete-malformed-FE-unary-shape\")",
|
||||
));
|
||||
rules.push(Rule::raw(
|
||||
"(rule (
|
||||
(= ?fe (Op (FusionEnd ?fe_shape ?fe_s ?dt) (ICons ?inner (INil))))
|
||||
(= ?inner (Op (CudaUnaryElementwise ?op ?inner_shape ?inner_in_s ?inner_s ?dt) ?inner_inputs))
|
||||
(!= ?fe_s ?inner_s)
|
||||
) (
|
||||
(delete (Op (FusionEnd ?fe_shape ?fe_s ?dt) (ICons ?inner (INil))))
|
||||
) :ruleset cleanup :name \"delete-malformed-FE-unary-strides\")",
|
||||
));
|
||||
rules.push(Rule::raw(
|
||||
"(rule (
|
||||
(= ?fe (Op (FusionEnd ?fe_shape ?fe_s ?dt) (ICons ?inner (INil))))
|
||||
(= ?inner (Op (CudaBinaryElementwise ?op ?inner_shape ?a_s ?b_s ?inner_s ?dt) ?inner_inputs))
|
||||
(!= ?fe_shape ?inner_shape)
|
||||
) (
|
||||
(delete (Op (FusionEnd ?fe_shape ?fe_s ?dt) (ICons ?inner (INil))))
|
||||
) :ruleset cleanup :name \"delete-malformed-FE-binary-shape\")",
|
||||
));
|
||||
rules.push(Rule::raw(
|
||||
"(rule (
|
||||
(= ?fe (Op (FusionEnd ?fe_shape ?fe_s ?dt) (ICons ?inner (INil))))
|
||||
(= ?inner (Op (CudaBinaryElementwise ?op ?inner_shape ?a_s ?b_s ?inner_s ?dt) ?inner_inputs))
|
||||
(!= ?fe_s ?inner_s)
|
||||
) (
|
||||
(delete (Op (FusionEnd ?fe_shape ?fe_s ?dt) (ICons ?inner (INil))))
|
||||
) :ruleset cleanup :name \"delete-malformed-FE-binary-strides\")",
|
||||
));
|
||||
rules.push(Rule::raw(
|
||||
"(rule (
|
||||
(= ?fe (Op (FusionEnd ?fe_shape ?fe_s ?dt) (ICons ?inner (INil))))
|
||||
(= ?inner (Op (FusionEnd ?inner_shape ?inner_s ?dt) ?inner_inputs))
|
||||
(!= ?fe_shape ?inner_shape)
|
||||
) (
|
||||
(delete (Op (FusionEnd ?fe_shape ?fe_s ?dt) (ICons ?inner (INil))))
|
||||
) :ruleset cleanup :name \"delete-malformed-FE-nested-shape\")",
|
||||
));
|
||||
rules.push(Rule::raw(
|
||||
"(rule (
|
||||
(= ?fe (Op (FusionEnd ?fe_shape ?fe_s ?dt) (ICons ?inner (INil))))
|
||||
(= ?inner (Op (FusionEnd ?inner_shape ?inner_s ?dt) ?inner_inputs))
|
||||
(!= ?fe_s ?inner_s)
|
||||
) (
|
||||
(delete (Op (FusionEnd ?fe_shape ?fe_s ?dt) (ICons ?inner (INil))))
|
||||
) :ruleset cleanup :name \"delete-malformed-FE-nested-strides\")",
|
||||
));
|
||||
|
||||
rules
|
||||
}
|
||||
|
||||
@@ -460,17 +394,10 @@ impl EgglogOp for FusionEnd {
|
||||
impl KernelOp for FusionEnd {
|
||||
fn compile(
|
||||
&self,
|
||||
stream: &Arc<CudaStream>,
|
||||
compile_cache: &mut FxHashMap<String, (Arc<CudaModule>, CudaFunction)>,
|
||||
_stream: &Arc<CudaStream>,
|
||||
_compile_cache: &mut FxHashMap<String, (Arc<CudaModule>, CudaFunction)>,
|
||||
) -> CompileOut {
|
||||
compile_identity_kernel(
|
||||
stream,
|
||||
compile_cache,
|
||||
"fusion_end_k",
|
||||
&self.shape,
|
||||
&self.strides,
|
||||
self.dtype,
|
||||
)
|
||||
unreachable!("FusionEnd must be compiled through fusion region codegen")
|
||||
}
|
||||
fn output_size(&self) -> Expression {
|
||||
self.shape.iter().copied().product()
|
||||
|
||||
@@ -2,25 +2,21 @@
|
||||
//!
|
||||
//! - `markers` — `FusionStart` / `FusionEnd` ops + the seven egglog rule
|
||||
//! families that build and extend FE-bracketed regions.
|
||||
//! - `fused_ops` — eight `FusedX` op variants (interior to a region) so
|
||||
//! pair-fuse rules' RHS sit in a different egglog sort than their LHS,
|
||||
//! blocking cascade by typing.
|
||||
//! - `elementwise` — generic region-internal CUDA elementwise op variants.
|
||||
//! - `region_codegen` — `kernel_to_host` calls into here to collapse each
|
||||
//! FE-rooted region into a single CUDA kernel at compile time.
|
||||
//!
|
||||
//! The LLIR keeps `FusionStart` / `FusedX` / `FusionEnd` nodes after
|
||||
//! The LLIR keeps `FusionStart` / generic elementwise / `FusionEnd` nodes after
|
||||
//! extraction; `region_codegen` is the only place that walks them.
|
||||
|
||||
pub mod fused_ops;
|
||||
pub mod elementwise;
|
||||
pub mod markers;
|
||||
pub mod region_codegen;
|
||||
|
||||
pub use fused_ops::{
|
||||
FusedAdd, FusedExp, FusedExp2, FusedLog2, FusedMul, FusedRecip, FusedSin, FusedSqrt,
|
||||
};
|
||||
pub use elementwise::{CudaBinaryElementwise, CudaUnaryElementwise};
|
||||
pub use markers::{FusionEnd, FusionStart};
|
||||
|
||||
/// All fusion-related op types that the egglog runtime needs to know about
|
||||
/// (markers + interior FusedX variants). Combined into a flat tuple for the
|
||||
/// `Ops` registry in `kernel::mod`.
|
||||
pub type Ops = (markers::Ops, fused_ops::Ops);
|
||||
/// (markers + interior generic elementwise variants). Combined into a flat
|
||||
/// tuple for the `Ops` registry in `kernel::mod`.
|
||||
pub type Ops = (markers::Ops, elementwise::Ops);
|
||||
|
||||
@@ -1,26 +1,26 @@
|
||||
// =========================================================================
|
||||
// Region codegen for FusionStart / FusionEnd-bracketed fused regions.
|
||||
//
|
||||
// PR1 left FusedX / FusionStart / FusionEnd nodes in the post-extraction
|
||||
// Older fusion lowering left elementwise / FusionStart / FusionEnd nodes in the post-extraction
|
||||
// LLIR, each compiling to its own standalone CUDA kernel. PR2 collapses
|
||||
// every FusionEnd-rooted region into ONE fused CUDA kernel at codegen
|
||||
// time — without rewriting the LLIR.
|
||||
//
|
||||
// Pipeline:
|
||||
// `kernel_to_host` builds a Vec<CompileUnit> from the topo order:
|
||||
// - CompileUnit::Single(node) — un-fused KernelX, compiled as before.
|
||||
// - CompileUnit::Region(rgn) — one FE + its interior FusedX DAG +
|
||||
// - CompileUnit::Single(node) — unfused non-region kernels, compiled as before.
|
||||
// - CompileUnit::Region(rgn) — one FE + its interior elementwise DAG +
|
||||
// its FS leaves. Compiled here as a
|
||||
// single CUDA kernel that reads from
|
||||
// the region's external inputs once,
|
||||
// chains all FusedX bodies through
|
||||
// chains all elementwise bodies through
|
||||
// register-resident locals, and writes
|
||||
// the FE's output.
|
||||
//
|
||||
// The CompiledKernel for a Region is keyed on the FE node and stores
|
||||
// `inputs = external producer NodeIndices` (one per interior FusionStart),
|
||||
// so the existing buffer-pointer wiring in to_host.rs picks up the right
|
||||
// device pointers at execute time. Interior FusedX / FusionStart nodes
|
||||
// device pointers at execute time. Interior Cuda*Elementwise / FusionStart nodes
|
||||
// never enter the kernels Vec — they have no buffers, no launches.
|
||||
// =========================================================================
|
||||
|
||||
@@ -40,6 +40,7 @@ use as_any::Downcast;
|
||||
use crate::{
|
||||
compile_module_image_for_current_device, cuda_dtype,
|
||||
kernel::KernelOp,
|
||||
kernel::fusion::elementwise::{CudaBinaryElementwise, CudaUnaryElementwise},
|
||||
kernel::fusion::markers::{FusionEnd, FusionStart},
|
||||
kernel::hlir::{dtype_includes, generate_dyn_dims_defines},
|
||||
};
|
||||
@@ -52,10 +53,10 @@ use crate::{
|
||||
pub(crate) struct RegionUnit {
|
||||
/// The FusionEnd node that anchors this region.
|
||||
pub fe_node: NodeIndex,
|
||||
/// Interior FusedX nodes, in topological order (predecessors before
|
||||
/// Interior Cuda*Elementwise nodes, in topological order (predecessors before
|
||||
/// consumers). Used to emit register-binding statements in dependency
|
||||
/// order in the fused CUDA kernel body.
|
||||
pub fusedx_topo: Vec<NodeIndex>,
|
||||
pub elementwise_topo: Vec<NodeIndex>,
|
||||
/// FusionStart nodes that bound the region's leaves. One per external
|
||||
/// read site — duplicates (different FS LLIR nodes wrapping the same
|
||||
/// upstream tensor) are kept separate so each read uses its own
|
||||
@@ -79,13 +80,13 @@ pub(crate) enum CompileUnit {
|
||||
|
||||
/// Group a sub-DAG's topo order into compile units. Each FusionEnd node
|
||||
/// becomes the root of a `CompileUnit::Region`; the region's interior
|
||||
/// FusedX and FusionStart nodes are absorbed into that region and removed
|
||||
/// Cuda*Elementwise and FusionStart nodes are absorbed into that region and removed
|
||||
/// from the per-node iteration. Anything else is wrapped in
|
||||
/// `CompileUnit::Single`.
|
||||
/// Globally-absorbed FS / FE markers — the set of marker nodes that any
|
||||
/// `FusionEnd` in the LLIR walks back to during region detection. A
|
||||
/// marker is "absorbed" iff some FE in the LLIR can reach it by walking
|
||||
/// incoming edges through `FusionEnd` / `FusedX` nodes, stopping at
|
||||
/// incoming edges through `FusionEnd` / Cuda*Elementwise nodes, stopping at
|
||||
/// `FusionStart` leaves.
|
||||
///
|
||||
/// This is computed once over the full LLIR rather than per-convex-
|
||||
@@ -93,9 +94,8 @@ pub(crate) enum CompileUnit {
|
||||
/// (one whose e-graph congruence-deduplicated it across multiple
|
||||
/// regions) into a different subgraph than the FE that absorbs it.
|
||||
/// Without this global view, `build_compile_units` running on the FS's
|
||||
/// subgraph would not see any FE walking back to the FS, would emit the
|
||||
/// FS as `CompileUnit::Single`, and the markers' identity-memcpy
|
||||
/// fallback would compile and launch — pure overhead at runtime.
|
||||
/// subgraph would not see any FE walking back to the FS and would emit the
|
||||
/// FS as `CompileUnit::Single`; marker standalone compilation is not supported.
|
||||
pub(crate) fn globally_absorbed_markers(llir_graph: &LLIRGraph) -> FxHashSet<NodeIndex> {
|
||||
let name_of = |idx: NodeIndex| -> Option<&'static str> {
|
||||
llir_graph
|
||||
@@ -124,7 +124,7 @@ pub(crate) fn globally_absorbed_markers(llir_graph: &LLIRGraph) -> FxHashSet<Nod
|
||||
absorbed.insert(pred);
|
||||
stack.push(pred);
|
||||
}
|
||||
Some(other) if other.starts_with("Fused") => {
|
||||
Some(_) if is_region_elementwise(llir_graph, pred) => {
|
||||
absorbed.insert(pred);
|
||||
stack.push(pred);
|
||||
}
|
||||
@@ -188,19 +188,18 @@ pub(crate) fn build_compile_units(
|
||||
absorbed.insert(pred);
|
||||
stack.push(pred);
|
||||
}
|
||||
Some(other) if other.starts_with("Fused") => {
|
||||
Some(_) if is_region_elementwise(llir_graph, pred) => {
|
||||
interior.push(pred);
|
||||
stack.push(pred);
|
||||
}
|
||||
_ => {
|
||||
// Non-marker, non-FusedX predecessor inside what
|
||||
// Non-marker, non-elementwise predecessor inside what
|
||||
// we thought was a region. Shouldn't happen with
|
||||
// the current rules; treat conservatively: do
|
||||
// not absorb — let the kernel_to_host single
|
||||
// path handle it. This means the region is
|
||||
// not absorb it. This means the region is
|
||||
// malformed and we likely should not have a
|
||||
// region at all. Caller will see incomplete
|
||||
// interior; the safer thing is to fall back.
|
||||
// region at all; caller will see incomplete
|
||||
// interior.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -231,7 +230,56 @@ pub(crate) fn build_compile_units(
|
||||
llir_graph
|
||||
.neighbors_directed(fs, Direction::Incoming)
|
||||
.next()
|
||||
.expect("FusionStart with no predecessor")
|
||||
.unwrap_or_else(|| {
|
||||
// Dump the malformed structure: which FE
|
||||
// triggered the walk, every node in fs_topo and
|
||||
// interior_topo, and each FS's incoming /
|
||||
// outgoing degree. Helps localize whether the
|
||||
// missing edge came from extraction or a
|
||||
// downstream LLIR transform.
|
||||
if std::env::var("LUMINAL_DEBUG_FUSION_PANIC").is_ok() {
|
||||
eprintln!(
|
||||
"FusionStart panic: fe={} (kernel={:?})",
|
||||
node.index(),
|
||||
llir_graph.node_weight(node).and_then(|op| {
|
||||
op.to_dialect::<dyn KernelOp>().map(|k| k.kernel_name())
|
||||
}),
|
||||
);
|
||||
eprintln!(" fs_topo ({}):", fs_topo.len());
|
||||
for &f in &fs_topo {
|
||||
let in_deg = llir_graph
|
||||
.neighbors_directed(f, Direction::Incoming)
|
||||
.count();
|
||||
let out_deg = llir_graph
|
||||
.neighbors_directed(f, Direction::Outgoing)
|
||||
.count();
|
||||
let kn = llir_graph
|
||||
.node_weight(f)
|
||||
.and_then(|op| {
|
||||
op.to_dialect::<dyn KernelOp>().map(|k| k.kernel_name())
|
||||
})
|
||||
.unwrap_or("?");
|
||||
eprintln!(
|
||||
" fs={} kind={} in_deg={} out_deg={}",
|
||||
f.index(),
|
||||
kn,
|
||||
in_deg,
|
||||
out_deg,
|
||||
);
|
||||
}
|
||||
eprintln!(" interior_topo ({}):", interior_topo.len());
|
||||
for &i in &interior_topo {
|
||||
let kn = llir_graph
|
||||
.node_weight(i)
|
||||
.and_then(|op| {
|
||||
op.to_dialect::<dyn KernelOp>().map(|k| k.kernel_name())
|
||||
})
|
||||
.unwrap_or("?");
|
||||
eprintln!(" interior={} kind={}", i.index(), kn);
|
||||
}
|
||||
}
|
||||
panic!("FusionStart with no predecessor")
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -242,7 +290,7 @@ pub(crate) fn build_compile_units(
|
||||
node,
|
||||
RegionUnit {
|
||||
fe_node: node,
|
||||
fusedx_topo: interior_topo,
|
||||
elementwise_topo: interior_topo,
|
||||
fs_nodes: fs_topo,
|
||||
external_inputs,
|
||||
},
|
||||
@@ -253,11 +301,10 @@ pub(crate) fn build_compile_units(
|
||||
// FE nodes with their RegionUnit and skipping anything absorbed —
|
||||
// either by a region in *this* subgraph (`absorbed`) or by any
|
||||
// region anywhere in the LLIR (`globally_absorbed`). Skipping the
|
||||
// latter prevents the identity-memcpy fallback from firing on
|
||||
// shared FS markers whose consumers live in other convex subgraphs:
|
||||
// latter prevents shared FS markers whose consumers live in other
|
||||
// convex subgraphs from being emitted as standalone compile units:
|
||||
// those FSes are absorbed by some other region, and the consuming
|
||||
// region reads from FS's external producer, so the FS never needs
|
||||
// its own kernel.
|
||||
// region reads from FS's external producer.
|
||||
let mut units: Vec<CompileUnit> = Vec::new();
|
||||
for &node in topo_order {
|
||||
if let Some(region) = regions.remove(&node) {
|
||||
@@ -272,24 +319,54 @@ pub(crate) fn build_compile_units(
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Per-FusedX body templates.
|
||||
// Per-elementwise body templates.
|
||||
//
|
||||
// Each entry takes the names of the local variables holding the op's
|
||||
// inputs and returns a CUDA expression evaluating to the op's output
|
||||
// (a register-resident value, no buffer involved).
|
||||
// =========================================================================
|
||||
|
||||
fn fused_body(name: &str, locals: &[&str]) -> String {
|
||||
match name {
|
||||
"FusedSin" => format!("sinf({})", locals[0]),
|
||||
"FusedSqrt" => format!("sqrtf({})", locals[0]),
|
||||
"FusedExp" => format!("expf({})", locals[0]),
|
||||
"FusedExp2" => format!("exp2f({})", locals[0]),
|
||||
"FusedLog2" => format!("log2f({})", locals[0]),
|
||||
"FusedRecip" => format!("1.0f / {}", locals[0]),
|
||||
"FusedAdd" => format!("{} + {}", locals[0], locals[1]),
|
||||
"FusedMul" => format!("{} * {}", locals[0], locals[1]),
|
||||
other => panic!("region_codegen: unknown FusedX op {other}"),
|
||||
fn is_region_elementwise(llir_graph: &LLIRGraph, node: NodeIndex) -> bool {
|
||||
llir_graph
|
||||
.node_weight(node)
|
||||
.and_then(|op| op.to_dialect::<dyn KernelOp>())
|
||||
.is_some_and(|op| {
|
||||
(***op).downcast_ref::<CudaUnaryElementwise>().is_some()
|
||||
|| (***op).downcast_ref::<CudaBinaryElementwise>().is_some()
|
||||
})
|
||||
}
|
||||
|
||||
fn elementwise_value(local: &str, dtype: DType) -> String {
|
||||
if matches!(dtype, DType::F8E4M3 | DType::F8E5M2 | DType::F8UE8M0) {
|
||||
format!("static_cast<float>({local})")
|
||||
} else {
|
||||
local.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
fn elementwise_init_expr(expr: &str, dtype: DType, cuda_ty: &str) -> String {
|
||||
if matches!(dtype, DType::F8E4M3 | DType::F8E5M2 | DType::F8UE8M0) {
|
||||
format!("{cuda_ty}({expr})")
|
||||
} else {
|
||||
expr.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
fn elementwise_body(op: &str, locals: &[&str], dtype: DType) -> String {
|
||||
let a = || elementwise_value(locals[0], dtype);
|
||||
let b = || elementwise_value(locals[1], dtype);
|
||||
match op {
|
||||
"Sin" => format!("sinf({})", a()),
|
||||
"Sqrt" => format!("sqrtf({})", a()),
|
||||
"Rsqrt" => format!("rsqrtf({})", a()),
|
||||
"Exp" => format!("expf({})", a()),
|
||||
"Exp2" => format!("exp2f({})", a()),
|
||||
"Log2" => format!("log2f({})", a()),
|
||||
"Recip" => format!("1.0f / {}", a()),
|
||||
"Sigmoid" => format!("1.0f / (1.0f + expf(-{}))", a()),
|
||||
"Add" => format!("{} + {}", a(), b()),
|
||||
"Mul" => format!("{} * {}", a(), b()),
|
||||
other => panic!("region_codegen: unknown elementwise op {other}"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -327,7 +404,7 @@ pub(crate) fn compile_region(
|
||||
let dtype: DType = fe_struct.dtype;
|
||||
|
||||
// Aggregate all dynamic vars used anywhere in the region (FS strides,
|
||||
// FE strides, FusedX shape — all FusedX share `out_shape`, but their
|
||||
// FE strides and elementwise shapes.
|
||||
// own strides are likewise relevant for any future stride-affine ops).
|
||||
let mut all_vars: FxHashSet<char> = FxHashSet::default();
|
||||
all_vars.extend(out_shape.iter().flat_map(|e| e.dyn_vars()));
|
||||
@@ -337,6 +414,19 @@ pub(crate) fn compile_region(
|
||||
let fs_struct: &FusionStart = (***fs_op).downcast_ref::<FusionStart>().unwrap();
|
||||
all_vars.extend(fs_struct.strides.iter().flat_map(|e| e.dyn_vars()));
|
||||
}
|
||||
for &elem_idx in ®ion.elementwise_topo {
|
||||
let elem_op = llir_graph[elem_idx].to_dialect::<dyn KernelOp>().unwrap();
|
||||
if let Some(elem) = (***elem_op).downcast_ref::<CudaUnaryElementwise>() {
|
||||
all_vars.extend(elem.shape.iter().flat_map(|e| e.dyn_vars()));
|
||||
all_vars.extend(elem.in_strides.iter().flat_map(|e| e.dyn_vars()));
|
||||
all_vars.extend(elem.out_strides.iter().flat_map(|e| e.dyn_vars()));
|
||||
} else if let Some(elem) = (***elem_op).downcast_ref::<CudaBinaryElementwise>() {
|
||||
all_vars.extend(elem.out_shape.iter().flat_map(|e| e.dyn_vars()));
|
||||
all_vars.extend(elem.a_stride.iter().flat_map(|e| e.dyn_vars()));
|
||||
all_vars.extend(elem.b_stride.iter().flat_map(|e| e.dyn_vars()));
|
||||
all_vars.extend(elem.out_stride.iter().flat_map(|e| e.dyn_vars()));
|
||||
}
|
||||
}
|
||||
|
||||
let cuda_ty = cuda_dtype(dtype);
|
||||
let includes = dtype_includes(&[dtype]);
|
||||
@@ -362,19 +452,19 @@ pub(crate) fn compile_region(
|
||||
}
|
||||
let signature = signature_params.join(", ");
|
||||
|
||||
// Body: read FS leaves, then walk FusedX in topo order emitting a
|
||||
// Body: read FS leaves, then walk elementwise nodes in topo order emitting a
|
||||
// local per op, then write FE output. Every node gets a local keyed
|
||||
// by a position-in-region index so the kernel string is invariant
|
||||
// under NodeIndex churn (each `egglog_to_llir` reissues NodeIndexes,
|
||||
// so naming locals by `n.index()` would invalidate the kernel
|
||||
// string cache on every search candidate). Indices: FS leaves get
|
||||
// 0..fs_nodes.len(), FusedX get fs_nodes.len()..(+ fusedx_topo.len()).
|
||||
// 0..fs_nodes.len(), elementwise nodes get fs_nodes.len()..(+ elementwise_topo.len()).
|
||||
let mut local_idx_map: FxHashMap<NodeIndex, usize> = FxHashMap::default();
|
||||
for (i, &fs_idx) in region.fs_nodes.iter().enumerate() {
|
||||
local_idx_map.insert(fs_idx, i);
|
||||
}
|
||||
let fs_count = region.fs_nodes.len();
|
||||
for (i, &op_idx) in region.fusedx_topo.iter().enumerate() {
|
||||
for (i, &op_idx) in region.elementwise_topo.iter().enumerate() {
|
||||
local_idx_map.insert(op_idx, fs_count + i);
|
||||
}
|
||||
let local_name = |n: NodeIndex| format!("v_{}", local_idx_map[&n]);
|
||||
@@ -397,12 +487,22 @@ pub(crate) fn compile_region(
|
||||
));
|
||||
}
|
||||
|
||||
// FusedX ops in topo order. Each looks up its predecessor locals
|
||||
// Elementwise ops in topo order. Each looks up its predecessor locals
|
||||
// (in incoming-edge id order to match the original op's input
|
||||
// arity / position).
|
||||
for &op_idx in ®ion.fusedx_topo {
|
||||
for &op_idx in ®ion.elementwise_topo {
|
||||
let op_ref = llir_graph[op_idx].to_dialect::<dyn KernelOp>().unwrap();
|
||||
let op_name = op_ref.kernel_name();
|
||||
let (elem_name, elem_dtype) =
|
||||
if let Some(elem) = (***op_ref).downcast_ref::<CudaUnaryElementwise>() {
|
||||
(elem.op.as_str(), elem.dtype)
|
||||
} else if let Some(elem) = (***op_ref).downcast_ref::<CudaBinaryElementwise>() {
|
||||
(elem.op.as_str(), elem.dtype)
|
||||
} else {
|
||||
panic!(
|
||||
"region_codegen: expected Cuda*Elementwise op, got {}",
|
||||
op_ref.kernel_name()
|
||||
);
|
||||
};
|
||||
|
||||
let mut input_locals: Vec<String> = llir_graph
|
||||
.edges_directed(op_idx, Direction::Incoming)
|
||||
@@ -421,15 +521,16 @@ pub(crate) fn compile_region(
|
||||
input_locals = edges.into_iter().map(|(_, src)| local_name(src)).collect();
|
||||
let inputs_ref: Vec<&str> = input_locals.iter().map(|s| s.as_str()).collect();
|
||||
|
||||
let expr = fused_body(op_name, &inputs_ref);
|
||||
let expr = elementwise_body(elem_name, &inputs_ref, elem_dtype);
|
||||
let expr = elementwise_init_expr(&expr, elem_dtype, cuda_ty);
|
||||
body.push_str(&format!(
|
||||
" {cuda_ty} {name} = {expr};\n",
|
||||
name = local_name(op_idx),
|
||||
));
|
||||
}
|
||||
|
||||
// FE write: pick the FusedX feeding FE (its single incoming edge in
|
||||
// the region — a FusedX or, in degenerate single-FS regions which
|
||||
// FE write: pick the elementwise node feeding FE (its single incoming edge in
|
||||
// the region — an elementwise node or, in degenerate single-FS regions which
|
||||
// shouldn't arise, an FS).
|
||||
let fe_input: NodeIndex = llir_graph
|
||||
.neighbors_directed(region.fe_node, Direction::Incoming)
|
||||
@@ -477,3 +578,63 @@ pub(crate) fn compile_region(
|
||||
constants: FxHashMap::default(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::kernel::fusion::elementwise::CudaBinaryElementwise;
|
||||
use luminal::op::LLIROp;
|
||||
use luminal::prelude::petgraph::algo::toposort;
|
||||
|
||||
/// Helper: wrap a `KernelOp` in an `LLIROp` of the kernel dialect.
|
||||
fn llir_of(op: impl KernelOp + 'static) -> LLIROp {
|
||||
LLIROp::new::<dyn KernelOp>(Box::new(op) as Box<dyn KernelOp>)
|
||||
}
|
||||
|
||||
/// Reproducer for the `FusionStart with no predecessor` panic at
|
||||
/// `region_codegen.rs:232`. The egglog rolling pass + iterated mode
|
||||
/// (`LUMINAL_LOOP_ROLL_ITERATE=1`) has been observed to produce LLIR
|
||||
/// graphs where a `FusionStart` marker is reached as a region leaf
|
||||
/// during the FE→FS walk but has no incoming edge — meaning the
|
||||
/// region has nothing to read from. `build_compile_units` then
|
||||
/// panics when constructing `external_inputs` because every FS leaf
|
||||
/// is required to have exactly one external producer.
|
||||
///
|
||||
/// Until that path is fixed, this test pins the failure mode so a
|
||||
/// regression doesn't silently change the panic message or location.
|
||||
/// `should_panic` rather than `ignore` so it stays runnable in CI
|
||||
/// and surfaces if the panic ever moves.
|
||||
#[test]
|
||||
#[should_panic(expected = "FusionStart with no predecessor")]
|
||||
fn fusion_start_with_no_predecessor_panics() {
|
||||
// Minimal reproducer:
|
||||
//
|
||||
// (no input) ──▶ FusionStart ──▶ CudaBinaryElementwise ──▶ FusionEnd
|
||||
//
|
||||
// CudaBinaryElementwise is a binary op (n_inputs = 2) so a real region would
|
||||
// have two FS leaves. For this panic-shape test only the *first*
|
||||
// FS leaf needs a missing predecessor — `build_compile_units`
|
||||
// panics in `expect("FusionStart with no predecessor")` as soon
|
||||
// as any FS in `fs_topo` lacks one. We add only one FS edge so
|
||||
// CudaBinaryElementwise has a dangling second input slot, but that's fine:
|
||||
// we're testing the specific panic path inside `build_compile_units`,
|
||||
// not full kernel codegen.
|
||||
let mut llir: LLIRGraph = LLIRGraph::default();
|
||||
|
||||
let fs_node = llir.add_node(llir_of(FusionStart::default()));
|
||||
let fadd_node = llir.add_node(llir_of(CudaBinaryElementwise::default()));
|
||||
let fe_node = llir.add_node(llir_of(FusionEnd::default()));
|
||||
|
||||
// FusionStart → CudaBinaryElementwise → FusionEnd.
|
||||
llir.add_edge(fs_node, fadd_node, ());
|
||||
llir.add_edge(fadd_node, fe_node, ());
|
||||
|
||||
let topo = toposort(&llir, None).expect("LLIR cycle in test setup");
|
||||
let absorbed = globally_absorbed_markers(&llir);
|
||||
|
||||
// This is the call that panics with `FusionStart with no
|
||||
// predecessor` because `fs_node`'s incoming-edges iterator is
|
||||
// empty.
|
||||
let _ = build_compile_units(&topo, &llir, &absorbed);
|
||||
}
|
||||
}
|
||||
|
||||
319
crates/luminal_cuda_lite/src/kernel/generic_matmul.rs
Normal file
319
crates/luminal_cuda_lite/src/kernel/generic_matmul.rs
Normal file
@@ -0,0 +1,319 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::{
|
||||
compile_module_image_for_current_device, cuda_dtype,
|
||||
kernel::{
|
||||
KernelOp,
|
||||
hlir::{dtype_includes, generate_dyn_dims_defines},
|
||||
},
|
||||
};
|
||||
use cudarc::driver::{CudaFunction, CudaModule, CudaSlice, CudaStream};
|
||||
use luminal::{
|
||||
egglog_utils::{
|
||||
api::{Rule, SortDef, sort},
|
||||
base::{DTYPE, ELIST, EXPRESSION, OP_KIND},
|
||||
extract_dtype, extract_expr, extract_expr_list,
|
||||
},
|
||||
op::*,
|
||||
prelude::*,
|
||||
shape::flatten_strides,
|
||||
};
|
||||
|
||||
#[derive(Default, Debug, Clone)]
|
||||
pub struct GenericMatmul {
|
||||
out_shape: Vec<Expression>,
|
||||
mul_shape: Vec<Expression>,
|
||||
k: Expression,
|
||||
lhs_strides: Vec<Expression>,
|
||||
rhs_strides: Vec<Expression>,
|
||||
sum_input_strides: Vec<Expression>,
|
||||
sum_iter_stride: Expression,
|
||||
out_strides: Vec<Expression>,
|
||||
dtype: DType,
|
||||
}
|
||||
|
||||
impl EgglogOp for GenericMatmul {
|
||||
fn sort(&self) -> SortDef {
|
||||
sort(
|
||||
OP_KIND,
|
||||
"GenericMatmul",
|
||||
&[
|
||||
("out_shape", ELIST),
|
||||
("mul_shape", ELIST),
|
||||
("k", EXPRESSION),
|
||||
("lhs_strides", ELIST),
|
||||
("rhs_strides", ELIST),
|
||||
("sum_input_strides", ELIST),
|
||||
("sum_iter_stride", EXPRESSION),
|
||||
("out_strides", ELIST),
|
||||
("dtype", DTYPE),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
fn n_inputs(&self) -> usize {
|
||||
2
|
||||
}
|
||||
|
||||
fn rewrites(&self) -> Vec<Rule> {
|
||||
vec![
|
||||
Rule::raw(
|
||||
"(rule
|
||||
(
|
||||
(= ?mul (Op (Mul ?mul_shape ?lhs_strides ?rhs_strides ?mul_out_strides)
|
||||
(ICons ?lhs (ICons ?rhs (INil)))))
|
||||
(= ?sum (Op (Sum ?out_shape ?k ?sum_input_strides ?sum_iter_stride ?out_strides)
|
||||
(ICons ?mul (INil))))
|
||||
(= ?dt (dtype ?sum))
|
||||
)
|
||||
(
|
||||
(let ?generic (Op (GenericMatmul
|
||||
?out_shape
|
||||
?mul_shape
|
||||
?k
|
||||
?lhs_strides
|
||||
?rhs_strides
|
||||
?sum_input_strides
|
||||
?sum_iter_stride
|
||||
?out_strides
|
||||
?dt)
|
||||
(ICons ?lhs (ICons ?rhs (INil)))))
|
||||
(union ?sum ?generic)
|
||||
(set (dtype ?generic) ?dt)
|
||||
)
|
||||
:ruleset matmul_backend
|
||||
:name \"generic-matmul-cuda-mul-sum\"
|
||||
)",
|
||||
),
|
||||
Rule::raw(
|
||||
"(rule
|
||||
(
|
||||
(= ?mul (Op (Mul ?mul_shape ?lhs_strides ?rhs_strides ?mul_out_strides)
|
||||
(ICons ?lhs (ICons ?rhs (INil)))))
|
||||
(= ?sum (Op (Sum ?out_shape ?k ?sum_input_strides ?sum_iter_stride ?out_strides)
|
||||
(ICons ?mul (INil))))
|
||||
(= ?sum (Op (GenericMatmul
|
||||
?go ?gm ?gk ?gls ?grs ?gsis ?gsit ?gos ?gdt)
|
||||
?generic_inputs))
|
||||
)
|
||||
(
|
||||
(delete (Op (Sum ?out_shape ?k ?sum_input_strides ?sum_iter_stride ?out_strides)
|
||||
(ICons ?mul (INil))))
|
||||
)
|
||||
:ruleset cleanup
|
||||
:name \"delete-sum-when-generic-matmul-exists\"
|
||||
)",
|
||||
),
|
||||
Rule::raw(
|
||||
"(rule
|
||||
(
|
||||
(= ?kernel_sum (Op (KernelSum ?out_shape ?k ?sum_input_strides ?sum_iter_stride ?out_strides ?dt)
|
||||
?sum_inputs))
|
||||
(= ?kernel_sum (Op (GenericMatmul
|
||||
?go ?gm ?gk ?gls ?grs ?gsis ?gsit ?gos ?gdt)
|
||||
?generic_inputs))
|
||||
)
|
||||
((delete (Op (KernelSum ?out_shape ?k ?sum_input_strides ?sum_iter_stride ?out_strides ?dt)
|
||||
?sum_inputs)))
|
||||
:ruleset cleanup
|
||||
:name \"delete-kernel-sum-when-generic-matmul-exists\"
|
||||
)",
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
fn cleanup(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn extract<'a>(
|
||||
&'a self,
|
||||
egraph: &'a SerializedEGraph,
|
||||
kind_children: &[&'a ENodeId],
|
||||
input_enodes: Vec<&'a ENodeId>,
|
||||
list_cache: &mut FxHashMap<&'a ENodeId, Vec<Expression>>,
|
||||
expr_cache: &mut FxHashMap<&'a ENodeId, Expression>,
|
||||
) -> (LLIROp, Vec<&'a ENodeId>) {
|
||||
(
|
||||
LLIROp::new::<dyn KernelOp>(Box::new(Self {
|
||||
out_shape: extract_expr_list(egraph, kind_children[0], list_cache, expr_cache)
|
||||
.unwrap(),
|
||||
mul_shape: extract_expr_list(egraph, kind_children[1], list_cache, expr_cache)
|
||||
.unwrap(),
|
||||
k: extract_expr(egraph, kind_children[2], expr_cache).unwrap(),
|
||||
lhs_strides: extract_expr_list(egraph, kind_children[3], list_cache, expr_cache)
|
||||
.unwrap(),
|
||||
rhs_strides: extract_expr_list(egraph, kind_children[4], list_cache, expr_cache)
|
||||
.unwrap(),
|
||||
sum_input_strides: extract_expr_list(
|
||||
egraph,
|
||||
kind_children[5],
|
||||
list_cache,
|
||||
expr_cache,
|
||||
)
|
||||
.unwrap(),
|
||||
sum_iter_stride: extract_expr(egraph, kind_children[6], expr_cache).unwrap(),
|
||||
out_strides: extract_expr_list(egraph, kind_children[7], list_cache, expr_cache)
|
||||
.unwrap(),
|
||||
dtype: extract_dtype(egraph, kind_children[8]),
|
||||
})),
|
||||
input_enodes,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl KernelOp for GenericMatmul {
|
||||
fn compile(
|
||||
&self,
|
||||
stream: &Arc<CudaStream>,
|
||||
compile_cache: &mut FxHashMap<String, (Arc<CudaModule>, CudaFunction)>,
|
||||
) -> (
|
||||
CudaFunction,
|
||||
Arc<CudaModule>,
|
||||
String,
|
||||
(Expression, Expression, Expression),
|
||||
(Expression, Expression, Expression),
|
||||
Expression,
|
||||
FxHashMap<char, CudaSlice<u8>>,
|
||||
) {
|
||||
let vars = self.all_dyn_vars();
|
||||
let dtype = cuda_dtype(self.dtype);
|
||||
let includes = dtype_includes(&[self.dtype]);
|
||||
let (dyn_defines, _sorted_dims) = generate_dyn_dims_defines(&vars);
|
||||
let dyn_dims_param = if vars.is_empty() {
|
||||
""
|
||||
} else {
|
||||
", const int* dyn_dims"
|
||||
};
|
||||
|
||||
let n_outputs = self.output_size();
|
||||
let sum_base_idx = flatten_strides(&self.out_shape, &self.sum_input_strides).to_kernel();
|
||||
let iter_offset = self.sum_iter_stride.to_kernel().replace("const_z", "i");
|
||||
let lhs_idx = flatten_strides(&self.mul_shape, &self.lhs_strides)
|
||||
.to_kernel()
|
||||
.replace("const_z", "mul_idx");
|
||||
let rhs_idx = flatten_strides(&self.mul_shape, &self.rhs_strides)
|
||||
.to_kernel()
|
||||
.replace("const_z", "mul_idx");
|
||||
let out_idx = flatten_strides(&self.out_shape, &self.out_strides).to_kernel();
|
||||
let k = self.k.to_kernel();
|
||||
|
||||
let kernel = format!(
|
||||
"{includes}
|
||||
#define WARP_SIZE 32
|
||||
#define THREADS_PER_BLOCK 256
|
||||
#define FULL_MASK 0xffffffff
|
||||
{dyn_defines}
|
||||
extern \"C\" {{
|
||||
__global__ void generic_matmul({dtype} *out, const {dtype} *lhs, const {dtype} *rhs{dyn_dims_param}) {{
|
||||
__shared__ float warp_sums[THREADS_PER_BLOCK / WARP_SIZE];
|
||||
long long const_z = blockIdx.x;
|
||||
if (const_z >= {n_outputs}) return;
|
||||
|
||||
int tid = threadIdx.x;
|
||||
int lane_id = tid % WARP_SIZE;
|
||||
int warp_id = tid / WARP_SIZE;
|
||||
|
||||
long long base_idx = {sum_base_idx};
|
||||
long long iters = {k};
|
||||
|
||||
float partial = 0.0f;
|
||||
for (long long i = tid; i < iters; i += THREADS_PER_BLOCK) {{
|
||||
long long mul_idx = base_idx + {iter_offset};
|
||||
partial += static_cast<float>(lhs[{lhs_idx}]) * static_cast<float>(rhs[{rhs_idx}]);
|
||||
}}
|
||||
|
||||
#pragma unroll
|
||||
for (int s = WARP_SIZE / 2; s > 0; s >>= 1) {{
|
||||
partial += __shfl_down_sync(FULL_MASK, partial, s);
|
||||
}}
|
||||
|
||||
if (lane_id == 0) {{
|
||||
warp_sums[warp_id] = partial;
|
||||
}}
|
||||
__syncthreads();
|
||||
|
||||
if (warp_id == 0) {{
|
||||
float block_sum = tid < (THREADS_PER_BLOCK / WARP_SIZE) ? warp_sums[tid] : 0.0f;
|
||||
|
||||
#pragma unroll
|
||||
for (int s = (THREADS_PER_BLOCK / WARP_SIZE) / 2; s > 0; s >>= 1) {{
|
||||
block_sum += __shfl_down_sync(FULL_MASK, block_sum, s);
|
||||
}}
|
||||
|
||||
if (tid == 0) {{
|
||||
out[{out_idx}] = ({dtype})block_sum;
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
}}",
|
||||
n_outputs = n_outputs.to_kernel(),
|
||||
);
|
||||
|
||||
let (module, func) = if let Some((module, func)) = compile_cache.get(&kernel) {
|
||||
(module.clone(), func.clone())
|
||||
} else {
|
||||
let ptx = compile_module_image_for_current_device(stream.context(), &kernel).unwrap();
|
||||
let module = stream.context().load_module(ptx).unwrap();
|
||||
let func = module.load_function("generic_matmul").unwrap();
|
||||
compile_cache.insert(kernel.clone(), (module.clone(), func.clone()));
|
||||
(module, func)
|
||||
};
|
||||
|
||||
(
|
||||
func,
|
||||
module,
|
||||
kernel,
|
||||
(n_outputs, 1.into(), 1.into()),
|
||||
(256.into(), 1.into(), 1.into()),
|
||||
32.into(),
|
||||
FxHashMap::default(),
|
||||
)
|
||||
}
|
||||
|
||||
fn output_size(&self) -> Expression {
|
||||
self.out_shape
|
||||
.iter()
|
||||
.copied()
|
||||
.product::<Expression>()
|
||||
.max(Expression::from(1))
|
||||
}
|
||||
|
||||
fn all_dyn_vars(&self) -> FxHashSet<char> {
|
||||
self.out_shape
|
||||
.iter()
|
||||
.flat_map(|e| e.dyn_vars())
|
||||
.chain(self.mul_shape.iter().flat_map(|e| e.dyn_vars()))
|
||||
.chain(self.k.dyn_vars())
|
||||
.chain(self.lhs_strides.iter().flat_map(|e| e.dyn_vars()))
|
||||
.chain(self.rhs_strides.iter().flat_map(|e| e.dyn_vars()))
|
||||
.chain(self.sum_input_strides.iter().flat_map(|e| e.dyn_vars()))
|
||||
.chain(self.sum_iter_stride.dyn_vars())
|
||||
.chain(self.out_strides.iter().flat_map(|e| e.dyn_vars()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn output_bytes(&self) -> Expression {
|
||||
(self.output_size() * self.dtype.bits()).ceil_div(8)
|
||||
}
|
||||
|
||||
fn bytes_loaded(&self) -> Expression {
|
||||
(self.output_size() * self.k * self.dtype.bits() * 2).ceil_div(8)
|
||||
}
|
||||
|
||||
fn bytes_stored(&self) -> Expression {
|
||||
self.output_bytes()
|
||||
}
|
||||
|
||||
fn flops(&self) -> Expression {
|
||||
self.output_size() * self.k * 2
|
||||
}
|
||||
|
||||
fn output_dtype(&self) -> DType {
|
||||
self.dtype
|
||||
}
|
||||
|
||||
fn kernel_name(&self) -> &'static str {
|
||||
"GenericMatmul"
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
427
crates/luminal_cuda_lite/src/kernel/matmul2d.rs
Normal file
427
crates/luminal_cuda_lite/src/kernel/matmul2d.rs
Normal file
@@ -0,0 +1,427 @@
|
||||
//! Direct 2D matmul kernel — bypasses egglog rewrites, used as a custom op
|
||||
//! for matmul shapes where the cublaslt egg rules don't reliably fire.
|
||||
//!
|
||||
//! The cublaslt 2D rules in `host/cublaslt/cublaslt_*Cm_rewrite.egg` /
|
||||
//! `cublaslt_Rm*_rewrite.egg` are *supposed* to match any 2D matmul whose
|
||||
//! Mul + SumReduce broadcast lowering has the expected stride patterns,
|
||||
//! and the conditional matmul cleanup is *supposed* to delete the
|
||||
//! elementwise Mul + KernelSumReduce fallback whenever a cublaslt alternative
|
||||
//! exists. In practice both fail to fire reliably for the VAE's mid-block
|
||||
//! `AttnBlock` matmuls — at 1024² that lets the search occasionally pick
|
||||
//! the broadcast-Mul path for `q @ kᵀ`, generating a `(HW, HW, C) =
|
||||
//! (16384, 16384, 512)` ≈ 524 GiB single intermediate that OOMs the GPU.
|
||||
//!
|
||||
//! Same approach as `kernel::conv2d`: define a `KernelOp`, wrap it in a
|
||||
//! `CustomOp`, expose a tiny `pub fn` so callers don't see the
|
||||
//! `cx.custom_op` plumbing. This is opaque to egglog by design — we
|
||||
//! aren't trying to fuse with surrounding ops, just guarantee a sane
|
||||
//! lowering for the matmuls we know are problematic.
|
||||
//!
|
||||
//! The CUDA implementation is a textbook 2D-blocked SGEMM:
|
||||
//! * 16×16 output tile per block (256 threads)
|
||||
//! * Tiled load of A and B into shared memory in K-size chunks
|
||||
//! * Each thread accumulates one output element across all K-tiles
|
||||
//! * Optional bias broadcast along the M axis at write-out
|
||||
//! * `transpose_b` toggles between row-major B `(K, N)` and row-major
|
||||
//! B `(N, K)` (i.e. the `A @ Bᵀ` pattern that linear/projection
|
||||
//! layers use).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use cudarc::driver::{CudaFunction, CudaModule, CudaSlice, CudaStream};
|
||||
use luminal::{
|
||||
dtype::DType, op::CustomOp, op::LLIROp, prelude::FxHashMap, prelude::GraphTensor,
|
||||
shape::Expression,
|
||||
};
|
||||
|
||||
use crate::compile_module_image_for_current_device;
|
||||
use crate::kernel::KernelOp;
|
||||
|
||||
/// Direct 2D matmul `(M, K) × {(K, N) | (N, K)} → (M, N)` with optional
|
||||
/// per-output-column bias and an optional batch axis. A and output are
|
||||
/// always F32. B can be F32 or BF16; BF16 is converted to F32 on each
|
||||
/// load, which avoids materializing the cast as a separate intermediate
|
||||
/// tensor (important for the text encoder / transformer where the F32-
|
||||
/// cast weights would not fit in GPU memory). All shape parameters are
|
||||
/// static (baked into the CUDA source via #defines).
|
||||
///
|
||||
/// When `batch > 1` the kernel does `batch` independent 2D matmuls in
|
||||
/// parallel: A is `(batch, M, K)`, B is `(batch, *, *)` with the same
|
||||
/// per-batch shape, output is `(batch, M, N)`. All three are assumed
|
||||
/// contiguous row-major across batches (i.e. `a_batch_stride = M*K`,
|
||||
/// `b_batch_stride = K*N` or `N*K` depending on `transpose_b`,
|
||||
/// `out_batch_stride = M*N`). Bias does NOT have a batch axis — it's
|
||||
/// `(N,)` and broadcast across batches.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Matmul2DKernel {
|
||||
pub m: usize,
|
||||
pub n: usize,
|
||||
pub k: usize,
|
||||
pub batch: usize,
|
||||
/// If `true`, B is interpreted as `(N, K)` row-major and accessed as
|
||||
/// `B[n][k]` (i.e. `A @ Bᵀ`). If `false`, B is `(K, N)` row-major and
|
||||
/// accessed as `B[k][n]` (i.e. `A @ B`).
|
||||
pub transpose_b: bool,
|
||||
pub has_bias: bool,
|
||||
/// Storage dtype of B. Currently F32 or BF16 are supported.
|
||||
pub weight_dtype: DType,
|
||||
}
|
||||
|
||||
const TILE: usize = 16;
|
||||
|
||||
impl KernelOp for Matmul2DKernel {
|
||||
fn compile(
|
||||
&self,
|
||||
stream: &Arc<CudaStream>,
|
||||
compile_cache: &mut FxHashMap<String, (Arc<CudaModule>, CudaFunction)>,
|
||||
) -> (
|
||||
CudaFunction,
|
||||
Arc<CudaModule>,
|
||||
String,
|
||||
(Expression, Expression, Expression),
|
||||
(Expression, Expression, Expression),
|
||||
Expression,
|
||||
FxHashMap<char, CudaSlice<u8>>,
|
||||
) {
|
||||
let bias_param = if self.has_bias {
|
||||
", const float* __restrict__ bias"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let bias_add = if self.has_bias {
|
||||
" acc += bias[n];\n"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
// We want Bs[ty][tx] = B_effective[k0+ty][b_n_base+tx] where:
|
||||
// transpose_b=false: B is (K, N) row-major → B[(k0+ty)*N + (b_n_base+tx)]
|
||||
// transpose_b=true: B is (N, K) row-major → B[(b_n_base+tx)*K + (k0+ty)]
|
||||
// Plus the per-batch offset (`b_batch_off`).
|
||||
let b_index_expr = if self.transpose_b {
|
||||
"b_batch_off + (b_n_base + tx) * K + (k0 + ty)"
|
||||
} else {
|
||||
"b_batch_off + (k0 + ty) * N + (b_n_base + tx)"
|
||||
};
|
||||
// Convert B's element to float on load. For BF16 we declare B as
|
||||
// `__nv_bfloat16*` and use `__bfloat162float`; for F32 it's a no-op.
|
||||
let (b_param_type, b_load_expr, bf16_include) = match self.weight_dtype {
|
||||
DType::F32 => (
|
||||
"const float* __restrict__ B",
|
||||
format!("B[{b_index_expr}]"),
|
||||
"",
|
||||
),
|
||||
DType::Bf16 => (
|
||||
"const __nv_bfloat16* __restrict__ B",
|
||||
format!("__bfloat162float(B[{b_index_expr}])"),
|
||||
"#include <cuda_bf16.h>\n",
|
||||
),
|
||||
other => panic!("Matmul2DKernel: unsupported weight_dtype {other:?}"),
|
||||
};
|
||||
|
||||
let kernel = format!(
|
||||
"
|
||||
{bf16_include}extern \"C\" __global__ void matmul_2d_kernel(
|
||||
float* __restrict__ C,
|
||||
const float* __restrict__ A,
|
||||
{b_param_type}{bias_param}
|
||||
) {{
|
||||
const int M = {m};
|
||||
const int N = {n};
|
||||
const int K = {k};
|
||||
const int TILE = {tile};
|
||||
|
||||
__shared__ float As[{tile}][{tile}];
|
||||
__shared__ float Bs[{tile}][{tile}];
|
||||
|
||||
int bx = blockIdx.x; // tile column (n)
|
||||
int by = blockIdx.y; // tile row (m)
|
||||
int batch = blockIdx.z; // batch index (0..BATCH-1)
|
||||
int tx = threadIdx.x; // 0..TILE-1, output col within tile
|
||||
int ty = threadIdx.y; // 0..TILE-1, output row within tile
|
||||
|
||||
int m_global = by * TILE + ty;
|
||||
int n_global = bx * TILE + tx;
|
||||
|
||||
int a_m_base = by * TILE;
|
||||
int b_n_base = bx * TILE;
|
||||
|
||||
// Per-batch base pointer offsets (contiguous row-major across batches).
|
||||
int a_batch_off = batch * (M * K);
|
||||
int b_batch_off = batch * (K * N);
|
||||
int c_batch_off = batch * (M * N);
|
||||
|
||||
float acc = 0.0f;
|
||||
|
||||
int n_tiles = (K + TILE - 1) / TILE;
|
||||
for (int t = 0; t < n_tiles; ++t) {{
|
||||
int k0 = t * TILE;
|
||||
|
||||
// Load A tile (TILE, TILE) row-major from A[m, k]: A[(by*TILE+ty)*K + (k0+tx)]
|
||||
int a_m = a_m_base + ty;
|
||||
int a_k = k0 + tx;
|
||||
As[ty][tx] = (a_m < M && a_k < K) ? A[a_batch_off + a_m * K + a_k] : 0.0f;
|
||||
|
||||
// Load B tile depending on transpose_b
|
||||
int b_n_or_k = b_n_base + tx; // for transpose_b=true this is N; for =false this is N
|
||||
int b_k_or_k = k0 + ty; // similarly
|
||||
// We compute Bs[ty][tx] such that the inner loop reads Bs[k_local][n_local] = B[k][n].
|
||||
// For transpose_b=true (B is (N,K)): B[k][n] in math = B_storage[n][k] = B[(b_n_base+tx)*K + (k0+ty)]
|
||||
// For transpose_b=false (B is (K,N)): B[k][n] in math = B_storage[k][n] = B[(k0+ty)*N + (b_n_base+tx)]
|
||||
bool b_in_bounds = ({transpose_b} ? (b_n_or_k < N && b_k_or_k < K)
|
||||
: (b_k_or_k < K && b_n_or_k < N));
|
||||
Bs[ty][tx] = b_in_bounds ? ({b_load_expr}) : 0.0f;
|
||||
|
||||
__syncthreads();
|
||||
|
||||
#pragma unroll
|
||||
for (int kk = 0; kk < {tile}; ++kk) {{
|
||||
acc += As[ty][kk] * Bs[kk][tx];
|
||||
}}
|
||||
__syncthreads();
|
||||
}}
|
||||
|
||||
if (m_global < M && n_global < N) {{
|
||||
int n = n_global;
|
||||
{bias_add} C[c_batch_off + m_global * N + n_global] = acc;
|
||||
}}
|
||||
}}
|
||||
",
|
||||
m = self.m,
|
||||
n = self.n,
|
||||
k = self.k,
|
||||
tile = TILE,
|
||||
transpose_b = self.transpose_b,
|
||||
b_load_expr = b_load_expr,
|
||||
b_param_type = b_param_type,
|
||||
bias_param = bias_param,
|
||||
bias_add = bias_add,
|
||||
bf16_include = bf16_include,
|
||||
);
|
||||
|
||||
let (module, func) = if let Some((m, f)) = compile_cache.get(&kernel) {
|
||||
(m.clone(), f.clone())
|
||||
} else {
|
||||
let ptx = compile_module_image_for_current_device(stream.context(), &kernel).unwrap();
|
||||
let module = stream.context().load_module(ptx).unwrap();
|
||||
let func = module.load_function("matmul_2d_kernel").unwrap();
|
||||
compile_cache.insert(kernel.clone(), (module.clone(), func.clone()));
|
||||
(module, func)
|
||||
};
|
||||
|
||||
let grid_x = self.n.div_ceil(TILE);
|
||||
let grid_y = self.m.div_ceil(TILE);
|
||||
(
|
||||
func,
|
||||
module,
|
||||
kernel,
|
||||
(
|
||||
Expression::from(grid_x),
|
||||
Expression::from(grid_y),
|
||||
Expression::from(self.batch),
|
||||
),
|
||||
(
|
||||
Expression::from(TILE),
|
||||
Expression::from(TILE),
|
||||
Expression::from(1usize),
|
||||
),
|
||||
Expression::from(0usize),
|
||||
FxHashMap::default(),
|
||||
)
|
||||
}
|
||||
|
||||
fn output_size(&self) -> Expression {
|
||||
Expression::from(self.batch * self.m * self.n)
|
||||
}
|
||||
|
||||
fn output_bytes(&self) -> Expression {
|
||||
self.output_size() * 4
|
||||
}
|
||||
|
||||
fn output_dtype(&self) -> DType {
|
||||
DType::F32
|
||||
}
|
||||
|
||||
fn bytes_loaded(&self) -> Expression {
|
||||
// K elements from A (F32) + K elements from B (F32 or BF16) + maybe bias (F32).
|
||||
let b_bytes = match self.weight_dtype {
|
||||
DType::F32 => 4,
|
||||
DType::Bf16 => 2,
|
||||
_ => 4,
|
||||
};
|
||||
let bias_bytes = if self.has_bias { 4 } else { 0 };
|
||||
Expression::from(
|
||||
self.batch * self.m * self.n * (self.k * 4 + self.k * b_bytes + bias_bytes),
|
||||
)
|
||||
}
|
||||
|
||||
fn bytes_stored(&self) -> Expression {
|
||||
self.output_size() * 4
|
||||
}
|
||||
|
||||
fn flops(&self) -> Expression {
|
||||
let per_out = self.k * 2 + if self.has_bias { 1 } else { 0 };
|
||||
Expression::from(self.batch * self.m * self.n * per_out)
|
||||
}
|
||||
|
||||
fn kernel_name(&self) -> &'static str {
|
||||
"Matmul2D"
|
||||
}
|
||||
}
|
||||
|
||||
/// CustomOp wrapper for [`Matmul2DKernel`].
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Matmul2DCustom(pub Matmul2DKernel);
|
||||
|
||||
impl CustomOp for Matmul2DCustom {
|
||||
fn to_llir_op(&self) -> LLIROp {
|
||||
LLIROp::new::<dyn KernelOp>(Box::new(self.0.clone()) as Box<dyn KernelOp>)
|
||||
}
|
||||
}
|
||||
|
||||
/// `(M, K) @ (K, N) -> (M, N)` for row-major F32 inputs. No bias.
|
||||
pub fn matmul_2d(a: GraphTensor, b: GraphTensor) -> GraphTensor {
|
||||
matmul_inner(a, b, /*transpose_b=*/ false, None)
|
||||
}
|
||||
|
||||
/// `(M, K) @ (N, K)ᵀ -> (M, N)` for row-major F32 inputs. No bias.
|
||||
/// Use this for `A @ Bᵀ` where B is stored row-major as `(N, K)` — the
|
||||
/// pattern produced by linear / projection layers (`x @ w.t()`).
|
||||
pub fn matmul_2d_t(a: GraphTensor, b: GraphTensor) -> GraphTensor {
|
||||
matmul_inner(a, b, /*transpose_b=*/ true, None)
|
||||
}
|
||||
|
||||
/// Linear projection with bias: `(M, K) @ (N, K)ᵀ + bias` where bias is
|
||||
/// `(N,)`, row-major F32 throughout.
|
||||
pub fn linear_bias(a: GraphTensor, b: GraphTensor, bias: GraphTensor) -> GraphTensor {
|
||||
matmul_inner(a, b, /*transpose_b=*/ true, Some(bias))
|
||||
}
|
||||
|
||||
/// Mixed-precision linear (no bias): `A (F32, M, K) @ B (BF16, N, K)ᵀ → (F32, M, N)`.
|
||||
///
|
||||
/// Lowers as plain HLIR — `Cast(A, BF16) @ permute(B_bf16) → Cast(F32)`.
|
||||
/// The activation cast and output cast are tiny (M*K and M*N elements;
|
||||
/// the K=hidden weight stays BF16). The inner BF16 matmul matches the
|
||||
/// existing cublaslt rewrite rules and runs as
|
||||
/// `CUBLAS_COMPUTE_32F_FAST_16BF` — Hopper's native 2× BF16 path.
|
||||
pub fn linear_no_bias_bf16_w(a: GraphTensor, b_bf16: GraphTensor) -> GraphTensor {
|
||||
assert_eq!(a.dtype, DType::F32, "linear_no_bias_bf16_w expects F32 A");
|
||||
assert_eq!(
|
||||
b_bf16.dtype,
|
||||
DType::Bf16,
|
||||
"linear_no_bias_bf16_w expects BF16 B"
|
||||
);
|
||||
let a_dims = a.dims();
|
||||
let b_dims = b_bf16.dims();
|
||||
assert_eq!(a_dims.len(), 2);
|
||||
assert_eq!(b_dims.len(), 2);
|
||||
let a_bf16 = a.cast(DType::Bf16);
|
||||
let b_kn = b_bf16.permute((1, 0));
|
||||
a_bf16.matmul(b_kn).cast(DType::F32)
|
||||
}
|
||||
|
||||
/// Batched matmul: `A (B, M, K) @ B (B, K, N) → (B, M, N)`, all F32 row-major.
|
||||
pub fn matmul_3d(a: GraphTensor, b: GraphTensor) -> GraphTensor {
|
||||
matmul_inner(a, b, /*transpose_b=*/ false, None)
|
||||
}
|
||||
|
||||
/// Batched matmul with B-transpose: `A (B, M, K) @ B (B, N, K)ᵀ → (B, M, N)`.
|
||||
pub fn matmul_3d_t(a: GraphTensor, b: GraphTensor) -> GraphTensor {
|
||||
matmul_inner(a, b, /*transpose_b=*/ true, None)
|
||||
}
|
||||
|
||||
fn matmul_inner(
|
||||
a: GraphTensor,
|
||||
b: GraphTensor,
|
||||
transpose_b: bool,
|
||||
bias: Option<GraphTensor>,
|
||||
) -> GraphTensor {
|
||||
assert_eq!(a.dtype, DType::F32, "matmul requires F32 A");
|
||||
let weight_dtype = b.dtype;
|
||||
assert!(
|
||||
matches!(weight_dtype, DType::F32 | DType::Bf16),
|
||||
"matmul B must be F32 or BF16, got {weight_dtype:?}",
|
||||
);
|
||||
let a_dims = a.dims();
|
||||
let b_dims = b.dims();
|
||||
assert_eq!(
|
||||
a_dims.len(),
|
||||
b_dims.len(),
|
||||
"matmul A/B rank mismatch: {} vs {}",
|
||||
a_dims.len(),
|
||||
b_dims.len(),
|
||||
);
|
||||
assert!(
|
||||
a_dims.len() == 2 || a_dims.len() == 3,
|
||||
"matmul expects rank 2 or 3, got rank {}",
|
||||
a_dims.len(),
|
||||
);
|
||||
|
||||
let (batch, a_off) = if a_dims.len() == 3 {
|
||||
let ba = a_dims[0].to_usize().expect("batch dim must be static");
|
||||
let bb = b_dims[0].to_usize().expect("batch dim must be static");
|
||||
assert_eq!(
|
||||
ba, bb,
|
||||
"matmul batch dim mismatch: A batch={ba}, B batch={bb}"
|
||||
);
|
||||
(ba, 1)
|
||||
} else {
|
||||
(1, 0)
|
||||
};
|
||||
|
||||
let m = a_dims[a_off].to_usize().expect("M must be a static dim");
|
||||
let k_a = a_dims[a_off + 1]
|
||||
.to_usize()
|
||||
.expect("K (A) must be a static dim");
|
||||
let (n, k_b) = if transpose_b {
|
||||
// B per-batch is (N, K)
|
||||
let n = b_dims[a_off].to_usize().expect("N must be a static dim");
|
||||
let k = b_dims[a_off + 1]
|
||||
.to_usize()
|
||||
.expect("K (B) must be a static dim");
|
||||
(n, k)
|
||||
} else {
|
||||
// B per-batch is (K, N)
|
||||
let k = b_dims[a_off]
|
||||
.to_usize()
|
||||
.expect("K (B) must be a static dim");
|
||||
let n = b_dims[a_off + 1]
|
||||
.to_usize()
|
||||
.expect("N must be a static dim");
|
||||
(n, k)
|
||||
};
|
||||
assert_eq!(k_a, k_b, "matmul K mismatch: A K={k_a}, B K={k_b}");
|
||||
let k = k_a;
|
||||
|
||||
let has_bias = bias.is_some();
|
||||
if let Some(bias) = bias {
|
||||
let bdims = bias.dims();
|
||||
assert_eq!(bdims.len(), 1, "matmul bias must be 1D");
|
||||
assert_eq!(
|
||||
bdims[0].to_usize().expect("bias dim must be static"),
|
||||
n,
|
||||
"matmul bias size must equal N"
|
||||
);
|
||||
assert_eq!(bias.dtype, DType::F32, "matmul bias must be F32");
|
||||
}
|
||||
|
||||
let kern = Matmul2DKernel {
|
||||
m,
|
||||
n,
|
||||
k,
|
||||
batch,
|
||||
transpose_b,
|
||||
has_bias,
|
||||
weight_dtype,
|
||||
};
|
||||
let cx = unsafe { &mut *a.graph_ref };
|
||||
let inputs: Vec<GraphTensor> = if let Some(bias) = bias {
|
||||
vec![a, b, bias]
|
||||
} else {
|
||||
vec![a, b]
|
||||
};
|
||||
if batch == 1 {
|
||||
cx.custom_op(Matmul2DCustom(kern), inputs, (m, n), DType::F32)
|
||||
} else {
|
||||
cx.custom_op(Matmul2DCustom(kern), inputs, (batch, m, n), DType::F32)
|
||||
}
|
||||
}
|
||||
@@ -9,14 +9,31 @@ use luminal_tracing::schema::{
|
||||
};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub mod conv2d;
|
||||
pub mod cuda_graph;
|
||||
pub mod fusion;
|
||||
pub mod generic_matmul;
|
||||
pub mod hlir;
|
||||
pub mod matmul2d;
|
||||
pub mod other_ops;
|
||||
pub mod rope;
|
||||
|
||||
pub use conv2d::KernelConv2D;
|
||||
pub use cuda_graph::*;
|
||||
pub use generic_matmul::GenericMatmul;
|
||||
pub use matmul2d::{
|
||||
Matmul2DCustom, Matmul2DKernel, linear_bias, linear_no_bias_bf16_w, matmul_2d, matmul_2d_t,
|
||||
matmul_3d, matmul_3d_t,
|
||||
};
|
||||
pub use rope::{RoPECustom, RoPEKernel, apply_rope};
|
||||
|
||||
pub type Ops = (hlir::Ops, other_ops::Ops, fusion::Ops);
|
||||
pub type Ops = (
|
||||
hlir::Ops,
|
||||
other_ops::Ops,
|
||||
conv2d::KernelConv2D,
|
||||
GenericMatmul,
|
||||
fusion::Ops,
|
||||
);
|
||||
|
||||
/// Build a mapping from interned string IDs to their string values for a given sequence.
|
||||
fn build_interned_strings(trace: &schema::Trace) -> std::collections::HashMap<(u32, u64), String> {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
189
crates/luminal_cuda_lite/src/kernel/rope.rs
Normal file
189
crates/luminal_cuda_lite/src/kernel/rope.rs
Normal file
@@ -0,0 +1,189 @@
|
||||
//! Fused RoPE (rotary position embedding) — interleaved-pair convention.
|
||||
//!
|
||||
//! Replaces flux2's 6-op RoPE chain (split / slice / squeeze / neg / concat /
|
||||
//! merge_dims / 4× cast / mul / add) with a single kernel launch per call.
|
||||
//! ~120 RoPE calls per forward pass at full DiT depth.
|
||||
//!
|
||||
//! Convention: `repeat_interleave_real=True` (Flux 2 / diffusers), so adjacent
|
||||
//! dim pairs rotate together. For an input `[a0, b0, a1, b1, ...]` and per-
|
||||
//! position `(cos, sin)`, the output is
|
||||
//! `out[2j] = x[2j] * cos[2j] - x[2j+1] * sin[2j]`
|
||||
//! `out[2j+1] = x[2j+1] * cos[2j+1] + x[2j] * sin[2j+1]`
|
||||
//!
|
||||
//! Layout: x `(S, H, D)`, cos/sin `(S, D)` (broadcast across H).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use cudarc::driver::{CudaFunction, CudaModule, CudaSlice, CudaStream};
|
||||
use luminal::{
|
||||
dtype::DType, op::CustomOp, op::LLIROp, prelude::FxHashMap, prelude::GraphTensor,
|
||||
shape::Expression,
|
||||
};
|
||||
|
||||
use crate::compile_module_image_for_current_device;
|
||||
use crate::kernel::KernelOp;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RoPEKernel {
|
||||
pub s: usize,
|
||||
pub h: usize,
|
||||
pub d: usize,
|
||||
}
|
||||
|
||||
const TPB: usize = 64;
|
||||
|
||||
impl KernelOp for RoPEKernel {
|
||||
fn compile(
|
||||
&self,
|
||||
stream: &Arc<CudaStream>,
|
||||
compile_cache: &mut FxHashMap<String, (Arc<CudaModule>, CudaFunction)>,
|
||||
) -> (
|
||||
CudaFunction,
|
||||
Arc<CudaModule>,
|
||||
String,
|
||||
(Expression, Expression, Expression),
|
||||
(Expression, Expression, Expression),
|
||||
Expression,
|
||||
FxHashMap<char, CudaSlice<u8>>,
|
||||
) {
|
||||
let s = self.s;
|
||||
let h = self.h;
|
||||
let d = self.d;
|
||||
assert!(d.is_multiple_of(2), "RoPE head_dim must be even");
|
||||
let kernel = format!(
|
||||
r#"
|
||||
extern "C" __global__ void rope_kernel(
|
||||
float* __restrict__ out,
|
||||
const float* __restrict__ x,
|
||||
const float* __restrict__ cos_,
|
||||
const float* __restrict__ sin_
|
||||
) {{
|
||||
const int S = {s};
|
||||
const int H = {h};
|
||||
const int D = {d};
|
||||
int sh = blockIdx.x; // 0..S*H
|
||||
int s_idx = sh / H;
|
||||
int tid = threadIdx.x;
|
||||
|
||||
const float* xr = x + sh * D;
|
||||
const float* cosr = cos_ + s_idx * D;
|
||||
const float* sinr = sin_ + s_idx * D;
|
||||
float* yr = out + sh * D;
|
||||
|
||||
for (int i = tid; i < D; i += {TPB}) {{
|
||||
float xi = xr[i];
|
||||
float xpair;
|
||||
if ((i & 1) == 0) {{
|
||||
// even: paired with i+1, rotated value is -x[i+1]
|
||||
xpair = -xr[i + 1];
|
||||
}} else {{
|
||||
// odd: paired with i-1, rotated value is +x[i-1]
|
||||
xpair = xr[i - 1];
|
||||
}}
|
||||
yr[i] = xi * cosr[i] + xpair * sinr[i];
|
||||
}}
|
||||
}}
|
||||
"#
|
||||
);
|
||||
|
||||
let (module, func) = if let Some((m, f)) = compile_cache.get(&kernel) {
|
||||
(m.clone(), f.clone())
|
||||
} else {
|
||||
let ptx = compile_module_image_for_current_device(stream.context(), &kernel).unwrap();
|
||||
let module = stream.context().load_module(ptx).unwrap();
|
||||
let func = module.load_function("rope_kernel").unwrap();
|
||||
compile_cache.insert(kernel.clone(), (module.clone(), func.clone()));
|
||||
(module, func)
|
||||
};
|
||||
|
||||
(
|
||||
func,
|
||||
module,
|
||||
"rope_kernel".to_string(),
|
||||
(
|
||||
Expression::from(s * h),
|
||||
Expression::from(1usize),
|
||||
Expression::from(1usize),
|
||||
),
|
||||
(
|
||||
Expression::from(TPB),
|
||||
Expression::from(1usize),
|
||||
Expression::from(1usize),
|
||||
),
|
||||
Expression::from(0usize),
|
||||
FxHashMap::default(),
|
||||
)
|
||||
}
|
||||
|
||||
fn output_size(&self) -> Expression {
|
||||
Expression::from(self.s * self.h * self.d)
|
||||
}
|
||||
|
||||
fn output_bytes(&self) -> Expression {
|
||||
self.output_size() * 4
|
||||
}
|
||||
|
||||
fn output_dtype(&self) -> DType {
|
||||
DType::F32
|
||||
}
|
||||
|
||||
fn bytes_loaded(&self) -> Expression {
|
||||
// x: full (S,H,D); cos/sin: (S,D) read H times each but cached.
|
||||
Expression::from(self.s * self.h * self.d * 4 + self.s * self.d * 4 * 2)
|
||||
}
|
||||
|
||||
fn bytes_stored(&self) -> Expression {
|
||||
self.output_size() * 4
|
||||
}
|
||||
|
||||
fn flops(&self) -> Expression {
|
||||
// 4 per output element (mul, neg/load, mul, add).
|
||||
Expression::from(self.s * self.h * self.d * 4)
|
||||
}
|
||||
|
||||
fn kernel_name(&self) -> &'static str {
|
||||
"RoPE"
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RoPECustom(pub RoPEKernel);
|
||||
|
||||
impl CustomOp for RoPECustom {
|
||||
fn to_llir_op(&self) -> LLIROp {
|
||||
LLIROp::new::<dyn KernelOp>(Box::new(self.0.clone()) as Box<dyn KernelOp>)
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply RoPE: `x` shape `(S, H, D)` F32, `cos`/`sin` shape `(S, D)` F32.
|
||||
/// Returns `(S, H, D)` F32.
|
||||
pub fn apply_rope(x: GraphTensor, cos: GraphTensor, sin: GraphTensor) -> GraphTensor {
|
||||
assert_eq!(x.dtype, DType::F32, "RoPE x must be F32");
|
||||
let cos = if cos.dtype == DType::F32 {
|
||||
cos
|
||||
} else {
|
||||
cos.cast(DType::F32)
|
||||
};
|
||||
let sin = if sin.dtype == DType::F32 {
|
||||
sin
|
||||
} else {
|
||||
sin.cast(DType::F32)
|
||||
};
|
||||
let x_dims = x.dims();
|
||||
assert_eq!(x_dims.len(), 3, "RoPE x must be 3-D (S, H, D)");
|
||||
let s = x_dims[0].to_usize().expect("RoPE: S must be static");
|
||||
let h = x_dims[1].to_usize().expect("RoPE: H must be static");
|
||||
let d = x_dims[2].to_usize().expect("RoPE: D must be static");
|
||||
let cos_dims = cos.dims();
|
||||
let sin_dims = sin.dims();
|
||||
assert_eq!(cos_dims.len(), 2, "RoPE cos must be 2-D (S, D)");
|
||||
assert_eq!(sin_dims.len(), 2, "RoPE sin must be 2-D (S, D)");
|
||||
assert_eq!(cos_dims[0].to_usize().unwrap(), s, "RoPE cos S mismatch");
|
||||
assert_eq!(cos_dims[1].to_usize().unwrap(), d, "RoPE cos D mismatch");
|
||||
assert_eq!(sin_dims[0].to_usize().unwrap(), s, "RoPE sin S mismatch");
|
||||
assert_eq!(sin_dims[1].to_usize().unwrap(), d, "RoPE sin D mismatch");
|
||||
|
||||
let kern = RoPEKernel { s, h, d };
|
||||
let cx = unsafe { &mut *x.graph_ref };
|
||||
cx.custom_op(RoPECustom(kern), vec![x, cos, sin], (s, h, d), DType::F32)
|
||||
}
|
||||
@@ -13,6 +13,7 @@ use itertools::Itertools;
|
||||
use luminal::{
|
||||
egglog_utils::{api::Rule, base::OP_KIND},
|
||||
graph::LLIRGraph,
|
||||
hlir::{LoopEnd, LoopInput, LoopInputStatic, LoopOutput, LoopOutputSelect, LoopStart},
|
||||
op::{EgglogOp, LLIROp},
|
||||
prelude::{
|
||||
petgraph::{Direction, algo::toposort, visit::EdgeRef},
|
||||
@@ -22,7 +23,7 @@ use luminal::{
|
||||
use tracing::{Level, enabled, span};
|
||||
|
||||
use crate::{
|
||||
host::HostOp,
|
||||
host::{DeviceBuffer, HostOp},
|
||||
kernel::{
|
||||
CudaFunctionExt, CudaGraphExecHandle, CudaGraphHandle, KernelOp, create_cuda_event,
|
||||
destroy_cuda_event,
|
||||
@@ -47,8 +48,12 @@ struct CompiledKernel {
|
||||
shared_mem: Expression,
|
||||
/// Input node indices (for buffer lookup)
|
||||
inputs: Vec<NodeIndex>,
|
||||
/// Human-readable labels for input nodes, for launch diagnostics.
|
||||
input_labels: Vec<String>,
|
||||
/// Reference to the KernelOp for trait methods
|
||||
kernel_op: Arc<Box<dyn KernelOp>>,
|
||||
/// Whether this compiled CUDA function has a trailing dyn_dims parameter.
|
||||
has_dyn_dims_param: bool,
|
||||
/// Internal buffers allocated for this kernel
|
||||
internal_bufs: Vec<CudaSlice<u8>>,
|
||||
/// Device constants from compile()
|
||||
@@ -68,7 +73,9 @@ impl CompiledKernel {
|
||||
block: (Expression, Expression, Expression),
|
||||
shared_mem: Expression,
|
||||
inputs: Vec<NodeIndex>,
|
||||
input_labels: Vec<String>,
|
||||
kernel_op: Arc<Box<dyn KernelOp>>,
|
||||
has_dyn_dims_param: bool,
|
||||
constants: FxHashMap<char, CudaSlice<u8>>,
|
||||
kernel_name: &'static str,
|
||||
) -> Self {
|
||||
@@ -79,7 +86,9 @@ impl CompiledKernel {
|
||||
block,
|
||||
shared_mem,
|
||||
inputs,
|
||||
input_labels,
|
||||
kernel_op,
|
||||
has_dyn_dims_param,
|
||||
internal_bufs: Vec::new(),
|
||||
constants,
|
||||
graph_node: None,
|
||||
@@ -183,6 +192,32 @@ impl CudaGraphOp {
|
||||
state: RefCell::new(state),
|
||||
}
|
||||
}
|
||||
|
||||
/// LLIR node IDs of every kernel in this CudaGraphOp, in the order
|
||||
/// they execute inside the compiled CUDA graph. This is the
|
||||
/// toposort `kernel_to_host` used at compile time, preserved here
|
||||
/// so the runtime can compute live ranges that match real
|
||||
/// execution order: each kernel in `state.kernels` was added to
|
||||
/// the CUDA graph with `prev_graph_node` as its sole dependency,
|
||||
/// which serializes them.
|
||||
pub fn kernel_topo_order(&self) -> Vec<NodeIndex> {
|
||||
self.state.borrow().kernels.iter().map(|k| k.node).collect()
|
||||
}
|
||||
|
||||
/// Direct LLIR-node inputs of one kernel inside this CudaGraphOp.
|
||||
/// Used by the runtime's live-range pass to refine intra-graph
|
||||
/// consumer positions: a kernel's input can stop being live as
|
||||
/// soon as that specific kernel finishes, not when the whole
|
||||
/// CudaGraphOp finishes.
|
||||
pub fn kernel_inputs(&self, kernel_node: NodeIndex) -> Vec<NodeIndex> {
|
||||
self.state
|
||||
.borrow()
|
||||
.kernels
|
||||
.iter()
|
||||
.find(|k| k.node == kernel_node)
|
||||
.map(|k| k.inputs.clone())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for CudaGraphOp {
|
||||
@@ -226,7 +261,7 @@ impl HostOp for CudaGraphOp {
|
||||
stream: &Arc<CudaStream>,
|
||||
_self_node: NodeIndex,
|
||||
_inputs: &[NodeIndex],
|
||||
buffers: &FxHashMap<NodeIndex, &CudaSlice<u8>>,
|
||||
buffers: &FxHashMap<NodeIndex, DeviceBuffer>,
|
||||
dyn_map: &FxHashMap<char, usize>,
|
||||
) -> anyhow::Result<()> {
|
||||
self.execute_internal(stream, buffers, dyn_map)
|
||||
@@ -258,6 +293,40 @@ impl HostOp for CudaGraphOp {
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn extra_buffer_lifetimes(&self) -> Option<Vec<(NodeIndex, usize, usize)>> {
|
||||
let state = self.state.borrow();
|
||||
let mut lifetimes: FxHashMap<NodeIndex, (usize, usize)> = FxHashMap::default();
|
||||
let max_step = state.kernels.len().saturating_sub(1);
|
||||
|
||||
let mut touch = |node: NodeIndex, step: usize| {
|
||||
lifetimes
|
||||
.entry(node)
|
||||
.and_modify(|(first, last)| {
|
||||
*first = (*first).min(step);
|
||||
*last = (*last).max(step);
|
||||
})
|
||||
.or_insert((step, step));
|
||||
};
|
||||
|
||||
for (step, kernel) in state.kernels.iter().enumerate() {
|
||||
for &input in &kernel.inputs {
|
||||
touch(input, step);
|
||||
}
|
||||
touch(kernel.node, step);
|
||||
}
|
||||
|
||||
for node in self.extra_buffer_nodes() {
|
||||
lifetimes.entry(node).or_insert((0, max_step));
|
||||
}
|
||||
|
||||
Some(
|
||||
lifetimes
|
||||
.into_iter()
|
||||
.map(|(node, (start, end))| (node, start, end))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
fn extra_buffer_sizes(&self) -> FxHashMap<NodeIndex, Expression> {
|
||||
self.buffer_sizes.clone()
|
||||
}
|
||||
@@ -268,11 +337,63 @@ impl HostOp for CudaGraphOp {
|
||||
}
|
||||
|
||||
impl CudaGraphOp {
|
||||
fn expected_kernel_inputs(kernel_name: &str) -> Option<usize> {
|
||||
match kernel_name {
|
||||
"Constant" | "Iota" => Some(0),
|
||||
"MaxReduce" | "MeanReduce" | "SumReduce" | "Cast" | "Exp" | "Exp2" | "Log2" | "Sin"
|
||||
| "Recip" | "Sigmoid" | "Softmax" | "Sqrt" => Some(1),
|
||||
"Add" | "Embed" | "Gather" | "GenericMatmul" | "LessThan" | "Mod" | "Mul" => Some(2),
|
||||
"Scatter" | "ScatterNoCopy" => Some(3),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn kernel_requires_output_buffer(
|
||||
kernel: &CompiledKernel,
|
||||
dyn_map: &FxHashMap<char, usize>,
|
||||
) -> bool {
|
||||
kernel.kernel_op.output_size().exec(dyn_map).unwrap_or(1) != 0
|
||||
&& kernel.kernel_op.output_aliases_input().is_none()
|
||||
}
|
||||
|
||||
fn validate_kernel_pointers(
|
||||
kernel: &CompiledKernel,
|
||||
output_ptr: u64,
|
||||
input_ptrs: &[u64],
|
||||
dyn_map: &FxHashMap<char, usize>,
|
||||
) -> anyhow::Result<()> {
|
||||
if Self::kernel_requires_output_buffer(kernel, dyn_map) && output_ptr == 0 {
|
||||
anyhow::bail!(
|
||||
"missing output buffer for CUDA kernel {} at LLIR node {:?}",
|
||||
kernel.kernel_name,
|
||||
kernel.node,
|
||||
);
|
||||
}
|
||||
|
||||
for (idx, (input_node, input_ptr)) in kernel.inputs.iter().zip(input_ptrs).enumerate() {
|
||||
if *input_ptr == 0 {
|
||||
let input_label = kernel
|
||||
.input_labels
|
||||
.get(idx)
|
||||
.map(String::as_str)
|
||||
.unwrap_or("unknown");
|
||||
anyhow::bail!(
|
||||
"missing input buffer {idx} for CUDA kernel {} at LLIR node {:?}; input LLIR node {:?} ({input_label})",
|
||||
kernel.kernel_name,
|
||||
kernel.node,
|
||||
input_node,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Execute the CUDA graph with the given buffers and dynamic dimensions.
|
||||
fn execute_internal(
|
||||
&self,
|
||||
stream: &Arc<CudaStream>,
|
||||
buffers: &FxHashMap<NodeIndex, &CudaSlice<u8>>,
|
||||
buffers: &FxHashMap<NodeIndex, DeviceBuffer>,
|
||||
dyn_map: &FxHashMap<char, usize>,
|
||||
) -> anyhow::Result<()> {
|
||||
let mut state = self.state.borrow_mut();
|
||||
@@ -343,7 +464,7 @@ impl CudaGraphOp {
|
||||
let mut current_buffer_ptrs: FxHashMap<NodeIndex, u64> = FxHashMap::default();
|
||||
for &node in &self.buffer_nodes {
|
||||
if let Some(buf) = buffers.get(&node) {
|
||||
current_buffer_ptrs.insert(node, buf.device_ptr(stream).0);
|
||||
current_buffer_ptrs.insert(node, buf.ptr());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -391,13 +512,26 @@ impl CudaGraphOp {
|
||||
.iter()
|
||||
.map(|inp| current_buffer_ptrs.get(inp).copied().unwrap_or(0))
|
||||
.collect();
|
||||
Self::validate_kernel_pointers(kernel, output_ptr, &input_ptrs, dyn_map)?;
|
||||
let kernel_dyn_dims_ptr = if kernel.has_dyn_dims_param {
|
||||
dyn_dims_ptr
|
||||
} else {
|
||||
0
|
||||
};
|
||||
if kernel.has_dyn_dims_param && kernel_dyn_dims_ptr == 0 {
|
||||
anyhow::bail!(
|
||||
"missing dyn_dims buffer for CUDA kernel {} at LLIR node {:?}",
|
||||
kernel.kernel_name,
|
||||
kernel.node,
|
||||
);
|
||||
}
|
||||
|
||||
let param_values = kernel.kernel_op.build_params(
|
||||
stream,
|
||||
output_ptr,
|
||||
&input_ptrs,
|
||||
&kernel.internal_bufs,
|
||||
dyn_dims_ptr,
|
||||
kernel_dyn_dims_ptr,
|
||||
);
|
||||
state.kernel_params[idx] = UnifiedKernelParams::new(param_values);
|
||||
}
|
||||
@@ -424,6 +558,19 @@ impl CudaGraphOp {
|
||||
kernel.block.1.exec(dyn_map).unwrap() as u32,
|
||||
kernel.block.2.exec(dyn_map).unwrap() as u32,
|
||||
);
|
||||
if grid_dim.0 == 0
|
||||
|| grid_dim.1 == 0
|
||||
|| grid_dim.2 == 0
|
||||
|| block_dim.0 == 0
|
||||
|| block_dim.1 == 0
|
||||
|| block_dim.2 == 0
|
||||
{
|
||||
anyhow::bail!(
|
||||
"invalid CUDA launch dimensions for kernel {} at LLIR node {:?}: grid={grid_dim:?} block={block_dim:?}",
|
||||
kernel.kernel_name,
|
||||
kernel.node,
|
||||
);
|
||||
}
|
||||
let shared_mem = kernel.shared_mem.exec(dyn_map).unwrap() as u32;
|
||||
let cu_func = unsafe { kernel.function.raw_function() };
|
||||
|
||||
@@ -452,7 +599,7 @@ impl CudaGraphOp {
|
||||
&self,
|
||||
state: &mut std::cell::RefMut<'_, CudaGraphOpState>,
|
||||
stream: &Arc<CudaStream>,
|
||||
buffers: &FxHashMap<NodeIndex, &CudaSlice<u8>>,
|
||||
buffers: &FxHashMap<NodeIndex, DeviceBuffer>,
|
||||
dyn_map: &FxHashMap<char, usize>,
|
||||
) -> anyhow::Result<()> {
|
||||
let ctx = stream.context().clone();
|
||||
@@ -474,7 +621,7 @@ impl CudaGraphOp {
|
||||
let mut buffer_ptrs: FxHashMap<NodeIndex, u64> = FxHashMap::default();
|
||||
for &node in &self.buffer_nodes {
|
||||
if let Some(buf) = buffers.get(&node) {
|
||||
buffer_ptrs.insert(node, buf.device_ptr(stream).0);
|
||||
buffer_ptrs.insert(node, buf.ptr());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -521,6 +668,19 @@ impl CudaGraphOp {
|
||||
kernel.block.1.exec(dyn_map).unwrap() as u32,
|
||||
kernel.block.2.exec(dyn_map).unwrap() as u32,
|
||||
);
|
||||
if grid_dim.0 == 0
|
||||
|| grid_dim.1 == 0
|
||||
|| grid_dim.2 == 0
|
||||
|| block_dim.0 == 0
|
||||
|| block_dim.1 == 0
|
||||
|| block_dim.2 == 0
|
||||
{
|
||||
anyhow::bail!(
|
||||
"invalid CUDA launch dimensions for kernel {} at LLIR node {:?}: grid={grid_dim:?} block={block_dim:?}",
|
||||
kernel.kernel_name,
|
||||
kernel.node,
|
||||
);
|
||||
}
|
||||
let shared_mem = kernel.shared_mem.exec(dyn_map).unwrap() as u32;
|
||||
|
||||
let output_ptr = buffer_ptrs.get(&kernel.node).copied().unwrap_or(0);
|
||||
@@ -529,18 +689,41 @@ impl CudaGraphOp {
|
||||
.iter()
|
||||
.map(|inp| buffer_ptrs.get(inp).copied().unwrap_or(0))
|
||||
.collect();
|
||||
Self::validate_kernel_pointers(kernel, output_ptr, &input_ptrs, dyn_map)?;
|
||||
let kernel_dyn_dims_ptr = if kernel.has_dyn_dims_param {
|
||||
dyn_dims_ptr
|
||||
} else {
|
||||
0
|
||||
};
|
||||
if kernel.has_dyn_dims_param && kernel_dyn_dims_ptr == 0 {
|
||||
anyhow::bail!(
|
||||
"missing dyn_dims buffer for CUDA kernel {} at LLIR node {:?}",
|
||||
kernel.kernel_name,
|
||||
kernel.node,
|
||||
);
|
||||
}
|
||||
|
||||
let param_values = kernel.kernel_op.build_params(
|
||||
stream,
|
||||
output_ptr,
|
||||
&input_ptrs,
|
||||
&kernel.internal_bufs,
|
||||
dyn_dims_ptr,
|
||||
kernel_dyn_dims_ptr,
|
||||
);
|
||||
let mut params = UnifiedKernelParams::new(param_values);
|
||||
|
||||
let cu_func = unsafe { kernel.function.raw_function() };
|
||||
let kernel_node = kernel.node;
|
||||
if std::env::var_os("LUMINAL_CUDA_DEBUG_GRAPH").is_some() {
|
||||
eprintln!(
|
||||
"cuGraphAddKernelNode kernel={} node={:?} grid={grid_dim:?} block={block_dim:?} shared_mem={shared_mem} inputs={} has_dyn={} params={}",
|
||||
kernel.kernel_name,
|
||||
kernel.node,
|
||||
kernel.inputs.len(),
|
||||
kernel.has_dyn_dims_param,
|
||||
params.values.len(),
|
||||
);
|
||||
}
|
||||
|
||||
// Get timing event for this index (separate access from kernels)
|
||||
let timing_event = if tracing_enabled {
|
||||
@@ -656,12 +839,42 @@ pub fn kernel_to_host(
|
||||
}
|
||||
|
||||
let kernel_subgraphs = partition_marked_convex(llir_graph, &kernel_ops_in_graph).unwrap();
|
||||
// Compute the set of FS / FE / FusedX nodes globally absorbed by some
|
||||
// FusionEnd in the LLIR. Used by `build_compile_units` to suppress the
|
||||
// identity-memcpy fallback for shared FS leaves whose consumers live
|
||||
// in a different convex subgraph than the FS itself.
|
||||
// Compute the set of FS / FE / Cuda*Elementwise nodes globally absorbed by some
|
||||
// FusionEnd in the LLIR. Used by `build_compile_units` to suppress
|
||||
// standalone marker compile units for shared FS leaves whose consumers
|
||||
// live in a different convex subgraph than the FS itself.
|
||||
let globally_absorbed = region_codegen::globally_absorbed_markers(llir_graph);
|
||||
|
||||
let name_of = |graph: &LLIRGraph, idx: NodeIndex| -> Option<&'static str> {
|
||||
graph
|
||||
.node_weight(idx)
|
||||
.and_then(|op| op.to_dialect::<dyn KernelOp>().map(|k| k.kernel_name()))
|
||||
};
|
||||
let is_transparent_input = |graph: &LLIRGraph, node: NodeIndex| -> bool {
|
||||
name_of(graph, node) == Some("FusionStart")
|
||||
|| graph[node].to_op::<LoopStart>().is_some()
|
||||
|| graph[node].to_op::<LoopEnd>().is_some()
|
||||
|| graph[node].to_op::<LoopInput>().is_some()
|
||||
|| graph[node].to_op::<LoopInputStatic>().is_some()
|
||||
|| graph[node].to_op::<LoopOutput>().is_some()
|
||||
|| graph[node].to_op::<LoopOutputSelect>().is_some()
|
||||
};
|
||||
let resolve_transparent_input = |graph: &LLIRGraph, mut node: NodeIndex| -> NodeIndex {
|
||||
let mut visited = FxHashSet::default();
|
||||
while visited.insert(node) && is_transparent_input(graph, node) {
|
||||
let Some(pred) = graph
|
||||
.edges_directed(node, Direction::Incoming)
|
||||
.sorted_by_key(|e| e.id())
|
||||
.map(|e| e.source())
|
||||
.next()
|
||||
else {
|
||||
break;
|
||||
};
|
||||
node = pred;
|
||||
}
|
||||
node
|
||||
};
|
||||
|
||||
// Track which kernel node belongs to which CudaGraphOp (for later edge creation)
|
||||
let mut kernel_to_cuda_graph: FxHashMap<NodeIndex, NodeIndex> = FxHashMap::default();
|
||||
// Track all CudaGraphOp nodes and their subgraphs for edge creation
|
||||
@@ -678,6 +891,7 @@ pub fn kernel_to_host(
|
||||
let mut all_dyn_dims = FxHashSet::default();
|
||||
let mut all_buffer_nodes = FxHashSet::default();
|
||||
let mut all_buffer_sizes: FxHashMap<NodeIndex, Expression> = FxHashMap::default();
|
||||
let mut external_inputs = FxHashSet::default();
|
||||
|
||||
// Pre-scan: collect all dynamic vars from all kernel ops without compiling.
|
||||
// This uses KernelOp::all_dyn_vars() which inspects struct expression fields.
|
||||
@@ -691,9 +905,7 @@ pub fn kernel_to_host(
|
||||
// Set global dyn dims ordering so compiles use consistent indices
|
||||
let mut global_dyn_dims: Vec<char> = all_dyn_dims.iter().copied().collect();
|
||||
global_dyn_dims.sort();
|
||||
if !global_dyn_dims.is_empty() {
|
||||
set_global_dyn_dims(global_dyn_dims.clone());
|
||||
}
|
||||
set_global_dyn_dims(global_dyn_dims.clone());
|
||||
|
||||
// Group the topo order into compile units: each FusionEnd-rooted
|
||||
// region collapses to a single CompileUnit::Region (one fused
|
||||
@@ -711,14 +923,35 @@ pub fn kernel_to_host(
|
||||
.to_dialect::<dyn KernelOp>()
|
||||
.unwrap();
|
||||
|
||||
let (kernel_function, _, _kernel_str, grid, block, shared_mem, constants) =
|
||||
let (kernel_function, _, kernel_str, grid, block, shared_mem, constants) =
|
||||
kernel_op_ref.compile(cuda_stream, kernel_cache);
|
||||
let has_dyn_dims_param = kernel_str.contains("dyn_dims");
|
||||
|
||||
// Collect inputs from graph edges
|
||||
let inputs: Vec<NodeIndex> = llir_graph
|
||||
.edges_directed(*kernel_node_idx, Direction::Incoming)
|
||||
.sorted_by_key(|e| e.id())
|
||||
.map(|e| e.source())
|
||||
.map(|input| resolve_transparent_input(llir_graph, input))
|
||||
.collect_vec();
|
||||
if let Some(expected_inputs) =
|
||||
CudaGraphOp::expected_kernel_inputs(kernel_op_ref.kernel_name())
|
||||
{
|
||||
assert_eq!(
|
||||
inputs.len(),
|
||||
expected_inputs,
|
||||
"invalid input arity for CUDA kernel {} at LLIR node {:?}",
|
||||
kernel_op_ref.kernel_name(),
|
||||
kernel_node_idx,
|
||||
);
|
||||
}
|
||||
let input_labels = inputs
|
||||
.iter()
|
||||
.map(|&input| {
|
||||
name_of(llir_graph, input)
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| format!("{:?}", llir_graph[input]))
|
||||
})
|
||||
.collect_vec();
|
||||
|
||||
// Collect buffer nodes and sizes
|
||||
@@ -729,6 +962,12 @@ pub fn kernel_to_host(
|
||||
all_buffer_sizes.insert(*kernel_node_idx, output_size);
|
||||
}
|
||||
all_buffer_nodes.extend(inputs.iter().copied());
|
||||
external_inputs.extend(
|
||||
inputs
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|input| !subgraph.contains(input)),
|
||||
);
|
||||
|
||||
let kernel_op: Arc<Box<dyn KernelOp>> = Arc::clone(kernel_op_ref);
|
||||
|
||||
@@ -739,7 +978,9 @@ pub fn kernel_to_host(
|
||||
block,
|
||||
shared_mem,
|
||||
inputs,
|
||||
input_labels,
|
||||
kernel_op.clone(),
|
||||
has_dyn_dims_param,
|
||||
constants,
|
||||
kernel_op.kernel_name(),
|
||||
));
|
||||
@@ -752,18 +993,32 @@ pub fn kernel_to_host(
|
||||
cuda_stream,
|
||||
kernel_cache,
|
||||
);
|
||||
let has_dyn_dims_param = compiled.kernel_str.contains("dyn_dims");
|
||||
|
||||
// The region's CompiledKernel is keyed on the FE node
|
||||
// (so FE provides trait methods like output_size /
|
||||
// build_params) but its `inputs` are the external
|
||||
// producers, not FE's literal LLIR predecessors —
|
||||
// those are interior FusedX nodes that don't exist
|
||||
// those are interior elementwise nodes that don't exist
|
||||
// as buffer-bearing nodes from the host's view.
|
||||
let fe_op_ref = llir_graph[region.fe_node]
|
||||
.to_dialect::<dyn KernelOp>()
|
||||
.unwrap();
|
||||
|
||||
let inputs: Vec<NodeIndex> = region.external_inputs.clone();
|
||||
let inputs: Vec<NodeIndex> = region
|
||||
.external_inputs
|
||||
.iter()
|
||||
.copied()
|
||||
.map(|input| resolve_transparent_input(llir_graph, input))
|
||||
.collect();
|
||||
let input_labels = inputs
|
||||
.iter()
|
||||
.map(|&input| {
|
||||
name_of(llir_graph, input)
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| format!("{:?}", llir_graph[input]))
|
||||
})
|
||||
.collect_vec();
|
||||
|
||||
let output_size = fe_op_ref.output_size();
|
||||
if output_size.exec(&FxHashMap::default()).unwrap_or(1) != 0 {
|
||||
@@ -771,6 +1026,12 @@ pub fn kernel_to_host(
|
||||
all_buffer_sizes.insert(region.fe_node, output_size);
|
||||
}
|
||||
all_buffer_nodes.extend(inputs.iter().copied());
|
||||
external_inputs.extend(
|
||||
inputs
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|input| !subgraph.contains(input)),
|
||||
);
|
||||
|
||||
let kernel_op: Arc<Box<dyn KernelOp>> = Arc::clone(fe_op_ref);
|
||||
|
||||
@@ -781,7 +1042,9 @@ pub fn kernel_to_host(
|
||||
compiled.block,
|
||||
compiled.shared_mem,
|
||||
inputs,
|
||||
input_labels,
|
||||
kernel_op,
|
||||
has_dyn_dims_param,
|
||||
compiled.constants,
|
||||
"FusedRegion",
|
||||
));
|
||||
@@ -826,16 +1089,17 @@ pub fn kernel_to_host(
|
||||
}
|
||||
cuda_graph_subgraphs.push((cuda_graph_node, subgraph.clone()));
|
||||
|
||||
// Find external inputs: nodes outside subgraph that have edges into subgraph
|
||||
let external_inputs: FxHashSet<NodeIndex> = subgraph
|
||||
.iter()
|
||||
.flat_map(|&node| {
|
||||
llir_graph
|
||||
.edges_directed(node, Direction::Incoming)
|
||||
.map(|e| e.source())
|
||||
.filter(|src| !subgraph.contains(src))
|
||||
})
|
||||
.collect();
|
||||
// Find external inputs: nodes outside subgraph that have edges into
|
||||
// subgraph. Also include normalized FusionStart predecessors, because
|
||||
// the compiled kernels read from the concrete producer buffer rather
|
||||
// than the marker node.
|
||||
external_inputs.extend(subgraph.iter().flat_map(|&node| {
|
||||
llir_graph
|
||||
.edges_directed(node, Direction::Incoming)
|
||||
.map(|e| e.source())
|
||||
.map(|input| resolve_transparent_input(llir_graph, input))
|
||||
.filter(|src| !subgraph.contains(src))
|
||||
}));
|
||||
|
||||
// Add edges from external inputs to CudaGraphOp
|
||||
for input in &external_inputs {
|
||||
@@ -900,7 +1164,7 @@ pub fn kernel_to_host(
|
||||
}
|
||||
|
||||
// Strip fully-absorbed marker nodes (FusionStart, nested FusionEnd,
|
||||
// FusedX) from the LLIR. Region codegen has already folded them into
|
||||
// Cuda*Elementwise) from the LLIR. Region codegen has already folded them into
|
||||
// a single fused CUDA function anchored at each region's root
|
||||
// FusionEnd; the absorbed nodes have no consumers outside the region
|
||||
// and never need their own buffers. Removing them keeps later
|
||||
|
||||
@@ -34,6 +34,7 @@ fn cuda_dtype(dtype: DType) -> &'static str {
|
||||
DType::Bf16 => "__nv_bfloat16",
|
||||
DType::TF32 => "float", // TF32 uses float storage, tensor cores handle the format
|
||||
DType::Int => "int",
|
||||
DType::I64 => "long long",
|
||||
DType::I16 => "short",
|
||||
DType::U16 => "unsigned short",
|
||||
DType::I8 => "signed char",
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -22,6 +22,10 @@ fn build_dynamic_matmul_graph(k: usize, n: usize) -> (Graph, NodeIndex, NodeInde
|
||||
(cx, a.id, b.id, c.id)
|
||||
}
|
||||
|
||||
fn bucket_options(buckets: &[DimBucket]) -> CompileOptions {
|
||||
CompileOptions::default().dim_buckets('s', buckets)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bucket_dispatch_simple() {
|
||||
// Tests that bucketed compilation produces correct results for different dim values
|
||||
@@ -31,9 +35,10 @@ fn test_bucket_dispatch_simple() {
|
||||
|
||||
let (mut cx, a, b) = build_dynamic_add_graph();
|
||||
|
||||
cx.set_dim_buckets('s', &[DimBucket::new(1, 1), DimBucket::new(2, 4)]);
|
||||
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
cx.build_search_space::<CudaRuntime>(bucket_options(&[
|
||||
DimBucket::new(1, 1),
|
||||
DimBucket::new(2, 4),
|
||||
]));
|
||||
let mut rt = CudaRuntime::initialize(stream);
|
||||
|
||||
// Set dummy input for search
|
||||
@@ -41,7 +46,7 @@ fn test_bucket_dispatch_simple() {
|
||||
rt.set_data(a, vec![1.0f32; 4]);
|
||||
|
||||
let mut rng = SmallRng::seed_from_u64(42);
|
||||
rt = cx.search_options(rt, SearchOptions::new(5), &mut rng);
|
||||
rt = cx.search_with_rng(rt, CompileOptions::new(5), &mut rng);
|
||||
|
||||
// Test bucket 1: s=1
|
||||
cx.set_dim('s', 1);
|
||||
@@ -73,9 +78,10 @@ fn test_bucket_matmul_dynamic() {
|
||||
let n = 4;
|
||||
let (mut cx, a, b_tensor, c) = build_dynamic_matmul_graph(k, n);
|
||||
|
||||
cx.set_dim_buckets('s', &[DimBucket::new(1, 1), DimBucket::new(2, 8)]);
|
||||
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
cx.build_search_space::<CudaRuntime>(bucket_options(&[
|
||||
DimBucket::new(1, 1),
|
||||
DimBucket::new(2, 8),
|
||||
]));
|
||||
let mut rt = CudaRuntime::initialize(stream);
|
||||
|
||||
cx.set_dim('s', 1);
|
||||
@@ -85,7 +91,7 @@ fn test_bucket_matmul_dynamic() {
|
||||
rt.set_data(b_tensor, b_data.clone());
|
||||
|
||||
let mut rng = SmallRng::seed_from_u64(42);
|
||||
rt = cx.search_options(rt, SearchOptions::new(5), &mut rng);
|
||||
rt = cx.search_with_rng(rt, CompileOptions::new(5), &mut rng);
|
||||
|
||||
// Execute at s=1
|
||||
cx.set_dim('s', 1);
|
||||
@@ -135,12 +141,12 @@ fn test_bucket_results_match_unbucketed() {
|
||||
// Non-bucketed run
|
||||
let (mut cx1, a1, b1) = build_dynamic_add_graph();
|
||||
cx1.set_dim('s', 3);
|
||||
cx1.build_search_space::<CudaRuntime>();
|
||||
cx1.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let mut rt1 = CudaRuntime::initialize(stream.clone());
|
||||
let input_data = random_f32_vec(12, seed, -1.0, 1.0);
|
||||
rt1.set_data(a1, input_data.clone());
|
||||
let mut rng1 = SmallRng::seed_from_u64(seed);
|
||||
rt1 = cx1.search_options(rt1, SearchOptions::new(5), &mut rng1);
|
||||
rt1 = cx1.search_with_rng(rt1, CompileOptions::new(5), &mut rng1);
|
||||
rt1.set_data(a1, input_data.clone());
|
||||
rt1.execute(&cx1.dyn_map);
|
||||
let result_unbucketed = rt1.get_f32(b1);
|
||||
@@ -148,12 +154,11 @@ fn test_bucket_results_match_unbucketed() {
|
||||
// Bucketed run with bucket that covers s=3
|
||||
let (mut cx2, a2, b2) = build_dynamic_add_graph();
|
||||
cx2.set_dim('s', 3);
|
||||
cx2.set_dim_buckets('s', &[DimBucket::new(1, 4)]);
|
||||
cx2.build_search_space::<CudaRuntime>();
|
||||
cx2.build_search_space::<CudaRuntime>(bucket_options(&[DimBucket::new(1, 4)]));
|
||||
let mut rt2 = CudaRuntime::initialize(stream.clone());
|
||||
rt2.set_data(a2, input_data.clone());
|
||||
let mut rng2 = SmallRng::seed_from_u64(seed);
|
||||
rt2 = cx2.search_options(rt2, SearchOptions::new(5), &mut rng2);
|
||||
rt2 = cx2.search_with_rng(rt2, CompileOptions::new(5), &mut rng2);
|
||||
rt2.set_data(a2, input_data.clone());
|
||||
rt2.execute(&cx2.dyn_map);
|
||||
let result_bucketed = rt2.get_f32(b2);
|
||||
@@ -172,14 +177,16 @@ fn test_bucket_out_of_range_panics() {
|
||||
};
|
||||
|
||||
let (mut cx, a, _b) = build_dynamic_add_graph();
|
||||
cx.set_dim_buckets('s', &[DimBucket::new(1, 1), DimBucket::new(2, 4)]);
|
||||
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
cx.build_search_space::<CudaRuntime>(bucket_options(&[
|
||||
DimBucket::new(1, 1),
|
||||
DimBucket::new(2, 4),
|
||||
]));
|
||||
let mut rt = CudaRuntime::initialize(stream);
|
||||
cx.set_dim('s', 1);
|
||||
rt.set_data(a, vec![1.0f32; 4]);
|
||||
let mut rng = SmallRng::seed_from_u64(42);
|
||||
rt = cx.search_options(rt, SearchOptions::new(3), &mut rng);
|
||||
rt = cx.search_with_rng(rt, CompileOptions::new(3), &mut rng);
|
||||
|
||||
// s=10 is outside all buckets — should panic
|
||||
cx.set_dim('s', 10);
|
||||
@@ -197,14 +204,14 @@ fn test_bucket_no_buckets_backward_compat() {
|
||||
let (mut cx, a, b) = build_dynamic_add_graph();
|
||||
cx.set_dim('s', 2);
|
||||
|
||||
// No set_dim_buckets call
|
||||
// No bucket options
|
||||
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let mut rt = CudaRuntime::initialize(stream);
|
||||
let input_data = vec![1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0];
|
||||
rt.set_data(a, input_data.clone());
|
||||
let mut rng = SmallRng::seed_from_u64(42);
|
||||
rt = cx.search_options(rt, SearchOptions::new(3), &mut rng);
|
||||
rt = cx.search_with_rng(rt, CompileOptions::new(3), &mut rng);
|
||||
|
||||
rt.set_data(a, input_data.clone());
|
||||
rt.execute(&cx.dyn_map);
|
||||
@@ -237,9 +244,10 @@ fn test_bucket_switch_preserves_weights() {
|
||||
let n = 4;
|
||||
let (mut cx, a, b_tensor, c) = build_dynamic_matmul_graph(k, n);
|
||||
|
||||
cx.set_dim_buckets('s', &[DimBucket::new(1, 1), DimBucket::new(2, 4)]);
|
||||
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
cx.build_search_space::<CudaRuntime>(bucket_options(&[
|
||||
DimBucket::new(1, 1),
|
||||
DimBucket::new(2, 4),
|
||||
]));
|
||||
let mut rt = CudaRuntime::initialize(stream);
|
||||
|
||||
cx.set_dim('s', 1);
|
||||
@@ -249,7 +257,7 @@ fn test_bucket_switch_preserves_weights() {
|
||||
rt.set_data(b_tensor, b_data.clone());
|
||||
|
||||
let mut rng = SmallRng::seed_from_u64(42);
|
||||
rt = cx.search_options(rt, SearchOptions::new(5), &mut rng);
|
||||
rt = cx.search_with_rng(rt, CompileOptions::new(5), &mut rng);
|
||||
|
||||
// Execute with bucket 1 (s=1)
|
||||
cx.set_dim('s', 1);
|
||||
@@ -297,15 +305,13 @@ fn test_bucket_multiple_executions_same_bucket() {
|
||||
|
||||
let (mut cx, a, b) = build_dynamic_add_graph();
|
||||
|
||||
cx.set_dim_buckets('s', &[DimBucket::new(1, 8)]);
|
||||
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
cx.build_search_space::<CudaRuntime>(bucket_options(&[DimBucket::new(1, 8)]));
|
||||
let mut rt = CudaRuntime::initialize(stream);
|
||||
|
||||
cx.set_dim('s', 1);
|
||||
rt.set_data(a, vec![1.0f32; 4]);
|
||||
let mut rng = SmallRng::seed_from_u64(42);
|
||||
rt = cx.search_options(rt, SearchOptions::new(3), &mut rng);
|
||||
rt = cx.search_with_rng(rt, CompileOptions::new(3), &mut rng);
|
||||
|
||||
// Execute at different sizes within the same bucket
|
||||
for s in [1, 2, 4, 8] {
|
||||
@@ -323,8 +329,7 @@ fn test_bucket_multiple_executions_same_bucket() {
|
||||
#[test]
|
||||
#[should_panic(expected = "Overlapping buckets")]
|
||||
fn test_bucket_overlapping_ranges_panics() {
|
||||
let mut cx = Graph::default();
|
||||
cx.set_dim_buckets('s', &[DimBucket::new(1, 4), DimBucket::new(3, 8)]);
|
||||
let _ = bucket_options(&[DimBucket::new(1, 4), DimBucket::new(3, 8)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
482
crates/luminal_cuda_lite/src/tests/conv2d_rewrite.rs
Normal file
482
crates/luminal_cuda_lite/src/tests/conv2d_rewrite.rs
Normal file
@@ -0,0 +1,482 @@
|
||||
use luminal::{
|
||||
egglog_utils::{
|
||||
NodeId, SerializedEGraph, egglog_to_llir, random_initial_choice, validate_choice_set,
|
||||
},
|
||||
prelude::*,
|
||||
};
|
||||
use rand::{SeedableRng, rngs::StdRng};
|
||||
|
||||
use crate::{kernel::KernelOp, runtime::CudaRuntime};
|
||||
|
||||
use super::utilities::{assert_close, get_cuda_stream};
|
||||
|
||||
fn conv2d_bias_hlir(
|
||||
x: GraphTensor,
|
||||
weight: GraphTensor,
|
||||
bias: GraphTensor,
|
||||
kernel_h: usize,
|
||||
kernel_w: usize,
|
||||
) -> GraphTensor {
|
||||
let unfolded = x.unfold(
|
||||
vec![1usize, kernel_h, kernel_w],
|
||||
vec![1usize, 1, 1],
|
||||
vec![1usize, 1, 1],
|
||||
);
|
||||
let output_spatial_dims = unfolded.dims()[1..3].to_vec();
|
||||
|
||||
let mut patches = unfolded.squeeze(3).permute(&[1, 2, 0, 3, 4]);
|
||||
while patches.dims().len() > 3 {
|
||||
let last = patches.dims().len();
|
||||
patches = patches.merge_dims(last - 2, last - 1);
|
||||
}
|
||||
let patches = patches.merge_dims(0, 1);
|
||||
|
||||
let out = patches.matmul(weight.t());
|
||||
let out = out
|
||||
.split_dims(0, output_spatial_dims[1])
|
||||
.permute(&[2, 0, 1]);
|
||||
let out_dims = out.dims();
|
||||
out + bias.expand_dim(1, out_dims[1]).expand_dim(2, out_dims[2])
|
||||
}
|
||||
|
||||
fn build_conv_graph() -> (Graph, GraphTensor, GraphTensor, GraphTensor, GraphTensor) {
|
||||
let mut cx = Graph::new();
|
||||
let x = cx.tensor((2usize, 5usize, 6usize));
|
||||
let weight = cx.tensor((3usize, 2usize * 3 * 2));
|
||||
let bias = cx.tensor(3usize);
|
||||
let out = conv2d_bias_hlir(x, weight, bias, 3, 2).output();
|
||||
(cx, x, weight, bias, out)
|
||||
}
|
||||
|
||||
fn conv2d_bias_padded_hlir(
|
||||
x: GraphTensor,
|
||||
weight: GraphTensor,
|
||||
bias: GraphTensor,
|
||||
kernel: usize,
|
||||
padding: usize,
|
||||
) -> GraphTensor {
|
||||
let zero = Expression::from(0);
|
||||
let pad = Expression::from(padding);
|
||||
let padded = x.pad(vec![(zero, zero), (pad, pad), (pad, pad)], 0.0);
|
||||
conv2d_bias_hlir(padded, weight, bias, kernel, kernel)
|
||||
}
|
||||
|
||||
fn build_padded_conv_graph() -> (Graph, GraphTensor, GraphTensor, GraphTensor, GraphTensor) {
|
||||
let mut cx = Graph::new();
|
||||
let x = cx.tensor((2usize, 4usize, 5usize));
|
||||
let weight = cx.tensor((3usize, 2usize * 3 * 3));
|
||||
let bias = cx.tensor(3usize);
|
||||
let out = conv2d_bias_padded_hlir(x, weight, bias, 3, 1).output();
|
||||
(cx, x, weight, bias, out)
|
||||
}
|
||||
|
||||
fn nearest_upsample_2x_hlir(x: GraphTensor) -> GraphTensor {
|
||||
let stage1 = x.expand_dim(2, 2usize).merge_dims(1, 2);
|
||||
stage1.expand_dim(3, 2usize).merge_dims(2, 3)
|
||||
}
|
||||
|
||||
fn build_upsample_conv_graph() -> (Graph, GraphTensor, GraphTensor, GraphTensor, GraphTensor) {
|
||||
let mut cx = Graph::new();
|
||||
let x = cx.tensor((2usize, 3usize, 4usize));
|
||||
let weight = cx.tensor((3usize, 2usize * 3 * 3));
|
||||
let bias = cx.tensor(3usize);
|
||||
let up = nearest_upsample_2x_hlir(x);
|
||||
let out = conv2d_bias_padded_hlir(up, weight, bias, 3, 1).output();
|
||||
(cx, x, weight, bias, out)
|
||||
}
|
||||
|
||||
fn conv1x1_bias_hlir(x: GraphTensor, weight: GraphTensor, bias: GraphTensor) -> GraphTensor {
|
||||
let dims = x.dims();
|
||||
let h = dims[1];
|
||||
let w = dims[2];
|
||||
let xt = x.permute(&[1, 2, 0]).merge_dims(0, 1);
|
||||
let out = xt.matmul(weight.t());
|
||||
let out = out.split_dims(0, w).permute(&[2, 0, 1]);
|
||||
out + bias.expand_dim(1, h).expand_dim(2, w)
|
||||
}
|
||||
|
||||
fn build_conv1x1_graph() -> (Graph, GraphTensor, GraphTensor, GraphTensor, GraphTensor) {
|
||||
let mut cx = Graph::new();
|
||||
let x = cx.tensor((2usize, 4usize, 5usize));
|
||||
let weight = cx.tensor((3usize, 2usize));
|
||||
let bias = cx.tensor(3usize);
|
||||
let out = conv1x1_bias_hlir(x, weight, bias).output();
|
||||
(cx, x, weight, bias, out)
|
||||
}
|
||||
|
||||
fn conv2d_matmul_without_conv_output_shape(
|
||||
x: GraphTensor,
|
||||
weight: GraphTensor,
|
||||
bias: GraphTensor,
|
||||
kernel_h: usize,
|
||||
kernel_w: usize,
|
||||
) -> GraphTensor {
|
||||
let unfolded = x.unfold(
|
||||
vec![1usize, kernel_h, kernel_w],
|
||||
vec![1usize, 1, 1],
|
||||
vec![1usize, 1, 1],
|
||||
);
|
||||
|
||||
let mut patches = unfolded.squeeze(3).permute(&[1, 2, 0, 3, 4]);
|
||||
while patches.dims().len() > 3 {
|
||||
let last = patches.dims().len();
|
||||
patches = patches.merge_dims(last - 2, last - 1);
|
||||
}
|
||||
let patches = patches.merge_dims(0, 1);
|
||||
|
||||
let out = patches.matmul(weight.t());
|
||||
let out_dims = out.dims();
|
||||
out + bias.expand_dim(0, out_dims[0])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generic_conv2d_rewrite_matches_unfold_matmul_bias() {
|
||||
let (mut cx, _, _, _, _) = build_conv_graph();
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let egraph = cx.egraph().expect("search space should have an e-graph");
|
||||
|
||||
assert!(
|
||||
!op_ir_nodes(egraph, "KernelConv2D").is_empty(),
|
||||
"expected generic conv2d rewrite candidate"
|
||||
);
|
||||
assert!(
|
||||
op_ir_nodes(egraph, "Add").is_empty(),
|
||||
"generic conv2d cleanup should prune the final bias Add fallback"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generic_conv2d_rewrite_matches_conv1x1_matmul_bias() {
|
||||
let (mut cx, _, _, _, _) = build_conv1x1_graph();
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let egraph = cx.egraph().expect("search space should have an e-graph");
|
||||
|
||||
assert!(
|
||||
!op_ir_nodes(egraph, "KernelConv2D").is_empty(),
|
||||
"expected generic conv2d rewrite candidate for 1x1 conv"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generic_conv2d_rewrite_requires_conv_output_shape() {
|
||||
let mut cx = Graph::new();
|
||||
let x = cx.tensor((2usize, 5usize, 6usize));
|
||||
let weight = cx.tensor((3usize, 2usize * 3 * 2));
|
||||
let bias = cx.tensor(3usize);
|
||||
conv2d_matmul_without_conv_output_shape(x, weight, bias, 3, 2).output();
|
||||
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let egraph = cx.egraph().expect("search space should have an e-graph");
|
||||
|
||||
assert!(
|
||||
op_ir_nodes(egraph, "KernelConv2D").is_empty(),
|
||||
"matmul+bias without [C_out,H_out,W_out] conv output shape should not match KernelConv2D"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generic_conv2d_candidate_executes_unfold_matmul_bias() {
|
||||
let Some(stream) = get_cuda_stream() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let (mut cx, x, weight, bias, out) = build_conv_graph();
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let llir = extract_forced_kernel_llir(&mut cx, "GenericConv2D");
|
||||
|
||||
let input: Vec<f32> = (0..2 * 5 * 6).map(|i| i as f32 * 0.03 - 0.4).collect();
|
||||
let weights: Vec<f32> = (0..3 * 2 * 3 * 2)
|
||||
.map(|i| (i as f32 % 11.0) * 0.04 - 0.2)
|
||||
.collect();
|
||||
let biases = vec![0.25_f32, -0.15, 0.05];
|
||||
let expected = reference_conv2d(
|
||||
&input,
|
||||
&weights,
|
||||
&biases,
|
||||
ConvCase {
|
||||
c_in: 2,
|
||||
h: 5,
|
||||
w: 6,
|
||||
c_out: 3,
|
||||
kh: 3,
|
||||
kw: 2,
|
||||
padding_h: 0,
|
||||
padding_w: 0,
|
||||
},
|
||||
);
|
||||
|
||||
let mut rt = CudaRuntime::initialize(stream);
|
||||
rt.load_llir(&llir);
|
||||
rt.set_data(x, input);
|
||||
rt.set_data(weight, weights);
|
||||
rt.set_data(bias, biases);
|
||||
rt.execute(&cx.dyn_map);
|
||||
|
||||
assert_close(&rt.get_f32(out.id), &expected, 1e-5, 1e-5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generic_conv2d_candidate_executes_conv1x1_matmul_bias() {
|
||||
let Some(stream) = get_cuda_stream() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let (mut cx, x, weight, bias, out) = build_conv1x1_graph();
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let llir = extract_forced_kernel_llir(&mut cx, "GenericConv2D");
|
||||
|
||||
let input: Vec<f32> = (0..2 * 4 * 5).map(|i| i as f32 * 0.07 - 1.0).collect();
|
||||
let weights: Vec<f32> = (0..3 * 2).map(|i| (i as f32 % 5.0) * 0.11 - 0.2).collect();
|
||||
let biases = vec![0.2_f32, -0.1, 0.4];
|
||||
let expected = reference_conv2d(
|
||||
&input,
|
||||
&weights,
|
||||
&biases,
|
||||
ConvCase {
|
||||
c_in: 2,
|
||||
h: 4,
|
||||
w: 5,
|
||||
c_out: 3,
|
||||
kh: 1,
|
||||
kw: 1,
|
||||
padding_h: 0,
|
||||
padding_w: 0,
|
||||
},
|
||||
);
|
||||
|
||||
let mut rt = CudaRuntime::initialize(stream);
|
||||
rt.load_llir(&llir);
|
||||
rt.set_data(x, input);
|
||||
rt.set_data(weight, weights);
|
||||
rt.set_data(bias, biases);
|
||||
rt.execute(&cx.dyn_map);
|
||||
|
||||
assert_close(&rt.get_f32(out.id), &expected, 1e-5, 1e-5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generic_conv2d_candidate_executes_padded_unfold_matmul_bias() {
|
||||
let Some(stream) = get_cuda_stream() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let (mut cx, x, weight, bias, out) = build_padded_conv_graph();
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let llir = extract_forced_kernel_llir(&mut cx, "GenericConv2D");
|
||||
|
||||
let input: Vec<f32> = (0..2 * 4 * 5).map(|i| i as f32 * 0.05 - 0.5).collect();
|
||||
let weights: Vec<f32> = (0..3 * 2 * 3 * 3)
|
||||
.map(|i| (i as f32 % 13.0) * 0.03 - 0.17)
|
||||
.collect();
|
||||
let biases = vec![0.15_f32, -0.25, 0.35];
|
||||
let expected = reference_conv2d(
|
||||
&input,
|
||||
&weights,
|
||||
&biases,
|
||||
ConvCase {
|
||||
c_in: 2,
|
||||
h: 4,
|
||||
w: 5,
|
||||
c_out: 3,
|
||||
kh: 3,
|
||||
kw: 3,
|
||||
padding_h: 1,
|
||||
padding_w: 1,
|
||||
},
|
||||
);
|
||||
|
||||
let mut rt = CudaRuntime::initialize(stream);
|
||||
rt.load_llir(&llir);
|
||||
rt.set_data(x, input);
|
||||
rt.set_data(weight, weights);
|
||||
rt.set_data(bias, biases);
|
||||
rt.execute(&cx.dyn_map);
|
||||
|
||||
assert_close(&rt.get_f32(out.id), &expected, 1e-5, 1e-5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generic_conv2d_candidate_executes_upsample_view_input() {
|
||||
let Some(stream) = get_cuda_stream() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let (mut cx, x, weight, bias, out) = build_upsample_conv_graph();
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let llir = extract_forced_kernel_llir(&mut cx, "GenericConv2D");
|
||||
|
||||
let input: Vec<f32> = (0..2 * 3 * 4).map(|i| i as f32 * 0.09 - 0.8).collect();
|
||||
let weights: Vec<f32> = (0..3 * 2 * 3 * 3)
|
||||
.map(|i| (i as f32 % 17.0) * 0.025 - 0.2)
|
||||
.collect();
|
||||
let biases = vec![0.05_f32, -0.1, 0.2];
|
||||
let upsampled = reference_nearest_upsample_2x(&input, 2, 3, 4);
|
||||
let expected = reference_conv2d(
|
||||
&upsampled,
|
||||
&weights,
|
||||
&biases,
|
||||
ConvCase {
|
||||
c_in: 2,
|
||||
h: 6,
|
||||
w: 8,
|
||||
c_out: 3,
|
||||
kh: 3,
|
||||
kw: 3,
|
||||
padding_h: 1,
|
||||
padding_w: 1,
|
||||
},
|
||||
);
|
||||
|
||||
let mut rt = CudaRuntime::initialize(stream);
|
||||
rt.load_llir(&llir);
|
||||
rt.set_data(x, input);
|
||||
rt.set_data(weight, weights);
|
||||
rt.set_data(bias, biases);
|
||||
rt.execute(&cx.dyn_map);
|
||||
|
||||
assert_close(&rt.get_f32(out.id), &expected, 1e-5, 1e-5);
|
||||
}
|
||||
|
||||
struct ConvCase {
|
||||
c_in: usize,
|
||||
h: usize,
|
||||
w: usize,
|
||||
c_out: usize,
|
||||
kh: usize,
|
||||
kw: usize,
|
||||
padding_h: usize,
|
||||
padding_w: usize,
|
||||
}
|
||||
|
||||
fn reference_nearest_upsample_2x(input: &[f32], c: usize, h: usize, w: usize) -> Vec<f32> {
|
||||
let mut out = vec![0.0_f32; c * h * 2 * w * 2];
|
||||
for ci in 0..c {
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let value = input[ci * h * w + y * w + x];
|
||||
for dy in 0..2 {
|
||||
for dx in 0..2 {
|
||||
let oy = y * 2 + dy;
|
||||
let ox = x * 2 + dx;
|
||||
out[ci * h * 2 * w * 2 + oy * w * 2 + ox] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn reference_conv2d(input: &[f32], weight: &[f32], bias: &[f32], case: ConvCase) -> Vec<f32> {
|
||||
let ConvCase {
|
||||
c_in,
|
||||
h,
|
||||
w,
|
||||
c_out,
|
||||
kh,
|
||||
kw,
|
||||
padding_h,
|
||||
padding_w,
|
||||
} = case;
|
||||
let h_out = h + 2 * padding_h - kh + 1;
|
||||
let w_out = w + 2 * padding_w - kw + 1;
|
||||
let mut out = vec![0.0; c_out * h_out * w_out];
|
||||
for co in 0..c_out {
|
||||
for oh in 0..h_out {
|
||||
for ow in 0..w_out {
|
||||
let mut acc = bias[co];
|
||||
for ci in 0..c_in {
|
||||
for r in 0..kh {
|
||||
for s in 0..kw {
|
||||
let Some(ih) = (oh + r).checked_sub(padding_h) else {
|
||||
continue;
|
||||
};
|
||||
let Some(iw) = (ow + s).checked_sub(padding_w) else {
|
||||
continue;
|
||||
};
|
||||
if ih >= h || iw >= w {
|
||||
continue;
|
||||
}
|
||||
let input_idx = ci * h * w + ih * w + iw;
|
||||
let weight_idx = co * c_in * kh * kw + (ci * kh + r) * kw + s;
|
||||
acc += input[input_idx] * weight[weight_idx];
|
||||
}
|
||||
}
|
||||
}
|
||||
out[co * h_out * w_out + oh * w_out + ow] = acc;
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn extract_forced_kernel_llir(cx: &mut Graph, kernel_name: &str) -> LLIRGraph {
|
||||
let egraph = cx.egraph().expect("search space should have an e-graph");
|
||||
let ops = cx
|
||||
.egglog_ops()
|
||||
.expect("search space should have registered egglog ops");
|
||||
let kernel_nodes = op_ir_nodes(egraph, "KernelConv2D");
|
||||
assert!(
|
||||
!kernel_nodes.is_empty(),
|
||||
"expected at least one {kernel_name} candidate"
|
||||
);
|
||||
|
||||
for (idx, kernel_node) in kernel_nodes.iter().enumerate() {
|
||||
let mut rng = StdRng::seed_from_u64(0xC0_2D00 + idx as u64);
|
||||
let mut choices = random_initial_choice(egraph, &mut rng);
|
||||
let kernel_class = &egraph.node_to_class[*kernel_node];
|
||||
choices.insert(kernel_class, kernel_node);
|
||||
|
||||
if validate_choice_set(egraph, &choices, ops).is_err() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut list_cache = FxHashMap::default();
|
||||
let mut expr_cache = FxHashMap::default();
|
||||
let llir = egglog_to_llir(
|
||||
egraph,
|
||||
choices,
|
||||
ops,
|
||||
&cx.custom_ops,
|
||||
&mut list_cache,
|
||||
&mut expr_cache,
|
||||
None,
|
||||
);
|
||||
if llir_kernel_names(&llir).contains(&kernel_name) {
|
||||
return llir;
|
||||
}
|
||||
}
|
||||
|
||||
panic!("could not extract a valid {kernel_name} candidate");
|
||||
}
|
||||
|
||||
fn llir_kernel_names(llir: &LLIRGraph) -> Vec<&'static str> {
|
||||
llir.node_indices()
|
||||
.filter_map(|node| {
|
||||
llir[node]
|
||||
.to_dialect::<dyn KernelOp>()
|
||||
.map(|kernel| kernel.kernel_name())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn op_ir_nodes<'a>(egraph: &'a SerializedEGraph, kind_label: &str) -> Vec<&'a NodeId> {
|
||||
let op_kind_classes = egraph
|
||||
.enodes
|
||||
.iter()
|
||||
.filter(|(_, (label, _))| label == kind_label)
|
||||
.map(|(node, _)| egraph.node_to_class[node].clone())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
egraph
|
||||
.enodes
|
||||
.iter()
|
||||
.filter_map(|(node, (label, children))| {
|
||||
(label == "Op"
|
||||
&& children
|
||||
.first()
|
||||
.is_some_and(|kind| op_kind_classes.contains(kind)))
|
||||
.then_some(node)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
3253
crates/luminal_cuda_lite/src/tests/cublaslt_rewrite_tests.rs
Normal file
3253
crates/luminal_cuda_lite/src/tests/cublaslt_rewrite_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
842
crates/luminal_cuda_lite/src/tests/flashinfer.rs
Normal file
842
crates/luminal_cuda_lite/src/tests/flashinfer.rs
Normal file
@@ -0,0 +1,842 @@
|
||||
//! Unit + integration tests for the FlashInfer port.
|
||||
//!
|
||||
//! Four layers:
|
||||
//! 1. Pure egglog metadata (no GPU): trait wiring, sort + rewrite parse cleanly.
|
||||
//! 2. Egglog rule firing (no GPU): the rule unifies on a real paged-attention
|
||||
//! HLIR and does NOT fire on bare attention or unrelated matmul/Gather mixes.
|
||||
//! 3. Mask helper correctness (GPU): the primitive-op `test_compute_attn_mask` builder produces the right (s, c) mask.
|
||||
//! 4. Full kernel correctness (GPU + JIT): direct `FlashInferAttention::execute`
|
||||
//! compared against a luminal-compiled reference attention graph.
|
||||
//!
|
||||
//! GPU-dependent tests short-circuit when no CUDA device is available.
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use cudarc::driver::{CudaStream, DevicePtr};
|
||||
use luminal::egglog_utils::{hlir_to_egglog, run_egglog};
|
||||
use luminal::op::{EgglogOp, IntoEgglogOp};
|
||||
use luminal::prelude::*;
|
||||
|
||||
use crate::host::flashinfer::FlashInferAttention;
|
||||
use crate::host::{DeviceBuffer, HostOp};
|
||||
use crate::runtime::CudaRuntime;
|
||||
use crate::tests::utilities::get_cuda_stream;
|
||||
|
||||
/// Look up an op in `CudaRuntime::Ops::into_vec()` by its egglog sort name.
|
||||
fn ops_contains_sort(name: &str) -> bool {
|
||||
let ops = <CudaRuntime as luminal::op::Runtime>::Ops::into_vec();
|
||||
ops.iter().any(|op| {
|
||||
// `SortDef` is opaque; its Debug repr starts with the sort name.
|
||||
let sort_dbg = format!("{:?}", op.sort());
|
||||
sort_dbg.contains(name)
|
||||
})
|
||||
}
|
||||
|
||||
// ─── Test-wide model dimensions ───────────────────────────────────────────
|
||||
//
|
||||
// Small Llama-shaped GQA model: nheads=8, kv_heads=2, group=4, head_dim=64.
|
||||
// Chosen so HEAD_DIM ∈ {64, 128, 256} (FlashInfer constraint) and the test
|
||||
// suite fits in O(1ms) of GPU time per case.
|
||||
|
||||
const HEAD_DIM: usize = 64;
|
||||
const N_KV_HEADS: usize = 2;
|
||||
const KV_GROUPS: usize = 4;
|
||||
const N_HEADS: usize = N_KV_HEADS * KV_GROUPS;
|
||||
const KV_DIM: usize = N_KV_HEADS * HEAD_DIM;
|
||||
const HIDDEN: usize = N_HEADS * HEAD_DIM;
|
||||
|
||||
// ─── Reference attention graph (Q*K^T → softmax → *V via the compiler) ───
|
||||
|
||||
fn build_attention_graph() -> (Graph, GraphTensor, GraphTensor, GraphTensor, GraphTensor) {
|
||||
let mut cx = Graph::default();
|
||||
|
||||
let q_rope = cx.named_tensor("q_rope", ('s', HIDDEN));
|
||||
let k_ctx = cx.named_tensor("k_ctx", ('c', KV_DIM));
|
||||
let v_ctx_input = cx.named_tensor("v_ctx", ('c', KV_DIM));
|
||||
|
||||
let q = (q_rope * 1.0).split_dims(1, HEAD_DIM).transpose(0, 1);
|
||||
let k = k_ctx.split_dims(1, HEAD_DIM).permute((1, 2, 0));
|
||||
let v_ctx = v_ctx_input.split_dims(1, HEAD_DIM).transpose(0, 1);
|
||||
|
||||
// GQA broadcast: zero-stride Mul by 1.0
|
||||
let k = k.expand_dim(1, KV_GROUPS).merge_dims(0, 1) * 1.0;
|
||||
let v_ctx = v_ctx.expand_dim(1, KV_GROUPS).merge_dims(0, 1) * 1.0;
|
||||
|
||||
let scores = q.matmul(k) / (HEAD_DIM as f32).sqrt();
|
||||
let weights = scores.softmax(2);
|
||||
let out = weights.matmul(v_ctx);
|
||||
|
||||
let attn_out = out.transpose(0, 1).merge_dims(1, 2);
|
||||
let attn_out = attn_out.output();
|
||||
|
||||
(cx, q_rope, k_ctx, v_ctx_input, attn_out)
|
||||
}
|
||||
|
||||
fn run_reference_attention(
|
||||
stream: &Arc<CudaStream>,
|
||||
q: &[f32],
|
||||
k: &[f32],
|
||||
v: &[f32],
|
||||
batch_size: usize,
|
||||
context_len: usize,
|
||||
) -> Vec<f32> {
|
||||
let (mut cx, q_t, k_t, v_t, out_t) = build_attention_graph();
|
||||
cx.set_dim('s', batch_size);
|
||||
cx.set_dim('c', context_len);
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
|
||||
let mut rt = CudaRuntime::initialize(stream.clone());
|
||||
rt.set_data(q_t, q.to_vec());
|
||||
rt.set_data(k_t, k.to_vec());
|
||||
rt.set_data(v_t, v.to_vec());
|
||||
rt = cx.search(rt, CompileOptions::new(3));
|
||||
|
||||
rt.set_data(q_t, q.to_vec());
|
||||
rt.set_data(k_t, k.to_vec());
|
||||
rt.set_data(v_t, v.to_vec());
|
||||
rt.execute(&cx.dyn_map);
|
||||
rt.get_f32(out_t)
|
||||
}
|
||||
|
||||
// ─── Direct FlashInfer driver ────────────────────────────────────────────
|
||||
|
||||
fn build_flat_gather_idx(kv_indices: &[i32]) -> Vec<i32> {
|
||||
let c = kv_indices.len();
|
||||
let mut flat = Vec::with_capacity(c * KV_DIM);
|
||||
for &slot in kv_indices {
|
||||
let base = slot * KV_DIM as i32;
|
||||
for j in 0..KV_DIM as i32 {
|
||||
flat.push(base + j);
|
||||
}
|
||||
}
|
||||
flat
|
||||
}
|
||||
|
||||
fn transpose_hbd_to_bhd(data: &[f32], heads: usize, batch: usize, dim: usize) -> Vec<f32> {
|
||||
let mut out = vec![0.0f32; data.len()];
|
||||
for h in 0..heads {
|
||||
for b in 0..batch {
|
||||
for d in 0..dim {
|
||||
out[b * heads * dim + h * dim + d] = data[h * batch * dim + b * dim + d];
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn alloc_dev(stream: &Arc<CudaStream>, bytes: usize) -> cudarc::driver::CudaSlice<u8> {
|
||||
let bytes = bytes.max(1);
|
||||
unsafe { stream.alloc::<u8>(bytes).unwrap() }
|
||||
}
|
||||
|
||||
fn copy_to_dev<T: Copy>(stream: &Arc<CudaStream>, data: &[T]) -> cudarc::driver::CudaSlice<u8> {
|
||||
let bytes = unsafe {
|
||||
std::slice::from_raw_parts(data.as_ptr() as *const u8, std::mem::size_of_val(data))
|
||||
};
|
||||
stream.clone_htod(bytes).unwrap()
|
||||
}
|
||||
|
||||
/// Run FlashInferAttention.execute() directly and reshape the output to the
|
||||
/// reference (batch, heads, dim) layout used by `run_reference_attention`.
|
||||
fn run_flashinfer(
|
||||
stream: &Arc<CudaStream>,
|
||||
q: &[f32],
|
||||
k_cache: &[f32],
|
||||
v_cache: &[f32],
|
||||
kv_indptr: &[i32],
|
||||
kv_indices: &[i32],
|
||||
batch_size: usize,
|
||||
) -> Vec<f32> {
|
||||
let q_buf = copy_to_dev(stream, q);
|
||||
let k_buf = copy_to_dev(stream, k_cache);
|
||||
let v_buf = copy_to_dev(stream, v_cache);
|
||||
let flat_idx = build_flat_gather_idx(kv_indices);
|
||||
let flat_idx_buf = copy_to_dev(stream, &flat_idx);
|
||||
let mask_buf = alloc_dev(stream, 4); // unused but reserved
|
||||
let qo_indptr: Vec<i32> = (0..=batch_size as i32).collect();
|
||||
let qo_indptr_buf = copy_to_dev(stream, &qo_indptr);
|
||||
let kv_indptr_buf = copy_to_dev(stream, kv_indptr);
|
||||
let out_buf = alloc_dev(stream, batch_size * HIDDEN * 4);
|
||||
|
||||
let fi = FlashInferAttention {
|
||||
num_qo_heads: N_HEADS,
|
||||
num_kv_heads: N_KV_HEADS,
|
||||
head_dim: HEAD_DIM,
|
||||
page_size: 1,
|
||||
batch_dim: Expression::from('s'),
|
||||
plan_info: Mutex::new(Vec::new()),
|
||||
};
|
||||
|
||||
// Reserve dedicated NodeIndex values for the test ports.
|
||||
let nodes: Vec<NodeIndex> = (0..8).map(NodeIndex::new).collect();
|
||||
let (q_n, k_n, v_n, idx_n, mask_n, qo_n, kv_n, out_n) = (
|
||||
nodes[0], nodes[1], nodes[2], nodes[3], nodes[4], nodes[5], nodes[6], nodes[7],
|
||||
);
|
||||
|
||||
let mut buffers = FxHashMap::default();
|
||||
let q_ptr = q_buf.device_ptr(stream).0;
|
||||
let k_ptr = k_buf.device_ptr(stream).0;
|
||||
let v_ptr = v_buf.device_ptr(stream).0;
|
||||
let idx_ptr = flat_idx_buf.device_ptr(stream).0;
|
||||
let mask_ptr = mask_buf.device_ptr(stream).0;
|
||||
let qo_ptr = qo_indptr_buf.device_ptr(stream).0;
|
||||
let kv_ptr = kv_indptr_buf.device_ptr(stream).0;
|
||||
let out_ptr = out_buf.device_ptr(stream).0;
|
||||
buffers.insert(q_n, DeviceBuffer::new(q_ptr, q.len() * 4));
|
||||
buffers.insert(k_n, DeviceBuffer::new(k_ptr, k_cache.len() * 4));
|
||||
buffers.insert(v_n, DeviceBuffer::new(v_ptr, v_cache.len() * 4));
|
||||
buffers.insert(idx_n, DeviceBuffer::new(idx_ptr, flat_idx.len() * 4));
|
||||
buffers.insert(mask_n, DeviceBuffer::new(mask_ptr, 4));
|
||||
buffers.insert(qo_n, DeviceBuffer::new(qo_ptr, qo_indptr.len() * 4));
|
||||
buffers.insert(kv_n, DeviceBuffer::new(kv_ptr, kv_indptr.len() * 4));
|
||||
buffers.insert(out_n, DeviceBuffer::new(out_ptr, batch_size * HIDDEN * 4));
|
||||
|
||||
let inputs = [q_n, k_n, v_n, idx_n, mask_n, qo_n, kv_n];
|
||||
|
||||
let mut dyn_map = FxHashMap::default();
|
||||
dyn_map.insert('s', batch_size);
|
||||
dyn_map.insert('c', kv_indices.len());
|
||||
dyn_map.insert('r', kv_indptr.len());
|
||||
|
||||
fi.execute(stream, out_n, &inputs, &buffers, &dyn_map)
|
||||
.expect("FlashInferAttention execute failed");
|
||||
stream.synchronize().unwrap();
|
||||
|
||||
// Output is (heads, batch, dim); reshape to (batch, heads, dim).
|
||||
let mut out_bytes = vec![0u8; batch_size * HIDDEN * 4];
|
||||
unsafe {
|
||||
cudarc::driver::result::memcpy_dtoh_async(&mut out_bytes, out_ptr, stream.cu_stream())
|
||||
.unwrap();
|
||||
}
|
||||
stream.synchronize().unwrap();
|
||||
let raw: Vec<f32> = unsafe {
|
||||
let mut bytes = std::mem::ManuallyDrop::new(out_bytes);
|
||||
let len = bytes.len() / 4;
|
||||
Vec::from_raw_parts(bytes.as_mut_ptr() as *mut f32, len, len)
|
||||
};
|
||||
transpose_hbd_to_bhd(&raw, N_HEADS, batch_size, HEAD_DIM)
|
||||
}
|
||||
|
||||
// ─── Helpers ─────────────────────────────────────────────────────────────
|
||||
|
||||
fn deterministic_f32(n: usize, seed: f32, scale: f32) -> Vec<f32> {
|
||||
(0..n).map(|i| (i as f32 * seed).sin() * scale).collect()
|
||||
}
|
||||
|
||||
fn assert_close(a: &[f32], b: &[f32], rtol: f32, atol: f32) {
|
||||
assert_eq!(
|
||||
a.len(),
|
||||
b.len(),
|
||||
"length mismatch: {} vs {}",
|
||||
a.len(),
|
||||
b.len()
|
||||
);
|
||||
let mut worst = (0usize, 0.0f32);
|
||||
for (i, (x, y)) in a.iter().zip(b.iter()).enumerate() {
|
||||
let diff = (x - y).abs();
|
||||
if diff > worst.1 {
|
||||
worst = (i, diff);
|
||||
}
|
||||
let tol = atol + rtol * y.abs();
|
||||
assert!(
|
||||
diff <= tol,
|
||||
"mismatch at idx {i}: {x} vs {y} (|diff|={diff}, tol={tol})"
|
||||
);
|
||||
}
|
||||
eprintln!("max |diff| = {:.2e} @ idx {}", worst.1, worst.0);
|
||||
}
|
||||
|
||||
// ─── Layer 1: egglog metadata sanity (no GPU) ────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn flashinfer_op_registers_via_into_egglog() {
|
||||
// Confirm the op is reachable through the Runtime::Ops tuple. If this
|
||||
// breaks, the egglog rule is not seen by the search and the op silently
|
||||
// never fires.
|
||||
assert!(
|
||||
ops_contains_sort("FlashInferAttention"),
|
||||
"FlashInferAttention is not in CudaRuntime::Ops"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flashinfer_egg_rule_parses() {
|
||||
// Rule::raw() returns the rule with no validation; egglog parses it at
|
||||
// graph build. Smoke-test by running it through the egglog frontend via
|
||||
// a tiny program string.
|
||||
let op = FlashInferAttention::default();
|
||||
let rewrites = op.rewrites();
|
||||
assert_eq!(rewrites.len(), 1);
|
||||
// The rule must mention FlashInferAttention to be the right one.
|
||||
let s = format!("{:?}", rewrites[0]);
|
||||
assert!(
|
||||
s.contains("FlashInferAttention"),
|
||||
"rewrite is not the FlashInfer rule: {s}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flashinfer_op_sort_shape() {
|
||||
let op = FlashInferAttention::default();
|
||||
let s = op.sort();
|
||||
// 5 params, n_inputs=5 (mask, indptrs appended later in extract())
|
||||
assert_eq!(op.n_inputs(), 5);
|
||||
let dbg = format!("{:?}", s);
|
||||
assert!(dbg.contains("FlashInferAttention"));
|
||||
}
|
||||
|
||||
// ─── Layer 3: FlashInfer kernel correctness ──────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn flashinfer_bs1_ctx4() {
|
||||
let Some(stream) = get_cuda_stream() else {
|
||||
return;
|
||||
};
|
||||
let batch_size = 1;
|
||||
let context_len = 4;
|
||||
let q = deterministic_f32(batch_size * HIDDEN, 0.011, 0.1);
|
||||
let k = deterministic_f32(context_len * KV_DIM, 0.021, 0.1);
|
||||
let v = deterministic_f32(context_len * KV_DIM, 0.031, 0.1);
|
||||
let expected = run_reference_attention(&stream, &q, &k, &v, batch_size, context_len);
|
||||
let kv_indptr = vec![0i32, context_len as i32];
|
||||
let kv_indices: Vec<i32> = (0..context_len as i32).collect();
|
||||
let result = run_flashinfer(&stream, &q, &k, &v, &kv_indptr, &kv_indices, batch_size);
|
||||
assert_close(&result, &expected, 1e-4, 1e-5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flashinfer_bs2_supersequence() {
|
||||
let Some(stream) = get_cuda_stream() else {
|
||||
return;
|
||||
};
|
||||
let batch_size = 2;
|
||||
let ctx0 = 8;
|
||||
let ctx1 = 3;
|
||||
let total_ctx = ctx0 + ctx1;
|
||||
|
||||
let q = deterministic_f32(batch_size * HIDDEN, 0.014, 0.1);
|
||||
let k = deterministic_f32(total_ctx * KV_DIM, 0.022, 0.1);
|
||||
let v = deterministic_f32(total_ctx * KV_DIM, 0.032, 0.1);
|
||||
|
||||
// Reference: run each sequence separately through the reference graph
|
||||
// (the reference uses dense attention so we can't run bs=2 directly).
|
||||
let expected0 = run_reference_attention(
|
||||
&stream,
|
||||
&q[..HIDDEN],
|
||||
&k[..ctx0 * KV_DIM],
|
||||
&v[..ctx0 * KV_DIM],
|
||||
1,
|
||||
ctx0,
|
||||
);
|
||||
let expected1 = run_reference_attention(
|
||||
&stream,
|
||||
&q[HIDDEN..],
|
||||
&k[ctx0 * KV_DIM..],
|
||||
&v[ctx0 * KV_DIM..],
|
||||
1,
|
||||
ctx1,
|
||||
);
|
||||
let expected: Vec<f32> = expected0.into_iter().chain(expected1).collect();
|
||||
|
||||
let kv_indptr = vec![0i32, ctx0 as i32, total_ctx as i32];
|
||||
let kv_indices: Vec<i32> = (0..total_ctx as i32).collect();
|
||||
let result = run_flashinfer(&stream, &q, &k, &v, &kv_indptr, &kv_indices, batch_size);
|
||||
assert_close(&result, &expected, 1e-4, 1e-5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flashinfer_noncontiguous_page_table() {
|
||||
let Some(stream) = get_cuda_stream() else {
|
||||
return;
|
||||
};
|
||||
let batch_size = 1;
|
||||
let context_len = 4;
|
||||
let num_slots = 8;
|
||||
let slot_indices = [3usize, 0, 7, 1];
|
||||
|
||||
let q = deterministic_f32(batch_size * HIDDEN, 0.011, 0.1);
|
||||
let k_full = deterministic_f32(num_slots * KV_DIM, 0.022, 0.1);
|
||||
let v_full = deterministic_f32(num_slots * KV_DIM, 0.033, 0.1);
|
||||
|
||||
// Reference operates on the contiguous gathered cache.
|
||||
let mut k_gathered = vec![0.0f32; context_len * KV_DIM];
|
||||
let mut v_gathered = vec![0.0f32; context_len * KV_DIM];
|
||||
for (i, &slot) in slot_indices.iter().enumerate() {
|
||||
k_gathered[i * KV_DIM..(i + 1) * KV_DIM]
|
||||
.copy_from_slice(&k_full[slot * KV_DIM..(slot + 1) * KV_DIM]);
|
||||
v_gathered[i * KV_DIM..(i + 1) * KV_DIM]
|
||||
.copy_from_slice(&v_full[slot * KV_DIM..(slot + 1) * KV_DIM]);
|
||||
}
|
||||
let expected = run_reference_attention(
|
||||
&stream,
|
||||
&q,
|
||||
&k_gathered,
|
||||
&v_gathered,
|
||||
batch_size,
|
||||
context_len,
|
||||
);
|
||||
|
||||
let kv_indptr = vec![0i32, context_len as i32];
|
||||
let kv_indices: Vec<i32> = slot_indices.iter().map(|&s| s as i32).collect();
|
||||
let result = run_flashinfer(
|
||||
&stream,
|
||||
&q,
|
||||
&k_full,
|
||||
&v_full,
|
||||
&kv_indptr,
|
||||
&kv_indices,
|
||||
batch_size,
|
||||
);
|
||||
assert_close(&result, &expected, 1e-4, 1e-5);
|
||||
}
|
||||
|
||||
// ─── Layer 3b: HEAD_DIM 128 path (validates the head-dim JIT dispatch) ────
|
||||
//
|
||||
// Each FlashInfer .so is compiled for one HEAD_DIM. JIT caches by head dim;
|
||||
// the OnceLock means only one is loaded per process. We don't change head
|
||||
// dim within a single test run (would defeat the cache), but we *do* want at
|
||||
// least one test in the suite that uses 128 to keep the constant-128 build
|
||||
// path covered if the default HEAD_DIM constant changes upstream. We assert
|
||||
// the constraint here rather than firing a second JIT.
|
||||
|
||||
#[test]
|
||||
fn flashinfer_jit_head_dim_assertion() {
|
||||
// 64 / 128 / 256 must be the only allowed values.
|
||||
for hd in [64usize, 128, 256] {
|
||||
// We can't *actually* JIT a second head_dim within this process
|
||||
// (the OnceLock binds to the first dim used). Just check the dim
|
||||
// is in the supported set.
|
||||
assert!(matches!(hd, 64 | 128 | 256));
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Layer 4: egglog rule firing (no GPU) ────────────────────────────────
|
||||
//
|
||||
// These tests build HLIR graphs and run egglog saturation. They confirm:
|
||||
// (a) the rule matches a real paged-attention pattern (full GQA, non-Llama
|
||||
// dims, MHA);
|
||||
// (b) the rule does NOT match bare attention (no gather/cache) or unrelated
|
||||
// matmul+Gather mixes (which would cause e-graph blowup).
|
||||
//
|
||||
// Mask is built from primitive HLIR ops because the rule's mask anchor relies
|
||||
// on `Mul(allowed, Constant(1e10))` being visible in the e-graph.
|
||||
|
||||
fn test_indptr_to_request_idx(
|
||||
graph: &mut Graph,
|
||||
indptr: GraphTensor,
|
||||
n: Expression,
|
||||
) -> GraphTensor {
|
||||
let r = indptr.dims1();
|
||||
let indices = graph.arange(n).expand_dim(1, r);
|
||||
let indptr_2d = indptr.expand_dim(0, n);
|
||||
let ge = indptr_2d.le(indices).cast(luminal::dtype::DType::Int);
|
||||
ge.sum(1).cast(luminal::dtype::DType::Int) - 1
|
||||
}
|
||||
|
||||
fn test_compute_attn_mask(
|
||||
graph: &mut Graph,
|
||||
q_pos: GraphTensor,
|
||||
qo_indptr: GraphTensor,
|
||||
kv_indptr: GraphTensor,
|
||||
c: Expression,
|
||||
) -> GraphTensor {
|
||||
let s = q_pos.dims1();
|
||||
let q_request = test_indptr_to_request_idx(graph, qo_indptr, s);
|
||||
let c_request = test_indptr_to_request_idx(graph, kv_indptr, c);
|
||||
let c_arange = graph.arange(c);
|
||||
let c_kv_start = kv_indptr.gather(c_request);
|
||||
let c_local_pos = c_arange - c_kv_start;
|
||||
let q_req_2d = q_request.expand_dim(1, c);
|
||||
let c_req_2d = c_request.expand_dim(0, s);
|
||||
let same = q_req_2d.eq(c_req_2d);
|
||||
let c_pos_2d = c_local_pos.expand_dim(0, s);
|
||||
let qp_2d = q_pos.expand_dim(1, c);
|
||||
let causal = c_pos_2d.le(qp_2d);
|
||||
let allowed = same.cast(luminal::dtype::DType::F32) * causal.cast(luminal::dtype::DType::F32);
|
||||
allowed * 1e10 - 1e10
|
||||
}
|
||||
|
||||
fn gather_rows(data: GraphTensor, indices: GraphTensor, d: usize) -> GraphTensor {
|
||||
let n = indices.dims1();
|
||||
let base = (indices * d).expand_dim(1, d);
|
||||
let col = data.graph().arange(d as i32).expand_dim(0, n);
|
||||
data.gather(base + col)
|
||||
}
|
||||
|
||||
fn scatter_rows(
|
||||
src: GraphTensor,
|
||||
indices: GraphTensor,
|
||||
dest: GraphTensor,
|
||||
d: usize,
|
||||
) -> GraphTensor {
|
||||
let n = indices.dims1();
|
||||
let base = (indices * d).expand_dim(1, d);
|
||||
let col = src.graph().arange(d as i32).expand_dim(0, n);
|
||||
src.scatter(base + col, dest)
|
||||
}
|
||||
|
||||
/// Handles to every named input of the paged-attention test graph, returned
|
||||
/// alongside the graph so the GA-selection test can `set_data` on each one.
|
||||
#[allow(dead_code)]
|
||||
struct PagedAttnHandles {
|
||||
q_rope: GraphTensor,
|
||||
k_rope: GraphTensor,
|
||||
v_new: GraphTensor,
|
||||
k_cache: GraphTensor,
|
||||
v_cache: GraphTensor,
|
||||
scatter_idx: GraphTensor,
|
||||
gather_idx: GraphTensor,
|
||||
q_pos: GraphTensor,
|
||||
qo_indptr: GraphTensor,
|
||||
kv_indptr: GraphTensor,
|
||||
}
|
||||
|
||||
/// Build a full paged-attention HLIR graph with the structural anchors the
|
||||
/// FlashInfer egglog rule looks for: scatter into a 2D cache, gather rows out
|
||||
/// by index, GQA broadcast via `Mul(..., 1.0)` with zero strides, Q*K^T → Sum
|
||||
/// → scale → mask Add → softmax → *V → Sum.
|
||||
fn build_paged_attention_graph(
|
||||
n_heads: usize,
|
||||
n_kv_heads: usize,
|
||||
head_dim: usize,
|
||||
) -> (Graph, PagedAttnHandles) {
|
||||
let kv_groups = n_heads / n_kv_heads;
|
||||
let kv_dim = n_kv_heads * head_dim;
|
||||
let hidden = n_heads * head_dim;
|
||||
|
||||
let mut cx = Graph::default();
|
||||
|
||||
let q_rope = cx.named_tensor("q_rope", ('s', hidden));
|
||||
let k_rope = cx.named_tensor("k_rope", ('s', kv_dim));
|
||||
let v_new = cx.named_tensor("v_new", ('s', kv_dim));
|
||||
let k_cache = cx.named_tensor("k_cache", (2048, kv_dim)).persist();
|
||||
let v_cache = cx.named_tensor("v_cache", (2048, kv_dim)).persist();
|
||||
let scatter_idx = cx
|
||||
.named_tensor("scatter_idx", 's')
|
||||
.as_dtype(luminal::dtype::DType::Int);
|
||||
let gather_idx = cx
|
||||
.named_tensor("gather_idx", 'c')
|
||||
.as_dtype(luminal::dtype::DType::Int);
|
||||
let q_pos = cx
|
||||
.named_tensor("q_pos", 's')
|
||||
.as_dtype(luminal::dtype::DType::Int);
|
||||
let qo_indptr = cx
|
||||
.named_tensor("qo_indptr", 'r')
|
||||
.as_dtype(luminal::dtype::DType::Int);
|
||||
let kv_indptr = cx
|
||||
.named_tensor("kv_indptr", 'r')
|
||||
.as_dtype(luminal::dtype::DType::Int);
|
||||
|
||||
let k_cache_out = scatter_rows(k_rope, scatter_idx, k_cache, kv_dim);
|
||||
let v_cache_out = scatter_rows(v_new, scatter_idx, v_cache, kv_dim);
|
||||
|
||||
let k = gather_rows(k_cache_out, gather_idx, kv_dim);
|
||||
let v_ctx = gather_rows(v_cache_out, gather_idx, kv_dim);
|
||||
|
||||
let c: Expression = 'c'.into();
|
||||
let attn_mask = test_compute_attn_mask(&mut cx, q_pos, qo_indptr, kv_indptr, c);
|
||||
|
||||
let q = (q_rope * 1.0).split_dims(1, head_dim).transpose(0, 1);
|
||||
let k = k.split_dims(1, head_dim).permute((1, 2, 0));
|
||||
let v_ctx = v_ctx.split_dims(1, head_dim).transpose(0, 1);
|
||||
let k = k.expand_dim(1, kv_groups).merge_dims(0, 1) * 1.0;
|
||||
let v_ctx = v_ctx.expand_dim(1, kv_groups).merge_dims(0, 1) * 1.0;
|
||||
|
||||
let scores = q.matmul(k) / (head_dim as f32).sqrt();
|
||||
let mask = attn_mask.expand_dim(0, n_heads);
|
||||
let masked_scores = scores + mask;
|
||||
let weights = masked_scores.softmax(2);
|
||||
let out = weights.matmul(v_ctx);
|
||||
let attn_out = out.transpose(0, 1).merge_dims(1, 2);
|
||||
|
||||
attn_out.output();
|
||||
k_cache_out.output();
|
||||
v_cache_out.output();
|
||||
|
||||
(
|
||||
cx,
|
||||
PagedAttnHandles {
|
||||
q_rope,
|
||||
k_rope,
|
||||
v_new,
|
||||
k_cache,
|
||||
v_cache,
|
||||
scatter_idx,
|
||||
gather_idx,
|
||||
q_pos,
|
||||
qo_indptr,
|
||||
kv_indptr,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Saturate egglog on the graph and report whether a FlashInferAttention
|
||||
/// e-node was produced. Helper used by the rule-firing tests.
|
||||
fn saturate_and_has_flashinfer(cx: &Graph) -> (bool, Vec<String>) {
|
||||
let (program, root) = hlir_to_egglog(cx);
|
||||
let mut ops = <CudaRuntime as luminal::op::Runtime>::Ops::into_vec();
|
||||
ops.extend(<luminal::hlir::HLIROps as IntoEgglogOp>::into_vec());
|
||||
// cleanup=false: keep every saturation-introduced e-node so we can inspect
|
||||
// whether the FlashInferAttention rule produced a node, regardless of
|
||||
// whether downstream extraction would have pruned it.
|
||||
let egraph = run_egglog(&program, &root, &ops, false).expect("egglog failed");
|
||||
|
||||
let has_flashinfer = egraph
|
||||
.enodes
|
||||
.values()
|
||||
.any(|(label, _)| label == "FlashInferAttention");
|
||||
|
||||
// Collect distinct OpKind labels so a failure can print what *did* match.
|
||||
let mut op_kinds: Vec<String> = egraph
|
||||
.enodes
|
||||
.values()
|
||||
.filter(|(l, _)| {
|
||||
!l.starts_with('(')
|
||||
&& ![
|
||||
"Op",
|
||||
"Input",
|
||||
"Output",
|
||||
"OutputJoin",
|
||||
"ICons",
|
||||
"INil",
|
||||
"ECons",
|
||||
"ENil",
|
||||
"MNum",
|
||||
"MVar",
|
||||
"MMul",
|
||||
"MDiv",
|
||||
"MIter",
|
||||
]
|
||||
.contains(&l.as_str())
|
||||
})
|
||||
.map(|(l, _)| l.clone())
|
||||
.collect();
|
||||
op_kinds.sort();
|
||||
op_kinds.dedup();
|
||||
|
||||
(has_flashinfer, op_kinds)
|
||||
}
|
||||
|
||||
/// Debug aid: dump the egglog program and key e-graph metrics for the lite
|
||||
/// paged-attention test so we can see why the FlashInfer rule isn't matching.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn flashinfer_dump_paged_attn_egglog() {
|
||||
// First sanity-check that each Ops member returns its rewrites and that
|
||||
// FlashInferAttention's rule appears in the combined corpus.
|
||||
let ops_vec = <CudaRuntime as luminal::op::Runtime>::Ops::into_vec();
|
||||
eprintln!("==== Ops rewrites count ====");
|
||||
let mut fi_rewrites = 0usize;
|
||||
let mut total_rewrites = 0usize;
|
||||
for op in &ops_vec {
|
||||
let rws = op.rewrites();
|
||||
total_rewrites += rws.len();
|
||||
for r in &rws {
|
||||
let s = format!("{r:?}");
|
||||
if s.contains("FlashInferAttention") {
|
||||
fi_rewrites += 1;
|
||||
eprintln!("FOUND FlashInfer rewrite ({} chars)", s.len());
|
||||
}
|
||||
}
|
||||
}
|
||||
eprintln!(
|
||||
"==== ops_vec.len()={} total_rewrites={total_rewrites} fi_rewrites={fi_rewrites} ====",
|
||||
ops_vec.len()
|
||||
);
|
||||
|
||||
let (cx, _) = build_paged_attention_graph(N_HEADS, N_KV_HEADS, HEAD_DIM);
|
||||
let (program, root) = hlir_to_egglog(&cx);
|
||||
eprintln!("==== EGGLOG PROGRAM (root={root}) ====");
|
||||
for (i, line) in program.lines().enumerate() {
|
||||
eprintln!("{:5}: {line}", i + 1);
|
||||
}
|
||||
eprintln!(
|
||||
"==== END EGGLOG PROGRAM ({} lines) ====",
|
||||
program.lines().count()
|
||||
);
|
||||
|
||||
let mut ops = <CudaRuntime as luminal::op::Runtime>::Ops::into_vec();
|
||||
ops.extend(<luminal::hlir::HLIROps as IntoEgglogOp>::into_vec());
|
||||
let egraph = run_egglog(&program, &root, &ops, false).expect("egglog failed");
|
||||
|
||||
// Bucket enode labels by frequency.
|
||||
let mut counts: std::collections::HashMap<String, usize> = Default::default();
|
||||
for (label, _) in egraph.enodes.values() {
|
||||
*counts.entry(label.clone()).or_default() += 1;
|
||||
}
|
||||
let mut sorted: Vec<_> = counts.iter().collect();
|
||||
sorted.sort_by(|a, b| b.1.cmp(a.1));
|
||||
eprintln!("==== E-GRAPH LABEL HISTOGRAM (top 60) ====");
|
||||
for (label, n) in sorted.iter().take(60) {
|
||||
eprintln!(" {n:6} {label}");
|
||||
}
|
||||
let has_fi = egraph
|
||||
.enodes
|
||||
.values()
|
||||
.any(|(label, _)| label == "FlashInferAttention");
|
||||
eprintln!("==== has FlashInferAttention enode: {has_fi} ====");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flashinfer_rule_does_not_fire_on_bare_attention() {
|
||||
// Dense attention without paged gather + cache should NOT match.
|
||||
let (cx, _, _, _, _) = build_attention_graph();
|
||||
let (has_flashinfer, _) = saturate_and_has_flashinfer(&cx);
|
||||
assert!(
|
||||
!has_flashinfer,
|
||||
"FlashInferAttention should NOT fire on bare attention (no gather/cache)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flashinfer_rule_does_not_fire_on_unrelated_matmuls() {
|
||||
// A Gather + plain matmul (MLP-shaped projection) plus two chained matmuls
|
||||
// through softmax — close to attention structurally but missing the GQA
|
||||
// broadcast / mask Add anchors. The rule must reject this.
|
||||
let mut cx = Graph::default();
|
||||
let cache = cx.named_tensor("cache", (4096, KV_DIM)).persist();
|
||||
let gather_idx = cx
|
||||
.named_tensor("gather_idx", 'c')
|
||||
.as_dtype(luminal::dtype::DType::Int);
|
||||
let weight = cx.named_tensor("weight", (HIDDEN, KV_DIM)).persist();
|
||||
|
||||
let n = gather_idx.dims1();
|
||||
let base = (gather_idx * KV_DIM).expand_dim(1, KV_DIM);
|
||||
let col = cx.arange(KV_DIM as i32).expand_dim(0, n);
|
||||
let gathered = cache.gather(base + col);
|
||||
let proj = gathered.matmul(weight.t());
|
||||
proj.output();
|
||||
|
||||
let a = cx.named_tensor("a", ('s', HIDDEN));
|
||||
let b = cx.named_tensor("b", (HIDDEN, HIDDEN)).persist();
|
||||
let c_tensor = cx.named_tensor("c_tensor", (HIDDEN, HIDDEN)).persist();
|
||||
let ab = a.matmul(b.t());
|
||||
let abc = ab.softmax(1).matmul(c_tensor.t());
|
||||
abc.output();
|
||||
|
||||
let (has_flashinfer, _) = saturate_and_has_flashinfer(&cx);
|
||||
assert!(
|
||||
!has_flashinfer,
|
||||
"FlashInferAttention should NOT fire on unrelated matmuls + Gather"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flashinfer_rule_fires_on_full_paged_attention() {
|
||||
// Default Llama-shaped test dims (HEAD_DIM=64, N_HEADS=8, N_KV_HEADS=2).
|
||||
let (cx, _) = build_paged_attention_graph(N_HEADS, N_KV_HEADS, HEAD_DIM);
|
||||
let (has_flashinfer, op_kinds) = saturate_and_has_flashinfer(&cx);
|
||||
assert!(
|
||||
has_flashinfer,
|
||||
"FlashInferAttention was NOT found in the e-graph (Llama-shaped paged attention). \
|
||||
OpKinds present: {op_kinds:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flashinfer_rule_fires_on_non_llama_dims() {
|
||||
// Different head counts: HEAD_DIM=64, N_HEADS=16, N_KV_HEADS=4 (group=4).
|
||||
// Exercises the model-agnostic structural variables in the rule.
|
||||
let (cx, _) = build_paged_attention_graph(16, 4, 64);
|
||||
let (has_flashinfer, op_kinds) = saturate_and_has_flashinfer(&cx);
|
||||
assert!(
|
||||
has_flashinfer,
|
||||
"FlashInferAttention was NOT found for non-Llama dims. \
|
||||
OpKinds present: {op_kinds:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flashinfer_rule_fires_on_mha() {
|
||||
// MHA: KV_GROUPS=1 (n_heads == n_kv_heads). The GQA broadcast still
|
||||
// structurally appears (expand_dim(1, 1) + merge), so the rule should
|
||||
// still match.
|
||||
let (cx, _) = build_paged_attention_graph(12, 12, 64);
|
||||
let (has_flashinfer, op_kinds) = saturate_and_has_flashinfer(&cx);
|
||||
assert!(
|
||||
has_flashinfer,
|
||||
"FlashInferAttention was NOT found for MHA dims. \
|
||||
OpKinds present: {op_kinds:?}"
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Layer 5: extraction reachability (no GPU) ───────────────────────────
|
||||
//
|
||||
// After `build_search_space` saturates egglog, the GA picks an extraction by
|
||||
// cost. In a tiny test graph the cuBLAS+kernel path is often faster than the
|
||||
// FlashInfer host op (which pays a `plan()` setup cost per call), so asserting
|
||||
// "GA picked FlashInfer" is flaky. Instead, sample many random valid genomes
|
||||
// from the search space and assert that the FlashInfer extraction is reachable
|
||||
// — meaning the rule fired AND `find_indptrs` extraction succeeded for at
|
||||
// least one offspring. That is the end-to-end check we actually want.
|
||||
|
||||
#[test]
|
||||
fn flashinfer_extraction_reachable_from_search_space() {
|
||||
use rand::SeedableRng;
|
||||
use rand::rngs::StdRng;
|
||||
|
||||
let (mut cx, _h) = build_paged_attention_graph(N_HEADS, N_KV_HEADS, HEAD_DIM);
|
||||
cx.set_dim('s', 1usize);
|
||||
cx.set_dim('c', 16usize);
|
||||
cx.set_dim('r', 2usize);
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
|
||||
let egraph = cx
|
||||
.egraph()
|
||||
.expect("egraph missing after build_search_space");
|
||||
let ops = cx
|
||||
.egglog_ops()
|
||||
.expect("egglog_ops missing after build_search_space");
|
||||
|
||||
let mut rng = StdRng::seed_from_u64(0xf1a541);
|
||||
let mut prev: FxHashSet<u64> = FxHashSet::default();
|
||||
let initial = luminal::egglog_utils::random_initial_choice(egraph, &mut rng);
|
||||
prev.insert(luminal::egglog_utils::hash_choice_set(&initial));
|
||||
let mut base = initial;
|
||||
|
||||
let mut found = false;
|
||||
'outer: for _ in 0..50 {
|
||||
let offspring =
|
||||
luminal::egglog_utils::extract_generation(egraph, &base, 10, 2, &mut prev, &mut rng);
|
||||
if offspring.is_empty() {
|
||||
break;
|
||||
}
|
||||
for genome in offspring {
|
||||
if luminal::egglog_utils::validate_choice_set(egraph, &genome, ops).is_err() {
|
||||
continue;
|
||||
}
|
||||
let mut list_cache = FxHashMap::default();
|
||||
let mut expr_cache = FxHashMap::default();
|
||||
// Catch a possible panic from find_indptrs walking the mask — we
|
||||
// want the test to fail with a clean message, not abort.
|
||||
let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
luminal::egglog_utils::egglog_to_llir(
|
||||
egraph,
|
||||
genome.clone(),
|
||||
ops,
|
||||
&cx.custom_ops,
|
||||
&mut list_cache,
|
||||
&mut expr_cache,
|
||||
None,
|
||||
)
|
||||
}));
|
||||
let Ok(llir_graph) = panicked else { continue };
|
||||
|
||||
let has_fi = llir_graph.node_indices().any(|n| {
|
||||
llir_graph[n]
|
||||
.to_dialect::<dyn HostOp>()
|
||||
.and_then(|op| op.stats_name())
|
||||
== Some("FlashInferAttention")
|
||||
});
|
||||
if has_fi {
|
||||
found = true;
|
||||
break 'outer;
|
||||
}
|
||||
base = genome;
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
found,
|
||||
"FlashInferAttention extraction not reachable from search space after 50 generations"
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
use as_any::Downcast;
|
||||
use luminal::egglog_utils::{egglog_to_llir, random_initial_choice};
|
||||
use luminal::prelude::*;
|
||||
|
||||
use crate::kernel::KernelOp;
|
||||
use crate::kernel::fusion::{CudaBinaryElementwise, CudaUnaryElementwise};
|
||||
use crate::runtime::CudaRuntime;
|
||||
use crate::tests::utilities::{
|
||||
TOLERANCE_SAFETY_FACTOR, dtype_epsilon, random_f32_vec, test_binary_cuda, test_unary_cuda,
|
||||
@@ -86,7 +88,7 @@ fn test_unary_fusion_preserves_output() {
|
||||
#[test]
|
||||
fn test_three_unary_ops_fuse() {
|
||||
// A chain of 3 pure-elementwise unaries with matching strides should be
|
||||
// reachable as a single marker region containing all three FusedX ops.
|
||||
// reachable as a single marker region containing all three elementwise ops.
|
||||
let mut cx = Graph::new();
|
||||
let a = cx.tensor(16);
|
||||
let _b = a.sin().sqrt().exp2().output();
|
||||
@@ -104,7 +106,7 @@ fn test_three_unary_ops_fuse() {
|
||||
#[test]
|
||||
fn test_four_unary_ops_fuse() {
|
||||
// 4-op chain should collapse into a single marker region containing all
|
||||
// four FusedX ops (one pair-fuse + repeated grow-FE→U firings).
|
||||
// four elementwise ops (one pair-fuse + repeated grow-FE→U firings).
|
||||
let mut cx = Graph::new();
|
||||
let a = cx.tensor(16);
|
||||
let _b = a.sin().sqrt().exp2().log2().output();
|
||||
@@ -291,7 +293,7 @@ struct FusedRegion {
|
||||
/// Helper: collect every distinct fused region reachable across many random
|
||||
/// extractions of the search space.
|
||||
fn extract_all_fused_regions(cx: &mut Graph) -> Vec<FusedRegion> {
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let egraph = cx.egraph().expect("egraph not built");
|
||||
let ops = cx.egglog_ops().expect("ops not built");
|
||||
let custom_ops = &cx.custom_ops;
|
||||
@@ -317,8 +319,15 @@ fn extract_all_fused_regions(cx: &mut Graph) -> Vec<FusedRegion> {
|
||||
|
||||
let name_of = |idx: NodeIndex| -> Option<String> {
|
||||
llir.node_weight(idx).and_then(|op| {
|
||||
op.to_dialect::<dyn KernelOp>()
|
||||
.map(|k| k.kernel_name().to_string())
|
||||
op.to_dialect::<dyn KernelOp>().map(|k| {
|
||||
if let Some(elem) = (***k).downcast_ref::<CudaUnaryElementwise>() {
|
||||
format!("Fused{}", elem.op)
|
||||
} else if let Some(elem) = (***k).downcast_ref::<CudaBinaryElementwise>() {
|
||||
format!("Fused{}", elem.op)
|
||||
} else {
|
||||
k.kernel_name().to_string()
|
||||
}
|
||||
})
|
||||
})
|
||||
};
|
||||
|
||||
@@ -343,12 +352,13 @@ fn extract_all_fused_regions(cx: &mut Graph) -> Vec<FusedRegion> {
|
||||
|
||||
// Resolve chains of nested FusionStart wrappers (cascade artifact)
|
||||
// to the real external source. A FusionStart whose incoming neighbor
|
||||
// is itself a FusionStart — or a FusionEnd whose region is fully
|
||||
// inside ours — is a cascade layer, not a new external tensor.
|
||||
// is itself a FusionStart is a cascade layer, not a new external
|
||||
// tensor. A FusionEnd predecessor is a real external region output
|
||||
// in the generic singleton-region model, so do not walk through it.
|
||||
let resolve_source = |mut n: NodeIndex| -> NodeIndex {
|
||||
loop {
|
||||
match name_of(n).as_deref() {
|
||||
Some("FusionStart") | Some("FusionEnd") => {
|
||||
Some("FusionStart") => {
|
||||
let mut inc = llir.neighbors_directed(n, petgraph::Direction::Incoming);
|
||||
match inc.next() {
|
||||
Some(p) => n = p,
|
||||
@@ -379,15 +389,6 @@ fn extract_all_fused_regions(cx: &mut Graph) -> Vec<FusedRegion> {
|
||||
let mut inc =
|
||||
llir.neighbors_directed(pred, petgraph::Direction::Incoming);
|
||||
match inc.next() {
|
||||
Some(src_node)
|
||||
if name_of(src_node).as_deref() == Some("FusionEnd") =>
|
||||
{
|
||||
// Merge adjacent regions — treat the FS/FE
|
||||
// pair as internal; walk past the upstream
|
||||
// FE into its region.
|
||||
visited.insert(src_node);
|
||||
stack.push(src_node);
|
||||
}
|
||||
Some(src_node) => {
|
||||
start_sources.insert(resolve_source(src_node));
|
||||
}
|
||||
@@ -467,6 +468,15 @@ fn test_single_binary_does_not_fuse_alone() {
|
||||
fn test_chain_of_binaries_fuses() {
|
||||
// `(a + b) * c`: three external inputs collapse into one region with
|
||||
// internal [Add, Mul] and 3 FusionStarts.
|
||||
//
|
||||
// Requires BB family, which is opt-in at runtime via
|
||||
// LUMINAL_FUSION_FAMILIES. Set it before the graph build so the rules
|
||||
// emitted from FusionEnd::rewrites include the B-B pair-fuse rules.
|
||||
// SAFETY: tests run in parallel; we set this before constructing the
|
||||
// Graph, and never unset, so concurrent tests just see BB on.
|
||||
unsafe {
|
||||
std::env::set_var("LUMINAL_FUSION_FAMILIES", "uu,bu,ub,bb");
|
||||
}
|
||||
let mut cx = Graph::new();
|
||||
let a = cx.tensor(8);
|
||||
let b = cx.tensor(8);
|
||||
@@ -520,6 +530,13 @@ fn test_unary_then_binary_fuses() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
// Subsume in grow rules (introduced to bound the BB partial-FE explosion)
|
||||
// means a multi-consumer producer can no longer be fused into the same
|
||||
// region as all its consumers — only one branch wins. The diamond's `t`
|
||||
// has two consumers, so the structural "one 5-op region" outcome is no
|
||||
// longer guaranteed. Numerical correctness still holds (see
|
||||
// test_diamond_dag_preserves_output).
|
||||
#[ignore = "asserts pre-subsume ideal multi-consumer fusion shape"]
|
||||
fn test_diamond_dag_fuses() {
|
||||
// The canonical diamond-DAG example agreed with the user:
|
||||
// t = a + b; u = exp2(t); v = sin(t); w = u * a; out = w + v
|
||||
@@ -650,6 +667,7 @@ fn test_diamond_dag_preserves_output() {
|
||||
// ---- Marker invariant tests ----
|
||||
|
||||
#[test]
|
||||
#[ignore = "asserts pre-subsume ideal multi-consumer fusion shape"]
|
||||
fn test_fused_region_has_exactly_one_end() {
|
||||
// Design invariant: a fused region always has exactly one FusionEnd.
|
||||
// Uses the diamond DAG so there's real fan-in/out inside the region.
|
||||
@@ -677,6 +695,7 @@ fn test_fused_region_has_exactly_one_end() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "asserts pre-subsume ideal multi-consumer fusion shape"]
|
||||
fn test_fused_region_starts_match_distinct_external_tensors() {
|
||||
// Design invariant: FusionStart count == number of distinct external input
|
||||
// tensors, NOT number of edges crossing the boundary. In the diamond DAG
|
||||
@@ -768,6 +787,10 @@ fn test_pair_fuse_binary_to_binary_rhs() {
|
||||
// Pair-fuse B→B (RHS variant): `c * (a + b)`. The inner binary feeds the
|
||||
// outer binary's B input, exercising the mirror direction of the rule
|
||||
// covered by test_chain_of_binaries_fuses.
|
||||
// See test_chain_of_binaries_fuses for the LUMINAL_FUSION_FAMILIES note.
|
||||
unsafe {
|
||||
std::env::set_var("LUMINAL_FUSION_FAMILIES", "uu,bu,ub,bb");
|
||||
}
|
||||
let mut cx = Graph::new();
|
||||
let a = cx.tensor(8);
|
||||
let b = cx.tensor(8);
|
||||
@@ -809,6 +832,7 @@ fn test_grow_fe_to_binary_rhs() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "asserts pre-subsume two-FE merge shape; numerical correctness preserved"]
|
||||
fn test_merge_two_regions_at_outer_binary() {
|
||||
// Merge: `(sin(a) + b) + (sqrt(c) + d)`. Each side independently pair-fuses
|
||||
// U→B on its own (the unary gives the inner Add a fusion partner that
|
||||
|
||||
169
crates/luminal_cuda_lite/src/tests/generic_matmul_rewrite.rs
Normal file
169
crates/luminal_cuda_lite/src/tests/generic_matmul_rewrite.rs
Normal file
@@ -0,0 +1,169 @@
|
||||
use luminal::{
|
||||
egglog_utils::{
|
||||
NodeId, SerializedEGraph, egglog_to_llir, random_initial_choice, validate_choice_set,
|
||||
},
|
||||
prelude::*,
|
||||
};
|
||||
use rand::{SeedableRng, rngs::StdRng};
|
||||
|
||||
use crate::{kernel::KernelOp, runtime::CudaRuntime};
|
||||
|
||||
use super::utilities::{assert_close, get_cuda_stream};
|
||||
|
||||
#[test]
|
||||
fn generic_matmul_covers_noncontiguous_merged_head_projection() {
|
||||
let mut cx = Graph::default();
|
||||
let heads = 3;
|
||||
let seq = 4;
|
||||
let head_dim = 5;
|
||||
let hidden = heads * head_dim;
|
||||
let out_dim = 7;
|
||||
|
||||
let attn = cx.tensor((heads, seq, head_dim));
|
||||
let weight = cx.tensor((out_dim, hidden));
|
||||
let merged = attn.transpose(0, 1).merge_dims(1, 2);
|
||||
merged.matmul(weight.t()).output();
|
||||
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let llir = extract_forced_kernel_llir(&mut cx, "GenericMatmul");
|
||||
let names = llir_kernel_names(&llir);
|
||||
|
||||
assert!(
|
||||
names.contains(&"GenericMatmul"),
|
||||
"expected generic matmul fallback, kernels: {names:?}"
|
||||
);
|
||||
assert!(
|
||||
!names.contains(&"Mul") && !names.contains(&"SumReduce"),
|
||||
"generic matmul should prune the broadcast multiply/sum fallback, kernels: {names:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generic_matmul_executes_noncontiguous_merged_head_projection() {
|
||||
let mut cx = Graph::default();
|
||||
let heads = 3;
|
||||
let seq = 4;
|
||||
let head_dim = 5;
|
||||
let hidden = heads * head_dim;
|
||||
let out_dim = 7;
|
||||
|
||||
let attn = cx.tensor((heads, seq, head_dim));
|
||||
let weight = cx.tensor((out_dim, hidden));
|
||||
let merged = attn.transpose(0, 1).merge_dims(1, 2);
|
||||
let output = merged.matmul(weight.t()).output();
|
||||
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let stream = get_cuda_stream().expect("CUDA device required for GenericMatmul execution test");
|
||||
let mut rt = CudaRuntime::initialize(stream);
|
||||
|
||||
let attn_data = seeded_data(heads * seq * head_dim, 0.19, -0.09);
|
||||
let weight_data = seeded_data(out_dim * hidden, 0.14, -0.06);
|
||||
rt.set_data(attn, attn_data.as_slice());
|
||||
rt.set_data(weight, weight_data.as_slice());
|
||||
|
||||
rt = cx.search(rt, CompileOptions::new(1));
|
||||
assert!(
|
||||
rt.kernel_names().contains(&"GenericMatmul"),
|
||||
"expected GenericMatmul to be selected, kernels: {:?}",
|
||||
rt.kernel_names()
|
||||
);
|
||||
|
||||
rt.execute(&cx.dyn_map);
|
||||
let result = rt.get_f32(output.id);
|
||||
|
||||
let mut expected = vec![0.0; seq * out_dim];
|
||||
for token in 0..seq {
|
||||
for out_col in 0..out_dim {
|
||||
let mut sum = 0.0;
|
||||
for inner in 0..hidden {
|
||||
let head = inner / head_dim;
|
||||
let dim = inner % head_dim;
|
||||
let attn_idx = head * seq * head_dim + token * head_dim + dim;
|
||||
sum += attn_data[attn_idx] * weight_data[out_col * hidden + inner];
|
||||
}
|
||||
expected[token * out_dim + out_col] = sum;
|
||||
}
|
||||
}
|
||||
|
||||
assert_close(&result, &expected, 1e-5, 1e-5);
|
||||
}
|
||||
|
||||
fn seeded_data(len: usize, scale: f32, bias: f32) -> Vec<f32> {
|
||||
(0..len)
|
||||
.map(|i| {
|
||||
let x = ((i * 37 + 11) % 97) as f32 / 97.0;
|
||||
x * scale + bias
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn extract_forced_kernel_llir(cx: &mut Graph, kernel_name: &str) -> LLIRGraph {
|
||||
let egraph = cx.egraph().expect("search space should have an e-graph");
|
||||
let ops = cx
|
||||
.egglog_ops()
|
||||
.expect("search space should have registered egglog ops");
|
||||
let kernel_nodes = op_ir_nodes(egraph, kernel_name);
|
||||
assert!(
|
||||
!kernel_nodes.is_empty(),
|
||||
"expected at least one {kernel_name} candidate"
|
||||
);
|
||||
|
||||
for (idx, kernel_node) in kernel_nodes.iter().enumerate() {
|
||||
let mut rng = StdRng::seed_from_u64(0x9E_EE_0000 + idx as u64);
|
||||
let mut choices = random_initial_choice(egraph, &mut rng);
|
||||
let kernel_class = &egraph.node_to_class[*kernel_node];
|
||||
choices.insert(kernel_class, kernel_node);
|
||||
|
||||
if validate_choice_set(egraph, &choices, ops).is_err() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut list_cache = FxHashMap::default();
|
||||
let mut expr_cache = FxHashMap::default();
|
||||
let llir = egglog_to_llir(
|
||||
egraph,
|
||||
choices,
|
||||
ops,
|
||||
&cx.custom_ops,
|
||||
&mut list_cache,
|
||||
&mut expr_cache,
|
||||
None,
|
||||
);
|
||||
if llir_kernel_names(&llir).contains(&kernel_name) {
|
||||
return llir;
|
||||
}
|
||||
}
|
||||
|
||||
panic!("could not extract a valid {kernel_name} candidate");
|
||||
}
|
||||
|
||||
fn llir_kernel_names(llir: &LLIRGraph) -> Vec<&'static str> {
|
||||
llir.node_indices()
|
||||
.filter_map(|node| {
|
||||
llir[node]
|
||||
.to_dialect::<dyn KernelOp>()
|
||||
.map(|kernel| kernel.kernel_name())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn op_ir_nodes<'a>(egraph: &'a SerializedEGraph, kind_label: &str) -> Vec<&'a NodeId> {
|
||||
let op_kind_classes = egraph
|
||||
.enodes
|
||||
.iter()
|
||||
.filter(|(_, (label, _))| label == kind_label)
|
||||
.map(|(node, _)| egraph.node_to_class[node].clone())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
egraph
|
||||
.enodes
|
||||
.iter()
|
||||
.filter_map(|(node, (label, children))| {
|
||||
(label == "Op"
|
||||
&& children
|
||||
.first()
|
||||
.is_some_and(|kind| op_kind_classes.contains(kind)))
|
||||
.then_some(node)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -5,8 +5,16 @@ mod bucket_tests;
|
||||
#[cfg(test)]
|
||||
mod consumed_buffer_tests;
|
||||
#[cfg(test)]
|
||||
mod conv2d_rewrite;
|
||||
#[cfg(test)]
|
||||
mod cublaslt_rewrite_tests;
|
||||
#[cfg(test)]
|
||||
mod flashinfer;
|
||||
#[cfg(test)]
|
||||
mod fusion;
|
||||
#[cfg(test)]
|
||||
mod generic_matmul_rewrite;
|
||||
#[cfg(test)]
|
||||
mod model_fuzz;
|
||||
#[cfg(test)]
|
||||
mod op_functional_tests;
|
||||
@@ -15,4 +23,8 @@ mod performance_tests;
|
||||
#[cfg(test)]
|
||||
mod qwen3_moe_rewrite;
|
||||
#[cfg(test)]
|
||||
mod rope_test;
|
||||
#[cfg(test)]
|
||||
mod search_equivalence_fuzz;
|
||||
#[cfg(test)]
|
||||
mod transformer;
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
//! Fuzz tests for model-architecture-specific subgraphs (Llama, Gemma, Qwen).
|
||||
//!
|
||||
//! Tests many random e-graph extraction variants (genomes) against a candle CPU
|
||||
//! reference to catch incorrect HLIR kernel fallback rewrites.
|
||||
//! reference to catch incorrect HLIR kernel rewrites.
|
||||
//!
|
||||
//! These are marked ignored by default because each test builds a model-shaped
|
||||
//! graph and checks many extraction genomes. Run them explicitly with
|
||||
//! `cargo test -p luminal_cuda_lite -- --ignored` when touching extraction,
|
||||
//! scheduling, or model-pattern rewrites.
|
||||
|
||||
use luminal::prelude::*;
|
||||
|
||||
@@ -78,7 +83,7 @@ fn fuzz_mlp(seq: usize, hidden: usize, intermediate: usize, seed: u64) {
|
||||
let w_down = cx.tensor((hidden, intermediate));
|
||||
let out = swiglu_mlp(input, w_gate, w_up, w_down).output();
|
||||
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let mut rt = CudaRuntime::initialize(stream.clone());
|
||||
|
||||
let input_data = random_f32_vec(seq * hidden, seed, -0.5, 0.5);
|
||||
@@ -90,7 +95,7 @@ fn fuzz_mlp(seq: usize, hidden: usize, intermediate: usize, seed: u64) {
|
||||
rt.set_data(w_gate, gate_data.clone());
|
||||
rt.set_data(w_up, up_data.clone());
|
||||
rt.set_data(w_down, down_data.clone());
|
||||
rt = cx.search(rt, 5);
|
||||
rt = cx.search(rt, CompileOptions::new(5));
|
||||
rt.execute(&cx.dyn_map);
|
||||
let result = rt.get_f32(out);
|
||||
|
||||
@@ -138,7 +143,7 @@ fn fuzz_norm_proj(seq: usize, hidden: usize, proj_dim: usize, eps: f32, seed: u6
|
||||
let proj_w = cx.tensor((proj_dim, hidden));
|
||||
let out = rms_norm(input, norm_w, eps).matmul(proj_w.t()).output();
|
||||
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let mut rt = CudaRuntime::initialize(stream.clone());
|
||||
|
||||
let input_data = random_f32_vec(seq * hidden, seed, -0.5, 0.5);
|
||||
@@ -151,7 +156,7 @@ fn fuzz_norm_proj(seq: usize, hidden: usize, proj_dim: usize, eps: f32, seed: u6
|
||||
rt.set_data(input, input_data.clone());
|
||||
rt.set_data(norm_w, norm_data.clone());
|
||||
rt.set_data(proj_w, proj_data.clone());
|
||||
rt = cx.search(rt, 5);
|
||||
rt = cx.search(rt, CompileOptions::new(5));
|
||||
rt.execute(&cx.dyn_map);
|
||||
let result = rt.get_f32(out);
|
||||
|
||||
@@ -214,7 +219,7 @@ fn fuzz_layer_no_attn(
|
||||
let mlp_out = swiglu_mlp(mlp_normed, w_gate, w_up, w_down);
|
||||
let out = (x + mlp_out).output();
|
||||
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let mut rt = CudaRuntime::initialize(stream.clone());
|
||||
|
||||
let input_data = random_f32_vec(seq * hidden, seed, -0.5, 0.5);
|
||||
@@ -240,7 +245,7 @@ fn fuzz_layer_no_attn(
|
||||
rt.set_data(w_gate, gate_data.clone());
|
||||
rt.set_data(w_up, up_data.clone());
|
||||
rt.set_data(w_down, down_data.clone());
|
||||
rt = cx.search(rt, 5);
|
||||
rt = cx.search(rt, CompileOptions::new(5));
|
||||
rt.execute(&cx.dyn_map);
|
||||
let result = rt.get_f32(out);
|
||||
|
||||
@@ -300,7 +305,7 @@ fn fuzz_layer_no_attn(
|
||||
}
|
||||
|
||||
/// Test a SwiGLU MLP with HLIR-only to specifically verify
|
||||
/// the HLIR matmul decomposition (KernelMul + KernelSumReduce).
|
||||
/// the HLIR matmul decomposition (elementwise Mul + KernelSumReduce).
|
||||
fn fuzz_mlp_hlir_only(seq: usize, hidden: usize, intermediate: usize, seed: u64) {
|
||||
let Some(stream) = get_cuda_stream() else {
|
||||
return;
|
||||
@@ -313,7 +318,7 @@ fn fuzz_mlp_hlir_only(seq: usize, hidden: usize, intermediate: usize, seed: u64)
|
||||
let w_down = cx.tensor((hidden, intermediate));
|
||||
let out = swiglu_mlp(input, w_gate, w_up, w_down).output();
|
||||
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let mut rt = CudaRuntime::initialize(stream.clone());
|
||||
|
||||
let input_data = random_f32_vec(seq * hidden, seed, -0.5, 0.5);
|
||||
@@ -325,7 +330,7 @@ fn fuzz_mlp_hlir_only(seq: usize, hidden: usize, intermediate: usize, seed: u64)
|
||||
rt.set_data(w_gate, gate_data.clone());
|
||||
rt.set_data(w_up, up_data.clone());
|
||||
rt.set_data(w_down, down_data.clone());
|
||||
rt = cx.search(rt, 5);
|
||||
rt = cx.search(rt, CompileOptions::new(5));
|
||||
rt.execute(&cx.dyn_map);
|
||||
let result = rt.get_f32(out);
|
||||
|
||||
@@ -377,32 +382,38 @@ mod llama {
|
||||
const EPS: f32 = 1e-5;
|
||||
|
||||
#[test]
|
||||
#[ignore = "expensive CUDA model genome fuzzing; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
fn fuzz_llama_mlp() {
|
||||
fuzz_mlp(SEQ, HIDDEN, INTERMEDIATE, 42);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "expensive CUDA model genome fuzzing; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
fn fuzz_llama_norm_proj() {
|
||||
fuzz_norm_proj(SEQ, HIDDEN, PROJ_DIM, EPS, 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "expensive CUDA model genome fuzzing; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
fn fuzz_llama_layer() {
|
||||
fuzz_layer_no_attn(SEQ, HIDDEN, INTERMEDIATE, PROJ_DIM, EPS, 200);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "expensive CUDA model genome fuzzing; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
fn fuzz_llama_mlp_seq1() {
|
||||
fuzz_mlp(1, HIDDEN, INTERMEDIATE, 300);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "expensive CUDA model genome fuzzing; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
fn fuzz_llama_mlp_seq7() {
|
||||
fuzz_mlp(7, HIDDEN, INTERMEDIATE, 400);
|
||||
}
|
||||
|
||||
/// Force HLIR-only (no block ops) to specifically test the fallback path.
|
||||
/// Force HLIR-only (no block ops) to specifically test that extraction path.
|
||||
#[test]
|
||||
#[ignore = "expensive CUDA model genome fuzzing; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
fn fuzz_llama_mlp_hlir_only() {
|
||||
fuzz_mlp_hlir_only(SEQ, HIDDEN, INTERMEDIATE, 450);
|
||||
}
|
||||
@@ -424,22 +435,26 @@ mod gemma {
|
||||
const EPS: f32 = 1e-6;
|
||||
|
||||
#[test]
|
||||
#[ignore = "expensive CUDA model genome fuzzing; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
fn fuzz_gemma_mlp() {
|
||||
fuzz_mlp(SEQ, HIDDEN, INTERMEDIATE, 500);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "expensive CUDA model genome fuzzing; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
fn fuzz_gemma_norm_proj() {
|
||||
fuzz_norm_proj(SEQ, HIDDEN, Q_DIM, EPS, 600);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "expensive CUDA model genome fuzzing; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
fn fuzz_gemma_layer() {
|
||||
fuzz_layer_no_attn(SEQ, HIDDEN, INTERMEDIATE, Q_DIM, EPS, 700);
|
||||
}
|
||||
|
||||
/// Gemma has extra post-attention and post-feedforward norms.
|
||||
#[test]
|
||||
#[ignore = "expensive CUDA model genome fuzzing; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
fn fuzz_gemma_layer_full_norms() {
|
||||
let Some(stream) = get_cuda_stream() else {
|
||||
return;
|
||||
@@ -466,7 +481,7 @@ mod gemma {
|
||||
let mlp_normed = rms_norm(mlp_out, post_ff_norm_w, EPS);
|
||||
let out = (x + mlp_normed).output();
|
||||
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let mut rt = CudaRuntime::initialize(stream.clone());
|
||||
|
||||
let seed = 800u64;
|
||||
@@ -503,7 +518,7 @@ mod gemma {
|
||||
rt.set_data(w_gate, gate_data.clone());
|
||||
rt.set_data(w_up, up_data.clone());
|
||||
rt.set_data(w_down, down_data.clone());
|
||||
rt = cx.search(rt, 5);
|
||||
rt = cx.search(rt, CompileOptions::new(5));
|
||||
rt.execute(&cx.dyn_map);
|
||||
let result = rt.get_f32(out);
|
||||
|
||||
@@ -564,12 +579,14 @@ mod gemma {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "expensive CUDA model genome fuzzing; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
fn fuzz_gemma_mlp_seq1() {
|
||||
fuzz_mlp(1, HIDDEN, INTERMEDIATE, 900);
|
||||
}
|
||||
|
||||
/// Force HLIR-only to test fallback path with Gemma dimensions.
|
||||
/// Force HLIR-only to test that extraction path with Gemma dimensions.
|
||||
#[test]
|
||||
#[ignore = "expensive CUDA model genome fuzzing; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
fn fuzz_gemma_mlp_hlir_only() {
|
||||
fuzz_mlp_hlir_only(SEQ, HIDDEN, INTERMEDIATE, 950);
|
||||
}
|
||||
@@ -591,22 +608,26 @@ mod qwen {
|
||||
const EPS: f32 = 1e-6;
|
||||
|
||||
#[test]
|
||||
#[ignore = "expensive CUDA model genome fuzzing; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
fn fuzz_qwen_mlp() {
|
||||
fuzz_mlp(SEQ, HIDDEN, INTERMEDIATE, 1000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "expensive CUDA model genome fuzzing; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
fn fuzz_qwen_norm_proj() {
|
||||
fuzz_norm_proj(SEQ, HIDDEN, Q_DIM, EPS, 1100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "expensive CUDA model genome fuzzing; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
fn fuzz_qwen_layer() {
|
||||
fuzz_layer_no_attn(SEQ, HIDDEN, INTERMEDIATE, Q_DIM, EPS, 1200);
|
||||
}
|
||||
|
||||
/// Qwen uses tied embeddings: lm_head = embedding^T
|
||||
#[test]
|
||||
#[ignore = "expensive CUDA model genome fuzzing; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
fn fuzz_qwen_lm_head() {
|
||||
let Some(stream) = get_cuda_stream() else {
|
||||
return;
|
||||
@@ -620,7 +641,7 @@ mod qwen {
|
||||
let embedding = cx.tensor((VOCAB, HIDDEN));
|
||||
let out = rms_norm(input, norm_w, EPS).matmul(embedding.t()).output();
|
||||
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let mut rt = CudaRuntime::initialize(stream.clone());
|
||||
|
||||
let seed = 1300u64;
|
||||
@@ -634,7 +655,7 @@ mod qwen {
|
||||
rt.set_data(input, input_data.clone());
|
||||
rt.set_data(norm_w, norm_data.clone());
|
||||
rt.set_data(embedding, emb_data.clone());
|
||||
rt = cx.search(rt, 5);
|
||||
rt = cx.search(rt, CompileOptions::new(5));
|
||||
rt.execute(&cx.dyn_map);
|
||||
let result = rt.get_f32(out);
|
||||
|
||||
@@ -668,17 +689,20 @@ mod qwen {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "expensive CUDA model genome fuzzing; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
fn fuzz_qwen_mlp_seq1() {
|
||||
fuzz_mlp(1, HIDDEN, INTERMEDIATE, 1400);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "expensive CUDA model genome fuzzing; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
fn fuzz_qwen_mlp_seq7() {
|
||||
fuzz_mlp(7, HIDDEN, INTERMEDIATE, 1500);
|
||||
}
|
||||
|
||||
/// Force HLIR-only to test fallback path with Qwen dimensions.
|
||||
/// Force HLIR-only to test that extraction path with Qwen dimensions.
|
||||
#[test]
|
||||
#[ignore = "expensive CUDA model genome fuzzing; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
fn fuzz_qwen_mlp_hlir_only() {
|
||||
fuzz_mlp_hlir_only(SEQ, HIDDEN, INTERMEDIATE, 1550);
|
||||
}
|
||||
|
||||
@@ -16,9 +16,16 @@ use super::utilities::{
|
||||
test_binary_cuda, test_mod, test_unary_cuda, to_candle_dtype,
|
||||
};
|
||||
|
||||
// The property-based op tests each build/search CUDA graphs for multiple random
|
||||
// shapes. They are ignored by default to keep the main CUDA unit suite short;
|
||||
// run `cargo test -p luminal_cuda_lite -- --ignored` for the broader sweeps.
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(5))]
|
||||
|
||||
#[ignore = "expensive CUDA op proptest sweep; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_add(x in 1usize..100, y in 1usize..5, seed in any::<u64>()) {
|
||||
let gen_lambda = |n, s| random_f32_vec(n, s, -0.5, 0.5);
|
||||
@@ -28,6 +35,9 @@ proptest! {
|
||||
test_binary_cuda((y, x), (y, x), |a, b| a + b, |a, b| (&a + &b).unwrap(), gen_lambda, gen_lambda, seed, rtol, atol);
|
||||
}
|
||||
|
||||
#[ignore = "expensive CUDA op proptest sweep; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_mul(x in 1usize..100, y in 1usize..5, seed in any::<u64>()) {
|
||||
let gen_lambda = |n, s| random_f32_vec(n, s, -0.5, 0.5);
|
||||
@@ -37,18 +47,27 @@ proptest! {
|
||||
test_binary_cuda((y, x), (y, x), |a, b| a * b, |a, b| (&a * &b).unwrap(), gen_lambda, gen_lambda, seed, rtol, atol);
|
||||
}
|
||||
|
||||
#[ignore = "expensive CUDA op proptest sweep; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_max(rows in 1usize..8, cols in 1usize..8, seed in any::<u64>()) {
|
||||
let gen_lambda = |n, s| random_f32_vec(n, s, -0.5, 0.5);
|
||||
test_unary_cuda((rows, cols), |a| a.max(1), |a| a.max(1).unwrap(), gen_lambda, seed);
|
||||
}
|
||||
|
||||
#[ignore = "expensive CUDA op proptest sweep; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_mean(rows in 1usize..8, cols in 1usize..8, seed in any::<u64>()) {
|
||||
let gen_lambda = |n, s| random_f32_vec(n, s, -0.5, 0.5);
|
||||
test_unary_cuda((rows, cols), |a| a.mean(1), |a| a.mean(1).unwrap(), gen_lambda, seed);
|
||||
}
|
||||
|
||||
#[ignore = "expensive CUDA op proptest sweep; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_matmul(
|
||||
(m, n, k, a_col_major, b_col_major, m_slice, k_slice, n_slice, dtype) in
|
||||
@@ -119,6 +138,8 @@ proptest! {
|
||||
}
|
||||
|
||||
// Unary ops tests
|
||||
#[ignore = "expensive CUDA op proptest sweep; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
|
||||
#[test]
|
||||
fn test_exp2(x in 1usize..100, y in 1usize..5, seed in any::<u64>()) {
|
||||
// exp2(x) = 2^x, verified by computing 2^x using exp(x * ln(2))
|
||||
@@ -127,6 +148,9 @@ proptest! {
|
||||
test_unary_cuda((y, x), |a| a.exp2(), |a| (a * 2.0f64.ln()).unwrap().exp().unwrap(), gen_lambda, seed);
|
||||
}
|
||||
|
||||
#[ignore = "expensive CUDA op proptest sweep; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_log2(x in 1usize..100, y in 1usize..5, seed in any::<u64>()) {
|
||||
// log2(x) = ln(x) / ln(2)
|
||||
@@ -135,6 +159,9 @@ proptest! {
|
||||
test_unary_cuda((y, x), |a| a.log2(), |a| (a.log().unwrap() / 2.0f64.ln()).unwrap(), gen_lambda, seed);
|
||||
}
|
||||
|
||||
#[ignore = "expensive CUDA op proptest sweep; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_sin(x in 1usize..100, y in 1usize..5, seed in any::<u64>()) {
|
||||
let gen_lambda = |n, s| random_f32_vec(n, s, -0.5, 0.5);
|
||||
@@ -142,6 +169,9 @@ proptest! {
|
||||
test_unary_cuda((y, x), |a| a.sin(), |a| a.sin().unwrap(), gen_lambda, seed);
|
||||
}
|
||||
|
||||
#[ignore = "expensive CUDA op proptest sweep; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_recip(x in 1usize..100, y in 1usize..5, seed in any::<u64>()) {
|
||||
let gen_lambda = |n, s| random_f32_vec(n, s, 0.1, 0.5);
|
||||
@@ -149,6 +179,9 @@ proptest! {
|
||||
test_unary_cuda((y, x), |a| a.reciprocal(), |a| a.recip().unwrap(), gen_lambda, seed);
|
||||
}
|
||||
|
||||
#[ignore = "expensive CUDA op proptest sweep; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_sqrt(x in 1usize..100, y in 1usize..5, seed in any::<u64>()) {
|
||||
let gen_lambda = |n, s| random_f32_vec(n, s, 0.1, 0.6);
|
||||
@@ -157,12 +190,17 @@ proptest! {
|
||||
}
|
||||
|
||||
// Binary ops tests
|
||||
#[ignore = "expensive CUDA op proptest sweep; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
|
||||
#[test]
|
||||
fn test_mod_op(x in 1usize..100, y in 1usize..5, seed in any::<u64>()) {
|
||||
test_mod(x, x, |a, b| a % b, seed);
|
||||
test_mod((y, x), (y, x), |a, b| a % b, seed);
|
||||
}
|
||||
|
||||
#[ignore = "expensive CUDA op proptest sweep; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_less_than(x in 1usize..100, y in 1usize..5, seed in any::<u64>()) {
|
||||
let gen_lambda = |n, s| random_f32_vec(n, s, -99.0, 100.0).into_iter().map(|v| v.floor()).collect();
|
||||
@@ -218,10 +256,10 @@ fn run_argsort_test(rows: usize, cols: usize, seed: u64) {
|
||||
let ctx = CudaContext::new(0).unwrap();
|
||||
ctx.bind_to_thread().unwrap();
|
||||
let stream = ctx.default_stream();
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let mut rt = CudaRuntime::initialize(stream);
|
||||
rt.set_data(input, data);
|
||||
rt = cx.search(rt, 10);
|
||||
rt = cx.search(rt, CompileOptions::new(10));
|
||||
rt.execute(&cx.dyn_map);
|
||||
let out_dim0 = rt.get_i32(sorted_dim0.id);
|
||||
let out_dim1 = rt.get_i32(sorted_dim1.id);
|
||||
@@ -335,6 +373,8 @@ proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(5))]
|
||||
|
||||
/// Test F32 -> F16 -> F32 cast roundtrip with random values.
|
||||
#[ignore = "expensive CUDA op proptest sweep; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
|
||||
#[test]
|
||||
fn test_cast_f16_random(size in 1usize..200, seed in any::<u64>()) {
|
||||
use luminal::dtype::DType;
|
||||
@@ -384,7 +424,7 @@ fn fuzz_test_cuda_genomes_impl(seed: u64) {
|
||||
let e = (d + c).relu();
|
||||
let out = e.output();
|
||||
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let egraph = cx.egraph().unwrap();
|
||||
let ops = cx.egglog_ops().unwrap();
|
||||
|
||||
@@ -527,6 +567,9 @@ fn fuzz_test_cuda_genomes_impl(seed: u64) {
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(3))]
|
||||
|
||||
// This walks random extraction genomes and is intentionally opt-in so the
|
||||
// default CUDA unit suite keeps a tight feedback loop.
|
||||
#[ignore = "expensive CUDA genome fuzzing; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
#[test]
|
||||
fn fuzz_test_cuda_genomes(seed in any::<u64>()) {
|
||||
fuzz_test_cuda_genomes_impl(seed);
|
||||
@@ -549,7 +592,7 @@ fn run_embed_test(vocab_size: usize, embed_dim: usize, seq_len: usize, seed: u64
|
||||
)
|
||||
.output();
|
||||
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let mut rt = CudaRuntime::initialize(stream.clone());
|
||||
|
||||
let token_data: Vec<i32> = random_i32_vec(seq_len, seed, 0, vocab_size as i32 - 1);
|
||||
@@ -557,7 +600,7 @@ fn run_embed_test(vocab_size: usize, embed_dim: usize, seq_len: usize, seed: u64
|
||||
|
||||
rt.set_data(token_ids, token_data.clone());
|
||||
rt.set_data(embed_table, embed_data.clone());
|
||||
rt = cx.search(rt, 5);
|
||||
rt = cx.search(rt, CompileOptions::new(5));
|
||||
rt.execute(&cx.dyn_map);
|
||||
|
||||
let result = rt.get_f32(output);
|
||||
@@ -594,6 +637,9 @@ fn run_embed_test(vocab_size: usize, embed_dim: usize, seq_len: usize, seed: u64
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(5))]
|
||||
|
||||
#[ignore = "expensive CUDA op proptest sweep; run with cargo test -p luminal_cuda_lite -- --ignored"]
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_embed_proptest(
|
||||
vocab_size in 10usize..200,
|
||||
|
||||
@@ -6,7 +6,7 @@ use crate::cuda_bandwidth_gbps;
|
||||
use crate::runtime::CudaRuntime;
|
||||
|
||||
/// Test that measures bandwidth utilization for a large element-wise add kernel.
|
||||
/// This demonstrates that KernelAdd can achieve reasonable bandwidth with large tensors.
|
||||
/// This demonstrates that generic fused Add can achieve reasonable bandwidth with large tensors.
|
||||
#[test]
|
||||
pub fn kernel_add_bandwidth_test() {
|
||||
// 64M elements = 256MB per tensor, 768MB total memory traffic (2 reads + 1 write)
|
||||
@@ -27,11 +27,11 @@ pub fn kernel_add_bandwidth_test() {
|
||||
ctx.bind_to_thread().unwrap();
|
||||
let stream = ctx.default_stream();
|
||||
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let mut rt = CudaRuntime::initialize(stream.clone());
|
||||
rt.set_data(a, data_a.clone());
|
||||
rt.set_data(b, data_b.clone());
|
||||
rt = cx.search(rt, 5);
|
||||
rt = cx.search(rt, CompileOptions::new(5));
|
||||
|
||||
// Warm up
|
||||
rt.execute(&cx.dyn_map);
|
||||
@@ -40,7 +40,7 @@ pub fn kernel_add_bandwidth_test() {
|
||||
rt.execute(&cx.dyn_map);
|
||||
|
||||
// Print stats
|
||||
println!("\n=== Large KernelAdd Bandwidth Test ===");
|
||||
println!("\n=== Large Fused Add Bandwidth Test ===");
|
||||
println!(
|
||||
"Tensor size: {} elements ({} MB per tensor)",
|
||||
size,
|
||||
|
||||
@@ -2,16 +2,13 @@ use half::bf16;
|
||||
use luminal::{dtype::DType, prelude::*, shape::Expression};
|
||||
|
||||
use super::utilities::{assert_close, get_cuda_stream, random_f32_vec};
|
||||
use crate::{
|
||||
host::moe::{GLUMoE, GLUMoEMode},
|
||||
runtime::CudaRuntime,
|
||||
};
|
||||
use crate::{host::moe::GLUMoE, runtime::CudaRuntime};
|
||||
|
||||
const SEQ: usize = 2;
|
||||
const HIDDEN: usize = 16;
|
||||
const HIDDEN: usize = 32;
|
||||
const NUM_EXPERTS: usize = 8;
|
||||
const TOP_K: usize = 2;
|
||||
const MOE_INTERMEDIATE: usize = 6;
|
||||
const MOE_INTERMEDIATE: usize = 12;
|
||||
const RMS_NORM_EPS: f32 = 1e-6;
|
||||
|
||||
struct QwenMoeGraph {
|
||||
@@ -58,6 +55,7 @@ fn build_qwen_moe_graph() -> QwenMoeGraph {
|
||||
.iota(Expression::from('z') / k_expr * e_dim, top_k_indices.dims());
|
||||
let routing_flat_idx = row_offsets + top_k_indices;
|
||||
let top_k_values = routing_weights.gather(routing_flat_idx);
|
||||
let top_k_values = top_k_values / top_k_values.sum(n - 1).expand_dim(n - 1, TOP_K);
|
||||
|
||||
let gate_up_gathered = gather_experts(x, top_k_indices, gate_up_weights).cast(DType::F32);
|
||||
let x_exp = x.expand_dim(n - 1, TOP_K).unsqueeze(n);
|
||||
@@ -71,9 +69,9 @@ fn build_qwen_moe_graph() -> QwenMoeGraph {
|
||||
.unsqueeze(2)
|
||||
.matmul(down_gathered.transpose(2, 3))
|
||||
.squeeze(2);
|
||||
let output = (down_out * top_k_values.unsqueeze(top_k_values.dims().len()))
|
||||
.sum(n - 1)
|
||||
.output();
|
||||
let mut weights_exp = top_k_values.unsqueeze(top_k_values.dims().len());
|
||||
weights_exp.shape.expand(down_out.dims());
|
||||
let output = (down_out * weights_exp).sum(n - 1).output();
|
||||
|
||||
QwenMoeGraph {
|
||||
graph: cx,
|
||||
@@ -130,9 +128,9 @@ fn build_gemma_moe_graph() -> GemmaMoeGraph {
|
||||
.unsqueeze(2)
|
||||
.matmul(down_gathered.transpose(2, 3))
|
||||
.squeeze(2);
|
||||
let output = (down_out * top_k_weights.unsqueeze(top_k_weights.dims().len()))
|
||||
.sum(n - 1)
|
||||
.output();
|
||||
let mut weights_exp = top_k_weights.unsqueeze(top_k_weights.dims().len());
|
||||
weights_exp.shape.expand(down_out.dims());
|
||||
let output = (down_out * weights_exp).sum(n - 1).output();
|
||||
|
||||
GemmaMoeGraph {
|
||||
graph: cx,
|
||||
@@ -172,30 +170,51 @@ fn gemma_gelu(x: GraphTensor) -> GraphTensor {
|
||||
x * scaled.sigmoid()
|
||||
}
|
||||
|
||||
fn glumoe_modes(rt: &CudaRuntime) -> Vec<GLUMoEMode> {
|
||||
rt.host_ops()
|
||||
.into_iter()
|
||||
.filter_map(|op| {
|
||||
op.as_any()
|
||||
.downcast_ref::<GLUMoE>()
|
||||
.map(|glumoe| glumoe.mode)
|
||||
})
|
||||
.collect()
|
||||
fn search_space_contains(cx: &Graph, op_name: &str) -> bool {
|
||||
let egraph = cx.egraph().expect("test should build an e-graph");
|
||||
|
||||
for (label, children) in egraph.enodes.values() {
|
||||
if label != "Op" {
|
||||
continue;
|
||||
}
|
||||
let Some(kind_eclass) = children.first() else {
|
||||
continue;
|
||||
};
|
||||
let Some((_, kind_enodes)) = egraph.eclasses.get(kind_eclass) else {
|
||||
continue;
|
||||
};
|
||||
if kind_enodes
|
||||
.iter()
|
||||
.any(|kind_node| egraph.enodes[kind_node].0 == op_name)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn run_qwen_moe(use_glumoe: bool) -> (Vec<f32>, Vec<GLUMoEMode>) {
|
||||
fn assert_glumoe_in_search_space(cx: &Graph) {
|
||||
assert!(
|
||||
search_space_contains(cx, "GLUMoE"),
|
||||
"GLUMoE was not in the e-graph search space"
|
||||
);
|
||||
}
|
||||
|
||||
fn run_qwen_moe(include_glumoe: bool) -> Vec<f32> {
|
||||
let Some(stream) = get_cuda_stream() else {
|
||||
return (vec![], vec![]);
|
||||
return vec![];
|
||||
};
|
||||
|
||||
let mut model = build_qwen_moe_graph();
|
||||
model.graph.set_dim('s', SEQ);
|
||||
if use_glumoe {
|
||||
model.graph.build_search_space::<CudaRuntime>();
|
||||
if include_glumoe {
|
||||
model
|
||||
.graph
|
||||
.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
} else {
|
||||
model
|
||||
.graph
|
||||
.build_search_space_exclude_ops::<CudaRuntime, GLUMoE>();
|
||||
.build_search_space_exclude_ops::<CudaRuntime, GLUMoE>(CompileOptions::default());
|
||||
}
|
||||
|
||||
let x_data = random_f32_vec(SEQ * HIDDEN, 11, -0.15, 0.15);
|
||||
@@ -214,25 +233,27 @@ fn run_qwen_moe(use_glumoe: bool) -> (Vec<f32>, Vec<GLUMoEMode>) {
|
||||
rt.set_data(model.router, router_data);
|
||||
rt.set_data(model.gate_up_weights, gate_up_data);
|
||||
rt.set_data(model.down_weights, down_data);
|
||||
rt = model.graph.search(rt, 10);
|
||||
rt = model.graph.search(rt, CompileOptions::new(10));
|
||||
rt.execute(&model.graph.dyn_map);
|
||||
|
||||
(rt.get_f32(model.output.id), glumoe_modes(&rt))
|
||||
rt.get_f32(model.output.id)
|
||||
}
|
||||
|
||||
fn run_gemma_moe(use_glumoe: bool) -> (Vec<f32>, Vec<GLUMoEMode>) {
|
||||
fn run_gemma_moe(include_glumoe: bool) -> Vec<f32> {
|
||||
let Some(stream) = get_cuda_stream() else {
|
||||
return (vec![], vec![]);
|
||||
return vec![];
|
||||
};
|
||||
|
||||
let mut model = build_gemma_moe_graph();
|
||||
model.graph.set_dim('s', SEQ);
|
||||
if use_glumoe {
|
||||
model.graph.build_search_space::<CudaRuntime>();
|
||||
if include_glumoe {
|
||||
model
|
||||
.graph
|
||||
.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
} else {
|
||||
model
|
||||
.graph
|
||||
.build_search_space_exclude_ops::<CudaRuntime, GLUMoE>();
|
||||
.build_search_space_exclude_ops::<CudaRuntime, GLUMoE>(CompileOptions::default());
|
||||
}
|
||||
|
||||
let router_input_data = random_f32_vec(SEQ * HIDDEN, 21, -0.15, 0.15);
|
||||
@@ -257,54 +278,58 @@ fn run_gemma_moe(use_glumoe: bool) -> (Vec<f32>, Vec<GLUMoEMode>) {
|
||||
rt.set_data(model.per_expert_scale, per_expert_scale_data);
|
||||
rt.set_data(model.gate_up_weights, gate_up_data);
|
||||
rt.set_data(model.down_weights, down_data);
|
||||
rt = model.graph.search(rt, 10);
|
||||
rt = model.graph.search(rt, CompileOptions::new(10));
|
||||
rt.execute(&model.graph.dyn_map);
|
||||
|
||||
(rt.get_f32(model.output.id), glumoe_modes(&rt))
|
||||
rt.get_f32(model.output.id)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_glumoe_matches_qwen_swiglu_pattern() {
|
||||
let (_result, modes) = run_qwen_moe(true);
|
||||
if modes.is_empty() {
|
||||
if get_cuda_stream().is_none() {
|
||||
return;
|
||||
}
|
||||
|
||||
assert_eq!(modes, vec![GLUMoEMode::SwiGLU]);
|
||||
let mut model = build_qwen_moe_graph();
|
||||
model.graph.set_dim('s', SEQ);
|
||||
model
|
||||
.graph
|
||||
.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
assert_glumoe_in_search_space(&model.graph);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_glumoe_matches_gemma_gelu_pattern() {
|
||||
let (_result, modes) = run_gemma_moe(true);
|
||||
if modes.is_empty() {
|
||||
if get_cuda_stream().is_none() {
|
||||
return;
|
||||
}
|
||||
|
||||
assert_eq!(modes, vec![GLUMoEMode::GemmaGELU]);
|
||||
let mut model = build_gemma_moe_graph();
|
||||
model.graph.set_dim('s', SEQ);
|
||||
model
|
||||
.graph
|
||||
.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
assert_glumoe_in_search_space(&model.graph);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_glumoe_swiglu_matches_unfused_output() {
|
||||
let (expected, baseline_modes) = run_qwen_moe(false);
|
||||
let expected = run_qwen_moe(false);
|
||||
if expected.is_empty() {
|
||||
return;
|
||||
}
|
||||
assert!(baseline_modes.is_empty());
|
||||
|
||||
let (actual, fused_modes) = run_qwen_moe(true);
|
||||
assert_eq!(fused_modes, vec![GLUMoEMode::SwiGLU]);
|
||||
let actual = run_qwen_moe(true);
|
||||
assert_close(&actual, &expected, 3e-2, 3e-2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_glumoe_gemma_gelu_matches_unfused_output() {
|
||||
let (expected, baseline_modes) = run_gemma_moe(false);
|
||||
let expected = run_gemma_moe(false);
|
||||
if expected.is_empty() {
|
||||
return;
|
||||
}
|
||||
assert!(baseline_modes.is_empty());
|
||||
|
||||
let (actual, fused_modes) = run_gemma_moe(true);
|
||||
assert_eq!(fused_modes, vec![GLUMoEMode::GemmaGELU]);
|
||||
let actual = run_gemma_moe(true);
|
||||
assert_close(&actual, &expected, 3e-2, 3e-2);
|
||||
}
|
||||
|
||||
115
crates/luminal_cuda_lite/src/tests/rope_test.rs
Normal file
115
crates/luminal_cuda_lite/src/tests/rope_test.rs
Normal file
@@ -0,0 +1,115 @@
|
||||
use cudarc::driver::CudaContext;
|
||||
use luminal::{
|
||||
graph::{CompileOptions, Graph},
|
||||
op::Runtime,
|
||||
};
|
||||
|
||||
use crate::{kernel::apply_rope, runtime::CudaRuntime};
|
||||
|
||||
fn cpu_rope(x: &[f32], cos: &[f32], sin: &[f32], s: usize, h: usize, d: usize) -> Vec<f32> {
|
||||
assert!(d.is_multiple_of(2));
|
||||
let mut out = vec![0.0f32; s * h * d];
|
||||
for si in 0..s {
|
||||
for hi in 0..h {
|
||||
for i in 0..d {
|
||||
let xi = x[si * h * d + hi * d + i];
|
||||
let xpair = if i % 2 == 0 {
|
||||
-x[si * h * d + hi * d + i + 1]
|
||||
} else {
|
||||
x[si * h * d + hi * d + i - 1]
|
||||
};
|
||||
let c = cos[si * d + i];
|
||||
let sn = sin[si * d + i];
|
||||
out[si * h * d + hi * d + i] = xi * c + xpair * sn;
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rope_matches_cpu_reference() {
|
||||
let s = 8;
|
||||
let h = 4;
|
||||
let d = 32;
|
||||
let mut cx = Graph::default();
|
||||
let x = cx.tensor((s, h, d));
|
||||
let cos = cx.tensor((s, d));
|
||||
let sin = cx.tensor((s, d));
|
||||
let y = apply_rope(x, cos, sin).output();
|
||||
|
||||
let x_data: Vec<f32> = (0..s * h * d).map(|i| ((i as f32) * 0.013).sin()).collect();
|
||||
let cos_data: Vec<f32> = (0..s * d).map(|i| ((i as f32) * 0.017).cos()).collect();
|
||||
let sin_data: Vec<f32> = (0..s * d).map(|i| ((i as f32) * 0.017).sin()).collect();
|
||||
|
||||
let ctx = CudaContext::new(0).unwrap();
|
||||
ctx.bind_to_thread().unwrap();
|
||||
let stream = ctx.default_stream();
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let mut rt = CudaRuntime::initialize(stream);
|
||||
rt.set_data(x, x_data.clone());
|
||||
rt.set_data(cos, cos_data.clone());
|
||||
rt.set_data(sin, sin_data.clone());
|
||||
rt = cx.search(rt, CompileOptions::new(1));
|
||||
rt.execute(&cx.dyn_map);
|
||||
let got = rt.get_f32(y.id);
|
||||
|
||||
let expected = cpu_rope(&x_data, &cos_data, &sin_data, s, h, d);
|
||||
let mut max_err = 0.0f32;
|
||||
for (g, e) in got.iter().zip(expected.iter()) {
|
||||
let err = (g - e).abs();
|
||||
if err > max_err {
|
||||
max_err = err;
|
||||
}
|
||||
}
|
||||
eprintln!("rope: max abs err: {max_err}");
|
||||
assert!(max_err < 1e-5, "max abs error {max_err} too high");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rope_flux2_shape() {
|
||||
// Flux 2 transformer attention: S=1536 (img+txt), H=48, D=128.
|
||||
let s = 1536;
|
||||
let h = 48;
|
||||
let d = 128;
|
||||
let mut cx = Graph::default();
|
||||
let x = cx.tensor((s, h, d));
|
||||
let cos = cx.tensor((s, d));
|
||||
let sin = cx.tensor((s, d));
|
||||
let y = apply_rope(x, cos, sin).output();
|
||||
|
||||
use rand::{Rng, SeedableRng};
|
||||
let mut rng = rand::rngs::SmallRng::seed_from_u64(11);
|
||||
let x_data: Vec<f32> = (0..s * h * d)
|
||||
.map(|_| rng.random_range(-2.0..2.0_f32))
|
||||
.collect();
|
||||
let cos_data: Vec<f32> = (0..s * d)
|
||||
.map(|_| rng.random_range(-1.0..1.0_f32))
|
||||
.collect();
|
||||
let sin_data: Vec<f32> = (0..s * d)
|
||||
.map(|_| rng.random_range(-1.0..1.0_f32))
|
||||
.collect();
|
||||
|
||||
let ctx = CudaContext::new(0).unwrap();
|
||||
ctx.bind_to_thread().unwrap();
|
||||
let stream = ctx.default_stream();
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let mut rt = CudaRuntime::initialize(stream);
|
||||
rt.set_data(x, x_data.clone());
|
||||
rt.set_data(cos, cos_data.clone());
|
||||
rt.set_data(sin, sin_data.clone());
|
||||
rt = cx.search(rt, CompileOptions::new(1));
|
||||
rt.execute(&cx.dyn_map);
|
||||
let got = rt.get_f32(y.id);
|
||||
|
||||
let expected = cpu_rope(&x_data, &cos_data, &sin_data, s, h, d);
|
||||
let mut max_err = 0.0f32;
|
||||
for (g, e) in got.iter().zip(expected.iter()) {
|
||||
let err = (g - e).abs();
|
||||
if err > max_err {
|
||||
max_err = err;
|
||||
}
|
||||
}
|
||||
eprintln!("rope flux2: max abs err: {max_err}");
|
||||
assert!(max_err < 1e-4, "max abs error {max_err} too high");
|
||||
}
|
||||
374
crates/luminal_cuda_lite/src/tests/search_equivalence_fuzz.rs
Normal file
374
crates/luminal_cuda_lite/src/tests/search_equivalence_fuzz.rs
Normal file
@@ -0,0 +1,374 @@
|
||||
//! End-to-end e-graph search-space equivalence fuzz tests.
|
||||
//!
|
||||
//! These tests do not compare against a hand-written reference. They assert the
|
||||
//! stronger search invariant: every selectable LLIR graph from the same e-graph
|
||||
//! must produce finite, numerically close outputs for the same runtime inputs.
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[path = "../../../../examples/llama/src/model.rs"]
|
||||
mod llama_model;
|
||||
|
||||
use half::bf16;
|
||||
use luminal::{dtype::DType, prelude::*, shape::Expression};
|
||||
use rand::{Rng, SeedableRng, rngs::StdRng};
|
||||
|
||||
use super::utilities::{CudaSearchEquivalenceFuzzer, get_cuda_stream, random_f32_vec};
|
||||
|
||||
const SEARCH_EQUIV_SAMPLES: usize = 32;
|
||||
|
||||
fn random_bf16_vec(n: usize, seed: u64, low: f32, high: f32) -> Vec<bf16> {
|
||||
random_f32_vec(n, seed, low, high)
|
||||
.into_iter()
|
||||
.map(bf16::from_f32)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn rms_norm(x: GraphTensor, weight: GraphTensor, eps: f32) -> GraphTensor {
|
||||
let normed = x.std_norm(x.shape.last_axis(), eps);
|
||||
normed * weight.expand_lhs(&x.dims()[..x.dims().len() - 1])
|
||||
}
|
||||
|
||||
#[allow(clippy::excessive_precision)]
|
||||
fn gemma_gelu(x: GraphTensor) -> GraphTensor {
|
||||
let scaled = 1.5957691216 * x * (1. + 0.044715 * x * x);
|
||||
x * scaled.sigmoid()
|
||||
}
|
||||
|
||||
fn gather_experts(
|
||||
graph_source: GraphTensor,
|
||||
top_k_indices: GraphTensor,
|
||||
weights: GraphTensor,
|
||||
) -> GraphTensor {
|
||||
let (_, d1, d2) = weights.dims3();
|
||||
let io = d1 * d2;
|
||||
let base = top_k_indices * io;
|
||||
let within = graph_source.graph().iota(Expression::from('z'), (d1, d2));
|
||||
let n_base = base.dims().len();
|
||||
let exp_base = base.expand_dim(n_base, d1).expand_dim(n_base + 1, d2);
|
||||
let mut exp_within = within;
|
||||
for (axis, dim) in base.dims().iter().enumerate() {
|
||||
exp_within = exp_within.expand_dim(axis, *dim);
|
||||
}
|
||||
let expert_flat_idx = exp_base + exp_within;
|
||||
weights.gather(expert_flat_idx)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn llama_architecture_search_space_equivalence_fuzz() {
|
||||
let Some(stream) = get_cuda_stream() else {
|
||||
return;
|
||||
};
|
||||
|
||||
const SEQ: usize = 2;
|
||||
const CTX: usize = 3;
|
||||
const SLOTS: usize = 4;
|
||||
|
||||
let config = llama_model::LlamaConfig {
|
||||
layers: 2,
|
||||
hidden: 32,
|
||||
intermediate: 64,
|
||||
head_dim: 8,
|
||||
kv_groups: 2,
|
||||
vocab_size: 64,
|
||||
};
|
||||
|
||||
let mut cx = Graph::default();
|
||||
cx.set_dim('s', SEQ);
|
||||
cx.set_dim('c', CTX);
|
||||
|
||||
let input = cx.named_tensor("input", 's').as_dtype(DType::Int);
|
||||
let q_pos = cx.named_tensor("q_pos", 's').as_dtype(DType::Int);
|
||||
let scatter_idx = cx.named_tensor("scatter_idx", 's').as_dtype(DType::Int);
|
||||
let gather_idx = cx.named_tensor("gather_idx", 'c').as_dtype(DType::Int);
|
||||
let attn_mask = cx.named_tensor("attn_mask", ('s', 'c'));
|
||||
let kv_cache = llama_model::KVCache::new_with_config(&mut cx, SLOTS, config);
|
||||
let llama = llama_model::Llama::init_with_config(&mut cx, config);
|
||||
|
||||
let (logits, cache_outputs) =
|
||||
llama.forward(input, q_pos, scatter_idx, gather_idx, attn_mask, &kv_cache);
|
||||
let logits = logits.output();
|
||||
let mut fuzzer = CudaSearchEquivalenceFuzzer::new(&mut cx, &stream)
|
||||
.seed(0x5EED_1234)
|
||||
.samples(SEARCH_EQUIV_SAMPLES)
|
||||
.generation_size(8)
|
||||
.mutations(3)
|
||||
.build_options(CompileOptions::default().max_memory_mib(512))
|
||||
.output_f32(logits.id, "logits", 5e-2, 5e-2);
|
||||
for (layer, (k_out, v_out)) in cache_outputs.into_iter().enumerate() {
|
||||
let k_out = k_out.output();
|
||||
let v_out = v_out.output();
|
||||
fuzzer = fuzzer.output_f32(k_out.id, format!("layer{layer}.k_cache"), 3e-3, 3e-3);
|
||||
fuzzer = fuzzer.output_f32(v_out.id, format!("layer{layer}.v_cache"), 3e-3, 3e-3);
|
||||
}
|
||||
|
||||
let mut rng = StdRng::seed_from_u64(0x11A_AA55);
|
||||
fuzzer = fuzzer
|
||||
.input_i32(input.id, vec![3, 17])
|
||||
.input_i32(q_pos.id, vec![1, 2])
|
||||
.input_i32(scatter_idx.id, vec![1, 2])
|
||||
.input_i32(gather_idx.id, vec![0, 1, 2])
|
||||
.input_f32(attn_mask.id, vec![0.0, 0.0, -1e4, 0.0, 0.0, 0.0]);
|
||||
|
||||
let kv_dim = config.kv_dim();
|
||||
for tensor in kv_cache.tensors() {
|
||||
fuzzer = fuzzer.input_f32(tensor.id, vec![0.0; SLOTS * kv_dim]);
|
||||
}
|
||||
for tensor in llama.parameter_tensors() {
|
||||
let elements = tensor
|
||||
.dims()
|
||||
.iter()
|
||||
.map(|dim| dim.to_usize().expect("tiny llama test uses static params"))
|
||||
.product::<usize>();
|
||||
let data = (0..elements)
|
||||
.map(|_| rng.random_range(-0.08f32..0.08f32))
|
||||
.collect::<Vec<_>>();
|
||||
fuzzer = fuzzer.input_f32(tensor.id, data);
|
||||
}
|
||||
|
||||
let report = fuzzer.run();
|
||||
eprintln!("llama search equivalence fuzz report: {report:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gemma_architecture_search_space_equivalence_fuzz() {
|
||||
let Some(stream) = get_cuda_stream() else {
|
||||
return;
|
||||
};
|
||||
|
||||
const SEQ: usize = 2;
|
||||
const HIDDEN: usize = 32;
|
||||
const Q_DIM: usize = 24;
|
||||
const INTERMEDIATE: usize = 64;
|
||||
const EPS: f32 = 1e-6;
|
||||
|
||||
let mut cx = Graph::default();
|
||||
let input = cx.tensor((SEQ, HIDDEN));
|
||||
let attn_norm_w = cx.tensor(HIDDEN);
|
||||
let post_attn_norm_w = cx.tensor(HIDDEN);
|
||||
let pre_ff_norm_w = cx.tensor(HIDDEN);
|
||||
let post_ff_norm_w = cx.tensor(HIDDEN);
|
||||
let proj_w = cx.tensor((Q_DIM, HIDDEN));
|
||||
let o_proj_w = cx.tensor((HIDDEN, Q_DIM));
|
||||
let w_gate = cx.tensor((INTERMEDIATE, HIDDEN));
|
||||
let w_up = cx.tensor((INTERMEDIATE, HIDDEN));
|
||||
let w_down = cx.tensor((HIDDEN, INTERMEDIATE));
|
||||
|
||||
let normed = rms_norm(input, attn_norm_w, EPS);
|
||||
let proj_out = normed.matmul(proj_w.t()).matmul(o_proj_w.t());
|
||||
let attn_normed = rms_norm(proj_out, post_attn_norm_w, EPS);
|
||||
let x = input + attn_normed;
|
||||
let ff_normed = rms_norm(x, pre_ff_norm_w, EPS);
|
||||
let mlp_out =
|
||||
(gemma_gelu(ff_normed.matmul(w_gate.t())) * ff_normed.matmul(w_up.t())).matmul(w_down.t());
|
||||
let mlp_normed = rms_norm(mlp_out, post_ff_norm_w, EPS);
|
||||
let out = (x + mlp_normed).output();
|
||||
|
||||
let report = CudaSearchEquivalenceFuzzer::new(&mut cx, &stream)
|
||||
.seed(0x6E4D_4DAA)
|
||||
.samples(SEARCH_EQUIV_SAMPLES)
|
||||
.generation_size(8)
|
||||
.mutations(3)
|
||||
.build_options(CompileOptions::default().max_memory_mib(512))
|
||||
.input_f32(input.id, random_f32_vec(SEQ * HIDDEN, 101, -0.15, 0.15))
|
||||
.input_f32(attn_norm_w.id, random_f32_vec(HIDDEN, 102, 0.7, 1.3))
|
||||
.input_f32(post_attn_norm_w.id, random_f32_vec(HIDDEN, 103, 0.7, 1.3))
|
||||
.input_f32(pre_ff_norm_w.id, random_f32_vec(HIDDEN, 104, 0.7, 1.3))
|
||||
.input_f32(post_ff_norm_w.id, random_f32_vec(HIDDEN, 105, 0.7, 1.3))
|
||||
.input_f32(proj_w.id, random_f32_vec(Q_DIM * HIDDEN, 106, -0.08, 0.08))
|
||||
.input_f32(
|
||||
o_proj_w.id,
|
||||
random_f32_vec(HIDDEN * Q_DIM, 107, -0.08, 0.08),
|
||||
)
|
||||
.input_f32(
|
||||
w_gate.id,
|
||||
random_f32_vec(INTERMEDIATE * HIDDEN, 108, -0.08, 0.08),
|
||||
)
|
||||
.input_f32(
|
||||
w_up.id,
|
||||
random_f32_vec(INTERMEDIATE * HIDDEN, 109, -0.08, 0.08),
|
||||
)
|
||||
.input_f32(
|
||||
w_down.id,
|
||||
random_f32_vec(HIDDEN * INTERMEDIATE, 110, -0.08, 0.08),
|
||||
)
|
||||
.output_f32(out.id, "gemma_block", 5e-3, 5e-3)
|
||||
.run();
|
||||
eprintln!("gemma search equivalence fuzz report: {report:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moe_architecture_search_space_equivalence_fuzz() {
|
||||
let Some(stream) = get_cuda_stream() else {
|
||||
return;
|
||||
};
|
||||
|
||||
const SEQ: usize = 2;
|
||||
const HIDDEN: usize = 16;
|
||||
const NUM_EXPERTS: usize = 8;
|
||||
const TOP_K: usize = 2;
|
||||
const MOE_INTERMEDIATE: usize = 6;
|
||||
const EPS: f32 = 1e-6;
|
||||
|
||||
let mut cx = Graph::default();
|
||||
let router_input = cx.tensor(('s', HIDDEN));
|
||||
let expert_input = cx.tensor(('s', HIDDEN));
|
||||
let router_scale = cx.tensor(HIDDEN);
|
||||
let router_proj = cx.tensor((NUM_EXPERTS, HIDDEN));
|
||||
let per_expert_scale = cx.tensor(NUM_EXPERTS);
|
||||
let gate_up_weights = cx
|
||||
.tensor((NUM_EXPERTS, MOE_INTERMEDIATE * 2, HIDDEN))
|
||||
.as_dtype(DType::Bf16);
|
||||
let down_weights = cx
|
||||
.tensor((NUM_EXPERTS, HIDDEN, MOE_INTERMEDIATE))
|
||||
.as_dtype(DType::Bf16);
|
||||
|
||||
let n = router_input.dims().len();
|
||||
let e_dim = *router_proj.dims().first().unwrap();
|
||||
let k_expr = Expression::from(TOP_K);
|
||||
|
||||
let router_hidden = router_input.std_norm(n - 1, EPS)
|
||||
* router_scale.expand_lhs(&router_input.dims()[..n - 1])
|
||||
* (HIDDEN as f32).sqrt().recip();
|
||||
let routing_weights = router_hidden.matmul(router_proj.t()).softmax(n - 1);
|
||||
|
||||
let top_k_indices = routing_weights.topk_indexes(TOP_K, n - 1);
|
||||
let row_offsets = router_input
|
||||
.graph()
|
||||
.iota(Expression::from('z') / k_expr * e_dim, top_k_indices.dims());
|
||||
let routing_flat_idx = row_offsets + top_k_indices;
|
||||
let top_k_values = routing_weights.gather(routing_flat_idx);
|
||||
let top_k_norm = top_k_values.sum(n - 1).expand_dim(n - 1, TOP_K);
|
||||
let top_k_weights = (top_k_values / top_k_norm) * per_expert_scale.gather(top_k_indices);
|
||||
|
||||
let gate_up_gathered =
|
||||
gather_experts(expert_input, top_k_indices, gate_up_weights).cast(DType::F32);
|
||||
let x_exp = expert_input.expand_dim(n - 1, TOP_K).unsqueeze(n);
|
||||
let gate_up_out = x_exp.matmul(gate_up_gathered.transpose(2, 3)).squeeze(n);
|
||||
let gate = gate_up_out.slice((.., .., ..MOE_INTERMEDIATE));
|
||||
let up = gate_up_out.slice((.., .., MOE_INTERMEDIATE..));
|
||||
let hidden = gemma_gelu(gate) * up;
|
||||
|
||||
let down_gathered = gather_experts(expert_input, top_k_indices, down_weights).cast(DType::F32);
|
||||
let down_out = hidden
|
||||
.unsqueeze(2)
|
||||
.matmul(down_gathered.transpose(2, 3))
|
||||
.squeeze(2);
|
||||
let mut weights_exp = top_k_weights.unsqueeze(top_k_weights.dims().len());
|
||||
weights_exp.shape.expand(down_out.dims());
|
||||
let out = (down_out * weights_exp).sum(n - 1).output();
|
||||
cx.set_dim('s', SEQ);
|
||||
|
||||
let report = CudaSearchEquivalenceFuzzer::new(&mut cx, &stream)
|
||||
.seed(0x0DEE_55EE)
|
||||
.samples(SEARCH_EQUIV_SAMPLES)
|
||||
.generation_size(8)
|
||||
.mutations(3)
|
||||
.build_options(CompileOptions::default().max_memory_mib(512))
|
||||
.input_f32(
|
||||
router_input.id,
|
||||
random_f32_vec(SEQ * HIDDEN, 201, -0.15, 0.15),
|
||||
)
|
||||
.input_f32(
|
||||
expert_input.id,
|
||||
random_f32_vec(SEQ * HIDDEN, 202, -0.15, 0.15),
|
||||
)
|
||||
.input_f32(router_scale.id, random_f32_vec(HIDDEN, 203, 0.7, 1.3))
|
||||
.input_f32(
|
||||
router_proj.id,
|
||||
random_f32_vec(NUM_EXPERTS * HIDDEN, 204, -0.2, 0.2),
|
||||
)
|
||||
.input_f32(
|
||||
per_expert_scale.id,
|
||||
random_f32_vec(NUM_EXPERTS, 205, 0.5, 1.5),
|
||||
)
|
||||
.input_bf16(
|
||||
gate_up_weights.id,
|
||||
random_bf16_vec(NUM_EXPERTS * MOE_INTERMEDIATE * 2 * HIDDEN, 206, -0.1, 0.1),
|
||||
)
|
||||
.input_bf16(
|
||||
down_weights.id,
|
||||
random_bf16_vec(NUM_EXPERTS * HIDDEN * MOE_INTERMEDIATE, 207, -0.1, 0.1),
|
||||
)
|
||||
.output_f32(out.id, "gemma_moe_block", 5e-2, 5e-2)
|
||||
.run();
|
||||
eprintln!("moe search equivalence fuzz report: {report:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moe_architecture_native_reference_fuzz() {
|
||||
let Some(stream) = get_cuda_stream() else {
|
||||
return;
|
||||
};
|
||||
|
||||
const SEQ: usize = 2;
|
||||
const HIDDEN: usize = 16;
|
||||
const NUM_EXPERTS: usize = 8;
|
||||
const TOP_K: usize = 2;
|
||||
const MOE_INTERMEDIATE: usize = 6;
|
||||
|
||||
let mut cx = Graph::default();
|
||||
let input = cx.tensor(('s', HIDDEN));
|
||||
let router = cx.tensor((NUM_EXPERTS, HIDDEN));
|
||||
let gate_up_weights = cx
|
||||
.tensor((NUM_EXPERTS, MOE_INTERMEDIATE * 2, HIDDEN))
|
||||
.as_dtype(DType::Bf16);
|
||||
let down_weights = cx
|
||||
.tensor((NUM_EXPERTS, HIDDEN, MOE_INTERMEDIATE))
|
||||
.as_dtype(DType::Bf16);
|
||||
|
||||
let n = input.dims().len();
|
||||
let e_dim = *router.dims().first().unwrap();
|
||||
let k_expr = Expression::from(TOP_K);
|
||||
|
||||
let routing_weights = input.matmul(router.t()).softmax(n - 1);
|
||||
let top_k_indices = routing_weights.topk_indexes(TOP_K, n - 1);
|
||||
let row_offsets = input
|
||||
.graph()
|
||||
.iota(Expression::from('z') / k_expr * e_dim, top_k_indices.dims());
|
||||
let routing_flat_idx = row_offsets + top_k_indices;
|
||||
let top_k_values = routing_weights.gather(routing_flat_idx);
|
||||
let top_k_weights = top_k_values / top_k_values.sum(n - 1).expand_dim(n - 1, TOP_K);
|
||||
|
||||
let gate_up_gathered = gather_experts(input, top_k_indices, gate_up_weights).cast(DType::F32);
|
||||
let input_exp = input.expand_dim(n - 1, TOP_K).unsqueeze(n);
|
||||
let gate_up_out = input_exp
|
||||
.matmul(gate_up_gathered.transpose(2, 3))
|
||||
.squeeze(n);
|
||||
let gate = gate_up_out.slice((.., .., ..MOE_INTERMEDIATE));
|
||||
let up = gate_up_out.slice((.., .., MOE_INTERMEDIATE..));
|
||||
let hidden = gate.silu() * up;
|
||||
|
||||
let down_gathered = gather_experts(input, top_k_indices, down_weights).cast(DType::F32);
|
||||
let down_out = hidden
|
||||
.unsqueeze(2)
|
||||
.matmul(down_gathered.transpose(2, 3))
|
||||
.squeeze(2);
|
||||
let mut weights_exp = top_k_weights.unsqueeze(top_k_weights.dims().len());
|
||||
weights_exp.shape.expand(down_out.dims());
|
||||
let out = (down_out * weights_exp).sum(n - 1).output();
|
||||
cx.set_dim('s', SEQ);
|
||||
|
||||
let report = CudaSearchEquivalenceFuzzer::new(&mut cx, &stream)
|
||||
.seed(0x51A7_E5ED)
|
||||
.samples(SEARCH_EQUIV_SAMPLES)
|
||||
.generation_size(8)
|
||||
.mutations(3)
|
||||
.build_options(CompileOptions::default().max_memory_mib(512))
|
||||
.native_reference()
|
||||
.input_f32(input.id, random_f32_vec(SEQ * HIDDEN, 301, -0.15, 0.15))
|
||||
.input_f32(
|
||||
router.id,
|
||||
random_f32_vec(NUM_EXPERTS * HIDDEN, 302, -0.2, 0.2),
|
||||
)
|
||||
.input_bf16(
|
||||
gate_up_weights.id,
|
||||
random_bf16_vec(NUM_EXPERTS * MOE_INTERMEDIATE * 2 * HIDDEN, 303, -0.1, 0.1),
|
||||
)
|
||||
.input_bf16(
|
||||
down_weights.id,
|
||||
random_bf16_vec(NUM_EXPERTS * HIDDEN * MOE_INTERMEDIATE, 304, -0.1, 0.1),
|
||||
)
|
||||
.output_f32(out.id, "qwen_swiglu_moe_native_reference", 6e-2, 6e-2)
|
||||
.run();
|
||||
eprintln!("moe native-reference fuzz report: {report:?}");
|
||||
}
|
||||
@@ -267,7 +267,7 @@ fn test_mini_transformer_layer() {
|
||||
let layer = MiniTransformerLayer::init(&mut cx);
|
||||
let out = layer.forward(input).output();
|
||||
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let mut rt = CudaRuntime::initialize(stream);
|
||||
|
||||
let input_data = random_f32_vec(SEQ * HIDDEN, 42, -0.5, 0.5);
|
||||
@@ -280,7 +280,7 @@ fn test_mini_transformer_layer() {
|
||||
|
||||
// Use minimal search iterations to avoid excessive graph rewriting
|
||||
// which can cause float drift through softmax/RMSNorm reordering
|
||||
rt = cx.search(rt, 1);
|
||||
rt = cx.search(rt, CompileOptions::new(1));
|
||||
rt.execute(&cx.dyn_map);
|
||||
let result = rt.get_f32(out);
|
||||
|
||||
@@ -303,7 +303,7 @@ fn test_mini_transformer_two_layers() {
|
||||
let x = layer1.forward(input);
|
||||
let out = layer2.forward(x).output();
|
||||
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let mut rt = CudaRuntime::initialize(stream);
|
||||
|
||||
let input_data = random_f32_vec(SEQ * HIDDEN, 42, -0.5, 0.5);
|
||||
@@ -316,7 +316,7 @@ fn test_mini_transformer_two_layers() {
|
||||
rt.set_data(*tensor, data.clone());
|
||||
}
|
||||
|
||||
rt = cx.search(rt, 1);
|
||||
rt = cx.search(rt, CompileOptions::new(1));
|
||||
rt.execute(&cx.dyn_map);
|
||||
let result = rt.get_f32(out);
|
||||
|
||||
@@ -361,7 +361,7 @@ fn test_transformer_multi_seed() {
|
||||
let layer = MiniTransformerLayer::init(&mut cx);
|
||||
let out = layer.forward(input).output();
|
||||
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let mut rt = CudaRuntime::initialize(stream.clone());
|
||||
|
||||
let input_data = random_f32_vec(SEQ * HIDDEN, seed, -0.5, 0.5);
|
||||
@@ -372,7 +372,7 @@ fn test_transformer_multi_seed() {
|
||||
rt.set_data(*tensor, data.clone());
|
||||
}
|
||||
|
||||
rt = cx.search(rt, 1);
|
||||
rt = cx.search(rt, CompileOptions::new(1));
|
||||
rt.execute(&cx.dyn_map);
|
||||
let result = rt.get_f32(out);
|
||||
|
||||
@@ -394,7 +394,7 @@ fn test_rms_norm_cuda() {
|
||||
let weight = cx.tensor(HIDDEN);
|
||||
let out = rms_norm(input, weight, 1e-5).output();
|
||||
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let mut rt = CudaRuntime::initialize(stream);
|
||||
|
||||
let input_data = random_f32_vec(SEQ * HIDDEN, 1, -0.5, 0.5);
|
||||
@@ -404,7 +404,7 @@ fn test_rms_norm_cuda() {
|
||||
.collect();
|
||||
rt.set_data(input, input_data.clone());
|
||||
rt.set_data(weight, weight_data.clone());
|
||||
rt = cx.search(rt, 5);
|
||||
rt = cx.search(rt, CompileOptions::new(5));
|
||||
rt.execute(&cx.dyn_map);
|
||||
let result = rt.get_f32(out);
|
||||
|
||||
@@ -433,7 +433,7 @@ fn test_self_attention_cuda() {
|
||||
let wo = cx.tensor((HIDDEN, HIDDEN));
|
||||
let out = self_attention(input, wq, wk, wv, wo).output();
|
||||
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let mut rt = CudaRuntime::initialize(stream);
|
||||
|
||||
let input_data = random_f32_vec(SEQ * HIDDEN, 10, -0.5, 0.5);
|
||||
@@ -447,7 +447,7 @@ fn test_self_attention_cuda() {
|
||||
rt.set_data(wk, wk_data.clone());
|
||||
rt.set_data(wv, wv_data.clone());
|
||||
rt.set_data(wo, wo_data.clone());
|
||||
rt = cx.search(rt, 5);
|
||||
rt = cx.search(rt, CompileOptions::new(5));
|
||||
rt.execute(&cx.dyn_map);
|
||||
let result = rt.get_f32(out);
|
||||
|
||||
@@ -479,7 +479,7 @@ fn test_swiglu_mlp_cuda() {
|
||||
let w_down = cx.tensor((HIDDEN, INTERMEDIATE));
|
||||
let out = swiglu_mlp(input, w_gate, w_up, w_down).output();
|
||||
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let mut rt = CudaRuntime::initialize(stream);
|
||||
|
||||
let input_data = random_f32_vec(SEQ * HIDDEN, 20, -0.5, 0.5);
|
||||
@@ -491,7 +491,7 @@ fn test_swiglu_mlp_cuda() {
|
||||
rt.set_data(w_gate, gate_data.clone());
|
||||
rt.set_data(w_up, up_data.clone());
|
||||
rt.set_data(w_down, down_data.clone());
|
||||
rt = cx.search(rt, 5);
|
||||
rt = cx.search(rt, CompileOptions::new(5));
|
||||
rt.execute(&cx.dyn_map);
|
||||
let result = rt.get_f32(out);
|
||||
|
||||
@@ -526,11 +526,11 @@ fn test_rolled_chained_scalar_muls() {
|
||||
let chained = ((x * 2.0_f32) * 3.0_f32) * 5.0_f32;
|
||||
let out = (chained + x).output();
|
||||
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let mut rt = CudaRuntime::initialize(stream);
|
||||
let x_data = random_f32_vec(4 * 32, 101, -0.5, 0.5);
|
||||
rt.set_data(x, x_data.clone());
|
||||
rt = cx.search(rt, 3);
|
||||
rt = cx.search(rt, CompileOptions::new(3));
|
||||
rt.execute(&cx.dyn_map);
|
||||
|
||||
let result = rt.get_f32(out);
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
use candle_core::{Device, Tensor, WithDType};
|
||||
use cudarc::driver::CudaContext;
|
||||
use half::{bf16, f16};
|
||||
use itertools::Itertools;
|
||||
use luminal::egglog_utils::{
|
||||
egglog_to_llir, extract_generation, hash_choice_set, random_initial_choice, validate_choice_set,
|
||||
EGraphChoiceSet, egglog_to_llir, extract_generation, hash_choice_set, random_initial_choice,
|
||||
validate_choice_set,
|
||||
};
|
||||
use luminal::prelude::{
|
||||
petgraph::{Direction, algo::toposort, visit::EdgeRef},
|
||||
*,
|
||||
};
|
||||
use luminal::prelude::*;
|
||||
use num_traits::{Num, Signed};
|
||||
use rand::{Rng, SeedableRng, rngs::StdRng};
|
||||
use std::sync::Arc;
|
||||
@@ -128,6 +133,498 @@ pub fn get_cuda_stream() -> Option<Arc<cudarc::driver::CudaStream>> {
|
||||
Some(ctx.default_stream())
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum CudaFuzzInput {
|
||||
F32(NodeIndex, Vec<f32>),
|
||||
Bf16(NodeIndex, Vec<bf16>),
|
||||
I32(NodeIndex, Vec<i32>),
|
||||
}
|
||||
|
||||
impl CudaFuzzInput {
|
||||
fn apply(&self, rt: &mut CudaRuntime) {
|
||||
match self {
|
||||
Self::F32(id, data) => rt.set_data(*id, data.clone()),
|
||||
Self::Bf16(id, data) => rt.set_data(*id, data.clone()),
|
||||
Self::I32(id, data) => rt.set_data(*id, data.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_native(&self, rt: &mut NativeRuntime) {
|
||||
match self {
|
||||
Self::F32(id, data) => rt.set_data(*id, data.clone()),
|
||||
Self::Bf16(id, data) => rt.set_data(*id, data.clone()),
|
||||
Self::I32(id, data) => rt.set_data(*id, data.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct F32OutputCheck {
|
||||
pub id: NodeIndex,
|
||||
pub name: String,
|
||||
pub rtol: f32,
|
||||
pub atol: f32,
|
||||
}
|
||||
|
||||
impl F32OutputCheck {
|
||||
pub fn new(id: NodeIndex, name: impl Into<String>, rtol: f32, atol: f32) -> Self {
|
||||
Self {
|
||||
id,
|
||||
name: name.into(),
|
||||
rtol,
|
||||
atol,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SearchEquivalenceFuzzConfig {
|
||||
pub seed: u64,
|
||||
pub samples: usize,
|
||||
pub generation_size: usize,
|
||||
pub mutations: usize,
|
||||
pub max_attempts: usize,
|
||||
pub build_options: CompileOptions,
|
||||
pub reference: SearchEquivalenceReference,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SearchEquivalenceReference {
|
||||
FirstCudaExtraction,
|
||||
NativeRuntime,
|
||||
}
|
||||
|
||||
impl Default for SearchEquivalenceFuzzConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
seed: 0,
|
||||
samples: 32,
|
||||
generation_size: 16,
|
||||
mutations: 2,
|
||||
max_attempts: 1_000,
|
||||
build_options: CompileOptions::default(),
|
||||
reference: SearchEquivalenceReference::FirstCudaExtraction,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct SearchEquivalenceFuzzReport {
|
||||
pub tested: usize,
|
||||
pub skipped_invalid: usize,
|
||||
}
|
||||
|
||||
struct ChoiceRun {
|
||||
outputs: Vec<Vec<f32>>,
|
||||
llir_summary: String,
|
||||
}
|
||||
|
||||
pub struct CudaSearchEquivalenceFuzzer<'a> {
|
||||
cx: &'a mut Graph,
|
||||
stream: &'a Arc<cudarc::driver::CudaStream>,
|
||||
inputs: Vec<CudaFuzzInput>,
|
||||
outputs: Vec<F32OutputCheck>,
|
||||
config: SearchEquivalenceFuzzConfig,
|
||||
}
|
||||
|
||||
impl<'a> CudaSearchEquivalenceFuzzer<'a> {
|
||||
pub fn new(cx: &'a mut Graph, stream: &'a Arc<cudarc::driver::CudaStream>) -> Self {
|
||||
Self {
|
||||
cx,
|
||||
stream,
|
||||
inputs: Vec::new(),
|
||||
outputs: Vec::new(),
|
||||
config: SearchEquivalenceFuzzConfig::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn seed(mut self, seed: u64) -> Self {
|
||||
self.config.seed = seed;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn samples(mut self, samples: usize) -> Self {
|
||||
self.config.samples = samples;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn generation_size(mut self, generation_size: usize) -> Self {
|
||||
self.config.generation_size = generation_size;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn mutations(mut self, mutations: usize) -> Self {
|
||||
self.config.mutations = mutations;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn build_options(mut self, build_options: CompileOptions) -> Self {
|
||||
self.config.build_options = build_options;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn native_reference(mut self) -> Self {
|
||||
self.config.reference = SearchEquivalenceReference::NativeRuntime;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn input_f32(mut self, id: NodeIndex, data: Vec<f32>) -> Self {
|
||||
self.inputs.push(CudaFuzzInput::F32(id, data));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn input_bf16(mut self, id: NodeIndex, data: Vec<bf16>) -> Self {
|
||||
self.inputs.push(CudaFuzzInput::Bf16(id, data));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn input_i32(mut self, id: NodeIndex, data: Vec<i32>) -> Self {
|
||||
self.inputs.push(CudaFuzzInput::I32(id, data));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn output_f32(
|
||||
mut self,
|
||||
id: NodeIndex,
|
||||
name: impl Into<String>,
|
||||
rtol: f32,
|
||||
atol: f32,
|
||||
) -> Self {
|
||||
self.outputs.push(F32OutputCheck::new(id, name, rtol, atol));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn run(self) -> SearchEquivalenceFuzzReport {
|
||||
fuzz_cuda_search_space_equivalence(
|
||||
self.cx,
|
||||
self.stream,
|
||||
&self.inputs,
|
||||
&self.outputs,
|
||||
self.config,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// End-to-end search-space equivalence fuzzing for CUDA.
|
||||
///
|
||||
/// This builds the normal CUDA e-graph search space, extracts random selectable
|
||||
/// LLIR graphs, runs each with identical inputs, and verifies every requested
|
||||
/// f32 output matches the first valid extraction. The reference is intentionally
|
||||
/// another selected LLIR graph, not a hand-written CPU implementation: this
|
||||
/// catches cases where supposedly equivalent e-graph choices diverge, including
|
||||
/// candidates that produce non-finite outputs.
|
||||
pub fn fuzz_cuda_search_space_equivalence(
|
||||
cx: &mut Graph,
|
||||
stream: &Arc<cudarc::driver::CudaStream>,
|
||||
inputs: &[CudaFuzzInput],
|
||||
outputs: &[F32OutputCheck],
|
||||
config: SearchEquivalenceFuzzConfig,
|
||||
) -> SearchEquivalenceFuzzReport {
|
||||
assert!(
|
||||
!outputs.is_empty(),
|
||||
"fuzz harness needs at least one output"
|
||||
);
|
||||
|
||||
let native_reference_outputs = if config.reference == SearchEquivalenceReference::NativeRuntime
|
||||
{
|
||||
cx.build_search_space::<NativeRuntime>(CompileOptions::default());
|
||||
let mut native_rng = StdRng::seed_from_u64(config.seed);
|
||||
let mut native_rt = cx.search_with_rng(
|
||||
NativeRuntime::default(),
|
||||
CompileOptions::new(1),
|
||||
&mut native_rng,
|
||||
);
|
||||
for input in inputs {
|
||||
input.apply_native(&mut native_rt);
|
||||
}
|
||||
native_rt.execute(&cx.dyn_map);
|
||||
Some(
|
||||
outputs
|
||||
.iter()
|
||||
.map(|out| native_rt.get_f32(out.id).clone())
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
cx.build_search_space::<CudaRuntime>(config.build_options);
|
||||
|
||||
let egraph = cx.egraph().expect("search space should be built");
|
||||
let ops = cx.egglog_ops().expect("search ops should be built");
|
||||
let seed = if native_reference_outputs.is_some() {
|
||||
config.seed.wrapping_add(0xC0DA_C0DA)
|
||||
} else {
|
||||
config.seed
|
||||
};
|
||||
let mut rng = StdRng::seed_from_u64(seed);
|
||||
let mut prev_selected = FxHashSet::default();
|
||||
let mut base = random_initial_choice(egraph, &mut rng);
|
||||
prev_selected.insert(hash_choice_set(&base));
|
||||
|
||||
let mut skipped_invalid = 0usize;
|
||||
let reference_is_cuda = native_reference_outputs.is_none();
|
||||
let (reference_hash, reference_outputs, reference_llir_summary, mut tested) =
|
||||
if let Some(reference_outputs) = native_reference_outputs {
|
||||
(0, reference_outputs, None, 0usize)
|
||||
} else {
|
||||
let mut attempts = 0usize;
|
||||
let (reference_hash, reference_run) = loop {
|
||||
attempts += 1;
|
||||
if attempts > config.max_attempts {
|
||||
panic!(
|
||||
"failed to extract a valid reference LLIR after {} attempts",
|
||||
config.max_attempts
|
||||
);
|
||||
}
|
||||
if validate_choice_set(egraph, &base, ops).is_err() {
|
||||
skipped_invalid += 1;
|
||||
} else {
|
||||
let hash = hash_choice_set(&base);
|
||||
match run_choice_outputs(cx, stream, inputs, outputs, &base) {
|
||||
Ok(run) => break (hash, run),
|
||||
Err(err) => panic!("reference candidate hash={hash} failed: {err}"),
|
||||
}
|
||||
}
|
||||
base = random_initial_choice(egraph, &mut rng);
|
||||
prev_selected.insert(hash_choice_set(&base));
|
||||
};
|
||||
(
|
||||
reference_hash,
|
||||
reference_run.outputs,
|
||||
Some(reference_run.llir_summary),
|
||||
1usize,
|
||||
)
|
||||
};
|
||||
|
||||
let mut attempts = 0usize;
|
||||
while tested < config.samples && attempts < config.max_attempts {
|
||||
attempts += 1;
|
||||
let mut candidates = extract_generation(
|
||||
egraph,
|
||||
&base,
|
||||
config.generation_size,
|
||||
config.mutations,
|
||||
&mut prev_selected,
|
||||
&mut rng,
|
||||
);
|
||||
if candidates.is_empty() {
|
||||
let next = random_initial_choice(egraph, &mut rng);
|
||||
prev_selected.insert(hash_choice_set(&next));
|
||||
candidates.push(next);
|
||||
}
|
||||
|
||||
for candidate in candidates {
|
||||
if tested >= config.samples {
|
||||
break;
|
||||
}
|
||||
let candidate_hash = hash_choice_set(&candidate);
|
||||
if reference_is_cuda && candidate_hash == reference_hash {
|
||||
continue;
|
||||
}
|
||||
if validate_choice_set(egraph, &candidate, ops).is_err() {
|
||||
skipped_invalid += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
let candidate_run = run_choice_outputs(cx, stream, inputs, outputs, &candidate)
|
||||
.unwrap_or_else(|err| panic!("candidate hash={candidate_hash} failed: {err}"));
|
||||
assert_fuzz_outputs_close(
|
||||
outputs,
|
||||
&reference_outputs,
|
||||
&candidate_run.outputs,
|
||||
&candidate_run.llir_summary,
|
||||
reference_llir_summary.as_deref(),
|
||||
reference_hash,
|
||||
candidate_hash,
|
||||
);
|
||||
base = candidate;
|
||||
tested += 1;
|
||||
}
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
tested, config.samples,
|
||||
"only tested {tested}/{} LLIR samples before exhausting attempts",
|
||||
config.samples
|
||||
);
|
||||
SearchEquivalenceFuzzReport {
|
||||
tested,
|
||||
skipped_invalid,
|
||||
}
|
||||
}
|
||||
|
||||
fn run_choice_outputs<'a>(
|
||||
cx: &'a Graph,
|
||||
stream: &Arc<cudarc::driver::CudaStream>,
|
||||
inputs: &[CudaFuzzInput],
|
||||
outputs: &[F32OutputCheck],
|
||||
choices: &EGraphChoiceSet<'a>,
|
||||
) -> Result<ChoiceRun, String> {
|
||||
let egraph = cx.egraph().ok_or("search space was not built")?;
|
||||
let ops = cx.egglog_ops().ok_or("search ops were not built")?;
|
||||
let mut list_cache = FxHashMap::default();
|
||||
let mut expr_cache = FxHashMap::default();
|
||||
let mut llir_graph = egglog_to_llir(
|
||||
egraph,
|
||||
choices.clone(),
|
||||
ops,
|
||||
&cx.custom_ops,
|
||||
&mut list_cache,
|
||||
&mut expr_cache,
|
||||
None,
|
||||
);
|
||||
unroll_loops_in_llir(&mut llir_graph);
|
||||
let llir_summary = summarize_llir(&llir_graph);
|
||||
|
||||
let mut rt = CudaRuntime::initialize(stream.clone());
|
||||
rt.load_llir(&llir_graph);
|
||||
rt.preserve_intermediate_buffers_for_debug();
|
||||
for input in inputs {
|
||||
input.apply(&mut rt);
|
||||
}
|
||||
if std::env::var_os("LUMINAL_FUZZ_DUMP_LAST_LLIR").is_some() {
|
||||
let _ = std::fs::write("/tmp/luminal_fuzz_last_candidate_llir.txt", &llir_summary);
|
||||
}
|
||||
rt.execute(&cx.dyn_map);
|
||||
let topo_order = toposort(&llir_graph, None).map_err(|cycle| {
|
||||
format!(
|
||||
"extracted LLIR contains cycle at node {:?}",
|
||||
cycle.node_id()
|
||||
)
|
||||
})?;
|
||||
if let Some(report) = rt.first_nonfinite_f32_buffer_in_nodes(topo_order) {
|
||||
let dump_path = "/tmp/luminal_fuzz_bad_candidate_llir.txt";
|
||||
let _ = std::fs::write(dump_path, &llir_summary);
|
||||
let op = llir_graph
|
||||
.node_weight(report.node)
|
||||
.map(|op| format!("{op:?}"))
|
||||
.unwrap_or_else(|| "unknown op".to_string());
|
||||
return Err(format!(
|
||||
"LLIR produced non-finite F32 buffer node={} index={} value={} op={}; llir={dump_path}",
|
||||
report.node.index(),
|
||||
report.index,
|
||||
report.value,
|
||||
op
|
||||
));
|
||||
}
|
||||
|
||||
let values = outputs
|
||||
.iter()
|
||||
.map(|out| rt.get_f32(out.id))
|
||||
.collect::<Vec<_>>();
|
||||
for (spec, values) in outputs.iter().zip(&values) {
|
||||
if let Some((idx, value)) = values
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(_, value)| !value.is_finite())
|
||||
{
|
||||
let dump_path = "/tmp/luminal_fuzz_bad_candidate_llir.txt";
|
||||
let _ = std::fs::write(dump_path, &llir_summary);
|
||||
let internal = rt
|
||||
.first_nonfinite_f32_buffer()
|
||||
.map(|report| {
|
||||
let op = llir_graph
|
||||
.node_weight(report.node)
|
||||
.map(|op| format!("{op:?}"))
|
||||
.unwrap_or_else(|| "unknown op".to_string());
|
||||
format!(
|
||||
"; first observed non-finite buffer node={} index={} value={} op={}",
|
||||
report.node.index(),
|
||||
report.index,
|
||||
report.value,
|
||||
op
|
||||
)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
return Err(format!(
|
||||
"output {} produced non-finite value {value} at index {idx}{internal}; llir={dump_path}",
|
||||
spec.name
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(ChoiceRun {
|
||||
outputs: values,
|
||||
llir_summary,
|
||||
})
|
||||
}
|
||||
|
||||
fn assert_fuzz_outputs_close(
|
||||
outputs: &[F32OutputCheck],
|
||||
expected: &[Vec<f32>],
|
||||
actual: &[Vec<f32>],
|
||||
candidate_llir_summary: &str,
|
||||
reference_llir_summary: Option<&str>,
|
||||
reference_hash: u64,
|
||||
candidate_hash: u64,
|
||||
) {
|
||||
for ((spec, expected), actual) in outputs.iter().zip(expected.iter()).zip(actual.iter()) {
|
||||
assert_eq!(
|
||||
expected.len(),
|
||||
actual.len(),
|
||||
"output {} length mismatch for candidate hash={candidate_hash} reference hash={reference_hash}",
|
||||
spec.name
|
||||
);
|
||||
let mut max_abs = 0.0f32;
|
||||
let mut max_rel = 0.0f32;
|
||||
let mut worst = 0usize;
|
||||
for (i, (&a, &b)) in actual.iter().zip(expected.iter()).enumerate() {
|
||||
assert!(
|
||||
a.is_finite(),
|
||||
"output {} candidate hash={candidate_hash} produced non-finite value {a} at index {i}",
|
||||
spec.name
|
||||
);
|
||||
assert!(
|
||||
b.is_finite(),
|
||||
"output {} reference hash={reference_hash} produced non-finite value {b} at index {i}",
|
||||
spec.name
|
||||
);
|
||||
let abs = (a - b).abs();
|
||||
let rel = abs / b.abs().max(1e-12);
|
||||
if abs > max_abs {
|
||||
max_abs = abs;
|
||||
max_rel = rel;
|
||||
worst = i;
|
||||
}
|
||||
if abs > spec.atol + spec.rtol * b.abs() {
|
||||
let dump_path = "/tmp/luminal_fuzz_bad_candidate_llir.txt";
|
||||
let _ = std::fs::write(dump_path, candidate_llir_summary);
|
||||
if let Some(reference_llir_summary) = reference_llir_summary {
|
||||
let _ = std::fs::write(
|
||||
"/tmp/luminal_fuzz_bad_reference_llir.txt",
|
||||
reference_llir_summary,
|
||||
);
|
||||
}
|
||||
panic!(
|
||||
"output {} mismatch candidate hash={candidate_hash} reference hash={reference_hash} index={i} actual={a} expected={b} abs={abs} rel={rel} tolerance={} candidate_llir={dump_path}",
|
||||
spec.name,
|
||||
spec.atol + spec.rtol * b.abs()
|
||||
);
|
||||
}
|
||||
}
|
||||
eprintln!(
|
||||
"fuzz output {} ok: candidate hash={candidate_hash} max_abs={max_abs} max_rel={max_rel} worst={worst}",
|
||||
spec.name
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn summarize_llir(llir_graph: &LLIRGraph) -> String {
|
||||
llir_graph
|
||||
.node_indices()
|
||||
.map(|idx| {
|
||||
let inputs = llir_graph
|
||||
.edges_directed(idx, Direction::Incoming)
|
||||
.sorted_by_key(|edge| edge.id())
|
||||
.map(|edge| edge.source().index().to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
format!("{} <- [{}]: {:?}", idx.index(), inputs, &llir_graph[idx])
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
/// Get the GPU compute capability as (major, minor).
|
||||
pub fn gpu_compute_cap() -> Option<(i32, i32)> {
|
||||
let ctx = CudaContext::new(0).ok()?;
|
||||
@@ -136,14 +633,15 @@ pub fn gpu_compute_cap() -> Option<(i32, i32)> {
|
||||
|
||||
/// Check if the current GPU supports the given dtype for tensor core / WMMA operations.
|
||||
pub fn gpu_supports_dtype(dtype: luminal::dtype::DType) -> bool {
|
||||
let Some((major, _)) = gpu_compute_cap() else {
|
||||
let Some((major, minor)) = gpu_compute_cap() else {
|
||||
return false;
|
||||
};
|
||||
match dtype {
|
||||
luminal::dtype::DType::Bf16 => major >= 8, // Ampere (sm_80+)
|
||||
luminal::dtype::DType::F4E2M1
|
||||
| luminal::dtype::DType::F8E4M3
|
||||
| luminal::dtype::DType::F8UE8M0 => major >= 10, // Blackwell (sm_100+)
|
||||
luminal::dtype::DType::F8E4M3 | luminal::dtype::DType::F8E5M2 => {
|
||||
major > 8 || (major == 8 && minor >= 9)
|
||||
} // Ada/Hopper (sm_89+)
|
||||
luminal::dtype::DType::F4E2M1 | luminal::dtype::DType::F8UE8M0 => major >= 10, // Blackwell (sm_100+)
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
@@ -198,12 +696,12 @@ pub fn test_unary_cuda<T: TestDType>(
|
||||
let a = cx.tensor(shape.clone());
|
||||
let b = func(a).output();
|
||||
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let mut rt = CudaRuntime::initialize(stream.clone());
|
||||
|
||||
let input_data = generator(n_elements, seed);
|
||||
rt.set_data(a, input_data.clone());
|
||||
rt = cx.search(rt, 5);
|
||||
rt = cx.search(rt, CompileOptions::new(5));
|
||||
rt.execute(&cx.dyn_map);
|
||||
|
||||
let result = T::get_from_runtime(&rt, b.id);
|
||||
@@ -271,14 +769,14 @@ pub fn test_binary_cuda<T: TestDType>(
|
||||
let b = cx.tensor(b_shape.clone());
|
||||
let c = func(a, b).output();
|
||||
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let mut rt = CudaRuntime::initialize(stream.clone());
|
||||
|
||||
let a_data = a_generator(a_elements, seed);
|
||||
let b_data = b_generator(b_elements, seed.wrapping_add(1));
|
||||
rt.set_data(a, a_data.clone());
|
||||
rt.set_data(b, b_data.clone());
|
||||
rt = cx.search(rt, 5);
|
||||
rt = cx.search(rt, CompileOptions::new(5));
|
||||
rt.execute(&cx.dyn_map);
|
||||
|
||||
let result = T::get_from_runtime(&rt, c.id);
|
||||
@@ -338,7 +836,7 @@ pub fn test_mod(
|
||||
let b = cx.tensor(b_shape.clone());
|
||||
let c = func(a, b).output();
|
||||
|
||||
cx.build_search_space::<CudaRuntime>();
|
||||
cx.build_search_space::<CudaRuntime>(CompileOptions::default());
|
||||
let mut rt = CudaRuntime::initialize(stream.clone());
|
||||
|
||||
let a_data = random_f32_vec(a_elements, seed, -0.5, 0.5);
|
||||
@@ -346,7 +844,7 @@ pub fn test_mod(
|
||||
let b_data = random_f32_vec(b_elements, seed.wrapping_add(1), 0.1, 0.5);
|
||||
rt.set_data(a, a_data.clone());
|
||||
rt.set_data(b, b_data.clone());
|
||||
rt = cx.search(rt, 5);
|
||||
rt = cx.search(rt, CompileOptions::new(5));
|
||||
rt.execute(&cx.dyn_map);
|
||||
|
||||
let result = rt.get_f32(c);
|
||||
|
||||
@@ -1,22 +1,32 @@
|
||||
[package]
|
||||
name = "luminal_metal"
|
||||
version = "0.2.0"
|
||||
edition = "2021"
|
||||
edition = "2024"
|
||||
description = "Metal backend for luminal"
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[dependencies]
|
||||
luminal = { path = "../.." }
|
||||
metal = "0.31"
|
||||
metal = { version = "0.31", features = ["mps"] }
|
||||
objc = "0.2"
|
||||
as-any = "0.3.2"
|
||||
itertools = "0.12.1"
|
||||
half = "2.7.1"
|
||||
half = { version = "2.7.1", features = ["bytemuck"] }
|
||||
tracing = "0.1.43"
|
||||
safetensors = "0.7.0"
|
||||
memmap2 = "0.9.9"
|
||||
bytemuck = "1.24.0"
|
||||
|
||||
[dev-dependencies]
|
||||
candle-core = "0.9.2-alpha.1"
|
||||
hf-hub = { version = "0.4", default-features = false, features = ["rustls-tls", "ureq"] }
|
||||
luminal_nn = { path = "../luminal_nn" }
|
||||
luminal_tracing = { path = "../luminal_tracing" }
|
||||
proptest = "1.9.0"
|
||||
rand = "0.9.2"
|
||||
rustc-hash = "2.1"
|
||||
tokenizers = "0.22.2"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
|
||||
[lints.rust]
|
||||
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(feature, values("cargo-clippy"))'] }
|
||||
|
||||
641
crates/luminal_metal/examples/llama_1b.rs
Normal file
641
crates/luminal_metal/examples/llama_1b.rs
Normal file
@@ -0,0 +1,641 @@
|
||||
use hf_hub::api::sync::Api;
|
||||
use luminal::{
|
||||
dtype::DType,
|
||||
graph::{CompileOptions, DimBucket, Graph},
|
||||
prelude::{F32Pow, GraphTensor, Runtime},
|
||||
};
|
||||
use luminal_metal::MetalRuntime;
|
||||
use luminal_nn::{LayerNorm, gather_rows, scatter_rows};
|
||||
use luminal_tracing::luminal_filter;
|
||||
use rustc_hash::FxHashSet;
|
||||
use std::{
|
||||
error::Error,
|
||||
io::Write,
|
||||
path::PathBuf,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tokenizers::Tokenizer;
|
||||
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
|
||||
|
||||
const REPO_ID: &str = "unsloth/Llama-3.2-1B-Instruct";
|
||||
const MAX_SEQ_LEN: usize = 2048;
|
||||
const GEN_TOKENS: usize = 96;
|
||||
const SEARCH_GRAPHS: usize = 100;
|
||||
const SEARCH_MEMORY_MIB: usize = 1536;
|
||||
const PROMPT: &str = "In one short paragraph, explain neural networks using the words layers, neurons, learning, and data.";
|
||||
|
||||
const LAYERS: usize = 16;
|
||||
const HIDDEN: usize = 2048;
|
||||
const INTERMEDIATE: usize = 8192;
|
||||
const HEAD_DIM: usize = 64;
|
||||
const N_HEADS: usize = 32;
|
||||
const N_KV_HEADS: usize = 8;
|
||||
const KV_GROUPS: usize = N_HEADS / N_KV_HEADS;
|
||||
const KV_DIM: usize = N_KV_HEADS * HEAD_DIM;
|
||||
const VOCAB_SIZE: usize = 128256;
|
||||
const RMS_NORM_EPS: f32 = 1e-5;
|
||||
const ROPE_THETA: f32 = 500_000.0;
|
||||
const EOS_TOKEN: u32 = 128009;
|
||||
const STOP_TOKEN: u32 = 128001;
|
||||
|
||||
fn prepare_hf_model() -> Result<PathBuf, Box<dyn Error>> {
|
||||
let repo = Api::new()?.model(REPO_ID.to_string());
|
||||
let tokenizer_path = repo.get("tokenizer.json")?;
|
||||
repo.get("model.safetensors")?;
|
||||
Ok(tokenizer_path.parent().unwrap().to_path_buf())
|
||||
}
|
||||
|
||||
fn llama3_chat_prompt(user_prompt: &str) -> String {
|
||||
format!(
|
||||
"<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n{user_prompt}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n"
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
struct StepProfile {
|
||||
total: Duration,
|
||||
execute: Duration,
|
||||
get_logits: Duration,
|
||||
cache_roundtrip: Duration,
|
||||
}
|
||||
|
||||
fn avg_ms(duration: Duration, n: usize) -> f64 {
|
||||
if n == 0 {
|
||||
0.0
|
||||
} else {
|
||||
duration.as_secs_f64() * 1e3 / n as f64
|
||||
}
|
||||
}
|
||||
|
||||
fn sample_greedy(logits_row: &[f32], seen: &FxHashSet<u32>, repetition_penalty: f32) -> u32 {
|
||||
let mut row = logits_row.to_vec();
|
||||
for &tok in seen {
|
||||
let logit = &mut row[tok as usize];
|
||||
if *logit > 0.0 {
|
||||
*logit /= repetition_penalty;
|
||||
} else {
|
||||
*logit *= repetition_penalty;
|
||||
}
|
||||
}
|
||||
row.iter()
|
||||
.enumerate()
|
||||
.max_by(|(_, a), (_, b)| a.total_cmp(b))
|
||||
.unwrap()
|
||||
.0 as u32
|
||||
}
|
||||
|
||||
fn causal_mask(q_pos: &[usize], context_len: usize) -> Vec<f32> {
|
||||
let mut mask = vec![-1e10f32; q_pos.len() * context_len];
|
||||
for (qi, &pos) in q_pos.iter().enumerate() {
|
||||
for ci in 0..context_len {
|
||||
if ci <= pos {
|
||||
mask[qi * context_len + ci] = 0.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
mask
|
||||
}
|
||||
|
||||
struct KVCache {
|
||||
k_caches: Vec<GraphTensor>,
|
||||
v_caches: Vec<GraphTensor>,
|
||||
}
|
||||
|
||||
impl KVCache {
|
||||
fn new(cx: &mut Graph, num_slots: usize) -> Self {
|
||||
let mut k_caches = Vec::with_capacity(LAYERS);
|
||||
let mut v_caches = Vec::with_capacity(LAYERS);
|
||||
for l in 0..LAYERS {
|
||||
k_caches.push(
|
||||
cx.named_tensor(format!("kv_cache.{l}.k"), (num_slots, KV_DIM))
|
||||
.persist(),
|
||||
);
|
||||
v_caches.push(
|
||||
cx.named_tensor(format!("kv_cache.{l}.v"), (num_slots, KV_DIM))
|
||||
.persist(),
|
||||
);
|
||||
}
|
||||
Self { k_caches, v_caches }
|
||||
}
|
||||
}
|
||||
|
||||
struct Llama {
|
||||
embedding: GraphTensor,
|
||||
layers: Vec<LlamaLayer>,
|
||||
lm_norm: LayerNorm,
|
||||
}
|
||||
|
||||
impl Llama {
|
||||
fn init(cx: &mut Graph) -> Self {
|
||||
let mut layers = Vec::with_capacity(LAYERS);
|
||||
for l in 0..LAYERS {
|
||||
layers.push(LlamaLayer {
|
||||
up: cx
|
||||
.named_tensor(
|
||||
format!("model.layers.{l}.mlp.up_proj.weight"),
|
||||
(INTERMEDIATE, HIDDEN),
|
||||
)
|
||||
.persist(),
|
||||
gate: cx
|
||||
.named_tensor(
|
||||
format!("model.layers.{l}.mlp.gate_proj.weight"),
|
||||
(INTERMEDIATE, HIDDEN),
|
||||
)
|
||||
.persist(),
|
||||
down: cx
|
||||
.named_tensor(
|
||||
format!("model.layers.{l}.mlp.down_proj.weight"),
|
||||
(HIDDEN, INTERMEDIATE),
|
||||
)
|
||||
.persist(),
|
||||
q_proj: cx
|
||||
.named_tensor(
|
||||
format!("model.layers.{l}.self_attn.q_proj.weight"),
|
||||
(HIDDEN, HIDDEN),
|
||||
)
|
||||
.persist(),
|
||||
k_proj: cx
|
||||
.named_tensor(
|
||||
format!("model.layers.{l}.self_attn.k_proj.weight"),
|
||||
(KV_DIM, HIDDEN),
|
||||
)
|
||||
.persist(),
|
||||
v_proj: cx
|
||||
.named_tensor(
|
||||
format!("model.layers.{l}.self_attn.v_proj.weight"),
|
||||
(KV_DIM, HIDDEN),
|
||||
)
|
||||
.persist(),
|
||||
o_proj: cx
|
||||
.named_tensor(
|
||||
format!("model.layers.{l}.self_attn.o_proj.weight"),
|
||||
(HIDDEN, HIDDEN),
|
||||
)
|
||||
.persist(),
|
||||
attn_rms: LayerNorm::new(
|
||||
HIDDEN,
|
||||
Some(&format!("model.layers.{l}.input_layernorm.weight")),
|
||||
None,
|
||||
false,
|
||||
RMS_NORM_EPS,
|
||||
cx,
|
||||
),
|
||||
mlp_rms: LayerNorm::new(
|
||||
HIDDEN,
|
||||
Some(&format!("model.layers.{l}.post_attention_layernorm.weight")),
|
||||
None,
|
||||
false,
|
||||
RMS_NORM_EPS,
|
||||
cx,
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
Self {
|
||||
embedding: cx
|
||||
.named_tensor("model.embed_tokens.weight", (VOCAB_SIZE, HIDDEN))
|
||||
.persist(),
|
||||
layers,
|
||||
lm_norm: LayerNorm::new(
|
||||
HIDDEN,
|
||||
Some("model.norm.weight"),
|
||||
None,
|
||||
false,
|
||||
RMS_NORM_EPS,
|
||||
cx,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn forward(
|
||||
&self,
|
||||
input: GraphTensor,
|
||||
q_pos: GraphTensor,
|
||||
scatter_idx: GraphTensor,
|
||||
gather_idx: GraphTensor,
|
||||
attn_mask: GraphTensor,
|
||||
kv_cache: &KVCache,
|
||||
) -> (GraphTensor, Vec<(GraphTensor, GraphTensor)>) {
|
||||
let seq = input.dims1();
|
||||
let mut x = self.embedding.gather(
|
||||
(input * HIDDEN).expand_dim(1, HIDDEN)
|
||||
+ input.graph().arange(HIDDEN).expand_dim(0, seq),
|
||||
);
|
||||
let mut cache_outputs = Vec::with_capacity(LAYERS);
|
||||
for (i, layer) in self.layers.iter().enumerate() {
|
||||
let (x_new, k_out, v_out) = layer.forward(
|
||||
x,
|
||||
q_pos,
|
||||
scatter_idx,
|
||||
gather_idx,
|
||||
attn_mask,
|
||||
kv_cache.k_caches[i],
|
||||
kv_cache.v_caches[i],
|
||||
);
|
||||
x = x_new;
|
||||
cache_outputs.push((k_out, v_out));
|
||||
}
|
||||
|
||||
let logits = self.lm_norm.forward(x).matmul(self.embedding.t());
|
||||
(logits, cache_outputs)
|
||||
}
|
||||
}
|
||||
|
||||
struct LlamaLayer {
|
||||
up: GraphTensor,
|
||||
gate: GraphTensor,
|
||||
down: GraphTensor,
|
||||
q_proj: GraphTensor,
|
||||
k_proj: GraphTensor,
|
||||
v_proj: GraphTensor,
|
||||
o_proj: GraphTensor,
|
||||
attn_rms: LayerNorm,
|
||||
mlp_rms: LayerNorm,
|
||||
}
|
||||
|
||||
fn llama_rotary_embeddings(mut input: GraphTensor, pos_ids: GraphTensor) -> GraphTensor {
|
||||
input = input.split_dims(1, HEAD_DIM).transpose(0, 1);
|
||||
|
||||
let freqs = input
|
||||
.graph()
|
||||
.arange_options(0, HEAD_DIM, 2)
|
||||
.cast(DType::F32)
|
||||
/ HEAD_DIM as f32;
|
||||
let inv_freqs = ROPE_THETA.pow(freqs).reciprocal();
|
||||
let emb = pos_ids
|
||||
.cast(DType::F32)
|
||||
.expand_dim(1, 1)
|
||||
.matmul(inv_freqs.expand_dim(0, 1));
|
||||
|
||||
let x0 = input.slice((.., .., ..HEAD_DIM / 2));
|
||||
let x1 = input.slice((.., .., HEAD_DIM / 2..));
|
||||
|
||||
let cos = emb.cos().expand_dim(0, x0.dims()[0]);
|
||||
let sin = emb.sin().expand_dim(0, x0.dims()[0]);
|
||||
let x0_out = x0 * cos - x1 * sin;
|
||||
let x1_out = x1 * cos + x0 * sin;
|
||||
|
||||
x0_out
|
||||
.concat_along(x1_out, 2)
|
||||
.transpose(0, 1)
|
||||
.merge_dims(1, 2)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn attention(
|
||||
q_rope: GraphTensor,
|
||||
k_rope: GraphTensor,
|
||||
v: GraphTensor,
|
||||
k_cache: GraphTensor,
|
||||
v_cache: GraphTensor,
|
||||
scatter_idx: GraphTensor,
|
||||
gather_idx: GraphTensor,
|
||||
attn_mask: GraphTensor,
|
||||
) -> (GraphTensor, GraphTensor, GraphTensor) {
|
||||
let k_cache_out = scatter_rows(k_rope, scatter_idx, k_cache, KV_DIM);
|
||||
let v_cache_out = scatter_rows(v, scatter_idx, v_cache, KV_DIM);
|
||||
|
||||
let k = gather_rows(k_cache_out, gather_idx, KV_DIM);
|
||||
let v_ctx = gather_rows(v_cache_out, gather_idx, KV_DIM);
|
||||
|
||||
let q = (q_rope * 1.0).split_dims(1, HEAD_DIM).transpose(0, 1);
|
||||
let k = k.split_dims(1, HEAD_DIM).permute((1, 2, 0));
|
||||
let v_ctx = v_ctx.split_dims(1, HEAD_DIM).transpose(0, 1);
|
||||
|
||||
let k = k.expand_dim(1, KV_GROUPS).merge_dims(0, 1) * 1.0;
|
||||
let v_ctx = v_ctx.expand_dim(1, KV_GROUPS).merge_dims(0, 1) * 1.0;
|
||||
|
||||
let scores = q.matmul(k) / (HEAD_DIM as f32).sqrt();
|
||||
let masked_scores = scores + attn_mask.expand_dim(0, N_HEADS);
|
||||
let weights = masked_scores.softmax(2);
|
||||
let out = weights.matmul(v_ctx);
|
||||
let attn_out = out.transpose(0, 1).merge_dims(1, 2);
|
||||
|
||||
(attn_out, k_cache_out, v_cache_out)
|
||||
}
|
||||
|
||||
impl LlamaLayer {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn forward(
|
||||
&self,
|
||||
mut x: GraphTensor,
|
||||
q_pos: GraphTensor,
|
||||
scatter_idx: GraphTensor,
|
||||
gather_idx: GraphTensor,
|
||||
attn_mask: GraphTensor,
|
||||
k_cache: GraphTensor,
|
||||
v_cache: GraphTensor,
|
||||
) -> (GraphTensor, GraphTensor, GraphTensor) {
|
||||
let x_attn = self.attn_rms.forward(x);
|
||||
let q = x_attn.matmul(self.q_proj.t());
|
||||
let k = x_attn.matmul(self.k_proj.t());
|
||||
let v = x_attn.matmul(self.v_proj.t());
|
||||
|
||||
let q_rope = llama_rotary_embeddings(q, q_pos);
|
||||
let k_rope = llama_rotary_embeddings(k, q_pos);
|
||||
let (attn_out, k_cache_out, v_cache_out) = attention(
|
||||
q_rope,
|
||||
k_rope,
|
||||
v,
|
||||
k_cache,
|
||||
v_cache,
|
||||
scatter_idx,
|
||||
gather_idx,
|
||||
attn_mask,
|
||||
);
|
||||
x += attn_out.matmul(self.o_proj.t());
|
||||
|
||||
let x_mlp = self.mlp_rms.forward(x);
|
||||
let mlp_out =
|
||||
(x_mlp.matmul(self.gate.t()).swish() * x_mlp.matmul(self.up.t())).matmul(self.down.t());
|
||||
(x + mlp_out, k_cache_out, v_cache_out)
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn run_model_step(
|
||||
cx: &mut Graph,
|
||||
runtime: &mut MetalRuntime,
|
||||
input: GraphTensor,
|
||||
q_pos_t: GraphTensor,
|
||||
scatter_idx_t: GraphTensor,
|
||||
gather_idx_t: GraphTensor,
|
||||
attn_mask_t: GraphTensor,
|
||||
logits: GraphTensor,
|
||||
kv_cache: &KVCache,
|
||||
cache_outputs: &[(GraphTensor, GraphTensor)],
|
||||
tokens: &[u32],
|
||||
q_pos: &[i32],
|
||||
scatter_idx: &[i32],
|
||||
gather_idx: &[i32],
|
||||
attn_mask: &[f32],
|
||||
) -> (Vec<f32>, StepProfile) {
|
||||
let start = Instant::now();
|
||||
cx.set_dim('s', tokens.len());
|
||||
cx.set_dim('c', gather_idx.len());
|
||||
|
||||
runtime.set_data(input, tokens.iter().map(|t| *t as i32).collect::<Vec<_>>());
|
||||
runtime.set_data(q_pos_t, q_pos.to_vec());
|
||||
runtime.set_data(scatter_idx_t, scatter_idx.to_vec());
|
||||
runtime.set_data(gather_idx_t, gather_idx.to_vec());
|
||||
runtime.set_data(attn_mask_t, attn_mask.to_vec());
|
||||
runtime.allocate_intermediate_buffers(&cx.dyn_map);
|
||||
|
||||
let execute_start = Instant::now();
|
||||
runtime.execute(&cx.dyn_map);
|
||||
let execute = execute_start.elapsed();
|
||||
|
||||
let logits_start = Instant::now();
|
||||
let logits_data = runtime.get_f32(logits);
|
||||
let get_logits = logits_start.elapsed();
|
||||
|
||||
let cache_start = Instant::now();
|
||||
for (layer_idx, (k_out, v_out)) in cache_outputs.iter().enumerate() {
|
||||
let k_buf = runtime.remove_buffer(*k_out);
|
||||
let v_buf = runtime.remove_buffer(*v_out);
|
||||
runtime.set_buffer(kv_cache.k_caches[layer_idx], k_buf);
|
||||
runtime.set_buffer(kv_cache.v_caches[layer_idx], v_buf);
|
||||
}
|
||||
let cache_roundtrip = cache_start.elapsed();
|
||||
|
||||
(
|
||||
logits_data,
|
||||
StepProfile {
|
||||
total: start.elapsed(),
|
||||
execute,
|
||||
get_logits,
|
||||
cache_roundtrip,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let _ = tracing_subscriber::registry()
|
||||
.with(tracing_subscriber::fmt::layer())
|
||||
.with(luminal_filter())
|
||||
.try_init();
|
||||
|
||||
let model_dir = prepare_hf_model()?;
|
||||
println!("Using model directory: {}", model_dir.display());
|
||||
|
||||
let tokenizer = Tokenizer::from_file(model_dir.join("tokenizer.json"))
|
||||
.map_err(|err| err as Box<dyn Error>)?;
|
||||
let prompt_tokens = tokenizer
|
||||
.encode(llama3_chat_prompt(PROMPT), false)
|
||||
.map_err(|err| err as Box<dyn Error>)?
|
||||
.get_ids()
|
||||
.to_vec();
|
||||
|
||||
let mut cx = Graph::default();
|
||||
let input = cx.named_tensor("input", 's').as_dtype(DType::Int);
|
||||
let q_pos_t = cx.named_tensor("q_pos", 's').as_dtype(DType::Int);
|
||||
let scatter_idx_t = cx.named_tensor("scatter_idx", 's').as_dtype(DType::Int);
|
||||
let gather_idx_t = cx.named_tensor("gather_idx", 'c').as_dtype(DType::Int);
|
||||
let attn_mask_t = cx.named_tensor("attn_mask", ('s', 'c'));
|
||||
let kv_cache = KVCache::new(&mut cx, MAX_SEQ_LEN);
|
||||
let (logits, cache_outputs) = Llama::init(&mut cx).forward(
|
||||
input,
|
||||
q_pos_t,
|
||||
scatter_idx_t,
|
||||
gather_idx_t,
|
||||
attn_mask_t,
|
||||
&kv_cache,
|
||||
);
|
||||
let logits = logits.output();
|
||||
for (k_out, v_out) in &cache_outputs {
|
||||
k_out.output();
|
||||
v_out.output();
|
||||
}
|
||||
|
||||
cx.set_dim('s', 1);
|
||||
cx.set_dim('c', 1);
|
||||
let max_prefill = (prompt_tokens.len() + 16)
|
||||
.next_power_of_two()
|
||||
.min(MAX_SEQ_LEN);
|
||||
let max_context = (prompt_tokens.len() + GEN_TOKENS + 1)
|
||||
.next_power_of_two()
|
||||
.min(MAX_SEQ_LEN);
|
||||
let search_s = 16.min(max_prefill).max(2);
|
||||
let search_c = 16.min(max_context).max(2);
|
||||
let build_options = CompileOptions::default()
|
||||
.max_memory_mib(SEARCH_MEMORY_MIB)
|
||||
.dim_buckets(
|
||||
's',
|
||||
&[
|
||||
DimBucket::new(1, 1),
|
||||
DimBucket::new(2, max_prefill).representative(search_s),
|
||||
],
|
||||
)
|
||||
.dim_buckets(
|
||||
'c',
|
||||
&[
|
||||
DimBucket::new(1, 1),
|
||||
DimBucket::new(2, max_context).representative(search_c),
|
||||
],
|
||||
);
|
||||
|
||||
println!("Building E-Graph...");
|
||||
let egraph_start = Instant::now();
|
||||
cx.build_search_space::<MetalRuntime>(build_options);
|
||||
println!(
|
||||
" E-Graph build: {:.2} s",
|
||||
egraph_start.elapsed().as_secs_f64()
|
||||
);
|
||||
|
||||
println!("Loading weights...");
|
||||
let load_start = Instant::now();
|
||||
let mut runtime = MetalRuntime::initialize(());
|
||||
runtime.load_safetensors(&cx, model_dir.join("model.safetensors").to_str().unwrap());
|
||||
println!(" Weight load: {:.2} s", load_start.elapsed().as_secs_f64());
|
||||
|
||||
let cache_bytes = MAX_SEQ_LEN * KV_DIM * std::mem::size_of::<f32>();
|
||||
for i in 0..LAYERS {
|
||||
runtime.set_zeros(kv_cache.k_caches[i], cache_bytes);
|
||||
runtime.set_zeros(kv_cache.v_caches[i], cache_bytes);
|
||||
}
|
||||
|
||||
println!("Compiling...");
|
||||
let compile_start = Instant::now();
|
||||
cx.set_dim('s', search_s);
|
||||
cx.set_dim('c', search_c);
|
||||
runtime.set_data(input, vec![1; search_s]);
|
||||
runtime.set_data(q_pos_t, (0..search_s as i32).collect::<Vec<_>>());
|
||||
runtime.set_data(scatter_idx_t, (0..search_s as i32).collect::<Vec<_>>());
|
||||
runtime.set_data(gather_idx_t, (0..search_c as i32).collect::<Vec<_>>());
|
||||
runtime.set_data(attn_mask_t, vec![0.0f32; search_s * search_c]);
|
||||
runtime = cx.search(runtime, CompileOptions::new(SEARCH_GRAPHS));
|
||||
println!(
|
||||
" Search/compile: {:.2} s",
|
||||
compile_start.elapsed().as_secs_f64()
|
||||
);
|
||||
|
||||
for i in 0..LAYERS {
|
||||
runtime.set_zeros(kv_cache.k_caches[i], cache_bytes);
|
||||
runtime.set_zeros(kv_cache.v_caches[i], cache_bytes);
|
||||
}
|
||||
|
||||
let prompt_len = prompt_tokens.len();
|
||||
let mut context_len = 0usize;
|
||||
let mut profiles = Vec::new();
|
||||
let mut seen_tokens = FxHashSet::default();
|
||||
let repetition_penalty = 1.05;
|
||||
|
||||
println!(
|
||||
"Prompt: {} tokens, generating up to {} tokens",
|
||||
prompt_len, GEN_TOKENS
|
||||
);
|
||||
|
||||
let mut generated = 0usize;
|
||||
let mut next_token = None;
|
||||
if GEN_TOKENS > 0 && prompt_len > 0 {
|
||||
let positions: Vec<usize> = (0..prompt_len).collect();
|
||||
let q_pos: Vec<i32> = positions.iter().map(|&p| p as i32).collect();
|
||||
let mask = causal_mask(&positions, prompt_len);
|
||||
let (logits_data, profile) = run_model_step(
|
||||
&mut cx,
|
||||
&mut runtime,
|
||||
input,
|
||||
q_pos_t,
|
||||
scatter_idx_t,
|
||||
gather_idx_t,
|
||||
attn_mask_t,
|
||||
logits,
|
||||
&kv_cache,
|
||||
&cache_outputs,
|
||||
&prompt_tokens,
|
||||
&q_pos,
|
||||
&q_pos,
|
||||
&q_pos,
|
||||
&mask,
|
||||
);
|
||||
context_len = prompt_len;
|
||||
|
||||
let token = sample_greedy(
|
||||
&logits_data[logits_data.len() - VOCAB_SIZE..],
|
||||
&seen_tokens,
|
||||
repetition_penalty,
|
||||
);
|
||||
seen_tokens.insert(token);
|
||||
next_token = Some(token);
|
||||
generated = 1;
|
||||
profiles.push(profile);
|
||||
|
||||
if token != EOS_TOKEN && token != STOP_TOKEN {
|
||||
print!(
|
||||
"{}",
|
||||
tokenizer
|
||||
.decode(&[token], true)
|
||||
.map_err(|err| err as Box<dyn Error>)?
|
||||
);
|
||||
std::io::stdout().flush()?;
|
||||
}
|
||||
}
|
||||
|
||||
while generated < GEN_TOKENS {
|
||||
let current_token = match next_token {
|
||||
Some(token) if token != EOS_TOKEN && token != STOP_TOKEN => token,
|
||||
_ => break,
|
||||
};
|
||||
let gather_idx = (0..=context_len as i32).collect::<Vec<_>>();
|
||||
let mask = causal_mask(&[context_len], context_len + 1);
|
||||
let (logits_data, profile) = run_model_step(
|
||||
&mut cx,
|
||||
&mut runtime,
|
||||
input,
|
||||
q_pos_t,
|
||||
scatter_idx_t,
|
||||
gather_idx_t,
|
||||
attn_mask_t,
|
||||
logits,
|
||||
&kv_cache,
|
||||
&cache_outputs,
|
||||
&[current_token],
|
||||
&[context_len as i32],
|
||||
&[context_len as i32],
|
||||
&gather_idx,
|
||||
&mask,
|
||||
);
|
||||
context_len += 1;
|
||||
|
||||
let token = sample_greedy(
|
||||
&logits_data[logits_data.len() - VOCAB_SIZE..],
|
||||
&seen_tokens,
|
||||
repetition_penalty,
|
||||
);
|
||||
seen_tokens.insert(token);
|
||||
next_token = Some(token);
|
||||
generated += 1;
|
||||
profiles.push(profile);
|
||||
|
||||
if token == EOS_TOKEN || token == STOP_TOKEN {
|
||||
break;
|
||||
}
|
||||
print!(
|
||||
"{}",
|
||||
tokenizer
|
||||
.decode(&[token], true)
|
||||
.map_err(|err| err as Box<dyn Error>)?
|
||||
);
|
||||
std::io::stdout().flush()?;
|
||||
}
|
||||
println!();
|
||||
|
||||
let ttft = profiles.first().map(|p| p.total).unwrap_or_default();
|
||||
let decode_steps = profiles.len().saturating_sub(1);
|
||||
let decode_total: Duration = profiles.iter().skip(1).map(|p| p.total).sum();
|
||||
println!(" TTFT: {:.2} ms", ttft.as_secs_f64() * 1e3);
|
||||
println!(" TPOT: {:.2} ms", avg_ms(decode_total, decode_steps));
|
||||
|
||||
let execute_total: Duration = profiles.iter().map(|p| p.execute).sum();
|
||||
let logits_total: Duration = profiles.iter().map(|p| p.get_logits).sum();
|
||||
let cache_total: Duration = profiles.iter().map(|p| p.cache_roundtrip).sum();
|
||||
println!(
|
||||
" Profile: n={}, exec={:.2} ms, logits={:.2} ms, cache={:.2} ms",
|
||||
profiles.len(),
|
||||
avg_ms(execute_total, profiles.len()),
|
||||
avg_ms(logits_total, profiles.len()),
|
||||
avg_ms(cache_total, profiles.len()),
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
//! [`DynBackend`] implementation for the Metal runtime.
|
||||
|
||||
use luminal::dtype::DType;
|
||||
use luminal::dyn_backend::{bytes_to_native_data, compile_backend, BackendCompileArgs, DynBackend};
|
||||
use luminal::dyn_backend::{BackendCompileArgs, DynBackend, bytes_to_native_data, compile_backend};
|
||||
use luminal::prelude::*;
|
||||
|
||||
use crate::runtime::MetalRuntime;
|
||||
@@ -31,10 +31,42 @@ impl DynBackend for MetalDynBackend {
|
||||
}
|
||||
}
|
||||
|
||||
/// Reject dtypes the Metal kernel emitters don't support.
|
||||
///
|
||||
/// Metal codegen has no native 64-bit integer or 64-bit float paths.
|
||||
/// Reaching the kernel emitter with one of these dtypes used to panic deep
|
||||
/// in MSL generation with an unhelpful error; surfacing a clean message
|
||||
/// at translate-time lets the user fall back to CPU or pick a narrower
|
||||
/// dtype before any Metal compilation runs.
|
||||
fn reject_unsupported_dtype(graph: &Graph) -> Result<(), String> {
|
||||
for node_id in graph.graph.node_indices() {
|
||||
if let Some(input) = (*graph.graph[node_id])
|
||||
.as_any()
|
||||
.downcast_ref::<luminal::hlir::Input>()
|
||||
{
|
||||
match input.dtype {
|
||||
DType::I64 | DType::F64 => {
|
||||
return Err(format!(
|
||||
"Metal backend does not support {:?} (input `{}`). \
|
||||
Metal codegen has no native 64-bit kernels; either \
|
||||
narrow the dtype (e.g. `.to(torch.int32)` / \
|
||||
`.to(torch.float32)`) before the boundary or \
|
||||
compile with the CPU / CUDA backend.",
|
||||
input.dtype, input.label
|
||||
));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn metal_factory(
|
||||
graph: &mut Graph,
|
||||
args: BackendCompileArgs,
|
||||
) -> Result<Box<dyn DynBackend>, String> {
|
||||
reject_unsupported_dtype(graph)?;
|
||||
compile_backend::<MetalRuntime>(
|
||||
graph,
|
||||
args,
|
||||
|
||||
@@ -1,227 +1,5 @@
|
||||
use super::{MetalMulInfo, MetalSumReduceInfo};
|
||||
use luminal::prelude::*;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum MetalMatmulFamily {
|
||||
#[default]
|
||||
Naive,
|
||||
RegularTiled,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MatmulDescriptor {
|
||||
pub m: Expression,
|
||||
pub n: Expression,
|
||||
pub k: Expression,
|
||||
pub batch_shape: Vec<Expression>,
|
||||
pub lhs_strides: Vec<Expression>,
|
||||
pub rhs_strides: Vec<Expression>,
|
||||
pub out_strides: Vec<Expression>,
|
||||
pub transpose_lhs: bool,
|
||||
pub transpose_rhs: bool,
|
||||
}
|
||||
|
||||
impl MatmulDescriptor {
|
||||
pub fn from_mul_and_sum(
|
||||
mul_info: &MetalMulInfo,
|
||||
sum_info: &MetalSumReduceInfo,
|
||||
) -> Option<Self> {
|
||||
let zero = Expression::from(0);
|
||||
let z = Expression::from('z');
|
||||
|
||||
let is_simple_2d_matmul = mul_info.shape.len() == 3
|
||||
&& sum_info.shape.len() == 2
|
||||
&& mul_info.a_strides.len() == 3
|
||||
&& mul_info.b_strides.len() == 3
|
||||
&& sum_info.strides.len() == 2
|
||||
&& mul_info.shape[0] == sum_info.shape[0]
|
||||
&& mul_info.shape[1] == sum_info.shape[1]
|
||||
&& mul_info.shape[2] == sum_info.iters
|
||||
&& mul_info.a_strides[1] == zero
|
||||
&& mul_info.a_strides[2] == z
|
||||
&& mul_info.b_strides[0] == zero
|
||||
&& mul_info.b_strides[1] == z
|
||||
&& sum_info.strides[1] == z
|
||||
&& sum_info.iter_stride == z;
|
||||
|
||||
if !is_simple_2d_matmul {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(Self {
|
||||
m: sum_info.shape[0],
|
||||
n: sum_info.shape[1],
|
||||
k: sum_info.iters,
|
||||
batch_shape: Vec::new(),
|
||||
lhs_strides: mul_info.a_strides.clone(),
|
||||
rhs_strides: mul_info.b_strides.clone(),
|
||||
out_strides: sum_info.strides.clone(),
|
||||
transpose_lhs: false,
|
||||
transpose_rhs: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MatmulPlan {
|
||||
pub family: MetalMatmulFamily,
|
||||
pub m: Expression,
|
||||
pub n: Expression,
|
||||
pub k: Expression,
|
||||
pub lda: Expression,
|
||||
pub ldb: Expression,
|
||||
pub ldd: Expression,
|
||||
pub batch_size: u32,
|
||||
pub batch_stride_a: u32,
|
||||
pub batch_stride_b: u32,
|
||||
pub batch_stride_d: u32,
|
||||
pub bm: u16,
|
||||
pub bn: u16,
|
||||
pub bk: u16,
|
||||
pub wm: u16,
|
||||
pub wn: u16,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy)]
|
||||
pub struct MetalMatmulPlanner;
|
||||
|
||||
impl MetalMatmulPlanner {
|
||||
pub fn plan(&self, desc: &MatmulDescriptor) -> MatmulPlan {
|
||||
let family = if desc.batch_shape.is_empty()
|
||||
&& desc.m.as_num().is_some_and(|m| m >= 32)
|
||||
&& desc.n.as_num().is_some_and(|n| n >= 32)
|
||||
&& desc.k.as_num().is_some_and(|k| k >= 32)
|
||||
{
|
||||
MetalMatmulFamily::RegularTiled
|
||||
} else {
|
||||
MetalMatmulFamily::Naive
|
||||
};
|
||||
MatmulPlan {
|
||||
family,
|
||||
m: desc.m,
|
||||
n: desc.n,
|
||||
k: desc.k,
|
||||
lda: desc.lhs_strides[0],
|
||||
ldb: desc.rhs_strides[2],
|
||||
ldd: desc.out_strides[0],
|
||||
batch_size: 1,
|
||||
batch_stride_a: 0,
|
||||
batch_stride_b: 0,
|
||||
batch_stride_d: 0,
|
||||
bm: 16,
|
||||
bn: 16,
|
||||
bk: 8,
|
||||
wm: 2,
|
||||
wn: 2,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn descriptor_recovers_simple_2d_matmul() {
|
||||
let mul = MetalMulInfo {
|
||||
shape: vec![
|
||||
Expression::from(4),
|
||||
Expression::from(8),
|
||||
Expression::from(16),
|
||||
],
|
||||
a_strides: vec![
|
||||
Expression::from('z') * 16,
|
||||
Expression::from(0),
|
||||
Expression::from('z'),
|
||||
],
|
||||
b_strides: vec![
|
||||
Expression::from(0),
|
||||
Expression::from('z'),
|
||||
Expression::from('z') * 8,
|
||||
],
|
||||
output_strides: vec![
|
||||
Expression::from('z') * 16,
|
||||
Expression::from('z') * 8,
|
||||
Expression::from('z'),
|
||||
],
|
||||
};
|
||||
let sum = MetalSumReduceInfo {
|
||||
shape: vec![Expression::from(4), Expression::from(8)],
|
||||
strides: vec![Expression::from('z') * 8, Expression::from('z')],
|
||||
iters: Expression::from(16),
|
||||
iter_stride: Expression::from('z'),
|
||||
};
|
||||
|
||||
let desc = MatmulDescriptor::from_mul_and_sum(&mul, &sum).unwrap();
|
||||
assert_eq!(desc.m, Expression::from(4));
|
||||
assert_eq!(desc.n, Expression::from(8));
|
||||
assert_eq!(desc.k, Expression::from(16));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn planner_keeps_small_problems_on_naive_path() {
|
||||
let desc = MatmulDescriptor {
|
||||
m: Expression::from(4),
|
||||
n: Expression::from(8),
|
||||
k: Expression::from(16),
|
||||
batch_shape: Vec::new(),
|
||||
lhs_strides: vec![
|
||||
Expression::from('z') * 16,
|
||||
Expression::from(0),
|
||||
Expression::from('z'),
|
||||
],
|
||||
rhs_strides: vec![
|
||||
Expression::from(0),
|
||||
Expression::from('z'),
|
||||
Expression::from('z') * 8,
|
||||
],
|
||||
out_strides: vec![Expression::from('z') * 8, Expression::from('z')],
|
||||
transpose_lhs: false,
|
||||
transpose_rhs: false,
|
||||
};
|
||||
|
||||
let planner = MetalMatmulPlanner;
|
||||
let plan = planner.plan(&desc);
|
||||
assert_eq!(plan.family, MetalMatmulFamily::Naive);
|
||||
assert_eq!(plan.bm, 16);
|
||||
assert_eq!(plan.bn, 16);
|
||||
assert_eq!(plan.bk, 8);
|
||||
assert_eq!(plan.wm, 2);
|
||||
assert_eq!(plan.wn, 2);
|
||||
assert_eq!(plan.lda, Expression::from('z') * 16);
|
||||
assert_eq!(plan.ldb, Expression::from('z') * 8);
|
||||
assert_eq!(plan.ldd, Expression::from('z') * 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn planner_promotes_large_problems_to_regular_tiled() {
|
||||
let desc = MatmulDescriptor {
|
||||
m: Expression::from(64),
|
||||
n: Expression::from(64),
|
||||
k: Expression::from(64),
|
||||
batch_shape: Vec::new(),
|
||||
lhs_strides: vec![
|
||||
Expression::from('z') * 64,
|
||||
Expression::from(0),
|
||||
Expression::from('z'),
|
||||
],
|
||||
rhs_strides: vec![
|
||||
Expression::from(0),
|
||||
Expression::from('z'),
|
||||
Expression::from('z') * 64,
|
||||
],
|
||||
out_strides: vec![Expression::from('z') * 64, Expression::from('z')],
|
||||
transpose_lhs: false,
|
||||
transpose_rhs: false,
|
||||
};
|
||||
|
||||
let planner = MetalMatmulPlanner;
|
||||
let plan = planner.plan(&desc);
|
||||
assert_eq!(plan.family, MetalMatmulFamily::RegularTiled);
|
||||
assert_eq!(plan.bm, 16);
|
||||
assert_eq!(plan.bn, 16);
|
||||
assert_eq!(plan.bk, 8);
|
||||
assert_eq!(plan.wm, 2);
|
||||
assert_eq!(plan.wn, 2);
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum MPSMatrixLayout {
|
||||
RowMajor,
|
||||
TransposedRowMajor,
|
||||
}
|
||||
|
||||
@@ -6,10 +6,127 @@ pub use ops::*;
|
||||
use luminal::dtype::DType;
|
||||
use luminal::op::EgglogOp;
|
||||
use luminal::prelude::*;
|
||||
use metal::{Buffer, ComputeCommandEncoderRef, ComputePipelineState, Device};
|
||||
use metal::{
|
||||
Buffer, CommandBufferRef, ComputeCommandEncoderRef, ComputePipelineState, Device,
|
||||
foreign_types::ForeignTypeRef, mps,
|
||||
};
|
||||
use objc::rc::StrongPtr;
|
||||
use objc::runtime::Object;
|
||||
use objc::{class, msg_send, sel, sel_impl};
|
||||
use std::cell::RefCell;
|
||||
|
||||
pub const DYN_SLOT_COUNT: usize = 26;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
struct MpsMatrixDescriptorKey {
|
||||
rows: usize,
|
||||
cols: usize,
|
||||
row_bytes: u64,
|
||||
data_type: isize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
struct MpsMatmulKey {
|
||||
transpose_lhs: bool,
|
||||
transpose_rhs: bool,
|
||||
m: usize,
|
||||
n: usize,
|
||||
k: usize,
|
||||
alpha: u64,
|
||||
beta: u64,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct MpsKernelCache {
|
||||
matrix_descriptors: FxHashMap<MpsMatrixDescriptorKey, StrongPtr>,
|
||||
matmul_kernels: FxHashMap<MpsMatmulKey, StrongPtr>,
|
||||
}
|
||||
|
||||
impl MpsKernelCache {
|
||||
pub(crate) fn matrix_descriptor(
|
||||
&mut self,
|
||||
rows: usize,
|
||||
cols: usize,
|
||||
row_bytes: u64,
|
||||
dtype: DType,
|
||||
) -> *mut Object {
|
||||
let key = MpsMatrixDescriptorKey {
|
||||
rows,
|
||||
cols,
|
||||
row_bytes,
|
||||
data_type: Self::mps_data_type(dtype),
|
||||
};
|
||||
let descriptor = self
|
||||
.matrix_descriptors
|
||||
.entry(key)
|
||||
.or_insert_with(|| unsafe {
|
||||
let descriptor: *mut Object = msg_send![
|
||||
class!(MPSMatrixDescriptor),
|
||||
matrixDescriptorWithRows: rows
|
||||
columns: cols
|
||||
rowBytes: row_bytes as usize
|
||||
dataType: key.data_type
|
||||
];
|
||||
StrongPtr::retain(descriptor)
|
||||
});
|
||||
**descriptor
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn matrix_multiplication(
|
||||
&mut self,
|
||||
command_buffer: &CommandBufferRef,
|
||||
transpose_lhs: bool,
|
||||
transpose_rhs: bool,
|
||||
m: usize,
|
||||
n: usize,
|
||||
k: usize,
|
||||
alpha: f64,
|
||||
beta: f64,
|
||||
) -> *mut Object {
|
||||
let key = MpsMatmulKey {
|
||||
transpose_lhs,
|
||||
transpose_rhs,
|
||||
m,
|
||||
n,
|
||||
k,
|
||||
alpha: alpha.to_bits(),
|
||||
beta: beta.to_bits(),
|
||||
};
|
||||
let kernel = self.matmul_kernels.entry(key).or_insert_with(|| unsafe {
|
||||
let device: *mut Object = msg_send![command_buffer.as_ptr(), device];
|
||||
let kernel: *mut Object = msg_send![class!(MPSMatrixMultiplication), alloc];
|
||||
let kernel: *mut Object = msg_send![
|
||||
kernel,
|
||||
initWithDevice: device
|
||||
transposeLeft: transpose_lhs
|
||||
transposeRight: transpose_rhs
|
||||
resultRows: m
|
||||
resultColumns: n
|
||||
interiorColumns: k
|
||||
alpha: alpha
|
||||
beta: beta
|
||||
];
|
||||
StrongPtr::new(kernel)
|
||||
});
|
||||
**kernel
|
||||
}
|
||||
|
||||
fn mps_data_type(dtype: DType) -> isize {
|
||||
match dtype {
|
||||
DType::F32 | DType::TF32 => mps::MPSDataType::Float32 as isize,
|
||||
DType::F16 => mps::MPSDataType::Float16 as isize,
|
||||
unsupported => panic!("MPSMatmul does not support dtype {unsupported:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MetalEncodeContext<'a> {
|
||||
pub(crate) command_buffer: &'a CommandBufferRef,
|
||||
pub(crate) dyn_buffer: &'a Buffer,
|
||||
pub(crate) mps_cache: &'a RefCell<MpsKernelCache>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MetalMulInfo {
|
||||
pub shape: Vec<Expression>,
|
||||
@@ -32,7 +149,7 @@ pub trait MetalKernelOp: EgglogOp {
|
||||
device: &Device,
|
||||
input_dtypes: &[DType],
|
||||
output_dtype: DType,
|
||||
) -> ComputePipelineState;
|
||||
) -> Option<ComputePipelineState>;
|
||||
|
||||
fn infer_output_dtype(&self, input_dtypes: &[DType]) -> DType {
|
||||
input_dtypes.first().copied().unwrap_or(DType::F32)
|
||||
@@ -40,7 +157,7 @@ pub trait MetalKernelOp: EgglogOp {
|
||||
|
||||
fn output_size(&self) -> Expression;
|
||||
|
||||
fn encode(
|
||||
fn encode_compute(
|
||||
&self,
|
||||
encoder: &ComputeCommandEncoderRef,
|
||||
pipeline: &ComputePipelineState,
|
||||
@@ -49,6 +166,25 @@ pub trait MetalKernelOp: EgglogOp {
|
||||
dyn_map: &FxHashMap<char, usize>,
|
||||
);
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn encode(
|
||||
&self,
|
||||
context: &mut MetalEncodeContext<'_>,
|
||||
pipeline: Option<&ComputePipelineState>,
|
||||
inputs: &[&Buffer],
|
||||
output: &Buffer,
|
||||
dyn_map: &FxHashMap<char, usize>,
|
||||
_input_dtypes: &[DType],
|
||||
_output_dtype: DType,
|
||||
) {
|
||||
let pipeline = pipeline.expect("compute pipeline not compiled");
|
||||
let encoder = context.command_buffer.new_compute_command_encoder();
|
||||
let dyn_idx = inputs.len() as u64 + 1;
|
||||
encoder.set_buffer(dyn_idx, Some(context.dyn_buffer), 0);
|
||||
self.encode_compute(encoder, pipeline, inputs, output, dyn_map);
|
||||
encoder.end_encoding();
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// Performance Metrics for MBU/MFU Calculation
|
||||
// ========================================================================
|
||||
@@ -73,6 +209,10 @@ pub trait MetalKernelOp: EgglogOp {
|
||||
None
|
||||
}
|
||||
|
||||
fn output_aliases_input(&self) -> Option<usize> {
|
||||
None
|
||||
}
|
||||
|
||||
fn is_matmul(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,6 @@
|
||||
pub mod dyn_backend;
|
||||
pub mod kernel;
|
||||
mod memory_analysis;
|
||||
pub mod runtime;
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
1478
crates/luminal_metal/src/memory_analysis.rs
Normal file
1478
crates/luminal_metal/src/memory_analysis.rs
Normal file
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "luminal_nn"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
edition = "2024"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
|
||||
@@ -166,8 +166,8 @@ mod tests {
|
||||
let indices = cx.tensor(3).as_dtype(DType::Int);
|
||||
let result = gather_rows(data, indices, 3).output();
|
||||
|
||||
cx.build_search_space::<NativeRuntime>();
|
||||
let mut rt = cx.search(NativeRuntime::default(), 1);
|
||||
cx.build_search_space::<NativeRuntime>(CompileOptions::default());
|
||||
let mut rt = cx.search(NativeRuntime::default(), CompileOptions::new(1));
|
||||
|
||||
// data = [[1,2,3], [4,5,6], [7,8,9], [10,11,12]]
|
||||
rt.set_data(
|
||||
@@ -192,8 +192,8 @@ mod tests {
|
||||
let dest = cx.tensor((4, 3));
|
||||
let result = scatter_rows(src, indices, dest, 3).output();
|
||||
|
||||
cx.build_search_space::<NativeRuntime>();
|
||||
let mut rt = cx.search(NativeRuntime::default(), 1);
|
||||
cx.build_search_space::<NativeRuntime>(CompileOptions::default());
|
||||
let mut rt = cx.search(NativeRuntime::default(), CompileOptions::new(1));
|
||||
|
||||
rt.set_data(src.id, vec![10., 20., 30., 40., 50., 60.]);
|
||||
rt.set_data(indices.id, vec![1, 3]);
|
||||
@@ -218,8 +218,8 @@ mod tests {
|
||||
let updated_cache = scatter_rows(kv_new, scatter_idx, cache, 4);
|
||||
let gathered = gather_rows(updated_cache, gather_idx, 4).output();
|
||||
|
||||
cx.build_search_space::<NativeRuntime>();
|
||||
let mut rt = cx.search(NativeRuntime::default(), 1);
|
||||
cx.build_search_space::<NativeRuntime>(CompileOptions::default());
|
||||
let mut rt = cx.search(NativeRuntime::default(), CompileOptions::new(1));
|
||||
|
||||
rt.set_data(kv_new.id, vec![1., 2., 3., 4., 5., 6., 7., 8.]);
|
||||
rt.set_data(scatter_idx.id, vec![1, 4]); // Write to slots 1 and 4
|
||||
@@ -271,8 +271,8 @@ mod tests {
|
||||
let k_cache_new = k_cache_new.output();
|
||||
let v_cache_new = v_cache_new.output();
|
||||
|
||||
cx.build_search_space::<NativeRuntime>();
|
||||
let mut rt = cx.search(NativeRuntime::default(), 1);
|
||||
cx.build_search_space::<NativeRuntime>(CompileOptions::default());
|
||||
let mut rt = cx.search(NativeRuntime::default(), CompileOptions::new(1));
|
||||
|
||||
// Q = [1, 0, 1, 0] → head0=[1,0], head1=[1,0]
|
||||
rt.set_data(q.id, vec![1., 0., 1., 0.]);
|
||||
@@ -344,8 +344,8 @@ mod tests {
|
||||
);
|
||||
let attn_out = attn_out.output();
|
||||
|
||||
cx.build_search_space::<NativeRuntime>();
|
||||
let mut rt = cx.search(NativeRuntime::default(), 1);
|
||||
cx.build_search_space::<NativeRuntime>(CompileOptions::default());
|
||||
let mut rt = cx.search(NativeRuntime::default(), CompileOptions::new(1));
|
||||
|
||||
// Setup: 1 cached token at slot 0, 1 new token written to slot 1
|
||||
// K cached at slot 0: [1, 0]
|
||||
@@ -416,8 +416,8 @@ mod tests {
|
||||
);
|
||||
let attn_out = attn_out.output();
|
||||
|
||||
cx.build_search_space::<NativeRuntime>();
|
||||
let mut rt = cx.search(NativeRuntime::default(), 1);
|
||||
cx.build_search_space::<NativeRuntime>(CompileOptions::default());
|
||||
let mut rt = cx.search(NativeRuntime::default(), CompileOptions::new(1));
|
||||
|
||||
// Cache has 1 token at slot 0
|
||||
let mut k_cache_data = vec![0.; num_slots * kv_dim];
|
||||
|
||||
@@ -61,7 +61,8 @@ impl MoE {
|
||||
let expert_out = expanded_act.matmul(gathered).squeeze(n); // [batch.., k, out]
|
||||
|
||||
// 6. Weighted sum over experts: [batch.., k, out] * [batch.., k, 1] → sum(k) → [batch.., out]
|
||||
let weights_exp = top_k_values.unsqueeze(top_k_values.dims().len()); // [batch.., k, 1]
|
||||
let mut weights_exp = top_k_values.unsqueeze(top_k_values.dims().len()); // [batch.., k, 1]
|
||||
weights_exp.shape.expand(expert_out.dims());
|
||||
(expert_out * weights_exp).sum(n - 1)
|
||||
}
|
||||
}
|
||||
@@ -70,7 +71,7 @@ impl MoE {
|
||||
mod tests {
|
||||
use super::MoE;
|
||||
use luminal::prelude::*;
|
||||
use rand::{rng, Rng};
|
||||
use rand::{Rng, rng};
|
||||
|
||||
fn random_vec(n: usize) -> Vec<f32> {
|
||||
let mut r = rng();
|
||||
@@ -182,8 +183,8 @@ mod tests {
|
||||
};
|
||||
let output = moe.forward(input).output();
|
||||
|
||||
cx.build_search_space::<NativeRuntime>();
|
||||
let mut rt = cx.search(NativeRuntime::default(), 1);
|
||||
cx.build_search_space::<NativeRuntime>(CompileOptions::default());
|
||||
let mut rt = cx.search(NativeRuntime::default(), CompileOptions::new(1));
|
||||
|
||||
let input_data = vec![1.0, 2.0, 3.0];
|
||||
// Router strongly favors expert 0
|
||||
@@ -237,8 +238,8 @@ mod tests {
|
||||
};
|
||||
let output = moe.forward(input).output();
|
||||
|
||||
cx.build_search_space::<NativeRuntime>();
|
||||
let mut rt = cx.search(NativeRuntime::default(), 1);
|
||||
cx.build_search_space::<NativeRuntime>(CompileOptions::default());
|
||||
let mut rt = cx.search(NativeRuntime::default(), CompileOptions::new(1));
|
||||
|
||||
let input_data = vec![1.0, 1.0];
|
||||
// Nearly-equal routing to all experts (slight differences to avoid argsort ties)
|
||||
@@ -291,8 +292,8 @@ mod tests {
|
||||
};
|
||||
let output = moe.forward(input).output();
|
||||
|
||||
cx.build_search_space::<NativeRuntime>();
|
||||
let mut rt = cx.search(NativeRuntime::default(), 1);
|
||||
cx.build_search_space::<NativeRuntime>(CompileOptions::default());
|
||||
let mut rt = cx.search(NativeRuntime::default(), CompileOptions::new(1));
|
||||
|
||||
let input_data = vec![
|
||||
1.0, 0.0, 0.0, // batch 0: routes to expert via feature 0
|
||||
@@ -348,8 +349,8 @@ mod tests {
|
||||
};
|
||||
let output = moe.forward(input).output();
|
||||
|
||||
cx.build_search_space::<NativeRuntime>();
|
||||
let mut rt = cx.search(NativeRuntime::default(), 1);
|
||||
cx.build_search_space::<NativeRuntime>(CompileOptions::default());
|
||||
let mut rt = cx.search(NativeRuntime::default(), CompileOptions::new(1));
|
||||
|
||||
let input_data = random_vec(in_dim);
|
||||
let router_data = random_vec(in_dim * n_experts);
|
||||
@@ -393,8 +394,8 @@ mod tests {
|
||||
};
|
||||
let output = moe.forward(input).output();
|
||||
|
||||
cx.build_search_space::<NativeRuntime>();
|
||||
let mut rt = cx.search(NativeRuntime::default(), 1);
|
||||
cx.build_search_space::<NativeRuntime>(CompileOptions::default());
|
||||
let mut rt = cx.search(NativeRuntime::default(), CompileOptions::new(1));
|
||||
|
||||
let input_data = random_vec(batch * in_dim);
|
||||
let router_data = random_vec(in_dim * n_experts);
|
||||
@@ -478,7 +479,8 @@ mod tests {
|
||||
let down_out = hidden_exp.matmul(down_gathered.transpose(2, 3)).squeeze(2); // [s, k, H]
|
||||
|
||||
// 7. Weighted sum over k experts → [s, H]
|
||||
let weights_exp = top_k_values.unsqueeze(top_k_values.dims().len()); // [s, k, 1]
|
||||
let mut weights_exp = top_k_values.unsqueeze(top_k_values.dims().len()); // [s, k, 1]
|
||||
weights_exp.shape.expand(down_out.dims());
|
||||
let _output = (down_out * weights_exp).sum(n - 1).output();
|
||||
|
||||
// Dump the HLIR to egglog
|
||||
|
||||
@@ -783,6 +783,78 @@ identical across all attempts (dtype issue) vs varying (actual numerical issue).
|
||||
4. **Cleaner formulation**: name the concept. Compute an `iteration_invariant_slots: HashSet<LoopStart>` set at the same time `start_meta` is built, with the rule `body_producer ∉ body_nodes ⇒ iteration_invariant`. `resolve_src` and `marker_post_sub` then have explicit branches: if the slot is invariant, use `body_producer` directly; otherwise the standard per-iter clone lookup. The behavior is the same as the `unwrap_or` band-aid, but the code now documents that this is a real, sound case the unroll handles correctly — not a panic suppressor.
|
||||
5. **Principle**: when an `unwrap_or` papers over a case that turns out to be semantically valid, the right cleanup isn't to keep the `unwrap_or` and add a comment — it's to name the case. Hoist the predicate into a set or enum and branch on it explicitly. The compiler then enforces that every consumer of the per-iter cloning machinery has an opinion on iteration-invariant slots, instead of silently relying on a `Map::get` returning `None` at the right moment.
|
||||
|
||||
---
|
||||
|
||||
## 2026-04-30 — `translate_grouped_mm` casted the full expert weight to F32, OOMing search on Qwen3-MoE
|
||||
|
||||
### What the symptom was
|
||||
|
||||
`benchmarks/ttft/run.py --config qwen3-moe` crashed every search-profile attempt with:
|
||||
```
|
||||
crates/luminal_cuda_lite/src/runtime.rs:711: called `Result::unwrap()` on an `Err` value:
|
||||
DriverError(CUDA_ERROR_OUT_OF_MEMORY, "out of memory")
|
||||
```
|
||||
The DB shows this had been failing every run for ~2 weeks. The rust `examples/qwen3_moe` ran fine end-to-end. python_baseline / python_torch_compile / qwen3-4b were all fine — only python_luminal × qwen3-moe failed.
|
||||
|
||||
### What the actual root cause was
|
||||
|
||||
`translate_grouped_mm` in `crates/luminal_python/rust/src/translator/tensor.rs` was lowering HF's `_grouped_mm(input, weight, offs)` op to a *full-broadcast* batched matmul plus a group-mask:
|
||||
|
||||
```rust
|
||||
let weight_f = weight.cast(DType::F32); // [G=128, K, N] cast → 1.5 GB / layer
|
||||
let input_batched = input_f.expand_dim(0, g);
|
||||
let all_out = input_batched.matmul(weight_f); // [G, S, N]
|
||||
let mask = ... (g_arange == expert_id).cast(F32);
|
||||
let out = (all_out * mask.expand_dim(2, n)).sum(0); // mask + sum over G
|
||||
```
|
||||
|
||||
The full `[G, K, N]` F32 cast intermediate is 1.5 GB / layer for gate-up and 0.6 GB / layer for down on Qwen3-30B-A3B. With 60 GB of persistent bf16 weights already on a 97 GB GPU, the search-time profiler ran out of memory allocating those casts.
|
||||
|
||||
By contrast, `examples/qwen3_moe`'s `gather_experts` gathers only the top-K active experts per token first, then casts that small `[s, k, d1, d2]` slice (~100 MB / layer). The GLUMoE host op (`crates/luminal_cuda_lite/src/host/moe/glumoe_rewrite.egg`) is also wired to this gather pattern.
|
||||
|
||||
### Why it was hard to find
|
||||
|
||||
1. **Code path was reasonable in isolation**: at small scale (`test_grouped_mm_fallback`: g=2, K=8, N=16) the broadcast version was fine — the F32 cast was only 1 KB, and search profiling never noticed.
|
||||
2. **The error reported "out of memory" but the rest of the system looked healthy**: 60 GB weights + 37 GB headroom looks like plenty until you realise 48 layers × 2.1 GB cast intermediates per layer doesn't fit, even after loop rolling.
|
||||
3. **The DB's `code 1` failures looked the same as a Python exception** — the actual panic site (`runtime.rs:711:64` `stream.alloc_zeros(needed_bytes).unwrap()`) had to be recovered from a tmux scrollback because the orchestrator's stdout was already torn down by the time we looked.
|
||||
|
||||
### The fix
|
||||
|
||||
Rewrote `translate_grouped_mm` to gather first, matmul second:
|
||||
|
||||
```rust
|
||||
// expert_id[m] = first g s.t. m < offs[g], clamped to [0, G-1]
|
||||
let expert_id = ge_boundary.sum(0).minimum_f32(g_max_f).cast(DType::Int);
|
||||
|
||||
// flat_idx = expert_id * (K*N) + iota('z', (K, N)) — same shape as
|
||||
// rust qwen3_moe's `gather_experts`
|
||||
let flat_idx = (expert_id * (k * n))
|
||||
.expand_dim(1, k).expand_dim(2, n)
|
||||
+ self.graph.iota(Expression::from('z'), (k, n)).expand_dim(0, s);
|
||||
|
||||
let weight_gathered = weight.gather(flat_idx); // [S, K, N], bf16
|
||||
let result = input.cast(F32).unsqueeze(1)
|
||||
.matmul(weight_gathered.cast(F32)) // [S, 1, N]
|
||||
.squeeze(1);
|
||||
```
|
||||
|
||||
Two important details:
|
||||
|
||||
1. **Clamp `expert_id` to `[0, G-1]`**: at search time, dummy data fills `offs` with all-1s (`make_ones_bytes` in `compile_backend`). For S>1 that pushes `expert_id` to G (boundary count = G), which is one past the last valid expert and OOBs the gather. HF's own grouped-MM forward also clamps for the same reason (invalid expert IDs from EP).
|
||||
2. **Don't cast the full weight**: the cast moved from before the batched-matmul (over `[G, K, N]`) to after the gather (over `[S, K, N]`). 16× shrink at prefill (S=top_k=8 vs G=128).
|
||||
|
||||
### Result
|
||||
|
||||
`search-iters=1` end-to-end works on Qwen3-30B-A3B: `BENCH_RESULT … "ttft_ms": 9350.5, "tpot_ms": 1166.7`. The OOM is gone.
|
||||
|
||||
`search-iters>=5` still crashes — but with a *different*, downstream `CUDA_ERROR_ILLEGAL_ADDRESS` during execution after search completes. That looks like the same family as the 2026-03-07 / 2026-03-09 egglog-extractor non-determinism bugs (some mutation during search picks a kernel/rewrite combo that's broken at this scale). It's a separate investigation — the gather-based lowering is correct in isolation (`test_grouped_mm_fallback` passes; a synthetic `g=128, S=8, K=2048, N=1536` bf16 test passes with max-diff ~2.4e-4).
|
||||
|
||||
### General principle
|
||||
|
||||
**When lowering an op that takes a per-row index over a large parameter, gather first and cast second — never cast the full parameter to F32 just because your matmul kernel is F32-only.** A "broadcast over G + mask" pattern is mathematically equivalent to "gather per-row" but materialises a G× larger intermediate — fine for tests, ruinous on real MoE checkpoints. When in doubt, mirror the rust example's pattern: the egglog fusion rules (GLUMoE here) are written to recognise the gather form, not the broadcast-and-mask form.
|
||||
|
||||
Also: search-time dummy-1 inputs are not the same shape as runtime inputs. Anything you compute from a runtime tensor (cumsum offsets, routing indices, mask boundaries) needs to remain in-bounds for the dummy. Clamp index-producing chains as a matter of course, not just when the math says you "should" — `make_ones_bytes` is a hostile witness.
|
||||
|
||||
## 2026-05-02 — Whisper port hit two missing-translator pitfalls
|
||||
|
||||
1. **Symptom**: Compiling a PyTorch port of Whisper-tiny.en through `luminal_backend` failed twice in a row at the dispatch table: first with `Unsupported ATen op: torch.ops.aten.gelu.default`, then with `full: unsupported fill value type ... -Infinity`.
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
# luminal_python
|
||||
|
||||
PyTorch `torch.compile` integration for Luminal.
|
||||
|
||||
## CUDA Tests
|
||||
|
||||
The Python CUDA CI job builds the Rust extension with the CUDA feature and runs
|
||||
the non-slow pytest suite:
|
||||
|
||||
```bash
|
||||
cd crates/luminal_python
|
||||
RUST_BACKTRACE=1 \
|
||||
LUMINAL_TEST_DEVICE=cuda \
|
||||
MATURIN_PEP517_ARGS="--features cuda --profile release" \
|
||||
CUDARC_CUDA_VERSION=12080 \
|
||||
uv run --group dev python -m pytest tests/ -v -s -m "not slow"
|
||||
```
|
||||
|
||||
The slow tests are explicit opt-in. They include large/pretrained model tests,
|
||||
full-width architecture compiles, Whisper end-to-end cases, and other cases that
|
||||
can take a long time or need a large GPU / Hugging Face cache.
|
||||
|
||||
Run the full Python CUDA suite, including slow tests:
|
||||
|
||||
```bash
|
||||
cd crates/luminal_python
|
||||
RUST_BACKTRACE=1 \
|
||||
LUMINAL_TEST_DEVICE=cuda \
|
||||
MATURIN_PEP517_ARGS="--features cuda --profile release" \
|
||||
CUDARC_CUDA_VERSION=12080 \
|
||||
uv run --group dev python -m pytest tests/ -v -s
|
||||
```
|
||||
|
||||
Run only the slow Python CUDA tests:
|
||||
|
||||
```bash
|
||||
cd crates/luminal_python
|
||||
RUST_BACKTRACE=1 \
|
||||
LUMINAL_TEST_DEVICE=cuda \
|
||||
MATURIN_PEP517_ARGS="--features cuda --profile release" \
|
||||
CUDARC_CUDA_VERSION=12080 \
|
||||
uv run --group dev python -m pytest tests/ -v -s -m slow
|
||||
```
|
||||
|
||||
The helper script follows the same convention:
|
||||
|
||||
```bash
|
||||
cd crates/luminal_python
|
||||
./run_tests_cuda.sh # non-slow CUDA suite
|
||||
./run_tests_cuda.sh --slow-only # only slow CUDA tests
|
||||
./run_tests_cuda.sh --include-slow
|
||||
```
|
||||
|
||||
The GitHub/Modal entrypoint uses the same marker split:
|
||||
|
||||
```bash
|
||||
cd crates/luminal_python
|
||||
modal run modal_pytest_runner.py --gpu A100 --timeout 7200 tests/ -v -s -m "not slow"
|
||||
modal run modal_pytest_runner.py --gpu A100 --timeout 7200 tests/ -v -s
|
||||
```
|
||||
|
||||
@@ -431,7 +431,7 @@ def main() -> None:
|
||||
tokenizer = WhisperTokenizer.from_pretrained(REPO_ID)
|
||||
|
||||
use_compiled = os.environ.get("LUMINAL_DISABLE", "0") != "1"
|
||||
max_new_tokens = int(os.environ.get("GEN_TOKENS", "100"))
|
||||
max_new_tokens = 100
|
||||
search_iters = int(os.environ.get("SEARCH_ITERATIONS", "10"))
|
||||
|
||||
if use_compiled:
|
||||
|
||||
@@ -22,7 +22,7 @@ from modal.volume import FileEntryType
|
||||
|
||||
app = modal.App("luminal-tests")
|
||||
|
||||
DEFAULT_TIMEOUT = 30 * 60
|
||||
DEFAULT_TIMEOUT = 2 * 60 * 60
|
||||
CUDARC_CUDA_VERSION = "12080"
|
||||
LOCAL_PROJECT_DIR = Path(__file__).resolve().parent
|
||||
PROJECT_DIR = "/root/luminal/crates/luminal_python"
|
||||
@@ -168,6 +168,37 @@ def _cleanup_remote_profile_artifacts(run_id: str) -> None:
|
||||
return
|
||||
|
||||
|
||||
def _build_cuda_extension(env: dict[str, str]) -> None:
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"--project",
|
||||
PROJECT_DIR,
|
||||
"--group",
|
||||
"dev",
|
||||
"maturin",
|
||||
"develop",
|
||||
"--manifest-path",
|
||||
f"{PROJECT_DIR}/rust/Cargo.toml",
|
||||
"--features",
|
||||
"cuda",
|
||||
"--profile",
|
||||
"release",
|
||||
]
|
||||
subprocess.run(cmd, env=env, cwd=PROJECT_DIR, check=True)
|
||||
|
||||
|
||||
def _effective_timeout(timeout: int) -> int:
|
||||
if os.environ.get("GITHUB_ACTIONS") == "true" and timeout < DEFAULT_TIMEOUT:
|
||||
print(
|
||||
f"Using Modal timeout {DEFAULT_TIMEOUT}s instead of requested "
|
||||
f"{timeout}s in GitHub Actions.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return DEFAULT_TIMEOUT
|
||||
return timeout
|
||||
|
||||
|
||||
@app.cls(image=image, timeout=DEFAULT_TIMEOUT)
|
||||
class TestRunner:
|
||||
@modal.method()
|
||||
@@ -194,6 +225,8 @@ class TestRunner:
|
||||
if pytest_addopts:
|
||||
env["PYTEST_ADDOPTS"] = pytest_addopts
|
||||
|
||||
_build_cuda_extension(env)
|
||||
|
||||
original_svg_requested = _has_pytest_flag(pytest_args, "--profile-svg")
|
||||
dot_available = shutil.which("dot") is not None
|
||||
sanitized_pytest_args = [
|
||||
@@ -218,8 +251,6 @@ class TestRunner:
|
||||
PROJECT_DIR,
|
||||
"--group",
|
||||
"dev",
|
||||
"--reinstall-package",
|
||||
"luminal_python",
|
||||
"python",
|
||||
"-m",
|
||||
"pytest",
|
||||
@@ -285,7 +316,7 @@ class TestRunner:
|
||||
|
||||
def _parse_cli_args(
|
||||
cli_args: tuple[str, ...],
|
||||
) -> tuple[str, int | None, bool, str | None, list[str]]:
|
||||
) -> tuple[str, int, bool, str | None, list[str]]:
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="modal run modal_pytest_runner.py",
|
||||
add_help=False,
|
||||
@@ -300,7 +331,8 @@ def _parse_cli_args(
|
||||
parser.add_argument(
|
||||
"--timeout",
|
||||
type=int,
|
||||
help="Optional Modal execution timeout in seconds. Defaults to 1800 seconds.",
|
||||
default=DEFAULT_TIMEOUT,
|
||||
help="Modal execution timeout in seconds. Defaults to %(default)s seconds.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--profile",
|
||||
@@ -334,11 +366,11 @@ def main(*cli_args: str):
|
||||
)
|
||||
profile_enabled = _profiling_enabled(cli_profile, pytest_args)
|
||||
pytest_addopts = os.environ.get("PYTEST_ADDOPTS", "")
|
||||
timeout = _effective_timeout(timeout)
|
||||
runner_options = {"gpu": gpu}
|
||||
hf_token_secret = _hf_token_secret()
|
||||
runner_volumes = {HF_CACHE_PATH: HF_CACHE_VOLUME}
|
||||
if timeout is not None:
|
||||
runner_options["timeout"] = timeout
|
||||
runner_options["timeout"] = timeout
|
||||
if profile_enabled:
|
||||
runner_volumes[PROFILE_VOLUME_PATH] = PROFILE_VOLUME
|
||||
runner_options["volumes"] = runner_volumes
|
||||
|
||||
@@ -32,7 +32,7 @@ module-name = "luminal.luminal"
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
markers = [
|
||||
"slow: tests that download large models or require pre-generated artifacts",
|
||||
"slow: tests that download large models, compile full-width model graphs, fuzz many CUDA search choices, or otherwise require explicit opt-in",
|
||||
]
|
||||
|
||||
[dependency-groups]
|
||||
|
||||
@@ -1,34 +1,43 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
export CUDARC_CUDA_VERSION="${CUDARC_CUDA_VERSION:-12080}"
|
||||
export MATURIN_PEP517_ARGS="${MATURIN_PEP517_ARGS:---features cuda --profile release}"
|
||||
|
||||
echo "=========================================="
|
||||
echo " Luminal Python: Full Test Suite"
|
||||
echo "=========================================="
|
||||
|
||||
NATIVE_TESTS="tests/test_hlir_ops.py tests/test_unary.py"
|
||||
CUDA_TESTS="tests/test_hlir_ops.py tests/test_unary.py tests/test_llama3.py"
|
||||
NATIVE_TESTS="tests/test_hlir_ops.py tests/test_unary.py tests/test_dtype_boundary.py tests/test_torch_dtype_parity.py"
|
||||
CUDA_TESTS="tests/"
|
||||
|
||||
# ── Phase 1: Native Backend ─────────────────────────────────
|
||||
|
||||
echo ""
|
||||
echo "=== Phase 1: Building native backend ==="
|
||||
rm -rf rust/target/wheels rust/target/debug rust/target/release
|
||||
uv run maturin develop --manifest-path rust/Cargo.toml
|
||||
uv run --group dev maturin develop --manifest-path rust/Cargo.toml
|
||||
|
||||
echo ""
|
||||
echo "--- 1a: Native backend tests ---"
|
||||
uv run pytest $NATIVE_TESTS -v
|
||||
uv run --group dev pytest $NATIVE_TESTS -v
|
||||
|
||||
# ── Phase 2: CUDA Backend ───────────────────────────────────
|
||||
|
||||
echo ""
|
||||
echo "=== Phase 2: Building CUDA backend ==="
|
||||
rm -rf rust/target/wheels rust/target/debug rust/target/release
|
||||
uv run maturin develop --manifest-path rust/Cargo.toml --features cuda -r
|
||||
uv run --group dev maturin develop --manifest-path rust/Cargo.toml --features cuda -r
|
||||
|
||||
echo ""
|
||||
echo "--- 2a: CUDA ---"
|
||||
RUST_BACKTRACE=1 LUMINAL_TEST_DEVICE=cuda uv run pytest $CUDA_TESTS -m "not slow" -v
|
||||
RUST_BACKTRACE=1 LUMINAL_TEST_DEVICE=cuda uv run --group dev pytest $CUDA_TESTS -m "not slow" -v
|
||||
|
||||
echo ""
|
||||
echo "Slow CUDA tests are opt-in. To include them, run:"
|
||||
echo " RUST_BACKTRACE=1 LUMINAL_TEST_DEVICE=cuda uv run pytest tests/ -v -s"
|
||||
echo "Or, for only slow tests:"
|
||||
echo " RUST_BACKTRACE=1 LUMINAL_TEST_DEVICE=cuda uv run pytest tests/ -m slow -v -s"
|
||||
|
||||
echo ""
|
||||
echo "=========================================="
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user