|
| 1 | +/* Copyright 2025 The xLLM Authors. All Rights Reserved. |
| 2 | +
|
| 3 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +you may not use this file except in compliance with the License. |
| 5 | +You may obtain a copy of the License at |
| 6 | +
|
| 7 | + https://github.com/jd-opensource/xllm/blob/main/LICENSE |
| 8 | +
|
| 9 | +Unless required by applicable law or agreed to in writing, software |
| 10 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +See the License for the specific language governing permissions and |
| 13 | +limitations under the License. |
| 14 | +==============================================================================*/ |
| 15 | + |
| 16 | +#pragma once |
| 17 | + |
| 18 | +#include <torch/torch.h> |
| 19 | + |
| 20 | +#include <string> |
| 21 | +#include <typeinfo> |
| 22 | +#include <vector> |
| 23 | + |
| 24 | +#include "core/common/global_flags.h" |
| 25 | +#include "core/common/interruption_bus.h" |
| 26 | +#include "core/framework/kv_cache/kv_cache.h" |
| 27 | +#include "core/framework/model/model_input_params.h" |
| 28 | +#include "core/framework/model_context.h" |
| 29 | +#include "core/layers/attention_mask.h" |
| 30 | +#include "core/layers/common/layer_utils.h" |
| 31 | +#include "core/layers/lm_head.h" |
| 32 | +#include "core/layers/rms_norm.h" |
| 33 | +#include "models/model_registry.h" |
| 34 | +#if defined(USE_CUDA) |
| 35 | +#include "core/layers/cuda/attention.h" |
| 36 | +#endif |
| 37 | +#if defined(USE_MLU) |
| 38 | +#include "core/layers/mlu/attention.h" |
| 39 | +#endif |
| 40 | + |
| 41 | +namespace xllm { |
| 42 | + |
| 43 | +template <typename DecoderType> |
| 44 | +class LlmDecoderLayerImplBase : public torch::nn::Module { |
| 45 | + public: |
| 46 | + LlmDecoderLayerImplBase(const ModelContext& context) { |
| 47 | + // register submodules |
| 48 | + decoder_layer_ = register_module("decoder_layer", DecoderType(context)); |
| 49 | + } |
| 50 | + |
| 51 | + virtual torch::Tensor forward(torch::Tensor& x, |
| 52 | + torch::Tensor& positions, |
| 53 | + const layer::AttentionMetadata& attn_metadata, |
| 54 | + KVCache& kv_cache, |
| 55 | + const ModelInputParams& input_params) { |
| 56 | + return decoder_layer_(x, positions, attn_metadata, kv_cache, input_params); |
| 57 | + } |
| 58 | + |
| 59 | + // load the weight from the checkpoint |
| 60 | + virtual void load_state_dict(const StateDict& state_dict) { |
| 61 | + // call each submodule's load_state_dict function |
| 62 | + decoder_layer_->load_state_dict(state_dict); |
| 63 | + } |
| 64 | + |
| 65 | + private: |
| 66 | + DecoderType decoder_layer_{nullptr}; |
| 67 | +}; |
| 68 | + |
| 69 | +template <typename DecoderLayerType> |
| 70 | +class LlmModelImplBase : public torch::nn::Module { |
| 71 | + public: |
| 72 | + // mode type: qwen2, qwen3 .etc |
| 73 | + LlmModelImplBase(const std::string& model_type, const ModelArgs& args) |
| 74 | + : model_type_(model_type) { |
| 75 | + InterruptionBus::get_instance().subscribe([this](bool interrupted) { |
| 76 | + this->layer_forward_interrupted_ = interrupted; |
| 77 | + }); |
| 78 | + mrope_section_ = args.rope_scaling_mrope_section(); |
| 79 | + } |
| 80 | + |
| 81 | + torch::Tensor get_input_embeddings(torch::Tensor input_ids) { |
| 82 | + return embed_tokens_(input_ids); |
| 83 | + } |
| 84 | + |
| 85 | + // tokens: [num_tokens] |
| 86 | + // positions: [num_tokens] token pos in the sequence |
| 87 | + virtual torch::Tensor forward(torch::Tensor tokens, |
| 88 | + torch::Tensor positions, |
| 89 | + std::vector<KVCache>& kv_caches, |
| 90 | + const ModelInputParams& input_params) { |
| 91 | + if (tokens.numel() == 0) { |
| 92 | + tokens = torch::tensor({1}).to(torch::kInt32).to(tokens.device()); |
| 93 | + positions = torch::tensor({0}).to(torch::kInt32).to(tokens.device()); |
| 94 | + } |
| 95 | + auto inputs_embeds = input_params.input_embedding; |
| 96 | + // test |
| 97 | + torch::Tensor h; |
| 98 | + if (inputs_embeds.defined()) { |
| 99 | + h = inputs_embeds; |
| 100 | + } else { |
| 101 | + h = embed_tokens_(tokens); |
| 102 | + } |
| 103 | + |
| 104 | + auto modified_input_params = input_params; |
| 105 | + auto position = positions; |
| 106 | + layer::update_dummy_run_input(dp_rank_, position, modified_input_params); |
| 107 | + bool is_prefill = modified_input_params.q_max_seq_len > 1; |
| 108 | + auto attn_metadata = |
| 109 | + layer::AttentionMetadata::build(modified_input_params, is_prefill); |
| 110 | + |
| 111 | + torch::Tensor h_ret; |
| 112 | + for (size_t i = 0; i < layers_.size(); i++) { |
| 113 | + auto& layer = layers_[i]; |
| 114 | + h_ret = layer( |
| 115 | + h, position, attn_metadata, kv_caches[i], modified_input_params); |
| 116 | + } |
| 117 | + return norm_(h_ret); |
| 118 | + } |
| 119 | + |
| 120 | + // load the weight from the checkpoint |
| 121 | + virtual void load_state_dict(const StateDict& state_dict) { |
| 122 | + embed_tokens_->load_state_dict( |
| 123 | + state_dict.get_dict_with_prefix("embed_tokens.")); |
| 124 | + |
| 125 | + // call each layer's load_state_dict function |
| 126 | + for (int i = 0; i < layers_.size(); i++) { |
| 127 | + layers_[i]->load_state_dict( |
| 128 | + state_dict.get_dict_with_prefix("layers." + std::to_string(i) + ".")); |
| 129 | + } |
| 130 | + norm_->load_state_dict(state_dict.get_dict_with_prefix("norm.")); |
| 131 | + } |
| 132 | + |
| 133 | + virtual layer::WordEmbedding get_word_embedding() { return embed_tokens_; } |
| 134 | + |
| 135 | + virtual void set_word_embedding(layer::WordEmbedding& word_embedding) { |
| 136 | + embed_tokens_ = word_embedding; |
| 137 | + } |
| 138 | + |
| 139 | + protected: |
| 140 | + int max_seq_len_ = 0; |
| 141 | + torch::Tensor cos_pos_; |
| 142 | + torch::Tensor sin_pos_; |
| 143 | + int device_id = 0; |
| 144 | + layer::AttentionMask attn_mask_; |
| 145 | + int dp_rank_ = 0; |
| 146 | + |
| 147 | + std::vector<int64_t> mrope_section_; |
| 148 | + // test |
| 149 | + // ParallelEmbedding embed_tokens_{nullptr}; |
| 150 | + layer::WordEmbedding embed_tokens_{nullptr}; |
| 151 | + layer::RmsNorm norm_{nullptr}; |
| 152 | + |
| 153 | + torch::nn::ModuleList blocks_{nullptr}; |
| 154 | + // hold same data but different type as blocks_ to avoid type cast |
| 155 | + std::vector<DecoderLayerType> layers_; |
| 156 | + |
| 157 | + bool layer_forward_interrupted_ = false; |
| 158 | + |
| 159 | + private: |
| 160 | + std::string model_type_; |
| 161 | +}; |
| 162 | + |
| 163 | +template <typename LlmModelType> |
| 164 | +class LlmForCausalLMImplBase : public torch::nn::Module { |
| 165 | + public: |
| 166 | + LlmForCausalLMImplBase(const ModelContext& context) { |
| 167 | + tie_word_embeddings = context.get_model_args().tie_word_embeddings(); |
| 168 | + // register submodules |
| 169 | + model_ = register_module("model", LlmModelType(context)); |
| 170 | + |
| 171 | + lm_head_ = register_module("lm_head", layer::LmHead(context)); |
| 172 | + } |
| 173 | + |
| 174 | + torch::Tensor get_input_embeddings(torch::Tensor input_ids) { |
| 175 | + return model_->get_input_embeddings(input_ids); |
| 176 | + } |
| 177 | + |
| 178 | + // tokens: [num_tokens] |
| 179 | + // positions: [num_tokens] token pos in the sequence |
| 180 | + // returns: [num_tokens, hidden_size] |
| 181 | + virtual torch::Tensor forward(const torch::Tensor& tokens, |
| 182 | + const torch::Tensor& positions, |
| 183 | + std::vector<KVCache>& kv_caches, |
| 184 | + const ModelInputParams& input_params) { |
| 185 | + return model_(tokens, positions, kv_caches, input_params); |
| 186 | + } |
| 187 | + |
| 188 | + // hidden_states: [num_tokens, hidden_size] |
| 189 | + // seleted_idxes: [num_tokens] |
| 190 | + // returns: [num_tokens, vocab_size] |
| 191 | + virtual torch::Tensor logits(const torch::Tensor& hidden_states, |
| 192 | + const torch::Tensor& seleted_idxes) { |
| 193 | + // select tokens if provided |
| 194 | + auto h = hidden_states; |
| 195 | + if (seleted_idxes.defined()) { |
| 196 | + h = h.index_select(/*dim=*/0, seleted_idxes); |
| 197 | + } |
| 198 | + return lm_head_(h); |
| 199 | + } |
| 200 | + |
| 201 | + void load_model(std::unique_ptr<ModelLoader> loader, |
| 202 | + std::string prefix = "model." /*llm model weight prefix*/) { |
| 203 | + for (const auto& state_dict : loader->get_state_dicts()) { |
| 204 | + model_->load_state_dict(state_dict->get_dict_with_prefix(prefix)); |
| 205 | + if (tie_word_embeddings) { |
| 206 | + lm_head_->load_state_dict( |
| 207 | + state_dict->get_dict_with_prefix(prefix + "embed_tokens.")); |
| 208 | + } else { |
| 209 | + lm_head_->load_state_dict(state_dict->get_dict_with_prefix("lm_head.")); |
| 210 | + } |
| 211 | + } |
| 212 | + } |
| 213 | + |
| 214 | + virtual void prepare_expert_weight(int32_t layer_id, |
| 215 | + const std::vector<int32_t>& expert_ids) { |
| 216 | + return; |
| 217 | + } |
| 218 | + virtual void update_expert_weight(int32_t layer_id) { return; } |
| 219 | + |
| 220 | + virtual layer::LmHead get_lm_head() { return lm_head_; } |
| 221 | + |
| 222 | + virtual void set_lm_head(layer::LmHead& head) { lm_head_ = head; } |
| 223 | + |
| 224 | + virtual layer::WordEmbedding get_word_embedding() { |
| 225 | + return model_->get_word_embedding(); |
| 226 | + } |
| 227 | + |
| 228 | + virtual void set_word_embedding(layer::WordEmbedding& word_embedding) { |
| 229 | + model_->set_word_embedding(word_embedding); |
| 230 | + } |
| 231 | + |
| 232 | + protected: |
| 233 | + // parameter members, must be registered |
| 234 | + LlmModelType model_{nullptr}; |
| 235 | + int device_id = 0; |
| 236 | + bool tie_word_embeddings{false}; |
| 237 | + layer::LmHead lm_head_{nullptr}; |
| 238 | +}; |
| 239 | + |
| 240 | +} // namespace xllm |
0 commit comments