File size: 12,888 Bytes
256a159
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
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
import types
from typing import Optional, Tuple

import mmengine
import torch
import torch.nn as nn
from mmengine.device import get_device
from transformers import AutoModelForCausalLM, AutoTokenizer
from transformers.generation import GenerationConfig
from transformers.modeling_outputs import BaseModelOutputWithPast

from opencompass.registry import MM_MODELS

from .generation_utils import decode_tokens, make_context


@MM_MODELS.register_module('qwen-vl-base')
class QwenVLBase(nn.Module):
    """Inference code of Qwen-VL.

    We load the Qwen model via Huggingface.
    Args:
        pretrained_path (str): Path to Qwen checkpoint or repo id.
        prompt_constructor (dict): The config of prompt constructor.
        post_processor (dict): The config of post processor.
        is_caption_task (bool): Whether the task is caption task.
            Defaults to False.
        commit_id (str): Use given version of Qwen-VL.
            Warning: the latest version may have some conflicts.
            Recommend to use the given default version.
    """

    def __init__(
            self,
            pretrained_path: str,
            prompt_constructor: dict = None,
            post_processor: dict = None,
            is_caption_task: bool = False,
            commit_id: str = '548275c8b99de56dec203c0e793be18e030f2f4c'
    ) -> None:
        super().__init__()
        self.tokenizer = AutoTokenizer.from_pretrained(pretrained_path,
                                                       trust_remote_code=True,
                                                       revision=commit_id)
        self.model = AutoModelForCausalLM.from_pretrained(
            pretrained_path,
            device_map=get_device(),
            trust_remote_code=True,
            revision=commit_id)
        self.model.generation_config = GenerationConfig.from_pretrained(
            pretrained_path, trust_remote_code=True, revision=commit_id)
        if prompt_constructor is not None:
            self.prompt_constructor = mmengine.registry.build_from_cfg(
                prompt_constructor, MM_MODELS)
        if post_processor is not None:
            self.post_processor = mmengine.registry.build_from_cfg(
                post_processor, MM_MODELS)
        else:
            self.post_processor = None
        self.is_caption_task = is_caption_task
        self.model.transformer.forward = types.MethodType(
            forward_hack, self.model.transformer)

    def _build_embeds(self, images, input_ids):
        # encode image
        images = self.model.transformer.visual(images)
        # compute image position
        bos_pos = torch.where(input_ids == self.model.transformer.config.
                              visual['image_start_id'])
        eos_pos = torch.where(
            input_ids ==
            self.model.transformer.config.visual['image_start_id'] + 1)
        assert (bos_pos[0] == eos_pos[0]).all()
        img_pos = torch.stack((bos_pos[0], bos_pos[1], eos_pos[1]), dim=1)
        # embed words
        inputs_embeds = self.model.transformer.wte(input_ids)
        # embed image tokens
        for idx, (i, a, b) in enumerate(img_pos):
            inputs_embeds[i][a + 1:b] = images[idx]
        return inputs_embeds

    def generate(self, batch):
        images = batch.pop('inputs')
        images = torch.stack(images, dim=0)
        format_input = self.prompt_constructor(batch)
        query = self.tokenizer.from_list_format(format_input)

        inputs = self.tokenizer(query, return_tensors='pt')
        inputs = inputs.to(get_device())
        input_ids, token_type_ids, attention_mask = inputs[
            'input_ids'], inputs['token_type_ids'], inputs['attention_mask']
        inputs_embeds = self._build_embeds(images, input_ids)
        pred = self.model.generate(input_ids=input_ids,
                                   inputs_embeds=inputs_embeds,
                                   attention_mask=attention_mask,
                                   token_type_ids=token_type_ids)
        response = self.post_processor(pred.cpu()[0])

        data_sample = batch['data_samples'][0]
        if self.is_caption_task:
            data_sample.pred_caption = response
        else:
            data_sample.pred_answer = response
        return data_sample

    def forward(self, batch):
        return self.generate(batch)


@MM_MODELS.register_module('qwen-vl-chat')
class QwenVLChat(QwenVLBase):
    """Inference code of Qwen-VL-Chat.

    We load the Qwen model via Huggingface.
    Args:
        pretrained_path (str): Path to Qwen checkpoint or repo id.
        prompt_constructor (dict): The config of prompt constructor.
        post_processor (dict): The config of post processor.
        is_caption_task (bool): Whether the task is caption task.
            Defaults to False.
    """

    def __init__(self,
                 pretrained_path: str,
                 prompt_constructor: dict = None,
                 post_processor: dict = None,
                 is_caption_task: bool = False) -> None:
        super().__init__(pretrained_path, prompt_constructor, post_processor,
                         is_caption_task)

    def generate(self, batch):
        images = batch.pop('inputs')
        images = torch.stack(images, dim=0)
        format_input = self.prompt_constructor(batch)
        query = self.tokenizer.from_list_format(format_input)

        raw_text, context_tokens = make_context(
            self.tokenizer,
            query,
            system='You are a helpful assistant.',
            chat_format=self.model.generation_config.chat_format,
        )

        input_ids = torch.tensor([context_tokens]).to(get_device())

        inputs_embeds = self._build_embeds(images, input_ids)
        pred = self.model.generate(input_ids=input_ids,
                                   inputs_embeds=inputs_embeds)

        response = decode_tokens(
            pred[0],
            self.tokenizer,
            raw_text_len=len(raw_text),
            context_length=len(context_tokens),
            chat_format=self.model.generation_config.chat_format,
            verbose=False,
            errors='replace')

        if self.post_processor:
            response = self.post_processor(response)

        data_sample = batch['data_samples'][0]
        if self.is_caption_task:
            data_sample.pred_caption = response
        else:
            data_sample.pred_answer = response
        return data_sample


def forward_hack(self,
                 input_ids: Optional[torch.LongTensor] = None,
                 past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
                 attention_mask: Optional[torch.FloatTensor] = None,
                 token_type_ids: Optional[torch.LongTensor] = None,
                 position_ids: Optional[torch.LongTensor] = None,
                 head_mask: Optional[torch.FloatTensor] = None,
                 inputs_embeds: Optional[torch.FloatTensor] = None,
                 encoder_hidden_states: Optional[torch.Tensor] = None,
                 encoder_attention_mask: Optional[torch.FloatTensor] = None,
                 use_cache: Optional[bool] = None,
                 output_attentions: Optional[bool] = None,
                 output_hidden_states: Optional[bool] = None,
                 return_dict: Optional[bool] = None):
    if past_key_values is None and input_ids is not None and torch.any(
            input_ids == self.config.visual['image_start_id']):
        bos_pos = torch.where(
            input_ids == self.config.visual['image_start_id'])
        eos_pos = torch.where(
            input_ids == self.config.visual['image_start_id'] + 1)
        assert (bos_pos[0] == eos_pos[0]).all()
        img_pos = torch.stack((bos_pos[0], bos_pos[1], eos_pos[1]), dim=1)
        images = []
        for i, a, b in img_pos:
            image = input_ids[i][a + 1:b - 1].tolist()
            image = image[:image.index(self.config.visual['image_start_id'] +
                                       2)]
            images.append(bytes(image).decode('utf-8'))

        images = self.visual.encode(images)
        assert images.shape[0] == len(images)
    else:
        images = None

    output_attentions = (output_attentions if output_attentions is not None
                         else self.config.output_attentions)
    output_hidden_states = (output_hidden_states if output_hidden_states
                            is not None else self.config.output_hidden_states)
    use_cache = use_cache if use_cache is not None else self.config.use_cache
    return_dict = (return_dict
                   if return_dict is not None else self.config.use_return_dict)

    if input_ids is not None and inputs_embeds is not None:
        raise ValueError(
            'You cannot specify both input_ids and inputs_embeds at the same time'  # noqa
        )
    elif input_ids is not None:
        input_shape = input_ids.size()
        input_ids = input_ids.view(-1, input_shape[-1])
        batch_size = input_ids.shape[0]
    elif inputs_embeds is not None:
        input_shape = inputs_embeds.size()[:-1]
        batch_size = inputs_embeds.shape[0]
    else:
        raise ValueError(
            'You have to specify either input_ids or inputs_embeds')

    device = input_ids.device if input_ids is not None else inputs_embeds.device  # noqa

    if token_type_ids is not None:
        token_type_ids = token_type_ids.view(-1, input_shape[-1])
    if position_ids is not None:
        position_ids = position_ids.view(-1, input_shape[-1])

    if past_key_values is None:
        past_length = 0
        past_key_values = tuple([None] * len(self.h))
    else:
        past_length = past_key_values[0][0].size(-2)

    if position_ids is None:
        position_ids = torch.arange(
            past_length,
            input_shape[-1] + past_length,
            dtype=torch.long,
            device=device,
        )
        position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])

    encoder_attention_mask = None
    head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)

    if inputs_embeds is None:
        inputs_embeds = self.wte(input_ids)

    if batch_size <= 0:
        raise ValueError('batch_size has to be defined and > 0')
    attention_mask = self._prepare_decoder_attention_mask(
        attention_mask, input_shape, inputs_embeds, past_length)

    hidden_states = inputs_embeds

    hidden_states = self.drop(hidden_states)
    if images is not None:
        for idx, (i, a, b) in enumerate(img_pos):
            hidden_states[i][a + 1:b] = images[idx]
    output_shape = input_shape + (hidden_states.size(-1), )

    presents = () if use_cache else None
    all_self_attentions = () if output_attentions else None
    all_hidden_states = () if output_hidden_states else None
    for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):

        if output_hidden_states:
            all_hidden_states = all_hidden_states + (hidden_states, )

        if self.gradient_checkpointing and self.training:

            def create_custom_forward(module):

                def custom_forward(*inputs):
                    # None for past_key_value
                    return module(*inputs, use_cache, output_attentions)

                return custom_forward

            outputs = torch.utils.checkpoint.checkpoint(
                create_custom_forward(block),
                hidden_states,
                None,
                attention_mask,
                head_mask[i],
                encoder_hidden_states,
                encoder_attention_mask,
            )
        else:
            outputs = block(
                hidden_states,
                layer_past=layer_past,
                attention_mask=attention_mask,
                head_mask=head_mask[i],
                encoder_hidden_states=encoder_hidden_states,
                encoder_attention_mask=encoder_attention_mask,
                use_cache=use_cache,
                output_attentions=output_attentions,
            )

        hidden_states = outputs[0]
        if use_cache is True:
            presents = presents + (outputs[2 if output_attentions else 1], )

        if output_attentions:
            all_self_attentions = all_self_attentions + (outputs[1], )

    hidden_states = self.ln_f(hidden_states)
    hidden_states = hidden_states.view(output_shape)
    # Add last hidden state
    if output_hidden_states:
        all_hidden_states = all_hidden_states + (hidden_states, )

    if not return_dict:
        return tuple(v for v in [hidden_states, presents, all_hidden_states]
                     if v is not None)

    return BaseModelOutputWithPast(
        last_hidden_state=hidden_states,
        past_key_values=presents,
        hidden_states=all_hidden_states,
        attentions=all_self_attentions,
    )