Spaces:
Running
on
A10G
Running
on
A10G
Commit
·
6c8a46d
1
Parent(s):
691ef95
models
Browse files- minigpt4/models/Qformer.py +1216 -0
- minigpt4/models/__init__.py +202 -0
- minigpt4/models/__pycache__/Qformer.cpython-39.pyc +0 -0
- minigpt4/models/__pycache__/__init__.cpython-39.pyc +0 -0
- minigpt4/models/__pycache__/base_model.cpython-39.pyc +0 -0
- minigpt4/models/__pycache__/eva_vit.cpython-39.pyc +0 -0
- minigpt4/models/__pycache__/minigpt4.cpython-39.pyc +0 -0
- minigpt4/models/__pycache__/minigpt_base.cpython-39.pyc +0 -0
- minigpt4/models/__pycache__/minigpt_v2.cpython-39.pyc +0 -0
- minigpt4/models/__pycache__/modeling_llama.cpython-39.pyc +0 -0
- minigpt4/models/base_model.py +251 -0
- minigpt4/models/eva_vit.py +442 -0
- minigpt4/models/minigpt4.py +195 -0
- minigpt4/models/minigpt_base.py +522 -0
- minigpt4/models/minigpt_v2.py +166 -0
- minigpt4/models/modeling_llama.py +116 -0
- minigpt4/processors/__init__.py +33 -0
- minigpt4/processors/__pycache__/__init__.cpython-39.pyc +0 -0
- minigpt4/processors/__pycache__/base_processor.cpython-39.pyc +0 -0
- minigpt4/processors/__pycache__/blip_processors.cpython-39.pyc +0 -0
- minigpt4/processors/__pycache__/randaugment.cpython-39.pyc +0 -0
- minigpt4/processors/base_processor.py +26 -0
- minigpt4/processors/blip_processors.py +140 -0
- minigpt4/processors/randaugment.py +398 -0
minigpt4/models/Qformer.py
ADDED
@@ -0,0 +1,1216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
* Copyright (c) 2023, salesforce.com, inc.
|
3 |
+
* All rights reserved.
|
4 |
+
* SPDX-License-Identifier: BSD-3-Clause
|
5 |
+
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
|
6 |
+
* By Junnan Li
|
7 |
+
* Based on huggingface code base
|
8 |
+
* https://github.com/huggingface/transformers/blob/v4.15.0/src/transformers/models/bert
|
9 |
+
"""
|
10 |
+
|
11 |
+
import math
|
12 |
+
import os
|
13 |
+
import warnings
|
14 |
+
from dataclasses import dataclass
|
15 |
+
from typing import Optional, Tuple, Dict, Any
|
16 |
+
|
17 |
+
import torch
|
18 |
+
from torch import Tensor, device, dtype, nn
|
19 |
+
import torch.utils.checkpoint
|
20 |
+
from torch import nn
|
21 |
+
from torch.nn import CrossEntropyLoss
|
22 |
+
import torch.nn.functional as F
|
23 |
+
|
24 |
+
from transformers.activations import ACT2FN
|
25 |
+
from transformers.file_utils import (
|
26 |
+
ModelOutput,
|
27 |
+
)
|
28 |
+
from transformers.modeling_outputs import (
|
29 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
30 |
+
BaseModelOutputWithPoolingAndCrossAttentions,
|
31 |
+
CausalLMOutputWithCrossAttentions,
|
32 |
+
MaskedLMOutput,
|
33 |
+
MultipleChoiceModelOutput,
|
34 |
+
NextSentencePredictorOutput,
|
35 |
+
QuestionAnsweringModelOutput,
|
36 |
+
SequenceClassifierOutput,
|
37 |
+
TokenClassifierOutput,
|
38 |
+
)
|
39 |
+
from transformers.modeling_utils import (
|
40 |
+
PreTrainedModel,
|
41 |
+
apply_chunking_to_forward,
|
42 |
+
find_pruneable_heads_and_indices,
|
43 |
+
prune_linear_layer,
|
44 |
+
)
|
45 |
+
from transformers.utils import logging
|
46 |
+
from transformers.models.bert.configuration_bert import BertConfig
|
47 |
+
|
48 |
+
logger = logging.get_logger(__name__)
|
49 |
+
|
50 |
+
|
51 |
+
class BertEmbeddings(nn.Module):
|
52 |
+
"""Construct the embeddings from word and position embeddings."""
|
53 |
+
|
54 |
+
def __init__(self, config):
|
55 |
+
super().__init__()
|
56 |
+
self.word_embeddings = nn.Embedding(
|
57 |
+
config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id
|
58 |
+
)
|
59 |
+
self.position_embeddings = nn.Embedding(
|
60 |
+
config.max_position_embeddings, config.hidden_size
|
61 |
+
)
|
62 |
+
|
63 |
+
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
|
64 |
+
# any TensorFlow checkpoint file
|
65 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
66 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
67 |
+
|
68 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
69 |
+
self.register_buffer(
|
70 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1))
|
71 |
+
)
|
72 |
+
self.position_embedding_type = getattr(
|
73 |
+
config, "position_embedding_type", "absolute"
|
74 |
+
)
|
75 |
+
|
76 |
+
self.config = config
|
77 |
+
|
78 |
+
def forward(
|
79 |
+
self,
|
80 |
+
input_ids=None,
|
81 |
+
position_ids=None,
|
82 |
+
query_embeds=None,
|
83 |
+
past_key_values_length=0,
|
84 |
+
):
|
85 |
+
if input_ids is not None:
|
86 |
+
seq_length = input_ids.size()[1]
|
87 |
+
else:
|
88 |
+
seq_length = 0
|
89 |
+
|
90 |
+
if position_ids is None:
|
91 |
+
position_ids = self.position_ids[
|
92 |
+
:, past_key_values_length : seq_length + past_key_values_length
|
93 |
+
].clone()
|
94 |
+
|
95 |
+
if input_ids is not None:
|
96 |
+
embeddings = self.word_embeddings(input_ids)
|
97 |
+
if self.position_embedding_type == "absolute":
|
98 |
+
position_embeddings = self.position_embeddings(position_ids)
|
99 |
+
embeddings = embeddings + position_embeddings
|
100 |
+
|
101 |
+
if query_embeds is not None:
|
102 |
+
embeddings = torch.cat((query_embeds, embeddings), dim=1)
|
103 |
+
else:
|
104 |
+
embeddings = query_embeds
|
105 |
+
|
106 |
+
embeddings = self.LayerNorm(embeddings)
|
107 |
+
embeddings = self.dropout(embeddings)
|
108 |
+
return embeddings
|
109 |
+
|
110 |
+
|
111 |
+
class BertSelfAttention(nn.Module):
|
112 |
+
def __init__(self, config, is_cross_attention):
|
113 |
+
super().__init__()
|
114 |
+
self.config = config
|
115 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(
|
116 |
+
config, "embedding_size"
|
117 |
+
):
|
118 |
+
raise ValueError(
|
119 |
+
"The hidden size (%d) is not a multiple of the number of attention "
|
120 |
+
"heads (%d)" % (config.hidden_size, config.num_attention_heads)
|
121 |
+
)
|
122 |
+
|
123 |
+
self.num_attention_heads = config.num_attention_heads
|
124 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
125 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
126 |
+
|
127 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
128 |
+
if is_cross_attention:
|
129 |
+
self.key = nn.Linear(config.encoder_width, self.all_head_size)
|
130 |
+
self.value = nn.Linear(config.encoder_width, self.all_head_size)
|
131 |
+
else:
|
132 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
133 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
134 |
+
|
135 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
136 |
+
self.position_embedding_type = getattr(
|
137 |
+
config, "position_embedding_type", "absolute"
|
138 |
+
)
|
139 |
+
if (
|
140 |
+
self.position_embedding_type == "relative_key"
|
141 |
+
or self.position_embedding_type == "relative_key_query"
|
142 |
+
):
|
143 |
+
self.max_position_embeddings = config.max_position_embeddings
|
144 |
+
self.distance_embedding = nn.Embedding(
|
145 |
+
2 * config.max_position_embeddings - 1, self.attention_head_size
|
146 |
+
)
|
147 |
+
self.save_attention = False
|
148 |
+
|
149 |
+
def save_attn_gradients(self, attn_gradients):
|
150 |
+
self.attn_gradients = attn_gradients
|
151 |
+
|
152 |
+
def get_attn_gradients(self):
|
153 |
+
return self.attn_gradients
|
154 |
+
|
155 |
+
def save_attention_map(self, attention_map):
|
156 |
+
self.attention_map = attention_map
|
157 |
+
|
158 |
+
def get_attention_map(self):
|
159 |
+
return self.attention_map
|
160 |
+
|
161 |
+
def transpose_for_scores(self, x):
|
162 |
+
new_x_shape = x.size()[:-1] + (
|
163 |
+
self.num_attention_heads,
|
164 |
+
self.attention_head_size,
|
165 |
+
)
|
166 |
+
x = x.view(*new_x_shape)
|
167 |
+
return x.permute(0, 2, 1, 3)
|
168 |
+
|
169 |
+
def forward(
|
170 |
+
self,
|
171 |
+
hidden_states,
|
172 |
+
attention_mask=None,
|
173 |
+
head_mask=None,
|
174 |
+
encoder_hidden_states=None,
|
175 |
+
encoder_attention_mask=None,
|
176 |
+
past_key_value=None,
|
177 |
+
output_attentions=False,
|
178 |
+
):
|
179 |
+
|
180 |
+
# If this is instantiated as a cross-attention module, the keys
|
181 |
+
# and values come from an encoder; the attention mask needs to be
|
182 |
+
# such that the encoder's padding tokens are not attended to.
|
183 |
+
is_cross_attention = encoder_hidden_states is not None
|
184 |
+
|
185 |
+
if is_cross_attention:
|
186 |
+
key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
|
187 |
+
value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
|
188 |
+
attention_mask = encoder_attention_mask
|
189 |
+
elif past_key_value is not None:
|
190 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
191 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
192 |
+
key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
|
193 |
+
value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
|
194 |
+
else:
|
195 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
196 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
197 |
+
|
198 |
+
mixed_query_layer = self.query(hidden_states)
|
199 |
+
|
200 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
201 |
+
|
202 |
+
past_key_value = (key_layer, value_layer)
|
203 |
+
|
204 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
205 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
206 |
+
|
207 |
+
if (
|
208 |
+
self.position_embedding_type == "relative_key"
|
209 |
+
or self.position_embedding_type == "relative_key_query"
|
210 |
+
):
|
211 |
+
seq_length = hidden_states.size()[1]
|
212 |
+
position_ids_l = torch.arange(
|
213 |
+
seq_length, dtype=torch.long, device=hidden_states.device
|
214 |
+
).view(-1, 1)
|
215 |
+
position_ids_r = torch.arange(
|
216 |
+
seq_length, dtype=torch.long, device=hidden_states.device
|
217 |
+
).view(1, -1)
|
218 |
+
distance = position_ids_l - position_ids_r
|
219 |
+
positional_embedding = self.distance_embedding(
|
220 |
+
distance + self.max_position_embeddings - 1
|
221 |
+
)
|
222 |
+
positional_embedding = positional_embedding.to(
|
223 |
+
dtype=query_layer.dtype
|
224 |
+
) # fp16 compatibility
|
225 |
+
|
226 |
+
if self.position_embedding_type == "relative_key":
|
227 |
+
relative_position_scores = torch.einsum(
|
228 |
+
"bhld,lrd->bhlr", query_layer, positional_embedding
|
229 |
+
)
|
230 |
+
attention_scores = attention_scores + relative_position_scores
|
231 |
+
elif self.position_embedding_type == "relative_key_query":
|
232 |
+
relative_position_scores_query = torch.einsum(
|
233 |
+
"bhld,lrd->bhlr", query_layer, positional_embedding
|
234 |
+
)
|
235 |
+
relative_position_scores_key = torch.einsum(
|
236 |
+
"bhrd,lrd->bhlr", key_layer, positional_embedding
|
237 |
+
)
|
238 |
+
attention_scores = (
|
239 |
+
attention_scores
|
240 |
+
+ relative_position_scores_query
|
241 |
+
+ relative_position_scores_key
|
242 |
+
)
|
243 |
+
|
244 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
245 |
+
if attention_mask is not None:
|
246 |
+
# Apply the attention mask is (precomputed for all layers in BertModel forward() function)
|
247 |
+
attention_scores = attention_scores + attention_mask
|
248 |
+
|
249 |
+
# Normalize the attention scores to probabilities.
|
250 |
+
attention_probs = nn.Softmax(dim=-1)(attention_scores)
|
251 |
+
|
252 |
+
if is_cross_attention and self.save_attention:
|
253 |
+
self.save_attention_map(attention_probs)
|
254 |
+
attention_probs.register_hook(self.save_attn_gradients)
|
255 |
+
|
256 |
+
# This is actually dropping out entire tokens to attend to, which might
|
257 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
258 |
+
attention_probs_dropped = self.dropout(attention_probs)
|
259 |
+
|
260 |
+
# Mask heads if we want to
|
261 |
+
if head_mask is not None:
|
262 |
+
attention_probs_dropped = attention_probs_dropped * head_mask
|
263 |
+
|
264 |
+
context_layer = torch.matmul(attention_probs_dropped, value_layer)
|
265 |
+
|
266 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
267 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
268 |
+
context_layer = context_layer.view(*new_context_layer_shape)
|
269 |
+
|
270 |
+
outputs = (
|
271 |
+
(context_layer, attention_probs) if output_attentions else (context_layer,)
|
272 |
+
)
|
273 |
+
|
274 |
+
outputs = outputs + (past_key_value,)
|
275 |
+
return outputs
|
276 |
+
|
277 |
+
|
278 |
+
class BertSelfOutput(nn.Module):
|
279 |
+
def __init__(self, config):
|
280 |
+
super().__init__()
|
281 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
282 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
283 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
284 |
+
|
285 |
+
def forward(self, hidden_states, input_tensor):
|
286 |
+
hidden_states = self.dense(hidden_states)
|
287 |
+
hidden_states = self.dropout(hidden_states)
|
288 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
289 |
+
return hidden_states
|
290 |
+
|
291 |
+
|
292 |
+
class BertAttention(nn.Module):
|
293 |
+
def __init__(self, config, is_cross_attention=False):
|
294 |
+
super().__init__()
|
295 |
+
self.self = BertSelfAttention(config, is_cross_attention)
|
296 |
+
self.output = BertSelfOutput(config)
|
297 |
+
self.pruned_heads = set()
|
298 |
+
|
299 |
+
def prune_heads(self, heads):
|
300 |
+
if len(heads) == 0:
|
301 |
+
return
|
302 |
+
heads, index = find_pruneable_heads_and_indices(
|
303 |
+
heads,
|
304 |
+
self.self.num_attention_heads,
|
305 |
+
self.self.attention_head_size,
|
306 |
+
self.pruned_heads,
|
307 |
+
)
|
308 |
+
|
309 |
+
# Prune linear layers
|
310 |
+
self.self.query = prune_linear_layer(self.self.query, index)
|
311 |
+
self.self.key = prune_linear_layer(self.self.key, index)
|
312 |
+
self.self.value = prune_linear_layer(self.self.value, index)
|
313 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
314 |
+
|
315 |
+
# Update hyper params and store pruned heads
|
316 |
+
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
|
317 |
+
self.self.all_head_size = (
|
318 |
+
self.self.attention_head_size * self.self.num_attention_heads
|
319 |
+
)
|
320 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
321 |
+
|
322 |
+
def forward(
|
323 |
+
self,
|
324 |
+
hidden_states,
|
325 |
+
attention_mask=None,
|
326 |
+
head_mask=None,
|
327 |
+
encoder_hidden_states=None,
|
328 |
+
encoder_attention_mask=None,
|
329 |
+
past_key_value=None,
|
330 |
+
output_attentions=False,
|
331 |
+
):
|
332 |
+
self_outputs = self.self(
|
333 |
+
hidden_states,
|
334 |
+
attention_mask,
|
335 |
+
head_mask,
|
336 |
+
encoder_hidden_states,
|
337 |
+
encoder_attention_mask,
|
338 |
+
past_key_value,
|
339 |
+
output_attentions,
|
340 |
+
)
|
341 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
342 |
+
|
343 |
+
outputs = (attention_output,) + self_outputs[
|
344 |
+
1:
|
345 |
+
] # add attentions if we output them
|
346 |
+
return outputs
|
347 |
+
|
348 |
+
|
349 |
+
class BertIntermediate(nn.Module):
|
350 |
+
def __init__(self, config):
|
351 |
+
super().__init__()
|
352 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
353 |
+
if isinstance(config.hidden_act, str):
|
354 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
355 |
+
else:
|
356 |
+
self.intermediate_act_fn = config.hidden_act
|
357 |
+
|
358 |
+
def forward(self, hidden_states):
|
359 |
+
hidden_states = self.dense(hidden_states)
|
360 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
361 |
+
return hidden_states
|
362 |
+
|
363 |
+
|
364 |
+
class BertOutput(nn.Module):
|
365 |
+
def __init__(self, config):
|
366 |
+
super().__init__()
|
367 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
368 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
369 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
370 |
+
|
371 |
+
def forward(self, hidden_states, input_tensor):
|
372 |
+
hidden_states = self.dense(hidden_states)
|
373 |
+
hidden_states = self.dropout(hidden_states)
|
374 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
375 |
+
return hidden_states
|
376 |
+
|
377 |
+
|
378 |
+
class BertLayer(nn.Module):
|
379 |
+
def __init__(self, config, layer_num):
|
380 |
+
super().__init__()
|
381 |
+
self.config = config
|
382 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
383 |
+
self.seq_len_dim = 1
|
384 |
+
self.attention = BertAttention(config)
|
385 |
+
self.layer_num = layer_num
|
386 |
+
if (
|
387 |
+
self.config.add_cross_attention
|
388 |
+
and layer_num % self.config.cross_attention_freq == 0
|
389 |
+
):
|
390 |
+
self.crossattention = BertAttention(
|
391 |
+
config, is_cross_attention=self.config.add_cross_attention
|
392 |
+
)
|
393 |
+
self.has_cross_attention = True
|
394 |
+
else:
|
395 |
+
self.has_cross_attention = False
|
396 |
+
self.intermediate = BertIntermediate(config)
|
397 |
+
self.output = BertOutput(config)
|
398 |
+
|
399 |
+
self.intermediate_query = BertIntermediate(config)
|
400 |
+
self.output_query = BertOutput(config)
|
401 |
+
|
402 |
+
def forward(
|
403 |
+
self,
|
404 |
+
hidden_states,
|
405 |
+
attention_mask=None,
|
406 |
+
head_mask=None,
|
407 |
+
encoder_hidden_states=None,
|
408 |
+
encoder_attention_mask=None,
|
409 |
+
past_key_value=None,
|
410 |
+
output_attentions=False,
|
411 |
+
query_length=0,
|
412 |
+
):
|
413 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
414 |
+
self_attn_past_key_value = (
|
415 |
+
past_key_value[:2] if past_key_value is not None else None
|
416 |
+
)
|
417 |
+
self_attention_outputs = self.attention(
|
418 |
+
hidden_states,
|
419 |
+
attention_mask,
|
420 |
+
head_mask,
|
421 |
+
output_attentions=output_attentions,
|
422 |
+
past_key_value=self_attn_past_key_value,
|
423 |
+
)
|
424 |
+
attention_output = self_attention_outputs[0]
|
425 |
+
outputs = self_attention_outputs[1:-1]
|
426 |
+
|
427 |
+
present_key_value = self_attention_outputs[-1]
|
428 |
+
|
429 |
+
if query_length > 0:
|
430 |
+
query_attention_output = attention_output[:, :query_length, :]
|
431 |
+
|
432 |
+
if self.has_cross_attention:
|
433 |
+
assert (
|
434 |
+
encoder_hidden_states is not None
|
435 |
+
), "encoder_hidden_states must be given for cross-attention layers"
|
436 |
+
cross_attention_outputs = self.crossattention(
|
437 |
+
query_attention_output,
|
438 |
+
attention_mask,
|
439 |
+
head_mask,
|
440 |
+
encoder_hidden_states,
|
441 |
+
encoder_attention_mask,
|
442 |
+
output_attentions=output_attentions,
|
443 |
+
)
|
444 |
+
query_attention_output = cross_attention_outputs[0]
|
445 |
+
outputs = (
|
446 |
+
outputs + cross_attention_outputs[1:-1]
|
447 |
+
) # add cross attentions if we output attention weights
|
448 |
+
|
449 |
+
layer_output = apply_chunking_to_forward(
|
450 |
+
self.feed_forward_chunk_query,
|
451 |
+
self.chunk_size_feed_forward,
|
452 |
+
self.seq_len_dim,
|
453 |
+
query_attention_output,
|
454 |
+
)
|
455 |
+
if attention_output.shape[1] > query_length:
|
456 |
+
layer_output_text = apply_chunking_to_forward(
|
457 |
+
self.feed_forward_chunk,
|
458 |
+
self.chunk_size_feed_forward,
|
459 |
+
self.seq_len_dim,
|
460 |
+
attention_output[:, query_length:, :],
|
461 |
+
)
|
462 |
+
layer_output = torch.cat([layer_output, layer_output_text], dim=1)
|
463 |
+
else:
|
464 |
+
layer_output = apply_chunking_to_forward(
|
465 |
+
self.feed_forward_chunk,
|
466 |
+
self.chunk_size_feed_forward,
|
467 |
+
self.seq_len_dim,
|
468 |
+
attention_output,
|
469 |
+
)
|
470 |
+
outputs = (layer_output,) + outputs
|
471 |
+
|
472 |
+
outputs = outputs + (present_key_value,)
|
473 |
+
|
474 |
+
return outputs
|
475 |
+
|
476 |
+
def feed_forward_chunk(self, attention_output):
|
477 |
+
intermediate_output = self.intermediate(attention_output)
|
478 |
+
layer_output = self.output(intermediate_output, attention_output)
|
479 |
+
return layer_output
|
480 |
+
|
481 |
+
def feed_forward_chunk_query(self, attention_output):
|
482 |
+
intermediate_output = self.intermediate_query(attention_output)
|
483 |
+
layer_output = self.output_query(intermediate_output, attention_output)
|
484 |
+
return layer_output
|
485 |
+
|
486 |
+
|
487 |
+
class BertEncoder(nn.Module):
|
488 |
+
def __init__(self, config):
|
489 |
+
super().__init__()
|
490 |
+
self.config = config
|
491 |
+
self.layer = nn.ModuleList(
|
492 |
+
[BertLayer(config, i) for i in range(config.num_hidden_layers)]
|
493 |
+
)
|
494 |
+
|
495 |
+
def forward(
|
496 |
+
self,
|
497 |
+
hidden_states,
|
498 |
+
attention_mask=None,
|
499 |
+
head_mask=None,
|
500 |
+
encoder_hidden_states=None,
|
501 |
+
encoder_attention_mask=None,
|
502 |
+
past_key_values=None,
|
503 |
+
use_cache=None,
|
504 |
+
output_attentions=False,
|
505 |
+
output_hidden_states=False,
|
506 |
+
return_dict=True,
|
507 |
+
query_length=0,
|
508 |
+
):
|
509 |
+
all_hidden_states = () if output_hidden_states else None
|
510 |
+
all_self_attentions = () if output_attentions else None
|
511 |
+
all_cross_attentions = (
|
512 |
+
() if output_attentions and self.config.add_cross_attention else None
|
513 |
+
)
|
514 |
+
|
515 |
+
next_decoder_cache = () if use_cache else None
|
516 |
+
|
517 |
+
for i in range(self.config.num_hidden_layers):
|
518 |
+
layer_module = self.layer[i]
|
519 |
+
if output_hidden_states:
|
520 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
521 |
+
|
522 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
523 |
+
past_key_value = past_key_values[i] if past_key_values is not None else None
|
524 |
+
|
525 |
+
if getattr(self.config, "gradient_checkpointing", False) and self.training:
|
526 |
+
|
527 |
+
if use_cache:
|
528 |
+
logger.warn(
|
529 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
530 |
+
)
|
531 |
+
use_cache = False
|
532 |
+
|
533 |
+
def create_custom_forward(module):
|
534 |
+
def custom_forward(*inputs):
|
535 |
+
return module(
|
536 |
+
*inputs, past_key_value, output_attentions, query_length
|
537 |
+
)
|
538 |
+
|
539 |
+
return custom_forward
|
540 |
+
|
541 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
542 |
+
create_custom_forward(layer_module),
|
543 |
+
hidden_states,
|
544 |
+
attention_mask,
|
545 |
+
layer_head_mask,
|
546 |
+
encoder_hidden_states,
|
547 |
+
encoder_attention_mask,
|
548 |
+
)
|
549 |
+
else:
|
550 |
+
layer_outputs = layer_module(
|
551 |
+
hidden_states,
|
552 |
+
attention_mask,
|
553 |
+
layer_head_mask,
|
554 |
+
encoder_hidden_states,
|
555 |
+
encoder_attention_mask,
|
556 |
+
past_key_value,
|
557 |
+
output_attentions,
|
558 |
+
query_length,
|
559 |
+
)
|
560 |
+
|
561 |
+
hidden_states = layer_outputs[0]
|
562 |
+
if use_cache:
|
563 |
+
next_decoder_cache += (layer_outputs[-1],)
|
564 |
+
if output_attentions:
|
565 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
566 |
+
all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
|
567 |
+
|
568 |
+
if output_hidden_states:
|
569 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
570 |
+
|
571 |
+
if not return_dict:
|
572 |
+
return tuple(
|
573 |
+
v
|
574 |
+
for v in [
|
575 |
+
hidden_states,
|
576 |
+
next_decoder_cache,
|
577 |
+
all_hidden_states,
|
578 |
+
all_self_attentions,
|
579 |
+
all_cross_attentions,
|
580 |
+
]
|
581 |
+
if v is not None
|
582 |
+
)
|
583 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
584 |
+
last_hidden_state=hidden_states,
|
585 |
+
past_key_values=next_decoder_cache,
|
586 |
+
hidden_states=all_hidden_states,
|
587 |
+
attentions=all_self_attentions,
|
588 |
+
cross_attentions=all_cross_attentions,
|
589 |
+
)
|
590 |
+
|
591 |
+
|
592 |
+
class BertPooler(nn.Module):
|
593 |
+
def __init__(self, config):
|
594 |
+
super().__init__()
|
595 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
596 |
+
self.activation = nn.Tanh()
|
597 |
+
|
598 |
+
def forward(self, hidden_states):
|
599 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
600 |
+
# to the first token.
|
601 |
+
first_token_tensor = hidden_states[:, 0]
|
602 |
+
pooled_output = self.dense(first_token_tensor)
|
603 |
+
pooled_output = self.activation(pooled_output)
|
604 |
+
return pooled_output
|
605 |
+
|
606 |
+
|
607 |
+
class BertPredictionHeadTransform(nn.Module):
|
608 |
+
def __init__(self, config):
|
609 |
+
super().__init__()
|
610 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
611 |
+
if isinstance(config.hidden_act, str):
|
612 |
+
self.transform_act_fn = ACT2FN[config.hidden_act]
|
613 |
+
else:
|
614 |
+
self.transform_act_fn = config.hidden_act
|
615 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
616 |
+
|
617 |
+
def forward(self, hidden_states):
|
618 |
+
hidden_states = self.dense(hidden_states)
|
619 |
+
hidden_states = self.transform_act_fn(hidden_states)
|
620 |
+
hidden_states = self.LayerNorm(hidden_states)
|
621 |
+
return hidden_states
|
622 |
+
|
623 |
+
|
624 |
+
class BertLMPredictionHead(nn.Module):
|
625 |
+
def __init__(self, config):
|
626 |
+
super().__init__()
|
627 |
+
self.transform = BertPredictionHeadTransform(config)
|
628 |
+
|
629 |
+
# The output weights are the same as the input embeddings, but there is
|
630 |
+
# an output-only bias for each token.
|
631 |
+
self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
632 |
+
|
633 |
+
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
|
634 |
+
|
635 |
+
# Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
|
636 |
+
self.decoder.bias = self.bias
|
637 |
+
|
638 |
+
def forward(self, hidden_states):
|
639 |
+
hidden_states = self.transform(hidden_states)
|
640 |
+
hidden_states = self.decoder(hidden_states)
|
641 |
+
return hidden_states
|
642 |
+
|
643 |
+
|
644 |
+
class BertOnlyMLMHead(nn.Module):
|
645 |
+
def __init__(self, config):
|
646 |
+
super().__init__()
|
647 |
+
self.predictions = BertLMPredictionHead(config)
|
648 |
+
|
649 |
+
def forward(self, sequence_output):
|
650 |
+
prediction_scores = self.predictions(sequence_output)
|
651 |
+
return prediction_scores
|
652 |
+
|
653 |
+
|
654 |
+
class BertPreTrainedModel(PreTrainedModel):
|
655 |
+
"""
|
656 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
657 |
+
models.
|
658 |
+
"""
|
659 |
+
|
660 |
+
config_class = BertConfig
|
661 |
+
base_model_prefix = "bert"
|
662 |
+
_keys_to_ignore_on_load_missing = [r"position_ids"]
|
663 |
+
|
664 |
+
def _init_weights(self, module):
|
665 |
+
"""Initialize the weights"""
|
666 |
+
if isinstance(module, (nn.Linear, nn.Embedding)):
|
667 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
668 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
669 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
670 |
+
elif isinstance(module, nn.LayerNorm):
|
671 |
+
module.bias.data.zero_()
|
672 |
+
module.weight.data.fill_(1.0)
|
673 |
+
if isinstance(module, nn.Linear) and module.bias is not None:
|
674 |
+
module.bias.data.zero_()
|
675 |
+
|
676 |
+
|
677 |
+
class BertModel(BertPreTrainedModel):
|
678 |
+
"""
|
679 |
+
The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
|
680 |
+
cross-attention is added between the self-attention layers, following the architecture described in `Attention is
|
681 |
+
all you need <https://arxiv.org/abs/1706.03762>`__ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
|
682 |
+
Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
|
683 |
+
argument and :obj:`add_cross_attention` set to :obj:`True`; an :obj:`encoder_hidden_states` is then expected as an
|
684 |
+
input to the forward pass.
|
685 |
+
"""
|
686 |
+
|
687 |
+
def __init__(self, config, add_pooling_layer=False):
|
688 |
+
super().__init__(config)
|
689 |
+
self.config = config
|
690 |
+
|
691 |
+
self.embeddings = BertEmbeddings(config)
|
692 |
+
|
693 |
+
self.encoder = BertEncoder(config)
|
694 |
+
|
695 |
+
self.pooler = BertPooler(config) if add_pooling_layer else None
|
696 |
+
|
697 |
+
self.init_weights()
|
698 |
+
|
699 |
+
def get_input_embeddings(self):
|
700 |
+
return self.embeddings.word_embeddings
|
701 |
+
|
702 |
+
def set_input_embeddings(self, value):
|
703 |
+
self.embeddings.word_embeddings = value
|
704 |
+
|
705 |
+
def _prune_heads(self, heads_to_prune):
|
706 |
+
"""
|
707 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
708 |
+
class PreTrainedModel
|
709 |
+
"""
|
710 |
+
for layer, heads in heads_to_prune.items():
|
711 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
712 |
+
|
713 |
+
def get_extended_attention_mask(
|
714 |
+
self,
|
715 |
+
attention_mask: Tensor,
|
716 |
+
input_shape: Tuple[int],
|
717 |
+
device: device,
|
718 |
+
is_decoder: bool,
|
719 |
+
has_query: bool = False,
|
720 |
+
) -> Tensor:
|
721 |
+
"""
|
722 |
+
Makes broadcastable attention and causal masks so that future and masked tokens are ignored.
|
723 |
+
|
724 |
+
Arguments:
|
725 |
+
attention_mask (:obj:`torch.Tensor`):
|
726 |
+
Mask with ones indicating tokens to attend to, zeros for tokens to ignore.
|
727 |
+
input_shape (:obj:`Tuple[int]`):
|
728 |
+
The shape of the input to the model.
|
729 |
+
device: (:obj:`torch.device`):
|
730 |
+
The device of the input to the model.
|
731 |
+
|
732 |
+
Returns:
|
733 |
+
:obj:`torch.Tensor` The extended attention mask, with a the same dtype as :obj:`attention_mask.dtype`.
|
734 |
+
"""
|
735 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
736 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
737 |
+
if attention_mask.dim() == 3:
|
738 |
+
extended_attention_mask = attention_mask[:, None, :, :]
|
739 |
+
elif attention_mask.dim() == 2:
|
740 |
+
# Provided a padding mask of dimensions [batch_size, seq_length]
|
741 |
+
# - if the model is a decoder, apply a causal mask in addition to the padding mask
|
742 |
+
# - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
743 |
+
if is_decoder:
|
744 |
+
batch_size, seq_length = input_shape
|
745 |
+
|
746 |
+
seq_ids = torch.arange(seq_length, device=device)
|
747 |
+
causal_mask = (
|
748 |
+
seq_ids[None, None, :].repeat(batch_size, seq_length, 1)
|
749 |
+
<= seq_ids[None, :, None]
|
750 |
+
)
|
751 |
+
|
752 |
+
# add a prefix ones mask to the causal mask
|
753 |
+
# causal and attention masks must have same type with pytorch version < 1.3
|
754 |
+
causal_mask = causal_mask.to(attention_mask.dtype)
|
755 |
+
|
756 |
+
if causal_mask.shape[1] < attention_mask.shape[1]:
|
757 |
+
prefix_seq_len = attention_mask.shape[1] - causal_mask.shape[1]
|
758 |
+
if has_query: # UniLM style attention mask
|
759 |
+
causal_mask = torch.cat(
|
760 |
+
[
|
761 |
+
torch.zeros(
|
762 |
+
(batch_size, prefix_seq_len, seq_length),
|
763 |
+
device=device,
|
764 |
+
dtype=causal_mask.dtype,
|
765 |
+
),
|
766 |
+
causal_mask,
|
767 |
+
],
|
768 |
+
axis=1,
|
769 |
+
)
|
770 |
+
causal_mask = torch.cat(
|
771 |
+
[
|
772 |
+
torch.ones(
|
773 |
+
(batch_size, causal_mask.shape[1], prefix_seq_len),
|
774 |
+
device=device,
|
775 |
+
dtype=causal_mask.dtype,
|
776 |
+
),
|
777 |
+
causal_mask,
|
778 |
+
],
|
779 |
+
axis=-1,
|
780 |
+
)
|
781 |
+
extended_attention_mask = (
|
782 |
+
causal_mask[:, None, :, :] * attention_mask[:, None, None, :]
|
783 |
+
)
|
784 |
+
else:
|
785 |
+
extended_attention_mask = attention_mask[:, None, None, :]
|
786 |
+
else:
|
787 |
+
raise ValueError(
|
788 |
+
"Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format(
|
789 |
+
input_shape, attention_mask.shape
|
790 |
+
)
|
791 |
+
)
|
792 |
+
|
793 |
+
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
|
794 |
+
# masked positions, this operation will create a tensor which is 0.0 for
|
795 |
+
# positions we want to attend and -10000.0 for masked positions.
|
796 |
+
# Since we are adding it to the raw scores before the softmax, this is
|
797 |
+
# effectively the same as removing these entirely.
|
798 |
+
extended_attention_mask = extended_attention_mask.to(
|
799 |
+
dtype=self.dtype
|
800 |
+
) # fp16 compatibility
|
801 |
+
extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
|
802 |
+
return extended_attention_mask
|
803 |
+
|
804 |
+
def forward(
|
805 |
+
self,
|
806 |
+
input_ids=None,
|
807 |
+
attention_mask=None,
|
808 |
+
position_ids=None,
|
809 |
+
head_mask=None,
|
810 |
+
query_embeds=None,
|
811 |
+
encoder_hidden_states=None,
|
812 |
+
encoder_attention_mask=None,
|
813 |
+
past_key_values=None,
|
814 |
+
use_cache=None,
|
815 |
+
output_attentions=None,
|
816 |
+
output_hidden_states=None,
|
817 |
+
return_dict=None,
|
818 |
+
is_decoder=False,
|
819 |
+
):
|
820 |
+
r"""
|
821 |
+
encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
|
822 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
823 |
+
the model is configured as a decoder.
|
824 |
+
encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
|
825 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
826 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
|
827 |
+
- 1 for tokens that are **not masked**,
|
828 |
+
- 0 for tokens that are **masked**.
|
829 |
+
past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
|
830 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
831 |
+
If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
|
832 |
+
(those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
|
833 |
+
instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
|
834 |
+
use_cache (:obj:`bool`, `optional`):
|
835 |
+
If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
|
836 |
+
decoding (see :obj:`past_key_values`).
|
837 |
+
"""
|
838 |
+
output_attentions = (
|
839 |
+
output_attentions
|
840 |
+
if output_attentions is not None
|
841 |
+
else self.config.output_attentions
|
842 |
+
)
|
843 |
+
output_hidden_states = (
|
844 |
+
output_hidden_states
|
845 |
+
if output_hidden_states is not None
|
846 |
+
else self.config.output_hidden_states
|
847 |
+
)
|
848 |
+
return_dict = (
|
849 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
850 |
+
)
|
851 |
+
|
852 |
+
# use_cache = use_cache if use_cache is not None else self.config.use_cache
|
853 |
+
|
854 |
+
if input_ids is None:
|
855 |
+
assert (
|
856 |
+
query_embeds is not None
|
857 |
+
), "You have to specify query_embeds when input_ids is None"
|
858 |
+
|
859 |
+
# past_key_values_length
|
860 |
+
past_key_values_length = (
|
861 |
+
past_key_values[0][0].shape[2] - self.config.query_length
|
862 |
+
if past_key_values is not None
|
863 |
+
else 0
|
864 |
+
)
|
865 |
+
|
866 |
+
query_length = query_embeds.shape[1] if query_embeds is not None else 0
|
867 |
+
|
868 |
+
embedding_output = self.embeddings(
|
869 |
+
input_ids=input_ids,
|
870 |
+
position_ids=position_ids,
|
871 |
+
query_embeds=query_embeds,
|
872 |
+
past_key_values_length=past_key_values_length,
|
873 |
+
)
|
874 |
+
|
875 |
+
input_shape = embedding_output.size()[:-1]
|
876 |
+
batch_size, seq_length = input_shape
|
877 |
+
device = embedding_output.device
|
878 |
+
|
879 |
+
if attention_mask is None:
|
880 |
+
attention_mask = torch.ones(
|
881 |
+
((batch_size, seq_length + past_key_values_length)), device=device
|
882 |
+
)
|
883 |
+
|
884 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
885 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
886 |
+
if is_decoder:
|
887 |
+
extended_attention_mask = self.get_extended_attention_mask(
|
888 |
+
attention_mask,
|
889 |
+
input_ids.shape,
|
890 |
+
device,
|
891 |
+
is_decoder,
|
892 |
+
has_query=(query_embeds is not None),
|
893 |
+
)
|
894 |
+
else:
|
895 |
+
extended_attention_mask = self.get_extended_attention_mask(
|
896 |
+
attention_mask, input_shape, device, is_decoder
|
897 |
+
)
|
898 |
+
|
899 |
+
# If a 2D or 3D attention mask is provided for the cross-attention
|
900 |
+
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
901 |
+
if encoder_hidden_states is not None:
|
902 |
+
if type(encoder_hidden_states) == list:
|
903 |
+
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[
|
904 |
+
0
|
905 |
+
].size()
|
906 |
+
else:
|
907 |
+
(
|
908 |
+
encoder_batch_size,
|
909 |
+
encoder_sequence_length,
|
910 |
+
_,
|
911 |
+
) = encoder_hidden_states.size()
|
912 |
+
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
|
913 |
+
|
914 |
+
if type(encoder_attention_mask) == list:
|
915 |
+
encoder_extended_attention_mask = [
|
916 |
+
self.invert_attention_mask(mask) for mask in encoder_attention_mask
|
917 |
+
]
|
918 |
+
elif encoder_attention_mask is None:
|
919 |
+
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
|
920 |
+
encoder_extended_attention_mask = self.invert_attention_mask(
|
921 |
+
encoder_attention_mask
|
922 |
+
)
|
923 |
+
else:
|
924 |
+
encoder_extended_attention_mask = self.invert_attention_mask(
|
925 |
+
encoder_attention_mask
|
926 |
+
)
|
927 |
+
else:
|
928 |
+
encoder_extended_attention_mask = None
|
929 |
+
|
930 |
+
# Prepare head mask if needed
|
931 |
+
# 1.0 in head_mask indicate we keep the head
|
932 |
+
# attention_probs has shape bsz x n_heads x N x N
|
933 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
934 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
935 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
936 |
+
|
937 |
+
encoder_outputs = self.encoder(
|
938 |
+
embedding_output,
|
939 |
+
attention_mask=extended_attention_mask,
|
940 |
+
head_mask=head_mask,
|
941 |
+
encoder_hidden_states=encoder_hidden_states,
|
942 |
+
encoder_attention_mask=encoder_extended_attention_mask,
|
943 |
+
past_key_values=past_key_values,
|
944 |
+
use_cache=use_cache,
|
945 |
+
output_attentions=output_attentions,
|
946 |
+
output_hidden_states=output_hidden_states,
|
947 |
+
return_dict=return_dict,
|
948 |
+
query_length=query_length,
|
949 |
+
)
|
950 |
+
sequence_output = encoder_outputs[0]
|
951 |
+
pooled_output = (
|
952 |
+
self.pooler(sequence_output) if self.pooler is not None else None
|
953 |
+
)
|
954 |
+
|
955 |
+
if not return_dict:
|
956 |
+
return (sequence_output, pooled_output) + encoder_outputs[1:]
|
957 |
+
|
958 |
+
return BaseModelOutputWithPoolingAndCrossAttentions(
|
959 |
+
last_hidden_state=sequence_output,
|
960 |
+
pooler_output=pooled_output,
|
961 |
+
past_key_values=encoder_outputs.past_key_values,
|
962 |
+
hidden_states=encoder_outputs.hidden_states,
|
963 |
+
attentions=encoder_outputs.attentions,
|
964 |
+
cross_attentions=encoder_outputs.cross_attentions,
|
965 |
+
)
|
966 |
+
|
967 |
+
|
968 |
+
class BertLMHeadModel(BertPreTrainedModel):
|
969 |
+
|
970 |
+
_keys_to_ignore_on_load_unexpected = [r"pooler"]
|
971 |
+
_keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
|
972 |
+
|
973 |
+
def __init__(self, config):
|
974 |
+
super().__init__(config)
|
975 |
+
|
976 |
+
self.bert = BertModel(config, add_pooling_layer=False)
|
977 |
+
self.cls = BertOnlyMLMHead(config)
|
978 |
+
|
979 |
+
self.init_weights()
|
980 |
+
|
981 |
+
def get_output_embeddings(self):
|
982 |
+
return self.cls.predictions.decoder
|
983 |
+
|
984 |
+
def set_output_embeddings(self, new_embeddings):
|
985 |
+
self.cls.predictions.decoder = new_embeddings
|
986 |
+
|
987 |
+
def forward(
|
988 |
+
self,
|
989 |
+
input_ids=None,
|
990 |
+
attention_mask=None,
|
991 |
+
position_ids=None,
|
992 |
+
head_mask=None,
|
993 |
+
query_embeds=None,
|
994 |
+
encoder_hidden_states=None,
|
995 |
+
encoder_attention_mask=None,
|
996 |
+
labels=None,
|
997 |
+
past_key_values=None,
|
998 |
+
use_cache=True,
|
999 |
+
output_attentions=None,
|
1000 |
+
output_hidden_states=None,
|
1001 |
+
return_dict=None,
|
1002 |
+
return_logits=False,
|
1003 |
+
is_decoder=True,
|
1004 |
+
reduction="mean",
|
1005 |
+
):
|
1006 |
+
r"""
|
1007 |
+
encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
|
1008 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
1009 |
+
the model is configured as a decoder.
|
1010 |
+
encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
|
1011 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
1012 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
|
1013 |
+
- 1 for tokens that are **not masked**,
|
1014 |
+
- 0 for tokens that are **masked**.
|
1015 |
+
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
|
1016 |
+
Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
|
1017 |
+
``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are
|
1018 |
+
ignored (masked), the loss is only computed for the tokens with labels n ``[0, ..., config.vocab_size]``
|
1019 |
+
past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
|
1020 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
1021 |
+
If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
|
1022 |
+
(those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
|
1023 |
+
instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
|
1024 |
+
use_cache (:obj:`bool`, `optional`):
|
1025 |
+
If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
|
1026 |
+
decoding (see :obj:`past_key_values`).
|
1027 |
+
Returns:
|
1028 |
+
Example::
|
1029 |
+
>>> from transformers import BertTokenizer, BertLMHeadModel, BertConfig
|
1030 |
+
>>> import torch
|
1031 |
+
>>> tokenizer = BertTokenizer.from_pretrained('bert-base-cased')
|
1032 |
+
>>> config = BertConfig.from_pretrained("bert-base-cased")
|
1033 |
+
>>> model = BertLMHeadModel.from_pretrained('bert-base-cased', config=config)
|
1034 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
|
1035 |
+
>>> outputs = model(**inputs)
|
1036 |
+
>>> prediction_logits = outputs.logits
|
1037 |
+
"""
|
1038 |
+
return_dict = (
|
1039 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
1040 |
+
)
|
1041 |
+
if labels is not None:
|
1042 |
+
use_cache = False
|
1043 |
+
if past_key_values is not None:
|
1044 |
+
query_embeds = None
|
1045 |
+
|
1046 |
+
outputs = self.bert(
|
1047 |
+
input_ids,
|
1048 |
+
attention_mask=attention_mask,
|
1049 |
+
position_ids=position_ids,
|
1050 |
+
head_mask=head_mask,
|
1051 |
+
query_embeds=query_embeds,
|
1052 |
+
encoder_hidden_states=encoder_hidden_states,
|
1053 |
+
encoder_attention_mask=encoder_attention_mask,
|
1054 |
+
past_key_values=past_key_values,
|
1055 |
+
use_cache=use_cache,
|
1056 |
+
output_attentions=output_attentions,
|
1057 |
+
output_hidden_states=output_hidden_states,
|
1058 |
+
return_dict=return_dict,
|
1059 |
+
is_decoder=is_decoder,
|
1060 |
+
)
|
1061 |
+
|
1062 |
+
sequence_output = outputs[0]
|
1063 |
+
if query_embeds is not None:
|
1064 |
+
sequence_output = outputs[0][:, query_embeds.shape[1] :, :]
|
1065 |
+
|
1066 |
+
prediction_scores = self.cls(sequence_output)
|
1067 |
+
|
1068 |
+
if return_logits:
|
1069 |
+
return prediction_scores[:, :-1, :].contiguous()
|
1070 |
+
|
1071 |
+
lm_loss = None
|
1072 |
+
if labels is not None:
|
1073 |
+
# we are doing next-token prediction; shift prediction scores and input ids by one
|
1074 |
+
shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
|
1075 |
+
labels = labels[:, 1:].contiguous()
|
1076 |
+
loss_fct = CrossEntropyLoss(reduction=reduction, label_smoothing=0.1)
|
1077 |
+
lm_loss = loss_fct(
|
1078 |
+
shifted_prediction_scores.view(-1, self.config.vocab_size),
|
1079 |
+
labels.view(-1),
|
1080 |
+
)
|
1081 |
+
if reduction == "none":
|
1082 |
+
lm_loss = lm_loss.view(prediction_scores.size(0), -1).sum(1)
|
1083 |
+
|
1084 |
+
if not return_dict:
|
1085 |
+
output = (prediction_scores,) + outputs[2:]
|
1086 |
+
return ((lm_loss,) + output) if lm_loss is not None else output
|
1087 |
+
|
1088 |
+
return CausalLMOutputWithCrossAttentions(
|
1089 |
+
loss=lm_loss,
|
1090 |
+
logits=prediction_scores,
|
1091 |
+
past_key_values=outputs.past_key_values,
|
1092 |
+
hidden_states=outputs.hidden_states,
|
1093 |
+
attentions=outputs.attentions,
|
1094 |
+
cross_attentions=outputs.cross_attentions,
|
1095 |
+
)
|
1096 |
+
|
1097 |
+
def prepare_inputs_for_generation(
|
1098 |
+
self, input_ids, query_embeds, past=None, attention_mask=None, **model_kwargs
|
1099 |
+
):
|
1100 |
+
# if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
|
1101 |
+
if attention_mask is None:
|
1102 |
+
attention_mask = input_ids.new_ones(input_ids.shape)
|
1103 |
+
query_mask = input_ids.new_ones(query_embeds.shape[:-1])
|
1104 |
+
attention_mask = torch.cat([query_mask, attention_mask], dim=-1)
|
1105 |
+
|
1106 |
+
# cut decoder_input_ids if past is used
|
1107 |
+
if past is not None:
|
1108 |
+
input_ids = input_ids[:, -1:]
|
1109 |
+
|
1110 |
+
return {
|
1111 |
+
"input_ids": input_ids,
|
1112 |
+
"query_embeds": query_embeds,
|
1113 |
+
"attention_mask": attention_mask,
|
1114 |
+
"past_key_values": past,
|
1115 |
+
"encoder_hidden_states": model_kwargs.get("encoder_hidden_states", None),
|
1116 |
+
"encoder_attention_mask": model_kwargs.get("encoder_attention_mask", None),
|
1117 |
+
"is_decoder": True,
|
1118 |
+
}
|
1119 |
+
|
1120 |
+
def _reorder_cache(self, past, beam_idx):
|
1121 |
+
reordered_past = ()
|
1122 |
+
for layer_past in past:
|
1123 |
+
reordered_past += (
|
1124 |
+
tuple(
|
1125 |
+
past_state.index_select(0, beam_idx) for past_state in layer_past
|
1126 |
+
),
|
1127 |
+
)
|
1128 |
+
return reordered_past
|
1129 |
+
|
1130 |
+
|
1131 |
+
class BertForMaskedLM(BertPreTrainedModel):
|
1132 |
+
|
1133 |
+
_keys_to_ignore_on_load_unexpected = [r"pooler"]
|
1134 |
+
_keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
|
1135 |
+
|
1136 |
+
def __init__(self, config):
|
1137 |
+
super().__init__(config)
|
1138 |
+
|
1139 |
+
self.bert = BertModel(config, add_pooling_layer=False)
|
1140 |
+
self.cls = BertOnlyMLMHead(config)
|
1141 |
+
|
1142 |
+
self.init_weights()
|
1143 |
+
|
1144 |
+
def get_output_embeddings(self):
|
1145 |
+
return self.cls.predictions.decoder
|
1146 |
+
|
1147 |
+
def set_output_embeddings(self, new_embeddings):
|
1148 |
+
self.cls.predictions.decoder = new_embeddings
|
1149 |
+
|
1150 |
+
def forward(
|
1151 |
+
self,
|
1152 |
+
input_ids=None,
|
1153 |
+
attention_mask=None,
|
1154 |
+
position_ids=None,
|
1155 |
+
head_mask=None,
|
1156 |
+
query_embeds=None,
|
1157 |
+
encoder_hidden_states=None,
|
1158 |
+
encoder_attention_mask=None,
|
1159 |
+
labels=None,
|
1160 |
+
output_attentions=None,
|
1161 |
+
output_hidden_states=None,
|
1162 |
+
return_dict=None,
|
1163 |
+
return_logits=False,
|
1164 |
+
is_decoder=False,
|
1165 |
+
):
|
1166 |
+
r"""
|
1167 |
+
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
|
1168 |
+
Labels for computing the masked language modeling loss. Indices should be in ``[-100, 0, ...,
|
1169 |
+
config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are ignored
|
1170 |
+
(masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]``
|
1171 |
+
"""
|
1172 |
+
|
1173 |
+
return_dict = (
|
1174 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
1175 |
+
)
|
1176 |
+
|
1177 |
+
outputs = self.bert(
|
1178 |
+
input_ids,
|
1179 |
+
attention_mask=attention_mask,
|
1180 |
+
position_ids=position_ids,
|
1181 |
+
head_mask=head_mask,
|
1182 |
+
query_embeds=query_embeds,
|
1183 |
+
encoder_hidden_states=encoder_hidden_states,
|
1184 |
+
encoder_attention_mask=encoder_attention_mask,
|
1185 |
+
output_attentions=output_attentions,
|
1186 |
+
output_hidden_states=output_hidden_states,
|
1187 |
+
return_dict=return_dict,
|
1188 |
+
is_decoder=is_decoder,
|
1189 |
+
)
|
1190 |
+
|
1191 |
+
if query_embeds is not None:
|
1192 |
+
sequence_output = outputs[0][:, query_embeds.shape[1] :, :]
|
1193 |
+
prediction_scores = self.cls(sequence_output)
|
1194 |
+
|
1195 |
+
if return_logits:
|
1196 |
+
return prediction_scores
|
1197 |
+
|
1198 |
+
masked_lm_loss = None
|
1199 |
+
if labels is not None:
|
1200 |
+
loss_fct = CrossEntropyLoss() # -100 index = padding token
|
1201 |
+
masked_lm_loss = loss_fct(
|
1202 |
+
prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)
|
1203 |
+
)
|
1204 |
+
|
1205 |
+
if not return_dict:
|
1206 |
+
output = (prediction_scores,) + outputs[2:]
|
1207 |
+
return (
|
1208 |
+
((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
1209 |
+
)
|
1210 |
+
|
1211 |
+
return MaskedLMOutput(
|
1212 |
+
loss=masked_lm_loss,
|
1213 |
+
logits=prediction_scores,
|
1214 |
+
hidden_states=outputs.hidden_states,
|
1215 |
+
attentions=outputs.attentions,
|
1216 |
+
)
|
minigpt4/models/__init__.py
ADDED
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Copyright (c) 2022, salesforce.com, inc.
|
3 |
+
All rights reserved.
|
4 |
+
SPDX-License-Identifier: BSD-3-Clause
|
5 |
+
For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause
|
6 |
+
"""
|
7 |
+
|
8 |
+
import logging
|
9 |
+
import torch
|
10 |
+
from omegaconf import OmegaConf
|
11 |
+
|
12 |
+
from minigpt4.common.registry import registry
|
13 |
+
from minigpt4.models.base_model import BaseModel
|
14 |
+
from minigpt4.models.minigpt_base import MiniGPTBase
|
15 |
+
from minigpt4.models.minigpt4 import MiniGPT4
|
16 |
+
from minigpt4.models.minigpt_v2 import MiniGPTv2
|
17 |
+
from minigpt4.processors.base_processor import BaseProcessor
|
18 |
+
|
19 |
+
|
20 |
+
__all__ = [
|
21 |
+
"load_model",
|
22 |
+
"BaseModel",
|
23 |
+
"MiniGPTBase",
|
24 |
+
"MiniGPT4",
|
25 |
+
"MiniGPTv2"
|
26 |
+
]
|
27 |
+
|
28 |
+
|
29 |
+
def load_model(name, model_type, is_eval=False, device="cpu", checkpoint=None):
|
30 |
+
"""
|
31 |
+
Load supported models.
|
32 |
+
|
33 |
+
To list all available models and types in registry:
|
34 |
+
>>> from minigpt4.models import model_zoo
|
35 |
+
>>> print(model_zoo)
|
36 |
+
|
37 |
+
Args:
|
38 |
+
name (str): name of the model.
|
39 |
+
model_type (str): type of the model.
|
40 |
+
is_eval (bool): whether the model is in eval mode. Default: False.
|
41 |
+
device (str): device to use. Default: "cpu".
|
42 |
+
checkpoint (str): path or to checkpoint. Default: None.
|
43 |
+
Note that expecting the checkpoint to have the same keys in state_dict as the model.
|
44 |
+
|
45 |
+
Returns:
|
46 |
+
model (torch.nn.Module): model.
|
47 |
+
"""
|
48 |
+
|
49 |
+
model = registry.get_model_class(name).from_pretrained(model_type=model_type)
|
50 |
+
|
51 |
+
if checkpoint is not None:
|
52 |
+
model.load_checkpoint(checkpoint)
|
53 |
+
|
54 |
+
if is_eval:
|
55 |
+
model.eval()
|
56 |
+
|
57 |
+
if device == "cpu":
|
58 |
+
model = model.float()
|
59 |
+
|
60 |
+
return model.to(device)
|
61 |
+
|
62 |
+
|
63 |
+
def load_preprocess(config):
|
64 |
+
"""
|
65 |
+
Load preprocessor configs and construct preprocessors.
|
66 |
+
|
67 |
+
If no preprocessor is specified, return BaseProcessor, which does not do any preprocessing.
|
68 |
+
|
69 |
+
Args:
|
70 |
+
config (dict): preprocessor configs.
|
71 |
+
|
72 |
+
Returns:
|
73 |
+
vis_processors (dict): preprocessors for visual inputs.
|
74 |
+
txt_processors (dict): preprocessors for text inputs.
|
75 |
+
|
76 |
+
Key is "train" or "eval" for processors used in training and evaluation respectively.
|
77 |
+
"""
|
78 |
+
|
79 |
+
def _build_proc_from_cfg(cfg):
|
80 |
+
return (
|
81 |
+
registry.get_processor_class(cfg.name).from_config(cfg)
|
82 |
+
if cfg is not None
|
83 |
+
else BaseProcessor()
|
84 |
+
)
|
85 |
+
|
86 |
+
vis_processors = dict()
|
87 |
+
txt_processors = dict()
|
88 |
+
|
89 |
+
vis_proc_cfg = config.get("vis_processor")
|
90 |
+
txt_proc_cfg = config.get("text_processor")
|
91 |
+
|
92 |
+
if vis_proc_cfg is not None:
|
93 |
+
vis_train_cfg = vis_proc_cfg.get("train")
|
94 |
+
vis_eval_cfg = vis_proc_cfg.get("eval")
|
95 |
+
else:
|
96 |
+
vis_train_cfg = None
|
97 |
+
vis_eval_cfg = None
|
98 |
+
|
99 |
+
vis_processors["train"] = _build_proc_from_cfg(vis_train_cfg)
|
100 |
+
vis_processors["eval"] = _build_proc_from_cfg(vis_eval_cfg)
|
101 |
+
|
102 |
+
if txt_proc_cfg is not None:
|
103 |
+
txt_train_cfg = txt_proc_cfg.get("train")
|
104 |
+
txt_eval_cfg = txt_proc_cfg.get("eval")
|
105 |
+
else:
|
106 |
+
txt_train_cfg = None
|
107 |
+
txt_eval_cfg = None
|
108 |
+
|
109 |
+
txt_processors["train"] = _build_proc_from_cfg(txt_train_cfg)
|
110 |
+
txt_processors["eval"] = _build_proc_from_cfg(txt_eval_cfg)
|
111 |
+
|
112 |
+
return vis_processors, txt_processors
|
113 |
+
|
114 |
+
|
115 |
+
def load_model_and_preprocess(name, model_type, is_eval=False, device="cpu"):
|
116 |
+
"""
|
117 |
+
Load model and its related preprocessors.
|
118 |
+
|
119 |
+
List all available models and types in registry:
|
120 |
+
>>> from minigpt4.models import model_zoo
|
121 |
+
>>> print(model_zoo)
|
122 |
+
|
123 |
+
Args:
|
124 |
+
name (str): name of the model.
|
125 |
+
model_type (str): type of the model.
|
126 |
+
is_eval (bool): whether the model is in eval mode. Default: False.
|
127 |
+
device (str): device to use. Default: "cpu".
|
128 |
+
|
129 |
+
Returns:
|
130 |
+
model (torch.nn.Module): model.
|
131 |
+
vis_processors (dict): preprocessors for visual inputs.
|
132 |
+
txt_processors (dict): preprocessors for text inputs.
|
133 |
+
"""
|
134 |
+
model_cls = registry.get_model_class(name)
|
135 |
+
|
136 |
+
# load model
|
137 |
+
model = model_cls.from_pretrained(model_type=model_type)
|
138 |
+
|
139 |
+
if is_eval:
|
140 |
+
model.eval()
|
141 |
+
|
142 |
+
# load preprocess
|
143 |
+
cfg = OmegaConf.load(model_cls.default_config_path(model_type))
|
144 |
+
if cfg is not None:
|
145 |
+
preprocess_cfg = cfg.preprocess
|
146 |
+
|
147 |
+
vis_processors, txt_processors = load_preprocess(preprocess_cfg)
|
148 |
+
else:
|
149 |
+
vis_processors, txt_processors = None, None
|
150 |
+
logging.info(
|
151 |
+
f"""No default preprocess for model {name} ({model_type}).
|
152 |
+
This can happen if the model is not finetuned on downstream datasets,
|
153 |
+
or it is not intended for direct use without finetuning.
|
154 |
+
"""
|
155 |
+
)
|
156 |
+
|
157 |
+
if device == "cpu" or device == torch.device("cpu"):
|
158 |
+
model = model.float()
|
159 |
+
|
160 |
+
return model.to(device), vis_processors, txt_processors
|
161 |
+
|
162 |
+
|
163 |
+
class ModelZoo:
|
164 |
+
"""
|
165 |
+
A utility class to create string representation of available model architectures and types.
|
166 |
+
|
167 |
+
>>> from minigpt4.models import model_zoo
|
168 |
+
>>> # list all available models
|
169 |
+
>>> print(model_zoo)
|
170 |
+
>>> # show total number of models
|
171 |
+
>>> print(len(model_zoo))
|
172 |
+
"""
|
173 |
+
|
174 |
+
def __init__(self) -> None:
|
175 |
+
self.model_zoo = {
|
176 |
+
k: list(v.PRETRAINED_MODEL_CONFIG_DICT.keys())
|
177 |
+
for k, v in registry.mapping["model_name_mapping"].items()
|
178 |
+
}
|
179 |
+
|
180 |
+
def __str__(self) -> str:
|
181 |
+
return (
|
182 |
+
"=" * 50
|
183 |
+
+ "\n"
|
184 |
+
+ f"{'Architectures':<30} {'Types'}\n"
|
185 |
+
+ "=" * 50
|
186 |
+
+ "\n"
|
187 |
+
+ "\n".join(
|
188 |
+
[
|
189 |
+
f"{name:<30} {', '.join(types)}"
|
190 |
+
for name, types in self.model_zoo.items()
|
191 |
+
]
|
192 |
+
)
|
193 |
+
)
|
194 |
+
|
195 |
+
def __iter__(self):
|
196 |
+
return iter(self.model_zoo.items())
|
197 |
+
|
198 |
+
def __len__(self):
|
199 |
+
return sum([len(v) for v in self.model_zoo.values()])
|
200 |
+
|
201 |
+
|
202 |
+
model_zoo = ModelZoo()
|
minigpt4/models/__pycache__/Qformer.cpython-39.pyc
ADDED
Binary file (30.9 kB). View file
|
|
minigpt4/models/__pycache__/__init__.cpython-39.pyc
ADDED
Binary file (6.14 kB). View file
|
|
minigpt4/models/__pycache__/base_model.cpython-39.pyc
ADDED
Binary file (7.21 kB). View file
|
|
minigpt4/models/__pycache__/eva_vit.cpython-39.pyc
ADDED
Binary file (14 kB). View file
|
|
minigpt4/models/__pycache__/minigpt4.cpython-39.pyc
ADDED
Binary file (5.35 kB). View file
|
|
minigpt4/models/__pycache__/minigpt_base.cpython-39.pyc
ADDED
Binary file (14.4 kB). View file
|
|
minigpt4/models/__pycache__/minigpt_v2.cpython-39.pyc
ADDED
Binary file (3.98 kB). View file
|
|
minigpt4/models/__pycache__/modeling_llama.cpython-39.pyc
ADDED
Binary file (3.87 kB). View file
|
|
minigpt4/models/base_model.py
ADDED
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Copyright (c) 2022, salesforce.com, inc.
|
3 |
+
All rights reserved.
|
4 |
+
SPDX-License-Identifier: BSD-3-Clause
|
5 |
+
For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause
|
6 |
+
"""
|
7 |
+
|
8 |
+
import os
|
9 |
+
import logging
|
10 |
+
import contextlib
|
11 |
+
|
12 |
+
from omegaconf import OmegaConf
|
13 |
+
import numpy as np
|
14 |
+
import torch
|
15 |
+
import torch.nn as nn
|
16 |
+
from transformers import LlamaTokenizer
|
17 |
+
from peft import (
|
18 |
+
LoraConfig,
|
19 |
+
get_peft_model,
|
20 |
+
prepare_model_for_int8_training,
|
21 |
+
)
|
22 |
+
|
23 |
+
from minigpt4.common.dist_utils import download_cached_file
|
24 |
+
from minigpt4.common.utils import get_abs_path, is_url
|
25 |
+
from minigpt4.models.eva_vit import create_eva_vit_g
|
26 |
+
from minigpt4.models.modeling_llama import LlamaForCausalLM
|
27 |
+
|
28 |
+
|
29 |
+
|
30 |
+
class BaseModel(nn.Module):
|
31 |
+
"""Base class for models."""
|
32 |
+
|
33 |
+
def __init__(self):
|
34 |
+
super().__init__()
|
35 |
+
|
36 |
+
@property
|
37 |
+
def device(self):
|
38 |
+
return list(self.parameters())[-1].device
|
39 |
+
|
40 |
+
def load_checkpoint(self, url_or_filename):
|
41 |
+
"""
|
42 |
+
Load from a finetuned checkpoint.
|
43 |
+
|
44 |
+
This should expect no mismatch in the model keys and the checkpoint keys.
|
45 |
+
"""
|
46 |
+
|
47 |
+
if is_url(url_or_filename):
|
48 |
+
cached_file = download_cached_file(
|
49 |
+
url_or_filename, check_hash=False, progress=True
|
50 |
+
)
|
51 |
+
checkpoint = torch.load(cached_file, map_location="cpu")
|
52 |
+
elif os.path.isfile(url_or_filename):
|
53 |
+
checkpoint = torch.load(url_or_filename, map_location="cpu")
|
54 |
+
else:
|
55 |
+
raise RuntimeError("checkpoint url or path is invalid")
|
56 |
+
|
57 |
+
if "model" in checkpoint.keys():
|
58 |
+
state_dict = checkpoint["model"]
|
59 |
+
else:
|
60 |
+
state_dict = checkpoint
|
61 |
+
|
62 |
+
msg = self.load_state_dict(state_dict, strict=False)
|
63 |
+
|
64 |
+
logging.info("Missing keys {}".format(msg.missing_keys))
|
65 |
+
logging.info("load checkpoint from %s" % url_or_filename)
|
66 |
+
|
67 |
+
return msg
|
68 |
+
|
69 |
+
@classmethod
|
70 |
+
def from_pretrained(cls, model_type):
|
71 |
+
"""
|
72 |
+
Build a pretrained model from default configuration file, specified by model_type.
|
73 |
+
|
74 |
+
Args:
|
75 |
+
- model_type (str): model type, specifying architecture and checkpoints.
|
76 |
+
|
77 |
+
Returns:
|
78 |
+
- model (nn.Module): pretrained or finetuned model, depending on the configuration.
|
79 |
+
"""
|
80 |
+
model_cfg = OmegaConf.load(cls.default_config_path(model_type)).model
|
81 |
+
model = cls.from_config(model_cfg)
|
82 |
+
|
83 |
+
return model
|
84 |
+
|
85 |
+
@classmethod
|
86 |
+
def default_config_path(cls, model_type):
|
87 |
+
assert (
|
88 |
+
model_type in cls.PRETRAINED_MODEL_CONFIG_DICT
|
89 |
+
), "Unknown model type {}".format(model_type)
|
90 |
+
return get_abs_path(cls.PRETRAINED_MODEL_CONFIG_DICT[model_type])
|
91 |
+
|
92 |
+
def load_checkpoint_from_config(self, cfg, **kwargs):
|
93 |
+
"""
|
94 |
+
Load checkpoint as specified in the config file.
|
95 |
+
|
96 |
+
If load_finetuned is True, load the finetuned model; otherwise, load the pretrained model.
|
97 |
+
When loading the pretrained model, each task-specific architecture may define their
|
98 |
+
own load_from_pretrained() method.
|
99 |
+
"""
|
100 |
+
load_finetuned = cfg.get("load_finetuned", True)
|
101 |
+
if load_finetuned:
|
102 |
+
finetune_path = cfg.get("finetuned", None)
|
103 |
+
assert (
|
104 |
+
finetune_path is not None
|
105 |
+
), "Found load_finetuned is True, but finetune_path is None."
|
106 |
+
self.load_checkpoint(url_or_filename=finetune_path)
|
107 |
+
else:
|
108 |
+
# load pre-trained weights
|
109 |
+
pretrain_path = cfg.get("pretrained", None)
|
110 |
+
assert "Found load_finetuned is False, but pretrain_path is None."
|
111 |
+
self.load_from_pretrained(url_or_filename=pretrain_path, **kwargs)
|
112 |
+
|
113 |
+
def before_evaluation(self, **kwargs):
|
114 |
+
pass
|
115 |
+
|
116 |
+
def show_n_params(self, return_str=True):
|
117 |
+
tot = 0
|
118 |
+
for p in self.parameters():
|
119 |
+
w = 1
|
120 |
+
for x in p.shape:
|
121 |
+
w *= x
|
122 |
+
tot += w
|
123 |
+
if return_str:
|
124 |
+
if tot >= 1e6:
|
125 |
+
return "{:.1f}M".format(tot / 1e6)
|
126 |
+
else:
|
127 |
+
return "{:.1f}K".format(tot / 1e3)
|
128 |
+
else:
|
129 |
+
return tot
|
130 |
+
|
131 |
+
def maybe_autocast(self, dtype=torch.float16):
|
132 |
+
# if on cpu, don't use autocast
|
133 |
+
# if on gpu, use autocast with dtype if provided, otherwise use torch.float16
|
134 |
+
enable_autocast = self.device != torch.device("cpu")
|
135 |
+
|
136 |
+
if enable_autocast:
|
137 |
+
return torch.cuda.amp.autocast(dtype=dtype)
|
138 |
+
else:
|
139 |
+
return contextlib.nullcontext()
|
140 |
+
|
141 |
+
@classmethod
|
142 |
+
def init_vision_encoder(
|
143 |
+
cls, model_name, img_size, drop_path_rate, use_grad_checkpoint, precision, freeze
|
144 |
+
):
|
145 |
+
logging.info('Loading VIT')
|
146 |
+
|
147 |
+
assert model_name == "eva_clip_g", "vit model must be eva_clip_g for current version of MiniGPT-4"
|
148 |
+
if not freeze:
|
149 |
+
precision = "fp32" # fp16 is not for training
|
150 |
+
|
151 |
+
visual_encoder = create_eva_vit_g(
|
152 |
+
img_size, drop_path_rate, use_grad_checkpoint, precision
|
153 |
+
)
|
154 |
+
|
155 |
+
ln_vision = LayerNorm(visual_encoder.num_features)
|
156 |
+
|
157 |
+
if freeze:
|
158 |
+
for name, param in visual_encoder.named_parameters():
|
159 |
+
param.requires_grad = False
|
160 |
+
visual_encoder = visual_encoder.eval()
|
161 |
+
visual_encoder.train = disabled_train
|
162 |
+
for name, param in ln_vision.named_parameters():
|
163 |
+
param.requires_grad = False
|
164 |
+
ln_vision = ln_vision.eval()
|
165 |
+
ln_vision.train = disabled_train
|
166 |
+
logging.info("freeze vision encoder")
|
167 |
+
|
168 |
+
logging.info('Loading VIT Done')
|
169 |
+
return visual_encoder, ln_vision
|
170 |
+
|
171 |
+
# lora_target_modules=["q_proj","v_proj"], **lora_kargs):
|
172 |
+
def init_llm(cls, llama_model_path, low_resource=False, low_res_device=0, lora_r=0,
|
173 |
+
lora_target_modules=["q_proj","k_proj"], **lora_kargs):
|
174 |
+
logging.info('Loading LLAMA')
|
175 |
+
llama_tokenizer = LlamaTokenizer.from_pretrained(llama_model_path, use_fast=False)
|
176 |
+
llama_tokenizer.pad_token = "$$"
|
177 |
+
|
178 |
+
if low_resource:
|
179 |
+
llama_model = LlamaForCausalLM.from_pretrained(
|
180 |
+
llama_model_path,
|
181 |
+
torch_dtype=torch.float16,
|
182 |
+
load_in_8bit=True,
|
183 |
+
device_map={'': low_res_device}
|
184 |
+
)
|
185 |
+
else:
|
186 |
+
llama_model = LlamaForCausalLM.from_pretrained(
|
187 |
+
llama_model_path,
|
188 |
+
torch_dtype=torch.float16,
|
189 |
+
)
|
190 |
+
|
191 |
+
if lora_r > 0:
|
192 |
+
llama_model = prepare_model_for_int8_training(llama_model)
|
193 |
+
loraconfig = LoraConfig(
|
194 |
+
r=lora_r,
|
195 |
+
bias="none",
|
196 |
+
task_type="CAUSAL_LM",
|
197 |
+
target_modules=lora_target_modules,
|
198 |
+
**lora_kargs
|
199 |
+
)
|
200 |
+
|
201 |
+
print("loraconfig:", loraconfig)
|
202 |
+
llama_model = get_peft_model(llama_model, loraconfig)
|
203 |
+
|
204 |
+
llama_model.print_trainable_parameters()
|
205 |
+
|
206 |
+
else:
|
207 |
+
for name, param in llama_model.named_parameters():
|
208 |
+
param.requires_grad = False
|
209 |
+
logging.info('Loading LLAMA Done')
|
210 |
+
return llama_model, llama_tokenizer
|
211 |
+
|
212 |
+
|
213 |
+
def load_from_pretrained(self, url_or_filename):
|
214 |
+
if is_url(url_or_filename):
|
215 |
+
cached_file = download_cached_file(
|
216 |
+
url_or_filename, check_hash=False, progress=True
|
217 |
+
)
|
218 |
+
checkpoint = torch.load(cached_file, map_location="cpu")
|
219 |
+
elif os.path.isfile(url_or_filename):
|
220 |
+
checkpoint = torch.load(url_or_filename, map_location="cpu")
|
221 |
+
else:
|
222 |
+
raise RuntimeError("checkpoint url or path is invalid")
|
223 |
+
|
224 |
+
state_dict = checkpoint["model"]
|
225 |
+
|
226 |
+
msg = self.load_state_dict(state_dict, strict=False)
|
227 |
+
|
228 |
+
# logging.info("Missing keys {}".format(msg.missing_keys))
|
229 |
+
logging.info("load checkpoint from %s" % url_or_filename)
|
230 |
+
|
231 |
+
return msg
|
232 |
+
|
233 |
+
|
234 |
+
def disabled_train(self, mode=True):
|
235 |
+
"""Overwrite model.train with this function to make sure train/eval mode
|
236 |
+
does not change anymore."""
|
237 |
+
return self
|
238 |
+
|
239 |
+
|
240 |
+
class LayerNorm(nn.LayerNorm):
|
241 |
+
"""Subclass torch's LayerNorm to handle fp16."""
|
242 |
+
|
243 |
+
def forward(self, x: torch.Tensor):
|
244 |
+
orig_type = x.dtype
|
245 |
+
ret = super().forward(x.type(torch.float32))
|
246 |
+
return ret.type(orig_type)
|
247 |
+
|
248 |
+
|
249 |
+
|
250 |
+
|
251 |
+
|
minigpt4/models/eva_vit.py
ADDED
@@ -0,0 +1,442 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Based on EVA, BEIT, timm and DeiT code bases
|
2 |
+
# https://github.com/baaivision/EVA
|
3 |
+
# https://github.com/rwightman/pytorch-image-models/tree/master/timm
|
4 |
+
# https://github.com/microsoft/unilm/tree/master/beit
|
5 |
+
# https://github.com/facebookresearch/deit/
|
6 |
+
# https://github.com/facebookresearch/dino
|
7 |
+
# --------------------------------------------------------'
|
8 |
+
import math
|
9 |
+
from functools import partial
|
10 |
+
|
11 |
+
import torch
|
12 |
+
import torch.nn as nn
|
13 |
+
import torch.nn.functional as F
|
14 |
+
import torch.utils.checkpoint as checkpoint
|
15 |
+
from timm.models.layers import drop_path, to_2tuple, trunc_normal_
|
16 |
+
from timm.models.registry import register_model
|
17 |
+
|
18 |
+
from minigpt4.common.dist_utils import download_cached_file
|
19 |
+
|
20 |
+
def _cfg(url='', **kwargs):
|
21 |
+
return {
|
22 |
+
'url': url,
|
23 |
+
'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': None,
|
24 |
+
'crop_pct': .9, 'interpolation': 'bicubic',
|
25 |
+
'mean': (0.5, 0.5, 0.5), 'std': (0.5, 0.5, 0.5),
|
26 |
+
**kwargs
|
27 |
+
}
|
28 |
+
|
29 |
+
|
30 |
+
class DropPath(nn.Module):
|
31 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
|
32 |
+
"""
|
33 |
+
def __init__(self, drop_prob=None):
|
34 |
+
super(DropPath, self).__init__()
|
35 |
+
self.drop_prob = drop_prob
|
36 |
+
|
37 |
+
def forward(self, x):
|
38 |
+
return drop_path(x, self.drop_prob, self.training)
|
39 |
+
|
40 |
+
def extra_repr(self) -> str:
|
41 |
+
return 'p={}'.format(self.drop_prob)
|
42 |
+
|
43 |
+
|
44 |
+
class Mlp(nn.Module):
|
45 |
+
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
|
46 |
+
super().__init__()
|
47 |
+
out_features = out_features or in_features
|
48 |
+
hidden_features = hidden_features or in_features
|
49 |
+
self.fc1 = nn.Linear(in_features, hidden_features)
|
50 |
+
self.act = act_layer()
|
51 |
+
self.fc2 = nn.Linear(hidden_features, out_features)
|
52 |
+
self.drop = nn.Dropout(drop)
|
53 |
+
|
54 |
+
def forward(self, x):
|
55 |
+
x = self.fc1(x)
|
56 |
+
x = self.act(x)
|
57 |
+
# x = self.drop(x)
|
58 |
+
# commit this for the orignal BERT implement
|
59 |
+
x = self.fc2(x)
|
60 |
+
x = self.drop(x)
|
61 |
+
return x
|
62 |
+
|
63 |
+
|
64 |
+
class Attention(nn.Module):
|
65 |
+
def __init__(
|
66 |
+
self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.,
|
67 |
+
proj_drop=0., window_size=None, attn_head_dim=None):
|
68 |
+
super().__init__()
|
69 |
+
self.num_heads = num_heads
|
70 |
+
head_dim = dim // num_heads
|
71 |
+
if attn_head_dim is not None:
|
72 |
+
head_dim = attn_head_dim
|
73 |
+
all_head_dim = head_dim * self.num_heads
|
74 |
+
self.scale = qk_scale or head_dim ** -0.5
|
75 |
+
|
76 |
+
self.qkv = nn.Linear(dim, all_head_dim * 3, bias=False)
|
77 |
+
if qkv_bias:
|
78 |
+
self.q_bias = nn.Parameter(torch.zeros(all_head_dim))
|
79 |
+
self.v_bias = nn.Parameter(torch.zeros(all_head_dim))
|
80 |
+
else:
|
81 |
+
self.q_bias = None
|
82 |
+
self.v_bias = None
|
83 |
+
|
84 |
+
if window_size:
|
85 |
+
self.window_size = window_size
|
86 |
+
self.num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3
|
87 |
+
self.relative_position_bias_table = nn.Parameter(
|
88 |
+
torch.zeros(self.num_relative_distance, num_heads)) # 2*Wh-1 * 2*Ww-1, nH
|
89 |
+
# cls to token & token 2 cls & cls to cls
|
90 |
+
|
91 |
+
# get pair-wise relative position index for each token inside the window
|
92 |
+
coords_h = torch.arange(window_size[0])
|
93 |
+
coords_w = torch.arange(window_size[1])
|
94 |
+
coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
|
95 |
+
coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
|
96 |
+
relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
|
97 |
+
relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
|
98 |
+
relative_coords[:, :, 0] += window_size[0] - 1 # shift to start from 0
|
99 |
+
relative_coords[:, :, 1] += window_size[1] - 1
|
100 |
+
relative_coords[:, :, 0] *= 2 * window_size[1] - 1
|
101 |
+
relative_position_index = \
|
102 |
+
torch.zeros(size=(window_size[0] * window_size[1] + 1, ) * 2, dtype=relative_coords.dtype)
|
103 |
+
relative_position_index[1:, 1:] = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
|
104 |
+
relative_position_index[0, 0:] = self.num_relative_distance - 3
|
105 |
+
relative_position_index[0:, 0] = self.num_relative_distance - 2
|
106 |
+
relative_position_index[0, 0] = self.num_relative_distance - 1
|
107 |
+
|
108 |
+
self.register_buffer("relative_position_index", relative_position_index)
|
109 |
+
else:
|
110 |
+
self.window_size = None
|
111 |
+
self.relative_position_bias_table = None
|
112 |
+
self.relative_position_index = None
|
113 |
+
|
114 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
115 |
+
self.proj = nn.Linear(all_head_dim, dim)
|
116 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
117 |
+
|
118 |
+
def forward(self, x, rel_pos_bias=None):
|
119 |
+
B, N, C = x.shape
|
120 |
+
qkv_bias = None
|
121 |
+
if self.q_bias is not None:
|
122 |
+
qkv_bias = torch.cat((self.q_bias, torch.zeros_like(self.v_bias, requires_grad=False), self.v_bias))
|
123 |
+
# qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
|
124 |
+
qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias)
|
125 |
+
qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
|
126 |
+
q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
|
127 |
+
|
128 |
+
q = q * self.scale
|
129 |
+
attn = (q @ k.transpose(-2, -1))
|
130 |
+
|
131 |
+
if self.relative_position_bias_table is not None:
|
132 |
+
relative_position_bias = \
|
133 |
+
self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
|
134 |
+
self.window_size[0] * self.window_size[1] + 1,
|
135 |
+
self.window_size[0] * self.window_size[1] + 1, -1) # Wh*Ww,Wh*Ww,nH
|
136 |
+
relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
|
137 |
+
attn = attn + relative_position_bias.unsqueeze(0)
|
138 |
+
|
139 |
+
if rel_pos_bias is not None:
|
140 |
+
attn = attn + rel_pos_bias
|
141 |
+
|
142 |
+
attn = attn.softmax(dim=-1)
|
143 |
+
attn = self.attn_drop(attn)
|
144 |
+
|
145 |
+
x = (attn @ v).transpose(1, 2).reshape(B, N, -1)
|
146 |
+
x = self.proj(x)
|
147 |
+
x = self.proj_drop(x)
|
148 |
+
return x
|
149 |
+
|
150 |
+
|
151 |
+
class Block(nn.Module):
|
152 |
+
|
153 |
+
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
|
154 |
+
drop_path=0., init_values=None, act_layer=nn.GELU, norm_layer=nn.LayerNorm,
|
155 |
+
window_size=None, attn_head_dim=None):
|
156 |
+
super().__init__()
|
157 |
+
self.norm1 = norm_layer(dim)
|
158 |
+
self.attn = Attention(
|
159 |
+
dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
|
160 |
+
attn_drop=attn_drop, proj_drop=drop, window_size=window_size, attn_head_dim=attn_head_dim)
|
161 |
+
# NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
|
162 |
+
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
|
163 |
+
self.norm2 = norm_layer(dim)
|
164 |
+
mlp_hidden_dim = int(dim * mlp_ratio)
|
165 |
+
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
|
166 |
+
|
167 |
+
if init_values is not None and init_values > 0:
|
168 |
+
self.gamma_1 = nn.Parameter(init_values * torch.ones((dim)),requires_grad=True)
|
169 |
+
self.gamma_2 = nn.Parameter(init_values * torch.ones((dim)),requires_grad=True)
|
170 |
+
else:
|
171 |
+
self.gamma_1, self.gamma_2 = None, None
|
172 |
+
|
173 |
+
def forward(self, x, rel_pos_bias=None):
|
174 |
+
if self.gamma_1 is None:
|
175 |
+
x = x + self.drop_path(self.attn(self.norm1(x), rel_pos_bias=rel_pos_bias))
|
176 |
+
x = x + self.drop_path(self.mlp(self.norm2(x)))
|
177 |
+
else:
|
178 |
+
x = x + self.drop_path(self.gamma_1 * self.attn(self.norm1(x), rel_pos_bias=rel_pos_bias))
|
179 |
+
x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x)))
|
180 |
+
return x
|
181 |
+
|
182 |
+
|
183 |
+
class PatchEmbed(nn.Module):
|
184 |
+
""" Image to Patch Embedding
|
185 |
+
"""
|
186 |
+
def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768):
|
187 |
+
super().__init__()
|
188 |
+
img_size = to_2tuple(img_size)
|
189 |
+
patch_size = to_2tuple(patch_size)
|
190 |
+
num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0])
|
191 |
+
self.patch_shape = (img_size[0] // patch_size[0], img_size[1] // patch_size[1])
|
192 |
+
self.img_size = img_size
|
193 |
+
self.patch_size = patch_size
|
194 |
+
self.num_patches = num_patches
|
195 |
+
|
196 |
+
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
|
197 |
+
|
198 |
+
def forward(self, x, **kwargs):
|
199 |
+
B, C, H, W = x.shape
|
200 |
+
# FIXME look at relaxing size constraints
|
201 |
+
assert H == self.img_size[0] and W == self.img_size[1], \
|
202 |
+
f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
|
203 |
+
x = self.proj(x).flatten(2).transpose(1, 2)
|
204 |
+
return x
|
205 |
+
|
206 |
+
|
207 |
+
class RelativePositionBias(nn.Module):
|
208 |
+
|
209 |
+
def __init__(self, window_size, num_heads):
|
210 |
+
super().__init__()
|
211 |
+
self.window_size = window_size
|
212 |
+
self.num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3
|
213 |
+
self.relative_position_bias_table = nn.Parameter(
|
214 |
+
torch.zeros(self.num_relative_distance, num_heads)) # 2*Wh-1 * 2*Ww-1, nH
|
215 |
+
# cls to token & token 2 cls & cls to cls
|
216 |
+
|
217 |
+
# get pair-wise relative position index for each token inside the window
|
218 |
+
coords_h = torch.arange(window_size[0])
|
219 |
+
coords_w = torch.arange(window_size[1])
|
220 |
+
coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
|
221 |
+
coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
|
222 |
+
relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
|
223 |
+
relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
|
224 |
+
relative_coords[:, :, 0] += window_size[0] - 1 # shift to start from 0
|
225 |
+
relative_coords[:, :, 1] += window_size[1] - 1
|
226 |
+
relative_coords[:, :, 0] *= 2 * window_size[1] - 1
|
227 |
+
relative_position_index = \
|
228 |
+
torch.zeros(size=(window_size[0] * window_size[1] + 1,) * 2, dtype=relative_coords.dtype)
|
229 |
+
relative_position_index[1:, 1:] = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
|
230 |
+
relative_position_index[0, 0:] = self.num_relative_distance - 3
|
231 |
+
relative_position_index[0:, 0] = self.num_relative_distance - 2
|
232 |
+
relative_position_index[0, 0] = self.num_relative_distance - 1
|
233 |
+
|
234 |
+
self.register_buffer("relative_position_index", relative_position_index)
|
235 |
+
|
236 |
+
# trunc_normal_(self.relative_position_bias_table, std=.02)
|
237 |
+
|
238 |
+
def forward(self):
|
239 |
+
relative_position_bias = \
|
240 |
+
self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
|
241 |
+
self.window_size[0] * self.window_size[1] + 1,
|
242 |
+
self.window_size[0] * self.window_size[1] + 1, -1) # Wh*Ww,Wh*Ww,nH
|
243 |
+
return relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
|
244 |
+
|
245 |
+
|
246 |
+
class VisionTransformer(nn.Module):
|
247 |
+
""" Vision Transformer with support for patch or hybrid CNN input stage
|
248 |
+
"""
|
249 |
+
def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dim=768, depth=12,
|
250 |
+
num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0.,
|
251 |
+
drop_path_rate=0., norm_layer=nn.LayerNorm, init_values=None,
|
252 |
+
use_abs_pos_emb=True, use_rel_pos_bias=False, use_shared_rel_pos_bias=False,
|
253 |
+
use_mean_pooling=True, init_scale=0.001, use_checkpoint=False):
|
254 |
+
super().__init__()
|
255 |
+
self.image_size = img_size
|
256 |
+
self.num_classes = num_classes
|
257 |
+
self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
|
258 |
+
|
259 |
+
self.patch_embed = PatchEmbed(
|
260 |
+
img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)
|
261 |
+
num_patches = self.patch_embed.num_patches
|
262 |
+
|
263 |
+
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
|
264 |
+
if use_abs_pos_emb:
|
265 |
+
self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))
|
266 |
+
else:
|
267 |
+
self.pos_embed = None
|
268 |
+
self.pos_drop = nn.Dropout(p=drop_rate)
|
269 |
+
|
270 |
+
if use_shared_rel_pos_bias:
|
271 |
+
self.rel_pos_bias = RelativePositionBias(window_size=self.patch_embed.patch_shape, num_heads=num_heads)
|
272 |
+
else:
|
273 |
+
self.rel_pos_bias = None
|
274 |
+
self.use_checkpoint = use_checkpoint
|
275 |
+
|
276 |
+
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
|
277 |
+
self.use_rel_pos_bias = use_rel_pos_bias
|
278 |
+
self.blocks = nn.ModuleList([
|
279 |
+
Block(
|
280 |
+
dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
|
281 |
+
drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer,
|
282 |
+
init_values=init_values, window_size=self.patch_embed.patch_shape if use_rel_pos_bias else None)
|
283 |
+
for i in range(depth)])
|
284 |
+
# self.norm = nn.Identity() if use_mean_pooling else norm_layer(embed_dim)
|
285 |
+
# self.fc_norm = norm_layer(embed_dim) if use_mean_pooling else None
|
286 |
+
# self.head = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity()
|
287 |
+
|
288 |
+
if self.pos_embed is not None:
|
289 |
+
trunc_normal_(self.pos_embed, std=.02)
|
290 |
+
trunc_normal_(self.cls_token, std=.02)
|
291 |
+
# trunc_normal_(self.mask_token, std=.02)
|
292 |
+
# if isinstance(self.head, nn.Linear):
|
293 |
+
# trunc_normal_(self.head.weight, std=.02)
|
294 |
+
self.apply(self._init_weights)
|
295 |
+
self.fix_init_weight()
|
296 |
+
# if isinstance(self.head, nn.Linear):
|
297 |
+
# self.head.weight.data.mul_(init_scale)
|
298 |
+
# self.head.bias.data.mul_(init_scale)
|
299 |
+
|
300 |
+
def fix_init_weight(self):
|
301 |
+
def rescale(param, layer_id):
|
302 |
+
param.div_(math.sqrt(2.0 * layer_id))
|
303 |
+
|
304 |
+
for layer_id, layer in enumerate(self.blocks):
|
305 |
+
rescale(layer.attn.proj.weight.data, layer_id + 1)
|
306 |
+
rescale(layer.mlp.fc2.weight.data, layer_id + 1)
|
307 |
+
|
308 |
+
def _init_weights(self, m):
|
309 |
+
if isinstance(m, nn.Linear):
|
310 |
+
trunc_normal_(m.weight, std=.02)
|
311 |
+
if isinstance(m, nn.Linear) and m.bias is not None:
|
312 |
+
nn.init.constant_(m.bias, 0)
|
313 |
+
elif isinstance(m, nn.LayerNorm):
|
314 |
+
nn.init.constant_(m.bias, 0)
|
315 |
+
nn.init.constant_(m.weight, 1.0)
|
316 |
+
|
317 |
+
def get_classifier(self):
|
318 |
+
return self.head
|
319 |
+
|
320 |
+
def reset_classifier(self, num_classes, global_pool=''):
|
321 |
+
self.num_classes = num_classes
|
322 |
+
self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
|
323 |
+
|
324 |
+
def forward_features(self, x):
|
325 |
+
x = self.patch_embed(x)
|
326 |
+
batch_size, seq_len, _ = x.size()
|
327 |
+
|
328 |
+
cls_tokens = self.cls_token.expand(batch_size, -1, -1) # stole cls_tokens impl from Phil Wang, thanks
|
329 |
+
x = torch.cat((cls_tokens, x), dim=1)
|
330 |
+
if self.pos_embed is not None:
|
331 |
+
x = x + self.pos_embed
|
332 |
+
x = self.pos_drop(x)
|
333 |
+
|
334 |
+
rel_pos_bias = self.rel_pos_bias() if self.rel_pos_bias is not None else None
|
335 |
+
for blk in self.blocks:
|
336 |
+
if self.use_checkpoint:
|
337 |
+
x = checkpoint.checkpoint(blk, x, rel_pos_bias)
|
338 |
+
else:
|
339 |
+
x = blk(x, rel_pos_bias)
|
340 |
+
return x
|
341 |
+
# x = self.norm(x)
|
342 |
+
|
343 |
+
# if self.fc_norm is not None:
|
344 |
+
# t = x[:, 1:, :]
|
345 |
+
# return self.fc_norm(t.mean(1))
|
346 |
+
# else:
|
347 |
+
# return x[:, 0]
|
348 |
+
|
349 |
+
def forward(self, x):
|
350 |
+
x = self.forward_features(x)
|
351 |
+
# x = self.head(x)
|
352 |
+
return x
|
353 |
+
|
354 |
+
def get_intermediate_layers(self, x):
|
355 |
+
x = self.patch_embed(x)
|
356 |
+
batch_size, seq_len, _ = x.size()
|
357 |
+
|
358 |
+
cls_tokens = self.cls_token.expand(batch_size, -1, -1) # stole cls_tokens impl from Phil Wang, thanks
|
359 |
+
x = torch.cat((cls_tokens, x), dim=1)
|
360 |
+
if self.pos_embed is not None:
|
361 |
+
x = x + self.pos_embed
|
362 |
+
x = self.pos_drop(x)
|
363 |
+
|
364 |
+
features = []
|
365 |
+
rel_pos_bias = self.rel_pos_bias() if self.rel_pos_bias is not None else None
|
366 |
+
for blk in self.blocks:
|
367 |
+
x = blk(x, rel_pos_bias)
|
368 |
+
features.append(x)
|
369 |
+
|
370 |
+
return features
|
371 |
+
|
372 |
+
|
373 |
+
def interpolate_pos_embed(model, checkpoint_model):
|
374 |
+
if 'pos_embed' in checkpoint_model:
|
375 |
+
pos_embed_checkpoint = checkpoint_model['pos_embed'].float()
|
376 |
+
embedding_size = pos_embed_checkpoint.shape[-1]
|
377 |
+
num_patches = model.patch_embed.num_patches
|
378 |
+
num_extra_tokens = model.pos_embed.shape[-2] - num_patches
|
379 |
+
# height (== width) for the checkpoint position embedding
|
380 |
+
orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5)
|
381 |
+
# height (== width) for the new position embedding
|
382 |
+
new_size = int(num_patches ** 0.5)
|
383 |
+
# class_token and dist_token are kept unchanged
|
384 |
+
if orig_size != new_size:
|
385 |
+
print("Position interpolate from %dx%d to %dx%d" % (orig_size, orig_size, new_size, new_size))
|
386 |
+
extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
|
387 |
+
# only the position tokens are interpolated
|
388 |
+
pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
|
389 |
+
pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2)
|
390 |
+
pos_tokens = torch.nn.functional.interpolate(
|
391 |
+
pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False)
|
392 |
+
pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2)
|
393 |
+
new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
|
394 |
+
checkpoint_model['pos_embed'] = new_pos_embed
|
395 |
+
|
396 |
+
|
397 |
+
def convert_weights_to_fp16(model: nn.Module):
|
398 |
+
"""Convert applicable model parameters to fp16"""
|
399 |
+
|
400 |
+
def _convert_weights_to_fp16(l):
|
401 |
+
if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
|
402 |
+
l.weight.data = l.weight.data.half()
|
403 |
+
if l.bias is not None:
|
404 |
+
l.bias.data = l.bias.data.half()
|
405 |
+
|
406 |
+
# if isinstance(l, (nn.MultiheadAttention, Attention)):
|
407 |
+
# for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]:
|
408 |
+
# tensor = getattr(l, attr)
|
409 |
+
# if tensor is not None:
|
410 |
+
# tensor.data = tensor.data.half()
|
411 |
+
|
412 |
+
model.apply(_convert_weights_to_fp16)
|
413 |
+
|
414 |
+
|
415 |
+
def create_eva_vit_g(img_size=224,drop_path_rate=0.4,use_checkpoint=False,precision="fp16"):
|
416 |
+
model = VisionTransformer(
|
417 |
+
img_size=img_size,
|
418 |
+
patch_size=14,
|
419 |
+
use_mean_pooling=False,
|
420 |
+
embed_dim=1408,
|
421 |
+
depth=39,
|
422 |
+
num_heads=1408//88,
|
423 |
+
mlp_ratio=4.3637,
|
424 |
+
qkv_bias=True,
|
425 |
+
drop_path_rate=drop_path_rate,
|
426 |
+
norm_layer=partial(nn.LayerNorm, eps=1e-6),
|
427 |
+
use_checkpoint=use_checkpoint,
|
428 |
+
)
|
429 |
+
url = "https://storage.googleapis.com/sfr-vision-language-research/LAVIS/models/BLIP2/eva_vit_g.pth"
|
430 |
+
cached_file = download_cached_file(
|
431 |
+
url, check_hash=False, progress=True
|
432 |
+
)
|
433 |
+
state_dict = torch.load(cached_file, map_location="cpu")
|
434 |
+
interpolate_pos_embed(model,state_dict)
|
435 |
+
|
436 |
+
incompatible_keys = model.load_state_dict(state_dict, strict=False)
|
437 |
+
# print(incompatible_keys)
|
438 |
+
|
439 |
+
if precision == "fp16":
|
440 |
+
# model.to("cuda")
|
441 |
+
convert_weights_to_fp16(model)
|
442 |
+
return model
|
minigpt4/models/minigpt4.py
ADDED
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
import random
|
3 |
+
|
4 |
+
import torch
|
5 |
+
from torch.cuda.amp import autocast as autocast
|
6 |
+
import torch.nn as nn
|
7 |
+
|
8 |
+
from minigpt4.common.registry import registry
|
9 |
+
from minigpt4.models.base_model import disabled_train
|
10 |
+
from minigpt4.models.minigpt_base import MiniGPTBase
|
11 |
+
from minigpt4.models.Qformer import BertConfig, BertLMHeadModel
|
12 |
+
|
13 |
+
|
14 |
+
@registry.register_model("minigpt4")
|
15 |
+
class MiniGPT4(MiniGPTBase):
|
16 |
+
"""
|
17 |
+
MiniGPT-4 model
|
18 |
+
"""
|
19 |
+
|
20 |
+
PRETRAINED_MODEL_CONFIG_DICT = {
|
21 |
+
"pretrain_vicuna0": "configs/models/minigpt4_vicuna0.yaml",
|
22 |
+
"pretrain_llama2": "configs/models/minigpt4_llama2.yaml",
|
23 |
+
}
|
24 |
+
|
25 |
+
def __init__(
|
26 |
+
self,
|
27 |
+
vit_model="eva_clip_g",
|
28 |
+
q_former_model="https://storage.googleapis.com/sfr-vision-language-research/LAVIS/models/BLIP2/blip2_pretrained_flant5xxl.pth",
|
29 |
+
img_size=224,
|
30 |
+
drop_path_rate=0,
|
31 |
+
use_grad_checkpoint=False,
|
32 |
+
vit_precision="fp16",
|
33 |
+
freeze_vit=True,
|
34 |
+
has_qformer=True,
|
35 |
+
freeze_qformer=True,
|
36 |
+
num_query_token=32,
|
37 |
+
llama_model="",
|
38 |
+
prompt_path="",
|
39 |
+
prompt_template="",
|
40 |
+
max_txt_len=32,
|
41 |
+
end_sym='\n',
|
42 |
+
low_resource=False, # use 8 bit and put vit in cpu
|
43 |
+
device_8bit=0, # the device of 8bit model should be set when loading and cannot be changed anymore.
|
44 |
+
):
|
45 |
+
super().__init__(
|
46 |
+
vit_model=vit_model,
|
47 |
+
img_size=img_size,
|
48 |
+
drop_path_rate=drop_path_rate,
|
49 |
+
use_grad_checkpoint=use_grad_checkpoint,
|
50 |
+
vit_precision=vit_precision,
|
51 |
+
freeze_vit=freeze_vit,
|
52 |
+
llama_model=llama_model,
|
53 |
+
max_txt_len=max_txt_len,
|
54 |
+
end_sym=end_sym,
|
55 |
+
low_resource=low_resource,
|
56 |
+
device_8bit=device_8bit,
|
57 |
+
)
|
58 |
+
|
59 |
+
self.has_qformer = has_qformer
|
60 |
+
if self.has_qformer:
|
61 |
+
print('Loading Q-Former')
|
62 |
+
self.Qformer, self.query_tokens = self.init_Qformer(
|
63 |
+
num_query_token, self.visual_encoder.num_features, freeze_qformer
|
64 |
+
)
|
65 |
+
self.load_from_pretrained(url_or_filename=q_former_model) # load q-former weights here
|
66 |
+
|
67 |
+
img_f_dim = self.Qformer.config.hidden_size
|
68 |
+
print('Loading Q-Former Done')
|
69 |
+
else:
|
70 |
+
img_f_dim = self.visual_encoder.num_features * 4
|
71 |
+
print('Do not use Q-Former here.')
|
72 |
+
|
73 |
+
self.llama_proj = nn.Linear(
|
74 |
+
img_f_dim, self.llama_model.config.hidden_size
|
75 |
+
)
|
76 |
+
|
77 |
+
if prompt_path:
|
78 |
+
with open(prompt_path, 'r') as f:
|
79 |
+
raw_prompts = f.read().splitlines()
|
80 |
+
filted_prompts = [raw_prompt for raw_prompt in raw_prompts if "<VideoHere>" in raw_prompt]
|
81 |
+
self.prompt_list = [prompt_template.format(p) for p in filted_prompts]
|
82 |
+
print('Load {} training prompts'.format(len(self.prompt_list)))
|
83 |
+
print('Prompt Example \n{}'.format(random.choice(self.prompt_list)))
|
84 |
+
else:
|
85 |
+
self.prompt_list = []
|
86 |
+
|
87 |
+
@classmethod
|
88 |
+
def init_Qformer(cls, num_query_token, vision_width, freeze):
|
89 |
+
encoder_config = BertConfig.from_pretrained("bert-base-uncased")
|
90 |
+
encoder_config.encoder_width = vision_width
|
91 |
+
# insert cross-attention layer every other block
|
92 |
+
encoder_config.add_cross_attention = True
|
93 |
+
encoder_config.cross_attention_freq = 2
|
94 |
+
encoder_config.query_length = num_query_token
|
95 |
+
Qformer = BertLMHeadModel(config=encoder_config)
|
96 |
+
query_tokens = nn.Parameter(
|
97 |
+
torch.zeros(1, num_query_token, encoder_config.hidden_size)
|
98 |
+
)
|
99 |
+
query_tokens.data.normal_(mean=0.0, std=encoder_config.initializer_range)
|
100 |
+
|
101 |
+
Qformer.cls = None
|
102 |
+
Qformer.bert.embeddings.word_embeddings = None
|
103 |
+
Qformer.bert.embeddings.position_embeddings = None
|
104 |
+
for layer in Qformer.bert.encoder.layer:
|
105 |
+
layer.output = None
|
106 |
+
layer.intermediate = None
|
107 |
+
|
108 |
+
if freeze:
|
109 |
+
for name, param in Qformer.named_parameters():
|
110 |
+
param.requires_grad = False
|
111 |
+
Qformer = Qformer.eval()
|
112 |
+
Qformer.train = disabled_train
|
113 |
+
query_tokens.requires_grad = False
|
114 |
+
logging.info("freeze Qformer")
|
115 |
+
|
116 |
+
return Qformer, query_tokens
|
117 |
+
|
118 |
+
def encode_img(self, image):
|
119 |
+
device = image.device
|
120 |
+
|
121 |
+
if len(image.shape) > 4:
|
122 |
+
image = image.reshape(-1, *image.shape[-3:])
|
123 |
+
|
124 |
+
with self.maybe_autocast():
|
125 |
+
image_embeds = self.ln_vision(self.visual_encoder(image)).to(device)
|
126 |
+
if self.has_qformer:
|
127 |
+
image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long).to(device)
|
128 |
+
|
129 |
+
query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1)
|
130 |
+
query_output = self.Qformer.bert(
|
131 |
+
query_embeds=query_tokens,
|
132 |
+
encoder_hidden_states=image_embeds,
|
133 |
+
encoder_attention_mask=image_atts,
|
134 |
+
return_dict=True,
|
135 |
+
)
|
136 |
+
|
137 |
+
inputs_llama = self.llama_proj(query_output.last_hidden_state)
|
138 |
+
else:
|
139 |
+
image_embeds = image_embeds[:, 1:, :]
|
140 |
+
bs, pn, hs = image_embeds.shape
|
141 |
+
image_embeds = image_embeds.view(bs, int(pn / 4), int(hs * 4))
|
142 |
+
|
143 |
+
inputs_llama = self.llama_proj(image_embeds)
|
144 |
+
atts_llama = torch.ones(inputs_llama.size()[:-1], dtype=torch.long).to(image.device)
|
145 |
+
return inputs_llama, atts_llama
|
146 |
+
|
147 |
+
@classmethod
|
148 |
+
def from_config(cls, cfg):
|
149 |
+
vit_model = cfg.get("vit_model", "eva_clip_g")
|
150 |
+
q_former_model = cfg.get("q_former_model", "https://storage.googleapis.com/sfr-vision-language-research/LAVIS/models/BLIP2/blip2_pretrained_flant5xxl.pth")
|
151 |
+
img_size = cfg.get("image_size")
|
152 |
+
num_query_token = cfg.get("num_query_token")
|
153 |
+
llama_model = cfg.get("llama_model")
|
154 |
+
|
155 |
+
drop_path_rate = cfg.get("drop_path_rate", 0)
|
156 |
+
use_grad_checkpoint = cfg.get("use_grad_checkpoint", False)
|
157 |
+
vit_precision = cfg.get("vit_precision", "fp16")
|
158 |
+
freeze_vit = cfg.get("freeze_vit", True)
|
159 |
+
has_qformer = cfg.get("has_qformer", True)
|
160 |
+
freeze_qformer = cfg.get("freeze_qformer", True)
|
161 |
+
low_resource = cfg.get("low_resource", False)
|
162 |
+
device_8bit = cfg.get("device_8bit", 0)
|
163 |
+
|
164 |
+
prompt_path = cfg.get("prompt_path", "")
|
165 |
+
prompt_template = cfg.get("prompt_template", "")
|
166 |
+
max_txt_len = cfg.get("max_txt_len", 32)
|
167 |
+
end_sym = cfg.get("end_sym", '\n')
|
168 |
+
|
169 |
+
model = cls(
|
170 |
+
vit_model=vit_model,
|
171 |
+
q_former_model=q_former_model,
|
172 |
+
img_size=img_size,
|
173 |
+
drop_path_rate=drop_path_rate,
|
174 |
+
use_grad_checkpoint=use_grad_checkpoint,
|
175 |
+
vit_precision=vit_precision,
|
176 |
+
freeze_vit=freeze_vit,
|
177 |
+
has_qformer=has_qformer,
|
178 |
+
freeze_qformer=freeze_qformer,
|
179 |
+
num_query_token=num_query_token,
|
180 |
+
llama_model=llama_model,
|
181 |
+
prompt_path=prompt_path,
|
182 |
+
prompt_template=prompt_template,
|
183 |
+
max_txt_len=max_txt_len,
|
184 |
+
end_sym=end_sym,
|
185 |
+
low_resource=low_resource,
|
186 |
+
device_8bit=device_8bit,
|
187 |
+
)
|
188 |
+
|
189 |
+
ckpt_path = cfg.get("ckpt", "") # load weights of MiniGPT-4
|
190 |
+
if ckpt_path:
|
191 |
+
print("Load MiniGPT-4 Checkpoint: {}".format(ckpt_path))
|
192 |
+
ckpt = torch.load(ckpt_path, map_location="cpu")
|
193 |
+
msg = model.load_state_dict(ckpt['model'], strict=False)
|
194 |
+
|
195 |
+
return model
|
minigpt4/models/minigpt_base.py
ADDED
@@ -0,0 +1,522 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
import random
|
3 |
+
|
4 |
+
import torch
|
5 |
+
from torch.cuda.amp import autocast as autocast
|
6 |
+
import torch.nn as nn
|
7 |
+
|
8 |
+
from minigpt4.common.registry import registry
|
9 |
+
from minigpt4.models.base_model import BaseModel
|
10 |
+
from transformers import StoppingCriteria, StoppingCriteriaList
|
11 |
+
|
12 |
+
from minigpt4.conversation.conversation import StoppingCriteriaSub
|
13 |
+
|
14 |
+
|
15 |
+
class Attention(nn.Module):
|
16 |
+
def __init__(self, output_dim, layers='256,128', dropout=0.3):
|
17 |
+
super(Attention, self).__init__()
|
18 |
+
|
19 |
+
dims = [1024, 1024, 1024, 4096, 4096, 4096, 4096]
|
20 |
+
self.features_count = 7
|
21 |
+
|
22 |
+
self.feats_prep = nn.ModuleList()
|
23 |
+
for i in range(len(dims)):
|
24 |
+
self.feats_prep.append(self.MLP(dims[i], layers, dropout))
|
25 |
+
|
26 |
+
layers_list = list(map(lambda x: int(x), layers.split(',')))
|
27 |
+
hiddendim = layers_list[-1] * self.features_count
|
28 |
+
self.attention_mlp = self.MLP(hiddendim, layers, dropout)
|
29 |
+
|
30 |
+
self.fc_att = nn.Linear(layers_list[-1], self.features_count)
|
31 |
+
self.fc_out = nn.Linear(layers_list[-1], output_dim)
|
32 |
+
self.softmax = nn.Softmax(dim=1)
|
33 |
+
|
34 |
+
def MLP(self, input_dim, layers, dropout):
|
35 |
+
all_layers = []
|
36 |
+
layers = list(map(lambda x: int(x), layers.split(',')))
|
37 |
+
for i in range(0, len(layers)):
|
38 |
+
all_layers.append(nn.Linear(input_dim, layers[i]))
|
39 |
+
all_layers.append(nn.ReLU())
|
40 |
+
all_layers.append(nn.Dropout(dropout))
|
41 |
+
input_dim = layers[i]
|
42 |
+
module = nn.Sequential(*all_layers)
|
43 |
+
return module
|
44 |
+
|
45 |
+
def forward(self, feats): # [1, 4, 4096]
|
46 |
+
|
47 |
+
feats_hidden = []
|
48 |
+
for i in range(self.features_count):
|
49 |
+
feats_hidden.append(self.feats_prep[i](feats[i])) # [batch_size, 128]
|
50 |
+
|
51 |
+
# import pdb
|
52 |
+
# pdb.set_trace()
|
53 |
+
|
54 |
+
multi_hidden1 = torch.cat(feats_hidden, dim=1) # [batch_size, 128*features_count]
|
55 |
+
multi_hidden2 = torch.stack(feats_hidden, dim=2) # [batch_size, 128, features_count]
|
56 |
+
|
57 |
+
# multi_hidden1 = torch.reshape(x, (x.size(0), -1)) # [batch_size, 128*features_count] [1, 512]
|
58 |
+
# multi_hidden2 = torch.transpose(x, 1, 2) # [batch_size, 128, features_count] [1, 128, 4]
|
59 |
+
|
60 |
+
|
61 |
+
attention = self.attention_mlp(multi_hidden1)
|
62 |
+
attention = self.fc_att(attention)
|
63 |
+
attention = torch.unsqueeze(attention, 2) # [batch_size, features_count, 1]
|
64 |
+
|
65 |
+
fused_feat = torch.matmul(multi_hidden2, attention)
|
66 |
+
fused_feat = fused_feat.squeeze(dim=2) # [batch_size, 128]
|
67 |
+
# fused_feat = fused_feat.squeeze() # [batch_size, 128]
|
68 |
+
emos_out = self.fc_out(fused_feat)
|
69 |
+
emos_pred = self.softmax(emos_out)
|
70 |
+
return emos_pred
|
71 |
+
|
72 |
+
|
73 |
+
class MiniGPTBase(BaseModel):
|
74 |
+
"""
|
75 |
+
Base class for MiniGPT-4 and MiniGPT-v2
|
76 |
+
"""
|
77 |
+
|
78 |
+
def __init__(
|
79 |
+
self,
|
80 |
+
vit_model="eva_clip_g",
|
81 |
+
img_size=224,
|
82 |
+
drop_path_rate=0,
|
83 |
+
use_grad_checkpoint=False,
|
84 |
+
vit_precision="fp16",
|
85 |
+
freeze_vit=True,
|
86 |
+
llama_model="",
|
87 |
+
max_txt_len=32,
|
88 |
+
max_context_len=3800,
|
89 |
+
prompt_template="",
|
90 |
+
end_sym='\n',
|
91 |
+
low_resource=False, # use 8 bit and put vit in cpu
|
92 |
+
device_8bit=0, # the device of 8bit model should be set when loading and cannot be changed anymore.
|
93 |
+
lora_r=0, # lora_r means lora is not used
|
94 |
+
lora_target_modules=["q_proj", "v_proj"],
|
95 |
+
lora_alpha=16,
|
96 |
+
lora_dropout=0.05,
|
97 |
+
):
|
98 |
+
super().__init__()
|
99 |
+
|
100 |
+
self.llama_model, self.llama_tokenizer = self.init_llm(
|
101 |
+
llama_model_path=llama_model,
|
102 |
+
low_resource=low_resource,
|
103 |
+
low_res_device=device_8bit,
|
104 |
+
lora_r=lora_r,
|
105 |
+
lora_target_modules=lora_target_modules,
|
106 |
+
lora_alpha=lora_alpha,
|
107 |
+
lora_dropout=lora_dropout,
|
108 |
+
)
|
109 |
+
|
110 |
+
self.visual_encoder, self.ln_vision = self.init_vision_encoder(
|
111 |
+
vit_model, img_size, drop_path_rate, use_grad_checkpoint, vit_precision, freeze_vit
|
112 |
+
)
|
113 |
+
|
114 |
+
self.max_txt_len = max_txt_len
|
115 |
+
self.max_context_len = max_context_len
|
116 |
+
self.end_sym = end_sym
|
117 |
+
|
118 |
+
self.prompt_template = prompt_template
|
119 |
+
self.prompt_list = []
|
120 |
+
|
121 |
+
self.attention = Attention(output_dim=6)
|
122 |
+
self.CEloss = nn.CrossEntropyLoss()
|
123 |
+
|
124 |
+
def vit_to_cpu(self):
|
125 |
+
self.ln_vision.to("cpu")
|
126 |
+
self.ln_vision.float()
|
127 |
+
self.visual_encoder.to("cpu")
|
128 |
+
self.visual_encoder.float()
|
129 |
+
|
130 |
+
def get_context_emb(self, prompt, img_list):
|
131 |
+
device = img_list[0].device
|
132 |
+
|
133 |
+
prompt_segs = prompt.split('<VideoHere>')
|
134 |
+
assert len(prompt_segs) == len(img_list) + 1, "Unmatched numbers of image placeholders and images."
|
135 |
+
seg_tokens = [
|
136 |
+
self.llama_tokenizer(
|
137 |
+
seg, return_tensors="pt", add_special_tokens=i==0).to(device).input_ids # only add bos to the first seg
|
138 |
+
for i, seg in enumerate(prompt_segs)
|
139 |
+
]
|
140 |
+
seg_embs = [self.embed_tokens(seg_t) for seg_t in seg_tokens]
|
141 |
+
|
142 |
+
mixed_embs = [emb for pair in zip(seg_embs[:-1], img_list) for emb in pair] + [seg_embs[-1]]
|
143 |
+
mixed_embs = torch.cat(mixed_embs, dim=1)
|
144 |
+
return mixed_embs
|
145 |
+
|
146 |
+
def prompt_wrap(self, img_embeds, atts_img, prompts, lengths=None):
|
147 |
+
if prompts is None or len(prompts) == 0:
|
148 |
+
# prompts is not provided, just return the original image embedding
|
149 |
+
return img_embeds, atts_img
|
150 |
+
elif img_embeds is None:
|
151 |
+
# prompt is provided but there is no image embedding. return the prompt embedding in right padding
|
152 |
+
self.llama_tokenizer.padding_side = "right"
|
153 |
+
prompt_tokens = self.llama_tokenizer(
|
154 |
+
prompts,
|
155 |
+
return_tensors="pt",
|
156 |
+
padding="longest",
|
157 |
+
add_special_tokens=False
|
158 |
+
).to(self.device)
|
159 |
+
prompt_embeds = self.embed_tokens(prompt_tokens.input_ids)
|
160 |
+
atts_prompt = prompt_tokens.attention_mask
|
161 |
+
return prompt_embeds, atts_prompt
|
162 |
+
else:
|
163 |
+
# return the multi-modal embedding in right padding
|
164 |
+
emb_lists = []
|
165 |
+
if isinstance(prompts, str):
|
166 |
+
prompts = [prompts] * len(img_embeds)
|
167 |
+
|
168 |
+
for idx, (each_img_embed, each_prompt) in enumerate(zip(img_embeds, prompts)):
|
169 |
+
each_video_feature = each_img_embed[-4:] # cls_tk_feats
|
170 |
+
each_img_embed = each_img_embed[:-4]
|
171 |
+
# each_video_feature = each_img_embed[-3:] #
|
172 |
+
# each_img_embed = each_img_embed[:-3]
|
173 |
+
|
174 |
+
pn = each_img_embed.shape[-2]
|
175 |
+
if lengths is not None:
|
176 |
+
each_img_embed = each_img_embed.reshape(-1, each_img_embed.shape[-1])
|
177 |
+
each_img_embed = each_img_embed[:lengths[idx] * pn]
|
178 |
+
|
179 |
+
p_segs = each_prompt.split('<VideoHere>')
|
180 |
+
interleave_emb = []
|
181 |
+
for idx, seg in enumerate(p_segs[:-1]):
|
182 |
+
p_tokens = self.llama_tokenizer(
|
183 |
+
seg, return_tensors="pt", add_special_tokens=False).to(img_embeds.device)
|
184 |
+
p_embed = self.embed_tokens(p_tokens.input_ids)
|
185 |
+
interleave_emb.append(torch.cat([p_embed, each_img_embed[None][:, idx * pn:(idx + 1) * pn]], dim=1))
|
186 |
+
wrapped_emb = torch.cat(interleave_emb, dim=1)
|
187 |
+
|
188 |
+
# 插入video features
|
189 |
+
f_segs = p_segs[-1].split('<FeatureHere>')
|
190 |
+
f_tokens = self.llama_tokenizer(
|
191 |
+
f_segs[0], return_tensors="pt", add_special_tokens=False).to(img_embeds.device)
|
192 |
+
f_embed = self.embed_tokens(f_tokens.input_ids)
|
193 |
+
f_wrapped_emb = torch.cat([f_embed, each_video_feature[None][:] ], dim=1)
|
194 |
+
|
195 |
+
p_tokens = self.llama_tokenizer(
|
196 |
+
# p_segs替换为f_segs
|
197 |
+
f_segs[-1], return_tensors="pt", add_special_tokens=False).to(img_embeds.device)
|
198 |
+
p_embed = self.embed_tokens(p_tokens.input_ids)
|
199 |
+
wrapped_emb = torch.cat([wrapped_emb, f_wrapped_emb, p_embed], dim=1)
|
200 |
+
emb_lists.append(wrapped_emb)
|
201 |
+
|
202 |
+
emb_lens = [emb.shape[1] for emb in emb_lists]
|
203 |
+
pad_emb = self.embed_tokens(torch.tensor(self.llama_tokenizer.pad_token_id, device=img_embeds.device))
|
204 |
+
|
205 |
+
max_length = max(emb_lens) if max(emb_lens) < self.max_context_len else self.max_context_len
|
206 |
+
wrapped_embs = pad_emb.expand(len(emb_lens), max_length, -1).clone()
|
207 |
+
wrapped_atts = torch.zeros([len(emb_lens), max_length], dtype=torch.int, device=img_embeds.device)
|
208 |
+
|
209 |
+
for i, emb in enumerate(emb_lists):
|
210 |
+
length = emb_lens[i] if emb_lens[i] < self.max_context_len else self.max_context_len
|
211 |
+
wrapped_embs[i, :length] = emb[:, :length]
|
212 |
+
wrapped_atts[i, :length] = 1
|
213 |
+
return wrapped_embs, wrapped_atts
|
214 |
+
|
215 |
+
def concat_emb_input_output(self, input_embs, input_atts, output_embs, output_atts):
|
216 |
+
"""
|
217 |
+
Concatenate the batched input embedding and batched output embedding together.
|
218 |
+
Both the input and the output embedding should be right padded.
|
219 |
+
"""
|
220 |
+
input_lens = []
|
221 |
+
cat_embs = []
|
222 |
+
cat_atts = []
|
223 |
+
for i in range(input_embs.size(0)):
|
224 |
+
input_len = input_atts[i].sum()
|
225 |
+
input_lens.append(input_len)
|
226 |
+
cat_embs.append(
|
227 |
+
torch.cat([
|
228 |
+
input_embs[i][:input_len],
|
229 |
+
output_embs[i],
|
230 |
+
input_embs[i][input_len:]
|
231 |
+
])
|
232 |
+
)
|
233 |
+
cat_atts.append(
|
234 |
+
torch.cat([
|
235 |
+
input_atts[i][:input_len],
|
236 |
+
output_atts[i],
|
237 |
+
input_atts[i][input_len:]
|
238 |
+
])
|
239 |
+
)
|
240 |
+
cat_embs = torch.stack(cat_embs)
|
241 |
+
cat_atts = torch.stack(cat_atts)
|
242 |
+
return cat_embs, cat_atts, input_lens
|
243 |
+
|
244 |
+
def tokenize_conversation(self, conv_q, conv_a):
|
245 |
+
"""concatenate conversation and make sure the model is only trained to regress the answer"""
|
246 |
+
|
247 |
+
to_regress_token_ids_list = []
|
248 |
+
targets_list = []
|
249 |
+
|
250 |
+
batch_size = len(conv_q)
|
251 |
+
for batch_idx in range(batch_size):
|
252 |
+
questions, answers = conv_q[batch_idx], conv_a[batch_idx]
|
253 |
+
questions = [self.llama_tokenizer(self.llama_tokenizer.bos_token + q,
|
254 |
+
return_tensors="pt",
|
255 |
+
add_special_tokens=False).to(self.device) for q in questions[1:]] # the first question is handled in the prompt wrap function, skip it
|
256 |
+
answers = [self.llama_tokenizer(a + self.end_sym,
|
257 |
+
return_tensors="pt",
|
258 |
+
add_special_tokens=False).to(self.device) for a in answers]
|
259 |
+
cur_id = []
|
260 |
+
cur_target = []
|
261 |
+
for i in range(len(questions)):
|
262 |
+
cur_id.append(answers[i].input_ids)
|
263 |
+
cur_target.append(answers[i].input_ids)
|
264 |
+
cur_id.append(questions[i].input_ids)
|
265 |
+
cur_target.append(torch.ones_like(questions[i].input_ids) * -100)
|
266 |
+
|
267 |
+
cur_id.append(answers[-1].input_ids)
|
268 |
+
cur_target.append(answers[-1].input_ids)
|
269 |
+
|
270 |
+
cur_id = torch.cat(cur_id, dim=1)
|
271 |
+
cur_target = torch.cat(cur_target, dim=1)
|
272 |
+
to_regress_token_ids_list.append(cur_id)
|
273 |
+
targets_list.append(cur_target)
|
274 |
+
|
275 |
+
max_len = min(max([target.shape[1] for target in targets_list]), self.max_txt_len)
|
276 |
+
to_regress_token_ids = torch.ones([batch_size, max_len],
|
277 |
+
dtype=cur_id.dtype, device=self.device) * self.llama_tokenizer.pad_token_id
|
278 |
+
targets = torch.ones([batch_size, max_len],
|
279 |
+
dtype=cur_id.dtype, device=self.device) * -100
|
280 |
+
for batch_idx in range(batch_size):
|
281 |
+
cur_len = to_regress_token_ids_list[batch_idx].shape[1]
|
282 |
+
to_regress_token_ids[batch_idx, :cur_len] = to_regress_token_ids_list[batch_idx][0, :max_len]
|
283 |
+
targets[batch_idx, :cur_len] = targets_list[batch_idx][0, :max_len]
|
284 |
+
|
285 |
+
to_regress_token_attn = (to_regress_token_ids != self.llama_tokenizer.pad_token_id).to(torch.int)
|
286 |
+
|
287 |
+
return to_regress_token_ids, to_regress_token_attn, targets
|
288 |
+
|
289 |
+
def preparing_embedding(self, samples):
|
290 |
+
### prepare input tokens
|
291 |
+
if 'image' in samples:
|
292 |
+
# img_embeds, img_atts = self.encode_img(samples["image"])
|
293 |
+
img_embeds, img_atts = self.encode_img(samples["image"], samples["video_features"])
|
294 |
+
else:
|
295 |
+
img_embeds = img_atts = None
|
296 |
+
|
297 |
+
if 'conv_q' in samples:
|
298 |
+
# handeling conversation datasets
|
299 |
+
conv_q, conv_a = samples['conv_q'], samples['conv_a']
|
300 |
+
|
301 |
+
connect_sym = samples['connect_sym'][0]
|
302 |
+
conv_q = [q.split(connect_sym)for q in conv_q]
|
303 |
+
conv_a = [a.split(connect_sym) for a in conv_a]
|
304 |
+
|
305 |
+
conv_q = [[self.prompt_template.format(item) for item in items] for items in conv_q]
|
306 |
+
|
307 |
+
cond_embeds, cond_atts = self.prompt_wrap(img_embeds, img_atts, [q[0] for q in conv_q])
|
308 |
+
regress_token_ids, regress_atts, part_targets = self.tokenize_conversation(conv_q, conv_a)
|
309 |
+
|
310 |
+
else:
|
311 |
+
if "instruction_input" in samples:
|
312 |
+
instruction = samples["instruction_input"]
|
313 |
+
elif self.prompt_list:
|
314 |
+
instruction = random.choice(self.prompt_list)
|
315 |
+
else:
|
316 |
+
instruction = None
|
317 |
+
|
318 |
+
if hasattr(self, 'chat_template') and self.chat_template:
|
319 |
+
instruction = [self.prompt_template.format(instruct) for instruct in instruction]
|
320 |
+
|
321 |
+
if 'length' in samples:
|
322 |
+
# the input is a image train (like videos)
|
323 |
+
bsz, pn, hs = img_embeds.shape
|
324 |
+
img_embeds = img_embeds.reshape(len(samples['image']), -1, pn, hs)
|
325 |
+
cond_embeds, cond_atts = self.prompt_wrap(img_embeds, img_atts, instruction, samples['length'])
|
326 |
+
else:
|
327 |
+
cond_embeds, cond_atts = self.prompt_wrap(img_embeds, img_atts, instruction)
|
328 |
+
|
329 |
+
### prepare target tokens
|
330 |
+
self.llama_tokenizer.padding_side = "right"
|
331 |
+
text = [t + self.end_sym for t in samples["answer"]]
|
332 |
+
|
333 |
+
regress_tokens = self.llama_tokenizer(
|
334 |
+
text,
|
335 |
+
return_tensors="pt",
|
336 |
+
padding="longest",
|
337 |
+
truncation=True,
|
338 |
+
max_length=self.max_txt_len,
|
339 |
+
add_special_tokens=False
|
340 |
+
).to(self.device)
|
341 |
+
|
342 |
+
regress_token_ids = regress_tokens.input_ids
|
343 |
+
regress_atts = regress_tokens.attention_mask
|
344 |
+
part_targets = regress_token_ids.masked_fill(
|
345 |
+
regress_token_ids == self.llama_tokenizer.pad_token_id, -100
|
346 |
+
)
|
347 |
+
|
348 |
+
regress_embeds = self.embed_tokens(regress_token_ids)
|
349 |
+
|
350 |
+
return cond_embeds, cond_atts, regress_embeds, regress_atts, part_targets
|
351 |
+
|
352 |
+
def forward(self, samples, reduction='mean'):
|
353 |
+
# import pdb
|
354 |
+
# pdb.set_trace()
|
355 |
+
# samples['image'].shape -> [1, 3, 448, 448]
|
356 |
+
|
357 |
+
# prepare the embedding to condition and the embedding to regress
|
358 |
+
cond_embeds, cond_atts, regress_embeds, regress_atts, part_targets = \
|
359 |
+
self.preparing_embedding(samples)
|
360 |
+
|
361 |
+
# concat the embedding to condition and the embedding to regress
|
362 |
+
inputs_embeds, attention_mask, input_lens = \
|
363 |
+
self.concat_emb_input_output(cond_embeds, cond_atts, regress_embeds, regress_atts)
|
364 |
+
|
365 |
+
# get bos token embedding
|
366 |
+
bos = torch.ones_like(part_targets[:, :1]) * self.llama_tokenizer.bos_token_id
|
367 |
+
bos_embeds = self.embed_tokens(bos)
|
368 |
+
bos_atts = cond_atts[:, :1]
|
369 |
+
|
370 |
+
# add bos token at the begining
|
371 |
+
inputs_embeds = torch.cat([bos_embeds, inputs_embeds], dim=1)
|
372 |
+
attention_mask = torch.cat([bos_atts, attention_mask], dim=1)
|
373 |
+
|
374 |
+
# ensemble the final targets
|
375 |
+
targets = torch.ones([inputs_embeds.shape[0], inputs_embeds.shape[1]],
|
376 |
+
dtype=torch.long).to(self.device).fill_(-100)
|
377 |
+
|
378 |
+
for i, target in enumerate(part_targets):
|
379 |
+
targets[i, input_lens[i]+1:input_lens[i]+len(target)+1] = target # plus 1 for bos
|
380 |
+
|
381 |
+
with self.maybe_autocast():
|
382 |
+
outputs = self.llama_model(
|
383 |
+
inputs_embeds=inputs_embeds,
|
384 |
+
attention_mask=attention_mask,
|
385 |
+
return_dict=True,
|
386 |
+
labels=targets,
|
387 |
+
reduction=reduction,
|
388 |
+
output_hidden_states=True,
|
389 |
+
emotion = samples['emotion'],
|
390 |
+
)
|
391 |
+
loss = outputs.loss
|
392 |
+
|
393 |
+
# import pdb
|
394 |
+
# pdb.set_trace()
|
395 |
+
|
396 |
+
# feature_list = []
|
397 |
+
# with self.maybe_autocast():
|
398 |
+
# video_features = torch.squeeze(samples['video_features'])
|
399 |
+
# video_list = torch.chunk(video_features, chunks=3, dim=0)
|
400 |
+
|
401 |
+
# feature_list.append(video_features[0].unsqueeze(dim=0).requires_grad_())
|
402 |
+
# feature_list.append(video_features[1].unsqueeze(dim=0).requires_grad_())
|
403 |
+
# feature_list.append(video_features[2].unsqueeze(dim=0).requires_grad_())
|
404 |
+
|
405 |
+
# # last
|
406 |
+
# feature_list.append(outputs.hidden_states[-1][:, 6, :].requires_grad_())
|
407 |
+
# feature_list.append(outputs.hidden_states[-1][:, 7, :].requires_grad_())
|
408 |
+
# feature_list.append(outputs.hidden_states[-1][:, 8, :].requires_grad_())
|
409 |
+
# feature_list.append(outputs.hidden_states[-1][:, 9, :].requires_grad_())
|
410 |
+
|
411 |
+
# emos_pred = self.attention(feature_list)
|
412 |
+
# emos_loss = self.CEloss(emos_pred, samples['emotion'])
|
413 |
+
|
414 |
+
emos_loss = loss
|
415 |
+
emos_pred = 0
|
416 |
+
|
417 |
+
return {"loss": loss, "emos_loss": emos_loss, "emos_pred": emos_pred, "emotion": samples['emotion']}
|
418 |
+
|
419 |
+
def embed_tokens(self, token_ids):
|
420 |
+
if hasattr(self.llama_model.base_model, 'model'): ## lora wrapped model
|
421 |
+
embeds = self.llama_model.base_model.model.model.embed_tokens(token_ids)
|
422 |
+
else:
|
423 |
+
embeds = self.llama_model.base_model.embed_tokens(token_ids)
|
424 |
+
return embeds
|
425 |
+
|
426 |
+
@torch.no_grad()
|
427 |
+
def generate(
|
428 |
+
self,
|
429 |
+
images,
|
430 |
+
video_features,
|
431 |
+
texts,
|
432 |
+
num_beams=1,
|
433 |
+
max_new_tokens=20,
|
434 |
+
min_length=1,
|
435 |
+
top_p=0.9,
|
436 |
+
repetition_penalty=1,
|
437 |
+
length_penalty=1,
|
438 |
+
temperature=1,
|
439 |
+
do_sample=False,
|
440 |
+
stop_words_ids=[2],
|
441 |
+
):
|
442 |
+
'''
|
443 |
+
function for generate test use
|
444 |
+
'''
|
445 |
+
|
446 |
+
stopping_criteria = StoppingCriteriaList([StoppingCriteriaSub(
|
447 |
+
stops=[torch.tensor([i]).to(self.device) for i in stop_words_ids])])
|
448 |
+
|
449 |
+
# img_embeds, atts_img = self.encode_img(images.to(self.device))
|
450 |
+
img_embeds, atts_img = self.encode_img(images.to(self.device), video_features.to(self.device))
|
451 |
+
|
452 |
+
image_lists = [[image_emb[None]] for image_emb in img_embeds]
|
453 |
+
|
454 |
+
batch_embs = [self.get_context_emb(text, img_list) for text, img_list in zip(texts, image_lists)]
|
455 |
+
|
456 |
+
batch_size = len(batch_embs)
|
457 |
+
max_len = max([emb.shape[1] for emb in batch_embs])
|
458 |
+
emb_dim = batch_embs[0].shape[2]
|
459 |
+
dtype = batch_embs[0].dtype
|
460 |
+
device = batch_embs[0].device
|
461 |
+
|
462 |
+
embs = torch.zeros([batch_size, max_len, emb_dim], dtype=dtype, device=device)
|
463 |
+
attn_mask = torch.zeros([batch_size, max_len], dtype=torch.int, device=device)
|
464 |
+
for i, emb in enumerate(batch_embs):
|
465 |
+
emb_len = emb.shape[1]
|
466 |
+
embs[i, -emb_len:] = emb[0]
|
467 |
+
attn_mask[i, -emb_len:] = 1
|
468 |
+
|
469 |
+
with self.maybe_autocast():
|
470 |
+
outputs = self.llama_model.generate(
|
471 |
+
inputs_embeds=embs,
|
472 |
+
attention_mask=attn_mask,
|
473 |
+
max_new_tokens=max_new_tokens,
|
474 |
+
num_beams=num_beams,
|
475 |
+
length_penalty=length_penalty,
|
476 |
+
temperature=temperature,
|
477 |
+
do_sample=do_sample,
|
478 |
+
min_length=min_length,
|
479 |
+
top_p=top_p,
|
480 |
+
repetition_penalty=repetition_penalty,
|
481 |
+
# stopping_criteria=stopping_criteria,
|
482 |
+
)
|
483 |
+
|
484 |
+
# with self.maybe_autocast():
|
485 |
+
# outputs = self.llama_model.generate(
|
486 |
+
# inputs_embeds=embs,
|
487 |
+
# attention_mask=attn_mask,
|
488 |
+
# max_new_tokens=max_new_tokens,
|
489 |
+
# num_beams=num_beams,
|
490 |
+
# do_sample=do_sample,
|
491 |
+
# # stopping_criteria=stopping_criteria,
|
492 |
+
# )
|
493 |
+
answers = []
|
494 |
+
for output_token in outputs:
|
495 |
+
if output_token[0] == 0:
|
496 |
+
output_token = output_token[1:]
|
497 |
+
output_texts = self.llama_tokenizer.decode(output_token, skip_special_tokens=True)
|
498 |
+
output_texts = output_texts.split('</s>')[0] # remove the stop sign </s>
|
499 |
+
output_texts = output_texts.replace("<s>", "")
|
500 |
+
output_texts = output_texts.split(r'[/INST]')[-1].strip()
|
501 |
+
answers.append(output_texts)
|
502 |
+
|
503 |
+
return answers
|
504 |
+
|
505 |
+
@torch.no_grad()
|
506 |
+
def multi_select(self, images, texts, answers, num_cand=None):
|
507 |
+
all_losses = []
|
508 |
+
for answer in answers:
|
509 |
+
choice_samples = {
|
510 |
+
'image': images,
|
511 |
+
'instruction_input': texts,
|
512 |
+
'answer': answer
|
513 |
+
}
|
514 |
+
loss = self.forward(choice_samples, reduction='none')['loss'].reshape(-1, 1)
|
515 |
+
all_losses.append(loss)
|
516 |
+
torch.cuda.empty_cache()
|
517 |
+
all_losses = torch.cat(all_losses, dim=-1)
|
518 |
+
if num_cand is not None:
|
519 |
+
for i in range(all_losses.shape[0]):
|
520 |
+
all_losses[i, num_cand[i]:] = 9999
|
521 |
+
output_class_ranks = torch.argsort(all_losses, dim=-1)
|
522 |
+
return output_class_ranks.tolist()
|
minigpt4/models/minigpt_v2.py
ADDED
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
import random
|
3 |
+
|
4 |
+
import torch
|
5 |
+
from torch.cuda.amp import autocast as autocast
|
6 |
+
import torch.nn as nn
|
7 |
+
|
8 |
+
from minigpt4.common.registry import registry
|
9 |
+
from minigpt4.models.base_model import disabled_train
|
10 |
+
from minigpt4.models.minigpt_base import MiniGPTBase
|
11 |
+
from minigpt4.models.Qformer import BertConfig, BertLMHeadModel
|
12 |
+
|
13 |
+
|
14 |
+
@registry.register_model("minigpt_v2")
|
15 |
+
class MiniGPTv2(MiniGPTBase):
|
16 |
+
"""
|
17 |
+
MiniGPT-v2 model
|
18 |
+
"""
|
19 |
+
|
20 |
+
PRETRAINED_MODEL_CONFIG_DICT = {
|
21 |
+
"pretrain": "configs/models/minigpt_v2.yaml",
|
22 |
+
}
|
23 |
+
|
24 |
+
def __init__(
|
25 |
+
self,
|
26 |
+
vit_model="eva_clip_g",
|
27 |
+
img_size=448,
|
28 |
+
drop_path_rate=0,
|
29 |
+
use_grad_checkpoint=False,
|
30 |
+
vit_precision="fp16",
|
31 |
+
freeze_vit=True,
|
32 |
+
llama_model="",
|
33 |
+
prompt_template='[INST] {} [/INST]',
|
34 |
+
max_txt_len=300,
|
35 |
+
end_sym='\n',
|
36 |
+
lora_r=64,
|
37 |
+
lora_target_modules=["q_proj", "v_proj"],
|
38 |
+
lora_alpha=16,
|
39 |
+
lora_dropout=0.05,
|
40 |
+
chat_template=False,
|
41 |
+
use_grad_checkpoint_llm=False,
|
42 |
+
max_context_len=3800,
|
43 |
+
low_resource=False, # use 8 bit and put vit in cpu
|
44 |
+
device_8bit=0, # the device of 8bit model should be set when loading and cannot be changed anymore.
|
45 |
+
):
|
46 |
+
# lora_target_modules = ["q_proj", "v_proj"]
|
47 |
+
# lora_r=128
|
48 |
+
super().__init__(
|
49 |
+
vit_model=vit_model,
|
50 |
+
img_size=img_size,
|
51 |
+
drop_path_rate=drop_path_rate,
|
52 |
+
use_grad_checkpoint=use_grad_checkpoint,
|
53 |
+
vit_precision=vit_precision,
|
54 |
+
freeze_vit=freeze_vit,
|
55 |
+
llama_model=llama_model,
|
56 |
+
max_txt_len=max_txt_len,
|
57 |
+
max_context_len=max_context_len,
|
58 |
+
end_sym=end_sym,
|
59 |
+
prompt_template=prompt_template,
|
60 |
+
low_resource=low_resource,
|
61 |
+
device_8bit=device_8bit,
|
62 |
+
lora_r=lora_r,
|
63 |
+
lora_target_modules=lora_target_modules,
|
64 |
+
lora_alpha=lora_alpha,
|
65 |
+
lora_dropout=lora_dropout,
|
66 |
+
)
|
67 |
+
|
68 |
+
img_f_dim = self.visual_encoder.num_features * 4
|
69 |
+
self.llama_proj = nn.Linear(
|
70 |
+
img_f_dim, self.llama_model.config.hidden_size
|
71 |
+
)
|
72 |
+
|
73 |
+
self.feats_llama_proj1 = nn.Linear(
|
74 |
+
1024, self.llama_model.config.hidden_size
|
75 |
+
)
|
76 |
+
self.feats_llama_proj2 = nn.Linear(
|
77 |
+
1024, self.llama_model.config.hidden_size
|
78 |
+
)
|
79 |
+
self.feats_llama_proj3 = nn.Linear(
|
80 |
+
1024, self.llama_model.config.hidden_size
|
81 |
+
)
|
82 |
+
|
83 |
+
self.cls_tk_llama_proj = nn.Linear(
|
84 |
+
1408, self.llama_model.config.hidden_size
|
85 |
+
)
|
86 |
+
|
87 |
+
self.chat_template = chat_template
|
88 |
+
|
89 |
+
if use_grad_checkpoint_llm:
|
90 |
+
self.llama_model.gradient_checkpointing_enable()
|
91 |
+
|
92 |
+
def encode_img(self, image, video_features):
|
93 |
+
# device = 'cuda:0'
|
94 |
+
device = image.device
|
95 |
+
if len(image.shape) > 4:
|
96 |
+
image = image.reshape(-1, *image.shape[-3:])
|
97 |
+
with self.maybe_autocast():
|
98 |
+
image_feats = self.visual_encoder(image) # [1, 1025, 1408]
|
99 |
+
image_embeds = self.ln_vision(image_feats).to(device) # [1, 1025, 1408]
|
100 |
+
image_cls_tk = image_embeds[:, :1, :] # [1, 1, 1408]
|
101 |
+
cls_tk_feats = self.cls_tk_llama_proj(image_cls_tk) # [1, 1, 4096]
|
102 |
+
image_embeds = image_embeds[:, 1:, :] # [1, 1024, 1408]
|
103 |
+
bs, pn, hs = image_embeds.shape
|
104 |
+
image_embeds = image_embeds.view(bs, int(pn / 4), int(hs * 4)) # [1, 256, 5632]
|
105 |
+
image_inputs_llama = self.llama_proj(image_embeds) # [1, 256, 4096]
|
106 |
+
video_features = video_features.to(device) # [1, 3, 1024]
|
107 |
+
video_features_split = torch.split(video_features, 1, dim=1)
|
108 |
+
output1 = self.feats_llama_proj1(video_features_split[0].squeeze(1))
|
109 |
+
output2 = self.feats_llama_proj2(video_features_split[1].squeeze(1))
|
110 |
+
output3 = self.feats_llama_proj3(video_features_split[2].squeeze(1))
|
111 |
+
video_feats = torch.stack([output1, output2, output3], dim=1)
|
112 |
+
inputs_llama = torch.cat((image_inputs_llama, video_feats, cls_tk_feats), dim=1) # cls_tk_feats
|
113 |
+
# inputs_llama = torch.cat((image_inputs_llama, video_feats), dim=1)
|
114 |
+
|
115 |
+
atts_llama = torch.ones(inputs_llama.size()[:-1], dtype=torch.long).to(image.device)
|
116 |
+
return inputs_llama, atts_llama
|
117 |
+
|
118 |
+
@classmethod
|
119 |
+
def from_config(cls, cfg):
|
120 |
+
vit_model = cfg.get("vit_model", "eva_clip_g")
|
121 |
+
img_size = cfg.get("image_size")
|
122 |
+
llama_model = cfg.get("llama_model")
|
123 |
+
|
124 |
+
drop_path_rate = cfg.get("drop_path_rate", 0)
|
125 |
+
use_grad_checkpoint = cfg.get("use_grad_checkpoint", False)
|
126 |
+
vit_precision = cfg.get("vit_precision", "fp16")
|
127 |
+
freeze_vit = cfg.get("freeze_vit", True)
|
128 |
+
low_resource = cfg.get("low_resource", False)
|
129 |
+
|
130 |
+
prompt_template = cfg.get("prompt_template", '[INST] {} [/INST]')
|
131 |
+
max_txt_len = cfg.get("max_txt_len", 300)
|
132 |
+
end_sym = cfg.get("end_sym", '\n')
|
133 |
+
|
134 |
+
lora_r = cfg.get("lora_r", 64)
|
135 |
+
lora_alpha = cfg.get("lora_alpha", 16)
|
136 |
+
chat_template = cfg.get("chat_template", False)
|
137 |
+
|
138 |
+
use_grad_checkpoint_llm = cfg.get("use_grad_checkpoint_llm", False)
|
139 |
+
max_context_len = cfg.get("max_context_len", 3800)
|
140 |
+
|
141 |
+
model = cls(
|
142 |
+
vit_model=vit_model,
|
143 |
+
img_size=img_size,
|
144 |
+
drop_path_rate=drop_path_rate,
|
145 |
+
use_grad_checkpoint=use_grad_checkpoint,
|
146 |
+
vit_precision=vit_precision,
|
147 |
+
freeze_vit=freeze_vit,
|
148 |
+
llama_model=llama_model,
|
149 |
+
prompt_template=prompt_template,
|
150 |
+
max_txt_len=max_txt_len,
|
151 |
+
low_resource=low_resource,
|
152 |
+
end_sym=end_sym,
|
153 |
+
lora_r=lora_r,
|
154 |
+
lora_alpha=lora_alpha,
|
155 |
+
chat_template=chat_template,
|
156 |
+
use_grad_checkpoint_llm=use_grad_checkpoint_llm,
|
157 |
+
max_context_len=max_context_len,
|
158 |
+
)
|
159 |
+
|
160 |
+
ckpt_path = cfg.get("ckpt", "") # load weights of MiniGPT-4
|
161 |
+
if ckpt_path:
|
162 |
+
print("Load Minigpt-4-LLM Checkpoint: {}".format(ckpt_path))
|
163 |
+
ckpt = torch.load(ckpt_path, map_location="cpu")
|
164 |
+
msg = model.load_state_dict(ckpt['model'], strict=False)
|
165 |
+
|
166 |
+
return model
|
minigpt4/models/modeling_llama.py
ADDED
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
from typing import List, Optional, Tuple, Union
|
3 |
+
|
4 |
+
import torch
|
5 |
+
import torch.nn.functional as F
|
6 |
+
from torch.nn import CrossEntropyLoss
|
7 |
+
|
8 |
+
from transformers.utils import add_start_docstrings_to_model_forward, replace_return_docstrings
|
9 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
10 |
+
from transformers.models.llama.modeling_llama import LLAMA_INPUTS_DOCSTRING, _CONFIG_FOR_DOC
|
11 |
+
from transformers.models.llama.modeling_llama import LlamaForCausalLM as LlamaForCausalLMOrig
|
12 |
+
|
13 |
+
|
14 |
+
class LlamaForCausalLM(LlamaForCausalLMOrig):
|
15 |
+
|
16 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
17 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
18 |
+
def forward(
|
19 |
+
self,
|
20 |
+
input_ids: torch.LongTensor = None,
|
21 |
+
attention_mask: Optional[torch.Tensor] = None,
|
22 |
+
position_ids: Optional[torch.LongTensor] = None,
|
23 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
24 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
25 |
+
labels: Optional[torch.LongTensor] = None,
|
26 |
+
use_cache: Optional[bool] = None,
|
27 |
+
output_attentions: Optional[bool] = None,
|
28 |
+
output_hidden_states: Optional[bool] = None,
|
29 |
+
emotion: Optional[torch.Tensor] = None,
|
30 |
+
return_dict: Optional[bool] = None,
|
31 |
+
reduction: Optional[str] = "mean",
|
32 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
33 |
+
r"""
|
34 |
+
Args:
|
35 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
36 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
37 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
38 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
39 |
+
|
40 |
+
Returns:
|
41 |
+
|
42 |
+
Example:
|
43 |
+
|
44 |
+
```python
|
45 |
+
>>> from transformers import AutoTokenizer, LlamaForCausalLM
|
46 |
+
|
47 |
+
>>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
|
48 |
+
>>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
|
49 |
+
|
50 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
51 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
52 |
+
|
53 |
+
>>> # Generate
|
54 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
55 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
56 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
57 |
+
```"""
|
58 |
+
|
59 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
60 |
+
output_hidden_states = (
|
61 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
62 |
+
)
|
63 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
64 |
+
|
65 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
66 |
+
outputs = self.model(
|
67 |
+
input_ids=input_ids,
|
68 |
+
attention_mask=attention_mask,
|
69 |
+
position_ids=position_ids,
|
70 |
+
past_key_values=past_key_values,
|
71 |
+
inputs_embeds=inputs_embeds,
|
72 |
+
use_cache=use_cache,
|
73 |
+
output_attentions=output_attentions,
|
74 |
+
output_hidden_states=output_hidden_states,
|
75 |
+
return_dict=return_dict,
|
76 |
+
)
|
77 |
+
|
78 |
+
hidden_states = outputs[0]
|
79 |
+
if hasattr(self.config, 'pretraining_tp') and self.config.pretraining_tp > 1:
|
80 |
+
lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
|
81 |
+
logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
|
82 |
+
logits = torch.cat(logits, dim=-1)
|
83 |
+
else:
|
84 |
+
logits = self.lm_head(hidden_states)
|
85 |
+
logits = logits.float()
|
86 |
+
|
87 |
+
loss = None
|
88 |
+
if labels is not None:
|
89 |
+
|
90 |
+
# Shift so that tokens < n predict n
|
91 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
92 |
+
shift_labels = labels[..., 1:].contiguous()
|
93 |
+
# Flatten the tokens
|
94 |
+
loss_fct = CrossEntropyLoss(reduction=reduction)
|
95 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
96 |
+
shift_labels = shift_labels.view(-1)
|
97 |
+
|
98 |
+
# Enable model parallelism
|
99 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
100 |
+
loss = loss_fct(shift_logits, shift_labels)
|
101 |
+
if reduction == "none":
|
102 |
+
loss = loss.view(logits.size(0), -1).mean(1)
|
103 |
+
|
104 |
+
|
105 |
+
|
106 |
+
if not return_dict:
|
107 |
+
output = (logits,) + outputs[1:]
|
108 |
+
return (loss,) + output if loss is not None else output
|
109 |
+
|
110 |
+
return CausalLMOutputWithPast(
|
111 |
+
loss=loss,
|
112 |
+
logits=logits,
|
113 |
+
past_key_values=outputs.past_key_values,
|
114 |
+
hidden_states=outputs.hidden_states,
|
115 |
+
attentions=outputs.attentions,
|
116 |
+
)
|
minigpt4/processors/__init__.py
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Copyright (c) 2022, salesforce.com, inc.
|
3 |
+
All rights reserved.
|
4 |
+
SPDX-License-Identifier: BSD-3-Clause
|
5 |
+
For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause
|
6 |
+
"""
|
7 |
+
|
8 |
+
from minigpt4.processors.base_processor import BaseProcessor
|
9 |
+
from minigpt4.processors.blip_processors import (
|
10 |
+
Blip2ImageTrainProcessor,
|
11 |
+
Blip2ImageEvalProcessor,
|
12 |
+
BlipCaptionProcessor,
|
13 |
+
)
|
14 |
+
|
15 |
+
from minigpt4.common.registry import registry
|
16 |
+
|
17 |
+
__all__ = [
|
18 |
+
"BaseProcessor",
|
19 |
+
"Blip2ImageTrainProcessor",
|
20 |
+
"Blip2ImageEvalProcessor",
|
21 |
+
"BlipCaptionProcessor",
|
22 |
+
]
|
23 |
+
|
24 |
+
|
25 |
+
def load_processor(name, cfg=None):
|
26 |
+
"""
|
27 |
+
Example
|
28 |
+
|
29 |
+
>>> processor = load_processor("alpro_video_train", cfg=None)
|
30 |
+
"""
|
31 |
+
processor = registry.get_processor_class(name).from_config(cfg)
|
32 |
+
|
33 |
+
return processor
|
minigpt4/processors/__pycache__/__init__.cpython-39.pyc
ADDED
Binary file (982 Bytes). View file
|
|
minigpt4/processors/__pycache__/base_processor.cpython-39.pyc
ADDED
Binary file (1.33 kB). View file
|
|
minigpt4/processors/__pycache__/blip_processors.cpython-39.pyc
ADDED
Binary file (4.32 kB). View file
|
|
minigpt4/processors/__pycache__/randaugment.cpython-39.pyc
ADDED
Binary file (12.2 kB). View file
|
|
minigpt4/processors/base_processor.py
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Copyright (c) 2022, salesforce.com, inc.
|
3 |
+
All rights reserved.
|
4 |
+
SPDX-License-Identifier: BSD-3-Clause
|
5 |
+
For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause
|
6 |
+
"""
|
7 |
+
|
8 |
+
from omegaconf import OmegaConf
|
9 |
+
|
10 |
+
|
11 |
+
class BaseProcessor:
|
12 |
+
def __init__(self):
|
13 |
+
self.transform = lambda x: x
|
14 |
+
return
|
15 |
+
|
16 |
+
def __call__(self, item):
|
17 |
+
return self.transform(item)
|
18 |
+
|
19 |
+
@classmethod
|
20 |
+
def from_config(cls, cfg=None):
|
21 |
+
return cls()
|
22 |
+
|
23 |
+
def build(self, **kwargs):
|
24 |
+
cfg = OmegaConf.create(kwargs)
|
25 |
+
|
26 |
+
return self.from_config(cfg)
|
minigpt4/processors/blip_processors.py
ADDED
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Copyright (c) 2022, salesforce.com, inc.
|
3 |
+
All rights reserved.
|
4 |
+
SPDX-License-Identifier: BSD-3-Clause
|
5 |
+
For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause
|
6 |
+
"""
|
7 |
+
|
8 |
+
import re
|
9 |
+
|
10 |
+
from minigpt4.common.registry import registry
|
11 |
+
from minigpt4.processors.base_processor import BaseProcessor
|
12 |
+
from minigpt4.processors.randaugment import RandomAugment
|
13 |
+
from omegaconf import OmegaConf
|
14 |
+
from torchvision import transforms
|
15 |
+
from torchvision.transforms.functional import InterpolationMode
|
16 |
+
|
17 |
+
|
18 |
+
class BlipImageBaseProcessor(BaseProcessor):
|
19 |
+
def __init__(self, mean=None, std=None):
|
20 |
+
if mean is None:
|
21 |
+
mean = (0.48145466, 0.4578275, 0.40821073)
|
22 |
+
if std is None:
|
23 |
+
std = (0.26862954, 0.26130258, 0.27577711)
|
24 |
+
|
25 |
+
self.normalize = transforms.Normalize(mean, std)
|
26 |
+
|
27 |
+
|
28 |
+
@registry.register_processor("blip_caption")
|
29 |
+
class BlipCaptionProcessor(BaseProcessor):
|
30 |
+
def __init__(self, prompt="", max_words=200):
|
31 |
+
self.prompt = prompt
|
32 |
+
self.max_words = max_words
|
33 |
+
|
34 |
+
def __call__(self, caption):
|
35 |
+
caption = self.prompt + self.pre_caption(caption)
|
36 |
+
|
37 |
+
return caption
|
38 |
+
|
39 |
+
@classmethod
|
40 |
+
def from_config(cls, cfg=None):
|
41 |
+
if cfg is None:
|
42 |
+
cfg = OmegaConf.create()
|
43 |
+
|
44 |
+
prompt = cfg.get("prompt", "")
|
45 |
+
max_words = cfg.get("max_words", 200)
|
46 |
+
|
47 |
+
return cls(prompt=prompt, max_words=max_words)
|
48 |
+
|
49 |
+
def pre_caption(self, caption):
|
50 |
+
caption = re.sub(
|
51 |
+
r"([.!\"()*#:;~])",
|
52 |
+
" ",
|
53 |
+
caption.lower(),
|
54 |
+
)
|
55 |
+
caption = re.sub(
|
56 |
+
r"\s{2,}",
|
57 |
+
" ",
|
58 |
+
caption,
|
59 |
+
)
|
60 |
+
caption = caption.rstrip("\n")
|
61 |
+
caption = caption.strip(" ")
|
62 |
+
|
63 |
+
# truncate caption
|
64 |
+
caption_words = caption.split(" ")
|
65 |
+
if len(caption_words) > self.max_words:
|
66 |
+
caption = " ".join(caption_words[: self.max_words])
|
67 |
+
|
68 |
+
return caption
|
69 |
+
|
70 |
+
|
71 |
+
@registry.register_processor("blip2_image_train")
|
72 |
+
class Blip2ImageTrainProcessor(BlipImageBaseProcessor):
|
73 |
+
def __init__(self, image_size=224, mean=None, std=None, min_scale=0.5, max_scale=1.0):
|
74 |
+
super().__init__(mean=mean, std=std)
|
75 |
+
|
76 |
+
self.transform = transforms.Compose(
|
77 |
+
[
|
78 |
+
transforms.Resize(
|
79 |
+
(image_size,image_size),
|
80 |
+
interpolation=InterpolationMode.BICUBIC,
|
81 |
+
),
|
82 |
+
transforms.ToTensor(),
|
83 |
+
self.normalize,
|
84 |
+
]
|
85 |
+
)
|
86 |
+
|
87 |
+
def __call__(self, item):
|
88 |
+
return self.transform(item)
|
89 |
+
|
90 |
+
@classmethod
|
91 |
+
def from_config(cls, cfg=None):
|
92 |
+
if cfg is None:
|
93 |
+
cfg = OmegaConf.create()
|
94 |
+
|
95 |
+
image_size = cfg.get("image_size", 224)
|
96 |
+
|
97 |
+
mean = cfg.get("mean", None)
|
98 |
+
std = cfg.get("std", None)
|
99 |
+
|
100 |
+
min_scale = cfg.get("min_scale", 0.5)
|
101 |
+
max_scale = cfg.get("max_scale", 1.0)
|
102 |
+
|
103 |
+
return cls(
|
104 |
+
image_size=image_size,
|
105 |
+
mean=mean,
|
106 |
+
std=std,
|
107 |
+
min_scale=min_scale,
|
108 |
+
max_scale=max_scale,
|
109 |
+
)
|
110 |
+
|
111 |
+
|
112 |
+
@registry.register_processor("blip2_image_eval")
|
113 |
+
class Blip2ImageEvalProcessor(BlipImageBaseProcessor):
|
114 |
+
def __init__(self, image_size=224, mean=None, std=None):
|
115 |
+
super().__init__(mean=mean, std=std)
|
116 |
+
|
117 |
+
self.transform = transforms.Compose(
|
118 |
+
[
|
119 |
+
transforms.Resize(
|
120 |
+
(image_size, image_size), interpolation=InterpolationMode.BICUBIC
|
121 |
+
),
|
122 |
+
transforms.ToTensor(),
|
123 |
+
self.normalize,
|
124 |
+
]
|
125 |
+
)
|
126 |
+
|
127 |
+
def __call__(self, item):
|
128 |
+
return self.transform(item)
|
129 |
+
|
130 |
+
@classmethod
|
131 |
+
def from_config(cls, cfg=None):
|
132 |
+
if cfg is None:
|
133 |
+
cfg = OmegaConf.create()
|
134 |
+
|
135 |
+
image_size = cfg.get("image_size", 224)
|
136 |
+
|
137 |
+
mean = cfg.get("mean", None)
|
138 |
+
std = cfg.get("std", None)
|
139 |
+
|
140 |
+
return cls(image_size=image_size, mean=mean, std=std)
|
minigpt4/processors/randaugment.py
ADDED
@@ -0,0 +1,398 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Copyright (c) 2022, salesforce.com, inc.
|
3 |
+
All rights reserved.
|
4 |
+
SPDX-License-Identifier: BSD-3-Clause
|
5 |
+
For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause
|
6 |
+
"""
|
7 |
+
|
8 |
+
import cv2
|
9 |
+
import numpy as np
|
10 |
+
|
11 |
+
import torch
|
12 |
+
|
13 |
+
|
14 |
+
## aug functions
|
15 |
+
def identity_func(img):
|
16 |
+
return img
|
17 |
+
|
18 |
+
|
19 |
+
def autocontrast_func(img, cutoff=0):
|
20 |
+
"""
|
21 |
+
same output as PIL.ImageOps.autocontrast
|
22 |
+
"""
|
23 |
+
n_bins = 256
|
24 |
+
|
25 |
+
def tune_channel(ch):
|
26 |
+
n = ch.size
|
27 |
+
cut = cutoff * n // 100
|
28 |
+
if cut == 0:
|
29 |
+
high, low = ch.max(), ch.min()
|
30 |
+
else:
|
31 |
+
hist = cv2.calcHist([ch], [0], None, [n_bins], [0, n_bins])
|
32 |
+
low = np.argwhere(np.cumsum(hist) > cut)
|
33 |
+
low = 0 if low.shape[0] == 0 else low[0]
|
34 |
+
high = np.argwhere(np.cumsum(hist[::-1]) > cut)
|
35 |
+
high = n_bins - 1 if high.shape[0] == 0 else n_bins - 1 - high[0]
|
36 |
+
if high <= low:
|
37 |
+
table = np.arange(n_bins)
|
38 |
+
else:
|
39 |
+
scale = (n_bins - 1) / (high - low)
|
40 |
+
offset = -low * scale
|
41 |
+
table = np.arange(n_bins) * scale + offset
|
42 |
+
table[table < 0] = 0
|
43 |
+
table[table > n_bins - 1] = n_bins - 1
|
44 |
+
table = table.clip(0, 255).astype(np.uint8)
|
45 |
+
return table[ch]
|
46 |
+
|
47 |
+
channels = [tune_channel(ch) for ch in cv2.split(img)]
|
48 |
+
out = cv2.merge(channels)
|
49 |
+
return out
|
50 |
+
|
51 |
+
|
52 |
+
def equalize_func(img):
|
53 |
+
"""
|
54 |
+
same output as PIL.ImageOps.equalize
|
55 |
+
PIL's implementation is different from cv2.equalize
|
56 |
+
"""
|
57 |
+
n_bins = 256
|
58 |
+
|
59 |
+
def tune_channel(ch):
|
60 |
+
hist = cv2.calcHist([ch], [0], None, [n_bins], [0, n_bins])
|
61 |
+
non_zero_hist = hist[hist != 0].reshape(-1)
|
62 |
+
step = np.sum(non_zero_hist[:-1]) // (n_bins - 1)
|
63 |
+
if step == 0:
|
64 |
+
return ch
|
65 |
+
n = np.empty_like(hist)
|
66 |
+
n[0] = step // 2
|
67 |
+
n[1:] = hist[:-1]
|
68 |
+
table = (np.cumsum(n) // step).clip(0, 255).astype(np.uint8)
|
69 |
+
return table[ch]
|
70 |
+
|
71 |
+
channels = [tune_channel(ch) for ch in cv2.split(img)]
|
72 |
+
out = cv2.merge(channels)
|
73 |
+
return out
|
74 |
+
|
75 |
+
|
76 |
+
def rotate_func(img, degree, fill=(0, 0, 0)):
|
77 |
+
"""
|
78 |
+
like PIL, rotate by degree, not radians
|
79 |
+
"""
|
80 |
+
H, W = img.shape[0], img.shape[1]
|
81 |
+
center = W / 2, H / 2
|
82 |
+
M = cv2.getRotationMatrix2D(center, degree, 1)
|
83 |
+
out = cv2.warpAffine(img, M, (W, H), borderValue=fill)
|
84 |
+
return out
|
85 |
+
|
86 |
+
|
87 |
+
def solarize_func(img, thresh=128):
|
88 |
+
"""
|
89 |
+
same output as PIL.ImageOps.posterize
|
90 |
+
"""
|
91 |
+
table = np.array([el if el < thresh else 255 - el for el in range(256)])
|
92 |
+
table = table.clip(0, 255).astype(np.uint8)
|
93 |
+
out = table[img]
|
94 |
+
return out
|
95 |
+
|
96 |
+
|
97 |
+
def color_func(img, factor):
|
98 |
+
"""
|
99 |
+
same output as PIL.ImageEnhance.Color
|
100 |
+
"""
|
101 |
+
## implementation according to PIL definition, quite slow
|
102 |
+
# degenerate = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)[:, :, np.newaxis]
|
103 |
+
# out = blend(degenerate, img, factor)
|
104 |
+
# M = (
|
105 |
+
# np.eye(3) * factor
|
106 |
+
# + np.float32([0.114, 0.587, 0.299]).reshape(3, 1) * (1. - factor)
|
107 |
+
# )[np.newaxis, np.newaxis, :]
|
108 |
+
M = np.float32(
|
109 |
+
[[0.886, -0.114, -0.114], [-0.587, 0.413, -0.587], [-0.299, -0.299, 0.701]]
|
110 |
+
) * factor + np.float32([[0.114], [0.587], [0.299]])
|
111 |
+
out = np.matmul(img, M).clip(0, 255).astype(np.uint8)
|
112 |
+
return out
|
113 |
+
|
114 |
+
|
115 |
+
def contrast_func(img, factor):
|
116 |
+
"""
|
117 |
+
same output as PIL.ImageEnhance.Contrast
|
118 |
+
"""
|
119 |
+
mean = np.sum(np.mean(img, axis=(0, 1)) * np.array([0.114, 0.587, 0.299]))
|
120 |
+
table = (
|
121 |
+
np.array([(el - mean) * factor + mean for el in range(256)])
|
122 |
+
.clip(0, 255)
|
123 |
+
.astype(np.uint8)
|
124 |
+
)
|
125 |
+
out = table[img]
|
126 |
+
return out
|
127 |
+
|
128 |
+
|
129 |
+
def brightness_func(img, factor):
|
130 |
+
"""
|
131 |
+
same output as PIL.ImageEnhance.Contrast
|
132 |
+
"""
|
133 |
+
table = (np.arange(256, dtype=np.float32) * factor).clip(0, 255).astype(np.uint8)
|
134 |
+
out = table[img]
|
135 |
+
return out
|
136 |
+
|
137 |
+
|
138 |
+
def sharpness_func(img, factor):
|
139 |
+
"""
|
140 |
+
The differences the this result and PIL are all on the 4 boundaries, the center
|
141 |
+
areas are same
|
142 |
+
"""
|
143 |
+
kernel = np.ones((3, 3), dtype=np.float32)
|
144 |
+
kernel[1][1] = 5
|
145 |
+
kernel /= 13
|
146 |
+
degenerate = cv2.filter2D(img, -1, kernel)
|
147 |
+
if factor == 0.0:
|
148 |
+
out = degenerate
|
149 |
+
elif factor == 1.0:
|
150 |
+
out = img
|
151 |
+
else:
|
152 |
+
out = img.astype(np.float32)
|
153 |
+
degenerate = degenerate.astype(np.float32)[1:-1, 1:-1, :]
|
154 |
+
out[1:-1, 1:-1, :] = degenerate + factor * (out[1:-1, 1:-1, :] - degenerate)
|
155 |
+
out = out.astype(np.uint8)
|
156 |
+
return out
|
157 |
+
|
158 |
+
|
159 |
+
def shear_x_func(img, factor, fill=(0, 0, 0)):
|
160 |
+
H, W = img.shape[0], img.shape[1]
|
161 |
+
M = np.float32([[1, factor, 0], [0, 1, 0]])
|
162 |
+
out = cv2.warpAffine(
|
163 |
+
img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR
|
164 |
+
).astype(np.uint8)
|
165 |
+
return out
|
166 |
+
|
167 |
+
|
168 |
+
def translate_x_func(img, offset, fill=(0, 0, 0)):
|
169 |
+
"""
|
170 |
+
same output as PIL.Image.transform
|
171 |
+
"""
|
172 |
+
H, W = img.shape[0], img.shape[1]
|
173 |
+
M = np.float32([[1, 0, -offset], [0, 1, 0]])
|
174 |
+
out = cv2.warpAffine(
|
175 |
+
img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR
|
176 |
+
).astype(np.uint8)
|
177 |
+
return out
|
178 |
+
|
179 |
+
|
180 |
+
def translate_y_func(img, offset, fill=(0, 0, 0)):
|
181 |
+
"""
|
182 |
+
same output as PIL.Image.transform
|
183 |
+
"""
|
184 |
+
H, W = img.shape[0], img.shape[1]
|
185 |
+
M = np.float32([[1, 0, 0], [0, 1, -offset]])
|
186 |
+
out = cv2.warpAffine(
|
187 |
+
img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR
|
188 |
+
).astype(np.uint8)
|
189 |
+
return out
|
190 |
+
|
191 |
+
|
192 |
+
def posterize_func(img, bits):
|
193 |
+
"""
|
194 |
+
same output as PIL.ImageOps.posterize
|
195 |
+
"""
|
196 |
+
out = np.bitwise_and(img, np.uint8(255 << (8 - bits)))
|
197 |
+
return out
|
198 |
+
|
199 |
+
|
200 |
+
def shear_y_func(img, factor, fill=(0, 0, 0)):
|
201 |
+
H, W = img.shape[0], img.shape[1]
|
202 |
+
M = np.float32([[1, 0, 0], [factor, 1, 0]])
|
203 |
+
out = cv2.warpAffine(
|
204 |
+
img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR
|
205 |
+
).astype(np.uint8)
|
206 |
+
return out
|
207 |
+
|
208 |
+
|
209 |
+
def cutout_func(img, pad_size, replace=(0, 0, 0)):
|
210 |
+
replace = np.array(replace, dtype=np.uint8)
|
211 |
+
H, W = img.shape[0], img.shape[1]
|
212 |
+
rh, rw = np.random.random(2)
|
213 |
+
pad_size = pad_size // 2
|
214 |
+
ch, cw = int(rh * H), int(rw * W)
|
215 |
+
x1, x2 = max(ch - pad_size, 0), min(ch + pad_size, H)
|
216 |
+
y1, y2 = max(cw - pad_size, 0), min(cw + pad_size, W)
|
217 |
+
out = img.copy()
|
218 |
+
out[x1:x2, y1:y2, :] = replace
|
219 |
+
return out
|
220 |
+
|
221 |
+
|
222 |
+
### level to args
|
223 |
+
def enhance_level_to_args(MAX_LEVEL):
|
224 |
+
def level_to_args(level):
|
225 |
+
return ((level / MAX_LEVEL) * 1.8 + 0.1,)
|
226 |
+
|
227 |
+
return level_to_args
|
228 |
+
|
229 |
+
|
230 |
+
def shear_level_to_args(MAX_LEVEL, replace_value):
|
231 |
+
def level_to_args(level):
|
232 |
+
level = (level / MAX_LEVEL) * 0.3
|
233 |
+
if np.random.random() > 0.5:
|
234 |
+
level = -level
|
235 |
+
return (level, replace_value)
|
236 |
+
|
237 |
+
return level_to_args
|
238 |
+
|
239 |
+
|
240 |
+
def translate_level_to_args(translate_const, MAX_LEVEL, replace_value):
|
241 |
+
def level_to_args(level):
|
242 |
+
level = (level / MAX_LEVEL) * float(translate_const)
|
243 |
+
if np.random.random() > 0.5:
|
244 |
+
level = -level
|
245 |
+
return (level, replace_value)
|
246 |
+
|
247 |
+
return level_to_args
|
248 |
+
|
249 |
+
|
250 |
+
def cutout_level_to_args(cutout_const, MAX_LEVEL, replace_value):
|
251 |
+
def level_to_args(level):
|
252 |
+
level = int((level / MAX_LEVEL) * cutout_const)
|
253 |
+
return (level, replace_value)
|
254 |
+
|
255 |
+
return level_to_args
|
256 |
+
|
257 |
+
|
258 |
+
def solarize_level_to_args(MAX_LEVEL):
|
259 |
+
def level_to_args(level):
|
260 |
+
level = int((level / MAX_LEVEL) * 256)
|
261 |
+
return (level,)
|
262 |
+
|
263 |
+
return level_to_args
|
264 |
+
|
265 |
+
|
266 |
+
def none_level_to_args(level):
|
267 |
+
return ()
|
268 |
+
|
269 |
+
|
270 |
+
def posterize_level_to_args(MAX_LEVEL):
|
271 |
+
def level_to_args(level):
|
272 |
+
level = int((level / MAX_LEVEL) * 4)
|
273 |
+
return (level,)
|
274 |
+
|
275 |
+
return level_to_args
|
276 |
+
|
277 |
+
|
278 |
+
def rotate_level_to_args(MAX_LEVEL, replace_value):
|
279 |
+
def level_to_args(level):
|
280 |
+
level = (level / MAX_LEVEL) * 30
|
281 |
+
if np.random.random() < 0.5:
|
282 |
+
level = -level
|
283 |
+
return (level, replace_value)
|
284 |
+
|
285 |
+
return level_to_args
|
286 |
+
|
287 |
+
|
288 |
+
func_dict = {
|
289 |
+
"Identity": identity_func,
|
290 |
+
"AutoContrast": autocontrast_func,
|
291 |
+
"Equalize": equalize_func,
|
292 |
+
"Rotate": rotate_func,
|
293 |
+
"Solarize": solarize_func,
|
294 |
+
"Color": color_func,
|
295 |
+
"Contrast": contrast_func,
|
296 |
+
"Brightness": brightness_func,
|
297 |
+
"Sharpness": sharpness_func,
|
298 |
+
"ShearX": shear_x_func,
|
299 |
+
"TranslateX": translate_x_func,
|
300 |
+
"TranslateY": translate_y_func,
|
301 |
+
"Posterize": posterize_func,
|
302 |
+
"ShearY": shear_y_func,
|
303 |
+
}
|
304 |
+
|
305 |
+
translate_const = 10
|
306 |
+
MAX_LEVEL = 10
|
307 |
+
replace_value = (128, 128, 128)
|
308 |
+
arg_dict = {
|
309 |
+
"Identity": none_level_to_args,
|
310 |
+
"AutoContrast": none_level_to_args,
|
311 |
+
"Equalize": none_level_to_args,
|
312 |
+
"Rotate": rotate_level_to_args(MAX_LEVEL, replace_value),
|
313 |
+
"Solarize": solarize_level_to_args(MAX_LEVEL),
|
314 |
+
"Color": enhance_level_to_args(MAX_LEVEL),
|
315 |
+
"Contrast": enhance_level_to_args(MAX_LEVEL),
|
316 |
+
"Brightness": enhance_level_to_args(MAX_LEVEL),
|
317 |
+
"Sharpness": enhance_level_to_args(MAX_LEVEL),
|
318 |
+
"ShearX": shear_level_to_args(MAX_LEVEL, replace_value),
|
319 |
+
"TranslateX": translate_level_to_args(translate_const, MAX_LEVEL, replace_value),
|
320 |
+
"TranslateY": translate_level_to_args(translate_const, MAX_LEVEL, replace_value),
|
321 |
+
"Posterize": posterize_level_to_args(MAX_LEVEL),
|
322 |
+
"ShearY": shear_level_to_args(MAX_LEVEL, replace_value),
|
323 |
+
}
|
324 |
+
|
325 |
+
|
326 |
+
class RandomAugment(object):
|
327 |
+
def __init__(self, N=2, M=10, isPIL=False, augs=[]):
|
328 |
+
self.N = N
|
329 |
+
self.M = M
|
330 |
+
self.isPIL = isPIL
|
331 |
+
if augs:
|
332 |
+
self.augs = augs
|
333 |
+
else:
|
334 |
+
self.augs = list(arg_dict.keys())
|
335 |
+
|
336 |
+
def get_random_ops(self):
|
337 |
+
sampled_ops = np.random.choice(self.augs, self.N)
|
338 |
+
return [(op, 0.5, self.M) for op in sampled_ops]
|
339 |
+
|
340 |
+
def __call__(self, img):
|
341 |
+
if self.isPIL:
|
342 |
+
img = np.array(img)
|
343 |
+
ops = self.get_random_ops()
|
344 |
+
for name, prob, level in ops:
|
345 |
+
if np.random.random() > prob:
|
346 |
+
continue
|
347 |
+
args = arg_dict[name](level)
|
348 |
+
img = func_dict[name](img, *args)
|
349 |
+
return img
|
350 |
+
|
351 |
+
|
352 |
+
class VideoRandomAugment(object):
|
353 |
+
def __init__(self, N=2, M=10, p=0.0, tensor_in_tensor_out=True, augs=[]):
|
354 |
+
self.N = N
|
355 |
+
self.M = M
|
356 |
+
self.p = p
|
357 |
+
self.tensor_in_tensor_out = tensor_in_tensor_out
|
358 |
+
if augs:
|
359 |
+
self.augs = augs
|
360 |
+
else:
|
361 |
+
self.augs = list(arg_dict.keys())
|
362 |
+
|
363 |
+
def get_random_ops(self):
|
364 |
+
sampled_ops = np.random.choice(self.augs, self.N, replace=False)
|
365 |
+
return [(op, self.M) for op in sampled_ops]
|
366 |
+
|
367 |
+
def __call__(self, frames):
|
368 |
+
assert (
|
369 |
+
frames.shape[-1] == 3
|
370 |
+
), "Expecting last dimension for 3-channels RGB (b, h, w, c)."
|
371 |
+
|
372 |
+
if self.tensor_in_tensor_out:
|
373 |
+
frames = frames.numpy().astype(np.uint8)
|
374 |
+
|
375 |
+
num_frames = frames.shape[0]
|
376 |
+
|
377 |
+
ops = num_frames * [self.get_random_ops()]
|
378 |
+
apply_or_not = num_frames * [np.random.random(size=self.N) > self.p]
|
379 |
+
|
380 |
+
frames = torch.stack(
|
381 |
+
list(map(self._aug, frames, ops, apply_or_not)), dim=0
|
382 |
+
).float()
|
383 |
+
|
384 |
+
return frames
|
385 |
+
|
386 |
+
def _aug(self, img, ops, apply_or_not):
|
387 |
+
for i, (name, level) in enumerate(ops):
|
388 |
+
if not apply_or_not[i]:
|
389 |
+
continue
|
390 |
+
args = arg_dict[name](level)
|
391 |
+
img = func_dict[name](img, *args)
|
392 |
+
return torch.from_numpy(img)
|
393 |
+
|
394 |
+
|
395 |
+
if __name__ == "__main__":
|
396 |
+
a = RandomAugment()
|
397 |
+
img = np.random.randn(32, 32, 3)
|
398 |
+
a(img)
|