LlamaTritonModel.cc 22.5 KB
Newer Older
Li Zhang's avatar
Li Zhang committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/*
 * Copyright (c) OpenMMLab. All rights reserved.
 * Copyright (c) 2020-2023, NVIDIA CORPORATION.  All rights reserved.
 *
 * 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.
 */

Li Zhang's avatar
Li Zhang committed
18
// Modified from
lvhan028's avatar
lvhan028 committed
19
// https://github.com/NVIDIA/FasterTransformer/blob/main/src/turbomind/triton_backend/multi_gpu_gpt/ParallelGptTritonModel.cc
Li Zhang's avatar
Li Zhang committed
20

lvhan028's avatar
lvhan028 committed
21
#include "src/turbomind/triton_backend/llama/LlamaTritonModel.h"
Li Zhang's avatar
Li Zhang committed
22
#include "3rdparty/INIReader.h"
lvhan028's avatar
lvhan028 committed
23
24
25
26
#include "src/turbomind/models/llama/LlamaInstanceComm.h"
#include "src/turbomind/triton_backend/llama/LlamaTritonModelInstance.h"
#include "src/turbomind/triton_backend/transformer_triton_backend.hpp"
#include "src/turbomind/utils/allocator.h"
Li Zhang's avatar
Li Zhang committed
27
28
#include <mutex>

lvhan028's avatar
lvhan028 committed
29
namespace ft = turbomind;
Li Zhang's avatar
Li Zhang committed
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

std::shared_ptr<AbstractTransformerModel> AbstractTransformerModel::createLlamaModel(std::string inifile)
{
    INIReader reader = INIReader(inifile);
    if (reader.ParseError() < 0) {
        std::cout << "[ERROR] Can't load '" << inifile << "'\n";
        return nullptr;
    }

    const std::string data_type        = reader.Get("ft_instance_hyperparameter", "data_type");
    int               tensor_para_size = reader.GetInteger("ft_instance_hyperparameter", "tensor_para_size");
    std::string       model_dir        = reader.Get("ft_instance_hyperparameter", "model_dir");

    if (data_type == "half" || data_type == "fp16") {
        return std::make_shared<LlamaTritonModel<half>>(
            reader.GetInteger("ft_instance_hyperparameter", "tensor_para_size"),
            reader.GetInteger("ft_instance_hyperparameter", "pipeline_para_size"),
            reader.GetInteger("ft_instance_hyperparameter", "enable_custom_all_reduce", 0),
            model_dir);
    }
zhouxiang's avatar
zhouxiang committed
50
#ifdef ENABLE_BF16
q.yao's avatar
q.yao committed
51
52
53
54
55
56
57
58
59
60
61
62
    else if (data_type == "bf16") {
#ifdef ENABLE_BF16
        return std::make_shared<LlamaTritonModel<__nv_bfloat16>>(
            reader.GetInteger("ft_instance_hyperparameter", "tensor_para_size"),
            reader.GetInteger("ft_instance_hyperparameter", "pipeline_para_size"),
            reader.GetInteger("ft_instance_hyperparameter", "enable_custom_all_reduce", 0),
            model_dir);
#else
        TM_LOG_ERROR("[ERROR] Turbomind is not built with ENABLE_BF16");
        ft::FT_CHECK(false);
#endif
    }
zhouxiang's avatar
zhouxiang committed
63
#endif
Li Zhang's avatar
Li Zhang committed
64
65
66
67
68
69
70
71
72
73
74
75
    else {
        return std::make_shared<LlamaTritonModel<float>>(
            reader.GetInteger("ft_instance_hyperparameter", "tensor_para_size"),
            reader.GetInteger("ft_instance_hyperparameter", "pipeline_para_size"),
            reader.GetInteger("ft_instance_hyperparameter", "enable_custom_all_reduce", 0),
            model_dir);
    }
}

template<typename T>
void LlamaTritonModel<T>::handleMissingParams()
{
76
77
78
79
80
    if (kv_head_num_ == 0) {
        kv_head_num_ = head_num_;
        TM_LOG_WARNING("[LlamaTritonModel] `kv_head_num` is not set, default to `head_num` (%d).", (int)kv_head_num_);
    }

81
82
83
84
    if (!attn_params_.max_position_embeddings) {
        attn_params_.max_position_embeddings = 2048;
        TM_LOG_WARNING("[LlamaTritonModel] `max_position_embeddings` is not set, default to %d.",
                       (int)attn_params_.max_position_embeddings);
Li Zhang's avatar
Li Zhang committed
85
86
    }

87
88
89
90
    if (!engine_params_.max_batch_size) {
        engine_params_.max_batch_size = 64;
        TM_LOG_WARNING("[LlamaTritonModel] `max_batch_size` is not set, default to %d.",
                       (int)engine_params_.max_batch_size);
Li Zhang's avatar
Li Zhang committed
91
92
    }

93
94
95
    if (!engine_params_.session_len) {
        engine_params_.session_len = attn_params_.max_position_embeddings;
        TM_LOG_WARNING("[LlamaTritonModel] `session_len` is not set, default to %d.", (int)engine_params_.session_len);
Li Zhang's avatar
Li Zhang committed
96
97
    }

98
99
    if (!engine_params_.max_context_token_num) {
        engine_params_.max_context_token_num = engine_params_.session_len;
lvhan028's avatar
lvhan028 committed
100
        TM_LOG_WARNING("[LlamaTritonModel] `max_context_token_num` is not set, default to %d.",
101
                       (int)engine_params_.max_context_token_num);
Li Zhang's avatar
Li Zhang committed
102
103
    }

104
105
106
    if (engine_params_.max_context_token_num <= engine_params_.max_batch_size) {
        engine_params_.max_context_token_num *= engine_params_.session_len;
        TM_LOG_WARNING("[LlamaTritonModel] `max_context_token_num` = %d.", (int)engine_params_.max_context_token_num);
Li Zhang's avatar
Li Zhang committed
107
108
    }

109
110
111
112
113
114
115
116
    if (!engine_params_.step_length) {
        engine_params_.step_length = 1;
    }

    if (!engine_params_.cache_max_block_count) {
        engine_params_.cache_max_block_count = .95f;
        TM_LOG_WARNING("[LlamaTritonModel] `cache_max_entry_count` is not set, default to %f.",
                       engine_params_.cache_max_block_count);
Li Zhang's avatar
Li Zhang committed
117
118
119
120
121
    }

    if (!cache_block_seq_len_) {
        cache_block_seq_len_ = 128;
        TM_LOG_WARNING("[LlamaTritonModel] `cache_block_seq_len` is not set, default to %d.", cache_block_seq_len_);
Li Zhang's avatar
Li Zhang committed
122
123
    }

124
125
126
127
128
129
130
131
132
133
    if (!engine_params_.cache_chunk_size) {
        engine_params_.cache_chunk_size = engine_params_.cache_max_block_count;
        TM_LOG_WARNING("[LlamaTritonModel] `cache_chunk_size` is not set, default to %d.",
                       (int)engine_params_.cache_chunk_size);
    }

    if (!engine_params_.num_tokens_per_iter) {
        engine_params_.num_tokens_per_iter = engine_params_.max_context_token_num;
        TM_LOG_WARNING("[LlamaTritonModel] `num_tokens_per_iter` is not set, default to `max_context_token_num` (%d).",
                       (int)engine_params_.num_tokens_per_iter);
Li Zhang's avatar
Li Zhang committed
134
135
136
137
138
139
140
    }
}

template<typename T>
LlamaTritonModel<T>::LlamaTritonModel(size_t      tensor_para_size,
                                      size_t      pipeline_para_size,
                                      int         enable_custom_all_reduce,
141
142
                                      std::string model_dir,
                                      std::string config):
Li Zhang's avatar
Li Zhang committed
143
144
145
146
147
    tensor_para_size_(tensor_para_size),
    pipeline_para_size_(pipeline_para_size),
    shared_weights_(std::vector<std::shared_ptr<ft::LlamaWeight<T>>>(ft::getDeviceCount())),
    enable_custom_all_reduce_(enable_custom_all_reduce)
{
148
    INIReader reader;
zhouxiang's avatar
zhouxiang committed
149
150
151
152
153
154
155
156
157
158
159
    FT_CHECK_WITH_INFO(!(config.empty() && model_dir.empty()), "invalid init options");

    if (!model_dir.empty()) {
        model_dir_ = model_dir;
        const std::string inifile{model_dir + "/config.ini"};
        reader = INIReader(inifile);
        if (reader.ParseError() < 0) {
            TM_LOG_ERROR("[ERROR] Can't load %s", inifile.c_str());
            ft::FT_CHECK(false);
        }
    }
160
161
162
163
164
165
166
167
168
169
170
171

    if (!config.empty()) {
        std::FILE* tmpf = std::tmpfile();
        std::fputs(config.c_str(), tmpf);
        std::rewind(tmpf);
        reader = INIReader(tmpf);
        if (reader.ParseError() < 0) {
            TM_LOG_ERROR("[ERROR] Can't init with config %s", config.c_str());
            ft::FT_CHECK(false);
        }
    }

172
173
174
175
176
177
178
179
180
181
    model_name_          = reader.Get("llama", "model_name");
    head_num_            = reader.GetInteger("llama", "head_num");
    kv_head_num_         = reader.GetInteger("llama", "kv_head_num", 0);
    size_per_head_       = reader.GetInteger("llama", "size_per_head");
    inter_size_          = reader.GetInteger("llama", "inter_size");
    num_layer_           = reader.GetInteger("llama", "num_layer");
    vocab_size_          = reader.GetInteger("llama", "vocab_size");
    norm_eps_            = reader.GetFloat("llama", "norm_eps");
    start_id_            = reader.GetInteger("llama", "start_id");
    end_id_              = reader.GetInteger("llama", "end_id");
182
183
    // use_context_fmha_    = reader.GetInteger("llama", "use_context_fmha", 1);
    use_context_fmha_    = 0;
184
    cache_block_seq_len_ = reader.GetInteger("llama", "cache_block_seq_len", 0);
Li Zhang's avatar
Li Zhang committed
185
186
187
188

    attn_bias_    = reader.GetInteger("llama", "attn_bias", 0);
    quant_policy_ = reader.GetInteger("llama", "quant_policy", 0);
    group_size_   = reader.GetInteger("llama", "group_size", 0);
gaoqiong's avatar
gaoqiong committed
189
    w4_weight_layout_   = reader.GetInteger("llama", "w4_weight_layout", 2);
gaoqiong's avatar
gaoqiong committed
190
    w4_pad_size_ = reader.GetInteger("llama", "w4_pad_size", 2);
Li Zhang's avatar
Li Zhang committed
191

Li Zhang's avatar
Li Zhang committed
192
193
    // rotary embedding parameters
    attn_params_.rotary_embedding_dim    = reader.GetInteger("llama", "rotary_embedding");
Lyu Han's avatar
Lyu Han committed
194
    attn_params_.rotary_embedding_base   = reader.GetFloat("llama", "rope_theta", 10000.0f);
Li Zhang's avatar
Li Zhang committed
195
    attn_params_.rope_scaling_factor     = reader.GetFloat("llama", "rope_scaling_factor", 0.f);
196
    attn_params_.max_position_embeddings = reader.GetInteger("llama", "max_position_embeddings", 0);
Li Zhang's avatar
Li Zhang committed
197
    // attn_params_.use_dynamic_ntk         = reader.GetInteger("llama", "use_dynamic_ntk", 0);
198
    attn_params_.use_logn_attn = reader.GetInteger("llama", "use_logn_attn", 0);
199

200
201
202
203
    engine_params_.max_batch_size        = reader.GetInteger("llama", "max_batch_size", 0);
    engine_params_.max_context_token_num = reader.GetInteger("llama", "max_context_token_num", 0);
    engine_params_.session_len           = reader.GetInteger("llama", "session_len", 0);
    engine_params_.step_length           = reader.GetInteger("llama", "step_length", 0);
Li Zhang's avatar
Li Zhang committed
204

205
206
207
208
209
210
211
212
    engine_params_.cache_max_block_count = reader.GetFloat("llama", "cache_max_entry_count", 0);
    engine_params_.cache_chunk_size      = reader.GetInteger("llama", "cache_chunk_size", 0);

    engine_params_.num_tokens_per_iter   = reader.GetInteger("llama", "num_tokens_per_iter", 0);
    engine_params_.extra_tokens_per_iter = reader.GetInteger("llama", "extra_tokens_per_iter", 0);
    engine_params_.max_prefill_iters     = reader.GetInteger("llama", "max_prefill_iters", 1);

    handleMissingParams();
Li Zhang's avatar
Li Zhang committed
213
214
215
216
217
218
219
220
221
222
223
224

    shared_state_          = std::make_shared<typename ft::LlamaV2<T>::SharedState>();
    shared_state_->barrier = std::make_shared<ft::Barrier>(tensor_para_size);

    const auto device_count = ft::getDeviceCount();
    shared_instances_.resize(device_count);
    shared_mutexes_.resize(device_count);

    const std::string weight_type_str = reader.Get("llama", "weight_type");
    if (weight_type_str == "fp16") {
        weight_type_ = ft::WeightType::kFP16;
    }
q.yao's avatar
q.yao committed
225
226
227
    else if (weight_type_str == "bf16") {
        weight_type_ = ft::WeightType::kBF16;
    }
Li Zhang's avatar
Li Zhang committed
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
    else if (weight_type_str == "fp32") {
        weight_type_ = ft::WeightType::kFP32;
    }
    else if (weight_type_str == "int8") {
        weight_type_ = ft::WeightType::kINT8;
    }
    else if (weight_type_str == "int4") {
        weight_type_ = ft::WeightType::kINT4;
    }
    else {
        std::cout << "[ERROR] Unsupported weight type: '" << weight_type_str << "'\n";
        ft::FT_CHECK(0);
    }
}

template<typename T>
std::unique_ptr<LlamaTritonSharedModelInstance<T>> LlamaTritonModel<T>::createSharedModelInstance(
    int                                                               device_id,
    int                                                               rank,
    std::pair<std::vector<ft::NcclParam>, std::vector<ft::NcclParam>> nccl_params,
    std::shared_ptr<ft::AbstractCustomComm>                           custom_all_reduce_comm)
{
    ft::check_cuda_error(cudaSetDevice(device_id));
    const int comms_rank = device_id % (tensor_para_size_ * pipeline_para_size_);

    std::unique_ptr<ft::Allocator<ft::AllocatorType::CUDA>> allocator(
        new ft::Allocator<ft::AllocatorType::CUDA>(device_id));

    /// TODO: this stream handle is leaked
    cudaStream_t stream{};
    ft::check_cuda_error(cudaStreamCreate(&stream));

    allocator->setStream(stream);

    cublasHandle_t   cublas_handle;
    cublasLtHandle_t cublaslt_handle;

    cublasCreate(&cublas_handle);
xiabo's avatar
xiabo committed
266
    // cublasLtCreate(&cublaslt_handle);
Li Zhang's avatar
Li Zhang committed
267
268
269
270
271
272
273
274
275
276
    cublasSetStream(cublas_handle, stream);

    std::unique_ptr<ft::cublasAlgoMap>   cublas_algo_map(new ft::cublasAlgoMap("gemm_config.in"));
    std::unique_ptr<std::mutex>          cublas_wrapper_mutex(new std::mutex());
    std::unique_ptr<ft::cublasMMWrapper> cublas_wrapper(new ft::cublasMMWrapper(
        cublas_handle, cublaslt_handle, stream, cublas_algo_map.get(), cublas_wrapper_mutex.get(), allocator.get()));

    std::unique_ptr<cudaDeviceProp> cuda_device_prop_ptr(new cudaDeviceProp);
    ft::check_cuda_error(cudaGetDeviceProperties(cuda_device_prop_ptr.get(), device_id));

zhouxiang's avatar
zhouxiang committed
277
278
279
280
281
282
    int hgemm_switch = 0;
    const char* env_var_value_str = std::getenv("LMDEPLOY_HGEMM_SWITCH");
    if (env_var_value_str != nullptr) {
        hgemm_switch = std::stoi(env_var_value_str);
    }

Li Zhang's avatar
Li Zhang committed
283
    if (std::is_same<T, half>::value) {
zhouxiang's avatar
zhouxiang committed
284
285
286
287
288
289
        if(hgemm_switch == 2){
            cublas_wrapper->setGemmConfig(CUDA_R_16F, CUDA_R_16F, CUDA_R_16F, CUDA_R_16F);
        }
        else{
            cublas_wrapper->setGemmConfig(CUDA_R_16F, CUDA_R_16F, CUDA_R_16F, CUDA_R_32F);
        }
Li Zhang's avatar
Li Zhang committed
290
291
292
293
    }
    else if (std::is_same<T, float>::value) {
        cublas_wrapper->setFP32GemmConfig();
    }
q.yao's avatar
q.yao committed
294
295
296
297
298
#ifdef ENABLE_BF16
    else if (std::is_same<T, __nv_bfloat16>::value) {
        cublas_wrapper->setBF16GemmConfig();
    }
#endif
Li Zhang's avatar
Li Zhang committed
299
300
301
302
303

    ft::NcclParam tensor_para   = nccl_params.first[comms_rank];
    ft::NcclParam pipeline_para = nccl_params.second[comms_rank];

    ft::FT_CHECK(tensor_para.world_size_ == tensor_para_size_);
Li Zhang's avatar
Li Zhang committed
304
    ft::FT_CHECK(pipeline_para.world_size_ == pipeline_para_size_);
Li Zhang's avatar
Li Zhang committed
305
306

    auto llama = std::make_unique<ft::LlamaV2<T>>(head_num_,
307
                                                  kv_head_num_,
Li Zhang's avatar
Li Zhang committed
308
309
310
311
312
                                                  size_per_head_,
                                                  inter_size_,
                                                  num_layer_,
                                                  vocab_size_,
                                                  norm_eps_,
313
                                                  attn_params_,
Li Zhang's avatar
Li Zhang committed
314
315
                                                  start_id_,
                                                  end_id_,
Li Zhang's avatar
Li Zhang committed
316
                                                  cache_block_seq_len_,
317
                                                  quant_policy_,
Li Zhang's avatar
Li Zhang committed
318
                                                  use_context_fmha_,
319
                                                  engine_params_,
Li Zhang's avatar
Li Zhang committed
320
321
322
323
324
325
326
327
328
329
                                                  shared_state_,
                                                  shared_weights_[device_id].get(),
                                                  tensor_para,
                                                  stream,
                                                  cublas_wrapper.get(),
                                                  allocator.get(),
                                                  false,  // is_free_buffer_after_forward,
                                                  cuda_device_prop_ptr.get());

    return std::make_unique<LlamaTritonSharedModelInstance<T>>(
Lyu Han's avatar
Lyu Han committed
330
        LlamaTritonSharedModelInstance<T>{std::move(allocator),
Li Zhang's avatar
Li Zhang committed
331
332
333
334
                                          std::move(cublas_algo_map),
                                          std::move(cublas_wrapper_mutex),
                                          std::move(cublas_wrapper),
                                          std::move(cuda_device_prop_ptr),
Lyu Han's avatar
Lyu Han committed
335
336
                                          shared_weights_[device_id],
                                          std::move(llama),
337
                                          engine_params_.session_len});
Li Zhang's avatar
Li Zhang committed
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
}

template<typename T>
std::unique_ptr<AbstractTransformerModelInstance>
LlamaTritonModel<T>::createModelInstance(int                                                               device_id,
                                         int                                                               rank,
                                         cudaStream_t                                                      stream,
                                         std::pair<std::vector<ft::NcclParam>, std::vector<ft::NcclParam>> nccl_params,
                                         std::shared_ptr<ft::AbstractCustomComm> custom_all_reduce_comm)
{
    ft::check_cuda_error(cudaSetDevice(device_id));
    // const int comms_rank = device_id % (tensor_para_size_ * pipeline_para_size_);

    std::shared_ptr<LlamaTritonSharedModelInstance<T>> instance;
    {
        std::lock_guard<std::mutex> lock(shared_mutexes_[device_id]);
354
        instance = shared_instances_[device_id];
Li Zhang's avatar
Li Zhang committed
355
356
        if (!instance) {
            instance = createSharedModelInstance(device_id, rank, nccl_params, custom_all_reduce_comm);
Chen Xin's avatar
Chen Xin committed
357
            instance->llm->setFfiLock(ffi_lock_);
Li Zhang's avatar
Li Zhang committed
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
            shared_instances_[device_id] = instance;
        }
    }

    std::unique_ptr<ft::Allocator<ft::AllocatorType::CUDA>> allocator(
        new ft::Allocator<ft::AllocatorType::CUDA>(device_id));

    allocator->setStream(stream);

    return std::make_unique<LlamaTritonModelInstance<T>>(instance, std::move(allocator));
}

template<typename T>
void LlamaTritonModel<T>::createSharedWeights(int device_id, int rank)
{
    ft::check_cuda_error(cudaSetDevice(device_id));
    const int tensor_para_rank   = rank % tensor_para_size_;
    const int pipeline_para_rank = rank / tensor_para_size_;
    ft::FT_CHECK(pipeline_para_size_ == 1 && pipeline_para_rank == 0);
377
378
379
    shared_weights_[device_id] = std::make_shared<ft::LlamaWeight<T>>(head_num_,
                                                                      kv_head_num_,
                                                                      size_per_head_,
Li Zhang's avatar
Li Zhang committed
380
381
382
                                                                      inter_size_,
                                                                      vocab_size_,
                                                                      num_layer_,
Li Zhang's avatar
Li Zhang committed
383
                                                                      attn_bias_,
384
385
                                                                      weight_type_,
                                                                      group_size_,
gaoqiong's avatar
gaoqiong committed
386
                                                                      w4_weight_layout_,
gaoqiong's avatar
gaoqiong committed
387
                                                                      w4_pad_size_,
Li Zhang's avatar
Li Zhang committed
388
                                                                      tensor_para_size_,
389
                                                                      tensor_para_rank);
390
391
392
393
    // model inited with model_dir
    if (model_dir_ != "") {
        shared_weights_[device_id]->loadModel(model_dir_);
    }
Li Zhang's avatar
Li Zhang committed
394
395
396
    return;
}

gaoqiong's avatar
gaoqiong committed
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
template<typename T>
void LlamaTritonModel<T>::modifySharedWeights(int device_id, int rank)
{
    ft::check_cuda_error(cudaSetDevice(device_id));
    const int tensor_para_rank   = rank % tensor_para_size_;
    const int pipeline_para_rank = rank / tensor_para_size_;
    ft::FT_CHECK(pipeline_para_size_ == 1 && pipeline_para_rank == 0);

    if(weight_type_== turbomind::WeightType::kINT4)
    {
        shared_weights_[device_id]->modifyModel();
    }
    return;
}

412
413
414
415
416
417
418
419
420
421
422
423
424
425
template<typename T>
TensorMap LlamaTritonModel<T>::getParams(int deviceId, int rank)
{
    ft::check_cuda_error(cudaSetDevice(deviceId));
    // shared_weight should be created before getParams
    ft::FT_CHECK(shared_weights_[deviceId] != nullptr);
    ft::TensorMap output = shared_weights_[deviceId]->getParams();
    TensorMap     result;
    for (auto [name, tensor] : output) {
        result.emplace(name, triton::Tensor{tensor.where, tensor.type, tensor.shape, tensor.data});
    }
    return result;
}

Li Zhang's avatar
Li Zhang committed
426
427
428
429
430
template<typename T>
std::string LlamaTritonModel<T>::toString()
{
    std::stringstream ss;
    ss << "Model: "
431
432
       << "\nhead_num: " << head_num_ << "\nkv_head_num: " << kv_head_num_ << "\nsize_per_head: " << size_per_head_
       << "\ninter_size: " << inter_size_ << "\nnum_layer: " << num_layer_ << "\nvocab_size: " << vocab_size_
433
434
435
436
437
       << "\nattn_bias: " << attn_bias_ << "\nmax_batch_size: " << engine_params_.max_batch_size
       << "\nmax_context_token_num: " << engine_params_.max_context_token_num
       << "\nsession_len: " << engine_params_.session_len << "\nstep_length: " << engine_params_.step_length
       << "\ncache_max_entry_count: " << engine_params_.cache_max_block_count
       << "\ncache_block_seq_len: " << cache_block_seq_len_ << "\ncache_chunk_size: " << engine_params_.cache_chunk_size
Li Zhang's avatar
Li Zhang committed
438
439
440
441
442
       << "\nuse_context_fmha: " << use_context_fmha_ << "\nstart_id: " << start_id_
       << "\ntensor_para_size: " << tensor_para_size_ << "\npipeline_para_size: " << pipeline_para_size_
       << "\nenable_custom_all_reduce: " << enable_custom_all_reduce_ << "\nmodel_name: " << model_name_
       << "\nmodel_dir: " << model_dir_ << "\nquant_policy: " << quant_policy_ << "\ngroup_size: " << group_size_
       << std::endl;
Li Zhang's avatar
Li Zhang committed
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463

    return ss.str();
}

template<typename T>
void LlamaTritonModel<T>::createCustomComms(
    std::vector<std::shared_ptr<ft::AbstractCustomComm>>* custom_all_reduce_comms, int world_size)
{
    using commDataType = typename ft::CustomARCommTypeConverter<T>::Type;
    ft::initCustomAllReduceComm<commDataType>(custom_all_reduce_comms, enable_custom_all_reduce_, world_size);
}

template<typename T>
std::pair<std::vector<ft::NcclParam>, std::vector<ft::NcclParam>>
LlamaTritonModel<T>::createNcclParams(const int node_id, const int device_id_start, const bool multi_node)
{
    const auto device_count     = ft::getDeviceCount();
    bool       need_nccl_params = false;
    // create nccl group when there are non-occupied devices
    for (int i = 0; i < device_count; ++i) {
        std::lock_guard<std::mutex> lock(shared_mutexes_[i]);
464
        if (shared_instances_[i] == nullptr) {
Li Zhang's avatar
Li Zhang committed
465
466
467
468
469
470
471
472
            need_nccl_params = true;
            break;
        }
    }
    if (need_nccl_params) {
        return AbstractTransformerModel::createNcclParams(node_id, device_id_start, multi_node);
    }
    else {
lvhan028's avatar
lvhan028 committed
473
        TM_LOG_INFO("Skipping NCCL param creation.");
Li Zhang's avatar
Li Zhang committed
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504

        const int tensor_para_size   = getTensorParaSize();
        const int pipeline_para_size = getPipelineParaSize();
        const int local_comm_size    = multi_node ? device_count : tensor_para_size * pipeline_para_size;

        std::vector<ft::NcclParam> tensor_para_params(local_comm_size);
        std::vector<ft::NcclParam> pipeline_para_params(local_comm_size);
        return {std::move(tensor_para_params), std::move(pipeline_para_params)};
    }
}

template<typename T>
std::unique_ptr<ft::AbstractInstanceComm> LlamaTritonModel<T>::createInstanceComm(int size)
{
    return std::make_unique<ft::LlamaInstanceComm>(size);
}

template<typename T>
int LlamaTritonModel<T>::getTensorParaSize()
{
    return tensor_para_size_;
}

template<typename T>
int LlamaTritonModel<T>::getPipelineParaSize()
{
    return pipeline_para_size_;
}

template struct LlamaTritonModel<float>;
template struct LlamaTritonModel<half>;
q.yao's avatar
q.yao committed
505
506
507
#ifdef ENABLE_BF16
template struct LlamaTritonModel<__nv_bfloat16>;
#endif