feat(cuda): integrate the verified fixed MoE router
This commit is contained in:
@@ -0,0 +1,125 @@
|
||||
// Adapted from topk-moe.cu/common.cuh in llama.cpp
|
||||
// 3cf03257f219afbe7334045ff7c6a06ac68c627d; finite F32, 512-expert/10-output path.
|
||||
// Source snapshot: native_router.cu at b72b060d5dcea5efe202e1d34650de22de926cca
|
||||
// SHA-256: 006cde3fa5bcdb721c8e8d8a7bdc1094b1d2ff09ec7bdc9b3a1855e494d8d39e
|
||||
// MIT License
|
||||
// Copyright (c) 2023-2026 The ggml authors
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
#include <float.h>
|
||||
#include <math.h>
|
||||
#include <stdint.h>
|
||||
|
||||
namespace {
|
||||
__device__ __forceinline__ float warp_sum(float value) {
|
||||
#pragma unroll
|
||||
for (int mask = 16; mask; mask >>= 1) {
|
||||
value += __shfl_xor_sync(0xffffffffu, value, mask, 32);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
__device__ __forceinline__ float warp_max(float value) {
|
||||
#pragma unroll
|
||||
for (int mask = 16; mask; mask >>= 1) {
|
||||
value = fmaxf(value, __shfl_xor_sync(0xffffffffu, value, mask, 32));
|
||||
}
|
||||
return value;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
// Fixed ABI: [512 f32 logits, 10 i32 IDs, 10 f32 weights]. Launch exactly
|
||||
// grid=(1,1,1), block=(32,8,1), dynamic shared memory=0. The inactive seven
|
||||
// warps return; the active warp has no inter-warp dependency, so no block-wide
|
||||
// barrier is used (a barrier after those returns would be invalid).
|
||||
extern "C" __global__
|
||||
void leleka_moe_route_top10(const float *__restrict__ logits,
|
||||
int32_t *__restrict__ ids,
|
||||
float *__restrict__ weights) {
|
||||
if (threadIdx.y != 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const int lane = static_cast<int>(threadIdx.x);
|
||||
float values[16];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 16; ++i) {
|
||||
values[i] = logits[lane + i * 32];
|
||||
}
|
||||
|
||||
float maximum = -INFINITY;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 16; ++i) {
|
||||
maximum = fmaxf(maximum, values[i]);
|
||||
}
|
||||
maximum = warp_max(maximum);
|
||||
|
||||
float sum = 0.0f;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 16; ++i) {
|
||||
values[i] = expf(values[i] - maximum);
|
||||
sum += values[i];
|
||||
}
|
||||
const float reciprocal = 1.0f / warp_sum(sum);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 16; ++i) {
|
||||
values[i] *= reciprocal;
|
||||
if (__isnanf(values[i])) {
|
||||
values[i] = -FLT_MAX;
|
||||
}
|
||||
}
|
||||
|
||||
float selected = 0.0f;
|
||||
float selected_sum = 0.0f;
|
||||
for (int rank = 0; rank < 10; ++rank) {
|
||||
float best = values[0];
|
||||
int expert = lane;
|
||||
#pragma unroll
|
||||
for (int i = 1; i < 16; ++i) {
|
||||
if (values[i] > best) {
|
||||
best = values[i];
|
||||
expert = lane + i * 32;
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int mask = 16; mask; mask >>= 1) {
|
||||
const float other = __shfl_xor_sync(0xffffffffu, best, mask, 32);
|
||||
const int other_id = __shfl_xor_sync(0xffffffffu, expert, mask, 32);
|
||||
if (other > best || (other == best && other_id < expert)) {
|
||||
best = other;
|
||||
expert = other_id;
|
||||
}
|
||||
}
|
||||
if ((expert & 31) == lane) {
|
||||
values[expert / 32] = -INFINITY;
|
||||
ids[rank] = expert;
|
||||
// Preserve the source's per-winning-lane accumulation in rank order.
|
||||
selected_sum += best;
|
||||
}
|
||||
if (rank == lane) {
|
||||
selected = best;
|
||||
}
|
||||
}
|
||||
|
||||
selected_sum = fmaxf(warp_sum(selected_sum), 6.103515625e-5f);
|
||||
const float inverse_selected_sum = 1.0f / selected_sum;
|
||||
if (lane < 10) {
|
||||
weights[lane] = selected * inverse_selected_sum;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -783,7 +783,14 @@ mod tests {
|
||||
#[test]
|
||||
fn qwen_receipt_refusal_precedes_any_backend_mutation() {
|
||||
for op in OPERATIONS {
|
||||
assert!(qwen_ffi::asset(op).is_none());
|
||||
if op == Operation::RouteTop10 {
|
||||
qwen_ffi::asset(op)
|
||||
.expect("admitted router")
|
||||
.validate(op)
|
||||
.unwrap();
|
||||
} else {
|
||||
assert!(qwen_ffi::asset(op).is_none());
|
||||
}
|
||||
for change in 0..9 {
|
||||
let mut asset = qwen_ffi::mock_asset(op);
|
||||
match change {
|
||||
|
||||
@@ -243,9 +243,39 @@ impl Asset {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
// Finite router component admission. This is not a full-model capability.
|
||||
const ROUTE_RECEIPT: Receipt = Receipt {
|
||||
version: 1,
|
||||
source_sha256: [
|
||||
0x4b, 0xd2, 0xc9, 0xc4, 0xe1, 0x0b, 0x9a, 0xa0, 0xbc, 0xc2, 0xb1, 0xa8, 0x60, 0xf6, 0x7d,
|
||||
0xb0, 0x4f, 0x01, 0xd1, 0x7f, 0x59, 0xc9, 0x3b, 0xde, 0xa0, 0xae, 0x42, 0x67, 0x90, 0xd6,
|
||||
0x73, 0x73,
|
||||
],
|
||||
ptx_sha256: [
|
||||
0x48, 0x04, 0xcc, 0xad, 0xee, 0x77, 0xaa, 0xbd, 0xa8, 0x80, 0xfb, 0xc0, 0xa5, 0xb3, 0x4f,
|
||||
0x10, 0xe8, 0x58, 0x51, 0xc1, 0x69, 0xea, 0xa8, 0x96, 0xf3, 0x31, 0x4b, 0xed, 0x64, 0x78,
|
||||
0xe2, 0x25,
|
||||
],
|
||||
oracle_sha256: [
|
||||
0x00, 0x6c, 0xde, 0x3f, 0xa5, 0xbc, 0xdb, 0x72, 0x1c, 0x8e, 0x8d, 0x8a, 0x7b, 0xdc, 0x10,
|
||||
0x94, 0xb1, 0xd2, 0xff, 0x09, 0xec, 0x7b, 0xdc, 0x9b, 0x3a, 0x18, 0x55, 0xe4, 0x94, 0xd8,
|
||||
0xd3, 0x9e,
|
||||
],
|
||||
compiler: "NVCC 12.8.93; CUDA 12.8.1; GCC 13.3",
|
||||
compiler_flags: "-ptx -O3 -std=c++17 -arch=compute_120; no --use_fast_math",
|
||||
qualification_receipt: "STRA-166 b31a40ef-50b1-4ece-8d9d-1467c1feb388",
|
||||
comparison: "RTX5090 driver595.91.07: five synthetic cases, 50 IDs and 50 F32 weight bits exact against unchanged native oracle; model quality unqualified",
|
||||
abi_version: 1,
|
||||
topology: [512, 10, 1],
|
||||
};
|
||||
const ROUTE_ASSET: Asset = Asset {
|
||||
operation: Operation::RouteTop10,
|
||||
ptx: concat!(include_str!("moe_route_top10.ptx"), "\0").as_bytes(),
|
||||
receipt: ROUTE_RECEIPT,
|
||||
pin: ROUTE_RECEIPT,
|
||||
};
|
||||
pub(super) fn asset(operation: Operation) -> Option<&'static Asset> {
|
||||
// No GR producer has delivered qualified executable bytes/ABI receipts.
|
||||
// Never install a dummy kernel or reinterpret a projection asset here.
|
||||
// Remaining GR/BF16 producers have not delivered complete qualification.
|
||||
match operation {
|
||||
Operation::Down
|
||||
| Operation::Up
|
||||
@@ -255,8 +285,8 @@ pub(super) fn asset(operation: Operation) -> Option<&'static Asset> {
|
||||
| Operation::LayerGate
|
||||
| Operation::FinalGate
|
||||
| Operation::InjectResidual
|
||||
| Operation::Bf16
|
||||
| Operation::RouteTop10 => None,
|
||||
| Operation::Bf16 => None,
|
||||
Operation::RouteTop10 => Some(&ROUTE_ASSET),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,28 +1,95 @@
|
||||
//! STRA-166 router shell and its producer-owned opaque product.
|
||||
//! STRA-166 fixed CUDA router and its producer-owned opaque products.
|
||||
#![allow(dead_code)]
|
||||
|
||||
use super::contract::{Error, LayerId, Position, Result, Stage, TokenId, TokenLayer};
|
||||
use super::contract::{
|
||||
Dimension, Error, ExpertId, FiniteF32, LayerId, Position, Result, Stage, TokenId, TokenLayer,
|
||||
};
|
||||
use super::session::QwenStepTxn;
|
||||
use crate::model_binding::qwen4exp_input::ModelBinding;
|
||||
use crate::model_binding::qwen4exp_input::{BindingIdentity, ModelBinding};
|
||||
use leleka_cuda_driver::{Context, Error as DriverError};
|
||||
|
||||
const EXPERTS: usize = 512;
|
||||
const SELECTED: usize = 10;
|
||||
const LOGITS_BYTES: usize = EXPERTS * std::mem::size_of::<f32>();
|
||||
const IDS_BYTES: usize = SELECTED * std::mem::size_of::<i32>();
|
||||
const WEIGHTS_BYTES: usize = SELECTED * std::mem::size_of::<f32>();
|
||||
|
||||
/// Router logits admitted from the immediately preceding producer for one
|
||||
/// artifact-bound token/layer. The fixed array is finite before it can exist.
|
||||
pub(super) struct RouterLogits {
|
||||
private: (),
|
||||
}
|
||||
pub(super) struct RoutedExperts {
|
||||
binding: BindingIdentity,
|
||||
identity: TokenLayer,
|
||||
values: [f32; EXPERTS],
|
||||
}
|
||||
impl RouterLogits {
|
||||
/// Called only by the preceding router-logit producer after it has computed
|
||||
/// this exact token/layer for the same verified model binding.
|
||||
pub(super) fn from_preceding(
|
||||
binding: &ModelBinding,
|
||||
token: TokenId,
|
||||
position: Position,
|
||||
layer: LayerId,
|
||||
values: [f32; EXPERTS],
|
||||
) -> Result<Self> {
|
||||
validate_logits(&values)?;
|
||||
Ok(Self {
|
||||
binding: binding.identity(),
|
||||
identity: TokenLayer::new(token, position, layer),
|
||||
values,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn fixture(
|
||||
binding: BindingIdentity,
|
||||
token: TokenId,
|
||||
position: Position,
|
||||
layer: LayerId,
|
||||
values: [f32; EXPERTS],
|
||||
) -> Result<Self> {
|
||||
validate_logits(&values)?;
|
||||
Ok(Self {
|
||||
binding,
|
||||
identity: TokenLayer::new(token, position, layer),
|
||||
values,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A complete route only. No caller can construct a partial ID/weight vector.
|
||||
pub(super) struct RoutedExperts {
|
||||
binding: BindingIdentity,
|
||||
identity: TokenLayer,
|
||||
experts: [ExpertId; SELECTED],
|
||||
weights: [FiniteF32; SELECTED],
|
||||
}
|
||||
impl RoutedExperts {
|
||||
// Private to this producing module. No shell creates routed output.
|
||||
fn new(token: TokenId, position: Position, layer: LayerId) -> Self {
|
||||
fn new(
|
||||
binding: BindingIdentity,
|
||||
identity: TokenLayer,
|
||||
experts: [ExpertId; SELECTED],
|
||||
weights: [FiniteF32; SELECTED],
|
||||
) -> Self {
|
||||
Self {
|
||||
identity: TokenLayer::new(token, position, layer),
|
||||
binding,
|
||||
identity,
|
||||
experts,
|
||||
weights,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn identity(&self) -> TokenLayer {
|
||||
self.identity
|
||||
}
|
||||
|
||||
pub(super) fn experts(&self) -> &[ExpertId; SELECTED] {
|
||||
&self.experts
|
||||
}
|
||||
|
||||
pub(super) fn weights(&self) -> &[FiniteF32; SELECTED] {
|
||||
&self.weights
|
||||
}
|
||||
|
||||
pub(super) fn validate_for(
|
||||
&self,
|
||||
token: TokenId,
|
||||
@@ -31,18 +98,187 @@ impl RoutedExperts {
|
||||
) -> Result<()> {
|
||||
self.identity.validate(token, position, layer)
|
||||
}
|
||||
|
||||
pub(super) fn validate_binding(&self, binding: &BindingIdentity) -> Result<()> {
|
||||
if self.binding.matches(binding) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::IdentityMismatch)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct MoeRouteStage;
|
||||
|
||||
impl MoeRouteStage {
|
||||
/// Route one token using the closed, fixed CUDA Driver operation. The
|
||||
/// transaction owns the device context; no kernel name or geometry is
|
||||
/// supplied here. All products remain local until output validation ends.
|
||||
pub(super) fn route(
|
||||
_binding: &ModelBinding,
|
||||
_layer: LayerId,
|
||||
_logits: &RouterLogits,
|
||||
_token: TokenId,
|
||||
_txn: &mut QwenStepTxn,
|
||||
binding: &ModelBinding,
|
||||
layer: LayerId,
|
||||
logits: &RouterLogits,
|
||||
token: TokenId,
|
||||
txn: &mut QwenStepTxn,
|
||||
) -> Result<RoutedExperts> {
|
||||
Err(Error::Unsupported(Stage::MoeRoute))
|
||||
let identity = validate_request(binding, layer, logits, token, txn)?;
|
||||
let context = txn.cuda_context()?;
|
||||
route_with(
|
||||
binding.identity(),
|
||||
binding.expert_count(),
|
||||
logits,
|
||||
identity,
|
||||
|values| run_cuda(context, values),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_request(
|
||||
binding: &ModelBinding,
|
||||
layer: LayerId,
|
||||
logits: &RouterLogits,
|
||||
token: TokenId,
|
||||
txn: &QwenStepTxn,
|
||||
) -> Result<TokenLayer> {
|
||||
let expert_count = binding.expert_count();
|
||||
let used_count = binding.expert_used_count();
|
||||
if expert_count != EXPERTS as u32 || used_count != SELECTED as u32 {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
|
||||
let layer_bound = Dimension::new(u64::from(binding.layer_count()))?;
|
||||
if LayerId::new(u64::from(layer.get()), layer_bound)? != layer {
|
||||
return Err(Error::InvalidLayer);
|
||||
}
|
||||
|
||||
let position = txn.position();
|
||||
if txn.token() != token {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
txn.validate_binding(&binding.identity())?;
|
||||
txn.validate_binding(&logits.binding)?;
|
||||
logits.identity.validate(token, position, layer)?;
|
||||
validate_logits(&logits.values)?;
|
||||
txn.validate_input(token, position)?;
|
||||
Ok(TokenLayer::new(token, position, layer))
|
||||
}
|
||||
|
||||
fn validate_logits(values: &[f32; EXPERTS]) -> Result<()> {
|
||||
if values.iter().any(|value| !value.is_finite()) {
|
||||
return Err(Error::NonFinite);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn route_with(
|
||||
binding: BindingIdentity,
|
||||
expert_count: u32,
|
||||
logits: &RouterLogits,
|
||||
identity: TokenLayer,
|
||||
execute: impl FnOnce(&[f32; EXPERTS]) -> Result<([i32; SELECTED], [f32; SELECTED])>,
|
||||
) -> Result<RoutedExperts> {
|
||||
if expert_count != EXPERTS as u32 {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
if !binding.matches(&logits.binding) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
if identity != logits.identity {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
validate_logits(&logits.values)?;
|
||||
let (raw_ids, raw_weights) = execute(&logits.values)?;
|
||||
let expert_bound = Dimension::new(u64::from(expert_count))?;
|
||||
let mut ids = [ExpertId::new(0, expert_bound)?; SELECTED];
|
||||
let mut seen = [false; EXPERTS];
|
||||
let mut weights = [FiniteF32::new(0.0)?; SELECTED];
|
||||
for index in 0..SELECTED {
|
||||
let id = ExpertId::from_signed(i64::from(raw_ids[index]), expert_bound)?;
|
||||
let slot = usize::try_from(id.get()).map_err(|_| Error::InvalidExpert)?;
|
||||
if seen[slot] {
|
||||
return Err(Error::InvalidExpert);
|
||||
}
|
||||
seen[slot] = true;
|
||||
|
||||
let weight = FiniteF32::new(raw_weights[index])?;
|
||||
if !(0.0..=1.0).contains(&weight.get()) {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
ids[index] = id;
|
||||
weights[index] = weight;
|
||||
}
|
||||
Ok(RoutedExperts::new(binding, identity, ids, weights))
|
||||
}
|
||||
|
||||
fn run_cuda(
|
||||
context: &Context<'_>,
|
||||
values: &[f32; EXPERTS],
|
||||
) -> Result<([i32; SELECTED], [f32; SELECTED])> {
|
||||
let mut logits_bytes = [0_u8; LOGITS_BYTES];
|
||||
for (chunk, value) in logits_bytes
|
||||
.as_chunks_mut::<{ std::mem::size_of::<f32>() }>()
|
||||
.0
|
||||
.iter_mut()
|
||||
.zip(values)
|
||||
{
|
||||
chunk.copy_from_slice(&value.to_ne_bytes());
|
||||
}
|
||||
|
||||
let mut input = context.allocate(LOGITS_BYTES).map_err(map_driver_error)?;
|
||||
let mut ids_buffer = context.allocate(IDS_BYTES).map_err(map_driver_error)?;
|
||||
let mut weights_buffer = context.allocate(WEIGHTS_BYTES).map_err(map_driver_error)?;
|
||||
|
||||
input.copy_from(&logits_bytes).map_err(map_driver_error)?;
|
||||
context
|
||||
.qwen_route_top10(&input, &mut ids_buffer, &mut weights_buffer)
|
||||
.map_err(map_driver_error)?;
|
||||
|
||||
let mut ids_bytes = [0_u8; IDS_BYTES];
|
||||
let mut weights_bytes = [0_u8; WEIGHTS_BYTES];
|
||||
ids_buffer
|
||||
.copy_to(&mut ids_bytes)
|
||||
.map_err(map_driver_error)?;
|
||||
weights_buffer
|
||||
.copy_to(&mut weights_bytes)
|
||||
.map_err(map_driver_error)?;
|
||||
|
||||
// Explicit releases are part of success: a cleanup/restoration failure
|
||||
// withholds the host result. On an earlier error, Drop remains best-effort
|
||||
// and the poisoned Driver retains uncertain resources as its contract says.
|
||||
weights_buffer.release().map_err(map_driver_error)?;
|
||||
ids_buffer.release().map_err(map_driver_error)?;
|
||||
input.release().map_err(map_driver_error)?;
|
||||
|
||||
let ids = std::array::from_fn(|index| {
|
||||
let start = index * std::mem::size_of::<i32>();
|
||||
i32::from_ne_bytes(
|
||||
ids_bytes[start..start + 4]
|
||||
.try_into()
|
||||
.expect("fixed ID extent"),
|
||||
)
|
||||
});
|
||||
let weights = std::array::from_fn(|index| {
|
||||
let start = index * std::mem::size_of::<f32>();
|
||||
f32::from_ne_bytes(
|
||||
weights_bytes[start..start + 4]
|
||||
.try_into()
|
||||
.expect("fixed weight extent"),
|
||||
)
|
||||
});
|
||||
Ok((ids, weights))
|
||||
}
|
||||
|
||||
fn map_driver_error(error: DriverError) -> Error {
|
||||
match error {
|
||||
DriverError::UnsupportedQwenOperation => Error::Unsupported(Stage::MoeRoute),
|
||||
DriverError::HostAllocation | DriverError::BudgetExceeded => Error::InputAllocation,
|
||||
DriverError::InvalidQwenShape
|
||||
| DriverError::InvalidSize
|
||||
| DriverError::ShapeMismatch { .. } => Error::InvalidDimension,
|
||||
DriverError::ContextMismatch => Error::IdentityMismatch,
|
||||
_ => Error::CudaExecution,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
use super::*;
|
||||
use crate::qwen_forward::contract::{Dimension, Position};
|
||||
|
||||
// The oracle's explicit lane-index loops preserve the fixed warp traversal.
|
||||
#[allow(clippy::needless_range_loop)]
|
||||
#[path = "../../../tests/stra166_reference.rs"]
|
||||
mod independent_reference;
|
||||
|
||||
fn token(value: u64) -> TokenId {
|
||||
TokenId::new(value, Dimension::new(248_320).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn position(value: u64) -> Position {
|
||||
Position::new(value, Dimension::new(262_144).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn layer(value: u64) -> LayerId {
|
||||
LayerId::new(value, Dimension::new(48).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn base_ids() -> [i32; SELECTED] {
|
||||
std::array::from_fn(|index| index as i32)
|
||||
}
|
||||
|
||||
fn route_fixture(
|
||||
binding: BindingIdentity,
|
||||
values: [f32; EXPERTS],
|
||||
ids: [i32; SELECTED],
|
||||
weights: [f32; SELECTED],
|
||||
) -> Result<RoutedExperts> {
|
||||
let logits = RouterLogits::fixture(binding.clone(), token(7), position(0), layer(3), values)?;
|
||||
route_with(binding, EXPERTS as u32, &logits, logits.identity, |_| {
|
||||
Ok((ids, weights))
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_result_preserves_independent_tie_order_and_weights() {
|
||||
let binding = BindingIdentity::test_identity();
|
||||
let values = [0.0; EXPERTS];
|
||||
let expected = independent_reference::reference(&values).unwrap();
|
||||
let routed = route_fixture(binding.clone(), values, expected.ids, expected.weights).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
(*routed.experts()).map(ExpertId::get),
|
||||
expected.ids.map(|id| id as u32)
|
||||
);
|
||||
for (actual, expected) in routed.weights().iter().zip(expected.weights) {
|
||||
assert_eq!(actual.get().to_bits(), expected.to_bits());
|
||||
}
|
||||
assert_eq!(routed.validate_binding(&binding), Ok(()));
|
||||
routed
|
||||
.validate_for(token(7), position(0), layer(3))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
routed.validate_for(token(7), position(0), layer(4)),
|
||||
Err(Error::IdentityMismatch)
|
||||
);
|
||||
assert_eq!(
|
||||
routed.validate_binding(&BindingIdentity::test_identity()),
|
||||
Err(Error::IdentityMismatch)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dominant_route_keeps_zero_weights_and_exact_id_order() {
|
||||
let binding = BindingIdentity::test_identity();
|
||||
let mut values = [0.0; EXPERTS];
|
||||
values[511] = 1000.0;
|
||||
let expected = independent_reference::reference(&values).unwrap();
|
||||
let routed = route_fixture(binding, values, expected.ids, expected.weights).unwrap();
|
||||
assert_eq!(
|
||||
(*routed.experts()).map(ExpertId::get),
|
||||
[511, 0, 1, 2, 3, 4, 5, 6, 7, 8]
|
||||
);
|
||||
assert_eq!(routed.weights()[0].get(), 1.0);
|
||||
assert!(
|
||||
routed.weights()[1..]
|
||||
.iter()
|
||||
.all(|weight| weight.get() == 0.0)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_binding_or_token_layer_identity_refuses_before_dispatch() {
|
||||
let binding = BindingIdentity::test_identity();
|
||||
let other = BindingIdentity::test_identity();
|
||||
let logits = RouterLogits::fixture(
|
||||
binding.clone(),
|
||||
token(7),
|
||||
position(0),
|
||||
layer(3),
|
||||
[0.0; EXPERTS],
|
||||
)
|
||||
.unwrap();
|
||||
let mut called = false;
|
||||
let wrong_binding = route_with(other, EXPERTS as u32, &logits, logits.identity, |_| {
|
||||
called = true;
|
||||
Ok((base_ids(), [0.1; SELECTED]))
|
||||
});
|
||||
assert_eq!(wrong_binding.err(), Some(Error::IdentityMismatch));
|
||||
assert!(!called);
|
||||
|
||||
let mismatched = route_with(
|
||||
binding,
|
||||
EXPERTS as u32,
|
||||
&logits,
|
||||
TokenLayer::new(token(8), position(0), layer(3)),
|
||||
|_| panic!("identity mismatch must fail before CUDA dispatch"),
|
||||
);
|
||||
assert_eq!(mismatched.err(), Some(Error::IdentityMismatch));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_ids_and_duplicate_experts_are_rejected() {
|
||||
let binding = BindingIdentity::test_identity();
|
||||
let values = [0.0; EXPERTS];
|
||||
let mut ids = base_ids();
|
||||
ids[0] = -1;
|
||||
assert_eq!(
|
||||
route_fixture(binding.clone(), values, ids, [0.1; SELECTED]).err(),
|
||||
Some(Error::InvalidExpert)
|
||||
);
|
||||
|
||||
let mut ids = base_ids();
|
||||
ids[9] = 512;
|
||||
assert_eq!(
|
||||
route_fixture(binding.clone(), values, ids, [0.1; SELECTED]).err(),
|
||||
Some(Error::InvalidExpert)
|
||||
);
|
||||
|
||||
let mut ids = base_ids();
|
||||
ids[9] = ids[0];
|
||||
assert_eq!(
|
||||
route_fixture(binding, values, ids, [0.1; SELECTED]).err(),
|
||||
Some(Error::InvalidExpert)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonfinite_or_out_of_range_weights_are_never_published() {
|
||||
let binding = BindingIdentity::test_identity();
|
||||
for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
|
||||
let mut weights = [0.1; SELECTED];
|
||||
weights[4] = invalid;
|
||||
assert_eq!(
|
||||
route_fixture(binding.clone(), [0.0; EXPERTS], base_ids(), weights).err(),
|
||||
Some(Error::NonFinite)
|
||||
);
|
||||
}
|
||||
for invalid in [-f32::MIN_POSITIVE, 1.0 + f32::EPSILON] {
|
||||
let mut weights = [0.1; SELECTED];
|
||||
weights[4] = invalid;
|
||||
assert_eq!(
|
||||
route_fixture(binding.clone(), [0.0; EXPERTS], base_ids(), weights).err(),
|
||||
Some(Error::InvalidDimension)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_topology_and_logits_fail_before_dispatch() {
|
||||
let binding = BindingIdentity::test_identity();
|
||||
let logits = RouterLogits::fixture(
|
||||
binding.clone(),
|
||||
token(7),
|
||||
position(0),
|
||||
layer(3),
|
||||
[0.0; EXPERTS],
|
||||
)
|
||||
.unwrap();
|
||||
let mut called = false;
|
||||
assert_eq!(
|
||||
route_with(binding.clone(), 511, &logits, logits.identity, |_| {
|
||||
called = true;
|
||||
Ok((base_ids(), [0.1; SELECTED]))
|
||||
})
|
||||
.err(),
|
||||
Some(Error::InvalidDimension)
|
||||
);
|
||||
assert!(!called);
|
||||
|
||||
let mut nonfinite = [0.0; EXPERTS];
|
||||
nonfinite[2] = f32::NAN;
|
||||
assert_eq!(
|
||||
RouterLogits::fixture(binding, token(7), position(0), layer(3), nonfinite).err(),
|
||||
Some(Error::NonFinite)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn driver_failure_never_returns_a_partial_route() {
|
||||
let binding = BindingIdentity::test_identity();
|
||||
let logits = RouterLogits::fixture(
|
||||
binding.clone(),
|
||||
token(7),
|
||||
position(0),
|
||||
layer(3),
|
||||
[0.0; EXPERTS],
|
||||
)
|
||||
.unwrap();
|
||||
let result = route_with(binding, EXPERTS as u32, &logits, logits.identity, |_| {
|
||||
Err(Error::CudaExecution)
|
||||
});
|
||||
assert!(matches!(result, Err(Error::CudaExecution)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixed_driver_errors_map_to_closed_runtime_categories() {
|
||||
assert_eq!(
|
||||
map_driver_error(DriverError::UnsupportedQwenOperation),
|
||||
Error::Unsupported(Stage::MoeRoute)
|
||||
);
|
||||
assert_eq!(
|
||||
map_driver_error(DriverError::InvalidQwenShape),
|
||||
Error::InvalidDimension
|
||||
);
|
||||
assert_eq!(
|
||||
map_driver_error(DriverError::ShapeMismatch {
|
||||
expected: LOGITS_BYTES,
|
||||
actual: LOGITS_BYTES - 4,
|
||||
}),
|
||||
Error::InvalidDimension
|
||||
);
|
||||
assert_eq!(
|
||||
map_driver_error(DriverError::ContextMismatch),
|
||||
Error::IdentityMismatch
|
||||
);
|
||||
assert_eq!(
|
||||
map_driver_error(DriverError::HostAllocation),
|
||||
Error::InputAllocation
|
||||
);
|
||||
assert_eq!(
|
||||
map_driver_error(DriverError::BudgetExceeded),
|
||||
Error::InputAllocation
|
||||
);
|
||||
assert_eq!(
|
||||
map_driver_error(DriverError::Driver {
|
||||
operation: "synthetic",
|
||||
code: 7,
|
||||
}),
|
||||
Error::CudaExecution
|
||||
);
|
||||
assert_eq!(
|
||||
map_driver_error(DriverError::ContextPoisoned),
|
||||
Error::CudaExecution
|
||||
);
|
||||
}
|
||||
@@ -25,6 +25,8 @@ fn xor_sum(mut lanes: [f32; 32]) -> [f32; 32] {
|
||||
lanes
|
||||
}
|
||||
|
||||
// Lane indexing deliberately mirrors the independent frozen reduction order.
|
||||
#[allow(clippy::needless_range_loop)]
|
||||
pub fn reference(logits: &[f32; EXPERTS]) -> Option<Reference> {
|
||||
if logits.iter().any(|value| !value.is_finite()) {
|
||||
return None;
|
||||
|
||||
Reference in New Issue
Block a user