Commit
•
2bf7de6
1
Parent(s):
f84e97e
Update modeling_cogvlm.py
Browse files- modeling_cogvlm.py +837 -808
modeling_cogvlm.py
CHANGED
@@ -1,808 +1,837 @@
|
|
1 |
-
"""largely copy from llama and adapt for cogvlm"""
|
2 |
-
import warnings
|
3 |
-
from typing import TYPE_CHECKING, Optional, Tuple, List, Union, Literal, Dict, Any
|
4 |
-
|
5 |
-
import math
|
6 |
-
import torch
|
7 |
-
from torch import nn
|
8 |
-
from torch.nn import CrossEntropyLoss
|
9 |
-
from torchvision import transforms
|
10 |
-
from einops import rearrange
|
11 |
-
|
12 |
-
|
13 |
-
from transformers
|
14 |
-
from transformers.
|
15 |
-
from transformers.
|
16 |
-
|
17 |
-
|
18 |
-
from .
|
19 |
-
from .
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
mask
|
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 |
-
self.
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
self.
|
82 |
-
self.
|
83 |
-
self.
|
84 |
-
self.
|
85 |
-
self.
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
vision_token_mask
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
self.
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
output[
|
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 |
-
attention_scores =
|
140 |
-
attention_scores =
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
self.
|
152 |
-
self.
|
153 |
-
self.
|
154 |
-
self.
|
155 |
-
self.
|
156 |
-
self.
|
157 |
-
self.
|
158 |
-
self.
|
159 |
-
self.
|
160 |
-
self.
|
161 |
-
self.
|
162 |
-
self.
|
163 |
-
self.
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
shape
|
188 |
-
|
189 |
-
mixed_raw_layer
|
190 |
-
mixed_raw_layer[
|
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 |
-
f" {
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
attn_output
|
229 |
-
attn_output[
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
self.
|
242 |
-
self.
|
243 |
-
self.
|
244 |
-
self.
|
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 |
-
hidden_states = self.
|
276 |
-
hidden_states =
|
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 |
-
tmp
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
is_boi_eoi
|
326 |
-
is_boi_eoi[:,
|
327 |
-
is_boi_eoi[:,
|
328 |
-
is_boi_eoi[:,
|
329 |
-
tmp[
|
330 |
-
|
331 |
-
|
332 |
-
y
|
333 |
-
y =
|
334 |
-
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
self.
|
342 |
-
self.
|
343 |
-
self.
|
344 |
-
self.
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
|
351 |
-
|
352 |
-
|
353 |
-
|
354 |
-
|
355 |
-
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
363 |
-
|
364 |
-
|
365 |
-
|
366 |
-
|
367 |
-
|
368 |
-
|
369 |
-
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
|
374 |
-
|
375 |
-
|
376 |
-
|
377 |
-
|
378 |
-
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
assert
|
388 |
-
|
389 |
-
|
390 |
-
images_features =
|
391 |
-
images_features = images_features
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
|
398 |
-
|
399 |
-
|
400 |
-
|
401 |
-
|
402 |
-
|
403 |
-
|
404 |
-
|
405 |
-
|
406 |
-
|
407 |
-
|
408 |
-
|
409 |
-
|
410 |
-
|
411 |
-
|
412 |
-
|
413 |
-
|
414 |
-
|
415 |
-
|
416 |
-
|
417 |
-
|
418 |
-
|
419 |
-
|
420 |
-
|
421 |
-
|
422 |
-
|
423 |
-
|
424 |
-
|
425 |
-
|
426 |
-
|
427 |
-
|
428 |
-
|
429 |
-
|
430 |
-
|
431 |
-
|
432 |
-
|
433 |
-
|
434 |
-
|
435 |
-
|
436 |
-
|
437 |
-
|
438 |
-
|
439 |
-
|
440 |
-
|
441 |
-
|
442 |
-
|
443 |
-
|
444 |
-
|
445 |
-
|
446 |
-
|
447 |
-
|
448 |
-
|
449 |
-
|
450 |
-
|
451 |
-
|
452 |
-
|
453 |
-
|
454 |
-
|
455 |
-
|
456 |
-
|
457 |
-
|
458 |
-
|
459 |
-
|
460 |
-
|
461 |
-
|
462 |
-
|
463 |
-
|
464 |
-
|
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 |
-
|
517 |
-
|
518 |
-
|
519 |
-
|
520 |
-
|
521 |
-
|
522 |
-
|
523 |
-
|
524 |
-
|
525 |
-
|
526 |
-
|
527 |
-
|
528 |
-
|
529 |
-
|
530 |
-
|
531 |
-
|
532 |
-
|
533 |
-
|
534 |
-
|
535 |
-
|
536 |
-
|
537 |
-
|
538 |
-
|
539 |
-
if
|
540 |
-
|
541 |
-
|
542 |
-
|
543 |
-
|
544 |
-
|
545 |
-
|
546 |
-
|
547 |
-
|
548 |
-
|
549 |
-
|
550 |
-
|
551 |
-
def
|
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 |
-
|
580 |
-
|
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 |
-
|
692 |
-
|
693 |
-
|
694 |
-
|
695 |
-
|
696 |
-
|
697 |
-
|
698 |
-
|
699 |
-
|
700 |
-
|
701 |
-
|
702 |
-
|
703 |
-
|
704 |
-
|
705 |
-
|
706 |
-
|
707 |
-
|
708 |
-
|
709 |
-
|
710 |
-
|
711 |
-
|
712 |
-
|
713 |
-
if
|
714 |
-
|
715 |
-
|
716 |
-
|
717 |
-
|
718 |
-
|
719 |
-
|
720 |
-
|
721 |
-
|
722 |
-
|
723 |
-
|
724 |
-
|
725 |
-
|
726 |
-
|
727 |
-
|
728 |
-
|
729 |
-
|
730 |
-
|
731 |
-
|
732 |
-
|
733 |
-
|
734 |
-
|
735 |
-
|
736 |
-
|
737 |
-
|
738 |
-
|
739 |
-
|
740 |
-
|
741 |
-
|
742 |
-
|
743 |
-
|
744 |
-
|
745 |
-
|
746 |
-
|
747 |
-
|
748 |
-
|
749 |
-
|
750 |
-
|
751 |
-
|
752 |
-
|
753 |
-
|
754 |
-
|
755 |
-
|
756 |
-
|
757 |
-
|
758 |
-
|
759 |
-
|
760 |
-
|
761 |
-
|
762 |
-
|
763 |
-
|
764 |
-
|
765 |
-
|
766 |
-
|
767 |
-
|
768 |
-
|
769 |
-
|
770 |
-
|
771 |
-
|
772 |
-
|
773 |
-
|
774 |
-
|
775 |
-
|
776 |
-
|
777 |
-
|
778 |
-
|
779 |
-
|
780 |
-
|
781 |
-
|
782 |
-
|
783 |
-
|
784 |
-
|
785 |
-
|
786 |
-
|
787 |
-
|
788 |
-
|
789 |
-
|
790 |
-
|
791 |
-
|
792 |
-
|
793 |
-
input_ids
|
794 |
-
token_type_ids
|
795 |
-
|
796 |
-
|
797 |
-
|
798 |
-
|
799 |
-
|
800 |
-
|
801 |
-
|
802 |
-
|
803 |
-
|
804 |
-
|
805 |
-
|
806 |
-
|
807 |
-
|
808 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""largely copy from llama and adapt for cogvlm"""
|
2 |
+
import warnings
|
3 |
+
from typing import TYPE_CHECKING, Optional, Tuple, List, Union, Literal, Dict, Any
|
4 |
+
|
5 |
+
import math
|
6 |
+
import torch
|
7 |
+
from torch import nn
|
8 |
+
from torch.nn import CrossEntropyLoss
|
9 |
+
from torchvision import transforms
|
10 |
+
from einops import rearrange
|
11 |
+
from torch.utils.checkpoint import checkpoint
|
12 |
+
|
13 |
+
from transformers import PreTrainedModel, PreTrainedTokenizer
|
14 |
+
from transformers.utils.logging import get_logger
|
15 |
+
from transformers.activations import ACT2FN
|
16 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
17 |
+
|
18 |
+
from .configuration_cogvlm import CogVLMConfig
|
19 |
+
from .util import FastRotaryEmbedding
|
20 |
+
from .visual import EVA2CLIPModel
|
21 |
+
|
22 |
+
if TYPE_CHECKING:
|
23 |
+
from transformers.utils import ModelOutput
|
24 |
+
|
25 |
+
logger = get_logger(__name__)
|
26 |
+
|
27 |
+
LANGUAGE_TOKEN_TYPE = 0
|
28 |
+
VISION_TOKEN_TYPE = 1
|
29 |
+
|
30 |
+
|
31 |
+
# Copied from transformers.models.bart.modeling_bart._make_causal_mask
|
32 |
+
def _make_causal_mask(
|
33 |
+
input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
|
34 |
+
):
|
35 |
+
"""
|
36 |
+
Make causal mask used for bi-directional self-attention.
|
37 |
+
"""
|
38 |
+
bsz, tgt_len = input_ids_shape
|
39 |
+
mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
|
40 |
+
mask_cond = torch.arange(mask.size(-1), device=device)
|
41 |
+
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
|
42 |
+
mask = mask.to(dtype)
|
43 |
+
|
44 |
+
if past_key_values_length > 0:
|
45 |
+
mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
|
46 |
+
return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
|
47 |
+
|
48 |
+
|
49 |
+
# Copied from transformers.models.bart.modeling_bart._expand_mask
|
50 |
+
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
51 |
+
"""
|
52 |
+
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
53 |
+
"""
|
54 |
+
bsz, src_len = mask.size()
|
55 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
56 |
+
|
57 |
+
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
58 |
+
|
59 |
+
inverted_mask = 1.0 - expanded_mask
|
60 |
+
|
61 |
+
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
|
62 |
+
|
63 |
+
|
64 |
+
class RMSNorm(nn.Module):
|
65 |
+
def __init__(self, hidden_size, eps=1e-5):
|
66 |
+
super().__init__()
|
67 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
68 |
+
self.variance_epsilon = eps
|
69 |
+
|
70 |
+
def forward(self, hidden_states):
|
71 |
+
input_dtype = hidden_states.dtype
|
72 |
+
hidden_states = hidden_states.to(torch.float32)
|
73 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
74 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
75 |
+
return (self.weight * hidden_states).to(input_dtype)
|
76 |
+
|
77 |
+
|
78 |
+
class MLP(nn.Module):
|
79 |
+
def __init__(self, config):
|
80 |
+
super().__init__()
|
81 |
+
self.hidden_size = config.hidden_size
|
82 |
+
self.intermediate_size = config.intermediate_size
|
83 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
84 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
85 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
86 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
87 |
+
|
88 |
+
def forward(self, x):
|
89 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
90 |
+
return down_proj
|
91 |
+
|
92 |
+
|
93 |
+
def get_expert_mask(token_type_ids: "torch.LongTensor(B, L)") -> "[torch.BoolTensor(B, L), torch.BoolTensor(B, L)]":
|
94 |
+
vision_token_mask = torch.zeros_like(token_type_ids, dtype=torch.bool)
|
95 |
+
vision_token_mask[:, :-1] = (token_type_ids[:, :-1] == VISION_TOKEN_TYPE) & (token_type_ids[:, 1:] == VISION_TOKEN_TYPE)
|
96 |
+
language_token_mask = ~vision_token_mask
|
97 |
+
return vision_token_mask, language_token_mask
|
98 |
+
|
99 |
+
|
100 |
+
class VisionExpertMLP(nn.Module):
|
101 |
+
def __init__(self, config):
|
102 |
+
super().__init__()
|
103 |
+
self.language_mlp = MLP(config)
|
104 |
+
self.vision_mlp = MLP(config)
|
105 |
+
|
106 |
+
def forward(self, hidden_states: "torch.Tensor(B, L, D)", token_type_ids: "torch.LongTensor(B, L)"):
|
107 |
+
output = torch.empty(hidden_states.shape, dtype=hidden_states.dtype, device=hidden_states.device)
|
108 |
+
vision_token_mask, language_token_mask = get_expert_mask(token_type_ids)
|
109 |
+
output[vision_token_mask] = self.vision_mlp(hidden_states[vision_token_mask])
|
110 |
+
output[language_token_mask] = self.language_mlp(hidden_states[language_token_mask])
|
111 |
+
return output
|
112 |
+
|
113 |
+
|
114 |
+
def attention_fn(
|
115 |
+
query_layer: "torch.tensor(B, H, L, HD)",
|
116 |
+
key_layer: "torch.tensor(B, H, L, HD)",
|
117 |
+
value_layer: "torch.tensor(B, H, L, HD)",
|
118 |
+
attention_mask: "torch.tensor(B, H, L, HD)",
|
119 |
+
*,
|
120 |
+
scaling_attention_score: bool = True,
|
121 |
+
attention_dropout: nn.Module = None
|
122 |
+
):
|
123 |
+
attention_mask_bool = (attention_mask == 0)
|
124 |
+
is_low_triangle = (attention_mask_bool == torch.ones_like(attention_mask_bool, dtype=torch.float).tril()).all()
|
125 |
+
is_full = (attention_mask_bool > 0).all()
|
126 |
+
if not (int(torch.__version__.split('.')[0]) >= 2):
|
127 |
+
warnings.warn("It's recommended to use torch2.0 or higher.")
|
128 |
+
if int(torch.__version__.split('.')[0]) >= 2 and scaling_attention_score and (is_full or is_low_triangle):
|
129 |
+
dropout_p = 0. if attention_dropout is None or not attention_dropout.training else attention_dropout.p
|
130 |
+
return torch.nn.functional.scaled_dot_product_attention(
|
131 |
+
query_layer, key_layer, value_layer,
|
132 |
+
attn_mask=None,
|
133 |
+
dropout_p=dropout_p,
|
134 |
+
is_causal=not is_full
|
135 |
+
)
|
136 |
+
else:
|
137 |
+
if scaling_attention_score:
|
138 |
+
query_layer = query_layer / math.sqrt(query_layer.shape[-1])
|
139 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
140 |
+
attention_scores = attention_scores + attention_mask
|
141 |
+
attention_scores = nn.functional.softmax(attention_scores, dim=-1, dtype=torch.float32).to(query_layer.dtype)
|
142 |
+
if attention_dropout is not None:
|
143 |
+
attention_scores = attention_dropout(attention_scores)
|
144 |
+
context_layer = torch.matmul(attention_scores, value_layer)
|
145 |
+
return context_layer
|
146 |
+
|
147 |
+
|
148 |
+
class VisionExpertAttention(nn.Module):
|
149 |
+
def __init__(self, config):
|
150 |
+
super().__init__()
|
151 |
+
self.config = config
|
152 |
+
self.hidden_size = config.hidden_size
|
153 |
+
self.num_attention_heads = config.num_attention_heads
|
154 |
+
self.num_multi_query_heads = config.num_multi_query_heads
|
155 |
+
self.hidden_size_per_attention_head = self.hidden_size // self.num_attention_heads
|
156 |
+
self.stride = [self.num_attention_heads, self.num_multi_query_heads, self.num_multi_query_heads]
|
157 |
+
self.qkv_size = self.hidden_size + self.hidden_size_per_attention_head * self.num_multi_query_heads * 2
|
158 |
+
self.head_dim = self.hidden_size // self.num_attention_heads
|
159 |
+
self.max_position_embeddings = config.max_position_embeddings
|
160 |
+
self.rotary_emb = FastRotaryEmbedding(dim=self.head_dim, pos_idx_in_fp32=False, base=500000)
|
161 |
+
self.vision_expert_query_key_value = nn.Linear(self.hidden_size, self.qkv_size, bias=True)
|
162 |
+
self.vision_expert_dense = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
|
163 |
+
self.language_expert_query_key_value = nn.Linear(self.hidden_size, self.qkv_size, bias=False)
|
164 |
+
self.language_expert_dense = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
|
165 |
+
|
166 |
+
def _transpose_for_scores(self, tensor):
|
167 |
+
"""Transpose a 3D tensor [B, L, H*HD] into a 4D tensor with size [B H L HD]."""
|
168 |
+
new_tensor_shape = tensor.size()[:-1] + \
|
169 |
+
(-1, # flexible for multi-query
|
170 |
+
self.hidden_size_per_attention_head)
|
171 |
+
tensor = tensor.view(*new_tensor_shape)
|
172 |
+
return tensor.permute(0, 2, 1, 3)
|
173 |
+
|
174 |
+
def forward(
|
175 |
+
self,
|
176 |
+
hidden_states: torch.Tensor,
|
177 |
+
token_type_ids: torch.LongTensor,
|
178 |
+
position_ids: torch.LongTensor,
|
179 |
+
attention_mask: Optional[torch.Tensor] = None,
|
180 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
181 |
+
output_attentions: bool = False,
|
182 |
+
use_cache: bool = False,
|
183 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
184 |
+
bsz, q_len, _ = hidden_states.size()
|
185 |
+
vision_token_mask, language_token_mask = get_expert_mask(token_type_ids)
|
186 |
+
|
187 |
+
shape = list(hidden_states.shape)
|
188 |
+
shape[-1] = self.qkv_size
|
189 |
+
mixed_raw_layer = torch.empty(shape, dtype=hidden_states.dtype, device=hidden_states.device)
|
190 |
+
mixed_raw_layer[vision_token_mask] = self.vision_expert_query_key_value(hidden_states[vision_token_mask])
|
191 |
+
mixed_raw_layer[language_token_mask] = self.language_expert_query_key_value(hidden_states[language_token_mask])
|
192 |
+
|
193 |
+
# query_states, key_states, value_states = torch.split(mixed_raw_layer, self.hidden_size, dim=-1)
|
194 |
+
factor = mixed_raw_layer.size()[-1] // sum(self.stride)
|
195 |
+
query_states, key_states, value_states = torch.split(mixed_raw_layer, [factor * x for x in self.stride], dim=-1)
|
196 |
+
|
197 |
+
query_states = self._transpose_for_scores(query_states) # B, H, L, HD
|
198 |
+
key_states = self._transpose_for_scores(key_states) # B, H, L, HD
|
199 |
+
value_states = self._transpose_for_scores(value_states) # B, H, L, HD
|
200 |
+
|
201 |
+
kv_seq_len = key_states.shape[-2]
|
202 |
+
if past_key_value is not None:
|
203 |
+
kv_seq_len += past_key_value[0].shape[-2]
|
204 |
+
|
205 |
+
query_states, key_states = self.rotary_emb(query_states, key_states, position_ids=position_ids, max_seqlen=position_ids.max() + 1)
|
206 |
+
|
207 |
+
if past_key_value is not None:
|
208 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
209 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
210 |
+
|
211 |
+
past_key_value = (key_states, value_states) if use_cache else None
|
212 |
+
|
213 |
+
key_states = key_states.unsqueeze(2).expand(-1, -1, self.num_attention_heads // self.num_multi_query_heads, -1, -1).contiguous().view(
|
214 |
+
bsz, self.num_attention_heads, *key_states.shape[2:])
|
215 |
+
value_states = value_states.unsqueeze(2).expand(-1, -1, self.num_attention_heads // self.num_multi_query_heads, -1,
|
216 |
+
-1).contiguous().view(bsz, self.num_attention_heads, *value_states.shape[2:])
|
217 |
+
|
218 |
+
context_layer = attention_fn(
|
219 |
+
query_layer=query_states, key_layer=key_states, value_layer=value_states, attention_mask=attention_mask,
|
220 |
+
scaling_attention_score=True, attention_dropout=None)
|
221 |
+
if context_layer.size() != (bsz, self.num_attention_heads, q_len, self.head_dim):
|
222 |
+
raise ValueError(
|
223 |
+
f"`attn_output` should be of size {(bsz, self.num_attention_heads, q_len, self.head_dim)}, but is"
|
224 |
+
f" {context_layer.size()}"
|
225 |
+
)
|
226 |
+
context_layer = context_layer.transpose(1, 2).contiguous().reshape(bsz, q_len, self.hidden_size)
|
227 |
+
|
228 |
+
attn_output = torch.empty(context_layer.shape, dtype=hidden_states.dtype, device=hidden_states.device)
|
229 |
+
attn_output[vision_token_mask] = self.vision_expert_dense(context_layer[vision_token_mask])
|
230 |
+
attn_output[language_token_mask] = self.language_expert_dense(context_layer[language_token_mask])
|
231 |
+
|
232 |
+
if output_attentions:
|
233 |
+
warnings.warn("output_attentions is not implemented.")
|
234 |
+
|
235 |
+
return attn_output, None, past_key_value
|
236 |
+
|
237 |
+
|
238 |
+
class CogVLMDecoderLayer(nn.Module):
|
239 |
+
def __init__(self, config):
|
240 |
+
super().__init__()
|
241 |
+
self.hidden_size = config.hidden_size
|
242 |
+
self.self_attn = VisionExpertAttention(config=config)
|
243 |
+
self.mlp = VisionExpertMLP(config)
|
244 |
+
self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
245 |
+
self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
246 |
+
|
247 |
+
def forward(
|
248 |
+
self,
|
249 |
+
hidden_states: torch.Tensor,
|
250 |
+
token_type_ids: torch.LongTensor,
|
251 |
+
position_ids: torch.LongTensor,
|
252 |
+
attention_mask: Optional[torch.Tensor] = None,
|
253 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
254 |
+
output_attentions: Optional[bool] = False,
|
255 |
+
use_cache: Optional[bool] = False,
|
256 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
257 |
+
residual = hidden_states
|
258 |
+
|
259 |
+
hidden_states = self.input_layernorm(hidden_states)
|
260 |
+
|
261 |
+
# Self Attention
|
262 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
263 |
+
hidden_states=hidden_states,
|
264 |
+
token_type_ids=token_type_ids,
|
265 |
+
position_ids=position_ids,
|
266 |
+
attention_mask=attention_mask,
|
267 |
+
past_key_value=past_key_value,
|
268 |
+
output_attentions=output_attentions,
|
269 |
+
use_cache=use_cache,
|
270 |
+
)
|
271 |
+
hidden_states = residual + hidden_states
|
272 |
+
|
273 |
+
# Fully Connected
|
274 |
+
residual = hidden_states
|
275 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
276 |
+
hidden_states = self.mlp(hidden_states, token_type_ids=token_type_ids)
|
277 |
+
hidden_states = residual + hidden_states
|
278 |
+
|
279 |
+
outputs = (hidden_states,)
|
280 |
+
|
281 |
+
if output_attentions:
|
282 |
+
outputs += (self_attn_weights,)
|
283 |
+
|
284 |
+
if use_cache:
|
285 |
+
outputs += (present_key_value,)
|
286 |
+
|
287 |
+
return outputs # type: ignore
|
288 |
+
|
289 |
+
|
290 |
+
class CogVLMPreTrainedModel(PreTrainedModel):
|
291 |
+
config_class = CogVLMConfig
|
292 |
+
base_model_prefix = "model"
|
293 |
+
supports_gradient_checkpointing = False
|
294 |
+
_no_split_modules = ["CogVLMDecoderLayer"]
|
295 |
+
_skip_keys_device_placement = "past_key_values"
|
296 |
+
|
297 |
+
def _init_weights(self, module):
|
298 |
+
std = self.config.initializer_range
|
299 |
+
if isinstance(module, nn.Linear):
|
300 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
301 |
+
if module.bias is not None:
|
302 |
+
module.bias.data.zero_()
|
303 |
+
elif isinstance(module, nn.Embedding):
|
304 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
305 |
+
if module.padding_idx is not None:
|
306 |
+
module.weight.data[module.padding_idx].zero_()
|
307 |
+
|
308 |
+
|
309 |
+
def is_empty(images_list: Optional[List[List[torch.Tensor]]]):
|
310 |
+
if images_list is None or len(images_list) == 0:
|
311 |
+
return True
|
312 |
+
for image_list in images_list:
|
313 |
+
if len(image_list):
|
314 |
+
return False
|
315 |
+
return True
|
316 |
+
|
317 |
+
|
318 |
+
def build_position_ids(x: "torch.BoolTensor(B, L)", attention_mask: Optional["torch.BoolTensor(B, L)"] = None) -> "torch.LongTensor(B, L)":
|
319 |
+
if attention_mask is not None:
|
320 |
+
tmp = x.clone()
|
321 |
+
tmp[~(attention_mask.bool())] = -1
|
322 |
+
else:
|
323 |
+
tmp = x.clone()
|
324 |
+
# image boi eoi token as LANGUAGE_TOKEN_TYPE
|
325 |
+
is_boi_eoi = torch.zeros_like(x, dtype=torch.bool)
|
326 |
+
is_boi_eoi[:, 1:] |= (tmp[:, 1:] == VISION_TOKEN_TYPE) & (tmp[:, :-1] == LANGUAGE_TOKEN_TYPE)
|
327 |
+
is_boi_eoi[:, 0] |= (tmp[:, 0] == VISION_TOKEN_TYPE)
|
328 |
+
is_boi_eoi[:, :-1] |= (tmp[:, :-1] == VISION_TOKEN_TYPE) & (tmp[:, 1:] == LANGUAGE_TOKEN_TYPE)
|
329 |
+
is_boi_eoi[:, -1] |= (tmp[:, -1] == VISION_TOKEN_TYPE)
|
330 |
+
tmp[is_boi_eoi] = LANGUAGE_TOKEN_TYPE
|
331 |
+
# final position ids
|
332 |
+
y = torch.zeros_like(x, dtype=torch.long)
|
333 |
+
y[:, 1:] = (tmp[:, 1:] == LANGUAGE_TOKEN_TYPE) | ((tmp[:, 1:] == VISION_TOKEN_TYPE) & (tmp[:, :-1] == LANGUAGE_TOKEN_TYPE))
|
334 |
+
y = y.cumsum(dim=-1)
|
335 |
+
return y
|
336 |
+
|
337 |
+
|
338 |
+
class CogVLMModel(CogVLMPreTrainedModel):
|
339 |
+
def __init__(self, config):
|
340 |
+
super().__init__(config)
|
341 |
+
self.padding_idx = 128002
|
342 |
+
self.vocab_size = config.vocab_size
|
343 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
344 |
+
self.layers = nn.ModuleList([CogVLMDecoderLayer(config) for _ in range(config.num_hidden_layers)])
|
345 |
+
self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
346 |
+
|
347 |
+
self.vision = EVA2CLIPModel(config)
|
348 |
+
|
349 |
+
self.gradient_checkpointing = False
|
350 |
+
# Initialize weights and apply final processing
|
351 |
+
self.post_init()
|
352 |
+
|
353 |
+
def encode_images(self, images: List[List[torch.Tensor]]) -> torch.Tensor:
|
354 |
+
images_list, images = images, []
|
355 |
+
|
356 |
+
images = []
|
357 |
+
for image_list in images_list:
|
358 |
+
for image in image_list:
|
359 |
+
images.append(image)
|
360 |
+
|
361 |
+
images = torch.stack(images)
|
362 |
+
images_features = self.vision(images)
|
363 |
+
return images_features
|
364 |
+
|
365 |
+
def forward(
|
366 |
+
self,
|
367 |
+
input_ids: torch.LongTensor = None,
|
368 |
+
images: List[List[torch.Tensor]] = None,
|
369 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
370 |
+
attention_mask: Optional[torch.Tensor] = None,
|
371 |
+
position_ids: Optional[torch.LongTensor] = None,
|
372 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
373 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
374 |
+
use_cache: Optional[bool] = None,
|
375 |
+
output_attentions: Optional[bool] = None,
|
376 |
+
output_hidden_states: Optional[bool] = None,
|
377 |
+
return_dict: Optional[bool] = None,
|
378 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
379 |
+
"""take care of image_encode, token_type_ids, position_ids and (attention_mask = None is fine)"""
|
380 |
+
|
381 |
+
if past_key_values is not None:
|
382 |
+
pass # generate mode with past_key_values. the image features are already mapped
|
383 |
+
else:
|
384 |
+
# not allow for inputs_embeds, because we want to process image feature
|
385 |
+
assert input_ids is not None and inputs_embeds is None, f"{input_ids} {inputs_embeds}"
|
386 |
+
if not is_empty(images): # multi-modality
|
387 |
+
assert token_type_ids is not None, f"multi-modality requires `token_type_ids`!"
|
388 |
+
assert len(input_ids) == len(images), f"{len(input_ids)} {len(images)}"
|
389 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
390 |
+
images_features = self.encode_images(images)
|
391 |
+
images_features = rearrange(images_features, 'b n d -> (b n) d')
|
392 |
+
images_features = images_features.to(dtype=inputs_embeds.dtype, device=inputs_embeds.device)
|
393 |
+
inputs_embeds = inputs_embeds.index_put([token_type_ids == VISION_TOKEN_TYPE], images_features)
|
394 |
+
else: # single-modality
|
395 |
+
if token_type_ids is None:
|
396 |
+
token_type_ids = torch.ones_like(input_ids, dtype=torch.long, device=input_ids.device) * LANGUAGE_TOKEN_TYPE
|
397 |
+
assert not (token_type_ids == VISION_TOKEN_TYPE).any(), f"{(token_type_ids == VISION_TOKEN_TYPE).sum()}"
|
398 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
399 |
+
|
400 |
+
if position_ids is None:
|
401 |
+
position_ids = build_position_ids(token_type_ids, attention_mask)
|
402 |
+
input_ids = None
|
403 |
+
return self.llm_forward(
|
404 |
+
input_ids=input_ids,
|
405 |
+
token_type_ids=token_type_ids,
|
406 |
+
attention_mask=attention_mask,
|
407 |
+
position_ids=position_ids,
|
408 |
+
past_key_values=past_key_values,
|
409 |
+
inputs_embeds=inputs_embeds,
|
410 |
+
use_cache=use_cache,
|
411 |
+
output_attentions=output_attentions,
|
412 |
+
output_hidden_states=output_hidden_states,
|
413 |
+
return_dict=return_dict,
|
414 |
+
)
|
415 |
+
|
416 |
+
def llm_forward(
|
417 |
+
self,
|
418 |
+
input_ids: torch.LongTensor = None,
|
419 |
+
token_type_ids: torch.LongTensor = None,
|
420 |
+
attention_mask: Optional[torch.Tensor] = None,
|
421 |
+
position_ids: Optional[torch.LongTensor] = None,
|
422 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
423 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
424 |
+
use_cache: Optional[bool] = None,
|
425 |
+
output_attentions: Optional[bool] = None,
|
426 |
+
output_hidden_states: Optional[bool] = None,
|
427 |
+
return_dict: Optional[bool] = None,
|
428 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
429 |
+
"""largely copy from llama forward and adapt for cogvlm with `token_type_ids`"""
|
430 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
431 |
+
output_hidden_states = (
|
432 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
433 |
+
)
|
434 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
435 |
+
|
436 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
437 |
+
|
438 |
+
# retrieve input_ids and inputs_embeds
|
439 |
+
if input_ids is not None and inputs_embeds is not None:
|
440 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
441 |
+
elif input_ids is not None:
|
442 |
+
batch_size, seq_length = input_ids.shape
|
443 |
+
elif inputs_embeds is not None:
|
444 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
445 |
+
else:
|
446 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
447 |
+
|
448 |
+
seq_length_with_past = seq_length
|
449 |
+
past_key_values_length = 0
|
450 |
+
|
451 |
+
if past_key_values is not None:
|
452 |
+
past_key_values_length = past_key_values[0][0].shape[2]
|
453 |
+
seq_length_with_past = seq_length_with_past + past_key_values_length
|
454 |
+
|
455 |
+
if position_ids is None:
|
456 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
457 |
+
position_ids = torch.arange(
|
458 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
459 |
+
)
|
460 |
+
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
461 |
+
else:
|
462 |
+
position_ids = position_ids.view(-1, seq_length).long()
|
463 |
+
|
464 |
+
if inputs_embeds is None:
|
465 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
466 |
+
# embed positions
|
467 |
+
if attention_mask is None:
|
468 |
+
attention_mask = torch.ones(
|
469 |
+
(batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
|
470 |
+
)
|
471 |
+
attention_mask = self._prepare_decoder_attention_mask(
|
472 |
+
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
473 |
+
)
|
474 |
+
|
475 |
+
hidden_states = inputs_embeds
|
476 |
+
|
477 |
+
# decoder layers
|
478 |
+
all_hidden_states = () if output_hidden_states else None
|
479 |
+
all_self_attns = () if output_attentions else None
|
480 |
+
next_decoder_cache = () if use_cache else None
|
481 |
+
|
482 |
+
for idx, decoder_layer in enumerate(self.layers):
|
483 |
+
if output_hidden_states:
|
484 |
+
all_hidden_states += (hidden_states,)
|
485 |
+
|
486 |
+
past_key_value = past_key_values[idx] if past_key_values is not None else None
|
487 |
+
|
488 |
+
def custom(index):
|
489 |
+
def custom_forward(
|
490 |
+
hidden_states,
|
491 |
+
token_type_ids=token_type_ids,
|
492 |
+
attention_mask=attention_mask,
|
493 |
+
position_ids=position_ids,
|
494 |
+
past_key_value=past_key_value,
|
495 |
+
output_attentions=output_attentions,
|
496 |
+
use_cache=use_cache,
|
497 |
+
):
|
498 |
+
layer = self.layers[index]
|
499 |
+
outputs = layer(
|
500 |
+
hidden_states,
|
501 |
+
token_type_ids=token_type_ids,
|
502 |
+
attention_mask=attention_mask,
|
503 |
+
position_ids=position_ids,
|
504 |
+
past_key_value=past_key_value,
|
505 |
+
output_attentions=output_attentions,
|
506 |
+
use_cache=use_cache,
|
507 |
+
)
|
508 |
+
return outputs
|
509 |
+
|
510 |
+
return custom_forward
|
511 |
+
# layer_outputs = decoder_layer(
|
512 |
+
# hidden_states,
|
513 |
+
# token_type_ids=token_type_ids,
|
514 |
+
# attention_mask=attention_mask,
|
515 |
+
# position_ids=position_ids,
|
516 |
+
# past_key_value=past_key_value,
|
517 |
+
# output_attentions=output_attentions,
|
518 |
+
# use_cache=use_cache,
|
519 |
+
# )
|
520 |
+
layer_outputs = checkpoint(custom(idx),
|
521 |
+
hidden_states,
|
522 |
+
use_reentrant=False
|
523 |
+
)
|
524 |
+
hidden_states = layer_outputs[0]
|
525 |
+
|
526 |
+
if use_cache:
|
527 |
+
next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
|
528 |
+
|
529 |
+
if output_attentions:
|
530 |
+
all_self_attns += (layer_outputs[1],)
|
531 |
+
|
532 |
+
hidden_states = self.norm(hidden_states)
|
533 |
+
|
534 |
+
# add hidden states from the last decoder layer
|
535 |
+
if output_hidden_states:
|
536 |
+
all_hidden_states += (hidden_states,)
|
537 |
+
|
538 |
+
next_cache = next_decoder_cache if use_cache else None
|
539 |
+
if not return_dict:
|
540 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
541 |
+
return BaseModelOutputWithPast(
|
542 |
+
last_hidden_state=hidden_states,
|
543 |
+
past_key_values=next_cache,
|
544 |
+
hidden_states=all_hidden_states,
|
545 |
+
attentions=all_self_attns,
|
546 |
+
)
|
547 |
+
|
548 |
+
def get_input_embeddings(self):
|
549 |
+
return self.embed_tokens
|
550 |
+
|
551 |
+
def set_input_embeddings(self, value):
|
552 |
+
self.embed_tokens = value
|
553 |
+
|
554 |
+
# noinspection PyMethodMayBeStatic
|
555 |
+
# Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
|
556 |
+
def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
|
557 |
+
# create causal mask
|
558 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
559 |
+
combined_attention_mask = None
|
560 |
+
if input_shape[-1] > 1:
|
561 |
+
combined_attention_mask = _make_causal_mask(
|
562 |
+
input_shape,
|
563 |
+
inputs_embeds.dtype,
|
564 |
+
device=inputs_embeds.device,
|
565 |
+
past_key_values_length=past_key_values_length,
|
566 |
+
)
|
567 |
+
|
568 |
+
if attention_mask is not None:
|
569 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
570 |
+
expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
|
571 |
+
inputs_embeds.device
|
572 |
+
)
|
573 |
+
combined_attention_mask = (
|
574 |
+
expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
|
575 |
+
)
|
576 |
+
|
577 |
+
return combined_attention_mask
|
578 |
+
|
579 |
+
|
580 |
+
def _history_to_prompt(signal_type, history, query):
|
581 |
+
if signal_type == 'base':
|
582 |
+
return query
|
583 |
+
elif signal_type == 'vqa':
|
584 |
+
answer_format = 'Short answer:'
|
585 |
+
elif signal_type == 'chat':
|
586 |
+
answer_format = 'Answer:'
|
587 |
+
else:
|
588 |
+
assert False, f"Unknown signal type {signal_type}"
|
589 |
+
|
590 |
+
prompt = ''
|
591 |
+
for i, (old_query, response) in enumerate(history):
|
592 |
+
prompt += 'Question: ' + old_query + " {} ".format(answer_format) + response + "\n"
|
593 |
+
prompt += 'Question: {} {}'.format(query, answer_format)
|
594 |
+
return prompt
|
595 |
+
|
596 |
+
|
597 |
+
class CogVLMForCausalLM(CogVLMPreTrainedModel):
|
598 |
+
_auto_class = "AutoModelForCausalLM"
|
599 |
+
|
600 |
+
def __init__(self, config):
|
601 |
+
super().__init__(config)
|
602 |
+
self.model = CogVLMModel(config)
|
603 |
+
self.vocab_size = config.vocab_size
|
604 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
605 |
+
|
606 |
+
# Initialize weights and apply final processing
|
607 |
+
self.post_init()
|
608 |
+
|
609 |
+
def get_input_embeddings(self):
|
610 |
+
return self.model.embed_tokens
|
611 |
+
|
612 |
+
def set_input_embeddings(self, value):
|
613 |
+
self.model.embed_tokens = value
|
614 |
+
|
615 |
+
def get_output_embeddings(self):
|
616 |
+
return self.lm_head
|
617 |
+
|
618 |
+
def set_output_embeddings(self, new_embeddings):
|
619 |
+
self.lm_head = new_embeddings
|
620 |
+
|
621 |
+
def set_decoder(self, decoder):
|
622 |
+
self.model = decoder
|
623 |
+
|
624 |
+
def get_decoder(self):
|
625 |
+
return self.model
|
626 |
+
|
627 |
+
def forward(
|
628 |
+
self,
|
629 |
+
input_ids: torch.LongTensor = None,
|
630 |
+
images: List[List[torch.Tensor]] = None,
|
631 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
632 |
+
attention_mask: Optional[torch.Tensor] = None,
|
633 |
+
position_ids: Optional[torch.LongTensor] = None,
|
634 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
635 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
636 |
+
use_cache: Optional[bool] = None,
|
637 |
+
output_attentions: Optional[bool] = None,
|
638 |
+
output_hidden_states: Optional[bool] = None,
|
639 |
+
return_dict: Optional[bool] = None,
|
640 |
+
labels: Optional[torch.LongTensor] = None,
|
641 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
642 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
643 |
+
output_hidden_states = (
|
644 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
645 |
+
)
|
646 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
647 |
+
|
648 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
649 |
+
outputs = self.model(
|
650 |
+
input_ids=input_ids,
|
651 |
+
images=images,
|
652 |
+
token_type_ids=token_type_ids,
|
653 |
+
attention_mask=attention_mask,
|
654 |
+
position_ids=position_ids,
|
655 |
+
past_key_values=past_key_values,
|
656 |
+
inputs_embeds=inputs_embeds,
|
657 |
+
use_cache=use_cache,
|
658 |
+
output_attentions=output_attentions,
|
659 |
+
output_hidden_states=output_hidden_states,
|
660 |
+
return_dict=return_dict,
|
661 |
+
)
|
662 |
+
|
663 |
+
hidden_states = outputs[0]
|
664 |
+
logits = self.lm_head(hidden_states)
|
665 |
+
logits = logits.float()
|
666 |
+
|
667 |
+
loss = None
|
668 |
+
if labels is not None:
|
669 |
+
# Shift so that tokens < n predict n
|
670 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
671 |
+
shift_labels = labels[..., 1:].contiguous()
|
672 |
+
# Flatten the tokens
|
673 |
+
loss_fct = CrossEntropyLoss()
|
674 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
675 |
+
shift_labels = shift_labels.view(-1)
|
676 |
+
# Enable model parallelism
|
677 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
678 |
+
loss = loss_fct(shift_logits, shift_labels)
|
679 |
+
|
680 |
+
if not return_dict:
|
681 |
+
output = (logits,) + outputs[1:]
|
682 |
+
return (loss,) + output if loss is not None else output
|
683 |
+
|
684 |
+
return CausalLMOutputWithPast(
|
685 |
+
loss=loss,
|
686 |
+
logits=logits,
|
687 |
+
past_key_values=outputs.past_key_values,
|
688 |
+
hidden_states=outputs.hidden_states,
|
689 |
+
attentions=outputs.attentions,
|
690 |
+
)
|
691 |
+
|
692 |
+
def _prepare_attention_mask_for_generation(
|
693 |
+
self,
|
694 |
+
inputs: torch.Tensor,
|
695 |
+
pad_token_id: Optional[int],
|
696 |
+
eos_token_id: Optional[Union[int, List[int]]],
|
697 |
+
) -> torch.LongTensor:
|
698 |
+
return torch.ones(inputs.shape[:2], dtype=torch.long, device=inputs.device) # type: ignore
|
699 |
+
|
700 |
+
def prepare_inputs_for_generation(
|
701 |
+
self, input_ids, token_type_ids, images=None, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
702 |
+
):
|
703 |
+
# build position_ids if needed
|
704 |
+
position_ids = kwargs.get("position_ids", None)
|
705 |
+
if position_ids is None:
|
706 |
+
position_ids = build_position_ids(token_type_ids, attention_mask)
|
707 |
+
|
708 |
+
if past_key_values:
|
709 |
+
input_ids = input_ids[:, -1:]
|
710 |
+
token_type_ids = token_type_ids[:, -1:]
|
711 |
+
position_ids = position_ids[:, -1:]
|
712 |
+
|
713 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
714 |
+
if inputs_embeds is not None and past_key_values is None:
|
715 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
716 |
+
else:
|
717 |
+
model_inputs = {"input_ids": input_ids}
|
718 |
+
|
719 |
+
model_inputs.update(
|
720 |
+
{
|
721 |
+
"token_type_ids": token_type_ids,
|
722 |
+
"images": images,
|
723 |
+
"position_ids": position_ids,
|
724 |
+
"past_key_values": past_key_values,
|
725 |
+
"use_cache": kwargs.get("use_cache"),
|
726 |
+
"attention_mask": attention_mask,
|
727 |
+
}
|
728 |
+
)
|
729 |
+
return model_inputs
|
730 |
+
|
731 |
+
def _update_model_kwargs_for_generation(
|
732 |
+
self,
|
733 |
+
outputs: "ModelOutput",
|
734 |
+
model_kwargs: Dict[str, Any],
|
735 |
+
is_encoder_decoder: bool = False,
|
736 |
+
standardize_cache_format: bool = False,
|
737 |
+
) -> Dict[str, Any]:
|
738 |
+
# update past_key_values
|
739 |
+
model_kwargs["past_key_values"] = self._extract_past_from_model_output(
|
740 |
+
outputs, standardize_cache_format=standardize_cache_format
|
741 |
+
)
|
742 |
+
if getattr(outputs, "state", None) is not None:
|
743 |
+
model_kwargs["state"] = outputs.state
|
744 |
+
|
745 |
+
# update token_type_ids with last value
|
746 |
+
if "token_type_ids" in model_kwargs:
|
747 |
+
token_type_ids = model_kwargs["token_type_ids"]
|
748 |
+
new_token_type_ids = torch.ones(size=(token_type_ids.shape[0], 1), dtype=token_type_ids.dtype, device=token_type_ids.device) * LANGUAGE_TOKEN_TYPE
|
749 |
+
model_kwargs["token_type_ids"] = torch.cat([token_type_ids, new_token_type_ids], dim=-1)
|
750 |
+
|
751 |
+
if not is_encoder_decoder:
|
752 |
+
# update attention mask
|
753 |
+
if "attention_mask" in model_kwargs:
|
754 |
+
attention_mask = model_kwargs["attention_mask"]
|
755 |
+
model_kwargs["attention_mask"] = torch.cat(
|
756 |
+
[attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
|
757 |
+
)
|
758 |
+
else:
|
759 |
+
# update decoder attention mask
|
760 |
+
if "decoder_attention_mask" in model_kwargs:
|
761 |
+
decoder_attention_mask = model_kwargs["decoder_attention_mask"]
|
762 |
+
model_kwargs["decoder_attention_mask"] = torch.cat(
|
763 |
+
[decoder_attention_mask, decoder_attention_mask.new_ones((decoder_attention_mask.shape[0], 1))],
|
764 |
+
dim=-1,
|
765 |
+
)
|
766 |
+
|
767 |
+
return model_kwargs
|
768 |
+
|
769 |
+
def _reorder_cache(self, past_key_values, beam_idx):
|
770 |
+
reordered_past = ()
|
771 |
+
for layer_past in past_key_values:
|
772 |
+
reordered_past += (
|
773 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
774 |
+
)
|
775 |
+
return reordered_past
|
776 |
+
|
777 |
+
def build_conversation_input_ids(
|
778 |
+
self,
|
779 |
+
tokenizer: "PreTrainedTokenizer",
|
780 |
+
*,
|
781 |
+
query: str,
|
782 |
+
history: Optional[List[Tuple[str, str]]] = None,
|
783 |
+
images: Optional[List["PIL.Image"]] = None,
|
784 |
+
template_version: Optional[Literal["base", "chat", "vqa"]] = None,
|
785 |
+
answer: str = None,
|
786 |
+
):
|
787 |
+
image_size: int = self.config.vision_config['image_size']
|
788 |
+
patch_size: int = self.config.vision_config['patch_size']
|
789 |
+
template_version = template_version or self.config.template_version
|
790 |
+
assert images is None or len(images) <= 1, f"not support multi images by now."
|
791 |
+
history = history or []
|
792 |
+
text = _history_to_prompt(template_version, history, query)
|
793 |
+
input_ids = [tokenizer.bos_token_id]
|
794 |
+
token_type_ids = [LANGUAGE_TOKEN_TYPE]
|
795 |
+
if images is not None and len(images) == 1:
|
796 |
+
# vision
|
797 |
+
transform = transforms.Compose(
|
798 |
+
[
|
799 |
+
transforms.Resize(
|
800 |
+
(image_size, image_size), interpolation=transforms.InterpolationMode.BICUBIC
|
801 |
+
),
|
802 |
+
transforms.ToTensor(),
|
803 |
+
transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
|
804 |
+
]
|
805 |
+
)
|
806 |
+
images = [transform(images[0])]
|
807 |
+
# language
|
808 |
+
vision_token_num = (image_size // patch_size // 2) * (image_size // patch_size // 2) + 2
|
809 |
+
|
810 |
+
tokenizer.pad_token_id = 128002 # llama3 adapt for cogvlm
|
811 |
+
|
812 |
+
input_ids += [tokenizer.pad_token_id] * vision_token_num
|
813 |
+
token_type_ids += [VISION_TOKEN_TYPE] * vision_token_num
|
814 |
+
text_ids = tokenizer.encode(text, add_special_tokens=False)
|
815 |
+
|
816 |
+
if answer is not None:
|
817 |
+
answer_ids = tokenizer.encode(answer, add_special_tokens=False)
|
818 |
+
answer_ids += [tokenizer.eos_token_id]
|
819 |
+
text_ids += answer_ids
|
820 |
+
|
821 |
+
|
822 |
+
input_ids += text_ids
|
823 |
+
token_type_ids += [LANGUAGE_TOKEN_TYPE] * len(text_ids)
|
824 |
+
attention_mask = [1] * len(input_ids)
|
825 |
+
if answer is not None:
|
826 |
+
labels = [-100 for _ in range(len(input_ids) - len(answer_ids))] + answer_ids
|
827 |
+
labels = torch.tensor(labels, dtype=torch.long)
|
828 |
+
else:
|
829 |
+
labels = None
|
830 |
+
|
831 |
+
return {
|
832 |
+
'input_ids': torch.tensor(input_ids, dtype=torch.long),
|
833 |
+
'token_type_ids': torch.tensor(token_type_ids, dtype=torch.long),
|
834 |
+
'attention_mask': torch.tensor(attention_mask, dtype=torch.long),
|
835 |
+
'images': images,
|
836 |
+
'labels': labels,
|
837 |
+
}
|