infer_engine.cpp 7.19 KB
Newer Older
1
#include "infer_engine.hpp"
yaoht's avatar
yaoht committed
2
#include "../cache/cache.hpp"
Ceng's avatar
Ceng committed
3
#include "spdlog/spdlog.h"
4

yaoht's avatar
yaoht committed
5
6
#include <algorithm>

7
8
9
10
11
namespace infinilm::engine {

//------------------------------------------------------
// Constructor
//------------------------------------------------------
12
13
14
15
16
17
18
19
20
21
22
23
/**
 * @deprecated This function is deprecated and will be REMOVED in the next major release (v0.2.0).
 *
 * ⚠️ DEVELOPMENT POLICY:
 *   - NO new development or feature additions permitted on this interface
 *   - Only critical bug fixes (security/stability) allowed until removal
 *   - All new code MUST migrate to the polymorphic overload below
 *
 * Replacement: Use the polymorphic overload of this same function name with updated signature
 * Reason: Legacy signature lacks support for dynamic quantization modes.
 * Removal target: v0.2.0 (Q2 2026)
 */
24
InferEngine::InferEngine(
Jiacheng Huang's avatar
Jiacheng Huang committed
25
    const InfinilmModel::Config &config,
26
    const distributed::DistConfig &distributed_config,
27
    infinicore::Device::Type device_type,
28
    const cache::CacheConfig *cache_config,
29
30
    bool enable_graph_compiling,
    backends::AttentionBackend attention_backend) // Changed parameter
31
    : communication_group_(distributed_config, device_type),
32
33
      legacy_model_config_(config),
      attention_backend_(attention_backend) {
34
35
36
37
38
39
40
41
42
43
44
45
46
    if (cache_config != nullptr) {
        cache_config_ = cache_config->unique_copy();
    }
    // Create one RankWorker per rank
    int world_size = communication_group_.get_world_size();
    barrier_ = std::make_unique<RankBarrier>((size_t)world_size);
    workers_.reserve(world_size);
    for (int r = 0; r < world_size; ++r) {
        workers_.emplace_back(std::make_unique<RankWorker>(
            legacy_model_config_,
            communication_group_.get_rank_info(r),
            cache_config_ != nullptr ? cache_config_.get() : nullptr,
            barrier_.get(),
47
48
            enable_graph_compiling,
            attention_backend_));
49
50
51
52
53
    }

    // Compile the model on all workers
    this->compile();
}
54

55
56
57
58
59
InferEngine::InferEngine(
    const std::string &model_path,
    const distributed::DistConfig &distributed_config,
    infinicore::Device::Type device_type,
    const cache::CacheConfig *cache_config,
60
61
62
    bool enable_graph_compiling,
    backends::AttentionBackend attention_backend) // Changed parameter
    : communication_group_(distributed_config, device_type), attention_backend_(attention_backend) {
PanZezhong's avatar
PanZezhong committed
63
64
    if (cache_config != nullptr) {
        cache_config_ = cache_config->unique_copy();
65
    }
66
67
68

    // Load model config if model_path is provided, model_path must be valid, and config.json exists
    this->model_config_ = std::make_shared<infinilm::config::ModelConfig>(model_path + "/config.json");
69
70
    // Create one RankWorker per rank
    int world_size = communication_group_.get_world_size();
71
    barrier_ = std::make_unique<RankBarrier>((size_t)world_size);
72
73
    workers_.reserve(world_size);
    for (int r = 0; r < world_size; ++r) {
74
75
76
        workers_.emplace_back(std::make_unique<RankWorker>(
            model_config_,
            communication_group_.get_rank_info(r),
77
            cache_config_ != nullptr ? cache_config_.get() : nullptr,
78
            barrier_.get(),
79
80
            enable_graph_compiling,
            attention_backend_));
81
    }
82
83
    // Compile the model on all workers
    this->compile();
84
85
86
87
88
89
90
91
92
93
94
}

//------------------------------------------------------
// load_param
//------------------------------------------------------
void InferEngine::load_param(const std::string &name, const infinicore::Tensor &param) {
    // Load the parameter on all workers
    for (auto &worker : workers_) {
        worker->load_param(name, param);
    }
}
95

96
97
98
//------------------------------------------------------
// state_dict
//------------------------------------------------------
99
100
std::vector<std::unordered_map<std::string, infinicore::nn::Parameter>> InferEngine::state_dict() {
    std::vector<std::unordered_map<std::string, infinicore::nn::Parameter>> results;
101
102
103
    if (0 == workers_.size()) {
        throw std::runtime_error(" Model object not found. ");
    }
104
105
106
107
108

    for (auto &worker : workers_) {
        results.push_back(worker->state_dict());
    }
    return results;
109
110
}

111
//------------------------------------------------------
112
// forward
113
//------------------------------------------------------
114
infinilm::InfinilmModel::Input
yaoht's avatar
yaoht committed
115
InferEngine::Input::to_model_input(infinicore::Device device, const cache::CacheConfig *cache_config) const {
116

117
118
119
120
    auto to_device = [&](const std::optional<infinicore::Tensor> &t)
        -> std::optional<infinicore::Tensor> {
        return t.has_value() ? t.value()->to(device) : t;
    };
121

yaoht's avatar
yaoht committed
122
    InfinilmModel::Input out{
123
        to_device(input_ids), // @todo: on device in the future
124
        to_device(position_ids),
125
        to_device(past_sequence_lengths), // @todo: on device in the future
126
127
        to_device(total_sequence_lengths),
        to_device(input_offsets),
128
        to_device(cu_seqlens),
129
130
131
        to_device(block_tables),
        to_device(slot_mapping),
    };
yaoht's avatar
yaoht committed
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152

    // Paged prefill FA: bounds without reading GPU tensor payloads (shape / cache config only).
    if (cache_config != nullptr) {
        if (const auto *paged = dynamic_cast<const cache::PagedKVCacheConfig *>(cache_config)) {
            if (out.block_tables.has_value()) {
                out.max_seqlen_k = static_cast<int>(out.block_tables.value()->size(1) * paged->block_size());
            }
            if (out.slot_mapping.has_value()) {
                out.max_seqlen_q = static_cast<int>(out.slot_mapping.value()->size(0));
            } else if (out.input_ids.has_value()) {
                const auto &sh = out.input_ids.value()->shape();
                if (sh.size() == 1) {
                    out.max_seqlen_q = static_cast<int>(sh[0]);
                } else if (sh.size() >= 2) {
                    out.max_seqlen_q = static_cast<int>(std::max(sh[0], sh[1]));
                }
            }
        }
    }

    return out;
PanZezhong's avatar
PanZezhong committed
153
}
154

PanZezhong's avatar
PanZezhong committed
155
InferEngine::Output InferEngine::forward(const InferEngine::Input &input) {
156
157
    // Trigger each worker to run inference
    for (auto &worker : workers_) {
158
        worker->run(input);
159
    }
PanZezhong's avatar
PanZezhong committed
160
161
162
163
    // Wait for all workers
    for (auto &worker : workers_) {
        worker->wait();
    }
164

165
    return workers_[0]->get_output();
166
167
}

168
169
170
171
172
173
174
175
176
177
void InferEngine::compile() {
    for (auto &worker : workers_) {
        worker->compile();
    }
    // Wait for all workers
    for (auto &worker : workers_) {
        worker->wait();
    }
}

178
179
180
181
182
183
184
185
186
187
188
189
190
191
//------------------------------------------------------
// Destructor
//------------------------------------------------------
InferEngine::~InferEngine() {
    // Close all workers
    for (auto &worker : workers_) {
        worker->close();
    }
}

const distributed::DistConfig &InferEngine::get_dist_config() const {
    return communication_group_.get_dist_config();
}

192
193
194
//------------------------------------------------------
// reset_cache (overloaded with CacheConfig)
//------------------------------------------------------
PanZezhong's avatar
PanZezhong committed
195
void InferEngine::reset_cache(const cache::CacheConfig *new_config) {
Ceng's avatar
Ceng committed
196
    for (auto &worker : workers_) {
PanZezhong's avatar
PanZezhong committed
197
        worker->reset_cache(new_config);
198
199
200
    }
    for (auto &worker : workers_) {
        worker->wait();
Ceng's avatar
Ceng committed
201
    }
PanZezhong's avatar
PanZezhong committed
202
    cache_config_ = new_config->unique_copy();
203
    this->compile();
Ceng's avatar
Ceng committed
204
205
}

206
} // namespace infinilm::engine