qwen3vl.cpp 31.3 KB
Newer Older
hejianlin's avatar
hejianlin committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include "qwen3vl_impl.hpp"

#include "../../tensor.hpp"
#include "../../utils.hpp"
#include "../inference_context.hpp"
#include "infinicore_infer.h"

#include <random>
#include <thread>
#include <vector>

void createDeviceResource(Qwen3vlDeviceResource *rsrc, const Qwen3vlMeta *meta,
                          std::shared_ptr<Qwen3vlDeviceWeights> weights,
                          infiniDevice_t device, int idev,
                          int ndev, int dev_id,
                          infinicclComm_t comm) {
    RUN_INFINI(infinirtSetDevice(device, dev_id));
    RUN_INFINI(infinirtStreamSynchronize(weights->load_stream));
    infiniopHandle_t handle;
    infiniopCreateHandle(&handle);
    infinirtStream_t stream;
    infinirtStreamCreate(&stream);

    auto memory_pool = std::make_shared<MemoryPool>();

    *rsrc = Qwen3vlDeviceResource{
        device,
        dev_id,
        handle,
        weights,
        stream,
        comm,
        memory_pool,
    };
    RUN_INFINI(infinirtDeviceSynchronize());
}

void releaseDeviceResource(Qwen3vlDeviceResource &res) {
    infinirtDeviceSynchronize();

    res.weights.reset();

    infiniopDestroyHandle(res.handle);
    res.handle = nullptr;
    infinirtStreamDestroy(res.stream);
    res.stream = nullptr;
    infinicclCommDestroy(res.comm);
    res.comm = nullptr;
}

PanZezhong's avatar
PanZezhong committed
51
inline std::shared_ptr<Tensor> get_custom_SinTable(const Qwen3vlMeta &meta, std::vector<std::vector<uint32_t>> &pos_ids, uint32_t dim, size_t theta) {
hejianlin's avatar
hejianlin committed
52
53
    // pos_ids shape:[seq, dim/2] , pos ids acting on each dim
    auto unit = dsize(meta.dtype);
PanZezhong's avatar
PanZezhong committed
54
    auto half_dim = dim / 2;
hejianlin's avatar
hejianlin committed
55
56
57
    size_t len = pos_ids.size();
    void *table = std::malloc(len * half_dim * unit);

PanZezhong's avatar
PanZezhong committed
58
    for (size_t i = 0; i < len; i++) {
hejianlin's avatar
hejianlin committed
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
        for (size_t j = 0; j < half_dim; j++) {
            float _cos = std::sin(
                static_cast<float>(pos_ids[i][j]) / std::pow(theta, static_cast<float>(j) / half_dim));
            if (meta.dtype == INFINI_DTYPE_F16) {
                ((uint16_t *)table)[i * half_dim + j] = f32_to_f16(_cos);
            } else if (meta.dtype == INFINI_DTYPE_BF16) {
                ((uint16_t *)table)[i * half_dim + j] = f32_to_bf16(_cos);
            } else if (meta.dtype == INFINI_DTYPE_F32) {
                ((float *)table)[i * half_dim + j] = _cos;
            } else {
                std::cout << "unsupported data type" << std::endl;
                exit(1);
            }
        }
    }
    auto shape = std::vector<size_t>({len, half_dim});
    auto tensor = Tensor::weight(table, meta.dtype, shape);
    std::free(table);
    return tensor;
}

PanZezhong's avatar
PanZezhong committed
80
inline std::shared_ptr<Tensor> get_custom_CosTable(const Qwen3vlMeta &meta, std::vector<std::vector<uint32_t>> &pos_ids, uint32_t dim, size_t theta) {
hejianlin's avatar
hejianlin committed
81
82
    // pos_ids shape:[seq, dim/2] , pos ids acting on each dim
    auto unit = dsize(meta.dtype);
PanZezhong's avatar
PanZezhong committed
83
    auto half_dim = dim / 2;
hejianlin's avatar
hejianlin committed
84
85
86
    size_t len = pos_ids.size();
    void *table = std::malloc(len * half_dim * unit);

PanZezhong's avatar
PanZezhong committed
87
    for (size_t i = 0; i < len; i++) {
hejianlin's avatar
hejianlin committed
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
        for (size_t j = 0; j < half_dim; j++) {
            float _cos = std::cos(
                static_cast<float>(pos_ids[i][j]) / std::pow(theta, static_cast<float>(j) / half_dim));
            if (meta.dtype == INFINI_DTYPE_F16) {
                ((uint16_t *)table)[i * half_dim + j] = f32_to_f16(_cos);
            } else if (meta.dtype == INFINI_DTYPE_BF16) {
                ((uint16_t *)table)[i * half_dim + j] = f32_to_bf16(_cos);
            } else if (meta.dtype == INFINI_DTYPE_F32) {
                ((float *)table)[i * half_dim + j] = _cos;
            } else {
                std::cout << "unsupported data type" << std::endl;
                exit(1);
            }
        }
    }
    auto shape = std::vector<size_t>({len, half_dim});
    auto tensor = Tensor::weight(table, meta.dtype, shape);
    std::free(table);
    return tensor;
}

PanZezhong's avatar
PanZezhong committed
109
110
111
inline std::shared_ptr<Tensor> fast_pos_embed_interpolate(const Qwen3vlMeta &meta, Qwen3vlDeviceResource &rsrc,
                                                          uint32_t *grid_thw, uint32_t num_batch, uint32_t total_patches) {
    auto dtype = meta.dtype;
hejianlin's avatar
hejianlin committed
112
113
114
115
116
117
    auto num_position_embeddings = meta.vis_meta.num_position_embeddings;
    auto hidden_size = meta.vis_meta.hidden_size;
    auto merge_size = meta.vis_meta.spatial_merge_size;
    auto num_grid_per_side = static_cast<uint32_t>(sqrt(num_position_embeddings));

    uint32_t total_pixels_offset = 0;
PanZezhong's avatar
PanZezhong committed
118
    std::shared_ptr<Tensor> patch_pos_embeds = Tensor::buffer(dtype, {total_patches, hidden_size}, rsrc.memory_pool);
hejianlin's avatar
hejianlin committed
119
120
121
122
123
124
125
    auto pos_embed_weight = rsrc.weights->w_vis->pos_embed_weight;

    std::vector<std::shared_ptr<Tensor>> pos_embeds(4);
    for (uint32_t i = 0; i < num_batch; ++i) {
        uint32_t t = grid_thw[i * 3];
        uint32_t h = grid_thw[i * 3 + 1];
        uint32_t w = grid_thw[i * 3 + 2];
PanZezhong's avatar
PanZezhong committed
126
127
        auto weight_array = std::vector<uint16_t>(h * w * hidden_size);
        auto weight_tensor = Tensor::buffer(dtype, {h * w, hidden_size}, rsrc.memory_pool);
hejianlin's avatar
hejianlin 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

        // 计算插值索引和权重
        std::vector<std::vector<uint32_t>> indices(4);
        std::vector<std::vector<float>> weights(4);

        auto linspace = [](float start, float end, uint32_t num_points) -> std::vector<float> {
            std::vector<float> res(num_points);
            for (uint32_t i = 0; i < num_points; ++i) {
                res[i] = start + (end - start) * i / (num_points - 1);
            }
            return res;
        };

        auto h_idxs = linspace(0, num_grid_per_side - 1, h);
        auto w_idxs = linspace(0, num_grid_per_side - 1, w);

        for (uint32_t ih = 0; ih < h; ++ih) {
            for (uint32_t iw = 0; iw < w; ++iw) {
                float h_idx_f = h_idxs[ih], w_idx_f = w_idxs[iw];
                uint32_t h_idx_floor = static_cast<uint32_t>(floor(h_idx_f)),
                         w_idx_floor = static_cast<uint32_t>(floor(w_idx_f));
                uint32_t h_idx_ceil = std::min(static_cast<uint32_t>(ceil(h_idx_f)), num_grid_per_side - 1),
                         w_idx_ceil = std::min(static_cast<uint32_t>(ceil(w_idx_f)), num_grid_per_side - 1);

                float dh = h_idx_f - h_idx_floor, dw = w_idx_f - w_idx_floor;

                indices[0].push_back((h_idx_floor * num_grid_per_side) + w_idx_floor);
                indices[1].push_back((h_idx_floor * num_grid_per_side) + w_idx_ceil);
                indices[2].push_back((h_idx_ceil * num_grid_per_side) + w_idx_floor);
                indices[3].push_back((h_idx_ceil * num_grid_per_side) + w_idx_ceil);

                weights[0].push_back((1 - dh) * (1 - dw));
                weights[1].push_back((1 - dh) * dw);
                weights[2].push_back(dh * (1 - dw));
                weights[3].push_back(dh * dw);
            }
        }

        // 查表并加权求和
        for (int j = 0; j < 4; ++j) {
PanZezhong's avatar
PanZezhong committed
168
            pos_embeds[j] = Tensor::buffer(dtype, {h * w, hidden_size}, rsrc.memory_pool);
hejianlin's avatar
hejianlin committed
169
            // 使用索引和权重获取对应位置嵌入,并乘以权重
PanZezhong's avatar
PanZezhong committed
170
171
            for (size_t i = 0; i < h * w; i++) {
                rearrange(pos_embeds[j]->slice(0, i, 1), pos_embed_weight->slice(0, indices[j][i], 1));
hejianlin's avatar
hejianlin committed
172
            }
PanZezhong's avatar
PanZezhong committed
173
            for (size_t i = 0; i < h * w; i++) {
hejianlin's avatar
hejianlin committed
174
                uint16_t w_value = f32_to_bf16(weights[j][i]);
PanZezhong's avatar
PanZezhong committed
175
176
                for (size_t k = 0; k < hidden_size; k++) {
                    weight_array[i * hidden_size + k] = w_value;
hejianlin's avatar
hejianlin committed
177
178
                }
            }
PanZezhong's avatar
PanZezhong committed
179
180
181
            RUN_INFINI(infinirtMemcpyAsync(weight_tensor->data(), weight_array.data(), sizeof(uint16_t) * h * w * hidden_size,
                                           INFINIRT_MEMCPY_H2D, rsrc.stream));
            mul(pos_embeds[j], pos_embeds[j], weight_tensor);
hejianlin's avatar
hejianlin committed
182
183
184
185
186
        }

        // 合并四个方向的结果
        auto patch_pos_embed = pos_embeds[0]; // [h*w, hidden_size]
        for (int j = 1; j < 4; ++j) {
PanZezhong's avatar
PanZezhong committed
187
            add(patch_pos_embed, patch_pos_embed, pos_embeds[j]);
hejianlin's avatar
hejianlin committed
188
189
190
191
        }

        // 对于视频帧数T>1的情况,重复patch_pos_embed T次
        if (t > 1) {
PanZezhong's avatar
PanZezhong committed
192
193
194
            auto temp_patch_pos_embed = Tensor::buffer(dtype, {t, h * w, hidden_size}, rsrc.memory_pool);
            for (size_t i = 0; i < t; i++) {
                rearrange(temp_patch_pos_embed->slice(0, i, 1), patch_pos_embed);
hejianlin's avatar
hejianlin committed
195
196
197
198
199
200
            }
            patch_pos_embed = temp_patch_pos_embed;
        }
        printf("merge patch pos embed/n");
        fflush(stdout);
        patch_pos_embed = patch_pos_embed
PanZezhong's avatar
PanZezhong committed
201
202
203
                              ->view({t, h / merge_size, merge_size, w / merge_size, merge_size, hidden_size})
                              ->permute({0, 1, 3, 2, 4, 5})
                              ->view({t * h * w, hidden_size}); // 可能因为内存不连续无法再view
hejianlin's avatar
hejianlin committed
204

PanZezhong's avatar
PanZezhong committed
205
206
        rearrange(patch_pos_embeds->slice(0, total_pixels_offset, t * h * w), patch_pos_embed);
        total_pixels_offset += t * h * w;
hejianlin's avatar
hejianlin committed
207
208
209
210
    }
    return patch_pos_embeds;
}

PanZezhong's avatar
PanZezhong committed
211
inline auto rot_pos_embed(const Qwen3vlMeta &meta, Qwen3vlDeviceResource &rsrc, uint32_t *grid_thw, uint32_t num_batch, uint32_t total_patches) {
hejianlin's avatar
hejianlin committed
212
213
214
215
216
217
    auto dtype = meta.dtype;
    auto hidden_size = meta.vis_meta.hidden_size;
    auto num_heads = meta.vis_meta.num_heads;
    auto head_dim = hidden_size / num_heads;
    auto merge_size = meta.vis_meta.spatial_merge_size;

PanZezhong's avatar
PanZezhong committed
218
    std::vector<std::vector<uint32_t>> pos_ids_table_y(
hejianlin's avatar
hejianlin committed
219
        total_patches,
PanZezhong's avatar
PanZezhong committed
220
221
        std::vector<uint32_t>(head_dim / 4));
    std::vector<std::vector<uint32_t>> pos_ids_table_x(
hejianlin's avatar
hejianlin committed
222
        total_patches,
PanZezhong's avatar
PanZezhong committed
223
        std::vector<uint32_t>(head_dim / 4));
hejianlin's avatar
hejianlin committed
224
225
226
    for (uint32_t b = 0; b < num_batch; ++b) {
        uint32_t offset = b * 3;
        uint32_t num_frames = grid_thw[offset + 0];
PanZezhong's avatar
PanZezhong committed
227
228
        uint32_t height = grid_thw[offset + 1];
        uint32_t width = grid_thw[offset + 2];
hejianlin's avatar
hejianlin committed
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243

        uint32_t merged_h = height / merge_size;
        uint32_t merged_w = width / merge_size;

        // 遍历所有块和块内位置
        size_t patch_offset = 0;
        for (uint32_t bh = 0; bh < merged_h; ++bh) {
            for (uint32_t bw = 0; bw < merged_w; ++bw) {
                for (uint32_t ih = 0; ih < merge_size; ++ih) {
                    for (uint32_t iw = 0; iw < merge_size; ++iw) {
                        uint32_t row = bh * merge_size + ih;
                        uint32_t col = bw * merge_size + iw;
                        // 如果是多帧,重复 num_frames 次
                        for (uint32_t f = 0; f < num_frames; ++f) {
                            size_t dim_offset = 0;
PanZezhong's avatar
PanZezhong committed
244
                            for (; dim_offset < head_dim / 4; dim_offset++) {
hejianlin's avatar
hejianlin committed
245
246
247
248
249
250
251
252
253
254
                                pos_ids_table_y[patch_offset][dim_offset] = row;
                                pos_ids_table_x[patch_offset][dim_offset] = col;
                            }
                            patch_offset++;
                        }
                    }
                }
            }
        }
    }
PanZezhong's avatar
PanZezhong committed
255
256
257
258
259
260
261
262
263
264
265
266
    auto sin = Tensor::buffer(dtype, {total_patches, head_dim / 2}, rsrc.memory_pool);
    auto sin_y = get_custom_SinTable(meta, pos_ids_table_y, head_dim / 2, 10000);
    rearrange(sin->slice(1, 0, head_dim / 4), sin_y);
    auto sin_x = get_custom_SinTable(meta, pos_ids_table_x, head_dim / 2, 10000);
    rearrange(sin->slice(1, head_dim / 4, head_dim / 2), sin_y);
    auto cos = Tensor::buffer(dtype, {total_patches, head_dim / 2}, rsrc.memory_pool);
    auto cos_y = get_custom_CosTable(meta, pos_ids_table_y, head_dim / 2, 10000);
    rearrange(cos->slice(1, 0, head_dim / 4), cos_y);
    auto cos_x = get_custom_CosTable(meta, pos_ids_table_x, head_dim / 2, 10000);
    rearrange(cos->slice(1, head_dim / 4, head_dim / 2), cos_y);

    return std::pair{sin, cos};
hejianlin's avatar
hejianlin committed
267
268
269
}

void inferDeviceBatchVision(const Qwen3vlMeta &meta, Qwen3vlDeviceResource &rsrc,
PanZezhong's avatar
PanZezhong committed
270
                            uint32_t idev, uint32_t ndev, InferRequest &req) {
hejianlin's avatar
hejianlin committed
271
272
273
274
275
276
    void *pixel_values = req.pixel_values;
    uint32_t total_patches = req.total_patches;
    uint32_t *image_grid_thw = req.image_grid_thw;
    uint32_t num_images = req.num_images;
    void *pixel_values_videos = req.pixel_values_videos;
    uint32_t total_patches_videos = req.total_patches_videos;
PanZezhong's avatar
PanZezhong committed
277
278
279
    // uint32_t *video_grid_thw = req.video_grid_thw;
    // uint32_t num_videos = req.num_videos;
    // uint32_t patch_features = req.patch_features;
hejianlin's avatar
hejianlin committed
280
281
282
283
284
285

    auto dtype = meta.dtype;
    auto d = meta.vis_meta.hidden_size;
    auto channels = meta.vis_meta.in_channels;
    auto patch_size = meta.vis_meta.patch_size;
    auto temporal_patch_size = meta.vis_meta.temporal_patch_size;
PanZezhong's avatar
PanZezhong committed
286
    // auto stream = rsrc.stream;
hejianlin's avatar
hejianlin committed
287
    auto weights = rsrc.weights;
PanZezhong's avatar
PanZezhong committed
288
289
290

    auto image_tensor = Tensor::weight(pixel_values, dtype, {total_patches, channels * temporal_patch_size * patch_size * patch_size});
    auto video_tensor = Tensor::weight(pixel_values_videos, dtype, {total_patches_videos, channels * temporal_patch_size * patch_size * patch_size});
hejianlin's avatar
hejianlin committed
291
292
293
294
295
296
    auto hidden_states = Tensor::buffer(dtype, {total_patches, d, 1, 1, 1}, rsrc.memory_pool);

    std::vector<size_t> pads = {0, 0, 0};
    std::vector<ptrdiff_t> strides = {static_cast<long>(temporal_patch_size), static_cast<long>(patch_size), static_cast<long>(patch_size)};
    std::vector<size_t> dilations = {1, 1, 1};
    conv(hidden_states, image_tensor, rsrc.weights->w_vis->patch_embed_weight, rsrc.weights->w_vis->patch_embed_bias,
PanZezhong's avatar
PanZezhong committed
297
         pads.data(), strides.data(), dilations.data(), 3);
hejianlin's avatar
hejianlin committed
298
299
    hidden_states = hidden_states->view({total_patches, d});

PanZezhong's avatar
PanZezhong committed
300
301
    auto pos_embeds = fast_pos_embed_interpolate(meta, rsrc, image_grid_thw, num_images, total_patches);
    add(hidden_states, hidden_states, pos_embeds);
hejianlin's avatar
hejianlin committed
302

PanZezhong's avatar
PanZezhong committed
303
    auto [sin, cos] = rot_pos_embed(meta, rsrc, image_grid_thw, num_images, total_patches);
hejianlin's avatar
hejianlin committed
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
}

void inferDeviceBatchText(const Qwen3vlMeta &meta, Qwen3vlDeviceResource &rsrc,
                          uint32_t idev, uint32_t ndev, InferRequest &req) {
    const uint32_t *tokens = req.tokens;
    uint32_t ntok = req.ntok;
    const uint32_t *req_lens = req.req_lens;
    uint32_t nreq = req.nreq;
    const uint32_t *req_pos = req.req_pos;
    struct Qwen3vlCache **caches = req.kv_caches;
    const float *temperature = req.temperature;
    const uint32_t *topk = req.topk;
    const float *topp = req.topp;
    uint32_t *output = req.output;
    void *last_logits = req.logits;

    assert(meta.text_meta.num_attention_heads % ndev == 0);
    assert(meta.text_meta.num_key_value_heads % ndev == 0);

    auto dtype = meta.dtype;
    auto nlayer = meta.text_meta.num_hidden_layers;
    size_t nh = meta.text_meta.num_attention_heads / size_t(ndev);
    size_t nkvh = meta.text_meta.num_key_value_heads / size_t(ndev);
    auto ngroup = nh / nkvh;
    auto dh = meta.text_meta.head_dim;
    auto d = meta.text_meta.hidden_size;
    auto di = meta.text_meta.intermediate_size / size_t(ndev);
    auto dvoc = meta.text_meta.vocab_size;
    float epsilon = meta.text_meta.rms_norm_eps;
    auto stream = rsrc.stream;
    auto weights = rsrc.weights;

PanZezhong's avatar
PanZezhong committed
336
    // Allocate buffers
hejianlin's avatar
hejianlin committed
337
338
339
    auto logits_in = Tensor::buffer(dtype, {ntok, d}, rsrc.memory_pool);
    auto logits_out = Tensor::buffer(dtype, {ntok, d}, rsrc.memory_pool);

PanZezhong's avatar
PanZezhong committed
340
    // 所有请求的当前token
hejianlin's avatar
hejianlin committed
341
342
    auto qkv_buf = Tensor::buffer(dtype, {ntok, (nh + nkvh * 2) * dh}, rsrc.memory_pool);
    auto o_buf = Tensor::buffer(dtype, {ntok, nh * dh}, rsrc.memory_pool);
PanZezhong's avatar
PanZezhong committed
343
    auto gate_up_buf = Tensor::buffer(dtype, {ntok, 2 * di}, rsrc.memory_pool);
hejianlin's avatar
hejianlin committed
344
345
346
347
348
349
350
351
352

    auto prob_buf = Tensor::buffer(dtype, {nreq, dvoc}, rsrc.memory_pool);
    auto result_buf = Tensor::buffer(INFINI_DTYPE_I64, {nreq}, rsrc.memory_pool);
    auto result_cpu = std::vector<int64_t>(nreq);

    auto qkv_rope = qkv_buf->view({ntok, nh + nkvh * 2, dh});
    auto q_buf = qkv_rope->slice(1, 0, nh);
    auto k_buf = qkv_rope->slice(1, nh, nkvh);

PanZezhong's avatar
PanZezhong committed
353
    // Prepare inputs
hejianlin's avatar
hejianlin committed
354
355
356
    auto batch_pos_ids = std::vector<uint32_t>(ntok);
    size_t req_start = 0;
    for (uint32_t req = 0; req < nreq; req++) {
PanZezhong's avatar
PanZezhong committed
357
358
        for (uint32_t i = 0; i < req_lens[req]; i++) {       // req_len 本次query长度,req_pos 历史长度
            batch_pos_ids[req_start + i] = req_pos[req] + i; // batch_pos_ids 展平后每个token的pos
hejianlin's avatar
hejianlin committed
359
360
361
362
363
364
365
366
367
368
369
370
        }
        req_start += req_lens[req];
    }
    std::shared_ptr<Tensor> pos_ids_buf;
    if (rsrc.device == INFINI_DEVICE_CPU) {
        pos_ids_buf = Tensor::weight(batch_pos_ids.data(), INFINI_DTYPE_U32, {ntok});
    } else {
        pos_ids_buf = Tensor::buffer(INFINI_DTYPE_U32, {ntok}, rsrc.memory_pool);
        RUN_INFINI(infinirtMemcpyAsync(pos_ids_buf->data(), batch_pos_ids.data(), sizeof(uint32_t) * ntok,
                                       INFINIRT_MEMCPY_H2D, stream));
    }

PanZezhong's avatar
PanZezhong committed
371
    // convert tokens to embeddings
hejianlin's avatar
hejianlin committed
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
    for (uint32_t i = 0; i < ntok; i++) {
        RUN_INFINI(infinirtMemcpyAsync(logits_in->data(i * d),
                                       weights->w_lang->in_embd->data(tokens[i] * d),
                                       dsize(dtype) * d, INFINIRT_MEMCPY_D2D, stream));
    }

    // attention inner
    size_t max_qk_size = 0;
    size_t max_seq_len = 0;

    for (uint32_t req = 0; req < nreq; req++) {
        auto past_len = req_pos[req];
        auto seq_len = req_lens[req];
        auto total_len = past_len + seq_len;

        max_qk_size = std::max(max_qk_size, size_t(seq_len * total_len));
        max_seq_len = std::max(max_seq_len, size_t(seq_len));
    }
PanZezhong's avatar
PanZezhong committed
390

hejianlin's avatar
hejianlin committed
391
392
393
394
395
396
397
398
399
    auto qk_buf = Tensor::buffer(dtype, {nh * max_qk_size}, rsrc.memory_pool);
    auto rearrange_q_buf = Tensor::buffer(dtype, {nkvh, ngroup * max_seq_len, dh}, rsrc.memory_pool);
    auto q_rearrange = rearrange_q_buf->view({nkvh, ngroup, max_seq_len, dh});
    auto attn_val_buf = Tensor::buffer(dtype, {nkvh, ngroup * max_seq_len, dh}, rsrc.memory_pool);
    auto attn_val_gemm = attn_val_buf->view({nkvh, ngroup, max_seq_len, dh});

    auto gate_buf = gate_up_buf->slice(1, 0, di);
    auto up_buf = gate_up_buf->slice(1, di, di);

PanZezhong's avatar
PanZezhong committed
400
401
    // Compute
    for (uint32_t i = 0; i < nlayer; i++) {
hejianlin's avatar
hejianlin committed
402
        // attn norm
PanZezhong's avatar
PanZezhong committed
403
        rmsnorm(logits_out, logits_in, weights->w_lang->layers[i].attn_norm, epsilon);
hejianlin's avatar
hejianlin committed
404
        // qkv_proj
PanZezhong's avatar
PanZezhong committed
405
        linear(qkv_buf, logits_out, weights->w_lang->layers[i].attn_qkv_proj, 1.0, 0.0, nullptr, nullptr);
hejianlin's avatar
hejianlin committed
406
        // qk_norm
PanZezhong's avatar
PanZezhong committed
407
408
409
410
411
412
        rmsnorm(q_buf, q_buf, weights->w_lang->layers[i].attn_q_norm, epsilon);
        rmsnorm(k_buf, k_buf, weights->w_lang->layers[i].attn_k_norm, epsilon);
        // rope
        rope_v2(q_buf, q_buf, pos_ids_buf, weights->sin_table, weights->cos_table);
        rope_v2(k_buf, k_buf, pos_ids_buf, weights->sin_table, weights->cos_table);

hejianlin's avatar
hejianlin committed
413
414
        // 逐个req处理
        size_t token_offset = 0;
PanZezhong's avatar
PanZezhong committed
415
        for (uint32_t req = 0; req < nreq; req++) {
hejianlin's avatar
hejianlin committed
416
417
418
419
            auto past_len = req_pos[req];
            auto seq_len = req_lens[req];
            auto total_len = past_len + seq_len;

PanZezhong's avatar
PanZezhong committed
420
421
422
423
            auto o = o_buf->slice(0, token_offset, seq_len)->view({seq_len, nkvh, ngroup, dh})->permute({1, 2, 0, 3});                    // [nkvh, ngroup, seq_len, dh]
            auto q = qkv_rope->slice({{0, token_offset, seq_len}, {1, 0, nh}})->view({seq_len, nkvh, ngroup, dh})->permute({1, 2, 0, 3}); // [nkvh, ngroup, seq_len, dh]
            auto k = qkv_rope->slice({{0, token_offset, seq_len}, {1, nh, nkvh}});                                                        // [ntok, nkvh, dh]
            auto v = qkv_rope->slice({{0, token_offset, seq_len}, {1, nh + nkvh, nkvh}});                                                 // [ntok, nkvh, dh]
hejianlin's avatar
hejianlin committed
424

PanZezhong's avatar
PanZezhong committed
425
426
427
            // concat to cache
            rearrange(caches[req]->k_rot[idev][i]->slice(0, past_len, seq_len), k);
            rearrange(caches[req]->v[idev][i]->slice(0, past_len, seq_len), v);
hejianlin's avatar
hejianlin committed
428

PanZezhong's avatar
PanZezhong committed
429
430
431
432
433
            // fill full_k full_v
            auto full_k_buff = caches[req]->k_rot[idev][i]->slice(0, 0, total_len)->permute({1, 2, 0}); // [nkvh, dh, total_len]
            auto full_v_buff = caches[req]->v[idev][i]->slice(0, 0, total_len)->permute({1, 0, 2});     // [nkvh, total_len, dh]

            // self-attn
hejianlin's avatar
hejianlin committed
434
            rearrange(q_rearrange->slice(2, 0, seq_len), q);
PanZezhong's avatar
PanZezhong committed
435
            auto attn_score_req = qk_buf->slice(0, 0, nh * seq_len * total_len)->view({nkvh, ngroup * seq_len, total_len});
hejianlin's avatar
hejianlin committed
436
            // [nkvh, ngroup * seq_len, dh] @ [nkvh, dh, total_len] = [nkvh, ngroup * seq_len, total_len]
PanZezhong's avatar
PanZezhong committed
437
            linear(attn_score_req, rearrange_q_buf->slice(1, 0, ngroup * seq_len), full_k_buff, 1.f / float(sqrt(dh)), 0.f, nullptr, nullptr);
hejianlin's avatar
hejianlin committed
438
439
            // softmax
            auto qk_softmax = attn_score_req->view({nh, seq_len, total_len});
PanZezhong's avatar
PanZezhong committed
440
            causalSoftmax(qk_softmax, qk_softmax);
hejianlin's avatar
hejianlin committed
441
442
            // [nkvh, ngroup * seq_len, total_len] @ [nkvh, total_len, dh] = [nkvh, ngroup * seq_len, dh]
            linear(attn_val_buf->slice(1, 0, ngroup * seq_len), attn_score_req, full_v_buff, 1.0, 0.0, nullptr, nullptr);
PanZezhong's avatar
PanZezhong committed
443
444
            // printf("rearrage o; layer[%d]\n",i);
            rearrange(o, attn_val_gemm->slice(2, 0, seq_len));
hejianlin's avatar
hejianlin committed
445
446
447
448
449
450
451
452
453
454
455
456
            token_offset += seq_len;
        }
        linear(logits_in, o_buf, weights->w_lang->layers[i].attn_o_proj, 1.0, 0.0, idev == 0 ? logits_in : nullptr, nullptr);
        // All_reduce if distributed
        if (rsrc.comm != nullptr) {
            RUN_INFINI(infinicclAllReduce(
                logits_in->data(), logits_in->data(), ntok * d, dtype,
                INFINICCL_SUM, rsrc.comm, stream));
            RUN_INFINI(infinirtStreamSynchronize(stream));
        }

        // mlp norm
PanZezhong's avatar
PanZezhong committed
457
        rmsnorm(logits_out, logits_in, weights->w_lang->layers[i].mlp_norm, epsilon);
hejianlin's avatar
hejianlin committed
458
        // mlp gate_up
PanZezhong's avatar
PanZezhong committed
459
        linear(gate_up_buf, logits_out, weights->w_lang->layers[i].mlp_gate_up, 1.0, 0.0, nullptr, nullptr);
hejianlin's avatar
hejianlin committed
460
        // silu
PanZezhong's avatar
PanZezhong committed
461
462
        silu(gate_buf, gate_buf);
        mul(gate_buf, gate_buf, up_buf);
hejianlin's avatar
hejianlin committed
463
        // mlp down
PanZezhong's avatar
PanZezhong committed
464
        linear(logits_in, gate_buf, weights->w_lang->layers[i].mlp_down, 1.0, 0.0, idev == 0 ? logits_in : nullptr, nullptr);
hejianlin's avatar
hejianlin committed
465
466
467
468
469
470
471
472
473
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
505
506
507
508
509
510
511
512
513
514
515
516
        // All_reduce if distributed
        if (rsrc.comm != nullptr) {
            RUN_INFINI(infinicclAllReduce(
                logits_in->data(), logits_in->data(), ntok * d, dtype,
                INFINICCL_SUM, rsrc.comm, stream));
            RUN_INFINI(infinirtStreamSynchronize(stream));
        }
    }
    // sample and output
    if (idev == 0) {
        if (last_logits != nullptr) {
            rmsnorm(logits_out, logits_in, weights->w_lang->out_norm, epsilon);
            auto last_logits_buf = Tensor::buffer(dtype, {ntok, dvoc}, rsrc.memory_pool);
            linear(last_logits_buf, logits_out, weights->w_lang->out_embd, 1.0, 0.0, nullptr, nullptr);
            RUN_INFINI(infinirtStreamSynchronize(stream));
            RUN_INFINI(infinirtMemcpy(last_logits, last_logits_buf->data(), dsize(dtype) * ntok * dvoc, INFINIRT_MEMCPY_D2H));
        }
        if (output != nullptr) {
            size_t token_offset = 0;
            for (uint32_t req = 0; req < nreq; req++) {
                auto seq_len = req_lens[req];
                token_offset += seq_len;
                rmsnorm(logits_out->slice(0, req, 1),
                        logits_in->slice(0, token_offset - 1, 1),
                        weights->w_lang->out_norm,
                        epsilon);
            }
            linear(prob_buf, logits_out->slice(0, 0, nreq), weights->w_lang->out_embd, 1.0, 0.0, nullptr, nullptr);
            std::random_device _rd;
            std::mt19937 gen(_rd());
            token_offset = 0;
            for (uint32_t req = 0; req < nreq; req++) {
                auto seq_len = req_lens[req];
                float random_val = std::uniform_real_distribution<float>(0, 1)(gen);
                randomSample(result_buf->slice(0, req, 1)->view_as({}, {}),
                             prob_buf->slice(0, req, 1)->view_as({dvoc}, {1}),
                             random_val, topp[req], topk[req], temperature[req]);
                token_offset += seq_len;
            }
            RUN_INFINI(infinirtStreamSynchronize(stream));
            RUN_INFINI(infinirtMemcpy(result_cpu.data(), result_buf->data(),
                                      sizeof(int64_t) * nreq, INFINIRT_MEMCPY_D2H));
            for (uint32_t req = 0; req < nreq; req++) {
                output[req] = uint32_t(result_cpu[req]);
            }
        }
    }
}

void inferDeviceBatch(const Qwen3vlMeta &meta, Qwen3vlDeviceResource &rsrc,
                      uint32_t idev, uint32_t ndev, InferState &state, InferRequest &req) {
    // infer vision + sync
PanZezhong's avatar
PanZezhong committed
517
    if (req.num_images > 0 || req.num_videos > 0) {
hejianlin's avatar
hejianlin committed
518
519
520
521
522
523
524
        inferDeviceBatchVision(meta, rsrc, idev, ndev, req);

        std::unique_lock<std::mutex> lock(state.mtx_sync);
        state.sync_cnt--;
        if (state.sync_cnt == 0) {
            state.cv_sync.notify_all();
        } else {
PanZezhong's avatar
PanZezhong committed
525
            state.cv_sync.wait(lock, [&] { return state.sync_cnt == 0; });
hejianlin's avatar
hejianlin committed
526
527
528
529
530
531
        }
    }
    // infer text
    inferDeviceBatchText(meta, rsrc, idev, ndev, req);
}

PanZezhong's avatar
PanZezhong committed
532
__INFINI_C void
hejianlin's avatar
hejianlin committed
533
inferBatchQwen3vl(struct Qwen3vlModel *model,
PanZezhong's avatar
PanZezhong committed
534
535
536
537
538
539
540
541
542
543
                  const uint32_t *tokens, uint32_t ntok,
                  void *pixel_values, uint32_t total_patches,
                  uint32_t *image_grid_thw, uint32_t num_images,
                  void *pixel_values_videos, uint32_t total_patches_videos,
                  uint32_t *video_grid_thw, uint32_t num_videos,
                  uint32_t patch_features,
                  const uint32_t *req_lens, uint32_t nreq, const uint32_t *req_pos,
                  struct Qwen3vlCache **kv_caches,
                  const float *temperature, const uint32_t *topk, const float *topp,
                  uint32_t *output) {
hejianlin's avatar
hejianlin committed
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
    model->req.tokens = tokens;
    model->req.ntok = ntok;
    model->req.pixel_values = pixel_values;
    model->req.total_patches = total_patches;
    model->req.image_grid_thw = image_grid_thw;
    model->req.num_images = num_images;
    model->req.pixel_values_videos = pixel_values_videos;
    model->req.total_patches_videos = total_patches_videos;
    model->req.video_grid_thw = video_grid_thw;
    model->req.num_videos = num_videos;
    model->req.patch_features = patch_features;
    model->req.req_lens = req_lens;
    model->req.nreq = nreq;
    model->req.req_pos = req_pos;
    model->req.kv_caches = kv_caches;
    model->req.output = output;
    model->req.logits = nullptr;
    model->req.temperature = temperature;
    model->req.topk = topk;
    model->req.topp = topp;
    model->states[0].sync_cnt = model->dev_ids.size();

    for (size_t idev = 0; idev < model->dev_ids.size(); idev++) {
        std::unique_lock<std::mutex> lock(model->states[idev].mtx);
        model->states[idev].proceed = true;
        lock.unlock();
        model->states[idev].cv_start.notify_one();
    }
    for (size_t i = model->dev_ids.size(); i > 0; i--) {
        auto idev = i - 1;
        std::unique_lock<std::mutex> lock(model->states[idev].mtx);
        model->states[idev].cv_done.wait(lock, [&] { return !(model->states[idev].proceed); });
        lock.unlock();
    }
}

PanZezhong's avatar
PanZezhong committed
580
__INFINI_C void
hejianlin's avatar
hejianlin committed
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
forwardBatchQwen3vl(struct Qwen3vlModel *model,
                    const uint32_t *tokens, uint32_t ntok,
                    void *pixel_values, uint32_t total_patches,
                    uint32_t *image_grid_thw, uint32_t num_images,
                    void *pixel_values_videos, uint32_t total_patches_videos,
                    uint32_t *video_grid_thw, uint32_t num_videos,
                    uint32_t patch_features,
                    const uint32_t *req_lens, uint32_t nreq, const uint32_t *req_pos,
                    struct Qwen3vlCache **kv_caches,
                    void *logits) {
    model->req.tokens = tokens;
    model->req.ntok = ntok;
    model->req.pixel_values = pixel_values;
    model->req.total_patches = total_patches;
    model->req.image_grid_thw = image_grid_thw;
    model->req.num_images = num_images;
    model->req.pixel_values_videos = pixel_values_videos;
    model->req.total_patches_videos = total_patches_videos;
    model->req.video_grid_thw = video_grid_thw;
    model->req.num_videos = num_videos;
    model->req.patch_features = patch_features;
    model->req.req_lens = req_lens;
    model->req.nreq = nreq;
    model->req.req_pos = req_pos;
    model->req.kv_caches = kv_caches;
    model->req.output = nullptr;
    model->req.logits = logits;
    model->req.temperature = nullptr;
    model->req.topk = nullptr;
    model->req.topp = nullptr;
    model->states[0].sync_cnt = model->dev_ids.size();

    for (size_t idev = 0; idev < model->dev_ids.size(); idev++) {
        std::unique_lock<std::mutex> lock(model->states[idev].mtx);
        model->states[idev].proceed = true;
        lock.unlock();
        model->states[idev].cv_start.notify_one();
    }
    for (size_t i = model->dev_ids.size(); i > 0; i--) {
        auto idev = i - 1;
        std::unique_lock<std::mutex> lock(model->states[idev].mtx);
        model->states[idev].cv_done.wait(lock, [&] { return !(model->states[idev].proceed); });
        lock.unlock();
    }
}

void launchDevice(const Qwen3vlMeta &meta, std::shared_ptr<Qwen3vlDeviceWeights> weights, Qwen3vlDeviceResource *rsrc, InferState &state, InferRequest &req,
                  infiniDevice_t device, int idev, int ndev, int dev_id, infinicclComm_t comm) {
    // Create Device Resource
    createDeviceResource(rsrc, &meta, weights, device, idev, ndev, dev_id, comm);

    CacheManager cache_manager(100);
    InferenceContext ctx(rsrc->handle, rsrc->memory_pool, &cache_manager, rsrc->stream);

    // Set the inference context for this thread
    setInferenceContext(&ctx);

    {
        std::unique_lock<std::mutex> lock(state.mtx);
        state.loaded = true;
        lock.unlock();
        state.cv_load.notify_one();
    }

    // Infer Loop
    while (true) {
        std::unique_lock<std::mutex> lock(state.mtx);
        state.cv_start.wait(lock, [&] { return state.proceed || state.exit_flag; });
        // quit if exit_flag is set
        if (state.exit_flag) {
            break;
        }

        inferDeviceBatch(meta, *rsrc, idev, ndev, state, req);

        state.proceed = false;
        lock.unlock();
        state.cv_done.notify_one();
    }

    // Clean-Up
    releaseDeviceResource(*rsrc);
    setInferenceContext(nullptr); // Clear the context when done
}

Qwen3vlModel::Qwen3vlModel(const Qwen3vlMeta *_meta, const Qwen3vlWeights *weights) : meta(*_meta) {
    auto device_weights = weights->device_weights;
    int ndev = device_weights.size();
    device = device_weights[0]->device;
    dev_ids.resize(ndev);
    for (int i = 0; i < ndev; i++) {
        dev_ids[i] = device_weights[i]->dev_id;
    }
    dev_resources = std::vector<Qwen3vlDeviceResource>(ndev);
    states = std::vector<InferState>(ndev);
    threads.resize(ndev);
    RUN_INFINI(infinirtInit());
    auto comms = std::vector<infinicclComm_t>(ndev, nullptr);
    if (ndev > 1) {
        RUN_INFINI(infinicclCommInitAll(device, comms.data(), ndev, dev_ids.data()));
    }
    for (int i = 0; i < ndev; i++) {
        threads[i] = std::thread(launchDevice, std::cref(meta), device_weights[i], &dev_resources[i], std::ref(states[i]), std::ref(req), device, i, ndev, dev_ids[i], comms[i]);
    }
    for (int i = 0; i < ndev; i++) {
        std::unique_lock<std::mutex> lock(states[i].mtx);
        states[i].cv_load.wait(lock, [&] { return states[i].loaded; });
        lock.unlock();
    }
}

PanZezhong's avatar
PanZezhong committed
692
__INFINI_C struct Qwen3vlModel *
hejianlin's avatar
hejianlin committed
693
createQwen3vlModel(const Qwen3vlMeta *_meta,
PanZezhong's avatar
PanZezhong committed
694
                   const Qwen3vlWeights *weights) {
hejianlin's avatar
hejianlin committed
695
696
697
698
    Qwen3vlModel *model = new Qwen3vlModel(_meta, weights);
    return model;
}

PanZezhong's avatar
PanZezhong committed
699
__INFINI_C void
hejianlin's avatar
hejianlin committed
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
destroyQwen3vlModel(struct Qwen3vlModel *model) {
    auto ndev = model->dev_resources.size();

    for (size_t idev = 0; idev < ndev; idev++) {
        std::unique_lock<std::mutex> lock(model->states[idev].mtx);
        model->states[idev].exit_flag = true;
        lock.unlock();
        model->states[idev].cv_start.notify_one();
    }

    for (size_t idev = 0; idev < ndev; idev++) {
        model->threads[idev].join();
    }

    delete model;
}