diff --git a/.github/workflows/ci_test.yml b/.github/workflows/ci_test.yml index 91106df7e..5e519da20 100644 --- a/.github/workflows/ci_test.yml +++ b/.github/workflows/ci_test.yml @@ -24,7 +24,7 @@ jobs: - name: Run selected host checks run: | python -m unittest discover -s test/scripts -p "test_base_config_device_detection.py" -v - python -m pytest test/service/test_agent_protocol.py test/service/test_processor_contracts.py -q + python -m pytest test/service/test_agent_protocol.py test/service/test_processor_contracts.py test/service/test_clover_server.py -q check-format: name: Check Format diff --git a/.gitignore b/.gitignore index 149d4bc38..11483da92 100644 --- a/.gitignore +++ b/.gitignore @@ -34,3 +34,8 @@ __pycache__/ *.http *.nsys-rep + +# Pip editable-install artifacts (copied native libs & generated licenses) +python/_infinilm.cpython-*.so +python/infinilm/_lib/*.so +python/infinilm/licenses/InfiniOps/ diff --git a/README.md b/README.md index 95d1a9185..b63b5ab7b 100644 --- a/README.md +++ b/README.md @@ -209,3 +209,9 @@ LM 不隐式构建依赖栈,也不安装 Core 的独立 Python runtime。 ```bash python examples/bench.py --device nvidia --model= --enable-paged-attn [--attn=default | --attn=flash-attn] ``` + +### Clover + +Native Clover block diffusion and the optional frontier/expert-reuse decoder +run on NVIDIA and Hygon devices. They are documented in +[the Clover guide](docs/clover.md). diff --git a/csrc/engine/infer_engine.cpp b/csrc/engine/infer_engine.cpp index b2243ef25..b0a0e970e 100644 --- a/csrc/engine/infer_engine.cpp +++ b/csrc/engine/infer_engine.cpp @@ -448,6 +448,8 @@ InferEngine::Input::to_model_input( : to_device(target_hidden_states), sample_all_positions}; input.logical_kv_upper_bound = logical_kv_upper_bound; + input.diffusion_preview = diffusion_preview; + input.diffusion_expert_budget = diffusion_expert_budget; auto &attn_metadata = forward_context.attn_metadata; attn_metadata = { diff --git a/csrc/engine/rank_worker.hpp b/csrc/engine/rank_worker.hpp index 4fcbb3e0b..d8193bbb9 100644 --- a/csrc/engine/rank_worker.hpp +++ b/csrc/engine/rank_worker.hpp @@ -98,6 +98,8 @@ class RankWorker { std::optional>> sampling_rows; std::optional nsa_owner_snapshot; + bool diffusion_preview{false}; + bool diffusion_expert_budget{false}; infinilm::InfinilmModel::Input to_model_input( infinilm::runtime::Device device, diff --git a/csrc/global_state/forward_context.hpp b/csrc/global_state/forward_context.hpp index f5dfce562..e56c1a7fe 100644 --- a/csrc/global_state/forward_context.hpp +++ b/csrc/global_state/forward_context.hpp @@ -31,6 +31,7 @@ struct StaticPrefillHostDescription { }; struct AttentionMetadata { + bool diffusion_preview{false}; /// Past Lengths of cached sequence for each request, of shape `[num_requests]`. std::optional past_sequence_lengths; /// ToTal Lengths for each request sequence, of shape `[num_requests]`. @@ -122,6 +123,11 @@ struct ForwardContext { AttentionMetadata attn_metadata; MambaMetadata mamba_metadata; MultiModalMetadata mm_metadata; + bool diffusion_preview{false}; + size_t diffusion_block_size{32}; + bool diffusion_expert_budget{false}; + infinilm::runtime::Tensor diffusion_valid; + infinilm::runtime::Tensor diffusion_live; std::vector kv_cache_vec; std::vector conv_state_vec; std::vector ssm_state_vec; diff --git a/csrc/layers/attention/backends/static_attn.cpp b/csrc/layers/attention/backends/static_attn.cpp index 31e5bb758..6f18b3e37 100644 --- a/csrc/layers/attention/backends/static_attn.cpp +++ b/csrc/layers/attention/backends/static_attn.cpp @@ -95,6 +95,7 @@ infinilm::runtime::Tensor StaticAttentionImpl::forward(const AttentionLayer &lay const bool finite_window = window_size[0] >= 0; bool varlen_candidate = finite_window; varlen_candidate = varlen_candidate || (prefill && seq_len > 1 && kv_quant_scheme_ == infinilm::quantization::KVQuantAlgo::NONE && (q_rope->dtype() == infinilm::runtime::DataType::kFloat16 || q_rope->dtype() == infinilm::runtime::DataType::kBFloat16)); + varlen_candidate = varlen_candidate && !attn_metadata.diffusion_preview; if (finite_window && seq_len > 1 && !prefill) { throw std::invalid_argument("Static finite window requires validated prefill row/past/total metadata"); } @@ -269,7 +270,7 @@ infinilm::runtime::Tensor StaticAttentionImpl::forward(const AttentionLayer &lay throw std::invalid_argument("causal_softmax has unsupported shape or dtype"); } std::optional causal_mask; - if (seq_len != 1) { + if (seq_len != 1 && !attn_metadata.diffusion_preview) { causal_mask = infinilm::runtime::Tensor::empty( runtime, {seq_len, total_seq_len}, attn_weight_softmax->dtype()); } diff --git a/csrc/models/clover_moe/clover_decoder_layer.cpp b/csrc/models/clover_moe/clover_decoder_layer.cpp new file mode 100644 index 000000000..0e8f3c2af --- /dev/null +++ b/csrc/models/clover_moe/clover_decoder_layer.cpp @@ -0,0 +1,83 @@ +#include "clover_decoder_layer.hpp" + +#include "runtime/runtime.hpp" +#include +#include +#include +#include + +namespace infinilm::models::clover_moe { + +CloverDecoderLayer::CloverDecoderLayer(infinilm::runtime::Runtime &runtime, + std::shared_ptr model_config, + size_t layer_idx, + const engine::distributed::RankInfo &rank_info, + backends::AttentionBackend attention_backend, + const layers::moe::EPConfig &ep_config) + : layer_idx_(layer_idx) { + runtime.assertOwnerThread(); + if (runtime.isGraphRecording()) { + throw std::logic_error("Clover decoder construction requires eager Runtime"); + } + if (!model_config || rank_info.device != runtime.device() || rank_info.tp_size <= 0 + || rank_info.tp_rank < 0 || rank_info.tp_rank >= rank_info.tp_size + || (rank_info.tp_size > 1 && !rank_info.comm)) { + throw std::invalid_argument("Invalid explicit Qwen35 decoder construction resources"); + } + const auto layer_types = model_config->get>("layer_types"); + layer_type_ = layer_types.at(layer_idx); + if (layer_type_ != "linear_attention" && layer_type_ != "full_attention") { + throw std::invalid_argument("Clover decoder has unsupported layer_type"); + } + try { + const auto &dtype = model_config->get_dtype(); + const size_t hidden_size = model_config->get("hidden_size"); + const double rms_norm_eps = model_config->get("rms_norm_eps"); + + input_layernorm_ = this->bind_child("input_layernorm", std::make_shared>(runtime, hidden_size, rms_norm_eps, dtype)); + post_attention_layernorm_ = this->bind_child("post_attention_layernorm", std::make_shared>(runtime, hidden_size, rms_norm_eps, dtype)); + mlp_ = this->bind_child("mlp", std::make_shared>(runtime, model_config, layer_idx, rank_info, attention_backend, ep_config)); + + if ("linear_attention" == layer_type_) { + linear_attn_ = this->bind_child("linear_attn", std::make_shared>(runtime, model_config, layer_idx, rank_info, attention_backend, ep_config)); + } else if ("full_attention" == layer_type_) { + self_attn_ = this->bind_child("self_attn", std::make_shared>(runtime, model_config, layer_idx, rank_info, attention_backend)); + } else { + throw std::runtime_error( + "CloverDecoderLayer: unsupported layer_type '" + layer_type_ + + "' for layer " + std::to_string(layer_idx)); + } + } catch (...) { + try { + runtime.syncStream(); + } catch (...) { std::terminate(); } + throw; + } +} + +std::tuple CloverDecoderLayer::forward( + const infinilm::runtime::Tensor &positions, + infinilm::runtime::Tensor &hidden_states, + infinilm::runtime::Tensor &residual, + infinilm::global_state::ForwardContext &forward_context) { + auto &runtime = forward_context.require_runtime(); + runtime.assertOwnerThread(); + if (!hidden_states || hidden_states->device() != runtime.device() + || (residual && residual->device() != runtime.device()) + || input_layernorm_->weight()->device() != runtime.device() + || post_attention_layernorm_->weight()->device() != runtime.device()) { + throw std::invalid_argument("CloverDecoderLayer: forward Runtime/input/norm device mismatch"); + } + input_layernorm_->forward_inplace(runtime, hidden_states, residual); + if ("linear_attention" == layer_type_) { + hidden_states = linear_attn_->forward(hidden_states, forward_context); + } else { + hidden_states = self_attn_->forward(positions, hidden_states, forward_context); + } + + post_attention_layernorm_->forward_inplace(runtime, hidden_states, residual); + hidden_states = mlp_->forward(runtime, hidden_states, forward_context); + return std::make_tuple(hidden_states, residual); +} + +} // namespace infinilm::models::clover_moe diff --git a/csrc/models/clover_moe/clover_decoder_layer.hpp b/csrc/models/clover_moe/clover_decoder_layer.hpp new file mode 100644 index 000000000..cbe7503fa --- /dev/null +++ b/csrc/models/clover_moe/clover_decoder_layer.hpp @@ -0,0 +1,43 @@ +#pragma once +#include "../../layers/normalization/rmsnorm.hpp" +#include "../../weights/weights.hpp" + +#include "../qwen3_5/qwen3_5_attention.hpp" +#include "clover_gdn.hpp" +#include "clover_moe.hpp" + +#include +#include + +namespace infinilm::models::clover_moe { + +class CloverDecoderLayer : public infinilm::weights::ModelWeights { +public: + CloverDecoderLayer(infinilm::runtime::Runtime &runtime, + std::shared_ptr model_config, + size_t layer_idx, + const engine::distributed::RankInfo &rank_info, + backends::AttentionBackend attention_backend, + const layers::moe::EPConfig &ep_config); + + std::tuple forward( + const infinilm::runtime::Tensor &positions, + infinilm::runtime::Tensor &hidden_states, + infinilm::runtime::Tensor &residual, + infinilm::global_state::ForwardContext &forward_context); + + size_t layer_idx() const { return layer_idx_; } + +protected: + std::shared_ptr input_layernorm_; + std::shared_ptr post_attention_layernorm_; + std::shared_ptr self_attn_; + std::shared_ptr linear_attn_; + std::shared_ptr mlp_; + +private: + size_t layer_idx_; + std::string layer_type_; +}; + +} // namespace infinilm::models::clover_moe diff --git a/csrc/models/clover_moe/clover_for_causal_lm.cpp b/csrc/models/clover_moe/clover_for_causal_lm.cpp new file mode 100644 index 000000000..0c97bdd79 --- /dev/null +++ b/csrc/models/clover_moe/clover_for_causal_lm.cpp @@ -0,0 +1,142 @@ +#include "../../layers/causal_lm_templates/text_causal_lm.hpp" +#include "../models_registry.hpp" +#include "../qwen3_5/qwen3_5_for_causal_lm.hpp" +#include "../qwen3_next/qwen3_next_allocate_kv_cache_tensors.hpp" +#include "clover_decoder_layer.hpp" +#include + +namespace infinilm::models::clover_moe { + +using CloverModel = layers::causal_lm_templates::TextModel; + +class CloverForCausalLM : public layers::causal_lm_templates::TextCausalLM { +public: + using Base = layers::causal_lm_templates::TextCausalLM; + using Base::Base; + + Output forward(const Input &input, global_state::ForwardContext &context) const override { + auto &runtime = context.require_runtime(); + if (runtime.isGraphRecording()) { + throw std::invalid_argument("Clover requires eager execution."); + } + context.diffusion_preview = input.diffusion_preview; + context.diffusion_expert_budget = input.diffusion_expert_budget; + context.attn_metadata.diffusion_preview = input.diffusion_preview; + context.diffusion_block_size = model_config_->get("block_size"); + // The MRoPE provider takes a 1-D packed [tokens] row, or a 2-D + // [3, tokens] axis-row form for multimodal callers. Anything else + // reaching the device would be an out-of-bounds read in release + // builds. Every Clover forward passes through here: prompt prefill, + // block preview and causal replay, so the shape is checked before + // any submit on all three paths. + if (input.input_ids && input.position_ids) { + const auto tokens = input.input_ids.value()->numel(); + const auto &positions = input.position_ids.value(); + const auto pos_rank = positions->ndim(); + const bool packed = pos_rank == 1 && positions->size(0) == tokens; + const bool axis_rows = pos_rank == 2 && positions->size(0) == 3 && positions->size(1) == tokens; + if (!packed && !axis_rows) { + throw std::invalid_argument( + "Clover positions must be [tokens] or [3, tokens]."); + } + } + if (!input.diffusion_preview) { + denoise_step_ = 0; + } + if (input.diffusion_preview) { + const auto &ids = input.input_ids.value(); + const auto tokens = ids->numel(); + if (!input.sample_all_positions || tokens % context.diffusion_block_size) { + throw std::invalid_argument("Clover preview requires complete blocks and all-position logits."); + } + // Every layer of the preview is written for exactly one block of + // one request: the block convolution and the coreset route per + // request, and the static attention lifts the causal mask for the + // whole suffix. Inputs that merely divide by the block size, like + // [2, 16] or [1, 64], would silently take unsupported paths. + if (ids->ndim() != 2 || ids->size(0) != 1 || ids->size(1) != static_cast(context.diffusion_block_size)) { + throw std::invalid_argument( + "Clover preview input must be [1, block_size]."); + } + context.diffusion_valid = runtime::Tensor::empty(runtime, {tokens}, runtime::DataType::kInt8); + execution::submit(runtime, infini::ops::Fill::DefaultConfig(runtime.device().type()), + context.diffusion_valid, 1.0, context.diffusion_valid); + if (input.diffusion_expert_budget) { + bool refresh = denoise_step_ % 5 == 0 || !previous_budget_; + const auto &ids = input.input_ids.value(); + if (!previous_ids_ || previous_ids_->shape() != ids->shape()) { + previous_ids_ = runtime::Tensor::empty(runtime, ids->shape(), ids->dtype()); + refresh = true; + } + context.diffusion_live = runtime::Tensor::empty(runtime, {tokens}, runtime::DataType::kInt8); + execution::submit(runtime, execution::RecordingPolicy::HostOnly, + infini::ops::CloverLiveMask::DefaultConfig(runtime.device().type()), ids, previous_ids_, + static_cast(model_config_->get("mask_token_id")), refresh, context.diffusion_live); + } + previous_budget_ = input.diffusion_expert_budget; + ++denoise_step_; + } + return Base::forward(input, context); + } + + void reset_cache(const cache::CacheConfig *cache_config, global_state::ForwardContext &context, + backends::AttentionBackend backend, const engine::distributed::RankInfo &rank) override { + if (backend != backends::AttentionBackend::STATIC_ATTN) { + throw std::invalid_argument("Clover currently requires the static attention backend."); + } + auto &runtime = context.require_runtime(); + denoise_step_ = 0; + previous_budget_ = false; + previous_ids_.reset(); + const auto *current = dynamic_cast(cache_config_.get()); + const auto *requested = dynamic_cast(cache_config); + if (current && requested && current->max_batch_size() == requested->max_batch_size() + && current->max_cache_len() == requested->max_cache_len()) { + // The allocation helpers create contiguous, owning cache tensors. + // Clear all three caches before admitting the next request. + for (auto *layers : {&context.kv_cache_vec, &context.conv_state_vec, &context.ssm_state_vec}) { + for (auto &tensor : *layers) { + if (tensor && tensor->nbytes()) { + runtime.setDeviceMemoryAsync(tensor->data(), 0, tensor->nbytes(), runtime.stream()); + } + } + } + runtime.syncStream(); + return; + } + auto allocated = qwen3_next::qwen3_next_allocate_cache_tensors( + runtime, rank, cache_config, model_config_, backend, runtime::DataType::kFloat32); + context.kv_cache_vec = std::move(allocated.kv_cache_tensors); + context.conv_state_vec = std::move(allocated.conv_state_tensors); + context.ssm_state_vec = std::move(allocated.ssm_state_tensors); + cache_config_ = cache_config ? cache_config->unique_copy() : nullptr; + } + +private: + mutable size_t denoise_step_{0}; + mutable bool previous_budget_{false}; + mutable runtime::Tensor previous_ids_; +}; + +std::shared_ptr create_clover_config(std::shared_ptr config) { + if (config->get_dtype() != runtime::DataType::kBFloat16) { + throw std::invalid_argument("Clover requires BF16 model weights."); + } + auto &json = config->get_config_json(); + if (json.at("model_type") != "clover_moe" || json.at("block_size") != 32 || json.at("linear_key_head_dim") != 128 || json.at("linear_value_head_dim") != 128 || json.at("linear_conv_kernel_dim") != 4 || json.at("num_experts") != 256 || json.at("num_experts_per_tok") != 8) { + throw std::invalid_argument("Unsupported Clover architecture."); + } + json["norm_topk_prob"] = true; + json["position_id_axes"] = 1; + json["rope_parameters"]["mrope_section"] = {16, 8, 8}; + json["rope_parameters"]["mrope_interleaved"] = false; + return qwen3_5::prepare_qwen3_5_model_config(config); +} + +} // namespace infinilm::models::clover_moe + +namespace { +INFINILM_REGISTER_EXPLICIT_CAUSAL_LM_MODEL(clover_moe, + infinilm::models::clover_moe::CloverForCausalLM, + infinilm::models::clover_moe::create_clover_config); +} diff --git a/csrc/models/clover_moe/clover_gdn.cpp b/csrc/models/clover_moe/clover_gdn.cpp new file mode 100644 index 000000000..0d68f9a98 --- /dev/null +++ b/csrc/models/clover_moe/clover_gdn.cpp @@ -0,0 +1,107 @@ +#include "clover_gdn.hpp" +#include "../../global_state/forward_context.hpp" +#include "execution/submit.hpp" +#include "runtime/runtime.hpp" +#include +#include +#include + +namespace infinilm::models::clover_moe { + +CloverGatedDeltaNet::CloverGatedDeltaNet(runtime::Runtime &runtime, std::shared_ptr config, + size_t layer, const engine::distributed::RankInfo &rank, + backends::AttentionBackend backend, const layers::moe::EPConfig &ep) + : Qwen3NextGatedDeltaNet(runtime, config, layer, rank, backend, ep), + tp_rank_(rank.tp_rank), tp_size_(rank.tp_size), + full_key_dim_(local_key_dim_ * tp_size_), full_value_dim_(local_value_dim_ * tp_size_) { + try { + const auto dtype = config->get_dtype(); + right_weight_ = weights::Weight(runtime, {2 * full_key_dim_ + full_value_dim_, 1, 3}, dtype); + bind_weight("conv_right_weight", right_weight_); + const auto heads = config->get("linear_num_value_heads"); + logit_scale_ = weights::Weight(runtime, {heads}, dtype, 0, tp_rank_, tp_size_); + history_bias_ = weights::Weight(runtime, {heads}, dtype, 0, tp_rank_, tp_size_); + history_c_ = weights::Weight(runtime, {heads}, dtype, 0, tp_rank_, tp_size_); + bind_weight("bd_softmax_logit_scale", logit_scale_); + bind_weight("bd_softmax_history_bias", history_bias_); + bind_weight("bd_softmax_history_c", history_c_); + } catch (...) { + runtime.syncStream(); + throw; + } +} + +void CloverGatedDeltaNet::process_weights_after_loading(runtime::Runtime &runtime, bool) { + conv_weight_ = conv1d_->state_dict().at("weight").tensor(); + auto local = runtime::Tensor::empty(runtime, {2 * local_key_dim_ + local_value_dim_, 1, 3}, right_weight_->dtype()); + for (size_t part = 0; part < 3; ++part) { + const size_t width = part == 2 ? local_value_dim_ : local_key_dim_; + const size_t src = part * full_key_dim_ + tp_rank_ * width; + const size_t dst = part * local_key_dim_; + local->narrow({{0, dst, width}})->copy_from(runtime, right_weight_->narrow({{0, src, width}})); + } + runtime.syncStream(); + right_weight_ = weights::Weight(local); + local_weights_["conv_right_weight"] = right_weight_; +} + +runtime::Tensor CloverGatedDeltaNet::forward(const runtime::Tensor &hidden, + const global_state::ForwardContext &context) const { + auto &runtime = context.require_runtime(); + auto input = hidden; + const size_t tokens = hidden->size(0) * hidden->size(1); + auto qkv = in_proj_qkv_->forward(runtime, input)->view({1, tokens, 2 * local_key_dim_ + local_value_dim_}); + auto z = in_proj_z_->forward(runtime, input); + auto a = in_proj_a_->forward(runtime, input)->view({1, tokens, local_num_value_heads_}); + auto b = in_proj_b_->forward(runtime, input)->view({1, tokens, local_num_value_heads_}); + const auto device = runtime.device().type(); + runtime::Tensor mixed; + if (context.diffusion_preview) { + auto flat = qkv->view({tokens, qkv->size(2)}); + auto out = runtime::Tensor::empty(runtime, flat->shape(), flat->dtype()); + execution::submit( + runtime, execution::RecordingPolicy::HostOnly, + infini::ops::CloverBlockConv1d::DefaultConfig(device), + flat, context.conv_state_vec[layer_idx_], context.mamba_metadata.init_state_indices.value(), + conv_weight_, right_weight_.tensor(), context.diffusion_valid, context.diffusion_block_size, out); + mixed = out->view(qkv->shape()); + } else { + mixed = conv1d_->forward(qkv, context); + } + auto q = mixed->narrow({{2, 0, local_key_dim_}})->as_strided({1, tokens, local_num_key_heads_, key_head_dim_}, {mixed->stride(0), mixed->stride(1), static_cast(key_head_dim_), 1}); + auto k = mixed->narrow({{2, local_key_dim_, local_key_dim_}})->as_strided(q->shape(), q->strides()); + auto v = mixed->narrow({{2, 2 * local_key_dim_, local_value_dim_}})->as_strided({1, tokens, local_num_value_heads_, value_head_dim_}, {mixed->stride(0), mixed->stride(1), static_cast(value_head_dim_), 1}); + auto g = runtime::Tensor::empty(runtime, a->shape(), runtime::DataType::kFloat32); + auto beta = runtime::Tensor::empty(runtime, a->shape(), runtime::DataType::kFloat32); + execution::submit( + runtime, execution::RecordingPolicy::HostOnly, + infini::ops::FusedGatedDeltaNetGating::DefaultConfig(device), + A_log_.tensor(), a, b, dt_bias_.tensor(), 1.0f, 20.0f, g, beta); + auto out = runtime::Tensor::empty(runtime, v->shape(), v->dtype()); + if (context.diffusion_preview) { + execution::submit( + runtime, execution::RecordingPolicy::HostOnly, + infini::ops::CloverLocalMemory::DefaultConfig(device), + q, k, v, g, context.ssm_state_vec[layer_idx_], context.mamba_metadata.init_state_indices.value(), + context.diffusion_valid, logit_scale_.tensor(), history_bias_.tensor(), history_c_.tensor(), + context.diffusion_block_size, out); + } else { + // Causal replay of the block: the packed form of the recurrence, which + // reads the state slot of every request and writes its final slot. + execution::submit( + runtime, execution::RecordingPolicy::HostOnly, + infini::ops::RecurrentGatedDeltaRule::DefaultConfig(device), + q, k, v, g, beta, context.ssm_state_vec[layer_idx_], + context.mamba_metadata.input_offsets.value(), + context.mamba_metadata.init_state_indices.value(), + context.mamba_metadata.final_state_indices.value(), out, true); + } + auto normalized = norm_->forward(runtime, out->view({tokens * local_num_value_heads_, value_head_dim_})); + normalized = normalized->view(z->shape()); + auto gate = runtime::Tensor::empty(runtime, z->shape(), z->dtype()); + execution::submit(runtime, infini::ops::Silu::DefaultConfig(device), z, gate); + execution::submit(runtime, infini::ops::Mul::DefaultConfig(device), normalized, gate, normalized); + return out_proj_->forward(runtime, normalized); +} + +} // namespace infinilm::models::clover_moe diff --git a/csrc/models/clover_moe/clover_gdn.hpp b/csrc/models/clover_moe/clover_gdn.hpp new file mode 100644 index 000000000..36589dc1d --- /dev/null +++ b/csrc/models/clover_moe/clover_gdn.hpp @@ -0,0 +1,22 @@ +#pragma once + +#include "../qwen3_next/qwen3_next_gated_deltanet.hpp" + +namespace infinilm::models::clover_moe { + +class CloverGatedDeltaNet : public qwen3_next::Qwen3NextGatedDeltaNet { +public: + CloverGatedDeltaNet(runtime::Runtime &runtime, std::shared_ptr config, + size_t layer, const engine::distributed::RankInfo &rank, + backends::AttentionBackend backend, const layers::moe::EPConfig &ep); + runtime::Tensor forward(const runtime::Tensor &hidden, + const global_state::ForwardContext &context) const; + void process_weights_after_loading(runtime::Runtime &runtime, bool pre_transpose) override; + +private: + weights::Weight right_weight_, logit_scale_, history_bias_, history_c_; + runtime::Tensor conv_weight_; + size_t tp_rank_, tp_size_, full_key_dim_, full_value_dim_; +}; + +} // namespace infinilm::models::clover_moe diff --git a/csrc/models/clover_moe/clover_moe.cpp b/csrc/models/clover_moe/clover_moe.cpp new file mode 100644 index 000000000..9b699680c --- /dev/null +++ b/csrc/models/clover_moe/clover_moe.cpp @@ -0,0 +1,104 @@ +#include "clover_moe.hpp" +#include "../../global_state/forward_context.hpp" +#include "../../layers/linear/dense.hpp" +#include "execution/submit.hpp" +#include +#include +#include + +namespace infinilm::models::clover_moe { + +CloverSparseMoe::CloverSparseMoe(runtime::Runtime &runtime, std::shared_ptr config, + size_t layer, const engine::distributed::RankInfo &rank, + backends::AttentionBackend backend, const layers::moe::EPConfig &ep) + : Qwen3NextSparseMoeBlock(runtime, config, layer, rank, backend, ep), + coreset_(config->get_or("moe_block_coreset_enabled", true)), + top_p_(config->get_or("moe_block_coreset_top_p", 0.9)), + top_k_(config->get("num_experts_per_tok")) { + router_weight_ = gate_->state_dict().at("weight").tensor(); +} + +std::tuple CloverSparseMoe::route( + runtime::Runtime &runtime, const runtime::Tensor &hidden, + const global_state::ForwardContext &context) const { + if (!context.diffusion_preview || (!coreset_ && !context.diffusion_expert_budget)) { + return gate_->forward(runtime, hidden); + } + auto logits = layers::linear::dense_projection(runtime, hidden, router_weight_, std::nullopt, 1.0f); + auto masked = logits; + const auto device = runtime.device().type(); + if (coreset_) { + masked = runtime::Tensor::empty(runtime, logits->shape(), logits->dtype()); + execution::submit(runtime, execution::RecordingPolicy::HostOnly, + infini::ops::CloverCoreset::DefaultConfig(device), logits, context.diffusion_block_size, top_p_, masked); + } + const auto active_top_k = context.diffusion_expert_budget ? size_t{4} : top_k_; + auto weights = runtime::Tensor::empty(runtime, {hidden->size(0), active_top_k}, runtime::DataType::kFloat32); + auto indices = runtime::Tensor::empty(runtime, weights->shape(), runtime::DataType::kInt32); + auto scratch = runtime::Tensor::empty(runtime, weights->shape(), runtime::DataType::kInt32); + execution::submit(runtime, execution::RecordingPolicy::HostOnly, + infini::ops::TopkSoftmax::DefaultConfig(device), masked, + std::optional{}, std::optional{}, true, + weights, indices, scratch); + return {weights, indices}; +} + +infinilm::runtime::Tensor CloverSparseMoe::forward(infinilm::runtime::Runtime &runtime, + const infinilm::runtime::Tensor &hidden_states, + const global_state::ForwardContext &context) const { + ASSERT(hidden_states->ndim() == 3); + + auto shape = hidden_states->shape(); + auto hidden_states_reshaped = hidden_states->view({shape[0] * shape[1], shape[2]}); + + auto [routing_weights, selected_experts] = route(runtime, hidden_states_reshaped, context); + if (context.diffusion_preview && context.diffusion_expert_budget) { + execution::submit(runtime, execution::RecordingPolicy::HostOnly, + infini::ops::CloverMaskRoutes::DefaultConfig(runtime.device().type()), + selected_experts, context.diffusion_live, int64_t{256}, selected_experts); + } + infinilm::layers::moe::TopKOutput topk_output{ + routing_weights, + selected_experts, + infinilm::runtime::Tensor(), + }; + auto routed_states = fused_moe_->forward( + runtime, hidden_states_reshaped, + topk_output, + experts_->moe_weights()); + if (context.diffusion_preview && context.diffusion_expert_budget) { + if (!cached_routed_ || cached_routed_->shape() != routed_states->shape()) { + cached_routed_ = runtime::Tensor::empty(runtime, routed_states->shape(), routed_states->dtype()); + } + execution::submit(runtime, execution::RecordingPolicy::HostOnly, + infini::ops::CloverMergeMoe::DefaultConfig(runtime.device().type()), + routed_states, context.diffusion_live, cached_routed_, routed_states); + } + + auto shared_states = shared_expert_->forward(runtime, hidden_states); + auto hidden_states_for_gate = hidden_states; + const auto ops_input = shared_expert_gate_->forward(runtime, hidden_states_for_gate); + auto shared_gate = infinilm::runtime::Tensor::empty(runtime, ops_input->shape(), ops_input->dtype()); + infinilm::execution::submit( + runtime, infini::ops::Sigmoid::DefaultConfig(runtime.device().type()), ops_input, shared_gate); + INFINILM_TRACE_OP(Sigmoid, shared_gate); + shared_gate = shared_gate->as_strided(shared_states->shape(), {shared_gate->stride(0), shared_gate->stride(1), 0}); + { + auto ops_output = infinilm::runtime::Tensor::empty(runtime, shared_states->shape(), shared_states->dtype()); + infinilm::execution::submit( + runtime, infini::ops::Mul::DefaultConfig(runtime.device().type()), shared_states, shared_gate, ops_output); + INFINILM_TRACE_OP(Mul, ops_output); + shared_states = std::move(ops_output); + } + + auto routed_states_3d = routed_states->as_strided( + {shape[0], shape[1], shape[2]}, + {static_cast(shape[1] * shape[2]), static_cast(shape[2]), 1}); + auto ops_output = infinilm::runtime::Tensor::empty(runtime, routed_states_3d->shape(), routed_states_3d->dtype()); + infinilm::execution::submit( + runtime, infini::ops::Add::DefaultConfig(runtime.device().type()), routed_states_3d, shared_states, ops_output); + INFINILM_TRACE_OP(Add, ops_output); + return ops_output; +} + +} // namespace infinilm::models::clover_moe diff --git a/csrc/models/clover_moe/clover_moe.hpp b/csrc/models/clover_moe/clover_moe.hpp new file mode 100644 index 000000000..8c1bd558e --- /dev/null +++ b/csrc/models/clover_moe/clover_moe.hpp @@ -0,0 +1,26 @@ +#pragma once + +#include "../../global_state/forward_context.hpp" +#include "../qwen3_next/qwen3_next_sparse_moe_block.hpp" + +namespace infinilm::models::clover_moe { + +class CloverSparseMoe : public qwen3_next::Qwen3NextSparseMoeBlock { +public: + CloverSparseMoe(runtime::Runtime &runtime, std::shared_ptr config, + size_t layer, const engine::distributed::RankInfo &rank, + backends::AttentionBackend backend, const layers::moe::EPConfig &ep); + runtime::Tensor forward(runtime::Runtime &runtime, const runtime::Tensor &hidden, + const global_state::ForwardContext &context) const; + +private: + std::tuple route(runtime::Runtime &runtime, + const runtime::Tensor &hidden, const global_state::ForwardContext &context) const; + runtime::Tensor router_weight_; + mutable runtime::Tensor cached_routed_; + bool coreset_; + double top_p_; + size_t top_k_; +}; + +} // namespace infinilm::models::clover_moe diff --git a/csrc/models/infinilm_model.hpp b/csrc/models/infinilm_model.hpp index 073bd4681..f35e38bfb 100644 --- a/csrc/models/infinilm_model.hpp +++ b/csrc/models/infinilm_model.hpp @@ -67,6 +67,8 @@ class InfinilmModel : public infinilm::weights::ModelWeights { /// Preserve logits for every packed position for speculative/MTP callers. bool sample_all_positions{false}; size_t logical_kv_upper_bound{0}; + bool diffusion_preview{false}; + bool diffusion_expert_budget{false}; }; struct Output { diff --git a/csrc/models/qwen3_next/qwen3_next_allocate_kv_cache_tensors.cpp b/csrc/models/qwen3_next/qwen3_next_allocate_kv_cache_tensors.cpp index d838120c8..cf2c6c2ea 100644 --- a/csrc/models/qwen3_next/qwen3_next_allocate_kv_cache_tensors.cpp +++ b/csrc/models/qwen3_next/qwen3_next_allocate_kv_cache_tensors.cpp @@ -16,7 +16,8 @@ AllocatedHybridCache qwen3_next_allocate_cache_tensors( const engine::distributed::RankInfo &rank_info, const cache::CacheConfig *cache_config, const std::shared_ptr &text_config, - const backends::AttentionBackend &attention_backend) { + const backends::AttentionBackend &attention_backend, + std::optional ssm_state_dtype) { if (nullptr == cache_config) { return {}; } @@ -73,7 +74,7 @@ AllocatedHybridCache qwen3_next_allocate_cache_tensors( linear_value_head_dim, linear_num_key_heads, linear_num_value_heads, - dtype, + ssm_state_dtype.value_or(dtype), pool_size); kv_cache_vec.emplace_back(); diff --git a/csrc/models/qwen3_next/qwen3_next_allocate_kv_cache_tensors.hpp b/csrc/models/qwen3_next/qwen3_next_allocate_kv_cache_tensors.hpp index 3e123677f..a4986c7fd 100644 --- a/csrc/models/qwen3_next/qwen3_next_allocate_kv_cache_tensors.hpp +++ b/csrc/models/qwen3_next/qwen3_next_allocate_kv_cache_tensors.hpp @@ -6,6 +6,7 @@ #include "../../config/model_config.hpp" #include +#include #include #include #include @@ -23,6 +24,7 @@ AllocatedHybridCache qwen3_next_allocate_cache_tensors( const engine::distributed::RankInfo &rank_info, const cache::CacheConfig *cache_config, const std::shared_ptr &text_config, - const backends::AttentionBackend &attention_backend); + const backends::AttentionBackend &attention_backend, + std::optional ssm_state_dtype = std::nullopt); } // namespace infinilm::models::qwen3_next diff --git a/csrc/models/qwen3_next/qwen3_next_gated_deltanet.hpp b/csrc/models/qwen3_next/qwen3_next_gated_deltanet.hpp index a74578fa9..aba19843d 100644 --- a/csrc/models/qwen3_next/qwen3_next_gated_deltanet.hpp +++ b/csrc/models/qwen3_next/qwen3_next_gated_deltanet.hpp @@ -64,7 +64,7 @@ class Qwen3NextGatedDeltaNet : public infinilm::weights::ModelWeights { infinilm::runtime::Tensor forward(const infinilm::runtime::Tensor &hidden_states, const infinilm::global_state::ForwardContext &forward_context) const; -private: +protected: std::shared_ptr in_proj_qkv_; std::shared_ptr in_proj_z_; std::shared_ptr in_proj_a_; diff --git a/csrc/pybind11/bindings.cc b/csrc/pybind11/bindings.cc index 4a4dda6aa..2ef7d37c3 100644 --- a/csrc/pybind11/bindings.cc +++ b/csrc/pybind11/bindings.cc @@ -37,6 +37,10 @@ PYBIND11_MODULE(_infinilm, m) { || !checkpoint_float(input->dtype()) || !checkpoint_float(output->dtype())) { throw std::invalid_argument("checkpoint Cast requires matching CPU shapes and FP32/FP16/BF16 tensors"); } + if (input->numel() != 0 && input->data() == output->data() + && input->dtype() != output->dtype()) { + throw std::invalid_argument("checkpoint dtype conversion requires distinct storage"); + } const infini::ops::Tensor input_view{input->view()}; const infini::ops::Tensor output_view{output->view()}; infini::ops::Cast::Call(input_view, output_view); }, py::arg("input"), py::arg("output"), py::call_guard()); diff --git a/csrc/pybind11/engine/engine.hpp b/csrc/pybind11/engine/engine.hpp index 2fbcdeec1..5927ecfe4 100644 --- a/csrc/pybind11/engine/engine.hpp +++ b/csrc/pybind11/engine/engine.hpp @@ -233,6 +233,8 @@ inline void bind_infer_engine(py::module &m) { "random_values", "sampling_rows", "nsa_owner_snapshot", + "diffusion_preview", + "diffusion_expert_budget", }; for (auto &item : kwargs) { @@ -243,7 +245,11 @@ inline void bind_infer_engine(py::module &m) { "InferEngine.Input got an unexpected keyword argument '" + key + "'"); } - if (key == "temperature") { + if (key == "diffusion_expert_budget") { + input.diffusion_expert_budget = py::cast(item.second); + } else if (key == "diffusion_preview") { + input.diffusion_preview = py::cast(item.second); + } else if (key == "temperature") { input.temperature = py::cast(item.second); } else if (key == "top_p") { input.top_p = py::cast(item.second); @@ -303,6 +309,8 @@ inline void bind_infer_engine(py::module &m) { .def_readwrite("visual_token_ranges", &InferEngine::Input::visual_token_ranges) .def_readwrite("target_hidden_states", &InferEngine::Input::target_hidden_states) .def_readwrite("sample_all_positions", &InferEngine::Input::sample_all_positions) + .def_readwrite("diffusion_preview", &InferEngine::Input::diffusion_preview) + .def_readwrite("diffusion_expert_budget", &InferEngine::Input::diffusion_expert_budget) .def_readwrite("temperature", &InferEngine::Input::temperature) .def_readwrite("top_k", &InferEngine::Input::top_k) .def_readwrite("top_p", &InferEngine::Input::top_p) diff --git a/docs/clover.md b/docs/clover.md new file mode 100644 index 000000000..9ed702e0c --- /dev/null +++ b/docs/clover.md @@ -0,0 +1,333 @@ +# Clover block diffusion + +`clover_moe` loads the complete Clover-35B-A3B-Preview checkpoint, including its +right-convolution and bidirectional GDN scalar shards. Model forward runs in +InfiniLM C++; InfiniOps supplies the device kernels, on NVIDIA and on Hygon. +NVIDIA uses native CUDA Clover kernels. The Hygon stack also uses Triton +kernels compiled on first use. Torch is used by the Python decoder for confidence selection, not +as a model-forward fallback. + +The model currently requires BF16 weights. Validated configurations: TP=2 on +two NVIDIA A100 80GB (CUDA 13.1) and TP=2 on two Hygon BW 64GB devices (DTK +26.04), both eager execution, static cache, and 32-token diffusion blocks. The +chat endpoint serializes requests and supports greedy, non-streaming text +generation. The measurements below cover concurrency one and short prompts; +they are not a measurement of maximum concurrent-serving capacity or +128K-context performance. + +## Build + +Build InfiniRT, InfiniOps and InfiniCCL for the selected platform, then +install InfiniLM using the common step below. + +### NVIDIA + +```sh +export INFINI_ROOT=/path/to/installed-stack +export CUDA_HOME=/usr/local/cuda +export LD_LIBRARY_PATH="$INFINI_ROOT/lib:$CUDA_HOME/lib64:$LD_LIBRARY_PATH" +cmake -S third_party/InfiniCore/submodules/InfiniRT -B build/rt \ + -DCMAKE_INSTALL_PREFIX="$INFINI_ROOT" -DWITH_CPU=ON -DWITH_NVIDIA=ON +cmake --build build/rt -j 12 +cmake --install build/rt +cmake -S third_party/InfiniCore/submodules/InfiniOps -B build/ops \ + -DINFINI_OPS_OPS="$PWD/third_party/InfiniCore/submodules/InfiniOps/scripts/configs/infiniops_ops_nvidia_infinilm.json" \ + -DCMAKE_INSTALL_PREFIX="$INFINI_ROOT" \ + -DINFINI_RT_ROOT="$INFINI_ROOT" -DWITH_CPU=ON -DWITH_NVIDIA=ON \ + -DWITH_TRITON=ON -DCMAKE_CUDA_ARCHITECTURES=80 \ + -DGENERATE_PYTHON_BINDINGS=ON \ + -DAUTO_DETECT_DEVICES=OFF -DAUTO_DETECT_BACKENDS=OFF +cmake --build build/ops -j 12 +cmake --install build/ops +cmake -S third_party/InfiniCore/submodules/InfiniCCL -B build/ccl \ + -DCMAKE_INSTALL_PREFIX="$INFINI_ROOT" -DWITH_NVIDIA=ON -DWITH_NCCL=ON \ + -DAUTO_DETECT_DEVICES=OFF -DBUILD_EXAMPLES=OFF +cmake --build build/ccl -j 12 +cmake --install build/ccl +``` + +Set `CMAKE_CUDA_ARCHITECTURES` to the real target arch (e.g. `80` for A100); +the default `75` compiles but CUTLASS bf16 MMA paths fail at runtime. + +### Hygon + +```sh +export INFINI_ROOT=/path/to/installed-stack +export CUDA_HOME=/opt/dtk/cuda/cuda +export LD_LIBRARY_PATH="$INFINI_ROOT/lib:$CUDA_HOME/lib64:$LD_LIBRARY_PATH" +cmake -S third_party/InfiniCore/submodules/InfiniRT -B build/rt \ + -DCMAKE_INSTALL_PREFIX="$INFINI_ROOT" -DWITH_CPU=ON -DWITH_HYGON=ON +cmake --build build/rt -j 12 +cmake --install build/rt +cmake -S third_party/InfiniCore/submodules/InfiniOps -B build/ops \ + -DCMAKE_BUILD_TYPE=Release \ + -DINFINI_OPS_OPS="$PWD/third_party/InfiniCore/submodules/InfiniOps/scripts/configs/infiniops_ops_hygon_infinilm.json" \ + -DCMAKE_INSTALL_PREFIX="$INFINI_ROOT" \ + -DINFINI_RT_ROOT="$INFINI_ROOT" -DWITH_CPU=ON -DWITH_HYGON=ON \ + -DWITH_TRITON=ON -DHYGON_ARCH=gfx936 -DGENERATE_PYTHON_BINDINGS=ON \ + -DAUTO_DETECT_DEVICES=OFF -DAUTO_DETECT_BACKENDS=OFF +cmake --build build/ops -j 12 +cmake --install build/ops +cmake -S third_party/InfiniCore/submodules/InfiniCCL -B build/ccl \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_INSTALL_PREFIX="$INFINI_ROOT" -DWITH_HYGON=ON -DWITH_NCCL=ON \ + -DAUTO_DETECT_DEVICES=OFF -DBUILD_EXAMPLES=OFF +cmake --build build/ccl -j 12 +cmake --install build/ccl +``` + +Match the C++ ABI to the installed DTK Torch build. `gfx936` is the tested +architecture, not a default for all Hygon products. + +With the InfiniOps revision of PR #1015 the fused MoE runs native `gfx936` +kernels instead of Triton; `INFINI_OPS_HYGON_MOE_TRITON=1` selects the Triton +kernels (see [Native fused MoE on gfx936](#native-fused-moe-on-gfx936)). + +### Common + +```sh +export INFINILM_CXX11_ABI=1 +xmake f -y -m release --cxx11-abi=1 +pip install -e '.[server,torch-compat]' --no-build-isolation +``` + +Clover needs the Torch checkpoint path (`torch-compat`) for checkpoint +loading, confidence selection and the diffusion tests, and the server +entry point (`server`) when it is served; drop `server` for local +generation only. Triton itself is a runtime dependency of the InfiniOps +`infini` package, not of InfiniLM: the DTK Torch wheel ships it, and the +environment must provide the same Triton the InfiniOps stack was built +with. + +Install the InfiniOps Python +package as `infini` as well: its JIT compiler and kernel sources must remain +importable. A direct CMake install puts that package at the install prefix; +placing a link named `infini` to this prefix in a Python search directory is +sufficient for a development build. A wheel installs this namespace normally. + +`INFINI_OPS_OPS` selects what the InfiniOps build generates. The profiles +live in the InfiniOps checkout, beside its own build profiles, and are +documented in its `docs/build-hygon-inference.md`: they list every operator +InfiniLM references, with the providers of the platform or as +`public_api_only` where there are none. The latter keep the complete InfiniLM +source compiling while those model families report unsupported; they install +no substitute kernels. The NVIDIA profile also covers the lean build above, +which leaves a few operators without providers — `upsample_bicubic2d` has +no NVIDIA provider under any backend flag, as in InfiniOps' own torch-free +profiles. Update the profiles when InfiniLM references another operator or a +platform gains a provider. + +The `pip install -e` step copies the Infini libraries from `$INFINI_ROOT/lib` +into `python/infinilm/_lib`, and the package loads those copies. Repeat it +after rebuilding an Infini library; otherwise the model keeps running the +previous build. + +The build types match the entries the top-level README uses: `pip install` +builds InfiniOps as Release (the scikit-build-core default) and +`scripts/build.sh` builds InfiniCCL as Release, while the InfiniRT command +sets none. Without a build type CMake adds no optimization flags. Release also +defines `NDEBUG`, which compiles out InfiniOps' operator-contract `assert`s; +drop it from the InfiniOps command when diagnosing rejected operator +arguments. + +## Generate and serve + +`device` accepts the framework's device names and aliases (`cuda`/`nvidia`, +`hygon`, …); `tp` defaults to 1, and the server's `--device` defaults to +`auto` (auto-detects the local platform like the main inference server). The +examples below use NVIDIA names; on Hygon pass `hygon` and select the devices +with `HIP_VISIBLE_DEVICES`. + +```python +from infinilm.diffusion.clover import CloverGenerator + +generator = CloverGenerator('/path/to/Clover-35B-A3B-Preview', tp=2, max_context=2048, device='nvidia') +result = generator.generate('What is the capital of France?', max_new_tokens=64) +print(result.text) +``` + +A single-process smoke test with three prompts: + +```sh +python examples/test_clover.py --device nvidia --model /path/to/Clover-35B-A3B-Preview +``` + +```sh +CUDA_VISIBLE_DEVICES=0,1 python -m infinilm.server.clover_server \ + --model /path/to/Clover-35B-A3B-Preview --tp 2 --max-context 2048 \ + --policy frontier --expert-budget --frontier-floor 0.7 --port 8000 +``` + +Send ordinary `/v1/chat/completions` requests with `temperature: 0` and +`stream: false`. Optional request fields are `diffusion_policy` (`baseline` or +`frontier`), `expert_budget`, and `frontier_confidence_floor`. Neutral repetition, +presence and frequency penalties and thinking disabled define the tested lane. +Nonzero penalties, stochastic sampling and streaming receive explicit errors. + +## Methods and state contract + +Preview reads the committed convolution/GDN state. Full attention can read the +causal prefix and all positions within the current block. Preview KV writes are +confined to the uncommitted suffix. Every block is fully resolved before causal +replay updates persistent state. Mask tokens are never emitted or committed. + +`baseline` uses the checkpoint's 0.95 low-confidence rule with top-one progress +when no masked position clears the threshold. `frontier` adapts the target +stride from Ringssss/dLLM-serve V3. It retains all positions above 0.95, adds +safe positions toward the stride, and guarantees progress. Its confidence +floor is explicit because lowering it changes decoding and can harm output. + +`expert_budget` adapts the supplied dllm-h100 study's top-4 expert budget and +TV6 decoded-row reuse with refresh interval five. Clover's own block coreset +continues to define the allowed experts. A token is eligible for reuse only +when it was unmasked in both consecutive previews. Inactive routes are omitted +from expert alignment/GEMMs and their previously combined outputs are restored. +Shared experts and causal replay still compute normally. State is reset at each +new block/request. These are optional approximate preview optimizations. + +This port does not implement the H100 code's DP/EP sequence-parallel communication +pipeline, or dLLM-serve's complete admission/compaction scheduler. The serial +endpoint exposes the mechanisms validated here. It also does not implement +Clover's separate self-speculative AR-verification serving mode. + +Source provenance: + +- dLLM-serve: `1da50a96c9ce6b888d245d378f2bac0425feba8c`, + `cwsrpt_v2/algorithm/cw_srpt_v3.py`, Apache-2.0; retained license/notice under + `python/infinilm/licenses/dLLM-serve`. +- Supplied dllm-h100 archive: top-4 routing and refresh/live-row logic in + `codex_coding/src/{test_m_skip_sweep.py,tv6_patch.py}`; reimplemented for the + Clover softmax router and InfiniLM state ownership. +- Preview kernels are provided and attributed by the companion InfiniOps PR. + +## Validation and measurement + +The native baseline matched the local SGLang Clover port's output tokens on +four initial prompts. Operator comparisons cover preview convolution/GDN, +clean-state immutability, packed recurrent commits, expert selection, fused +MoE, liveness and cached-row merging. Broader generative outputs can differ +across kernel implementations even with identical sampling settings. + +The throughput numbers below were recorded with TP=2, on two Hygon BW 64GB +devices and on two NVIDIA A100 80GB. + +The recorded HTTP campaign uses the same model, tokenizer, BF16 precision, +TP2 budget, prompts, per-request output caps and sampling controls. Each of five +lanes ran 32 prompts three times after a separate warmup, alternating lane +order. Throughput is visible completion tokens, retokenized identically, divided +by summed client request time. SGLang's diffusion usage counters can include +block padding, so they are not used as the numerator. Results and the exact +workload are recorded in the PR evidence; no profiling run contributes to timing. + +A portable client and the controlled 32-prompt workload are included: + +```sh +python examples/bench_clover.py --url http://127.0.0.1:8000 --model clover \ + --tokenizer /path/to/Clover-35B-A3B-Preview --output native.jsonl +python examples/bench_clover.py --url http://127.0.0.1:8001 --model /served/model/name \ + --tokenizer /path/to/Clover-35B-A3B-Preview --backend sglang --variants baseline --output sglang.jsonl +``` + +Repeat `-1` is warmup and must be excluded. Sum `visible_tokens` over successful +requests and divide by summed `elapsed_s` over all measured requests, retaining +failures. Keep model weights, TP, sampling, output caps and context capacity fixed. + +### Native fused MoE on gfx936 + +On `gfx936` the Hygon provider of `MoeFusedDense` runs native kernels for +block size 16 with hidden and intermediate sizes that are multiples of 8 of at +least 32, which covers the Clover shapes. One wavefront streams two 16-row +weight bands of an expert block and feeds the matrix instructions through +shared memory; the Triton kernels use the same instruction with one 16 x 64 +output tile per four-wavefront workgroup. Other shapes, other Hygon +architectures and `INFINI_OPS_HYGON_MOE_TRITON=1` select the Triton kernels. + +What this gains depends on the routing. With the routes of a forward spread +over the experts, every MoE layer streams hundreds of expert blocks. Clover +per-rank shapes (256 experts, hidden 2048, intermediate 256, top-8), routes +spread: + +| Tokens | Native | Triton | Speedup | +| ---: | ---: | ---: | ---: | +| 32 | 0.51 ms | 1.78 ms | 3.5x | +| 64 | 0.69 ms | 2.98 ms | 4.3x | +| 128 | 0.79 ms | 3.31 ms | 4.2x | +| 256 | 0.82 ms | 3.47 ms | 4.2x | +| 1024 | 1.64 ms | 4.09 ms | 2.5x | + +The block coreset of the model concentrates the routes of a 32-token block on +a few experts instead. So few blocks are left to stream that both +implementations take the same time: with about 25 active blocks, 0.10 ms at 32 +tokens for either. In the 32-token blocks of the model the fused MoE is 4-5% +of a forward's GPU kernel time, and the native kernels save 1-2% end to end. + +### Logit comparison with the reference implementation + +`test/diffusion` compares engine logits with the checkpoint's reference +implementation on the same inputs and decoding trajectory. Record the +reference in BF16, repeat it in FP32 as the truth, replay it with the engine +and compare: + +```sh +python test/diffusion/reference_logits.py --model /path/to/Clover-35B-A3B-Preview --out ref_bf16 +python test/diffusion/reference_logits.py --model /path/to/Clover-35B-A3B-Preview --out ref_fp32 --dtype float32 --trajectory ref_bf16 +python test/diffusion/engine_logits.py --model /path/to/Clover-35B-A3B-Preview --reference ref_bf16 --out engine --device nvidia +python test/diffusion/compare_logits.py --truth ref_fp32 bf16_reference=ref_bf16 engine=engine +``` + +Each command handles cases `0,1,2,3` of the workload; `--cases` selects +others. The FP32 run needs devices that hold about 139 GB of weights. + +### Recorded short-prompt campaign on Hygon + +| Variant | Visible output tok/s | Per device tok/s | +| --- | ---: | ---: | +| InfiniLM baseline | 28.57 | 14.29 | +| Frontier stride | 38.47 | 19.24 | +| Expert budget and live-row reuse | 28.70 | 14.35 | +| Joint, confidence floor 0.7 | 39.92 | 19.96 | +| Local SGLang Clover iterative port | 5.88 | 2.94 | + +The joint path is 1.397x the native baseline and 6.791x this local SGLang port. +Three joint repetitions measured 39.85–40.02 visible tok/s. The SGLang reference +is the local DTK 0.5.12 port of iterative Clover, with eager Triton attention/MoE; +it is not the official self-speculative implementation. The two lanes use +separate pairs of identical BW devices on the same host. Context capacity is +2048 for both. These numbers include HTTP/request latency and real EOS behavior. + +All requests completed. The controlled structural/answer checks passed 96/96 +for joint, 93/96 for expert-only and 90/96 for baseline/frontier/SGLang. This +checks the included fixture, not general quality equivalence. Generated text +can still contain imperfect wording. A lower floor of 0.5 produced invalid +Python and repetitions and was rejected. Keep outputs and failed candidates in +any further evaluation. + +![Rendered validation record of the Hygon campaign](images/clover-hygon-validation.png) + +### Recorded short-prompt campaign on NVIDIA + +The same client, workload, prompts, per-request output caps and sampling +controls, on two A100 80GB (CUDA 13.1) with TP=2, BF16, concurrency one and a +context capacity of 2048. Each variant ran the 32 prompts three times after a +separate warmup, alternating variant order. + +| Variant | Requests | Visible output tok/s | Per device tok/s | +| --- | ---: | ---: | ---: | +| InfiniLM baseline | 96/96 | 44.09 | 22.05 | +| Expert budget and live-row reuse | 96/96 | 46.98 | 23.49 | +| Frontier stride | 96/96 | 57.51 | 28.76 | +| Joint, confidence floor 0.7 | 96/96 | 58.51 | 29.26 | + +The joint path is 1.327x the native baseline. Three joint repetitions measured +57.24–59.58 visible tok/s. Every measured request completed, and each variant +answered the workload's own `check` on all 96 requests. This checks the included +fixture, not general quality equivalence. The SGLang comparison was not run: that +port is not available on the NVIDIA host. + +A profiled generation ran the native kernel of every Clover operator and of the +packed recurrence; no Triton kernel ran. With the NVIDIA operator profile, +InfiniRT passed 14 tests and InfiniOps 133 Clover tests, with one skipped that +needs Hygon. Two upstream `moe_fused_dense` tests (block size 4, an operator this +path does not call) fail on NVIDIA independently of this work. + +![Rendered validation record of the NVIDIA campaign](images/clover-nvidia-validation.png) diff --git a/docs/images/clover-hygon-validation.png b/docs/images/clover-hygon-validation.png new file mode 100644 index 000000000..61c415b6a Binary files /dev/null and b/docs/images/clover-hygon-validation.png differ diff --git a/docs/images/clover-nvidia-validation.png b/docs/images/clover-nvidia-validation.png new file mode 100644 index 000000000..38604ff0d Binary files /dev/null and b/docs/images/clover-nvidia-validation.png differ diff --git a/examples/bench_clover.py b/examples/bench_clover.py new file mode 100644 index 000000000..a45f23db3 --- /dev/null +++ b/examples/bench_clover.py @@ -0,0 +1,109 @@ +"""Measure serial Clover chat requests and retain every response and failure.""" + +import argparse +import http.client +import json +import time +import urllib.request +from pathlib import Path + +from transformers import AutoTokenizer + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--url", required=True) + parser.add_argument("--model", required=True) + parser.add_argument("--backend", choices=("infinilm", "sglang"), default="infinilm") + parser.add_argument("--tokenizer", required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument( + "--workload", + type=Path, + default=Path(__file__).parents[1] / "test/diffusion/workload.json", + ) + parser.add_argument("--variants", default="baseline,frontier,budget,joint") + parser.add_argument("--repeats", type=int, default=3) + parser.add_argument("--frontier-floor", type=float, default=0.7) + args = parser.parse_args() + variants = args.variants.split(",") + if not variants or set(variants) - {"baseline", "frontier", "budget", "joint"}: + parser.error("Unknown variant.") + if args.backend == "sglang" and variants != ["baseline"]: + parser.error("The SGLang comparison requires --variants baseline.") + tokenizer = AutoTokenizer.from_pretrained(args.tokenizer, trust_remote_code=True) + workload = json.loads(args.workload.read_text()) + args.output.parent.mkdir(parents=True, exist_ok=True) + for repeat in range(-1, args.repeats): + for item in workload: + order = variants if (repeat + item["id"]) % 2 == 0 else variants[::-1] + for variant in order: + request = { + "model": args.model, + "messages": [{"role": "user", "content": item["prompt"]}], + "temperature": 0, + "max_tokens": item["max_tokens"], + "presence_penalty": 0, + "frequency_penalty": 0, + "repetition_penalty": 1, + "chat_template_kwargs": {"enable_thinking": False}, + } + if args.backend == "infinilm": + request.update( + diffusion_policy="frontier" + if variant in ("frontier", "joint") + else "baseline", + expert_budget=variant in ("budget", "joint"), + frontier_confidence_floor=args.frontier_floor, + ) + record = { + "repeat": repeat, + "prompt_id": item["id"], + "variant": variant, + "request": request, + "success": False, + } + start = time.perf_counter() + try: + http_request = urllib.request.Request( + args.url.rstrip("/") + "/v1/chat/completions", + data=json.dumps(request).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(http_request, timeout=240) as response: + result = json.load(response) + record["elapsed_s"] = time.perf_counter() - start + text = result["choices"][0]["message"]["content"] + record.update( + success=True, + response=result, + visible_tokens=len( + tokenizer(text, add_special_tokens=False)["input_ids"] + ), + ) + except ( + OSError, + http.client.HTTPException, + ValueError, + LookupError, + TypeError, + ) as error: + record.update( + elapsed_s=time.perf_counter() - start, + error=str(error), + visible_tokens=0, + ) + with args.output.open("a") as output: + output.write(json.dumps(record, ensure_ascii=False) + "\n") + print( + variant, + repeat, + item["id"], + record["success"], + round(record["elapsed_s"], 4), + flush=True, + ) + + +if __name__ == "__main__": + main() diff --git a/examples/test_clover.py b/examples/test_clover.py new file mode 100644 index 000000000..f0ab9f9a2 --- /dev/null +++ b/examples/test_clover.py @@ -0,0 +1,43 @@ +"""Generate text with the native Clover block diffusion engine on a few prompts.""" + +import argparse + +from infinilm.diffusion.clover import CloverGenerator + +PROMPTS = ( + "What is the capital of France?", + "Write a Python function that reverses a string.", + "简要说一下光合作用的过程。", +) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--model", required=True, help="Checkpoint directory.") + parser.add_argument( + "--device", required=True, help="InfiniLM device name, for example `hygon`." + ) + parser.add_argument("--tp", type=int, default=2) + parser.add_argument("--max-context", type=int, default=2048) + parser.add_argument("--max-new-tokens", type=int, default=64) + parser.add_argument( + "--prompt", action="append", help="Prompt to generate; repeatable." + ) + args = parser.parse_args() + + generator = CloverGenerator( + args.model, tp=args.tp, max_context=args.max_context, device=args.device + ) + for prompt in args.prompt or PROMPTS: + result = generator.generate(prompt, max_new_tokens=args.max_new_tokens) + print(f"PROMPT: {prompt}") + print(f"TEXT: {result.text}") + print( + f"STAT: tokens={len(result.token_ids)} iterations={result.iterations} " + f"elapsed={result.elapsed_s:.2f}s tok/s={result.output_tokens_per_second:.2f}", + flush=True, + ) + + +if __name__ == "__main__": + main() diff --git a/python/infinilm/diffusion/__init__.py b/python/infinilm/diffusion/__init__.py new file mode 100644 index 000000000..a7fac7008 --- /dev/null +++ b/python/infinilm/diffusion/__init__.py @@ -0,0 +1 @@ +"""Block diffusion inference with explicit preview and causal commit phases.""" diff --git a/python/infinilm/diffusion/clover.py b/python/infinilm/diffusion/clover.py new file mode 100644 index 000000000..40bee2871 --- /dev/null +++ b/python/infinilm/diffusion/clover.py @@ -0,0 +1,258 @@ +"""Native Clover block diffusion on the InfiniLM C++ model and InfiniOps.""" + +import time +from dataclasses import dataclass + +from infinilm._core.utils import to_torch_dtype + +from .frontier import FrontierPolicy + + +@dataclass +class CloverResult: + text: str + token_ids: list[int] + iterations: list[int] + elapsed_s: float + prompt_token_count: int + + @property + def output_tokens_per_second(self): + return len(self.token_ids) / self.elapsed_s + + +class CloverGenerator: + """Run greedy diffusion with clean prefix state and causal block replay.""" + + # Canonical device.type -> Torch device string (Hygon DTK Torch exposes + # its GPUs through the regular torch.cuda namespace). + _TORCH_DEVICE = { + "cpu": "cpu", + "cuda": "cuda", + "hygon": "cuda", + "metax": "metax", + "iluvatar": "iluvatar", + "mlu": "mlu", + "musa": "musa", + "npu": "npu", + } + + def _torch_device_str(self, device): + try: + name = self._TORCH_DEVICE[device.type] + except KeyError as error: + raise ValueError( + f"Torch device name unknown for '{device.type}'; " + "Clover diffusion currently supports " + f"{', '.join(sorted(self._TORCH_DEVICE))}." + ) from error + return f"{name}:{device.index}" + + def __init__(self, model_path, *, tp=1, max_context=4096, device="cuda"): + import torch + from transformers import AutoTokenizer + + from infinilm import _core as core + from infinilm.cache import StaticKVCacheConfig + from infinilm.distributed import DistConfig + from infinilm.infer_engine import InferEngine, read_hf_config + from infinilm.modeling_utils import load_model_state_dict_by_file + + config = read_hf_config(model_path) + if config["model_type"] != "clover_moe": + raise ValueError("CloverGenerator requires a Clover checkpoint.") + max_positions = config["max_position_embeddings"] + if not 1 <= max_context <= max_positions: + raise ValueError(f"max_context must be between 1 and {max_positions}.") + + self.torch = torch + self.core = core + self.cache_config = StaticKVCacheConfig(1, max_context) + self.device = core.device(device) + self.torch_device = self._torch_device_str(self.device) + # The TP ranks must sit on the requested device, not on the first + # `tp` devices of the platform: `device="cuda:1", tp=1` would + # otherwise put the engine's weights on GPU 0 while Torch buffers + # live on GPU 1. A bare platform name keeps the first `tp` ranks + # (CUDA_VISIBLE_DEVICES / HIP_VISIBLE_DEVICES already place them); + # an index written into the string or an already-normalized device + # object both name one specific accelerator, which is only + # meaningful for the single rank of tp=1. + explicit_index = not isinstance(device, str) or ":" in device + if explicit_index: + if tp != 1: + raise ValueError( + "An indexed device is only supported with tp=1; use " + "CUDA_VISIBLE_DEVICES / HIP_VISIBLE_DEVICES to place " + "wider TP ranks." + ) + device_ids = [self.device.index] + else: + device_ids = list(range(tp)) + self.engine = InferEngine( + model_path, + device=self.device, + distributed_config=DistConfig(device_ids), + cache_config=self.cache_config, + ) + load_model_state_dict_by_file(self.engine, model_path, self.engine.dtype) + self.tokenizer = AutoTokenizer.from_pretrained( + model_path, trust_remote_code=True + ) + self.mask_id = self.engine.hf_config["mask_token_id"] + self.block_size = self.engine.hf_config["block_size"] + self.max_context = max_context + + def _tensor(self, values, *, wide=False): + import numpy as np + + return self.core.from_numpy( + np.asarray(values, dtype=np.int64 if wide else np.int32) + ) + + def _forward(self, ids, past, *, preview=False, expert_budget=False): + length = len(ids) + return self.engine.forward_raw( + self._tensor([ids], wide=True), + # Mrope reads 2-D positions as [3, tokens] axis rows, so single-axis + # Clover passes the packed 1-D form like the engine's paged path. + position_ids=self._tensor(list(range(past, past + length)), wide=True), + past_kv_lengths=self._tensor([past]), + total_kv_lengths=self._tensor([past + length]), + input_offsets=self._tensor([0, length]), + cu_seqlens=self._tensor([0, past + length]), + block_tables=self._tensor([[0]]), + mamba_init_state_indices=self._tensor([0]), + mamba_final_state_indices=self._tensor([0]), + diffusion_preview=preview, + diffusion_expert_budget=expert_budget, + sample_all_positions=preview, + temperature=0, + top_k=1, + ) + + def _logits(self, value): + # The copy runs between like-typed buffers: a model with BF16 weights + # and an FP32 output head produces FP32 logits, and copying those + # through a BF16 buffer would truncate them before `.float()`. + torch, core = self.torch, self.core + value_dtype = value.dtype + out = torch.empty( + value.shape, + device=self.torch_device, + dtype=to_torch_dtype(value_dtype), + ) + target = core.from_blob( + out.data_ptr(), + list(value.shape), + dtype=value_dtype, + device=self.device, + owner=out, + ) + target.copy_(value) + core.set_device(self.device) + core.sync_device() + return out.view(self.block_size, -1).float() + + def generate( + self, + prompt, + *, + max_new_tokens=128, + policy="baseline", + threshold=0.95, + ignore_eos=False, + expert_budget=False, + frontier_confidence_floor=0.9, + ): + if policy not in ("baseline", "frontier"): + raise ValueError("Policy must be baseline or frontier.") + if max_new_tokens < 0 or not 0 <= threshold <= 1: + raise ValueError("Invalid output limit or confidence threshold.") + frontier = ( + FrontierPolicy(confidence_floor=frontier_confidence_floor) + if policy == "frontier" + else None + ) + torch = self.torch + prompt_ids = self.tokenizer.apply_chat_template( + ( + [{"role": "user", "content": prompt}] + if isinstance(prompt, str) + else prompt + ), + tokenize=True, + add_generation_prompt=True, + enable_thinking=False, + ) + if hasattr(prompt_ids, "keys"): + prompt_ids = prompt_ids["input_ids"] + blocks = (max_new_tokens + self.block_size - 1) // self.block_size + prompt_token_count = len(prompt_ids) + if prompt_token_count + blocks * self.block_size > self.max_context: + raise ValueError( + "Prompt and complete diffusion blocks exceed the cache capacity." + ) + start = time.perf_counter() + if max_new_tokens == 0: + return CloverResult( + "", [], [], time.perf_counter() - start, prompt_token_count + ) + self.engine.reset_cache(self.cache_config) + self._forward(prompt_ids, 0) + output, iterations = [], [] + eos = set(self.engine.eos_token_id) + for _ in range(blocks): + past = prompt_token_count + len(output) + ids = torch.full( + (self.block_size,), + self.mask_id, + device=self.torch_device, + dtype=torch.int64, + ) + for iteration in range(self.block_size): + result = self._forward( + ids.cpu().tolist(), + past, + preview=True, + expert_budget=expert_budget, + ) + logits = self._logits(result["logits"]) + logits[:, self.mask_id] = -float("inf") + confidence, proposed = logits.softmax(-1).max(-1) + masked = ids == self.mask_id + if frontier is not None: + selected = frontier.select( + confidence[None], masked[None], iteration + )[0] + else: + selected = masked & (confidence >= threshold) + if not bool(selected.any()): + selected[confidence.masked_fill(~masked, -1).argmax()] = True + ids = torch.where(selected, proposed, ids) + if not bool((ids == self.mask_id).any()): + break + resolved = ids.cpu().tolist() + if self.mask_id in resolved: + raise RuntimeError("An unresolved diffusion block cannot be committed.") + iterations.append(iteration + 1) + remaining = max_new_tokens - len(output) + for token in resolved[:remaining]: + if not ignore_eos and token in eos: + return CloverResult( + self.tokenizer.decode(output, skip_special_tokens=True), + output, + iterations, + time.perf_counter() - start, + prompt_token_count, + ) + output.append(token) + if len(output) < max_new_tokens: + self._forward(resolved, past) + return CloverResult( + self.tokenizer.decode(output, skip_special_tokens=True), + output, + iterations, + time.perf_counter() - start, + prompt_token_count, + ) diff --git a/python/infinilm/diffusion/frontier.py b/python/infinilm/diffusion/frontier.py new file mode 100644 index 000000000..d1af1a938 --- /dev/null +++ b/python/infinilm/diffusion/frontier.py @@ -0,0 +1,43 @@ +"""Frontier-guided denoising adapted from Ringssss/dLLM-serve (Apache-2.0).""" + +from dataclasses import dataclass + + +@dataclass(frozen=True) +class FrontierPolicy: + """Choose confident positions with a bounded, adaptive target stride.""" + + target_iterations: int = 8 + min_unmask: int = 2 + max_unmask: int = 16 + confidence_floor: float = 0.9 + confident_threshold: float = 0.95 + + def __post_init__(self): + if not 1 <= self.min_unmask <= self.max_unmask <= 32: + raise ValueError("Unmask bounds must satisfy 1 <= min <= max <= 32.") + if self.target_iterations < 1 or not ( + 0 <= self.confidence_floor <= self.confident_threshold <= 1 + ): + raise ValueError("Invalid target iterations or confidence floor.") + + def select(self, confidence, masked, iteration): + import torch + + remaining = masked.sum(-1) + rounds = max(1, self.target_iterations - iteration) + stride = torch.div(remaining + rounds - 1, rounds, rounding_mode="floor") + stride = torch.minimum( + stride.clamp(self.min_unmask, self.max_unmask), remaining + ) + scores = confidence.masked_fill(~masked, -float("inf")) + order = scores.argsort(dim=-1, descending=True, stable=True) + ranks = torch.arange(masked.shape[-1], device=masked.device) + take = ranks < stride[..., None] + transfer = torch.zeros_like(masked).scatter(-1, order, take) + transfer &= masked & (confidence >= self.confidence_floor) + transfer |= masked & (confidence >= self.confident_threshold) + stalled = masked.any(-1) & ~transfer.any(-1) + best = scores.argmax(-1, keepdim=True) + transfer.scatter_(-1, best, transfer.gather(-1, best) | stalled[..., None]) + return transfer diff --git a/python/infinilm/infer_engine.py b/python/infinilm/infer_engine.py index 67cc645ca..05a8c29f8 100644 --- a/python/infinilm/infer_engine.py +++ b/python/infinilm/infer_engine.py @@ -338,6 +338,8 @@ def _build_input( visual_token_ranges=None, target_hidden_states=None, sample_all_positions=False, + diffusion_preview=False, + diffusion_expert_budget=False, temperature=None, top_k=None, top_p=None, @@ -399,6 +401,8 @@ def convert_tensor_list(tensor_list_): visual_token_ranges=visual_token_ranges, target_hidden_states=target_hidden_states, sample_all_positions=sample_all_positions, + diffusion_preview=diffusion_preview, + diffusion_expert_budget=diffusion_expert_budget, temperature=temperature, top_k=top_k, top_p=top_p, @@ -534,6 +538,10 @@ def forward_raw( visual_token_ranges=None, target_hidden_states=None, sample_all_positions=True, + diffusion_preview=False, + diffusion_expert_budget=False, + mamba_init_state_indices=None, + mamba_final_state_indices=None, temperature=None, top_k=None, top_p=None, @@ -557,6 +565,10 @@ def forward_raw( visual_token_ranges=visual_token_ranges, target_hidden_states=target_hidden_states, sample_all_positions=sample_all_positions, + diffusion_preview=diffusion_preview, + diffusion_expert_budget=diffusion_expert_budget, + mamba_init_state_indices=mamba_init_state_indices, + mamba_final_state_indices=mamba_final_state_indices, temperature=temperature, top_k=top_k, top_p=top_p, diff --git a/python/infinilm/licenses/dLLM-serve/LICENSE b/python/infinilm/licenses/dLLM-serve/LICENSE new file mode 100644 index 000000000..261eeb9e9 --- /dev/null +++ b/python/infinilm/licenses/dLLM-serve/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/python/infinilm/licenses/dLLM-serve/NOTICE b/python/infinilm/licenses/dLLM-serve/NOTICE new file mode 100644 index 000000000..8f60423ca --- /dev/null +++ b/python/infinilm/licenses/dLLM-serve/NOTICE @@ -0,0 +1,4 @@ +Frontier-guided stride control is adapted from Ringssss/dLLM-serve, commit +1da50a96c9ce6b888d245d378f2bac0425feba8c, cwsrpt_v2/algorithm/cw_srpt_v3.py. +The adaptation preserves confident-token progress and uses a configurable +confidence floor. Original source is distributed under Apache-2.0. diff --git a/python/infinilm/modeling_utils.py b/python/infinilm/modeling_utils.py index 114aae846..b1916c66d 100644 --- a/python/infinilm/modeling_utils.py +++ b/python/infinilm/modeling_utils.py @@ -328,6 +328,7 @@ def load_model_state_dict_by_file( _remap_qwen3_next, _remap_qwen3_5, _remap_qwen3_5_moe, + _remap_clover_moe, _remap_kimi_k3, ) or ( @@ -1328,6 +1329,12 @@ def _remap_kimi_k3(state_dict, config): return state_dict +def _remap_clover_moe(state_dict, config, *, defer_tie=False): + """Load Clover's Qwen weights while retaining every diffusion parameter.""" + wrapped = dict(config, text_config=config) + return _remap_qwen3_5_moe(state_dict, wrapped, defer_tie=defer_tie) + + _WEIGHT_REMAPPER = { "glm4": _remap_glm4, "chatglm": _remap_chatglm, @@ -1337,6 +1344,7 @@ def _remap_kimi_k3(state_dict, config): "videonsa": _remap_videonsa, "qwen3_5": _remap_qwen3_5, "qwen3_5_moe": _remap_qwen3_5_moe, + "clover_moe": _remap_clover_moe, "qwen3_next": _remap_qwen3_next, "kimi_k3": _remap_kimi_k3, } diff --git a/python/infinilm/server/clover_server.py b/python/infinilm/server/clover_server.py new file mode 100644 index 000000000..3dadce48c --- /dev/null +++ b/python/infinilm/server/clover_server.py @@ -0,0 +1,232 @@ +"""OpenAI-compatible serial serving for the native Clover diffusion engine.""" + +import argparse +import asyncio +import time +import uuid +from functools import partial + +import anyio +from fastapi import FastAPI, HTTPException, Request +from jinja2 import TemplateError +from pydantic import BaseModel, Field + +from infinilm.diffusion.frontier import FrontierPolicy + + +class ChatRequest(BaseModel): + model: str = "clover" + messages: list[dict] + max_tokens: int = Field(default=128, ge=0) + temperature: float = 0 + stream: bool = False + diffusion_policy: str | None = None + expert_budget: bool | None = None + frontier_confidence_floor: float | None = Field( + default=None, ge=0, le=FrontierPolicy.confident_threshold + ) + presence_penalty: float = 0 + frequency_penalty: float = 0 + repetition_penalty: float = 1 + chat_template_kwargs: dict = Field(default_factory=dict) + + # OpenAI clients send `max_completion_tokens`; a server that accepts the + # field but ignores it would silently generate a different length than + # requested. + max_completion_tokens: int | None = Field(default=None, ge=0) + # Accepted-with-ignored fields the endpoint cannot serve yet: rejecting + # them up front is honest, silent truncation is not. + stop: list[str] | None = None + n: int | None = Field(default=None, ge=1) + + +async def _generate_when_connected(request, slot, generate): + """Wait for the one model slot while the client is connected.""" + disconnected = False + owns_slot = False + + async def watch_disconnect(): + nonlocal disconnected + # FastAPI has already consumed the chat request body. + while True: + message = await request.receive() + if message["type"] == "http.disconnect": + disconnected = True + watchers.cancel_scope.cancel() + return + + def generation_finished(future): + slot.release() + if not future.cancelled(): + # The request may have left before the worker raised. + future.exception() + + try: + async with anyio.create_task_group() as watchers: + watchers.start_soon(watch_disconnect) + await slot.acquire() + owns_slot = True + watchers.cancel_scope.cancel() + + # The watcher has exited. Check once more for a disconnect delivered + # as the previous generation handed off the slot. + if disconnected or await request.is_disconnected(): + raise HTTPException(499, "Client disconnected.") + + future = asyncio.get_running_loop().run_in_executor(None, generate) + future.add_done_callback(generation_finished) + owns_slot = False # The worker's completion now releases the slot. + return await asyncio.shield(future) + finally: + if owns_slot: + slot.release() + + +def create_app( + generator, *, policy="baseline", expert_budget=False, frontier_floor=0.9 +): + """Serialize requests because each worker owns one recurrent state slot.""" + slot = asyncio.Lock() + app = FastAPI() + + @app.get("/health") + def health(): + return {"status": "ok"} + + @app.get("/v1/models") + def models(): + return {"object": "list", "data": [{"id": "clover", "object": "model"}]} + + @app.post("/v1/chat/completions") + async def chat(request: ChatRequest, raw: Request): + if ( + request.presence_penalty != 0 + or request.frequency_penalty != 0 + or request.repetition_penalty != 1 + or request.chat_template_kwargs.get("enable_thinking", False) + ): + raise HTTPException( + 400, "This endpoint requires neutral penalties and thinking disabled." + ) + if request.stream or request.temperature != 0: + raise HTTPException( + 400, "Clover currently supports non-streaming greedy requests." + ) + if request.stop: + raise HTTPException( + 400, "Stop sequences are not supported by the Clover endpoint." + ) + if request.n is not None and request.n != 1: + raise HTTPException( + 400, "Only a single candidate per request is supported." + ) + if any( + message.get("role") not in ("system", "user", "assistant") + or not isinstance(message.get("content"), str) + for message in request.messages + ): + raise HTTPException( + 400, "Messages require a supported role and text content." + ) + if not request.messages: + raise HTTPException(400, "At least one message is required.") + # One effective cap, computed once: the generation and the response + # finish_reason both use it, so an OpenAI `max_completion_tokens` + # request reports `length` at exactly the cap that was honored. + max_tokens = ( + request.max_completion_tokens + if request.max_completion_tokens is not None + else request.max_tokens + ) + generate = partial( + generator.generate, + request.messages, + max_new_tokens=max_tokens, + policy=request.diffusion_policy or policy, + frontier_confidence_floor=frontier_floor + if request.frontier_confidence_floor is None + else request.frontier_confidence_floor, + expert_budget=expert_budget + if request.expert_budget is None + else request.expert_budget, + ) + try: + result = await _generate_when_connected(raw, slot, generate) + except (ValueError, TemplateError) as exc: + raise HTTPException(400, str(exc)) from exc + prompt_count = result.prompt_token_count + output_count = len(result.token_ids) + return { + "id": "chatcmpl-" + uuid.uuid4().hex, + "object": "chat.completion", + "created": int(time.time()), + "model": request.model, + "choices": [ + { + "index": 0, + "message": {"role": "assistant", "content": result.text}, + "finish_reason": "length" + if max_tokens == 0 or output_count >= max_tokens + else "stop", + } + ], + "usage": { + "prompt_tokens": prompt_count, + "completion_tokens": output_count, + "total_tokens": prompt_count + output_count, + }, + } + + return app + + +def main(): + import uvicorn + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--model", required=True) + parser.add_argument("--tp", type=int, default=1) + parser.add_argument("--max-context", type=int, default=4096) + parser.add_argument( + "--device", + default="auto", + help=( + "device platform: auto, cpu, nvidia/cuda, hygon, metax, moore, " + "iluvatar, cambricon, ascend" + ), + ) + parser.add_argument( + "--policy", choices=("baseline", "frontier"), default="baseline" + ) + parser.add_argument("--expert-budget", action="store_true") + parser.add_argument("--frontier-floor", type=float, default=0.9) + parser.add_argument("--host", default="127.0.0.1") + parser.add_argument("--port", type=int, default=8000) + args = parser.parse_args() + if not 0 <= args.frontier_floor <= FrontierPolicy.confident_threshold: + parser.error( + f"--frontier-floor must be between 0 and {FrontierPolicy.confident_threshold}" + ) + from infinilm.base_config import BaseConfig + from infinilm.diffusion.clover import CloverGenerator + + # Reuse the framework's device resolution (auto-detection + alias + # normalization) without parsing the server's argv a second time. + config = BaseConfig.__new__(BaseConfig) + config.backend = "cpp" # native backend: probe via infinicore, not vendor CLIs + config._auto_detected_device = None + device = config.get_device_str(args.device) + generator = CloverGenerator( + args.model, tp=args.tp, max_context=args.max_context, device=device + ) + app = create_app( + generator, + policy=args.policy, + expert_budget=args.expert_budget, + frontier_floor=args.frontier_floor, + ) + uvicorn.run(app, host=args.host, port=args.port) + + +if __name__ == "__main__": + main() diff --git a/test/diffusion/compare_logits.py b/test/diffusion/compare_logits.py new file mode 100644 index 000000000..19aa5678c --- /dev/null +++ b/test/diffusion/compare_logits.py @@ -0,0 +1,189 @@ +"""Measure how far saved logits are from a float32 reference. + +Each prefix names the files written by ``reference_logits.py`` or +``engine_logits.py``. The report prints, per stage of the block loop, the KL +divergence from the truth, the share of positions far from it and how often +the most likely token agrees. +""" + +import argparse +from pathlib import Path + +import numpy as np + +STAGES = ( + ("prompt_logits", "prefill"), + ("preview_full_mask_logits", "preview, all-mask block"), + ("preview_partial_logits", "preview, after first unmask"), + ("replay_logits", "replay of resolved block"), + ("next_preview_logits", "preview of next block"), +) + + +def parse_cases(value): + """Return the workload ids given as a comma-separated list.""" + try: + cases = sorted({int(item) for item in value.split(",")}) + except ValueError as error: + raise argparse.ArgumentTypeError( + "Cases must be a comma-separated list of ids." + ) from error + if not cases or cases[0] < 0: + raise argparse.ArgumentTypeError("Cases must be a comma-separated list of ids.") + return cases + + +def softmax(logits): + """Return the softmax of the last axis, evaluated in float64.""" + shifted = logits.astype(np.float64) + shifted -= shifted.max(-1, keepdims=True) + exponent = np.exp(shifted) + return exponent / exponent.sum(-1, keepdims=True) + + +def kl_divergence(truth, logits): + """Return the per-position KL divergence `KL(truth || logits)`.""" + expected, actual = softmax(truth), softmax(logits) + return (expected * (np.log(expected + 1e-300) - np.log(actual + 1e-300))).sum(-1) + + +def load(prefix, cases): + """Return the recorded cases of a run, one dictionary per case.""" + missing = [case for case in cases if not Path(f"{prefix}_{case}.npz").is_file()] + if missing: + raise FileNotFoundError(f"`{prefix}` has no record for case {missing}.") + return [np.load(f"{prefix}_{case}.npz") for case in cases] + + +def gather(truth, runs, key, measure, *, truth_key=None): + """Measure matched positions, omitting only an optional second preview.""" + results = [[] for _ in runs] + count = 0 + for reference, *candidates in zip(truth, *runs): + if key == "preview_partial_logits" and any( + key not in case for case in (reference, *candidates) + ): + continue + expected = reference[truth_key or key] + for output, candidate in zip(results, candidates): + actual = candidate[key] + if expected.ndim != 2 or actual.shape != expected.shape: + raise ValueError( + f"{key}: expected [positions, vocabulary] {expected.shape}, " + f"got {actual.shape}" + ) + output.append(measure(expected, actual)) + count += 1 + return [np.concatenate(output) if count else [] for output in results], count + + +def print_table(title, stat, table_rows, labels): + """Print one table with a stage per row and a run per column.""" + width = max(12, *(len(label) for label in labels)) + 2 + margin = max(28, *(len(name) for name, _ in table_rows)) + 2 + print(title) + print(f"{'':<{margin}}" + "".join(f"{label:>{width}}" for label in labels)) + for name, measures in table_rows: + print( + f"{name:<{margin}}" + + "".join(f"{stat(measure):>{width}.5f}" for measure in measures) + ) + whole = [ + np.concatenate([measures[index] for _, measures in table_rows]) + for index in range(len(labels)) + ] + print( + f"{'all stages':<{margin}}" + + "".join(f"{stat(measure):>{width}.5f}" for measure in whole) + ) + print() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--truth", required=True, help="Prefix of the float32 reference." + ) + parser.add_argument( + "runs", nargs="+", metavar="LABEL=PREFIX", help="Run to compare with the truth." + ) + parser.add_argument("--cases", type=parse_cases, default=parse_cases("0,1,2,3")) + args = parser.parse_args() + if any("=" not in run for run in args.runs): + parser.error("Runs are written as LABEL=PREFIX.") + try: + truth = load(args.truth, args.cases) + runs = [load(run.split("=", 1)[1], args.cases) for run in args.runs] + except FileNotFoundError as error: + parser.error(str(error)) + + labels = [run.split("=", 1)[0] for run in args.runs] + rows = [] + for key, stage in STAGES: + divergences, count = gather(truth, runs, key, kl_divergence) + if not count: + continue + agreements, _ = gather( + truth, runs, key, lambda a, b: (a.argmax(-1) == b.argmax(-1)).astype(float) + ) + name = stage if count == len(args.cases) else f"{stage} [{count} cases]" + rows.append((name, divergences, agreements)) + positions = sum(len(row[1][0]) for row in rows) + + print_table( + f"=== Mean KL from the truth over {positions} positions", + np.mean, + [(name, measures) for name, measures, _ in rows], + labels, + ) + print_table( + "=== Median KL per position", + np.median, + [(name, measures) for name, measures, _ in rows], + labels, + ) + print_table( + "=== Share of positions with KL above 0.1", + lambda k: float((k > 0.1).mean()), + [(name, measures) for name, measures, _ in rows], + labels, + ) + print_table( + "=== Share of positions with KL above 0.5", + lambda k: float((k > 0.5).mean()), + [(name, measures) for name, measures, _ in rows], + labels, + ) + print_table( + "=== Share of positions whose most likely token agrees", + np.mean, + [(name, measures) for name, _, measures in rows], + labels, + ) + + common = set.intersection(*(set(case) for run in (truth, *runs) for case in run)) + shift_keys = sorted( + (key for key in common if key.startswith("prompt_logits_shift_")), + key=lambda key: int(key.rsplit("_", 1)[1]), + ) + if not shift_keys: + return + width = max(12, *(len(label) for label in labels)) + 2 + print( + "=== Mean KL from the truth's prefill for prefills with all positions " + "shifted by a constant, an equivalent input" + ) + print(f"{'':<28}" + "".join(f"{label:>{width}}" for label in ("truth", *labels))) + for key in shift_keys: + measures, _ = gather( + truth, (truth, *runs), key, kl_divergence, truth_key="prompt_logits" + ) + cells = [values.mean() for values in measures] + print( + f"{'shift ' + key.rsplit('_', 1)[1]:<28}" + + "".join(f"{value:>{width}.5f}" for value in cells) + ) + + +if __name__ == "__main__": + main() diff --git a/test/diffusion/engine_logits.py b/test/diffusion/engine_logits.py new file mode 100644 index 000000000..35c819b71 --- /dev/null +++ b/test/diffusion/engine_logits.py @@ -0,0 +1,222 @@ +"""Replay reference trajectories with InfiniLM and save logits at the same points. + +`--reference` names the prefix of the files written by `reference_logits.py`. +The first unmask step and the resolved block are read from them, so the engine +sees the same inputs as the reference. +""" + +import argparse +import json +import time +from pathlib import Path + +import numpy as np +import torch +from infinilm._core.utils import to_torch_dtype +from infinilm.diffusion.clover import CloverGenerator + +WORKLOAD = Path(__file__).with_name("workload.json") + + +def parse_cases(value): + """Return the workload ids given as a comma-separated list.""" + try: + cases = sorted({int(item) for item in value.split(",")}) + except ValueError as error: + raise argparse.ArgumentTypeError( + "Cases must be a comma-separated list of ids." + ) from error + if not cases or cases[0] < 0: + raise argparse.ArgumentTypeError("Cases must be a comma-separated list of ids.") + return cases + + +def parse_shifts(value): + """Return the position shifts given as a comma-separated list.""" + try: + return sorted({int(item) for item in value.split(",") if item}) + except ValueError as error: + raise argparse.ArgumentTypeError( + "Shifts must be a comma-separated list of integers." + ) from error + + +def forward(generator, ids, past, *, preview, layout, shift=0): + """Call the engine like `CloverGenerator._forward`, keeping every position's logits.""" + length = len(ids) + rows = list(range(past + shift, past + shift + length)) + positions = [rows] * 3 if layout == "axis-rows" else rows + + def tensor(values, dtype): + return generator.core.from_numpy(np.asarray(values, dtype=dtype)) + + int64, int32 = np.int64, np.int32 + return generator.engine.forward_raw( + tensor([ids], int64), + position_ids=tensor(positions, int64), + past_kv_lengths=tensor([past], int32), + total_kv_lengths=tensor([past + length], int32), + input_offsets=tensor([0, length], int32), + cu_seqlens=tensor([0, past + length], int32), + block_tables=tensor([[0]], int32), + mamba_init_state_indices=tensor([0], int32), + mamba_final_state_indices=tensor([0], int32), + diffusion_preview=preview, + diffusion_expert_budget=False, + sample_all_positions=True, + temperature=0, + top_k=1, + ) + + +def logits_of(generator, result, tokens): + """Copy the engine logits out before the next forward reuses the buffer.""" + value = result["logits"] + # Copy between like-typed buffers: a BF16 model with an FP32 output head + # yields FP32 logits, which a BF16 staging buffer would truncate. + value_dtype = value.dtype + out = torch.empty( + value.shape, + device=generator.torch_device, + dtype=to_torch_dtype(value_dtype), + ) + target = generator.core.from_blob( + out.data_ptr(), + list(value.shape), + dtype=value_dtype, + device=generator.device, + owner=out, + ) + target.copy_(value) + generator.core.set_device(generator.device) + generator.core.sync_device() + return out.view(tokens, -1).float().cpu().numpy() + + +def replay_case(generator, reference, *, layout, shifts): + """Replay one recorded trajectory and collect logits at the same points.""" + mask, width = generator.mask_id, generator.block_size + prompt_ids = reference["prompt_ids"].tolist() + past = len(prompt_ids) + if past + 2 * width > generator.max_context: + raise ValueError("Replay needs cache space for the prompt and two blocks.") + position_limit = generator.engine.hf_config["max_position_embeddings"] + if any(shift < 0 or shift + past > position_limit for shift in shifts): + raise ValueError("Shifted prompt positions exceed the rotary table.") + full_mask = [mask] * width + transfer = reference["step1_transfer"].astype(bool) + partial = list(full_mask) + for position in np.nonzero(transfer)[0]: + partial[int(position)] = int(reference["step1_prediction"][int(position)]) + resolved = reference["resolved_block"].tolist() + + def logits(ids, at, *, preview, shift=0): + """Return the logits of one forward as a NumPy array.""" + result = forward( + generator, ids, at, preview=preview, layout=layout, shift=shift + ) + return logits_of(generator, result, len(ids)) + + generator.engine.reset_cache(generator.cache_config) + saved = { + "prompt_ids": np.asarray(prompt_ids, dtype=np.int64), + "step1_transfer": transfer, + "resolved_block": np.asarray(resolved, dtype=np.int64), + "prompt_logits": logits(prompt_ids, 0, preview=False), + "preview_full_mask_logits": logits(full_mask, past, preview=True), + } + if "preview_partial_logits" in reference: + saved["preview_partial_logits"] = logits(partial, past, preview=True) + saved["replay_logits"] = logits(resolved, past, preview=False) + saved["next_preview_logits"] = logits(full_mask, past + width, preview=True) + # The engine cache is stateful, so each shifted prefill starts from a reset. + for shift in shifts: + generator.engine.reset_cache(generator.cache_config) + saved[f"prompt_logits_shift_{shift}"] = logits( + prompt_ids, 0, preview=False, shift=shift + ) + return saved + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--model", required=True, help="Checkpoint directory.") + parser.add_argument( + "--reference", required=True, help="Prefix written by `reference_logits.py`." + ) + parser.add_argument( + "--out", required=True, help="Output prefix; one `.npz` per case." + ) + parser.add_argument("--workload", type=Path, default=WORKLOAD) + parser.add_argument("--cases", type=parse_cases, default=parse_cases("0,1,2,3")) + parser.add_argument( + "--device", required=True, help="InfiniLM device name or alias." + ) + parser.add_argument("--tp", type=int, default=2) + parser.add_argument("--max-context", type=int, default=2048) + parser.add_argument( + "--positions", + choices=("packed", "axis-rows"), + default="packed", + help="Use packed positions or repeat the text positions on all three axes.", + ) + parser.add_argument( + "--shifts", + type=parse_shifts, + default=[], + help="Also prefill with every token position shifted by each constant.", + ) + parser.add_argument( + "--repeat", + type=int, + default=1, + help="Replay each case this many times and require identical logits.", + ) + args = parser.parse_args() + + items = {item["id"]: item for item in json.loads(args.workload.read_text())} + missing = [case for case in args.cases if case not in items] + if missing: + parser.error(f"The workload has no case {missing}.") + missing = [ + case + for case in args.cases + if not Path(f"{args.reference}_{case}.npz").is_file() + ] + if missing: + parser.error(f"No reference record for case {missing}.") + generator = CloverGenerator( + args.model, tp=args.tp, max_context=args.max_context, device=args.device + ) + Path(args.out).parent.mkdir(parents=True, exist_ok=True) + for case in args.cases: + reference = np.load(f"{args.reference}_{case}.npz") + start = time.perf_counter() + saved = replay_case( + generator, reference, layout=args.positions, shifts=args.shifts + ) + for _ in range(args.repeat - 1): + again = replay_case( + generator, reference, layout=args.positions, shifts=args.shifts + ) + if not all(np.array_equal(saved[key], again[key]) for key in saved): + raise SystemExit( + f"case {case}: repeated replays produced different logits." + ) + np.savez(f"{args.out}_{case}.npz", **saved) + result = generator.generate( + items[case]["prompt"], + max_new_tokens=generator.block_size, + ignore_eos=True, + ) + same = result.token_ids == reference["resolved_block"].tolist() + print( + f"case {case}: replay {time.perf_counter() - start:.1f}s | " + f"first block identical to the reference: {same} | " + f"iterations={result.iterations} text={result.text!r}", + flush=True, + ) + + +if __name__ == "__main__": + main() diff --git a/test/diffusion/mrope_positions_probe.py b/test/diffusion/mrope_positions_probe.py new file mode 100644 index 000000000..99d4fb027 --- /dev/null +++ b/test/diffusion/mrope_positions_probe.py @@ -0,0 +1,94 @@ +"""Compare the InfiniOps `Mrope` kernel with the checkpoint's rotary for each positions layout. + +usage: python test/diffusion/mrope_positions_probe.py [CASE ...] + +`Mrope` accepts packed ``[tokens]`` positions or ``[3, tokens]`` axis rows. +""" + +import sys + +import infini.ops as ops +import torch + +HEAD, ROTARY, SECTIONS = 256, 64, (16, 8, 8) +QUERY_HEADS, KEY_HEADS, TOKENS, TABLE = 16, 2, 40, 2048 +CASES = ("1d", "3d_same", "3d_distinct") + + +def reference(value, cos, sin, axis_rows): + """Rotate like the checkpoint's `CloverAttention.rotary`, one position per axis.""" + width = ROTARY // 2 + axis_of_pair = torch.cat( + [ + torch.full((section,), index, device=value.device) + for index, section in enumerate(SECTIONS) + ] + ) + position = axis_rows[axis_of_pair].T + pair = torch.arange(width, device=value.device)[None, :] + phase_cos, phase_sin = ( + cos[position, pair][:, None, :], + sin[position, pair][:, None, :], + ) + view = value.view(TOKENS, -1, HEAD) + x, y = view[:, :, :width].float(), view[:, :, width:ROTARY].float() + out = value.clone().view(TOKENS, -1, HEAD) + out[:, :, :width] = x * phase_cos - y * phase_sin + out[:, :, width:ROTARY] = y * phase_cos + x * phase_sin + return out.reshape(value.shape) + + +def case_inputs(case, device): + """Return the positions tensor and the axis rows whose results are compared.""" + rows = torch.arange(TOKENS, device=device, dtype=torch.int64) + packed = ("packed positions", rows.expand(3, -1)) + if case == "1d": + return rows, [packed] + if case == "3d_same": + return rows.expand(3, -1).contiguous(), [packed] + if case == "3d_distinct": + distinct = torch.stack((rows, rows + 5, rows + 100)) + return distinct, [("three distinct axis rows", distinct)] + raise ValueError(f"Unknown layout {case!r}.") + + +def main(): + cases = sys.argv[1:] or list(CASES) + if set(cases) - set(CASES): + raise SystemExit(f"Unknown case. Choose from {', '.join(CASES)}.") + device, dtype = "cuda", torch.bfloat16 + torch.manual_seed(0) + query = torch.randn(TOKENS, QUERY_HEADS * HEAD, device=device).to(dtype) + key = torch.randn(TOKENS, KEY_HEADS * HEAD, device=device).to(dtype) + # A random table makes every pair sensitive to the position it reads. + cos = torch.randn(TABLE, ROTARY // 2, device=device).to(dtype) + sin = torch.randn(TABLE, ROTARY // 2, device=device).to(dtype) + stream = torch.cuda.current_stream().cuda_stream + for case in cases: + positions, expectations = case_inputs(case, device) + query_out, key_out = torch.empty_like(query), torch.empty_like(key) + print(f"case={case} positions shape={tuple(positions.shape)}", flush=True) + ops.mrope( + query, + key, + cos, + sin, + positions, + HEAD, + ROTARY, + *SECTIONS, + False, + query_out, + key_out, + stream=stream, + ) + torch.cuda.synchronize() + for label, axis_rows in expectations: + for value, out in ((query, query_out), (key, key_out)): + want = reference(value, cos, sin, axis_rows).to(out.dtype) + torch.testing.assert_close(out, want, rtol=0.02, atol=0.03) + print(f" matches {label}: query and key") + + +if __name__ == "__main__": + main() diff --git a/test/diffusion/reference_logits.py b/test/diffusion/reference_logits.py new file mode 100644 index 000000000..a71f96cc1 --- /dev/null +++ b/test/diffusion/reference_logits.py @@ -0,0 +1,190 @@ +"""Save the reference implementation's logits along its block diffusion trajectory. + +Each selected workload case writes ``_.npz`` with the logits of the +causal prefill, the first preview of an all-mask block, the preview after the +first unmask step, the causal replay of the resolved block and the first +preview of the next block. ``engine_logits.py`` replays the same trajectory. + +The block loop follows ``CloverMoeModelLM.generate`` with neutral penalties. +The reference code is loaded from the checkpoint directory with +``trust_remote_code``. +""" + +import argparse +import json +import time +from pathlib import Path + +import numpy as np +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +WORKLOAD = Path(__file__).with_name("workload.json") + + +def parse_cases(value): + """Return the workload ids given as a comma-separated list.""" + try: + cases = sorted({int(item) for item in value.split(",")}) + except ValueError as error: + raise argparse.ArgumentTypeError( + "Cases must be a comma-separated list of ids." + ) from error + if not cases or cases[0] < 0: + raise argparse.ArgumentTypeError("Cases must be a comma-separated list of ids.") + return cases + + +def parse_shifts(value): + """Return the position shifts given as a comma-separated list.""" + try: + return sorted({int(item) for item in value.split(",") if item}) + except ValueError as error: + raise argparse.ArgumentTypeError( + "Shifts must be a comma-separated list of integers." + ) from error + + +def run_case(model, tokenizer, prompt, forced, shifts): + """Run one prompt through the block loop and collect logits. + + `forced` is the record of another run. When given, the first unmask step and + the resolved block are taken from it instead of this run's own decisions. + """ + config = model.config + block_size, mask_id = config.block_size, config.mask_token_id + threshold = config.denoising_config["threshold"] + device = model.model.embed_tokens.weight.device + prompt_ids = tokenizer.apply_chat_template( + [{"role": "user", "content": prompt}], + tokenize=True, + add_generation_prompt=True, + enable_thinking=False, + ) + if hasattr(prompt_ids, "keys"): + prompt_ids = prompt_ids["input_ids"] + if forced is not None and not np.array_equal(prompt_ids, forced["prompt_ids"]): + raise ValueError("Reference trajectory was recorded with different prompt IDs.") + ids = torch.tensor([prompt_ids], device=device) + saved = {"prompt_ids": np.asarray(prompt_ids, dtype=np.int64)} + + def preview(block, cache): + """Run one preview forward. The clean cache is returned unchanged.""" + return model( + block, + attention_mask=torch.ones_like(block, dtype=torch.bool), + past_key_values=cache, + use_cache=True, + preview=True, + ) + + with torch.inference_mode(): + prefill = model(input_ids=ids, use_cache=True) + cache = prefill.past_key_values + saved["prompt_logits"] = prefill.logits[0].float().cpu().numpy() + # RoPE only depends on relative positions, so a constant shift is an + # equivalent input that rounds differently in low precision. + for shift in shifts: + positions = (torch.arange(ids.shape[1], device=device) + shift).view(1, -1) + saved[f"prompt_logits_shift_{shift}"] = ( + model(input_ids=ids, position_ids=positions, use_cache=False) + .logits[0] + .float() + .cpu() + .numpy() + ) + block = torch.full((1, block_size), mask_id, device=device, dtype=torch.long) + pending = torch.ones_like(block[0], dtype=torch.bool) + iterations = 0 + while bool(pending.any()): + iterations += 1 + logits = preview(block, cache).logits[0].float() + if iterations == 1: + saved["preview_full_mask_logits"] = logits.cpu().numpy() + elif iterations == 2: + saved["preview_partial_logits"] = logits.cpu().numpy() + raw = logits.clone() + raw[:, mask_id] = float("-inf") + confidence, prediction = raw.softmax(-1).max(-1) + confidence = confidence.masked_fill(~pending, float("-inf")) + transfer = (confidence > threshold) & pending + if not bool(transfer.any()): + transfer[confidence.argmax()] = True + if forced is not None: + if iterations == 1: + prediction = torch.from_numpy(forced["step1_prediction"]).to(device) + transfer = torch.from_numpy( + forced["step1_transfer"].astype(bool) + ).to(device) + else: + prediction = torch.from_numpy(forced["resolved_block"]).to(device) + transfer = pending.clone() + if iterations == 1: + saved.update( + step1_prediction=prediction.cpu().numpy(), + step1_transfer=transfer.cpu().numpy(), + ) + block[0, transfer] = prediction[transfer] + pending[transfer] = False + saved["resolved_block"] = block[0].cpu().numpy() + hidden = model.model(block, past_key_values=cache, use_cache=True) + saved["replay_logits"] = ( + model.lm_head(hidden.last_hidden_state)[0].float().cpu().numpy() + ) + next_block = torch.full( + (1, block_size), mask_id, device=device, dtype=torch.long + ) + saved["next_preview_logits"] = ( + preview(next_block, hidden.past_key_values).logits[0].float().cpu().numpy() + ) + saved["iterations"] = np.asarray(iterations, dtype=np.int64) + return saved + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--model", required=True, help="Checkpoint directory.") + parser.add_argument( + "--out", required=True, help="Output prefix; one `.npz` per case." + ) + parser.add_argument("--workload", type=Path, default=WORKLOAD) + parser.add_argument("--cases", type=parse_cases, default=parse_cases("0,1,2,3")) + parser.add_argument("--dtype", choices=("bfloat16", "float32"), default="bfloat16") + parser.add_argument( + "--shifts", + type=parse_shifts, + default=[], + help="Also prefill with every token position shifted by each constant.", + ) + parser.add_argument( + "--trajectory", + help="Prefix of a previous run whose first unmask step and resolved block are replayed.", + ) + args = parser.parse_args() + + items = {item["id"]: item for item in json.loads(args.workload.read_text())} + missing = [case for case in args.cases if case not in items] + if missing: + parser.error(f"The workload has no case {missing}.") + tokenizer = AutoTokenizer.from_pretrained(args.model, trust_remote_code=True) + model = AutoModelForCausalLM.from_pretrained( + args.model, + trust_remote_code=True, + dtype=getattr(torch, args.dtype), + device_map="auto", + ).eval() + Path(args.out).parent.mkdir(parents=True, exist_ok=True) + for case in args.cases: + forced = np.load(f"{args.trajectory}_{case}.npz") if args.trajectory else None + start = time.perf_counter() + saved = run_case(model, tokenizer, items[case]["prompt"], forced, args.shifts) + np.savez(f"{args.out}_{case}.npz", **saved) + print( + f"case {case}: prompt_tokens={len(saved['prompt_ids'])} " + f"iterations={int(saved['iterations'])} ({time.perf_counter() - start:.1f}s)", + flush=True, + ) + + +if __name__ == "__main__": + main() diff --git a/test/diffusion/test_clover_generation.py b/test/diffusion/test_clover_generation.py new file mode 100644 index 000000000..321773af0 --- /dev/null +++ b/test/diffusion/test_clover_generation.py @@ -0,0 +1,54 @@ +"""Exercise the Clover generation loop using CPU logits for two-token blocks.""" + +from unittest.mock import Mock, call + +import pytest +import torch +from infinilm.diffusion.clover import CloverGenerator + + +@pytest.mark.parametrize( + ("eos", "tokens", "iterations"), + [([], [1, 1, 1], [1, 1]), ([1], [], [1])], +) +def test_block_handoff_replays_only_when_another_block_follows(eos, tokens, iterations): + generator = CloverGenerator.__new__(CloverGenerator) + generator.engine = Mock(eos_token_id=eos) + generator.tokenizer = Mock() + generator.tokenizer.apply_chat_template.return_value = [9] + generator.cache_config = None + generator.torch = torch + generator.torch_device = "cpu" + generator.block_size = 2 + generator.mask_id = 2 + generator.max_context = 5 + generator._logits = lambda value: value + + # Every preview is confident about token 1, so each block resolves in one + # step: a block is replayed only to prepare the next one, and the last + # block - or a block that ends in EOS - is not replayed. + confident = torch.tensor([[0.0, 10.0, 0.0, -torch.inf]] * 2) + generator._forward = Mock( + side_effect=[ + None, + {"logits": confident}, + None, + {"logits": confident}, + ] + ) + result = generator.generate("prompt", max_new_tokens=3, threshold=0.5) + expected = [ + call([9], 0), + call([2, 2], 1, preview=True, expert_budget=False), + ] + if not eos: + expected.extend( + [ + call([1, 1], 1), + call([2, 2], 3, preview=True, expert_budget=False), + ] + ) + assert generator._forward.call_args_list == expected + assert result.iterations == iterations + assert result.token_ids == tokens + assert result.prompt_token_count == 1 diff --git a/test/diffusion/test_clover_loading.py b/test/diffusion/test_clover_loading.py new file mode 100644 index 000000000..e7d5d2772 --- /dev/null +++ b/test/diffusion/test_clover_loading.py @@ -0,0 +1,38 @@ +"""Protect the text-only Clover checkpoint layout and learned preview weights.""" + +import numpy as np +from infinilm import _core as core +from infinilm.modeling_utils import _remap_clover_moe + + +def test_clover_remap_preserves_preview_weights_and_splits_qkv(): + config = { + "linear_key_head_dim": 2, + "linear_num_key_heads": 1, + "num_experts": 2, + "moe_intermediate_size": 2, + } + prefix = "model.layers.0.linear_attn." + norm = core.from_list([0.25, -0.5], dtype=core.float32) + scalar = core.from_list([5.0, 6.0], dtype=core.float32) + packed = core.from_numpy(np.arange(24, dtype=np.float32).reshape(6, 4)) + output = _remap_clover_moe( + { + "model.norm.weight": norm, + prefix + "norm.weight": norm, + prefix + "bd_softmax_history_bias": scalar, + prefix + "in_proj_qkv.weight": packed, + }, + config, + ) + np.testing.assert_array_equal(output["model.norm.weight"].to_numpy(), [1.25, 0.5]) + np.testing.assert_array_equal( + output[prefix + "norm.weight"].to_numpy(), [0.25, -0.5] + ) + assert output[prefix + "bd_softmax_history_bias"] is scalar + assert prefix + "in_proj_qkv.weight" not in output + for part, begin in (("q", 0), ("k", 2), ("v", 4)): + np.testing.assert_array_equal( + output[prefix + f"in_proj_{part}.weight"].to_numpy(), + packed.to_numpy()[begin : begin + 2], + ) diff --git a/test/diffusion/test_frontier.py b/test/diffusion/test_frontier.py new file mode 100644 index 000000000..665d17f4c --- /dev/null +++ b/test/diffusion/test_frontier.py @@ -0,0 +1,35 @@ +"""Exercise progress, resolved-token preservation and high-confidence bypass.""" + +import importlib.util +import sys +from pathlib import Path + +import torch + +spec = importlib.util.spec_from_file_location( + "clover_frontier", + Path(__file__).parents[2] / "python/infinilm/diffusion/frontier.py", +) +module = importlib.util.module_from_spec(spec) +sys.modules[spec.name] = module +spec.loader.exec_module(module) + + +def test_confident_tokens_are_not_delayed_by_stride(): + policy = module.FrontierPolicy() + confidence = torch.ones(2, 32) + masked = torch.ones(2, 32, dtype=torch.bool) + masked[1, :7] = False + assert torch.equal(policy.select(confidence, masked, 0), masked) + + +def test_stalled_rows_progress_without_touching_finished_rows(): + policy = module.FrontierPolicy() + confidence = torch.full((3, 32), 0.1) + masked = torch.zeros(3, 32, dtype=torch.bool) + masked[0, 5:] = True + masked[1, 17] = True + selected = policy.select(confidence, masked, 3) + assert selected.sum(-1).tolist() == [1, 1, 0] + assert not (selected & ~masked).any() + assert selected[0, 5] and selected[1, 17] diff --git a/test/diffusion/workload.json b/test/diffusion/workload.json new file mode 100644 index 000000000..883b3870c --- /dev/null +++ b/test/diffusion/workload.json @@ -0,0 +1,194 @@ +[ + { + "id": 0, + "prompt": "What is 2 + 2? Reply with only the number.", + "max_tokens": 32, + "check": "4" + }, + { + "id": 1, + "prompt": "What is the capital of France? Answer in one sentence.", + "max_tokens": 64, + "check": "Paris" + }, + { + "id": 2, + "prompt": "What is the capital of Germany? Answer briefly.", + "max_tokens": 64, + "check": "Berlin" + }, + { + "id": 3, + "prompt": "Sort these numbers in ascending order: 3, 1, 2. Reply only with a JSON array.", + "max_tokens": 64, + "check": "[1, 2, 3]" + }, + { + "id": 4, + "prompt": "Return only this JSON object: {\"ok\": true, \"count\": 3}", + "max_tokens": 64, + "check": "json" + }, + { + "id": 5, + "prompt": "Translate \"good morning\" into Chinese. Answer briefly.", + "max_tokens": 64, + "check": "早" + }, + { + "id": 6, + "prompt": "Reverse the string abc. Output only the reversed string.", + "max_tokens": 32, + "check": "cba" + }, + { + "id": 7, + "prompt": "What is 6 multiplied by 7? Answer with only the number.", + "max_tokens": 32, + "check": "42" + }, + { + "id": 8, + "prompt": "Write a Python function add(a, b) that returns their sum. Return only the function.", + "max_tokens": 128, + "check": "code" + }, + { + "id": 9, + "prompt": "Write a Python function square(x) that returns x squared. Return only the function.", + "max_tokens": 128, + "check": "code" + }, + { + "id": 10, + "prompt": "用一句话解释什么是机器学习。", + "max_tokens": 128, + "check": null + }, + { + "id": 11, + "prompt": "Explain photosynthesis in two short sentences.", + "max_tokens": 128, + "check": null + }, + { + "id": 12, + "prompt": "List three primary colors of light, with no explanation.", + "max_tokens": 64, + "check": "red" + }, + { + "id": 13, + "prompt": "Give two benefits of unit testing in software.", + "max_tokens": 128, + "check": null + }, + { + "id": 14, + "prompt": "用两句话解释为什么需要备份数据。", + "max_tokens": 128, + "check": null + }, + { + "id": 15, + "prompt": "Write a polite one-sentence message declining a meeting invitation.", + "max_tokens": 128, + "check": null + }, + { + "id": 16, + "prompt": "Summarize this in one sentence: Bees transfer pollen between flowers. This helps many plants produce fruit and seeds.", + "max_tokens": 128, + "check": null + }, + { + "id": 17, + "prompt": "What is the opposite of hot? Reply with one word.", + "max_tokens": 32, + "check": "cold" + }, + { + "id": 18, + "prompt": "Return a JSON object with name Ada and age 30. No explanation.", + "max_tokens": 64, + "check": "json" + }, + { + "id": 19, + "prompt": "Complete the sequence: 2, 4, 6, 8, __. Reply with only the next number.", + "max_tokens": 32, + "check": "10" + }, + { + "id": 20, + "prompt": "Write a Python function is_even(n) that returns whether n is even. Return only code.", + "max_tokens": 128, + "check": "code" + }, + { + "id": 21, + "prompt": "Explain the difference between a list and a tuple in Python in two sentences.", + "max_tokens": 128, + "check": null + }, + { + "id": 22, + "prompt": "请用一句话解释什么是开源软件。", + "max_tokens": 128, + "check": null + }, + { + "id": 23, + "prompt": "计算:一个盒子有12个苹果,拿走5个,再放入8个,还剩多少个?", + "max_tokens": 64, + "check": "15" + }, + { + "id": 24, + "prompt": "What is the largest planet in our solar system? Answer briefly.", + "max_tokens": 64, + "check": "Jupiter" + }, + { + "id": 25, + "prompt": "Convert 100 centimeters to meters. Answer briefly.", + "max_tokens": 32, + "check": "1" + }, + { + "id": 26, + "prompt": "Write a short definition of a database index.", + "max_tokens": 128, + "check": null + }, + { + "id": 27, + "prompt": "Translate \"Thank you for your help\" into Chinese.", + "max_tokens": 64, + "check": "帮助" + }, + { + "id": 28, + "prompt": "What is 10 minus 3? Reply with only the number.", + "max_tokens": 32, + "check": "7" + }, + { + "id": 29, + "prompt": "Name the chemical formula of water. Reply with only the formula.", + "max_tokens": 32, + "check": "H2O" + }, + { + "id": 30, + "prompt": "Write a Python function that returns the nth Fibonacci number.", + "max_tokens": 192, + "check": "code" + }, + { + "id": 31, + "prompt": "Describe how to make tea in three short steps.", + "max_tokens": 128, + "check": null + } +] diff --git a/test/service/test_clover_server.py b/test/service/test_clover_server.py new file mode 100644 index 000000000..f9b78c7ab --- /dev/null +++ b/test/service/test_clover_server.py @@ -0,0 +1,165 @@ +"""CPU tests for the Clover chat endpoint and its serial generation slot.""" + +import asyncio +import threading +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest +from fastapi import HTTPException, Request +from fastapi.testclient import TestClient +from jinja2 import TemplateError +from test_agent_protocol import SERVER, load_module + +frontier = load_module( + "clover_frontier_under_test", SERVER.parent / "diffusion/frontier.py" +) +server = load_module( + "clover_server_under_test", + SERVER / "clover_server.py", + {"infinilm.diffusion.frontier": frontier}, +) +_generate_when_connected = server._generate_when_connected + + +def test_chat_template_error_releases_slot_and_valid_request_reports_usage(): + generator = Mock() + generator.generate.side_effect = [ + TemplateError("No user query found in messages."), + SimpleNamespace(text="4", token_ids=[19], prompt_token_count=7), + ] + with TestClient(server.create_app(generator)) as client: + rejected = client.post( + "/v1/chat/completions", + json={"messages": [{"role": "system", "content": "System only."}]}, + ) + assert rejected.status_code == 400 + assert rejected.json()["detail"] == "No user query found in messages." + response = client.post( + "/v1/chat/completions", + json={"messages": [{"role": "user", "content": "2+2?"}]}, + ) + assert response.status_code == 200 + assert response.json()["usage"] == { + "prompt_tokens": 7, + "completion_tokens": 1, + "total_tokens": 8, + } + assert generator.generate.call_count == 2 + + +def test_frontier_floor_above_policy_threshold_is_rejected_before_generation(): + generator = Mock() + with TestClient(server.create_app(generator)) as client: + response = client.post( + "/v1/chat/completions", + json={ + "messages": [{"role": "user", "content": "2+2?"}], + "frontier_confidence_floor": 0.96, + }, + ) + assert response.status_code == 422 + generator.generate.assert_not_called() + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +def client(): + messages = asyncio.Queue() + listening = asyncio.Event() + + async def receive(): + listening.set() + return await messages.get() + + return Request({"type": "http"}, receive), messages, listening + + +@pytest.mark.anyio +@pytest.mark.parametrize("release_at_disconnect", [False, True]) +async def test_disconnected_waiter_never_generates(release_at_disconnect): + slot = asyncio.Lock() + await slot.acquire() + request, messages, listening = client() + calls = [] + waiter = asyncio.create_task( + _generate_when_connected(request, slot, lambda: calls.append("disconnected")) + ) + await asyncio.wait_for(listening.wait(), 2) + + if release_at_disconnect: + # Make both the slot and the disconnect available in one event-loop turn. + slot.release() + messages.put_nowait({"type": "http.disconnect"}) + with pytest.raises(HTTPException) as exc: + await asyncio.wait_for(waiter, 2) + assert exc.value.status_code == 499 + assert calls == [] + assert slot.locked() == (not release_at_disconnect) + if slot.locked(): + slot.release() + + request, _, _ = client() + assert ( + await asyncio.wait_for( + _generate_when_connected(request, slot, lambda: "next"), 2 + ) + == "next" + ) + + +@pytest.mark.anyio +async def test_disconnect_already_buffered_on_admission(): + slot = asyncio.Lock() + request, messages, _ = client() + messages.put_nowait({"type": "http.disconnect"}) + with pytest.raises(HTTPException) as exc: + await _generate_when_connected(request, slot, lambda: pytest.fail("dispatched")) + assert exc.value.status_code == 499 + assert not slot.locked() + + +@pytest.mark.anyio +async def test_running_worker_keeps_slot_after_request_cancellation(): + loop = asyncio.get_running_loop() + slot = asyncio.Lock() + started = asyncio.Event() + finish = threading.Event() + calls = [] + + def first(): + calls.append("first") + loop.call_soon_threadsafe(started.set) + assert finish.wait(5) + calls.append("finished") + + request, _, _ = client() + active = asyncio.create_task(_generate_when_connected(request, slot, first)) + try: + await asyncio.wait_for(started.wait(), 2) + active.cancel() + with pytest.raises(asyncio.CancelledError): + await active + + request, _, listening = client() + queued = asyncio.create_task( + _generate_when_connected(request, slot, lambda: calls.append("cancelled")) + ) + await asyncio.wait_for(listening.wait(), 2) + queued.cancel() + with pytest.raises(asyncio.CancelledError): + await queued + assert slot.locked() + + request, _, listening = client() + live = asyncio.create_task( + _generate_when_connected(request, slot, lambda: calls.append("live")) + ) + await asyncio.wait_for(listening.wait(), 2) + finally: + finish.set() + await asyncio.wait_for(live, 2) + assert calls == ["first", "finished", "live"] diff --git a/third_party/InfiniCore b/third_party/InfiniCore index b350edf6d..2aa713783 160000 --- a/third_party/InfiniCore +++ b/third_party/InfiniCore @@ -1 +1 @@ -Subproject commit b350edf6d06f6c312ac7eb2c115008799e05e5e6 +Subproject commit 2aa713783ff0a2c41118f474ee7e2870bf5ba48f