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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 57 additions & 7 deletions csrc/activation/silu_and_mul.cu
Original file line number Diff line number Diff line change
Expand Up @@ -171,8 +171,36 @@ __global__ void silu_and_mul_kernel(const T* gate, const T* up, T* out, int64_t
}
}

template <typename T, bool aligned>
__global__ void silu_and_mul_rows(const T* gate, const T* up, T* out,
int64_t width, int64_t rows, int64_t gate_stride,
int64_t up_stride, int64_t work_per_row) {
const int64_t first = static_cast<int64_t>(blockIdx.x) * blockDim.x + threadIdx.x;
const int64_t stride = static_cast<int64_t>(gridDim.x) * blockDim.x;
for (int64_t i = first; i < rows * work_per_row; i += stride) {
const int64_t row = i / work_per_row;
const int64_t col = i % work_per_row;
if constexpr (aligned) {
constexpr int elements = 16 / sizeof(T);
constexpr int pairs = 16 / sizeof(typename Math<T>::Pair);
const int64_t offset = col * elements;
Vector<T> g = load_vector<T, true>(gate + row * gate_stride, offset, width);
Vector<T> u = load_vector<T, true>(up + row * up_stride, offset, width);
Vector<T> result;
#pragma unroll
for (int j = 0; j < pairs; ++j) {
result.pairs[j] = Math<T>::compute(g.pairs[j], u.pairs[j]);
}
*reinterpret_cast<uint4*>(out + row * width + offset) =
*reinterpret_cast<const uint4*>(&result);
} else {
out[i] = compute_scalar(gate[row * gate_stride + col], up[row * up_stride + col]);
}
}
}

template <typename T>
void launch(const at::Tensor& gate, const at::Tensor& up, at::Tensor& out) {
void launch(const at::Tensor& gate, const at::Tensor& up, at::Tensor& out, bool contiguous) {
const T* g = reinterpret_cast<const T*>(gate.const_data_ptr());
const T* u = reinterpret_cast<const T*>(up.const_data_ptr());
T* result = reinterpret_cast<T*>(out.mutable_data_ptr());
Expand All @@ -182,6 +210,27 @@ void launch(const at::Tensor& gate, const at::Tensor& up, at::Tensor& out) {
reinterpret_cast<uintptr_t>(result)) & 15) == 0;
const int64_t count = gate.numel();
constexpr int threads = 256;
auto stream = c10::cuda::getCurrentCUDAStream(gate.get_device());
if (!contiguous) {
const int64_t width = gate.size(1);
const int64_t rows = gate.size(0);
const int64_t gs = gate.stride(0);
const int64_t us = up.stride(0);
constexpr int elements = 16 / sizeof(T);
const bool aligned = vectorized && (width | gs | us) % elements == 0;
const int64_t work_per_row = aligned ? width / elements : width;
const int blocks = static_cast<int>(std::min<int64_t>(
(rows * work_per_row + threads - 1) / threads, 4096));
if (aligned) {
silu_and_mul_rows<T, true><<<blocks, threads, 0, stream>>>(
g, u, result, width, rows, gs, us, work_per_row);
} else {
silu_and_mul_rows<T, false><<<blocks, threads, 0, stream>>>(
g, u, result, width, rows, gs, us, work_per_row);
}
C10_CUDA_KERNEL_LAUNCH_CHECK();
return;
}
bool scalar = false;
if (!vectorized) {
// Use 160 reference vector blocks per SM to determine the element cutoff.
Expand All @@ -204,7 +253,6 @@ void launch(const at::Tensor& gate, const at::Tensor& up, at::Tensor& out) {
}
}
const int blocks = static_cast<int>(std::min<int64_t>((work + threads - 1) / threads, max_blocks));
auto stream = c10::cuda::getCurrentCUDAStream(gate.get_device());
if (vectorized) {
silu_and_mul_kernel<T, AccessMode::Aligned><<<blocks, threads, 0, stream>>>(g, u, result, count);
} else if (scalar) {
Expand All @@ -227,8 +275,10 @@ at::Tensor silu_and_mul_cuda(const at::Tensor& gate, const at::Tensor& up) {
gate.scalar_type() == at::kBFloat16,
"silu_and_mul supports float32, float16 and bfloat16");

TORCH_CHECK(gate.is_contiguous() && up.is_contiguous(),
"silu_and_mul expects contiguous inputs");
const bool contiguous = gate.is_contiguous() && up.is_contiguous();
TORCH_CHECK(contiguous ||
(gate.dim() == 2 && gate.stride(1) == 1 && up.stride(1) == 1),
"silu_and_mul expects contiguous inputs or 2D inputs with contiguous rows");
TORCH_CHECK(!at::GradMode::is_enabled() || (!gate.requires_grad() && !up.requires_grad()),
"silu_and_mul is inference-only; use torch.no_grad() or silu_and_mul_reference");

Expand All @@ -238,9 +288,9 @@ at::Tensor silu_and_mul_cuda(const at::Tensor& gate, const at::Tensor& up) {
return out;
}
switch (gate.scalar_type()) {
case at::kHalf: launch<__half>(gate, up, out); break;
case at::kBFloat16: launch<__nv_bfloat16>(gate, up, out); break;
case at::kFloat: launch<float>(gate, up, out); break;
case at::kHalf: launch<__half>(gate, up, out, contiguous); break;
case at::kBFloat16: launch<__nv_bfloat16>(gate, up, out, contiguous); break;
case at::kFloat: launch<float>(gate, up, out, contiguous); break;
default: TORCH_CHECK(false, "unsupported dtype");
}
return out;
Expand Down
9 changes: 5 additions & 4 deletions docs/kernels.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,11 @@ are FP32, FP16 and BF16. The output owns new storage and preserves input shape,
dtype and device. Neither input is modified. The Torch reference preserves
the intermediate SiLU rounding of the existing MLP expression.

Separate inputs avoid concatenating Ouro and Nanbeige's separate projection
outputs. The reference also accepts Huginn's noncontiguous split-projection
views. The native entry requires both inputs to be contiguous; it neither pads
nor copies incompatible inputs.
The native entry accepts contiguous inputs and 2D inputs with unit column
strides. Ouro's fused gate/up projection produces two such views into one
matrix. The kernel reads both row strides directly with 16-byte vector loads
when the rows and their starts are aligned, or scalar loads otherwise.
Inputs outside these layouts are rejected without copying.

`silu_and_mul(gate, up)` uses PyTorch dispatch: CUDA inputs use the native kernel
when the extension is installed; CPU inputs and installations without the
Expand Down
23 changes: 20 additions & 3 deletions tests/test_activation.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,9 +307,26 @@ def test_silu_and_mul_cuda_special_values_and_underflow(dtype, offsets):


@pytest.mark.gpu
def test_silu_and_mul_cuda_rejects_noncontiguous_input_without_copying():
gate, up = torch.randn(2, 14, device="cuda").chunk(2, dim=-1)
with pytest.raises(RuntimeError, match="contiguous inputs"):
@pytest.mark.parametrize("rows,width", [(8, 5632), (32, 5632), (128, 5632), (3, 13)])
def test_silu_and_mul_cuda_consumes_packed_projection_without_repacking(rows, width):
packed = torch.randn((rows, 2 * width), device="cuda", dtype=torch.bfloat16)
gate, up = packed.split(width, dim=-1)
assert not gate.is_contiguous() and not up.is_contiguous()
actual = silu_and_mul(gate, up)
torch.testing.assert_close(actual, silu_and_mul_reference(gate, up), rtol=0, atol=0)

graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
actual = silu_and_mul(gate, up)
packed.normal_()
graph.replay()
torch.testing.assert_close(actual, silu_and_mul_reference(gate, up), rtol=0, atol=0)


@pytest.mark.gpu
def test_silu_and_mul_cuda_rejects_nonunit_column_stride_without_copying():
gate, up = torch.randn(2, 28, device="cuda")[:, ::2].chunk(2, dim=-1)
with pytest.raises(RuntimeError, match="contiguous rows"):
silu_and_mul(gate, up)


Expand Down
118 changes: 118 additions & 0 deletions tests/test_fused_projections.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
# SPDX-License-Identifier: Apache-2.0
"""Exercise Ouro's packed weights through checkpoint and GPU execution paths."""

import pickle

import pytest
import torch
from torch.nn import functional as F

from tests.helpers import tiny_ouro_config
from vllm_rlt.models.ouro import OuroForCausalLM, OuroMLP


def test_reload_legacy_weights_updates_a_previously_used_mlp():
model = OuroForCausalLM(tiny_ouro_config())
mlp = model.model.layers[0].mlp
hidden = torch.ones(4, model.config.hidden_size)
before = mlp(hidden)
assert torch.count_nonzero(before)

original = mlp.state_dict()["up_proj.weight"].clone()
missing, unexpected = mlp.load_state_dict(
{"gate_proj.weight": torch.zeros_like(original)}, strict=False
)
assert set(missing) == {"up_proj.weight", "down_proj.weight"}
assert not unexpected
assert torch.equal(mlp.state_dict()["up_proj.weight"], original)
torch.testing.assert_close(mlp(hidden), torch.zeros_like(before), atol=0, rtol=0)


@pytest.mark.parametrize("roundtrip", ["convert", "pickle", "load", "assign"])
def test_checkpoint_views_share_one_weight_after_roundtrip(roundtrip):
config = tiny_ouro_config(num_key_value_heads=1)
original = OuroForCausalLM(config)
checkpoint = original.state_dict()
if roundtrip == "convert":
model = original.bfloat16()
elif roundtrip == "pickle":
model = pickle.loads(pickle.dumps(original))
elif roundtrip == "load":
model = OuroForCausalLM(config)
model.load_state_dict(checkpoint)
else:
with torch.device("meta"):
model = OuroForCausalLM(config)
model.load_state_dict(checkpoint, assign=True)

weights = model.state_dict()
assert weights.keys() == checkpoint.keys()
for name, value in weights.items():
assert torch.equal(value, checkpoint[name].to(dtype=value.dtype))
for layer in model.model.layers:
for module, names in (
(layer.self_attn, ("q_proj", "k_proj", "v_proj")),
(layer.mlp, ("gate_proj", "up_proj")),
):
expected_offset = 0
for name in names:
part = module.state_dict()[f"{name}.weight"]
assert part.untyped_storage().data_ptr() == module.input_weight.data_ptr()
assert part.storage_offset() == expected_offset
expected_offset += part.numel()
assert expected_offset == module.input_weight.numel()
assert module.input_weight.untyped_storage().nbytes() == (
expected_offset * module.input_weight.element_size()
)


@pytest.mark.parametrize("corruption", ["missing", "shape", "internal"])
def test_strict_load_validates_legacy_fused_keys(corruption):
model = OuroForCausalLM(tiny_ouro_config())
checkpoint = model.state_dict()
key = "model.layers.0.self_attn.k_proj.weight"
if corruption == "missing":
del checkpoint[key]
elif corruption == "shape":
checkpoint[key] = checkpoint[key][:-1]
else:
key = "model.layers.0.self_attn.input_weight"
checkpoint[key] = model.model.layers[0].self_attn.input_weight
with pytest.raises(RuntimeError, match=key):
model.load_state_dict(checkpoint)


@pytest.mark.gpu
def test_mlp_output_is_bitwise_identical_to_the_unfused_expression():
from vllm_rlt.kernels._extension import load_extension

load_extension()
torch.manual_seed(1)
config = tiny_ouro_config(hidden_size=64, intermediate_size=128)
mlp = OuroMLP(config).to("cuda", torch.bfloat16).eval()
hidden = torch.randn(4, config.hidden_size, device="cuda", dtype=torch.bfloat16)
params = mlp.state_dict()
with torch.no_grad():
expected = mlp.down_proj(
F.silu(F.linear(hidden, params["gate_proj.weight"]))
* F.linear(hidden, params["up_proj.weight"])
)
got = mlp(hidden)
torch.testing.assert_close(got, expected, atol=0, rtol=0)


@pytest.mark.gpu
def test_attention_split_matches_separate_projections_within_bf16_rounding():
torch.manual_seed(2)
config = tiny_ouro_config(hidden_size=64, num_key_value_heads=1)
model = OuroForCausalLM(config).to("cuda", torch.bfloat16)
attn = model.model.layers[0].self_attn
hidden = torch.randn(4, config.hidden_size, device="cuda", dtype=torch.bfloat16)
params = attn.state_dict()
with torch.no_grad():
parts = attn.project(hidden)
separate = tuple(F.linear(hidden, params[f"{name}_proj.weight"]) for name in "qkv")
for got, exp in zip(parts, separate):
diff = (got.float() - exp.float()).abs().max().item()
scale = max(exp.float().abs().max().item(), 1e-9)
assert diff / scale < 0.0078, f"relative diff {diff / scale:.5f} exceeds 1 BF16 ULP"
28 changes: 16 additions & 12 deletions tests/test_ouro.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import pytest
import torch
from safetensors.torch import save_file
from torch.nn import functional as F

from tests.helpers import make_cpu_cache, tiny_ouro_config
from tests.reference import dense_reference
Expand All @@ -21,17 +22,22 @@ def model():
return OuroForCausalLM(tiny_ouro_config())


def _unfused_mlp(layer, hidden):
weights = layer.state_dict()
gate = F.linear(hidden, weights["gate_proj.weight"])
up = F.linear(hidden, weights["up_proj.weight"])
return F.linear(F.silu(gate) * up, weights["down_proj.weight"])


@pytest.mark.gpu
@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16, torch.float32])
@pytest.mark.parametrize("rows", [1, 7, 32])
def test_cuda_mlp_matches_torch_expression(dtype, rows):
torch.manual_seed(72)
layer = OuroMLP(tiny_ouro_config(intermediate_size=17)).to(device="cuda", dtype=dtype)
layer.requires_grad_(False)
hidden = torch.randn(rows, layer.gate_proj.in_features, device="cuda", dtype=dtype)
expected = layer.down_proj(
torch.nn.functional.silu(layer.gate_proj(hidden)) * layer.up_proj(hidden)
)
hidden = torch.randn(rows, layer.input_weight.shape[1], device="cuda", dtype=dtype)
expected = _unfused_mlp(layer, hidden)
torch.testing.assert_close(layer(hidden), expected, rtol=0, atol=0)


Expand All @@ -55,10 +61,10 @@ def import_module(name, *args, **kwargs):
assert torch._C._dispatch_has_kernel_for_dispatch_key(
'vllm_rlt::silu_and_mul', 'CUDA') == {native_available}
layer = OuroMLP(tiny_ouro_config()).cuda().bfloat16().requires_grad_(False)
hidden = torch.randn(3, layer.gate_proj.in_features,
hidden = torch.randn(3, layer.input_weight.shape[1],
device='cuda', dtype=torch.bfloat16)
expected = layer.down_proj(
torch.nn.functional.silu(layer.gate_proj(hidden)) * layer.up_proj(hidden))
from tests.test_ouro import _unfused_mlp
expected = _unfused_mlp(layer, hidden)
with torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CPU]) as prof:
actual = layer(hidden)
torch.testing.assert_close(actual, expected, rtol=0, atol=0)
Expand All @@ -74,7 +80,7 @@ def test_cuda_mlp_graph_replays_updated_hidden():
layer = OuroMLP(tiny_ouro_config(intermediate_size=17)).cuda().bfloat16().requires_grad_(False)
stream = torch.cuda.Stream()
with torch.cuda.stream(stream):
hidden = torch.randn(3, layer.gate_proj.in_features, device="cuda", dtype=torch.bfloat16)
hidden = torch.randn(3, layer.input_weight.shape[1], device="cuda", dtype=torch.bfloat16)
for _ in range(3):
layer(hidden)
stream.synchronize()
Expand All @@ -83,9 +89,7 @@ def test_cuda_mlp_graph_replays_updated_hidden():
actual = layer(hidden)
hidden.fill_(0.5)
graph.replay()
expected = layer.down_proj(
torch.nn.functional.silu(layer.gate_proj(hidden)) * layer.up_proj(hidden)
)
expected = _unfused_mlp(layer, hidden)
torch.testing.assert_close(actual, expected, rtol=0, atol=0)


Expand Down Expand Up @@ -226,7 +230,7 @@ def snapshot_download(**kwargs):
)
monkeypatch.setattr("huggingface_hub.snapshot_download", snapshot_download)
loaded = OuroForCausalLM.from_pretrained("test-org/checkpoint", revision="test-revision")
for name, parameter in loaded.named_parameters():
for name, parameter in loaded.state_dict().items():
torch.testing.assert_close(parameter, model.state_dict()[name].bfloat16(), atol=0, rtol=0)
assert loaded.model.rotary_emb.inv_freq.dtype == torch.float32
assert called["revision"] == "test-revision"
Expand Down
3 changes: 2 additions & 1 deletion vllm_rlt/kernels/activation.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ def silu_and_mul_reference(gate: torch.Tensor, up: torch.Tensor) -> torch.Tensor

Inputs have equal shape, dtype and device. The result has the same shape,
dtype and device and owns new storage. Noncontiguous inputs are supported
by this reference; the native entry requires contiguous inputs.
by this reference; the native entry supports contiguous tensors and 2D
tensors with contiguous rows.
"""
_validate_inputs(gate, up)
return F.silu(gate) * up
Expand Down
Loading
Loading