"examples/inference/image_to_image.py" did not exist on "5782e0393d1643383243c31629790491c5e69db8"
LlamaDecoder.cc 11.2 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
18
/*
 * Copyright (c) OpenMMLab. All rights reserved.
 * Copyright (c) 2019-2023, NVIDIA CORPORATION.  All rights reserved.
 * Copyright (c) 2022, SK Telecom Authored by A. Dialog
 *
 * 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
19
// Modified from
lvhan028's avatar
lvhan028 committed
20
// https://github.com/NVIDIA/FasterTransformer/blob/main/src/turbomind/models/multi_gpu_gpt/ParallelGptDecoder.cc
Li Zhang's avatar
Li Zhang committed
21

lvhan028's avatar
lvhan028 committed
22
#include "src/turbomind/models/llama/LlamaDecoder.h"
Chen Xin's avatar
Chen Xin committed
23
#include "src/turbomind/macro.h"
lvhan028's avatar
lvhan028 committed
24
25
#include "src/turbomind/models/llama/llama_decoder_kernels.h"
#include "src/turbomind/models/llama/llama_kernels.h"
26
#include "src/turbomind/models/llama/llama_params.h"
lvhan028's avatar
lvhan028 committed
27
#include "src/turbomind/models/llama/llama_utils.h"
Li Zhang's avatar
Li Zhang committed
28

lvhan028's avatar
lvhan028 committed
29
namespace turbomind {
Li Zhang's avatar
Li Zhang committed
30
31

template<typename T>
32
33
34
35
36
37
38
39
40
41
42
43
LlamaDecoder<T>::LlamaDecoder(size_t                      head_num,
                              size_t                      kv_head_num,
                              size_t                      size_per_head,
                              size_t                      inter_size,
                              size_t                      num_layer,
                              const LlamaAttentionParams& attn_params,
                              float                       rmsnorm_eps,
                              NcclParam                   tensor_para,
                              cudaStream_t                stream,
                              cublasMMWrapper*            cublas_wrapper,
                              IAllocator*                 allocator,
                              bool                        is_free_buffer_after_forward,
Li Zhang's avatar
Li Zhang committed
44
                              int                         cache_block_seq_len,
45
                              int                         quant_policy):
Li Zhang's avatar
Li Zhang committed
46
47
48
49
50
51
52
53
54
55
    BaseLayer(stream, cublas_wrapper, allocator, is_free_buffer_after_forward),
    head_num_(head_num),
    size_per_head_(size_per_head),
    inter_size_(inter_size),
    num_layer_(num_layer),
    hidden_units_(head_num * size_per_head),
    rmsnorm_eps_(rmsnorm_eps),
    tensor_para_(tensor_para),
    data_type_(getTensorType<T>())
{
lvhan028's avatar
lvhan028 committed
56
    TM_LOG_DEBUG(__PRETTY_FUNCTION__);
Li Zhang's avatar
Li Zhang committed
57
    initialize(attn_params, kv_head_num, cache_block_seq_len, quant_policy);
Li Zhang's avatar
Li Zhang committed
58
59
60
61
62
}

template<typename T>
LlamaDecoder<T>::~LlamaDecoder()
{
lvhan028's avatar
lvhan028 committed
63
    TM_LOG_DEBUG(__PRETTY_FUNCTION__);
Li Zhang's avatar
Li Zhang committed
64
65
66
67
68
    delete self_attention_layer_;
    delete silu_ffn_layer_;
}

template<typename T>
Li Zhang's avatar
Li Zhang committed
69
70
71
72
void LlamaDecoder<T>::initialize(const LlamaAttentionParams& attn_params,
                                 size_t                      kv_head_num,
                                 int                         cache_block_seq_len,
                                 int                         quant_policy)
Li Zhang's avatar
Li Zhang committed
73
{
lvhan028's avatar
lvhan028 committed
74
    TM_LOG_DEBUG(__PRETTY_FUNCTION__);
Li Zhang's avatar
Li Zhang committed
75
76

    self_attention_layer_ = new LlamaDecoderSelfAttentionLayer<T>(head_num_,
77
                                                                  kv_head_num,
Li Zhang's avatar
Li Zhang committed
78
                                                                  size_per_head_,
79
                                                                  attn_params,
Li Zhang's avatar
Li Zhang committed
80
81
82
83
                                                                  tensor_para_,
                                                                  stream_,
                                                                  cublas_wrapper_,
                                                                  allocator_,
84
                                                                  is_free_buffer_after_forward_,
Li Zhang's avatar
Li Zhang committed
85
                                                                  cache_block_seq_len,
86
                                                                  quant_policy);
Li Zhang's avatar
Li Zhang committed
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106

    silu_ffn_layer_ = new LlamaFfnLayer<T>(head_num_,
                                           size_per_head_,
                                           inter_size_,
                                           tensor_para_,
                                           stream_,
                                           cublas_wrapper_,
                                           allocator_,
                                           is_free_buffer_after_forward_);
}

template<typename T>
void LlamaDecoder<T>::allocateBuffer()
{
    FT_CHECK(false);
}

template<typename T>
void LlamaDecoder<T>::allocateBuffer(size_t batch_size)
{
lvhan028's avatar
lvhan028 committed
107
    TM_LOG_DEBUG(__PRETTY_FUNCTION__);
Li Zhang's avatar
Li Zhang committed
108
109
110
111
112
113
    is_allocate_buffer_ = true;
}

template<typename T>
void LlamaDecoder<T>::freeBuffer()
{
lvhan028's avatar
lvhan028 committed
114
    TM_LOG_DEBUG(__PRETTY_FUNCTION__);
Li Zhang's avatar
Li Zhang committed
115
116
117
118
119
120
121
122
123
124
125
    if (is_allocate_buffer_) {
        is_allocate_buffer_ = false;
    }
}

template<typename T>
void LlamaDecoder<T>::forwardSelfAttn(const LlamaDecoder::Session&                   sess,
                                      T*                                             attn_io,
                                      const std::unordered_map<std::string, Tensor>* input_tensors,
                                      size_t                                         layer)
{
Li Zhang's avatar
Li Zhang committed
126
    NvtxScope scope("self_attn");
lvhan028's avatar
lvhan028 committed
127
    TM_LOG_DEBUG(__PRETTY_FUNCTION__);
Li Zhang's avatar
Li Zhang committed
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
    TensorMap self_attention_input_tensors(*input_tensors);
    self_attention_input_tensors.insert("input_query",
                                        {MEMORY_GPU, data_type_, {sess.batch_size, hidden_units_}, attn_io});
    const int layer_id = layer;
    self_attention_input_tensors.insert("layer_id", {MEMORY_CPU, TYPE_INT32, {1}, &layer_id});
    auto& k_cache = *sess.k_cache;
    auto& v_cache = *sess.v_cache;

    TensorMap self_attention_output_tensors{
        {"attention_output", {MEMORY_GPU, data_type_, {sess.batch_size, hidden_units_}, attn_io}},
        {"key_cache", k_cache},
        {"value_cache", v_cache},
    };

    self_attention_layer_->forward(&self_attention_output_tensors,  //
                                   &self_attention_input_tensors,
                                   &sess.weights->at(layer)->self_attn_weights);
}

template<typename T>
void LlamaDecoder<T>::forwardFfn(const LlamaDecoder::Session& sess, T* ffn_io, size_t layer)
{
    TensorMap ffn_inputs{{"ffn_input", {MEMORY_GPU, data_type_, {sess.batch_size, hidden_units_}, ffn_io}}};
    TensorMap ffn_outputs{{"ffn_output", {MEMORY_GPU, data_type_, {sess.batch_size, hidden_units_}, ffn_io}}};
    silu_ffn_layer_->forward(&ffn_outputs, &ffn_inputs, &sess.weights->at(layer)->ffn_weights);
}

template<typename T>
void LlamaDecoder<T>::forward(std::vector<Tensor>*                            output_tensors,
                              const std::vector<Tensor>*                      input_tensors,
                              const std::vector<LlamaDecoderLayerWeight<T>*>* decoder_layer_weights)
{
    FT_CHECK(false);
}

template<typename T>
void LlamaDecoder<T>::forward(std::unordered_map<std::string, Tensor>*        output_tensors,
                              const std::unordered_map<std::string, Tensor>*  input_tensors,
                              const std::vector<LlamaDecoderLayerWeight<T>*>* decoder_layer_weights)
{
lvhan028's avatar
lvhan028 committed
168
    TM_LOG_DEBUG(__PRETTY_FUNCTION__);
Li Zhang's avatar
Li Zhang committed
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
    /**
     * input_tensors:
     *   \param decoder_input [batch_size, hidden_dims]
     *   \param sequence_lengths [batch_size] int
     *   \param output_norm_weight [hidden_dims]
     *   \param step [1] on cpu
     *   \param ite [1] on cpu
     *   \param finished [batch_size] bool
     *   \param total_padding_tokens [batch_size], int
     *   \param max_seq_len [1] on cpu
     *   \param masked_tokens [batch_size, memory_len] bool (optional), NOT USED YET
     *
     * output_tensors:
     *   \param decoder_output [batch_size, hidden_dimension]
     *   \param key_cache [batch_size] uint64_t
     *   \param value_cache [batch_size] uint64_t
     */

    // for the shape of key cache, refer to decoder_masked_multihead_attention_template.hpp

Li Zhang's avatar
Li Zhang committed
189
190
    NvtxScope forward_scope("decoder_forward");

Li Zhang's avatar
Li Zhang committed
191
192
193
194
195
196
197
198
199
200
201
202
    Session sess{};
    sess.batch_size = input_tensors->at("decoder_input").shape[0];
    sess.weights    = decoder_layer_weights;

    allocateBuffer(sess.batch_size);

    sess.k_cache = &output_tensors->at("key_cache");
    sess.v_cache = &output_tensors->at("value_cache");

    T* decoder_input  = input_tensors->at("decoder_input").getPtr<T>();
    T* decoder_output = output_tensors->at("decoder_output").getPtr<T>();

Li Zhang's avatar
Li Zhang committed
203
204
205
    int step = input_tensors->at("step").getVal<int>();
    // Compare(decoder_input, sess.batch_size * hidden_units_, Concat("decoder_input", 0, step), kCmpRead, stream_);

Li Zhang's avatar
Li Zhang committed
206
207
    ////////////////////////////////////////////
    /// RMSNorm
Li Zhang's avatar
Li Zhang committed
208
209
210
211
212
213
214
215
216
217
218
    {
        NvtxScope rms_norm_scope("rms_norm_0");
        invokeRootMeanSquareNorm(decoder_output,
                                 decoder_input,
                                 decoder_layer_weights->at(0)->self_attn_norm_weights,
                                 rmsnorm_eps_,
                                 sess.batch_size,
                                 hidden_units_,
                                 stream_);
        sync_check_cuda_error();
    }
Li Zhang's avatar
Li Zhang committed
219
220

    for (size_t layer = 0; layer < num_layer_; ++layer) {
Li Zhang's avatar
Li Zhang committed
221
222
        NvtxScope layer_scope("decode_layer");

Li Zhang's avatar
Li Zhang committed
223
224
225
        // output: self_attn_output_, k_cache, v_cache = self_attn(decoder_normed_input_)
        forwardSelfAttn(sess, decoder_output, input_tensors, layer);

Li Zhang's avatar
Li Zhang committed
226
227
228
229
230
231
232
233
234
235
236
237
        {
            NvtxScope rms_norm_scope("rms_norm_1");
            invokeFusedAddBiasResidualRMSNorm(decoder_input,
                                              decoder_output,
                                              decoder_layer_weights->at(layer)->self_attn_weights.output.bias,
                                              decoder_layer_weights->at(layer)->ffn_norm_weights,
                                              rmsnorm_eps_,
                                              sess.batch_size,
                                              hidden_units_,
                                              stream_);
            sync_check_cuda_error();
        }
Li Zhang's avatar
Li Zhang committed
238
239
240
241

        // decoder_layer_output_ = ffn(decoder_normed_input_)
        forwardFfn(sess, decoder_output, layer);

Li Zhang's avatar
Li Zhang committed
242
243
244
245
246
247
248
249
250
251
252
253
254
255
        {
            NvtxScope rms_norm_scope("rms_norm_2");
            auto scale_weight = layer < num_layer_ - 1 ? decoder_layer_weights->at(layer + 1)->self_attn_norm_weights :
                                                         input_tensors->at("output_norm_weight").getPtr<T>();
            invokeFusedAddBiasResidualRMSNorm(decoder_input,  //
                                              decoder_output,
                                              decoder_layer_weights->at(layer)->ffn_weights.output.bias,
                                              scale_weight,
                                              rmsnorm_eps_,
                                              sess.batch_size,
                                              hidden_units_,
                                              stream_);
            sync_check_cuda_error();
        }
Li Zhang's avatar
Li Zhang committed
256
257
258
259
260
261
262
263
264
265
    }

    if (is_free_buffer_after_forward_) {
        freeBuffer();
    }
}

template class LlamaDecoder<half>;
template class LlamaDecoder<float>;

lvhan028's avatar
lvhan028 committed
266
}  // namespace turbomind