jxu124 commited on
Commit
13607a8
·
verified ·
1 Parent(s): fbd81e5

Upload folder using huggingface_hub

Browse files
added_tokens.json ADDED
The diff for this file is too large to render. See raw diff
 
config.json ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation_dropout": 0.0,
3
+ "activation_function": "gelu",
4
+ "add_type_embedding": true,
5
+ "architectures": [
6
+ "TiOModel"
7
+ ],
8
+ "attention_dropout": 0.0,
9
+ "attn_scale_factor": 2.0,
10
+ "auto_map": {
11
+ "AutoConfig": "configuration_tio.TiOConfig",
12
+ "AutoModel": "modeling_tio.TiOModel",
13
+ "AutoModelForCausalLM": "modeling_tio.TiOModel",
14
+ "AutoModelForSeq2SeqLM": "modeling_tio.TiOModel",
15
+ "AutoModelForSequenceClassification": "modeling_tio.TiOModel"
16
+ },
17
+ "bos_token_id": 0,
18
+ "classifier_dropout": 0.0,
19
+ "code_image_size": 128,
20
+ "code_layernorm_embedding": true,
21
+ "d_model": 1280,
22
+ "decoder_attention_heads": 16,
23
+ "decoder_drop_path_rate": 0.0,
24
+ "decoder_ffn_dim": 5120,
25
+ "decoder_layerdrop": 0.0,
26
+ "decoder_layers": 12,
27
+ "decoder_normalize_before": true,
28
+ "decoder_start_token_id": 0,
29
+ "dropout": 0.1,
30
+ "encoder_attention_heads": 16,
31
+ "encoder_drop_path_rate": 0.0,
32
+ "encoder_ffn_dim": 5120,
33
+ "encoder_layerdrop": 0.0,
34
+ "encoder_layers": 24,
35
+ "encoder_normalize_before": true,
36
+ "entangle_position_embedding": false,
37
+ "eos_token_id": 2,
38
+ "forced_eos_token_id": 2,
39
+ "image_bucket_size": 42,
40
+ "init_std": 0.02,
41
+ "is_encoder_decoder": true,
42
+ "label_smoothing": 0.1,
43
+ "layernorm_embedding": true,
44
+ "max_position_embeddings": 1024,
45
+ "model_type": "tio",
46
+ "normformer": true,
47
+ "num_hidden_layers": 24,
48
+ "pad_token_id": 1,
49
+ "patch_layernorm_embedding": true,
50
+ "resnet_drop_path_rate": 0.0,
51
+ "resnet_model_path": null,
52
+ "resnet_type": "resnet152",
53
+ "scale_embedding": false,
54
+ "share_decoder_input_output_embed": true,
55
+ "token_bucket_size": 256,
56
+ "torch_dtype": "float32",
57
+ "transformers_version": "4.36.2",
58
+ "use_cache": false,
59
+ "vocab_size": 59457
60
+ }
configuration_tio.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # [Apache-2.0] Modified from https://github.com/OFA-Sys/OFA
3
+ """ TiO model configuration"""
4
+ import warnings
5
+ from transformers import PretrainedConfig
6
+
7
+
8
+ class TiOConfig(PretrainedConfig):
9
+ r"""
10
+ This is the configuration class to store the configuration of a [`~TiOModel`]. It is used to instantiate an TiO
11
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
12
+ defaults will yield a similar configuration to that of the TiO.
13
+ architecture.
14
+
15
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
16
+ documentation from [`PretrainedConfig`] for more information.
17
+
18
+
19
+ Args:
20
+ vocab_size (`int`, *optional*, defaults to 50265):
21
+ Vocabulary size of the TiO model. Defines the number of different tokens that can be represented by the
22
+ `inputs_ids` passed when calling [`~TiOModel`] or [`~TFTiOModel`].
23
+ d_model (`int`, *optional*, defaults to 1024):
24
+ Dimension of the layers and the pooler layer.
25
+ encoder_layers (`int`, *optional*, defaults to 12):
26
+ Number of encoder layers.
27
+ decoder_layers (`int`, *optional*, defaults to 12):
28
+ Number of decoder layers.
29
+ encoder_attention_heads (`int`, *optional*, defaults to 16):
30
+ Number of attention heads for each attention layer in the Transformer encoder.
31
+ decoder_attention_heads (`int`, *optional*, defaults to 16):
32
+ Number of attention heads for each attention layer in the Transformer decoder.
33
+ decoder_ffn_dim (`int`, *optional*, defaults to 4096):
34
+ Dimension of the "intermediate" (often named feed-forward) layer in decoder.
35
+ encoder_ffn_dim (`int`, *optional*, defaults to 4096):
36
+ Dimension of the "intermediate" (often named feed-forward) layer in decoder.
37
+ activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
38
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
39
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
40
+ dropout (`float`, *optional*, defaults to 0.1):
41
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
42
+ attention_dropout (`float`, *optional*, defaults to 0.0):
43
+ The dropout ratio for the attention probabilities.
44
+ activation_dropout (`float`, *optional*, defaults to 0.0):
45
+ The dropout ratio for activations inside the fully connected layer.
46
+ classifier_dropout (`float`, *optional*, defaults to 0.0):
47
+ The dropout ratio for classifier.
48
+ max_position_embeddings (`int`, *optional*, defaults to 1024):
49
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
50
+ just in case (e.g., 512 or 1024 or 2048).
51
+ init_std (`float`, *optional*, defaults to 0.02):
52
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
53
+ encoder_layerdrop: (`float`, *optional*, defaults to 0.0):
54
+ The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
55
+ for more details.
56
+ decoder_layerdrop: (`float`, *optional*, defaults to 0.0):
57
+ The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
58
+ for more details.
59
+ use_cache (`bool`, *optional*, defaults to `True`):
60
+ Whether or not the model should return the last key/values attentions (not used by all models).
61
+ """
62
+
63
+ model_type = "tio"
64
+ keys_to_ignore_at_inference = ["past_key_values"]
65
+
66
+ attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
67
+
68
+ def __init__(
69
+ self,
70
+ vocab_size=59457,
71
+ max_position_embeddings=1024,
72
+ encoder_layers=4,
73
+ encoder_ffn_dim=512 * 4,
74
+ encoder_attention_heads=8,
75
+ decoder_layers=4,
76
+ decoder_ffn_dim=512 * 4,
77
+ decoder_attention_heads=8,
78
+ encoder_layerdrop=0.0,
79
+ decoder_layerdrop=0.0,
80
+ use_cache=True,
81
+ is_encoder_decoder=True,
82
+ activation_function="gelu",
83
+ d_model=512,
84
+ dropout=0.1,
85
+ attention_dropout=0.0,
86
+ activation_dropout=0.0,
87
+ init_std=0.02,
88
+ classifier_dropout=0.0,
89
+ scale_embedding=False,
90
+ pad_token_id=1,
91
+ bos_token_id=0,
92
+ decoder_start_token_id=0,
93
+ eos_token_id=2,
94
+ forced_eos_token_id=2,
95
+ encoder_normalize_before=True,
96
+ decoder_normalize_before=True,
97
+ normformer=True,
98
+ encoder_drop_path_rate=0.0,
99
+ decoder_drop_path_rate=0.0,
100
+ layernorm_embedding=True,
101
+ patch_layernorm_embedding=True,
102
+ resnet_type="resnet101",
103
+ resnet_model_path=None,
104
+ resnet_drop_path_rate=0.0,
105
+ token_bucket_size=256,
106
+ image_bucket_size=42,
107
+ add_type_embedding=True,
108
+ share_decoder_input_output_embed=True,
109
+ attn_scale_factor=2.0,
110
+ code_layernorm_embedding=True,
111
+ code_image_size=128,
112
+ entangle_position_embedding=False,
113
+ label_smoothing=0.1,
114
+ **kwargs
115
+ ):
116
+ self.vocab_size = vocab_size
117
+ self.max_position_embeddings = max_position_embeddings
118
+ self.d_model = d_model
119
+ self.encoder_ffn_dim = encoder_ffn_dim
120
+ self.encoder_layers = encoder_layers
121
+ self.encoder_attention_heads = encoder_attention_heads
122
+ self.decoder_ffn_dim = decoder_ffn_dim
123
+ self.decoder_layers = decoder_layers
124
+ self.decoder_attention_heads = decoder_attention_heads
125
+ self.dropout = dropout
126
+ self.attention_dropout = attention_dropout
127
+ self.activation_dropout = activation_dropout
128
+ self.activation_function = activation_function
129
+ self.init_std = init_std
130
+ self.encoder_layerdrop = encoder_layerdrop
131
+ self.decoder_layerdrop = decoder_layerdrop
132
+ self.classifier_dropout = classifier_dropout
133
+ self.use_cache = use_cache
134
+ self.num_hidden_layers = encoder_layers
135
+ self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
136
+ self.encoder_normalize_before = encoder_normalize_before
137
+ self.decoder_normalize_before = decoder_normalize_before
138
+ self.normformer = normformer
139
+ self.encoder_drop_path_rate = encoder_drop_path_rate
140
+ self.decoder_drop_path_rate = decoder_drop_path_rate
141
+ self.layernorm_embedding = layernorm_embedding
142
+ self.patch_layernorm_embedding = patch_layernorm_embedding
143
+ self.resnet_type = resnet_type
144
+ self.resnet_model_path = resnet_model_path
145
+ self.resnet_drop_path_rate = resnet_drop_path_rate
146
+ self.token_bucket_size = token_bucket_size
147
+ self.image_bucket_size = image_bucket_size
148
+ self.add_type_embedding = add_type_embedding
149
+ self.share_decoder_input_output_embed = share_decoder_input_output_embed
150
+ self.attn_scale_factor = attn_scale_factor
151
+ self.code_layernorm_embedding = code_layernorm_embedding
152
+ self.code_image_size = code_image_size
153
+ self.entangle_position_embedding = entangle_position_embedding
154
+
155
+ self.label_smoothing = label_smoothing
156
+
157
+ super().__init__(
158
+ pad_token_id=pad_token_id,
159
+ bos_token_id=bos_token_id,
160
+ eos_token_id=eos_token_id,
161
+ is_encoder_decoder=is_encoder_decoder,
162
+ decoder_start_token_id=bos_token_id,
163
+ forced_eos_token_id=forced_eos_token_id,
164
+ **kwargs,
165
+ )
166
+
167
+ # ensure backward compatibility for BART CNN models
168
+ if self.forced_bos_token_id is None and kwargs.get("force_bos_token_to_be_generated", False):
169
+ self.forced_bos_token_id = self.bos_token_id
170
+ warnings.warn(
171
+ f"Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. "
172
+ "The config can simply be saved and uploaded again to be fixed."
173
+ )
generation_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 0,
4
+ "decoder_start_token_id": 0,
5
+ "eos_token_id": 2,
6
+ "forced_eos_token_id": 2,
7
+ "pad_token_id": 1,
8
+ "transformers_version": "4.36.2",
9
+ "use_cache": false
10
+ }
gradio_app.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from threading import Thread
2
+ from typing import Iterator
3
+ from transformers import AutoModel, AutoTokenizer, AutoImageProcessor, TextIteratorStreamer
4
+ from PIL import Image as PILImage
5
+ import tempfile
6
+ import torch
7
+ import gradio as gr
8
+
9
+
10
+ def get_gradio_demo(model, tokenizer, image_processor) -> gr.Interface:
11
+
12
+ def get_prompt(message: str, chat_history: list[tuple[str, str]],
13
+ system_prompt: str) -> str:
14
+ texts = [f'#instruction: {system_prompt}\n', '#context:\n']
15
+ texts += [f"human: {user_input.strip()}\nagent: {response.strip()}\n" for user_input, response in chat_history if isinstance(user_input, str)]
16
+ texts += [f'human: {message.strip()}']
17
+ return ''.join(texts)
18
+
19
+
20
+ def get_input_token_length(message: str, chat_history: list[tuple[str, str]], system_prompt: str) -> int:
21
+ prompt = get_prompt(message, chat_history, system_prompt)
22
+ input_ids = tokenizer([prompt], return_tensors='np', add_special_tokens=False)['input_ids']
23
+ return input_ids.shape[-1]
24
+
25
+
26
+ def run(image: PILImage.Image,
27
+ message: str,
28
+ chat_history: list[tuple[str, str]],
29
+ system_prompt: str,
30
+ max_new_tokens: int = 192,
31
+ temperature: float = 0.1,
32
+ top_p: float = 0.9,
33
+ top_k: int = 50) -> Iterator[str]:
34
+ prompt = get_prompt(message, chat_history, system_prompt)
35
+ patch_images = image_processor([image], return_tensors="pt").pixel_values.to(torch.float16).to('cuda')
36
+ inputs = tokenizer([prompt], return_tensors='pt').to('cuda')
37
+
38
+ streamer = TextIteratorStreamer(tokenizer, timeout=10.) #
39
+ generate_kwargs = dict(
40
+ inputs,
41
+ patch_images=patch_images,
42
+ streamer=streamer,
43
+ max_length=max_new_tokens,
44
+ do_sample=True,
45
+ top_p=top_p,
46
+ top_k=top_k,
47
+ temperature=temperature,
48
+ num_beams=1,
49
+ )
50
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
51
+ t.start()
52
+
53
+ outputs = []
54
+ for text in streamer:
55
+ outputs.append(text)
56
+ yield ''.join(outputs).replace("not yet.", "").replace("<s>", "").replace("</s>", "").strip()
57
+
58
+ # -------
59
+
60
+ DEFAULT_SYSTEM_PROMPT = """can you specify which region the context describes?"""
61
+ MAX_MAX_NEW_TOKENS = 512
62
+ DEFAULT_MAX_NEW_TOKENS = 128
63
+ MAX_INPUT_TOKEN_LENGTH = 512
64
+
65
+ DESCRIPTION = """<h1 align="center">TiO Demo</h1>
66
+ <div align="center">https://huggingface.co/jxu124/TiO</div>
67
+ """
68
+
69
+ LICENSE = """
70
+ <p/>
71
+
72
+ ---
73
+ """
74
+
75
+ if not torch.cuda.is_available():
76
+ DESCRIPTION += '\n<p>Running on CPU 🥶 This demo does not work on CPU.</p>'
77
+
78
+
79
+ def upload_image(file_obj):
80
+ chatbot = [[(file_obj.name,), None]]
81
+ return (gr.update(visible=False), gr.update(interactive=True, placeholder='Type a message...',), chatbot)
82
+
83
+
84
+ def clear_and_save_textbox(message: str) -> tuple[str, str]:
85
+ return '', message
86
+
87
+
88
+ def display_input(message: str,
89
+ history: list[tuple[str, str]]) -> list[tuple[str, str]]:
90
+ if len(history) == 0:
91
+ raise gr.Error(f'Upload an image first and try again.')
92
+ history.append((message, ''))
93
+ return history
94
+
95
+
96
+ def delete_prev_fn(
97
+ history: list[tuple[str, str]]) -> tuple[list[tuple[str, str]], str]:
98
+ try:
99
+ message, _ = history.pop()
100
+ if not isinstance(message, str):
101
+ message, _ = history.pop()
102
+ except IndexError:
103
+ message = ''
104
+ return history, message or ''
105
+
106
+
107
+ def generate(
108
+ message: str,
109
+ history_with_input: list[tuple[str, str]],
110
+ system_prompt: str,
111
+ max_new_tokens: int,
112
+ temperature: float,
113
+ top_p: float,
114
+ top_k: int,
115
+ ) -> Iterator[list[tuple[str, str]]]:
116
+ if max_new_tokens > MAX_MAX_NEW_TOKENS:
117
+ raise ValueError
118
+
119
+ image = PILImage.open(history_with_input[0][0][0])
120
+ history = history_with_input[:-1]
121
+ generator = run(image, message, history, system_prompt, max_new_tokens, temperature, top_p, top_k)
122
+ try:
123
+ first_response = next(generator)
124
+ yield history + [(message, first_response)]
125
+ except StopIteration:
126
+ yield history + [(message, '')]
127
+ for response in generator:
128
+ if "region:" in response:
129
+ bboxes = model.utils.sbbox_to_bbox(response)
130
+ if len(bboxes):
131
+ with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as f:
132
+ model.utils.show_mask(image, bboxes).save(f)
133
+ chatbot = history + [(message, "OK, I see."), (None, (f.name,))]
134
+ else:
135
+ chatbot = history + [(message, response)]
136
+ yield chatbot
137
+
138
+
139
+ def process_example(message: str) -> tuple[str, list[tuple[str, str]]]:
140
+ generator = generate(message, [], DEFAULT_SYSTEM_PROMPT, 192, 1, 0.95, 50)
141
+ for x in generator:
142
+ pass
143
+ return '', x
144
+
145
+
146
+ def check_input_token_length(message: str, chat_history: list[tuple[str, str]], system_prompt: str) -> None:
147
+ input_token_length = get_input_token_length(message, chat_history[:-1], system_prompt)
148
+ if input_token_length > MAX_INPUT_TOKEN_LENGTH:
149
+ raise gr.Error(f'The accumulated input is too long ({input_token_length} > {MAX_INPUT_TOKEN_LENGTH}). Clear your chat history and try again.')
150
+
151
+
152
+ with gr.Blocks() as demo:
153
+ gr.Markdown(DESCRIPTION)
154
+
155
+ with gr.Group():
156
+ chatbot = gr.Chatbot(label='Chatbot')
157
+ imagebox = gr.File(
158
+ file_types=["image"],
159
+ show_label=False,
160
+ )
161
+ with gr.Row():
162
+ textbox = gr.Textbox(
163
+ container=False,
164
+ show_label=False,
165
+ interactive=False,
166
+ placeholder='Upload an image...',
167
+ scale=10,
168
+ )
169
+ submit_button = gr.Button('Submit',
170
+ variant='primary',
171
+ scale=1,
172
+ min_width=0)
173
+ with gr.Row():
174
+ retry_button = gr.Button('🔄 Retry', variant='secondary')
175
+ undo_button = gr.Button('↩️ Undo', variant='secondary')
176
+ clear_button = gr.Button('🗑️ Clear', variant='secondary')
177
+
178
+ saved_input = gr.State()
179
+
180
+ with gr.Accordion(label='Advanced options', open=False):
181
+ system_prompt = gr.Textbox(label='System prompt',
182
+ value=DEFAULT_SYSTEM_PROMPT,
183
+ lines=6)
184
+ max_new_tokens = gr.Slider(
185
+ label='Max new tokens',
186
+ minimum=1,
187
+ maximum=MAX_MAX_NEW_TOKENS,
188
+ step=1,
189
+ value=DEFAULT_MAX_NEW_TOKENS,
190
+ )
191
+ temperature = gr.Slider(
192
+ label='Temperature',
193
+ minimum=0.1,
194
+ maximum=4.0,
195
+ step=0.1,
196
+ value=0.5,
197
+ )
198
+ top_p = gr.Slider(
199
+ label='Top-p (nucleus sampling)',
200
+ minimum=0.05,
201
+ maximum=1.0,
202
+ step=0.05,
203
+ value=0.9,
204
+ )
205
+ top_k = gr.Slider(
206
+ label='Top-k',
207
+ minimum=1,
208
+ maximum=1000,
209
+ step=1,
210
+ value=20,
211
+ )
212
+
213
+ gr.Markdown(LICENSE)
214
+ imagebox.upload(
215
+ fn=upload_image,
216
+ inputs=imagebox,
217
+ outputs=[imagebox, textbox, chatbot],
218
+ api_name=None,
219
+ queue=False,
220
+ )
221
+
222
+ textbox.submit(
223
+ fn=clear_and_save_textbox,
224
+ inputs=textbox,
225
+ outputs=[textbox, saved_input],
226
+ api_name=None,
227
+ queue=False,
228
+ ).then(
229
+ fn=display_input,
230
+ inputs=[saved_input, chatbot],
231
+ outputs=chatbot,
232
+ api_name=None,
233
+ queue=False,
234
+ ).then(
235
+ fn=check_input_token_length,
236
+ inputs=[saved_input, chatbot, system_prompt],
237
+ api_name=None,
238
+ queue=False,
239
+ ).success(
240
+ fn=generate,
241
+ inputs=[
242
+ saved_input,
243
+ chatbot,
244
+ system_prompt,
245
+ max_new_tokens,
246
+ temperature,
247
+ top_p,
248
+ top_k,
249
+ ],
250
+ outputs=chatbot,
251
+ api_name="generate",
252
+ )
253
+
254
+ button_event_preprocess = submit_button.click(
255
+ fn=clear_and_save_textbox,
256
+ inputs=textbox,
257
+ outputs=[textbox, saved_input],
258
+ api_name=None,
259
+ queue=False,
260
+ ).then(
261
+ fn=display_input,
262
+ inputs=[saved_input, chatbot],
263
+ outputs=chatbot,
264
+ api_name=None,
265
+ queue=False,
266
+ ).then(
267
+ fn=check_input_token_length,
268
+ inputs=[saved_input, chatbot, system_prompt],
269
+ api_name=None,
270
+ queue=False,
271
+ ).success(
272
+ fn=generate,
273
+ inputs=[
274
+ saved_input,
275
+ chatbot,
276
+ system_prompt,
277
+ max_new_tokens,
278
+ temperature,
279
+ top_p,
280
+ top_k,
281
+ ],
282
+ outputs=chatbot,
283
+ api_name=None,
284
+ )
285
+
286
+ retry_button.click(
287
+ fn=delete_prev_fn,
288
+ inputs=chatbot,
289
+ outputs=[chatbot, saved_input],
290
+ api_name=None,
291
+ queue=False,
292
+ ).then(
293
+ fn=display_input,
294
+ inputs=[saved_input, chatbot],
295
+ outputs=chatbot,
296
+ api_name=None,
297
+ queue=False,
298
+ ).then(
299
+ fn=generate,
300
+ inputs=[
301
+ saved_input,
302
+ chatbot,
303
+ system_prompt,
304
+ max_new_tokens,
305
+ temperature,
306
+ top_p,
307
+ top_k,
308
+ ],
309
+ outputs=chatbot,
310
+ api_name=None,
311
+ )
312
+
313
+ undo_button.click(
314
+ fn=delete_prev_fn,
315
+ inputs=chatbot,
316
+ outputs=[chatbot, saved_input],
317
+ api_name=None,
318
+ queue=False,
319
+ ).then(
320
+ fn=lambda x: x,
321
+ inputs=[saved_input],
322
+ outputs=textbox,
323
+ api_name=None,
324
+ queue=False,
325
+ )
326
+
327
+ clear_button.click(
328
+ fn=lambda: ([], '', gr.update(value=None, visible=True), gr.update(interactive=False, placeholder='Upload an image...',)),
329
+ outputs=[chatbot, saved_input, imagebox, textbox],
330
+ queue=False,
331
+ api_name=None,
332
+ )
333
+
334
+ return demo
335
+
336
+
337
+ def main(model_id: str = 'jxu124/TiO', host: str = "0.0.0.0", port: int = None):
338
+ assert torch.cuda.is_available()
339
+ model = AutoModel.from_pretrained(model_id, trust_remote_code=True, torch_dtype=torch.float16).cuda()
340
+ tokenizer = AutoTokenizer.from_pretrained(model_id, use_fast=False)
341
+ image_processor = AutoImageProcessor.from_pretrained(model_id)
342
+
343
+ # ---- gradio demo ----
344
+ model.get_gradio_demo(tokenizer, image_processor).queue(max_size=20).launch(server_name=host, server_port=port)
345
+
346
+
347
+ if __name__ == "__main__":
348
+ import fire
349
+ fire.Fire(main)
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b865f121748f39f18d2eb21aa05abc6297cdd65bad27c2922cd55554279ae474
3
+ size 3785310272
modeling_tio.py ADDED
@@ -0,0 +1,2036 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # [Apache-2.0] Modified from https://github.com/OFA-Sys/OFA
3
+ """ PyTorch TiO model."""
4
+
5
+ import math
6
+ import random
7
+ from typing import Optional, Tuple
8
+ from dataclasses import dataclass
9
+
10
+ import torch
11
+ from torch import nn
12
+ from torch.nn import functional as F
13
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
14
+
15
+ from transformers.activations import ACT2FN
16
+ from transformers import PreTrainedModel
17
+ # from ...activations import ACT2FN
18
+ # from ...file_utils import (
19
+ # add_code_sample_docstrings,
20
+ # add_end_docstrings,
21
+ # add_start_docstrings,
22
+ # add_start_docstrings_to_model_forward,
23
+ # replace_return_docstrings,
24
+ # )
25
+ # from ...file_utils import ModelOutput
26
+ # from ...modeling_outputs import (
27
+ # BaseModelOutputWithPastAndCrossAttentions,
28
+ # Seq2SeqLMOutput,
29
+ # Seq2SeqModelOutput,
30
+ # )
31
+ # from ...modeling_utils import PreTrainedModel
32
+ # from ...utils import logging
33
+ from transformers.utils import logging, ModelOutput
34
+ from transformers.modeling_outputs import BaseModelOutputWithPastAndCrossAttentions, Seq2SeqLMOutput, Seq2SeqModelOutput
35
+ from .configuration_tio import TiOConfig
36
+ from .resnet import ResNet
37
+ from torch import Tensor
38
+ from typing import Dict, List, Optional, Tuple
39
+
40
+ logger = logging.get_logger(__name__)
41
+
42
+ _CONFIG_FOR_DOC = "TiOConfig"
43
+ _TOKENIZER_FOR_DOC = "TiOTokenizer"
44
+
45
+ DEFAULT_MAX_SOURCE_POSITIONS = 1024
46
+ DEFAULT_MAX_TARGET_POSITIONS = 1024
47
+
48
+ DEFAULT_MIN_PARAMS_TO_WRAP = int(1e8)
49
+
50
+ try:
51
+ from apex.normalization import FusedLayerNorm as _FusedLayerNorm
52
+
53
+ has_fused_layernorm = True
54
+
55
+ class FusedLayerNorm(_FusedLayerNorm):
56
+ @torch.jit.unused
57
+ def forward(self, x):
58
+ if not x.is_cuda:
59
+ return super().forward(x)
60
+ else:
61
+ with torch.cuda.device(x.device):
62
+ return super().forward(x)
63
+
64
+ except ImportError:
65
+ has_fused_layernorm = False
66
+
67
+
68
+ def LayerNorm(normalized_shape, eps=1e-5, elementwise_affine=True, export=False):
69
+ r"""
70
+ Layer normalization.
71
+ If apex is available, use `FusedLayerNorm` instead.
72
+ """
73
+ if torch.jit.is_scripting():
74
+ export = True
75
+ if not export and torch.cuda.is_available() and has_fused_layernorm:
76
+ return FusedLayerNorm(normalized_shape, eps, elementwise_affine)
77
+ return torch.nn.LayerNorm(normalized_shape, eps, elementwise_affine)
78
+
79
+
80
+ def make_token_bucket_position(bucket_size, max_position=DEFAULT_MAX_SOURCE_POSITIONS):
81
+ r"""
82
+ Make relative position indices for the text.
83
+ """
84
+ context_pos = torch.arange(max_position, dtype=torch.long)[:, None]
85
+ memory_pos = torch.arange(max_position, dtype=torch.long)[None, :]
86
+ relative_pos = context_pos - memory_pos
87
+ sign = torch.sign(relative_pos)
88
+ mid = bucket_size // 2
89
+ abs_pos = torch.where((relative_pos < mid) & (relative_pos > -mid), mid - 1, torch.abs(relative_pos))
90
+ # import pdb; pdb.set_trace()
91
+ log_pos = torch.ceil(torch.log(abs_pos / mid) / math.log((max_position - 1) / mid) * (mid - 1)) + mid
92
+ log_pos = log_pos.int()
93
+ # import numpy as np
94
+ # log_pos = np.ceil(np.log(abs_pos.cpu().numpy() / mid) / math.log((max_position - 1) / mid) * (mid - 1)) + mid
95
+ # log_pos = torch.tensor(log_pos.astype('int64'))
96
+ # log_pos = torch.LongTensor(log_pos.astype('int64'), device=abs_pos.device)
97
+ bucket_pos = torch.where(abs_pos.le(mid), relative_pos, log_pos * sign).long()
98
+ return bucket_pos + bucket_size - 1
99
+
100
+
101
+ def make_image_bucket_position(bucket_size, num_relative_distance):
102
+ r"""
103
+ Make relative position indices for the image.
104
+ """
105
+ coords_h = torch.arange(bucket_size)
106
+ coords_w = torch.arange(bucket_size)
107
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w], indexing="ij")) # 2, Wh, Ww
108
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
109
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
110
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
111
+ relative_coords[:, :, 0] += bucket_size - 1 # shift to start from 0
112
+ relative_coords[:, :, 1] += bucket_size - 1
113
+ relative_coords[:, :, 0] *= 2 * bucket_size - 1
114
+ relative_position_index = torch.zeros(size=(bucket_size * bucket_size + 1,) * 2, dtype=relative_coords.dtype)
115
+ relative_position_index[1:, 1:] = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
116
+ relative_position_index[0, 0:] = num_relative_distance - 3
117
+ relative_position_index[0:, 0] = num_relative_distance - 2
118
+ relative_position_index[0, 0] = num_relative_distance - 1
119
+ return relative_position_index
120
+
121
+
122
+ def new_arange(x, *size):
123
+ r"""
124
+ Return a Tensor of `size` filled with a range function on the device of x.
125
+ If size is empty, using the size of the variable x.
126
+ """
127
+ if len(size) == 0:
128
+ size = x.size()
129
+ return torch.arange(size[-1], device=x.device).expand(*size).contiguous()
130
+
131
+
132
+ def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
133
+ r"""
134
+ Shift input ids one token to the right.
135
+ """
136
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
137
+ shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
138
+ shifted_input_ids[:, 0] = decoder_start_token_id
139
+
140
+ assert pad_token_id is not None, "self.model.config.pad_token_id has to be defined."
141
+ # replace possible -100 values in labels by `pad_token_id`
142
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
143
+
144
+ return shifted_input_ids
145
+
146
+
147
+ def _make_causal_mask(input_ids_shape: torch.Size, dtype: torch.dtype, past_key_values_length: int = 0):
148
+ r"""
149
+ Make causal mask used for uni-directional self-attention.
150
+ """
151
+ bsz, tgt_len = input_ids_shape
152
+ mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min)
153
+ mask_cond = torch.arange(mask.size(-1))
154
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
155
+ mask = mask.to(dtype)
156
+
157
+ if past_key_values_length > 0:
158
+ mask = torch.cat([torch.ones(tgt_len, past_key_values_length, dtype=dtype), mask], dim=-1)
159
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
160
+
161
+
162
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
163
+ r"""
164
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
165
+ """
166
+ bsz, src_len = mask.size()
167
+ tgt_len = tgt_len if tgt_len is not None else src_len
168
+
169
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
170
+ inverted_mask = 1.0 - expanded_mask
171
+
172
+ return inverted_mask.masked_fill(inverted_mask.bool(), torch.finfo(dtype).min)
173
+
174
+
175
+ def Embedding(num_embeddings, embedding_dim, padding_idx=None, zero_init=False):
176
+ r"""
177
+ Embedding for tokens
178
+ """
179
+ m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx)
180
+ nn.init.normal_(m.weight, mean=0, std=embedding_dim**-0.5)
181
+ if padding_idx is not None:
182
+ nn.init.constant_(m.weight[padding_idx], 0)
183
+ if zero_init:
184
+ nn.init.constant_(m.weight, 0)
185
+ return m
186
+
187
+
188
+ def Linear(in_features, out_features, bias=True):
189
+ r"""
190
+ Implementation of linear projection with xavier initialization
191
+ """
192
+ m = nn.Linear(in_features, out_features, bias)
193
+ nn.init.xavier_uniform_(m.weight)
194
+ if bias:
195
+ nn.init.constant_(m.bias, 0.0)
196
+ return m
197
+
198
+
199
+ class LayerDropModuleList(nn.ModuleList):
200
+ r"""
201
+ A LayerDrop implementation based on :class:`torch.nn.ModuleList`.
202
+
203
+ Args:
204
+ p (float): probability of dropping out each layer
205
+ modules (iterable, optional): an iterable of modules to add
206
+ """
207
+
208
+ def __init__(self, p, modules=None):
209
+ super().__init__(modules)
210
+ self.p = p
211
+
212
+ def __iter__(self):
213
+ dropout_probs = torch.empty(len(self)).uniform_()
214
+ for i, m in enumerate(super().__iter__()):
215
+ if not self.training or (dropout_probs[i] > self.p):
216
+ yield m
217
+
218
+
219
+ def drop_path(x, drop_prob: float = 0.0, training: bool = False):
220
+ r"""
221
+ Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
222
+
223
+ Args:
224
+ x (`nn.Modules`): input nn layers.
225
+ drop_prob (`float`): drop path ratio.
226
+ training (`bool`): whether is training or inference.
227
+ """
228
+ if drop_prob == 0.0 or not training:
229
+ return x
230
+ keep_prob = 1 - drop_prob
231
+ shape = (1, x.shape[1], 1)
232
+ random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
233
+ random_tensor.floor_() # binarize
234
+ output = x.div(keep_prob) * random_tensor
235
+ return output
236
+
237
+
238
+ class DropPath(nn.Module):
239
+ r"""
240
+ Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
241
+
242
+ Args:
243
+ drop_prob: drop path ratio.
244
+ """
245
+
246
+ def __init__(self, drop_prob=None):
247
+ super().__init__()
248
+ self.drop_prob = drop_prob
249
+
250
+ def forward(self, x):
251
+ return drop_path(x, self.drop_prob, self.training)
252
+
253
+ def extra_repr(self) -> str:
254
+ return "p={}".format(self.drop_prob)
255
+
256
+
257
+ class TiOAttention(nn.Module):
258
+ r"""
259
+ Multi-headed attention, with additional implementation for NormFormer.
260
+
261
+ Args:
262
+ embed_dim (`int`): embedding dimension.
263
+ num_heads (`int`): the number of attention heads.
264
+ dropout (`float32`): the ratio for dropout.
265
+ is_decoder (`bool`): whether or not decoder attention.
266
+ bias (`bool`): whether to add bias.
267
+ scale_heads (`bool`): whether to learn scaling heads, only for Normformer.
268
+ """
269
+
270
+ def __init__(
271
+ self,
272
+ embed_dim: int,
273
+ num_heads: int,
274
+ dropout: float = 0.0,
275
+ is_decoder: bool = False,
276
+ bias: bool = True,
277
+ scale_heads: bool = True,
278
+ ):
279
+ super().__init__()
280
+ self.embed_dim = embed_dim
281
+ self.num_heads = num_heads
282
+ self.dropout = dropout
283
+ self.head_dim = embed_dim // num_heads
284
+ assert (
285
+ self.head_dim * num_heads == self.embed_dim
286
+ ), f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`: {num_heads})."
287
+ scale_factor=2
288
+ self.scaling = float(self.head_dim * scale_factor) ** -0.5
289
+ self.is_decoder = is_decoder
290
+
291
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
292
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
293
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
294
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
295
+ self.attn_dropout = nn.Dropout(p=dropout)
296
+ self.c_attn = nn.Parameter(torch.ones((self.num_heads,)), requires_grad=True) if scale_heads else None
297
+
298
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
299
+ r"""
300
+ Reshape tensors for multi-head attention.
301
+ """
302
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
303
+
304
+ def forward(
305
+ self,
306
+ hidden_states: torch.Tensor,
307
+ key_value_states: Optional[torch.Tensor] = None,
308
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
309
+ attention_mask: Optional[torch.Tensor] = None,
310
+ output_attentions: bool = False,
311
+ attn_bias: Optional[torch.Tensor] = None,
312
+ ):
313
+ r"""
314
+ Args:
315
+ hidden_states (`torch.FloatTensor` of shape `(bsz, tgt_len, embed_dim)`)`: input states.
316
+ key_value_states (`torch.FloatTensor` of shape (bsz, tgt_len, embed_dim), *optional*): key value states.
317
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*):
318
+ cached past key value states for fast inference.
319
+ attention_mask (`torch.FloatTensor` of shape `(bsz, 1, tgt_len, seq_len)`, *optional*): attention mask.
320
+ output_attentions (`bool`, *optional*): whether to output attention weights of all layers.
321
+ attn_bias (`torch.FloatTensor` of shape `(bsz, 1, tgt_len, src_len)`, *optional*):
322
+ the attention bias for positional information.
323
+
324
+ Returns:
325
+ attn_output (`torch.FloatTensor` of shape `(bsz, tgt_len, embed_dim)`): attention outputs.
326
+ attn_weights_reshaped (`torch.FloatTensor`, *optional*): attention weights of all layers.
327
+ past_key_value (`torch.FloatTensor`, *optional*): cached key value states for fast inference.
328
+ """
329
+
330
+ # if key_value_states are provided this layer is used as a cross-attention layer
331
+ # for the decoder
332
+ is_cross_attention = key_value_states is not None
333
+ bsz, tgt_len, embed_dim = hidden_states.size()
334
+
335
+ # get query proj
336
+ query_states = self.q_proj(hidden_states) * self.scaling
337
+ # get key, value proj
338
+ if is_cross_attention and past_key_value is not None:
339
+ # reuse k,v, cross_attentions
340
+ key_states = past_key_value[0]
341
+ value_states = past_key_value[1]
342
+ elif is_cross_attention:
343
+ # cross_attentions
344
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
345
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
346
+ elif past_key_value is not None:
347
+ # reuse k, v, self_attention
348
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
349
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
350
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
351
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
352
+ else:
353
+ # self_attention
354
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
355
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
356
+
357
+ if self.is_decoder:
358
+ past_key_value = (key_states, value_states)
359
+
360
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
361
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
362
+ key_states = key_states.view(*proj_shape)
363
+ value_states = value_states.view(*proj_shape)
364
+
365
+ src_len = key_states.size(1)
366
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
367
+
368
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
369
+ raise ValueError(
370
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is {attn_weights.size()}"
371
+ )
372
+
373
+ # Add attention bias for positional information
374
+ if attn_bias is not None:
375
+ attn_weights += attn_bias
376
+
377
+ if attention_mask is not None:
378
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
379
+ raise ValueError(
380
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
381
+ )
382
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
383
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
384
+
385
+ attn_weights = F.softmax(attn_weights, dim=-1)
386
+
387
+ if output_attentions:
388
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
389
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
390
+ else:
391
+ attn_weights_reshaped = None
392
+
393
+ attn_probs = self.attn_dropout(attn_weights)
394
+
395
+ attn_output = torch.bmm(attn_probs, value_states)
396
+
397
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
398
+ raise ValueError(
399
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is {attn_output.size()}"
400
+ )
401
+
402
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
403
+ attn_output = attn_output.transpose(1, 2)
404
+ attn_output = attn_output.reshape(bsz, tgt_len, embed_dim)
405
+
406
+ if self.c_attn is not None:
407
+ attn_output = attn_output.view(bsz, tgt_len, self.num_heads, self.head_dim)
408
+ attn_output = torch.einsum("bthd,h->bthd", attn_output, self.c_attn)
409
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
410
+
411
+ attn_output = self.out_proj(attn_output)
412
+
413
+ return attn_output, attn_weights_reshaped, past_key_value
414
+
415
+
416
+ class TiOEncoderLayer(nn.Module):
417
+ r"""
418
+ TiO encoder layer implementation.
419
+
420
+ Args:
421
+ config: configuration for TiO.
422
+ drop_path_rate: the ratio for drop path.
423
+ """
424
+
425
+ def __init__(self, config: TiOConfig, drop_path_rate=0.0):
426
+ super().__init__()
427
+ self.embed_dim = config.d_model
428
+ self.self_attn = TiOAttention(
429
+ embed_dim=self.embed_dim,
430
+ num_heads=config.encoder_attention_heads,
431
+ dropout=config.attention_dropout,
432
+ )
433
+ self.self_attn_layer_norm = LayerNorm(self.embed_dim)
434
+ self.self_attn_mid_layer_norm = LayerNorm(self.embed_dim) if config.normformer else None
435
+ self.dropout = nn.Dropout(config.dropout)
436
+ self.activation_fn = ACT2FN[config.activation_function]
437
+ self.activation_dropout = nn.Dropout(config.activation_dropout)
438
+ self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
439
+ self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
440
+ self.ffn_layer_norm = LayerNorm(config.encoder_ffn_dim) if config.normformer else None
441
+ self.final_layer_norm = LayerNorm(self.embed_dim)
442
+ self.normalize_before = config.encoder_normalize_before
443
+ self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
444
+
445
+ def residual_connection(self, x, residual):
446
+ r"""
447
+ Residual connection with drop path.
448
+ """
449
+ return residual + self.drop_path(x)
450
+
451
+ def forward(
452
+ self,
453
+ hidden_states: torch.Tensor,
454
+ attention_mask: torch.Tensor,
455
+ output_attentions: bool = False,
456
+ attn_bias: Optional[torch.Tensor] = None,
457
+ ):
458
+ r"""
459
+ Args:
460
+ hidden_states (`torch.FloatTensor`): input to the layer of shape *(bsz, src_len, embed_dim)*
461
+ attention_mask (`torch.FloatTensor`): attention mask of size
462
+ *(bsz, 1, src_len, src_len)* where padding elements are indicated by very large negative values.
463
+ output_attentions (`bool`, *optional*):
464
+ whether to return the attentions tensors of all attention layers. See `attentions` under
465
+ returned tensors for more detail.
466
+ attn_bias (`torch.FloatTensor`): bias for positional information.
467
+
468
+ Returns:
469
+ outputs (`tuple(torch.FloatTensor)`):
470
+ output hidden states of size (bsz, src_len, embed_dim), optionally with attention weights.
471
+ """
472
+
473
+ residual = hidden_states
474
+ if self.normalize_before:
475
+ hidden_states = self.self_attn_layer_norm(hidden_states)
476
+ hidden_states, attn_weights, _ = self.self_attn(
477
+ hidden_states=hidden_states,
478
+ attention_mask=attention_mask,
479
+ output_attentions=output_attentions,
480
+ attn_bias=attn_bias,
481
+ )
482
+ if self.self_attn_mid_layer_norm:
483
+ hidden_states = self.self_attn_mid_layer_norm(hidden_states)
484
+ hidden_states = self.dropout(hidden_states)
485
+ hidden_states = self.residual_connection(hidden_states, residual)
486
+ if not self.normalize_before:
487
+ hidden_states = self.self_attn_layer_norm(hidden_states)
488
+
489
+ residual = hidden_states
490
+
491
+ if self.normalize_before:
492
+ hidden_states = self.final_layer_norm(hidden_states)
493
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
494
+ hidden_states = self.activation_dropout(hidden_states)
495
+ if self.ffn_layer_norm:
496
+ hidden_states = self.ffn_layer_norm(hidden_states)
497
+ hidden_states = self.fc2(hidden_states)
498
+ hidden_states = self.dropout(hidden_states)
499
+ hidden_states = self.residual_connection(hidden_states, residual)
500
+ if not self.normalize_before:
501
+ hidden_states = self.final_layer_norm(hidden_states)
502
+
503
+ if hidden_states.dtype == torch.float16 and (
504
+ torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any()
505
+ ):
506
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
507
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
508
+
509
+ outputs = (hidden_states,)
510
+
511
+ if output_attentions:
512
+ outputs += (attn_weights,)
513
+
514
+ return outputs
515
+
516
+
517
+ class TiODecoderLayer(nn.Module):
518
+ r"""
519
+ TiO decoder layer implementation.
520
+
521
+ Args:
522
+ config: configuration for TiO.
523
+ drop_path_rate: the ratio for drop path.
524
+ """
525
+
526
+ def __init__(self, config: TiOConfig, drop_path_rate=0.0):
527
+ super().__init__()
528
+ self.embed_dim = config.d_model
529
+
530
+ self.self_attn = TiOAttention(
531
+ embed_dim=self.embed_dim,
532
+ num_heads=config.decoder_attention_heads,
533
+ dropout=config.attention_dropout,
534
+ is_decoder=True,
535
+ )
536
+ self.dropout = nn.Dropout(p=config.dropout)
537
+ self.activation_fn = ACT2FN[config.activation_function]
538
+ self.activation_dropout = nn.Dropout(p=config.activation_dropout)
539
+
540
+ self.self_attn_layer_norm = LayerNorm(self.embed_dim)
541
+ self.self_attn_mid_layer_norm = LayerNorm(self.embed_dim) if config.normformer else None
542
+ self.cross_attn = TiOAttention(
543
+ self.embed_dim,
544
+ config.decoder_attention_heads,
545
+ dropout=config.attention_dropout,
546
+ is_decoder=True,
547
+ )
548
+ self.cross_attn_layer_norm = LayerNorm(self.embed_dim)
549
+ self.cross_attn_mid_layer_norm = LayerNorm(self.embed_dim) if config.normformer else None
550
+ self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
551
+ self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
552
+ self.ffn_layer_norm = LayerNorm(config.decoder_ffn_dim) if config.normformer else None
553
+ self.final_layer_norm = LayerNorm(self.embed_dim)
554
+ self.normalize_before = config.decoder_normalize_before
555
+ self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
556
+
557
+ def residual_connection(self, x, residual):
558
+ r"""
559
+ Residual connection with drop path.
560
+ """
561
+ return residual + self.drop_path(x)
562
+
563
+ def forward(
564
+ self,
565
+ hidden_states: torch.Tensor,
566
+ attention_mask: Optional[torch.Tensor] = None,
567
+ encoder_hidden_states: Optional[torch.Tensor] = None,
568
+ encoder_attention_mask: Optional[torch.Tensor] = None,
569
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
570
+ output_attentions: Optional[bool] = False,
571
+ use_cache: Optional[bool] = False,
572
+ self_attn_bias: Optional[torch.Tensor] = None,
573
+ cross_attn_bias: Optional[torch.Tensor] = None,
574
+ ):
575
+ r"""
576
+ Args:
577
+ hidden_states (`torch.FloatTensor` of shape `(bsz, seq_len, embed_dim)`): input to the layer.
578
+ attention_mask (`torch.FloatTensor` of shape `(bsz, 1, tgt_len, src_len)`):
579
+ attention mask where padding elements are indicated by very large negative values.
580
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch, seq_len, embed_dim)`):
581
+ cross attention input to the layer.
582
+ encoder_attention_mask (`torch.FloatTensor` of shape `(bsz, 1, tgt_len, src_len)`):
583
+ encoder attention mask where padding elements are indicated by very large negative values.
584
+ past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states
585
+ output_attentions (`bool`, *optional*): whether to return the attentions tensors of all attention layers.
586
+ use_cache (`bool`, *optional*): whether to use cache
587
+ self_attn_bias (`torch.FloatTensor`): self attention bias for positional information.
588
+ cross_attn_bias (`torch.FloatTensor`): cross attention bias for positional information.
589
+ """
590
+
591
+ # Self attention with intermediate layernorm
592
+ residual = hidden_states
593
+ if self.normalize_before:
594
+ hidden_states = self.self_attn_layer_norm(hidden_states)
595
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
596
+ # add present self-attn cache to position 1,2 of present_key_value tuple
597
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
598
+ hidden_states=hidden_states,
599
+ past_key_value=self_attn_past_key_value,
600
+ attention_mask=attention_mask,
601
+ output_attentions=output_attentions,
602
+ attn_bias=self_attn_bias,
603
+ )
604
+ if self.self_attn_mid_layer_norm:
605
+ hidden_states = self.self_attn_mid_layer_norm(hidden_states)
606
+ hidden_states = self.dropout(hidden_states)
607
+ hidden_states = self.residual_connection(hidden_states, residual)
608
+ if not self.normalize_before:
609
+ hidden_states = self.self_attn_layer_norm(hidden_states)
610
+
611
+ # Cross attention with intermediate layernorm
612
+ cross_attn_present_key_value = None
613
+ cross_attn_weights = None
614
+ if encoder_hidden_states is not None:
615
+ residual = hidden_states
616
+ if self.normalize_before:
617
+ hidden_states = self.cross_attn_layer_norm(hidden_states)
618
+ # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
619
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
620
+ hidden_states, cross_attn_weights, cross_attn_present_key_value = self.cross_attn(
621
+ hidden_states=hidden_states,
622
+ key_value_states=encoder_hidden_states,
623
+ attention_mask=encoder_attention_mask,
624
+ past_key_value=cross_attn_past_key_value,
625
+ output_attentions=output_attentions,
626
+ attn_bias=cross_attn_bias,
627
+ )
628
+ if self.cross_attn_mid_layer_norm:
629
+ hidden_states = self.cross_attn_mid_layer_norm(hidden_states)
630
+ hidden_states = self.dropout(hidden_states)
631
+ hidden_states = self.residual_connection(hidden_states, residual)
632
+ if not self.normalize_before:
633
+ hidden_states = self.cross_attn_layer_norm(hidden_states)
634
+
635
+ # add cross-attn to positions 3,4 of present_key_value tuple
636
+ present_key_value = present_key_value + cross_attn_present_key_value
637
+
638
+ # FFN with intermediate layernorm
639
+ residual = hidden_states
640
+ if self.normalize_before:
641
+ hidden_states = self.final_layer_norm(hidden_states)
642
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
643
+ hidden_states = self.activation_dropout(hidden_states)
644
+ if self.ffn_layer_norm:
645
+ hidden_states = self.ffn_layer_norm(hidden_states)
646
+ hidden_states = self.fc2(hidden_states)
647
+ hidden_states = self.dropout(hidden_states)
648
+ hidden_states = self.residual_connection(hidden_states, residual)
649
+ if not self.normalize_before:
650
+ hidden_states = self.final_layer_norm(hidden_states)
651
+
652
+ outputs = (hidden_states,)
653
+
654
+ if output_attentions:
655
+ outputs += (self_attn_weights, cross_attn_weights)
656
+
657
+ if use_cache:
658
+ outputs += (present_key_value,)
659
+
660
+ return outputs
661
+
662
+
663
+ class TiOPreTrainedModel(PreTrainedModel):
664
+ r"""
665
+ Base class TiO
666
+ """
667
+
668
+ config_class = TiOConfig
669
+ base_model_prefix = "model"
670
+ supports_gradient_checkpointing = True
671
+
672
+ def _init_weights(self, module):
673
+ r"""
674
+ Weight initialization which follows BERT.
675
+ """
676
+ std = self.config.init_std
677
+ if isinstance(module, nn.Linear):
678
+ module.weight.data.normal_(mean=0.0, std=std)
679
+ if module.bias is not None:
680
+ module.bias.data.zero_()
681
+ elif isinstance(module, nn.Embedding):
682
+ module.weight.data.normal_(mean=0.0, std=std)
683
+ if module.padding_idx is not None:
684
+ module.weight.data[module.padding_idx].zero_()
685
+
686
+ def _set_gradient_checkpointing(self, module, value=False):
687
+ r"""
688
+ Turn on the switch of gradient checkpointing.
689
+ """
690
+ if isinstance(module, (TiODecoder, TiOEncoder)):
691
+ module.gradient_checkpointing = value
692
+
693
+
694
+ @dataclass
695
+ class TiOEncoderOutput(ModelOutput):
696
+ r"""
697
+ Base class for TiO's outputs.
698
+
699
+ Args:
700
+ last_hidden_state (`torch.FloatTensor` of shape `(bsz, seq_len, hidden)`):
701
+ Sequence of hidden-states at the output of the last layer of the model.
702
+
703
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed
704
+ or when `config.output_hidden_states=True`):
705
+
706
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
707
+ shape `(bsz, seq_len, hidden)`.
708
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
709
+
710
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed
711
+ or when `config.output_attentions=True`):
712
+
713
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(bsz, num_heads, seq_len, seq_len)`.
714
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
715
+ heads.
716
+
717
+ position_embedding (`torch.FloatTensor` of shape `(bsz, seq_len, hidden)`):
718
+ postional embeddings of the inputs.
719
+ """
720
+
721
+ last_hidden_state: torch.FloatTensor = None
722
+ padding_mask: torch.Tensor = None
723
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
724
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
725
+ position_embedding: Optional[torch.FloatTensor] = None
726
+
727
+
728
+ TiO_START_DOCSTRING = r"""
729
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
730
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
731
+ etc.)
732
+
733
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
734
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
735
+ and behavior.
736
+
737
+ Parameters:
738
+ config ([`~TiOConfig`]):
739
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
740
+ load the weights associated with the model, only the configuration. Check out the
741
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
742
+ """
743
+
744
+
745
+ TiO_GENERATION_EXAMPLE = r"""
746
+ Image captioning example:
747
+
748
+ ```python
749
+ >>> from PIL import Image
750
+ >>> from torchvision import transforms
751
+ >>> from transformers import TiOTokenizer, TiOForConditionalGeneration
752
+
753
+ >>> mean, std = [0.5, 0.5, 0.5], [0.5, 0.5, 0.5]
754
+ >>> resolution = 256
755
+ >>> patch_resize_transform = transforms.Compose([
756
+ lambda image: image.convert("RGB"),
757
+ transforms.Resize((resolution, resolution), interpolation=Image.BICUBIC),
758
+ transforms.ToTensor(),
759
+ transforms.Normalize(mean=mean, std=std)
760
+ ])
761
+
762
+ >>> model = TiOForConditionalGeneration.from_pretrained(ckpt_dir)
763
+ >>> tokenizer = TiOTokenizer.from_pretrained(ckpt_dir)
764
+
765
+ >>> txt = " what is the description of the image?"
766
+ >>> inputs = tokenizer([txt], max_length=1024, return_tensors="pt")["input_ids"]
767
+ >>> img = Image.open(path_to_image)
768
+ >>> patch_img = patch_resize_transform(img).unsqueeze(0)
769
+
770
+ >>> gen = model.generate(inputs, patch_img=patch_img, num_beams=4)
771
+ >>> print(tokenizer.decode(gen, skip_special_tokens=True, clean_up_tokenization_spaces=False))
772
+ ```
773
+ """
774
+
775
+
776
+ TiO_INPUTS_DOCSTRING = r"""
777
+ Args:
778
+ input_ids (`torch.LongTensor` of shape `(bsz, seq_len)`):
779
+ indices of input sequence tokens in the vocabular, and padding will be ignored by default;
780
+
781
+ indices can be obtained using [`~TiOTokenizer`].
782
+
783
+ patch_images (`torch.FloatTensor` of shape `(bsz, 3, height, width)`):
784
+ the resized image, which are transformed by the default operations.
785
+ patch_images_2 (`torch.FloatTensor` of shape `(bsz, 3, height, width)`):
786
+ the second (if it exists) image.
787
+ patch_masks (`torch.BoolTensor`): the patches to be masked.
788
+ token_embeddings (`torch.FloatTensor` of shape `(bsz, seq_len, embed_dim)`): token embeddings.
789
+ sample_patch_num (`int`): the number of patches to sample.
790
+ decoder_input_ids (`torch.LongTensor` of shape `(bsz, seq_len)`): indices of the sequence in the vocabulary.
791
+ code_masks (`torch.Tensor` of shape `(bsz, seq_len)`): masks only for code generation.
792
+ attention_mask (`torch.Tensor` of shape `(bsz, seq_len)`): attention mask for decoding.
793
+ encoder_outputs (`TiOEncoderOutput`):
794
+ encoder outputs with hidden states, positional embeddings, and padding masks.
795
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed):
796
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
797
+ shape `(bsz, num_heads, tgt_len, head_size)`) and 2 additional tensors of
798
+ shape `(bsz, num_heads, src_len, head_size)`.
799
+ use_cache (`bool`): whether to use cache for faster inference.
800
+ output_attentions (`bool`): whether to output attention weights.
801
+ output_hidden_states (`bool`): whether to output hidden states.
802
+ return_dict (`bool`): unused. Keep it for generation only.
803
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
804
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
805
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
806
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
807
+ """
808
+
809
+
810
+ class TiOEncoder(TiOPreTrainedModel):
811
+ r"""
812
+ TiO encoder consisting of layers of [`TiOEncoderLayer`].
813
+
814
+ Args:
815
+ config: TiOConfig
816
+ embed_tokens (`nn.Embedding`, *optional*): output embedding
817
+ """
818
+
819
+ def __init__(self, config: TiOConfig, embed_tokens: Optional[nn.Embedding] = None):
820
+ super().__init__(config)
821
+
822
+ self.dropout = nn.Dropout(config.dropout)
823
+ self.encoder_layerdrop = config.encoder_layerdrop
824
+
825
+ embed_dim = config.d_model
826
+ self.padding_idx = config.pad_token_id
827
+ self.max_source_positions = config.max_position_embeddings
828
+ self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
829
+ self.num_attention_heads = config.encoder_attention_heads
830
+
831
+ if getattr(config, "layernorm_embedding", False):
832
+ self.layernorm_embedding = LayerNorm(embed_dim)
833
+ else:
834
+ self.layernorm_embedding = None
835
+
836
+ if embed_tokens is not None:
837
+ self.embed_tokens = embed_tokens
838
+ else:
839
+ self.embed_tokens = nn.Embedding(config.vocab_size, embed_dim, self.padding_idx)
840
+
841
+ if config.add_type_embedding:
842
+ self.type_embedding = Embedding(2, embed_dim, padding_idx=None)
843
+ else:
844
+ self.type_embedding = None
845
+
846
+ if config.resnet_type == "resnet18":
847
+ self.embed_images = ResNet([2, 2, 2], drop_path_rate=config.resnet_drop_path_rate)
848
+ elif config.resnet_type == "resnet34":
849
+ self.embed_images = ResNet([3, 4, 6], drop_path_rate=config.resnet_drop_path_rate)
850
+ elif config.resnet_type == "resnet50":
851
+ self.embed_images = ResNet([3, 4, 6], drop_path_rate=config.resnet_drop_path_rate)
852
+ elif config.resnet_type == "resnet101":
853
+ self.embed_images = ResNet([3, 4, 23], drop_path_rate=config.resnet_drop_path_rate)
854
+ elif config.resnet_type == "resnet152":
855
+ self.embed_images = ResNet([3, 8, 36], drop_path_rate=config.resnet_drop_path_rate)
856
+ else:
857
+ raise NotImplementedError
858
+ self.image_proj = Linear(1024, embed_dim)
859
+
860
+ if config.resnet_model_path:
861
+ resnet_state_dict = torch.load(config.resnet_model_path)
862
+ self.embed_images.load_state_dict(resnet_state_dict)
863
+ if config.patch_layernorm_embedding:
864
+ self.patch_layernorm_embedding = LayerNorm(embed_dim)
865
+ else:
866
+ self.patch_layernorm_embedding = None
867
+
868
+ self.embed_positions = Embedding(self.max_source_positions + 2, embed_dim)
869
+ self.embed_image_positions = Embedding(config.image_bucket_size**2 + 1, embed_dim)
870
+ self.pos_ln = LayerNorm(embed_dim)
871
+ self.image_pos_ln = LayerNorm(embed_dim)
872
+ self.pos_scaling = float(embed_dim / self.num_attention_heads * config.attn_scale_factor) ** -0.5
873
+ self.pos_q_linear = nn.Linear(embed_dim, embed_dim)
874
+ self.pos_k_linear = nn.Linear(embed_dim, embed_dim)
875
+
876
+ if self.encoder_layerdrop > 0.0:
877
+ self.layers = LayerDropModuleList(p=self.encoder_layerdrop)
878
+ else:
879
+ self.layers = nn.ModuleList([])
880
+
881
+ dpr = [x.item() for x in torch.linspace(0, config.encoder_drop_path_rate, config.encoder_layers)]
882
+ self.layers.extend(
883
+ [TiOEncoderLayer(config, drop_path_rate=dpr[i]) for i in range(config.encoder_layers)]
884
+ )
885
+ self.num_layers = len(self.layers)
886
+
887
+ if config.encoder_normalize_before:
888
+ self.layer_norm = LayerNorm(embed_dim)
889
+ else:
890
+ self.layer_norm = None
891
+
892
+ self.token_bucket_size = config.token_bucket_size
893
+ token_num_rel_dis = 2 * config.token_bucket_size - 1
894
+ token_rp_bucket = make_token_bucket_position(config.token_bucket_size)
895
+ self.token_rel_pos_table_list = nn.ModuleList(
896
+ [Embedding(token_num_rel_dis, self.num_attention_heads, zero_init=True) for _ in
897
+ range(config.encoder_layers)]
898
+ )
899
+
900
+ self.image_bucket_size = config.image_bucket_size
901
+ image_num_rel_dis = (2 * config.image_bucket_size - 1) * (2 * config.image_bucket_size - 1) + 3
902
+ image_rp_bucket = make_image_bucket_position(config.image_bucket_size, image_num_rel_dis)
903
+ self.image_rel_pos_table_list = nn.ModuleList(
904
+ [Embedding(image_num_rel_dis, self.num_attention_heads, zero_init=True) for _ in
905
+ range(config.encoder_layers)]
906
+ )
907
+
908
+ if config.layernorm_embedding:
909
+ self.layernorm_embedding = LayerNorm(embed_dim)
910
+ else:
911
+ self.layernorm_embedding = None
912
+
913
+ self.register_buffer("token_rp_bucket", token_rp_bucket)
914
+ self.register_buffer("image_rp_bucket", image_rp_bucket)
915
+ self.entangle_position_embedding = config.entangle_position_embedding
916
+
917
+ self.gradient_checkpointing = False
918
+ # Initialize weights and apply final processing
919
+ self.post_init()
920
+
921
+ def get_input_embeddings(self):
922
+ r"""
923
+ Get the embedding weight.
924
+ """
925
+ return self.embed_tokens
926
+
927
+ def set_input_embeddings(self, value):
928
+ r"""
929
+ Set the weight of embedding with the given tensor.
930
+ """
931
+ self.embed_tokens = value
932
+
933
+ def get_rel_pos_bias(self, x, idx):
934
+ r"""
935
+ Get the relative positional bias of the text, for attention.
936
+ """
937
+
938
+ seq_len = x.size(1)
939
+ rp_bucket = self.token_rp_bucket[:seq_len, :seq_len]
940
+ values = F.embedding(rp_bucket, self.token_rel_pos_table_list[idx].weight)
941
+ values = values.unsqueeze(0).expand(x.size(0), -1, -1, -1)
942
+ values = values.permute([0, 3, 1, 2])
943
+ return values.contiguous()
944
+
945
+ def get_image_rel_pos_bias(self, image_position_ids, idx):
946
+ r"""
947
+ Get the relative positional bias of the image, for attention.
948
+ """
949
+
950
+ bsz, seq_len = image_position_ids.shape
951
+ rp_bucket_size = self.image_rp_bucket.size(1)
952
+
953
+ rp_bucket = self.image_rp_bucket.unsqueeze(0).expand(
954
+ bsz, rp_bucket_size, rp_bucket_size
955
+ ).gather(1, image_position_ids[:, :, None].expand(bsz, seq_len, rp_bucket_size)
956
+ ).gather(2, image_position_ids[:, None, :].expand(bsz, seq_len, seq_len))
957
+ values = F.embedding(rp_bucket, self.image_rel_pos_table_list[idx].weight)
958
+ values = values.permute(0, 3, 1, 2)
959
+ return values
960
+
961
+ def get_patch_images_info(self, patch_images, sample_patch_num, device):
962
+ r"""
963
+ Get the basic information of the resized image.
964
+
965
+ Args:
966
+ patch_images (`torch.FloatTensor` of shape `(bsz, 3, height, width)`): the resized image.
967
+ sample_patch_num (`int`):
968
+ the number of patches to sample. If it is equal to -1, no sampling will be performed.
969
+ device: GPU device.
970
+
971
+ Returns:
972
+ image_embed (`torch.FloatTensor` of shape `(bsz, h * w, hidden)`): the output of the visual encoder.
973
+ image_num_patches (`int`, equal to `h * w`): the number of patches.
974
+ image_padding_mask (`torch.BooleanTensor` of shape `(bsz, h*w)`): image padding mask.
975
+ image_position_ids (`torch.LongTensor` of shape `(bsz, h*w)`): image position ids.
976
+ image_pos_embed (`torch.FloatTensor` of shape (bsz, h*w, hidden)): the positional embedding.
977
+ """
978
+
979
+ image_embed = self.embed_images(patch_images)
980
+ h, w = image_embed.shape[-2:]
981
+ image_num_patches = h * w
982
+ image_padding_mask = patch_images.new_zeros((patch_images.size(0), image_num_patches)).bool()
983
+ image_position_idx = torch.arange(w).unsqueeze(0).expand(h, w) + \
984
+ torch.arange(h).unsqueeze(1) * self.image_bucket_size + 1
985
+ image_position_idx = image_position_idx.view(-1).to(device)
986
+ image_position_ids = image_position_idx[None, :].expand(patch_images.size(0), image_num_patches)
987
+
988
+ image_embed = image_embed.flatten(2).transpose(1, 2)
989
+ if sample_patch_num is not None:
990
+ patch_orders = [
991
+ random.sample(range(image_num_patches), k=sample_patch_num)
992
+ for _ in range(patch_images.size(0))
993
+ ]
994
+ patch_orders = torch.LongTensor(patch_orders, device=device)
995
+ image_embed = image_embed.gather(
996
+ 1, patch_orders.unsqueeze(2).expand(-1, -1, image_embed.size(2))
997
+ )
998
+ image_num_patches = sample_patch_num
999
+ image_padding_mask = image_padding_mask.gather(1, patch_orders)
1000
+ image_position_ids = image_position_ids.gather(1, patch_orders)
1001
+ image_pos_embed = self.embed_image_positions(image_position_ids)
1002
+
1003
+ return image_embed, image_num_patches, image_padding_mask, image_position_ids, image_pos_embed
1004
+
1005
+ def forward_embedding(
1006
+ self,
1007
+ input_ids,
1008
+ image_embed: Optional[torch.Tensor] = None,
1009
+ image_embed_2: Optional[torch.Tensor] = None,
1010
+ token_embedding: Optional[torch.Tensor] = None,
1011
+ pos_embed: Optional[torch.Tensor] = None,
1012
+ image_pos_embed: Optional[torch.Tensor] = None,
1013
+ image_pos_embed_2: Optional[torch.Tensor] = None
1014
+ ):
1015
+ r"""
1016
+ Generate embeddings of both the image and the text.
1017
+ Actually since TiO unifies both unimodal and multimodal data,
1018
+ image inputs are optional.
1019
+
1020
+ Args:
1021
+ input_ids (`torch.LongTensor` of shape `(bsz, seq_len)`): indices of the tokens in the vocabulary.
1022
+ image_embed (`torch.FloatTensor` of shape `(bsz, h*w, embed_dim)`, *optional*): image embeddings.
1023
+ image_embed_2 (`torch.FloatTensor` of shape `(bsz, h*w, embed_dim)`, *optional*):
1024
+ image embeddings of the second image (if it exists).
1025
+ token_embedding (`torch.FloatTensor` of shape `(bsz, seq_len, embed_dim)`, *optional*):
1026
+ input token embeddings to replace the embeddings of input ids.
1027
+ image_pos_embed (`torch.FloatTensor` of shape `(bsz, h*w, embed_dim)`, *optional*):
1028
+ positional embeddings of the image.
1029
+ image_pos_embed_2 (`torch.FloatTensor` of shape `(bsz, h*w, embed_dim)`, *optional*):
1030
+ positional embeddings of the second image.
1031
+
1032
+ Returns:
1033
+ x (`torch.FloatTensor` of shape `(bsz, h*w+seq_len, embed_dim)`): embeddings of the input.
1034
+ embed (`torch.FloatTensor` of shape `(bsz, h*w+seq_len, embed_dim)`):
1035
+ embeddings without adding positional and type embeddings.
1036
+ """
1037
+
1038
+ # embed tokens and positions
1039
+ if token_embedding is None:
1040
+ token_embedding = self.embed_tokens(input_ids)
1041
+ x = embed = self.embed_scale * token_embedding
1042
+ if self.entangle_position_embedding and pos_embed is not None:
1043
+ x += pos_embed
1044
+ if self.type_embedding is not None:
1045
+ x += self.type_embedding(input_ids.new_zeros(x.size()[:2]))
1046
+ if self.layernorm_embedding is not None:
1047
+ x = self.layernorm_embedding(x)
1048
+ x = self.dropout(x)
1049
+
1050
+ # embed raw images
1051
+ if image_embed is not None:
1052
+ image_embed = self.image_proj(image_embed)
1053
+ image_x = image_embed = self.embed_scale * image_embed
1054
+ if self.entangle_position_embedding and image_pos_embed is not None:
1055
+ image_x += image_pos_embed
1056
+ if self.type_embedding is not None:
1057
+ image_x += self.type_embedding(input_ids.new_ones(image_x.size()[:2]))
1058
+ if self.patch_layernorm_embedding is not None:
1059
+ image_x = self.patch_layernorm_embedding(image_x)
1060
+ image_x = self.dropout(image_x)
1061
+ x = torch.cat([image_x, x], dim=1)
1062
+ embed = torch.cat([image_embed, embed], dim=1)
1063
+
1064
+ if image_embed_2 is not None:
1065
+ assert self.type_embedding is not None
1066
+ image_embed_2 = self.image_proj(image_embed_2)
1067
+ image_x_2 = image_embed_2 = self.embed_scale * image_embed_2
1068
+ if self.entangle_position_embedding and image_pos_embed_2 is not None:
1069
+ image_x_2 += image_pos_embed_2
1070
+ if self.type_embedding is not None:
1071
+ image_x_2 += self.type_embedding(input_ids.new_full(image_x_2.size()[:2], fill_value=2))
1072
+ if self.patch_layernorm_embedding is not None:
1073
+ image_x_2 = self.patch_layernorm_embedding(image_x_2)
1074
+ image_x_2 = self.dropout(image_x_2)
1075
+ if self.quant_noise is not None:
1076
+ image_x_2 = self.quant_noise(image_x_2)
1077
+ x = torch.cat([image_x_2, x], dim=1)
1078
+ embed = torch.cat([image_embed_2, embed], dim=1)
1079
+
1080
+ return x, embed
1081
+
1082
+ def reorder_encoder_out(self, encoder_out, new_order):
1083
+ """
1084
+ Reorder encoder output according to *new_order*.
1085
+
1086
+ Args:
1087
+ encoder_out: output from the ``forward()`` method
1088
+ new_order (LongTensor): desired order
1089
+
1090
+ Returns:
1091
+ *encoder_out* rearranged according to *new_order*
1092
+ """
1093
+
1094
+ if "last_hidden_state" not in encoder_out:
1095
+ new_encoder_out = None
1096
+ else:
1097
+ new_encoder_out = encoder_out["last_hidden_state"].index_select(0, new_order)
1098
+
1099
+ if "padding_mask" not in encoder_out:
1100
+ new_encoder_padding_mask = None
1101
+ else:
1102
+ new_encoder_padding_mask = encoder_out["padding_mask"].index_select(0, new_order)
1103
+
1104
+
1105
+ if "position_embedding" not in encoder_out:
1106
+ new_position_embeddings = None
1107
+ else:
1108
+ new_position_embeddings = encoder_out["position_embedding"].index_select(0, new_order)
1109
+
1110
+ if "hidden_states" not in encoder_out:
1111
+ new_encoer_states = None
1112
+ else:
1113
+ encoder_states = encoder_out["hidden_states"]
1114
+ new_encoer_states = ()
1115
+ if len(encoder_states) > 0:
1116
+ for idx, state in enumerate(encoder_states):
1117
+ new_encoer_states += (state.index_select(0, new_order),)
1118
+
1119
+ if "attentions" not in encoder_out:
1120
+ attentions = None
1121
+ else:
1122
+ attentions = encoder_out["attentions"]
1123
+
1124
+ return TiOEncoderOutput(
1125
+ last_hidden_state=new_encoder_out,
1126
+ padding_mask=new_encoder_padding_mask,
1127
+ hidden_states=new_encoer_states,
1128
+ attentions=attentions,
1129
+ position_embedding=new_position_embeddings
1130
+ )
1131
+
1132
+ def forward(
1133
+ self,
1134
+ input_ids=None,
1135
+ patch_images: Optional[torch.Tensor] = None,
1136
+ patch_images_2: Optional[torch.Tensor] = None,
1137
+ patch_masks: Optional[torch.Tensor] = None,
1138
+ output_attentions: bool = False,
1139
+ output_hidden_states: bool = False,
1140
+ token_embeddings: Optional[torch.Tensor] = None,
1141
+ sample_patch_num: Optional[int] = None,
1142
+ ):
1143
+ r"""
1144
+ Args:
1145
+ input_ids (`torch.LongTensor` of shape `(bsz, seq_len)`):
1146
+ indices of input sequence tokens in the vocabular, and padding will be ignored by default;
1147
+
1148
+ indices can be obtained using [`~TiOTokenizer`].
1149
+
1150
+ patch_images (`torch.FloatTensor` of shape `(bsz, 3, height, width)`):
1151
+ the resized image, which are transformed by the default operations.
1152
+ patch_images_2 (`torch.FloatTensor` of shape `(bsz, 3, height, width)`):
1153
+ the second (if it exists) image.
1154
+ patch_masks (`torch.BoolTensor`): the patches to be masked.
1155
+ output_attentions (`bool`): whether to return all attention weights,
1156
+ output_hidden_states (`bool`): whether to return all hidden states.
1157
+ token_embeddings (`torch.FloatTensor` of shape `(bsz, seq_len, embed_dim)`): token embeddings.
1158
+ sample_patch_num (`int`): the number of patches to sample.
1159
+
1160
+ Returns:
1161
+ [`TiOEncoderOutput`]:
1162
+ last_hidden_state (`torch.FloatTensor` of shape `(bsz, seq_len, embed_dim)`):
1163
+ the states of the last layer.
1164
+ padding_mask (`torch.BoolTensor` of shape `(bsz, seq_len)`):
1165
+ the padding mask of the source context.
1166
+ hidden_states (`torch.FloatTensor` of shape `(bsz, seq_len, embed_dim)`):
1167
+ the states of all layers including the embeddings.
1168
+ attentions (`torch.FloatTensor` of shape `(bsz, num_heads, seq_len, seq_len)`):
1169
+ the attention weights of all layers.
1170
+ position_embedding (`torch.FloatTensor` of shape `(bsz, seq_len, embed_dim)`):
1171
+ positional embeddings of the input image and tokens.
1172
+ """
1173
+
1174
+ image_embed = None
1175
+ image_embed_2 = None
1176
+ image_pos_embed = None
1177
+ image_pos_embed_2 = None
1178
+ if patch_images is not None:
1179
+ image_embed, image_num_patches, image_padding_mask, image_position_ids, image_pos_embed = \
1180
+ self.get_patch_images_info(patch_images, sample_patch_num, input_ids.device)
1181
+ # image_padding_mask[~patch_masks] = True # comment the line to temporarily fix the bug of mismatch
1182
+ if patch_images_2 is not None:
1183
+ image_embed_2, image_num_patches_2, image_padding_mask_2, image_position_ids_2, image_pos_embed_2 = \
1184
+ self.get_patch_images_info(patch_images_2, sample_patch_num, input_ids.device)
1185
+ image_padding_mask_2[~patch_masks] = True
1186
+
1187
+ encoder_padding_mask = input_ids.eq(self.padding_idx)
1188
+ if patch_images is not None:
1189
+ encoder_padding_mask = torch.cat([image_padding_mask, encoder_padding_mask], dim=1)
1190
+ if patch_images_2 is not None:
1191
+ encoder_padding_mask = torch.cat([image_padding_mask_2, encoder_padding_mask], dim=1)
1192
+ has_pads = encoder_padding_mask.any()
1193
+
1194
+ pos_embed = self.embed_positions(new_arange(input_ids))
1195
+ x, encoder_embedding = self.forward_embedding(
1196
+ input_ids, image_embed, image_embed_2, token_embeddings,
1197
+ pos_embed, image_pos_embed, image_pos_embed_2
1198
+ )
1199
+
1200
+ # account for padding while computing the representation
1201
+ if has_pads:
1202
+ x = x * (1 - encoder_padding_mask.unsqueeze(-1).type_as(x))
1203
+
1204
+ pos_embed = self.pos_ln(pos_embed)
1205
+ if patch_images is not None:
1206
+ image_pos_embed = self.image_pos_ln(image_pos_embed)
1207
+ pos_embed = torch.cat([image_pos_embed, pos_embed], dim=1)
1208
+ if patch_images_2 is not None:
1209
+ image_pos_embed_2 = self.image_pos_ln(image_pos_embed_2)
1210
+ pos_embed = torch.cat([image_pos_embed_2, pos_embed], dim=1)
1211
+
1212
+ pos_q = self.pos_q_linear(pos_embed).view(
1213
+ x.size(0), x.size(1), self.num_attention_heads, -1
1214
+ ).transpose(1, 2) * self.pos_scaling
1215
+ pos_k = self.pos_k_linear(pos_embed).view(
1216
+ x.size(0), x.size(1), self.num_attention_heads, -1
1217
+ ).transpose(1, 2)
1218
+ abs_pos_bias = torch.matmul(pos_q, pos_k.transpose(2, 3))
1219
+
1220
+ # expand attention_mask
1221
+ if has_pads:
1222
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1223
+ attention_mask = _expand_mask(~encoder_padding_mask, dtype=x.dtype)
1224
+
1225
+ encoder_states = () if output_hidden_states else None
1226
+ all_attentions = () if output_attentions else None
1227
+
1228
+ # encoder layers
1229
+ for idx, layer in enumerate(self.layers):
1230
+ if output_hidden_states:
1231
+ encoder_states += (x,)
1232
+ self_attn_bias = abs_pos_bias.clone()
1233
+ self_attn_bias[:, :, -input_ids.size(1):, -input_ids.size(1):] += self.get_rel_pos_bias(input_ids, idx)
1234
+ if patch_images_2 is not None:
1235
+ self_attn_bias[:, :, :image_num_patches_2, :image_num_patches_2] += \
1236
+ self.get_image_rel_pos_bias(image_position_ids_2, idx)
1237
+ self_attn_bias[:, :, image_num_patches_2:image_num_patches_2 + image_num_patches,
1238
+ image_num_patches_2:image_num_patches_2 + image_num_patches] += \
1239
+ self.get_image_rel_pos_bias(image_position_ids, idx)
1240
+ elif patch_images is not None:
1241
+ self_attn_bias[:, :, :x.size(1) - input_ids.size(1), :x.size(1) - input_ids.size(1)] += \
1242
+ self.get_image_rel_pos_bias(image_position_ids, idx)
1243
+ self_attn_bias = self_attn_bias.reshape(-1, x.size(1), x.size(1))
1244
+
1245
+ hidden_outputs = layer(x, attention_mask if has_pads else None, attn_bias=self_attn_bias, output_attentions=output_attentions)
1246
+ x = hidden_outputs[0]
1247
+
1248
+ if output_attentions:
1249
+ attention = hidden_outputs[1]
1250
+ all_attentions = all_attentions + (attention,)
1251
+
1252
+ if output_hidden_states:
1253
+ encoder_states += (x,)
1254
+
1255
+ if self.layer_norm is not None:
1256
+ x = self.layer_norm(x)
1257
+
1258
+ return TiOEncoderOutput(
1259
+ last_hidden_state=x,
1260
+ padding_mask=encoder_padding_mask,
1261
+ hidden_states=encoder_states,
1262
+ attentions=all_attentions,
1263
+ position_embedding=pos_embed,
1264
+ )
1265
+
1266
+
1267
+ class TiODecoder(TiOPreTrainedModel):
1268
+ r"""
1269
+ TiO decoder consisting of layers of [`TiODecoderLayer`]
1270
+
1271
+ Args:
1272
+ config: TiOConfig
1273
+ embed_tokens (`nn.Embedding`, *optional*): output embedding
1274
+ """
1275
+
1276
+ def __init__(self, config: TiOConfig, embed_tokens: Optional[nn.Embedding] = None, output_projection=None):
1277
+ super().__init__(config)
1278
+ self.dropout = nn.Dropout(config.dropout)
1279
+ self.decoder_layerdrop = config.decoder_layerdrop
1280
+ self.padding_idx = config.pad_token_id
1281
+ self.max_target_positions = config.max_position_embeddings
1282
+ self.embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
1283
+
1284
+ self._future_mask = torch.empty(0)
1285
+ self.share_input_output_embed = config.share_decoder_input_output_embed
1286
+ self.num_attention_heads = config.decoder_attention_heads
1287
+
1288
+ if embed_tokens is not None:
1289
+ self.embed_tokens = embed_tokens
1290
+ else:
1291
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model, self.padding_idx)
1292
+
1293
+ self.embed_dim = config.d_model
1294
+ self.output_embed_dim = config.d_model
1295
+
1296
+ self.layers = nn.ModuleList([TiODecoderLayer(config) for _ in range(config.decoder_layers)])
1297
+ if config.layernorm_embedding:
1298
+ self.layernorm_embedding = LayerNorm(self.embed_dim)
1299
+ else:
1300
+ self.layernorm_embedding = None
1301
+
1302
+ self.window_size = config.code_image_size // 8
1303
+
1304
+ self.embed_positions = Embedding(self.max_target_positions + 2, self.embed_dim)
1305
+ self.embed_image_positions = Embedding(config.image_bucket_size**2 + 1, self.embed_dim)
1306
+ self.pos_ln = LayerNorm(self.embed_dim)
1307
+ self.image_pos_ln = LayerNorm(self.embed_dim)
1308
+ self.pos_scaling = float(self.embed_dim / self.num_attention_heads * config.attn_scale_factor) ** -0.5
1309
+ self.self_pos_q_linear = nn.Linear(self.embed_dim, self.embed_dim)
1310
+ self.self_pos_k_linear = nn.Linear(self.embed_dim, self.embed_dim)
1311
+ self.cross_pos_q_linear = nn.Linear(self.embed_dim, self.embed_dim)
1312
+ self.cross_pos_k_linear = nn.Linear(self.embed_dim, self.embed_dim)
1313
+
1314
+ if config.code_layernorm_embedding:
1315
+ self.code_layernorm_embedding = LayerNorm(self.embed_dim)
1316
+ else:
1317
+ self.code_layernorm_embedding = None
1318
+
1319
+ if self.decoder_layerdrop > 0.0:
1320
+ self.layers = LayerDropModuleList(p=self.decoder_layerdrop)
1321
+ else:
1322
+ self.layers = nn.ModuleList([])
1323
+
1324
+ dpr = [x.item() for x in torch.linspace(0, config.decoder_drop_path_rate, config.decoder_layers)]
1325
+ self.layers.extend([TiODecoderLayer(config, drop_path_rate=dpr[i]) for i in range(config.decoder_layers)])
1326
+ self.num_layers = len(self.layers)
1327
+
1328
+ if config.decoder_normalize_before:
1329
+ self.layer_norm = LayerNorm(self.embed_dim)
1330
+ else:
1331
+ self.layer_norm = None
1332
+
1333
+ self.adaptive_softmax = None
1334
+ self.output_projection = output_projection
1335
+ if self.output_projection is None:
1336
+ self.build_output_projection(config)
1337
+
1338
+ self.token_bucket_size = config.token_bucket_size
1339
+ token_num_rel_dis = 2 * config.token_bucket_size - 1
1340
+ token_rp_bucket = make_token_bucket_position(config.token_bucket_size)
1341
+ self.token_rel_pos_table_list = nn.ModuleList(
1342
+ [
1343
+ Embedding(token_num_rel_dis, self.num_attention_heads, zero_init=True)
1344
+ for _ in range(config.decoder_layers)
1345
+ ]
1346
+ )
1347
+
1348
+ self.image_bucket_size = config.image_bucket_size
1349
+ image_num_rel_dis = (2 * config.image_bucket_size - 1) * (2 * config.image_bucket_size - 1) + 3
1350
+ image_rp_bucket = make_image_bucket_position(config.image_bucket_size, image_num_rel_dis)
1351
+ image_position_idx = torch.arange(self.window_size).unsqueeze(0).expand(self.window_size, self.window_size) + \
1352
+ torch.arange(self.window_size).unsqueeze(1) * config.image_bucket_size + 1
1353
+ image_position_idx = torch.cat([torch.tensor([0]), image_position_idx.view(-1)])
1354
+ image_position_idx = torch.cat([image_position_idx, torch.tensor([1024] * 768)])
1355
+ self.image_rel_pos_table_list = nn.ModuleList(
1356
+ [
1357
+ Embedding(image_num_rel_dis, self.num_attention_heads, zero_init=True)
1358
+ for _ in range(config.decoder_layers)
1359
+ ]
1360
+ )
1361
+
1362
+ self.register_buffer("token_rp_bucket", token_rp_bucket)
1363
+ self.register_buffer("image_rp_bucket", image_rp_bucket)
1364
+ self.register_buffer("image_position_idx", image_position_idx)
1365
+ self.entangle_position_embedding = config.entangle_position_embedding
1366
+
1367
+ self.gradient_checkpointing = False
1368
+ # Initialize weights and apply final processing
1369
+ self.post_init()
1370
+
1371
+ def build_output_projection(self, config):
1372
+ if self.share_input_output_embed:
1373
+ self.output_projection = nn.Linear(
1374
+ self.embed_tokens.weight.shape[1],
1375
+ self.embed_tokens.weight.shape[0],
1376
+ bias=False,
1377
+ )
1378
+ self.output_projection.weight = self.embed_tokens.weight
1379
+ else:
1380
+ self.output_projection = nn.Linear(
1381
+ self.output_embed_dim, config.vocab_size, bias=False
1382
+ )
1383
+ nn.init.normal_(self.output_projection.weight, mean=0, std=self.output_embed_dim**-0.5)
1384
+
1385
+ def get_rel_pos_bias(self, x, idx):
1386
+ r"""
1387
+ Get the relative positional bias of the text, for attention.
1388
+ """
1389
+
1390
+ seq_len = x.size(1)
1391
+ rp_bucket = self.token_rp_bucket[:seq_len, :seq_len]
1392
+ values = F.embedding(rp_bucket, self.token_rel_pos_table_list[idx].weight)
1393
+ values = values.permute([2, 0, 1])
1394
+ return values.contiguous()
1395
+
1396
+ def get_image_rel_pos_bias(self, x, idx):
1397
+ r"""
1398
+ Get the relative positional bias of the image, for attention.
1399
+ """
1400
+
1401
+ seq_len = x.size(1)
1402
+ image_position_idx = self.image_position_idx[:seq_len]
1403
+ rp_bucket = self.image_rp_bucket[image_position_idx][:, image_position_idx]
1404
+ values = F.embedding(rp_bucket, self.image_rel_pos_table_list[idx].weight)
1405
+ values = values.permute(2, 0, 1)
1406
+ return values
1407
+
1408
+ def get_pos_info(self, tgt_pos_embed, src_pos_embed=None, use_image=False):
1409
+ r"""
1410
+ Get the positional information.
1411
+
1412
+ Args:
1413
+ tgt_pos_embed (`torch.FloatTensor` of shape `(bsz, tgt_len, embed_dim)`):
1414
+ the target-side positional embeddings.
1415
+ src_pos_embed (`torch.FloatTensor` of shape `(bsz, src_len, embed_dim)`, *optional*):
1416
+ the source-side positional embeddings.
1417
+ use_image (`bool`): whether to use image.
1418
+
1419
+ Returns:
1420
+ abs_pos_bias (`torch.FloatTensor` of shape `(bsz, src_len, tgt_len, src_len)`):
1421
+ absolute positional bias for attention.
1422
+ """
1423
+
1424
+ batch_size = tgt_pos_embed.size(0)
1425
+ tgt_len = tgt_pos_embed.size(1)
1426
+ tgt_pos_embed = self.image_pos_ln(tgt_pos_embed) if use_image else self.pos_ln(tgt_pos_embed)
1427
+
1428
+ if src_pos_embed is not None:
1429
+ src_len = src_pos_embed.size(1)
1430
+ pos_q = self.cross_pos_q_linear(tgt_pos_embed).view(
1431
+ batch_size, tgt_len, self.num_attention_heads, -1
1432
+ ).transpose(1, 2) * self.pos_scaling
1433
+ pos_k = self.cross_pos_k_linear(src_pos_embed).view(
1434
+ batch_size, src_len, self.num_attention_heads, -1
1435
+ ).transpose(1, 2)
1436
+ else:
1437
+ src_len = tgt_pos_embed.size(1)
1438
+ pos_q = self.self_pos_q_linear(tgt_pos_embed).view(
1439
+ batch_size, tgt_len, self.num_attention_heads, -1
1440
+ ).transpose(1, 2) * self.pos_scaling
1441
+ pos_k = self.self_pos_k_linear(tgt_pos_embed).view(
1442
+ batch_size, src_len, self.num_attention_heads, -1
1443
+ ).transpose(1, 2)
1444
+ abs_pos_bias = torch.matmul(pos_q, pos_k.transpose(2, 3))
1445
+
1446
+ return abs_pos_bias
1447
+
1448
+ def get_input_embeddings(self):
1449
+ r"""
1450
+ Get the input embeddings
1451
+ """
1452
+ return self.embed_tokens
1453
+
1454
+ def set_input_embeddings(self, value):
1455
+ r"""
1456
+ Set the weights of the embeddings with the given tensor.
1457
+ """
1458
+ self.embed_tokens = value
1459
+
1460
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, dtype, past_key_values_length):
1461
+ r"""
1462
+ Create causal mask for unidirectional decoding.
1463
+ [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1464
+ """
1465
+ combined_attention_mask = None
1466
+ if input_shape[-1] > 1:
1467
+ combined_attention_mask = _make_causal_mask(
1468
+ input_shape, dtype, past_key_values_length=past_key_values_length
1469
+ )
1470
+
1471
+ if attention_mask is not None:
1472
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1473
+ expanded_attn_mask = _expand_mask(attention_mask, dtype, tgt_len=input_shape[-1])
1474
+ combined_attention_mask = (
1475
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask.to(expanded_attn_mask.device)
1476
+ )
1477
+
1478
+ return combined_attention_mask
1479
+
1480
+ def max_positions(self):
1481
+ """Maximum output length supported by the decoder."""
1482
+ if self.embed_positions is None:
1483
+ return self.max_target_positions
1484
+ return self.max_target_positions
1485
+
1486
+ def get_normalized_probs(
1487
+ self,
1488
+ net_output: Tuple[Tensor, Optional[Dict[str, List[Optional[Tensor]]]]],
1489
+ log_probs: bool,
1490
+ sample: Optional[Dict[str, Tensor]] = None,
1491
+ ):
1492
+ """Get normalized probabilities (or log probs) from a net's output."""
1493
+ return self.get_normalized_probs_scriptable(net_output, log_probs, sample)
1494
+
1495
+ def get_normalized_probs_scriptable(
1496
+ self,
1497
+ net_output: Tuple[Tensor, Optional[Dict[str, List[Optional[Tensor]]]]],
1498
+ log_probs: bool,
1499
+ sample: Optional[Dict[str, Tensor]] = None,
1500
+ ):
1501
+ """Get normalized probabilities (or log probs) from a net's output."""
1502
+
1503
+ if hasattr(self, "adaptive_softmax") and self.adaptive_softmax is not None:
1504
+ if sample is not None:
1505
+ assert "target" in sample
1506
+ target = sample["target"]
1507
+ else:
1508
+ target = None
1509
+ out = self.adaptive_softmax.get_log_prob(net_output[0], target=target)
1510
+ return out.exp_() if not log_probs else out
1511
+
1512
+ logits = net_output[0]
1513
+ if log_probs:
1514
+ return F.log_softmax(logits, dim=-1)
1515
+ else:
1516
+ return F.softmax(logits, dim=-1)
1517
+
1518
+ def reorder_incremental_state_scripting(
1519
+ self,
1520
+ # incremental_state: Dict[str, Dict[str, Optional[Tensor]]],
1521
+ past_key_values: Optional[torch.Tensor],
1522
+ new_order: Tensor,
1523
+ ):
1524
+ """Main entry point for reordering the incremental state.
1525
+
1526
+ Due to limitations in TorchScript, we call this function in
1527
+ :class:`fairseq.sequence_generator.SequenceGenerator` instead of
1528
+ calling :func:`reorder_incremental_state` directly.
1529
+ """
1530
+ input_buffer = past_key_values
1531
+ new_past_key_values = []
1532
+ if input_buffer is not None:
1533
+ for input_buffer_k in input_buffer:
1534
+ new_input_buffer_k = []
1535
+ for input in input_buffer_k:
1536
+ if input is None:
1537
+ input = None
1538
+ else:
1539
+ input = input.index_select(0, new_order)
1540
+ new_input_buffer_k.append(input)
1541
+ new_past_key_values.append(new_input_buffer_k)
1542
+ return new_past_key_values
1543
+
1544
+ def forward(
1545
+ self,
1546
+ input_ids: torch.Tensor = None,
1547
+ attention_mask: torch.Tensor = None,
1548
+ encoder_hidden_states: torch.Tensor = None,
1549
+ encoder_attention_mask: torch.Tensor = None,
1550
+ code_masks: Optional[torch.Tensor] = None,
1551
+ src_pos_embed: torch.Tensor = None,
1552
+ past_key_values: Optional[torch.Tensor] = None,
1553
+ use_cache: bool = False,
1554
+ output_attentions: bool = False,
1555
+ output_hidden_states: bool = False,
1556
+ ):
1557
+ r"""
1558
+ Args:
1559
+ input_ids (`torch.LongTensor` of shape `(bsz, seq_len)`): indices of the sequence in the vocabulary.
1560
+ attention_mask (`torch.Tensor` of shape `(bsz, seq_len)`): mask to avoid attention on padding tokens.
1561
+ encoder_hidden_states (`torch.FloatTensor` of shape `(bsz, seq_len, hidden)`): the last hidden state of the encoder.
1562
+ encoder_attention_mask (`torch.Tensor` of shape `(bsz, seq_len)`): the padding mask of the source side.
1563
+ code_masks (`torch.Tensor` of shape `(bsz, seq_len)`): masks only for code generation.
1564
+ src_pos_embed (`torch.FloatTensor` of shape `(bsz, seq_len, hidden)`): the positional embeddings of the source side.
1565
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed):
1566
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1567
+ shape `(bsz, num_heads, tgt_len, head_size)`) and 2 additional tensors of
1568
+ shape `(bsz, num_heads, src_len, head_size)`.
1569
+ use_cache (`bool`): whether to use cache for faster inference.
1570
+ output_attentions (`bool`): whether to output attention weights.
1571
+ output_hidden_states (`bool`): whether to output hidden states.
1572
+
1573
+ Returns:
1574
+ BaseModelOutputWithPastAndCrossAttentions or a plain tuple:
1575
+ last_hidden_state (`torch.FloatTensor` of shape `(bsz, seq_len, hidden)`): the last hidden states.
1576
+ past_key_values (`tuple(tuple(torch.FloatTensor)): past keys and values for faster inference.
1577
+ hidden_states (`tuple(torch.FloatTensor)`): hidden states of all layers.
1578
+ attentions (`tuple(torch.FloatTensor)): self attention weights of all layers.
1579
+ cross_attentions (`tuple(torch.FloatTensor)): cross attention weights of all layers.
1580
+ """
1581
+
1582
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1583
+ output_hidden_states = (
1584
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1585
+ )
1586
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1587
+
1588
+ if past_key_values is not None and len(past_key_values)>0:
1589
+ size = past_key_values[0][0].size()
1590
+ bsz, tgt_len = size[0], size[-2] + 1
1591
+ token_position_idx = torch.arange(tgt_len, device=input_ids.device).expand([bsz, tgt_len]).contiguous()
1592
+ else:
1593
+ bsz, tgt_len = input_ids.shape
1594
+ token_position_idx = new_arange(input_ids)
1595
+ tgt_pos_embed = self.embed_positions(token_position_idx)
1596
+ if code_masks is not None and torch.any(code_masks):
1597
+ image_position_idx = self.image_position_idx[:input_ids.size(1)].unsqueeze(0).expand(bsz, tgt_len)
1598
+ tgt_pos_embed[code_masks] = self.embed_image_positions(image_position_idx)[code_masks]
1599
+
1600
+ # self attn position bias
1601
+ self_abs_pos_bias = self.get_pos_info(tgt_pos_embed, use_image=False)
1602
+ if code_masks is not None and torch.any(code_masks):
1603
+ self_image_abs_pos_bias = self.get_pos_info(tgt_pos_embed, use_image=True)
1604
+ self_abs_pos_bias[code_masks] = self_image_abs_pos_bias[code_masks]
1605
+ # cross attn position bias
1606
+ cross_abs_pos_bias = self.get_pos_info(tgt_pos_embed, src_pos_embed=src_pos_embed)
1607
+ if code_masks is not None and torch.any(code_masks):
1608
+ cross_image_abs_pos_bias = self.get_pos_info(tgt_pos_embed, src_pos_embed=src_pos_embed, use_image=True)
1609
+ cross_abs_pos_bias[code_masks] = cross_image_abs_pos_bias[code_masks]
1610
+ cross_abs_pos_bias = cross_abs_pos_bias.reshape(-1, *cross_abs_pos_bias.size()[-2:])
1611
+
1612
+ all_prev_output_tokens = input_ids.clone()
1613
+ if past_key_values is not None and len(past_key_values)>0:
1614
+ input_ids = input_ids[:, -1:]
1615
+ cross_abs_pos_bias = cross_abs_pos_bias[:, -1:, :]
1616
+ tgt_pos_embed = tgt_pos_embed[:, -1:, :]
1617
+
1618
+ # embed tokens and positions
1619
+ x = self.embed_scale * self.embed_tokens(input_ids)
1620
+
1621
+
1622
+ if self.entangle_position_embedding and not self.disable_entangle:
1623
+ x += tgt_pos_embed
1624
+
1625
+ if self.layernorm_embedding is not None:
1626
+ if code_masks is None or not code_masks.any() or not self.code_layernorm_embedding:
1627
+ x = self.layernorm_embedding(x)
1628
+ elif code_masks is not None and code_masks.all():
1629
+ x = self.code_layernorm_embedding(x)
1630
+ else:
1631
+ x[~code_masks] = self.layernorm_embedding(x[~code_masks])
1632
+ x[code_masks] = self.code_layernorm_embedding(x[code_masks])
1633
+
1634
+ hidden_states = self.dropout(x)
1635
+
1636
+ # past_key_values_length
1637
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None and len(past_key_values)>0 else 0
1638
+
1639
+ shape, dtype = input_ids.shape, hidden_states.dtype
1640
+ attention_mask = self._prepare_decoder_attention_mask(attention_mask, shape, dtype, past_key_values_length)
1641
+
1642
+ # decoder layers
1643
+ all_hidden_states = () if output_hidden_states else None
1644
+ all_self_attns = () if output_attentions else None
1645
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
1646
+ next_decoder_cache = () if use_cache else None
1647
+
1648
+ # decoder layers
1649
+ for idx, layer in enumerate(self.layers):
1650
+ # add hidden states from the last decoder layer
1651
+ if output_hidden_states:
1652
+ all_hidden_states += (hidden_states,)
1653
+
1654
+ past_key_value = past_key_values[idx] if past_key_values is not None and len(past_key_values)>0 else None
1655
+
1656
+ self_attn_bias = self_abs_pos_bias.clone()
1657
+ if code_masks is None or not code_masks.any():
1658
+ self_attn_bias += self.get_rel_pos_bias(all_prev_output_tokens, idx).unsqueeze(0)
1659
+ elif code_masks is not None and code_masks.all():
1660
+ self_attn_bias += self.get_image_rel_pos_bias(all_prev_output_tokens, idx).unsqueeze(0)
1661
+ else:
1662
+ self_attn_bias[~code_masks] += self.get_rel_pos_bias(all_prev_output_tokens, idx).unsqueeze(0)
1663
+ self_attn_bias[code_masks] += self.get_image_rel_pos_bias(all_prev_output_tokens, idx).unsqueeze(0)
1664
+ self_attn_bias = self_attn_bias.reshape(-1, *self_attn_bias.size()[-2:])
1665
+ if past_key_value is not None and len(past_key_values)>0 :
1666
+ self_attn_bias = self_attn_bias[:, -1:, :]
1667
+
1668
+ layer_outputs = layer(
1669
+ hidden_states,
1670
+ attention_mask=attention_mask,
1671
+ encoder_hidden_states=encoder_hidden_states,
1672
+ encoder_attention_mask=encoder_attention_mask,
1673
+ past_key_value=past_key_value,
1674
+ output_attentions=output_attentions,
1675
+ use_cache=use_cache,
1676
+ self_attn_bias=self_attn_bias,
1677
+ cross_attn_bias=cross_abs_pos_bias,
1678
+ )
1679
+ hidden_states = layer_outputs[0]
1680
+
1681
+ if use_cache:
1682
+ next_decoder_cache += (layer_outputs[3 if output_attentions else 1],)
1683
+
1684
+ if output_attentions:
1685
+ all_self_attns += (layer_outputs[1],)
1686
+
1687
+ if encoder_hidden_states is not None:
1688
+ all_cross_attentions += (layer_outputs[2],)
1689
+
1690
+ # add hidden states from the last decoder layer
1691
+ if output_hidden_states:
1692
+ all_hidden_states += (hidden_states,)
1693
+
1694
+ next_cache = next_decoder_cache if use_cache else None
1695
+
1696
+ if self.layer_norm is not None:
1697
+ hidden_states = self.layer_norm(hidden_states)
1698
+
1699
+ if self.output_projection is not None:
1700
+ hidden_states = self.output_projection(hidden_states)
1701
+
1702
+ return BaseModelOutputWithPastAndCrossAttentions(
1703
+ last_hidden_state=hidden_states,
1704
+ past_key_values=next_cache,
1705
+ hidden_states=all_hidden_states,
1706
+ attentions=all_self_attns,
1707
+ cross_attentions=all_cross_attentions,
1708
+ )
1709
+
1710
+
1711
+ # @add_start_docstrings(
1712
+ # "The bare TiO Model outputting raw hidden-states without any specific head on top.",
1713
+ # TiO_START_DOCSTRING,
1714
+ # )
1715
+ class TiOModel(TiOPreTrainedModel):
1716
+ r"""
1717
+ The TiO model built with an encoder and a decoder only, without any classification head.
1718
+
1719
+ Args:
1720
+ config (TiOConfig): TiO configuration.
1721
+ """
1722
+
1723
+ def __init__(self, config: TiOConfig, **kwargs):
1724
+ super().__init__(config)
1725
+ self.disable_entangle = getattr(kwargs,'disable_entangle',False)
1726
+
1727
+ self.padding_idx, vocab_size = config.pad_token_id, config.vocab_size
1728
+ shared = nn.Embedding(vocab_size, config.d_model, self.padding_idx)
1729
+
1730
+ self.encoder = TiOEncoder(config, shared)
1731
+ self.decoder = TiODecoder(config, shared)
1732
+
1733
+ # Initialize weights and apply final processing
1734
+ self.post_init()
1735
+
1736
+ def get_input_embeddings(self):
1737
+ r"""
1738
+ Retrieve input embeddings.
1739
+ """
1740
+ return self.encoder.get_input_embeddings()
1741
+
1742
+ def set_input_embeddings(self, value):
1743
+ r"""
1744
+ Set values for input embeddings
1745
+ """
1746
+ shared = value
1747
+ self.encoder.embed_tokens = shared
1748
+ self.decoder.embed_tokens = shared
1749
+
1750
+ def get_encoder(self):
1751
+ r"""
1752
+ Retrieve the encoder
1753
+ """
1754
+ return self.encoder
1755
+
1756
+ def get_decoder(self):
1757
+ r"""
1758
+ Retrieve the decoder
1759
+ """
1760
+ return self.decoder
1761
+
1762
+ # @add_start_docstrings_to_model_forward(TiO_INPUTS_DOCSTRING)
1763
+ # @add_code_sample_docstrings(
1764
+ # processor_class=_TOKENIZER_FOR_DOC,
1765
+ # checkpoint=_CHECKPOINT_FOR_DOC,
1766
+ # output_type=Seq2SeqModelOutput,
1767
+ # config_class=_CONFIG_FOR_DOC,
1768
+ # )
1769
+
1770
+ def max_decoder_positions(self):
1771
+ """Maximum length supported by the decoder."""
1772
+ return self.decoder.max_positions()
1773
+
1774
+ def get_normalized_probs(
1775
+ self,
1776
+ net_output: Tuple[Tensor, Optional[Dict[str, List[Optional[Tensor]]]]],
1777
+ log_probs: bool,
1778
+ sample: Optional[Dict[str, Tensor]] = None,
1779
+ ):
1780
+ """Get normalized probabilities (or log probs) from a net's output."""
1781
+ return self.get_normalized_probs_scriptable(net_output, log_probs, sample)
1782
+
1783
+
1784
+ def get_normalized_probs_scriptable(
1785
+ self,
1786
+ net_output: Tuple[Tensor, Optional[Dict[str, List[Optional[Tensor]]]]],
1787
+ log_probs: bool,
1788
+ sample: Optional[Dict[str, Tensor]] = None,
1789
+ ):
1790
+ """Scriptable helper function for get_normalized_probs in ~BaseFairseqModel"""
1791
+ if hasattr(self, "decoder"):
1792
+ return self.decoder.get_normalized_probs(net_output, log_probs, sample)
1793
+ elif torch.is_tensor(net_output):
1794
+ # syntactic sugar for simple models which don't have a decoder
1795
+ # (e.g., the classification tutorial)
1796
+ logits = net_output.float()
1797
+ if log_probs:
1798
+ return F.log_softmax(logits, dim=-1)
1799
+ else:
1800
+ return F.softmax(logits, dim=-1)
1801
+ raise NotImplementedError
1802
+
1803
+ def forward(
1804
+ self,
1805
+ input_ids=None,
1806
+ patch_images=None,
1807
+ patch_images_2=None,
1808
+ patch_masks=None,
1809
+ token_embeddings=None,
1810
+ sample_patch_num=None,
1811
+ decoder_input_ids=None,
1812
+ code_masks=None,
1813
+ attention_mask=None,
1814
+ encoder_outputs=None,
1815
+ past_key_values=None,
1816
+ use_cache=False,
1817
+ output_attentions=False,
1818
+ output_hidden_states=False,
1819
+ return_dict=False,
1820
+ **args
1821
+ ):
1822
+ r"""
1823
+ Args:
1824
+ input_ids (`torch.LongTensor` of shape `(bsz, seq_len)`):
1825
+ indices of input sequence tokens in the vocabular, and padding will be ignored by default;
1826
+
1827
+ indices can be obtained using [`~TiOTokenizer`].
1828
+
1829
+ patch_images (`torch.FloatTensor` of shape `(bsz, 3, height, width)`):
1830
+ the resized image, which are transformed by the default operations.
1831
+ patch_images_2 (`torch.FloatTensor` of shape `(bsz, 3, height, width)`):
1832
+ the second (if it exists) image.
1833
+ patch_masks (`torch.BoolTensor`): the patches to be masked.
1834
+ token_embeddings (`torch.FloatTensor` of shape `(bsz, seq_len, embed_dim)`): token embeddings.
1835
+ sample_patch_num (`int`): the number of patches to sample.
1836
+ decoder_input_ids (`torch.LongTensor` of shape `(bsz, seq_len)`): indices of the sequence in the vocabulary.
1837
+ code_masks (`torch.Tensor` of shape `(bsz, seq_len)`): masks only for code generation.
1838
+ attention_mask (`torch.Tensor` of shape `(bsz, seq_len)`): attention mask for decoding.
1839
+ encoder_outputs (`TiOEncoderOutput`):
1840
+ encoder outputs with hidden states, positional embeddings, and padding masks.
1841
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed):
1842
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1843
+ shape `(bsz, num_heads, tgt_len, head_size)`) and 2 additional tensors of
1844
+ shape `(bsz, num_heads, src_len, head_size)`.
1845
+ use_cache (`bool`): whether to use cache for faster inference.
1846
+ output_attentions (`bool`): whether to output attention weights.
1847
+ output_hidden_states (`bool`): whether to output hidden states.
1848
+ return_dict (`bool`): unused. Keep it for generation only.
1849
+
1850
+ Returns:
1851
+ Seq2SeqLMOutput:
1852
+ logits (`torch.FloatTensor` of shape `(bsz, seq_len, hidden)`): the last decoder hidden states.
1853
+ past_key_values (`tuple(tuple(torch.FloatTensor)): past keys and values for faster inference.
1854
+ decoder_hidden_states (`tuple(torch.FloatTensor)`): the decoder hidden states of all layers.
1855
+ decoder_attentions (`tuple(torch.FloatTensor)): the decoder self attention weights of all layers.
1856
+ cross_attentions (`tuple(torch.FloatTensor)): cross attention weights of all layers.
1857
+ encoder_last_hidden_state (`torch.FloatTensor` of shape `(bsz, seq_len, embed_dim)`):
1858
+ the encoder last hidden state.
1859
+ encoder_hidden_states (`torch.FloatTensor` of shape `(bsz, seq_len, embed_dim)`):
1860
+ the encoder states of all layers including the embeddings.
1861
+ encoder_attentions (`torch.FloatTensor` of shape `(bsz, num_heads, seq_len, seq_len)`):
1862
+ the encoder attention weights of all layers.
1863
+ """
1864
+
1865
+ # 适配新的tokenizer输入
1866
+ patch_images = args.get("pixel_values", patch_images)
1867
+ if "labels_attention_mask" in args:
1868
+ attention_mask = args.get("labels_attention_mask")[:-1]
1869
+ decoder_input_ids = args.get("labels")[:-1]
1870
+
1871
+ output_attentions = output_attentions if output_attentions else self.config.output_attentions
1872
+ output_hidden_states = output_hidden_states if output_hidden_states else self.config.output_hidden_states
1873
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1874
+
1875
+ if encoder_outputs is None:
1876
+ encoder_outputs = self.encoder(
1877
+ input_ids=input_ids,
1878
+ patch_images=patch_images,
1879
+ patch_images_2=patch_images_2,
1880
+ patch_masks=patch_masks,
1881
+ output_attentions=output_attentions,
1882
+ output_hidden_states=output_hidden_states,
1883
+ token_embeddings=token_embeddings,
1884
+ sample_patch_num=sample_patch_num,
1885
+ )
1886
+
1887
+ # if decoder_input_ids.eq(self.config.pad_token_id).any():
1888
+ # attention_mask = decoder_input_ids.eq(self.padding_idx)
1889
+
1890
+ encoder_hidden_states = encoder_outputs.last_hidden_state
1891
+ if past_key_values is not None and len(past_key_values)>0:
1892
+ encoder_attention_mask = _expand_mask(
1893
+ ~encoder_outputs.padding_mask, encoder_hidden_states.dtype, decoder_input_ids[:, -1:].shape[-1]
1894
+ )
1895
+ else:
1896
+ encoder_attention_mask = _expand_mask(
1897
+ ~encoder_outputs.padding_mask, encoder_hidden_states.dtype, decoder_input_ids.shape[-1]
1898
+ )
1899
+ src_pos_embed = encoder_outputs.position_embedding
1900
+
1901
+ decoder_outputs = self.decoder(
1902
+ input_ids=decoder_input_ids,
1903
+ attention_mask=attention_mask,
1904
+ encoder_hidden_states=encoder_hidden_states,
1905
+ encoder_attention_mask=encoder_attention_mask,
1906
+ code_masks=code_masks,
1907
+ src_pos_embed=src_pos_embed,
1908
+ past_key_values=past_key_values,
1909
+ use_cache=use_cache,
1910
+ output_attentions=output_attentions,
1911
+ output_hidden_states=output_hidden_states,
1912
+ )
1913
+
1914
+ logits = decoder_outputs.last_hidden_state
1915
+ loss = None
1916
+
1917
+ return Seq2SeqLMOutput(
1918
+ loss=loss,
1919
+ logits=decoder_outputs.last_hidden_state,
1920
+ past_key_values=decoder_outputs.past_key_values,
1921
+ decoder_hidden_states=decoder_outputs.hidden_states,
1922
+ decoder_attentions=decoder_outputs.attentions,
1923
+ cross_attentions=decoder_outputs.cross_attentions,
1924
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1925
+ encoder_hidden_states=encoder_outputs.hidden_states,
1926
+ encoder_attentions=encoder_outputs.attentions,
1927
+ )
1928
+
1929
+ def prepare_inputs_for_generation(
1930
+ self,
1931
+ decoder_input_ids=None,
1932
+ past=None,
1933
+ attention_mask=None,
1934
+ code_masks=None,
1935
+ use_cache=False,
1936
+ encoder_outputs=None,
1937
+ **kwargs
1938
+ ):
1939
+ # if attention_mask is None:
1940
+ attention_mask = decoder_input_ids.new_ones(decoder_input_ids.shape)
1941
+
1942
+ # cut decoder_input_ids if past is used
1943
+ # if past is not None:
1944
+ # decoder_input_ids = decoder_input_ids[:, -1:]
1945
+
1946
+ return {
1947
+ "input_ids": None,
1948
+ "patch_images": None,
1949
+ "patch_images_2": None,
1950
+ "patch_masks": None,
1951
+ "token_embeddings": None,
1952
+ "sample_patch_num": None,
1953
+ "attention_mask": attention_mask,
1954
+ "encoder_outputs": encoder_outputs,
1955
+ "past_key_values": past,
1956
+ "decoder_input_ids": decoder_input_ids,
1957
+ "code_masks": code_masks,
1958
+ "use_cache": use_cache,
1959
+ }
1960
+
1961
+ def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
1962
+ return shift_tokens_right(labels, self.config.pad_token_id, self.config.decoder_start_token_id)
1963
+
1964
+ def _prepare_encoder_decoder_kwargs_for_generation(
1965
+ self, inputs_tensor: torch.Tensor, model_kwargs, model_input_name: Optional[str] = None
1966
+ ):
1967
+ # 1. get encoder
1968
+ encoder = self.get_encoder()
1969
+
1970
+ # 2. prepare encoder args and encoder kwargs from model kwargs
1971
+ irrelevant_prefix = ["decoder_", "cross_attn", "use_cache", "attention_mask"]
1972
+ encoder_kwargs = {
1973
+ argument: value
1974
+ for argument, value in model_kwargs.items()
1975
+ if not any(argument.startswith(p) for p in irrelevant_prefix)
1976
+ }
1977
+
1978
+ if encoder_kwargs.get("patch_masks") is None:
1979
+ encoder_kwargs["patch_masks"] = torch.ones((len(inputs_tensor), 1), dtype=torch.bool, device=inputs_tensor.device)
1980
+
1981
+ # 3. make sure that encoder returns `ModelOutput`
1982
+ model_input_name = model_input_name if model_input_name is not None else self.main_input_name
1983
+ encoder_kwargs[model_input_name] = inputs_tensor
1984
+ model_kwargs["encoder_outputs"]: ModelOutput = encoder(**encoder_kwargs)
1985
+ model_kwargs["attention_mask"] = None
1986
+
1987
+ return model_kwargs
1988
+
1989
+ @staticmethod
1990
+ def _reorder_cache(past, beam_idx):
1991
+ reordered_past = ()
1992
+ for layer_past in past:
1993
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
1994
+ return reordered_past
1995
+
1996
+ @staticmethod
1997
+ def _expand_inputs_for_generation(
1998
+ input_ids: torch.LongTensor,
1999
+ expand_size: int = 1,
2000
+ is_encoder_decoder: bool = False,
2001
+ attention_mask: Optional[torch.LongTensor] = None,
2002
+ encoder_outputs: Optional[ModelOutput] = None,
2003
+ **model_kwargs,
2004
+ ):
2005
+ expanded_return_idx = (
2006
+ torch.arange(input_ids.shape[0]).view(-1, 1).repeat(1, expand_size).view(-1).to(input_ids.device)
2007
+ )
2008
+ input_ids = input_ids.index_select(0, expanded_return_idx)
2009
+
2010
+ if "token_type_ids" in model_kwargs:
2011
+ token_type_ids = model_kwargs["token_type_ids"]
2012
+ model_kwargs["token_type_ids"] = token_type_ids.index_select(0, expanded_return_idx)
2013
+
2014
+ if attention_mask is not None:
2015
+ model_kwargs["attention_mask"] = attention_mask.index_select(0, expanded_return_idx)
2016
+
2017
+ if is_encoder_decoder:
2018
+ if encoder_outputs is None:
2019
+ raise ValueError("If `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined.")
2020
+ encoder_outputs["last_hidden_state"] = encoder_outputs.last_hidden_state.index_select(
2021
+ 0, expanded_return_idx.to(encoder_outputs.last_hidden_state.device)
2022
+ )
2023
+ encoder_outputs["position_embedding"] = encoder_outputs.position_embedding.index_select(
2024
+ 0, expanded_return_idx.to(encoder_outputs.position_embedding.device)
2025
+ )
2026
+ encoder_outputs["padding_mask"] = encoder_outputs.padding_mask.index_select(
2027
+ 0, expanded_return_idx.to(encoder_outputs.padding_mask.device)
2028
+ )
2029
+ model_kwargs["encoder_outputs"] = encoder_outputs
2030
+ return input_ids, model_kwargs
2031
+
2032
+
2033
+ from .utils_tio import Utils
2034
+ from .gradio_app import get_gradio_demo
2035
+ TiOModel.utils = Utils
2036
+ TiOModel.get_gradio_demo = get_gradio_demo
preprocessor_config.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "crop_pct": 0.875,
3
+ "do_normalize": true,
4
+ "do_rescale": true,
5
+ "do_resize": true,
6
+ "image_mean": [
7
+ 0.5,
8
+ 0.5,
9
+ 0.5
10
+ ],
11
+ "image_processor_type": "ConvNextImageProcessor",
12
+ "image_std": [
13
+ 0.5,
14
+ 0.5,
15
+ 0.5
16
+ ],
17
+ "resample": 3,
18
+ "rescale_factor": 0.00392156862745098,
19
+ "size": {
20
+ "shortest_edge": 512
21
+ }
22
+ }
resnet.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # [Apache-2.0] Copyed from https://github.com/OFA-Sys/OFA
3
+ # Copyright 2022 The OFA-Sys Team. All rights reserved.
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+
8
+
9
+ def drop_path(x, drop_prob: float = 0.0, training: bool = False):
10
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
11
+ This is the same as the DropConnect impl I created for EfficientNet, etc networks, however,
12
+ the original name is misleading as 'Drop Connect' is a.sh different form of dropout in a.sh separate paper...
13
+ See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for
14
+ changing the layer and argument names to 'drop path' rather than mix DropConnect as a.sh layer name and use
15
+ 'survival rate' as the argument.
16
+ """
17
+ if drop_prob == 0.0 or not training:
18
+ return x
19
+ keep_prob = 1 - drop_prob
20
+ shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
21
+ random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
22
+ random_tensor.floor_() # binarize
23
+ output = x.div(keep_prob) * random_tensor
24
+ return output
25
+
26
+
27
+ class DropPath(nn.Module):
28
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
29
+
30
+ def __init__(self, drop_prob=None):
31
+ super(DropPath, self).__init__()
32
+ self.drop_prob = drop_prob
33
+
34
+ def forward(self, x):
35
+ return drop_path(x, self.drop_prob, self.training)
36
+
37
+
38
+ def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
39
+ """3x3 convolution with padding"""
40
+ return nn.Conv2d(
41
+ in_planes,
42
+ out_planes,
43
+ kernel_size=3,
44
+ stride=stride,
45
+ padding=dilation,
46
+ groups=groups,
47
+ bias=False,
48
+ dilation=dilation,
49
+ )
50
+
51
+
52
+ def conv1x1(in_planes, out_planes, stride=1):
53
+ """1x1 convolution"""
54
+ return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
55
+
56
+
57
+ class BasicBlock(nn.Module):
58
+ expansion = 1
59
+
60
+ def __init__(
61
+ self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, dilation=1, norm_layer=None
62
+ ):
63
+ super(BasicBlock, self).__init__()
64
+ if norm_layer is None:
65
+ norm_layer = nn.BatchNorm2d
66
+ if groups != 1 or base_width != 64:
67
+ raise ValueError("BasicBlock only supports groups=1 and base_width=64")
68
+ if dilation > 1:
69
+ raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
70
+ # Both self.conv1 and self.downsample layers downsample the input when stride != 1
71
+ self.conv1 = conv3x3(inplanes, planes, stride)
72
+ self.bn1 = norm_layer(planes)
73
+ self.relu = nn.ReLU(inplace=True)
74
+ self.conv2 = conv3x3(planes, planes)
75
+ self.bn2 = norm_layer(planes)
76
+ self.downsample = downsample
77
+ self.stride = stride
78
+
79
+ def forward(self, x):
80
+ assert False
81
+ identity = x
82
+
83
+ out = self.conv1(x)
84
+ out = self.bn1(out)
85
+ out = self.relu(out)
86
+
87
+ out = self.conv2(out)
88
+ out = self.bn2(out)
89
+
90
+ if self.downsample is not None:
91
+ identity = self.downsample(x)
92
+
93
+ out += identity
94
+ out = self.relu(out)
95
+
96
+ return out
97
+
98
+
99
+ class Bottleneck(nn.Module):
100
+ # Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2)
101
+ # while original implementation places the stride at the first 1x1 convolution(self.conv1)
102
+ # according to "Deep residual learning for image recognition"https://arxiv.org/abs/1512.03385.
103
+ # This variant is also known as ResNet V1.5 and improves accuracy according to
104
+ # https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch.
105
+
106
+ expansion = 4
107
+
108
+ def __init__(
109
+ self,
110
+ inplanes,
111
+ planes,
112
+ stride=1,
113
+ downsample=None,
114
+ groups=1,
115
+ base_width=64,
116
+ dilation=1,
117
+ norm_layer=None,
118
+ drop_path_rate=0.0,
119
+ ):
120
+ super(Bottleneck, self).__init__()
121
+ if norm_layer is None:
122
+ norm_layer = nn.BatchNorm2d
123
+ width = int(planes * (base_width / 64.0)) * groups
124
+ # Both self.conv2 and self.downsample layers downsample the input when stride != 1
125
+ self.conv1 = conv1x1(inplanes, width)
126
+ self.bn1 = norm_layer(width)
127
+ self.conv2 = conv3x3(width, width, stride, groups, dilation)
128
+ self.bn2 = norm_layer(width)
129
+ self.conv3 = conv1x1(width, planes * self.expansion)
130
+ self.bn3 = norm_layer(planes * self.expansion)
131
+ self.relu = nn.ReLU(inplace=True)
132
+ self.downsample = downsample
133
+ self.stride = stride
134
+ self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
135
+
136
+ def forward(self, x):
137
+ identity = x
138
+
139
+ out = self.conv1(x)
140
+ out = self.bn1(out)
141
+ out = self.relu(out)
142
+
143
+ out = self.conv2(out)
144
+ out = self.bn2(out)
145
+ out = self.relu(out)
146
+
147
+ out = self.conv3(out)
148
+ out = self.bn3(out)
149
+
150
+ if self.downsample is not None:
151
+ identity = self.downsample(x)
152
+
153
+ out = identity + self.drop_path(out)
154
+ out = self.relu(out)
155
+
156
+ return out
157
+
158
+
159
+ class ResNet(nn.Module):
160
+ def __init__(
161
+ self,
162
+ layers,
163
+ zero_init_residual=False,
164
+ groups=1,
165
+ width_per_group=64,
166
+ replace_stride_with_dilation=None,
167
+ norm_layer=None,
168
+ drop_path_rate=0.0,
169
+ ):
170
+ super(ResNet, self).__init__()
171
+ if norm_layer is None:
172
+ norm_layer = nn.BatchNorm2d
173
+ self._norm_layer = norm_layer
174
+
175
+ self.inplanes = 64
176
+ self.dilation = 1
177
+ if replace_stride_with_dilation is None:
178
+ # each element in the tuple indicates if we should replace
179
+ # the 2x2 stride with a dilated convolution instead
180
+ replace_stride_with_dilation = [False, False, False]
181
+ if len(replace_stride_with_dilation) != 3:
182
+ raise ValueError(
183
+ "replace_stride_with_dilation should be None "
184
+ "or a 3-element tuple, got {}".format(replace_stride_with_dilation)
185
+ )
186
+ self.groups = groups
187
+ self.base_width = width_per_group
188
+ self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False)
189
+ self.bn1 = norm_layer(self.inplanes)
190
+ self.relu = nn.ReLU(inplace=True)
191
+ self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
192
+ self.layer1 = self._make_layer(Bottleneck, 64, layers[0], drop_path_rate=drop_path_rate)
193
+ self.layer2 = self._make_layer(
194
+ Bottleneck, 128, layers[1], stride=2, dilate=replace_stride_with_dilation[0], drop_path_rate=drop_path_rate
195
+ )
196
+ self.layer3 = self._make_layer(
197
+ Bottleneck, 256, layers[2], stride=2, dilate=replace_stride_with_dilation[1], drop_path_rate=drop_path_rate
198
+ )
199
+
200
+ for m in self.modules():
201
+ if isinstance(m, nn.Conv2d):
202
+ nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
203
+ elif isinstance(m, (nn.SyncBatchNorm, nn.BatchNorm2d, nn.GroupNorm)):
204
+ nn.init.constant_(m.weight, 1)
205
+ nn.init.constant_(m.bias, 0)
206
+
207
+ # Zero-initialize the last BN in each residual branch,
208
+ # so that the residual branch starts with zeros, and each residual block behaves like an identity.
209
+ # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
210
+ if zero_init_residual:
211
+ for m in self.modules():
212
+ if isinstance(m, Bottleneck):
213
+ nn.init.constant_(m.bn3.weight, 0)
214
+ elif isinstance(m, BasicBlock):
215
+ nn.init.constant_(m.bn2.weight, 0)
216
+
217
+ def _make_layer(self, block, planes, blocks, stride=1, dilate=False, drop_path_rate=0.0):
218
+ norm_layer = self._norm_layer
219
+ downsample = None
220
+ previous_dilation = self.dilation
221
+ if dilate:
222
+ self.dilation *= stride
223
+ stride = 1
224
+ if stride != 1 or self.inplanes != planes * block.expansion:
225
+ downsample = nn.Sequential(
226
+ conv1x1(self.inplanes, planes * block.expansion, stride),
227
+ norm_layer(planes * block.expansion),
228
+ )
229
+
230
+ layers = []
231
+ layers.append(
232
+ block(
233
+ self.inplanes, planes, stride, downsample, self.groups, self.base_width, previous_dilation, norm_layer
234
+ )
235
+ )
236
+ self.inplanes = planes * block.expansion
237
+
238
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, blocks)]
239
+ for i in range(1, blocks):
240
+ layers.append(
241
+ block(
242
+ self.inplanes,
243
+ planes,
244
+ groups=self.groups,
245
+ base_width=self.base_width,
246
+ dilation=self.dilation,
247
+ norm_layer=norm_layer,
248
+ drop_path_rate=dpr[i],
249
+ )
250
+ )
251
+
252
+ return nn.Sequential(*layers)
253
+
254
+ def _forward_impl(self, x):
255
+ # See note [TorchScript super()]
256
+ x = self.conv1(x)
257
+ x = self.bn1(x)
258
+ x = self.relu(x)
259
+ x = self.maxpool(x)
260
+
261
+ x = self.layer1(x)
262
+ x = self.layer2(x)
263
+ x = self.layer3(x)
264
+
265
+ return x
266
+
267
+ def forward(self, x):
268
+ return self._forward_impl(x)
special_tokens_map.json ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": true,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "cls_token": {
10
+ "content": "<s>",
11
+ "lstrip": false,
12
+ "normalized": true,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "eos_token": {
17
+ "content": "</s>",
18
+ "lstrip": false,
19
+ "normalized": true,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "mask_token": {
24
+ "content": "<mask>",
25
+ "lstrip": true,
26
+ "normalized": true,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ },
30
+ "pad_token": {
31
+ "content": "<pad>",
32
+ "lstrip": false,
33
+ "normalized": true,
34
+ "rstrip": false,
35
+ "single_word": false
36
+ },
37
+ "sep_token": {
38
+ "content": "</s>",
39
+ "lstrip": false,
40
+ "normalized": true,
41
+ "rstrip": false,
42
+ "single_word": false
43
+ },
44
+ "unk_token": {
45
+ "content": "<unk>",
46
+ "lstrip": false,
47
+ "normalized": true,
48
+ "rstrip": false,
49
+ "single_word": false
50
+ }
51
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
The diff for this file is too large to render. See raw diff
 
utils_tio.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image as PILImage
2
+ from transformers import AutoModel, AutoTokenizer, AutoImageProcessor
3
+ import re
4
+ import cv2
5
+ import numpy as np
6
+
7
+
8
+ class Utils():
9
+ def xywh2xyxy(b):
10
+ b[..., 2:] += b[..., :2]
11
+ return b
12
+
13
+ def bbox_to_sbbox(bbox):
14
+ # xyxy in [0, 1]
15
+ assert len(bbox) == 4
16
+ bbox = (np.asarray(bbox) * 1000).astype(np.int16)
17
+ bbox = np.clip(bbox, 0, 999)
18
+ bbox = " ".join([f"<bin_{i}>" for i in bbox])
19
+ return bbox
20
+
21
+ def sbbox_to_bbox(sbbox, set_default: bool = False):
22
+ sbbox = [re.findall(r"<bin_(\d+)>", s)[:4] for s in sbbox.split("region:")]
23
+ bbox = np.asarray([s for s in sbbox if len(s) >= 4], dtype=int)
24
+ if set_default and not len(bbox):
25
+ bbox = np.asarray([0, 0, 1000, 1000])
26
+ bbox = np.clip(bbox / 1000, 1e-5, 1 - 1e-5)
27
+ return bbox.reshape(-1, 4)
28
+
29
+ def make_dialog_context(dialog: list, text_human: str = None) -> str:
30
+ # dialog: [("pass me an apple.", "which apple do you want?"), ...]
31
+ context = "".join([f"human: {d[0]}\nagent: {d[1]}\n" for d in dialog])
32
+ if text_human is not None:
33
+ context += f"human: {text_human}"
34
+ return context
35
+
36
+ def show_mask(image: PILImage.Image, bboxes=None, masks=None, show_id=False, text_size=1) -> PILImage.Image:
37
+ """ 给图片画上mask: 只更改被mask标记部分的rgb值. """
38
+ import colorsys
39
+ colors = [tuple(int(c * 255) for c in colorsys.hsv_to_rgb(i * 1.0 / 36, 1, 1)) for i in range(36)]
40
+ size = image.size
41
+ image = np.asarray(image)
42
+ if bboxes is not None:
43
+ bboxes = np.array(bboxes).reshape(-1, 4)
44
+ for k, bbox in enumerate(bboxes):
45
+ bbox = (np.asarray(bbox) * np.asarray([*size, *size])).astype(int)
46
+ image = cv2.rectangle(image, tuple(bbox[:2]), tuple(bbox[2:]), tuple(colors[k]), thickness=2)
47
+ if show_id:
48
+ for k, bbox in enumerate(bboxes):
49
+ bbox = (np.asarray(bbox) * np.asarray([*size, *size])).astype(int)
50
+ image = cv2.putText(image, str(k), tuple(bbox[:2] + np.array([2, 28 * text_size])), cv2.FONT_HERSHEY_SIMPLEX, text_size, (255, 255, 255), 2, cv2.LINE_AA)
51
+ image = cv2.putText(image, str(k), tuple(bbox[:2] + np.array([2, 28 * text_size])), cv2.FONT_HERSHEY_SIMPLEX, text_size, tuple(colors[k%len(colors)]), 1, cv2.LINE_AA)
52
+
53
+ if masks is not None:
54
+ for k, mask in enumerate(masks):
55
+ mask_color = (mask[..., None] * colors[k%len(colors)][:3]).astype(np.uint8)
56
+ image_mask = cv2.addWeighted(mask_color, 0.5, image * mask[..., None], 0.5, 0)
57
+ image = cv2.add(image * ~mask[..., None], image_mask)
58
+ return PILImage.fromarray(image)
vocab.json ADDED
The diff for this file is too large to render. See raw diff