Skip to content
Draft
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
3 changes: 0 additions & 3 deletions tests/core/framework/hf_model_loader_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -752,7 +752,6 @@ TEST(HFModelLoaderTest, Qwen3DFlash2AcceptsArrayEosTokenIds) {
EXPECT_EQ(args.stop_token_ids(),
std::unordered_set<int32_t>({154820, 154827, 154829}));
if (std::string(model_name) == "qwen3") {
EXPECT_EQ(args.block_size(), 8);
EXPECT_EQ(args.dflash2_selector_top_k(), 16);
}
}
Expand All @@ -776,7 +775,6 @@ TEST(HFModelLoaderTest, Qwen3DFlash2ReadsFlatBlockGeometry) {

ModelArgs args;
ASSERT_TRUE(loader(reader, &args));
EXPECT_EQ(args.block_size(), 5);
EXPECT_EQ(args.dflash2_conv_group_size(), 2);
EXPECT_EQ(args.dflash2_conv_kernel_size(), 3);
EXPECT_EQ(args.dflash2_selector_rank(), 128);
Expand Down Expand Up @@ -829,7 +827,6 @@ TEST(HFModelLoaderTest, DeepseekV4DSparkModelArgsFrom0731Config) {
ASSERT_TRUE(loader(reader, &args));
EXPECT_EQ(args.model_type(), "deepseek_v4");
EXPECT_EQ(args.dspark_num_layers(), 3);
EXPECT_EQ(args.block_size(), 5);
EXPECT_EQ(args.markov_rank(), 256);
ASSERT_EQ(args.compress_ratios().size(), 43);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ limitations under the License.
#include "core/layers/common/attention_metadata_builder.h"
#include "core/layers/common/expanded_decode_metadata_builder.h"
#include "core/runtime/forward_params.h"
#include "core/runtime/options.h"
#include "core/runtime/py_attention_metadata.h"

namespace py = pybind11;
Expand Down Expand Up @@ -322,7 +323,8 @@ TEST(MtpAsyncInputBuilderTest, PybindViewOwnsGlobalDpKvMaxSequenceLengths) {
params.parallel.dp_global_token_nums = {expected[0] == 0 ? 0 : 1,
expected[1] == 0 ? 0 : 1};
params.parallel.dp_global_kv_max_seq_lens = expected;
py_metadata = py::cast(PyAttentionMetadataView(metadata, params));
py_metadata = py::cast(
PyAttentionMetadataView(metadata, params, runtime::Options{}));
EXPECT_EQ(py_metadata.attr("raw_dp_execution_token_counts")
.cast<std::vector<int32_t>>(),
params.parallel.dp_global_token_nums);
Expand Down Expand Up @@ -375,7 +377,8 @@ TEST(MtpAsyncInputBuilderTest, PybindViewExposesLinearStateReadAndWriteSlots) {
params.embedding.linear_state_read_ids = {2, 6};
params.meta.batch_forward_type = BatchForwardType::PREFILL;

py::object py_metadata = py::cast(PyAttentionMetadataView(metadata, params));
py::object py_metadata =
py::cast(PyAttentionMetadataView(metadata, params, runtime::Options{}));
EXPECT_TRUE(torch::equal(
py_metadata.attr("linear_state_indices").cast<torch::Tensor>(),
torch::tensor({3, 7}, torch::kInt)));
Expand Down Expand Up @@ -435,7 +438,8 @@ TEST(MtpAsyncInputBuilderTest, PybindViewsPreserveGraphMetadataStorage) {
params.parallel.dp_global_token_nums = {6, 0};
params.parallel.dp_global_sequence_nums = {3, 0};
params.parallel = params.parallel.to(torch::Device(torch::kCPU));
py::object py_metadata = py::cast(PyAttentionMetadataView(metadata, params));
py::object py_metadata =
py::cast(PyAttentionMetadataView(metadata, params, runtime::Options{}));
EXPECT_EQ(
py_metadata.attr("dp_global_sequence_nums").cast<std::vector<int32_t>>(),
(std::vector<int32_t>{3, 0}));
Expand Down Expand Up @@ -464,7 +468,8 @@ TEST(MtpAsyncInputBuilderTest, PybindViewsPreserveGraphMetadataStorage) {
auto sparse = std::make_shared<layer::AttentionMetadata>(
layer::AttentionMetadataBuilder::build_mtp_sparse_decode(
table, lengths, slots, /*block_size=*/128));
py::object sparse_view = py::cast(PyAttentionMetadataView(sparse, params));
py::object sparse_view =
py::cast(PyAttentionMetadataView(sparse, params, runtime::Options{}));
const torch::Tensor view_table =
sparse_view.attr("block_table").cast<torch::Tensor>();
const torch::Tensor view_lengths =
Expand Down
4 changes: 2 additions & 2 deletions tests/core/layers/npu_torch/dflash2_grouped_conv_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ TEST(DFlash2GroupedConvTest, ResetsHistoryAtEachBlockBoundary) {
torch::Tensor output = dflash2_grouped_conv(hidden,
delta,
base,
/*block_size=*/2,
/*num_speculative_tokens=*/1,
/*num_groups=*/2,
/*group_size=*/2,
/*taps=*/2);
Expand All @@ -49,7 +49,7 @@ TEST(DFlash2GroupedConvTest, BroadcastsDynamicKernelWithinEachGroup) {
torch::Tensor output = dflash2_grouped_conv(hidden,
delta,
base,
/*block_size=*/2,
/*num_speculative_tokens=*/1,
/*num_groups=*/2,
/*group_size=*/2,
/*taps=*/1);
Expand Down
71 changes: 10 additions & 61 deletions tests/core/runtime/acl_graph_executor_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -255,9 +255,6 @@ class SimpleCausalLM : public CausalLM {
<< ", positions: " << positions.sizes()
<< ", kv_caches: " << kv_caches.size()
<< ", params: " << params.meta.num_sequences;
const int64_t num_tokens = tokens.size(0);
const int64_t hidden_size = args_.hidden_size();

// Create token embeddings using standard embedding lookup
auto token_embeddings = torch::embedding(token_embedding_table_, tokens);

Expand Down Expand Up @@ -324,26 +321,12 @@ class SimpleCausalLM : public CausalLM {
return model_output;
}

void set_return_aux_hidden_states(bool value) {
return_aux_hidden_states_ = value;
}

const torch::TensorOptions& options() const override {
static torch::TensorOptions opts =
torch::dtype(torch::kFloat32).device(device_);
return opts;
}

const ModelArgs& args() const { return args_; }

bool last_forward_enabled_graph() const {
return last_forward_enabled_graph_;
}

bool last_forward_had_attn_metadata() const {
return last_forward_had_attn_metadata_;
}

// Implement required virtual functions
torch::Tensor logits(const torch::Tensor& hidden_states,
const torch::Tensor& selected_idxes) override {
Expand All @@ -368,6 +351,10 @@ class SimpleCausalLM : public CausalLM {
// Simple implementation for testing
}

bool return_aux_hidden_states_ = false;
bool last_forward_enabled_graph_ = false;
bool last_forward_had_attn_metadata_ = false;

private:
ModelArgs args_;
torch::Device device_;
Expand All @@ -380,9 +367,6 @@ class SimpleCausalLM : public CausalLM {
torch::Tensor block_scale_;
torch::Tensor block_size_;
torch::Tensor scalar_one_;
bool return_aux_hidden_states_ = false;
bool last_forward_enabled_graph_ = false;
bool last_forward_had_attn_metadata_ = false;
};

class AclGraphExecutorTest : public ::testing::Test {
Expand Down Expand Up @@ -596,7 +580,7 @@ TEST_F(AclGraphExecutorTest, PreservesAuxHiddenStatesAcrossGraphReplay) {

SimpleCausalLM* simple_model = dynamic_cast<SimpleCausalLM*>(model_.get());
ASSERT_NE(simple_model, nullptr);
simple_model->set_return_aux_hidden_states(/*value=*/true);
simple_model->return_aux_hidden_states_ = true;
options_.enable_graph_aux_hidden_states(/*value=*/true);

ModelOutput eager_output =
Expand Down Expand Up @@ -832,8 +816,8 @@ TEST_F(AclGraphExecutorTest, DecodeBatchSizeThresholdFallsBackToEager) {
EXPECT_EQ(graph_out.hidden_states.size(1), model_args_.hidden_size());
auto* simple_model = dynamic_cast<SimpleCausalLM*>(model_.get());
ASSERT_NE(simple_model, nullptr);
EXPECT_FALSE(simple_model->last_forward_enabled_graph());
EXPECT_FALSE(simple_model->last_forward_had_attn_metadata());
EXPECT_FALSE(simple_model->last_forward_enabled_graph_);
EXPECT_FALSE(simple_model->last_forward_had_attn_metadata_);
EXPECT_TRUE(torch::allclose(eager_out.hidden_states,
graph_out.hidden_states,
/*rtol=*/1e-5,
Expand Down Expand Up @@ -894,8 +878,8 @@ TEST_F(AclGraphExecutorTest, NoPaddingBucketCapturesOnlyForWarmup) {
{ModelParamsView(forward_input.input_params)});
auto* simple_model = dynamic_cast<SimpleCausalLM*>(model_.get());
ASSERT_NE(simple_model, nullptr);
EXPECT_FALSE(simple_model->last_forward_enabled_graph());
EXPECT_FALSE(simple_model->last_forward_had_attn_metadata());
EXPECT_FALSE(simple_model->last_forward_enabled_graph_);
EXPECT_FALSE(simple_model->last_forward_had_attn_metadata_);

forward_input.input_params.meta.is_graph_warmup = true;
auto warmup_graph_out =
Expand All @@ -915,7 +899,7 @@ TEST_F(AclGraphExecutorTest, NoPaddingBucketCapturesOnlyForWarmup) {
graph_out.hidden_states,
/*rtol=*/1e-5,
/*atol=*/1e-6));
EXPECT_TRUE(simple_model->last_forward_enabled_graph());
EXPECT_TRUE(simple_model->last_forward_enabled_graph_);
EXPECT_EQ(warmup_graph_out.hidden_states.size(0),
batch_size * (options_.num_speculative_tokens() + 1));
EXPECT_EQ(warmup_graph_out.hidden_states.size(1), model_args_.hidden_size());
Expand Down Expand Up @@ -1523,41 +1507,6 @@ TEST(DSparkWorkerWeightsTest, DedicatedVocabularyOverridesFallbackInAnyOrder) {
EXPECT_FALSE(dedicated_first.should_load(Source::DEDICATED));
}

TEST(SpeculativeWorkerDispatchTest, DecodeRequiresEveryDpRankToDecode) {
LlmModelParams params;
params.meta.batch_forward_type = BatchForwardType::DECODE;
params.parallel.dp_global_token_nums = {1, 1};
params.parallel.dp_is_decode = {1, 1};
EXPECT_TRUE(should_run_speculative_decode(params));

params.parallel.dp_global_token_nums = {1, 8095};
params.parallel.dp_is_decode = {1, 0};
EXPECT_FALSE(should_run_speculative_decode(params));
}

TEST(SpeculativeWorkerDispatchTest, PreservesSingleDpRankBehavior) {
LlmModelParams params;
params.meta.batch_forward_type = BatchForwardType::DECODE;
EXPECT_TRUE(should_run_speculative_decode(params));

params.parallel.dp_global_token_nums = {1};
EXPECT_TRUE(should_run_speculative_decode(params));

params.parallel.dp_is_decode = {1};
EXPECT_TRUE(should_run_speculative_decode(params));

params.meta.batch_forward_type = BatchForwardType::CHUNKED_PREFILL;
EXPECT_FALSE(should_run_speculative_decode(params));
}

TEST(SpeculativeWorkerDispatchTest, DecodeRejectsIncompleteDpMetadata) {
LlmModelParams params;
params.meta.batch_forward_type = BatchForwardType::DECODE;
params.parallel.dp_global_token_nums = {1, 8095};
params.parallel.dp_is_decode = {1};
EXPECT_FALSE(should_run_speculative_decode(params));
}

TEST(AclGraphPersistentParamTest, SpecVerifyGraphUpdateSupportsRuntimeBatch) {
constexpr int32_t kSpecWidth = 4;
constexpr int32_t kBatchSize = 2;
Expand Down
14 changes: 9 additions & 5 deletions tests/models/py_causal_lm_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,8 @@ TEST(PyCausalLMMegaMoeCapacityTest,
// real model classes such as deepseek_v4 require full vocab/layer configs).
ModelContext make_bridge_model_context(const char* model_type,
ModelArgs model_args = {},
EplbWorkerConfig eplb_config = {}) {
EplbWorkerConfig eplb_config = {},
int32_t num_speculative_tokens = 0) {
{
py::gil_scoped_acquire gil;
// Idempotent, but run the py::exec/registry writes only once across the
Expand Down Expand Up @@ -169,7 +170,8 @@ ModelContext make_bridge_model_context(const char* model_type,
parallel_args,
model_args,
QuantArgs(),
torch::TensorOptions().device(torch::kCPU).dtype(torch::kFloat32));
torch::TensorOptions().device(torch::kCPU).dtype(torch::kFloat32),
num_speculative_tokens);
}

TEST(PyCausalLMConfigBridgeTest,
Expand Down Expand Up @@ -317,8 +319,7 @@ TEST(PyCausalLMConfigBridgeTest, PreservesBlockDraftWindowEnablement) {
config["use_sliding_window"] = *test.enabled;
}
if (draft_type == "dflash2") {
config["dflash_config"] = {{"block_size", 4},
{"conv_group_size", 2},
config["dflash_config"] = {{"conv_group_size", 2},
{"conv_kernel_size", 2},
{"selector_rank", 2},
{"selector_top_k", 2}};
Expand Down Expand Up @@ -347,7 +348,10 @@ TEST(PyCausalLMConfigBridgeTest, PreservesBlockDraftWindowEnablement) {
const char* model_type =
is_dflash2 ? "DFlash2DraftModel" : "DSparkDraftModel";
ModelContext context =
make_bridge_model_context(model_type, std::move(args));
make_bridge_model_context(model_type,
std::move(args),
{},
/*num_speculative_tokens=*/3);
PyCausalLM model(context, kBridgeTestModelType);
py::gil_scoped_acquire gil;
const char* module = is_dflash2 ? "xllm.python.models.qwen3_dflash2"
Expand Down
47 changes: 4 additions & 43 deletions tests/python/test_csa_attention.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,6 @@
from xllm.python.attention.backend import LayerCache
from xllm.python.attention.csa_attention import (
DsaAttentionBackend,
_build_dspark_swa_indices,
_deepseek_v4_ori_window_left,
_scatter_by_slot,
)
from xllm.python.model_executor.v4_cp_context import (
Expand Down Expand Up @@ -68,48 +66,11 @@ def _make_dspark_native_backend() -> DsaAttentionBackend:
rope_head_dim=2,
device=torch.device("cpu"),
dtype=torch.float32,
block_size=3,
num_speculative_tokens=3,
dspark_use_native_sas=True,
)


def test_dspark_native_sas_window_matches_cpp_contract() -> None:
assert _deepseek_v4_ori_window_left(128, 5, False) == 127
assert _deepseek_v4_ori_window_left(128, 0, True) == 127
assert _deepseek_v4_ori_window_left(128, 5, True) == 132


def test_dspark_native_swa_indices_are_shared_by_query_rows() -> None:
indices = _build_dspark_swa_indices(
torch.tensor([[10, 11, 12]], dtype=torch.int32),
torch.tensor([0, 3], dtype=torch.int32),
torch.tensor([6], dtype=torch.int32),
window_size=4,
block_size=3,
cache_block_size=4,
)

assert indices.shape == (3, 1, 128)
expected = torch.tensor([40, 41, 42, 43, 44, 45, -1], dtype=torch.int32)
for row in range(3):
torch.testing.assert_close(indices[row, 0, :7], expected)


def test_dspark_native_swa_indices_wrap_ring_buffer() -> None:
indices = _build_dspark_swa_indices(
torch.tensor([[20, 21]], dtype=torch.int32),
torch.tensor([0, 1], dtype=torch.int32),
torch.tensor([10], dtype=torch.int32),
window_size=4,
block_size=3,
cache_block_size=2,
)

assert indices.shape == (1, 1, 128)
expected = torch.tensor([41, 42, 43, 40, 41], dtype=torch.int32)
torch.testing.assert_close(indices[0, 0, :5], expected)


def test_dspark_native_swa_indices_map_expanded_metadata_ring() -> None:
backend = _make_dspark_native_backend()
compressed_metadata = backend._builder.build(
Expand Down Expand Up @@ -488,7 +449,7 @@ def fake_qli_metadata(**kwargs):


def test_dspark_native_decode_metadata_uses_expanded_window(monkeypatch) -> None:
backend = _make_backend(compress_ratios=[1], n_layers=1, block_size=5, dspark_use_native_sas=True)
backend = _make_backend(compress_ratios=[1], n_layers=1, num_speculative_tokens=5, dspark_use_native_sas=True)
sparse_calls: list[dict] = []

monkeypatch.setattr(
Expand Down Expand Up @@ -586,7 +547,7 @@ def test_dspark_native_mixed_ratio_decode_uses_expanded_window(
rope_head_dim=2,
device=torch.device("cpu"),
dtype=torch.float32,
block_size=3,
num_speculative_tokens=3,
dspark_use_native_sas=True,
)
backend.bind_kv_caches([LayerCache(key=None, value=None, swa=torch.zeros(1, 4, 1, 4))])
Expand Down Expand Up @@ -938,7 +899,7 @@ def test_graph_dsa_build_uses_stable_host_length_values(monkeypatch) -> None:
def test_prefill_and_dummy_decode_metadata_stay_in_sync_with_execute(
monkeypatch,
) -> None:
backend = _make_backend(compress_ratios=[1], n_layers=1, block_size=5, dspark_use_native_sas=True)
backend = _make_backend(compress_ratios=[1], n_layers=1, num_speculative_tokens=5, dspark_use_native_sas=True)
swa = torch.zeros(2, 128, 1, 512, dtype=torch.float32)
backend.bind_kv_caches([LayerCache(key=None, value=None, swa=swa)])
block_table = torch.tensor([[1]], dtype=torch.int32)
Expand Down
1 change: 0 additions & 1 deletion tests/python/test_deepseek_v4_dspark.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,6 @@ def test_dspark_config_builds_only_draft_layers() -> None:
assert model.cfg.n_layers == 3
assert model.cfg.n_hash_layers == 0
assert model.cfg.compress_ratios == [1, 1, 1]
assert model.cfg.dspark_use_native_sas is False
assert len(model.model.layers) == 3
assert model.model.main_proj.in_features == 24
assert model.model.main_proj.out_features == 8
Expand Down
Loading
Loading